feat: 代理商资金可见性重构(agent-fund-visibility)
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m10s
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m10s
- 将 GET /shops/commission-summary 重命名为 GET /shops/fund-summary, 响应新增 main_balance、main_frozen_balance 两个预充值钱包字段 - 新增 GET /shops/:id/main-wallet/transactions 预充值钱包流水接口 - 将佣金统计、每日统计、发起提现从 /my/ 路径迁移至 /shops/:id/ 路径: GET /shops/:id/commission-stats GET /shops/:id/commission-daily-stats POST /shops/:id/withdrawal-requests - 删除 MyCommissionService、MyCommissionHandler 及全部 /my/ 路由 - 补齐 ListShopWithdrawalRequests、ListShopCommissionRecords 的 CanManageShop 越权校验(安全修复) - 提现接口增加严格权限:仅代理账号本人可为自己店铺发起提现 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -3,6 +3,8 @@ package shop_commission
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
@@ -11,41 +13,52 @@ import (
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Service 代理商资金管理服务
|
||||
type Service struct {
|
||||
shopStore *postgres.ShopStore
|
||||
accountStore *postgres.AccountStore
|
||||
agentWalletStore *postgres.AgentWalletStore
|
||||
commissionWithdrawalReqStore *postgres.CommissionWithdrawalRequestStore
|
||||
commissionRecordStore *postgres.CommissionRecordStore
|
||||
db *gorm.DB
|
||||
logger *zap.Logger
|
||||
shopStore *postgres.ShopStore
|
||||
accountStore *postgres.AccountStore
|
||||
agentWalletStore *postgres.AgentWalletStore
|
||||
commissionWithdrawalReqStore *postgres.CommissionWithdrawalRequestStore
|
||||
commissionWithdrawalSettingStore *postgres.CommissionWithdrawalSettingStore
|
||||
commissionRecordStore *postgres.CommissionRecordStore
|
||||
agentWalletTransactionStore *postgres.AgentWalletTransactionStore
|
||||
db *gorm.DB
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// New 创建代理商资金管理服务
|
||||
func New(
|
||||
shopStore *postgres.ShopStore,
|
||||
accountStore *postgres.AccountStore,
|
||||
agentWalletStore *postgres.AgentWalletStore,
|
||||
commissionWithdrawalReqStore *postgres.CommissionWithdrawalRequestStore,
|
||||
commissionWithdrawalSettingStore *postgres.CommissionWithdrawalSettingStore,
|
||||
commissionRecordStore *postgres.CommissionRecordStore,
|
||||
agentWalletTransactionStore *postgres.AgentWalletTransactionStore,
|
||||
db *gorm.DB,
|
||||
logger *zap.Logger,
|
||||
) *Service {
|
||||
return &Service{
|
||||
shopStore: shopStore,
|
||||
accountStore: accountStore,
|
||||
agentWalletStore: agentWalletStore,
|
||||
commissionWithdrawalReqStore: commissionWithdrawalReqStore,
|
||||
commissionRecordStore: commissionRecordStore,
|
||||
db: db,
|
||||
logger: logger,
|
||||
shopStore: shopStore,
|
||||
accountStore: accountStore,
|
||||
agentWalletStore: agentWalletStore,
|
||||
commissionWithdrawalReqStore: commissionWithdrawalReqStore,
|
||||
commissionWithdrawalSettingStore: commissionWithdrawalSettingStore,
|
||||
commissionRecordStore: commissionRecordStore,
|
||||
agentWalletTransactionStore: agentWalletTransactionStore,
|
||||
db: db,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) ListShopCommissionSummary(ctx context.Context, req *dto.ShopCommissionSummaryListReq) (*dto.ShopCommissionSummaryPageResult, error) {
|
||||
// ListShopFundSummary 代理商资金概况列表(含预充值余额和佣金钱包)
|
||||
// GET /shops/fund-summary
|
||||
func (s *Service) ListShopFundSummary(ctx context.Context, req *dto.ShopFundSummaryListReq) (*dto.ShopFundSummaryPageResult, error) {
|
||||
opts := &store.QueryOptions{
|
||||
Page: req.Page,
|
||||
PageSize: req.PageSize,
|
||||
@@ -69,8 +82,8 @@ func (s *Service) ListShopCommissionSummary(ctx context.Context, req *dto.ShopCo
|
||||
}
|
||||
|
||||
if len(shops) == 0 {
|
||||
return &dto.ShopCommissionSummaryPageResult{
|
||||
Items: []dto.ShopCommissionSummaryItem{},
|
||||
return &dto.ShopFundSummaryPageResult{
|
||||
Items: []dto.ShopFundSummaryItem{},
|
||||
Total: 0,
|
||||
Page: opts.Page,
|
||||
Size: opts.PageSize,
|
||||
@@ -82,6 +95,12 @@ func (s *Service) ListShopCommissionSummary(ctx context.Context, req *dto.ShopCo
|
||||
shopIDs = append(shopIDs, shop.ID)
|
||||
}
|
||||
|
||||
// 批量获取主钱包(预充值钱包)余额
|
||||
mainWallets, err := s.agentWalletStore.GetShopMainWalletBatch(ctx, shopIDs)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "查询主钱包余额失败")
|
||||
}
|
||||
|
||||
walletSummaries, err := s.agentWalletStore.GetShopCommissionSummaryBatch(ctx, shopIDs)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "查询店铺钱包汇总失败")
|
||||
@@ -109,7 +128,7 @@ func (s *Service) ListShopCommissionSummary(ctx context.Context, req *dto.ShopCo
|
||||
}
|
||||
}
|
||||
|
||||
items := make([]dto.ShopCommissionSummaryItem, 0, len(shops))
|
||||
items := make([]dto.ShopFundSummaryItem, 0, len(shops))
|
||||
for _, shop := range shops {
|
||||
if req.Username != "" {
|
||||
acc := accountMap[shop.ID]
|
||||
@@ -119,11 +138,11 @@ func (s *Service) ListShopCommissionSummary(ctx context.Context, req *dto.ShopCo
|
||||
}
|
||||
}
|
||||
|
||||
item := s.buildCommissionSummaryItem(shop, walletSummaries[shop.ID], withdrawnAmounts[shop.ID], withdrawingAmounts[shop.ID], accountMap[shop.ID])
|
||||
item := s.buildFundSummaryItem(shop, mainWallets[shop.ID], walletSummaries[shop.ID], withdrawnAmounts[shop.ID], withdrawingAmounts[shop.ID], accountMap[shop.ID])
|
||||
items = append(items, item)
|
||||
}
|
||||
|
||||
return &dto.ShopCommissionSummaryPageResult{
|
||||
return &dto.ShopFundSummaryPageResult{
|
||||
Items: items,
|
||||
Total: total,
|
||||
Page: opts.Page,
|
||||
@@ -131,11 +150,20 @@ func (s *Service) ListShopCommissionSummary(ctx context.Context, req *dto.ShopCo
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) buildCommissionSummaryItem(shop *model.Shop, walletSummary *model.AgentWallet, withdrawnAmount, withdrawingAmount int64, account *model.Account) dto.ShopCommissionSummaryItem {
|
||||
// buildFundSummaryItem 构造资金概况条目
|
||||
func (s *Service) buildFundSummaryItem(shop *model.Shop, mainWallet, commissionWallet *model.AgentWallet, withdrawnAmount, withdrawingAmount int64, account *model.Account) dto.ShopFundSummaryItem {
|
||||
// 主钱包余额(若未充值则为0)
|
||||
var mainBalance, mainFrozenBalance int64
|
||||
if mainWallet != nil {
|
||||
mainBalance = mainWallet.Balance
|
||||
mainFrozenBalance = mainWallet.FrozenBalance
|
||||
}
|
||||
|
||||
// 佣金钱包
|
||||
var balance, frozenBalance int64
|
||||
if walletSummary != nil {
|
||||
balance = walletSummary.Balance
|
||||
frozenBalance = walletSummary.FrozenBalance
|
||||
if commissionWallet != nil {
|
||||
balance = commissionWallet.Balance
|
||||
frozenBalance = commissionWallet.FrozenBalance
|
||||
}
|
||||
|
||||
totalCommission := balance + frozenBalance + withdrawnAmount
|
||||
@@ -151,12 +179,14 @@ func (s *Service) buildCommissionSummaryItem(shop *model.Shop, walletSummary *mo
|
||||
phone = account.Phone
|
||||
}
|
||||
|
||||
return dto.ShopCommissionSummaryItem{
|
||||
return dto.ShopFundSummaryItem{
|
||||
ShopID: shop.ID,
|
||||
ShopName: shop.ShopName,
|
||||
ShopCode: shop.ShopCode,
|
||||
Username: username,
|
||||
Phone: phone,
|
||||
MainBalance: mainBalance,
|
||||
MainFrozenBalance: mainFrozenBalance,
|
||||
TotalCommission: totalCommission,
|
||||
WithdrawnCommission: withdrawnAmount,
|
||||
UnwithdrawCommission: unwithdrawCommission,
|
||||
@@ -167,7 +197,14 @@ func (s *Service) buildCommissionSummaryItem(shop *model.Shop, walletSummary *mo
|
||||
}
|
||||
}
|
||||
|
||||
// ListShopWithdrawalRequests 查询代理商提现记录
|
||||
// GET /shops/:id/withdrawal-requests
|
||||
func (s *Service) ListShopWithdrawalRequests(ctx context.Context, shopID uint, req *dto.ShopWithdrawalRequestListReq) (*dto.ShopWithdrawalRequestPageResult, error) {
|
||||
// 越权校验:平台人员可查所有,代理只能查自己和下级
|
||||
if err := middleware.CanManageShop(ctx, shopID); err != nil {
|
||||
return nil, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
|
||||
}
|
||||
|
||||
_, err := s.shopStore.GetByID(ctx, shopID)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.CodeShopNotFound, "店铺不存在")
|
||||
@@ -252,6 +289,7 @@ func (s *Service) ListShopWithdrawalRequests(ctx context.Context, shopID uint, r
|
||||
}, nil
|
||||
}
|
||||
|
||||
// buildWithdrawalRequestItem 构造提现记录条目
|
||||
func (s *Service) buildWithdrawalRequestItem(r *model.CommissionWithdrawalRequest, shopName, shopHierarchy string, applicantMap, processorMap map[uint]string) dto.ShopWithdrawalRequestItem {
|
||||
var processorID *uint
|
||||
if r.ProcessorID > 0 {
|
||||
@@ -311,6 +349,7 @@ func (s *Service) buildWithdrawalRequestItem(r *model.CommissionWithdrawalReques
|
||||
}
|
||||
}
|
||||
|
||||
// buildShopHierarchyPath 构造店铺层级路径(最多两层上级)
|
||||
func (s *Service) buildShopHierarchyPath(ctx context.Context, shop *model.Shop) string {
|
||||
if shop == nil {
|
||||
return ""
|
||||
@@ -333,7 +372,14 @@ func (s *Service) buildShopHierarchyPath(ctx context.Context, shop *model.Shop)
|
||||
return path
|
||||
}
|
||||
|
||||
// ListShopCommissionRecords 查询代理商佣金明细
|
||||
// GET /shops/:id/commission-records
|
||||
func (s *Service) ListShopCommissionRecords(ctx context.Context, shopID uint, req *dto.ShopCommissionRecordListReq) (*dto.ShopCommissionRecordPageResult, error) {
|
||||
// 越权校验:平台人员可查所有,代理只能查自己和下级
|
||||
if err := middleware.CanManageShop(ctx, shopID); err != nil {
|
||||
return nil, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
|
||||
}
|
||||
|
||||
_, err := s.shopStore.GetByID(ctx, shopID)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.CodeShopNotFound, "店铺不存在")
|
||||
@@ -391,47 +437,292 @@ func (s *Service) ListShopCommissionRecords(ctx context.Context, shopID uint, re
|
||||
}, nil
|
||||
}
|
||||
|
||||
func getWithdrawalStatusName(status int) string {
|
||||
switch status {
|
||||
case constants.WithdrawalStatusPending:
|
||||
return "待审核"
|
||||
case constants.WithdrawalStatusApproved:
|
||||
return "已通过"
|
||||
case constants.WithdrawalStatusRejected:
|
||||
return "已拒绝"
|
||||
case constants.WithdrawalStatusPaid:
|
||||
return "已到账"
|
||||
default:
|
||||
return "未知"
|
||||
// GetStats 获取佣金统计
|
||||
// GET /shops/:id/commission-stats
|
||||
func (s *Service) GetStats(ctx context.Context, shopID uint, req *dto.CommissionStatsRequest) (*dto.CommissionStatsResponse, error) {
|
||||
// 越权校验:平台人员可查所有,代理只能查自己和下级
|
||||
if err := middleware.CanManageShop(ctx, shopID); err != nil {
|
||||
return nil, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
|
||||
}
|
||||
}
|
||||
|
||||
func getCommissionStatusName(status int) string {
|
||||
switch status {
|
||||
case constants.CommissionStatusFrozen:
|
||||
return "已冻结"
|
||||
case constants.CommissionStatusUnfreezing:
|
||||
return "解冻中"
|
||||
case constants.CommissionStatusReleased:
|
||||
return "已发放"
|
||||
case constants.CommissionStatusInvalid:
|
||||
return "已失效"
|
||||
default:
|
||||
return "未知"
|
||||
filters := &postgres.CommissionRecordListFilters{
|
||||
ShopID: shopID,
|
||||
StartTime: req.StartTime,
|
||||
EndTime: req.EndTime,
|
||||
}
|
||||
|
||||
stats, err := s.commissionRecordStore.GetStats(ctx, filters)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "获取佣金统计失败")
|
||||
}
|
||||
|
||||
if stats == nil {
|
||||
return &dto.CommissionStatsResponse{}, nil
|
||||
}
|
||||
|
||||
var costDiffPercent, oneTimePercent int64
|
||||
if stats.TotalAmount > 0 {
|
||||
costDiffPercent = stats.CostDiffAmount * 1000 / stats.TotalAmount
|
||||
oneTimePercent = stats.OneTimeAmount * 1000 / stats.TotalAmount
|
||||
}
|
||||
|
||||
return &dto.CommissionStatsResponse{
|
||||
TotalAmount: stats.TotalAmount,
|
||||
CostDiffAmount: stats.CostDiffAmount,
|
||||
OneTimeAmount: stats.OneTimeAmount,
|
||||
CostDiffPercent: costDiffPercent,
|
||||
OneTimePercent: oneTimePercent,
|
||||
TotalCount: stats.TotalCount,
|
||||
CostDiffCount: stats.CostDiffCount,
|
||||
OneTimeCount: stats.OneTimeCount,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func containsSubstring(s, substr string) bool {
|
||||
return len(s) >= len(substr) && (s == substr || len(substr) == 0 || (len(s) > 0 && len(substr) > 0 && contains(s, substr)))
|
||||
// GetDailyStats 获取每日佣金统计
|
||||
// GET /shops/:id/commission-daily-stats
|
||||
func (s *Service) GetDailyStats(ctx context.Context, shopID uint, req *dto.DailyCommissionStatsRequest) ([]*dto.DailyCommissionStatsResponse, error) {
|
||||
// 越权校验:平台人员可查所有,代理只能查自己和下级
|
||||
if err := middleware.CanManageShop(ctx, shopID); err != nil {
|
||||
return nil, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
|
||||
}
|
||||
|
||||
days := 30
|
||||
if req.Days != nil && *req.Days > 0 {
|
||||
days = *req.Days
|
||||
}
|
||||
|
||||
filters := &postgres.CommissionRecordListFilters{
|
||||
ShopID: shopID,
|
||||
StartTime: req.StartDate,
|
||||
EndTime: req.EndDate,
|
||||
}
|
||||
|
||||
dailyStats, err := s.commissionRecordStore.GetDailyStats(ctx, filters, days)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "获取每日佣金统计失败")
|
||||
}
|
||||
|
||||
result := make([]*dto.DailyCommissionStatsResponse, 0, len(dailyStats))
|
||||
for _, stat := range dailyStats {
|
||||
result = append(result, &dto.DailyCommissionStatsResponse{
|
||||
Date: stat.Date,
|
||||
TotalAmount: stat.TotalAmount,
|
||||
TotalCount: stat.TotalCount,
|
||||
})
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func contains(s, substr string) bool {
|
||||
for i := 0; i <= len(s)-len(substr); i++ {
|
||||
if s[i:i+len(substr)] == substr {
|
||||
return true
|
||||
// CreateWithdrawalRequest 代理发起提现申请
|
||||
// POST /shops/:id/withdrawal-requests
|
||||
func (s *Service) CreateWithdrawalRequest(ctx context.Context, shopID uint, req *dto.CreateMyWithdrawalReq) (*dto.CreateMyWithdrawalResp, error) {
|
||||
// 提现权限比查询更严格:必须是代理账号本人操作,不允许平台人员或顶级代理替下级提现
|
||||
userType := middleware.GetUserTypeFromContext(ctx)
|
||||
if userType != constants.UserTypeAgent {
|
||||
return nil, errors.New(errors.CodeForbidden, "仅代理商用户可发起提现")
|
||||
}
|
||||
if shopID != middleware.GetShopIDFromContext(ctx) {
|
||||
return nil, errors.New(errors.CodeForbidden, "仅可为本人店铺发起提现")
|
||||
}
|
||||
|
||||
currentUserID := middleware.GetUserIDFromContext(ctx)
|
||||
if currentUserID == 0 {
|
||||
return nil, errors.New(errors.CodeForbidden, "无法获取用户信息")
|
||||
}
|
||||
|
||||
// 获取提现配置
|
||||
setting, err := s.commissionWithdrawalSettingStore.GetCurrent(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "暂未开放提现功能")
|
||||
}
|
||||
|
||||
// 验证最低提现金额
|
||||
if req.Amount < setting.MinWithdrawalAmount {
|
||||
return nil, errors.New(errors.CodeInvalidParam, fmt.Sprintf("提现金额不能低于 %.2f 元", float64(setting.MinWithdrawalAmount)/100))
|
||||
}
|
||||
|
||||
// 获取佣金钱包
|
||||
wallet, err := s.agentWalletStore.GetCommissionWallet(ctx, shopID)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.CodeInsufficientBalance, "钱包不存在")
|
||||
}
|
||||
|
||||
// 验证可用余额
|
||||
if req.Amount > wallet.GetAvailableBalance() {
|
||||
return nil, errors.New(errors.CodeInsufficientBalance, "可提现余额不足")
|
||||
}
|
||||
|
||||
// 验证今日提现次数
|
||||
today := time.Now().Format("2006-01-02")
|
||||
var todayCount int64
|
||||
s.db.WithContext(ctx).Model(&model.CommissionWithdrawalRequest{}).
|
||||
Where("shop_id = ? AND created_at >= ? AND created_at <= ?", shopID, today+" 00:00:00", today+" 23:59:59").
|
||||
Count(&todayCount)
|
||||
if int(todayCount) >= setting.DailyWithdrawalLimit {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "今日提现次数已达上限")
|
||||
}
|
||||
|
||||
// 计算手续费
|
||||
fee := req.Amount * setting.FeeRate / 10000
|
||||
actualAmount := req.Amount - fee
|
||||
withdrawalNo := generateWithdrawalNo()
|
||||
|
||||
accountInfo := map[string]string{
|
||||
"account_name": req.AccountName,
|
||||
"account_number": req.AccountNumber,
|
||||
}
|
||||
accountInfoJSON, _ := json.Marshal(accountInfo)
|
||||
|
||||
var withdrawalRequest *model.CommissionWithdrawalRequest
|
||||
|
||||
err = s.db.Transaction(func(tx *gorm.DB) error {
|
||||
// 使用条件更新防并发
|
||||
result := tx.WithContext(ctx).Model(&model.AgentWallet{}).
|
||||
Where("id = ? AND balance - frozen_balance >= ?", wallet.ID, req.Amount).
|
||||
Updates(map[string]interface{}{
|
||||
"frozen_balance": gorm.Expr("frozen_balance + ?", req.Amount),
|
||||
})
|
||||
if result.Error != nil {
|
||||
return errors.Wrap(errors.CodeInternalError, result.Error, "冻结余额失败")
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return errors.New(errors.CodeInsufficientBalance, "余额不足或并发冲突,请稍后重试")
|
||||
}
|
||||
|
||||
withdrawalRequest = &model.CommissionWithdrawalRequest{
|
||||
WithdrawalNo: withdrawalNo,
|
||||
ShopID: shopID,
|
||||
ApplicantID: currentUserID,
|
||||
Amount: req.Amount,
|
||||
FeeRate: setting.FeeRate,
|
||||
Fee: fee,
|
||||
ActualAmount: actualAmount,
|
||||
WithdrawalMethod: req.WithdrawalMethod,
|
||||
AccountInfo: accountInfoJSON,
|
||||
Status: 1, // 待审核
|
||||
}
|
||||
withdrawalRequest.Creator = currentUserID
|
||||
withdrawalRequest.Updater = currentUserID
|
||||
|
||||
if err := tx.WithContext(ctx).Create(withdrawalRequest).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeInternalError, err, "创建提现申请失败")
|
||||
}
|
||||
|
||||
remark := fmt.Sprintf("提现冻结,单号:%s", withdrawalNo)
|
||||
refType := constants.ReferenceTypeWithdrawal
|
||||
transaction := &model.AgentWalletTransaction{
|
||||
AgentWalletID: wallet.ID,
|
||||
ShopID: shopID,
|
||||
UserID: currentUserID,
|
||||
TransactionType: constants.TransactionTypeWithdrawal,
|
||||
Amount: -req.Amount,
|
||||
BalanceBefore: wallet.Balance,
|
||||
BalanceAfter: wallet.Balance - req.Amount,
|
||||
Status: constants.TransactionStatusProcessing,
|
||||
ReferenceType: &refType,
|
||||
ReferenceID: &withdrawalRequest.ID,
|
||||
Remark: &remark,
|
||||
Creator: currentUserID,
|
||||
ShopIDTag: shopID,
|
||||
}
|
||||
|
||||
if err := tx.WithContext(ctx).Create(transaction).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeInternalError, err, "创建钱包流水失败")
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return false
|
||||
|
||||
return &dto.CreateMyWithdrawalResp{
|
||||
ID: withdrawalRequest.ID,
|
||||
WithdrawalNo: withdrawalRequest.WithdrawalNo,
|
||||
Amount: withdrawalRequest.Amount,
|
||||
FeeRate: withdrawalRequest.FeeRate,
|
||||
Fee: withdrawalRequest.Fee,
|
||||
ActualAmount: withdrawalRequest.ActualAmount,
|
||||
Status: withdrawalRequest.Status,
|
||||
StatusName: getWithdrawalStatusName(withdrawalRequest.Status),
|
||||
CreatedAt: withdrawalRequest.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListMainWalletTransactions 查询代理主钱包(预充值钱包)流水
|
||||
// GET /shops/:id/main-wallet/transactions
|
||||
func (s *Service) ListMainWalletTransactions(ctx context.Context, shopID uint, req *dto.MainWalletTransactionListRequest) (*dto.MainWalletTransactionListResponse, error) {
|
||||
// 越权校验
|
||||
if err := middleware.CanManageShop(ctx, shopID); err != nil {
|
||||
return nil, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
|
||||
}
|
||||
|
||||
page := req.Page
|
||||
pageSize := req.PageSize
|
||||
if page == 0 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize == 0 {
|
||||
pageSize = constants.DefaultPageSize
|
||||
}
|
||||
|
||||
// 获取主钱包,不存在则返回空列表
|
||||
mainWallet, err := s.agentWalletStore.GetMainWallet(ctx, shopID)
|
||||
if err != nil {
|
||||
return &dto.MainWalletTransactionListResponse{
|
||||
Items: []dto.MainWalletTransactionItem{},
|
||||
Total: 0,
|
||||
Page: page,
|
||||
Size: pageSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
filters := &postgres.AgentWalletTransactionListFilters{
|
||||
TransactionType: req.TransactionType,
|
||||
StartDate: req.StartDate,
|
||||
EndDate: req.EndDate,
|
||||
}
|
||||
|
||||
offset := (page - 1) * pageSize
|
||||
transactions, err := s.agentWalletTransactionStore.ListByWalletIDWithFilters(ctx, mainWallet.ID, offset, pageSize, filters)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "查询主钱包流水失败")
|
||||
}
|
||||
|
||||
total, err := s.agentWalletTransactionStore.CountByWalletID(ctx, mainWallet.ID, filters)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "统计主钱包流水失败")
|
||||
}
|
||||
|
||||
items := make([]dto.MainWalletTransactionItem, 0, len(transactions))
|
||||
for _, t := range transactions {
|
||||
var remark string
|
||||
if t.Remark != nil {
|
||||
remark = *t.Remark
|
||||
}
|
||||
var subtype string
|
||||
if t.TransactionSubtype != nil {
|
||||
subtype = *t.TransactionSubtype
|
||||
}
|
||||
items = append(items, dto.MainWalletTransactionItem{
|
||||
ID: t.ID,
|
||||
TransactionType: t.TransactionType,
|
||||
TransactionSubtype: subtype,
|
||||
Amount: t.Amount,
|
||||
BalanceBefore: t.BalanceBefore,
|
||||
BalanceAfter: t.BalanceAfter,
|
||||
Remark: remark,
|
||||
CreatedAt: t.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
|
||||
return &dto.MainWalletTransactionListResponse{
|
||||
Items: items,
|
||||
Total: total,
|
||||
Page: page,
|
||||
Size: pageSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ResolveCommissionRecord 修正待审佣金记录(status=99)
|
||||
@@ -472,7 +763,6 @@ func (s *Service) ResolveCommissionRecord(ctx context.Context, recordID uint, re
|
||||
}
|
||||
|
||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||
// 更新佣金记录
|
||||
if err := s.commissionRecordStore.UpdateByID(ctx, tx, recordID, map[string]any{
|
||||
"status": model.CommissionStatusReleased,
|
||||
"amount": amount,
|
||||
@@ -482,7 +772,6 @@ func (s *Service) ResolveCommissionRecord(ctx context.Context, recordID uint, re
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "更新佣金记录失败")
|
||||
}
|
||||
|
||||
// 入账到佣金钱包(乐观锁)
|
||||
balanceBefore := wallet.Balance
|
||||
result := tx.Model(&model.AgentWallet{}).
|
||||
Where("id = ? AND version = ?", wallet.ID, wallet.Version).
|
||||
@@ -497,7 +786,6 @@ func (s *Service) ResolveCommissionRecord(ctx context.Context, recordID uint, re
|
||||
return errors.New(errors.CodeInternalError, "佣金钱包版本冲突,请重试")
|
||||
}
|
||||
|
||||
// 回写入账后余额
|
||||
if err := s.commissionRecordStore.UpdateByID(ctx, tx, recordID, map[string]any{
|
||||
"balance_after": balanceBefore + amount,
|
||||
}); err != nil {
|
||||
@@ -507,3 +795,54 @@ func (s *Service) ResolveCommissionRecord(ctx context.Context, recordID uint, re
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// getWithdrawalStatusName 获取提现状态名称
|
||||
func getWithdrawalStatusName(status int) string {
|
||||
switch status {
|
||||
case constants.WithdrawalStatusPending:
|
||||
return "待审核"
|
||||
case constants.WithdrawalStatusApproved:
|
||||
return "已通过"
|
||||
case constants.WithdrawalStatusRejected:
|
||||
return "已拒绝"
|
||||
case constants.WithdrawalStatusPaid:
|
||||
return "已到账"
|
||||
default:
|
||||
return "未知"
|
||||
}
|
||||
}
|
||||
|
||||
// getCommissionStatusName 获取佣金状态名称
|
||||
func getCommissionStatusName(status int) string {
|
||||
switch status {
|
||||
case constants.CommissionStatusFrozen:
|
||||
return "已冻结"
|
||||
case constants.CommissionStatusUnfreezing:
|
||||
return "解冻中"
|
||||
case constants.CommissionStatusReleased:
|
||||
return "已发放"
|
||||
case constants.CommissionStatusInvalid:
|
||||
return "已失效"
|
||||
default:
|
||||
return "未知"
|
||||
}
|
||||
}
|
||||
|
||||
// generateWithdrawalNo 生成提现单号
|
||||
func generateWithdrawalNo() string {
|
||||
now := time.Now()
|
||||
return fmt.Sprintf("W%s%04d", now.Format("20060102150405"), rand.Intn(10000))
|
||||
}
|
||||
|
||||
func containsSubstring(s, substr string) bool {
|
||||
return len(s) >= len(substr) && (s == substr || len(substr) == 0 || (len(s) > 0 && len(substr) > 0 && contains(s, substr)))
|
||||
}
|
||||
|
||||
func contains(s, substr string) bool {
|
||||
for i := 0; i <= len(s)-len(substr); i++ {
|
||||
if s[i:i+len(substr)] == substr {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user