Index.php 282 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531
  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. /**
  54. * 手机端:HTML 错误不用框架跳转页(哭脸倒计时),改为普通 Toast 后跳转;Ajax/JSON 仍走原逻辑
  55. *
  56. * @param mixed $msg
  57. * @param string $url
  58. * @param mixed $data
  59. * @param int $wait
  60. * @param array $header
  61. * @return void
  62. */
  63. protected function error($msg = '', $url = null, $data = '', $wait = 3, array $header = [])
  64. {
  65. $type = method_exists($this, 'getResponseType') ? (string)$this->getResponseType() : 'html';
  66. if (strtolower($type) === 'html') {
  67. if ($url === null || $url === '') {
  68. $url = (string)url('index/index/index');
  69. } elseif ($url !== '' && strpos((string)$url, '://') === false && strpos((string)$url, '/') !== 0
  70. && strpos((string)$url, 'javascript:') !== 0) {
  71. $url = (string)\think\Url::build((string)$url);
  72. }
  73. if (is_string($url) && stripos($url, 'javascript:') === 0) {
  74. $url = (string)url('index/index/index');
  75. }
  76. $html = $this->view->fetch('toast_tip', [
  77. 'toastMsg' => (string)$msg,
  78. 'redirectUrl' => (string)$url,
  79. 'waitMs' => max(1000, ((int)$wait) * 1000),
  80. ]);
  81. $response = \think\Response::create($html, 'html', 200)->header($header);
  82. throw new \think\exception\HttpResponseException($response);
  83. }
  84. parent::error($msg, $url, $data, $wait, $header);
  85. }
  86. /** 登录有效小时数(用于前端 localStorage 过期时间) */
  87. protected function mprocKeepHours(): int
  88. {
  89. return max(1, (int)round($this->mprocTtlSeconds / 3600));
  90. }
  91. /**
  92. * 当前手机端登录用户;未登录返回 null(支持 Cookie 令牌 + 7 天记住登录)
  93. */
  94. protected function mprocGetUser()
  95. {
  96. $token = $this->mprocReadTokenFromRequest();
  97. if ($token !== '') {
  98. $user = $this->mprocLoadUserByToken($token);
  99. if ($user) {
  100. $token = $this->mprocTouchLoginState($user, $token);
  101. $user['token'] = $token;
  102. return $user;
  103. }
  104. }
  105. $user = $this->mprocUserFromRememberCookie();
  106. if (!$user) {
  107. return null;
  108. }
  109. $token = $this->mprocPackSignedAuthToken($user);
  110. $token = $this->mprocTouchLoginState($user, $token);
  111. $user['token'] = $token;
  112. return $user;
  113. }
  114. protected function mprocReadTokenFromRequest(): string
  115. {
  116. $token = Session::get('mproc_token');
  117. if ($token === null || $token === '') {
  118. $token = Cookie::get('mproc_token');
  119. }
  120. if ($token === null || $token === '') {
  121. $token = $this->request->header('X-Mproc-Token');
  122. }
  123. if ($token === null || $token === '') {
  124. $token = $this->request->request('mproc_token', '');
  125. }
  126. $token = trim((string)$token);
  127. if ($token === '') {
  128. return '';
  129. }
  130. if ($this->mprocIsSignedAuthToken($token)) {
  131. return $token;
  132. }
  133. $token = preg_replace('/[^a-f0-9]/i', '', $token);
  134. return strlen($token) >= 16 ? $token : '';
  135. }
  136. protected function mprocIsSignedAuthToken(string $token): bool
  137. {
  138. return strpos($token, '.') !== false
  139. && preg_match('/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/', $token) === 1;
  140. }
  141. protected function mprocAuthCacheKey(string $token): string
  142. {
  143. return 'mproc_u_' . md5($token);
  144. }
  145. /**
  146. * @return array<string, mixed>|null
  147. */
  148. protected function mprocLoadUserByToken(string $token): ?array
  149. {
  150. if ($this->mprocIsSignedAuthToken($token)) {
  151. if ($this->mprocIsAuthTokenRevoked($token)) {
  152. return null;
  153. }
  154. $user = $this->mprocUserFromSignedToken($token);
  155. if (!$user) {
  156. return null;
  157. }
  158. if (time() - (int)($user['login_time'] ?? 0) > $this->mprocTtlSeconds) {
  159. $this->mprocClearLogin($token);
  160. return null;
  161. }
  162. $user['token'] = $token;
  163. return $user;
  164. }
  165. $user = Cache::get('mproc_u_' . $token);
  166. if (!is_array($user)) {
  167. $user = $this->mprocUserFromRememberCookie();
  168. if (!$user) {
  169. return null;
  170. }
  171. }
  172. if (empty($user['phone']) && empty($user['account']) && empty($user['username'])) {
  173. return null;
  174. }
  175. if (time() - (int)($user['login_time'] ?? 0) > $this->mprocTtlSeconds) {
  176. $this->mprocClearLogin($token);
  177. return null;
  178. }
  179. $user['token'] = $token;
  180. return $user;
  181. }
  182. /**
  183. * 滑动续期:刷新签名令牌 / Cache / Session / Cookie(保留 7 天)
  184. *
  185. * @param array<string, mixed> $user
  186. */
  187. protected function mprocTouchLoginState(array $user, string $token): string
  188. {
  189. $user['login_time'] = time();
  190. if ($this->mprocIsSignedAuthToken($token)) {
  191. $token = $this->mprocPackSignedAuthToken($user);
  192. }
  193. Cache::set($this->mprocAuthCacheKey($token), $user, $this->mprocTtlSeconds + 86400);
  194. if (!$this->mprocIsSignedAuthToken($token)) {
  195. Cache::set('mproc_u_' . $token, $user, $this->mprocTtlSeconds + 86400);
  196. }
  197. Session::set('mproc_token', $token);
  198. $this->mprocSetTokenCookie($token);
  199. $this->mprocSetRememberCookie($user, $token);
  200. return $token;
  201. }
  202. /**
  203. * @return array<string, mixed>
  204. */
  205. protected function mprocCookieOptions(): array
  206. {
  207. $opts = [
  208. 'expire' => $this->mprocTtlSeconds,
  209. 'path' => '/',
  210. 'httponly' => true,
  211. ];
  212. if ($this->request->isSsl()) {
  213. $opts['secure'] = true;
  214. }
  215. if (PHP_VERSION_ID >= 70300) {
  216. $opts['samesite'] = 'Lax';
  217. }
  218. return $opts;
  219. }
  220. protected function mprocSetTokenCookie(string $token): void
  221. {
  222. Cookie::set('mproc_token', $token, $this->mprocCookieOptions());
  223. }
  224. /**
  225. * @param array<string, mixed> $user
  226. */
  227. protected function mprocSetRememberCookie(array $user, ?string $token = null): void
  228. {
  229. $val = $token !== null && $token !== '' ? $token : $this->mprocPackSignedAuthToken($user);
  230. Cookie::set('mproc_remember', $val, $this->mprocCookieOptions());
  231. }
  232. protected function mprocAuthSignSecret(): string
  233. {
  234. $key = trim((string)Config::get('mproc.auth_sign_key'));
  235. if ($key === '') {
  236. $key = (string)Config::get('database.database') . '|' . (string)Config::get('database.hostname') . '|mproc';
  237. }
  238. return hash('sha256', $key);
  239. }
  240. /**
  241. * @param array<string, mixed> $user
  242. */
  243. protected function mprocPackSignedAuthToken(array $user): string
  244. {
  245. $payload = [
  246. 'uid' => (int)($user['customer_user_id'] ?? $user['customer_id'] ?? 0),
  247. 'phone' => trim((string)($user['phone'] ?? '')),
  248. 'uname' => trim((string)($user['username'] ?? $user['account'] ?? '')),
  249. 'admin' => !empty($user['is_admin']) ? 1 : 0,
  250. 'lt' => time(),
  251. ];
  252. $b64 = rtrim(strtr(base64_encode(json_encode($payload, JSON_UNESCAPED_UNICODE)), '+/', '-_'), '=');
  253. $sig = hash_hmac('sha256', $b64, $this->mprocAuthSignSecret());
  254. return $b64 . '.' . $sig;
  255. }
  256. /** @deprecated 使用 mprocPackSignedAuthToken */
  257. protected function mprocPackRememberCookie(array $user): string
  258. {
  259. return $this->mprocPackSignedAuthToken($user);
  260. }
  261. /**
  262. * @return array<string, mixed>|null
  263. */
  264. protected function mprocUserFromSignedToken(string $raw): ?array
  265. {
  266. $parts = explode('.', trim($raw), 2);
  267. if (count($parts) !== 2) {
  268. return null;
  269. }
  270. $b64 = $parts[0];
  271. $sig = $parts[1];
  272. if (!hash_equals(hash_hmac('sha256', $b64, $this->mprocAuthSignSecret()), $sig)) {
  273. return null;
  274. }
  275. $pad = strlen($b64) % 4;
  276. if ($pad > 0) {
  277. $b64 .= str_repeat('=', 4 - $pad);
  278. }
  279. $json = base64_decode(strtr($b64, '-_', '+/'), true);
  280. if ($json === false || $json === '') {
  281. return null;
  282. }
  283. $payload = json_decode($json, true);
  284. if (!is_array($payload)) {
  285. return null;
  286. }
  287. $lt = (int)($payload['lt'] ?? 0);
  288. if ($lt <= 0 || time() - $lt > $this->mprocTtlSeconds) {
  289. return null;
  290. }
  291. return $this->mprocRebuildUserFromRememberPayload($payload, $lt);
  292. }
  293. /**
  294. * @return array<string, mixed>|null
  295. */
  296. protected function mprocUserFromRememberCookie(): ?array
  297. {
  298. $raw = Cookie::get('mproc_remember');
  299. if ($raw === null || $raw === '') {
  300. $raw = Cookie::get('mproc_token');
  301. }
  302. if ($raw === null || $raw === '') {
  303. return null;
  304. }
  305. $raw = (string)$raw;
  306. if ($this->mprocIsAuthTokenRevoked($raw)) {
  307. return null;
  308. }
  309. return $this->mprocUserFromSignedToken($raw);
  310. }
  311. /**
  312. * @param array<string, mixed> $payload
  313. * @return array<string, mixed>|null
  314. */
  315. protected function mprocRebuildUserFromRememberPayload(array $payload, int $loginTime): ?array
  316. {
  317. if (!empty($payload['admin'])) {
  318. $uname = trim((string)($payload['uname'] ?? ''));
  319. if ($uname === '') {
  320. return null;
  321. }
  322. try {
  323. $row = Db::name('admin')->where('username', $uname)->find();
  324. } catch (\Throwable $e) {
  325. $row = null;
  326. }
  327. if (!is_array($row) || ($row['status'] ?? '') === 'hidden') {
  328. return null;
  329. }
  330. return [
  331. 'phone' => trim((string)($row['mobile'] ?? '')),
  332. 'company_name' => '',
  333. 'username' => $uname,
  334. 'customer_user_id' => 0,
  335. 'admin_id' => (int)($row['id'] ?? 0),
  336. 'login_type' => 'remember',
  337. 'is_admin' => 1,
  338. 'login_time' => $loginTime,
  339. ];
  340. }
  341. $cid = (int)($payload['uid'] ?? 0);
  342. if ($cid > 0) {
  343. try {
  344. $cu = Db::table('customer')->where('id', $cid)->find();
  345. } catch (\Throwable $e) {
  346. $cu = null;
  347. }
  348. if (is_array($cu) && $cu !== [] && $this->mprocCustomerUserActive($cu)) {
  349. $user = $this->mprocLoginPayloadFromCustomer($cu, 'remember');
  350. $user['login_time'] = $loginTime;
  351. return $user;
  352. }
  353. }
  354. $phone = trim((string)($payload['phone'] ?? ''));
  355. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  356. $cu = $this->mprocFindCustomerUserByMobile($phone);
  357. if ($cu) {
  358. $user = $this->mprocLoginPayloadFromCustomer($cu, 'remember');
  359. $user['login_time'] = $loginTime;
  360. return $user;
  361. }
  362. }
  363. return null;
  364. }
  365. protected function mprocAuthRevokeCacheKey(string $token): string
  366. {
  367. return 'mproc_revoked_' . md5($token);
  368. }
  369. protected function mprocRevokeAuthToken(string $token): void
  370. {
  371. $token = trim($token);
  372. if ($token === '') {
  373. return;
  374. }
  375. try {
  376. Cache::set($this->mprocAuthRevokeCacheKey($token), 1, $this->mprocTtlSeconds + 86400);
  377. } catch (\Throwable $e) {
  378. }
  379. }
  380. protected function mprocIsAuthTokenRevoked(string $token): bool
  381. {
  382. $token = trim($token);
  383. if ($token === '') {
  384. return false;
  385. }
  386. try {
  387. return (bool)Cache::get($this->mprocAuthRevokeCacheKey($token));
  388. } catch (\Throwable $e) {
  389. return false;
  390. }
  391. }
  392. /**
  393. * 按与写入时相同的 path/secure/samesite 清除 Cookie,避免仅 delete 时删不掉
  394. */
  395. protected function mprocExpireAuthCookies(): void
  396. {
  397. $opts = $this->mprocCookieOptions();
  398. $opts['expire'] = -3600;
  399. try {
  400. Cookie::set('mproc_token', '', $opts);
  401. Cookie::set('mproc_remember', '', $opts);
  402. } catch (\Throwable $e) {
  403. }
  404. try {
  405. Cookie::delete('mproc_token');
  406. Cookie::delete('mproc_remember');
  407. } catch (\Throwable $e) {
  408. }
  409. unset($_COOKIE['mproc_token'], $_COOKIE['mproc_remember']);
  410. $prefix = (string)Config::get('cookie.prefix');
  411. if ($prefix !== '') {
  412. unset($_COOKIE[$prefix . 'mproc_token'], $_COOKIE[$prefix . 'mproc_remember']);
  413. }
  414. }
  415. protected function mprocClearLogin($token)
  416. {
  417. $token = trim((string)($token ?? ''));
  418. if ($token !== '') {
  419. $this->mprocRevokeAuthToken($token);
  420. try {
  421. Cache::rm($this->mprocAuthCacheKey($token));
  422. } catch (\Throwable $e) {
  423. }
  424. if (!$this->mprocIsSignedAuthToken($token)) {
  425. try {
  426. Cache::rm('mproc_u_' . $token);
  427. } catch (\Throwable $e) {
  428. }
  429. }
  430. }
  431. // 同时作废 remember / 另一份 cookie 里可能残留的签名令牌
  432. foreach (['mproc_token', 'mproc_remember'] as $ck) {
  433. $raw = Cookie::get($ck);
  434. if ($raw !== null && $raw !== '' && (string)$raw !== $token) {
  435. $this->mprocRevokeAuthToken((string)$raw);
  436. }
  437. }
  438. Session::delete('mproc_token');
  439. $this->mprocExpireAuthCookies();
  440. }
  441. /**
  442. * 登录成功后的回跳地址校验(仅允许本站手机端首页 / 入库评分页,防止开放重定向)
  443. *
  444. * @param string $raw GET/POST 的 redirect 或当前 REQUEST_URI
  445. */
  446. protected function mprocSanitizeRedirectUrl($raw)
  447. {
  448. $s = str_replace(["\r", "\n", "\0"], '', trim((string)$raw));
  449. if ($s === '') {
  450. return '';
  451. }
  452. if (preg_match('#^https?://#i', $s)) {
  453. $h = parse_url($s, PHP_URL_HOST);
  454. if (!is_string($h) || strcasecmp($h, (string)$this->request->host()) !== 0) {
  455. return '';
  456. }
  457. $path = parse_url($s, PHP_URL_PATH);
  458. $query = parse_url($s, PHP_URL_QUERY);
  459. $s = (is_string($path) && $path !== '' ? $path : '/');
  460. if (is_string($query) && $query !== '') {
  461. $s .= '?' . $query;
  462. }
  463. }
  464. if (strpos($s, '://') !== false) {
  465. return '';
  466. }
  467. if ($s === '' || ($s[0] !== '/' && stripos($s, 'index.php') !== 0)) {
  468. return '';
  469. }
  470. if ($s[0] !== '/') {
  471. $s = '/' . ltrim($s, '/');
  472. }
  473. if (strpos($s, '//') === 0) {
  474. return '';
  475. }
  476. $okHome = stripos($s, 'index/index/index') !== false;
  477. $okInbound = stripos($s, 'index/index/inboundscore') !== false;
  478. $okDelivery = stripos($s, 'index/index/deliveryscore') !== false;
  479. $okRfqAdd = stripos($s, 'index/index/rfqadd') !== false;
  480. $okNote = stripos($s, 'index/index/deliverynote') !== false;
  481. if (!$okHome && !$okInbound && !$okDelivery && !$okRfqAdd && !$okNote) {
  482. return '';
  483. }
  484. if (stripos($s, 'index/index/login') !== false) {
  485. return '';
  486. }
  487. return $s;
  488. }
  489. protected function mprocRememberFocusEid(int $focusEid): void
  490. {
  491. if ($focusEid > 0) {
  492. Session::set('mproc_focus_eid', $focusEid);
  493. }
  494. }
  495. protected function mprocPullSessionFocusEid(): int
  496. {
  497. $fe = (int)Session::get('mproc_focus_eid', 0);
  498. if ($fe > 0) {
  499. Session::delete('mproc_focus_eid');
  500. }
  501. return $fe;
  502. }
  503. /**
  504. * 从 URI/query 中解析 focus_eid(兼容邮件客户端把 &amp;focus_eid 拼进上一参数值的情况)
  505. */
  506. protected function mprocParseFocusEidFromUriString(string $uri): int
  507. {
  508. if ($uri === '' || stripos($uri, 'focus_eid') === false) {
  509. return 0;
  510. }
  511. if (preg_match('/(?:[?&;]|%26)(?:amp;)*focus_eid=(\d+)/i', $uri, $m)) {
  512. return (int)$m[1];
  513. }
  514. $query = parse_url($uri, PHP_URL_QUERY);
  515. if (!is_string($query) || $query === '') {
  516. return 0;
  517. }
  518. $q = [];
  519. parse_str($query, $q);
  520. if (!is_array($q)) {
  521. return 0;
  522. }
  523. if (isset($q['focus_eid'])) {
  524. $fe = (int)$q['focus_eid'];
  525. if ($fe > 0) {
  526. return $fe;
  527. }
  528. }
  529. foreach ($q as $k => $v) {
  530. $blob = (is_string($k) ? $k : '') . '=' . (is_scalar($v) ? (string)$v : '');
  531. if (preg_match('/(?:^|[?&;]|%26)(?:amp;)*focus_eid=(\d+)/i', $blob, $m2)) {
  532. return (int)$m2[1];
  533. }
  534. }
  535. return 0;
  536. }
  537. /**
  538. * 从请求中读取短信/邮件直达明细 ID(兼容 query、pathinfo、REQUEST_URI、登录回跳 Session)
  539. */
  540. protected function mprocReadFocusEidFromRequest(): int
  541. {
  542. $fe = (int)$this->request->param('focus_eid', 0);
  543. if ($fe > 0) {
  544. $this->mprocRememberFocusEid($fe);
  545. return $fe;
  546. }
  547. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  548. $fe = $this->mprocParseFocusEidFromUriString($uri);
  549. if ($fe > 0) {
  550. $this->mprocRememberFocusEid($fe);
  551. return $fe;
  552. }
  553. $fe = (int)Session::get('mproc_focus_eid', 0);
  554. if ($fe > 0) {
  555. return $fe;
  556. }
  557. return 0;
  558. }
  559. /**
  560. * 手机端登录页 URL。注意:勿用 url('...login', ['redirect'=>]),在 url_html_suffix 下会把参数拼进 PATHINFO 导致 404。
  561. *
  562. * @param string $redirectPath 已通过 {@see mprocSanitizeRedirectUrl} 的回跳路径(含 query),空则不带参数
  563. */
  564. protected function mprocBuildLoginUrl($redirectPath = '')
  565. {
  566. $root = rtrim($this->request->root(), '/');
  567. $path = '/index/index/login';
  568. $rp = trim((string)$redirectPath);
  569. if ($rp === '') {
  570. return $root . $path;
  571. }
  572. return $root . $path . '?' . http_build_query(['redirect' => $rp], '', '&', PHP_QUERY_RFC3986);
  573. }
  574. /**
  575. * 登录成功后跳转到订单首页:用当前入口 {@see Request::root} 拼 URL,并从原 redirect 中只保留白名单 query(避免子目录部署丢参、开放重定向)
  576. *
  577. * @param string $redirectPathOrUrl 已通过 {@see mprocSanitizeRedirectUrl} 的路径或完整 URL(可含 ?focus_eid=)
  578. */
  579. protected function mprocBuildAfterLoginIndexUrl($redirectPathOrUrl)
  580. {
  581. $raw = trim((string)$redirectPathOrUrl);
  582. if ($raw === '') {
  583. return url('index/index/index', '', '', true);
  584. }
  585. $queryStr = '';
  586. if (preg_match('#^https?://#i', $raw)) {
  587. $pq = parse_url($raw);
  588. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  589. } elseif (isset($raw[0]) && $raw[0] === '/') {
  590. $pq = parse_url('http://127.0.0.1' . $raw);
  591. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  592. } else {
  593. $pq = parse_url('http://127.0.0.1/' . ltrim($raw, '/'));
  594. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  595. }
  596. $q = [];
  597. if ($queryStr !== '') {
  598. parse_str($queryStr, $q);
  599. if (!is_array($q)) {
  600. $q = [];
  601. }
  602. }
  603. $allowed = [];
  604. $fe = 0;
  605. if (isset($q['focus_eid'])) {
  606. $fe = (int)$q['focus_eid'];
  607. }
  608. if ($fe <= 0) {
  609. $fe = $this->mprocParseFocusEidFromUriString($raw);
  610. }
  611. if ($fe <= 0) {
  612. $fe = (int)Session::get('mproc_focus_eid', 0);
  613. }
  614. if ($fe > 0) {
  615. $allowed['focus_eid'] = $fe;
  616. $this->mprocRememberFocusEid($fe);
  617. }
  618. $mt = isset($q['main_tab']) ? trim((string)$q['main_tab']) : '';
  619. if ($mt === 'me' || $mt === 'orders') {
  620. $allowed['main_tab'] = $mt;
  621. }
  622. $tb = isset($q['tab']) ? trim((string)$q['tab']) : '';
  623. if ($tb === 'me' || in_array($this->mprocNormalizeListTab($tb), $this->mprocListTabWhitelist(), true)) {
  624. $allowed['tab'] = ($tb === 'me') ? 'me' : $this->mprocNormalizeListTab($tb);
  625. }
  626. if (isset($q['q']) && trim((string)$q['q']) !== '') {
  627. $allowed['q'] = substr(trim((string)$q['q']), 0, 120);
  628. }
  629. if (isset($allowed['focus_eid']) && !isset($allowed['main_tab'])) {
  630. $allowed['main_tab'] = 'orders';
  631. }
  632. $base = rtrim($this->request->root(true), '/');
  633. $path = '/index/index/index';
  634. if (isset($allowed['focus_eid']) && (int)$allowed['focus_eid'] > 0 && !isset($allowed['q'])) {
  635. $fe = (int)$allowed['focus_eid'];
  636. if (!isset($allowed['tab']) && (!isset($allowed['main_tab']) || $allowed['main_tab'] === 'orders')) {
  637. return $base . $path . '?focus_eid=' . $fe . '#mproc_fe=' . $fe;
  638. }
  639. $ordered = ['focus_eid' => $fe];
  640. if (isset($allowed['tab'])) {
  641. $ordered['tab'] = $allowed['tab'];
  642. }
  643. if (isset($allowed['main_tab'])) {
  644. $ordered['main_tab'] = $allowed['main_tab'];
  645. }
  646. return $base . $path . '?' . http_build_query($ordered, '', '&', PHP_QUERY_RFC3986) . '#mproc_fe=' . $fe;
  647. }
  648. $qs = $allowed !== [] ? ('?' . http_build_query($allowed, '', '&', PHP_QUERY_RFC3986)) : '';
  649. return $base . $path . $qs;
  650. }
  651. /**
  652. * 按登录身份决定首页:供应商→报价;质检→质量评分;生产→交货情况
  653. * 后台账号无手机端角色时返回空串(勿回登录页,避免 302 死循环)
  654. *
  655. * @param array<string, mixed> $user
  656. * @param string $redirectPathOrUrl
  657. */
  658. protected function mprocBuildAfterLoginHomeUrl(array $user, $redirectPathOrUrl = '')
  659. {
  660. if (!empty($user['is_admin'])) {
  661. $canQuality = $this->mprocAdminHasMobileRole($user, 'quality');
  662. $canDelivery = $this->mprocAdminHasMobileRole($user, 'delivery');
  663. $canRfq = $this->mprocAdminHasMobileRole($user, 'rfq');
  664. $raw = $this->mprocSanitizeRedirectUrl($redirectPathOrUrl);
  665. if ($raw !== '') {
  666. if ($canDelivery && stripos($raw, 'deliveryscore') !== false) {
  667. return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/deliveryscore');
  668. }
  669. if ($canQuality && stripos($raw, 'inboundscore') !== false) {
  670. return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/inboundscore');
  671. }
  672. if ($canRfq && stripos($raw, 'rfqadd') !== false) {
  673. return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/rfqadd');
  674. }
  675. }
  676. if ($canQuality) {
  677. return url('index/index/inboundscore', '', '', true);
  678. }
  679. if ($canDelivery) {
  680. return url('index/index/deliveryscore', '', '', true);
  681. }
  682. if ($canRfq) {
  683. return url('index/index/rfqadd', '', '', true);
  684. }
  685. return '';
  686. }
  687. $raw = $this->mprocSanitizeRedirectUrl($redirectPathOrUrl);
  688. if ($raw !== '' && stripos($raw, 'deliverynote') !== false) {
  689. return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/deliverynote');
  690. }
  691. return $this->mprocBuildAfterLoginIndexUrl($redirectPathOrUrl);
  692. }
  693. /**
  694. * 操作人员是否具备手机端任一业务角色(质检 / 生产 / 业务员询价,含超管)
  695. *
  696. * @param array<string, mixed> $user
  697. */
  698. protected function mprocAdminHasAnyMobileAccess(array $user): bool
  699. {
  700. return $this->mprocAdminHasMobileRole($user, 'quality')
  701. || $this->mprocAdminHasMobileRole($user, 'delivery')
  702. || $this->mprocAdminHasMobileRole($user, 'rfq');
  703. }
  704. /**
  705. * @param array<string, mixed> $row admin 表行
  706. * @return array<string, mixed>
  707. */
  708. protected function mprocLoginPayloadFromAdmin(array $row, string $loginType): array
  709. {
  710. return [
  711. 'phone' => trim((string)($row['mobile'] ?? '')),
  712. 'company_name' => '',
  713. 'username' => trim((string)($row['username'] ?? '')),
  714. 'account' => trim((string)($row['username'] ?? '')),
  715. 'customer_user_id' => 0,
  716. 'customer_id' => 0,
  717. 'admin_id' => (int)($row['id'] ?? 0),
  718. 'login_type' => $loginType,
  719. 'is_admin' => 1,
  720. ];
  721. }
  722. /** 清除当前请求中的手机端登录态(解决无权限账号卡在登录跳转) */
  723. protected function mprocDropCurrentLogin(): void
  724. {
  725. $token = $this->mprocReadTokenFromRequest();
  726. $this->mprocClearLogin($token);
  727. }
  728. /**
  729. * @param string $rawSanitized
  730. * @param string $fallbackRoute
  731. */
  732. protected function mprocAbsoluteFromSanitizedPath($rawSanitized, $fallbackRoute)
  733. {
  734. $base = rtrim((string)$this->request->root(true), '/');
  735. $path = parse_url($rawSanitized, PHP_URL_PATH);
  736. $query = parse_url($rawSanitized, PHP_URL_QUERY);
  737. if (!is_string($path) || $path === '') {
  738. return url($fallbackRoute, '', '', true);
  739. }
  740. $path = '/' . ltrim(str_replace('\\', '/', $path), '/');
  741. // root(true) 常为 http://host/index.php,而 redirect/REQUEST_URI 也可能以 /index.php 开头,
  742. // 直接拼接会变成 /index.php/index.php/... → 报「模块不存在:index.php」
  743. if (preg_match('#/index\.php$#i', $base)) {
  744. $path = preg_replace('#^/index\.php(?=/|$)#i', '', $path);
  745. if ($path === '' || (isset($path[0]) && $path[0] !== '/')) {
  746. $path = '/' . ltrim((string)$path, '/');
  747. }
  748. }
  749. return $base . $path . (is_string($query) && $query !== '' ? ('?' . $query) : '');
  750. }
  751. /**
  752. * 从 purchase_order_detail 表解析真实列名(SHOW COLUMNS 只查一次,按候选小写名匹配第一条)
  753. *
  754. * @param string[] $candidatesLower 如 ['status','istatus']
  755. * @return string|null
  756. */
  757. protected function mprocResolveProcuremenColumn(array $candidatesLower)
  758. {
  759. if (self::$mprocProcuremenColumns === null) {
  760. self::$mprocProcuremenColumns = [];
  761. try {
  762. $rows = Db::query('SHOW COLUMNS FROM `purchase_order_detail`');
  763. if (is_array($rows)) {
  764. foreach ($rows as $c) {
  765. $name = isset($c['Field']) ? (string)$c['Field'] : '';
  766. if ($name !== '') {
  767. self::$mprocProcuremenColumns[strtolower($name)] = $name;
  768. }
  769. }
  770. }
  771. } catch (\Throwable $e) {
  772. self::$mprocProcuremenColumns = [];
  773. }
  774. }
  775. foreach ($candidatesLower as $low) {
  776. $k = strtolower((string)$low);
  777. if (isset(self::$mprocProcuremenColumns[$k])) {
  778. return self::$mprocProcuremenColumns[$k];
  779. }
  780. }
  781. return null;
  782. }
  783. /**
  784. * 供应商整单备注(purchase_order_detail.remark)
  785. *
  786. * @param array<string, mixed> $row
  787. */
  788. protected function mprocResolveDetailRemark(array $row): string
  789. {
  790. $col = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
  791. if ($col === null) {
  792. return '';
  793. }
  794. foreach ($row as $k => $v) {
  795. if (strcasecmp((string)$k, $col) === 0) {
  796. return trim((string)$v);
  797. }
  798. }
  799. return '';
  800. }
  801. /**
  802. * 供应商自己填的备注;与订单 MBZ 相同视为未填
  803. */
  804. protected function mprocSupplierOwnRemark($detailRemark, $orderMbz = ''): string
  805. {
  806. $own = trim((string)$detailRemark);
  807. $mbz = trim((string)$orderMbz);
  808. if ($own === '' || ($mbz !== '' && $own === $mbz)) {
  809. return '';
  810. }
  811. return $own;
  812. }
  813. /**
  814. * 列表:非管理员按 company_name 与登录单位一致,或 phone 与登录手机号一致(兼容手工下发单位名细微差异)
  815. *
  816. * @return array|callable 可直接 $query->where(...);空数组表示不加条件
  817. */
  818. protected function mprocListWhereForLoginUser(array $user)
  819. {
  820. if (!empty($user['is_admin'])) {
  821. return [];
  822. }
  823. $cCol = $this->mprocResolveProcuremenColumn(['company_name']);
  824. $pCol = $this->mprocResolveProcuremenColumn(['phone']);
  825. if (($cCol === null || $cCol === '') && ($pCol === null || $pCol === '')) {
  826. return ['id' => 0];
  827. }
  828. $cn = trim((string)($user['company_name'] ?? ''));
  829. $phone = trim((string)($user['phone'] ?? ''));
  830. if ($cn === '' && $phone !== '') {
  831. $cn = $this->mprocResolveCompanyForLoginPhone($phone);
  832. }
  833. if ($cn === '' && $phone === '') {
  834. return ['id' => 0];
  835. }
  836. return function ($q) use ($cCol, $pCol, $cn, $phone) {
  837. $first = true;
  838. if ($cCol !== null && $cCol !== '' && $cn !== '') {
  839. $q->where($cCol, $cn);
  840. $first = false;
  841. }
  842. if ($pCol !== null && $pCol !== '' && $phone !== '') {
  843. if ($first) {
  844. $q->where($pCol, $phone);
  845. } else {
  846. $q->whereOr($pCol, $phone);
  847. }
  848. }
  849. if ($first) {
  850. $q->where('id', 0);
  851. }
  852. };
  853. }
  854. /**
  855. * customer 是否允许登录(status:1 / 正常;空视为可登录以兼容旧数据)
  856. */
  857. protected function mprocCustomerUserActive(array $row): bool
  858. {
  859. $st = $row['status'] ?? '';
  860. if ($st === '' || $st === null) {
  861. return true;
  862. }
  863. return $st === 1 || $st === '1';
  864. }
  865. /**
  866. * @return array<string, mixed>|null
  867. */
  868. protected function mprocFindCustomerUserByMobile(string $phone): ?array
  869. {
  870. return $this->mprocFindCustomerRowByPhone($phone);
  871. }
  872. /**
  873. * 按登录账号(account)查找 customer;兼容旧会话把 11 位手机号写在 username 里
  874. *
  875. * @return array<string, mixed>|null
  876. */
  877. protected function mprocFindCustomerUserByUsername(string $username): ?array
  878. {
  879. $username = trim($username);
  880. if ($username === '') {
  881. return null;
  882. }
  883. try {
  884. $row = Db::table('customer')->where('account', $username)->order('id', 'asc')->find();
  885. } catch (\Throwable $e) {
  886. $row = null;
  887. }
  888. if ((!is_array($row) || $row === []) && preg_match('/^1\d{10}$/', $username)) {
  889. $row = $this->mprocFindCustomerRowByPhone($username);
  890. }
  891. if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
  892. return null;
  893. }
  894. return $row;
  895. }
  896. /**
  897. * customer 密码校验(md5(md5) 无 salt;兼容 bcrypt)
  898. */
  899. protected function mprocVerifyCustomerUserPassword(array $row, string $password): bool
  900. {
  901. $stored = (string)($row['password'] ?? '');
  902. if ($stored === '' || $password === '') {
  903. return false;
  904. }
  905. if (preg_match('/^\$2[ayb]\$/', $stored)) {
  906. return password_verify($password, $stored);
  907. }
  908. return hash_equals($stored, md5(md5($password)));
  909. }
  910. /**
  911. * 生成 customer 登录密码密文
  912. */
  913. protected function mprocHashCustomerUserPassword(string $password, string $existingSalt = ''): string
  914. {
  915. unset($existingSalt);
  916. return md5(md5($password));
  917. }
  918. /**
  919. * 手机端强密码校验:通过返回空字符串,否则返回错误提示
  920. */
  921. protected function mprocValidateStrongPassword(string $password): string
  922. {
  923. $len = strlen($password);
  924. if ($len < 8 || $len > 20) {
  925. return '密码长度须为8~20位';
  926. }
  927. if (preg_match('/\s/', $password)) {
  928. return '密码不能包含空格';
  929. }
  930. if (preg_match('/^\d+$/', $password)) {
  931. return '密码不能为纯数字,请同时包含字母';
  932. }
  933. if (preg_match('/^[a-zA-Z]+$/', $password)) {
  934. return '密码不能为纯字母,请同时包含数字';
  935. }
  936. if (!preg_match('/[a-zA-Z]/', $password) || !preg_match('/\d/', $password)) {
  937. return '密码须同时包含字母和数字';
  938. }
  939. if (preg_match('/(.)\1{3,}/', $password)) {
  940. return '密码不能包含过多重复字符(如1111、aaaa)';
  941. }
  942. if ($this->mprocPasswordHasSequentialRun($password, 4)) {
  943. return '密码不能包含连续字符(如1234、abcd)';
  944. }
  945. $weak = [
  946. '12345678', '123456789', '1234567890', '87654321', '01234567',
  947. 'password', 'password1', 'passw0rd', 'qwerty12', 'qwertyui',
  948. 'abc12345', 'abcd1234', 'a1b2c3d4', '11111111', '00000000',
  949. '88888888', '66666666', '11223344', '1qaz2wsx', 'qazwsxed',
  950. ];
  951. if (in_array(strtolower($password), $weak, true)) {
  952. return '密码过于简单,请重新设置';
  953. }
  954. return '';
  955. }
  956. /**
  957. * 是否包含连续递增/递减片段(长度 >= $runLen),如 1234、4321、abcd
  958. */
  959. protected function mprocPasswordHasSequentialRun(string $password, int $runLen = 4): bool
  960. {
  961. $runLen = max(3, $runLen);
  962. $lower = strtolower($password);
  963. $n = strlen($lower);
  964. if ($n < $runLen) {
  965. return false;
  966. }
  967. for ($i = 0; $i <= $n - $runLen; $i++) {
  968. $asc = true;
  969. $desc = true;
  970. for ($j = 1; $j < $runLen; $j++) {
  971. $prev = ord($lower[$i + $j - 1]);
  972. $cur = ord($lower[$i + $j]);
  973. if ($cur !== $prev + 1) {
  974. $asc = false;
  975. }
  976. if ($cur !== $prev - 1) {
  977. $desc = false;
  978. }
  979. if (!$asc && !$desc) {
  980. break;
  981. }
  982. }
  983. if ($asc || $desc) {
  984. return true;
  985. }
  986. }
  987. return false;
  988. }
  989. /**
  990. * @param array<string, mixed> $cu
  991. * @return array<string, mixed>
  992. */
  993. protected function mprocLoginPayloadFromCustomer(array $cu, string $loginType): array
  994. {
  995. $phone = trim((string)($cu['phone'] ?? ''));
  996. $account = trim((string)($cu['account'] ?? ''));
  997. if ($phone === '' && preg_match('/^1\d{10}$/', $account)) {
  998. $phone = $account;
  999. }
  1000. if ($account === '' && preg_match('/^1\d{10}$/', $phone)) {
  1001. $account = $phone;
  1002. }
  1003. $companyName = trim((string)($cu['company_name'] ?? ''));
  1004. if ($companyName === '' && $phone !== '') {
  1005. $companyName = $this->mprocResolveCompanyForLoginPhone($phone);
  1006. }
  1007. $id = (int)($cu['id'] ?? 0);
  1008. return [
  1009. 'phone' => $phone,
  1010. 'account' => $account,
  1011. 'company_name' => $companyName,
  1012. 'username' => trim((string)($cu['username'] ?? '')),
  1013. 'customer_id' => $id,
  1014. 'customer_user_id' => $id,
  1015. 'login_type' => $loginType,
  1016. 'is_admin' => 0,
  1017. ];
  1018. }
  1019. /**
  1020. * 写入手机端登录态并返回跳转 URL
  1021. *
  1022. * @param array<string, mixed> $userData
  1023. */
  1024. protected function mprocFinishLogin(array $userData): void
  1025. {
  1026. $old = Session::get('mproc_token');
  1027. if ($old) {
  1028. $this->mprocClearLogin((string)$old);
  1029. }
  1030. $userData['login_time'] = time();
  1031. $token = $this->mprocPackSignedAuthToken($userData);
  1032. $token = $this->mprocTouchLoginState($userData, $token);
  1033. $postR = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  1034. $sessR = $this->mprocSanitizeRedirectUrl((string)Session::get('mproc_intended_url', ''));
  1035. Session::delete('mproc_intended_url');
  1036. $raw = $postR !== '' ? $postR : $sessR;
  1037. $jump = $this->mprocBuildAfterLoginHomeUrl($userData, $raw);
  1038. if ($jump === '') {
  1039. $this->mprocClearLogin($token);
  1040. $this->error('账号或密码错误');
  1041. }
  1042. $this->success('登录成功', $jump, [
  1043. 'mproc_token' => $token,
  1044. 'keep_hours' => $this->mprocKeepHours(),
  1045. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  1046. ]);
  1047. }
  1048. /**
  1049. * 登录手机号对应的外协单位名称:customer 表;否则 purchase_order_detail
  1050. */
  1051. protected function mprocResolveCompanyForLoginPhone(string $phone): string
  1052. {
  1053. $phone = trim($phone);
  1054. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  1055. return '';
  1056. }
  1057. $cust = $this->mprocFindCustomerRowByPhone($phone);
  1058. if (is_array($cust) && $cust !== []) {
  1059. $co = $this->mprocCustomerPickField($cust, ['company_name', 'name']);
  1060. if ($co !== '') {
  1061. return $co;
  1062. }
  1063. }
  1064. try {
  1065. $one = Db::table('purchase_order_detail')
  1066. ->where('phone', $phone)
  1067. ->order('id', 'desc')
  1068. ->find();
  1069. if (is_array($one)) {
  1070. $n = trim((string)($one['company_name'] ?? ''));
  1071. if ($n !== '') {
  1072. return $n;
  1073. }
  1074. }
  1075. } catch (\Throwable $e) {
  1076. }
  1077. return '';
  1078. }
  1079. /**
  1080. * 按手机号匹配 customer(phone 或 account 单值相等)
  1081. *
  1082. * @return array<string, mixed>|null
  1083. */
  1084. protected function mprocFindCustomerRowByPhone(string $phone): ?array
  1085. {
  1086. $phone = trim($phone);
  1087. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  1088. return null;
  1089. }
  1090. try {
  1091. $row = Db::table('customer')
  1092. ->where(function ($q) use ($phone) {
  1093. $q->where('phone', $phone)->whereOr('account', $phone);
  1094. })
  1095. ->order('id', 'asc')
  1096. ->find();
  1097. } catch (\Throwable $e) {
  1098. return null;
  1099. }
  1100. if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
  1101. return null;
  1102. }
  1103. return $row;
  1104. }
  1105. /**
  1106. * 管理员表 fa_admin.mobile 与当前手机号一致且未禁用(用于手机验证码管理员通道)
  1107. *
  1108. * @return array<string, mixed>|null
  1109. */
  1110. protected function mprocAdminRowByMobile(string $phone): ?array
  1111. {
  1112. $phone = trim($phone);
  1113. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  1114. return null;
  1115. }
  1116. try {
  1117. $row = Db::name('admin')
  1118. ->where('mobile', $phone)
  1119. ->where('status', '<>', 'hidden')
  1120. ->order('id', 'asc')
  1121. ->find();
  1122. } catch (\Throwable $e) {
  1123. return null;
  1124. }
  1125. return is_array($row) && $row !== [] ? $row : null;
  1126. }
  1127. /**
  1128. * 在 customer 表中匹配当前用户:优先手机号,否则按公司名
  1129. *
  1130. * @return array<string, mixed>|null
  1131. */
  1132. protected function mprocFindCustomerRowForUser(array $user): ?array
  1133. {
  1134. $phone = trim((string)($user['phone'] ?? ''));
  1135. if ($phone === '') {
  1136. $phone = trim((string)($user['account'] ?? ''));
  1137. }
  1138. $cn = trim((string)($user['company_name'] ?? ''));
  1139. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  1140. $byPhone = $this->mprocFindCustomerRowByPhone($phone);
  1141. if ($byPhone !== null) {
  1142. return $byPhone;
  1143. }
  1144. }
  1145. if ($cn !== '') {
  1146. try {
  1147. // customer 表无 name 列,勿用 whereOr('name')
  1148. $hit = Db::table('customer')
  1149. ->where('company_name', $cn)
  1150. ->order('id', 'desc')
  1151. ->find();
  1152. } catch (\Throwable $e) {
  1153. $hit = null;
  1154. }
  1155. if (is_array($hit) && $hit !== []) {
  1156. return $hit;
  1157. }
  1158. }
  1159. return null;
  1160. }
  1161. /**
  1162. * 从 customer 行取字段(兼容列名大小写)
  1163. *
  1164. * @param string[] $candidates
  1165. */
  1166. protected function mprocCustomerPickField(array $row, array $candidates): string
  1167. {
  1168. foreach ($candidates as $want) {
  1169. $lw = strtolower($want);
  1170. foreach ($row as $k => $v) {
  1171. if (!is_string($k)) {
  1172. continue;
  1173. }
  1174. if (strtolower($k) !== $lw) {
  1175. continue;
  1176. }
  1177. $s = trim((string)$v);
  1178. if ($s !== '') {
  1179. return $s;
  1180. }
  1181. }
  1182. }
  1183. return '';
  1184. }
  1185. /**
  1186. * 明细表关键字搜索:仅对 purchase_order_detail 真实存在的列 LIKE;
  1187. * 主表 purchase_order 上的订单号、印件、工序等另查 scydgy_id 再 OR 进列表(避免引用不存在的列导致整页查失败)。
  1188. *
  1189. * @param \think\db\Query $query
  1190. */
  1191. protected function mprocApplySearchKeywordToDetailQuery($query, $search)
  1192. {
  1193. $kw = trim((string)$search);
  1194. if ($kw === '') {
  1195. return;
  1196. }
  1197. $map = self::$mprocProcuremenColumns;
  1198. if (!is_array($map) || $map === []) {
  1199. return;
  1200. }
  1201. $like = '%' . addcslashes($kw, '%_\\') . '%';
  1202. $wantLower = ['ccydh', 'cyjmc', 'cdxmc', 'company_name', 'cgzzxmc', 'cgymc', 'cdf', 'phone', 'email'];
  1203. $detailCols = [];
  1204. foreach ($wantLower as $low) {
  1205. if (isset($map[$low])) {
  1206. $detailCols[] = $map[$low];
  1207. }
  1208. }
  1209. $scydgyCol = isset($map['scydgy_id']) ? $map['scydgy_id'] : 'scydgy_id';
  1210. $idCol = isset($map['id']) ? $map['id'] : 'id';
  1211. $poSidList = [];
  1212. $poWant = ['CCYDH', 'CYJMC', 'CDXMC', 'CGYMC', 'cGzzxMc', 'CDF'];
  1213. try {
  1214. $col = Db::table('purchase_order')
  1215. ->where(function ($sub) use ($like, $poWant) {
  1216. $firstPo = true;
  1217. foreach ($poWant as $pf) {
  1218. if ($firstPo) {
  1219. $sub->where($pf, 'like', $like);
  1220. $firstPo = false;
  1221. } else {
  1222. $sub->whereOr($pf, 'like', $like);
  1223. }
  1224. }
  1225. })
  1226. ->column('scydgy_id');
  1227. if (is_array($col)) {
  1228. foreach ($col as $v) {
  1229. $id = (int)$v;
  1230. if ($this->mprocIsValidScydgyRowId($id)) {
  1231. $poSidList[$id] = true;
  1232. }
  1233. }
  1234. }
  1235. $poSidList = array_keys($poSidList);
  1236. } catch (\Throwable $e) {
  1237. $poSidList = [];
  1238. }
  1239. $query->where(function ($q2) use ($like, $detailCols, $poSidList, $scydgyCol, $idCol) {
  1240. $first = true;
  1241. foreach ($detailCols as $col) {
  1242. if ($first) {
  1243. $q2->where($col, 'like', $like);
  1244. $first = false;
  1245. } else {
  1246. $q2->whereOr($col, 'like', $like);
  1247. }
  1248. }
  1249. if ($poSidList !== []) {
  1250. if ($first) {
  1251. $q2->where($scydgyCol, 'in', $poSidList);
  1252. $first = false;
  1253. } else {
  1254. $q2->whereOr($scydgyCol, 'in', $poSidList);
  1255. }
  1256. }
  1257. if ($first) {
  1258. $q2->where($idCol, '=', 0);
  1259. }
  1260. });
  1261. }
  1262. /**
  1263. * 列表:按左侧 Tab 追加 status_name 条件(与数值 status 0/1/2 无关;值由后端维护)
  1264. * - draft:status_name = 未提交
  1265. * - submitted:status_name = 已提交
  1266. * - done:status_name = 已完成
  1267. * 表无 status_name 列时不加条件(三个 Tab 数据相同,待库表补列后再筛)
  1268. *
  1269. * @param mixed $query
  1270. * @param string $tab draft|submitted|done
  1271. * @param string|null $statusNameCol 真实列名,如 status_name
  1272. */
  1273. protected function mprocApplyListTabConditions($query, $tab, $statusNameCol)
  1274. {
  1275. if ($statusNameCol === null) {
  1276. return;
  1277. }
  1278. $map = [
  1279. 'draft' => '未提交',
  1280. 'submitted' => '已提交',
  1281. 'done' => '已完成',
  1282. ];
  1283. $label = $map[$tab] ?? '未提交';
  1284. $query->where($statusNameCol, '=', $label);
  1285. }
  1286. /**
  1287. * 按登录态解析 customer 行
  1288. *
  1289. * @return array<string, mixed>|null
  1290. */
  1291. protected function mprocResolveCustomerUserForSession(array $user): ?array
  1292. {
  1293. if (!empty($user['is_admin'])) {
  1294. return null;
  1295. }
  1296. $cuId = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  1297. if ($cuId > 0) {
  1298. try {
  1299. $row = Db::table('customer')->where('id', $cuId)->find();
  1300. } catch (\Throwable $e) {
  1301. $row = null;
  1302. }
  1303. if (is_array($row) && $row !== [] && $this->mprocCustomerUserActive($row)) {
  1304. return $row;
  1305. }
  1306. }
  1307. $account = trim((string)($user['account'] ?? ''));
  1308. if ($account !== '') {
  1309. $byAcc = $this->mprocFindCustomerUserByUsername($account);
  1310. if ($byAcc !== null) {
  1311. return $byAcc;
  1312. }
  1313. }
  1314. $phone = trim((string)($user['phone'] ?? ''));
  1315. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  1316. return $this->mprocFindCustomerUserByMobile($phone);
  1317. }
  1318. $uname = trim((string)($user['username'] ?? ''));
  1319. if ($uname !== '' && preg_match('/^1\d{10}$/', $uname)) {
  1320. return $this->mprocFindCustomerUserByMobile($uname);
  1321. }
  1322. return null;
  1323. }
  1324. /**
  1325. * customer 表字段 →「我的」展示结构
  1326. *
  1327. * @param array<string, mixed> $cu
  1328. * @return array{account:string,contact_name:string,department:string,phone:string,email:string,company_name:string}
  1329. */
  1330. protected function mprocProfileFromCustomerUserRow(array $cu): array
  1331. {
  1332. $nm = trim((string)($cu['username'] ?? ''));
  1333. $account = trim((string)($cu['account'] ?? ''));
  1334. $phone = trim((string)($cu['phone'] ?? ''));
  1335. if ($phone === '') {
  1336. $phone = $account;
  1337. }
  1338. $company = trim((string)($cu['company_name'] ?? ''));
  1339. return [
  1340. 'account' => $account !== '' ? $account : $phone,
  1341. 'contact_name' => $nm,
  1342. 'department' => $company,
  1343. 'phone' => $phone,
  1344. 'email' => trim((string)($cu['email'] ?? '')),
  1345. 'company_name' => $company,
  1346. ];
  1347. }
  1348. /**
  1349. * 管理员「我的」:账号、姓名、部门(角色组)、手机、邮箱
  1350. *
  1351. * @return array{account:string,contact_name:string,department:string,phone:string,email:string,company_name:string}
  1352. */
  1353. protected function mprocProfileForAdmin(array $user): array
  1354. {
  1355. $uname = trim((string)($user['username'] ?? ''));
  1356. $out = [
  1357. 'account' => $uname,
  1358. 'contact_name' => $uname !== '' ? $uname : '管理员',
  1359. 'department' => '',
  1360. 'phone' => trim((string)($user['phone'] ?? '')),
  1361. 'email' => '',
  1362. 'company_name' => '',
  1363. ];
  1364. if ($uname === '') {
  1365. return $out;
  1366. }
  1367. try {
  1368. $row = Db::name('admin')->where('username', $uname)->find();
  1369. } catch (\Throwable $e) {
  1370. $row = null;
  1371. }
  1372. if (!is_array($row) || $row === []) {
  1373. return $out;
  1374. }
  1375. $out['account'] = trim((string)($row['username'] ?? $uname));
  1376. $nick = trim((string)($row['nickname'] ?? ''));
  1377. if ($nick !== '') {
  1378. $out['contact_name'] = $nick;
  1379. }
  1380. $mob = trim((string)($row['mobile'] ?? ''));
  1381. if ($mob !== '') {
  1382. $out['phone'] = $mob;
  1383. }
  1384. $em = trim((string)($row['email'] ?? ''));
  1385. if ($em !== '') {
  1386. $out['email'] = $em;
  1387. }
  1388. $dept = $this->mprocAdminDepartmentLabel((int)($row['id'] ?? 0));
  1389. $out['department'] = $dept;
  1390. $out['company_name'] = $dept;
  1391. return $out;
  1392. }
  1393. /**
  1394. * 管理员部门展示:优先质检中心/生产部,否则拼接所属角色组名
  1395. */
  1396. protected function mprocAdminDepartmentLabel(int $adminId): string
  1397. {
  1398. if ($adminId <= 0) {
  1399. return '';
  1400. }
  1401. $names = [];
  1402. try {
  1403. $rows = Db::name('auth_group_access')
  1404. ->alias('aga')
  1405. ->join('auth_group ag', 'aga.group_id = ag.id')
  1406. ->where('aga.uid', $adminId)
  1407. ->where('ag.status', 'normal')
  1408. ->field('ag.id,ag.name')
  1409. ->order('ag.id', 'asc')
  1410. ->select();
  1411. } catch (\Throwable $e) {
  1412. $rows = [];
  1413. }
  1414. if (!is_array($rows)) {
  1415. return '';
  1416. }
  1417. $qualityId = $this->mprocResolveMobileQualityGroupId();
  1418. $deliveryId = $this->mprocResolveMobileDeliveryGroupId();
  1419. $deliveryLabel = trim((string)Config::get('mproc.mobile_delivery_dept_name'));
  1420. if ($deliveryLabel === '') {
  1421. $deliveryLabel = '生产部';
  1422. }
  1423. foreach ($rows as $r) {
  1424. if (!is_array($r)) {
  1425. continue;
  1426. }
  1427. $gid = (int)($r['id'] ?? 0);
  1428. $name = trim((string)($r['name'] ?? ''));
  1429. if ($gid === $qualityId) {
  1430. $names[] = '质检中心';
  1431. continue;
  1432. }
  1433. if ($gid === $deliveryId) {
  1434. $names[] = $deliveryLabel;
  1435. continue;
  1436. }
  1437. if ($name !== '') {
  1438. $names[] = $name;
  1439. }
  1440. }
  1441. $names = array_values(array_unique($names));
  1442. return $names !== [] ? implode('、', $names) : '';
  1443. }
  1444. /**
  1445. * 旧会话补全 customer_id 等字段
  1446. */
  1447. protected function mprocSyncSessionCustomerUser(array $user): array
  1448. {
  1449. if (!empty($user['is_admin'])) {
  1450. return $user;
  1451. }
  1452. $cu = $this->mprocResolveCustomerUserForSession($user);
  1453. if (!$cu) {
  1454. return $user;
  1455. }
  1456. $id = (int)($cu['id'] ?? 0);
  1457. $user['customer_id'] = $id;
  1458. $user['customer_user_id'] = $id;
  1459. $user['username'] = trim((string)($cu['username'] ?? $user['username'] ?? ''));
  1460. $user['company_name'] = trim((string)($cu['company_name'] ?? ''));
  1461. $user['account'] = trim((string)($cu['account'] ?? ''));
  1462. $mob = trim((string)($cu['phone'] ?? ''));
  1463. if ($mob === '') {
  1464. $mob = trim((string)($cu['account'] ?? ''));
  1465. }
  1466. if ($mob !== '') {
  1467. $user['phone'] = $mob;
  1468. }
  1469. $token = Session::get('mproc_token');
  1470. if ($token) {
  1471. $user['login_time'] = (int)($user['login_time'] ?? time());
  1472. $tok = trim((string)$token);
  1473. Cache::set($this->mprocAuthCacheKey($tok), $user, $this->mprocTtlSeconds + 86400);
  1474. if (!$this->mprocIsSignedAuthToken($tok)) {
  1475. Cache::set('mproc_u_' . preg_replace('/[^a-f0-9]/i', '', $tok), $user, $this->mprocTtlSeconds + 86400);
  1476. }
  1477. }
  1478. return $user;
  1479. }
  1480. /**
  1481. * 「我的」:普通用户 customer;管理员 admin
  1482. */
  1483. protected function mprocProfileForUser(array $user)
  1484. {
  1485. if (!empty($user['is_admin'])) {
  1486. return $this->mprocProfileForAdmin($user);
  1487. }
  1488. $cu = $this->mprocResolveCustomerUserForSession($user);
  1489. if (is_array($cu) && $cu !== []) {
  1490. return $this->mprocProfileFromCustomerUserRow($cu);
  1491. }
  1492. $phone = trim((string)($user['phone'] ?? ''));
  1493. if ($phone === '') {
  1494. $phone = trim((string)($user['account'] ?? ''));
  1495. }
  1496. return [
  1497. 'account' => $phone !== '' ? $phone : trim((string)($user['account'] ?? '')),
  1498. 'contact_name' => trim((string)($user['username'] ?? '')),
  1499. 'department' => trim((string)($user['company_name'] ?? '')),
  1500. 'phone' => $phone,
  1501. 'email' => '',
  1502. 'company_name' => trim((string)($user['company_name'] ?? '')),
  1503. ];
  1504. }
  1505. protected function mprocIsValidScydgyRowId($id): bool
  1506. {
  1507. return (int)$id !== 0;
  1508. }
  1509. /**
  1510. * 将 purchase_order(工序行主表)快照合并进 purchase_order_detail 行:订单级信息以主表为准;
  1511. * 金额、交期、外厂 company、明细 status 等仍保留明细表。
  1512. *
  1513. * @param array $row 引用:明细行
  1514. * @param array $poRow purchase_order 一行
  1515. */
  1516. protected function mprocMergePurchaseOrderIntoDetail(array &$row, array $poRow)
  1517. {
  1518. $pl = array_change_key_case($poRow, CASE_LOWER);
  1519. $hdr = [
  1520. 'ccydh' => 'CCYDH',
  1521. 'cyjmc' => 'CYJMC',
  1522. 'cdf' => 'CDF',
  1523. 'cgzzxmc' => 'cGzzxMc',
  1524. 'cgymc' => 'CGYMC',
  1525. 'cdxmc' => 'CDXMC',
  1526. 'ngzl' => 'NGZL',
  1527. 'cdw' => 'CDW',
  1528. 'cgybh' => 'CGYBH',
  1529. ];
  1530. foreach ($hdr as $lk => $out) {
  1531. if (!array_key_exists($lk, $pl)) {
  1532. continue;
  1533. }
  1534. $v = $pl[$lk];
  1535. if ($v !== null && $v !== '') {
  1536. $row[$out] = $v;
  1537. }
  1538. }
  1539. // 本次数量、最高限价:仅存在于主表;PDO 列名大小写可能不一致
  1540. $qtyRaw = '';
  1541. foreach (['this_quantity', 'This_quantity'] as $qk) {
  1542. if (array_key_exists($qk, $pl) && $pl[$qk] !== null && $pl[$qk] !== '') {
  1543. $qtyRaw = trim((string)$pl[$qk]);
  1544. break;
  1545. }
  1546. }
  1547. if ($qtyRaw === '') {
  1548. foreach (['This_quantity', 'this_quantity'] as $qk) {
  1549. if (array_key_exists($qk, $poRow) && $poRow[$qk] !== null && $poRow[$qk] !== '') {
  1550. $qtyRaw = trim((string)$poRow[$qk]);
  1551. break;
  1552. }
  1553. }
  1554. }
  1555. if ($qtyRaw !== '') {
  1556. $row['This_quantity'] = $qtyRaw;
  1557. }
  1558. $ceilRaw = '';
  1559. foreach (['ceilingprice', 'ceiling_price', 'CeilingPrice'] as $ck) {
  1560. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  1561. $ceilRaw = trim((string)$pl[$ck]);
  1562. break;
  1563. }
  1564. }
  1565. if ($ceilRaw === '') {
  1566. foreach (['ceilingPrice', 'ceiling_price', 'CeilingPrice'] as $ck) {
  1567. if (array_key_exists($ck, $poRow) && $poRow[$ck] !== null && $poRow[$ck] !== '') {
  1568. $ceilRaw = trim((string)$poRow[$ck]);
  1569. break;
  1570. }
  1571. }
  1572. }
  1573. if ($ceilRaw !== '') {
  1574. $row['ceilingPrice'] = $ceilRaw;
  1575. }
  1576. $sysRq = '';
  1577. foreach (['sys_rq', 'SYS_RQ'] as $sk) {
  1578. if (array_key_exists($sk, $pl) && $pl[$sk] !== null && $pl[$sk] !== '') {
  1579. $sysRq = trim((string)$pl[$sk]);
  1580. break;
  1581. }
  1582. if (array_key_exists($sk, $poRow) && $poRow[$sk] !== null && $poRow[$sk] !== '') {
  1583. $sysRq = trim((string)$poRow[$sk]);
  1584. break;
  1585. }
  1586. }
  1587. if ($sysRq !== '' && !preg_match('/^0000-00-00/i', $sysRq)) {
  1588. $row['sys_rq'] = $sysRq;
  1589. }
  1590. $deliveryDeadline = '';
  1591. foreach (['delivery_deadline', 'Delivery_deadline'] as $dk) {
  1592. if (array_key_exists($dk, $pl) && $pl[$dk] !== null && $pl[$dk] !== '') {
  1593. $deliveryDeadline = trim((string)$pl[$dk]);
  1594. break;
  1595. }
  1596. if (array_key_exists($dk, $poRow) && $poRow[$dk] !== null && $poRow[$dk] !== '') {
  1597. $deliveryDeadline = trim((string)$poRow[$dk]);
  1598. break;
  1599. }
  1600. }
  1601. if ($deliveryDeadline !== '' && !preg_match('/^0000-00-00/i', $deliveryDeadline)) {
  1602. $row['delivery_deadline'] = $deliveryDeadline;
  1603. }
  1604. // 下发备注(purchase_order.MBZ)→ 手机端未提交/已提交/已完成展示
  1605. $mbz = '';
  1606. foreach (['mbz', 'MBZ'] as $mk) {
  1607. if (array_key_exists($mk, $pl) && $pl[$mk] !== null && trim((string)$pl[$mk]) !== '') {
  1608. $mbz = trim((string)$pl[$mk]);
  1609. break;
  1610. }
  1611. if (array_key_exists($mk, $poRow) && $poRow[$mk] !== null && trim((string)$poRow[$mk]) !== '') {
  1612. $mbz = trim((string)$poRow[$mk]);
  1613. break;
  1614. }
  1615. }
  1616. if ($mbz !== '') {
  1617. $row['MBZ'] = $mbz;
  1618. $row['mproc_order_remark'] = $mbz;
  1619. }
  1620. }
  1621. /**
  1622. * @param int[] $sidList
  1623. * @return array<int, string>
  1624. */
  1625. protected function mprocLoadScydgyMbzByIds(array $sidList): array
  1626. {
  1627. $ids = [];
  1628. foreach ($sidList as $sid) {
  1629. $sid = (int)$sid;
  1630. if ($this->mprocIsValidScydgyRowId($sid)) {
  1631. $ids[$sid] = true;
  1632. }
  1633. }
  1634. if ($ids === []) {
  1635. return [];
  1636. }
  1637. try {
  1638. $map = Db::table('scydgy')->where('ID', 'in', array_keys($ids))->column('MBZ', 'ID');
  1639. } catch (\Throwable $e) {
  1640. return [];
  1641. }
  1642. return is_array($map) ? $map : [];
  1643. }
  1644. /**
  1645. * 统一取年月日(无效则空串)
  1646. */
  1647. protected function mprocFormatYmdValue($raw): string
  1648. {
  1649. $s = trim((string)$raw);
  1650. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  1651. return '';
  1652. }
  1653. $s = str_replace(['/', '.'], '-', $s);
  1654. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  1655. return $m[1];
  1656. }
  1657. $ts = strtotime(str_replace('T', ' ', $s));
  1658. if ($ts === false || $ts <= 0) {
  1659. return '';
  1660. }
  1661. return date('Y-m-d', $ts);
  1662. }
  1663. /**
  1664. * 招标截止展示:年月日 + 时分(有秒也保留到分即可)
  1665. */
  1666. protected function mprocFormatYmdHmValue($raw): string
  1667. {
  1668. $s = trim((string)$raw);
  1669. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  1670. return '';
  1671. }
  1672. $s = str_replace(['/', '.'], '-', $s);
  1673. $s = str_replace('T', ' ', $s);
  1674. if (preg_match('/^(\d{4}-\d{2}-\d{2})\s+(\d{2}):(\d{2})(?::\d{2})?/', $s, $m)) {
  1675. return $m[1] . ' ' . $m[2] . ':' . $m[3];
  1676. }
  1677. if (preg_match('/^(\d{4}-\d{2}-\d{2})$/', $s, $m)) {
  1678. return $m[1];
  1679. }
  1680. $ts = strtotime($s);
  1681. if ($ts === false || $ts <= 0) {
  1682. return '';
  1683. }
  1684. return date('Y-m-d H:i', $ts);
  1685. }
  1686. /**
  1687. * 列表展示:招标截止 / 交货截止
  1688. *
  1689. * @param array<string, mixed> $row
  1690. */
  1691. protected function mprocEnrichOrderDeadlineDisplay(array &$row): void
  1692. {
  1693. $sysRqRaw = $this->mprocResolveSysRqFromPo($row);
  1694. $bidRaw = $sysRqRaw !== '' ? $sysRqRaw : trim((string)($row['sys_rq'] ?? ''));
  1695. $bid = $this->mprocFormatYmdHmValue($bidRaw);
  1696. $del = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? '');
  1697. $row['mproc_bid_deadline_display'] = $bid;
  1698. // 完整截止时间供前端保存前校验(含时分秒)
  1699. $row['mproc_bid_deadline'] = $bidRaw;
  1700. $row['mproc_delivery_deadline_display'] = $del;
  1701. $row['mproc_delivery_deadline'] = $del;
  1702. }
  1703. /**
  1704. * 明细对应主表的交货截止日期 Y-m-d
  1705. *
  1706. * @param array<string, mixed> $row
  1707. */
  1708. protected function mprocResolveDeliveryDeadlineYmdForDetailRow(array $row): string
  1709. {
  1710. $fromRow = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? $row['mproc_delivery_deadline'] ?? '');
  1711. if ($fromRow !== '') {
  1712. return $fromRow;
  1713. }
  1714. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1715. if (!$this->mprocIsValidScydgyRowId($sid)) {
  1716. return '';
  1717. }
  1718. try {
  1719. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1720. } catch (\Throwable $e) {
  1721. $po = null;
  1722. }
  1723. if (!is_array($po)) {
  1724. return '';
  1725. }
  1726. return $this->mprocFormatYmdValue($po['delivery_deadline'] ?? $po['Delivery_deadline'] ?? '');
  1727. }
  1728. /**
  1729. * 主表报价截止时间(未设置则视为未截止)
  1730. *
  1731. * @param array<string, mixed>|null $po
  1732. */
  1733. protected function mprocResolveSysRqFromPo(?array $po): string
  1734. {
  1735. if (!is_array($po)) {
  1736. return '';
  1737. }
  1738. $sr = trim((string)($po['sys_rq'] ?? $po['SYS_RQ'] ?? ''));
  1739. if ($sr === '') {
  1740. $pl = array_change_key_case($po, CASE_LOWER);
  1741. $sr = trim((string)($pl['sys_rq'] ?? ''));
  1742. }
  1743. return ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) ? $sr : '';
  1744. }
  1745. /**
  1746. * 从主表/明细解析订单号
  1747. *
  1748. * @param array<string, mixed>|null $po
  1749. * @param array<string, mixed>|null $row
  1750. */
  1751. protected function mprocResolveCcydhFromPoOrRow(?array $po, ?array $row = null): string
  1752. {
  1753. foreach ([$po, $row] as $src) {
  1754. if (!is_array($src)) {
  1755. continue;
  1756. }
  1757. $c = trim((string)($src['CCYDH'] ?? $src['ccydh'] ?? ''));
  1758. if ($c !== '') {
  1759. return $c;
  1760. }
  1761. }
  1762. return '';
  1763. }
  1764. /**
  1765. * 批量:已开标验证的订单号集合(本请求内可复用)
  1766. *
  1767. * @var array<string, bool>|null
  1768. */
  1769. protected $mprocBidOpenVerifiedSet = null;
  1770. /**
  1771. * @param array<int, string> $ccydhs
  1772. * @return array<string, bool>
  1773. */
  1774. protected function mprocLoadBidOpenVerifiedCcydhSet(array $ccydhs): array
  1775. {
  1776. $set = [];
  1777. $list = [];
  1778. foreach ($ccydhs as $c) {
  1779. $c = trim((string)$c);
  1780. if ($c !== '') {
  1781. $list[$c] = true;
  1782. }
  1783. }
  1784. if ($list === []) {
  1785. return $set;
  1786. }
  1787. try {
  1788. $rows = Db::table('purchase_order_bid_open')
  1789. ->where('ccydh', 'in', array_keys($list))
  1790. ->field('ccydh')
  1791. ->select();
  1792. if (!is_array($rows)) {
  1793. return $set;
  1794. }
  1795. foreach ($rows as $row) {
  1796. if (!is_array($row)) {
  1797. continue;
  1798. }
  1799. $c = trim((string)($row['ccydh'] ?? ''));
  1800. if ($c !== '') {
  1801. $set[$c] = true;
  1802. }
  1803. }
  1804. } catch (\Throwable $e) {
  1805. return [];
  1806. }
  1807. return $set;
  1808. }
  1809. /**
  1810. * 该订单是否已完成开标双重验证(有 purchase_order_bid_open 记录)
  1811. */
  1812. protected function mprocIsBidOpenVerified(string $ccydh): bool
  1813. {
  1814. $ccydh = trim($ccydh);
  1815. if ($ccydh === '') {
  1816. return false;
  1817. }
  1818. if (is_array($this->mprocBidOpenVerifiedSet)) {
  1819. return isset($this->mprocBidOpenVerifiedSet[$ccydh]);
  1820. }
  1821. try {
  1822. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1823. return is_array($row);
  1824. } catch (\Throwable $e) {
  1825. return false;
  1826. }
  1827. }
  1828. /**
  1829. * @param array<string, mixed>|null $po
  1830. * @param array<string, mixed>|null $row
  1831. */
  1832. protected function mprocIsBidOpenVerifiedForPoOrRow(?array $po, ?array $row = null): bool
  1833. {
  1834. return $this->mprocIsBidOpenVerified($this->mprocResolveCcydhFromPoOrRow($po, $row));
  1835. }
  1836. /**
  1837. * 手机端:仅当主表设置了 sys_rq 且已到期时视为截止(无截止时间仍可填报)
  1838. * 保存时务必再调一次,防止页面长时间打开、截止后仍提交
  1839. *
  1840. * @param array<string, mixed>|null $po
  1841. */
  1842. protected function mprocIsQuoteDeadlineReachedForPo(?array $po): bool
  1843. {
  1844. $raw = $this->mprocResolveSysRqFromPo($po);
  1845. if ($raw === '') {
  1846. return false;
  1847. }
  1848. $ts = strtotime(str_replace('T', ' ', $raw));
  1849. if ($ts === false || $ts <= 0) {
  1850. return false;
  1851. }
  1852. return time() >= $ts;
  1853. }
  1854. /**
  1855. * 保存前强制按库中最新招标截止时间校验(避免弹窗久开后仍提交)
  1856. *
  1857. * @param array<string, mixed>|null $po
  1858. */
  1859. protected function mprocAssertQuoteNotDeadlineReached(?array $po, string $label = ''): void
  1860. {
  1861. // 以库中最新主表为准,避免内存中旧快照
  1862. $freshPo = null;
  1863. if (is_array($po)) {
  1864. $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
  1865. if ($this->mprocIsValidScydgyRowId($sid)) {
  1866. try {
  1867. $freshPo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1868. } catch (\Throwable $e) {
  1869. $freshPo = null;
  1870. }
  1871. }
  1872. }
  1873. $checkPo = is_array($freshPo) ? $freshPo : $po;
  1874. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($checkPo) ? $checkPo : null)) {
  1875. throw new \InvalidArgumentException(
  1876. ($label !== '' ? $label : '') . '已超过招标截止时间,不可再提交'
  1877. );
  1878. }
  1879. }
  1880. /**
  1881. * 保存前:截止时间 + 已开标均不可再改
  1882. *
  1883. * @param array<string, mixed>|null $po
  1884. * @param array<string, mixed>|null $row
  1885. */
  1886. protected function mprocAssertQuoteStillEditable(?array $po, string $label = '', ?array $row = null): void
  1887. {
  1888. $sid = 0;
  1889. if (is_array($row)) {
  1890. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1891. }
  1892. if ($sid === 0 && is_array($po)) {
  1893. $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
  1894. }
  1895. // 手工询价无招标截止、不开标
  1896. if ($sid < 0) {
  1897. return;
  1898. }
  1899. $this->mprocAssertQuoteNotDeadlineReached($po, $label);
  1900. $freshPo = is_array($po) ? $po : null;
  1901. if (is_array($po)) {
  1902. if ($this->mprocIsValidScydgyRowId($sid)) {
  1903. try {
  1904. $got = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1905. if (is_array($got)) {
  1906. $freshPo = $got;
  1907. }
  1908. } catch (\Throwable $e) {
  1909. }
  1910. }
  1911. }
  1912. // 保存场景不走列表缓存,直接查库
  1913. $prev = $this->mprocBidOpenVerifiedSet;
  1914. $this->mprocBidOpenVerifiedSet = null;
  1915. $opened = $this->mprocIsBidOpenVerifiedForPoOrRow($freshPo, $row);
  1916. $this->mprocBidOpenVerifiedSet = $prev;
  1917. if ($opened) {
  1918. throw new \InvalidArgumentException(
  1919. ($label !== '' ? $label : '') . '已开标验证,不可再提交'
  1920. );
  1921. }
  1922. }
  1923. /**
  1924. * 主单已完结后:中标 / 未中标
  1925. *
  1926. * @param array<string, mixed> $row
  1927. * @param array<string, mixed>|null $po
  1928. */
  1929. protected function mprocResolvePickResultText(array $row, ?array $po): string
  1930. {
  1931. if (!is_array($po) || !ProcuremenStatus::isPoCompleted($po['status'] ?? $po['STATUS'] ?? '')) {
  1932. return '';
  1933. }
  1934. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  1935. return ProcuremenStatus::isPodPicked($detailStatus) ? '中标' : '未中标';
  1936. }
  1937. /**
  1938. * 手机端左侧 Tab:
  1939. * 询价:rfq / rfq_submitted(手工单 scydgy_id&lt;0,仅未提交/已提交)
  1940. * 报价:draft / submitted / done(协助下发)
  1941. *
  1942. * @param array<string, mixed> $row
  1943. * @param array<string, mixed>|null $po
  1944. */
  1945. protected function mprocResolveListTabForRow(array $row, ?array $po, string $effectiveSn): string
  1946. {
  1947. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1948. // 手工询价:无招标截止;仅未提交/已提交(对应待报价/已报价)
  1949. if ($sid < 0) {
  1950. if ($effectiveSn === '已提交'
  1951. || in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  1952. return 'rfq_submitted';
  1953. }
  1954. return 'rfq';
  1955. }
  1956. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  1957. return 'done';
  1958. }
  1959. if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)
  1960. || $this->mprocIsQuoteDeadlineReachedForPo($po)) {
  1961. // 已开标或已过招标截止 →「已完成」
  1962. return 'done';
  1963. }
  1964. if ($effectiveSn === '已提交') {
  1965. return 'submitted';
  1966. }
  1967. return 'draft';
  1968. }
  1969. /**
  1970. * @return string[]
  1971. */
  1972. protected function mprocListTabWhitelist(): array
  1973. {
  1974. return ['rfq', 'rfq_submitted', 'draft', 'submitted', 'done'];
  1975. }
  1976. /**
  1977. * 兼容旧地址 tab=rfq_done → 询价已提交
  1978. */
  1979. protected function mprocNormalizeListTab(string $tab): string
  1980. {
  1981. if ($tab === 'rfq_done') {
  1982. return 'rfq_submitted';
  1983. }
  1984. if (!in_array($tab, $this->mprocListTabWhitelist(), true)) {
  1985. return 'draft';
  1986. }
  1987. return $tab;
  1988. }
  1989. protected function mprocIsDoneListTab(string $tab): bool
  1990. {
  1991. return $tab === 'done';
  1992. }
  1993. protected function mprocIsRfqListTab(string $tab): bool
  1994. {
  1995. return $tab === 'rfq' || $tab === 'rfq_submitted';
  1996. }
  1997. /**
  1998. * 复合 Tab → 状态维度:draft|submitted|done
  1999. */
  2000. protected function mprocStatusFromListTab(string $tab): string
  2001. {
  2002. if ($tab === 'rfq' || $tab === 'draft') {
  2003. return 'draft';
  2004. }
  2005. if ($tab === 'rfq_submitted' || $tab === 'submitted') {
  2006. return 'submitted';
  2007. }
  2008. if ($this->mprocIsDoneListTab($tab)) {
  2009. return 'done';
  2010. }
  2011. return 'draft';
  2012. }
  2013. /**
  2014. * 同一订单号 + 供应商合并为一张卡片
  2015. *
  2016. * @param array<int, array<string, mixed>> $rows
  2017. * @return array<int, array<string, mixed>>
  2018. */
  2019. protected function mprocGroupRowsByOrder(array $rows): array
  2020. {
  2021. $groups = [];
  2022. $order = [];
  2023. foreach ($rows as $row) {
  2024. if (!is_array($row)) {
  2025. continue;
  2026. }
  2027. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2028. $cname = trim((string)($row['company_name'] ?? ''));
  2029. $isVoid = (int)($row['mproc_is_void'] ?? 0) === 1
  2030. || $this->mprocDetailRowIsVoid($row);
  2031. // 已废弃轮与当前轮拆成两张卡,避免混在一起看不清
  2032. $roundKey = $isVoid
  2033. ? ('void:' . (int)($row['eid'] ?? $row['id'] ?? 0))
  2034. : 'active';
  2035. $key = ($ccydh !== '' ? $ccydh : ('eid_' . (int)($row['eid'] ?? 0))) . '|' . $cname . '|' . $roundKey;
  2036. if (!isset($groups[$key])) {
  2037. $groups[$key] = [
  2038. 'group_key' => $key,
  2039. 'CCYDH' => $ccydh,
  2040. 'CYJMC' => trim((string)($row['CYJMC'] ?? '')),
  2041. 'company_name' => $cname,
  2042. 'mproc_bid_deadline_display' => trim((string)($row['mproc_bid_deadline_display'] ?? '')),
  2043. 'mproc_bid_deadline' => trim((string)($row['mproc_bid_deadline'] ?? '')),
  2044. 'mproc_delivery_deadline_display' => trim((string)($row['mproc_delivery_deadline_display'] ?? '')),
  2045. 'mproc_delivery_deadline' => trim((string)($row['mproc_delivery_deadline'] ?? '')),
  2046. 'lines' => [],
  2047. ];
  2048. $order[] = $key;
  2049. } else {
  2050. if ($groups[$key]['mproc_delivery_deadline'] === ''
  2051. && trim((string)($row['mproc_delivery_deadline'] ?? '')) !== '') {
  2052. $groups[$key]['mproc_delivery_deadline'] = trim((string)$row['mproc_delivery_deadline']);
  2053. $groups[$key]['mproc_delivery_deadline_display'] = trim((string)($row['mproc_delivery_deadline_display'] ?? ''));
  2054. }
  2055. if ($groups[$key]['mproc_bid_deadline'] === ''
  2056. && trim((string)($row['mproc_bid_deadline'] ?? '')) !== '') {
  2057. $groups[$key]['mproc_bid_deadline'] = trim((string)$row['mproc_bid_deadline']);
  2058. }
  2059. if ($groups[$key]['mproc_bid_deadline_display'] === ''
  2060. && trim((string)($row['mproc_bid_deadline_display'] ?? '')) !== '') {
  2061. $groups[$key]['mproc_bid_deadline_display'] = trim((string)$row['mproc_bid_deadline_display']);
  2062. }
  2063. }
  2064. $groups[$key]['lines'][] = $row;
  2065. }
  2066. $out = [];
  2067. foreach ($order as $key) {
  2068. $g = $groups[$key];
  2069. $lines = is_array($g['lines'] ?? null) ? $g['lines'] : [];
  2070. usort($lines, function ($a, $b) {
  2071. $sa = (int)($a['scydgy_id'] ?? 0);
  2072. $sb = (int)($b['scydgy_id'] ?? 0);
  2073. if ($sa !== $sb) {
  2074. return $sa <=> $sb;
  2075. }
  2076. return ((int)($a['eid'] ?? 0)) <=> ((int)($b['eid'] ?? 0));
  2077. });
  2078. $g['lines'] = $lines;
  2079. $g['line_count'] = count($lines);
  2080. $canEdit = false;
  2081. $bidOpen = false;
  2082. foreach ($lines as $ln) {
  2083. if (!is_array($ln)) {
  2084. continue;
  2085. }
  2086. if ((int)($ln['mproc_can_edit'] ?? 0) === 1) {
  2087. $canEdit = true;
  2088. }
  2089. if ((int)($ln['mproc_bid_open_verified'] ?? 0) === 1) {
  2090. $bidOpen = true;
  2091. }
  2092. }
  2093. $g['can_edit'] = $canEdit ? 1 : 0;
  2094. $g['mproc_bid_open_verified'] = $bidOpen ? 1 : 0;
  2095. $remark = '';
  2096. $orderRemarkList = [];
  2097. $doneLabel = '';
  2098. $pickResult = '';
  2099. $hasWin = false;
  2100. $hasLose = false;
  2101. $hasExpired = false;
  2102. $hasVoid = false;
  2103. foreach ($lines as $ln) {
  2104. if (!is_array($ln)) {
  2105. continue;
  2106. }
  2107. $rm = $this->mprocSupplierOwnRemark(
  2108. (string)($ln['mproc_remark'] ?? ''),
  2109. (string)($ln['mproc_order_remark'] ?? $ln['MBZ'] ?? '')
  2110. );
  2111. if ($rm !== '' && $remark === '') {
  2112. $remark = $rm;
  2113. }
  2114. $ombz = trim((string)($ln['mproc_order_remark'] ?? $ln['MBZ'] ?? ''));
  2115. if ($ombz !== '' && !in_array($ombz, $orderRemarkList, true)) {
  2116. $orderRemarkList[] = $ombz;
  2117. }
  2118. $pr = trim((string)($ln['mproc_pick_result'] ?? ''));
  2119. $dl = trim((string)($ln['mproc_done_label'] ?? ''));
  2120. if ($pr === '中标' || $dl === '中标') {
  2121. $hasWin = true;
  2122. } elseif ($pr === '未中标' || $dl === '未中标') {
  2123. $hasLose = true;
  2124. } elseif ($dl === '已废弃' || (int)($ln['mproc_is_void'] ?? 0) === 1) {
  2125. $hasVoid = true;
  2126. } elseif ($dl === '已截止' || (int)($ln['mproc_deadline_reached'] ?? 0) === 1) {
  2127. $hasExpired = true;
  2128. }
  2129. }
  2130. if ($hasVoid) {
  2131. $doneLabel = '已废弃';
  2132. $pickResult = '';
  2133. } elseif ($hasWin) {
  2134. $doneLabel = '中标';
  2135. $pickResult = '中标';
  2136. } elseif ($hasLose) {
  2137. $doneLabel = '未中标';
  2138. $pickResult = '未中标';
  2139. } elseif ($hasExpired) {
  2140. $doneLabel = '已截止';
  2141. $pickResult = '';
  2142. }
  2143. $g['remark'] = $remark;
  2144. $g['mproc_order_remark'] = $orderRemarkList !== [] ? implode('、', $orderRemarkList) : '';
  2145. $g['mproc_done_label'] = $doneLabel;
  2146. $g['mproc_pick_result'] = $pickResult;
  2147. $out[] = $g;
  2148. }
  2149. return $out;
  2150. }
  2151. /**
  2152. * 查询 purchase_order_detail 列表(订单页)
  2153. * 无搜索词 / 有搜索词:均按左侧 Tab 筛选(draft/submitted/done)
  2154. * 有搜索词时:在当前 Tab 内做关键字匹配
  2155. *
  2156. * @param string $tab draft|submitted|done
  2157. * @param string|null $statusNameCol status_name 真实列名;为 null 时不按 Tab 过滤
  2158. * @return array{rows: array, done_no_status: int}
  2159. */
  2160. protected function mprocFetchProcuremenList(array $user, $tab, $q, $statusNameCol)
  2161. {
  2162. $query = Db::table('purchase_order_detail')->order('id', 'desc');
  2163. // 初选下发已向供应商发送通知后,手机端可见 wflow_status>=1 的明细
  2164. $userWhere = $this->mprocListWhereForLoginUser($user);
  2165. if ($userWhere !== []) {
  2166. $query->where($userWhere);
  2167. }
  2168. if (trim((string)$q) === '' && $this->mprocIsDoneListTab((string)$tab) && $statusNameCol !== null) {
  2169. $this->mprocSyncLegacyApprovedStatusNames($user, $statusNameCol);
  2170. }
  2171. $this->mprocApplySearchKeywordToDetailQuery($query, $q);
  2172. // Tab 筛选在 PHP 层按截止时间、审批结果综合判断(含逾期进「已完成」、未中标等)
  2173. try {
  2174. $rows = $query->limit(500)->select();
  2175. } catch (\Throwable $e) {
  2176. $rows = [];
  2177. }
  2178. if (!is_array($rows)) {
  2179. $rows = [];
  2180. }
  2181. $poBySid = [];
  2182. $sidList = [];
  2183. foreach ($rows as $r0) {
  2184. if (!is_array($r0)) {
  2185. continue;
  2186. }
  2187. $sid0 = (int)($r0['scydgy_id'] ?? $r0['SCYDGY_ID'] ?? 0);
  2188. if ($this->mprocIsValidScydgyRowId($sid0)) {
  2189. $sidList[$sid0] = true;
  2190. }
  2191. }
  2192. if ($sidList !== []) {
  2193. try {
  2194. $poRows = Db::table('purchase_order')
  2195. ->where('scydgy_id', 'in', array_values(array_keys($sidList)))
  2196. ->select();
  2197. if (is_array($poRows)) {
  2198. foreach ($poRows as $pr) {
  2199. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  2200. if ($this->mprocIsValidScydgyRowId($sidk)) {
  2201. $poBySid[$sidk] = $pr;
  2202. }
  2203. }
  2204. }
  2205. } catch (\Throwable $e) {
  2206. }
  2207. }
  2208. $ccydhForBid = [];
  2209. foreach ($poBySid as $pr) {
  2210. if (!is_array($pr)) {
  2211. continue;
  2212. }
  2213. $c = trim((string)($pr['CCYDH'] ?? $pr['ccydh'] ?? ''));
  2214. if ($c !== '') {
  2215. $ccydhForBid[$c] = true;
  2216. }
  2217. }
  2218. foreach ($rows as $r0) {
  2219. if (!is_array($r0)) {
  2220. continue;
  2221. }
  2222. $c = trim((string)($r0['CCYDH'] ?? $r0['ccydh'] ?? ''));
  2223. if ($c !== '') {
  2224. $ccydhForBid[$c] = true;
  2225. }
  2226. }
  2227. $this->mprocBidOpenVerifiedSet = $this->mprocLoadBidOpenVerifiedCcydhSet(array_keys($ccydhForBid));
  2228. $needScydgyMbzSids = [];
  2229. foreach ($poBySid as $sidKey => $pr) {
  2230. if (!is_array($pr)) {
  2231. continue;
  2232. }
  2233. $mbzPo = '';
  2234. foreach (['mbz', 'MBZ'] as $mk) {
  2235. if (array_key_exists($mk, $pr) && $pr[$mk] !== null && trim((string)$pr[$mk]) !== '') {
  2236. $mbzPo = trim((string)$pr[$mk]);
  2237. break;
  2238. }
  2239. }
  2240. if ($mbzPo === '' && $this->mprocIsValidScydgyRowId((int)$sidKey)) {
  2241. $needScydgyMbzSids[(int)$sidKey] = true;
  2242. }
  2243. }
  2244. $scydgyMbzBySid = [];
  2245. if ($needScydgyMbzSids !== []) {
  2246. $loadedMbz = $this->mprocLoadScydgyMbzByIds(array_keys($needScydgyMbzSids));
  2247. foreach ($loadedMbz as $sidKey => $mbzVal) {
  2248. $mbzVal = trim((string)$mbzVal);
  2249. if ($mbzVal !== '') {
  2250. $scydgyMbzBySid[(int)$sidKey] = $mbzVal;
  2251. }
  2252. }
  2253. }
  2254. foreach ($rows as &$row) {
  2255. if (!is_array($row)) {
  2256. continue;
  2257. }
  2258. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? 0);
  2259. $isVoid = $this->mprocDetailRowIsVoid($row);
  2260. // 已废弃:仅展示「填过报价」的旧轮,与当前轮并排,避免供应商误以为没填过
  2261. if ($isVoid && !$this->mprocDetailRowHasQuote($row)) {
  2262. $row = null;
  2263. continue;
  2264. }
  2265. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2266. if ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) {
  2267. $this->mprocMergePurchaseOrderIntoDetail($row, $poBySid[$sid]);
  2268. }
  2269. if (trim((string)($row['mproc_order_remark'] ?? $row['MBZ'] ?? '')) === ''
  2270. && $this->mprocIsValidScydgyRowId($sid)
  2271. && isset($scydgyMbzBySid[$sid])
  2272. && is_string($scydgyMbzBySid[$sid])) {
  2273. $row['MBZ'] = $scydgyMbzBySid[$sid];
  2274. $row['mproc_order_remark'] = $scydgyMbzBySid[$sid];
  2275. }
  2276. $poRow = ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) ? $poBySid[$sid] : null;
  2277. $oldSn = trim((string)($row['status_name'] ?? ''));
  2278. if ($isVoid) {
  2279. $effectiveSn = ProcuremenStatus::POD_VOID;
  2280. $listTab = 'done';
  2281. $row['status_name'] = $effectiveSn;
  2282. $row['mproc_list_tab'] = $listTab;
  2283. $row['mproc_is_void'] = 1;
  2284. $row['mproc_is_rfq'] = ((int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0) < 0) ? 1 : 0;
  2285. $row['mproc_deadline_reached'] = 0;
  2286. $row['mproc_bid_open_verified'] = 0;
  2287. $row['mproc_pick_result'] = '';
  2288. $row['mproc_done_label'] = '已废弃';
  2289. $row['mproc_can_edit'] = 0;
  2290. } else {
  2291. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, $poRow);
  2292. $row['status_name'] = $effectiveSn;
  2293. if ($statusNameCol !== null && $effectiveSn !== $oldSn && $row['eid'] > 0) {
  2294. $this->mprocPersistDetailStatusName((int)$row['eid'], $statusNameCol, $effectiveSn);
  2295. }
  2296. $listTab = $this->mprocResolveListTabForRow($row, $poRow, $effectiveSn);
  2297. $row['mproc_list_tab'] = $listTab;
  2298. $row['mproc_is_void'] = 0;
  2299. $row['mproc_is_rfq'] = ((int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0) < 0) ? 1 : 0;
  2300. if ((int)$row['mproc_is_rfq'] === 1) {
  2301. $row['mproc_bid_deadline'] = '';
  2302. $row['mproc_bid_deadline_display'] = '';
  2303. $row['mproc_delivery_deadline'] = '';
  2304. $row['mproc_delivery_deadline_display'] = '';
  2305. $row['mproc_deadline_reached'] = 0;
  2306. $row['mproc_bid_open_verified'] = 0;
  2307. $row['mproc_pick_result'] = '';
  2308. } else {
  2309. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  2310. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  2311. $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow($poRow, $row) ? 1 : 0;
  2312. }
  2313. if ($row['mproc_pick_result'] !== '') {
  2314. $row['mproc_done_label'] = $row['mproc_pick_result'];
  2315. } elseif ($this->mprocIsDoneListTab($listTab) && (
  2316. (int)$row['mproc_deadline_reached'] === 1
  2317. || (int)$row['mproc_bid_open_verified'] === 1
  2318. )) {
  2319. $row['mproc_done_label'] = '已截止';
  2320. } else {
  2321. $row['mproc_done_label'] = '';
  2322. }
  2323. if (!isset($row['status_name']) || $row['status_name'] === null) {
  2324. $row['status_name'] = '';
  2325. } else {
  2326. $row['status_name'] = trim((string)$row['status_name']);
  2327. }
  2328. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  2329. }
  2330. $am = $row['amount'] ?? null;
  2331. if ($am === null || $am === '' || (is_string($am) && trim($am) === '')) {
  2332. $row['amount_display'] = '';
  2333. } else {
  2334. $row['amount_display'] = is_scalar($am) ? (string)$am : '';
  2335. }
  2336. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2337. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  2338. $row['delivery_display'] = $m[1];
  2339. } elseif ($dv !== '') {
  2340. $row['delivery_display'] = $dv;
  2341. } else {
  2342. $row['delivery_display'] = '';
  2343. }
  2344. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  2345. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  2346. $this->mprocEnrichLeadDaysDisplay($row);
  2347. if ((int)$row['mproc_is_rfq'] === 1) {
  2348. $row['mproc_bid_deadline'] = '';
  2349. $row['mproc_bid_deadline_display'] = '';
  2350. $row['mproc_delivery_deadline'] = '';
  2351. $row['mproc_delivery_deadline_display'] = '';
  2352. } else {
  2353. $this->mprocEnrichOrderDeadlineDisplay($row);
  2354. }
  2355. $row['mproc_fill_hint'] = '';
  2356. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  2357. $orderRemark = trim((string)($row['mproc_order_remark'] ?? $row['MBZ'] ?? ''));
  2358. $detailRemark = $this->mprocResolveDetailRemark($row);
  2359. if ($orderRemark === '') {
  2360. $row['mproc_order_remark'] = '';
  2361. }
  2362. $row['mproc_remark'] = $this->mprocSupplierOwnRemark($detailRemark, $orderRemark);
  2363. }
  2364. unset($row);
  2365. $rows = array_values(array_filter($rows, function ($r) {
  2366. return is_array($r);
  2367. }));
  2368. // 同一供应商同一工序:保留最新有效轮 + 最近一轮已废弃且有报价的记录
  2369. $rows = $this->mprocDedupeDetailRowsByCompanyProcess($rows);
  2370. // 始终按 Tab 过滤(含搜索):未中标/已截止等只出现在「已完成」
  2371. $rows = array_values(array_filter($rows, function ($r) use ($tab) {
  2372. return is_array($r) && trim((string)($r['mproc_list_tab'] ?? '')) === $tab;
  2373. }));
  2374. // 「已完成」仅保留近三个月(按招标截止日,缺省则交货截止/创建时间)
  2375. if ($this->mprocIsDoneListTab((string)$tab)) {
  2376. $rows = array_values(array_filter($rows, function ($r) {
  2377. return is_array($r) && $this->mprocIsWithinRecentMonths($r, 3);
  2378. }));
  2379. }
  2380. // 按招标截止日期排序:未提交/已提交截止近的在前;已完成最近截止的在前
  2381. $rows = $this->mprocSortRowsByBidDeadline($rows, $this->mprocIsDoneListTab((string)$tab) ? 'desc' : 'asc');
  2382. $groups = $this->mprocGroupRowsByOrder($rows);
  2383. return [
  2384. 'rows' => $rows ?: [],
  2385. 'groups' => $groups ?: [],
  2386. 'done_no_status' => (int)($statusNameCol === null),
  2387. ];
  2388. }
  2389. /**
  2390. * 按招标截止时间排序(无截止时间的排最后)
  2391. *
  2392. * @param array<int, array<string, mixed>> $rows
  2393. * @param string $dir asc|desc
  2394. * @return array<int, array<string, mixed>>
  2395. */
  2396. protected function mprocSortRowsByBidDeadline(array $rows, string $dir = 'asc'): array
  2397. {
  2398. $dir = strtolower($dir) === 'desc' ? 'desc' : 'asc';
  2399. usort($rows, function ($a, $b) use ($dir) {
  2400. $ta = $this->mprocBidDeadlineSortTs(is_array($a) ? $a : []);
  2401. $tb = $this->mprocBidDeadlineSortTs(is_array($b) ? $b : []);
  2402. $ha = $ta > 0;
  2403. $hb = $tb > 0;
  2404. if ($ha !== $hb) {
  2405. return $ha ? -1 : 1;
  2406. }
  2407. if ($ha && $ta !== $tb) {
  2408. return $dir === 'desc' ? ($tb <=> $ta) : ($ta <=> $tb);
  2409. }
  2410. $ida = (int)($a['eid'] ?? $a['id'] ?? 0);
  2411. $idb = (int)($b['eid'] ?? $b['id'] ?? 0);
  2412. return $idb <=> $ida;
  2413. });
  2414. return array_values($rows);
  2415. }
  2416. /**
  2417. * @param array<string, mixed> $row
  2418. */
  2419. protected function mprocBidDeadlineSortTs(array $row): int
  2420. {
  2421. $raw = trim((string)($row['mproc_bid_deadline'] ?? $row['sys_rq'] ?? $row['SYS_RQ'] ?? ''));
  2422. if ($raw === '') {
  2423. $raw = trim((string)($row['mproc_bid_deadline_display'] ?? ''));
  2424. }
  2425. if ($raw === '') {
  2426. return 0;
  2427. }
  2428. $ts = strtotime(str_replace('T', ' ', $raw));
  2429. return ($ts !== false && $ts > 0) ? (int)$ts : 0;
  2430. }
  2431. /**
  2432. * 是否属于近 N 个月(优先招标截止,其次交货截止,再次创建/更新时间)
  2433. *
  2434. * @param array<string, mixed> $row
  2435. */
  2436. protected function mprocIsWithinRecentMonths(array $row, int $months = 3): bool
  2437. {
  2438. $months = max(1, $months);
  2439. $since = strtotime(date('Y-m-d 00:00:00', strtotime('-' . $months . ' months')));
  2440. if ($since === false) {
  2441. return true;
  2442. }
  2443. $candidates = [
  2444. $row['mproc_bid_deadline'] ?? '',
  2445. $row['sys_rq'] ?? '',
  2446. $row['SYS_RQ'] ?? '',
  2447. $row['mproc_bid_deadline_display'] ?? '',
  2448. $row['mproc_delivery_deadline'] ?? '',
  2449. $row['delivery_deadline'] ?? '',
  2450. $row['mproc_delivery_deadline_display'] ?? '',
  2451. $row['createtime'] ?? '',
  2452. $row['updatetime'] ?? '',
  2453. ];
  2454. foreach ($candidates as $raw) {
  2455. $raw = trim((string)$raw);
  2456. if ($raw === '' || stripos($raw, '0000-00-00') === 0) {
  2457. continue;
  2458. }
  2459. $ts = strtotime(str_replace('T', ' ', $raw));
  2460. if ($ts === false || $ts <= 0) {
  2461. continue;
  2462. }
  2463. return $ts >= $since;
  2464. }
  2465. return false;
  2466. }
  2467. /**
  2468. * 同一供应商 + 同一工序:
  2469. * - 有效轮只保留 id 最大的一条
  2470. * - 已废弃且有报价的,再保留 id 最大的一条(与有效轮并排展示)
  2471. *
  2472. * @param array<int, array<string, mixed>> $rows
  2473. * @return array<int, array<string, mixed>>
  2474. */
  2475. protected function mprocDedupeDetailRowsByCompanyProcess(array $rows): array
  2476. {
  2477. $bestActive = [];
  2478. $bestVoid = [];
  2479. $orderKeys = [];
  2480. foreach ($rows as $row) {
  2481. if (!is_array($row)) {
  2482. continue;
  2483. }
  2484. $cn = trim((string)($row['company_name'] ?? ''));
  2485. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2486. $eid = (int)($row['eid'] ?? $row['id'] ?? $row['ID'] ?? 0);
  2487. if ($this->mprocIsValidScydgyRowId($sid)) {
  2488. $key = $cn . '|sid:' . $sid;
  2489. } else {
  2490. $key = $cn . '|eid:' . $eid;
  2491. }
  2492. $isVoid = (int)($row['mproc_is_void'] ?? 0) === 1 || $this->mprocDetailRowIsVoid($row);
  2493. if ($isVoid) {
  2494. if (!$this->mprocDetailRowHasQuote($row)) {
  2495. continue;
  2496. }
  2497. if (!isset($bestVoid[$key])) {
  2498. $bestVoid[$key] = $row;
  2499. if (!isset($bestActive[$key]) && !in_array($key, $orderKeys, true)) {
  2500. $orderKeys[] = $key;
  2501. }
  2502. continue;
  2503. }
  2504. $prevEid = (int)($bestVoid[$key]['eid'] ?? $bestVoid[$key]['id'] ?? 0);
  2505. if ($eid > $prevEid) {
  2506. $bestVoid[$key] = $row;
  2507. }
  2508. continue;
  2509. }
  2510. if (!isset($bestActive[$key])) {
  2511. $bestActive[$key] = $row;
  2512. if (!in_array($key, $orderKeys, true)) {
  2513. $orderKeys[] = $key;
  2514. }
  2515. continue;
  2516. }
  2517. $prevEid = (int)($bestActive[$key]['eid'] ?? $bestActive[$key]['id'] ?? 0);
  2518. if ($eid > $prevEid) {
  2519. $bestActive[$key] = $row;
  2520. }
  2521. }
  2522. $out = [];
  2523. foreach ($orderKeys as $key) {
  2524. // 先当前轮,后已废弃轮(列表里当前在上更直观)
  2525. if (isset($bestActive[$key])) {
  2526. $out[] = $bestActive[$key];
  2527. }
  2528. if (isset($bestVoid[$key])) {
  2529. $activeEid = isset($bestActive[$key])
  2530. ? (int)($bestActive[$key]['eid'] ?? $bestActive[$key]['id'] ?? 0)
  2531. : 0;
  2532. $voidEid = (int)($bestVoid[$key]['eid'] ?? $bestVoid[$key]['id'] ?? 0);
  2533. if ($voidEid > 0 && $voidEid !== $activeEid) {
  2534. $out[] = $bestVoid[$key];
  2535. }
  2536. }
  2537. }
  2538. return $out;
  2539. }
  2540. /**
  2541. * @param array<string, mixed> $row
  2542. */
  2543. protected function mprocDetailRowIsVoid(array $row): bool
  2544. {
  2545. return ProcuremenStatus::isPodVoid($row['status'] ?? '')
  2546. || trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  2547. }
  2548. /**
  2549. * @param array<string, mixed> $row
  2550. */
  2551. protected function mprocDetailRowHasQuote(array $row): bool
  2552. {
  2553. $am = $row['amount'] ?? null;
  2554. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  2555. return true;
  2556. }
  2557. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2558. if ($dv !== '' && !preg_match('/^0000-00-00/i', $dv)) {
  2559. return true;
  2560. }
  2561. $ld = $row['lead_days'] ?? null;
  2562. return $ld !== null && $ld !== '' && is_numeric($ld);
  2563. }
  2564. /**
  2565. * status_name → 手机端左侧 Tab
  2566. */
  2567. protected function mprocStatusNameToListTab(string $statusName): string
  2568. {
  2569. $map = ['未提交' => 'draft', '已提交' => 'submitted', '已完成' => 'done', '未通过' => 'done', '已废弃' => 'done'];
  2570. $sn = trim($statusName);
  2571. return isset($map[$sn]) ? $map[$sn] : '';
  2572. }
  2573. /**
  2574. * 短信/邮件 focus_eid 应落在的列表 Tab
  2575. */
  2576. protected function mprocResolveListTabForFocusEid(int $focusEid, array $user): string
  2577. {
  2578. if ($focusEid <= 0) {
  2579. return '';
  2580. }
  2581. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2582. if ($idCol === null) {
  2583. return '';
  2584. }
  2585. try {
  2586. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  2587. $qw = $this->mprocListWhereForLoginUser($user);
  2588. if ($qw !== []) {
  2589. $qrow->where($qw);
  2590. }
  2591. $dr = $qrow->find();
  2592. } catch (\Throwable $e) {
  2593. $dr = null;
  2594. }
  2595. if (!is_array($dr) || $dr === []) {
  2596. return '';
  2597. }
  2598. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  2599. $po = null;
  2600. if ($this->mprocIsValidScydgyRowId($sid)) {
  2601. try {
  2602. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2603. } catch (\Throwable $e) {
  2604. $po = null;
  2605. }
  2606. }
  2607. return $this->mprocResolveListTabForRow(
  2608. $dr,
  2609. is_array($po) ? $po : null,
  2610. $this->mprocResolveEffectiveStatusName($dr, is_array($po) ? $po : null)
  2611. );
  2612. }
  2613. /**
  2614. * 短信/邮件直达链接:确保 focus 对应明细出现在当前列表(便于高亮定位)
  2615. *
  2616. * @param array<string, mixed> $bundle
  2617. * @param array<string, mixed> $user
  2618. * @return array<string, mixed>
  2619. */
  2620. protected function mprocEnsureFocusRowInList(
  2621. array $bundle,
  2622. int $focusEid,
  2623. array $user,
  2624. $statusNameCol,
  2625. string $tab = 'draft',
  2626. string $q = ''
  2627. ): array {
  2628. if ($focusEid <= 0) {
  2629. return $bundle;
  2630. }
  2631. $rows = isset($bundle['rows']) && is_array($bundle['rows']) ? $bundle['rows'] : [];
  2632. $foundIdx = -1;
  2633. foreach ($rows as $idx => $r) {
  2634. if (!is_array($r)) {
  2635. continue;
  2636. }
  2637. if ((int)($r['eid'] ?? $r['id'] ?? $r['ID'] ?? 0) === $focusEid) {
  2638. $foundIdx = (int)$idx;
  2639. break;
  2640. }
  2641. }
  2642. if ($foundIdx > 0) {
  2643. $hit = $rows[$foundIdx];
  2644. array_splice($rows, $foundIdx, 1);
  2645. array_unshift($rows, $hit);
  2646. $bundle['rows'] = $rows;
  2647. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  2648. return $bundle;
  2649. }
  2650. if ($foundIdx === 0) {
  2651. return $bundle;
  2652. }
  2653. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2654. if ($idCol === null) {
  2655. return $bundle;
  2656. }
  2657. try {
  2658. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  2659. $qw = $this->mprocListWhereForLoginUser($user);
  2660. if ($qw !== []) {
  2661. $qrow->where($qw);
  2662. }
  2663. $dr = $qrow->find();
  2664. } catch (\Throwable $e) {
  2665. $dr = null;
  2666. }
  2667. if (!is_array($dr) || $dr === []) {
  2668. return $bundle;
  2669. }
  2670. $row = $dr;
  2671. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? $focusEid);
  2672. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2673. $poRow = null;
  2674. if ($this->mprocIsValidScydgyRowId($sid)) {
  2675. try {
  2676. $poRow = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2677. } catch (\Throwable $e) {
  2678. $poRow = null;
  2679. }
  2680. if (is_array($poRow)) {
  2681. $this->mprocMergePurchaseOrderIntoDetail($row, $poRow);
  2682. }
  2683. }
  2684. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($poRow) ? $poRow : null);
  2685. $rowTab = $this->mprocResolveListTabForRow($row, is_array($poRow) ? $poRow : null, $effectiveSn);
  2686. if ($rowTab !== '' && $rowTab !== $tab) {
  2687. return $bundle;
  2688. }
  2689. $row['status_name'] = $effectiveSn;
  2690. $listTab = $rowTab;
  2691. $row['mproc_list_tab'] = $listTab;
  2692. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  2693. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  2694. $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow(is_array($poRow) ? $poRow : null, $row) ? 1 : 0;
  2695. if ($row['mproc_pick_result'] !== '') {
  2696. $row['mproc_done_label'] = $row['mproc_pick_result'];
  2697. } elseif ($this->mprocIsDoneListTab($listTab) && (
  2698. (int)$row['mproc_deadline_reached'] === 1
  2699. || (int)$row['mproc_bid_open_verified'] === 1
  2700. )) {
  2701. $row['mproc_done_label'] = '已截止';
  2702. } else {
  2703. $row['mproc_done_label'] = '';
  2704. }
  2705. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  2706. $am = $row['amount'] ?? null;
  2707. $row['amount_display'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? '' : (is_scalar($am) ? (string)$am : '');
  2708. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2709. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  2710. $row['delivery_display'] = $m[1];
  2711. } elseif ($dv !== '') {
  2712. $row['delivery_display'] = $dv;
  2713. } else {
  2714. $row['delivery_display'] = '';
  2715. }
  2716. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  2717. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  2718. $this->mprocEnrichLeadDaysDisplay($row);
  2719. $this->mprocEnrichOrderDeadlineDisplay($row);
  2720. $row['mproc_fill_hint'] = '';
  2721. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  2722. array_unshift($rows, $row);
  2723. $bundle['rows'] = $rows;
  2724. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  2725. return $bundle;
  2726. }
  2727. /**
  2728. * 列表展示用「本次数量」:主表本次数量为空时回退显示 NGZL(工作量)
  2729. *
  2730. * @param array<string, mixed> $row
  2731. */
  2732. protected function mprocResolveDisplayThisQuantity(array $row): string
  2733. {
  2734. $qty = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  2735. if ($qty !== '') {
  2736. return $qty;
  2737. }
  2738. $gzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  2739. if ($gzl === null || $gzl === '') {
  2740. return '';
  2741. }
  2742. return is_scalar($gzl) ? trim((string)$gzl) : '';
  2743. }
  2744. /**
  2745. * 明细是否已填写单价或交货日期
  2746. *
  2747. * @param array<string, mixed> $row
  2748. */
  2749. protected function mprocDetailQuoteSubmitted(array $row): bool
  2750. {
  2751. $am = $row['amount'] ?? null;
  2752. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2753. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  2754. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  2755. return $amountFilled || $deliveryFilled;
  2756. }
  2757. /**
  2758. * 手机端列表 Tab 用 status_name;审批通过后主表 status=1 时按明细 status 纠偏
  2759. *
  2760. * @param array<string, mixed> $row
  2761. * @param array<string, mixed>|null $po
  2762. */
  2763. protected function mprocResolveEffectiveStatusName(array $row, ?array $po): string
  2764. {
  2765. $sn = trim((string)($row['status_name'] ?? ''));
  2766. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  2767. return $sn;
  2768. }
  2769. if (!is_array($po)) {
  2770. if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
  2771. return '已提交';
  2772. }
  2773. if ($sn !== '') {
  2774. return $sn;
  2775. }
  2776. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  2777. }
  2778. $poStatus = $po['status'] ?? $po['STATUS'] ?? '';
  2779. if (!ProcuremenStatus::isPoCompleted($poStatus)) {
  2780. // 库中仍写「未提交」但已填单价/交期:按已提交展示(手工单常见)
  2781. if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
  2782. return '已提交';
  2783. }
  2784. if ($sn !== '') {
  2785. return $sn;
  2786. }
  2787. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  2788. }
  2789. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  2790. if (ProcuremenStatus::isPodPicked($detailStatus)) {
  2791. return '已完成';
  2792. }
  2793. if ($sn === '已提交') {
  2794. return '未通过';
  2795. }
  2796. return $sn !== '' ? $sn : '未提交';
  2797. }
  2798. /**
  2799. * 将纠偏后的 status_name 写回库表(兼容历史已审批数据)
  2800. */
  2801. protected function mprocPersistDetailStatusName(int $detailId, string $statusNameCol, string $statusName): void
  2802. {
  2803. if ($detailId <= 0 || $statusNameCol === '') {
  2804. return;
  2805. }
  2806. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2807. if ($idCol === null || $idCol === '') {
  2808. return;
  2809. }
  2810. try {
  2811. Db::table('purchase_order_detail')->where($idCol, $detailId)->update([$statusNameCol => $statusName]);
  2812. } catch (\Throwable $e) {
  2813. }
  2814. }
  2815. /**
  2816. * 纠偏历史数据:主表已审批(status=1)但明细 status_name 仍为「已提交」
  2817. *
  2818. * @param array<string, mixed> $user
  2819. */
  2820. protected function mprocSyncLegacyApprovedStatusNames(array $user, string $statusNameCol): void
  2821. {
  2822. $userWhere = $this->mprocListWhereForLoginUser($user);
  2823. try {
  2824. $query = Db::table('purchase_order_detail')->where($statusNameCol, '已提交');
  2825. if ($userWhere !== []) {
  2826. $query->where($userWhere);
  2827. }
  2828. $candidates = $query->limit(200)->select();
  2829. } catch (\Throwable $e) {
  2830. return;
  2831. }
  2832. if (!is_array($candidates) || $candidates === []) {
  2833. return;
  2834. }
  2835. $sidList = [];
  2836. foreach ($candidates as $cr) {
  2837. if (!is_array($cr)) {
  2838. continue;
  2839. }
  2840. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  2841. if ($this->mprocIsValidScydgyRowId($sid)) {
  2842. $sidList[$sid] = true;
  2843. }
  2844. }
  2845. if ($sidList === []) {
  2846. return;
  2847. }
  2848. $poBySid = [];
  2849. try {
  2850. $poRows = Db::table('purchase_order')
  2851. ->where('scydgy_id', 'in', array_keys($sidList))
  2852. ->whereIn('status', ProcuremenStatus::poCompletedValues())
  2853. ->select();
  2854. if (is_array($poRows)) {
  2855. foreach ($poRows as $pr) {
  2856. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  2857. if ($this->mprocIsValidScydgyRowId($sidk)) {
  2858. $poBySid[$sidk] = $pr;
  2859. }
  2860. }
  2861. }
  2862. } catch (\Throwable $e) {
  2863. return;
  2864. }
  2865. if ($poBySid === []) {
  2866. return;
  2867. }
  2868. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2869. if ($idCol === null || $idCol === '') {
  2870. return;
  2871. }
  2872. foreach ($candidates as $cr) {
  2873. if (!is_array($cr)) {
  2874. continue;
  2875. }
  2876. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  2877. if (!isset($poBySid[$sid])) {
  2878. continue;
  2879. }
  2880. $detailId = (int)($cr[$idCol] ?? $cr['id'] ?? $cr['ID'] ?? 0);
  2881. if ($detailId <= 0) {
  2882. continue;
  2883. }
  2884. $targetSn = $this->mprocResolveEffectiveStatusName($cr, $poBySid[$sid]);
  2885. if ($targetSn === '已提交') {
  2886. continue;
  2887. }
  2888. $this->mprocPersistDetailStatusName($detailId, $statusNameCol, $targetSn);
  2889. }
  2890. }
  2891. /**
  2892. * 协助明细首页(需登录)
  2893. * GET:main_tab=orders|me,orders 时 tab=draft|submitted|done 对应 status_name:未提交|已提交|已完成;q 搜索词
  2894. */
  2895. public function index()
  2896. {
  2897. $user = $this->mprocGetUser();
  2898. if (!$user) {
  2899. $pendingFocus = $this->mprocReadFocusEidFromRequest();
  2900. if ($pendingFocus > 0) {
  2901. $this->mprocRememberFocusEid($pendingFocus);
  2902. }
  2903. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  2904. $safe = $this->mprocSanitizeRedirectUrl($uri);
  2905. if ($safe !== '' && $pendingFocus > 0 && stripos($safe, 'focus_eid') === false) {
  2906. $safe .= (strpos($safe, '?') !== false ? '&' : '?') . 'focus_eid=' . $pendingFocus;
  2907. }
  2908. if ($safe !== '') {
  2909. Session::set('mproc_intended_url', $safe);
  2910. }
  2911. $this->redirect($this->mprocBuildLoginUrl($safe));
  2912. return;
  2913. }
  2914. // 管理员进对应业务页,不进供应商报价列表
  2915. if (!empty($user['is_admin'])) {
  2916. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  2917. if ($jump === '') {
  2918. $this->mprocDropCurrentLogin();
  2919. $this->redirect(url('index/index/login'));
  2920. return;
  2921. }
  2922. $this->redirect($jump);
  2923. return;
  2924. }
  2925. $user = $this->mprocSyncSessionCustomerUser($user);
  2926. $tabParamRaw = $this->request->get('tab', null);
  2927. $hasExplicitTab = ($tabParamRaw !== null && trim((string)$tabParamRaw) !== '');
  2928. $tabParam = trim((string)($tabParamRaw ?? 'draft'));
  2929. $mainTab = trim((string)$this->request->get('main_tab', 'orders'));
  2930. // 旧地址 ?tab=me 表示「我的」
  2931. if ($tabParam === 'me') {
  2932. $mainTab = 'me';
  2933. }
  2934. if (!in_array($mainTab, ['orders', 'me'], true)) {
  2935. $mainTab = 'orders';
  2936. }
  2937. $tab = $tabParam === 'me' ? 'draft' : $this->mprocNormalizeListTab($tabParam);
  2938. $q = trim((string)$this->request->get('q', ''));
  2939. $mprocFocusEid = 0;
  2940. $focusEid = $this->mprocReadFocusEidFromRequest();
  2941. if ($focusEid > 0 && $mainTab === 'orders') {
  2942. $resolvedTab = $this->mprocResolveListTabForFocusEid($focusEid, $user);
  2943. // 用户已手动点了其他左侧 Tab:取消定位锁定,避免刷新又跳回
  2944. if ($hasExplicitTab && $resolvedTab !== '' && $resolvedTab !== $tab) {
  2945. Session::delete('mproc_focus_eid');
  2946. $focusEid = 0;
  2947. } else {
  2948. $mprocFocusEid = $focusEid;
  2949. // 仅邮件/短信直链且 URL 未带 tab 时,自动切到定位单所在 Tab
  2950. $focusFromUrl = (int)$this->request->param('focus_eid', 0) > 0;
  2951. if (!$focusFromUrl) {
  2952. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  2953. $focusFromUrl = $this->mprocParseFocusEidFromUriString($uri) > 0;
  2954. }
  2955. if ($focusFromUrl && trim((string)$q) === '' && !$hasExplicitTab) {
  2956. if ($resolvedTab !== '') {
  2957. $tab = $resolvedTab;
  2958. }
  2959. }
  2960. }
  2961. }
  2962. // 左侧 Tab 按 purchase_order_detail.status_name(未提交/已提交/已完成),与数值 status 无关
  2963. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2964. $profile = $this->mprocProfileForUser($user);
  2965. $this->view->assign('mprocMainTab', $mainTab);
  2966. $this->view->assign('mprocTab', $tab);
  2967. $this->view->assign('mprocIsRfqTab', $this->mprocIsRfqListTab($tab) ? 1 : 0);
  2968. $this->view->assign('mprocStatusTab', $this->mprocStatusFromListTab($tab));
  2969. $this->view->assign('mprocSearchQ', $q);
  2970. $this->view->assign('mprocProfile', $profile);
  2971. $this->view->assign('mprocIsAdmin', !empty($user['is_admin']) ? 1 : 0);
  2972. $cid = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  2973. $this->view->assign('mprocCanChangePwd', empty($user['is_admin']) && $cid > 0 ? 1 : 0);
  2974. $this->view->assign('mprocFocusEid', $mprocFocusEid);
  2975. $mprocFocusTab = $mprocFocusEid > 0 ? $this->mprocResolveListTabForFocusEid($mprocFocusEid, $user) : '';
  2976. $this->view->assign('mprocFocusTab', $mprocFocusTab);
  2977. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  2978. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  2979. $this->view->assign('mprocDeliveryNoteUrl', url('index/index/deliverynote'));
  2980. if ($mainTab === 'me') {
  2981. $this->view->assign('rows', []);
  2982. return $this->view->fetch();
  2983. }
  2984. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  2985. if ($mprocFocusEid > 0) {
  2986. $bundle = $this->mprocEnsureFocusRowInList($bundle, $mprocFocusEid, $user, $statusNameCol, $tab, $q);
  2987. }
  2988. $this->view->assign('rows', $bundle['rows']);
  2989. $this->view->assign('groups', $bundle['groups'] ?? $this->mprocGroupRowsByOrder($bundle['rows']));
  2990. return $this->view->fetch();
  2991. }
  2992. /**
  2993. * 协助明细列表 JSON(需登录)
  2994. * main_tab=orders|me;orders 时 tab=draft|submitted|done、q=搜索词
  2995. */
  2996. public function mprocList()
  2997. {
  2998. $user = $this->mprocGetUser();
  2999. if (!$user) {
  3000. $this->error('请先登录', url('index/index/login'));
  3001. }
  3002. $user = $this->mprocSyncSessionCustomerUser($user);
  3003. $tabParam = trim((string)$this->request->request('tab', 'draft'));
  3004. $mainTab = trim((string)$this->request->request('main_tab', 'orders'));
  3005. if ($tabParam === 'me') {
  3006. $mainTab = 'me';
  3007. }
  3008. if (!in_array($mainTab, ['orders', 'me'], true)) {
  3009. $mainTab = 'orders';
  3010. }
  3011. $tab = $tabParam === 'me' ? 'draft' : $this->mprocNormalizeListTab($tabParam);
  3012. $q = trim((string)$this->request->request('q', ''));
  3013. if ($mainTab === 'me') {
  3014. // Jump::success($msg, $url, $data, …) 第二参是 URL,数据必须放第三参
  3015. $this->success('ok', '', [
  3016. 'main_tab' => 'me',
  3017. 'tab' => $tab,
  3018. 'rows' => [],
  3019. 'profile' => $this->mprocProfileForUser($user),
  3020. 'done_no_status' => 0,
  3021. ]);
  3022. }
  3023. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  3024. if ((int)$this->request->request('clear_focus', 0) === 1) {
  3025. Session::delete('mproc_focus_eid');
  3026. $focusEid = 0;
  3027. $focusTab = '';
  3028. } else {
  3029. $focusEid = $this->mprocReadFocusEidFromRequest();
  3030. $focusTab = $focusEid > 0 ? $this->mprocResolveListTabForFocusEid($focusEid, $user) : '';
  3031. // 列表请求已指定 Tab,且与定位单所在 Tab 不同:视为用户离开锁定页
  3032. if ($focusEid > 0 && $focusTab !== '' && $focusTab !== $tab) {
  3033. Session::delete('mproc_focus_eid');
  3034. $focusEid = 0;
  3035. $focusTab = '';
  3036. }
  3037. }
  3038. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  3039. if ($focusEid > 0) {
  3040. $bundle = $this->mprocEnsureFocusRowInList($bundle, $focusEid, $user, $statusNameCol, $tab, $q);
  3041. }
  3042. $this->success('ok', '', array_merge([
  3043. 'main_tab' => 'orders',
  3044. 'tab' => $tab,
  3045. 'focus_tab' => $focusTab,
  3046. 'is_admin' => !empty($user['is_admin']) ? 1 : 0,
  3047. 'focus_eid' => $focusEid,
  3048. ], $bundle));
  3049. }
  3050. /**
  3051. * 登录页(手机号验证码 / 账号密码)
  3052. */
  3053. public function login()
  3054. {
  3055. $redirect = $this->mprocSanitizeRedirectUrl($this->request->get('redirect', ''));
  3056. $user = $this->mprocGetUser();
  3057. if ($user) {
  3058. $jump = $this->mprocBuildAfterLoginHomeUrl($user, $redirect);
  3059. if ($jump !== '') {
  3060. $this->redirect($jump);
  3061. return;
  3062. }
  3063. // 已登录但无手机端权限(其它后台账号):清会话,避免登录页↔自身 302 死循环
  3064. $this->mprocDropCurrentLogin();
  3065. }
  3066. if ($redirect !== '') {
  3067. Session::set('mproc_intended_url', $redirect);
  3068. }
  3069. $this->view->assign('mprocLoginRedirect', $redirect);
  3070. $this->view->assign('mprocCaptchaUrl', url('index/index/captcha'));
  3071. $this->view->assign('mprocCaptchaLen', (int)(Config::get('captcha.length') ?: 4));
  3072. return $this->view->fetch();
  3073. }
  3074. /**
  3075. * 图形验证码(手机号登录用)
  3076. */
  3077. public function captcha($id = '')
  3078. {
  3079. $captcha = new Captcha((array)Config::get('captcha'));
  3080. return $captcha->entry($id);
  3081. }
  3082. /**
  3083. * 发送登录验证码(POST:phone、captcha)
  3084. */
  3085. public function sendSms()
  3086. {
  3087. if (!$this->request->isPost()) {
  3088. $this->error('请使用 POST');
  3089. }
  3090. $phone = trim((string)$this->request->post('phone', ''));
  3091. $captcha = trim((string)$this->request->post('captcha', ''));
  3092. if (!preg_match('/^1\d{10}$/', $phone)) {
  3093. $this->error('请输入正确的11位手机号');
  3094. }
  3095. if ($captcha === '') {
  3096. $this->error('请输入图形验证码');
  3097. }
  3098. $cu = $this->mprocFindCustomerUserByMobile($phone);
  3099. $adminRow = $cu ? null : $this->mprocAdminRowByMobile($phone);
  3100. if (!$cu && !$adminRow) {
  3101. $this->error('账号或密码错误');
  3102. }
  3103. if ($adminRow) {
  3104. $probe = $this->mprocLoginPayloadFromAdmin($adminRow, 'sms');
  3105. if (!$this->mprocAdminHasAnyMobileAccess($probe)) {
  3106. $this->error('账号或密码错误');
  3107. }
  3108. }
  3109. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  3110. if (Cache::get('mproc_sms_wait_' . $phone)) {
  3111. $this->error('发送过于频繁,请稍后再试');
  3112. }
  3113. if (!Validate::is($captcha, 'captcha')) {
  3114. $this->error('图形验证码不正确');
  3115. }
  3116. $code = (string)random_int(100000, 999999);
  3117. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  3118. $ttl = max(60, min(600, $ttl));
  3119. Cache::set('mproc_code_' . $phone, $code, $ttl);
  3120. Cache::set('mproc_sms_wait_' . $phone, 1, $cd);
  3121. try {
  3122. $tpl = trim((string)Config::get('mproc.sms_login_template'));
  3123. if ($tpl === '') {
  3124. $tpl = '【可集达】您的验证码是{code}。如非本人操作,请忽略本短信';
  3125. }
  3126. $content = str_replace('{code}', $code, $tpl);
  3127. $this->mprocSmsSend($phone, $content);
  3128. } catch (\Exception $e) {
  3129. Cache::rm('mproc_code_' . $phone);
  3130. Cache::rm('mproc_sms_wait_' . $phone);
  3131. $this->error($e->getMessage());
  3132. }
  3133. $this->success('验证码已发送');
  3134. }
  3135. /**
  3136. * 验证码登录(POST:phone、code)
  3137. */
  3138. public function doLogin()
  3139. {
  3140. if (!$this->request->isPost()) {
  3141. $this->error('请使用 POST');
  3142. }
  3143. $phone = trim((string)$this->request->post('phone', ''));
  3144. $code = trim((string)$this->request->post('code', ''));
  3145. if (!preg_match('/^1\d{10}$/', $phone)) {
  3146. $this->error('手机号格式不正确');
  3147. }
  3148. if (!preg_match('/^\d{6}$/', $code)) {
  3149. $this->error('请输入6位验证码');
  3150. }
  3151. // 本地调试:application/extra/mproc.php 中配置 mock_sms_code 与输入一致时,不校验短信缓存(生产务必留空)
  3152. $mock = Config::get('mproc.mock_sms_code');
  3153. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3154. Cache::rm('mproc_code_' . $phone);
  3155. } else {
  3156. $cached = Cache::get('mproc_code_' . $phone);
  3157. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3158. $this->error('验证码错误或已过期');
  3159. }
  3160. Cache::rm('mproc_code_' . $phone);
  3161. }
  3162. $cu = $this->mprocFindCustomerUserByMobile($phone);
  3163. if ($cu) {
  3164. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'sms'));
  3165. return;
  3166. }
  3167. $adminRow = $this->mprocAdminRowByMobile($phone);
  3168. if ($adminRow) {
  3169. $payload = $this->mprocLoginPayloadFromAdmin($adminRow, 'sms');
  3170. if (!$this->mprocAdminHasAnyMobileAccess($payload)) {
  3171. $this->error('账号或密码错误');
  3172. }
  3173. $this->mprocFinishLogin($payload);
  3174. return;
  3175. }
  3176. $this->error('账号或密码错误');
  3177. }
  3178. /**
  3179. * 用本地保存的 token 恢复登录态(POST:mproc_token)
  3180. */
  3181. public function mprocRestore()
  3182. {
  3183. if (!$this->request->isPost()) {
  3184. $this->error('请使用 POST');
  3185. }
  3186. $token = $this->mprocReadTokenFromRequest();
  3187. $user = null;
  3188. if ($token !== '') {
  3189. $user = $this->mprocLoadUserByToken($token);
  3190. }
  3191. if (!$user) {
  3192. $user = $this->mprocUserFromRememberCookie();
  3193. if ($user) {
  3194. $token = $this->mprocPackSignedAuthToken($user);
  3195. }
  3196. }
  3197. if (!$user) {
  3198. $this->error('登录已过期,请重新登录', url('index/index/login'));
  3199. }
  3200. $token = $this->mprocTouchLoginState($user, $token !== '' ? $token : $this->mprocPackSignedAuthToken($user));
  3201. $redirect = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  3202. $jump = $this->mprocBuildAfterLoginHomeUrl($user, $redirect);
  3203. if ($jump === '') {
  3204. $this->mprocClearLogin($token);
  3205. $this->error('账号或密码错误', url('index/index/login'));
  3206. }
  3207. $this->success('ok', $jump, [
  3208. 'mproc_token' => $token,
  3209. 'keep_hours' => $this->mprocKeepHours(),
  3210. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  3211. ]);
  3212. }
  3213. /**
  3214. * 账号密码登录(POST:username、password)
  3215. * 先 customer(account),未命中再 admin;admin 密码规则同 FastAdmin Auth::login
  3216. */
  3217. public function doLoginPwd()
  3218. {
  3219. if (!$this->request->isPost()) {
  3220. $this->error('请使用 POST');
  3221. }
  3222. $username = trim((string)$this->request->post('username', ''));
  3223. $password = (string)$this->request->post('password', '');
  3224. if ($username === '' || $password === '') {
  3225. $this->error('请输入账号和密码');
  3226. }
  3227. $cu = $this->mprocFindCustomerUserByUsername($username);
  3228. if ($cu) {
  3229. if (!$this->mprocVerifyCustomerUserPassword($cu, $password)) {
  3230. $this->error('账号或密码错误');
  3231. }
  3232. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'pwd'));
  3233. }
  3234. // 管理员:表 admin
  3235. $row = null;
  3236. try {
  3237. $row = Db::name('admin')
  3238. ->field('id,username,password,salt,status,loginfailure,updatetime,mobile')
  3239. ->where('username', $username)
  3240. ->find();
  3241. } catch (\Throwable $e) {
  3242. $row = null;
  3243. }
  3244. if (!$row || !is_array($row)) {
  3245. $this->error('账号或密码错误');
  3246. }
  3247. $id = (int)($row['id'] ?? 0);
  3248. if (($row['status'] ?? '') == 'hidden') {
  3249. $this->error('该账号已禁用');
  3250. }
  3251. if (Config::get('fastadmin.login_failure_retry') && (int)($row['loginfailure'] ?? 0) >= 10 && time() - (int)($row['updatetime'] ?? 0) < 86400) {
  3252. $this->error('登录失败次数过多,请24小时后再试');
  3253. }
  3254. $salt = (string)($row['salt'] ?? '');
  3255. $hashStored = (string)($row['password'] ?? '');
  3256. $hashInput = md5(md5($password) . $salt);
  3257. if ($hashStored === '' || $hashInput !== $hashStored) {
  3258. if ($id > 0) {
  3259. try {
  3260. Db::name('admin')->where('id', $id)->update([
  3261. 'loginfailure' => (int)($row['loginfailure'] ?? 0) + 1,
  3262. 'updatetime' => time(),
  3263. ]);
  3264. } catch (\Throwable $e) {
  3265. }
  3266. }
  3267. $this->error('账号或密码错误');
  3268. }
  3269. if ($id > 0) {
  3270. try {
  3271. Db::name('admin')->where('id', $id)->update([
  3272. 'loginfailure' => 0,
  3273. 'updatetime' => time(),
  3274. ]);
  3275. } catch (\Throwable $e) {
  3276. }
  3277. }
  3278. $payload = $this->mprocLoginPayloadFromAdmin($row, 'pwd');
  3279. if (!$this->mprocAdminHasAnyMobileAccess($payload)) {
  3280. $this->error('账号或密码错误');
  3281. }
  3282. $this->mprocFinishLogin($payload);
  3283. }
  3284. /**
  3285. * 是否允许当前登录用户修改该条 purchase_order_detail 的金额、交期
  3286. * 仅普通用户(customer)可改;管理员(admin)仅可查看
  3287. */
  3288. protected function mprocCanEditRow(array $user, array $row, ?array $po = null)
  3289. {
  3290. if (!empty($user['is_admin'])) {
  3291. return false;
  3292. }
  3293. $sn = trim((string)($row['status_name'] ?? ''));
  3294. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  3295. return false;
  3296. }
  3297. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3298. // 手工询价无招标截止/开标限制
  3299. if ($sid >= 0) {
  3300. if ($this->mprocIsQuoteDeadlineReachedForPo($po)) {
  3301. return false;
  3302. }
  3303. if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)) {
  3304. return false;
  3305. }
  3306. }
  3307. $uCo = trim((string)($user['company_name'] ?? ''));
  3308. if ($uCo === '') {
  3309. $uPhone = trim((string)($user['phone'] ?? ''));
  3310. if ($uPhone !== '') {
  3311. $uCo = $this->mprocResolveCompanyForLoginPhone($uPhone);
  3312. }
  3313. }
  3314. $rCo = trim((string)($row['company_name'] ?? ''));
  3315. if ($uCo !== '' && $rCo !== '' && strcmp($rCo, $uCo) === 0) {
  3316. return true;
  3317. }
  3318. $uPhone = trim((string)($user['phone'] ?? ''));
  3319. $rPhone = trim((string)($row['phone'] ?? ''));
  3320. return $uPhone !== '' && $rPhone !== '' && strcasecmp($rPhone, $uPhone) === 0;
  3321. }
  3322. /**
  3323. * 明细行对应最高限价(来自 purchase_order;无或无效则返回 null,不校验)
  3324. *
  3325. * @param array<string, mixed> $detailRow
  3326. */
  3327. protected function mprocResolveCeilingPriceForDetailRow(array $detailRow): ?float
  3328. {
  3329. $sid = (int)($detailRow['scydgy_id'] ?? $detailRow['SCYDGY_ID'] ?? 0);
  3330. $raw = trim((string)($detailRow['ceilingPrice'] ?? $detailRow['ceiling_price'] ?? ''));
  3331. if ($raw === '' && $this->mprocIsValidScydgyRowId($sid)) {
  3332. try {
  3333. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3334. } catch (\Throwable $e) {
  3335. $po = null;
  3336. }
  3337. if (is_array($po)) {
  3338. $pl = array_change_key_case($po, CASE_LOWER);
  3339. foreach (['ceilingprice', 'ceiling_price'] as $ck) {
  3340. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  3341. $raw = trim((string)$pl[$ck]);
  3342. break;
  3343. }
  3344. }
  3345. if ($raw === '') {
  3346. $raw = trim((string)($po['ceilingPrice'] ?? $po['ceiling_price'] ?? ''));
  3347. }
  3348. }
  3349. }
  3350. if ($raw === '' || !preg_match('/^-?\d+(\.\d{1,5})?$/', $raw)) {
  3351. return null;
  3352. }
  3353. return (float)$raw;
  3354. }
  3355. protected function mprocFormatCeilingPriceDisplay(float $n): string
  3356. {
  3357. $s = rtrim(rtrim(sprintf('%.5F', $n), '0'), '.');
  3358. return $s === '' ? '0' : $s;
  3359. }
  3360. /**
  3361. * 确保 purchase_order_detail.lead_days 字段存在
  3362. */
  3363. protected function mprocEnsureLeadDaysColumn(): void
  3364. {
  3365. static $done = false;
  3366. if ($done) {
  3367. return;
  3368. }
  3369. $done = true;
  3370. try {
  3371. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_detail` LIKE 'lead_days'");
  3372. if (empty($cols)) {
  3373. Db::execute(
  3374. "ALTER TABLE `purchase_order_detail` ADD COLUMN `lead_days` int(10) unsigned DEFAULT NULL COMMENT '预估工期(天)' AFTER `delivery`"
  3375. );
  3376. }
  3377. } catch (\Throwable $e) {
  3378. // 忽略:保存时再按列是否存在处理
  3379. }
  3380. }
  3381. /**
  3382. * 交货日期相对今天的天数(可负数,调用方自行 clamp)
  3383. */
  3384. protected function mprocCalcLeadDaysFromDeliveryYmd(string $ymd): ?int
  3385. {
  3386. if (!preg_match('/^(\d{4}-\d{2}-\d{2})/', $ymd, $m)) {
  3387. return null;
  3388. }
  3389. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  3390. $t2 = strtotime($m[1] . ' 00:00:00');
  3391. if ($t1 === false || $t2 === false) {
  3392. return null;
  3393. }
  3394. return (int)round(($t2 - $t1) / 86400);
  3395. }
  3396. protected function mprocAddDaysToToday(int $days): string
  3397. {
  3398. $base = strtotime(date('Y-m-d') . ' 00:00:00');
  3399. if ($base === false) {
  3400. $base = time();
  3401. }
  3402. return date('Y-m-d', strtotime('+' . max(0, $days) . ' days', $base));
  3403. }
  3404. /**
  3405. * @param array<string, mixed> $row
  3406. */
  3407. protected function mprocEnrichLeadDaysDisplay(array &$row): void
  3408. {
  3409. $days = null;
  3410. $raw = $row['lead_days'] ?? null;
  3411. if ($raw !== null && $raw !== '' && is_numeric($raw)) {
  3412. $days = max(0, (int)$raw);
  3413. } else {
  3414. $dd = trim((string)($row['delivery_display'] ?? ''));
  3415. if ($dd === '') {
  3416. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  3417. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  3418. $dd = $m[1];
  3419. }
  3420. }
  3421. if ($dd !== '') {
  3422. $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($dd);
  3423. if ($calc !== null) {
  3424. $days = max(0, $calc);
  3425. }
  3426. }
  3427. }
  3428. if ($days !== null) {
  3429. $row['lead_days'] = $days;
  3430. $row['lead_days_display'] = (string)$days;
  3431. $row['lead_days_missing'] = 0;
  3432. } else {
  3433. $row['lead_days'] = '';
  3434. $row['lead_days_display'] = '';
  3435. $row['lead_days_missing'] = 1;
  3436. }
  3437. }
  3438. /**
  3439. * 保存单条协助明细的金额、交期、工期(内部)
  3440. *
  3441. * @param array<string, mixed> $user
  3442. * @param int $id
  3443. * @param string $amountRaw
  3444. * @param string $deliveryRaw
  3445. * @param string|int|null $leadDaysRaw
  3446. * @return string 工序名(用于批量错误提示)
  3447. */
  3448. protected function mprocSaveDetailQuote(array $user, int $id, string $amountRaw, string $deliveryRaw, $leadDaysRaw = null): string
  3449. {
  3450. if ($id <= 0) {
  3451. throw new \InvalidArgumentException('参数错误');
  3452. }
  3453. $row = null;
  3454. try {
  3455. $row = Db::table('purchase_order_detail')->where('id', $id)->find();
  3456. if (!$row) {
  3457. $row = Db::table('purchase_order_detail')->where('ID', $id)->find();
  3458. }
  3459. } catch (\Throwable $e) {
  3460. $row = null;
  3461. }
  3462. if (!$row || !is_array($row)) {
  3463. throw new \InvalidArgumentException('记录不存在');
  3464. }
  3465. $gymc = trim((string)($row['CGYMC'] ?? $row['cgymc'] ?? ''));
  3466. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3467. $po = null;
  3468. if ($this->mprocIsValidScydgyRowId($sid)) {
  3469. try {
  3470. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3471. } catch (\Throwable $e) {
  3472. $po = null;
  3473. }
  3474. if (is_array($po)) {
  3475. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  3476. if ($gymc === '') {
  3477. $gymc = trim((string)($row['CGYMC'] ?? ''));
  3478. }
  3479. }
  3480. }
  3481. $label = $gymc !== '' ? ('工序「' . $gymc . '」') : ('记录#' . $id);
  3482. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  3483. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  3484. throw new \InvalidArgumentException($label . '已结束,不能再修改');
  3485. }
  3486. $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, $label, $row);
  3487. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  3488. if (!empty($user['is_admin'])) {
  3489. throw new \InvalidArgumentException('当前账号仅可查看,不能修改单价与交货日期');
  3490. }
  3491. // 截止后 / 已开标 canEdit=false,统一给明确文案
  3492. if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
  3493. throw new \InvalidArgumentException($label . '已开标验证,不可再提交');
  3494. }
  3495. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  3496. throw new \InvalidArgumentException($label . '已超过招标截止时间,不可再提交');
  3497. }
  3498. throw new \InvalidArgumentException($label . '无权修改');
  3499. }
  3500. $this->mprocEnsureLeadDaysColumn();
  3501. $amountRaw = trim($amountRaw);
  3502. $deliveryRaw = trim($deliveryRaw);
  3503. $leadRaw = trim((string)($leadDaysRaw ?? ''));
  3504. $hasAmt = $amountRaw !== '';
  3505. $hasLead = $leadRaw !== '';
  3506. $hasDel = $deliveryRaw !== '';
  3507. $isManualRfq = ($sid < 0);
  3508. if ($isManualRfq) {
  3509. // 手工询价:只需填写单价
  3510. if (!$hasAmt) {
  3511. throw new \InvalidArgumentException($label . '请填写单价');
  3512. }
  3513. } else {
  3514. $filledCount = ($hasAmt ? 1 : 0) + ($hasLead ? 1 : 0) + ($hasDel ? 1 : 0);
  3515. if ($filledCount === 0) {
  3516. throw new \InvalidArgumentException($label . '请填写单价、工期、交期');
  3517. }
  3518. if ($filledCount < 3) {
  3519. if (!$hasAmt) {
  3520. throw new \InvalidArgumentException($label . '请填写单价');
  3521. }
  3522. if (!$hasLead) {
  3523. throw new \InvalidArgumentException($label . '请填写工期');
  3524. }
  3525. throw new \InvalidArgumentException($label . '请填写交期');
  3526. }
  3527. }
  3528. $leadDays = null;
  3529. if ($leadRaw !== '') {
  3530. if (!preg_match('/^\d+$/', $leadRaw)) {
  3531. throw new \InvalidArgumentException($label . '工期须为非负整数(天)');
  3532. }
  3533. $leadDays = (int)$leadRaw;
  3534. }
  3535. $data = [];
  3536. if ($amountRaw === '') {
  3537. $data['amount'] = null;
  3538. } else {
  3539. if (!preg_match('/^\d+(\.\d{1,5})?$/', $amountRaw)) {
  3540. throw new \InvalidArgumentException($label . '单价格式不正确,最多五位小数');
  3541. }
  3542. if ((float)$amountRaw <= 0) {
  3543. throw new \InvalidArgumentException($label . '单价必须大于0');
  3544. }
  3545. $ceilingLimit = $this->mprocResolveCeilingPriceForDetailRow($row);
  3546. if ($ceilingLimit !== null && (float)$amountRaw > $ceilingLimit) {
  3547. throw new \InvalidArgumentException(
  3548. $label . '单价不能超过最高限价 ' . $this->mprocFormatCeilingPriceDisplay($ceilingLimit)
  3549. );
  3550. }
  3551. $data['amount'] = $amountRaw;
  3552. }
  3553. if ($deliveryRaw === '') {
  3554. $data['delivery'] = null;
  3555. } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryRaw)) {
  3556. $existingDel = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  3557. $timePart = date('H:i:s');
  3558. if ($existingDel !== '') {
  3559. $tsEx = strtotime(str_replace('T', ' ', $existingDel));
  3560. if ($tsEx !== false) {
  3561. $hms = date('H:i:s', $tsEx);
  3562. if ($hms !== '00:00:00') {
  3563. $timePart = $hms;
  3564. }
  3565. }
  3566. }
  3567. $data['delivery'] = $deliveryRaw . ' ' . $timePart;
  3568. } else {
  3569. $deliveryRaw = str_replace('T', ' ', $deliveryRaw);
  3570. $ts = strtotime($deliveryRaw);
  3571. if ($ts === false) {
  3572. throw new \InvalidArgumentException($label . '交期时间格式不正确');
  3573. }
  3574. $data['delivery'] = date('Y-m-d H:i:s', $ts);
  3575. }
  3576. // 工期 ↔ 交货日期互通:仅填工期则推交期;仅填交期则推工期
  3577. if (($data['delivery'] === null || $data['delivery'] === '') && $leadDays !== null) {
  3578. $data['delivery'] = $this->mprocAddDaysToToday($leadDays) . ' ' . date('H:i:s');
  3579. }
  3580. if ($leadDays === null && !empty($data['delivery'])) {
  3581. $ymd = substr((string)$data['delivery'], 0, 10);
  3582. $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($ymd);
  3583. if ($calc !== null) {
  3584. $leadDays = max(0, $calc);
  3585. }
  3586. }
  3587. $data['lead_days'] = $leadDays;
  3588. $dcCol = $this->mprocResolveProcuremenColumn(['delivery_createtime', 'deliverycreatetime']);
  3589. if ($dcCol !== null) {
  3590. $shouldStampQuoteTime = false;
  3591. if (array_key_exists('delivery', $data) && $data['delivery'] !== null && $data['delivery'] !== '') {
  3592. $shouldStampQuoteTime = true;
  3593. }
  3594. // 手工询价只填单价:有单价也记报价时间
  3595. if ($isManualRfq && array_key_exists('amount', $data) && $data['amount'] !== null && $data['amount'] !== '') {
  3596. $shouldStampQuoteTime = true;
  3597. }
  3598. if ($shouldStampQuoteTime) {
  3599. $data[$dcCol] = date('Y-m-d H:i:s');
  3600. }
  3601. }
  3602. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3603. if ($upCol !== null) {
  3604. $data[$upCol] = date('Y-m-d H:i:s');
  3605. }
  3606. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  3607. if ($statusNameCol !== null) {
  3608. $curSn = '';
  3609. foreach ($row as $k => $v) {
  3610. if (strcasecmp((string)$k, $statusNameCol) === 0) {
  3611. $curSn = trim((string)$v);
  3612. break;
  3613. }
  3614. }
  3615. if ($curSn !== '已完成') {
  3616. $effAm = array_key_exists('amount', $data) ? $data['amount'] : ($row['amount'] ?? null);
  3617. $effDv = array_key_exists('delivery', $data) ? trim((string)$data['delivery']) : trim((string)($row['delivery'] ?? ''));
  3618. $amountFilled = !($effAm === null || $effAm === '' || (is_string($effAm) && trim($effAm) === ''));
  3619. $deliveryFilled = ($effDv !== '' && !preg_match('/^0000-00-00/i', $effDv));
  3620. $data[$statusNameCol] = ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3621. }
  3622. }
  3623. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  3624. $pkVal = (int)($row[$pkField] ?? $id);
  3625. try {
  3626. $aff = Db::table('purchase_order_detail')->where($pkField, $pkVal)->update($data);
  3627. } catch (\Throwable $e) {
  3628. $msg = $e->getMessage();
  3629. if (stripos($msg, 'Unknown column') !== false) {
  3630. $msg = '请确认数据表 purchase_order_detail 已包含 amount、delivery、lead_days 字段';
  3631. }
  3632. throw new \RuntimeException('保存失败:' . $msg);
  3633. }
  3634. if ($aff === false) {
  3635. throw new \RuntimeException($label . '保存失败');
  3636. }
  3637. return $gymc;
  3638. }
  3639. /**
  3640. * 保存同订单号+供应商下的整单备注(写入该组全部明细行)
  3641. *
  3642. * @param array<string, mixed> $user
  3643. * @param int[] $detailIds 本次保存涉及的明细 ID
  3644. * @param string $remarkRaw
  3645. */
  3646. protected function mprocSaveOrderGroupRemark(array $user, array $detailIds, string $remarkRaw): void
  3647. {
  3648. $remarkCol = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
  3649. if ($remarkCol === null) {
  3650. return;
  3651. }
  3652. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3653. if ($detailIds === []) {
  3654. return;
  3655. }
  3656. $anchorId = $detailIds[0];
  3657. $row = null;
  3658. try {
  3659. $row = Db::table('purchase_order_detail')->where('id', $anchorId)->find();
  3660. if (!$row) {
  3661. $row = Db::table('purchase_order_detail')->where('ID', $anchorId)->find();
  3662. }
  3663. } catch (\Throwable $e) {
  3664. $row = null;
  3665. }
  3666. if (!$row || !is_array($row)) {
  3667. throw new \InvalidArgumentException('记录不存在');
  3668. }
  3669. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3670. $po = null;
  3671. if ($this->mprocIsValidScydgyRowId($sid)) {
  3672. try {
  3673. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3674. } catch (\Throwable $e) {
  3675. $po = null;
  3676. }
  3677. if (is_array($po)) {
  3678. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  3679. }
  3680. }
  3681. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  3682. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  3683. throw new \InvalidArgumentException('订单已结束,不能再修改备注');
  3684. }
  3685. $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, '', $row);
  3686. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  3687. if (!empty($user['is_admin'])) {
  3688. throw new \InvalidArgumentException('当前账号仅可查看,不能修改备注');
  3689. }
  3690. if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
  3691. throw new \InvalidArgumentException('已开标验证,不可再提交');
  3692. }
  3693. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  3694. throw new \InvalidArgumentException('已超过招标截止时间,不可再提交');
  3695. }
  3696. throw new \InvalidArgumentException('无权修改备注');
  3697. }
  3698. $orderMbz = '';
  3699. if (is_array($po)) {
  3700. $orderMbz = trim((string)($po['MBZ'] ?? $po['mbz'] ?? ''));
  3701. }
  3702. $remarkRaw = $this->mprocSupplierOwnRemark($remarkRaw, $orderMbz);
  3703. $ccydhCol = $this->mprocResolveProcuremenColumn(['ccydh']);
  3704. $companyCol = $this->mprocResolveProcuremenColumn(['company_name']);
  3705. if ($ccydhCol === null || $companyCol === null) {
  3706. return;
  3707. }
  3708. $ccydh = '';
  3709. $company = '';
  3710. foreach ($row as $k => $v) {
  3711. if (strcasecmp((string)$k, $ccydhCol) === 0) {
  3712. $ccydh = trim((string)$v);
  3713. } elseif (strcasecmp((string)$k, $companyCol) === 0) {
  3714. $company = trim((string)$v);
  3715. }
  3716. }
  3717. if ($ccydh === '' || $company === '') {
  3718. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  3719. $data = [$remarkCol => ($remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8'))];
  3720. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3721. if ($upCol !== null) {
  3722. $data[$upCol] = date('Y-m-d H:i:s');
  3723. }
  3724. Db::table('purchase_order_detail')->where($pkField, (int)($row[$pkField] ?? $anchorId))->update($data);
  3725. return;
  3726. }
  3727. $remarkVal = $remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8');
  3728. $data = [$remarkCol => $remarkVal];
  3729. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3730. if ($upCol !== null) {
  3731. $data[$upCol] = date('Y-m-d H:i:s');
  3732. }
  3733. $query = Db::table('purchase_order_detail')
  3734. ->where($ccydhCol, $ccydh)
  3735. ->where($companyCol, $company);
  3736. $userWhere = $this->mprocListWhereForLoginUser($user);
  3737. if ($userWhere !== []) {
  3738. $query->where($userWhere);
  3739. }
  3740. try {
  3741. $query->update($data);
  3742. } catch (\Throwable $e) {
  3743. throw new \RuntimeException('备注保存失败:' . $e->getMessage());
  3744. }
  3745. }
  3746. /**
  3747. * 保存协助明细金额、交期、工期
  3748. * 单条:POST id、amount、delivery、lead_days
  3749. * 批量:POST items=[{id,amount,delivery,lead_days},...] JSON
  3750. */
  3751. public function mprocSave()
  3752. {
  3753. if (!$this->request->isPost()) {
  3754. $this->error('请使用 POST');
  3755. }
  3756. $user = $this->mprocGetUser();
  3757. if (!$user) {
  3758. $this->error('请先登录', url('index/index/login'));
  3759. }
  3760. // Frontend 默认 filter 含 htmlspecialchars,会把 JSON 的双引号变成 &quot; 导致解析失败
  3761. $itemsRaw = $this->request->post('items', '', null);
  3762. if ($itemsRaw === '' || $itemsRaw === null) {
  3763. $itemsRaw = isset($_POST['items']) ? $_POST['items'] : '';
  3764. }
  3765. if (is_string($itemsRaw) && $itemsRaw !== '' && strpos($itemsRaw, '&quot;') !== false) {
  3766. $itemsRaw = htmlspecialchars_decode($itemsRaw, ENT_QUOTES);
  3767. }
  3768. $items = [];
  3769. if (is_string($itemsRaw) && trim($itemsRaw) !== '') {
  3770. $decoded = json_decode($itemsRaw, true);
  3771. if (!is_array($decoded)) {
  3772. $decoded = json_decode(htmlspecialchars_decode($itemsRaw, ENT_QUOTES), true);
  3773. }
  3774. if (is_array($decoded)) {
  3775. $items = $decoded;
  3776. }
  3777. } elseif (is_array($itemsRaw)) {
  3778. $items = $itemsRaw;
  3779. }
  3780. if ($items === []) {
  3781. $id = (int)$this->request->post('id', 0, null);
  3782. if ($id <= 0) {
  3783. $this->error('保存失败,请关闭弹窗后重试');
  3784. }
  3785. $items = [[
  3786. 'id' => $id,
  3787. 'amount' => (string)$this->request->post('amount', '', null),
  3788. 'delivery' => (string)$this->request->post('delivery', '', null),
  3789. 'lead_days' => (string)$this->request->post('lead_days', '', null),
  3790. ]];
  3791. }
  3792. $saved = 0;
  3793. $savedIds = [];
  3794. $remarkRaw = $this->request->post('remark', '', null);
  3795. if ($remarkRaw === '' || $remarkRaw === null) {
  3796. $remarkRaw = isset($_POST['remark']) ? $_POST['remark'] : '';
  3797. }
  3798. $remarkRaw = trim(htmlspecialchars_decode((string)$remarkRaw, ENT_QUOTES));
  3799. Db::startTrans();
  3800. try {
  3801. foreach ($items as $it) {
  3802. if (!is_array($it)) {
  3803. continue;
  3804. }
  3805. $id = (int)($it['id'] ?? $it['eid'] ?? 0);
  3806. if ($id <= 0) {
  3807. continue;
  3808. }
  3809. $delivery = (string)($it['delivery'] ?? '');
  3810. // 兼容部分手机浏览器把日期显示/提交成 2026/07/24
  3811. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})$/', trim($delivery), $dm)) {
  3812. $delivery = sprintf('%04d-%02d-%02d', (int)$dm[1], (int)$dm[2], (int)$dm[3]);
  3813. }
  3814. $leadDays = (string)($it['lead_days'] ?? $it['leadDays'] ?? '');
  3815. $amount = trim((string)($it['amount'] ?? ''));
  3816. $leadDays = trim($leadDays);
  3817. $delivery = trim($delivery);
  3818. // 全空工序跳过:多工序时允许只保存已填全的
  3819. if ($amount === '' && $leadDays === '' && $delivery === '') {
  3820. continue;
  3821. }
  3822. $this->mprocSaveDetailQuote(
  3823. $user,
  3824. $id,
  3825. $amount,
  3826. $delivery,
  3827. $leadDays
  3828. );
  3829. $saved++;
  3830. $savedIds[] = $id;
  3831. }
  3832. if ($saved < 1) {
  3833. throw new \InvalidArgumentException('请填写单价、工期、交期');
  3834. }
  3835. $this->mprocSaveOrderGroupRemark($user, $savedIds, $remarkRaw);
  3836. Db::commit();
  3837. } catch (\InvalidArgumentException $e) {
  3838. Db::rollback();
  3839. $this->error($e->getMessage());
  3840. } catch (\Throwable $e) {
  3841. Db::rollback();
  3842. $this->error($e->getMessage());
  3843. }
  3844. $this->success($saved > 1 ? ('已保存 ' . $saved . ' 道工序') : '已保存');
  3845. }
  3846. /**
  3847. * 修改密码(POST:old_password、new_password、renew_password)
  3848. * 支持供应商 customer 与手机端管理员 admin
  3849. */
  3850. public function mprocChangePwd()
  3851. {
  3852. if (!$this->request->isPost()) {
  3853. $this->error('请使用 POST');
  3854. }
  3855. $user = $this->mprocGetUser();
  3856. if (!$user) {
  3857. $this->error('请先登录', url('index/index/login'));
  3858. }
  3859. $oldPwd = (string)$this->request->post('old_password', '');
  3860. $newPwd = (string)$this->request->post('new_password', '');
  3861. $renewPwd = (string)$this->request->post('renew_password', '');
  3862. if ($oldPwd === '' || $newPwd === '' || $renewPwd === '') {
  3863. $this->error('请填写完整');
  3864. }
  3865. $pwdErr = $this->mprocValidateStrongPassword($newPwd);
  3866. if ($pwdErr !== '') {
  3867. $this->error($pwdErr);
  3868. }
  3869. if ($newPwd !== $renewPwd) {
  3870. $this->error('两次输入的新密码不一致');
  3871. }
  3872. if ($oldPwd === $newPwd) {
  3873. $this->error('新密码不能与旧密码相同');
  3874. }
  3875. if (!empty($user['is_admin'])) {
  3876. $adminId = (int)($user['admin_id'] ?? 0);
  3877. if ($adminId <= 0) {
  3878. $this->error('账号不存在或已禁用');
  3879. }
  3880. $row = null;
  3881. try {
  3882. $row = Db::name('admin')
  3883. ->field('id,username,password,salt,status')
  3884. ->where('id', $adminId)
  3885. ->find();
  3886. } catch (\Throwable $e) {
  3887. $row = null;
  3888. }
  3889. if (!$row || !is_array($row) || (($row['status'] ?? '') === 'hidden')) {
  3890. $this->error('账号不存在或已禁用');
  3891. }
  3892. $salt = (string)($row['salt'] ?? '');
  3893. $hashStored = (string)($row['password'] ?? '');
  3894. $hashOld = md5(md5($oldPwd) . $salt);
  3895. if ($hashStored === '' || $hashOld !== $hashStored) {
  3896. $this->error('原密码不正确');
  3897. }
  3898. $hashNew = md5(md5($newPwd) . $salt);
  3899. try {
  3900. Db::name('admin')->where('id', $adminId)->update([
  3901. 'password' => $hashNew,
  3902. 'updatetime' => time(),
  3903. ]);
  3904. } catch (\Throwable $e) {
  3905. $this->error('修改失败:' . $e->getMessage());
  3906. }
  3907. } else {
  3908. $user = $this->mprocSyncSessionCustomerUser($user);
  3909. $cu = $this->mprocResolveCustomerUserForSession($user);
  3910. if (!$cu) {
  3911. $this->error('账号不存在或已禁用');
  3912. }
  3913. $cuId = (int)($cu['id'] ?? 0);
  3914. if (!$this->mprocVerifyCustomerUserPassword($cu, $oldPwd)) {
  3915. $this->error('原密码不正确');
  3916. }
  3917. $data = [
  3918. 'password' => $this->mprocHashCustomerUserPassword($newPwd),
  3919. 'updatetime' => date('Y-m-d H:i:s'),
  3920. ];
  3921. try {
  3922. Db::table('customer')->where('id', $cuId)->update($data);
  3923. } catch (\Throwable $e) {
  3924. $this->error('修改失败:' . $e->getMessage());
  3925. }
  3926. }
  3927. // 改密后强制重新登录
  3928. $token = Session::get('mproc_token');
  3929. if ($token === null || $token === '') {
  3930. $token = Cookie::get('mproc_token');
  3931. }
  3932. if ($token === null || $token === '') {
  3933. $token = Cookie::get('mproc_remember');
  3934. }
  3935. $this->mprocClearLogin((string)$token);
  3936. $this->success('密码已修改,请重新登录', url('index/index/login'));
  3937. }
  3938. /**
  3939. * 退出登录
  3940. */
  3941. public function logout()
  3942. {
  3943. $token = Session::get('mproc_token');
  3944. if ($token === null || $token === '') {
  3945. $token = Cookie::get('mproc_token');
  3946. }
  3947. if ($token === null || $token === '') {
  3948. $token = Cookie::get('mproc_remember');
  3949. }
  3950. // 无论有无 token 都清 Cookie/Session,避免「记住登录」把用户又带回来
  3951. $this->mprocClearLogin((string)$token);
  3952. $this->redirect(url('index/index/login'));
  3953. }
  3954. /**
  3955. * 短信宝(与后台协助审核一致,便于复用账号)
  3956. *
  3957. * @throws \Exception
  3958. */
  3959. protected function mprocSmsSend($phone, $content)
  3960. {
  3961. $statusStr = [
  3962. '0' => '短信发送成功',
  3963. '-1' => '参数不全',
  3964. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  3965. '30' => '密码错误',
  3966. '40' => '账号不存在',
  3967. '41' => '余额不足',
  3968. '42' => '帐户已过期',
  3969. '43' => 'IP地址限制',
  3970. '50' => '内容含有敏感词',
  3971. ];
  3972. $smsapi = 'http://api.smsbao.com/';
  3973. $user = trim((string)Config::get('mproc.smsbao_user'));
  3974. if ($user === '') {
  3975. $user = 'zhuwei123';
  3976. }
  3977. $passPlain = Config::get('mproc.smsbao_pass');
  3978. $pass = ($passPlain !== null && $passPlain !== '')
  3979. ? md5((string)$passPlain)
  3980. : md5('1d1e605c101e4c1f8a156c6d7b19f126');
  3981. $phone = trim((string)$phone);
  3982. $content = trim((string)$content);
  3983. if ($phone === '' || $content === '') {
  3984. throw new \Exception('短信发送失败:参数不全');
  3985. }
  3986. $sendurl = $smsapi . 'sms?u=' . rawurlencode($user) . '&p=' . $pass . '&m=' . rawurlencode($phone) . '&c=' . rawurlencode($content);
  3987. $result = @file_get_contents($sendurl);
  3988. if ($result === false) {
  3989. Log::record('smsbao 请求失败 phone=' . $phone . ' content=' . $content, 'error');
  3990. throw new \Exception('短信发送失败:网络异常');
  3991. }
  3992. $result = trim((string)$result);
  3993. if ($result !== '0') {
  3994. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  3995. Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg . ' content=' . $content, 'error');
  3996. throw new \Exception('短信发送失败:' . $msg);
  3997. }
  3998. Log::record('smsbao 发送成功 phone=' . $phone . ' content=' . $content, 'info');
  3999. }
  4000. /**
  4001. * 质量评分页(质检中心:合格/投诉/中断)
  4002. */
  4003. public function inboundscore()
  4004. {
  4005. $user = $this->mprocGetUser();
  4006. if (!$user) {
  4007. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  4008. $safe = $this->mprocSanitizeRedirectUrl($uri);
  4009. if ($safe !== '') {
  4010. Session::set('mproc_intended_url', $safe);
  4011. }
  4012. $this->redirect($this->mprocBuildLoginUrl($safe));
  4013. return;
  4014. }
  4015. if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'quality')) {
  4016. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  4017. if ($jump === '') {
  4018. $this->mprocDropCurrentLogin();
  4019. $this->redirect(url('index/index/login'));
  4020. return;
  4021. }
  4022. $this->redirect($jump);
  4023. return;
  4024. }
  4025. $this->mprocEnsureInboundScoreTable();
  4026. $q = trim((string)$this->request->get('q', ''));
  4027. $profile = $this->mprocProfileForUser($user);
  4028. $this->view->assign('mprocSearchQ', $q);
  4029. $this->view->assign('mprocProfile', $profile);
  4030. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  4031. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  4032. $this->view->assign('mprocScoreScope', 'quality');
  4033. $this->view->assign('rows', $this->mprocLoadInboundScoreRows('pending', $q, (int)($user['admin_id'] ?? 0), 'quality'));
  4034. return $this->view->fetch();
  4035. }
  4036. /**
  4037. * 交货情况页(生产部:准时/滞后)
  4038. */
  4039. public function deliveryscore()
  4040. {
  4041. $user = $this->mprocGetUser();
  4042. if (!$user) {
  4043. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  4044. $safe = $this->mprocSanitizeRedirectUrl($uri);
  4045. if ($safe !== '') {
  4046. Session::set('mproc_intended_url', $safe);
  4047. }
  4048. $this->redirect($this->mprocBuildLoginUrl($safe));
  4049. return;
  4050. }
  4051. if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'delivery')) {
  4052. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  4053. if ($jump === '') {
  4054. $this->mprocDropCurrentLogin();
  4055. $this->redirect(url('index/index/login'));
  4056. return;
  4057. }
  4058. $this->redirect($jump);
  4059. return;
  4060. }
  4061. $this->mprocEnsureInboundScoreTable();
  4062. $ccydh = trim((string)$this->request->get('ccydh', ''));
  4063. $q = trim((string)$this->request->get('q', ''));
  4064. if ($q === '' && $ccydh !== '') {
  4065. $q = $ccydh;
  4066. }
  4067. if ($ccydh === '' && $q !== '') {
  4068. $ccydh = $q;
  4069. }
  4070. $adminId = (int)($user['admin_id'] ?? 0);
  4071. $scoreTab = trim((string)$this->request->get('tab', ''));
  4072. if (!in_array($scoreTab, ['pending', 'scored'], true)) {
  4073. $scoreTab = 'pending';
  4074. }
  4075. $rows = $this->mprocLoadInboundScoreRows($scoreTab, $q, $adminId, 'delivery');
  4076. if ($ccydh !== '' && $rows === [] && $scoreTab === 'pending') {
  4077. $scored = $this->mprocLoadInboundScoreRows('scored', $q, $adminId, 'delivery');
  4078. if ($scored !== []) {
  4079. $scoreTab = 'scored';
  4080. $rows = $scored;
  4081. }
  4082. }
  4083. $profile = $this->mprocProfileForUser($user);
  4084. $this->view->assign('mprocSearchQ', $q);
  4085. $this->view->assign('mprocFocusCcydh', $ccydh);
  4086. $this->view->assign('mprocScoreTab', $scoreTab);
  4087. $this->view->assign('mprocProfile', $profile);
  4088. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  4089. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  4090. $this->view->assign('mprocScoreScope', 'delivery');
  4091. $this->view->assign('rows', $rows);
  4092. return $this->view->fetch();
  4093. }
  4094. /**
  4095. * 供应商送货单(中标后出示二维码,生产部扫码进入交货评估)
  4096. */
  4097. public function deliverynote()
  4098. {
  4099. $user = $this->mprocGetUser();
  4100. if (!$user) {
  4101. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  4102. $safe = $this->mprocSanitizeRedirectUrl($uri);
  4103. if ($safe !== '') {
  4104. Session::set('mproc_intended_url', $safe);
  4105. }
  4106. $this->redirect($this->mprocBuildLoginUrl($safe));
  4107. return;
  4108. }
  4109. if (!empty($user['is_admin'])) {
  4110. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  4111. if ($jump === '') {
  4112. $this->mprocDropCurrentLogin();
  4113. $this->redirect(url('index/index/login'));
  4114. return;
  4115. }
  4116. $this->redirect($jump);
  4117. return;
  4118. }
  4119. $user = $this->mprocSyncSessionCustomerUser($user);
  4120. $ccydh = trim((string)$this->request->param('ccydh', ''));
  4121. $checkOnly = (int)$this->request->param('check', 0) === 1;
  4122. $note = $this->mprocLoadWonDeliveryNote($user, $ccydh);
  4123. if ($note === null) {
  4124. // 列表点「送货码」先 Ajax check:当前页 Toast;直达链接仍走轻提示页
  4125. $this->error('未找到该中标订单的送货单', $checkOnly ? null : url('index/index/index', ['tab' => 'done']));
  4126. return;
  4127. }
  4128. if ($checkOnly) {
  4129. $this->success('ok');
  4130. return;
  4131. }
  4132. $this->view->assign('note', $note);
  4133. return $this->view->fetch();
  4134. }
  4135. /**
  4136. * 当前供应商的中标送货单数据;无权或不存在返回 null
  4137. *
  4138. * @param array<string, mixed> $user
  4139. * @return array<string, mixed>|null
  4140. */
  4141. protected function mprocLoadWonDeliveryNote(array $user, string $ccydh): ?array
  4142. {
  4143. $ccydh = trim($ccydh);
  4144. if ($ccydh === '') {
  4145. return null;
  4146. }
  4147. $company = trim((string)($user['company_name'] ?? ''));
  4148. $phone = trim((string)($user['phone'] ?? ''));
  4149. if ($company === '' && $phone !== '') {
  4150. $company = $this->mprocResolveCompanyForLoginPhone($phone);
  4151. }
  4152. try {
  4153. $poRows = Db::table('purchase_order')
  4154. ->where('CCYDH', $ccydh)
  4155. ->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%\')')
  4156. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CDW,CDF,MBZ,cGzzxMc,CCLBMMC,CDXMC,This_quantity,NGZL,pick_company_name,pick_time,wflow_status,status')
  4157. ->order('id', 'asc')
  4158. ->select();
  4159. } catch (\Throwable $e) {
  4160. $poRows = [];
  4161. }
  4162. if (!is_array($poRows) || $poRows === []) {
  4163. return null;
  4164. }
  4165. $won = false;
  4166. $gymcList = [];
  4167. $qtyList = [];
  4168. foreach ($poRows as $po) {
  4169. if (!is_array($po)) {
  4170. continue;
  4171. }
  4172. $pick = trim((string)($po['pick_company_name'] ?? ''));
  4173. if ($pick !== '' && $company !== '' && $pick === $company) {
  4174. $won = true;
  4175. }
  4176. $gx = trim((string)($po['CGYMC'] ?? ''));
  4177. if ($gx !== '' && !in_array($gx, $gymcList, true)) {
  4178. $gymcList[] = $gx;
  4179. }
  4180. $qDisp = $this->mprocResolveDisplayThisQuantity($po);
  4181. if ($qDisp !== '') {
  4182. $qtyList[] = $qDisp;
  4183. }
  4184. }
  4185. $qtyList = array_values(array_unique($qtyList));
  4186. $orderQty = $qtyList !== [] ? implode('、', $qtyList) : '';
  4187. // 本次送货数量暂无独立数据,留空由页面原样展示
  4188. $deliveryQty = '';
  4189. $detailPhone = '';
  4190. try {
  4191. $dq = Db::table('purchase_order_detail')->where('CCYDH', $ccydh);
  4192. $userWhere = $this->mprocListWhereForLoginUser($user);
  4193. if ($userWhere !== []) {
  4194. $dq->where($userWhere);
  4195. }
  4196. $details = $dq->field('id,scydgy_id,company_name,phone,status,status_name,remark')->select();
  4197. } catch (\Throwable $e) {
  4198. $details = [];
  4199. }
  4200. if (is_array($details)) {
  4201. foreach ($details as $d) {
  4202. if (!is_array($d)) {
  4203. continue;
  4204. }
  4205. if ($detailPhone === '') {
  4206. $detailPhone = trim((string)($d['phone'] ?? ''));
  4207. }
  4208. $dCn = trim((string)($d['company_name'] ?? ''));
  4209. if ($dCn !== '' && $company !== '' && $dCn === $company) {
  4210. if (ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  4211. $won = true;
  4212. }
  4213. }
  4214. }
  4215. }
  4216. if (!$won) {
  4217. return null;
  4218. }
  4219. $pickFirst = static function (array $rows, array $keys): string {
  4220. foreach ($rows as $row) {
  4221. if (!is_array($row)) {
  4222. continue;
  4223. }
  4224. foreach ($keys as $k) {
  4225. $v = trim((string)($row[$k] ?? ''));
  4226. if ($v !== '') {
  4227. return $v;
  4228. }
  4229. }
  4230. }
  4231. return '';
  4232. };
  4233. $profile = $this->mprocProfileForUser($user);
  4234. $supplierName = trim((string)($profile['company_name'] ?? ''));
  4235. if ($supplierName === '') {
  4236. $supplierName = $company;
  4237. }
  4238. if ($supplierName === '') {
  4239. $supplierName = $pickFirst($poRows, ['pick_company_name']);
  4240. }
  4241. $mobile = trim((string)($profile['phone'] ?? ''));
  4242. if ($mobile === '') {
  4243. $mobile = $phone !== '' ? $phone : $detailPhone;
  4244. }
  4245. $contact = trim((string)($profile['contact_name'] ?? ''));
  4246. $customerName = trim((string)Config::get('mproc.delivery_customer_name'));
  4247. if ($customerName === '') {
  4248. $customerName = '浙江新华数码印务有限公司';
  4249. }
  4250. $address = trim((string)Config::get('mproc.delivery_address'));
  4251. if ($address === '') {
  4252. $address = '杭州市经济技术开发区文海北路369号';
  4253. }
  4254. $base = $this->mprocDeliveryScanBaseUrl();
  4255. $scanUrl = $base . $this->mprocDeliveryScanPath() . '?' . http_build_query(
  4256. ['ccydh' => $ccydh, 'q' => $ccydh],
  4257. '',
  4258. '&',
  4259. PHP_QUERY_RFC3986
  4260. );
  4261. return [
  4262. 'generated_at' => $this->mprocDeliveryNoteGeneratedAt($ccydh, $supplierName),
  4263. 'ccydh' => $ccydh,
  4264. 'cyjmc' => $pickFirst($poRows, ['CYJMC']),
  4265. 'cgymc' => $gymcList !== [] ? implode('、', $gymcList) : '',
  4266. 'cdw' => $pickFirst($poRows, ['CDW']),
  4267. 'cdf' => $pickFirst($poRows, ['CDF']),
  4268. 'remark' => $pickFirst($poRows, ['MBZ']),
  4269. 'order_qty' => $orderQty,
  4270. 'delivery_qty' => $deliveryQty,
  4271. 'customer_name' => $customerName,
  4272. 'address' => $address,
  4273. 'supplier_name' => $supplierName,
  4274. 'contact_name' => $contact,
  4275. 'mobile' => $mobile,
  4276. 'scan_url' => $scanUrl,
  4277. 'qr_data_uri' => $this->mprocDeliveryQrDataUri($scanUrl),
  4278. ];
  4279. }
  4280. /**
  4281. * 送货单首次生成时间:点过送货码后保持不变
  4282. */
  4283. protected function mprocDeliveryNoteGeneratedAt(string $ccydh, string $company): string
  4284. {
  4285. $now = date('Y-m-d H:i:s');
  4286. $this->mprocEnsureDeliveryNoteTable();
  4287. try {
  4288. $q = Db::table('purchase_order_delivery_note')->where('ccydh', $ccydh);
  4289. if ($company !== '') {
  4290. $q->where('company_name', $company);
  4291. }
  4292. $row = $q->order('id', 'asc')->find();
  4293. if (is_array($row) && trim((string)($row['generated_at'] ?? '')) !== '') {
  4294. $t = strtotime((string)$row['generated_at']);
  4295. return $t ? date('Y-m-d H:i', $t) : date('Y-m-d H:i');
  4296. }
  4297. Db::table('purchase_order_delivery_note')->insert([
  4298. 'ccydh' => $ccydh,
  4299. 'company_name' => $company,
  4300. 'generated_at' => $now,
  4301. 'createtime' => $now,
  4302. 'updatetime' => $now,
  4303. ]);
  4304. return date('Y-m-d H:i');
  4305. } catch (\Throwable $e) {
  4306. return date('Y-m-d H:i');
  4307. }
  4308. }
  4309. protected function mprocEnsureDeliveryNoteTable(): void
  4310. {
  4311. static $ok = false;
  4312. if ($ok) {
  4313. return;
  4314. }
  4315. try {
  4316. Db::query('SELECT 1 FROM `purchase_order_delivery_note` LIMIT 1');
  4317. $ok = true;
  4318. } catch (\Throwable $e) {
  4319. try {
  4320. Db::execute("CREATE TABLE IF NOT EXISTS `purchase_order_delivery_note` (
  4321. `id` int unsigned NOT NULL AUTO_INCREMENT,
  4322. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  4323. `company_name` varchar(255) NOT NULL DEFAULT '' COMMENT '供应商',
  4324. `generated_at` datetime NOT NULL COMMENT '首次生成时间',
  4325. `createtime` datetime DEFAULT NULL,
  4326. `updatetime` datetime DEFAULT NULL,
  4327. PRIMARY KEY (`id`),
  4328. UNIQUE KEY `uk_ccydh_company` (`ccydh`,`company_name`(64))
  4329. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='送货单首次生成记录'");
  4330. $ok = true;
  4331. } catch (\Throwable $e2) {
  4332. }
  4333. }
  4334. }
  4335. /**
  4336. * QR Code 容错 H(约 30%),输出 data URI,避免手机端 canvas 空白
  4337. */
  4338. protected function mprocDeliveryQrDataUri(string $text): string
  4339. {
  4340. $text = trim($text);
  4341. if ($text === '' || !function_exists('imagepng')) {
  4342. return '';
  4343. }
  4344. $lib = ROOT_PATH . 'extend' . DIRECTORY_SEPARATOR . 'phpqrcode' . DIRECTORY_SEPARATOR . 'phpqrcode.php';
  4345. if (!is_file($lib)) {
  4346. return '';
  4347. }
  4348. if (!class_exists('QRcode', false)) {
  4349. require_once $lib;
  4350. }
  4351. if (!class_exists('QRcode')) {
  4352. return '';
  4353. }
  4354. $tmp = tempnam(sys_get_temp_dir(), 'dnqr');
  4355. if ($tmp === false) {
  4356. return '';
  4357. }
  4358. $bin = '';
  4359. try {
  4360. \QRcode::png($text, $tmp, 'H', 6, 2);
  4361. $bin = is_file($tmp) ? (string)file_get_contents($tmp) : '';
  4362. } catch (\Throwable $e) {
  4363. $bin = '';
  4364. }
  4365. if (is_file($tmp)) {
  4366. @unlink($tmp);
  4367. }
  4368. if ($bin === '' || strncmp($bin, "\x89PNG", 4) !== 0) {
  4369. return '';
  4370. }
  4371. return 'data:image/png;base64,' . base64_encode($bin);
  4372. }
  4373. /**
  4374. * 送货单二维码根地址:与邮件链接共用 mproc.mobile_base_url;未配则用当前访问根地址。
  4375. */
  4376. protected function mprocDeliveryScanBaseUrl(): string
  4377. {
  4378. $cfg = rtrim(trim((string)Config::get('mproc.mobile_base_url')), '/');
  4379. if ($cfg !== '' && preg_match('#^https?://#i', $cfg)) {
  4380. return $cfg;
  4381. }
  4382. return rtrim((string)$this->request->root(true), '/');
  4383. }
  4384. /**
  4385. * 送货单扫码路径。局域网 IP 通常没有伪静态,必须带 /index.php
  4386. */
  4387. protected function mprocDeliveryScanPath(): string
  4388. {
  4389. $indexPath = trim((string)Config::get('mproc.mobile_index_path'));
  4390. if ($indexPath === '') {
  4391. $indexPath = '/index.php/index/index/index';
  4392. } else {
  4393. $indexPath = '/' . ltrim($indexPath, '/');
  4394. }
  4395. $path = preg_replace('#/index$#', '/deliveryscore', rtrim($indexPath, '/'));
  4396. if (!is_string($path) || $path === '' || substr($path, -6) === '/index') {
  4397. return '/index.php/index/index/deliveryscore';
  4398. }
  4399. return $path;
  4400. }
  4401. protected function mprocIsLanIpv4(string $ip): bool
  4402. {
  4403. if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  4404. return false;
  4405. }
  4406. if ($ip === '127.0.0.1' || strpos($ip, '127.') === 0 || strpos($ip, '169.254.') === 0) {
  4407. return false;
  4408. }
  4409. return (bool)preg_match('/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|20\.0\.)/', $ip);
  4410. }
  4411. protected function mprocDetectLanIpv4(): string
  4412. {
  4413. if (function_exists('socket_create')) {
  4414. $sock = @socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
  4415. if ($sock) {
  4416. @socket_connect($sock, '8.8.8.8', 53);
  4417. $addr = '';
  4418. @socket_getsockname($sock, $addr);
  4419. @socket_close($sock);
  4420. if (is_string($addr) && $this->mprocIsLanIpv4($addr)) {
  4421. return $addr;
  4422. }
  4423. }
  4424. }
  4425. if (strncasecmp(PHP_OS, 'WIN', 3) === 0) {
  4426. $out = @shell_exec('ipconfig');
  4427. if (is_string($out) && preg_match_all('/IPv4[^0-9]+(\d+\.\d+\.\d+\.\d+)/', $out, $m)) {
  4428. foreach ($m[1] as $ip) {
  4429. if ($this->mprocIsLanIpv4((string)$ip)) {
  4430. return (string)$ip;
  4431. }
  4432. }
  4433. }
  4434. }
  4435. $guess = gethostbyname(gethostname());
  4436. if (is_string($guess) && $this->mprocIsLanIpv4($guess)) {
  4437. return $guess;
  4438. }
  4439. return '';
  4440. }
  4441. /**
  4442. * 质量评分列表 JSON(质检;tab=pending|scored)
  4443. */
  4444. public function inboundscorelist()
  4445. {
  4446. $user = $this->mprocRequireQualityUser();
  4447. $this->mprocEnsureInboundScoreTable();
  4448. $q = trim((string)$this->request->request('q', ''));
  4449. $tab = trim((string)$this->request->request('tab', 'pending'));
  4450. if (!in_array($tab, ['pending', 'scored', 'pass', 'fail'], true)) {
  4451. $tab = 'pending';
  4452. }
  4453. if ($tab === 'pass' || $tab === 'fail') {
  4454. $tab = 'scored';
  4455. }
  4456. $adminId = (int)($user['admin_id'] ?? 0);
  4457. $rows = $this->mprocLoadInboundScoreRows($tab, $q, $adminId, 'quality');
  4458. $this->success('ok', '', [
  4459. 'tab' => $tab,
  4460. 'q' => $q,
  4461. 'scope' => 'quality',
  4462. 'rows' => $rows,
  4463. 'count' => count($rows),
  4464. ]);
  4465. }
  4466. /**
  4467. * 交货情况列表 JSON(生产部;tab=pending|scored)
  4468. */
  4469. public function deliveryscorelist()
  4470. {
  4471. $user = $this->mprocRequireDeliveryUser();
  4472. $this->mprocEnsureInboundScoreTable();
  4473. $q = trim((string)$this->request->request('q', ''));
  4474. $tab = trim((string)$this->request->request('tab', 'pending'));
  4475. if (!in_array($tab, ['pending', 'scored'], true)) {
  4476. $tab = 'pending';
  4477. }
  4478. $adminId = (int)($user['admin_id'] ?? 0);
  4479. $rows = $this->mprocLoadInboundScoreRows($tab, $q, $adminId, 'delivery');
  4480. $this->success('ok', '', [
  4481. 'tab' => $tab,
  4482. 'q' => $q,
  4483. 'scope' => 'delivery',
  4484. 'rows' => $rows,
  4485. 'count' => count($rows),
  4486. ]);
  4487. }
  4488. /**
  4489. * 交货情况 — 历史库位(去重,按使用次数多到少)
  4490. */
  4491. public function deliverystoragelocations()
  4492. {
  4493. $this->mprocRequireDeliveryUser();
  4494. $this->mprocEnsureInboundScoreTable();
  4495. $list = [];
  4496. try {
  4497. $rows = Db::table('purchase_order_inbound_score')
  4498. ->where('storage_location', '<>', '')
  4499. ->whereRaw("TRIM(storage_location) <> ''")
  4500. ->field('storage_location, COUNT(*) AS use_cnt')
  4501. ->group('storage_location')
  4502. ->order('use_cnt', 'desc')
  4503. ->order('storage_location', 'asc')
  4504. ->limit(100)
  4505. ->select();
  4506. } catch (\Throwable $e) {
  4507. $rows = [];
  4508. }
  4509. $seen = [];
  4510. if (is_array($rows)) {
  4511. foreach ($rows as $row) {
  4512. if (!is_array($row)) {
  4513. continue;
  4514. }
  4515. $loc = trim((string)($row['storage_location'] ?? ''));
  4516. if ($loc === '' || isset($seen[$loc])) {
  4517. continue;
  4518. }
  4519. $seen[$loc] = true;
  4520. $list[] = $loc;
  4521. }
  4522. }
  4523. // group 失败时回退:按出现次数统计
  4524. if ($list === []) {
  4525. try {
  4526. $raw = Db::table('purchase_order_inbound_score')
  4527. ->where('storage_location', '<>', '')
  4528. ->field('storage_location')
  4529. ->order('id', 'desc')
  4530. ->limit(1000)
  4531. ->select();
  4532. } catch (\Throwable $e) {
  4533. $raw = [];
  4534. }
  4535. $cntMap = [];
  4536. if (is_array($raw)) {
  4537. foreach ($raw as $row) {
  4538. if (!is_array($row)) {
  4539. continue;
  4540. }
  4541. $loc = trim((string)($row['storage_location'] ?? ''));
  4542. if ($loc === '') {
  4543. continue;
  4544. }
  4545. $cntMap[$loc] = isset($cntMap[$loc]) ? ($cntMap[$loc] + 1) : 1;
  4546. }
  4547. }
  4548. arsort($cntMap, SORT_NUMERIC);
  4549. $list = array_keys($cntMap);
  4550. if (count($list) > 100) {
  4551. $list = array_slice($list, 0, 100);
  4552. }
  4553. }
  4554. $this->success('ok', '', ['list' => array_values($list)]);
  4555. }
  4556. /**
  4557. * 保存质量评分(质检中心)
  4558. * POST:ccydh、result、order_interrupt、remark
  4559. * 客诉事后由 inboundscorecomplaint 补登,首次默认否
  4560. */
  4561. public function inboundscoresave()
  4562. {
  4563. $user = $this->mprocRequireQualityUser();
  4564. if (!$this->request->isPost()) {
  4565. $this->error('请使用 POST');
  4566. }
  4567. $this->mprocEnsureInboundScoreTable();
  4568. $ccydh = trim((string)$this->request->post('ccydh', ''));
  4569. $sid = (int)$this->request->post('scydgy_id', 0);
  4570. $result = trim((string)$this->request->post('result', ''));
  4571. if ($result !== '合格' && $result !== '不合格') {
  4572. $this->error('请选择生产是否合格');
  4573. }
  4574. $orderInterrupt = (int)$this->request->post('order_interrupt', -1);
  4575. if ($orderInterrupt !== 0 && $orderInterrupt !== 1) {
  4576. $this->error('请选择生产是否中断');
  4577. }
  4578. $remark = trim((string)$this->request->post('remark', ''));
  4579. if ($result === '不合格' && $remark === '') {
  4580. $this->error('请填写不合格原因');
  4581. }
  4582. if (mb_strlen($remark) > 500) {
  4583. $remark = mb_substr($remark, 0, 500);
  4584. }
  4585. $poRows = $this->mprocLoadApprovedPoRowsForScore($ccydh, $sid);
  4586. $now = date('Y-m-d H:i:s');
  4587. $adminId = (int)($user['admin_id'] ?? 0);
  4588. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  4589. $saved = 0;
  4590. $firstSid = 0;
  4591. $firstPoId = 0;
  4592. $deliveryReady = true;
  4593. try {
  4594. Db::startTrans();
  4595. foreach ($poRows as $po) {
  4596. if (!is_array($po)) {
  4597. continue;
  4598. }
  4599. $rowSid = (int)($po['scydgy_id'] ?? 0);
  4600. if ($rowSid <= 0) {
  4601. continue;
  4602. }
  4603. if ($firstSid <= 0) {
  4604. $firstSid = $rowSid;
  4605. $firstPoId = (int)($po['id'] ?? 0);
  4606. }
  4607. $exist = Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->find();
  4608. $existDs = is_array($exist) ? trim((string)($exist['delivery_status'] ?? '')) : '';
  4609. if ($existDs !== '准时' && $existDs !== '滞后') {
  4610. $deliveryReady = false;
  4611. }
  4612. $data = [
  4613. 'scydgy_id' => $rowSid,
  4614. 'purchase_order_id' => (int)($po['id'] ?? 0),
  4615. 'ccydh' => trim((string)($po['CCYDH'] ?? $ccydh)),
  4616. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  4617. 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
  4618. 'company_name' => trim((string)($po['pick_company_name'] ?? '')),
  4619. 'result' => $result,
  4620. 'order_interrupt' => $orderInterrupt,
  4621. 'remark' => $remark,
  4622. 'admin_id' => $adminId,
  4623. 'admin_name' => $adminName,
  4624. 'updatetime' => $now,
  4625. ];
  4626. if (is_array($exist) && $exist !== []) {
  4627. // 客诉事后补登,首次评分不覆盖已有客诉
  4628. Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->update($data);
  4629. } else {
  4630. $data['customer_complaint'] = 0;
  4631. $data['complaint_remark'] = '';
  4632. $data['delivery_status'] = '';
  4633. $data['createtime'] = $now;
  4634. Db::table('purchase_order_inbound_score')->insert($data);
  4635. $deliveryReady = false;
  4636. }
  4637. $saved++;
  4638. }
  4639. if ($saved < 1) {
  4640. throw new \RuntimeException('没有可保存的工序');
  4641. }
  4642. if ($deliveryReady) {
  4643. foreach ($poRows as $po) {
  4644. if (!is_array($po)) {
  4645. continue;
  4646. }
  4647. $rowSid = (int)($po['scydgy_id'] ?? 0);
  4648. if ($rowSid > 0) {
  4649. Db::table('purchase_order')->where('scydgy_id', $rowSid)->update([
  4650. 'status' => ProcuremenStatus::PO_COMPLETED,
  4651. ]);
  4652. }
  4653. }
  4654. }
  4655. Db::commit();
  4656. } catch (\Throwable $e) {
  4657. try {
  4658. Db::rollback();
  4659. } catch (\Throwable $e2) {
  4660. }
  4661. Log::record('inboundscoresave fail: ' . $e->getMessage(), 'error');
  4662. $this->error('保存失败,请稍后重试');
  4663. }
  4664. $logDetail = '质量评分:生产是否合格=' . $result
  4665. . ';生产是否中断:' . ($orderInterrupt === 1 ? '是' : '否');
  4666. if ($remark !== '') {
  4667. $logDetail .= ';备注:' . $remark;
  4668. }
  4669. \app\common\library\ProcuremenOperLog::write(
  4670. $firstSid,
  4671. 'inbound_score',
  4672. $logDetail,
  4673. $firstPoId > 0 ? $firstPoId : null,
  4674. [$adminId, $adminName]
  4675. );
  4676. $this->mprocSyncMonthlyAfterInboundScore($poRows, $now);
  4677. if ($deliveryReady) {
  4678. $this->mprocRefreshCompletedArchivePdfs($poRows);
  4679. }
  4680. $this->success('操作成功', '', [
  4681. 'ccydh' => $ccydh,
  4682. 'result' => $result,
  4683. 'order_interrupt' => $orderInterrupt,
  4684. 'remark' => $remark,
  4685. 'count' => $saved,
  4686. 'completed' => $deliveryReady ? 1 : 0,
  4687. ]);
  4688. }
  4689. /**
  4690. * 事后投诉反馈(质检中心,仅已质量评分订单)
  4691. * POST:ccydh、customer_complaint=0|1、complaint_remark(投诉为是时必填)
  4692. */
  4693. public function inboundscorecomplaint()
  4694. {
  4695. $user = $this->mprocRequireQualityUser();
  4696. if (!$this->request->isPost()) {
  4697. $this->error('请使用 POST');
  4698. }
  4699. $this->mprocEnsureInboundScoreTable();
  4700. $ccydh = trim((string)$this->request->post('ccydh', ''));
  4701. $sid = (int)$this->request->post('scydgy_id', 0);
  4702. $customerComplaint = (int)$this->request->post('customer_complaint', -1);
  4703. if ($customerComplaint !== 0 && $customerComplaint !== 1) {
  4704. $this->error('请选择客户是否投诉');
  4705. }
  4706. $complaintRemark = trim((string)$this->request->post('complaint_remark', ''));
  4707. if ($customerComplaint === 1 && $complaintRemark === '') {
  4708. $this->error('请填写投诉说明');
  4709. }
  4710. if ($customerComplaint !== 1) {
  4711. $complaintRemark = '';
  4712. }
  4713. if (mb_strlen($complaintRemark) > 500) {
  4714. $complaintRemark = mb_substr($complaintRemark, 0, 500);
  4715. }
  4716. if ($ccydh === '' && $sid > 0) {
  4717. try {
  4718. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  4719. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  4720. } catch (\Throwable $e) {
  4721. $ccydh = '';
  4722. }
  4723. }
  4724. if ($ccydh === '') {
  4725. $this->error('缺少订单号');
  4726. }
  4727. try {
  4728. $scoreRows = Db::table('purchase_order_inbound_score')
  4729. ->where('ccydh', $ccydh)
  4730. ->field('id,scydgy_id,purchase_order_id,result,company_name')
  4731. ->select();
  4732. } catch (\Throwable $e) {
  4733. $scoreRows = [];
  4734. }
  4735. if (!is_array($scoreRows) || $scoreRows === []) {
  4736. $this->error('请先完成质量评分后再投诉反馈');
  4737. }
  4738. $hasQuality = false;
  4739. foreach ($scoreRows as $sc) {
  4740. if (!is_array($sc)) {
  4741. continue;
  4742. }
  4743. $res = trim((string)($sc['result'] ?? ''));
  4744. if ($res === '合格' || $res === '不合格') {
  4745. $hasQuality = true;
  4746. break;
  4747. }
  4748. }
  4749. if (!$hasQuality) {
  4750. $this->error('请先完成质量评分后再投诉反馈');
  4751. }
  4752. $now = date('Y-m-d H:i:s');
  4753. $adminId = (int)($user['admin_id'] ?? 0);
  4754. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  4755. $firstSid = 0;
  4756. $firstPoId = 0;
  4757. $companyName = '';
  4758. $updated = 0;
  4759. try {
  4760. Db::startTrans();
  4761. foreach ($scoreRows as $sc) {
  4762. if (!is_array($sc)) {
  4763. continue;
  4764. }
  4765. $rowSid = (int)($sc['scydgy_id'] ?? 0);
  4766. $id = (int)($sc['id'] ?? 0);
  4767. if ($id <= 0) {
  4768. continue;
  4769. }
  4770. if ($firstSid <= 0 && $rowSid > 0) {
  4771. $firstSid = $rowSid;
  4772. $firstPoId = (int)($sc['purchase_order_id'] ?? 0);
  4773. }
  4774. if ($companyName === '') {
  4775. $companyName = trim((string)($sc['company_name'] ?? ''));
  4776. }
  4777. Db::table('purchase_order_inbound_score')->where('id', $id)->update([
  4778. 'customer_complaint' => $customerComplaint,
  4779. 'complaint_remark' => $complaintRemark,
  4780. 'updatetime' => $now,
  4781. ]);
  4782. $updated++;
  4783. }
  4784. if ($updated < 1) {
  4785. throw new \RuntimeException('没有可更新的记录');
  4786. }
  4787. Db::commit();
  4788. } catch (\Throwable $e) {
  4789. try {
  4790. Db::rollback();
  4791. } catch (\Throwable $e2) {
  4792. }
  4793. Log::record('inboundscorecomplaint fail: ' . $e->getMessage(), 'error');
  4794. $this->error('保存失败,请稍后重试');
  4795. }
  4796. if ($firstSid > 0) {
  4797. $logDetail = '投诉反馈:客户投诉=' . ($customerComplaint === 1 ? '是' : '否');
  4798. if ($complaintRemark !== '') {
  4799. $logDetail .= ';投诉说明:' . $complaintRemark;
  4800. }
  4801. \app\common\library\ProcuremenOperLog::write(
  4802. $firstSid,
  4803. 'inbound_score',
  4804. $logDetail,
  4805. $firstPoId > 0 ? $firstPoId : null,
  4806. [$adminId, $adminName]
  4807. );
  4808. }
  4809. if ($companyName !== '') {
  4810. $scoreYm = date('Y-m', strtotime($now) ?: time());
  4811. try {
  4812. \app\common\library\ProcuremenSupplierScore::syncQualityScoreFromInbound($scoreYm, $companyName);
  4813. } catch (\Throwable $e) {
  4814. Log::record('inboundscorecomplaint quality sync: ' . $e->getMessage(), 'error');
  4815. }
  4816. }
  4817. $this->success('操作成功', '', [
  4818. 'ccydh' => $ccydh,
  4819. 'customer_complaint' => $customerComplaint,
  4820. 'complaint_remark' => $complaintRemark,
  4821. 'count' => $updated,
  4822. ]);
  4823. }
  4824. /**
  4825. * 保存交货情况(生产部)
  4826. * POST:ccydh、storage_location、delivery_status=准时|滞后、delivery_date=YYYY-MM-DD、remark
  4827. */
  4828. public function deliveryscoresave()
  4829. {
  4830. $user = $this->mprocRequireDeliveryUser();
  4831. if (!$this->request->isPost()) {
  4832. $this->error('请使用 POST');
  4833. }
  4834. $this->mprocEnsureInboundScoreTable();
  4835. $ccydh = trim((string)$this->request->post('ccydh', ''));
  4836. $sid = (int)$this->request->post('scydgy_id', 0);
  4837. $storageLocation = trim((string)$this->request->post('storage_location', ''));
  4838. if ($storageLocation === '') {
  4839. $this->error('请填写库位');
  4840. }
  4841. if (mb_strlen($storageLocation) > 64) {
  4842. $this->error('库位最多64个字符');
  4843. }
  4844. $deliveryStatus = trim((string)$this->request->post('delivery_status', ''));
  4845. if ($deliveryStatus !== '准时' && $deliveryStatus !== '滞后') {
  4846. $this->error('请选择交货情况');
  4847. }
  4848. $deliveryDate = trim((string)$this->request->post('delivery_date', ''));
  4849. if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryDate)) {
  4850. $this->error('请选择交货日期');
  4851. }
  4852. $ts = strtotime($deliveryDate . ' 00:00:00');
  4853. if ($ts === false) {
  4854. $this->error('交货日期格式不正确');
  4855. }
  4856. $deliveryDate = date('Y-m-d', $ts);
  4857. $remark = trim((string)$this->request->post('remark', ''));
  4858. if ($deliveryStatus === '滞后' && $remark === '') {
  4859. $this->error('请填写滞后原因');
  4860. }
  4861. if (mb_strlen($remark) > 500) {
  4862. $remark = mb_substr($remark, 0, 500);
  4863. }
  4864. $poRows = $this->mprocLoadApprovedPoRowsForScore($ccydh, $sid);
  4865. $deadlineYmd = '';
  4866. foreach ($poRows as $po) {
  4867. if (!is_array($po)) {
  4868. continue;
  4869. }
  4870. $deadlineYmd = $this->mprocFormatYmdValue($po['delivery_deadline'] ?? $po['Delivery_deadline'] ?? '');
  4871. if ($deadlineYmd !== '') {
  4872. break;
  4873. }
  4874. }
  4875. if ($deadlineYmd !== '' && $deliveryDate > $deadlineYmd && $deliveryStatus === '准时') {
  4876. $this->error('交货日期已超过截止日期,只能选择滞后');
  4877. }
  4878. if ($deadlineYmd !== '' && $deliveryDate <= $deadlineYmd && $deliveryStatus === '滞后') {
  4879. $this->error('已选择滞后请确认交货日期');
  4880. }
  4881. $now = date('Y-m-d H:i:s');
  4882. $adminId = (int)($user['admin_id'] ?? 0);
  4883. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  4884. $saved = 0;
  4885. $firstSid = 0;
  4886. $firstPoId = 0;
  4887. $qualityReady = true;
  4888. try {
  4889. Db::startTrans();
  4890. foreach ($poRows as $po) {
  4891. if (!is_array($po)) {
  4892. continue;
  4893. }
  4894. $rowSid = (int)($po['scydgy_id'] ?? 0);
  4895. if ($rowSid <= 0) {
  4896. continue;
  4897. }
  4898. if ($firstSid <= 0) {
  4899. $firstSid = $rowSid;
  4900. $firstPoId = (int)($po['id'] ?? 0);
  4901. }
  4902. $exist = Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->find();
  4903. $existResult = is_array($exist) ? trim((string)($exist['result'] ?? '')) : '';
  4904. if ($existResult !== '合格' && $existResult !== '不合格') {
  4905. $qualityReady = false;
  4906. }
  4907. $data = [
  4908. 'scydgy_id' => $rowSid,
  4909. 'purchase_order_id' => (int)($po['id'] ?? 0),
  4910. 'ccydh' => trim((string)($po['CCYDH'] ?? $ccydh)),
  4911. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  4912. 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
  4913. 'company_name' => trim((string)($po['pick_company_name'] ?? '')),
  4914. 'storage_location' => $storageLocation,
  4915. 'delivery_status' => $deliveryStatus,
  4916. 'delivery_date' => $deliveryDate,
  4917. 'remark' => $remark,
  4918. 'delivery_admin_id' => $adminId,
  4919. 'delivery_admin_name' => $adminName,
  4920. 'updatetime' => $now,
  4921. ];
  4922. if (is_array($exist) && $exist !== []) {
  4923. Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->update($data);
  4924. } else {
  4925. $data['result'] = '';
  4926. $data['customer_complaint'] = 0;
  4927. $data['complaint_remark'] = '';
  4928. $data['order_interrupt'] = 0;
  4929. $data['admin_id'] = $adminId;
  4930. $data['admin_name'] = $adminName;
  4931. $data['createtime'] = $now;
  4932. Db::table('purchase_order_inbound_score')->insert($data);
  4933. $qualityReady = false;
  4934. }
  4935. $saved++;
  4936. }
  4937. if ($saved < 1) {
  4938. throw new \RuntimeException('没有可保存的工序');
  4939. }
  4940. if ($qualityReady) {
  4941. foreach ($poRows as $po) {
  4942. if (!is_array($po)) {
  4943. continue;
  4944. }
  4945. $rowSid = (int)($po['scydgy_id'] ?? 0);
  4946. if ($rowSid > 0) {
  4947. Db::table('purchase_order')->where('scydgy_id', $rowSid)->update([
  4948. 'status' => ProcuremenStatus::PO_COMPLETED,
  4949. ]);
  4950. }
  4951. }
  4952. }
  4953. Db::commit();
  4954. } catch (\Throwable $e) {
  4955. try {
  4956. Db::rollback();
  4957. } catch (\Throwable $e2) {
  4958. }
  4959. Log::record('deliveryscoresave fail: ' . $e->getMessage(), 'error');
  4960. $this->error('保存失败,请稍后重试');
  4961. }
  4962. $logDetail = '库位:' . $storageLocation . ';交货情况:' . $deliveryStatus . ';交货日期:' . $deliveryDate;
  4963. if ($remark !== '') {
  4964. $logDetail .= ';备注:' . $remark;
  4965. }
  4966. \app\common\library\ProcuremenOperLog::write(
  4967. $firstSid,
  4968. 'inbound_score',
  4969. $logDetail,
  4970. $firstPoId > 0 ? $firstPoId : null,
  4971. [$adminId, $adminName]
  4972. );
  4973. $this->mprocSyncMonthlyAfterInboundScore($poRows, $now);
  4974. if ($qualityReady) {
  4975. $this->mprocRefreshCompletedArchivePdfs($poRows);
  4976. }
  4977. $this->success('操作成功', '', [
  4978. 'ccydh' => $ccydh,
  4979. 'storage_location' => $storageLocation,
  4980. 'delivery_status' => $deliveryStatus,
  4981. 'delivery_date' => $deliveryDate,
  4982. 'remark' => $remark,
  4983. 'count' => $saved,
  4984. 'completed' => $qualityReady ? 1 : 0,
  4985. ]);
  4986. }
  4987. /**
  4988. * 交货情况(已确认)— 通知人员名单(质检中心 + 业务员)
  4989. */
  4990. public function deliverynotifymen()
  4991. {
  4992. $user = $this->mprocRequireDeliveryUser();
  4993. $ccydh = trim((string)$this->request->request('ccydh', ''));
  4994. $sid = (int)$this->request->request('scydgy_id', 0);
  4995. $order = $this->mprocLoadDeliveryNotifyOrder($ccydh, $sid);
  4996. if ($order === null) {
  4997. $this->error('未找到可通知的订单');
  4998. }
  4999. $selfAdminId = (int)($user['admin_id'] ?? 0);
  5000. $list = [];
  5001. foreach ($this->mprocLoadArrivalNotifyStaffOptions() as $opt) {
  5002. $email = trim((string)($opt['email'] ?? ''));
  5003. $adminId = (int)($opt['admin_id'] ?? 0);
  5004. $list[] = [
  5005. 'name' => (string)($opt['name'] ?? ''),
  5006. 'email' => $email,
  5007. 'mobile' => (string)($opt['mobile'] ?? ''),
  5008. 'role' => (string)($opt['role'] ?? ''),
  5009. 'admin_id' => $adminId,
  5010. 'can_select' => ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) ? 1 : 0,
  5011. 'is_self' => ($selfAdminId > 0 && $adminId === $selfAdminId) ? 1 : 0,
  5012. ];
  5013. }
  5014. $this->success('ok', '', [
  5015. 'ccydh' => (string)($order['CCYDH'] ?? ''),
  5016. 'cyjmc' => (string)($order['CYJMC'] ?? ''),
  5017. 'cgymc' => (string)($order['CGYMC'] ?? ''),
  5018. 'this_quantity' => (string)($order['order_qty'] ?? ''),
  5019. 'supplier_name' => (string)($order['pick_company_name'] ?? ''),
  5020. 'delivery_deadline' => (string)($order['delivery_deadline'] ?? ''),
  5021. 'list' => $list,
  5022. ]);
  5023. }
  5024. /**
  5025. * 交货情况(已确认)— 邮箱通知所选质检/业务员:订单已到货
  5026. * POST:ccydh、staff_json=["姓名",...]
  5027. */
  5028. public function deliverynotify()
  5029. {
  5030. $user = $this->mprocRequireDeliveryUser();
  5031. if (!$this->request->isPost()) {
  5032. $this->error('请使用 POST');
  5033. }
  5034. $ccydh = trim((string)$this->request->post('ccydh', ''));
  5035. $sid = (int)$this->request->post('scydgy_id', 0);
  5036. $order = $this->mprocLoadDeliveryNotifyOrder($ccydh, $sid);
  5037. if ($order === null) {
  5038. $this->error('未找到可通知的订单');
  5039. }
  5040. $ccydh = trim((string)($order['CCYDH'] ?? $ccydh));
  5041. $raw = $this->request->post('staff/a', []);
  5042. if (!is_array($raw) || $raw === []) {
  5043. // 关闭过滤器,避免 staff_json 中的引号被转义导致 json_decode 失败
  5044. $staffJson = (string)$this->request->post('staff_json', '', null);
  5045. if ($staffJson === '') {
  5046. $staffJson = (string)($this->request->param('staff_json', '', null) ?: '');
  5047. }
  5048. if ($staffJson !== '') {
  5049. $decoded = json_decode(html_entity_decode($staffJson, ENT_QUOTES, 'UTF-8'), true);
  5050. if (!is_array($decoded)) {
  5051. $decoded = json_decode($staffJson, true);
  5052. }
  5053. $raw = is_array($decoded) ? $decoded : [];
  5054. }
  5055. }
  5056. $selectedNames = [];
  5057. foreach ((array)$raw as $item) {
  5058. $n = is_array($item) ? trim((string)($item['name'] ?? '')) : trim((string)$item);
  5059. if ($n !== '') {
  5060. $selectedNames[] = $n;
  5061. }
  5062. }
  5063. $selectedNames = array_values(array_unique($selectedNames));
  5064. if ($selectedNames === []) {
  5065. $this->error('请选择要通知的人员');
  5066. }
  5067. $optionMap = [];
  5068. foreach ($this->mprocLoadArrivalNotifyStaffOptions() as $opt) {
  5069. $n = trim((string)($opt['name'] ?? ''));
  5070. if ($n !== '') {
  5071. $optionMap[$n] = $opt;
  5072. }
  5073. }
  5074. $targets = [];
  5075. foreach ($selectedNames as $n) {
  5076. if (!isset($optionMap[$n])) {
  5077. $this->error('人员不在可选名单中:' . $n);
  5078. }
  5079. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  5080. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  5081. $this->error('未填写有效邮箱,无法通知:' . $n);
  5082. }
  5083. $targets[] = $optionMap[$n];
  5084. }
  5085. try {
  5086. $mailConfig = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  5087. } catch (\Throwable $e) {
  5088. $mailConfig = [];
  5089. }
  5090. if (!is_array($mailConfig) || empty($mailConfig['host'])) {
  5091. $this->error('邮件 SMTP 未配置');
  5092. }
  5093. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  5094. $this->error('发件邮箱未配置');
  5095. }
  5096. $this->mprocEnsureArrivalNotifyEmailTemplate();
  5097. try {
  5098. $platformUrl = $this->mprocBuildInboundscoreNotifyUrl($ccydh);
  5099. } catch (\Throwable $e) {
  5100. $this->error($e->getMessage());
  5101. }
  5102. $tpl = $this->mprocLoadNotifyTemplateRow('arrival_notify_email');
  5103. if ($tpl === null || trim((string)($tpl['content'] ?? '')) === '') {
  5104. $tpl = $this->mprocLoadNotifyTemplateRow('delivery_notify_email');
  5105. }
  5106. if ($tpl === null || trim((string)($tpl['content'] ?? '')) === '') {
  5107. $this->error('邮件模版未配置,请在后台「短信模版配置」维护「订单已到货通知-邮箱」');
  5108. }
  5109. $subjectTpl = trim((string)($tpl['title'] ?? ''));
  5110. if ($subjectTpl === '' || stripos($subjectTpl, '交货情况') !== false) {
  5111. $subjectTpl = '订单已到货通知 - {ccydh}';
  5112. }
  5113. $contentTpl = (string)$tpl['content'];
  5114. $ok = 0;
  5115. $okNames = [];
  5116. $failMsgs = [];
  5117. $firstSid = (int)($order['scydgy_id'] ?? 0);
  5118. $firstPoId = (int)($order['id'] ?? 0);
  5119. $adminId = (int)($user['admin_id'] ?? 0);
  5120. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  5121. foreach ($targets as $contact) {
  5122. $toName = trim((string)($contact['name'] ?? ''));
  5123. $toEmail = trim((string)($contact['email'] ?? ''));
  5124. $vars = [
  5125. 'contact_name' => $toName,
  5126. 'company_name' => $toName,
  5127. 'email' => $toEmail,
  5128. 'ccydh' => $ccydh,
  5129. 'cyjmc' => (string)($order['CYJMC'] ?? ''),
  5130. 'cgymc' => (string)($order['CGYMC'] ?? ''),
  5131. 'this_quantity' => (string)($order['order_qty'] ?? ''),
  5132. 'supplier_name' => (string)($order['pick_company_name'] ?? ''),
  5133. 'delivery_deadline' => (string)($order['delivery_deadline'] ?? ''),
  5134. 'delivery_status' => (string)($order['delivery_status'] ?? ''),
  5135. 'delivery_date' => (string)($order['delivery_date'] ?? ''),
  5136. 'storage_location' => (string)($order['storage_location'] ?? ''),
  5137. 'remark' => (string)($order['delivery_remark'] ?? ''),
  5138. 'platform_url' => $platformUrl,
  5139. ];
  5140. $mailPlain = $contentTpl;
  5141. $mailSubject = $subjectTpl;
  5142. foreach ($vars as $k => $v) {
  5143. $mailPlain = str_replace('{' . $k . '}', (string)$v, $mailPlain);
  5144. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  5145. }
  5146. $mailPlain = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailPlain);
  5147. $mailSubject = trim((string)preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject));
  5148. if ($mailSubject === '') {
  5149. $mailSubject = '订单已到货通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  5150. }
  5151. $mailBody = $this->mprocPlainTextToHtmlEmailBody($mailPlain);
  5152. try {
  5153. $this->mprocSendNotifyEmail($mailConfig, $toEmail, $toName, $mailSubject, $mailBody, $toEmail);
  5154. $ok++;
  5155. if ($toName !== '') {
  5156. $okNames[] = $toName;
  5157. }
  5158. $this->mprocPersistEmailSendLog([
  5159. 'from_email' => trim((string)($mailConfig['addr'] ?? '')),
  5160. 'to_email' => $toEmail,
  5161. 'scene' => '订单已到货通知',
  5162. 'ccydh' => $ccydh,
  5163. 'company_name' => $toName,
  5164. 'mail_subject' => $mailSubject,
  5165. 'status' => 1,
  5166. 'fail_reason' => '',
  5167. 'scydgy_id' => $firstSid,
  5168. 'purchase_order_id' => $firstPoId,
  5169. 'admin_id' => $adminId,
  5170. 'admin_name' => $adminName,
  5171. ]);
  5172. } catch (\Throwable $e) {
  5173. $failMsgs[] = $toName . ':' . $e->getMessage();
  5174. $this->mprocPersistEmailSendLog([
  5175. 'from_email' => trim((string)($mailConfig['addr'] ?? '')),
  5176. 'to_email' => $toEmail,
  5177. 'scene' => '订单已到货通知',
  5178. 'ccydh' => $ccydh,
  5179. 'company_name' => $toName,
  5180. 'mail_subject' => $mailSubject,
  5181. 'status' => 0,
  5182. 'fail_reason' => $e->getMessage(),
  5183. 'scydgy_id' => $firstSid,
  5184. 'purchase_order_id' => $firstPoId,
  5185. 'admin_id' => $adminId,
  5186. 'admin_name' => $adminName,
  5187. ]);
  5188. }
  5189. }
  5190. if ($ok < 1) {
  5191. $this->error('发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  5192. }
  5193. $mergedStaff = $this->mprocPersistArrivalNotifyStaff($ccydh, $okNames);
  5194. if ($firstSid > 0) {
  5195. \app\common\library\ProcuremenOperLog::write(
  5196. $firstSid,
  5197. 'arrival_notify',
  5198. '手机端交货情况通知已到货(质检/业务员):' . implode('、', $okNames),
  5199. $firstPoId > 0 ? $firstPoId : null,
  5200. [$adminId, $adminName]
  5201. );
  5202. }
  5203. $msg = '已通知 ' . $ok . ' 人';
  5204. if ($failMsgs !== []) {
  5205. $msg .= ';部分失败:' . implode(';', $failMsgs);
  5206. }
  5207. $this->success($msg, '', [
  5208. 'ok_count' => $ok,
  5209. 'fail_count' => count($failMsgs),
  5210. 'arrival_notify_staff' => $mergedStaff,
  5211. ]);
  5212. }
  5213. /**
  5214. * 已到货通知可选人员:质检中心 + 业务员
  5215. *
  5216. * @return array<int, array{admin_id:int,name:string,email:string,mobile:string,role:string}>
  5217. */
  5218. protected function mprocLoadArrivalNotifyStaffOptions(): array
  5219. {
  5220. $groups = [
  5221. ['id' => $this->mprocResolveMobileQualityGroupId(), 'role' => '质检'],
  5222. ['id' => $this->mprocResolveMobileRfqGroupId(), 'role' => '业务员'],
  5223. ];
  5224. $out = [];
  5225. $seen = [];
  5226. foreach ($groups as $g) {
  5227. $groupId = (int)($g['id'] ?? 0);
  5228. $role = (string)($g['role'] ?? '');
  5229. if ($groupId <= 0) {
  5230. continue;
  5231. }
  5232. try {
  5233. $adminIds = Db::name('auth_group_access')->where('group_id', $groupId)->column('uid');
  5234. } catch (\Throwable $e) {
  5235. continue;
  5236. }
  5237. $adminIds = is_array($adminIds)
  5238. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  5239. : [];
  5240. if ($adminIds === []) {
  5241. continue;
  5242. }
  5243. try {
  5244. $rows = Db::name('admin')
  5245. ->where('status', 'normal')
  5246. ->where('id', 'in', $adminIds)
  5247. ->order('id', 'asc')
  5248. ->field('id,nickname,username,email,mobile')
  5249. ->select();
  5250. } catch (\Throwable $e) {
  5251. continue;
  5252. }
  5253. if (!is_array($rows)) {
  5254. continue;
  5255. }
  5256. foreach ($rows as $row) {
  5257. if (!is_array($row)) {
  5258. continue;
  5259. }
  5260. $name = trim((string)($row['nickname'] ?? ''));
  5261. if ($name === '') {
  5262. $name = trim((string)($row['username'] ?? ''));
  5263. }
  5264. if ($name === '' || isset($seen[$name])) {
  5265. continue;
  5266. }
  5267. $seen[$name] = true;
  5268. $out[] = [
  5269. 'admin_id' => (int)($row['id'] ?? 0),
  5270. 'name' => $name,
  5271. 'email' => trim((string)($row['email'] ?? '')),
  5272. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  5273. 'role' => $role,
  5274. ];
  5275. }
  5276. }
  5277. return $out;
  5278. }
  5279. /**
  5280. * @return array<int, array{admin_id:int,name:string,email:string,mobile:string}>
  5281. */
  5282. protected function mprocLoadDeliveryStaffOptions(): array
  5283. {
  5284. $out = [];
  5285. $seen = [];
  5286. $groupId = $this->mprocResolveMobileDeliveryGroupId();
  5287. if ($groupId <= 0) {
  5288. return [];
  5289. }
  5290. try {
  5291. $adminIds = Db::name('auth_group_access')->where('group_id', $groupId)->column('uid');
  5292. } catch (\Throwable $e) {
  5293. return [];
  5294. }
  5295. $adminIds = is_array($adminIds)
  5296. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  5297. : [];
  5298. if ($adminIds === []) {
  5299. return [];
  5300. }
  5301. try {
  5302. $rows = Db::name('admin')
  5303. ->where('status', 'normal')
  5304. ->where('id', 'in', $adminIds)
  5305. ->order('id', 'asc')
  5306. ->field('id,nickname,username,email,mobile')
  5307. ->select();
  5308. } catch (\Throwable $e) {
  5309. return [];
  5310. }
  5311. if (!is_array($rows)) {
  5312. return [];
  5313. }
  5314. foreach ($rows as $row) {
  5315. if (!is_array($row)) {
  5316. continue;
  5317. }
  5318. $name = trim((string)($row['nickname'] ?? ''));
  5319. if ($name === '') {
  5320. $name = trim((string)($row['username'] ?? ''));
  5321. }
  5322. if ($name === '' || isset($seen[$name])) {
  5323. continue;
  5324. }
  5325. $seen[$name] = true;
  5326. $out[] = [
  5327. 'admin_id' => (int)($row['id'] ?? 0),
  5328. 'name' => $name,
  5329. 'email' => trim((string)($row['email'] ?? '')),
  5330. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  5331. ];
  5332. }
  5333. return $out;
  5334. }
  5335. /**
  5336. * 合并已通知人员姓名(去重,顿号分隔)
  5337. *
  5338. * @param string $old
  5339. * @param string[] $names
  5340. */
  5341. protected function mprocMergeArrivalNotifyStaffNames(string $old, array $names): string
  5342. {
  5343. $map = [];
  5344. foreach (preg_split('/[、,,;;]+/u', $old) ?: [] as $p) {
  5345. $p = trim((string)$p);
  5346. if ($p !== '') {
  5347. $map[$p] = true;
  5348. }
  5349. }
  5350. foreach ($names as $n) {
  5351. $n = trim((string)$n);
  5352. if ($n !== '') {
  5353. $map[$n] = true;
  5354. }
  5355. }
  5356. return implode('、', array_keys($map));
  5357. }
  5358. /**
  5359. * 记录订单已到货通知人员(写入 inbound_score,按订单号合并)
  5360. *
  5361. * @param string[] $names
  5362. */
  5363. protected function mprocPersistArrivalNotifyStaff(string $ccydh, array $names): string
  5364. {
  5365. $ccydh = trim($ccydh);
  5366. $names = array_values(array_filter(array_map(static function ($n) {
  5367. return trim((string)$n);
  5368. }, $names)));
  5369. if ($ccydh === '' || $names === []) {
  5370. return '';
  5371. }
  5372. $this->mprocEnsureInboundScoreTable();
  5373. $now = date('Y-m-d H:i:s');
  5374. $merged = implode('、', $names);
  5375. try {
  5376. $rows = Db::table('purchase_order_inbound_score')
  5377. ->where('ccydh', $ccydh)
  5378. ->field('id,arrival_notify_staff')
  5379. ->select();
  5380. } catch (\Throwable $e) {
  5381. try {
  5382. $rows = Db::table('purchase_order_inbound_score')
  5383. ->where('CCYDH', $ccydh)
  5384. ->field('id,arrival_notify_staff')
  5385. ->select();
  5386. } catch (\Throwable $e2) {
  5387. $rows = [];
  5388. }
  5389. }
  5390. if (!is_array($rows) || $rows === []) {
  5391. // 按工序写入:订单下已确认交货的 scydgy
  5392. try {
  5393. $sids = Db::table('purchase_order')
  5394. ->where('CCYDH', $ccydh)
  5395. ->where('scydgy_id', '>', 0)
  5396. ->column('scydgy_id');
  5397. } catch (\Throwable $e) {
  5398. $sids = [];
  5399. }
  5400. $sids = is_array($sids) ? array_values(array_unique(array_filter(array_map('intval', $sids)))) : [];
  5401. if ($sids !== []) {
  5402. try {
  5403. $rows = Db::table('purchase_order_inbound_score')
  5404. ->where('scydgy_id', 'in', $sids)
  5405. ->field('id,arrival_notify_staff')
  5406. ->select();
  5407. } catch (\Throwable $e) {
  5408. $rows = [];
  5409. }
  5410. }
  5411. }
  5412. if (!is_array($rows) || $rows === []) {
  5413. return $merged;
  5414. }
  5415. foreach ($rows as $row) {
  5416. if (!is_array($row)) {
  5417. continue;
  5418. }
  5419. $id = (int)($row['id'] ?? 0);
  5420. if ($id <= 0) {
  5421. continue;
  5422. }
  5423. $staff = $this->mprocMergeArrivalNotifyStaffNames((string)($row['arrival_notify_staff'] ?? ''), $names);
  5424. $merged = $staff !== '' ? $staff : $merged;
  5425. try {
  5426. Db::table('purchase_order_inbound_score')->where('id', $id)->update([
  5427. 'arrival_notify_staff' => $staff,
  5428. 'arrival_notify_time' => $now,
  5429. 'updatetime' => $now,
  5430. ]);
  5431. } catch (\Throwable $e) {
  5432. try {
  5433. Db::table('purchase_order_inbound_score')->where('id', $id)->update([
  5434. 'arrival_notify_staff' => $staff,
  5435. 'arrival_notify_time' => $now,
  5436. ]);
  5437. } catch (\Throwable $e2) {
  5438. }
  5439. }
  5440. }
  5441. return $merged;
  5442. }
  5443. /**
  5444. * @return array<string, mixed>|null
  5445. */
  5446. protected function mprocLoadDeliveryNotifyOrder(string $ccydh, int $sid = 0): ?array
  5447. {
  5448. $ccydh = trim($ccydh);
  5449. if ($ccydh === '' && $sid > 0) {
  5450. try {
  5451. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  5452. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  5453. } catch (\Throwable $e) {
  5454. $ccydh = '';
  5455. }
  5456. }
  5457. if ($ccydh === '') {
  5458. return null;
  5459. }
  5460. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  5461. $approvedIn = implode(',', array_map(static function ($v) {
  5462. return "'" . str_replace("'", "''", (string)$v) . "'";
  5463. }, $approvedVals));
  5464. try {
  5465. $rows = Db::table('purchase_order')
  5466. ->where('CCYDH', $ccydh)
  5467. ->where('scydgy_id', '>', 0)
  5468. ->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%\')')
  5469. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  5470. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  5471. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,This_quantity,NGZL,pick_company_name,delivery_deadline')
  5472. ->order('id', 'asc')
  5473. ->select();
  5474. } catch (\Throwable $e) {
  5475. $rows = [];
  5476. }
  5477. if (!is_array($rows) || $rows === []) {
  5478. return null;
  5479. }
  5480. $gymc = [];
  5481. $qty = [];
  5482. $first = null;
  5483. foreach ($rows as $r) {
  5484. if (!is_array($r)) {
  5485. continue;
  5486. }
  5487. if ($first === null) {
  5488. $first = $r;
  5489. }
  5490. $g = trim((string)($r['CGYMC'] ?? ''));
  5491. if ($g !== '' && !in_array($g, $gymc, true)) {
  5492. $gymc[] = $g;
  5493. }
  5494. $q = $this->mprocResolveDisplayThisQuantity($r);
  5495. if ($q !== '' && !in_array($q, $qty, true)) {
  5496. $qty[] = $q;
  5497. }
  5498. }
  5499. if (!is_array($first)) {
  5500. return null;
  5501. }
  5502. $dl = trim((string)($first['delivery_deadline'] ?? ''));
  5503. if ($dl !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', str_replace(['/', '.'], '-', $dl), $m)) {
  5504. $dl = $m[1];
  5505. } elseif ($dl !== '' && preg_match('/^0000-00-00/', $dl)) {
  5506. $dl = '';
  5507. }
  5508. $first['CGYMC'] = $gymc !== [] ? implode('、', $gymc) : '';
  5509. $first['order_qty'] = $qty !== [] ? implode('、', $qty) : '';
  5510. $first['delivery_deadline'] = $dl;
  5511. $first['delivery_date'] = '';
  5512. $first['storage_location'] = '';
  5513. $first['delivery_status'] = '';
  5514. $first['delivery_remark'] = '';
  5515. $sids = [];
  5516. foreach ($rows as $r) {
  5517. if (!is_array($r)) {
  5518. continue;
  5519. }
  5520. $sidOne = (int)($r['scydgy_id'] ?? 0);
  5521. if ($sidOne > 0) {
  5522. $sids[$sidOne] = true;
  5523. }
  5524. }
  5525. if ($sids !== []) {
  5526. try {
  5527. $scores = Db::table('purchase_order_inbound_score')
  5528. ->where('scydgy_id', 'in', array_keys($sids))
  5529. ->field('scydgy_id,delivery_status,delivery_date,storage_location,remark')
  5530. ->select();
  5531. } catch (\Throwable $e) {
  5532. try {
  5533. $scores = Db::table('purchase_order_inbound_score')
  5534. ->where('scydgy_id', 'in', array_keys($sids))
  5535. ->field('scydgy_id,delivery_date,storage_location')
  5536. ->select();
  5537. } catch (\Throwable $e2) {
  5538. $scores = [];
  5539. }
  5540. }
  5541. if (is_array($scores)) {
  5542. foreach ($scores as $sc) {
  5543. if (!is_array($sc)) {
  5544. continue;
  5545. }
  5546. $ds = trim((string)($sc['delivery_status'] ?? ''));
  5547. if ($ds !== '' && $first['delivery_status'] === '') {
  5548. $first['delivery_status'] = $ds;
  5549. }
  5550. $dd = trim((string)($sc['delivery_date'] ?? ''));
  5551. if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', str_replace(['/', '.'], '-', $dd), $mdd)
  5552. && $first['delivery_date'] === '') {
  5553. $first['delivery_date'] = $mdd[1];
  5554. }
  5555. $loc = trim((string)($sc['storage_location'] ?? ''));
  5556. if ($loc !== '' && $first['storage_location'] === '') {
  5557. $first['storage_location'] = $loc;
  5558. }
  5559. $rm = trim((string)($sc['remark'] ?? ''));
  5560. if ($rm !== '' && $first['delivery_remark'] === '') {
  5561. $first['delivery_remark'] = $rm;
  5562. }
  5563. }
  5564. }
  5565. }
  5566. return $first;
  5567. }
  5568. protected function mprocBuildInboundscoreNotifyUrl(string $ccydh): string
  5569. {
  5570. $base = rtrim(trim((string)Config::get('mproc.mobile_base_url')), '/');
  5571. if ($base === '' || !preg_match('#^https?://#i', $base)) {
  5572. $base = rtrim((string)$this->request->root(true), '/');
  5573. }
  5574. if ($base === '') {
  5575. throw new \RuntimeException('无法生成通知链接');
  5576. }
  5577. $ccydh = trim($ccydh);
  5578. return $base . '/index.php/index/index/inboundscore' . ($ccydh !== '' ? ('?ccydh=' . rawurlencode($ccydh)) : '');
  5579. }
  5580. /** @deprecated 兼容旧调用,已改跳转质量评分 */
  5581. protected function mprocBuildDeliveryscoreNotifyUrl(string $ccydh): string
  5582. {
  5583. return $this->mprocBuildInboundscoreNotifyUrl($ccydh);
  5584. }
  5585. /**
  5586. * @return array{title:string,content:string}|null
  5587. */
  5588. protected function mprocLoadNotifyTemplateRow(string $scene): ?array
  5589. {
  5590. try {
  5591. $row = Db::table('purchase_sms_template')
  5592. ->where('scene', $scene)
  5593. ->where(function ($q) {
  5594. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  5595. })
  5596. ->order('id', 'asc')
  5597. ->find();
  5598. } catch (\Throwable $e) {
  5599. return null;
  5600. }
  5601. if (!is_array($row) || $row === []) {
  5602. return null;
  5603. }
  5604. return [
  5605. 'title' => trim((string)($row['title'] ?? '')),
  5606. 'content' => trim((string)($row['content'] ?? '')),
  5607. ];
  5608. }
  5609. protected function mprocEnsureArrivalNotifyEmailTemplate(): void
  5610. {
  5611. static $done = false;
  5612. if ($done) {
  5613. return;
  5614. }
  5615. $done = true;
  5616. $content = "您好,{contact_name}:\n\n"
  5617. . "订单已到货,请知悉。\n\n"
  5618. . "订单信息\n"
  5619. . "\t订单号:{ccydh}\n"
  5620. . "\t印件名称:{cyjmc}\n"
  5621. . "\t工序名称:{cgymc}\n"
  5622. . "\t订单数量:{this_quantity}\n"
  5623. . "\t供应商:{supplier_name}\n"
  5624. . "\t交货截止日期:{delivery_deadline}\n\n"
  5625. . "交货信息\n"
  5626. . "\t交货情况:{delivery_status}\n"
  5627. . "\t交货日期:{delivery_date}\n"
  5628. . "\t库位:{storage_location}\n"
  5629. . "\t备注:{remark}\n";
  5630. $title = '订单已到货通知 - {ccydh}';
  5631. $remark = '手机端交货情况-通知质检/业务员已到货;模版名称作邮件主题';
  5632. try {
  5633. $row = Db::table('purchase_sms_template')->where('scene', 'arrival_notify_email')->find();
  5634. } catch (\Throwable $e) {
  5635. return;
  5636. }
  5637. $now = date('Y-m-d H:i:s');
  5638. try {
  5639. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  5640. } catch (\Throwable $e) {
  5641. $cols = [];
  5642. }
  5643. $colNames = [];
  5644. foreach ($cols as $c) {
  5645. if (!is_array($c)) {
  5646. continue;
  5647. }
  5648. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  5649. if ($n !== '') {
  5650. $colNames[$n] = true;
  5651. }
  5652. }
  5653. try {
  5654. if (is_array($row) && $row !== []) {
  5655. $upd = [
  5656. 'title' => $title,
  5657. 'content' => $content,
  5658. 'remark' => $remark,
  5659. 'status' => 1,
  5660. ];
  5661. if (isset($colNames['updatetime'])) {
  5662. $upd['updatetime'] = $now;
  5663. }
  5664. Db::table('purchase_sms_template')
  5665. ->where('id', (int)($row['id'] ?? 0))
  5666. ->update($upd);
  5667. return;
  5668. }
  5669. $data = [
  5670. 'scene' => 'arrival_notify_email',
  5671. 'title' => $title,
  5672. 'content' => $content,
  5673. 'remark' => $remark,
  5674. 'status' => 1,
  5675. ];
  5676. if (isset($colNames['updatetime'])) {
  5677. $data['updatetime'] = $now;
  5678. }
  5679. if (isset($colNames['createtime'])) {
  5680. $data['createtime'] = $now;
  5681. }
  5682. Db::table('purchase_sms_template')->insert($data);
  5683. } catch (\Throwable $e) {
  5684. }
  5685. }
  5686. /** @deprecated 兼容旧调用 */
  5687. protected function mprocEnsureDeliveryNotifyEmailTemplate(): void
  5688. {
  5689. $this->mprocEnsureArrivalNotifyEmailTemplate();
  5690. }
  5691. protected function mprocPlainTextToHtmlEmailBody(string $plain): string
  5692. {
  5693. $esc = htmlspecialchars($plain, ENT_QUOTES, 'UTF-8');
  5694. $esc = preg_replace(
  5695. '#(https?://[^\s<]+)#u',
  5696. '<a href="$1" style="color:#3c8dbc;word-break:break-all;">$1</a>',
  5697. $esc
  5698. );
  5699. $esc = nl2br($esc);
  5700. return '<div style="font-size:14px;line-height:1.7;color:#333;font-family:sans-serif;">' . $esc . '</div>';
  5701. }
  5702. /**
  5703. * @param array<string, mixed> $mailConfig
  5704. */
  5705. protected function mprocSendNotifyEmail(array $mailConfig, string $toEmail, string $toName, string $subject, string $htmlBody, string $excludeCc = ''): void
  5706. {
  5707. $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
  5708. $mail->isSMTP();
  5709. $mail->Host = (string)($mailConfig['host'] ?? '');
  5710. $mail->SMTPAuth = true;
  5711. $mail->Username = (string)($mailConfig['addr'] ?? '');
  5712. $mail->Password = (string)($mailConfig['pass'] ?? '');
  5713. $mail->SMTPSecure = (string)($mailConfig['security'] ?? 'ssl');
  5714. $mail->Port = (int)($mailConfig['port'] ?? 465);
  5715. $mail->CharSet = (string)($mailConfig['charset'] ?? 'utf-8');
  5716. $mail->setFrom((string)($mailConfig['addr'] ?? ''), (string)($mailConfig['name'] ?? '协助采购'));
  5717. $mail->addAddress($toEmail, $toName);
  5718. $ccRaw = trim((string)Config::get('mproc.cc_email'));
  5719. if ($ccRaw !== '') {
  5720. $exclude = strtolower(trim($excludeCc));
  5721. foreach (preg_split('/[,;,;\s]+/', $ccRaw) ?: [] as $piece) {
  5722. $cc = strtolower(trim((string)$piece));
  5723. if ($cc === '' || !filter_var($cc, FILTER_VALIDATE_EMAIL)) {
  5724. continue;
  5725. }
  5726. if ($exclude !== '' && $cc === $exclude) {
  5727. continue;
  5728. }
  5729. $mail->addCC($cc);
  5730. }
  5731. }
  5732. $mail->isHTML(true);
  5733. $mail->Subject = $subject;
  5734. $mail->Body = $htmlBody;
  5735. $mail->send();
  5736. }
  5737. /**
  5738. * @param array<string, mixed> $row
  5739. */
  5740. protected function mprocPersistEmailSendLog(array $row): void
  5741. {
  5742. try {
  5743. $data = [
  5744. 'from_email' => (string)($row['from_email'] ?? ''),
  5745. 'to_email' => (string)($row['to_email'] ?? ''),
  5746. 'send_time' => date('Y-m-d H:i:s'),
  5747. 'scene' => (string)($row['scene'] ?? ''),
  5748. 'ccydh' => (string)($row['ccydh'] ?? ''),
  5749. 'company_name' => (string)($row['company_name'] ?? ''),
  5750. 'mail_subject' => (string)($row['mail_subject'] ?? ''),
  5751. 'status' => (int)($row['status'] ?? 0),
  5752. 'fail_reason' => (string)($row['fail_reason'] ?? ''),
  5753. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  5754. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  5755. 'admin_id' => (int)($row['admin_id'] ?? 0),
  5756. 'admin_name' => (string)($row['admin_name'] ?? ''),
  5757. ];
  5758. Db::table('purchase_email_send_log')->insert($data);
  5759. } catch (\Throwable $e) {
  5760. Log::record('mprocPersistEmailSendLog: ' . $e->getMessage(), 'error');
  5761. }
  5762. }
  5763. /**
  5764. * 质量+交货均完成后,按最新详情重存存证 PDF
  5765. *
  5766. * @param array<int, mixed> $poRows
  5767. */
  5768. protected function mprocRefreshCompletedArchivePdfs(array $poRows): void
  5769. {
  5770. $done = [];
  5771. foreach ($poRows as $po) {
  5772. if (!is_array($po)) {
  5773. continue;
  5774. }
  5775. $sid = (int)($po['scydgy_id'] ?? 0);
  5776. if ($sid <= 0 || isset($done[$sid])) {
  5777. continue;
  5778. }
  5779. $done[$sid] = true;
  5780. try {
  5781. \app\admin\controller\Procuremen::regenerateArchivePdfWithoutAuth($sid, true);
  5782. } catch (\Throwable $e) {
  5783. Log::record('完结存证PDF刷新失败 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  5784. }
  5785. }
  5786. }
  5787. /**
  5788. * @return array<int, array<string, mixed>>
  5789. */
  5790. protected function mprocLoadApprovedPoRowsForScore(string $ccydh, int $sid): array
  5791. {
  5792. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  5793. $approvedIn = implode(',', array_map(static function ($v) {
  5794. return "'" . str_replace("'", "''", (string)$v) . "'";
  5795. }, $approvedVals));
  5796. try {
  5797. $q = Db::table('purchase_order')
  5798. ->where('scydgy_id', '>', 0)
  5799. ->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%\')')
  5800. ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
  5801. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  5802. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  5803. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,delivery_deadline,pick_company_name,pick_time,wflow_status,status');
  5804. if ($ccydh !== '') {
  5805. $q->where('CCYDH', $ccydh);
  5806. } elseif ($sid > 0) {
  5807. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  5808. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  5809. if ($ccydh === '') {
  5810. $this->error('缺少订单号');
  5811. }
  5812. $q->where('CCYDH', $ccydh);
  5813. } else {
  5814. $this->error('缺少订单号');
  5815. }
  5816. $poRows = $q->order('id', 'asc')->select();
  5817. } catch (\Throwable $e) {
  5818. $poRows = [];
  5819. }
  5820. if (!is_array($poRows) || $poRows === []) {
  5821. $this->error('未找到可评分的已审核订单');
  5822. }
  5823. return $poRows;
  5824. }
  5825. /**
  5826. * 操作人展示名:优先后台管理员昵称(名称),避免记成登录账号
  5827. *
  5828. * @param array<string, mixed> $user
  5829. */
  5830. protected function mprocResolveAdminDisplayName(array $user, int $adminId): string
  5831. {
  5832. $adminName = '';
  5833. if ($adminId > 0) {
  5834. try {
  5835. $adminRow = Db::name('admin')->where('id', $adminId)->field('nickname,username')->find();
  5836. if (is_array($adminRow)) {
  5837. $nick = trim((string)($adminRow['nickname'] ?? ''));
  5838. $uname = trim((string)($adminRow['username'] ?? ''));
  5839. if ($nick !== '') {
  5840. $adminName = $nick;
  5841. } elseif ($uname !== '') {
  5842. $adminName = $uname;
  5843. }
  5844. }
  5845. } catch (\Throwable $e) {
  5846. }
  5847. }
  5848. if ($adminName === '') {
  5849. $adminName = trim((string)($user['nickname'] ?? ''));
  5850. }
  5851. if ($adminName === '') {
  5852. $adminName = trim((string)($user['username'] ?? ''));
  5853. }
  5854. return $adminName !== '' ? $adminName : '管理员';
  5855. }
  5856. /**
  5857. * @param array<int, mixed> $poRows
  5858. */
  5859. protected function mprocSyncMonthlyAfterInboundScore(array $poRows, string $now): void
  5860. {
  5861. $companyName = '';
  5862. foreach ($poRows as $po) {
  5863. if (!is_array($po)) {
  5864. continue;
  5865. }
  5866. $companyName = trim((string)($po['pick_company_name'] ?? ''));
  5867. if ($companyName !== '') {
  5868. break;
  5869. }
  5870. }
  5871. $scoreYm = date('Y-m', strtotime($now) ?: time());
  5872. if ($companyName === '') {
  5873. return;
  5874. }
  5875. try {
  5876. \app\common\library\ProcuremenSupplierScore::syncQualityScoreFromInbound($scoreYm, $companyName);
  5877. } catch (\Throwable $e) {
  5878. Log::record('inboundscoresave quality sync: ' . $e->getMessage(), 'error');
  5879. }
  5880. }
  5881. /**
  5882. * @return array<string, mixed>
  5883. */
  5884. protected function mprocRequireAdminUser(): array
  5885. {
  5886. $user = $this->mprocGetUser();
  5887. if (!$user) {
  5888. $this->error('请先登录', url('index/index/login'));
  5889. }
  5890. if (empty($user['is_admin'])) {
  5891. $this->error('仅系统管理员可操作');
  5892. }
  5893. return $user;
  5894. }
  5895. /** 质检中心角色组 id */
  5896. protected function mprocResolveMobileQualityGroupId(): int
  5897. {
  5898. $id = (int)Config::get('mproc.mobile_quality_group_id');
  5899. if ($id > 0) {
  5900. return $id;
  5901. }
  5902. try {
  5903. $found = Db::name('auth_group')
  5904. ->where('name', '质检中心')
  5905. ->where('status', 'normal')
  5906. ->order('id', 'asc')
  5907. ->value('id');
  5908. $id = (int)$found;
  5909. } catch (\Throwable $e) {
  5910. $id = 0;
  5911. }
  5912. return $id > 0 ? $id : 16;
  5913. }
  5914. /** 生产部/生产员角色组 id */
  5915. protected function mprocResolveMobileDeliveryGroupId(): int
  5916. {
  5917. $id = (int)Config::get('mproc.mobile_delivery_group_id');
  5918. if ($id > 0) {
  5919. return $id;
  5920. }
  5921. try {
  5922. $found = Db::name('auth_group')
  5923. ->where('name', 'in', ['生产部', '生产员'])
  5924. ->where('status', 'normal')
  5925. ->order('id', 'asc')
  5926. ->value('id');
  5927. $id = (int)$found;
  5928. } catch (\Throwable $e) {
  5929. $id = 0;
  5930. }
  5931. return $id > 0 ? $id : 15;
  5932. }
  5933. /** 业务员(手机端新增询价)角色组 id */
  5934. protected function mprocResolveMobileRfqGroupId(): int
  5935. {
  5936. $id = (int)Config::get('mproc.mobile_rfq_group_id');
  5937. if ($id <= 0) {
  5938. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  5939. }
  5940. if ($id > 0) {
  5941. return $id;
  5942. }
  5943. try {
  5944. $found = Db::name('auth_group')
  5945. ->where('name', '业务员')
  5946. ->where('status', 'normal')
  5947. ->order('id', 'asc')
  5948. ->value('id');
  5949. $id = (int)$found;
  5950. } catch (\Throwable $e) {
  5951. $id = 0;
  5952. }
  5953. return $id > 0 ? $id : 12;
  5954. }
  5955. /**
  5956. * @return int[]
  5957. */
  5958. protected function mprocAdminGroupIds(int $adminId): array
  5959. {
  5960. if ($adminId <= 0) {
  5961. return [];
  5962. }
  5963. try {
  5964. $ids = Db::name('auth_group_access')->where('uid', $adminId)->column('group_id');
  5965. } catch (\Throwable $e) {
  5966. return [];
  5967. }
  5968. if (!is_array($ids)) {
  5969. return [];
  5970. }
  5971. return array_values(array_unique(array_filter(array_map('intval', $ids))));
  5972. }
  5973. /** 超管(角色组 rules=*)或协同「管理员」组 */
  5974. protected function mprocAdminIsMobileSuper(int $adminId): bool
  5975. {
  5976. if ($adminId <= 0) {
  5977. return false;
  5978. }
  5979. try {
  5980. $rows = Db::name('auth_group_access')
  5981. ->alias('aga')
  5982. ->join('auth_group ag', 'aga.group_id = ag.id')
  5983. ->where('aga.uid', $adminId)
  5984. ->field('ag.id,ag.rules')
  5985. ->select();
  5986. } catch (\Throwable $e) {
  5987. return false;
  5988. }
  5989. if (!is_array($rows)) {
  5990. return false;
  5991. }
  5992. foreach ($rows as $r) {
  5993. if (!is_array($r)) {
  5994. continue;
  5995. }
  5996. if (trim((string)($r['rules'] ?? '')) === '*') {
  5997. return true;
  5998. }
  5999. // 供应链协同「管理员」组
  6000. if ((int)($r['id'] ?? 0) === 11) {
  6001. return true;
  6002. }
  6003. }
  6004. return false;
  6005. }
  6006. /**
  6007. * @param array<string, mixed> $user
  6008. * @param string $role quality|delivery|rfq
  6009. */
  6010. protected function mprocAdminHasMobileRole(array $user, string $role): bool
  6011. {
  6012. if (empty($user['is_admin'])) {
  6013. return false;
  6014. }
  6015. $adminId = (int)($user['admin_id'] ?? 0);
  6016. if ($adminId <= 0) {
  6017. return false;
  6018. }
  6019. if ($this->mprocAdminIsMobileSuper($adminId)) {
  6020. return true;
  6021. }
  6022. $gids = $this->mprocAdminGroupIds($adminId);
  6023. if ($role === 'quality') {
  6024. $need = $this->mprocResolveMobileQualityGroupId();
  6025. return $need > 0 && in_array($need, $gids, true);
  6026. }
  6027. if ($role === 'delivery') {
  6028. $need = $this->mprocResolveMobileDeliveryGroupId();
  6029. return $need > 0 && in_array($need, $gids, true);
  6030. }
  6031. if ($role === 'rfq') {
  6032. $need = $this->mprocResolveMobileRfqGroupId();
  6033. return $need > 0 && in_array($need, $gids, true);
  6034. }
  6035. return false;
  6036. }
  6037. /**
  6038. * @return array<string, mixed>
  6039. */
  6040. protected function mprocRequireRfqUser(): array
  6041. {
  6042. $user = $this->mprocRequireAdminUser();
  6043. if (!$this->mprocAdminHasMobileRole($user, 'rfq')) {
  6044. $this->error('仅业务员账号可新增订单询价');
  6045. }
  6046. return $user;
  6047. }
  6048. /**
  6049. * @return array<string, mixed>
  6050. */
  6051. protected function mprocRequireQualityUser(): array
  6052. {
  6053. $user = $this->mprocRequireAdminUser();
  6054. if (!$this->mprocAdminHasMobileRole($user, 'quality')) {
  6055. $this->error('仅质检中心账号可操作质量评分');
  6056. }
  6057. return $user;
  6058. }
  6059. /**
  6060. * @return array<string, mixed>
  6061. */
  6062. protected function mprocRequireDeliveryUser(): array
  6063. {
  6064. $user = $this->mprocRequireAdminUser();
  6065. if (!$this->mprocAdminHasMobileRole($user, 'delivery')) {
  6066. $this->error('仅生产部账号可操作交货情况');
  6067. }
  6068. return $user;
  6069. }
  6070. protected function mprocEnsureInboundScoreTable(): void
  6071. {
  6072. static $ok = false;
  6073. if ($ok) {
  6074. return;
  6075. }
  6076. try {
  6077. Db::query('SELECT 1 FROM `purchase_order_inbound_score` LIMIT 1');
  6078. } catch (\Throwable $e) {
  6079. try {
  6080. Db::execute("CREATE TABLE IF NOT EXISTS `purchase_order_inbound_score` (
  6081. `id` int unsigned NOT NULL AUTO_INCREMENT,
  6082. `scydgy_id` int NOT NULL DEFAULT 0 COMMENT '工序ID',
  6083. `purchase_order_id` int unsigned NOT NULL DEFAULT 0 COMMENT 'purchase_order.id',
  6084. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  6085. `cyjmc` varchar(255) NOT NULL DEFAULT '' COMMENT '印件名称',
  6086. `cgymc` varchar(255) NOT NULL DEFAULT '' COMMENT '工序名称',
  6087. `company_name` varchar(255) NOT NULL DEFAULT '' COMMENT '中标供应商',
  6088. `result` varchar(16) NOT NULL DEFAULT '' COMMENT '合格/不合格',
  6089. `delivery_status` varchar(16) NOT NULL DEFAULT '' COMMENT '交货情况 准时/滞后',
  6090. `delivery_date` date DEFAULT NULL COMMENT '交货日期',
  6091. `storage_location` varchar(64) NOT NULL DEFAULT '' COMMENT '库位',
  6092. `customer_complaint` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '客户是否投诉 1=是',
  6093. `complaint_remark` varchar(500) NOT NULL DEFAULT '' COMMENT '投诉说明',
  6094. `order_interrupt` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '订单是否中断 1=是',
  6095. `admin_id` int unsigned NOT NULL DEFAULT 0,
  6096. `admin_name` varchar(64) NOT NULL DEFAULT '',
  6097. `delivery_admin_id` int unsigned NOT NULL DEFAULT 0 COMMENT '交货确认人ID',
  6098. `delivery_admin_name` varchar(64) NOT NULL DEFAULT '' COMMENT '交货确认人',
  6099. `remark` varchar(500) NOT NULL DEFAULT '',
  6100. `createtime` datetime DEFAULT NULL,
  6101. `updatetime` datetime DEFAULT NULL,
  6102. PRIMARY KEY (`id`),
  6103. UNIQUE KEY `uk_scydgy_id` (`scydgy_id`),
  6104. KEY `idx_ccydh` (`ccydh`),
  6105. KEY `idx_result` (`result`),
  6106. KEY `idx_updatetime` (`updatetime`)
  6107. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='质量评分'");
  6108. } catch (\Throwable $e2) {
  6109. Log::record('mprocEnsureInboundScoreTable: ' . $e2->getMessage(), 'error');
  6110. return;
  6111. }
  6112. }
  6113. foreach ([
  6114. 'delivery_status' => "ADD COLUMN `delivery_status` varchar(16) NOT NULL DEFAULT '' COMMENT '交货情况 准时/滞后' AFTER `result`",
  6115. 'delivery_date' => "ADD COLUMN `delivery_date` date DEFAULT NULL COMMENT '交货日期' AFTER `delivery_status`",
  6116. 'storage_location' => "ADD COLUMN `storage_location` varchar(64) NOT NULL DEFAULT '' COMMENT '库位' AFTER `delivery_date`",
  6117. 'customer_complaint' => "ADD COLUMN `customer_complaint` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '客户是否投诉 1=是' AFTER `storage_location`",
  6118. 'complaint_remark' => "ADD COLUMN `complaint_remark` varchar(500) NOT NULL DEFAULT '' COMMENT '投诉说明' AFTER `customer_complaint`",
  6119. 'order_interrupt' => "ADD COLUMN `order_interrupt` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '订单是否中断 1=是' AFTER `complaint_remark`",
  6120. 'delivery_admin_id' => "ADD COLUMN `delivery_admin_id` int unsigned NOT NULL DEFAULT 0 COMMENT '交货确认人ID' AFTER `admin_name`",
  6121. 'delivery_admin_name'=> "ADD COLUMN `delivery_admin_name` varchar(64) NOT NULL DEFAULT '' COMMENT '交货确认人' AFTER `delivery_admin_id`",
  6122. 'arrival_notify_staff' => "ADD COLUMN `arrival_notify_staff` varchar(500) NOT NULL DEFAULT '' COMMENT '已到货已通知人员' AFTER `delivery_admin_name`",
  6123. 'arrival_notify_time' => "ADD COLUMN `arrival_notify_time` datetime DEFAULT NULL COMMENT '已到货通知时间' AFTER `arrival_notify_staff`",
  6124. ] as $col => $ddl) {
  6125. try {
  6126. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_inbound_score` LIKE '{$col}'");
  6127. if (!is_array($cols) || $cols === []) {
  6128. Db::execute("ALTER TABLE `purchase_order_inbound_score` {$ddl}");
  6129. }
  6130. } catch (\Throwable $e) {
  6131. Log::record("mprocEnsureInboundScoreTable {$col}: " . $e->getMessage(), 'error');
  6132. }
  6133. }
  6134. $ok = true;
  6135. }
  6136. /**
  6137. * 质量评分列表:按订单号合并(一单一行,工序顿号合并)
  6138. * tab=pending 待评分;scored 已评分(仅当前管理员操作过的)
  6139. *
  6140. * @return array<int, array<string, mixed>>
  6141. */
  6142. protected function mprocLoadInboundScoreRows(string $tab, string $keyword = '', int $adminId = 0, string $scope = 'quality'): array
  6143. {
  6144. $this->mprocEnsureInboundScoreTable();
  6145. $keyword = trim($keyword);
  6146. $scope = $scope === 'delivery' ? 'delivery' : 'quality';
  6147. if (!in_array($tab, ['pending', 'scored', 'pass', 'fail'], true)) {
  6148. $tab = 'pending';
  6149. }
  6150. if ($tab === 'pass' || $tab === 'fail') {
  6151. $tab = 'scored';
  6152. }
  6153. try {
  6154. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  6155. $approvedIn = implode(',', array_map(static function ($v) {
  6156. return "'" . str_replace("'", "''", (string)$v) . "'";
  6157. }, $approvedVals));
  6158. $poRows = Db::table('purchase_order')
  6159. ->where('scydgy_id', '>', 0)
  6160. ->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%\')')
  6161. ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
  6162. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  6163. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  6164. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CCLBMMC,CDW,This_quantity,NGZL,delivery_deadline,pick_company_name,pick_time,wflow_status,status')
  6165. ->order('pick_time', 'desc')
  6166. ->order('id', 'asc')
  6167. ->limit(800)
  6168. ->select();
  6169. } catch (\Throwable $e) {
  6170. Log::record('mprocLoadInboundScoreRows: ' . $e->getMessage(), 'error');
  6171. return [];
  6172. }
  6173. if (!is_array($poRows) || $poRows === []) {
  6174. return [];
  6175. }
  6176. $sids = [];
  6177. foreach ($poRows as $po) {
  6178. if (!is_array($po)) {
  6179. continue;
  6180. }
  6181. $sid = (int)($po['scydgy_id'] ?? 0);
  6182. if ($sid > 0) {
  6183. $sids[$sid] = true;
  6184. }
  6185. }
  6186. $scoreMap = [];
  6187. if ($sids !== []) {
  6188. try {
  6189. $scores = Db::table('purchase_order_inbound_score')
  6190. ->where('scydgy_id', 'in', array_keys($sids))
  6191. ->field('scydgy_id,result,delivery_status,delivery_date,storage_location,customer_complaint,complaint_remark,order_interrupt,remark,admin_id,admin_name,delivery_admin_id,delivery_admin_name,arrival_notify_staff,arrival_notify_time,updatetime,createtime')
  6192. ->select();
  6193. } catch (\Throwable $e) {
  6194. try {
  6195. $scores = Db::table('purchase_order_inbound_score')
  6196. ->where('scydgy_id', 'in', array_keys($sids))
  6197. ->field('scydgy_id,result,delivery_status,delivery_date,storage_location,customer_complaint,complaint_remark,order_interrupt,remark,admin_id,admin_name,delivery_admin_id,delivery_admin_name,updatetime,createtime')
  6198. ->select();
  6199. } catch (\Throwable $e2) {
  6200. try {
  6201. $scores = Db::table('purchase_order_inbound_score')
  6202. ->where('scydgy_id', 'in', array_keys($sids))
  6203. ->field('scydgy_id,result,delivery_status,delivery_date,customer_complaint,complaint_remark,order_interrupt,remark,admin_id,admin_name,updatetime,createtime')
  6204. ->select();
  6205. } catch (\Throwable $e3) {
  6206. try {
  6207. $scores = Db::table('purchase_order_inbound_score')
  6208. ->where('scydgy_id', 'in', array_keys($sids))
  6209. ->field('scydgy_id,result,delivery_status,customer_complaint,order_interrupt,remark,admin_id,admin_name,updatetime,createtime')
  6210. ->select();
  6211. } catch (\Throwable $e4) {
  6212. $scores = [];
  6213. }
  6214. }
  6215. }
  6216. }
  6217. if (is_array($scores)) {
  6218. foreach ($scores as $sc) {
  6219. if (!is_array($sc)) {
  6220. continue;
  6221. }
  6222. $sid = (int)($sc['scydgy_id'] ?? 0);
  6223. if ($sid > 0) {
  6224. $scoreMap[$sid] = $sc;
  6225. }
  6226. }
  6227. }
  6228. }
  6229. /** @var array<string, array<string, mixed>> $groups */
  6230. $groups = [];
  6231. foreach ($poRows as $po) {
  6232. if (!is_array($po)) {
  6233. continue;
  6234. }
  6235. $sid = (int)($po['scydgy_id'] ?? 0);
  6236. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  6237. if ($sid <= 0 || $ccydh === '') {
  6238. continue;
  6239. }
  6240. if (!isset($groups[$ccydh])) {
  6241. $pickRaw = trim((string)($po['pick_time'] ?? ''));
  6242. $pickDisp = $pickRaw !== '' ? \app\common\library\ProcuremenTime::formatDisplayDateTime($pickRaw) : '';
  6243. $groups[$ccydh] = [
  6244. 'CCYDH' => $ccydh,
  6245. 'scydgy_id' => $sid,
  6246. 'scydgy_ids' => [],
  6247. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  6248. 'CCLBMMC' => trim((string)($po['CCLBMMC'] ?? '')),
  6249. 'CGYMC_list' => [],
  6250. 'qty_list' => [],
  6251. 'pick_company_name' => trim((string)($po['pick_company_name'] ?? '')),
  6252. 'pick_time' => $pickDisp !== '' ? $pickDisp : $pickRaw,
  6253. 'pick_time_raw' => $pickRaw,
  6254. 'process_count' => 0,
  6255. 'results' => [],
  6256. 'score_admin_ids' => [],
  6257. 'score_time_raw' => '',
  6258. 'score_operator' => '',
  6259. 'quality_operator' => '',
  6260. 'customer_complaint'=> 0,
  6261. 'complaint_remark' => '',
  6262. 'order_interrupt' => 0,
  6263. 'delivery_status' => '',
  6264. 'delivery_date' => '',
  6265. 'delivery_deadline' => '',
  6266. 'storage_location' => '',
  6267. 'remark' => '',
  6268. 'arrival_notify_staff' => '',
  6269. 'arrival_notify_time' => '',
  6270. ];
  6271. }
  6272. $g = &$groups[$ccydh];
  6273. $g['scydgy_ids'][] = $sid;
  6274. $g['process_count']++;
  6275. if ($g['scydgy_id'] <= 0) {
  6276. $g['scydgy_id'] = $sid;
  6277. }
  6278. if ($g['CYJMC'] === '') {
  6279. $g['CYJMC'] = trim((string)($po['CYJMC'] ?? ''));
  6280. }
  6281. if ($g['CCLBMMC'] === '') {
  6282. $g['CCLBMMC'] = trim((string)($po['CCLBMMC'] ?? ''));
  6283. }
  6284. if ($g['pick_company_name'] === '') {
  6285. $g['pick_company_name'] = trim((string)($po['pick_company_name'] ?? ''));
  6286. }
  6287. if ($g['delivery_deadline'] === '') {
  6288. $g['delivery_deadline'] = $this->mprocFormatYmdValue($po['delivery_deadline'] ?? $po['Delivery_deadline'] ?? '');
  6289. }
  6290. $pt = trim((string)($po['pick_time'] ?? ''));
  6291. if ($pt !== '' && ($g['pick_time_raw'] === '' || strcmp($pt, $g['pick_time_raw']) > 0)) {
  6292. $g['pick_time_raw'] = $pt;
  6293. $disp = \app\common\library\ProcuremenTime::formatDisplayDateTime($pt);
  6294. $g['pick_time'] = $disp !== '' ? $disp : $pt;
  6295. }
  6296. $gymc = trim((string)($po['CGYMC'] ?? ''));
  6297. if ($gymc !== '' && !in_array($gymc, $g['CGYMC_list'], true)) {
  6298. $g['CGYMC_list'][] = $gymc;
  6299. }
  6300. $qDisp = $this->mprocResolveDisplayThisQuantity($po);
  6301. if ($qDisp !== '' && !in_array($qDisp, $g['qty_list'], true)) {
  6302. $g['qty_list'][] = $qDisp;
  6303. }
  6304. $sc = $scoreMap[$sid] ?? null;
  6305. $res = is_array($sc) ? trim((string)($sc['result'] ?? '')) : '';
  6306. $g['results'][] = $res;
  6307. if (is_array($sc)) {
  6308. $ns = trim((string)($sc['arrival_notify_staff'] ?? ''));
  6309. if ($ns !== '') {
  6310. $g['arrival_notify_staff'] = $this->mprocMergeArrivalNotifyStaffNames(
  6311. (string)($g['arrival_notify_staff'] ?? ''),
  6312. preg_split('/[、,,;;]+/u', $ns) ?: []
  6313. );
  6314. }
  6315. $nt = trim((string)($sc['arrival_notify_time'] ?? ''));
  6316. if ($nt !== '' && ((string)($g['arrival_notify_time'] ?? '') === '' || strcmp($nt, (string)$g['arrival_notify_time']) > 0)) {
  6317. $g['arrival_notify_time'] = $nt;
  6318. }
  6319. }
  6320. if (is_array($sc) && $res !== '') {
  6321. $aid = (int)($sc['admin_id'] ?? 0);
  6322. if ($aid > 0) {
  6323. $g['score_admin_ids'][$aid] = true;
  6324. }
  6325. $qOp = trim((string)($sc['admin_name'] ?? ''));
  6326. if ($qOp !== '') {
  6327. $g['quality_operator'] = $qOp;
  6328. }
  6329. if ((int)($sc['customer_complaint'] ?? 0) === 1) {
  6330. $g['customer_complaint'] = 1;
  6331. }
  6332. $crm = trim((string)($sc['complaint_remark'] ?? ''));
  6333. if ($crm !== '' && $g['complaint_remark'] === '') {
  6334. $g['complaint_remark'] = $crm;
  6335. }
  6336. if ((int)($sc['order_interrupt'] ?? 0) === 1) {
  6337. $g['order_interrupt'] = 1;
  6338. }
  6339. $ds = trim((string)($sc['delivery_status'] ?? ''));
  6340. if ($ds !== '' && $g['delivery_status'] === '') {
  6341. $g['delivery_status'] = $ds;
  6342. }
  6343. if ($ds !== '' && $g['score_operator'] === '') {
  6344. $op = trim((string)($sc['delivery_admin_name'] ?? ''));
  6345. if ($op === '') {
  6346. $op = trim((string)($sc['admin_name'] ?? ''));
  6347. }
  6348. if ($op !== '') {
  6349. $g['score_operator'] = $op;
  6350. }
  6351. }
  6352. $dd = trim((string)($sc['delivery_date'] ?? ''));
  6353. if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dd, $mdd) && $g['delivery_date'] === '') {
  6354. $g['delivery_date'] = $mdd[1];
  6355. }
  6356. $loc = trim((string)($sc['storage_location'] ?? ''));
  6357. if ($loc !== '' && $g['storage_location'] === '') {
  6358. $g['storage_location'] = $loc;
  6359. }
  6360. $rm = trim((string)($sc['remark'] ?? ''));
  6361. if ($rm !== '' && $g['remark'] === '') {
  6362. $g['remark'] = $rm;
  6363. }
  6364. $st = trim((string)($sc['updatetime'] ?? ''));
  6365. if ($st === '') {
  6366. $st = trim((string)($sc['createtime'] ?? ''));
  6367. }
  6368. if ($st !== '' && ($g['score_time_raw'] === '' || strcmp($st, $g['score_time_raw']) > 0)) {
  6369. $g['score_time_raw'] = $st;
  6370. $op = trim((string)($sc['delivery_admin_name'] ?? ''));
  6371. if ($op === '') {
  6372. $op = trim((string)($sc['admin_name'] ?? ''));
  6373. }
  6374. if ($op !== '') {
  6375. $g['score_operator'] = $op;
  6376. }
  6377. }
  6378. } elseif (is_array($sc)) {
  6379. // 仅填了交货、尚未质量评分
  6380. $ds = trim((string)($sc['delivery_status'] ?? ''));
  6381. if ($ds !== '' && $g['delivery_status'] === '') {
  6382. $g['delivery_status'] = $ds;
  6383. }
  6384. if ($ds !== '' && $g['score_operator'] === '') {
  6385. $op = trim((string)($sc['delivery_admin_name'] ?? ''));
  6386. if ($op === '') {
  6387. $op = trim((string)($sc['admin_name'] ?? ''));
  6388. }
  6389. if ($op !== '') {
  6390. $g['score_operator'] = $op;
  6391. }
  6392. }
  6393. $dd = trim((string)($sc['delivery_date'] ?? ''));
  6394. if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dd, $mdd) && $g['delivery_date'] === '') {
  6395. $g['delivery_date'] = $mdd[1];
  6396. }
  6397. $loc = trim((string)($sc['storage_location'] ?? ''));
  6398. if ($loc !== '' && $g['storage_location'] === '') {
  6399. $g['storage_location'] = $loc;
  6400. }
  6401. $rm = trim((string)($sc['remark'] ?? ''));
  6402. if ($rm !== '' && $g['remark'] === '') {
  6403. $g['remark'] = $rm;
  6404. }
  6405. $st = trim((string)($sc['updatetime'] ?? ''));
  6406. if ($st === '') {
  6407. $st = trim((string)($sc['createtime'] ?? ''));
  6408. }
  6409. if ($st !== '' && ($g['score_time_raw'] === '' || strcmp($st, $g['score_time_raw']) > 0)) {
  6410. $g['score_time_raw'] = $st;
  6411. $op = trim((string)($sc['delivery_admin_name'] ?? ''));
  6412. if ($op === '') {
  6413. $op = trim((string)($sc['admin_name'] ?? ''));
  6414. }
  6415. if ($op !== '') {
  6416. $g['score_operator'] = $op;
  6417. }
  6418. }
  6419. }
  6420. unset($g);
  6421. }
  6422. $out = [];
  6423. foreach ($groups as $ccydh => $g) {
  6424. $gymcList = is_array($g['CGYMC_list'] ?? null) ? $g['CGYMC_list'] : [];
  6425. $company = (string)($g['pick_company_name'] ?? '');
  6426. $cyjmc = (string)($g['CYJMC'] ?? '');
  6427. if ($keyword !== '') {
  6428. $blob = $ccydh . ' ' . $cyjmc . ' ' . implode('、', $gymcList) . ' ' . $company;
  6429. if (mb_stripos($blob, $keyword) === false) {
  6430. continue;
  6431. }
  6432. }
  6433. $results = is_array($g['results'] ?? null) ? $g['results'] : [];
  6434. $uniq = [];
  6435. $allScored = true;
  6436. foreach ($results as $r) {
  6437. $r = trim((string)$r);
  6438. if ($r === '') {
  6439. $allScored = false;
  6440. continue;
  6441. }
  6442. $uniq[$r] = true;
  6443. }
  6444. $orderResult = '';
  6445. if ($allScored && count($uniq) === 1) {
  6446. $keys = array_keys($uniq);
  6447. $orderResult = (string)($keys[0] ?? '');
  6448. } elseif ($allScored && count($uniq) > 1) {
  6449. $orderResult = '';
  6450. }
  6451. $deliveryStatus = trim((string)($g['delivery_status'] ?? ''));
  6452. $hasDelivery = ($deliveryStatus === '准时' || $deliveryStatus === '滞后');
  6453. if ($scope === 'quality') {
  6454. if ($tab === 'pending' && $orderResult !== '') {
  6455. continue;
  6456. }
  6457. if ($tab === 'scored') {
  6458. if ($orderResult !== '合格' && $orderResult !== '不合格') {
  6459. continue;
  6460. }
  6461. if ($adminId <= 0) {
  6462. continue;
  6463. }
  6464. $adminIds = is_array($g['score_admin_ids'] ?? null) ? $g['score_admin_ids'] : [];
  6465. if (empty($adminIds[$adminId])) {
  6466. continue;
  6467. }
  6468. }
  6469. } else {
  6470. // 交货:待评=尚未填准时/滞后;已评=已填
  6471. if ($tab === 'pending' && $hasDelivery) {
  6472. continue;
  6473. }
  6474. if ($tab === 'scored' && !$hasDelivery) {
  6475. continue;
  6476. }
  6477. }
  6478. $scoreTimeRaw = trim((string)($g['score_time_raw'] ?? ''));
  6479. if ($scoreTimeRaw === '') {
  6480. $scoreTime = '';
  6481. } elseif ($scope === 'delivery') {
  6482. // 交货确认列表:操作时间仅年月日
  6483. $scoreTime = $this->mprocFormatYmdValue($scoreTimeRaw);
  6484. } else {
  6485. $scoreTime = \app\common\library\ProcuremenTime::formatDisplayDateTime($scoreTimeRaw);
  6486. }
  6487. $qtyList = is_array($g['qty_list'] ?? null) ? $g['qty_list'] : [];
  6488. $out[] = [
  6489. 'CCYDH' => $ccydh,
  6490. 'scydgy_id' => (int)($g['scydgy_id'] ?? 0),
  6491. 'scydgy_ids' => array_values(array_unique(array_map('intval', $g['scydgy_ids'] ?? []))),
  6492. 'CYJMC' => $cyjmc,
  6493. 'CGYMC' => $gymcList !== [] ? implode('、', $gymcList) : '',
  6494. 'CCLBMMC' => (string)($g['CCLBMMC'] ?? ''),
  6495. 'pick_company_name' => $company,
  6496. 'pick_time' => (string)($g['pick_time'] ?? ''),
  6497. 'score_time' => $scoreTime !== '' ? $scoreTime : $scoreTimeRaw,
  6498. 'score_time_raw' => $scoreTimeRaw,
  6499. 'score_operator' => $scope === 'quality'
  6500. ? (string)($g['quality_operator'] ?? '')
  6501. : (string)($g['score_operator'] ?? ''),
  6502. 'process_count' => (int)($g['process_count'] ?? 0),
  6503. 'order_qty' => $qtyList !== [] ? implode('、', $qtyList) : '',
  6504. 'result' => $orderResult,
  6505. 'customer_complaint' => (int)($g['customer_complaint'] ?? 0),
  6506. 'complaint_remark' => (string)($g['complaint_remark'] ?? ''),
  6507. 'order_interrupt' => (int)($g['order_interrupt'] ?? 0),
  6508. 'delivery_status' => (string)($g['delivery_status'] ?? ''),
  6509. 'delivery_date' => (string)($g['delivery_date'] ?? ''),
  6510. 'delivery_deadline' => (string)($g['delivery_deadline'] ?? ''),
  6511. 'storage_location' => (string)($g['storage_location'] ?? ''),
  6512. 'remark' => (string)($g['remark'] ?? ''),
  6513. 'arrival_notify_staff' => (string)($g['arrival_notify_staff'] ?? ''),
  6514. 'arrival_notify_time' => (string)($g['arrival_notify_time'] ?? ''),
  6515. ];
  6516. }
  6517. usort($out, static function ($a, $b) use ($tab) {
  6518. if ($tab === 'scored') {
  6519. $ta = (string)($a['score_time_raw'] ?? '');
  6520. $tb = (string)($b['score_time_raw'] ?? '');
  6521. if ($ta !== $tb) {
  6522. return strcmp($tb, $ta);
  6523. }
  6524. }
  6525. $ta = (string)($a['pick_time'] ?? '');
  6526. $tb = (string)($b['pick_time'] ?? '');
  6527. if ($ta !== $tb) {
  6528. return strcmp($tb, $ta);
  6529. }
  6530. return strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  6531. });
  6532. return $out;
  6533. }
  6534. /**
  6535. * 业务员:新增订单询价页
  6536. */
  6537. public function rfqadd()
  6538. {
  6539. $user = $this->mprocGetUser();
  6540. if (!$user) {
  6541. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  6542. $safe = $this->mprocSanitizeRedirectUrl($uri);
  6543. if ($safe !== '') {
  6544. Session::set('mproc_intended_url', $safe);
  6545. }
  6546. $this->redirect($this->mprocBuildLoginUrl($safe));
  6547. return;
  6548. }
  6549. if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'rfq')) {
  6550. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  6551. if ($jump === '') {
  6552. $this->mprocDropCurrentLogin();
  6553. $this->redirect(url('index/index/login'));
  6554. return;
  6555. }
  6556. $this->redirect($jump);
  6557. return;
  6558. }
  6559. $profile = $this->mprocProfileForUser($user);
  6560. $defaultDept = trim((string)($profile['department'] ?? ''));
  6561. if ($defaultDept === '' || $defaultDept === '业务员' || $defaultDept === '管理员') {
  6562. $defaultDept = '营销中心';
  6563. }
  6564. $statusTab = trim((string)$this->request->get('status', 'pending'));
  6565. if ($statusTab !== 'quoted') {
  6566. $statusTab = 'pending';
  6567. }
  6568. $focusSid = (int)$this->request->param('focus_sid', 0);
  6569. if ($focusSid >= 0) {
  6570. $focusSid = 0;
  6571. }
  6572. $this->view->assign('mprocProfile', $profile);
  6573. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  6574. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  6575. $this->view->assign('nextOrderCcydh', $this->mprocAllocateManualOrderCcydh());
  6576. $this->view->assign('defaultCclbmmc', $defaultDept);
  6577. $this->view->assign('adminNickname', trim((string)($profile['contact_name'] ?? '')) ?: '业务员');
  6578. $this->view->assign('rfqDeptOptions', $this->mprocLoadRfqDeptNameOptions());
  6579. $this->view->assign('rfqStatusTab', $statusTab);
  6580. $this->view->assign('rfqFocusSid', $focusSid);
  6581. $this->view->assign('rows', $this->mprocLoadRfqAddRows($user, '', $statusTab));
  6582. return $this->view->fetch();
  6583. }
  6584. /**
  6585. * 业务员询价列表 JSON(本人发起或被通知)
  6586. * GET:q、status=pending|quoted
  6587. */
  6588. public function rfqaddlist()
  6589. {
  6590. $user = $this->mprocRequireRfqUser();
  6591. $q = trim((string)$this->request->get('q', ''));
  6592. $status = trim((string)$this->request->get('status', 'pending'));
  6593. if ($status !== 'quoted') {
  6594. $status = 'pending';
  6595. }
  6596. $rows = $this->mprocLoadRfqAddRows($user, $q, $status);
  6597. $this->success('ok', null, ['rows' => $rows, 'total' => count($rows), 'status' => $status]);
  6598. }
  6599. /**
  6600. * 业务员查看询价报价(供应商 + 单价)
  6601. * GET:scydgy_id
  6602. */
  6603. public function rfqaddquotes()
  6604. {
  6605. $user = $this->mprocRequireRfqUser();
  6606. $sid = (int)$this->request->param('scydgy_id', 0);
  6607. if ($sid >= 0) {
  6608. $this->error('仅支持手工询价单');
  6609. }
  6610. $po = $this->mprocLoadAccessibleRfqOrder($user, $sid);
  6611. if (!$po) {
  6612. $this->error('询价单不存在或无权查看');
  6613. }
  6614. $list = [];
  6615. try {
  6616. $rows = Db::table('purchase_order_detail')
  6617. ->where('scydgy_id', $sid)
  6618. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  6619. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')')
  6620. ->field('id,company_name,amount')
  6621. ->order('id', 'asc')
  6622. ->select();
  6623. } catch (\Throwable $e) {
  6624. try {
  6625. $rows = Db::table('purchase_order_detail')
  6626. ->where('scydgy_id', $sid)
  6627. ->field('id,company_name,amount')
  6628. ->order('id', 'asc')
  6629. ->select();
  6630. } catch (\Throwable $e2) {
  6631. $rows = [];
  6632. }
  6633. }
  6634. if (!is_array($rows)) {
  6635. $rows = [];
  6636. }
  6637. foreach ($rows as $row) {
  6638. if (!is_array($row)) {
  6639. continue;
  6640. }
  6641. $amount = trim((string)($row['amount'] ?? ''));
  6642. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  6643. $list[] = [
  6644. 'company_name' => trim((string)($row['company_name'] ?? '')),
  6645. 'amount' => $amount,
  6646. 'amount_text' => $isQuoted ? $amount : '',
  6647. 'is_quoted' => $isQuoted,
  6648. ];
  6649. }
  6650. $this->success('ok', null, [
  6651. 'scydgy_id' => $sid,
  6652. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  6653. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  6654. 'list' => $list,
  6655. ]);
  6656. }
  6657. /**
  6658. * 业务员提交新增订单询价
  6659. * POST:CYJMC、CCLBMMC、CGYMC、CDW、This_quantity、ceilingPrice、CDF、MBZ
  6660. */
  6661. public function rfqaddsave()
  6662. {
  6663. $user = $this->mprocRequireRfqUser();
  6664. if (!$this->request->isPost()) {
  6665. $this->error('请使用 POST');
  6666. }
  6667. $profile = $this->mprocProfileForUser($user);
  6668. $cyjmc = trim((string)$this->request->post('CYJMC', ''));
  6669. $cgymc = trim((string)$this->request->post('CGYMC', ''));
  6670. $cclbmmc = trim((string)$this->request->post('CCLBMMC', ''));
  6671. if ($cyjmc === '') {
  6672. $this->error('请填写印件名称');
  6673. }
  6674. if ($cclbmmc === '') {
  6675. $cclbmmc = trim((string)($profile['department'] ?? ''));
  6676. }
  6677. if ($cclbmmc === '') {
  6678. $cclbmmc = '营销中心';
  6679. }
  6680. $cywyxm = trim((string)($profile['contact_name'] ?? ''));
  6681. if ($cywyxm === '') {
  6682. $cywyxm = trim((string)($user['username'] ?? ''));
  6683. }
  6684. $now = date('Y-m-d H:i:s');
  6685. $lockName = 'procuremen_manual_order_alloc';
  6686. if (!$this->mprocAcquireNamedLock($lockName, 10)) {
  6687. $this->error('系统繁忙,请稍后重试');
  6688. }
  6689. try {
  6690. $ccydh = $this->mprocAllocateManualOrderCcydh();
  6691. $sid = $this->mprocAllocateManualScydgyId();
  6692. $data = [
  6693. 'scydgy_id' => $sid,
  6694. 'CCYDH' => $ccydh,
  6695. 'CYJMC' => $cyjmc,
  6696. 'CGYMC' => $cgymc,
  6697. 'CCLBMMC' => $cclbmmc,
  6698. 'CDW' => trim((string)$this->request->post('CDW', '')),
  6699. 'NGZL' => '',
  6700. 'CDF' => trim((string)$this->request->post('CDF', '')),
  6701. 'cGzzxMc' => '',
  6702. 'MBZ' => trim((string)$this->request->post('MBZ', '')),
  6703. 'cywyxm' => $cywyxm,
  6704. 'notify_salesman' => '',
  6705. 'rfq_salesman_notified' => 0,
  6706. 'rfq_salesman_notify_time' => null,
  6707. 'This_quantity' => trim((string)$this->request->post('This_quantity', '')),
  6708. 'ceilingPrice' => trim((string)$this->request->post('ceilingPrice', '')),
  6709. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  6710. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6711. 'createtime' => $now,
  6712. 'dStamp' => $now,
  6713. 'dputrecord' => $now,
  6714. ];
  6715. try {
  6716. $this->mprocEnsureRfqSalesmanColumns();
  6717. Db::table('purchase_order')->insert($data);
  6718. } catch (\Throwable $e) {
  6719. $this->error('新增失败:' . $e->getMessage());
  6720. }
  6721. $nextCcydh = $this->mprocAllocateManualOrderCcydh();
  6722. } finally {
  6723. $this->mprocReleaseNamedLock($lockName);
  6724. }
  6725. $this->success('新增成功', '', [
  6726. 'scydgy_id' => $sid,
  6727. 'CCYDH' => $ccydh,
  6728. 'nextOrderCcydh' => $nextCcydh,
  6729. ]);
  6730. }
  6731. /**
  6732. * MySQL 命名锁(跨连接防并发撞号)
  6733. */
  6734. protected function mprocAcquireNamedLock(string $name, int $timeoutSec = 10): bool
  6735. {
  6736. $name = trim($name);
  6737. if ($name === '') {
  6738. return false;
  6739. }
  6740. try {
  6741. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  6742. $rows = Db::query('SELECT GET_LOCK(\'' . $nameSql . '\', ' . max(1, $timeoutSec) . ') AS locked');
  6743. if (!is_array($rows) || $rows === []) {
  6744. return false;
  6745. }
  6746. $v = $rows[0]['locked'] ?? $rows[0]['LOCKED'] ?? null;
  6747. return (int)$v === 1;
  6748. } catch (\Throwable $e) {
  6749. return false;
  6750. }
  6751. }
  6752. protected function mprocReleaseNamedLock(string $name): void
  6753. {
  6754. $name = trim($name);
  6755. if ($name === '') {
  6756. return;
  6757. }
  6758. try {
  6759. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  6760. Db::query('SELECT RELEASE_LOCK(\'' . $nameSql . '\')');
  6761. } catch (\Throwable $e) {
  6762. }
  6763. }
  6764. protected function mprocAllocateManualScydgyId(): int
  6765. {
  6766. try {
  6767. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  6768. $min = (int)$min;
  6769. return $min < 0 ? $min - 1 : -1;
  6770. } catch (\Throwable $e) {
  6771. return -1;
  6772. }
  6773. }
  6774. /**
  6775. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  6776. * 调用方须在命名锁内执行,避免并发重复
  6777. */
  6778. protected function mprocAllocateManualOrderCcydh(): string
  6779. {
  6780. $prefix = 'YW' . date('Ymd');
  6781. $maxSeq = 0;
  6782. try {
  6783. $rows = Db::table('purchase_order')
  6784. ->where('CCYDH', 'like', $prefix . '%')
  6785. ->column('CCYDH');
  6786. if (is_array($rows)) {
  6787. foreach ($rows as $ccydh) {
  6788. $ccydh = trim((string)$ccydh);
  6789. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3,})$/', $ccydh, $m)) {
  6790. $maxSeq = max($maxSeq, (int)$m[1]);
  6791. }
  6792. }
  6793. }
  6794. } catch (\Throwable $e) {
  6795. }
  6796. $next = $maxSeq + 1;
  6797. $width = $next > 999 ? strlen((string)$next) : 3;
  6798. return $prefix . str_pad((string)$next, $width, '0', STR_PAD_LEFT);
  6799. }
  6800. /**
  6801. * @return string[]
  6802. */
  6803. protected function mprocLoadRfqDeptNameOptions(): array
  6804. {
  6805. $out = [];
  6806. try {
  6807. $vals = Db::table('mcyd')
  6808. ->where('CCLBMMC', '<>', '')
  6809. ->whereNotNull('CCLBMMC')
  6810. ->distinct(true)
  6811. ->limit(300)
  6812. ->column('CCLBMMC');
  6813. } catch (\Throwable $e) {
  6814. $vals = [];
  6815. }
  6816. if (is_array($vals)) {
  6817. foreach ($vals as $v) {
  6818. $v = trim((string)$v);
  6819. if ($v === '' || isset($out[$v])) {
  6820. continue;
  6821. }
  6822. $out[$v] = $v;
  6823. }
  6824. }
  6825. try {
  6826. $poVals = Db::table('purchase_order')
  6827. ->where('CCLBMMC', '<>', '')
  6828. ->whereNotNull('CCLBMMC')
  6829. ->distinct(true)
  6830. ->limit(200)
  6831. ->column('CCLBMMC');
  6832. } catch (\Throwable $e) {
  6833. $poVals = [];
  6834. }
  6835. if (is_array($poVals)) {
  6836. foreach ($poVals as $v) {
  6837. $v = trim((string)$v);
  6838. if ($v === '' || isset($out[$v])) {
  6839. continue;
  6840. }
  6841. $out[$v] = $v;
  6842. }
  6843. }
  6844. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  6845. if (!isset($out[$preset])) {
  6846. $out[$preset] = $preset;
  6847. }
  6848. }
  6849. $list = array_values($out);
  6850. usort($list, static function ($a, $b) {
  6851. $weight = [
  6852. '营销中心' => 1,
  6853. '业务部' => 2,
  6854. '市场部' => 3,
  6855. '外贸部' => 4,
  6856. '新华技术业务部' => 5,
  6857. ];
  6858. $wa = $weight[$a] ?? 100;
  6859. $wb = $weight[$b] ?? 100;
  6860. if ($wa !== $wb) {
  6861. return $wa <=> $wb;
  6862. }
  6863. return strcmp((string)$a, (string)$b);
  6864. });
  6865. return $list;
  6866. }
  6867. protected function mprocEnsureRfqSalesmanColumns(): void
  6868. {
  6869. static $ok = false;
  6870. if ($ok) {
  6871. return;
  6872. }
  6873. $alters = [
  6874. 'notify_salesman' => "ADD COLUMN `notify_salesman` varchar(500) NOT NULL DEFAULT '' COMMENT '通知业务员' AFTER `cywyxm`",
  6875. 'rfq_salesman_notified' => "ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '是否已通知业务员' AFTER `notify_salesman`",
  6876. 'rfq_salesman_notify_time' => "ADD COLUMN `rfq_salesman_notify_time` datetime DEFAULT NULL COMMENT '通知业务员时间' AFTER `rfq_salesman_notified`",
  6877. ];
  6878. foreach ($alters as $col => $sql) {
  6879. try {
  6880. $exists = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  6881. if (is_array($exists) && $exists !== []) {
  6882. continue;
  6883. }
  6884. Db::execute('ALTER TABLE `purchase_order` ' . $sql);
  6885. } catch (\Throwable $e) {
  6886. }
  6887. }
  6888. $ok = true;
  6889. }
  6890. /**
  6891. * 校验业务员是否可访问该手工询价单
  6892. *
  6893. * @param array<string, mixed> $user
  6894. * @return array<string, mixed>|null
  6895. */
  6896. protected function mprocLoadAccessibleRfqOrder(array $user, int $sid): ?array
  6897. {
  6898. if ($sid >= 0) {
  6899. return null;
  6900. }
  6901. $profile = $this->mprocProfileForUser($user);
  6902. $adminName = trim((string)($profile['contact_name'] ?? ''));
  6903. if ($adminName === '') {
  6904. $adminName = trim((string)($user['username'] ?? ''));
  6905. }
  6906. $isSuper = $this->mprocAdminIsMobileSuper((int)($user['admin_id'] ?? 0));
  6907. $this->mprocEnsureRfqSalesmanColumns();
  6908. try {
  6909. $query = Db::table('purchase_order')
  6910. ->where('scydgy_id', $sid)
  6911. ->whereRaw(
  6912. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  6913. );
  6914. if (!$isSuper) {
  6915. if ($adminName === '') {
  6916. return null;
  6917. }
  6918. $query->where(function ($q2) use ($adminName) {
  6919. $q2->where('cywyxm', $adminName)
  6920. ->whereOr('notify_salesman', $adminName)
  6921. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  6922. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  6923. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  6924. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  6925. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  6926. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  6927. });
  6928. }
  6929. $row = $query->find();
  6930. } catch (\Throwable $e) {
  6931. return null;
  6932. }
  6933. return is_array($row) ? $row : null;
  6934. }
  6935. /**
  6936. * 手机端业务员询价列表(本人发起 / 被通知)
  6937. *
  6938. * @param array<string, mixed> $user
  6939. * @param string $status pending|quoted|''(空=全部)
  6940. * @return array<int, array<string, mixed>>
  6941. */
  6942. protected function mprocLoadRfqAddRows(array $user, string $q, string $status = ''): array
  6943. {
  6944. $profile = $this->mprocProfileForUser($user);
  6945. $adminName = trim((string)($profile['contact_name'] ?? ''));
  6946. if ($adminName === '') {
  6947. $adminName = trim((string)($user['username'] ?? ''));
  6948. }
  6949. $isSuper = $this->mprocAdminIsMobileSuper((int)($user['admin_id'] ?? 0));
  6950. $this->mprocEnsureRfqSalesmanColumns();
  6951. try {
  6952. $query = Db::table('purchase_order')
  6953. ->where('scydgy_id', '<', 0)
  6954. ->whereRaw(
  6955. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  6956. );
  6957. if (!$isSuper) {
  6958. if ($adminName === '') {
  6959. return [];
  6960. }
  6961. $query->where(function ($q2) use ($adminName) {
  6962. $q2->where('cywyxm', $adminName)
  6963. ->whereOr('notify_salesman', $adminName)
  6964. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  6965. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  6966. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  6967. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  6968. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  6969. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  6970. });
  6971. }
  6972. $q = trim($q);
  6973. if ($q !== '') {
  6974. $like = '%' . str_replace(['%', '_'], ['\\%', '\\_'], $q) . '%';
  6975. $query->where(function ($q2) use ($like) {
  6976. $q2->where('CCYDH', 'like', $like)
  6977. ->whereOr('CYJMC', 'like', $like)
  6978. ->whereOr('CGYMC', 'like', $like)
  6979. ->whereOr('CCLBMMC', 'like', $like)
  6980. ->whereOr('MBZ', 'like', $like);
  6981. });
  6982. }
  6983. $rows = $query
  6984. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,CDW,CDF,This_quantity,ceilingPrice,cywyxm,MBZ,status,wflow_status,rfq_salesman_notified,createtime,dStamp')
  6985. ->order('id', 'desc')
  6986. ->limit(200)
  6987. ->select();
  6988. } catch (\Throwable $e) {
  6989. $rows = [];
  6990. }
  6991. if (!is_array($rows)) {
  6992. $rows = [];
  6993. }
  6994. $out = [];
  6995. $sids = [];
  6996. foreach ($rows as $r) {
  6997. if (!is_array($r)) {
  6998. continue;
  6999. }
  7000. $sid = (int)($r['scydgy_id'] ?? 0);
  7001. if ($sid < 0) {
  7002. $sids[$sid] = $sid;
  7003. }
  7004. }
  7005. $quotedMap = $this->mprocLoadRfqQuotedSidMap(array_values($sids));
  7006. $status = trim($status);
  7007. if ($status !== 'pending' && $status !== 'quoted') {
  7008. $status = '';
  7009. }
  7010. foreach ($rows as $r) {
  7011. if (!is_array($r)) {
  7012. continue;
  7013. }
  7014. $sid = (int)($r['scydgy_id'] ?? 0);
  7015. $isQuoted = !empty($quotedMap[$sid]);
  7016. if ($status === 'pending' && $isQuoted) {
  7017. continue;
  7018. }
  7019. if ($status === 'quoted' && !$isQuoted) {
  7020. continue;
  7021. }
  7022. $created = trim((string)($r['createtime'] ?? ''));
  7023. if ($created === '' || stripos($created, '0000-00-00') === 0) {
  7024. $created = trim((string)($r['dStamp'] ?? ''));
  7025. }
  7026. if (preg_match('/^\d{10,}$/', $created)) {
  7027. $created = date('Y-m-d H:i:s', (int)$created);
  7028. }
  7029. if ($created !== '' && stripos($created, '0000-00-00') === 0) {
  7030. $created = '';
  7031. }
  7032. $out[] = [
  7033. 'id' => (int)($r['id'] ?? 0),
  7034. 'scydgy_id' => $sid,
  7035. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  7036. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  7037. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  7038. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  7039. 'CDW' => trim((string)($r['CDW'] ?? '')),
  7040. 'CDF' => trim((string)($r['CDF'] ?? '')),
  7041. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  7042. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  7043. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  7044. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  7045. 'progress_text' => $isQuoted ? '已报价' : '待询价',
  7046. 'createtime' => $created,
  7047. ];
  7048. }
  7049. return $out;
  7050. }
  7051. /**
  7052. * 哪些手工询价单已有有效报价(amount 非空且非 0)
  7053. *
  7054. * @param array<int, int> $sids
  7055. * @return array<int, bool>
  7056. */
  7057. protected function mprocLoadRfqQuotedSidMap(array $sids): array
  7058. {
  7059. $out = [];
  7060. $sids = array_values(array_unique(array_filter(array_map('intval', $sids), static function ($v) {
  7061. return $v < 0;
  7062. })));
  7063. if ($sids === []) {
  7064. return $out;
  7065. }
  7066. foreach (array_chunk($sids, 200) as $chunk) {
  7067. try {
  7068. $rows = Db::table('purchase_order_detail')
  7069. ->where('scydgy_id', 'in', $chunk)
  7070. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  7071. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')')
  7072. ->where('amount', '<>', '')
  7073. ->whereNotNull('amount')
  7074. ->where('amount', '<>', '0')
  7075. ->where('amount', '<>', '0.00')
  7076. ->field('scydgy_id')
  7077. ->group('scydgy_id')
  7078. ->select();
  7079. } catch (\Throwable $e) {
  7080. try {
  7081. $rows = Db::table('purchase_order_detail')
  7082. ->where('scydgy_id', 'in', $chunk)
  7083. ->where('amount', '<>', '')
  7084. ->whereNotNull('amount')
  7085. ->where('amount', '<>', '0')
  7086. ->where('amount', '<>', '0.00')
  7087. ->field('scydgy_id')
  7088. ->group('scydgy_id')
  7089. ->select();
  7090. } catch (\Throwable $e2) {
  7091. $rows = [];
  7092. }
  7093. }
  7094. if (!is_array($rows)) {
  7095. continue;
  7096. }
  7097. foreach ($rows as $r) {
  7098. if (!is_array($r)) {
  7099. continue;
  7100. }
  7101. $sid = (int)($r['scydgy_id'] ?? 0);
  7102. if ($sid < 0) {
  7103. $out[$sid] = true;
  7104. }
  7105. }
  7106. }
  7107. return $out;
  7108. }
  7109. /**
  7110. * @param array<string, mixed> $row
  7111. */
  7112. protected function mprocFormatRfqProgressText(array $row): string
  7113. {
  7114. $sid = (int)($row['scydgy_id'] ?? 0);
  7115. if ($sid < 0) {
  7116. $map = $this->mprocLoadRfqQuotedSidMap([$sid]);
  7117. if (!empty($map[$sid])) {
  7118. return '已报价';
  7119. }
  7120. }
  7121. return '待询价';
  7122. }
  7123. }