| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708 |
- <?php
- namespace app\index\controller;
- use app\common\controller\Frontend;
- use app\common\library\ProcuremenSchema;
- use app\common\library\ProcuremenStatus;
- use think\Cache;
- use think\captcha\Captcha;
- use think\Config;
- use think\Cookie;
- use think\Db;
- use think\Log;
- use think\Session;
- use think\Validate;
- /**
- * 手机端:协助明细(purchase_order_detail)验证码 / 账号密码登录 + 列表
- * 普通用户(customer):登录后进报价列表,可填单价/交期
- * 质检中心:登录后进「质量评分」(合格/投诉/中断)
- * 生产部(生产员):登录后进「交货情况」(准时/滞后)
- * 业务员:登录后进「新增订单询价」
- */
- class Index extends Frontend
- {
- protected $noNeedLogin = ['*'];
- protected $noNeedRight = ['*'];
- protected $layout = '';
- /** @var int 登录态有效天数 */
- protected $mprocTtlSeconds = 0;
- /** @var array<string, string>|null purchase_order_detail 表字段:小写 => 真实列名 */
- protected static $mprocProcuremenColumns = null;
- public function _initialize()
- {
- parent::_initialize();
- if (is_file(APP_PATH . 'extra/mproc.php')) {
- Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
- }
- $hours = (int)Config::get('mproc.session_hours');
- if ($hours > 0) {
- $this->mprocTtlSeconds = max(1, min(720, $hours)) * 3600;
- } else {
- $days = (int)(Config::get('mproc.session_days') ?: 3);
- $days = max(1, min(30, $days));
- $this->mprocTtlSeconds = $days * 86400;
- }
- if (PHP_VERSION_ID >= 70300) {
- ini_set('session.cookie_lifetime', (string)$this->mprocTtlSeconds);
- ini_set('session.gc_maxlifetime', (string)$this->mprocTtlSeconds);
- }
- try {
- ProcuremenSchema::ensureAll();
- } catch (\Throwable $e) {
- }
- }
- /**
- * 手机端:HTML 错误不用框架跳转页(哭脸倒计时),改为普通 Toast 后跳转;Ajax/JSON 仍走原逻辑
- *
- * @param mixed $msg
- * @param string $url
- * @param mixed $data
- * @param int $wait
- * @param array $header
- * @return void
- */
- protected function error($msg = '', $url = null, $data = '', $wait = 3, array $header = [])
- {
- $type = method_exists($this, 'getResponseType') ? (string)$this->getResponseType() : 'html';
- if (strtolower($type) === 'html') {
- if ($url === null || $url === '') {
- $url = (string)url('index/index/index');
- } elseif ($url !== '' && strpos((string)$url, '://') === false && strpos((string)$url, '/') !== 0
- && strpos((string)$url, 'javascript:') !== 0) {
- $url = (string)\think\Url::build((string)$url);
- }
- if (is_string($url) && stripos($url, 'javascript:') === 0) {
- $url = (string)url('index/index/index');
- }
- $html = $this->view->fetch('toast_tip', [
- 'toastMsg' => (string)$msg,
- 'redirectUrl' => (string)$url,
- 'waitMs' => max(1000, ((int)$wait) * 1000),
- ]);
- $response = \think\Response::create($html, 'html', 200)->header($header);
- throw new \think\exception\HttpResponseException($response);
- }
- parent::error($msg, $url, $data, $wait, $header);
- }
- /** 登录有效小时数(用于前端 localStorage 过期时间) */
- protected function mprocKeepHours(): int
- {
- return max(1, (int)round($this->mprocTtlSeconds / 3600));
- }
- /**
- * 当前手机端登录用户;未登录返回 null(支持 Cookie 令牌 + 7 天记住登录)
- */
- protected function mprocGetUser()
- {
- $token = $this->mprocReadTokenFromRequest();
- if ($token !== '') {
- $user = $this->mprocLoadUserByToken($token);
- if ($user) {
- $token = $this->mprocTouchLoginState($user, $token);
- $user['token'] = $token;
- return $user;
- }
- }
- $user = $this->mprocUserFromRememberCookie();
- if (!$user) {
- return null;
- }
- $token = $this->mprocPackSignedAuthToken($user);
- $token = $this->mprocTouchLoginState($user, $token);
- $user['token'] = $token;
- return $user;
- }
- protected function mprocReadTokenFromRequest(): string
- {
- $token = Session::get('mproc_token');
- if ($token === null || $token === '') {
- $token = Cookie::get('mproc_token');
- }
- if ($token === null || $token === '') {
- $token = $this->request->header('X-Mproc-Token');
- }
- if ($token === null || $token === '') {
- $token = $this->request->request('mproc_token', '');
- }
- $token = trim((string)$token);
- if ($token === '') {
- return '';
- }
- if ($this->mprocIsSignedAuthToken($token)) {
- return $token;
- }
- $token = preg_replace('/[^a-f0-9]/i', '', $token);
- return strlen($token) >= 16 ? $token : '';
- }
- protected function mprocIsSignedAuthToken(string $token): bool
- {
- return strpos($token, '.') !== false
- && preg_match('/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/', $token) === 1;
- }
- protected function mprocAuthCacheKey(string $token): string
- {
- return 'mproc_u_' . md5($token);
- }
- /**
- * @return array<string, mixed>|null
- */
- protected function mprocLoadUserByToken(string $token): ?array
- {
- if ($this->mprocIsSignedAuthToken($token)) {
- if ($this->mprocIsAuthTokenRevoked($token)) {
- return null;
- }
- $user = $this->mprocUserFromSignedToken($token);
- if (!$user) {
- return null;
- }
- if (time() - (int)($user['login_time'] ?? 0) > $this->mprocTtlSeconds) {
- $this->mprocClearLogin($token);
- return null;
- }
- $user['token'] = $token;
- return $user;
- }
- $user = Cache::get('mproc_u_' . $token);
- if (!is_array($user)) {
- $user = $this->mprocUserFromRememberCookie();
- if (!$user) {
- return null;
- }
- }
- if (empty($user['phone']) && empty($user['account']) && empty($user['username'])) {
- return null;
- }
- if (time() - (int)($user['login_time'] ?? 0) > $this->mprocTtlSeconds) {
- $this->mprocClearLogin($token);
- return null;
- }
- $user['token'] = $token;
- return $user;
- }
- /**
- * 滑动续期:刷新签名令牌 / Cache / Session / Cookie(保留 7 天)
- *
- * @param array<string, mixed> $user
- */
- protected function mprocTouchLoginState(array $user, string $token): string
- {
- $user['login_time'] = time();
- if ($this->mprocIsSignedAuthToken($token)) {
- $token = $this->mprocPackSignedAuthToken($user);
- }
- Cache::set($this->mprocAuthCacheKey($token), $user, $this->mprocTtlSeconds + 86400);
- if (!$this->mprocIsSignedAuthToken($token)) {
- Cache::set('mproc_u_' . $token, $user, $this->mprocTtlSeconds + 86400);
- }
- Session::set('mproc_token', $token);
- $this->mprocSetTokenCookie($token);
- $this->mprocSetRememberCookie($user, $token);
- return $token;
- }
- /**
- * @return array<string, mixed>
- */
- protected function mprocCookieOptions(): array
- {
- $opts = [
- 'expire' => $this->mprocTtlSeconds,
- 'path' => '/',
- 'httponly' => true,
- ];
- if ($this->request->isSsl()) {
- $opts['secure'] = true;
- }
- if (PHP_VERSION_ID >= 70300) {
- $opts['samesite'] = 'Lax';
- }
- return $opts;
- }
- protected function mprocSetTokenCookie(string $token): void
- {
- Cookie::set('mproc_token', $token, $this->mprocCookieOptions());
- }
- /**
- * @param array<string, mixed> $user
- */
- protected function mprocSetRememberCookie(array $user, ?string $token = null): void
- {
- $val = $token !== null && $token !== '' ? $token : $this->mprocPackSignedAuthToken($user);
- Cookie::set('mproc_remember', $val, $this->mprocCookieOptions());
- }
- protected function mprocAuthSignSecret(): string
- {
- $key = trim((string)Config::get('mproc.auth_sign_key'));
- if ($key === '') {
- $key = (string)Config::get('database.database') . '|' . (string)Config::get('database.hostname') . '|mproc';
- }
- return hash('sha256', $key);
- }
- /**
- * @param array<string, mixed> $user
- */
- protected function mprocPackSignedAuthToken(array $user): string
- {
- $payload = [
- 'uid' => (int)($user['customer_user_id'] ?? $user['customer_id'] ?? 0),
- 'phone' => trim((string)($user['phone'] ?? '')),
- 'uname' => trim((string)($user['username'] ?? $user['account'] ?? '')),
- 'admin' => !empty($user['is_admin']) ? 1 : 0,
- 'lt' => time(),
- ];
- $b64 = rtrim(strtr(base64_encode(json_encode($payload, JSON_UNESCAPED_UNICODE)), '+/', '-_'), '=');
- $sig = hash_hmac('sha256', $b64, $this->mprocAuthSignSecret());
- return $b64 . '.' . $sig;
- }
- /** @deprecated 使用 mprocPackSignedAuthToken */
- protected function mprocPackRememberCookie(array $user): string
- {
- return $this->mprocPackSignedAuthToken($user);
- }
- /**
- * @return array<string, mixed>|null
- */
- protected function mprocUserFromSignedToken(string $raw): ?array
- {
- $parts = explode('.', trim($raw), 2);
- if (count($parts) !== 2) {
- return null;
- }
- $b64 = $parts[0];
- $sig = $parts[1];
- if (!hash_equals(hash_hmac('sha256', $b64, $this->mprocAuthSignSecret()), $sig)) {
- return null;
- }
- $pad = strlen($b64) % 4;
- if ($pad > 0) {
- $b64 .= str_repeat('=', 4 - $pad);
- }
- $json = base64_decode(strtr($b64, '-_', '+/'), true);
- if ($json === false || $json === '') {
- return null;
- }
- $payload = json_decode($json, true);
- if (!is_array($payload)) {
- return null;
- }
- $lt = (int)($payload['lt'] ?? 0);
- if ($lt <= 0 || time() - $lt > $this->mprocTtlSeconds) {
- return null;
- }
- return $this->mprocRebuildUserFromRememberPayload($payload, $lt);
- }
- /**
- * @return array<string, mixed>|null
- */
- protected function mprocUserFromRememberCookie(): ?array
- {
- $raw = Cookie::get('mproc_remember');
- if ($raw === null || $raw === '') {
- $raw = Cookie::get('mproc_token');
- }
- if ($raw === null || $raw === '') {
- return null;
- }
- $raw = (string)$raw;
- if ($this->mprocIsAuthTokenRevoked($raw)) {
- return null;
- }
- return $this->mprocUserFromSignedToken($raw);
- }
- /**
- * @param array<string, mixed> $payload
- * @return array<string, mixed>|null
- */
- protected function mprocRebuildUserFromRememberPayload(array $payload, int $loginTime): ?array
- {
- if (!empty($payload['admin'])) {
- $uname = trim((string)($payload['uname'] ?? ''));
- if ($uname === '') {
- return null;
- }
- try {
- $row = Db::name('admin')->where('username', $uname)->find();
- } catch (\Throwable $e) {
- $row = null;
- }
- if (!is_array($row) || ($row['status'] ?? '') === 'hidden') {
- return null;
- }
- return [
- 'phone' => trim((string)($row['mobile'] ?? '')),
- 'company_name' => '',
- 'username' => $uname,
- 'customer_user_id' => 0,
- 'admin_id' => (int)($row['id'] ?? 0),
- 'login_type' => 'remember',
- 'is_admin' => 1,
- 'login_time' => $loginTime,
- ];
- }
- $cid = (int)($payload['uid'] ?? 0);
- if ($cid > 0) {
- try {
- $cu = Db::table('customer')->where('id', $cid)->find();
- } catch (\Throwable $e) {
- $cu = null;
- }
- if (is_array($cu) && $cu !== [] && $this->mprocCustomerUserActive($cu)) {
- $user = $this->mprocLoginPayloadFromCustomer($cu, 'remember');
- $user['login_time'] = $loginTime;
- return $user;
- }
- }
- $phone = trim((string)($payload['phone'] ?? ''));
- if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
- $cu = $this->mprocFindCustomerUserByMobile($phone);
- if ($cu) {
- $user = $this->mprocLoginPayloadFromCustomer($cu, 'remember');
- $user['login_time'] = $loginTime;
- return $user;
- }
- }
- return null;
- }
- protected function mprocAuthRevokeCacheKey(string $token): string
- {
- return 'mproc_revoked_' . md5($token);
- }
- protected function mprocRevokeAuthToken(string $token): void
- {
- $token = trim($token);
- if ($token === '') {
- return;
- }
- try {
- Cache::set($this->mprocAuthRevokeCacheKey($token), 1, $this->mprocTtlSeconds + 86400);
- } catch (\Throwable $e) {
- }
- }
- protected function mprocIsAuthTokenRevoked(string $token): bool
- {
- $token = trim($token);
- if ($token === '') {
- return false;
- }
- try {
- return (bool)Cache::get($this->mprocAuthRevokeCacheKey($token));
- } catch (\Throwable $e) {
- return false;
- }
- }
- /**
- * 按与写入时相同的 path/secure/samesite 清除 Cookie,避免仅 delete 时删不掉
- */
- protected function mprocExpireAuthCookies(): void
- {
- $opts = $this->mprocCookieOptions();
- $opts['expire'] = -3600;
- try {
- Cookie::set('mproc_token', '', $opts);
- Cookie::set('mproc_remember', '', $opts);
- } catch (\Throwable $e) {
- }
- try {
- Cookie::delete('mproc_token');
- Cookie::delete('mproc_remember');
- } catch (\Throwable $e) {
- }
- unset($_COOKIE['mproc_token'], $_COOKIE['mproc_remember']);
- $prefix = (string)Config::get('cookie.prefix');
- if ($prefix !== '') {
- unset($_COOKIE[$prefix . 'mproc_token'], $_COOKIE[$prefix . 'mproc_remember']);
- }
- }
- protected function mprocClearLogin($token)
- {
- $token = trim((string)($token ?? ''));
- if ($token !== '') {
- $this->mprocRevokeAuthToken($token);
- try {
- Cache::rm($this->mprocAuthCacheKey($token));
- } catch (\Throwable $e) {
- }
- if (!$this->mprocIsSignedAuthToken($token)) {
- try {
- Cache::rm('mproc_u_' . $token);
- } catch (\Throwable $e) {
- }
- }
- }
- // 同时作废 remember / 另一份 cookie 里可能残留的签名令牌
- foreach (['mproc_token', 'mproc_remember'] as $ck) {
- $raw = Cookie::get($ck);
- if ($raw !== null && $raw !== '' && (string)$raw !== $token) {
- $this->mprocRevokeAuthToken((string)$raw);
- }
- }
- Session::delete('mproc_token');
- $this->mprocExpireAuthCookies();
- }
- /**
- * 登录成功后的回跳地址校验(仅允许本站手机端首页 / 入库评分页,防止开放重定向)
- *
- * @param string $raw GET/POST 的 redirect 或当前 REQUEST_URI
- */
- protected function mprocSanitizeRedirectUrl($raw)
- {
- $s = str_replace(["\r", "\n", "\0"], '', trim((string)$raw));
- if ($s === '') {
- return '';
- }
- if (preg_match('#^https?://#i', $s)) {
- $h = parse_url($s, PHP_URL_HOST);
- if (!is_string($h) || strcasecmp($h, (string)$this->request->host()) !== 0) {
- return '';
- }
- $path = parse_url($s, PHP_URL_PATH);
- $query = parse_url($s, PHP_URL_QUERY);
- $s = (is_string($path) && $path !== '' ? $path : '/');
- if (is_string($query) && $query !== '') {
- $s .= '?' . $query;
- }
- }
- if (strpos($s, '://') !== false) {
- return '';
- }
- if ($s === '' || ($s[0] !== '/' && stripos($s, 'index.php') !== 0)) {
- return '';
- }
- if ($s[0] !== '/') {
- $s = '/' . ltrim($s, '/');
- }
- if (strpos($s, '//') === 0) {
- return '';
- }
- $okHome = stripos($s, 'index/index/index') !== false;
- $okInbound = stripos($s, 'index/index/inboundscore') !== false;
- $okDelivery = stripos($s, 'index/index/deliveryscore') !== false;
- $okRfqAdd = stripos($s, 'index/index/rfqadd') !== false;
- $okNote = stripos($s, 'index/index/deliverynote') !== false;
- if (!$okHome && !$okInbound && !$okDelivery && !$okRfqAdd && !$okNote) {
- return '';
- }
- if (stripos($s, 'index/index/login') !== false) {
- return '';
- }
- return $s;
- }
- protected function mprocRememberFocusEid(int $focusEid): void
- {
- if ($focusEid > 0) {
- Session::set('mproc_focus_eid', $focusEid);
- }
- }
- protected function mprocPullSessionFocusEid(): int
- {
- $fe = (int)Session::get('mproc_focus_eid', 0);
- if ($fe > 0) {
- Session::delete('mproc_focus_eid');
- }
- return $fe;
- }
- /**
- * 从 URI/query 中解析 focus_eid(兼容邮件客户端把 &focus_eid 拼进上一参数值的情况)
- */
- protected function mprocParseFocusEidFromUriString(string $uri): int
- {
- if ($uri === '' || stripos($uri, 'focus_eid') === false) {
- return 0;
- }
- if (preg_match('/(?:[?&;]|%26)(?:amp;)*focus_eid=(\d+)/i', $uri, $m)) {
- return (int)$m[1];
- }
- $query = parse_url($uri, PHP_URL_QUERY);
- if (!is_string($query) || $query === '') {
- return 0;
- }
- $q = [];
- parse_str($query, $q);
- if (!is_array($q)) {
- return 0;
- }
- if (isset($q['focus_eid'])) {
- $fe = (int)$q['focus_eid'];
- if ($fe > 0) {
- return $fe;
- }
- }
- foreach ($q as $k => $v) {
- $blob = (is_string($k) ? $k : '') . '=' . (is_scalar($v) ? (string)$v : '');
- if (preg_match('/(?:^|[?&;]|%26)(?:amp;)*focus_eid=(\d+)/i', $blob, $m2)) {
- return (int)$m2[1];
- }
- }
- return 0;
- }
- /**
- * 从请求中读取短信/邮件直达明细 ID(兼容 query、pathinfo、REQUEST_URI、登录回跳 Session)
- */
- protected function mprocReadFocusEidFromRequest(): int
- {
- $fe = (int)$this->request->param('focus_eid', 0);
- if ($fe > 0) {
- $this->mprocRememberFocusEid($fe);
- return $fe;
- }
- $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
- $fe = $this->mprocParseFocusEidFromUriString($uri);
- if ($fe > 0) {
- $this->mprocRememberFocusEid($fe);
- return $fe;
- }
- $fe = (int)Session::get('mproc_focus_eid', 0);
- if ($fe > 0) {
- return $fe;
- }
- return 0;
- }
- /**
- * 手机端登录页 URL。注意:勿用 url('...login', ['redirect'=>]),在 url_html_suffix 下会把参数拼进 PATHINFO 导致 404。
- *
- * @param string $redirectPath 已通过 {@see mprocSanitizeRedirectUrl} 的回跳路径(含 query),空则不带参数
- */
- protected function mprocBuildLoginUrl($redirectPath = '')
- {
- $root = rtrim($this->request->root(), '/');
- $path = '/index/index/login';
- $rp = trim((string)$redirectPath);
- if ($rp === '') {
- return $root . $path;
- }
- return $root . $path . '?' . http_build_query(['redirect' => $rp], '', '&', PHP_QUERY_RFC3986);
- }
- /**
- * 登录成功后跳转到订单首页:用当前入口 {@see Request::root} 拼 URL,并从原 redirect 中只保留白名单 query(避免子目录部署丢参、开放重定向)
- *
- * @param string $redirectPathOrUrl 已通过 {@see mprocSanitizeRedirectUrl} 的路径或完整 URL(可含 ?focus_eid=)
- */
- protected function mprocBuildAfterLoginIndexUrl($redirectPathOrUrl)
- {
- $raw = trim((string)$redirectPathOrUrl);
- if ($raw === '') {
- return url('index/index/index', '', '', true);
- }
- $queryStr = '';
- if (preg_match('#^https?://#i', $raw)) {
- $pq = parse_url($raw);
- $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
- } elseif (isset($raw[0]) && $raw[0] === '/') {
- $pq = parse_url('http://127.0.0.1' . $raw);
- $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
- } else {
- $pq = parse_url('http://127.0.0.1/' . ltrim($raw, '/'));
- $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
- }
- $q = [];
- if ($queryStr !== '') {
- parse_str($queryStr, $q);
- if (!is_array($q)) {
- $q = [];
- }
- }
- $allowed = [];
- $fe = 0;
- if (isset($q['focus_eid'])) {
- $fe = (int)$q['focus_eid'];
- }
- if ($fe <= 0) {
- $fe = $this->mprocParseFocusEidFromUriString($raw);
- }
- if ($fe <= 0) {
- $fe = (int)Session::get('mproc_focus_eid', 0);
- }
- if ($fe > 0) {
- $allowed['focus_eid'] = $fe;
- $this->mprocRememberFocusEid($fe);
- }
- $mt = isset($q['main_tab']) ? trim((string)$q['main_tab']) : '';
- if ($mt === 'me' || $mt === 'orders') {
- $allowed['main_tab'] = $mt;
- }
- $tb = isset($q['tab']) ? trim((string)$q['tab']) : '';
- if ($tb === 'me' || in_array($this->mprocNormalizeListTab($tb), $this->mprocListTabWhitelist(), true)) {
- $allowed['tab'] = ($tb === 'me') ? 'me' : $this->mprocNormalizeListTab($tb);
- }
- if (isset($q['q']) && trim((string)$q['q']) !== '') {
- $allowed['q'] = substr(trim((string)$q['q']), 0, 120);
- }
- if (isset($allowed['focus_eid']) && !isset($allowed['main_tab'])) {
- $allowed['main_tab'] = 'orders';
- }
- $base = rtrim($this->request->root(true), '/');
- $path = '/index/index/index';
- if (isset($allowed['focus_eid']) && (int)$allowed['focus_eid'] > 0 && !isset($allowed['q'])) {
- $fe = (int)$allowed['focus_eid'];
- if (!isset($allowed['tab']) && (!isset($allowed['main_tab']) || $allowed['main_tab'] === 'orders')) {
- return $base . $path . '?focus_eid=' . $fe . '#mproc_fe=' . $fe;
- }
- $ordered = ['focus_eid' => $fe];
- if (isset($allowed['tab'])) {
- $ordered['tab'] = $allowed['tab'];
- }
- if (isset($allowed['main_tab'])) {
- $ordered['main_tab'] = $allowed['main_tab'];
- }
- return $base . $path . '?' . http_build_query($ordered, '', '&', PHP_QUERY_RFC3986) . '#mproc_fe=' . $fe;
- }
- $qs = $allowed !== [] ? ('?' . http_build_query($allowed, '', '&', PHP_QUERY_RFC3986)) : '';
- return $base . $path . $qs;
- }
- /**
- * 按登录身份决定首页:供应商→报价;质检→质量评分;生产→交货情况
- * 后台账号无手机端角色时返回空串(勿回登录页,避免 302 死循环)
- *
- * @param array<string, mixed> $user
- * @param string $redirectPathOrUrl
- */
- protected function mprocBuildAfterLoginHomeUrl(array $user, $redirectPathOrUrl = '')
- {
- if (!empty($user['is_admin'])) {
- $canQuality = $this->mprocAdminHasMobileRole($user, 'quality');
- $canDelivery = $this->mprocAdminHasMobileRole($user, 'delivery');
- $canRfq = $this->mprocAdminHasMobileRole($user, 'rfq');
- $raw = $this->mprocSanitizeRedirectUrl($redirectPathOrUrl);
- if ($raw !== '') {
- if ($canDelivery && stripos($raw, 'deliveryscore') !== false) {
- return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/deliveryscore');
- }
- if ($canQuality && stripos($raw, 'inboundscore') !== false) {
- return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/inboundscore');
- }
- if ($canRfq && stripos($raw, 'rfqadd') !== false) {
- return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/rfqadd');
- }
- }
- if ($canQuality) {
- return url('index/index/inboundscore', '', '', true);
- }
- if ($canDelivery) {
- return url('index/index/deliveryscore', '', '', true);
- }
- if ($canRfq) {
- return url('index/index/rfqadd', '', '', true);
- }
- return '';
- }
- $raw = $this->mprocSanitizeRedirectUrl($redirectPathOrUrl);
- if ($raw !== '' && stripos($raw, 'deliverynote') !== false) {
- return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/deliverynote');
- }
- return $this->mprocBuildAfterLoginIndexUrl($redirectPathOrUrl);
- }
- /**
- * 操作人员是否具备手机端任一业务角色(质检 / 生产 / 业务员询价,含超管)
- *
- * @param array<string, mixed> $user
- */
- protected function mprocAdminHasAnyMobileAccess(array $user): bool
- {
- return $this->mprocAdminHasMobileRole($user, 'quality')
- || $this->mprocAdminHasMobileRole($user, 'delivery')
- || $this->mprocAdminHasMobileRole($user, 'rfq');
- }
- /**
- * @param array<string, mixed> $row admin 表行
- * @return array<string, mixed>
- */
- protected function mprocLoginPayloadFromAdmin(array $row, string $loginType): array
- {
- return [
- 'phone' => trim((string)($row['mobile'] ?? '')),
- 'company_name' => '',
- 'username' => trim((string)($row['username'] ?? '')),
- 'account' => trim((string)($row['username'] ?? '')),
- 'customer_user_id' => 0,
- 'customer_id' => 0,
- 'admin_id' => (int)($row['id'] ?? 0),
- 'login_type' => $loginType,
- 'is_admin' => 1,
- ];
- }
- /** 清除当前请求中的手机端登录态(解决无权限账号卡在登录跳转) */
- protected function mprocDropCurrentLogin(): void
- {
- $token = $this->mprocReadTokenFromRequest();
- $this->mprocClearLogin($token);
- }
- /**
- * @param string $rawSanitized
- * @param string $fallbackRoute
- */
- protected function mprocAbsoluteFromSanitizedPath($rawSanitized, $fallbackRoute)
- {
- $base = rtrim((string)$this->request->root(true), '/');
- $path = parse_url($rawSanitized, PHP_URL_PATH);
- $query = parse_url($rawSanitized, PHP_URL_QUERY);
- if (!is_string($path) || $path === '') {
- return url($fallbackRoute, '', '', true);
- }
- $path = '/' . ltrim(str_replace('\\', '/', $path), '/');
- // root(true) 常为 http://host/index.php,而 redirect/REQUEST_URI 也可能以 /index.php 开头,
- // 直接拼接会变成 /index.php/index.php/... → 报「模块不存在:index.php」
- if (preg_match('#/index\.php$#i', $base)) {
- $path = preg_replace('#^/index\.php(?=/|$)#i', '', $path);
- if ($path === '' || (isset($path[0]) && $path[0] !== '/')) {
- $path = '/' . ltrim((string)$path, '/');
- }
- }
- return $base . $path . (is_string($query) && $query !== '' ? ('?' . $query) : '');
- }
- /**
- * 从 purchase_order_detail 表解析真实列名(SHOW COLUMNS 只查一次,按候选小写名匹配第一条)
- *
- * @param string[] $candidatesLower 如 ['status','istatus']
- * @return string|null
- */
- protected function mprocResolveProcuremenColumn(array $candidatesLower)
- {
- if (self::$mprocProcuremenColumns === null) {
- self::$mprocProcuremenColumns = [];
- try {
- $rows = Db::query('SHOW COLUMNS FROM `purchase_order_detail`');
- if (is_array($rows)) {
- foreach ($rows as $c) {
- $name = isset($c['Field']) ? (string)$c['Field'] : '';
- if ($name !== '') {
- self::$mprocProcuremenColumns[strtolower($name)] = $name;
- }
- }
- }
- } catch (\Throwable $e) {
- self::$mprocProcuremenColumns = [];
- }
- }
- foreach ($candidatesLower as $low) {
- $k = strtolower((string)$low);
- if (isset(self::$mprocProcuremenColumns[$k])) {
- return self::$mprocProcuremenColumns[$k];
- }
- }
- return null;
- }
- /**
- * 供应商整单备注(purchase_order_detail.remark)
- *
- * @param array<string, mixed> $row
- */
- protected function mprocResolveDetailRemark(array $row): string
- {
- $col = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
- if ($col === null) {
- return '';
- }
- foreach ($row as $k => $v) {
- if (strcasecmp((string)$k, $col) === 0) {
- return trim((string)$v);
- }
- }
- return '';
- }
- /**
- * 供应商自己填的备注;与订单 MBZ 相同视为未填
- */
- protected function mprocSupplierOwnRemark($detailRemark, $orderMbz = ''): string
- {
- $own = trim((string)$detailRemark);
- $mbz = trim((string)$orderMbz);
- if ($own === '' || ($mbz !== '' && $own === $mbz)) {
- return '';
- }
- return $own;
- }
- /**
- * 列表:非管理员按 company_name 与登录单位一致,或 phone 与登录手机号一致(兼容手工下发单位名细微差异)
- *
- * @return array|callable 可直接 $query->where(...);空数组表示不加条件
- */
- protected function mprocListWhereForLoginUser(array $user)
- {
- if (!empty($user['is_admin'])) {
- return [];
- }
- $cCol = $this->mprocResolveProcuremenColumn(['company_name']);
- $pCol = $this->mprocResolveProcuremenColumn(['phone']);
- if (($cCol === null || $cCol === '') && ($pCol === null || $pCol === '')) {
- return ['id' => 0];
- }
- $cn = trim((string)($user['company_name'] ?? ''));
- $phone = trim((string)($user['phone'] ?? ''));
- if ($cn === '' && $phone !== '') {
- $cn = $this->mprocResolveCompanyForLoginPhone($phone);
- }
- if ($cn === '' && $phone === '') {
- return ['id' => 0];
- }
- return function ($q) use ($cCol, $pCol, $cn, $phone) {
- $first = true;
- if ($cCol !== null && $cCol !== '' && $cn !== '') {
- $q->where($cCol, $cn);
- $first = false;
- }
- if ($pCol !== null && $pCol !== '' && $phone !== '') {
- if ($first) {
- $q->where($pCol, $phone);
- } else {
- $q->whereOr($pCol, $phone);
- }
- }
- if ($first) {
- $q->where('id', 0);
- }
- };
- }
- /**
- * customer 是否允许登录(status:1 / 正常;空视为可登录以兼容旧数据)
- */
- protected function mprocCustomerUserActive(array $row): bool
- {
- $st = $row['status'] ?? '';
- if ($st === '' || $st === null) {
- return true;
- }
- return $st === 1 || $st === '1';
- }
- /**
- * @return array<string, mixed>|null
- */
- protected function mprocFindCustomerUserByMobile(string $phone): ?array
- {
- return $this->mprocFindCustomerRowByPhone($phone);
- }
- /**
- * 按登录账号(account)查找 customer;兼容旧会话把 11 位手机号写在 username 里
- *
- * @return array<string, mixed>|null
- */
- protected function mprocFindCustomerUserByUsername(string $username): ?array
- {
- $username = trim($username);
- if ($username === '') {
- return null;
- }
- try {
- $row = Db::table('customer')->where('account', $username)->order('id', 'asc')->find();
- } catch (\Throwable $e) {
- $row = null;
- }
- if ((!is_array($row) || $row === []) && preg_match('/^1\d{10}$/', $username)) {
- $row = $this->mprocFindCustomerRowByPhone($username);
- }
- if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
- return null;
- }
- return $row;
- }
- /**
- * customer 密码校验(md5(md5) 无 salt;兼容 bcrypt)
- */
- protected function mprocVerifyCustomerUserPassword(array $row, string $password): bool
- {
- $stored = (string)($row['password'] ?? '');
- if ($stored === '' || $password === '') {
- return false;
- }
- if (preg_match('/^\$2[ayb]\$/', $stored)) {
- return password_verify($password, $stored);
- }
- return hash_equals($stored, md5(md5($password)));
- }
- /**
- * 生成 customer 登录密码密文
- */
- protected function mprocHashCustomerUserPassword(string $password, string $existingSalt = ''): string
- {
- unset($existingSalt);
- return md5(md5($password));
- }
- /**
- * 手机端强密码校验:通过返回空字符串,否则返回错误提示
- */
- protected function mprocValidateStrongPassword(string $password): string
- {
- $len = strlen($password);
- if ($len < 8 || $len > 20) {
- return '密码长度须为8~20位';
- }
- if (preg_match('/\s/', $password)) {
- return '密码不能包含空格';
- }
- if (preg_match('/^\d+$/', $password)) {
- return '密码不能为纯数字,请同时包含字母';
- }
- if (preg_match('/^[a-zA-Z]+$/', $password)) {
- return '密码不能为纯字母,请同时包含数字';
- }
- if (!preg_match('/[a-zA-Z]/', $password) || !preg_match('/\d/', $password)) {
- return '密码须同时包含字母和数字';
- }
- if (preg_match('/(.)\1{3,}/', $password)) {
- return '密码不能包含过多重复字符(如1111、aaaa)';
- }
- if ($this->mprocPasswordHasSequentialRun($password, 4)) {
- return '密码不能包含连续字符(如1234、abcd)';
- }
- $weak = [
- '12345678', '123456789', '1234567890', '87654321', '01234567',
- 'password', 'password1', 'passw0rd', 'qwerty12', 'qwertyui',
- 'abc12345', 'abcd1234', 'a1b2c3d4', '11111111', '00000000',
- '88888888', '66666666', '11223344', '1qaz2wsx', 'qazwsxed',
- ];
- if (in_array(strtolower($password), $weak, true)) {
- return '密码过于简单,请重新设置';
- }
- return '';
- }
- /**
- * 是否包含连续递增/递减片段(长度 >= $runLen),如 1234、4321、abcd
- */
- protected function mprocPasswordHasSequentialRun(string $password, int $runLen = 4): bool
- {
- $runLen = max(3, $runLen);
- $lower = strtolower($password);
- $n = strlen($lower);
- if ($n < $runLen) {
- return false;
- }
- for ($i = 0; $i <= $n - $runLen; $i++) {
- $asc = true;
- $desc = true;
- for ($j = 1; $j < $runLen; $j++) {
- $prev = ord($lower[$i + $j - 1]);
- $cur = ord($lower[$i + $j]);
- if ($cur !== $prev + 1) {
- $asc = false;
- }
- if ($cur !== $prev - 1) {
- $desc = false;
- }
- if (!$asc && !$desc) {
- break;
- }
- }
- if ($asc || $desc) {
- return true;
- }
- }
- return false;
- }
- /**
- * @param array<string, mixed> $cu
- * @return array<string, mixed>
- */
- protected function mprocLoginPayloadFromCustomer(array $cu, string $loginType): array
- {
- $phone = trim((string)($cu['phone'] ?? ''));
- $account = trim((string)($cu['account'] ?? ''));
- if ($phone === '' && preg_match('/^1\d{10}$/', $account)) {
- $phone = $account;
- }
- if ($account === '' && preg_match('/^1\d{10}$/', $phone)) {
- $account = $phone;
- }
- $companyName = trim((string)($cu['company_name'] ?? ''));
- if ($companyName === '' && $phone !== '') {
- $companyName = $this->mprocResolveCompanyForLoginPhone($phone);
- }
- $id = (int)($cu['id'] ?? 0);
- return [
- 'phone' => $phone,
- 'account' => $account,
- 'company_name' => $companyName,
- 'username' => trim((string)($cu['username'] ?? '')),
- 'customer_id' => $id,
- 'customer_user_id' => $id,
- 'login_type' => $loginType,
- 'is_admin' => 0,
- ];
- }
- /**
- * 写入手机端登录态并返回跳转 URL
- *
- * @param array<string, mixed> $userData
- */
- protected function mprocFinishLogin(array $userData): void
- {
- $old = Session::get('mproc_token');
- if ($old) {
- $this->mprocClearLogin((string)$old);
- }
- $userData['login_time'] = time();
- $token = $this->mprocPackSignedAuthToken($userData);
- $token = $this->mprocTouchLoginState($userData, $token);
- $postR = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
- $sessR = $this->mprocSanitizeRedirectUrl((string)Session::get('mproc_intended_url', ''));
- Session::delete('mproc_intended_url');
- $raw = $postR !== '' ? $postR : $sessR;
- $jump = $this->mprocBuildAfterLoginHomeUrl($userData, $raw);
- if ($jump === '') {
- $this->mprocClearLogin($token);
- $this->error('账号或密码错误');
- }
- $this->success('登录成功', $jump, [
- 'mproc_token' => $token,
- 'keep_hours' => $this->mprocKeepHours(),
- 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
- ]);
- }
- /**
- * 登录手机号对应的外协单位名称:customer 表;否则 purchase_order_detail
- */
- protected function mprocResolveCompanyForLoginPhone(string $phone): string
- {
- $phone = trim($phone);
- if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
- return '';
- }
- $cust = $this->mprocFindCustomerRowByPhone($phone);
- if (is_array($cust) && $cust !== []) {
- $co = $this->mprocCustomerPickField($cust, ['company_name', 'name']);
- if ($co !== '') {
- return $co;
- }
- }
- try {
- $one = Db::table('purchase_order_detail')
- ->where('phone', $phone)
- ->order('id', 'desc')
- ->find();
- if (is_array($one)) {
- $n = trim((string)($one['company_name'] ?? ''));
- if ($n !== '') {
- return $n;
- }
- }
- } catch (\Throwable $e) {
- }
- return '';
- }
- /**
- * 按手机号匹配 customer(phone 或 account 单值相等)
- *
- * @return array<string, mixed>|null
- */
- protected function mprocFindCustomerRowByPhone(string $phone): ?array
- {
- $phone = trim($phone);
- if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
- return null;
- }
- try {
- $row = Db::table('customer')
- ->where(function ($q) use ($phone) {
- $q->where('phone', $phone)->whereOr('account', $phone);
- })
- ->order('id', 'asc')
- ->find();
- } catch (\Throwable $e) {
- return null;
- }
- if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
- return null;
- }
- return $row;
- }
- /**
- * 管理员表 fa_admin.mobile 与当前手机号一致且未禁用(用于手机验证码管理员通道)
- *
- * @return array<string, mixed>|null
- */
- protected function mprocAdminRowByMobile(string $phone): ?array
- {
- $phone = trim($phone);
- if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
- return null;
- }
- try {
- $row = Db::name('admin')
- ->where('mobile', $phone)
- ->where('status', '<>', 'hidden')
- ->order('id', 'asc')
- ->find();
- } catch (\Throwable $e) {
- return null;
- }
- return is_array($row) && $row !== [] ? $row : null;
- }
- /**
- * 在 customer 表中匹配当前用户:优先手机号,否则按公司名
- *
- * @return array<string, mixed>|null
- */
- protected function mprocFindCustomerRowForUser(array $user): ?array
- {
- $phone = trim((string)($user['phone'] ?? ''));
- if ($phone === '') {
- $phone = trim((string)($user['account'] ?? ''));
- }
- $cn = trim((string)($user['company_name'] ?? ''));
- if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
- $byPhone = $this->mprocFindCustomerRowByPhone($phone);
- if ($byPhone !== null) {
- return $byPhone;
- }
- }
- if ($cn !== '') {
- try {
- // customer 表无 name 列,勿用 whereOr('name')
- $hit = Db::table('customer')
- ->where('company_name', $cn)
- ->order('id', 'desc')
- ->find();
- } catch (\Throwable $e) {
- $hit = null;
- }
- if (is_array($hit) && $hit !== []) {
- return $hit;
- }
- }
- return null;
- }
- /**
- * 从 customer 行取字段(兼容列名大小写)
- *
- * @param string[] $candidates
- */
- protected function mprocCustomerPickField(array $row, array $candidates): string
- {
- foreach ($candidates as $want) {
- $lw = strtolower($want);
- foreach ($row as $k => $v) {
- if (!is_string($k)) {
- continue;
- }
- if (strtolower($k) !== $lw) {
- continue;
- }
- $s = trim((string)$v);
- if ($s !== '') {
- return $s;
- }
- }
- }
- return '';
- }
- /**
- * 明细表关键字搜索:仅对 purchase_order_detail 真实存在的列 LIKE;
- * 主表 purchase_order 上的订单号、印件、工序等另查 scydgy_id 再 OR 进列表(避免引用不存在的列导致整页查失败)。
- *
- * @param \think\db\Query $query
- */
- protected function mprocApplySearchKeywordToDetailQuery($query, $search)
- {
- $kw = trim((string)$search);
- if ($kw === '') {
- return;
- }
- $map = self::$mprocProcuremenColumns;
- if (!is_array($map) || $map === []) {
- return;
- }
- $like = '%' . addcslashes($kw, '%_\\') . '%';
- $wantLower = ['ccydh', 'cyjmc', 'cdxmc', 'company_name', 'cgzzxmc', 'cgymc', 'cdf', 'phone', 'email'];
- $detailCols = [];
- foreach ($wantLower as $low) {
- if (isset($map[$low])) {
- $detailCols[] = $map[$low];
- }
- }
- $scydgyCol = isset($map['scydgy_id']) ? $map['scydgy_id'] : 'scydgy_id';
- $idCol = isset($map['id']) ? $map['id'] : 'id';
- $poSidList = [];
- $poWant = ['CCYDH', 'CYJMC', 'CDXMC', 'CGYMC', 'cGzzxMc', 'CDF'];
- try {
- $col = Db::table('purchase_order')
- ->where(function ($sub) use ($like, $poWant) {
- $firstPo = true;
- foreach ($poWant as $pf) {
- if ($firstPo) {
- $sub->where($pf, 'like', $like);
- $firstPo = false;
- } else {
- $sub->whereOr($pf, 'like', $like);
- }
- }
- })
- ->column('scydgy_id');
- if (is_array($col)) {
- foreach ($col as $v) {
- $id = (int)$v;
- if ($this->mprocIsValidScydgyRowId($id)) {
- $poSidList[$id] = true;
- }
- }
- }
- $poSidList = array_keys($poSidList);
- } catch (\Throwable $e) {
- $poSidList = [];
- }
- $query->where(function ($q2) use ($like, $detailCols, $poSidList, $scydgyCol, $idCol) {
- $first = true;
- foreach ($detailCols as $col) {
- if ($first) {
- $q2->where($col, 'like', $like);
- $first = false;
- } else {
- $q2->whereOr($col, 'like', $like);
- }
- }
- if ($poSidList !== []) {
- if ($first) {
- $q2->where($scydgyCol, 'in', $poSidList);
- $first = false;
- } else {
- $q2->whereOr($scydgyCol, 'in', $poSidList);
- }
- }
- if ($first) {
- $q2->where($idCol, '=', 0);
- }
- });
- }
- /**
- * 列表:按左侧 Tab 追加 status_name 条件(与数值 status 0/1/2 无关;值由后端维护)
- * - draft:status_name = 未提交
- * - submitted:status_name = 已提交
- * - done:status_name = 已完成
- * 表无 status_name 列时不加条件(三个 Tab 数据相同,待库表补列后再筛)
- *
- * @param mixed $query
- * @param string $tab draft|submitted|done
- * @param string|null $statusNameCol 真实列名,如 status_name
- */
- protected function mprocApplyListTabConditions($query, $tab, $statusNameCol)
- {
- if ($statusNameCol === null) {
- return;
- }
- $map = [
- 'draft' => '未提交',
- 'submitted' => '已提交',
- 'done' => '已完成',
- ];
- $label = $map[$tab] ?? '未提交';
- $query->where($statusNameCol, '=', $label);
- }
- /**
- * 按登录态解析 customer 行
- *
- * @return array<string, mixed>|null
- */
- protected function mprocResolveCustomerUserForSession(array $user): ?array
- {
- if (!empty($user['is_admin'])) {
- return null;
- }
- $cuId = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
- if ($cuId > 0) {
- try {
- $row = Db::table('customer')->where('id', $cuId)->find();
- } catch (\Throwable $e) {
- $row = null;
- }
- if (is_array($row) && $row !== [] && $this->mprocCustomerUserActive($row)) {
- return $row;
- }
- }
- $account = trim((string)($user['account'] ?? ''));
- if ($account !== '') {
- $byAcc = $this->mprocFindCustomerUserByUsername($account);
- if ($byAcc !== null) {
- return $byAcc;
- }
- }
- $phone = trim((string)($user['phone'] ?? ''));
- if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
- return $this->mprocFindCustomerUserByMobile($phone);
- }
- $uname = trim((string)($user['username'] ?? ''));
- if ($uname !== '' && preg_match('/^1\d{10}$/', $uname)) {
- return $this->mprocFindCustomerUserByMobile($uname);
- }
- return null;
- }
- /**
- * customer 表字段 →「我的」展示结构
- *
- * @param array<string, mixed> $cu
- * @return array{account:string,contact_name:string,department:string,phone:string,email:string,company_name:string}
- */
- protected function mprocProfileFromCustomerUserRow(array $cu): array
- {
- $nm = trim((string)($cu['username'] ?? ''));
- $account = trim((string)($cu['account'] ?? ''));
- $phone = trim((string)($cu['phone'] ?? ''));
- if ($phone === '') {
- $phone = $account;
- }
- $company = trim((string)($cu['company_name'] ?? ''));
- return [
- 'account' => $account !== '' ? $account : $phone,
- 'contact_name' => $nm,
- 'department' => $company,
- 'phone' => $phone,
- 'email' => trim((string)($cu['email'] ?? '')),
- 'company_name' => $company,
- ];
- }
- /**
- * 管理员「我的」:账号、姓名、部门(角色组)、手机、邮箱
- *
- * @return array{account:string,contact_name:string,department:string,phone:string,email:string,company_name:string}
- */
- protected function mprocProfileForAdmin(array $user): array
- {
- $uname = trim((string)($user['username'] ?? ''));
- $out = [
- 'account' => $uname,
- 'contact_name' => $uname !== '' ? $uname : '管理员',
- 'department' => '',
- 'phone' => trim((string)($user['phone'] ?? '')),
- 'email' => '',
- 'company_name' => '',
- ];
- if ($uname === '') {
- return $out;
- }
- try {
- $row = Db::name('admin')->where('username', $uname)->find();
- } catch (\Throwable $e) {
- $row = null;
- }
- if (!is_array($row) || $row === []) {
- return $out;
- }
- $out['account'] = trim((string)($row['username'] ?? $uname));
- $nick = trim((string)($row['nickname'] ?? ''));
- if ($nick !== '') {
- $out['contact_name'] = $nick;
- }
- $mob = trim((string)($row['mobile'] ?? ''));
- if ($mob !== '') {
- $out['phone'] = $mob;
- }
- $em = trim((string)($row['email'] ?? ''));
- if ($em !== '') {
- $out['email'] = $em;
- }
- $dept = $this->mprocAdminDepartmentLabel((int)($row['id'] ?? 0));
- $out['department'] = $dept;
- $out['company_name'] = $dept;
- return $out;
- }
- /**
- * 管理员部门展示:优先质检中心/生产部,否则拼接所属角色组名
- */
- protected function mprocAdminDepartmentLabel(int $adminId): string
- {
- if ($adminId <= 0) {
- return '';
- }
- $names = [];
- try {
- $rows = Db::name('auth_group_access')
- ->alias('aga')
- ->join('auth_group ag', 'aga.group_id = ag.id')
- ->where('aga.uid', $adminId)
- ->where('ag.status', 'normal')
- ->field('ag.id,ag.name')
- ->order('ag.id', 'asc')
- ->select();
- } catch (\Throwable $e) {
- $rows = [];
- }
- if (!is_array($rows)) {
- return '';
- }
- $qualityId = $this->mprocResolveMobileQualityGroupId();
- $deliveryId = $this->mprocResolveMobileDeliveryGroupId();
- $deliveryLabel = trim((string)Config::get('mproc.mobile_delivery_dept_name'));
- if ($deliveryLabel === '') {
- $deliveryLabel = '生产部';
- }
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $gid = (int)($r['id'] ?? 0);
- $name = trim((string)($r['name'] ?? ''));
- if ($gid === $qualityId) {
- $names[] = '质检中心';
- continue;
- }
- if ($gid === $deliveryId) {
- $names[] = $deliveryLabel;
- continue;
- }
- if ($name !== '') {
- $names[] = $name;
- }
- }
- $names = array_values(array_unique($names));
- return $names !== [] ? implode('、', $names) : '';
- }
- /**
- * 旧会话补全 customer_id 等字段
- */
- protected function mprocSyncSessionCustomerUser(array $user): array
- {
- if (!empty($user['is_admin'])) {
- return $user;
- }
- $cu = $this->mprocResolveCustomerUserForSession($user);
- if (!$cu) {
- return $user;
- }
- $id = (int)($cu['id'] ?? 0);
- $user['customer_id'] = $id;
- $user['customer_user_id'] = $id;
- $user['username'] = trim((string)($cu['username'] ?? $user['username'] ?? ''));
- $user['company_name'] = trim((string)($cu['company_name'] ?? ''));
- $user['account'] = trim((string)($cu['account'] ?? ''));
- $mob = trim((string)($cu['phone'] ?? ''));
- if ($mob === '') {
- $mob = trim((string)($cu['account'] ?? ''));
- }
- if ($mob !== '') {
- $user['phone'] = $mob;
- }
- $token = Session::get('mproc_token');
- if ($token) {
- $user['login_time'] = (int)($user['login_time'] ?? time());
- $tok = trim((string)$token);
- Cache::set($this->mprocAuthCacheKey($tok), $user, $this->mprocTtlSeconds + 86400);
- if (!$this->mprocIsSignedAuthToken($tok)) {
- Cache::set('mproc_u_' . preg_replace('/[^a-f0-9]/i', '', $tok), $user, $this->mprocTtlSeconds + 86400);
- }
- }
- return $user;
- }
- /**
- * 「我的」:普通用户 customer;管理员 admin
- */
- protected function mprocProfileForUser(array $user)
- {
- if (!empty($user['is_admin'])) {
- return $this->mprocProfileForAdmin($user);
- }
- $cu = $this->mprocResolveCustomerUserForSession($user);
- if (is_array($cu) && $cu !== []) {
- return $this->mprocProfileFromCustomerUserRow($cu);
- }
- $phone = trim((string)($user['phone'] ?? ''));
- if ($phone === '') {
- $phone = trim((string)($user['account'] ?? ''));
- }
- return [
- 'account' => $phone !== '' ? $phone : trim((string)($user['account'] ?? '')),
- 'contact_name' => trim((string)($user['username'] ?? '')),
- 'department' => trim((string)($user['company_name'] ?? '')),
- 'phone' => $phone,
- 'email' => '',
- 'company_name' => trim((string)($user['company_name'] ?? '')),
- ];
- }
- protected function mprocIsValidScydgyRowId($id): bool
- {
- return (int)$id !== 0;
- }
- /**
- * 将 purchase_order(工序行主表)快照合并进 purchase_order_detail 行:订单级信息以主表为准;
- * 金额、交期、外厂 company、明细 status 等仍保留明细表。
- *
- * @param array $row 引用:明细行
- * @param array $poRow purchase_order 一行
- */
- protected function mprocMergePurchaseOrderIntoDetail(array &$row, array $poRow)
- {
- $pl = array_change_key_case($poRow, CASE_LOWER);
- $hdr = [
- 'ccydh' => 'CCYDH',
- 'cyjmc' => 'CYJMC',
- 'cdf' => 'CDF',
- 'cgzzxmc' => 'cGzzxMc',
- 'cgymc' => 'CGYMC',
- 'cdxmc' => 'CDXMC',
- 'ngzl' => 'NGZL',
- 'cdw' => 'CDW',
- 'cgybh' => 'CGYBH',
- ];
- foreach ($hdr as $lk => $out) {
- if (!array_key_exists($lk, $pl)) {
- continue;
- }
- $v = $pl[$lk];
- if ($v !== null && $v !== '') {
- $row[$out] = $v;
- }
- }
- // 本次数量、最高限价:仅存在于主表;PDO 列名大小写可能不一致
- $qtyRaw = '';
- foreach (['this_quantity', 'This_quantity'] as $qk) {
- if (array_key_exists($qk, $pl) && $pl[$qk] !== null && $pl[$qk] !== '') {
- $qtyRaw = trim((string)$pl[$qk]);
- break;
- }
- }
- if ($qtyRaw === '') {
- foreach (['This_quantity', 'this_quantity'] as $qk) {
- if (array_key_exists($qk, $poRow) && $poRow[$qk] !== null && $poRow[$qk] !== '') {
- $qtyRaw = trim((string)$poRow[$qk]);
- break;
- }
- }
- }
- if ($qtyRaw !== '') {
- $row['This_quantity'] = $qtyRaw;
- }
- $ceilRaw = '';
- foreach (['ceilingprice', 'ceiling_price', 'CeilingPrice'] as $ck) {
- if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
- $ceilRaw = trim((string)$pl[$ck]);
- break;
- }
- }
- if ($ceilRaw === '') {
- foreach (['ceilingPrice', 'ceiling_price', 'CeilingPrice'] as $ck) {
- if (array_key_exists($ck, $poRow) && $poRow[$ck] !== null && $poRow[$ck] !== '') {
- $ceilRaw = trim((string)$poRow[$ck]);
- break;
- }
- }
- }
- if ($ceilRaw !== '') {
- $row['ceilingPrice'] = $ceilRaw;
- }
- $sysRq = '';
- foreach (['sys_rq', 'SYS_RQ'] as $sk) {
- if (array_key_exists($sk, $pl) && $pl[$sk] !== null && $pl[$sk] !== '') {
- $sysRq = trim((string)$pl[$sk]);
- break;
- }
- if (array_key_exists($sk, $poRow) && $poRow[$sk] !== null && $poRow[$sk] !== '') {
- $sysRq = trim((string)$poRow[$sk]);
- break;
- }
- }
- if ($sysRq !== '' && !preg_match('/^0000-00-00/i', $sysRq)) {
- $row['sys_rq'] = $sysRq;
- }
- $deliveryDeadline = '';
- foreach (['delivery_deadline', 'Delivery_deadline'] as $dk) {
- if (array_key_exists($dk, $pl) && $pl[$dk] !== null && $pl[$dk] !== '') {
- $deliveryDeadline = trim((string)$pl[$dk]);
- break;
- }
- if (array_key_exists($dk, $poRow) && $poRow[$dk] !== null && $poRow[$dk] !== '') {
- $deliveryDeadline = trim((string)$poRow[$dk]);
- break;
- }
- }
- if ($deliveryDeadline !== '' && !preg_match('/^0000-00-00/i', $deliveryDeadline)) {
- $row['delivery_deadline'] = $deliveryDeadline;
- }
- // 下发备注(purchase_order.MBZ)→ 手机端未提交/已提交/已完成展示
- $mbz = '';
- foreach (['mbz', 'MBZ'] as $mk) {
- if (array_key_exists($mk, $pl) && $pl[$mk] !== null && trim((string)$pl[$mk]) !== '') {
- $mbz = trim((string)$pl[$mk]);
- break;
- }
- if (array_key_exists($mk, $poRow) && $poRow[$mk] !== null && trim((string)$poRow[$mk]) !== '') {
- $mbz = trim((string)$poRow[$mk]);
- break;
- }
- }
- if ($mbz !== '') {
- $row['MBZ'] = $mbz;
- $row['mproc_order_remark'] = $mbz;
- }
- }
- /**
- * @param int[] $sidList
- * @return array<int, string>
- */
- protected function mprocLoadScydgyMbzByIds(array $sidList): array
- {
- $ids = [];
- foreach ($sidList as $sid) {
- $sid = (int)$sid;
- if ($this->mprocIsValidScydgyRowId($sid)) {
- $ids[$sid] = true;
- }
- }
- if ($ids === []) {
- return [];
- }
- try {
- $map = Db::table('scydgy')->where('ID', 'in', array_keys($ids))->column('MBZ', 'ID');
- } catch (\Throwable $e) {
- return [];
- }
- return is_array($map) ? $map : [];
- }
- /**
- * 统一取年月日(无效则空串)
- */
- protected function mprocFormatYmdValue($raw): string
- {
- $s = trim((string)$raw);
- if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
- return '';
- }
- $s = str_replace(['/', '.'], '-', $s);
- if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
- return $m[1];
- }
- $ts = strtotime(str_replace('T', ' ', $s));
- if ($ts === false || $ts <= 0) {
- return '';
- }
- return date('Y-m-d', $ts);
- }
- /**
- * 招标截止展示:年月日 + 时分(有秒也保留到分即可)
- */
- protected function mprocFormatYmdHmValue($raw): string
- {
- $s = trim((string)$raw);
- if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
- return '';
- }
- $s = str_replace(['/', '.'], '-', $s);
- $s = str_replace('T', ' ', $s);
- if (preg_match('/^(\d{4}-\d{2}-\d{2})\s+(\d{2}):(\d{2})(?::\d{2})?/', $s, $m)) {
- return $m[1] . ' ' . $m[2] . ':' . $m[3];
- }
- if (preg_match('/^(\d{4}-\d{2}-\d{2})$/', $s, $m)) {
- return $m[1];
- }
- $ts = strtotime($s);
- if ($ts === false || $ts <= 0) {
- return '';
- }
- return date('Y-m-d H:i', $ts);
- }
- /**
- * 列表展示:招标截止 / 交货截止
- *
- * @param array<string, mixed> $row
- */
- protected function mprocEnrichOrderDeadlineDisplay(array &$row): void
- {
- $sysRqRaw = $this->mprocResolveSysRqFromPo($row);
- $bidRaw = $sysRqRaw !== '' ? $sysRqRaw : trim((string)($row['sys_rq'] ?? ''));
- $bid = $this->mprocFormatYmdHmValue($bidRaw);
- $del = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? '');
- $row['mproc_bid_deadline_display'] = $bid;
- // 完整截止时间供前端保存前校验(含时分秒)
- $row['mproc_bid_deadline'] = $bidRaw;
- $row['mproc_delivery_deadline_display'] = $del;
- $row['mproc_delivery_deadline'] = $del;
- }
- /**
- * 明细对应主表的交货截止日期 Y-m-d
- *
- * @param array<string, mixed> $row
- */
- protected function mprocResolveDeliveryDeadlineYmdForDetailRow(array $row): string
- {
- $fromRow = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? $row['mproc_delivery_deadline'] ?? '');
- if ($fromRow !== '') {
- return $fromRow;
- }
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- if (!$this->mprocIsValidScydgyRowId($sid)) {
- return '';
- }
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- } catch (\Throwable $e) {
- $po = null;
- }
- if (!is_array($po)) {
- return '';
- }
- return $this->mprocFormatYmdValue($po['delivery_deadline'] ?? $po['Delivery_deadline'] ?? '');
- }
- /**
- * 主表报价截止时间(未设置则视为未截止)
- *
- * @param array<string, mixed>|null $po
- */
- protected function mprocResolveSysRqFromPo(?array $po): string
- {
- if (!is_array($po)) {
- return '';
- }
- $sr = trim((string)($po['sys_rq'] ?? $po['SYS_RQ'] ?? ''));
- if ($sr === '') {
- $pl = array_change_key_case($po, CASE_LOWER);
- $sr = trim((string)($pl['sys_rq'] ?? ''));
- }
- return ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) ? $sr : '';
- }
- /**
- * 从主表/明细解析订单号
- *
- * @param array<string, mixed>|null $po
- * @param array<string, mixed>|null $row
- */
- protected function mprocResolveCcydhFromPoOrRow(?array $po, ?array $row = null): string
- {
- foreach ([$po, $row] as $src) {
- if (!is_array($src)) {
- continue;
- }
- $c = trim((string)($src['CCYDH'] ?? $src['ccydh'] ?? ''));
- if ($c !== '') {
- return $c;
- }
- }
- return '';
- }
- /**
- * 批量:已开标验证的订单号集合(本请求内可复用)
- *
- * @var array<string, bool>|null
- */
- protected $mprocBidOpenVerifiedSet = null;
- /**
- * @param array<int, string> $ccydhs
- * @return array<string, bool>
- */
- protected function mprocLoadBidOpenVerifiedCcydhSet(array $ccydhs): array
- {
- $set = [];
- $list = [];
- foreach ($ccydhs as $c) {
- $c = trim((string)$c);
- if ($c !== '') {
- $list[$c] = true;
- }
- }
- if ($list === []) {
- return $set;
- }
- try {
- $rows = Db::table('purchase_order_bid_open')
- ->where('ccydh', 'in', array_keys($list))
- ->field('ccydh')
- ->select();
- if (!is_array($rows)) {
- return $set;
- }
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $c = trim((string)($row['ccydh'] ?? ''));
- if ($c !== '') {
- $set[$c] = true;
- }
- }
- } catch (\Throwable $e) {
- return [];
- }
- return $set;
- }
- /**
- * 该订单是否已完成开标双重验证(有 purchase_order_bid_open 记录)
- */
- protected function mprocIsBidOpenVerified(string $ccydh): bool
- {
- $ccydh = trim($ccydh);
- if ($ccydh === '') {
- return false;
- }
- if (is_array($this->mprocBidOpenVerifiedSet)) {
- return isset($this->mprocBidOpenVerifiedSet[$ccydh]);
- }
- try {
- $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
- return is_array($row);
- } catch (\Throwable $e) {
- return false;
- }
- }
- /**
- * @param array<string, mixed>|null $po
- * @param array<string, mixed>|null $row
- */
- protected function mprocIsBidOpenVerifiedForPoOrRow(?array $po, ?array $row = null): bool
- {
- return $this->mprocIsBidOpenVerified($this->mprocResolveCcydhFromPoOrRow($po, $row));
- }
- /**
- * 手机端:仅当主表设置了 sys_rq 且已到期时视为截止(无截止时间仍可填报)
- * 保存时务必再调一次,防止页面长时间打开、截止后仍提交
- *
- * @param array<string, mixed>|null $po
- */
- protected function mprocIsQuoteDeadlineReachedForPo(?array $po): bool
- {
- $raw = $this->mprocResolveSysRqFromPo($po);
- if ($raw === '') {
- return false;
- }
- $ts = strtotime(str_replace('T', ' ', $raw));
- if ($ts === false || $ts <= 0) {
- return false;
- }
- return time() >= $ts;
- }
- /**
- * 保存前强制按库中最新招标截止时间校验(避免弹窗久开后仍提交)
- *
- * @param array<string, mixed>|null $po
- */
- protected function mprocAssertQuoteNotDeadlineReached(?array $po, string $label = ''): void
- {
- // 以库中最新主表为准,避免内存中旧快照
- $freshPo = null;
- if (is_array($po)) {
- $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
- if ($this->mprocIsValidScydgyRowId($sid)) {
- try {
- $freshPo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- } catch (\Throwable $e) {
- $freshPo = null;
- }
- }
- }
- $checkPo = is_array($freshPo) ? $freshPo : $po;
- if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($checkPo) ? $checkPo : null)) {
- throw new \InvalidArgumentException(
- ($label !== '' ? $label : '') . '已超过招标截止时间,不可再提交'
- );
- }
- }
- /**
- * 保存前:截止时间 + 已开标均不可再改
- *
- * @param array<string, mixed>|null $po
- * @param array<string, mixed>|null $row
- */
- protected function mprocAssertQuoteStillEditable(?array $po, string $label = '', ?array $row = null): void
- {
- $sid = 0;
- if (is_array($row)) {
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- }
- if ($sid === 0 && is_array($po)) {
- $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
- }
- // 手工询价无招标截止、不开标
- if ($sid < 0) {
- return;
- }
- $this->mprocAssertQuoteNotDeadlineReached($po, $label);
- $freshPo = is_array($po) ? $po : null;
- if (is_array($po)) {
- if ($this->mprocIsValidScydgyRowId($sid)) {
- try {
- $got = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- if (is_array($got)) {
- $freshPo = $got;
- }
- } catch (\Throwable $e) {
- }
- }
- }
- // 保存场景不走列表缓存,直接查库
- $prev = $this->mprocBidOpenVerifiedSet;
- $this->mprocBidOpenVerifiedSet = null;
- $opened = $this->mprocIsBidOpenVerifiedForPoOrRow($freshPo, $row);
- $this->mprocBidOpenVerifiedSet = $prev;
- if ($opened) {
- throw new \InvalidArgumentException(
- ($label !== '' ? $label : '') . '已开标验证,不可再提交'
- );
- }
- }
- /**
- * 审批通过后:中标 / 未中标
- * 说明:采购终审通过后主单仍为「进行中」(待入库评分),仅 wflow=已审核;
- * 不能等主单「已完结」才标中标,否则手机端会误显示「已截止」。
- *
- * @param array<string, mixed> $row
- * @param array<string, mixed>|null $po
- */
- protected function mprocResolvePickResultText(array $row, ?array $po): string
- {
- if (!is_array($po)) {
- return '';
- }
- $approved = ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')
- || ProcuremenStatus::isPoCompleted($po['status'] ?? $po['STATUS'] ?? '');
- if (!$approved) {
- return '';
- }
- $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
- if (ProcuremenStatus::isPodPicked($detailStatus)) {
- return '中标';
- }
- $sn = trim((string)($row['status_name'] ?? ''));
- if ($sn === '已完成') {
- return '中标';
- }
- return '未中标';
- }
- /**
- * 手机端左侧 Tab:
- * 询价:rfq / rfq_submitted(手工单 scydgy_id<0,仅未提交/已提交)
- * 报价:draft / submitted / done(协助下发)
- *
- * @param array<string, mixed> $row
- * @param array<string, mixed>|null $po
- */
- protected function mprocResolveListTabForRow(array $row, ?array $po, string $effectiveSn): string
- {
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- // 手工询价:无招标截止;仅未提交/已提交(对应待报价/已报价)
- if ($sid < 0) {
- if ($effectiveSn === '已提交'
- || in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
- return 'rfq_submitted';
- }
- return 'rfq';
- }
- if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
- return 'done';
- }
- if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)
- || $this->mprocIsQuoteDeadlineReachedForPo($po)) {
- // 已开标或已过招标截止 →「已完成」
- return 'done';
- }
- if ($effectiveSn === '已提交') {
- return 'submitted';
- }
- return 'draft';
- }
- /**
- * @return string[]
- */
- protected function mprocListTabWhitelist(): array
- {
- return ['rfq', 'rfq_submitted', 'draft', 'submitted', 'done'];
- }
- /**
- * 兼容旧地址 tab=rfq_done → 询价已提交
- */
- protected function mprocNormalizeListTab(string $tab): string
- {
- if ($tab === 'rfq_done') {
- return 'rfq_submitted';
- }
- if (!in_array($tab, $this->mprocListTabWhitelist(), true)) {
- return 'draft';
- }
- return $tab;
- }
- protected function mprocIsDoneListTab(string $tab): bool
- {
- return $tab === 'done';
- }
- protected function mprocIsRfqListTab(string $tab): bool
- {
- return $tab === 'rfq' || $tab === 'rfq_submitted';
- }
- /**
- * 复合 Tab → 状态维度:draft|submitted|done
- */
- protected function mprocStatusFromListTab(string $tab): string
- {
- if ($tab === 'rfq' || $tab === 'draft') {
- return 'draft';
- }
- if ($tab === 'rfq_submitted' || $tab === 'submitted') {
- return 'submitted';
- }
- if ($this->mprocIsDoneListTab($tab)) {
- return 'done';
- }
- return 'draft';
- }
- /**
- * 同一订单号 + 供应商合并为一张卡片
- *
- * @param array<int, array<string, mixed>> $rows
- * @return array<int, array<string, mixed>>
- */
- protected function mprocGroupRowsByOrder(array $rows): array
- {
- $groups = [];
- $order = [];
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $ccydh = trim((string)($row['CCYDH'] ?? ''));
- $cname = trim((string)($row['company_name'] ?? ''));
- $isVoid = (int)($row['mproc_is_void'] ?? 0) === 1
- || $this->mprocDetailRowIsVoid($row);
- // 已废弃轮与当前轮拆成两张卡,避免混在一起看不清
- $roundKey = $isVoid
- ? ('void:' . (int)($row['eid'] ?? $row['id'] ?? 0))
- : 'active';
- $key = ($ccydh !== '' ? $ccydh : ('eid_' . (int)($row['eid'] ?? 0))) . '|' . $cname . '|' . $roundKey;
- if (!isset($groups[$key])) {
- $groups[$key] = [
- 'group_key' => $key,
- 'CCYDH' => $ccydh,
- 'CYJMC' => trim((string)($row['CYJMC'] ?? '')),
- 'company_name' => $cname,
- 'mproc_bid_deadline_display' => trim((string)($row['mproc_bid_deadline_display'] ?? '')),
- 'mproc_bid_deadline' => trim((string)($row['mproc_bid_deadline'] ?? '')),
- 'mproc_delivery_deadline_display' => trim((string)($row['mproc_delivery_deadline_display'] ?? '')),
- 'mproc_delivery_deadline' => trim((string)($row['mproc_delivery_deadline'] ?? '')),
- 'lines' => [],
- ];
- $order[] = $key;
- } else {
- if ($groups[$key]['mproc_delivery_deadline'] === ''
- && trim((string)($row['mproc_delivery_deadline'] ?? '')) !== '') {
- $groups[$key]['mproc_delivery_deadline'] = trim((string)$row['mproc_delivery_deadline']);
- $groups[$key]['mproc_delivery_deadline_display'] = trim((string)($row['mproc_delivery_deadline_display'] ?? ''));
- }
- if ($groups[$key]['mproc_bid_deadline'] === ''
- && trim((string)($row['mproc_bid_deadline'] ?? '')) !== '') {
- $groups[$key]['mproc_bid_deadline'] = trim((string)$row['mproc_bid_deadline']);
- }
- if ($groups[$key]['mproc_bid_deadline_display'] === ''
- && trim((string)($row['mproc_bid_deadline_display'] ?? '')) !== '') {
- $groups[$key]['mproc_bid_deadline_display'] = trim((string)$row['mproc_bid_deadline_display']);
- }
- }
- $groups[$key]['lines'][] = $row;
- }
- $out = [];
- foreach ($order as $key) {
- $g = $groups[$key];
- $lines = is_array($g['lines'] ?? null) ? $g['lines'] : [];
- usort($lines, function ($a, $b) {
- $sa = (int)($a['scydgy_id'] ?? 0);
- $sb = (int)($b['scydgy_id'] ?? 0);
- if ($sa !== $sb) {
- return $sa <=> $sb;
- }
- return ((int)($a['eid'] ?? 0)) <=> ((int)($b['eid'] ?? 0));
- });
- $g['lines'] = $lines;
- $g['line_count'] = count($lines);
- $canEdit = false;
- $bidOpen = false;
- foreach ($lines as $ln) {
- if (!is_array($ln)) {
- continue;
- }
- if ((int)($ln['mproc_can_edit'] ?? 0) === 1) {
- $canEdit = true;
- }
- if ((int)($ln['mproc_bid_open_verified'] ?? 0) === 1) {
- $bidOpen = true;
- }
- }
- $g['can_edit'] = $canEdit ? 1 : 0;
- $g['mproc_bid_open_verified'] = $bidOpen ? 1 : 0;
- $remark = '';
- $orderRemarkList = [];
- $doneLabel = '';
- $pickResult = '';
- $hasWin = false;
- $hasLose = false;
- $hasExpired = false;
- $hasVoid = false;
- foreach ($lines as $ln) {
- if (!is_array($ln)) {
- continue;
- }
- $rm = $this->mprocSupplierOwnRemark(
- (string)($ln['mproc_remark'] ?? ''),
- (string)($ln['mproc_order_remark'] ?? $ln['MBZ'] ?? '')
- );
- if ($rm !== '' && $remark === '') {
- $remark = $rm;
- }
- $ombz = trim((string)($ln['mproc_order_remark'] ?? $ln['MBZ'] ?? ''));
- if ($ombz !== '' && !in_array($ombz, $orderRemarkList, true)) {
- $orderRemarkList[] = $ombz;
- }
- $pr = trim((string)($ln['mproc_pick_result'] ?? ''));
- $dl = trim((string)($ln['mproc_done_label'] ?? ''));
- if ($pr === '中标' || $dl === '中标') {
- $hasWin = true;
- } elseif ($pr === '未中标' || $dl === '未中标') {
- $hasLose = true;
- } elseif ($dl === '已废弃' || (int)($ln['mproc_is_void'] ?? 0) === 1) {
- $hasVoid = true;
- } elseif ($dl === '已截止' || (int)($ln['mproc_deadline_reached'] ?? 0) === 1) {
- $hasExpired = true;
- }
- }
- if ($hasVoid) {
- $doneLabel = '已废弃';
- $pickResult = '';
- } elseif ($hasWin) {
- $doneLabel = '中标';
- $pickResult = '中标';
- } elseif ($hasLose) {
- $doneLabel = '未中标';
- $pickResult = '未中标';
- } elseif ($hasExpired) {
- $doneLabel = '已截止';
- $pickResult = '';
- }
- $g['remark'] = $remark;
- $g['mproc_order_remark'] = $orderRemarkList !== [] ? implode('、', $orderRemarkList) : '';
- $g['mproc_done_label'] = $doneLabel;
- $g['mproc_pick_result'] = $pickResult;
- $out[] = $g;
- }
- return $out;
- }
- /**
- * 查询 purchase_order_detail 列表(订单页)
- * 无搜索词 / 有搜索词:均按左侧 Tab 筛选(draft/submitted/done)
- * 有搜索词时:在当前 Tab 内做关键字匹配
- *
- * @param string $tab draft|submitted|done
- * @param string|null $statusNameCol status_name 真实列名;为 null 时不按 Tab 过滤
- * @return array{rows: array, done_no_status: int}
- */
- protected function mprocFetchProcuremenList(array $user, $tab, $q, $statusNameCol)
- {
- $query = Db::table('purchase_order_detail')->order('id', 'desc');
- // 初选下发已向供应商发送通知后,手机端可见 wflow_status>=1 的明细
- $userWhere = $this->mprocListWhereForLoginUser($user);
- if ($userWhere !== []) {
- $query->where($userWhere);
- }
- if (trim((string)$q) === '' && $this->mprocIsDoneListTab((string)$tab) && $statusNameCol !== null) {
- $this->mprocSyncLegacyApprovedStatusNames($user, $statusNameCol);
- }
- $this->mprocApplySearchKeywordToDetailQuery($query, $q);
- // Tab 筛选在 PHP 层按截止时间、审批结果综合判断(含逾期进「已完成」、未中标等)
- try {
- $rows = $query->limit(500)->select();
- } catch (\Throwable $e) {
- $rows = [];
- }
- if (!is_array($rows)) {
- $rows = [];
- }
- $poBySid = [];
- $sidList = [];
- foreach ($rows as $r0) {
- if (!is_array($r0)) {
- continue;
- }
- $sid0 = (int)($r0['scydgy_id'] ?? $r0['SCYDGY_ID'] ?? 0);
- if ($this->mprocIsValidScydgyRowId($sid0)) {
- $sidList[$sid0] = true;
- }
- }
- if ($sidList !== []) {
- try {
- $poRows = Db::table('purchase_order')
- ->where('scydgy_id', 'in', array_values(array_keys($sidList)))
- ->select();
- if (is_array($poRows)) {
- foreach ($poRows as $pr) {
- $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
- if ($this->mprocIsValidScydgyRowId($sidk)) {
- $poBySid[$sidk] = $pr;
- }
- }
- }
- } catch (\Throwable $e) {
- }
- }
- $ccydhForBid = [];
- foreach ($poBySid as $pr) {
- if (!is_array($pr)) {
- continue;
- }
- $c = trim((string)($pr['CCYDH'] ?? $pr['ccydh'] ?? ''));
- if ($c !== '') {
- $ccydhForBid[$c] = true;
- }
- }
- foreach ($rows as $r0) {
- if (!is_array($r0)) {
- continue;
- }
- $c = trim((string)($r0['CCYDH'] ?? $r0['ccydh'] ?? ''));
- if ($c !== '') {
- $ccydhForBid[$c] = true;
- }
- }
- $this->mprocBidOpenVerifiedSet = $this->mprocLoadBidOpenVerifiedCcydhSet(array_keys($ccydhForBid));
- $needScydgyMbzSids = [];
- foreach ($poBySid as $sidKey => $pr) {
- if (!is_array($pr)) {
- continue;
- }
- $mbzPo = '';
- foreach (['mbz', 'MBZ'] as $mk) {
- if (array_key_exists($mk, $pr) && $pr[$mk] !== null && trim((string)$pr[$mk]) !== '') {
- $mbzPo = trim((string)$pr[$mk]);
- break;
- }
- }
- if ($mbzPo === '' && $this->mprocIsValidScydgyRowId((int)$sidKey)) {
- $needScydgyMbzSids[(int)$sidKey] = true;
- }
- }
- $scydgyMbzBySid = [];
- if ($needScydgyMbzSids !== []) {
- $loadedMbz = $this->mprocLoadScydgyMbzByIds(array_keys($needScydgyMbzSids));
- foreach ($loadedMbz as $sidKey => $mbzVal) {
- $mbzVal = trim((string)$mbzVal);
- if ($mbzVal !== '') {
- $scydgyMbzBySid[(int)$sidKey] = $mbzVal;
- }
- }
- }
- foreach ($rows as &$row) {
- if (!is_array($row)) {
- continue;
- }
- $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? 0);
- $isVoid = $this->mprocDetailRowIsVoid($row);
- // 已废弃:仅展示「填过报价」的旧轮,与当前轮并排,避免供应商误以为没填过
- if ($isVoid && !$this->mprocDetailRowHasQuote($row)) {
- $row = null;
- continue;
- }
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- if ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) {
- $this->mprocMergePurchaseOrderIntoDetail($row, $poBySid[$sid]);
- }
- if (trim((string)($row['mproc_order_remark'] ?? $row['MBZ'] ?? '')) === ''
- && $this->mprocIsValidScydgyRowId($sid)
- && isset($scydgyMbzBySid[$sid])
- && is_string($scydgyMbzBySid[$sid])) {
- $row['MBZ'] = $scydgyMbzBySid[$sid];
- $row['mproc_order_remark'] = $scydgyMbzBySid[$sid];
- }
- $poRow = ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) ? $poBySid[$sid] : null;
- $oldSn = trim((string)($row['status_name'] ?? ''));
- if ($isVoid) {
- $effectiveSn = ProcuremenStatus::POD_VOID;
- $listTab = 'done';
- $row['status_name'] = $effectiveSn;
- $row['mproc_list_tab'] = $listTab;
- $row['mproc_is_void'] = 1;
- $row['mproc_is_rfq'] = ((int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0) < 0) ? 1 : 0;
- $row['mproc_deadline_reached'] = 0;
- $row['mproc_bid_open_verified'] = 0;
- $row['mproc_pick_result'] = '';
- $row['mproc_done_label'] = '已废弃';
- $row['mproc_can_edit'] = 0;
- } else {
- $effectiveSn = $this->mprocResolveEffectiveStatusName($row, $poRow);
- $row['status_name'] = $effectiveSn;
- if ($statusNameCol !== null && $effectiveSn !== $oldSn && $row['eid'] > 0) {
- $this->mprocPersistDetailStatusName((int)$row['eid'], $statusNameCol, $effectiveSn);
- }
- $listTab = $this->mprocResolveListTabForRow($row, $poRow, $effectiveSn);
- $row['mproc_list_tab'] = $listTab;
- $row['mproc_is_void'] = 0;
- $row['mproc_is_rfq'] = ((int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0) < 0) ? 1 : 0;
- if ((int)$row['mproc_is_rfq'] === 1) {
- $row['mproc_bid_deadline'] = '';
- $row['mproc_bid_deadline_display'] = '';
- $row['mproc_delivery_deadline'] = '';
- $row['mproc_delivery_deadline_display'] = '';
- $row['mproc_deadline_reached'] = 0;
- $row['mproc_bid_open_verified'] = 0;
- $row['mproc_pick_result'] = '';
- } else {
- $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
- $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
- $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow($poRow, $row) ? 1 : 0;
- }
- if ($row['mproc_pick_result'] !== '') {
- $row['mproc_done_label'] = $row['mproc_pick_result'];
- } elseif ($this->mprocIsDoneListTab($listTab) && (
- (int)$row['mproc_deadline_reached'] === 1
- || (int)$row['mproc_bid_open_verified'] === 1
- )) {
- $row['mproc_done_label'] = '已截止';
- } else {
- $row['mproc_done_label'] = '';
- }
- if (!isset($row['status_name']) || $row['status_name'] === null) {
- $row['status_name'] = '';
- } else {
- $row['status_name'] = trim((string)$row['status_name']);
- }
- $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
- }
- $am = $row['amount'] ?? null;
- if ($am === null || $am === '' || (is_string($am) && trim($am) === '')) {
- $row['amount_display'] = '';
- } else {
- $row['amount_display'] = is_scalar($am) ? (string)$am : '';
- }
- $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
- if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
- $row['delivery_display'] = $m[1];
- } elseif ($dv !== '') {
- $row['delivery_display'] = $dv;
- } else {
- $row['delivery_display'] = '';
- }
- $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
- $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
- $this->mprocEnrichLeadDaysDisplay($row);
- if ((int)$row['mproc_is_rfq'] === 1) {
- $row['mproc_bid_deadline'] = '';
- $row['mproc_bid_deadline_display'] = '';
- $row['mproc_delivery_deadline'] = '';
- $row['mproc_delivery_deadline_display'] = '';
- } else {
- $this->mprocEnrichOrderDeadlineDisplay($row);
- }
- $row['mproc_fill_hint'] = '';
- $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
- $orderRemark = trim((string)($row['mproc_order_remark'] ?? $row['MBZ'] ?? ''));
- $detailRemark = $this->mprocResolveDetailRemark($row);
- if ($orderRemark === '') {
- $row['mproc_order_remark'] = '';
- }
- $row['mproc_remark'] = $this->mprocSupplierOwnRemark($detailRemark, $orderRemark);
- }
- unset($row);
- $rows = array_values(array_filter($rows, function ($r) {
- return is_array($r);
- }));
- // 同一供应商同一工序:保留最新有效轮 + 最近一轮已废弃且有报价的记录
- $rows = $this->mprocDedupeDetailRowsByCompanyProcess($rows);
- // 始终按 Tab 过滤(含搜索):未中标/已截止等只出现在「已完成」
- $rows = array_values(array_filter($rows, function ($r) use ($tab) {
- return is_array($r) && trim((string)($r['mproc_list_tab'] ?? '')) === $tab;
- }));
- // 「已完成」仅保留近三个月(按招标截止日,缺省则交货截止/创建时间)
- if ($this->mprocIsDoneListTab((string)$tab)) {
- $rows = array_values(array_filter($rows, function ($r) {
- return is_array($r) && $this->mprocIsWithinRecentMonths($r, 3);
- }));
- }
- // 按招标截止日期排序:未提交/已提交截止近的在前;已完成最近截止的在前
- $rows = $this->mprocSortRowsByBidDeadline($rows, $this->mprocIsDoneListTab((string)$tab) ? 'desc' : 'asc');
- $groups = $this->mprocGroupRowsByOrder($rows);
- return [
- 'rows' => $rows ?: [],
- 'groups' => $groups ?: [],
- 'done_no_status' => (int)($statusNameCol === null),
- ];
- }
- /**
- * 按招标截止时间排序(无截止时间的排最后)
- *
- * @param array<int, array<string, mixed>> $rows
- * @param string $dir asc|desc
- * @return array<int, array<string, mixed>>
- */
- protected function mprocSortRowsByBidDeadline(array $rows, string $dir = 'asc'): array
- {
- $dir = strtolower($dir) === 'desc' ? 'desc' : 'asc';
- usort($rows, function ($a, $b) use ($dir) {
- $ta = $this->mprocBidDeadlineSortTs(is_array($a) ? $a : []);
- $tb = $this->mprocBidDeadlineSortTs(is_array($b) ? $b : []);
- $ha = $ta > 0;
- $hb = $tb > 0;
- if ($ha !== $hb) {
- return $ha ? -1 : 1;
- }
- if ($ha && $ta !== $tb) {
- return $dir === 'desc' ? ($tb <=> $ta) : ($ta <=> $tb);
- }
- $ida = (int)($a['eid'] ?? $a['id'] ?? 0);
- $idb = (int)($b['eid'] ?? $b['id'] ?? 0);
- return $idb <=> $ida;
- });
- return array_values($rows);
- }
- /**
- * @param array<string, mixed> $row
- */
- protected function mprocBidDeadlineSortTs(array $row): int
- {
- $raw = trim((string)($row['mproc_bid_deadline'] ?? $row['sys_rq'] ?? $row['SYS_RQ'] ?? ''));
- if ($raw === '') {
- $raw = trim((string)($row['mproc_bid_deadline_display'] ?? ''));
- }
- if ($raw === '') {
- return 0;
- }
- $ts = strtotime(str_replace('T', ' ', $raw));
- return ($ts !== false && $ts > 0) ? (int)$ts : 0;
- }
- /**
- * 是否属于近 N 个月(优先招标截止,其次交货截止,再次创建/更新时间)
- *
- * @param array<string, mixed> $row
- */
- protected function mprocIsWithinRecentMonths(array $row, int $months = 3): bool
- {
- $months = max(1, $months);
- $since = strtotime(date('Y-m-d 00:00:00', strtotime('-' . $months . ' months')));
- if ($since === false) {
- return true;
- }
- $candidates = [
- $row['mproc_bid_deadline'] ?? '',
- $row['sys_rq'] ?? '',
- $row['SYS_RQ'] ?? '',
- $row['mproc_bid_deadline_display'] ?? '',
- $row['mproc_delivery_deadline'] ?? '',
- $row['delivery_deadline'] ?? '',
- $row['mproc_delivery_deadline_display'] ?? '',
- $row['createtime'] ?? '',
- $row['updatetime'] ?? '',
- ];
- foreach ($candidates as $raw) {
- $raw = trim((string)$raw);
- if ($raw === '' || stripos($raw, '0000-00-00') === 0) {
- continue;
- }
- $ts = strtotime(str_replace('T', ' ', $raw));
- if ($ts === false || $ts <= 0) {
- continue;
- }
- return $ts >= $since;
- }
- return false;
- }
- /**
- * 同一供应商 + 同一工序:
- * - 有效轮只保留 id 最大的一条
- * - 已废弃且有报价的,再保留 id 最大的一条(与有效轮并排展示)
- *
- * @param array<int, array<string, mixed>> $rows
- * @return array<int, array<string, mixed>>
- */
- protected function mprocDedupeDetailRowsByCompanyProcess(array $rows): array
- {
- $bestActive = [];
- $bestVoid = [];
- $orderKeys = [];
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $cn = trim((string)($row['company_name'] ?? ''));
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- $eid = (int)($row['eid'] ?? $row['id'] ?? $row['ID'] ?? 0);
- if ($this->mprocIsValidScydgyRowId($sid)) {
- $key = $cn . '|sid:' . $sid;
- } else {
- $key = $cn . '|eid:' . $eid;
- }
- $isVoid = (int)($row['mproc_is_void'] ?? 0) === 1 || $this->mprocDetailRowIsVoid($row);
- if ($isVoid) {
- if (!$this->mprocDetailRowHasQuote($row)) {
- continue;
- }
- if (!isset($bestVoid[$key])) {
- $bestVoid[$key] = $row;
- if (!isset($bestActive[$key]) && !in_array($key, $orderKeys, true)) {
- $orderKeys[] = $key;
- }
- continue;
- }
- $prevEid = (int)($bestVoid[$key]['eid'] ?? $bestVoid[$key]['id'] ?? 0);
- if ($eid > $prevEid) {
- $bestVoid[$key] = $row;
- }
- continue;
- }
- if (!isset($bestActive[$key])) {
- $bestActive[$key] = $row;
- if (!in_array($key, $orderKeys, true)) {
- $orderKeys[] = $key;
- }
- continue;
- }
- $prevEid = (int)($bestActive[$key]['eid'] ?? $bestActive[$key]['id'] ?? 0);
- if ($eid > $prevEid) {
- $bestActive[$key] = $row;
- }
- }
- $out = [];
- foreach ($orderKeys as $key) {
- // 先当前轮,后已废弃轮(列表里当前在上更直观)
- if (isset($bestActive[$key])) {
- $out[] = $bestActive[$key];
- }
- if (isset($bestVoid[$key])) {
- $activeEid = isset($bestActive[$key])
- ? (int)($bestActive[$key]['eid'] ?? $bestActive[$key]['id'] ?? 0)
- : 0;
- $voidEid = (int)($bestVoid[$key]['eid'] ?? $bestVoid[$key]['id'] ?? 0);
- if ($voidEid > 0 && $voidEid !== $activeEid) {
- $out[] = $bestVoid[$key];
- }
- }
- }
- return $out;
- }
- /**
- * @param array<string, mixed> $row
- */
- protected function mprocDetailRowIsVoid(array $row): bool
- {
- return ProcuremenStatus::isPodVoid($row['status'] ?? '')
- || trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
- }
- /**
- * @param array<string, mixed> $row
- */
- protected function mprocDetailRowHasQuote(array $row): bool
- {
- $am = $row['amount'] ?? null;
- if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
- return true;
- }
- $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
- if ($dv !== '' && !preg_match('/^0000-00-00/i', $dv)) {
- return true;
- }
- $ld = $row['lead_days'] ?? null;
- return $ld !== null && $ld !== '' && is_numeric($ld);
- }
- /**
- * status_name → 手机端左侧 Tab
- */
- protected function mprocStatusNameToListTab(string $statusName): string
- {
- $map = ['未提交' => 'draft', '已提交' => 'submitted', '已完成' => 'done', '未通过' => 'done', '已废弃' => 'done'];
- $sn = trim($statusName);
- return isset($map[$sn]) ? $map[$sn] : '';
- }
- /**
- * 短信/邮件 focus_eid 应落在的列表 Tab
- */
- protected function mprocResolveListTabForFocusEid(int $focusEid, array $user): string
- {
- if ($focusEid <= 0) {
- return '';
- }
- $idCol = $this->mprocResolveProcuremenColumn(['id']);
- if ($idCol === null) {
- return '';
- }
- try {
- $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
- $qw = $this->mprocListWhereForLoginUser($user);
- if ($qw !== []) {
- $qrow->where($qw);
- }
- $dr = $qrow->find();
- } catch (\Throwable $e) {
- $dr = null;
- }
- if (!is_array($dr) || $dr === []) {
- return '';
- }
- $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
- $po = null;
- if ($this->mprocIsValidScydgyRowId($sid)) {
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- } catch (\Throwable $e) {
- $po = null;
- }
- }
- return $this->mprocResolveListTabForRow(
- $dr,
- is_array($po) ? $po : null,
- $this->mprocResolveEffectiveStatusName($dr, is_array($po) ? $po : null)
- );
- }
- /**
- * 短信/邮件直达链接:确保 focus 对应明细出现在当前列表(便于高亮定位)
- *
- * @param array<string, mixed> $bundle
- * @param array<string, mixed> $user
- * @return array<string, mixed>
- */
- protected function mprocEnsureFocusRowInList(
- array $bundle,
- int $focusEid,
- array $user,
- $statusNameCol,
- string $tab = 'draft',
- string $q = ''
- ): array {
- if ($focusEid <= 0) {
- return $bundle;
- }
- $rows = isset($bundle['rows']) && is_array($bundle['rows']) ? $bundle['rows'] : [];
- $foundIdx = -1;
- foreach ($rows as $idx => $r) {
- if (!is_array($r)) {
- continue;
- }
- if ((int)($r['eid'] ?? $r['id'] ?? $r['ID'] ?? 0) === $focusEid) {
- $foundIdx = (int)$idx;
- break;
- }
- }
- if ($foundIdx > 0) {
- $hit = $rows[$foundIdx];
- array_splice($rows, $foundIdx, 1);
- array_unshift($rows, $hit);
- $bundle['rows'] = $rows;
- $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
- return $bundle;
- }
- if ($foundIdx === 0) {
- return $bundle;
- }
- $idCol = $this->mprocResolveProcuremenColumn(['id']);
- if ($idCol === null) {
- return $bundle;
- }
- try {
- $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
- $qw = $this->mprocListWhereForLoginUser($user);
- if ($qw !== []) {
- $qrow->where($qw);
- }
- $dr = $qrow->find();
- } catch (\Throwable $e) {
- $dr = null;
- }
- if (!is_array($dr) || $dr === []) {
- return $bundle;
- }
- $row = $dr;
- $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? $focusEid);
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- $poRow = null;
- if ($this->mprocIsValidScydgyRowId($sid)) {
- try {
- $poRow = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- } catch (\Throwable $e) {
- $poRow = null;
- }
- if (is_array($poRow)) {
- $this->mprocMergePurchaseOrderIntoDetail($row, $poRow);
- }
- }
- $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($poRow) ? $poRow : null);
- $rowTab = $this->mprocResolveListTabForRow($row, is_array($poRow) ? $poRow : null, $effectiveSn);
- if ($rowTab !== '' && $rowTab !== $tab) {
- return $bundle;
- }
- $row['status_name'] = $effectiveSn;
- $listTab = $rowTab;
- $row['mproc_list_tab'] = $listTab;
- $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
- $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
- $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow(is_array($poRow) ? $poRow : null, $row) ? 1 : 0;
- if ($row['mproc_pick_result'] !== '') {
- $row['mproc_done_label'] = $row['mproc_pick_result'];
- } elseif ($this->mprocIsDoneListTab($listTab) && (
- (int)$row['mproc_deadline_reached'] === 1
- || (int)$row['mproc_bid_open_verified'] === 1
- )) {
- $row['mproc_done_label'] = '已截止';
- } else {
- $row['mproc_done_label'] = '';
- }
- $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
- $am = $row['amount'] ?? null;
- $row['amount_display'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? '' : (is_scalar($am) ? (string)$am : '');
- $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
- if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
- $row['delivery_display'] = $m[1];
- } elseif ($dv !== '') {
- $row['delivery_display'] = $dv;
- } else {
- $row['delivery_display'] = '';
- }
- $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
- $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
- $this->mprocEnrichLeadDaysDisplay($row);
- $this->mprocEnrichOrderDeadlineDisplay($row);
- $row['mproc_fill_hint'] = '';
- $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
- array_unshift($rows, $row);
- $bundle['rows'] = $rows;
- $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
- return $bundle;
- }
- /**
- * 列表展示用「本次数量」:主表本次数量为空时回退显示 NGZL(工作量)
- *
- * @param array<string, mixed> $row
- */
- protected function mprocResolveDisplayThisQuantity(array $row): string
- {
- $qty = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
- if ($qty !== '') {
- return $qty;
- }
- $gzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
- if ($gzl === null || $gzl === '') {
- return '';
- }
- return is_scalar($gzl) ? trim((string)$gzl) : '';
- }
- /**
- * 明细是否已填写单价或交货日期
- *
- * @param array<string, mixed> $row
- */
- protected function mprocDetailQuoteSubmitted(array $row): bool
- {
- $am = $row['amount'] ?? null;
- $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
- $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
- $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
- return $amountFilled || $deliveryFilled;
- }
- /**
- * 手机端列表 Tab 用 status_name;审批通过后主表 status=1 时按明细 status 纠偏
- *
- * @param array<string, mixed> $row
- * @param array<string, mixed>|null $po
- */
- protected function mprocResolveEffectiveStatusName(array $row, ?array $po): string
- {
- $sn = trim((string)($row['status_name'] ?? ''));
- if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
- return $sn;
- }
- if (!is_array($po)) {
- if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
- return '已提交';
- }
- if ($sn !== '') {
- return $sn;
- }
- return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
- }
- $poStatus = $po['status'] ?? $po['STATUS'] ?? '';
- if (!ProcuremenStatus::isPoCompleted($poStatus)) {
- // 库中仍写「未提交」但已填单价/交期:按已提交展示(手工单常见)
- if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
- return '已提交';
- }
- if ($sn !== '') {
- return $sn;
- }
- return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
- }
- $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
- if (ProcuremenStatus::isPodPicked($detailStatus)) {
- return '已完成';
- }
- if ($sn === '已提交') {
- return '未通过';
- }
- return $sn !== '' ? $sn : '未提交';
- }
- /**
- * 将纠偏后的 status_name 写回库表(兼容历史已审批数据)
- */
- protected function mprocPersistDetailStatusName(int $detailId, string $statusNameCol, string $statusName): void
- {
- if ($detailId <= 0 || $statusNameCol === '') {
- return;
- }
- $idCol = $this->mprocResolveProcuremenColumn(['id']);
- if ($idCol === null || $idCol === '') {
- return;
- }
- try {
- Db::table('purchase_order_detail')->where($idCol, $detailId)->update([$statusNameCol => $statusName]);
- } catch (\Throwable $e) {
- }
- }
- /**
- * 纠偏历史数据:主表已审批(status=1)但明细 status_name 仍为「已提交」
- *
- * @param array<string, mixed> $user
- */
- protected function mprocSyncLegacyApprovedStatusNames(array $user, string $statusNameCol): void
- {
- $userWhere = $this->mprocListWhereForLoginUser($user);
- try {
- $query = Db::table('purchase_order_detail')->where($statusNameCol, '已提交');
- if ($userWhere !== []) {
- $query->where($userWhere);
- }
- $candidates = $query->limit(200)->select();
- } catch (\Throwable $e) {
- return;
- }
- if (!is_array($candidates) || $candidates === []) {
- return;
- }
- $sidList = [];
- foreach ($candidates as $cr) {
- if (!is_array($cr)) {
- continue;
- }
- $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
- if ($this->mprocIsValidScydgyRowId($sid)) {
- $sidList[$sid] = true;
- }
- }
- if ($sidList === []) {
- return;
- }
- $poBySid = [];
- try {
- $poRows = Db::table('purchase_order')
- ->where('scydgy_id', 'in', array_keys($sidList))
- ->whereIn('status', ProcuremenStatus::poCompletedValues())
- ->select();
- if (is_array($poRows)) {
- foreach ($poRows as $pr) {
- $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
- if ($this->mprocIsValidScydgyRowId($sidk)) {
- $poBySid[$sidk] = $pr;
- }
- }
- }
- } catch (\Throwable $e) {
- return;
- }
- if ($poBySid === []) {
- return;
- }
- $idCol = $this->mprocResolveProcuremenColumn(['id']);
- if ($idCol === null || $idCol === '') {
- return;
- }
- foreach ($candidates as $cr) {
- if (!is_array($cr)) {
- continue;
- }
- $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
- if (!isset($poBySid[$sid])) {
- continue;
- }
- $detailId = (int)($cr[$idCol] ?? $cr['id'] ?? $cr['ID'] ?? 0);
- if ($detailId <= 0) {
- continue;
- }
- $targetSn = $this->mprocResolveEffectiveStatusName($cr, $poBySid[$sid]);
- if ($targetSn === '已提交') {
- continue;
- }
- $this->mprocPersistDetailStatusName($detailId, $statusNameCol, $targetSn);
- }
- }
- /**
- * 协助明细首页(需登录)
- * GET:main_tab=orders|me,orders 时 tab=draft|submitted|done 对应 status_name:未提交|已提交|已完成;q 搜索词
- */
- public function index()
- {
- $user = $this->mprocGetUser();
- if (!$user) {
- $pendingFocus = $this->mprocReadFocusEidFromRequest();
- if ($pendingFocus > 0) {
- $this->mprocRememberFocusEid($pendingFocus);
- }
- $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
- $safe = $this->mprocSanitizeRedirectUrl($uri);
- if ($safe !== '' && $pendingFocus > 0 && stripos($safe, 'focus_eid') === false) {
- $safe .= (strpos($safe, '?') !== false ? '&' : '?') . 'focus_eid=' . $pendingFocus;
- }
- if ($safe !== '') {
- Session::set('mproc_intended_url', $safe);
- }
- $this->redirect($this->mprocBuildLoginUrl($safe));
- return;
- }
- // 管理员进对应业务页,不进供应商报价列表
- if (!empty($user['is_admin'])) {
- $jump = $this->mprocBuildAfterLoginHomeUrl($user);
- if ($jump === '') {
- $this->mprocDropCurrentLogin();
- $this->redirect(url('index/index/login'));
- return;
- }
- $this->redirect($jump);
- return;
- }
- $user = $this->mprocSyncSessionCustomerUser($user);
- $tabParamRaw = $this->request->get('tab', null);
- $hasExplicitTab = ($tabParamRaw !== null && trim((string)$tabParamRaw) !== '');
- $tabParam = trim((string)($tabParamRaw ?? 'draft'));
- $mainTab = trim((string)$this->request->get('main_tab', 'orders'));
- // 旧地址 ?tab=me 表示「我的」
- if ($tabParam === 'me') {
- $mainTab = 'me';
- }
- if (!in_array($mainTab, ['orders', 'me'], true)) {
- $mainTab = 'orders';
- }
- $tab = $tabParam === 'me' ? 'draft' : $this->mprocNormalizeListTab($tabParam);
- $q = trim((string)$this->request->get('q', ''));
- $mprocFocusEid = 0;
- $focusEid = $this->mprocReadFocusEidFromRequest();
- if ($focusEid > 0 && $mainTab === 'orders') {
- $resolvedTab = $this->mprocResolveListTabForFocusEid($focusEid, $user);
- // 用户已手动点了其他左侧 Tab:取消定位锁定,避免刷新又跳回
- if ($hasExplicitTab && $resolvedTab !== '' && $resolvedTab !== $tab) {
- Session::delete('mproc_focus_eid');
- $focusEid = 0;
- } else {
- $mprocFocusEid = $focusEid;
- // 仅邮件/短信直链且 URL 未带 tab 时,自动切到定位单所在 Tab
- $focusFromUrl = (int)$this->request->param('focus_eid', 0) > 0;
- if (!$focusFromUrl) {
- $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
- $focusFromUrl = $this->mprocParseFocusEidFromUriString($uri) > 0;
- }
- if ($focusFromUrl && trim((string)$q) === '' && !$hasExplicitTab) {
- if ($resolvedTab !== '') {
- $tab = $resolvedTab;
- }
- }
- }
- }
- // 左侧 Tab 按 purchase_order_detail.status_name(未提交/已提交/已完成),与数值 status 无关
- $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
- $profile = $this->mprocProfileForUser($user);
- $this->view->assign('mprocMainTab', $mainTab);
- $this->view->assign('mprocTab', $tab);
- $this->view->assign('mprocIsRfqTab', $this->mprocIsRfqListTab($tab) ? 1 : 0);
- $this->view->assign('mprocStatusTab', $this->mprocStatusFromListTab($tab));
- $this->view->assign('mprocSearchQ', $q);
- $this->view->assign('mprocProfile', $profile);
- $this->view->assign('mprocIsAdmin', !empty($user['is_admin']) ? 1 : 0);
- $cid = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
- $this->view->assign('mprocCanChangePwd', empty($user['is_admin']) && $cid > 0 ? 1 : 0);
- $this->view->assign('mprocFocusEid', $mprocFocusEid);
- $mprocFocusTab = $mprocFocusEid > 0 ? $this->mprocResolveListTabForFocusEid($mprocFocusEid, $user) : '';
- $this->view->assign('mprocFocusTab', $mprocFocusTab);
- $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
- $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
- $this->view->assign('mprocDeliveryNoteUrl', url('index/index/deliverynote'));
- if ($mainTab === 'me') {
- $this->view->assign('rows', []);
- return $this->view->fetch();
- }
- $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
- if ($mprocFocusEid > 0) {
- $bundle = $this->mprocEnsureFocusRowInList($bundle, $mprocFocusEid, $user, $statusNameCol, $tab, $q);
- }
- $this->view->assign('rows', $bundle['rows']);
- $this->view->assign('groups', $bundle['groups'] ?? $this->mprocGroupRowsByOrder($bundle['rows']));
- return $this->view->fetch();
- }
- /**
- * 协助明细列表 JSON(需登录)
- * main_tab=orders|me;orders 时 tab=draft|submitted|done、q=搜索词
- */
- public function mprocList()
- {
- $user = $this->mprocGetUser();
- if (!$user) {
- $this->error('请先登录', url('index/index/login'));
- }
- $user = $this->mprocSyncSessionCustomerUser($user);
- $tabParam = trim((string)$this->request->request('tab', 'draft'));
- $mainTab = trim((string)$this->request->request('main_tab', 'orders'));
- if ($tabParam === 'me') {
- $mainTab = 'me';
- }
- if (!in_array($mainTab, ['orders', 'me'], true)) {
- $mainTab = 'orders';
- }
- $tab = $tabParam === 'me' ? 'draft' : $this->mprocNormalizeListTab($tabParam);
- $q = trim((string)$this->request->request('q', ''));
- if ($mainTab === 'me') {
- // Jump::success($msg, $url, $data, …) 第二参是 URL,数据必须放第三参
- $this->success('ok', '', [
- 'main_tab' => 'me',
- 'tab' => $tab,
- 'rows' => [],
- 'profile' => $this->mprocProfileForUser($user),
- 'done_no_status' => 0,
- ]);
- }
- $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
- if ((int)$this->request->request('clear_focus', 0) === 1) {
- Session::delete('mproc_focus_eid');
- $focusEid = 0;
- $focusTab = '';
- } else {
- $focusEid = $this->mprocReadFocusEidFromRequest();
- $focusTab = $focusEid > 0 ? $this->mprocResolveListTabForFocusEid($focusEid, $user) : '';
- // 列表请求已指定 Tab,且与定位单所在 Tab 不同:视为用户离开锁定页
- if ($focusEid > 0 && $focusTab !== '' && $focusTab !== $tab) {
- Session::delete('mproc_focus_eid');
- $focusEid = 0;
- $focusTab = '';
- }
- }
- $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
- if ($focusEid > 0) {
- $bundle = $this->mprocEnsureFocusRowInList($bundle, $focusEid, $user, $statusNameCol, $tab, $q);
- }
- $this->success('ok', '', array_merge([
- 'main_tab' => 'orders',
- 'tab' => $tab,
- 'focus_tab' => $focusTab,
- 'is_admin' => !empty($user['is_admin']) ? 1 : 0,
- 'focus_eid' => $focusEid,
- ], $bundle));
- }
- /**
- * 登录页(手机号验证码 / 账号密码)
- */
- public function login()
- {
- $redirect = $this->mprocSanitizeRedirectUrl($this->request->get('redirect', ''));
- $user = $this->mprocGetUser();
- if ($user) {
- $jump = $this->mprocBuildAfterLoginHomeUrl($user, $redirect);
- if ($jump !== '') {
- $this->redirect($jump);
- return;
- }
- // 已登录但无手机端权限(其它后台账号):清会话,避免登录页↔自身 302 死循环
- $this->mprocDropCurrentLogin();
- }
- if ($redirect !== '') {
- Session::set('mproc_intended_url', $redirect);
- }
- $this->view->assign('mprocLoginRedirect', $redirect);
- $this->view->assign('mprocCaptchaUrl', url('index/index/captcha'));
- $this->view->assign('mprocCaptchaLen', (int)(Config::get('captcha.length') ?: 4));
- return $this->view->fetch();
- }
- /**
- * 图形验证码(手机号登录用)
- */
- public function captcha($id = '')
- {
- $captcha = new Captcha((array)Config::get('captcha'));
- return $captcha->entry($id);
- }
- /**
- * 发送登录验证码(POST:phone、captcha)
- */
- public function sendSms()
- {
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $phone = trim((string)$this->request->post('phone', ''));
- $captcha = trim((string)$this->request->post('captcha', ''));
- if (!preg_match('/^1\d{10}$/', $phone)) {
- $this->error('请输入正确的11位手机号');
- }
- if ($captcha === '') {
- $this->error('请输入图形验证码');
- }
- $cu = $this->mprocFindCustomerUserByMobile($phone);
- $adminRow = $cu ? null : $this->mprocAdminRowByMobile($phone);
- if (!$cu && !$adminRow) {
- $this->error('账号或密码错误');
- }
- if ($adminRow) {
- $probe = $this->mprocLoginPayloadFromAdmin($adminRow, 'sms');
- if (!$this->mprocAdminHasAnyMobileAccess($probe)) {
- $this->error('账号或密码错误');
- }
- }
- $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
- if (Cache::get('mproc_sms_wait_' . $phone)) {
- $this->error('发送过于频繁,请稍后再试');
- }
- if (!Validate::is($captcha, 'captcha')) {
- $this->error('图形验证码不正确');
- }
- $code = (string)random_int(100000, 999999);
- $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
- $ttl = max(60, min(600, $ttl));
- Cache::set('mproc_code_' . $phone, $code, $ttl);
- Cache::set('mproc_sms_wait_' . $phone, 1, $cd);
- try {
- $tpl = trim((string)Config::get('mproc.sms_login_template'));
- if ($tpl === '') {
- $tpl = '【可集达】您的验证码是{code}。如非本人操作,请忽略本短信';
- }
- $content = str_replace('{code}', $code, $tpl);
- $this->mprocSmsSend($phone, $content);
- } catch (\Exception $e) {
- Cache::rm('mproc_code_' . $phone);
- Cache::rm('mproc_sms_wait_' . $phone);
- $this->error($e->getMessage());
- }
- $this->success('验证码已发送');
- }
- /**
- * 验证码登录(POST:phone、code)
- */
- public function doLogin()
- {
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $phone = trim((string)$this->request->post('phone', ''));
- $code = trim((string)$this->request->post('code', ''));
- if (!preg_match('/^1\d{10}$/', $phone)) {
- $this->error('手机号格式不正确');
- }
- if (!preg_match('/^\d{6}$/', $code)) {
- $this->error('请输入6位验证码');
- }
- // 本地调试:application/extra/mproc.php 中配置 mock_sms_code 与输入一致时,不校验短信缓存(生产务必留空)
- $mock = Config::get('mproc.mock_sms_code');
- if ($mock !== null && $mock !== '' && (string)$mock === $code) {
- Cache::rm('mproc_code_' . $phone);
- } else {
- $cached = Cache::get('mproc_code_' . $phone);
- if ($cached === false || $cached === null || (string)$cached !== $code) {
- $this->error('验证码错误或已过期');
- }
- Cache::rm('mproc_code_' . $phone);
- }
- $cu = $this->mprocFindCustomerUserByMobile($phone);
- if ($cu) {
- $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'sms'));
- return;
- }
- $adminRow = $this->mprocAdminRowByMobile($phone);
- if ($adminRow) {
- $payload = $this->mprocLoginPayloadFromAdmin($adminRow, 'sms');
- if (!$this->mprocAdminHasAnyMobileAccess($payload)) {
- $this->error('账号或密码错误');
- }
- $this->mprocFinishLogin($payload);
- return;
- }
- $this->error('账号或密码错误');
- }
- /**
- * 用本地保存的 token 恢复登录态(POST:mproc_token)
- */
- public function mprocRestore()
- {
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $token = $this->mprocReadTokenFromRequest();
- $user = null;
- if ($token !== '') {
- $user = $this->mprocLoadUserByToken($token);
- }
- if (!$user) {
- $user = $this->mprocUserFromRememberCookie();
- if ($user) {
- $token = $this->mprocPackSignedAuthToken($user);
- }
- }
- if (!$user) {
- $this->error('登录已过期,请重新登录', url('index/index/login'));
- }
- $token = $this->mprocTouchLoginState($user, $token !== '' ? $token : $this->mprocPackSignedAuthToken($user));
- $redirect = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
- $jump = $this->mprocBuildAfterLoginHomeUrl($user, $redirect);
- if ($jump === '') {
- $this->mprocClearLogin($token);
- $this->error('账号或密码错误', url('index/index/login'));
- }
- $this->success('ok', $jump, [
- 'mproc_token' => $token,
- 'keep_hours' => $this->mprocKeepHours(),
- 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
- ]);
- }
- /**
- * 账号密码登录(POST:username、password)
- * 先 customer(account),未命中再 admin;admin 密码规则同 FastAdmin Auth::login
- */
- public function doLoginPwd()
- {
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $username = trim((string)$this->request->post('username', ''));
- $password = (string)$this->request->post('password', '');
- if ($username === '' || $password === '') {
- $this->error('请输入账号和密码');
- }
- $cu = $this->mprocFindCustomerUserByUsername($username);
- if ($cu) {
- if (!$this->mprocVerifyCustomerUserPassword($cu, $password)) {
- $this->error('账号或密码错误');
- }
- $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'pwd'));
- }
- // 管理员:表 admin
- $row = null;
- try {
- $row = Db::name('admin')
- ->field('id,username,password,salt,status,loginfailure,updatetime,mobile')
- ->where('username', $username)
- ->find();
- } catch (\Throwable $e) {
- $row = null;
- }
- if (!$row || !is_array($row)) {
- $this->error('账号或密码错误');
- }
- $id = (int)($row['id'] ?? 0);
- if (($row['status'] ?? '') == 'hidden') {
- $this->error('该账号已禁用');
- }
- if (Config::get('fastadmin.login_failure_retry') && (int)($row['loginfailure'] ?? 0) >= 10 && time() - (int)($row['updatetime'] ?? 0) < 86400) {
- $this->error('登录失败次数过多,请24小时后再试');
- }
- $salt = (string)($row['salt'] ?? '');
- $hashStored = (string)($row['password'] ?? '');
- $hashInput = md5(md5($password) . $salt);
- if ($hashStored === '' || $hashInput !== $hashStored) {
- if ($id > 0) {
- try {
- Db::name('admin')->where('id', $id)->update([
- 'loginfailure' => (int)($row['loginfailure'] ?? 0) + 1,
- 'updatetime' => time(),
- ]);
- } catch (\Throwable $e) {
- }
- }
- $this->error('账号或密码错误');
- }
- if ($id > 0) {
- try {
- Db::name('admin')->where('id', $id)->update([
- 'loginfailure' => 0,
- 'updatetime' => time(),
- ]);
- } catch (\Throwable $e) {
- }
- }
- $payload = $this->mprocLoginPayloadFromAdmin($row, 'pwd');
- if (!$this->mprocAdminHasAnyMobileAccess($payload)) {
- $this->error('账号或密码错误');
- }
- $this->mprocFinishLogin($payload);
- }
- /**
- * 是否允许当前登录用户修改该条 purchase_order_detail 的金额、交期
- * 仅普通用户(customer)可改;管理员(admin)仅可查看
- */
- protected function mprocCanEditRow(array $user, array $row, ?array $po = null)
- {
- if (!empty($user['is_admin'])) {
- return false;
- }
- $sn = trim((string)($row['status_name'] ?? ''));
- if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
- return false;
- }
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- // 手工询价无招标截止/开标限制
- if ($sid >= 0) {
- if ($this->mprocIsQuoteDeadlineReachedForPo($po)) {
- return false;
- }
- if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)) {
- return false;
- }
- }
- $uCo = trim((string)($user['company_name'] ?? ''));
- if ($uCo === '') {
- $uPhone = trim((string)($user['phone'] ?? ''));
- if ($uPhone !== '') {
- $uCo = $this->mprocResolveCompanyForLoginPhone($uPhone);
- }
- }
- $rCo = trim((string)($row['company_name'] ?? ''));
- if ($uCo !== '' && $rCo !== '' && strcmp($rCo, $uCo) === 0) {
- return true;
- }
- $uPhone = trim((string)($user['phone'] ?? ''));
- $rPhone = trim((string)($row['phone'] ?? ''));
- return $uPhone !== '' && $rPhone !== '' && strcasecmp($rPhone, $uPhone) === 0;
- }
- /**
- * 明细行对应最高限价(来自 purchase_order;无或无效则返回 null,不校验)
- *
- * @param array<string, mixed> $detailRow
- */
- protected function mprocResolveCeilingPriceForDetailRow(array $detailRow): ?float
- {
- $sid = (int)($detailRow['scydgy_id'] ?? $detailRow['SCYDGY_ID'] ?? 0);
- $raw = trim((string)($detailRow['ceilingPrice'] ?? $detailRow['ceiling_price'] ?? ''));
- if ($raw === '' && $this->mprocIsValidScydgyRowId($sid)) {
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- } catch (\Throwable $e) {
- $po = null;
- }
- if (is_array($po)) {
- $pl = array_change_key_case($po, CASE_LOWER);
- foreach (['ceilingprice', 'ceiling_price'] as $ck) {
- if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
- $raw = trim((string)$pl[$ck]);
- break;
- }
- }
- if ($raw === '') {
- $raw = trim((string)($po['ceilingPrice'] ?? $po['ceiling_price'] ?? ''));
- }
- }
- }
- if ($raw === '' || !preg_match('/^-?\d+(\.\d{1,5})?$/', $raw)) {
- return null;
- }
- return (float)$raw;
- }
- protected function mprocFormatCeilingPriceDisplay(float $n): string
- {
- $s = rtrim(rtrim(sprintf('%.5F', $n), '0'), '.');
- return $s === '' ? '0' : $s;
- }
- /**
- * 确保 purchase_order_detail.lead_days 字段存在
- */
- protected function mprocEnsureLeadDaysColumn(): void
- {
- static $done = false;
- if ($done) {
- return;
- }
- $done = true;
- try {
- $cols = Db::query("SHOW COLUMNS FROM `purchase_order_detail` LIKE 'lead_days'");
- if (empty($cols)) {
- Db::execute(
- "ALTER TABLE `purchase_order_detail` ADD COLUMN `lead_days` int(10) unsigned DEFAULT NULL COMMENT '预估工期(天)' AFTER `delivery`"
- );
- }
- } catch (\Throwable $e) {
- // 忽略:保存时再按列是否存在处理
- }
- }
- /**
- * 交货日期相对今天的天数(可负数,调用方自行 clamp)
- */
- protected function mprocCalcLeadDaysFromDeliveryYmd(string $ymd): ?int
- {
- if (!preg_match('/^(\d{4}-\d{2}-\d{2})/', $ymd, $m)) {
- return null;
- }
- $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
- $t2 = strtotime($m[1] . ' 00:00:00');
- if ($t1 === false || $t2 === false) {
- return null;
- }
- return (int)round(($t2 - $t1) / 86400);
- }
- protected function mprocAddDaysToToday(int $days): string
- {
- $base = strtotime(date('Y-m-d') . ' 00:00:00');
- if ($base === false) {
- $base = time();
- }
- return date('Y-m-d', strtotime('+' . max(0, $days) . ' days', $base));
- }
- /**
- * @param array<string, mixed> $row
- */
- protected function mprocEnrichLeadDaysDisplay(array &$row): void
- {
- $days = null;
- $raw = $row['lead_days'] ?? null;
- if ($raw !== null && $raw !== '' && is_numeric($raw)) {
- $days = max(0, (int)$raw);
- } else {
- $dd = trim((string)($row['delivery_display'] ?? ''));
- if ($dd === '') {
- $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
- if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
- $dd = $m[1];
- }
- }
- if ($dd !== '') {
- $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($dd);
- if ($calc !== null) {
- $days = max(0, $calc);
- }
- }
- }
- if ($days !== null) {
- $row['lead_days'] = $days;
- $row['lead_days_display'] = (string)$days;
- $row['lead_days_missing'] = 0;
- } else {
- $row['lead_days'] = '';
- $row['lead_days_display'] = '';
- $row['lead_days_missing'] = 1;
- }
- }
- /**
- * 保存单条协助明细的金额、交期、工期(内部)
- *
- * @param array<string, mixed> $user
- * @param int $id
- * @param string $amountRaw
- * @param string $deliveryRaw
- * @param string|int|null $leadDaysRaw
- * @return string 工序名(用于批量错误提示)
- */
- protected function mprocSaveDetailQuote(array $user, int $id, string $amountRaw, string $deliveryRaw, $leadDaysRaw = null): string
- {
- if ($id <= 0) {
- throw new \InvalidArgumentException('参数错误');
- }
- $row = null;
- try {
- $row = Db::table('purchase_order_detail')->where('id', $id)->find();
- if (!$row) {
- $row = Db::table('purchase_order_detail')->where('ID', $id)->find();
- }
- } catch (\Throwable $e) {
- $row = null;
- }
- if (!$row || !is_array($row)) {
- throw new \InvalidArgumentException('记录不存在');
- }
- $gymc = trim((string)($row['CGYMC'] ?? $row['cgymc'] ?? ''));
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- $po = null;
- if ($this->mprocIsValidScydgyRowId($sid)) {
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- } catch (\Throwable $e) {
- $po = null;
- }
- if (is_array($po)) {
- $this->mprocMergePurchaseOrderIntoDetail($row, $po);
- if ($gymc === '') {
- $gymc = trim((string)($row['CGYMC'] ?? ''));
- }
- }
- }
- $label = $gymc !== '' ? ('工序「' . $gymc . '」') : ('记录#' . $id);
- $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
- if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
- throw new \InvalidArgumentException($label . '已结束,不能再修改');
- }
- $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, $label, $row);
- if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
- if (!empty($user['is_admin'])) {
- throw new \InvalidArgumentException('当前账号仅可查看,不能修改单价与交货日期');
- }
- // 截止后 / 已开标 canEdit=false,统一给明确文案
- if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
- throw new \InvalidArgumentException($label . '已开标验证,不可再提交');
- }
- if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
- throw new \InvalidArgumentException($label . '已超过招标截止时间,不可再提交');
- }
- throw new \InvalidArgumentException($label . '无权修改');
- }
- $this->mprocEnsureLeadDaysColumn();
- $amountRaw = trim($amountRaw);
- $deliveryRaw = trim($deliveryRaw);
- $leadRaw = trim((string)($leadDaysRaw ?? ''));
- $hasAmt = $amountRaw !== '';
- $hasLead = $leadRaw !== '';
- $hasDel = $deliveryRaw !== '';
- $isManualRfq = ($sid < 0);
- if ($isManualRfq) {
- // 手工询价:只需填写单价
- if (!$hasAmt) {
- throw new \InvalidArgumentException($label . '请填写单价');
- }
- } else {
- $filledCount = ($hasAmt ? 1 : 0) + ($hasLead ? 1 : 0) + ($hasDel ? 1 : 0);
- if ($filledCount === 0) {
- throw new \InvalidArgumentException($label . '请填写单价、工期、交期');
- }
- if ($filledCount < 3) {
- if (!$hasAmt) {
- throw new \InvalidArgumentException($label . '请填写单价');
- }
- if (!$hasLead) {
- throw new \InvalidArgumentException($label . '请填写工期');
- }
- throw new \InvalidArgumentException($label . '请填写交期');
- }
- }
- $leadDays = null;
- if ($leadRaw !== '') {
- if (!preg_match('/^\d+$/', $leadRaw)) {
- throw new \InvalidArgumentException($label . '工期须为非负整数(天)');
- }
- $leadDays = (int)$leadRaw;
- }
- $data = [];
- if ($amountRaw === '') {
- $data['amount'] = null;
- } else {
- if (!preg_match('/^\d+(\.\d{1,5})?$/', $amountRaw)) {
- throw new \InvalidArgumentException($label . '单价格式不正确,最多五位小数');
- }
- if ((float)$amountRaw <= 0) {
- throw new \InvalidArgumentException($label . '单价必须大于0');
- }
- $ceilingLimit = $this->mprocResolveCeilingPriceForDetailRow($row);
- if ($ceilingLimit !== null && (float)$amountRaw > $ceilingLimit) {
- throw new \InvalidArgumentException(
- $label . '单价不能超过最高限价 ' . $this->mprocFormatCeilingPriceDisplay($ceilingLimit)
- );
- }
- $data['amount'] = $amountRaw;
- }
- if ($deliveryRaw === '') {
- $data['delivery'] = null;
- } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryRaw)) {
- $existingDel = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
- $timePart = date('H:i:s');
- if ($existingDel !== '') {
- $tsEx = strtotime(str_replace('T', ' ', $existingDel));
- if ($tsEx !== false) {
- $hms = date('H:i:s', $tsEx);
- if ($hms !== '00:00:00') {
- $timePart = $hms;
- }
- }
- }
- $data['delivery'] = $deliveryRaw . ' ' . $timePart;
- } else {
- $deliveryRaw = str_replace('T', ' ', $deliveryRaw);
- $ts = strtotime($deliveryRaw);
- if ($ts === false) {
- throw new \InvalidArgumentException($label . '交期时间格式不正确');
- }
- $data['delivery'] = date('Y-m-d H:i:s', $ts);
- }
- // 工期 ↔ 交货日期互通:仅填工期则推交期;仅填交期则推工期
- if (($data['delivery'] === null || $data['delivery'] === '') && $leadDays !== null) {
- $data['delivery'] = $this->mprocAddDaysToToday($leadDays) . ' ' . date('H:i:s');
- }
- if ($leadDays === null && !empty($data['delivery'])) {
- $ymd = substr((string)$data['delivery'], 0, 10);
- $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($ymd);
- if ($calc !== null) {
- $leadDays = max(0, $calc);
- }
- }
- $data['lead_days'] = $leadDays;
- $dcCol = $this->mprocResolveProcuremenColumn(['delivery_createtime', 'deliverycreatetime']);
- if ($dcCol !== null) {
- $shouldStampQuoteTime = false;
- if (array_key_exists('delivery', $data) && $data['delivery'] !== null && $data['delivery'] !== '') {
- $shouldStampQuoteTime = true;
- }
- // 手工询价只填单价:有单价也记报价时间
- if ($isManualRfq && array_key_exists('amount', $data) && $data['amount'] !== null && $data['amount'] !== '') {
- $shouldStampQuoteTime = true;
- }
- if ($shouldStampQuoteTime) {
- $data[$dcCol] = date('Y-m-d H:i:s');
- }
- }
- $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
- if ($upCol !== null) {
- $data[$upCol] = date('Y-m-d H:i:s');
- }
- $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
- if ($statusNameCol !== null) {
- $curSn = '';
- foreach ($row as $k => $v) {
- if (strcasecmp((string)$k, $statusNameCol) === 0) {
- $curSn = trim((string)$v);
- break;
- }
- }
- if ($curSn !== '已完成') {
- $effAm = array_key_exists('amount', $data) ? $data['amount'] : ($row['amount'] ?? null);
- $effDv = array_key_exists('delivery', $data) ? trim((string)$data['delivery']) : trim((string)($row['delivery'] ?? ''));
- $amountFilled = !($effAm === null || $effAm === '' || (is_string($effAm) && trim($effAm) === ''));
- $deliveryFilled = ($effDv !== '' && !preg_match('/^0000-00-00/i', $effDv));
- $data[$statusNameCol] = ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
- }
- }
- $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
- $pkVal = (int)($row[$pkField] ?? $id);
- try {
- $aff = Db::table('purchase_order_detail')->where($pkField, $pkVal)->update($data);
- } catch (\Throwable $e) {
- $msg = $e->getMessage();
- if (stripos($msg, 'Unknown column') !== false) {
- $msg = '请确认数据表 purchase_order_detail 已包含 amount、delivery、lead_days 字段';
- }
- throw new \RuntimeException('保存失败:' . $msg);
- }
- if ($aff === false) {
- throw new \RuntimeException($label . '保存失败');
- }
- return $gymc;
- }
- /**
- * 保存同订单号+供应商下的整单备注(写入该组全部明细行)
- *
- * @param array<string, mixed> $user
- * @param int[] $detailIds 本次保存涉及的明细 ID
- * @param string $remarkRaw
- */
- protected function mprocSaveOrderGroupRemark(array $user, array $detailIds, string $remarkRaw): void
- {
- $remarkCol = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
- if ($remarkCol === null) {
- return;
- }
- $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
- if ($detailIds === []) {
- return;
- }
- $anchorId = $detailIds[0];
- $row = null;
- try {
- $row = Db::table('purchase_order_detail')->where('id', $anchorId)->find();
- if (!$row) {
- $row = Db::table('purchase_order_detail')->where('ID', $anchorId)->find();
- }
- } catch (\Throwable $e) {
- $row = null;
- }
- if (!$row || !is_array($row)) {
- throw new \InvalidArgumentException('记录不存在');
- }
- $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
- $po = null;
- if ($this->mprocIsValidScydgyRowId($sid)) {
- try {
- $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
- } catch (\Throwable $e) {
- $po = null;
- }
- if (is_array($po)) {
- $this->mprocMergePurchaseOrderIntoDetail($row, $po);
- }
- }
- $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
- if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
- throw new \InvalidArgumentException('订单已结束,不能再修改备注');
- }
- $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, '', $row);
- if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
- if (!empty($user['is_admin'])) {
- throw new \InvalidArgumentException('当前账号仅可查看,不能修改备注');
- }
- if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
- throw new \InvalidArgumentException('已开标验证,不可再提交');
- }
- if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
- throw new \InvalidArgumentException('已超过招标截止时间,不可再提交');
- }
- throw new \InvalidArgumentException('无权修改备注');
- }
- $orderMbz = '';
- if (is_array($po)) {
- $orderMbz = trim((string)($po['MBZ'] ?? $po['mbz'] ?? ''));
- }
- $remarkRaw = $this->mprocSupplierOwnRemark($remarkRaw, $orderMbz);
- $ccydhCol = $this->mprocResolveProcuremenColumn(['ccydh']);
- $companyCol = $this->mprocResolveProcuremenColumn(['company_name']);
- if ($ccydhCol === null || $companyCol === null) {
- return;
- }
- $ccydh = '';
- $company = '';
- foreach ($row as $k => $v) {
- if (strcasecmp((string)$k, $ccydhCol) === 0) {
- $ccydh = trim((string)$v);
- } elseif (strcasecmp((string)$k, $companyCol) === 0) {
- $company = trim((string)$v);
- }
- }
- if ($ccydh === '' || $company === '') {
- $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
- $data = [$remarkCol => ($remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8'))];
- $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
- if ($upCol !== null) {
- $data[$upCol] = date('Y-m-d H:i:s');
- }
- Db::table('purchase_order_detail')->where($pkField, (int)($row[$pkField] ?? $anchorId))->update($data);
- return;
- }
- $remarkVal = $remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8');
- $data = [$remarkCol => $remarkVal];
- $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
- if ($upCol !== null) {
- $data[$upCol] = date('Y-m-d H:i:s');
- }
- $query = Db::table('purchase_order_detail')
- ->where($ccydhCol, $ccydh)
- ->where($companyCol, $company);
- $userWhere = $this->mprocListWhereForLoginUser($user);
- if ($userWhere !== []) {
- $query->where($userWhere);
- }
- try {
- $query->update($data);
- } catch (\Throwable $e) {
- throw new \RuntimeException('备注保存失败:' . $e->getMessage());
- }
- }
- /**
- * 保存协助明细金额、交期、工期
- * 单条:POST id、amount、delivery、lead_days
- * 批量:POST items=[{id,amount,delivery,lead_days},...] JSON
- */
- public function mprocSave()
- {
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $user = $this->mprocGetUser();
- if (!$user) {
- $this->error('请先登录', url('index/index/login'));
- }
- // Frontend 默认 filter 含 htmlspecialchars,会把 JSON 的双引号变成 " 导致解析失败
- $itemsRaw = $this->request->post('items', '', null);
- if ($itemsRaw === '' || $itemsRaw === null) {
- $itemsRaw = isset($_POST['items']) ? $_POST['items'] : '';
- }
- if (is_string($itemsRaw) && $itemsRaw !== '' && strpos($itemsRaw, '"') !== false) {
- $itemsRaw = htmlspecialchars_decode($itemsRaw, ENT_QUOTES);
- }
- $items = [];
- if (is_string($itemsRaw) && trim($itemsRaw) !== '') {
- $decoded = json_decode($itemsRaw, true);
- if (!is_array($decoded)) {
- $decoded = json_decode(htmlspecialchars_decode($itemsRaw, ENT_QUOTES), true);
- }
- if (is_array($decoded)) {
- $items = $decoded;
- }
- } elseif (is_array($itemsRaw)) {
- $items = $itemsRaw;
- }
- if ($items === []) {
- $id = (int)$this->request->post('id', 0, null);
- if ($id <= 0) {
- $this->error('保存失败,请关闭弹窗后重试');
- }
- $items = [[
- 'id' => $id,
- 'amount' => (string)$this->request->post('amount', '', null),
- 'delivery' => (string)$this->request->post('delivery', '', null),
- 'lead_days' => (string)$this->request->post('lead_days', '', null),
- ]];
- }
- $saved = 0;
- $savedIds = [];
- $remarkRaw = $this->request->post('remark', '', null);
- if ($remarkRaw === '' || $remarkRaw === null) {
- $remarkRaw = isset($_POST['remark']) ? $_POST['remark'] : '';
- }
- $remarkRaw = trim(htmlspecialchars_decode((string)$remarkRaw, ENT_QUOTES));
- Db::startTrans();
- try {
- foreach ($items as $it) {
- if (!is_array($it)) {
- continue;
- }
- $id = (int)($it['id'] ?? $it['eid'] ?? 0);
- if ($id <= 0) {
- continue;
- }
- $delivery = (string)($it['delivery'] ?? '');
- // 兼容部分手机浏览器把日期显示/提交成 2026/07/24
- if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})$/', trim($delivery), $dm)) {
- $delivery = sprintf('%04d-%02d-%02d', (int)$dm[1], (int)$dm[2], (int)$dm[3]);
- }
- $leadDays = (string)($it['lead_days'] ?? $it['leadDays'] ?? '');
- $amount = trim((string)($it['amount'] ?? ''));
- $leadDays = trim($leadDays);
- $delivery = trim($delivery);
- // 全空工序跳过:多工序时允许只保存已填全的
- if ($amount === '' && $leadDays === '' && $delivery === '') {
- continue;
- }
- $this->mprocSaveDetailQuote(
- $user,
- $id,
- $amount,
- $delivery,
- $leadDays
- );
- $saved++;
- $savedIds[] = $id;
- }
- if ($saved < 1) {
- throw new \InvalidArgumentException('请填写单价、工期、交期');
- }
- $this->mprocSaveOrderGroupRemark($user, $savedIds, $remarkRaw);
- Db::commit();
- } catch (\InvalidArgumentException $e) {
- Db::rollback();
- $this->error($e->getMessage());
- } catch (\Throwable $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->success($saved > 1 ? ('已保存 ' . $saved . ' 道工序') : '已保存');
- }
- /**
- * 修改密码(POST:old_password、new_password、renew_password)
- * 支持供应商 customer 与手机端管理员 admin
- */
- public function mprocChangePwd()
- {
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $user = $this->mprocGetUser();
- if (!$user) {
- $this->error('请先登录', url('index/index/login'));
- }
- $oldPwd = (string)$this->request->post('old_password', '');
- $newPwd = (string)$this->request->post('new_password', '');
- $renewPwd = (string)$this->request->post('renew_password', '');
- if ($oldPwd === '' || $newPwd === '' || $renewPwd === '') {
- $this->error('请填写完整');
- }
- $pwdErr = $this->mprocValidateStrongPassword($newPwd);
- if ($pwdErr !== '') {
- $this->error($pwdErr);
- }
- if ($newPwd !== $renewPwd) {
- $this->error('两次输入的新密码不一致');
- }
- if ($oldPwd === $newPwd) {
- $this->error('新密码不能与旧密码相同');
- }
- if (!empty($user['is_admin'])) {
- $adminId = (int)($user['admin_id'] ?? 0);
- if ($adminId <= 0) {
- $this->error('账号不存在或已禁用');
- }
- $row = null;
- try {
- $row = Db::name('admin')
- ->field('id,username,password,salt,status')
- ->where('id', $adminId)
- ->find();
- } catch (\Throwable $e) {
- $row = null;
- }
- if (!$row || !is_array($row) || (($row['status'] ?? '') === 'hidden')) {
- $this->error('账号不存在或已禁用');
- }
- $salt = (string)($row['salt'] ?? '');
- $hashStored = (string)($row['password'] ?? '');
- $hashOld = md5(md5($oldPwd) . $salt);
- if ($hashStored === '' || $hashOld !== $hashStored) {
- $this->error('原密码不正确');
- }
- $hashNew = md5(md5($newPwd) . $salt);
- try {
- Db::name('admin')->where('id', $adminId)->update([
- 'password' => $hashNew,
- 'updatetime' => time(),
- ]);
- } catch (\Throwable $e) {
- $this->error('修改失败:' . $e->getMessage());
- }
- } else {
- $user = $this->mprocSyncSessionCustomerUser($user);
- $cu = $this->mprocResolveCustomerUserForSession($user);
- if (!$cu) {
- $this->error('账号不存在或已禁用');
- }
- $cuId = (int)($cu['id'] ?? 0);
- if (!$this->mprocVerifyCustomerUserPassword($cu, $oldPwd)) {
- $this->error('原密码不正确');
- }
- $data = [
- 'password' => $this->mprocHashCustomerUserPassword($newPwd),
- 'updatetime' => date('Y-m-d H:i:s'),
- ];
- try {
- Db::table('customer')->where('id', $cuId)->update($data);
- } catch (\Throwable $e) {
- $this->error('修改失败:' . $e->getMessage());
- }
- }
- // 改密后强制重新登录
- $token = Session::get('mproc_token');
- if ($token === null || $token === '') {
- $token = Cookie::get('mproc_token');
- }
- if ($token === null || $token === '') {
- $token = Cookie::get('mproc_remember');
- }
- $this->mprocClearLogin((string)$token);
- $this->success('密码已修改,请重新登录', url('index/index/login'));
- }
- /**
- * 退出登录
- */
- public function logout()
- {
- $token = Session::get('mproc_token');
- if ($token === null || $token === '') {
- $token = Cookie::get('mproc_token');
- }
- if ($token === null || $token === '') {
- $token = Cookie::get('mproc_remember');
- }
- // 无论有无 token 都清 Cookie/Session,避免「记住登录」把用户又带回来
- $this->mprocClearLogin((string)$token);
- $this->redirect(url('index/index/login'));
- }
- /**
- * 短信宝(与后台协助审核一致,便于复用账号)
- *
- * @throws \Exception
- */
- protected function mprocSmsSend($phone, $content)
- {
- $statusStr = [
- '0' => '短信发送成功',
- '-1' => '参数不全',
- '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
- '30' => '密码错误',
- '40' => '账号不存在',
- '41' => '余额不足',
- '42' => '帐户已过期',
- '43' => 'IP地址限制',
- '50' => '内容含有敏感词',
- ];
- $smsapi = 'http://api.smsbao.com/';
- $user = trim((string)Config::get('mproc.smsbao_user'));
- if ($user === '') {
- $user = 'zhuwei123';
- }
- $passPlain = Config::get('mproc.smsbao_pass');
- $pass = ($passPlain !== null && $passPlain !== '')
- ? md5((string)$passPlain)
- : md5('1d1e605c101e4c1f8a156c6d7b19f126');
- $phone = trim((string)$phone);
- $content = trim((string)$content);
- if ($phone === '' || $content === '') {
- throw new \Exception('短信发送失败:参数不全');
- }
- $sendurl = $smsapi . 'sms?u=' . rawurlencode($user) . '&p=' . $pass . '&m=' . rawurlencode($phone) . '&c=' . rawurlencode($content);
- $result = @file_get_contents($sendurl);
- if ($result === false) {
- Log::record('smsbao 请求失败 phone=' . $phone . ' content=' . $content, 'error');
- throw new \Exception('短信发送失败:网络异常');
- }
- $result = trim((string)$result);
- if ($result !== '0') {
- $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
- Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg . ' content=' . $content, 'error');
- throw new \Exception('短信发送失败:' . $msg);
- }
- Log::record('smsbao 发送成功 phone=' . $phone . ' content=' . $content, 'info');
- }
- /**
- * 质量评分页(质检中心:合格/投诉/中断)
- */
- public function inboundscore()
- {
- $user = $this->mprocGetUser();
- if (!$user) {
- $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
- $safe = $this->mprocSanitizeRedirectUrl($uri);
- if ($safe !== '') {
- Session::set('mproc_intended_url', $safe);
- }
- $this->redirect($this->mprocBuildLoginUrl($safe));
- return;
- }
- if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'quality')) {
- $jump = $this->mprocBuildAfterLoginHomeUrl($user);
- if ($jump === '') {
- $this->mprocDropCurrentLogin();
- $this->redirect(url('index/index/login'));
- return;
- }
- $this->redirect($jump);
- return;
- }
- $this->mprocEnsureInboundScoreTable();
- $q = trim((string)$this->request->get('q', ''));
- $profile = $this->mprocProfileForUser($user);
- $this->view->assign('mprocSearchQ', $q);
- $this->view->assign('mprocProfile', $profile);
- $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
- $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
- $this->view->assign('mprocScoreScope', 'quality');
- $this->view->assign('rows', $this->mprocLoadInboundScoreRows('pending', $q, (int)($user['admin_id'] ?? 0), 'quality'));
- return $this->view->fetch();
- }
- /**
- * 交货情况页(生产部:准时/滞后)
- */
- public function deliveryscore()
- {
- $user = $this->mprocGetUser();
- if (!$user) {
- $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
- $safe = $this->mprocSanitizeRedirectUrl($uri);
- if ($safe !== '') {
- Session::set('mproc_intended_url', $safe);
- }
- $this->redirect($this->mprocBuildLoginUrl($safe));
- return;
- }
- if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'delivery')) {
- $jump = $this->mprocBuildAfterLoginHomeUrl($user);
- if ($jump === '') {
- $this->mprocDropCurrentLogin();
- $this->redirect(url('index/index/login'));
- return;
- }
- $this->redirect($jump);
- return;
- }
- $this->mprocEnsureInboundScoreTable();
- $ccydh = trim((string)$this->request->get('ccydh', ''));
- $q = trim((string)$this->request->get('q', ''));
- if ($q === '' && $ccydh !== '') {
- $q = $ccydh;
- }
- if ($ccydh === '' && $q !== '') {
- $ccydh = $q;
- }
- $adminId = (int)($user['admin_id'] ?? 0);
- $scoreTab = trim((string)$this->request->get('tab', ''));
- if (!in_array($scoreTab, ['pending', 'scored'], true)) {
- $scoreTab = 'pending';
- }
- $rows = $this->mprocLoadInboundScoreRows($scoreTab, $q, $adminId, 'delivery');
- if ($ccydh !== '' && $rows === [] && $scoreTab === 'pending') {
- $scored = $this->mprocLoadInboundScoreRows('scored', $q, $adminId, 'delivery');
- if ($scored !== []) {
- $scoreTab = 'scored';
- $rows = $scored;
- }
- }
- $profile = $this->mprocProfileForUser($user);
- $this->view->assign('mprocSearchQ', $q);
- $this->view->assign('mprocFocusCcydh', $ccydh);
- $this->view->assign('mprocScoreTab', $scoreTab);
- $this->view->assign('mprocProfile', $profile);
- $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
- $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
- $this->view->assign('mprocScoreScope', 'delivery');
- $this->view->assign('rows', $rows);
- return $this->view->fetch();
- }
- /**
- * 供应商送货单(中标后出示二维码,生产部扫码进入交货评估)
- */
- public function deliverynote()
- {
- $user = $this->mprocGetUser();
- if (!$user) {
- $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
- $safe = $this->mprocSanitizeRedirectUrl($uri);
- if ($safe !== '') {
- Session::set('mproc_intended_url', $safe);
- }
- $this->redirect($this->mprocBuildLoginUrl($safe));
- return;
- }
- if (!empty($user['is_admin'])) {
- $jump = $this->mprocBuildAfterLoginHomeUrl($user);
- if ($jump === '') {
- $this->mprocDropCurrentLogin();
- $this->redirect(url('index/index/login'));
- return;
- }
- $this->redirect($jump);
- return;
- }
- $user = $this->mprocSyncSessionCustomerUser($user);
- $ccydh = trim((string)$this->request->param('ccydh', ''));
- $checkOnly = (int)$this->request->param('check', 0) === 1;
- $note = $this->mprocLoadWonDeliveryNote($user, $ccydh);
- if ($note === null) {
- // 列表点「送货码」先 Ajax check:当前页 Toast;直达链接仍走轻提示页
- $this->error('未找到该中标订单的送货单', $checkOnly ? null : url('index/index/index', ['tab' => 'done']));
- return;
- }
- if ($checkOnly) {
- $this->success('ok');
- return;
- }
- $this->view->assign('note', $note);
- return $this->view->fetch();
- }
- /**
- * 当前供应商的中标送货单数据;无权或不存在返回 null
- *
- * @param array<string, mixed> $user
- * @return array<string, mixed>|null
- */
- protected function mprocLoadWonDeliveryNote(array $user, string $ccydh): ?array
- {
- $ccydh = trim($ccydh);
- if ($ccydh === '') {
- return null;
- }
- $company = trim((string)($user['company_name'] ?? ''));
- $phone = trim((string)($user['phone'] ?? ''));
- if ($company === '' && $phone !== '') {
- $company = $this->mprocResolveCompanyForLoginPhone($phone);
- }
- try {
- $poRows = Db::table('purchase_order')
- ->where('CCYDH', $ccydh)
- ->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%\')')
- ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CDW,CDF,MBZ,cGzzxMc,CCLBMMC,CDXMC,This_quantity,NGZL,pick_company_name,pick_time,wflow_status,status')
- ->order('id', 'asc')
- ->select();
- } catch (\Throwable $e) {
- $poRows = [];
- }
- if (!is_array($poRows) || $poRows === []) {
- return null;
- }
- $won = false;
- $gymcList = [];
- $qtyList = [];
- foreach ($poRows as $po) {
- if (!is_array($po)) {
- continue;
- }
- $pick = trim((string)($po['pick_company_name'] ?? ''));
- if ($pick !== '' && $company !== '' && $pick === $company) {
- $won = true;
- }
- $gx = trim((string)($po['CGYMC'] ?? ''));
- if ($gx !== '' && !in_array($gx, $gymcList, true)) {
- $gymcList[] = $gx;
- }
- $qDisp = $this->mprocResolveDisplayThisQuantity($po);
- if ($qDisp !== '') {
- $qtyList[] = $qDisp;
- }
- }
- $qtyList = array_values(array_unique($qtyList));
- $orderQty = $qtyList !== [] ? implode('、', $qtyList) : '';
- // 本次送货数量暂无独立数据,留空由页面原样展示
- $deliveryQty = '';
- $detailPhone = '';
- try {
- $dq = Db::table('purchase_order_detail')->where('CCYDH', $ccydh);
- $userWhere = $this->mprocListWhereForLoginUser($user);
- if ($userWhere !== []) {
- $dq->where($userWhere);
- }
- $details = $dq->field('id,scydgy_id,company_name,phone,status,status_name,remark')->select();
- } catch (\Throwable $e) {
- $details = [];
- }
- if (is_array($details)) {
- foreach ($details as $d) {
- if (!is_array($d)) {
- continue;
- }
- if ($detailPhone === '') {
- $detailPhone = trim((string)($d['phone'] ?? ''));
- }
- $dCn = trim((string)($d['company_name'] ?? ''));
- if ($dCn !== '' && $company !== '' && $dCn === $company) {
- if (ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
- $won = true;
- }
- }
- }
- }
- if (!$won) {
- return null;
- }
- $pickFirst = static function (array $rows, array $keys): string {
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- foreach ($keys as $k) {
- $v = trim((string)($row[$k] ?? ''));
- if ($v !== '') {
- return $v;
- }
- }
- }
- return '';
- };
- $profile = $this->mprocProfileForUser($user);
- $supplierName = trim((string)($profile['company_name'] ?? ''));
- if ($supplierName === '') {
- $supplierName = $company;
- }
- if ($supplierName === '') {
- $supplierName = $pickFirst($poRows, ['pick_company_name']);
- }
- $mobile = trim((string)($profile['phone'] ?? ''));
- if ($mobile === '') {
- $mobile = $phone !== '' ? $phone : $detailPhone;
- }
- $contact = trim((string)($profile['contact_name'] ?? ''));
- $customerName = trim((string)Config::get('mproc.delivery_customer_name'));
- if ($customerName === '') {
- $customerName = '浙江新华数码印务有限公司';
- }
- $address = trim((string)Config::get('mproc.delivery_address'));
- if ($address === '') {
- $address = '杭州市经济技术开发区文海北路369号';
- }
- $base = $this->mprocDeliveryScanBaseUrl();
- $scanUrl = $base . $this->mprocDeliveryScanPath() . '?' . http_build_query(
- ['ccydh' => $ccydh, 'q' => $ccydh],
- '',
- '&',
- PHP_QUERY_RFC3986
- );
- return [
- 'generated_at' => $this->mprocDeliveryNoteGeneratedAt($ccydh, $supplierName),
- 'ccydh' => $ccydh,
- 'cyjmc' => $pickFirst($poRows, ['CYJMC']),
- 'cgymc' => $gymcList !== [] ? implode('、', $gymcList) : '',
- 'cdw' => $pickFirst($poRows, ['CDW']),
- 'cdf' => $pickFirst($poRows, ['CDF']),
- 'remark' => $pickFirst($poRows, ['MBZ']),
- 'order_qty' => $orderQty,
- 'delivery_qty' => $deliveryQty,
- 'customer_name' => $customerName,
- 'address' => $address,
- 'supplier_name' => $supplierName,
- 'contact_name' => $contact,
- 'mobile' => $mobile,
- 'scan_url' => $scanUrl,
- 'qr_data_uri' => $this->mprocDeliveryQrDataUri($scanUrl),
- ];
- }
- /**
- * 送货单首次生成时间:点过送货码后保持不变
- */
- protected function mprocDeliveryNoteGeneratedAt(string $ccydh, string $company): string
- {
- $now = date('Y-m-d H:i:s');
- $this->mprocEnsureDeliveryNoteTable();
- try {
- $q = Db::table('purchase_order_delivery_note')->where('ccydh', $ccydh);
- if ($company !== '') {
- $q->where('company_name', $company);
- }
- $row = $q->order('id', 'asc')->find();
- if (is_array($row) && trim((string)($row['generated_at'] ?? '')) !== '') {
- $t = strtotime((string)$row['generated_at']);
- return $t ? date('Y-m-d H:i', $t) : date('Y-m-d H:i');
- }
- Db::table('purchase_order_delivery_note')->insert([
- 'ccydh' => $ccydh,
- 'company_name' => $company,
- 'generated_at' => $now,
- 'createtime' => $now,
- 'updatetime' => $now,
- ]);
- return date('Y-m-d H:i');
- } catch (\Throwable $e) {
- return date('Y-m-d H:i');
- }
- }
- protected function mprocEnsureDeliveryNoteTable(): void
- {
- static $ok = false;
- if ($ok) {
- return;
- }
- try {
- Db::query('SELECT 1 FROM `purchase_order_delivery_note` LIMIT 1');
- $ok = true;
- } catch (\Throwable $e) {
- try {
- Db::execute("CREATE TABLE IF NOT EXISTS `purchase_order_delivery_note` (
- `id` int unsigned NOT NULL AUTO_INCREMENT,
- `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
- `company_name` varchar(255) NOT NULL DEFAULT '' COMMENT '供应商',
- `generated_at` datetime NOT NULL COMMENT '首次生成时间',
- `createtime` datetime DEFAULT NULL,
- `updatetime` datetime DEFAULT NULL,
- PRIMARY KEY (`id`),
- UNIQUE KEY `uk_ccydh_company` (`ccydh`,`company_name`(64))
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='送货单首次生成记录'");
- $ok = true;
- } catch (\Throwable $e2) {
- }
- }
- }
- /**
- * QR Code 容错 H(约 30%),输出 data URI,避免手机端 canvas 空白
- */
- protected function mprocDeliveryQrDataUri(string $text): string
- {
- $text = trim($text);
- if ($text === '' || !function_exists('imagepng')) {
- return '';
- }
- $lib = ROOT_PATH . 'extend' . DIRECTORY_SEPARATOR . 'phpqrcode' . DIRECTORY_SEPARATOR . 'phpqrcode.php';
- if (!is_file($lib)) {
- return '';
- }
- if (!class_exists('QRcode', false)) {
- require_once $lib;
- }
- if (!class_exists('QRcode')) {
- return '';
- }
- $tmp = tempnam(sys_get_temp_dir(), 'dnqr');
- if ($tmp === false) {
- return '';
- }
- $bin = '';
- try {
- \QRcode::png($text, $tmp, 'H', 6, 2);
- $bin = is_file($tmp) ? (string)file_get_contents($tmp) : '';
- } catch (\Throwable $e) {
- $bin = '';
- }
- if (is_file($tmp)) {
- @unlink($tmp);
- }
- if ($bin === '' || strncmp($bin, "\x89PNG", 4) !== 0) {
- return '';
- }
- return 'data:image/png;base64,' . base64_encode($bin);
- }
- /**
- * 送货单二维码根地址:与邮件链接共用 mproc.mobile_base_url;未配则用当前访问根地址。
- */
- protected function mprocDeliveryScanBaseUrl(): string
- {
- $cfg = rtrim(trim((string)Config::get('mproc.mobile_base_url')), '/');
- if ($cfg !== '' && preg_match('#^https?://#i', $cfg)) {
- return $cfg;
- }
- return rtrim((string)$this->request->root(true), '/');
- }
- /**
- * 送货单扫码路径。局域网 IP 通常没有伪静态,必须带 /index.php
- */
- protected function mprocDeliveryScanPath(): string
- {
- $indexPath = trim((string)Config::get('mproc.mobile_index_path'));
- if ($indexPath === '') {
- $indexPath = '/index.php/index/index/index';
- } else {
- $indexPath = '/' . ltrim($indexPath, '/');
- }
- $path = preg_replace('#/index$#', '/deliveryscore', rtrim($indexPath, '/'));
- if (!is_string($path) || $path === '' || substr($path, -6) === '/index') {
- return '/index.php/index/index/deliveryscore';
- }
- return $path;
- }
- protected function mprocIsLanIpv4(string $ip): bool
- {
- if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
- return false;
- }
- if ($ip === '127.0.0.1' || strpos($ip, '127.') === 0 || strpos($ip, '169.254.') === 0) {
- return false;
- }
- return (bool)preg_match('/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|20\.0\.)/', $ip);
- }
- protected function mprocDetectLanIpv4(): string
- {
- if (function_exists('socket_create')) {
- $sock = @socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
- if ($sock) {
- @socket_connect($sock, '8.8.8.8', 53);
- $addr = '';
- @socket_getsockname($sock, $addr);
- @socket_close($sock);
- if (is_string($addr) && $this->mprocIsLanIpv4($addr)) {
- return $addr;
- }
- }
- }
- if (strncasecmp(PHP_OS, 'WIN', 3) === 0) {
- $out = @shell_exec('ipconfig');
- if (is_string($out) && preg_match_all('/IPv4[^0-9]+(\d+\.\d+\.\d+\.\d+)/', $out, $m)) {
- foreach ($m[1] as $ip) {
- if ($this->mprocIsLanIpv4((string)$ip)) {
- return (string)$ip;
- }
- }
- }
- }
- $guess = gethostbyname(gethostname());
- if (is_string($guess) && $this->mprocIsLanIpv4($guess)) {
- return $guess;
- }
- return '';
- }
- /**
- * 质量评分列表 JSON(质检;tab=pending|scored)
- */
- public function inboundscorelist()
- {
- $user = $this->mprocRequireQualityUser();
- $this->mprocEnsureInboundScoreTable();
- $q = trim((string)$this->request->request('q', ''));
- $tab = trim((string)$this->request->request('tab', 'pending'));
- if (!in_array($tab, ['pending', 'scored', 'pass', 'fail'], true)) {
- $tab = 'pending';
- }
- if ($tab === 'pass' || $tab === 'fail') {
- $tab = 'scored';
- }
- $adminId = (int)($user['admin_id'] ?? 0);
- $rows = $this->mprocLoadInboundScoreRows($tab, $q, $adminId, 'quality');
- $this->success('ok', '', [
- 'tab' => $tab,
- 'q' => $q,
- 'scope' => 'quality',
- 'rows' => $rows,
- 'count' => count($rows),
- ]);
- }
- /**
- * 交货情况列表 JSON(生产部;tab=pending|scored)
- */
- public function deliveryscorelist()
- {
- $user = $this->mprocRequireDeliveryUser();
- $this->mprocEnsureInboundScoreTable();
- $q = trim((string)$this->request->request('q', ''));
- $tab = trim((string)$this->request->request('tab', 'pending'));
- if (!in_array($tab, ['pending', 'scored'], true)) {
- $tab = 'pending';
- }
- $adminId = (int)($user['admin_id'] ?? 0);
- $rows = $this->mprocLoadInboundScoreRows($tab, $q, $adminId, 'delivery');
- $this->success('ok', '', [
- 'tab' => $tab,
- 'q' => $q,
- 'scope' => 'delivery',
- 'rows' => $rows,
- 'count' => count($rows),
- ]);
- }
- /**
- * 交货情况 — 历史库位(去重,按使用次数多到少)
- */
- public function deliverystoragelocations()
- {
- $this->mprocRequireDeliveryUser();
- $this->mprocEnsureInboundScoreTable();
- $list = [];
- try {
- $rows = Db::table('purchase_order_inbound_score')
- ->where('storage_location', '<>', '')
- ->whereRaw("TRIM(storage_location) <> ''")
- ->field('storage_location, COUNT(*) AS use_cnt')
- ->group('storage_location')
- ->order('use_cnt', 'desc')
- ->order('storage_location', 'asc')
- ->limit(100)
- ->select();
- } catch (\Throwable $e) {
- $rows = [];
- }
- $seen = [];
- if (is_array($rows)) {
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $loc = trim((string)($row['storage_location'] ?? ''));
- if ($loc === '' || isset($seen[$loc])) {
- continue;
- }
- $seen[$loc] = true;
- $list[] = $loc;
- }
- }
- // group 失败时回退:按出现次数统计
- if ($list === []) {
- try {
- $raw = Db::table('purchase_order_inbound_score')
- ->where('storage_location', '<>', '')
- ->field('storage_location')
- ->order('id', 'desc')
- ->limit(1000)
- ->select();
- } catch (\Throwable $e) {
- $raw = [];
- }
- $cntMap = [];
- if (is_array($raw)) {
- foreach ($raw as $row) {
- if (!is_array($row)) {
- continue;
- }
- $loc = trim((string)($row['storage_location'] ?? ''));
- if ($loc === '') {
- continue;
- }
- $cntMap[$loc] = isset($cntMap[$loc]) ? ($cntMap[$loc] + 1) : 1;
- }
- }
- arsort($cntMap, SORT_NUMERIC);
- $list = array_keys($cntMap);
- if (count($list) > 100) {
- $list = array_slice($list, 0, 100);
- }
- }
- $this->success('ok', '', ['list' => array_values($list)]);
- }
- /**
- * 保存质量评分(质检中心)
- * POST:ccydh、result、order_interrupt、remark
- * 客诉事后由 inboundscorecomplaint 补登,首次默认否
- */
- public function inboundscoresave()
- {
- $user = $this->mprocRequireQualityUser();
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $this->mprocEnsureInboundScoreTable();
- $ccydh = trim((string)$this->request->post('ccydh', ''));
- $sid = (int)$this->request->post('scydgy_id', 0);
- $batchNo = trim((string)$this->request->post('order_batch_no', ''));
- $companyName = trim((string)$this->request->post('pick_company_name', ''));
- $result = trim((string)$this->request->post('result', ''));
- if ($result !== '合格' && $result !== '不合格') {
- $this->error('请选择生产是否合格');
- }
- $orderInterrupt = (int)$this->request->post('order_interrupt', -1);
- if ($orderInterrupt !== 0 && $orderInterrupt !== 1) {
- $this->error('请选择生产是否中断');
- }
- $remark = trim((string)$this->request->post('remark', ''));
- if ($result === '不合格' && $remark === '') {
- $this->error('请填写不合格原因');
- }
- if (mb_strlen($remark) > 500) {
- $remark = mb_substr($remark, 0, 500);
- }
- $poRows = $this->mprocLoadApprovedPoRowsForScore($ccydh, $sid, $batchNo, $companyName);
- $now = date('Y-m-d H:i:s');
- $adminId = (int)($user['admin_id'] ?? 0);
- $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
- $saved = 0;
- $firstSid = 0;
- $firstPoId = 0;
- $deliveryReady = true;
- try {
- Db::startTrans();
- foreach ($poRows as $po) {
- if (!is_array($po)) {
- continue;
- }
- $rowSid = (int)($po['scydgy_id'] ?? 0);
- if ($rowSid <= 0) {
- continue;
- }
- if ($firstSid <= 0) {
- $firstSid = $rowSid;
- $firstPoId = (int)($po['id'] ?? 0);
- }
- $exist = Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->find();
- $existDs = is_array($exist) ? trim((string)($exist['delivery_status'] ?? '')) : '';
- if ($existDs !== '准时' && $existDs !== '滞后') {
- $deliveryReady = false;
- }
- $data = [
- 'scydgy_id' => $rowSid,
- 'purchase_order_id' => (int)($po['id'] ?? 0),
- 'ccydh' => trim((string)($po['CCYDH'] ?? $ccydh)),
- 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
- 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
- 'company_name' => trim((string)($po['pick_company_name'] ?? '')),
- 'result' => $result,
- 'order_interrupt' => $orderInterrupt,
- 'remark' => $remark,
- 'admin_id' => $adminId,
- 'admin_name' => $adminName,
- 'updatetime' => $now,
- ];
- if (is_array($exist) && $exist !== []) {
- // 客诉事后补登,首次评分不覆盖已有客诉
- Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->update($data);
- } else {
- $data['customer_complaint'] = 0;
- $data['complaint_remark'] = '';
- $data['delivery_status'] = '';
- $data['createtime'] = $now;
- Db::table('purchase_order_inbound_score')->insert($data);
- $deliveryReady = false;
- }
- $saved++;
- }
- if ($saved < 1) {
- throw new \RuntimeException('没有可保存的工序');
- }
- if ($deliveryReady) {
- foreach ($poRows as $po) {
- if (!is_array($po)) {
- continue;
- }
- $rowSid = (int)($po['scydgy_id'] ?? 0);
- if ($rowSid > 0) {
- Db::table('purchase_order')->where('scydgy_id', $rowSid)->update([
- 'status' => ProcuremenStatus::PO_COMPLETED,
- ]);
- }
- }
- }
- Db::commit();
- } catch (\Throwable $e) {
- try {
- Db::rollback();
- } catch (\Throwable $e2) {
- }
- Log::record('inboundscoresave fail: ' . $e->getMessage(), 'error');
- $this->error('保存失败,请稍后重试');
- }
- $logDetail = '质量评分:生产是否合格=' . $result
- . ';生产是否中断:' . ($orderInterrupt === 1 ? '是' : '否');
- if ($remark !== '') {
- $logDetail .= ';备注:' . $remark;
- }
- \app\common\library\ProcuremenOperLog::write(
- $firstSid,
- 'inbound_score',
- $logDetail,
- $firstPoId > 0 ? $firstPoId : null,
- [$adminId, $adminName]
- );
- $this->mprocSyncMonthlyAfterInboundScore($poRows, $now);
- if ($deliveryReady) {
- $this->mprocRefreshCompletedArchivePdfs($poRows);
- }
- $this->success('操作成功', '', [
- 'ccydh' => $ccydh,
- 'result' => $result,
- 'order_interrupt' => $orderInterrupt,
- 'remark' => $remark,
- 'count' => $saved,
- 'completed' => $deliveryReady ? 1 : 0,
- ]);
- }
- /**
- * 事后投诉反馈(质检中心,仅已质量评分订单)
- * POST:ccydh、customer_complaint=0|1、complaint_remark(投诉为是时必填)
- */
- public function inboundscorecomplaint()
- {
- $user = $this->mprocRequireQualityUser();
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $this->mprocEnsureInboundScoreTable();
- $ccydh = trim((string)$this->request->post('ccydh', ''));
- $sid = (int)$this->request->post('scydgy_id', 0);
- $customerComplaint = (int)$this->request->post('customer_complaint', -1);
- if ($customerComplaint !== 0 && $customerComplaint !== 1) {
- $this->error('请选择客户是否投诉');
- }
- $complaintRemark = trim((string)$this->request->post('complaint_remark', ''));
- if ($customerComplaint === 1 && $complaintRemark === '') {
- $this->error('请填写投诉说明');
- }
- if ($customerComplaint !== 1) {
- $complaintRemark = '';
- }
- if (mb_strlen($complaintRemark) > 500) {
- $complaintRemark = mb_substr($complaintRemark, 0, 500);
- }
- if ($ccydh === '' && $sid > 0) {
- try {
- $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
- $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
- } catch (\Throwable $e) {
- $ccydh = '';
- }
- }
- if ($ccydh === '') {
- $this->error('缺少订单号');
- }
- try {
- $scoreRows = Db::table('purchase_order_inbound_score')
- ->where('ccydh', $ccydh)
- ->field('id,scydgy_id,purchase_order_id,result,company_name')
- ->select();
- } catch (\Throwable $e) {
- $scoreRows = [];
- }
- if (!is_array($scoreRows) || $scoreRows === []) {
- $this->error('请先完成质量评分后再投诉反馈');
- }
- $hasQuality = false;
- foreach ($scoreRows as $sc) {
- if (!is_array($sc)) {
- continue;
- }
- $res = trim((string)($sc['result'] ?? ''));
- if ($res === '合格' || $res === '不合格') {
- $hasQuality = true;
- break;
- }
- }
- if (!$hasQuality) {
- $this->error('请先完成质量评分后再投诉反馈');
- }
- $now = date('Y-m-d H:i:s');
- $adminId = (int)($user['admin_id'] ?? 0);
- $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
- $firstSid = 0;
- $firstPoId = 0;
- $companyName = '';
- $updated = 0;
- try {
- Db::startTrans();
- foreach ($scoreRows as $sc) {
- if (!is_array($sc)) {
- continue;
- }
- $rowSid = (int)($sc['scydgy_id'] ?? 0);
- $id = (int)($sc['id'] ?? 0);
- if ($id <= 0) {
- continue;
- }
- if ($firstSid <= 0 && $rowSid > 0) {
- $firstSid = $rowSid;
- $firstPoId = (int)($sc['purchase_order_id'] ?? 0);
- }
- if ($companyName === '') {
- $companyName = trim((string)($sc['company_name'] ?? ''));
- }
- Db::table('purchase_order_inbound_score')->where('id', $id)->update([
- 'customer_complaint' => $customerComplaint,
- 'complaint_remark' => $complaintRemark,
- 'updatetime' => $now,
- ]);
- $updated++;
- }
- if ($updated < 1) {
- throw new \RuntimeException('没有可更新的记录');
- }
- Db::commit();
- } catch (\Throwable $e) {
- try {
- Db::rollback();
- } catch (\Throwable $e2) {
- }
- Log::record('inboundscorecomplaint fail: ' . $e->getMessage(), 'error');
- $this->error('保存失败,请稍后重试');
- }
- if ($firstSid > 0) {
- $logDetail = '投诉反馈:客户投诉=' . ($customerComplaint === 1 ? '是' : '否');
- if ($complaintRemark !== '') {
- $logDetail .= ';投诉说明:' . $complaintRemark;
- }
- \app\common\library\ProcuremenOperLog::write(
- $firstSid,
- 'inbound_score',
- $logDetail,
- $firstPoId > 0 ? $firstPoId : null,
- [$adminId, $adminName]
- );
- }
- if ($companyName !== '') {
- $scoreYm = date('Y-m', strtotime($now) ?: time());
- try {
- \app\common\library\ProcuremenSupplierScore::syncQualityScoreFromInbound($scoreYm, $companyName);
- } catch (\Throwable $e) {
- Log::record('inboundscorecomplaint quality sync: ' . $e->getMessage(), 'error');
- }
- }
- $this->success('操作成功', '', [
- 'ccydh' => $ccydh,
- 'customer_complaint' => $customerComplaint,
- 'complaint_remark' => $complaintRemark,
- 'count' => $updated,
- ]);
- }
- /**
- * 保存交货情况(生产部)
- * POST:ccydh、storage_location、delivery_status=准时|滞后、delivery_date=YYYY-MM-DD、remark
- */
- public function deliveryscoresave()
- {
- $user = $this->mprocRequireDeliveryUser();
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $this->mprocEnsureInboundScoreTable();
- $ccydh = trim((string)$this->request->post('ccydh', ''));
- $sid = (int)$this->request->post('scydgy_id', 0);
- $batchNo = trim((string)$this->request->post('order_batch_no', ''));
- $companyName = trim((string)$this->request->post('pick_company_name', ''));
- $storageLocation = trim((string)$this->request->post('storage_location', ''));
- if ($storageLocation === '') {
- $this->error('请填写库位');
- }
- if (mb_strlen($storageLocation) > 64) {
- $this->error('库位最多64个字符');
- }
- $deliveryStatus = trim((string)$this->request->post('delivery_status', ''));
- if ($deliveryStatus !== '准时' && $deliveryStatus !== '滞后') {
- $this->error('请选择交货情况');
- }
- $deliveryDate = trim((string)$this->request->post('delivery_date', ''));
- if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryDate)) {
- $this->error('请选择交货日期');
- }
- $ts = strtotime($deliveryDate . ' 00:00:00');
- if ($ts === false) {
- $this->error('交货日期格式不正确');
- }
- $deliveryDate = date('Y-m-d', $ts);
- $remark = trim((string)$this->request->post('remark', ''));
- if ($deliveryStatus === '滞后' && $remark === '') {
- $this->error('请填写滞后原因');
- }
- if (mb_strlen($remark) > 500) {
- $remark = mb_substr($remark, 0, 500);
- }
- $poRows = $this->mprocLoadApprovedPoRowsForScore($ccydh, $sid, $batchNo, $companyName);
- $deadlineYmd = '';
- foreach ($poRows as $po) {
- if (!is_array($po)) {
- continue;
- }
- $deadlineYmd = $this->mprocFormatYmdValue($po['delivery_deadline'] ?? $po['Delivery_deadline'] ?? '');
- if ($deadlineYmd !== '') {
- break;
- }
- }
- if ($deadlineYmd !== '' && $deliveryDate > $deadlineYmd && $deliveryStatus === '准时') {
- $this->error('交货日期已超过截止日期,只能选择滞后');
- }
- if ($deadlineYmd !== '' && $deliveryDate <= $deadlineYmd && $deliveryStatus === '滞后') {
- $this->error('已选择滞后请确认交货日期');
- }
- $now = date('Y-m-d H:i:s');
- $adminId = (int)($user['admin_id'] ?? 0);
- $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
- $saved = 0;
- $firstSid = 0;
- $firstPoId = 0;
- $qualityReady = true;
- try {
- Db::startTrans();
- foreach ($poRows as $po) {
- if (!is_array($po)) {
- continue;
- }
- $rowSid = (int)($po['scydgy_id'] ?? 0);
- if ($rowSid <= 0) {
- continue;
- }
- if ($firstSid <= 0) {
- $firstSid = $rowSid;
- $firstPoId = (int)($po['id'] ?? 0);
- }
- $exist = Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->find();
- $existResult = is_array($exist) ? trim((string)($exist['result'] ?? '')) : '';
- if ($existResult !== '合格' && $existResult !== '不合格') {
- $qualityReady = false;
- }
- $data = [
- 'scydgy_id' => $rowSid,
- 'purchase_order_id' => (int)($po['id'] ?? 0),
- 'ccydh' => trim((string)($po['CCYDH'] ?? $ccydh)),
- 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
- 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
- 'company_name' => trim((string)($po['pick_company_name'] ?? '')),
- 'storage_location' => $storageLocation,
- 'delivery_status' => $deliveryStatus,
- 'delivery_date' => $deliveryDate,
- 'remark' => $remark,
- 'delivery_admin_id' => $adminId,
- 'delivery_admin_name' => $adminName,
- 'updatetime' => $now,
- ];
- if (is_array($exist) && $exist !== []) {
- Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->update($data);
- } else {
- $data['result'] = '';
- $data['customer_complaint'] = 0;
- $data['complaint_remark'] = '';
- $data['order_interrupt'] = 0;
- $data['admin_id'] = $adminId;
- $data['admin_name'] = $adminName;
- $data['createtime'] = $now;
- Db::table('purchase_order_inbound_score')->insert($data);
- $qualityReady = false;
- }
- $saved++;
- }
- if ($saved < 1) {
- throw new \RuntimeException('没有可保存的工序');
- }
- if ($qualityReady) {
- foreach ($poRows as $po) {
- if (!is_array($po)) {
- continue;
- }
- $rowSid = (int)($po['scydgy_id'] ?? 0);
- if ($rowSid > 0) {
- Db::table('purchase_order')->where('scydgy_id', $rowSid)->update([
- 'status' => ProcuremenStatus::PO_COMPLETED,
- ]);
- }
- }
- }
- Db::commit();
- } catch (\Throwable $e) {
- try {
- Db::rollback();
- } catch (\Throwable $e2) {
- }
- Log::record('deliveryscoresave fail: ' . $e->getMessage(), 'error');
- $this->error('保存失败,请稍后重试');
- }
- $logDetail = '库位:' . $storageLocation . ';交货情况:' . $deliveryStatus . ';交货日期:' . $deliveryDate;
- if ($remark !== '') {
- $logDetail .= ';备注:' . $remark;
- }
- \app\common\library\ProcuremenOperLog::write(
- $firstSid,
- 'delivery_score',
- $logDetail,
- $firstPoId > 0 ? $firstPoId : null,
- [$adminId, $adminName]
- );
- $this->mprocSyncMonthlyAfterInboundScore($poRows, $now);
- if ($qualityReady) {
- $this->mprocRefreshCompletedArchivePdfs($poRows);
- }
- $this->success('操作成功', '', [
- 'ccydh' => $ccydh,
- 'storage_location' => $storageLocation,
- 'delivery_status' => $deliveryStatus,
- 'delivery_date' => $deliveryDate,
- 'remark' => $remark,
- 'count' => $saved,
- 'completed' => $qualityReady ? 1 : 0,
- ]);
- }
- /**
- * 交货情况(已确认)— 通知人员名单(质检中心 + 业务员)
- */
- public function deliverynotifymen()
- {
- $user = $this->mprocRequireDeliveryUser();
- $ccydh = trim((string)$this->request->request('ccydh', ''));
- $sid = (int)$this->request->request('scydgy_id', 0);
- $order = $this->mprocLoadDeliveryNotifyOrder($ccydh, $sid);
- if ($order === null) {
- $this->error('未找到可通知的订单');
- }
- $selfAdminId = (int)($user['admin_id'] ?? 0);
- $list = [];
- foreach ($this->mprocLoadArrivalNotifyStaffOptions() as $opt) {
- $email = trim((string)($opt['email'] ?? ''));
- $adminId = (int)($opt['admin_id'] ?? 0);
- $list[] = [
- 'name' => (string)($opt['name'] ?? ''),
- 'email' => $email,
- 'mobile' => (string)($opt['mobile'] ?? ''),
- 'role' => (string)($opt['role'] ?? ''),
- 'admin_id' => $adminId,
- 'can_select' => ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) ? 1 : 0,
- 'is_self' => ($selfAdminId > 0 && $adminId === $selfAdminId) ? 1 : 0,
- ];
- }
- $this->success('ok', '', [
- 'ccydh' => (string)($order['CCYDH'] ?? ''),
- 'cyjmc' => (string)($order['CYJMC'] ?? ''),
- 'cgymc' => (string)($order['CGYMC'] ?? ''),
- 'this_quantity' => (string)($order['order_qty'] ?? ''),
- 'supplier_name' => (string)($order['pick_company_name'] ?? ''),
- 'delivery_deadline' => (string)($order['delivery_deadline'] ?? ''),
- 'list' => $list,
- ]);
- }
- /**
- * 交货情况(已确认)— 邮箱通知所选质检/业务员:订单已到货
- * POST:ccydh、staff_json=["姓名",...]
- */
- public function deliverynotify()
- {
- $user = $this->mprocRequireDeliveryUser();
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $ccydh = trim((string)$this->request->post('ccydh', ''));
- $sid = (int)$this->request->post('scydgy_id', 0);
- $order = $this->mprocLoadDeliveryNotifyOrder($ccydh, $sid);
- if ($order === null) {
- $this->error('未找到可通知的订单');
- }
- $ccydh = trim((string)($order['CCYDH'] ?? $ccydh));
- $raw = $this->request->post('staff/a', []);
- if (!is_array($raw) || $raw === []) {
- // 关闭过滤器,避免 staff_json 中的引号被转义导致 json_decode 失败
- $staffJson = (string)$this->request->post('staff_json', '', null);
- if ($staffJson === '') {
- $staffJson = (string)($this->request->param('staff_json', '', null) ?: '');
- }
- if ($staffJson !== '') {
- $decoded = json_decode(html_entity_decode($staffJson, ENT_QUOTES, 'UTF-8'), true);
- if (!is_array($decoded)) {
- $decoded = json_decode($staffJson, true);
- }
- $raw = is_array($decoded) ? $decoded : [];
- }
- }
- $selectedNames = [];
- foreach ((array)$raw as $item) {
- $n = is_array($item) ? trim((string)($item['name'] ?? '')) : trim((string)$item);
- if ($n !== '') {
- $selectedNames[] = $n;
- }
- }
- $selectedNames = array_values(array_unique($selectedNames));
- if ($selectedNames === []) {
- $this->error('请选择要通知的人员');
- }
- $optionMap = [];
- foreach ($this->mprocLoadArrivalNotifyStaffOptions() as $opt) {
- $n = trim((string)($opt['name'] ?? ''));
- if ($n !== '') {
- $optionMap[$n] = $opt;
- }
- }
- $targets = [];
- foreach ($selectedNames as $n) {
- if (!isset($optionMap[$n])) {
- $this->error('人员不在可选名单中:' . $n);
- }
- $email = trim((string)($optionMap[$n]['email'] ?? ''));
- if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
- $this->error('未填写有效邮箱,无法通知:' . $n);
- }
- $targets[] = $optionMap[$n];
- }
- try {
- $mailConfig = \app\admin\model\Purchaseemail::getActiveMailerConfig();
- } catch (\Throwable $e) {
- $mailConfig = [];
- }
- if (!is_array($mailConfig) || empty($mailConfig['host'])) {
- $this->error('邮件 SMTP 未配置');
- }
- if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
- $this->error('发件邮箱未配置');
- }
- $this->mprocEnsureArrivalNotifyEmailTemplate();
- try {
- $platformUrl = $this->mprocBuildInboundscoreNotifyUrl($ccydh);
- } catch (\Throwable $e) {
- $this->error($e->getMessage());
- }
- $tpl = $this->mprocLoadNotifyTemplateRow('arrival_notify_email');
- if ($tpl === null || trim((string)($tpl['content'] ?? '')) === '') {
- $tpl = $this->mprocLoadNotifyTemplateRow('delivery_notify_email');
- }
- if ($tpl === null || trim((string)($tpl['content'] ?? '')) === '') {
- $this->error('邮件模版未配置,请在后台「短信模版配置」维护「订单已到货通知-邮箱」');
- }
- $subjectTpl = trim((string)($tpl['title'] ?? ''));
- if ($subjectTpl === '' || stripos($subjectTpl, '交货情况') !== false) {
- $subjectTpl = '订单已到货通知 - {ccydh}';
- }
- $contentTpl = (string)$tpl['content'];
- $ok = 0;
- $okNames = [];
- $failMsgs = [];
- $firstSid = (int)($order['scydgy_id'] ?? 0);
- $firstPoId = (int)($order['id'] ?? 0);
- $adminId = (int)($user['admin_id'] ?? 0);
- $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
- foreach ($targets as $contact) {
- $toName = trim((string)($contact['name'] ?? ''));
- $toEmail = trim((string)($contact['email'] ?? ''));
- $vars = [
- 'contact_name' => $toName,
- 'company_name' => $toName,
- 'email' => $toEmail,
- 'ccydh' => $ccydh,
- 'cyjmc' => (string)($order['CYJMC'] ?? ''),
- 'cgymc' => (string)($order['CGYMC'] ?? ''),
- 'this_quantity' => (string)($order['order_qty'] ?? ''),
- 'supplier_name' => (string)($order['pick_company_name'] ?? ''),
- 'delivery_deadline' => (string)($order['delivery_deadline'] ?? ''),
- 'delivery_status' => (string)($order['delivery_status'] ?? ''),
- 'delivery_date' => (string)($order['delivery_date'] ?? ''),
- 'storage_location' => (string)($order['storage_location'] ?? ''),
- 'remark' => (string)($order['delivery_remark'] ?? ''),
- 'platform_url' => $platformUrl,
- ];
- $mailPlain = $contentTpl;
- $mailSubject = $subjectTpl;
- foreach ($vars as $k => $v) {
- $mailPlain = str_replace('{' . $k . '}', (string)$v, $mailPlain);
- $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
- }
- $mailPlain = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailPlain);
- $mailSubject = trim((string)preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject));
- if ($mailSubject === '') {
- $mailSubject = '订单已到货通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
- }
- $mailBody = $this->mprocPlainTextToHtmlEmailBody($mailPlain);
- try {
- $this->mprocSendNotifyEmail($mailConfig, $toEmail, $toName, $mailSubject, $mailBody, $toEmail);
- $ok++;
- if ($toName !== '') {
- $okNames[] = $toName;
- }
- $this->mprocPersistEmailSendLog([
- 'from_email' => trim((string)($mailConfig['addr'] ?? '')),
- 'to_email' => $toEmail,
- 'scene' => '订单已到货通知',
- 'order_batch_no' => trim((string)($order['order_batch_no'] ?? $order['issue_batch_no'] ?? '')),
- 'ccydh' => $ccydh,
- 'company_name' => $toName,
- 'mail_subject' => $mailSubject,
- 'status' => 1,
- 'fail_reason' => '',
- 'scydgy_id' => $firstSid,
- 'purchase_order_id' => $firstPoId,
- 'admin_id' => $adminId,
- 'admin_name' => $adminName,
- ]);
- } catch (\Throwable $e) {
- $failMsgs[] = $toName . ':' . $e->getMessage();
- $this->mprocPersistEmailSendLog([
- 'from_email' => trim((string)($mailConfig['addr'] ?? '')),
- 'to_email' => $toEmail,
- 'scene' => '订单已到货通知',
- 'order_batch_no' => trim((string)($order['order_batch_no'] ?? $order['issue_batch_no'] ?? '')),
- 'ccydh' => $ccydh,
- 'company_name' => $toName,
- 'mail_subject' => $mailSubject,
- 'status' => 0,
- 'fail_reason' => $e->getMessage(),
- 'scydgy_id' => $firstSid,
- 'purchase_order_id' => $firstPoId,
- 'admin_id' => $adminId,
- 'admin_name' => $adminName,
- ]);
- }
- }
- if ($ok < 1) {
- $this->error('发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
- }
- $mergedStaff = $this->mprocPersistArrivalNotifyStaff($ccydh, $okNames);
- if ($firstSid > 0) {
- \app\common\library\ProcuremenOperLog::write(
- $firstSid,
- 'arrival_notify',
- '手机端交货情况通知已到货(质检/业务员):' . implode('、', $okNames),
- $firstPoId > 0 ? $firstPoId : null,
- [$adminId, $adminName]
- );
- }
- $msg = '已通知 ' . $ok . ' 人';
- if ($failMsgs !== []) {
- $msg .= ';部分失败:' . implode(';', $failMsgs);
- }
- $this->success($msg, '', [
- 'ok_count' => $ok,
- 'fail_count' => count($failMsgs),
- 'arrival_notify_staff' => $mergedStaff,
- ]);
- }
- /**
- * 已到货通知可选人员:质检中心 + 业务员
- *
- * @return array<int, array{admin_id:int,name:string,email:string,mobile:string,role:string}>
- */
- protected function mprocLoadArrivalNotifyStaffOptions(): array
- {
- $groups = [
- ['id' => $this->mprocResolveMobileQualityGroupId(), 'role' => '质检'],
- ['id' => $this->mprocResolveMobileRfqGroupId(), 'role' => '业务员'],
- ];
- $out = [];
- $seen = [];
- foreach ($groups as $g) {
- $groupId = (int)($g['id'] ?? 0);
- $role = (string)($g['role'] ?? '');
- if ($groupId <= 0) {
- continue;
- }
- try {
- $adminIds = Db::name('auth_group_access')->where('group_id', $groupId)->column('uid');
- } catch (\Throwable $e) {
- continue;
- }
- $adminIds = is_array($adminIds)
- ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
- : [];
- if ($adminIds === []) {
- continue;
- }
- try {
- $rows = Db::name('admin')
- ->where('status', 'normal')
- ->where('id', 'in', $adminIds)
- ->order('id', 'asc')
- ->field('id,nickname,username,email,mobile')
- ->select();
- } catch (\Throwable $e) {
- continue;
- }
- if (!is_array($rows)) {
- continue;
- }
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $name = trim((string)($row['nickname'] ?? ''));
- if ($name === '') {
- $name = trim((string)($row['username'] ?? ''));
- }
- if ($name === '' || isset($seen[$name])) {
- continue;
- }
- $seen[$name] = true;
- $out[] = [
- 'admin_id' => (int)($row['id'] ?? 0),
- 'name' => $name,
- 'email' => trim((string)($row['email'] ?? '')),
- 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
- 'role' => $role,
- ];
- }
- }
- return $out;
- }
- /**
- * @return array<int, array{admin_id:int,name:string,email:string,mobile:string}>
- */
- protected function mprocLoadDeliveryStaffOptions(): array
- {
- $out = [];
- $seen = [];
- $groupId = $this->mprocResolveMobileDeliveryGroupId();
- if ($groupId <= 0) {
- return [];
- }
- try {
- $adminIds = Db::name('auth_group_access')->where('group_id', $groupId)->column('uid');
- } catch (\Throwable $e) {
- return [];
- }
- $adminIds = is_array($adminIds)
- ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
- : [];
- if ($adminIds === []) {
- return [];
- }
- try {
- $rows = Db::name('admin')
- ->where('status', 'normal')
- ->where('id', 'in', $adminIds)
- ->order('id', 'asc')
- ->field('id,nickname,username,email,mobile')
- ->select();
- } catch (\Throwable $e) {
- return [];
- }
- if (!is_array($rows)) {
- return [];
- }
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $name = trim((string)($row['nickname'] ?? ''));
- if ($name === '') {
- $name = trim((string)($row['username'] ?? ''));
- }
- if ($name === '' || isset($seen[$name])) {
- continue;
- }
- $seen[$name] = true;
- $out[] = [
- 'admin_id' => (int)($row['id'] ?? 0),
- 'name' => $name,
- 'email' => trim((string)($row['email'] ?? '')),
- 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
- ];
- }
- return $out;
- }
- /**
- * 合并已通知人员姓名(去重,顿号分隔)
- *
- * @param string $old
- * @param string[] $names
- */
- protected function mprocMergeArrivalNotifyStaffNames(string $old, array $names): string
- {
- $map = [];
- foreach (preg_split('/[、,,;;]+/u', $old) ?: [] as $p) {
- $p = trim((string)$p);
- if ($p !== '') {
- $map[$p] = true;
- }
- }
- foreach ($names as $n) {
- $n = trim((string)$n);
- if ($n !== '') {
- $map[$n] = true;
- }
- }
- return implode('、', array_keys($map));
- }
- /**
- * 记录订单已到货通知人员(写入 inbound_score,按订单号合并)
- *
- * @param string[] $names
- */
- protected function mprocPersistArrivalNotifyStaff(string $ccydh, array $names): string
- {
- $ccydh = trim($ccydh);
- $names = array_values(array_filter(array_map(static function ($n) {
- return trim((string)$n);
- }, $names)));
- if ($ccydh === '' || $names === []) {
- return '';
- }
- $this->mprocEnsureInboundScoreTable();
- $now = date('Y-m-d H:i:s');
- $merged = implode('、', $names);
- try {
- $rows = Db::table('purchase_order_inbound_score')
- ->where('ccydh', $ccydh)
- ->field('id,arrival_notify_staff')
- ->select();
- } catch (\Throwable $e) {
- try {
- $rows = Db::table('purchase_order_inbound_score')
- ->where('CCYDH', $ccydh)
- ->field('id,arrival_notify_staff')
- ->select();
- } catch (\Throwable $e2) {
- $rows = [];
- }
- }
- if (!is_array($rows) || $rows === []) {
- // 按工序写入:订单下已确认交货的 scydgy
- try {
- $sids = Db::table('purchase_order')
- ->where('CCYDH', $ccydh)
- ->where('scydgy_id', '>', 0)
- ->column('scydgy_id');
- } catch (\Throwable $e) {
- $sids = [];
- }
- $sids = is_array($sids) ? array_values(array_unique(array_filter(array_map('intval', $sids)))) : [];
- if ($sids !== []) {
- try {
- $rows = Db::table('purchase_order_inbound_score')
- ->where('scydgy_id', 'in', $sids)
- ->field('id,arrival_notify_staff')
- ->select();
- } catch (\Throwable $e) {
- $rows = [];
- }
- }
- }
- if (!is_array($rows) || $rows === []) {
- return $merged;
- }
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $id = (int)($row['id'] ?? 0);
- if ($id <= 0) {
- continue;
- }
- $staff = $this->mprocMergeArrivalNotifyStaffNames((string)($row['arrival_notify_staff'] ?? ''), $names);
- $merged = $staff !== '' ? $staff : $merged;
- try {
- Db::table('purchase_order_inbound_score')->where('id', $id)->update([
- 'arrival_notify_staff' => $staff,
- 'arrival_notify_time' => $now,
- 'updatetime' => $now,
- ]);
- } catch (\Throwable $e) {
- try {
- Db::table('purchase_order_inbound_score')->where('id', $id)->update([
- 'arrival_notify_staff' => $staff,
- 'arrival_notify_time' => $now,
- ]);
- } catch (\Throwable $e2) {
- }
- }
- }
- return $merged;
- }
- /**
- * @return array<string, mixed>|null
- */
- protected function mprocLoadDeliveryNotifyOrder(string $ccydh, int $sid = 0): ?array
- {
- $ccydh = trim($ccydh);
- if ($ccydh === '' && $sid > 0) {
- try {
- $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
- $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
- } catch (\Throwable $e) {
- $ccydh = '';
- }
- }
- if ($ccydh === '') {
- return null;
- }
- $approvedVals = ProcuremenStatus::wflowApprovedValues();
- $approvedIn = implode(',', array_map(static function ($v) {
- return "'" . str_replace("'", "''", (string)$v) . "'";
- }, $approvedVals));
- try {
- $rows = Db::table('purchase_order')
- ->where('CCYDH', $ccydh)
- ->where('scydgy_id', '>', 0)
- ->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%\')')
- ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
- ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
- ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,This_quantity,NGZL,pick_company_name,delivery_deadline')
- ->order('id', 'asc')
- ->select();
- } catch (\Throwable $e) {
- $rows = [];
- }
- if (!is_array($rows) || $rows === []) {
- return null;
- }
- $gymc = [];
- $qty = [];
- $first = null;
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- if ($first === null) {
- $first = $r;
- }
- $g = trim((string)($r['CGYMC'] ?? ''));
- if ($g !== '' && !in_array($g, $gymc, true)) {
- $gymc[] = $g;
- }
- $q = $this->mprocResolveDisplayThisQuantity($r);
- if ($q !== '' && !in_array($q, $qty, true)) {
- $qty[] = $q;
- }
- }
- if (!is_array($first)) {
- return null;
- }
- $dl = trim((string)($first['delivery_deadline'] ?? ''));
- if ($dl !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', str_replace(['/', '.'], '-', $dl), $m)) {
- $dl = $m[1];
- } elseif ($dl !== '' && preg_match('/^0000-00-00/', $dl)) {
- $dl = '';
- }
- $first['CGYMC'] = $gymc !== [] ? implode('、', $gymc) : '';
- $first['order_qty'] = $qty !== [] ? implode('、', $qty) : '';
- $first['delivery_deadline'] = $dl;
- $first['delivery_date'] = '';
- $first['storage_location'] = '';
- $first['delivery_status'] = '';
- $first['delivery_remark'] = '';
- $sids = [];
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sidOne = (int)($r['scydgy_id'] ?? 0);
- if ($sidOne > 0) {
- $sids[$sidOne] = true;
- }
- }
- if ($sids !== []) {
- try {
- $scores = Db::table('purchase_order_inbound_score')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->field('scydgy_id,delivery_status,delivery_date,storage_location,remark')
- ->select();
- } catch (\Throwable $e) {
- try {
- $scores = Db::table('purchase_order_inbound_score')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->field('scydgy_id,delivery_date,storage_location')
- ->select();
- } catch (\Throwable $e2) {
- $scores = [];
- }
- }
- if (is_array($scores)) {
- foreach ($scores as $sc) {
- if (!is_array($sc)) {
- continue;
- }
- $ds = trim((string)($sc['delivery_status'] ?? ''));
- if ($ds !== '' && $first['delivery_status'] === '') {
- $first['delivery_status'] = $ds;
- }
- $dd = trim((string)($sc['delivery_date'] ?? ''));
- if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', str_replace(['/', '.'], '-', $dd), $mdd)
- && $first['delivery_date'] === '') {
- $first['delivery_date'] = $mdd[1];
- }
- $loc = trim((string)($sc['storage_location'] ?? ''));
- if ($loc !== '' && $first['storage_location'] === '') {
- $first['storage_location'] = $loc;
- }
- $rm = trim((string)($sc['remark'] ?? ''));
- if ($rm !== '' && $first['delivery_remark'] === '') {
- $first['delivery_remark'] = $rm;
- }
- }
- }
- }
- return $first;
- }
- protected function mprocBuildInboundscoreNotifyUrl(string $ccydh): string
- {
- $base = rtrim(trim((string)Config::get('mproc.mobile_base_url')), '/');
- if ($base === '' || !preg_match('#^https?://#i', $base)) {
- $base = rtrim((string)$this->request->root(true), '/');
- }
- if ($base === '') {
- throw new \RuntimeException('无法生成通知链接');
- }
- $ccydh = trim($ccydh);
- return $base . '/index.php/index/index/inboundscore' . ($ccydh !== '' ? ('?ccydh=' . rawurlencode($ccydh)) : '');
- }
- /** @deprecated 兼容旧调用,已改跳转质量评分 */
- protected function mprocBuildDeliveryscoreNotifyUrl(string $ccydh): string
- {
- return $this->mprocBuildInboundscoreNotifyUrl($ccydh);
- }
- /**
- * @return array{title:string,content:string}|null
- */
- protected function mprocLoadNotifyTemplateRow(string $scene): ?array
- {
- try {
- $row = Db::table('purchase_sms_template')
- ->where('scene', $scene)
- ->where(function ($q) {
- $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
- })
- ->order('id', 'asc')
- ->find();
- } catch (\Throwable $e) {
- return null;
- }
- if (!is_array($row) || $row === []) {
- return null;
- }
- return [
- 'title' => trim((string)($row['title'] ?? '')),
- 'content' => trim((string)($row['content'] ?? '')),
- ];
- }
- protected function mprocEnsureArrivalNotifyEmailTemplate(): void
- {
- static $done = false;
- if ($done) {
- return;
- }
- $done = true;
- $content = "您好,{contact_name}:\n\n"
- . "订单已到货,请知悉。\n\n"
- . "订单信息\n"
- . "\t订单号:{ccydh}\n"
- . "\t印件名称:{cyjmc}\n"
- . "\t工序名称:{cgymc}\n"
- . "\t订单数量:{this_quantity}\n"
- . "\t供应商:{supplier_name}\n"
- . "\t交货截止日期:{delivery_deadline}\n\n"
- . "交货信息\n"
- . "\t交货情况:{delivery_status}\n"
- . "\t交货日期:{delivery_date}\n"
- . "\t库位:{storage_location}\n"
- . "\t备注:{remark}\n";
- $title = '订单已到货通知 - {ccydh}';
- $remark = '手机端交货情况-通知质检/业务员已到货;模版名称作邮件主题';
- try {
- $row = Db::table('purchase_sms_template')->where('scene', 'arrival_notify_email')->find();
- } catch (\Throwable $e) {
- return;
- }
- $now = date('Y-m-d H:i:s');
- try {
- $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
- } catch (\Throwable $e) {
- $cols = [];
- }
- $colNames = [];
- foreach ($cols as $c) {
- if (!is_array($c)) {
- continue;
- }
- $n = (string)($c['Field'] ?? $c['field'] ?? '');
- if ($n !== '') {
- $colNames[$n] = true;
- }
- }
- try {
- if (is_array($row) && $row !== []) {
- $upd = [
- 'title' => $title,
- 'content' => $content,
- 'remark' => $remark,
- 'status' => 1,
- ];
- if (isset($colNames['updatetime'])) {
- $upd['updatetime'] = $now;
- }
- Db::table('purchase_sms_template')
- ->where('id', (int)($row['id'] ?? 0))
- ->update($upd);
- return;
- }
- $data = [
- 'scene' => 'arrival_notify_email',
- 'title' => $title,
- 'content' => $content,
- 'remark' => $remark,
- 'status' => 1,
- ];
- if (isset($colNames['updatetime'])) {
- $data['updatetime'] = $now;
- }
- if (isset($colNames['createtime'])) {
- $data['createtime'] = $now;
- }
- Db::table('purchase_sms_template')->insert($data);
- } catch (\Throwable $e) {
- }
- }
- /** @deprecated 兼容旧调用 */
- protected function mprocEnsureDeliveryNotifyEmailTemplate(): void
- {
- $this->mprocEnsureArrivalNotifyEmailTemplate();
- }
- protected function mprocPlainTextToHtmlEmailBody(string $plain): string
- {
- $esc = htmlspecialchars($plain, ENT_QUOTES, 'UTF-8');
- $esc = preg_replace(
- '#(https?://[^\s<]+)#u',
- '<a href="$1" style="color:#3c8dbc;word-break:break-all;">$1</a>',
- $esc
- );
- $esc = nl2br($esc);
- return '<div style="font-size:14px;line-height:1.7;color:#333;font-family:sans-serif;">' . $esc . '</div>';
- }
- /**
- * @param array<string, mixed> $mailConfig
- */
- protected function mprocSendNotifyEmail(array $mailConfig, string $toEmail, string $toName, string $subject, string $htmlBody, string $excludeCc = ''): void
- {
- $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
- $mail->isSMTP();
- $mail->Host = (string)($mailConfig['host'] ?? '');
- $mail->SMTPAuth = true;
- $mail->Username = (string)($mailConfig['addr'] ?? '');
- $mail->Password = (string)($mailConfig['pass'] ?? '');
- $mail->SMTPSecure = (string)($mailConfig['security'] ?? 'ssl');
- $mail->Port = (int)($mailConfig['port'] ?? 465);
- $mail->CharSet = (string)($mailConfig['charset'] ?? 'utf-8');
- $mail->setFrom((string)($mailConfig['addr'] ?? ''), (string)($mailConfig['name'] ?? '协助采购'));
- $mail->addAddress($toEmail, $toName);
- $ccRaw = trim((string)Config::get('mproc.cc_email'));
- if ($ccRaw !== '') {
- $exclude = strtolower(trim($excludeCc));
- foreach (preg_split('/[,;,;\s]+/', $ccRaw) ?: [] as $piece) {
- $cc = strtolower(trim((string)$piece));
- if ($cc === '' || !filter_var($cc, FILTER_VALIDATE_EMAIL)) {
- continue;
- }
- if ($exclude !== '' && $cc === $exclude) {
- continue;
- }
- $mail->addCC($cc);
- }
- }
- $mail->isHTML(true);
- $mail->Subject = $subject;
- $mail->Body = $htmlBody;
- $mail->send();
- }
- /**
- * @param array<string, mixed> $row
- */
- protected function mprocPersistEmailSendLog(array $row): void
- {
- try {
- $data = [
- 'from_email' => (string)($row['from_email'] ?? ''),
- 'to_email' => (string)($row['to_email'] ?? ''),
- 'send_time' => date('Y-m-d H:i:s'),
- 'scene' => (string)($row['scene'] ?? ''),
- 'order_batch_no' => (string)($row['order_batch_no'] ?? ''),
- 'ccydh' => (string)($row['ccydh'] ?? ''),
- 'company_name' => (string)($row['company_name'] ?? ''),
- 'mail_subject' => (string)($row['mail_subject'] ?? ''),
- 'status' => (int)($row['status'] ?? 0),
- 'fail_reason' => (string)($row['fail_reason'] ?? ''),
- 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
- 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
- 'admin_id' => (int)($row['admin_id'] ?? 0),
- 'admin_name' => (string)($row['admin_name'] ?? ''),
- ];
- try {
- Db::table('purchase_email_send_log')->insert($data);
- } catch (\Throwable $e) {
- if (stripos($e->getMessage(), 'order_batch_no') === false) {
- throw $e;
- }
- unset($data['order_batch_no']);
- Db::table('purchase_email_send_log')->insert($data);
- }
- } catch (\Throwable $e) {
- Log::record('mprocPersistEmailSendLog: ' . $e->getMessage(), 'error');
- }
- }
- /**
- * 质量+交货均完成后,按最新详情重存存证 PDF
- *
- * @param array<int, mixed> $poRows
- */
- protected function mprocRefreshCompletedArchivePdfs(array $poRows): void
- {
- $done = [];
- foreach ($poRows as $po) {
- if (!is_array($po)) {
- continue;
- }
- $sid = (int)($po['scydgy_id'] ?? 0);
- if ($sid <= 0 || isset($done[$sid])) {
- continue;
- }
- $done[$sid] = true;
- try {
- \app\admin\controller\Procuremen::regenerateArchivePdfWithoutAuth($sid, true);
- } catch (\Throwable $e) {
- Log::record('完结存证PDF刷新失败 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
- }
- }
- }
- /**
- * @return array<int, array<string, mixed>>
- */
- /**
- * 交货/质量评分作用域键:订单号 + 批次号 + 中标供应商
- * (同订单号下不同批次/供应商必须分开,避免串单)
- */
- protected function mprocBuildScoreGroupKey(string $ccydh, string $batchNo, string $companyName): string
- {
- $ccydh = trim($ccydh);
- $batchNo = trim($batchNo);
- $companyName = trim($companyName);
- return $ccydh . "\x1e" . ($batchNo !== '' ? $batchNo : '_') . "\x1e" . ($companyName !== '' ? $companyName : '_');
- }
- /**
- * @param array<string, mixed> $po
- */
- protected function mprocResolvePoBatchNo(array $po): string
- {
- foreach (['order_batch_no', 'issue_batch_no'] as $k) {
- $v = trim((string)($po[$k] ?? ''));
- if ($v !== '') {
- return $v;
- }
- }
- return '';
- }
- /**
- * 已审核可评分主单:仅限同一订单号 + 同一批次 + 同一中标供应商
- *
- * @return array<int, array<string, mixed>>
- */
- protected function mprocLoadApprovedPoRowsForScore(string $ccydh, int $sid, string $batchNo = '', string $companyName = ''): array
- {
- $approvedVals = ProcuremenStatus::wflowApprovedValues();
- $approvedIn = implode(',', array_map(static function ($v) {
- return "'" . str_replace("'", "''", (string)$v) . "'";
- }, $approvedVals));
- try {
- $q = Db::table('purchase_order')
- ->where('scydgy_id', '>', 0)
- ->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%\')')
- ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
- ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
- ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
- ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,delivery_deadline,pick_company_name,pick_time,wflow_status,status,order_batch_no');
- if ($ccydh !== '') {
- $q->where('CCYDH', $ccydh);
- } elseif ($sid > 0) {
- $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH,order_batch_no,pick_company_name')->find();
- $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
- if ($ccydh === '') {
- $this->error('缺少订单号');
- }
- if ($batchNo === '' && is_array($one)) {
- $batchNo = $this->mprocResolvePoBatchNo($one);
- }
- if ($companyName === '' && is_array($one)) {
- $companyName = trim((string)($one['pick_company_name'] ?? ''));
- }
- $q->where('CCYDH', $ccydh);
- } else {
- $this->error('缺少订单号');
- }
- $poRows = $q->order('id', 'asc')->select();
- } catch (\Throwable $e) {
- // 兼容缺 order_batch_no 列
- try {
- $q = Db::table('purchase_order')
- ->where('scydgy_id', '>', 0)
- ->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%\')')
- ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
- ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
- ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
- ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,delivery_deadline,pick_company_name,pick_time,wflow_status,status');
- if ($ccydh !== '') {
- $q->where('CCYDH', $ccydh);
- } elseif ($sid > 0) {
- $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH,pick_company_name')->find();
- $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
- if ($ccydh === '') {
- $this->error('缺少订单号');
- }
- if ($companyName === '' && is_array($one)) {
- $companyName = trim((string)($one['pick_company_name'] ?? ''));
- }
- $q->where('CCYDH', $ccydh);
- } else {
- $this->error('缺少订单号');
- }
- $poRows = $q->order('id', 'asc')->select();
- } catch (\Throwable $e2) {
- $poRows = [];
- }
- }
- if (!is_array($poRows) || $poRows === []) {
- $this->error('未找到可评分的已审核订单');
- }
- // 用锚点工序补齐批次/供应商作用域
- if ($sid > 0 && ($batchNo === '' || $companyName === '')) {
- foreach ($poRows as $po) {
- if (!is_array($po) || (int)($po['scydgy_id'] ?? 0) !== $sid) {
- continue;
- }
- if ($batchNo === '') {
- $batchNo = $this->mprocResolvePoBatchNo($po);
- }
- if ($companyName === '') {
- $companyName = trim((string)($po['pick_company_name'] ?? ''));
- }
- break;
- }
- }
- $scopeKey = '';
- if ($batchNo !== '' || $companyName !== '' || $sid > 0) {
- // 若仍缺公司名,用 sid 所在行;再不行用首行(兼容仅一单)
- if ($companyName === '' && $sid <= 0 && count($poRows) === 1 && is_array($poRows[0])) {
- $companyName = trim((string)($poRows[0]['pick_company_name'] ?? ''));
- $batchNo = $batchNo !== '' ? $batchNo : $this->mprocResolvePoBatchNo($poRows[0]);
- }
- $scopeKey = $this->mprocBuildScoreGroupKey($ccydh, $batchNo, $companyName);
- }
- $filtered = [];
- $groupKeys = [];
- foreach ($poRows as $po) {
- if (!is_array($po)) {
- continue;
- }
- $rowBatch = $this->mprocResolvePoBatchNo($po);
- $rowCompany = trim((string)($po['pick_company_name'] ?? ''));
- $rowCcydh = trim((string)($po['CCYDH'] ?? $ccydh));
- $gk = $this->mprocBuildScoreGroupKey($rowCcydh, $rowBatch, $rowCompany);
- $groupKeys[$gk] = true;
- if ($scopeKey !== '' && $gk !== $scopeKey) {
- continue;
- }
- $filtered[] = $po;
- }
- if ($scopeKey === '' && count($groupKeys) > 1) {
- $this->error('该订单存在多个批次或中标供应商,请刷新页面后按卡片分别填写');
- }
- if ($filtered === []) {
- $this->error('未找到可评分的已审核订单(批次/供应商不匹配)');
- }
- return $filtered;
- }
- /**
- * 操作人展示名:优先后台管理员昵称(名称),避免记成登录账号
- *
- * @param array<string, mixed> $user
- */
- protected function mprocResolveAdminDisplayName(array $user, int $adminId): string
- {
- $adminName = '';
- if ($adminId > 0) {
- try {
- $adminRow = Db::name('admin')->where('id', $adminId)->field('nickname,username')->find();
- if (is_array($adminRow)) {
- $nick = trim((string)($adminRow['nickname'] ?? ''));
- $uname = trim((string)($adminRow['username'] ?? ''));
- if ($nick !== '') {
- $adminName = $nick;
- } elseif ($uname !== '') {
- $adminName = $uname;
- }
- }
- } catch (\Throwable $e) {
- }
- }
- if ($adminName === '') {
- $adminName = trim((string)($user['nickname'] ?? ''));
- }
- if ($adminName === '') {
- $adminName = trim((string)($user['username'] ?? ''));
- }
- return $adminName !== '' ? $adminName : '管理员';
- }
- /**
- * @param array<int, mixed> $poRows
- */
- protected function mprocSyncMonthlyAfterInboundScore(array $poRows, string $now): void
- {
- $companyName = '';
- foreach ($poRows as $po) {
- if (!is_array($po)) {
- continue;
- }
- $companyName = trim((string)($po['pick_company_name'] ?? ''));
- if ($companyName !== '') {
- break;
- }
- }
- $scoreYm = date('Y-m', strtotime($now) ?: time());
- if ($companyName === '') {
- return;
- }
- try {
- \app\common\library\ProcuremenSupplierScore::syncQualityScoreFromInbound($scoreYm, $companyName);
- } catch (\Throwable $e) {
- Log::record('inboundscoresave quality sync: ' . $e->getMessage(), 'error');
- }
- }
- /**
- * @return array<string, mixed>
- */
- protected function mprocRequireAdminUser(): array
- {
- $user = $this->mprocGetUser();
- if (!$user) {
- $this->error('请先登录', url('index/index/login'));
- }
- if (empty($user['is_admin'])) {
- $this->error('仅系统管理员可操作');
- }
- return $user;
- }
- /** 质检中心角色组 id */
- protected function mprocResolveMobileQualityGroupId(): int
- {
- $id = (int)Config::get('mproc.mobile_quality_group_id');
- if ($id > 0) {
- return $id;
- }
- try {
- $found = Db::name('auth_group')
- ->where('name', '质检中心')
- ->where('status', 'normal')
- ->order('id', 'asc')
- ->value('id');
- $id = (int)$found;
- } catch (\Throwable $e) {
- $id = 0;
- }
- return $id > 0 ? $id : 16;
- }
- /** 生产部/生产员角色组 id */
- protected function mprocResolveMobileDeliveryGroupId(): int
- {
- $id = (int)Config::get('mproc.mobile_delivery_group_id');
- if ($id > 0) {
- return $id;
- }
- try {
- $found = Db::name('auth_group')
- ->where('name', 'in', ['生产部', '生产员'])
- ->where('status', 'normal')
- ->order('id', 'asc')
- ->value('id');
- $id = (int)$found;
- } catch (\Throwable $e) {
- $id = 0;
- }
- return $id > 0 ? $id : 15;
- }
- /** 业务员(手机端新增询价)角色组 id */
- protected function mprocResolveMobileRfqGroupId(): int
- {
- $id = (int)Config::get('mproc.mobile_rfq_group_id');
- if ($id <= 0) {
- $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
- }
- if ($id > 0) {
- return $id;
- }
- try {
- $found = Db::name('auth_group')
- ->where('name', '业务员')
- ->where('status', 'normal')
- ->order('id', 'asc')
- ->value('id');
- $id = (int)$found;
- } catch (\Throwable $e) {
- $id = 0;
- }
- return $id > 0 ? $id : 12;
- }
- /**
- * @return int[]
- */
- protected function mprocAdminGroupIds(int $adminId): array
- {
- if ($adminId <= 0) {
- return [];
- }
- try {
- $ids = Db::name('auth_group_access')->where('uid', $adminId)->column('group_id');
- } catch (\Throwable $e) {
- return [];
- }
- if (!is_array($ids)) {
- return [];
- }
- return array_values(array_unique(array_filter(array_map('intval', $ids))));
- }
- /** 超管(角色组 rules=*)或协同「管理员」组 */
- protected function mprocAdminIsMobileSuper(int $adminId): bool
- {
- if ($adminId <= 0) {
- return false;
- }
- try {
- $rows = Db::name('auth_group_access')
- ->alias('aga')
- ->join('auth_group ag', 'aga.group_id = ag.id')
- ->where('aga.uid', $adminId)
- ->field('ag.id,ag.rules')
- ->select();
- } catch (\Throwable $e) {
- return false;
- }
- if (!is_array($rows)) {
- return false;
- }
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- if (trim((string)($r['rules'] ?? '')) === '*') {
- return true;
- }
- // 供应链协同「管理员」组
- if ((int)($r['id'] ?? 0) === 11) {
- return true;
- }
- }
- return false;
- }
- /**
- * @param array<string, mixed> $user
- * @param string $role quality|delivery|rfq
- */
- protected function mprocAdminHasMobileRole(array $user, string $role): bool
- {
- if (empty($user['is_admin'])) {
- return false;
- }
- $adminId = (int)($user['admin_id'] ?? 0);
- if ($adminId <= 0) {
- return false;
- }
- if ($this->mprocAdminIsMobileSuper($adminId)) {
- return true;
- }
- $gids = $this->mprocAdminGroupIds($adminId);
- if ($role === 'quality') {
- $need = $this->mprocResolveMobileQualityGroupId();
- return $need > 0 && in_array($need, $gids, true);
- }
- if ($role === 'delivery') {
- $need = $this->mprocResolveMobileDeliveryGroupId();
- return $need > 0 && in_array($need, $gids, true);
- }
- if ($role === 'rfq') {
- $need = $this->mprocResolveMobileRfqGroupId();
- return $need > 0 && in_array($need, $gids, true);
- }
- return false;
- }
- /**
- * @return array<string, mixed>
- */
- protected function mprocRequireRfqUser(): array
- {
- $user = $this->mprocRequireAdminUser();
- if (!$this->mprocAdminHasMobileRole($user, 'rfq')) {
- $this->error('仅业务员账号可新增订单询价');
- }
- return $user;
- }
- /**
- * @return array<string, mixed>
- */
- protected function mprocRequireQualityUser(): array
- {
- $user = $this->mprocRequireAdminUser();
- if (!$this->mprocAdminHasMobileRole($user, 'quality')) {
- $this->error('仅质检中心账号可操作质量评分');
- }
- return $user;
- }
- /**
- * @return array<string, mixed>
- */
- protected function mprocRequireDeliveryUser(): array
- {
- $user = $this->mprocRequireAdminUser();
- if (!$this->mprocAdminHasMobileRole($user, 'delivery')) {
- $this->error('仅生产部账号可操作交货情况');
- }
- return $user;
- }
- protected function mprocEnsureInboundScoreTable(): void
- {
- static $ok = false;
- if ($ok) {
- return;
- }
- try {
- Db::query('SELECT 1 FROM `purchase_order_inbound_score` LIMIT 1');
- } catch (\Throwable $e) {
- try {
- Db::execute("CREATE TABLE IF NOT EXISTS `purchase_order_inbound_score` (
- `id` int unsigned NOT NULL AUTO_INCREMENT,
- `scydgy_id` int NOT NULL DEFAULT 0 COMMENT '工序ID',
- `purchase_order_id` int unsigned NOT NULL DEFAULT 0 COMMENT 'purchase_order.id',
- `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
- `cyjmc` varchar(255) NOT NULL DEFAULT '' COMMENT '印件名称',
- `cgymc` varchar(255) NOT NULL DEFAULT '' COMMENT '工序名称',
- `company_name` varchar(255) NOT NULL DEFAULT '' COMMENT '中标供应商',
- `result` varchar(16) NOT NULL DEFAULT '' COMMENT '合格/不合格',
- `delivery_status` varchar(16) NOT NULL DEFAULT '' COMMENT '交货情况 准时/滞后',
- `delivery_date` date DEFAULT NULL COMMENT '交货日期',
- `storage_location` varchar(64) NOT NULL DEFAULT '' COMMENT '库位',
- `customer_complaint` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '客户是否投诉 1=是',
- `complaint_remark` varchar(500) NOT NULL DEFAULT '' COMMENT '投诉说明',
- `order_interrupt` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '订单是否中断 1=是',
- `admin_id` int unsigned NOT NULL DEFAULT 0,
- `admin_name` varchar(64) NOT NULL DEFAULT '',
- `delivery_admin_id` int unsigned NOT NULL DEFAULT 0 COMMENT '交货确认人ID',
- `delivery_admin_name` varchar(64) NOT NULL DEFAULT '' COMMENT '交货确认人',
- `remark` varchar(500) NOT NULL DEFAULT '',
- `createtime` datetime DEFAULT NULL,
- `updatetime` datetime DEFAULT NULL,
- PRIMARY KEY (`id`),
- UNIQUE KEY `uk_scydgy_id` (`scydgy_id`),
- KEY `idx_ccydh` (`ccydh`),
- KEY `idx_result` (`result`),
- KEY `idx_updatetime` (`updatetime`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='质量评分'");
- } catch (\Throwable $e2) {
- Log::record('mprocEnsureInboundScoreTable: ' . $e2->getMessage(), 'error');
- return;
- }
- }
- foreach ([
- 'delivery_status' => "ADD COLUMN `delivery_status` varchar(16) NOT NULL DEFAULT '' COMMENT '交货情况 准时/滞后' AFTER `result`",
- 'delivery_date' => "ADD COLUMN `delivery_date` date DEFAULT NULL COMMENT '交货日期' AFTER `delivery_status`",
- 'storage_location' => "ADD COLUMN `storage_location` varchar(64) NOT NULL DEFAULT '' COMMENT '库位' AFTER `delivery_date`",
- 'customer_complaint' => "ADD COLUMN `customer_complaint` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '客户是否投诉 1=是' AFTER `storage_location`",
- 'complaint_remark' => "ADD COLUMN `complaint_remark` varchar(500) NOT NULL DEFAULT '' COMMENT '投诉说明' AFTER `customer_complaint`",
- 'order_interrupt' => "ADD COLUMN `order_interrupt` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '订单是否中断 1=是' AFTER `complaint_remark`",
- 'delivery_admin_id' => "ADD COLUMN `delivery_admin_id` int unsigned NOT NULL DEFAULT 0 COMMENT '交货确认人ID' AFTER `admin_name`",
- 'delivery_admin_name'=> "ADD COLUMN `delivery_admin_name` varchar(64) NOT NULL DEFAULT '' COMMENT '交货确认人' AFTER `delivery_admin_id`",
- 'arrival_notify_staff' => "ADD COLUMN `arrival_notify_staff` varchar(500) NOT NULL DEFAULT '' COMMENT '已到货已通知人员' AFTER `delivery_admin_name`",
- 'arrival_notify_time' => "ADD COLUMN `arrival_notify_time` datetime DEFAULT NULL COMMENT '已到货通知时间' AFTER `arrival_notify_staff`",
- ] as $col => $ddl) {
- try {
- $cols = Db::query("SHOW COLUMNS FROM `purchase_order_inbound_score` LIKE '{$col}'");
- if (!is_array($cols) || $cols === []) {
- Db::execute("ALTER TABLE `purchase_order_inbound_score` {$ddl}");
- }
- } catch (\Throwable $e) {
- Log::record("mprocEnsureInboundScoreTable {$col}: " . $e->getMessage(), 'error');
- }
- }
- $ok = true;
- }
- /**
- * 质量评分列表:按订单号合并(一单一行,工序顿号合并)
- * tab=pending 待评分;scored 已评分(仅当前管理员操作过的)
- *
- * @return array<int, array<string, mixed>>
- */
- protected function mprocLoadInboundScoreRows(string $tab, string $keyword = '', int $adminId = 0, string $scope = 'quality'): array
- {
- $this->mprocEnsureInboundScoreTable();
- $keyword = trim($keyword);
- $scope = $scope === 'delivery' ? 'delivery' : 'quality';
- if (!in_array($tab, ['pending', 'scored', 'pass', 'fail'], true)) {
- $tab = 'pending';
- }
- if ($tab === 'pass' || $tab === 'fail') {
- $tab = 'scored';
- }
- try {
- $approvedVals = ProcuremenStatus::wflowApprovedValues();
- $approvedIn = implode(',', array_map(static function ($v) {
- return "'" . str_replace("'", "''", (string)$v) . "'";
- }, $approvedVals));
- $poRows = Db::table('purchase_order')
- ->where('scydgy_id', '>', 0)
- ->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%\')')
- ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
- ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
- ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
- ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CCLBMMC,CDW,This_quantity,NGZL,delivery_deadline,pick_company_name,pick_time,wflow_status,status,order_batch_no')
- ->order('pick_time', 'desc')
- ->order('id', 'asc')
- ->limit(800)
- ->select();
- } catch (\Throwable $e) {
- try {
- $poRows = Db::table('purchase_order')
- ->where('scydgy_id', '>', 0)
- ->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%\')')
- ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
- ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
- ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
- ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CCLBMMC,CDW,This_quantity,NGZL,delivery_deadline,pick_company_name,pick_time,wflow_status,status')
- ->order('pick_time', 'desc')
- ->order('id', 'asc')
- ->limit(800)
- ->select();
- } catch (\Throwable $e2) {
- Log::record('mprocLoadInboundScoreRows: ' . $e2->getMessage(), 'error');
- return [];
- }
- }
- if (!is_array($poRows) || $poRows === []) {
- return [];
- }
- $sids = [];
- foreach ($poRows as $po) {
- if (!is_array($po)) {
- continue;
- }
- $sid = (int)($po['scydgy_id'] ?? 0);
- if ($sid > 0) {
- $sids[$sid] = true;
- }
- }
- $scoreMap = [];
- if ($sids !== []) {
- try {
- $scores = Db::table('purchase_order_inbound_score')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->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')
- ->select();
- } catch (\Throwable $e) {
- try {
- $scores = Db::table('purchase_order_inbound_score')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->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')
- ->select();
- } catch (\Throwable $e2) {
- try {
- $scores = Db::table('purchase_order_inbound_score')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->field('scydgy_id,result,delivery_status,delivery_date,customer_complaint,complaint_remark,order_interrupt,remark,admin_id,admin_name,updatetime,createtime')
- ->select();
- } catch (\Throwable $e3) {
- try {
- $scores = Db::table('purchase_order_inbound_score')
- ->where('scydgy_id', 'in', array_keys($sids))
- ->field('scydgy_id,result,delivery_status,customer_complaint,order_interrupt,remark,admin_id,admin_name,updatetime,createtime')
- ->select();
- } catch (\Throwable $e4) {
- $scores = [];
- }
- }
- }
- }
- if (is_array($scores)) {
- foreach ($scores as $sc) {
- if (!is_array($sc)) {
- continue;
- }
- $sid = (int)($sc['scydgy_id'] ?? 0);
- if ($sid > 0) {
- $scoreMap[$sid] = $sc;
- }
- }
- }
- }
- /** @var array<string, array<string, mixed>> $groups */
- $groups = [];
- foreach ($poRows as $po) {
- if (!is_array($po)) {
- continue;
- }
- $sid = (int)($po['scydgy_id'] ?? 0);
- $ccydh = trim((string)($po['CCYDH'] ?? ''));
- if ($sid <= 0 || $ccydh === '') {
- continue;
- }
- $batchNo = $this->mprocResolvePoBatchNo($po);
- $company = trim((string)($po['pick_company_name'] ?? ''));
- $groupKey = $this->mprocBuildScoreGroupKey($ccydh, $batchNo, $company);
- if (!isset($groups[$groupKey])) {
- $pickRaw = trim((string)($po['pick_time'] ?? ''));
- $pickDisp = $pickRaw !== '' ? \app\common\library\ProcuremenTime::formatDisplayDateTime($pickRaw) : '';
- $groups[$groupKey] = [
- 'CCYDH' => $ccydh,
- 'order_batch_no' => $batchNo,
- 'scydgy_id' => $sid,
- 'scydgy_ids' => [],
- 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
- 'CCLBMMC' => trim((string)($po['CCLBMMC'] ?? '')),
- 'CGYMC_list' => [],
- 'qty_list' => [],
- 'pick_company_name' => $company,
- 'pick_time' => $pickDisp !== '' ? $pickDisp : $pickRaw,
- 'pick_time_raw' => $pickRaw,
- 'process_count' => 0,
- 'results' => [],
- 'score_admin_ids' => [],
- 'score_time_raw' => '',
- 'score_operator' => '',
- 'quality_operator' => '',
- 'customer_complaint'=> 0,
- 'complaint_remark' => '',
- 'order_interrupt' => 0,
- 'delivery_status' => '',
- 'delivery_date' => '',
- 'delivery_deadline' => '',
- 'storage_location' => '',
- 'remark' => '',
- 'arrival_notify_staff' => '',
- 'arrival_notify_time' => '',
- ];
- }
- $g = &$groups[$groupKey];
- $g['scydgy_ids'][] = $sid;
- $g['process_count']++;
- if ($g['scydgy_id'] <= 0) {
- $g['scydgy_id'] = $sid;
- }
- if ($g['CYJMC'] === '') {
- $g['CYJMC'] = trim((string)($po['CYJMC'] ?? ''));
- }
- if ($g['CCLBMMC'] === '') {
- $g['CCLBMMC'] = trim((string)($po['CCLBMMC'] ?? ''));
- }
- if ($g['pick_company_name'] === '') {
- $g['pick_company_name'] = $company;
- }
- if ($g['order_batch_no'] === '' && $batchNo !== '') {
- $g['order_batch_no'] = $batchNo;
- }
- if ($g['delivery_deadline'] === '') {
- $g['delivery_deadline'] = $this->mprocFormatYmdValue($po['delivery_deadline'] ?? $po['Delivery_deadline'] ?? '');
- }
- $pt = trim((string)($po['pick_time'] ?? ''));
- if ($pt !== '' && ($g['pick_time_raw'] === '' || strcmp($pt, $g['pick_time_raw']) > 0)) {
- $g['pick_time_raw'] = $pt;
- $disp = \app\common\library\ProcuremenTime::formatDisplayDateTime($pt);
- $g['pick_time'] = $disp !== '' ? $disp : $pt;
- }
- $gymc = trim((string)($po['CGYMC'] ?? ''));
- if ($gymc !== '' && !in_array($gymc, $g['CGYMC_list'], true)) {
- $g['CGYMC_list'][] = $gymc;
- }
- $qDisp = $this->mprocResolveDisplayThisQuantity($po);
- if ($qDisp !== '' && !in_array($qDisp, $g['qty_list'], true)) {
- $g['qty_list'][] = $qDisp;
- }
- $sc = $scoreMap[$sid] ?? null;
- $res = is_array($sc) ? trim((string)($sc['result'] ?? '')) : '';
- $g['results'][] = $res;
- if (is_array($sc)) {
- $ns = trim((string)($sc['arrival_notify_staff'] ?? ''));
- if ($ns !== '') {
- $g['arrival_notify_staff'] = $this->mprocMergeArrivalNotifyStaffNames(
- (string)($g['arrival_notify_staff'] ?? ''),
- preg_split('/[、,,;;]+/u', $ns) ?: []
- );
- }
- $nt = trim((string)($sc['arrival_notify_time'] ?? ''));
- if ($nt !== '' && ((string)($g['arrival_notify_time'] ?? '') === '' || strcmp($nt, (string)$g['arrival_notify_time']) > 0)) {
- $g['arrival_notify_time'] = $nt;
- }
- }
- if (is_array($sc) && $res !== '') {
- $aid = (int)($sc['admin_id'] ?? 0);
- if ($aid > 0) {
- $g['score_admin_ids'][$aid] = true;
- }
- $qOp = trim((string)($sc['admin_name'] ?? ''));
- if ($qOp !== '') {
- $g['quality_operator'] = $qOp;
- }
- if ((int)($sc['customer_complaint'] ?? 0) === 1) {
- $g['customer_complaint'] = 1;
- }
- $crm = trim((string)($sc['complaint_remark'] ?? ''));
- if ($crm !== '' && $g['complaint_remark'] === '') {
- $g['complaint_remark'] = $crm;
- }
- if ((int)($sc['order_interrupt'] ?? 0) === 1) {
- $g['order_interrupt'] = 1;
- }
- $ds = trim((string)($sc['delivery_status'] ?? ''));
- if ($ds !== '' && $g['delivery_status'] === '') {
- $g['delivery_status'] = $ds;
- }
- if ($ds !== '' && $g['score_operator'] === '') {
- $op = trim((string)($sc['delivery_admin_name'] ?? ''));
- if ($op === '') {
- $op = trim((string)($sc['admin_name'] ?? ''));
- }
- if ($op !== '') {
- $g['score_operator'] = $op;
- }
- }
- $dd = trim((string)($sc['delivery_date'] ?? ''));
- if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dd, $mdd) && $g['delivery_date'] === '') {
- $g['delivery_date'] = $mdd[1];
- }
- $loc = trim((string)($sc['storage_location'] ?? ''));
- if ($loc !== '' && $g['storage_location'] === '') {
- $g['storage_location'] = $loc;
- }
- $rm = trim((string)($sc['remark'] ?? ''));
- if ($rm !== '' && $g['remark'] === '') {
- $g['remark'] = $rm;
- }
- $st = trim((string)($sc['updatetime'] ?? ''));
- if ($st === '') {
- $st = trim((string)($sc['createtime'] ?? ''));
- }
- if ($st !== '' && ($g['score_time_raw'] === '' || strcmp($st, $g['score_time_raw']) > 0)) {
- $g['score_time_raw'] = $st;
- $op = trim((string)($sc['delivery_admin_name'] ?? ''));
- if ($op === '') {
- $op = trim((string)($sc['admin_name'] ?? ''));
- }
- if ($op !== '') {
- $g['score_operator'] = $op;
- }
- }
- } elseif (is_array($sc)) {
- // 仅填了交货、尚未质量评分
- $ds = trim((string)($sc['delivery_status'] ?? ''));
- if ($ds !== '' && $g['delivery_status'] === '') {
- $g['delivery_status'] = $ds;
- }
- if ($ds !== '' && $g['score_operator'] === '') {
- $op = trim((string)($sc['delivery_admin_name'] ?? ''));
- if ($op === '') {
- $op = trim((string)($sc['admin_name'] ?? ''));
- }
- if ($op !== '') {
- $g['score_operator'] = $op;
- }
- }
- $dd = trim((string)($sc['delivery_date'] ?? ''));
- if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dd, $mdd) && $g['delivery_date'] === '') {
- $g['delivery_date'] = $mdd[1];
- }
- $loc = trim((string)($sc['storage_location'] ?? ''));
- if ($loc !== '' && $g['storage_location'] === '') {
- $g['storage_location'] = $loc;
- }
- $rm = trim((string)($sc['remark'] ?? ''));
- if ($rm !== '' && $g['remark'] === '') {
- $g['remark'] = $rm;
- }
- $st = trim((string)($sc['updatetime'] ?? ''));
- if ($st === '') {
- $st = trim((string)($sc['createtime'] ?? ''));
- }
- if ($st !== '' && ($g['score_time_raw'] === '' || strcmp($st, $g['score_time_raw']) > 0)) {
- $g['score_time_raw'] = $st;
- $op = trim((string)($sc['delivery_admin_name'] ?? ''));
- if ($op === '') {
- $op = trim((string)($sc['admin_name'] ?? ''));
- }
- if ($op !== '') {
- $g['score_operator'] = $op;
- }
- }
- }
- unset($g);
- }
- $out = [];
- foreach ($groups as $g) {
- $ccydh = (string)($g['CCYDH'] ?? '');
- $gymcList = is_array($g['CGYMC_list'] ?? null) ? $g['CGYMC_list'] : [];
- $company = (string)($g['pick_company_name'] ?? '');
- $batchNo = (string)($g['order_batch_no'] ?? '');
- $cyjmc = (string)($g['CYJMC'] ?? '');
- if ($keyword !== '') {
- $blob = $ccydh . ' ' . $batchNo . ' ' . $cyjmc . ' ' . implode('、', $gymcList) . ' ' . $company;
- if (mb_stripos($blob, $keyword) === false) {
- continue;
- }
- }
- $results = is_array($g['results'] ?? null) ? $g['results'] : [];
- $uniq = [];
- $allScored = true;
- foreach ($results as $r) {
- $r = trim((string)$r);
- if ($r === '') {
- $allScored = false;
- continue;
- }
- $uniq[$r] = true;
- }
- $orderResult = '';
- if ($allScored && count($uniq) === 1) {
- $keys = array_keys($uniq);
- $orderResult = (string)($keys[0] ?? '');
- } elseif ($allScored && count($uniq) > 1) {
- $orderResult = '';
- }
- $deliveryStatus = trim((string)($g['delivery_status'] ?? ''));
- $hasDelivery = ($deliveryStatus === '准时' || $deliveryStatus === '滞后');
- if ($scope === 'quality') {
- if ($tab === 'pending' && $orderResult !== '') {
- continue;
- }
- if ($tab === 'scored') {
- if ($orderResult !== '合格' && $orderResult !== '不合格') {
- continue;
- }
- if ($adminId <= 0) {
- continue;
- }
- $adminIds = is_array($g['score_admin_ids'] ?? null) ? $g['score_admin_ids'] : [];
- if (empty($adminIds[$adminId])) {
- continue;
- }
- }
- } else {
- // 交货:待评=尚未填准时/滞后;已评=已填
- if ($tab === 'pending' && $hasDelivery) {
- continue;
- }
- if ($tab === 'scored' && !$hasDelivery) {
- continue;
- }
- }
- $scoreTimeRaw = trim((string)($g['score_time_raw'] ?? ''));
- if ($scoreTimeRaw === '') {
- $scoreTime = '';
- } elseif ($scope === 'delivery') {
- // 交货确认列表:操作时间仅年月日
- $scoreTime = $this->mprocFormatYmdValue($scoreTimeRaw);
- } else {
- $scoreTime = \app\common\library\ProcuremenTime::formatDisplayDateTime($scoreTimeRaw);
- }
- $qtyList = is_array($g['qty_list'] ?? null) ? $g['qty_list'] : [];
- $out[] = [
- 'CCYDH' => $ccydh,
- 'order_batch_no' => $batchNo,
- 'scydgy_id' => (int)($g['scydgy_id'] ?? 0),
- 'scydgy_ids' => array_values(array_unique(array_map('intval', $g['scydgy_ids'] ?? []))),
- 'CYJMC' => $cyjmc,
- 'CGYMC' => $gymcList !== [] ? implode('、', $gymcList) : '',
- 'CCLBMMC' => (string)($g['CCLBMMC'] ?? ''),
- 'pick_company_name' => $company,
- 'pick_time' => (string)($g['pick_time'] ?? ''),
- 'score_time' => $scoreTime !== '' ? $scoreTime : $scoreTimeRaw,
- 'score_time_raw' => $scoreTimeRaw,
- 'score_operator' => $scope === 'quality'
- ? (string)($g['quality_operator'] ?? '')
- : (string)($g['score_operator'] ?? ''),
- 'process_count' => (int)($g['process_count'] ?? 0),
- 'order_qty' => $qtyList !== [] ? implode('、', $qtyList) : '',
- 'result' => $orderResult,
- 'customer_complaint' => (int)($g['customer_complaint'] ?? 0),
- 'complaint_remark' => (string)($g['complaint_remark'] ?? ''),
- 'order_interrupt' => (int)($g['order_interrupt'] ?? 0),
- 'delivery_status' => (string)($g['delivery_status'] ?? ''),
- 'delivery_date' => (string)($g['delivery_date'] ?? ''),
- 'delivery_deadline' => (string)($g['delivery_deadline'] ?? ''),
- 'storage_location' => (string)($g['storage_location'] ?? ''),
- 'remark' => (string)($g['remark'] ?? ''),
- 'arrival_notify_staff' => (string)($g['arrival_notify_staff'] ?? ''),
- 'arrival_notify_time' => (string)($g['arrival_notify_time'] ?? ''),
- ];
- }
- usort($out, static function ($a, $b) use ($tab) {
- if ($tab === 'scored') {
- $ta = (string)($a['score_time_raw'] ?? '');
- $tb = (string)($b['score_time_raw'] ?? '');
- if ($ta !== $tb) {
- return strcmp($tb, $ta);
- }
- }
- $ta = (string)($a['pick_time'] ?? '');
- $tb = (string)($b['pick_time'] ?? '');
- if ($ta !== $tb) {
- return strcmp($tb, $ta);
- }
- $ca = (string)($a['CCYDH'] ?? '');
- $cb = (string)($b['CCYDH'] ?? '');
- if ($ca !== $cb) {
- return strcmp($cb, $ca);
- }
- $ba = (string)($a['order_batch_no'] ?? '');
- $bb = (string)($b['order_batch_no'] ?? '');
- return strcmp($bb, $ba);
- });
- return $out;
- }
- /**
- * 业务员:新增订单询价页
- */
- public function rfqadd()
- {
- $user = $this->mprocGetUser();
- if (!$user) {
- $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
- $safe = $this->mprocSanitizeRedirectUrl($uri);
- if ($safe !== '') {
- Session::set('mproc_intended_url', $safe);
- }
- $this->redirect($this->mprocBuildLoginUrl($safe));
- return;
- }
- if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'rfq')) {
- $jump = $this->mprocBuildAfterLoginHomeUrl($user);
- if ($jump === '') {
- $this->mprocDropCurrentLogin();
- $this->redirect(url('index/index/login'));
- return;
- }
- $this->redirect($jump);
- return;
- }
- $profile = $this->mprocProfileForUser($user);
- $defaultDept = trim((string)($profile['department'] ?? ''));
- if ($defaultDept === '' || $defaultDept === '业务员' || $defaultDept === '管理员') {
- $defaultDept = '营销中心';
- }
- $statusTab = trim((string)$this->request->get('status', 'pending'));
- if ($statusTab !== 'quoted') {
- $statusTab = 'pending';
- }
- $focusSid = (int)$this->request->param('focus_sid', 0);
- if ($focusSid >= 0) {
- $focusSid = 0;
- }
- $this->view->assign('mprocProfile', $profile);
- $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
- $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
- $this->view->assign('nextOrderCcydh', $this->mprocAllocateManualOrderCcydh());
- $this->view->assign('defaultCclbmmc', $defaultDept);
- $this->view->assign('adminNickname', trim((string)($profile['contact_name'] ?? '')) ?: '业务员');
- $this->view->assign('rfqDeptOptions', $this->mprocLoadRfqDeptNameOptions());
- $this->view->assign('rfqStatusTab', $statusTab);
- $this->view->assign('rfqFocusSid', $focusSid);
- $this->view->assign('rows', $this->mprocLoadRfqAddRows($user, '', $statusTab));
- return $this->view->fetch();
- }
- /**
- * 业务员询价列表 JSON(本人发起或被通知)
- * GET:q、status=pending|quoted
- */
- public function rfqaddlist()
- {
- $user = $this->mprocRequireRfqUser();
- $q = trim((string)$this->request->get('q', ''));
- $status = trim((string)$this->request->get('status', 'pending'));
- if ($status !== 'quoted') {
- $status = 'pending';
- }
- $rows = $this->mprocLoadRfqAddRows($user, $q, $status);
- $this->success('ok', null, ['rows' => $rows, 'total' => count($rows), 'status' => $status]);
- }
- /**
- * 业务员查看询价报价(供应商 + 单价)
- * GET:scydgy_id
- */
- public function rfqaddquotes()
- {
- $user = $this->mprocRequireRfqUser();
- $sid = (int)$this->request->param('scydgy_id', 0);
- if ($sid >= 0) {
- $this->error('仅支持手工询价单');
- }
- $po = $this->mprocLoadAccessibleRfqOrder($user, $sid);
- if (!$po) {
- $this->error('询价单不存在或无权查看');
- }
- $list = [];
- try {
- $rows = Db::table('purchase_order_detail')
- ->where('scydgy_id', $sid)
- ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
- ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')')
- ->field('id,company_name,amount')
- ->order('id', 'asc')
- ->select();
- } catch (\Throwable $e) {
- try {
- $rows = Db::table('purchase_order_detail')
- ->where('scydgy_id', $sid)
- ->field('id,company_name,amount')
- ->order('id', 'asc')
- ->select();
- } catch (\Throwable $e2) {
- $rows = [];
- }
- }
- if (!is_array($rows)) {
- $rows = [];
- }
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $amount = trim((string)($row['amount'] ?? ''));
- $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
- $list[] = [
- 'company_name' => trim((string)($row['company_name'] ?? '')),
- 'amount' => $amount,
- 'amount_text' => $isQuoted ? $amount : '',
- 'is_quoted' => $isQuoted,
- ];
- }
- $this->success('ok', null, [
- 'scydgy_id' => $sid,
- 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
- 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
- 'list' => $list,
- ]);
- }
- /**
- * 业务员提交新增订单询价
- * POST:CYJMC、CCLBMMC、CGYMC、CDW、This_quantity、ceilingPrice、CDF、MBZ
- */
- public function rfqaddsave()
- {
- $user = $this->mprocRequireRfqUser();
- if (!$this->request->isPost()) {
- $this->error('请使用 POST');
- }
- $profile = $this->mprocProfileForUser($user);
- $cyjmc = trim((string)$this->request->post('CYJMC', ''));
- $cgymc = trim((string)$this->request->post('CGYMC', ''));
- $cclbmmc = trim((string)$this->request->post('CCLBMMC', ''));
- if ($cyjmc === '') {
- $this->error('请填写印件名称');
- }
- if ($cclbmmc === '') {
- $cclbmmc = trim((string)($profile['department'] ?? ''));
- }
- if ($cclbmmc === '') {
- $cclbmmc = '营销中心';
- }
- $cywyxm = trim((string)($profile['contact_name'] ?? ''));
- if ($cywyxm === '') {
- $cywyxm = trim((string)($user['username'] ?? ''));
- }
- $now = date('Y-m-d H:i:s');
- $lockName = 'procuremen_manual_order_alloc';
- if (!$this->mprocAcquireNamedLock($lockName, 10)) {
- $this->error('系统繁忙,请稍后重试');
- }
- try {
- $ccydh = $this->mprocAllocateManualOrderCcydh();
- $sid = $this->mprocAllocateManualScydgyId();
- $data = [
- 'scydgy_id' => $sid,
- 'CCYDH' => $ccydh,
- 'CYJMC' => $cyjmc,
- 'CGYMC' => $cgymc,
- 'CCLBMMC' => $cclbmmc,
- 'CDW' => trim((string)$this->request->post('CDW', '')),
- 'NGZL' => '',
- 'CDF' => trim((string)$this->request->post('CDF', '')),
- 'cGzzxMc' => '',
- 'MBZ' => trim((string)$this->request->post('MBZ', '')),
- 'cywyxm' => $cywyxm,
- 'notify_salesman' => '',
- 'rfq_salesman_notified' => 0,
- 'rfq_salesman_notify_time' => null,
- 'This_quantity' => trim((string)$this->request->post('This_quantity', '')),
- 'ceilingPrice' => trim((string)$this->request->post('ceilingPrice', '')),
- 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
- 'status' => ProcuremenStatus::PO_IN_PROGRESS,
- 'createtime' => $now,
- 'dStamp' => $now,
- 'dputrecord' => $now,
- ];
- try {
- $this->mprocEnsureRfqSalesmanColumns();
- Db::table('purchase_order')->insert($data);
- } catch (\Throwable $e) {
- $this->error('新增失败:' . $e->getMessage());
- }
- $nextCcydh = $this->mprocAllocateManualOrderCcydh();
- } finally {
- $this->mprocReleaseNamedLock($lockName);
- }
- $this->success('新增成功', '', [
- 'scydgy_id' => $sid,
- 'CCYDH' => $ccydh,
- 'nextOrderCcydh' => $nextCcydh,
- ]);
- }
- /**
- * MySQL 命名锁(跨连接防并发撞号)
- */
- protected function mprocAcquireNamedLock(string $name, int $timeoutSec = 10): bool
- {
- $name = trim($name);
- if ($name === '') {
- return false;
- }
- try {
- $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
- $rows = Db::query('SELECT GET_LOCK(\'' . $nameSql . '\', ' . max(1, $timeoutSec) . ') AS locked');
- if (!is_array($rows) || $rows === []) {
- return false;
- }
- $v = $rows[0]['locked'] ?? $rows[0]['LOCKED'] ?? null;
- return (int)$v === 1;
- } catch (\Throwable $e) {
- return false;
- }
- }
- protected function mprocReleaseNamedLock(string $name): void
- {
- $name = trim($name);
- if ($name === '') {
- return;
- }
- try {
- $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
- Db::query('SELECT RELEASE_LOCK(\'' . $nameSql . '\')');
- } catch (\Throwable $e) {
- }
- }
- protected function mprocAllocateManualScydgyId(): int
- {
- try {
- $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
- $min = (int)$min;
- return $min < 0 ? $min - 1 : -1;
- } catch (\Throwable $e) {
- return -1;
- }
- }
- /**
- * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
- * 调用方须在命名锁内执行,避免并发重复
- */
- protected function mprocAllocateManualOrderCcydh(): string
- {
- $prefix = 'YW' . date('Ymd');
- $maxSeq = 0;
- try {
- $rows = Db::table('purchase_order')
- ->where('CCYDH', 'like', $prefix . '%')
- ->column('CCYDH');
- if (is_array($rows)) {
- foreach ($rows as $ccydh) {
- $ccydh = trim((string)$ccydh);
- if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3,})$/', $ccydh, $m)) {
- $maxSeq = max($maxSeq, (int)$m[1]);
- }
- }
- }
- } catch (\Throwable $e) {
- }
- $next = $maxSeq + 1;
- $width = $next > 999 ? strlen((string)$next) : 3;
- return $prefix . str_pad((string)$next, $width, '0', STR_PAD_LEFT);
- }
- /**
- * @return string[]
- */
- protected function mprocLoadRfqDeptNameOptions(): array
- {
- $out = [];
- try {
- $vals = Db::table('mcyd')
- ->where('CCLBMMC', '<>', '')
- ->whereNotNull('CCLBMMC')
- ->distinct(true)
- ->limit(300)
- ->column('CCLBMMC');
- } catch (\Throwable $e) {
- $vals = [];
- }
- if (is_array($vals)) {
- foreach ($vals as $v) {
- $v = trim((string)$v);
- if ($v === '' || isset($out[$v])) {
- continue;
- }
- $out[$v] = $v;
- }
- }
- try {
- $poVals = Db::table('purchase_order')
- ->where('CCLBMMC', '<>', '')
- ->whereNotNull('CCLBMMC')
- ->distinct(true)
- ->limit(200)
- ->column('CCLBMMC');
- } catch (\Throwable $e) {
- $poVals = [];
- }
- if (is_array($poVals)) {
- foreach ($poVals as $v) {
- $v = trim((string)$v);
- if ($v === '' || isset($out[$v])) {
- continue;
- }
- $out[$v] = $v;
- }
- }
- foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
- if (!isset($out[$preset])) {
- $out[$preset] = $preset;
- }
- }
- $list = array_values($out);
- usort($list, static function ($a, $b) {
- $weight = [
- '营销中心' => 1,
- '业务部' => 2,
- '市场部' => 3,
- '外贸部' => 4,
- '新华技术业务部' => 5,
- ];
- $wa = $weight[$a] ?? 100;
- $wb = $weight[$b] ?? 100;
- if ($wa !== $wb) {
- return $wa <=> $wb;
- }
- return strcmp((string)$a, (string)$b);
- });
- return $list;
- }
- protected function mprocEnsureRfqSalesmanColumns(): void
- {
- static $ok = false;
- if ($ok) {
- return;
- }
- $alters = [
- 'notify_salesman' => "ADD COLUMN `notify_salesman` varchar(500) NOT NULL DEFAULT '' COMMENT '通知业务员' AFTER `cywyxm`",
- 'rfq_salesman_notified' => "ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '是否已通知业务员' AFTER `notify_salesman`",
- 'rfq_salesman_notify_time' => "ADD COLUMN `rfq_salesman_notify_time` datetime DEFAULT NULL COMMENT '通知业务员时间' AFTER `rfq_salesman_notified`",
- ];
- foreach ($alters as $col => $sql) {
- try {
- $exists = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
- if (is_array($exists) && $exists !== []) {
- continue;
- }
- Db::execute('ALTER TABLE `purchase_order` ' . $sql);
- } catch (\Throwable $e) {
- }
- }
- $ok = true;
- }
- /**
- * 校验业务员是否可访问该手工询价单
- *
- * @param array<string, mixed> $user
- * @return array<string, mixed>|null
- */
- protected function mprocLoadAccessibleRfqOrder(array $user, int $sid): ?array
- {
- if ($sid >= 0) {
- return null;
- }
- $profile = $this->mprocProfileForUser($user);
- $adminName = trim((string)($profile['contact_name'] ?? ''));
- if ($adminName === '') {
- $adminName = trim((string)($user['username'] ?? ''));
- }
- $isSuper = $this->mprocAdminIsMobileSuper((int)($user['admin_id'] ?? 0));
- $this->mprocEnsureRfqSalesmanColumns();
- try {
- $query = Db::table('purchase_order')
- ->where('scydgy_id', $sid)
- ->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%\')'
- );
- if (!$isSuper) {
- if ($adminName === '') {
- return null;
- }
- $query->where(function ($q2) use ($adminName) {
- $q2->where('cywyxm', $adminName)
- ->whereOr('notify_salesman', $adminName)
- ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
- ->whereOr('notify_salesman', 'like', $adminName . '、%')
- ->whereOr('notify_salesman', 'like', '%、' . $adminName)
- ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
- ->whereOr('notify_salesman', 'like', $adminName . ',%')
- ->whereOr('notify_salesman', 'like', '%,' . $adminName);
- });
- }
- $row = $query->find();
- } catch (\Throwable $e) {
- return null;
- }
- return is_array($row) ? $row : null;
- }
- /**
- * 手机端业务员询价列表(本人发起 / 被通知)
- *
- * @param array<string, mixed> $user
- * @param string $status pending|quoted|''(空=全部)
- * @return array<int, array<string, mixed>>
- */
- protected function mprocLoadRfqAddRows(array $user, string $q, string $status = ''): array
- {
- $profile = $this->mprocProfileForUser($user);
- $adminName = trim((string)($profile['contact_name'] ?? ''));
- if ($adminName === '') {
- $adminName = trim((string)($user['username'] ?? ''));
- }
- $isSuper = $this->mprocAdminIsMobileSuper((int)($user['admin_id'] ?? 0));
- $this->mprocEnsureRfqSalesmanColumns();
- try {
- $query = Db::table('purchase_order')
- ->where('scydgy_id', '<', 0)
- ->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%\')'
- );
- if (!$isSuper) {
- if ($adminName === '') {
- return [];
- }
- $query->where(function ($q2) use ($adminName) {
- $q2->where('cywyxm', $adminName)
- ->whereOr('notify_salesman', $adminName)
- ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
- ->whereOr('notify_salesman', 'like', $adminName . '、%')
- ->whereOr('notify_salesman', 'like', '%、' . $adminName)
- ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
- ->whereOr('notify_salesman', 'like', $adminName . ',%')
- ->whereOr('notify_salesman', 'like', '%,' . $adminName);
- });
- }
- $q = trim($q);
- if ($q !== '') {
- $like = '%' . str_replace(['%', '_'], ['\\%', '\\_'], $q) . '%';
- $query->where(function ($q2) use ($like) {
- $q2->where('CCYDH', 'like', $like)
- ->whereOr('CYJMC', 'like', $like)
- ->whereOr('CGYMC', 'like', $like)
- ->whereOr('CCLBMMC', 'like', $like)
- ->whereOr('MBZ', 'like', $like);
- });
- }
- $rows = $query
- ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,CDW,CDF,This_quantity,ceilingPrice,cywyxm,MBZ,status,wflow_status,rfq_salesman_notified,createtime,dStamp')
- ->order('id', 'desc')
- ->limit(200)
- ->select();
- } catch (\Throwable $e) {
- $rows = [];
- }
- if (!is_array($rows)) {
- $rows = [];
- }
- $out = [];
- $sids = [];
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['scydgy_id'] ?? 0);
- if ($sid < 0) {
- $sids[$sid] = $sid;
- }
- }
- $quotedMap = $this->mprocLoadRfqQuotedSidMap(array_values($sids));
- $status = trim($status);
- if ($status !== 'pending' && $status !== 'quoted') {
- $status = '';
- }
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['scydgy_id'] ?? 0);
- $isQuoted = !empty($quotedMap[$sid]);
- if ($status === 'pending' && $isQuoted) {
- continue;
- }
- if ($status === 'quoted' && !$isQuoted) {
- continue;
- }
- $created = trim((string)($r['createtime'] ?? ''));
- if ($created === '' || stripos($created, '0000-00-00') === 0) {
- $created = trim((string)($r['dStamp'] ?? ''));
- }
- if (preg_match('/^\d{10,}$/', $created)) {
- $created = date('Y-m-d H:i:s', (int)$created);
- }
- if ($created !== '' && stripos($created, '0000-00-00') === 0) {
- $created = '';
- }
- $out[] = [
- 'id' => (int)($r['id'] ?? 0),
- 'scydgy_id' => $sid,
- 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
- 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
- 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
- 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
- 'CDW' => trim((string)($r['CDW'] ?? '')),
- 'CDF' => trim((string)($r['CDF'] ?? '')),
- 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
- 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
- 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
- 'MBZ' => trim((string)($r['MBZ'] ?? '')),
- 'progress_text' => $isQuoted ? '已报价' : '待询价',
- 'createtime' => $created,
- ];
- }
- return $out;
- }
- /**
- * 哪些手工询价单已有有效报价(amount 非空且非 0)
- *
- * @param array<int, int> $sids
- * @return array<int, bool>
- */
- protected function mprocLoadRfqQuotedSidMap(array $sids): array
- {
- $out = [];
- $sids = array_values(array_unique(array_filter(array_map('intval', $sids), static function ($v) {
- return $v < 0;
- })));
- if ($sids === []) {
- return $out;
- }
- foreach (array_chunk($sids, 200) as $chunk) {
- try {
- $rows = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', $chunk)
- ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
- ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')')
- ->where('amount', '<>', '')
- ->whereNotNull('amount')
- ->where('amount', '<>', '0')
- ->where('amount', '<>', '0.00')
- ->field('scydgy_id')
- ->group('scydgy_id')
- ->select();
- } catch (\Throwable $e) {
- try {
- $rows = Db::table('purchase_order_detail')
- ->where('scydgy_id', 'in', $chunk)
- ->where('amount', '<>', '')
- ->whereNotNull('amount')
- ->where('amount', '<>', '0')
- ->where('amount', '<>', '0.00')
- ->field('scydgy_id')
- ->group('scydgy_id')
- ->select();
- } catch (\Throwable $e2) {
- $rows = [];
- }
- }
- if (!is_array($rows)) {
- continue;
- }
- foreach ($rows as $r) {
- if (!is_array($r)) {
- continue;
- }
- $sid = (int)($r['scydgy_id'] ?? 0);
- if ($sid < 0) {
- $out[$sid] = true;
- }
- }
- }
- return $out;
- }
- /**
- * @param array<string, mixed> $row
- */
- protected function mprocFormatRfqProgressText(array $row): string
- {
- $sid = (int)($row['scydgy_id'] ?? 0);
- if ($sid < 0) {
- $map = $this->mprocLoadRfqQuotedSidMap([$sid]);
- if (!empty($map[$sid])) {
- return '已报价';
- }
- }
- return '待询价';
- }
- }
|