fix: 第1批 M8、M13、M14 审批提交失败终态与退款关闭类终态定位
- 审批核心在实例进入提交失败的同一事务内写 submission_failed 决策投递与终态事件,消费入口单独放行 - 核销(4)、退款(7)、扫码注册(3)、资料资格(4)、线下充值(7)、佣金提现(5)新增“审批提交失败”终态并释放预占/冻结 - 三处恢复入口不再重放提交失败;退款关闭类终态按审批尝试定位退款单(M13) - 核销列表与详情批量返回审批提交状态;筛选、字段说明、状态名称、退款导出加入新状态 - 迁移 000239 放宽五张业务表状态约束与决策投递取值约束(测试库已执行 up/down/up) - OpenSpec Change fix-approval-submission-failure-terminal:18/26,测试部署后端到端验证与存量补数据待完成
This commit is contained in:
@@ -34,7 +34,7 @@ func NewApprovalDecisionHandler(
|
||||
return &ApprovalDecisionHandler{db: db, posting: posting, audit: audit, billCreation: billCreation}
|
||||
}
|
||||
|
||||
// Handle 幂等处理标准审批终态;只有 approved 首次入账,其他终态不修改钱包。
|
||||
// Handle 幂等处理标准审批终态;只有 approved 首次入账,其他终态(含审批提交失败)不修改钱包。
|
||||
func (h *ApprovalDecisionHandler) Handle(ctx context.Context, event approvalapp.TerminalDecisionEvent) error {
|
||||
if h == nil || h.db == nil || h.posting == nil || h.audit == nil {
|
||||
return errors.New(errors.CodeInternalError, "员工线下代充值审批终态能力未配置")
|
||||
@@ -70,6 +70,12 @@ func (h *ApprovalDecisionHandler) Handle(ctx context.Context, event approvalapp.
|
||||
return h.closeOfflineRecharge(ctx, tx, &record, event, constants.RechargeStatusClosed, "企业微信审批已删除")
|
||||
case constants.ApprovalDecisionRevokedAfterApproved:
|
||||
return nil
|
||||
case constants.ApprovalDecisionSubmissionFailed:
|
||||
reason, failed, err := approvalapp.ConfirmSubmissionFailed(ctx, tx, event.InstanceID)
|
||||
if err != nil || !failed {
|
||||
return err
|
||||
}
|
||||
return h.closeOfflineRecharge(ctx, tx, &record, event, constants.RechargeStatusSubmissionFailed, reason)
|
||||
default:
|
||||
return errors.New(errors.CodeInvalidParam, "不支持的线下代充值审批终态")
|
||||
}
|
||||
|
||||
44
internal/application/approval/submission_failure.go
Normal file
44
internal/application/approval/submission_failure.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package approval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
)
|
||||
|
||||
// ConfirmSubmissionFailed 在业务消费事务内锁定审批实例并确认其仍为“提交失败”,返回可对外展示的失败原因。
|
||||
// 实例已不是提交失败(例如被恢复重放)时 ok 为 false,业务消费者应不改变业务单。
|
||||
// 原因只返回固定白名单文案,禁止透传企微原文或内部错误。
|
||||
func ConfirmSubmissionFailed(ctx context.Context, tx *gorm.DB, instanceID uint) (string, bool, error) {
|
||||
var row struct {
|
||||
Status int `gorm:"column:status"`
|
||||
LastError string `gorm:"column:last_error"`
|
||||
}
|
||||
result := tx.WithContext(ctx).Raw(
|
||||
`SELECT ai.status, COALESCE(wc.last_error, '') AS last_error
|
||||
FROM tb_approval_instance ai
|
||||
LEFT JOIN tb_wecom_approval_context wc ON wc.approval_instance_id = ai.id
|
||||
WHERE ai.id = ? FOR UPDATE OF ai`, instanceID).Scan(&row)
|
||||
if result.Error != nil {
|
||||
return "", false, errors.Wrap(errors.CodeDatabaseError, result.Error, "锁定提交失败审批实例失败")
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return "", false, errors.New(errors.CodeNotFound, "审批实例不存在")
|
||||
}
|
||||
if row.Status != constants.ApprovalStatusSubmissionFailed {
|
||||
return "", false, nil
|
||||
}
|
||||
return SubmissionFailureReason(row.LastError), true, nil
|
||||
}
|
||||
|
||||
// SubmissionFailureReason 把企微提交失败原文转换为稳定白名单文案。
|
||||
func SubmissionFailureReason(lastError string) string {
|
||||
if strings.TrimSpace(lastError) == "" {
|
||||
return constants.ApprovalSubmissionFailedStatusName
|
||||
}
|
||||
return constants.ApprovalSubmissionFailedReason
|
||||
}
|
||||
@@ -67,6 +67,14 @@ func (h *QualificationApprovalHandler) Handle(ctx context.Context, event approva
|
||||
constants.ApprovalDecisionDeleted,
|
||||
constants.ApprovalDecisionRevokedAfterApproved:
|
||||
return h.applyRejected(ctx, tx, &version, shop, before, event)
|
||||
case constants.ApprovalDecisionSubmissionFailed:
|
||||
reason, failed, err := approvalapp.ConfirmSubmissionFailed(ctx, tx, event.InstanceID)
|
||||
if err != nil || !failed {
|
||||
return err
|
||||
}
|
||||
return h.closeVersion(ctx, tx, &version, shop, before, event,
|
||||
constants.WithdrawalQualificationStatusSubmissionFailed, constants.AuditActionWithdrawalQualificationRejected,
|
||||
"submission_failed", "提现资料资格审批提交失败:"+reason)
|
||||
default:
|
||||
return errors.New(errors.CodeInvalidParam, "不支持的提现资料资格审批终态")
|
||||
}
|
||||
@@ -169,26 +177,42 @@ func (h *QualificationApprovalHandler) applyRejected(
|
||||
shop *model.Shop,
|
||||
before map[string]any,
|
||||
event approvalapp.TerminalDecisionEvent,
|
||||
) error {
|
||||
return h.closeVersion(ctx, tx, version, shop, before, event,
|
||||
constants.WithdrawalQualificationStatusRejected, constants.AuditActionWithdrawalQualificationRejected,
|
||||
"rejected", "企业微信未通过提现资料资格")
|
||||
}
|
||||
|
||||
// closeVersion 以待审批状态条件更新把资料版本置为未生效终态(已驳回或审批提交失败),不影响其他版本。
|
||||
func (h *QualificationApprovalHandler) closeVersion(
|
||||
ctx context.Context,
|
||||
tx *gorm.DB,
|
||||
version *model.WithdrawalQualification,
|
||||
shop *model.Shop,
|
||||
before map[string]any,
|
||||
event approvalapp.TerminalDecisionEvent,
|
||||
targetStatus int,
|
||||
actionCode, eventSuffix, summary string,
|
||||
) error {
|
||||
now := time.Now().UTC()
|
||||
result := tx.WithContext(ctx).Model(&model.WithdrawalQualification{}).
|
||||
Where("id = ? AND status = ?", version.ID, constants.WithdrawalQualificationStatusPending).
|
||||
Updates(map[string]any{
|
||||
"status": constants.WithdrawalQualificationStatusRejected,
|
||||
"status": targetStatus,
|
||||
"decided_at": now, "updater": 0,
|
||||
})
|
||||
if result.Error != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, result.Error, "标记提现资料资格版本已驳回失败")
|
||||
return errors.Wrap(errors.CodeDatabaseError, result.Error, "结束提现资料资格版本失败")
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
return errors.New(errors.CodeConflict, "提现资料资格版本状态已变化")
|
||||
}
|
||||
version.Status = constants.WithdrawalQualificationStatusRejected
|
||||
version.Status = targetStatus
|
||||
version.DecidedAt = &now
|
||||
return h.audit.WriteDistributionWithdrawal(ctx, tx, AuditChange{
|
||||
EventID: "withdrawal-qualification:" + uintText(version.ID) + ":rejected",
|
||||
ActionCode: constants.AuditActionWithdrawalQualificationRejected,
|
||||
Summary: "企业微信未通过提现资料资格",
|
||||
EventID: "withdrawal-qualification:" + uintText(version.ID) + ":" + eventSuffix,
|
||||
ActionCode: actionCode,
|
||||
Summary: summary,
|
||||
CorrelationID: event.CorrelationID, Qualification: version, Shop: shop,
|
||||
BeforeData: before, AfterData: qualificationAuditSnapshot(version),
|
||||
})
|
||||
|
||||
@@ -96,8 +96,8 @@ func (s *RegistrationService) RecoverApproval(ctx context.Context, id uint) erro
|
||||
branch = "unknown"
|
||||
recoveryErr = s.recovery.EnqueueUnknownConfirm(ctx, tx, instanceID)
|
||||
} else if instance.Status == constants.ApprovalStatusSubmissionFailed && wc.SubmissionStatus == constants.WeComSubmissionStatusFailed {
|
||||
branch = "replay"
|
||||
_, recoveryErr = s.recovery.RecoverSubmissionEvent(ctx, tx, instanceID)
|
||||
// 提交失败已由决策终止注册记录,不再重放。
|
||||
return errors.New(errors.CodeConflict, constants.ApprovalSubmissionFailedNotRecoverableMessage)
|
||||
} else if instance.Status == constants.ApprovalStatusSubmitting || instance.Status == constants.ApprovalStatusPending || wc.SubmissionStatus == constants.WeComSubmissionStatusReady || wc.SubmissionStatus == constants.WeComSubmissionStatusSending {
|
||||
} else {
|
||||
return errors.New(errors.CodeConflict, "当前审批提交状态不允许恢复")
|
||||
|
||||
@@ -74,6 +74,14 @@ func (h *DistributionApprovalHandler) Handle(ctx context.Context, event approval
|
||||
case constants.ApprovalDecisionRevokedAfterApproved:
|
||||
// 注册记录无已建立的对外资金事实;通过后撤销按驳回处理并保留渠道决策痕迹。
|
||||
return h.applyRejected(ctx, tx, registration, event)
|
||||
case constants.ApprovalDecisionSubmissionFailed:
|
||||
reason, failed, err := approvalapp.ConfirmSubmissionFailed(ctx, tx, event.InstanceID)
|
||||
if err != nil || !failed {
|
||||
return err
|
||||
}
|
||||
return h.closeRegistration(ctx, tx, registration, event,
|
||||
constants.AgentDistributionRegistrationStatusSubmissionFailed, reason,
|
||||
"submission_failed", "扫码注册审批提交失败,未创建任何实体")
|
||||
default:
|
||||
return errors.New(errors.CodeInvalidParam, "不支持的代理分销注册审批终态")
|
||||
}
|
||||
@@ -190,29 +198,42 @@ func (h *DistributionApprovalHandler) applyRejected(
|
||||
tx *gorm.DB,
|
||||
registration *model.AgentDistributionRegistration,
|
||||
event approvalapp.TerminalDecisionEvent,
|
||||
) error {
|
||||
return h.closeRegistration(ctx, tx, registration, event,
|
||||
constants.AgentDistributionRegistrationStatusRejected, rejectionReason(event.Decision),
|
||||
"rejected", "企业微信未通过扫码注册,未创建任何实体")
|
||||
}
|
||||
|
||||
// closeRegistration 以待审批状态条件更新把注册记录置为不创建实体的终态(已驳回或审批提交失败)。
|
||||
func (h *DistributionApprovalHandler) closeRegistration(
|
||||
ctx context.Context,
|
||||
tx *gorm.DB,
|
||||
registration *model.AgentDistributionRegistration,
|
||||
event approvalapp.TerminalDecisionEvent,
|
||||
targetStatus int,
|
||||
reason, eventSuffix, summary string,
|
||||
) error {
|
||||
now := time.Now().UTC()
|
||||
reason := rejectionReason(event.Decision)
|
||||
result := tx.WithContext(ctx).Model(&model.AgentDistributionRegistration{}).
|
||||
Where("id = ? AND status = ?", registration.ID, constants.AgentDistributionRegistrationStatusPending).
|
||||
Updates(map[string]any{
|
||||
"status": constants.AgentDistributionRegistrationStatusRejected,
|
||||
"status": targetStatus,
|
||||
"reject_reason": reason, "decided_at": now, "updater": 0,
|
||||
})
|
||||
if result.Error != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, result.Error, "标记扫码注册记录已驳回失败")
|
||||
return errors.Wrap(errors.CodeDatabaseError, result.Error, "结束扫码注册记录失败")
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
return errors.New(errors.CodeConflict, "扫码注册记录状态已变化")
|
||||
}
|
||||
before := registration.Status
|
||||
registration.Status = constants.AgentDistributionRegistrationStatusRejected
|
||||
registration.Status = targetStatus
|
||||
registration.RejectReason = reason
|
||||
registration.DecidedAt = &now
|
||||
return h.audit.WriteDistributionWithdrawal(ctx, tx, AuditChange{
|
||||
EventID: "agent-distribution:" + uintText(registration.ID) + ":rejected",
|
||||
EventID: "agent-distribution:" + uintText(registration.ID) + ":" + eventSuffix,
|
||||
ActionCode: constants.AuditActionAgentDistributionRegistrationRejected,
|
||||
Summary: "企业微信未通过扫码注册,未创建任何实体",
|
||||
Summary: summary,
|
||||
CorrelationID: event.CorrelationID, Registration: registration,
|
||||
BeforeData: map[string]any{"status": before},
|
||||
AfterData: registrationAuditSnapshot(registration),
|
||||
|
||||
@@ -145,8 +145,8 @@ func (s *WithdrawalService) submit(
|
||||
if request.ShopID != submitter.ShopID {
|
||||
return errors.New(errors.CodeNotFound, "提现申请不存在")
|
||||
}
|
||||
if request.Status != constants.WithdrawalStatusRejected {
|
||||
return errors.New(errors.CodeConflict, "仅已被驳回的提现申请可重提")
|
||||
if !isWithdrawalResubmittable(request.Status) {
|
||||
return errors.New(errors.CodeConflict, "仅已被驳回或审批提交失败的提现申请可重提")
|
||||
}
|
||||
if request.ApprovalInstanceID == nil {
|
||||
return errors.New(errors.CodeConflict, "存量提现申请不支持企业微信重提")
|
||||
@@ -579,7 +579,20 @@ func nextWithdrawalAttemptNo(ctx context.Context, tx *gorm.DB, requestID uint) (
|
||||
return row.MaxAttemptNo + 1, nil
|
||||
}
|
||||
|
||||
// updateWithdrawalRequestForResubmit 以已驳回状态条件更新申请为最新尝试的镜像。
|
||||
// withdrawalResubmittableStatuses 允许重提的提现状态:已驳回与审批提交失败,两者冻结均已释放。
|
||||
var withdrawalResubmittableStatuses = []int{constants.WithdrawalStatusRejected, constants.WithdrawalStatusSubmissionFailed}
|
||||
|
||||
// isWithdrawalResubmittable 判断提现申请当前状态是否允许重提。
|
||||
func isWithdrawalResubmittable(status int) bool {
|
||||
for _, allowed := range withdrawalResubmittableStatuses {
|
||||
if status == allowed {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// updateWithdrawalRequestForResubmit 以已驳回或审批提交失败状态条件更新申请为最新尝试的镜像。
|
||||
func updateWithdrawalRequestForResubmit(
|
||||
ctx context.Context,
|
||||
tx *gorm.DB,
|
||||
@@ -591,7 +604,7 @@ func updateWithdrawalRequestForResubmit(
|
||||
accountInfo []byte,
|
||||
) error {
|
||||
result := tx.WithContext(ctx).Model(&model.CommissionWithdrawalRequest{}).
|
||||
Where("id = ? AND status = ?", request.ID, constants.WithdrawalStatusRejected).
|
||||
Where("id = ? AND status IN ?", request.ID, withdrawalResubmittableStatuses).
|
||||
Updates(map[string]any{
|
||||
"amount": input.Amount, "fee": fee, "fee_rate": policy.FeeRate, "actual_amount": actualAmount,
|
||||
"withdrawal_method": input.WithdrawalMethod, "account_info": accountInfo,
|
||||
|
||||
@@ -83,6 +83,16 @@ func (h *WithdrawalApprovalHandler) Handle(ctx context.Context, event approvalap
|
||||
return h.applyClosed(ctx, tx, request, &attempt, event)
|
||||
case constants.ApprovalDecisionRevokedAfterApproved:
|
||||
return h.applyRevoked(ctx, tx, request, &attempt, event)
|
||||
case constants.ApprovalDecisionSubmissionFailed:
|
||||
reason, failed, err := approvalapp.ConfirmSubmissionFailed(ctx, tx, event.InstanceID)
|
||||
if err != nil || !failed {
|
||||
return err
|
||||
}
|
||||
return h.closeAttempt(ctx, tx, request, &attempt, event, withdrawalCloseOutcome{
|
||||
status: constants.WithdrawalStatusSubmissionFailed, reason: reason, eventSuffix: "submission_failed",
|
||||
summary: "佣金提现审批提交失败,已释放本次尝试冻结余额",
|
||||
releaseRemark: "审批提交失败,释放提现冻结,单号:",
|
||||
})
|
||||
default:
|
||||
return errors.New(errors.CodeInvalidParam, "不支持的提现申请审批终态")
|
||||
}
|
||||
@@ -163,6 +173,32 @@ func (h *WithdrawalApprovalHandler) applyClosed(
|
||||
request *model.CommissionWithdrawalRequest,
|
||||
attempt *model.CommissionWithdrawalRequestAttempt,
|
||||
event approvalapp.TerminalDecisionEvent,
|
||||
) error {
|
||||
return h.closeAttempt(ctx, tx, request, attempt, event, withdrawalCloseOutcome{
|
||||
status: constants.WithdrawalStatusRejected, reason: rejectionReason(event.Decision), eventSuffix: "closed",
|
||||
summary: "企业微信未通过佣金提现,已释放本次尝试冻结余额",
|
||||
releaseRemark: "企业微信未通过,释放提现冻结,单号:",
|
||||
})
|
||||
}
|
||||
|
||||
// withdrawalCloseOutcome 描述提现尝试未通过时的终态、原因、审计与释放流水文案。
|
||||
type withdrawalCloseOutcome struct {
|
||||
status int
|
||||
reason string
|
||||
eventSuffix string
|
||||
summary string
|
||||
releaseRemark string
|
||||
}
|
||||
|
||||
// closeAttempt 在同一事务内仅一次释放本次尝试冻结、写释放流水,并把申请从待审核置为未通过终态。
|
||||
// 幂等守卫为「尝试已结算时间仍为空」的条件更新且影响行数为 1。
|
||||
func (h *WithdrawalApprovalHandler) closeAttempt(
|
||||
ctx context.Context,
|
||||
tx *gorm.DB,
|
||||
request *model.CommissionWithdrawalRequest,
|
||||
attempt *model.CommissionWithdrawalRequestAttempt,
|
||||
event approvalapp.TerminalDecisionEvent,
|
||||
outcome withdrawalCloseOutcome,
|
||||
) error {
|
||||
if attempt.ReleasedAt != nil {
|
||||
return nil
|
||||
@@ -186,36 +222,36 @@ func (h *WithdrawalApprovalHandler) applyClosed(
|
||||
if !ok {
|
||||
return errors.New(errors.CodeConflict, "提现冻结余额与尝试记录不一致,请人工核对")
|
||||
}
|
||||
reason := rejectionReason(event.Decision)
|
||||
reason := outcome.reason
|
||||
result := tx.WithContext(ctx).Model(&model.CommissionWithdrawalRequest{}).
|
||||
Where("id = ? AND status = ?", request.ID, constants.WithdrawalStatusPending).
|
||||
Updates(map[string]any{
|
||||
"status": constants.WithdrawalStatusRejected,
|
||||
"status": outcome.status,
|
||||
"processed_at": now,
|
||||
"reject_reason": reason,
|
||||
"updater": 0,
|
||||
})
|
||||
if result.Error != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, result.Error, "标记提现申请已驳回失败")
|
||||
return errors.Wrap(errors.CodeDatabaseError, result.Error, "结束提现申请失败")
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
return errors.New(errors.CodeConflict, "提现申请状态已变化")
|
||||
}
|
||||
frozenBefore := wallet.FrozenBalance + attempt.Amount
|
||||
wallet.FrozenBalance = frozenBefore - attempt.Amount
|
||||
transaction, err := recordWithdrawalReleaseTransaction(ctx, tx, wallet, request, attempt, frozenBefore)
|
||||
transaction, err := recordWithdrawalReleaseTransaction(ctx, tx, wallet, request, attempt, outcome.releaseRemark)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
attempt.ReleasedAt = &now
|
||||
before := map[string]any{"status": constants.WithdrawalStatusPending, "frozen_balance": frozenBefore}
|
||||
request.Status = constants.WithdrawalStatusRejected
|
||||
request.Status = outcome.status
|
||||
request.ProcessedAt = &now
|
||||
request.RejectReason = reason
|
||||
return h.audit.WriteDistributionWithdrawal(ctx, tx, AuditChange{
|
||||
EventID: "commission-withdrawal:" + uintText(request.ID) + ":attempt:" + intText(attempt.AttemptNo) + ":closed",
|
||||
EventID: "commission-withdrawal:" + uintText(request.ID) + ":attempt:" + intText(attempt.AttemptNo) + ":" + outcome.eventSuffix,
|
||||
ActionCode: constants.AuditActionCommissionWithdrawalAttemptClosed,
|
||||
Summary: "企业微信未通过佣金提现,已释放本次尝试冻结余额",
|
||||
Summary: outcome.summary,
|
||||
CorrelationID: event.CorrelationID, Withdrawal: request, Attempt: attempt,
|
||||
Wallet: wallet, Transaction: transaction,
|
||||
BeforeData: before, AfterData: withdrawalAuditSnapshot(request, attempt, wallet),
|
||||
@@ -336,16 +372,16 @@ func recordWithdrawalDeductTransaction(
|
||||
return transaction, nil
|
||||
}
|
||||
|
||||
// recordWithdrawalReleaseTransaction 写入驳回时的钱包流水,仅冻结余额减少。
|
||||
// recordWithdrawalReleaseTransaction 写入未通过(驳回或审批提交失败)时的钱包流水,仅冻结余额减少。
|
||||
func recordWithdrawalReleaseTransaction(
|
||||
ctx context.Context,
|
||||
tx *gorm.DB,
|
||||
wallet *model.AgentWallet,
|
||||
request *model.CommissionWithdrawalRequest,
|
||||
attempt *model.CommissionWithdrawalRequestAttempt,
|
||||
frozenBefore int64,
|
||||
remarkPrefix string,
|
||||
) (*model.AgentWalletTransaction, error) {
|
||||
remark := "企业微信未通过,释放提现冻结,单号:" + request.WithdrawalNo
|
||||
remark := remarkPrefix + request.WithdrawalNo
|
||||
refType := constants.ReferenceTypeWithdrawal
|
||||
refID := request.ID
|
||||
transaction := &model.AgentWalletTransaction{
|
||||
@@ -360,6 +396,5 @@ func recordWithdrawalReleaseTransaction(
|
||||
if err := tx.WithContext(ctx).Create(transaction).Error; err != nil {
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "创建提现释放钱包流水失败")
|
||||
}
|
||||
_ = frozenBefore
|
||||
return transaction, nil
|
||||
}
|
||||
|
||||
@@ -161,8 +161,8 @@ func (s *ApplicationService) RecoverApproval(ctx context.Context, applicationID
|
||||
action = "unknown"
|
||||
recoveryErr = s.recovery.EnqueueUnknownConfirm(ctx, tx, instance.ID)
|
||||
} else if instance.Status == constants.ApprovalStatusSubmissionFailed && wc.SubmissionStatus == constants.WeComSubmissionStatusFailed {
|
||||
action = "replay"
|
||||
_, recoveryErr = s.recovery.RecoverSubmissionEvent(ctx, tx, instance.ID)
|
||||
// 提交失败已由决策终止业务单,重放会造成“业务单终态、企微又生成审批”的分裂。
|
||||
return errors.New(errors.CodeConflict, constants.ApprovalSubmissionFailedNotRecoverableMessage)
|
||||
} else if instance.Status != constants.ApprovalStatusSubmitting && instance.Status != constants.ApprovalStatusPending && wc.SubmissionStatus != constants.WeComSubmissionStatusReady && wc.SubmissionStatus != constants.WeComSubmissionStatusSending {
|
||||
return errors.New(errors.CodeConflict, "当前审批提交状态不允许恢复")
|
||||
}
|
||||
|
||||
@@ -70,6 +70,13 @@ func (h *ApprovalDecisionHandler) Handle(ctx context.Context, event approvalapp.
|
||||
constants.EmployeeCollectionApplicationStatusRevoked, "企业微信审批已删除")
|
||||
case constants.ApprovalDecisionRevokedAfterApproved:
|
||||
return h.applyRevoked(ctx, tx, application, &attempt, event)
|
||||
case constants.ApprovalDecisionSubmissionFailed:
|
||||
reason, failed, err := approvalapp.ConfirmSubmissionFailed(ctx, tx, event.InstanceID)
|
||||
if err != nil || !failed {
|
||||
return err
|
||||
}
|
||||
return h.applyClosed(ctx, tx, application, &attempt, event,
|
||||
constants.EmployeeCollectionApplicationStatusSubmissionFailed, reason)
|
||||
default:
|
||||
return errors.New(errors.CodeInvalidParam, "不支持的核销申请审批终态")
|
||||
}
|
||||
@@ -138,7 +145,7 @@ func (h *ApprovalDecisionHandler) applyApproved(
|
||||
})
|
||||
}
|
||||
|
||||
// applyClosed 处理最终驳回与渠道撤销、删除:释放全部预占并把申请置为对应终态。
|
||||
// applyClosed 处理最终驳回、渠道撤销、删除与审批提交失败:释放全部预占并把申请置为对应终态。
|
||||
func (h *ApprovalDecisionHandler) applyClosed(
|
||||
ctx context.Context,
|
||||
tx *gorm.DB,
|
||||
@@ -168,7 +175,8 @@ func (h *ApprovalDecisionHandler) applyClosed(
|
||||
}
|
||||
}
|
||||
terminalReason := ""
|
||||
if targetStatus == constants.EmployeeCollectionApplicationStatusRevoked {
|
||||
if targetStatus == constants.EmployeeCollectionApplicationStatusRevoked ||
|
||||
targetStatus == constants.EmployeeCollectionApplicationStatusSubmissionFailed {
|
||||
terminalReason = reason
|
||||
}
|
||||
result := tx.WithContext(ctx).Model(&model.EmployeeCollectionApplication{}).
|
||||
@@ -196,10 +204,14 @@ func (h *ApprovalDecisionHandler) applyClosed(
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
summary := "企业微信审批未通过,核销申请预占已释放"
|
||||
if targetStatus == constants.EmployeeCollectionApplicationStatusSubmissionFailed {
|
||||
summary = "审批提交失败,核销申请终止,预占已释放"
|
||||
}
|
||||
return h.audit.WriteEmployeeCollectionApplication(ctx, tx, ApplicationAudit{
|
||||
EventID: closedEventID,
|
||||
ActionCode: constants.AuditActionEmployeeCollectionApplicationRejected,
|
||||
Summary: "企业微信审批未通过,核销申请预占已释放",
|
||||
Summary: summary,
|
||||
Application: application, Attempt: attempt, Allocations: allocations, Bills: bills,
|
||||
BeforeData: map[string]any{"status": before},
|
||||
AfterData: applicationAuditSnapshot(application), CorrelationID: event.CorrelationID,
|
||||
@@ -495,6 +507,8 @@ func decisionEventSuffix(decision string) string {
|
||||
return "cancelled"
|
||||
case constants.ApprovalDecisionDeleted:
|
||||
return "deleted"
|
||||
case constants.ApprovalDecisionSubmissionFailed:
|
||||
return "submission_failed"
|
||||
default:
|
||||
return "closed"
|
||||
}
|
||||
|
||||
@@ -103,17 +103,11 @@ func (s *RecoveryService) Execute(ctx context.Context, refundID uint) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if instance.Status != constants.ApprovalStatusSubmissionFailed || context.SubmissionStatus != constants.WeComSubmissionStatusFailed {
|
||||
return errors.New(errors.CodeConflict, "当前审批提交状态不允许恢复")
|
||||
if instance.Status == constants.ApprovalStatusSubmissionFailed && context.SubmissionStatus == constants.WeComSubmissionStatusFailed {
|
||||
// 提交失败已由决策终止退款单,不再重放;须在卡管重新发起。
|
||||
return errors.New(errors.CodeConflict, constants.ApprovalSubmissionFailedNotRecoverableMessage)
|
||||
}
|
||||
branch = "replay"
|
||||
if s.audit != nil {
|
||||
if err := s.audit.WriteRecoveryRequest(ctx, tx, &instance, actorID, branch); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err = s.recovery.RecoverSubmissionEvent(ctx, tx, instance.ID)
|
||||
return err
|
||||
return errors.New(errors.CodeConflict, "当前审批提交状态不允许恢复")
|
||||
})
|
||||
}
|
||||
func fillMissingSnapshot(instance *model.ApprovalInstance, attempt *model.RefundRequestAttempt) ([]string, error) {
|
||||
|
||||
@@ -87,9 +87,11 @@ func NormalizeApplicationInput(input ApplicationInput, acting bool) (NormalizedA
|
||||
}
|
||||
|
||||
// ValidateApplicationResubmit 校验申请当前状态允许修改并重提。
|
||||
// 只有企业微信最终驳回的申请可以修改重提;已通过、审批中与异常终态一律拒绝。
|
||||
// 只有企业微信最终驳回或审批提交失败的申请可以修改重提;已通过、审批中与异常终态一律拒绝。
|
||||
func ValidateApplicationResubmit(status int) error {
|
||||
if status == constants.EmployeeCollectionApplicationStatusRejected {
|
||||
// 审批提交失败与驳回同属“预占已释放、可修改后重提”的终态。
|
||||
if status == constants.EmployeeCollectionApplicationStatusRejected ||
|
||||
status == constants.EmployeeCollectionApplicationStatusSubmissionFailed {
|
||||
return nil
|
||||
}
|
||||
return errors.New(errors.CodeEmployeeCollectionApplicationStatusInvalid)
|
||||
|
||||
@@ -251,7 +251,7 @@ func formatRefundProcessingStatus(status int, commissionDeducted, assetReset boo
|
||||
switch status {
|
||||
case model.RefundStatusPending, model.RefundStatusReturned:
|
||||
return "待审批"
|
||||
case model.RefundStatusRejected:
|
||||
case model.RefundStatusRejected, model.RefundStatusSubmissionFailed:
|
||||
return "无需处理"
|
||||
case model.RefundStatusApproved:
|
||||
if commissionDeducted && assetReset {
|
||||
|
||||
@@ -19,7 +19,7 @@ type AgentDistributionRegistration struct {
|
||||
City string `gorm:"column:city;type:varchar(50);not null;default:'';comment:城市快照" json:"city"`
|
||||
District string `gorm:"column:district;type:varchar(50);not null;default:'';comment:区县快照" json:"district"`
|
||||
Address string `gorm:"column:address;type:varchar(255);not null;default:'';comment:详细地址快照" json:"address"`
|
||||
Status int `gorm:"column:status;type:smallint;not null;default:0;comment:状态 0-待审批 1-已通过 2-已驳回" json:"status"`
|
||||
Status int `gorm:"column:status;type:smallint;not null;default:0;comment:状态 0-待审批 1-已通过 2-已驳回 3-审批提交失败" json:"status"`
|
||||
ApprovalInstanceID *uint `gorm:"column:approval_instance_id;comment:关联的通用审批实例ID" json:"approval_instance_id,omitempty"`
|
||||
RejectReason string `gorm:"column:reject_reason;type:varchar(500);not null;default:'';comment:企业微信驳回原因" json:"reject_reason"`
|
||||
DecidedAt *time.Time `gorm:"column:decided_at;type:timestamptz;comment:审批终态到达时间" json:"decided_at,omitempty"`
|
||||
|
||||
@@ -20,7 +20,7 @@ type CreateAgentDistributionRegistrationReq struct {
|
||||
// 仅返回注册记录标识与待审批状态,不返回任何账号凭证或审批实例明细。
|
||||
type CreateAgentDistributionRegistrationResp struct {
|
||||
ID uint `json:"id" description:"待审批注册记录ID"`
|
||||
Status int `json:"status" description:"注册记录状态 (0:待审批, 1:已通过, 2:已驳回)"`
|
||||
Status int `json:"status" description:"注册记录状态 (0:待审批, 1:已通过, 2:已驳回, 3:审批提交失败)"`
|
||||
StatusName string `json:"status_name" description:"状态名称(中文)"`
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ type SubmitWithdrawalQualificationReq struct {
|
||||
// SubmitWithdrawalQualificationResp 提现资料资格提交响应。
|
||||
type SubmitWithdrawalQualificationResp struct {
|
||||
ID uint `json:"id" description:"资料版本ID"`
|
||||
Status int `json:"status" description:"资料版本状态 (0:待审批, 1:已通过有效, 2:已驳回, 3:已失效)"`
|
||||
Status int `json:"status" description:"资料版本状态 (0:待审批, 1:已通过有效, 2:已驳回, 3:已失效, 4:审批提交失败)"`
|
||||
StatusName string `json:"status_name" description:"状态名称(中文)"`
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ type WithdrawalQualificationListReq struct {
|
||||
ShopID uint `json:"-" params:"shop_id" path:"shop_id" validate:"required" required:"true" description:"店铺ID(路径参数,必填;查询前校验当前账号对该店铺的数据范围)"`
|
||||
Page int `query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码(默认1)"`
|
||||
PageSize int `query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页数量(默认20,最大100)"`
|
||||
Status *int `query:"status" validate:"omitempty,oneof=0 1 2 3" enum:"0,1,2,3" description:"资料版本状态 (0:待审批, 1:已通过有效, 2:已驳回, 3:已失效)"`
|
||||
Status *int `query:"status" validate:"omitempty,oneof=0 1 2 3 4" enum:"0,1,2,3,4" description:"资料版本状态 (0:待审批, 1:已通过有效, 2:已驳回, 3:已失效, 4:审批提交失败)"`
|
||||
}
|
||||
|
||||
// WithdrawalQualificationItem 提现资料资格版本项。
|
||||
@@ -83,7 +83,7 @@ type WithdrawalQualificationItem struct {
|
||||
ShopFrontFileKey string `json:"shop_front_file_key,omitempty" description:"门头照附件对象存储 Key"`
|
||||
InvoiceFileKey string `json:"invoice_file_key,omitempty" description:"发票附件对象存储 Key"`
|
||||
InvoiceTitle string `json:"invoice_title,omitempty" description:"发票抬头"`
|
||||
Status int `json:"status" description:"状态 (0:待审批, 1:已通过有效, 2:已驳回, 3:已失效)"`
|
||||
Status int `json:"status" description:"状态 (0:待审批, 1:已通过有效, 2:已驳回, 3:已失效, 4:审批提交失败)"`
|
||||
StatusName string `json:"status_name" description:"状态名称(中文)"`
|
||||
InvalidReason string `json:"invalid_reason,omitempty" description:"失效或作废原因"`
|
||||
InvalidatedAt string `json:"invalidated_at,omitempty" description:"失效时间"`
|
||||
@@ -158,7 +158,7 @@ type ShopWithdrawalRequestDetailResp struct {
|
||||
type AgentDistributionRegistrationListReq struct {
|
||||
Page int `query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码(默认1)"`
|
||||
PageSize int `query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页数量(默认20,最大100)"`
|
||||
Status *int `query:"status" validate:"omitempty,oneof=0 1 2" enum:"0,1,2" description:"注册业务状态 (0:待审批, 1:已通过, 2:已驳回)"`
|
||||
Status *int `query:"status" validate:"omitempty,oneof=0 1 2 3" enum:"0,1,2,3" description:"注册业务状态 (0:待审批, 1:已通过, 2:已驳回, 3:审批提交失败)"`
|
||||
StartTime string `query:"start_time" description:"申请开始时间(RFC3339,闭区间)"`
|
||||
EndTime string `query:"end_time" description:"申请结束时间(RFC3339,闭区间)"`
|
||||
DecidedStartTime string `query:"decided_start_time" description:"决定开始时间(RFC3339,闭区间)"`
|
||||
@@ -173,7 +173,7 @@ type AgentDistributionRegistrationListReq struct {
|
||||
// 该投影不包含密码哈希、验证码及企业微信内部响应。
|
||||
type AgentDistributionRegistrationItem struct {
|
||||
ID uint `json:"id" description:"注册申请ID"`
|
||||
Status int `json:"status" description:"注册业务状态 (0:待审批, 1:已通过, 2:已驳回)"`
|
||||
Status int `json:"status" description:"注册业务状态 (0:待审批, 1:已通过, 2:已驳回, 3:审批提交失败)"`
|
||||
StatusName string `json:"status_name" description:"注册业务状态名称"`
|
||||
ShopName string `json:"shop_name" description:"申请店铺名称"`
|
||||
ShopCode string `json:"shop_code" description:"申请店铺编号"`
|
||||
|
||||
@@ -23,7 +23,7 @@ type AgentRechargeOnlineResponse struct {
|
||||
RechargeSourceName string `json:"recharge_source_name" description:"充值来源名称(中文)"`
|
||||
Amount int64 `json:"amount" description:"在线充值金额(分),范围10000分~100000000分"`
|
||||
QRContent string `json:"qr_content" description:"支付链接(HTTPS URL),由前端渲染二维码"`
|
||||
Status int `json:"status" description:"状态 (1:待支付, 2:已支付, 3:已完成, 4:已关闭, 5:已退款, 6:已驳回)"`
|
||||
Status int `json:"status" description:"状态 (1:待支付, 2:已支付, 3:已完成, 4:已关闭, 5:已退款, 6:已驳回, 7:审批提交失败)"`
|
||||
StatusName string `json:"status_name" description:"状态名称(中文)"`
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ type AgentRechargePaymentStatusResponse struct {
|
||||
RechargeNo string `json:"recharge_no" description:"充值单号(ARCH前缀)"`
|
||||
RechargeSource string `json:"recharge_source" description:"充值来源 (platform_offline:平台线下代充, agent_online:代理在线自充)"`
|
||||
RechargeSourceName string `json:"recharge_source_name" description:"充值来源名称(中文)"`
|
||||
Status int `json:"status" description:"充值状态 (1:待支付, 2:已支付, 3:已完成, 4:已关闭, 5:已退款, 6:已驳回)"`
|
||||
Status int `json:"status" description:"充值状态 (1:待支付, 2:已支付, 3:已完成, 4:已关闭, 5:已退款, 6:已驳回, 7:审批提交失败)"`
|
||||
StatusName string `json:"status_name" description:"充值状态名称(中文)"`
|
||||
PaymentStatus int `json:"payment_status" description:"支付状态 (0:待支付, 1:已支付, 2:已失败, 3:已退款)"`
|
||||
PaymentStatusName string `json:"payment_status_name" description:"支付状态名称(中文)"`
|
||||
@@ -104,7 +104,7 @@ type AgentRechargeResponse struct {
|
||||
OtherVoucherKey []string `json:"other_voucher_key" description:"其他凭证对象存储Key列表,仅线下充值有值;不返回凭证内容"`
|
||||
PaymentVoucherKey []string `json:"payment_voucher_key" description:"支付凭证对象存储Key列表(线下支付时存在,最多5个)"`
|
||||
Remark string `json:"remark,omitempty" description:"运营备注"`
|
||||
Status int `json:"status" description:"状态 (1:待支付, 2:已支付, 3:已完成, 4:已关闭, 5:已退款, 6:已驳回)"`
|
||||
Status int `json:"status" description:"状态 (1:待支付, 2:已支付, 3:已完成, 4:已关闭, 5:已退款, 6:已驳回, 7:审批提交失败)"`
|
||||
StatusName string `json:"status_name" description:"状态名称(中文)"`
|
||||
RejectionReason *string `json:"rejection_reason,omitempty" description:"驳回原因,仅 status=6 时有值"`
|
||||
SubmitterID uint `json:"submitter_id" description:"提交人账号ID"`
|
||||
@@ -135,7 +135,7 @@ type AgentRechargeListRequest struct {
|
||||
Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码,默认1"`
|
||||
PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页条数,默认20,最大100"`
|
||||
ShopID *uint `json:"shop_id" query:"shop_id" description:"按店铺ID过滤"`
|
||||
Status *int `json:"status" query:"status" description:"按状态过滤 (1:待支付, 2:已支付, 3:已完成, 4:已关闭, 5:已退款, 6:已驳回)"`
|
||||
Status *int `json:"status" query:"status" description:"按状态过滤 (1:待支付, 2:已支付, 3:已完成, 4:已关闭, 5:已退款, 6:已驳回, 7:审批提交失败)"`
|
||||
RechargeSource string `json:"recharge_source" query:"recharge_source" validate:"omitempty,oneof=platform_offline agent_online" description:"按充值来源过滤 (platform_offline:平台线下代充, agent_online:代理在线自充)"`
|
||||
StartTime string `json:"start_time" query:"start_time" description:"创建时间起始(带时区的 RFC3339 秒级时间,闭区间含该时刻,如 2026-09-01T00:00:00+08:00)"`
|
||||
EndTime string `json:"end_time" query:"end_time" description:"创建时间结束(带时区的 RFC3339 秒级时间,闭区间含该时刻,如 2026-09-30T23:59:59+08:00)"`
|
||||
|
||||
@@ -4,7 +4,7 @@ package dto
|
||||
type WithdrawalRequestListReq struct {
|
||||
Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码(默认1)"`
|
||||
PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页数量(默认20,最大100)"`
|
||||
Status *int `json:"status" query:"status" validate:"omitempty,min=1,max=4" minimum:"1" maximum:"4" description:"状态 (1:待审核, 2:已通过, 3:已拒绝, 4:已到账)"`
|
||||
Status *int `json:"status" query:"status" validate:"omitempty,min=1,max=5" minimum:"1" maximum:"5" description:"状态 (1:待审核, 2:已通过, 3:已拒绝, 4:已到账, 5:审批提交失败)"`
|
||||
WithdrawalNo string `json:"withdrawal_no" query:"withdrawal_no" validate:"omitempty,max=50" maxLength:"50" description:"提现单号(精确查询)"`
|
||||
ShopName string `json:"shop_name" query:"shop_name" validate:"omitempty,max=100" maxLength:"100" description:"店铺名称(模糊查询)"`
|
||||
StartTime string `json:"start_time" query:"start_time" description:"申请时间起始(带时区的 RFC3339 秒级时间,闭区间含该时刻,如 2026-09-01T00:00:00+08:00)"`
|
||||
@@ -19,7 +19,7 @@ type WithdrawalRequestItem struct {
|
||||
FeeRate int64 `json:"fee_rate" description:"手续费比率(基点,100=1%)"`
|
||||
Fee int64 `json:"fee" description:"手续费(分)"`
|
||||
ActualAmount int64 `json:"actual_amount" description:"实际到账金额(分)"`
|
||||
Status int `json:"status" description:"状态 (1:待审核, 2:已通过, 3:已拒绝, 4:已到账)"`
|
||||
Status int `json:"status" description:"状态 (1:待审核, 2:已通过, 3:已拒绝, 4:已到账, 5:审批提交失败)"`
|
||||
StatusName string `json:"status_name" description:"状态名称"`
|
||||
ShopID uint `json:"shop_id" description:"店铺ID"`
|
||||
ShopName string `json:"shop_name" description:"店铺名称"`
|
||||
@@ -68,7 +68,7 @@ type RejectWithdrawalReq struct {
|
||||
type WithdrawalApprovalResp struct {
|
||||
ID uint `json:"id" description:"提现申请ID"`
|
||||
WithdrawalNo string `json:"withdrawal_no" description:"提现单号"`
|
||||
Status int `json:"status" description:"状态 (1:待审核, 2:已通过, 3:已拒绝, 4:已到账)"`
|
||||
Status int `json:"status" description:"状态 (1:待审核, 2:已通过, 3:已拒绝, 4:已到账, 5:审批提交失败)"`
|
||||
StatusName string `json:"status_name" description:"状态名称"`
|
||||
ProcessedAt string `json:"processed_at" description:"处理时间"`
|
||||
}
|
||||
|
||||
@@ -146,7 +146,7 @@ type EmployeeCollectionBillRefundResponse struct {
|
||||
type EmployeeCollectionBillAllocationResponse struct {
|
||||
ID uint `json:"id" description:"分摊ID"`
|
||||
ApplicationID uint `json:"application_id" description:"核销申请ID"`
|
||||
ApplicationStatus int `json:"application_status" description:"申请状态 (0:审批中, 1:已通过, 2:已驳回, 3:已撤销或已关闭)"`
|
||||
ApplicationStatus int `json:"application_status" description:"申请状态 (0:审批中, 1:已通过, 2:已驳回, 3:已撤销或已关闭, 4:审批提交失败)"`
|
||||
ApplicationStatusName string `json:"application_status_name" description:"申请状态中文名称"`
|
||||
AttemptID uint `json:"attempt_id" description:"所属审批尝试记录ID"`
|
||||
Amount int64 `json:"amount" description:"本次分摊金额(分)"`
|
||||
@@ -194,7 +194,7 @@ type EmployeeCollectionBillApplicationResponse struct {
|
||||
ExternalTransactionNo string `json:"external_transaction_no" description:"外部交易流水号"`
|
||||
PaymentVoucherKeys []string `json:"payment_voucher_keys" description:"支付凭证对象存储Key列表,仅返回对象键引用"`
|
||||
Remark string `json:"remark" description:"申请备注"`
|
||||
Status int `json:"status" description:"申请状态 (0:审批中, 1:已通过, 2:已驳回, 3:已撤销或已关闭)"`
|
||||
Status int `json:"status" description:"申请状态 (0:审批中, 1:已通过, 2:已驳回, 3:已撤销或已关闭, 4:审批提交失败)"`
|
||||
StatusName string `json:"status_name" description:"申请状态中文名称"`
|
||||
LatestApprovalInstanceID uint `json:"latest_approval_instance_id" description:"最新通用审批实例ID,仅用于展示"`
|
||||
DecidedAt *time.Time `json:"decided_at,omitempty" description:"审批终态到达时间"`
|
||||
@@ -267,7 +267,7 @@ type SubmitEmployeeCollectionApplicationRequest struct {
|
||||
type EmployeeCollectionApplicationListRequest struct {
|
||||
Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码,默认1"`
|
||||
PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页条数,默认20,最大100"`
|
||||
Status *int `json:"status" query:"status" validate:"omitempty,oneof=0 1 2 3" enum:"0,1,2,3" description:"按申请状态过滤 (0:审批中, 1:已通过, 2:已驳回, 3:已撤销或已关闭)"`
|
||||
Status *int `json:"status" query:"status" validate:"omitempty,oneof=0 1 2 3 4" enum:"0,1,2,3,4" description:"按申请状态过滤 (0:审批中, 1:已通过, 2:已驳回, 3:已撤销或已关闭, 4:审批提交失败)"`
|
||||
ApplicantAccountID *uint `json:"applicant_account_id" query:"applicant_account_id" description:"按申请人账号ID过滤;非超级管理员固定为当前账号,该参数被忽略"`
|
||||
PaymentMethodID *uint `json:"payment_method_id" query:"payment_method_id" description:"按线下收款方式字典ID过滤"`
|
||||
CreatedFrom *string `json:"created_from" query:"created_from" description:"创建时间起始(YYYY-MM-DD,含当日 00:00:00)"`
|
||||
@@ -289,11 +289,11 @@ type EmployeeCollectionApplicationResponse struct {
|
||||
ExternalTransactionNo string `json:"external_transaction_no" description:"人工确认的外部交易流水号,申请人可原样核对与重用"`
|
||||
PaymentVoucherKeys []string `json:"payment_voucher_keys" description:"支付凭证对象存储Key列表,仅返回对象键引用"`
|
||||
Remark string `json:"remark" description:"申请备注"`
|
||||
Status int `json:"status" description:"申请状态 (0:审批中, 1:已通过, 2:已驳回, 3:已撤销或已关闭)"`
|
||||
Status int `json:"status" description:"申请状态 (0:审批中, 1:已通过, 2:已驳回, 3:已撤销或已关闭, 4:审批提交失败)"`
|
||||
StatusName string `json:"status_name" description:"申请状态中文名称"`
|
||||
LatestAttemptID uint `json:"latest_attempt_id" description:"最新审批尝试记录ID,仅用于展示"`
|
||||
LatestApprovalInstanceID uint `json:"latest_approval_instance_id" description:"最新通用审批实例ID,仅用于展示"`
|
||||
ApprovalSubmissionStatus int `json:"approval_submission_status" description:"审批提交状态"`
|
||||
ApprovalSubmissionStatus int `json:"approval_submission_status" description:"最新审批实例的企业微信提交状态 (0:待提交, 1:提交中, 2:已提交, 3:提交失败, 4:结果未知);无审批上下文为 0"`
|
||||
ApprovalSubmissionName string `json:"approval_submission_name" description:"审批提交状态中文名称"`
|
||||
ApprovalFailureSummary string `json:"approval_failure_summary,omitempty" description:"脱敏审批失败摘要"`
|
||||
Recoverable bool `json:"recoverable" description:"是否允许恢复原审批"`
|
||||
|
||||
@@ -56,7 +56,7 @@ type ReturnRefundRequest struct {
|
||||
type RefundListRequest struct {
|
||||
Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码(默认1)"`
|
||||
PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页数量(默认20,最大100)"`
|
||||
Status *int `json:"status" query:"status" validate:"omitempty,min=1,max=6" minimum:"1" maximum:"6" description:"状态 (1:待审批, 2:已通过, 3:已拒绝, 4:已退回, 5:原路退款处理中, 6:原路退款失败)"`
|
||||
Status *int `json:"status" query:"status" validate:"omitempty,min=1,max=7" minimum:"1" maximum:"7" description:"状态 (1:待审批, 2:已通过, 3:已拒绝, 4:已退回, 5:原路退款处理中, 6:原路退款失败, 7:审批提交失败)"`
|
||||
OrderID *uint `json:"order_id" query:"order_id" validate:"omitempty" description:"关联订单ID"`
|
||||
ShopID *uint `json:"shop_id" query:"shop_id" validate:"omitempty" description:"店铺ID"`
|
||||
AssetIdentifier string `json:"asset_identifier" query:"asset_identifier" validate:"omitempty,max=100" maxLength:"100" description:"资产标识精确检索(ICCID 或 设备虚拟号,非空时精确匹配)"`
|
||||
@@ -84,7 +84,7 @@ type RefundResponse struct {
|
||||
ApprovedRefundAmount *int64 `json:"approved_refund_amount,omitempty" description:"审批实际退款金额(分)"`
|
||||
RefundVoucherKey []string `json:"refund_voucher_key" description:"退款凭证对象存储file_key列表(最多5个)"`
|
||||
RefundReason string `json:"refund_reason" description:"退款原因"`
|
||||
Status int `json:"status" description:"状态 (1:待审批, 2:已通过, 3:已拒绝, 4:已退回, 5:原路退款处理中, 6:原路退款失败)"`
|
||||
Status int `json:"status" description:"状态 (1:待审批, 2:已通过, 3:已拒绝, 4:已退回, 5:原路退款处理中, 6:原路退款失败, 7:审批提交失败)"`
|
||||
StatusName string `json:"status_name" description:"状态名称(中文)"`
|
||||
Method string `json:"method" description:"退款方式 (original_route:原路退款, customer_account:客户收款信息退款, asset_wallet:退回资产钱包, agent_wallet:退回代理主钱包),空表示未接入方式的存量申请"`
|
||||
MethodName string `json:"method_name" description:"退款方式中文名称"`
|
||||
|
||||
@@ -23,7 +23,7 @@ type CommissionWithdrawalRequest struct {
|
||||
WithdrawalMethod string `gorm:"column:withdrawal_method;type:varchar(20);comment:提现方式 alipay-支付宝 wechat-微信 bank-银行卡" json:"withdrawal_method"`
|
||||
PaymentType string `gorm:"column:payment_type;type:varchar(20);default:'manual';comment:放款类型(manual=人工打款)" json:"payment_type"`
|
||||
AccountInfo datatypes.JSON `gorm:"column:account_info;type:jsonb;comment:收款账户信息(姓名、账号等)" json:"account_info"`
|
||||
Status int `gorm:"column:status;type:int;default:1;comment:状态 1-待审核 2-已通过 3-已拒绝 4-已到账" json:"status"`
|
||||
Status int `gorm:"column:status;type:int;default:1;comment:状态 1-待审核 2-已通过 3-已拒绝 4-已到账 5-审批提交失败" json:"status"`
|
||||
ProcessorID uint `gorm:"column:processor_id;index;comment:处理人ID" json:"processor_id"`
|
||||
ProcessedAt *time.Time `gorm:"column:processed_at;comment:处理时间" json:"processed_at"`
|
||||
PaidAt *time.Time `gorm:"column:paid_at;comment:到账时间" json:"paid_at"`
|
||||
|
||||
@@ -122,6 +122,8 @@ const (
|
||||
RefundStatusChannelProcessing = 5
|
||||
// RefundStatusChannelFailed 表示原路渠道明确失败或超时可恢复失败。
|
||||
RefundStatusChannelFailed = 6
|
||||
// RefundStatusSubmissionFailed 表示提交企业微信审批被明确拒绝,退款单终止且钱未动;可对原单重新发起或新建退款单。
|
||||
RefundStatusSubmissionFailed = 7
|
||||
)
|
||||
|
||||
// RefundActiveStatuses 返回会阻止同一订单创建新退款申请的状态集合。
|
||||
@@ -132,5 +134,5 @@ func RefundActiveStatuses() []int {
|
||||
|
||||
// RefundResubmittableStatuses 返回允许修改材料并重提的状态集合。
|
||||
func RefundResubmittableStatuses() []int {
|
||||
return []int{RefundStatusRejected, RefundStatusReturned, RefundStatusChannelFailed}
|
||||
return []int{RefundStatusRejected, RefundStatusReturned, RefundStatusChannelFailed, RefundStatusSubmissionFailed}
|
||||
}
|
||||
|
||||
@@ -433,6 +433,6 @@ func projectRegistration(row registrationProjection) dto.AgentDistributionRegist
|
||||
if item.SubmissionStatusName == "" {
|
||||
item.SubmissionStatusName = "未知"
|
||||
}
|
||||
item.Recoverable = row.Status == constants.AgentDistributionRegistrationStatusPending && row.ParentShopStatus == 1 && row.ApprovalInstanceID > 0 && (row.ApprovalStatus == constants.ApprovalStatusSubmitting || row.ApprovalStatus == constants.ApprovalStatusPending || row.ApprovalStatus == constants.ApprovalStatusSubmissionFailed || row.ApprovalStatus == constants.ApprovalStatusSubmissionUnknown || row.SubmissionStatus == constants.WeComSubmissionStatusFailed || row.SubmissionStatus == constants.WeComSubmissionStatusUnknown)
|
||||
item.Recoverable = row.Status == constants.AgentDistributionRegistrationStatusPending && row.ParentShopStatus == 1 && row.ApprovalInstanceID > 0 && (row.ApprovalStatus == constants.ApprovalStatusSubmitting || row.ApprovalStatus == constants.ApprovalStatusPending || row.ApprovalStatus == constants.ApprovalStatusSubmissionUnknown || row.SubmissionStatus == constants.WeComSubmissionStatusUnknown)
|
||||
return item
|
||||
}
|
||||
|
||||
@@ -47,6 +47,9 @@ func (q *ApplicationQuery) List(
|
||||
for index := range applications {
|
||||
list = append(list, ProjectApplication(&applications[index]))
|
||||
}
|
||||
if err := q.fillApplicationSubmission(ctx, list); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto.EmployeeCollectionApplicationListResponse{
|
||||
List: list, Total: total, Page: page, PageSize: pageSize,
|
||||
}, nil
|
||||
@@ -77,8 +80,12 @@ func (q *ApplicationQuery) Detail(ctx context.Context, id uint) (*dto.EmployeeCo
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
projected := ProjectApplication(&application)
|
||||
if err := q.fillApplicationSubmission(ctx, []*dto.EmployeeCollectionApplicationResponse{projected}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto.EmployeeCollectionApplicationDetailResponse{
|
||||
Application: ProjectApplication(&application), Allocations: allocations, Attempts: attempts,
|
||||
Application: projected, Allocations: allocations, Attempts: attempts,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -105,7 +112,8 @@ func (q *ApplicationQuery) applyApplicationScope(
|
||||
case constants.EmployeeCollectionApplicationStatusPending,
|
||||
constants.EmployeeCollectionApplicationStatusApproved,
|
||||
constants.EmployeeCollectionApplicationStatusRejected,
|
||||
constants.EmployeeCollectionApplicationStatusRevoked:
|
||||
constants.EmployeeCollectionApplicationStatusRevoked,
|
||||
constants.EmployeeCollectionApplicationStatusSubmissionFailed:
|
||||
query = query.Where("status = ?", *request.Status)
|
||||
default:
|
||||
return nil, errors.New(errors.CodeInvalidParam, "不支持的核销申请状态")
|
||||
|
||||
71
internal/query/employeecollection/application_submission.go
Normal file
71
internal/query/employeecollection/application_submission.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package employeecollection
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
approvalapp "github.com/break/junhong_cmp_fiber/internal/application/approval"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
)
|
||||
|
||||
// applicationSubmissionRow 是核销申请最新审批实例的提交事实。
|
||||
type applicationSubmissionRow struct {
|
||||
InstanceID uint `gorm:"column:instance_id"`
|
||||
InstanceStatus int `gorm:"column:instance_status"`
|
||||
SubmissionStatus int `gorm:"column:submission_status"`
|
||||
LastError string `gorm:"column:last_error"`
|
||||
LastRecoveryAt *time.Time `gorm:"column:last_recovery_at"`
|
||||
}
|
||||
|
||||
// fillApplicationSubmission 按最新审批实例一次批量读取企微审批上下文,填充提交状态、脱敏摘要、可恢复与最近恢复时间。
|
||||
// 无审批实例或无企微上下文的申请保持零值。
|
||||
func (q *ApplicationQuery) fillApplicationSubmission(ctx context.Context, responses []*dto.EmployeeCollectionApplicationResponse) error {
|
||||
instanceIDs := make([]uint, 0, len(responses))
|
||||
for _, response := range responses {
|
||||
if response != nil && response.LatestApprovalInstanceID != 0 {
|
||||
instanceIDs = append(instanceIDs, response.LatestApprovalInstanceID)
|
||||
}
|
||||
}
|
||||
if len(instanceIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
var rows []applicationSubmissionRow
|
||||
if err := q.db.WithContext(ctx).Raw(
|
||||
`SELECT ai.id AS instance_id, ai.status AS instance_status,
|
||||
COALESCE(wc.submission_status, 0) AS submission_status,
|
||||
COALESCE(wc.last_error, '') AS last_error, wc.last_recovery_at
|
||||
FROM tb_approval_instance ai
|
||||
LEFT JOIN tb_wecom_approval_context wc ON wc.approval_instance_id = ai.id
|
||||
WHERE ai.id IN ?`, instanceIDs).Scan(&rows).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "批量查询核销申请审批提交状态失败")
|
||||
}
|
||||
byInstance := make(map[uint]applicationSubmissionRow, len(rows))
|
||||
for _, row := range rows {
|
||||
byInstance[row.InstanceID] = row
|
||||
}
|
||||
for _, response := range responses {
|
||||
if response == nil {
|
||||
continue
|
||||
}
|
||||
row, ok := byInstance[response.LatestApprovalInstanceID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
response.ApprovalSubmissionStatus = row.SubmissionStatus
|
||||
response.ApprovalSubmissionName = constants.GetWeComSubmissionStatusName(row.SubmissionStatus)
|
||||
if row.SubmissionStatus == constants.WeComSubmissionStatusFailed {
|
||||
response.ApprovalFailureSummary = approvalapp.SubmissionFailureReason(row.LastError)
|
||||
}
|
||||
// 提交失败为终态不可恢复;只有审批中的申请且实例仍在提交中、审批中或结果未知时可恢复。
|
||||
response.Recoverable = response.Status == constants.EmployeeCollectionApplicationStatusPending &&
|
||||
(row.InstanceStatus == constants.ApprovalStatusSubmitting ||
|
||||
row.InstanceStatus == constants.ApprovalStatusPending ||
|
||||
row.InstanceStatus == constants.ApprovalStatusSubmissionUnknown)
|
||||
if row.LastRecoveryAt != nil {
|
||||
response.LastRecoveryAt = row.LastRecoveryAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -28,7 +28,8 @@ func (s *Service) Handle(ctx context.Context, event approvalapp.TerminalDecision
|
||||
switch event.Decision {
|
||||
case constants.ApprovalDecisionApproved:
|
||||
return s.applyApprovedDecision(ctx, event)
|
||||
case constants.ApprovalDecisionRejected, constants.ApprovalDecisionCancelled, constants.ApprovalDecisionDeleted:
|
||||
case constants.ApprovalDecisionRejected, constants.ApprovalDecisionCancelled, constants.ApprovalDecisionDeleted,
|
||||
constants.ApprovalDecisionSubmissionFailed:
|
||||
return s.applyClosedDecision(ctx, event)
|
||||
case constants.ApprovalDecisionRevokedAfterApproved:
|
||||
return s.applyRevokedAfterApproved(ctx, event)
|
||||
@@ -214,6 +215,8 @@ func (s *Service) prepareChannelRefundInTx(ctx context.Context, tx *gorm.DB, ref
|
||||
return s.channelRefund.PrepareInTx(ctx, tx, refund, attempt)
|
||||
}
|
||||
|
||||
// applyClosedDecision 处理企微拒绝、撤销、删除(退款单→已拒绝)与审批提交失败(退款单→审批提交失败),均为钱未动的终态。
|
||||
// 业务标识按审批尝试优先解析(BusinessID 在尝试模式下是尝试 ID),再按退款单 ID 加行锁。
|
||||
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{
|
||||
@@ -221,18 +224,35 @@ func (s *Service) applyClosedDecision(ctx context.Context, event approvalapp.Ter
|
||||
constants.ApprovalDecisionCancelled: "企业微信审批已撤销",
|
||||
constants.ApprovalDecisionDeleted: "企业微信审批已删除",
|
||||
}[event.Decision]
|
||||
submissionFailed := event.Decision == constants.ApprovalDecisionSubmissionFailed
|
||||
targetStatus, actionSummary, auditSuffix, auditResult := model.RefundStatusRejected, "拒绝退款审批", ":rejected", "退款已拒绝"
|
||||
if submissionFailed {
|
||||
targetStatus, actionSummary, auditSuffix, auditResult = model.RefundStatusSubmissionFailed, "退款审批提交失败", ":submission_failed", "退款审批提交失败"
|
||||
}
|
||||
var refund model.RefundRequest
|
||||
var order model.Order
|
||||
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, _, 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.ApprovalInstanceID == nil || *refund.ApprovalInstanceID != event.InstanceID {
|
||||
return errors.New(errors.CodeConflict, "退款申请关联的审批实例不一致")
|
||||
}
|
||||
if refund.Status == model.RefundStatusRejected {
|
||||
// 已被重新发起取代的历史审批不再改变退款单事实。
|
||||
if refund.LatestApprovalInstanceID != 0 && refund.LatestApprovalInstanceID != event.InstanceID {
|
||||
return nil
|
||||
}
|
||||
if refund.Status == targetStatus {
|
||||
return nil
|
||||
}
|
||||
if submissionFailed {
|
||||
failureReason, failed, err := approvalapp.ConfirmSubmissionFailed(ctx, tx, event.InstanceID)
|
||||
if err != nil || !failed {
|
||||
return err
|
||||
}
|
||||
reason = failureReason
|
||||
}
|
||||
if refund.Status != model.RefundStatusPending {
|
||||
return errors.New(errors.CodeInvalidStatus, "退款申请状态不允许结束审批")
|
||||
}
|
||||
@@ -243,7 +263,7 @@ func (s *Service) applyClosedDecision(ctx context.Context, event approvalapp.Ter
|
||||
result := tx.WithContext(ctx).Model(&model.RefundRequest{}).
|
||||
Where("id = ? AND status = ?", refund.ID, model.RefundStatusPending).
|
||||
Updates(map[string]any{
|
||||
"status": model.RefundStatusRejected, "processed_at": event.OccurredAt,
|
||||
"status": targetStatus, "processed_at": event.OccurredAt,
|
||||
"reject_reason": strings.TrimSpace(reason), "updated_at": event.OccurredAt,
|
||||
})
|
||||
if result.Error != nil {
|
||||
@@ -252,8 +272,9 @@ func (s *Service) applyClosedDecision(ctx context.Context, event approvalapp.Ter
|
||||
if result.RowsAffected != 1 {
|
||||
return errors.New(errors.CodeConflict, "退款申请状态已变化")
|
||||
}
|
||||
return s.appendRefundAudit(ctx, tx, refund.ID, constants.AuditActionRefundRejected, "拒绝退款审批",
|
||||
"refund:"+strconv.FormatUint(uint64(refund.ID), 10)+":rejected", beforeRefund, nil, "退款已拒绝")
|
||||
return s.appendRefundAudit(ctx, tx, refund.ID, constants.AuditActionRefundRejected, actionSummary,
|
||||
"refund:"+strconv.FormatUint(uint64(refund.ID), 10)+auditSuffix+":"+strconv.FormatUint(uint64(event.InstanceID), 10),
|
||||
beforeRefund, nil, auditResult)
|
||||
})
|
||||
if err != nil {
|
||||
s.recordRefundFailure(ctx, constants.AuditActionRefundRejected, "拒绝退款审批失败", &refund, &order, err)
|
||||
|
||||
@@ -1464,7 +1464,8 @@ func (s *Service) loadApprovalSummaries(ctx context.Context, refunds []*model.Re
|
||||
}
|
||||
for _, row := range rows {
|
||||
summary := approvalSummary{Provider: row.Provider, Status: row.Status, SubmissionStatus: row.SubmissionStatus, FailureSummary: sanitizeApprovalFailure(row.LastError), LastRecoveryAt: row.LastRecoveryAt, SPNo: row.SPNo, EventStatus: row.EventStatus}
|
||||
summary.Recoverable = row.Status == constants.ApprovalStatusSubmissionFailed && row.SubmissionStatus == constants.WeComSubmissionStatusFailed && row.SPNo == "" && (row.EventStatus == constants.OutboxStatusFailed || row.EventStatus == constants.OutboxStatusDelivered)
|
||||
// 提交失败为终态不可恢复;只有提交中、审批中与结果未知仍可由恢复入口确认。
|
||||
summary.Recoverable = row.Status == constants.ApprovalStatusSubmitting || row.Status == constants.ApprovalStatusPending || row.Status == constants.ApprovalStatusSubmissionUnknown
|
||||
result[row.ID] = summary
|
||||
}
|
||||
return result, nil
|
||||
|
||||
Reference in New Issue
Block a user