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
配置启用场景与模板控件映射;未配置时相应提交失败关闭。
329 lines
13 KiB
Go
329 lines
13 KiB
Go
// Package shop 提供店铺创建与业务员归属的简单写事务脚本。
|
|
package shop
|
|
|
|
import (
|
|
"context"
|
|
stderrors "errors"
|
|
"strings"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
"gorm.io/gorm"
|
|
|
|
accessauditapp "github.com/break/junhong_cmp_fiber/internal/application/accessaudit"
|
|
distributiondomain "github.com/break/junhong_cmp_fiber/internal/domain/distribution"
|
|
"github.com/break/junhong_cmp_fiber/internal/model"
|
|
"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"
|
|
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
|
)
|
|
|
|
// CreateService 收口平台与代理创建店铺的完整事务。
|
|
type CreateService struct {
|
|
db *gorm.DB
|
|
audit accessauditapp.Writer
|
|
}
|
|
|
|
// NewCreateService 创建店铺创建事务脚本。
|
|
func NewCreateService(db *gorm.DB, audit accessauditapp.Writer) *CreateService {
|
|
return &CreateService{db: db, audit: audit}
|
|
}
|
|
|
|
// Create 按操作者类型执行平台显式归属或代理安全继承。
|
|
func (s *CreateService) Create(ctx context.Context, request *dto.CreateShopRequest) (*dto.ShopResponse, error) {
|
|
userType := middleware.GetUserTypeFromContext(ctx)
|
|
operatorID := middleware.GetUserIDFromContext(ctx)
|
|
if operatorID == 0 {
|
|
return nil, errors.New(errors.CodeUnauthorized)
|
|
}
|
|
resolver := resolvePlatformBusinessOwner
|
|
switch userType {
|
|
case constants.UserTypeSuperAdmin, constants.UserTypePlatform:
|
|
case constants.UserTypeAgent:
|
|
if request.BusinessOwnerAccountIDSet {
|
|
return s.fail(ctx, request, errors.New(errors.CodeForbidden, "无权限设置店铺业务员"))
|
|
}
|
|
if request.ParentID == nil {
|
|
return s.fail(ctx, request, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在"))
|
|
}
|
|
if err := middleware.CanManageShop(ctx, *request.ParentID); err != nil {
|
|
return s.fail(ctx, request, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在"))
|
|
}
|
|
resolver = resolveInheritedBusinessOwner
|
|
default:
|
|
return s.fail(ctx, request, errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在"))
|
|
}
|
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(request.InitPassword), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return s.fail(ctx, request, errors.Wrap(errors.CodeInternalError, err, "密码哈希失败"))
|
|
}
|
|
|
|
var response *dto.ShopResponse
|
|
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
created, createErr := createShop(ctx, tx, request, operatorID, string(hashedPassword), resolver, s.audit)
|
|
if createErr != nil {
|
|
return createErr
|
|
}
|
|
response = created
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return s.fail(ctx, request, err)
|
|
}
|
|
return response, nil
|
|
}
|
|
|
|
type businessOwnerResolver func(*gorm.DB, *dto.CreateShopRequest, *model.Shop) (*uint, error)
|
|
|
|
func createShop(ctx context.Context, tx *gorm.DB, request *dto.CreateShopRequest, operatorID uint, hashedPassword string, resolveOwner businessOwnerResolver, audit accessauditapp.Writer) (*dto.ShopResponse, error) {
|
|
if exists, err := recordExists(tx, &model.Shop{}, "shop_code = ?", request.ShopCode); err != nil {
|
|
return nil, errors.Wrap(errors.CodeDatabaseError, err, "校验店铺编号失败")
|
|
} else if exists {
|
|
return nil, errors.New(errors.CodeShopCodeExists, "店铺编号已存在")
|
|
}
|
|
if exists, err := recordExists(tx, &model.Account{}, "username = ?", request.InitUsername); err != nil {
|
|
return nil, errors.Wrap(errors.CodeDatabaseError, err, "校验初始账号用户名失败")
|
|
} else if exists {
|
|
return nil, errors.New(errors.CodeUsernameExists, "初始账号用户名已存在")
|
|
}
|
|
if exists, err := recordExists(tx, &model.Account{}, "phone = ?", request.InitPhone); err != nil {
|
|
return nil, errors.Wrap(errors.CodeDatabaseError, err, "校验初始账号手机号失败")
|
|
} else if exists {
|
|
return nil, errors.New(errors.CodePhoneExists, "初始账号手机号已存在")
|
|
}
|
|
|
|
parent, level, err := resolveParent(tx, request.ParentID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
ownerID, err := resolveOwner(tx, request, parent)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var role model.Role
|
|
if err := tx.Where("id = ? AND role_type = ? AND status = ?", request.DefaultRoleID, constants.RoleTypeCustomer, constants.StatusEnabled).First(&role).Error; err != nil {
|
|
return nil, errors.New(errors.CodeInvalidParam, "请选择启用的客户角色")
|
|
}
|
|
|
|
shop := &model.Shop{
|
|
ShopName: request.ShopName, ShopCode: request.ShopCode, ParentID: request.ParentID,
|
|
BusinessOwnerAccountID: ownerID, Level: level, ContactName: request.ContactName,
|
|
ContactPhone: request.ContactPhone, Province: request.Province, City: request.City,
|
|
District: request.District, Address: request.Address, Status: constants.ShopStatusEnabled,
|
|
}
|
|
shop.Creator = operatorID
|
|
shop.Updater = operatorID
|
|
// 分销码在创建时随机生成且唯一;冲突时重新生成并重试,不提供人工指定或编辑入口。
|
|
if err := CreateShopWithDistributionCode(ctx, tx, shop); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
account := &model.Account{
|
|
Username: request.InitUsername, Phone: request.InitPhone, Password: hashedPassword,
|
|
UserType: constants.UserTypeAgent, ShopID: &shop.ID, Status: constants.StatusEnabled, IsPrimary: true,
|
|
}
|
|
account.Creator = operatorID
|
|
account.Updater = operatorID
|
|
if err := tx.Create(account).Error; err != nil {
|
|
return nil, errors.Wrap(errors.CodeDatabaseError, err, "创建初始账号失败")
|
|
}
|
|
if err := tx.Create(&model.AccountRole{
|
|
AccountID: account.ID, RoleID: request.DefaultRoleID, Status: constants.StatusEnabled,
|
|
Creator: operatorID, Updater: operatorID,
|
|
}).Error; err != nil {
|
|
return nil, errors.Wrap(errors.CodeDatabaseError, err, "为初始账号分配角色失败")
|
|
}
|
|
if err := tx.Create(&model.ShopRole{
|
|
ShopID: shop.ID, RoleID: request.DefaultRoleID, Status: constants.StatusEnabled,
|
|
Creator: operatorID, Updater: operatorID,
|
|
}).Error; err != nil {
|
|
return nil, errors.Wrap(errors.CodeDatabaseError, err, "设置店铺默认角色失败")
|
|
}
|
|
if err := tx.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 nil, errors.Wrap(errors.CodeDatabaseError, err, "初始化店铺钱包失败")
|
|
}
|
|
|
|
parentName := ""
|
|
if parent != nil {
|
|
parentName = parent.ShopName
|
|
}
|
|
response := newShopResponse(shop, parentName)
|
|
if err := fillBusinessOwnerResponse(tx, shop, response); err != nil {
|
|
return nil, err
|
|
}
|
|
if audit == nil {
|
|
return nil, errors.New(errors.CodeInvalidStatus, "店铺创建审计接缝未配置")
|
|
}
|
|
if err := audit.WriteAccessChange(ctx, tx, accessauditapp.ChangeAudit{
|
|
ActionCode: constants.AuditActionShopCreated, Summary: "创建店铺",
|
|
OperatorID: operatorID, Shop: shop, ParentShop: parent,
|
|
AfterData: shopCreationData(shop),
|
|
}); err != nil {
|
|
return nil, errors.Wrap(errors.CodeInternalError, err, "写入店铺创建审计失败")
|
|
}
|
|
if ownerID != nil {
|
|
if err := audit.WriteAccessChange(ctx, tx, accessauditapp.ChangeAudit{
|
|
ActionCode: constants.AuditActionShopBusinessOwnerUpdated, Summary: "设置店铺业务员归属",
|
|
OperatorID: operatorID, Shop: shop, ParentShop: parent,
|
|
Accounts: businessOwnerAuditAccounts(tx, nil, ownerID),
|
|
AfterData: map[string]any{"business_owner_account_id": ownerID},
|
|
SubjectVisibility: constants.AuditSubjectResult, SubjectSummary: "店铺业务员归属已设置",
|
|
}); err != nil {
|
|
return nil, errors.Wrap(errors.CodeInternalError, err, "写入店铺业务员审计失败")
|
|
}
|
|
}
|
|
return response, nil
|
|
}
|
|
|
|
func (s *CreateService) fail(ctx context.Context, request *dto.CreateShopRequest, originalErr error) (*dto.ShopResponse, error) {
|
|
shop := &model.Shop{ShopName: request.ShopName, ShopCode: request.ShopCode, ParentID: request.ParentID}
|
|
var parent *model.Shop
|
|
if request.ParentID != nil {
|
|
parent = &model.Shop{}
|
|
parent.ID = *request.ParentID
|
|
}
|
|
accessauditapp.RecordFailure(ctx, s.db, s.audit, accessauditapp.ChangeAudit{
|
|
ActionCode: constants.AuditActionShopCreated, Summary: "创建店铺失败", Result: shopAuditFailureResult(originalErr),
|
|
OperatorID: middleware.GetUserIDFromContext(ctx), Shop: shop, ParentShop: parent,
|
|
}, originalErr)
|
|
return nil, originalErr
|
|
}
|
|
|
|
func shopCreationData(shop *model.Shop) map[string]any {
|
|
data := shopProfileData(shop)
|
|
data["shop_code"] = shop.ShopCode
|
|
// 分销码是本 Change 新增的建店事实,按脱敏值记录,口径与审批建店路径一致。
|
|
data["distribution_code_masked"] = distributiondomain.MaskDistributionCode(shop.DistributionCode)
|
|
data["parent_id"] = shop.ParentID
|
|
data["level"] = shop.Level
|
|
return data
|
|
}
|
|
|
|
func shopProfileData(shop *model.Shop) map[string]any {
|
|
return map[string]any{
|
|
"shop_name": shop.ShopName, "contact_name": shop.ContactName, "contact_phone": shop.ContactPhone,
|
|
"province": shop.Province, "city": shop.City, "district": shop.District, "address": shop.Address,
|
|
}
|
|
}
|
|
|
|
func shopProfileChanged(before, after *model.Shop) bool {
|
|
return before.ShopName != after.ShopName || before.ContactName != after.ContactName ||
|
|
before.ContactPhone != after.ContactPhone || before.Province != after.Province || before.City != after.City ||
|
|
before.District != after.District || before.Address != after.Address
|
|
}
|
|
|
|
func shopAuditFailureResult(err error) string {
|
|
var appErr *errors.AppError
|
|
if stderrors.As(err, &appErr) {
|
|
switch appErr.Code {
|
|
case errors.CodeForbidden, errors.CodeInvalidParam, errors.CodeNotFound, errors.CodeInvalidParentID,
|
|
errors.CodeShopLevelExceeded, errors.CodeShopCodeExists, errors.CodeUsernameExists, errors.CodePhoneExists:
|
|
return constants.AuditResultDenied
|
|
}
|
|
}
|
|
return constants.AuditResultFailed
|
|
}
|
|
|
|
func resolveParent(tx *gorm.DB, parentID *uint) (*model.Shop, int, error) {
|
|
if parentID == nil {
|
|
return nil, 1, nil
|
|
}
|
|
var parent model.Shop
|
|
if err := tx.First(&parent, *parentID).Error; err != nil {
|
|
return nil, 0, errors.New(errors.CodeInvalidParentID, "上级店铺不存在或无效")
|
|
}
|
|
level := parent.Level + 1
|
|
if level > constants.ShopMaxLevel {
|
|
return nil, 0, errors.New(errors.CodeShopLevelExceeded, "店铺层级不能超过 7 级")
|
|
}
|
|
return &parent, level, nil
|
|
}
|
|
|
|
func resolvePlatformBusinessOwner(tx *gorm.DB, request *dto.CreateShopRequest, parent *model.Shop) (*uint, error) {
|
|
if !request.BusinessOwnerAccountIDSet {
|
|
if parent == nil || parent.BusinessOwnerAccountID == nil {
|
|
return nil, nil
|
|
}
|
|
ownerID := *parent.BusinessOwnerAccountID
|
|
return &ownerID, nil
|
|
}
|
|
if request.BusinessOwnerAccountID == nil {
|
|
return nil, nil
|
|
}
|
|
if *request.BusinessOwnerAccountID == 0 {
|
|
return nil, errors.New(errors.CodeInvalidParam, "业务员账号无效")
|
|
}
|
|
var account model.Account
|
|
if err := tx.Where("id = ? AND user_type = ? AND status = ?", *request.BusinessOwnerAccountID, constants.UserTypePlatform, constants.StatusEnabled).
|
|
First(&account).Error; err != nil {
|
|
return nil, errors.New(errors.CodeInvalidParam, "业务员账号无效或不可用")
|
|
}
|
|
ownerID := account.ID
|
|
return &ownerID, nil
|
|
}
|
|
|
|
func resolveInheritedBusinessOwner(_ *gorm.DB, _ *dto.CreateShopRequest, parent *model.Shop) (*uint, error) {
|
|
if parent == nil || parent.BusinessOwnerAccountID == nil {
|
|
return nil, nil
|
|
}
|
|
ownerID := *parent.BusinessOwnerAccountID
|
|
return &ownerID, nil
|
|
}
|
|
|
|
func recordExists(tx *gorm.DB, target any, query string, value any) (bool, error) {
|
|
var count int64
|
|
err := tx.Model(target).Where(query, value).Count(&count).Error
|
|
return count > 0, err
|
|
}
|
|
|
|
func newShopResponse(shop *model.Shop, parentName string) *dto.ShopResponse {
|
|
return &dto.ShopResponse{
|
|
ID: shop.ID, ShopName: shop.ShopName, ShopCode: shop.ShopCode,
|
|
DistributionCode: shop.DistributionCode, ParentID: shop.ParentID,
|
|
BusinessOwnerAccountID: shop.BusinessOwnerAccountID,
|
|
ParentShopName: parentName, Level: shop.Level, ContactName: shop.ContactName,
|
|
ContactPhone: shop.ContactPhone, Province: shop.Province, City: shop.City,
|
|
District: shop.District, Address: shop.Address, Status: shop.Status,
|
|
ClientLoginDisabled: shop.ClientLoginDisabled,
|
|
StatusName: constants.GetStatusName(shop.Status), CreatedAt: shop.CreatedAt.Format("2006-01-02 15:04:05"),
|
|
UpdatedAt: shop.UpdatedAt.Format("2006-01-02 15:04:05"),
|
|
}
|
|
}
|
|
|
|
func fillBusinessOwnerResponse(tx *gorm.DB, shop *model.Shop, response *dto.ShopResponse) error {
|
|
if shop.BusinessOwnerAccountID == nil {
|
|
return nil
|
|
}
|
|
var account model.Account
|
|
err := tx.Unscoped().Where("id = ?", *shop.BusinessOwnerAccountID).First(&account).Error
|
|
if err == gorm.ErrRecordNotFound {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return errors.Wrap(errors.CodeDatabaseError, err, "查询业务员摘要失败")
|
|
}
|
|
response.BusinessOwnerUsername = account.Username
|
|
response.BusinessOwnerPhoneSummary = maskBusinessOwnerPhone(account.Phone)
|
|
response.BusinessOwnerAvailable = account.UserType == constants.UserTypePlatform && account.Status == constants.StatusEnabled && !account.DeletedAt.Valid
|
|
return nil
|
|
}
|
|
|
|
func maskBusinessOwnerPhone(phone string) string {
|
|
phone = strings.TrimSpace(phone)
|
|
if len(phone) < 7 {
|
|
return ""
|
|
}
|
|
return phone[:3] + "****" + phone[len(phone)-4:]
|
|
}
|