Index.php 188 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096
  1. <?php
  2. namespace app\index\controller;
  3. use app\common\controller\Frontend;
  4. use app\common\library\ProcuremenStatus;
  5. use think\Cache;
  6. use think\captcha\Captcha;
  7. use think\Config;
  8. use think\Cookie;
  9. use think\Db;
  10. use think\Log;
  11. use think\Session;
  12. use think\Validate;
  13. /**
  14. * 手机端:协助明细(purchase_order_detail)验证码 / 账号密码登录 + 列表
  15. * 普通用户(customer):登录后进报价列表,可填单价/交期
  16. * 质检中心:登录后进「质量评分」(合格/投诉/中断)
  17. * 生产部(生产员):登录后进「交货情况」(准时/滞后)
  18. */
  19. class Index extends Frontend
  20. {
  21. protected $noNeedLogin = ['*'];
  22. protected $noNeedRight = ['*'];
  23. protected $layout = '';
  24. /** @var int 登录态有效天数 */
  25. protected $mprocTtlSeconds = 0;
  26. /** @var array<string, string>|null purchase_order_detail 表字段:小写 => 真实列名 */
  27. protected static $mprocProcuremenColumns = null;
  28. public function _initialize()
  29. {
  30. parent::_initialize();
  31. if (is_file(APP_PATH . 'extra/mproc.php')) {
  32. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  33. }
  34. $hours = (int)Config::get('mproc.session_hours');
  35. if ($hours > 0) {
  36. $this->mprocTtlSeconds = max(1, min(720, $hours)) * 3600;
  37. } else {
  38. $days = (int)(Config::get('mproc.session_days') ?: 3);
  39. $days = max(1, min(30, $days));
  40. $this->mprocTtlSeconds = $days * 86400;
  41. }
  42. if (PHP_VERSION_ID >= 70300) {
  43. ini_set('session.cookie_lifetime', (string)$this->mprocTtlSeconds);
  44. ini_set('session.gc_maxlifetime', (string)$this->mprocTtlSeconds);
  45. }
  46. }
  47. /** 登录有效小时数(用于前端 localStorage 过期时间) */
  48. protected function mprocKeepHours(): int
  49. {
  50. return max(1, (int)round($this->mprocTtlSeconds / 3600));
  51. }
  52. /**
  53. * 当前手机端登录用户;未登录返回 null(支持 Cookie 令牌 + 7 天记住登录)
  54. */
  55. protected function mprocGetUser()
  56. {
  57. $token = $this->mprocReadTokenFromRequest();
  58. if ($token !== '') {
  59. $user = $this->mprocLoadUserByToken($token);
  60. if ($user) {
  61. $token = $this->mprocTouchLoginState($user, $token);
  62. $user['token'] = $token;
  63. return $user;
  64. }
  65. }
  66. $user = $this->mprocUserFromRememberCookie();
  67. if (!$user) {
  68. return null;
  69. }
  70. $token = $this->mprocPackSignedAuthToken($user);
  71. $token = $this->mprocTouchLoginState($user, $token);
  72. $user['token'] = $token;
  73. return $user;
  74. }
  75. protected function mprocReadTokenFromRequest(): string
  76. {
  77. $token = Session::get('mproc_token');
  78. if ($token === null || $token === '') {
  79. $token = Cookie::get('mproc_token');
  80. }
  81. if ($token === null || $token === '') {
  82. $token = $this->request->header('X-Mproc-Token');
  83. }
  84. if ($token === null || $token === '') {
  85. $token = $this->request->request('mproc_token', '');
  86. }
  87. $token = trim((string)$token);
  88. if ($token === '') {
  89. return '';
  90. }
  91. if ($this->mprocIsSignedAuthToken($token)) {
  92. return $token;
  93. }
  94. $token = preg_replace('/[^a-f0-9]/i', '', $token);
  95. return strlen($token) >= 16 ? $token : '';
  96. }
  97. protected function mprocIsSignedAuthToken(string $token): bool
  98. {
  99. return strpos($token, '.') !== false
  100. && preg_match('/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/', $token) === 1;
  101. }
  102. protected function mprocAuthCacheKey(string $token): string
  103. {
  104. return 'mproc_u_' . md5($token);
  105. }
  106. /**
  107. * @return array<string, mixed>|null
  108. */
  109. protected function mprocLoadUserByToken(string $token): ?array
  110. {
  111. if ($this->mprocIsSignedAuthToken($token)) {
  112. if ($this->mprocIsAuthTokenRevoked($token)) {
  113. return null;
  114. }
  115. $user = $this->mprocUserFromSignedToken($token);
  116. if (!$user) {
  117. return null;
  118. }
  119. if (time() - (int)($user['login_time'] ?? 0) > $this->mprocTtlSeconds) {
  120. $this->mprocClearLogin($token);
  121. return null;
  122. }
  123. $user['token'] = $token;
  124. return $user;
  125. }
  126. $user = Cache::get('mproc_u_' . $token);
  127. if (!is_array($user)) {
  128. $user = $this->mprocUserFromRememberCookie();
  129. if (!$user) {
  130. return null;
  131. }
  132. }
  133. if (empty($user['phone']) && empty($user['account']) && empty($user['username'])) {
  134. return null;
  135. }
  136. if (time() - (int)($user['login_time'] ?? 0) > $this->mprocTtlSeconds) {
  137. $this->mprocClearLogin($token);
  138. return null;
  139. }
  140. $user['token'] = $token;
  141. return $user;
  142. }
  143. /**
  144. * 滑动续期:刷新签名令牌 / Cache / Session / Cookie(保留 7 天)
  145. *
  146. * @param array<string, mixed> $user
  147. */
  148. protected function mprocTouchLoginState(array $user, string $token): string
  149. {
  150. $user['login_time'] = time();
  151. if ($this->mprocIsSignedAuthToken($token)) {
  152. $token = $this->mprocPackSignedAuthToken($user);
  153. }
  154. Cache::set($this->mprocAuthCacheKey($token), $user, $this->mprocTtlSeconds + 86400);
  155. if (!$this->mprocIsSignedAuthToken($token)) {
  156. Cache::set('mproc_u_' . $token, $user, $this->mprocTtlSeconds + 86400);
  157. }
  158. Session::set('mproc_token', $token);
  159. $this->mprocSetTokenCookie($token);
  160. $this->mprocSetRememberCookie($user, $token);
  161. return $token;
  162. }
  163. /**
  164. * @return array<string, mixed>
  165. */
  166. protected function mprocCookieOptions(): array
  167. {
  168. $opts = [
  169. 'expire' => $this->mprocTtlSeconds,
  170. 'path' => '/',
  171. 'httponly' => true,
  172. ];
  173. if ($this->request->isSsl()) {
  174. $opts['secure'] = true;
  175. }
  176. if (PHP_VERSION_ID >= 70300) {
  177. $opts['samesite'] = 'Lax';
  178. }
  179. return $opts;
  180. }
  181. protected function mprocSetTokenCookie(string $token): void
  182. {
  183. Cookie::set('mproc_token', $token, $this->mprocCookieOptions());
  184. }
  185. /**
  186. * @param array<string, mixed> $user
  187. */
  188. protected function mprocSetRememberCookie(array $user, ?string $token = null): void
  189. {
  190. $val = $token !== null && $token !== '' ? $token : $this->mprocPackSignedAuthToken($user);
  191. Cookie::set('mproc_remember', $val, $this->mprocCookieOptions());
  192. }
  193. protected function mprocAuthSignSecret(): string
  194. {
  195. $key = trim((string)Config::get('mproc.auth_sign_key'));
  196. if ($key === '') {
  197. $key = (string)Config::get('database.database') . '|' . (string)Config::get('database.hostname') . '|mproc';
  198. }
  199. return hash('sha256', $key);
  200. }
  201. /**
  202. * @param array<string, mixed> $user
  203. */
  204. protected function mprocPackSignedAuthToken(array $user): string
  205. {
  206. $payload = [
  207. 'uid' => (int)($user['customer_user_id'] ?? $user['customer_id'] ?? 0),
  208. 'phone' => trim((string)($user['phone'] ?? '')),
  209. 'uname' => trim((string)($user['username'] ?? $user['account'] ?? '')),
  210. 'admin' => !empty($user['is_admin']) ? 1 : 0,
  211. 'lt' => time(),
  212. ];
  213. $b64 = rtrim(strtr(base64_encode(json_encode($payload, JSON_UNESCAPED_UNICODE)), '+/', '-_'), '=');
  214. $sig = hash_hmac('sha256', $b64, $this->mprocAuthSignSecret());
  215. return $b64 . '.' . $sig;
  216. }
  217. /** @deprecated 使用 mprocPackSignedAuthToken */
  218. protected function mprocPackRememberCookie(array $user): string
  219. {
  220. return $this->mprocPackSignedAuthToken($user);
  221. }
  222. /**
  223. * @return array<string, mixed>|null
  224. */
  225. protected function mprocUserFromSignedToken(string $raw): ?array
  226. {
  227. $parts = explode('.', trim($raw), 2);
  228. if (count($parts) !== 2) {
  229. return null;
  230. }
  231. $b64 = $parts[0];
  232. $sig = $parts[1];
  233. if (!hash_equals(hash_hmac('sha256', $b64, $this->mprocAuthSignSecret()), $sig)) {
  234. return null;
  235. }
  236. $pad = strlen($b64) % 4;
  237. if ($pad > 0) {
  238. $b64 .= str_repeat('=', 4 - $pad);
  239. }
  240. $json = base64_decode(strtr($b64, '-_', '+/'), true);
  241. if ($json === false || $json === '') {
  242. return null;
  243. }
  244. $payload = json_decode($json, true);
  245. if (!is_array($payload)) {
  246. return null;
  247. }
  248. $lt = (int)($payload['lt'] ?? 0);
  249. if ($lt <= 0 || time() - $lt > $this->mprocTtlSeconds) {
  250. return null;
  251. }
  252. return $this->mprocRebuildUserFromRememberPayload($payload, $lt);
  253. }
  254. /**
  255. * @return array<string, mixed>|null
  256. */
  257. protected function mprocUserFromRememberCookie(): ?array
  258. {
  259. $raw = Cookie::get('mproc_remember');
  260. if ($raw === null || $raw === '') {
  261. $raw = Cookie::get('mproc_token');
  262. }
  263. if ($raw === null || $raw === '') {
  264. return null;
  265. }
  266. $raw = (string)$raw;
  267. if ($this->mprocIsAuthTokenRevoked($raw)) {
  268. return null;
  269. }
  270. return $this->mprocUserFromSignedToken($raw);
  271. }
  272. /**
  273. * @param array<string, mixed> $payload
  274. * @return array<string, mixed>|null
  275. */
  276. protected function mprocRebuildUserFromRememberPayload(array $payload, int $loginTime): ?array
  277. {
  278. if (!empty($payload['admin'])) {
  279. $uname = trim((string)($payload['uname'] ?? ''));
  280. if ($uname === '') {
  281. return null;
  282. }
  283. try {
  284. $row = Db::name('admin')->where('username', $uname)->find();
  285. } catch (\Throwable $e) {
  286. $row = null;
  287. }
  288. if (!is_array($row) || ($row['status'] ?? '') === 'hidden') {
  289. return null;
  290. }
  291. return [
  292. 'phone' => trim((string)($row['mobile'] ?? '')),
  293. 'company_name' => '',
  294. 'username' => $uname,
  295. 'customer_user_id' => 0,
  296. 'admin_id' => (int)($row['id'] ?? 0),
  297. 'login_type' => 'remember',
  298. 'is_admin' => 1,
  299. 'login_time' => $loginTime,
  300. ];
  301. }
  302. $cid = (int)($payload['uid'] ?? 0);
  303. if ($cid > 0) {
  304. try {
  305. $cu = Db::table('customer')->where('id', $cid)->find();
  306. } catch (\Throwable $e) {
  307. $cu = null;
  308. }
  309. if (is_array($cu) && $cu !== [] && $this->mprocCustomerUserActive($cu)) {
  310. $user = $this->mprocLoginPayloadFromCustomer($cu, 'remember');
  311. $user['login_time'] = $loginTime;
  312. return $user;
  313. }
  314. }
  315. $phone = trim((string)($payload['phone'] ?? ''));
  316. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  317. $cu = $this->mprocFindCustomerUserByMobile($phone);
  318. if ($cu) {
  319. $user = $this->mprocLoginPayloadFromCustomer($cu, 'remember');
  320. $user['login_time'] = $loginTime;
  321. return $user;
  322. }
  323. }
  324. return null;
  325. }
  326. protected function mprocAuthRevokeCacheKey(string $token): string
  327. {
  328. return 'mproc_revoked_' . md5($token);
  329. }
  330. protected function mprocRevokeAuthToken(string $token): void
  331. {
  332. $token = trim($token);
  333. if ($token === '') {
  334. return;
  335. }
  336. try {
  337. Cache::set($this->mprocAuthRevokeCacheKey($token), 1, $this->mprocTtlSeconds + 86400);
  338. } catch (\Throwable $e) {
  339. }
  340. }
  341. protected function mprocIsAuthTokenRevoked(string $token): bool
  342. {
  343. $token = trim($token);
  344. if ($token === '') {
  345. return false;
  346. }
  347. try {
  348. return (bool)Cache::get($this->mprocAuthRevokeCacheKey($token));
  349. } catch (\Throwable $e) {
  350. return false;
  351. }
  352. }
  353. /**
  354. * 按与写入时相同的 path/secure/samesite 清除 Cookie,避免仅 delete 时删不掉
  355. */
  356. protected function mprocExpireAuthCookies(): void
  357. {
  358. $opts = $this->mprocCookieOptions();
  359. $opts['expire'] = -3600;
  360. try {
  361. Cookie::set('mproc_token', '', $opts);
  362. Cookie::set('mproc_remember', '', $opts);
  363. } catch (\Throwable $e) {
  364. }
  365. try {
  366. Cookie::delete('mproc_token');
  367. Cookie::delete('mproc_remember');
  368. } catch (\Throwable $e) {
  369. }
  370. unset($_COOKIE['mproc_token'], $_COOKIE['mproc_remember']);
  371. $prefix = (string)Config::get('cookie.prefix');
  372. if ($prefix !== '') {
  373. unset($_COOKIE[$prefix . 'mproc_token'], $_COOKIE[$prefix . 'mproc_remember']);
  374. }
  375. }
  376. protected function mprocClearLogin($token)
  377. {
  378. $token = trim((string)($token ?? ''));
  379. if ($token !== '') {
  380. $this->mprocRevokeAuthToken($token);
  381. try {
  382. Cache::rm($this->mprocAuthCacheKey($token));
  383. } catch (\Throwable $e) {
  384. }
  385. if (!$this->mprocIsSignedAuthToken($token)) {
  386. try {
  387. Cache::rm('mproc_u_' . $token);
  388. } catch (\Throwable $e) {
  389. }
  390. }
  391. }
  392. // 同时作废 remember / 另一份 cookie 里可能残留的签名令牌
  393. foreach (['mproc_token', 'mproc_remember'] as $ck) {
  394. $raw = Cookie::get($ck);
  395. if ($raw !== null && $raw !== '' && (string)$raw !== $token) {
  396. $this->mprocRevokeAuthToken((string)$raw);
  397. }
  398. }
  399. Session::delete('mproc_token');
  400. $this->mprocExpireAuthCookies();
  401. }
  402. /**
  403. * 登录成功后的回跳地址校验(仅允许本站手机端首页 / 入库评分页,防止开放重定向)
  404. *
  405. * @param string $raw GET/POST 的 redirect 或当前 REQUEST_URI
  406. */
  407. protected function mprocSanitizeRedirectUrl($raw)
  408. {
  409. $s = str_replace(["\r", "\n", "\0"], '', trim((string)$raw));
  410. if ($s === '') {
  411. return '';
  412. }
  413. if (preg_match('#^https?://#i', $s)) {
  414. $h = parse_url($s, PHP_URL_HOST);
  415. if (!is_string($h) || strcasecmp($h, (string)$this->request->host()) !== 0) {
  416. return '';
  417. }
  418. $path = parse_url($s, PHP_URL_PATH);
  419. $query = parse_url($s, PHP_URL_QUERY);
  420. $s = (is_string($path) && $path !== '' ? $path : '/');
  421. if (is_string($query) && $query !== '') {
  422. $s .= '?' . $query;
  423. }
  424. }
  425. if (strpos($s, '://') !== false) {
  426. return '';
  427. }
  428. if ($s === '' || ($s[0] !== '/' && stripos($s, 'index.php') !== 0)) {
  429. return '';
  430. }
  431. if ($s[0] !== '/') {
  432. $s = '/' . ltrim($s, '/');
  433. }
  434. if (strpos($s, '//') === 0) {
  435. return '';
  436. }
  437. $okHome = stripos($s, 'index/index/index') !== false;
  438. $okInbound = stripos($s, 'index/index/inboundscore') !== false;
  439. $okDelivery = stripos($s, 'index/index/deliveryscore') !== false;
  440. if (!$okHome && !$okInbound && !$okDelivery) {
  441. return '';
  442. }
  443. if (stripos($s, 'index/index/login') !== false) {
  444. return '';
  445. }
  446. return $s;
  447. }
  448. protected function mprocRememberFocusEid(int $focusEid): void
  449. {
  450. if ($focusEid > 0) {
  451. Session::set('mproc_focus_eid', $focusEid);
  452. }
  453. }
  454. protected function mprocPullSessionFocusEid(): int
  455. {
  456. $fe = (int)Session::get('mproc_focus_eid', 0);
  457. if ($fe > 0) {
  458. Session::delete('mproc_focus_eid');
  459. }
  460. return $fe;
  461. }
  462. /**
  463. * 从 URI/query 中解析 focus_eid(兼容邮件客户端把 &amp;focus_eid 拼进上一参数值的情况)
  464. */
  465. protected function mprocParseFocusEidFromUriString(string $uri): int
  466. {
  467. if ($uri === '' || stripos($uri, 'focus_eid') === false) {
  468. return 0;
  469. }
  470. if (preg_match('/(?:[?&;]|%26)(?:amp;)*focus_eid=(\d+)/i', $uri, $m)) {
  471. return (int)$m[1];
  472. }
  473. $query = parse_url($uri, PHP_URL_QUERY);
  474. if (!is_string($query) || $query === '') {
  475. return 0;
  476. }
  477. $q = [];
  478. parse_str($query, $q);
  479. if (!is_array($q)) {
  480. return 0;
  481. }
  482. if (isset($q['focus_eid'])) {
  483. $fe = (int)$q['focus_eid'];
  484. if ($fe > 0) {
  485. return $fe;
  486. }
  487. }
  488. foreach ($q as $k => $v) {
  489. $blob = (is_string($k) ? $k : '') . '=' . (is_scalar($v) ? (string)$v : '');
  490. if (preg_match('/(?:^|[?&;]|%26)(?:amp;)*focus_eid=(\d+)/i', $blob, $m2)) {
  491. return (int)$m2[1];
  492. }
  493. }
  494. return 0;
  495. }
  496. /**
  497. * 从请求中读取短信/邮件直达明细 ID(兼容 query、pathinfo、REQUEST_URI、登录回跳 Session)
  498. */
  499. protected function mprocReadFocusEidFromRequest(): int
  500. {
  501. $fe = (int)$this->request->param('focus_eid', 0);
  502. if ($fe > 0) {
  503. $this->mprocRememberFocusEid($fe);
  504. return $fe;
  505. }
  506. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  507. $fe = $this->mprocParseFocusEidFromUriString($uri);
  508. if ($fe > 0) {
  509. $this->mprocRememberFocusEid($fe);
  510. return $fe;
  511. }
  512. $fe = (int)Session::get('mproc_focus_eid', 0);
  513. if ($fe > 0) {
  514. return $fe;
  515. }
  516. return 0;
  517. }
  518. /**
  519. * 手机端登录页 URL。注意:勿用 url('...login', ['redirect'=>]),在 url_html_suffix 下会把参数拼进 PATHINFO 导致 404。
  520. *
  521. * @param string $redirectPath 已通过 {@see mprocSanitizeRedirectUrl} 的回跳路径(含 query),空则不带参数
  522. */
  523. protected function mprocBuildLoginUrl($redirectPath = '')
  524. {
  525. $root = rtrim($this->request->root(), '/');
  526. $path = '/index/index/login';
  527. $rp = trim((string)$redirectPath);
  528. if ($rp === '') {
  529. return $root . $path;
  530. }
  531. return $root . $path . '?' . http_build_query(['redirect' => $rp], '', '&', PHP_QUERY_RFC3986);
  532. }
  533. /**
  534. * 登录成功后跳转到订单首页:用当前入口 {@see Request::root} 拼 URL,并从原 redirect 中只保留白名单 query(避免子目录部署丢参、开放重定向)
  535. *
  536. * @param string $redirectPathOrUrl 已通过 {@see mprocSanitizeRedirectUrl} 的路径或完整 URL(可含 ?focus_eid=)
  537. */
  538. protected function mprocBuildAfterLoginIndexUrl($redirectPathOrUrl)
  539. {
  540. $raw = trim((string)$redirectPathOrUrl);
  541. if ($raw === '') {
  542. return url('index/index/index', '', '', true);
  543. }
  544. $queryStr = '';
  545. if (preg_match('#^https?://#i', $raw)) {
  546. $pq = parse_url($raw);
  547. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  548. } elseif (isset($raw[0]) && $raw[0] === '/') {
  549. $pq = parse_url('http://127.0.0.1' . $raw);
  550. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  551. } else {
  552. $pq = parse_url('http://127.0.0.1/' . ltrim($raw, '/'));
  553. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  554. }
  555. $q = [];
  556. if ($queryStr !== '') {
  557. parse_str($queryStr, $q);
  558. if (!is_array($q)) {
  559. $q = [];
  560. }
  561. }
  562. $allowed = [];
  563. $fe = 0;
  564. if (isset($q['focus_eid'])) {
  565. $fe = (int)$q['focus_eid'];
  566. }
  567. if ($fe <= 0) {
  568. $fe = $this->mprocParseFocusEidFromUriString($raw);
  569. }
  570. if ($fe <= 0) {
  571. $fe = (int)Session::get('mproc_focus_eid', 0);
  572. }
  573. if ($fe > 0) {
  574. $allowed['focus_eid'] = $fe;
  575. $this->mprocRememberFocusEid($fe);
  576. }
  577. $mt = isset($q['main_tab']) ? trim((string)$q['main_tab']) : '';
  578. if ($mt === 'me' || $mt === 'orders') {
  579. $allowed['main_tab'] = $mt;
  580. }
  581. $tb = isset($q['tab']) ? trim((string)$q['tab']) : '';
  582. if ($tb === 'me' || in_array($this->mprocNormalizeListTab($tb), $this->mprocListTabWhitelist(), true)) {
  583. $allowed['tab'] = ($tb === 'me') ? 'me' : $this->mprocNormalizeListTab($tb);
  584. }
  585. if (isset($q['q']) && trim((string)$q['q']) !== '') {
  586. $allowed['q'] = substr(trim((string)$q['q']), 0, 120);
  587. }
  588. if (isset($allowed['focus_eid']) && !isset($allowed['main_tab'])) {
  589. $allowed['main_tab'] = 'orders';
  590. }
  591. $base = rtrim($this->request->root(true), '/');
  592. $path = '/index/index/index';
  593. if (isset($allowed['focus_eid']) && (int)$allowed['focus_eid'] > 0 && !isset($allowed['q'])) {
  594. $fe = (int)$allowed['focus_eid'];
  595. if (!isset($allowed['tab']) && (!isset($allowed['main_tab']) || $allowed['main_tab'] === 'orders')) {
  596. return $base . $path . '?focus_eid=' . $fe . '#mproc_fe=' . $fe;
  597. }
  598. $ordered = ['focus_eid' => $fe];
  599. if (isset($allowed['tab'])) {
  600. $ordered['tab'] = $allowed['tab'];
  601. }
  602. if (isset($allowed['main_tab'])) {
  603. $ordered['main_tab'] = $allowed['main_tab'];
  604. }
  605. return $base . $path . '?' . http_build_query($ordered, '', '&', PHP_QUERY_RFC3986) . '#mproc_fe=' . $fe;
  606. }
  607. $qs = $allowed !== [] ? ('?' . http_build_query($allowed, '', '&', PHP_QUERY_RFC3986)) : '';
  608. return $base . $path . $qs;
  609. }
  610. /**
  611. * 按登录身份决定首页:供应商→报价;质检→质量评分;生产→交货情况
  612. * 后台账号无手机端角色时返回空串(勿回登录页,避免 302 死循环)
  613. *
  614. * @param array<string, mixed> $user
  615. * @param string $redirectPathOrUrl
  616. */
  617. protected function mprocBuildAfterLoginHomeUrl(array $user, $redirectPathOrUrl = '')
  618. {
  619. if (!empty($user['is_admin'])) {
  620. $canQuality = $this->mprocAdminHasMobileRole($user, 'quality');
  621. $canDelivery = $this->mprocAdminHasMobileRole($user, 'delivery');
  622. $raw = $this->mprocSanitizeRedirectUrl($redirectPathOrUrl);
  623. if ($raw !== '') {
  624. if ($canDelivery && stripos($raw, 'deliveryscore') !== false) {
  625. return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/deliveryscore');
  626. }
  627. if ($canQuality && stripos($raw, 'inboundscore') !== false) {
  628. return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/inboundscore');
  629. }
  630. }
  631. if ($canQuality) {
  632. return url('index/index/inboundscore', '', '', true);
  633. }
  634. if ($canDelivery) {
  635. return url('index/index/deliveryscore', '', '', true);
  636. }
  637. return '';
  638. }
  639. return $this->mprocBuildAfterLoginIndexUrl($redirectPathOrUrl);
  640. }
  641. /**
  642. * 操作人员是否具备手机端任一业务角色(质检 / 生产,含超管)
  643. *
  644. * @param array<string, mixed> $user
  645. */
  646. protected function mprocAdminHasAnyMobileAccess(array $user): bool
  647. {
  648. return $this->mprocAdminHasMobileRole($user, 'quality')
  649. || $this->mprocAdminHasMobileRole($user, 'delivery');
  650. }
  651. /**
  652. * @param array<string, mixed> $row admin 表行
  653. * @return array<string, mixed>
  654. */
  655. protected function mprocLoginPayloadFromAdmin(array $row, string $loginType): array
  656. {
  657. return [
  658. 'phone' => trim((string)($row['mobile'] ?? '')),
  659. 'company_name' => '',
  660. 'username' => trim((string)($row['username'] ?? '')),
  661. 'account' => trim((string)($row['username'] ?? '')),
  662. 'customer_user_id' => 0,
  663. 'customer_id' => 0,
  664. 'admin_id' => (int)($row['id'] ?? 0),
  665. 'login_type' => $loginType,
  666. 'is_admin' => 1,
  667. ];
  668. }
  669. /** 清除当前请求中的手机端登录态(解决无权限账号卡在登录跳转) */
  670. protected function mprocDropCurrentLogin(): void
  671. {
  672. $token = $this->mprocReadTokenFromRequest();
  673. $this->mprocClearLogin($token);
  674. }
  675. /**
  676. * @param string $rawSanitized
  677. * @param string $fallbackRoute
  678. */
  679. protected function mprocAbsoluteFromSanitizedPath($rawSanitized, $fallbackRoute)
  680. {
  681. $base = rtrim($this->request->root(true), '/');
  682. $path = parse_url($rawSanitized, PHP_URL_PATH);
  683. $query = parse_url($rawSanitized, PHP_URL_QUERY);
  684. if (!is_string($path) || $path === '') {
  685. return url($fallbackRoute, '', '', true);
  686. }
  687. return $base . $path . (is_string($query) && $query !== '' ? ('?' . $query) : '');
  688. }
  689. /**
  690. * 从 purchase_order_detail 表解析真实列名(SHOW COLUMNS 只查一次,按候选小写名匹配第一条)
  691. *
  692. * @param string[] $candidatesLower 如 ['status','istatus']
  693. * @return string|null
  694. */
  695. protected function mprocResolveProcuremenColumn(array $candidatesLower)
  696. {
  697. if (self::$mprocProcuremenColumns === null) {
  698. self::$mprocProcuremenColumns = [];
  699. try {
  700. $rows = Db::query('SHOW COLUMNS FROM `purchase_order_detail`');
  701. if (is_array($rows)) {
  702. foreach ($rows as $c) {
  703. $name = isset($c['Field']) ? (string)$c['Field'] : '';
  704. if ($name !== '') {
  705. self::$mprocProcuremenColumns[strtolower($name)] = $name;
  706. }
  707. }
  708. }
  709. } catch (\Throwable $e) {
  710. self::$mprocProcuremenColumns = [];
  711. }
  712. }
  713. foreach ($candidatesLower as $low) {
  714. $k = strtolower((string)$low);
  715. if (isset(self::$mprocProcuremenColumns[$k])) {
  716. return self::$mprocProcuremenColumns[$k];
  717. }
  718. }
  719. return null;
  720. }
  721. /**
  722. * 供应商整单备注(purchase_order_detail.remark)
  723. *
  724. * @param array<string, mixed> $row
  725. */
  726. protected function mprocResolveDetailRemark(array $row): string
  727. {
  728. $col = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
  729. if ($col === null) {
  730. return '';
  731. }
  732. foreach ($row as $k => $v) {
  733. if (strcasecmp((string)$k, $col) === 0) {
  734. return trim((string)$v);
  735. }
  736. }
  737. return '';
  738. }
  739. /**
  740. * 列表:非管理员按 company_name 与登录单位一致,或 phone 与登录手机号一致(兼容手工下发单位名细微差异)
  741. *
  742. * @return array|callable 可直接 $query->where(...);空数组表示不加条件
  743. */
  744. protected function mprocListWhereForLoginUser(array $user)
  745. {
  746. if (!empty($user['is_admin'])) {
  747. return [];
  748. }
  749. $cCol = $this->mprocResolveProcuremenColumn(['company_name']);
  750. $pCol = $this->mprocResolveProcuremenColumn(['phone']);
  751. if (($cCol === null || $cCol === '') && ($pCol === null || $pCol === '')) {
  752. return ['id' => 0];
  753. }
  754. $cn = trim((string)($user['company_name'] ?? ''));
  755. $phone = trim((string)($user['phone'] ?? ''));
  756. if ($cn === '' && $phone !== '') {
  757. $cn = $this->mprocResolveCompanyForLoginPhone($phone);
  758. }
  759. if ($cn === '' && $phone === '') {
  760. return ['id' => 0];
  761. }
  762. return function ($q) use ($cCol, $pCol, $cn, $phone) {
  763. $first = true;
  764. if ($cCol !== null && $cCol !== '' && $cn !== '') {
  765. $q->where($cCol, $cn);
  766. $first = false;
  767. }
  768. if ($pCol !== null && $pCol !== '' && $phone !== '') {
  769. if ($first) {
  770. $q->where($pCol, $phone);
  771. } else {
  772. $q->whereOr($pCol, $phone);
  773. }
  774. }
  775. if ($first) {
  776. $q->where('id', 0);
  777. }
  778. };
  779. }
  780. /**
  781. * customer 是否允许登录(status:1 / 正常;空视为可登录以兼容旧数据)
  782. */
  783. protected function mprocCustomerUserActive(array $row): bool
  784. {
  785. $st = $row['status'] ?? '';
  786. if ($st === '' || $st === null) {
  787. return true;
  788. }
  789. return $st === 1 || $st === '1';
  790. }
  791. /**
  792. * @return array<string, mixed>|null
  793. */
  794. protected function mprocFindCustomerUserByMobile(string $phone): ?array
  795. {
  796. return $this->mprocFindCustomerRowByPhone($phone);
  797. }
  798. /**
  799. * 按登录账号(account)查找 customer;兼容旧会话把 11 位手机号写在 username 里
  800. *
  801. * @return array<string, mixed>|null
  802. */
  803. protected function mprocFindCustomerUserByUsername(string $username): ?array
  804. {
  805. $username = trim($username);
  806. if ($username === '') {
  807. return null;
  808. }
  809. try {
  810. $row = Db::table('customer')->where('account', $username)->order('id', 'asc')->find();
  811. } catch (\Throwable $e) {
  812. $row = null;
  813. }
  814. if ((!is_array($row) || $row === []) && preg_match('/^1\d{10}$/', $username)) {
  815. $row = $this->mprocFindCustomerRowByPhone($username);
  816. }
  817. if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
  818. return null;
  819. }
  820. return $row;
  821. }
  822. /**
  823. * customer 密码校验(md5(md5) 无 salt;兼容 bcrypt)
  824. */
  825. protected function mprocVerifyCustomerUserPassword(array $row, string $password): bool
  826. {
  827. $stored = (string)($row['password'] ?? '');
  828. if ($stored === '' || $password === '') {
  829. return false;
  830. }
  831. if (preg_match('/^\$2[ayb]\$/', $stored)) {
  832. return password_verify($password, $stored);
  833. }
  834. return hash_equals($stored, md5(md5($password)));
  835. }
  836. /**
  837. * 生成 customer 登录密码密文
  838. */
  839. protected function mprocHashCustomerUserPassword(string $password, string $existingSalt = ''): string
  840. {
  841. unset($existingSalt);
  842. return md5(md5($password));
  843. }
  844. /**
  845. * 手机端强密码校验:通过返回空字符串,否则返回错误提示
  846. */
  847. protected function mprocValidateStrongPassword(string $password): string
  848. {
  849. $len = strlen($password);
  850. if ($len < 8 || $len > 20) {
  851. return '密码长度须为8~20位';
  852. }
  853. if (preg_match('/\s/', $password)) {
  854. return '密码不能包含空格';
  855. }
  856. if (preg_match('/^\d+$/', $password)) {
  857. return '密码不能为纯数字,请同时包含字母';
  858. }
  859. if (preg_match('/^[a-zA-Z]+$/', $password)) {
  860. return '密码不能为纯字母,请同时包含数字';
  861. }
  862. if (!preg_match('/[a-zA-Z]/', $password) || !preg_match('/\d/', $password)) {
  863. return '密码须同时包含字母和数字';
  864. }
  865. if (preg_match('/(.)\1{3,}/', $password)) {
  866. return '密码不能包含过多重复字符(如1111、aaaa)';
  867. }
  868. if ($this->mprocPasswordHasSequentialRun($password, 4)) {
  869. return '密码不能包含连续字符(如1234、abcd)';
  870. }
  871. $weak = [
  872. '12345678', '123456789', '1234567890', '87654321', '01234567',
  873. 'password', 'password1', 'passw0rd', 'qwerty12', 'qwertyui',
  874. 'abc12345', 'abcd1234', 'a1b2c3d4', '11111111', '00000000',
  875. '88888888', '66666666', '11223344', '1qaz2wsx', 'qazwsxed',
  876. ];
  877. if (in_array(strtolower($password), $weak, true)) {
  878. return '密码过于简单,请重新设置';
  879. }
  880. return '';
  881. }
  882. /**
  883. * 是否包含连续递增/递减片段(长度 >= $runLen),如 1234、4321、abcd
  884. */
  885. protected function mprocPasswordHasSequentialRun(string $password, int $runLen = 4): bool
  886. {
  887. $runLen = max(3, $runLen);
  888. $lower = strtolower($password);
  889. $n = strlen($lower);
  890. if ($n < $runLen) {
  891. return false;
  892. }
  893. for ($i = 0; $i <= $n - $runLen; $i++) {
  894. $asc = true;
  895. $desc = true;
  896. for ($j = 1; $j < $runLen; $j++) {
  897. $prev = ord($lower[$i + $j - 1]);
  898. $cur = ord($lower[$i + $j]);
  899. if ($cur !== $prev + 1) {
  900. $asc = false;
  901. }
  902. if ($cur !== $prev - 1) {
  903. $desc = false;
  904. }
  905. if (!$asc && !$desc) {
  906. break;
  907. }
  908. }
  909. if ($asc || $desc) {
  910. return true;
  911. }
  912. }
  913. return false;
  914. }
  915. /**
  916. * @param array<string, mixed> $cu
  917. * @return array<string, mixed>
  918. */
  919. protected function mprocLoginPayloadFromCustomer(array $cu, string $loginType): array
  920. {
  921. $phone = trim((string)($cu['phone'] ?? ''));
  922. $account = trim((string)($cu['account'] ?? ''));
  923. if ($phone === '' && preg_match('/^1\d{10}$/', $account)) {
  924. $phone = $account;
  925. }
  926. if ($account === '' && preg_match('/^1\d{10}$/', $phone)) {
  927. $account = $phone;
  928. }
  929. $companyName = trim((string)($cu['company_name'] ?? ''));
  930. if ($companyName === '' && $phone !== '') {
  931. $companyName = $this->mprocResolveCompanyForLoginPhone($phone);
  932. }
  933. $id = (int)($cu['id'] ?? 0);
  934. return [
  935. 'phone' => $phone,
  936. 'account' => $account,
  937. 'company_name' => $companyName,
  938. 'username' => trim((string)($cu['username'] ?? '')),
  939. 'customer_id' => $id,
  940. 'customer_user_id' => $id,
  941. 'login_type' => $loginType,
  942. 'is_admin' => 0,
  943. ];
  944. }
  945. /**
  946. * 写入手机端登录态并返回跳转 URL
  947. *
  948. * @param array<string, mixed> $userData
  949. */
  950. protected function mprocFinishLogin(array $userData): void
  951. {
  952. $old = Session::get('mproc_token');
  953. if ($old) {
  954. $this->mprocClearLogin((string)$old);
  955. }
  956. $userData['login_time'] = time();
  957. $token = $this->mprocPackSignedAuthToken($userData);
  958. $token = $this->mprocTouchLoginState($userData, $token);
  959. $postR = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  960. $sessR = $this->mprocSanitizeRedirectUrl((string)Session::get('mproc_intended_url', ''));
  961. Session::delete('mproc_intended_url');
  962. $raw = $postR !== '' ? $postR : $sessR;
  963. $jump = $this->mprocBuildAfterLoginHomeUrl($userData, $raw);
  964. if ($jump === '') {
  965. $this->mprocClearLogin($token);
  966. $this->error('账号或密码错误');
  967. }
  968. $this->success('登录成功', $jump, [
  969. 'mproc_token' => $token,
  970. 'keep_hours' => $this->mprocKeepHours(),
  971. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  972. ]);
  973. }
  974. /**
  975. * 登录手机号对应的外协单位名称:customer 表;否则 purchase_order_detail
  976. */
  977. protected function mprocResolveCompanyForLoginPhone(string $phone): string
  978. {
  979. $phone = trim($phone);
  980. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  981. return '';
  982. }
  983. $cust = $this->mprocFindCustomerRowByPhone($phone);
  984. if (is_array($cust) && $cust !== []) {
  985. $co = $this->mprocCustomerPickField($cust, ['company_name', 'name']);
  986. if ($co !== '') {
  987. return $co;
  988. }
  989. }
  990. try {
  991. $one = Db::table('purchase_order_detail')
  992. ->where('phone', $phone)
  993. ->order('id', 'desc')
  994. ->find();
  995. if (is_array($one)) {
  996. $n = trim((string)($one['company_name'] ?? ''));
  997. if ($n !== '') {
  998. return $n;
  999. }
  1000. }
  1001. } catch (\Throwable $e) {
  1002. }
  1003. return '';
  1004. }
  1005. /**
  1006. * 按手机号匹配 customer(phone 或 account 单值相等)
  1007. *
  1008. * @return array<string, mixed>|null
  1009. */
  1010. protected function mprocFindCustomerRowByPhone(string $phone): ?array
  1011. {
  1012. $phone = trim($phone);
  1013. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  1014. return null;
  1015. }
  1016. try {
  1017. $row = Db::table('customer')
  1018. ->where(function ($q) use ($phone) {
  1019. $q->where('phone', $phone)->whereOr('account', $phone);
  1020. })
  1021. ->order('id', 'asc')
  1022. ->find();
  1023. } catch (\Throwable $e) {
  1024. return null;
  1025. }
  1026. if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
  1027. return null;
  1028. }
  1029. return $row;
  1030. }
  1031. /**
  1032. * 管理员表 fa_admin.mobile 与当前手机号一致且未禁用(用于手机验证码管理员通道)
  1033. *
  1034. * @return array<string, mixed>|null
  1035. */
  1036. protected function mprocAdminRowByMobile(string $phone): ?array
  1037. {
  1038. $phone = trim($phone);
  1039. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  1040. return null;
  1041. }
  1042. try {
  1043. $row = Db::name('admin')
  1044. ->where('mobile', $phone)
  1045. ->where('status', '<>', 'hidden')
  1046. ->order('id', 'asc')
  1047. ->find();
  1048. } catch (\Throwable $e) {
  1049. return null;
  1050. }
  1051. return is_array($row) && $row !== [] ? $row : null;
  1052. }
  1053. /**
  1054. * 在 customer 表中匹配当前用户:优先手机号,否则按公司名
  1055. *
  1056. * @return array<string, mixed>|null
  1057. */
  1058. protected function mprocFindCustomerRowForUser(array $user): ?array
  1059. {
  1060. $phone = trim((string)($user['phone'] ?? ''));
  1061. if ($phone === '') {
  1062. $phone = trim((string)($user['account'] ?? ''));
  1063. }
  1064. $cn = trim((string)($user['company_name'] ?? ''));
  1065. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  1066. $byPhone = $this->mprocFindCustomerRowByPhone($phone);
  1067. if ($byPhone !== null) {
  1068. return $byPhone;
  1069. }
  1070. }
  1071. if ($cn !== '') {
  1072. try {
  1073. // customer 表无 name 列,勿用 whereOr('name')
  1074. $hit = Db::table('customer')
  1075. ->where('company_name', $cn)
  1076. ->order('id', 'desc')
  1077. ->find();
  1078. } catch (\Throwable $e) {
  1079. $hit = null;
  1080. }
  1081. if (is_array($hit) && $hit !== []) {
  1082. return $hit;
  1083. }
  1084. }
  1085. return null;
  1086. }
  1087. /**
  1088. * 从 customer 行取字段(兼容列名大小写)
  1089. *
  1090. * @param string[] $candidates
  1091. */
  1092. protected function mprocCustomerPickField(array $row, array $candidates): string
  1093. {
  1094. foreach ($candidates as $want) {
  1095. $lw = strtolower($want);
  1096. foreach ($row as $k => $v) {
  1097. if (!is_string($k)) {
  1098. continue;
  1099. }
  1100. if (strtolower($k) !== $lw) {
  1101. continue;
  1102. }
  1103. $s = trim((string)$v);
  1104. if ($s !== '') {
  1105. return $s;
  1106. }
  1107. }
  1108. }
  1109. return '';
  1110. }
  1111. /**
  1112. * 明细表关键字搜索:仅对 purchase_order_detail 真实存在的列 LIKE;
  1113. * 主表 purchase_order 上的订单号、印件、工序等另查 scydgy_id 再 OR 进列表(避免引用不存在的列导致整页查失败)。
  1114. *
  1115. * @param \think\db\Query $query
  1116. */
  1117. protected function mprocApplySearchKeywordToDetailQuery($query, $search)
  1118. {
  1119. $kw = trim((string)$search);
  1120. if ($kw === '') {
  1121. return;
  1122. }
  1123. $map = self::$mprocProcuremenColumns;
  1124. if (!is_array($map) || $map === []) {
  1125. return;
  1126. }
  1127. $like = '%' . addcslashes($kw, '%_\\') . '%';
  1128. $wantLower = ['ccydh', 'cyjmc', 'cdxmc', 'company_name', 'cgzzxmc', 'cgymc', 'cdf', 'phone', 'email'];
  1129. $detailCols = [];
  1130. foreach ($wantLower as $low) {
  1131. if (isset($map[$low])) {
  1132. $detailCols[] = $map[$low];
  1133. }
  1134. }
  1135. $scydgyCol = isset($map['scydgy_id']) ? $map['scydgy_id'] : 'scydgy_id';
  1136. $idCol = isset($map['id']) ? $map['id'] : 'id';
  1137. $poSidList = [];
  1138. $poWant = ['CCYDH', 'CYJMC', 'CDXMC', 'CGYMC', 'cGzzxMc', 'CDF'];
  1139. try {
  1140. $col = Db::table('purchase_order')
  1141. ->where(function ($sub) use ($like, $poWant) {
  1142. $firstPo = true;
  1143. foreach ($poWant as $pf) {
  1144. if ($firstPo) {
  1145. $sub->where($pf, 'like', $like);
  1146. $firstPo = false;
  1147. } else {
  1148. $sub->whereOr($pf, 'like', $like);
  1149. }
  1150. }
  1151. })
  1152. ->column('scydgy_id');
  1153. if (is_array($col)) {
  1154. foreach ($col as $v) {
  1155. $id = (int)$v;
  1156. if ($this->mprocIsValidScydgyRowId($id)) {
  1157. $poSidList[$id] = true;
  1158. }
  1159. }
  1160. }
  1161. $poSidList = array_keys($poSidList);
  1162. } catch (\Throwable $e) {
  1163. $poSidList = [];
  1164. }
  1165. $query->where(function ($q2) use ($like, $detailCols, $poSidList, $scydgyCol, $idCol) {
  1166. $first = true;
  1167. foreach ($detailCols as $col) {
  1168. if ($first) {
  1169. $q2->where($col, 'like', $like);
  1170. $first = false;
  1171. } else {
  1172. $q2->whereOr($col, 'like', $like);
  1173. }
  1174. }
  1175. if ($poSidList !== []) {
  1176. if ($first) {
  1177. $q2->where($scydgyCol, 'in', $poSidList);
  1178. $first = false;
  1179. } else {
  1180. $q2->whereOr($scydgyCol, 'in', $poSidList);
  1181. }
  1182. }
  1183. if ($first) {
  1184. $q2->where($idCol, '=', 0);
  1185. }
  1186. });
  1187. }
  1188. /**
  1189. * 列表:按左侧 Tab 追加 status_name 条件(与数值 status 0/1/2 无关;值由后端维护)
  1190. * - draft:status_name = 未提交
  1191. * - submitted:status_name = 已提交
  1192. * - done:status_name = 已完成
  1193. * 表无 status_name 列时不加条件(三个 Tab 数据相同,待库表补列后再筛)
  1194. *
  1195. * @param mixed $query
  1196. * @param string $tab draft|submitted|done
  1197. * @param string|null $statusNameCol 真实列名,如 status_name
  1198. */
  1199. protected function mprocApplyListTabConditions($query, $tab, $statusNameCol)
  1200. {
  1201. if ($statusNameCol === null) {
  1202. return;
  1203. }
  1204. $map = [
  1205. 'draft' => '未提交',
  1206. 'submitted' => '已提交',
  1207. 'done' => '已完成',
  1208. ];
  1209. $label = $map[$tab] ?? '未提交';
  1210. $query->where($statusNameCol, '=', $label);
  1211. }
  1212. /**
  1213. * 按登录态解析 customer 行
  1214. *
  1215. * @return array<string, mixed>|null
  1216. */
  1217. protected function mprocResolveCustomerUserForSession(array $user): ?array
  1218. {
  1219. if (!empty($user['is_admin'])) {
  1220. return null;
  1221. }
  1222. $cuId = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  1223. if ($cuId > 0) {
  1224. try {
  1225. $row = Db::table('customer')->where('id', $cuId)->find();
  1226. } catch (\Throwable $e) {
  1227. $row = null;
  1228. }
  1229. if (is_array($row) && $row !== [] && $this->mprocCustomerUserActive($row)) {
  1230. return $row;
  1231. }
  1232. }
  1233. $account = trim((string)($user['account'] ?? ''));
  1234. if ($account !== '') {
  1235. $byAcc = $this->mprocFindCustomerUserByUsername($account);
  1236. if ($byAcc !== null) {
  1237. return $byAcc;
  1238. }
  1239. }
  1240. $phone = trim((string)($user['phone'] ?? ''));
  1241. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  1242. return $this->mprocFindCustomerUserByMobile($phone);
  1243. }
  1244. $uname = trim((string)($user['username'] ?? ''));
  1245. if ($uname !== '' && preg_match('/^1\d{10}$/', $uname)) {
  1246. return $this->mprocFindCustomerUserByMobile($uname);
  1247. }
  1248. return null;
  1249. }
  1250. /**
  1251. * customer 表字段 →「我的」展示结构
  1252. *
  1253. * @param array<string, mixed> $cu
  1254. * @return array{account:string,contact_name:string,department:string,phone:string,email:string,company_name:string}
  1255. */
  1256. protected function mprocProfileFromCustomerUserRow(array $cu): array
  1257. {
  1258. $nm = trim((string)($cu['username'] ?? ''));
  1259. $account = trim((string)($cu['account'] ?? ''));
  1260. $phone = trim((string)($cu['phone'] ?? ''));
  1261. if ($phone === '') {
  1262. $phone = $account;
  1263. }
  1264. $company = trim((string)($cu['company_name'] ?? ''));
  1265. return [
  1266. 'account' => $account !== '' ? $account : $phone,
  1267. 'contact_name' => $nm,
  1268. 'department' => $company,
  1269. 'phone' => $phone,
  1270. 'email' => trim((string)($cu['email'] ?? '')),
  1271. 'company_name' => $company,
  1272. ];
  1273. }
  1274. /**
  1275. * 管理员「我的」:账号、姓名、部门(角色组)、手机、邮箱
  1276. *
  1277. * @return array{account:string,contact_name:string,department:string,phone:string,email:string,company_name:string}
  1278. */
  1279. protected function mprocProfileForAdmin(array $user): array
  1280. {
  1281. $uname = trim((string)($user['username'] ?? ''));
  1282. $out = [
  1283. 'account' => $uname,
  1284. 'contact_name' => $uname !== '' ? $uname : '管理员',
  1285. 'department' => '',
  1286. 'phone' => trim((string)($user['phone'] ?? '')),
  1287. 'email' => '',
  1288. 'company_name' => '',
  1289. ];
  1290. if ($uname === '') {
  1291. return $out;
  1292. }
  1293. try {
  1294. $row = Db::name('admin')->where('username', $uname)->find();
  1295. } catch (\Throwable $e) {
  1296. $row = null;
  1297. }
  1298. if (!is_array($row) || $row === []) {
  1299. return $out;
  1300. }
  1301. $out['account'] = trim((string)($row['username'] ?? $uname));
  1302. $nick = trim((string)($row['nickname'] ?? ''));
  1303. if ($nick !== '') {
  1304. $out['contact_name'] = $nick;
  1305. }
  1306. $mob = trim((string)($row['mobile'] ?? ''));
  1307. if ($mob !== '') {
  1308. $out['phone'] = $mob;
  1309. }
  1310. $em = trim((string)($row['email'] ?? ''));
  1311. if ($em !== '') {
  1312. $out['email'] = $em;
  1313. }
  1314. $dept = $this->mprocAdminDepartmentLabel((int)($row['id'] ?? 0));
  1315. $out['department'] = $dept;
  1316. $out['company_name'] = $dept;
  1317. return $out;
  1318. }
  1319. /**
  1320. * 管理员部门展示:优先质检中心/生产部,否则拼接所属角色组名
  1321. */
  1322. protected function mprocAdminDepartmentLabel(int $adminId): string
  1323. {
  1324. if ($adminId <= 0) {
  1325. return '';
  1326. }
  1327. $names = [];
  1328. try {
  1329. $rows = Db::name('auth_group_access')
  1330. ->alias('aga')
  1331. ->join('auth_group ag', 'aga.group_id = ag.id')
  1332. ->where('aga.uid', $adminId)
  1333. ->where('ag.status', 'normal')
  1334. ->field('ag.id,ag.name')
  1335. ->order('ag.id', 'asc')
  1336. ->select();
  1337. } catch (\Throwable $e) {
  1338. $rows = [];
  1339. }
  1340. if (!is_array($rows)) {
  1341. return '';
  1342. }
  1343. $qualityId = $this->mprocResolveMobileQualityGroupId();
  1344. $deliveryId = $this->mprocResolveMobileDeliveryGroupId();
  1345. $deliveryLabel = trim((string)Config::get('mproc.mobile_delivery_dept_name'));
  1346. if ($deliveryLabel === '') {
  1347. $deliveryLabel = '生产部';
  1348. }
  1349. foreach ($rows as $r) {
  1350. if (!is_array($r)) {
  1351. continue;
  1352. }
  1353. $gid = (int)($r['id'] ?? 0);
  1354. $name = trim((string)($r['name'] ?? ''));
  1355. if ($gid === $qualityId) {
  1356. $names[] = '质检中心';
  1357. continue;
  1358. }
  1359. if ($gid === $deliveryId) {
  1360. $names[] = $deliveryLabel;
  1361. continue;
  1362. }
  1363. if ($name !== '') {
  1364. $names[] = $name;
  1365. }
  1366. }
  1367. $names = array_values(array_unique($names));
  1368. return $names !== [] ? implode('、', $names) : '';
  1369. }
  1370. /**
  1371. * 旧会话补全 customer_id 等字段
  1372. */
  1373. protected function mprocSyncSessionCustomerUser(array $user): array
  1374. {
  1375. if (!empty($user['is_admin'])) {
  1376. return $user;
  1377. }
  1378. $cu = $this->mprocResolveCustomerUserForSession($user);
  1379. if (!$cu) {
  1380. return $user;
  1381. }
  1382. $id = (int)($cu['id'] ?? 0);
  1383. $user['customer_id'] = $id;
  1384. $user['customer_user_id'] = $id;
  1385. $user['username'] = trim((string)($cu['username'] ?? $user['username'] ?? ''));
  1386. $user['company_name'] = trim((string)($cu['company_name'] ?? ''));
  1387. $user['account'] = trim((string)($cu['account'] ?? ''));
  1388. $mob = trim((string)($cu['phone'] ?? ''));
  1389. if ($mob === '') {
  1390. $mob = trim((string)($cu['account'] ?? ''));
  1391. }
  1392. if ($mob !== '') {
  1393. $user['phone'] = $mob;
  1394. }
  1395. $token = Session::get('mproc_token');
  1396. if ($token) {
  1397. $user['login_time'] = (int)($user['login_time'] ?? time());
  1398. $tok = trim((string)$token);
  1399. Cache::set($this->mprocAuthCacheKey($tok), $user, $this->mprocTtlSeconds + 86400);
  1400. if (!$this->mprocIsSignedAuthToken($tok)) {
  1401. Cache::set('mproc_u_' . preg_replace('/[^a-f0-9]/i', '', $tok), $user, $this->mprocTtlSeconds + 86400);
  1402. }
  1403. }
  1404. return $user;
  1405. }
  1406. /**
  1407. * 「我的」:普通用户 customer;管理员 admin
  1408. */
  1409. protected function mprocProfileForUser(array $user)
  1410. {
  1411. if (!empty($user['is_admin'])) {
  1412. return $this->mprocProfileForAdmin($user);
  1413. }
  1414. $cu = $this->mprocResolveCustomerUserForSession($user);
  1415. if (is_array($cu) && $cu !== []) {
  1416. return $this->mprocProfileFromCustomerUserRow($cu);
  1417. }
  1418. $phone = trim((string)($user['phone'] ?? ''));
  1419. if ($phone === '') {
  1420. $phone = trim((string)($user['account'] ?? ''));
  1421. }
  1422. return [
  1423. 'account' => $phone !== '' ? $phone : trim((string)($user['account'] ?? '')),
  1424. 'contact_name' => trim((string)($user['username'] ?? '')),
  1425. 'department' => trim((string)($user['company_name'] ?? '')),
  1426. 'phone' => $phone,
  1427. 'email' => '',
  1428. 'company_name' => trim((string)($user['company_name'] ?? '')),
  1429. ];
  1430. }
  1431. protected function mprocIsValidScydgyRowId($id): bool
  1432. {
  1433. return (int)$id !== 0;
  1434. }
  1435. /**
  1436. * 将 purchase_order(工序行主表)快照合并进 purchase_order_detail 行:订单级信息以主表为准;
  1437. * 金额、交期、外厂 company、明细 status 等仍保留明细表。
  1438. *
  1439. * @param array $row 引用:明细行
  1440. * @param array $poRow purchase_order 一行
  1441. */
  1442. protected function mprocMergePurchaseOrderIntoDetail(array &$row, array $poRow)
  1443. {
  1444. $pl = array_change_key_case($poRow, CASE_LOWER);
  1445. $hdr = [
  1446. 'ccydh' => 'CCYDH',
  1447. 'cyjmc' => 'CYJMC',
  1448. 'cdf' => 'CDF',
  1449. 'cgzzxmc' => 'cGzzxMc',
  1450. 'cgymc' => 'CGYMC',
  1451. 'cdxmc' => 'CDXMC',
  1452. 'ngzl' => 'NGZL',
  1453. 'cdw' => 'CDW',
  1454. 'cgybh' => 'CGYBH',
  1455. ];
  1456. foreach ($hdr as $lk => $out) {
  1457. if (!array_key_exists($lk, $pl)) {
  1458. continue;
  1459. }
  1460. $v = $pl[$lk];
  1461. if ($v !== null && $v !== '') {
  1462. $row[$out] = $v;
  1463. }
  1464. }
  1465. // 本次数量、最高限价:仅存在于主表;PDO 列名大小写可能不一致
  1466. $qtyRaw = '';
  1467. foreach (['this_quantity', 'This_quantity'] as $qk) {
  1468. if (array_key_exists($qk, $pl) && $pl[$qk] !== null && $pl[$qk] !== '') {
  1469. $qtyRaw = trim((string)$pl[$qk]);
  1470. break;
  1471. }
  1472. }
  1473. if ($qtyRaw === '') {
  1474. foreach (['This_quantity', 'this_quantity'] as $qk) {
  1475. if (array_key_exists($qk, $poRow) && $poRow[$qk] !== null && $poRow[$qk] !== '') {
  1476. $qtyRaw = trim((string)$poRow[$qk]);
  1477. break;
  1478. }
  1479. }
  1480. }
  1481. if ($qtyRaw !== '') {
  1482. $row['This_quantity'] = $qtyRaw;
  1483. }
  1484. $ceilRaw = '';
  1485. foreach (['ceilingprice', 'ceiling_price', 'CeilingPrice'] as $ck) {
  1486. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  1487. $ceilRaw = trim((string)$pl[$ck]);
  1488. break;
  1489. }
  1490. }
  1491. if ($ceilRaw === '') {
  1492. foreach (['ceilingPrice', 'ceiling_price', 'CeilingPrice'] as $ck) {
  1493. if (array_key_exists($ck, $poRow) && $poRow[$ck] !== null && $poRow[$ck] !== '') {
  1494. $ceilRaw = trim((string)$poRow[$ck]);
  1495. break;
  1496. }
  1497. }
  1498. }
  1499. if ($ceilRaw !== '') {
  1500. $row['ceilingPrice'] = $ceilRaw;
  1501. }
  1502. $sysRq = '';
  1503. foreach (['sys_rq', 'SYS_RQ'] as $sk) {
  1504. if (array_key_exists($sk, $pl) && $pl[$sk] !== null && $pl[$sk] !== '') {
  1505. $sysRq = trim((string)$pl[$sk]);
  1506. break;
  1507. }
  1508. if (array_key_exists($sk, $poRow) && $poRow[$sk] !== null && $poRow[$sk] !== '') {
  1509. $sysRq = trim((string)$poRow[$sk]);
  1510. break;
  1511. }
  1512. }
  1513. if ($sysRq !== '' && !preg_match('/^0000-00-00/i', $sysRq)) {
  1514. $row['sys_rq'] = $sysRq;
  1515. }
  1516. $deliveryDeadline = '';
  1517. foreach (['delivery_deadline', 'Delivery_deadline'] as $dk) {
  1518. if (array_key_exists($dk, $pl) && $pl[$dk] !== null && $pl[$dk] !== '') {
  1519. $deliveryDeadline = trim((string)$pl[$dk]);
  1520. break;
  1521. }
  1522. if (array_key_exists($dk, $poRow) && $poRow[$dk] !== null && $poRow[$dk] !== '') {
  1523. $deliveryDeadline = trim((string)$poRow[$dk]);
  1524. break;
  1525. }
  1526. }
  1527. if ($deliveryDeadline !== '' && !preg_match('/^0000-00-00/i', $deliveryDeadline)) {
  1528. $row['delivery_deadline'] = $deliveryDeadline;
  1529. }
  1530. }
  1531. /**
  1532. * 统一取年月日(无效则空串)
  1533. */
  1534. protected function mprocFormatYmdValue($raw): string
  1535. {
  1536. $s = trim((string)$raw);
  1537. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  1538. return '';
  1539. }
  1540. $s = str_replace(['/', '.'], '-', $s);
  1541. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  1542. return $m[1];
  1543. }
  1544. $ts = strtotime(str_replace('T', ' ', $s));
  1545. if ($ts === false || $ts <= 0) {
  1546. return '';
  1547. }
  1548. return date('Y-m-d', $ts);
  1549. }
  1550. /**
  1551. * 列表展示:招标截止 / 交货截止
  1552. *
  1553. * @param array<string, mixed> $row
  1554. */
  1555. protected function mprocEnrichOrderDeadlineDisplay(array &$row): void
  1556. {
  1557. $sysRqRaw = $this->mprocResolveSysRqFromPo($row);
  1558. $bid = $this->mprocFormatYmdValue($sysRqRaw !== '' ? $sysRqRaw : ($row['sys_rq'] ?? ''));
  1559. $del = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? '');
  1560. $row['mproc_bid_deadline_display'] = $bid;
  1561. // 完整截止时间供前端保存前校验(含时分秒)
  1562. $row['mproc_bid_deadline'] = $sysRqRaw;
  1563. $row['mproc_delivery_deadline_display'] = $del;
  1564. $row['mproc_delivery_deadline'] = $del;
  1565. }
  1566. /**
  1567. * 明细对应主表的交货截止日期 Y-m-d
  1568. *
  1569. * @param array<string, mixed> $row
  1570. */
  1571. protected function mprocResolveDeliveryDeadlineYmdForDetailRow(array $row): string
  1572. {
  1573. $fromRow = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? $row['mproc_delivery_deadline'] ?? '');
  1574. if ($fromRow !== '') {
  1575. return $fromRow;
  1576. }
  1577. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1578. if (!$this->mprocIsValidScydgyRowId($sid)) {
  1579. return '';
  1580. }
  1581. try {
  1582. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1583. } catch (\Throwable $e) {
  1584. $po = null;
  1585. }
  1586. if (!is_array($po)) {
  1587. return '';
  1588. }
  1589. return $this->mprocFormatYmdValue($po['delivery_deadline'] ?? $po['Delivery_deadline'] ?? '');
  1590. }
  1591. /**
  1592. * 主表报价截止时间(未设置则视为未截止)
  1593. *
  1594. * @param array<string, mixed>|null $po
  1595. */
  1596. protected function mprocResolveSysRqFromPo(?array $po): string
  1597. {
  1598. if (!is_array($po)) {
  1599. return '';
  1600. }
  1601. $sr = trim((string)($po['sys_rq'] ?? $po['SYS_RQ'] ?? ''));
  1602. if ($sr === '') {
  1603. $pl = array_change_key_case($po, CASE_LOWER);
  1604. $sr = trim((string)($pl['sys_rq'] ?? ''));
  1605. }
  1606. return ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) ? $sr : '';
  1607. }
  1608. /**
  1609. * 从主表/明细解析订单号
  1610. *
  1611. * @param array<string, mixed>|null $po
  1612. * @param array<string, mixed>|null $row
  1613. */
  1614. protected function mprocResolveCcydhFromPoOrRow(?array $po, ?array $row = null): string
  1615. {
  1616. foreach ([$po, $row] as $src) {
  1617. if (!is_array($src)) {
  1618. continue;
  1619. }
  1620. $c = trim((string)($src['CCYDH'] ?? $src['ccydh'] ?? ''));
  1621. if ($c !== '') {
  1622. return $c;
  1623. }
  1624. }
  1625. return '';
  1626. }
  1627. /**
  1628. * 批量:已开标验证的订单号集合(本请求内可复用)
  1629. *
  1630. * @var array<string, bool>|null
  1631. */
  1632. protected $mprocBidOpenVerifiedSet = null;
  1633. /**
  1634. * @param array<int, string> $ccydhs
  1635. * @return array<string, bool>
  1636. */
  1637. protected function mprocLoadBidOpenVerifiedCcydhSet(array $ccydhs): array
  1638. {
  1639. $set = [];
  1640. $list = [];
  1641. foreach ($ccydhs as $c) {
  1642. $c = trim((string)$c);
  1643. if ($c !== '') {
  1644. $list[$c] = true;
  1645. }
  1646. }
  1647. if ($list === []) {
  1648. return $set;
  1649. }
  1650. try {
  1651. $rows = Db::table('purchase_order_bid_open')
  1652. ->where('ccydh', 'in', array_keys($list))
  1653. ->field('ccydh')
  1654. ->select();
  1655. if (!is_array($rows)) {
  1656. return $set;
  1657. }
  1658. foreach ($rows as $row) {
  1659. if (!is_array($row)) {
  1660. continue;
  1661. }
  1662. $c = trim((string)($row['ccydh'] ?? ''));
  1663. if ($c !== '') {
  1664. $set[$c] = true;
  1665. }
  1666. }
  1667. } catch (\Throwable $e) {
  1668. return [];
  1669. }
  1670. return $set;
  1671. }
  1672. /**
  1673. * 该订单是否已完成开标双重验证(有 purchase_order_bid_open 记录)
  1674. */
  1675. protected function mprocIsBidOpenVerified(string $ccydh): bool
  1676. {
  1677. $ccydh = trim($ccydh);
  1678. if ($ccydh === '') {
  1679. return false;
  1680. }
  1681. if (is_array($this->mprocBidOpenVerifiedSet)) {
  1682. return isset($this->mprocBidOpenVerifiedSet[$ccydh]);
  1683. }
  1684. try {
  1685. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1686. return is_array($row);
  1687. } catch (\Throwable $e) {
  1688. return false;
  1689. }
  1690. }
  1691. /**
  1692. * @param array<string, mixed>|null $po
  1693. * @param array<string, mixed>|null $row
  1694. */
  1695. protected function mprocIsBidOpenVerifiedForPoOrRow(?array $po, ?array $row = null): bool
  1696. {
  1697. return $this->mprocIsBidOpenVerified($this->mprocResolveCcydhFromPoOrRow($po, $row));
  1698. }
  1699. /**
  1700. * 手机端:仅当主表设置了 sys_rq 且已到期时视为截止(无截止时间仍可填报)
  1701. * 保存时务必再调一次,防止页面长时间打开、截止后仍提交
  1702. *
  1703. * @param array<string, mixed>|null $po
  1704. */
  1705. protected function mprocIsQuoteDeadlineReachedForPo(?array $po): bool
  1706. {
  1707. $raw = $this->mprocResolveSysRqFromPo($po);
  1708. if ($raw === '') {
  1709. return false;
  1710. }
  1711. $ts = strtotime(str_replace('T', ' ', $raw));
  1712. if ($ts === false || $ts <= 0) {
  1713. return false;
  1714. }
  1715. return time() >= $ts;
  1716. }
  1717. /**
  1718. * 保存前强制按库中最新招标截止时间校验(避免弹窗久开后仍提交)
  1719. *
  1720. * @param array<string, mixed>|null $po
  1721. */
  1722. protected function mprocAssertQuoteNotDeadlineReached(?array $po, string $label = ''): void
  1723. {
  1724. // 以库中最新主表为准,避免内存中旧快照
  1725. $freshPo = null;
  1726. if (is_array($po)) {
  1727. $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
  1728. if ($this->mprocIsValidScydgyRowId($sid)) {
  1729. try {
  1730. $freshPo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1731. } catch (\Throwable $e) {
  1732. $freshPo = null;
  1733. }
  1734. }
  1735. }
  1736. $checkPo = is_array($freshPo) ? $freshPo : $po;
  1737. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($checkPo) ? $checkPo : null)) {
  1738. throw new \InvalidArgumentException(
  1739. ($label !== '' ? $label : '') . '已超过招标截止时间,不可再提交'
  1740. );
  1741. }
  1742. }
  1743. /**
  1744. * 保存前:截止时间 + 已开标均不可再改
  1745. *
  1746. * @param array<string, mixed>|null $po
  1747. * @param array<string, mixed>|null $row
  1748. */
  1749. protected function mprocAssertQuoteStillEditable(?array $po, string $label = '', ?array $row = null): void
  1750. {
  1751. $sid = 0;
  1752. if (is_array($row)) {
  1753. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1754. }
  1755. if ($sid === 0 && is_array($po)) {
  1756. $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
  1757. }
  1758. // 手工询价无招标截止、不开标
  1759. if ($sid < 0) {
  1760. return;
  1761. }
  1762. $this->mprocAssertQuoteNotDeadlineReached($po, $label);
  1763. $freshPo = is_array($po) ? $po : null;
  1764. if (is_array($po)) {
  1765. if ($this->mprocIsValidScydgyRowId($sid)) {
  1766. try {
  1767. $got = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1768. if (is_array($got)) {
  1769. $freshPo = $got;
  1770. }
  1771. } catch (\Throwable $e) {
  1772. }
  1773. }
  1774. }
  1775. // 保存场景不走列表缓存,直接查库
  1776. $prev = $this->mprocBidOpenVerifiedSet;
  1777. $this->mprocBidOpenVerifiedSet = null;
  1778. $opened = $this->mprocIsBidOpenVerifiedForPoOrRow($freshPo, $row);
  1779. $this->mprocBidOpenVerifiedSet = $prev;
  1780. if ($opened) {
  1781. throw new \InvalidArgumentException(
  1782. ($label !== '' ? $label : '') . '已开标验证,不可再提交'
  1783. );
  1784. }
  1785. }
  1786. /**
  1787. * 主单已完结后:中标 / 未中标
  1788. *
  1789. * @param array<string, mixed> $row
  1790. * @param array<string, mixed>|null $po
  1791. */
  1792. protected function mprocResolvePickResultText(array $row, ?array $po): string
  1793. {
  1794. if (!is_array($po) || !ProcuremenStatus::isPoCompleted($po['status'] ?? $po['STATUS'] ?? '')) {
  1795. return '';
  1796. }
  1797. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  1798. return ProcuremenStatus::isPodPicked($detailStatus) ? '中标' : '未中标';
  1799. }
  1800. /**
  1801. * 手机端左侧 Tab:
  1802. * 询价:rfq / rfq_submitted(手工单 scydgy_id&lt;0,仅未提交/已提交)
  1803. * 报价:draft / submitted / done(协助下发)
  1804. *
  1805. * @param array<string, mixed> $row
  1806. * @param array<string, mixed>|null $po
  1807. */
  1808. protected function mprocResolveListTabForRow(array $row, ?array $po, string $effectiveSn): string
  1809. {
  1810. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1811. // 手工询价:无招标截止;仅未提交/已提交(对应待报价/已报价)
  1812. if ($sid < 0) {
  1813. if ($effectiveSn === '已提交'
  1814. || in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  1815. return 'rfq_submitted';
  1816. }
  1817. return 'rfq';
  1818. }
  1819. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  1820. return 'done';
  1821. }
  1822. if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)
  1823. || $this->mprocIsQuoteDeadlineReachedForPo($po)) {
  1824. // 已开标或已过招标截止 →「已完成」
  1825. return 'done';
  1826. }
  1827. if ($effectiveSn === '已提交') {
  1828. return 'submitted';
  1829. }
  1830. return 'draft';
  1831. }
  1832. /**
  1833. * @return string[]
  1834. */
  1835. protected function mprocListTabWhitelist(): array
  1836. {
  1837. return ['rfq', 'rfq_submitted', 'draft', 'submitted', 'done'];
  1838. }
  1839. /**
  1840. * 兼容旧地址 tab=rfq_done → 询价已提交
  1841. */
  1842. protected function mprocNormalizeListTab(string $tab): string
  1843. {
  1844. if ($tab === 'rfq_done') {
  1845. return 'rfq_submitted';
  1846. }
  1847. if (!in_array($tab, $this->mprocListTabWhitelist(), true)) {
  1848. return 'draft';
  1849. }
  1850. return $tab;
  1851. }
  1852. protected function mprocIsDoneListTab(string $tab): bool
  1853. {
  1854. return $tab === 'done';
  1855. }
  1856. protected function mprocIsRfqListTab(string $tab): bool
  1857. {
  1858. return $tab === 'rfq' || $tab === 'rfq_submitted';
  1859. }
  1860. /**
  1861. * 复合 Tab → 状态维度:draft|submitted|done
  1862. */
  1863. protected function mprocStatusFromListTab(string $tab): string
  1864. {
  1865. if ($tab === 'rfq' || $tab === 'draft') {
  1866. return 'draft';
  1867. }
  1868. if ($tab === 'rfq_submitted' || $tab === 'submitted') {
  1869. return 'submitted';
  1870. }
  1871. if ($this->mprocIsDoneListTab($tab)) {
  1872. return 'done';
  1873. }
  1874. return 'draft';
  1875. }
  1876. /**
  1877. * 同一订单号 + 供应商合并为一张卡片
  1878. *
  1879. * @param array<int, array<string, mixed>> $rows
  1880. * @return array<int, array<string, mixed>>
  1881. */
  1882. protected function mprocGroupRowsByOrder(array $rows): array
  1883. {
  1884. $groups = [];
  1885. $order = [];
  1886. foreach ($rows as $row) {
  1887. if (!is_array($row)) {
  1888. continue;
  1889. }
  1890. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1891. $cname = trim((string)($row['company_name'] ?? ''));
  1892. $key = ($ccydh !== '' ? $ccydh : ('eid_' . (int)($row['eid'] ?? 0))) . '|' . $cname;
  1893. if (!isset($groups[$key])) {
  1894. $groups[$key] = [
  1895. 'group_key' => $key,
  1896. 'CCYDH' => $ccydh,
  1897. 'CYJMC' => trim((string)($row['CYJMC'] ?? '')),
  1898. 'company_name' => $cname,
  1899. 'mproc_bid_deadline_display' => trim((string)($row['mproc_bid_deadline_display'] ?? '')),
  1900. 'mproc_bid_deadline' => trim((string)($row['mproc_bid_deadline'] ?? '')),
  1901. 'mproc_delivery_deadline_display' => trim((string)($row['mproc_delivery_deadline_display'] ?? '')),
  1902. 'mproc_delivery_deadline' => trim((string)($row['mproc_delivery_deadline'] ?? '')),
  1903. 'lines' => [],
  1904. ];
  1905. $order[] = $key;
  1906. } else {
  1907. if ($groups[$key]['mproc_delivery_deadline'] === ''
  1908. && trim((string)($row['mproc_delivery_deadline'] ?? '')) !== '') {
  1909. $groups[$key]['mproc_delivery_deadline'] = trim((string)$row['mproc_delivery_deadline']);
  1910. $groups[$key]['mproc_delivery_deadline_display'] = trim((string)($row['mproc_delivery_deadline_display'] ?? ''));
  1911. }
  1912. if ($groups[$key]['mproc_bid_deadline'] === ''
  1913. && trim((string)($row['mproc_bid_deadline'] ?? '')) !== '') {
  1914. $groups[$key]['mproc_bid_deadline'] = trim((string)$row['mproc_bid_deadline']);
  1915. }
  1916. if ($groups[$key]['mproc_bid_deadline_display'] === ''
  1917. && trim((string)($row['mproc_bid_deadline_display'] ?? '')) !== '') {
  1918. $groups[$key]['mproc_bid_deadline_display'] = trim((string)$row['mproc_bid_deadline_display']);
  1919. }
  1920. }
  1921. $groups[$key]['lines'][] = $row;
  1922. }
  1923. $out = [];
  1924. foreach ($order as $key) {
  1925. $g = $groups[$key];
  1926. $lines = is_array($g['lines'] ?? null) ? $g['lines'] : [];
  1927. usort($lines, function ($a, $b) {
  1928. $sa = (int)($a['scydgy_id'] ?? 0);
  1929. $sb = (int)($b['scydgy_id'] ?? 0);
  1930. if ($sa !== $sb) {
  1931. return $sa <=> $sb;
  1932. }
  1933. return ((int)($a['eid'] ?? 0)) <=> ((int)($b['eid'] ?? 0));
  1934. });
  1935. $g['lines'] = $lines;
  1936. $g['line_count'] = count($lines);
  1937. $canEdit = false;
  1938. $bidOpen = false;
  1939. foreach ($lines as $ln) {
  1940. if (!is_array($ln)) {
  1941. continue;
  1942. }
  1943. if ((int)($ln['mproc_can_edit'] ?? 0) === 1) {
  1944. $canEdit = true;
  1945. }
  1946. if ((int)($ln['mproc_bid_open_verified'] ?? 0) === 1) {
  1947. $bidOpen = true;
  1948. }
  1949. }
  1950. $g['can_edit'] = $canEdit ? 1 : 0;
  1951. $g['mproc_bid_open_verified'] = $bidOpen ? 1 : 0;
  1952. $remark = '';
  1953. $doneLabel = '';
  1954. $pickResult = '';
  1955. $hasWin = false;
  1956. $hasLose = false;
  1957. $hasExpired = false;
  1958. foreach ($lines as $ln) {
  1959. if (!is_array($ln)) {
  1960. continue;
  1961. }
  1962. $rm = trim((string)($ln['mproc_remark'] ?? ''));
  1963. if ($rm !== '' && $remark === '') {
  1964. $remark = $rm;
  1965. }
  1966. $pr = trim((string)($ln['mproc_pick_result'] ?? ''));
  1967. $dl = trim((string)($ln['mproc_done_label'] ?? ''));
  1968. if ($pr === '中标' || $dl === '中标') {
  1969. $hasWin = true;
  1970. } elseif ($pr === '未中标' || $dl === '未中标') {
  1971. $hasLose = true;
  1972. } elseif ($dl === '已截止' || (int)($ln['mproc_deadline_reached'] ?? 0) === 1) {
  1973. $hasExpired = true;
  1974. }
  1975. }
  1976. if ($hasWin) {
  1977. $doneLabel = '中标';
  1978. $pickResult = '中标';
  1979. } elseif ($hasLose) {
  1980. $doneLabel = '未中标';
  1981. $pickResult = '未中标';
  1982. } elseif ($hasExpired) {
  1983. $doneLabel = '已截止';
  1984. $pickResult = '';
  1985. }
  1986. $g['remark'] = $remark;
  1987. $g['mproc_done_label'] = $doneLabel;
  1988. $g['mproc_pick_result'] = $pickResult;
  1989. $out[] = $g;
  1990. }
  1991. return $out;
  1992. }
  1993. /**
  1994. * 查询 purchase_order_detail 列表(订单页)
  1995. * 无搜索词 / 有搜索词:均按左侧 Tab 筛选(draft/submitted/done)
  1996. * 有搜索词时:在当前 Tab 内做关键字匹配
  1997. *
  1998. * @param string $tab draft|submitted|done
  1999. * @param string|null $statusNameCol status_name 真实列名;为 null 时不按 Tab 过滤
  2000. * @return array{rows: array, done_no_status: int}
  2001. */
  2002. protected function mprocFetchProcuremenList(array $user, $tab, $q, $statusNameCol)
  2003. {
  2004. $query = Db::table('purchase_order_detail')->order('id', 'desc');
  2005. // 初选下发已向供应商发送通知后,手机端可见 wflow_status>=1 的明细
  2006. $userWhere = $this->mprocListWhereForLoginUser($user);
  2007. if ($userWhere !== []) {
  2008. $query->where($userWhere);
  2009. }
  2010. if (trim((string)$q) === '' && $this->mprocIsDoneListTab((string)$tab) && $statusNameCol !== null) {
  2011. $this->mprocSyncLegacyApprovedStatusNames($user, $statusNameCol);
  2012. }
  2013. $this->mprocApplySearchKeywordToDetailQuery($query, $q);
  2014. // Tab 筛选在 PHP 层按截止时间、审批结果综合判断(含逾期进「已完成」、未中标等)
  2015. try {
  2016. $rows = $query->limit(500)->select();
  2017. } catch (\Throwable $e) {
  2018. $rows = [];
  2019. }
  2020. if (!is_array($rows)) {
  2021. $rows = [];
  2022. }
  2023. $poBySid = [];
  2024. $sidList = [];
  2025. foreach ($rows as $r0) {
  2026. if (!is_array($r0)) {
  2027. continue;
  2028. }
  2029. $sid0 = (int)($r0['scydgy_id'] ?? $r0['SCYDGY_ID'] ?? 0);
  2030. if ($this->mprocIsValidScydgyRowId($sid0)) {
  2031. $sidList[$sid0] = true;
  2032. }
  2033. }
  2034. if ($sidList !== []) {
  2035. try {
  2036. $poRows = Db::table('purchase_order')
  2037. ->where('scydgy_id', 'in', array_values(array_keys($sidList)))
  2038. ->select();
  2039. if (is_array($poRows)) {
  2040. foreach ($poRows as $pr) {
  2041. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  2042. if ($this->mprocIsValidScydgyRowId($sidk)) {
  2043. $poBySid[$sidk] = $pr;
  2044. }
  2045. }
  2046. }
  2047. } catch (\Throwable $e) {
  2048. }
  2049. }
  2050. $ccydhForBid = [];
  2051. foreach ($poBySid as $pr) {
  2052. if (!is_array($pr)) {
  2053. continue;
  2054. }
  2055. $c = trim((string)($pr['CCYDH'] ?? $pr['ccydh'] ?? ''));
  2056. if ($c !== '') {
  2057. $ccydhForBid[$c] = true;
  2058. }
  2059. }
  2060. foreach ($rows as $r0) {
  2061. if (!is_array($r0)) {
  2062. continue;
  2063. }
  2064. $c = trim((string)($r0['CCYDH'] ?? $r0['ccydh'] ?? ''));
  2065. if ($c !== '') {
  2066. $ccydhForBid[$c] = true;
  2067. }
  2068. }
  2069. $this->mprocBidOpenVerifiedSet = $this->mprocLoadBidOpenVerifiedCcydhSet(array_keys($ccydhForBid));
  2070. foreach ($rows as &$row) {
  2071. if (!is_array($row)) {
  2072. continue;
  2073. }
  2074. // 废弃明细不在手机端展示
  2075. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')
  2076. || trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID) {
  2077. $row = null;
  2078. continue;
  2079. }
  2080. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? 0);
  2081. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2082. if ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) {
  2083. $this->mprocMergePurchaseOrderIntoDetail($row, $poBySid[$sid]);
  2084. }
  2085. $poRow = ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) ? $poBySid[$sid] : null;
  2086. $oldSn = trim((string)($row['status_name'] ?? ''));
  2087. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, $poRow);
  2088. $row['status_name'] = $effectiveSn;
  2089. if ($statusNameCol !== null && $effectiveSn !== $oldSn && $row['eid'] > 0) {
  2090. $this->mprocPersistDetailStatusName((int)$row['eid'], $statusNameCol, $effectiveSn);
  2091. }
  2092. $listTab = $this->mprocResolveListTabForRow($row, $poRow, $effectiveSn);
  2093. $row['mproc_list_tab'] = $listTab;
  2094. $row['mproc_is_rfq'] = ((int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0) < 0) ? 1 : 0;
  2095. if ((int)$row['mproc_is_rfq'] === 1) {
  2096. // 手工询价不展示招标/交货截止,也不走开标截止逻辑
  2097. $row['mproc_bid_deadline'] = '';
  2098. $row['mproc_bid_deadline_display'] = '';
  2099. $row['mproc_delivery_deadline'] = '';
  2100. $row['mproc_delivery_deadline_display'] = '';
  2101. $row['mproc_deadline_reached'] = 0;
  2102. $row['mproc_bid_open_verified'] = 0;
  2103. $row['mproc_pick_result'] = '';
  2104. } else {
  2105. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  2106. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  2107. $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow($poRow, $row) ? 1 : 0;
  2108. }
  2109. if ($row['mproc_pick_result'] !== '') {
  2110. $row['mproc_done_label'] = $row['mproc_pick_result'];
  2111. } elseif ($this->mprocIsDoneListTab($listTab) && (
  2112. (int)$row['mproc_deadline_reached'] === 1
  2113. || (int)$row['mproc_bid_open_verified'] === 1
  2114. )) {
  2115. $row['mproc_done_label'] = '已截止';
  2116. } else {
  2117. $row['mproc_done_label'] = '';
  2118. }
  2119. // status_name 由库表/后端维护,不在此根据 amount 覆盖
  2120. if (!isset($row['status_name']) || $row['status_name'] === null) {
  2121. $row['status_name'] = '';
  2122. } else {
  2123. $row['status_name'] = trim((string)$row['status_name']);
  2124. }
  2125. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  2126. $am = $row['amount'] ?? null;
  2127. if ($am === null || $am === '' || (is_string($am) && trim($am) === '')) {
  2128. $row['amount_display'] = '';
  2129. } else {
  2130. $row['amount_display'] = is_scalar($am) ? (string)$am : '';
  2131. }
  2132. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2133. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  2134. $row['delivery_display'] = $m[1];
  2135. } elseif ($dv !== '') {
  2136. $row['delivery_display'] = $dv;
  2137. } else {
  2138. $row['delivery_display'] = '';
  2139. }
  2140. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  2141. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  2142. $this->mprocEnrichLeadDaysDisplay($row);
  2143. if ((int)$row['mproc_is_rfq'] === 1) {
  2144. $row['mproc_bid_deadline'] = '';
  2145. $row['mproc_bid_deadline_display'] = '';
  2146. $row['mproc_delivery_deadline'] = '';
  2147. $row['mproc_delivery_deadline_display'] = '';
  2148. } else {
  2149. $this->mprocEnrichOrderDeadlineDisplay($row);
  2150. }
  2151. $row['mproc_fill_hint'] = '';
  2152. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  2153. $row['mproc_remark'] = $this->mprocResolveDetailRemark($row);
  2154. }
  2155. unset($row);
  2156. $rows = array_values(array_filter($rows, function ($r) {
  2157. return is_array($r);
  2158. }));
  2159. // 同一供应商同一工序若有多条有效明细(重复下发),只保留最新一条
  2160. $rows = $this->mprocDedupeDetailRowsByCompanyProcess($rows);
  2161. // 始终按 Tab 过滤(含搜索):未中标/已截止等只出现在「已完成」
  2162. $rows = array_values(array_filter($rows, function ($r) use ($tab) {
  2163. return is_array($r) && trim((string)($r['mproc_list_tab'] ?? '')) === $tab;
  2164. }));
  2165. // 「已完成」仅保留近三个月(按招标截止日,缺省则交货截止/创建时间)
  2166. if ($this->mprocIsDoneListTab((string)$tab)) {
  2167. $rows = array_values(array_filter($rows, function ($r) {
  2168. return is_array($r) && $this->mprocIsWithinRecentMonths($r, 3);
  2169. }));
  2170. }
  2171. // 按招标截止日期排序:未提交/已提交截止近的在前;已完成最近截止的在前
  2172. $rows = $this->mprocSortRowsByBidDeadline($rows, $this->mprocIsDoneListTab((string)$tab) ? 'desc' : 'asc');
  2173. $groups = $this->mprocGroupRowsByOrder($rows);
  2174. return [
  2175. 'rows' => $rows ?: [],
  2176. 'groups' => $groups ?: [],
  2177. 'done_no_status' => (int)($statusNameCol === null),
  2178. ];
  2179. }
  2180. /**
  2181. * 按招标截止时间排序(无截止时间的排最后)
  2182. *
  2183. * @param array<int, array<string, mixed>> $rows
  2184. * @param string $dir asc|desc
  2185. * @return array<int, array<string, mixed>>
  2186. */
  2187. protected function mprocSortRowsByBidDeadline(array $rows, string $dir = 'asc'): array
  2188. {
  2189. $dir = strtolower($dir) === 'desc' ? 'desc' : 'asc';
  2190. usort($rows, function ($a, $b) use ($dir) {
  2191. $ta = $this->mprocBidDeadlineSortTs(is_array($a) ? $a : []);
  2192. $tb = $this->mprocBidDeadlineSortTs(is_array($b) ? $b : []);
  2193. $ha = $ta > 0;
  2194. $hb = $tb > 0;
  2195. if ($ha !== $hb) {
  2196. return $ha ? -1 : 1;
  2197. }
  2198. if ($ha && $ta !== $tb) {
  2199. return $dir === 'desc' ? ($tb <=> $ta) : ($ta <=> $tb);
  2200. }
  2201. $ida = (int)($a['eid'] ?? $a['id'] ?? 0);
  2202. $idb = (int)($b['eid'] ?? $b['id'] ?? 0);
  2203. return $idb <=> $ida;
  2204. });
  2205. return array_values($rows);
  2206. }
  2207. /**
  2208. * @param array<string, mixed> $row
  2209. */
  2210. protected function mprocBidDeadlineSortTs(array $row): int
  2211. {
  2212. $raw = trim((string)($row['mproc_bid_deadline'] ?? $row['sys_rq'] ?? $row['SYS_RQ'] ?? ''));
  2213. if ($raw === '') {
  2214. $raw = trim((string)($row['mproc_bid_deadline_display'] ?? ''));
  2215. }
  2216. if ($raw === '') {
  2217. return 0;
  2218. }
  2219. $ts = strtotime(str_replace('T', ' ', $raw));
  2220. return ($ts !== false && $ts > 0) ? (int)$ts : 0;
  2221. }
  2222. /**
  2223. * 是否属于近 N 个月(优先招标截止,其次交货截止,再次创建/更新时间)
  2224. *
  2225. * @param array<string, mixed> $row
  2226. */
  2227. protected function mprocIsWithinRecentMonths(array $row, int $months = 3): bool
  2228. {
  2229. $months = max(1, $months);
  2230. $since = strtotime(date('Y-m-d 00:00:00', strtotime('-' . $months . ' months')));
  2231. if ($since === false) {
  2232. return true;
  2233. }
  2234. $candidates = [
  2235. $row['mproc_bid_deadline'] ?? '',
  2236. $row['sys_rq'] ?? '',
  2237. $row['SYS_RQ'] ?? '',
  2238. $row['mproc_bid_deadline_display'] ?? '',
  2239. $row['mproc_delivery_deadline'] ?? '',
  2240. $row['delivery_deadline'] ?? '',
  2241. $row['mproc_delivery_deadline_display'] ?? '',
  2242. $row['createtime'] ?? '',
  2243. $row['updatetime'] ?? '',
  2244. ];
  2245. foreach ($candidates as $raw) {
  2246. $raw = trim((string)$raw);
  2247. if ($raw === '' || stripos($raw, '0000-00-00') === 0) {
  2248. continue;
  2249. }
  2250. $ts = strtotime(str_replace('T', ' ', $raw));
  2251. if ($ts === false || $ts <= 0) {
  2252. continue;
  2253. }
  2254. return $ts >= $since;
  2255. }
  2256. return false;
  2257. }
  2258. /**
  2259. * 同一供应商 + 同一工序只保留一条明细(优先 id 更大的最新记录)
  2260. *
  2261. * @param array<int, array<string, mixed>> $rows
  2262. * @return array<int, array<string, mixed>>
  2263. */
  2264. protected function mprocDedupeDetailRowsByCompanyProcess(array $rows): array
  2265. {
  2266. $best = [];
  2267. $orderKeys = [];
  2268. foreach ($rows as $row) {
  2269. if (!is_array($row)) {
  2270. continue;
  2271. }
  2272. $cn = trim((string)($row['company_name'] ?? ''));
  2273. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2274. $eid = (int)($row['eid'] ?? $row['id'] ?? $row['ID'] ?? 0);
  2275. if ($this->mprocIsValidScydgyRowId($sid)) {
  2276. $key = $cn . '|sid:' . $sid;
  2277. } else {
  2278. $key = $cn . '|eid:' . $eid;
  2279. }
  2280. if (!isset($best[$key])) {
  2281. $best[$key] = $row;
  2282. $orderKeys[] = $key;
  2283. continue;
  2284. }
  2285. $prevEid = (int)($best[$key]['eid'] ?? $best[$key]['id'] ?? $best[$key]['ID'] ?? 0);
  2286. if ($eid > $prevEid) {
  2287. $best[$key] = $row;
  2288. }
  2289. }
  2290. $out = [];
  2291. foreach ($orderKeys as $key) {
  2292. if (isset($best[$key])) {
  2293. $out[] = $best[$key];
  2294. }
  2295. }
  2296. return $out;
  2297. }
  2298. /**
  2299. * status_name → 手机端左侧 Tab
  2300. */
  2301. protected function mprocStatusNameToListTab(string $statusName): string
  2302. {
  2303. $map = ['未提交' => 'draft', '已提交' => 'submitted', '已完成' => 'done', '未通过' => 'done', '已废弃' => 'done'];
  2304. $sn = trim($statusName);
  2305. return isset($map[$sn]) ? $map[$sn] : '';
  2306. }
  2307. /**
  2308. * 短信/邮件 focus_eid 应落在的列表 Tab
  2309. */
  2310. protected function mprocResolveListTabForFocusEid(int $focusEid, array $user): string
  2311. {
  2312. if ($focusEid <= 0) {
  2313. return '';
  2314. }
  2315. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2316. if ($idCol === null) {
  2317. return '';
  2318. }
  2319. try {
  2320. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  2321. $qw = $this->mprocListWhereForLoginUser($user);
  2322. if ($qw !== []) {
  2323. $qrow->where($qw);
  2324. }
  2325. $dr = $qrow->find();
  2326. } catch (\Throwable $e) {
  2327. $dr = null;
  2328. }
  2329. if (!is_array($dr) || $dr === []) {
  2330. return '';
  2331. }
  2332. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  2333. $po = null;
  2334. if ($this->mprocIsValidScydgyRowId($sid)) {
  2335. try {
  2336. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2337. } catch (\Throwable $e) {
  2338. $po = null;
  2339. }
  2340. }
  2341. return $this->mprocResolveListTabForRow(
  2342. $dr,
  2343. is_array($po) ? $po : null,
  2344. $this->mprocResolveEffectiveStatusName($dr, is_array($po) ? $po : null)
  2345. );
  2346. }
  2347. /**
  2348. * 短信/邮件直达链接:确保 focus 对应明细出现在当前列表(便于高亮定位)
  2349. *
  2350. * @param array<string, mixed> $bundle
  2351. * @param array<string, mixed> $user
  2352. * @return array<string, mixed>
  2353. */
  2354. protected function mprocEnsureFocusRowInList(
  2355. array $bundle,
  2356. int $focusEid,
  2357. array $user,
  2358. $statusNameCol,
  2359. string $tab = 'draft',
  2360. string $q = ''
  2361. ): array {
  2362. if ($focusEid <= 0) {
  2363. return $bundle;
  2364. }
  2365. $rows = isset($bundle['rows']) && is_array($bundle['rows']) ? $bundle['rows'] : [];
  2366. $foundIdx = -1;
  2367. foreach ($rows as $idx => $r) {
  2368. if (!is_array($r)) {
  2369. continue;
  2370. }
  2371. if ((int)($r['eid'] ?? $r['id'] ?? $r['ID'] ?? 0) === $focusEid) {
  2372. $foundIdx = (int)$idx;
  2373. break;
  2374. }
  2375. }
  2376. if ($foundIdx > 0) {
  2377. $hit = $rows[$foundIdx];
  2378. array_splice($rows, $foundIdx, 1);
  2379. array_unshift($rows, $hit);
  2380. $bundle['rows'] = $rows;
  2381. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  2382. return $bundle;
  2383. }
  2384. if ($foundIdx === 0) {
  2385. return $bundle;
  2386. }
  2387. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2388. if ($idCol === null) {
  2389. return $bundle;
  2390. }
  2391. try {
  2392. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  2393. $qw = $this->mprocListWhereForLoginUser($user);
  2394. if ($qw !== []) {
  2395. $qrow->where($qw);
  2396. }
  2397. $dr = $qrow->find();
  2398. } catch (\Throwable $e) {
  2399. $dr = null;
  2400. }
  2401. if (!is_array($dr) || $dr === []) {
  2402. return $bundle;
  2403. }
  2404. $row = $dr;
  2405. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? $focusEid);
  2406. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2407. $poRow = null;
  2408. if ($this->mprocIsValidScydgyRowId($sid)) {
  2409. try {
  2410. $poRow = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2411. } catch (\Throwable $e) {
  2412. $poRow = null;
  2413. }
  2414. if (is_array($poRow)) {
  2415. $this->mprocMergePurchaseOrderIntoDetail($row, $poRow);
  2416. }
  2417. }
  2418. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($poRow) ? $poRow : null);
  2419. $rowTab = $this->mprocResolveListTabForRow($row, is_array($poRow) ? $poRow : null, $effectiveSn);
  2420. if ($rowTab !== '' && $rowTab !== $tab) {
  2421. return $bundle;
  2422. }
  2423. $row['status_name'] = $effectiveSn;
  2424. $listTab = $rowTab;
  2425. $row['mproc_list_tab'] = $listTab;
  2426. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  2427. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  2428. $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow(is_array($poRow) ? $poRow : null, $row) ? 1 : 0;
  2429. if ($row['mproc_pick_result'] !== '') {
  2430. $row['mproc_done_label'] = $row['mproc_pick_result'];
  2431. } elseif ($this->mprocIsDoneListTab($listTab) && (
  2432. (int)$row['mproc_deadline_reached'] === 1
  2433. || (int)$row['mproc_bid_open_verified'] === 1
  2434. )) {
  2435. $row['mproc_done_label'] = '已截止';
  2436. } else {
  2437. $row['mproc_done_label'] = '';
  2438. }
  2439. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  2440. $am = $row['amount'] ?? null;
  2441. $row['amount_display'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? '' : (is_scalar($am) ? (string)$am : '');
  2442. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2443. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  2444. $row['delivery_display'] = $m[1];
  2445. } elseif ($dv !== '') {
  2446. $row['delivery_display'] = $dv;
  2447. } else {
  2448. $row['delivery_display'] = '';
  2449. }
  2450. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  2451. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  2452. $this->mprocEnrichLeadDaysDisplay($row);
  2453. $this->mprocEnrichOrderDeadlineDisplay($row);
  2454. $row['mproc_fill_hint'] = '';
  2455. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  2456. array_unshift($rows, $row);
  2457. $bundle['rows'] = $rows;
  2458. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  2459. return $bundle;
  2460. }
  2461. /**
  2462. * 列表展示用「本次数量」:主表本次数量为空时回退显示 NGZL(工作量)
  2463. *
  2464. * @param array<string, mixed> $row
  2465. */
  2466. protected function mprocResolveDisplayThisQuantity(array $row): string
  2467. {
  2468. $qty = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  2469. if ($qty !== '') {
  2470. return $qty;
  2471. }
  2472. $gzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  2473. if ($gzl === null || $gzl === '') {
  2474. return '';
  2475. }
  2476. return is_scalar($gzl) ? trim((string)$gzl) : '';
  2477. }
  2478. /**
  2479. * 明细是否已填写单价或交货日期
  2480. *
  2481. * @param array<string, mixed> $row
  2482. */
  2483. protected function mprocDetailQuoteSubmitted(array $row): bool
  2484. {
  2485. $am = $row['amount'] ?? null;
  2486. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2487. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  2488. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  2489. return $amountFilled || $deliveryFilled;
  2490. }
  2491. /**
  2492. * 手机端列表 Tab 用 status_name;审批通过后主表 status=1 时按明细 status 纠偏
  2493. *
  2494. * @param array<string, mixed> $row
  2495. * @param array<string, mixed>|null $po
  2496. */
  2497. protected function mprocResolveEffectiveStatusName(array $row, ?array $po): string
  2498. {
  2499. $sn = trim((string)($row['status_name'] ?? ''));
  2500. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  2501. return $sn;
  2502. }
  2503. if (!is_array($po)) {
  2504. if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
  2505. return '已提交';
  2506. }
  2507. if ($sn !== '') {
  2508. return $sn;
  2509. }
  2510. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  2511. }
  2512. $poStatus = $po['status'] ?? $po['STATUS'] ?? '';
  2513. if (!ProcuremenStatus::isPoCompleted($poStatus)) {
  2514. // 库中仍写「未提交」但已填单价/交期:按已提交展示(手工单常见)
  2515. if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
  2516. return '已提交';
  2517. }
  2518. if ($sn !== '') {
  2519. return $sn;
  2520. }
  2521. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  2522. }
  2523. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  2524. if (ProcuremenStatus::isPodPicked($detailStatus)) {
  2525. return '已完成';
  2526. }
  2527. if ($sn === '已提交') {
  2528. return '未通过';
  2529. }
  2530. return $sn !== '' ? $sn : '未提交';
  2531. }
  2532. /**
  2533. * 将纠偏后的 status_name 写回库表(兼容历史已审批数据)
  2534. */
  2535. protected function mprocPersistDetailStatusName(int $detailId, string $statusNameCol, string $statusName): void
  2536. {
  2537. if ($detailId <= 0 || $statusNameCol === '') {
  2538. return;
  2539. }
  2540. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2541. if ($idCol === null || $idCol === '') {
  2542. return;
  2543. }
  2544. try {
  2545. Db::table('purchase_order_detail')->where($idCol, $detailId)->update([$statusNameCol => $statusName]);
  2546. } catch (\Throwable $e) {
  2547. }
  2548. }
  2549. /**
  2550. * 纠偏历史数据:主表已审批(status=1)但明细 status_name 仍为「已提交」
  2551. *
  2552. * @param array<string, mixed> $user
  2553. */
  2554. protected function mprocSyncLegacyApprovedStatusNames(array $user, string $statusNameCol): void
  2555. {
  2556. $userWhere = $this->mprocListWhereForLoginUser($user);
  2557. try {
  2558. $query = Db::table('purchase_order_detail')->where($statusNameCol, '已提交');
  2559. if ($userWhere !== []) {
  2560. $query->where($userWhere);
  2561. }
  2562. $candidates = $query->limit(200)->select();
  2563. } catch (\Throwable $e) {
  2564. return;
  2565. }
  2566. if (!is_array($candidates) || $candidates === []) {
  2567. return;
  2568. }
  2569. $sidList = [];
  2570. foreach ($candidates as $cr) {
  2571. if (!is_array($cr)) {
  2572. continue;
  2573. }
  2574. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  2575. if ($this->mprocIsValidScydgyRowId($sid)) {
  2576. $sidList[$sid] = true;
  2577. }
  2578. }
  2579. if ($sidList === []) {
  2580. return;
  2581. }
  2582. $poBySid = [];
  2583. try {
  2584. $poRows = Db::table('purchase_order')
  2585. ->where('scydgy_id', 'in', array_keys($sidList))
  2586. ->whereIn('status', ProcuremenStatus::poCompletedValues())
  2587. ->select();
  2588. if (is_array($poRows)) {
  2589. foreach ($poRows as $pr) {
  2590. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  2591. if ($this->mprocIsValidScydgyRowId($sidk)) {
  2592. $poBySid[$sidk] = $pr;
  2593. }
  2594. }
  2595. }
  2596. } catch (\Throwable $e) {
  2597. return;
  2598. }
  2599. if ($poBySid === []) {
  2600. return;
  2601. }
  2602. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2603. if ($idCol === null || $idCol === '') {
  2604. return;
  2605. }
  2606. foreach ($candidates as $cr) {
  2607. if (!is_array($cr)) {
  2608. continue;
  2609. }
  2610. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  2611. if (!isset($poBySid[$sid])) {
  2612. continue;
  2613. }
  2614. $detailId = (int)($cr[$idCol] ?? $cr['id'] ?? $cr['ID'] ?? 0);
  2615. if ($detailId <= 0) {
  2616. continue;
  2617. }
  2618. $targetSn = $this->mprocResolveEffectiveStatusName($cr, $poBySid[$sid]);
  2619. if ($targetSn === '已提交') {
  2620. continue;
  2621. }
  2622. $this->mprocPersistDetailStatusName($detailId, $statusNameCol, $targetSn);
  2623. }
  2624. }
  2625. /**
  2626. * 协助明细首页(需登录)
  2627. * GET:main_tab=orders|me,orders 时 tab=draft|submitted|done 对应 status_name:未提交|已提交|已完成;q 搜索词
  2628. */
  2629. public function index()
  2630. {
  2631. $user = $this->mprocGetUser();
  2632. if (!$user) {
  2633. $pendingFocus = $this->mprocReadFocusEidFromRequest();
  2634. if ($pendingFocus > 0) {
  2635. $this->mprocRememberFocusEid($pendingFocus);
  2636. }
  2637. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  2638. $safe = $this->mprocSanitizeRedirectUrl($uri);
  2639. if ($safe !== '' && $pendingFocus > 0 && stripos($safe, 'focus_eid') === false) {
  2640. $safe .= (strpos($safe, '?') !== false ? '&' : '?') . 'focus_eid=' . $pendingFocus;
  2641. }
  2642. if ($safe !== '') {
  2643. Session::set('mproc_intended_url', $safe);
  2644. }
  2645. $this->redirect($this->mprocBuildLoginUrl($safe));
  2646. return;
  2647. }
  2648. // 管理员进对应业务页,不进供应商报价列表
  2649. if (!empty($user['is_admin'])) {
  2650. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  2651. if ($jump === '') {
  2652. $this->mprocDropCurrentLogin();
  2653. $this->redirect(url('index/index/login'));
  2654. return;
  2655. }
  2656. $this->redirect($jump);
  2657. return;
  2658. }
  2659. $user = $this->mprocSyncSessionCustomerUser($user);
  2660. $tabParamRaw = $this->request->get('tab', null);
  2661. $hasExplicitTab = ($tabParamRaw !== null && trim((string)$tabParamRaw) !== '');
  2662. $tabParam = trim((string)($tabParamRaw ?? 'draft'));
  2663. $mainTab = trim((string)$this->request->get('main_tab', 'orders'));
  2664. // 旧地址 ?tab=me 表示「我的」
  2665. if ($tabParam === 'me') {
  2666. $mainTab = 'me';
  2667. }
  2668. if (!in_array($mainTab, ['orders', 'me'], true)) {
  2669. $mainTab = 'orders';
  2670. }
  2671. $tab = $tabParam === 'me' ? 'draft' : $this->mprocNormalizeListTab($tabParam);
  2672. $q = trim((string)$this->request->get('q', ''));
  2673. $mprocFocusEid = 0;
  2674. $focusEid = $this->mprocReadFocusEidFromRequest();
  2675. if ($focusEid > 0 && $mainTab === 'orders') {
  2676. $resolvedTab = $this->mprocResolveListTabForFocusEid($focusEid, $user);
  2677. // 用户已手动点了其他左侧 Tab:取消定位锁定,避免刷新又跳回
  2678. if ($hasExplicitTab && $resolvedTab !== '' && $resolvedTab !== $tab) {
  2679. Session::delete('mproc_focus_eid');
  2680. $focusEid = 0;
  2681. } else {
  2682. $mprocFocusEid = $focusEid;
  2683. // 仅邮件/短信直链且 URL 未带 tab 时,自动切到定位单所在 Tab
  2684. $focusFromUrl = (int)$this->request->param('focus_eid', 0) > 0;
  2685. if (!$focusFromUrl) {
  2686. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  2687. $focusFromUrl = $this->mprocParseFocusEidFromUriString($uri) > 0;
  2688. }
  2689. if ($focusFromUrl && trim((string)$q) === '' && !$hasExplicitTab) {
  2690. if ($resolvedTab !== '') {
  2691. $tab = $resolvedTab;
  2692. }
  2693. }
  2694. }
  2695. }
  2696. // 左侧 Tab 按 purchase_order_detail.status_name(未提交/已提交/已完成),与数值 status 无关
  2697. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2698. $profile = $this->mprocProfileForUser($user);
  2699. $this->view->assign('mprocMainTab', $mainTab);
  2700. $this->view->assign('mprocTab', $tab);
  2701. $this->view->assign('mprocIsRfqTab', $this->mprocIsRfqListTab($tab) ? 1 : 0);
  2702. $this->view->assign('mprocStatusTab', $this->mprocStatusFromListTab($tab));
  2703. $this->view->assign('mprocSearchQ', $q);
  2704. $this->view->assign('mprocProfile', $profile);
  2705. $this->view->assign('mprocIsAdmin', !empty($user['is_admin']) ? 1 : 0);
  2706. $cid = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  2707. $this->view->assign('mprocCanChangePwd', empty($user['is_admin']) && $cid > 0 ? 1 : 0);
  2708. $this->view->assign('mprocFocusEid', $mprocFocusEid);
  2709. $mprocFocusTab = $mprocFocusEid > 0 ? $this->mprocResolveListTabForFocusEid($mprocFocusEid, $user) : '';
  2710. $this->view->assign('mprocFocusTab', $mprocFocusTab);
  2711. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  2712. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  2713. if ($mainTab === 'me') {
  2714. $this->view->assign('rows', []);
  2715. return $this->view->fetch();
  2716. }
  2717. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  2718. if ($mprocFocusEid > 0) {
  2719. $bundle = $this->mprocEnsureFocusRowInList($bundle, $mprocFocusEid, $user, $statusNameCol, $tab, $q);
  2720. }
  2721. $this->view->assign('rows', $bundle['rows']);
  2722. $this->view->assign('groups', $bundle['groups'] ?? $this->mprocGroupRowsByOrder($bundle['rows']));
  2723. return $this->view->fetch();
  2724. }
  2725. /**
  2726. * 协助明细列表 JSON(需登录)
  2727. * main_tab=orders|me;orders 时 tab=draft|submitted|done、q=搜索词
  2728. */
  2729. public function mprocList()
  2730. {
  2731. $user = $this->mprocGetUser();
  2732. if (!$user) {
  2733. $this->error('请先登录', url('index/index/login'));
  2734. }
  2735. $user = $this->mprocSyncSessionCustomerUser($user);
  2736. $tabParam = trim((string)$this->request->request('tab', 'draft'));
  2737. $mainTab = trim((string)$this->request->request('main_tab', 'orders'));
  2738. if ($tabParam === 'me') {
  2739. $mainTab = 'me';
  2740. }
  2741. if (!in_array($mainTab, ['orders', 'me'], true)) {
  2742. $mainTab = 'orders';
  2743. }
  2744. $tab = $tabParam === 'me' ? 'draft' : $this->mprocNormalizeListTab($tabParam);
  2745. $q = trim((string)$this->request->request('q', ''));
  2746. if ($mainTab === 'me') {
  2747. // Jump::success($msg, $url, $data, …) 第二参是 URL,数据必须放第三参
  2748. $this->success('ok', '', [
  2749. 'main_tab' => 'me',
  2750. 'tab' => $tab,
  2751. 'rows' => [],
  2752. 'profile' => $this->mprocProfileForUser($user),
  2753. 'done_no_status' => 0,
  2754. ]);
  2755. }
  2756. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2757. if ((int)$this->request->request('clear_focus', 0) === 1) {
  2758. Session::delete('mproc_focus_eid');
  2759. $focusEid = 0;
  2760. $focusTab = '';
  2761. } else {
  2762. $focusEid = $this->mprocReadFocusEidFromRequest();
  2763. $focusTab = $focusEid > 0 ? $this->mprocResolveListTabForFocusEid($focusEid, $user) : '';
  2764. // 列表请求已指定 Tab,且与定位单所在 Tab 不同:视为用户离开锁定页
  2765. if ($focusEid > 0 && $focusTab !== '' && $focusTab !== $tab) {
  2766. Session::delete('mproc_focus_eid');
  2767. $focusEid = 0;
  2768. $focusTab = '';
  2769. }
  2770. }
  2771. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  2772. if ($focusEid > 0) {
  2773. $bundle = $this->mprocEnsureFocusRowInList($bundle, $focusEid, $user, $statusNameCol, $tab, $q);
  2774. }
  2775. $this->success('ok', '', array_merge([
  2776. 'main_tab' => 'orders',
  2777. 'tab' => $tab,
  2778. 'focus_tab' => $focusTab,
  2779. 'is_admin' => !empty($user['is_admin']) ? 1 : 0,
  2780. 'focus_eid' => $focusEid,
  2781. ], $bundle));
  2782. }
  2783. /**
  2784. * 登录页(手机号验证码 / 账号密码)
  2785. */
  2786. public function login()
  2787. {
  2788. $redirect = $this->mprocSanitizeRedirectUrl($this->request->get('redirect', ''));
  2789. $user = $this->mprocGetUser();
  2790. if ($user) {
  2791. $jump = $this->mprocBuildAfterLoginHomeUrl($user, $redirect);
  2792. if ($jump !== '') {
  2793. $this->redirect($jump);
  2794. return;
  2795. }
  2796. // 已登录但无手机端权限(其它后台账号):清会话,避免登录页↔自身 302 死循环
  2797. $this->mprocDropCurrentLogin();
  2798. }
  2799. if ($redirect !== '') {
  2800. Session::set('mproc_intended_url', $redirect);
  2801. }
  2802. $this->view->assign('mprocLoginRedirect', $redirect);
  2803. $this->view->assign('mprocCaptchaUrl', url('index/index/captcha'));
  2804. $this->view->assign('mprocCaptchaLen', (int)(Config::get('captcha.length') ?: 4));
  2805. return $this->view->fetch();
  2806. }
  2807. /**
  2808. * 图形验证码(手机号登录用)
  2809. */
  2810. public function captcha($id = '')
  2811. {
  2812. $captcha = new Captcha((array)Config::get('captcha'));
  2813. return $captcha->entry($id);
  2814. }
  2815. /**
  2816. * 发送登录验证码(POST:phone、captcha)
  2817. */
  2818. public function sendSms()
  2819. {
  2820. if (!$this->request->isPost()) {
  2821. $this->error('请使用 POST');
  2822. }
  2823. $phone = trim((string)$this->request->post('phone', ''));
  2824. $captcha = trim((string)$this->request->post('captcha', ''));
  2825. if (!preg_match('/^1\d{10}$/', $phone)) {
  2826. $this->error('请输入正确的11位手机号');
  2827. }
  2828. if ($captcha === '') {
  2829. $this->error('请输入图形验证码');
  2830. }
  2831. $cu = $this->mprocFindCustomerUserByMobile($phone);
  2832. $adminRow = $cu ? null : $this->mprocAdminRowByMobile($phone);
  2833. if (!$cu && !$adminRow) {
  2834. $this->error('账号或密码错误');
  2835. }
  2836. if ($adminRow) {
  2837. $probe = $this->mprocLoginPayloadFromAdmin($adminRow, 'sms');
  2838. if (!$this->mprocAdminHasAnyMobileAccess($probe)) {
  2839. $this->error('账号或密码错误');
  2840. }
  2841. }
  2842. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  2843. if (Cache::get('mproc_sms_wait_' . $phone)) {
  2844. $this->error('发送过于频繁,请稍后再试');
  2845. }
  2846. if (!Validate::is($captcha, 'captcha')) {
  2847. $this->error('图形验证码不正确');
  2848. }
  2849. $code = (string)random_int(100000, 999999);
  2850. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  2851. $ttl = max(60, min(600, $ttl));
  2852. Cache::set('mproc_code_' . $phone, $code, $ttl);
  2853. Cache::set('mproc_sms_wait_' . $phone, 1, $cd);
  2854. try {
  2855. $tpl = trim((string)Config::get('mproc.sms_login_template'));
  2856. if ($tpl === '') {
  2857. $tpl = '【可集达】您的验证码是{code}。如非本人操作,请忽略本短信';
  2858. }
  2859. $content = str_replace('{code}', $code, $tpl);
  2860. $this->mprocSmsSend($phone, $content);
  2861. } catch (\Exception $e) {
  2862. Cache::rm('mproc_code_' . $phone);
  2863. Cache::rm('mproc_sms_wait_' . $phone);
  2864. $this->error($e->getMessage());
  2865. }
  2866. $this->success('验证码已发送');
  2867. }
  2868. /**
  2869. * 验证码登录(POST:phone、code)
  2870. */
  2871. public function doLogin()
  2872. {
  2873. if (!$this->request->isPost()) {
  2874. $this->error('请使用 POST');
  2875. }
  2876. $phone = trim((string)$this->request->post('phone', ''));
  2877. $code = trim((string)$this->request->post('code', ''));
  2878. if (!preg_match('/^1\d{10}$/', $phone)) {
  2879. $this->error('手机号格式不正确');
  2880. }
  2881. if (!preg_match('/^\d{6}$/', $code)) {
  2882. $this->error('请输入6位验证码');
  2883. }
  2884. // 本地调试:application/extra/mproc.php 中配置 mock_sms_code 与输入一致时,不校验短信缓存(生产务必留空)
  2885. $mock = Config::get('mproc.mock_sms_code');
  2886. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2887. Cache::rm('mproc_code_' . $phone);
  2888. } else {
  2889. $cached = Cache::get('mproc_code_' . $phone);
  2890. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2891. $this->error('验证码错误或已过期');
  2892. }
  2893. Cache::rm('mproc_code_' . $phone);
  2894. }
  2895. $cu = $this->mprocFindCustomerUserByMobile($phone);
  2896. if ($cu) {
  2897. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'sms'));
  2898. return;
  2899. }
  2900. $adminRow = $this->mprocAdminRowByMobile($phone);
  2901. if ($adminRow) {
  2902. $payload = $this->mprocLoginPayloadFromAdmin($adminRow, 'sms');
  2903. if (!$this->mprocAdminHasAnyMobileAccess($payload)) {
  2904. $this->error('账号或密码错误');
  2905. }
  2906. $this->mprocFinishLogin($payload);
  2907. return;
  2908. }
  2909. $this->error('账号或密码错误');
  2910. }
  2911. /**
  2912. * 用本地保存的 token 恢复登录态(POST:mproc_token)
  2913. */
  2914. public function mprocRestore()
  2915. {
  2916. if (!$this->request->isPost()) {
  2917. $this->error('请使用 POST');
  2918. }
  2919. $token = $this->mprocReadTokenFromRequest();
  2920. $user = null;
  2921. if ($token !== '') {
  2922. $user = $this->mprocLoadUserByToken($token);
  2923. }
  2924. if (!$user) {
  2925. $user = $this->mprocUserFromRememberCookie();
  2926. if ($user) {
  2927. $token = $this->mprocPackSignedAuthToken($user);
  2928. }
  2929. }
  2930. if (!$user) {
  2931. $this->error('登录已过期,请重新登录', url('index/index/login'));
  2932. }
  2933. $token = $this->mprocTouchLoginState($user, $token !== '' ? $token : $this->mprocPackSignedAuthToken($user));
  2934. $redirect = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  2935. $jump = $this->mprocBuildAfterLoginHomeUrl($user, $redirect);
  2936. if ($jump === '') {
  2937. $this->mprocClearLogin($token);
  2938. $this->error('账号或密码错误', url('index/index/login'));
  2939. }
  2940. $this->success('ok', $jump, [
  2941. 'mproc_token' => $token,
  2942. 'keep_hours' => $this->mprocKeepHours(),
  2943. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  2944. ]);
  2945. }
  2946. /**
  2947. * 账号密码登录(POST:username、password)
  2948. * 先 customer(account),未命中再 admin;admin 密码规则同 FastAdmin Auth::login
  2949. */
  2950. public function doLoginPwd()
  2951. {
  2952. if (!$this->request->isPost()) {
  2953. $this->error('请使用 POST');
  2954. }
  2955. $username = trim((string)$this->request->post('username', ''));
  2956. $password = (string)$this->request->post('password', '');
  2957. if ($username === '' || $password === '') {
  2958. $this->error('请输入账号和密码');
  2959. }
  2960. $cu = $this->mprocFindCustomerUserByUsername($username);
  2961. if ($cu) {
  2962. if (!$this->mprocVerifyCustomerUserPassword($cu, $password)) {
  2963. $this->error('账号或密码错误');
  2964. }
  2965. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'pwd'));
  2966. }
  2967. // 管理员:表 admin
  2968. $row = null;
  2969. try {
  2970. $row = Db::name('admin')
  2971. ->field('id,username,password,salt,status,loginfailure,updatetime,mobile')
  2972. ->where('username', $username)
  2973. ->find();
  2974. } catch (\Throwable $e) {
  2975. $row = null;
  2976. }
  2977. if (!$row || !is_array($row)) {
  2978. $this->error('账号或密码错误');
  2979. }
  2980. $id = (int)($row['id'] ?? 0);
  2981. if (($row['status'] ?? '') == 'hidden') {
  2982. $this->error('该账号已禁用');
  2983. }
  2984. if (Config::get('fastadmin.login_failure_retry') && (int)($row['loginfailure'] ?? 0) >= 10 && time() - (int)($row['updatetime'] ?? 0) < 86400) {
  2985. $this->error('登录失败次数过多,请24小时后再试');
  2986. }
  2987. $salt = (string)($row['salt'] ?? '');
  2988. $hashStored = (string)($row['password'] ?? '');
  2989. $hashInput = md5(md5($password) . $salt);
  2990. if ($hashStored === '' || $hashInput !== $hashStored) {
  2991. if ($id > 0) {
  2992. try {
  2993. Db::name('admin')->where('id', $id)->update([
  2994. 'loginfailure' => (int)($row['loginfailure'] ?? 0) + 1,
  2995. 'updatetime' => time(),
  2996. ]);
  2997. } catch (\Throwable $e) {
  2998. }
  2999. }
  3000. $this->error('账号或密码错误');
  3001. }
  3002. if ($id > 0) {
  3003. try {
  3004. Db::name('admin')->where('id', $id)->update([
  3005. 'loginfailure' => 0,
  3006. 'updatetime' => time(),
  3007. ]);
  3008. } catch (\Throwable $e) {
  3009. }
  3010. }
  3011. $payload = $this->mprocLoginPayloadFromAdmin($row, 'pwd');
  3012. if (!$this->mprocAdminHasAnyMobileAccess($payload)) {
  3013. $this->error('账号或密码错误');
  3014. }
  3015. $this->mprocFinishLogin($payload);
  3016. }
  3017. /**
  3018. * 是否允许当前登录用户修改该条 purchase_order_detail 的金额、交期
  3019. * 仅普通用户(customer)可改;管理员(admin)仅可查看
  3020. */
  3021. protected function mprocCanEditRow(array $user, array $row, ?array $po = null)
  3022. {
  3023. if (!empty($user['is_admin'])) {
  3024. return false;
  3025. }
  3026. $sn = trim((string)($row['status_name'] ?? ''));
  3027. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  3028. return false;
  3029. }
  3030. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3031. // 手工询价无招标截止/开标限制
  3032. if ($sid >= 0) {
  3033. if ($this->mprocIsQuoteDeadlineReachedForPo($po)) {
  3034. return false;
  3035. }
  3036. if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)) {
  3037. return false;
  3038. }
  3039. }
  3040. $uCo = trim((string)($user['company_name'] ?? ''));
  3041. if ($uCo === '') {
  3042. $uPhone = trim((string)($user['phone'] ?? ''));
  3043. if ($uPhone !== '') {
  3044. $uCo = $this->mprocResolveCompanyForLoginPhone($uPhone);
  3045. }
  3046. }
  3047. $rCo = trim((string)($row['company_name'] ?? ''));
  3048. if ($uCo !== '' && $rCo !== '' && strcmp($rCo, $uCo) === 0) {
  3049. return true;
  3050. }
  3051. $uPhone = trim((string)($user['phone'] ?? ''));
  3052. $rPhone = trim((string)($row['phone'] ?? ''));
  3053. return $uPhone !== '' && $rPhone !== '' && strcasecmp($rPhone, $uPhone) === 0;
  3054. }
  3055. /**
  3056. * 明细行对应最高限价(来自 purchase_order;无或无效则返回 null,不校验)
  3057. *
  3058. * @param array<string, mixed> $detailRow
  3059. */
  3060. protected function mprocResolveCeilingPriceForDetailRow(array $detailRow): ?float
  3061. {
  3062. $sid = (int)($detailRow['scydgy_id'] ?? $detailRow['SCYDGY_ID'] ?? 0);
  3063. $raw = trim((string)($detailRow['ceilingPrice'] ?? $detailRow['ceiling_price'] ?? ''));
  3064. if ($raw === '' && $this->mprocIsValidScydgyRowId($sid)) {
  3065. try {
  3066. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3067. } catch (\Throwable $e) {
  3068. $po = null;
  3069. }
  3070. if (is_array($po)) {
  3071. $pl = array_change_key_case($po, CASE_LOWER);
  3072. foreach (['ceilingprice', 'ceiling_price'] as $ck) {
  3073. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  3074. $raw = trim((string)$pl[$ck]);
  3075. break;
  3076. }
  3077. }
  3078. if ($raw === '') {
  3079. $raw = trim((string)($po['ceilingPrice'] ?? $po['ceiling_price'] ?? ''));
  3080. }
  3081. }
  3082. }
  3083. if ($raw === '' || !preg_match('/^-?\d+(\.\d{1,5})?$/', $raw)) {
  3084. return null;
  3085. }
  3086. return (float)$raw;
  3087. }
  3088. protected function mprocFormatCeilingPriceDisplay(float $n): string
  3089. {
  3090. $s = rtrim(rtrim(sprintf('%.5F', $n), '0'), '.');
  3091. return $s === '' ? '0' : $s;
  3092. }
  3093. /**
  3094. * 确保 purchase_order_detail.lead_days 字段存在
  3095. */
  3096. protected function mprocEnsureLeadDaysColumn(): void
  3097. {
  3098. static $done = false;
  3099. if ($done) {
  3100. return;
  3101. }
  3102. $done = true;
  3103. try {
  3104. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_detail` LIKE 'lead_days'");
  3105. if (empty($cols)) {
  3106. Db::execute(
  3107. "ALTER TABLE `purchase_order_detail` ADD COLUMN `lead_days` int(10) unsigned DEFAULT NULL COMMENT '预估工期(天)' AFTER `delivery`"
  3108. );
  3109. }
  3110. } catch (\Throwable $e) {
  3111. // 忽略:保存时再按列是否存在处理
  3112. }
  3113. }
  3114. /**
  3115. * 交货日期相对今天的天数(可负数,调用方自行 clamp)
  3116. */
  3117. protected function mprocCalcLeadDaysFromDeliveryYmd(string $ymd): ?int
  3118. {
  3119. if (!preg_match('/^(\d{4}-\d{2}-\d{2})/', $ymd, $m)) {
  3120. return null;
  3121. }
  3122. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  3123. $t2 = strtotime($m[1] . ' 00:00:00');
  3124. if ($t1 === false || $t2 === false) {
  3125. return null;
  3126. }
  3127. return (int)round(($t2 - $t1) / 86400);
  3128. }
  3129. protected function mprocAddDaysToToday(int $days): string
  3130. {
  3131. $base = strtotime(date('Y-m-d') . ' 00:00:00');
  3132. if ($base === false) {
  3133. $base = time();
  3134. }
  3135. return date('Y-m-d', strtotime('+' . max(0, $days) . ' days', $base));
  3136. }
  3137. /**
  3138. * @param array<string, mixed> $row
  3139. */
  3140. protected function mprocEnrichLeadDaysDisplay(array &$row): void
  3141. {
  3142. $days = null;
  3143. $raw = $row['lead_days'] ?? null;
  3144. if ($raw !== null && $raw !== '' && is_numeric($raw)) {
  3145. $days = max(0, (int)$raw);
  3146. } else {
  3147. $dd = trim((string)($row['delivery_display'] ?? ''));
  3148. if ($dd === '') {
  3149. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  3150. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  3151. $dd = $m[1];
  3152. }
  3153. }
  3154. if ($dd !== '') {
  3155. $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($dd);
  3156. if ($calc !== null) {
  3157. $days = max(0, $calc);
  3158. }
  3159. }
  3160. }
  3161. if ($days !== null) {
  3162. $row['lead_days'] = $days;
  3163. $row['lead_days_display'] = (string)$days;
  3164. $row['lead_days_missing'] = 0;
  3165. } else {
  3166. $row['lead_days'] = '';
  3167. $row['lead_days_display'] = '';
  3168. $row['lead_days_missing'] = 1;
  3169. }
  3170. }
  3171. /**
  3172. * 保存单条协助明细的金额、交期、工期(内部)
  3173. *
  3174. * @param array<string, mixed> $user
  3175. * @param int $id
  3176. * @param string $amountRaw
  3177. * @param string $deliveryRaw
  3178. * @param string|int|null $leadDaysRaw
  3179. * @return string 工序名(用于批量错误提示)
  3180. */
  3181. protected function mprocSaveDetailQuote(array $user, int $id, string $amountRaw, string $deliveryRaw, $leadDaysRaw = null): string
  3182. {
  3183. if ($id <= 0) {
  3184. throw new \InvalidArgumentException('参数错误');
  3185. }
  3186. $row = null;
  3187. try {
  3188. $row = Db::table('purchase_order_detail')->where('id', $id)->find();
  3189. if (!$row) {
  3190. $row = Db::table('purchase_order_detail')->where('ID', $id)->find();
  3191. }
  3192. } catch (\Throwable $e) {
  3193. $row = null;
  3194. }
  3195. if (!$row || !is_array($row)) {
  3196. throw new \InvalidArgumentException('记录不存在');
  3197. }
  3198. $gymc = trim((string)($row['CGYMC'] ?? $row['cgymc'] ?? ''));
  3199. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3200. $po = null;
  3201. if ($this->mprocIsValidScydgyRowId($sid)) {
  3202. try {
  3203. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3204. } catch (\Throwable $e) {
  3205. $po = null;
  3206. }
  3207. if (is_array($po)) {
  3208. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  3209. if ($gymc === '') {
  3210. $gymc = trim((string)($row['CGYMC'] ?? ''));
  3211. }
  3212. }
  3213. }
  3214. $label = $gymc !== '' ? ('工序「' . $gymc . '」') : ('记录#' . $id);
  3215. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  3216. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  3217. throw new \InvalidArgumentException($label . '已结束,不能再修改');
  3218. }
  3219. $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, $label, $row);
  3220. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  3221. if (!empty($user['is_admin'])) {
  3222. throw new \InvalidArgumentException('当前账号仅可查看,不能修改单价与交货日期');
  3223. }
  3224. // 截止后 / 已开标 canEdit=false,统一给明确文案
  3225. if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
  3226. throw new \InvalidArgumentException($label . '已开标验证,不可再提交');
  3227. }
  3228. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  3229. throw new \InvalidArgumentException($label . '已超过招标截止时间,不可再提交');
  3230. }
  3231. throw new \InvalidArgumentException($label . '无权修改');
  3232. }
  3233. $this->mprocEnsureLeadDaysColumn();
  3234. $amountRaw = trim($amountRaw);
  3235. $deliveryRaw = trim($deliveryRaw);
  3236. $leadRaw = trim((string)($leadDaysRaw ?? ''));
  3237. $hasAmt = $amountRaw !== '';
  3238. $hasLead = $leadRaw !== '';
  3239. $hasDel = $deliveryRaw !== '';
  3240. $isManualRfq = ($sid < 0);
  3241. if ($isManualRfq) {
  3242. // 手工询价:只需填写单价
  3243. if (!$hasAmt) {
  3244. throw new \InvalidArgumentException($label . '请填写单价');
  3245. }
  3246. } else {
  3247. $filledCount = ($hasAmt ? 1 : 0) + ($hasLead ? 1 : 0) + ($hasDel ? 1 : 0);
  3248. if ($filledCount === 0) {
  3249. throw new \InvalidArgumentException($label . '请填写单价、工期、交期');
  3250. }
  3251. if ($filledCount < 3) {
  3252. if (!$hasAmt) {
  3253. throw new \InvalidArgumentException($label . '请填写单价');
  3254. }
  3255. if (!$hasLead) {
  3256. throw new \InvalidArgumentException($label . '请填写工期');
  3257. }
  3258. throw new \InvalidArgumentException($label . '请填写交期');
  3259. }
  3260. }
  3261. $leadDays = null;
  3262. if ($leadRaw !== '') {
  3263. if (!preg_match('/^\d+$/', $leadRaw)) {
  3264. throw new \InvalidArgumentException($label . '工期须为非负整数(天)');
  3265. }
  3266. $leadDays = (int)$leadRaw;
  3267. }
  3268. $data = [];
  3269. if ($amountRaw === '') {
  3270. $data['amount'] = null;
  3271. } else {
  3272. if (!preg_match('/^\d+(\.\d{1,5})?$/', $amountRaw)) {
  3273. throw new \InvalidArgumentException($label . '单价格式不正确,最多五位小数');
  3274. }
  3275. if ((float)$amountRaw <= 0) {
  3276. throw new \InvalidArgumentException($label . '单价必须大于0');
  3277. }
  3278. $ceilingLimit = $this->mprocResolveCeilingPriceForDetailRow($row);
  3279. if ($ceilingLimit !== null && (float)$amountRaw > $ceilingLimit) {
  3280. throw new \InvalidArgumentException(
  3281. $label . '单价不能超过最高限价 ' . $this->mprocFormatCeilingPriceDisplay($ceilingLimit)
  3282. );
  3283. }
  3284. $data['amount'] = $amountRaw;
  3285. }
  3286. if ($deliveryRaw === '') {
  3287. $data['delivery'] = null;
  3288. } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryRaw)) {
  3289. $existingDel = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  3290. $timePart = date('H:i:s');
  3291. if ($existingDel !== '') {
  3292. $tsEx = strtotime(str_replace('T', ' ', $existingDel));
  3293. if ($tsEx !== false) {
  3294. $hms = date('H:i:s', $tsEx);
  3295. if ($hms !== '00:00:00') {
  3296. $timePart = $hms;
  3297. }
  3298. }
  3299. }
  3300. $data['delivery'] = $deliveryRaw . ' ' . $timePart;
  3301. } else {
  3302. $deliveryRaw = str_replace('T', ' ', $deliveryRaw);
  3303. $ts = strtotime($deliveryRaw);
  3304. if ($ts === false) {
  3305. throw new \InvalidArgumentException($label . '交期时间格式不正确');
  3306. }
  3307. $data['delivery'] = date('Y-m-d H:i:s', $ts);
  3308. }
  3309. // 工期 ↔ 交货日期互通:仅填工期则推交期;仅填交期则推工期
  3310. if (($data['delivery'] === null || $data['delivery'] === '') && $leadDays !== null) {
  3311. $data['delivery'] = $this->mprocAddDaysToToday($leadDays) . ' ' . date('H:i:s');
  3312. }
  3313. if ($leadDays === null && !empty($data['delivery'])) {
  3314. $ymd = substr((string)$data['delivery'], 0, 10);
  3315. $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($ymd);
  3316. if ($calc !== null) {
  3317. $leadDays = max(0, $calc);
  3318. }
  3319. }
  3320. $data['lead_days'] = $leadDays;
  3321. $dcCol = $this->mprocResolveProcuremenColumn(['delivery_createtime', 'deliverycreatetime']);
  3322. if ($dcCol !== null) {
  3323. $shouldStampQuoteTime = false;
  3324. if (array_key_exists('delivery', $data) && $data['delivery'] !== null && $data['delivery'] !== '') {
  3325. $shouldStampQuoteTime = true;
  3326. }
  3327. // 手工询价只填单价:有单价也记报价时间
  3328. if ($isManualRfq && array_key_exists('amount', $data) && $data['amount'] !== null && $data['amount'] !== '') {
  3329. $shouldStampQuoteTime = true;
  3330. }
  3331. if ($shouldStampQuoteTime) {
  3332. $data[$dcCol] = date('Y-m-d H:i:s');
  3333. }
  3334. }
  3335. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3336. if ($upCol !== null) {
  3337. $data[$upCol] = date('Y-m-d H:i:s');
  3338. }
  3339. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  3340. if ($statusNameCol !== null) {
  3341. $curSn = '';
  3342. foreach ($row as $k => $v) {
  3343. if (strcasecmp((string)$k, $statusNameCol) === 0) {
  3344. $curSn = trim((string)$v);
  3345. break;
  3346. }
  3347. }
  3348. if ($curSn !== '已完成') {
  3349. $effAm = array_key_exists('amount', $data) ? $data['amount'] : ($row['amount'] ?? null);
  3350. $effDv = array_key_exists('delivery', $data) ? trim((string)$data['delivery']) : trim((string)($row['delivery'] ?? ''));
  3351. $amountFilled = !($effAm === null || $effAm === '' || (is_string($effAm) && trim($effAm) === ''));
  3352. $deliveryFilled = ($effDv !== '' && !preg_match('/^0000-00-00/i', $effDv));
  3353. $data[$statusNameCol] = ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3354. }
  3355. }
  3356. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  3357. $pkVal = (int)($row[$pkField] ?? $id);
  3358. try {
  3359. $aff = Db::table('purchase_order_detail')->where($pkField, $pkVal)->update($data);
  3360. } catch (\Throwable $e) {
  3361. $msg = $e->getMessage();
  3362. if (stripos($msg, 'Unknown column') !== false) {
  3363. $msg = '请确认数据表 purchase_order_detail 已包含 amount、delivery、lead_days 字段';
  3364. }
  3365. throw new \RuntimeException('保存失败:' . $msg);
  3366. }
  3367. if ($aff === false) {
  3368. throw new \RuntimeException($label . '保存失败');
  3369. }
  3370. return $gymc;
  3371. }
  3372. /**
  3373. * 保存同订单号+供应商下的整单备注(写入该组全部明细行)
  3374. *
  3375. * @param array<string, mixed> $user
  3376. * @param int[] $detailIds 本次保存涉及的明细 ID
  3377. * @param string $remarkRaw
  3378. */
  3379. protected function mprocSaveOrderGroupRemark(array $user, array $detailIds, string $remarkRaw): void
  3380. {
  3381. $remarkCol = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
  3382. if ($remarkCol === null) {
  3383. return;
  3384. }
  3385. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3386. if ($detailIds === []) {
  3387. return;
  3388. }
  3389. $anchorId = $detailIds[0];
  3390. $row = null;
  3391. try {
  3392. $row = Db::table('purchase_order_detail')->where('id', $anchorId)->find();
  3393. if (!$row) {
  3394. $row = Db::table('purchase_order_detail')->where('ID', $anchorId)->find();
  3395. }
  3396. } catch (\Throwable $e) {
  3397. $row = null;
  3398. }
  3399. if (!$row || !is_array($row)) {
  3400. throw new \InvalidArgumentException('记录不存在');
  3401. }
  3402. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3403. $po = null;
  3404. if ($this->mprocIsValidScydgyRowId($sid)) {
  3405. try {
  3406. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3407. } catch (\Throwable $e) {
  3408. $po = null;
  3409. }
  3410. if (is_array($po)) {
  3411. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  3412. }
  3413. }
  3414. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  3415. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  3416. throw new \InvalidArgumentException('订单已结束,不能再修改备注');
  3417. }
  3418. $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, '', $row);
  3419. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  3420. if (!empty($user['is_admin'])) {
  3421. throw new \InvalidArgumentException('当前账号仅可查看,不能修改备注');
  3422. }
  3423. if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
  3424. throw new \InvalidArgumentException('已开标验证,不可再提交');
  3425. }
  3426. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  3427. throw new \InvalidArgumentException('已超过招标截止时间,不可再提交');
  3428. }
  3429. throw new \InvalidArgumentException('无权修改备注');
  3430. }
  3431. $ccydhCol = $this->mprocResolveProcuremenColumn(['ccydh']);
  3432. $companyCol = $this->mprocResolveProcuremenColumn(['company_name']);
  3433. if ($ccydhCol === null || $companyCol === null) {
  3434. return;
  3435. }
  3436. $ccydh = '';
  3437. $company = '';
  3438. foreach ($row as $k => $v) {
  3439. if (strcasecmp((string)$k, $ccydhCol) === 0) {
  3440. $ccydh = trim((string)$v);
  3441. } elseif (strcasecmp((string)$k, $companyCol) === 0) {
  3442. $company = trim((string)$v);
  3443. }
  3444. }
  3445. if ($ccydh === '' || $company === '') {
  3446. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  3447. $data = [$remarkCol => ($remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8'))];
  3448. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3449. if ($upCol !== null) {
  3450. $data[$upCol] = date('Y-m-d H:i:s');
  3451. }
  3452. Db::table('purchase_order_detail')->where($pkField, (int)($row[$pkField] ?? $anchorId))->update($data);
  3453. return;
  3454. }
  3455. $remarkVal = $remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8');
  3456. $data = [$remarkCol => $remarkVal];
  3457. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3458. if ($upCol !== null) {
  3459. $data[$upCol] = date('Y-m-d H:i:s');
  3460. }
  3461. $query = Db::table('purchase_order_detail')
  3462. ->where($ccydhCol, $ccydh)
  3463. ->where($companyCol, $company);
  3464. $userWhere = $this->mprocListWhereForLoginUser($user);
  3465. if ($userWhere !== []) {
  3466. $query->where($userWhere);
  3467. }
  3468. try {
  3469. $query->update($data);
  3470. } catch (\Throwable $e) {
  3471. throw new \RuntimeException('备注保存失败:' . $e->getMessage());
  3472. }
  3473. }
  3474. /**
  3475. * 保存协助明细金额、交期、工期
  3476. * 单条:POST id、amount、delivery、lead_days
  3477. * 批量:POST items=[{id,amount,delivery,lead_days},...] JSON
  3478. */
  3479. public function mprocSave()
  3480. {
  3481. if (!$this->request->isPost()) {
  3482. $this->error('请使用 POST');
  3483. }
  3484. $user = $this->mprocGetUser();
  3485. if (!$user) {
  3486. $this->error('请先登录', url('index/index/login'));
  3487. }
  3488. // Frontend 默认 filter 含 htmlspecialchars,会把 JSON 的双引号变成 &quot; 导致解析失败
  3489. $itemsRaw = $this->request->post('items', '', null);
  3490. if ($itemsRaw === '' || $itemsRaw === null) {
  3491. $itemsRaw = isset($_POST['items']) ? $_POST['items'] : '';
  3492. }
  3493. if (is_string($itemsRaw) && $itemsRaw !== '' && strpos($itemsRaw, '&quot;') !== false) {
  3494. $itemsRaw = htmlspecialchars_decode($itemsRaw, ENT_QUOTES);
  3495. }
  3496. $items = [];
  3497. if (is_string($itemsRaw) && trim($itemsRaw) !== '') {
  3498. $decoded = json_decode($itemsRaw, true);
  3499. if (!is_array($decoded)) {
  3500. $decoded = json_decode(htmlspecialchars_decode($itemsRaw, ENT_QUOTES), true);
  3501. }
  3502. if (is_array($decoded)) {
  3503. $items = $decoded;
  3504. }
  3505. } elseif (is_array($itemsRaw)) {
  3506. $items = $itemsRaw;
  3507. }
  3508. if ($items === []) {
  3509. $id = (int)$this->request->post('id', 0, null);
  3510. if ($id <= 0) {
  3511. $this->error('保存失败,请关闭弹窗后重试');
  3512. }
  3513. $items = [[
  3514. 'id' => $id,
  3515. 'amount' => (string)$this->request->post('amount', '', null),
  3516. 'delivery' => (string)$this->request->post('delivery', '', null),
  3517. 'lead_days' => (string)$this->request->post('lead_days', '', null),
  3518. ]];
  3519. }
  3520. $saved = 0;
  3521. $savedIds = [];
  3522. $remarkRaw = $this->request->post('remark', '', null);
  3523. if ($remarkRaw === '' || $remarkRaw === null) {
  3524. $remarkRaw = isset($_POST['remark']) ? $_POST['remark'] : '';
  3525. }
  3526. $remarkRaw = trim(htmlspecialchars_decode((string)$remarkRaw, ENT_QUOTES));
  3527. Db::startTrans();
  3528. try {
  3529. foreach ($items as $it) {
  3530. if (!is_array($it)) {
  3531. continue;
  3532. }
  3533. $id = (int)($it['id'] ?? $it['eid'] ?? 0);
  3534. if ($id <= 0) {
  3535. continue;
  3536. }
  3537. $delivery = (string)($it['delivery'] ?? '');
  3538. // 兼容部分手机浏览器把日期显示/提交成 2026/07/24
  3539. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})$/', trim($delivery), $dm)) {
  3540. $delivery = sprintf('%04d-%02d-%02d', (int)$dm[1], (int)$dm[2], (int)$dm[3]);
  3541. }
  3542. $leadDays = (string)($it['lead_days'] ?? $it['leadDays'] ?? '');
  3543. $amount = trim((string)($it['amount'] ?? ''));
  3544. $leadDays = trim($leadDays);
  3545. $delivery = trim($delivery);
  3546. // 全空工序跳过:多工序时允许只保存已填全的
  3547. if ($amount === '' && $leadDays === '' && $delivery === '') {
  3548. continue;
  3549. }
  3550. $this->mprocSaveDetailQuote(
  3551. $user,
  3552. $id,
  3553. $amount,
  3554. $delivery,
  3555. $leadDays
  3556. );
  3557. $saved++;
  3558. $savedIds[] = $id;
  3559. }
  3560. if ($saved < 1) {
  3561. throw new \InvalidArgumentException('请填写单价、工期、交期');
  3562. }
  3563. $this->mprocSaveOrderGroupRemark($user, $savedIds, $remarkRaw);
  3564. Db::commit();
  3565. } catch (\InvalidArgumentException $e) {
  3566. Db::rollback();
  3567. $this->error($e->getMessage());
  3568. } catch (\Throwable $e) {
  3569. Db::rollback();
  3570. $this->error($e->getMessage());
  3571. }
  3572. $this->success($saved > 1 ? ('已保存 ' . $saved . ' 道工序') : '已保存');
  3573. }
  3574. /**
  3575. * 普通用户修改密码(POST:old_password、new_password、renew_password)
  3576. */
  3577. public function mprocChangePwd()
  3578. {
  3579. if (!$this->request->isPost()) {
  3580. $this->error('请使用 POST');
  3581. }
  3582. $user = $this->mprocGetUser();
  3583. if (!$user) {
  3584. $this->error('请先登录', url('index/index/login'));
  3585. }
  3586. $user = $this->mprocSyncSessionCustomerUser($user);
  3587. if (!empty($user['is_admin'])) {
  3588. $this->error('当前账号不支持修改密码');
  3589. }
  3590. $cu = $this->mprocResolveCustomerUserForSession($user);
  3591. if (!$cu) {
  3592. $this->error('账号不存在或已禁用');
  3593. }
  3594. $oldPwd = (string)$this->request->post('old_password', '');
  3595. $newPwd = (string)$this->request->post('new_password', '');
  3596. $renewPwd = (string)$this->request->post('renew_password', '');
  3597. if ($oldPwd === '' || $newPwd === '' || $renewPwd === '') {
  3598. $this->error('请填写完整');
  3599. }
  3600. $pwdErr = $this->mprocValidateStrongPassword($newPwd);
  3601. if ($pwdErr !== '') {
  3602. $this->error($pwdErr);
  3603. }
  3604. if ($newPwd !== $renewPwd) {
  3605. $this->error('两次输入的新密码不一致');
  3606. }
  3607. if ($oldPwd === $newPwd) {
  3608. $this->error('新密码不能与旧密码相同');
  3609. }
  3610. $cuId = (int)($cu['id'] ?? 0);
  3611. if (!$this->mprocVerifyCustomerUserPassword($cu, $oldPwd)) {
  3612. $this->error('原密码不正确');
  3613. }
  3614. $data = [
  3615. 'password' => $this->mprocHashCustomerUserPassword($newPwd),
  3616. 'updatetime' => date('Y-m-d H:i:s'),
  3617. ];
  3618. try {
  3619. Db::table('customer')->where('id', $cuId)->update($data);
  3620. } catch (\Throwable $e) {
  3621. $this->error('修改失败:' . $e->getMessage());
  3622. }
  3623. // 改密后强制重新登录
  3624. $token = Session::get('mproc_token');
  3625. if ($token === null || $token === '') {
  3626. $token = Cookie::get('mproc_token');
  3627. }
  3628. if ($token === null || $token === '') {
  3629. $token = Cookie::get('mproc_remember');
  3630. }
  3631. $this->mprocClearLogin((string)$token);
  3632. $this->success('密码已修改,请重新登录', url('index/index/login'));
  3633. }
  3634. /**
  3635. * 退出登录
  3636. */
  3637. public function logout()
  3638. {
  3639. $token = Session::get('mproc_token');
  3640. if ($token === null || $token === '') {
  3641. $token = Cookie::get('mproc_token');
  3642. }
  3643. if ($token === null || $token === '') {
  3644. $token = Cookie::get('mproc_remember');
  3645. }
  3646. // 无论有无 token 都清 Cookie/Session,避免「记住登录」把用户又带回来
  3647. $this->mprocClearLogin((string)$token);
  3648. $this->redirect(url('index/index/login'));
  3649. }
  3650. /**
  3651. * 短信宝(与后台协助审核一致,便于复用账号)
  3652. *
  3653. * @throws \Exception
  3654. */
  3655. protected function mprocSmsSend($phone, $content)
  3656. {
  3657. $statusStr = [
  3658. '0' => '短信发送成功',
  3659. '-1' => '参数不全',
  3660. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  3661. '30' => '密码错误',
  3662. '40' => '账号不存在',
  3663. '41' => '余额不足',
  3664. '42' => '帐户已过期',
  3665. '43' => 'IP地址限制',
  3666. '50' => '内容含有敏感词',
  3667. ];
  3668. $smsapi = 'http://api.smsbao.com/';
  3669. $user = trim((string)Config::get('mproc.smsbao_user'));
  3670. if ($user === '') {
  3671. $user = 'zhuwei123';
  3672. }
  3673. $passPlain = Config::get('mproc.smsbao_pass');
  3674. $pass = ($passPlain !== null && $passPlain !== '')
  3675. ? md5((string)$passPlain)
  3676. : md5('1d1e605c101e4c1f8a156c6d7b19f126');
  3677. $phone = trim((string)$phone);
  3678. $content = trim((string)$content);
  3679. if ($phone === '' || $content === '') {
  3680. throw new \Exception('短信发送失败:参数不全');
  3681. }
  3682. $sendurl = $smsapi . 'sms?u=' . rawurlencode($user) . '&p=' . $pass . '&m=' . rawurlencode($phone) . '&c=' . rawurlencode($content);
  3683. $result = @file_get_contents($sendurl);
  3684. if ($result === false) {
  3685. Log::record('smsbao 请求失败 phone=' . $phone . ' content=' . $content, 'error');
  3686. throw new \Exception('短信发送失败:网络异常');
  3687. }
  3688. $result = trim((string)$result);
  3689. if ($result !== '0') {
  3690. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  3691. Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg . ' content=' . $content, 'error');
  3692. throw new \Exception('短信发送失败:' . $msg);
  3693. }
  3694. Log::record('smsbao 发送成功 phone=' . $phone . ' content=' . $content, 'info');
  3695. }
  3696. /**
  3697. * 质量评分页(质检中心:合格/投诉/中断)
  3698. */
  3699. public function inboundscore()
  3700. {
  3701. $user = $this->mprocGetUser();
  3702. if (!$user) {
  3703. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  3704. $safe = $this->mprocSanitizeRedirectUrl($uri);
  3705. if ($safe !== '') {
  3706. Session::set('mproc_intended_url', $safe);
  3707. }
  3708. $this->redirect($this->mprocBuildLoginUrl($safe));
  3709. return;
  3710. }
  3711. if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'quality')) {
  3712. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  3713. if ($jump === '') {
  3714. $this->mprocDropCurrentLogin();
  3715. $this->redirect(url('index/index/login'));
  3716. return;
  3717. }
  3718. $this->redirect($jump);
  3719. return;
  3720. }
  3721. $this->mprocEnsureInboundScoreTable();
  3722. $q = trim((string)$this->request->get('q', ''));
  3723. $profile = $this->mprocProfileForUser($user);
  3724. $this->view->assign('mprocSearchQ', $q);
  3725. $this->view->assign('mprocProfile', $profile);
  3726. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  3727. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  3728. $this->view->assign('mprocScoreScope', 'quality');
  3729. $this->view->assign('rows', $this->mprocLoadInboundScoreRows('pending', $q, (int)($user['admin_id'] ?? 0), 'quality'));
  3730. return $this->view->fetch();
  3731. }
  3732. /**
  3733. * 交货情况页(生产部:准时/滞后)
  3734. */
  3735. public function deliveryscore()
  3736. {
  3737. $user = $this->mprocGetUser();
  3738. if (!$user) {
  3739. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  3740. $safe = $this->mprocSanitizeRedirectUrl($uri);
  3741. if ($safe !== '') {
  3742. Session::set('mproc_intended_url', $safe);
  3743. }
  3744. $this->redirect($this->mprocBuildLoginUrl($safe));
  3745. return;
  3746. }
  3747. if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'delivery')) {
  3748. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  3749. if ($jump === '') {
  3750. $this->mprocDropCurrentLogin();
  3751. $this->redirect(url('index/index/login'));
  3752. return;
  3753. }
  3754. $this->redirect($jump);
  3755. return;
  3756. }
  3757. $this->mprocEnsureInboundScoreTable();
  3758. $q = trim((string)$this->request->get('q', ''));
  3759. $profile = $this->mprocProfileForUser($user);
  3760. $this->view->assign('mprocSearchQ', $q);
  3761. $this->view->assign('mprocProfile', $profile);
  3762. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  3763. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  3764. $this->view->assign('mprocScoreScope', 'delivery');
  3765. $this->view->assign('rows', $this->mprocLoadInboundScoreRows('pending', $q, (int)($user['admin_id'] ?? 0), 'delivery'));
  3766. return $this->view->fetch();
  3767. }
  3768. /**
  3769. * 质量评分列表 JSON(质检;tab=pending|scored)
  3770. */
  3771. public function inboundscorelist()
  3772. {
  3773. $user = $this->mprocRequireQualityUser();
  3774. $this->mprocEnsureInboundScoreTable();
  3775. $q = trim((string)$this->request->request('q', ''));
  3776. $tab = trim((string)$this->request->request('tab', 'pending'));
  3777. if (!in_array($tab, ['pending', 'scored', 'pass', 'fail'], true)) {
  3778. $tab = 'pending';
  3779. }
  3780. if ($tab === 'pass' || $tab === 'fail') {
  3781. $tab = 'scored';
  3782. }
  3783. $adminId = (int)($user['admin_id'] ?? 0);
  3784. $rows = $this->mprocLoadInboundScoreRows($tab, $q, $adminId, 'quality');
  3785. $this->success('ok', '', [
  3786. 'tab' => $tab,
  3787. 'q' => $q,
  3788. 'scope' => 'quality',
  3789. 'rows' => $rows,
  3790. 'count' => count($rows),
  3791. ]);
  3792. }
  3793. /**
  3794. * 交货情况列表 JSON(生产部;tab=pending|scored)
  3795. */
  3796. public function deliveryscorelist()
  3797. {
  3798. $user = $this->mprocRequireDeliveryUser();
  3799. $this->mprocEnsureInboundScoreTable();
  3800. $q = trim((string)$this->request->request('q', ''));
  3801. $tab = trim((string)$this->request->request('tab', 'pending'));
  3802. if (!in_array($tab, ['pending', 'scored'], true)) {
  3803. $tab = 'pending';
  3804. }
  3805. $adminId = (int)($user['admin_id'] ?? 0);
  3806. $rows = $this->mprocLoadInboundScoreRows($tab, $q, $adminId, 'delivery');
  3807. $this->success('ok', '', [
  3808. 'tab' => $tab,
  3809. 'q' => $q,
  3810. 'scope' => 'delivery',
  3811. 'rows' => $rows,
  3812. 'count' => count($rows),
  3813. ]);
  3814. }
  3815. /**
  3816. * 保存质量评分(质检中心)
  3817. * POST:ccydh、result、order_interrupt、remark
  3818. * 客诉事后由 inboundscorecomplaint 补登,首次默认否
  3819. */
  3820. public function inboundscoresave()
  3821. {
  3822. $user = $this->mprocRequireQualityUser();
  3823. if (!$this->request->isPost()) {
  3824. $this->error('请使用 POST');
  3825. }
  3826. $this->mprocEnsureInboundScoreTable();
  3827. $ccydh = trim((string)$this->request->post('ccydh', ''));
  3828. $sid = (int)$this->request->post('scydgy_id', 0);
  3829. $result = trim((string)$this->request->post('result', ''));
  3830. if ($result !== '合格' && $result !== '不合格') {
  3831. $this->error('请选择是否合格');
  3832. }
  3833. $orderInterrupt = (int)$this->request->post('order_interrupt', -1);
  3834. if ($orderInterrupt !== 0 && $orderInterrupt !== 1) {
  3835. $this->error('请选择订单是否中断');
  3836. }
  3837. $remark = trim((string)$this->request->post('remark', ''));
  3838. if ($result === '不合格' && $remark === '') {
  3839. $this->error('请填写不合格原因');
  3840. }
  3841. if (mb_strlen($remark) > 500) {
  3842. $remark = mb_substr($remark, 0, 500);
  3843. }
  3844. $poRows = $this->mprocLoadApprovedPoRowsForScore($ccydh, $sid);
  3845. $now = date('Y-m-d H:i:s');
  3846. $adminId = (int)($user['admin_id'] ?? 0);
  3847. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  3848. $saved = 0;
  3849. $firstSid = 0;
  3850. $firstPoId = 0;
  3851. $deliveryReady = true;
  3852. try {
  3853. Db::startTrans();
  3854. foreach ($poRows as $po) {
  3855. if (!is_array($po)) {
  3856. continue;
  3857. }
  3858. $rowSid = (int)($po['scydgy_id'] ?? 0);
  3859. if ($rowSid <= 0) {
  3860. continue;
  3861. }
  3862. if ($firstSid <= 0) {
  3863. $firstSid = $rowSid;
  3864. $firstPoId = (int)($po['id'] ?? 0);
  3865. }
  3866. $exist = Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->find();
  3867. $existDs = is_array($exist) ? trim((string)($exist['delivery_status'] ?? '')) : '';
  3868. if ($existDs !== '准时' && $existDs !== '滞后') {
  3869. $deliveryReady = false;
  3870. }
  3871. $data = [
  3872. 'scydgy_id' => $rowSid,
  3873. 'purchase_order_id' => (int)($po['id'] ?? 0),
  3874. 'ccydh' => trim((string)($po['CCYDH'] ?? $ccydh)),
  3875. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  3876. 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
  3877. 'company_name' => trim((string)($po['pick_company_name'] ?? '')),
  3878. 'result' => $result,
  3879. 'order_interrupt' => $orderInterrupt,
  3880. 'remark' => $remark,
  3881. 'admin_id' => $adminId,
  3882. 'admin_name' => $adminName,
  3883. 'updatetime' => $now,
  3884. ];
  3885. if (is_array($exist) && $exist !== []) {
  3886. // 客诉事后补登,首次评分不覆盖已有客诉
  3887. Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->update($data);
  3888. } else {
  3889. $data['customer_complaint'] = 0;
  3890. $data['complaint_remark'] = '';
  3891. $data['delivery_status'] = '';
  3892. $data['createtime'] = $now;
  3893. Db::table('purchase_order_inbound_score')->insert($data);
  3894. $deliveryReady = false;
  3895. }
  3896. $saved++;
  3897. }
  3898. if ($saved < 1) {
  3899. throw new \RuntimeException('没有可保存的工序');
  3900. }
  3901. if ($deliveryReady) {
  3902. foreach ($poRows as $po) {
  3903. if (!is_array($po)) {
  3904. continue;
  3905. }
  3906. $rowSid = (int)($po['scydgy_id'] ?? 0);
  3907. if ($rowSid > 0) {
  3908. Db::table('purchase_order')->where('scydgy_id', $rowSid)->update([
  3909. 'status' => ProcuremenStatus::PO_COMPLETED,
  3910. ]);
  3911. }
  3912. }
  3913. }
  3914. Db::commit();
  3915. } catch (\Throwable $e) {
  3916. try {
  3917. Db::rollback();
  3918. } catch (\Throwable $e2) {
  3919. }
  3920. Log::record('inboundscoresave fail: ' . $e->getMessage(), 'error');
  3921. $this->error('保存失败,请稍后重试');
  3922. }
  3923. $logDetail = '质量评分:是否合格=' . $result
  3924. . ';订单中断:' . ($orderInterrupt === 1 ? '是' : '否');
  3925. if ($remark !== '') {
  3926. $logDetail .= ';备注:' . $remark;
  3927. }
  3928. \app\common\library\ProcuremenOperLog::write(
  3929. $firstSid,
  3930. 'inbound_score',
  3931. $logDetail,
  3932. $firstPoId > 0 ? $firstPoId : null,
  3933. [$adminId, $adminName]
  3934. );
  3935. $this->mprocSyncMonthlyAfterInboundScore($poRows, $now);
  3936. $this->success('操作成功', '', [
  3937. 'ccydh' => $ccydh,
  3938. 'result' => $result,
  3939. 'order_interrupt' => $orderInterrupt,
  3940. 'remark' => $remark,
  3941. 'count' => $saved,
  3942. 'completed' => $deliveryReady ? 1 : 0,
  3943. ]);
  3944. }
  3945. /**
  3946. * 事后登记客诉(质检中心,仅已质量评分订单)
  3947. * POST:ccydh、customer_complaint=0|1、complaint_remark(投诉为是时必填)
  3948. */
  3949. public function inboundscorecomplaint()
  3950. {
  3951. $user = $this->mprocRequireQualityUser();
  3952. if (!$this->request->isPost()) {
  3953. $this->error('请使用 POST');
  3954. }
  3955. $this->mprocEnsureInboundScoreTable();
  3956. $ccydh = trim((string)$this->request->post('ccydh', ''));
  3957. $sid = (int)$this->request->post('scydgy_id', 0);
  3958. $customerComplaint = (int)$this->request->post('customer_complaint', -1);
  3959. if ($customerComplaint !== 0 && $customerComplaint !== 1) {
  3960. $this->error('请选择客户是否投诉');
  3961. }
  3962. $complaintRemark = trim((string)$this->request->post('complaint_remark', ''));
  3963. if ($customerComplaint === 1 && $complaintRemark === '') {
  3964. $this->error('请填写投诉说明');
  3965. }
  3966. if ($customerComplaint !== 1) {
  3967. $complaintRemark = '';
  3968. }
  3969. if (mb_strlen($complaintRemark) > 500) {
  3970. $complaintRemark = mb_substr($complaintRemark, 0, 500);
  3971. }
  3972. if ($ccydh === '' && $sid > 0) {
  3973. try {
  3974. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  3975. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  3976. } catch (\Throwable $e) {
  3977. $ccydh = '';
  3978. }
  3979. }
  3980. if ($ccydh === '') {
  3981. $this->error('缺少订单号');
  3982. }
  3983. try {
  3984. $scoreRows = Db::table('purchase_order_inbound_score')
  3985. ->where('ccydh', $ccydh)
  3986. ->field('id,scydgy_id,purchase_order_id,result,company_name')
  3987. ->select();
  3988. } catch (\Throwable $e) {
  3989. $scoreRows = [];
  3990. }
  3991. if (!is_array($scoreRows) || $scoreRows === []) {
  3992. $this->error('请先完成质量评分后再登记客诉');
  3993. }
  3994. $hasQuality = false;
  3995. foreach ($scoreRows as $sc) {
  3996. if (!is_array($sc)) {
  3997. continue;
  3998. }
  3999. $res = trim((string)($sc['result'] ?? ''));
  4000. if ($res === '合格' || $res === '不合格') {
  4001. $hasQuality = true;
  4002. break;
  4003. }
  4004. }
  4005. if (!$hasQuality) {
  4006. $this->error('请先完成质量评分后再登记客诉');
  4007. }
  4008. $now = date('Y-m-d H:i:s');
  4009. $adminId = (int)($user['admin_id'] ?? 0);
  4010. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  4011. $firstSid = 0;
  4012. $firstPoId = 0;
  4013. $companyName = '';
  4014. $updated = 0;
  4015. try {
  4016. Db::startTrans();
  4017. foreach ($scoreRows as $sc) {
  4018. if (!is_array($sc)) {
  4019. continue;
  4020. }
  4021. $rowSid = (int)($sc['scydgy_id'] ?? 0);
  4022. $id = (int)($sc['id'] ?? 0);
  4023. if ($id <= 0) {
  4024. continue;
  4025. }
  4026. if ($firstSid <= 0 && $rowSid > 0) {
  4027. $firstSid = $rowSid;
  4028. $firstPoId = (int)($sc['purchase_order_id'] ?? 0);
  4029. }
  4030. if ($companyName === '') {
  4031. $companyName = trim((string)($sc['company_name'] ?? ''));
  4032. }
  4033. Db::table('purchase_order_inbound_score')->where('id', $id)->update([
  4034. 'customer_complaint' => $customerComplaint,
  4035. 'complaint_remark' => $complaintRemark,
  4036. 'updatetime' => $now,
  4037. ]);
  4038. $updated++;
  4039. }
  4040. if ($updated < 1) {
  4041. throw new \RuntimeException('没有可更新的记录');
  4042. }
  4043. Db::commit();
  4044. } catch (\Throwable $e) {
  4045. try {
  4046. Db::rollback();
  4047. } catch (\Throwable $e2) {
  4048. }
  4049. Log::record('inboundscorecomplaint fail: ' . $e->getMessage(), 'error');
  4050. $this->error('保存失败,请稍后重试');
  4051. }
  4052. if ($firstSid > 0) {
  4053. $logDetail = '登记客诉:客户投诉=' . ($customerComplaint === 1 ? '是' : '否');
  4054. if ($complaintRemark !== '') {
  4055. $logDetail .= ';投诉说明:' . $complaintRemark;
  4056. }
  4057. \app\common\library\ProcuremenOperLog::write(
  4058. $firstSid,
  4059. 'inbound_score',
  4060. $logDetail,
  4061. $firstPoId > 0 ? $firstPoId : null,
  4062. [$adminId, $adminName]
  4063. );
  4064. }
  4065. if ($companyName !== '') {
  4066. $scoreYm = date('Y-m', strtotime($now) ?: time());
  4067. try {
  4068. \app\common\library\ProcuremenSupplierScore::syncQualityScoreFromInbound($scoreYm, $companyName);
  4069. } catch (\Throwable $e) {
  4070. Log::record('inboundscorecomplaint quality sync: ' . $e->getMessage(), 'error');
  4071. }
  4072. }
  4073. $this->success('操作成功', '', [
  4074. 'ccydh' => $ccydh,
  4075. 'customer_complaint' => $customerComplaint,
  4076. 'complaint_remark' => $complaintRemark,
  4077. 'count' => $updated,
  4078. ]);
  4079. }
  4080. /**
  4081. * 保存交货情况(生产部)
  4082. * POST:ccydh、delivery_status=准时|滞后、delivery_date=YYYY-MM-DD
  4083. */
  4084. public function deliveryscoresave()
  4085. {
  4086. $user = $this->mprocRequireDeliveryUser();
  4087. if (!$this->request->isPost()) {
  4088. $this->error('请使用 POST');
  4089. }
  4090. $this->mprocEnsureInboundScoreTable();
  4091. $ccydh = trim((string)$this->request->post('ccydh', ''));
  4092. $sid = (int)$this->request->post('scydgy_id', 0);
  4093. $deliveryStatus = trim((string)$this->request->post('delivery_status', ''));
  4094. if ($deliveryStatus !== '准时' && $deliveryStatus !== '滞后') {
  4095. $this->error('请选择交货情况');
  4096. }
  4097. $deliveryDate = trim((string)$this->request->post('delivery_date', ''));
  4098. if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryDate)) {
  4099. $this->error('请选择交货日期');
  4100. }
  4101. $ts = strtotime($deliveryDate . ' 00:00:00');
  4102. if ($ts === false) {
  4103. $this->error('交货日期格式不正确');
  4104. }
  4105. $deliveryDate = date('Y-m-d', $ts);
  4106. $poRows = $this->mprocLoadApprovedPoRowsForScore($ccydh, $sid);
  4107. $now = date('Y-m-d H:i:s');
  4108. $adminId = (int)($user['admin_id'] ?? 0);
  4109. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  4110. $saved = 0;
  4111. $firstSid = 0;
  4112. $firstPoId = 0;
  4113. $qualityReady = true;
  4114. try {
  4115. Db::startTrans();
  4116. foreach ($poRows as $po) {
  4117. if (!is_array($po)) {
  4118. continue;
  4119. }
  4120. $rowSid = (int)($po['scydgy_id'] ?? 0);
  4121. if ($rowSid <= 0) {
  4122. continue;
  4123. }
  4124. if ($firstSid <= 0) {
  4125. $firstSid = $rowSid;
  4126. $firstPoId = (int)($po['id'] ?? 0);
  4127. }
  4128. $exist = Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->find();
  4129. $existResult = is_array($exist) ? trim((string)($exist['result'] ?? '')) : '';
  4130. if ($existResult !== '合格' && $existResult !== '不合格') {
  4131. $qualityReady = false;
  4132. }
  4133. $data = [
  4134. 'scydgy_id' => $rowSid,
  4135. 'purchase_order_id' => (int)($po['id'] ?? 0),
  4136. 'ccydh' => trim((string)($po['CCYDH'] ?? $ccydh)),
  4137. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  4138. 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
  4139. 'company_name' => trim((string)($po['pick_company_name'] ?? '')),
  4140. 'delivery_status' => $deliveryStatus,
  4141. 'delivery_date' => $deliveryDate,
  4142. 'updatetime' => $now,
  4143. ];
  4144. if (is_array($exist) && $exist !== []) {
  4145. Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->update($data);
  4146. } else {
  4147. $data['result'] = '';
  4148. $data['customer_complaint'] = 0;
  4149. $data['complaint_remark'] = '';
  4150. $data['order_interrupt'] = 0;
  4151. $data['remark'] = '';
  4152. $data['admin_id'] = $adminId;
  4153. $data['admin_name'] = $adminName;
  4154. $data['createtime'] = $now;
  4155. Db::table('purchase_order_inbound_score')->insert($data);
  4156. $qualityReady = false;
  4157. }
  4158. $saved++;
  4159. }
  4160. if ($saved < 1) {
  4161. throw new \RuntimeException('没有可保存的工序');
  4162. }
  4163. if ($qualityReady) {
  4164. foreach ($poRows as $po) {
  4165. if (!is_array($po)) {
  4166. continue;
  4167. }
  4168. $rowSid = (int)($po['scydgy_id'] ?? 0);
  4169. if ($rowSid > 0) {
  4170. Db::table('purchase_order')->where('scydgy_id', $rowSid)->update([
  4171. 'status' => ProcuremenStatus::PO_COMPLETED,
  4172. ]);
  4173. }
  4174. }
  4175. }
  4176. Db::commit();
  4177. } catch (\Throwable $e) {
  4178. try {
  4179. Db::rollback();
  4180. } catch (\Throwable $e2) {
  4181. }
  4182. Log::record('deliveryscoresave fail: ' . $e->getMessage(), 'error');
  4183. $this->error('保存失败,请稍后重试');
  4184. }
  4185. \app\common\library\ProcuremenOperLog::write(
  4186. $firstSid,
  4187. 'inbound_score',
  4188. '交货情况:' . $deliveryStatus . ';交货日期:' . $deliveryDate,
  4189. $firstPoId > 0 ? $firstPoId : null,
  4190. [$adminId, $adminName]
  4191. );
  4192. $this->mprocSyncMonthlyAfterInboundScore($poRows, $now);
  4193. $this->success('操作成功', '', [
  4194. 'ccydh' => $ccydh,
  4195. 'delivery_status' => $deliveryStatus,
  4196. 'delivery_date' => $deliveryDate,
  4197. 'count' => $saved,
  4198. 'completed' => $qualityReady ? 1 : 0,
  4199. ]);
  4200. }
  4201. /**
  4202. * @return array<int, array<string, mixed>>
  4203. */
  4204. protected function mprocLoadApprovedPoRowsForScore(string $ccydh, int $sid): array
  4205. {
  4206. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  4207. $approvedIn = implode(',', array_map(static function ($v) {
  4208. return "'" . str_replace("'", "''", (string)$v) . "'";
  4209. }, $approvedVals));
  4210. try {
  4211. $q = Db::table('purchase_order')
  4212. ->where('scydgy_id', '>', 0)
  4213. ->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%\')')
  4214. ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
  4215. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  4216. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  4217. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,pick_company_name,pick_time,wflow_status,status');
  4218. if ($ccydh !== '') {
  4219. $q->where('CCYDH', $ccydh);
  4220. } elseif ($sid > 0) {
  4221. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  4222. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  4223. if ($ccydh === '') {
  4224. $this->error('缺少订单号');
  4225. }
  4226. $q->where('CCYDH', $ccydh);
  4227. } else {
  4228. $this->error('缺少订单号');
  4229. }
  4230. $poRows = $q->order('id', 'asc')->select();
  4231. } catch (\Throwable $e) {
  4232. $poRows = [];
  4233. }
  4234. if (!is_array($poRows) || $poRows === []) {
  4235. $this->error('未找到可评分的已审核订单');
  4236. }
  4237. return $poRows;
  4238. }
  4239. /**
  4240. * @param array<string, mixed> $user
  4241. */
  4242. protected function mprocResolveAdminDisplayName(array $user, int $adminId): string
  4243. {
  4244. $adminName = '';
  4245. if ($adminId > 0) {
  4246. try {
  4247. $adminRow = Db::name('admin')->where('id', $adminId)->field('nickname,username')->find();
  4248. if (is_array($adminRow)) {
  4249. $adminName = trim((string)($adminRow['nickname'] ?? ''));
  4250. if ($adminName === '') {
  4251. $adminName = trim((string)($adminRow['username'] ?? ''));
  4252. }
  4253. }
  4254. } catch (\Throwable $e) {
  4255. }
  4256. }
  4257. if ($adminName === '') {
  4258. $adminName = trim((string)($user['username'] ?? ''));
  4259. }
  4260. return $adminName !== '' ? $adminName : '管理员';
  4261. }
  4262. /**
  4263. * @param array<int, mixed> $poRows
  4264. */
  4265. protected function mprocSyncMonthlyAfterInboundScore(array $poRows, string $now): void
  4266. {
  4267. $companyName = '';
  4268. foreach ($poRows as $po) {
  4269. if (!is_array($po)) {
  4270. continue;
  4271. }
  4272. $companyName = trim((string)($po['pick_company_name'] ?? ''));
  4273. if ($companyName !== '') {
  4274. break;
  4275. }
  4276. }
  4277. $scoreYm = date('Y-m', strtotime($now) ?: time());
  4278. if ($companyName === '') {
  4279. return;
  4280. }
  4281. try {
  4282. \app\common\library\ProcuremenSupplierScore::syncQualityScoreFromInbound($scoreYm, $companyName);
  4283. } catch (\Throwable $e) {
  4284. Log::record('inboundscoresave quality sync: ' . $e->getMessage(), 'error');
  4285. }
  4286. }
  4287. /**
  4288. * @return array<string, mixed>
  4289. */
  4290. protected function mprocRequireAdminUser(): array
  4291. {
  4292. $user = $this->mprocGetUser();
  4293. if (!$user) {
  4294. $this->error('请先登录', url('index/index/login'));
  4295. }
  4296. if (empty($user['is_admin'])) {
  4297. $this->error('仅系统管理员可操作');
  4298. }
  4299. return $user;
  4300. }
  4301. /** 质检中心角色组 id */
  4302. protected function mprocResolveMobileQualityGroupId(): int
  4303. {
  4304. $id = (int)Config::get('mproc.mobile_quality_group_id');
  4305. if ($id > 0) {
  4306. return $id;
  4307. }
  4308. try {
  4309. $found = Db::name('auth_group')
  4310. ->where('name', '质检中心')
  4311. ->where('status', 'normal')
  4312. ->order('id', 'asc')
  4313. ->value('id');
  4314. $id = (int)$found;
  4315. } catch (\Throwable $e) {
  4316. $id = 0;
  4317. }
  4318. return $id > 0 ? $id : 16;
  4319. }
  4320. /** 生产部/生产员角色组 id */
  4321. protected function mprocResolveMobileDeliveryGroupId(): int
  4322. {
  4323. $id = (int)Config::get('mproc.mobile_delivery_group_id');
  4324. if ($id > 0) {
  4325. return $id;
  4326. }
  4327. try {
  4328. $found = Db::name('auth_group')
  4329. ->where('name', 'in', ['生产部', '生产员'])
  4330. ->where('status', 'normal')
  4331. ->order('id', 'asc')
  4332. ->value('id');
  4333. $id = (int)$found;
  4334. } catch (\Throwable $e) {
  4335. $id = 0;
  4336. }
  4337. return $id > 0 ? $id : 15;
  4338. }
  4339. /**
  4340. * @return int[]
  4341. */
  4342. protected function mprocAdminGroupIds(int $adminId): array
  4343. {
  4344. if ($adminId <= 0) {
  4345. return [];
  4346. }
  4347. try {
  4348. $ids = Db::name('auth_group_access')->where('uid', $adminId)->column('group_id');
  4349. } catch (\Throwable $e) {
  4350. return [];
  4351. }
  4352. if (!is_array($ids)) {
  4353. return [];
  4354. }
  4355. return array_values(array_unique(array_filter(array_map('intval', $ids))));
  4356. }
  4357. /** 超管(角色组 rules=*)或协同「管理员」组 */
  4358. protected function mprocAdminIsMobileSuper(int $adminId): bool
  4359. {
  4360. if ($adminId <= 0) {
  4361. return false;
  4362. }
  4363. try {
  4364. $rows = Db::name('auth_group_access')
  4365. ->alias('aga')
  4366. ->join('auth_group ag', 'aga.group_id = ag.id')
  4367. ->where('aga.uid', $adminId)
  4368. ->field('ag.id,ag.rules')
  4369. ->select();
  4370. } catch (\Throwable $e) {
  4371. return false;
  4372. }
  4373. if (!is_array($rows)) {
  4374. return false;
  4375. }
  4376. foreach ($rows as $r) {
  4377. if (!is_array($r)) {
  4378. continue;
  4379. }
  4380. if (trim((string)($r['rules'] ?? '')) === '*') {
  4381. return true;
  4382. }
  4383. // 供应链协同「管理员」组
  4384. if ((int)($r['id'] ?? 0) === 11) {
  4385. return true;
  4386. }
  4387. }
  4388. return false;
  4389. }
  4390. /**
  4391. * @param array<string, mixed> $user
  4392. * @param string $role quality|delivery
  4393. */
  4394. protected function mprocAdminHasMobileRole(array $user, string $role): bool
  4395. {
  4396. if (empty($user['is_admin'])) {
  4397. return false;
  4398. }
  4399. $adminId = (int)($user['admin_id'] ?? 0);
  4400. if ($adminId <= 0) {
  4401. return false;
  4402. }
  4403. if ($this->mprocAdminIsMobileSuper($adminId)) {
  4404. return true;
  4405. }
  4406. $gids = $this->mprocAdminGroupIds($adminId);
  4407. if ($role === 'quality') {
  4408. $need = $this->mprocResolveMobileQualityGroupId();
  4409. return $need > 0 && in_array($need, $gids, true);
  4410. }
  4411. if ($role === 'delivery') {
  4412. $need = $this->mprocResolveMobileDeliveryGroupId();
  4413. return $need > 0 && in_array($need, $gids, true);
  4414. }
  4415. return false;
  4416. }
  4417. /**
  4418. * @return array<string, mixed>
  4419. */
  4420. protected function mprocRequireQualityUser(): array
  4421. {
  4422. $user = $this->mprocRequireAdminUser();
  4423. if (!$this->mprocAdminHasMobileRole($user, 'quality')) {
  4424. $this->error('仅质检中心账号可操作质量评分');
  4425. }
  4426. return $user;
  4427. }
  4428. /**
  4429. * @return array<string, mixed>
  4430. */
  4431. protected function mprocRequireDeliveryUser(): array
  4432. {
  4433. $user = $this->mprocRequireAdminUser();
  4434. if (!$this->mprocAdminHasMobileRole($user, 'delivery')) {
  4435. $this->error('仅生产部账号可操作交货情况');
  4436. }
  4437. return $user;
  4438. }
  4439. protected function mprocEnsureInboundScoreTable(): void
  4440. {
  4441. static $ok = false;
  4442. if ($ok) {
  4443. return;
  4444. }
  4445. try {
  4446. Db::query('SELECT 1 FROM `purchase_order_inbound_score` LIMIT 1');
  4447. } catch (\Throwable $e) {
  4448. try {
  4449. Db::execute("CREATE TABLE IF NOT EXISTS `purchase_order_inbound_score` (
  4450. `id` int unsigned NOT NULL AUTO_INCREMENT,
  4451. `scydgy_id` int NOT NULL DEFAULT 0 COMMENT '工序ID',
  4452. `purchase_order_id` int unsigned NOT NULL DEFAULT 0 COMMENT 'purchase_order.id',
  4453. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  4454. `cyjmc` varchar(255) NOT NULL DEFAULT '' COMMENT '印件名称',
  4455. `cgymc` varchar(255) NOT NULL DEFAULT '' COMMENT '工序名称',
  4456. `company_name` varchar(255) NOT NULL DEFAULT '' COMMENT '中标供应商',
  4457. `result` varchar(16) NOT NULL DEFAULT '' COMMENT '合格/不合格',
  4458. `delivery_status` varchar(16) NOT NULL DEFAULT '' COMMENT '交货情况 准时/滞后',
  4459. `delivery_date` date DEFAULT NULL COMMENT '交货日期',
  4460. `customer_complaint` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '客户是否投诉 1=是',
  4461. `complaint_remark` varchar(500) NOT NULL DEFAULT '' COMMENT '投诉说明',
  4462. `order_interrupt` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '订单是否中断 1=是',
  4463. `admin_id` int unsigned NOT NULL DEFAULT 0,
  4464. `admin_name` varchar(64) NOT NULL DEFAULT '',
  4465. `remark` varchar(500) NOT NULL DEFAULT '',
  4466. `createtime` datetime DEFAULT NULL,
  4467. `updatetime` datetime DEFAULT NULL,
  4468. PRIMARY KEY (`id`),
  4469. UNIQUE KEY `uk_scydgy_id` (`scydgy_id`),
  4470. KEY `idx_ccydh` (`ccydh`),
  4471. KEY `idx_result` (`result`),
  4472. KEY `idx_updatetime` (`updatetime`)
  4473. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='质量评分'");
  4474. } catch (\Throwable $e2) {
  4475. Log::record('mprocEnsureInboundScoreTable: ' . $e2->getMessage(), 'error');
  4476. return;
  4477. }
  4478. }
  4479. foreach ([
  4480. 'delivery_status' => "ADD COLUMN `delivery_status` varchar(16) NOT NULL DEFAULT '' COMMENT '交货情况 准时/滞后' AFTER `result`",
  4481. 'delivery_date' => "ADD COLUMN `delivery_date` date DEFAULT NULL COMMENT '交货日期' AFTER `delivery_status`",
  4482. 'customer_complaint' => "ADD COLUMN `customer_complaint` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '客户是否投诉 1=是' AFTER `delivery_date`",
  4483. 'complaint_remark' => "ADD COLUMN `complaint_remark` varchar(500) NOT NULL DEFAULT '' COMMENT '投诉说明' AFTER `customer_complaint`",
  4484. 'order_interrupt' => "ADD COLUMN `order_interrupt` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '订单是否中断 1=是' AFTER `complaint_remark`",
  4485. ] as $col => $ddl) {
  4486. try {
  4487. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_inbound_score` LIKE '{$col}'");
  4488. if (!is_array($cols) || $cols === []) {
  4489. Db::execute("ALTER TABLE `purchase_order_inbound_score` {$ddl}");
  4490. }
  4491. } catch (\Throwable $e) {
  4492. Log::record("mprocEnsureInboundScoreTable {$col}: " . $e->getMessage(), 'error');
  4493. }
  4494. }
  4495. $ok = true;
  4496. }
  4497. /**
  4498. * 质量评分列表:按订单号合并(一单一行,工序顿号合并)
  4499. * tab=pending 待评分;scored 已评分(仅当前管理员操作过的)
  4500. *
  4501. * @return array<int, array<string, mixed>>
  4502. */
  4503. protected function mprocLoadInboundScoreRows(string $tab, string $keyword = '', int $adminId = 0, string $scope = 'quality'): array
  4504. {
  4505. $this->mprocEnsureInboundScoreTable();
  4506. $keyword = trim($keyword);
  4507. $scope = $scope === 'delivery' ? 'delivery' : 'quality';
  4508. if (!in_array($tab, ['pending', 'scored', 'pass', 'fail'], true)) {
  4509. $tab = 'pending';
  4510. }
  4511. if ($tab === 'pass' || $tab === 'fail') {
  4512. $tab = 'scored';
  4513. }
  4514. try {
  4515. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  4516. $approvedIn = implode(',', array_map(static function ($v) {
  4517. return "'" . str_replace("'", "''", (string)$v) . "'";
  4518. }, $approvedVals));
  4519. $poRows = Db::table('purchase_order')
  4520. ->where('scydgy_id', '>', 0)
  4521. ->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%\')')
  4522. ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
  4523. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  4524. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  4525. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CCLBMMC,CDW,This_quantity,pick_company_name,pick_time,wflow_status,status')
  4526. ->order('pick_time', 'desc')
  4527. ->order('id', 'asc')
  4528. ->limit(800)
  4529. ->select();
  4530. } catch (\Throwable $e) {
  4531. Log::record('mprocLoadInboundScoreRows: ' . $e->getMessage(), 'error');
  4532. return [];
  4533. }
  4534. if (!is_array($poRows) || $poRows === []) {
  4535. return [];
  4536. }
  4537. $sids = [];
  4538. foreach ($poRows as $po) {
  4539. if (!is_array($po)) {
  4540. continue;
  4541. }
  4542. $sid = (int)($po['scydgy_id'] ?? 0);
  4543. if ($sid > 0) {
  4544. $sids[$sid] = true;
  4545. }
  4546. }
  4547. $scoreMap = [];
  4548. if ($sids !== []) {
  4549. try {
  4550. $scores = Db::table('purchase_order_inbound_score')
  4551. ->where('scydgy_id', 'in', array_keys($sids))
  4552. ->field('scydgy_id,result,delivery_status,delivery_date,customer_complaint,complaint_remark,order_interrupt,remark,admin_id,admin_name,updatetime,createtime')
  4553. ->select();
  4554. } catch (\Throwable $e) {
  4555. try {
  4556. $scores = Db::table('purchase_order_inbound_score')
  4557. ->where('scydgy_id', 'in', array_keys($sids))
  4558. ->field('scydgy_id,result,delivery_status,customer_complaint,order_interrupt,remark,admin_id,admin_name,updatetime,createtime')
  4559. ->select();
  4560. } catch (\Throwable $e2) {
  4561. $scores = [];
  4562. }
  4563. }
  4564. if (is_array($scores)) {
  4565. foreach ($scores as $sc) {
  4566. if (!is_array($sc)) {
  4567. continue;
  4568. }
  4569. $sid = (int)($sc['scydgy_id'] ?? 0);
  4570. if ($sid > 0) {
  4571. $scoreMap[$sid] = $sc;
  4572. }
  4573. }
  4574. }
  4575. }
  4576. /** @var array<string, array<string, mixed>> $groups */
  4577. $groups = [];
  4578. foreach ($poRows as $po) {
  4579. if (!is_array($po)) {
  4580. continue;
  4581. }
  4582. $sid = (int)($po['scydgy_id'] ?? 0);
  4583. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  4584. if ($sid <= 0 || $ccydh === '') {
  4585. continue;
  4586. }
  4587. if (!isset($groups[$ccydh])) {
  4588. $pickRaw = trim((string)($po['pick_time'] ?? ''));
  4589. $pickDisp = $pickRaw !== '' ? \app\common\library\ProcuremenTime::formatDisplayDateTime($pickRaw) : '';
  4590. $groups[$ccydh] = [
  4591. 'CCYDH' => $ccydh,
  4592. 'scydgy_id' => $sid,
  4593. 'scydgy_ids' => [],
  4594. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  4595. 'CCLBMMC' => trim((string)($po['CCLBMMC'] ?? '')),
  4596. 'CGYMC_list' => [],
  4597. 'pick_company_name' => trim((string)($po['pick_company_name'] ?? '')),
  4598. 'pick_time' => $pickDisp !== '' ? $pickDisp : $pickRaw,
  4599. 'pick_time_raw' => $pickRaw,
  4600. 'process_count' => 0,
  4601. 'results' => [],
  4602. 'score_admin_ids' => [],
  4603. 'score_time_raw' => '',
  4604. 'customer_complaint'=> 0,
  4605. 'complaint_remark' => '',
  4606. 'order_interrupt' => 0,
  4607. 'delivery_status' => '',
  4608. 'delivery_date' => '',
  4609. 'remark' => '',
  4610. ];
  4611. }
  4612. $g = &$groups[$ccydh];
  4613. $g['scydgy_ids'][] = $sid;
  4614. $g['process_count']++;
  4615. if ($g['scydgy_id'] <= 0) {
  4616. $g['scydgy_id'] = $sid;
  4617. }
  4618. if ($g['CYJMC'] === '') {
  4619. $g['CYJMC'] = trim((string)($po['CYJMC'] ?? ''));
  4620. }
  4621. if ($g['CCLBMMC'] === '') {
  4622. $g['CCLBMMC'] = trim((string)($po['CCLBMMC'] ?? ''));
  4623. }
  4624. if ($g['pick_company_name'] === '') {
  4625. $g['pick_company_name'] = trim((string)($po['pick_company_name'] ?? ''));
  4626. }
  4627. $pt = trim((string)($po['pick_time'] ?? ''));
  4628. if ($pt !== '' && ($g['pick_time_raw'] === '' || strcmp($pt, $g['pick_time_raw']) > 0)) {
  4629. $g['pick_time_raw'] = $pt;
  4630. $disp = \app\common\library\ProcuremenTime::formatDisplayDateTime($pt);
  4631. $g['pick_time'] = $disp !== '' ? $disp : $pt;
  4632. }
  4633. $gymc = trim((string)($po['CGYMC'] ?? ''));
  4634. if ($gymc !== '' && !in_array($gymc, $g['CGYMC_list'], true)) {
  4635. $g['CGYMC_list'][] = $gymc;
  4636. }
  4637. $sc = $scoreMap[$sid] ?? null;
  4638. $res = is_array($sc) ? trim((string)($sc['result'] ?? '')) : '';
  4639. $g['results'][] = $res;
  4640. if (is_array($sc) && $res !== '') {
  4641. $aid = (int)($sc['admin_id'] ?? 0);
  4642. if ($aid > 0) {
  4643. $g['score_admin_ids'][$aid] = true;
  4644. }
  4645. if ((int)($sc['customer_complaint'] ?? 0) === 1) {
  4646. $g['customer_complaint'] = 1;
  4647. }
  4648. $crm = trim((string)($sc['complaint_remark'] ?? ''));
  4649. if ($crm !== '' && $g['complaint_remark'] === '') {
  4650. $g['complaint_remark'] = $crm;
  4651. }
  4652. if ((int)($sc['order_interrupt'] ?? 0) === 1) {
  4653. $g['order_interrupt'] = 1;
  4654. }
  4655. $ds = trim((string)($sc['delivery_status'] ?? ''));
  4656. if ($ds !== '' && $g['delivery_status'] === '') {
  4657. $g['delivery_status'] = $ds;
  4658. }
  4659. $dd = trim((string)($sc['delivery_date'] ?? ''));
  4660. if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dd, $mdd) && $g['delivery_date'] === '') {
  4661. $g['delivery_date'] = $mdd[1];
  4662. }
  4663. $rm = trim((string)($sc['remark'] ?? ''));
  4664. if ($rm !== '' && $g['remark'] === '') {
  4665. $g['remark'] = $rm;
  4666. }
  4667. $st = trim((string)($sc['updatetime'] ?? ''));
  4668. if ($st === '') {
  4669. $st = trim((string)($sc['createtime'] ?? ''));
  4670. }
  4671. if ($st !== '' && ($g['score_time_raw'] === '' || strcmp($st, $g['score_time_raw']) > 0)) {
  4672. $g['score_time_raw'] = $st;
  4673. }
  4674. } elseif (is_array($sc)) {
  4675. // 仅填了交货、尚未质量评分
  4676. $ds = trim((string)($sc['delivery_status'] ?? ''));
  4677. if ($ds !== '' && $g['delivery_status'] === '') {
  4678. $g['delivery_status'] = $ds;
  4679. }
  4680. $dd = trim((string)($sc['delivery_date'] ?? ''));
  4681. if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dd, $mdd) && $g['delivery_date'] === '') {
  4682. $g['delivery_date'] = $mdd[1];
  4683. }
  4684. $st = trim((string)($sc['updatetime'] ?? ''));
  4685. if ($st === '') {
  4686. $st = trim((string)($sc['createtime'] ?? ''));
  4687. }
  4688. if ($st !== '' && ($g['score_time_raw'] === '' || strcmp($st, $g['score_time_raw']) > 0)) {
  4689. $g['score_time_raw'] = $st;
  4690. }
  4691. }
  4692. unset($g);
  4693. }
  4694. $out = [];
  4695. foreach ($groups as $ccydh => $g) {
  4696. $gymcList = is_array($g['CGYMC_list'] ?? null) ? $g['CGYMC_list'] : [];
  4697. $company = (string)($g['pick_company_name'] ?? '');
  4698. $cyjmc = (string)($g['CYJMC'] ?? '');
  4699. if ($keyword !== '') {
  4700. $blob = $ccydh . ' ' . $cyjmc . ' ' . implode('、', $gymcList) . ' ' . $company;
  4701. if (mb_stripos($blob, $keyword) === false) {
  4702. continue;
  4703. }
  4704. }
  4705. $results = is_array($g['results'] ?? null) ? $g['results'] : [];
  4706. $uniq = [];
  4707. $allScored = true;
  4708. foreach ($results as $r) {
  4709. $r = trim((string)$r);
  4710. if ($r === '') {
  4711. $allScored = false;
  4712. continue;
  4713. }
  4714. $uniq[$r] = true;
  4715. }
  4716. $orderResult = '';
  4717. if ($allScored && count($uniq) === 1) {
  4718. $keys = array_keys($uniq);
  4719. $orderResult = (string)($keys[0] ?? '');
  4720. } elseif ($allScored && count($uniq) > 1) {
  4721. $orderResult = '';
  4722. }
  4723. $deliveryStatus = trim((string)($g['delivery_status'] ?? ''));
  4724. $hasDelivery = ($deliveryStatus === '准时' || $deliveryStatus === '滞后');
  4725. if ($scope === 'quality') {
  4726. if ($tab === 'pending' && $orderResult !== '') {
  4727. continue;
  4728. }
  4729. if ($tab === 'scored') {
  4730. if ($orderResult !== '合格' && $orderResult !== '不合格') {
  4731. continue;
  4732. }
  4733. if ($adminId <= 0) {
  4734. continue;
  4735. }
  4736. $adminIds = is_array($g['score_admin_ids'] ?? null) ? $g['score_admin_ids'] : [];
  4737. if (empty($adminIds[$adminId])) {
  4738. continue;
  4739. }
  4740. }
  4741. } else {
  4742. // 交货:待评=尚未填准时/滞后;已评=已填
  4743. if ($tab === 'pending' && $hasDelivery) {
  4744. continue;
  4745. }
  4746. if ($tab === 'scored' && !$hasDelivery) {
  4747. continue;
  4748. }
  4749. }
  4750. $scoreTimeRaw = trim((string)($g['score_time_raw'] ?? ''));
  4751. $scoreTime = $scoreTimeRaw !== ''
  4752. ? \app\common\library\ProcuremenTime::formatDisplayDateTime($scoreTimeRaw)
  4753. : '';
  4754. $out[] = [
  4755. 'CCYDH' => $ccydh,
  4756. 'scydgy_id' => (int)($g['scydgy_id'] ?? 0),
  4757. 'scydgy_ids' => array_values(array_unique(array_map('intval', $g['scydgy_ids'] ?? []))),
  4758. 'CYJMC' => $cyjmc,
  4759. 'CGYMC' => $gymcList !== [] ? implode('、', $gymcList) : '',
  4760. 'CCLBMMC' => (string)($g['CCLBMMC'] ?? ''),
  4761. 'pick_company_name' => $company,
  4762. 'pick_time' => (string)($g['pick_time'] ?? ''),
  4763. 'score_time' => $scoreTime !== '' ? $scoreTime : $scoreTimeRaw,
  4764. 'score_time_raw' => $scoreTimeRaw,
  4765. 'process_count' => (int)($g['process_count'] ?? 0),
  4766. 'result' => $orderResult,
  4767. 'customer_complaint' => (int)($g['customer_complaint'] ?? 0),
  4768. 'complaint_remark' => (string)($g['complaint_remark'] ?? ''),
  4769. 'order_interrupt' => (int)($g['order_interrupt'] ?? 0),
  4770. 'delivery_status' => (string)($g['delivery_status'] ?? ''),
  4771. 'delivery_date' => (string)($g['delivery_date'] ?? ''),
  4772. 'remark' => (string)($g['remark'] ?? ''),
  4773. ];
  4774. }
  4775. usort($out, static function ($a, $b) use ($tab) {
  4776. if ($tab === 'scored') {
  4777. $ta = (string)($a['score_time_raw'] ?? '');
  4778. $tb = (string)($b['score_time_raw'] ?? '');
  4779. if ($ta !== $tb) {
  4780. return strcmp($tb, $ta);
  4781. }
  4782. }
  4783. $ta = (string)($a['pick_time'] ?? '');
  4784. $tb = (string)($b['pick_time'] ?? '');
  4785. if ($ta !== $tb) {
  4786. return strcmp($tb, $ta);
  4787. }
  4788. return strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  4789. });
  4790. return $out;
  4791. }
  4792. }