Files
junhong_cmp_fiber/internal/infrastructure/audit/approval.go
break ba0855d9eb 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 与行为核对,未调用真实渠道。
2026-09-14 11:55:16 +08:00

298 lines
15 KiB
Go

package audit
import (
"context"
"strconv"
"strings"
"github.com/bytedance/sonic"
"gorm.io/gorm"
approvalapp "github.com/break/junhong_cmp_fiber/internal/application/approval"
"github.com/break/junhong_cmp_fiber/internal/application/refundapproval"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/errors"
)
// WriteApproval 将通用审批状态变化及其 Integration/Outbox 引用写入统一 Audit Event。
func (w *Writer) WriteApproval(ctx context.Context, tx *gorm.DB, change approvalapp.AuditChange) error {
if change.InstanceID == 0 || change.BusinessID == 0 || change.BusinessType == "" || change.SubmitterAccountID == 0 {
return errors.New(errors.CodeInvalidParam, "通用审批审计资源不完整")
}
resources, err := approvalResources(ctx, tx, change)
if err != nil {
return err
}
result := change.Result
if result == "" {
result = constants.AuditResultSuccess
}
return w.Append(ctx, tx, AppendInput{
EventID: change.EventID, ActionCode: change.ActionCode, Summary: change.Summary,
Actor: ActorInput{Kind: change.ActorKind, ID: change.ActorID, Name: change.ActorName}, Source: change.Source,
ScopeType: constants.AuditScopePlatform, Result: result, ErrorSummary: change.ErrorSummary,
CorrelationID: change.CorrelationID, ParentEventID: change.ParentEventID,
Metadata: map[string]any{"provider": change.Provider, "decision": change.Decision}, Resources: resources,
})
}
func approvalResources(ctx context.Context, tx *gorm.DB, change approvalapp.AuditChange) ([]ResourceInput, error) {
instanceID := strconv.FormatUint(uint64(change.InstanceID), 10)
resources := []ResourceInput{{
Type: constants.AuditResourceApprovalInstance, ID: &instanceID, Key: instanceID, DisplayName: "审批实例 " + instanceID,
Relation: constants.AuditResourceRelationPrimary, Role: constants.AuditResourceRoleApprovalTarget,
IdentitySnapshot: map[string]any{
"id": change.InstanceID, "business_type": change.BusinessType, "business_id": change.BusinessID,
"submitter_account_id": change.SubmitterAccountID, "provider": change.Provider,
"external_ref": change.AfterExternalRef, "correlation_id": change.CorrelationID,
"status": statusValue(change.AfterStatus),
},
BeforeData: approvalState(change.BeforeStatus, change.BeforeExternalRef),
AfterData: approvalState(change.AfterStatus, change.AfterExternalRef),
}}
business, err := approvalBusinessResource(ctx, tx, change.BusinessType, change.BusinessID, change.InstanceID)
if err != nil {
return nil, err
}
resources = append(resources, business...)
resources = append(resources, approvalSubmitterResource(change))
seenIntegrationIDs := make(map[string]struct{}, len(change.IntegrationIDs))
for _, integrationID := range change.IntegrationIDs {
integrationID = strings.TrimSpace(integrationID)
if integrationID == "" {
continue
}
if _, exists := seenIntegrationIDs[integrationID]; exists {
continue
}
seenIntegrationIDs[integrationID] = struct{}{}
resource, err := approvalIntegrationResource(ctx, tx, integrationID)
if err != nil {
return nil, err
}
resources = append(resources, resource)
}
if strings.TrimSpace(change.OutboxEventID) != "" {
resource, err := approvalOutboxResource(ctx, tx, change.OutboxEventID)
if err != nil {
return nil, err
}
resources = append(resources, resource)
}
return resources, nil
}
// approvalBusinessResource 构造审批关联的业务资源。
//
// 退款审批的业务标识在尝试模式下指向退款审批尝试记录、存量模式下指向退款申请本身,
// 因此该分支统一经 refundapproval.ResolveRefundInTx 解析业务归属:主资源固定为解析出的
// 退款单,尝试记录存在时再追加一条引用资源,使两种语义在同一审计事件内都可追溯。
func approvalBusinessResource(ctx context.Context, tx *gorm.DB, businessType string, businessID, instanceID uint) ([]ResourceInput, error) {
id := strconv.FormatUint(uint64(businessID), 10)
switch businessType {
case constants.ApprovalBusinessTypeRefund:
refund, attempt, err := refundapproval.ResolveRefundInTx(ctx, tx, businessID, instanceID)
if err != nil {
// 提交事务内的「审批申请」审计先于 attachAttemptInstance 执行:此刻尝试记录已写入,
// 但 approval_instance_id 仍为空,共享解析器的实例一致性校验必然不命中。
// 这里只补一条尚未回写实例的尝试记录解析,其余不一致仍按解析器的冲突错误失败关闭。
refund, attempt, err = resolvePendingRefundAttempt(ctx, tx, businessID, err)
if err != nil {
return nil, err
}
}
refundID := strconv.FormatUint(uint64(refund.ID), 10)
resources := []ResourceInput{{
Type: constants.AuditResourceRefund, ID: &refundID, Key: refund.RefundNo, DisplayName: refund.RefundNo,
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalBusiness,
IdentitySnapshot: map[string]any{
"id": refund.ID, "refund_no": refund.RefundNo, "order_id": refund.OrderID, "order_no": refund.OrderNo,
"order_type": refund.OrderType, "asset_identifier": refund.AssetIdentifier, "shop_id": refund.ShopID,
"requested_refund_amount": refund.RequestedRefundAmount, "actual_received_amount": refund.ActualReceivedAmount,
"method": refund.Method, "frozen_actual_received_amount": refund.FrozenActualReceivedAmount,
"latest_attempt_id": refund.LatestAttemptID, "channel_refund_status": refund.ChannelRefundStatus,
"failure_reason": refund.FailureReason, "anomaly_flag": refund.AnomalyFlag,
"approval_instance_id": instanceID, "status": refund.Status,
},
}}
if attempt == nil {
return resources, nil
}
attemptID := strconv.FormatUint(uint64(attempt.ID), 10)
// 客户收款信息是自由文本、凭证是对象存储标识,两者都不进审计快照,只记录存在性与凭证数量。
resources = append(resources, ResourceInput{
Type: constants.AuditResourceRefundAttempt, ID: &attemptID, Key: attemptID, DisplayName: "退款审批尝试 " + attemptID,
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalBusiness,
IdentitySnapshot: map[string]any{
"id": attempt.ID, "refund_id": attempt.RefundID, "attempt_no": attempt.AttemptNo,
"method": attempt.Method, "refund_amount": attempt.RefundAmount,
"frozen_actual_received_amount": attempt.FrozenActualReceivedAmount,
"approval_instance_id": instanceID,
"channel_refund_request_no": attempt.ChannelRefundRequestNo,
"submitted_by_account_id": attempt.SubmittedByAccountID,
"customer_account_info_present": attempt.CustomerAccountInfo != "",
"customer_voucher_count": len(attempt.CustomerVoucherKeys),
"created_at": attempt.CreatedAt,
},
})
return resources, nil
case constants.ApprovalBusinessTypeOfflineRecharge:
var recharge model.AgentRechargeRecord
if err := tx.WithContext(ctx).First(&recharge, businessID).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联充值单失败")
}
return []ResourceInput{{
Type: constants.AuditResourceAgentRecharge, ID: &id, Key: recharge.RechargeNo, DisplayName: recharge.RechargeNo,
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalBusiness,
IdentitySnapshot: map[string]any{
"id": recharge.ID, "recharge_no": recharge.RechargeNo, "user_id": recharge.UserID,
"shop_id": recharge.ShopID, "agent_wallet_id": recharge.AgentWalletID, "amount": recharge.Amount,
"payment_method": recharge.PaymentMethod, "payment_channel": recharge.PaymentChannel,
"approval_instance_id": instanceID, "status": recharge.Status,
},
}}, nil
case constants.ApprovalBusinessTypeEmployeeCollection:
var attempt model.EmployeeCollectionApplicationAttempt
if err := tx.WithContext(ctx).First(&attempt, businessID).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联核销审批尝试记录失败")
}
return []ResourceInput{{
Type: constants.AuditResourceEmployeeCollectionAttempt, ID: &id,
Key: id, DisplayName: "审批尝试 " + id,
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalBusiness,
IdentitySnapshot: map[string]any{
"id": attempt.ID, "application_id": attempt.ApplicationID, "attempt_no": attempt.AttemptNo,
"paid_amount": attempt.PaidAmount, "approval_instance_id": instanceID,
},
}}, nil
case constants.ApprovalBusinessTypeAgentDistribution:
var registration model.AgentDistributionRegistration
if err := tx.WithContext(ctx).First(&registration, businessID).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联扫码注册记录失败")
}
return []ResourceInput{{
Type: constants.AuditResourceAgentDistributionRegistration, ID: &id,
Key: id, DisplayName: "扫码注册记录 " + id,
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalBusiness,
IdentitySnapshot: map[string]any{
"id": registration.ID, "parent_shop_id": registration.ParentShopID,
"status": registration.Status, "approval_instance_id": instanceID,
},
}}, nil
case constants.ApprovalBusinessTypeWithdrawalQualification:
var qualification model.WithdrawalQualification
if err := tx.WithContext(ctx).First(&qualification, businessID).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联提现资料资格版本失败")
}
return []ResourceInput{{
Type: constants.AuditResourceWithdrawalQualification, ID: &id,
Key: id, DisplayName: "提现资料资格版本 " + id,
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalBusiness,
IdentitySnapshot: map[string]any{
"id": qualification.ID, "shop_id": qualification.ShopID,
"subject_type": qualification.SubjectType, "status": qualification.Status,
"approval_instance_id": instanceID,
},
}}, nil
case constants.ApprovalBusinessTypeCommissionWithdrawal:
var attempt model.CommissionWithdrawalRequestAttempt
if err := tx.WithContext(ctx).First(&attempt, businessID).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联提现审批尝试记录失败")
}
return []ResourceInput{{
Type: constants.AuditResourceCommissionWithdrawalAttempt, ID: &id,
Key: id, DisplayName: "提现审批尝试 " + id,
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalBusiness,
IdentitySnapshot: map[string]any{
"id": attempt.ID, "request_id": attempt.RequestID, "attempt_no": attempt.AttemptNo,
"amount": attempt.Amount, "approval_instance_id": instanceID,
},
}}, nil
default:
return nil, errors.New(errors.CodeInvalidParam, "审批业务类型尚未注册审计资源")
}
}
// resolvePendingRefundAttempt 解析尚未回写审批实例的退款审批尝试记录。
//
// 只在共享解析器返回冲突时调用:审批申请审计与「尝试记录回写审批实例」同事务,
// 但审计先执行,因此 business_id 指向的尝试记录此刻 approval_instance_id 仍为空。
// 该形态由 refundapproval.ResolveRefundForApprovalRequestInTx 单独承认,其余情况
// 原样返回解析器的冲突错误,不放宽为任意未回写记录。
func resolvePendingRefundAttempt(ctx context.Context, tx *gorm.DB, businessID uint, cause error) (*model.RefundRequest, *model.RefundRequestAttempt, error) {
refund, attempt, err := refundapproval.ResolveRefundForApprovalRequestInTx(ctx, tx, businessID)
if err != nil {
return nil, nil, cause
}
return refund, attempt, nil
}
func approvalSubmitterResource(change approvalapp.AuditChange) ResourceInput {
accountID := strconv.FormatUint(uint64(change.SubmitterAccountID), 10)
identity := map[string]any{"id": change.SubmitterAccountID}
var snapshot map[string]any
if sonic.Unmarshal(change.SubmitterSnapshot, &snapshot) == nil {
identity["username"] = snapshot["account_name"]
identity["user_type"] = snapshot["user_type"]
}
displayName, _ := identity["username"].(string)
if displayName == "" {
displayName = "账号 " + accountID
}
return ResourceInput{
Type: constants.AuditResourceAccount, ID: &accountID, Key: accountID, DisplayName: displayName,
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalSubmitter,
IdentitySnapshot: identity,
}
}
func approvalIntegrationResource(ctx context.Context, tx *gorm.DB, integrationID string) (ResourceInput, error) {
var record model.IntegrationLog
if err := tx.WithContext(ctx).Where("integration_id = ?", integrationID).First(&record).Error; err != nil {
return ResourceInput{}, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联 Integration Log 失败")
}
id := strconv.FormatUint(uint64(record.ID), 10)
return ResourceInput{
Type: constants.AuditResourceIntegrationLog, ID: &id, Key: record.IntegrationID, DisplayName: record.IntegrationID,
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalIntegration,
IdentitySnapshot: map[string]any{
"integration_id": record.IntegrationID, "provider": record.Provider, "direction": record.Direction,
"operation": record.Operation, "external_id": record.ExternalID,
"resource_type": record.ResourceType, "resource_id": record.ResourceID, "resource_key": record.ResourceKey,
"correlation_id": record.CorrelationID,
},
}, nil
}
func approvalOutboxResource(ctx context.Context, tx *gorm.DB, eventID string) (ResourceInput, error) {
var event model.OutboxEvent
if err := tx.WithContext(ctx).Where("event_id = ?", eventID).First(&event).Error; err != nil {
return ResourceInput{}, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联 Outbox 事件失败")
}
id := strconv.FormatUint(uint64(event.ID), 10)
return ResourceInput{
Type: constants.AuditResourceOutboxEvent, ID: &id, Key: event.EventID, DisplayName: event.EventID,
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalOutbox,
IdentitySnapshot: map[string]any{
"event_id": event.EventID, "event_type": event.EventType, "aggregate_type": event.AggregateType,
"aggregate_id": event.AggregateID, "resource_type": event.ResourceType,
"resource_id": event.ResourceID, "business_key": event.BusinessKey,
},
}, nil
}
func approvalState(status *int, externalRef string) map[string]any {
if status == nil {
return nil
}
return map[string]any{"status": *status, "external_ref": externalRef}
}
func statusValue(status *int) any {
if status == nil {
return nil
}
return *status
}