UserManagementFacade.java 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. package com.lantone.security.facade;
  2. import cn.hutool.crypto.digest.BCrypt;
  3. import com.alibaba.fastjson.JSON;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  6. import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
  7. import com.baomidou.mybatisplus.core.metadata.IPage;
  8. import com.google.common.collect.Lists;
  9. import com.lantone.common.api.CommonResult;
  10. import com.lantone.common.constant.AuthConstant;
  11. import com.lantone.common.domain.UserDto;
  12. import com.lantone.common.dto.JwtStore;
  13. import com.lantone.common.dto.LoginLogDTO;
  14. import com.lantone.common.dto.SendToTopicDTO;
  15. import com.lantone.common.enums.DataAuthDataTypeEnum;
  16. import com.lantone.common.enums.IsDeleteEnum;
  17. import com.lantone.common.enums.StatusEnum;
  18. import com.lantone.common.exception.Asserts;
  19. import com.lantone.common.service.DictSetsService;
  20. import com.lantone.common.service.SysTokenService;
  21. import com.lantone.common.util.DateUtil;
  22. import com.lantone.common.util.EntityUtil;
  23. import com.lantone.common.util.HttpUtils;
  24. import com.lantone.common.util.ListUtil;
  25. import com.lantone.common.util.StringUtil;
  26. import com.lantone.common.util.SysUserUtils;
  27. import com.lantone.security.client.AuthService;
  28. import com.lantone.security.client.MessageService;
  29. import com.lantone.security.dto.GetDeptTreeDTO;
  30. import com.lantone.security.dto.GetHospitalTreeDTO;
  31. import com.lantone.security.dto.GetUserDTO;
  32. import com.lantone.security.dto.GetUserHospitalDeptDTO;
  33. import com.lantone.security.dto.GetUserHospitalsDTO;
  34. import com.lantone.security.dto.GetUserPageDTO;
  35. import com.lantone.security.dto.SoftwareDTO;
  36. import com.lantone.security.dto.UserInfoDTO;
  37. import com.lantone.security.dto.UserRoleDTO;
  38. import com.lantone.security.dto.UserSoftwareHospitalDTO;
  39. import com.lantone.security.entity.Dept;
  40. import com.lantone.security.entity.DeptUser;
  41. import com.lantone.security.entity.Doctor;
  42. import com.lantone.security.entity.Hospital;
  43. import com.lantone.security.entity.HospitalUser;
  44. import com.lantone.security.entity.MedoupDoctor;
  45. import com.lantone.security.entity.Role;
  46. import com.lantone.security.entity.User;
  47. import com.lantone.security.entity.UserRole;
  48. import com.lantone.security.enums.DictionaryEnum;
  49. import com.lantone.security.enums.HospitalTypeEnum;
  50. import com.lantone.security.enums.RelationEnum;
  51. import com.lantone.security.enums.ReturnTypeEnum;
  52. import com.lantone.security.facade.base.DeptFacade;
  53. import com.lantone.security.facade.base.DeptUserFacade;
  54. import com.lantone.security.facade.base.DoctorFacade;
  55. import com.lantone.security.facade.base.HospitalFacade;
  56. import com.lantone.security.facade.base.HospitalUserFacade;
  57. import com.lantone.security.facade.base.MedoupDoctorFacade;
  58. import com.lantone.security.facade.base.RoleFacade;
  59. import com.lantone.security.facade.base.UserFacade;
  60. import com.lantone.security.facade.base.UserRoleFacade;
  61. import com.lantone.security.vo.AddHospitalTreeVO;
  62. import com.lantone.security.vo.AddUserVO;
  63. import com.lantone.security.vo.GetUserPageVO;
  64. import com.lantone.security.vo.LoginVO;
  65. import com.lantone.security.vo.UpdateUserVO;
  66. import eu.bitwalker.useragentutils.UserAgent;
  67. import org.springframework.beans.BeanUtils;
  68. import org.springframework.beans.factory.annotation.Autowired;
  69. import org.springframework.stereotype.Component;
  70. import java.util.ArrayList;
  71. import java.util.Date;
  72. import java.util.HashMap;
  73. import java.util.HashSet;
  74. import java.util.List;
  75. import java.util.Map;
  76. import java.util.Set;
  77. import java.util.concurrent.atomic.AtomicInteger;
  78. import java.util.stream.Collectors;
  79. /**
  80. * @Description: 用户管理-业务处理类
  81. * @author: rengb
  82. * @time: 2021/7/20 12:39
  83. */
  84. @Component
  85. public class UserManagementFacade {
  86. @Autowired
  87. private AuthService authService;
  88. @Autowired
  89. private HospitalFacade hospitalFacade;
  90. @Autowired
  91. private HospitalUserFacade hospitalUserFacade;
  92. @Autowired
  93. private DeptFacade deptFacade;
  94. @Autowired
  95. private UserFacade userFacade;
  96. @Autowired
  97. private DeptUserFacade userDeptFacade;
  98. @Autowired
  99. private UserRoleFacade userRoleFacade;
  100. @Autowired
  101. private RoleFacade roleFacade;
  102. @Autowired
  103. private MedoupDoctorFacade medoupDoctorFacade;
  104. @Autowired
  105. private DoctorFacade doctorfacade;
  106. @Autowired
  107. private DictSetsService dictSetsService;
  108. @Autowired
  109. private MessageService messageService;
  110. @Autowired
  111. private SysTokenService sysTokenService;
  112. public CommonResult login(LoginVO loginVO) {
  113. Map<String, String> params = new HashMap<>();
  114. params.put("client_id", AuthConstant.SECURITY_CENTER_CLIENT_ID);
  115. params.put("client_secret", "lantone_20210723");
  116. params.put("grant_type", "password");
  117. params.put("username", loginVO.getUsername());
  118. params.put("password", loginVO.getPassword());
  119. CommonResult restResult = authService.getAccessToken(params);
  120. userLoginCheck(restResult);
  121. sendLogRecordMessage(restResult);
  122. return restResult;
  123. }
  124. private void userLoginCheck(CommonResult restResult) {
  125. if (restResult.getData() != null) {
  126. Map<String, Object> map = JSONObject.parseObject(JSON.toJSONString(restResult.getData()));
  127. if (map.containsKey(AuthConstant.ASSESS_TOKEN) && null != map.get(AuthConstant.ASSESS_TOKEN)) {
  128. String userId = sysTokenService.getUserIDByToken(map.get(AuthConstant.ASSESS_TOKEN).toString());
  129. JwtStore oldJwt = sysTokenService.getToken(userId);
  130. String ip = HttpUtils.getIpAddress();
  131. //异地登录
  132. if (StringUtil.isNotBlank(ip)
  133. && oldJwt != null
  134. && !ip.equals(oldJwt.getIp())) {
  135. //推送消息
  136. List<SendToTopicDTO> sendToTopics = new ArrayList<>();
  137. SendToTopicDTO sendToTopicDTO = new SendToTopicDTO();
  138. sendToTopicDTO.setMessage("温誓提示,您的账号在其它地方已登录您将被迫下线!");
  139. sendToTopicDTO.setType("login");
  140. sendToTopicDTO.setTopic(userId);
  141. sendToTopics.add(sendToTopicDTO);
  142. messageService.sendToTopic(sendToTopics);
  143. }
  144. JwtStore jwtStore = new JwtStore();
  145. jwtStore.setAccessToken(map.get(AuthConstant.ASSESS_TOKEN).toString());
  146. jwtStore.setRefreshToken(map.get(AuthConstant.REFRESH_TOKEN).toString());
  147. jwtStore.setIp(HttpUtils.getIpAddress());
  148. sysTokenService.createToken(jwtStore);
  149. }
  150. }
  151. }
  152. public CommonResult<UserDto> loadUserByUsername(String username) {
  153. QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
  154. userQueryWrapper.eq("username", username);
  155. userQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey());
  156. List<User> userList = userFacade.list(userQueryWrapper);
  157. if (userList.size() == 0) {
  158. return CommonResult.failed("用户不存在!");
  159. }
  160. if (userList.size() > 1) {
  161. return CommonResult.failed("当前账号异常!");
  162. }
  163. UserDto userDTO = new UserDto();
  164. User user = userList.get(0);
  165. QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
  166. userRoleQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey());
  167. userRoleQueryWrapper.eq("user_id", user.getId());
  168. List<Long> roleIdList = userRoleFacade.list(userRoleQueryWrapper)
  169. .stream()
  170. .map(i -> i.getRoleId())
  171. .collect(Collectors.toList());
  172. QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
  173. roleQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey());
  174. roleQueryWrapper.eq("status", StatusEnum.Enable.getKey());
  175. roleQueryWrapper.in(ListUtil.isNotEmpty(roleIdList), "id", roleIdList);
  176. List<String> roleIdNames = roleFacade.list(roleQueryWrapper).stream().map(i -> i.getId() + "_" + i.getName()).collect(Collectors.toList());
  177. BeanUtils.copyProperties(user, userDTO);
  178. userDTO.setUserName(user.getUsername());
  179. userDTO.setRoles(roleIdNames);
  180. return CommonResult.success(userDTO);
  181. }
  182. /**
  183. * @param addUserVO
  184. * @Description添加用户
  185. * @Return boolean
  186. */
  187. public boolean addUser(AddUserVO addUserVO) {
  188. //1.新增用户基本信息
  189. User user = new User();
  190. BeanUtils.copyProperties(addUserVO, user);
  191. user.setCreator(SysUserUtils.getCurrentPrincipleId() + "");
  192. user.setGmtCreate(DateUtil.now());
  193. user.setPassword(BCrypt.hashpw(user.getPassword()));
  194. //1.1校验用户
  195. boolean deptFlag = false;
  196. if (ListUtil.isNotEmpty(addUserVO.getAddHospitalTreeVO().getDepts())) {
  197. deptFlag = true;
  198. }
  199. checkUser(user, deptFlag, addUserVO.getAddHospitalTreeVO().getHospitals(), addUserVO.getRoles());
  200. try {
  201. if (userFacade.save(user)) {
  202. //2.插入用户所属组织
  203. return saveUserHospital(addUserVO.getAddHospitalTreeVO(), user.getId(), addUserVO.getRoles());
  204. } else {
  205. Asserts.fail("用户添加失败");
  206. }
  207. } catch (Exception e) {
  208. Asserts.fail("用户添加失败");
  209. }
  210. return false;
  211. }
  212. /**
  213. * @param user
  214. * @param hospitals 插入用户组织id
  215. * @param roles 插入用户角色id
  216. * @Description用户校验
  217. * @Return void
  218. */
  219. private void checkUser(User user, boolean deptFlag, List<Long> hospitals, List<Long> roles) {
  220. //1.当前登录用户、组织是否还存在、能用
  221. loginCheck();
  222. //2.当前用户是否已存在
  223. //添加时判断
  224. List<User> users = userFacade.list(new QueryWrapper<User>()
  225. .eq("username", user.getUsername()));
  226. if (user.getId() == null) {
  227. if (ListUtil.isNotEmpty(users)) {
  228. Asserts.fail("该用户已存在,请更换用户名");
  229. }
  230. //修改时判断
  231. } else {
  232. if (ListUtil.isNotEmpty(users)) {
  233. users.stream().forEach(user1 -> {
  234. if (!user.getId().equals(user1.getId())) {
  235. Asserts.fail("该用户已存在,请更换用户名");
  236. }
  237. });
  238. }
  239. }
  240. //3.校验插入用户所属组织是否正常
  241. checkHospitals(hospitals);
  242. //4.校验插入用户角色是否正常
  243. // checkRoles(roles);(目前角色校验有问题通过id查不到角色)
  244. //5.用户如果没有医疗组、科室 绑定角色不能选择本医疗组、全部科室除本科室外、本科室数据权限角色
  245. //科室
  246. userDeptCheck(roles, deptFlag);
  247. //医疗组(无医生信息,就不会有医疗组;有医生信息无医疗组)
  248. boolean groupFlag = false;
  249. if (StringUtil.isEmpty(user.getJobNo())) {
  250. groupFlag = true;
  251. } else {
  252. List<Doctor> doctors = doctorfacade.list(new QueryWrapper<Doctor>()
  253. .eq("code", user.getJobNo())
  254. .eq("is_deleted", IsDeleteEnum.N.getKey()));
  255. if (ListUtil.isNotEmpty(doctors)) {
  256. List<MedoupDoctor> medoupDoctors = medoupDoctorFacade.list(new QueryWrapper<MedoupDoctor>()
  257. .in("dcotor_id", doctors.stream().map(Doctor::getId).collect(Collectors.toList()))
  258. .eq("is_deleted", IsDeleteEnum.N.getKey()));
  259. if (ListUtil.isEmpty(medoupDoctors)) {
  260. groupFlag = true;
  261. }
  262. }
  263. }
  264. if (!groupFlag) {
  265. usermedoupCheck();
  266. }
  267. }
  268. /**
  269. * @param
  270. * @Description医疗组校验
  271. * @Return void
  272. */
  273. private void usermedoupCheck() {
  274. //获取当前用户的角色
  275. List<Long> dataTypes = new ArrayList<>();
  276. dataTypes.add(DataAuthDataTypeEnum.SELF_MEDOUP.getKey() * 1l);
  277. List<UserRoleDTO> checkRoles = roleFacade.getBaseMapper()
  278. .getDataAuthRole(SysUserUtils.getCurrentPrincipleId(), null, dataTypes);
  279. StringBuffer errStr = new StringBuffer();
  280. if (ListUtil.isNotEmpty(checkRoles)) {
  281. checkRoles.stream().forEach(userRoleDTO -> {
  282. errStr.append(userRoleDTO.getRoleName() + ";");
  283. });
  284. Asserts.fail(errStr.toString() + "角色需要用户填写医生工号并且该医生存在医疗组信息");
  285. }
  286. }
  287. /**
  288. * @param roles
  289. * @Description校验用户如果没有科室信息时,是否分配科室数据权限相关的角色
  290. * @Return void
  291. */
  292. private void userDeptCheck(List<Long> roles, boolean deptFlag) {
  293. //获取当前用户的角色
  294. List<Long> dataTypes = new ArrayList<>();
  295. dataTypes.add(DataAuthDataTypeEnum.ALL_DEPT_NOT_SELF.getKey() * 1l);
  296. dataTypes.add(DataAuthDataTypeEnum.ALL_SELF_DEPT.getKey() * 1l);
  297. List<UserRoleDTO> checkRoles = roleFacade.getBaseMapper()
  298. .getDataAuthRole(SysUserUtils.getCurrentPrincipleId(), roles, dataTypes);
  299. StringBuffer errStr = new StringBuffer();
  300. //角色需要用户包含科室信息
  301. if (ListUtil.isNotEmpty(checkRoles)) {
  302. if (!deptFlag) {
  303. checkRoles.stream().forEach(userRoleDTO -> {
  304. errStr.append(userRoleDTO.getRoleName() + ";");
  305. });
  306. }
  307. if (StringUtil.isNotEmpty(errStr.toString())) {
  308. Asserts.fail(errStr.toString() + "角色需要用户具备科室信息");
  309. }
  310. }
  311. }
  312. /**
  313. * 修改密码
  314. *
  315. * @param password 原密码
  316. * @param modifyPassword 新密码
  317. * @return 修改密码是否成功
  318. */
  319. public Boolean modifyPassword(String password, String modifyPassword) {
  320. //使用MD5对原密码和新密码进行加密
  321. String MD5Password = BCrypt.hashpw(password);
  322. String MD5ModifyPassword = BCrypt.hashpw(modifyPassword);
  323. //对传入的密码进行格式验证
  324. Long hospitalID = SysUserUtils.getCurrentHospitalId();
  325. Boolean regularBoolean = passwordRegular(modifyPassword, hospitalID + "");
  326. if (!regularBoolean) {
  327. Asserts.fail("请输入正确格式的新密码");
  328. }
  329. String userId = SysUserUtils.getCurrentPrincipleId() + "";
  330. User user = userFacade.getOne(new QueryWrapper<User>()
  331. .eq("is_deleted", IsDeleteEnum.N.getKey())
  332. .eq("status", StatusEnum.Enable.getKey())
  333. .eq("id", userId), false);
  334. if (null == user) {
  335. Asserts.fail("用户不存在");
  336. }
  337. if (!BCrypt.checkpw(password, user.getPassword())) {
  338. Asserts.fail("原密码错误");
  339. }
  340. if (password.equals(modifyPassword)) {
  341. Asserts.fail("原密码和新密码不能相同");
  342. }
  343. user.setPassword(MD5ModifyPassword);
  344. user.setGmtModified(DateUtil.now());
  345. user.setModifier(userId);
  346. return userFacade.updateById(user);
  347. }
  348. /**
  349. * 未加密密文正则表达式 至少8个字符,1个大写字母,1个小写字母,1个数字和1个特殊字符:
  350. *
  351. * @param password
  352. * @return
  353. */
  354. public Boolean passwordRegular(String password, String hospitalId) {
  355. boolean check = true;
  356. Map<String, Map<String, String>> dictionaryWithKey = dictSetsService.getDicMap(ReturnTypeEnum.INTERFACE.getKey(),
  357. Lists.newArrayList(DictionaryEnum.PASSWORD.getKey() + ""));
  358. if (dictionaryWithKey != null) {
  359. Map<String, String> stringStringMap = dictionaryWithKey.get(DictionaryEnum.PASSWORD.getKey() + "");
  360. if (stringStringMap != null) {
  361. String regular = stringStringMap.get("check");
  362. if (StringUtil.isNotEmpty(regular)) {
  363. check = password.matches(regular);
  364. }
  365. }
  366. }
  367. return check;
  368. }
  369. /**
  370. * @param roles
  371. * @Description插入角色校验
  372. * @Return void
  373. */
  374. private void checkRoles(List<Long> roles) {
  375. if (ListUtil.isNotEmpty(roles)) {
  376. if (roles.size() != roleFacade.getBaseMapper().getCount(roles, StatusEnum.Enable.getKey(), IsDeleteEnum.N.getKey())) {
  377. Asserts.fail("插入用户角色列表有改动,请刷新页面重新操作");
  378. }
  379. }
  380. }
  381. /**
  382. * @param hospitals
  383. * @Description插入组织校验
  384. * @Return void
  385. */
  386. private void checkHospitals(List<Long> hospitals) {
  387. if (ListUtil.isNotEmpty(hospitals)) {
  388. if (hospitals.size() != hospitalFacade.list(new QueryWrapper<Hospital>()
  389. .in("id", hospitals)
  390. .eq("status", StatusEnum.Enable.getKey())
  391. .eq("is_deleted", IsDeleteEnum.N.getKey())).size()) {
  392. Asserts.fail("插入用户所属组织有改动,请刷新页面重新操作");
  393. }
  394. }
  395. }
  396. /**
  397. * @param
  398. * @Description操作用户校验
  399. * @Return void
  400. */
  401. private void loginCheck() {
  402. if (hospitalFacade.list(new QueryWrapper<Hospital>()
  403. .eq("id", SysUserUtils.getCurrentHospitalId())
  404. .eq("status", StatusEnum.Enable.getKey())
  405. .eq("is_deleted", IsDeleteEnum.N.getKey())).size() <= 0) {
  406. Asserts.fail("操作用户所属组织已被禁用或删除");
  407. }
  408. if (userFacade.list(new QueryWrapper<User>()
  409. .eq("id", SysUserUtils.getCurrentPrincipleId())
  410. .eq("status", StatusEnum.Enable.getKey())
  411. .eq("is_deleted", IsDeleteEnum.N.getKey())).size() <= 0) {
  412. Asserts.fail("该账号暂未开通或已被禁用,请联系管理员~");
  413. }
  414. }
  415. /**
  416. * @param addHospitalTreeVO
  417. * @param userId
  418. * @Description保存用户关联的医院、科室
  419. * @Return boolean
  420. */
  421. private boolean saveUserHospital(AddHospitalTreeVO addHospitalTreeVO, Long userId, List<Long> roles) {
  422. if (ListUtil.isEmpty(addHospitalTreeVO.getDepts()) && ListUtil.isEmpty(addHospitalTreeVO.getHospitals())) {
  423. Asserts.fail("用户关联的医院或科室都为空");
  424. }
  425. //如果选择科室没有添加科室对应的医院
  426. if (ListUtil.isNotEmpty(addHospitalTreeVO.getDepts())) {
  427. addHospitalTreeVO.getHospitals().addAll(deptFacade.list(new QueryWrapper<Dept>()
  428. .in("id", addHospitalTreeVO.getDepts())
  429. .eq("is_deleted", IsDeleteEnum.N.getKey())
  430. .eq("status", StatusEnum.Enable.getKey())).stream().map(Dept::getHospitalId).collect(Collectors.toList()));
  431. //去重
  432. Set<Long> hospitalSet = new HashSet<>(addHospitalTreeVO.getHospitals());
  433. List<Long> hospitals = new ArrayList<>(hospitalSet);
  434. addHospitalTreeVO.setHospitals(hospitals);
  435. }
  436. //插入用户和科室的关系(没有科室信息默认为全院)
  437. if (ListUtil.isNotEmpty(addHospitalTreeVO.getDepts())) {
  438. addHospitalTreeVO.getDepts().stream().forEach(deptID -> {
  439. DeptUser userDept = new DeptUser();
  440. userDept.setDeptId(deptID);
  441. userDept.setUserId(userId);
  442. userDeptFacade.save(userDept);
  443. });
  444. }
  445. //插入用户和医院的关系
  446. if (ListUtil.isNotEmpty(addHospitalTreeVO.getHospitals())) {
  447. addHospitalTreeVO.getHospitals().stream().forEach(hospitalId -> {
  448. HospitalUser hospitalUser = new HospitalUser();
  449. hospitalUser.setUserId(userId);
  450. hospitalUser.setHospitalId(hospitalId);
  451. hospitalUserFacade.save(hospitalUser);
  452. });
  453. }
  454. //插入用户和角色的关系
  455. return saveUserRole(userId, roles);
  456. }
  457. /**
  458. * @param userId
  459. * @param roles
  460. * @Description插入用户和角色的关系
  461. * @Return boolean
  462. */
  463. private boolean saveUserRole(Long userId, List<Long> roles) {
  464. if (ListUtil.isNotEmpty(roles)) {
  465. roles.stream().forEach(roleId -> {
  466. UserRole userRole = new UserRole();
  467. userRole.setRoleId(roleId);
  468. userRole.setUserId(userId);
  469. userRoleFacade.save(userRole);
  470. });
  471. return true;
  472. }
  473. return false;
  474. }
  475. /**
  476. * @param
  477. * @Description获取当前用户的组织机构树
  478. * @Return java.util.List<com.lantone.security.dto.GetHospitalTreeDTO>
  479. */
  480. public List<GetHospitalTreeDTO> getLoginUserHospitalTree() {
  481. Hospital hospital = hospitalFacade.getById(SysUserUtils.getCurrentHospitalId());
  482. if (hospital == null) {
  483. Asserts.fail("登录用户组织不存在,请联系管理员~");
  484. }
  485. //获取当前医院的树状结构
  486. List<GetHospitalTreeDTO> hospitalTrees = hospitalFacade.getBaseMapper()
  487. .getHospitalTreeInfo(SysUserUtils.getCurrentHospitalId(), StatusEnum.Enable.getKey());
  488. //根据parentid分组
  489. Map<Long, List<GetHospitalTreeDTO>> hospitalMap = EntityUtil.makeEntityListMap(hospitalTrees, "parentId");
  490. //深度遍历拼装结果
  491. List<GetHospitalTreeDTO> hospitalTree = hospitalMap.get(hospital.getParentId());
  492. for (GetHospitalTreeDTO getHospitalTreeDTO : hospitalTree) {
  493. //真实医院添加科室信息
  494. if (HospitalTypeEnum.SINGLE_HOSPITAL.getKey() == Integer.parseInt(getHospitalTreeDTO.getType())) {
  495. getHospitalTreeDTO.setDepts(deptFacade.getBaseMapper().getDeptInfo(getHospitalTreeDTO.getHospitalId()));
  496. }
  497. getSonHospital(getHospitalTreeDTO, hospitalMap);
  498. }
  499. return hospitalTree;
  500. }
  501. /**
  502. * @param updateUserVO
  503. * @Description修改用户
  504. * @Return boolean
  505. */
  506. public boolean updateUser(UpdateUserVO updateUserVO) {
  507. //1.删除该用户关联的科室、医院
  508. if (delUserHospitalORDept(updateUserVO.getId())) {
  509. User user = new User();
  510. BeanUtils.copyProperties(updateUserVO, user);
  511. user.setPassword(BCrypt.hashpw(user.getPassword()));
  512. //1.1校验用户
  513. boolean deptFlag = false;
  514. if (ListUtil.isNotEmpty(updateUserVO.getAddHospitalTreeVO().getDepts())) {
  515. deptFlag = true;
  516. }
  517. checkUser(user, deptFlag, updateUserVO.getAddHospitalTreeVO().getHospitals(), updateUserVO.getRoles());
  518. //修改用户不修改密码
  519. user.setPassword(null);
  520. if (userFacade.updateById(user)) {
  521. //2.插入用户新关联的医院、科室
  522. return saveUserHospital(updateUserVO.getAddHospitalTreeVO(), updateUserVO.getId(), updateUserVO.getRoles());
  523. } else {
  524. Asserts.fail("用户基本信息修改失败");
  525. }
  526. }
  527. return false;
  528. }
  529. /**
  530. * @param id
  531. * @Description删除用户与医院、科室的关联关系
  532. * @Return boolean
  533. */
  534. private boolean delUserHospitalORDept(Long id) {
  535. if (hospitalUserFacade.remove(new UpdateWrapper<HospitalUser>()
  536. .eq("user_id", id)
  537. .eq("is_deleted", IsDeleteEnum.N.getKey()))) {
  538. if (userRoleFacade.remove(new UpdateWrapper<UserRole>()
  539. .eq("user_id", id)
  540. .eq("is_deleted", IsDeleteEnum.N.getKey()))) {
  541. if (userDeptFacade.list(new QueryWrapper<DeptUser>()
  542. .eq("user_id", id)
  543. .eq("is_deleted", IsDeleteEnum.N.getKey())).size() > 0) {
  544. return userDeptFacade.remove(new UpdateWrapper<DeptUser>()
  545. .eq("user_id", id)
  546. .eq("is_deleted", IsDeleteEnum.N.getKey()));
  547. }
  548. return true;
  549. } else {
  550. Asserts.fail("用户和角色的关联关系删除失败");
  551. }
  552. } else {
  553. Asserts.fail("用户和医院的关联关系删除失败");
  554. }
  555. return false;
  556. }
  557. /**
  558. * @param userId
  559. * @Description删除用户
  560. * @Return boolean
  561. */
  562. public boolean deleteUser(Long userId) {
  563. return userFacade.update(new UpdateWrapper<User>()
  564. .set("is_deleted", IsDeleteEnum.Y.getKey())
  565. .eq("id", userId));
  566. }
  567. /**
  568. * @param userId
  569. * @param status
  570. * @Description启用禁用用户
  571. * @Return boolean
  572. */
  573. public boolean disableUser(Long userId, String status) {
  574. return userFacade.update(new UpdateWrapper<User>()
  575. .set("status", status)
  576. .eq("id", userId)
  577. .eq("is_deleted", IsDeleteEnum.N.getKey()));
  578. }
  579. /**
  580. * @param userId
  581. * @Description获取用户详情
  582. * @Return com.lantone.security.dto.GetUserDTO
  583. */
  584. public GetUserDTO getUserById(Long userId) {
  585. GetUserDTO getUserDTO = new GetUserDTO();
  586. //1.获取用户的基本信息
  587. User user = userFacade.getById(userId);
  588. if (user == null) {
  589. Asserts.fail("该用户不存在请刷新重试~");
  590. }
  591. BeanUtils.copyProperties(user, getUserDTO);
  592. //2.获取当前用户的组织类型
  593. Hospital hospital = hospitalFacade.getById(SysUserUtils.getCurrentHospitalId());
  594. if (hospital == null) {
  595. Asserts.fail("该用户所属组织不存在请刷新重试~");
  596. }
  597. //3.获取查询用户的科室id列表、医院id列表
  598. List<Long> hospitals = hospitalUserFacade.list(new QueryWrapper<HospitalUser>()
  599. .eq("user_id", userId)
  600. .eq("is_deleted", IsDeleteEnum.N.getKey())).stream().map(HospitalUser::getHospitalId).collect(Collectors.toList());
  601. //如果用户属于某医院但是没有科室信息默认为全院
  602. List<GetUserHospitalDeptDTO> userHospitalDepts = hospitalUserFacade.getBaseMapper().getUserHospitaDeptById(userId);
  603. //3.2获取当前登录用户的组织机构树
  604. //获取当前医院的树状结构
  605. List<GetHospitalTreeDTO> hospitalTrees = hospitalFacade.getBaseMapper()
  606. .getHospitalTreeInfo(SysUserUtils.getCurrentHospitalId(), StatusEnum.Enable.getKey());
  607. //根据parentid分组
  608. Map<Long, List<GetHospitalTreeDTO>> hospitalMap = EntityUtil.makeEntityListMap(hospitalTrees, "parentId");
  609. //深度遍历拼装结果
  610. List<GetHospitalTreeDTO> hospitalTree = hospitalMap.get(hospital.getParentId());
  611. getHospitalDeptInfo(hospitalMap, hospitals, userHospitalDepts, hospitalTree);
  612. getUserDTO.setHospitals(hospitalTree);
  613. //4.获取用户的角色
  614. getUserDTO.setRoles(userRoleFacade.getBaseMapper().getUserRoles(userId));
  615. return getUserDTO;
  616. }
  617. /**
  618. * 递归获取医院结构
  619. *
  620. * @param hospital 当前医院
  621. * @param hospitalMap 医院集
  622. */
  623. public void getSonHospital(GetHospitalTreeDTO hospital, Map<Long, List<GetHospitalTreeDTO>> hospitalMap, List<Long> hospitals, List<GetUserHospitalDeptDTO> userHospitalDepts) {
  624. List<GetHospitalTreeDTO> hospitalTreeDTOS = hospitalMap.get(hospital.getHospitalId());
  625. if (ListUtil.isNotEmpty(hospitalTreeDTOS)) {
  626. hospital.setChildren(hospitalTreeDTOS);
  627. getHospitalDeptInfo(hospitalMap, hospitals, userHospitalDepts, hospitalTreeDTOS);
  628. }
  629. }
  630. /**
  631. * @param hospitalMap 医院结果级
  632. * @param hospitals 查询用户所在医院集
  633. * @param userHospitalDepts 查询用户所在科室集
  634. * @param hospitalTreeDTOS 当前遍历医院集
  635. * @Description
  636. * @Return void
  637. */
  638. private void getHospitalDeptInfo(Map<Long, List<GetHospitalTreeDTO>> hospitalMap, List<Long> hospitals, List<GetUserHospitalDeptDTO> userHospitalDepts, List<GetHospitalTreeDTO> hospitalTreeDTOS) {
  639. for (GetHospitalTreeDTO bean : hospitalTreeDTOS) {
  640. //真实医院添加科室信息
  641. if (HospitalTypeEnum.SINGLE_HOSPITAL.getKey() == Integer.parseInt(bean.getType())) {
  642. List<GetDeptTreeDTO> getDeptTreeDTOList = deptFacade.getBaseMapper().getDeptInfo(bean.getHospitalId());
  643. //通过查询用户所在的科室集添加关联关系
  644. List<Long> depts = userHospitalDepts.stream().map(GetUserHospitalDeptDTO::getDeptId).collect(Collectors.toList());
  645. List<Long> dHospitals = userHospitalDepts.stream().map(GetUserHospitalDeptDTO::getHospitalId).collect(Collectors.toList());
  646. getDeptTreeDTOList.stream().forEach(getDeptTreeDTO -> {
  647. if (depts.contains(getDeptTreeDTO.getDeptId())) {
  648. getDeptTreeDTO.setRelation(RelationEnum.Y.getName());
  649. //如果只有医院没有科室则是医院全选
  650. } else if (hospitals.contains(bean.getHospitalId()) && !dHospitals.contains(bean.getHospitalId())) {
  651. getDeptTreeDTO.setRelation(RelationEnum.Y.getName());
  652. bean.setRelation(RelationEnum.Y.getName());
  653. }
  654. });
  655. bean.setDepts(getDeptTreeDTOList);
  656. }
  657. getSonHospital(bean, hospitalMap, hospitals, userHospitalDepts);
  658. }
  659. }
  660. /**
  661. * 递归获取医院结构
  662. *
  663. * @param hospital 当前医院
  664. * @param hospitalMap 医院集
  665. * @return 空
  666. */
  667. public void getSonHospital(GetUserHospitalsDTO hospital, Map<Long, List<GetUserHospitalsDTO>> hospitalMap) {
  668. List<GetUserHospitalsDTO> hospitals = hospitalMap.get(hospital.getHospitalId());
  669. if (ListUtil.isNotEmpty(hospitals)) {
  670. hospital.setChildren(hospitals);
  671. for (GetUserHospitalsDTO bean : hospitals) {
  672. getSonHospital(bean, hospitalMap);
  673. }
  674. }
  675. }
  676. /**
  677. * 递归获取医院结构
  678. *
  679. * @param hospital 当前医院
  680. * @param hospitalMap 医院集
  681. * @return 空
  682. */
  683. public void getSonHospital(GetHospitalTreeDTO hospital, Map<Long, List<GetHospitalTreeDTO>> hospitalMap) {
  684. List<GetHospitalTreeDTO> hospitals = hospitalMap.get(hospital.getHospitalId());
  685. if (ListUtil.isNotEmpty(hospitals)) {
  686. hospital.setChildren(hospitals);
  687. for (GetHospitalTreeDTO bean : hospitals) {
  688. //真实医院添加科室信息
  689. if (HospitalTypeEnum.SINGLE_HOSPITAL.getKey() == Integer.parseInt(bean.getType())) {
  690. bean.setDepts(deptFacade.getBaseMapper().getDeptInfo(bean.getHospitalId()));
  691. }
  692. getSonHospital(bean, hospitalMap);
  693. }
  694. }
  695. }
  696. /**
  697. * @param getUserPageVO
  698. * @Description获取登录用户的用户列表
  699. * @Return com.baomidou.mybatisplus.core.metadata.IPage<com.lantone.security.dto.GetUserPageDTO>
  700. */
  701. public IPage<GetUserPageDTO> getUserPage(GetUserPageVO getUserPageVO) {
  702. getUserPageVO.setHospitalId(SysUserUtils.getCurrentHospitalId());
  703. //查出的用户列表不能包含当前登录的管理用户
  704. getUserPageVO.setLocalUserID(SysUserUtils.getCurrentPrincipleId());
  705. return hospitalUserFacade.getBaseMapper().getUserPage(getUserPageVO);
  706. }
  707. /**
  708. * @param
  709. * @Description获取用户所属组织
  710. * @Return java.util.List<com.lantone.security.dto.GetHospitalTreeDTO>
  711. */
  712. public Map<String, Object> getUserHospitals() {
  713. Map<String, Object> out = new HashMap<>();
  714. //但系统单家医院直接跳转
  715. boolean jumpFlag = true;
  716. //1.获取用户系统信息
  717. List<SoftwareDTO> softwares = userFacade.getBaseMapper().getUserSoftwareByUId(SysUserUtils.getCurrentPrincipleId());
  718. if (softwares.size() > 1) {
  719. jumpFlag = false;
  720. }
  721. AtomicInteger count = new AtomicInteger();
  722. List<UserSoftwareHospitalDTO> userSoftwareHospitals = new ArrayList<>();
  723. if (ListUtil.isNotEmpty(softwares)) {
  724. softwares.stream().forEach(softwareDTO -> {
  725. UserSoftwareHospitalDTO tempU = new UserSoftwareHospitalDTO();
  726. BeanUtils.copyProperties(softwareDTO, tempU);
  727. //获取该系统下的医院
  728. List<GetUserHospitalsDTO> softwareHospitals = userFacade.getBaseMapper()
  729. .getUserSoftwareHospitals(SysUserUtils.getCurrentPrincipleId(), softwareDTO.getId());
  730. count.set(count.get() + softwareHospitals.size());
  731. //转换成树状结构
  732. Map<Long, List<GetUserHospitalsDTO>> softwareHospitalMap = EntityUtil.makeEntityListMap(softwareHospitals, "parentId");
  733. tempU.setHospitals(transTreeData(softwareHospitalMap, softwareHospitals));
  734. userSoftwareHospitals.add(tempU);
  735. });
  736. }
  737. if (count.get() > 1) {
  738. jumpFlag = false;
  739. }
  740. out.put("jump", jumpFlag);
  741. out.put("software", userSoftwareHospitals);
  742. UserInfoDTO userInfo = new UserInfoDTO();
  743. User user = userFacade.getById(SysUserUtils.getCurrentPrincipleId());
  744. if (user == null) {
  745. Asserts.fail("用户不存在,请联系管理员~");
  746. }
  747. BeanUtils.copyProperties(user, userInfo);
  748. out.put("userInfo", userInfo);
  749. return out;
  750. }
  751. /**
  752. * @param softwareHospitalMap
  753. * @param softwareHospitals
  754. * @Description将医院信息转换成树状结构
  755. * @Return java.util.List<com.lantone.security.dto.GetUserHospitalsDTO>
  756. */
  757. private List<GetUserHospitalsDTO> transTreeData(Map<Long, List<GetUserHospitalsDTO>> softwareHospitalMap, List<GetUserHospitalsDTO> softwareHospitals) {
  758. if (softwareHospitalMap == null) {
  759. return null;
  760. }
  761. List<GetUserHospitalsDTO> out = new ArrayList<>();
  762. Set<Long> tempParents = new HashSet<>();
  763. Set<Long> parents = softwareHospitalMap.keySet();
  764. parents.stream().forEach(id -> {
  765. softwareHospitals.stream().forEach(getUserHospitalsDTO -> {
  766. if (getUserHospitalsDTO.getHospitalId().equals(id)) {
  767. tempParents.add(id);
  768. }
  769. });
  770. });
  771. parents.stream().forEach(parentId -> {
  772. if (!tempParents.contains(parentId)) {
  773. List<GetUserHospitalsDTO> hospitalListInfos = softwareHospitalMap.get(parentId);
  774. for (GetUserHospitalsDTO bean : hospitalListInfos) {
  775. getSonHospital(bean, softwareHospitalMap);
  776. }
  777. out.addAll(hospitalListInfos);
  778. }
  779. });
  780. return out;
  781. }
  782. /**
  783. * @Description: 用户获取token后发送登录信息
  784. * @Param: [commonResult]
  785. * @return: void
  786. * @Author: cy
  787. * @Date: 2021/9/5
  788. */
  789. public void sendLogRecordMessage(CommonResult commonResult) {
  790. Object data = commonResult.getData();
  791. if (null != data) {
  792. Map<String, Object> map = JSONObject.parseObject(JSON.toJSONString(data));
  793. if (map.containsKey("token") && null != map.get("token")) {
  794. LoginLogDTO loginLog = new LoginLogDTO();
  795. Date date = new Date();
  796. loginLog.setLoginDate(date);
  797. loginLog.setGmtCreate(date);
  798. String token = map.get("token").toString();
  799. UserDto userByToken = SysUserUtils.getUserByToken(token);
  800. loginLog.setLoginId(userByToken.getId());
  801. loginLog.setLoginName(userByToken.getUserName());
  802. loginLog.setLoginIp(HttpUtils.getIpAddress());
  803. UserAgent userAgent = UserAgent.parseUserAgentString(HttpUtils.getHttpServletRequest().getHeader("User-Agent"));
  804. // 获取客户端浏览器
  805. String browser = userAgent.getBrowser().getName();
  806. loginLog.setLoginBrowser(browser);
  807. messageService.loginLogHandle(loginLog);
  808. }
  809. }
  810. }
  811. /**
  812. * @param userId
  813. * @Description用户登出
  814. * @Return com.lantone.common.api.CommonResult<java.lang.Boolean>
  815. */
  816. public CommonResult<Boolean> close(String userId) {
  817. return CommonResult.success(sysTokenService.deleteToken(userId));
  818. }
  819. }