Index.php 216 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842
  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. }
  1546. /**
  1547. * 统一取年月日(无效则空串)
  1548. */
  1549. protected function mprocFormatYmdValue($raw): string
  1550. {
  1551. $s = trim((string)$raw);
  1552. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  1553. return '';
  1554. }
  1555. $s = str_replace(['/', '.'], '-', $s);
  1556. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  1557. return $m[1];
  1558. }
  1559. $ts = strtotime(str_replace('T', ' ', $s));
  1560. if ($ts === false || $ts <= 0) {
  1561. return '';
  1562. }
  1563. return date('Y-m-d', $ts);
  1564. }
  1565. /**
  1566. * 列表展示:招标截止 / 交货截止
  1567. *
  1568. * @param array<string, mixed> $row
  1569. */
  1570. protected function mprocEnrichOrderDeadlineDisplay(array &$row): void
  1571. {
  1572. $sysRqRaw = $this->mprocResolveSysRqFromPo($row);
  1573. $bid = $this->mprocFormatYmdValue($sysRqRaw !== '' ? $sysRqRaw : ($row['sys_rq'] ?? ''));
  1574. $del = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? '');
  1575. $row['mproc_bid_deadline_display'] = $bid;
  1576. // 完整截止时间供前端保存前校验(含时分秒)
  1577. $row['mproc_bid_deadline'] = $sysRqRaw;
  1578. $row['mproc_delivery_deadline_display'] = $del;
  1579. $row['mproc_delivery_deadline'] = $del;
  1580. }
  1581. /**
  1582. * 明细对应主表的交货截止日期 Y-m-d
  1583. *
  1584. * @param array<string, mixed> $row
  1585. */
  1586. protected function mprocResolveDeliveryDeadlineYmdForDetailRow(array $row): string
  1587. {
  1588. $fromRow = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? $row['mproc_delivery_deadline'] ?? '');
  1589. if ($fromRow !== '') {
  1590. return $fromRow;
  1591. }
  1592. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1593. if (!$this->mprocIsValidScydgyRowId($sid)) {
  1594. return '';
  1595. }
  1596. try {
  1597. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1598. } catch (\Throwable $e) {
  1599. $po = null;
  1600. }
  1601. if (!is_array($po)) {
  1602. return '';
  1603. }
  1604. return $this->mprocFormatYmdValue($po['delivery_deadline'] ?? $po['Delivery_deadline'] ?? '');
  1605. }
  1606. /**
  1607. * 主表报价截止时间(未设置则视为未截止)
  1608. *
  1609. * @param array<string, mixed>|null $po
  1610. */
  1611. protected function mprocResolveSysRqFromPo(?array $po): string
  1612. {
  1613. if (!is_array($po)) {
  1614. return '';
  1615. }
  1616. $sr = trim((string)($po['sys_rq'] ?? $po['SYS_RQ'] ?? ''));
  1617. if ($sr === '') {
  1618. $pl = array_change_key_case($po, CASE_LOWER);
  1619. $sr = trim((string)($pl['sys_rq'] ?? ''));
  1620. }
  1621. return ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) ? $sr : '';
  1622. }
  1623. /**
  1624. * 从主表/明细解析订单号
  1625. *
  1626. * @param array<string, mixed>|null $po
  1627. * @param array<string, mixed>|null $row
  1628. */
  1629. protected function mprocResolveCcydhFromPoOrRow(?array $po, ?array $row = null): string
  1630. {
  1631. foreach ([$po, $row] as $src) {
  1632. if (!is_array($src)) {
  1633. continue;
  1634. }
  1635. $c = trim((string)($src['CCYDH'] ?? $src['ccydh'] ?? ''));
  1636. if ($c !== '') {
  1637. return $c;
  1638. }
  1639. }
  1640. return '';
  1641. }
  1642. /**
  1643. * 批量:已开标验证的订单号集合(本请求内可复用)
  1644. *
  1645. * @var array<string, bool>|null
  1646. */
  1647. protected $mprocBidOpenVerifiedSet = null;
  1648. /**
  1649. * @param array<int, string> $ccydhs
  1650. * @return array<string, bool>
  1651. */
  1652. protected function mprocLoadBidOpenVerifiedCcydhSet(array $ccydhs): array
  1653. {
  1654. $set = [];
  1655. $list = [];
  1656. foreach ($ccydhs as $c) {
  1657. $c = trim((string)$c);
  1658. if ($c !== '') {
  1659. $list[$c] = true;
  1660. }
  1661. }
  1662. if ($list === []) {
  1663. return $set;
  1664. }
  1665. try {
  1666. $rows = Db::table('purchase_order_bid_open')
  1667. ->where('ccydh', 'in', array_keys($list))
  1668. ->field('ccydh')
  1669. ->select();
  1670. if (!is_array($rows)) {
  1671. return $set;
  1672. }
  1673. foreach ($rows as $row) {
  1674. if (!is_array($row)) {
  1675. continue;
  1676. }
  1677. $c = trim((string)($row['ccydh'] ?? ''));
  1678. if ($c !== '') {
  1679. $set[$c] = true;
  1680. }
  1681. }
  1682. } catch (\Throwable $e) {
  1683. return [];
  1684. }
  1685. return $set;
  1686. }
  1687. /**
  1688. * 该订单是否已完成开标双重验证(有 purchase_order_bid_open 记录)
  1689. */
  1690. protected function mprocIsBidOpenVerified(string $ccydh): bool
  1691. {
  1692. $ccydh = trim($ccydh);
  1693. if ($ccydh === '') {
  1694. return false;
  1695. }
  1696. if (is_array($this->mprocBidOpenVerifiedSet)) {
  1697. return isset($this->mprocBidOpenVerifiedSet[$ccydh]);
  1698. }
  1699. try {
  1700. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1701. return is_array($row);
  1702. } catch (\Throwable $e) {
  1703. return false;
  1704. }
  1705. }
  1706. /**
  1707. * @param array<string, mixed>|null $po
  1708. * @param array<string, mixed>|null $row
  1709. */
  1710. protected function mprocIsBidOpenVerifiedForPoOrRow(?array $po, ?array $row = null): bool
  1711. {
  1712. return $this->mprocIsBidOpenVerified($this->mprocResolveCcydhFromPoOrRow($po, $row));
  1713. }
  1714. /**
  1715. * 手机端:仅当主表设置了 sys_rq 且已到期时视为截止(无截止时间仍可填报)
  1716. * 保存时务必再调一次,防止页面长时间打开、截止后仍提交
  1717. *
  1718. * @param array<string, mixed>|null $po
  1719. */
  1720. protected function mprocIsQuoteDeadlineReachedForPo(?array $po): bool
  1721. {
  1722. $raw = $this->mprocResolveSysRqFromPo($po);
  1723. if ($raw === '') {
  1724. return false;
  1725. }
  1726. $ts = strtotime(str_replace('T', ' ', $raw));
  1727. if ($ts === false || $ts <= 0) {
  1728. return false;
  1729. }
  1730. return time() >= $ts;
  1731. }
  1732. /**
  1733. * 保存前强制按库中最新招标截止时间校验(避免弹窗久开后仍提交)
  1734. *
  1735. * @param array<string, mixed>|null $po
  1736. */
  1737. protected function mprocAssertQuoteNotDeadlineReached(?array $po, string $label = ''): void
  1738. {
  1739. // 以库中最新主表为准,避免内存中旧快照
  1740. $freshPo = null;
  1741. if (is_array($po)) {
  1742. $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
  1743. if ($this->mprocIsValidScydgyRowId($sid)) {
  1744. try {
  1745. $freshPo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1746. } catch (\Throwable $e) {
  1747. $freshPo = null;
  1748. }
  1749. }
  1750. }
  1751. $checkPo = is_array($freshPo) ? $freshPo : $po;
  1752. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($checkPo) ? $checkPo : null)) {
  1753. throw new \InvalidArgumentException(
  1754. ($label !== '' ? $label : '') . '已超过招标截止时间,不可再提交'
  1755. );
  1756. }
  1757. }
  1758. /**
  1759. * 保存前:截止时间 + 已开标均不可再改
  1760. *
  1761. * @param array<string, mixed>|null $po
  1762. * @param array<string, mixed>|null $row
  1763. */
  1764. protected function mprocAssertQuoteStillEditable(?array $po, string $label = '', ?array $row = null): void
  1765. {
  1766. $sid = 0;
  1767. if (is_array($row)) {
  1768. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1769. }
  1770. if ($sid === 0 && is_array($po)) {
  1771. $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
  1772. }
  1773. // 手工询价无招标截止、不开标
  1774. if ($sid < 0) {
  1775. return;
  1776. }
  1777. $this->mprocAssertQuoteNotDeadlineReached($po, $label);
  1778. $freshPo = is_array($po) ? $po : null;
  1779. if (is_array($po)) {
  1780. if ($this->mprocIsValidScydgyRowId($sid)) {
  1781. try {
  1782. $got = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1783. if (is_array($got)) {
  1784. $freshPo = $got;
  1785. }
  1786. } catch (\Throwable $e) {
  1787. }
  1788. }
  1789. }
  1790. // 保存场景不走列表缓存,直接查库
  1791. $prev = $this->mprocBidOpenVerifiedSet;
  1792. $this->mprocBidOpenVerifiedSet = null;
  1793. $opened = $this->mprocIsBidOpenVerifiedForPoOrRow($freshPo, $row);
  1794. $this->mprocBidOpenVerifiedSet = $prev;
  1795. if ($opened) {
  1796. throw new \InvalidArgumentException(
  1797. ($label !== '' ? $label : '') . '已开标验证,不可再提交'
  1798. );
  1799. }
  1800. }
  1801. /**
  1802. * 主单已完结后:中标 / 未中标
  1803. *
  1804. * @param array<string, mixed> $row
  1805. * @param array<string, mixed>|null $po
  1806. */
  1807. protected function mprocResolvePickResultText(array $row, ?array $po): string
  1808. {
  1809. if (!is_array($po) || !ProcuremenStatus::isPoCompleted($po['status'] ?? $po['STATUS'] ?? '')) {
  1810. return '';
  1811. }
  1812. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  1813. return ProcuremenStatus::isPodPicked($detailStatus) ? '中标' : '未中标';
  1814. }
  1815. /**
  1816. * 手机端左侧 Tab:
  1817. * 询价:rfq / rfq_submitted(手工单 scydgy_id&lt;0,仅未提交/已提交)
  1818. * 报价:draft / submitted / done(协助下发)
  1819. *
  1820. * @param array<string, mixed> $row
  1821. * @param array<string, mixed>|null $po
  1822. */
  1823. protected function mprocResolveListTabForRow(array $row, ?array $po, string $effectiveSn): string
  1824. {
  1825. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1826. // 手工询价:无招标截止;仅未提交/已提交(对应待报价/已报价)
  1827. if ($sid < 0) {
  1828. if ($effectiveSn === '已提交'
  1829. || in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  1830. return 'rfq_submitted';
  1831. }
  1832. return 'rfq';
  1833. }
  1834. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  1835. return 'done';
  1836. }
  1837. if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)
  1838. || $this->mprocIsQuoteDeadlineReachedForPo($po)) {
  1839. // 已开标或已过招标截止 →「已完成」
  1840. return 'done';
  1841. }
  1842. if ($effectiveSn === '已提交') {
  1843. return 'submitted';
  1844. }
  1845. return 'draft';
  1846. }
  1847. /**
  1848. * @return string[]
  1849. */
  1850. protected function mprocListTabWhitelist(): array
  1851. {
  1852. return ['rfq', 'rfq_submitted', 'draft', 'submitted', 'done'];
  1853. }
  1854. /**
  1855. * 兼容旧地址 tab=rfq_done → 询价已提交
  1856. */
  1857. protected function mprocNormalizeListTab(string $tab): string
  1858. {
  1859. if ($tab === 'rfq_done') {
  1860. return 'rfq_submitted';
  1861. }
  1862. if (!in_array($tab, $this->mprocListTabWhitelist(), true)) {
  1863. return 'draft';
  1864. }
  1865. return $tab;
  1866. }
  1867. protected function mprocIsDoneListTab(string $tab): bool
  1868. {
  1869. return $tab === 'done';
  1870. }
  1871. protected function mprocIsRfqListTab(string $tab): bool
  1872. {
  1873. return $tab === 'rfq' || $tab === 'rfq_submitted';
  1874. }
  1875. /**
  1876. * 复合 Tab → 状态维度:draft|submitted|done
  1877. */
  1878. protected function mprocStatusFromListTab(string $tab): string
  1879. {
  1880. if ($tab === 'rfq' || $tab === 'draft') {
  1881. return 'draft';
  1882. }
  1883. if ($tab === 'rfq_submitted' || $tab === 'submitted') {
  1884. return 'submitted';
  1885. }
  1886. if ($this->mprocIsDoneListTab($tab)) {
  1887. return 'done';
  1888. }
  1889. return 'draft';
  1890. }
  1891. /**
  1892. * 同一订单号 + 供应商合并为一张卡片
  1893. *
  1894. * @param array<int, array<string, mixed>> $rows
  1895. * @return array<int, array<string, mixed>>
  1896. */
  1897. protected function mprocGroupRowsByOrder(array $rows): array
  1898. {
  1899. $groups = [];
  1900. $order = [];
  1901. foreach ($rows as $row) {
  1902. if (!is_array($row)) {
  1903. continue;
  1904. }
  1905. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1906. $cname = trim((string)($row['company_name'] ?? ''));
  1907. $key = ($ccydh !== '' ? $ccydh : ('eid_' . (int)($row['eid'] ?? 0))) . '|' . $cname;
  1908. if (!isset($groups[$key])) {
  1909. $groups[$key] = [
  1910. 'group_key' => $key,
  1911. 'CCYDH' => $ccydh,
  1912. 'CYJMC' => trim((string)($row['CYJMC'] ?? '')),
  1913. 'company_name' => $cname,
  1914. 'mproc_bid_deadline_display' => trim((string)($row['mproc_bid_deadline_display'] ?? '')),
  1915. 'mproc_bid_deadline' => trim((string)($row['mproc_bid_deadline'] ?? '')),
  1916. 'mproc_delivery_deadline_display' => trim((string)($row['mproc_delivery_deadline_display'] ?? '')),
  1917. 'mproc_delivery_deadline' => trim((string)($row['mproc_delivery_deadline'] ?? '')),
  1918. 'lines' => [],
  1919. ];
  1920. $order[] = $key;
  1921. } else {
  1922. if ($groups[$key]['mproc_delivery_deadline'] === ''
  1923. && trim((string)($row['mproc_delivery_deadline'] ?? '')) !== '') {
  1924. $groups[$key]['mproc_delivery_deadline'] = trim((string)$row['mproc_delivery_deadline']);
  1925. $groups[$key]['mproc_delivery_deadline_display'] = trim((string)($row['mproc_delivery_deadline_display'] ?? ''));
  1926. }
  1927. if ($groups[$key]['mproc_bid_deadline'] === ''
  1928. && trim((string)($row['mproc_bid_deadline'] ?? '')) !== '') {
  1929. $groups[$key]['mproc_bid_deadline'] = trim((string)$row['mproc_bid_deadline']);
  1930. }
  1931. if ($groups[$key]['mproc_bid_deadline_display'] === ''
  1932. && trim((string)($row['mproc_bid_deadline_display'] ?? '')) !== '') {
  1933. $groups[$key]['mproc_bid_deadline_display'] = trim((string)$row['mproc_bid_deadline_display']);
  1934. }
  1935. }
  1936. $groups[$key]['lines'][] = $row;
  1937. }
  1938. $out = [];
  1939. foreach ($order as $key) {
  1940. $g = $groups[$key];
  1941. $lines = is_array($g['lines'] ?? null) ? $g['lines'] : [];
  1942. usort($lines, function ($a, $b) {
  1943. $sa = (int)($a['scydgy_id'] ?? 0);
  1944. $sb = (int)($b['scydgy_id'] ?? 0);
  1945. if ($sa !== $sb) {
  1946. return $sa <=> $sb;
  1947. }
  1948. return ((int)($a['eid'] ?? 0)) <=> ((int)($b['eid'] ?? 0));
  1949. });
  1950. $g['lines'] = $lines;
  1951. $g['line_count'] = count($lines);
  1952. $canEdit = false;
  1953. $bidOpen = false;
  1954. foreach ($lines as $ln) {
  1955. if (!is_array($ln)) {
  1956. continue;
  1957. }
  1958. if ((int)($ln['mproc_can_edit'] ?? 0) === 1) {
  1959. $canEdit = true;
  1960. }
  1961. if ((int)($ln['mproc_bid_open_verified'] ?? 0) === 1) {
  1962. $bidOpen = true;
  1963. }
  1964. }
  1965. $g['can_edit'] = $canEdit ? 1 : 0;
  1966. $g['mproc_bid_open_verified'] = $bidOpen ? 1 : 0;
  1967. $remark = '';
  1968. $doneLabel = '';
  1969. $pickResult = '';
  1970. $hasWin = false;
  1971. $hasLose = false;
  1972. $hasExpired = false;
  1973. foreach ($lines as $ln) {
  1974. if (!is_array($ln)) {
  1975. continue;
  1976. }
  1977. $rm = trim((string)($ln['mproc_remark'] ?? ''));
  1978. if ($rm !== '' && $remark === '') {
  1979. $remark = $rm;
  1980. }
  1981. $pr = trim((string)($ln['mproc_pick_result'] ?? ''));
  1982. $dl = trim((string)($ln['mproc_done_label'] ?? ''));
  1983. if ($pr === '中标' || $dl === '中标') {
  1984. $hasWin = true;
  1985. } elseif ($pr === '未中标' || $dl === '未中标') {
  1986. $hasLose = true;
  1987. } elseif ($dl === '已截止' || (int)($ln['mproc_deadline_reached'] ?? 0) === 1) {
  1988. $hasExpired = true;
  1989. }
  1990. }
  1991. if ($hasWin) {
  1992. $doneLabel = '中标';
  1993. $pickResult = '中标';
  1994. } elseif ($hasLose) {
  1995. $doneLabel = '未中标';
  1996. $pickResult = '未中标';
  1997. } elseif ($hasExpired) {
  1998. $doneLabel = '已截止';
  1999. $pickResult = '';
  2000. }
  2001. $g['remark'] = $remark;
  2002. $g['mproc_done_label'] = $doneLabel;
  2003. $g['mproc_pick_result'] = $pickResult;
  2004. $out[] = $g;
  2005. }
  2006. return $out;
  2007. }
  2008. /**
  2009. * 查询 purchase_order_detail 列表(订单页)
  2010. * 无搜索词 / 有搜索词:均按左侧 Tab 筛选(draft/submitted/done)
  2011. * 有搜索词时:在当前 Tab 内做关键字匹配
  2012. *
  2013. * @param string $tab draft|submitted|done
  2014. * @param string|null $statusNameCol status_name 真实列名;为 null 时不按 Tab 过滤
  2015. * @return array{rows: array, done_no_status: int}
  2016. */
  2017. protected function mprocFetchProcuremenList(array $user, $tab, $q, $statusNameCol)
  2018. {
  2019. $query = Db::table('purchase_order_detail')->order('id', 'desc');
  2020. // 初选下发已向供应商发送通知后,手机端可见 wflow_status>=1 的明细
  2021. $userWhere = $this->mprocListWhereForLoginUser($user);
  2022. if ($userWhere !== []) {
  2023. $query->where($userWhere);
  2024. }
  2025. if (trim((string)$q) === '' && $this->mprocIsDoneListTab((string)$tab) && $statusNameCol !== null) {
  2026. $this->mprocSyncLegacyApprovedStatusNames($user, $statusNameCol);
  2027. }
  2028. $this->mprocApplySearchKeywordToDetailQuery($query, $q);
  2029. // Tab 筛选在 PHP 层按截止时间、审批结果综合判断(含逾期进「已完成」、未中标等)
  2030. try {
  2031. $rows = $query->limit(500)->select();
  2032. } catch (\Throwable $e) {
  2033. $rows = [];
  2034. }
  2035. if (!is_array($rows)) {
  2036. $rows = [];
  2037. }
  2038. $poBySid = [];
  2039. $sidList = [];
  2040. foreach ($rows as $r0) {
  2041. if (!is_array($r0)) {
  2042. continue;
  2043. }
  2044. $sid0 = (int)($r0['scydgy_id'] ?? $r0['SCYDGY_ID'] ?? 0);
  2045. if ($this->mprocIsValidScydgyRowId($sid0)) {
  2046. $sidList[$sid0] = true;
  2047. }
  2048. }
  2049. if ($sidList !== []) {
  2050. try {
  2051. $poRows = Db::table('purchase_order')
  2052. ->where('scydgy_id', 'in', array_values(array_keys($sidList)))
  2053. ->select();
  2054. if (is_array($poRows)) {
  2055. foreach ($poRows as $pr) {
  2056. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  2057. if ($this->mprocIsValidScydgyRowId($sidk)) {
  2058. $poBySid[$sidk] = $pr;
  2059. }
  2060. }
  2061. }
  2062. } catch (\Throwable $e) {
  2063. }
  2064. }
  2065. $ccydhForBid = [];
  2066. foreach ($poBySid as $pr) {
  2067. if (!is_array($pr)) {
  2068. continue;
  2069. }
  2070. $c = trim((string)($pr['CCYDH'] ?? $pr['ccydh'] ?? ''));
  2071. if ($c !== '') {
  2072. $ccydhForBid[$c] = true;
  2073. }
  2074. }
  2075. foreach ($rows as $r0) {
  2076. if (!is_array($r0)) {
  2077. continue;
  2078. }
  2079. $c = trim((string)($r0['CCYDH'] ?? $r0['ccydh'] ?? ''));
  2080. if ($c !== '') {
  2081. $ccydhForBid[$c] = true;
  2082. }
  2083. }
  2084. $this->mprocBidOpenVerifiedSet = $this->mprocLoadBidOpenVerifiedCcydhSet(array_keys($ccydhForBid));
  2085. foreach ($rows as &$row) {
  2086. if (!is_array($row)) {
  2087. continue;
  2088. }
  2089. // 废弃明细不在手机端展示
  2090. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')
  2091. || trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID) {
  2092. $row = null;
  2093. continue;
  2094. }
  2095. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? 0);
  2096. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2097. if ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) {
  2098. $this->mprocMergePurchaseOrderIntoDetail($row, $poBySid[$sid]);
  2099. }
  2100. $poRow = ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) ? $poBySid[$sid] : null;
  2101. $oldSn = trim((string)($row['status_name'] ?? ''));
  2102. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, $poRow);
  2103. $row['status_name'] = $effectiveSn;
  2104. if ($statusNameCol !== null && $effectiveSn !== $oldSn && $row['eid'] > 0) {
  2105. $this->mprocPersistDetailStatusName((int)$row['eid'], $statusNameCol, $effectiveSn);
  2106. }
  2107. $listTab = $this->mprocResolveListTabForRow($row, $poRow, $effectiveSn);
  2108. $row['mproc_list_tab'] = $listTab;
  2109. $row['mproc_is_rfq'] = ((int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0) < 0) ? 1 : 0;
  2110. if ((int)$row['mproc_is_rfq'] === 1) {
  2111. // 手工询价不展示招标/交货截止,也不走开标截止逻辑
  2112. $row['mproc_bid_deadline'] = '';
  2113. $row['mproc_bid_deadline_display'] = '';
  2114. $row['mproc_delivery_deadline'] = '';
  2115. $row['mproc_delivery_deadline_display'] = '';
  2116. $row['mproc_deadline_reached'] = 0;
  2117. $row['mproc_bid_open_verified'] = 0;
  2118. $row['mproc_pick_result'] = '';
  2119. } else {
  2120. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  2121. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  2122. $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow($poRow, $row) ? 1 : 0;
  2123. }
  2124. if ($row['mproc_pick_result'] !== '') {
  2125. $row['mproc_done_label'] = $row['mproc_pick_result'];
  2126. } elseif ($this->mprocIsDoneListTab($listTab) && (
  2127. (int)$row['mproc_deadline_reached'] === 1
  2128. || (int)$row['mproc_bid_open_verified'] === 1
  2129. )) {
  2130. $row['mproc_done_label'] = '已截止';
  2131. } else {
  2132. $row['mproc_done_label'] = '';
  2133. }
  2134. // status_name 由库表/后端维护,不在此根据 amount 覆盖
  2135. if (!isset($row['status_name']) || $row['status_name'] === null) {
  2136. $row['status_name'] = '';
  2137. } else {
  2138. $row['status_name'] = trim((string)$row['status_name']);
  2139. }
  2140. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  2141. $am = $row['amount'] ?? null;
  2142. if ($am === null || $am === '' || (is_string($am) && trim($am) === '')) {
  2143. $row['amount_display'] = '';
  2144. } else {
  2145. $row['amount_display'] = is_scalar($am) ? (string)$am : '';
  2146. }
  2147. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2148. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  2149. $row['delivery_display'] = $m[1];
  2150. } elseif ($dv !== '') {
  2151. $row['delivery_display'] = $dv;
  2152. } else {
  2153. $row['delivery_display'] = '';
  2154. }
  2155. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  2156. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  2157. $this->mprocEnrichLeadDaysDisplay($row);
  2158. if ((int)$row['mproc_is_rfq'] === 1) {
  2159. $row['mproc_bid_deadline'] = '';
  2160. $row['mproc_bid_deadline_display'] = '';
  2161. $row['mproc_delivery_deadline'] = '';
  2162. $row['mproc_delivery_deadline_display'] = '';
  2163. } else {
  2164. $this->mprocEnrichOrderDeadlineDisplay($row);
  2165. }
  2166. $row['mproc_fill_hint'] = '';
  2167. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  2168. $row['mproc_remark'] = $this->mprocResolveDetailRemark($row);
  2169. }
  2170. unset($row);
  2171. $rows = array_values(array_filter($rows, function ($r) {
  2172. return is_array($r);
  2173. }));
  2174. // 同一供应商同一工序若有多条有效明细(重复下发),只保留最新一条
  2175. $rows = $this->mprocDedupeDetailRowsByCompanyProcess($rows);
  2176. // 始终按 Tab 过滤(含搜索):未中标/已截止等只出现在「已完成」
  2177. $rows = array_values(array_filter($rows, function ($r) use ($tab) {
  2178. return is_array($r) && trim((string)($r['mproc_list_tab'] ?? '')) === $tab;
  2179. }));
  2180. // 「已完成」仅保留近三个月(按招标截止日,缺省则交货截止/创建时间)
  2181. if ($this->mprocIsDoneListTab((string)$tab)) {
  2182. $rows = array_values(array_filter($rows, function ($r) {
  2183. return is_array($r) && $this->mprocIsWithinRecentMonths($r, 3);
  2184. }));
  2185. }
  2186. // 按招标截止日期排序:未提交/已提交截止近的在前;已完成最近截止的在前
  2187. $rows = $this->mprocSortRowsByBidDeadline($rows, $this->mprocIsDoneListTab((string)$tab) ? 'desc' : 'asc');
  2188. $groups = $this->mprocGroupRowsByOrder($rows);
  2189. return [
  2190. 'rows' => $rows ?: [],
  2191. 'groups' => $groups ?: [],
  2192. 'done_no_status' => (int)($statusNameCol === null),
  2193. ];
  2194. }
  2195. /**
  2196. * 按招标截止时间排序(无截止时间的排最后)
  2197. *
  2198. * @param array<int, array<string, mixed>> $rows
  2199. * @param string $dir asc|desc
  2200. * @return array<int, array<string, mixed>>
  2201. */
  2202. protected function mprocSortRowsByBidDeadline(array $rows, string $dir = 'asc'): array
  2203. {
  2204. $dir = strtolower($dir) === 'desc' ? 'desc' : 'asc';
  2205. usort($rows, function ($a, $b) use ($dir) {
  2206. $ta = $this->mprocBidDeadlineSortTs(is_array($a) ? $a : []);
  2207. $tb = $this->mprocBidDeadlineSortTs(is_array($b) ? $b : []);
  2208. $ha = $ta > 0;
  2209. $hb = $tb > 0;
  2210. if ($ha !== $hb) {
  2211. return $ha ? -1 : 1;
  2212. }
  2213. if ($ha && $ta !== $tb) {
  2214. return $dir === 'desc' ? ($tb <=> $ta) : ($ta <=> $tb);
  2215. }
  2216. $ida = (int)($a['eid'] ?? $a['id'] ?? 0);
  2217. $idb = (int)($b['eid'] ?? $b['id'] ?? 0);
  2218. return $idb <=> $ida;
  2219. });
  2220. return array_values($rows);
  2221. }
  2222. /**
  2223. * @param array<string, mixed> $row
  2224. */
  2225. protected function mprocBidDeadlineSortTs(array $row): int
  2226. {
  2227. $raw = trim((string)($row['mproc_bid_deadline'] ?? $row['sys_rq'] ?? $row['SYS_RQ'] ?? ''));
  2228. if ($raw === '') {
  2229. $raw = trim((string)($row['mproc_bid_deadline_display'] ?? ''));
  2230. }
  2231. if ($raw === '') {
  2232. return 0;
  2233. }
  2234. $ts = strtotime(str_replace('T', ' ', $raw));
  2235. return ($ts !== false && $ts > 0) ? (int)$ts : 0;
  2236. }
  2237. /**
  2238. * 是否属于近 N 个月(优先招标截止,其次交货截止,再次创建/更新时间)
  2239. *
  2240. * @param array<string, mixed> $row
  2241. */
  2242. protected function mprocIsWithinRecentMonths(array $row, int $months = 3): bool
  2243. {
  2244. $months = max(1, $months);
  2245. $since = strtotime(date('Y-m-d 00:00:00', strtotime('-' . $months . ' months')));
  2246. if ($since === false) {
  2247. return true;
  2248. }
  2249. $candidates = [
  2250. $row['mproc_bid_deadline'] ?? '',
  2251. $row['sys_rq'] ?? '',
  2252. $row['SYS_RQ'] ?? '',
  2253. $row['mproc_bid_deadline_display'] ?? '',
  2254. $row['mproc_delivery_deadline'] ?? '',
  2255. $row['delivery_deadline'] ?? '',
  2256. $row['mproc_delivery_deadline_display'] ?? '',
  2257. $row['createtime'] ?? '',
  2258. $row['updatetime'] ?? '',
  2259. ];
  2260. foreach ($candidates as $raw) {
  2261. $raw = trim((string)$raw);
  2262. if ($raw === '' || stripos($raw, '0000-00-00') === 0) {
  2263. continue;
  2264. }
  2265. $ts = strtotime(str_replace('T', ' ', $raw));
  2266. if ($ts === false || $ts <= 0) {
  2267. continue;
  2268. }
  2269. return $ts >= $since;
  2270. }
  2271. return false;
  2272. }
  2273. /**
  2274. * 同一供应商 + 同一工序只保留一条明细(优先 id 更大的最新记录)
  2275. *
  2276. * @param array<int, array<string, mixed>> $rows
  2277. * @return array<int, array<string, mixed>>
  2278. */
  2279. protected function mprocDedupeDetailRowsByCompanyProcess(array $rows): array
  2280. {
  2281. $best = [];
  2282. $orderKeys = [];
  2283. foreach ($rows as $row) {
  2284. if (!is_array($row)) {
  2285. continue;
  2286. }
  2287. $cn = trim((string)($row['company_name'] ?? ''));
  2288. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2289. $eid = (int)($row['eid'] ?? $row['id'] ?? $row['ID'] ?? 0);
  2290. if ($this->mprocIsValidScydgyRowId($sid)) {
  2291. $key = $cn . '|sid:' . $sid;
  2292. } else {
  2293. $key = $cn . '|eid:' . $eid;
  2294. }
  2295. if (!isset($best[$key])) {
  2296. $best[$key] = $row;
  2297. $orderKeys[] = $key;
  2298. continue;
  2299. }
  2300. $prevEid = (int)($best[$key]['eid'] ?? $best[$key]['id'] ?? $best[$key]['ID'] ?? 0);
  2301. if ($eid > $prevEid) {
  2302. $best[$key] = $row;
  2303. }
  2304. }
  2305. $out = [];
  2306. foreach ($orderKeys as $key) {
  2307. if (isset($best[$key])) {
  2308. $out[] = $best[$key];
  2309. }
  2310. }
  2311. return $out;
  2312. }
  2313. /**
  2314. * status_name → 手机端左侧 Tab
  2315. */
  2316. protected function mprocStatusNameToListTab(string $statusName): string
  2317. {
  2318. $map = ['未提交' => 'draft', '已提交' => 'submitted', '已完成' => 'done', '未通过' => 'done', '已废弃' => 'done'];
  2319. $sn = trim($statusName);
  2320. return isset($map[$sn]) ? $map[$sn] : '';
  2321. }
  2322. /**
  2323. * 短信/邮件 focus_eid 应落在的列表 Tab
  2324. */
  2325. protected function mprocResolveListTabForFocusEid(int $focusEid, array $user): string
  2326. {
  2327. if ($focusEid <= 0) {
  2328. return '';
  2329. }
  2330. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2331. if ($idCol === null) {
  2332. return '';
  2333. }
  2334. try {
  2335. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  2336. $qw = $this->mprocListWhereForLoginUser($user);
  2337. if ($qw !== []) {
  2338. $qrow->where($qw);
  2339. }
  2340. $dr = $qrow->find();
  2341. } catch (\Throwable $e) {
  2342. $dr = null;
  2343. }
  2344. if (!is_array($dr) || $dr === []) {
  2345. return '';
  2346. }
  2347. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  2348. $po = null;
  2349. if ($this->mprocIsValidScydgyRowId($sid)) {
  2350. try {
  2351. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2352. } catch (\Throwable $e) {
  2353. $po = null;
  2354. }
  2355. }
  2356. return $this->mprocResolveListTabForRow(
  2357. $dr,
  2358. is_array($po) ? $po : null,
  2359. $this->mprocResolveEffectiveStatusName($dr, is_array($po) ? $po : null)
  2360. );
  2361. }
  2362. /**
  2363. * 短信/邮件直达链接:确保 focus 对应明细出现在当前列表(便于高亮定位)
  2364. *
  2365. * @param array<string, mixed> $bundle
  2366. * @param array<string, mixed> $user
  2367. * @return array<string, mixed>
  2368. */
  2369. protected function mprocEnsureFocusRowInList(
  2370. array $bundle,
  2371. int $focusEid,
  2372. array $user,
  2373. $statusNameCol,
  2374. string $tab = 'draft',
  2375. string $q = ''
  2376. ): array {
  2377. if ($focusEid <= 0) {
  2378. return $bundle;
  2379. }
  2380. $rows = isset($bundle['rows']) && is_array($bundle['rows']) ? $bundle['rows'] : [];
  2381. $foundIdx = -1;
  2382. foreach ($rows as $idx => $r) {
  2383. if (!is_array($r)) {
  2384. continue;
  2385. }
  2386. if ((int)($r['eid'] ?? $r['id'] ?? $r['ID'] ?? 0) === $focusEid) {
  2387. $foundIdx = (int)$idx;
  2388. break;
  2389. }
  2390. }
  2391. if ($foundIdx > 0) {
  2392. $hit = $rows[$foundIdx];
  2393. array_splice($rows, $foundIdx, 1);
  2394. array_unshift($rows, $hit);
  2395. $bundle['rows'] = $rows;
  2396. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  2397. return $bundle;
  2398. }
  2399. if ($foundIdx === 0) {
  2400. return $bundle;
  2401. }
  2402. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2403. if ($idCol === null) {
  2404. return $bundle;
  2405. }
  2406. try {
  2407. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  2408. $qw = $this->mprocListWhereForLoginUser($user);
  2409. if ($qw !== []) {
  2410. $qrow->where($qw);
  2411. }
  2412. $dr = $qrow->find();
  2413. } catch (\Throwable $e) {
  2414. $dr = null;
  2415. }
  2416. if (!is_array($dr) || $dr === []) {
  2417. return $bundle;
  2418. }
  2419. $row = $dr;
  2420. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? $focusEid);
  2421. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2422. $poRow = null;
  2423. if ($this->mprocIsValidScydgyRowId($sid)) {
  2424. try {
  2425. $poRow = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2426. } catch (\Throwable $e) {
  2427. $poRow = null;
  2428. }
  2429. if (is_array($poRow)) {
  2430. $this->mprocMergePurchaseOrderIntoDetail($row, $poRow);
  2431. }
  2432. }
  2433. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($poRow) ? $poRow : null);
  2434. $rowTab = $this->mprocResolveListTabForRow($row, is_array($poRow) ? $poRow : null, $effectiveSn);
  2435. if ($rowTab !== '' && $rowTab !== $tab) {
  2436. return $bundle;
  2437. }
  2438. $row['status_name'] = $effectiveSn;
  2439. $listTab = $rowTab;
  2440. $row['mproc_list_tab'] = $listTab;
  2441. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  2442. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  2443. $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow(is_array($poRow) ? $poRow : null, $row) ? 1 : 0;
  2444. if ($row['mproc_pick_result'] !== '') {
  2445. $row['mproc_done_label'] = $row['mproc_pick_result'];
  2446. } elseif ($this->mprocIsDoneListTab($listTab) && (
  2447. (int)$row['mproc_deadline_reached'] === 1
  2448. || (int)$row['mproc_bid_open_verified'] === 1
  2449. )) {
  2450. $row['mproc_done_label'] = '已截止';
  2451. } else {
  2452. $row['mproc_done_label'] = '';
  2453. }
  2454. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  2455. $am = $row['amount'] ?? null;
  2456. $row['amount_display'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? '' : (is_scalar($am) ? (string)$am : '');
  2457. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2458. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  2459. $row['delivery_display'] = $m[1];
  2460. } elseif ($dv !== '') {
  2461. $row['delivery_display'] = $dv;
  2462. } else {
  2463. $row['delivery_display'] = '';
  2464. }
  2465. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  2466. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  2467. $this->mprocEnrichLeadDaysDisplay($row);
  2468. $this->mprocEnrichOrderDeadlineDisplay($row);
  2469. $row['mproc_fill_hint'] = '';
  2470. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  2471. array_unshift($rows, $row);
  2472. $bundle['rows'] = $rows;
  2473. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  2474. return $bundle;
  2475. }
  2476. /**
  2477. * 列表展示用「本次数量」:主表本次数量为空时回退显示 NGZL(工作量)
  2478. *
  2479. * @param array<string, mixed> $row
  2480. */
  2481. protected function mprocResolveDisplayThisQuantity(array $row): string
  2482. {
  2483. $qty = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  2484. if ($qty !== '') {
  2485. return $qty;
  2486. }
  2487. $gzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  2488. if ($gzl === null || $gzl === '') {
  2489. return '';
  2490. }
  2491. return is_scalar($gzl) ? trim((string)$gzl) : '';
  2492. }
  2493. /**
  2494. * 明细是否已填写单价或交货日期
  2495. *
  2496. * @param array<string, mixed> $row
  2497. */
  2498. protected function mprocDetailQuoteSubmitted(array $row): bool
  2499. {
  2500. $am = $row['amount'] ?? null;
  2501. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2502. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  2503. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  2504. return $amountFilled || $deliveryFilled;
  2505. }
  2506. /**
  2507. * 手机端列表 Tab 用 status_name;审批通过后主表 status=1 时按明细 status 纠偏
  2508. *
  2509. * @param array<string, mixed> $row
  2510. * @param array<string, mixed>|null $po
  2511. */
  2512. protected function mprocResolveEffectiveStatusName(array $row, ?array $po): string
  2513. {
  2514. $sn = trim((string)($row['status_name'] ?? ''));
  2515. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  2516. return $sn;
  2517. }
  2518. if (!is_array($po)) {
  2519. if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
  2520. return '已提交';
  2521. }
  2522. if ($sn !== '') {
  2523. return $sn;
  2524. }
  2525. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  2526. }
  2527. $poStatus = $po['status'] ?? $po['STATUS'] ?? '';
  2528. if (!ProcuremenStatus::isPoCompleted($poStatus)) {
  2529. // 库中仍写「未提交」但已填单价/交期:按已提交展示(手工单常见)
  2530. if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
  2531. return '已提交';
  2532. }
  2533. if ($sn !== '') {
  2534. return $sn;
  2535. }
  2536. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  2537. }
  2538. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  2539. if (ProcuremenStatus::isPodPicked($detailStatus)) {
  2540. return '已完成';
  2541. }
  2542. if ($sn === '已提交') {
  2543. return '未通过';
  2544. }
  2545. return $sn !== '' ? $sn : '未提交';
  2546. }
  2547. /**
  2548. * 将纠偏后的 status_name 写回库表(兼容历史已审批数据)
  2549. */
  2550. protected function mprocPersistDetailStatusName(int $detailId, string $statusNameCol, string $statusName): void
  2551. {
  2552. if ($detailId <= 0 || $statusNameCol === '') {
  2553. return;
  2554. }
  2555. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2556. if ($idCol === null || $idCol === '') {
  2557. return;
  2558. }
  2559. try {
  2560. Db::table('purchase_order_detail')->where($idCol, $detailId)->update([$statusNameCol => $statusName]);
  2561. } catch (\Throwable $e) {
  2562. }
  2563. }
  2564. /**
  2565. * 纠偏历史数据:主表已审批(status=1)但明细 status_name 仍为「已提交」
  2566. *
  2567. * @param array<string, mixed> $user
  2568. */
  2569. protected function mprocSyncLegacyApprovedStatusNames(array $user, string $statusNameCol): void
  2570. {
  2571. $userWhere = $this->mprocListWhereForLoginUser($user);
  2572. try {
  2573. $query = Db::table('purchase_order_detail')->where($statusNameCol, '已提交');
  2574. if ($userWhere !== []) {
  2575. $query->where($userWhere);
  2576. }
  2577. $candidates = $query->limit(200)->select();
  2578. } catch (\Throwable $e) {
  2579. return;
  2580. }
  2581. if (!is_array($candidates) || $candidates === []) {
  2582. return;
  2583. }
  2584. $sidList = [];
  2585. foreach ($candidates as $cr) {
  2586. if (!is_array($cr)) {
  2587. continue;
  2588. }
  2589. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  2590. if ($this->mprocIsValidScydgyRowId($sid)) {
  2591. $sidList[$sid] = true;
  2592. }
  2593. }
  2594. if ($sidList === []) {
  2595. return;
  2596. }
  2597. $poBySid = [];
  2598. try {
  2599. $poRows = Db::table('purchase_order')
  2600. ->where('scydgy_id', 'in', array_keys($sidList))
  2601. ->whereIn('status', ProcuremenStatus::poCompletedValues())
  2602. ->select();
  2603. if (is_array($poRows)) {
  2604. foreach ($poRows as $pr) {
  2605. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  2606. if ($this->mprocIsValidScydgyRowId($sidk)) {
  2607. $poBySid[$sidk] = $pr;
  2608. }
  2609. }
  2610. }
  2611. } catch (\Throwable $e) {
  2612. return;
  2613. }
  2614. if ($poBySid === []) {
  2615. return;
  2616. }
  2617. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2618. if ($idCol === null || $idCol === '') {
  2619. return;
  2620. }
  2621. foreach ($candidates as $cr) {
  2622. if (!is_array($cr)) {
  2623. continue;
  2624. }
  2625. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  2626. if (!isset($poBySid[$sid])) {
  2627. continue;
  2628. }
  2629. $detailId = (int)($cr[$idCol] ?? $cr['id'] ?? $cr['ID'] ?? 0);
  2630. if ($detailId <= 0) {
  2631. continue;
  2632. }
  2633. $targetSn = $this->mprocResolveEffectiveStatusName($cr, $poBySid[$sid]);
  2634. if ($targetSn === '已提交') {
  2635. continue;
  2636. }
  2637. $this->mprocPersistDetailStatusName($detailId, $statusNameCol, $targetSn);
  2638. }
  2639. }
  2640. /**
  2641. * 协助明细首页(需登录)
  2642. * GET:main_tab=orders|me,orders 时 tab=draft|submitted|done 对应 status_name:未提交|已提交|已完成;q 搜索词
  2643. */
  2644. public function index()
  2645. {
  2646. $user = $this->mprocGetUser();
  2647. if (!$user) {
  2648. $pendingFocus = $this->mprocReadFocusEidFromRequest();
  2649. if ($pendingFocus > 0) {
  2650. $this->mprocRememberFocusEid($pendingFocus);
  2651. }
  2652. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  2653. $safe = $this->mprocSanitizeRedirectUrl($uri);
  2654. if ($safe !== '' && $pendingFocus > 0 && stripos($safe, 'focus_eid') === false) {
  2655. $safe .= (strpos($safe, '?') !== false ? '&' : '?') . 'focus_eid=' . $pendingFocus;
  2656. }
  2657. if ($safe !== '') {
  2658. Session::set('mproc_intended_url', $safe);
  2659. }
  2660. $this->redirect($this->mprocBuildLoginUrl($safe));
  2661. return;
  2662. }
  2663. // 管理员进对应业务页,不进供应商报价列表
  2664. if (!empty($user['is_admin'])) {
  2665. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  2666. if ($jump === '') {
  2667. $this->mprocDropCurrentLogin();
  2668. $this->redirect(url('index/index/login'));
  2669. return;
  2670. }
  2671. $this->redirect($jump);
  2672. return;
  2673. }
  2674. $user = $this->mprocSyncSessionCustomerUser($user);
  2675. $tabParamRaw = $this->request->get('tab', null);
  2676. $hasExplicitTab = ($tabParamRaw !== null && trim((string)$tabParamRaw) !== '');
  2677. $tabParam = trim((string)($tabParamRaw ?? 'draft'));
  2678. $mainTab = trim((string)$this->request->get('main_tab', 'orders'));
  2679. // 旧地址 ?tab=me 表示「我的」
  2680. if ($tabParam === 'me') {
  2681. $mainTab = 'me';
  2682. }
  2683. if (!in_array($mainTab, ['orders', 'me'], true)) {
  2684. $mainTab = 'orders';
  2685. }
  2686. $tab = $tabParam === 'me' ? 'draft' : $this->mprocNormalizeListTab($tabParam);
  2687. $q = trim((string)$this->request->get('q', ''));
  2688. $mprocFocusEid = 0;
  2689. $focusEid = $this->mprocReadFocusEidFromRequest();
  2690. if ($focusEid > 0 && $mainTab === 'orders') {
  2691. $resolvedTab = $this->mprocResolveListTabForFocusEid($focusEid, $user);
  2692. // 用户已手动点了其他左侧 Tab:取消定位锁定,避免刷新又跳回
  2693. if ($hasExplicitTab && $resolvedTab !== '' && $resolvedTab !== $tab) {
  2694. Session::delete('mproc_focus_eid');
  2695. $focusEid = 0;
  2696. } else {
  2697. $mprocFocusEid = $focusEid;
  2698. // 仅邮件/短信直链且 URL 未带 tab 时,自动切到定位单所在 Tab
  2699. $focusFromUrl = (int)$this->request->param('focus_eid', 0) > 0;
  2700. if (!$focusFromUrl) {
  2701. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  2702. $focusFromUrl = $this->mprocParseFocusEidFromUriString($uri) > 0;
  2703. }
  2704. if ($focusFromUrl && trim((string)$q) === '' && !$hasExplicitTab) {
  2705. if ($resolvedTab !== '') {
  2706. $tab = $resolvedTab;
  2707. }
  2708. }
  2709. }
  2710. }
  2711. // 左侧 Tab 按 purchase_order_detail.status_name(未提交/已提交/已完成),与数值 status 无关
  2712. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2713. $profile = $this->mprocProfileForUser($user);
  2714. $this->view->assign('mprocMainTab', $mainTab);
  2715. $this->view->assign('mprocTab', $tab);
  2716. $this->view->assign('mprocIsRfqTab', $this->mprocIsRfqListTab($tab) ? 1 : 0);
  2717. $this->view->assign('mprocStatusTab', $this->mprocStatusFromListTab($tab));
  2718. $this->view->assign('mprocSearchQ', $q);
  2719. $this->view->assign('mprocProfile', $profile);
  2720. $this->view->assign('mprocIsAdmin', !empty($user['is_admin']) ? 1 : 0);
  2721. $cid = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  2722. $this->view->assign('mprocCanChangePwd', empty($user['is_admin']) && $cid > 0 ? 1 : 0);
  2723. $this->view->assign('mprocFocusEid', $mprocFocusEid);
  2724. $mprocFocusTab = $mprocFocusEid > 0 ? $this->mprocResolveListTabForFocusEid($mprocFocusEid, $user) : '';
  2725. $this->view->assign('mprocFocusTab', $mprocFocusTab);
  2726. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  2727. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  2728. if ($mainTab === 'me') {
  2729. $this->view->assign('rows', []);
  2730. return $this->view->fetch();
  2731. }
  2732. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  2733. if ($mprocFocusEid > 0) {
  2734. $bundle = $this->mprocEnsureFocusRowInList($bundle, $mprocFocusEid, $user, $statusNameCol, $tab, $q);
  2735. }
  2736. $this->view->assign('rows', $bundle['rows']);
  2737. $this->view->assign('groups', $bundle['groups'] ?? $this->mprocGroupRowsByOrder($bundle['rows']));
  2738. return $this->view->fetch();
  2739. }
  2740. /**
  2741. * 协助明细列表 JSON(需登录)
  2742. * main_tab=orders|me;orders 时 tab=draft|submitted|done、q=搜索词
  2743. */
  2744. public function mprocList()
  2745. {
  2746. $user = $this->mprocGetUser();
  2747. if (!$user) {
  2748. $this->error('请先登录', url('index/index/login'));
  2749. }
  2750. $user = $this->mprocSyncSessionCustomerUser($user);
  2751. $tabParam = trim((string)$this->request->request('tab', 'draft'));
  2752. $mainTab = trim((string)$this->request->request('main_tab', 'orders'));
  2753. if ($tabParam === 'me') {
  2754. $mainTab = 'me';
  2755. }
  2756. if (!in_array($mainTab, ['orders', 'me'], true)) {
  2757. $mainTab = 'orders';
  2758. }
  2759. $tab = $tabParam === 'me' ? 'draft' : $this->mprocNormalizeListTab($tabParam);
  2760. $q = trim((string)$this->request->request('q', ''));
  2761. if ($mainTab === 'me') {
  2762. // Jump::success($msg, $url, $data, …) 第二参是 URL,数据必须放第三参
  2763. $this->success('ok', '', [
  2764. 'main_tab' => 'me',
  2765. 'tab' => $tab,
  2766. 'rows' => [],
  2767. 'profile' => $this->mprocProfileForUser($user),
  2768. 'done_no_status' => 0,
  2769. ]);
  2770. }
  2771. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2772. if ((int)$this->request->request('clear_focus', 0) === 1) {
  2773. Session::delete('mproc_focus_eid');
  2774. $focusEid = 0;
  2775. $focusTab = '';
  2776. } else {
  2777. $focusEid = $this->mprocReadFocusEidFromRequest();
  2778. $focusTab = $focusEid > 0 ? $this->mprocResolveListTabForFocusEid($focusEid, $user) : '';
  2779. // 列表请求已指定 Tab,且与定位单所在 Tab 不同:视为用户离开锁定页
  2780. if ($focusEid > 0 && $focusTab !== '' && $focusTab !== $tab) {
  2781. Session::delete('mproc_focus_eid');
  2782. $focusEid = 0;
  2783. $focusTab = '';
  2784. }
  2785. }
  2786. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  2787. if ($focusEid > 0) {
  2788. $bundle = $this->mprocEnsureFocusRowInList($bundle, $focusEid, $user, $statusNameCol, $tab, $q);
  2789. }
  2790. $this->success('ok', '', array_merge([
  2791. 'main_tab' => 'orders',
  2792. 'tab' => $tab,
  2793. 'focus_tab' => $focusTab,
  2794. 'is_admin' => !empty($user['is_admin']) ? 1 : 0,
  2795. 'focus_eid' => $focusEid,
  2796. ], $bundle));
  2797. }
  2798. /**
  2799. * 登录页(手机号验证码 / 账号密码)
  2800. */
  2801. public function login()
  2802. {
  2803. $redirect = $this->mprocSanitizeRedirectUrl($this->request->get('redirect', ''));
  2804. $user = $this->mprocGetUser();
  2805. if ($user) {
  2806. $jump = $this->mprocBuildAfterLoginHomeUrl($user, $redirect);
  2807. if ($jump !== '') {
  2808. $this->redirect($jump);
  2809. return;
  2810. }
  2811. // 已登录但无手机端权限(其它后台账号):清会话,避免登录页↔自身 302 死循环
  2812. $this->mprocDropCurrentLogin();
  2813. }
  2814. if ($redirect !== '') {
  2815. Session::set('mproc_intended_url', $redirect);
  2816. }
  2817. $this->view->assign('mprocLoginRedirect', $redirect);
  2818. $this->view->assign('mprocCaptchaUrl', url('index/index/captcha'));
  2819. $this->view->assign('mprocCaptchaLen', (int)(Config::get('captcha.length') ?: 4));
  2820. return $this->view->fetch();
  2821. }
  2822. /**
  2823. * 图形验证码(手机号登录用)
  2824. */
  2825. public function captcha($id = '')
  2826. {
  2827. $captcha = new Captcha((array)Config::get('captcha'));
  2828. return $captcha->entry($id);
  2829. }
  2830. /**
  2831. * 发送登录验证码(POST:phone、captcha)
  2832. */
  2833. public function sendSms()
  2834. {
  2835. if (!$this->request->isPost()) {
  2836. $this->error('请使用 POST');
  2837. }
  2838. $phone = trim((string)$this->request->post('phone', ''));
  2839. $captcha = trim((string)$this->request->post('captcha', ''));
  2840. if (!preg_match('/^1\d{10}$/', $phone)) {
  2841. $this->error('请输入正确的11位手机号');
  2842. }
  2843. if ($captcha === '') {
  2844. $this->error('请输入图形验证码');
  2845. }
  2846. $cu = $this->mprocFindCustomerUserByMobile($phone);
  2847. $adminRow = $cu ? null : $this->mprocAdminRowByMobile($phone);
  2848. if (!$cu && !$adminRow) {
  2849. $this->error('账号或密码错误');
  2850. }
  2851. if ($adminRow) {
  2852. $probe = $this->mprocLoginPayloadFromAdmin($adminRow, 'sms');
  2853. if (!$this->mprocAdminHasAnyMobileAccess($probe)) {
  2854. $this->error('账号或密码错误');
  2855. }
  2856. }
  2857. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  2858. if (Cache::get('mproc_sms_wait_' . $phone)) {
  2859. $this->error('发送过于频繁,请稍后再试');
  2860. }
  2861. if (!Validate::is($captcha, 'captcha')) {
  2862. $this->error('图形验证码不正确');
  2863. }
  2864. $code = (string)random_int(100000, 999999);
  2865. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  2866. $ttl = max(60, min(600, $ttl));
  2867. Cache::set('mproc_code_' . $phone, $code, $ttl);
  2868. Cache::set('mproc_sms_wait_' . $phone, 1, $cd);
  2869. try {
  2870. $tpl = trim((string)Config::get('mproc.sms_login_template'));
  2871. if ($tpl === '') {
  2872. $tpl = '【可集达】您的验证码是{code}。如非本人操作,请忽略本短信';
  2873. }
  2874. $content = str_replace('{code}', $code, $tpl);
  2875. $this->mprocSmsSend($phone, $content);
  2876. } catch (\Exception $e) {
  2877. Cache::rm('mproc_code_' . $phone);
  2878. Cache::rm('mproc_sms_wait_' . $phone);
  2879. $this->error($e->getMessage());
  2880. }
  2881. $this->success('验证码已发送');
  2882. }
  2883. /**
  2884. * 验证码登录(POST:phone、code)
  2885. */
  2886. public function doLogin()
  2887. {
  2888. if (!$this->request->isPost()) {
  2889. $this->error('请使用 POST');
  2890. }
  2891. $phone = trim((string)$this->request->post('phone', ''));
  2892. $code = trim((string)$this->request->post('code', ''));
  2893. if (!preg_match('/^1\d{10}$/', $phone)) {
  2894. $this->error('手机号格式不正确');
  2895. }
  2896. if (!preg_match('/^\d{6}$/', $code)) {
  2897. $this->error('请输入6位验证码');
  2898. }
  2899. // 本地调试:application/extra/mproc.php 中配置 mock_sms_code 与输入一致时,不校验短信缓存(生产务必留空)
  2900. $mock = Config::get('mproc.mock_sms_code');
  2901. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2902. Cache::rm('mproc_code_' . $phone);
  2903. } else {
  2904. $cached = Cache::get('mproc_code_' . $phone);
  2905. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2906. $this->error('验证码错误或已过期');
  2907. }
  2908. Cache::rm('mproc_code_' . $phone);
  2909. }
  2910. $cu = $this->mprocFindCustomerUserByMobile($phone);
  2911. if ($cu) {
  2912. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'sms'));
  2913. return;
  2914. }
  2915. $adminRow = $this->mprocAdminRowByMobile($phone);
  2916. if ($adminRow) {
  2917. $payload = $this->mprocLoginPayloadFromAdmin($adminRow, 'sms');
  2918. if (!$this->mprocAdminHasAnyMobileAccess($payload)) {
  2919. $this->error('账号或密码错误');
  2920. }
  2921. $this->mprocFinishLogin($payload);
  2922. return;
  2923. }
  2924. $this->error('账号或密码错误');
  2925. }
  2926. /**
  2927. * 用本地保存的 token 恢复登录态(POST:mproc_token)
  2928. */
  2929. public function mprocRestore()
  2930. {
  2931. if (!$this->request->isPost()) {
  2932. $this->error('请使用 POST');
  2933. }
  2934. $token = $this->mprocReadTokenFromRequest();
  2935. $user = null;
  2936. if ($token !== '') {
  2937. $user = $this->mprocLoadUserByToken($token);
  2938. }
  2939. if (!$user) {
  2940. $user = $this->mprocUserFromRememberCookie();
  2941. if ($user) {
  2942. $token = $this->mprocPackSignedAuthToken($user);
  2943. }
  2944. }
  2945. if (!$user) {
  2946. $this->error('登录已过期,请重新登录', url('index/index/login'));
  2947. }
  2948. $token = $this->mprocTouchLoginState($user, $token !== '' ? $token : $this->mprocPackSignedAuthToken($user));
  2949. $redirect = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  2950. $jump = $this->mprocBuildAfterLoginHomeUrl($user, $redirect);
  2951. if ($jump === '') {
  2952. $this->mprocClearLogin($token);
  2953. $this->error('账号或密码错误', url('index/index/login'));
  2954. }
  2955. $this->success('ok', $jump, [
  2956. 'mproc_token' => $token,
  2957. 'keep_hours' => $this->mprocKeepHours(),
  2958. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  2959. ]);
  2960. }
  2961. /**
  2962. * 账号密码登录(POST:username、password)
  2963. * 先 customer(account),未命中再 admin;admin 密码规则同 FastAdmin Auth::login
  2964. */
  2965. public function doLoginPwd()
  2966. {
  2967. if (!$this->request->isPost()) {
  2968. $this->error('请使用 POST');
  2969. }
  2970. $username = trim((string)$this->request->post('username', ''));
  2971. $password = (string)$this->request->post('password', '');
  2972. if ($username === '' || $password === '') {
  2973. $this->error('请输入账号和密码');
  2974. }
  2975. $cu = $this->mprocFindCustomerUserByUsername($username);
  2976. if ($cu) {
  2977. if (!$this->mprocVerifyCustomerUserPassword($cu, $password)) {
  2978. $this->error('账号或密码错误');
  2979. }
  2980. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'pwd'));
  2981. }
  2982. // 管理员:表 admin
  2983. $row = null;
  2984. try {
  2985. $row = Db::name('admin')
  2986. ->field('id,username,password,salt,status,loginfailure,updatetime,mobile')
  2987. ->where('username', $username)
  2988. ->find();
  2989. } catch (\Throwable $e) {
  2990. $row = null;
  2991. }
  2992. if (!$row || !is_array($row)) {
  2993. $this->error('账号或密码错误');
  2994. }
  2995. $id = (int)($row['id'] ?? 0);
  2996. if (($row['status'] ?? '') == 'hidden') {
  2997. $this->error('该账号已禁用');
  2998. }
  2999. if (Config::get('fastadmin.login_failure_retry') && (int)($row['loginfailure'] ?? 0) >= 10 && time() - (int)($row['updatetime'] ?? 0) < 86400) {
  3000. $this->error('登录失败次数过多,请24小时后再试');
  3001. }
  3002. $salt = (string)($row['salt'] ?? '');
  3003. $hashStored = (string)($row['password'] ?? '');
  3004. $hashInput = md5(md5($password) . $salt);
  3005. if ($hashStored === '' || $hashInput !== $hashStored) {
  3006. if ($id > 0) {
  3007. try {
  3008. Db::name('admin')->where('id', $id)->update([
  3009. 'loginfailure' => (int)($row['loginfailure'] ?? 0) + 1,
  3010. 'updatetime' => time(),
  3011. ]);
  3012. } catch (\Throwable $e) {
  3013. }
  3014. }
  3015. $this->error('账号或密码错误');
  3016. }
  3017. if ($id > 0) {
  3018. try {
  3019. Db::name('admin')->where('id', $id)->update([
  3020. 'loginfailure' => 0,
  3021. 'updatetime' => time(),
  3022. ]);
  3023. } catch (\Throwable $e) {
  3024. }
  3025. }
  3026. $payload = $this->mprocLoginPayloadFromAdmin($row, 'pwd');
  3027. if (!$this->mprocAdminHasAnyMobileAccess($payload)) {
  3028. $this->error('账号或密码错误');
  3029. }
  3030. $this->mprocFinishLogin($payload);
  3031. }
  3032. /**
  3033. * 是否允许当前登录用户修改该条 purchase_order_detail 的金额、交期
  3034. * 仅普通用户(customer)可改;管理员(admin)仅可查看
  3035. */
  3036. protected function mprocCanEditRow(array $user, array $row, ?array $po = null)
  3037. {
  3038. if (!empty($user['is_admin'])) {
  3039. return false;
  3040. }
  3041. $sn = trim((string)($row['status_name'] ?? ''));
  3042. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  3043. return false;
  3044. }
  3045. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3046. // 手工询价无招标截止/开标限制
  3047. if ($sid >= 0) {
  3048. if ($this->mprocIsQuoteDeadlineReachedForPo($po)) {
  3049. return false;
  3050. }
  3051. if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)) {
  3052. return false;
  3053. }
  3054. }
  3055. $uCo = trim((string)($user['company_name'] ?? ''));
  3056. if ($uCo === '') {
  3057. $uPhone = trim((string)($user['phone'] ?? ''));
  3058. if ($uPhone !== '') {
  3059. $uCo = $this->mprocResolveCompanyForLoginPhone($uPhone);
  3060. }
  3061. }
  3062. $rCo = trim((string)($row['company_name'] ?? ''));
  3063. if ($uCo !== '' && $rCo !== '' && strcmp($rCo, $uCo) === 0) {
  3064. return true;
  3065. }
  3066. $uPhone = trim((string)($user['phone'] ?? ''));
  3067. $rPhone = trim((string)($row['phone'] ?? ''));
  3068. return $uPhone !== '' && $rPhone !== '' && strcasecmp($rPhone, $uPhone) === 0;
  3069. }
  3070. /**
  3071. * 明细行对应最高限价(来自 purchase_order;无或无效则返回 null,不校验)
  3072. *
  3073. * @param array<string, mixed> $detailRow
  3074. */
  3075. protected function mprocResolveCeilingPriceForDetailRow(array $detailRow): ?float
  3076. {
  3077. $sid = (int)($detailRow['scydgy_id'] ?? $detailRow['SCYDGY_ID'] ?? 0);
  3078. $raw = trim((string)($detailRow['ceilingPrice'] ?? $detailRow['ceiling_price'] ?? ''));
  3079. if ($raw === '' && $this->mprocIsValidScydgyRowId($sid)) {
  3080. try {
  3081. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3082. } catch (\Throwable $e) {
  3083. $po = null;
  3084. }
  3085. if (is_array($po)) {
  3086. $pl = array_change_key_case($po, CASE_LOWER);
  3087. foreach (['ceilingprice', 'ceiling_price'] as $ck) {
  3088. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  3089. $raw = trim((string)$pl[$ck]);
  3090. break;
  3091. }
  3092. }
  3093. if ($raw === '') {
  3094. $raw = trim((string)($po['ceilingPrice'] ?? $po['ceiling_price'] ?? ''));
  3095. }
  3096. }
  3097. }
  3098. if ($raw === '' || !preg_match('/^-?\d+(\.\d{1,5})?$/', $raw)) {
  3099. return null;
  3100. }
  3101. return (float)$raw;
  3102. }
  3103. protected function mprocFormatCeilingPriceDisplay(float $n): string
  3104. {
  3105. $s = rtrim(rtrim(sprintf('%.5F', $n), '0'), '.');
  3106. return $s === '' ? '0' : $s;
  3107. }
  3108. /**
  3109. * 确保 purchase_order_detail.lead_days 字段存在
  3110. */
  3111. protected function mprocEnsureLeadDaysColumn(): void
  3112. {
  3113. static $done = false;
  3114. if ($done) {
  3115. return;
  3116. }
  3117. $done = true;
  3118. try {
  3119. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_detail` LIKE 'lead_days'");
  3120. if (empty($cols)) {
  3121. Db::execute(
  3122. "ALTER TABLE `purchase_order_detail` ADD COLUMN `lead_days` int(10) unsigned DEFAULT NULL COMMENT '预估工期(天)' AFTER `delivery`"
  3123. );
  3124. }
  3125. } catch (\Throwable $e) {
  3126. // 忽略:保存时再按列是否存在处理
  3127. }
  3128. }
  3129. /**
  3130. * 交货日期相对今天的天数(可负数,调用方自行 clamp)
  3131. */
  3132. protected function mprocCalcLeadDaysFromDeliveryYmd(string $ymd): ?int
  3133. {
  3134. if (!preg_match('/^(\d{4}-\d{2}-\d{2})/', $ymd, $m)) {
  3135. return null;
  3136. }
  3137. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  3138. $t2 = strtotime($m[1] . ' 00:00:00');
  3139. if ($t1 === false || $t2 === false) {
  3140. return null;
  3141. }
  3142. return (int)round(($t2 - $t1) / 86400);
  3143. }
  3144. protected function mprocAddDaysToToday(int $days): string
  3145. {
  3146. $base = strtotime(date('Y-m-d') . ' 00:00:00');
  3147. if ($base === false) {
  3148. $base = time();
  3149. }
  3150. return date('Y-m-d', strtotime('+' . max(0, $days) . ' days', $base));
  3151. }
  3152. /**
  3153. * @param array<string, mixed> $row
  3154. */
  3155. protected function mprocEnrichLeadDaysDisplay(array &$row): void
  3156. {
  3157. $days = null;
  3158. $raw = $row['lead_days'] ?? null;
  3159. if ($raw !== null && $raw !== '' && is_numeric($raw)) {
  3160. $days = max(0, (int)$raw);
  3161. } else {
  3162. $dd = trim((string)($row['delivery_display'] ?? ''));
  3163. if ($dd === '') {
  3164. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  3165. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  3166. $dd = $m[1];
  3167. }
  3168. }
  3169. if ($dd !== '') {
  3170. $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($dd);
  3171. if ($calc !== null) {
  3172. $days = max(0, $calc);
  3173. }
  3174. }
  3175. }
  3176. if ($days !== null) {
  3177. $row['lead_days'] = $days;
  3178. $row['lead_days_display'] = (string)$days;
  3179. $row['lead_days_missing'] = 0;
  3180. } else {
  3181. $row['lead_days'] = '';
  3182. $row['lead_days_display'] = '';
  3183. $row['lead_days_missing'] = 1;
  3184. }
  3185. }
  3186. /**
  3187. * 保存单条协助明细的金额、交期、工期(内部)
  3188. *
  3189. * @param array<string, mixed> $user
  3190. * @param int $id
  3191. * @param string $amountRaw
  3192. * @param string $deliveryRaw
  3193. * @param string|int|null $leadDaysRaw
  3194. * @return string 工序名(用于批量错误提示)
  3195. */
  3196. protected function mprocSaveDetailQuote(array $user, int $id, string $amountRaw, string $deliveryRaw, $leadDaysRaw = null): string
  3197. {
  3198. if ($id <= 0) {
  3199. throw new \InvalidArgumentException('参数错误');
  3200. }
  3201. $row = null;
  3202. try {
  3203. $row = Db::table('purchase_order_detail')->where('id', $id)->find();
  3204. if (!$row) {
  3205. $row = Db::table('purchase_order_detail')->where('ID', $id)->find();
  3206. }
  3207. } catch (\Throwable $e) {
  3208. $row = null;
  3209. }
  3210. if (!$row || !is_array($row)) {
  3211. throw new \InvalidArgumentException('记录不存在');
  3212. }
  3213. $gymc = trim((string)($row['CGYMC'] ?? $row['cgymc'] ?? ''));
  3214. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3215. $po = null;
  3216. if ($this->mprocIsValidScydgyRowId($sid)) {
  3217. try {
  3218. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3219. } catch (\Throwable $e) {
  3220. $po = null;
  3221. }
  3222. if (is_array($po)) {
  3223. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  3224. if ($gymc === '') {
  3225. $gymc = trim((string)($row['CGYMC'] ?? ''));
  3226. }
  3227. }
  3228. }
  3229. $label = $gymc !== '' ? ('工序「' . $gymc . '」') : ('记录#' . $id);
  3230. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  3231. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  3232. throw new \InvalidArgumentException($label . '已结束,不能再修改');
  3233. }
  3234. $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, $label, $row);
  3235. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  3236. if (!empty($user['is_admin'])) {
  3237. throw new \InvalidArgumentException('当前账号仅可查看,不能修改单价与交货日期');
  3238. }
  3239. // 截止后 / 已开标 canEdit=false,统一给明确文案
  3240. if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
  3241. throw new \InvalidArgumentException($label . '已开标验证,不可再提交');
  3242. }
  3243. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  3244. throw new \InvalidArgumentException($label . '已超过招标截止时间,不可再提交');
  3245. }
  3246. throw new \InvalidArgumentException($label . '无权修改');
  3247. }
  3248. $this->mprocEnsureLeadDaysColumn();
  3249. $amountRaw = trim($amountRaw);
  3250. $deliveryRaw = trim($deliveryRaw);
  3251. $leadRaw = trim((string)($leadDaysRaw ?? ''));
  3252. $hasAmt = $amountRaw !== '';
  3253. $hasLead = $leadRaw !== '';
  3254. $hasDel = $deliveryRaw !== '';
  3255. $isManualRfq = ($sid < 0);
  3256. if ($isManualRfq) {
  3257. // 手工询价:只需填写单价
  3258. if (!$hasAmt) {
  3259. throw new \InvalidArgumentException($label . '请填写单价');
  3260. }
  3261. } else {
  3262. $filledCount = ($hasAmt ? 1 : 0) + ($hasLead ? 1 : 0) + ($hasDel ? 1 : 0);
  3263. if ($filledCount === 0) {
  3264. throw new \InvalidArgumentException($label . '请填写单价、工期、交期');
  3265. }
  3266. if ($filledCount < 3) {
  3267. if (!$hasAmt) {
  3268. throw new \InvalidArgumentException($label . '请填写单价');
  3269. }
  3270. if (!$hasLead) {
  3271. throw new \InvalidArgumentException($label . '请填写工期');
  3272. }
  3273. throw new \InvalidArgumentException($label . '请填写交期');
  3274. }
  3275. }
  3276. $leadDays = null;
  3277. if ($leadRaw !== '') {
  3278. if (!preg_match('/^\d+$/', $leadRaw)) {
  3279. throw new \InvalidArgumentException($label . '工期须为非负整数(天)');
  3280. }
  3281. $leadDays = (int)$leadRaw;
  3282. }
  3283. $data = [];
  3284. if ($amountRaw === '') {
  3285. $data['amount'] = null;
  3286. } else {
  3287. if (!preg_match('/^\d+(\.\d{1,5})?$/', $amountRaw)) {
  3288. throw new \InvalidArgumentException($label . '单价格式不正确,最多五位小数');
  3289. }
  3290. if ((float)$amountRaw <= 0) {
  3291. throw new \InvalidArgumentException($label . '单价必须大于0');
  3292. }
  3293. $ceilingLimit = $this->mprocResolveCeilingPriceForDetailRow($row);
  3294. if ($ceilingLimit !== null && (float)$amountRaw > $ceilingLimit) {
  3295. throw new \InvalidArgumentException(
  3296. $label . '单价不能超过最高限价 ' . $this->mprocFormatCeilingPriceDisplay($ceilingLimit)
  3297. );
  3298. }
  3299. $data['amount'] = $amountRaw;
  3300. }
  3301. if ($deliveryRaw === '') {
  3302. $data['delivery'] = null;
  3303. } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryRaw)) {
  3304. $existingDel = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  3305. $timePart = date('H:i:s');
  3306. if ($existingDel !== '') {
  3307. $tsEx = strtotime(str_replace('T', ' ', $existingDel));
  3308. if ($tsEx !== false) {
  3309. $hms = date('H:i:s', $tsEx);
  3310. if ($hms !== '00:00:00') {
  3311. $timePart = $hms;
  3312. }
  3313. }
  3314. }
  3315. $data['delivery'] = $deliveryRaw . ' ' . $timePart;
  3316. } else {
  3317. $deliveryRaw = str_replace('T', ' ', $deliveryRaw);
  3318. $ts = strtotime($deliveryRaw);
  3319. if ($ts === false) {
  3320. throw new \InvalidArgumentException($label . '交期时间格式不正确');
  3321. }
  3322. $data['delivery'] = date('Y-m-d H:i:s', $ts);
  3323. }
  3324. // 工期 ↔ 交货日期互通:仅填工期则推交期;仅填交期则推工期
  3325. if (($data['delivery'] === null || $data['delivery'] === '') && $leadDays !== null) {
  3326. $data['delivery'] = $this->mprocAddDaysToToday($leadDays) . ' ' . date('H:i:s');
  3327. }
  3328. if ($leadDays === null && !empty($data['delivery'])) {
  3329. $ymd = substr((string)$data['delivery'], 0, 10);
  3330. $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($ymd);
  3331. if ($calc !== null) {
  3332. $leadDays = max(0, $calc);
  3333. }
  3334. }
  3335. $data['lead_days'] = $leadDays;
  3336. $dcCol = $this->mprocResolveProcuremenColumn(['delivery_createtime', 'deliverycreatetime']);
  3337. if ($dcCol !== null) {
  3338. $shouldStampQuoteTime = false;
  3339. if (array_key_exists('delivery', $data) && $data['delivery'] !== null && $data['delivery'] !== '') {
  3340. $shouldStampQuoteTime = true;
  3341. }
  3342. // 手工询价只填单价:有单价也记报价时间
  3343. if ($isManualRfq && array_key_exists('amount', $data) && $data['amount'] !== null && $data['amount'] !== '') {
  3344. $shouldStampQuoteTime = true;
  3345. }
  3346. if ($shouldStampQuoteTime) {
  3347. $data[$dcCol] = date('Y-m-d H:i:s');
  3348. }
  3349. }
  3350. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3351. if ($upCol !== null) {
  3352. $data[$upCol] = date('Y-m-d H:i:s');
  3353. }
  3354. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  3355. if ($statusNameCol !== null) {
  3356. $curSn = '';
  3357. foreach ($row as $k => $v) {
  3358. if (strcasecmp((string)$k, $statusNameCol) === 0) {
  3359. $curSn = trim((string)$v);
  3360. break;
  3361. }
  3362. }
  3363. if ($curSn !== '已完成') {
  3364. $effAm = array_key_exists('amount', $data) ? $data['amount'] : ($row['amount'] ?? null);
  3365. $effDv = array_key_exists('delivery', $data) ? trim((string)$data['delivery']) : trim((string)($row['delivery'] ?? ''));
  3366. $amountFilled = !($effAm === null || $effAm === '' || (is_string($effAm) && trim($effAm) === ''));
  3367. $deliveryFilled = ($effDv !== '' && !preg_match('/^0000-00-00/i', $effDv));
  3368. $data[$statusNameCol] = ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3369. }
  3370. }
  3371. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  3372. $pkVal = (int)($row[$pkField] ?? $id);
  3373. try {
  3374. $aff = Db::table('purchase_order_detail')->where($pkField, $pkVal)->update($data);
  3375. } catch (\Throwable $e) {
  3376. $msg = $e->getMessage();
  3377. if (stripos($msg, 'Unknown column') !== false) {
  3378. $msg = '请确认数据表 purchase_order_detail 已包含 amount、delivery、lead_days 字段';
  3379. }
  3380. throw new \RuntimeException('保存失败:' . $msg);
  3381. }
  3382. if ($aff === false) {
  3383. throw new \RuntimeException($label . '保存失败');
  3384. }
  3385. return $gymc;
  3386. }
  3387. /**
  3388. * 保存同订单号+供应商下的整单备注(写入该组全部明细行)
  3389. *
  3390. * @param array<string, mixed> $user
  3391. * @param int[] $detailIds 本次保存涉及的明细 ID
  3392. * @param string $remarkRaw
  3393. */
  3394. protected function mprocSaveOrderGroupRemark(array $user, array $detailIds, string $remarkRaw): void
  3395. {
  3396. $remarkCol = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
  3397. if ($remarkCol === null) {
  3398. return;
  3399. }
  3400. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3401. if ($detailIds === []) {
  3402. return;
  3403. }
  3404. $anchorId = $detailIds[0];
  3405. $row = null;
  3406. try {
  3407. $row = Db::table('purchase_order_detail')->where('id', $anchorId)->find();
  3408. if (!$row) {
  3409. $row = Db::table('purchase_order_detail')->where('ID', $anchorId)->find();
  3410. }
  3411. } catch (\Throwable $e) {
  3412. $row = null;
  3413. }
  3414. if (!$row || !is_array($row)) {
  3415. throw new \InvalidArgumentException('记录不存在');
  3416. }
  3417. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3418. $po = null;
  3419. if ($this->mprocIsValidScydgyRowId($sid)) {
  3420. try {
  3421. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3422. } catch (\Throwable $e) {
  3423. $po = null;
  3424. }
  3425. if (is_array($po)) {
  3426. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  3427. }
  3428. }
  3429. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  3430. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  3431. throw new \InvalidArgumentException('订单已结束,不能再修改备注');
  3432. }
  3433. $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, '', $row);
  3434. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  3435. if (!empty($user['is_admin'])) {
  3436. throw new \InvalidArgumentException('当前账号仅可查看,不能修改备注');
  3437. }
  3438. if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
  3439. throw new \InvalidArgumentException('已开标验证,不可再提交');
  3440. }
  3441. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  3442. throw new \InvalidArgumentException('已超过招标截止时间,不可再提交');
  3443. }
  3444. throw new \InvalidArgumentException('无权修改备注');
  3445. }
  3446. $ccydhCol = $this->mprocResolveProcuremenColumn(['ccydh']);
  3447. $companyCol = $this->mprocResolveProcuremenColumn(['company_name']);
  3448. if ($ccydhCol === null || $companyCol === null) {
  3449. return;
  3450. }
  3451. $ccydh = '';
  3452. $company = '';
  3453. foreach ($row as $k => $v) {
  3454. if (strcasecmp((string)$k, $ccydhCol) === 0) {
  3455. $ccydh = trim((string)$v);
  3456. } elseif (strcasecmp((string)$k, $companyCol) === 0) {
  3457. $company = trim((string)$v);
  3458. }
  3459. }
  3460. if ($ccydh === '' || $company === '') {
  3461. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  3462. $data = [$remarkCol => ($remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8'))];
  3463. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3464. if ($upCol !== null) {
  3465. $data[$upCol] = date('Y-m-d H:i:s');
  3466. }
  3467. Db::table('purchase_order_detail')->where($pkField, (int)($row[$pkField] ?? $anchorId))->update($data);
  3468. return;
  3469. }
  3470. $remarkVal = $remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8');
  3471. $data = [$remarkCol => $remarkVal];
  3472. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3473. if ($upCol !== null) {
  3474. $data[$upCol] = date('Y-m-d H:i:s');
  3475. }
  3476. $query = Db::table('purchase_order_detail')
  3477. ->where($ccydhCol, $ccydh)
  3478. ->where($companyCol, $company);
  3479. $userWhere = $this->mprocListWhereForLoginUser($user);
  3480. if ($userWhere !== []) {
  3481. $query->where($userWhere);
  3482. }
  3483. try {
  3484. $query->update($data);
  3485. } catch (\Throwable $e) {
  3486. throw new \RuntimeException('备注保存失败:' . $e->getMessage());
  3487. }
  3488. }
  3489. /**
  3490. * 保存协助明细金额、交期、工期
  3491. * 单条:POST id、amount、delivery、lead_days
  3492. * 批量:POST items=[{id,amount,delivery,lead_days},...] JSON
  3493. */
  3494. public function mprocSave()
  3495. {
  3496. if (!$this->request->isPost()) {
  3497. $this->error('请使用 POST');
  3498. }
  3499. $user = $this->mprocGetUser();
  3500. if (!$user) {
  3501. $this->error('请先登录', url('index/index/login'));
  3502. }
  3503. // Frontend 默认 filter 含 htmlspecialchars,会把 JSON 的双引号变成 &quot; 导致解析失败
  3504. $itemsRaw = $this->request->post('items', '', null);
  3505. if ($itemsRaw === '' || $itemsRaw === null) {
  3506. $itemsRaw = isset($_POST['items']) ? $_POST['items'] : '';
  3507. }
  3508. if (is_string($itemsRaw) && $itemsRaw !== '' && strpos($itemsRaw, '&quot;') !== false) {
  3509. $itemsRaw = htmlspecialchars_decode($itemsRaw, ENT_QUOTES);
  3510. }
  3511. $items = [];
  3512. if (is_string($itemsRaw) && trim($itemsRaw) !== '') {
  3513. $decoded = json_decode($itemsRaw, true);
  3514. if (!is_array($decoded)) {
  3515. $decoded = json_decode(htmlspecialchars_decode($itemsRaw, ENT_QUOTES), true);
  3516. }
  3517. if (is_array($decoded)) {
  3518. $items = $decoded;
  3519. }
  3520. } elseif (is_array($itemsRaw)) {
  3521. $items = $itemsRaw;
  3522. }
  3523. if ($items === []) {
  3524. $id = (int)$this->request->post('id', 0, null);
  3525. if ($id <= 0) {
  3526. $this->error('保存失败,请关闭弹窗后重试');
  3527. }
  3528. $items = [[
  3529. 'id' => $id,
  3530. 'amount' => (string)$this->request->post('amount', '', null),
  3531. 'delivery' => (string)$this->request->post('delivery', '', null),
  3532. 'lead_days' => (string)$this->request->post('lead_days', '', null),
  3533. ]];
  3534. }
  3535. $saved = 0;
  3536. $savedIds = [];
  3537. $remarkRaw = $this->request->post('remark', '', null);
  3538. if ($remarkRaw === '' || $remarkRaw === null) {
  3539. $remarkRaw = isset($_POST['remark']) ? $_POST['remark'] : '';
  3540. }
  3541. $remarkRaw = trim(htmlspecialchars_decode((string)$remarkRaw, ENT_QUOTES));
  3542. Db::startTrans();
  3543. try {
  3544. foreach ($items as $it) {
  3545. if (!is_array($it)) {
  3546. continue;
  3547. }
  3548. $id = (int)($it['id'] ?? $it['eid'] ?? 0);
  3549. if ($id <= 0) {
  3550. continue;
  3551. }
  3552. $delivery = (string)($it['delivery'] ?? '');
  3553. // 兼容部分手机浏览器把日期显示/提交成 2026/07/24
  3554. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})$/', trim($delivery), $dm)) {
  3555. $delivery = sprintf('%04d-%02d-%02d', (int)$dm[1], (int)$dm[2], (int)$dm[3]);
  3556. }
  3557. $leadDays = (string)($it['lead_days'] ?? $it['leadDays'] ?? '');
  3558. $amount = trim((string)($it['amount'] ?? ''));
  3559. $leadDays = trim($leadDays);
  3560. $delivery = trim($delivery);
  3561. // 全空工序跳过:多工序时允许只保存已填全的
  3562. if ($amount === '' && $leadDays === '' && $delivery === '') {
  3563. continue;
  3564. }
  3565. $this->mprocSaveDetailQuote(
  3566. $user,
  3567. $id,
  3568. $amount,
  3569. $delivery,
  3570. $leadDays
  3571. );
  3572. $saved++;
  3573. $savedIds[] = $id;
  3574. }
  3575. if ($saved < 1) {
  3576. throw new \InvalidArgumentException('请填写单价、工期、交期');
  3577. }
  3578. $this->mprocSaveOrderGroupRemark($user, $savedIds, $remarkRaw);
  3579. Db::commit();
  3580. } catch (\InvalidArgumentException $e) {
  3581. Db::rollback();
  3582. $this->error($e->getMessage());
  3583. } catch (\Throwable $e) {
  3584. Db::rollback();
  3585. $this->error($e->getMessage());
  3586. }
  3587. $this->success($saved > 1 ? ('已保存 ' . $saved . ' 道工序') : '已保存');
  3588. }
  3589. /**
  3590. * 修改密码(POST:old_password、new_password、renew_password)
  3591. * 支持供应商 customer 与手机端管理员 admin
  3592. */
  3593. public function mprocChangePwd()
  3594. {
  3595. if (!$this->request->isPost()) {
  3596. $this->error('请使用 POST');
  3597. }
  3598. $user = $this->mprocGetUser();
  3599. if (!$user) {
  3600. $this->error('请先登录', url('index/index/login'));
  3601. }
  3602. $oldPwd = (string)$this->request->post('old_password', '');
  3603. $newPwd = (string)$this->request->post('new_password', '');
  3604. $renewPwd = (string)$this->request->post('renew_password', '');
  3605. if ($oldPwd === '' || $newPwd === '' || $renewPwd === '') {
  3606. $this->error('请填写完整');
  3607. }
  3608. $pwdErr = $this->mprocValidateStrongPassword($newPwd);
  3609. if ($pwdErr !== '') {
  3610. $this->error($pwdErr);
  3611. }
  3612. if ($newPwd !== $renewPwd) {
  3613. $this->error('两次输入的新密码不一致');
  3614. }
  3615. if ($oldPwd === $newPwd) {
  3616. $this->error('新密码不能与旧密码相同');
  3617. }
  3618. if (!empty($user['is_admin'])) {
  3619. $adminId = (int)($user['admin_id'] ?? 0);
  3620. if ($adminId <= 0) {
  3621. $this->error('账号不存在或已禁用');
  3622. }
  3623. $row = null;
  3624. try {
  3625. $row = Db::name('admin')
  3626. ->field('id,username,password,salt,status')
  3627. ->where('id', $adminId)
  3628. ->find();
  3629. } catch (\Throwable $e) {
  3630. $row = null;
  3631. }
  3632. if (!$row || !is_array($row) || (($row['status'] ?? '') === 'hidden')) {
  3633. $this->error('账号不存在或已禁用');
  3634. }
  3635. $salt = (string)($row['salt'] ?? '');
  3636. $hashStored = (string)($row['password'] ?? '');
  3637. $hashOld = md5(md5($oldPwd) . $salt);
  3638. if ($hashStored === '' || $hashOld !== $hashStored) {
  3639. $this->error('原密码不正确');
  3640. }
  3641. $hashNew = md5(md5($newPwd) . $salt);
  3642. try {
  3643. Db::name('admin')->where('id', $adminId)->update([
  3644. 'password' => $hashNew,
  3645. 'updatetime' => time(),
  3646. ]);
  3647. } catch (\Throwable $e) {
  3648. $this->error('修改失败:' . $e->getMessage());
  3649. }
  3650. } else {
  3651. $user = $this->mprocSyncSessionCustomerUser($user);
  3652. $cu = $this->mprocResolveCustomerUserForSession($user);
  3653. if (!$cu) {
  3654. $this->error('账号不存在或已禁用');
  3655. }
  3656. $cuId = (int)($cu['id'] ?? 0);
  3657. if (!$this->mprocVerifyCustomerUserPassword($cu, $oldPwd)) {
  3658. $this->error('原密码不正确');
  3659. }
  3660. $data = [
  3661. 'password' => $this->mprocHashCustomerUserPassword($newPwd),
  3662. 'updatetime' => date('Y-m-d H:i:s'),
  3663. ];
  3664. try {
  3665. Db::table('customer')->where('id', $cuId)->update($data);
  3666. } catch (\Throwable $e) {
  3667. $this->error('修改失败:' . $e->getMessage());
  3668. }
  3669. }
  3670. // 改密后强制重新登录
  3671. $token = Session::get('mproc_token');
  3672. if ($token === null || $token === '') {
  3673. $token = Cookie::get('mproc_token');
  3674. }
  3675. if ($token === null || $token === '') {
  3676. $token = Cookie::get('mproc_remember');
  3677. }
  3678. $this->mprocClearLogin((string)$token);
  3679. $this->success('密码已修改,请重新登录', url('index/index/login'));
  3680. }
  3681. /**
  3682. * 退出登录
  3683. */
  3684. public function logout()
  3685. {
  3686. $token = Session::get('mproc_token');
  3687. if ($token === null || $token === '') {
  3688. $token = Cookie::get('mproc_token');
  3689. }
  3690. if ($token === null || $token === '') {
  3691. $token = Cookie::get('mproc_remember');
  3692. }
  3693. // 无论有无 token 都清 Cookie/Session,避免「记住登录」把用户又带回来
  3694. $this->mprocClearLogin((string)$token);
  3695. $this->redirect(url('index/index/login'));
  3696. }
  3697. /**
  3698. * 短信宝(与后台协助审核一致,便于复用账号)
  3699. *
  3700. * @throws \Exception
  3701. */
  3702. protected function mprocSmsSend($phone, $content)
  3703. {
  3704. $statusStr = [
  3705. '0' => '短信发送成功',
  3706. '-1' => '参数不全',
  3707. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  3708. '30' => '密码错误',
  3709. '40' => '账号不存在',
  3710. '41' => '余额不足',
  3711. '42' => '帐户已过期',
  3712. '43' => 'IP地址限制',
  3713. '50' => '内容含有敏感词',
  3714. ];
  3715. $smsapi = 'http://api.smsbao.com/';
  3716. $user = trim((string)Config::get('mproc.smsbao_user'));
  3717. if ($user === '') {
  3718. $user = 'zhuwei123';
  3719. }
  3720. $passPlain = Config::get('mproc.smsbao_pass');
  3721. $pass = ($passPlain !== null && $passPlain !== '')
  3722. ? md5((string)$passPlain)
  3723. : md5('1d1e605c101e4c1f8a156c6d7b19f126');
  3724. $phone = trim((string)$phone);
  3725. $content = trim((string)$content);
  3726. if ($phone === '' || $content === '') {
  3727. throw new \Exception('短信发送失败:参数不全');
  3728. }
  3729. $sendurl = $smsapi . 'sms?u=' . rawurlencode($user) . '&p=' . $pass . '&m=' . rawurlencode($phone) . '&c=' . rawurlencode($content);
  3730. $result = @file_get_contents($sendurl);
  3731. if ($result === false) {
  3732. Log::record('smsbao 请求失败 phone=' . $phone . ' content=' . $content, 'error');
  3733. throw new \Exception('短信发送失败:网络异常');
  3734. }
  3735. $result = trim((string)$result);
  3736. if ($result !== '0') {
  3737. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  3738. Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg . ' content=' . $content, 'error');
  3739. throw new \Exception('短信发送失败:' . $msg);
  3740. }
  3741. Log::record('smsbao 发送成功 phone=' . $phone . ' content=' . $content, 'info');
  3742. }
  3743. /**
  3744. * 质量评分页(质检中心:合格/投诉/中断)
  3745. */
  3746. public function inboundscore()
  3747. {
  3748. $user = $this->mprocGetUser();
  3749. if (!$user) {
  3750. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  3751. $safe = $this->mprocSanitizeRedirectUrl($uri);
  3752. if ($safe !== '') {
  3753. Session::set('mproc_intended_url', $safe);
  3754. }
  3755. $this->redirect($this->mprocBuildLoginUrl($safe));
  3756. return;
  3757. }
  3758. if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'quality')) {
  3759. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  3760. if ($jump === '') {
  3761. $this->mprocDropCurrentLogin();
  3762. $this->redirect(url('index/index/login'));
  3763. return;
  3764. }
  3765. $this->redirect($jump);
  3766. return;
  3767. }
  3768. $this->mprocEnsureInboundScoreTable();
  3769. $q = trim((string)$this->request->get('q', ''));
  3770. $profile = $this->mprocProfileForUser($user);
  3771. $this->view->assign('mprocSearchQ', $q);
  3772. $this->view->assign('mprocProfile', $profile);
  3773. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  3774. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  3775. $this->view->assign('mprocScoreScope', 'quality');
  3776. $this->view->assign('rows', $this->mprocLoadInboundScoreRows('pending', $q, (int)($user['admin_id'] ?? 0), 'quality'));
  3777. return $this->view->fetch();
  3778. }
  3779. /**
  3780. * 交货情况页(生产部:准时/滞后)
  3781. */
  3782. public function deliveryscore()
  3783. {
  3784. $user = $this->mprocGetUser();
  3785. if (!$user) {
  3786. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  3787. $safe = $this->mprocSanitizeRedirectUrl($uri);
  3788. if ($safe !== '') {
  3789. Session::set('mproc_intended_url', $safe);
  3790. }
  3791. $this->redirect($this->mprocBuildLoginUrl($safe));
  3792. return;
  3793. }
  3794. if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'delivery')) {
  3795. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  3796. if ($jump === '') {
  3797. $this->mprocDropCurrentLogin();
  3798. $this->redirect(url('index/index/login'));
  3799. return;
  3800. }
  3801. $this->redirect($jump);
  3802. return;
  3803. }
  3804. $this->mprocEnsureInboundScoreTable();
  3805. $q = trim((string)$this->request->get('q', ''));
  3806. $profile = $this->mprocProfileForUser($user);
  3807. $this->view->assign('mprocSearchQ', $q);
  3808. $this->view->assign('mprocProfile', $profile);
  3809. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  3810. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  3811. $this->view->assign('mprocScoreScope', 'delivery');
  3812. $this->view->assign('rows', $this->mprocLoadInboundScoreRows('pending', $q, (int)($user['admin_id'] ?? 0), 'delivery'));
  3813. return $this->view->fetch();
  3814. }
  3815. /**
  3816. * 质量评分列表 JSON(质检;tab=pending|scored)
  3817. */
  3818. public function inboundscorelist()
  3819. {
  3820. $user = $this->mprocRequireQualityUser();
  3821. $this->mprocEnsureInboundScoreTable();
  3822. $q = trim((string)$this->request->request('q', ''));
  3823. $tab = trim((string)$this->request->request('tab', 'pending'));
  3824. if (!in_array($tab, ['pending', 'scored', 'pass', 'fail'], true)) {
  3825. $tab = 'pending';
  3826. }
  3827. if ($tab === 'pass' || $tab === 'fail') {
  3828. $tab = 'scored';
  3829. }
  3830. $adminId = (int)($user['admin_id'] ?? 0);
  3831. $rows = $this->mprocLoadInboundScoreRows($tab, $q, $adminId, 'quality');
  3832. $this->success('ok', '', [
  3833. 'tab' => $tab,
  3834. 'q' => $q,
  3835. 'scope' => 'quality',
  3836. 'rows' => $rows,
  3837. 'count' => count($rows),
  3838. ]);
  3839. }
  3840. /**
  3841. * 交货情况列表 JSON(生产部;tab=pending|scored)
  3842. */
  3843. public function deliveryscorelist()
  3844. {
  3845. $user = $this->mprocRequireDeliveryUser();
  3846. $this->mprocEnsureInboundScoreTable();
  3847. $q = trim((string)$this->request->request('q', ''));
  3848. $tab = trim((string)$this->request->request('tab', 'pending'));
  3849. if (!in_array($tab, ['pending', 'scored'], true)) {
  3850. $tab = 'pending';
  3851. }
  3852. $adminId = (int)($user['admin_id'] ?? 0);
  3853. $rows = $this->mprocLoadInboundScoreRows($tab, $q, $adminId, 'delivery');
  3854. $this->success('ok', '', [
  3855. 'tab' => $tab,
  3856. 'q' => $q,
  3857. 'scope' => 'delivery',
  3858. 'rows' => $rows,
  3859. 'count' => count($rows),
  3860. ]);
  3861. }
  3862. /**
  3863. * 保存质量评分(质检中心)
  3864. * POST:ccydh、result、order_interrupt、remark
  3865. * 客诉事后由 inboundscorecomplaint 补登,首次默认否
  3866. */
  3867. public function inboundscoresave()
  3868. {
  3869. $user = $this->mprocRequireQualityUser();
  3870. if (!$this->request->isPost()) {
  3871. $this->error('请使用 POST');
  3872. }
  3873. $this->mprocEnsureInboundScoreTable();
  3874. $ccydh = trim((string)$this->request->post('ccydh', ''));
  3875. $sid = (int)$this->request->post('scydgy_id', 0);
  3876. $result = trim((string)$this->request->post('result', ''));
  3877. if ($result !== '合格' && $result !== '不合格') {
  3878. $this->error('请选择生产是否合格');
  3879. }
  3880. $orderInterrupt = (int)$this->request->post('order_interrupt', -1);
  3881. if ($orderInterrupt !== 0 && $orderInterrupt !== 1) {
  3882. $this->error('请选择生产是否中断');
  3883. }
  3884. $remark = trim((string)$this->request->post('remark', ''));
  3885. if ($result === '不合格' && $remark === '') {
  3886. $this->error('请填写不合格原因');
  3887. }
  3888. if (mb_strlen($remark) > 500) {
  3889. $remark = mb_substr($remark, 0, 500);
  3890. }
  3891. $poRows = $this->mprocLoadApprovedPoRowsForScore($ccydh, $sid);
  3892. $now = date('Y-m-d H:i:s');
  3893. $adminId = (int)($user['admin_id'] ?? 0);
  3894. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  3895. $saved = 0;
  3896. $firstSid = 0;
  3897. $firstPoId = 0;
  3898. $deliveryReady = true;
  3899. try {
  3900. Db::startTrans();
  3901. foreach ($poRows as $po) {
  3902. if (!is_array($po)) {
  3903. continue;
  3904. }
  3905. $rowSid = (int)($po['scydgy_id'] ?? 0);
  3906. if ($rowSid <= 0) {
  3907. continue;
  3908. }
  3909. if ($firstSid <= 0) {
  3910. $firstSid = $rowSid;
  3911. $firstPoId = (int)($po['id'] ?? 0);
  3912. }
  3913. $exist = Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->find();
  3914. $existDs = is_array($exist) ? trim((string)($exist['delivery_status'] ?? '')) : '';
  3915. if ($existDs !== '准时' && $existDs !== '滞后') {
  3916. $deliveryReady = false;
  3917. }
  3918. $data = [
  3919. 'scydgy_id' => $rowSid,
  3920. 'purchase_order_id' => (int)($po['id'] ?? 0),
  3921. 'ccydh' => trim((string)($po['CCYDH'] ?? $ccydh)),
  3922. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  3923. 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
  3924. 'company_name' => trim((string)($po['pick_company_name'] ?? '')),
  3925. 'result' => $result,
  3926. 'order_interrupt' => $orderInterrupt,
  3927. 'remark' => $remark,
  3928. 'admin_id' => $adminId,
  3929. 'admin_name' => $adminName,
  3930. 'updatetime' => $now,
  3931. ];
  3932. if (is_array($exist) && $exist !== []) {
  3933. // 客诉事后补登,首次评分不覆盖已有客诉
  3934. Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->update($data);
  3935. } else {
  3936. $data['customer_complaint'] = 0;
  3937. $data['complaint_remark'] = '';
  3938. $data['delivery_status'] = '';
  3939. $data['createtime'] = $now;
  3940. Db::table('purchase_order_inbound_score')->insert($data);
  3941. $deliveryReady = false;
  3942. }
  3943. $saved++;
  3944. }
  3945. if ($saved < 1) {
  3946. throw new \RuntimeException('没有可保存的工序');
  3947. }
  3948. if ($deliveryReady) {
  3949. foreach ($poRows as $po) {
  3950. if (!is_array($po)) {
  3951. continue;
  3952. }
  3953. $rowSid = (int)($po['scydgy_id'] ?? 0);
  3954. if ($rowSid > 0) {
  3955. Db::table('purchase_order')->where('scydgy_id', $rowSid)->update([
  3956. 'status' => ProcuremenStatus::PO_COMPLETED,
  3957. ]);
  3958. }
  3959. }
  3960. }
  3961. Db::commit();
  3962. } catch (\Throwable $e) {
  3963. try {
  3964. Db::rollback();
  3965. } catch (\Throwable $e2) {
  3966. }
  3967. Log::record('inboundscoresave fail: ' . $e->getMessage(), 'error');
  3968. $this->error('保存失败,请稍后重试');
  3969. }
  3970. $logDetail = '质量评分:生产是否合格=' . $result
  3971. . ';生产是否中断:' . ($orderInterrupt === 1 ? '是' : '否');
  3972. if ($remark !== '') {
  3973. $logDetail .= ';备注:' . $remark;
  3974. }
  3975. \app\common\library\ProcuremenOperLog::write(
  3976. $firstSid,
  3977. 'inbound_score',
  3978. $logDetail,
  3979. $firstPoId > 0 ? $firstPoId : null,
  3980. [$adminId, $adminName]
  3981. );
  3982. $this->mprocSyncMonthlyAfterInboundScore($poRows, $now);
  3983. if ($deliveryReady) {
  3984. $this->mprocRefreshCompletedArchivePdfs($poRows);
  3985. }
  3986. $this->success('操作成功', '', [
  3987. 'ccydh' => $ccydh,
  3988. 'result' => $result,
  3989. 'order_interrupt' => $orderInterrupt,
  3990. 'remark' => $remark,
  3991. 'count' => $saved,
  3992. 'completed' => $deliveryReady ? 1 : 0,
  3993. ]);
  3994. }
  3995. /**
  3996. * 事后投诉反馈(质检中心,仅已质量评分订单)
  3997. * POST:ccydh、customer_complaint=0|1、complaint_remark(投诉为是时必填)
  3998. */
  3999. public function inboundscorecomplaint()
  4000. {
  4001. $user = $this->mprocRequireQualityUser();
  4002. if (!$this->request->isPost()) {
  4003. $this->error('请使用 POST');
  4004. }
  4005. $this->mprocEnsureInboundScoreTable();
  4006. $ccydh = trim((string)$this->request->post('ccydh', ''));
  4007. $sid = (int)$this->request->post('scydgy_id', 0);
  4008. $customerComplaint = (int)$this->request->post('customer_complaint', -1);
  4009. if ($customerComplaint !== 0 && $customerComplaint !== 1) {
  4010. $this->error('请选择客户是否投诉');
  4011. }
  4012. $complaintRemark = trim((string)$this->request->post('complaint_remark', ''));
  4013. if ($customerComplaint === 1 && $complaintRemark === '') {
  4014. $this->error('请填写投诉说明');
  4015. }
  4016. if ($customerComplaint !== 1) {
  4017. $complaintRemark = '';
  4018. }
  4019. if (mb_strlen($complaintRemark) > 500) {
  4020. $complaintRemark = mb_substr($complaintRemark, 0, 500);
  4021. }
  4022. if ($ccydh === '' && $sid > 0) {
  4023. try {
  4024. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  4025. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  4026. } catch (\Throwable $e) {
  4027. $ccydh = '';
  4028. }
  4029. }
  4030. if ($ccydh === '') {
  4031. $this->error('缺少订单号');
  4032. }
  4033. try {
  4034. $scoreRows = Db::table('purchase_order_inbound_score')
  4035. ->where('ccydh', $ccydh)
  4036. ->field('id,scydgy_id,purchase_order_id,result,company_name')
  4037. ->select();
  4038. } catch (\Throwable $e) {
  4039. $scoreRows = [];
  4040. }
  4041. if (!is_array($scoreRows) || $scoreRows === []) {
  4042. $this->error('请先完成质量评分后再投诉反馈');
  4043. }
  4044. $hasQuality = false;
  4045. foreach ($scoreRows as $sc) {
  4046. if (!is_array($sc)) {
  4047. continue;
  4048. }
  4049. $res = trim((string)($sc['result'] ?? ''));
  4050. if ($res === '合格' || $res === '不合格') {
  4051. $hasQuality = true;
  4052. break;
  4053. }
  4054. }
  4055. if (!$hasQuality) {
  4056. $this->error('请先完成质量评分后再投诉反馈');
  4057. }
  4058. $now = date('Y-m-d H:i:s');
  4059. $adminId = (int)($user['admin_id'] ?? 0);
  4060. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  4061. $firstSid = 0;
  4062. $firstPoId = 0;
  4063. $companyName = '';
  4064. $updated = 0;
  4065. try {
  4066. Db::startTrans();
  4067. foreach ($scoreRows as $sc) {
  4068. if (!is_array($sc)) {
  4069. continue;
  4070. }
  4071. $rowSid = (int)($sc['scydgy_id'] ?? 0);
  4072. $id = (int)($sc['id'] ?? 0);
  4073. if ($id <= 0) {
  4074. continue;
  4075. }
  4076. if ($firstSid <= 0 && $rowSid > 0) {
  4077. $firstSid = $rowSid;
  4078. $firstPoId = (int)($sc['purchase_order_id'] ?? 0);
  4079. }
  4080. if ($companyName === '') {
  4081. $companyName = trim((string)($sc['company_name'] ?? ''));
  4082. }
  4083. Db::table('purchase_order_inbound_score')->where('id', $id)->update([
  4084. 'customer_complaint' => $customerComplaint,
  4085. 'complaint_remark' => $complaintRemark,
  4086. 'updatetime' => $now,
  4087. ]);
  4088. $updated++;
  4089. }
  4090. if ($updated < 1) {
  4091. throw new \RuntimeException('没有可更新的记录');
  4092. }
  4093. Db::commit();
  4094. } catch (\Throwable $e) {
  4095. try {
  4096. Db::rollback();
  4097. } catch (\Throwable $e2) {
  4098. }
  4099. Log::record('inboundscorecomplaint fail: ' . $e->getMessage(), 'error');
  4100. $this->error('保存失败,请稍后重试');
  4101. }
  4102. if ($firstSid > 0) {
  4103. $logDetail = '投诉反馈:客户投诉=' . ($customerComplaint === 1 ? '是' : '否');
  4104. if ($complaintRemark !== '') {
  4105. $logDetail .= ';投诉说明:' . $complaintRemark;
  4106. }
  4107. \app\common\library\ProcuremenOperLog::write(
  4108. $firstSid,
  4109. 'inbound_score',
  4110. $logDetail,
  4111. $firstPoId > 0 ? $firstPoId : null,
  4112. [$adminId, $adminName]
  4113. );
  4114. }
  4115. if ($companyName !== '') {
  4116. $scoreYm = date('Y-m', strtotime($now) ?: time());
  4117. try {
  4118. \app\common\library\ProcuremenSupplierScore::syncQualityScoreFromInbound($scoreYm, $companyName);
  4119. } catch (\Throwable $e) {
  4120. Log::record('inboundscorecomplaint quality sync: ' . $e->getMessage(), 'error');
  4121. }
  4122. }
  4123. $this->success('操作成功', '', [
  4124. 'ccydh' => $ccydh,
  4125. 'customer_complaint' => $customerComplaint,
  4126. 'complaint_remark' => $complaintRemark,
  4127. 'count' => $updated,
  4128. ]);
  4129. }
  4130. /**
  4131. * 保存交货情况(生产部)
  4132. * POST:ccydh、delivery_status=准时|滞后、delivery_date=YYYY-MM-DD
  4133. */
  4134. public function deliveryscoresave()
  4135. {
  4136. $user = $this->mprocRequireDeliveryUser();
  4137. if (!$this->request->isPost()) {
  4138. $this->error('请使用 POST');
  4139. }
  4140. $this->mprocEnsureInboundScoreTable();
  4141. $ccydh = trim((string)$this->request->post('ccydh', ''));
  4142. $sid = (int)$this->request->post('scydgy_id', 0);
  4143. $deliveryStatus = trim((string)$this->request->post('delivery_status', ''));
  4144. if ($deliveryStatus !== '准时' && $deliveryStatus !== '滞后') {
  4145. $this->error('请选择交货情况');
  4146. }
  4147. $deliveryDate = trim((string)$this->request->post('delivery_date', ''));
  4148. if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryDate)) {
  4149. $this->error('请选择交货日期');
  4150. }
  4151. $ts = strtotime($deliveryDate . ' 00:00:00');
  4152. if ($ts === false) {
  4153. $this->error('交货日期格式不正确');
  4154. }
  4155. $deliveryDate = date('Y-m-d', $ts);
  4156. $poRows = $this->mprocLoadApprovedPoRowsForScore($ccydh, $sid);
  4157. $now = date('Y-m-d H:i:s');
  4158. $adminId = (int)($user['admin_id'] ?? 0);
  4159. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  4160. $saved = 0;
  4161. $firstSid = 0;
  4162. $firstPoId = 0;
  4163. $qualityReady = true;
  4164. try {
  4165. Db::startTrans();
  4166. foreach ($poRows as $po) {
  4167. if (!is_array($po)) {
  4168. continue;
  4169. }
  4170. $rowSid = (int)($po['scydgy_id'] ?? 0);
  4171. if ($rowSid <= 0) {
  4172. continue;
  4173. }
  4174. if ($firstSid <= 0) {
  4175. $firstSid = $rowSid;
  4176. $firstPoId = (int)($po['id'] ?? 0);
  4177. }
  4178. $exist = Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->find();
  4179. $existResult = is_array($exist) ? trim((string)($exist['result'] ?? '')) : '';
  4180. if ($existResult !== '合格' && $existResult !== '不合格') {
  4181. $qualityReady = false;
  4182. }
  4183. $data = [
  4184. 'scydgy_id' => $rowSid,
  4185. 'purchase_order_id' => (int)($po['id'] ?? 0),
  4186. 'ccydh' => trim((string)($po['CCYDH'] ?? $ccydh)),
  4187. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  4188. 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
  4189. 'company_name' => trim((string)($po['pick_company_name'] ?? '')),
  4190. 'delivery_status' => $deliveryStatus,
  4191. 'delivery_date' => $deliveryDate,
  4192. 'updatetime' => $now,
  4193. ];
  4194. if (is_array($exist) && $exist !== []) {
  4195. Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->update($data);
  4196. } else {
  4197. $data['result'] = '';
  4198. $data['customer_complaint'] = 0;
  4199. $data['complaint_remark'] = '';
  4200. $data['order_interrupt'] = 0;
  4201. $data['remark'] = '';
  4202. $data['admin_id'] = $adminId;
  4203. $data['admin_name'] = $adminName;
  4204. $data['createtime'] = $now;
  4205. Db::table('purchase_order_inbound_score')->insert($data);
  4206. $qualityReady = false;
  4207. }
  4208. $saved++;
  4209. }
  4210. if ($saved < 1) {
  4211. throw new \RuntimeException('没有可保存的工序');
  4212. }
  4213. if ($qualityReady) {
  4214. foreach ($poRows as $po) {
  4215. if (!is_array($po)) {
  4216. continue;
  4217. }
  4218. $rowSid = (int)($po['scydgy_id'] ?? 0);
  4219. if ($rowSid > 0) {
  4220. Db::table('purchase_order')->where('scydgy_id', $rowSid)->update([
  4221. 'status' => ProcuremenStatus::PO_COMPLETED,
  4222. ]);
  4223. }
  4224. }
  4225. }
  4226. Db::commit();
  4227. } catch (\Throwable $e) {
  4228. try {
  4229. Db::rollback();
  4230. } catch (\Throwable $e2) {
  4231. }
  4232. Log::record('deliveryscoresave fail: ' . $e->getMessage(), 'error');
  4233. $this->error('保存失败,请稍后重试');
  4234. }
  4235. \app\common\library\ProcuremenOperLog::write(
  4236. $firstSid,
  4237. 'inbound_score',
  4238. '交货情况:' . $deliveryStatus . ';交货日期:' . $deliveryDate,
  4239. $firstPoId > 0 ? $firstPoId : null,
  4240. [$adminId, $adminName]
  4241. );
  4242. $this->mprocSyncMonthlyAfterInboundScore($poRows, $now);
  4243. if ($qualityReady) {
  4244. $this->mprocRefreshCompletedArchivePdfs($poRows);
  4245. }
  4246. $this->success('操作成功', '', [
  4247. 'ccydh' => $ccydh,
  4248. 'delivery_status' => $deliveryStatus,
  4249. 'delivery_date' => $deliveryDate,
  4250. 'count' => $saved,
  4251. 'completed' => $qualityReady ? 1 : 0,
  4252. ]);
  4253. }
  4254. /**
  4255. * 质量+交货均完成后,按最新详情重存存证 PDF
  4256. *
  4257. * @param array<int, mixed> $poRows
  4258. */
  4259. protected function mprocRefreshCompletedArchivePdfs(array $poRows): void
  4260. {
  4261. $done = [];
  4262. foreach ($poRows as $po) {
  4263. if (!is_array($po)) {
  4264. continue;
  4265. }
  4266. $sid = (int)($po['scydgy_id'] ?? 0);
  4267. if ($sid <= 0 || isset($done[$sid])) {
  4268. continue;
  4269. }
  4270. $done[$sid] = true;
  4271. try {
  4272. \app\admin\controller\Procuremen::regenerateArchivePdfWithoutAuth($sid, true);
  4273. } catch (\Throwable $e) {
  4274. Log::record('完结存证PDF刷新失败 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  4275. }
  4276. }
  4277. }
  4278. /**
  4279. * @return array<int, array<string, mixed>>
  4280. */
  4281. protected function mprocLoadApprovedPoRowsForScore(string $ccydh, int $sid): array
  4282. {
  4283. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  4284. $approvedIn = implode(',', array_map(static function ($v) {
  4285. return "'" . str_replace("'", "''", (string)$v) . "'";
  4286. }, $approvedVals));
  4287. try {
  4288. $q = Db::table('purchase_order')
  4289. ->where('scydgy_id', '>', 0)
  4290. ->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%\')')
  4291. ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
  4292. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  4293. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  4294. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,pick_company_name,pick_time,wflow_status,status');
  4295. if ($ccydh !== '') {
  4296. $q->where('CCYDH', $ccydh);
  4297. } elseif ($sid > 0) {
  4298. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  4299. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  4300. if ($ccydh === '') {
  4301. $this->error('缺少订单号');
  4302. }
  4303. $q->where('CCYDH', $ccydh);
  4304. } else {
  4305. $this->error('缺少订单号');
  4306. }
  4307. $poRows = $q->order('id', 'asc')->select();
  4308. } catch (\Throwable $e) {
  4309. $poRows = [];
  4310. }
  4311. if (!is_array($poRows) || $poRows === []) {
  4312. $this->error('未找到可评分的已审核订单');
  4313. }
  4314. return $poRows;
  4315. }
  4316. /**
  4317. * 操作人展示名:优先后台管理员昵称(名称),避免记成登录账号
  4318. *
  4319. * @param array<string, mixed> $user
  4320. */
  4321. protected function mprocResolveAdminDisplayName(array $user, int $adminId): string
  4322. {
  4323. $adminName = '';
  4324. if ($adminId > 0) {
  4325. try {
  4326. $adminRow = Db::name('admin')->where('id', $adminId)->field('nickname,username')->find();
  4327. if (is_array($adminRow)) {
  4328. $nick = trim((string)($adminRow['nickname'] ?? ''));
  4329. $uname = trim((string)($adminRow['username'] ?? ''));
  4330. if ($nick !== '') {
  4331. $adminName = $nick;
  4332. } elseif ($uname !== '') {
  4333. $adminName = $uname;
  4334. }
  4335. }
  4336. } catch (\Throwable $e) {
  4337. }
  4338. }
  4339. if ($adminName === '') {
  4340. $adminName = trim((string)($user['nickname'] ?? ''));
  4341. }
  4342. if ($adminName === '') {
  4343. $adminName = trim((string)($user['username'] ?? ''));
  4344. }
  4345. return $adminName !== '' ? $adminName : '管理员';
  4346. }
  4347. /**
  4348. * @param array<int, mixed> $poRows
  4349. */
  4350. protected function mprocSyncMonthlyAfterInboundScore(array $poRows, string $now): void
  4351. {
  4352. $companyName = '';
  4353. foreach ($poRows as $po) {
  4354. if (!is_array($po)) {
  4355. continue;
  4356. }
  4357. $companyName = trim((string)($po['pick_company_name'] ?? ''));
  4358. if ($companyName !== '') {
  4359. break;
  4360. }
  4361. }
  4362. $scoreYm = date('Y-m', strtotime($now) ?: time());
  4363. if ($companyName === '') {
  4364. return;
  4365. }
  4366. try {
  4367. \app\common\library\ProcuremenSupplierScore::syncQualityScoreFromInbound($scoreYm, $companyName);
  4368. } catch (\Throwable $e) {
  4369. Log::record('inboundscoresave quality sync: ' . $e->getMessage(), 'error');
  4370. }
  4371. }
  4372. /**
  4373. * @return array<string, mixed>
  4374. */
  4375. protected function mprocRequireAdminUser(): array
  4376. {
  4377. $user = $this->mprocGetUser();
  4378. if (!$user) {
  4379. $this->error('请先登录', url('index/index/login'));
  4380. }
  4381. if (empty($user['is_admin'])) {
  4382. $this->error('仅系统管理员可操作');
  4383. }
  4384. return $user;
  4385. }
  4386. /** 质检中心角色组 id */
  4387. protected function mprocResolveMobileQualityGroupId(): int
  4388. {
  4389. $id = (int)Config::get('mproc.mobile_quality_group_id');
  4390. if ($id > 0) {
  4391. return $id;
  4392. }
  4393. try {
  4394. $found = Db::name('auth_group')
  4395. ->where('name', '质检中心')
  4396. ->where('status', 'normal')
  4397. ->order('id', 'asc')
  4398. ->value('id');
  4399. $id = (int)$found;
  4400. } catch (\Throwable $e) {
  4401. $id = 0;
  4402. }
  4403. return $id > 0 ? $id : 16;
  4404. }
  4405. /** 生产部/生产员角色组 id */
  4406. protected function mprocResolveMobileDeliveryGroupId(): int
  4407. {
  4408. $id = (int)Config::get('mproc.mobile_delivery_group_id');
  4409. if ($id > 0) {
  4410. return $id;
  4411. }
  4412. try {
  4413. $found = Db::name('auth_group')
  4414. ->where('name', 'in', ['生产部', '生产员'])
  4415. ->where('status', 'normal')
  4416. ->order('id', 'asc')
  4417. ->value('id');
  4418. $id = (int)$found;
  4419. } catch (\Throwable $e) {
  4420. $id = 0;
  4421. }
  4422. return $id > 0 ? $id : 15;
  4423. }
  4424. /** 业务员(手机端新增询价)角色组 id */
  4425. protected function mprocResolveMobileRfqGroupId(): int
  4426. {
  4427. $id = (int)Config::get('mproc.mobile_rfq_group_id');
  4428. if ($id <= 0) {
  4429. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  4430. }
  4431. if ($id > 0) {
  4432. return $id;
  4433. }
  4434. try {
  4435. $found = Db::name('auth_group')
  4436. ->where('name', '业务员')
  4437. ->where('status', 'normal')
  4438. ->order('id', 'asc')
  4439. ->value('id');
  4440. $id = (int)$found;
  4441. } catch (\Throwable $e) {
  4442. $id = 0;
  4443. }
  4444. return $id > 0 ? $id : 12;
  4445. }
  4446. /**
  4447. * @return int[]
  4448. */
  4449. protected function mprocAdminGroupIds(int $adminId): array
  4450. {
  4451. if ($adminId <= 0) {
  4452. return [];
  4453. }
  4454. try {
  4455. $ids = Db::name('auth_group_access')->where('uid', $adminId)->column('group_id');
  4456. } catch (\Throwable $e) {
  4457. return [];
  4458. }
  4459. if (!is_array($ids)) {
  4460. return [];
  4461. }
  4462. return array_values(array_unique(array_filter(array_map('intval', $ids))));
  4463. }
  4464. /** 超管(角色组 rules=*)或协同「管理员」组 */
  4465. protected function mprocAdminIsMobileSuper(int $adminId): bool
  4466. {
  4467. if ($adminId <= 0) {
  4468. return false;
  4469. }
  4470. try {
  4471. $rows = Db::name('auth_group_access')
  4472. ->alias('aga')
  4473. ->join('auth_group ag', 'aga.group_id = ag.id')
  4474. ->where('aga.uid', $adminId)
  4475. ->field('ag.id,ag.rules')
  4476. ->select();
  4477. } catch (\Throwable $e) {
  4478. return false;
  4479. }
  4480. if (!is_array($rows)) {
  4481. return false;
  4482. }
  4483. foreach ($rows as $r) {
  4484. if (!is_array($r)) {
  4485. continue;
  4486. }
  4487. if (trim((string)($r['rules'] ?? '')) === '*') {
  4488. return true;
  4489. }
  4490. // 供应链协同「管理员」组
  4491. if ((int)($r['id'] ?? 0) === 11) {
  4492. return true;
  4493. }
  4494. }
  4495. return false;
  4496. }
  4497. /**
  4498. * @param array<string, mixed> $user
  4499. * @param string $role quality|delivery|rfq
  4500. */
  4501. protected function mprocAdminHasMobileRole(array $user, string $role): bool
  4502. {
  4503. if (empty($user['is_admin'])) {
  4504. return false;
  4505. }
  4506. $adminId = (int)($user['admin_id'] ?? 0);
  4507. if ($adminId <= 0) {
  4508. return false;
  4509. }
  4510. if ($this->mprocAdminIsMobileSuper($adminId)) {
  4511. return true;
  4512. }
  4513. $gids = $this->mprocAdminGroupIds($adminId);
  4514. if ($role === 'quality') {
  4515. $need = $this->mprocResolveMobileQualityGroupId();
  4516. return $need > 0 && in_array($need, $gids, true);
  4517. }
  4518. if ($role === 'delivery') {
  4519. $need = $this->mprocResolveMobileDeliveryGroupId();
  4520. return $need > 0 && in_array($need, $gids, true);
  4521. }
  4522. if ($role === 'rfq') {
  4523. $need = $this->mprocResolveMobileRfqGroupId();
  4524. return $need > 0 && in_array($need, $gids, true);
  4525. }
  4526. return false;
  4527. }
  4528. /**
  4529. * @return array<string, mixed>
  4530. */
  4531. protected function mprocRequireRfqUser(): array
  4532. {
  4533. $user = $this->mprocRequireAdminUser();
  4534. if (!$this->mprocAdminHasMobileRole($user, 'rfq')) {
  4535. $this->error('仅业务员账号可新增订单询价');
  4536. }
  4537. return $user;
  4538. }
  4539. /**
  4540. * @return array<string, mixed>
  4541. */
  4542. protected function mprocRequireQualityUser(): array
  4543. {
  4544. $user = $this->mprocRequireAdminUser();
  4545. if (!$this->mprocAdminHasMobileRole($user, 'quality')) {
  4546. $this->error('仅质检中心账号可操作质量评分');
  4547. }
  4548. return $user;
  4549. }
  4550. /**
  4551. * @return array<string, mixed>
  4552. */
  4553. protected function mprocRequireDeliveryUser(): array
  4554. {
  4555. $user = $this->mprocRequireAdminUser();
  4556. if (!$this->mprocAdminHasMobileRole($user, 'delivery')) {
  4557. $this->error('仅生产部账号可操作交货情况');
  4558. }
  4559. return $user;
  4560. }
  4561. protected function mprocEnsureInboundScoreTable(): void
  4562. {
  4563. static $ok = false;
  4564. if ($ok) {
  4565. return;
  4566. }
  4567. try {
  4568. Db::query('SELECT 1 FROM `purchase_order_inbound_score` LIMIT 1');
  4569. } catch (\Throwable $e) {
  4570. try {
  4571. Db::execute("CREATE TABLE IF NOT EXISTS `purchase_order_inbound_score` (
  4572. `id` int unsigned NOT NULL AUTO_INCREMENT,
  4573. `scydgy_id` int NOT NULL DEFAULT 0 COMMENT '工序ID',
  4574. `purchase_order_id` int unsigned NOT NULL DEFAULT 0 COMMENT 'purchase_order.id',
  4575. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  4576. `cyjmc` varchar(255) NOT NULL DEFAULT '' COMMENT '印件名称',
  4577. `cgymc` varchar(255) NOT NULL DEFAULT '' COMMENT '工序名称',
  4578. `company_name` varchar(255) NOT NULL DEFAULT '' COMMENT '中标供应商',
  4579. `result` varchar(16) NOT NULL DEFAULT '' COMMENT '合格/不合格',
  4580. `delivery_status` varchar(16) NOT NULL DEFAULT '' COMMENT '交货情况 准时/滞后',
  4581. `delivery_date` date DEFAULT NULL COMMENT '交货日期',
  4582. `customer_complaint` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '客户是否投诉 1=是',
  4583. `complaint_remark` varchar(500) NOT NULL DEFAULT '' COMMENT '投诉说明',
  4584. `order_interrupt` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '订单是否中断 1=是',
  4585. `admin_id` int unsigned NOT NULL DEFAULT 0,
  4586. `admin_name` varchar(64) NOT NULL DEFAULT '',
  4587. `remark` varchar(500) NOT NULL DEFAULT '',
  4588. `createtime` datetime DEFAULT NULL,
  4589. `updatetime` datetime DEFAULT NULL,
  4590. PRIMARY KEY (`id`),
  4591. UNIQUE KEY `uk_scydgy_id` (`scydgy_id`),
  4592. KEY `idx_ccydh` (`ccydh`),
  4593. KEY `idx_result` (`result`),
  4594. KEY `idx_updatetime` (`updatetime`)
  4595. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='质量评分'");
  4596. } catch (\Throwable $e2) {
  4597. Log::record('mprocEnsureInboundScoreTable: ' . $e2->getMessage(), 'error');
  4598. return;
  4599. }
  4600. }
  4601. foreach ([
  4602. 'delivery_status' => "ADD COLUMN `delivery_status` varchar(16) NOT NULL DEFAULT '' COMMENT '交货情况 准时/滞后' AFTER `result`",
  4603. 'delivery_date' => "ADD COLUMN `delivery_date` date DEFAULT NULL COMMENT '交货日期' AFTER `delivery_status`",
  4604. 'customer_complaint' => "ADD COLUMN `customer_complaint` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '客户是否投诉 1=是' AFTER `delivery_date`",
  4605. 'complaint_remark' => "ADD COLUMN `complaint_remark` varchar(500) NOT NULL DEFAULT '' COMMENT '投诉说明' AFTER `customer_complaint`",
  4606. 'order_interrupt' => "ADD COLUMN `order_interrupt` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '订单是否中断 1=是' AFTER `complaint_remark`",
  4607. ] as $col => $ddl) {
  4608. try {
  4609. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_inbound_score` LIKE '{$col}'");
  4610. if (!is_array($cols) || $cols === []) {
  4611. Db::execute("ALTER TABLE `purchase_order_inbound_score` {$ddl}");
  4612. }
  4613. } catch (\Throwable $e) {
  4614. Log::record("mprocEnsureInboundScoreTable {$col}: " . $e->getMessage(), 'error');
  4615. }
  4616. }
  4617. $ok = true;
  4618. }
  4619. /**
  4620. * 质量评分列表:按订单号合并(一单一行,工序顿号合并)
  4621. * tab=pending 待评分;scored 已评分(仅当前管理员操作过的)
  4622. *
  4623. * @return array<int, array<string, mixed>>
  4624. */
  4625. protected function mprocLoadInboundScoreRows(string $tab, string $keyword = '', int $adminId = 0, string $scope = 'quality'): array
  4626. {
  4627. $this->mprocEnsureInboundScoreTable();
  4628. $keyword = trim($keyword);
  4629. $scope = $scope === 'delivery' ? 'delivery' : 'quality';
  4630. if (!in_array($tab, ['pending', 'scored', 'pass', 'fail'], true)) {
  4631. $tab = 'pending';
  4632. }
  4633. if ($tab === 'pass' || $tab === 'fail') {
  4634. $tab = 'scored';
  4635. }
  4636. try {
  4637. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  4638. $approvedIn = implode(',', array_map(static function ($v) {
  4639. return "'" . str_replace("'", "''", (string)$v) . "'";
  4640. }, $approvedVals));
  4641. $poRows = Db::table('purchase_order')
  4642. ->where('scydgy_id', '>', 0)
  4643. ->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%\')')
  4644. ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
  4645. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  4646. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  4647. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CCLBMMC,CDW,This_quantity,pick_company_name,pick_time,wflow_status,status')
  4648. ->order('pick_time', 'desc')
  4649. ->order('id', 'asc')
  4650. ->limit(800)
  4651. ->select();
  4652. } catch (\Throwable $e) {
  4653. Log::record('mprocLoadInboundScoreRows: ' . $e->getMessage(), 'error');
  4654. return [];
  4655. }
  4656. if (!is_array($poRows) || $poRows === []) {
  4657. return [];
  4658. }
  4659. $sids = [];
  4660. foreach ($poRows as $po) {
  4661. if (!is_array($po)) {
  4662. continue;
  4663. }
  4664. $sid = (int)($po['scydgy_id'] ?? 0);
  4665. if ($sid > 0) {
  4666. $sids[$sid] = true;
  4667. }
  4668. }
  4669. $scoreMap = [];
  4670. if ($sids !== []) {
  4671. try {
  4672. $scores = Db::table('purchase_order_inbound_score')
  4673. ->where('scydgy_id', 'in', array_keys($sids))
  4674. ->field('scydgy_id,result,delivery_status,delivery_date,customer_complaint,complaint_remark,order_interrupt,remark,admin_id,admin_name,updatetime,createtime')
  4675. ->select();
  4676. } catch (\Throwable $e) {
  4677. try {
  4678. $scores = Db::table('purchase_order_inbound_score')
  4679. ->where('scydgy_id', 'in', array_keys($sids))
  4680. ->field('scydgy_id,result,delivery_status,customer_complaint,order_interrupt,remark,admin_id,admin_name,updatetime,createtime')
  4681. ->select();
  4682. } catch (\Throwable $e2) {
  4683. $scores = [];
  4684. }
  4685. }
  4686. if (is_array($scores)) {
  4687. foreach ($scores as $sc) {
  4688. if (!is_array($sc)) {
  4689. continue;
  4690. }
  4691. $sid = (int)($sc['scydgy_id'] ?? 0);
  4692. if ($sid > 0) {
  4693. $scoreMap[$sid] = $sc;
  4694. }
  4695. }
  4696. }
  4697. }
  4698. /** @var array<string, array<string, mixed>> $groups */
  4699. $groups = [];
  4700. foreach ($poRows as $po) {
  4701. if (!is_array($po)) {
  4702. continue;
  4703. }
  4704. $sid = (int)($po['scydgy_id'] ?? 0);
  4705. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  4706. if ($sid <= 0 || $ccydh === '') {
  4707. continue;
  4708. }
  4709. if (!isset($groups[$ccydh])) {
  4710. $pickRaw = trim((string)($po['pick_time'] ?? ''));
  4711. $pickDisp = $pickRaw !== '' ? \app\common\library\ProcuremenTime::formatDisplayDateTime($pickRaw) : '';
  4712. $groups[$ccydh] = [
  4713. 'CCYDH' => $ccydh,
  4714. 'scydgy_id' => $sid,
  4715. 'scydgy_ids' => [],
  4716. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  4717. 'CCLBMMC' => trim((string)($po['CCLBMMC'] ?? '')),
  4718. 'CGYMC_list' => [],
  4719. 'pick_company_name' => trim((string)($po['pick_company_name'] ?? '')),
  4720. 'pick_time' => $pickDisp !== '' ? $pickDisp : $pickRaw,
  4721. 'pick_time_raw' => $pickRaw,
  4722. 'process_count' => 0,
  4723. 'results' => [],
  4724. 'score_admin_ids' => [],
  4725. 'score_time_raw' => '',
  4726. 'customer_complaint'=> 0,
  4727. 'complaint_remark' => '',
  4728. 'order_interrupt' => 0,
  4729. 'delivery_status' => '',
  4730. 'delivery_date' => '',
  4731. 'remark' => '',
  4732. ];
  4733. }
  4734. $g = &$groups[$ccydh];
  4735. $g['scydgy_ids'][] = $sid;
  4736. $g['process_count']++;
  4737. if ($g['scydgy_id'] <= 0) {
  4738. $g['scydgy_id'] = $sid;
  4739. }
  4740. if ($g['CYJMC'] === '') {
  4741. $g['CYJMC'] = trim((string)($po['CYJMC'] ?? ''));
  4742. }
  4743. if ($g['CCLBMMC'] === '') {
  4744. $g['CCLBMMC'] = trim((string)($po['CCLBMMC'] ?? ''));
  4745. }
  4746. if ($g['pick_company_name'] === '') {
  4747. $g['pick_company_name'] = trim((string)($po['pick_company_name'] ?? ''));
  4748. }
  4749. $pt = trim((string)($po['pick_time'] ?? ''));
  4750. if ($pt !== '' && ($g['pick_time_raw'] === '' || strcmp($pt, $g['pick_time_raw']) > 0)) {
  4751. $g['pick_time_raw'] = $pt;
  4752. $disp = \app\common\library\ProcuremenTime::formatDisplayDateTime($pt);
  4753. $g['pick_time'] = $disp !== '' ? $disp : $pt;
  4754. }
  4755. $gymc = trim((string)($po['CGYMC'] ?? ''));
  4756. if ($gymc !== '' && !in_array($gymc, $g['CGYMC_list'], true)) {
  4757. $g['CGYMC_list'][] = $gymc;
  4758. }
  4759. $sc = $scoreMap[$sid] ?? null;
  4760. $res = is_array($sc) ? trim((string)($sc['result'] ?? '')) : '';
  4761. $g['results'][] = $res;
  4762. if (is_array($sc) && $res !== '') {
  4763. $aid = (int)($sc['admin_id'] ?? 0);
  4764. if ($aid > 0) {
  4765. $g['score_admin_ids'][$aid] = true;
  4766. }
  4767. if ((int)($sc['customer_complaint'] ?? 0) === 1) {
  4768. $g['customer_complaint'] = 1;
  4769. }
  4770. $crm = trim((string)($sc['complaint_remark'] ?? ''));
  4771. if ($crm !== '' && $g['complaint_remark'] === '') {
  4772. $g['complaint_remark'] = $crm;
  4773. }
  4774. if ((int)($sc['order_interrupt'] ?? 0) === 1) {
  4775. $g['order_interrupt'] = 1;
  4776. }
  4777. $ds = trim((string)($sc['delivery_status'] ?? ''));
  4778. if ($ds !== '' && $g['delivery_status'] === '') {
  4779. $g['delivery_status'] = $ds;
  4780. }
  4781. $dd = trim((string)($sc['delivery_date'] ?? ''));
  4782. if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dd, $mdd) && $g['delivery_date'] === '') {
  4783. $g['delivery_date'] = $mdd[1];
  4784. }
  4785. $rm = trim((string)($sc['remark'] ?? ''));
  4786. if ($rm !== '' && $g['remark'] === '') {
  4787. $g['remark'] = $rm;
  4788. }
  4789. $st = trim((string)($sc['updatetime'] ?? ''));
  4790. if ($st === '') {
  4791. $st = trim((string)($sc['createtime'] ?? ''));
  4792. }
  4793. if ($st !== '' && ($g['score_time_raw'] === '' || strcmp($st, $g['score_time_raw']) > 0)) {
  4794. $g['score_time_raw'] = $st;
  4795. }
  4796. } elseif (is_array($sc)) {
  4797. // 仅填了交货、尚未质量评分
  4798. $ds = trim((string)($sc['delivery_status'] ?? ''));
  4799. if ($ds !== '' && $g['delivery_status'] === '') {
  4800. $g['delivery_status'] = $ds;
  4801. }
  4802. $dd = trim((string)($sc['delivery_date'] ?? ''));
  4803. if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dd, $mdd) && $g['delivery_date'] === '') {
  4804. $g['delivery_date'] = $mdd[1];
  4805. }
  4806. $st = trim((string)($sc['updatetime'] ?? ''));
  4807. if ($st === '') {
  4808. $st = trim((string)($sc['createtime'] ?? ''));
  4809. }
  4810. if ($st !== '' && ($g['score_time_raw'] === '' || strcmp($st, $g['score_time_raw']) > 0)) {
  4811. $g['score_time_raw'] = $st;
  4812. }
  4813. }
  4814. unset($g);
  4815. }
  4816. $out = [];
  4817. foreach ($groups as $ccydh => $g) {
  4818. $gymcList = is_array($g['CGYMC_list'] ?? null) ? $g['CGYMC_list'] : [];
  4819. $company = (string)($g['pick_company_name'] ?? '');
  4820. $cyjmc = (string)($g['CYJMC'] ?? '');
  4821. if ($keyword !== '') {
  4822. $blob = $ccydh . ' ' . $cyjmc . ' ' . implode('、', $gymcList) . ' ' . $company;
  4823. if (mb_stripos($blob, $keyword) === false) {
  4824. continue;
  4825. }
  4826. }
  4827. $results = is_array($g['results'] ?? null) ? $g['results'] : [];
  4828. $uniq = [];
  4829. $allScored = true;
  4830. foreach ($results as $r) {
  4831. $r = trim((string)$r);
  4832. if ($r === '') {
  4833. $allScored = false;
  4834. continue;
  4835. }
  4836. $uniq[$r] = true;
  4837. }
  4838. $orderResult = '';
  4839. if ($allScored && count($uniq) === 1) {
  4840. $keys = array_keys($uniq);
  4841. $orderResult = (string)($keys[0] ?? '');
  4842. } elseif ($allScored && count($uniq) > 1) {
  4843. $orderResult = '';
  4844. }
  4845. $deliveryStatus = trim((string)($g['delivery_status'] ?? ''));
  4846. $hasDelivery = ($deliveryStatus === '准时' || $deliveryStatus === '滞后');
  4847. if ($scope === 'quality') {
  4848. if ($tab === 'pending' && $orderResult !== '') {
  4849. continue;
  4850. }
  4851. if ($tab === 'scored') {
  4852. if ($orderResult !== '合格' && $orderResult !== '不合格') {
  4853. continue;
  4854. }
  4855. if ($adminId <= 0) {
  4856. continue;
  4857. }
  4858. $adminIds = is_array($g['score_admin_ids'] ?? null) ? $g['score_admin_ids'] : [];
  4859. if (empty($adminIds[$adminId])) {
  4860. continue;
  4861. }
  4862. }
  4863. } else {
  4864. // 交货:待评=尚未填准时/滞后;已评=已填
  4865. if ($tab === 'pending' && $hasDelivery) {
  4866. continue;
  4867. }
  4868. if ($tab === 'scored' && !$hasDelivery) {
  4869. continue;
  4870. }
  4871. }
  4872. $scoreTimeRaw = trim((string)($g['score_time_raw'] ?? ''));
  4873. $scoreTime = $scoreTimeRaw !== ''
  4874. ? \app\common\library\ProcuremenTime::formatDisplayDateTime($scoreTimeRaw)
  4875. : '';
  4876. $out[] = [
  4877. 'CCYDH' => $ccydh,
  4878. 'scydgy_id' => (int)($g['scydgy_id'] ?? 0),
  4879. 'scydgy_ids' => array_values(array_unique(array_map('intval', $g['scydgy_ids'] ?? []))),
  4880. 'CYJMC' => $cyjmc,
  4881. 'CGYMC' => $gymcList !== [] ? implode('、', $gymcList) : '',
  4882. 'CCLBMMC' => (string)($g['CCLBMMC'] ?? ''),
  4883. 'pick_company_name' => $company,
  4884. 'pick_time' => (string)($g['pick_time'] ?? ''),
  4885. 'score_time' => $scoreTime !== '' ? $scoreTime : $scoreTimeRaw,
  4886. 'score_time_raw' => $scoreTimeRaw,
  4887. 'process_count' => (int)($g['process_count'] ?? 0),
  4888. 'result' => $orderResult,
  4889. 'customer_complaint' => (int)($g['customer_complaint'] ?? 0),
  4890. 'complaint_remark' => (string)($g['complaint_remark'] ?? ''),
  4891. 'order_interrupt' => (int)($g['order_interrupt'] ?? 0),
  4892. 'delivery_status' => (string)($g['delivery_status'] ?? ''),
  4893. 'delivery_date' => (string)($g['delivery_date'] ?? ''),
  4894. 'remark' => (string)($g['remark'] ?? ''),
  4895. ];
  4896. }
  4897. usort($out, static function ($a, $b) use ($tab) {
  4898. if ($tab === 'scored') {
  4899. $ta = (string)($a['score_time_raw'] ?? '');
  4900. $tb = (string)($b['score_time_raw'] ?? '');
  4901. if ($ta !== $tb) {
  4902. return strcmp($tb, $ta);
  4903. }
  4904. }
  4905. $ta = (string)($a['pick_time'] ?? '');
  4906. $tb = (string)($b['pick_time'] ?? '');
  4907. if ($ta !== $tb) {
  4908. return strcmp($tb, $ta);
  4909. }
  4910. return strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  4911. });
  4912. return $out;
  4913. }
  4914. /**
  4915. * 业务员:新增订单询价页
  4916. */
  4917. public function rfqadd()
  4918. {
  4919. $user = $this->mprocGetUser();
  4920. if (!$user) {
  4921. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  4922. $safe = $this->mprocSanitizeRedirectUrl($uri);
  4923. if ($safe !== '') {
  4924. Session::set('mproc_intended_url', $safe);
  4925. }
  4926. $this->redirect($this->mprocBuildLoginUrl($safe));
  4927. return;
  4928. }
  4929. if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'rfq')) {
  4930. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  4931. if ($jump === '') {
  4932. $this->mprocDropCurrentLogin();
  4933. $this->redirect(url('index/index/login'));
  4934. return;
  4935. }
  4936. $this->redirect($jump);
  4937. return;
  4938. }
  4939. $profile = $this->mprocProfileForUser($user);
  4940. $defaultDept = trim((string)($profile['department'] ?? ''));
  4941. if ($defaultDept === '' || $defaultDept === '业务员' || $defaultDept === '管理员') {
  4942. $defaultDept = '营销中心';
  4943. }
  4944. $statusTab = trim((string)$this->request->get('status', 'pending'));
  4945. if ($statusTab !== 'quoted') {
  4946. $statusTab = 'pending';
  4947. }
  4948. $focusSid = (int)$this->request->param('focus_sid', 0);
  4949. if ($focusSid >= 0) {
  4950. $focusSid = 0;
  4951. }
  4952. $this->view->assign('mprocProfile', $profile);
  4953. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  4954. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  4955. $this->view->assign('nextOrderCcydh', $this->mprocAllocateManualOrderCcydh());
  4956. $this->view->assign('defaultCclbmmc', $defaultDept);
  4957. $this->view->assign('adminNickname', trim((string)($profile['contact_name'] ?? '')) ?: '业务员');
  4958. $this->view->assign('rfqDeptOptions', $this->mprocLoadRfqDeptNameOptions());
  4959. $this->view->assign('rfqStatusTab', $statusTab);
  4960. $this->view->assign('rfqFocusSid', $focusSid);
  4961. $this->view->assign('rows', $this->mprocLoadRfqAddRows($user, '', $statusTab));
  4962. return $this->view->fetch();
  4963. }
  4964. /**
  4965. * 业务员询价列表 JSON(本人发起或被通知)
  4966. * GET:q、status=pending|quoted
  4967. */
  4968. public function rfqaddlist()
  4969. {
  4970. $user = $this->mprocRequireRfqUser();
  4971. $q = trim((string)$this->request->get('q', ''));
  4972. $status = trim((string)$this->request->get('status', 'pending'));
  4973. if ($status !== 'quoted') {
  4974. $status = 'pending';
  4975. }
  4976. $rows = $this->mprocLoadRfqAddRows($user, $q, $status);
  4977. $this->success('ok', null, ['rows' => $rows, 'total' => count($rows), 'status' => $status]);
  4978. }
  4979. /**
  4980. * 业务员查看询价报价(供应商 + 单价)
  4981. * GET:scydgy_id
  4982. */
  4983. public function rfqaddquotes()
  4984. {
  4985. $user = $this->mprocRequireRfqUser();
  4986. $sid = (int)$this->request->param('scydgy_id', 0);
  4987. if ($sid >= 0) {
  4988. $this->error('仅支持手工询价单');
  4989. }
  4990. $po = $this->mprocLoadAccessibleRfqOrder($user, $sid);
  4991. if (!$po) {
  4992. $this->error('询价单不存在或无权查看');
  4993. }
  4994. $list = [];
  4995. try {
  4996. $rows = Db::table('purchase_order_detail')
  4997. ->where('scydgy_id', $sid)
  4998. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  4999. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')')
  5000. ->field('id,company_name,amount')
  5001. ->order('id', 'asc')
  5002. ->select();
  5003. } catch (\Throwable $e) {
  5004. try {
  5005. $rows = Db::table('purchase_order_detail')
  5006. ->where('scydgy_id', $sid)
  5007. ->field('id,company_name,amount')
  5008. ->order('id', 'asc')
  5009. ->select();
  5010. } catch (\Throwable $e2) {
  5011. $rows = [];
  5012. }
  5013. }
  5014. if (!is_array($rows)) {
  5015. $rows = [];
  5016. }
  5017. foreach ($rows as $row) {
  5018. if (!is_array($row)) {
  5019. continue;
  5020. }
  5021. $amount = trim((string)($row['amount'] ?? ''));
  5022. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  5023. $list[] = [
  5024. 'company_name' => trim((string)($row['company_name'] ?? '')),
  5025. 'amount' => $amount,
  5026. 'amount_text' => $isQuoted ? $amount : '',
  5027. 'is_quoted' => $isQuoted,
  5028. ];
  5029. }
  5030. $this->success('ok', null, [
  5031. 'scydgy_id' => $sid,
  5032. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  5033. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  5034. 'list' => $list,
  5035. ]);
  5036. }
  5037. /**
  5038. * 业务员提交新增订单询价
  5039. * POST:CYJMC、CCLBMMC、CGYMC、CDW、This_quantity、ceilingPrice、CDF、MBZ
  5040. */
  5041. public function rfqaddsave()
  5042. {
  5043. $user = $this->mprocRequireRfqUser();
  5044. if (!$this->request->isPost()) {
  5045. $this->error('请使用 POST');
  5046. }
  5047. $profile = $this->mprocProfileForUser($user);
  5048. $cyjmc = trim((string)$this->request->post('CYJMC', ''));
  5049. $cgymc = trim((string)$this->request->post('CGYMC', ''));
  5050. $cclbmmc = trim((string)$this->request->post('CCLBMMC', ''));
  5051. if ($cyjmc === '') {
  5052. $this->error('请填写印件名称');
  5053. }
  5054. if ($cclbmmc === '') {
  5055. $cclbmmc = trim((string)($profile['department'] ?? ''));
  5056. }
  5057. if ($cclbmmc === '') {
  5058. $cclbmmc = '营销中心';
  5059. }
  5060. $cywyxm = trim((string)($profile['contact_name'] ?? ''));
  5061. if ($cywyxm === '') {
  5062. $cywyxm = trim((string)($user['username'] ?? ''));
  5063. }
  5064. $now = date('Y-m-d H:i:s');
  5065. $lockName = 'procuremen_manual_order_alloc';
  5066. if (!$this->mprocAcquireNamedLock($lockName, 10)) {
  5067. $this->error('系统繁忙,请稍后重试');
  5068. }
  5069. try {
  5070. $ccydh = $this->mprocAllocateManualOrderCcydh();
  5071. $sid = $this->mprocAllocateManualScydgyId();
  5072. $data = [
  5073. 'scydgy_id' => $sid,
  5074. 'CCYDH' => $ccydh,
  5075. 'CYJMC' => $cyjmc,
  5076. 'CGYMC' => $cgymc,
  5077. 'CCLBMMC' => $cclbmmc,
  5078. 'CDW' => trim((string)$this->request->post('CDW', '')),
  5079. 'NGZL' => '',
  5080. 'CDF' => trim((string)$this->request->post('CDF', '')),
  5081. 'cGzzxMc' => '',
  5082. 'MBZ' => trim((string)$this->request->post('MBZ', '')),
  5083. 'cywyxm' => $cywyxm,
  5084. 'notify_salesman' => '',
  5085. 'rfq_salesman_notified' => 0,
  5086. 'rfq_salesman_notify_time' => null,
  5087. 'This_quantity' => trim((string)$this->request->post('This_quantity', '')),
  5088. 'ceilingPrice' => trim((string)$this->request->post('ceilingPrice', '')),
  5089. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  5090. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5091. 'createtime' => $now,
  5092. 'dStamp' => $now,
  5093. 'dputrecord' => $now,
  5094. ];
  5095. try {
  5096. $this->mprocEnsureRfqSalesmanColumns();
  5097. Db::table('purchase_order')->insert($data);
  5098. } catch (\Throwable $e) {
  5099. $this->error('新增失败:' . $e->getMessage());
  5100. }
  5101. $nextCcydh = $this->mprocAllocateManualOrderCcydh();
  5102. } finally {
  5103. $this->mprocReleaseNamedLock($lockName);
  5104. }
  5105. $this->success('新增成功', '', [
  5106. 'scydgy_id' => $sid,
  5107. 'CCYDH' => $ccydh,
  5108. 'nextOrderCcydh' => $nextCcydh,
  5109. ]);
  5110. }
  5111. /**
  5112. * MySQL 命名锁(跨连接防并发撞号)
  5113. */
  5114. protected function mprocAcquireNamedLock(string $name, int $timeoutSec = 10): bool
  5115. {
  5116. $name = trim($name);
  5117. if ($name === '') {
  5118. return false;
  5119. }
  5120. try {
  5121. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  5122. $rows = Db::query('SELECT GET_LOCK(\'' . $nameSql . '\', ' . max(1, $timeoutSec) . ') AS locked');
  5123. if (!is_array($rows) || $rows === []) {
  5124. return false;
  5125. }
  5126. $v = $rows[0]['locked'] ?? $rows[0]['LOCKED'] ?? null;
  5127. return (int)$v === 1;
  5128. } catch (\Throwable $e) {
  5129. return false;
  5130. }
  5131. }
  5132. protected function mprocReleaseNamedLock(string $name): void
  5133. {
  5134. $name = trim($name);
  5135. if ($name === '') {
  5136. return;
  5137. }
  5138. try {
  5139. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  5140. Db::query('SELECT RELEASE_LOCK(\'' . $nameSql . '\')');
  5141. } catch (\Throwable $e) {
  5142. }
  5143. }
  5144. protected function mprocAllocateManualScydgyId(): int
  5145. {
  5146. try {
  5147. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  5148. $min = (int)$min;
  5149. return $min < 0 ? $min - 1 : -1;
  5150. } catch (\Throwable $e) {
  5151. return -1;
  5152. }
  5153. }
  5154. /**
  5155. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  5156. * 调用方须在命名锁内执行,避免并发重复
  5157. */
  5158. protected function mprocAllocateManualOrderCcydh(): string
  5159. {
  5160. $prefix = 'YW' . date('Ymd');
  5161. $maxSeq = 0;
  5162. try {
  5163. $rows = Db::table('purchase_order')
  5164. ->where('CCYDH', 'like', $prefix . '%')
  5165. ->column('CCYDH');
  5166. if (is_array($rows)) {
  5167. foreach ($rows as $ccydh) {
  5168. $ccydh = trim((string)$ccydh);
  5169. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3,})$/', $ccydh, $m)) {
  5170. $maxSeq = max($maxSeq, (int)$m[1]);
  5171. }
  5172. }
  5173. }
  5174. } catch (\Throwable $e) {
  5175. }
  5176. $next = $maxSeq + 1;
  5177. $width = $next > 999 ? strlen((string)$next) : 3;
  5178. return $prefix . str_pad((string)$next, $width, '0', STR_PAD_LEFT);
  5179. }
  5180. /**
  5181. * @return string[]
  5182. */
  5183. protected function mprocLoadRfqDeptNameOptions(): array
  5184. {
  5185. $out = [];
  5186. try {
  5187. $vals = Db::table('mcyd')
  5188. ->where('CCLBMMC', '<>', '')
  5189. ->whereNotNull('CCLBMMC')
  5190. ->distinct(true)
  5191. ->limit(300)
  5192. ->column('CCLBMMC');
  5193. } catch (\Throwable $e) {
  5194. $vals = [];
  5195. }
  5196. if (is_array($vals)) {
  5197. foreach ($vals as $v) {
  5198. $v = trim((string)$v);
  5199. if ($v === '' || isset($out[$v])) {
  5200. continue;
  5201. }
  5202. $out[$v] = $v;
  5203. }
  5204. }
  5205. try {
  5206. $poVals = Db::table('purchase_order')
  5207. ->where('CCLBMMC', '<>', '')
  5208. ->whereNotNull('CCLBMMC')
  5209. ->distinct(true)
  5210. ->limit(200)
  5211. ->column('CCLBMMC');
  5212. } catch (\Throwable $e) {
  5213. $poVals = [];
  5214. }
  5215. if (is_array($poVals)) {
  5216. foreach ($poVals as $v) {
  5217. $v = trim((string)$v);
  5218. if ($v === '' || isset($out[$v])) {
  5219. continue;
  5220. }
  5221. $out[$v] = $v;
  5222. }
  5223. }
  5224. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  5225. if (!isset($out[$preset])) {
  5226. $out[$preset] = $preset;
  5227. }
  5228. }
  5229. $list = array_values($out);
  5230. usort($list, static function ($a, $b) {
  5231. $weight = [
  5232. '营销中心' => 1,
  5233. '业务部' => 2,
  5234. '市场部' => 3,
  5235. '外贸部' => 4,
  5236. '新华技术业务部' => 5,
  5237. ];
  5238. $wa = $weight[$a] ?? 100;
  5239. $wb = $weight[$b] ?? 100;
  5240. if ($wa !== $wb) {
  5241. return $wa <=> $wb;
  5242. }
  5243. return strcmp((string)$a, (string)$b);
  5244. });
  5245. return $list;
  5246. }
  5247. protected function mprocEnsureRfqSalesmanColumns(): void
  5248. {
  5249. static $ok = false;
  5250. if ($ok) {
  5251. return;
  5252. }
  5253. $alters = [
  5254. 'notify_salesman' => "ADD COLUMN `notify_salesman` varchar(500) NOT NULL DEFAULT '' COMMENT '通知业务员' AFTER `cywyxm`",
  5255. 'rfq_salesman_notified' => "ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '是否已通知业务员' AFTER `notify_salesman`",
  5256. 'rfq_salesman_notify_time' => "ADD COLUMN `rfq_salesman_notify_time` datetime DEFAULT NULL COMMENT '通知业务员时间' AFTER `rfq_salesman_notified`",
  5257. ];
  5258. foreach ($alters as $col => $sql) {
  5259. try {
  5260. $exists = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  5261. if (is_array($exists) && $exists !== []) {
  5262. continue;
  5263. }
  5264. Db::execute('ALTER TABLE `purchase_order` ' . $sql);
  5265. } catch (\Throwable $e) {
  5266. }
  5267. }
  5268. $ok = true;
  5269. }
  5270. /**
  5271. * 校验业务员是否可访问该手工询价单
  5272. *
  5273. * @param array<string, mixed> $user
  5274. * @return array<string, mixed>|null
  5275. */
  5276. protected function mprocLoadAccessibleRfqOrder(array $user, int $sid): ?array
  5277. {
  5278. if ($sid >= 0) {
  5279. return null;
  5280. }
  5281. $profile = $this->mprocProfileForUser($user);
  5282. $adminName = trim((string)($profile['contact_name'] ?? ''));
  5283. if ($adminName === '') {
  5284. $adminName = trim((string)($user['username'] ?? ''));
  5285. }
  5286. $isSuper = $this->mprocAdminIsMobileSuper((int)($user['admin_id'] ?? 0));
  5287. $this->mprocEnsureRfqSalesmanColumns();
  5288. try {
  5289. $query = Db::table('purchase_order')
  5290. ->where('scydgy_id', $sid)
  5291. ->whereRaw(
  5292. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  5293. );
  5294. if (!$isSuper) {
  5295. if ($adminName === '') {
  5296. return null;
  5297. }
  5298. $query->where(function ($q2) use ($adminName) {
  5299. $q2->where('cywyxm', $adminName)
  5300. ->whereOr('notify_salesman', $adminName)
  5301. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  5302. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  5303. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  5304. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  5305. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  5306. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  5307. });
  5308. }
  5309. $row = $query->find();
  5310. } catch (\Throwable $e) {
  5311. return null;
  5312. }
  5313. return is_array($row) ? $row : null;
  5314. }
  5315. /**
  5316. * 手机端业务员询价列表(本人发起 / 被通知)
  5317. *
  5318. * @param array<string, mixed> $user
  5319. * @param string $status pending|quoted|''(空=全部)
  5320. * @return array<int, array<string, mixed>>
  5321. */
  5322. protected function mprocLoadRfqAddRows(array $user, string $q, string $status = ''): array
  5323. {
  5324. $profile = $this->mprocProfileForUser($user);
  5325. $adminName = trim((string)($profile['contact_name'] ?? ''));
  5326. if ($adminName === '') {
  5327. $adminName = trim((string)($user['username'] ?? ''));
  5328. }
  5329. $isSuper = $this->mprocAdminIsMobileSuper((int)($user['admin_id'] ?? 0));
  5330. $this->mprocEnsureRfqSalesmanColumns();
  5331. try {
  5332. $query = Db::table('purchase_order')
  5333. ->where('scydgy_id', '<', 0)
  5334. ->whereRaw(
  5335. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  5336. );
  5337. if (!$isSuper) {
  5338. if ($adminName === '') {
  5339. return [];
  5340. }
  5341. $query->where(function ($q2) use ($adminName) {
  5342. $q2->where('cywyxm', $adminName)
  5343. ->whereOr('notify_salesman', $adminName)
  5344. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  5345. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  5346. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  5347. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  5348. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  5349. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  5350. });
  5351. }
  5352. $q = trim($q);
  5353. if ($q !== '') {
  5354. $like = '%' . str_replace(['%', '_'], ['\\%', '\\_'], $q) . '%';
  5355. $query->where(function ($q2) use ($like) {
  5356. $q2->where('CCYDH', 'like', $like)
  5357. ->whereOr('CYJMC', 'like', $like)
  5358. ->whereOr('CGYMC', 'like', $like)
  5359. ->whereOr('CCLBMMC', 'like', $like)
  5360. ->whereOr('MBZ', 'like', $like);
  5361. });
  5362. }
  5363. $rows = $query
  5364. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,CDW,CDF,This_quantity,ceilingPrice,cywyxm,MBZ,status,wflow_status,rfq_salesman_notified,createtime,dStamp')
  5365. ->order('id', 'desc')
  5366. ->limit(200)
  5367. ->select();
  5368. } catch (\Throwable $e) {
  5369. $rows = [];
  5370. }
  5371. if (!is_array($rows)) {
  5372. $rows = [];
  5373. }
  5374. $out = [];
  5375. $sids = [];
  5376. foreach ($rows as $r) {
  5377. if (!is_array($r)) {
  5378. continue;
  5379. }
  5380. $sid = (int)($r['scydgy_id'] ?? 0);
  5381. if ($sid < 0) {
  5382. $sids[$sid] = $sid;
  5383. }
  5384. }
  5385. $quotedMap = $this->mprocLoadRfqQuotedSidMap(array_values($sids));
  5386. $status = trim($status);
  5387. if ($status !== 'pending' && $status !== 'quoted') {
  5388. $status = '';
  5389. }
  5390. foreach ($rows as $r) {
  5391. if (!is_array($r)) {
  5392. continue;
  5393. }
  5394. $sid = (int)($r['scydgy_id'] ?? 0);
  5395. $isQuoted = !empty($quotedMap[$sid]);
  5396. if ($status === 'pending' && $isQuoted) {
  5397. continue;
  5398. }
  5399. if ($status === 'quoted' && !$isQuoted) {
  5400. continue;
  5401. }
  5402. $created = trim((string)($r['createtime'] ?? ''));
  5403. if ($created === '' || stripos($created, '0000-00-00') === 0) {
  5404. $created = trim((string)($r['dStamp'] ?? ''));
  5405. }
  5406. if (preg_match('/^\d{10,}$/', $created)) {
  5407. $created = date('Y-m-d H:i:s', (int)$created);
  5408. }
  5409. if ($created !== '' && stripos($created, '0000-00-00') === 0) {
  5410. $created = '';
  5411. }
  5412. $out[] = [
  5413. 'id' => (int)($r['id'] ?? 0),
  5414. 'scydgy_id' => $sid,
  5415. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  5416. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  5417. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  5418. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  5419. 'CDW' => trim((string)($r['CDW'] ?? '')),
  5420. 'CDF' => trim((string)($r['CDF'] ?? '')),
  5421. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  5422. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  5423. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  5424. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  5425. 'progress_text' => $isQuoted ? '已报价' : '待询价',
  5426. 'createtime' => $created,
  5427. ];
  5428. }
  5429. return $out;
  5430. }
  5431. /**
  5432. * 哪些手工询价单已有有效报价(amount 非空且非 0)
  5433. *
  5434. * @param array<int, int> $sids
  5435. * @return array<int, bool>
  5436. */
  5437. protected function mprocLoadRfqQuotedSidMap(array $sids): array
  5438. {
  5439. $out = [];
  5440. $sids = array_values(array_unique(array_filter(array_map('intval', $sids), static function ($v) {
  5441. return $v < 0;
  5442. })));
  5443. if ($sids === []) {
  5444. return $out;
  5445. }
  5446. foreach (array_chunk($sids, 200) as $chunk) {
  5447. try {
  5448. $rows = Db::table('purchase_order_detail')
  5449. ->where('scydgy_id', 'in', $chunk)
  5450. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  5451. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')')
  5452. ->where('amount', '<>', '')
  5453. ->whereNotNull('amount')
  5454. ->where('amount', '<>', '0')
  5455. ->where('amount', '<>', '0.00')
  5456. ->field('scydgy_id')
  5457. ->group('scydgy_id')
  5458. ->select();
  5459. } catch (\Throwable $e) {
  5460. try {
  5461. $rows = Db::table('purchase_order_detail')
  5462. ->where('scydgy_id', 'in', $chunk)
  5463. ->where('amount', '<>', '')
  5464. ->whereNotNull('amount')
  5465. ->where('amount', '<>', '0')
  5466. ->where('amount', '<>', '0.00')
  5467. ->field('scydgy_id')
  5468. ->group('scydgy_id')
  5469. ->select();
  5470. } catch (\Throwable $e2) {
  5471. $rows = [];
  5472. }
  5473. }
  5474. if (!is_array($rows)) {
  5475. continue;
  5476. }
  5477. foreach ($rows as $r) {
  5478. if (!is_array($r)) {
  5479. continue;
  5480. }
  5481. $sid = (int)($r['scydgy_id'] ?? 0);
  5482. if ($sid < 0) {
  5483. $out[$sid] = true;
  5484. }
  5485. }
  5486. }
  5487. return $out;
  5488. }
  5489. /**
  5490. * @param array<string, mixed> $row
  5491. */
  5492. protected function mprocFormatRfqProgressText(array $row): string
  5493. {
  5494. $sid = (int)($row['scydgy_id'] ?? 0);
  5495. if ($sid < 0) {
  5496. $map = $this->mprocLoadRfqQuotedSidMap([$sid]);
  5497. if (!empty($map[$sid])) {
  5498. return '已报价';
  5499. }
  5500. }
  5501. return '待询价';
  5502. }
  5503. }