feat(platform-ops): 增加平台只读统计接口与超管入口
This commit is contained in:
@@ -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)
|
||||
}
|
||||
Reference in New Issue
Block a user