Index.php 233 KB

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