Index.php 212 KB

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