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
配置启用场景与模板控件映射;未配置时相应提交失败关闭。
439 lines
14 KiB
Go
439 lines
14 KiB
Go
package shop
|
||
|
||
import (
|
||
"context"
|
||
|
||
accessauditapp "github.com/break/junhong_cmp_fiber/internal/application/accessaudit"
|
||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||
"github.com/break/junhong_cmp_fiber/internal/store"
|
||
"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/redis/go-redis/v9"
|
||
"gorm.io/gorm"
|
||
"gorm.io/gorm/clause"
|
||
)
|
||
|
||
type Service struct {
|
||
db *gorm.DB
|
||
redisClient *redis.Client
|
||
accessAudit accessauditapp.Writer
|
||
qualificationInvalidator WithdrawalQualificationInvalidator
|
||
shopStore *postgres.ShopStore
|
||
accountStore *postgres.AccountStore
|
||
shopRoleStore *postgres.ShopRoleStore
|
||
roleStore *postgres.RoleStore
|
||
}
|
||
|
||
// SetAccessAudit 注入店铺角色授权的事务、缓存和统一审计边界。
|
||
func (s *Service) SetAccessAudit(db *gorm.DB, redisClient *redis.Client, writer accessauditapp.Writer) {
|
||
s.db = db
|
||
s.redisClient = redisClient
|
||
s.accessAudit = writer
|
||
}
|
||
|
||
func New(
|
||
shopStore *postgres.ShopStore,
|
||
accountStore *postgres.AccountStore,
|
||
shopRoleStore *postgres.ShopRoleStore,
|
||
roleStore *postgres.RoleStore,
|
||
) *Service {
|
||
return &Service{
|
||
shopStore: shopStore,
|
||
accountStore: accountStore,
|
||
shopRoleStore: shopRoleStore,
|
||
roleStore: roleStore,
|
||
}
|
||
}
|
||
|
||
// WithdrawalQualificationInvalidator 在店铺停用事务内联动失效提现资料资格。
|
||
type WithdrawalQualificationInvalidator interface {
|
||
InvalidateByShopDisable(ctx context.Context, tx *gorm.DB, shopID uint, reason string) error
|
||
}
|
||
|
||
// SetWithdrawalQualificationInvalidator 注入店铺停用联动的提现资料资格失效接缝。
|
||
// 未注入时停用不联动,用于不依赖该能力的旧装配路径。
|
||
func (s *Service) SetWithdrawalQualificationInvalidator(invalidator WithdrawalQualificationInvalidator) {
|
||
s.qualificationInvalidator = invalidator
|
||
}
|
||
|
||
func (s *Service) Update(ctx context.Context, id uint, req *dto.UpdateShopRequest) (*dto.ShopResponse, error) {
|
||
currentUserID := middleware.GetUserIDFromContext(ctx)
|
||
if currentUserID == 0 {
|
||
return nil, errors.New(errors.CodeUnauthorized, "未授权访问")
|
||
}
|
||
|
||
shop, err := s.shopStore.GetByID(ctx, id)
|
||
if err != nil {
|
||
return nil, errors.New(errors.CodeShopNotFound, "店铺不存在")
|
||
}
|
||
|
||
previousStatus := shop.Status
|
||
shop.ShopName = req.ShopName
|
||
shop.ContactName = req.ContactName
|
||
shop.ContactPhone = req.ContactPhone
|
||
shop.Province = req.Province
|
||
shop.City = req.City
|
||
shop.District = req.District
|
||
shop.Address = req.Address
|
||
shop.Status = req.Status
|
||
shop.Updater = currentUserID
|
||
|
||
if err := s.persistShopWithQualificationInvalidation(ctx, shop, previousStatus); err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
parentShopName := ""
|
||
if shop.ParentID != nil {
|
||
parentShop, err := s.shopStore.GetByID(ctx, *shop.ParentID)
|
||
if err == nil {
|
||
parentShopName = parentShop.ShopName
|
||
}
|
||
}
|
||
|
||
return &dto.ShopResponse{
|
||
ID: shop.ID,
|
||
ShopName: shop.ShopName,
|
||
ShopCode: shop.ShopCode,
|
||
DistributionCode: shop.DistributionCode,
|
||
ParentID: shop.ParentID,
|
||
ParentShopName: parentShopName,
|
||
Level: shop.Level,
|
||
ContactName: shop.ContactName,
|
||
ContactPhone: shop.ContactPhone,
|
||
Province: shop.Province,
|
||
City: shop.City,
|
||
District: shop.District,
|
||
Address: shop.Address,
|
||
Status: shop.Status,
|
||
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"),
|
||
}, nil
|
||
}
|
||
|
||
// Disable 禁用店铺
|
||
func (s *Service) Disable(ctx context.Context, id uint) error {
|
||
// 获取当前用户 ID
|
||
currentUserID := middleware.GetUserIDFromContext(ctx)
|
||
if currentUserID == 0 {
|
||
return errors.New(errors.CodeUnauthorized, "未授权访问")
|
||
}
|
||
|
||
// 查询店铺
|
||
shop, err := s.shopStore.GetByID(ctx, id)
|
||
if err != nil {
|
||
return errors.New(errors.CodeShopNotFound, "店铺不存在")
|
||
}
|
||
|
||
// 更新状态
|
||
previousStatus := shop.Status
|
||
shop.Status = constants.StatusDisabled
|
||
shop.Updater = currentUserID
|
||
|
||
return s.persistShopWithQualificationInvalidation(ctx, shop, previousStatus)
|
||
}
|
||
|
||
// persistShopWithQualificationInvalidation 保存店铺状态,并在本次停用时联动失效提现资料资格。
|
||
// 停用与失效必须同事务提交,避免店铺已停用而资格仍显示有效。
|
||
func (s *Service) persistShopWithQualificationInvalidation(
|
||
ctx context.Context,
|
||
shop *model.Shop,
|
||
previousStatus int,
|
||
) error {
|
||
disabling := previousStatus != constants.ShopStatusDisabled && shop.Status == constants.ShopStatusDisabled
|
||
if !disabling || s.qualificationInvalidator == nil || s.db == nil {
|
||
return s.shopStore.Update(ctx, shop)
|
||
}
|
||
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||
if err := postgres.NewShopStore(tx, s.redisClient).Update(ctx, shop); err != nil {
|
||
return err
|
||
}
|
||
return s.qualificationInvalidator.InvalidateByShopDisable(
|
||
ctx, tx, shop.ID, "代理店铺已停用,提现资料资格自动失效")
|
||
})
|
||
}
|
||
|
||
// Enable 启用店铺
|
||
func (s *Service) Enable(ctx context.Context, id uint) error {
|
||
// 获取当前用户 ID
|
||
currentUserID := middleware.GetUserIDFromContext(ctx)
|
||
if currentUserID == 0 {
|
||
return errors.New(errors.CodeUnauthorized, "未授权访问")
|
||
}
|
||
|
||
// 查询店铺
|
||
shop, err := s.shopStore.GetByID(ctx, id)
|
||
if err != nil {
|
||
return errors.New(errors.CodeShopNotFound, "店铺不存在")
|
||
}
|
||
|
||
// 更新状态
|
||
shop.Status = constants.StatusEnabled
|
||
shop.Updater = currentUserID
|
||
|
||
return s.shopStore.Update(ctx, shop)
|
||
}
|
||
|
||
// GetByID 获取店铺详情
|
||
func (s *Service) GetByID(ctx context.Context, id uint) (*model.Shop, error) {
|
||
shop, err := s.shopStore.GetByID(ctx, id)
|
||
if err != nil {
|
||
return nil, errors.New(errors.CodeShopNotFound, "店铺不存在")
|
||
}
|
||
return shop, nil
|
||
}
|
||
|
||
func (s *Service) ListShopResponses(ctx context.Context, req *dto.ShopListRequest) ([]*dto.ShopResponse, int64, error) {
|
||
opts := &store.QueryOptions{
|
||
Page: req.Page,
|
||
PageSize: req.PageSize,
|
||
OrderBy: "created_at DESC",
|
||
}
|
||
if opts.Page == 0 {
|
||
opts.Page = 1
|
||
}
|
||
if opts.PageSize == 0 {
|
||
opts.PageSize = constants.DefaultPageSize
|
||
}
|
||
|
||
filters := make(map[string]interface{})
|
||
if req.ShopName != "" {
|
||
filters["shop_name"] = req.ShopName
|
||
}
|
||
if req.ShopCode != "" {
|
||
filters["shop_code"] = req.ShopCode
|
||
}
|
||
if req.ContactPhone != "" {
|
||
filters["contact_phone"] = req.ContactPhone
|
||
}
|
||
if req.ParentID != nil {
|
||
filters["parent_id"] = *req.ParentID
|
||
}
|
||
if req.Level != nil {
|
||
filters["level"] = *req.Level
|
||
}
|
||
if req.Status != nil {
|
||
filters["status"] = *req.Status
|
||
}
|
||
|
||
shops, total, err := s.shopStore.List(ctx, opts, filters)
|
||
if err != nil {
|
||
return nil, 0, errors.Wrap(errors.CodeInternalError, err, "查询店铺列表失败")
|
||
}
|
||
|
||
parentShopNameMap, err := s.buildParentShopNameMap(ctx, shops)
|
||
if err != nil {
|
||
return nil, 0, errors.Wrap(errors.CodeInternalError, err, "查询上级店铺名称失败")
|
||
}
|
||
|
||
responses := make([]*dto.ShopResponse, 0, len(shops))
|
||
for _, shop := range shops {
|
||
parentShopName := ""
|
||
if shop.ParentID != nil {
|
||
parentShopName = parentShopNameMap[*shop.ParentID]
|
||
}
|
||
|
||
responses = append(responses, &dto.ShopResponse{
|
||
ID: shop.ID,
|
||
ShopName: shop.ShopName,
|
||
ShopCode: shop.ShopCode,
|
||
DistributionCode: shop.DistributionCode,
|
||
ParentID: shop.ParentID,
|
||
ParentShopName: parentShopName,
|
||
Level: shop.Level,
|
||
ContactName: shop.ContactName,
|
||
ContactPhone: shop.ContactPhone,
|
||
Province: shop.Province,
|
||
City: shop.City,
|
||
District: shop.District,
|
||
Address: shop.Address,
|
||
Status: shop.Status,
|
||
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"),
|
||
})
|
||
}
|
||
|
||
return responses, total, nil
|
||
}
|
||
|
||
// buildParentShopNameMap 批量查询店铺上级名称,避免列表接口出现 N+1 查询。
|
||
func (s *Service) buildParentShopNameMap(ctx context.Context, shops []*model.Shop) (map[uint]string, error) {
|
||
parentIDs := make([]uint, 0, len(shops))
|
||
parentIDSet := make(map[uint]struct{}, len(shops))
|
||
for _, shop := range shops {
|
||
if shop.ParentID == nil {
|
||
continue
|
||
}
|
||
if _, exists := parentIDSet[*shop.ParentID]; exists {
|
||
continue
|
||
}
|
||
parentIDSet[*shop.ParentID] = struct{}{}
|
||
parentIDs = append(parentIDs, *shop.ParentID)
|
||
}
|
||
|
||
if len(parentIDs) == 0 {
|
||
return map[uint]string{}, nil
|
||
}
|
||
|
||
parentShops, err := s.shopStore.GetByIDs(ctx, parentIDs)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
parentShopNameMap := make(map[uint]string, len(parentShops))
|
||
for _, parentShop := range parentShops {
|
||
parentShopNameMap[parentShop.ID] = parentShop.ShopName
|
||
}
|
||
return parentShopNameMap, nil
|
||
}
|
||
|
||
func (s *Service) List(ctx context.Context, opts *store.QueryOptions, filters map[string]interface{}) ([]*model.Shop, int64, error) {
|
||
return s.shopStore.List(ctx, opts, filters)
|
||
}
|
||
|
||
// ListCascade 联级查询店铺,用于新增店铺或其他场景选择上级店铺
|
||
func (s *Service) ListCascade(ctx context.Context, req *dto.ShopCascadeRequest) ([]*dto.ShopCascadeItem, error) {
|
||
shops, err := s.shopStore.ListForCascade(ctx, req.ShopName, req.ParentID, req.ExcludeSelf)
|
||
if err != nil {
|
||
return nil, errors.Wrap(errors.CodeInternalError, err, "查询店铺失败")
|
||
}
|
||
|
||
if len(shops) == 0 {
|
||
return []*dto.ShopCascadeItem{}, nil
|
||
}
|
||
|
||
ids := make([]uint, 0, len(shops))
|
||
for _, shop := range shops {
|
||
ids = append(ids, shop.ID)
|
||
}
|
||
|
||
childParentIDs, err := s.shopStore.GetParentIDsWithChildren(ctx, ids)
|
||
if err != nil {
|
||
return nil, errors.Wrap(errors.CodeInternalError, err, "查询下级店铺失败")
|
||
}
|
||
|
||
hasChildrenSet := make(map[uint]bool, len(childParentIDs))
|
||
for _, pid := range childParentIDs {
|
||
hasChildrenSet[pid] = true
|
||
}
|
||
|
||
result := make([]*dto.ShopCascadeItem, 0, len(shops))
|
||
for _, shop := range shops {
|
||
result = append(result, &dto.ShopCascadeItem{
|
||
ID: shop.ID,
|
||
ShopName: shop.ShopName,
|
||
HasChildren: hasChildrenSet[shop.ID],
|
||
})
|
||
}
|
||
|
||
return result, nil
|
||
}
|
||
|
||
func (s *Service) Delete(ctx context.Context, id uint) error {
|
||
currentUserID := middleware.GetUserIDFromContext(ctx)
|
||
if currentUserID == 0 {
|
||
return errors.New(errors.CodeUnauthorized, "未授权访问")
|
||
}
|
||
|
||
if s.db == nil || s.accessAudit == nil {
|
||
return errors.New(errors.CodeInvalidStatus, "店铺删除审计接缝未配置")
|
||
}
|
||
var shop *model.Shop
|
||
var parent *model.Shop
|
||
var accounts []*model.Account
|
||
var accountIDs []uint
|
||
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||
var locked model.Shop
|
||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&locked, id).Error; err != nil {
|
||
if err == gorm.ErrRecordNotFound {
|
||
return errors.New(errors.CodeShopNotFound, "店铺不存在")
|
||
}
|
||
return errors.Wrap(errors.CodeDatabaseError, err, "获取店铺失败")
|
||
}
|
||
shop = &locked
|
||
parent = loadDeletedShopParent(tx, locked.ParentID)
|
||
if err := tx.Where("shop_id = ?", locked.ID).Find(&accounts).Error; err != nil {
|
||
return errors.Wrap(errors.CodeDatabaseError, err, "查询店铺账号失败")
|
||
}
|
||
accountChanges := make([]accessauditapp.AccountChange, 0, len(accounts))
|
||
accountIDs = make([]uint, 0, len(accounts))
|
||
for _, account := range accounts {
|
||
accountIDs = append(accountIDs, account.ID)
|
||
accountChanges = append(accountChanges, accessauditapp.AccountChange{
|
||
Account: account, BeforeData: map[string]any{"status": account.Status}, AfterData: map[string]any{"status": constants.StatusDisabled},
|
||
})
|
||
}
|
||
if len(accountIDs) > 0 {
|
||
if err := postgres.NewAccountStore(tx, nil).BulkUpdateStatus(ctx, accountIDs, constants.StatusDisabled, currentUserID); err != nil {
|
||
return errors.Wrap(errors.CodeDatabaseError, err, "禁用店铺账号失败")
|
||
}
|
||
}
|
||
// 店铺删除与停用同等失效该店铺全部有效提现资料资格。
|
||
// 必须在软删除之前执行:失效路径按 deleted_at IS NULL 读取店铺以写审计,
|
||
// 删除后再调用会因店铺不可见而报 NotFound,导致含有效资格的店铺永远删不掉。
|
||
if s.qualificationInvalidator != nil {
|
||
if err := s.qualificationInvalidator.InvalidateByShopDisable(
|
||
ctx, tx, locked.ID, "代理店铺已删除,提现资料资格自动失效"); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
if err := tx.Delete(&model.Shop{}, id).Error; err != nil {
|
||
return errors.Wrap(errors.CodeDatabaseError, err, "删除店铺失败")
|
||
}
|
||
if err := s.accessAudit.WriteAccessChange(ctx, tx, accessauditapp.ChangeAudit{
|
||
ActionCode: constants.AuditActionShopDeleted, Summary: "删除店铺", OperatorID: currentUserID,
|
||
Shop: shop, ParentShop: parent, Accounts: accountChanges,
|
||
BeforeData: map[string]any{"deleted": false}, AfterData: map[string]any{"deleted": true},
|
||
SubjectVisibility: constants.AuditSubjectResult, SubjectSummary: "店铺已删除",
|
||
}); err != nil {
|
||
return errors.Wrap(errors.CodeInternalError, err, "写入店铺删除审计失败")
|
||
}
|
||
return nil
|
||
})
|
||
if err != nil {
|
||
if shop != nil {
|
||
accessauditapp.RecordFailure(ctx, s.db, s.accessAudit, accessauditapp.ChangeAudit{
|
||
ActionCode: constants.AuditActionShopDeleted, Summary: "删除店铺失败", Result: shopRoleFailureResult(err),
|
||
OperatorID: currentUserID, Shop: shop, ParentShop: parent, SubjectVisibility: constants.AuditSubjectInternalOnly,
|
||
}, err)
|
||
}
|
||
return err
|
||
}
|
||
s.clearDeletedShopCaches(ctx, shop.ID, shop.ParentID, accountIDs)
|
||
return nil
|
||
}
|
||
|
||
func (s *Service) clearDeletedShopCaches(ctx context.Context, shopID uint, parentID *uint, accountIDs []uint) {
|
||
if s.redisClient == nil {
|
||
return
|
||
}
|
||
keys := []string{constants.RedisShopSubordinatesKey(shopID)}
|
||
if parentID != nil {
|
||
keys = append(keys, constants.RedisShopSubordinatesKey(*parentID))
|
||
}
|
||
for _, accountID := range accountIDs {
|
||
keys = append(keys, constants.RedisUserPermissionsKey(accountID))
|
||
}
|
||
_ = s.redisClient.Del(ctx, keys...).Err()
|
||
}
|
||
|
||
func loadDeletedShopParent(tx *gorm.DB, parentID *uint) *model.Shop {
|
||
if parentID == nil {
|
||
return nil
|
||
}
|
||
var parent model.Shop
|
||
if err := tx.Unscoped().First(&parent, *parentID).Error; err != nil {
|
||
return nil
|
||
}
|
||
return &parent
|
||
}
|
||
|
||
// GetSubordinateShopIDs 获取下级店铺 ID 列表(包含自己)
|
||
func (s *Service) GetSubordinateShopIDs(ctx context.Context, shopID uint) ([]uint, error) {
|
||
return s.shopStore.GetSubordinateShopIDs(ctx, shopID)
|
||
}
|