feat(distribution): 分销站点消息中心与钱包提现多租户独立分支隔离
- 新增 000070 数据库迁移:支持 chat_conversations、wallet_accounts、wallet_ledger、withdrawal_requests 按 distribution_site_id 隔离 - 消息中心:会话列表、未读数统计、站点专属客服及订单群聊与主站实现双向完全隔离 - 资金账户与提现:独立按 (user_id, distribution_site_id) 建账,分销订单自动结算至对应分站钱包,提现与流水相互独立 - 前台界面:Axios 自动透传 X-Distribution-Site-Code,钱包、提现与消息页面呈现分站专属标牌与独立说明
This commit is contained in:
@@ -4,6 +4,7 @@ import "time"
|
||||
|
||||
type AccountDTO struct {
|
||||
UserID uint64 `json:"user_id"`
|
||||
DistributionSiteID uint64 `json:"distribution_site_id"`
|
||||
AvailableBalanceCent int64 `json:"available_balance_cent"`
|
||||
FrozenBalanceCent int64 `json:"frozen_balance_cent"`
|
||||
Status string `json:"status"`
|
||||
@@ -14,18 +15,19 @@ type WithdrawRequest struct {
|
||||
}
|
||||
|
||||
type LedgerDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
LedgerNo string `json:"ledger_no"`
|
||||
UserID uint64 `json:"user_id"`
|
||||
OrderID *uint64 `json:"order_id"`
|
||||
Direction string `json:"direction"`
|
||||
AmountCent int64 `json:"amount_cent"`
|
||||
BalanceAfterCent int64 `json:"balance_after_cent"`
|
||||
BalanceType string `json:"balance_type"`
|
||||
BizType string `json:"biz_type"`
|
||||
BizNo string `json:"biz_no"`
|
||||
Remark string `json:"remark"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID uint64 `json:"id"`
|
||||
LedgerNo string `json:"ledger_no"`
|
||||
UserID uint64 `json:"user_id"`
|
||||
DistributionSiteID uint64 `json:"distribution_site_id"`
|
||||
OrderID *uint64 `json:"order_id"`
|
||||
Direction string `json:"direction"`
|
||||
AmountCent int64 `json:"amount_cent"`
|
||||
BalanceAfterCent int64 `json:"balance_after_cent"`
|
||||
BalanceType string `json:"balance_type"`
|
||||
BizType string `json:"biz_type"`
|
||||
BizNo string `json:"biz_no"`
|
||||
Remark string `json:"remark"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type AdminLedgerQuery struct {
|
||||
|
||||
@@ -3,6 +3,7 @@ package wallet
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/middleware"
|
||||
"hfb_sys/backend/pkg/response"
|
||||
@@ -18,13 +19,28 @@ func NewHandler(service *Service) *Handler {
|
||||
return &Handler{service: service}
|
||||
}
|
||||
|
||||
func parseSiteCode(c *gin.Context) string {
|
||||
for _, val := range []string{
|
||||
c.Query("distribution_site_code"),
|
||||
c.Query("site_code"),
|
||||
c.GetHeader("X-Distribution-Site-Code"),
|
||||
c.GetHeader("X-Site-Code"),
|
||||
} {
|
||||
if trimmed := strings.TrimSpace(val); trimmed != "" {
|
||||
return trimmed
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (h *Handler) Balance(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
return
|
||||
}
|
||||
account, err := h.service.Account(c.Request.Context(), userID)
|
||||
siteCode := parseSiteCode(c)
|
||||
account, err := h.service.Account(c.Request.Context(), userID, siteCode)
|
||||
if err != nil {
|
||||
writeWalletError(c, err)
|
||||
return
|
||||
@@ -54,7 +70,8 @@ func (h *Handler) Ledger(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
page, pageSize := parsePagination(c)
|
||||
result, err := h.service.Ledger(c.Request.Context(), userID, page, pageSize)
|
||||
siteCode := parseSiteCode(c)
|
||||
result, err := h.service.Ledger(c.Request.Context(), userID, page, pageSize, siteCode)
|
||||
if err != nil {
|
||||
writeWalletError(c, err)
|
||||
return
|
||||
|
||||
@@ -3,7 +3,9 @@ package wallet
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
@@ -19,27 +21,52 @@ type Repository struct {
|
||||
}
|
||||
|
||||
type Entry struct {
|
||||
UserID uint64
|
||||
OrderID *uint64
|
||||
Direction string
|
||||
AmountCent int64
|
||||
BalanceType string
|
||||
BizType string
|
||||
BizNo string
|
||||
Remark string
|
||||
UserID uint64
|
||||
DistributionSiteID uint64
|
||||
OrderID *uint64
|
||||
Direction string
|
||||
AmountCent int64
|
||||
BalanceType string
|
||||
BizType string
|
||||
BizNo string
|
||||
Remark string
|
||||
}
|
||||
|
||||
func NewRepository(db *gorm.DB) *Repository {
|
||||
return &Repository{db: db}
|
||||
}
|
||||
|
||||
func (r *Repository) Account(ctx context.Context, userID uint64) (*AccountDTO, error) {
|
||||
func (r *Repository) resolveSiteID(ctx context.Context, siteCode string) (uint64, error) {
|
||||
siteCode = strings.TrimSpace(siteCode)
|
||||
if siteCode == "" {
|
||||
return 0, nil
|
||||
}
|
||||
var site model.DistributionSite
|
||||
if err := r.db.WithContext(ctx).Where("site_code = ? AND status = 'active'", siteCode).First(&site).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return 0, errors.New("distribution site unavailable")
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
return site.ID, nil
|
||||
}
|
||||
|
||||
func (r *Repository) Account(ctx context.Context, userID uint64, siteCode ...string) (*AccountDTO, error) {
|
||||
var code string
|
||||
if len(siteCode) > 0 {
|
||||
code = siteCode[0]
|
||||
}
|
||||
siteID, err := r.resolveSiteID(ctx, code)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var account model.WalletAccount
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := ensureAccount(tx, userID); err != nil {
|
||||
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := ensureAccount(tx, userID, siteID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Where("user_id = ?", userID).First(&account).Error
|
||||
return tx.Where("user_id = ? AND distribution_site_id = ?", userID, siteID).First(&account).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -47,14 +74,36 @@ func (r *Repository) Account(ctx context.Context, userID uint64) (*AccountDTO, e
|
||||
return toAccountDTO(account), nil
|
||||
}
|
||||
|
||||
func (r *Repository) Ledger(ctx context.Context, userID uint64, page, pageSize int) (*PaginatedResult, error) {
|
||||
func (r *Repository) Ledger(ctx context.Context, userID uint64, page, pageSize int, siteCode ...string) (*PaginatedResult, error) {
|
||||
var code string
|
||||
if len(siteCode) > 0 {
|
||||
code = siteCode[0]
|
||||
}
|
||||
siteID, err := r.resolveSiteID(ctx, code)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&model.WalletLedger{}).Where("user_id = ?", userID)
|
||||
if siteID > 0 {
|
||||
query = query.Where("distribution_site_id = ?", siteID)
|
||||
} else {
|
||||
query = query.Where("distribution_site_id = 0 OR distribution_site_id IS NULL")
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := r.db.WithContext(ctx).Model(&model.WalletLedger{}).Where("user_id = ?", userID).Count(&total).Error; err != nil {
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
offset := (page - 1) * pageSize
|
||||
var rows []model.WalletLedger
|
||||
if err := r.db.WithContext(ctx).Where("user_id = ?", userID).Order("id DESC").Offset(offset).Limit(pageSize).Find(&rows).Error; err != nil {
|
||||
dataQuery := r.db.WithContext(ctx).Where("user_id = ?", userID)
|
||||
if siteID > 0 {
|
||||
dataQuery = dataQuery.Where("distribution_site_id = ?", siteID)
|
||||
} else {
|
||||
dataQuery = dataQuery.Where("distribution_site_id = 0 OR distribution_site_id IS NULL")
|
||||
}
|
||||
if err := dataQuery.Order("id DESC").Offset(offset).Limit(pageSize).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]LedgerDTO, 0, len(rows))
|
||||
@@ -127,11 +176,11 @@ func AppendEntries(tx *gorm.DB, entries ...Entry) error {
|
||||
if entry.AmountCent <= 0 {
|
||||
continue
|
||||
}
|
||||
if err := ensureAccount(tx, entry.UserID); err != nil {
|
||||
if err := ensureAccount(tx, entry.UserID, entry.DistributionSiteID); err != nil {
|
||||
return err
|
||||
}
|
||||
var account model.WalletAccount
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("user_id = ?", entry.UserID).First(&account).Error; err != nil {
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("user_id = ? AND distribution_site_id = ?", entry.UserID, entry.DistributionSiteID).First(&account).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
balanceAfterCent, err := applyEntry(&account, entry)
|
||||
@@ -146,16 +195,17 @@ func AppendEntries(tx *gorm.DB, entries ...Entry) error {
|
||||
return err
|
||||
}
|
||||
ledger := model.WalletLedger{
|
||||
LedgerNo: ledgerNo,
|
||||
UserID: entry.UserID,
|
||||
OrderID: entry.OrderID,
|
||||
Direction: entry.Direction,
|
||||
AmountCent: entry.AmountCent,
|
||||
BalanceAfterCent: balanceAfterCent,
|
||||
BalanceType: entry.BalanceType,
|
||||
BizType: entry.BizType,
|
||||
BizNo: entry.BizNo,
|
||||
Remark: entry.Remark,
|
||||
LedgerNo: ledgerNo,
|
||||
UserID: entry.UserID,
|
||||
DistributionSiteID: entry.DistributionSiteID,
|
||||
OrderID: entry.OrderID,
|
||||
Direction: entry.Direction,
|
||||
AmountCent: entry.AmountCent,
|
||||
BalanceAfterCent: balanceAfterCent,
|
||||
BalanceType: entry.BalanceType,
|
||||
BizType: entry.BizType,
|
||||
BizNo: entry.BizNo,
|
||||
Remark: entry.Remark,
|
||||
}
|
||||
if err := tx.Create(&ledger).Error; err != nil {
|
||||
return err
|
||||
@@ -164,14 +214,19 @@ func AppendEntries(tx *gorm.DB, entries ...Entry) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func ensureAccount(tx *gorm.DB, userID uint64) error {
|
||||
return EnsureAccountTx(tx, userID)
|
||||
func ensureAccount(tx *gorm.DB, userID uint64, siteID ...uint64) error {
|
||||
return EnsureAccountTx(tx, userID, siteID...)
|
||||
}
|
||||
|
||||
// EnsureAccountTx 在事务内确保用户钱包账户存在(幂等)。
|
||||
func EnsureAccountTx(tx *gorm.DB, userID uint64) error {
|
||||
func EnsureAccountTx(tx *gorm.DB, userID uint64, siteID ...uint64) error {
|
||||
var sID uint64
|
||||
if len(siteID) > 0 {
|
||||
sID = siteID[0]
|
||||
}
|
||||
account := model.WalletAccount{
|
||||
UserID: userID,
|
||||
DistributionSiteID: sID,
|
||||
AvailableBalanceCent: 0,
|
||||
FrozenBalanceCent: 0,
|
||||
Status: "active",
|
||||
@@ -213,6 +268,7 @@ func roundWalletMoney(yuan float64) float64 {
|
||||
func toAccountDTO(account model.WalletAccount) *AccountDTO {
|
||||
return &AccountDTO{
|
||||
UserID: account.UserID,
|
||||
DistributionSiteID: account.DistributionSiteID,
|
||||
AvailableBalanceCent: account.AvailableBalanceCent,
|
||||
FrozenBalanceCent: account.FrozenBalanceCent,
|
||||
Status: account.Status,
|
||||
@@ -221,18 +277,19 @@ func toAccountDTO(account model.WalletAccount) *AccountDTO {
|
||||
|
||||
func toLedgerDTO(ledger model.WalletLedger) LedgerDTO {
|
||||
return LedgerDTO{
|
||||
ID: ledger.ID,
|
||||
LedgerNo: ledger.LedgerNo,
|
||||
UserID: ledger.UserID,
|
||||
OrderID: ledger.OrderID,
|
||||
Direction: ledger.Direction,
|
||||
AmountCent: ledger.AmountCent,
|
||||
BalanceAfterCent: ledger.BalanceAfterCent,
|
||||
BalanceType: ledger.BalanceType,
|
||||
BizType: ledger.BizType,
|
||||
BizNo: ledger.BizNo,
|
||||
Remark: ledger.Remark,
|
||||
CreatedAt: ledger.CreatedAt,
|
||||
ID: ledger.ID,
|
||||
LedgerNo: ledger.LedgerNo,
|
||||
UserID: ledger.UserID,
|
||||
DistributionSiteID: ledger.DistributionSiteID,
|
||||
OrderID: ledger.OrderID,
|
||||
Direction: ledger.Direction,
|
||||
AmountCent: ledger.AmountCent,
|
||||
BalanceAfterCent: ledger.BalanceAfterCent,
|
||||
BalanceType: ledger.BalanceType,
|
||||
BizType: ledger.BizType,
|
||||
BizNo: ledger.BizNo,
|
||||
Remark: ledger.Remark,
|
||||
CreatedAt: ledger.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ func setupTestDB(t *testing.T) *gorm.DB {
|
||||
if err := db.AutoMigrate(
|
||||
&model.WalletAccount{},
|
||||
&model.WalletLedger{},
|
||||
&model.DistributionSite{},
|
||||
); err != nil {
|
||||
t.Fatalf("数据库迁移失败: %v", err)
|
||||
}
|
||||
@@ -259,3 +260,138 @@ func TestRepositoryLedgerPagination(t *testing.T) {
|
||||
t.Fatalf("Page 3 items = %d, want 5", len(items3))
|
||||
}
|
||||
}
|
||||
|
||||
func TestWalletTenantIsolation(t *testing.T) {
|
||||
db := setupTestDB(t)
|
||||
repo := NewRepository(db)
|
||||
ctx := context.Background()
|
||||
userID := uint64(2001)
|
||||
|
||||
// 创建测试分销站点
|
||||
site := model.DistributionSite{
|
||||
ID: 10,
|
||||
SiteCode: "branch_alpha",
|
||||
SiteName: "阿尔法分站",
|
||||
Domain: "alpha.hfb.com",
|
||||
Status: "active",
|
||||
}
|
||||
if err := db.Create(&site).Error; err != nil {
|
||||
t.Fatalf("创建分销站点失败: %v", err)
|
||||
}
|
||||
|
||||
// 1. 在主站入账 5000 分
|
||||
err := db.Transaction(func(tx *gorm.DB) error {
|
||||
return AppendEntries(tx, Entry{
|
||||
UserID: userID,
|
||||
DistributionSiteID: 0,
|
||||
Direction: "in",
|
||||
AmountCent: 5000,
|
||||
BalanceType: "available",
|
||||
BizType: "main_recharge",
|
||||
BizNo: "MAIN_001",
|
||||
Remark: "主站充值",
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("主站充值失败: %v", err)
|
||||
}
|
||||
|
||||
// 2. 在分销站点入账 3000 分
|
||||
err = db.Transaction(func(tx *gorm.DB) error {
|
||||
return AppendEntries(tx, Entry{
|
||||
UserID: userID,
|
||||
DistributionSiteID: site.ID,
|
||||
Direction: "in",
|
||||
AmountCent: 3000,
|
||||
BalanceType: "available",
|
||||
BizType: "site_income",
|
||||
BizNo: "SITE_001",
|
||||
Remark: "分销站收益",
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("分站入账失败: %v", err)
|
||||
}
|
||||
|
||||
// 3. 校验主站钱包余额
|
||||
mainAccount, err := repo.Account(ctx, userID)
|
||||
if err != nil {
|
||||
t.Fatalf("查询主站钱包失败: %v", err)
|
||||
}
|
||||
if mainAccount.AvailableBalanceCent != 5000 {
|
||||
t.Fatalf("主站余额 = %d, want 5000", mainAccount.AvailableBalanceCent)
|
||||
}
|
||||
if mainAccount.DistributionSiteID != 0 {
|
||||
t.Fatalf("主站账号 DistributionSiteID = %d, want 0", mainAccount.DistributionSiteID)
|
||||
}
|
||||
|
||||
// 4. 校验分销站点钱包余额
|
||||
siteAccount, err := repo.Account(ctx, userID, site.SiteCode)
|
||||
if err != nil {
|
||||
t.Fatalf("查询分站钱包失败: %v", err)
|
||||
}
|
||||
if siteAccount.AvailableBalanceCent != 3000 {
|
||||
t.Fatalf("分站余额 = %d, want 3000", siteAccount.AvailableBalanceCent)
|
||||
}
|
||||
if siteAccount.DistributionSiteID != site.ID {
|
||||
t.Fatalf("分站账号 DistributionSiteID = %d, want %d", siteAccount.DistributionSiteID, site.ID)
|
||||
}
|
||||
|
||||
// 5. 校验流水隔离
|
||||
mainLedger, err := repo.Ledger(ctx, userID, 1, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("查询主站流水失败: %v", err)
|
||||
}
|
||||
if mainLedger.Total != 1 {
|
||||
t.Fatalf("主站流水条数 = %d, want 1", mainLedger.Total)
|
||||
}
|
||||
mainItems := mainLedger.Items.([]LedgerDTO)
|
||||
if mainItems[0].BizNo != "MAIN_001" {
|
||||
t.Fatalf("主站流水第一条 BizNo = %s, want MAIN_001", mainItems[0].BizNo)
|
||||
}
|
||||
|
||||
siteLedger, err := repo.Ledger(ctx, userID, 1, 10, site.SiteCode)
|
||||
if err != nil {
|
||||
t.Fatalf("查询分站流水失败: %v", err)
|
||||
}
|
||||
if siteLedger.Total != 1 {
|
||||
t.Fatalf("分站流水条数 = %d, want 1", siteLedger.Total)
|
||||
}
|
||||
siteItems := siteLedger.Items.([]LedgerDTO)
|
||||
if siteItems[0].BizNo != "SITE_001" {
|
||||
t.Fatalf("分站流水第一条 BizNo = %s, want SITE_001", siteItems[0].BizNo)
|
||||
}
|
||||
|
||||
// 6. 分站扣款 2000 分,主站余额不受任何影响
|
||||
err = db.Transaction(func(tx *gorm.DB) error {
|
||||
return AppendEntries(tx, Entry{
|
||||
UserID: userID,
|
||||
DistributionSiteID: site.ID,
|
||||
Direction: "out",
|
||||
AmountCent: 2000,
|
||||
BalanceType: "available",
|
||||
BizType: "site_withdraw",
|
||||
BizNo: "SITE_WD_001",
|
||||
Remark: "分站提现支出",
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("分站扣款失败: %v", err)
|
||||
}
|
||||
|
||||
siteAccountAfter, err := repo.Account(ctx, userID, site.SiteCode)
|
||||
if err != nil {
|
||||
t.Fatalf("查询扣款后分站钱包失败: %v", err)
|
||||
}
|
||||
if siteAccountAfter.AvailableBalanceCent != 1000 {
|
||||
t.Fatalf("分站扣款后余额 = %d, want 1000", siteAccountAfter.AvailableBalanceCent)
|
||||
}
|
||||
|
||||
mainAccountAfter, err := repo.Account(ctx, userID)
|
||||
if err != nil {
|
||||
t.Fatalf("再次查询主站钱包失败: %v", err)
|
||||
}
|
||||
if mainAccountAfter.AvailableBalanceCent != 5000 {
|
||||
t.Fatalf("主站余额受影响: got %d, want 5000", mainAccountAfter.AvailableBalanceCent)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,18 +20,18 @@ func NewService(repo *Repository) *Service {
|
||||
return &Service{repo: repo}
|
||||
}
|
||||
|
||||
func (s *Service) Account(ctx context.Context, userID uint64) (*AccountDTO, error) {
|
||||
func (s *Service) Account(ctx context.Context, userID uint64, siteCode ...string) (*AccountDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.Account(ctx, userID)
|
||||
return s.repo.Account(ctx, userID, siteCode...)
|
||||
}
|
||||
|
||||
func (s *Service) Ledger(ctx context.Context, userID uint64, page, pageSize int) (*PaginatedResult, error) {
|
||||
func (s *Service) Ledger(ctx context.Context, userID uint64, page, pageSize int, siteCode ...string) (*PaginatedResult, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.Ledger(ctx, userID, page, pageSize)
|
||||
return s.repo.Ledger(ctx, userID, page, pageSize, siteCode...)
|
||||
}
|
||||
|
||||
func (s *Service) Withdraw(ctx context.Context, userID uint64, req WithdrawRequest) (*AccountDTO, error) {
|
||||
|
||||
Reference in New Issue
Block a user