SysRoleServiceImpl.java 10.4 KB
package com.youjia.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.spring.service.impl.ServiceImpl;
import com.youjia.common.constant.CommonConstants;
import com.youjia.common.core.PageResult;
import com.youjia.common.core.ResultCode;
import com.youjia.common.enums.DataScopeEnum;
import com.youjia.common.exception.BusinessException;
import com.youjia.system.dto.RoleMenuAssignDTO;
import com.youjia.system.dto.SysRoleCreateDTO;
import com.youjia.system.dto.SysRoleQueryDTO;
import com.youjia.system.dto.SysRoleUpdateDTO;
import com.youjia.system.entity.SysMenu;
import com.youjia.system.entity.SysRole;
import com.youjia.system.entity.SysRoleMenu;
import com.youjia.system.entity.SysUserRole;
import com.youjia.system.mapper.SysMenuMapper;
import com.youjia.system.mapper.SysRoleMapper;
import com.youjia.system.mapper.SysRoleMenuMapper;
import com.youjia.system.mapper.SysUserRoleMapper;
import com.youjia.system.service.SysRoleService;
import com.youjia.system.vo.SysRoleDetailVO;
import com.youjia.system.vo.SysRoleVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色管理服务实现。
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    private final SysRoleMenuMapper sysRoleMenuMapper;
    private final SysUserRoleMapper sysUserRoleMapper;
    private final SysMenuMapper sysMenuMapper;

    @Override
    public PageResult<SysRoleVO> pageRole(SysRoleQueryDTO query) {
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<SysRole>()
                .eq(query.getIsBuiltin() != null, SysRole::getIsBuiltin, query.getIsBuiltin())
                .eq(query.getStatus() != null, SysRole::getStatus, query.getStatus())
                .eq(query.getDefaultDataScope() != null, SysRole::getDefaultDataScope, query.getDefaultDataScope())
                .and(StringUtils.hasText(query.getKeyword()), w -> w
                        .like(SysRole::getRoleName, query.getKeyword())
                        .or().like(SysRole::getRoleCode, query.getKeyword()))
                .orderByAsc(SysRole::getSort)
                .orderByAsc(SysRole::getRoleId);

        Page<SysRole> page = this.page(new Page<>(query.getCurrent(), query.getSize()), wrapper);
        List<SysRoleVO> records = page.getRecords().stream().map(this::toVO).collect(Collectors.toList());
        return PageResult.of(records, page.getTotal(), page.getCurrent(), page.getSize());
    }

    @Override
    public SysRoleDetailVO getRoleDetail(Long roleId) {
        SysRole role = getById(roleId);
        if (role == null) {
            throw new BusinessException(ResultCode.DATA_NOT_FOUND, "角色不存在");
        }
        SysRoleDetailVO vo = new SysRoleDetailVO();
        vo.setRoleId(role.getRoleId());
        vo.setRoleCode(role.getRoleCode());
        vo.setRoleName(role.getRoleName());
        vo.setDescription(role.getDescription());
        vo.setIsBuiltin(role.getIsBuiltin());
        vo.setDefaultDataScope(role.getDefaultDataScope());
        vo.setDefaultDataScopeLabel(DataScopeEnum.of(role.getDefaultDataScope())
                .map(DataScopeEnum::getLabel).orElse(null));
        vo.setSort(role.getSort());
        vo.setStatus(role.getStatus());
        vo.setUserCount(sysUserRoleMapper.selectCount(
                new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getRoleId, roleId)));
        // 超级管理员角色权限矩阵只读,其余角色可编辑
        vo.setPermEditable(!CommonConstants.ROLE_SYS_ADMIN.equals(role.getRoleCode()));
        vo.setMenuIds(listMenuIds(roleId));
        return vo;
    }

    @Override
    public List<SysRoleVO> listRoleOptions() {
        return this.list(new LambdaQueryWrapper<SysRole>()
                        .eq(SysRole::getStatus, CommonConstants.YES)
                        .orderByAsc(SysRole::getSort)
                        .orderByAsc(SysRole::getRoleId))
                .stream().map(this::toVO).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createRole(SysRoleCreateDTO dto) {
        long exists = this.count(new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleCode, dto.getRoleCode()));
        if (exists > 0) {
            throw new BusinessException(ResultCode.ROLE_CODE_EXISTS);
        }
        SysRole role = new SysRole();
        role.setRoleCode(dto.getRoleCode());
        role.setRoleName(dto.getRoleName());
        role.setDescription(dto.getDescription());
        role.setDefaultDataScope(dto.getDefaultDataScope());
        role.setLeaderUserId(dto.getLeaderUserId());
        role.setSort(dto.getSort());
        role.setStatus(dto.getStatus());
        role.setIsBuiltin(CommonConstants.NO);
        this.save(role);
        // 新建角色未配置任何权限时仅能登录、看不到任何菜单,需在详情抽屉中继续配置
        return role.getRoleId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRole(SysRoleUpdateDTO dto) {
        SysRole existed = getById(dto.getRoleId());
        if (existed == null) {
            throw new BusinessException(ResultCode.DATA_NOT_FOUND, "角色不存在");
        }
        SysRole role = new SysRole();
        role.setRoleId(dto.getRoleId());
        role.setRoleName(dto.getRoleName());
        role.setDescription(dto.getDescription());
        role.setDefaultDataScope(dto.getDefaultDataScope());
        role.setLeaderUserId(dto.getLeaderUserId());
        role.setSort(dto.getSort());
        role.setStatus(dto.getStatus());
        // 角色编码创建后不可修改,此处显式忽略
        this.updateById(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRole(Long roleId) {
        SysRole role = getById(roleId);
        if (role == null) {
            throw new BusinessException(ResultCode.DATA_NOT_FOUND, "角色不存在");
        }
        if (CommonConstants.YES == role.getIsBuiltin()) {
            throw new BusinessException(ResultCode.ROLE_BUILTIN_PROTECTED);
        }
        long userCount = sysUserRoleMapper.selectCount(
                new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getRoleId, roleId));
        if (userCount > 0) {
            throw new BusinessException(ResultCode.OPERATION_NOT_ALLOWED,
                    "该角色下仍存在 " + userCount + " 个账号,请先解除分配");
        }
        this.removeById(roleId);
        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, roleId));
    }

    @Override
    public List<Long> listMenuIds(Long roleId) {
        return sysRoleMenuMapper.selectList(new LambdaQueryWrapper<SysRoleMenu>()
                        .eq(SysRoleMenu::getRoleId, roleId))
                .stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignMenus(RoleMenuAssignDTO dto) {
        SysRole role = getById(dto.getRoleId());
        if (role == null) {
            throw new BusinessException(ResultCode.DATA_NOT_FOUND, "角色不存在");
        }
        if (CommonConstants.ROLE_SYS_ADMIN.equals(role.getRoleCode())) {
            throw new BusinessException(ResultCode.ROLE_BUILTIN_PROTECTED, "超级管理员角色的权限不可编辑");
        }
        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, dto.getRoleId()));
        List<Long> menuIds = dto.getMenuIds();
        if (CollectionUtils.isEmpty(menuIds)) {
            return;
        }
        for (Long menuId : menuIds.stream().distinct().toList()) {
            SysRoleMenu relation = new SysRoleMenu();
            relation.setRoleId(dto.getRoleId());
            relation.setMenuId(menuId);
            sysRoleMenuMapper.insert(relation);
        }
        // TODO 权限变更后失效该角色下所有在线用户的权限缓存,用户下次请求即按新权限校验
    }

    @Override
    public List<String> listPermCodesByUserId(Long userId) {
        List<Long> roleIds = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>()
                        .eq(SysUserRole::getUserId, userId))
                .stream().map(SysUserRole::getRoleId).toList();
        if (roleIds.isEmpty()) {
            return Collections.emptyList();
        }
        boolean isSysAdmin = this.listByIds(roleIds).stream()
                .anyMatch(r -> CommonConstants.ROLE_SYS_ADMIN.equals(r.getRoleCode()));
        if (isSysAdmin) {
            return sysMenuMapper.selectList(new LambdaQueryWrapper<SysMenu>()
                            .isNotNull(SysMenu::getPermCode))
                    .stream().map(SysMenu::getPermCode).distinct().collect(Collectors.toList());
        }
        List<Long> menuIds = sysRoleMenuMapper.selectList(new LambdaQueryWrapper<SysRoleMenu>()
                        .in(SysRoleMenu::getRoleId, roleIds))
                .stream().map(SysRoleMenu::getMenuId).distinct().toList();
        if (menuIds.isEmpty()) {
            return Collections.emptyList();
        }
        return sysMenuMapper.selectBatchIds(menuIds).stream()
                .map(SysMenu::getPermCode)
                .filter(StringUtils::hasText)
                .distinct()
                .collect(Collectors.toList());
    }

    private SysRoleVO toVO(SysRole role) {
        SysRoleVO vo = new SysRoleVO();
        vo.setRoleId(role.getRoleId());
        vo.setRoleCode(role.getRoleCode());
        vo.setRoleName(role.getRoleName());
        vo.setDescription(role.getDescription());
        vo.setIsBuiltin(role.getIsBuiltin());
        vo.setDefaultDataScope(role.getDefaultDataScope());
        vo.setSort(role.getSort());
        vo.setStatus(role.getStatus());
        vo.setDefaultDataScopeLabel(DataScopeEnum.of(role.getDefaultDataScope())
                .map(DataScopeEnum::getLabel).orElse(null));
        vo.setUserCount(sysUserRoleMapper.selectCount(
                new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getRoleId, role.getRoleId())));
        return vo;
    }
}