From 3cc61615f9200719f1973fba906f498ed093741b Mon Sep 17 00:00:00 2001 From: yml Date: Tue, 24 Nov 2026 22:12:52 +0800 Subject: [PATCH] =?UTF-8?q?fix(distribution):=20=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E5=88=86=E9=94=80=E8=AE=A2=E5=8D=95=E7=A7=9F=E6=88=B7=E7=AE=A1?= =?UTF-8?q?=E7=90=86=E5=8F=A3=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../modules/admindashboard/repository.go | 9 +- .../admindashboard/tenant_scope_test.go | 30 +++- .../modules/adminfinance/dashboard.go | 24 +--- .../modules/adminfinance/disbursement.go | 3 +- .../modules/adminfinance/disbursement_list.go | 3 +- .../modules/adminfinance/tenant_scope_test.go | 116 +++++++++++++++- .../internal/modules/dispute/arbitration.go | 2 +- backend/internal/modules/dispute/mutation.go | 2 +- backend/internal/modules/dispute/query.go | 10 +- .../modules/dispute/repository_test.go | 22 +++ .../internal/modules/listing/tenant_offer.go | 12 +- .../modules/listing/tenant_offer_test.go | 19 +++ backend/internal/modules/order/lifecycle.go | 3 - backend/internal/modules/order/queries.go | 3 +- .../modules/order/tenant_offer_test.go | 131 ++++++++++++++++-- .../modules/payment/order_payments.go | 12 +- backend/internal/modules/payment/query.go | 22 +-- .../modules/payment/tenant_scope_test.go | 21 +++ backend/internal/router/file_access.go | 9 +- backend/internal/router/file_access_test.go | 110 +++++++++++++++ 20 files changed, 462 insertions(+), 101 deletions(-) diff --git a/backend/internal/modules/admindashboard/repository.go b/backend/internal/modules/admindashboard/repository.go index bfa61e24..da0e942d 100644 --- a/backend/internal/modules/admindashboard/repository.go +++ b/backend/internal/modules/admindashboard/repository.go @@ -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"). diff --git a/backend/internal/modules/admindashboard/tenant_scope_test.go b/backend/internal/modules/admindashboard/tenant_scope_test.go index 78b7d6a1..73bfb5b4 100644 --- a/backend/internal/modules/admindashboard/tenant_scope_test.go +++ b/backend/internal/modules/admindashboard/tenant_scope_test.go @@ -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) { diff --git a/backend/internal/modules/adminfinance/dashboard.go b/backend/internal/modules/adminfinance/dashboard.go index 18a5fffa..027de1c6 100644 --- a/backend/internal/modules/adminfinance/dashboard.go +++ b/backend/internal/modules/adminfinance/dashboard.go @@ -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) } diff --git a/backend/internal/modules/adminfinance/disbursement.go b/backend/internal/modules/adminfinance/disbursement.go index 9f967e9a..bb8b9a40 100644 --- a/backend/internal/modules/adminfinance/disbursement.go +++ b/backend/internal/modules/adminfinance/disbursement.go @@ -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 { diff --git a/backend/internal/modules/adminfinance/disbursement_list.go b/backend/internal/modules/adminfinance/disbursement_list.go index 6e7621d4..8158e99b 100644 --- a/backend/internal/modules/adminfinance/disbursement_list.go +++ b/backend/internal/modules/adminfinance/disbursement_list.go @@ -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"). diff --git a/backend/internal/modules/adminfinance/tenant_scope_test.go b/backend/internal/modules/adminfinance/tenant_scope_test.go index f36922e2..74e65dd3 100644 --- a/backend/internal/modules/adminfinance/tenant_scope_test.go +++ b/backend/internal/modules/adminfinance/tenant_scope_test.go @@ -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) diff --git a/backend/internal/modules/dispute/arbitration.go b/backend/internal/modules/dispute/arbitration.go index e15c5a6a..d317981b 100644 --- a/backend/internal/modules/dispute/arbitration.go +++ b/backend/internal/modules/dispute/arbitration.go @@ -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 diff --git a/backend/internal/modules/dispute/mutation.go b/backend/internal/modules/dispute/mutation.go index 0a3d5a37..6f77acb2 100644 --- a/backend/internal/modules/dispute/mutation.go +++ b/backend/internal/modules/dispute/mutation.go @@ -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" { diff --git a/backend/internal/modules/dispute/query.go b/backend/internal/modules/dispute/query.go index ce1a2219..9061d347 100644 --- a/backend/internal/modules/dispute/query.go +++ b/backend/internal/modules/dispute/query.go @@ -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 { diff --git a/backend/internal/modules/dispute/repository_test.go b/backend/internal/modules/dispute/repository_test.go index f19b343f..b590664d 100644 --- a/backend/internal/modules/dispute/repository_test.go +++ b/backend/internal/modules/dispute/repository_test.go @@ -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) { diff --git a/backend/internal/modules/listing/tenant_offer.go b/backend/internal/modules/listing/tenant_offer.go index b8d9c33c..08cec2af 100644 --- a/backend/internal/modules/listing/tenant_offer.go +++ b/backend/internal/modules/listing/tenant_offer.go @@ -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 diff --git a/backend/internal/modules/listing/tenant_offer_test.go b/backend/internal/modules/listing/tenant_offer_test.go index d327fdac..9387cbaf 100644 --- a/backend/internal/modules/listing/tenant_offer_test.go +++ b/backend/internal/modules/listing/tenant_offer_test.go @@ -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) + } } diff --git a/backend/internal/modules/order/lifecycle.go b/backend/internal/modules/order/lifecycle.go index b003a822..23b45949 100644 --- a/backend/internal/modules/order/lifecycle.go +++ b/backend/internal/modules/order/lifecycle.go @@ -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 diff --git a/backend/internal/modules/order/queries.go b/backend/internal/modules/order/queries.go index c5647c6b..956b319c 100644 --- a/backend/internal/modules/order/queries.go +++ b/backend/internal/modules/order/queries.go @@ -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 { diff --git a/backend/internal/modules/order/tenant_offer_test.go b/backend/internal/modules/order/tenant_offer_test.go index 413382f9..0641c633 100644 --- a/backend/internal/modules/order/tenant_offer_test.go +++ b/backend/internal/modules/order/tenant_offer_test.go @@ -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) } } diff --git a/backend/internal/modules/payment/order_payments.go b/backend/internal/modules/payment/order_payments.go index 18240d87..bdd021f4 100644 --- a/backend/internal/modules/payment/order_payments.go +++ b/backend/internal/modules/payment/order_payments.go @@ -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 { diff --git a/backend/internal/modules/payment/query.go b/backend/internal/modules/payment/query.go index 14cab80d..c63e91de 100644 --- a/backend/internal/modules/payment/query.go +++ b/backend/internal/modules/payment/query.go @@ -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) diff --git a/backend/internal/modules/payment/tenant_scope_test.go b/backend/internal/modules/payment/tenant_scope_test.go index 8dd41658..e28b317c 100644 --- a/backend/internal/modules/payment/tenant_scope_test.go +++ b/backend/internal/modules/payment/tenant_scope_test.go @@ -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) + } } diff --git a/backend/internal/router/file_access.go b/backend/internal/router/file_access.go index 5507da65..ec44ccce 100644 --- a/backend/internal/router/file_access.go +++ b/backend/internal/router/file_access.go @@ -329,8 +329,7 @@ WHERE ` + conversationTenantAccessClause("c") + ` AND ` + chatMembers, return []fileAccessQuery{{ sql: `SELECT COUNT(1) FROM handoff_records h JOIN rental_orders o ON o.id = h.order_id -WHERE (? = 0 OR ((o.buyer_tenant_id = ? OR o.source_tenant_id = ?) - AND (o.distribution_site_id IS NULL OR o.distribution_site_id = 0))) +WHERE (? = 0 OR (o.buyer_tenant_id = ? OR o.source_tenant_id = ?)) AND ` + handoffMembers, args: append([]any{tenantID, tenantID, tenantID}, jsonArgs...), }}, true @@ -339,16 +338,16 @@ WHERE (? = 0 OR ((o.buyer_tenant_id = ? OR o.source_tenant_id = ?) { sql: `SELECT COUNT(1) FROM disputes d JOIN rental_orders o ON o.id = d.order_id -WHERE (? = 0 OR (o.buyer_tenant_id = ? AND (o.distribution_site_id IS NULL OR o.distribution_site_id = 0))) +WHERE (? = 0 OR o.buyer_tenant_id = ?) AND ` + disputeMembers, args: append([]any{tenantID, tenantID}, jsonArgs...), }, { sql: `SELECT COUNT(1) FROM order_checkouts c JOIN rental_orders o ON o.id = c.order_id -WHERE (? = 0 OR (o.buyer_tenant_id = ? AND (o.distribution_site_id IS NULL OR o.distribution_site_id = 0))) +WHERE (? = 0 OR o.buyer_tenant_id = ? OR o.source_tenant_id = ?) AND ` + checkoutMembers, - args: append([]any{tenantID, tenantID}, jsonArgs...), + args: append([]any{tenantID, tenantID, tenantID}, jsonArgs...), }, }, true case "payment-cert": diff --git a/backend/internal/router/file_access_test.go b/backend/internal/router/file_access_test.go index 03b89ce8..70ab9235 100644 --- a/backend/internal/router/file_access_test.go +++ b/backend/internal/router/file_access_test.go @@ -127,6 +127,116 @@ func TestPrivateFileAccessMatchesCrossTenantConversation(t *testing.T) { } } +func TestAdminOrderEvidenceFilesFollowOrderTenantOnDistributionListing(t *testing.T) { + db := database.NewTestDB() + site := model.DistributionSite{ + SiteCode: "evidence_scope_dist", SiteName: "证据文件测试站", + Domain: "evidence-scope.example.com", Status: "active", + } + if err := db.Create(&site).Error; err != nil { + t.Fatal(err) + } + seller := model.User{TenantID: 202, Phone: "13900004101", Status: "active"} + buyer := model.User{TenantID: 101, Phone: "13900004102", Status: "active"} + if err := db.Create(&seller).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&buyer).Error; err != nil { + t.Fatal(err) + } + account := model.GameAccount{ + SourceTenantID: 202, OwnerID: seller.ID, ServerRegion: "国服", + LoginPlatform: "steam", Title: "分销证据文件商品", Status: "published", + } + if err := db.Create(&account).Error; err != nil { + t.Fatal(err) + } + listing := model.RentalListing{ + SourceTenantID: 202, DistributionSiteID: &site.ID, + ListingNo: "L-EVIDENCE-SCOPE", AccountID: account.ID, OwnerID: seller.ID, + PriceCent: 1000, Status: "rented", ReviewStatus: "approved", + } + if err := db.Create(&listing).Error; err != nil { + t.Fatal(err) + } + order := model.RentalOrder{ + BuyerTenantID: 101, SourceTenantID: 202, PaymentTenantID: 101, + DistributionSiteID: &site.ID, DistributionMode: "two_party_distributor_receive", + OrderNo: "RO-EVIDENCE-SCOPE", ListingID: listing.ID, AccountID: account.ID, + OwnerID: seller.ID, RenterID: buyer.ID, Status: "pending_handoff", + } + if err := db.Create(&order).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&model.HandoffRecord{ + OrderID: order.ID, FromUserID: seller.ID, ToUserID: buyer.ID, Type: "owner_handoff", + AttachmentURLS: datatypes.JSON([]byte(`["/api/files/object?key=handoff%2Fdistribution.jpg"]`)), + }).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&model.Dispute{ + OrderID: order.ID, InitiatorID: buyer.ID, InitiatorType: "user", + TargetUserID: seller.ID, Type: "cannot_login", Status: "open", + EvidenceURLS: datatypes.JSON([]byte(`["/api/files/object?key=dispute%2Fdistribution.jpg"]`)), + }).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&model.OrderCheckout{ + OrderID: order.ID, Status: "open", + EvidenceURLS: datatypes.JSON([]byte(`["/api/files/object?key=dispute%2Fcheckout.jpg"]`)), + }).Error; err != nil { + t.Fatal(err) + } + + for _, tc := range []struct { + name string + key string + allowSource bool + }{ + {name: "交接附件", key: "handoff/distribution.jpg", allowSource: true}, + {name: "纠纷证据", key: "dispute/distribution.jpg"}, + {name: "结账证据", key: "dispute/checkout.jpg", allowSource: true}, + } { + t.Run(tc.name, func(t *testing.T) { + queries, known := knownAdminFileQueries( + context.Background(), db, 0, 101, fileReferenceValues(tc.key, tc.key), + ) + if !known { + t.Fatal("文件类型应进入管理员业务权限校验") + } + allowed, err := runFileAccessQueries(context.Background(), db, queries) + if err != nil { + t.Fatal(err) + } + if !allowed { + t.Fatalf("买方租户管理员应可访问分销订单%s", tc.name) + } + + queries, _ = knownAdminFileQueries( + context.Background(), db, 0, 202, fileReferenceValues(tc.key, tc.key), + ) + allowed, err = runFileAccessQueries(context.Background(), db, queries) + if err != nil { + t.Fatal(err) + } + if allowed != tc.allowSource { + t.Fatalf("货源租户访问分销订单%s allowed=%v, want %v", tc.name, allowed, tc.allowSource) + } + + queries, _ = knownAdminFileQueries( + context.Background(), db, 0, 303, fileReferenceValues(tc.key, tc.key), + ) + allowed, err = runFileAccessQueries(context.Background(), db, queries) + if err != nil { + t.Fatal(err) + } + if allowed { + t.Fatalf("无关租户不得访问分销订单%s", tc.name) + } + }) + } +} + func TestAdminQrCodeFileAccessUsesConversationScope(t *testing.T) { db := database.NewTestDB() admin := model.AdminUser{Username: "dachui-ops", PasswordHash: "x", Status: "active", TokenVersion: 1}