Index.php 217 KB

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