fix: 角色删除前校验分配情况,禁止删除使用中的角色

角色被删除后,其关联的账号-角色记录未清理,导致 CountByAccountID
统计到孤儿记录,使被分配该角色的账号无法重新分配新角色。

修复方案:删除角色前检查 tb_account_role 和 tb_shop_role,
若仍有账号或店铺持有该角色则返回 1028 错误,强制管理员显式
解除所有分配后再删除,保证数据一致性与审计完整性。
This commit is contained in:
2026-04-07 17:23:49 +08:00
parent 434a8b0349
commit 7e489a19fb
5 changed files with 50 additions and 6 deletions

View File

@@ -121,3 +121,15 @@ func (s *AccountRoleStore) CountByAccountID(ctx context.Context, accountID uint)
}
return count, nil
}
// CountByRoleID 统计持有指定角色的账号数量
func (s *AccountRoleStore) CountByRoleID(ctx context.Context, roleID uint) (int64, error) {
var count int64
if err := s.db.WithContext(ctx).
Model(&model.AccountRole{}).
Where("role_id = ?", roleID).
Count(&count).Error; err != nil {
return 0, err
}
return count, nil
}

View File

@@ -61,6 +61,18 @@ func (s *ShopRoleStore) DeleteByShopID(ctx context.Context, shopID uint) error {
return nil
}
// CountByRoleID 统计持有指定角色的店铺数量
func (s *ShopRoleStore) CountByRoleID(ctx context.Context, roleID uint) (int64, error) {
var count int64
if err := s.db.WithContext(ctx).
Model(&model.ShopRole{}).
Where("role_id = ?", roleID).
Count(&count).Error; err != nil {
return 0, err
}
return count, nil
}
func (s *ShopRoleStore) GetByShopID(ctx context.Context, shopID uint) ([]*model.ShopRole, error) {
var srs []*model.ShopRole
query := s.db.WithContext(ctx).Where("shop_id = ?", shopID)