feat(tenant): 增加双站订单视图与租户统计
This commit is contained in:
@@ -4,6 +4,7 @@ import "time"
|
||||
|
||||
type DashboardDTO struct {
|
||||
Metrics MetricsDTO `json:"metrics"`
|
||||
Tenant *TenantStatsDTO `json:"tenant,omitempty"`
|
||||
Pending PendingDTO `json:"pending"`
|
||||
ListingDaily ListingDailyOverviewDTO `json:"listing_daily"`
|
||||
TradingDaily TradingDailyOverviewDTO `json:"trading_daily"`
|
||||
@@ -13,6 +14,17 @@ type DashboardDTO struct {
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
}
|
||||
|
||||
type TenantStatsDTO struct {
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
UserCount int64 `json:"user_count"`
|
||||
VerifiedUsers int64 `json:"verified_users"`
|
||||
PublishedListings int64 `json:"published_listings"`
|
||||
BuyerOrderCount int64 `json:"buyer_order_count"`
|
||||
BuyerGMVCent int64 `json:"buyer_gmv_cent"`
|
||||
SourceOrderCount int64 `json:"source_order_count"`
|
||||
SourceAmountCent int64 `json:"source_amount_cent"`
|
||||
}
|
||||
|
||||
type MetricsDTO struct {
|
||||
TotalUsers int64 `json:"total_users"`
|
||||
VerifiedUsers int64 `json:"verified_users"`
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package admindashboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
)
|
||||
|
||||
func dashboardTenantContext(tenantID uint64) context.Context {
|
||||
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
|
||||
}
|
||||
|
||||
func TestSummaryScopesBuyerAndSourceMetricsByTenant(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
tenants := []model.Tenant{
|
||||
{ID: 101, Code: "tenant_a", Name: "A站", Status: "active"},
|
||||
{ID: 202, Code: "tenant_b", Name: "B站", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&tenants).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
users := []model.User{
|
||||
{TenantID: 101, Phone: "13200000101", Status: "active", RealnameStatus: "verified"},
|
||||
{TenantID: 101, Phone: "13200000102", Status: "active"},
|
||||
{TenantID: 202, Phone: "13200000201", Status: "active", RealnameStatus: "verified"},
|
||||
}
|
||||
if err := db.Create(&users).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accountA := model.GameAccount{
|
||||
SourceTenantID: 101, OwnerID: users[0].ID, ServerRegion: "国服",
|
||||
LoginPlatform: "steam", Title: "A站货源", Status: "published",
|
||||
}
|
||||
accountB := model.GameAccount{
|
||||
SourceTenantID: 202, OwnerID: users[2].ID, ServerRegion: "国服",
|
||||
LoginPlatform: "steam", Title: "B站货源", Status: "published",
|
||||
}
|
||||
if err := db.Create(&accountA).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&accountB).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listingA := model.RentalListing{
|
||||
SourceTenantID: 101, ListingNo: "L-DASHBOARD-A", AccountID: accountA.ID,
|
||||
OwnerID: users[0].ID, PriceCent: 1000, Status: "published", ReviewStatus: "approved",
|
||||
}
|
||||
listingB := model.RentalListing{
|
||||
SourceTenantID: 202, ListingNo: "L-DASHBOARD-B", AccountID: accountB.ID,
|
||||
OwnerID: users[2].ID, PriceCent: 2000, Status: "published", ReviewStatus: "approved",
|
||||
}
|
||||
if err := db.Create(&listingA).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&listingB).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
orders := []model.RentalOrder{
|
||||
{
|
||||
OrderNo: "RO-DASHBOARD-A-BUY", ListingID: listingB.ID, AccountID: accountB.ID,
|
||||
OwnerID: users[2].ID, RenterID: users[0].ID, BuyerTenantID: 101,
|
||||
SourceTenantID: 202, PaymentTenantID: 101, RentAmountCent: 2500,
|
||||
OwnerRentAmountCent: 1600, SourceAmountCent: 1600, Status: "renting",
|
||||
},
|
||||
{
|
||||
OrderNo: "RO-DASHBOARD-A-SOURCE", ListingID: listingA.ID, AccountID: accountA.ID,
|
||||
OwnerID: users[0].ID, RenterID: users[2].ID, BuyerTenantID: 202,
|
||||
SourceTenantID: 101, PaymentTenantID: 202, RentAmountCent: 3000,
|
||||
OwnerRentAmountCent: 1800, SourceAmountCent: 1800, Status: "completed",
|
||||
},
|
||||
}
|
||||
if err := db.Create(&orders).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
summary, err := NewRepository(db).Summary(dashboardTenantContext(101))
|
||||
if err != nil {
|
||||
t.Fatalf("tenant summary: %v", err)
|
||||
}
|
||||
if summary.Metrics.TotalUsers != 2 || summary.Metrics.VerifiedUsers != 1 {
|
||||
t.Fatalf("tenant user metrics = %+v", summary.Metrics)
|
||||
}
|
||||
if summary.Metrics.TotalListings != 1 || summary.Metrics.PublishedListings != 1 {
|
||||
t.Fatalf("tenant listing metrics = %+v", summary.Metrics)
|
||||
}
|
||||
if summary.Metrics.TotalOrders != 2 {
|
||||
t.Fatalf("tenant relevant order count = %d, want 2", summary.Metrics.TotalOrders)
|
||||
}
|
||||
if summary.Tenant == nil {
|
||||
t.Fatal("tenant statistics missing")
|
||||
}
|
||||
if summary.Tenant.BuyerOrderCount != 1 || summary.Tenant.BuyerGMVCent != 2500 {
|
||||
t.Fatalf("buyer tenant stats = %+v", summary.Tenant)
|
||||
}
|
||||
if summary.Tenant.SourceOrderCount != 1 || summary.Tenant.SourceAmountCent != 1800 {
|
||||
t.Fatalf("source tenant stats = %+v", summary.Tenant)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ type OrderDTO struct {
|
||||
BuyerTenantID uint64 `json:"buyer_tenant_id"`
|
||||
SourceTenantID uint64 `json:"source_tenant_id"`
|
||||
PaymentTenantID uint64 `json:"payment_tenant_id"`
|
||||
SiteRole string `json:"site_role,omitempty"`
|
||||
OrderNo string `json:"order_no"`
|
||||
ListingID uint64 `json:"listing_id"`
|
||||
ListingNo string `json:"listing_no"`
|
||||
@@ -126,6 +127,10 @@ type UserOrderListItemDTO struct {
|
||||
// AdminOrderListItemDTO 是后台订单表格的最小展示数据;手机号按客服需要返回完整值,其余敏感详情仅由详情接口按权限获取。
|
||||
type AdminOrderListItemDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
BuyerTenantID uint64 `json:"buyer_tenant_id"`
|
||||
SourceTenantID uint64 `json:"source_tenant_id"`
|
||||
PaymentTenantID uint64 `json:"payment_tenant_id"`
|
||||
SiteRole string `json:"site_role,omitempty"`
|
||||
OrderNo string `json:"order_no"`
|
||||
ListingID uint64 `json:"listing_id"`
|
||||
ListingNo string `json:"listing_no"`
|
||||
|
||||
@@ -219,6 +219,9 @@ func (row orderRow) toUserListItem(userID uint64, paymentDeadlineAt *time.Time)
|
||||
func (row orderRow) toAdminListItem() AdminOrderListItemDTO {
|
||||
return AdminOrderListItemDTO{
|
||||
ID: row.ID,
|
||||
BuyerTenantID: row.BuyerTenantID,
|
||||
SourceTenantID: row.SourceTenantID,
|
||||
PaymentTenantID: row.PaymentTenantID,
|
||||
OrderNo: row.OrderNo,
|
||||
ListingID: row.ListingID,
|
||||
ListingNo: row.ListingNo,
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/distribution"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -208,6 +209,7 @@ func (r *Repository) ListAdmin(ctx context.Context, query AdminOrderQuery) (*Adm
|
||||
items := make([]AdminOrderListItemDTO, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
item := row.toAdminListItem()
|
||||
item.SiteRole = tenantOrderRole(ctx, row.RentalOrder)
|
||||
if amount, ok := ownerIncome[row.ID]; ok {
|
||||
value := amount
|
||||
item.OwnerIncomeAmountCent = &value
|
||||
@@ -250,7 +252,7 @@ func (r *Repository) adminOrderCountQuery(ctx context.Context, query AdminOrderQ
|
||||
}
|
||||
}
|
||||
if !needsJoin {
|
||||
return r.db.WithContext(ctx).Table("rental_orders AS o")
|
||||
return applyTenantOrderScope(r.db.WithContext(ctx).Table("rental_orders AS o"), ctx)
|
||||
}
|
||||
return r.adminOrderJoinQuery(ctx)
|
||||
}
|
||||
@@ -367,6 +369,8 @@ func (r *Repository) FindAdmin(ctx context.Context, orderID uint64) (*OrderDTO,
|
||||
return nil, err
|
||||
}
|
||||
dto := row.toAdminDTO()
|
||||
dto.SiteRole = tenantOrderRole(ctx, row.RentalOrder)
|
||||
filterAdminActionsForSiteRole(&dto)
|
||||
applyPaymentDeadline(&dto, row.RentalOrder, pendingPaymentTimeoutMinutes(db))
|
||||
dto.ActiveDispute = r.activeDisputeDTO(ctx, orderID)
|
||||
dto.Checkout = r.latestCheckoutAdminDTO(ctx, orderID)
|
||||
@@ -383,12 +387,28 @@ func (r *Repository) FindLatestAdminByListing(ctx context.Context, listingID uin
|
||||
return nil, err
|
||||
}
|
||||
dto := row.toAdminDTO()
|
||||
dto.SiteRole = tenantOrderRole(ctx, row.RentalOrder)
|
||||
filterAdminActionsForSiteRole(&dto)
|
||||
applyPaymentDeadline(&dto, row.RentalOrder, pendingPaymentTimeoutMinutes(db))
|
||||
dto.ActiveDispute = r.activeDisputeDTO(ctx, row.ID)
|
||||
dto.Checkout = r.latestCheckoutAdminDTO(ctx, row.ID)
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
func (r *Repository) EnsureAdminOrderAccess(ctx context.Context, orderID uint64) error {
|
||||
if tenancy.IDFromContext(ctx) == 0 {
|
||||
return nil
|
||||
}
|
||||
var count int64
|
||||
if err := r.adminOrderJoinQuery(ctx).Where("o.id = ?", orderID).Count(&count).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if count == 0 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) FindForUser(ctx context.Context, userID uint64, orderID uint64, siteCode ...string) (*OrderDTO, error) {
|
||||
var row orderRow
|
||||
db := r.db.WithContext(ctx)
|
||||
@@ -411,6 +431,7 @@ func (r *Repository) FindForUser(ctx context.Context, userID uint64, orderID uin
|
||||
return nil, err
|
||||
}
|
||||
dto := row.toDTOForUser(userID)
|
||||
dto.SiteRole = tenantOrderRole(ctx, row.RentalOrder)
|
||||
applyPaymentDeadline(&dto, row.RentalOrder, pendingPaymentTimeoutMinutes(db))
|
||||
dto.ActiveDispute = r.activeDisputeDTO(ctx, orderID)
|
||||
dto.Checkout = r.latestCheckoutDTOForUser(ctx, orderID, userID, row.RentalOrder)
|
||||
@@ -506,11 +527,65 @@ func (r *Repository) adminQuery(ctx context.Context) *gorm.DB {
|
||||
}
|
||||
|
||||
func (r *Repository) adminOrderJoinQuery(ctx context.Context) *gorm.DB {
|
||||
return r.db.WithContext(ctx).Table("rental_orders AS o").
|
||||
query := r.db.WithContext(ctx).Table("rental_orders AS o").
|
||||
Joins("JOIN rental_listings AS l ON l.id = o.listing_id").
|
||||
Joins("JOIN game_accounts AS a ON a.id = o.account_id").
|
||||
Joins("JOIN users AS owner ON owner.id = o.owner_id").
|
||||
Joins("JOIN users AS renter ON renter.id = o.renter_id")
|
||||
return applyTenantOrderScope(query, ctx)
|
||||
}
|
||||
|
||||
func applyTenantOrderScope(query *gorm.DB, ctx context.Context) *gorm.DB {
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID == 0 {
|
||||
return query
|
||||
}
|
||||
return query.Where("(o.buyer_tenant_id = ? OR o.source_tenant_id = ?)", tenantID, tenantID)
|
||||
}
|
||||
|
||||
func applyBuyerTenantOrderScope(query *gorm.DB, ctx context.Context) *gorm.DB {
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID == 0 {
|
||||
return query
|
||||
}
|
||||
return query.Where("o.buyer_tenant_id = ?", tenantID)
|
||||
}
|
||||
|
||||
func tenantOrderRole(ctx context.Context, order model.RentalOrder) string {
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID == 0 {
|
||||
return ""
|
||||
}
|
||||
isBuyer := order.BuyerTenantID == tenantID
|
||||
isSource := order.SourceTenantID == tenantID
|
||||
switch {
|
||||
case isBuyer && isSource:
|
||||
return "both"
|
||||
case isBuyer:
|
||||
return "buyer"
|
||||
case isSource:
|
||||
return "source"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func filterAdminActionsForSiteRole(dto *OrderDTO) {
|
||||
if dto == nil || dto.AdminActions == nil || dto.SiteRole == "" || dto.SiteRole == "both" {
|
||||
return
|
||||
}
|
||||
actions := dto.AdminActions
|
||||
if dto.SiteRole == "buyer" {
|
||||
actions.ResetHandoff = nil
|
||||
actions.PlatformHandoff = nil
|
||||
actions.ForceHandoff = nil
|
||||
actions.PlatformOfflineSettlement = nil
|
||||
}
|
||||
if dto.SiteRole == "source" {
|
||||
actions.PlatformCheckoutConfirm = nil
|
||||
actions.PlatformCheckoutCounter = nil
|
||||
actions.PlatformCheckoutDispute = nil
|
||||
}
|
||||
}
|
||||
|
||||
type orderRow struct {
|
||||
|
||||
@@ -2,14 +2,12 @@ package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
)
|
||||
|
||||
// ListPendingRefund 查询所有待客服审核退款的订单。
|
||||
func (r *Repository) ListPendingRefund(ctx context.Context) ([]OrderDTO, error) {
|
||||
var rows []orderRow
|
||||
err := r.adminQuery(ctx).
|
||||
err := applyBuyerTenantOrderScope(r.adminQuery(ctx), ctx).
|
||||
Where("o.refund_status = ?", refundStatusPendingReview).
|
||||
Order("o.updated_at ASC, o.id ASC").
|
||||
Limit(200).
|
||||
@@ -23,6 +21,7 @@ func (r *Repository) ListPendingRefund(ctx context.Context) ([]OrderDTO, error)
|
||||
items := make([]OrderDTO, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
dto := row.toAdminDTO()
|
||||
dto.SiteRole = tenantOrderRole(ctx, row.RentalOrder)
|
||||
applyPaymentDeadline(&dto, row.RentalOrder, paymentTimeoutMinutes)
|
||||
items = append(items, dto)
|
||||
}
|
||||
@@ -32,9 +31,10 @@ func (r *Repository) ListPendingRefund(ctx context.Context) ([]OrderDTO, error)
|
||||
// PendingRefundCount 返回待客服审核退款数量,用于后台导航角标。
|
||||
func (r *Repository) PendingRefundCount(ctx context.Context) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).
|
||||
Model(&model.RentalOrder{}).
|
||||
Where("refund_status = ?", refundStatusPendingReview).
|
||||
Count(&count).Error
|
||||
query := r.db.WithContext(ctx).
|
||||
Table("rental_orders AS o").
|
||||
Where("refund_status = ?", refundStatusPendingReview)
|
||||
query = applyBuyerTenantOrderScope(query, ctx)
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
@@ -206,6 +206,9 @@ func (s *Service) HandoffRecordsAdmin(ctx context.Context, orderID uint64) ([]Ha
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repo.HandoffRecordsAdmin(ctx, orderID)
|
||||
}
|
||||
|
||||
@@ -213,6 +216,9 @@ func (s *Service) ProcessEventsAdmin(ctx context.Context, orderID uint64) ([]Pro
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repo.ProcessEventsAdmin(ctx, orderID)
|
||||
}
|
||||
|
||||
@@ -223,6 +229,9 @@ func (s *Service) AdminClose(ctx context.Context, adminID uint64, orderID uint64
|
||||
if orderID == 0 || req.Reason == "" {
|
||||
return ErrOrderCannotComplete
|
||||
}
|
||||
if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.AdminClose(ctx, adminID, orderID, req, meta)
|
||||
}
|
||||
|
||||
@@ -233,6 +242,9 @@ func (s *Service) AdminMarkAbnormal(ctx context.Context, adminID uint64, orderID
|
||||
if orderID == 0 || req.Reason == "" {
|
||||
return ErrOrderCannotComplete
|
||||
}
|
||||
if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.AdminMarkAbnormal(ctx, adminID, orderID, req, meta)
|
||||
}
|
||||
|
||||
@@ -243,6 +255,9 @@ func (s *Service) AdminSeal(ctx context.Context, adminID uint64, orderID uint64,
|
||||
if orderID == 0 || req.Reason == "" {
|
||||
return ErrOrderCannotComplete
|
||||
}
|
||||
if err := s.ensureAdminOrderAccess(ctx, orderID); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.AdminSeal(ctx, adminID, orderID, req, meta)
|
||||
}
|
||||
|
||||
@@ -253,6 +268,9 @@ func (s *Service) AdminResetHandoff(ctx context.Context, adminID uint64, orderID
|
||||
if orderID == 0 || req.Reason == "" {
|
||||
return ErrOrderCannotResetHandoff
|
||||
}
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityHandoff); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.AdminResetHandoff(ctx, adminID, orderID, req, meta)
|
||||
}
|
||||
|
||||
@@ -263,6 +281,9 @@ func (s *Service) AdminPlatformHandoff(ctx context.Context, adminID uint64, orde
|
||||
if orderID == 0 || req.Content == "" || req.Reason == "" {
|
||||
return nil, ErrOrderCannotHandoff
|
||||
}
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityHandoff); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repo.AdminPlatformHandoff(ctx, adminID, orderID, req, meta)
|
||||
}
|
||||
|
||||
@@ -273,6 +294,9 @@ func (s *Service) AdminForceHandoff(ctx context.Context, adminID uint64, orderID
|
||||
if orderID == 0 || req.Reason == "" {
|
||||
return ErrOrderCannotForceHandoff
|
||||
}
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityHandoff); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.AdminForceHandoff(ctx, adminID, orderID, req, meta)
|
||||
}
|
||||
|
||||
@@ -283,6 +307,9 @@ func (s *Service) AdminPlatformCheckoutConfirm(ctx context.Context, adminID uint
|
||||
if orderID == 0 || req.Reason == "" {
|
||||
return ErrCheckoutCannotConfirm
|
||||
}
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityCheckout); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.AdminPlatformCheckoutConfirm(ctx, adminID, orderID, req, meta)
|
||||
}
|
||||
|
||||
@@ -293,6 +320,9 @@ func (s *Service) AdminPlatformCheckoutCounter(ctx context.Context, adminID uint
|
||||
if orderID == 0 || req.Reason == "" {
|
||||
return nil, ErrCheckoutCannotCounter
|
||||
}
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityCheckout); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repo.AdminPlatformCheckoutCounter(ctx, adminID, orderID, req, meta)
|
||||
}
|
||||
|
||||
@@ -303,6 +333,9 @@ func (s *Service) AdminPlatformCheckoutDispute(ctx context.Context, adminID uint
|
||||
if orderID == 0 || req.Reason == "" {
|
||||
return ErrCheckoutCannotCounter
|
||||
}
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityCheckout); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.AdminPlatformCheckoutDispute(ctx, adminID, orderID, req, meta)
|
||||
}
|
||||
|
||||
@@ -313,6 +346,9 @@ func (s *Service) AdminMarkOfflineSettlement(ctx context.Context, adminID uint64
|
||||
if orderID == 0 {
|
||||
return ErrOfflineSettlementCannotMark
|
||||
}
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityHandoff); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.AdminMarkOfflineSettlement(ctx, adminID, orderID, req, meta)
|
||||
}
|
||||
|
||||
@@ -323,6 +359,9 @@ func (s *Service) AdminHoldDeposit(ctx context.Context, adminID uint64, orderID
|
||||
if orderID == 0 || req.Reason == "" {
|
||||
return ErrDepositCannotHold
|
||||
}
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.AdminHoldDeposit(ctx, adminID, orderID, req, meta)
|
||||
}
|
||||
|
||||
@@ -333,6 +372,9 @@ func (s *Service) AdminReleaseDeposit(ctx context.Context, adminID uint64, order
|
||||
if orderID == 0 || req.Reason == "" {
|
||||
return ErrDepositCannotHold
|
||||
}
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.AdminReleaseDeposit(ctx, adminID, orderID, req, meta)
|
||||
}
|
||||
|
||||
@@ -343,6 +385,9 @@ func (s *Service) AdminRefund(ctx context.Context, orderID uint64) (*RefundStatu
|
||||
if orderID == 0 {
|
||||
return nil, ErrOrderCannotComplete
|
||||
}
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repo.AdminRefund(ctx, orderID)
|
||||
}
|
||||
|
||||
@@ -353,6 +398,9 @@ func (s *Service) AdminRefundStatus(ctx context.Context, orderID uint64) (*Refun
|
||||
if orderID == 0 {
|
||||
return nil, ErrOrderCannotComplete
|
||||
}
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repo.AdminRefundStatus(ctx, orderID)
|
||||
}
|
||||
|
||||
@@ -363,6 +411,9 @@ func (s *Service) AdminApproveRefund(ctx context.Context, orderID uint64) error
|
||||
if orderID == 0 {
|
||||
return ErrOrderCannotComplete
|
||||
}
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.AdminApproveRefund(ctx, orderID)
|
||||
}
|
||||
|
||||
@@ -373,6 +424,9 @@ func (s *Service) AdminRejectRefund(ctx context.Context, orderID uint64, action
|
||||
if orderID == 0 {
|
||||
return ErrOrderCannotComplete
|
||||
}
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.AdminRejectRefund(ctx, orderID, action)
|
||||
}
|
||||
|
||||
@@ -396,3 +450,23 @@ func (s *Service) FindForUser(ctx context.Context, userID uint64, orderID uint64
|
||||
}
|
||||
return s.repo.FindForUser(ctx, userID, orderID, siteCode...)
|
||||
}
|
||||
|
||||
func (s *Service) ensureAdminOrderAccess(ctx context.Context, orderID uint64) error {
|
||||
if s.repo == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
if orderID == 0 {
|
||||
return ErrOrderCannotComplete
|
||||
}
|
||||
return s.repo.EnsureAdminOrderAccess(ctx, orderID)
|
||||
}
|
||||
|
||||
func (s *Service) ensureAdminOrderCapability(ctx context.Context, orderID uint64, capability string) error {
|
||||
if s.repo == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
if orderID == 0 {
|
||||
return ErrOrderCannotComplete
|
||||
}
|
||||
return s.repo.EnsureAdminOrderCapability(ctx, orderID, capability)
|
||||
}
|
||||
|
||||
@@ -169,3 +169,118 @@ func TestConcurrentTenantsCanOnlyRentListingOnce(t *testing.T) {
|
||||
t.Fatalf("order count = %d, want 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminOrdersAreScopedByCurrentTenant(t *testing.T) {
|
||||
db := setupOrderTestDB(t)
|
||||
tenants := []model.Tenant{
|
||||
{ID: 101, Code: "tenant_a", Name: "A站", Status: "active"},
|
||||
{ID: 202, Code: "tenant_b", Name: "B站", Status: "active"},
|
||||
{ID: 303, Code: "tenant_c", Name: "C站", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&tenants).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner := model.User{TenantID: 101, Phone: "13000000101", Status: "active"}
|
||||
renterB := model.User{TenantID: 202, Phone: "13000000202", Status: "active"}
|
||||
renterA := model.User{TenantID: 101, Phone: "13000000102", Status: "active"}
|
||||
if err := db.Create(&owner).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&renterB).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&renterA).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accountA := model.GameAccount{
|
||||
SourceTenantID: 101, OwnerID: owner.ID, ServerRegion: "国服",
|
||||
LoginPlatform: "steam", Title: "A站商品", Status: "published",
|
||||
}
|
||||
if err := db.Create(&accountA).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listingA := model.RentalListing{
|
||||
SourceTenantID: 101, ListingNo: "L-ADMIN-TENANT-A",
|
||||
AccountID: accountA.ID, OwnerID: owner.ID, PriceCent: 1000,
|
||||
Status: listingStatusPublished, ReviewStatus: listingReviewStatusApproved,
|
||||
}
|
||||
accountC := model.GameAccount{
|
||||
SourceTenantID: 303, OwnerID: owner.ID, ServerRegion: "国服",
|
||||
LoginPlatform: "steam", Title: "C站商品", Status: "published",
|
||||
}
|
||||
if err := db.Create(&accountC).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listingC := model.RentalListing{
|
||||
SourceTenantID: 303, ListingNo: "L-ADMIN-TENANT-C",
|
||||
AccountID: accountC.ID, OwnerID: owner.ID, PriceCent: 1000,
|
||||
Status: listingStatusPublished, ReviewStatus: listingReviewStatusApproved,
|
||||
}
|
||||
if err := db.Create(&listingA).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&listingC).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
orders := []model.RentalOrder{
|
||||
{
|
||||
OrderNo: "RO-TENANT-VISIBLE-B", ListingID: listingA.ID, AccountID: accountA.ID,
|
||||
OwnerID: owner.ID, RenterID: renterB.ID, BuyerTenantID: 202,
|
||||
SourceTenantID: 101, PaymentTenantID: 202, Status: orderStatusRenting,
|
||||
},
|
||||
{
|
||||
OrderNo: "RO-TENANT-HIDDEN", ListingID: listingC.ID, AccountID: accountC.ID,
|
||||
OwnerID: owner.ID, RenterID: renterA.ID, BuyerTenantID: 101,
|
||||
SourceTenantID: 303, PaymentTenantID: 101, Status: orderStatusRenting,
|
||||
},
|
||||
}
|
||||
if err := db.Create(&orders).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
|
||||
result, err := repo.ListAdmin(orderTenantContext(202), AdminOrderQuery{Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatalf("list B tenant orders: %v", err)
|
||||
}
|
||||
if result.Total != 1 || len(result.Items) != 1 || result.Items[0].ID != orders[0].ID {
|
||||
t.Fatalf("B tenant admin orders = %+v", result)
|
||||
}
|
||||
if result.Items[0].SiteRole != "buyer" || result.Items[0].SourceTenantID != 101 {
|
||||
t.Fatalf("B tenant order role = %+v", result.Items[0])
|
||||
}
|
||||
if _, err := repo.FindAdmin(orderTenantContext(202), orders[1].ID); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("cross-tenant admin detail error = %v", err)
|
||||
}
|
||||
service := NewService(repo)
|
||||
if _, err := service.AdminRefundStatus(orderTenantContext(202), orders[1].ID); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("cross-tenant admin action error = %v", err)
|
||||
}
|
||||
if err := repo.EnsureAdminOrderCapability(orderTenantContext(101), orders[0].ID, tenantOrderCapabilityRefund); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("source tenant refund capability error = %v", err)
|
||||
}
|
||||
if err := repo.EnsureAdminOrderCapability(orderTenantContext(202), orders[0].ID, tenantOrderCapabilityRefund); err != nil {
|
||||
t.Fatalf("buyer tenant refund capability: %v", err)
|
||||
}
|
||||
if err := repo.EnsureAdminOrderCapability(orderTenantContext(101), orders[0].ID, tenantOrderCapabilityHandoff); err != nil {
|
||||
t.Fatalf("source tenant handoff capability: %v", err)
|
||||
}
|
||||
if err := repo.EnsureAdminOrderCapability(orderTenantContext(202), orders[0].ID, tenantOrderCapabilityHandoff); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("buyer tenant handoff capability error = %v", err)
|
||||
}
|
||||
|
||||
sourceResult, err := repo.ListAdmin(orderTenantContext(101), AdminOrderQuery{Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sourceResult.Total != 2 {
|
||||
t.Fatalf("A tenant relevant orders = %+v", sourceResult)
|
||||
}
|
||||
roles := map[uint64]string{}
|
||||
for _, item := range sourceResult.Items {
|
||||
roles[item.ID] = item.SiteRole
|
||||
}
|
||||
if roles[orders[0].ID] != "source" || roles[orders[1].ID] != "buyer" {
|
||||
t.Fatalf("A tenant order roles = %+v", roles)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"hfb_sys/backend/internal/logging"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
tenantOrderCapabilityHandoff = "handoff"
|
||||
tenantOrderCapabilityCheckout = "checkout"
|
||||
tenantOrderCapabilityRefund = "refund"
|
||||
)
|
||||
|
||||
func (r *Repository) EnsureAdminOrderCapability(ctx context.Context, orderID uint64, capability string) error {
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID == 0 {
|
||||
return nil
|
||||
}
|
||||
var order struct {
|
||||
BuyerTenantID uint64
|
||||
SourceTenantID uint64
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Table("rental_orders").
|
||||
Select("buyer_tenant_id, source_tenant_id").
|
||||
Where("id = ?", orderID).
|
||||
Scan(&order).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if order.BuyerTenantID == 0 && order.SourceTenantID == 0 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
isBuyer := order.BuyerTenantID == tenantID
|
||||
isSource := order.SourceTenantID == tenantID
|
||||
if !isBuyer && !isSource {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
if r.adminIsPlatformSuper(ctx) {
|
||||
return nil
|
||||
}
|
||||
allowed := false
|
||||
switch capability {
|
||||
case tenantOrderCapabilityHandoff:
|
||||
allowed = isSource
|
||||
case tenantOrderCapabilityCheckout, tenantOrderCapabilityRefund:
|
||||
allowed = isBuyer
|
||||
default:
|
||||
allowed = true
|
||||
}
|
||||
if !allowed {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) adminIsPlatformSuper(ctx context.Context) bool {
|
||||
adminID := logging.AdminIDFromContext(ctx)
|
||||
if adminID == 0 {
|
||||
return false
|
||||
}
|
||||
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 aur.tenant_id = 0 AND r.code = ?", adminID, "super_admin").
|
||||
Count(&count).Error
|
||||
return err == nil && count > 0
|
||||
}
|
||||
@@ -94,6 +94,16 @@ export interface ManualEntryTodayStats {
|
||||
|
||||
export interface AdminDashboard {
|
||||
metrics: DashboardMetrics
|
||||
tenant?: {
|
||||
tenant_id: number
|
||||
user_count: number
|
||||
verified_users: number
|
||||
published_listings: number
|
||||
buyer_order_count: number
|
||||
buyer_gmv_cent: number
|
||||
source_order_count: number
|
||||
source_amount_cent: number
|
||||
}
|
||||
pending: DashboardPending
|
||||
listing_daily: ListingDailyOverview
|
||||
trading_daily: TradingDailyOverview
|
||||
|
||||
@@ -59,6 +59,7 @@ const tradingToday = computed<TradingDayStats>(
|
||||
}
|
||||
)
|
||||
const tradingDays = computed(() => dashboard.value?.trading_daily?.days ?? 7)
|
||||
const tenantStats = computed(() => dashboard.value?.tenant)
|
||||
|
||||
const listingTrend = computed(() => dashboard.value?.listing_daily?.trend ?? [])
|
||||
const listingChannelTrend = computed(() => dashboard.value?.listing_daily?.channel_trend ?? [])
|
||||
@@ -194,7 +195,11 @@ function shortDate(date: string) {
|
||||
<div class="metric-info">
|
||||
<span class="metric-label">订单总数</span>
|
||||
<strong class="metric-val amber-val">{{ dashboard.metrics.total_orders }}</strong>
|
||||
<span class="metric-sub-pill warning"
|
||||
<span v-if="tenantStats" class="metric-sub-pill warning">
|
||||
本站买入 {{ tenantStats.buyer_order_count }} 单 · 出货
|
||||
{{ tenantStats.source_order_count }} 单
|
||||
</span>
|
||||
<span v-else class="metric-sub-pill warning"
|
||||
>使用中 {{ dashboard.metrics.renting_orders }} 个</span
|
||||
>
|
||||
</div>
|
||||
|
||||
@@ -352,3 +352,12 @@
|
||||
justify-content: flex-start;
|
||||
}
|
||||
}
|
||||
.page-title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.page-title-row h1 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@@ -173,32 +173,52 @@ const platformCheckoutDisputeAction = computed(
|
||||
const offlineSettlementAction = computed(
|
||||
() => order.value?.admin_actions?.platform_offline_settlement
|
||||
)
|
||||
const hasBuyerRole = computed(
|
||||
() => !order.value?.site_role || ['buyer', 'both'].includes(order.value.site_role)
|
||||
)
|
||||
const hasSourceRole = computed(
|
||||
() => !order.value?.site_role || ['source', 'both'].includes(order.value.site_role)
|
||||
)
|
||||
const resetActionLabel = computed(() => {
|
||||
return resetAction.value?.label || '重置'
|
||||
})
|
||||
const canResetHandoff = computed(() => resetAction.value?.enabled === true)
|
||||
const canPlatformHandoff = computed(() => platformHandoffAction.value?.enabled === true)
|
||||
const canForceHandoff = computed(() => forceHandoffAction.value?.enabled === true)
|
||||
const canResetHandoff = computed(() => hasSourceRole.value && resetAction.value?.enabled === true)
|
||||
const canPlatformHandoff = computed(
|
||||
() => hasSourceRole.value && platformHandoffAction.value?.enabled === true
|
||||
)
|
||||
const canForceHandoff = computed(
|
||||
() => hasSourceRole.value && forceHandoffAction.value?.enabled === true
|
||||
)
|
||||
const forceHandoffNeedsContent = computed(
|
||||
() =>
|
||||
order.value?.handoff_status === 'pending_owner' ||
|
||||
order.value?.handoff_status === 'owner_timeout'
|
||||
)
|
||||
const canPlatformCheckoutConfirm = computed(
|
||||
() => platformCheckoutConfirmAction.value?.enabled === true
|
||||
() => hasBuyerRole.value && platformCheckoutConfirmAction.value?.enabled === true
|
||||
)
|
||||
const canPlatformCheckoutCounter = computed(
|
||||
() => platformCheckoutCounterAction.value?.enabled === true
|
||||
() => hasBuyerRole.value && platformCheckoutCounterAction.value?.enabled === true
|
||||
)
|
||||
const canPlatformCheckoutDispute = computed(
|
||||
() => platformCheckoutDisputeAction.value?.enabled === true
|
||||
() => hasBuyerRole.value && platformCheckoutDisputeAction.value?.enabled === true
|
||||
)
|
||||
const canOfflineSettlement = computed(
|
||||
() => hasSourceRole.value && offlineSettlementAction.value?.enabled === true
|
||||
)
|
||||
const canAdminCreateDispute = computed(
|
||||
() => hasBuyerRole.value && canOperate.value && !order.value?.active_dispute
|
||||
)
|
||||
const canOfflineSettlement = computed(() => offlineSettlementAction.value?.enabled === true)
|
||||
const canAdminCreateDispute = computed(() => canOperate.value && !order.value?.active_dispute)
|
||||
const isPlatformManaged = computed(
|
||||
() =>
|
||||
order.value?.handoff_mode === 'platform' || order.value?.settlement_mode === 'platform_managed'
|
||||
)
|
||||
const siteRoleLabel = computed(() => {
|
||||
if (order.value?.site_role === 'source') return '本站出货'
|
||||
if (order.value?.site_role === 'both') return '本站买卖'
|
||||
if (order.value?.site_role === 'buyer') return '本站买入'
|
||||
return ''
|
||||
})
|
||||
const offlineSettlementStatus = computed(() => order.value?.offline_settlement_status || 'none')
|
||||
// 押金暂扣:仅进行中、有实付押金、且未暂扣过的订单可暂扣。
|
||||
const depositHoldStatus = computed(() => order.value?.deposit_hold_status || 'none')
|
||||
@@ -206,11 +226,14 @@ const depositHoldAmountCent = computed(() => Number(order.value?.deposit_hold_am
|
||||
const isDepositHeld = computed(() => depositHoldStatus.value === 'held')
|
||||
const canHoldDeposit = computed(
|
||||
() =>
|
||||
hasBuyerRole.value &&
|
||||
canOperate.value &&
|
||||
depositHoldStatus.value === 'none' &&
|
||||
Number(order.value?.deposit_amount_cent || 0) > 0
|
||||
)
|
||||
const canReleaseDeposit = computed(() => isDepositHeld.value && depositHoldAmountCent.value > 0)
|
||||
const canReleaseDeposit = computed(
|
||||
() => hasBuyerRole.value && isDepositHeld.value && depositHoldAmountCent.value > 0
|
||||
)
|
||||
const depositHoldStatusLabel = computed(() => {
|
||||
switch (depositHoldStatus.value) {
|
||||
case 'held':
|
||||
@@ -369,6 +392,14 @@ const hasOwnerRentBreakdown = computed(() => ownerCoinBasePriceCent.value !== nu
|
||||
const platformFeeBreakdown = computed(() => orderPlatformFeeBreakdown(order.value))
|
||||
const fundSplitRows = computed(() => {
|
||||
if (!order.value) return []
|
||||
if (!hasBuyerRole.value && hasSourceRole.value) {
|
||||
return [
|
||||
{
|
||||
label: '本站货源结算金额',
|
||||
amountCent: order.value.source_amount_cent,
|
||||
},
|
||||
]
|
||||
}
|
||||
const rows: FundSplitRow[] = []
|
||||
rows.push(
|
||||
{ label: '预收纯币原价', amountCent: order.value.pure_coin_original_amount_cent },
|
||||
@@ -446,14 +477,15 @@ async function loadOrder() {
|
||||
loading.value = true
|
||||
try {
|
||||
order.value = await fetchAdminOrder(String(route.params.id))
|
||||
const [handoffs, events, payments] = await Promise.all([
|
||||
const [handoffs, events] = await Promise.all([
|
||||
fetchAdminHandoffRecords(String(route.params.id)),
|
||||
fetchAdminOrderProcessEvents(String(route.params.id)),
|
||||
fetchAdminPayments({ order_id: String(route.params.id) }),
|
||||
])
|
||||
handoffRecords.value = handoffs
|
||||
processEvents.value = events
|
||||
paymentRecords.value = payments.items
|
||||
paymentRecords.value = hasBuyerRole.value
|
||||
? (await fetchAdminPayments({ order_id: String(route.params.id) })).items
|
||||
: []
|
||||
await loadRefundStatus()
|
||||
} finally {
|
||||
loading.value = false
|
||||
@@ -461,6 +493,10 @@ async function loadOrder() {
|
||||
}
|
||||
|
||||
async function loadRefundStatus() {
|
||||
if (!hasBuyerRole.value) {
|
||||
refundStatus.value = null
|
||||
return
|
||||
}
|
||||
try {
|
||||
refundStatus.value = await adminRefundStatus(Number(route.params.id))
|
||||
} catch {
|
||||
@@ -1002,7 +1038,10 @@ function formatRatioNumber(value: number) {
|
||||
<div v-if="order" class="page-header-row">
|
||||
<div class="page-header">
|
||||
<p class="eyebrow">{{ order.order_no }}</p>
|
||||
<h1>订单详情</h1>
|
||||
<div class="page-title-row">
|
||||
<h1>订单详情</h1>
|
||||
<el-tag v-if="siteRoleLabel" effect="plain">{{ siteRoleLabel }}</el-tag>
|
||||
</div>
|
||||
<p>
|
||||
商品编号 {{ listingCode }} · {{ order.title }} · {{ order.server_region }} /
|
||||
{{ order.login_platform }}
|
||||
@@ -1074,7 +1113,11 @@ function formatRatioNumber(value: number) {
|
||||
<el-button type="warning" plain @click="confirmHoldDeposit"> 暂扣押金 </el-button>
|
||||
</span>
|
||||
</el-tooltip>
|
||||
<el-tooltip v-if="isDepositHeld" :content="depositReleaseActionTip" placement="top">
|
||||
<el-tooltip
|
||||
v-if="isDepositHeld && hasBuyerRole"
|
||||
:content="depositReleaseActionTip"
|
||||
placement="top"
|
||||
>
|
||||
<span>
|
||||
<el-button
|
||||
type="success"
|
||||
@@ -1086,7 +1129,7 @@ function formatRatioNumber(value: number) {
|
||||
</el-button>
|
||||
</span>
|
||||
</el-tooltip>
|
||||
<el-tooltip :content="refundActionTip" placement="top">
|
||||
<el-tooltip v-if="hasBuyerRole" :content="refundActionTip" placement="top">
|
||||
<span>
|
||||
<el-button
|
||||
type="primary"
|
||||
@@ -1264,7 +1307,7 @@ function formatRatioNumber(value: number) {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="dashboard-panel detail-panel">
|
||||
<section v-if="hasBuyerRole" class="dashboard-panel detail-panel">
|
||||
<div class="panel-heading">
|
||||
<h2>退款概况</h2>
|
||||
<el-tag :type="refundStatusType(refundStatus?.refund_status || '')" effect="light">
|
||||
@@ -1420,7 +1463,7 @@ function formatRatioNumber(value: number) {
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<AdminOrderPaymentRecords :records="paymentRecords" />
|
||||
<AdminOrderPaymentRecords v-if="hasBuyerRole" :records="paymentRecords" />
|
||||
|
||||
<section class="dashboard-panel detail-panel order-wide-panel">
|
||||
<div class="panel-heading">
|
||||
|
||||
@@ -169,6 +169,13 @@ function ownerActualIncome(row: AdminOrderListItem) {
|
||||
const value = row.owner_income_amount_cent
|
||||
return typeof value === 'number' ? value : null
|
||||
}
|
||||
|
||||
function siteRoleLabel(row: AdminOrderListItem) {
|
||||
if (row.site_role === 'source') return '本站出货'
|
||||
if (row.site_role === 'both') return '本站买卖'
|
||||
if (row.site_role === 'buyer') return '本站买入'
|
||||
return ''
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -177,7 +184,7 @@ function ownerActualIncome(row: AdminOrderListItem) {
|
||||
<div class="page-header">
|
||||
<p class="eyebrow">Orders</p>
|
||||
<h1>订单管理</h1>
|
||||
<p>查看全量订单、交接状态、金额和结算状态。</p>
|
||||
<p>查看本站买入与本站出货订单、交接状态、金额和结算状态。</p>
|
||||
</div>
|
||||
<div class="toolbar-actions">
|
||||
<el-button v-if="canReturnToWithdrawals" :icon="ArrowLeft" @click="returnToWithdrawals">
|
||||
@@ -297,6 +304,9 @@ function ownerActualIncome(row: AdminOrderListItem) {
|
||||
{{ row.order_no }}
|
||||
</RouterLink>
|
||||
<span>商品编号 {{ formatListingNo(row.listing_no, row.listing_id) }}</span>
|
||||
<el-tag v-if="siteRoleLabel(row)" size="small" effect="plain">
|
||||
{{ siteRoleLabel(row) }}
|
||||
</el-tag>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
@@ -432,6 +442,10 @@ function ownerActualIncome(row: AdminOrderListItem) {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.order-main-cell :deep(.el-tag) {
|
||||
align-self: flex-start;
|
||||
}
|
||||
|
||||
.stacked-cell strong {
|
||||
overflow: hidden;
|
||||
color: #1b2559;
|
||||
|
||||
@@ -7,6 +7,10 @@ import { getTrackCode } from '@/shared/utils/trackCode'
|
||||
|
||||
export interface Order {
|
||||
id: number
|
||||
buyer_tenant_id?: number
|
||||
source_tenant_id?: number
|
||||
payment_tenant_id?: number
|
||||
site_role?: 'buyer' | 'source' | 'both' | ''
|
||||
order_no: string
|
||||
listing_id: number
|
||||
listing_no: string
|
||||
@@ -25,6 +29,7 @@ export interface Order {
|
||||
display_amount_cent: number
|
||||
rent_amount_cent?: number
|
||||
owner_rent_amount_cent?: number
|
||||
source_amount_cent?: number
|
||||
deposit_amount_cent: number
|
||||
deposit_original_amount_cent: number
|
||||
deposit_waived_amount_cent: number
|
||||
@@ -114,6 +119,10 @@ export interface UserOrderListItem {
|
||||
// 后台订单列表返回客服需要的完整用户手机号,其余敏感字段仅在详情接口中按权限返回。
|
||||
export interface AdminOrderListItem {
|
||||
id: number
|
||||
buyer_tenant_id: number
|
||||
source_tenant_id: number
|
||||
payment_tenant_id: number
|
||||
site_role?: 'buyer' | 'source' | 'both' | ''
|
||||
order_no: string
|
||||
listing_id: number
|
||||
listing_no: string
|
||||
|
||||
Reference in New Issue
Block a user