feat(platform-ops): 增加平台只读统计接口与超管入口

This commit is contained in:
yml
2026-11-15 21:31:12 +08:00
parent d494746839
commit 5ba893cfde
19 changed files with 752 additions and 3 deletions
+1
View File
@@ -24,6 +24,7 @@ JWT_SECRET=change-me
# 经营租户域名;本地留空时通过 X-Tenant-Code 或旧分销站点方式调试。
CADDY_DOMAIN=
TENANT_JIEYOU_DOMAIN=
OPS_DOMAIN=ops.localhost
# 前端后台页面入口;本地默认 /admin,生产建议改成不公开的单段路径。
VITE_ADMIN_BASE_PATH=/admin
+2
View File
@@ -7,6 +7,8 @@ CADDY_DOMAIN=hfb.221329.cc.cd
CADDY_EMAIL=admin@example.com
# 解忧商行前台域名;未启用解忧时留空。
TENANT_JIEYOU_DOMAIN=zuhaox.com
# 平台运营统计后台域名;留空时生产环境按 ops.<CADDY_DOMAIN> 推导。
OPS_DOMAIN=
# 选号网(hfb_show)独立域名,与主站同机;不部署选号网可留空。
# CADDY_SHOW_DOMAIN=show.example.com
# 选号网源码目录(相对 hfb_sys 根或绝对路径),默认 ../hfb_show
+19 -2
View File
@@ -26,6 +26,7 @@ type Config struct {
BootstrapAdminNickname string
PrimaryDomain string
TenantJieyouDomain string
OpsDomain string
Storage StorageConfig
StorageMirror StorageConfig
SMS SMSConfig
@@ -85,8 +86,10 @@ type DatabaseConfig struct {
}
func Load() Config {
appEnv := getEnv("APP_ENV", "development")
primaryDomain := strings.TrimSpace(getEnv("CADDY_DOMAIN", ""))
return Config{
AppEnv: getEnv("APP_ENV", "development"),
AppEnv: appEnv,
AppAddr: getEnv("APP_ADDR", ":18088"),
MySQLDSN: getEnv("MYSQL_DSN", "hfb:secret@tcp(127.0.0.1:13306)/hfb_sys?charset=utf8mb4&parseTime=True&loc=Local"),
RedisAddr: getEnv("REDIS_ADDR", "127.0.0.1:16379"),
@@ -104,8 +107,9 @@ func Load() Config {
BootstrapAdminUsername: getEnv("ADMIN_BOOTSTRAP_USERNAME", ""),
BootstrapAdminPassword: getEnv("ADMIN_BOOTSTRAP_PASSWORD", ""),
BootstrapAdminNickname: getEnv("ADMIN_BOOTSTRAP_NICKNAME", "超级管理员"),
PrimaryDomain: strings.TrimSpace(getEnv("CADDY_DOMAIN", "")),
PrimaryDomain: primaryDomain,
TenantJieyouDomain: strings.TrimSpace(getEnv("TENANT_JIEYOU_DOMAIN", "")),
OpsDomain: opsDomain(appEnv, getEnv("OPS_DOMAIN", ""), primaryDomain),
Storage: StorageConfig{
Endpoint: getEnv("STORAGE_ENDPOINT", "http://localhost:19090"),
Bucket: getEnv("STORAGE_BUCKET", "hfb-sys"),
@@ -159,6 +163,19 @@ func Load() Config {
}
}
func opsDomain(appEnv string, value string, primaryDomain string) string {
if domain := strings.TrimSpace(value); domain != "" {
return domain
}
if strings.EqualFold(strings.TrimSpace(appEnv), "production") {
if primary := strings.TrimSpace(primaryDomain); primary != "" {
return "ops." + primary
}
return ""
}
return "ops.localhost"
}
func (c Config) ValidateProductionSecurity() error {
if !IsProductionEnv(c.AppEnv) {
return nil
+22
View File
@@ -26,6 +26,28 @@ func TestIsProductionEnv(t *testing.T) {
}
}
func TestOpsDomain(t *testing.T) {
cases := []struct {
name string
appEnv string
value string
primary string
expected string
}{
{name: "开发默认", appEnv: "development", expected: "ops.localhost"},
{name: "生产按主域推导", appEnv: "production", primary: "hao858.com", expected: "ops.hao858.com"},
{name: "显式覆盖", appEnv: "production", value: "ops.example.com", primary: "hao858.com", expected: "ops.example.com"},
{name: "生产无主域", appEnv: "production", expected: ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := opsDomain(tc.appEnv, tc.value, tc.primary); got != tc.expected {
t.Fatalf("opsDomain() = %q, want %q", got, tc.expected)
}
})
}
}
func TestLoadDatabaseConfigFromEnvironment(t *testing.T) {
t.Setenv("DATABASE_MAX_OPEN_CONNS", "80")
t.Setenv("DATABASE_MAX_IDLE_CONNS", "16")
@@ -0,0 +1,67 @@
package middleware
import (
"strings"
"hfb_sys/backend/internal/platformscope"
"hfb_sys/backend/internal/sitecode"
"hfb_sys/backend/pkg/response"
"github.com/gin-gonic/gin"
)
func PlatformOpsContext(domain string) gin.HandlerFunc {
expected := strings.ToLower(sitecode.ExtractHost(domain))
return func(c *gin.Context) {
if expected != "" && sitecode.ExtractHost(c.Request.Host) == expected {
c.Request = c.Request.WithContext(platformscope.WithScope(c.Request.Context()))
}
c.Next()
}
}
func RequirePlatformOps() gin.HandlerFunc {
return func(c *gin.Context) {
if !platformscope.IsScope(c.Request.Context()) {
response.Forbidden(c, "当前入口不是平台运营后台")
c.Abort()
return
}
c.Next()
}
}
// PlatformOpsReadOnlyGuard 保证平台运营域名只能访问登录、身份和只读统计接口。
func PlatformOpsReadOnlyGuard() gin.HandlerFunc {
allowedPrefixes := []string{
"/api/admin/auth/",
"/api/admin/platform/",
}
allowedPaths := map[string]bool{
"/api/admin/me": true,
"/api/admin/admin-users/me/password": true,
}
return func(c *gin.Context) {
if !platformscope.IsScope(c.Request.Context()) {
c.Next()
return
}
path := c.Request.URL.Path
if allowedPaths[path] {
c.Next()
return
}
for _, prefix := range allowedPrefixes {
if strings.HasPrefix(path, prefix) {
c.Next()
return
}
}
if strings.HasPrefix(path, "/api/admin/") {
response.Forbidden(c, "平台运营后台仅提供统计查看")
c.Abort()
return
}
c.Next()
}
}
@@ -0,0 +1,50 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"hfb_sys/backend/internal/platformscope"
"github.com/gin-gonic/gin"
)
func TestPlatformOpsContextAndReadOnlyGuard(t *testing.T) {
gin.SetMode(gin.TestMode)
engine := gin.New()
engine.Use(PlatformOpsContext("ops.localhost"), PlatformOpsReadOnlyGuard())
engine.GET("/probe", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"platform": platformscope.IsScope(c.Request.Context())})
})
engine.GET("/api/admin/platform/overview", func(c *gin.Context) {
c.Status(http.StatusNoContent)
})
engine.GET("/api/admin/users", func(c *gin.Context) {
c.Status(http.StatusNoContent)
})
req := httptest.NewRequest(http.MethodGet, "/probe", nil)
req.Host = "ops.localhost:5189"
rec := httptest.NewRecorder()
engine.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || rec.Body.String() != `{"platform":true}` {
t.Fatalf("platform context response = %d %s", rec.Code, rec.Body.String())
}
req = httptest.NewRequest(http.MethodGet, "/api/admin/platform/overview", nil)
req.Host = "ops.localhost:5189"
rec = httptest.NewRecorder()
engine.ServeHTTP(rec, req)
if rec.Code != http.StatusNoContent {
t.Fatalf("platform overview status = %d", rec.Code)
}
req = httptest.NewRequest(http.MethodGet, "/api/admin/users", nil)
req.Host = "ops.localhost:5189"
rec = httptest.NewRecorder()
engine.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("platform non-readonly route status = %d, want 403", rec.Code)
}
}
@@ -6,6 +6,7 @@ import (
"sync"
"time"
"hfb_sys/backend/internal/platformscope"
"hfb_sys/backend/internal/sitecode"
"hfb_sys/backend/internal/tenancy"
@@ -66,6 +67,10 @@ func SiteDomainFallback(resolver SiteDomainResolver, logger *zap.Logger) gin.Han
}
cache := newSiteDomainCache()
return func(c *gin.Context) {
if platformscope.IsScope(c.Request.Context()) {
c.Next()
return
}
if _, ok := tenancy.FromContext(c.Request.Context()); ok || sitecode.HasTenantScope(c.Request.Context()) {
c.Next()
return
@@ -5,6 +5,7 @@ import (
"strings"
"hfb_sys/backend/internal/config"
"hfb_sys/backend/internal/platformscope"
"hfb_sys/backend/internal/sitecode"
"hfb_sys/backend/internal/tenancy"
"hfb_sys/backend/pkg/response"
@@ -34,6 +35,10 @@ func TenantContext(resolver TenantResolver, appEnv string, logger *zap.Logger, d
defaultTenantCode = strings.TrimSpace(defaultTenantCodes[0])
}
return func(c *gin.Context) {
if platformscope.IsScope(c.Request.Context()) {
c.Next()
return
}
var (
scope *tenancy.Scope
err error
@@ -13,6 +13,7 @@ import (
"hfb_sys/backend/internal/logging"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/auth"
"hfb_sys/backend/internal/platformscope"
"hfb_sys/backend/internal/tenancy"
"github.com/redis/go-redis/v9"
@@ -76,6 +77,9 @@ func (r *Repository) Login(ctx context.Context, username string, password string
return LoginResult{}, ErrInvalidCredential
}
allowed, err := r.adminHasTenantAccess(ctx, admin.ID)
if platformscope.IsScope(ctx) {
allowed, err = r.adminHasPlatformAccess(ctx, admin.ID)
}
if err != nil {
return LoginResult{}, err
}
@@ -120,6 +124,9 @@ func (r *Repository) FindActiveForToken(ctx context.Context, id uint64, tokenVer
return nil, newTokenVersionMismatchError(tokenVersion, admin.TokenVersion)
}
allowed, err := r.adminHasTenantAccess(ctx, admin.ID)
if platformscope.IsScope(ctx) {
allowed, err = r.adminHasPlatformAccess(ctx, admin.ID)
}
if err != nil {
return nil, newTokenDependencyError(err)
}
@@ -226,7 +233,9 @@ func (r *Repository) loadRolesAndPerms(ctx context.Context, dto *AdminDTO) {
roleQuery := r.db.WithContext(ctx).Table("roles").
Joins("JOIN admin_user_roles aur ON aur.role_id = roles.id").
Where("aur.admin_user_id = ?", dto.ID)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
if platformscope.IsScope(ctx) {
roleQuery = roleQuery.Where("roles.code = ?", "super_admin")
} else if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
roleQuery = roleQuery.Where("(aur.tenant_id = ? OR roles.code = ?)", tenantID, "super_admin")
}
roleQuery.Find(&roles)
@@ -331,12 +340,24 @@ func scopedAuthKey(tenantID uint64, base string) string {
func adminPermissionCacheKey(ctx context.Context, adminID uint64) string {
key := fmt.Sprintf("admin:perms:%d", adminID)
if platformscope.IsScope(ctx) {
return key + ":platform"
}
if scope := tenancy.ScopeKey(ctx); scope != "" {
key += ":" + scope
}
return key
}
func (r *Repository) adminHasPlatformAccess(ctx context.Context, adminID uint64) (bool, error) {
var count int64
err := r.db.WithContext(ctx).Table("admin_user_roles AS aur").
Joins("JOIN roles AS r ON r.id = aur.role_id").
Where("aur.admin_user_id = ? AND r.code = ?", adminID, "super_admin").
Count(&count).Error
return count > 0, err
}
func (r *Repository) adminHasTenantAccess(ctx context.Context, adminID uint64) (bool, error) {
tenantID := tenancy.IDFromContext(ctx)
if tenantID == 0 {
@@ -7,6 +7,7 @@ import (
"hfb_sys/backend/internal/database"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/platformscope"
"hfb_sys/backend/internal/tenancy"
)
@@ -14,6 +15,50 @@ func adminTenantContext(tenantID uint64) context.Context {
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
}
func TestPlatformOpsOnlyAllowsSuperAdmin(t *testing.T) {
db := database.NewTestDB()
roles := []model.Role{
{Code: "super_admin", Name: "超级管理员"},
{Code: "cs", Name: "客服"},
}
if err := db.Create(&roles).Error; err != nil {
t.Fatal(err)
}
tenantAdmin := model.AdminUser{Username: "tenant-cs-platform", PasswordHash: "x", Status: "active", TokenVersion: 1}
superAdmin := model.AdminUser{Username: "root-platform", PasswordHash: "x", Status: "active", TokenVersion: 1}
if err := db.Create(&tenantAdmin).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&superAdmin).Error; err != nil {
t.Fatal(err)
}
for _, assignment := range []model.AdminUserRole{
{AdminID: tenantAdmin.ID, RoleID: roles[1].ID, TenantID: 101},
{AdminID: superAdmin.ID, RoleID: roles[0].ID, TenantID: 0},
} {
if err := db.Create(&assignment).Error; err != nil {
t.Fatal(err)
}
}
repo := NewRepository(db, nil, nil)
ctx := platformscope.WithScope(context.Background())
if _, err := repo.FindActiveForToken(ctx, tenantAdmin.ID, 1); !errors.Is(err, ErrAdminNotFound) {
t.Fatalf("tenant admin platform token error = %v, want ErrAdminNotFound", err)
}
if _, err := repo.FindActiveForToken(ctx, superAdmin.ID, 1); err != nil {
t.Fatalf("super admin platform token: %v", err)
}
dto, err := repo.FindByID(ctx, superAdmin.ID)
if err != nil {
t.Fatal(err)
}
if len(dto.Roles) != 1 || dto.Roles[0].Code != "super_admin" ||
len(dto.Permissions) != 1 || dto.Permissions[0] != "*" {
t.Fatalf("platform super admin = %+v", dto)
}
}
func TestAdminAccessAndPermissionsAreScopedByTenant(t *testing.T) {
db := database.NewTestDB()
roles := []model.Role{
@@ -0,0 +1,59 @@
package platformops
import "time"
type OverviewDTO struct {
GeneratedAt time.Time `json:"generated_at"`
Totals TotalsDTO `json:"totals"`
Sites []SiteStatsDTO `json:"sites"`
Trend []TrendPointDTO `json:"trend"`
}
type TotalsDTO struct {
TenantCount int64 `json:"tenant_count" gorm:"column:tenant_count"`
ActiveTenantCount int64 `json:"active_tenant_count" gorm:"column:active_tenant_count"`
UserCount int64 `json:"user_count" gorm:"column:user_count"`
VerifiedUsers int64 `json:"verified_users" gorm:"column:verified_users"`
TodayNewUsers int64 `json:"today_new_users" gorm:"column:today_new_users"`
TotalListings int64 `json:"total_listings" gorm:"column:total_listings"`
PublishedListings int64 `json:"published_listings" gorm:"column:published_listings"`
TodayNewListings int64 `json:"today_new_listings" gorm:"column:today_new_listings"`
PendingReviews int64 `json:"pending_reviews" gorm:"column:pending_reviews"`
TotalOrders int64 `json:"total_orders" gorm:"column:total_orders"`
PaidOrders int64 `json:"paid_orders" gorm:"column:paid_orders"`
RentingOrders int64 `json:"renting_orders" gorm:"column:renting_orders"`
TodayOrders int64 `json:"today_orders" gorm:"column:today_orders"`
TodayGMVCent int64 `json:"today_gmv_cent" gorm:"column:today_gmv_cent"`
PaidGMVCent int64 `json:"paid_gmv_cent" gorm:"column:paid_gmv_cent"`
PendingDisputes int64 `json:"pending_disputes" gorm:"column:pending_disputes"`
PendingHandoffs int64 `json:"pending_handoffs" gorm:"column:pending_handoffs"`
PendingReturns int64 `json:"pending_returns" gorm:"column:pending_returns"`
}
type SiteStatsDTO struct {
TenantID uint64 `json:"tenant_id" gorm:"column:tenant_id"`
TenantCode string `json:"tenant_code"`
TenantName string `json:"tenant_name"`
Status string `json:"status"`
UserCount int64 `json:"user_count" gorm:"column:user_count"`
VerifiedUsers int64 `json:"verified_users" gorm:"column:verified_users"`
TodayNewUsers int64 `json:"today_new_users" gorm:"column:today_new_users"`
TotalListings int64 `json:"total_listings" gorm:"column:total_listings"`
PublishedListings int64 `json:"published_listings" gorm:"column:published_listings"`
PendingReviews int64 `json:"pending_reviews" gorm:"column:pending_reviews"`
BuyerOrders int64 `json:"buyer_orders" gorm:"column:buyer_orders"`
BuyerGMVCent int64 `json:"buyer_gmv_cent" gorm:"column:buyer_gmv_cent"`
SourceOrders int64 `json:"source_orders" gorm:"column:source_orders"`
SourceAmountCent int64 `json:"source_amount_cent" gorm:"column:source_amount_cent"`
RentingOrders int64 `json:"renting_orders" gorm:"column:renting_orders"`
TodayOrders int64 `json:"today_orders" gorm:"column:today_orders"`
TodayGMVCent int64 `json:"today_gmv_cent" gorm:"column:today_gmv_cent"`
}
type TrendPointDTO struct {
Date string `json:"date"`
NewUsers int64 `json:"new_users"`
NewListings int64 `json:"new_listings"`
Orders int64 `json:"orders"`
PaidGMVCent int64 `json:"paid_gmv_cent"`
}
@@ -0,0 +1,32 @@
package platformops
import (
"errors"
"net/http"
"hfb_sys/backend/pkg/response"
"github.com/gin-gonic/gin"
)
type Handler struct {
service *Service
}
func NewHandler(service *Service) *Handler {
return &Handler{service: service}
}
func (h *Handler) Overview(c *gin.Context) {
item, err := h.service.Overview(c.Request.Context())
if err != nil {
response.RecordError(c, err)
if errors.Is(err, ErrDependencyUnavailable) {
response.ServiceUnavailable(c, "数据库未连接")
return
}
response.Error(c, http.StatusInternalServerError, "platform_overview_failed", "平台统计加载失败")
return
}
response.OK(c, item)
}
@@ -0,0 +1,237 @@
package platformops
import (
"context"
"time"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/timeutil"
"gorm.io/gorm"
)
const paidOrderCondition = "status NOT IN ('pending_payment', 'cancelled', 'closed')"
type Repository struct {
db *gorm.DB
}
func NewRepository(db *gorm.DB) *Repository {
return &Repository{db: db}
}
func (r *Repository) Overview(ctx context.Context) (*OverviewDTO, error) {
now := timeutil.ShanghaiNow()
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, timeutil.ShanghaiLocation())
db := r.db.WithContext(ctx)
var tenants []model.Tenant
if err := db.Order("id ASC").Find(&tenants).Error; err != nil {
return nil, err
}
totals, err := r.totals(db, today)
if err != nil {
return nil, err
}
totals.TenantCount = int64(len(tenants))
for _, tenant := range tenants {
if tenant.Status == "active" {
totals.ActiveTenantCount++
}
}
sites := make([]SiteStatsDTO, 0, len(tenants))
for _, tenant := range tenants {
site, err := r.siteStats(db, tenant, today)
if err != nil {
return nil, err
}
sites = append(sites, site)
}
trend, err := r.trend(db, now, 7)
if err != nil {
return nil, err
}
return &OverviewDTO{
GeneratedAt: now,
Totals: *totals,
Sites: sites,
Trend: trend,
}, nil
}
func (r *Repository) totals(db *gorm.DB, today time.Time) (*TotalsDTO, error) {
result := &TotalsDTO{}
if err := db.Table("users").
Select("COUNT(*) AS user_count, COALESCE(SUM(realname_status = 'verified'), 0) AS verified_users, COALESCE(SUM(created_at >= ?), 0) AS today_new_users", today).
Row().
Scan(&result.UserCount, &result.VerifiedUsers, &result.TodayNewUsers); err != nil {
return nil, err
}
if err := db.Table("rental_listings").
Select(`COUNT(*) AS total_listings,
COALESCE(SUM(status = 'published' AND review_status = 'approved'), 0) AS published_listings,
COALESCE(SUM(created_at >= ?), 0) AS today_new_listings,
COALESCE(SUM(review_status = 'pending' AND status <> 'offline'), 0) AS pending_reviews`, today).
Row().
Scan(&result.TotalListings, &result.PublishedListings, &result.TodayNewListings, &result.PendingReviews); err != nil {
return nil, err
}
var orderStats struct {
TotalOrders int64 `gorm:"column:total_orders"`
PaidOrders int64 `gorm:"column:paid_orders"`
RentingOrders int64 `gorm:"column:renting_orders"`
TodayOrders int64 `gorm:"column:today_orders"`
PaidGMVCent int64 `gorm:"column:paid_gmv_cent"`
TodayGMVCent int64 `gorm:"column:today_gmv_cent"`
}
if err := db.Table("rental_orders AS o").
Select(`COUNT(*) AS total_orders,
COALESCE(SUM(o.`+paidOrderCondition+`), 0) AS paid_orders,
COALESCE(SUM(o.status = 'renting'), 0) AS renting_orders,
COALESCE(SUM(o.created_at >= ?), 0) AS today_orders,
COALESCE(SUM(CASE WHEN o.`+paidOrderCondition+` THEN o.rent_amount_cent ELSE 0 END), 0) AS paid_gmv_cent,
COALESCE(SUM(CASE WHEN o.`+paidOrderCondition+` AND o.created_at >= ? THEN o.rent_amount_cent ELSE 0 END), 0) AS today_gmv_cent`, today, today).
Scan(&orderStats).Error; err != nil {
return nil, err
}
result.TotalOrders = orderStats.TotalOrders
result.PaidOrders = orderStats.PaidOrders
result.RentingOrders = orderStats.RentingOrders
result.TodayOrders = orderStats.TodayOrders
result.PaidGMVCent = orderStats.PaidGMVCent
result.TodayGMVCent = orderStats.TodayGMVCent
if err := db.Table("disputes AS d").Where("d.status IN ?", []string{"open", "processing"}).Count(&result.PendingDisputes).Error; err != nil {
return nil, err
}
if err := db.Table("rental_orders AS o").
Where("o.status = ? AND o.handoff_status IN ?", "pending_handoff", []string{"pending_owner", "pending_renter_confirm"}).
Count(&result.PendingHandoffs).Error; err != nil {
return nil, err
}
if err := db.Table("rental_orders AS o").
Where("o.status IN ?", []string{"pending_checkout_confirm", "pending_checkout_accept"}).
Count(&result.PendingReturns).Error; err != nil {
return nil, err
}
return result, nil
}
func (r *Repository) siteStats(db *gorm.DB, tenant model.Tenant, today time.Time) (SiteStatsDTO, error) {
result := SiteStatsDTO{
TenantID: tenant.ID,
TenantCode: tenant.Code,
TenantName: tenant.Name,
Status: tenant.Status,
}
if err := db.Table("users").Where("tenant_id = ?", tenant.ID).
Select("COUNT(*) AS user_count, COALESCE(SUM(realname_status = 'verified'), 0) AS verified_users, COALESCE(SUM(created_at >= ?), 0) AS today_new_users", today).
Row().
Scan(&result.UserCount, &result.VerifiedUsers, &result.TodayNewUsers); err != nil {
return result, err
}
if err := db.Table("rental_listings").Where("source_tenant_id = ?", tenant.ID).
Select(`COUNT(*) AS total_listings,
COALESCE(SUM(status = 'published' AND review_status = 'approved'), 0) AS published_listings,
COALESCE(SUM(review_status = 'pending' AND status <> 'offline'), 0) AS pending_reviews`).
Row().
Scan(&result.TotalListings, &result.PublishedListings, &result.PendingReviews); err != nil {
return result, err
}
var orderStats struct {
BuyerOrders int64 `gorm:"column:buyer_orders"`
BuyerGMVCent int64 `gorm:"column:buyer_gmv_cent"`
SourceOrders int64 `gorm:"column:source_orders"`
SourceAmountCent int64 `gorm:"column:source_amount_cent"`
RentingOrders int64 `gorm:"column:renting_orders"`
TodayOrders int64 `gorm:"column:today_orders"`
TodayGMVCent int64 `gorm:"column:today_gmv_cent"`
}
if err := db.Table("rental_orders AS o").
Select(`COALESCE(SUM(o.buyer_tenant_id = ? AND o.`+paidOrderCondition+`), 0) AS buyer_orders,
COALESCE(SUM(CASE WHEN o.buyer_tenant_id = ? AND o.`+paidOrderCondition+` THEN o.rent_amount_cent ELSE 0 END), 0) AS buyer_gmv_cent,
COALESCE(SUM(o.source_tenant_id = ? AND o.`+paidOrderCondition+`), 0) AS source_orders,
COALESCE(SUM(CASE WHEN o.source_tenant_id = ? AND o.`+paidOrderCondition+` THEN o.source_amount_cent ELSE 0 END), 0) AS source_amount_cent,
COALESCE(SUM((o.buyer_tenant_id = ? OR o.source_tenant_id = ?) AND o.status = 'renting'), 0) AS renting_orders,
COALESCE(SUM(o.buyer_tenant_id = ? AND o.`+paidOrderCondition+` AND o.created_at >= ?), 0) AS today_orders,
COALESCE(SUM(CASE WHEN o.buyer_tenant_id = ? AND o.`+paidOrderCondition+` AND o.created_at >= ? THEN o.rent_amount_cent ELSE 0 END), 0) AS today_gmv_cent`,
tenant.ID, tenant.ID, tenant.ID, tenant.ID, tenant.ID, tenant.ID, tenant.ID, today, tenant.ID, today).
Scan(&orderStats).Error; err != nil {
return result, err
}
result.BuyerOrders = orderStats.BuyerOrders
result.BuyerGMVCent = orderStats.BuyerGMVCent
result.SourceOrders = orderStats.SourceOrders
result.SourceAmountCent = orderStats.SourceAmountCent
result.RentingOrders = orderStats.RentingOrders
result.TodayOrders = orderStats.TodayOrders
result.TodayGMVCent = orderStats.TodayGMVCent
return result, nil
}
func (r *Repository) trend(db *gorm.DB, now time.Time, days int) ([]TrendPointDTO, error) {
loc := timeutil.ShanghaiLocation()
end := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc).AddDate(0, 0, 1)
start := end.AddDate(0, 0, -days)
type row struct {
Date string `gorm:"column:date"`
Value int64 `gorm:"column:value"`
AmountCent int64 `gorm:"column:amount_cent"`
}
users := map[string]int64{}
var userRows []row
if err := db.Table("users").
Select("DATE(created_at) AS date, COUNT(*) AS value").
Where("created_at >= ? AND created_at < ?", start, end).
Group("DATE(created_at)").Scan(&userRows).Error; err != nil {
return nil, err
}
for _, item := range userRows {
users[item.Date] = item.Value
}
listings := map[string]int64{}
var listingRows []row
if err := db.Table("rental_listings").
Select("DATE(created_at) AS date, COUNT(*) AS value").
Where("created_at >= ? AND created_at < ?", start, end).
Group("DATE(created_at)").Scan(&listingRows).Error; err != nil {
return nil, err
}
for _, item := range listingRows {
listings[item.Date] = item.Value
}
orders := map[string]row{}
var orderRows []row
if err := db.Table("rental_orders").
Select(`DATE(created_at) AS date,
COALESCE(SUM(`+paidOrderCondition+`), 0) AS value,
COALESCE(SUM(CASE WHEN `+paidOrderCondition+` THEN rent_amount_cent ELSE 0 END), 0) AS amount_cent`).
Where("created_at >= ? AND created_at < ?", start, end).
Group("DATE(created_at)").Scan(&orderRows).Error; err != nil {
return nil, err
}
for _, item := range orderRows {
orders[item.Date] = item
}
result := make([]TrendPointDTO, 0, days)
for date := start; date.Before(end); date = date.AddDate(0, 0, 1) {
key := date.Format("2006-01-02")
order := orders[key]
result = append(result, TrendPointDTO{
Date: key,
NewUsers: users[key],
NewListings: listings[key],
Orders: order.Value,
PaidGMVCent: order.AmountCent,
})
}
return result, nil
}
@@ -0,0 +1,109 @@
package platformops
import (
"testing"
"hfb_sys/backend/internal/database"
"hfb_sys/backend/internal/model"
)
func TestOverviewAggregatesAllTenantsAndSites(t *testing.T) {
db := database.NewTestDB()
tenants := []model.Tenant{
{Code: "tenant_a", Name: "A站", Status: "active"},
{Code: "tenant_b", Name: "B站", Status: "active"},
}
if err := db.Create(&tenants).Error; err != nil {
t.Fatal(err)
}
users := []model.User{
{TenantID: tenants[0].ID, Phone: "13100000101", Status: "active", RealnameStatus: "verified"},
{TenantID: tenants[0].ID, Phone: "13100000102", Status: "active"},
{TenantID: tenants[1].ID, Phone: "13100000201", Status: "active", RealnameStatus: "verified"},
{TenantID: tenants[1].ID, Phone: "13100000202", Status: "active"},
}
if err := db.Create(&users).Error; err != nil {
t.Fatal(err)
}
for index, tenant := range tenants {
account := model.GameAccount{
SourceTenantID: tenant.ID,
OwnerID: users[index*2].ID,
GameName: "delta_force",
ServerRegion: "国服",
LoginPlatform: "QQ",
Title: tenant.Name + "账号",
Status: "published",
}
if err := db.Create(&account).Error; err != nil {
t.Fatal(err)
}
listing := model.RentalListing{
SourceTenantID: tenant.ID,
ListingNo: "OPS-" + tenant.Code,
AccountID: account.ID,
OwnerID: users[index*2].ID,
Status: "published",
ReviewStatus: "approved",
PriceCent: 1000,
}
if err := db.Create(&listing).Error; err != nil {
t.Fatal(err)
}
}
orders := []model.RentalOrder{
{
OrderNo: "OPS-ORDER-1",
BuyerTenantID: tenants[0].ID,
SourceTenantID: tenants[1].ID,
PaymentTenantID: tenants[0].ID,
RenterID: users[0].ID,
OwnerID: users[2].ID,
Status: "completed",
RentAmountCent: 1000,
SourceAmountCent: 800,
},
{
OrderNo: "OPS-ORDER-2",
BuyerTenantID: tenants[1].ID,
SourceTenantID: tenants[0].ID,
PaymentTenantID: tenants[1].ID,
RenterID: users[2].ID,
OwnerID: users[0].ID,
Status: "pending_payment",
RentAmountCent: 2000,
SourceAmountCent: 1600,
},
}
if err := db.Create(&orders).Error; err != nil {
t.Fatal(err)
}
var userCount int64
if err := db.Model(&model.User{}).Count(&userCount).Error; err != nil || userCount != 4 {
t.Fatalf("seeded users = %d, err=%v", userCount, err)
}
overview, err := NewRepository(db).Overview(t.Context())
if err != nil {
t.Fatal(err)
}
if overview.Totals.TenantCount != 2 || overview.Totals.UserCount != 4 ||
overview.Totals.VerifiedUsers != 2 || overview.Totals.TotalListings != 2 {
t.Fatalf("overview totals = %+v", overview.Totals)
}
if overview.Totals.TotalOrders != 2 || overview.Totals.PaidOrders != 1 ||
overview.Totals.PaidGMVCent != 1000 {
t.Fatalf("overview order totals = %+v", overview.Totals)
}
if len(overview.Sites) != 2 || len(overview.Trend) != 7 {
t.Fatalf("sites=%d trend=%d", len(overview.Sites), len(overview.Trend))
}
if overview.Sites[0].UserCount != 2 || overview.Sites[0].BuyerOrders != 1 ||
overview.Sites[0].SourceOrders != 0 {
t.Fatalf("site A stats = %+v", overview.Sites[0])
}
if overview.Sites[1].UserCount != 2 || overview.Sites[1].BuyerOrders != 0 ||
overview.Sites[1].SourceOrders != 1 {
t.Fatalf("site B stats = %+v", overview.Sites[1])
}
}
@@ -0,0 +1,23 @@
package platformops
import (
"context"
"errors"
)
var ErrDependencyUnavailable = errors.New("platform ops dependency unavailable")
type Service struct {
repo *Repository
}
func NewService(repo *Repository) *Service {
return &Service{repo: repo}
}
func (s *Service) Overview(ctx context.Context) (*OverviewDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.Overview(ctx)
}
+14
View File
@@ -0,0 +1,14 @@
package platformscope
import "context"
type contextKey struct{}
func WithScope(ctx context.Context) context.Context {
return context.WithValue(ctx, contextKey{}, true)
}
func IsScope(ctx context.Context) bool {
enabled, _ := ctx.Value(contextKey{}).(bool)
return enabled
}
+14
View File
@@ -36,6 +36,7 @@ import (
"hfb_sys/backend/internal/modules/paymentaccount"
"hfb_sys/backend/internal/modules/paymentconfig"
"hfb_sys/backend/internal/modules/pickup"
"hfb_sys/backend/internal/modules/platformops"
"hfb_sys/backend/internal/modules/pointsmall"
"hfb_sys/backend/internal/modules/qualityowner"
"hfb_sys/backend/internal/modules/realname"
@@ -112,6 +113,11 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
}
adminDashboardService := admindashboard.NewService(adminDashboardRepo)
adminDashboardHandler := admindashboard.NewHandler(adminDashboardService)
var platformOpsRepo *platformops.Repository
if deps.DB != nil {
platformOpsRepo = platformops.NewRepository(deps.DB)
}
platformOpsHandler := platformops.NewHandler(platformops.NewService(platformOpsRepo))
var manualEntryRepo *csmanualentry.Repository
if deps.DB != nil {
manualEntryRepo = csmanualentry.NewRepository(deps.DB)
@@ -357,6 +363,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
}
}
// 先识别经营租户,再兼容旧分销站点。经营租户识别成功后,后续旧分销参数和域名兜底均不生效。
engine.Use(middleware.PlatformOpsContext(cfg.OpsDomain))
if tenantRepo != nil {
engine.Use(middleware.TenantContext(tenantRepo, cfg.AppEnv, logger, "dachui"))
}
@@ -365,6 +372,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
engine.Use(middleware.SiteDomainFallback(distributionRepo, logger))
}
engine.Use(middleware.BlockTenantLegacyDistributionAdmin())
engine.Use(middleware.PlatformOpsReadOnlyGuard())
distributionHandler := distribution.NewHandler(distributionService)
if invitationHandler != nil && distributionService != nil {
invitationHandler.SetSiteScoper(distributionService)
@@ -771,6 +779,12 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
adminRoutes.GET("/me", adminAuthHandler.Me)
adminRoutes.PUT("/me/support-status", adminAuthHandler.UpdateSupportStatus)
adminRoutes.POST("/auth/logout", adminAuthHandler.Logout)
adminRoutes.GET(
"/platform/overview",
middleware.RequirePlatformOps(),
requirePerm("dashboard:view"),
platformOpsHandler.Overview,
)
adminRoutes.GET("/distribution/auth/me", distributionHandler.Me)
adminRoutes.POST("/distribution/auth/logout", distributionHandler.Logout)
adminRoutes.POST("/files/upload", fileHandler.Upload)
+25
View File
@@ -119,6 +119,31 @@ distribution.{$CADDY_DOMAIN} {
}
}
# 平台运营只读统计后台:仅平台超级管理员登录。
ops.{$CADDY_DOMAIN} {
encode zstd gzip
import public_api
header {
Strict-Transport-Security "max-age=31536000"
X-Content-Type-Options "nosniff"
X-Frame-Options "DENY"
Referrer-Policy "strict-origin-when-cross-origin"
Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' https: data: blob:; font-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; form-action 'self'"
}
@ops_admin path {$ADMIN_BASE_PATH:/manage-7x9k2p} {$ADMIN_BASE_PATH:/manage-7x9k2p}/*
handle @ops_admin {
root * /srv/dist
try_files {path} /index.html
file_server
}
handle {
respond 404
}
}
# 选号网(hfb_show):仅当 CADDY_SHOW_DOMAIN 有值时由部署脚本启用 conf.d/show.caddy。
# 未配置时 conf.d 为空,不影响主站。
import /etc/caddy/conf.d/*.caddy
+1
View File
@@ -719,6 +719,7 @@ main() {
fi
log_success "部署完成:$(public_url)"
log_success "平台运营统计后台:https://ops.$(require_env CADDY_DOMAIN)"
if [[ -n "$(env_value CADDY_SHOW_DOMAIN || true)" ]]; then
log_success "选号网:https://$(env_value CADDY_SHOW_DOMAIN)"
fi