Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
AUG26-008。
- 迁移 000214–000217:tb_shop 全局唯一且不可修改的随机分销码(含存量回填)、
tb_agent_distribution_registration 待审批注册记录、tb_withdrawal_qualification 资料版本、
tb_commission_withdrawal_request_attempt 审批尝试记录,以及提现申请的 latest_*/异常标记列;
不修改既有迁移,down 在存在本 Change 业务事实或新类型场景行时拒绝破坏性回滚。
- 公开接口 POST /api/c/v1/agent-distribution-registrations:无认证,复用既有短信验证码校验、
消费与限流;无效分销码、停用上级、验证码无效或已消费统一返回「分销码不可用」且不落库,
审批通过前不创建店铺、账号或钱包。
- 审批通过才在同一事务内建启用店铺、代理主账号、钱包、上级层级与业务员快照,驳回不建实体,
重复回调不重复建实体,提交后清理上级下级缓存。
- 提现资料资格按不可变版本保存,替换合同或法人身份证即新增版本并同事务失效旧有效版本;
超管作废原因必填;代理停用与店铺删除联动失效。
- 提现每次提交或重提新增不可变审批尝试记录并冻结金额;企业微信通过仅一次从冻结扣减、
保持状态 2 并写 paid_at(不使用状态 4),驳回/cancelled/deleted 仅一次释放,
通过后撤销不回滚、不重新冻结、只写正交异常标记;加锁顺序统一为申请→尝试→钱包。
- 本地人工终审对已关联审批实例的申请返回状态冲突,approval_instance_id 为空的存量申请保持既有行为,
不新增任何配置开关。
- 补齐审批业务类型注册点全集:业务类型与场景字段常量、场景 DTO 两处枚举与中文描述、
场景字段白名单/合法类型/中文名、数据库 CHECK、Worker 决策消费者与装配、审批审计资源映射,
以及三个新审计资源与 13 个审计动作;失败/拒绝审计改为必达。
- 新增后台路由与 OpenAPI:资格提交/查询/作废、提现申请/重提/详情、店铺详情返回只读分销码。
- 归档本 Change:主 Spec 新增 agent-distribution-withdrawal 能力(5 个 Requirement)。
验证(junhong_cmp_test + Redis DB 6,显式 DB_*,未重置整库):
- 迁移 up → version 217 且 dirty=false → down 3 → up 回 217,fixture 复核残留为 0。
- 受控状态机脚手架 227 项通过 / 0 项失败,覆盖 18 组场景(幂等与乱序回调、资金冻结/释放/重提、
退款回扣 × 在途提现并发、负向场景拒绝审计与 14 个动作码审计真实落库)。
- gofmt 空、go build/go vet 通过、gendocs 与工作区逐字节一致、context-health 通过、
openspec validate --strict 通过、doctor healthy;自动化测试按项目决策为 N/A。
运行期前置(未完成,非代码交付物):由超管经 PUT /api/admin/wecom/scenes/{business_type} 为
agent_distribution_approval、withdrawal_qualification_approval、commission_withdrawal_approval
配置启用场景与模板控件映射;未配置时相应提交失败关闭。
280 lines
12 KiB
Go
280 lines
12 KiB
Go
package distributionwithdrawal
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
approvalapp "github.com/break/junhong_cmp_fiber/internal/application/approval"
|
|
shopapp "github.com/break/junhong_cmp_fiber/internal/application/shop"
|
|
"github.com/break/junhong_cmp_fiber/internal/model"
|
|
"github.com/break/junhong_cmp_fiber/pkg/auditcontext"
|
|
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
|
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
|
)
|
|
|
|
// SubordinateCacheInvalidator 在审批通过事务提交后清理上级店铺下级集合缓存。
|
|
type SubordinateCacheInvalidator interface {
|
|
InvalidateSubordinateCache(ctx context.Context, shopID uint)
|
|
}
|
|
|
|
// DistributionApprovalHandler 将渠道无关企业微信终态应用到代理扫码注册记录。
|
|
// 通过才在单一事务内创建启用店铺、代理主账号、所需钱包、上级层级与业务员快照;
|
|
// 驳回只标记注册记录,不创建任何实体;重复或乱序回调不重复创建账号、层级或钱包。
|
|
type DistributionApprovalHandler struct {
|
|
db *gorm.DB
|
|
audit AuditWriter
|
|
cache SubordinateCacheInvalidator
|
|
}
|
|
|
|
// NewDistributionApprovalHandler 创建代理分销注册审批终态消费者。
|
|
func NewDistributionApprovalHandler(
|
|
db *gorm.DB,
|
|
audit AuditWriter,
|
|
cache SubordinateCacheInvalidator,
|
|
) *DistributionApprovalHandler {
|
|
return &DistributionApprovalHandler{db: db, audit: audit, cache: cache}
|
|
}
|
|
|
|
// Handle 幂等消费标准审批终态。
|
|
// 业务标识为待审批注册记录主键;先锁定注册记录并校验审批实例一致,再按条件更新推进状态。
|
|
func (h *DistributionApprovalHandler) Handle(ctx context.Context, event approvalapp.TerminalDecisionEvent) error {
|
|
if h == nil || h.db == nil || h.audit == nil {
|
|
return errors.New(errors.CodeInternalError, "代理分销注册审批终态能力未配置")
|
|
}
|
|
if event.BusinessType != constants.ApprovalBusinessTypeAgentDistribution ||
|
|
event.BusinessID == 0 || event.InstanceID == 0 {
|
|
return errors.New(errors.CodeInvalidParam, "代理分销注册审批终态参数无效")
|
|
}
|
|
ctx = auditcontext.With(ctx, auditcontext.Context{
|
|
CorrelationID: event.CorrelationID, ParentEventID: event.EventID,
|
|
})
|
|
parentShopID := uint(0)
|
|
err := h.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
registration, err := lockRegistrationForUpdate(ctx, tx, event.BusinessID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if registration.ApprovalInstanceID == nil || *registration.ApprovalInstanceID != event.InstanceID {
|
|
return errors.New(errors.CodeConflict, "扫码注册记录关联的审批实例不一致")
|
|
}
|
|
if registration.Status != constants.AgentDistributionRegistrationStatusPending {
|
|
// 已是终态:重复或乱序回调不再改变事实。
|
|
return nil
|
|
}
|
|
switch event.Decision {
|
|
case constants.ApprovalDecisionApproved:
|
|
parentShopID = registration.ParentShopID
|
|
return h.applyApproved(ctx, tx, registration, event)
|
|
case constants.ApprovalDecisionRejected,
|
|
constants.ApprovalDecisionCancelled,
|
|
constants.ApprovalDecisionDeleted:
|
|
return h.applyRejected(ctx, tx, registration, event)
|
|
case constants.ApprovalDecisionRevokedAfterApproved:
|
|
// 注册记录无已建立的对外资金事实;通过后撤销按驳回处理并保留渠道决策痕迹。
|
|
return h.applyRejected(ctx, tx, registration, event)
|
|
default:
|
|
return errors.New(errors.CodeInvalidParam, "不支持的代理分销注册审批终态")
|
|
}
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if parentShopID != 0 && h.cache != nil {
|
|
// 缓存清理必须在事务提交后执行,避免回滚后缓存与库内事实不一致。
|
|
h.cache.InvalidateSubordinateCache(ctx, parentShopID)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// applyApproved 在同一事务内建立店铺、账号、钱包、层级与业务员快照。
|
|
// 上级店铺必须仍然存在且启用;手机号或用户名已被并发注册占用时整体回滚,不留半套实体。
|
|
func (h *DistributionApprovalHandler) applyApproved(
|
|
ctx context.Context,
|
|
tx *gorm.DB,
|
|
registration *model.AgentDistributionRegistration,
|
|
event approvalapp.TerminalDecisionEvent,
|
|
) error {
|
|
parent, err := loadEnabledParentShop(ctx, tx, registration.ParentShopID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
level := parent.Level + 1
|
|
if level > constants.ShopMaxLevel {
|
|
return errors.New(errors.CodeShopLevelExceeded, "店铺层级不能超过 7 级")
|
|
}
|
|
role, err := loadEnabledCustomerRole(ctx, tx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
shop := &model.Shop{
|
|
ShopName: registration.ShopName, ShopCode: registration.ShopCode,
|
|
ParentID: &parent.ID, Level: level,
|
|
ContactName: registration.ContactName, Province: registration.Province,
|
|
City: registration.City, District: registration.District, Address: registration.Address,
|
|
Status: constants.ShopStatusEnabled,
|
|
}
|
|
shop.BusinessOwnerAccountID = parent.BusinessOwnerAccountID
|
|
shop.Creator = registration.ID
|
|
shop.Updater = registration.ID
|
|
// 新店铺生成自己的分销码:注册记录上的分销码是上级店铺快照,复用会与父店铺同码并命中唯一索引。
|
|
if err := shopapp.CreateShopWithDistributionCode(ctx, tx, shop); err != nil {
|
|
return err
|
|
}
|
|
account := &model.Account{
|
|
Username: registration.Username, Phone: registration.Phone,
|
|
Password: registration.PasswordHash, UserType: constants.UserTypeAgent,
|
|
ShopID: &shop.ID, Status: constants.StatusEnabled, IsPrimary: true,
|
|
}
|
|
account.Creator = registration.ID
|
|
account.Updater = registration.ID
|
|
if err := tx.WithContext(ctx).Create(account).Error; err != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, err, "创建扫码注册代理账号失败")
|
|
}
|
|
if err := tx.WithContext(ctx).Create(&model.AccountRole{
|
|
AccountID: account.ID, RoleID: role.ID, Status: constants.StatusEnabled,
|
|
Creator: registration.ID, Updater: registration.ID,
|
|
}).Error; err != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, err, "为扫码注册代理账号分配角色失败")
|
|
}
|
|
if err := tx.WithContext(ctx).Create(&model.ShopRole{
|
|
ShopID: shop.ID, RoleID: role.ID, Status: constants.StatusEnabled,
|
|
Creator: registration.ID, Updater: registration.ID,
|
|
}).Error; err != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, err, "设置扫码注册店铺默认角色失败")
|
|
}
|
|
if err := tx.WithContext(ctx).Create([]*model.AgentWallet{
|
|
{
|
|
ShopID: shop.ID, WalletType: constants.AgentWalletTypeMain,
|
|
CreditEnabled: role.DefaultCreditEnabled, CreditLimit: role.DefaultCreditLimit,
|
|
Currency: "CNY", Status: constants.AgentWalletStatusNormal, ShopIDTag: shop.ID,
|
|
},
|
|
{
|
|
ShopID: shop.ID, WalletType: constants.AgentWalletTypeCommission,
|
|
CreditEnabled: false, CreditLimit: 0,
|
|
Currency: "CNY", Status: constants.AgentWalletStatusNormal, ShopIDTag: shop.ID,
|
|
},
|
|
}).Error; err != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, err, "初始化扫码注册店铺钱包失败")
|
|
}
|
|
if err := markRegistrationApproved(ctx, tx, registration); err != nil {
|
|
return err
|
|
}
|
|
// 建店与业务员归属的访问审计不在本用例职责内:该动作面向后台账号入口,
|
|
// 由审批消费任务触发的建店无法提供其要求的操作者/数据范围投影,
|
|
// 强行写入会以「账号权限或组织审计操作者不完整」失败并中止事务。
|
|
// 新建店铺已作为 CreatedShop 资源记录在本用例的分销审计中。
|
|
return h.audit.WriteDistributionWithdrawal(ctx, tx, AuditChange{
|
|
EventID: "agent-distribution:" + uintText(registration.ID) + ":approved",
|
|
ActionCode: constants.AuditActionAgentDistributionRegistrationApproved,
|
|
Summary: "企业微信通过扫码注册,已创建店铺与代理账号",
|
|
CorrelationID: event.CorrelationID, Registration: registration,
|
|
ParentShop: parent, CreatedShop: shop,
|
|
AppliedDistributionCode: registration.DistributionCode,
|
|
AfterData: registrationAuditSnapshot(registration),
|
|
})
|
|
}
|
|
|
|
// applyRejected 只标记注册记录终态,不创建店铺、账号、钱包或层级。
|
|
func (h *DistributionApprovalHandler) applyRejected(
|
|
ctx context.Context,
|
|
tx *gorm.DB,
|
|
registration *model.AgentDistributionRegistration,
|
|
event approvalapp.TerminalDecisionEvent,
|
|
) 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,
|
|
"reject_reason": reason, "decided_at": now, "updater": 0,
|
|
})
|
|
if result.Error != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, result.Error, "标记扫码注册记录已驳回失败")
|
|
}
|
|
if result.RowsAffected != 1 {
|
|
return errors.New(errors.CodeConflict, "扫码注册记录状态已变化")
|
|
}
|
|
before := registration.Status
|
|
registration.Status = constants.AgentDistributionRegistrationStatusRejected
|
|
registration.RejectReason = reason
|
|
registration.DecidedAt = &now
|
|
return h.audit.WriteDistributionWithdrawal(ctx, tx, AuditChange{
|
|
EventID: "agent-distribution:" + uintText(registration.ID) + ":rejected",
|
|
ActionCode: constants.AuditActionAgentDistributionRegistrationRejected,
|
|
Summary: "企业微信未通过扫码注册,未创建任何实体",
|
|
CorrelationID: event.CorrelationID, Registration: registration,
|
|
BeforeData: map[string]any{"status": before},
|
|
AfterData: registrationAuditSnapshot(registration),
|
|
})
|
|
}
|
|
|
|
// markRegistrationApproved 以待审批状态条件更新标记注册记录已通过,重复回调不重复推进。
|
|
func markRegistrationApproved(
|
|
ctx context.Context,
|
|
tx *gorm.DB,
|
|
registration *model.AgentDistributionRegistration,
|
|
) error {
|
|
now := time.Now().UTC()
|
|
result := tx.WithContext(ctx).Model(&model.AgentDistributionRegistration{}).
|
|
Where("id = ? AND status = ?", registration.ID, constants.AgentDistributionRegistrationStatusPending).
|
|
Updates(map[string]any{
|
|
"status": constants.AgentDistributionRegistrationStatusApproved,
|
|
"decided_at": now, "updater": 0,
|
|
})
|
|
if result.Error != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, result.Error, "标记扫码注册记录已通过失败")
|
|
}
|
|
if result.RowsAffected != 1 {
|
|
return errors.New(errors.CodeConflict, "扫码注册记录状态已变化")
|
|
}
|
|
registration.Status = constants.AgentDistributionRegistrationStatusApproved
|
|
registration.DecidedAt = &now
|
|
return nil
|
|
}
|
|
|
|
// rejectionReason 把渠道决策映射为可查询的中文驳回原因。
|
|
func rejectionReason(decision string) string {
|
|
switch decision {
|
|
case constants.ApprovalDecisionCancelled:
|
|
return "企业微信审批已撤销"
|
|
case constants.ApprovalDecisionDeleted:
|
|
return "企业微信审批已删除"
|
|
case constants.ApprovalDecisionRevokedAfterApproved:
|
|
return "企业微信审批通过后撤销"
|
|
default:
|
|
return "企业微信审批已驳回"
|
|
}
|
|
}
|
|
|
|
// loadEnabledParentShop 校验分销码所属店铺仍存在且启用。
|
|
func loadEnabledParentShop(ctx context.Context, tx *gorm.DB, shopID uint) (*model.Shop, error) {
|
|
var parent model.Shop
|
|
if err := tx.WithContext(ctx).First(&parent, shopID).Error; err != nil {
|
|
if err == gorm.ErrRecordNotFound {
|
|
return nil, errors.New(errors.CodeNotFound, "上级店铺不存在")
|
|
}
|
|
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询上级店铺失败")
|
|
}
|
|
if parent.Status != constants.ShopStatusEnabled {
|
|
return nil, errors.New(errors.CodeInvalidStatus, "上级店铺已停用,不允许注册下级")
|
|
}
|
|
return &parent, nil
|
|
}
|
|
|
|
// loadEnabledCustomerRole 读取启用的客户角色,用于新建代理店铺的默认角色与信用额度。
|
|
func loadEnabledCustomerRole(ctx context.Context, tx *gorm.DB) (*model.Role, error) {
|
|
var role model.Role
|
|
if err := tx.WithContext(ctx).
|
|
Where("role_type = ? AND status = ?", constants.RoleTypeCustomer, constants.StatusEnabled).
|
|
Order("id ASC").First(&role).Error; err != nil {
|
|
if err == gorm.ErrRecordNotFound {
|
|
return nil, errors.New(errors.CodeInvalidStatus, "缺少启用的客户角色,无法创建代理店铺")
|
|
}
|
|
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询启用客户角色失败")
|
|
}
|
|
return &role, nil
|
|
}
|