feat(tenant): 增加租户基础与域名解析
This commit is contained in:
@@ -109,7 +109,7 @@ SKIP_CHECKS=1 git push
|
||||
- [接口规划](docs/api.md)
|
||||
- [业务规则](docs/business-rules.md)
|
||||
- [分销网管理后台设计方案](docs/分销网管理后台设计方案.md)
|
||||
- [双运营主体多租户改造分析](docs/双运营主体多租户改造分析.md)
|
||||
- [解忧商行双站点改造方案](docs/解忧商行双站点改造实施计划.md)
|
||||
|
||||
### 分销独立测试库
|
||||
|
||||
|
||||
@@ -21,6 +21,10 @@ REDIS_DB=0
|
||||
|
||||
JWT_SECRET=change-me
|
||||
|
||||
# 经营租户域名;本地留空时通过 X-Tenant-Code 或旧分销站点方式调试。
|
||||
CADDY_DOMAIN=
|
||||
TENANT_JIEYOU_DOMAIN=
|
||||
|
||||
# 前端后台页面入口;本地默认 /admin,生产建议改成不公开的单段路径。
|
||||
VITE_ADMIN_BASE_PATH=/admin
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ APP_ADDR=:8080
|
||||
# Caddy 自动申请和续签 HTTPS 证书使用。
|
||||
CADDY_DOMAIN=hfb.221329.cc.cd
|
||||
CADDY_EMAIL=admin@example.com
|
||||
# 解忧商行前台域名;未启用解忧时留空。
|
||||
TENANT_JIEYOU_DOMAIN=zuhaox.com
|
||||
# 选号网(hfb_show)独立域名,与主站同机;不部署选号网可留空。
|
||||
# CADDY_SHOW_DOMAIN=show.example.com
|
||||
# 选号网源码目录(相对 hfb_sys 根或绝对路径),默认 ../hfb_show
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"hfb_sys/backend/internal/modules/paymentconfig"
|
||||
"hfb_sys/backend/internal/modules/systemconfig"
|
||||
"hfb_sys/backend/internal/router"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
@@ -84,6 +85,12 @@ func main() {
|
||||
}); err != nil {
|
||||
logger.Fatal("初始管理员创建失败", zap.Error(err))
|
||||
}
|
||||
if err := tenancy.BootstrapDomains(context.Background(), db, tenancy.BootstrapConfig{
|
||||
PrimaryDomain: cfg.PrimaryDomain,
|
||||
JieyouDomain: cfg.TenantJieyouDomain,
|
||||
}); err != nil {
|
||||
logger.Fatal("经营租户域名初始化失败", zap.Error(err))
|
||||
}
|
||||
}
|
||||
redisClient, err := database.OpenRedis(context.Background(), database.RedisConfig{
|
||||
Addr: cfg.RedisAddr,
|
||||
|
||||
@@ -24,6 +24,8 @@ type Config struct {
|
||||
BootstrapAdminUsername string
|
||||
BootstrapAdminPassword string
|
||||
BootstrapAdminNickname string
|
||||
PrimaryDomain string
|
||||
TenantJieyouDomain string
|
||||
Storage StorageConfig
|
||||
StorageMirror StorageConfig
|
||||
SMS SMSConfig
|
||||
@@ -102,6 +104,8 @@ func Load() Config {
|
||||
BootstrapAdminUsername: getEnv("ADMIN_BOOTSTRAP_USERNAME", ""),
|
||||
BootstrapAdminPassword: getEnv("ADMIN_BOOTSTRAP_PASSWORD", ""),
|
||||
BootstrapAdminNickname: getEnv("ADMIN_BOOTSTRAP_NICKNAME", "超级管理员"),
|
||||
PrimaryDomain: strings.TrimSpace(getEnv("CADDY_DOMAIN", "")),
|
||||
TenantJieyouDomain: strings.TrimSpace(getEnv("TENANT_JIEYOU_DOMAIN", "")),
|
||||
Storage: StorageConfig{
|
||||
Endpoint: getEnv("STORAGE_ENDPOINT", "http://localhost:19090"),
|
||||
Bucket: getEnv("STORAGE_BUCKET", "hfb-sys"),
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/config"
|
||||
"hfb_sys/backend/internal/sitecode"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const (
|
||||
ContextTenantID = "tenant_id"
|
||||
ContextTenantCode = "tenant_code"
|
||||
tenantCodeHeader = "X-Tenant-Code"
|
||||
)
|
||||
|
||||
type TenantResolver interface {
|
||||
ResolveHost(ctx context.Context, host string) (*tenancy.Scope, error)
|
||||
ResolveCode(ctx context.Context, code string) (*tenancy.Scope, error)
|
||||
}
|
||||
|
||||
func TenantContext(resolver TenantResolver, appEnv string, logger *zap.Logger) gin.HandlerFunc {
|
||||
if resolver == nil {
|
||||
return func(c *gin.Context) { c.Next() }
|
||||
}
|
||||
production := config.IsProductionEnv(appEnv)
|
||||
return func(c *gin.Context) {
|
||||
var (
|
||||
scope *tenancy.Scope
|
||||
err error
|
||||
)
|
||||
if !production {
|
||||
code := strings.TrimSpace(firstNonEmpty(c.GetHeader(tenantCodeHeader), c.Query("tenant_code")))
|
||||
if code != "" {
|
||||
scope, err = resolver.ResolveCode(c.Request.Context(), code)
|
||||
}
|
||||
}
|
||||
if scope == nil && err == nil {
|
||||
scope, err = resolver.ResolveHost(c.Request.Context(), c.Request.Host)
|
||||
}
|
||||
if err != nil && logger != nil {
|
||||
logger.Warn("经营租户解析失败,按旧站点上下文继续",
|
||||
zap.String("host", sitecode.ExtractHost(c.Request.Host)),
|
||||
zap.Error(err),
|
||||
)
|
||||
}
|
||||
if scope != nil {
|
||||
c.Request = c.Request.WithContext(tenancy.WithScope(c.Request.Context(), *scope))
|
||||
c.Set(ContextTenantID, scope.TenantID)
|
||||
c.Set(ContextTenantCode, scope.TenantCode)
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if trimmed := strings.TrimSpace(value); trimmed != "" {
|
||||
return trimmed
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func newTenantContextTestEngine(t *testing.T, appEnv string) (*gin.Engine, model.Tenant) {
|
||||
t.Helper()
|
||||
db := database.NewTestDB()
|
||||
tenant := model.Tenant{Code: "dachui", Name: "大锤商行", Status: "active"}
|
||||
if err := db.Create(&tenant).Error; err != nil {
|
||||
t.Fatalf("create tenant: %v", err)
|
||||
}
|
||||
repo := tenancy.NewRepository(db)
|
||||
if err := repo.UpsertDomain(t.Context(), tenant.Code, "hao858.com", "storefront"); err != nil {
|
||||
t.Fatalf("create domain: %v", err)
|
||||
}
|
||||
|
||||
gin.SetMode(gin.TestMode)
|
||||
engine := gin.New()
|
||||
engine.Use(TenantContext(repo, appEnv, nil))
|
||||
engine.GET("/probe", func(c *gin.Context) {
|
||||
scope, ok := tenancy.FromContext(c.Request.Context())
|
||||
if !ok {
|
||||
c.JSON(http.StatusNotFound, gin.H{"found": false})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"tenant_id": scope.TenantID, "tenant_code": scope.TenantCode})
|
||||
})
|
||||
return engine, tenant
|
||||
}
|
||||
|
||||
func TestTenantContextResolvesHost(t *testing.T) {
|
||||
engine, tenant := newTenantContextTestEngine(t, "production")
|
||||
req := httptest.NewRequest(http.MethodGet, "/probe", nil)
|
||||
req.Host = "hao858.com"
|
||||
rec := httptest.NewRecorder()
|
||||
engine.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if body := rec.Body.String(); body == "" || !contains(body, `"tenant_id":`) {
|
||||
t.Fatalf("unexpected body: %s", body)
|
||||
}
|
||||
if tenant.ID == 0 {
|
||||
t.Fatal("tenant ID should not be zero")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTenantContextAllowsDevelopmentCodeAndIgnoresItInProduction(t *testing.T) {
|
||||
engine, _ := newTenantContextTestEngine(t, "development")
|
||||
req := httptest.NewRequest(http.MethodGet, "/probe", nil)
|
||||
req.Host = "localhost"
|
||||
req.Header.Set(tenantCodeHeader, "dachui")
|
||||
rec := httptest.NewRecorder()
|
||||
engine.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("development code status = %d, body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
engine, _ = newTenantContextTestEngine(t, "production")
|
||||
req = httptest.NewRequest(http.MethodGet, "/probe", nil)
|
||||
req.Host = "localhost"
|
||||
req.Header.Set(tenantCodeHeader, "dachui")
|
||||
rec = httptest.NewRecorder()
|
||||
engine.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("production header status = %d, want 404", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func contains(value, target string) bool {
|
||||
for i := 0; i+len(target) <= len(value); i++ {
|
||||
if value[i:i+len(target)] == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
)
|
||||
|
||||
type Tenant struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
Code string `gorm:"size:32;not null;uniqueIndex:uk_tenants_code" json:"code"`
|
||||
Name string `gorm:"size:64;not null" json:"name"`
|
||||
Status string `gorm:"size:16;not null;default:'active';index" json:"status"`
|
||||
ProfileJSON datatypes.JSON `gorm:"type:json" json:"profile_json"`
|
||||
FeaturesJSON datatypes.JSON `gorm:"type:json" json:"features_json"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (Tenant) TableName() string {
|
||||
return "tenants"
|
||||
}
|
||||
|
||||
type TenantDomain struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint64 `gorm:"not null;index:idx_tenant_domains_tenant" json:"tenant_id"`
|
||||
Host string `gorm:"size:255;not null;uniqueIndex:uk_tenant_domains_host" json:"host"`
|
||||
DomainType string `gorm:"size:32;not null;default:'storefront'" json:"domain_type"`
|
||||
Status string `gorm:"size:16;not null;default:'active';index:idx_tenant_domains_tenant" json:"status"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (TenantDomain) TableName() string {
|
||||
return "tenant_domains"
|
||||
}
|
||||
|
||||
type TenantListingOffer struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint64 `gorm:"not null;uniqueIndex:uk_tenant_listing_offers_listing;index:idx_tenant_listing_offers_display" json:"tenant_id"`
|
||||
ListingID uint64 `gorm:"not null;uniqueIndex:uk_tenant_listing_offers_listing;index:idx_tenant_listing_offers_display" json:"listing_id"`
|
||||
DisplayStatus string `gorm:"size:16;not null;default:'enabled';index:idx_tenant_listing_offers_display" json:"display_status"`
|
||||
PriceCent *int64 `json:"price_cent"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (TenantListingOffer) TableName() string {
|
||||
return "tenant_listing_offers"
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package router
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/config"
|
||||
@@ -43,6 +44,7 @@ import (
|
||||
"hfb_sys/backend/internal/modules/user"
|
||||
"hfb_sys/backend/internal/modules/wallet"
|
||||
"hfb_sys/backend/internal/modules/withdrawal"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
_ "hfb_sys/backend/docs" // Swagger 文档
|
||||
|
||||
@@ -64,6 +66,12 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
engine.Use(middleware.RequestID())
|
||||
engine.Use(middleware.RequestLogger(logger))
|
||||
engine.Use(middleware.Recovery(logger))
|
||||
var tenantRepo *tenancy.Repository
|
||||
if deps.DB != nil {
|
||||
tenantRepo = tenancy.NewRepository(deps.DB)
|
||||
engine.Use(middleware.TenantContext(tenantRepo, cfg.AppEnv, logger))
|
||||
}
|
||||
tenantHandler := tenancy.NewHandler()
|
||||
jwtManager := auth.NewJWTManager(cfg.JWTSecret)
|
||||
|
||||
health := handler.NewHealthHandler(newReadinessChecks(deps))
|
||||
@@ -462,6 +470,33 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
api.GET("/home-announcements", systemConfigHandler.HomeAnnouncements)
|
||||
api.GET("/mobile-home-config", systemConfigHandler.HomeConfig)
|
||||
api.GET("/public/files/object", fileHandler.PublicObject)
|
||||
api.GET("/site/context", tenantHandler.SiteContext)
|
||||
api.GET("/site/check-domain", func(c *gin.Context) {
|
||||
domain := strings.TrimSpace(c.Query("domain"))
|
||||
if domain == "" {
|
||||
c.String(http.StatusBadRequest, "domain required")
|
||||
return
|
||||
}
|
||||
if tenantRepo != nil {
|
||||
allowed, err := tenantRepo.IsActiveDomain(c.Request.Context(), domain)
|
||||
if err != nil {
|
||||
c.String(http.StatusServiceUnavailable, "tenant domain check failed")
|
||||
return
|
||||
}
|
||||
if allowed {
|
||||
c.String(http.StatusOK, "ok")
|
||||
return
|
||||
}
|
||||
}
|
||||
if distributionService != nil {
|
||||
info, err := distributionService.GetPublicSiteInfo(c.Request.Context(), "", domain)
|
||||
if err == nil && info != nil && info.Status == "active" {
|
||||
c.String(http.StatusOK, "ok")
|
||||
return
|
||||
}
|
||||
}
|
||||
c.String(http.StatusNotFound, "domain not allowed")
|
||||
})
|
||||
// Gin 同一前缀只能有一种通配符名;管理端已用 /sites/:id/*,公开列表必须同名。
|
||||
api.GET("/distribution/sites/:id/listings", distributionHandler.ListPublicSiteListings)
|
||||
api.GET("/distribution/site-info", distributionHandler.GetPublicSiteInfo)
|
||||
|
||||
@@ -3,10 +3,12 @@ package router
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/config"
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
@@ -56,6 +58,8 @@ func TestExtractedAdminRoutesRemainRegisteredWithoutDuplicates(t *testing.T) {
|
||||
"PUT /api/admin/roles/:id/permissions",
|
||||
"PUT /api/admin/admin-users/:id/password",
|
||||
"POST /api/admin/announcements/:id/publish",
|
||||
"GET /api/site/context",
|
||||
"GET /api/site/check-domain",
|
||||
"GET /api/distribution/sites/:id/listings",
|
||||
"GET /api/distribution/sites/:id/wallet",
|
||||
} {
|
||||
@@ -64,3 +68,71 @@ func TestExtractedAdminRoutesRemainRegisteredWithoutDuplicates(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSiteContextRouteUsesTenantHost(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
tenant := model.Tenant{
|
||||
Code: "jieyou",
|
||||
Name: "解忧商行",
|
||||
Status: "active",
|
||||
ProfileJSON: []byte(`{"site_name":"解忧商行","logo_url":"https://cdn.example/logo.png"}`),
|
||||
FeaturesJSON: []byte(
|
||||
`{"rental_listing":true}`,
|
||||
),
|
||||
}
|
||||
if err := db.Create(&tenant).Error; err != nil {
|
||||
t.Fatalf("create tenant: %v", err)
|
||||
}
|
||||
if err := db.Create(&model.TenantDomain{
|
||||
TenantID: tenant.ID,
|
||||
Host: "zuhaox.com",
|
||||
DomainType: "storefront",
|
||||
Status: "active",
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("create tenant domain: %v", err)
|
||||
}
|
||||
if err := db.Create(&model.DistributionSite{
|
||||
SiteCode: "legacy_dist",
|
||||
SiteName: "历史分销站",
|
||||
Domain: "legacy.example.com",
|
||||
Status: "active",
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("create legacy distribution site: %v", err)
|
||||
}
|
||||
|
||||
engine := New(testConfig(), Dependencies{DB: db}, zap.NewNop())
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/site/context", nil)
|
||||
req.Host = "zuhaox.com"
|
||||
rec := httptest.NewRecorder()
|
||||
engine.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
body := rec.Body.String()
|
||||
for _, want := range []string{`"tenant_code":"jieyou"`, `"site_name":"解忧商行"`, `"rental_listing":true`} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Fatalf("body missing %s: %s", want, body)
|
||||
}
|
||||
}
|
||||
|
||||
req = httptest.NewRequest(http.MethodGet, "/api/site/context", nil)
|
||||
req.Host = "unknown.example.com"
|
||||
rec = httptest.NewRecorder()
|
||||
engine.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("unknown host status = %d, want 404", rec.Code)
|
||||
}
|
||||
|
||||
for domain, wantStatus := range map[string]int{
|
||||
"zuhaox.com": http.StatusOK,
|
||||
"legacy.example.com": http.StatusOK,
|
||||
"unknown.example.com": http.StatusNotFound,
|
||||
} {
|
||||
req = httptest.NewRequest(http.MethodGet, "/api/site/check-domain?domain="+domain, nil)
|
||||
rec = httptest.NewRecorder()
|
||||
engine.ServeHTTP(rec, req)
|
||||
if rec.Code != wantStatus {
|
||||
t.Fatalf("check domain %s status = %d, want %d; body=%s", domain, rec.Code, wantStatus, rec.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package tenancy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
)
|
||||
|
||||
type contextKey struct{}
|
||||
|
||||
type Scope struct {
|
||||
TenantID uint64
|
||||
TenantCode string
|
||||
TenantName string
|
||||
TenantStatus string
|
||||
Host string
|
||||
DomainType string
|
||||
ProfileJSON datatypes.JSON
|
||||
FeaturesJSON datatypes.JSON
|
||||
}
|
||||
|
||||
func WithScope(ctx context.Context, scope Scope) context.Context {
|
||||
return context.WithValue(ctx, contextKey{}, scope)
|
||||
}
|
||||
|
||||
func FromContext(ctx context.Context) (Scope, bool) {
|
||||
scope, ok := ctx.Value(contextKey{}).(Scope)
|
||||
return scope, ok && scope.TenantID > 0
|
||||
}
|
||||
|
||||
func MustFromContext(ctx context.Context) Scope {
|
||||
scope, ok := FromContext(ctx)
|
||||
if !ok {
|
||||
panic("tenant scope missing from context")
|
||||
}
|
||||
return scope
|
||||
}
|
||||
|
||||
func (s Scope) Profile() map[string]any {
|
||||
return decodeJSONMap(s.ProfileJSON)
|
||||
}
|
||||
|
||||
func (s Scope) Features() map[string]any {
|
||||
return decodeJSONMap(s.FeaturesJSON)
|
||||
}
|
||||
|
||||
func decodeJSONMap(raw datatypes.JSON) map[string]any {
|
||||
if len(raw) == 0 {
|
||||
return map[string]any{}
|
||||
}
|
||||
var value map[string]any
|
||||
if err := json.Unmarshal(raw, &value); err != nil || value == nil {
|
||||
return map[string]any{}
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package tenancy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type SiteContextDTO struct {
|
||||
Mode string `json:"mode"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
TenantCode string `json:"tenant_code"`
|
||||
TenantName string `json:"tenant_name"`
|
||||
Host string `json:"host"`
|
||||
DomainType string `json:"domain_type"`
|
||||
Status string `json:"status"`
|
||||
Profile map[string]any `json:"profile"`
|
||||
Features map[string]any `json:"features"`
|
||||
}
|
||||
|
||||
type Handler struct{}
|
||||
|
||||
func NewHandler() *Handler {
|
||||
return &Handler{}
|
||||
}
|
||||
|
||||
func (h *Handler) SiteContext(c *gin.Context) {
|
||||
scope, ok := FromContext(c.Request.Context())
|
||||
if !ok {
|
||||
response.Error(c, http.StatusNotFound, "site_not_found", "当前域名未配置站点")
|
||||
return
|
||||
}
|
||||
response.OK(c, SiteContextDTO{
|
||||
Mode: "tenant",
|
||||
TenantID: scope.TenantID,
|
||||
TenantCode: scope.TenantCode,
|
||||
TenantName: scope.TenantName,
|
||||
Host: scope.Host,
|
||||
DomainType: scope.DomainType,
|
||||
Status: scope.TenantStatus,
|
||||
Profile: scope.Profile(),
|
||||
Features: scope.Features(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package tenancy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/sitecode"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrDependencyUnavailable = errors.New("tenancy dependency unavailable")
|
||||
ErrTenantNotFound = errors.New("tenant not found")
|
||||
ErrDomainConflict = errors.New("tenant domain belongs to another tenant")
|
||||
)
|
||||
|
||||
const domainCacheTTL = time.Minute
|
||||
|
||||
type domainCacheEntry struct {
|
||||
scope *Scope
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
type Repository struct {
|
||||
db *gorm.DB
|
||||
mu sync.RWMutex
|
||||
cache map[string]domainCacheEntry
|
||||
}
|
||||
|
||||
func NewRepository(db *gorm.DB) *Repository {
|
||||
return &Repository{db: db, cache: make(map[string]domainCacheEntry)}
|
||||
}
|
||||
|
||||
func (r *Repository) ResolveHost(ctx context.Context, rawHost string) (*Scope, error) {
|
||||
if r == nil || r.db == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
host := sitecode.ExtractHost(rawHost)
|
||||
if host == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if cached, ok := r.cachedHost(host); ok {
|
||||
return cached, nil
|
||||
}
|
||||
|
||||
var row struct {
|
||||
TenantID uint64 `gorm:"column:tenant_id"`
|
||||
TenantCode string `gorm:"column:tenant_code"`
|
||||
TenantName string `gorm:"column:tenant_name"`
|
||||
TenantStatus string `gorm:"column:tenant_status"`
|
||||
Host string `gorm:"column:host"`
|
||||
DomainType string `gorm:"column:domain_type"`
|
||||
ProfileJSON []byte `gorm:"column:profile_json"`
|
||||
FeaturesJSON []byte `gorm:"column:features_json"`
|
||||
}
|
||||
err := r.db.WithContext(ctx).
|
||||
Table("tenant_domains AS d").
|
||||
Select(`t.id AS tenant_id, t.code AS tenant_code, t.name AS tenant_name, t.status AS tenant_status,
|
||||
d.host, d.domain_type, t.profile_json, t.features_json`).
|
||||
Joins("JOIN tenants AS t ON t.id = d.tenant_id").
|
||||
Where("d.host = ? AND d.status = ? AND t.status = ?", host, "active", "active").
|
||||
Take(&row).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
r.cacheHost(host, nil)
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
scope := &Scope{
|
||||
TenantID: row.TenantID,
|
||||
TenantCode: row.TenantCode,
|
||||
TenantName: row.TenantName,
|
||||
TenantStatus: row.TenantStatus,
|
||||
Host: row.Host,
|
||||
DomainType: row.DomainType,
|
||||
ProfileJSON: row.ProfileJSON,
|
||||
FeaturesJSON: row.FeaturesJSON,
|
||||
}
|
||||
r.cacheHost(host, scope)
|
||||
return scope, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ResolveCode(ctx context.Context, code string) (*Scope, error) {
|
||||
if r == nil || r.db == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
code = strings.TrimSpace(strings.ToLower(code))
|
||||
if code == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var tenant model.Tenant
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("code = ? AND status = ?", code, "active").
|
||||
First(&tenant).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &Scope{
|
||||
TenantID: tenant.ID,
|
||||
TenantCode: tenant.Code,
|
||||
TenantName: tenant.Name,
|
||||
TenantStatus: tenant.Status,
|
||||
DomainType: "development",
|
||||
ProfileJSON: tenant.ProfileJSON,
|
||||
FeaturesJSON: tenant.FeaturesJSON,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Repository) IsActiveDomain(ctx context.Context, rawHost string) (bool, error) {
|
||||
scope, err := r.ResolveHost(ctx, rawHost)
|
||||
return scope != nil, err
|
||||
}
|
||||
|
||||
func (r *Repository) Invalidate() {
|
||||
r.mu.Lock()
|
||||
r.cache = make(map[string]domainCacheEntry)
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
func (r *Repository) cachedHost(host string) (*Scope, bool) {
|
||||
r.mu.RLock()
|
||||
entry, ok := r.cache[host]
|
||||
r.mu.RUnlock()
|
||||
if !ok || time.Now().After(entry.expiresAt) {
|
||||
return nil, false
|
||||
}
|
||||
if entry.scope == nil {
|
||||
return nil, true
|
||||
}
|
||||
copied := *entry.scope
|
||||
return &copied, true
|
||||
}
|
||||
|
||||
func (r *Repository) cacheHost(host string, scope *Scope) {
|
||||
r.mu.Lock()
|
||||
r.cache[host] = domainCacheEntry{scope: scope, expiresAt: time.Now().Add(domainCacheTTL)}
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
type BootstrapConfig struct {
|
||||
PrimaryDomain string
|
||||
JieyouDomain string
|
||||
}
|
||||
|
||||
func BootstrapDomains(ctx context.Context, db *gorm.DB, cfg BootstrapConfig) error {
|
||||
if db == nil {
|
||||
return nil
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
primary := sitecode.ExtractHost(cfg.PrimaryDomain)
|
||||
jieyou := sitecode.ExtractHost(cfg.JieyouDomain)
|
||||
|
||||
if primary != "" {
|
||||
if err := repo.UpsertDomain(ctx, "dachui", primary, "storefront"); err != nil {
|
||||
return err
|
||||
}
|
||||
h5 := "h5." + primary
|
||||
if err := repo.UpsertDomain(ctx, "dachui", h5, "storefront_alias"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if jieyou != "" && jieyou != primary {
|
||||
if err := repo.UpsertDomain(ctx, "jieyou", jieyou, "storefront"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) UpsertDomain(ctx context.Context, tenantCode, rawHost, domainType string) error {
|
||||
if r == nil || r.db == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
host := sitecode.ExtractHost(rawHost)
|
||||
if host == "" {
|
||||
return nil
|
||||
}
|
||||
var tenant model.Tenant
|
||||
if err := r.db.WithContext(ctx).Where("code = ?", tenantCode).First(&tenant).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrTenantNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var existing model.TenantDomain
|
||||
err := tx.Where("host = ?", host).First(&existing).Error
|
||||
if err == nil {
|
||||
if existing.TenantID != tenant.ID {
|
||||
return ErrDomainConflict
|
||||
}
|
||||
return tx.Model(&existing).Updates(map[string]any{
|
||||
"domain_type": domainType,
|
||||
"status": "active",
|
||||
}).Error
|
||||
}
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return err
|
||||
}
|
||||
return tx.Create(&model.TenantDomain{
|
||||
TenantID: tenant.ID,
|
||||
Host: host,
|
||||
DomainType: domainType,
|
||||
Status: "active",
|
||||
}).Error
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
r.Invalidate()
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package tenancy
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
)
|
||||
|
||||
func setupTenantRepoTest(t *testing.T) (*Repository, model.Tenant, model.Tenant) {
|
||||
t.Helper()
|
||||
db := database.NewTestDB()
|
||||
dachui := model.Tenant{Code: "dachui", Name: "大锤商行", Status: "active"}
|
||||
jieyou := model.Tenant{Code: "jieyou", Name: "解忧商行", Status: "active"}
|
||||
if err := db.Create(&dachui).Error; err != nil {
|
||||
t.Fatalf("create dachui tenant: %v", err)
|
||||
}
|
||||
if err := db.Create(&jieyou).Error; err != nil {
|
||||
t.Fatalf("create jieyou tenant: %v", err)
|
||||
}
|
||||
return NewRepository(db), dachui, jieyou
|
||||
}
|
||||
|
||||
func TestResolveHostNormalizesAndIgnoresInactiveDomains(t *testing.T) {
|
||||
repo, dachui, jieyou := setupTenantRepoTest(t)
|
||||
if err := repo.UpsertDomain(t.Context(), "dachui", "hao858.com", "storefront"); err != nil {
|
||||
t.Fatalf("upsert dachui domain: %v", err)
|
||||
}
|
||||
if err := repo.db.Create(&model.TenantDomain{
|
||||
TenantID: jieyou.ID,
|
||||
Host: "disabled.example.com",
|
||||
DomainType: "storefront",
|
||||
Status: "disabled",
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("create disabled domain: %v", err)
|
||||
}
|
||||
|
||||
scope, err := repo.ResolveHost(t.Context(), "HAO858.COM:443")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve host: %v", err)
|
||||
}
|
||||
if scope == nil || scope.TenantID != dachui.ID || scope.TenantCode != "dachui" {
|
||||
t.Fatalf("resolved scope = %#v, want dachui", scope)
|
||||
}
|
||||
|
||||
scope, err = repo.ResolveHost(t.Context(), "disabled.example.com")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve disabled host: %v", err)
|
||||
}
|
||||
if scope != nil {
|
||||
t.Fatalf("disabled domain resolved to %#v", scope)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrapDomainsIsIdempotentAndRejectsHostConflict(t *testing.T) {
|
||||
repo, _, _ := setupTenantRepoTest(t)
|
||||
cfg := BootstrapConfig{PrimaryDomain: "hao858.com", JieyouDomain: "zuhaox.com"}
|
||||
if err := BootstrapDomains(t.Context(), repo.db, cfg); err != nil {
|
||||
t.Fatalf("bootstrap domains: %v", err)
|
||||
}
|
||||
if err := BootstrapDomains(t.Context(), repo.db, cfg); err != nil {
|
||||
t.Fatalf("bootstrap domains second run: %v", err)
|
||||
}
|
||||
|
||||
var count int64
|
||||
if err := repo.db.Model(&model.TenantDomain{}).Count(&count).Error; err != nil {
|
||||
t.Fatalf("count domains: %v", err)
|
||||
}
|
||||
if count != 3 {
|
||||
t.Fatalf("domain count = %d, want 3", count)
|
||||
}
|
||||
if err := repo.UpsertDomain(t.Context(), "jieyou", "hao858.com", "storefront"); !errors.Is(err, ErrDomainConflict) {
|
||||
t.Fatalf("conflicting domain error = %v, want ErrDomainConflict", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveCode(t *testing.T) {
|
||||
repo, dachui, _ := setupTenantRepoTest(t)
|
||||
scope, err := repo.ResolveCode(t.Context(), " DAC HUI ")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve empty code: %v", err)
|
||||
}
|
||||
if scope != nil {
|
||||
t.Fatalf("invalid code resolved to %#v", scope)
|
||||
}
|
||||
scope, err = repo.ResolveCode(t.Context(), "DACHUI")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve code: %v", err)
|
||||
}
|
||||
if scope == nil || scope.TenantID != dachui.ID {
|
||||
t.Fatalf("resolved scope = %#v, want dachui", scope)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tenants (
|
||||
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
|
||||
code VARCHAR(32) NOT NULL,
|
||||
name VARCHAR(64) NOT NULL,
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'active',
|
||||
profile_json JSON NULL,
|
||||
features_json JSON NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY uk_tenants_code (code),
|
||||
KEY idx_tenants_status (status)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='经营租户';
|
||||
|
||||
INSERT INTO tenants (code, name, status, profile_json, features_json)
|
||||
VALUES
|
||||
('dachui', '大锤商行', 'active', JSON_OBJECT('site_name', '大锤商行'), JSON_OBJECT()),
|
||||
('jieyou', '解忧商行', 'active', JSON_OBJECT('site_name', '解忧商行'), JSON_OBJECT())
|
||||
ON DUPLICATE KEY UPDATE
|
||||
name = VALUES(name),
|
||||
status = VALUES(status),
|
||||
updated_at = CURRENT_TIMESTAMP;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tenant_domains (
|
||||
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
|
||||
tenant_id BIGINT UNSIGNED NOT NULL,
|
||||
host VARCHAR(255) NOT NULL,
|
||||
domain_type VARCHAR(32) NOT NULL DEFAULT 'storefront',
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'active',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY uk_tenant_domains_host (host),
|
||||
KEY idx_tenant_domains_tenant (tenant_id, domain_type, status)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='经营租户域名';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tenant_listing_offers (
|
||||
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
|
||||
tenant_id BIGINT UNSIGNED NOT NULL,
|
||||
listing_id BIGINT UNSIGNED NOT NULL,
|
||||
display_status VARCHAR(16) NOT NULL DEFAULT 'enabled',
|
||||
price_cent BIGINT NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY uk_tenant_listing_offers_listing (tenant_id, listing_id),
|
||||
KEY idx_tenant_listing_offers_display (tenant_id, display_status, listing_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='经营租户商品货架';
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE IF EXISTS tenant_listing_offers;
|
||||
DROP TABLE IF EXISTS tenant_domains;
|
||||
DROP TABLE IF EXISTS tenants;
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
email {$CADDY_EMAIL}
|
||||
on_demand_tls {
|
||||
ask http://backend:8080/api/distribution/check-domain
|
||||
ask http://backend:8080/api/site/check-domain
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,8 +47,8 @@
|
||||
}
|
||||
}
|
||||
|
||||
# 前台商城静态资源与安全头配置(主站与所有分销站点共享):
|
||||
# 前端通过 window.location.hostname 自动向 /api/distribution/site-info 请求分销配置。
|
||||
# 前台商城静态资源与安全头配置(经营站点与历史分销站点共享):
|
||||
# 前端先通过 /api/site/context 解析经营租户,历史分销域名继续走 /api/distribution/site-info。
|
||||
(storefront) {
|
||||
encode zstd gzip
|
||||
|
||||
@@ -143,8 +143,8 @@ gitea.hao858.com {
|
||||
reverse_proxy gitea:3000
|
||||
}
|
||||
|
||||
# 分销站点动态域名入口:
|
||||
# 支持任意二级域名及分销商独立域名,首次访问时通过 on_demand_tls 触发后端白名单校验并自动签发 SSL 证书。
|
||||
# 动态域名入口:
|
||||
# 支持经营租户域名、二级域名及历史分销独立域名,首次访问时通过 on_demand_tls 白名单校验后签发 SSL 证书。
|
||||
https:// {
|
||||
tls {
|
||||
on_demand
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,369 @@
|
||||
# 解忧商行双站点改造方案
|
||||
|
||||
> 状态:MVP 基调稿 v2.0
|
||||
> 更新时间:2026-11-15
|
||||
> 目标:用一套后端、一套数据库和一套前端,上线大锤商行、解忧商行两个经营站点
|
||||
|
||||
## 1. 基调
|
||||
|
||||
首期只解决以下问题:
|
||||
|
||||
- 两个站点共享同一号库和租赁库存。
|
||||
- 两个站点都有独立用户、登录、支付、钱包、后台权限和统计。
|
||||
- 两个站点都能发布商品,也都能购买对方货架上的商品。
|
||||
- 同一商品只能被一个租户成功锁定和出租。
|
||||
- 现有分销系统继续按旧逻辑运行,不升级成经营租户。
|
||||
|
||||
首期不建设完整公司会计系统,不做自动公司间结算、自动打款、复杂对账、双履约状态机或跨站内部案件。公司间货款先按订单报表线下确认和结算。
|
||||
|
||||
## 2. 不可混淆的概念
|
||||
|
||||
| 概念 | 定义 |
|
||||
|---|---|
|
||||
| 经营租户 | 大锤商行或解忧商行,存储于 `tenants` |
|
||||
| 买方租户 | 用户实际下单、支付和接受对客服务的站点 |
|
||||
| 货源租户 | 商品和号主所属的站点 |
|
||||
| 支付租户 | 实际收取款项的站点,首期等于买方租户 |
|
||||
| 租户货架 | `tenant_listing_offers`,表示共享商品在某个站点的展示和售价 |
|
||||
| 历史分销站 | 现有 `distribution_sites`,仅保留旧分销渠道语义 |
|
||||
|
||||
解忧不是分销站。不得把解忧写入 `distribution_sites`,不得用 `distribution_mode`、分销规则或分销结算表达经营租户。
|
||||
|
||||
买卖方向不固定:
|
||||
|
||||
- 大锤用户可以购买解忧商品。
|
||||
- 解忧用户可以购买大锤商品。
|
||||
- 哪个站点发布商品,哪个站点就是货源租户。
|
||||
- 哪个站点的用户下单和付款,哪个站点就是买方租户和支付租户。
|
||||
|
||||
## 3. 首期范围
|
||||
|
||||
### 3.1 必须完成
|
||||
|
||||
- 域名到经营租户的服务端解析。
|
||||
- 两个站点独立注册、登录、JWT、短信和实名。
|
||||
- 共享商品、号主来源租户和双站货架。
|
||||
- 双站商品列表、详情、图片、搜索、货架价格和下单校验。
|
||||
- 订单记录买方租户、货源租户和支付租户。
|
||||
- 两个站点互相购买。
|
||||
- 支付商户、支付单和退款按租户隔离。
|
||||
- 用户钱包、提现、通知和后台数据按租户隔离。
|
||||
- 站点用户数、成交额、支付、退款、货源出货和号主结算统计。
|
||||
- 订单、会话、缓存、文件和定时任务带租户上下文。
|
||||
- 现有分销链路回归测试保持通过。
|
||||
|
||||
### 3.2 首期不做
|
||||
|
||||
- 公司间自动应收应付、总账、冲销和对账系统。
|
||||
- 自动银行清算、分账和公司间打款。
|
||||
- 独立的客户订单状态和货源供货状态机。
|
||||
- `fulfillment_tasks`、`order_tenant_roles` 等额外订单体系。
|
||||
- 客户会话、号主会话和平台内部案件三套聊天体系。
|
||||
- 独立租户二维码表。
|
||||
- 独立平台后台域名和租户后台域名。
|
||||
- 统一跨站客服工作台。
|
||||
- 双向自动铺货规则、复杂供货合同和自动追偿。
|
||||
- 与首期无关的撞车、积分、邀请、成长、优质号主、线下提号和广告归因改造。
|
||||
|
||||
## 4. 目标架构
|
||||
|
||||
```text
|
||||
大锤域名 / 解忧域名
|
||||
|
|
||||
Caddy / HTTPS
|
||||
|
|
||||
同一套 Go 后端
|
||||
|
|
||||
同一个 MySQL
|
||||
|
|
||||
共享号库和租赁库存
|
||||
```
|
||||
|
||||
保持一套后端、一套数据库和一套前端代码。两个站点通过 Host 解析租户,不复制服务,不建立租户独立数据库。
|
||||
|
||||
生产环境只信任服务端解析的 Host。未知域名失败关闭,不使用 query、`sessionStorage` 或 `X-Distribution-Site-Code` 切换经营租户。开发环境可以使用显式租户标识模拟站点。
|
||||
|
||||
## 5. 最小数据模型
|
||||
|
||||
### 5.1 新增核心表
|
||||
|
||||
| 表 | 作用 |
|
||||
|---|---|
|
||||
| `tenants` | 租户编码、名称、状态、品牌配置和功能配置 |
|
||||
| `tenant_domains` | 租户域名、域名类型和启用状态 |
|
||||
| `tenant_listing_offers` | 商品在某个租户货架的展示状态和销售价格 |
|
||||
|
||||
首期不新增 `tenant_profiles`、`tenant_configs`、`tenant_feature_flags`、`tenant_memberships` 等重复抽象:
|
||||
|
||||
- 品牌和功能配置放 `tenants.profile_json`、`tenants.features_json`。
|
||||
- 配置覆盖使用现有 `system_configs` 增加 `tenant_id`。
|
||||
- 后台人员租户范围通过现有 `admin_user_roles` 增加 `tenant_id`。
|
||||
|
||||
### 5.2 现有表增加租户字段
|
||||
|
||||
| 表 | 字段 |
|
||||
|---|---|
|
||||
| `users` | `tenant_id`,手机号唯一键改为 `(tenant_id, phone)` |
|
||||
| `user_realname` | `tenant_id`,身份证唯一键改为 `(tenant_id, id_no_hash)` |
|
||||
| `user_payment_accounts` | `tenant_id` |
|
||||
| `wallet_accounts`、`wallet_ledger` | `tenant_id` |
|
||||
| `withdrawal_requests` | `tenant_id` |
|
||||
| `game_accounts` | `source_tenant_id` |
|
||||
| `rental_listings` | `source_tenant_id`、`owner_tenant_id` |
|
||||
| `rental_orders` | `buyer_tenant_id`、`source_tenant_id`、`payment_tenant_id`、`source_amount_cent` |
|
||||
| `payment_merchant_configs` | `owner_tenant_id` |
|
||||
| `payment_orders` | `tenant_id` |
|
||||
| `notifications`、`sms_messages` | `tenant_id`、`source_tenant_id` |
|
||||
| `chat_conversations`、`chat_support_groups`、`chat_quick_replies` | `tenant_id` |
|
||||
| `chat_qrcode_pool`、`chat_qrcode_delivery_tasks` | `tenant_id` |
|
||||
| `announcements` | `tenant_id` |
|
||||
| `file_upload_owners` | `tenant_id` |
|
||||
| `system_configs` | `tenant_id`,租户唯一键为 `(tenant_id, key)` |
|
||||
| `admin_user_roles` | `tenant_id`,平台角色使用 `0` |
|
||||
|
||||
现有 `distribution_*` 表不增加经营租户语义,继续服务历史分销。
|
||||
|
||||
### 5.3 订单必须保存的最小角色快照
|
||||
|
||||
```text
|
||||
buyer_tenant_id
|
||||
source_tenant_id
|
||||
payment_tenant_id
|
||||
source_amount_cent
|
||||
```
|
||||
|
||||
约束:
|
||||
|
||||
- 首期 `payment_tenant_id = buyer_tenant_id`。
|
||||
- 买方用户所属租户必须等于买方租户。
|
||||
- 号主用户所属租户必须等于货源租户。
|
||||
- 买方商品价格取租户货架价格。
|
||||
- 货源金额取商品基础价或双方确认的供货价,并在下单时固化。
|
||||
|
||||
不再增加合同卖方、履约方、争议方等可由上述字段推导的角色字段。
|
||||
|
||||
## 6. 用户、后台和权限
|
||||
|
||||
- 同一手机号可以在两个租户分别注册。
|
||||
- JWT 必须包含 `tenant_id` 和 `scope`。
|
||||
- 用户令牌只能访问令牌所属经营租户。
|
||||
- 短信验证码、登录失败、限流、实名和钱包 Key 都带租户。
|
||||
- 管理员仍是全局身份,通过 `admin_user_roles.tenant_id` 获得一个或多个租户角色。
|
||||
- 共享客服可以同时拥有两个租户的客服角色。
|
||||
- `super_admin` 使用 `tenant_id=0` 的平台角色,可以查看全部租户。
|
||||
- 首期复用同一套后台页面,通过当前 Host 确定租户;不拆独立后台域名。
|
||||
- 权限缓存 Key 至少包含管理员 ID 和租户 ID。
|
||||
|
||||
## 7. 共享号库和双站货架
|
||||
|
||||
### 7.1 商品来源
|
||||
|
||||
- 商品和游戏账号只有一份。
|
||||
- 商品发布人所属租户即为货源租户。
|
||||
- 货源租户负责商品、号主、交接和号主结算。
|
||||
- 买方租户不能修改货源租户的商品和号主信息。
|
||||
|
||||
### 7.2 货架
|
||||
|
||||
商品审核通过后,为大锤和解忧各创建一条 `tenant_listing_offers`:
|
||||
|
||||
- 两个站点默认都可见。
|
||||
- 每个站点可以单独关闭展示。
|
||||
- 每个站点可以设置自己的销售价格。
|
||||
- 站点未启用的商品不得通过列表、详情、图片、搜索、分享链接或下单访问。
|
||||
|
||||
商品详情和图片必须根据当前租户货架校验,不能只依赖列表过滤。
|
||||
|
||||
### 7.3 库存
|
||||
|
||||
库存锁定继续使用 `rental_listings` 和共享账号行锁。两个租户同时下单时,只允许一笔订单成功占用商品。
|
||||
|
||||
## 8. 订单和双向购买
|
||||
|
||||
### 8.1 下单
|
||||
|
||||
同一数据库事务内完成:
|
||||
|
||||
1. 校验买方用户属于当前租户。
|
||||
2. 校验租户货架已启用。
|
||||
3. 锁定商品和账号。
|
||||
4. 读取买方货架售价和货源金额。
|
||||
5. 创建一笔 `rental_orders`。
|
||||
6. 保存买方、货源、支付租户和价格快照。
|
||||
7. 锁定商品并写入买方订单通知。
|
||||
|
||||
### 8.2 订单展示
|
||||
|
||||
只保留一份订单和一套现有租赁状态机,按访问者角色过滤字段和操作:
|
||||
|
||||
- 买方用户看到支付、客户资料、交付、归还、结账和退款操作。
|
||||
- 号主看到商品、交接、归还确认和结算信息。
|
||||
- 买方租户后台负责对客订单和退款。
|
||||
- 货源租户后台负责号主交接和货源出货。
|
||||
- 平台超级管理员可以查看完整订单。
|
||||
|
||||
同一订单可以在两个站点出现,但必须明确显示“本站买入”或“本站出货”,不能都叫“本站成交”。
|
||||
|
||||
### 8.3 跨租户流程
|
||||
|
||||
```text
|
||||
A 站商品进入 B 站货架
|
||||
-> B 站用户下单并支付到 B 站商户
|
||||
-> A 站号主在 A 站处理交接
|
||||
-> B 站买方在 B 站确认收号和归还
|
||||
-> B 站记录客户成交和退款
|
||||
-> A 站记录货源出货和号主收入
|
||||
-> 两站货款线下结算
|
||||
```
|
||||
|
||||
大锤买解忧和 解忧买大锤使用同一逻辑,不写两套代码。
|
||||
|
||||
## 9. 支付、退款和钱包
|
||||
|
||||
- 买方订单只使用买方租户的支付商户。
|
||||
- 找不到本租户商户时支付失败,不回退其他租户。
|
||||
- 支付回调通过支付单定位租户,不依赖回调 Host。
|
||||
- 退款固定使用原支付单和原商户。
|
||||
- 原商户不可用时停止自动退款并告警。
|
||||
- 买方用户钱包、提现按买方租户隔离。
|
||||
- 号主收入进入货源租户用户钱包。
|
||||
- 支付成功不等于号主收入到账,号主结算仍由订单完成流程触发。
|
||||
- 首期不生成公司间总账。跨公司应结算金额通过订单快照和报表输出。
|
||||
|
||||
## 10. 独立统计
|
||||
|
||||
每个租户至少提供以下两组口径:
|
||||
|
||||
| 口径 | 统计来源 |
|
||||
|---|---|
|
||||
| 本站用户 | `users.tenant_id` |
|
||||
| 本站买入订单和客户 GMV | `rental_orders.buyer_tenant_id` |
|
||||
| 本站支付和退款 | `payment_orders.tenant_id` |
|
||||
| 本站卖出商品 | `rental_listings.source_tenant_id` |
|
||||
| 本站出货订单 | `rental_orders.source_tenant_id` |
|
||||
| 号主应结算 | 订单货源金额和号主结算金额 |
|
||||
|
||||
平台统计按租户分组展示,不把两个租户的内部交易重复相加为公司 GMV。
|
||||
|
||||
## 11. 客服、通知、文件和任务
|
||||
|
||||
首期使用最小隔离:
|
||||
|
||||
- 一笔订单创建一个订单会话,会话归属买方租户。
|
||||
- 买方和货源号主按订单角色参与该会话。
|
||||
- 共享客服必须拥有当前租户的客服角色才能查看和回复。
|
||||
- SSE 事件带 `tenant_id`,无权限管理员不能收到会话内容。
|
||||
- 二维码池增加 `tenant_id`,订单会话使用买方租户二维码。
|
||||
- 通知、短信、未读统计和消息缓存按租户隔离。
|
||||
- 私有文件上传和读取校验租户及业务角色。
|
||||
- 定时任务从订单、支付、会话等业务记录恢复租户,无法解析时暂停并告警。
|
||||
|
||||
首期不做客户会话、货源会话、内部案件的复杂拆分。
|
||||
|
||||
## 12. 历史分销兼容
|
||||
|
||||
- `distribution_sites`、分销后台、分销订单和分销结算保持现有逻辑。
|
||||
- 分销用户继续按 `distribution_site_id` 保持渠道归属。
|
||||
- 历史分销域名继续由现有分销解析逻辑处理。
|
||||
- 新经营租户订单不写分销财务快照。
|
||||
- 历史分销订单不根据 `distribution_site_id` 猜测经营租户。
|
||||
- 现有分销 E2E 测试必须全部保持通过。
|
||||
|
||||
## 13. 实施阶段
|
||||
|
||||
### 阶段 0:确认基调,1~2 天
|
||||
|
||||
- 确认两个站点都允许发布和购买。
|
||||
- 确认买方租户负责收款和退款。
|
||||
- 确认站间货款线下结算。
|
||||
- 确认首期不建设公司总账和双状态机。
|
||||
|
||||
### 阶段 1:租户和域名,3~5 天
|
||||
|
||||
- 新增 3 张核心表。
|
||||
- 实现 Host 解析和前端租户配置。
|
||||
- 完成 Caddy 域名校验和未知域名失败关闭。
|
||||
|
||||
### 阶段 2:用户、认证和后台权限,5~7 天
|
||||
|
||||
- 用户、实名、收款账户、钱包和提现增加租户。
|
||||
- JWT、短信和登录限流增加租户。
|
||||
- 后台角色和权限增加租户范围。
|
||||
- 完成同手机号双租户注册和越权测试。
|
||||
|
||||
### 阶段 3:共享商品和双站货架,4~6 天
|
||||
|
||||
- 商品增加来源租户。
|
||||
- 审核通过后生成两个站点的货架。
|
||||
- 列表、详情、图片、搜索和下单统一校验货架。
|
||||
- 完成双站并发抢号测试。
|
||||
|
||||
### 阶段 4:订单和统计,6~8 天
|
||||
|
||||
- 订单增加买方、货源、支付租户及货源金额快照。
|
||||
- 两个站点支持互相下单和角色化订单展示。
|
||||
- 完成买方统计、货源统计和平台统计。
|
||||
|
||||
### 阶段 5:支付、退款和钱包,4~6 天
|
||||
|
||||
- 支付配置和支付单增加租户。
|
||||
- 禁止跨租户商户回退。
|
||||
- 退款固定原商户。
|
||||
- 号主收入进入货源租户钱包。
|
||||
|
||||
### 阶段 6:客服、通知、文件和任务,4~6 天
|
||||
|
||||
- 会话、二维码、通知、短信和未读统计增加租户。
|
||||
- 文件访问增加租户和角色校验。
|
||||
- 定时任务按记录租户处理。
|
||||
|
||||
### 阶段 7:迁移、灰度上线,5~7 天
|
||||
|
||||
- 创建大锤和解忧租户。
|
||||
- 回填历史大锤用户和业务数据。
|
||||
- 生产库副本执行迁移和并发、支付、退款、越权测试。
|
||||
- 解忧先内部访问,再灰度开放。
|
||||
|
||||
预计 30~40 人日。两个后端、一个前端和测试并行时,约 4~6 周进入灰度。
|
||||
|
||||
## 14. 迁移和回滚
|
||||
|
||||
迁移顺序:
|
||||
|
||||
1. 创建租户、域名和货架表。
|
||||
2. 创建大锤、解忧两个固定租户。
|
||||
3. 增加可空租户字段并回填历史大锤数据。
|
||||
4. 创建货架关系和复合索引。
|
||||
5. 切换新租户读写路径。
|
||||
6. 验证后给关键字段增加非空约束。
|
||||
|
||||
现有分销表不迁移为经营租户。
|
||||
|
||||
启用解忧前必须保留大锤完整回归数据。启用同手机号双租户后,应用回滚不能再退回旧全局手机号版本;故障回滚通过关闭解忧域名和功能开关、保留兼容代码完成。
|
||||
|
||||
## 15. 上线验收
|
||||
|
||||
- 未知域名不会落到大锤。
|
||||
- 同一手机号可以在两个租户注册。
|
||||
- 大锤 JWT 不能访问解忧数据,反向同样拒绝。
|
||||
- 两个站点都能看到双方开放的商品。
|
||||
- 未开放商品无法通过详情、图片、搜索或分享链接访问。
|
||||
- 两个租户并发购买同一账号只能成功一单。
|
||||
- 大锤用户能买解忧商品。
|
||||
- 解忧用户能买大锤商品。
|
||||
- 支付只进入买方租户商户,缺失时失败关闭。
|
||||
- 退款只使用原支付租户和原商户。
|
||||
- 两个站点的用户、订单、支付、钱包和统计互不串数据。
|
||||
- 无租户上下文的任务暂停并告警。
|
||||
- 现有分销 E2E 全部通过。
|
||||
|
||||
## 16. 后续增强
|
||||
|
||||
以下能力单独设计,不进入本次上线:
|
||||
|
||||
- 公司间自动总账、对账和打款。
|
||||
- 自动供货合同和追偿。
|
||||
- 客户会话、货源会话、平台内部案件拆分。
|
||||
- 统一跨站客服工作台。
|
||||
- 独立平台后台域名和租户后台域名。
|
||||
- 自动双向铺货策略和复杂定价规则。
|
||||
@@ -697,11 +697,6 @@ function resourceText(row: Listing, key: string) {
|
||||
return quantity > 0 ? formatQuantity(quantity) : '-'
|
||||
}
|
||||
|
||||
function skinGroupText(row: Listing, groupKey: string) {
|
||||
const skins = getSkinGroup(row, groupKey)
|
||||
return skins.length ? skins.join('、') : '-'
|
||||
}
|
||||
|
||||
function skinAssetText(row: Listing) {
|
||||
const groups = [
|
||||
{ label: '刀', key: 'melee' },
|
||||
|
||||
@@ -68,7 +68,7 @@ const displayAnnouncements = computed(() => {
|
||||
const banners = ref<HomeBannerSlide[]>(defaultHomeBanners)
|
||||
const displayBanners = computed<HomeBannerSlide[]>(() => {
|
||||
const list =
|
||||
siteStore.isDistribution && siteStore.banners.length > 0
|
||||
siteStore.hasCustomBrand && siteStore.banners.length > 0
|
||||
? mapDistributionHomeBanners(siteStore.banners, siteStore.siteName)
|
||||
: banners.value
|
||||
return list.filter(slide => slide.enabled !== false)
|
||||
|
||||
@@ -114,7 +114,7 @@ const displayAnnouncements = computed(() => {
|
||||
const bannerSlides = ref<HomeBannerSlide[]>(defaultHomeBanners)
|
||||
const displayBanners = computed<HomeBannerSlide[]>(() => {
|
||||
const list =
|
||||
siteStore.isDistribution && siteStore.banners.length > 0
|
||||
siteStore.hasCustomBrand && siteStore.banners.length > 0
|
||||
? mapDistributionHomeBanners(siteStore.banners, siteStore.siteName)
|
||||
: bannerSlides.value
|
||||
return list.filter(slide => slide.enabled !== false)
|
||||
@@ -873,15 +873,13 @@ if (!restoreHomeConfigFromCache()) {
|
||||
<section class="mobile-hero">
|
||||
<div class="mobile-topbar">
|
||||
<div class="mobile-brand">
|
||||
<span class="mobile-logo">{{
|
||||
siteStore.isDistribution ? siteStore.siteName.slice(0, 1) : '锤'
|
||||
}}</span>
|
||||
<span class="mobile-logo">{{ siteStore.brandMark }}</span>
|
||||
<div>
|
||||
<div class="mobile-brand-title-row">
|
||||
<strong>{{ siteStore.siteName }}</strong>
|
||||
</div>
|
||||
<small>{{
|
||||
siteStore.isDistribution ? siteStore.storefrontText.tagline : '哈夫币租号'
|
||||
siteStore.hasCustomBrand ? siteStore.storefrontText.tagline : '哈夫币租号'
|
||||
}}</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -155,15 +155,13 @@ async function handleSupportClick() {
|
||||
alt="Site Logo"
|
||||
class="pc-brand-logo-img"
|
||||
/>
|
||||
<span v-else class="pc-brand-mark">{{
|
||||
siteStore.isDistribution ? siteStore.siteName.slice(0, 1) : '锤'
|
||||
}}</span>
|
||||
<span v-else class="pc-brand-mark">{{ siteStore.brandMark }}</span>
|
||||
<div class="pc-brand-info">
|
||||
<div class="pc-brand-title-row">
|
||||
<span class="pc-brand-text">{{ siteStore.siteName }}</span>
|
||||
</div>
|
||||
<small class="pc-brand-sub">{{
|
||||
siteStore.isDistribution ? siteStore.storefrontText.tagline : '哈夫币租号'
|
||||
siteStore.hasCustomBrand ? siteStore.storefrontText.tagline : '哈夫币租号'
|
||||
}}</small>
|
||||
</div>
|
||||
</RouterLink>
|
||||
|
||||
@@ -140,6 +140,27 @@ export interface DistributionSiteInfo {
|
||||
receive_cost_delta?: number
|
||||
}
|
||||
|
||||
export interface TenantSiteContext {
|
||||
mode: 'tenant'
|
||||
tenant_id: number
|
||||
tenant_code: string
|
||||
tenant_name: string
|
||||
host: string
|
||||
domain_type: string
|
||||
status: string
|
||||
profile: Record<string, unknown>
|
||||
features: Record<string, unknown>
|
||||
}
|
||||
|
||||
export function shouldProbeTenantContext(
|
||||
hostname: string,
|
||||
_querySite: string,
|
||||
_envCode: string
|
||||
): boolean {
|
||||
if (!hostname || hostname === 'localhost' || hostname === '127.0.0.1') return false
|
||||
return !hostname.endsWith('.localhost')
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前上下文生效的分销站点编码
|
||||
* 优先级:
|
||||
@@ -173,6 +194,10 @@ export const useDistributionSiteStore = defineStore('distributionSite', {
|
||||
return {
|
||||
siteCode: code,
|
||||
siteName: sessionStorage.getItem('hfb_site_name') || '大锤商行',
|
||||
tenantId: 0,
|
||||
tenantCode: '',
|
||||
siteMode: 'legacy' as 'legacy' | 'tenant',
|
||||
features: {} as Record<string, unknown>,
|
||||
domain: '',
|
||||
isDistribution: Boolean(code),
|
||||
displayAccountEnabled: true,
|
||||
@@ -192,10 +217,18 @@ export const useDistributionSiteStore = defineStore('distributionSite', {
|
||||
getters: {
|
||||
/** 品牌标识字符:分站取站名首字,主站沿用「锤」。 */
|
||||
brandMark(state): string {
|
||||
if (state.siteMode === 'tenant') return state.siteName.slice(0, 1) || '锤'
|
||||
return state.isDistribution && state.siteName ? state.siteName.slice(0, 1) : '锤'
|
||||
},
|
||||
isTenant(state): boolean {
|
||||
return state.siteMode === 'tenant'
|
||||
},
|
||||
hasCustomBrand(state): boolean {
|
||||
return state.siteMode === 'tenant' || state.isDistribution
|
||||
},
|
||||
/** 分站首页主标题:站名与主站联名。 */
|
||||
coBrandName(state): string {
|
||||
if (state.siteMode === 'tenant') return state.siteName || '大锤商行'
|
||||
return formatDistributionCoBrandName(state.siteName, state.isDistribution)
|
||||
},
|
||||
},
|
||||
@@ -212,6 +245,23 @@ export const useDistributionSiteStore = defineStore('distributionSite', {
|
||||
''
|
||||
).trim()
|
||||
|
||||
if (shouldProbeTenantContext(hostname, querySite, envCode)) {
|
||||
try {
|
||||
const { data } = await apiClient.get<ApiResponse<TenantSiteContext>>('/site/context', {
|
||||
silent: true,
|
||||
skipErrorHandler: true,
|
||||
})
|
||||
const info = data.data
|
||||
if (info?.mode === 'tenant' && info.status === 'active') {
|
||||
this.applyTenantContext(info)
|
||||
this.initialized = true
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// 当前域名不是经营租户时继续走历史分销站点识别。
|
||||
}
|
||||
}
|
||||
|
||||
// 1. 显式清除或重置为主站
|
||||
if (querySite === 'main' || querySite === 'clear' || querySite === '0') {
|
||||
this.resetToMainSite()
|
||||
@@ -262,6 +312,10 @@ export const useDistributionSiteStore = defineStore('distributionSite', {
|
||||
if (info && info.site_code && info.status === 'active') {
|
||||
this.siteCode = info.site_code
|
||||
this.siteName = info.site_name || info.site_code
|
||||
this.tenantId = 0
|
||||
this.tenantCode = ''
|
||||
this.siteMode = 'legacy'
|
||||
this.features = {}
|
||||
this.domain = info.domain || ''
|
||||
this.isDistribution = true
|
||||
this.displayAccountEnabled = info.display_account_enabled ?? true
|
||||
@@ -342,6 +396,10 @@ export const useDistributionSiteStore = defineStore('distributionSite', {
|
||||
resetToMainSite() {
|
||||
this.siteCode = ''
|
||||
this.siteName = '大锤商行'
|
||||
this.tenantId = 0
|
||||
this.tenantCode = ''
|
||||
this.siteMode = 'legacy'
|
||||
this.features = {}
|
||||
this.domain = ''
|
||||
this.isDistribution = false
|
||||
this.displayAccountEnabled = true
|
||||
@@ -360,5 +418,77 @@ export const useDistributionSiteStore = defineStore('distributionSite', {
|
||||
localStorage.removeItem('hfb_site_name')
|
||||
document.title = '大锤商行 - 官方租号平台'
|
||||
},
|
||||
|
||||
applyTenantContext(info: TenantSiteContext) {
|
||||
const profile = info.profile || {}
|
||||
this.tenantId = Number(info.tenant_id || 0)
|
||||
this.tenantCode = info.tenant_code || ''
|
||||
this.siteMode = 'tenant'
|
||||
this.features = info.features || {}
|
||||
this.siteCode = ''
|
||||
this.siteName = text(profile.site_name) || info.tenant_name || info.tenant_code
|
||||
this.domain = info.host || ''
|
||||
this.isDistribution = false
|
||||
this.displayAccountEnabled =
|
||||
typeof profile.display_account_enabled === 'boolean'
|
||||
? profile.display_account_enabled
|
||||
: true
|
||||
this.defaultSupportGroupId =
|
||||
typeof profile.default_support_group_id === 'number'
|
||||
? profile.default_support_group_id
|
||||
: null
|
||||
this.logoUrl = text(profile.logo_url)
|
||||
this.faviconUrl = text(profile.favicon_url)
|
||||
this.banners = parseJSONArray<DistributionBanner>(profile.banners_json)
|
||||
this.announcements = normalizeAnnouncements(
|
||||
parseJSONArray<unknown>(profile.announcements_json)
|
||||
)
|
||||
this.footerInfo = parseJSONObject<DistributionFooterInfo>(profile.footer_info_json)
|
||||
this.storefrontText = mergeStorefrontText(
|
||||
parseJSONObject<Partial<StorefrontText>>(profile.storefront_text_json)
|
||||
)
|
||||
this.receiveRatioDelta = Math.max(0, Number(profile.receive_ratio_delta || 0))
|
||||
this.receiveCostDelta = Math.max(0, Number(profile.receive_cost_delta || 0))
|
||||
|
||||
sessionStorage.removeItem('hfb_site_code')
|
||||
sessionStorage.removeItem('hfb_site_name')
|
||||
localStorage.removeItem('hfb_site_code')
|
||||
localStorage.removeItem('hfb_site_name')
|
||||
document.title = `${this.siteName} - 官方租号平台`
|
||||
this.applyFavicon()
|
||||
},
|
||||
|
||||
applyFavicon() {
|
||||
if (!this.faviconUrl || typeof document === 'undefined') return
|
||||
let link = document.querySelector("link[rel*='icon']") as HTMLLinkElement | null
|
||||
if (!link) {
|
||||
link = document.createElement('link')
|
||||
link.rel = 'icon'
|
||||
document.head.appendChild(link)
|
||||
}
|
||||
link.href = this.faviconUrl
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
function parseJSONArray<T>(value: unknown): T[] {
|
||||
if (Array.isArray(value)) return value as T[]
|
||||
if (typeof value !== 'string' || !value.trim()) return []
|
||||
try {
|
||||
const parsed = JSON.parse(value)
|
||||
return Array.isArray(parsed) ? parsed : []
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function parseJSONObject<T extends object>(value: unknown): T | null {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) return value as T
|
||||
if (typeof value !== 'string' || !value.trim()) return null
|
||||
try {
|
||||
const parsed = JSON.parse(value)
|
||||
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as T) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { shouldProbeTenantContext } from './distributionSite'
|
||||
|
||||
describe('shouldProbeTenantContext', () => {
|
||||
it('正式域名优先探测经营租户', () => {
|
||||
expect(shouldProbeTenantContext('zuhaox.com', '', '')).toBe(true)
|
||||
expect(shouldProbeTenantContext('hfb.example.com', '', '')).toBe(true)
|
||||
})
|
||||
|
||||
it('本地开发不主动探测,避免覆盖旧分销调试模式', () => {
|
||||
expect(shouldProbeTenantContext('localhost', '', '')).toBe(false)
|
||||
expect(shouldProbeTenantContext('127.0.0.1', '', '')).toBe(false)
|
||||
expect(shouldProbeTenantContext('site.localhost', '', '')).toBe(false)
|
||||
})
|
||||
|
||||
it('正式域名先识别经营租户,不能通过旧分站参数覆盖', () => {
|
||||
expect(shouldProbeTenantContext('zuhaox.com', 'branch_a', '')).toBe(true)
|
||||
expect(shouldProbeTenantContext('zuhaox.com', '', 'branch_b')).toBe(true)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user