3 Commits

Author SHA1 Message Date
邹进
0f1ea5bc3e fix: 第1批 M9 套餐临期提醒按资产、扫码进入时触发
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 10m17s
- 每日扫描不再给个人客户写临期通知,店铺通知不变
- H5 资产信息在当前资产剩余 0~15 天且当天首次进入时返回 expiry_reminder,并为该客户、该资产写一条临期通知(Redis 去重,失败不占键)
- 个人通知列表、未读数、全部已读中临期提醒只处理当前资产(按 ref_key)
- OpenSpec Change scope-expiry-reminder-to-current-asset:6/9,临期 fixture 端到端验证与每日扫描验证待测试部署后完成
2026-10-12 00:15:27 +09:00
邹进
9ced14fa1b fix: 第1批 F1、M12 一资产一号与换货按手机号关联校验
- F1 一个资产同时只能有一个有效手机号关联,他号绑定返回 1192(不含号码),同号幂等
- 登录 need_bind_phone 改看资产是否已有有效关联,新增 asset_phone_bound、asset_phone_is_own;H5 绑定按客户/资产两侧状态分别写入
- 客户换号不再迁移资产关联
- M12 换货新资产有有效手机号关联即拒绝,号码只在 data.phone;换货完成清空旧资产客户绑定并失效旧资产关联(exchange_completed),均不迁移
- OpenSpec Change enforce-single-phone-per-asset:11/16,H5 短信与换货端到端验证待测试部署后完成
2026-10-12 00:10:41 +09:00
邹进
6298a9061f 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,测试部署后端到端验证与存量补数据待完成
2026-10-12 00:03:46 +09:00
78 changed files with 1796 additions and 638 deletions

View File

@@ -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, "不支持的线下代充值审批终态")
}

View 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
}

View File

@@ -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),
})

View File

@@ -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, "当前审批提交状态不允许恢复")

View File

@@ -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),

View File

@@ -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,

View File

@@ -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
}

View File

@@ -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, "当前审批提交状态不允许恢复")
}

View File

@@ -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"
}

View File

@@ -68,13 +68,17 @@ func (s *ReadService) MarkPersonalRead(ctx context.Context, customerID, notifica
constants.AuditActorPersonalCustomer, constants.AuditSourcePersonalAPI)
}
// MarkAllPersonalRead 将当前个人客户可见的全部未过期通知幂等标记为已读。
func (s *ReadService) MarkAllPersonalRead(ctx context.Context, customerID uint) (*dto.NotificationReadAllResponse, error) {
// MarkAllPersonalRead 将当前个人客户可见的全部未过期通知幂等标记为已读;
// 套餐临期提醒只处理当前资产的,其他资产的临期提醒保持未读。
func (s *ReadService) MarkAllPersonalRead(ctx context.Context, customerID uint, currentAssetKey string) (*dto.NotificationReadAllResponse, error) {
if customerID == 0 {
return nil, errors.New(errors.CodeInvalidParam)
}
count, err := s.markAllRead(ctx, constants.NotificationRecipientKindPersonalCustomer, customerID, "",
constants.AuditActorPersonalCustomer, constants.AuditSourcePersonalAPI)
constants.AuditActorPersonalCustomer, constants.AuditSourcePersonalAPI, func(query *gorm.DB) *gorm.DB {
return query.Where(constants.NotificationPersonalExpiringAssetCondition,
constants.NotificationTypePackageExpiring, constants.NotificationRefTypeAsset, currentAssetKey)
})
if err != nil {
return nil, err
}
@@ -107,7 +111,7 @@ func (s *ReadService) markOneRead(ctx context.Context, recipientKind string, rec
})
}
func (s *ReadService) markAllRead(ctx context.Context, recipientKind string, recipientID uint, category, actorKind, source string) (int64, error) {
func (s *ReadService) markAllRead(ctx context.Context, recipientKind string, recipientID uint, category, actorKind, source string, scopes ...func(*gorm.DB) *gorm.DB) (int64, error) {
if s.auditWriter == nil {
return 0, errors.New(errors.CodeInvalidStatus, "通知统一审计接缝未配置")
}
@@ -120,6 +124,9 @@ func (s *ReadService) markAllRead(ctx context.Context, recipientKind string, rec
if category != "" {
query = query.Where("category = ?", category)
}
for _, scope := range scopes {
query = scope(query)
}
if err := query.Order("id ASC").Find(&notifications).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "查询批量通知已读状态失败")
}

View File

@@ -0,0 +1,98 @@
package packageexpiry
import (
"context"
"time"
"github.com/redis/go-redis/v9"
"go.uber.org/zap"
"github.com/break/junhong_cmp_fiber/internal/model/dto"
packageexpiryquery "github.com/break/junhong_cmp_fiber/internal/query/packageexpiry"
"github.com/break/junhong_cmp_fiber/pkg/constants"
)
// entryReminderWindowDays 临期提醒窗口:剩余 0~15 个上海自然日。
const entryReminderWindowDays = 15
var entryReminderLocation = time.FixedZone("Asia/Shanghai", 8*60*60)
// PersonalReminderPublisher 为单个个人客户幂等写一条临期通知。
type PersonalReminderPublisher interface {
PublishPersonal(ctx context.Context, candidate dto.ExpiringAssetItem, customerID uint) error
}
// EntryReminder 在 H5 进入资产时判定并发出套餐临期提醒,同一客户、同一资产、同一上海自然日至多一次。
type EntryReminder struct {
redis *redis.Client
publisher PersonalReminderPublisher
logger *zap.Logger
now func() time.Time
}
// NewEntryReminder 创建进入资产时的临期提醒用例。
func NewEntryReminder(redisClient *redis.Client, publisher PersonalReminderPublisher, logger *zap.Logger) *EntryReminder {
return &EntryReminder{redis: redisClient, publisher: publisher, logger: logger, now: time.Now}
}
// Remind 返回本次应展示的临期提醒;不在窗口、当天已提醒或通知写入失败时返回 nil,不让资产信息接口失败。
// 顺序:检查去重键 → 写通知 → SET NX → 抢到键才返回;Redis 不可用按未提醒处理,通知由事件号幂等。
func (r *EntryReminder) Remind(ctx context.Context, customerID uint, candidate dto.ExpiringAssetItem) *dto.AssetExpiryReminder {
if r == nil || r.publisher == nil || customerID == 0 || !inEntryReminderWindow(candidate.PackageExpiryEstimate) {
return nil
}
now := r.now().In(entryReminderLocation)
key := constants.RedisPackageExpiryEntryReminderKey(customerID, candidate.AssetType, candidate.Identifier, now.Format("20060102"))
redisOK := r.redis != nil
if redisOK {
exists, err := r.redis.Exists(ctx, key).Result()
if err != nil {
redisOK = false
r.warn("检查临期提醒去重键失败,按未提醒处理", err)
} else if exists > 0 {
return nil
}
}
if err := r.publisher.PublishPersonal(ctx, candidate, customerID); err != nil {
// 写通知失败不占键、不返回字段,下次进入重试。
r.warn("写入进入资产临期通知失败", err)
return nil
}
if redisOK {
ttl := endOfShanghaiDay(now).Sub(now) + constants.PackageExpiryEntryReminderTTLBuffer
acquired, err := r.redis.SetNX(ctx, key, "1", ttl).Result()
if err != nil {
r.warn("占用临期提醒去重键失败,按未提醒处理", err)
} else if !acquired {
return nil
}
}
days := *candidate.DaysUntilFinalExpiry
level, levelName := packageexpiryquery.ExpiryLevel(days)
return &dto.AssetExpiryReminder{
RemainingDays: days, ExpiresAt: *candidate.EstimatedFinalExpiresAt,
Level: level, LevelName: levelName,
}
}
// inEntryReminderWindow 判断最终到期可精确推算且剩余 0~15 个上海自然日。
func inEntryReminderWindow(estimate dto.PackageExpiryEstimate) bool {
if estimate.ExpiryEstimateStatus != constants.PackageExpiryEstimateStatusExact ||
estimate.DaysUntilFinalExpiry == nil || estimate.EstimatedFinalExpiresAt == nil {
return false
}
days := *estimate.DaysUntilFinalExpiry
return days >= 0 && days <= entryReminderWindowDays
}
// endOfShanghaiDay 返回上海时间当天结束时刻(次日零点)。
func endOfShanghaiDay(now time.Time) time.Time {
year, month, day := now.In(entryReminderLocation).Date()
return time.Date(year, month, day+1, 0, 0, 0, 0, entryReminderLocation)
}
func (r *EntryReminder) warn(message string, err error) {
if r.logger != nil {
r.logger.Warn(message, zap.Error(err))
}
}

View File

@@ -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) {

View File

@@ -7,6 +7,7 @@ import (
h5PopupApp "github.com/break/junhong_cmp_fiber/internal/application/h5popup"
merchantPaymentApp "github.com/break/junhong_cmp_fiber/internal/application/merchantpayment"
notificationApp "github.com/break/junhong_cmp_fiber/internal/application/notification"
packageExpiryApp "github.com/break/junhong_cmp_fiber/internal/application/packageexpiry"
roleApp "github.com/break/junhong_cmp_fiber/internal/application/role"
shopApp "github.com/break/junhong_cmp_fiber/internal/application/shop"
systemConfigApp "github.com/break/junhong_cmp_fiber/internal/application/systemconfig"
@@ -21,7 +22,9 @@ import (
auditInfra "github.com/break/junhong_cmp_fiber/internal/infrastructure/audit"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/carriercallback"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/integrationlog"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/messaging/outbox"
notificationInfra "github.com/break/junhong_cmp_fiber/internal/infrastructure/notification"
packageExpiryInfra "github.com/break/junhong_cmp_fiber/internal/infrastructure/packageexpiry"
systemConfigInfra "github.com/break/junhong_cmp_fiber/internal/infrastructure/systemconfig"
wecomInfra "github.com/break/junhong_cmp_fiber/internal/infrastructure/wecom"
pollingPkg "github.com/break/junhong_cmp_fiber/internal/polling"
@@ -209,6 +212,9 @@ func initHandlers(svc *services, deps *Dependencies) *Handlers {
handler.SetObservationSeriesDispatcher(svc.ObservationSeries)
handler.SetPaymentMethodPolicy(paymentMethodPolicy)
handler.SetForceRechargeChecker(svc.Recharge)
handler.SetExpiryReminder(packageExpiryApp.NewEntryReminder(
deps.Redis, packageExpiryInfra.NewReminderPublisher(deps.DB, outbox.NewRepository()), deps.Logger,
))
return handler
}(),
ClientWallet: func() *app.ClientWalletHandler {

View File

@@ -370,6 +370,7 @@ func initServices(s *stores, deps *Dependencies) *services {
exchangeService := exchangeSvc.New(deps.DB, s.ExchangeOrder, s.IotCard, s.Device, s.AssetWallet, s.AssetWalletTransaction, s.PackageUsage, s.PackageUsageDailyRecord, s.ResourceTag, customerBinding, deps.Logger)
exchangeService.SetShippingCreatedNotifier(exchangeApp.NewShippingCreatedNotifier(exchangeInfra.NewShippingNotificationWriter(outbox.NewRepository())))
exchangeService.SetAccessAudit(auditWriter)
exchangeService.SetPhoneAssetAssociationStore(s.PhoneAssetAssociation)
assetService := assetSvc.New(deps.DB, s.Device, s.IotCard, s.PackageUsage, s.Package, s.PackageSeries, s.DeviceSimBinding, s.Shop, deps.Redis, iotCard, deps.GatewayClient, s.AssetIdentifier, s.Order, s.OrderItem, s.ExchangeOrder)
assetService.SetPhoneAssetAssociationStore(s.PhoneAssetAssociation)
assetService.SetAccessAudit(auditWriter)

View File

@@ -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)

View File

@@ -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 {

View File

@@ -46,6 +46,17 @@ type ClientAssetHandler struct {
observationSeries cardObservationApp.BestEffortSeriesDispatcher
paymentMethodPolicy ClientPaymentMethodPolicy
forceRechargeChecker ClientForceRechargeChecker
expiryReminder ClientExpiryReminder
}
// ClientExpiryReminder 在 H5 进入资产时判定并发出套餐临期提醒。
type ClientExpiryReminder interface {
Remind(ctx context.Context, customerID uint, candidate dto.ExpiringAssetItem) *dto.AssetExpiryReminder
}
// SetExpiryReminder 注入进入资产时的套餐临期提醒用例。
func (h *ClientAssetHandler) SetExpiryReminder(reminder ClientExpiryReminder) {
h.expiryReminder = reminder
}
// ClientPaymentMethodPolicy 提供 C 端支付方式读取和校验能力。
@@ -279,6 +290,10 @@ func (h *ClientAssetHandler) GetAssetInfo(c *fiber.Ctx) error {
BoundDeviceName: resolved.Asset.BoundDeviceName,
}
if h.expiryReminder != nil {
resp.ExpiryReminder = h.expiryReminder.Remind(c.UserContext(), resolved.CustomerID, expiringCandidateOf(resolved.Asset))
}
// 调用服务层获取设备实时 Gateway 数据(per D-11)
// Gateway 失败时 DeviceRealtime 仅含 gateway_msg,不阻断主流程(per D-06)
if resp.AssetType == "device" {
@@ -851,3 +866,24 @@ func mapDeviceGatewayInfoToClientInfo(g *dto.DeviceGatewayInfo) *dto.DeviceRealt
info.GatewayMsg = g.GatewayMsg
return info
}
// expiringCandidateOf 把资产解析结果转换为临期提醒候选;资产标识与通知中心过滤口径一致(卡 ICCID;设备虚拟号,空则 IMEI)。
func expiringCandidateOf(asset *dto.AssetResolveResponse) dto.ExpiringAssetItem {
candidate := dto.ExpiringAssetItem{
AssetID: asset.AssetID, ShopID: asset.ShopID, PackageExpiryEstimate: asset.PackageExpiryEstimate,
}
if asset.CurrentPackageUsageID != nil {
candidate.PackageUsageID = *asset.CurrentPackageUsageID
}
if asset.AssetType == "device" {
candidate.AssetType = constants.AssetTypeDevice
candidate.Identifier = asset.VirtualNo
if candidate.Identifier == "" {
candidate.Identifier = asset.IMEI
}
return candidate
}
candidate.AssetType = constants.AssetTypeIotCard
candidate.Identifier = asset.ICCID
return candidate
}

View File

@@ -36,7 +36,11 @@ func (h *ClientNotificationHandler) UnreadCount(c *fiber.Ctx) error {
if !ok || customerID == 0 {
return errors.New(errors.CodeUnauthorized)
}
result, err := h.query.PersonalUnreadCount(c.UserContext(), customerID)
assetKey, err := h.currentAssetKey(c)
if err != nil {
return err
}
result, err := h.query.PersonalUnreadCount(c.UserContext(), customerID, assetKey)
if err != nil {
return err
}
@@ -61,7 +65,11 @@ func (h *ClientNotificationHandler) List(c *fiber.Ctx) error {
if !ok || customerID == 0 {
return errors.New(errors.CodeUnauthorized)
}
result, err := h.query.PersonalList(c.UserContext(), customerID, request)
assetKey, err := h.currentAssetKey(c)
if err != nil {
return err
}
result, err := h.query.PersonalList(c.UserContext(), customerID, assetKey, request)
if err != nil {
return err
}
@@ -75,7 +83,11 @@ func (h *ClientNotificationHandler) MarkAllRead(c *fiber.Ctx) error {
if !ok || customerID == 0 {
return errors.New(errors.CodeUnauthorized)
}
result, err := h.readService.MarkAllPersonalRead(c.UserContext(), customerID)
assetKey, err := h.currentAssetKey(c)
if err != nil {
return err
}
result, err := h.readService.MarkAllPersonalRead(c.UserContext(), customerID, assetKey)
if err != nil {
return err
}
@@ -99,6 +111,15 @@ func (h *ClientNotificationHandler) MarkRead(c *fiber.Ctx) error {
return response.Success(c, dto.NotificationReadResponse{Success: true})
}
// currentAssetKey 读取令牌当前资产的通知引用标识,用于只展示当前资产的套餐临期提醒。
func (h *ClientNotificationHandler) currentAssetKey(c *fiber.Ctx) (string, error) {
assetType, assetID, ok := middleware.GetCurrentAsset(c)
if !ok {
return "", nil
}
return h.query.CurrentAssetRefKey(c.UserContext(), assetType, assetID)
}
func logPersonalNotificationListValidationFailure(c *fiber.Ctx, request dto.PersonalNotificationListRequest, err error) {
logger.GetAppLogger().Warn("个人客户站内通知列表参数验证失败",
zap.String("method", c.Method()),

View File

@@ -18,7 +18,7 @@ import (
var shanghaiLocation = time.FixedZone("Asia/Shanghai", 8*60*60)
// ReminderPublisher 将每日临期事实转换为店铺和个人客户通知 Outbox。
// ReminderPublisher 将临期事实转换为店铺通知(每日扫描)与个人客户通知(H5 进入资产时)Outbox。
type ReminderPublisher struct {
db *gorm.DB
outbox *outbox.Repository
@@ -29,41 +29,38 @@ func NewReminderPublisher(db *gorm.DB, repository *outbox.Repository) *ReminderP
return &ReminderPublisher{db: db, outbox: repository}
}
type recipientRow struct {
AssetID uint
CustomerID uint
}
// Publish 批量解析资产关联个人客户,并在同一事务内幂等追加店铺和个人通知事件。
// Publish 每日扫描在同一事务内幂等追加店铺通知事件。
// 不再给个人客户批量写临期通知:个人客户只在 H5 进入该资产时由 PublishPersonal 提醒。
func (p *ReminderPublisher) Publish(ctx context.Context, candidates []dto.ExpiringAssetItem) error {
if p == nil || p.db == nil || p.outbox == nil {
return errors.New(errors.CodeInternalError, "套餐临期通知 Publisher 未配置")
}
recipients, err := p.loadRecipients(ctx, candidates)
if err != nil {
return err
}
return p.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
for _, candidate := range candidates {
if candidate.DaysUntilFinalExpiry == nil || candidate.EstimatedFinalExpiresAt == nil {
if candidate.DaysUntilFinalExpiry == nil || candidate.EstimatedFinalExpiresAt == nil || candidate.ShopID == nil {
continue
}
key := recipientKey(candidate.AssetType, candidate.AssetID)
if candidate.ShopID != nil {
if err := p.appendShopNotification(ctx, tx, candidate, *candidate.ShopID); err != nil {
return err
}
}
for customerID := range recipients[key] {
if err := p.appendNotification(ctx, tx, candidate, customerID); err != nil {
return err
}
if err := p.appendShopNotification(ctx, tx, candidate, *candidate.ShopID); err != nil {
return err
}
}
return nil
})
}
// PublishPersonal 为进入资产的个人客户幂等写一条临期通知;事件号含资产、到期日、剩余天数与客户。
func (p *ReminderPublisher) PublishPersonal(ctx context.Context, candidate dto.ExpiringAssetItem, customerID uint) error {
if p == nil || p.db == nil || p.outbox == nil {
return errors.New(errors.CodeInternalError, "套餐临期通知 Publisher 未配置")
}
if candidate.DaysUntilFinalExpiry == nil || candidate.EstimatedFinalExpiresAt == nil || customerID == 0 {
return errors.New(errors.CodeInvalidParam, "套餐临期个人通知参数不完整")
}
return p.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
return p.appendNotification(ctx, tx, candidate, customerID)
})
}
// appendShopNotification 按资产所属店铺写入一条动态接收人通知事件。
func (p *ReminderPublisher) appendShopNotification(ctx context.Context, tx *gorm.DB, candidate dto.ExpiringAssetItem, shopID uint) error {
node := *candidate.DaysUntilFinalExpiry
@@ -93,57 +90,6 @@ func (p *ReminderPublisher) appendShopNotification(ctx context.Context, tx *gorm
return nil
}
func (p *ReminderPublisher) loadRecipients(ctx context.Context, candidates []dto.ExpiringAssetItem) (map[string]map[uint]struct{}, error) {
cardIDs := make([]uint, 0)
deviceIDs := make([]uint, 0)
for _, candidate := range candidates {
if candidate.AssetType == constants.AssetTypeIotCard {
cardIDs = append(cardIDs, candidate.AssetID)
} else if candidate.AssetType == constants.AssetTypeDevice {
deviceIDs = append(deviceIDs, candidate.AssetID)
}
}
result := make(map[string]map[uint]struct{})
queries := []struct {
assetType string
ids []uint
sql string
}{
{constants.AssetTypeIotCard, cardIDs, `
SELECT c.id AS asset_id, b.customer_id
FROM tb_iot_card c
JOIN tb_personal_customer_device b ON c.virtual_no <> '' AND b.virtual_no = c.virtual_no
WHERE c.id IN ? AND c.deleted_at IS NULL AND b.deleted_at IS NULL AND b.status = 1`},
{constants.AssetTypeIotCard, cardIDs, `
SELECT c.id AS asset_id, b.customer_id
FROM tb_iot_card c
JOIN tb_personal_customer_iccid b ON c.virtual_no = '' AND (b.iccid = c.iccid OR (b.iccid_19 <> '' AND b.iccid_19 = c.iccid_19))
WHERE c.id IN ? AND c.deleted_at IS NULL AND b.deleted_at IS NULL AND b.status = 1`},
{constants.AssetTypeDevice, deviceIDs, `
SELECT d.id AS asset_id, b.customer_id
FROM tb_device d
JOIN tb_personal_customer_device b ON b.virtual_no = CASE WHEN d.virtual_no <> '' THEN d.virtual_no ELSE d.imei END
WHERE d.id IN ? AND d.deleted_at IS NULL AND b.deleted_at IS NULL AND b.status = 1`},
}
for _, query := range queries {
if len(query.ids) == 0 {
continue
}
var rows []recipientRow
if err := p.db.WithContext(ctx).Raw(query.sql, query.ids).Scan(&rows).Error; err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "批量查询临期资产关联客户失败")
}
for _, row := range rows {
key := recipientKey(query.assetType, row.AssetID)
if result[key] == nil {
result[key] = make(map[uint]struct{})
}
result[key][row.CustomerID] = struct{}{}
}
}
return result, nil
}
func (p *ReminderPublisher) appendNotification(ctx context.Context, tx *gorm.DB, candidate dto.ExpiringAssetItem, customerID uint) error {
node := *candidate.DaysUntilFinalExpiry
expiryDate := candidate.EstimatedFinalExpiresAt.In(shanghaiLocation).Format("20060102")
@@ -191,7 +137,3 @@ func expiryTemplateData(candidate dto.ExpiringAssetItem) map[string]string {
"expiry_date": expiryDate,
}
}
func recipientKey(assetType string, assetID uint) string {
return fmt.Sprintf("%s:%d", assetType, assetID)
}

View File

@@ -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"`

View File

@@ -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:"申请店铺编号"`

View File

@@ -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)"`

View File

@@ -13,8 +13,18 @@ type AssetInfoRequest struct {
// AssetInfoResponse B1 资产信息响应
// 根据 asset_type 不同,设备专属字段或卡专属字段会分别填充(另一侧为零值/omit)
// AssetExpiryReminder H5 进入资产时的套餐临期提醒;同一客户、同一资产、同一上海自然日至多返回一次。
type AssetExpiryReminder struct {
RemainingDays int `json:"remaining_days" description:"距最终到期的剩余上海自然日天数(0~15)"`
ExpiresAt time.Time `json:"expires_at" description:"预计套餐最终到期时间"`
Level string `json:"level" description:"提醒等级 (red:0至3天, purple:4至7天, pink:8至15天)"`
LevelName string `json:"level_name" description:"提醒等级中文名称"`
}
type AssetInfoResponse struct {
PackageExpiryEstimate
// ExpiryReminder 当前资产临期且当天首次进入时返回,否则不返回该字段
ExpiryReminder *AssetExpiryReminder `json:"expiry_reminder,omitempty" description:"套餐临期提醒:当前资产剩余 0~15 天且该客户当天首次进入时返回,同时写一条该资产的临期通知;否则不返回"`
// === 登录用户信息 ===
BoundPhone string `json:"bound_phone" description:"当前登录用户绑定的手机号"`

View File

@@ -29,9 +29,11 @@ type WechatLoginRequest struct {
// WechatLoginResponse A2/A3 登录统一响应
type WechatLoginResponse struct {
Token string `json:"token" description:"登录JWT令牌"`
NeedBindPhone bool `json:"need_bind_phone" description:"是否需要绑定手机号"`
IsNewUser bool `json:"is_new_user" description:"是否新创建用户"`
Token string `json:"token" description:"登录JWT令牌"`
NeedBindPhone bool `json:"need_bind_phone" description:"是否需要绑定手机号(仅前端提示):强制绑定开关开启时,客户无手机号或当前资产尚无有效手机号关联为 true;开关关闭恒为 false"`
AssetPhoneBound bool `json:"asset_phone_bound" description:"当前资产是否已绑定手机号(一资产一号);不返回号码"`
AssetPhoneIsOwn bool `json:"asset_phone_is_own" description:"当前资产绑定的手机号是否为当前客户自己的手机号;不返回号码"`
IsNewUser bool `json:"is_new_user" description:"是否新创建用户"`
}
// ========================================

View File

@@ -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:"处理时间"`
}

View File

@@ -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:"是否允许恢复原审批"`

View File

@@ -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:"退款方式中文名称"`

View File

@@ -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"`

View File

@@ -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}
}

View File

@@ -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
}

View File

@@ -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, "不支持的核销申请状态")

View 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
}

View File

@@ -84,13 +84,15 @@ func (q *Query) List(ctx context.Context, recipientID uint, request dto.Notifica
}, nil
}
// PersonalUnreadCount 查询当前个人客户可见业务通知的准确未读数。
func (q *Query) PersonalUnreadCount(ctx context.Context, customerID uint) (*dto.NotificationUnreadCountResponse, error) {
// PersonalUnreadCount 查询当前个人客户可见业务通知的准确未读数;套餐临期提醒只计当前资产的。
func (q *Query) PersonalUnreadCount(ctx context.Context, customerID uint, currentAssetKey string) (*dto.NotificationUnreadCountResponse, error) {
if customerID == 0 {
return nil, errors.New(errors.CodeInvalidParam)
}
var count int64
err := personalNotificationScope(q.db.WithContext(ctx).Model(&model.Notification{}), customerID, q.now().UTC()).
Where(constants.NotificationPersonalExpiringAssetCondition,
constants.NotificationTypePackageExpiring, constants.NotificationRefTypeAsset, currentAssetKey).
Where("is_read = ?", false).
Count(&count).Error
if err != nil {
@@ -99,8 +101,8 @@ func (q *Query) PersonalUnreadCount(ctx context.Context, customerID uint) (*dto.
return newUnreadCountResponse(count), nil
}
// PersonalList 查询当前个人客户可见的未过期业务通知简化列表。
func (q *Query) PersonalList(ctx context.Context, customerID uint, request dto.PersonalNotificationListRequest) (*dto.PersonalNotificationListResponse, error) {
// PersonalList 查询当前个人客户可见的未过期业务通知简化列表;套餐临期提醒只含当前资产的。
func (q *Query) PersonalList(ctx context.Context, customerID uint, currentAssetKey string, request dto.PersonalNotificationListRequest) (*dto.PersonalNotificationListResponse, error) {
if customerID == 0 {
return nil, errors.New(errors.CodeInvalidParam)
}
@@ -108,7 +110,9 @@ func (q *Query) PersonalList(ctx context.Context, customerID uint, request dto.P
if err != nil {
return nil, err
}
base := personalNotificationScope(q.db.WithContext(ctx).Model(&model.Notification{}), customerID, q.now().UTC())
base := personalNotificationScope(q.db.WithContext(ctx).Model(&model.Notification{}), customerID, q.now().UTC()).
Where(constants.NotificationPersonalExpiringAssetCondition,
constants.NotificationTypePackageExpiring, constants.NotificationRefTypeAsset, currentAssetKey)
if request.IsRead != nil {
base = base.Where("is_read = ?", *request.IsRead)
}
@@ -238,3 +242,35 @@ func popupSnapshotItem(record model.Notification) *dto.NotificationPopupSnapshot
ActionType: record.PopupSnapshot.ActionType,
}
}
// CurrentAssetRefKey 返回个人客户令牌当前资产的通知引用标识:卡为 ICCID;设备优先虚拟号,为空则 IMEI。
// 资产不存在或类型未知时返回空串,此时个人通知中心不展示任何套餐临期提醒。
func (q *Query) CurrentAssetRefKey(ctx context.Context, assetType string, assetID uint) (string, error) {
if assetID == 0 {
return "", nil
}
var row struct {
ICCID string `gorm:"column:iccid"`
VirtualNo string `gorm:"column:virtual_no"`
IMEI string `gorm:"column:imei"`
}
var result *gorm.DB
switch assetType {
case constants.AssetTypeIotCard, "card":
result = q.db.WithContext(ctx).Model(&model.IotCard{}).Select("iccid").Where("id = ?", assetID).Limit(1).Scan(&row)
case constants.AssetTypeDevice:
result = q.db.WithContext(ctx).Model(&model.Device{}).Select("virtual_no", "imei").Where("id = ?", assetID).Limit(1).Scan(&row)
default:
return "", nil
}
if result.Error != nil {
return "", errors.Wrap(errors.CodeDatabaseError, result.Error, "查询当前资产标识失败")
}
if row.ICCID != "" {
return row.ICCID, nil
}
if row.VirtualNo != "" {
return row.VirtualNo, nil
}
return row.IMEI, nil
}

View File

@@ -246,7 +246,7 @@ func (q *Query) resolveCandidates(ctx context.Context, candidates []assetCandida
if filter.PackageID != nil && usage.PackageID != *filter.PackageID {
continue
}
level, levelName := expiryLevel(days)
level, levelName := ExpiryLevel(days)
items = append(items, dto.ExpiringAssetItem{
AssetType: candidate.AssetType, AssetID: candidate.AssetID, Identifier: candidate.Identifier, ShopID: candidate.ShopID,
PackageUsageID: usage.ID, PackageID: usage.PackageID, PackageName: usage.PackageName,
@@ -363,7 +363,8 @@ func validateListFilter(filter ListFilter) error {
return nil
}
func expiryLevel(days int) (string, string) {
// ExpiryLevel 返回临期高亮等级与中文名称:≤3 红、≤7 紫、其余粉红。
func ExpiryLevel(days int) (string, string) {
if days <= 3 {
return "red", "红色"
}

View File

@@ -10,10 +10,12 @@ import (
func registerAdminExchangeRoutes(router fiber.Router, handler *admin.ExchangeHandler, doc *openapi.Generator, basePath string) {
Register(router, doc, basePath, "POST", "/exchanges", handler.Create, RouteSpec{
Summary: "创建换货单",
Tags: []string{"换货管理"},
Input: new(dto.CreateExchangeRequest),
Output: new(dto.ExchangeOrderResponse),
Auth: true,
Description: "新资产存在有效手机号关联时拒绝(错误码 1202),提示先在后台解除该资产的手机号绑定;完整号码只在错误响应 data.phone 中返回,不进日志。" +
"不再以“有人扫过码”拒绝。直接换货完成时清空旧资产的个人客户绑定并失效旧资产手机号关联(exchange_completed),均不迁移到新资产。",
Tags: []string{"换货管理"},
Input: new(dto.CreateExchangeRequest),
Output: new(dto.ExchangeOrderResponse),
Auth: true,
})
Register(router, doc, basePath, "GET", "/exchanges", handler.List, RouteSpec{
@@ -43,7 +45,9 @@ func registerAdminExchangeRoutes(router fiber.Router, handler *admin.ExchangeHan
Register(router, doc, basePath, "POST", "/exchanges/:id/complete", handler.Complete, RouteSpec{
Summary: "确认换货完成",
Description: "确认换货完成;仅超级管理员或平台用户可对迁移状态为 failed 的物流换货单重试," +
"其他账号对 failed 单返回 403/1005;非 failed 单沿用既有完成权限。",
"其他账号对 failed 单返回 403/1005;非 failed 单沿用既有完成权限。" +
"新资产存在有效手机号关联时拒绝并停在已发货待确认,完整号码在错误响应 data.phone;后台解除后可重新确认。" +
"完成时清空旧资产个人客户绑定并失效旧资产手机号关联,均不迁移到新资产。",
Tags: []string{"换货管理"},
Input: new(dto.ExchangeIDRequest),
Output: nil,

View File

@@ -93,18 +93,21 @@ func RegisterPersonalCustomerRoutes(router fiber.Router, doc *openapi.Generator,
Register(authProtectedGroup, doc, basePath+authBasePath, "POST", "/bind-phone", handlers.ClientAuth.BindPhone, RouteSpec{
Summary: "绑定手机号",
Tags: []string{"个人客户 - 认证"},
Auth: true,
Input: &dto.BindPhoneRequest{},
Output: &dto.BindPhoneResponse{},
Description: "客户手机号与资产手机号相互独立:无手机号且资产无关联时同时写入两者;有手机号且资产无关联时只为资产建立关联,号码可与客户手机号不同;" +
"无手机号而资产已绑定时只写客户手机号;资产已绑定其他号码时返回 1192“该资产已绑定手机号,如需更换请联系管理员”,响应不含号码。",
Tags: []string{"个人客户 - 认证"},
Auth: true,
Input: &dto.BindPhoneRequest{},
Output: &dto.BindPhoneResponse{},
})
Register(authProtectedGroup, doc, basePath+authBasePath, "POST", "/change-phone", handlers.ClientAuth.ChangePhone, RouteSpec{
Summary: "更换手机号",
Tags: []string{"个人客户 - 认证"},
Auth: true,
Input: &dto.ChangePhoneRequest{},
Output: &dto.ChangePhoneResponse{},
Summary: "更换手机号",
Description: "同时验证旧、新号码,只更换客户手机号,不迁移、复制或失效任何资产手机号关联。",
Tags: []string{"个人客户 - 认证"},
Auth: true,
Input: &dto.ChangePhoneRequest{},
Output: &dto.ChangePhoneResponse{},
})
Register(authProtectedGroup, doc, basePath+authBasePath, "POST", "/logout", handlers.ClientAuth.Logout, RouteSpec{
@@ -146,11 +149,12 @@ func RegisterPersonalCustomerRoutes(router fiber.Router, doc *openapi.Generator,
})
Register(authGroup, doc, basePath, "GET", "/asset/info", handlers.ClientAsset.GetAssetInfo, RouteSpec{
Summary: "资产信息",
Tags: []string{"个人客户 - 资产"},
Auth: true,
Input: &dto.AssetInfoRequest{},
Output: &dto.AssetInfoResponse{},
Summary: "资产信息",
Description: "资产剩余 0~15 个上海自然日且当前客户当天首次进入时返回 expiry_reminder,并为该客户、该资产写一条套餐临期通知;同一客户、同一资产当天只返回一次。",
Tags: []string{"个人客户 - 资产"},
Auth: true,
Input: &dto.AssetInfoRequest{},
Output: &dto.AssetInfoResponse{},
})
Register(authGroup, doc, basePath, "GET", "/asset/packages", handlers.ClientAsset.GetAvailablePackages, RouteSpec{

View File

@@ -15,7 +15,7 @@ func registerPersonalNotificationRoutes(router fiber.Router, handler *apphandler
Register(notifications, doc, groupPath, "GET", "/unread-count", handler.UnreadCount, RouteSpec{
Summary: "查询个人客户通知未读数",
Description: "仅查询当前认证个人客户的未过期业务通知,平台同步和系统运维通知不会进入结果。",
Description: "仅查询当前认证个人客户的未过期业务通知,平台同步和系统运维通知不会进入结果;套餐临期提醒只计当前登录资产的。",
Tags: []string{"个人客户 - 站内通知"},
Output: new(dto.NotificationUnreadCountResponse),
Auth: true,
@@ -23,7 +23,7 @@ func registerPersonalNotificationRoutes(router fiber.Router, handler *apphandler
Register(notifications, doc, groupPath, "GET", "", handler.List, RouteSpec{
Summary: "查询个人客户通知列表",
Description: "仅返回当前认证个人客户的未过期业务通知,可按已读状态筛选,固定按创建时间和通知 ID 倒序。当前 C 端契约只承诺列表展示和未读弹窗;ref_type/ref_id/ref_key 是资源引用与展示快照,不是URL,也不承诺可直接拼接页面路由。",
Description: "仅返回当前认证个人客户的未过期业务通知,可按已读状态筛选,固定按创建时间和通知 ID 倒序;套餐临期提醒只返回当前登录资产的(按 ref_key 匹配,卡为 ICCID、设备为虚拟号或 IMEI),其他类型不受影响。当前 C 端契约只承诺列表展示和未读弹窗;ref_type/ref_id/ref_key 是资源引用与展示快照,不是URL,也不承诺可直接拼接页面路由。",
Tags: []string{"个人客户 - 站内通知"},
Input: new(dto.PersonalNotificationListRequest),
Output: new(dto.PersonalNotificationListResponse),
@@ -33,7 +33,7 @@ func registerPersonalNotificationRoutes(router fiber.Router, handler *apphandler
// 静态路径必须先于通知 ID 动态路径,避免被动态参数吞掉。
Register(notifications, doc, groupPath, "PUT", "/read-all", handler.MarkAllRead, RouteSpec{
Summary: "全部标记个人客户通知已读",
Description: "只更新当前认证个人客户可见的未过期未读业务通知,重复调用幂等成功。",
Description: "只更新当前认证个人客户可见的未过期未读业务通知,重复调用幂等成功;其他资产的套餐临期提醒保持未读。",
Tags: []string{"个人客户 - 站内通知"},
Output: new(dto.NotificationReadAllResponse),
Auth: true,

View File

@@ -7,7 +7,6 @@ import (
"gorm.io/gorm"
"gorm.io/gorm/clause"
accessauditapp "github.com/break/junhong_cmp_fiber/internal/application/accessaudit"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/pkg/config"
"github.com/break/junhong_cmp_fiber/pkg/errors"
@@ -88,15 +87,14 @@ func (s *Service) establishAssociation(
return s.associationWriter.Establish(ctx, tx, customer, phone, assetType, assetID)
}
// migrateAssociations 委托关联写入规则完成换绑原子迁移与上限/冲突判定。
// 开关关闭时完全短路,不迁移任何关联。
func (s *Service) migrateAssociations(
ctx context.Context,
tx *gorm.DB,
oldPhone, newPhone string,
) ([]accessauditapp.PhoneAssetAssociationChange, error) {
if !requirePhoneBinding() {
return nil, nil
// assetHasValidAssociation 判断当前访问资产是否已有任一有效手机号关联;开关关闭或无资产身份时返回 false。
func (s *Service) assetHasValidAssociation(ctx context.Context, tx *gorm.DB, assetType string, assetID uint) (bool, error) {
if !requirePhoneBinding() || assetType == "" || assetID == 0 {
return false, nil
}
return s.associationWriter.Migrate(ctx, tx, oldPhone, newPhone)
phones, err := s.associationStore.WithTx(tx).ListValidByAsset(ctx, assetType, assetID)
if err != nil {
return false, errors.Wrap(errors.CodeInternalError, err, "查询资产手机号关联失败")
}
return len(phones) > 0, nil
}

View File

@@ -197,7 +197,7 @@ func (s *Service) WechatLogin(ctx context.Context, req *dto.WechatLoginRequest,
return nil, err
}
token, needBindPhone, err := s.issueLoginToken(ctx, customerID, assetClaims.AssetType, assetClaims.AssetID)
token, bindState, err := s.issueLoginToken(ctx, customerID, assetClaims.AssetType, assetClaims.AssetID)
if err != nil {
return nil, err
}
@@ -208,9 +208,11 @@ func (s *Service) WechatLogin(ctx context.Context, req *dto.WechatLoginRequest,
)
return &dto.WechatLoginResponse{
Token: token,
NeedBindPhone: needBindPhone,
IsNewUser: isNewUser,
Token: token,
NeedBindPhone: bindState.NeedBindPhone,
AssetPhoneBound: bindState.AssetPhoneBound,
AssetPhoneIsOwn: bindState.AssetPhoneIsOwn,
IsNewUser: isNewUser,
}, nil
}
@@ -256,7 +258,7 @@ func (s *Service) MiniappLogin(ctx context.Context, req *dto.MiniappLoginRequest
return nil, err
}
token, needBindPhone, err := s.issueLoginToken(ctx, customerID, assetClaims.AssetType, assetClaims.AssetID)
token, bindState, err := s.issueLoginToken(ctx, customerID, assetClaims.AssetType, assetClaims.AssetID)
if err != nil {
return nil, err
}
@@ -267,9 +269,11 @@ func (s *Service) MiniappLogin(ctx context.Context, req *dto.MiniappLoginRequest
)
return &dto.WechatLoginResponse{
Token: token,
NeedBindPhone: needBindPhone,
IsNewUser: isNewUser,
Token: token,
NeedBindPhone: bindState.NeedBindPhone,
AssetPhoneBound: bindState.AssetPhoneBound,
AssetPhoneIsOwn: bindState.AssetPhoneIsOwn,
IsNewUser: isNewUser,
}, nil
}
@@ -299,8 +303,12 @@ func (s *Service) SendCode(ctx context.Context, req *dto.ClientSendCodeRequest,
// BindPhone A5 绑定手机号
// POST /api/c/v1/auth/bind-phone
// 无主手机号时建立账号手机号;已有主手机号且提交号码与主号一致、验证码有效时,
// 幂等建立当前访问资产与该手机号的关联且不修改账号手机号;提交号码与主号不一致仍拒绝。
// 客户手机号与资产手机号相互独立,按两侧状态分别写入:
// - 无主手机号、资产无有效关联:同时写客户手机号与资产关联;
// - 无主手机号、资产已有有效关联:只写客户手机号,不动资产关联;
// - 已有主手机号、资产无有效关联:只为资产建立关联,号码可与主号不同,不改客户手机号;
// - 已有主手机号、资产已有有效关联:同号幂等成功,其他号码按一资产一号拒绝。
//
// 请求不含当前访问资产身份时只完成账号手机号绑定,不建立关联。
func (s *Service) BindPhone(ctx context.Context, customerID uint, assetType string, assetID uint, req *dto.BindPhoneRequest) (*dto.BindPhoneResponse, error) {
if req == nil {
@@ -380,6 +388,11 @@ func (s *Service) BindPhone(ctx context.Context, customerID uint, assetType stri
)); err != nil {
return err
}
// 资产已有有效关联(无论号码属于谁)时只写客户手机号,不动资产关联。
assetBound, err := s.assetHasValidAssociation(ctx, tx, assetType, assetID)
if err != nil || assetBound {
return err
}
// 建联与账号手机号同事务:超限或写入失败时账号手机号一并回滚。
if _, err := s.establishAssociation(ctx, tx, customer, record.Phone, assetType, assetID); err != nil {
return err
@@ -397,8 +410,8 @@ func (s *Service) BindPhone(ctx context.Context, customerID uint, assetType stri
}, nil
}
// bindExistingPrimaryPhone 处理已有主手机号的绑定请求。
// 提交号码等于主号且验证码有效时幂等建立关联且不改账号手机号;号码不一致仍拒绝换号。
// bindExistingPrimaryPhone 处理已有主手机号的绑定请求:只为当前访问资产建立关联,不改账号手机号。
// 强制绑定开启且带资产身份时,资产侧号码可与主号不同;否则提交号码必须等于主号(不支持经绑定入口换号)。
func (s *Service) bindExistingPrimaryPhone(
ctx context.Context,
customer *model.PersonalCustomer,
@@ -407,7 +420,8 @@ func (s *Service) bindExistingPrimaryPhone(
assetID uint,
req *dto.BindPhoneRequest,
) (*dto.BindPhoneResponse, error) {
if primary.Phone != req.Phone {
assetBinding := requirePhoneBinding() && assetType != "" && assetID != 0
if primary.Phone != req.Phone && !assetBinding {
appErr := errors.New(errors.CodeAlreadyBoundPhone)
s.recordPersonalFailure(ctx, constants.AuditActionPersonalCustomerPhoneBound, "绑定个人手机号被拒绝", customer, primary, appErr)
return nil, appErr
@@ -421,7 +435,7 @@ func (s *Service) bindExistingPrimaryPhone(
now := time.Now()
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// 固定加锁次序:先取手机号串行化点(advisory),再按 id ASC 锁行。
if err := s.lockPhoneScopesInOrder(ctx, tx, primary.Phone); err != nil {
if err := s.lockPhoneScopesInOrder(ctx, tx, req.Phone); err != nil {
return err
}
if err := s.lockPhoneRowsInIDOrder(ctx, tx, []uint{primary.ID}); err != nil {
@@ -436,11 +450,11 @@ func (s *Service) bindExistingPrimaryPhone(
}
return errors.Wrap(errors.CodeInternalError, err, "查询主手机号失败")
}
if locked.Phone != req.Phone {
if !assetBinding && locked.Phone != req.Phone {
// 并发换绑已把主号改成其他号码:提交号码不再等于账号手机号,按既有语义拒绝。
return errors.New(errors.CodeAlreadyBoundPhone)
}
_, err := s.establishAssociation(ctx, tx, customer, locked.Phone, assetType, assetID)
_, err := s.establishAssociation(ctx, tx, customer, req.Phone, assetType, assetID)
return err
})
if err != nil {
@@ -498,9 +512,8 @@ func (s *Service) ChangePhone(ctx context.Context, customerID uint, req *dto.Cha
now := time.Now()
var beforeData map[string]any
var failurePhone *model.PersonalCustomerPhone
var migrationChanges []accessauditapp.PhoneAssetAssociationChange
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// 统一加锁顺序:先按手机号行 id ASC 锁定旧、新手机号行,再由关联迁移按 id ASC 锁定两侧有效关系行。
// 统一加锁顺序:先取旧、新手机号串行化点,再按手机号行 id ASC 锁定旧、新手机号行。
// 换绑两行的加锁顺序与 bind-phone 的单行加锁一致,两条路径不会形成 A→B / B→A 死锁环。
if idErr := s.lockPhoneScopesInOrder(ctx, tx, primary.Phone, req.NewPhone); idErr != nil {
return idErr
@@ -533,12 +546,7 @@ func (s *Service) ChangePhone(ctx context.Context, customerID uint, req *dto.Cha
} else if err != nil && err != gorm.ErrRecordNotFound {
return errors.Wrap(errors.CodeInternalError, err, "查询新手机号绑定关系失败")
}
// 关联迁移先于账号手机号改写:超限或与既有关系冲突时整次失败,旧、新关系均保持原状。
changes, migrateErr := s.migrateAssociations(ctx, tx, primary.Phone, req.NewPhone)
if migrateErr != nil {
return migrateErr
}
migrationChanges = changes
// 客户手机号与资产手机号相互独立:换号只改客户手机号,不迁移、复制或失效任何资产关联。
if err := tx.Model(primary).Updates(map[string]any{
"phone": req.NewPhone,
"verified_at": now,
@@ -548,22 +556,10 @@ func (s *Service) ChangePhone(ctx context.Context, customerID uint, req *dto.Cha
}
primary.Phone = req.NewPhone
primary.VerifiedAt = &now
if err := s.accessAudit.WriteAccessChange(ctx, tx, personalPhoneAudit(
return s.accessAudit.WriteAccessChange(ctx, tx, personalPhoneAudit(
constants.AuditActionPersonalCustomerPhoneChanged, "更换个人手机号", customer, primary, beforeData,
map[string]any{"phone": sanitizer.MaskPhone(primary.Phone)}, "手机号已更换", constants.AuditResultSuccess,
)); err != nil {
return err
}
if len(migrationChanges) == 0 {
return nil
}
return s.accessAudit.WriteAccessChange(ctx, tx, accessauditapp.ChangeAudit{
ActionCode: constants.AuditActionPhoneAssetAssociationMigrated,
Summary: "换绑手机号并迁移资产关联",
OperatorID: customer.ID, ActorKind: constants.AuditActorPersonalCustomer, ActorName: customer.Nickname,
Source: constants.AuditSourcePersonalAPI, ScopeType: constants.AuditScopePersonalCustomer,
PhoneAssociations: migrationChanges,
})
))
})
if err != nil {
if failurePhone == nil {
@@ -1014,10 +1010,10 @@ func (s *Service) bindAsset(ctx context.Context, tx *gorm.DB, customerID uint, a
// 已存在有效关系 → false。全局开关关闭时恒为 false,且不查询、不创建、不删除任何关系。
// 关联查询使用当前访问资产的 asset_type/asset_id,不使用 phone claim:phone 是登录时快照,
// 换绑后到下次登录前仍是旧号。该字段只作前端提示,不改变任何资源授权。
func (s *Service) issueLoginToken(ctx context.Context, customerID uint, assetType string, assetID uint) (string, bool, error) {
func (s *Service) issueLoginToken(ctx context.Context, customerID uint, assetType string, assetID uint) (string, loginBindState, error) {
// 查询用户已绑定的主手机号,写入 JWT,供后续接口直接从 context 取用
var boundPhone string
needBindPhone := false
state := loginBindState{}
cfg := config.Get()
requirePhoneBinding := true
if cfg != nil {
@@ -1027,30 +1023,26 @@ func (s *Service) issueLoginToken(ctx context.Context, customerID uint, assetTyp
if phoneErr == nil {
boundPhone = primaryPhone.Phone
} else if phoneErr != gorm.ErrRecordNotFound {
return "", false, errors.Wrap(errors.CodeInternalError, phoneErr, "查询手机号绑定关系失败")
return "", state, errors.Wrap(errors.CodeInternalError, phoneErr, "查询手机号绑定关系失败")
}
// 开关关闭必须完全短路:既不查询也不写任何关系,否则会出现「关闭开关却写库」的越权写入。
if requirePhoneBinding {
if boundPhone == "" {
needBindPhone = true
} else {
associated, err := s.associationStore.ExistsValid(ctx, boundPhone, assetType, assetID)
if err != nil {
return "", false, errors.Wrap(errors.CodeInternalError, err, "查询手机号资产关联失败")
}
needBindPhone = !associated
resolved, err := s.resolveLoginBindState(ctx, boundPhone, assetType, assetID)
if err != nil {
return "", state, err
}
state = resolved
}
token, err := s.jwtManager.GeneratePersonalCustomerToken(customerID, boundPhone, assetType, assetID)
if err != nil {
return "", false, errors.Wrap(errors.CodeInternalError, err, "生成登录令牌失败")
return "", state, errors.Wrap(errors.CodeInternalError, err, "生成登录令牌失败")
}
claims, err := s.jwtManager.VerifyPersonalCustomerToken(token)
if err != nil {
return "", false, errors.Wrap(errors.CodeInternalError, err, "解析登录令牌失败")
return "", state, errors.Wrap(errors.CodeInternalError, err, "解析登录令牌失败")
}
ttl := time.Until(claims.ExpiresAt.Time)
@@ -1060,10 +1052,38 @@ func (s *Service) issueLoginToken(ctx context.Context, customerID uint, assetTyp
redisKey := constants.RedisPersonalCustomerTokenKey(customerID)
if err := s.redis.Set(ctx, redisKey, token, ttl).Err(); err != nil {
return "", false, errors.Wrap(errors.CodeRedisError, err, "保存登录状态失败")
return "", state, errors.Wrap(errors.CodeRedisError, err, "保存登录状态失败")
}
return token, needBindPhone, nil
return token, state, nil
}
// loginBindState 是登录响应的手机号绑定提示,只含布尔值,不含号码。
type loginBindState struct {
NeedBindPhone bool
AssetPhoneBound bool
AssetPhoneIsOwn bool
}
// resolveLoginBindState 按客户主手机号与当前资产有效关联判定绑定提示:
// 客户无主手机号仍需绑定;资产尚无有效关联需为资产绑定;资产已有有效关联(无论号码属于谁)且客户有主手机号时不需绑定。
func (s *Service) resolveLoginBindState(ctx context.Context, boundPhone, assetType string, assetID uint) (loginBindState, error) {
state := loginBindState{}
if assetType != "" && assetID != 0 {
assetPhones, err := s.associationStore.ListValidByAsset(ctx, assetType, assetID)
if err != nil {
return state, errors.Wrap(errors.CodeInternalError, err, "查询资产手机号关联失败")
}
state.AssetPhoneBound = len(assetPhones) > 0
for _, phone := range assetPhones {
if boundPhone != "" && phone == boundPhone {
state.AssetPhoneIsOwn = true
break
}
}
}
state.NeedBindPhone = boundPhone == "" || !state.AssetPhoneBound
return state, nil
}
// DevLogin 开发环境测试登录

View File

@@ -98,58 +98,6 @@ func deviceAuditChange(device *model.Device, relation, role string, beforeData,
}
}
func (s *Service) loadAuditAssets(ctx context.Context, tx *gorm.DB, oldType string, oldID uint, newType string, newID uint) ([]accessauditapp.IotCardChange, []accessauditapp.DeviceChange, error) {
cards := make([]accessauditapp.IotCardChange, 0, 2)
devices := make([]accessauditapp.DeviceChange, 0, 2)
appendAsset := func(assetType string, assetID uint, role string) error {
switch normalizeAssetType(assetType) {
case assetTypeIotCard:
card, err := s.readCard(ctx, tx, assetID)
if err != nil {
return err
}
cards = append(cards, cardAuditChange(card, constants.AuditResourceRelationAffected, role, nil, nil))
case assetTypeDevice:
device, err := s.readDevice(ctx, tx, assetID)
if err != nil {
return err
}
devices = append(devices, deviceAuditChange(device, constants.AuditResourceRelationAffected, role, nil, nil))
default:
return errors.New(errors.CodeInvalidParam, "无效的资产类型")
}
return nil
}
if err := appendAsset(oldType, oldID, constants.AuditResourceRolePersonalCustomerOldAsset); err != nil {
return nil, nil, err
}
if err := appendAsset(newType, newID, constants.AuditResourceRolePersonalCustomerNewAsset); err != nil {
return nil, nil, err
}
return cards, devices, nil
}
func (s *Service) writeMigrationAudit(
ctx context.Context,
tx *gorm.DB,
customerID uint,
oldType string,
oldID uint,
newType string,
newID uint,
personalDevices []accessauditapp.PersonalCustomerDeviceChange,
personalICCIDs []accessauditapp.PersonalCustomerICCIDChange,
) error {
cards, devices, err := s.loadAuditAssets(ctx, tx, oldType, oldID, newType, newID)
if err != nil {
return err
}
return s.writeBindingAudit(
ctx, tx, constants.AuditActionPersonalCustomerAssetBindingMigrated, "换货迁移个人客户资产绑定",
customerID, personalDevices, personalICCIDs, cards, devices,
)
}
// UnbindByVirtualNo 按现有换货重置语义删除设备号绑定,并在同一事务记录实际删除关系。
func (s *Service) UnbindByVirtualNo(ctx context.Context, tx *gorm.DB, assetType string, assetID uint, virtualNo string) error {
if s.accessAudit == nil {

View File

@@ -349,273 +349,103 @@ func (s *Service) bindViaPCI(ctx context.Context, pci pciOps, tx *gorm.DB, custo
}, nil)
}
// Migrate 将旧资产的所有有效客户绑定迁移到新资产(换货专用)
// 无绑定时静默跳过;按旧/新资产虚拟号有无路由到 pcd 或 pci
func (s *Service) Migrate(ctx context.Context, tx *gorm.DB, oldAssetType string, oldAssetID uint, newAssetType string, newAssetID uint) error {
// ClearForExchange 换货完成时在同一事务内把旧资产的全部有效个人客户绑定置为无效,不迁移到新资产。
// 定位口径同原换货迁移:卡的虚拟号绑定与 ICCID 绑定两边都清;设备按虚拟号,无虚拟号时按 IMEI。
// 原客户之后重新扫码旧资产仍可按既有登录规则重新建立绑定。
func (s *Service) ClearForExchange(ctx context.Context, tx *gorm.DB, oldAssetType string, oldAssetID uint) error {
if s.accessAudit == nil {
return errors.New(errors.CodeInvalidStatus, "个人客户资产审计接缝未配置")
}
if tx == nil {
tx = s.db
}
pcd := s.makePCD(tx)
pci := s.makePCI(tx)
switch normalizeAssetType(oldAssetType) {
case assetTypeIotCard:
oldCard, err := s.readCard(ctx, tx, oldAssetID)
card, err := s.readCard(ctx, tx, oldAssetID)
if err != nil {
return err
}
if oldCard.VirtualNo != "" {
return s.migrateFromPCD(ctx, tx, pcd, pci, oldCard.VirtualNo, oldAssetType, oldAssetID, newAssetType, newAssetID)
assetChange := []accessauditapp.IotCardChange{cardAuditChange(card, constants.AuditResourceRelationAffected, constants.AuditResourceRolePersonalCustomerOldAsset, nil, nil)}
if card.VirtualNo != "" {
if err := s.clearDeviceBindings(ctx, tx, card.VirtualNo, assetChange, nil); err != nil {
return err
}
}
return s.migrateFromPCI(ctx, tx, pcd, pci, oldCard.ICCID, oldAssetType, oldAssetID, newAssetType, newAssetID)
return s.clearICCIDBindings(ctx, tx, card.ICCID, assetChange)
case assetTypeDevice:
oldDevice, err := s.readDevice(ctx, tx, oldAssetID)
device, err := s.readDevice(ctx, tx, oldAssetID)
if err != nil {
return err
}
key := oldDevice.VirtualNo
key := device.VirtualNo
if key == "" {
key = oldDevice.IMEI
key = device.IMEI
}
return s.migrateFromPCD(ctx, tx, pcd, pci, key, oldAssetType, oldAssetID, newAssetType, newAssetID)
if key == "" {
return nil
}
assetChange := []accessauditapp.DeviceChange{deviceAuditChange(device, constants.AuditResourceRelationAffected, constants.AuditResourceRolePersonalCustomerOldAsset, nil, nil)}
return s.clearDeviceBindings(ctx, tx, key, nil, assetChange)
}
return errors.New(errors.CodeInvalidParam)
}
// migrateFromPCD 将 tb_personal_customer_device 中 oldKey 的所有有效绑定迁移到新资产
func (s *Service) migrateFromPCD(ctx context.Context, db *gorm.DB, pcd pcdOps, pci pciOps, oldKey string, oldAssetType string, oldAssetID uint, newAssetType string, newAssetID uint) error {
records, err := pcd.GetByDeviceNo(ctx, oldKey)
// clearDeviceBindings 把按虚拟号(或 IMEI)定位的有效绑定置为无效并逐条写审计。
func (s *Service) clearDeviceBindings(ctx context.Context, tx *gorm.DB, key string, cards []accessauditapp.IotCardChange, devices []accessauditapp.DeviceChange) error {
pcd := s.makePCD(tx)
records, err := pcd.GetByDeviceNo(ctx, key)
if err != nil {
return errors.Wrap(errors.CodeInternalError, err, "查询旧资产绑定记录失败")
return errors.Wrap(errors.CodeInternalError, err, "查询旧资产客户绑定失败")
}
// 仅处理 status=1 的有效记录
var active []*model.PersonalCustomerDevice
for _, r := range records {
if r.Status == 1 {
active = append(active, r)
for _, record := range records {
if record == nil || record.Status != 1 {
continue
}
}
if len(active) == 0 {
return nil
}
switch normalizeAssetType(newAssetType) {
case assetTypeIotCard:
newCard, err := s.readCard(ctx, db, newAssetID)
if err != nil {
if err := pcd.UpdateStatus(ctx, record.ID, 0); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "清空旧资产客户绑定失败")
}
if err := s.writeBindingAudit(
ctx, tx, constants.AuditActionPersonalCustomerAssetUnbound, "换货完成清空旧资产个人客户绑定", record.CustomerID,
[]accessauditapp.PersonalCustomerDeviceChange{{
Binding: record, Role: constants.AuditResourceRolePersonalCustomerOldAssetBinding,
BeforeData: map[string]any{"virtual_no": record.VirtualNo, "status": record.Status},
AfterData: map[string]any{"virtual_no": record.VirtualNo, "status": 0},
}}, nil, cards, devices,
); err != nil {
return err
}
if newCard.VirtualNo != "" {
// 新卡有虚拟号:更新 pcd virtual_no
for _, rec := range active {
if err := pcd.UpdateVirtualNo(ctx, rec.ID, newCard.VirtualNo); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "迁移客户绑定关系失败")
}
after := *rec
after.VirtualNo = newCard.VirtualNo
if err := s.writeMigrationAudit(ctx, db, rec.CustomerID, oldAssetType, oldAssetID, newAssetType, newAssetID,
[]accessauditapp.PersonalCustomerDeviceChange{{
Binding: &after, Role: constants.AuditResourceRolePersonalCustomerAssetBinding,
BeforeData: map[string]any{"virtual_no": rec.VirtualNo, "status": rec.Status},
AfterData: map[string]any{"virtual_no": after.VirtualNo, "status": after.Status},
}}, nil); err != nil {
return err
}
}
} else {
// 新卡无虚拟号:禁用旧 pcd + 创建新 pci
iccid19 := newCard.ICCID
if len(newCard.ICCID) == 20 {
iccid19 = newCard.ICCID[:19]
}
for _, rec := range active {
if err := pcd.UpdateStatus(ctx, rec.ID, 0); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "禁用旧客户绑定关系失败")
}
newPCI := &model.PersonalCustomerICCID{
CustomerID: rec.CustomerID,
ICCID: newCard.ICCID,
ICCID19: iccid19,
Status: 1,
}
if err := pci.Create(ctx, newPCI); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "创建新客户绑定关系失败")
}
if err := s.writeMigrationAudit(ctx, db, rec.CustomerID, oldAssetType, oldAssetID, newAssetType, newAssetID,
[]accessauditapp.PersonalCustomerDeviceChange{{
Binding: rec, Role: constants.AuditResourceRolePersonalCustomerOldAssetBinding,
BeforeData: map[string]any{"virtual_no": rec.VirtualNo, "status": rec.Status},
AfterData: map[string]any{"virtual_no": rec.VirtualNo, "status": 0},
}}, []accessauditapp.PersonalCustomerICCIDChange{{
Binding: newPCI, Role: constants.AuditResourceRolePersonalCustomerNewAssetBinding,
AfterData: map[string]any{"iccid": newPCI.ICCID, "status": newPCI.Status},
}}); err != nil {
return err
}
}
}
case assetTypeDevice:
newDevice, err := s.readDevice(ctx, db, newAssetID)
if err != nil {
return err
}
newKey := newDevice.VirtualNo
if newKey == "" {
newKey = newDevice.IMEI
}
for _, rec := range active {
if err := pcd.UpdateVirtualNo(ctx, rec.ID, newKey); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "迁移设备客户绑定关系失败")
}
after := *rec
after.VirtualNo = newKey
if err := s.writeMigrationAudit(ctx, db, rec.CustomerID, oldAssetType, oldAssetID, newAssetType, newAssetID,
[]accessauditapp.PersonalCustomerDeviceChange{{
Binding: &after, Role: constants.AuditResourceRolePersonalCustomerAssetBinding,
BeforeData: map[string]any{"virtual_no": rec.VirtualNo, "status": rec.Status},
AfterData: map[string]any{"virtual_no": after.VirtualNo, "status": after.Status},
}}, nil); err != nil {
return err
}
}
default:
return errors.New(errors.CodeInvalidParam)
}
return nil
}
// migrateFromPCI 将 tb_personal_customer_iccid 中 oldICCID 的所有有效绑定迁移到新资产
func (s *Service) migrateFromPCI(ctx context.Context, db *gorm.DB, pcd pcdOps, pci pciOps, oldICCID string, oldAssetType string, oldAssetID uint, newAssetType string, newAssetID uint) error {
records, err := pci.GetByICCID(ctx, oldICCID)
if err != nil {
return errors.Wrap(errors.CodeInternalError, err, "查询旧 ICCID 绑定记录失败")
}
var active []*model.PersonalCustomerICCID
for _, r := range records {
if r.Status == 1 {
active = append(active, r)
}
}
if len(active) == 0 {
// clearICCIDBindings 把按 ICCID 定位的有效绑定置为无效并逐条写审计。
func (s *Service) clearICCIDBindings(ctx context.Context, tx *gorm.DB, iccid string, cards []accessauditapp.IotCardChange) error {
if iccid == "" {
return nil
}
switch normalizeAssetType(newAssetType) {
case assetTypeIotCard:
newCard, err := s.readCard(ctx, db, newAssetID)
if err != nil {
return err
}
if newCard.VirtualNo != "" {
// 新卡有虚拟号:禁用旧 pci + 创建新 pcd
for _, rec := range active {
if err := pci.UpdateStatus(ctx, rec.ID, 0); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "禁用旧 ICCID 绑定关系失败")
}
newPCD := &model.PersonalCustomerDevice{
CustomerID: rec.CustomerID,
VirtualNo: newCard.VirtualNo,
Status: 1,
}
if err := pcd.Create(ctx, newPCD); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "创建新客户绑定关系失败")
}
if err := s.writeMigrationAudit(ctx, db, rec.CustomerID, oldAssetType, oldAssetID, newAssetType, newAssetID,
[]accessauditapp.PersonalCustomerDeviceChange{{
Binding: newPCD, Role: constants.AuditResourceRolePersonalCustomerNewAssetBinding,
AfterData: map[string]any{"virtual_no": newPCD.VirtualNo, "status": newPCD.Status},
}}, []accessauditapp.PersonalCustomerICCIDChange{{
Binding: rec, Role: constants.AuditResourceRolePersonalCustomerOldAssetBinding,
BeforeData: map[string]any{"iccid": rec.ICCID, "status": rec.Status},
AfterData: map[string]any{"iccid": rec.ICCID, "status": 0},
}}); err != nil {
return err
}
}
} else {
// 新卡也无虚拟号:禁用旧 pci + 创建新 pci(新 ICCID)
iccid19 := newCard.ICCID
if len(newCard.ICCID) == 20 {
iccid19 = newCard.ICCID[:19]
}
for _, rec := range active {
if err := pci.UpdateStatus(ctx, rec.ID, 0); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "禁用旧 ICCID 绑定关系失败")
}
newPCI := &model.PersonalCustomerICCID{
CustomerID: rec.CustomerID,
ICCID: newCard.ICCID,
ICCID19: iccid19,
Status: 1,
}
if err := pci.Create(ctx, newPCI); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "创建新 ICCID 绑定关系失败")
}
if err := s.writeMigrationAudit(ctx, db, rec.CustomerID, oldAssetType, oldAssetID, newAssetType, newAssetID,
nil, []accessauditapp.PersonalCustomerICCIDChange{
{
Binding: rec, Role: constants.AuditResourceRolePersonalCustomerOldAssetBinding,
BeforeData: map[string]any{"iccid": rec.ICCID, "status": rec.Status},
AfterData: map[string]any{"iccid": rec.ICCID, "status": 0},
},
{
Binding: newPCI, Role: constants.AuditResourceRolePersonalCustomerNewAssetBinding,
AfterData: map[string]any{"iccid": newPCI.ICCID, "status": newPCI.Status},
},
}); err != nil {
return err
}
}
}
case assetTypeDevice:
newDevice, err := s.readDevice(ctx, db, newAssetID)
if err != nil {
return err
}
newKey := newDevice.VirtualNo
if newKey == "" {
newKey = newDevice.IMEI
}
for _, rec := range active {
if err := pci.UpdateStatus(ctx, rec.ID, 0); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "禁用旧 ICCID 绑定关系失败")
}
newPCD := &model.PersonalCustomerDevice{
CustomerID: rec.CustomerID,
VirtualNo: newKey,
Status: 1,
}
if err := pcd.Create(ctx, newPCD); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "创建新客户绑定关系失败")
}
if err := s.writeMigrationAudit(ctx, db, rec.CustomerID, oldAssetType, oldAssetID, newAssetType, newAssetID,
[]accessauditapp.PersonalCustomerDeviceChange{{
Binding: newPCD, Role: constants.AuditResourceRolePersonalCustomerNewAssetBinding,
AfterData: map[string]any{"virtual_no": newPCD.VirtualNo, "status": newPCD.Status},
}}, []accessauditapp.PersonalCustomerICCIDChange{{
Binding: rec, Role: constants.AuditResourceRolePersonalCustomerOldAssetBinding,
BeforeData: map[string]any{"iccid": rec.ICCID, "status": rec.Status},
AfterData: map[string]any{"iccid": rec.ICCID, "status": 0},
}}); err != nil {
return err
}
}
default:
return errors.New(errors.CodeInvalidParam)
pci := s.makePCI(tx)
records, err := pci.GetByICCID(ctx, iccid)
if err != nil {
return errors.Wrap(errors.CodeInternalError, err, "查询旧 ICCID 客户绑定失败")
}
for _, record := range records {
if record == nil || record.Status != 1 {
continue
}
if err := pci.UpdateStatus(ctx, record.ID, 0); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "清空旧 ICCID 客户绑定失败")
}
if err := s.writeBindingAudit(
ctx, tx, constants.AuditActionPersonalCustomerAssetUnbound, "换货完成清空旧资产个人客户绑定", record.CustomerID,
nil, []accessauditapp.PersonalCustomerICCIDChange{{
Binding: record, Role: constants.AuditResourceRolePersonalCustomerOldAssetBinding,
BeforeData: map[string]any{"iccid": record.ICCID, "status": record.Status},
AfterData: map[string]any{"iccid": record.ICCID, "status": 0},
}}, cards, nil,
); err != nil {
return err
}
}
return nil
}

View File

@@ -0,0 +1,93 @@
package exchange
import (
"context"
"time"
"gorm.io/gorm"
accessauditapp "github.com/break/junhong_cmp_fiber/internal/application/accessaudit"
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/errors"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
"github.com/break/junhong_cmp_fiber/pkg/sanitizer"
)
// exchangeNewAssetPhoneBoundMessage 新资产已绑定手机号时的拒绝提示,不含号码。
const exchangeNewAssetPhoneBoundMessage = "新资产已绑定手机号,请先在后台解除该资产的手机号绑定,再重新提交换货申请"
// SetPhoneAssetAssociationStore 注入手机号—资产关联存储,用于换货校验与换货完成失效旧资产关联。
func (s *Service) SetPhoneAssetAssociationStore(store *postgres.PhoneAssetAssociationStore) {
s.phoneAssociationStore = store
}
// ensureNewAssetPhoneUnboundWithTx 新资产存在有效手机号关联时拒绝换货。
// 完整号码只放在错误响应 data.phone 中,错误信息与日志不含号码。
func (s *Service) ensureNewAssetPhoneUnboundWithTx(ctx context.Context, tx *gorm.DB, newAsset *resolvedExchangeAsset) error {
if s.phoneAssociationStore == nil {
return errors.New(errors.CodeInvalidStatus, "手机号资产关联存储未配置")
}
phones, err := s.phoneAssociationStore.WithTx(tx).ListValidByAsset(ctx, newAsset.AssetType, newAsset.AssetID)
if err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "查询新资产手机号关联失败")
}
if len(phones) == 0 {
return nil
}
return errors.NewWithData(errors.CodeExchangeStatusInvalid, map[string]any{"phone": phones[0]}, exchangeNewAssetPhoneBoundMessage)
}
// invalidateOldAssetPhoneAssociationsWithTx 换货完成时在同一事务内失效旧资产全部有效手机号关联,释放号码名额。
// 旧资产无有效关联时跳过;操作人为确认换货完成的账号,审计只写脱敏手机号。
func (s *Service) invalidateOldAssetPhoneAssociationsWithTx(ctx context.Context, tx *gorm.DB, oldAsset *resolvedExchangeAsset) error {
if s.phoneAssociationStore == nil {
return errors.New(errors.CodeInvalidStatus, "手机号资产关联存储未配置")
}
store := s.phoneAssociationStore.WithTx(tx)
rows, err := store.LockValidByAsset(ctx, tx, oldAsset.AssetType, oldAsset.AssetID)
if err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "锁定旧资产手机号关联失败")
}
if len(rows) == 0 {
return nil
}
if s.auditWriter == nil {
return errors.New(errors.CodeInvalidStatus, "换货审计接缝未配置")
}
ids := make([]uint, 0, len(rows))
for _, row := range rows {
ids = append(ids, row.ID)
}
now := time.Now()
method, reason := constants.PhoneAssetAssociationInvalidateMethodExchangeCompleted, constants.PhoneAssetAssociationExchangeCompletedReason
operatorID, operatorName := middleware.GetUserIDFromContext(ctx), middleware.GetUsernameFromContext(ctx)
affected, err := store.InvalidateByIDs(ctx, tx, ids, method, reason, operatorID, operatorName, now)
if err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "失效旧资产手机号关联失败")
}
if int(affected) != len(rows) {
return errors.New(errors.CodeConflict, "旧资产手机号关联已变化,请重试")
}
changes := make([]accessauditapp.PhoneAssetAssociationChange, 0, len(rows))
for _, row := range rows {
changes = append(changes, accessauditapp.PhoneAssetAssociationChange{
AssociationID: row.ID, PhoneMasked: sanitizer.MaskPhone(row.Phone),
AssetType: row.AssetType, AssetID: row.AssetID, AssetDisplayName: oldAsset.Identifier,
Status: constants.PhoneAssetAssociationStatusInvalid, Source: row.Source,
InvalidatedAt: &now, InvalidationMethod: method, InvalidationReason: reason,
BeforeData: map[string]any{"status": constants.PhoneAssetAssociationStatusValid},
AfterData: map[string]any{
"status": constants.PhoneAssetAssociationStatusInvalid,
"invalidated_at": now, "invalidation_method": method, "invalidation_reason": reason,
},
})
}
return s.auditWriter.WriteAccessChange(ctx, tx, accessauditapp.ChangeAudit{
ActionCode: constants.AuditActionPhoneAssetAssociationUnbound,
Summary: "换货完成失效旧资产手机号关联",
OperatorID: operatorID, ActorKind: constants.AuditActorAccount, ActorName: operatorName,
Source: constants.AuditSourceAdminAPI, ScopeType: constants.AuditScopePlatform,
PhoneAssociations: changes,
})
}

View File

@@ -31,6 +31,7 @@ type Service struct {
packageUsageDailyRecordStore *postgres.PackageUsageDailyRecordStore
resourceTagStore *postgres.ResourceTagStore
customerBinding *customerBindingSvc.Service
phoneAssociationStore *postgres.PhoneAssetAssociationStore
shippingCreatedNotifier *exchangeapp.ShippingCreatedNotifier
auditWriter *audit.Writer
logger *zap.Logger
@@ -1068,26 +1069,17 @@ func (s *Service) validateExchangeAssetsWithTx(ctx context.Context, tx *gorm.DB,
return nil
}
// ensureNewAssetBindingAvailableWithTx 新资产已绑定手机号时拒绝换货;不再以“有人扫过码”(客户绑定)作为拒绝依据。
func (s *Service) ensureNewAssetBindingAvailableWithTx(ctx context.Context, tx *gorm.DB, oldAsset, newAsset *resolvedExchangeAsset) error {
newKey := exchangeAssetBindingKey(newAsset)
// 新资产无虚拟号时不再拦截:Migrate() 已能正确处理无绑定跳过、有绑定迁移到 pci 的情形
if newKey == "" {
return nil
}
var newBindCount int64
if err := tx.WithContext(ctx).Model(&model.PersonalCustomerDevice{}).
Where("virtual_no = ? AND status = ?", newKey, constants.StatusEnabled).
Count(&newBindCount).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "查询新资产客户绑定失败")
}
if newBindCount > 0 {
return errors.New(errors.CodeExchangeStatusInvalid, "新资产存在有效客户绑定,不可用于换货")
}
return nil
return s.ensureNewAssetPhoneUnboundWithTx(ctx, tx, newAsset)
}
// switchCustomerBindingWithTx 换货完成时清空旧资产的客户绑定并失效旧资产手机号关联,均不迁移到新资产。
func (s *Service) switchCustomerBindingWithTx(ctx context.Context, tx *gorm.DB, oldAsset, newAsset *resolvedExchangeAsset) error {
return s.customerBinding.Migrate(ctx, tx, oldAsset.AssetType, oldAsset.AssetID, newAsset.AssetType, newAsset.AssetID)
if err := s.customerBinding.ClearForExchange(ctx, tx, oldAsset.AssetType, oldAsset.AssetID); err != nil {
return err
}
return s.invalidateOldAssetPhoneAssociationsWithTx(ctx, tx, oldAsset)
}
// syncNewAssetOwnershipWithTx 将新资产归属同步为旧资产当前归属。

View File

@@ -2,10 +2,8 @@ package phone_asset_association
import (
"context"
stderrors "errors"
"time"
"github.com/jackc/pgx/v5/pgconn"
"gorm.io/gorm"
accessauditapp "github.com/break/junhong_cmp_fiber/internal/application/accessaudit"
@@ -16,11 +14,7 @@ import (
"github.com/break/junhong_cmp_fiber/pkg/sanitizer"
)
// associationUniqueConstraint 是「有效关系」部分唯一索引名。
// 换绑迁移撞上它说明新号已存在同资产有效关系,必须整次失败而不是产生并存关系。
const associationUniqueConstraint = "uq_phone_asset_association_valid"
// AssociationWriter 承载手机号—资产关联的写入规则:幂等建联、换绑迁移与十项上限。
// AssociationWriter 承载手机号—资产关联的写入规则:一资产一号、幂等建联与十项上限。
// 关联只能由 H5 短信验证建立,因此这里不提供任何后台创建入口。
type AssociationWriter struct {
store *postgres.PhoneAssetAssociationStore
@@ -32,7 +26,7 @@ func NewAssociationWriter(store *postgres.PhoneAssetAssociationStore, auditWrite
return &AssociationWriter{store: store, audit: auditWriter}
}
// Establish 建立手机号与当前访问资产的有效关联;同一关系已存在时保持幂等。
// Establish 建立手机号与当前访问资产的有效关联;同一关系已存在时保持幂等,资产已绑定其他号码时拒绝。
// 串行化点:先取手机号事务级 advisory lock,再锁定该号码现有有效关系行,
// 使「计数」与「插入」同处临界区;新号没有行可锁时仍由 advisory lock 保证串行。
// 已达十项的手机号对已关联资产重复验证必须返回成功且不产生第二条关系,
@@ -50,6 +44,20 @@ func (w *AssociationWriter) Establish(
return false, nil
}
store := w.store.WithTx(tx)
// 一资产一号:先查后写,不加资产锁(两个号码同时为同一资产完成验证属已接受的极小概率,由只读统计发现后后台解除)。
assetPhones, err := store.ListValidByAsset(ctx, assetType, assetID)
if err != nil {
return false, errors.Wrap(errors.CodeDatabaseError, err, "查询资产有效手机号关联失败")
}
for _, bound := range assetPhones {
if bound == phone {
return false, nil
}
}
if len(assetPhones) > 0 {
// 提示与响应不含任何号码。
return false, errors.New(errors.CodeAssetPhoneAlreadyBound)
}
if err := store.LockPhoneScopes(ctx, phone); err != nil {
return false, errors.Wrap(errors.CodeDatabaseError, err, "锁定手机号串行化点失败")
}
@@ -102,64 +110,3 @@ func (w *AssociationWriter) Establish(
}
return true, nil
}
// Migrate 在同一事务内把旧号全部有效关联原子迁移到新号。
// 串行化点:先按号码字符串升序取旧、新手机号 advisory lock,再按 id ASC 锁定两侧有效关系行。
// 迁移前比较「新号现有有效关系数 + 旧号待迁移有效关系数」:超过十项整次失败,旧、新关系均不变。
// 与「新号已存在的同资产有效关系」冲突时整次失败回滚,不产生并存的有效关系。
// 返回每次迁移的审计事实;无有效关系时返回空。
func (w *AssociationWriter) Migrate(ctx context.Context, tx *gorm.DB, oldPhone, newPhone string) ([]accessauditapp.PhoneAssetAssociationChange, error) {
store := w.store.WithTx(tx)
if err := store.LockPhoneScopes(ctx, oldPhone, newPhone); err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "锁定手机号串行化点失败")
}
locked, err := store.LockValidByPhones(ctx, oldPhone, newPhone)
if err != nil {
return nil, errors.Wrap(errors.CodeDatabaseError, err, "锁定手机号关联资产失败")
}
pending := make([]*model.PhoneAssetAssociation, 0, len(locked))
newPhoneValidCount := 0
for _, row := range locked {
if row.Phone == oldPhone {
pending = append(pending, row)
continue
}
newPhoneValidCount++
}
if newPhoneValidCount+len(pending) > constants.PhoneAssetAssociationMaxValidPerPhone {
return nil, errors.New(errors.CodeInvalidStatus, constants.PhoneAssetAssociationLimitMessage)
}
if len(pending) == 0 {
return nil, nil
}
now := time.Now()
if err := tx.WithContext(ctx).Model(&model.PhoneAssetAssociation{}).
Where("phone = ? AND status = ?", oldPhone, constants.PhoneAssetAssociationStatusValid).
Updates(map[string]any{"phone": newPhone, "updated_at": now}).Error; err != nil {
if isAssociationUniqueViolation(err) {
return nil, errors.New(errors.CodeInvalidStatus, "新手机号已存在与待迁移资产相同的有效关联,换绑已回滚")
}
return nil, errors.Wrap(errors.CodeDatabaseError, err, "迁移手机号资产关联失败")
}
oldPhoneMasked, newPhoneMasked := sanitizer.MaskPhone(oldPhone), sanitizer.MaskPhone(newPhone)
changes := make([]accessauditapp.PhoneAssetAssociationChange, 0, len(pending))
for _, row := range pending {
changes = append(changes, accessauditapp.PhoneAssetAssociationChange{
AssociationID: row.ID, PhoneMasked: newPhoneMasked,
AssetType: row.AssetType, AssetID: row.AssetID,
Status: constants.PhoneAssetAssociationStatusValid, Source: row.Source,
BeforeData: map[string]any{"phone_masked": oldPhoneMasked},
AfterData: map[string]any{"phone_masked": newPhoneMasked},
})
}
return changes, nil
}
// isAssociationUniqueViolation 判断错误是否为有效关系部分唯一索引冲突。
func isAssociationUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
if !stderrors.As(err, &pgErr) {
return false
}
return pgErr.Code == "23505" && pgErr.ConstraintName == associationUniqueConstraint
}

View File

@@ -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)

View File

@@ -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

View File

@@ -0,0 +1,33 @@
-- 回滚 000239:恢复五张业务表原状态约束与列注释。
-- 执行前必须确认已无“审批提交失败”状态数据,否则重建约束会失败。
ALTER TABLE tb_employee_collection_application DROP CONSTRAINT IF EXISTS chk_employee_collection_application_status;
ALTER TABLE tb_employee_collection_application
ADD CONSTRAINT chk_employee_collection_application_status CHECK (status IN (0, 1, 2, 3));
COMMENT ON COLUMN tb_employee_collection_application.status IS '状态:0 审批中、1 已通过、2 已驳回、3 已撤销或已关闭';
ALTER TABLE tb_refund_request DROP CONSTRAINT IF EXISTS chk_refund_request_status;
ALTER TABLE tb_refund_request
ADD CONSTRAINT chk_refund_request_status CHECK (status IN (1, 2, 3, 4, 5, 6));
COMMENT ON COLUMN tb_refund_request.status IS '状态 1-待审批 2-已通过 3-已拒绝 4-已退回 5-原路退款处理中 6-原路退款失败';
ALTER TABLE tb_agent_distribution_registration DROP CONSTRAINT IF EXISTS chk_agent_distribution_registration_status;
ALTER TABLE tb_agent_distribution_registration
ADD CONSTRAINT chk_agent_distribution_registration_status CHECK (status IN (0, 1, 2));
COMMENT ON COLUMN tb_agent_distribution_registration.status IS '状态:0 待审批、1 已通过、2 已驳回';
ALTER TABLE tb_withdrawal_qualification DROP CONSTRAINT IF EXISTS chk_withdrawal_qualification_status;
ALTER TABLE tb_withdrawal_qualification
ADD CONSTRAINT chk_withdrawal_qualification_status CHECK (status IN (0, 1, 2, 3));
COMMENT ON COLUMN tb_withdrawal_qualification.status IS '状态:0 待审批、1 已通过有效、2 已驳回、3 已失效或已作废';
ALTER TABLE tb_agent_recharge_record DROP CONSTRAINT IF EXISTS chk_agent_recharge_status;
ALTER TABLE tb_agent_recharge_record
ADD CONSTRAINT chk_agent_recharge_status CHECK (status IN (1, 2, 3, 4, 5, 6));
COMMENT ON COLUMN tb_agent_recharge_record.status IS '充值状态:1-待支付 2-已支付 3-已完成 4-已关闭 5-已退款';
COMMENT ON COLUMN tb_commission_withdrawal_request.status IS '状态 1-待审核 2-已通过 3-已拒绝 4-已到账';
ALTER TABLE tb_approval_decision_delivery DROP CONSTRAINT IF EXISTS ck_approval_decision_delivery_decision;
ALTER TABLE tb_approval_decision_delivery
ADD CONSTRAINT ck_approval_decision_delivery_decision
CHECK (decision IN ('approved', 'rejected', 'cancelled', 'deleted', 'revoked_after_approved'));

View File

@@ -0,0 +1,35 @@
-- 审批提交失败终态:放宽五张业务表的状态约束,新增“审批提交失败”状态值(只放宽,不改既有数据)。
-- 核销申请 4、退款 7、扫码注册代理 3、提现资料资格 4、线下代理充值 7;佣金提现表无状态约束,只更新列注释(新增 5);
-- 另放宽审批决策投递表的决策取值,允许 submission_failed。
ALTER TABLE tb_employee_collection_application DROP CONSTRAINT IF EXISTS chk_employee_collection_application_status;
ALTER TABLE tb_employee_collection_application
ADD CONSTRAINT chk_employee_collection_application_status CHECK (status IN (0, 1, 2, 3, 4));
COMMENT ON COLUMN tb_employee_collection_application.status IS '状态:0 审批中、1 已通过、2 已驳回、3 已撤销或已关闭、4 审批提交失败';
ALTER TABLE tb_refund_request DROP CONSTRAINT IF EXISTS chk_refund_request_status;
ALTER TABLE tb_refund_request
ADD CONSTRAINT chk_refund_request_status CHECK (status IN (1, 2, 3, 4, 5, 6, 7));
COMMENT ON COLUMN tb_refund_request.status IS '状态 1-待审批 2-已通过 3-已拒绝 4-已退回 5-原路退款处理中 6-原路退款失败 7-审批提交失败';
ALTER TABLE tb_agent_distribution_registration DROP CONSTRAINT IF EXISTS chk_agent_distribution_registration_status;
ALTER TABLE tb_agent_distribution_registration
ADD CONSTRAINT chk_agent_distribution_registration_status CHECK (status IN (0, 1, 2, 3));
COMMENT ON COLUMN tb_agent_distribution_registration.status IS '状态:0 待审批、1 已通过、2 已驳回、3 审批提交失败';
ALTER TABLE tb_withdrawal_qualification DROP CONSTRAINT IF EXISTS chk_withdrawal_qualification_status;
ALTER TABLE tb_withdrawal_qualification
ADD CONSTRAINT chk_withdrawal_qualification_status CHECK (status IN (0, 1, 2, 3, 4));
COMMENT ON COLUMN tb_withdrawal_qualification.status IS '状态:0 待审批、1 已通过有效、2 已驳回、3 已失效或已作废、4 审批提交失败';
ALTER TABLE tb_agent_recharge_record DROP CONSTRAINT IF EXISTS chk_agent_recharge_status;
ALTER TABLE tb_agent_recharge_record
ADD CONSTRAINT chk_agent_recharge_status CHECK (status IN (1, 2, 3, 4, 5, 6, 7));
COMMENT ON COLUMN tb_agent_recharge_record.status IS '充值状态:1-待支付 2-已支付 3-已完成 4-已关闭 5-已退款 6-已驳回 7-审批提交失败';
COMMENT ON COLUMN tb_commission_withdrawal_request.status IS '状态 1-待审核 2-已通过 3-已拒绝 4-已到账 5-审批提交失败';
-- 审批核心在实例进入提交失败时写入 submission_failed 决策投递事实,放宽决策取值约束。
ALTER TABLE tb_approval_decision_delivery DROP CONSTRAINT IF EXISTS ck_approval_decision_delivery_decision;
ALTER TABLE tb_approval_decision_delivery
ADD CONSTRAINT ck_approval_decision_delivery_decision
CHECK (decision IN ('approved', 'rejected', 'cancelled', 'deleted', 'revoked_after_approved', 'submission_failed'));

View File

@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-11

View File

@@ -0,0 +1,47 @@
## Context
承接《第1批-8-9月迭代缺陷修复技术方案》(下称“方案”)第 5、6 节。
- `AssociationWriter.Establish`(`internal/service/phone_asset_association/association_write.go`)只限制一个手机号最多 10 个资产;部分唯一索引 `uq_phone_asset_association_valid (phone, asset_type, asset_id)`(迁移 `000223`)只防同号同资产重复。
- `BindPhone` 用同一号码同时写客户手机号与资产关联;`ChangePhone` 经 `migrateAssociations` 迁移关联;`need_bind_phone` 只看当前客户号码与资产是否关联。
- `ensureNewAssetBindingAvailableWithTx`(`internal/service/exchange/service.go:1071`)查 `tb_personal_customer_device`,有人扫过码即拒绝;`switchCustomerBindingWithTx`(`:1089`)调用 `customerBinding.Migrate` 迁移客户绑定,`Migrate` 只有换货一个调用方。
- 后台解除接口已存在(`internal/routes/phone_asset_association.go`):单条、按资产批量、CSV 导入、关联列表。
- 测试库 2026-10-11:有效关联 0 条;强制绑定开关已在测试环境打开(提交 `f56113ba`)。
## Goals / Non-Goals
**Goals:**
- 一资产一号,资产已绑定时不再出现资产侧绑定入口。
- 换货能被后台解除放行,换货后旧资产与原客户、原号码脱钩。
**Non-Goals:**
- 不加数据库唯一约束(已确认用程序控制)。
- 不做历史关联回填,不调整关联写入与强制绑定开关的耦合关系(方案第 5 节第 7 条,另行决定)。
- 不改“新号已被其他客户持有返回 1184”。
- 不新增后台解除接口。
## Decisions
1. **一资产一号只做“先查后写”,不加资产锁。** `Establish` 写入前查询该资产的有效关联再判断;不加 Redis 锁、不锁资产行、不加应用锁。2026-10-11 确认:两个不同号码在同一时刻为同一资产完成短信验证的概率极低,后果只是该资产多一个号,可在后台解除,不值得为此加锁。手机号侧既有的十项名额串行(`LockPhoneScopes`)保持不变。
2. **不加唯一约束。** 部分唯一索引 `(asset_type, asset_id) WHERE status = 1` 能兜底,但存量可能有多号资产,加约束前要先清理;已确认本批用程序控制,存量只读统计后交业务处理。
3. **绑定入口按两侧状态拆写。** `bindExistingPrimaryPhone` 不再要求提交号码等于客户手机号;客户侧与资产侧分别判断是否写入。错误码在 `pkg/errors` 新增,提示不带号码。
4. **`ChangePhone` 去掉 `migrateAssociations` 及其迁移审计。** 客户手机号与资产手机号独立,换号不应牵动资产。
5. **换货错误号码放 `data`。** 统一错误处理会把错误信息写日志(`pkg/errors/handler.go`),`data` 只随响应返回;用 `errors.NewWithData` 承载 `{"phone": ...}`,错误码沿用现有冲突类。
6. **换货清空旧资产客户绑定。** 新增 `customer_binding.ClearForExchange(ctx, tx, oldAssetType, oldAssetID)`:定位口径同原 `Migrate`;只处理 `status = 1`,置 0(沿用 `pcdOps.UpdateStatus`、`pciOps.GetByICCID` / `UpdateStatus`),审计角色用 `AuditResourceRolePersonalCustomerOldAssetBinding`。删除 `Migrate`、`migrateFromPCD`、`migrateFromPCI`。
7. **换货失效旧资产关联复用存储方法。** 用 `LockValidByAsset` + `InvalidateByIDs`(`phone_asset_association_store.go:215、229`),不复用 `Service.unbindAsset`:它自开事务并做后台数据范围校验,放不进换货事务。新增失效方式常量 `exchange_completed`(该列无约束,无迁移)。
## Risks / Trade-offs
- [历史上绑过号但没有关联记录的资产不会被换货拦截] → 取决于回填决定,本 Change 不处理。
- [新资产已有钱包余额或生效套餐时,迁移会叠加] → 现状如此,不拦截。
- [前端仍按旧 `need_bind_phone` 语义展示] → 测试环境交付时前端接入两个新布尔字段与 `data.phone`。
- [同一资产并发绑定两个号码] → 不加锁,接受极小概率;交付前与日常用只读统计“同一资产多条有效关联”发现,后台解除多余的。
- [原客户手上的旧资产页面在换货后失效] → 属预期,重新扫码即可进入,已在对外行为变化中告知运营与客服。
## Migration Plan
无数据库迁移。测试环境交付前只读统计“同一资产多条有效关联”,有则出清单交业务在后台解除。
## Open Questions
- 历史关联回填及口径、关联写入是否与强制绑定开关解耦:方案定为“发布时定”,不阻塞本 Change 开发。

View File

@@ -0,0 +1,31 @@
## Why
现行规则只限制“一个手机号最多关联 10 个资产”,不限制一个资产能绑几个号;资产已被别人绑定时 H5 仍出现绑定入口;客户换号会把资产关联一并迁走。换货校验又看的是“是否有人扫过码”(`tb_personal_customer_device`),后台解除手机号也解不开,测试库 6 台设备全部被拦。依据为《第1批-8-9月迭代缺陷修复技术方案》第 5、6 节(F1、M12);原在途 Change `limit-phones-per-asset` 与本规则相反,已于 2026-10-11 作废并删除。
## What Changes
- **BREAKING** 一个资产同时只能有一个有效手机号关联;同号重复验证幂等成功;其他号码绑定被拒,提示“该资产已绑定手机号,如需更换请联系管理员”,不带号码。换号须后台先解除再绑定。
- **BREAKING** `need_bind_phone` 的资产侧判断改为“当前资产是否已有有效关联”;客户自己没有手机号时仍强制绑定客户手机号。登录响应新增两个布尔值:资产是否已绑定手机号、是否为当前客户自己的号码,不返回号码。
- H5 绑定按“客户有无手机号 × 资产有无手机号”四种场景分别写客户手机号、资产手机号;资产侧号码可与客户手机号不同,两者不联动。
- **BREAKING** 客户更换手机号不再迁移资产关联。
- **BREAKING** 换货校验改为:新资产有有效手机号关联就拒绝,提示后台先解除;完整号码放在错误响应 `data.phone`,不进日志。
- **BREAKING** 换货完成时清空旧资产上的客户绑定(不迁移到新资产),并失效旧资产的手机号关联(失效方式 `exchange_completed`),释放名额。
## Capabilities
### New Capabilities
无。
### Modified Capabilities
- `phone-asset-association`:一资产一号、资产已绑定不强制、客户与资产手机号独立、换号不迁移关联、换货完成失效旧资产关联。
- `order-refund-exchange`:换货新资产校验改看手机号关联;换货完成清空旧资产客户绑定、不迁移到新资产。
## Impact
- 代码:`internal/service/phone_asset_association/association_write.go`(`Establish` 增加一资产一号判断,不加锁)、`internal/service/client_auth/service.go`(`need_bind_phone`、绑定入口拆分、`ChangePhone` 去掉 `migrateAssociations`)、`internal/model/dto/client_auth_dto.go`;`internal/service/exchange/service.go`(`ensureNewAssetBindingAvailableWithTx`、`switchCustomerBindingWithTx`)、`customer_binding` 新增 `ClearForExchange` 并删除只有换货使用的 `Migrate`;`phone_asset_association_store.go` 复用 `LockValidByAsset` + `InvalidateByIDs`;`pkg/errors` 新增错误码;`pkg/constants/phone_asset_association.go` 新增失效方式常量。
- 接口:H5 登录与绑定响应新增字段与错误码;换货被拒响应 `data.phone`,测试环境前端需读取展示;重新生成接口文档。
- 数据:无迁移(不加数据库唯一约束);交付前只读统计测试库“同一资产多条有效关联”(2026-10-11 为 0 条)。
- 运营与客服:换货后原客户手上的旧资产页面失效,需重新扫码才能再打开旧资产(谁扫谁能打开,规则不变);资产换号须后台解除。
- 已删除作废的 `openspec/changes/limit-phones-per-asset`(未实施、未归档)。

View File

@@ -0,0 +1,52 @@
## MODIFIED Requirements
### Requirement: 换货业务数据迁移范围
系统 SHALL 仅在选择业务数据迁移的换货完成中迁移旧资产的钱包余额、有效套餐使用记录、累计充值字段和资产标签。资产归属 SHALL 继续作为换货完成固有动作,不受业务数据迁移选项控制。换货完成时系统 MUST 清空旧资产上的全部有效个人客户—资产绑定(设备按虚拟号、为空则 IMEI 定位;卡按虚拟号与 ICCID 两种绑定都清),置为无效而非物理删除,同事务写审计(原因“换货完成”);MUST NOT 把客户绑定迁移到新资产,新资产 MUST NOT 新增任何客户绑定;客户自己的手机号与微信绑定不变。清空后原客户已持有的旧资产 H5 令牌在下一次资产归属校验时失效;任何客户(含原客户)重新扫码旧资产时,按普通扫码登录重新建立绑定,系统 MUST NOT 因曾被换货而拒绝。手机号—资产关联 MUST NOT 随换货或业务数据迁移转移,旧资产关联按手机号—资产关联能力在换货完成时失效,新资产首次访问时按其适用的手机号绑定规则处理。
#### Scenario: 选择业务数据迁移完成换货
- **WHEN** 换货单选择业务数据迁移并成功确认完成
- **THEN** 系统迁移钱包余额、有效套餐使用记录、累计充值字段和资产标签,且不迁移客户绑定与手机号—资产关联
#### Scenario: 不选择业务数据迁移完成换货
- **WHEN** 换货单未选择业务数据迁移并确认完成
- **THEN** 系统仍完成资产归属的固有换货动作并清空旧资产客户绑定,但不迁移钱包余额、套餐使用记录、累计充值字段或资产标签
#### Scenario: 换货后原客户用旧令牌访问旧资产
- **WHEN** 换货完成后,原客户不重新扫码、直接用换货前的旧资产 H5 令牌访问旧资产
- **THEN** 系统按资产不属于该客户拒绝访问
#### Scenario: 换货后重新扫码旧资产
- **WHEN** 换货完成后,原客户或其他客户重新扫码旧资产登录
- **THEN** 系统按普通扫码建立新的有效绑定,可正常访问旧资产,且不重复标记资产已售
#### Scenario: 卡换货清空两种绑定
- **WHEN** 旧卡同时存在按虚拟号与按 ICCID 的有效客户绑定,换货完成
- **THEN** 两种绑定都变为无效并写审计,新卡不新增客户绑定
## ADDED Requirements
### Requirement: 换货新资产手机号关联校验
创建直接换货与确认物流换货完成时,系统 SHALL 检查新资产是否存在有效手机号—资产关联,存在则拒绝,错误信息为“新资产已绑定手机号,请先在后台解除该资产的手机号绑定,再重新提交换货申请”,错误信息 MUST NOT 包含号码;完整号码 MUST 放在错误响应的 `data.phone` 中,MUST NOT 写入日志。系统 MUST NOT 再以“有人扫过码”(个人客户—资产绑定)作为拒绝依据。直接换货被拒时整体回滚、不留换货单;物流换货被拒时停在已发货待确认,后台解除关联后可重新确认。类型一致、旧资产状态可换、新资产未被其他换货单占用的既有校验不变。
#### Scenario: 新资产已绑定手机号
- **WHEN** 后台为一项已与号码 P 有效关联的新资产创建直接换货
- **THEN** 系统拒绝且不产生换货单,错误信息不含号码,`data.phone` 为 P
#### Scenario: 解除后重新提交
- **WHEN** 后台解除新资产的手机号关联后重新创建换货
- **THEN** 换货创建成功
#### Scenario: 只被扫码过的新资产
- **WHEN** 新资产没有有效手机号关联,但存在多个客户的扫码绑定
- **THEN** 系统不因客户绑定拒绝换货
#### Scenario: 物流换货确认完成时被拒
- **WHEN** 物流换货在确认完成时新资产存在有效手机号关联
- **THEN** 换货单保持已发货待确认,解除关联后再次确认成功

View File

@@ -0,0 +1,111 @@
## MODIFIED Requirements
### Requirement: H5 验证建立关联与数量上限
系统 SHALL 保留既有全局 H5 强制绑定开关。开关开启时,客户首次登录一项尚无任何有效手机号关联的资产,必须完成短信验证码校验后才建立关系;资产已有有效关联时不再要求为该资产验证。开关关闭时登录不要求验证,且不查询、不新增、不删除任何关系,已有关系保留。关联只能由 H5 验证建立,卡(`iot_card`)与设备(`device`)分别计为独立资产。
一个资产同时 MUST 至多存在一条有效手机号关联;单手机号最多关联十项当前有效资产;两项上限都只统计当前有效关系,已失效关系不占用额度。建立关联前系统 MUST 查询该资产的有效关联:无有效关联时写入;有效关联的号码与本次相同时幂等成功、不产生第二条关系;有效关联为其他号码时 MUST 拒绝,提示“该资产已绑定手机号,如需更换请联系管理员”,提示与响应 MUST NOT 包含任何号码。所有建立关联的入口 MUST 经同一写入路径,MUST NOT 绕开上述判断。该判断不加资产锁、不加唯一约束:两个不同号码在同一时刻为同一资产完成验证时可能都写入,属已接受的极小概率情况,由只读统计“同一资产多条有效关联”发现后在后台解除。上线不回填历史客户—资产关系。
#### Scenario: 第十一项资产验证
- **WHEN** 已关联十项有效资产的手机号验证第十一项资产
- **THEN** 系统拒绝本次新关联,已有十项关系不变
#### Scenario: 资产已绑定其他号码
- **GIVEN** 资产 A 已与号码 P 存在有效关系
- **WHEN** 任一客户以号码 Q 通过接口为 A 绑定
- **THEN** 系统拒绝并提示“该资产已绑定手机号,如需更换请联系管理员”,响应不含 P 或 Q,A 的关系不变
#### Scenario: 同号重复验证
- **WHEN** 号码 P 对已与 P 有效关联的资产再次完成验证
- **THEN** 系统返回成功且不产生第二条有效关系
#### Scenario: 开关关闭后登录未关联资产
- **WHEN** 全局强制绑定开关关闭,客户登录一项未关联其手机号的资产
- **THEN** 系统不要求验证、不新增关系,且既有关系不被删除
#### Scenario: 卡与设备分别计数
- **WHEN** 同一手机号关联了 `iot_card` 类型 ID 为 5 的资产与 `device` 类型 ID 为 5 的资产
- **THEN** 两者计为两项资产,互不覆盖也不合并计数
### Requirement: 登录提示判定
系统 SHALL 在登录响应中以 `need_bind_phone` 表示当前客户或当前访问资产是否仍需完成手机号绑定,并额外返回两个布尔字段:当前资产是否已绑定手机号、该手机号是否为当前客户自己的号码;响应 MUST NOT 返回号码。开关开启时:客户无主手机号,返回 `true`(客户手机号仍强制绑定);客户有主手机号且当前资产尚无任何有效关联,返回 `true`;当前资产已有有效关联(无论号码属于谁)且客户有主手机号,返回 `false`。开关关闭时 `need_bind_phone` 恒为 `false`。该字段 MUST 只作为前端提示,系统 MUST NOT 因缺少关系拒绝任何资产业务入口。
#### Scenario: 已有手机号但资产未关联
- **WHEN** 客户已有主手机号,登录一项尚无任何有效关联的资产
- **THEN** 响应 `need_bind_phone=true`,资产已绑定为 `false`
#### Scenario: 资产已被他人号码绑定
- **WHEN** 客户已有主手机号,登录一项已与其他号码有效关联的资产
- **THEN** 响应 `need_bind_phone=false`,资产已绑定为 `true`,是否本人号码为 `false`,且不返回号码
#### Scenario: 客户无手机号而资产已绑定
- **WHEN** 客户没有主手机号,登录一项已有有效关联的资产
- **THEN** 响应 `need_bind_phone=true`,资产已绑定为 `true`,验证通过后只写客户手机号
#### Scenario: 缺关系不拦截业务接口
- **WHEN** 客户在 `need_bind_phone=true` 状态下调用其有权访问的资产业务接口
- **THEN** 系统按既有资产归属与数据范围规则授权,不因缺少该关系返回拒绝
### Requirement: H5 绑定与换绑的关联写入
客户手机号与资产手机号 SHALL 相互独立,不要求一致、不联动。H5 短信验证成功后,系统 MUST 按客户与当前访问资产两侧状态分别写入:
| 客户 | 资产 | 写入 |
|---|---|---|
| 无手机号 | 无有效关联 | 一次验证,同时写客户手机号与资产关联 |
| 有手机号 | 无有效关联 | 只建立资产关联,号码可与客户手机号不同,不修改客户手机号 |
| 无手机号 | 已有有效关联 | 只写客户手机号,不动资产关联 |
| 有手机号 | 已有有效关联 | 不需要绑定 |
请求不含当前访问资产身份时,系统只完成客户手机号绑定,不建立关联。资产关联写入 MUST 遵守“H5 验证建立关联与数量上限”的一资产一号与十项上限。
客户更换手机号时 MUST 同时验证旧、新号码,只更换客户手机号,MUST NOT 迁移、复制或失效任何资产关联,也不受资产关联名额影响;新号码已被其他客户持有时的既有拒绝行为保持不变。
#### Scenario: 已有主号为新资产绑定不同号码
- **WHEN** 客户主手机号为 P,当前访问资产尚无关联,客户提交号码 Q 与有效验证码
- **THEN** 系统建立 Q 与该资产的有效关系,客户手机号仍为 P
#### Scenario: 无主号且资产无关联
- **WHEN** 客户无主手机号,当前访问资产尚无关联,客户提交号码 P 与有效验证码
- **THEN** 系统同时写入客户手机号 P 与 P—资产有效关系
#### Scenario: 无主号而资产已绑定
- **WHEN** 客户无主手机号,当前访问资产已与号码 Q 有效关联,客户提交号码 P 与有效验证码
- **THEN** 系统只写入客户手机号 P,资产仍只与 Q 关联
#### Scenario: 客户换号不迁移关联
- **WHEN** 客户把手机号从 P 换成 R
- **THEN** 客户手机号变为 R,P 的全部资产关联保持不变
### Requirement: 关联不影响换货与其他写入路径
资产导入、后台资产编辑与个人客户主手机号变更 MUST NOT 创建、推断、复制或迁移手机号—资产关系。换货 MUST NOT 把旧资产的关联转移到新资产;换货完成时系统 MUST 在同一事务内将旧资产的全部有效关联置为失效,失效方式为 `exchange_completed`,失效原因“换货完成”,操作人为确认换货完成的账号,写审计(手机号脱敏),释放该号码名额;旧资产无有效关联时跳过。新资产在客户首次 H5 访问时,按当时全局开关与其自身关联状态重新走验证。
#### Scenario: 换货不迁移关系并失效旧资产关联
- **WHEN** 换货完成并用新资产替换旧资产,旧资产与号码 P 存在有效关系
- **THEN** 新资产不继承 P,旧资产与 P 的关系变为失效(`exchange_completed`),P 的有效关联数量减一
#### Scenario: 换货新资产首次登录
- **WHEN** 全局开关开启,客户换货完成后首次登录尚无关联的新资产
- **THEN** 响应 `need_bind_phone=true`
#### Scenario: 资产导入与后台资产编辑不产生关系
- **WHEN** 导入资产或修改后台资产属性
- **THEN** 关联记录数不变,不产生任何手机号—资产关系

View File

@@ -0,0 +1,27 @@
## 1. F1 一资产一号
- [x] 1.1 `pkg/errors` 新增“该资产已绑定手机号,如需更换请联系管理员”错误码,提示不含号码。
- [x] 1.2 `Establish` 写入前查询该资产有效关联:无则写入、同号幂等、他号拒绝;不加任何资产锁(Redis、行锁、应用锁都不加),手机号侧既有十项名额判断不变。
- [x] 1.3 核对所有写资产关联的入口(H5 绑定、老客户给新资产绑定)都只经 `Establish`。
## 2. F1 H5 登录与绑定
- [x] 2.1 `need_bind_phone` 资产侧改为“当前资产是否已有有效关联”,客户无手机号仍为 true;登录响应 DTO 新增资产是否已绑定、是否本人号码两个布尔字段,不返回号码。
- [x] 2.2 拆分 H5 绑定写入,按 delta spec 四种场景分别写客户手机号与资产关联;`bindExistingPrimaryPhone` 不再要求号码等于客户手机号。
- [x] 2.3 `ChangePhone` 去掉 `migrateAssociations` 调用及对应迁移审计,其余校验不变。
## 3. M12 换货
- [x] 3.1 `ensureNewAssetBindingAvailableWithTx` 改查 `tb_phone_asset_association` 有效关联,用 `errors.NewWithData` 返回不含号码的错误信息与 `data.phone`;不再查客户绑定表。
- [x] 3.2 `customer_binding` 新增 `ClearForExchange`(设备虚拟号或 IMEI、卡虚拟号与 ICCID 两边都清,`status 1 → 0`,同事务审计);`switchCustomerBindingWithTx` 改调用它;删除 `Migrate`、`migrateFromPCD`、`migrateFromPCI`。
- [x] 3.3 `pkg/constants/phone_asset_association.go` 新增失效方式 `exchange_completed`;换货完成事务内用 `LockValidByAsset` + `InvalidateByIDs` 失效旧资产有效关联,失效原因“换货完成”,操作人为确认完成账号,写审计(手机号脱敏)。
- [x] 3.4 更新换货接口说明(`data.phone`)与 H5 登录、绑定接口说明。
## 4. 文档与测试环境验证
- [x] 4.1 `gofmt`、`go build ./cmd/api ./cmd/worker`、`go run cmd/gendocs/main.go`。
- [x] 4.2 只读统计测试库“同一资产多条有效关联”,有则出清单。
- [ ] 4.3 F1(按 ENG-TEST-001,关联只经 H5 短信验证建立,不直接改库):资产已有号码 A 时任何客户进入资产侧不要求绑定;号码 B 绑定被拒、错误码与提示正确且不含号码;A 重复验证幂等;四种 H5 场景按 delta spec 写入;客户换号后资产关联不变;后台解除后资产侧重新要求绑定、B 可绑定;`associated_phones` 与审计正确。
- [ ] 4.4 M12:给一台测试设备经 H5 建立关联后,直接换货被拒、不产生换货单、`data.phone` 正确且日志无完整号码 → 后台解除 → 重新提交成功;旧资产客户绑定全部无效、审计写入、原客户用旧令牌访问旧资产被拒、原客户重新扫码旧资产可正常进入且不重复标记已售;新资产不新增客户绑定;卡换货虚拟号与 ICCID 两种绑定都被清空;客户手机号不变;无关联但多人扫码的资产可直接换货;类型不一致、状态不可换、已被占用仍被拒;物流换货确认完成时被拒、解除后成功;完成后旧资产关联失效(`exchange_completed`)、名额释放。
- [ ] 4.5 通知测试环境前端接入登录响应两个新布尔字段与换货 `data.phone`。
- [ ] 4.6 运行 `openspec validate --all` 与 `./scripts/context-health.sh`。

View File

@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-11

View File

@@ -0,0 +1,53 @@
## Context
承接《第1批-8-9月迭代缺陷修复技术方案》(下称“方案”)第 3、7、8 节。
- 提交失败:`approval_submission_consumer.go` 在表单构造失败和企微明确拒绝两处调用 `ApprovalContextRepository.MarkFailed`,其内部 `markSubmissionState` 单事务更新企微上下文与审批实例(7),但不通知业务模块。测试库退款、线下充值、核销、扫码注册均有提交失败实例停在待审批。
- 决策分发:六个业务类型已通过 `DecisionDispatcher` 注册决策消费者,终态经 `TerminalEventWriter`(`internal/infrastructure/approval/terminal_event.go`)写入公共 Outbox;各消费者 `switch` 的 `default` 分支返回错误。
- M13:`internal/service/refund/approval_decision.go:227` 关闭分支用 `event.BusinessID` 直接查退款单,而新流程中 `BusinessID` 是审批尝试 ID;通过分支(:48、:92)已用 `refundapproval.ResolveRefundInTx`。
- 恢复:核销、退款、扫码注册三处恢复入口在“实例为 7 且上下文为提交失败”时走 `RecoverSubmissionEvent` 重放。
- 状态约束:五张业务表有 `CHECK (status IN ...)`,佣金提现表无约束。
- 核销列表投影 `ProjectApplication`(`internal/query/employeecollection/application.go:207`)未给审批提交状态字段赋值。
## Goals / Non-Goals
**Goals:**
- 提交失败的业务单进入明确终态并释放占用,可在卡管重新发起。
- 退款关闭类终态正确结束退款单。
- 核销列表与详情显示真实提交状态。
**Non-Goals:**
- 不改通过、驳回、撤销、通过后撤销的既有处理(M13 只修定位)。
- 不处理提交结果未知(8),仍由恢复任务确认。
- 不支持企微侧重新提交挂接回原单。
- 不新增佣金提现表的状态约束。
## Decisions
1. **复用既有决策通道,新增决策值而不是新事件类型。** `pkg/constants/approval.go` 增加 `ApprovalDecisionSubmissionFailed = "submission_failed"`;`markSubmissionState` 在状态 7 分支、实例更新成功后,同一事务写入决策投递记录与 `TerminalEventWriter.Append` 事件(见决策 9),事件号为 `approval:{实例ID}:submission_failed`。不新建订阅链路,幂等、重试、死信全部沿用现有机制。备选是业务模块轮询“实例 7 且业务单待审批”,延迟高且要六处各写一套扫描,放弃。
2. **六个消费者同一次交付接入。** `default` 分支返回错误,未接入的业务类型会进入分发失败重试,因此 M8、M14 同批,消费者显式处理新值,不能落入驳回分支。处理前锁审批实例并确认仍为 7。
3. **提交失败为终态,去掉重放。** 决策异步消费,若业务单变终态前有人点“恢复审批”,实例被重放回提交中,会出现“业务单已终态、企微又生成审批”的分裂。三处恢复入口的 replay 分支一律拒绝;“结果未知”“已有单号同步”分支不变。
4. **状态值。** 核销 4、退款 7、扫码注册 3、资料资格 4、线下充值 7、佣金提现 5。
5. **退款状态 7 的门禁与已拒绝(3)一致。** 加入 `RefundResubmittableStatuses()`,不加入 `RefundActiveStatuses()`:既可对原单重新发起,也可为同一订单新建退款单,两张同时生效由 `uk_refund_request_active_order` 兜底。状态 7 与 3、4 同属“钱未动的终态”,且不可恢复,无重复退款风险;状态 6 禁止另建新单是因为渠道退款可能已发起,与 7 不同。2026-10-11 已确认按 3、4 处理。换货校验 `HasUnfinishedByAsset` 不改,新状态自然不阻断换货。
6. **M13 照通过分支写法。** `ResolveRefundInTx` 本身不加锁,解析后再按 `target.ID` 对退款单 `SELECT ... FOR UPDATE`;其余逻辑不变。重新发起沿用 `CreationService.Resubmit`,已允许状态 3。
7. **核销投影一次批量读取。** 按 `latest_approval_instance_id` 批量读 `tb_wecom_approval_context`,状态名称映射与脱敏复用退款已有实现(`internal/service/refund/service.go:1467-1520`)。
8. **迁移只放宽约束。** 一组新的成对迁移:五张表逐表 `DROP CONSTRAINT` 后按新值集合重建、更新列注释;佣金提现只更新列注释。down 恢复原约束(执行前须确认没有新状态数据)。资料资格的 `chk_withdrawal_qualification_invalidated` 与 `WHERE status = 1` 唯一索引不受影响。同一迁移放宽 `tb_approval_decision_delivery.ck_approval_decision_delivery_decision`,允许 `submission_failed`,否则决策 9 写投递记录会违反约束(2026-10-11 实施时发现)。
9. **写决策时同时建投递记录。** 现有终态决策(`internal/application/approval/sync_decision.go`)在同一事务里调用 `DecisionDeliveryWriter.Create` 与 `TerminalEventWriter.Append`;分发器处理前 `Claim` 投递记录(`internal/infrastructure/approval/decision_delivery.go`,要求更新到 1 行),没有记录时返回未认领,分发器直接结束,业务单永远不变且不报错。因此 `markSubmissionState` 必须两者都写,事件号沿用 `terminalDecisionEventID` 的格式 `approval:{实例ID}:submission_failed`。`ApprovalContextRepository`(`internal/infrastructure/wecom`)需注入这两个写入器,同步修改启动装配。
10. **只在消费入口放行新决策值。** `TerminalDecisionConsumer.Consume`(`internal/infrastructure/approval/terminal_event.go:69`)用 `approvaldomain.StatusForDecision` 校验决策值,目前不认 `submission_failed`。该函数也被渠道状态推进 `ApplyDecision` 使用,直接加值会让企微回调可以把实例推到提交失败;因此只在 `Consume` 中对 `submission_failed` 单独放行,`StatusForDecision` 不改。
11. **失败原因由业务模块读取。** `TerminalDecisionEvent` 没有原因字段,不扩展事件结构;各业务消费者处理 `submission_failed` 时按实例读取 `tb_wecom_approval_context.last_error`,脱敏后写入各自的终态原因字段与审计。
## Risks / Trade-offs
- [某个消费者漏接新决策] → 分发失败重试堆积;任务中逐个消费者核对,测试环境对六个业务类型各构造一次提交失败。
- [漏写投递记录或消费入口未放行] → 事件静默结束或被拒;验证时逐个确认投递记录状态为成功、业务单状态已变化。
- [测试库已有“实例 7、业务单待审批”存量] → 代码不自动修正;在测试环境只读统计,需要时写一次性补数据脚本,经确认后执行。
- [佣金提现冻结释放出错影响余额] → 释放与状态更新同事务、条件更新检查 `RowsAffected`,验证时核对钱包余额与流水。
- [退款状态 7 可同时走重发与新建两条路] → 与已拒绝一致,唯一索引保证至多一张活动申请。
## Migration Plan
测试环境:先执行新的成对迁移(只放宽约束,旧代码照常运行),再部署 API 与 Worker。六个消费者与核心决策同一次部署。
## Open Questions
无。

View File

@@ -0,0 +1,33 @@
## Why
企微明确拒绝提交审批时,审批核心只把审批实例改为“提交失败”,不通知业务模块,业务单永远停在待审批:核销申请的账单预占、佣金提现的冻结金额一直不释放。另外退款审批在企微被拒绝、撤销、删除时,关闭分支把审批尝试 ID 当成退款单 ID,退款单停在待审批(测试库退款单 511 已复现)。核销申请列表与详情的审批提交状态字段也从未赋值。依据为《第1批-8-9月迭代缺陷修复技术方案》第 3、7、8 节(M8、M13、M14)。
## What Changes
- 审批核心在实例变为“提交失败”的同一事务内,发出新的终态决策 `submission_failed`,带脱敏失败摘要;提交结果未知不发。六个业务决策消费者必须同时接入该决策。
- 核销申请新增状态 4“审批提交失败”(终态),收到决策后释放全部预占;列表与详情一次批量返回审批提交状态(M8)。
- 退款新增状态 7“审批提交失败”(终态);扫码注册代理新增 3、提现资料资格新增 4、线下充值新增 7、佣金提现新增 5,各自为终态并释放占用;佣金提现释放冻结金额(M14)。
- 以上状态均不再提供“恢复审批”;核销、退款、扫码注册代理三处恢复入口对“提交失败”的重放分支改为拒绝。要再办理须在卡管重新发起,生成新的审批尝试与新的企微审批。
- 退款审批在企微被拒绝、撤销、删除后,按审批尝试正确定位退款单并置为“已拒绝”(终态);企微侧重新提交产生的新单号不关联(M13)。
- **BREAKING** 上述业务列表、筛选、导出出现新状态值;新增一组成对迁移,放宽五张表的状态 `CHECK` 约束。
## Capabilities
### New Capabilities
无。
### Modified Capabilities
- `external-integration`:审批提交失败作为终态决策通知业务模块。
- `employee-collection-bill`:核销申请新增“审批提交失败”终态;列表与详情返回审批提交状态。
- `order-refund-exchange`:退款新增“审批提交失败”终态;企微关闭类终态按审批尝试定位退款单;企微侧重新提交不关联;恢复入口不再重放提交失败。
- `agent-distribution-withdrawal`:扫码注册代理、佣金提现、提现资料资格新增“审批提交失败”终态;注册恢复入口不再重放提交失败。
- `agent-funds-commission`:线下代理充值新增“审批提交失败”终态。
## Impact
- 代码:`pkg/constants/approval.go`、`internal/infrastructure/wecom/approval_context_repository.go`、`internal/infrastructure/approval/terminal_event.go`;六个决策消费者(`internal/application/employeecollection/approval_decision.go`、`internal/service/refund/approval_decision.go`、`internal/application/agentrecharge/approval_decision.go`、`internal/application/distributionwithdrawal/{registration,withdrawal,qualification}_approval.go`);三处恢复入口;各业务状态常量、列表筛选、状态名称、导出格式化;`internal/query/employeecollection/application.go`。
- 数据库:新增一组成对迁移(编号排在 238 之后),放宽 `tb_employee_collection_application`、`tb_refund_request`、`tb_agent_distribution_registration`、`tb_withdrawal_qualification`、`tb_agent_recharge_record` 的状态约束,更新列注释(含无约束的 `tb_commission_withdrawal_request`);放宽 `tb_approval_decision_delivery` 的决策取值约束,允许 `submission_failed`。
- 接口:列表筛选与状态说明新增值;重新生成接口文档。
- 运营:这些单据提交企微失败后需在卡管重新发起,不再“恢复审批”。

View File

@@ -0,0 +1,50 @@
## MODIFIED Requirements
### Requirement: 代理注册原审批可受控恢复
系统 SHALL 提供 `POST /api/admin/agent-distribution-registrations/{id}/recover-approval`,允许有权平台账号及申请直接上级代理恢复仍待审批的注册申请。恢复 MUST 校验原审批实例及业务关联、上级店铺启用状态和调用方范围,复用原实例与稳定提交事实;不得新建注册记录、审批实例、企业微信审批单、店铺、账号或钱包。结果未知时 MUST 优先确认原提交,已有审批单号时 MUST 同步原审批;审批实例为提交失败时 MUST 返回“审批提交失败为终态,请重新发起”,MUST NOT 重放原提交事件。终态申请(含审批提交失败)或停用上级 MUST 返回稳定冲突;恢复 MUST 写入脱敏审计。
#### Scenario: 提交失败不可恢复
- **WHEN** 注册申请的原审批实例已提交失败时请求恢复
- **THEN** 系统返回“审批提交失败为终态,请重新发起”,不重放提交事件、不新建注册记录或业务实体
#### Scenario: 结果未知优先确认
- **WHEN** 待审批申请的原提交结果未知
- **THEN** 系统进入原实例确认流程,不直接创建新的企业微信审批
#### Scenario: 终态或停用上级拒绝恢复
- **WHEN** 注册申请已终态或其直接上级店铺已停用时请求恢复
- **THEN** 系统返回稳定冲突且不改变注册、审批或实体事实
## ADDED Requirements
### Requirement: 扫码注册代理审批提交失败
审批核心对注册申请的审批实例发出 `submission_failed` 决策时,系统 SHALL 确认审批实例仍为提交失败,将注册记录从待审批(0)条件更新为审批提交失败(3),记录脱敏失败原因并写审计,按事件幂等;MUST NOT 创建店铺、账号、钱包或层级。审批提交失败为终态,MUST NOT 阻止同一手机号、用户名或店铺编号再次提交;客户重新扫码提交形成新的注册记录与新的审批实例。
#### Scenario: 注册审批提交失败
- **WHEN** 待审批注册申请的审批实例提交企微失败
- **THEN** 注册记录变为审批提交失败,不创建任何业务实体,同一手机号可重新扫码提交
### Requirement: 佣金提现审批提交失败
审批核心对提现申请最新审批尝试发出 `submission_failed` 决策时,系统 SHALL 确认审批实例仍为提交失败,在同一事务内仅一次释放该次尝试的冻结余额并记录释放时间,将提现申请从待审核条件更新为审批提交失败(5),记录脱敏失败原因并写审计,按事件幂等。审批提交失败的申请 MUST 允许代理修改金额、收款信息和本次发票后重新发起,重新发起时按新金额重新冻结、新增审批尝试与审批实例,资料资格保持有效。
#### Scenario: 提现审批提交失败释放冻结
- **WHEN** 待审核提现申请的审批实例提交企微失败
- **THEN** 申请变为审批提交失败,冻结金额仅一次释放,钱包余额与流水一致
#### Scenario: 提交失败后重新发起
- **WHEN** 代理对审批提交失败的提现申请修改后重新发起
- **THEN** 系统按新金额重新冻结并创建新的审批尝试与审批实例,历史尝试不被覆盖
### Requirement: 提现资料资格审批提交失败
审批核心对资料版本审批实例发出 `submission_failed` 决策时,系统 SHALL 确认审批实例仍为提交失败,将资料版本从等待终审(0)条件更新为审批提交失败(4),记录脱敏失败原因并写审计,按事件幂等。审批提交失败为终态,MUST NOT 阻止代理提交新的资料版本,MUST NOT 影响已通过的有效版本。
#### Scenario: 资料资格审批提交失败
- **WHEN** 等待终审的资料版本审批实例提交企微失败
- **THEN** 该版本变为审批提交失败,代理可提交新的资料版本,已通过的有效版本不受影响

View File

@@ -0,0 +1,13 @@
## ADDED Requirements
### Requirement: 线下代理充值审批提交失败
审批核心对线下代理充值申请的审批实例发出 `submission_failed` 决策时,系统 SHALL 确认审批实例仍为提交失败,将充值记录从待审批条件更新为审批提交失败(7),记录脱敏失败原因并写审计,按事件幂等;MUST NOT 入账或改变代理钱包余额。审批提交失败为终态,代理充值列表、筛选、状态名称与导出 MUST 显示该状态;要再充值由申请人重新发起新的充值申请。
#### Scenario: 线下充值审批提交失败
- **WHEN** 待审批线下代理充值申请的审批实例提交企微失败
- **THEN** 充值记录变为审批提交失败,钱包余额不变,列表与筛选可见该状态
#### Scenario: 重复投递
- **WHEN** 同一 `submission_failed` 决策被重复投递
- **THEN** 充值记录状态与审计只生效一次

View File

@@ -0,0 +1,46 @@
## MODIFIED Requirements
### Requirement: 核销申请审批、重提与幂等
核销申请状态 SHALL 为 `审批中`、`已通过`、`已驳回`、`已撤销/已关闭`、`审批提交失败`,且不得以申请状态覆盖账单核销状态。提交或重提时系统 MUST 新增一条不可变审批尝试记录(冻结当次收款方式、外部付款、附件、备注、账单分摊及审批材料快照)并为其创建新的企业微信审批实例;申请只保存最新审批实例 ID 用于展示。企业微信业务类型 MUST 为 `employee_collection_approval`,其业务标识 MUST 取审批尝试记录主键,使同一申请的多次提交各自持有独立审批实例,且 MUST NOT 修改既有审批实例的共享唯一约束或既有 `refund_approval`、`offline_recharge_approval` 场景语义。
企业微信最终通过时,系统 MUST 幂等地将申请标记为已通过、将各分摊写入账单已核销金额并释放其预占;最终驳回时 MUST 标记申请已驳回、释放全部预占且保留审批意见。已驳回或审批提交失败的申请可修改全部申请内容后重提,重提生成新的审批尝试与新的企业微信审批,历史审批实例、材料和结果不得覆盖;已通过分摊不可修改。
审批核心对最新审批尝试发出 `submission_failed` 决策时,系统 MUST 确认审批实例仍为提交失败,并在同一事务内释放该次尝试的全部预占分摊与账单预占、将申请从审批中条件更新为审批提交失败、以脱敏失败摘要写入终态原因并写审计;非最新尝试或申请已不是审批中时幂等结束。审批提交失败为终态,MUST NOT 再通过“恢复审批”重放原提交,恢复入口对该情形 MUST 返回“审批提交失败为终态,请重新发起”,`recoverable` MUST 返回 false。回调延迟或提交结果未知时申请保持在途,系统 MUST 使用既有查询/恢复机制确认渠道结果,且不得由本地人工通过或拒绝绕过企业微信。企业微信对已通过申请撤销时,系统 MUST NOT 回滚已核销金额,MUST 将申请转为异常终态、保留审计与账单详情提示,并禁止自动重提。同一撤销结果在本地申请仍为审批中时(回调乱序或通过结果未被消费),系统 MUST 释放该次审批尝试的全部审批中预占、将申请转为异常终态并记录终态原因、保留审计,MUST NOT 自动重提。
#### Scenario: 企业微信通过核销申请
- **WHEN** 企业微信对含多笔分摊的核销申请返回最终通过,且该结果首次被消费
- **THEN** 系统仅一次更新申请、各账单已核销金额和状态,并保留审批实例及冻结快照
#### Scenario: 企业微信驳回后重提
- **WHEN** 企业微信最终驳回核销申请
- **THEN** 系统释放预占、保留驳回实例和意见;员工或有代办权限的超级管理员修改申请后重提时新增审批尝试记录并创建新的审批实例,历史实例与材料不被覆盖
#### Scenario: 企业微信通过后撤销
- **WHEN** 已通过的核销申请收到企业微信撤销结果
- **THEN** 系统不回滚已核销金额,将申请标记为异常终态、保留审计并在账单详情提示,且不允许自动重提
#### Scenario: 审批中收到通过后撤销
- **WHEN** 企业微信对仍处于审批中的核销申请返回“通过后撤销”(回调乱序或本地未消费到通过结果)
- **THEN** 系统释放该申请全部审批中预占、将申请转为异常终态并记录终态原因、保留审计,且不回滚任何已核销金额;该申请禁止自动重提,账单可重新发起新的核销申请
#### Scenario: 审批提交失败释放预占
- **WHEN** 核销申请的最新审批实例因缺必填控件映射或企微明确拒绝而提交失败
- **THEN** 申请变为审批提交失败、全部预占释放、账单可再次核销、审计写入,且对该申请“恢复审批”被拒
#### Scenario: 审批提交失败后重提
- **WHEN** 员工修改审批提交失败的申请后重提
- **THEN** 系统新增审批尝试记录并创建新的企业微信审批,申请回到审批中
#### Scenario: 提交结果未知保持在途
- **WHEN** 核销申请的审批实例提交结果未知
- **THEN** 申请保持审批中,预占不释放
## ADDED Requirements
### Requirement: 核销申请返回审批提交状态
核销申请列表与详情 SHALL 返回审批提交状态、状态名称、脱敏失败摘要、可恢复标记、最近一次恢复结果与时间,按申请的最新审批实例一次批量读取企微审批上下文,MUST NOT 逐行查询;状态名称映射与失败摘要脱敏 MUST 与退款审批投影一致。无审批上下文的申请 MUST 返回默认值,MUST NOT 报错或丢行。
#### Scenario: 列表返回提交状态
- **WHEN** 查询一页核销申请,其中部分有审批上下文、部分没有
- **THEN** 有上下文的申请返回与测试库企微审批上下文一致的提交状态,没有的返回默认值,整页无逐行查询

View File

@@ -0,0 +1,29 @@
## ADDED Requirements
### Requirement: 审批提交失败通知业务模块
审批实例因企微明确拒绝提交或审批表单无法构造(如缺必填控件映射)而变为“提交失败”(7)时,系统 SHALL 在同一事务内经既有终态决策通道发出决策 `submission_failed`:MUST 同时写入标准决策 Outbox 事件与决策投递记录(与其他终态决策相同,缺投递记录时业务消费者不会处理);事件标识 MUST 沿用既有格式 `approval:{审批实例标识}:submission_failed`,重复写入不产生第二个事件。决策事件结构不新增字段,失败原因由业务模块从该实例的企微审批上下文读取并脱敏后保存。决策消费入口 MUST 接受 `submission_failed`;渠道回调与轮询的审批状态推进 MUST NOT 因此接受该决策值。提交结果未知(8)MUST NOT 发出该决策,仍由既有恢复机制确认。所有已注册的审批业务类型(核销、退款、扫码注册代理、线下充值、佣金提现、提现资料资格)MUST 显式处理该决策,MUST NOT 将其按驳回处理;各业务处理前 MUST 确认审批实例仍为提交失败,否则幂等结束。
#### Scenario: 企微明确拒绝提交
- **WHEN** 某业务单的审批实例提交企微被明确拒绝
- **THEN** 审批实例变为提交失败,同一事务写入一条 `submission_failed` 决策事件,对应业务模块随后将业务单置为“审批提交失败”
#### Scenario: 审批表单构造失败
- **WHEN** 某审批实例因缺少必填控件映射无法构造表单
- **THEN** 系统按提交失败处理并发出 `submission_failed` 决策
#### Scenario: 提交结果未知不发决策
- **WHEN** 审批实例提交结果未知
- **THEN** 系统不发出 `submission_failed` 决策,业务单保持审批中
#### Scenario: 业务模块确实收到决策
- **WHEN** 审批实例变为提交失败并写入决策事件
- **THEN** 该事件存在对应的决策投递记录,业务消费者能认领并处理,业务单状态发生变化,而不是被当作已处理直接结束
#### Scenario: 渠道回调不能推进到提交失败
- **WHEN** 企微回调或轮询带来的决策值为 `submission_failed`
- **THEN** 审批状态推进按不受支持的决策拒绝,审批实例状态不变
#### Scenario: 决策重复投递
- **WHEN** 同一 `submission_failed` 决策被重复投递
- **THEN** 业务单状态、释放的占用与审计均只生效一次

View File

@@ -0,0 +1,97 @@
## MODIFIED Requirements
### Requirement: 订单、退款与换货状态门禁
系统 SHALL 仅允许待支付订单取消;退款申请按待审批、已通过、已拒绝、已退回、原路退款处理中、原路退款失败、审批提交失败流转,仅已拒绝、已退回、原路退款失败和审批提交失败申请可修改并重新提交;换货按待填写信息、待发货、已发货、已完成或已取消流转,并拒绝与当前状态或流程类型不匹配的操作。处于待审批、原路退款处理中或原路退款失败的退款申请 MUST 阻止同一订单创建新的退款申请,且 MUST NOT 被再次推进为新的审批实例或第二次渠道退款。已拒绝与审批提交失败的退款申请为终态,MUST NOT 阻止同一订单创建新的退款申请,也 MUST NOT 阻止该资产换货。
#### Scenario: 重复推进终态
- **GIVEN** 退款或换货已进入不允许当前操作的状态
- **WHEN** 再次审批、发货、完成、取消或重新提交
- **THEN** 系统返回状态冲突且不重复改变资产、余额或业务状态
#### Scenario: 原路退款失败后重提
- **WHEN** 退款申请处于原路退款失败状态且调用方在其数据范围内修改材料后重新提交
- **THEN** 系统新增一条审批尝试记录与一个新的企业微信审批实例并使申请回到待审批,历史尝试与已提交的渠道退款不被覆盖
#### Scenario: 企业微信通过后撤销的申请被再次推进
- **GIVEN** 退款申请已记录企业微信通过后撤销的审批异常
- **WHEN** 调用者再次提交或重提该申请
- **THEN** 系统返回状态冲突,不恢复套餐权益、不取消已提交的渠道退款且不自动重提
#### Scenario: 审批提交失败的退款不阻断换货
- **GIVEN** 资产的退款申请处于审批提交失败
- **WHEN** 调用方为该资产发起换货
- **THEN** 系统不因该退款申请拒绝换货
### Requirement: 企业微信唯一终审与审批尝试重提
退款申请 SHALL 保存退款原因、冻结实收金额、唯一关联套餐及其使用情况、方式、金额和当次材料快照。超级管理员、平台用户和代理可在各自订单数据范围内创建、修改并重提未成功申请;企业微信是唯一终审,本地 MUST NOT 人工通过、拒绝或退回已关联审批实例的申请。每次创建或重提 MUST 新增一条不可变的审批尝试记录,并以该尝试记录作为通用审批业务标识;同一申请每次提交各自持有独立审批实例,历史尝试材料与审批结果不被覆盖。退款单 SHALL 仅保存最新尝试与最新审批实例引用用于展示。
同一订单同时至多存在一张待审批、原路退款处理中或原路退款失败的退款申请。企业微信驳回、撤销或删除待审批申请后,系统 MUST 将退款申请置为已拒绝(终态),拒绝原因分别为“企业微信审批已拒绝”“企业微信审批已撤销”“企业微信审批已删除”,并写审计;要再退款须在卡管对该申请重新发起,生成新的审批尝试与新的企业微信审批。企业微信侧对已驳回或已撤销审批重新提交产生的新审批单号,系统 MUST NOT 关联到任何退款申请,只按既有“未关联本系统业务,已忽略”留痕。原路退款明确失败后可修改未成功申请的金额、原因、方式、收款信息和附件并重提;每次重提必须新建审批实例及快照。
审批核心对最新审批实例发出 `submission_failed` 决策时,系统 MUST 确认审批实例仍为提交失败,将退款申请从待审批条件更新为审批提交失败(终态),记录脱敏失败原因并写审计,按事件幂等;该申请 MUST 可在卡管重新发起,MUST NOT 再通过恢复入口重放原提交。审批结果未知时申请保持在途,使用既有查询与恢复闭环,不得另建或重提。企业微信通过后撤销时不回滚套餐失效或已启动退款,标记审批异常并禁止自动重提。
审批终态(含通过、驳回、撤销、删除、通过后撤销与提交失败)MUST 以审批实例标识判别业务归属:先按审批尝试记录标识与审批实例匹配,未命中时按退款申请标识与审批实例匹配以兼容尚未切换到尝试模式的存量申请,两者均不匹配时返回稳定冲突错误,不得回落到任一候选业务单。定位后 MUST 对退款申请加行锁再推进状态。
#### Scenario: 审批通过前结果未知
- **WHEN** 企业微信提交成功性或最终结果暂时未知
- **THEN** 申请保持在途且订单不得创建第二张活动申请,系统通过既有恢复机制确认结果
#### Scenario: 未成功申请重提新建实例
- **GIVEN** 退款申请处于已拒绝、已退回、原路退款失败或审批提交失败状态且无审批异常
- **WHEN** 调用者修改材料后重新提交
- **THEN** 系统在同一事务新增审批尝试记录并创建新的企业微信审批实例,原尝试记录与历史审批结果保持不变
#### Scenario: 尝试模式申请被企业微信撤销
- **GIVEN** 退款申请以审批尝试记录作为审批业务标识,且处于待审批
- **WHEN** 企业微信对该审批返回撤销、拒绝或删除
- **THEN** 系统按审批尝试定位到该退款申请,将其置为已拒绝并记录对应原因与审计,该资产随后可换货
#### Scenario: 企业微信侧重新提交不关联
- **WHEN** 企业微信回调一个卡管未创建的审批单号(企微侧对已驳回或已撤销审批的重新提交)
- **THEN** 系统不关联任何退款申请,只留痕“未关联本系统业务,已忽略”
#### Scenario: 审批提交失败
- **WHEN** 待审批退款申请的最新审批实例提交企微失败
- **THEN** 退款申请变为审批提交失败并写审计,列表、筛选、导出显示该状态;重复投递结果不变
#### Scenario: 存量申请审批终态仍被消费
- **GIVEN** 退款申请由本能力上线前创建,其审批实例的业务标识指向退款申请本身
- **WHEN** 该审批实例到达通过或关闭终态
- **THEN** 系统按审批实例标识匹配到该退款申请并幂等推进,不按尝试模式误判为不存在
#### Scenario: 已关联实例的本地人工终审
- **GIVEN** 退款申请已关联审批实例
- **WHEN** 后台账号调用本地通过、拒绝或退回入口
- **THEN** 系统拒绝该操作且不改变退款申请与订单状态
#### Scenario: 存量无实例待审批申请仍可终结
- **GIVEN** 退款申请未关联任何审批实例且处于待审批状态
- **WHEN** 后台账号在既有开关开放时调用本地通过、拒绝或退回入口
- **THEN** 系统按既有语义终结该申请,不要求该申请先接入企业微信审批
### Requirement: 退款原审批实例可受控恢复
系统 SHALL 提供 `POST /api/admin/refunds/{id}/recover-approval`,允许既有退款管理范围内的超级管理员、平台用户和代理恢复仍处于待审批的退款最新审批实例;企业账号拒绝,越权与不存在不可区分。恢复 MUST 复用原审批实例及 `approval:{instance_id}:submission` 稳定提交事实,不得新增审批尝试/实例、修改冻结退款材料或触发退款、订单、套餐与资金动作。已有 `sp_no` 只查询同步,结果未知只确认;审批实例为提交失败时 MUST 返回“审批提交失败为终态,请重新发起”,MUST NOT 重放原提交事件。审批终态、审批提交失败、原路退款处理中或渠道退款失败 MUST 返回状态冲突。审批提交失败的退款申请 `recoverable` MUST 为 false。历史快照缺失新增键时,只能从关联不可变审批尝试补齐缺失值并写脱敏审计。
#### Scenario: 恢复入口只处理原审批事实
- **WHEN** 授权账号请求恢复待审批退款
- **THEN** 系统按最新尝试与实例关联选择恢复分支,列表/详情返回提交状态、可恢复标记、安全失败摘要和最近恢复时间,重复或并发请求至多一次改变提交事实。
#### Scenario: 提交失败不可恢复
- **WHEN** 授权账号对审批实例已提交失败的退款申请请求恢复
- **THEN** 系统返回“审批提交失败为终态,请重新发起”,不重放提交事件、不改变审批实例

View File

@@ -0,0 +1,43 @@
## 1. 迁移与常量
- [x] 1.1 新增成对迁移(编号排在 238 之后):放宽核销 `IN (0..4)`、退款 `IN (1..7)`、扫码注册 `IN (0..3)`、资料资格 `IN (0..4)`、线下充值 `IN (1..7)` 的状态约束并更新列注释;佣金提现只更新列注释;同时放宽 `tb_approval_decision_delivery` 决策取值约束允许 `submission_failed`;down 恢复原约束。
- [x] 1.2 新增状态常量与中文名“审批提交失败”:核销 4、退款 7、扫码注册 3、资料资格 4、线下充值 7、佣金提现 5,同步模型注释与状态名称函数。
- [x] 1.3 `pkg/constants/approval.go` 新增 `ApprovalDecisionSubmissionFailed = "submission_failed"`。
## 2. 审批核心发出提交失败决策
- [x] 2.1 `markSubmissionState` 在状态 7 分支、实例更新成功后,同一事务内依次调用 `DecisionDeliveryWriter.Create` 与 `TerminalEventWriter.Append` 写 `submission_failed`(事件号 `approval:{实例ID}:submission_failed`,事件结构不加字段);状态 8 不发。`ApprovalContextRepository` 注入两个写入器并修改启动装配。
- [x] 2.2 核对 `approval_submission_consumer.go` 表单构造失败与企微明确拒绝两处均经该分支发出决策。
- [x] 2.3 `TerminalDecisionConsumer.Consume` 对 `submission_failed` 单独放行,`StatusForDecision` 与 `ApplyDecision` 不改,渠道回调仍拒绝该值。
- [x] 2.4 六个消费者处理 `submission_failed` 时按实例读取企微审批上下文 `last_error`,脱敏后写入终态原因与审计。
## 3. M13 退款关闭类终态定位
- [x] 3.1 `internal/service/refund/approval_decision.go` 的 `applyClosedDecision` 改为 `ResolveRefundInTx` 定位,再按 `target.ID` 对退款单加行锁;其余逻辑不变。
## 4. 六个业务消费者接入(同一次交付)
- [x] 4.1 核销:照 `applyClosed` 实现 `applySubmitFailed`(确认实例为 7、只处理最新尝试、释放全部预占、0→4 条件更新、终态原因、审计);`ValidateApplicationResubmit` 允许状态 4 重提。
- [x] 4.2 退款:新增提交失败分支,用 `ResolveRefundInTx` 定位,待审批→7 条件更新、记录原因、审计;状态 7 加入 `RefundResubmittableStatuses()`,不加入 `RefundActiveStatuses()`。
- [x] 4.3 扫码注册代理:0→3,不创建实体,审计。
- [x] 4.4 线下充值:待审批→7,不入账,审计。
- [x] 4.5 佣金提现:同事务释放冻结并记录释放时间,待审核→5,审计;`Resubmit` 扩展为允许状态 5,按新金额重新冻结。
- [x] 4.6 提现资料资格:0→4,审计;确认可提交新资料版本、不影响已通过版本。
## 5. 恢复入口与投影
- [x] 5.1 核销、退款、扫码注册三处恢复入口的提交失败 replay 分支改为拒绝“审批提交失败为终态,请重新发起”;`recoverable` 对新状态返回 false。
- [x] 5.2 核销列表与详情按最新审批实例批量读取企微上下文,填充提交状态、名称、脱敏摘要、可恢复、最近恢复结果与时间。
- [x] 5.3 六个业务的列表筛选、接口字段说明、导出状态格式化(含 `internal/exporter/refund_scene.go`)加入新状态;实现时 `grep` 各状态常量逐处核对。
## 6. 文档与测试环境验证
- [x] 6.1 `gofmt`、`go build ./cmd/api ./cmd/worker`、`go run cmd/gendocs/main.go`。
- [x] 6.2 在 `junhong_cmp_test` 执行新迁移(up、down、再 up)并确认旧数据不受影响。
- [ ] 6.3 按 ENG-TEST-001 用缺必填控件映射对六个业务类型各构造一次提交失败:业务单变为“审批提交失败”、占用释放(核销预占、提现冻结与钱包流水)、审计写入、列表筛选导出可见;恢复被拒;重新发起生成新尝试与新审批;同一事件重复投递结果不变。
- [ ] 6.4 构造提交结果未知的实例,业务单保持审批中。
- [ ] 6.5 核对每个提交失败事件都有决策投递记录且最终为成功;模拟渠道回调带 `submission_failed` 被拒、实例状态不变。
- [ ] 6.6 M13:对尝试模式退款分别用模拟企微撤销、拒绝、删除终态事件触发,退款单变为已拒绝、原因与审计正确、资产可换货;对其重新发起生成新审批;模拟卡管未知的企微单号回调只留痕;“通过”“通过后撤销”与早期 `business_id = 退款单 ID` 的数据回归不变。
- [ ] 6.7 核销列表与详情提交状态与测试库一致,无上下文申请正常返回,无逐行查询。
- [ ] 6.8 只读统计测试库“实例 7 或已终态、业务单仍审批中”的存量,需要时写一次性补数据脚本,经确认后执行。
- [ ] 6.9 运行 `openspec validate --all` 与 `./scripts/context-health.sh`。

View File

@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-11

View File

@@ -0,0 +1,31 @@
## Context
承接《第1批-8-9月迭代缺陷修复技术方案》第 4 节。`packageexpiry` 的 `Publish` 在每日扫描中给店铺接收人(`appendShopNotification`)和所有绑定客户(`loadRecipients`)批量写通知;个人通知列表(`PersonalNotificationListRequest`,`internal/model/dto/notification_dto.go:94`)无资产过滤。H5 令牌带当前资产(`middleware.GetCurrentAsset`),资产信息接口为 `GET /api/c/v1/asset/info`。Outbox 写入按 `event_id` 冲突忽略(`internal/infrastructure/messaging/outbox/repository.go:103`)。
## Goals / Non-Goals
**Goals:** 临期提醒只在客户进入该资产时出现,每天一次;通知中心只显示当前资产的临期提醒。
**Non-Goals:** 不改到期推算、提醒窗口与等级、店铺通知;不新增接口入参;无迁移。
## Decisions
1. **进入时判定,复用最终到期推算。** 在资产信息接口内按当前资产调用 `packageexpiry` 的推算,与每日扫描同口径。
2. **去重顺序:先查键 → 写通知 → `SET NX` → 抢到才返回字段。** 方案原顺序是“先写通知再 `SET NX`”,当天每次进入都会写一次 Outbox(虽冲突忽略,仍是无效写)。评审确认先用 Redis `EXISTS`/`GET` 检查,键存在直接返回,只有未提醒时才写通知。写通知成功后才占键,写失败不占键、不返回字段,避免“当天已去重但通知没发出”。两个并发请求都通过检查时,通知由事件号幂等,只有抢到键的一方返回字段。键定义放 `pkg/constants/redis.go`,TTL 到当天上海时间结束再加缓冲。
3. **Redis 不可用按未提醒处理。** 字段可能当天多次返回,通知由事件号兜底不重复;接受该降级,不因 Redis 故障让资产信息接口失败。
4. **只用 `ref_key` 过滤,列表、未读数、全部已读同一口径。** `ref_id` 不带资产类型,卡 5 与设备 5 冲突。过滤只作用于 `type = package.expiring AND ref_type = asset`。“全部已读”(`PUT /notifications/read-all`)也加同样的条件,否则会把客户在其他资产才能看到的临期提醒一并标为已读。
5. **停用个人客户预发布。** 去掉 `Publish` 里给绑定客户批量写通知的循环,店铺通知不变。
## Risks / Trade-offs
- [GET 接口产生写副作用] → 只在当天首次命中时写一次通知,其余请求只读 Redis。
- [设备补虚拟号后历史提醒匹配不上] → 影响可接受,已在 spec 中写明。
- [资产信息接口延迟增加] → 推算与 Redis 检查各一次;推算结果为非临期时不访问 Redis。
## Migration Plan
无迁移。测试环境部署后,每日扫描不再产生个人客户临期通知;已有个人通知按过滤规则展示。
## Open Questions
- 资产信息响应中提醒字段的具体命名在实现时确定,并写入接口文档。

View File

@@ -0,0 +1,26 @@
## Why
套餐临期提醒发给所有绑定过该资产的客户(`reminder_publisher.go` 的 `loadRecipients`),个人通知列表又没有资产过滤,客户在任一资产页都会看到名下全部资产的临期提醒(运营清单 26)。业务已确认改为按资产提醒:哪个资产被扫码进入就提醒哪个,同一客户、同一资产、同一天只提醒一次。依据为《第1批-8-9月迭代缺陷修复技术方案》第 4 节(M9)。
## What Changes
- H5 资产信息接口 `GET /api/c/v1/asset/info` 在当前资产处于临期窗口(剩余 0~15 天)且当天未提醒过时,返回临期提醒字段(剩余天数、到期时间、等级),并为“当前客户、当前资产”写一条 `package.expiring` 个人通知;同一客户、同一资产、同一北京时间日期只提醒一次。
- **BREAKING** 每日扫描不再给个人客户写临期通知;店铺通知不变。
- **BREAKING** 个人通知列表、未读数与“全部已读”中,临期提醒只处理当前资产的;其他类型通知不受影响,接口入参不变。
## Capabilities
### New Capabilities
无。
### Modified Capabilities
- `notification-delivery`:每日临期扫描只通知店铺接收人;新增 H5 进入资产时的临期提醒;个人通知中心临期提醒按当前资产过滤。
## Impact
- 代码:`internal/infrastructure/packageexpiry/reminder_publisher.go`(去掉个人客户批量写入)、H5 资产信息 Handler 与服务(复用 `packageexpiry` 最终到期推算、写 Outbox 个人通知)、个人通知列表与未读数查询、`pkg/constants/redis.go`(去重键)、资产信息响应 DTO。
- 接口:`GET /api/c/v1/asset/info` 新增字段;个人通知列表与未读数结果范围变化;重新生成接口文档。
- 依赖:Redis(去重键);Outbox 按 `event_id` 冲突忽略写入(`internal/infrastructure/messaging/outbox/repository.go`)。
- 无数据库迁移。

View File

@@ -0,0 +1,65 @@
## MODIFIED Requirements
### Requirement: 套餐临期每日站内提醒
系统 SHALL 在每日扫描时,向最终到期时间可精确推算且剩余 0 至 15 个上海自然日的资产所属店铺后台接收人创建套餐临期站内通知。系统 MUST 对同一资产、同一最终到期日期、同一剩余天数和同一接收人保持幂等。每日扫描 MUST NOT 向个人客户创建套餐临期通知;个人客户的临期提醒只按“H5 进入资产时的套餐临期提醒”产生。
#### Scenario: 临期窗口内连续两日提醒
- **GIVEN** 一项资产的最终到期时间可精确推算,昨天剩余 3 个上海自然日,今天剩余 2 个上海自然日,且两日均有有效店铺接收人
- **WHEN** 每日临期扫描分别执行
- **THEN** 系统分别为店铺接收人创建昨天和今天的套餐临期通知
#### Scenario: 不在临期窗口的资产
- **GIVEN** 一项资产剩余超过 15 个上海自然日、已经到期或最终到期时间不可精确推算
- **WHEN** 每日临期扫描执行
- **THEN** 系统不为该资产创建套餐临期通知
#### Scenario: 每日扫描不通知个人客户
- **GIVEN** 一项临期资产绑定了个人客户
- **WHEN** 每日临期扫描执行
- **THEN** 系统只为店铺接收人创建通知,不为个人客户创建通知
## ADDED Requirements
### Requirement: H5 进入资产时的套餐临期提醒
个人客户访问 `GET /api/c/v1/asset/info` 时,系统 SHALL 以令牌中的当前资产,按与每日扫描相同的最终到期推算判断是否临期(剩余 0~15 个上海自然日,≤3 红、≤7 紫、≤15 粉红)。命中且该客户当天(上海自然日)尚未就该资产提醒过时,系统 MUST 在响应中返回临期提醒字段(剩余天数、到期时间、等级),并为当前客户、当前资产写一条 `package.expiring` 个人通知,通知幂等事件号 MUST 包含资产、到期日、剩余天数与客户。
同一客户、同一资产、同一上海自然日 MUST 至多返回一次提醒字段、至多产生一条通知;去重键为“客户 + 资产标识 + 日期”。系统 MUST 先检查去重键,已存在则不返回字段、不写通知;不存在时先写通知,写入成功后再占用去重键,抢占成功才返回字段。通知写入失败时 MUST NOT 占用去重键、MUST NOT 返回字段,下次进入重试。去重存储不可用时系统按“未提醒过”处理,提醒字段可能当天多次返回,通知由事件号幂等保证不重复。
#### Scenario: 当天首次进入临期资产
- **WHEN** 客户首次在当天进入一项剩余 2 天的资产
- **THEN** 响应返回剩余天数 2、到期时间与红色等级,并新增一条该资产的临期通知
#### Scenario: 同一天再次进入
- **WHEN** 同一客户当天再次进入该资产
- **THEN** 响应不返回临期提醒字段,不新增通知
#### Scenario: 第二天再次进入
- **WHEN** 同一客户第二天进入该资产且仍在临期窗口
- **THEN** 再次返回提醒字段并新增一条通知
#### Scenario: 不同客户进入同一资产
- **WHEN** 客户 B 当天进入客户 A 已被提醒过的资产
- **THEN** 客户 B 独立获得一次提醒
#### Scenario: 非临期资产
- **WHEN** 客户进入剩余超过 15 天或最终到期不可精确推算的资产
- **THEN** 响应不返回临期提醒字段,不写通知
### Requirement: 个人通知中心临期提醒按当前资产过滤
个人客户通知列表、未读数与“全部已读”(`PUT /api/c/v1/notifications/read-all`)SHALL 对 `type = package.expiring` 且 `ref_type = asset` 的通知,只处理 `ref_key` 等于当前资产标识的通知(卡为 ICCID;设备优先虚拟号,为空则 IMEI);MUST NOT 使用 `ref_id` 过滤。“全部已读”MUST NOT 把其他资产的临期提醒标为已读。其他类型通知 MUST 不受影响,接口入参不变。设备后补虚拟号前产生的历史提醒 `ref_key` 为 IMEI,补号后不再匹配,属可接受限制。
#### Scenario: 客户名下两个临期资产
- **GIVEN** 客户名下资产 A、B 都有临期通知
- **WHEN** 客户在资产 A 中查询通知列表与未读数
- **THEN** 临期通知只含 A 的,未读数只计 A 的临期通知与其他类型通知
#### Scenario: 全部已读只处理当前资产的临期提醒
- **GIVEN** 客户名下资产 A、B 都有未读临期通知
- **WHEN** 客户在资产 A 中点“全部已读”
- **THEN** A 的临期通知与其他类型通知变为已读,B 的临期通知仍为未读,客户进入 B 时仍能看到
#### Scenario: 非临期通知不受过滤
- **WHEN** 客户在资产 A 中查询通知列表
- **THEN** 非 `package.expiring` 类型的通知照常返回

View File

@@ -0,0 +1,20 @@
## 1. 停用个人客户预发布
- [x] 1.1 `internal/infrastructure/packageexpiry/reminder_publisher.go` 的 `Publish` 去掉给绑定客户批量写个人通知的循环,保留 `appendShopNotification`。
## 2. 进入资产时提醒
- [x] 2.1 `pkg/constants/redis.go` 新增去重键(客户 ID + 资产标识 + 上海日期)及 TTL 计算(当天结束加缓冲)。
- [x] 2.2 资产信息服务按当前资产复用 `packageexpiry` 最终到期推算;命中窗口时依次:检查键 → 经 Outbox 写 `package.expiring` 个人通知(事件号 `pex:资产:到期日:剩余天数:客户`)→ `SET NX` → 抢到才返回字段;写通知失败不占键不返回;Redis 不可用按未提醒处理。
- [x] 2.3 资产信息响应 DTO 新增临期提醒字段(剩余天数、到期时间、等级),更新接口说明。
## 3. 通知中心过滤
- [x] 3.1 个人通知列表、未读数与“全部已读”对 `type = package.expiring AND ref_type = asset` 只保留 `ref_key` 等于当前资产标识(卡 ICCID;设备虚拟号,空则 IMEI)的记录,其他类型不变,入参不变。
## 4. 文档与测试环境验证
- [x] 4.1 `gofmt`、`go build ./cmd/api ./cmd/worker`、`go run cmd/gendocs/main.go`。
- [ ] 4.2 按 ENG-TEST-001(测试库 `junhong_cmp_test`、Redis DB 6)构造同一客户绑定两个临期资产:进入 A 只返回 A 的字段并新增 A 的通知,通知中心与未读数只含 A;在 A 中“全部已读”后 B 的临期通知仍未读;同一天再次进入 A 不返回字段、不新增通知;清理键模拟第二天后再次提醒;客户 B 进入 A 独立提醒一次;非临期通知不受过滤。
- [ ] 4.3 手动触发每日扫描:不再给个人客户写临期通知,店铺通知照常。
- [ ] 4.4 运行 `openspec validate --all` 与 `./scripts/context-health.sh`。

View File

@@ -7,6 +7,8 @@ const (
AgentDistributionRegistrationStatusApproved = 1
// AgentDistributionRegistrationStatusRejected 表示注册记录已驳回,未创建任何实体。
AgentDistributionRegistrationStatusRejected = 2
// AgentDistributionRegistrationStatusSubmissionFailed 表示提交企业微信审批被明确拒绝,注册终止且未创建任何实体。
AgentDistributionRegistrationStatusSubmissionFailed = 3
)
const (
@@ -23,6 +25,8 @@ func GetAgentDistributionRegistrationStatusName(status int) string {
return "已通过"
case AgentDistributionRegistrationStatusRejected:
return "已驳回"
case AgentDistributionRegistrationStatusSubmissionFailed:
return ApprovalSubmissionFailedStatusName
default:
return "未知"
}

View File

@@ -228,6 +228,15 @@ const (
ApprovalDecisionDeleted = "deleted"
// ApprovalDecisionRevokedAfterApproved 表示标准审批通过后撤销决策。
ApprovalDecisionRevokedAfterApproved = "revoked_after_approved"
// ApprovalDecisionSubmissionFailed 表示审批提交被企业微信明确拒绝(实例进入提交失败),由审批核心在同一事务内发出。
// 该值只在终态决策消费入口放行,渠道回调状态推进不接受此值。
ApprovalDecisionSubmissionFailed = "submission_failed"
// ApprovalSubmissionFailedStatusName 各业务“审批提交失败”终态的统一中文名称。
ApprovalSubmissionFailedStatusName = "审批提交失败"
// ApprovalSubmissionFailedReason 提交失败对外展示的脱敏原因,不透传企微原文。
ApprovalSubmissionFailedReason = "审批提交失败,请检查审批模板与渠道状态"
// ApprovalSubmissionFailedNotRecoverableMessage 恢复入口拒绝重放提交失败审批时的提示。
ApprovalSubmissionFailedNotRecoverableMessage = "审批提交失败为终态,请重新发起"
)
const (
@@ -285,6 +294,8 @@ const (
ApprovalSyncSourcePolling = "polling"
// ApprovalSyncSourceManual 表示由受控人工动作触发权威同步。
ApprovalSyncSourceManual = "manual"
// ApprovalSyncSourceSubmission 表示由审批提交 Worker 在提交被明确拒绝时发出决策。
ApprovalSyncSourceSubmission = "submission"
)
// GetApprovalStatusName 返回通用审批状态的中文名称。

View File

@@ -31,6 +31,8 @@ const (
EmployeeCollectionApplicationStatusRejected = 2
// EmployeeCollectionApplicationStatusRevoked 表示核销申请通过后撤销等异常终态或已关闭。
EmployeeCollectionApplicationStatusRevoked = 3
// EmployeeCollectionApplicationStatusSubmissionFailed 表示提交企业微信审批被明确拒绝,申请终止并释放预占。
EmployeeCollectionApplicationStatusSubmissionFailed = 4
)
// 核销分摊状态,取值与 tb_employee_collection_application_allocation.status 检查约束一致。
@@ -118,6 +120,8 @@ func GetEmployeeCollectionApplicationStatusName(status int) string {
return "已驳回"
case EmployeeCollectionApplicationStatusRevoked:
return "已撤销或已关闭"
case EmployeeCollectionApplicationStatusSubmissionFailed:
return ApprovalSubmissionFailedStatusName
default:
return "未知状态"
}

View File

@@ -248,6 +248,8 @@ const (
WithdrawalStatusApproved = 2 // 已通过
WithdrawalStatusRejected = 3 // 已拒绝
WithdrawalStatusPaid = 4 // 已到账
// WithdrawalStatusSubmissionFailed 提交企业微信审批被明确拒绝,提现终止并释放冻结金额。
WithdrawalStatusSubmissionFailed = 5
)
// 提现方式
@@ -416,7 +418,7 @@ func GetOrderCommissionResultName(result int) string {
}
// GetRefundStatusName 获取退款申请状态名称
// 1=待审批, 2=已通过, 3=已拒绝, 4=已退回, 5=原路退款处理中, 6=原路退款失败
// 1=待审批, 2=已通过, 3=已拒绝, 4=已退回, 5=原路退款处理中, 6=原路退款失败, 7=审批提交失败
func GetRefundStatusName(status int) string {
switch status {
case 1:
@@ -431,13 +433,15 @@ func GetRefundStatusName(status int) string {
return "原路退款处理中"
case 6:
return "原路退款失败"
case 7:
return ApprovalSubmissionFailedStatusName
default:
return "未知"
}
}
// GetWithdrawalStatusName 获取提现申请状态名称
// 对应 WithdrawalStatus* 常量:1=待审核, 2=已通过, 3=已拒绝, 4=已到账
// 对应 WithdrawalStatus* 常量:1=待审核, 2=已通过, 3=已拒绝, 4=已到账, 5=审批提交失败
func GetWithdrawalStatusName(status int) string {
switch status {
case WithdrawalStatusPending:
@@ -448,6 +452,8 @@ func GetWithdrawalStatusName(status int) string {
return "已拒绝"
case WithdrawalStatusPaid:
return "已到账"
case WithdrawalStatusSubmissionFailed:
return ApprovalSubmissionFailedStatusName
default:
return "未知"
}

View File

@@ -59,6 +59,9 @@ const (
NotificationRefTypePackage = "package"
// NotificationRefTypeAsset 表示个人客户资产资源引用。
NotificationRefTypeAsset = "asset"
// NotificationPersonalExpiringAssetCondition 个人通知中心只保留当前资产的套餐临期提醒:
// 参数依次为临期通知类型、资产引用类型、当前资产标识(卡 ICCID;设备虚拟号,空则 IMEI);不按 ref_id 过滤。
NotificationPersonalExpiringAssetCondition = "(NOT (type = ? AND ref_type = ?) OR ref_key = ?)"
// NotificationRefTypeRefund 表示退款详情资源引用。
NotificationRefTypeRefund = "refund"
// NotificationRefTypeAgentRecharge 表示代理充值详情资源引用。

View File

@@ -24,6 +24,10 @@ const (
PhoneAssetAssociationInvalidateMethodBackendBatch = "backend_batch"
// PhoneAssetAssociationInvalidateMethodCSVImport 表示 CSV 导入解除。
PhoneAssetAssociationInvalidateMethodCSVImport = "csv_import"
// PhoneAssetAssociationInvalidateMethodExchangeCompleted 表示换货完成时随旧资产一并失效。
PhoneAssetAssociationInvalidateMethodExchangeCompleted = "exchange_completed"
// PhoneAssetAssociationExchangeCompletedReason 换货完成失效旧资产关联的原因。
PhoneAssetAssociationExchangeCompletedReason = "换货完成"
)
// 手机号—资产关联的业务口径常量。
@@ -136,6 +140,8 @@ func PhoneAssetAssociationInvalidateMethodName(method string) string {
return "后台批量解除"
case PhoneAssetAssociationInvalidateMethodCSVImport:
return "CSV导入解除"
case PhoneAssetAssociationInvalidateMethodExchangeCompleted:
return "换货完成失效"
default:
return "未知"
}

View File

@@ -1,6 +1,9 @@
package constants
import "fmt"
import (
"fmt"
"time"
)
// ========================================
// 认证相关 Redis Key
@@ -556,6 +559,16 @@ func RedisPollingConfigChangedChannel() string {
// 系统全局配置 Redis Key
// ========================================
// RedisPackageExpiryEntryReminderKey H5 进入资产时套餐临期提醒的去重键
// 用途:同一客户、同一资产、同一上海自然日至多返回一次提醒字段
// 过期时间:当天上海时间结束后再加缓冲,由调用方计算
func RedisPackageExpiryEntryReminderKey(customerID uint, assetType, assetIdentifier, shanghaiDate string) string {
return fmt.Sprintf("package_expiry:entry_reminder:%d:%s:%s:%s", customerID, assetType, assetIdentifier, shanghaiDate)
}
// PackageExpiryEntryReminderTTLBuffer 临期提醒去重键在当天结束后保留的缓冲时长。
const PackageExpiryEntryReminderTTLBuffer = time.Hour
// RedisSystemOperationPasswordKey 全局操作密码 Redis 键
// 用途:存储超级管理员设置的全局操作密码(bcrypt 哈希值)
// 过期时间:永久存储(无 TTL)

View File

@@ -136,6 +136,8 @@ const (
RechargeStatusClosed = 4 // 已关闭
RechargeStatusRefunded = 5 // 已退款
RechargeStatusRejected = 6 // 已驳回
// RechargeStatusSubmissionFailed 线下代理充值提交企业微信审批被明确拒绝,充值终止且不入账。
RechargeStatusSubmissionFailed = 7
)
// 充值支付方式
@@ -161,7 +163,7 @@ const (
// ========== Redis Key 生成函数 ==========
// GetRechargeStatusName 获取充值状态名称
// 对应 RechargeStatus* 常量:1=待支付, 2=已支付, 3=已完成, 4=已关闭, 5=已退款, 6=已驳回
// 对应 RechargeStatus* 常量:1=待支付, 2=已支付, 3=已完成, 4=已关闭, 5=已退款, 6=已驳回, 7=审批提交失败
func GetRechargeStatusName(status int) string {
switch status {
case RechargeStatusPending:
@@ -176,6 +178,8 @@ func GetRechargeStatusName(status int) string {
return "已退款"
case RechargeStatusRejected:
return "已驳回"
case RechargeStatusSubmissionFailed:
return ApprovalSubmissionFailedStatusName
default:
return "未知"
}

View File

@@ -16,6 +16,8 @@ const (
WithdrawalQualificationStatusRejected = 2
// WithdrawalQualificationStatusInvalidated 表示资料版本已失效或已被超级管理员作废。
WithdrawalQualificationStatusInvalidated = 3
// WithdrawalQualificationStatusSubmissionFailed 表示资料版本提交企业微信审批被明确拒绝,该版本终止。
WithdrawalQualificationStatusSubmissionFailed = 4
)
// WithdrawalQualificationCheckPassed 表示本次提现资料资格校验通过。
@@ -66,6 +68,8 @@ func GetWithdrawalQualificationStatusName(status int) string {
return "已驳回"
case WithdrawalQualificationStatusInvalidated:
return "已失效"
case WithdrawalQualificationStatusSubmissionFailed:
return ApprovalSubmissionFailedStatusName
default:
return "未知"
}

View File

@@ -157,6 +157,7 @@ const (
CodeRealnameNotAvailable = 1189 // 请先完成充值或购买套餐后再进行实名认证
CodeOpenAPITimestampInvalid = 1190 // 开放接口时间戳无效
CodeOpenAPINonceReplay = 1191 // 开放接口 nonce 重放
CodeAssetPhoneAlreadyBound = 1192 // 资产已绑定其他手机号(一资产一号)
// 换货相关错误 (1200-1209)
CodeExchangeOrderNotFound = 1200 // 换货单不存在
@@ -328,6 +329,7 @@ var allErrorCodes = []int{
CodeRealnameNotAvailable,
CodeOpenAPITimestampInvalid,
CodeOpenAPINonceReplay,
CodeAssetPhoneAlreadyBound,
CodeExchangeOrderNotFound,
CodeExchangeInProgress,
CodeExchangeStatusInvalid,
@@ -477,6 +479,7 @@ var errorMessages = map[int]string{
CodeSmsSendFailed: "短信发送失败",
CodeVerificationCodeInvalid: "验证码错误或已过期",
CodePhoneAlreadyBound: "手机号已被其他客户绑定",
CodeAssetPhoneAlreadyBound: "该资产已绑定手机号,如需更换请联系管理员",
CodeAlreadyBoundPhone: "当前客户已绑定手机号,不可重复绑定",
CodeOldPhoneMismatch: "旧手机号与当前绑定不匹配",
CodeNeedRealname: "该套餐需实名认证后购买",