feat(退款分佣): 佣金回溯明细替换全额失效并补齐读侧与导出
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m26s

用 PRD 2.14 语义整体替换退款佣金「整单全额失效」实现:原佣金保持已发放不变,
回溯事实落在新表 tb_commission_clawback_record 的负数、不可提现明细上。

- 新增成对迁移 000220 建 tb_commission_clawback_record,唯一约束
  (refund_id, original_commission_id) 为权威幂等键,附店铺+时间/原佣金/订单索引。
- 回溯用例(internal/service/refund/clawback.go):准入仅由退款申请状态、审批异常
  标记与退款方式决定;金额按分整数计算,分母取冻结实收(缺失回落审批尝试)、
  分子原路取渠道成功金额,乘法用 math/big 中间量,舍入差自末条起向前补差;
  终态判据要求订单佣金已离开待计算且不存在 status IN (1,2,99) 的记录。
- 三层幂等:唯一约束兜底、佣金行行锁 + 钱包乐观锁、commission_deducted 仅作投影
  并带 WHERE commission_deducted = false 条件置位;闭合三结果为已回溯、无需回溯、
  审批异常转人工。
- 事务内顺序固定:锁提现申请行 → 锁尝试行 → 解冻冻结 → 置驳回 → 插回溯明细 →
  扣 balance(允许为负)→ 写负数流水 → 审计;删除旧全额失效写入与其两个审计调用点,
  refund.invalidate_commission 仅保留常量与注册供历史审计读取。
- 读侧:佣金明细列表 status 筛选透传,两表 UNION ALL 合并分页并以 source ASC 作
  末位次序键;新增佣金明细详情接口并同步路由与 OpenAPI 装配。
- 导出:新增 commission_record 场景(白名单、exporter 注册、DTO oneof、DataSource
  与列定义),粒度为佣金记录,原佣金与回溯各一行,金额保持分且可为负。
- 新增退款佣金回溯周期补偿任务(@every 1m / MaxRetry(3) / Timeout(10m) /
  Unique(10m),独立队列),保留启动时补偿扫描,判据与既有实现一致。

Refs: AUG26-012
This commit is contained in:
2026-09-14 13:40:34 +08:00
parent 67893617fe
commit 1aa4eacee2
30 changed files with 1867 additions and 399 deletions

View File

@@ -118,6 +118,24 @@ func CommissionRecordResource(record *model.CommissionRecord, beforeData, afterD
}
}
// CommissionClawbackResource 构造退款生成的佣金回溯明细资源。
// 金额按分保留负数、余额可为负,与资金事实一致;不含任何凭证或敏感内容。
func CommissionClawbackResource(record *model.CommissionClawbackRecord) ResourceInput {
id := strconv.FormatUint(uint64(record.ID), 10)
return ResourceInput{
Type: constants.AuditResourceCommissionClawback, ID: &id, Key: id, DisplayName: "佣金回溯明细 " + id,
Relation: constants.AuditResourceRelationAffected, Role: constants.AuditResourceRoleRefundClawback,
IdentitySnapshot: map[string]any{
"id": record.ID, "refund_id": record.RefundID, "refund_no": record.RefundNo,
"original_commission_id": record.OriginalCommissionID,
"order_id": record.OrderID, "order_no": record.OrderNo, "shop_id": record.ShopID,
"commission_source": record.CommissionSource, "amount": record.Amount,
"balance_after": record.BalanceAfter, "withdrawable": record.Withdrawable,
"status": record.Status, "created_at": record.CreatedAt,
},
}
}
func refundStateData(refund *model.RefundRequest) map[string]any {
return map[string]any{
"status": refund.Status, "approved_refund_amount": refund.ApprovedRefundAmount,

View File

@@ -309,6 +309,9 @@ func NewRegistry() *Registry {
refundReturned := refundAction(constants.AuditActionRefundReturned, "退回退款申请", false)
refundResubmitted := refundAction(constants.AuditActionRefundResubmitted, "重新提交退款申请", false)
refundCommissionInvalidated := refundSystemAction(constants.AuditActionRefundCommissionInvalidated, "退款失效佣金")
// 回溯明细与「无需回溯」都由退款佣金后处理任务在 Worker 内写入,与既有退款系统动作入口一致。
refundClawbackCommission := refundSystemAction(constants.AuditActionRefundClawbackCommission, "生成退款佣金回溯明细")
refundClawbackNotRequired := refundSystemAction(constants.AuditActionRefundClawbackNotRequired, "退款无需回溯佣金")
refundAssetProcessed := refundSystemAction(constants.AuditActionRefundAssetProcessed, "完成退款资产后处理")
// 退款审批尝试由后台账号提交与重提;终态与异常标记由企业微信审批消费任务写入(复用 refundAction 的 Worker 入口)。
refundAttemptSubmitted := refundAction(constants.AuditActionRefundAttemptSubmitted, "提交退款审批尝试", false)
@@ -638,6 +641,8 @@ func NewRegistry() *Registry {
constants.AuditActionRefundReturned: refundReturned,
constants.AuditActionRefundResubmitted: refundResubmitted,
constants.AuditActionRefundCommissionInvalidated: refundCommissionInvalidated,
constants.AuditActionRefundClawbackCommission: refundClawbackCommission,
constants.AuditActionRefundClawbackNotRequired: refundClawbackNotRequired,
constants.AuditActionRefundAssetProcessed: refundAssetProcessed,
constants.AuditActionRefundAttemptSubmitted: refundAttemptSubmitted,
constants.AuditActionRefundAttemptApproved: refundAttemptApproved,
@@ -816,6 +821,10 @@ func NewRegistry() *Registry {
Type: constants.AuditResourceRefundChannelRefund, Name: "渠道原路退款事实",
IdentityFields: []string{"id", "refund_no", "channel_refund_status", "channel_refund_no", "channel_refund_request_no", "channel_refund_amount", "failure_reason", "anomaly_flag"},
},
constants.AuditResourceCommissionClawback: {
Type: constants.AuditResourceCommissionClawback, Name: "佣金回溯明细",
IdentityFields: []string{"id", "refund_id", "refund_no", "original_commission_id", "order_id", "order_no", "shop_id", "commission_source", "amount", "balance_after", "withdrawable", "status", "created_at"},
},
constants.AuditResourceEnterprise: {
Type: constants.AuditResourceEnterprise, Name: "企业",
IdentityFields: []string{"id", "enterprise_code", "enterprise_name", "owner_shop_id"},

View File

@@ -111,7 +111,6 @@ func Recover(ctx context.Context, db *gorm.DB, repository *outbox.Repository, li
limit = 100
}
orderStats := RecoveryStats{}
refundStats := RecoveryStats{}
var orders []model.Order
if err := db.WithContext(ctx).Where("payment_status = ? AND commission_status = ?", model.PaymentStatusPaid, model.CommissionStatusPending).Order("id ASC").Limit(limit).Find(&orders).Error; err != nil {
logger.Warn("扫描待计算订单失败", zap.Error(err))
@@ -120,6 +119,19 @@ func Recover(ctx context.Context, db *gorm.DB, repository *outbox.Repository, li
recoverOne(ctx, db, repository, EventCommissionCalculate, order.ID, order.ID, &orderStats, logger, false)
}
}
refundStats := RecoverRefundPostProcessing(ctx, db, repository, limit, logger)
logger.Info("佣金与退款补偿扫描完成",
zap.Int("订单已补发", orderStats.Resent), zap.Int("订单无需补发", orderStats.Unchanged), zap.Int("订单失败", orderStats.Failed),
zap.Int("退款已补发", refundStats.Resent), zap.Int("退款无需补发", refundStats.Unchanged), zap.Int("退款失败", refundStats.Failed))
}
// RecoverRefundPostProcessing 只扫描已通过但后处理未闭合的退款单并按稳定业务键恢复缺失或终态失败事件。
// 返还的统计用于启动日志与周期任务日志;本函数只重投事件,不直接改资金。
func RecoverRefundPostProcessing(ctx context.Context, db *gorm.DB, repository *outbox.Repository, limit int, logger *zap.Logger) RecoveryStats {
if limit <= 0 {
limit = 100
}
refundStats := RecoveryStats{}
var refunds []model.RefundRequest
if err := db.WithContext(ctx).Where("status = ? AND (commission_deducted = ? OR asset_reset = ?)", model.RefundStatusApproved, false, false).Order("id ASC").Limit(limit).Find(&refunds).Error; err != nil {
logger.Warn("扫描退款后处理失败", zap.Error(err))
@@ -133,9 +145,7 @@ func Recover(ctx context.Context, db *gorm.DB, repository *outbox.Repository, li
}
}
}
logger.Info("佣金与退款补偿扫描完成",
zap.Int("订单已补发", orderStats.Resent), zap.Int("订单无需补发", orderStats.Unchanged), zap.Int("订单失败", orderStats.Failed),
zap.Int("退款已补发", refundStats.Resent), zap.Int("退款无需补发", refundStats.Unchanged), zap.Int("退款失败", refundStats.Failed))
return refundStats
}
func recoverOne(ctx context.Context, db *gorm.DB, repository *outbox.Repository, eventType string, aggregateID, orderID uint, stats *RecoveryStats, logger *zap.Logger, retryDelivered bool) {

View File

@@ -0,0 +1,41 @@
package commissiondelivery
import (
"context"
"github.com/hibiken/asynq"
"go.uber.org/zap"
"gorm.io/gorm"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/messaging/outbox"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/errors"
)
// RecoverLimit 是单次补偿扫描的退款单上限。
const RecoverLimit = 100
// RefundRecoveryTaskHandler 执行退款佣金回溯后处理的周期性补偿任务。
// 该任务只按稳定业务键重投 Outbox 事件,绝不直接改资金;重复执行由消费端幂等兜底。
type RefundRecoveryTaskHandler struct {
db *gorm.DB
repository *outbox.Repository
logger *zap.Logger
}
// NewRefundRecoveryTaskHandler 创建退款佣金回溯补偿任务 Handler。
func NewRefundRecoveryTaskHandler(db *gorm.DB, repository *outbox.Repository, logger *zap.Logger) *RefundRecoveryTaskHandler {
return &RefundRecoveryTaskHandler{db: db, repository: repository, logger: logger}
}
// Handle 扫描已通过但佣金回溯后处理未闭合的退款单,恢复其唯一后处理请求投递。
func (h *RefundRecoveryTaskHandler) Handle(ctx context.Context, _ *asynq.Task) error {
if h == nil || h.db == nil || h.repository == nil {
return errors.New(errors.CodeServiceUnavailable, "退款佣金回溯补偿任务未配置")
}
stats := RecoverRefundPostProcessing(ctx, h.db, h.repository, RecoverLimit, h.logger)
h.logger.Info("退款佣金回溯补偿完成",
zap.String("task_type", constants.TaskTypeRefundCommissionRecovery),
zap.Int("已补发", stats.Resent), zap.Int("无需补发", stats.Unchanged), zap.Int("失败", stats.Failed))
return nil
}