fix(pickup): 支持天域分销货源提号结算

This commit is contained in:
yml
2026-11-24 14:41:49 +08:00
parent b63f5d771b
commit 8d8f6f773e
5 changed files with 435 additions and 221 deletions
+6
View File
@@ -57,6 +57,9 @@ type PickupDTO struct {
SourceTenantID uint64 `json:"source_tenant_id"` SourceTenantID uint64 `json:"source_tenant_id"`
SourceTenantCode string `json:"source_tenant_code"` SourceTenantCode string `json:"source_tenant_code"`
SourceTenantName string `json:"source_tenant_name"` SourceTenantName string `json:"source_tenant_name"`
SourceDistributionSiteID uint64 `json:"source_distribution_site_id"`
SourceDistributionSiteCode string `json:"source_distribution_site_code"`
SourceDistributionSiteName string `json:"source_distribution_site_name"`
IsCrossTenant bool `json:"is_cross_tenant"` IsCrossTenant bool `json:"is_cross_tenant"`
PickupNo string `json:"pickup_no"` PickupNo string `json:"pickup_no"`
ListingID uint64 `json:"listing_id"` ListingID uint64 `json:"listing_id"`
@@ -257,6 +260,9 @@ type AvailableListingDTO struct {
SourceTenantID uint64 `json:"source_tenant_id"` SourceTenantID uint64 `json:"source_tenant_id"`
SourceTenantCode string `json:"source_tenant_code"` SourceTenantCode string `json:"source_tenant_code"`
SourceTenantName string `json:"source_tenant_name"` SourceTenantName string `json:"source_tenant_name"`
SourceDistributionSiteID uint64 `json:"source_distribution_site_id"`
SourceDistributionSiteCode string `json:"source_distribution_site_code"`
SourceDistributionSiteName string `json:"source_distribution_site_name"`
IsCrossTenant bool `json:"is_cross_tenant"` IsCrossTenant bool `json:"is_cross_tenant"`
ListingNo string `json:"listing_no"` ListingNo string `json:"listing_no"`
AccountID uint64 `json:"account_id"` AccountID uint64 `json:"account_id"`
+52 -3
View File
@@ -136,6 +136,7 @@ func (r *Repository) Create(ctx context.Context, req CreateRequest, adminID uint
if err := appendPickupEvent(tx, pickup, "pickup_created", adminID, "管理员创建线下提号。", pickup.Remark, map[string]any{ if err := appendPickupEvent(tx, pickup, "pickup_created", adminID, "管理员创建线下提号。", pickup.Remark, map[string]any{
"tenant_id": pickup.TenantID, "tenant_id": pickup.TenantID,
"source_tenant_id": pickup.SourceTenantID, "source_tenant_id": pickup.SourceTenantID,
"source_distribution_site_id": pickupDistributionSiteID(listing),
"listing_price_cent": pickup.ListingPriceCent, "listing_price_cent": pickup.ListingPriceCent,
"order_amount_cent": pickup.OrderAmountCent, "order_amount_cent": pickup.OrderAmountCent,
"deposit_amount_cent": pickup.DepositAmountCent, "deposit_amount_cent": pickup.DepositAmountCent,
@@ -196,6 +197,7 @@ func (r *Repository) Create(ctx context.Context, req CreateRequest, adminID uint
"pickup_no": pickupNo, "pickup_no": pickupNo,
"tenant_id": pickup.TenantID, "tenant_id": pickup.TenantID,
"source_tenant_id": pickup.SourceTenantID, "source_tenant_id": pickup.SourceTenantID,
"source_distribution_site_id": pickupDistributionSiteID(listing),
"listing_id": listing.ID, "listing_id": listing.ID,
"platform": pickup.Platform, "platform": pickup.Platform,
"third_party_order_no": pickup.ThirdPartyOrderNo, "third_party_order_no": pickup.ThirdPartyOrderNo,
@@ -303,7 +305,9 @@ func (r *Repository) Complete(ctx context.Context, pickupID uint64, req Complete
} }
} else { } else {
if err := wallet.AppendEntries(tx, wallet.Entry{ if err := wallet.AppendEntries(tx, wallet.Entry{
TenantID: pickup.SourceTenantID,
UserID: pickup.OwnerID, UserID: pickup.OwnerID,
DistributionSiteID: pickupDistributionSiteID(listing),
Direction: "in", Direction: "in",
AmountCent: req.SettleAmountCent, AmountCent: req.SettleAmountCent,
BalanceType: "available", BalanceType: "available",
@@ -650,8 +654,14 @@ func (r *Repository) CreateFinancialAdjustment(ctx context.Context, pickupID uin
// 站内钱包的补款在创建调整时立即到账;扣款统一转待追回,避免余额被扣成负数。 // 站内钱包的补款在创建调整时立即到账;扣款统一转待追回,避免余额被扣成负数。
if pickup.SettlementMode == SettlementModeOwnerWallet && settleDeltaCent > 0 { if pickup.SettlementMode == SettlementModeOwnerWallet && settleDeltaCent > 0 {
var listing model.RentalListing
if err := tx.Select("id", "distribution_site_id").First(&listing, pickup.ListingID).Error; err != nil {
return err
}
if err := wallet.AppendEntries(tx, wallet.Entry{ if err := wallet.AppendEntries(tx, wallet.Entry{
TenantID: pickup.SourceTenantID,
UserID: pickup.OwnerID, UserID: pickup.OwnerID,
DistributionSiteID: pickupDistributionSiteID(listing),
Direction: "in", Direction: "in",
AmountCent: settleDeltaCent, AmountCent: settleDeltaCent,
BalanceType: "available", BalanceType: "available",
@@ -1567,10 +1577,23 @@ func (r *Repository) ListAvailableListings(ctx context.Context, query AvailableL
Joins("JOIN game_accounts AS a ON a.id = l.account_id"). Joins("JOIN game_accounts AS a ON a.id = l.account_id").
Joins("JOIN users AS owner ON owner.id = l.owner_id"). Joins("JOIN users AS owner ON owner.id = l.owner_id").
Joins("LEFT JOIN tenants AS source_tenant ON source_tenant.id = l.source_tenant_id"). Joins("LEFT JOIN tenants AS source_tenant ON source_tenant.id = l.source_tenant_id").
Joins("LEFT JOIN distribution_sites AS source_site ON source_site.id = l.distribution_site_id").
Joins("LEFT JOIN (?) AS latest_upload ON latest_upload.listing_id = l.id", latestUploads). Joins("LEFT JOIN (?) AS latest_upload ON latest_upload.listing_id = l.id", latestUploads).
Joins("LEFT JOIN listing_uploads AS lu ON lu.id = latest_upload.upload_id"). Joins("LEFT JOIN listing_uploads AS lu ON lu.id = latest_upload.upload_id").
Where("l.status = ? AND l.review_status = ? AND l.in_transaction = ?", "published", "approved", false). Where("l.status = ? AND l.review_status = ? AND l.in_transaction = ?", "published", "approved", false)
Where("(l.distribution_site_id IS NULL OR l.distribution_site_id = 0)") if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
q = q.Where(`(
l.distribution_site_id IS NULL
OR l.distribution_site_id = 0
OR EXISTS (
SELECT 1
FROM tenant_listing_offers AS tlo
WHERE tlo.listing_id = l.id
AND tlo.tenant_id = ?
AND tlo.display_status = 'enabled'
)
)`, tenantID)
}
if kw := strings.TrimSpace(query.Keyword); kw != "" { if kw := strings.TrimSpace(query.Keyword); kw != "" {
upper := strings.ToUpper(kw) upper := strings.ToUpper(kw)
if strings.HasPrefix(upper, "L") || (len(kw) >= 12 && isAllDigits(kw)) { if strings.HasPrefix(upper, "L") || (len(kw) >= 12 && isAllDigits(kw)) {
@@ -1594,6 +1617,9 @@ func (r *Repository) ListAvailableListings(ctx context.Context, query AvailableL
if err := buildQuery().Select(`l.id, l.source_tenant_id, if err := buildQuery().Select(`l.id, l.source_tenant_id,
COALESCE(source_tenant.code, '') AS source_tenant_code, COALESCE(source_tenant.code, '') AS source_tenant_code,
COALESCE(source_tenant.name, '') AS source_tenant_name, COALESCE(source_tenant.name, '') AS source_tenant_name,
COALESCE(source_site.id, 0) AS source_distribution_site_id,
COALESCE(source_site.site_code, '') AS source_distribution_site_code,
COALESCE(source_site.site_name, '') AS source_distribution_site_name,
l.listing_no, l.account_id, l.owner_id, l.price_cent AS listing_price_cent, l.listing_no, l.account_id, l.owner_id, l.price_cent AS listing_price_cent,
a.title AS account_title, a.server_region, a.login_platform, a.haf_coin_amount, a.asset_summary, a.title AS account_title, a.server_region, a.login_platform, a.haf_coin_amount, a.asset_summary,
owner.phone AS owner_phone, l.handoff_mode, l.settlement_mode, owner.phone AS owner_phone, l.handoff_mode, l.settlement_mode,
@@ -1627,13 +1653,17 @@ func (r *Repository) baseQuery(ctx context.Context) *gorm.DB {
COALESCE(pickup_tenant.name, '') AS tenant_name, COALESCE(pickup_tenant.name, '') AS tenant_name,
COALESCE(source_tenant.code, '') AS source_tenant_code, COALESCE(source_tenant.code, '') AS source_tenant_code,
COALESCE(source_tenant.name, '') AS source_tenant_name, COALESCE(source_tenant.name, '') AS source_tenant_name,
COALESCE(source_site.id, 0) AS source_distribution_site_id,
COALESCE(source_site.site_code, '') AS source_distribution_site_code,
COALESCE(source_site.site_name, '') AS source_distribution_site_name,
COALESCE((SELECT SUM(fa.profit_delta_cent) FROM admin_pickup_financial_adjustments AS fa WHERE fa.pickup_id = p.id), 0) AS profit_adjustment_cent, COALESCE((SELECT SUM(fa.profit_delta_cent) FROM admin_pickup_financial_adjustments AS fa WHERE fa.pickup_id = p.id), 0) AS profit_adjustment_cent,
COALESCE((SELECT SUM(fa.settle_delta_cent) FROM admin_pickup_financial_adjustments AS fa WHERE fa.pickup_id = p.id), 0) AS settle_adjustment_cent`). COALESCE((SELECT SUM(fa.settle_delta_cent) FROM admin_pickup_financial_adjustments AS fa WHERE fa.pickup_id = p.id), 0) AS settle_adjustment_cent`).
Joins("JOIN rental_listings AS l ON l.id = p.listing_id"). Joins("JOIN rental_listings AS l ON l.id = p.listing_id").
Joins("JOIN game_accounts AS a ON a.id = p.account_id"). Joins("JOIN game_accounts AS a ON a.id = p.account_id").
Joins("JOIN users AS owner ON owner.id = p.owner_id"). Joins("JOIN users AS owner ON owner.id = p.owner_id").
Joins("LEFT JOIN tenants AS pickup_tenant ON pickup_tenant.id = p.tenant_id"). Joins("LEFT JOIN tenants AS pickup_tenant ON pickup_tenant.id = p.tenant_id").
Joins("LEFT JOIN tenants AS source_tenant ON source_tenant.id = p.source_tenant_id") Joins("LEFT JOIN tenants AS source_tenant ON source_tenant.id = p.source_tenant_id").
Joins("LEFT JOIN distribution_sites AS source_site ON source_site.id = l.distribution_site_id")
} }
func (r *Repository) adminBaseQuery(ctx context.Context) *gorm.DB { func (r *Repository) adminBaseQuery(ctx context.Context) *gorm.DB {
@@ -1646,6 +1676,9 @@ type pickupRow struct {
TenantName string TenantName string
SourceTenantCode string SourceTenantCode string
SourceTenantName string SourceTenantName string
SourceDistributionSiteID uint64
SourceDistributionSiteCode string
SourceDistributionSiteName string
ListingNo string ListingNo string
AccountTitle string AccountTitle string
ServerRegion string ServerRegion string
@@ -1664,6 +1697,9 @@ func (row pickupRow) toDTO() PickupDTO {
SourceTenantID: row.SourceTenantID, SourceTenantID: row.SourceTenantID,
SourceTenantCode: row.SourceTenantCode, SourceTenantCode: row.SourceTenantCode,
SourceTenantName: row.SourceTenantName, SourceTenantName: row.SourceTenantName,
SourceDistributionSiteID: row.SourceDistributionSiteID,
SourceDistributionSiteCode: row.SourceDistributionSiteCode,
SourceDistributionSiteName: row.SourceDistributionSiteName,
IsCrossTenant: row.TenantID > 0 && row.SourceTenantID > 0 && row.TenantID != row.SourceTenantID, IsCrossTenant: row.TenantID > 0 && row.SourceTenantID > 0 && row.TenantID != row.SourceTenantID,
PickupNo: row.PickupNo, PickupNo: row.PickupNo,
ListingID: row.ListingID, ListingID: row.ListingID,
@@ -1751,11 +1787,21 @@ func pickupRequiresOfflineSettlement(pickup model.AdminPickup) bool {
return pickup.SettlementMode == SettlementModePlatformManaged return pickup.SettlementMode == SettlementModePlatformManaged
} }
func pickupDistributionSiteID(listing model.RentalListing) uint64 {
if listing.DistributionSiteID == nil {
return 0
}
return *listing.DistributionSiteID
}
type availableListingRow struct { type availableListingRow struct {
ID uint64 ID uint64
SourceTenantID uint64 SourceTenantID uint64
SourceTenantCode string SourceTenantCode string
SourceTenantName string SourceTenantName string
SourceDistributionSiteID uint64
SourceDistributionSiteCode string
SourceDistributionSiteName string
ListingNo string ListingNo string
AccountID uint64 AccountID uint64
AccountTitle string AccountTitle string
@@ -1786,6 +1832,9 @@ func (row availableListingRow) toDTO() AvailableListingDTO {
SourceTenantID: row.SourceTenantID, SourceTenantID: row.SourceTenantID,
SourceTenantCode: row.SourceTenantCode, SourceTenantCode: row.SourceTenantCode,
SourceTenantName: row.SourceTenantName, SourceTenantName: row.SourceTenantName,
SourceDistributionSiteID: row.SourceDistributionSiteID,
SourceDistributionSiteCode: row.SourceDistributionSiteCode,
SourceDistributionSiteName: row.SourceDistributionSiteName,
ListingNo: row.ListingNo, ListingNo: row.ListingNo,
AccountID: row.AccountID, AccountID: row.AccountID,
AccountTitle: row.AccountTitle, AccountTitle: row.AccountTitle,
@@ -56,6 +56,47 @@ func seedPickupTenantListing(t *testing.T, db *gorm.DB, tenantID uint64, suffix
return listing return listing
} }
func seedPickupDistributionListing(t *testing.T, db *gorm.DB, tenantID, siteID uint64, suffix string) model.RentalListing {
t.Helper()
owner := model.User{
TenantID: tenantID,
DistributionSiteID: siteID,
Phone: "1890000" + suffix,
Nickname: "分销号主" + suffix,
Status: "active",
}
if err := db.Create(&owner).Error; err != nil {
t.Fatal(err)
}
account := model.GameAccount{
SourceTenantID: tenantID,
OwnerID: owner.ID,
ServerRegion: "测试区",
LoginPlatform: "微信",
Title: "天域账号" + suffix,
Status: "published",
}
if err := db.Create(&account).Error; err != nil {
t.Fatal(err)
}
listing := model.RentalListing{
SourceTenantID: tenantID,
ListingNo: "LST-PICKUP-DIST-" + suffix,
AccountID: account.ID,
OwnerID: owner.ID,
PriceCent: 12000,
Status: "published",
ReviewStatus: "approved",
HandoffMode: "owner",
SettlementMode: "owner_wallet",
DistributionSiteID: &siteID,
}
if err := db.Create(&listing).Error; err != nil {
t.Fatal(err)
}
return listing
}
func TestPickupTenantScopeSupportsCrossTenantCreationAndSeparateLists(t *testing.T) { func TestPickupTenantScopeSupportsCrossTenantCreationAndSeparateLists(t *testing.T) {
db := database.NewTestDB() db := database.NewTestDB()
tenants := []model.Tenant{ tenants := []model.Tenant{
@@ -150,6 +191,110 @@ func TestPickupTenantScopeSupportsCrossTenantCreationAndSeparateLists(t *testing
} }
} }
func TestPickupSupportsSharedDistributionSourceAcrossTenants(t *testing.T) {
db := database.NewTestDB()
tenants := []model.Tenant{
{Code: "pickup_dist_source", Name: "货源站", Status: "active"},
{Code: "pickup_dist_a", Name: "提号A站", Status: "active"},
{Code: "pickup_dist_b", Name: "提号B站", Status: "active"},
{Code: "pickup_dist_other", Name: "未铺货站", Status: "active"},
}
if err := db.Create(&tenants).Error; err != nil {
t.Fatal(err)
}
site := model.DistributionSite{
SiteCode: "tianyu_pickup",
SiteName: "天域商行",
Domain: "tianyu-pickup.example.com",
Status: "active",
}
if err := db.Create(&site).Error; err != nil {
t.Fatal(err)
}
sourceTenant, tenantA, tenantB, otherTenant := tenants[0], tenants[1], tenants[2], tenants[3]
listing := seedPickupDistributionListing(t, db, sourceTenant.ID, site.ID, "01")
listingNumber := "202611230328"
if err := db.Model(&listing).Update("listing_no", listingNumber).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&[]model.TenantListingOffer{
{TenantID: tenantA.ID, ListingID: listing.ID, DisplayStatus: "enabled"},
{TenantID: tenantB.ID, ListingID: listing.ID, DisplayStatus: "enabled"},
}).Error; err != nil {
t.Fatal(err)
}
repo := NewRepository(db)
for _, tc := range []struct {
name string
ctx context.Context
crossTenant bool
}{
{name: "A站", ctx: pickupTenantContext(tenantA.ID), crossTenant: true},
{name: "B站", ctx: pickupTenantContext(tenantB.ID), crossTenant: true},
} {
available, err := repo.ListAvailableListings(tc.ctx, AvailableListingQuery{
Keyword: listingNumber,
Page: 1,
PageSize: 20,
})
if err != nil {
t.Fatalf("%s 查询可提号商品: %v", tc.name, err)
}
if len(available.Items) != 1 {
t.Fatalf("%s 可提号商品 = %+v, want 天域商品", tc.name, available.Items)
}
item := available.Items[0]
if item.ID != listing.ID ||
item.SourceDistributionSiteID != site.ID ||
item.SourceDistributionSiteName != site.SiteName ||
item.IsCrossTenant != tc.crossTenant {
t.Fatalf("%s 天域货源快照 = %+v", tc.name, item)
}
}
otherAvailable, err := repo.ListAvailableListings(pickupTenantContext(otherTenant.ID), AvailableListingQuery{Page: 1, PageSize: 20})
if err != nil {
t.Fatal(err)
}
if len(otherAvailable.Items) != 0 {
t.Fatalf("未铺货经营租户看到了天域商品: %+v", otherAvailable.Items)
}
pickup, err := repo.Create(pickupTenantContext(tenantB.ID), CreateRequest{ListingID: listing.ID}, 9, auditlog.Meta{})
if err != nil {
t.Fatalf("从 B 站创建天域货源提号: %v", err)
}
if _, err := repo.Complete(pickupTenantContext(tenantB.ID), pickup.ID, CompleteRequest{
SettleAmountCent: 8000,
}, 9, auditlog.Meta{}); err != nil {
t.Fatalf("完成天域货源提号: %v", err)
}
var ledger model.WalletLedger
if err := db.Where("biz_type = ? AND biz_no = ?", "admin_pickup_settle", pickup.PickupNo).First(&ledger).Error; err != nil {
t.Fatalf("查询天域货源结算流水: %v", err)
}
if ledger.TenantID != sourceTenant.ID || ledger.DistributionSiteID != site.ID {
t.Fatalf("天域货源结算流水归属 = %+v, want tenant=%d site=%d", ledger, sourceTenant.ID, site.ID)
}
adjustedSettleAmount := int64(9000)
if _, err := repo.CreateFinancialAdjustment(pickupTenantContext(tenantB.ID), pickup.ID, FinancialAdjustmentRequest{
SettleAmountCent: &adjustedSettleAmount,
Reason: "补发天域货源结算差额",
}, 9, auditlog.Meta{}); err != nil {
t.Fatalf("创建天域货源结算补款: %v", err)
}
var adjustmentLedger model.WalletLedger
if err := db.Where("biz_type = ? AND biz_no LIKE ?", "admin_pickup_adjustment", pickup.PickupNo+"-A%").
First(&adjustmentLedger).Error; err != nil {
t.Fatalf("查询天域货源补款流水: %v", err)
}
if adjustmentLedger.TenantID != sourceTenant.ID || adjustmentLedger.DistributionSiteID != site.ID {
t.Fatalf("天域货源补款流水归属 = %+v, want tenant=%d site=%d", adjustmentLedger, sourceTenant.ID, site.ID)
}
}
func TestPickupShopsAreSeparatedByTenant(t *testing.T) { func TestPickupShopsAreSeparatedByTenant(t *testing.T) {
db := database.NewTestDB() db := database.NewTestDB()
tenants := []model.Tenant{ tenants := []model.Tenant{
@@ -16,6 +16,9 @@ export interface AdminPickup {
source_tenant_id: number source_tenant_id: number
source_tenant_code: string source_tenant_code: string
source_tenant_name: string source_tenant_name: string
source_distribution_site_id: number
source_distribution_site_code: string
source_distribution_site_name: string
is_cross_tenant: boolean is_cross_tenant: boolean
pickup_no: string pickup_no: string
listing_id: number listing_id: number
@@ -101,6 +104,9 @@ export interface AvailableListing {
source_tenant_id: number source_tenant_id: number
source_tenant_code: string source_tenant_code: string
source_tenant_name: string source_tenant_name: string
source_distribution_site_id: number
source_distribution_site_code: string
source_distribution_site_name: string
is_cross_tenant: boolean is_cross_tenant: boolean
listing_no: string listing_no: string
account_id: number account_id: number
@@ -609,11 +609,19 @@ function siteName(code: string, name: string) {
} }
function pickupSiteText(row: AdminPickup) { function pickupSiteText(row: AdminPickup) {
if (row.source_distribution_site_id > 0) {
const source = siteName(row.source_distribution_site_code, row.source_distribution_site_name)
return row.is_cross_tenant ? `跨站 · ${source}` : `本站 · ${source}`
}
if (!row.is_cross_tenant) return '本站货源' if (!row.is_cross_tenant) return '本站货源'
return `跨站 · ${siteName(row.source_tenant_code, row.source_tenant_name)}` return `跨站 · ${siteName(row.source_tenant_code, row.source_tenant_name)}`
} }
function listingSiteText(item: AvailableListing) { function listingSiteText(item: AvailableListing) {
if (item.source_distribution_site_id > 0) {
const source = siteName(item.source_distribution_site_code, item.source_distribution_site_name)
return item.is_cross_tenant ? `跨站 · ${source}` : `本站 · ${source}`
}
const source = siteName(item.source_tenant_code, item.source_tenant_name) const source = siteName(item.source_tenant_code, item.source_tenant_name)
return item.is_cross_tenant ? `跨站 · ${source}` : `本站 · ${source}` return item.is_cross_tenant ? `跨站 · ${source}` : `本站 · ${source}`
} }