package jnpf.permission.controller; import cn.dev33.satoken.annotation.SaCheckPermission; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.google.common.collect.ImmutableList; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameters; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import jnpf.base.ActionResult; import jnpf.base.Page; import jnpf.base.Pagination; import jnpf.base.UserInfo; import jnpf.base.controller.SuperController; import jnpf.base.entity.DictionaryDataEntity; import jnpf.base.entity.SystemEntity; import jnpf.base.service.DictionaryDataService; import jnpf.base.service.SysconfigService; import jnpf.base.service.SystemService; import jnpf.base.util.ExcelTool; import jnpf.base.vo.DownloadVO; import jnpf.base.vo.ListVO; import jnpf.base.vo.PageListVO; import jnpf.base.vo.PaginationVO; import jnpf.config.ConfigValueUtil; import jnpf.constant.FileTypeConstant; import jnpf.constant.MsgCode; import jnpf.constant.PermissionConst; import jnpf.database.util.TenantDataSourceUtil; import jnpf.exception.DataException; import jnpf.flowable.enums.ExtraRuleEnum; import jnpf.message.service.SynThirdDingTalkService; import jnpf.message.service.SynThirdQyService; import jnpf.model.*; import jnpf.model.tenant.AdminInfoVO; import jnpf.model.tenant.TenantReSetPasswordForm; import jnpf.model.tenant.TenantVO; import jnpf.permission.constant.UserColumnMap; import jnpf.permission.entity.*; import jnpf.permission.model.check.CheckResult; import jnpf.permission.model.position.PosConModel; import jnpf.permission.model.position.PositionListVO; import jnpf.permission.model.position.PositionVo; import jnpf.permission.model.user.UserAuthForm; import jnpf.permission.model.user.UserIdListVo; import jnpf.permission.model.user.UserRelationIds; import jnpf.permission.model.user.WorkHandoverModel; import jnpf.permission.model.user.form.UserBatchForm; import jnpf.permission.model.user.form.UserCrForm; import jnpf.permission.model.user.form.UserResetPasswordForm; import jnpf.permission.model.user.form.UserUpForm; import jnpf.permission.model.user.mod.*; import jnpf.permission.model.user.page.PageUser; import jnpf.permission.model.user.page.PaginationUser; import jnpf.permission.model.user.page.UserPagination; import jnpf.permission.model.user.vo.*; import jnpf.permission.rest.PullUserUtil; import jnpf.permission.service.*; import jnpf.permission.util.AuthPermUtil; import jnpf.permission.util.PermissionUtil; import jnpf.service.AuthService; import jnpf.util.*; import jnpf.util.enums.DictionaryDataEnum; import jnpf.util.treeutil.SumTree; import jnpf.util.treeutil.newtreeutil.TreeDotUtils; import jnpf.workflow.service.TemplateApi; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; import static jnpf.util.Constants.ADMIN_KEY; /** * 用户管理 * * @author JNPF开发平台组 * @version V3.1.0 * @copyright 引迈信息技术有限公司 * @date 2019年9月26日 上午9:18 */ @Tag(name = "用户管理", description = "Users") @Slf4j @RestController @RequestMapping("/api/permission/Users") public class UserController extends SuperController { @Autowired private CacheKeyUtil cacheKeyUtil; @Autowired private SynThirdQyService synThirdQyService; @Autowired private SynThirdDingTalkService synThirdDingTalkService; @Autowired private UserService userService; @Autowired private OrganizeService organizeService; @Autowired private RedisUtil redisUtil; @Autowired private UserRelationService userRelationService; @Autowired private RoleRelationService roleRelationService; @Autowired private RoleService roleService; @Autowired private PositionService positionService; @Autowired private GroupService groupService; @Autowired private TemplateApi templateApi; @Autowired private AuthService authService; @Autowired private DictionaryDataService dictionaryDataApi; @Autowired private ConfigValueUtil configValueUtil; @Autowired private SysconfigService sysconfigApi; @Autowired private AuthPermUtil authPermUtil; @Autowired private SystemService systemService; @Operation(summary = "获取用户列表") @GetMapping public ActionResult> getList(UserPagination pagination) { List userList = userService.getList(pagination); List list = new ArrayList<>(); List dataServiceList4 = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.SEX_TYPE.getDictionaryTypeId()); Map genderMap = dataServiceList4.stream().collect(Collectors.toMap(DictionaryDataEntity::getEnCode, DictionaryDataEntity::getFullName)); Map positionMap = positionService.getPosFullNameMap(); //责任人(有岗位信息时添加属性) String dutyUser = ""; if (StringUtil.isNotEmpty(pagination.getPositionId())) { PositionEntity info = positionService.getInfo(pagination.getPositionId()); if (info != null) dutyUser = info.getDutyUser(); } for (UserEntity userEntity : userList) { UserListVO userVO = JsonUtil.getJsonToBean(userEntity, UserListVO.class); userVO.setFullName(userVO.getRealName() + "/" + userVO.getAccount()); userVO.setHandoverMark(userEntity.getHandoverMark() == null ? 0 : userEntity.getHandoverMark()); userVO.setHeadIcon(UploaderUtil.uploaderImg(userVO.getHeadIcon())); // 时间小于当前时间则判断已解锁 if (userVO.getEnabledMark() != null && userVO.getEnabledMark() != 0) { if (Objects.nonNull(userEntity.getUnlockTime()) && userEntity.getUnlockTime().getTime() > System.currentTimeMillis()) { userVO.setEnabledMark(2); } else if (Objects.nonNull(userEntity.getUnlockTime()) && userEntity.getUnlockTime().getTime() < System.currentTimeMillis()) { userVO.setEnabledMark(1); } } userVO.setGender(genderMap.get(userEntity.getGender())); StringJoiner positionJoiner = new StringJoiner(","); StringJoiner organizeJoiner = new StringJoiner(","); List allPostion = userRelationService.getListByObjectType(userEntity.getId(), PermissionConst.POSITION); if (CollectionUtil.isNotEmpty(allPostion)) { for (UserRelationEntity item : allPostion) { String posName = positionMap.get(item.getObjectId()); if (posName != null) { positionJoiner.add(posName); organizeJoiner.add(posName.substring(0, posName.lastIndexOf("/"))); } } } userVO.setPosition(positionJoiner.toString()); userVO.setOrganize(organizeJoiner.toString()); if (StringUtil.isNotEmpty(dutyUser) && dutyUser.equals(userEntity.getId())) { userVO.setIsDutyUser(1); } list.add(userVO); } PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class); return ActionResult.page(list, paginationVO); } @Operation(summary = "详情") @Parameters({ @Parameter(name = "id", description = "用户id", required = true) }) @SaCheckPermission("permission.user") @GetMapping("/{id}") public ActionResult getInfo(@PathVariable("id") String id) throws DataException { UserEntity entity = userService.getInfo(id); if (entity == null) { return ActionResult.fail(MsgCode.FA001.get()); } QueryWrapper roleQuery = new QueryWrapper<>(); roleQuery.lambda().eq(UserRelationEntity::getUserId, id); roleQuery.lambda().eq(UserRelationEntity::getObjectType, PermissionConst.ROLE); List roleIdList = new ArrayList<>(); for (UserRelationEntity ure : userRelationService.list(roleQuery)) { roleIdList.add(ure.getObjectId()); } entity.setHeadIcon(UploaderUtil.uploaderImg(entity.getHeadIcon())); // 得到组织树 UserInfoVO vo = JsonUtilEx.getJsonToBeanEx(entity, UserInfoVO.class); vo.setRoleId(String.join(",", roleIdList)); // 获取组织id数组 QueryWrapper query = new QueryWrapper<>(); query.lambda().eq(UserRelationEntity::getUserId, id); query.lambda().eq(UserRelationEntity::getObjectType, PermissionConst.ORGANIZE); List organizeIds = new ArrayList<>(); userRelationService.list(query).forEach(u -> { organizeIds.add(u.getObjectId()); }); // 岗位装配 QueryWrapper positionQuery = new QueryWrapper<>(); positionQuery.lambda().eq(UserRelationEntity::getUserId, id); positionQuery.lambda().eq(UserRelationEntity::getObjectType, PermissionConst.POSITION); String positionIds = ""; for (UserRelationEntity ure : userRelationService.list(positionQuery)) { PositionEntity info = positionService.getInfo(ure.getObjectId()); if (info != null) { positionIds = positionIds + "," + ure.getObjectId(); } } if (!positionIds.isEmpty()) { vo.setPositionId(positionIds.substring(1)); } else { vo.setPositionId(null); } // 设置分组id List listByObjectType = userRelationService.getListByObjectType(entity.getId(), PermissionConst.GROUP); StringBuilder groupId = new StringBuilder(); listByObjectType.stream().forEach(t -> groupId.append("," + t.getObjectId())); if (groupId.length() > 0) { vo.setGroupId(groupId.toString().replaceFirst(",", "")); } vo.setOrganizeIdTree(PermissionUtil.getOrgIdsTree(organizeIds, 1, organizeService)); return ActionResult.success(vo); } @Operation(summary = "新建用户") @Parameters({ @Parameter(name = "userCrForm", description = "表单参数", required = true) }) @SaCheckPermission("permission.user") @PostMapping public ActionResult create(@RequestBody @Valid UserCrForm userCrForm) throws Exception { UserEntity entity = JsonUtil.getJsonToBean(userCrForm, UserEntity.class); if (userService.isExistByAccount(userCrForm.getAccount())) { return ActionResult.fail(MsgCode.EXIST001.get()); } if (StringUtil.isEmpty(entity.getGender())) { return ActionResult.fail(MsgCode.PS020.get()); } userService.create(entity); String catchKey = cacheKeyUtil.getAllUser(); if (redisUtil.exists(catchKey)) { redisUtil.remove(catchKey); } BaseSystemInfo sysInfo = sysconfigApi.getSysInfo(); entity.setPassword(sysInfo.getNewUserDefaultPassword()); PullUserUtil.syncUser(entity, "create", UserProvider.getUser().getTenantId()); return ActionResult.success(MsgCode.SU001.get()); } @Operation(summary = "修改用户") @Parameters({ @Parameter(name = "id", description = "主键值", required = true), @Parameter(name = "userUpForm", description = "表单参数", required = true) }) @SaCheckPermission("permission.user") @PutMapping("/{id}") public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid UserUpForm userUpForm) throws Exception { UserEntity entity = JsonUtil.getJsonToBean(userUpForm, UserEntity.class); if (StringUtil.isEmpty(entity.getGender())) { return ActionResult.fail(MsgCode.PS020.get()); } //将禁用的id加进数据 UserEntity originUser = userService.getInfo(id); UserInfoVO infoVO = this.getInfo(id).getData(); // 如果是管理员的话 if ("1".equals(String.valueOf(originUser.getIsAdministrator()))) { UserInfo operatorUser = UserProvider.getUser(); // 管理员可以修改自己,但是无法修改其他管理员 if (operatorUser.getIsAdministrator()) { if (originUser.getEnabledMark() != 0 && entity.getEnabledMark() == 0) { return ActionResult.fail(MsgCode.PS021.get()); } if (!ADMIN_KEY.equals(userService.getInfo(operatorUser.getUserId()).getAccount())) { if (!operatorUser.getUserId().equals(id)) { return ActionResult.fail(MsgCode.PS022.get()); } } } else { return ActionResult.fail(MsgCode.PS023.get()); } } if (!originUser.getAccount().equals(entity.getAccount())) { if (userService.isExistByAccount(entity.getAccount())) { return ActionResult.fail(MsgCode.EXIST001.get()); } } // 如果账号被锁定 if ("2".equals(String.valueOf(entity.getEnabledMark()))) { entity.setUnlockTime(null); entity.setLogErrorCount(0); } // 如果原来是锁定,现在不锁定,则置空错误次数 if (originUser.getEnabledMark() == 2 && entity.getEnabledMark() == 1) { entity.setUnlockTime(null); entity.setLogErrorCount(0); } boolean flag = userService.update(id, entity); ThreadPoolExecutorUtil.getExecutor().execute(() -> { try { //修改用户之后判断是否需要同步到企业微信 synThirdQyService.updateUserSysToQy(false, entity, "", 1); //修改用户之后判断是否需要同步到钉钉 synThirdDingTalkService.updateUserSysToDing(false, entity, "", 1); } catch (Exception e) { log.error("修改用户之后同步失败到企业微信或钉钉失败,异常: {}", e.getMessage()); } }); if (!flag) { return ActionResult.fail(MsgCode.FA002.get()); } // 踢出在线的用户 if (Objects.equals(entity.getEnabledMark(), 0)) { userService.logoutUser(MsgCode.LOG208.get(), ImmutableList.of(entity.getId())); } else if (Objects.equals(entity.getEnabledMark(), 2)) { userService.logoutUser(MsgCode.LOG209.get(), ImmutableList.of(entity.getId())); } PullUserUtil.syncUser(entity, "update", UserProvider.getUser().getTenantId()); return ActionResult.success(MsgCode.SU004.get()); } @Operation(summary = "删除用户") @Parameters({ @Parameter(name = "id", description = "主键值", required = true) }) @SaCheckPermission("permission.user") @DeleteMapping("/{id}") public ActionResult delete(@PathVariable("id") String id) { UserEntity entity = userService.getInfo(id); if (entity != null) { if ("1".equals(String.valueOf(entity.getIsAdministrator()))) { return ActionResult.fail(MsgCode.PS026.get()); } //判断是否是部门主管 if (!(organizeService.getList(false).stream().filter(t -> id.equals(t.getManagerId())).count() == 0)) { return ActionResult.fail(MsgCode.PS027.get()); } String tenantId = StringUtil.isEmpty(UserProvider.getUser().getTenantId()) ? "" : UserProvider.getUser().getTenantId(); String catchKey = tenantId + "allUser"; if (redisUtil.exists(catchKey)) { redisUtil.remove(catchKey); } //删除之前进行判断 List relationEntities = userRelationService.getListByUserId(id, PermissionConst.ORGANIZE); SocialsSysConfig socialsConfig = sysconfigApi.getSocialsConfig(); String dingDepartment = socialsConfig.getDingDepartment(); String qyhDepartment = socialsConfig.getQyhDepartment(); boolean dingChoice; boolean qyChoice; OrganizeEntity dingOrg = organizeService.getInfo(dingDepartment); OrganizeEntity qyQrg = organizeService.getInfo(qyhDepartment); if (ObjectUtil.isNotEmpty(dingOrg)) { dingChoice = relationEntities.stream().noneMatch(t -> dingOrg.getOrganizeIdTree().contains(t.getObjectId())); } else { dingChoice = true; } if (ObjectUtil.isNotEmpty(qyQrg)) { qyChoice = relationEntities.stream().noneMatch(t -> qyQrg.getOrganizeIdTree().contains(t.getObjectId())); } else { qyChoice = true; } userService.delete(entity); ThreadPoolExecutorUtil.getExecutor().execute(() -> { try { //删除用户之后判断是否需要同步到企业微信 if (!qyChoice) { synThirdQyService.deleteUserSysToQy(false, id, ""); } //删除用户之后判断是否需要同步到钉钉 if (!dingChoice) { synThirdDingTalkService.deleteUserSysToDing(false, id, ""); } } catch (Exception e) { log.error("删除用户之后同步失败到企业微信或钉钉失败,异常:" + e.getMessage()); } }); userService.logoutUser(MsgCode.LOG207.get(), ImmutableList.of(entity.getId())); PullUserUtil.syncUser(entity, "delete", UserProvider.getUser().getTenantId()); return ActionResult.success(MsgCode.SU003.get()); } return ActionResult.fail(MsgCode.FA003.get()); } //++++++++++++++++++++++批量操作start+++++++++++++++++++++++++ @Operation(summary = "批量删除") @Parameters({ @Parameter(name = "idList", description = "用户id列表", required = true) }) @SaCheckPermission("permission.user") @PostMapping("/BatchDelete") public ActionResult BatchDelete(@RequestBody UserBatchForm form) { List listByUserIds = userService.getListByUserIds(form.getIds()); List userIdList = new ArrayList<>(); if (CollectionUtil.isNotEmpty(listByUserIds)) { List collect = listByUserIds.stream().filter(t -> !Objects.equals("1", t.getIsAdministrator())).map(UserEntity::getId).collect(Collectors.toList()); userIdList.addAll(collect); } else { return ActionResult.fail(MsgCode.FA003.get()); } if (CollectionUtil.isEmpty(userIdList)) { return ActionResult.fail(MsgCode.PS026.get()); } if (redisUtil.exists(cacheKeyUtil.getAllUser())) { redisUtil.remove(cacheKeyUtil.getAllUser()); } SocialsSysConfig socialsConfig = sysconfigApi.getSocialsConfig(); String dingDepartment = socialsConfig.getDingDepartment(); String qyhDepartment = socialsConfig.getQyhDepartment(); OrganizeEntity dingOrg = organizeService.getInfo(dingDepartment); OrganizeEntity qyQrg = organizeService.getInfo(qyhDepartment); for (UserEntity userItem : listByUserIds) { if (userIdList.contains(userItem.getId())) { String id = userItem.getId(); List relationEntities = userRelationService.getListByUserId(id, PermissionConst.ORGANIZE); boolean dingChoice; boolean qyChoice; if (ObjectUtil.isNotEmpty(dingOrg)) { dingChoice = relationEntities.stream().noneMatch(t -> dingOrg.getOrganizeIdTree().contains(t.getObjectId())); } else { dingChoice = true; } if (ObjectUtil.isNotEmpty(qyQrg)) { qyChoice = relationEntities.stream().noneMatch(t -> qyQrg.getOrganizeIdTree().contains(t.getObjectId())); } else { qyChoice = true; } ThreadPoolExecutorUtil.getExecutor().execute(() -> { try { //删除用户之后判断是否需要同步到企业微信 if (!qyChoice) { synThirdQyService.deleteUserSysToQy(false, id, ""); } //删除用户之后判断是否需要同步到钉钉 if (!dingChoice) { synThirdDingTalkService.deleteUserSysToDing(false, id, ""); } } catch (Exception e) { log.error("删除用户之后同步失败到企业微信或钉钉失败,异常:" + e.getMessage()); } }); PullUserUtil.syncUser(userItem, "delete", UserProvider.getUser().getTenantId()); } } userService.batchDelete(userIdList); userService.logoutUser(MsgCode.LOG207.get(), userIdList); return ActionResult.success(MsgCode.SU003.get()); } @Operation(summary = "批量更新状态:锁定、禁用、删除") @Parameters({ @Parameter(name = "idList", description = "用户id列表", required = true), @Parameter(name = "enableMark", description = "用户id列表", required = true) }) @SaCheckPermission("permission.user") @PostMapping("/BatchUpdateState") public ActionResult BatchUpdateState(@RequestBody UserBatchForm form) { if (CollectionUtil.isNotEmpty(form.getIds())) { List listByUserIds = userService.getListByUserIds(form.getIds()); if (CollectionUtil.isNotEmpty(listByUserIds)) { try { for (UserEntity entity : listByUserIds) { if (Objects.equals(entity.getIsAdministrator(), 1)) { continue; } entity.setEnabledMark(form.getEnabledMark()); userService.update(entity.getId(), entity); //禁用移除在线用户 if (Objects.equals(form.getEnabledMark(), 0)) { userService.logoutUser(MsgCode.LOG208.get(), ImmutableList.of(entity.getId())); } else if (Objects.equals(form.getEnabledMark(), 2)) { userService.logoutUser(MsgCode.LOG209.get(), ImmutableList.of(entity.getId())); } } } catch (Exception e) { e.printStackTrace(); } return ActionResult.success(MsgCode.SU005.get()); } } return ActionResult.success(MsgCode.FA001.get()); } //++++++++++++++++++++++批量操作end+++++++++++++++++++++++++ /** * 获取用户列表 * * @return ignore */ @Operation(summary = "获取所有用户列表") @GetMapping("/All") public ActionResult> getAllUsers(PaginationUser pagination) { List list = userService.getList(pagination, null, false, false, null, null); List user = JsonUtil.getJsonToList(list, UserAllVO.class); ListVO vo = new ListVO<>(); vo.setList(user); return ActionResult.success(vo); } /** * IM通讯获取用户接口 * * @param pagination 分页参数 * @return ignore */ @Operation(summary = "IM通讯获取用户") @GetMapping("/ImUser") public ActionResult> getAllImUserUsers(Pagination pagination) { PageUser pageUser = JsonUtil.getJsonToBean(pagination, PageUser.class); List data = userService.getList(pageUser, true); List list = new ArrayList<>(); Map orgMaps = organizeService.getOrganizeName(data.stream().map(t -> t.getOrganizeId()).collect(Collectors.toList()), null, false, null); for (UserEntity entity : data) { ImUserListVo user = JsonUtil.getJsonToBean(entity, ImUserListVo.class); OrganizeEntity organize = orgMaps.get(entity.getOrganizeId()); user.setDepartment(organize != null ? organize.getFullName() : ""); user.setHeadIcon(UploaderUtil.uploaderImg(entity.getHeadIcon())); list.add(user); } PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class); return ActionResult.page(list, paginationVO); } /** * 获取用户下拉框列表 * * @return ignore */ @Operation(summary = "获取用户下拉框列表") @GetMapping("/Selector") public ActionResult> selector() { Map orgMaps = organizeService.getOrgMaps(null, true, null); List organizeData = new ArrayList<>(orgMaps.values()); List userData = userService.getList(true); List treeList = JsonUtil.getJsonToList(organizeData, UserSelectorModel.class); for (UserSelectorModel entity1 : treeList) { if ("department".equals(entity1.getType())) { entity1.setIcon(PermissionConst.DEPARTMENT_ICON); } else if ("company".equals(entity1.getType())) { entity1.setIcon(PermissionConst.COMPANY_ICON); } } for (UserEntity entity : userData) { UserSelectorModel treeModel = new UserSelectorModel(); treeModel.setId(entity.getId()); treeModel.setParentId(entity.getOrganizeId()); treeModel.setFullName(entity.getRealName() + "/" + entity.getAccount()); treeModel.setType("user"); treeModel.setIcon(PermissionConst.USER_ICON); treeList.add(treeModel); } List> trees = TreeDotUtils.convertListToTreeDot(treeList); List listvo = JsonUtil.getJsonToList(trees, UserSelectorVO.class); List entities = organizeData.stream().filter( t -> "-1".equals(t.getParentId()) ).collect(Collectors.toList()); Iterator iterator = listvo.iterator(); while (iterator.hasNext()) { UserSelectorVO userSelectorVO = iterator.next(); for (OrganizeEntity entity : entities) { if (entity.getId().equals(userSelectorVO.getParentId())) { iterator.remove();//使用迭代器的删除方法删除 } } } ListVO vo = new ListVO<>(); vo.setList(listvo); return ActionResult.success(vo); } /** * 通过部门、岗位、用户、角色、分组id获取用户列表 * * @param userConditionModel 用户选择模型 * @return */ @Operation(summary = "通过部门、岗位、用户、角色、分组id获取用户列表") @Parameters({ @Parameter(name = "userConditionModel", description = "用户选择模型", required = true) }) @PostMapping("/UserCondition") public ActionResult userCondition(@RequestBody UserConditionModel userConditionModel) { List list = new ArrayList<>(16); if (userConditionModel.getDepartIds() != null) { list.addAll(userConditionModel.getDepartIds()); } if (userConditionModel.getRoleIds() != null) { list.addAll(userConditionModel.getRoleIds()); } if (userConditionModel.getPositionIds() != null) { list.addAll(userConditionModel.getPositionIds()); } if (userConditionModel.getGroupIds() != null) { list.addAll(userConditionModel.getGroupIds()); } if (list.size() == 0) { list = userRelationService.getListByObjectType(userConditionModel.getType()).stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList()); if (PermissionConst.GROUP.equals(userConditionModel.getType())) { List groupList = groupService.getListByIds(list); list = groupList.stream().map(GroupEntity::getId).collect(Collectors.toList()); } if (PermissionConst.ORGANIZE.equals(userConditionModel.getType())) { List orgList = organizeService.getOrgEntityList(list, true); list = orgList.stream().map(OrganizeEntity::getId).collect(Collectors.toList()); } if (PermissionConst.ROLE.equals(userConditionModel.getType())) { List roleList = roleService.getListByIds(list, null, false); list = roleList.stream().filter(t -> t.getEnabledMark() == 1).map(RoleEntity::getId).collect(Collectors.toList()); } if (PermissionConst.POSITION.equals(userConditionModel.getType())) { List positionList = positionService.getPosList(list); list = positionList.stream().filter(t -> t.getEnabledMark() == 1).map(PositionEntity::getId).collect(Collectors.toList()); } } List collect = userRelationService.getListByObjectIdAll(list).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList()); if (userConditionModel.getUserIds() != null) { collect.addAll(userConditionModel.getUserIds()); } collect = collect.stream().distinct().collect(Collectors.toList()); List userName = userService.getUserName(collect, userConditionModel.getPagination()); List jsonToList = JsonUtil.getJsonToList(userName, UserIdListVo.class); Map orgIdNameMaps = organizeService.getInfoList(); jsonToList.forEach(t -> { t.setHeadIcon(UploaderUtil.uploaderImg(t.getHeadIcon())); t.setFullName(t.getRealName() + "/" + t.getAccount()); List listByUserId = userRelationService.getListByUserId(t.getId(), PermissionConst.ORGANIZE); List orgId = listByUserId.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList()); List organizeName = new ArrayList<>(organizeService.getOrganizeName(orgId, null, false, null).values()); StringBuilder stringBuilder = new StringBuilder(); organizeName.forEach(org -> { if (StringUtil.isNotEmpty(org.getOrganizeIdTree())) { String fullNameByOrgIdTree = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, org.getOrganizeIdTree(), "/"); stringBuilder.append(","); stringBuilder.append(fullNameByOrgIdTree); } }); if (stringBuilder.length() > 0) { t.setOrganize(stringBuilder.toString().replaceFirst(",", "")); } }); PaginationVO paginationVO = JsonUtil.getJsonToBean(userConditionModel.getPagination(), PaginationVO.class); return ActionResult.page(jsonToList, paginationVO); } /** * 获取用户下拉框列表 * * @param organizeIdForm 组织id * @param pagination 分页模型 * @return */ @Operation(summary = "获取用户下拉框列表") @Parameters({ @Parameter(name = "organizeId", description = "组织id", required = true), @Parameter(name = "pagination", description = "分页模型", required = true) }) @PostMapping("/ImUser/Selector/{organizeId}") public ActionResult imUserSelector(@PathVariable("organizeId") String organizeIdForm, @RequestBody Pagination pagination) { String organizeId = XSSEscape.escape(organizeIdForm); List jsonToList = new ArrayList<>(); Map orgIdNameMaps = organizeService.getInfoList(); Map orgMaps = organizeService.getOrgMaps(null, true, null); //判断是否搜索关键字 if (StringUtil.isNotEmpty(pagination.getKeyword())) { //通过关键字查询 PageUser pageUser = JsonUtil.getJsonToBean(pagination, PageUser.class); List list = userService.getList(pageUser, false); //遍历用户给要返回的值插入值 for (UserEntity entity : list) { UserSelectorVO vo = JsonUtil.getJsonToBean(entity, UserSelectorVO.class); vo.setParentId(entity.getOrganizeId()); vo.setFullName(entity.getRealName() + "/" + entity.getAccount()); vo.setType("user"); vo.setIcon(PermissionConst.USER_ICON); vo.setHeadIcon(UploaderUtil.uploaderImg(vo.getHeadIcon())); List listByUserId = userRelationService.getListByUserId(entity.getId()).stream().filter(t -> t != null && PermissionConst.ORGANIZE.equals(t.getObjectType())).collect(Collectors.toList()); StringJoiner stringJoiner = new StringJoiner(","); listByUserId.forEach(t -> { OrganizeEntity organizeEntity = orgMaps.get(t.getObjectId()); if (organizeEntity != null) { String fullNameByOrgIdTree = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity.getOrganizeIdTree(), "/"); if (StringUtil.isNotEmpty(fullNameByOrgIdTree)) { stringJoiner.add(fullNameByOrgIdTree); } } }); vo.setOrganize(stringJoiner.toString()); vo.setHasChildren(false); vo.setIsLeaf(true); jsonToList.add(vo); } PaginationVO jsonToBean = JsonUtil.getJsonToBean(pagination, PaginationVO.class); return ActionResult.page(jsonToList, jsonToBean); } //获取所有组织 List collect = new ArrayList<>(orgMaps.values()); //判断时候传入组织id //如果传入组织id,则取出对应的子集 if (!"0".equals(organizeId)) { //通过组织查询部门及人员 //单个组织 OrganizeEntity organizeEntity = orgMaps.get(organizeId); if (organizeEntity != null) { //取出组织下的部门 List collect1 = collect.stream().filter(t -> t.getParentId().equals(organizeEntity.getId())).collect(Collectors.toList()); for (OrganizeEntity entitys : collect1) { UserSelectorVO vo = JsonUtil.getJsonToBean(entitys, UserSelectorVO.class); if ("department".equals(entitys.getCategory())) { vo.setIcon(PermissionConst.DEPARTMENT_ICON); } else if ("company".equals(entitys.getCategory())) { vo.setIcon(PermissionConst.COMPANY_ICON); } vo.setOrganize(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, entitys.getOrganizeIdTree(), "/")); // 判断组织下是否有人 jsonToList.add(vo); vo.setHasChildren(true); vo.setIsLeaf(false); } //取出组织下的人员 List entityList = userService.getListByOrganizeId(organizeId, null); for (UserEntity entity : entityList) { if ("0".equals(String.valueOf(entity.getEnabledMark()))) { continue; } UserSelectorVO vo = JsonUtil.getJsonToBean(entity, UserSelectorVO.class); vo.setParentId(organizeId); vo.setFullName(entity.getRealName() + "/" + entity.getAccount()); vo.setType("user"); vo.setIcon(PermissionConst.USER_ICON); List listByUserId = userRelationService.getListByUserId(entity.getId()).stream().filter(t -> t != null && PermissionConst.ORGANIZE.equals(t.getObjectType())).collect(Collectors.toList()); StringBuilder stringBuilder = new StringBuilder(); listByUserId.forEach(t -> { OrganizeEntity organizeEntity1 = orgMaps.get(t.getObjectId()); if (organizeEntity1 != null) { String fullNameByOrgIdTree = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity1.getOrganizeIdTree(), "/"); if (StringUtil.isNotEmpty(fullNameByOrgIdTree)) { stringBuilder.append("," + fullNameByOrgIdTree); } } }); if (stringBuilder.length() > 0) { vo.setOrganize(stringBuilder.toString().replaceFirst(",", "")); } vo.setHeadIcon(UploaderUtil.uploaderImg(vo.getHeadIcon())); vo.setHasChildren(false); vo.setIsLeaf(true); jsonToList.add(vo); } } ListVO vo = new ListVO<>(); vo.setList(jsonToList); return ActionResult.success(vo); } //如果没有组织id,则取出所有组织 jsonToList = JsonUtil.getJsonToList(collect.stream().filter(t -> "-1".equals(t.getParentId())).collect(Collectors.toList()), UserSelectorVO.class); //添加图标 for (UserSelectorVO userSelectorVO : jsonToList) { userSelectorVO.setIcon(PermissionConst.COMPANY_ICON); userSelectorVO.setHasChildren(true); userSelectorVO.setIsLeaf(false); userSelectorVO.setOrganize(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, orgMaps.get(userSelectorVO.getId()).getOrganizeIdTree(), "/")); } ListVO vo = new ListVO<>(); vo.setList(jsonToList); return ActionResult.success(vo); } /** * 获取用户下拉框列表 * * @param organizeId 组织id * @param page 关键字 * @return */ @Operation(summary = "获取用户下拉框列表") @Parameters({ @Parameter(name = "organizeId", description = "组织id", required = true), @Parameter(name = "page", description = "关键字", required = true) }) @SaCheckPermission("permission.grade") @PostMapping("/GetListByAuthorize/{organizeId}") public ActionResult> getListByAuthorize(@PathVariable("organizeId") String organizeId, @RequestBody Page page) { List jsonToList = userService.getListByAuthorize(organizeId, page); ListVO listVO = new ListVO(); listVO.setList(jsonToList); return ActionResult.success(listVO); } @Operation(summary = "个人权限") @Parameters({ @Parameter(name = "id", description = "主键值", required = true), }) @GetMapping("/Authorize") public ActionResult getAuthorize(UserAuthForm param) { return ActionResult.success(authPermUtil.getUserAuth(param)); } @Operation(summary = "角色岗位权限列表") @GetMapping("/getAllPermission") public ActionResult> getAllPermission(@RequestParam(value = "userId", required = false) String userId) { if (StringUtil.isEmpty(userId)) { userId = UserProvider.getUser().getUserId(); } List listRes = new ArrayList<>(); listRes.add(new PositionVo("all", "全部权限")); //添加岗位 List posIds = userRelationService.getListByUserId(userId, PermissionConst.POSITION).stream().map(u -> u.getObjectId()).collect(Collectors.toList()); if (CollectionUtil.isNotEmpty(posIds)) { PositionVo pv = new PositionVo(PermissionConst.POSITION, "所属岗位"); pv.setHasChildren(true); List child = new ArrayList<>(); Map allOrgsTreeName = organizeService.getAllOrgsTreeName(); List rList = positionService.getListByIds(posIds); for (PositionEntity item : rList) { PositionVo vo = JsonUtil.getJsonToBean(item, PositionVo.class); vo.setFullName(allOrgsTreeName.get(item.getOrganizeId()) + "/" + item.getFullName()); vo.setType(PermissionConst.POSITION); child.add(vo); } pv.setChildren(child); listRes.add(pv); } //添加角色 List roleIds = roleRelationService.getListByObjectId(userId, PermissionConst.USER) .stream().map(RoleRelationEntity::getRoleId).collect(Collectors.toList()); if (CollectionUtil.isNotEmpty(roleIds)) { PositionVo pv = new PositionVo(PermissionConst.ROLE, "所属角色"); pv.setHasChildren(true); List child = new ArrayList<>(); List rList = roleService.getListByIds(roleIds); for (RoleEntity item : rList) { PositionVo vo = JsonUtil.getJsonToBean(item, PositionVo.class); vo.setType(PermissionConst.ROLE); child.add(vo); } pv.setChildren(child); listRes.add(pv); } return ActionResult.success(listRes); } @Operation(summary = "用户获取岗位") @Parameters({ @Parameter(name = "id", description = "主键值", required = true), }) @SaCheckPermission("permission.user") @GetMapping("/{id}/GetPosition") public ActionResult> GetPosition(@PathVariable("id") String id) { UserEntity entity = userService.getInfo(id); List list = new ArrayList<>(); if (entity != null) { List relationList = userRelationService.getListByUserId(id, PermissionConst.POSITION); Map allOrgsTreeName = organizeService.getAllOrgsTreeName(); List positionList = positionService.getListByIds(relationList.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList())); for (PositionEntity item : positionList) { PositionListVO vo = JsonUtil.getJsonToBean(item, PositionListVO.class); vo.setOrgNameTree(allOrgsTreeName.get(item.getOrganizeId()) + "/" + item.getFullName()); list.add(vo); } } return ActionResult.success(list); } @Operation(summary = "同岗位用户列表") @Parameters({ @Parameter(name = "id", description = "主键值", required = true), }) @SaCheckPermission("permission.user") @GetMapping("/{id}/SelectorByUserPosId") public ActionResult> SelectorByUserPosId(@PathVariable("id") String id, Pagination pagination) { UserEntity entity = userService.getInfo(id); PageUser pageUser = JsonUtil.getJsonToBean(pagination, PageUser.class); List list = new ArrayList<>(); if (entity != null) { List relationList = userRelationService.getListByUserId(id, PermissionConst.POSITION); List posIds = relationList.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList()); List userIds = userRelationService.getListByObjectIdAll(posIds).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList()); if (CollectionUtil.isNotEmpty(userIds)) { pageUser.setIdList(userIds); List userList = userService.getList(pageUser, true); for (UserEntity item : userList) { UserListVO vo = JsonUtil.getJsonToBean(item, UserListVO.class); vo.setFullName(item.getRealName() + "/" + item.getAccount()); vo.setHeadIcon(UploaderUtil.uploaderImg(item.getHeadIcon())); list.add(vo); } } } PaginationVO paginationVO = JsonUtil.getJsonToBean(pageUser, PaginationVO.class); return ActionResult.page(list, paginationVO); } @Operation(summary = "用户调整岗位") @Parameters({ @Parameter(name = "id", description = "用户主键值", required = true) }) @SaCheckPermission("permission.user") @PostMapping("/{id}/SetPosition") public ActionResult setPosition(@PathVariable("id") String id, @RequestBody UserBatchForm form) { UserEntity entity = userService.getInfo(id); if (entity == null) { return ActionResult.fail(MsgCode.FA001.get()); } if (Objects.equals(entity.getIsAdministrator(), 1)) { return ActionResult.success(MsgCode.PS023.get()); } List posIds = form.getIds(); List relationList = userRelationService.getListByUserId(id, PermissionConst.POSITION); //直接打开不编辑保存不执行代码 if (!posIds.isEmpty() && posIds.equals(relationList.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList()))) { return ActionResult.success(MsgCode.SU023.get()); } List posList = positionService.getListByIds(posIds); //判断约束 -- 逐一判断,能成功的就添加res List res = new ArrayList<>(); Set huchi = new HashSet<>(); Set xianjue = new HashSet<>(); List errList1 = new ArrayList<>(); filterPos(posIds, posList, errList1, huchi, res, xianjue); //先决第一个判断不存在,再次判断后续有没有添加上先决的 if (CollectionUtil.isNotEmpty(xianjue)) { filterXianJuePos(new ArrayList<>(xianjue), posList, errList1, res); } //只有出现约束异常就直接修改失败 if (CollectionUtil.isNotEmpty(errList1)) { return ActionResult.fail(MsgCode.FA055.get(MsgCode.PS004.get())); } List orgList = userRelationService.getListByUserId(id, PermissionConst.ORGANIZE); //移除全部岗位、组织和用户得关系 List deleteAll = new ArrayList<>(); deleteAll.addAll(relationList); deleteAll.addAll(orgList); //删除之前进行判断 SocialsSysConfig socialsConfig = sysconfigApi.getSocialsConfig(); String dingDepartment = socialsConfig.getDingDepartment(); String qyhDepartment = socialsConfig.getQyhDepartment(); boolean dingChoice; boolean qyChoice; OrganizeEntity dingOrg = organizeService.getInfo(dingDepartment); OrganizeEntity qyQrg = organizeService.getInfo(qyhDepartment); if (ObjectUtil.isNotEmpty(dingOrg)) { dingChoice = deleteAll.stream().noneMatch(t -> dingOrg.getOrganizeIdTree().contains(t.getObjectId())); } else { dingChoice = true; } if (ObjectUtil.isNotEmpty(qyQrg)) { qyChoice = deleteAll.stream().noneMatch(t -> qyQrg.getOrganizeIdTree().contains(t.getObjectId())); } else { qyChoice = true; } ThreadPoolExecutorUtil.getExecutor().execute(() -> { try { //获取公司关联 List collect = deleteAll.stream() .filter(t -> t.getObjectType().equals(PermissionConst.ORGANIZE)) .map(UserRelationEntity::getObjectId).collect(Collectors.toList()); if (!dingChoice) { synThirdDingTalkService.deleteUserSysToDing(false, entity, "", collect); } if (!qyChoice) { synThirdQyService.deleteUserSysToQy(false, entity, "", collect); } } catch (Exception e) { log.error("创建组织后同步失败到钉钉失败,异常:{}", e.getMessage()); } }); for (UserRelationEntity relationEntity : deleteAll) { userRelationService.removeById(relationEntity); } List addAll = new ArrayList<>(); if (CollectionUtil.isNotEmpty(res)) { for (String positionId : res) { PositionEntity info = posList.stream().filter(t -> t.getId().equals(positionId)).findFirst().orElse(null); UserRelationEntity userRelation = new UserRelationEntity(); userRelation.setObjectId(positionId); userRelation.setUserId(id); userRelation.setObjectType(PermissionConst.POSITION); addAll.add(userRelation); //岗位添加组织关系方便使用 UserRelationEntity userOrgRelation = new UserRelationEntity(); userOrgRelation.setObjectId(info.getOrganizeId()); userOrgRelation.setUserId(id); userOrgRelation.setObjectType(PermissionConst.ORGANIZE); addAll.add(userOrgRelation); } userRelationService.save(addAll); ThreadPoolExecutorUtil.getExecutor().execute(() -> { try { //获取公司关联 List collect = addAll.stream() .filter(t -> t.getObjectType().equals(PermissionConst.ORGANIZE)) .map(UserRelationEntity::getObjectId).collect(Collectors.toList()); synThirdQyService.createUserSysToQy(false, entity, "", collect); synThirdDingTalkService.createUserSysToDing(false, entity, "", collect); } catch (Exception e) { log.error("创建组织后同步失败到企业微信或钉钉失败,异常:{}", e.getMessage()); } }); userService.delCurUser(MsgCode.PS010.get(), Collections.singletonList(id)); } return ActionResult.success(MsgCode.SU023.get()); } private void filterPos(List posIds, List posList, List errList1, Set huchi, List res, Set xianjue) { for (String positionId : posIds) { List errList2 = new ArrayList<>(); PositionEntity info = posList.stream().filter(t -> t.getId().equals(positionId)).findFirst().orElse(null); List userIds = userRelationService.getListByObjectId(positionId, PermissionConst.POSITION) .stream().map(UserRelationEntity::getUserId).collect(Collectors.toList()); PosConModel posConModel = new PosConModel(); if (Objects.equals(info.getIsCondition(), 1)) { posConModel = JsonUtil.getJsonToBean(info.getConditionJson(), PosConModel.class); posConModel.init(); } //超出权限基数的截取 if (posConModel.getNumFlag() && posConModel.getUserNum() < (1 + userIds.size())) { errList2.add(MsgCode.SYS135.get(MsgCode.PS004.get())); } //在已有岗位的互斥信息里 if (huchi.contains(positionId)) { errList2.add(MsgCode.SYS137.get(MsgCode.PS004.get())); } //当前的岗位互斥信息-存在互斥岗位 List mutualExclusion = posConModel.getMutualExclusion(); if (posConModel.getMutualExclusionFlag()) { //互斥 List collect = res.stream().filter(t -> mutualExclusion.contains(t)).collect(Collectors.toList()); if (CollectionUtil.isNotEmpty(collect)) { errList2.add(MsgCode.SYS137.get(MsgCode.PS004.get())); } } if (posConModel.getPrerequisiteFlag()) { //先决 xianjue.add(positionId); } if (errList2.size() == 0) { res.add(positionId); if (CollectionUtil.isNotEmpty(mutualExclusion)) { huchi.addAll(mutualExclusion); } } else { errList1.addAll(errList2); } } } private void filterXianJuePos(List posIds, List posList, List errList1, List res) { for (String positionId : posIds) { List errList2 = new ArrayList<>(); PositionEntity info = posList.stream().filter(t -> t.getId().equals(positionId)).findFirst().orElse(null); PosConModel posConModel = new PosConModel(); if (Objects.equals(info.getIsCondition(), 1)) { posConModel = JsonUtil.getJsonToBean(info.getConditionJson(), PosConModel.class); posConModel.init(); } if (posConModel.getPrerequisiteFlag() && !res.containsAll(posConModel.getPrerequisite())) { //先决 errList2.add(MsgCode.SYS138.get(MsgCode.PS004.get())); } if (errList2.size() == 0) { res.add(positionId); } else { errList1.addAll(errList2); } } } @Operation(summary = "批量调整岗位") @SaCheckPermission("permission.user") @PostMapping("/SetPositionBatch") public ActionResult setPositionBatch(@RequestBody UserBatchForm form) { List userList = userService.getListByUserIds(form.getUserIds()); List posIds = form.getIds(); List positionList = positionService.getListByIds(posIds); if (CollectionUtil.isEmpty(userList)) { return ActionResult.fail(MsgCode.FA001.get()); } SocialsSysConfig socialsConfig = sysconfigApi.getSocialsConfig(); String dingDepartment = socialsConfig.getDingDepartment(); String qyhDepartment = socialsConfig.getQyhDepartment(); OrganizeEntity dingOrg = organizeService.getInfo(dingDepartment); OrganizeEntity qyQrg = organizeService.getInfo(qyhDepartment); List userIds = userList.stream().filter(t -> !Objects.equals(t.getIsAdministrator(), 1)).map(UserEntity::getId).collect(Collectors.toList()); //再加 List addUserIds = new ArrayList<>(); List skipUserIds = new ArrayList<>(); for (String userId : userIds) { List relationList = userRelationService.getListByObjectType(userId, null); //直接打开不编辑保存不执行代码 if (posIds.size() > 0 && posIds.equals(relationList.stream().filter(t -> PermissionConst.POSITION.equals(t.getObjectType())) .map(UserRelationEntity::getObjectId).collect(Collectors.toList()))) { skipUserIds.add(userId); continue; } //判断约束 List res = new ArrayList<>(); Set huchi = new HashSet<>(); Set xianjue = new HashSet<>(); List errList1 = new ArrayList<>(); filterPos(posIds, positionList, errList1, huchi, res, xianjue); //先决第一个判断不存在,再次判断后续有没有添加上先决的 if (CollectionUtil.isNotEmpty(xianjue)) { filterXianJuePos(new ArrayList<>(xianjue), positionList, errList1, res); } //岗位有约束异常就不添加 if (CollectionUtil.isNotEmpty(errList1)) { continue; } addUserIds.add(userId); List addAll = new ArrayList<>(); for (String positionId : posIds) { PositionEntity info = positionList.stream().filter(t -> t.getId().equals(positionId)).findFirst().orElse(null); UserRelationEntity userRelation = new UserRelationEntity(); userRelation.setObjectId(info.getId()); userRelation.setUserId(userId); userRelation.setObjectType(PermissionConst.POSITION); addAll.add(userRelation); //岗位添加组织关系方便使用 UserRelationEntity userOrgRelation = new UserRelationEntity(); userOrgRelation.setObjectId(info.getOrganizeId()); userOrgRelation.setUserId(userId); userOrgRelation.setObjectType(PermissionConst.ORGANIZE); addAll.add(userOrgRelation); } //先删 List deleteList = relationList.stream().filter(t -> PermissionConst.POSITION.equals(t.getObjectType()) || PermissionConst.ORGANIZE.equals(t.getObjectType())).collect(Collectors.toList()); //删除之前进行判断 boolean dingChoice; boolean qyChoice; if (ObjectUtil.isNotEmpty(dingOrg)) { dingChoice = deleteList.stream().noneMatch(t -> dingOrg.getOrganizeIdTree().contains(t.getObjectId())); } else { dingChoice = true; } if (ObjectUtil.isNotEmpty(qyQrg)) { qyChoice = deleteList.stream().noneMatch(t -> qyQrg.getOrganizeIdTree().contains(t.getObjectId())); } else { qyChoice = true; } for (UserRelationEntity relationEntity : deleteList) { userRelationService.removeById(relationEntity); } try { List collect = deleteList.stream() .map(UserRelationEntity::getUserId) .collect(Collectors.toList()); if (!qyChoice) { synThirdQyService.deleteUserSysToQy(false, collect, "", ""); } if (!dingChoice) { synThirdDingTalkService.deleteUserSysToDing(false, collect, "", ""); } } catch (Exception e) { log.error(e.getMessage()); } userRelationService.save(addAll); try { Map> collect = addAll .stream() .filter(t -> t.getObjectType().equals(PermissionConst.POSITION)) .collect(Collectors.groupingBy(UserRelationEntity::getObjectId)); for (String string : collect.keySet()) { PositionEntity info = positionService.getInfo(string); List userRelationEntities = collect.get(string); List userEntityIds = userRelationEntities.stream().map(UserRelationEntity::getUserId) .collect(Collectors.toList()); List userEntities = userService.getUserList(userEntityIds) .stream().peek(t -> t.setOrganizeId(info.getOrganizeId())) .collect(Collectors.toList()); synThirdQyService.createUserSysToQy(false, userEntities, "", info.getId()); synThirdDingTalkService.createUserSysToDing(false, userEntities, "", info.getId()); } } catch (Exception e) { log.error(e.getMessage()); } } if (CollectionUtil.isNotEmpty(addUserIds)) { userService.delCurUser(MsgCode.PS010.get(), addUserIds); } if (addUserIds.size() == 0 && skipUserIds.size() == 0) { return ActionResult.fail(MsgCode.FA054.get()); } else if (addUserIds.size() > 0 && addUserIds.size() != userIds.size()) { return ActionResult.success(MsgCode.SU024.get()); } return ActionResult.success(MsgCode.SU023.get()); } @Operation(summary = "修改用户密码") @Parameters({ @Parameter(name = "id", description = "主键值", required = true), @Parameter(name = "userResetPasswordForm", description = "修改密码模型", required = true) }) @SaCheckPermission("permission.user") @PostMapping("/{id}/Actions/ResetPassword") public ActionResult modifyPassword(@PathVariable("id") String id, @RequestBody @Valid UserResetPasswordForm userResetPasswordForm) { UserEntity entity = userService.getInfo(id); if (entity != null) { entity.setPassword(userResetPasswordForm.getUserPassword()); userService.updatePassword(entity); userService.logoutUser(MsgCode.PS011.get(), ImmutableList.of(entity.getId())); entity.setPassword(userResetPasswordForm.getUserPassword()); PullUserUtil.syncUser(entity, "modifyPassword", UserProvider.getUser().getTenantId()); return ActionResult.success(MsgCode.SU005.get()); } return ActionResult.success(MsgCode.FA001.get()); } /** * 更新用户状态 * * @param id 主键值 * @return ignore */ @Operation(summary = "更新用户状态") @Parameters({ @Parameter(name = "id", description = "主键值", required = true) }) @SaCheckPermission("permission.user") @PutMapping("/{id}/Actions/State") public ActionResult disable(@PathVariable("id") String id) throws Exception { UserEntity entity = userService.getInfo(id); if (entity != null) { if ("1".equals(String.valueOf(entity.getIsAdministrator()))) { return ActionResult.fail(MsgCode.PS029.get()); } if (entity.getEnabledMark() != null) { if ("1".equals(String.valueOf(entity.getEnabledMark()))) { entity.setEnabledMark(0); userService.delCurUser(null, ImmutableList.of(entity.getId())); userService.update(id, entity); } else { entity.setEnabledMark(1); userService.update(id, entity); } } else { entity.setEnabledMark(1); userService.update(id, entity); } return ActionResult.success(MsgCode.SU005.get()); } return ActionResult.success(MsgCode.FA001.get()); } /** * 解除锁定 * * @param id 主键值 * @return ignore */ @Operation(summary = "解除锁定") @Parameters({ @Parameter(name = "id", description = "主键值", required = true) }) @SaCheckPermission("permission.user") @PutMapping("/{id}/Actions/unlock") public ActionResult unlock(@PathVariable("id") String id) throws Exception { UserEntity entity = userService.getInfo(id); if (entity != null) { // 状态变成正常 entity.setEnabledMark(1); entity.setUnlockTime(null); entity.setLogErrorCount(0); entity.setId(id); userService.updateById(entity); return ActionResult.success(MsgCode.SU005.get()); } return ActionResult.success(MsgCode.FA001.get()); } /** * 获取用户基本信息 * * @param userIdModel 用户id * @return ignore */ @Operation(summary = "获取用户基本信息") @Parameters({ @Parameter(name = "userIdModel", description = "用户id", required = true) }) @PostMapping("/getUserList") public ActionResult> getUserList(@RequestBody UserIdModel userIdModel) { List userName = userService.getUserName(userIdModel.getIds(), true); List list = JsonUtil.getJsonToList(userName, UserIdListVo.class); List listByUserIds = userRelationService.getRelationByUserIds(list.stream().map(UserIdListVo::getId).collect(Collectors.toList())); Map orgIdNameMaps = organizeService.getInfoList(); for (UserIdListVo entity : list) { if (entity == null) { break; } entity.setFullName(entity.getRealName() + "/" + entity.getAccount()); List listByUserId = listByUserIds.stream().filter(t -> t.getUserId().equals(entity.getId())).collect(Collectors.toList()); StringBuilder stringBuilder = new StringBuilder(); List orgEntityList = organizeService.getOrgEntityList(listByUserId.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList()), false); listByUserId.forEach(t -> { OrganizeEntity organizeEntity = orgEntityList.stream().filter(org -> org.getId().equals(t.getObjectId())).findFirst().orElse(null); if (organizeEntity != null) { String fullNameByOrgIdTree = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity.getOrganizeIdTree(), "/"); if (StringUtil.isNotEmpty(fullNameByOrgIdTree)) { stringBuilder.append("," + fullNameByOrgIdTree); } } }); if (stringBuilder.length() > 0) { entity.setOrganize(stringBuilder.toString().replaceFirst(",", "")); } entity.setHeadIcon(UploaderUtil.uploaderImg(entity.getHeadIcon())); } ListVO listVO = new ListVO<>(); listVO.setList(list); return ActionResult.success(listVO); } /** * 获取选中组织、岗位、角色、用户基本信息 * * @param userIdModel 用户id * @return ignore */ @Operation(summary = "获取选中组织、岗位、角色、用户基本信息") @Parameters({ @Parameter(name = "userIdModel", description = "用户id", required = true) }) @PostMapping("/getSelectedList") public ActionResult> getSelectedList(@RequestBody UserIdModel userIdModel) { List ids = userIdModel.getIds(); List list = userService.selectedByIds(ids); ListVO listVO = new ListVO<>(); listVO.setList(list); return ActionResult.success(listVO); } /** * 获取用户基本信息 * * @param userIdModel 用户id * @return ignore */ @Operation(summary = "获取选中用户基本信息") @Parameters({ @Parameter(name = "userIdModel", description = "用户id", required = true) }) @PostMapping("/getSelectedUserList") public ActionResult> getSelectedUserList(@RequestBody UserIdModelByPage userIdModel) { List jsonToList = userService.getObjList(userIdModel.getIds(), userIdModel); PaginationVO paginationVO = JsonUtil.getJsonToBean(userIdModel, PaginationVO.class); return ActionResult.page(jsonToList, paginationVO); } /** * 获取组织下的人员 * * @param page 页面信息 * @return ignore */ @Operation(summary = "获取组织下的人员") @GetMapping("/getOrganization") public ActionResult> getOrganization(PageUser page) { String departmentId = page.getOrganizeId(); // 判断是否获取当前组织下的人员 if ("0".equals(departmentId)) { departmentId = UserProvider.getUser().getDepartmentId(); // 为空则取组织id if (StringUtil.isEmpty(departmentId)) { departmentId = UserProvider.getUser().getOrganizeId(); } } Map orgMaps = organizeService.getOrgMaps(null, true, null); List list = userService.getListByOrganizeId(departmentId, page.getKeyword()); List jsonToList = JsonUtil.getJsonToList(list, UserIdListVo.class); Map orgIdNameMaps = organizeService.getInfoList(); List listByObjectType = userRelationService.getListByObjectType(PermissionConst.ORGANIZE); jsonToList.forEach(t -> { t.setRealName(t.getRealName() + "/" + t.getAccount()); t.setFullName(t.getRealName()); List collect = listByObjectType.stream().filter(userRelationEntity -> userRelationEntity.getUserId().equals(t.getId())).map(UserRelationEntity::getObjectId).collect(Collectors.toList()); StringJoiner stringJoiner = new StringJoiner(","); collect.forEach(objectId -> { OrganizeEntity organizeEntity = orgMaps.get(objectId); if (organizeEntity != null) { String fullNameByOrgIdTree = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity.getOrganizeIdTree(), "/"); if (StringUtil.isNotEmpty(fullNameByOrgIdTree)) { stringJoiner.add(fullNameByOrgIdTree); } } }); t.setOrganize(stringJoiner.toString()); t.setHeadIcon(UploaderUtil.uploaderImg(t.getHeadIcon())); }); return ActionResult.success(jsonToList); } /** * 获取人员,委托选人接口 * * @param type 范围类型 * @param pagination 参数 */ @Operation(summary = "获取人员") @GetMapping("/ReceiveUserList") public ActionResult receiveUserList(@RequestParam("type") Integer type, Pagination pagination) { UserInfo userInfo = UserProvider.getUser(); UserEntity user = userService.getInfo(userInfo.getUserId()); List userId = new ArrayList<>(); List ruleList = ImmutableList.of(ExtraRuleEnum.organize.getCode(), ExtraRuleEnum.position.getCode(), ExtraRuleEnum.department.getCode()); boolean isDepartmeng = false; if (ruleList.contains(type)) { List positionList = new ArrayList<>(); List organizeList = new ArrayList<>(); List userPositionList = userRelationService.getListByUserIdAll(ImmutableList.of(user.getId())).stream() .filter(t -> PermissionConst.POSITION.equals(t.getObjectType())).collect(Collectors.toList()); for (UserRelationEntity relation : userPositionList) { PositionEntity positionInfo = positionService.getInfo(relation.getObjectId()); if (positionInfo != null) { positionList.add(positionInfo.getId()); OrganizeEntity organizeInfo = organizeService.getInfo(positionInfo.getOrganizeId()); if (organizeInfo != null) { organizeList.add(organizeInfo.getId()); } } } switch (ExtraRuleEnum.getByCode(type)) { case organize: // 委托范围为同一部门,但委托人的所属组织是公司,无需选人 for (String organizeId : organizeList) { OrganizeEntity organizeInfo = organizeService.getInfo(organizeId); if (null != organizeInfo && Objects.equals(organizeInfo.getCategory(), PermissionConst.DEPARTMENT)) { userId.addAll(userRelationService.getListByObjectIdAll(ImmutableList.of(organizeId)).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList())); } } break; case position: for (String positionId : positionList) { userId.addAll(userRelationService.getListByObjectIdAll(ImmutableList.of(positionId)).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList())); } break; case department: List categoryList = ImmutableList.of("agency", "office"); int num = 0; for (String organizeId : organizeList) { OrganizeEntity organizeInfo = organizeService.getInfo(organizeId); if (organizeInfo == null || categoryList.contains(organizeInfo.getCategory())) { continue; } List orgList = organizeService.getDepartmentAll(organizeId).stream().map(OrganizeEntity::getId).collect(Collectors.toList()); List departmentAll = positionService.getListByOrgIds(orgList).stream().map(PositionEntity::getId).collect(Collectors.toList()); for (String id : departmentAll) { userId.addAll(userRelationService.getListByObjectIdAll(ImmutableList.of(id)).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList())); } num++; } isDepartmeng = num == 0; break; } } List list = isDepartmeng ? userService.getUserPage(pagination) : userService.getUserName(userId, pagination); List jsonToList = JsonUtil.getJsonToList(list, UserIdListVo.class); if (!jsonToList.isEmpty()) { List userIdList = list.stream().map(UserEntity::getId).collect(Collectors.toList()); List userRelationList = userRelationService.getRelationByUserIds(userIdList); Map> userMap = userRelationList.stream() .filter(t -> PermissionConst.POSITION.equals(t.getObjectType())).collect(Collectors.groupingBy(UserRelationEntity::getUserId)); jsonToList.forEach(t -> { t.setRealName(t.getRealName() + "/" + t.getAccount()); t.setFullName(t.getRealName()); t.setHeadIcon(UploaderUtil.uploaderImg(t.getHeadIcon())); List listByUserId = userMap.get(user.getId()) != null ? userMap.get(user.getId()) : new ArrayList<>(); StringJoiner joiner = new StringJoiner(","); for (UserRelationEntity relation : listByUserId) { StringJoiner name = new StringJoiner("/"); PositionEntity position = positionService.getInfo(relation.getObjectId()); if (position != null) { OrganizeEntity organize = organizeService.getInfo(position.getOrganizeId()); if (organize != null) { List organizeIdTree = new ArrayList<>(Arrays.asList(organize.getOrganizeIdTree().split(","))); List organizeList = organizeService.getOrganizeName(organizeIdTree); for (String organizeId : organizeIdTree) { OrganizeEntity entity = organizeList.stream().filter(e -> Objects.equals(e.getId(), organizeId)).findFirst().orElse(null); if (entity != null) { name.add(entity.getFullName()); } } } List positionIdTree = new ArrayList<>(Arrays.asList(position.getPositionIdTree().split(","))); List positionList = positionService.getPosList(positionIdTree); for (String positionId : positionIdTree) { PositionEntity entity = positionList.stream().filter(e -> Objects.equals(e.getId(), positionId)).findFirst().orElse(null); if (entity != null) { name.add(entity.getFullName()); } } } joiner.add(name.toString()); t.setOrganize(joiner.toString()); } }); } PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class); return ActionResult.page(jsonToList, paginationVO); } /** * 获取岗位人员 * * @param page 页面信息 * @return ignore */ @Operation(summary = "获取岗位人员") @GetMapping("/GetUsersByPositionId") public ActionResult> getUsersByPositionId(UsersByPositionModel page) { List list = new ArrayList<>(1); String keyword = page.getKeyword(); // 岗位id String positionId = page.getPositionId(); // 得到关联的组织id PositionEntity positionEntity = positionService.getInfo(positionId); if (positionEntity != null) { UserByRoleVO vo = new UserByRoleVO(); String organizeId = positionEntity.getOrganizeId(); // 得到组织信息 OrganizeEntity organizeEntity = organizeService.getInfo(organizeId); if (Objects.nonNull(organizeEntity)) { vo.setId(organizeEntity.getId()); vo.setType(organizeEntity.getCategory()); if ("department".equals(organizeEntity.getCategory())) { vo.setIcon(PermissionConst.DEPARTMENT_ICON); } else { vo.setIcon(PermissionConst.COMPANY_ICON); } vo.setEnabledMark(organizeEntity.getEnabledMark()); Map orgIdNameMaps = organizeService.getInfoList(); // 组装组织名称 String orgName = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity.getOrganizeIdTree(), "/"); vo.setFullName(orgName); // 赋予子集 List userByRoleVOS = new ArrayList<>(16); List lists = userService.getListByOrganizeId(organizeEntity.getId(), keyword); if (lists.size() > 0) { vo.setHasChildren(true); vo.setIsLeaf(false); lists.stream().forEach(t -> { UserByRoleVO userByRoleVO = new UserByRoleVO(); userByRoleVO.setParentId(organizeEntity.getId()); userByRoleVO.setId(t.getId()); userByRoleVO.setFullName(t.getRealName() + "/" + t.getAccount()); userByRoleVO.setEnabledMark(t.getEnabledMark()); userByRoleVO.setHeadIcon(UploaderUtil.uploaderImg(t.getHeadIcon())); userByRoleVO.setOrganize(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity.getOrganizeIdTree(), "/")); userByRoleVO.setIsLeaf(true); userByRoleVO.setHasChildren(false); userByRoleVO.setIcon(PermissionConst.USER_ICON); userByRoleVO.setType("user"); userByRoleVOS.add(userByRoleVO); }); vo.setChildren(userByRoleVOS); } else { vo.setHasChildren(false); vo.setIsLeaf(true); vo.setChildren(new ArrayList<>()); } list.add(vo); } } return ActionResult.success(list); } /** * 获取我的下属(不取子集) * * @param page 页面信息 * @return ignore */ @Operation(summary = "获取我的下属(不取子集)") @Parameters({ @Parameter(name = "page", description = "关键字", required = true) }) @PostMapping("/getSubordinates") public ActionResult> getSubordinates(@RequestBody Page page) { Map orgMaps = organizeService.getOrgMaps(null, false, null); List list = userService.getListByManagerId(UserProvider.getUser().getUserId(), page.getKeyword()); List jsonToList = JsonUtil.getJsonToList(list, UserIdListVo.class); Map orgIdNameMaps = organizeService.getInfoList(); jsonToList.forEach(t -> { t.setRealName(t.getRealName() + "/" + t.getAccount()); t.setFullName(t.getRealName()); List listByUserId = userRelationService.getListByUserId(t.getId()).stream().filter(ur -> PermissionConst.ORGANIZE.equals(ur.getObjectType())).collect(Collectors.toList()); StringJoiner stringJoiner = new StringJoiner(","); listByUserId.forEach(tt -> { OrganizeEntity organizeEntity = orgMaps.get(tt.getObjectId()); if (organizeEntity != null) { String fullNameByOrgIdTree = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity.getOrganizeIdTree(), "/"); if (StringUtil.isNotEmpty(fullNameByOrgIdTree)) { stringJoiner.add(fullNameByOrgIdTree); } } }); t.setOrganize(stringJoiner.toString()); t.setHeadIcon(UploaderUtil.uploaderImg(t.getHeadIcon())); }); return ActionResult.success(jsonToList); } /** * 根据角色ID获取所属组织的所有成员 * * @param pagination 分页模型 * @return */ @Operation(summary = "根据角色ID获取所有成员") @SaCheckPermission("permission.role") @GetMapping("/getUsersByRoleId") public ActionResult getUsersByRoleId(PaginationUser pagination) { List userList = new ArrayList<>(); if (roleService.getInfo(pagination.getRoleId()).getGlobalMark() == 1) { userList.addAll(userService.getList(pagination, null, false, false, null, null)); } else { // 根据roleId获取所有组织 userService.getListByRoleId(pagination.getRoleId()).forEach(u -> { userList.add(userService.getInfo(u.getId())); }); } // 去重 List afterUserList = userList.stream().distinct().collect(Collectors.toList()); if (StringUtil.isNotEmpty(pagination.getKeyword())) { afterUserList = afterUserList.stream().filter(t -> t.getRealName().contains(pagination.getKeyword()) || t.getAccount().contains(pagination.getKeyword())).collect(Collectors.toList()); } PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class); return ActionResult.page(afterUserList, paginationVO); } /** * 获取默认当前值用户ID * * @param userConditionModel 参数 * @return 执行结构 * @throws DataException ignore */ @Operation(summary = "获取默认当前值用户ID") @Parameters({ @Parameter(name = "userConditionModel", description = "参数", required = true) }) @PostMapping("/getDefaultCurrentValueUserId") public ActionResult getDefaultCurrentValueUserId(@RequestBody UserConditionModel userConditionModel) throws DataException { String userId = userService.getDefaultCurrentValueUserId(userConditionModel); Map dataMap = new HashMap(); dataMap.put("userId", userId); return ActionResult.success(MsgCode.SU022.get(), dataMap); } /** * 工作交接 * * @param workHandoverModel 模型 * @return 执行结构 */ @Operation(summary = "工作交接") @SaCheckPermission("permission.user") @Parameters({ @Parameter(name = "workHandoverModel", description = "模型", required = true) }) @PostMapping("/workHandover") public ActionResult workHandover(@RequestBody @Valid WorkHandoverModel workHandoverModel) { if (CollectionUtil.isEmpty(workHandoverModel.getAppList()) && CollectionUtil.isEmpty(workHandoverModel.getFlowList()) && CollectionUtil.isEmpty(workHandoverModel.getFlowTaskList())) { return ActionResult.fail(MsgCode.PS042.get()); } // 开始交接就禁用用户 UserEntity entity = userService.getInfo(workHandoverModel.getFromId()); if (StringUtil.isEmpty(workHandoverModel.getHandoverUser())) { return ActionResult.fail(MsgCode.PS043.get()); } if (StringUtil.isEmpty(workHandoverModel.getAppHandoverUser())) { return ActionResult.fail(MsgCode.PS044.get()); } UserEntity entitys = userService.getInfo(workHandoverModel.getHandoverUser()); if (entity == null || entitys == null) { return ActionResult.fail(MsgCode.FA001.get()); } if (workHandoverModel.getFromId().equals(workHandoverModel.getHandoverUser()) || workHandoverModel.getFromId().equals(workHandoverModel.getAppHandoverUser())) { return ActionResult.fail(MsgCode.PS035.get()); } if (ADMIN_KEY.equals(entitys.getAccount())) { return ActionResult.fail(MsgCode.PS034.get()); } try { boolean flag = templateApi.flowWork(workHandoverModel); if (!flag) { return ActionResult.fail(MsgCode.FA101.get()); } systemService.workHandover(workHandoverModel); entity.setHandoverMark(1); return ActionResult.success(MsgCode.PS033.get()); } finally { userService.updateById(entity); } } /** * 获取用户工作详情 * * @return 执行结构 */ @Operation(summary = "获取用户工作详情") @SaCheckPermission("permission.user") @Parameters({ @Parameter(name = "userId", description = "主键", required = true) }) @GetMapping("/getWorkByUser") public ActionResult getWorkByUser(@RequestParam("fromId") String fromId) { FlowWorkListVO flowWorkListVO = templateApi.flowWork(fromId); if (flowWorkListVO == null) { log.error("用户:" + fromId + ",待办事宜及负责流程获取失败"); flowWorkListVO = new FlowWorkListVO(); } List authListByUser = systemService.getAuthListByUser(fromId, false); // authListByUser = authListByUser.stream().filter(t -> !Objects.equals(t.getIsMain(), 1) && (fromId.equals(t.getUserId()) // || (StringUtil.isNotEmpty(t.getAuthorizeId()) && t.getAuthorizeId().contains(fromId)))).collect(Collectors.toList()); List sysList = JsonUtil.getJsonToList(authListByUser, FlowWorkModel.class); Boolean isAppShow = CollectionUtil.isNotEmpty(sysList) ? true : false; WorkHandoverVo workHandoverVo = new WorkHandoverVo(flowWorkListVO.getFlow(), flowWorkListVO.getFlowTask(), sysList, isAppShow); return ActionResult.success(workHandoverVo); } // ----------------------------- 多租户调用 /** * 重置管理员密码 * * @param userResetPasswordForm 修改密码模型 * @return ignore */ @Operation(summary = "重置管理员密码") @Parameters({ @Parameter(name = "userResetPasswordForm", description = "修改密码模型", required = true) }) @PutMapping("/Tenant/ResetPassword") @NoDataSourceBind public ActionResult resetPassword(@RequestBody @Valid TenantReSetPasswordForm userResetPasswordForm) { if (configValueUtil.isMultiTenancy()) { TenantDataSourceUtil.switchTenant(userResetPasswordForm.getTenantId()); } UserEntity entity = userService.getUserByAccount(ADMIN_KEY); if (entity != null) { entity.setPassword(userResetPasswordForm.getUserPassword()); userService.updatePassword(entity); userService.logoutUser(MsgCode.PS011.get(), ImmutableList.of(entity.getId())); entity.setPassword(userResetPasswordForm.getUserPassword()); PullUserUtil.syncUser(entity, "modifyPassword", userResetPasswordForm.getTenantId()); return ActionResult.success(MsgCode.SU005.get()); } return ActionResult.fail(MsgCode.FA001.get()); } /** * 获取用户信息 * * @param tenantId 租户号 * @return ignore */ @Operation(summary = "获取用户信息") @Parameters({ @Parameter(name = "tenantId", description = "租户号", required = true) }) @NoDataSourceBind @GetMapping("/Tenant/AdminInfo") public AdminInfoVO adminInfo(@RequestParam("tenantId") String tenantId) throws DataException { if (configValueUtil.isMultiTenancy()) { TenantDataSourceUtil.switchTenant(tenantId); } UserEntity entity = userService.getUserByAccount(ADMIN_KEY); AdminInfoVO adminInfoVO = JsonUtil.getJsonToBean(entity, AdminInfoVO.class); return adminInfoVO; } /** * 修改管理员信息 * * @param adminInfoVO 模型 * @return ignore */ @Operation(summary = "修改管理员信息") @Parameters({ @Parameter(name = "adminInfoVO", description = "模型", required = true) }) @NoDataSourceBind @PutMapping("/Tenant/UpdateAdminInfo") public ActionResult adminInfo(@RequestBody AdminInfoVO adminInfoVO) throws DataException { if (configValueUtil.isMultiTenancy()) { TenantDataSourceUtil.switchTenant(adminInfoVO.getTenantId()); } UserEntity entity = userService.getUserByAccount(ADMIN_KEY); if (entity == null) { return ActionResult.fail(MsgCode.FA001.get()); } entity.setRealName(adminInfoVO.getRealName()); entity.setMobilePhone(adminInfoVO.getMobilePhone()); entity.setEmail(adminInfoVO.getEmail()); userService.updateById(entity); ThreadPoolExecutorUtil.getExecutor().execute(() -> { try { //修改用户之后判断是否需要同步到企业微信 synThirdQyService.updateUserSysToQy(false, entity, "", ""); //修改用户之后判断是否需要同步到钉钉 synThirdDingTalkService.updateUserSysToDing(false, entity, ""); } catch (Exception e) { log.error("修改用户之后同步失败到企业微信或钉钉失败,异常:{}", e.getMessage()); } }); // 删除在线的用户 PullUserUtil.syncUser(entity, "update", adminInfoVO.getTenantId()); return ActionResult.success(MsgCode.SU004.get()); } /** * 移除租户账号在线用户 * * @param tenantId 租户号 * @return ignore */ @Operation(summary = "移除租户账号在线用户") @Parameters({ @Parameter(name = "tenantId", description = "租户号", required = true) }) @NoDataSourceBind @GetMapping("/Tenant/RemoveOnlineByTenantId") public void removeOnlineByTenantId(@RequestParam("tenantId") String tenantId) throws DataException { List tokenList = new ArrayList<>(); List tokens = UserProvider.getLoginUserListToken(); tokens.forEach(token -> { UserInfo userInfo = UserProvider.getUser(token); if (tenantId.equals(userInfo.getTenantId())) { tokenList.add(token); } }); authService.kickoutByToken(tokenList.toArray(new String[0])); } //--------------------以下导入导出----- @Operation(summary = "模板下载") @SaCheckPermission("permission.user") @GetMapping("/TemplateDownload") public ActionResult TemplateDownload() { UserColumnMap columnMap = new UserColumnMap(); String excelName = columnMap.getExcelName(); Map keyMap = columnMap.getColumnByType(0); List models = columnMap.getFieldsModel(false); List> list = columnMap.getDefaultList(); Map optionMap = getOptionMap(); ExcelModel excelModel = ExcelModel.builder().models(models).selectKey(new ArrayList<>(keyMap.keySet())).optionMap(optionMap).build(); DownloadVO vo = ExcelTool.getImportTemplate(FileTypeConstant.TEMPORARY, excelName, keyMap, list, excelModel); return ActionResult.success(vo); } @Operation(summary = "上传导入Excel") @SaCheckPermission("permission.user") @PostMapping("/Uploader") public ActionResult Uploader() { return ExcelTool.uploader(); } @Operation(summary = "导入预览") @SaCheckPermission("permission.user") @GetMapping("/ImportPreview") public ActionResult> ImportPreview(String fileName) throws Exception { // 导入字段 UserColumnMap columnMap = new UserColumnMap(); Map keyMap = columnMap.getColumnByType(0); Map headAndDataMap = ExcelTool.importPreview(FileTypeConstant.TEMPORARY, fileName, keyMap); return ActionResult.success(headAndDataMap); } /** * 导出异常报告 * * @return */ @Operation(summary = "导出异常报告") @SaCheckPermission("permission.user") @PostMapping("/ExportExceptionData") public ActionResult ExportExceptionData(@RequestBody ExcelImportForm visualImportModel) { List> dataList = visualImportModel.getList(); UserColumnMap columnMap = new UserColumnMap(); String excelName = columnMap.getExcelName(); Map keyMap = columnMap.getColumnByType(0); List models = columnMap.getFieldsModel(true); ExcelModel excelModel = ExcelModel.builder().optionMap(getOptionMap()).models(models).build(); DownloadVO vo = ExcelTool.exportExceptionReport(FileTypeConstant.TEMPORARY, excelName, keyMap, dataList, excelModel); return ActionResult.success(vo); } /** * 导入数据 * * @return */ @Operation(summary = "导入数据") @SaCheckPermission("permission.user") @PostMapping("/ImportData") public ActionResult ImportData(@RequestBody ExcelImportForm visualImportModel) throws Exception { List> listData = new ArrayList<>(); List> headerRow = new ArrayList<>(); if (visualImportModel.isType()) { ActionResult result = ImportPreview(visualImportModel.getFileName()); if (result == null) { throw new Exception(MsgCode.FA018.get()); } if (result.getCode() != 200) { throw new Exception(result.getMsg()); } if (result.getData() instanceof Map) { Map data = (Map) result.getData(); listData = (List>) data.get("dataRow"); headerRow = (List>) data.get("headerRow"); } } else { listData = visualImportModel.getList(); } List addList = new ArrayList<>(); List> failList = new ArrayList<>(); // 对数据做校验 this.validateImportData(listData, addList, failList); //正常数据插入 for (UserEntity each : addList) { userService.create(each); } ExcelImportVO importModel = new ExcelImportVO(); importModel.setSnum(addList.size()); importModel.setFnum(failList.size()); importModel.setResultType(failList.size() > 0 ? 1 : 0); importModel.setFailResult(failList); importModel.setHeaderRow(headerRow); return ActionResult.success(importModel); } /** * 导出Excel * * @return */ @Operation(summary = "导出Excel") @SaCheckPermission("permission.user") @GetMapping("/ExportData") public ActionResult ExportData(PaginationUser pagination) throws IOException { if (StringUtil.isEmpty(pagination.getSelectKey())) { return ActionResult.fail(MsgCode.IMP011.get()); } List list = userService.getList(pagination, null, false, false, null, null); Map roleIdAndNameMap = roleService.getList(false, PermissionConst.USER, null) .stream().collect(Collectors.toMap(RoleEntity::getId, t -> t.getFullName() + "/" + t.getEnCode())); Map posIdAndName = positionService.getPosEncodeAndName(true).entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); Map groupEncodeMap = groupService.getGroupEncodeMap(true).entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); Map orgMap = organizeService.getAllOrgsTreeName(true); Map userNameMap = userService.getUserNameAndIdMap(true).entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); //性别 Map sexMap = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.SEX_TYPE.getDictionaryTypeId()) .stream().collect(Collectors.toMap(DictionaryDataEntity::getEnCode, DictionaryDataEntity::getFullName)); //职级 Map ranksMap = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.RANK.getDictionaryTypeId()) .stream().collect(Collectors.toMap(DictionaryDataEntity::getId, DictionaryDataEntity::getFullName)); //民族 Map nationMap = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.NATION.getDictionaryTypeId()) .stream().collect(Collectors.toMap(DictionaryDataEntity::getId, DictionaryDataEntity::getFullName)); //证件类型 Map certificatesTypeMap = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.CERTIFICATE_TYPE.getDictionaryTypeId()) .stream().collect(Collectors.toMap(DictionaryDataEntity::getId, DictionaryDataEntity::getFullName)); //文化程度 Map educationMap = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.EDUCATION.getDictionaryTypeId()) .stream().collect(Collectors.toMap(DictionaryDataEntity::getId, DictionaryDataEntity::getFullName)); List roleRelationList = roleRelationService.getListByRoleId("", PermissionConst.USER); List userRelationList = userRelationService.getListByObjectType(PermissionConst.POSITION); List> realList = new ArrayList<>(); for (UserEntity entity : list) { entity.setHeadIcon(UploaderUtil.uploaderImg(entity.getHeadIcon())); //获取角色 List userRoleRelation = roleRelationList.stream().filter(t -> t.getObjectId().equals(entity.getId())).collect(Collectors.toList()); List roleIdList = new ArrayList<>(); for (RoleRelationEntity ure : userRoleRelation) { if (StringUtil.isNotEmpty(roleIdAndNameMap.get(ure.getRoleId()))) { roleIdList.add(roleIdAndNameMap.get(ure.getRoleId())); } } entity.setRoleId(String.join(",", roleIdList)); // 岗位装配 List userPosRelation = userRelationList.stream().filter(t -> t.getUserId().equals(entity.getId())).collect(Collectors.toList()); List positionIds = new ArrayList<>(); for (UserRelationEntity ure : userPosRelation) { if (posIdAndName.containsKey(ure.getObjectId())) { positionIds.add(posIdAndName.get(ure.getObjectId())); } } entity.setPositionId(String.join(",", positionIds)); //性别 entity.setGender(sexMap.get(entity.getGender())); entity.setRanks(ranksMap.get(entity.getRanks())); entity.setNation(nationMap.get(entity.getNation())); entity.setCertificatesType(certificatesTypeMap.get(entity.getCertificatesType())); entity.setEducation(educationMap.get(entity.getEducation())); Map obj = JsonUtil.entityToMap(entity); if (obj.get("enabledMark") != null) { String stateName = ""; if (Objects.equals(obj.get("enabledMark"), 0)) { stateName = "禁用"; } else if (Objects.equals(obj.get("enabledMark"), 1)) { stateName = "启用"; } else if (Objects.equals(obj.get("enabledMark"), 2)) { stateName = "锁定"; } obj.put("enabledMark", stateName); } if (obj.get("birthday") != null) { obj.put("birthday", DateUtil.daFormat(Long.parseLong(obj.get("birthday").toString()))); } if (obj.get("entryDate") != null) { obj.put("entryDate", DateUtil.daFormat(Long.parseLong(obj.get("entryDate").toString()))); } realList.add(obj); } String[] keys = !StringUtil.isEmpty(pagination.getSelectKey()) ? pagination.getSelectKey() : new String[0]; UserColumnMap columnMap = new UserColumnMap(); String excelName = columnMap.getExcelName(); List models = columnMap.getFieldsModel(false); Map keyMap = columnMap.getColumnByType(null); ExcelModel excelModel = ExcelModel.builder().selectKey(Arrays.asList(keys)).models(models).build(); DownloadVO vo = ExcelTool.creatModelExcel(FileTypeConstant.TEMPORARY, excelName, keyMap, realList, excelModel); return ActionResult.success(vo); } /** * 导入验证 * * @param listData * @param addList * @param failList */ private void validateImportData(List> listData, List addList, List> failList) { UserColumnMap columnMap = new UserColumnMap(); Map keyMap = columnMap.getColumnByType(0); List sexList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.SEX_TYPE.getDictionaryTypeId()); Map genderMap = sexList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getEnCode)); List rankList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.RANK.getDictionaryTypeId()); Map ranksMap = rankList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getId)); List nationList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.NATION.getDictionaryTypeId()); Map nationMap = nationList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getId)); List certificateList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.CERTIFICATE_TYPE.getDictionaryTypeId()); Map certificateMap = certificateList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getId)); List educationList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.EDUCATION.getDictionaryTypeId()); Map educationMap = educationList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getId)); Map allOrgsTreeName = organizeService.getAllOrgsTreeName(); Map userNameMap = userService.getUserNameAndIdMap(); List allPos = positionService.getList(true); Map posNameMap = positionService.getPosEncodeAndName(true); List allUserRole = roleService.getList(true, PermissionConst.USER, null); Map roleMap = allUserRole.stream().collect(Collectors.toMap(t -> t.getFullName(), RoleEntity::getId)); //所有岗位的用户列表 List posAllUser = userRelationService.getListByObjectType(PermissionConst.POSITION); //所有用户角色的用户列表 List roleAllUser = roleRelationService.getListByRoleId("", PermissionConst.USER); //角色用户数量 Map roleIdUserNum = new HashMap<>(); for (int i = 0, len = listData.size(); i < len; i++) { Map eachMap = listData.get(i); Map realMap = JsonUtil.getJsonToBean(eachMap, Map.class); StringJoiner errInfo = new StringJoiner(","); // 开启多租住的-判断用户额度 String tenantId = UserProvider.getUser().getTenantId(); if (StringUtil.isNotEmpty(tenantId)) { TenantVO cacheTenantInfo = TenantDataSourceUtil.getCacheTenantInfo(tenantId); long count = userService.count() + addList.size(); if (cacheTenantInfo.getAccountNum() != 0 && cacheTenantInfo.getAccountNum() < count) { eachMap.put("errorsInfo", MsgCode.PS009.get()); failList.add(eachMap); continue; } } //组织多选id,用于查询角色和岗位 StringJoiner organizeIds = new StringJoiner(","); for (String column : keyMap.keySet()) { Object valueObj = eachMap.get(column); String value = valueObj == null ? null : String.valueOf(valueObj); String columnName = keyMap.get(column); switch (column) { case "gender": if (StringUtil.isEmpty(value)) { errInfo.add(columnName + "不能为空"); break; } if (genderMap.containsKey(valueObj.toString())) { realMap.put("gender", genderMap.get(value)); } else { errInfo.add("找不到该" + columnName + "值"); } break; case "ranks": if (StringUtil.isNotEmpty(value)) { if (ranksMap.containsKey(valueObj.toString())) { realMap.put("ranks", ranksMap.get(value)); } else { errInfo.add("找不到该" + columnName + "值"); } } break; case "nation": if (StringUtil.isNotEmpty(value)) { if (nationMap.containsKey(valueObj.toString())) { realMap.put("nation", nationMap.get(value)); } else { errInfo.add("找不到该" + columnName + "值"); } } break; case "certificatesType": if (StringUtil.isNotEmpty(value)) { if (certificateMap.containsKey(valueObj.toString())) { realMap.put("certificatesType", certificateMap.get(value)); } else { errInfo.add("找不到该" + columnName + "值"); } } break; case "education": if (StringUtil.isNotEmpty(value)) { if (educationMap.containsKey(valueObj.toString())) { realMap.put("education", educationMap.get(value)); } else { errInfo.add("找不到该" + columnName + "值"); } } break; case "account": //账号 if (StringUtil.isEmpty(value)) { errInfo.add(columnName + "不能为空"); break; } if (value.length() > 50) { errInfo.add(columnName + "值超出最多输入字符限制"); } //值不能含有特殊符号 if (!RegexUtils.checkSpecoalSymbols(value)) { errInfo.add(columnName + "值不能含有特殊符号"); } //库里重复 if (userService.isExistByAccount(value)) { errInfo.add(columnName + "值已存在"); break; } //表格内重复 long enCodeCount = addList.stream().filter(t -> t.getAccount().equals(value)).count(); if (enCodeCount > 0) { errInfo.add(columnName + "值已存在"); break; } break; case "realName": if (StringUtil.isEmpty(value)) { errInfo.add(columnName + "不能为空"); break; } if (value.length() > 50) { errInfo.add(columnName + "值超出最多输入字符限制"); } //值不能含有特殊符号 if (!RegexUtils.checkSpecoalSymbols(value)) { errInfo.add(columnName + "值不能含有特殊符号"); } break; case "positionId": if (StringUtil.isNotEmpty(value)) { List posIds = new ArrayList<>(); List posErrList = new ArrayList<>(); List listName = Arrays.asList(value.split(",")); for (String item : listName) { if (posNameMap.containsKey(item)) { posIds.add(posNameMap.get(item).toString()); } else { posErrList.add(item); } } if (posErrList.size() > 0) { if (listName.size() > 1) { errInfo.add("找不到该" + columnName + "(" + String.join("、", posErrList) + ")"); break; } else if (listName.size() == 1) { errInfo.add("找不到该" + columnName); break; } } if (CollectionUtil.isNotEmpty(posIds)) { //判断约束 for (String item : posIds) { PositionEntity info = allPos.stream().filter(t -> t.getId().equals(item)).findFirst().orElse(null); //库里岗位用户数 List thisPosUsers = posAllUser.stream().filter(t -> t.getObjectId().equals(item)).collect(Collectors.toList()); //表格里的岗位用户数 List excelUserList = addList.stream().filter(t -> t.getPositionId() != null && t.getPositionId().contains(item)).collect(Collectors.toList()); Integer userNum = thisPosUsers.size() + excelUserList.size(); if (Objects.equals(info.getIsCondition(), 1)) { PosConModel conModelP = JsonUtil.getJsonToBean(info.getConditionJson(), PosConModel.class); conModelP.init(); if (conModelP.getMutualExclusionFlag() && conModelP.getMutualExclusion().stream().anyMatch(t -> posIds.contains(t))) { errInfo.add(info.getFullName() + "存在互斥岗位"); break; } if (conModelP.getNumFlag() && userNum >= conModelP.getUserNum()) { errInfo.add(info.getFullName() + "岗位已达用户限制个数"); break; } if (conModelP.getPrerequisiteFlag() && !posIds.containsAll(conModelP.getPrerequisite())) { errInfo.add(info.getFullName() + "存在先决岗位"); break; } } } realMap.put("positionId", String.join(",", posIds)); Set orgList = allPos.stream().filter(t -> posIds.contains(t)).map(PositionEntity::getOrganizeId).collect(Collectors.toSet()); realMap.put("organizeId", String.join(",", orgList)); break; } break; } break; case "roleId": if (StringUtil.isNotEmpty(value)) { List roleIds = new ArrayList<>(); List roleErrList = new ArrayList<>(); List listName = Arrays.asList(value.split(",")); for (String item : listName) { if (roleMap.containsKey(item)) { roleIds.add(roleMap.get(item)); } else { roleErrList.add(item); } } if (roleErrList.size() > 0) { if (listName.size() > 1) { errInfo.add("找不到该" + columnName + "(" + String.join("、", roleErrList) + ")"); break; } else if (listName.size() == 1) { errInfo.add("找不到该" + columnName); break; } } if (CollectionUtil.isNotEmpty(roleIds)) { //判断约束 for (String item : roleIds) { RoleEntity info = allUserRole.stream().filter(t -> t.getId().equals(item)).findFirst().orElse(null); List thisRoleUsers = roleAllUser.stream().filter(t -> t.getRoleId().equals(item)).collect(Collectors.toList()); //表格里的岗位用户数 List excelUserList = addList.stream().filter(t -> t.getRoleId() != null && t.getRoleId().contains(item)).collect(Collectors.toList()); Integer userNum = thisRoleUsers.size() + excelUserList.size(); if (Objects.equals(info.getIsCondition(), 1)) { PosConModel conModelP = JsonUtil.getJsonToBean(info.getConditionJson(), PosConModel.class); conModelP.init(); if (conModelP.getMutualExclusionFlag() && conModelP.getMutualExclusion().stream().anyMatch(t -> roleIds.contains(t))) { errInfo.add(info.getFullName() + "存在互斥角色"); break; } if (conModelP.getNumFlag() && userNum >= conModelP.getUserNum()) { errInfo.add(info.getFullName() + "角色已达用户限制个数"); break; } if (conModelP.getPrerequisiteFlag() && !roleIds.containsAll(conModelP.getPrerequisite())) { errInfo.add(info.getFullName() + "存在先决角色"); break; } } } realMap.put("roleId", String.join(",", roleIds)); break; } } break; case "entryDate": if (StringUtil.isNotEmpty(value)) { Date date = DateUtil.checkDate(value, "yyyy-MM-dd"); if (date == null) { errInfo.add(columnName + "值不正确"); break; } realMap.put("entryDate", date); } break; case "birthday": if (StringUtil.isNotEmpty(value)) { Date date = DateUtil.checkDate(value, "yyyy-MM-dd"); if (date == null) { errInfo.add(columnName + "值不正确"); break; } realMap.put("birthday", date); } break; case "sortCode": if (StringUtil.isEmpty(value)) { realMap.put("sortCode", 0); break; } Long numValue = 0l; try { numValue = Long.parseLong(value); } catch (Exception e) { errInfo.add(columnName + "值不正确"); break; } if (numValue < 0) { errInfo.add(columnName + "值不能小于0"); break; } if (numValue > 1000000) { errInfo.add(columnName + "值不能大于999999"); break; } break; case "enabledMark": if (StringUtil.isEmpty(value)) { errInfo.add(columnName + "不能为空"); break; } if ("启用".equals(value)) { realMap.put("enabledMark", 1); } else if ("禁用".equals(value)) { realMap.put("enabledMark", 0); } else if ("锁定".equals(value)) { realMap.put("enabledMark", 2); } else { errInfo.add("找不到该" + columnName + "值"); } break; default: break; } } if (errInfo.length() == 0) { UserEntity entity = JsonUtil.getJsonToBean(realMap, UserEntity.class); entity.setCreatorTime(new Date()); addList.add(entity); } else { eachMap.put("errorsInfo", errInfo.toString()); failList.add(eachMap); } } } private CheckResult checkOrganizeId(String organizeName, Map allOrgsTreeName) { for (String key : allOrgsTreeName.keySet()) { Object o = allOrgsTreeName.get(key); if (organizeName.equals(o.toString())) { String[] split = key.split(","); return new CheckResult(true, null, split[split.length - 1]); } } return new CheckResult(false, "所属组织不正确", null); } /** * 获取下拉框 * * @return */ private Map getOptionMap() { Map optionMap = new HashMap<>(); //性别 List sexList = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.SEX_TYPE.getDictionaryTypeId()); String[] gender = sexList.stream().map(DictionaryDataEntity::getFullName).toArray(String[]::new); optionMap.put("gender", gender); //职级 List ranksList = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.RANK.getDictionaryTypeId()); String[] ranks = ranksList.stream().map(DictionaryDataEntity::getFullName).toArray(String[]::new); optionMap.put("ranks", ranks); //状态 optionMap.put("enabledMark", new String[]{"启用", "禁用", "锁定"}); //民族 List nationList = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.NATION.getDictionaryTypeId()); String[] nation = nationList.stream().map(DictionaryDataEntity::getFullName).toArray(String[]::new); optionMap.put("nation", nation); //证件类型 List certificatesTypeList = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.CERTIFICATE_TYPE.getDictionaryTypeId()); String[] certificatesType = certificatesTypeList.stream().map(DictionaryDataEntity::getFullName).toArray(String[]::new); optionMap.put("certificatesType", certificatesType); //文化程度 List educationList = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.EDUCATION.getDictionaryTypeId()); String[] education = educationList.stream().map(DictionaryDataEntity::getFullName).toArray(String[]::new); optionMap.put("education", education); return optionMap; } }