fix(distribution): 统一分销订单租户管理口径

This commit is contained in:
yml
2026-11-24 22:12:52 +08:00
parent 3ac4052ac5
commit 3cc61615f9
20 changed files with 462 additions and 101 deletions
@@ -92,7 +92,6 @@ func (r *Repository) Summary(ctx context.Context) (*DashboardDTO, error) {
SELECT 1 FROM rental_orders AS tenant_order
WHERE tenant_order.id = d.order_id
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 {
@@ -163,7 +162,6 @@ 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 {
@@ -177,7 +175,6 @@ 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 {
@@ -193,8 +190,7 @@ func applyDashboardOrderScope(query *gorm.DB, tenantID uint64) *gorm.DB {
return query
}
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)")
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) {
@@ -597,8 +593,7 @@ func (r *Repository) recentDisputes(ctx context.Context) ([]RecentDisputeDTO, er
Joins("JOIN game_accounts AS a ON a.id = o.account_id")
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)")
Where("o.buyer_tenant_id = ?", tenantID)
}
err := query.
Order("d.id DESC").
@@ -86,6 +86,13 @@ func TestSummaryScopesBuyerAndSourceMetricsByTenant(t *testing.T) {
if err := db.Create(&listingB).Error; err != nil {
t.Fatal(err)
}
site := model.DistributionSite{
SiteCode: "dashboard_shared_dist", SiteName: "看板共享货源站",
Domain: "dashboard-shared.example.com", Status: "active",
}
if err := db.Create(&site).Error; err != nil {
t.Fatal(err)
}
orders := []model.RentalOrder{
{
OrderNo: "RO-DASHBOARD-A-BUY", ListingID: listingB.ID, AccountID: accountB.ID,
@@ -99,10 +106,23 @@ func TestSummaryScopesBuyerAndSourceMetricsByTenant(t *testing.T) {
SourceTenantID: 101, PaymentTenantID: 202, RentAmountCent: 3000,
OwnerRentAmountCent: 1800, SourceAmountCent: 1800, Status: "completed",
},
{
OrderNo: "RO-DASHBOARD-A-SHARED", ListingID: listingB.ID, AccountID: accountB.ID,
OwnerID: users[2].ID, RenterID: users[0].ID, BuyerTenantID: 101,
SourceTenantID: 202, PaymentTenantID: 101, RentAmountCent: 4000,
OwnerRentAmountCent: 2600, SourceAmountCent: 2600, Status: "completed",
DistributionSiteID: &site.ID, DistributionMode: "two_party_distributor_receive",
},
}
if err := db.Create(&orders).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&model.Dispute{
OrderID: orders[2].ID, InitiatorID: users[0].ID, InitiatorType: "user",
TargetUserID: users[2].ID, Type: "cannot_login", Status: "open",
}).Error; err != nil {
t.Fatal(err)
}
summary, err := NewRepository(db).Summary(dashboardTenantContext(101))
if err != nil {
@@ -114,18 +134,22 @@ func TestSummaryScopesBuyerAndSourceMetricsByTenant(t *testing.T) {
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.Metrics.TotalOrders != 3 {
t.Fatalf("tenant relevant order count = %d, want 3", summary.Metrics.TotalOrders)
}
if summary.Tenant == nil {
t.Fatal("tenant statistics missing")
}
if summary.Tenant.BuyerOrderCount != 1 || summary.Tenant.BuyerGMVCent != 2500 {
if summary.Tenant.BuyerOrderCount != 2 || summary.Tenant.BuyerGMVCent != 6500 {
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)
}
if summary.Pending.Disputes != 1 || len(summary.RecentDisputes) != 1 {
t.Fatalf("distribution disputes missing from tenant dashboard: pending=%+v recent=%+v",
summary.Pending, summary.RecentDisputes)
}
}
func TestSummaryPendingReviewsIncludeTenantDistributionSites(t *testing.T) {
@@ -426,8 +426,7 @@ func (r *Repository) dailyEstimates(ctx context.Context, query DashboardQuery) (
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).
Where("(distribution_site_id IS NULL OR distribution_site_id = 0)")
Where("(buyer_tenant_id = ? OR source_tenant_id = ?)", tenantID, tenantID)
}
err := orderQuery.
Group("DATE_FORMAT(created_at, '%Y-%m-%d')").
@@ -497,8 +496,7 @@ func (r *Repository) dailySettlements(ctx context.Context, query DashboardQuery)
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).
Where("(ro.distribution_site_id IS NULL OR ro.distribution_site_id = 0)")
Where("(ro.buyer_tenant_id = ? OR ro.source_tenant_id = ?)", tenantID, tenantID)
}
err := settlementQuery.
Group("DATE_FORMAT(ro.settled_at, '%Y-%m-%d')").
@@ -584,15 +582,7 @@ 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).
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()...))
paymentQuery = paymentQuery.Where("po.tenant_id = ?", tenantID)
}
err := paymentQuery.
Select(`DATE_FORMAT(po.created_at, '%Y-%m-%d') AS date,
@@ -637,13 +627,7 @@ func (r *Repository) dailyPaidOrders(ctx context.Context, query DashboardQuery)
pickupTenantFilter := ""
args := []any{query.StartDate, query.EndDate}
if tenantID > 0 {
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
))`
paymentTenantFilter = " AND tenant_id = ?"
pickupTenantFilter = " AND tenant_id = ?"
args = append(args, tenantID)
}
@@ -308,8 +308,7 @@ func applyRentalOrderTenantScope(db *gorm.DB, tenantID uint64) *gorm.DB {
return db
}
return db.
Where("(buyer_tenant_id = ? OR source_tenant_id = ?)", tenantID, tenantID).
Where("(distribution_site_id IS NULL OR distribution_site_id = 0)")
Where("(buyer_tenant_id = ? OR source_tenant_id = ?)", tenantID, tenantID)
}
type dailyDisbursementSourceRow struct {
@@ -100,8 +100,7 @@ func (r *Repository) disbursementListBaseQuery(ctx context.Context, phoneKeyword
Where("ro.offline_settlement_amount_cent > 0")
if tenantID > 0 {
platformManaged = platformManaged.
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)")
Where("(ro.buyer_tenant_id = ? OR ro.source_tenant_id = ?)", tenantID, tenantID)
}
pickupManaged := db.Table("admin_pickups AS ap").
@@ -18,6 +18,21 @@ func financeTenantContext(tenantID uint64) context.Context {
func TestFinancePaymentStatsAreScopedByTenant(t *testing.T) {
db := database.NewTestDB()
now := time.Now()
site := model.DistributionSite{
SiteCode: "finance_scope_dist", SiteName: "财务归属测试站",
Domain: "finance-scope.example.com", Status: "active",
}
if err := db.Create(&site).Error; err != nil {
t.Fatal(err)
}
order := model.RentalOrder{
OrderNo: "RO-FIN-DISTRIBUTION", BuyerTenantID: 101, SourceTenantID: 202,
PaymentTenantID: 101, DistributionSiteID: &site.ID,
DistributionMode: "two_party_distributor_receive", Status: "completed",
}
if err := db.Create(&order).Error; err != nil {
t.Fatal(err)
}
payments := []model.PaymentOrder{
{
TenantID: 101, PaymentNo: "PAY-FIN-A", OrderID: 1, OrderNo: "RO-FIN-A",
@@ -31,6 +46,12 @@ func TestFinancePaymentStatsAreScopedByTenant(t *testing.T) {
ThirdOrderID: "PAY-FIN-B", PayWay: "ZFBZF", AmountCent: 2000,
BizType: "order_pay", Status: "paid", PaidAt: &now,
},
{
TenantID: 101, PaymentNo: "PAY-FIN-DIST", OrderID: order.ID, OrderNo: order.OrderNo,
UserID: 3, PaymentConfigID: 3, Provider: "mock", MerchantID: "DIST",
ThirdOrderID: "PAY-FIN-DIST", PayWay: "ZFBZF", AmountCent: 3000,
BizType: "order_pay", Status: "paid", PaidAt: &now,
},
}
if err := db.Create(&payments).Error; err != nil {
t.Fatal(err)
@@ -45,14 +66,80 @@ func TestFinancePaymentStatsAreScopedByTenant(t *testing.T) {
for _, row := range rows {
flow += row.TotalFlowAmountCent
}
if flow != 1000 {
t.Fatalf("dachui payment flow = %d, want 1000", flow)
if flow != 4000 {
t.Fatalf("dachui payment flow = %d, want 4000", flow)
}
if repo.dashboardCacheKey(financeTenantContext(101), query) == repo.dashboardCacheKey(financeTenantContext(202), query) {
t.Fatal("dashboard cache key must include tenant")
}
}
func TestFinanceOrderStatsIncludeDistributionOrdersForBusinessTenant(t *testing.T) {
db := database.NewTestDB()
now := time.Now()
site := model.DistributionSite{
SiteCode: "finance_order_dist", SiteName: "订单财务测试站",
Domain: "finance-order.example.com", Status: "active",
}
if err := db.Create(&site).Error; err != nil {
t.Fatal(err)
}
settledOrder := model.RentalOrder{
OrderNo: "RO-FIN-SETTLED-DIST", BuyerTenantID: 101, SourceTenantID: 202,
PaymentTenantID: 101, DistributionSiteID: &site.ID,
DistributionMode: "two_party_distributor_receive",
Status: "completed", SettlementStatus: "settled",
PlatformFeeCent: 500, SettledAt: &now,
}
if err := db.Create(&settledOrder).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&model.OrderCheckout{
OrderID: settledOrder.ID, Status: "accepted", PlatformFeeCent: 500,
}).Error; err != nil {
t.Fatal(err)
}
pendingOrder := model.RentalOrder{
OrderNo: "RO-FIN-PENDING-DIST", BuyerTenantID: 101, SourceTenantID: 202,
PaymentTenantID: 101, DistributionSiteID: &site.ID,
DistributionMode: "two_party_distributor_receive",
Status: "renting", SettlementStatus: "unsettled",
PlatformFeeCent: 300,
}
if err := db.Create(&pendingOrder).Error; err != nil {
t.Fatal(err)
}
repo := NewRepository(db)
ctx := financeTenantContext(101)
query := DashboardQuery{StartDate: now.Add(-time.Hour), EndDate: now.Add(time.Hour)}
estimates, err := repo.dailyEstimates(ctx, query)
if err != nil {
t.Fatal(err)
}
var pendingCount, estimatedCent int64
for _, row := range estimates {
pendingCount += row.PendingSettleOrderCount
estimatedCent += row.EstimatedIncomeAmountCent
}
if pendingCount != 1 || estimatedCent != 300 {
t.Fatalf("distribution estimates = count:%d amount:%d, want 1/300", pendingCount, estimatedCent)
}
settlements, err := repo.dailySettlements(ctx, query)
if err != nil {
t.Fatal(err)
}
var settledCount, platformIncomeCent int64
for _, row := range settlements {
settledCount += row.SettledOrderCount
platformIncomeCent += row.PlatformIncomeAmountCent
}
if settledCount != 1 || platformIncomeCent != 500 {
t.Fatalf("distribution settlements = count:%d income:%d, want 1/500", settledCount, platformIncomeCent)
}
}
func TestFinancePickupStatsAndDisbursementsAreScopedByPickupTenant(t *testing.T) {
db := database.NewTestDB()
loc := timeutil.ShanghaiLocation()
@@ -81,6 +168,29 @@ func TestFinancePickupStatsAndDisbursementsAreScopedByPickupTenant(t *testing.T)
now, now).Error; err != nil {
t.Fatal(err)
}
site := model.DistributionSite{
SiteCode: "finance_paid_dist", SiteName: "成交归属测试站",
Domain: "finance-paid.example.com", Status: "active",
}
if err := db.Create(&site).Error; err != nil {
t.Fatal(err)
}
distributionOrder := model.RentalOrder{
OrderNo: "RO-FIN-PAID-DIST", BuyerTenantID: 101, SourceTenantID: 202,
PaymentTenantID: 101, DistributionSiteID: &site.ID,
DistributionMode: "two_party_distributor_receive", Status: "completed",
}
if err := db.Create(&distributionOrder).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&model.PaymentOrder{
TenantID: 101, PaymentNo: "PAY-FIN-PAID-DIST", OrderID: distributionOrder.ID,
OrderNo: distributionOrder.OrderNo, UserID: 1, Provider: "mock",
ThirdOrderID: "PAY-FIN-PAID-DIST", PayWay: "ZFBZF", AmountCent: 1000,
BizType: "order_pay", Status: "paid", PaidAt: &now,
}).Error; err != nil {
t.Fatal(err)
}
repo := NewRepository(db)
ctxA := financeTenantContext(101)
@@ -99,7 +209,7 @@ func TestFinancePickupStatsAndDisbursementsAreScopedByPickupTenant(t *testing.T)
if err != nil {
t.Fatal(err)
}
if len(paid) != 1 || paid[0].PaidOrderCount != 1 {
if len(paid) != 1 || paid[0].PaidOrderCount != 2 {
t.Fatalf("tenant paid pickup orders = %+v", paid)
}
cancelled, err := repo.dailyPickupCancelled(ctxA, query)
@@ -38,7 +38,7 @@ 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) {
if !currentTenantCanAdminDisputeOrder(ctx, order.BuyerTenantID) {
return gorm.ErrRecordNotFound
}
var listing model.RentalListing
+1 -1
View File
@@ -171,7 +171,7 @@ 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) {
if !currentTenantCanAdminDisputeOrder(ctx, order.BuyerTenantID) {
return gorm.ErrRecordNotFound
}
if order.Status == "completed" || order.Status == "cancelled" || order.Status == "closed" {
+3 -7
View File
@@ -116,19 +116,15 @@ func applyAdminDisputeTenantScope(ctx context.Context, db *gorm.DB) *gorm.DB {
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)")
return db.Where("o.buyer_tenant_id = ?", tenantID)
}
func currentTenantCanAdminDisputeOrder(ctx context.Context, orderBuyerTenantID uint64, distributionSiteID *uint64) bool {
func currentTenantCanAdminDisputeOrder(ctx context.Context, orderBuyerTenantID uint64) bool {
tenantID := tenancy.IDFromContext(ctx)
if tenantID == 0 {
return true
}
if orderBuyerTenantID != tenantID {
return false
}
return distributionSiteID == nil || *distributionSiteID == 0
return orderBuyerTenantID == tenantID
}
func (r *Repository) adminFilterQuery(ctx context.Context) *gorm.DB {
@@ -831,8 +831,16 @@ func TestAdminDisputeQueriesAndActionsAreScopedByBuyerTenant(t *testing.T) {
if err := db.Create(&tenantB).Error; err != nil {
t.Fatal(err)
}
site := model.DistributionSite{
SiteCode: "dispute_tenant_scope", SiteName: "纠纷归属测试站",
Domain: "dispute-tenant-scope.example.com", Status: "active",
}
if err := db.Create(&site).Error; err != nil {
t.Fatal(err)
}
_, _, orderA := createDisputeOrderFixture(t, db, model.RentalOrder{
OrderNo: "RO-DISPUTE-TENANT-A", BuyerTenantID: 101, SourceTenantID: 202, Status: "renting",
DistributionSiteID: &site.ID, DistributionMode: "two_party_distributor_receive",
})
_, _, orderB := createDisputeOrderFixture(t, db, model.RentalOrder{
OrderNo: "RO-DISPUTE-TENANT-B", BuyerTenantID: 202, SourceTenantID: 101, Status: "renting",
@@ -866,6 +874,20 @@ func TestAdminDisputeQueriesAndActionsAreScopedByBuyerTenant(t *testing.T) {
}, AuditMeta{}); !errors.Is(err, gorm.ErrRecordNotFound) {
t.Fatalf("cross-tenant arbitrate error = %v", err)
}
_, _, orderC := createDisputeOrderFixture(t, db, model.RentalOrder{
OrderNo: "RO-DISPUTE-TENANT-C", BuyerTenantID: 101, SourceTenantID: 202, Status: "renting",
DistributionSiteID: &site.ID, DistributionMode: "two_party_distributor_receive",
})
created, err := repo.AdminCreateByOrder(ctx, 9, orderC.ID, AdminCreateRequest{
Type: "cannot_login", Description: "分销订单允许租户客服创建纠纷", TargetRole: "owner",
}, AuditMeta{})
if err != nil {
t.Fatalf("buyer tenant should create dispute for distribution order: %v", err)
}
if created.OrderID != orderC.ID {
t.Fatalf("created dispute order = %d, want %d", created.OrderID, orderC.ID)
}
}
func TestStampOwnerIncomeSiteUsesListingSite(t *testing.T) {
@@ -19,8 +19,10 @@ func (r *Repository) FindTenantOffer(ctx context.Context, listingID uint64) (*Te
}
var listing model.RentalListing
if err := r.db.WithContext(ctx).
Select("id, price_cent").
Where("id = ? AND (distribution_site_id IS NULL OR distribution_site_id = 0)", listingID).
Table("rental_listings AS l").
Select("l.id, l.price_cent").
Joins("JOIN tenant_listing_offers AS tlo ON tlo.listing_id = l.id AND tlo.tenant_id = ?", tenantID).
Where("l.id = ?", listingID).
First(&listing).Error; err != nil {
return nil, err
}
@@ -54,8 +56,10 @@ func (r *Repository) UpdateTenantOffer(
}
var listing model.RentalListing
if err := r.db.WithContext(ctx).
Select("id, price_cent").
Where("id = ? AND (distribution_site_id IS NULL OR distribution_site_id = 0)", listingID).
Table("rental_listings AS l").
Select("l.id, l.price_cent").
Joins("JOIN tenant_listing_offers AS tlo ON tlo.listing_id = l.id AND tlo.tenant_id = ?", tenantID).
Where("l.id = ?", listingID).
First(&listing).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrListingNotFound
@@ -2,6 +2,7 @@ package listing
import (
"context"
"errors"
"testing"
"hfb_sys/backend/internal/database"
@@ -219,6 +220,19 @@ func TestPublicListingSharedPoolUsesTenantOffers(t *testing.T) {
if _, err := repo.FindPublic(listingTenantContext(jieyou.ID), listing.ID, "", 0); err != nil {
t.Fatalf("shared distribution listing detail should be visible to jieyou: %v", err)
}
if _, err := repo.FindTenantOffer(listingTenantContext(dachui.ID), listing.ID); err != nil {
t.Fatalf("dachui should read its distribution listing offer: %v", err)
}
updatedPrice := int64(12000)
updated, err := repo.UpdateTenantOffer(listingTenantContext(jieyou.ID), listing.ID, UpdateTenantListingOfferRequest{
DisplayStatus: "disabled", PriceCent: &updatedPrice,
})
if err != nil {
t.Fatalf("jieyou should update its distribution listing offer: %v", err)
}
if updated.DisplayStatus != "disabled" || updated.EffectivePriceCent != updatedPrice {
t.Fatalf("updated distribution offer = %+v", updated)
}
otherResult, err := repo.ListPublic(listingTenantContext(other.ID), PublicListQuery{})
if err != nil {
@@ -230,4 +244,9 @@ func TestPublicListingSharedPoolUsesTenantOffers(t *testing.T) {
if _, err := repo.FindPublic(listingTenantContext(other.ID), listing.ID, "", 0); err == nil {
t.Fatal("distribution listing detail must not be visible without tenant offer")
}
if _, err := repo.UpdateTenantOffer(listingTenantContext(other.ID), listing.ID, UpdateTenantListingOfferRequest{
DisplayStatus: "enabled",
}); !errors.Is(err, ErrListingNotFound) {
t.Fatalf("tenant without offer must not create distribution offer, err=%v", err)
}
}
@@ -44,9 +44,6 @@ 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
+1 -2
View File
@@ -552,8 +552,7 @@ func applyTenantOrderScope(query *gorm.DB, ctx context.Context) *gorm.DB {
return query
}
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)")
Where("(o.buyer_tenant_id = ? OR o.source_tenant_id = ?)", tenantID, tenantID)
}
func tenantOrderRole(ctx context.Context, order model.RentalOrder) string {
@@ -5,6 +5,7 @@ import (
"errors"
"sync"
"testing"
"time"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
@@ -170,6 +171,104 @@ func TestConcurrentTenantsCanOnlyRentListingOnce(t *testing.T) {
}
}
func TestCreateOrderAllowsSharedDistributionListingWithTenantOffer(t *testing.T) {
db := setupOrderTestDB(t)
dachui := model.Tenant{ID: 101, Code: "dachui_test", Name: "大锤测试站", Status: "active"}
jieyou := model.Tenant{ID: 202, Code: "jieyou_test", Name: "解忧测试站", Status: "active"}
if err := db.Create(&dachui).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&jieyou).Error; err != nil {
t.Fatal(err)
}
site := model.DistributionSite{
SiteCode: "tianyu_shared_test",
SiteName: "天域商行",
Domain: "tianyu-shared-test.example.com",
Status: "active",
DisplayAccountEnabled: true,
}
if err := db.Create(&site).Error; err != nil {
t.Fatal(err)
}
siteID := site.ID
rule := model.DistributionRuleVersion{
SiteID: &siteID,
Mode: "two_party_distributor_receive",
Version: 1,
Status: "active",
DistributorReceiveRatio: 35,
PlatformSellRatio: 40,
ServiceFeeValue: 25,
ServiceFeeUnit: "percent",
PaymentFeeBPS: 50,
EffectiveFrom: time.Now().Add(-time.Hour),
}
if err := db.Create(&rule).Error; err != nil {
t.Fatal(err)
}
owner := model.User{TenantID: 0, DistributionSiteID: site.ID, Phone: "13100000901", Status: "active"}
renter := model.User{TenantID: dachui.ID, Phone: "13100000902", Status: "active"}
if err := db.Create(&owner).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&renter).Error; err != nil {
t.Fatal(err)
}
account := model.GameAccount{
SourceTenantID: 0,
OwnerID: owner.ID,
ServerRegion: "微信",
LoginPlatform: "扫码",
Title: "天域共享库存账号",
Status: "published",
}
if err := db.Create(&account).Error; err != nil {
t.Fatal(err)
}
listing := model.RentalListing{
SourceTenantID: 0,
ListingNo: "L-TIANYU-SHARED-1",
AccountID: account.ID,
OwnerID: owner.ID,
PriceCent: 21130,
DepositAmountCent: 35000,
Status: listingStatusPublished,
ReviewStatus: listingReviewStatusApproved,
DistributionSiteID: &siteID,
}
if err := db.Create(&listing).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&[]model.TenantListingOffer{
{TenantID: dachui.ID, ListingID: listing.ID, DisplayStatus: "enabled"},
{TenantID: jieyou.ID, ListingID: listing.ID, DisplayStatus: "enabled"},
}).Error; err != nil {
t.Fatal(err)
}
repo := NewRepository(db)
dto, err := repo.Create(orderTenantContext(dachui.ID), renter.ID, CreateRequest{ListingID: listing.ID})
if err != nil {
t.Fatalf("create shared distribution order: %v", err)
}
if dto.BuyerTenantID != dachui.ID {
t.Fatalf("buyer tenant = %d, want %d", dto.BuyerTenantID, dachui.ID)
}
var saved model.RentalOrder
if err := db.First(&saved, dto.ID).Error; err != nil {
t.Fatal(err)
}
if saved.DistributionSiteID == nil || *saved.DistributionSiteID != site.ID ||
saved.DistributionRuleVersionID == nil || *saved.DistributionRuleVersionID != rule.ID ||
saved.DistributionMode != rule.Mode {
t.Fatalf("distribution snapshot = site:%v rule:%v mode:%s",
saved.DistributionSiteID, saved.DistributionRuleVersionID, saved.DistributionMode)
}
}
func TestAdminOrdersAreScopedByCurrentTenant(t *testing.T) {
db := setupOrderTestDB(t)
tenants := []model.Tenant{
@@ -180,11 +279,11 @@ 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",
sharedDistributionSite := model.DistributionSite{
ID: 999, SiteCode: "shared_ops_test", SiteName: "共享货源测试站",
Domain: "shared-ops-test.example.com", Status: "active",
}
if err := db.Create(&legacySite).Error; err != nil {
if err := db.Create(&sharedDistributionSite).Error; err != nil {
t.Fatal(err)
}
owner := model.User{TenantID: 101, Phone: "13000000101", Status: "active"}
@@ -241,12 +340,12 @@ func TestAdminOrdersAreScopedByCurrentTenant(t *testing.T) {
SourceTenantID: 303, PaymentTenantID: 101, Status: orderStatusRenting,
},
}
legacySiteID := legacySite.ID
sharedDistributionSiteID := sharedDistributionSite.ID
orders = append(orders, model.RentalOrder{
OrderNo: "RO-LEGACY-DISTRIBUTION", ListingID: listingA.ID, AccountID: accountA.ID,
OrderNo: "RO-SHARED-DISTRIBUTION", ListingID: listingA.ID, AccountID: accountA.ID,
OwnerID: owner.ID, RenterID: renterA.ID, BuyerTenantID: 101,
SourceTenantID: 101, PaymentTenantID: 101, DistributionSiteID: &legacySiteID,
Status: orderStatusRenting,
SourceTenantID: 101, PaymentTenantID: 101, DistributionSiteID: &sharedDistributionSiteID,
DistributionMode: "two_party_distributor_receive", Status: orderStatusRenting,
})
if err := db.Create(&orders).Error; err != nil {
t.Fatal(err)
@@ -278,33 +377,39 @@ func TestAdminOrdersAreScopedByCurrentTenant(t *testing.T) {
if err := repo.EnsureAdminOrderAccess(orderTenantContext(303), orders[0].ID); !errors.Is(err, gorm.ErrRecordNotFound) {
t.Fatalf("unrelated tenant order access error = %v", err)
}
if err := repo.EnsureAdminOrderAccess(orderTenantContext(101), orders[2].ID); err != nil {
t.Fatalf("buyer tenant must access distribution order: %v", err)
}
if _, err := repo.FindAdmin(orderTenantContext(101), orders[2].ID); err != nil {
t.Fatalf("buyer tenant must see distribution order detail: %v", err)
}
sourceResult, err := repo.ListAdmin(orderTenantContext(101), AdminOrderQuery{Page: 1, PageSize: 20})
if err != nil {
t.Fatal(err)
}
if sourceResult.Total != 2 {
if sourceResult.Total != 3 {
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" {
if roles[orders[0].ID] != "source" || roles[orders[1].ID] != "buyer" || roles[orders[2].ID] != "both" {
t.Fatalf("A tenant order roles = %+v", roles)
}
if err := db.Model(&model.RentalOrder{}).
Where("id = ?", orders[0].ID).
Where("id IN ?", []uint64{orders[0].ID, orders[2].ID}).
Update("refund_status", refundStatusPendingReview).Error; err != nil {
t.Fatal(err)
}
for _, tenantID := range []uint64{101, 202} {
for tenantID, wantCount := range map[uint64]int{101: 2, 202: 1} {
items, err := repo.ListPendingRefund(orderTenantContext(tenantID))
if err != nil {
t.Fatalf("tenant %d pending refunds: %v", tenantID, err)
}
if len(items) != 1 || items[0].ID != orders[0].ID {
if len(items) != wantCount {
t.Fatalf("tenant %d pending refunds = %+v", tenantID, items)
}
}
@@ -17,14 +17,13 @@ func (r *Repository) OrderPayments(ctx context.Context, orderID uint64) ([]Admin
}
var order struct {
BuyerTenantID uint64
SourceTenantID uint64
PaymentTenantID uint64
DistributionSiteID *uint64
BuyerTenantID uint64
SourceTenantID uint64
PaymentTenantID uint64
}
if err := r.db.WithContext(ctx).
Model(&model.RentalOrder{}).
Select("buyer_tenant_id, source_tenant_id, payment_tenant_id, distribution_site_id").
Select("buyer_tenant_id, source_tenant_id, payment_tenant_id").
Where("id = ?", orderID).
Take(&order).Error; err != nil {
if err == gorm.ErrRecordNotFound {
@@ -37,9 +36,6 @@ func (r *Repository) OrderPayments(ctx context.Context, orderID uint64) ([]Admin
if tenantID > 0 && order.BuyerTenantID != tenantID && order.SourceTenantID != tenantID {
return nil, ErrPaymentNotFound
}
if order.DistributionSiteID != nil && *order.DistributionSiteID > 0 {
return nil, ErrPaymentNotFound
}
paymentTenantID := order.PaymentTenantID
if paymentTenantID == 0 {
+2 -20
View File
@@ -58,26 +58,8 @@ 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 {
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,
)
db = db.Where("p.tenant_id = ?", tenantID)
countDB = countDB.Where("tenant_id = ?", tenantID)
}
if query.UserID > 0 {
db = db.Where("p.user_id = ?", query.UserID)
@@ -120,10 +120,18 @@ func TestTenantOrderWithoutOwnConfigDoesNotUseOtherTenantDefault(t *testing.T) {
func TestRefundAndOrderPaymentsUsePaymentTenant(t *testing.T) {
db := database.NewTestDB()
site := model.DistributionSite{
SiteCode: "payment_scope_dist", SiteName: "支付归属测试站",
Domain: "payment-scope.example.com", Status: "active",
}
if err := db.Create(&site).Error; err != nil {
t.Fatal(err)
}
order := model.RentalOrder{
BuyerTenantID: 202, SourceTenantID: 101, PaymentTenantID: 202,
OrderNo: "RO-CROSS-SITE-REFUND", RenterID: 1,
RentAmountCent: 1000, DepositAmountCent: 500, Status: "renting",
DistributionSiteID: &site.ID, DistributionMode: "two_party_distributor_receive",
}
if err := db.Create(&order).Error; err != nil {
t.Fatal(err)
@@ -155,7 +163,20 @@ func TestRefundAndOrderPaymentsUsePaymentTenant(t *testing.T) {
t.Fatalf("order payments = %+v", items)
}
list, err := repo.AdminList(paymentTenantContext(202), AdminPaymentQuery{Page: 1, PageSize: 20})
if err != nil {
t.Fatalf("tenant payment list: %v", err)
}
if list.Total != 1 {
t.Fatalf("tenant payment list total = %d, want 1; items=%+v", list.Total, list.Items)
}
if _, err := repo.OrderPayments(paymentTenantContext(303), order.ID); !errors.Is(err, ErrPaymentNotFound) {
t.Fatalf("unrelated tenant payment access error = %v", err)
}
if list, err := repo.AdminList(paymentTenantContext(303), AdminPaymentQuery{Page: 1, PageSize: 20}); err != nil {
t.Fatalf("unrelated tenant payment list: %v", err)
} else if list.Total != 0 {
t.Fatalf("unrelated tenant payment list leaked %d rows", list.Total)
}
}