| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465 |
- 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<UserService, UserEntity> {
- @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<PageListVO<UserListVO>> getList(UserPagination pagination) {
- List<UserEntity> userList = userService.getList(pagination);
- List<UserListVO> list = new ArrayList<>();
- List<DictionaryDataEntity> dataServiceList4 = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.SEX_TYPE.getDictionaryTypeId());
- Map<String, String> genderMap = dataServiceList4.stream().collect(Collectors.toMap(DictionaryDataEntity::getEnCode, DictionaryDataEntity::getFullName));
- Map<String, String> 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<UserRelationEntity> 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<UserInfoVO> getInfo(@PathVariable("id") String id) throws DataException {
- UserEntity entity = userService.getInfo(id);
- if (entity == null) {
- return ActionResult.fail(MsgCode.FA001.get());
- }
- QueryWrapper<UserRelationEntity> roleQuery = new QueryWrapper<>();
- roleQuery.lambda().eq(UserRelationEntity::getUserId, id);
- roleQuery.lambda().eq(UserRelationEntity::getObjectType, PermissionConst.ROLE);
- List<String> 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<UserRelationEntity> query = new QueryWrapper<>();
- query.lambda().eq(UserRelationEntity::getUserId, id);
- query.lambda().eq(UserRelationEntity::getObjectType, PermissionConst.ORGANIZE);
- List<String> organizeIds = new ArrayList<>();
- userRelationService.list(query).forEach(u -> {
- organizeIds.add(u.getObjectId());
- });
- // 岗位装配
- QueryWrapper<UserRelationEntity> 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<UserRelationEntity> 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<String> 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<String> 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<UserRelationEntity> 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<UserEntity> listByUserIds = userService.getListByUserIds(form.getIds());
- List<String> userIdList = new ArrayList<>();
- if (CollectionUtil.isNotEmpty(listByUserIds)) {
- List<String> 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<UserRelationEntity> 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<String> BatchUpdateState(@RequestBody UserBatchForm form) {
- if (CollectionUtil.isNotEmpty(form.getIds())) {
- List<UserEntity> 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<ListVO<UserAllVO>> getAllUsers(PaginationUser pagination) {
- List<UserEntity> list = userService.getList(pagination, null, false, false, null, null);
- List<UserAllVO> user = JsonUtil.getJsonToList(list, UserAllVO.class);
- ListVO<UserAllVO> vo = new ListVO<>();
- vo.setList(user);
- return ActionResult.success(vo);
- }
- /**
- * IM通讯获取用户接口
- *
- * @param pagination 分页参数
- * @return ignore
- */
- @Operation(summary = "IM通讯获取用户")
- @GetMapping("/ImUser")
- public ActionResult<PageListVO<ImUserListVo>> getAllImUserUsers(Pagination pagination) {
- PageUser pageUser = JsonUtil.getJsonToBean(pagination, PageUser.class);
- List<UserEntity> data = userService.getList(pageUser, true);
- List<ImUserListVo> list = new ArrayList<>();
- Map<String, OrganizeEntity> 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<ListVO<UserSelectorVO>> selector() {
- Map<String, OrganizeEntity> orgMaps = organizeService.getOrgMaps(null, true, null);
- List<OrganizeEntity> organizeData = new ArrayList<>(orgMaps.values());
- List<UserEntity> userData = userService.getList(true);
- List<UserSelectorModel> 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<SumTree<UserSelectorModel>> trees = TreeDotUtils.convertListToTreeDot(treeList);
- List<UserSelectorVO> listvo = JsonUtil.getJsonToList(trees, UserSelectorVO.class);
- List<OrganizeEntity> entities = organizeData.stream().filter(
- t -> "-1".equals(t.getParentId())
- ).collect(Collectors.toList());
- Iterator<UserSelectorVO> iterator = listvo.iterator();
- while (iterator.hasNext()) {
- UserSelectorVO userSelectorVO = iterator.next();
- for (OrganizeEntity entity : entities) {
- if (entity.getId().equals(userSelectorVO.getParentId())) {
- iterator.remove();//使用迭代器的删除方法删除
- }
- }
- }
- ListVO<UserSelectorVO> 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<String> 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<GroupEntity> groupList = groupService.getListByIds(list);
- list = groupList.stream().map(GroupEntity::getId).collect(Collectors.toList());
- }
- if (PermissionConst.ORGANIZE.equals(userConditionModel.getType())) {
- List<OrganizeEntity> orgList = organizeService.getOrgEntityList(list, true);
- list = orgList.stream().map(OrganizeEntity::getId).collect(Collectors.toList());
- }
- if (PermissionConst.ROLE.equals(userConditionModel.getType())) {
- List<RoleEntity> 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<PositionEntity> positionList = positionService.getPosList(list);
- list = positionList.stream().filter(t -> t.getEnabledMark() == 1).map(PositionEntity::getId).collect(Collectors.toList());
- }
- }
- List<String> 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<UserEntity> userName = userService.getUserName(collect, userConditionModel.getPagination());
- List<UserIdListVo> jsonToList = JsonUtil.getJsonToList(userName, UserIdListVo.class);
- Map<String, String> orgIdNameMaps = organizeService.getInfoList();
- jsonToList.forEach(t -> {
- t.setHeadIcon(UploaderUtil.uploaderImg(t.getHeadIcon()));
- t.setFullName(t.getRealName() + "/" + t.getAccount());
- List<UserRelationEntity> listByUserId = userRelationService.getListByUserId(t.getId(), PermissionConst.ORGANIZE);
- List<String> orgId = listByUserId.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList());
- List<OrganizeEntity> 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<UserSelectorVO> jsonToList = new ArrayList<>();
- Map<String, String> orgIdNameMaps = organizeService.getInfoList();
- Map<String, OrganizeEntity> orgMaps = organizeService.getOrgMaps(null, true, null);
- //判断是否搜索关键字
- if (StringUtil.isNotEmpty(pagination.getKeyword())) {
- //通过关键字查询
- PageUser pageUser = JsonUtil.getJsonToBean(pagination, PageUser.class);
- List<UserEntity> 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<UserRelationEntity> 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<OrganizeEntity> collect = new ArrayList<>(orgMaps.values());
- //判断时候传入组织id
- //如果传入组织id,则取出对应的子集
- if (!"0".equals(organizeId)) {
- //通过组织查询部门及人员
- //单个组织
- OrganizeEntity organizeEntity = orgMaps.get(organizeId);
- if (organizeEntity != null) {
- //取出组织下的部门
- List<OrganizeEntity> 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<UserEntity> 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<UserRelationEntity> 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<UserSelectorVO> 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<UserSelectorVO> 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<ListVO<UserByRoleVO>> getListByAuthorize(@PathVariable("organizeId") String organizeId, @RequestBody Page page) {
- List<UserByRoleVO> 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<UserAuthorizeVO> getAuthorize(UserAuthForm param) {
- return ActionResult.success(authPermUtil.getUserAuth(param));
- }
- @Operation(summary = "角色岗位权限列表")
- @GetMapping("/getAllPermission")
- public ActionResult<List<PositionVo>> getAllPermission(@RequestParam(value = "userId", required = false) String userId) {
- if (StringUtil.isEmpty(userId)) {
- userId = UserProvider.getUser().getUserId();
- }
- List<PositionVo> listRes = new ArrayList<>();
- listRes.add(new PositionVo("all", "全部权限"));
- //添加岗位
- List<String> 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<PositionVo> child = new ArrayList<>();
- Map<String, Object> allOrgsTreeName = organizeService.getAllOrgsTreeName();
- List<PositionEntity> 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<String> 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<PositionVo> child = new ArrayList<>();
- List<RoleEntity> 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<List<PositionListVO>> GetPosition(@PathVariable("id") String id) {
- UserEntity entity = userService.getInfo(id);
- List<PositionListVO> list = new ArrayList<>();
- if (entity != null) {
- List<UserRelationEntity> relationList = userRelationService.getListByUserId(id, PermissionConst.POSITION);
- Map<String, Object> allOrgsTreeName = organizeService.getAllOrgsTreeName();
- List<PositionEntity> 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<PageListVO<UserListVO>> SelectorByUserPosId(@PathVariable("id") String id, Pagination pagination) {
- UserEntity entity = userService.getInfo(id);
- PageUser pageUser = JsonUtil.getJsonToBean(pagination, PageUser.class);
- List<UserListVO> list = new ArrayList<>();
- if (entity != null) {
- List<UserRelationEntity> relationList = userRelationService.getListByUserId(id, PermissionConst.POSITION);
- List<String> posIds = relationList.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList());
- List<String> userIds = userRelationService.getListByObjectIdAll(posIds).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
- if (CollectionUtil.isNotEmpty(userIds)) {
- pageUser.setIdList(userIds);
- List<UserEntity> 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<String> posIds = form.getIds();
- List<UserRelationEntity> 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<PositionEntity> posList = positionService.getListByIds(posIds);
- //判断约束 -- 逐一判断,能成功的就添加res
- List<String> res = new ArrayList<>();
- Set<String> huchi = new HashSet<>();
- Set<String> xianjue = new HashSet<>();
- List<String> 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<UserRelationEntity> orgList = userRelationService.getListByUserId(id, PermissionConst.ORGANIZE);
- //移除全部岗位、组织和用户得关系
- List<UserRelationEntity> 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<String> 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<UserRelationEntity> 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<String> 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<String> posIds, List<PositionEntity> posList, List<String> errList1, Set<String> huchi, List<String> res, Set<String> xianjue) {
- for (String positionId : posIds) {
- List<String> errList2 = new ArrayList<>();
- PositionEntity info = posList.stream().filter(t -> t.getId().equals(positionId)).findFirst().orElse(null);
- List<String> 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<String> mutualExclusion = posConModel.getMutualExclusion();
- if (posConModel.getMutualExclusionFlag()) {
- //互斥
- List<String> 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<String> posIds, List<PositionEntity> posList, List<String> errList1, List<String> res) {
- for (String positionId : posIds) {
- List<String> 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<UserEntity> userList = userService.getListByUserIds(form.getUserIds());
- List<String> posIds = form.getIds();
- List<PositionEntity> 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<String> userIds = userList.stream().filter(t -> !Objects.equals(t.getIsAdministrator(), 1)).map(UserEntity::getId).collect(Collectors.toList());
- //再加
- List<String> addUserIds = new ArrayList<>();
- List<String> skipUserIds = new ArrayList<>();
- for (String userId : userIds) {
- List<UserRelationEntity> 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<String> res = new ArrayList<>();
- Set<String> huchi = new HashSet<>();
- Set<String> xianjue = new HashSet<>();
- List<String> 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<UserRelationEntity> 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<UserRelationEntity> 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<String> 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<String, List<UserRelationEntity>> 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<UserRelationEntity> userRelationEntities = collect.get(string);
- List<String> userEntityIds = userRelationEntities.stream().map(UserRelationEntity::getUserId)
- .collect(Collectors.toList());
- List<UserEntity> 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<String> 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<String> 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<String> 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<ListVO<UserIdListVo>> getUserList(@RequestBody UserIdModel userIdModel) {
- List<UserEntity> userName = userService.getUserName(userIdModel.getIds(), true);
- List<UserIdListVo> list = JsonUtil.getJsonToList(userName, UserIdListVo.class);
- List<UserRelationEntity> listByUserIds = userRelationService.getRelationByUserIds(list.stream().map(UserIdListVo::getId).collect(Collectors.toList()));
- Map<String, String> orgIdNameMaps = organizeService.getInfoList();
- for (UserIdListVo entity : list) {
- if (entity == null) {
- break;
- }
- entity.setFullName(entity.getRealName() + "/" + entity.getAccount());
- List<UserRelationEntity> listByUserId = listByUserIds.stream().filter(t -> t.getUserId().equals(entity.getId())).collect(Collectors.toList());
- StringBuilder stringBuilder = new StringBuilder();
- List<OrganizeEntity> 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<UserIdListVo> 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<ListVO<BaseInfoVo>> getSelectedList(@RequestBody UserIdModel userIdModel) {
- List<String> ids = userIdModel.getIds();
- List<BaseInfoVo> list = userService.selectedByIds(ids);
- ListVO<BaseInfoVo> 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<PageListVO<BaseInfoVo>> getSelectedUserList(@RequestBody UserIdModelByPage userIdModel) {
- List<BaseInfoVo> 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<List<UserIdListVo>> 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<String, OrganizeEntity> orgMaps = organizeService.getOrgMaps(null, true, null);
- List<UserEntity> list = userService.getListByOrganizeId(departmentId, page.getKeyword());
- List<UserIdListVo> jsonToList = JsonUtil.getJsonToList(list, UserIdListVo.class);
- Map<String, String> orgIdNameMaps = organizeService.getInfoList();
- List<UserRelationEntity> listByObjectType = userRelationService.getListByObjectType(PermissionConst.ORGANIZE);
- jsonToList.forEach(t -> {
- t.setRealName(t.getRealName() + "/" + t.getAccount());
- t.setFullName(t.getRealName());
- List<String> 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<String> userId = new ArrayList<>();
- List<Integer> ruleList = ImmutableList.of(ExtraRuleEnum.organize.getCode(), ExtraRuleEnum.position.getCode(),
- ExtraRuleEnum.department.getCode());
- boolean isDepartmeng = false;
- if (ruleList.contains(type)) {
- List<String> positionList = new ArrayList<>();
- List<String> organizeList = new ArrayList<>();
- List<UserRelationEntity> 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<String> 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<String> orgList = organizeService.getDepartmentAll(organizeId).stream().map(OrganizeEntity::getId).collect(Collectors.toList());
- List<String> 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<UserEntity> list = isDepartmeng ? userService.getUserPage(pagination) : userService.getUserName(userId, pagination);
- List<UserIdListVo> jsonToList = JsonUtil.getJsonToList(list, UserIdListVo.class);
- if (!jsonToList.isEmpty()) {
- List<String> userIdList = list.stream().map(UserEntity::getId).collect(Collectors.toList());
- List<UserRelationEntity> userRelationList = userRelationService.getRelationByUserIds(userIdList);
- Map<String, List<UserRelationEntity>> 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<UserRelationEntity> 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<String> organizeIdTree = new ArrayList<>(Arrays.asList(organize.getOrganizeIdTree().split(",")));
- List<OrganizeEntity> 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<String> positionIdTree = new ArrayList<>(Arrays.asList(position.getPositionIdTree().split(",")));
- List<PositionEntity> 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<List<UserByRoleVO>> getUsersByPositionId(UsersByPositionModel page) {
- List<UserByRoleVO> 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<String, String> orgIdNameMaps = organizeService.getInfoList();
- // 组装组织名称
- String orgName = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity.getOrganizeIdTree(), "/");
- vo.setFullName(orgName);
- // 赋予子集
- List<UserByRoleVO> userByRoleVOS = new ArrayList<>(16);
- List<UserEntity> 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<List<UserIdListVo>> getSubordinates(@RequestBody Page page) {
- Map<String, OrganizeEntity> orgMaps = organizeService.getOrgMaps(null, false, null);
- List<UserEntity> list = userService.getListByManagerId(UserProvider.getUser().getUserId(), page.getKeyword());
- List<UserIdListVo> jsonToList = JsonUtil.getJsonToList(list, UserIdListVo.class);
- Map<String, String> orgIdNameMaps = organizeService.getInfoList();
- jsonToList.forEach(t -> {
- t.setRealName(t.getRealName() + "/" + t.getAccount());
- t.setFullName(t.getRealName());
- List<UserRelationEntity> 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<UserEntity> 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<UserEntity> 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<String, Object> dataMap = new HashMap<String, Object>();
- 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<WorkHandoverVo> getWorkByUser(@RequestParam("fromId") String fromId) {
- FlowWorkListVO flowWorkListVO = templateApi.flowWork(fromId);
- if (flowWorkListVO == null) {
- log.error("用户:" + fromId + ",待办事宜及负责流程获取失败");
- flowWorkListVO = new FlowWorkListVO();
- }
- List<SystemEntity> 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<FlowWorkModel> 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<String> 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<String> tokenList = new ArrayList<>();
- List<String> 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<DownloadVO> TemplateDownload() {
- UserColumnMap columnMap = new UserColumnMap();
- String excelName = columnMap.getExcelName();
- Map<String, String> keyMap = columnMap.getColumnByType(0);
- List<ExcelColumnAttr> models = columnMap.getFieldsModel(false);
- List<Map<String, Object>> list = columnMap.getDefaultList();
- Map<String, String[]> 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<Object> Uploader() {
- return ExcelTool.uploader();
- }
- @Operation(summary = "导入预览")
- @SaCheckPermission("permission.user")
- @GetMapping("/ImportPreview")
- public ActionResult<Map<String, Object>> ImportPreview(String fileName) throws Exception {
- // 导入字段
- UserColumnMap columnMap = new UserColumnMap();
- Map<String, String> keyMap = columnMap.getColumnByType(0);
- Map<String, Object> headAndDataMap = ExcelTool.importPreview(FileTypeConstant.TEMPORARY, fileName, keyMap);
- return ActionResult.success(headAndDataMap);
- }
- /**
- * 导出异常报告
- *
- * @return
- */
- @Operation(summary = "导出异常报告")
- @SaCheckPermission("permission.user")
- @PostMapping("/ExportExceptionData")
- public ActionResult<DownloadVO> ExportExceptionData(@RequestBody ExcelImportForm visualImportModel) {
- List<Map<String, Object>> dataList = visualImportModel.getList();
- UserColumnMap columnMap = new UserColumnMap();
- String excelName = columnMap.getExcelName();
- Map<String, String> keyMap = columnMap.getColumnByType(0);
- List<ExcelColumnAttr> 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<ExcelImportVO> ImportData(@RequestBody ExcelImportForm visualImportModel) throws Exception {
- List<Map<String, Object>> listData = new ArrayList<>();
- List<Map<String, Object>> 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<String, Object> data = (Map<String, Object>) result.getData();
- listData = (List<Map<String, Object>>) data.get("dataRow");
- headerRow = (List<Map<String, Object>>) data.get("headerRow");
- }
- } else {
- listData = visualImportModel.getList();
- }
- List<UserEntity> addList = new ArrayList<>();
- List<Map<String, Object>> 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<UserEntity> list = userService.getList(pagination, null, false, false, null, null);
- Map<String, String> roleIdAndNameMap = roleService.getList(false, PermissionConst.USER, null)
- .stream().collect(Collectors.toMap(RoleEntity::getId, t -> t.getFullName() + "/" + t.getEnCode()));
- Map<Object, String> posIdAndName = positionService.getPosEncodeAndName(true).entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
- Map<Object, String> groupEncodeMap = groupService.getGroupEncodeMap(true).entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
- Map<String, String> orgMap = organizeService.getAllOrgsTreeName(true);
- Map<Object, String> userNameMap = userService.getUserNameAndIdMap(true).entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
- //性别
- Map<String, String> sexMap = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.SEX_TYPE.getDictionaryTypeId())
- .stream().collect(Collectors.toMap(DictionaryDataEntity::getEnCode, DictionaryDataEntity::getFullName));
- //职级
- Map<String, String> ranksMap = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.RANK.getDictionaryTypeId())
- .stream().collect(Collectors.toMap(DictionaryDataEntity::getId, DictionaryDataEntity::getFullName));
- //民族
- Map<String, String> nationMap = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.NATION.getDictionaryTypeId())
- .stream().collect(Collectors.toMap(DictionaryDataEntity::getId, DictionaryDataEntity::getFullName));
- //证件类型
- Map<String, String> certificatesTypeMap = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.CERTIFICATE_TYPE.getDictionaryTypeId())
- .stream().collect(Collectors.toMap(DictionaryDataEntity::getId, DictionaryDataEntity::getFullName));
- //文化程度
- Map<String, String> educationMap = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.EDUCATION.getDictionaryTypeId())
- .stream().collect(Collectors.toMap(DictionaryDataEntity::getId, DictionaryDataEntity::getFullName));
- List<RoleRelationEntity> roleRelationList = roleRelationService.getListByRoleId("", PermissionConst.USER);
- List<UserRelationEntity> userRelationList = userRelationService.getListByObjectType(PermissionConst.POSITION);
- List<Map<String, Object>> realList = new ArrayList<>();
- for (UserEntity entity : list) {
- entity.setHeadIcon(UploaderUtil.uploaderImg(entity.getHeadIcon()));
- //获取角色
- List<RoleRelationEntity> userRoleRelation = roleRelationList.stream().filter(t -> t.getObjectId().equals(entity.getId())).collect(Collectors.toList());
- List<String> 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<UserRelationEntity> userPosRelation = userRelationList.stream().filter(t -> t.getUserId().equals(entity.getId())).collect(Collectors.toList());
- List<String> 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<String, Object> 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<ExcelColumnAttr> models = columnMap.getFieldsModel(false);
- Map<String, String> 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<Map<String, Object>> listData, List<UserEntity> addList, List<Map<String, Object>> failList) {
- UserColumnMap columnMap = new UserColumnMap();
- Map<String, String> keyMap = columnMap.getColumnByType(0);
- List<DictionaryDataEntity> sexList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.SEX_TYPE.getDictionaryTypeId());
- Map<String, String> genderMap = sexList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getEnCode));
- List<DictionaryDataEntity> rankList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.RANK.getDictionaryTypeId());
- Map<String, String> ranksMap = rankList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getId));
- List<DictionaryDataEntity> nationList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.NATION.getDictionaryTypeId());
- Map<String, String> nationMap = nationList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getId));
- List<DictionaryDataEntity> certificateList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.CERTIFICATE_TYPE.getDictionaryTypeId());
- Map<String, String> certificateMap = certificateList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getId));
- List<DictionaryDataEntity> educationList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.EDUCATION.getDictionaryTypeId());
- Map<String, String> educationMap = educationList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getId));
- Map<String, Object> allOrgsTreeName = organizeService.getAllOrgsTreeName();
- Map<String, Object> userNameMap = userService.getUserNameAndIdMap();
- List<PositionEntity> allPos = positionService.getList(true);
- Map<String, Object> posNameMap = positionService.getPosEncodeAndName(true);
- List<RoleEntity> allUserRole = roleService.getList(true, PermissionConst.USER, null);
- Map<String, String> roleMap = allUserRole.stream().collect(Collectors.toMap(t -> t.getFullName(), RoleEntity::getId));
- //所有岗位的用户列表
- List<UserRelationEntity> posAllUser = userRelationService.getListByObjectType(PermissionConst.POSITION);
- //所有用户角色的用户列表
- List<RoleRelationEntity> roleAllUser = roleRelationService.getListByRoleId("", PermissionConst.USER);
- //角色用户数量
- Map<String, Integer> roleIdUserNum = new HashMap<>();
- for (int i = 0, len = listData.size(); i < len; i++) {
- Map<String, Object> eachMap = listData.get(i);
- Map<String, Object> 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<String> posIds = new ArrayList<>();
- List<String> posErrList = new ArrayList<>();
- List<String> 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<UserRelationEntity> thisPosUsers = posAllUser.stream().filter(t -> t.getObjectId().equals(item)).collect(Collectors.toList());
- //表格里的岗位用户数
- List<UserEntity> 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<String> 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<String> roleIds = new ArrayList<>();
- List<String> roleErrList = new ArrayList<>();
- List<String> 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<RoleRelationEntity> thisRoleUsers = roleAllUser.stream().filter(t -> t.getRoleId().equals(item)).collect(Collectors.toList());
- //表格里的岗位用户数
- List<UserEntity> 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<String, Object> 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<String, String[]> getOptionMap() {
- Map<String, String[]> optionMap = new HashMap<>();
- //性别
- List<DictionaryDataEntity> sexList = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.SEX_TYPE.getDictionaryTypeId());
- String[] gender = sexList.stream().map(DictionaryDataEntity::getFullName).toArray(String[]::new);
- optionMap.put("gender", gender);
- //职级
- List<DictionaryDataEntity> 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<DictionaryDataEntity> nationList = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.NATION.getDictionaryTypeId());
- String[] nation = nationList.stream().map(DictionaryDataEntity::getFullName).toArray(String[]::new);
- optionMap.put("nation", nation);
- //证件类型
- List<DictionaryDataEntity> certificatesTypeList = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.CERTIFICATE_TYPE.getDictionaryTypeId());
- String[] certificatesType = certificatesTypeList.stream().map(DictionaryDataEntity::getFullName).toArray(String[]::new);
- optionMap.put("certificatesType", certificatesType);
- //文化程度
- List<DictionaryDataEntity> educationList = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.EDUCATION.getDictionaryTypeId());
- String[] education = educationList.stream().map(DictionaryDataEntity::getFullName).toArray(String[]::new);
- optionMap.put("education", education);
- return optionMap;
- }
- }
|