UserManagementFacade.java 36 KB

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