fix(tenant): 收紧双站后台边界并补齐货架管理
This commit is contained in:
@@ -41,7 +41,7 @@ func (r *Repository) Summary(ctx context.Context) (*DashboardDTO, error) {
|
||||
|
||||
userQuery := db.Model(&model.User{})
|
||||
if tenantID > 0 {
|
||||
userQuery = userQuery.Where("tenant_id = ?", tenantID)
|
||||
userQuery = userQuery.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||
}
|
||||
if err := userQuery.Count(&metrics.TotalUsers).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -51,7 +51,8 @@ func (r *Repository) Summary(ctx context.Context) (*DashboardDTO, error) {
|
||||
}
|
||||
listingQuery := db.Model(&model.RentalListing{})
|
||||
if tenantID > 0 {
|
||||
listingQuery = listingQuery.Where("source_tenant_id = ?", tenantID)
|
||||
listingQuery = listingQuery.Where("source_tenant_id = ?", tenantID).
|
||||
Where("(distribution_site_id IS NULL OR distribution_site_id = 0)")
|
||||
}
|
||||
if err := listingQuery.Count(&metrics.TotalListings).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -72,7 +73,8 @@ func (r *Repository) Summary(ctx context.Context) (*DashboardDTO, error) {
|
||||
}
|
||||
ledgerQuery := db.Model(&model.WalletLedger{})
|
||||
if tenantID > 0 {
|
||||
ledgerQuery = ledgerQuery.Where("tenant_id = ?", tenantID)
|
||||
ledgerQuery = ledgerQuery.Where("tenant_id = ?", tenantID).
|
||||
Where("(distribution_site_id = 0 OR distribution_site_id IS NULL)")
|
||||
}
|
||||
if err := ledgerQuery.
|
||||
Select("COALESCE(SUM(amount_cent), 0)").
|
||||
@@ -88,8 +90,9 @@ func (r *Repository) Summary(ctx context.Context) (*DashboardDTO, error) {
|
||||
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)
|
||||
AND tenant_order.buyer_tenant_id = ?
|
||||
AND (tenant_order.distribution_site_id IS NULL OR tenant_order.distribution_site_id = 0)
|
||||
)`, tenantID)
|
||||
}
|
||||
if err := disputeQuery.Where("d.status IN ?", []string{"open", "processing"}).Count(&pending.Disputes).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -159,6 +162,7 @@ func (r *Repository) tenantStats(ctx context.Context, tenantID uint64, metrics M
|
||||
}
|
||||
if err := db.Table("rental_orders AS o").
|
||||
Where("o.buyer_tenant_id = ?", tenantID).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)").
|
||||
Where(tradingOrderPaidCondition).
|
||||
Select("COUNT(*) AS buyer_order_count, COALESCE(SUM(o.rent_amount_cent), 0) AS buyer_gmv_cent").
|
||||
Scan(&buyerStats).Error; err != nil {
|
||||
@@ -172,6 +176,7 @@ func (r *Repository) tenantStats(ctx context.Context, tenantID uint64, metrics M
|
||||
}
|
||||
if err := db.Table("rental_orders AS o").
|
||||
Where("o.source_tenant_id = ?", tenantID).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)").
|
||||
Where(tradingOrderPaidCondition).
|
||||
Select("COUNT(*) AS source_order_count, COALESCE(SUM(o.source_amount_cent), 0) AS source_amount_cent").
|
||||
Scan(&sourceStats).Error; err != nil {
|
||||
@@ -186,7 +191,9 @@ 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)
|
||||
return query.
|
||||
Where("(o.buyer_tenant_id = ? OR o.source_tenant_id = ?)", tenantID, tenantID).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)")
|
||||
}
|
||||
|
||||
func (r *Repository) listingDailyOverview(ctx context.Context, now time.Time, days int) (ListingDailyOverviewDTO, error) {
|
||||
@@ -223,7 +230,8 @@ func (r *Repository) listingDailyOverview(ctx context.Context, now time.Time, da
|
||||
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)
|
||||
Where("tenant_listing.source_tenant_id = ?", tenantID).
|
||||
Where("(tenant_listing.distribution_site_id IS NULL OR tenant_listing.distribution_site_id = 0)")
|
||||
}
|
||||
if err := eventQuery.Scan(&events).Error; err != nil {
|
||||
return ListingDailyOverviewDTO{}, err
|
||||
@@ -232,7 +240,8 @@ func (r *Repository) listingDailyOverview(ctx context.Context, now time.Time, da
|
||||
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)
|
||||
Where("tenant_listing.source_tenant_id = ?", tenantID).
|
||||
Where("(tenant_listing.distribution_site_id IS NULL OR tenant_listing.distribution_site_id = 0)")
|
||||
}
|
||||
if err := uploadQuery.
|
||||
Select("COALESCE(lu.matched_admin_id, 0) AS uploader_id, lu.uploader_name, lu.created_at").
|
||||
@@ -584,7 +593,11 @@ func (r *Repository) recentDisputes(ctx context.Context) ([]RecentDisputeDTO, er
|
||||
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")
|
||||
query = applyDashboardOrderScope(query, tenancy.IDFromContext(ctx))
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.
|
||||
Where("o.buyer_tenant_id = ?", tenantID).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)")
|
||||
}
|
||||
err := query.
|
||||
Order("d.id DESC").
|
||||
Limit(8).
|
||||
|
||||
@@ -411,7 +411,9 @@ func (r *Repository) dailyEstimates(ctx context.Context, query DashboardQuery) (
|
||||
Where("status NOT IN ?", nonBillableOrderStatuses()).
|
||||
Where("created_at >= ? AND created_at <= ?", query.StartDate, query.EndDate)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
orderQuery = orderQuery.Where("(buyer_tenant_id = ? OR source_tenant_id = ?)", tenantID, tenantID)
|
||||
orderQuery = orderQuery.
|
||||
Where("(buyer_tenant_id = ? OR source_tenant_id = ?)", tenantID, tenantID).
|
||||
Where("(distribution_site_id IS NULL OR distribution_site_id = 0)")
|
||||
}
|
||||
err := orderQuery.
|
||||
Group("DATE_FORMAT(created_at, '%Y-%m-%d')").
|
||||
@@ -480,7 +482,9 @@ func (r *Repository) dailySettlements(ctx context.Context, query DashboardQuery)
|
||||
Joins("LEFT JOIN (?) AS w ON w.order_id = ro.id", ownerWalletIncomeForSettledOrdersSubquery(db, query)).
|
||||
Where("ro.settled_at >= ? AND ro.settled_at <= ?", query.StartDate, query.EndDate)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
settlementQuery = settlementQuery.Where("(ro.buyer_tenant_id = ? OR ro.source_tenant_id = ?)", tenantID, tenantID)
|
||||
settlementQuery = settlementQuery.
|
||||
Where("(ro.buyer_tenant_id = ? OR ro.source_tenant_id = ?)", tenantID, tenantID).
|
||||
Where("(ro.distribution_site_id IS NULL OR ro.distribution_site_id = 0)")
|
||||
}
|
||||
err := settlementQuery.
|
||||
Group("DATE_FORMAT(ro.settled_at, '%Y-%m-%d')").
|
||||
@@ -566,7 +570,15 @@ func (r *Repository) dailyPayments(ctx context.Context, query DashboardQuery) ([
|
||||
db := r.db.WithContext(ctx)
|
||||
paymentQuery := db.Table("payment_orders AS po USE INDEX (idx_payment_orders_dashboard_created)")
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
paymentQuery = paymentQuery.Where("po.tenant_id = ?", tenantID)
|
||||
paymentQuery = paymentQuery.
|
||||
Where("po.tenant_id = ?", tenantID).
|
||||
Where(`NOT EXISTS (
|
||||
SELECT 1 FROM rental_orders AS legacy_order
|
||||
WHERE legacy_order.id = po.order_id
|
||||
AND legacy_order.distribution_site_id IS NOT NULL
|
||||
AND legacy_order.distribution_site_id > 0
|
||||
AND po.biz_type IN ?
|
||||
)`, append([]string{"order_pay"}, refundBizTypes()...))
|
||||
}
|
||||
err := paymentQuery.
|
||||
Select(`DATE_FORMAT(po.created_at, '%Y-%m-%d') AS date,
|
||||
@@ -612,7 +624,13 @@ func (r *Repository) dailyPaidOrders(ctx context.Context, query DashboardQuery)
|
||||
pickupTenantFilter := ""
|
||||
args := []any{query.StartDate, query.EndDate}
|
||||
if tenantID > 0 {
|
||||
paymentTenantFilter = " AND tenant_id = ?"
|
||||
paymentTenantFilter = ` AND tenant_id = ?
|
||||
AND (biz_type <> 'order_pay' OR NOT EXISTS (
|
||||
SELECT 1 FROM rental_orders AS legacy_order
|
||||
WHERE legacy_order.id = payment_orders.order_id
|
||||
AND legacy_order.distribution_site_id IS NOT NULL
|
||||
AND legacy_order.distribution_site_id > 0
|
||||
))`
|
||||
pickupTenantFilter = " AND 1 = 0"
|
||||
args = append(args, tenantID)
|
||||
}
|
||||
|
||||
@@ -129,7 +129,8 @@ func (r *Repository) disbursementSummary(ctx context.Context, query DashboardQue
|
||||
}
|
||||
withdrawalQuery := db.Table("withdrawal_requests")
|
||||
if tenantID > 0 {
|
||||
withdrawalQuery = withdrawalQuery.Where("tenant_id = ?", tenantID)
|
||||
withdrawalQuery = withdrawalQuery.Where("tenant_id = ?", tenantID).
|
||||
Where("distribution_site_id = 0")
|
||||
}
|
||||
if err := withdrawalQuery.Select(`
|
||||
COALESCE(SUM(CASE WHEN status = 'completed' AND paid_at >= ? AND paid_at <= ? THEN amount_cent ELSE 0 END), 0) AS paid_amount_cent,
|
||||
@@ -232,7 +233,8 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
||||
withdrawalRows := make([]dailyDisbursementSourceRow, 0)
|
||||
withdrawalQuery := db.Table("withdrawal_requests")
|
||||
if tenantID > 0 {
|
||||
withdrawalQuery = withdrawalQuery.Where("tenant_id = ?", tenantID)
|
||||
withdrawalQuery = withdrawalQuery.Where("tenant_id = ?", tenantID).
|
||||
Where("distribution_site_id = 0")
|
||||
}
|
||||
if err := withdrawalQuery.
|
||||
Select(`DATE_FORMAT(paid_at, '%Y-%m-%d') AS date,
|
||||
@@ -298,7 +300,9 @@ func applyRentalOrderTenantScope(db *gorm.DB, tenantID uint64) *gorm.DB {
|
||||
if tenantID == 0 {
|
||||
return db
|
||||
}
|
||||
return db.Where("(buyer_tenant_id = ? OR source_tenant_id = ?)", tenantID, tenantID)
|
||||
return db.
|
||||
Where("(buyer_tenant_id = ? OR source_tenant_id = ?)", tenantID, tenantID).
|
||||
Where("(distribution_site_id IS NULL OR distribution_site_id = 0)")
|
||||
}
|
||||
|
||||
type dailyDisbursementSourceRow struct {
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"hfb_sys/backend/internal/modules/realname"
|
||||
"hfb_sys/backend/internal/modules/rentergrowth"
|
||||
"hfb_sys/backend/internal/modules/wallet"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/pkg/crypto"
|
||||
|
||||
"gorm.io/gorm"
|
||||
@@ -74,6 +75,7 @@ func (r *Repository) List(ctx context.Context, page, pageSize int, query ListQue
|
||||
Joins("LEFT JOIN (SELECT renter_id AS user_id, SUM(deposit_waived_amount_cent) AS deposit_free_used_cent FROM rental_orders WHERE status NOT IN ('completed', 'cancelled', 'closed') GROUP BY renter_id) AS df ON df.user_id = u.id").
|
||||
Joins("LEFT JOIN wallet_accounts AS w ON w.user_id = u.id AND w.distribution_site_id = 0")
|
||||
listTx = applyUserFilter(listTx, query, growthConfig)
|
||||
listTx = applyUserContextScope(ctx, listTx, "u")
|
||||
err = listTx.
|
||||
Order("u.id DESC").
|
||||
Offset(offset).Limit(pageSize).
|
||||
@@ -89,6 +91,7 @@ func (r *Repository) List(ctx context.Context, page, pageSize int, query ListQue
|
||||
} else {
|
||||
countTx := applyUserFilter(r.db.WithContext(ctx).Table("users AS u").
|
||||
Joins("LEFT JOIN tenants AS t ON t.id = u.tenant_id"), query, growthConfig)
|
||||
countTx = applyUserContextScope(ctx, countTx, "u")
|
||||
if err := countTx.Count(&total).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -101,6 +104,28 @@ func (r *Repository) List(ctx context.Context, page, pageSize int, query ListQue
|
||||
return &PaginatedResult{Items: items, Total: total, Page: page, PageSize: pageSize}, nil
|
||||
}
|
||||
|
||||
// applyUserContextScope 将经营站点后台固定到当前租户及其本站用户。
|
||||
// 历史分销用户虽回填到大锤租户,但仍通过 distribution_site_id 保留渠道归属。
|
||||
func applyUserContextScope(ctx context.Context, db *gorm.DB, alias string) *gorm.DB {
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID == 0 {
|
||||
return db
|
||||
}
|
||||
column := "tenant_id"
|
||||
siteColumn := "distribution_site_id"
|
||||
if alias != "" {
|
||||
column = alias + "." + column
|
||||
siteColumn = alias + "." + siteColumn
|
||||
}
|
||||
return db.Where(column+" = ?", tenantID).Where(siteColumn + " = 0")
|
||||
}
|
||||
|
||||
func lockScopedUser(ctx context.Context, tx *gorm.DB, userID uint64, user *model.User) error {
|
||||
return applyUserContextScope(ctx, tx, "").
|
||||
Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
First(user, userID).Error
|
||||
}
|
||||
|
||||
// applyUserFilter 将列表筛选条件应用到查询(基于 users 表别名 u)。
|
||||
func applyUserFilter(tx *gorm.DB, query ListQuery, growthConfig rentergrowth.Config) *gorm.DB {
|
||||
if query.Status != "" {
|
||||
@@ -208,7 +233,7 @@ func (r *Repository) SetDepositFreeQuota(ctx context.Context, adminID uint64, us
|
||||
}
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := lockScopedUser(ctx, tx, userID, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
beforeAmountCent := user.DepositFreeQuotaCent
|
||||
@@ -231,7 +256,7 @@ func (r *Repository) SetDepositFreeQuota(ctx context.Context, adminID uint64, us
|
||||
func (r *Repository) AdjustGrowthPoints(ctx context.Context, adminID uint64, userID uint64, req GrowthPointsAdjustRequest, meta AuditMeta) (*UserDTO, error) {
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := lockScopedUser(ctx, tx, userID, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
if user.RenterGrowthPoints == req.TargetPoints {
|
||||
@@ -298,7 +323,7 @@ func (r *Repository) AdjustGrowthPoints(ctx context.Context, adminID uint64, use
|
||||
func (r *Repository) AdjustGrowthLevel(ctx context.Context, adminID uint64, userID uint64, req GrowthLevelAdjustRequest, meta AuditMeta) (*UserDTO, error) {
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := lockScopedUser(ctx, tx, userID, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
cfg, err := rentergrowth.ConfigForTx(tx)
|
||||
@@ -349,7 +374,7 @@ func (r *Repository) updateStatus(ctx context.Context, adminID uint64, userID ui
|
||||
statusChanged := false
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := lockScopedUser(ctx, tx, userID, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
beforeStatus := user.Status
|
||||
@@ -389,7 +414,7 @@ func (r *Repository) updateStatus(ctx context.Context, adminID uint64, userID ui
|
||||
func (r *Repository) RevokeRealname(ctx context.Context, adminID uint64, userID uint64, req RevokeRealnameRequest, meta AuditMeta) (*UserDTO, error) {
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := lockScopedUser(ctx, tx, userID, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
var realnameCount int64
|
||||
@@ -457,7 +482,7 @@ func (r *Repository) ManualRealname(ctx context.Context, adminID uint64, userID
|
||||
|
||||
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := lockScopedUser(ctx, tx, userID, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
if user.RealnameStatus == "verified" {
|
||||
@@ -533,7 +558,7 @@ func (r *Repository) Find(ctx context.Context, userID uint64) (*UserDTO, error)
|
||||
return nil, err
|
||||
}
|
||||
var row userRow
|
||||
err = r.db.WithContext(ctx).Table("users AS u").
|
||||
query := r.db.WithContext(ctx).Table("users AS u").
|
||||
Select(`u.*, COALESCE(t.code, '') AS tenant_code, COALESCE(t.name, '') AS tenant_name,
|
||||
COALESCE(o.order_count, 0) AS order_count,
|
||||
COALESCE(l.listing_count, 0) AS listing_count,
|
||||
@@ -547,8 +572,9 @@ func (r *Repository) Find(ctx context.Context, userID uint64) (*UserDTO, error)
|
||||
Joins("LEFT JOIN (SELECT user_id, COUNT(*) AS dispute_count FROM (SELECT initiator_id AS user_id FROM disputes UNION ALL SELECT target_user_id AS user_id FROM disputes) AS dispute_users GROUP BY user_id) AS d ON d.user_id = u.id").
|
||||
Joins("LEFT JOIN (SELECT renter_id AS user_id, SUM(deposit_waived_amount_cent) AS deposit_free_used_cent FROM rental_orders WHERE status NOT IN ('completed', 'cancelled', 'closed') GROUP BY renter_id) AS df ON df.user_id = u.id").
|
||||
Joins("LEFT JOIN wallet_accounts AS w ON w.user_id = u.id AND w.distribution_site_id = 0").
|
||||
Where("u.id = ?", userID).
|
||||
First(&row).Error
|
||||
Where("u.id = ?", userID)
|
||||
query = applyUserContextScope(ctx, query, "u")
|
||||
err = query.First(&row).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -581,7 +607,7 @@ func (r *Repository) AdjustWallet(ctx context.Context, adminID uint64, userID ui
|
||||
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := lockScopedUser(ctx, tx, userID, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package adminuser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -8,10 +9,15 @@ import (
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/rentergrowth"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func adminUserTenantContext(tenantID uint64) context.Context {
|
||||
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
|
||||
}
|
||||
|
||||
func TestDepositFreeQuotaAmountCent(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -578,6 +584,45 @@ func TestFreezeAndUnfreezeBumpUserTokenVersion(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserAdminIsScopedToCurrentTenantAndOperatingUsers(t *testing.T) {
|
||||
db := setupAdminUserTestDB(t)
|
||||
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: "13700000101", Status: "active"},
|
||||
{TenantID: 101, Phone: "13700000102", Status: "active", DistributionSiteID: 999},
|
||||
{TenantID: 202, Phone: "13700000201", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&users).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
ctx := adminUserTenantContext(101)
|
||||
|
||||
result, err := repo.List(ctx, 1, 20, ListQuery{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items := result.Items.([]UserDTO)
|
||||
if result.Total != 1 || len(items) != 1 || items[0].ID != users[0].ID {
|
||||
t.Fatalf("tenant user list = %+v", result)
|
||||
}
|
||||
if _, err := repo.Find(ctx, users[2].ID); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("cross-tenant user detail error = %v", err)
|
||||
}
|
||||
if _, err := repo.Freeze(ctx, 9, users[2].ID, FreezeRequest{Reason: "越权测试"}, AuditMeta{}); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("cross-tenant user freeze error = %v", err)
|
||||
}
|
||||
if _, err := repo.Find(ctx, users[1].ID); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("legacy distribution user detail error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func setupAdminUserTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db := database.NewTestDB()
|
||||
|
||||
@@ -38,6 +38,9 @@ func (r *Repository) Arbitrate(ctx context.Context, adminID uint64, id uint64, r
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&order, row.OrderID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if !currentTenantCanAdminDisputeOrder(ctx, order.BuyerTenantID, order.DistributionSiteID) {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
var listing model.RentalListing
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&listing, order.ListingID).Error; err != nil {
|
||||
return err
|
||||
|
||||
@@ -171,6 +171,9 @@ func (r *Repository) AdminCreateByOrder(ctx context.Context, adminID uint64, ord
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&order, orderID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if !currentTenantCanAdminDisputeOrder(ctx, order.BuyerTenantID, order.DistributionSiteID) {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
if order.Status == "completed" || order.Status == "cancelled" || order.Status == "closed" {
|
||||
return ErrInvalidDispute
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -48,7 +50,7 @@ func (r *Repository) ListAdmin(ctx context.Context, query AdminListQuery) (*Pagi
|
||||
offset := (page - 1) * pageSize
|
||||
|
||||
var rows []disputeRow
|
||||
err := applyAdminListFilters(r.baseQuery(ctx), query).
|
||||
err := applyAdminListFilters(r.adminScopedBaseQuery(ctx), query).
|
||||
Order("d.id DESC").
|
||||
Offset(offset).
|
||||
Limit(pageSize).
|
||||
@@ -72,7 +74,7 @@ func (r *Repository) ListAdmin(ctx context.Context, query AdminListQuery) (*Pagi
|
||||
|
||||
func (r *Repository) FindAdminByID(ctx context.Context, id uint64) (*DisputeDTO, error) {
|
||||
var row disputeRow
|
||||
if err := r.baseQuery(ctx).Where("d.id = ?", id).First(&row).Error; err != nil {
|
||||
if err := r.adminScopedBaseQuery(ctx).Where("d.id = ?", id).First(&row).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dto := row.toDTO()
|
||||
@@ -105,6 +107,30 @@ func (r *Repository) baseQuery(ctx context.Context) *gorm.DB {
|
||||
CASE WHEN c.deposit_deduct_amount_cent > 0 THEN c.deposit_deduct_amount_cent ELSE c.other_amount_cent END AS checkout_deposit_deduct_amount_cent`)
|
||||
}
|
||||
|
||||
func (r *Repository) adminScopedBaseQuery(ctx context.Context) *gorm.DB {
|
||||
return applyAdminDisputeTenantScope(ctx, r.baseQuery(ctx))
|
||||
}
|
||||
|
||||
func applyAdminDisputeTenantScope(ctx context.Context, db *gorm.DB) *gorm.DB {
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID == 0 {
|
||||
return db
|
||||
}
|
||||
return db.Where("o.buyer_tenant_id = ?", tenantID).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)")
|
||||
}
|
||||
|
||||
func currentTenantCanAdminDisputeOrder(ctx context.Context, orderBuyerTenantID uint64, distributionSiteID *uint64) bool {
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID == 0 {
|
||||
return true
|
||||
}
|
||||
if orderBuyerTenantID != tenantID {
|
||||
return false
|
||||
}
|
||||
return distributionSiteID == nil || *distributionSiteID == 0
|
||||
}
|
||||
|
||||
func (r *Repository) adminFilterQuery(ctx context.Context) *gorm.DB {
|
||||
return r.db.WithContext(ctx).Table("disputes AS d").
|
||||
Joins("JOIN rental_orders AS o ON o.id = d.order_id").
|
||||
@@ -116,29 +142,7 @@ func (r *Repository) adminFilterQuery(ctx context.Context) *gorm.DB {
|
||||
}
|
||||
|
||||
func (r *Repository) adminDisputeCountQuery(ctx context.Context, query AdminListQuery) *gorm.DB {
|
||||
kw := strings.TrimSpace(query.Keyword)
|
||||
if kw == "" {
|
||||
return r.db.WithContext(ctx).Table("disputes AS d")
|
||||
}
|
||||
upper := strings.ToUpper(kw)
|
||||
if id, err := strconv.ParseUint(kw, 10, 64); err == nil && id > 0 && kw[0] != '0' && id < 100000000 {
|
||||
return r.db.WithContext(ctx).Table("disputes AS d").
|
||||
Joins("JOIN rental_orders AS o ON o.id = d.order_id")
|
||||
}
|
||||
if strings.HasPrefix(upper, "RO") || strings.HasPrefix(upper, "ORD") {
|
||||
return r.db.WithContext(ctx).Table("disputes AS d").
|
||||
Joins("JOIN rental_orders AS o ON o.id = d.order_id")
|
||||
}
|
||||
if strings.HasPrefix(upper, "L") || (len(kw) >= 12 && isAllDigits(kw)) {
|
||||
return r.db.WithContext(ctx).Table("disputes AS d").
|
||||
Joins("JOIN rental_orders AS o ON o.id = d.order_id").
|
||||
Joins("JOIN rental_listings AS l ON l.id = o.listing_id")
|
||||
}
|
||||
if isPhoneKeyword(kw) {
|
||||
return r.db.WithContext(ctx).Table("disputes AS d").
|
||||
Joins("JOIN rental_orders AS o ON o.id = d.order_id")
|
||||
}
|
||||
return r.adminFilterQuery(ctx)
|
||||
return applyAdminDisputeTenantScope(ctx, r.adminFilterQuery(ctx))
|
||||
}
|
||||
|
||||
func applyAdminListFilters(db *gorm.DB, query AdminListQuery) *gorm.DB {
|
||||
|
||||
@@ -3,6 +3,7 @@ package dispute
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -12,6 +13,7 @@ import (
|
||||
"hfb_sys/backend/internal/model"
|
||||
ordermodule "hfb_sys/backend/internal/modules/order"
|
||||
"hfb_sys/backend/internal/modules/wallet"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/gorm"
|
||||
@@ -56,11 +58,15 @@ func setupDisputeTestDB(t *testing.T) *gorm.DB {
|
||||
|
||||
func createDisputeOrderFixture(t *testing.T, db *gorm.DB, order model.RentalOrder) (model.User, model.User, model.RentalOrder) {
|
||||
t.Helper()
|
||||
owner := model.User{Phone: "13800000001"}
|
||||
var userCount int64
|
||||
if err := db.Model(&model.User{}).Count(&userCount).Error; err != nil {
|
||||
t.Fatalf("统计用户失败: %v", err)
|
||||
}
|
||||
owner := model.User{Phone: fmt.Sprintf("138%08d", userCount*2+1)}
|
||||
if err := db.Create(&owner).Error; err != nil {
|
||||
t.Fatalf("创建号主失败: %v", err)
|
||||
}
|
||||
renter := model.User{Phone: "13800000002"}
|
||||
renter := model.User{Phone: fmt.Sprintf("138%08d", userCount*2+2)}
|
||||
if err := db.Create(&renter).Error; err != nil {
|
||||
t.Fatalf("创建租客失败: %v", err)
|
||||
}
|
||||
@@ -74,6 +80,7 @@ func createDisputeOrderFixture(t *testing.T, db *gorm.DB, order model.RentalOrde
|
||||
t.Fatalf("创建账号失败: %v", err)
|
||||
}
|
||||
listing := model.RentalListing{
|
||||
ListingNo: fmt.Sprintf("L-DISPUTE-%d", userCount/2+1),
|
||||
AccountID: account.ID,
|
||||
OwnerID: owner.ID,
|
||||
PriceCent: 1000,
|
||||
@@ -84,7 +91,9 @@ func createDisputeOrderFixture(t *testing.T, db *gorm.DB, order model.RentalOrde
|
||||
if err := db.Create(&listing).Error; err != nil {
|
||||
t.Fatalf("创建商品失败: %v", err)
|
||||
}
|
||||
order.OrderNo = "RO202606130001"
|
||||
if order.OrderNo == "" {
|
||||
order.OrderNo = "RO202606130001"
|
||||
}
|
||||
order.ListingID = listing.ID
|
||||
order.AccountID = account.ID
|
||||
order.OwnerID = owner.ID
|
||||
@@ -812,6 +821,53 @@ func TestApplyAdminListFiltersSmartRouting(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminDisputeQueriesAndActionsAreScopedByBuyerTenant(t *testing.T) {
|
||||
db := setupDisputeTestDB(t)
|
||||
tenantA := model.Tenant{ID: 101, Code: "tenant_a", Name: "A站", Status: "active"}
|
||||
tenantB := model.Tenant{ID: 202, Code: "tenant_b", Name: "B站", Status: "active"}
|
||||
if err := db.Create(&tenantA).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&tenantB).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _, orderA := createDisputeOrderFixture(t, db, model.RentalOrder{
|
||||
OrderNo: "RO-DISPUTE-TENANT-A", BuyerTenantID: 101, SourceTenantID: 202, Status: "renting",
|
||||
})
|
||||
_, _, orderB := createDisputeOrderFixture(t, db, model.RentalOrder{
|
||||
OrderNo: "RO-DISPUTE-TENANT-B", BuyerTenantID: 202, SourceTenantID: 101, Status: "renting",
|
||||
})
|
||||
disputes := []model.Dispute{
|
||||
{OrderID: orderA.ID, InitiatorID: orderA.RenterID, InitiatorType: "user", TargetUserID: orderA.OwnerID, Type: "cannot_login", Status: "open"},
|
||||
{OrderID: orderB.ID, InitiatorID: orderB.RenterID, InitiatorType: "user", TargetUserID: orderB.OwnerID, Type: "cannot_login", Status: "open"},
|
||||
}
|
||||
if err := db.Create(&disputes).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 101})
|
||||
repo := NewRepository(db)
|
||||
result, err := repo.ListAdmin(ctx, AdminListQuery{Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.Total != 1 || result.Items[0].ID != disputes[0].ID {
|
||||
t.Fatalf("tenant dispute list = %+v", result)
|
||||
}
|
||||
if _, err := repo.FindAdminByID(ctx, disputes[1].ID); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("cross-tenant dispute detail error = %v", err)
|
||||
}
|
||||
if _, err := repo.AdminCreateByOrder(ctx, 9, orderB.ID, AdminCreateRequest{
|
||||
Type: "cannot_login", Description: "越权测试", TargetRole: "owner",
|
||||
}, AuditMeta{}); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("cross-tenant admin create error = %v", err)
|
||||
}
|
||||
if _, err := repo.Arbitrate(ctx, 9, disputes[1].ID, ArbitrateRequest{
|
||||
Result: "full_refund", Remark: "越权测试",
|
||||
}, AuditMeta{}); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("cross-tenant arbitrate error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStampOwnerIncomeSiteUsesListingSite(t *testing.T) {
|
||||
siteID := uint64(3)
|
||||
orderID := uint64(9)
|
||||
|
||||
@@ -324,7 +324,7 @@ func applyTenantOfferVisibility(ctx context.Context, db *gorm.DB) *gorm.DB {
|
||||
return db.Joins(
|
||||
"INNER JOIN tenant_listing_offers AS tlo ON tlo.listing_id = l.id AND tlo.tenant_id = ? AND tlo.display_status = 'enabled'",
|
||||
tenantID,
|
||||
)
|
||||
).Where("(l.distribution_site_id IS NULL OR l.distribution_site_id = 0)")
|
||||
}
|
||||
|
||||
func (r *Repository) applyTenantOfferPrices(ctx context.Context, items []ListingDTO) error {
|
||||
|
||||
@@ -266,10 +266,14 @@ func applyListingSourceTenantScope(ctx context.Context, query *gorm.DB, alias st
|
||||
return query
|
||||
}
|
||||
column := "source_tenant_id"
|
||||
distributionColumn := "distribution_site_id"
|
||||
if alias != "" {
|
||||
column = alias + "." + column
|
||||
distributionColumn = alias + "." + distributionColumn
|
||||
}
|
||||
return query.Where(column+" = ?", tenantID)
|
||||
return query.
|
||||
Where(column+" = ?", tenantID).
|
||||
Where("(" + distributionColumn + " IS NULL OR " + distributionColumn + " = 0)")
|
||||
}
|
||||
|
||||
func (r *Repository) findForReviewUpdate(ctx context.Context, tx *gorm.DB, listingID uint64) (*model.RentalListing, *model.GameAccount, error) {
|
||||
|
||||
@@ -18,7 +18,10 @@ func (r *Repository) FindTenantOffer(ctx context.Context, listingID uint64) (*Te
|
||||
return nil, ErrTenantRequired
|
||||
}
|
||||
var listing model.RentalListing
|
||||
if err := r.db.WithContext(ctx).Select("id, price_cent").First(&listing, listingID).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).
|
||||
Select("id, price_cent").
|
||||
Where("id = ? AND (distribution_site_id IS NULL OR distribution_site_id = 0)", listingID).
|
||||
First(&listing).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var offer model.TenantListingOffer
|
||||
@@ -50,7 +53,10 @@ func (r *Repository) UpdateTenantOffer(
|
||||
return nil, ErrInvalidPrice
|
||||
}
|
||||
var listing model.RentalListing
|
||||
if err := r.db.WithContext(ctx).Select("id, price_cent").First(&listing, listingID).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).
|
||||
Select("id, price_cent").
|
||||
Where("id = ? AND (distribution_site_id IS NULL OR distribution_site_id = 0)", listingID).
|
||||
First(&listing).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrListingNotFound
|
||||
}
|
||||
|
||||
@@ -29,6 +29,13 @@ func TestPublicListingUsesCurrentTenantOffer(t *testing.T) {
|
||||
if err := db.Create(&other).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacySite := model.DistributionSite{
|
||||
ID: 999, SiteCode: "legacy_listing_offer", SiteName: "历史分销测试站",
|
||||
Domain: "legacy-listing-offer.example.com", Status: "active",
|
||||
}
|
||||
if err := db.Create(&legacySite).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner := model.User{TenantID: dachui.ID, Phone: "13100000001", Status: "active"}
|
||||
if err := db.Create(&owner).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -57,6 +64,20 @@ func TestPublicListingUsesCurrentTenantOffer(t *testing.T) {
|
||||
if err := db.Create(&offers).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacySiteID := legacySite.ID
|
||||
legacyListing := model.RentalListing{
|
||||
SourceTenantID: dachui.ID, ListingNo: "L-LEGACY-DIST",
|
||||
AccountID: account.ID, OwnerID: owner.ID, PriceCent: 9000,
|
||||
Status: "published", ReviewStatus: "approved", DistributionSiteID: &legacySiteID,
|
||||
}
|
||||
if err := db.Create(&legacyListing).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.TenantListingOffer{
|
||||
TenantID: jieyou.ID, ListingID: legacyListing.ID, DisplayStatus: "enabled",
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewRepository(db, nil)
|
||||
|
||||
dachuiResult, err := repo.ListPublic(listingTenantContext(dachui.ID), PublicListQuery{})
|
||||
|
||||
@@ -44,6 +44,9 @@ func (r *Repository) Create(ctx context.Context, renterID uint64, req CreateRequ
|
||||
if requestTenantID > 0 && renter.TenantID != requestTenantID {
|
||||
return ErrPermissionDenied
|
||||
}
|
||||
if requestTenantID > 0 && listing.DistributionSiteID != nil && *listing.DistributionSiteID > 0 {
|
||||
return ErrListingUnavailable
|
||||
}
|
||||
buyerTenantID := renter.TenantID
|
||||
if requestTenantID > 0 {
|
||||
buyerTenantID = requestTenantID
|
||||
|
||||
@@ -546,7 +546,9 @@ func applyTenantOrderScope(query *gorm.DB, ctx context.Context) *gorm.DB {
|
||||
if tenantID == 0 {
|
||||
return query
|
||||
}
|
||||
return query.Where("(o.buyer_tenant_id = ? OR o.source_tenant_id = ?)", tenantID, tenantID)
|
||||
return query.
|
||||
Where("(o.buyer_tenant_id = ? OR o.source_tenant_id = ?)", tenantID, tenantID).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)")
|
||||
}
|
||||
|
||||
func applyBuyerTenantOrderScope(query *gorm.DB, ctx context.Context) *gorm.DB {
|
||||
@@ -554,7 +556,9 @@ func applyBuyerTenantOrderScope(query *gorm.DB, ctx context.Context) *gorm.DB {
|
||||
if tenantID == 0 {
|
||||
return query
|
||||
}
|
||||
return query.Where("o.buyer_tenant_id = ?", tenantID)
|
||||
return query.
|
||||
Where("o.buyer_tenant_id = ?", tenantID).
|
||||
Where("(o.distribution_site_id IS NULL OR o.distribution_site_id = 0)")
|
||||
}
|
||||
|
||||
func tenantOrderRole(ctx context.Context, order model.RentalOrder) string {
|
||||
|
||||
@@ -229,7 +229,7 @@ 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 {
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.AdminClose(ctx, adminID, orderID, req, meta)
|
||||
@@ -255,7 +255,7 @@ 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 {
|
||||
if err := s.ensureAdminOrderCapability(ctx, orderID, tenantOrderCapabilityRefund); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.AdminSeal(ctx, adminID, orderID, req, meta)
|
||||
|
||||
@@ -180,6 +180,13 @@ func TestAdminOrdersAreScopedByCurrentTenant(t *testing.T) {
|
||||
if err := db.Create(&tenants).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacySite := model.DistributionSite{
|
||||
ID: 999, SiteCode: "legacy_ops_test", SiteName: "历史分销测试站",
|
||||
Domain: "legacy-ops-test.example.com", Status: "active",
|
||||
}
|
||||
if err := db.Create(&legacySite).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"}
|
||||
@@ -234,6 +241,13 @@ func TestAdminOrdersAreScopedByCurrentTenant(t *testing.T) {
|
||||
SourceTenantID: 303, PaymentTenantID: 101, Status: orderStatusRenting,
|
||||
},
|
||||
}
|
||||
legacySiteID := legacySite.ID
|
||||
orders = append(orders, model.RentalOrder{
|
||||
OrderNo: "RO-LEGACY-DISTRIBUTION", ListingID: listingA.ID, AccountID: accountA.ID,
|
||||
OwnerID: owner.ID, RenterID: renterA.ID, BuyerTenantID: 101,
|
||||
SourceTenantID: 101, PaymentTenantID: 101, DistributionSiteID: &legacySiteID,
|
||||
Status: orderStatusRenting,
|
||||
})
|
||||
if err := db.Create(&orders).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -268,6 +282,12 @@ func TestAdminOrdersAreScopedByCurrentTenant(t *testing.T) {
|
||||
if err := repo.EnsureAdminOrderCapability(orderTenantContext(202), orders[0].ID, tenantOrderCapabilityHandoff); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("buyer tenant handoff capability error = %v", err)
|
||||
}
|
||||
if err := service.AdminClose(orderTenantContext(101), 9, orders[0].ID, AdminActionRequest{Reason: "source close"}, AuditMeta{}); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("source tenant close capability error = %v", err)
|
||||
}
|
||||
if err := service.AdminSeal(orderTenantContext(101), 9, orders[0].ID, AdminActionRequest{Reason: "source seal"}, AuditMeta{}); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("source tenant seal capability error = %v", err)
|
||||
}
|
||||
|
||||
sourceResult, err := repo.ListAdmin(orderTenantContext(101), AdminOrderQuery{Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
|
||||
@@ -21,12 +21,13 @@ func (r *Repository) EnsureAdminOrderCapability(ctx context.Context, orderID uin
|
||||
return nil
|
||||
}
|
||||
var order struct {
|
||||
BuyerTenantID uint64
|
||||
SourceTenantID uint64
|
||||
BuyerTenantID uint64
|
||||
SourceTenantID uint64
|
||||
DistributionSiteID *uint64
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Table("rental_orders").
|
||||
Select("buyer_tenant_id, source_tenant_id").
|
||||
Select("buyer_tenant_id, source_tenant_id, distribution_site_id").
|
||||
Where("id = ?", orderID).
|
||||
Scan(&order).Error; err != nil {
|
||||
return err
|
||||
@@ -34,6 +35,9 @@ func (r *Repository) EnsureAdminOrderCapability(ctx context.Context, orderID uin
|
||||
if order.BuyerTenantID == 0 && order.SourceTenantID == 0 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
if order.DistributionSiteID != nil && *order.DistributionSiteID > 0 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
isBuyer := order.BuyerTenantID == tenantID
|
||||
isSource := order.SourceTenantID == tenantID
|
||||
if !isBuyer && !isSource {
|
||||
|
||||
@@ -54,8 +54,26 @@ func (r *Repository) AdminList(ctx context.Context, query AdminPaymentQuery) (*P
|
||||
Joins("LEFT JOIN users AS u ON u.id = p.user_id")
|
||||
countDB := r.db.WithContext(ctx).Model(&model.PaymentOrder{})
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
db = db.Where("p.tenant_id = ?", tenantID)
|
||||
countDB = countDB.Where("tenant_id = ?", tenantID)
|
||||
legacyDistributionCondition := `NOT EXISTS (
|
||||
SELECT 1 FROM rental_orders AS legacy_order
|
||||
WHERE legacy_order.id = p.order_id
|
||||
AND legacy_order.distribution_site_id IS NOT NULL
|
||||
AND legacy_order.distribution_site_id > 0
|
||||
AND p.biz_type IN ?
|
||||
)`
|
||||
orderBizTypes := append([]string{"order_pay"}, RefundBizTypes()...)
|
||||
db = db.Where("p.tenant_id = ?", tenantID).
|
||||
Where(legacyDistributionCondition, orderBizTypes)
|
||||
countDB = countDB.Where("tenant_id = ?", tenantID).Where(
|
||||
`NOT EXISTS (
|
||||
SELECT 1 FROM rental_orders AS legacy_order
|
||||
WHERE legacy_order.id = payment_orders.order_id
|
||||
AND legacy_order.distribution_site_id IS NOT NULL
|
||||
AND legacy_order.distribution_site_id > 0
|
||||
AND payment_orders.biz_type IN ?
|
||||
)`,
|
||||
orderBizTypes,
|
||||
)
|
||||
}
|
||||
if query.UserID > 0 {
|
||||
db = db.Where("p.user_id = ?", query.UserID)
|
||||
|
||||
@@ -65,6 +65,7 @@ func (r *Repository) Overview(ctx context.Context) (*OverviewDTO, error) {
|
||||
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 {
|
||||
@@ -72,6 +73,7 @@ func (r *Repository) totals(db *gorm.DB, today time.Time) (*TotalsDTO, error) {
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -89,6 +91,7 @@ func (r *Repository) totals(db *gorm.DB, today time.Time) (*TotalsDTO, error) {
|
||||
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,
|
||||
@@ -104,20 +107,27 @@ func (r *Repository) totals(db *gorm.DB, today time.Time) (*TotalsDTO, error) {
|
||||
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 {
|
||||
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,
|
||||
@@ -128,6 +138,7 @@ func (r *Repository) totals(db *gorm.DB, today time.Time) (*TotalsDTO, error) {
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -141,14 +152,16 @@ func (r *Repository) siteStats(db *gorm.DB, tenant model.Tenant, today time.Time
|
||||
TenantName: tenant.Name,
|
||||
Status: tenant.Status,
|
||||
}
|
||||
if err := db.Table("users").Where("tenant_id = ?", tenant.ID).
|
||||
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).
|
||||
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,
|
||||
@@ -167,6 +180,7 @@ func (r *Repository) siteStats(db *gorm.DB, tenant model.Tenant, today time.Time
|
||||
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,
|
||||
@@ -185,7 +199,9 @@ func (r *Repository) siteStats(db *gorm.DB, tenant model.Tenant, today time.Time
|
||||
result.RentingOrders = orderStats.RentingOrders
|
||||
result.TodayOrders = orderStats.TodayOrders
|
||||
result.TodayGMVCent = orderStats.TodayGMVCent
|
||||
if err := db.Table("wallet_ledger").Where("tenant_id = ?", tenant.ID).
|
||||
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,
|
||||
@@ -194,7 +210,9 @@ func (r *Repository) siteStats(db *gorm.DB, tenant model.Tenant, today time.Time
|
||||
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).
|
||||
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
|
||||
@@ -218,6 +236,7 @@ func (r *Repository) trend(db *gorm.DB, now time.Time, days int) ([]TrendPointDT
|
||||
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
|
||||
@@ -230,6 +249,7 @@ func (r *Repository) trend(db *gorm.DB, now time.Time, days int) ([]TrendPointDT
|
||||
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
|
||||
@@ -244,6 +264,7 @@ func (r *Repository) trend(db *gorm.DB, now time.Time, days int) ([]TrendPointDT
|
||||
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
|
||||
@@ -258,6 +279,7 @@ func (r *Repository) trend(db *gorm.DB, now time.Time, days int) ([]TrendPointDT
|
||||
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
|
||||
|
||||
@@ -97,8 +97,64 @@ func TestOverviewAggregatesAllTenantsAndSites(t *testing.T) {
|
||||
if err := db.Create(&withdrawals).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacySite := model.DistributionSite{
|
||||
SiteCode: "legacy_platform_ops", SiteName: "历史分销测试站",
|
||||
Domain: "legacy-platform-ops.example.com", Status: "active",
|
||||
}
|
||||
if err := db.Create(&legacySite).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacyUser := model.User{
|
||||
TenantID: tenants[0].ID, Phone: "13100000999", Status: "active",
|
||||
DistributionSiteID: legacySite.ID,
|
||||
}
|
||||
if err := db.Create(&legacyUser).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacyAccount := model.GameAccount{
|
||||
SourceTenantID: tenants[0].ID, OwnerID: legacyUser.ID,
|
||||
GameName: "delta_force", ServerRegion: "国服", LoginPlatform: "QQ",
|
||||
Title: "历史分销商品", Status: "published",
|
||||
}
|
||||
if err := db.Create(&legacyAccount).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacyListing := model.RentalListing{
|
||||
SourceTenantID: tenants[0].ID, ListingNo: "OPS-LEGACY-DIST",
|
||||
AccountID: legacyAccount.ID, OwnerID: legacyUser.ID,
|
||||
Status: "published", ReviewStatus: "approved", PriceCent: 5000,
|
||||
DistributionSiteID: &legacySite.ID,
|
||||
}
|
||||
if err := db.Create(&legacyListing).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacyOrder := model.RentalOrder{
|
||||
OrderNo: "OPS-LEGACY-ORDER", BuyerTenantID: tenants[0].ID,
|
||||
SourceTenantID: tenants[0].ID, PaymentTenantID: tenants[0].ID,
|
||||
ListingID: legacyListing.ID, AccountID: legacyAccount.ID,
|
||||
OwnerID: legacyUser.ID, RenterID: legacyUser.ID,
|
||||
Status: "completed", RentAmountCent: 5000, SourceAmountCent: 4000,
|
||||
DistributionSiteID: &legacySite.ID,
|
||||
}
|
||||
if err := db.Create(&legacyOrder).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.WalletLedger{
|
||||
LedgerNo: "OPS-LEGACY-WL", TenantID: tenants[0].ID, UserID: legacyUser.ID,
|
||||
DistributionSiteID: legacySite.ID, Direction: "in", AmountCent: 5000,
|
||||
BalanceType: "available", BizType: "owner_income", BizNo: legacyOrder.OrderNo,
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.WithdrawalRequest{
|
||||
WithdrawNo: "OPS-LEGACY-WD", TenantID: tenants[0].ID, UserID: legacyUser.ID,
|
||||
DistributionSiteID: legacySite.ID, AmountCent: 500, ActualAmountCent: 500,
|
||||
AccountType: "bank", AccountName: "历史站用户", AccountNo: "****9999", Status: "pending",
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var userCount int64
|
||||
if err := db.Model(&model.User{}).Count(&userCount).Error; err != nil || userCount != 4 {
|
||||
if err := db.Model(&model.User{}).Count(&userCount).Error; err != nil || userCount != 5 {
|
||||
t.Fatalf("seeded users = %d, err=%v", userCount, err)
|
||||
}
|
||||
|
||||
|
||||
@@ -80,13 +80,15 @@ func (r *Repository) Status(ctx context.Context, userID uint64) (*StatusDTO, err
|
||||
return nil, err
|
||||
}
|
||||
var user model.User
|
||||
if err := r.db.WithContext(ctx).First(&user, userID).Error; err != nil {
|
||||
if err := loadQualityOwnerUser(ctx, r.db.WithContext(ctx), userID, false, &user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var account model.WalletAccount
|
||||
walletErr := r.db.WithContext(ctx).
|
||||
Where("user_id = ? AND distribution_site_id = 0", userID).
|
||||
First(&account).Error
|
||||
accountQuery := r.db.WithContext(ctx).Where("user_id = ? AND distribution_site_id = 0", userID)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
accountQuery = accountQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
walletErr := accountQuery.First(&account).Error
|
||||
if walletErr != nil && !errors.Is(walletErr, gorm.ErrRecordNotFound) {
|
||||
return nil, walletErr
|
||||
}
|
||||
@@ -107,7 +109,7 @@ func (r *Repository) PaymentAmount(ctx context.Context, userID uint64) (int64, b
|
||||
return 0, false, ErrInvalidUser
|
||||
}
|
||||
var user model.User
|
||||
if err := r.db.WithContext(ctx).First(&user, userID).Error; err != nil {
|
||||
if err := loadQualityOwnerUser(ctx, r.db.WithContext(ctx), userID, false, &user); err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
if user.QualityOwnerStatus == StatusActive {
|
||||
@@ -130,8 +132,12 @@ func (r *Repository) ConfirmQualityOwnerDepositPaidTx(tx *gorm.DB, userID uint64
|
||||
if tx == nil || userID == 0 || amountCent <= 0 || paymentNo == "" {
|
||||
return ErrInvalidUser
|
||||
}
|
||||
ctx := tx.Statement.Context
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := loadQualityOwnerUser(ctx, tx, userID, true, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
var appliedCount int64
|
||||
@@ -208,7 +214,7 @@ func (r *Repository) Activate(ctx context.Context, userID uint64) (*StatusDTO, e
|
||||
}
|
||||
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := loadQualityOwnerUser(ctx, tx, userID, true, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
if user.RealnameStatus != "verified" {
|
||||
@@ -303,7 +309,7 @@ func (r *Repository) Cancel(ctx context.Context, userID uint64, meta AuditMeta)
|
||||
}
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := loadQualityOwnerUser(ctx, tx, userID, true, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
if user.QualityOwnerStatus != StatusActive {
|
||||
@@ -358,7 +364,7 @@ func (r *Repository) AdminSet(ctx context.Context, adminID uint64, userID uint64
|
||||
}
|
||||
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var user model.User
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
|
||||
if err := loadQualityOwnerUser(ctx, tx, userID, true, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
beforeStatus := user.QualityOwnerStatus
|
||||
@@ -414,6 +420,17 @@ func (r *Repository) AdminSet(ctx context.Context, adminID uint64, userID uint64
|
||||
return r.Status(ctx, userID)
|
||||
}
|
||||
|
||||
func loadQualityOwnerUser(ctx context.Context, db *gorm.DB, userID uint64, lock bool, user *model.User) error {
|
||||
query := db.Model(&model.User{})
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||
}
|
||||
if lock {
|
||||
query = query.Clauses(clause.Locking{Strength: "UPDATE"})
|
||||
}
|
||||
return query.First(user, userID).Error
|
||||
}
|
||||
|
||||
func activePremiumListingCount(db *gorm.DB, userID uint64) (int64, error) {
|
||||
var count int64
|
||||
err := db.Model(&model.RentalListing{}).
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package qualityowner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestAdminSetRejectsCrossTenantUser(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
tenants := []model.Tenant{
|
||||
{ID: 101, Code: "quality_tenant_a", Name: "A站", Status: "active"},
|
||||
{ID: 202, Code: "quality_tenant_b", Name: "B站", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&tenants).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
user := model.User{TenantID: 202, Phone: "13600000202", Status: "active"}
|
||||
if err := db.Create(&user).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 101})
|
||||
repo := NewRepository(db)
|
||||
if _, err := repo.AdminSet(ctx, 9, user.ID, AdminSetRequest{
|
||||
Enabled: true,
|
||||
Reason: "跨站越权测试",
|
||||
}, AuditMeta{}); !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
t.Fatalf("cross-tenant quality owner error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -166,8 +166,10 @@ func (r *Repository) AdminLedger(ctx context.Context, query AdminLedgerQuery) (*
|
||||
|
||||
countDB := r.db.WithContext(ctx).Model(&model.WalletLedger{})
|
||||
if tenantID > 0 {
|
||||
db = db.Where("wl.tenant_id = ?", tenantID)
|
||||
countDB = countDB.Where("tenant_id = ?", tenantID)
|
||||
db = db.Where("wl.tenant_id = ?", tenantID).
|
||||
Where("(wl.distribution_site_id = 0 OR wl.distribution_site_id IS NULL)")
|
||||
countDB = countDB.Where("tenant_id = ?", tenantID).
|
||||
Where("(distribution_site_id = 0 OR distribution_site_id IS NULL)")
|
||||
}
|
||||
if query.UserID > 0 {
|
||||
db = db.Where("wl.user_id = ?", query.UserID)
|
||||
|
||||
@@ -18,7 +18,8 @@ import (
|
||||
func (r *Repository) AdminList(ctx context.Context, query AdminListQuery) (*AdminPaginatedResult, error) {
|
||||
db := r.db.WithContext(ctx).Model(&model.WithdrawalRequest{})
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
db = db.Where("tenant_id = ?", tenantID)
|
||||
db = db.Where("tenant_id = ?", tenantID).
|
||||
Where("distribution_site_id = 0")
|
||||
}
|
||||
|
||||
if query.Status != "" {
|
||||
|
||||
Reference in New Issue
Block a user