feat(tenant): 增加双站订单视图与租户统计

This commit is contained in:
yml
2026-11-15 15:54:49 +08:00
parent 4eb2bc253b
commit 6d2affa15f
16 changed files with 697 additions and 54 deletions
@@ -7,6 +7,7 @@ import (
"hfb_sys/backend/internal/listingstatus"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"hfb_sys/backend/internal/timeutil"
"gorm.io/gorm"
@@ -36,44 +37,75 @@ func (r *Repository) Summary(ctx context.Context) (*DashboardDTO, error) {
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)
metrics := MetricsDTO{}
pending := PendingDTO{}
tenantID := tenancy.IDFromContext(ctx)
if err := db.Model(&model.User{}).Count(&metrics.TotalUsers).Error; err != nil {
userQuery := db.Model(&model.User{})
if tenantID > 0 {
userQuery = userQuery.Where("tenant_id = ?", tenantID)
}
if err := userQuery.Count(&metrics.TotalUsers).Error; err != nil {
return nil, err
}
if err := db.Model(&model.User{}).Where("realname_status = ?", "verified").Count(&metrics.VerifiedUsers).Error; err != nil {
if err := userQuery.Session(&gorm.Session{}).Where("realname_status = ?", "verified").Count(&metrics.VerifiedUsers).Error; err != nil {
return nil, err
}
if err := db.Model(&model.RentalListing{}).Count(&metrics.TotalListings).Error; err != nil {
listingQuery := db.Model(&model.RentalListing{})
if tenantID > 0 {
listingQuery = listingQuery.Where("source_tenant_id = ?", tenantID)
}
if err := listingQuery.Count(&metrics.TotalListings).Error; err != nil {
return nil, err
}
if err := db.Model(&model.RentalListing{}).Where("status = ? AND review_status = ?", "published", "approved").Count(&metrics.PublishedListings).Error; err != nil {
if err := listingQuery.Session(&gorm.Session{}).Where("status = ? AND review_status = ?", "published", "approved").Count(&metrics.PublishedListings).Error; err != nil {
return nil, err
}
if err := db.Model(&model.RentalOrder{}).Count(&metrics.TotalOrders).Error; err != nil {
orderQuery := db.Table("rental_orders AS o")
orderQuery = applyDashboardOrderScope(orderQuery, tenantID)
if err := orderQuery.Count(&metrics.TotalOrders).Error; err != nil {
return nil, err
}
if err := db.Model(&model.RentalOrder{}).Where("status = ?", "renting").Count(&metrics.RentingOrders).Error; err != nil {
if err := orderQuery.Session(&gorm.Session{}).Where("o.status = ?", "renting").Count(&metrics.RentingOrders).Error; err != nil {
return nil, err
}
if err := db.Model(&model.RentalOrder{}).Where("created_at >= ?", today).Count(&metrics.TodayOrders).Error; err != nil {
if err := orderQuery.Session(&gorm.Session{}).Where("o.created_at >= ?", today).Count(&metrics.TodayOrders).Error; err != nil {
return nil, err
}
if err := db.Model(&model.WalletLedger{}).
ledgerQuery := db.Model(&model.WalletLedger{})
if tenantID > 0 {
ledgerQuery = ledgerQuery.Where("tenant_id = ?", tenantID)
}
if err := ledgerQuery.
Select("COALESCE(SUM(amount_cent), 0)").
Where("created_at >= ?", today).
Scan(&metrics.TodayLedgerAmountCent).Error; err != nil {
return nil, err
}
if err := db.Model(&model.RentalListing{}).Where("review_status = ?", "pending").Count(&pending.ListingReviews).Error; err != nil {
if err := listingQuery.Session(&gorm.Session{}).Where("review_status = ?", "pending").Count(&pending.ListingReviews).Error; err != nil {
return nil, err
}
if err := db.Model(&model.Dispute{}).Where("status IN ?", []string{"open", "processing"}).Count(&pending.Disputes).Error; err != nil {
disputeQuery := db.Table("disputes AS d")
if tenantID > 0 {
disputeQuery = disputeQuery.Where(`EXISTS (
SELECT 1 FROM rental_orders AS tenant_order
WHERE tenant_order.id = d.order_id
AND (tenant_order.buyer_tenant_id = ? OR tenant_order.source_tenant_id = ?)
)`, tenantID, tenantID)
}
if err := disputeQuery.Where("d.status IN ?", []string{"open", "processing"}).Count(&pending.Disputes).Error; err != nil {
return nil, err
}
if err := db.Model(&model.RentalOrder{}).Where("status = ? AND handoff_status IN ?", "pending_handoff", []string{"pending_owner", "pending_renter_confirm"}).Count(&pending.PendingHandoffs).Error; err != nil {
if err := orderQuery.Session(&gorm.Session{}).
Where("o.status = ? AND o.handoff_status IN ?", "pending_handoff", []string{"pending_owner", "pending_renter_confirm"}).
Count(&pending.PendingHandoffs).Error; err != nil {
return nil, err
}
if err := db.Model(&model.RentalOrder{}).Where("status IN ?", []string{"pending_checkout_confirm", "pending_checkout_accept"}).Count(&pending.PendingReturnConfirms).Error; err != nil {
if err := orderQuery.Session(&gorm.Session{}).
Where("o.status IN ?", []string{"pending_checkout_confirm", "pending_checkout_accept"}).
Count(&pending.PendingReturnConfirms).Error; err != nil {
return nil, err
}
tenantStats, err := r.tenantStats(ctx, tenantID, metrics)
if err != nil {
return nil, err
}
@@ -99,6 +131,7 @@ func (r *Repository) Summary(ctx context.Context) (*DashboardDTO, error) {
}
return &DashboardDTO{
Metrics: metrics,
Tenant: tenantStats,
Pending: pending,
ListingDaily: listingDaily,
TradingDaily: tradingDaily,
@@ -109,6 +142,53 @@ func (r *Repository) Summary(ctx context.Context) (*DashboardDTO, error) {
}, nil
}
func (r *Repository) tenantStats(ctx context.Context, tenantID uint64, metrics MetricsDTO) (*TenantStatsDTO, error) {
if tenantID == 0 {
return nil, nil
}
result := &TenantStatsDTO{
TenantID: tenantID,
UserCount: metrics.TotalUsers,
VerifiedUsers: metrics.VerifiedUsers,
PublishedListings: metrics.PublishedListings,
}
db := r.db.WithContext(ctx)
var buyerStats struct {
OrderCount int64 `gorm:"column:buyer_order_count"`
GMVCent int64 `gorm:"column:buyer_gmv_cent"`
}
if err := db.Table("rental_orders AS o").
Where("o.buyer_tenant_id = ?", tenantID).
Where(tradingOrderPaidCondition).
Select("COUNT(*) AS buyer_order_count, COALESCE(SUM(o.rent_amount_cent), 0) AS buyer_gmv_cent").
Scan(&buyerStats).Error; err != nil {
return nil, err
}
result.BuyerOrderCount = buyerStats.OrderCount
result.BuyerGMVCent = buyerStats.GMVCent
var sourceStats struct {
OrderCount int64 `gorm:"column:source_order_count"`
AmountCent int64 `gorm:"column:source_amount_cent"`
}
if err := db.Table("rental_orders AS o").
Where("o.source_tenant_id = ?", tenantID).
Where(tradingOrderPaidCondition).
Select("COUNT(*) AS source_order_count, COALESCE(SUM(o.source_amount_cent), 0) AS source_amount_cent").
Scan(&sourceStats).Error; err != nil {
return nil, err
}
result.SourceOrderCount = sourceStats.OrderCount
result.SourceAmountCent = sourceStats.AmountCent
return result, nil
}
func applyDashboardOrderScope(query *gorm.DB, tenantID uint64) *gorm.DB {
if tenantID == 0 {
return query
}
return query.Where("(o.buyer_tenant_id = ? OR o.source_tenant_id = ?)", tenantID, tenantID)
}
func (r *Repository) listingDailyOverview(ctx context.Context, now time.Time, days int) (ListingDailyOverviewDTO, error) {
if days <= 0 {
days = listingDailyTrendDays
@@ -127,11 +207,12 @@ func (r *Repository) listingDailyOverview(ctx context.Context, now time.Time, da
}
events := make([]eventRow, 0)
db := r.db.WithContext(ctx)
tenantID := tenancy.IDFromContext(ctx)
uploadSource := db.Table("listing_uploads").
Select("listing_id, MAX(id) AS upload_id, MAX(NULLIF(source_channel, '')) AS source_channel").
Where("listing_id IS NOT NULL").
Group("listing_id")
if err := db.Table("listing_status_events AS e").
eventQuery := db.Table("listing_status_events AS e").
Select(`e.event_type, e.source, e.created_at,
CASE
WHEN lu.upload_id IS NULL THEN ?
@@ -139,15 +220,24 @@ func (r *Repository) listingDailyOverview(ctx context.Context, now time.Time, da
ELSE lu.source_channel
END AS source_channel`, listingChannelWebsite, listingChannelExternalUnknown).
Joins("LEFT JOIN (?) AS lu ON lu.listing_id = e.listing_id", uploadSource).
Where("e.created_at >= ? AND e.created_at < ?", start, end).
Scan(&events).Error; err != nil {
Where("e.created_at >= ? AND e.created_at < ?", start, end)
if tenantID > 0 {
eventQuery = eventQuery.Joins("JOIN rental_listings AS tenant_listing ON tenant_listing.id = e.listing_id").
Where("tenant_listing.source_tenant_id = ?", tenantID)
}
if err := eventQuery.Scan(&events).Error; err != nil {
return ListingDailyOverviewDTO{}, err
}
uploads := make([]listingUploaderRow, 0)
if err := db.Table("listing_uploads").
Select("COALESCE(matched_admin_id, 0) AS uploader_id, uploader_name, created_at").
Where("listing_id IS NOT NULL").
Where("created_at >= ? AND created_at < ?", start, end).
uploadQuery := db.Table("listing_uploads AS lu")
if tenantID > 0 {
uploadQuery = uploadQuery.Joins("JOIN rental_listings AS tenant_listing ON tenant_listing.id = lu.listing_id").
Where("tenant_listing.source_tenant_id = ?", tenantID)
}
if err := uploadQuery.
Select("COALESCE(lu.matched_admin_id, 0) AS uploader_id, lu.uploader_name, lu.created_at").
Where("lu.listing_id IS NOT NULL").
Where("lu.created_at >= ? AND lu.created_at < ?", start, end).
Scan(&uploads).Error; err != nil {
return ListingDailyOverviewDTO{}, err
}
@@ -381,11 +471,12 @@ func (r *Repository) tradingDailyOverview(ctx context.Context, now time.Time, da
}
rows := make([]row, 0)
// 读取区间内订单后在 Go 侧按上海时区归日,避免依赖 MySQL 会话时区。
if err := r.db.WithContext(ctx).Table("rental_orders").
Select("created_at, is_premium, compensation_plan, insurance_fee_bps").
orderQuery := r.db.WithContext(ctx).Table("rental_orders AS o").
Select("o.created_at, o.is_premium, o.compensation_plan, o.insurance_fee_bps")
orderQuery = applyDashboardOrderScope(orderQuery, tenancy.IDFromContext(ctx)).
Where(tradingOrderPaidCondition).
Where("created_at >= ? AND created_at < ?", start, end).
Scan(&rows).Error; err != nil {
Where("o.created_at >= ? AND o.created_at < ?", start, end)
if err := orderQuery.Scan(&rows).Error; err != nil {
return TradingDailyOverviewDTO{}, err
}
@@ -435,6 +526,9 @@ func (r *Repository) tradingDailyOverview(ctx context.Context, now time.Time, da
// 录单表是后来新增的功能表,若迁移尚未执行(表不存在)则降级为空统计,
// 避免连带整个仪表盘不可用。
func (r *Repository) manualEntryToday(ctx context.Context, now time.Time) ([]ManualEntryAgentStatsDTO, error) {
if tenancy.IDFromContext(ctx) > 0 {
return []ManualEntryAgentStatsDTO{}, nil
}
if r.db == nil || !r.db.Migrator().HasTable("cs_manual_entries") {
return []ManualEntryAgentStatsDTO{}, nil
}
@@ -474,7 +568,8 @@ func (r *Repository) manualEntryToday(ctx context.Context, now time.Time) ([]Man
func (r *Repository) recentOrders(ctx context.Context) ([]RecentOrderDTO, error) {
rows := make([]RecentOrderDTO, 0)
err := r.db.WithContext(ctx).Table("rental_orders AS o").
query := applyDashboardOrderScope(r.db.WithContext(ctx).Table("rental_orders AS o"), tenancy.IDFromContext(ctx))
err := query.
Select("o.id, o.order_no, a.title, o.renter_id, o.owner_id, o.status, o.rent_amount_cent, o.deposit_amount_cent, o.created_at").
Joins("JOIN game_accounts AS a ON a.id = o.account_id").
Order("o.id DESC").
@@ -485,10 +580,12 @@ func (r *Repository) recentOrders(ctx context.Context) ([]RecentOrderDTO, error)
func (r *Repository) recentDisputes(ctx context.Context) ([]RecentDisputeDTO, error) {
rows := make([]RecentDisputeDTO, 0)
err := r.db.WithContext(ctx).Table("disputes AS d").
query := r.db.WithContext(ctx).Table("disputes AS d").
Select("d.id, d.order_id, o.order_no, a.title, d.type, d.status, d.initiator_id, d.created_at").
Joins("JOIN rental_orders AS o ON o.id = d.order_id").
Joins("JOIN game_accounts AS a ON a.id = o.account_id").
Joins("JOIN game_accounts AS a ON a.id = o.account_id")
query = applyDashboardOrderScope(query, tenancy.IDFromContext(ctx))
err := query.
Order("d.id DESC").
Limit(8).
Scan(&rows).Error