feat(退款): AUG26-006 退款方式选择与原路退款

按 PRD 2.3/2.4/2.5 落地套餐退款的方式矩阵与原路渠道退款:

- 退款申请派生并冻结权威实收金额(线上取原成功支付记录,钱包/线下取订单实际收款),
  提交人不可填写或修改;按来源支付方式生成可选方式矩阵并在创建、提交、执行前重复校验。
- 审批切换为「每次提交一条不可变审批尝试记录 + 独立企业微信审批实例」,业务标识取尝试
  记录主键;终态消费按尝试记录优先、退款申请兜底双读,兼容存量无实例与已关联实例申请。
  新增活动退款部分唯一索引 (order_id) WHERE status IN (1,5,6)。
- 本地人工终审保持既有开关,补齐通过入口的 approval_instance_id IS NULL 守卫,使三个
  入口一致拒绝已关联审批实例的申请;重提按尝试模式重写(仅已拒绝/已退回/原路失败且无异常)。
- 权益时点:企微通过事务写退款终态、按方式确定的订单态、钱包回款、员工账单冲销与可靠
  失效事实;套餐失效/接续/停机仍由既有可靠机制最终一致执行,不把外部调用放入资金事务。
  订单支付状态按方式置位:凭证退款与退回原钱包在企微通过时置已退款,原路须渠道明确成功。
- 按官方契约实现微信直连 v3、微信 v2(双向证书)、富友(/commonRefund 与 /refundQuery)、
  支付宝四类原路退款;能力只由服务商类型与退款必需凭证完整性决定,无人工开关。
  渠道请求号在提交时冻结到尝试记录,并以 channel_submitted_at 条件认领保证资金动作至多
  提交一次(重复投递只查询不二次提交);不向任何渠道传递退款结果通知地址。
- 新增 refund:channel:recovery 恢复任务只查询回填;本地查询窗口超期(富友 72 小时、
  微信 v2 7 天)转原路退款失败、渠道状态已失败、分类超时未知并置异常转人工,不放行自动
  重提以避免重复退款。
- 同步退款 DTO/导出/审计资源与审计查询关联、商户凭证文档,并修正 fuiou 集成契约文档。

迁移 000218(退款尝试与渠道退款事实)、000219(微信 v2 客户端证书凭证)成对提供,
未修改既有迁移;测试库 junhong_cmp_test 完成 up/down/up 与行为核对,未调用真实渠道。
This commit is contained in:
2026-09-14 11:55:16 +08:00
parent 48c85a4916
commit ba0855d9eb
51 changed files with 5995 additions and 986 deletions

View File

@@ -10,6 +10,7 @@ import (
approvalapp "github.com/break/junhong_cmp_fiber/internal/application/approval"
employeecollectionapp "github.com/break/junhong_cmp_fiber/internal/application/employeecollection"
refundapproval "github.com/break/junhong_cmp_fiber/internal/application/refundapproval"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/commissiondelivery"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/messaging/outbox"
"github.com/break/junhong_cmp_fiber/internal/model"
@@ -30,28 +31,76 @@ func (s *Service) Handle(ctx context.Context, event approvalapp.TerminalDecision
case constants.ApprovalDecisionRejected, constants.ApprovalDecisionCancelled, constants.ApprovalDecisionDeleted:
return s.applyClosedDecision(ctx, event)
case constants.ApprovalDecisionRevokedAfterApproved:
return nil
return s.applyRevokedAfterApproved(ctx, event)
default:
return errors.New(errors.CodeInvalidParam, "不支持的退款审批终态")
}
}
// applyRevokedAfterApproved 处理企业微信通过后撤销。
//
// 不回滚已失效的套餐权益、不取消已提交的渠道退款、也不恢复订单退款状态:这些事实在通过时
// 已经成立。系统只标记审批异常并禁止后续自动重提,交由超级管理员线下处理。
func (s *Service) applyRevokedAfterApproved(ctx context.Context, event approvalapp.TerminalDecisionEvent) error {
ctx = auditcontext.With(ctx, auditcontext.Context{CorrelationID: event.CorrelationID, ParentEventID: event.EventID})
var refund model.RefundRequest
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
target, _, err := refundapproval.ResolveRefundInTx(ctx, tx, event.BusinessID, event.InstanceID)
if err != nil {
return err
}
if err := tx.WithContext(ctx).Clauses(clause.Locking{Strength: "UPDATE"}).First(&refund, target.ID).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "锁定退款申请失败")
}
if refund.AnomalyFlag == 1 {
return nil
}
beforeRefund := refundAuditState(&refund)
result := tx.WithContext(ctx).Model(&model.RefundRequest{}).
Where("id = ? AND anomaly_flag = 0", refund.ID).
Updates(map[string]any{
"anomaly_flag": 1,
"anomaly_reason": "企业微信通过后撤销,需超级管理员线下处理",
"failure_reason": constants.RefundFailureRevokedAfterApproved,
"updated_at": event.OccurredAt,
})
if result.Error != nil {
return errors.Wrap(errors.CodeDatabaseError, result.Error, "标记退款审批异常失败")
}
if result.RowsAffected != 1 {
return nil
}
refund.AnomalyFlag = 1
refund.AnomalyReason = "企业微信通过后撤销,需超级管理员线下处理"
refund.FailureReason = constants.RefundFailureRevokedAfterApproved
return s.appendRefundAudit(ctx, tx, refund.ID, constants.AuditActionRefundAnomalyFlagged, "标记退款审批异常",
"refund:"+strconv.FormatUint(uint64(refund.ID), 10)+":revoked", beforeRefund, nil, "退款审批通过后撤销")
})
if err != nil {
return err
}
return nil
}
func (s *Service) applyApprovedDecision(ctx context.Context, event approvalapp.TerminalDecisionEvent) error {
ctx = auditcontext.With(ctx, auditcontext.Context{CorrelationID: event.CorrelationID, ParentEventID: event.EventID})
var refund model.RefundRequest
var order model.Order
changed := false
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.WithContext(ctx).Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", event.BusinessID).First(&refund).Error; err != nil {
// 业务标识解析:审批尝试记录优先,退款申请兜底(兼容尚未接入尝试模式的存量申请)。
target, attempt, err := refundapproval.ResolveRefundInTx(ctx, tx, event.BusinessID, event.InstanceID)
if err != nil {
return err
}
if err := tx.WithContext(ctx).Clauses(clause.Locking{Strength: "UPDATE"}).First(&refund, target.ID).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
}
return errors.Wrap(errors.CodeDatabaseError, err, "锁定退款申请失败")
}
if refund.ApprovalInstanceID == nil || *refund.ApprovalInstanceID != event.InstanceID {
return errors.New(errors.CodeConflict, "退款申请关联的审批实例不一致")
}
if refund.Status != model.RefundStatusPending && refund.Status != model.RefundStatusApproved {
if refund.Status != model.RefundStatusPending && refund.Status != model.RefundStatusApproved &&
refund.Status != model.RefundStatusChannelProcessing {
return errors.New(errors.CodeInvalidStatus, "退款申请状态不允许审批通过")
}
if err := tx.WithContext(ctx).Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", refund.OrderID).First(&order).Error; err != nil {
@@ -66,13 +115,21 @@ func (s *Service) applyApprovedDecision(ctx context.Context, event approvalapp.T
if err := s.preparePaymentRefundCredentials(ctx, tx, order.ID); err != nil {
return err
}
// 原路退款只登记待执行事实:退款单转入原路处理中,订单在渠道明确成功前保持已支付。
// 客户收款信息与退回原钱包在审批通过时即完成,订单同时置为已退款。
originalRoute := refund.Method == constants.RefundMethodOriginalRoute
if refund.Status == model.RefundStatusPending {
changed = true
targetStatus := model.RefundStatusApproved
if originalRoute {
targetStatus = model.RefundStatusChannelProcessing
}
result := tx.WithContext(ctx).Model(&model.RefundRequest{}).
Where("id = ? AND status = ?", refund.ID, model.RefundStatusPending).
Updates(map[string]any{
"status": model.RefundStatusApproved, "processed_at": event.OccurredAt,
"status": targetStatus, "processed_at": event.OccurredAt,
"approved_refund_amount": approvedAmount, "remark": "企业微信审批通过",
"failure_reason": "", "failure_message": "",
"updated_at": event.OccurredAt,
})
if result.Error != nil {
@@ -81,23 +138,33 @@ func (s *Service) applyApprovedDecision(ctx context.Context, event approvalapp.T
if result.RowsAffected != 1 {
return errors.New(errors.CodeConflict, "退款申请状态已变化")
}
refund.Status = targetStatus
}
switch order.PaymentStatus {
case model.PaymentStatusPaid:
changed = true
result := tx.WithContext(ctx).Model(&model.Order{}).
Where("id = ? AND payment_status = ?", order.ID, model.PaymentStatusPaid).
Updates(map[string]any{"payment_status": model.PaymentStatusRefunded, "updated_at": event.OccurredAt})
if result.Error != nil {
return errors.Wrap(errors.CodeDatabaseError, result.Error, "更新订单退款状态失败")
if !originalRoute {
switch order.PaymentStatus {
case model.PaymentStatusPaid:
changed = true
result := tx.WithContext(ctx).Model(&model.Order{}).
Where("id = ? AND payment_status = ?", order.ID, model.PaymentStatusPaid).
Updates(map[string]any{"payment_status": model.PaymentStatusRefunded, "updated_at": event.OccurredAt})
if result.Error != nil {
return errors.Wrap(errors.CodeDatabaseError, result.Error, "更新订单退款状态失败")
}
if result.RowsAffected != 1 {
return errors.New(errors.CodeConflict, "订单退款状态已变化")
}
order.PaymentStatus = model.PaymentStatusRefunded
case model.PaymentStatusRefunded:
default:
return errors.New(errors.CodeInvalidStatus, "订单状态不允许完成退款")
}
if result.RowsAffected != 1 {
return errors.New(errors.CodeConflict, "订单退款状态已变化")
} else {
if order.PaymentStatus != model.PaymentStatusPaid && order.PaymentStatus != model.PaymentStatusRefunded {
return errors.New(errors.CodeInvalidStatus, "订单状态不允许原路退款")
}
if err := s.prepareChannelRefundInTx(ctx, tx, &refund, attempt); err != nil {
return err
}
order.PaymentStatus = model.PaymentStatusRefunded
case model.PaymentStatusRefunded:
default:
return errors.New(errors.CodeInvalidStatus, "订单状态不允许完成退款")
}
if err := s.refundWalletPayment(ctx, tx, &refund, &order, approvedAmount, event.SubmitterAccountID); err != nil {
return err
@@ -112,8 +179,10 @@ func (s *Service) applyApprovedDecision(ctx context.Context, event approvalapp.T
}); err != nil {
return err
}
if err := s.appendCompletedNotification(ctx, tx, &refund); err != nil {
return err
if !originalRoute {
if err := s.appendCompletedNotification(ctx, tx, &refund); err != nil {
return err
}
}
if err := commissiondelivery.AppendRefundCommissionDeduct(ctx, tx, outbox.NewRepository(), refund.ID, refund.OrderID); err != nil {
return err
@@ -134,6 +203,17 @@ func (s *Service) applyApprovedDecision(ctx context.Context, event approvalapp.T
return nil
}
// prepareChannelRefundInTx 在企微通过事务内登记原路退款的待执行事实。
//
// 只写本地事实与可靠事件:请求号在提交时已冻结到审批尝试记录,这里把它落到退款单并转入
// 原路处理中真正的渠道调用由可靠事件驱动的事务外消费者执行ENG-TX-001
func (s *Service) prepareChannelRefundInTx(ctx context.Context, tx *gorm.DB, refund *model.RefundRequest, attempt *model.RefundRequestAttempt) error {
if s.channelRefund == nil {
return errors.New(errors.CodeInternalError, "渠道原路退款能力未配置")
}
return s.channelRefund.PrepareInTx(ctx, tx, refund, attempt)
}
func (s *Service) applyClosedDecision(ctx context.Context, event approvalapp.TerminalDecisionEvent) error {
ctx = auditcontext.With(ctx, auditcontext.Context{CorrelationID: event.CorrelationID, ParentEventID: event.EventID})
reason := map[string]string{