Files
hfb_sys/backend/internal/modules/platformops/repository.go
T

308 lines
12 KiB
Go

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").
Where("distribution_site_id = 0").
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").
Where("(distribution_site_id IS NULL OR distribution_site_id = 0)").
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").
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)").
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").
Joins("JOIN rental_orders AS o ON o.id = d.order_id").
Where("d.status IN ?", []string{"open", "processing"}).
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)").
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"}).
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)").
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"}).
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)").
Count(&result.PendingReturns).Error; err != nil {
return nil, err
}
if err := db.Table("wallet_ledger").
Where("(distribution_site_id = 0 OR distribution_site_id IS NULL)").
Select(`COALESCE(SUM(CASE WHEN direction = 'in' THEN amount_cent ELSE 0 END), 0) AS wallet_inflow_cent,
COALESCE(SUM(CASE WHEN direction = 'out' THEN amount_cent ELSE 0 END), 0) AS wallet_outflow_cent,
COALESCE(SUM(CASE WHEN direction = 'in' AND created_at >= ? THEN amount_cent ELSE 0 END), 0) AS today_wallet_inflow_cent,
COALESCE(SUM(CASE WHEN direction = 'out' AND created_at >= ? THEN amount_cent ELSE 0 END), 0) AS today_wallet_outflow_cent`, today, today).
Row().
Scan(&result.WalletInflowCent, &result.WalletOutflowCent, &result.TodayWalletInflowCent, &result.TodayWalletOutflowCent); err != nil {
return nil, err
}
if err := db.Table("withdrawal_requests").
Where("status IN ?", []string{"pending", "processing"}).
Where("distribution_site_id = 0").
Count(&result.PendingWithdrawals).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 = ? AND distribution_site_id = 0", 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).
Where("(distribution_site_id IS NULL OR distribution_site_id = 0)").
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 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").
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)").
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
if err := db.Table("wallet_ledger").
Where("tenant_id = ?", tenant.ID).
Where("(distribution_site_id = 0 OR distribution_site_id IS NULL)").
Select(`COALESCE(SUM(CASE WHEN direction = 'in' THEN amount_cent ELSE 0 END), 0) AS wallet_inflow_cent,
COALESCE(SUM(CASE WHEN direction = 'out' THEN amount_cent ELSE 0 END), 0) AS wallet_outflow_cent,
COALESCE(SUM(CASE WHEN direction = 'in' AND created_at >= ? THEN amount_cent ELSE 0 END), 0) AS today_wallet_inflow_cent,
COALESCE(SUM(CASE WHEN direction = 'out' AND created_at >= ? THEN amount_cent ELSE 0 END), 0) AS today_wallet_outflow_cent`, today, today).
Row().
Scan(&result.WalletInflowCent, &result.WalletOutflowCent, &result.TodayWalletInflowCent, &result.TodayWalletOutflowCent); err != nil {
return result, err
}
if err := db.Table("withdrawal_requests").
Where("tenant_id = ?", tenant.ID).
Where("distribution_site_id = 0").
Where("status IN ?", []string{"pending", "processing"}).
Count(&result.PendingWithdrawals).Error; err != nil {
return result, err
}
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 time.Time `gorm:"column:date"`
Value int64 `gorm:"column:value"`
AmountCent int64 `gorm:"column:amount_cent"`
InflowCent int64 `gorm:"column:inflow_cent"`
OutflowCent int64 `gorm:"column:outflow_cent"`
}
users := map[string]int64{}
var userRows []row
if err := db.Table("users").
Select("DATE(created_at) AS date, COUNT(*) AS value").
Where("distribution_site_id = 0").
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.Format("2006-01-02")] = 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("(distribution_site_id IS NULL OR distribution_site_id = 0)").
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.Format("2006-01-02")] = 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("(distribution_site_id IS NULL OR distribution_site_id = 0)").
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.Format("2006-01-02")] = item
}
walletTrend := map[string]row{}
var walletRows []row
if err := db.Table("wallet_ledger").
Select(`DATE(created_at) AS date,
COALESCE(SUM(CASE WHEN direction = 'in' THEN amount_cent ELSE 0 END), 0) AS inflow_cent,
COALESCE(SUM(CASE WHEN direction = 'out' THEN amount_cent ELSE 0 END), 0) AS outflow_cent`).
Where("(distribution_site_id = 0 OR distribution_site_id IS NULL)").
Where("created_at >= ? AND created_at < ?", start, end).
Group("DATE(created_at)").Scan(&walletRows).Error; err != nil {
return nil, err
}
for _, item := range walletRows {
walletTrend[item.Date.Format("2006-01-02")] = 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]
wallet := walletTrend[key]
result = append(result, TrendPointDTO{
Date: key,
NewUsers: users[key],
NewListings: listings[key],
Orders: order.Value,
PaidGMVCent: order.AmountCent,
WalletInflowCent: wallet.InflowCent,
WalletOutflowCent: wallet.OutflowCent,
})
}
return result, nil
}