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:
@@ -10,7 +10,8 @@ import (
|
|||||||
type ChatConversation struct {
|
type ChatConversation struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
OrderID *uint64 `gorm:"uniqueIndex" json:"order_id"`
|
OrderID *uint64 `gorm:"uniqueIndex" json:"order_id"`
|
||||||
ListingID *uint64 `gorm:"index" json:"listing_id"`
|
ListingID *uint64 `gorm:"index" json:"listing_id"`
|
||||||
|
DistributionSiteID *uint64 `gorm:"index" json:"distribution_site_id,omitempty"`
|
||||||
// 发布群没有固定订单时,以下字段保存该商品最新订单的轻量快照,供客服列表筛选使用。
|
// 发布群没有固定订单时,以下字段保存该商品最新订单的轻量快照,供客服列表筛选使用。
|
||||||
// 这样读取会话列表不必每次扫描全部订单再按商品分组。
|
// 这样读取会话列表不必每次扫描全部订单再按商品分组。
|
||||||
LatestOrderID *uint64 `gorm:"index" json:"-"`
|
LatestOrderID *uint64 `gorm:"index" json:"-"`
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ import "time"
|
|||||||
|
|
||||||
type WalletAccount struct {
|
type WalletAccount struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
UserID uint64 `gorm:"not null;uniqueIndex" json:"user_id"`
|
UserID uint64 `gorm:"not null;uniqueIndex:uk_wallet_accounts_user_site" json:"user_id"`
|
||||||
|
DistributionSiteID uint64 `gorm:"not null;default:0;uniqueIndex:uk_wallet_accounts_user_site" json:"distribution_site_id"`
|
||||||
AvailableBalanceCent int64 `gorm:"not null;default:0" json:"-"`
|
AvailableBalanceCent int64 `gorm:"not null;default:0" json:"-"`
|
||||||
FrozenBalanceCent int64 `gorm:"not null;default:0" json:"-"`
|
FrozenBalanceCent int64 `gorm:"not null;default:0" json:"-"`
|
||||||
Status string `gorm:"size:32;not null;default:'active'" json:"status"`
|
Status string `gorm:"size:32;not null;default:'active'" json:"status"`
|
||||||
@@ -17,18 +18,19 @@ func (WalletAccount) TableName() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type WalletLedger struct {
|
type WalletLedger struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
LedgerNo string `gorm:"size:64;not null;uniqueIndex" json:"ledger_no"`
|
LedgerNo string `gorm:"size:64;not null;uniqueIndex" json:"ledger_no"`
|
||||||
UserID uint64 `gorm:"not null;index" json:"user_id"`
|
UserID uint64 `gorm:"not null;index:idx_wallet_ledger_user_site" json:"user_id"`
|
||||||
OrderID *uint64 `json:"order_id"`
|
DistributionSiteID uint64 `gorm:"not null;default:0;index:idx_wallet_ledger_user_site" json:"distribution_site_id"`
|
||||||
Direction string `gorm:"size:16;not null" json:"direction"`
|
OrderID *uint64 `json:"order_id"`
|
||||||
AmountCent int64 `gorm:"not null;default:0" json:"-"`
|
Direction string `gorm:"size:16;not null" json:"direction"`
|
||||||
BalanceAfterCent int64 `gorm:"not null;default:0" json:"-"`
|
AmountCent int64 `gorm:"not null;default:0" json:"-"`
|
||||||
BalanceType string `gorm:"size:32;not null" json:"balance_type"`
|
BalanceAfterCent int64 `gorm:"not null;default:0" json:"-"`
|
||||||
BizType string `gorm:"size:32;not null" json:"biz_type"`
|
BalanceType string `gorm:"size:32;not null" json:"balance_type"`
|
||||||
BizNo string `gorm:"size:64;not null" json:"biz_no"`
|
BizType string `gorm:"size:32;not null" json:"biz_type"`
|
||||||
Remark string `gorm:"size:255;not null;default:''" json:"remark"`
|
BizNo string `gorm:"size:64;not null" json:"biz_no"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
Remark string `gorm:"size:255;not null;default:''" json:"remark"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (WalletLedger) TableName() string {
|
func (WalletLedger) TableName() string {
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ import "time"
|
|||||||
type WithdrawalRequest struct {
|
type WithdrawalRequest struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
WithdrawNo string `gorm:"size:64;not null;uniqueIndex" json:"withdraw_no"`
|
WithdrawNo string `gorm:"size:64;not null;uniqueIndex" json:"withdraw_no"`
|
||||||
UserID uint64 `gorm:"not null;index" json:"user_id"`
|
UserID uint64 `gorm:"not null;index:idx_withdrawal_user_site" json:"user_id"`
|
||||||
|
DistributionSiteID uint64 `gorm:"not null;default:0;index:idx_withdrawal_user_site" json:"distribution_site_id"`
|
||||||
AmountCent int64 `gorm:"not null;default:0" json:"-"`
|
AmountCent int64 `gorm:"not null;default:0" json:"-"`
|
||||||
FeeCent int64 `gorm:"not null;default:0" json:"-"`
|
FeeCent int64 `gorm:"not null;default:0" json:"-"`
|
||||||
ActualAmountCent int64 `gorm:"not null;default:0" json:"-"`
|
ActualAmountCent int64 `gorm:"not null;default:0" json:"-"`
|
||||||
|
|||||||
@@ -3,28 +3,72 @@ package chat
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/clause"
|
"gorm.io/gorm/clause"
|
||||||
"hfb_sys/backend/internal/model"
|
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func (r *Repository) ListConversations(ctx context.Context, principal Principal, page, pageSize int) (*PaginatedResult, error) {
|
func (r *Repository) resolveSite(ctx context.Context, siteCode string) (*model.DistributionSite, error) {
|
||||||
|
siteCode = strings.TrimSpace(siteCode)
|
||||||
|
if siteCode == "" {
|
||||||
|
return nil, 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 nil, errors.New("distribution site unavailable")
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &site, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) ListConversations(ctx context.Context, principal Principal, page, pageSize int, siteCode ...string) (*PaginatedResult, error) {
|
||||||
page, pageSize = normalizePagination(page, pageSize)
|
page, pageSize = normalizePagination(page, pageSize)
|
||||||
db := r.db.WithContext(ctx)
|
db := r.db.WithContext(ctx)
|
||||||
var total int64
|
|
||||||
|
var code string
|
||||||
|
if len(siteCode) > 0 {
|
||||||
|
code = siteCode[0]
|
||||||
|
}
|
||||||
|
site, err := r.resolveSite(ctx, code)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
countDB := db.Table("chat_conversations AS c").
|
countDB := db.Table("chat_conversations AS c").
|
||||||
Joins("JOIN chat_participants AS cp ON cp.conversation_id = c.id").
|
Joins("JOIN chat_participants AS cp ON cp.conversation_id = c.id").
|
||||||
Where("cp.participant_type = ? AND cp.participant_id = ?", principal.Type, principal.ID).
|
Where("cp.participant_type = ? AND cp.participant_id = ?", principal.Type, principal.ID).
|
||||||
Where("c.status = ?", "active")
|
Where("c.status = ?", "active")
|
||||||
|
|
||||||
|
dataQuery := r.conversationQuery(ctx, principal).
|
||||||
|
Where("c.status = ?", "active")
|
||||||
|
|
||||||
|
if principal.Type == "user" {
|
||||||
|
if site != nil {
|
||||||
|
siteFilter := "(c.distribution_site_id = ? OR (c.order_id IS NOT NULL AND c.order_id IN (SELECT ro.id FROM rental_orders ro WHERE ro.distribution_site_id = ?)))"
|
||||||
|
countDB = countDB.Where(siteFilter, site.ID, site.ID)
|
||||||
|
dataQuery = dataQuery.Where(siteFilter, site.ID, site.ID)
|
||||||
|
} else {
|
||||||
|
mainFilter := "(c.distribution_site_id IS NULL OR c.distribution_site_id = 0) AND (c.order_id IS NULL OR c.order_id NOT IN (SELECT ro.id FROM rental_orders ro WHERE ro.distribution_site_id IS NOT NULL AND ro.distribution_site_id > 0))"
|
||||||
|
countDB = countDB.Where(mainFilter)
|
||||||
|
dataQuery = dataQuery.Where(mainFilter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var total int64
|
||||||
if err := countDB.Count(&total).Error; err != nil {
|
if err := countDB.Count(&total).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var rows []conversationRow
|
var rows []conversationRow
|
||||||
offset := (page - 1) * pageSize
|
offset := (page - 1) * pageSize
|
||||||
err := r.conversationQuery(ctx, principal).
|
err = dataQuery.
|
||||||
Where("c.status = ?", "active").
|
|
||||||
Order("COALESCE(c.last_message_at, c.created_at) DESC, c.id DESC").
|
Order("COALESCE(c.last_message_at, c.created_at) DESC, c.id DESC").
|
||||||
Offset(offset).
|
Offset(offset).
|
||||||
Limit(pageSize).
|
Limit(pageSize).
|
||||||
@@ -38,6 +82,7 @@ func (r *Repository) ListConversations(ctx context.Context, principal Principal,
|
|||||||
}
|
}
|
||||||
return &PaginatedResult{Items: items, Total: total, Page: page, PageSize: pageSize}, nil
|
return &PaginatedResult{Items: items, Total: total, Page: page, PageSize: pageSize}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Repository) FindConversation(ctx context.Context, principal Principal, id uint64) (*ConversationDTO, error) {
|
func (r *Repository) FindConversation(ctx context.Context, principal Principal, id uint64) (*ConversationDTO, error) {
|
||||||
db := r.db.WithContext(ctx)
|
db := r.db.WithContext(ctx)
|
||||||
// 管理员可以查看任意会话,无需是 participant
|
// 管理员可以查看任意会话,无需是 participant
|
||||||
@@ -69,6 +114,7 @@ func (r *Repository) FindConversation(ctx context.Context, principal Principal,
|
|||||||
ID: conversation.ID,
|
ID: conversation.ID,
|
||||||
OrderID: conversation.OrderID,
|
OrderID: conversation.OrderID,
|
||||||
ListingID: conversation.ListingID,
|
ListingID: conversation.ListingID,
|
||||||
|
DistributionSiteID: conversation.DistributionSiteID,
|
||||||
Type: conversation.Type,
|
Type: conversation.Type,
|
||||||
SupportScene: conversation.SupportScene,
|
SupportScene: conversation.SupportScene,
|
||||||
Title: conversation.Title,
|
Title: conversation.Title,
|
||||||
@@ -102,6 +148,7 @@ func (r *Repository) FindConversation(ctx context.Context, principal Principal,
|
|||||||
dto := row.toDTO(participants)
|
dto := row.toDTO(participants)
|
||||||
return &dto, nil
|
return &dto, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Repository) FindOrderConversation(ctx context.Context, userID uint64, orderID uint64) (*ConversationDTO, error) {
|
func (r *Repository) FindOrderConversation(ctx context.Context, userID uint64, orderID uint64) (*ConversationDTO, error) {
|
||||||
principal := Principal{Type: "user", ID: userID}
|
principal := Principal{Type: "user", ID: userID}
|
||||||
var order model.RentalOrder
|
var order model.RentalOrder
|
||||||
@@ -112,6 +159,22 @@ func (r *Repository) FindOrderConversation(ctx context.Context, userID uint64, o
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if order.DistributionSiteID != nil && *order.DistributionSiteID > 0 {
|
||||||
|
var row conversationRow
|
||||||
|
err := r.conversationQuery(ctx, principal).Where("c.order_id = ?", orderID).First(&row).Error
|
||||||
|
if err == nil {
|
||||||
|
participants, err := r.participants(ctx, row.ID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
dto := row.toDTO(participants)
|
||||||
|
return &dto, nil
|
||||||
|
}
|
||||||
|
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if order.ListingID > 0 {
|
if order.ListingID > 0 {
|
||||||
var row conversationRow
|
var row conversationRow
|
||||||
err := r.conversationQuery(ctx, principal).
|
err := r.conversationQuery(ctx, principal).
|
||||||
@@ -145,31 +208,52 @@ func (r *Repository) FindOrderConversation(ctx context.Context, userID uint64, o
|
|||||||
dto := row.toDTO(participants)
|
dto := row.toDTO(participants)
|
||||||
return &dto, nil
|
return &dto, nil
|
||||||
}
|
}
|
||||||
func (r *Repository) EnsureSupportConversation(ctx context.Context, userID uint64, scene string) (*ConversationDTO, error) {
|
|
||||||
|
func (r *Repository) EnsureSupportConversation(ctx context.Context, userID uint64, scene string, siteCode ...string) (*ConversationDTO, error) {
|
||||||
|
var code string
|
||||||
|
if len(siteCode) > 0 {
|
||||||
|
code = siteCode[0]
|
||||||
|
}
|
||||||
|
site, err := r.resolveSite(ctx, code)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
scene, title, groupCode, welcome := resolveSupportScene(scene)
|
scene, title, groupCode, welcome := resolveSupportScene(scene)
|
||||||
|
if site != nil {
|
||||||
|
title = fmt.Sprintf("【%s】%s", site.SiteName, title)
|
||||||
|
welcome = fmt.Sprintf("您好,欢迎咨询【%s】在线客服!请直接描述您遇到的问题,客服会尽快回复。", site.SiteName)
|
||||||
|
}
|
||||||
|
|
||||||
var conversationID uint64
|
var conversationID uint64
|
||||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
var existing model.ChatConversation
|
var existing model.ChatConversation
|
||||||
err := tx.Table("chat_conversations AS c").
|
existingQuery := tx.Table("chat_conversations AS c").
|
||||||
Select("c.*").
|
Select("c.*").
|
||||||
Joins("JOIN chat_participants AS cp ON cp.conversation_id = c.id").
|
Joins("JOIN chat_participants AS cp ON cp.conversation_id = c.id").
|
||||||
Where(
|
Where(
|
||||||
"c.type = ? AND c.support_scene = ? AND cp.participant_type = ? AND cp.participant_id = ?",
|
"c.type = ? AND c.support_scene = ? AND cp.participant_type = ? AND cp.participant_id = ?",
|
||||||
ConversationTypeGeneralSupport, scene, "user", userID,
|
ConversationTypeGeneralSupport, scene, "user", userID,
|
||||||
).
|
)
|
||||||
Order("c.id ASC").
|
|
||||||
Limit(1).
|
if site != nil {
|
||||||
Find(&existing).Error
|
existingQuery = existingQuery.Where("c.distribution_site_id = ?", site.ID)
|
||||||
|
} else {
|
||||||
|
existingQuery = existingQuery.Where("c.distribution_site_id IS NULL OR c.distribution_site_id = 0")
|
||||||
|
}
|
||||||
|
|
||||||
|
err := existingQuery.Order("c.id ASC").Limit(1).Find(&existing).Error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// 兼容旧数据:scene=general 时也匹配未回填 support_scene 的历史会话
|
|
||||||
if existing.ID == 0 && scene == SupportSceneGeneral {
|
// 兼容旧数据:主站 scene=general 时也匹配未回填 support_scene 的历史会话
|
||||||
|
if site == nil && existing.ID == 0 && scene == SupportSceneGeneral {
|
||||||
err = tx.Table("chat_conversations AS c").
|
err = tx.Table("chat_conversations AS c").
|
||||||
Select("c.*").
|
Select("c.*").
|
||||||
Joins("JOIN chat_participants AS cp ON cp.conversation_id = c.id").
|
Joins("JOIN chat_participants AS cp ON cp.conversation_id = c.id").
|
||||||
Where(
|
Where(
|
||||||
"c.type = ? AND (c.support_scene = '' OR c.support_scene IS NULL) AND cp.participant_type = ? AND cp.participant_id = ?",
|
"c.type = ? AND (c.support_scene = '' OR c.support_scene IS NULL) AND cp.participant_type = ? AND cp.participant_id = ? AND (c.distribution_site_id IS NULL OR c.distribution_site_id = 0)",
|
||||||
ConversationTypeGeneralSupport, "user", userID,
|
ConversationTypeGeneralSupport, "user", userID,
|
||||||
).
|
).
|
||||||
Order("c.id ASC").
|
Order("c.id ASC").
|
||||||
@@ -183,12 +267,12 @@ func (r *Repository) EnsureSupportConversation(ctx context.Context, userID uint6
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// 兼容旧摸大红场景码 mohong → crash
|
// 兼容旧摸大红场景码 mohong → crash
|
||||||
if existing.ID == 0 && scene == SupportSceneCrash {
|
if site == nil && existing.ID == 0 && scene == SupportSceneCrash {
|
||||||
err = tx.Table("chat_conversations AS c").
|
err = tx.Table("chat_conversations AS c").
|
||||||
Select("c.*").
|
Select("c.*").
|
||||||
Joins("JOIN chat_participants AS cp ON cp.conversation_id = c.id").
|
Joins("JOIN chat_participants AS cp ON cp.conversation_id = c.id").
|
||||||
Where(
|
Where(
|
||||||
"c.type = ? AND c.support_scene = ? AND cp.participant_type = ? AND cp.participant_id = ?",
|
"c.type = ? AND c.support_scene = ? AND cp.participant_type = ? AND cp.participant_id = ? AND (c.distribution_site_id IS NULL OR c.distribution_site_id = 0)",
|
||||||
ConversationTypeGeneralSupport, SupportSceneMohong, "user", userID,
|
ConversationTypeGeneralSupport, SupportSceneMohong, "user", userID,
|
||||||
).
|
).
|
||||||
Order("c.id ASC").
|
Order("c.id ASC").
|
||||||
@@ -210,6 +294,9 @@ func (r *Repository) EnsureSupportConversation(ctx context.Context, userID uint6
|
|||||||
Title: title,
|
Title: title,
|
||||||
Status: "active",
|
Status: "active",
|
||||||
}
|
}
|
||||||
|
if site != nil {
|
||||||
|
conversation.DistributionSiteID = &site.ID
|
||||||
|
}
|
||||||
if err := tx.Create(&conversation).Error; err != nil {
|
if err := tx.Create(&conversation).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -223,7 +310,19 @@ func (r *Repository) EnsureSupportConversation(ctx context.Context, userID uint6
|
|||||||
JoinedAt: now,
|
JoinedAt: now,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
if supportID := pickSupportAdminForScene(tx, groupCode); supportID > 0 {
|
|
||||||
|
var supportID uint64
|
||||||
|
if site != nil && site.DefaultSupportGroupID != nil && *site.DefaultSupportGroupID > 0 {
|
||||||
|
var member model.ChatSupportGroupMember
|
||||||
|
if err := tx.Where("group_id = ?", *site.DefaultSupportGroupID).Order("id ASC").First(&member).Error; err == nil && member.AdminID > 0 {
|
||||||
|
supportID = member.AdminID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if supportID == 0 {
|
||||||
|
supportID = pickSupportAdminForScene(tx, groupCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
if supportID > 0 {
|
||||||
participants = append(participants, model.ChatParticipant{
|
participants = append(participants, model.ChatParticipant{
|
||||||
ConversationID: conversation.ID,
|
ConversationID: conversation.ID,
|
||||||
ParticipantType: "admin",
|
ParticipantType: "admin",
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ func setupConversationTestDB(t *testing.T) *gorm.DB {
|
|||||||
&model.ChatParticipant{},
|
&model.ChatParticipant{},
|
||||||
&model.ChatAdminConversationState{},
|
&model.ChatAdminConversationState{},
|
||||||
&model.ChatMessage{},
|
&model.ChatMessage{},
|
||||||
|
&model.DistributionSite{},
|
||||||
); err != nil {
|
); err != nil {
|
||||||
t.Fatalf("数据库迁移失败: %v", err)
|
t.Fatalf("数据库迁移失败: %v", err)
|
||||||
}
|
}
|
||||||
@@ -151,3 +152,127 @@ func TestFindOrderConversationFallsBackToOrderGroup(t *testing.T) {
|
|||||||
t.Fatalf("会话类型 = %q, want %q", dto.Type, ConversationTypeOrderGroup)
|
t.Fatalf("会话类型 = %q, want %q", dto.Type, ConversationTypeOrderGroup)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestChatTenantIsolation(t *testing.T) {
|
||||||
|
db := setupConversationTestDB(t)
|
||||||
|
repo := NewRepository(db, nil, nil)
|
||||||
|
now := time.Now()
|
||||||
|
|
||||||
|
user := model.User{Phone: "13900002001", Nickname: "分销用户"}
|
||||||
|
if err := db.Create(&user).Error; err != nil {
|
||||||
|
t.Fatalf("创建用户失败: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
site := model.DistributionSite{
|
||||||
|
ID: 20,
|
||||||
|
SiteCode: "site_beta",
|
||||||
|
SiteName: "贝塔分销",
|
||||||
|
Domain: "beta.hfb.com",
|
||||||
|
Status: "active",
|
||||||
|
}
|
||||||
|
if err := db.Create(&site).Error; err != nil {
|
||||||
|
t.Fatalf("创建分销站点失败: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. 创建主站客服会话
|
||||||
|
mainConv := model.ChatConversation{
|
||||||
|
Type: ConversationTypeGeneralSupport,
|
||||||
|
SupportScene: SupportSceneGeneral,
|
||||||
|
Title: "主站客服",
|
||||||
|
Status: "active",
|
||||||
|
}
|
||||||
|
if err := db.Create(&mainConv).Error; err != nil {
|
||||||
|
t.Fatalf("创建主站客服会话失败: %v", err)
|
||||||
|
}
|
||||||
|
if err := db.Create(&model.ChatParticipant{
|
||||||
|
ConversationID: mainConv.ID,
|
||||||
|
ParticipantType: "user",
|
||||||
|
ParticipantID: user.ID,
|
||||||
|
Role: "customer",
|
||||||
|
JoinedAt: now,
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatalf("添加主站会话成员失败: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 创建分销站客服会话
|
||||||
|
siteConv := model.ChatConversation{
|
||||||
|
DistributionSiteID: &site.ID,
|
||||||
|
Type: ConversationTypeGeneralSupport,
|
||||||
|
SupportScene: SupportSceneGeneral,
|
||||||
|
Title: "【贝塔分销】平台客服",
|
||||||
|
Status: "active",
|
||||||
|
}
|
||||||
|
if err := db.Create(&siteConv).Error; err != nil {
|
||||||
|
t.Fatalf("创建分站客服会话失败: %v", err)
|
||||||
|
}
|
||||||
|
if err := db.Create(&model.ChatParticipant{
|
||||||
|
ConversationID: siteConv.ID,
|
||||||
|
ParticipantType: "user",
|
||||||
|
ParticipantID: user.ID,
|
||||||
|
Role: "customer",
|
||||||
|
JoinedAt: now,
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatalf("添加分站会话成员失败: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
principal := Principal{Type: "user", ID: user.ID}
|
||||||
|
|
||||||
|
// 3. 校验主站查询会话列表:严格只看到主站会话
|
||||||
|
mainList, err := repo.ListConversations(t.Context(), principal, 1, 20)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("查询主站会话列表失败: %v", err)
|
||||||
|
}
|
||||||
|
if mainList.Total != 1 {
|
||||||
|
t.Fatalf("主站会话数量 = %d, want 1", mainList.Total)
|
||||||
|
}
|
||||||
|
mainItems := mainList.Items.([]ConversationDTO)
|
||||||
|
if mainItems[0].ID != mainConv.ID {
|
||||||
|
t.Fatalf("主站会话 ID = %d, want %d", mainItems[0].ID, mainConv.ID)
|
||||||
|
}
|
||||||
|
if mainItems[0].DistributionSiteID != nil {
|
||||||
|
t.Fatalf("主站会话 DistributionSiteID = %v, want nil", mainItems[0].DistributionSiteID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 校验分站查询会话列表:严格只看到分站会话
|
||||||
|
siteList, err := repo.ListConversations(t.Context(), principal, 1, 20, site.SiteCode)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("查询分站会话列表失败: %v", err)
|
||||||
|
}
|
||||||
|
if siteList.Total != 1 {
|
||||||
|
t.Fatalf("分站会话数量 = %d, want 1", siteList.Total)
|
||||||
|
}
|
||||||
|
siteItems := siteList.Items.([]ConversationDTO)
|
||||||
|
if siteItems[0].ID != siteConv.ID {
|
||||||
|
t.Fatalf("分站会话 ID = %d, want %d", siteItems[0].ID, siteConv.ID)
|
||||||
|
}
|
||||||
|
if siteItems[0].DistributionSiteID == nil || *siteItems[0].DistributionSiteID != site.ID {
|
||||||
|
t.Fatalf("分站会话 DistributionSiteID = %v, want %d", siteItems[0].DistributionSiteID, site.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. 测试 EnsureSupportConversation 分销站点场景
|
||||||
|
ensuredSiteConv, err := repo.EnsureSupportConversation(t.Context(), user.ID, "crash", site.SiteCode)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("分站创建撞车客服失败: %v", err)
|
||||||
|
}
|
||||||
|
if ensuredSiteConv.DistributionSiteID == nil || *ensuredSiteConv.DistributionSiteID != site.ID {
|
||||||
|
t.Fatalf("新建分站会话 DistributionSiteID = %v, want %d", ensuredSiteConv.DistributionSiteID, site.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 主站再次查询,仍然只有 1 个主站会话
|
||||||
|
mainListAfter, err := repo.ListConversations(t.Context(), principal, 1, 20)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("主站列表查询失败: %v", err)
|
||||||
|
}
|
||||||
|
if mainListAfter.Total != 1 {
|
||||||
|
t.Fatalf("主站会话数量 = %d, want 1 (分站新增会话不应出现在主站)", mainListAfter.Total)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分站再次查询,有 2 个分站会话
|
||||||
|
siteListAfter, err := repo.ListConversations(t.Context(), principal, 1, 20, site.SiteCode)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("分站列表查询失败: %v", err)
|
||||||
|
}
|
||||||
|
if siteListAfter.Total != 2 {
|
||||||
|
t.Fatalf("分站会话数量 = %d, want 2", siteListAfter.Total)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ type ConversationDTO struct {
|
|||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
OrderID *uint64 `json:"order_id"`
|
OrderID *uint64 `json:"order_id"`
|
||||||
ListingID *uint64 `json:"listing_id"`
|
ListingID *uint64 `json:"listing_id"`
|
||||||
|
DistributionSiteID *uint64 `json:"distribution_site_id,omitempty"`
|
||||||
LatestOrderID *uint64 `json:"latest_order_id,omitempty"`
|
LatestOrderID *uint64 `json:"latest_order_id,omitempty"`
|
||||||
LatestOrderNo string `json:"latest_order_no,omitempty"`
|
LatestOrderNo string `json:"latest_order_no,omitempty"`
|
||||||
LatestOrderStatus string `json:"latest_order_status,omitempty"`
|
LatestOrderStatus string `json:"latest_order_status,omitempty"`
|
||||||
@@ -38,7 +39,8 @@ type ConversationDTO struct {
|
|||||||
// EnsureSupportRequest 创建/复用客服会话。
|
// EnsureSupportRequest 创建/复用客服会话。
|
||||||
type EnsureSupportRequest struct {
|
type EnsureSupportRequest struct {
|
||||||
// Scene 业务场景:general(默认)/ crash(撞车,兼容旧值 mohong)
|
// Scene 业务场景:general(默认)/ crash(撞车,兼容旧值 mohong)
|
||||||
Scene string `json:"scene"`
|
Scene string `json:"scene"`
|
||||||
|
DistributionSiteCode string `json:"distribution_site_code"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ParticipantDTO struct {
|
type ParticipantDTO struct {
|
||||||
|
|||||||
@@ -1,14 +1,31 @@
|
|||||||
package chat
|
package chat
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
"hfb_sys/backend/pkg/response"
|
"hfb_sys/backend/pkg/response"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
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) list(c *gin.Context, principal Principal) {
|
func (h *Handler) list(c *gin.Context, principal Principal) {
|
||||||
page, pageSize := parsePagination(c)
|
page, pageSize := parsePagination(c)
|
||||||
result, err := h.service.ListConversations(c.Request.Context(), principal, page, pageSize)
|
siteCode := parseSiteCode(c)
|
||||||
|
result, err := h.service.ListConversations(c.Request.Context(), principal, page, pageSize, siteCode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeChatError(c, err)
|
writeChatError(c, err)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -21,7 +21,8 @@ func (h *Handler) UnreadCount(c *gin.Context) {
|
|||||||
response.Unauthorized(c, "缺少用户上下文")
|
response.Unauthorized(c, "缺少用户上下文")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
result, err := h.service.CountUnreadMessages(c.Request.Context(), Principal{Type: "user", ID: userID})
|
siteCode := parseSiteCode(c)
|
||||||
|
result, err := h.service.CountUnreadMessages(c.Request.Context(), Principal{Type: "user", ID: userID}, siteCode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeChatError(c, err)
|
writeChatError(c, err)
|
||||||
return
|
return
|
||||||
@@ -65,7 +66,11 @@ func (h *Handler) EnsureSupportConversation(c *gin.Context) {
|
|||||||
var req EnsureSupportRequest
|
var req EnsureSupportRequest
|
||||||
// scene 可选;空 body 仍按平台客服处理
|
// scene 可选;空 body 仍按平台客服处理
|
||||||
_ = c.ShouldBindJSON(&req)
|
_ = c.ShouldBindJSON(&req)
|
||||||
item, err := h.service.EnsureSupportConversation(c.Request.Context(), userID, req.Scene)
|
siteCode := parseSiteCode(c)
|
||||||
|
if siteCode == "" && req.DistributionSiteCode != "" {
|
||||||
|
siteCode = req.DistributionSiteCode
|
||||||
|
}
|
||||||
|
item, err := h.service.EnsureSupportConversation(c.Request.Context(), userID, req.Scene, siteCode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeChatError(c, err)
|
writeChatError(c, err)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ type conversationRow struct {
|
|||||||
ID uint64
|
ID uint64
|
||||||
OrderID *uint64
|
OrderID *uint64
|
||||||
ListingID *uint64
|
ListingID *uint64
|
||||||
|
DistributionSiteID *uint64
|
||||||
LatestOrderID *uint64
|
LatestOrderID *uint64
|
||||||
LatestOrderNo string
|
LatestOrderNo string
|
||||||
LatestOrderStatus string
|
LatestOrderStatus string
|
||||||
@@ -40,7 +41,7 @@ type conversationRow struct {
|
|||||||
|
|
||||||
func (r *Repository) conversationQuery(ctx context.Context, principal Principal) *gorm.DB {
|
func (r *Repository) conversationQuery(ctx context.Context, principal Principal) *gorm.DB {
|
||||||
return r.db.WithContext(ctx).Table("chat_conversations AS c").
|
return r.db.WithContext(ctx).Table("chat_conversations AS c").
|
||||||
Select(`c.id, c.order_id, c.listing_id, c.type, c.support_scene, c.title, c.status, c.last_message_id,
|
Select(`c.id, c.order_id, c.listing_id, c.distribution_site_id, c.type, c.support_scene, c.title, c.status, c.last_message_id,
|
||||||
c.last_message_preview, c.last_message_at, c.created_at, c.updated_at, cp.role,
|
c.last_message_preview, c.last_message_at, c.created_at, c.updated_at, cp.role,
|
||||||
(
|
(
|
||||||
SELECT COUNT(1)
|
SELECT COUNT(1)
|
||||||
@@ -54,17 +55,37 @@ func (r *Repository) conversationQuery(ctx context.Context, principal Principal)
|
|||||||
Where("cp.participant_type = ? AND cp.participant_id = ?", principal.Type, principal.ID)
|
Where("cp.participant_type = ? AND cp.participant_id = ?", principal.Type, principal.ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Repository) CountUnreadMessages(ctx context.Context, principal Principal) (int64, error) {
|
func (r *Repository) CountUnreadMessages(ctx context.Context, principal Principal, siteCode ...string) (int64, error) {
|
||||||
var total int64
|
var code string
|
||||||
err := r.db.WithContext(ctx).Table("chat_messages AS cm").
|
if len(siteCode) > 0 {
|
||||||
|
code = siteCode[0]
|
||||||
|
}
|
||||||
|
site, err := r.resolveSite(ctx, code)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
query := r.db.WithContext(ctx).Table("chat_messages AS cm").
|
||||||
Joins("JOIN chat_participants AS cp ON cp.conversation_id = cm.conversation_id").
|
Joins("JOIN chat_participants AS cp ON cp.conversation_id = cm.conversation_id").
|
||||||
Joins("JOIN chat_conversations AS c ON c.id = cm.conversation_id").
|
Joins("JOIN chat_conversations AS c ON c.id = cm.conversation_id").
|
||||||
Where("cp.participant_type = ? AND cp.participant_id = ?", principal.Type, principal.ID).
|
Where("cp.participant_type = ? AND cp.participant_id = ?", principal.Type, principal.ID).
|
||||||
Where("c.status = ?", "active").
|
Where("c.status = ?", "active").
|
||||||
Where("NOT (cm.sender_type = ? AND cm.sender_id = ?)", principal.Type, principal.ID).
|
Where("NOT (cm.sender_type = ? AND cm.sender_id = ?)", principal.Type, principal.ID).
|
||||||
Where("cm.sender_type <> ?", "system").
|
Where("cm.sender_type <> ?", "system").
|
||||||
Where("(cp.last_read_at IS NULL OR cm.created_at > cp.last_read_at)").
|
Where("(cp.last_read_at IS NULL OR cm.created_at > cp.last_read_at)")
|
||||||
Count(&total).Error
|
|
||||||
|
if principal.Type == "user" {
|
||||||
|
if site != nil {
|
||||||
|
siteFilter := "(c.distribution_site_id = ? OR (c.order_id IS NOT NULL AND c.order_id IN (SELECT ro.id FROM rental_orders ro WHERE ro.distribution_site_id = ?)))"
|
||||||
|
query = query.Where(siteFilter, site.ID, site.ID)
|
||||||
|
} else {
|
||||||
|
mainFilter := "(c.distribution_site_id IS NULL OR c.distribution_site_id = 0) AND (c.order_id IS NULL OR c.order_id NOT IN (SELECT ro.id FROM rental_orders ro WHERE ro.distribution_site_id IS NOT NULL AND ro.distribution_site_id > 0))"
|
||||||
|
query = query.Where(mainFilter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var total int64
|
||||||
|
err = query.Count(&total).Error
|
||||||
return total, err
|
return total, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,6 +336,7 @@ func (row conversationRow) toDTO(participants []ParticipantDTO) ConversationDTO
|
|||||||
ID: row.ID,
|
ID: row.ID,
|
||||||
OrderID: row.OrderID,
|
OrderID: row.OrderID,
|
||||||
ListingID: row.ListingID,
|
ListingID: row.ListingID,
|
||||||
|
DistributionSiteID: row.DistributionSiteID,
|
||||||
LatestOrderID: row.LatestOrderID,
|
LatestOrderID: row.LatestOrderID,
|
||||||
LatestOrderNo: row.LatestOrderNo,
|
LatestOrderNo: row.LatestOrderNo,
|
||||||
LatestOrderStatus: row.LatestOrderStatus,
|
LatestOrderStatus: row.LatestOrderStatus,
|
||||||
|
|||||||
@@ -89,10 +89,11 @@ func EnsureOrderConversation(tx *gorm.DB, order model.RentalOrder) (*model.ChatC
|
|||||||
|
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
conversation := model.ChatConversation{
|
conversation := model.ChatConversation{
|
||||||
OrderID: &order.ID,
|
OrderID: &order.ID,
|
||||||
Type: "order_group",
|
DistributionSiteID: order.DistributionSiteID,
|
||||||
Title: orderConversationTitle(order),
|
Type: "order_group",
|
||||||
Status: "active",
|
Title: orderConversationTitle(order),
|
||||||
|
Status: "active",
|
||||||
}
|
}
|
||||||
if err := tx.Create(&conversation).Error; err != nil {
|
if err := tx.Create(&conversation).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -22,18 +22,18 @@ func NewService(repo *Repository) *Service {
|
|||||||
return &Service{repo: repo}
|
return &Service{repo: repo}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) ListConversations(ctx context.Context, principal Principal, page, pageSize int) (*PaginatedResult, error) {
|
func (s *Service) ListConversations(ctx context.Context, principal Principal, page, pageSize int, siteCode ...string) (*PaginatedResult, error) {
|
||||||
if s.repo == nil {
|
if s.repo == nil {
|
||||||
return nil, ErrDependencyUnavailable
|
return nil, ErrDependencyUnavailable
|
||||||
}
|
}
|
||||||
return s.repo.ListConversations(ctx, principal, page, pageSize)
|
return s.repo.ListConversations(ctx, principal, page, pageSize, siteCode...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) CountUnreadMessages(ctx context.Context, principal Principal) (*UnreadCountDTO, error) {
|
func (s *Service) CountUnreadMessages(ctx context.Context, principal Principal, siteCode ...string) (*UnreadCountDTO, error) {
|
||||||
if s.repo == nil {
|
if s.repo == nil {
|
||||||
return nil, ErrDependencyUnavailable
|
return nil, ErrDependencyUnavailable
|
||||||
}
|
}
|
||||||
total, err := s.repo.CountUnreadMessages(ctx, principal)
|
total, err := s.repo.CountUnreadMessages(ctx, principal, siteCode...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -54,14 +54,14 @@ func (s *Service) FindOrderConversation(ctx context.Context, userID uint64, orde
|
|||||||
return s.repo.FindOrderConversation(ctx, userID, orderID)
|
return s.repo.FindOrderConversation(ctx, userID, orderID)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) EnsureSupportConversation(ctx context.Context, userID uint64, scene string) (*ConversationDTO, error) {
|
func (s *Service) EnsureSupportConversation(ctx context.Context, userID uint64, scene string, siteCode ...string) (*ConversationDTO, error) {
|
||||||
if s.repo == nil {
|
if s.repo == nil {
|
||||||
return nil, ErrDependencyUnavailable
|
return nil, ErrDependencyUnavailable
|
||||||
}
|
}
|
||||||
if userID == 0 {
|
if userID == 0 {
|
||||||
return nil, ErrPermissionDenied
|
return nil, ErrPermissionDenied
|
||||||
}
|
}
|
||||||
return s.repo.EnsureSupportConversation(ctx, userID, scene)
|
return s.repo.EnsureSupportConversation(ctx, userID, scene, siteCode...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) Messages(ctx context.Context, principal Principal, conversationID uint64, page, pageSize int) (*PaginatedResult, error) {
|
func (s *Service) Messages(ctx context.Context, principal Principal, conversationID uint64, page, pageSize int) (*PaginatedResult, error) {
|
||||||
|
|||||||
@@ -69,29 +69,35 @@ func appendCheckoutOwnerIncome(tx *gorm.DB, order *model.RentalOrder, settlement
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
orderID := order.ID
|
orderID := order.ID
|
||||||
|
var siteID uint64
|
||||||
|
if order.DistributionSiteID != nil {
|
||||||
|
siteID = *order.DistributionSiteID
|
||||||
|
}
|
||||||
var ownerEntries []wallet.Entry
|
var ownerEntries []wallet.Entry
|
||||||
if settlement.OwnerRentIncomeCent > 0 {
|
if settlement.OwnerRentIncomeCent > 0 {
|
||||||
ownerEntries = append(ownerEntries, wallet.Entry{
|
ownerEntries = append(ownerEntries, wallet.Entry{
|
||||||
UserID: order.OwnerID,
|
UserID: order.OwnerID,
|
||||||
OrderID: &orderID,
|
DistributionSiteID: siteID,
|
||||||
Direction: "in",
|
OrderID: &orderID,
|
||||||
AmountCent: settlement.OwnerRentIncomeCent,
|
Direction: "in",
|
||||||
BalanceType: "available",
|
AmountCent: settlement.OwnerRentIncomeCent,
|
||||||
BizType: walletBizOwnerIncome,
|
BalanceType: "available",
|
||||||
BizNo: order.OrderNo,
|
BizType: walletBizOwnerIncome,
|
||||||
Remark: "订单结账租金收入",
|
BizNo: order.OrderNo,
|
||||||
|
Remark: "订单结账租金收入",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
if settlement.DepositCompensationCent > 0 {
|
if settlement.DepositCompensationCent > 0 {
|
||||||
ownerEntries = append(ownerEntries, wallet.Entry{
|
ownerEntries = append(ownerEntries, wallet.Entry{
|
||||||
UserID: order.OwnerID,
|
UserID: order.OwnerID,
|
||||||
OrderID: &orderID,
|
DistributionSiteID: siteID,
|
||||||
Direction: "in",
|
OrderID: &orderID,
|
||||||
AmountCent: settlement.DepositCompensationCent,
|
Direction: "in",
|
||||||
BalanceType: "available",
|
AmountCent: settlement.DepositCompensationCent,
|
||||||
BizType: walletBizDepositCompensation,
|
BalanceType: "available",
|
||||||
BizNo: order.OrderNo,
|
BizType: walletBizDepositCompensation,
|
||||||
Remark: "订单结账押金赔付",
|
BizNo: order.OrderNo,
|
||||||
|
Remark: "订单结账押金赔付",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
if len(ownerEntries) == 0 {
|
if len(ownerEntries) == 0 {
|
||||||
|
|||||||
@@ -273,15 +273,25 @@ func (r *Repository) ConfirmPaidFromChannelTx(tx *gorm.DB, orderID uint64) (uint
|
|||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// 拉租客进发布群(替代原来的建订单群)
|
// 分销订单创建独立分站群聊;主站订单拉租客进发布群
|
||||||
conversationID := uint64(0)
|
conversationID := uint64(0)
|
||||||
if err := chat.AddRenterToListingConversation(tx, listing.ID, order.RenterID, order.OrderNo); err != nil {
|
if order.DistributionSiteID != nil && *order.DistributionSiteID > 0 {
|
||||||
return 0, err
|
orderConv, err := chat.EnsureOrderConversation(tx, *order)
|
||||||
}
|
if err != nil {
|
||||||
// 查询发布群ID用于返回
|
return 0, err
|
||||||
var listingConv model.ChatConversation
|
}
|
||||||
if err := tx.Where("listing_id = ?", listing.ID).First(&listingConv).Error; err == nil {
|
if orderConv != nil {
|
||||||
conversationID = listingConv.ID
|
conversationID = orderConv.ID
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err := chat.AddRenterToListingConversation(tx, listing.ID, order.RenterID, order.OrderNo); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
// 查询发布群ID用于返回
|
||||||
|
var listingConv model.ChatConversation
|
||||||
|
if err := tx.Where("listing_id = ?", listing.ID).First(&listingConv).Error; err == nil {
|
||||||
|
conversationID = listingConv.ID
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if isPlatformHandoffOrder(*order) {
|
if isPlatformHandoffOrder(*order) {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import "time"
|
|||||||
|
|
||||||
type AccountDTO struct {
|
type AccountDTO struct {
|
||||||
UserID uint64 `json:"user_id"`
|
UserID uint64 `json:"user_id"`
|
||||||
|
DistributionSiteID uint64 `json:"distribution_site_id"`
|
||||||
AvailableBalanceCent int64 `json:"available_balance_cent"`
|
AvailableBalanceCent int64 `json:"available_balance_cent"`
|
||||||
FrozenBalanceCent int64 `json:"frozen_balance_cent"`
|
FrozenBalanceCent int64 `json:"frozen_balance_cent"`
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
@@ -14,18 +15,19 @@ type WithdrawRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type LedgerDTO struct {
|
type LedgerDTO struct {
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
LedgerNo string `json:"ledger_no"`
|
LedgerNo string `json:"ledger_no"`
|
||||||
UserID uint64 `json:"user_id"`
|
UserID uint64 `json:"user_id"`
|
||||||
OrderID *uint64 `json:"order_id"`
|
DistributionSiteID uint64 `json:"distribution_site_id"`
|
||||||
Direction string `json:"direction"`
|
OrderID *uint64 `json:"order_id"`
|
||||||
AmountCent int64 `json:"amount_cent"`
|
Direction string `json:"direction"`
|
||||||
BalanceAfterCent int64 `json:"balance_after_cent"`
|
AmountCent int64 `json:"amount_cent"`
|
||||||
BalanceType string `json:"balance_type"`
|
BalanceAfterCent int64 `json:"balance_after_cent"`
|
||||||
BizType string `json:"biz_type"`
|
BalanceType string `json:"balance_type"`
|
||||||
BizNo string `json:"biz_no"`
|
BizType string `json:"biz_type"`
|
||||||
Remark string `json:"remark"`
|
BizNo string `json:"biz_no"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
Remark string `json:"remark"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type AdminLedgerQuery struct {
|
type AdminLedgerQuery struct {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package wallet
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/middleware"
|
"hfb_sys/backend/internal/middleware"
|
||||||
"hfb_sys/backend/pkg/response"
|
"hfb_sys/backend/pkg/response"
|
||||||
@@ -18,13 +19,28 @@ func NewHandler(service *Service) *Handler {
|
|||||||
return &Handler{service: service}
|
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) {
|
func (h *Handler) Balance(c *gin.Context) {
|
||||||
userID, ok := currentUserID(c)
|
userID, ok := currentUserID(c)
|
||||||
if !ok {
|
if !ok {
|
||||||
response.Unauthorized(c, "缺少用户上下文")
|
response.Unauthorized(c, "缺少用户上下文")
|
||||||
return
|
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 {
|
if err != nil {
|
||||||
writeWalletError(c, err)
|
writeWalletError(c, err)
|
||||||
return
|
return
|
||||||
@@ -54,7 +70,8 @@ func (h *Handler) Ledger(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
page, pageSize := parsePagination(c)
|
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 {
|
if err != nil {
|
||||||
writeWalletError(c, err)
|
writeWalletError(c, err)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ package wallet
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
@@ -19,27 +21,52 @@ type Repository struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Entry struct {
|
type Entry struct {
|
||||||
UserID uint64
|
UserID uint64
|
||||||
OrderID *uint64
|
DistributionSiteID uint64
|
||||||
Direction string
|
OrderID *uint64
|
||||||
AmountCent int64
|
Direction string
|
||||||
BalanceType string
|
AmountCent int64
|
||||||
BizType string
|
BalanceType string
|
||||||
BizNo string
|
BizType string
|
||||||
Remark string
|
BizNo string
|
||||||
|
Remark string
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRepository(db *gorm.DB) *Repository {
|
func NewRepository(db *gorm.DB) *Repository {
|
||||||
return &Repository{db: db}
|
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
|
var account model.WalletAccount
|
||||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
if err := ensureAccount(tx, userID); err != nil {
|
if err := ensureAccount(tx, userID, siteID); err != nil {
|
||||||
return err
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -47,14 +74,36 @@ func (r *Repository) Account(ctx context.Context, userID uint64) (*AccountDTO, e
|
|||||||
return toAccountDTO(account), nil
|
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
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
offset := (page - 1) * pageSize
|
offset := (page - 1) * pageSize
|
||||||
var rows []model.WalletLedger
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
items := make([]LedgerDTO, 0, len(rows))
|
items := make([]LedgerDTO, 0, len(rows))
|
||||||
@@ -127,11 +176,11 @@ func AppendEntries(tx *gorm.DB, entries ...Entry) error {
|
|||||||
if entry.AmountCent <= 0 {
|
if entry.AmountCent <= 0 {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if err := ensureAccount(tx, entry.UserID); err != nil {
|
if err := ensureAccount(tx, entry.UserID, entry.DistributionSiteID); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
var account model.WalletAccount
|
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
|
return err
|
||||||
}
|
}
|
||||||
balanceAfterCent, err := applyEntry(&account, entry)
|
balanceAfterCent, err := applyEntry(&account, entry)
|
||||||
@@ -146,16 +195,17 @@ func AppendEntries(tx *gorm.DB, entries ...Entry) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
ledger := model.WalletLedger{
|
ledger := model.WalletLedger{
|
||||||
LedgerNo: ledgerNo,
|
LedgerNo: ledgerNo,
|
||||||
UserID: entry.UserID,
|
UserID: entry.UserID,
|
||||||
OrderID: entry.OrderID,
|
DistributionSiteID: entry.DistributionSiteID,
|
||||||
Direction: entry.Direction,
|
OrderID: entry.OrderID,
|
||||||
AmountCent: entry.AmountCent,
|
Direction: entry.Direction,
|
||||||
BalanceAfterCent: balanceAfterCent,
|
AmountCent: entry.AmountCent,
|
||||||
BalanceType: entry.BalanceType,
|
BalanceAfterCent: balanceAfterCent,
|
||||||
BizType: entry.BizType,
|
BalanceType: entry.BalanceType,
|
||||||
BizNo: entry.BizNo,
|
BizType: entry.BizType,
|
||||||
Remark: entry.Remark,
|
BizNo: entry.BizNo,
|
||||||
|
Remark: entry.Remark,
|
||||||
}
|
}
|
||||||
if err := tx.Create(&ledger).Error; err != nil {
|
if err := tx.Create(&ledger).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -164,14 +214,19 @@ func AppendEntries(tx *gorm.DB, entries ...Entry) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ensureAccount(tx *gorm.DB, userID uint64) error {
|
func ensureAccount(tx *gorm.DB, userID uint64, siteID ...uint64) error {
|
||||||
return EnsureAccountTx(tx, userID)
|
return EnsureAccountTx(tx, userID, siteID...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// EnsureAccountTx 在事务内确保用户钱包账户存在(幂等)。
|
// 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{
|
account := model.WalletAccount{
|
||||||
UserID: userID,
|
UserID: userID,
|
||||||
|
DistributionSiteID: sID,
|
||||||
AvailableBalanceCent: 0,
|
AvailableBalanceCent: 0,
|
||||||
FrozenBalanceCent: 0,
|
FrozenBalanceCent: 0,
|
||||||
Status: "active",
|
Status: "active",
|
||||||
@@ -213,6 +268,7 @@ func roundWalletMoney(yuan float64) float64 {
|
|||||||
func toAccountDTO(account model.WalletAccount) *AccountDTO {
|
func toAccountDTO(account model.WalletAccount) *AccountDTO {
|
||||||
return &AccountDTO{
|
return &AccountDTO{
|
||||||
UserID: account.UserID,
|
UserID: account.UserID,
|
||||||
|
DistributionSiteID: account.DistributionSiteID,
|
||||||
AvailableBalanceCent: account.AvailableBalanceCent,
|
AvailableBalanceCent: account.AvailableBalanceCent,
|
||||||
FrozenBalanceCent: account.FrozenBalanceCent,
|
FrozenBalanceCent: account.FrozenBalanceCent,
|
||||||
Status: account.Status,
|
Status: account.Status,
|
||||||
@@ -221,18 +277,19 @@ func toAccountDTO(account model.WalletAccount) *AccountDTO {
|
|||||||
|
|
||||||
func toLedgerDTO(ledger model.WalletLedger) LedgerDTO {
|
func toLedgerDTO(ledger model.WalletLedger) LedgerDTO {
|
||||||
return LedgerDTO{
|
return LedgerDTO{
|
||||||
ID: ledger.ID,
|
ID: ledger.ID,
|
||||||
LedgerNo: ledger.LedgerNo,
|
LedgerNo: ledger.LedgerNo,
|
||||||
UserID: ledger.UserID,
|
UserID: ledger.UserID,
|
||||||
OrderID: ledger.OrderID,
|
DistributionSiteID: ledger.DistributionSiteID,
|
||||||
Direction: ledger.Direction,
|
OrderID: ledger.OrderID,
|
||||||
AmountCent: ledger.AmountCent,
|
Direction: ledger.Direction,
|
||||||
BalanceAfterCent: ledger.BalanceAfterCent,
|
AmountCent: ledger.AmountCent,
|
||||||
BalanceType: ledger.BalanceType,
|
BalanceAfterCent: ledger.BalanceAfterCent,
|
||||||
BizType: ledger.BizType,
|
BalanceType: ledger.BalanceType,
|
||||||
BizNo: ledger.BizNo,
|
BizType: ledger.BizType,
|
||||||
Remark: ledger.Remark,
|
BizNo: ledger.BizNo,
|
||||||
CreatedAt: ledger.CreatedAt,
|
Remark: ledger.Remark,
|
||||||
|
CreatedAt: ledger.CreatedAt,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ func setupTestDB(t *testing.T) *gorm.DB {
|
|||||||
if err := db.AutoMigrate(
|
if err := db.AutoMigrate(
|
||||||
&model.WalletAccount{},
|
&model.WalletAccount{},
|
||||||
&model.WalletLedger{},
|
&model.WalletLedger{},
|
||||||
|
&model.DistributionSite{},
|
||||||
); err != nil {
|
); err != nil {
|
||||||
t.Fatalf("数据库迁移失败: %v", err)
|
t.Fatalf("数据库迁移失败: %v", err)
|
||||||
}
|
}
|
||||||
@@ -259,3 +260,138 @@ func TestRepositoryLedgerPagination(t *testing.T) {
|
|||||||
t.Fatalf("Page 3 items = %d, want 5", len(items3))
|
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}
|
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 {
|
if s.repo == nil {
|
||||||
return nil, ErrDependencyUnavailable
|
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 {
|
if s.repo == nil {
|
||||||
return nil, ErrDependencyUnavailable
|
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) {
|
func (s *Service) Withdraw(ctx context.Context, userID uint64, req WithdrawRequest) (*AccountDTO, error) {
|
||||||
|
|||||||
@@ -106,21 +106,23 @@ func (r *Repository) Review(ctx context.Context, adminID, id uint64, req ReviewW
|
|||||||
// 如果拒绝,解冻余额
|
// 如果拒绝,解冻余额
|
||||||
if !approved {
|
if !approved {
|
||||||
if err := wallet.AppendEntries(tx, wallet.Entry{
|
if err := wallet.AppendEntries(tx, wallet.Entry{
|
||||||
UserID: withdrawal.UserID,
|
UserID: withdrawal.UserID,
|
||||||
Direction: "out",
|
DistributionSiteID: withdrawal.DistributionSiteID,
|
||||||
AmountCent: withdrawal.AmountCent,
|
Direction: "out",
|
||||||
BalanceType: "frozen",
|
AmountCent: withdrawal.AmountCent,
|
||||||
BizType: "withdraw_reject",
|
BalanceType: "frozen",
|
||||||
BizNo: withdrawal.WithdrawNo,
|
BizType: "withdraw_reject",
|
||||||
Remark: fmt.Sprintf("提现被拒绝: %s", req.Remark),
|
BizNo: withdrawal.WithdrawNo,
|
||||||
|
Remark: fmt.Sprintf("提现被拒绝: %s", req.Remark),
|
||||||
}, wallet.Entry{
|
}, wallet.Entry{
|
||||||
UserID: withdrawal.UserID,
|
UserID: withdrawal.UserID,
|
||||||
Direction: "in",
|
DistributionSiteID: withdrawal.DistributionSiteID,
|
||||||
AmountCent: withdrawal.AmountCent,
|
Direction: "in",
|
||||||
BalanceType: "available",
|
AmountCent: withdrawal.AmountCent,
|
||||||
BizType: "withdraw_reject",
|
BalanceType: "available",
|
||||||
BizNo: withdrawal.WithdrawNo,
|
BizType: "withdraw_reject",
|
||||||
Remark: fmt.Sprintf("提现被拒绝: %s", req.Remark),
|
BizNo: withdrawal.WithdrawNo,
|
||||||
|
Remark: fmt.Sprintf("提现被拒绝: %s", req.Remark),
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -166,13 +168,14 @@ func (r *Repository) ConfirmPayment(ctx context.Context, adminID, id uint64, req
|
|||||||
|
|
||||||
// 扣除冻结余额
|
// 扣除冻结余额
|
||||||
if err := wallet.AppendEntries(tx, wallet.Entry{
|
if err := wallet.AppendEntries(tx, wallet.Entry{
|
||||||
UserID: withdrawal.UserID,
|
UserID: withdrawal.UserID,
|
||||||
Direction: "out",
|
DistributionSiteID: withdrawal.DistributionSiteID,
|
||||||
AmountCent: withdrawal.AmountCent,
|
Direction: "out",
|
||||||
BalanceType: "frozen",
|
AmountCent: withdrawal.AmountCent,
|
||||||
BizType: "withdraw_complete",
|
BalanceType: "frozen",
|
||||||
BizNo: withdrawal.WithdrawNo,
|
BizType: "withdraw_complete",
|
||||||
Remark: "提现完成",
|
BizNo: withdrawal.WithdrawNo,
|
||||||
|
Remark: "提现完成",
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,31 +6,33 @@ import (
|
|||||||
|
|
||||||
// 用户端 DTO
|
// 用户端 DTO
|
||||||
type WithdrawalDTO struct {
|
type WithdrawalDTO struct {
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
WithdrawNo string `json:"withdraw_no"`
|
WithdrawNo string `json:"withdraw_no"`
|
||||||
UserID uint64 `json:"user_id"`
|
UserID uint64 `json:"user_id"`
|
||||||
AmountCent int64 `json:"amount_cent"`
|
DistributionSiteID uint64 `json:"distribution_site_id"`
|
||||||
FeeCent int64 `json:"fee_cent"`
|
AmountCent int64 `json:"amount_cent"`
|
||||||
ActualAmountCent int64 `json:"actual_amount_cent"`
|
FeeCent int64 `json:"fee_cent"`
|
||||||
AccountType string `json:"account_type"`
|
ActualAmountCent int64 `json:"actual_amount_cent"`
|
||||||
AccountName string `json:"account_name"`
|
AccountType string `json:"account_type"`
|
||||||
AccountNo string `json:"account_no"` // 脱敏
|
AccountName string `json:"account_name"`
|
||||||
BankName string `json:"bank_name"`
|
AccountNo string `json:"account_no"` // 脱敏
|
||||||
Status string `json:"status"`
|
BankName string `json:"bank_name"`
|
||||||
ReviewRemark string `json:"review_remark"`
|
Status string `json:"status"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
ReviewRemark string `json:"review_remark"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
ReviewedAt *time.Time `json:"reviewed_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
PaidAt *time.Time `json:"paid_at"`
|
ReviewedAt *time.Time `json:"reviewed_at"`
|
||||||
|
PaidAt *time.Time `json:"paid_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// 管理员端详细 DTO
|
// 管理员端详细 DTO
|
||||||
type WithdrawalDetailDTO struct {
|
type WithdrawalDetailDTO struct {
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
WithdrawNo string `json:"withdraw_no"`
|
WithdrawNo string `json:"withdraw_no"`
|
||||||
UserID uint64 `json:"user_id"`
|
UserID uint64 `json:"user_id"`
|
||||||
UserNickname string `json:"user_nickname"`
|
DistributionSiteID uint64 `json:"distribution_site_id"`
|
||||||
UserPhone string `json:"user_phone"`
|
UserNickname string `json:"user_nickname"`
|
||||||
|
UserPhone string `json:"user_phone"`
|
||||||
AmountCent int64 `json:"amount_cent"`
|
AmountCent int64 `json:"amount_cent"`
|
||||||
FeeCent int64 `json:"fee_cent"`
|
FeeCent int64 `json:"fee_cent"`
|
||||||
ActualAmountCent int64 `json:"actual_amount_cent"`
|
ActualAmountCent int64 `json:"actual_amount_cent"`
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
package withdrawal
|
package withdrawal
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"hfb_sys/backend/pkg/response"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"hfb_sys/backend/pkg/response"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
@@ -15,6 +17,20 @@ func NewHandler(service *Service) *Handler {
|
|||||||
return &Handler{service: service}
|
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) Create(c *gin.Context) {
|
func (h *Handler) Create(c *gin.Context) {
|
||||||
@@ -30,7 +46,8 @@ func (h *Handler) Create(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
withdrawal, err := h.service.Create(c.Request.Context(), userID, req)
|
siteCode := parseSiteCode(c)
|
||||||
|
withdrawal, err := h.service.Create(c.Request.Context(), userID, req, siteCode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(c, err)
|
writeError(c, err)
|
||||||
return
|
return
|
||||||
@@ -49,7 +66,8 @@ func (h *Handler) List(c *gin.Context) {
|
|||||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||||
|
|
||||||
result, err := h.service.List(c.Request.Context(), userID, page, pageSize)
|
siteCode := parseSiteCode(c)
|
||||||
|
result, err := h.service.List(c.Request.Context(), userID, page, pageSize, siteCode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(c, err)
|
writeError(c, err)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -10,22 +10,23 @@ import (
|
|||||||
// 转换为用户DTO
|
// 转换为用户DTO
|
||||||
func toDTO(w model.WithdrawalRequest) WithdrawalDTO {
|
func toDTO(w model.WithdrawalRequest) WithdrawalDTO {
|
||||||
return WithdrawalDTO{
|
return WithdrawalDTO{
|
||||||
ID: w.ID,
|
ID: w.ID,
|
||||||
WithdrawNo: w.WithdrawNo,
|
WithdrawNo: w.WithdrawNo,
|
||||||
UserID: w.UserID,
|
UserID: w.UserID,
|
||||||
AmountCent: w.AmountCent,
|
DistributionSiteID: w.DistributionSiteID,
|
||||||
FeeCent: w.FeeCent,
|
AmountCent: w.AmountCent,
|
||||||
ActualAmountCent: w.ActualAmountCent,
|
FeeCent: w.FeeCent,
|
||||||
AccountType: w.AccountType,
|
ActualAmountCent: w.ActualAmountCent,
|
||||||
AccountName: w.AccountName,
|
AccountType: w.AccountType,
|
||||||
AccountNo: w.AccountNo,
|
AccountName: w.AccountName,
|
||||||
BankName: w.BankName,
|
AccountNo: w.AccountNo,
|
||||||
Status: w.Status,
|
BankName: w.BankName,
|
||||||
ReviewRemark: w.ReviewRemark,
|
Status: w.Status,
|
||||||
CreatedAt: w.CreatedAt,
|
ReviewRemark: w.ReviewRemark,
|
||||||
UpdatedAt: w.UpdatedAt,
|
CreatedAt: w.CreatedAt,
|
||||||
ReviewedAt: w.ReviewedAt,
|
UpdatedAt: w.UpdatedAt,
|
||||||
PaidAt: w.PaidAt,
|
ReviewedAt: w.ReviewedAt,
|
||||||
|
PaidAt: w.PaidAt,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,10 +76,11 @@ func (r *Repository) toDetailDTO(ctx context.Context, w model.WithdrawalRequest)
|
|||||||
}
|
}
|
||||||
|
|
||||||
return &WithdrawalDetailDTO{
|
return &WithdrawalDetailDTO{
|
||||||
ID: w.ID,
|
ID: w.ID,
|
||||||
WithdrawNo: w.WithdrawNo,
|
WithdrawNo: w.WithdrawNo,
|
||||||
UserID: w.UserID,
|
UserID: w.UserID,
|
||||||
UserNickname: user.Nickname,
|
DistributionSiteID: w.DistributionSiteID,
|
||||||
|
UserNickname: user.Nickname,
|
||||||
UserPhone: user.Phone,
|
UserPhone: user.Phone,
|
||||||
AmountCent: w.AmountCent,
|
AmountCent: w.AmountCent,
|
||||||
FeeCent: w.FeeCent,
|
FeeCent: w.FeeCent,
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ func NewService(repo *Repository) *Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 用户端方法
|
// 用户端方法
|
||||||
func (s *Service) Create(ctx context.Context, userID uint64, req CreateWithdrawalRequest) (*WithdrawalDTO, error) {
|
func (s *Service) Create(ctx context.Context, userID uint64, req CreateWithdrawalRequest, siteCode ...string) (*WithdrawalDTO, error) {
|
||||||
if s.repo == nil {
|
if s.repo == nil {
|
||||||
return nil, ErrDependencyUnavailable
|
return nil, ErrDependencyUnavailable
|
||||||
}
|
}
|
||||||
@@ -45,10 +45,10 @@ func (s *Service) Create(ctx context.Context, userID uint64, req CreateWithdrawa
|
|||||||
return nil, ErrMaxWithdrawalAmount
|
return nil, ErrMaxWithdrawalAmount
|
||||||
}
|
}
|
||||||
|
|
||||||
return s.repo.Create(ctx, userID, req)
|
return s.repo.Create(ctx, userID, req, siteCode...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) List(ctx context.Context, userID uint64, page, pageSize int) (*PaginatedResult, error) {
|
func (s *Service) List(ctx context.Context, userID uint64, page, pageSize int, siteCode ...string) (*PaginatedResult, error) {
|
||||||
if s.repo == nil {
|
if s.repo == nil {
|
||||||
return nil, ErrDependencyUnavailable
|
return nil, ErrDependencyUnavailable
|
||||||
}
|
}
|
||||||
@@ -58,7 +58,7 @@ func (s *Service) List(ctx context.Context, userID uint64, page, pageSize int) (
|
|||||||
if pageSize < 1 || pageSize > 100 {
|
if pageSize < 1 || pageSize > 100 {
|
||||||
pageSize = 20
|
pageSize = 20
|
||||||
}
|
}
|
||||||
return s.repo.List(ctx, userID, page, pageSize)
|
return s.repo.List(ctx, userID, page, pageSize, siteCode...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) FindByID(ctx context.Context, userID, id uint64) (*WithdrawalDTO, error) {
|
func (s *Service) FindByID(ctx context.Context, userID, id uint64) (*WithdrawalDTO, error) {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package withdrawal
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
"hfb_sys/backend/internal/modules/wallet"
|
"hfb_sys/backend/internal/modules/wallet"
|
||||||
@@ -11,8 +12,23 @@ import (
|
|||||||
"gorm.io/gorm/clause"
|
"gorm.io/gorm/clause"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
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) Create(ctx context.Context, userID uint64, req CreateWithdrawalRequest) (*WithdrawalDTO, error) {
|
func (r *Repository) Create(ctx context.Context, userID uint64, req CreateWithdrawalRequest, siteCode ...string) (*WithdrawalDTO, error) {
|
||||||
db := r.db.WithContext(ctx)
|
db := r.db.WithContext(ctx)
|
||||||
// 验证收款账号
|
// 验证收款账号
|
||||||
var paymentAccount model.UserPaymentAccount
|
var paymentAccount model.UserPaymentAccount
|
||||||
@@ -24,6 +40,15 @@ func (r *Repository) Create(ctx context.Context, userID uint64, req CreateWithdr
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var code string
|
||||||
|
if len(siteCode) > 0 {
|
||||||
|
code = siteCode[0]
|
||||||
|
}
|
||||||
|
siteID, err := r.resolveSiteID(ctx, code)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
// 计算手续费和实际到账金额(分)
|
// 计算手续费和实际到账金额(分)
|
||||||
feeCent := int64(float64(req.AmountCent) * WithdrawalFeeRate)
|
feeCent := int64(float64(req.AmountCent) * WithdrawalFeeRate)
|
||||||
actualAmountCent := req.AmountCent - feeCent
|
actualAmountCent := req.AmountCent - feeCent
|
||||||
@@ -41,18 +66,19 @@ func (r *Repository) Create(ctx context.Context, userID uint64, req CreateWithdr
|
|||||||
}
|
}
|
||||||
|
|
||||||
withdrawal := model.WithdrawalRequest{
|
withdrawal := model.WithdrawalRequest{
|
||||||
WithdrawNo: withdrawNo,
|
WithdrawNo: withdrawNo,
|
||||||
UserID: userID,
|
UserID: userID,
|
||||||
AmountCent: req.AmountCent,
|
DistributionSiteID: siteID,
|
||||||
FeeCent: feeCent,
|
AmountCent: req.AmountCent,
|
||||||
ActualAmountCent: actualAmountCent,
|
FeeCent: feeCent,
|
||||||
PaymentAccountID: &req.PaymentAccountID,
|
ActualAmountCent: actualAmountCent,
|
||||||
AccountType: paymentAccount.AccountType,
|
PaymentAccountID: &req.PaymentAccountID,
|
||||||
AccountName: paymentAccount.AccountName,
|
AccountType: paymentAccount.AccountType,
|
||||||
AccountNo: maskAccountNo(decryptedNo, paymentAccount.AccountType),
|
AccountName: paymentAccount.AccountName,
|
||||||
BankName: paymentAccount.BankName,
|
AccountNo: maskAccountNo(decryptedNo, paymentAccount.AccountType),
|
||||||
BankBranch: paymentAccount.BankBranch,
|
BankName: paymentAccount.BankName,
|
||||||
Status: "pending",
|
BankBranch: paymentAccount.BankBranch,
|
||||||
|
Status: "pending",
|
||||||
}
|
}
|
||||||
|
|
||||||
// 事务处理
|
// 事务处理
|
||||||
@@ -64,21 +90,23 @@ func (r *Repository) Create(ctx context.Context, userID uint64, req CreateWithdr
|
|||||||
|
|
||||||
// 冻结用户余额
|
// 冻结用户余额
|
||||||
if err := wallet.AppendEntries(tx, wallet.Entry{
|
if err := wallet.AppendEntries(tx, wallet.Entry{
|
||||||
UserID: userID,
|
UserID: userID,
|
||||||
Direction: "out",
|
DistributionSiteID: siteID,
|
||||||
AmountCent: req.AmountCent,
|
Direction: "out",
|
||||||
BalanceType: "available",
|
AmountCent: req.AmountCent,
|
||||||
BizType: "withdraw_freeze",
|
BalanceType: "available",
|
||||||
BizNo: withdrawNo,
|
BizType: "withdraw_freeze",
|
||||||
Remark: "提现冻结",
|
BizNo: withdrawNo,
|
||||||
|
Remark: "提现冻结",
|
||||||
}, wallet.Entry{
|
}, wallet.Entry{
|
||||||
UserID: userID,
|
UserID: userID,
|
||||||
Direction: "in",
|
DistributionSiteID: siteID,
|
||||||
AmountCent: req.AmountCent,
|
Direction: "in",
|
||||||
BalanceType: "frozen",
|
AmountCent: req.AmountCent,
|
||||||
BizType: "withdraw_freeze",
|
BalanceType: "frozen",
|
||||||
BizNo: withdrawNo,
|
BizType: "withdraw_freeze",
|
||||||
Remark: "提现冻结",
|
BizNo: withdrawNo,
|
||||||
|
Remark: "提现冻结",
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -94,21 +122,35 @@ func (r *Repository) Create(ctx context.Context, userID uint64, req CreateWithdr
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 用户查询提现列表
|
// 用户查询提现列表
|
||||||
|
func (r *Repository) List(ctx context.Context, userID uint64, page, pageSize int, siteCode ...string) (*PaginatedResult, error) {
|
||||||
// 用户查询提现列表
|
|
||||||
func (r *Repository) List(ctx context.Context, userID uint64, page, pageSize int) (*PaginatedResult, error) {
|
|
||||||
db := r.db.WithContext(ctx)
|
db := r.db.WithContext(ctx)
|
||||||
|
var code string
|
||||||
|
if len(siteCode) > 0 {
|
||||||
|
code = siteCode[0]
|
||||||
|
}
|
||||||
|
siteID, err := r.resolveSiteID(ctx, code)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
countDB := db.Model(&model.WithdrawalRequest{}).Where("user_id = ?", userID)
|
||||||
|
dataDB := db.Where("user_id = ?", userID)
|
||||||
|
if siteID > 0 {
|
||||||
|
countDB = countDB.Where("distribution_site_id = ?", siteID)
|
||||||
|
dataDB = dataDB.Where("distribution_site_id = ?", siteID)
|
||||||
|
} else {
|
||||||
|
countDB = countDB.Where("distribution_site_id = 0 OR distribution_site_id IS NULL")
|
||||||
|
dataDB = dataDB.Where("distribution_site_id = 0 OR distribution_site_id IS NULL")
|
||||||
|
}
|
||||||
|
|
||||||
var total int64
|
var total int64
|
||||||
if err := db.Model(&model.WithdrawalRequest{}).
|
if err := countDB.Count(&total).Error; err != nil {
|
||||||
Where("user_id = ?", userID).
|
|
||||||
Count(&total).Error; err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
offset := (page - 1) * pageSize
|
offset := (page - 1) * pageSize
|
||||||
var withdrawals []model.WithdrawalRequest
|
var withdrawals []model.WithdrawalRequest
|
||||||
if err := db.Where("user_id = ?", userID).
|
if err := dataDB.Order("created_at DESC").
|
||||||
Order("created_at DESC").
|
|
||||||
Offset(offset).Limit(pageSize).
|
Offset(offset).Limit(pageSize).
|
||||||
Find(&withdrawals).Error; err != nil {
|
Find(&withdrawals).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -170,21 +212,23 @@ func (r *Repository) Cancel(ctx context.Context, userID, id uint64) error {
|
|||||||
|
|
||||||
// 解冻余额
|
// 解冻余额
|
||||||
if err := wallet.AppendEntries(tx, wallet.Entry{
|
if err := wallet.AppendEntries(tx, wallet.Entry{
|
||||||
UserID: userID,
|
UserID: userID,
|
||||||
Direction: "out",
|
DistributionSiteID: withdrawal.DistributionSiteID,
|
||||||
AmountCent: withdrawal.AmountCent,
|
Direction: "out",
|
||||||
BalanceType: "frozen",
|
AmountCent: withdrawal.AmountCent,
|
||||||
BizType: "withdraw_cancel",
|
BalanceType: "frozen",
|
||||||
BizNo: withdrawal.WithdrawNo,
|
BizType: "withdraw_cancel",
|
||||||
Remark: "用户取消提现",
|
BizNo: withdrawal.WithdrawNo,
|
||||||
|
Remark: "用户取消提现",
|
||||||
}, wallet.Entry{
|
}, wallet.Entry{
|
||||||
UserID: userID,
|
UserID: userID,
|
||||||
Direction: "in",
|
DistributionSiteID: withdrawal.DistributionSiteID,
|
||||||
AmountCent: withdrawal.AmountCent,
|
Direction: "in",
|
||||||
BalanceType: "available",
|
AmountCent: withdrawal.AmountCent,
|
||||||
BizType: "withdraw_cancel",
|
BalanceType: "available",
|
||||||
BizNo: withdrawal.WithdrawNo,
|
BizType: "withdraw_cancel",
|
||||||
Remark: "用户取消提现",
|
BizNo: withdrawal.WithdrawNo,
|
||||||
|
Remark: "用户取消提现",
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
-- +goose Up
|
||||||
|
|
||||||
|
-- 1. chat_conversations 表新增 distribution_site_id
|
||||||
|
ALTER TABLE chat_conversations
|
||||||
|
ADD COLUMN distribution_site_id BIGINT UNSIGNED NULL AFTER listing_id,
|
||||||
|
ADD KEY idx_chat_conversations_distribution_site (distribution_site_id, status);
|
||||||
|
|
||||||
|
-- 2. wallet_accounts 表新增 distribution_site_id 并将唯一键变更为 (user_id, distribution_site_id)
|
||||||
|
ALTER TABLE wallet_accounts
|
||||||
|
ADD COLUMN distribution_site_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER user_id,
|
||||||
|
DROP KEY uk_wallet_accounts_user_id,
|
||||||
|
ADD UNIQUE KEY uk_wallet_accounts_user_site (user_id, distribution_site_id);
|
||||||
|
|
||||||
|
-- 3. wallet_ledger 表新增 distribution_site_id 列与联合索引
|
||||||
|
ALTER TABLE wallet_ledger
|
||||||
|
ADD COLUMN distribution_site_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER user_id,
|
||||||
|
ADD KEY idx_wallet_ledger_user_site (user_id, distribution_site_id);
|
||||||
|
|
||||||
|
-- 4. withdrawal_requests 表新增 distribution_site_id 列与联合索引
|
||||||
|
ALTER TABLE withdrawal_requests
|
||||||
|
ADD COLUMN distribution_site_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER user_id,
|
||||||
|
ADD KEY idx_withdrawal_user_site (user_id, distribution_site_id);
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
|
||||||
|
ALTER TABLE withdrawal_requests
|
||||||
|
DROP KEY idx_withdrawal_user_site,
|
||||||
|
DROP COLUMN distribution_site_id;
|
||||||
|
|
||||||
|
ALTER TABLE wallet_ledger
|
||||||
|
DROP KEY idx_wallet_ledger_user_site,
|
||||||
|
DROP COLUMN distribution_site_id;
|
||||||
|
|
||||||
|
ALTER TABLE wallet_accounts
|
||||||
|
DROP KEY uk_wallet_accounts_user_site,
|
||||||
|
ADD UNIQUE KEY uk_wallet_accounts_user_id (user_id),
|
||||||
|
DROP COLUMN distribution_site_id;
|
||||||
|
|
||||||
|
ALTER TABLE chat_conversations
|
||||||
|
DROP KEY idx_chat_conversations_distribution_site,
|
||||||
|
DROP COLUMN distribution_site_id;
|
||||||
@@ -40,6 +40,7 @@ export interface ChatConversation {
|
|||||||
last_sender_role?: string
|
last_sender_role?: string
|
||||||
unread_count: number
|
unread_count: number
|
||||||
needs_reply: boolean
|
needs_reply: boolean
|
||||||
|
distribution_site_id?: number | null
|
||||||
created_at: string
|
created_at: string
|
||||||
updated_at: string
|
updated_at: string
|
||||||
}
|
}
|
||||||
@@ -92,17 +93,34 @@ export interface ChatMessage {
|
|||||||
created_at: string
|
created_at: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchChats(page = 1, pageSize = 20) {
|
export async function fetchChats(page = 1, pageSize = 20, distributionSiteCode?: string) {
|
||||||
|
const siteCode =
|
||||||
|
distributionSiteCode ||
|
||||||
|
(typeof window !== 'undefined' ? localStorage.getItem('hfb_site_code') : '') ||
|
||||||
|
undefined
|
||||||
|
const params: Record<string, unknown> = { page, page_size: pageSize }
|
||||||
|
if (siteCode) {
|
||||||
|
params.distribution_site_code = siteCode
|
||||||
|
}
|
||||||
const { data } = await apiClient.get<ApiResponse<PaginatedResult<ChatConversation>>>('/chats', {
|
const { data } = await apiClient.get<ApiResponse<PaginatedResult<ChatConversation>>>('/chats', {
|
||||||
params: { page, page_size: pageSize },
|
params,
|
||||||
})
|
})
|
||||||
return data.data
|
return data.data
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchUnreadChatCount() {
|
export async function fetchUnreadChatCount(distributionSiteCode?: string) {
|
||||||
|
const siteCode =
|
||||||
|
distributionSiteCode ||
|
||||||
|
(typeof window !== 'undefined' ? localStorage.getItem('hfb_site_code') : '') ||
|
||||||
|
undefined
|
||||||
|
const params: Record<string, unknown> = {}
|
||||||
|
if (siteCode) {
|
||||||
|
params.distribution_site_code = siteCode
|
||||||
|
}
|
||||||
const { data } = await apiClient.get<ApiResponse<{ unread_count: number }>>(
|
const { data } = await apiClient.get<ApiResponse<{ unread_count: number }>>(
|
||||||
'/chats/unread-count',
|
'/chats/unread-count',
|
||||||
{
|
{
|
||||||
|
params,
|
||||||
silent: true,
|
silent: true,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
@@ -119,10 +137,21 @@ export async function fetchOrderChat(orderId: number) {
|
|||||||
return data.data
|
return data.data
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function ensureSupportChat(scene: SupportScene | string = 'general') {
|
export async function ensureSupportChat(
|
||||||
const { data } = await apiClient.post<ApiResponse<ChatConversation>>('/chats/support', {
|
scene: SupportScene | string = 'general',
|
||||||
|
distributionSiteCode?: string
|
||||||
|
) {
|
||||||
|
const siteCode =
|
||||||
|
distributionSiteCode ||
|
||||||
|
(typeof window !== 'undefined' ? localStorage.getItem('hfb_site_code') : '') ||
|
||||||
|
undefined
|
||||||
|
const payload: { scene: string; distribution_site_code?: string } = {
|
||||||
scene: scene || 'general',
|
scene: scene || 'general',
|
||||||
})
|
}
|
||||||
|
if (siteCode) {
|
||||||
|
payload.distribution_site_code = siteCode
|
||||||
|
}
|
||||||
|
const { data } = await apiClient.post<ApiResponse<ChatConversation>>('/chats/support', payload)
|
||||||
return data.data
|
return data.data
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,9 +18,11 @@ import {
|
|||||||
useNotificationUnreadCount,
|
useNotificationUnreadCount,
|
||||||
} from '@/features/auth/composables/useNotificationUnreadCount'
|
} from '@/features/auth/composables/useNotificationUnreadCount'
|
||||||
import { formatDateMinute, formatDateTime } from '@/shared/utils/time'
|
import { formatDateMinute, formatDateTime } from '@/shared/utils/time'
|
||||||
|
import { useDistributionSiteStore } from '@/stores/distributionSite'
|
||||||
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
|
const distributionStore = useDistributionSiteStore()
|
||||||
const currentUserId = Number(localStorage.getItem('user_id') || 0)
|
const currentUserId = Number(localStorage.getItem('user_id') || 0)
|
||||||
|
|
||||||
// ── 聊天状态 ──
|
// ── 聊天状态 ──
|
||||||
@@ -65,7 +67,11 @@ async function loadChats(isRefresh = false, showLoading = true) {
|
|||||||
if (loading.value) return
|
if (loading.value) return
|
||||||
if (showLoading) loading.value = true
|
if (showLoading) loading.value = true
|
||||||
try {
|
try {
|
||||||
const res = await fetchChats(page.value, pageSize)
|
const res = await fetchChats(
|
||||||
|
page.value,
|
||||||
|
pageSize,
|
||||||
|
distributionStore.isDistribution ? distributionStore.siteCode : undefined
|
||||||
|
)
|
||||||
conversations.value = isRefresh ? res.items : [...conversations.value, ...res.items]
|
conversations.value = isRefresh ? res.items : [...conversations.value, ...res.items]
|
||||||
total.value = res.total
|
total.value = res.total
|
||||||
if (conversations.value.length < res.total && res.items.length > 0) {
|
if (conversations.value.length < res.total && res.items.length > 0) {
|
||||||
@@ -180,13 +186,30 @@ function handleTabChange(tab: string) {
|
|||||||
<section class="page messages-page">
|
<section class="page messages-page">
|
||||||
<div class="page-header-row">
|
<div class="page-header-row">
|
||||||
<div class="page-header">
|
<div class="page-header">
|
||||||
<p class="eyebrow">Messages</p>
|
<p class="eyebrow">
|
||||||
<h1>消息</h1>
|
Messages
|
||||||
|
<el-tag
|
||||||
|
v-if="distributionStore.isDistribution"
|
||||||
|
type="warning"
|
||||||
|
effect="light"
|
||||||
|
size="small"
|
||||||
|
class="distribution-site-tag"
|
||||||
|
>
|
||||||
|
{{ distributionStore.siteName }}专属分站
|
||||||
|
</el-tag>
|
||||||
|
</p>
|
||||||
|
<h1>
|
||||||
|
{{
|
||||||
|
distributionStore.isDistribution ? `${distributionStore.siteName} · 消息中心` : '消息'
|
||||||
|
}}
|
||||||
|
</h1>
|
||||||
<p>
|
<p>
|
||||||
{{
|
{{
|
||||||
combinedUnread > 0
|
distributionStore.isDistribution
|
||||||
? `${combinedUnread} 条未读`
|
? `当前查看的是【${distributionStore.siteName}】分站专属客服会话与订单群聊。`
|
||||||
: '查看订单群聊、平台客服消息和系统通知。'
|
: combinedUnread > 0
|
||||||
|
? `${combinedUnread} 条未读`
|
||||||
|
: '查看订单群聊、平台客服消息和系统通知。'
|
||||||
}}
|
}}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -352,6 +375,12 @@ function handleTabChange(tab: string) {
|
|||||||
align-items: flex-end;
|
align-items: flex-end;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.distribution-site-tag {
|
||||||
|
margin-left: 8px;
|
||||||
|
vertical-align: middle;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
.header-actions {
|
.header-actions {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 10px;
|
gap: 10px;
|
||||||
|
|||||||
@@ -5,8 +5,10 @@ import { showToast } from 'vant'
|
|||||||
import MobileBottomNav from '@/components/MobileBottomNav.vue'
|
import MobileBottomNav from '@/components/MobileBottomNav.vue'
|
||||||
import { fetchChats, type ChatConversation } from '@/features/chats/api/chats'
|
import { fetchChats, type ChatConversation } from '@/features/chats/api/chats'
|
||||||
import { formatDateMinute } from '@/shared/utils/time'
|
import { formatDateMinute } from '@/shared/utils/time'
|
||||||
|
import { useDistributionSiteStore } from '@/stores/distributionSite'
|
||||||
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const distributionStore = useDistributionSiteStore()
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const refreshing = ref(false)
|
const refreshing = ref(false)
|
||||||
const finished = ref(false)
|
const finished = ref(false)
|
||||||
@@ -26,7 +28,11 @@ async function loadChats(isRefresh = false) {
|
|||||||
}
|
}
|
||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
const res = await fetchChats(page.value, pageSize)
|
const res = await fetchChats(
|
||||||
|
page.value,
|
||||||
|
pageSize,
|
||||||
|
distributionStore.isDistribution ? distributionStore.siteCode : undefined
|
||||||
|
)
|
||||||
conversations.value = isRefresh ? res.items : [...conversations.value, ...res.items]
|
conversations.value = isRefresh ? res.items : [...conversations.value, ...res.items]
|
||||||
total.value = res.total
|
total.value = res.total
|
||||||
if (conversations.value.length >= res.total || res.items.length === 0) {
|
if (conversations.value.length >= res.total || res.items.length === 0) {
|
||||||
@@ -85,7 +91,9 @@ const unreadTotal = computed(() =>
|
|||||||
<button class="back-btn" type="button" @click="router.back()">
|
<button class="back-btn" type="button" @click="router.back()">
|
||||||
<van-icon name="arrow-left" :size="20" />
|
<van-icon name="arrow-left" :size="20" />
|
||||||
</button>
|
</button>
|
||||||
<h1>消息</h1>
|
<h1>
|
||||||
|
{{ distributionStore.isDistribution ? `${distributionStore.siteName} · 消息` : '消息' }}
|
||||||
|
</h1>
|
||||||
<span class="header-count">{{ unreadTotal > 0 ? `${unreadTotal} 未读` : '' }}</span>
|
<span class="header-count">{{ unreadTotal > 0 ? `${unreadTotal} 未读` : '' }}</span>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ export interface WalletAccount {
|
|||||||
available_balance_cent: number
|
available_balance_cent: number
|
||||||
frozen_balance_cent: number
|
frozen_balance_cent: number
|
||||||
status: WalletStatus
|
status: WalletStatus
|
||||||
|
distribution_site_id?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WalletLedger {
|
export interface WalletLedger {
|
||||||
@@ -22,19 +23,36 @@ export interface WalletLedger {
|
|||||||
biz_type: string
|
biz_type: string
|
||||||
biz_no: string
|
biz_no: string
|
||||||
remark: string
|
remark: string
|
||||||
|
distribution_site_id?: number
|
||||||
created_at: string
|
created_at: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchWalletBalance() {
|
export async function fetchWalletBalance(distributionSiteCode?: string) {
|
||||||
const { data } = await apiClient.get<ApiResponse<WalletAccount>>('/wallet/balance')
|
const siteCode =
|
||||||
|
distributionSiteCode ||
|
||||||
|
(typeof window !== 'undefined' ? localStorage.getItem('hfb_site_code') : '') ||
|
||||||
|
undefined
|
||||||
|
const params: Record<string, unknown> = {}
|
||||||
|
if (siteCode) {
|
||||||
|
params.distribution_site_code = siteCode
|
||||||
|
}
|
||||||
|
const { data } = await apiClient.get<ApiResponse<WalletAccount>>('/wallet/balance', { params })
|
||||||
return data.data
|
return data.data
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchWalletLedger(page = 1, pageSize = 20) {
|
export async function fetchWalletLedger(page = 1, pageSize = 20, distributionSiteCode?: string) {
|
||||||
|
const siteCode =
|
||||||
|
distributionSiteCode ||
|
||||||
|
(typeof window !== 'undefined' ? localStorage.getItem('hfb_site_code') : '') ||
|
||||||
|
undefined
|
||||||
|
const params: Record<string, unknown> = { page, page_size: pageSize }
|
||||||
|
if (siteCode) {
|
||||||
|
params.distribution_site_code = siteCode
|
||||||
|
}
|
||||||
const { data } = await apiClient.get<ApiResponse<PaginatedResult<WalletLedger>>>(
|
const { data } = await apiClient.get<ApiResponse<PaginatedResult<WalletLedger>>>(
|
||||||
'/wallet/ledger',
|
'/wallet/ledger',
|
||||||
{
|
{
|
||||||
params: { page, page_size: pageSize },
|
params,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
return data.data
|
return data.data
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ export interface WithdrawalRequest {
|
|||||||
bank_name: string
|
bank_name: string
|
||||||
status: WithdrawalStatus
|
status: WithdrawalStatus
|
||||||
review_remark: string
|
review_remark: string
|
||||||
|
distribution_site_id?: number
|
||||||
created_at: string
|
created_at: string
|
||||||
updated_at: string
|
updated_at: string
|
||||||
reviewed_at: string | null
|
reviewed_at: string | null
|
||||||
@@ -65,6 +66,7 @@ export interface WithdrawalRequest {
|
|||||||
export interface CreateWithdrawalRequest {
|
export interface CreateWithdrawalRequest {
|
||||||
payment_account_id: number
|
payment_account_id: number
|
||||||
amount_cent: number
|
amount_cent: number
|
||||||
|
distribution_site_code?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== 收款账号管理 API ==========
|
// ========== 收款账号管理 API ==========
|
||||||
@@ -110,16 +112,36 @@ export async function setDefaultPaymentAccount(id: number) {
|
|||||||
|
|
||||||
// ========== 提现申请 API ==========
|
// ========== 提现申请 API ==========
|
||||||
|
|
||||||
export async function createWithdrawal(req: CreateWithdrawalRequest) {
|
export async function createWithdrawal(
|
||||||
const { data } = await apiClient.post<ApiResponse<WithdrawalRequest>>('/withdrawals', req)
|
req: CreateWithdrawalRequest,
|
||||||
|
distributionSiteCode?: string
|
||||||
|
) {
|
||||||
|
const siteCode =
|
||||||
|
distributionSiteCode ||
|
||||||
|
req.distribution_site_code ||
|
||||||
|
(typeof window !== 'undefined' ? localStorage.getItem('hfb_site_code') : '') ||
|
||||||
|
undefined
|
||||||
|
const payload: CreateWithdrawalRequest = { ...req }
|
||||||
|
if (siteCode) {
|
||||||
|
payload.distribution_site_code = siteCode
|
||||||
|
}
|
||||||
|
const { data } = await apiClient.post<ApiResponse<WithdrawalRequest>>('/withdrawals', payload)
|
||||||
return data.data
|
return data.data
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchWithdrawals(page = 1, pageSize = 20) {
|
export async function fetchWithdrawals(page = 1, pageSize = 20, distributionSiteCode?: string) {
|
||||||
|
const siteCode =
|
||||||
|
distributionSiteCode ||
|
||||||
|
(typeof window !== 'undefined' ? localStorage.getItem('hfb_site_code') : '') ||
|
||||||
|
undefined
|
||||||
|
const params: Record<string, unknown> = { page, page_size: pageSize }
|
||||||
|
if (siteCode) {
|
||||||
|
params.distribution_site_code = siteCode
|
||||||
|
}
|
||||||
const { data } = await apiClient.get<ApiResponse<PaginatedResult<WithdrawalRequest>>>(
|
const { data } = await apiClient.get<ApiResponse<PaginatedResult<WithdrawalRequest>>>(
|
||||||
'/withdrawals',
|
'/withdrawals',
|
||||||
{
|
{
|
||||||
params: { page, page_size: pageSize },
|
params,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
return data.data
|
return data.data
|
||||||
|
|||||||
@@ -52,6 +52,19 @@
|
|||||||
box-shadow: 0 14px 28px rgba(255, 106, 0, 0.22);
|
box-shadow: 0 14px 28px rgba(255, 106, 0, 0.22);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.site-account-tip {
|
||||||
|
display: inline-block;
|
||||||
|
align-self: start;
|
||||||
|
width: fit-content;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: rgba(255, 255, 255, 0.25);
|
||||||
|
color: #fff;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 500;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
}
|
||||||
|
|
||||||
.balance-panel span,
|
.balance-panel span,
|
||||||
.balance-panel small {
|
.balance-panel small {
|
||||||
color: rgba(255, 255, 255, 0.72);
|
color: rgba(255, 255, 255, 0.72);
|
||||||
|
|||||||
@@ -23,8 +23,10 @@ import { formatCent, formatMoney, yuanToCent } from '@/shared/utils/money'
|
|||||||
import { formatDateMinute } from '@/shared/utils/time'
|
import { formatDateMinute } from '@/shared/utils/time'
|
||||||
import alipayReceiveQrExample from '@/assets/alipay-receive-qr-example.png'
|
import alipayReceiveQrExample from '@/assets/alipay-receive-qr-example.png'
|
||||||
import wechatReceiveQrExample from '@/assets/wechat-receive-qr-example.png'
|
import wechatReceiveQrExample from '@/assets/wechat-receive-qr-example.png'
|
||||||
|
import { useDistributionSiteStore } from '@/stores/distributionSite'
|
||||||
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const distributionStore = useDistributionSiteStore()
|
||||||
|
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const submitting = ref(false)
|
const submitting = ref(false)
|
||||||
@@ -104,10 +106,11 @@ onMounted(loadData)
|
|||||||
async function loadData() {
|
async function loadData() {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
|
const siteCode = distributionStore.isDistribution ? distributionStore.siteCode : undefined
|
||||||
const [balanceData, accountsData, withdrawalsData] = await Promise.all([
|
const [balanceData, accountsData, withdrawalsData] = await Promise.all([
|
||||||
fetchWalletBalance(),
|
fetchWalletBalance(siteCode),
|
||||||
fetchPaymentAccounts(1, 100),
|
fetchPaymentAccounts(1, 100),
|
||||||
fetchWithdrawals(1, 20),
|
fetchWithdrawals(1, 20, siteCode),
|
||||||
])
|
])
|
||||||
account.value = balanceData
|
account.value = balanceData
|
||||||
paymentAccounts.value = accountsData.items
|
paymentAccounts.value = accountsData.items
|
||||||
@@ -142,10 +145,13 @@ async function handleSubmit() {
|
|||||||
|
|
||||||
submitting.value = true
|
submitting.value = true
|
||||||
try {
|
try {
|
||||||
await createWithdrawal({
|
await createWithdrawal(
|
||||||
payment_account_id: withdrawForm.payment_account_id,
|
{
|
||||||
amount_cent: amountCent.value,
|
payment_account_id: withdrawForm.payment_account_id,
|
||||||
})
|
amount_cent: amountCent.value,
|
||||||
|
},
|
||||||
|
distributionStore.isDistribution ? distributionStore.siteCode : undefined
|
||||||
|
)
|
||||||
showToast({ message: '提现申请已提交', icon: 'passed' })
|
showToast({ message: '提现申请已提交', icon: 'passed' })
|
||||||
withdrawForm.amount = ''
|
withdrawForm.amount = ''
|
||||||
await loadData()
|
await loadData()
|
||||||
@@ -386,13 +392,18 @@ function statusType(status: string): 'primary' | 'success' | 'danger' | 'warning
|
|||||||
<button class="back-btn" type="button" @click="router.back()">
|
<button class="back-btn" type="button" @click="router.back()">
|
||||||
<van-icon name="arrow-left" :size="20" />
|
<van-icon name="arrow-left" :size="20" />
|
||||||
</button>
|
</button>
|
||||||
<h1>提现</h1>
|
<h1>
|
||||||
|
{{ distributionStore.isDistribution ? `${distributionStore.siteName} · 提现` : '提现' }}
|
||||||
|
</h1>
|
||||||
<button class="refresh-btn" type="button" @click="loadData">
|
<button class="refresh-btn" type="button" @click="loadData">
|
||||||
<van-icon name="replay" :size="18" />
|
<van-icon name="replay" :size="18" />
|
||||||
</button>
|
</button>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<section class="balance-panel">
|
<section class="balance-panel">
|
||||||
|
<div v-if="distributionStore.isDistribution" class="site-account-tip">
|
||||||
|
{{ distributionStore.siteName }}独立账户
|
||||||
|
</div>
|
||||||
<span>可用余额</span>
|
<span>可用余额</span>
|
||||||
<strong>¥{{ formatCent(availableBalanceCent) }}</strong>
|
<strong>¥{{ formatCent(availableBalanceCent) }}</strong>
|
||||||
<small>冻结余额 ¥{{ formatCent(account?.frozen_balance_cent) }}</small>
|
<small>冻结余额 ¥{{ formatCent(account?.frozen_balance_cent) }}</small>
|
||||||
|
|||||||
@@ -23,8 +23,10 @@ import {
|
|||||||
} from '@/shared/utils/statusLabels'
|
} from '@/shared/utils/statusLabels'
|
||||||
import { formatDateTime } from '@/shared/utils/time'
|
import { formatDateTime } from '@/shared/utils/time'
|
||||||
import { formatCentWithSymbol } from '@/shared/utils/money'
|
import { formatCentWithSymbol } from '@/shared/utils/money'
|
||||||
|
import { useDistributionSiteStore } from '@/stores/distributionSite'
|
||||||
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const distributionStore = useDistributionSiteStore()
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const account = ref<WalletAccount | null>(null)
|
const account = ref<WalletAccount | null>(null)
|
||||||
const ledger = ref<WalletLedger[]>([])
|
const ledger = ref<WalletLedger[]>([])
|
||||||
@@ -66,9 +68,10 @@ onMounted(loadWallet)
|
|||||||
async function loadWallet() {
|
async function loadWallet() {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
|
const siteCode = distributionStore.isDistribution ? distributionStore.siteCode : undefined
|
||||||
const [balance, result] = await Promise.all([
|
const [balance, result] = await Promise.all([
|
||||||
fetchWalletBalance(),
|
fetchWalletBalance(siteCode),
|
||||||
fetchWalletLedger(currentPage.value, currentPageSize.value),
|
fetchWalletLedger(currentPage.value, currentPageSize.value, siteCode),
|
||||||
])
|
])
|
||||||
account.value = balance
|
account.value = balance
|
||||||
ledger.value = result.items
|
ledger.value = result.items
|
||||||
@@ -138,9 +141,32 @@ function amountPrefix(direction: string) {
|
|||||||
<section class="page wallet-page" v-loading="loading">
|
<section class="page wallet-page" v-loading="loading">
|
||||||
<div class="wallet-hero">
|
<div class="wallet-hero">
|
||||||
<div class="page-header">
|
<div class="page-header">
|
||||||
<p class="eyebrow">我的钱包</p>
|
<p class="eyebrow">
|
||||||
<h1>资金账户</h1>
|
我的钱包
|
||||||
<p>查看卖家结算收入、可提现余额和每一笔资金变化。</p>
|
<el-tag
|
||||||
|
v-if="distributionStore.isDistribution"
|
||||||
|
type="warning"
|
||||||
|
effect="light"
|
||||||
|
size="small"
|
||||||
|
class="distribution-site-tag"
|
||||||
|
>
|
||||||
|
{{ distributionStore.siteName }}专属分站
|
||||||
|
</el-tag>
|
||||||
|
</p>
|
||||||
|
<h1>
|
||||||
|
{{
|
||||||
|
distributionStore.isDistribution
|
||||||
|
? `${distributionStore.siteName} · 资金账户`
|
||||||
|
: '资金账户'
|
||||||
|
}}
|
||||||
|
</h1>
|
||||||
|
<p>
|
||||||
|
{{
|
||||||
|
distributionStore.isDistribution
|
||||||
|
? `当前查看的是【${distributionStore.siteName}】专属分站钱包与流水明细,资金及流水与主站完全独立。`
|
||||||
|
: '查看卖家结算收入、可提现余额和每一笔资金变化。'
|
||||||
|
}}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="wallet-hero-action">
|
<div class="wallet-hero-action">
|
||||||
<span>当前可用</span>
|
<span>当前可用</span>
|
||||||
@@ -258,6 +284,12 @@ function amountPrefix(direction: string) {
|
|||||||
max-width: 780px;
|
max-width: 780px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.distribution-site-tag {
|
||||||
|
margin-left: 8px;
|
||||||
|
vertical-align: middle;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
.wallet-hero-action {
|
.wallet-hero-action {
|
||||||
min-width: 220px;
|
min-width: 220px;
|
||||||
padding: 16px 18px;
|
padding: 16px 18px;
|
||||||
|
|||||||
@@ -14,8 +14,10 @@ import {
|
|||||||
} from '../api/withdrawal'
|
} from '../api/withdrawal'
|
||||||
import { fetchWalletBalance, type WalletAccount } from '../api/wallet'
|
import { fetchWalletBalance, type WalletAccount } from '../api/wallet'
|
||||||
import { formatMoney, formatMoneyWithSymbol, formatCent, yuanToCent } from '@/shared/utils/money'
|
import { formatMoney, formatMoneyWithSymbol, formatCent, yuanToCent } from '@/shared/utils/money'
|
||||||
|
import { useDistributionSiteStore } from '@/stores/distributionSite'
|
||||||
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const distributionStore = useDistributionSiteStore()
|
||||||
|
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const submitting = ref(false)
|
const submitting = ref(false)
|
||||||
@@ -42,10 +44,11 @@ onMounted(() => {
|
|||||||
async function loadData() {
|
async function loadData() {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
|
const siteCode = distributionStore.isDistribution ? distributionStore.siteCode : undefined
|
||||||
const [balanceData, accountsData, withdrawalsData] = await Promise.all([
|
const [balanceData, accountsData, withdrawalsData] = await Promise.all([
|
||||||
fetchWalletBalance(),
|
fetchWalletBalance(siteCode),
|
||||||
fetchPaymentAccounts(1, 100),
|
fetchPaymentAccounts(1, 100),
|
||||||
fetchWithdrawals(currentPage.value, pageSize.value),
|
fetchWithdrawals(currentPage.value, pageSize.value, siteCode),
|
||||||
])
|
])
|
||||||
account.value = balanceData
|
account.value = balanceData
|
||||||
paymentAccounts.value = accountsData.items
|
paymentAccounts.value = accountsData.items
|
||||||
@@ -95,10 +98,13 @@ async function handleSubmit() {
|
|||||||
)
|
)
|
||||||
|
|
||||||
submitting.value = true
|
submitting.value = true
|
||||||
await createWithdrawal({
|
await createWithdrawal(
|
||||||
payment_account_id: withdrawForm.value.payment_account_id,
|
{
|
||||||
amount_cent: yuanToCent(withdrawForm.value.amount),
|
payment_account_id: withdrawForm.value.payment_account_id,
|
||||||
})
|
amount_cent: yuanToCent(withdrawForm.value.amount),
|
||||||
|
},
|
||||||
|
distributionStore.isDistribution ? distributionStore.siteCode : undefined
|
||||||
|
)
|
||||||
ElMessage.success('提现申请已提交')
|
ElMessage.success('提现申请已提交')
|
||||||
withdrawForm.value.amount = 0
|
withdrawForm.value.amount = 0
|
||||||
await loadData()
|
await loadData()
|
||||||
@@ -167,8 +173,25 @@ function accountTypeLabel(type: string) {
|
|||||||
<template>
|
<template>
|
||||||
<div class="withdrawal-page">
|
<div class="withdrawal-page">
|
||||||
<div class="page-header">
|
<div class="page-header">
|
||||||
<h2>提现</h2>
|
<h2>
|
||||||
<p class="page-desc">将钱包余额提现到您的收款账号</p>
|
提现
|
||||||
|
<el-tag
|
||||||
|
v-if="distributionStore.isDistribution"
|
||||||
|
type="warning"
|
||||||
|
effect="light"
|
||||||
|
size="small"
|
||||||
|
class="distribution-site-tag"
|
||||||
|
>
|
||||||
|
{{ distributionStore.siteName }}专属分站
|
||||||
|
</el-tag>
|
||||||
|
</h2>
|
||||||
|
<p class="page-desc">
|
||||||
|
{{
|
||||||
|
distributionStore.isDistribution
|
||||||
|
? `将【${distributionStore.siteName}】专属分站钱包余额提现到您的收款账号`
|
||||||
|
: '将钱包余额提现到您的收款账号'
|
||||||
|
}}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 余额卡片 -->
|
<!-- 余额卡片 -->
|
||||||
@@ -376,6 +399,12 @@ function accountTypeLabel(type: string) {
|
|||||||
margin-bottom: 24px;
|
margin-bottom: 24px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.distribution-site-tag {
|
||||||
|
margin-left: 8px;
|
||||||
|
vertical-align: middle;
|
||||||
|
font-weight: normal;
|
||||||
|
}
|
||||||
|
|
||||||
.page-header h2 {
|
.page-header h2 {
|
||||||
margin: 0 0 8px;
|
margin: 0 0 8px;
|
||||||
font-size: 24px;
|
font-size: 24px;
|
||||||
|
|||||||
@@ -201,6 +201,13 @@ apiClient.interceptors.request.use(
|
|||||||
config.headers.Authorization = `Bearer ${token}`
|
config.headers.Authorization = `Bearer ${token}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
const siteCode = localStorage.getItem('hfb_site_code')
|
||||||
|
if (siteCode && !config.headers['X-Distribution-Site-Code']) {
|
||||||
|
config.headers['X-Distribution-Site-Code'] = siteCode
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 记录请求日志
|
// 记录请求日志
|
||||||
logRequest(config)
|
logRequest(config)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user