feat(代理分销提现): 落地扫码注册、提现资料资格与企微终审提现
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled

AUG26-008。

- 迁移 000214–000217:tb_shop 全局唯一且不可修改的随机分销码(含存量回填)、
  tb_agent_distribution_registration 待审批注册记录、tb_withdrawal_qualification 资料版本、
  tb_commission_withdrawal_request_attempt 审批尝试记录,以及提现申请的 latest_*/异常标记列;
  不修改既有迁移,down 在存在本 Change 业务事实或新类型场景行时拒绝破坏性回滚。
- 公开接口 POST /api/c/v1/agent-distribution-registrations:无认证,复用既有短信验证码校验、
  消费与限流;无效分销码、停用上级、验证码无效或已消费统一返回「分销码不可用」且不落库,
  审批通过前不创建店铺、账号或钱包。
- 审批通过才在同一事务内建启用店铺、代理主账号、钱包、上级层级与业务员快照,驳回不建实体,
  重复回调不重复建实体,提交后清理上级下级缓存。
- 提现资料资格按不可变版本保存,替换合同或法人身份证即新增版本并同事务失效旧有效版本;
  超管作废原因必填;代理停用与店铺删除联动失效。
- 提现每次提交或重提新增不可变审批尝试记录并冻结金额;企业微信通过仅一次从冻结扣减、
  保持状态 2 并写 paid_at(不使用状态 4),驳回/cancelled/deleted 仅一次释放,
  通过后撤销不回滚、不重新冻结、只写正交异常标记;加锁顺序统一为申请→尝试→钱包。
- 本地人工终审对已关联审批实例的申请返回状态冲突,approval_instance_id 为空的存量申请保持既有行为,
  不新增任何配置开关。
- 补齐审批业务类型注册点全集:业务类型与场景字段常量、场景 DTO 两处枚举与中文描述、
  场景字段白名单/合法类型/中文名、数据库 CHECK、Worker 决策消费者与装配、审批审计资源映射,
  以及三个新审计资源与 13 个审计动作;失败/拒绝审计改为必达。
- 新增后台路由与 OpenAPI:资格提交/查询/作废、提现申请/重提/详情、店铺详情返回只读分销码。
- 归档本 Change:主 Spec 新增 agent-distribution-withdrawal 能力(5 个 Requirement)。

验证(junhong_cmp_test + Redis DB 6,显式 DB_*,未重置整库):
- 迁移 up → version 217 且 dirty=false → down 3 → up 回 217,fixture 复核残留为 0。
- 受控状态机脚手架 227 项通过 / 0 项失败,覆盖 18 组场景(幂等与乱序回调、资金冻结/释放/重提、
  退款回扣 × 在途提现并发、负向场景拒绝审计与 14 个动作码审计真实落库)。
- gofmt 空、go build/go vet 通过、gendocs 与工作区逐字节一致、context-health 通过、
  openspec validate --strict 通过、doctor healthy;自动化测试按项目决策为 N/A。

运行期前置(未完成,非代码交付物):由超管经 PUT /api/admin/wecom/scenes/{business_type} 为
agent_distribution_approval、withdrawal_qualification_approval、commission_withdrawal_approval
配置启用场景与模板控件映射;未配置时相应提交失败关闭。
This commit is contained in:
2026-09-14 09:45:13 +08:00
parent 315a7de3e4
commit 575d056f54
68 changed files with 5759 additions and 309 deletions

View File

@@ -160,6 +160,13 @@ func (s *Service) Approve(ctx context.Context, id uint, req *dto.ApproveWithdraw
return nil, errors.New(errors.CodeNotFound, "提现申请不存在")
}
if withdrawal.ApprovalInstanceID != nil {
// 已关联企业微信审批实例的申请只接受渠道终审,本地人工终审一律拒绝且不改动任何事实。
businessErr := errors.New(errors.CodeConflict, "提现申请已接入企业微信终审,不支持本地人工处理")
s.recordWithdrawalDecisionFailure(ctx, withdrawal, nil, constants.AuditActionCommissionWithdrawalApproved, "通过佣金提现申请失败", businessErr)
return nil, businessErr
}
if withdrawal.Status != constants.WithdrawalStatusPending {
businessErr := errors.New(errors.CodeInvalidStatus, "申请状态不允许此操作")
s.recordWithdrawalDecisionFailure(ctx, withdrawal, nil, constants.AuditActionCommissionWithdrawalApproved, "通过佣金提现申请失败", businessErr)
@@ -280,6 +287,13 @@ func (s *Service) Reject(ctx context.Context, id uint, req *dto.RejectWithdrawal
return nil, errors.New(errors.CodeNotFound, "提现申请不存在")
}
if withdrawal.ApprovalInstanceID != nil {
// 已关联企业微信审批实例的申请只接受渠道终审,本地人工终审一律拒绝且不改动任何事实。
businessErr := errors.New(errors.CodeConflict, "提现申请已接入企业微信终审,不支持本地人工处理")
s.recordWithdrawalDecisionFailure(ctx, withdrawal, nil, constants.AuditActionCommissionWithdrawalRejected, "驳回佣金提现申请失败", businessErr)
return nil, businessErr
}
if withdrawal.Status != constants.WithdrawalStatusPending {
businessErr := errors.New(errors.CodeInvalidStatus, "申请状态不允许此操作")
s.recordWithdrawalDecisionFailure(ctx, withdrawal, nil, constants.AuditActionCommissionWithdrawalRejected, "驳回佣金提现申请失败", businessErr)

View File

@@ -896,13 +896,20 @@ func (s *Service) deductSingleCommission(ctx context.Context, refund *model.Refu
}
return nil
}
// 全库统一加锁顺序:申请行 → 尝试行 → 钱包行(钱包永远最后)。
// 待审提现的加锁与释放额计算必须发生在钱包加锁之前,否则与企微终态消费者
// (申请 → 尝试 → 钱包)形成 A→B、B→A 的死锁环。
rejects, err := s.collectPendingWithdrawalRejects(ctx, tx, current.ShopID)
if err != nil {
return err
}
var wallet model.AgentWallet
if err := tx.WithContext(ctx).Clauses(clause.Locking{Strength: "UPDATE"}).
Where("shop_id = ? AND wallet_type = ?", current.ShopID, constants.AgentWalletTypeCommission).
First(&wallet).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "锁定退款佣金钱包失败")
}
if err := s.rejectPendingWithdrawals(ctx, tx, &wallet, current.ShopID, refund); err != nil {
if err := s.applyPendingWithdrawalRejects(ctx, tx, &wallet, refund, rejects); err != nil {
return err
}
result := tx.WithContext(ctx).Model(&model.AgentWallet{}).
@@ -939,39 +946,98 @@ func (s *Service) deductSingleCommission(ctx context.Context, refund *model.Refu
})
}
// rejectPendingWithdrawals 回扣佣金前拒绝该店铺所有待审提现。
// 提现冻结的是佣金余额,退款回扣优先级更高;先解冻并拒绝,避免已回扣佣金仍被提现。
func (s *Service) rejectPendingWithdrawals(ctx context.Context, tx *gorm.DB, wallet *model.AgentWallet, shopID uint, refund *model.RefundRequest) error {
// pendingWithdrawalReject 是一条待审提现的本次拒绝事实
// releaseAmount 是本次实际释放额:接入企业微信审批的申请取尝试记录事实,
// 从未关联审批实例的存量申请取申请金额;已结算尝试的本次释放额为 0。
type pendingWithdrawalReject struct {
Withdrawal model.CommissionWithdrawalRequest
Before map[string]any
ReleaseAmount int64
}
// collectPendingWithdrawalRejects 在钱包加锁之前锁定该店铺全部待审提现并算出本次释放额。
// 加锁顺序申请行FOR UPDATE→ 尝试行FOR UPDATE钱包行留给调用方最后加锁。
func (s *Service) collectPendingWithdrawalRejects(
ctx context.Context,
tx *gorm.DB,
shopID uint,
) ([]pendingWithdrawalReject, error) {
var withdrawals []model.CommissionWithdrawalRequest
if err := tx.WithContext(ctx).Clauses(clause.Locking{Strength: "UPDATE"}).
Where("shop_id = ? AND status = ?", shopID, constants.WithdrawalStatusPending).
Find(&withdrawals).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "查询待审核佣金提现失败")
Order("id ASC").Find(&withdrawals).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询待审核佣金提现失败")
}
if len(withdrawals) == 0 {
return nil, nil
}
requestIDs := make([]uint, 0, len(withdrawals))
for i := range withdrawals {
requestIDs = append(requestIDs, withdrawals[i].ID)
}
releasedAmounts, err := postgres.ReleaseUnsettledForRequestsInTx(ctx, tx, requestIDs, time.Now().UTC())
if err != nil {
return nil, err
}
withAttempts, err := postgres.CountRequestsWithAttemptsInTx(ctx, tx, requestIDs)
if err != nil {
return nil, err
}
rejects := make([]pendingWithdrawalReject, 0, len(withdrawals))
for i := range withdrawals {
withdrawal := withdrawals[i]
releaseAmount := withdrawal.Amount
if _, hasAttempt := withAttempts[withdrawal.ID]; hasAttempt {
// 接入企业微信审批的申请:释放金额取本次实际释放的尝试事实。
releaseAmount = releasedAmounts[withdrawal.ID]
}
rejects = append(rejects, pendingWithdrawalReject{
Withdrawal: withdrawal, Before: withdrawalRejectState(&withdrawal), ReleaseAmount: releaseAmount,
})
}
return rejects, nil
}
// applyPendingWithdrawalRejects 按本次实际释放额解冻钱包、置驳回并写流水与审计。
// 释放额为 0 时不写无意义的 0 金额流水,审计也不带钱包流水资源。
func (s *Service) applyPendingWithdrawalRejects(
ctx context.Context,
tx *gorm.DB,
wallet *model.AgentWallet,
refund *model.RefundRequest,
rejects []pendingWithdrawalReject,
) error {
if len(rejects) == 0 {
return nil
}
var shop model.Shop
if err := tx.WithContext(ctx).First(&shop, shopID).Error; err != nil {
if err := tx.WithContext(ctx).First(&shop, wallet.ShopID).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "查询提现店铺失败")
}
for i := range withdrawals {
w := &withdrawals[i]
before := withdrawalRejectState(w)
if err := s.agentWalletStore.UnfreezeBalanceWithTx(ctx, tx, wallet.ID, w.Amount); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "解冻提现冻结余额失败")
remark := "退款佣金回扣,自动拒绝提现"
for i := range rejects {
reject := &rejects[i]
w := &reject.Withdrawal
releaseAmount := reject.ReleaseAmount
if releaseAmount > 0 {
if err := s.agentWalletStore.UnfreezeBalanceWithTx(ctx, tx, wallet.ID, releaseAmount); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "解冻提现冻结余额失败")
}
}
refType := constants.ReferenceTypeWithdrawal
remark := "退款佣金回扣,自动拒绝提现"
transaction := &model.AgentWalletTransaction{
AgentWalletID: wallet.ID, ShopID: shopID, UserID: refund.Creator,
TransactionType: constants.AgentTransactionTypeRefund, Amount: w.Amount,
BalanceBefore: wallet.Balance, BalanceAfter: wallet.Balance,
Status: constants.TransactionStatusSuccess, ReferenceType: &refType, ReferenceID: &w.ID,
Remark: &remark, Creator: refund.Creator, ShopIDTag: shopID,
}
if err := tx.WithContext(ctx).Create(transaction).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "创建自动拒绝提现流水失败")
var transaction *model.AgentWalletTransaction
if releaseAmount > 0 {
// 只有本次确实释放了冻结才写流水,避免产生无意义的 0 金额流水。
refType := constants.ReferenceTypeWithdrawal
transaction = &model.AgentWalletTransaction{
AgentWalletID: wallet.ID, ShopID: wallet.ShopID, UserID: refund.Creator,
TransactionType: constants.AgentTransactionTypeRefund, Amount: releaseAmount,
BalanceBefore: wallet.Balance, BalanceAfter: wallet.Balance,
Status: constants.TransactionStatusSuccess, ReferenceType: &refType, ReferenceID: &w.ID,
Remark: &remark, Creator: refund.Creator, ShopIDTag: wallet.ShopID,
}
if err := tx.WithContext(ctx).Create(transaction).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "创建自动拒绝提现流水失败")
}
}
now := time.Now()
result := tx.WithContext(ctx).Model(&model.CommissionWithdrawalRequest{}).
@@ -991,7 +1057,10 @@ func (s *Service) rejectPendingWithdrawals(ctx context.Context, tx *gorm.DB, wal
w.Status = constants.WithdrawalStatusRejected
w.ProcessedAt = &now
w.RejectReason = remark
if err := s.appendWithdrawalRejectAudit(ctx, tx, w, wallet, transaction, &shop, before); err != nil {
frozenBefore := wallet.FrozenBalance
wallet.FrozenBalance = frozenBefore - releaseAmount
if err := s.appendWithdrawalRejectAudit(ctx, tx, w, wallet, transaction, &shop,
reject.Before, releaseAmount, frozenBefore); err != nil {
return err
}
}
@@ -1005,7 +1074,17 @@ func withdrawalRejectState(w *model.CommissionWithdrawalRequest) map[string]any
}
}
func (s *Service) appendWithdrawalRejectAudit(ctx context.Context, tx *gorm.DB, withdrawal *model.CommissionWithdrawalRequest, wallet *model.AgentWallet, transaction *model.AgentWalletTransaction, shop *model.Shop, before map[string]any) error {
func (s *Service) appendWithdrawalRejectAudit(
ctx context.Context,
tx *gorm.DB,
withdrawal *model.CommissionWithdrawalRequest,
wallet *model.AgentWallet,
transaction *model.AgentWalletTransaction,
shop *model.Shop,
before map[string]any,
releaseAmount int64,
frozenBefore int64,
) error {
if s.auditWriter == nil {
return errors.New(errors.CodeInvalidStatus, "退款统一审计接缝未配置")
}
@@ -1013,21 +1092,32 @@ func (s *Service) appendWithdrawalRejectAudit(ctx context.Context, tx *gorm.DB,
before, withdrawalRejectState(withdrawal))
primary.SubjectVisibility = constants.AuditSubjectResult
primary.SubjectSummary = "退款佣金回扣自动拒绝提现"
// 审计前后冻结额一律取本次实际释放额,避免与实际释放不一致甚至为负。
walletResource := audit.AgentWalletResource(wallet, constants.AuditResourceRelationAffected, constants.AuditResourceRoleWithdrawalWallet,
map[string]any{"balance": wallet.Balance, "frozen_balance": wallet.FrozenBalance},
map[string]any{"balance": wallet.Balance, "frozen_balance": wallet.FrozenBalance - withdrawal.Amount})
map[string]any{"balance": wallet.Balance, "frozen_balance": frozenBefore},
map[string]any{"balance": wallet.Balance, "frozen_balance": frozenBefore - releaseAmount})
walletResource.SubjectVisibility = constants.AuditSubjectInternalOnly
transactionResource := audit.AgentWalletTransactionResource(transaction, constants.AuditResourceRelationAffected, constants.AuditResourceRoleWithdrawalTransaction)
transactionResource.SubjectVisibility = constants.AuditSubjectInternalOnly
shopResource := audit.ShopResource(shop, constants.AuditResourceRelationReference, constants.AuditResourceRoleWithdrawalShop)
shopResource.SubjectVisibility = constants.AuditSubjectInternalOnly
return s.auditWriter.Append(ctx, tx, audit.AppendInput{
resources := []audit.ResourceInput{primary, walletResource, shopResource}
if transaction != nil {
transactionResource := audit.AgentWalletTransactionResource(transaction, constants.AuditResourceRelationAffected, constants.AuditResourceRoleWithdrawalTransaction)
transactionResource.SubjectVisibility = constants.AuditSubjectInternalOnly
resources = append(resources, transactionResource)
}
// 与分销/提现终审路径统一口径:这笔审计属于「要求成功必达」的拒绝事实,
// 必须与业务事实同事务原子提交,因此使用非吞错变体并显式返回错误。
if _, err := s.auditWriter.AppendAndGet(ctx, tx, audit.AppendInput{
EventID: "commission-withdrawal:" + strconv.FormatUint(uint64(withdrawal.ID), 10) + ":refund-rejected",
ActionCode: constants.AuditActionCommissionWithdrawalRejected, Summary: "退款佣金回扣自动拒绝提现",
ScopeType: constants.AuditScopePlatform, Result: constants.AuditResultSuccess,
CorrelationID: withdrawal.WithdrawalNo, Metadata: map[string]any{"amount": withdrawal.Amount, "status": withdrawal.Status},
Resources: []audit.ResourceInput{primary, walletResource, transactionResource, shopResource},
})
CorrelationID: withdrawal.WithdrawalNo,
Metadata: map[string]any{"amount": withdrawal.Amount, "released_amount": releaseAmount, "status": withdrawal.Status},
Resources: resources,
}); err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "写入退款自动拒绝提现审计失败")
}
return nil
}
// handleRefundAssetProcessing 幂等处理退款后的资产状态。

View File

@@ -17,13 +17,14 @@ import (
)
type Service struct {
db *gorm.DB
redisClient *redis.Client
accessAudit accessauditapp.Writer
shopStore *postgres.ShopStore
accountStore *postgres.AccountStore
shopRoleStore *postgres.ShopRoleStore
roleStore *postgres.RoleStore
db *gorm.DB
redisClient *redis.Client
accessAudit accessauditapp.Writer
qualificationInvalidator WithdrawalQualificationInvalidator
shopStore *postgres.ShopStore
accountStore *postgres.AccountStore
shopRoleStore *postgres.ShopRoleStore
roleStore *postgres.RoleStore
}
// SetAccessAudit 注入店铺角色授权的事务、缓存和统一审计边界。
@@ -47,6 +48,17 @@ func New(
}
}
// WithdrawalQualificationInvalidator 在店铺停用事务内联动失效提现资料资格。
type WithdrawalQualificationInvalidator interface {
InvalidateByShopDisable(ctx context.Context, tx *gorm.DB, shopID uint, reason string) error
}
// SetWithdrawalQualificationInvalidator 注入店铺停用联动的提现资料资格失效接缝。
// 未注入时停用不联动,用于不依赖该能力的旧装配路径。
func (s *Service) SetWithdrawalQualificationInvalidator(invalidator WithdrawalQualificationInvalidator) {
s.qualificationInvalidator = invalidator
}
func (s *Service) Update(ctx context.Context, id uint, req *dto.UpdateShopRequest) (*dto.ShopResponse, error) {
currentUserID := middleware.GetUserIDFromContext(ctx)
if currentUserID == 0 {
@@ -58,6 +70,7 @@ func (s *Service) Update(ctx context.Context, id uint, req *dto.UpdateShopReques
return nil, errors.New(errors.CodeShopNotFound, "店铺不存在")
}
previousStatus := shop.Status
shop.ShopName = req.ShopName
shop.ContactName = req.ContactName
shop.ContactPhone = req.ContactPhone
@@ -68,7 +81,7 @@ func (s *Service) Update(ctx context.Context, id uint, req *dto.UpdateShopReques
shop.Status = req.Status
shop.Updater = currentUserID
if err := s.shopStore.Update(ctx, shop); err != nil {
if err := s.persistShopWithQualificationInvalidation(ctx, shop, previousStatus); err != nil {
return nil, err
}
@@ -81,22 +94,23 @@ func (s *Service) Update(ctx context.Context, id uint, req *dto.UpdateShopReques
}
return &dto.ShopResponse{
ID: shop.ID,
ShopName: shop.ShopName,
ShopCode: shop.ShopCode,
ParentID: shop.ParentID,
ParentShopName: parentShopName,
Level: shop.Level,
ContactName: shop.ContactName,
ContactPhone: shop.ContactPhone,
Province: shop.Province,
City: shop.City,
District: shop.District,
Address: shop.Address,
Status: shop.Status,
StatusName: constants.GetStatusName(shop.Status),
CreatedAt: shop.CreatedAt.Format("2006-01-02 15:04:05"),
UpdatedAt: shop.UpdatedAt.Format("2006-01-02 15:04:05"),
ID: shop.ID,
ShopName: shop.ShopName,
ShopCode: shop.ShopCode,
DistributionCode: shop.DistributionCode,
ParentID: shop.ParentID,
ParentShopName: parentShopName,
Level: shop.Level,
ContactName: shop.ContactName,
ContactPhone: shop.ContactPhone,
Province: shop.Province,
City: shop.City,
District: shop.District,
Address: shop.Address,
Status: shop.Status,
StatusName: constants.GetStatusName(shop.Status),
CreatedAt: shop.CreatedAt.Format("2006-01-02 15:04:05"),
UpdatedAt: shop.UpdatedAt.Format("2006-01-02 15:04:05"),
}, nil
}
@@ -115,10 +129,31 @@ func (s *Service) Disable(ctx context.Context, id uint) error {
}
// 更新状态
previousStatus := shop.Status
shop.Status = constants.StatusDisabled
shop.Updater = currentUserID
return s.shopStore.Update(ctx, shop)
return s.persistShopWithQualificationInvalidation(ctx, shop, previousStatus)
}
// persistShopWithQualificationInvalidation 保存店铺状态,并在本次停用时联动失效提现资料资格。
// 停用与失效必须同事务提交,避免店铺已停用而资格仍显示有效。
func (s *Service) persistShopWithQualificationInvalidation(
ctx context.Context,
shop *model.Shop,
previousStatus int,
) error {
disabling := previousStatus != constants.ShopStatusDisabled && shop.Status == constants.ShopStatusDisabled
if !disabling || s.qualificationInvalidator == nil || s.db == nil {
return s.shopStore.Update(ctx, shop)
}
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := postgres.NewShopStore(tx, s.redisClient).Update(ctx, shop); err != nil {
return err
}
return s.qualificationInvalidator.InvalidateByShopDisable(
ctx, tx, shop.ID, "代理店铺已停用,提现资料资格自动失效")
})
}
// Enable 启用店铺
@@ -202,22 +237,23 @@ func (s *Service) ListShopResponses(ctx context.Context, req *dto.ShopListReques
}
responses = append(responses, &dto.ShopResponse{
ID: shop.ID,
ShopName: shop.ShopName,
ShopCode: shop.ShopCode,
ParentID: shop.ParentID,
ParentShopName: parentShopName,
Level: shop.Level,
ContactName: shop.ContactName,
ContactPhone: shop.ContactPhone,
Province: shop.Province,
City: shop.City,
District: shop.District,
Address: shop.Address,
Status: shop.Status,
StatusName: constants.GetStatusName(shop.Status),
CreatedAt: shop.CreatedAt.Format("2006-01-02 15:04:05"),
UpdatedAt: shop.UpdatedAt.Format("2006-01-02 15:04:05"),
ID: shop.ID,
ShopName: shop.ShopName,
ShopCode: shop.ShopCode,
DistributionCode: shop.DistributionCode,
ParentID: shop.ParentID,
ParentShopName: parentShopName,
Level: shop.Level,
ContactName: shop.ContactName,
ContactPhone: shop.ContactPhone,
Province: shop.Province,
City: shop.City,
District: shop.District,
Address: shop.Address,
Status: shop.Status,
StatusName: constants.GetStatusName(shop.Status),
CreatedAt: shop.CreatedAt.Format("2006-01-02 15:04:05"),
UpdatedAt: shop.UpdatedAt.Format("2006-01-02 15:04:05"),
})
}
@@ -336,6 +372,15 @@ func (s *Service) Delete(ctx context.Context, id uint) error {
return errors.Wrap(errors.CodeDatabaseError, err, "禁用店铺账号失败")
}
}
// 店铺删除与停用同等失效该店铺全部有效提现资料资格。
// 必须在软删除之前执行:失效路径按 deleted_at IS NULL 读取店铺以写审计,
// 删除后再调用会因店铺不可见而报 NotFound导致含有效资格的店铺永远删不掉。
if s.qualificationInvalidator != nil {
if err := s.qualificationInvalidator.InvalidateByShopDisable(
ctx, tx, locked.ID, "代理店铺已删除,提现资料资格自动失效"); err != nil {
return err
}
}
if err := tx.Delete(&model.Shop{}, id).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "删除店铺失败")
}

View File

@@ -7,6 +7,7 @@ import (
"math/rand"
"time"
"github.com/break/junhong_cmp_fiber/internal/application/distributionwithdrawal"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/audit"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/model/dto"
@@ -30,6 +31,7 @@ type Service struct {
agentWalletTransactionStore *postgres.AgentWalletTransactionStore
db *gorm.DB
auditWriter *audit.Writer
withdrawalApprovalService *distributionwithdrawal.WithdrawalService
logger *zap.Logger
}
@@ -38,6 +40,12 @@ func (s *Service) SetAuditWriter(writer *audit.Writer) {
s.auditWriter = writer
}
// SetWithdrawalApprovalService 注入接入企业微信终审的提现申请用例。
// 未注入时发起提现失败关闭,避免绕过资料资格校验与审批实例创建。
func (s *Service) SetWithdrawalApprovalService(service *distributionwithdrawal.WithdrawalService) {
s.withdrawalApprovalService = service
}
// New 创建代理商资金管理服务
func New(
shopStore *postgres.ShopStore,
@@ -409,7 +417,12 @@ func (s *Service) GetDailyStats(ctx context.Context, shopID uint, req *dto.Daily
// CreateWithdrawalRequest 代理发起提现申请
// POST /shops/:id/withdrawal-requests
// 先校验提现配置与本人代理身份,再在同一事务内校验有效提现资料资格、冻结余额、
// 写审批尝试记录并创建企业微信审批实例。任何校验失败都不创建申请、审批实例或冻结。
func (s *Service) CreateWithdrawalRequest(ctx context.Context, shopID uint, req *dto.CreateMyWithdrawalReq) (*dto.CreateMyWithdrawalResp, error) {
if s.withdrawalApprovalService == nil {
return nil, errors.New(errors.CodeServiceUnavailable, "提现审批能力尚未配置")
}
// 提现权限比查询更严格:必须是代理账号本人操作,不允许平台人员或顶级代理替下级提现
userType := middleware.GetUserTypeFromContext(ctx)
if userType != constants.UserTypeAgent {
@@ -418,130 +431,86 @@ func (s *Service) CreateWithdrawalRequest(ctx context.Context, shopID uint, req
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)
policy, err := s.currentWithdrawalPolicy(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)
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: constants.WithdrawalStatusPending,
}
withdrawalRequest.Creator = currentUserID
withdrawalRequest.Updater = currentUserID
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, "余额不足或并发冲突,请稍后重试")
}
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.AgentTransactionTypeWithdrawal,
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 s.appendWithdrawalRequestAudit(ctx, tx, withdrawalRequest, wallet, transaction)
})
if err != nil {
s.recordWithdrawalRequestFailure(ctx, withdrawalRequest, wallet, err)
return nil, err
}
result, err := s.withdrawalApprovalService.Create(ctx, shopID, policy, distributionwithdrawal.WithdrawalInput{
Amount: req.Amount,
WithdrawalMethod: req.WithdrawalMethod,
AccountName: req.AccountName,
AccountNumber: req.AccountNumber,
})
if err != nil {
return nil, err
}
return withdrawalApprovalResp(result), nil
}
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: constants.GetWithdrawalStatusName(withdrawalRequest.Status),
CreatedAt: withdrawalRequest.CreatedAt.Format("2006-01-02 15:04:05"),
// ResubmitWithdrawalRequest 代理修改金额、收款信息与本次发票后重提已被驳回的提现申请
// PUT /shops/:shop_id/withdrawal-requests/:id
// 事务内先释放旧未结算尝试的冻结,再按新金额冻结;历史尝试与审批结果不被覆盖。
func (s *Service) ResubmitWithdrawalRequest(ctx context.Context, shopID uint, requestID uint, req *dto.ResubmitWithdrawalReq) (*dto.CreateMyWithdrawalResp, error) {
if s.withdrawalApprovalService == nil {
return nil, errors.New(errors.CodeServiceUnavailable, "提现审批能力尚未配置")
}
userType := middleware.GetUserTypeFromContext(ctx)
if userType != constants.UserTypeAgent {
return nil, errors.New(errors.CodeForbidden, "仅代理商用户可重提提现")
}
if shopID == 0 || shopID != middleware.GetShopIDFromContext(ctx) {
return nil, errors.New(errors.CodeForbidden, "仅可为本人店铺重提提现")
}
// 先复核申请属于该店铺,越权与不存在返回同一结果。
existing, err := s.commissionWithdrawalReqStore.GetByID(ctx, requestID)
if err != nil || existing == nil || existing.ShopID != shopID {
return nil, errors.New(errors.CodeNotFound, "提现申请不存在")
}
policy, err := s.currentWithdrawalPolicy(ctx)
if err != nil {
return nil, err
}
result, err := s.withdrawalApprovalService.Resubmit(ctx, requestID, policy, distributionwithdrawal.WithdrawalInput{
Amount: req.Amount,
WithdrawalMethod: req.WithdrawalMethod,
AccountName: req.AccountName,
AccountNumber: req.AccountNumber,
InvoiceKeys: req.InvoiceKeys,
})
if err != nil {
return nil, err
}
return withdrawalApprovalResp(result), nil
}
// currentWithdrawalPolicy 读取当前提现配置为调用方策略快照,未开放提现时返回稳定错误。
func (s *Service) currentWithdrawalPolicy(ctx context.Context) (distributionwithdrawal.WithdrawalPolicy, error) {
setting, err := s.commissionWithdrawalSettingStore.GetCurrent(ctx)
if err != nil {
return distributionwithdrawal.WithdrawalPolicy{}, errors.New(errors.CodeInvalidParam, "暂未开放提现功能")
}
return distributionwithdrawal.WithdrawalPolicy{
MinAmount: setting.MinWithdrawalAmount,
FeeRate: setting.FeeRate,
DailyWithdrawalLimit: setting.DailyWithdrawalLimit,
}, nil
}
// withdrawalApprovalResp 把提现用例结果映射为发起提现响应。
func withdrawalApprovalResp(result *distributionwithdrawal.WithdrawalResult) *dto.CreateMyWithdrawalResp {
return &dto.CreateMyWithdrawalResp{
ID: result.RequestID,
WithdrawalNo: result.WithdrawalNo,
Amount: result.Amount,
FeeRate: result.FeeRate,
Fee: result.Fee,
ActualAmount: result.ActualAmount,
Status: result.Status,
StatusName: constants.GetWithdrawalStatusName(result.Status),
CreatedAt: result.CreatedAt.Format("2006-01-02 15:04:05"),
}
}
// ListMainWalletTransactions 查询代理主钱包(预充值钱包)流水
// GET /shops/:id/main-wallet/transactions
func (s *Service) ListMainWalletTransactions(ctx context.Context, shopID uint, req *dto.MainWalletTransactionListRequest) (*dto.MainWalletTransactionListResponse, error) {