UserManagementFacade.java 37 KB

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