diff --git a/internal/service/role/service.go b/internal/service/role/service.go index 867aa03..2ba991c 100644 --- a/internal/service/role/service.go +++ b/internal/service/role/service.go @@ -313,6 +313,7 @@ func (s *Service) BatchRemovePermissions(ctx context.Context, roleID uint, permI } // UpdateStatus 更新角色状态 +// 禁用角色时,若角色已分配给账号或店铺,则拒绝操作 func (s *Service) UpdateStatus(ctx context.Context, id uint, status int) error { currentUserID := middleware.GetUserIDFromContext(ctx) if currentUserID == 0 { @@ -327,6 +328,23 @@ func (s *Service) UpdateStatus(ctx context.Context, id uint, status int) error { return errors.Wrap(errors.CodeInternalError, err, "获取角色失败") } + // 禁用角色时检查是否已有分配 + if status == constants.StatusDisabled { + accountCount, err := s.accountRoleStore.CountByRoleID(ctx, id) + if err != nil { + return errors.Wrap(errors.CodeInternalError, err, "检查角色分配情况失败") + } + + shopCount, err := s.shopRoleStore.CountByRoleID(ctx, id) + if err != nil { + return errors.Wrap(errors.CodeInternalError, err, "检查角色分配情况失败") + } + + if accountCount > 0 || shopCount > 0 { + return errors.New(errors.CodeRoleInUse, fmt.Sprintf("该角色已分配给 %d 个账号、%d 个店铺,请先移除相关分配后再禁用", accountCount, shopCount)) + } + } + role.Status = status role.Updater = currentUserID