package tenancy import ( "context" "encoding/json" "fmt" "gorm.io/datatypes" ) type contextKey struct{} type adminAllTenantsKey struct{} // WithAdminAllTenantScope 标记当前管理员拥有平台级全租户查看权限。 // 该标记只用于管理后台查询范围,不改变请求 Host 对应的经营租户上下文。 func WithAdminAllTenantScope(ctx context.Context) context.Context { return context.WithValue(ctx, adminAllTenantsKey{}, true) } func HasAdminAllTenantScope(ctx context.Context) bool { enabled, _ := ctx.Value(adminAllTenantsKey{}).(bool) return enabled } 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 IDFromContext(ctx context.Context) uint64 { scope, ok := FromContext(ctx) if !ok { return 0 } return scope.TenantID } // ScopeKey returns a stable cache scope suffix. An empty string keeps legacy // callers and tests on their existing unqualified keys. func ScopeKey(ctx context.Context) string { if tenantID := IDFromContext(ctx); tenantID > 0 { return fmt.Sprintf("tenant:%d", tenantID) } return "" } 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 }