package com.jtzx.crm.module.sys.service; import cc.uncarbon.framework.core.context.UserContextHolder; import cc.uncarbon.framework.core.exception.BusinessException; import cc.uncarbon.framework.core.page.PageResult; import cc.uncarbon.framework.crud.entity.HelioBaseEntity; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.google.common.collect.Lists; import com.jtzx.crm.config.AsyncVThreadConfiguration; import com.jtzx.crm.module.api.util.CrmAdminStpUtil; import com.jtzx.crm.module.sys.entity.SysGroupEntity; import com.jtzx.crm.module.sys.entity.SysRoleEntity; import com.jtzx.crm.module.sys.entity.SysUserEntity; import com.jtzx.crm.module.sys.entity.SysUserRoleRelationEntity; import com.jtzx.crm.module.sys.mapper.SysGroupMapper; import com.jtzx.crm.module.sys.mapper.SysRoleMapper; import com.jtzx.crm.module.sys.mapper.SysUserMapper; import com.jtzx.crm.module.sys.mapper.SysUserRoleRelationMapper; import com.jtzx.crm.module.sys.model.request.UserRoleRelationDTO; import com.jtzx.crm.module.sys.model.request.UserRoleRelationInsertDTO; import com.jtzx.crm.module.sys.model.response.*; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Comparator; import java.util.HashSet; import java.util.List; /** * 后台用户-角色关联 */ @RequiredArgsConstructor @Service @Slf4j public class SysUserRoleRelationService { private final SysUserRoleRelationMapper sysUserRoleRelationMapper; private final SysRoleMapper sysRoleMapper; private final SysUserMapper sysUserMapper; private final SysGroupMapper sysGroupMapper; private final AsyncVThreadConfiguration asyncVThreadConfiguration; /** * 更新用户redis中的角色信息 * * @param userId */ @Transactional(rollbackFor = Exception.class) public void updateUserRole(Long userId) { List roleValueLists = Lists.newArrayList(); List roleIdList = Lists.newArrayList(); List roleRelationEntityList = sysUserRoleRelationMapper.selectList( new LambdaQueryWrapper<>(SysUserRoleRelationEntity.class) .select( SysUserRoleRelationEntity::getRoleValue, SysUserRoleRelationEntity::getRoleId ) .eq(SysUserRoleRelationEntity::getUserId, userId) ); if (CollUtil.isNotEmpty(roleRelationEntityList)) { roleValueLists.addAll( roleRelationEntityList.stream() .map(SysUserRoleRelationEntity::getRoleValue) .toList()); roleIdList.addAll( roleRelationEntityList.stream() .map(SysUserRoleRelationEntity::getRoleId) .toList()); } UserContextHolder.getUserContext().setRoles(roleValueLists.stream().distinct().toList()); UserContextHolder.getUserContext().setRolesIds(new HashSet<>(roleIdList)); } /** * 查询角色下拉数据列表 * * @return */ public List queryRoleData() { List sysRoleEntities = sysRoleMapper.selectList( new LambdaQueryWrapper<>(SysRoleEntity.class) .ne(SysRoleEntity::getValue, "Member") ); List result = Lists.newArrayList(); sysRoleEntities.stream() .sorted(Comparator.comparing(SysRoleEntity::getSortCode).reversed()) .forEach(sysRoleEntity -> { SysRoleListBO bo = SysRoleListBO.builder().build(); bo.setId(sysRoleEntity.getId()); bo.setTitle(sysRoleEntity.getTitle()); result.add(bo); }); return result; } /** * 分页查询表格数据列表 * * @param dto * @return */ public PageResult queryTableListByPage(UserRoleRelationDTO dto) { //查询角色数据 List roleEntityList = sysRoleMapper.selectList( new LambdaQueryWrapper<>(SysRoleEntity.class) .select( SysRoleEntity::getSortCode, SysRoleEntity::getId, SysRoleEntity::getValue, SysRoleEntity::getTitle ) .eq(dto.getRoleId() != null, SysRoleEntity::getId, dto.getRoleId()) .ne(SysRoleEntity::getValue, "Member") ); if (CollUtil.isEmpty(roleEntityList)) { return new PageResult() .setCurrent(1) .setSize(dto.getPageSize()) .setTotal(0) .setRecords(Lists.newArrayList()); } //查询分组数据 List groupEntityList = sysGroupMapper.selectList( new LambdaQueryWrapper<>(SysGroupEntity.class) .select( SysGroupEntity::getSortCode, SysGroupEntity::getId, SysGroupEntity::getTitle ) .eq(dto.getGroupId() != null, HelioBaseEntity::getId, dto.getGroupId()) ); if (CollUtil.isEmpty(groupEntityList)) { return new PageResult() .setCurrent(1) .setSize(dto.getPageSize()) .setTotal(0) .setRecords(Lists.newArrayList()); } //查询用户 List userEntityList = sysUserMapper.selectList( new LambdaQueryWrapper<>(SysUserEntity.class) .select( SysUserEntity::getUserName, SysUserEntity::getId, SysUserEntity::getPin ) .eq(dto.getUserId() != null, SysUserEntity::getId, dto.getUserId()) .eq(SysUserEntity::getStatus, 1) .and(StrUtil.isNotEmpty(dto.getQueryStr()), z -> z.like(SysUserEntity::getUserName, dto.getQueryStr()) .or().like(SysUserEntity::getPin, dto.getQueryStr()) ) ); if (CollUtil.isEmpty(userEntityList)) { return new PageResult() .setCurrent(1) .setSize(dto.getPageSize()) .setTotal(0) .setRecords(Lists.newArrayList()); } List userIds = userEntityList.stream() .sorted(Comparator.comparing(SysUserEntity::getId)) .map(SysUserEntity::getId) .toList(); Page entityPage = sysUserRoleRelationMapper.selectPage( new Page<>(dto.getPageNum(), dto.getPageSize()), new LambdaQueryWrapper<>(SysUserRoleRelationEntity.class) .eq(dto.getRoleId() != null, SysUserRoleRelationEntity::getRoleId, dto.getRoleId()) .eq(dto.getGroupId() != null, SysUserRoleRelationEntity::getGroupId, dto.getGroupId()) .eq(dto.getUserId() != null && StrUtil.isEmpty(dto.getQueryStr()), SysUserRoleRelationEntity::getUserId, dto.getUserId()) .in(StrUtil.isNotEmpty(dto.getQueryStr()), SysUserRoleRelationEntity::getUserId, userIds) .ne(SysUserRoleRelationEntity::getRoleValue, "Member") .orderByDesc(SysUserRoleRelationEntity::getCreatedAt) ); if (CollUtil.isEmpty(entityPage.getRecords())) { return new PageResult() .setCurrent(1) .setSize(dto.getPageSize()) .setTotal(0) .setRecords(Lists.newArrayList()); } List result = Lists.newArrayList(); entityPage.getRecords().forEach(record -> { UserRoleRelationPageListBO bo = UserRoleRelationPageListBO.builder().build(); bo.setId(record.getId()); bo.setGroupId(null); bo.setGroupName("-"); if (record.getGroupId() != null) { groupEntityList.stream() .filter(x -> x.getId().equals(record.getGroupId())) .findFirst() .ifPresent(group -> { bo.setGroupId(group.getId()); bo.setGroupName(group.getTitle()); }); } userEntityList.stream() .filter(x -> x.getId().equals(record.getUserId())) .findFirst() .ifPresent(user -> { bo.setUserId(user.getId()); bo.setUserName(user.getUserName()); bo.setAccount(user.getPin()); }); roleEntityList.stream() .filter(x -> x.getId().equals(record.getRoleId())) .findFirst() .ifPresent(role -> { bo.setRoleId(role.getId()); bo.setRoleName(role.getTitle()); }); bo.setDelStatus(0); result.add(bo); }); return new PageResult() .setCurrent(entityPage.getCurrent()) .setSize(entityPage.getSize()) .setTotal(entityPage.getTotal()) .setRecords(result); } /** * 查询用户下拉数据列表 * @return */ public List queryUserData() { List result = Lists.newArrayList(); //查询关系数据 List relationEntityList = sysUserRoleRelationMapper.selectList( new LambdaQueryWrapper<>(SysUserRoleRelationEntity.class) .ne(SysUserRoleRelationEntity::getRoleValue, "Member") .orderByDesc(SysUserRoleRelationEntity::getCreatedAt) ); if (CollUtil.isNotEmpty(relationEntityList)) { List userIds = relationEntityList.stream() .map(SysUserRoleRelationEntity::getUserId) .distinct().toList(); //查询用户 List sysUserEntityList = sysUserMapper.selectList( new LambdaQueryWrapper<>(SysUserEntity.class) .in(SysUserEntity::getId, userIds) .eq(SysUserEntity::getStatus, 1) ); relationEntityList.forEach(record -> { if (CollUtil.isNotEmpty(sysUserEntityList)) { sysUserEntityList.stream() .filter(x -> x.getId().equals(record.getUserId())) .findFirst() .ifPresent(user -> { RoleUserBO bo = RoleUserBO.builder().build(); bo.setId(record.getId()); bo.setUserId(record.getUserId()); bo.setUserName(sysUserMapper.selectById(record.getUserId()).getUserName()); bo.setGroupId(record.getGroupId()); bo.setRoleId(record.getRoleId()); bo.setUserName(user.getUserName()); bo.setAccount(user.getPin()); result.add(bo); }); } }); } return result; } /** * 查询权限表格数据 */ public List queryTableData() { List userRoleRelationBOList = Lists.newArrayList(); //查询关系数据 List relationEntityList = sysUserRoleRelationMapper.selectList( new LambdaQueryWrapper<>(SysUserRoleRelationEntity.class) .ne(SysUserRoleRelationEntity::getRoleValue, "Member") ); //查询角色 List sysRoleEntities = sysRoleMapper.selectList( new LambdaQueryWrapper<>(SysRoleEntity.class) .ne(SysRoleEntity::getValue, "Member") ); //查询用户 List sysUserEntityList = sysUserMapper.selectList( new LambdaQueryWrapper<>(SysUserEntity.class) .eq(SysUserEntity::getStatus, 1) ); //查询分组数据 List groupEntityList = sysGroupMapper.selectList(null); //数据处理 if (CollUtil.isNotEmpty(sysRoleEntities)) { sysRoleEntities.stream() .sorted(Comparator.comparing(SysRoleEntity::getSortCode).reversed()) .forEach(roleEntity -> { List roleRelationEntityList = Lists.newArrayList(); if (CollUtil.isNotEmpty(relationEntityList)) { roleRelationEntityList.addAll( relationEntityList.stream() .filter(relationEntity -> relationEntity.getRoleId().equals(roleEntity.getId())) .toList()); } List sysUserEntities = Lists.newArrayList(); if (CollUtil.isNotEmpty(roleRelationEntityList) && CollUtil.isNotEmpty(sysUserEntityList)) { List userIds = roleRelationEntityList.stream() .map(SysUserRoleRelationEntity::getUserId) .distinct().toList(); sysUserEntities.addAll( sysUserEntityList.stream() .filter(x -> userIds.contains(x.getId())) .toList()); } //处理数据 userRoleRelationBOList.add( this.handleResultData(roleEntity, groupEntityList, roleRelationEntityList, sysUserEntities)); }); } return userRoleRelationBOList; } /** * 处理数据 * * @param roleEntity * @param groupEntityList * @param roleRelationEntityList * @param sysUserEntities * @return */ public UserRoleRelationBO handleResultData(SysRoleEntity roleEntity, List groupEntityList, List roleRelationEntityList, List sysUserEntities) { UserRoleRelationBO roleRelationBO = UserRoleRelationBO.builder().build(); roleRelationBO.setRoleId(roleEntity.getId()); roleRelationBO.setRoleName(roleEntity.getTitle()); roleRelationBO.setSortCode(roleEntity.getSortCode()); //处理分组数据 List groupData = Lists.newArrayList(); if (roleEntity.getValue().equals("GroupManager")) { groupEntityList.stream() .sorted(Comparator.comparing(SysGroupEntity::getSortCode)) .forEach(groupEntity -> { SysGroupBO sysGroupBO = SysGroupBO.builder().build(); sysGroupBO.setId(groupEntity.getId()); sysGroupBO.setTitle(groupEntity.getTitle()); sysGroupBO.setSortCode(groupEntity.getSortCode()); groupData.add(sysGroupBO); }); } roleRelationBO.setGroupData(groupData); //处理用户数据 List userData = Lists.newArrayList(); if (CollUtil.isNotEmpty(roleRelationEntityList)) { if (CollUtil.isNotEmpty(groupData)) { groupData.stream() .sorted(Comparator.comparing(SysGroupBO::getSortCode)) .forEach(sysGroupBO -> { List userRoleRelationEntities = roleRelationEntityList.stream() .filter(x -> x.getGroupId().equals(sysGroupBO.getId())) .toList(); if (CollUtil.isNotEmpty(userRoleRelationEntities)) { //处理用户数据 userData.addAll( this.handleUserData(userRoleRelationEntities, sysUserEntities)); } }); } else { //处理用户数据 userData.addAll( this.handleUserData(roleRelationEntityList, sysUserEntities)); } } roleRelationBO.setUserData(userData); return roleRelationBO; } /** * 处理用户数据 * * @param roleRelationEntityList * @param sysUserEntities * @return */ public List handleUserData(List roleRelationEntityList, List sysUserEntities) { List userData = Lists.newArrayList(); roleRelationEntityList.stream() .sorted(Comparator.comparing(HelioBaseEntity::getCreatedAt)) .forEach(roleRelation -> { if (CollUtil.isNotEmpty(sysUserEntities)) { sysUserEntities.stream() .filter(x -> x.getId().equals(roleRelation.getUserId())) .findFirst() .ifPresent(user -> { if (CollUtil.isEmpty(userData) || userData.stream().map(RoleUserBO::getUserId).noneMatch(user.getId()::equals)) { RoleUserBO roleUserBO = RoleUserBO.builder().build(); roleUserBO.setId(roleRelation.getId()); roleUserBO.setUserId(user.getId()); roleUserBO.setUserName(user.getUserName()); roleUserBO.setAccount(user.getPin()); roleUserBO.setGroupId(roleRelation.getGroupId()); userData.add(roleUserBO); } }); } }); return userData; } /** * 后台管理-新增 * 注:本方法较为特殊,仅供SysTenantFacadeImpl调用 */ @Transactional(rollbackFor = Exception.class) public Long adminInsert(UserRoleRelationInsertDTO dto) { long count = sysUserRoleRelationMapper.selectCount( new LambdaQueryWrapper<>(SysUserRoleRelationEntity.class) .select(SysUserRoleRelationEntity::getUserId) .eq(SysUserRoleRelationEntity::getRoleId, dto.getRoleId()) .eq(SysUserRoleRelationEntity::getUserId, dto.getUserId()) .eq(dto.getGroupId() != null, SysUserRoleRelationEntity::getGroupId, dto.getGroupId()) ); if (count > 0) { throw new BusinessException(400, "请勿重复设置"); } SysRoleEntity sysRoleEntity = sysRoleMapper.selectById(dto.getRoleId()); SysUserRoleRelationEntity entity = new SysUserRoleRelationEntity() .setUserId(dto.getUserId()).setRoleId(dto.getRoleId()).setGroupId(dto.getGroupId()).setRoleValue(sysRoleEntity.getValue()); sysUserRoleRelationMapper.insert(entity); CrmAdminStpUtil.kickout(dto.getUserId()); this.updateUserRole(dto.getUserId()); // if (sysRoleEntity.getValue().equals("Admin")) { // CrmAdminStpUtil.kickout(dto.getUserId()); // } // else { // //异步执行更新用户角色问题 // asyncVThreadConfiguration.getAsyncExecutor().execute(() -> // this.updateUserRole(dto.getUserId())); // } return entity.getId(); } @Transactional(rollbackFor = Exception.class) public void adminInsertGroupUser(UserRoleRelationInsertDTO dto) { long count = sysUserRoleRelationMapper.selectCount( new LambdaQueryWrapper<>(SysUserRoleRelationEntity.class) .select(SysUserRoleRelationEntity::getUserId) .eq(SysUserRoleRelationEntity::getRoleId, dto.getRoleId()) .eq(SysUserRoleRelationEntity::getUserId, dto.getUserId()) .eq(dto.getGroupId() != null, SysUserRoleRelationEntity::getGroupId, dto.getGroupId()) ); if (count == 0) { SysRoleEntity sysRoleEntity = sysRoleMapper.selectById(dto.getRoleId()); SysUserRoleRelationEntity entity = new SysUserRoleRelationEntity() .setUserId(dto.getUserId()).setRoleId(dto.getRoleId()).setGroupId(dto.getGroupId()).setRoleValue(sysRoleEntity.getValue()); sysUserRoleRelationMapper.insert(entity); this.updateUserRole(dto.getUserId()); // if (sysRoleEntity.getValue().equals("Admin")) { // CrmAdminStpUtil.kickout(dto.getUserId()); // } else { // //异步执行更新用户角色问题 // asyncVThreadConfiguration.getAsyncExecutor().execute(() -> // this.updateUserRole(dto.getUserId())); // } } } @Transactional(rollbackFor = Exception.class) public void delete(Long id) { SysUserRoleRelationEntity roleRelationEntity = sysUserRoleRelationMapper.selectById(id); if (roleRelationEntity != null) { sysUserRoleRelationMapper.deleteById(id); //如果处理的是管理员,需要重新登陆 CrmAdminStpUtil.kickout(roleRelationEntity.getUserId()); // this.updateUserRole(roleRelationEntity.getUserId()); // if (roleRelationEntity.getRoleValue().equals("Admin")) { // CrmAdminStpUtil.kickout(roleRelationEntity.getUserId()); // } else { // //异步执行更新用户角色问题 // asyncVThreadConfiguration.getAsyncExecutor().execute(() -> // this.updateUserRole(roleRelationEntity.getUserId())); // } } } @Transactional(rollbackFor = Exception.class) public void delete(Long userId, Long groupId, String roleValue) { sysUserRoleRelationMapper.delete( new LambdaQueryWrapper<>(SysUserRoleRelationEntity.class) .eq(SysUserRoleRelationEntity::getUserId, userId) .eq(SysUserRoleRelationEntity::getGroupId, groupId) .eq(SysUserRoleRelationEntity::getRoleValue, roleValue) ); } }