UserServiceImpl.java 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. package com.jsh.erp.service.impl;
  2. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  3. import com.jsh.erp.datasource.entities.*;
  4. import com.jsh.erp.datasource.mappers.TenantMapper;
  5. import com.jsh.erp.datasource.vo.SpinnerVO;
  6. import com.jsh.erp.exception.BusinessParamCheckingException;
  7. import com.jsh.erp.service.*;
  8. import com.jsh.erp.utils.*;
  9. import org.springframework.util.StringUtils;
  10. import com.alibaba.fastjson.JSONArray;
  11. import com.alibaba.fastjson.JSONObject;
  12. import com.jsh.erp.constants.BusinessConstants;
  13. import com.jsh.erp.constants.ExceptionConstants;
  14. import com.jsh.erp.datasource.mappers.UserMapper;
  15. import com.jsh.erp.datasource.mappers.UserMapperEx;
  16. import com.jsh.erp.datasource.vo.TreeNodeEx;
  17. import com.jsh.erp.exception.BusinessRunTimeException;
  18. import com.jsh.erp.exception.JshException;
  19. import org.slf4j.Logger;
  20. import org.slf4j.LoggerFactory;
  21. import org.springframework.beans.factory.annotation.Value;
  22. import org.springframework.stereotype.Service;
  23. import org.springframework.transaction.annotation.Transactional;
  24. import org.springframework.web.context.request.RequestContextHolder;
  25. import org.springframework.web.context.request.ServletRequestAttributes;
  26. import javax.annotation.Resource;
  27. import javax.servlet.http.HttpServletRequest;
  28. import java.security.NoSuchAlgorithmException;
  29. import java.util.*;
  30. @Service
  31. public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
  32. private Logger logger = LoggerFactory.getLogger(UserService.class);
  33. @Resource
  34. private UserMapper userMapper;
  35. @Resource
  36. private TenantMapper tenantMapper;
  37. @Resource
  38. private UserMapperEx userMapperEx;
  39. @Resource
  40. private OrgaUserRelService orgaUserRelService;
  41. @Resource
  42. private LogService logService;
  43. @Resource
  44. private UserService userService;
  45. @Resource
  46. private TenantService tenantService;
  47. @Resource
  48. private UserBusinessService userBusinessService;
  49. @Resource
  50. private RoleService roleService;
  51. @Resource
  52. private FunctionService functionService;
  53. @Resource
  54. private PlatformConfigService platformConfigService;
  55. @Resource
  56. private RedisService redisService;
  57. @Resource
  58. private OrganizationService organizationService;
  59. @Value("${tenant.userNumLimit}")
  60. private Integer userNumLimit;
  61. @Value("${tenant.tryDayLimit}")
  62. private Integer tryDayLimit;
  63. @Override
  64. public User getUser(long id) {
  65. User result=null;
  66. try{
  67. result=userMapper.selectByPrimaryKey(id);
  68. }catch(Exception e){
  69. JshException.readFail(logger, e);
  70. }
  71. return result;
  72. }
  73. /**
  74. * 获取用户下拉框数据
  75. * @return
  76. */
  77. @Override
  78. public List<SpinnerVO> creatorSpinnerList() {
  79. return userMapper.creatorSpinnerList();
  80. }
  81. @Override
  82. public List<User> getUserListByIds(String ids)throws Exception {
  83. List<Long> idList = StringUtil.strToLongList(ids);
  84. List<User> list = new ArrayList<>();
  85. try{
  86. UserExample example = new UserExample();
  87. example.createCriteria().andIdIn(idList);
  88. list = userMapper.selectByExample(example);
  89. }catch(Exception e){
  90. JshException.readFail(logger, e);
  91. }
  92. return list;
  93. }
  94. @Override
  95. public List<User> getUser(HttpServletRequest request) throws Exception {
  96. List<User> list=null;
  97. try{
  98. //先校验是否登录,然后才能查询用户数据
  99. Long userId = this.getUserId(request);
  100. if(userId!=null) {
  101. UserExample example = new UserExample();
  102. example.createCriteria().andStatusEqualTo(BusinessConstants.USER_STATUS_NORMAL).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
  103. list = userMapper.selectByExample(example);
  104. }
  105. }catch(Exception e){
  106. JshException.readFail(logger, e);
  107. }
  108. return list;
  109. }
  110. @Override
  111. public List<UserEx> select(String userName, String loginName)throws Exception {
  112. List<UserEx> list=null;
  113. try {
  114. //先校验是否登录,然后才能查询用户数据
  115. HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
  116. Long userId = this.getUserId(request);
  117. if(userId!=null) {
  118. PageUtils.startPage();
  119. list = userMapperEx.selectByConditionUser(userName, loginName);
  120. for (UserEx ue : list) {
  121. String userType = "";
  122. if (ue.getId().equals(ue.getTenantId())) {
  123. userType = "租户";
  124. } else if (ue.getTenantId() == null) {
  125. userType = "超管";
  126. } else {
  127. userType = "普通";
  128. }
  129. ue.setUserType(userType);
  130. //是否经理
  131. String leaderFlagStr = "";
  132. if ("1".equals(ue.getLeaderFlag())) {
  133. leaderFlagStr = "是";
  134. } else {
  135. leaderFlagStr = "否";
  136. }
  137. ue.setLeaderFlagStr(leaderFlagStr);
  138. }
  139. }
  140. } catch(Exception e){
  141. JshException.readFail(logger, e);
  142. }
  143. return list;
  144. }
  145. @Override
  146. public Long countUser(String userName, String loginName)throws Exception {
  147. Long result=null;
  148. try{
  149. result=userMapperEx.countsByUser(userName, loginName);
  150. }catch(Exception e){
  151. JshException.readFail(logger, e);
  152. }
  153. return result;
  154. }
  155. @Override
  156. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  157. public int insertUser(JSONObject obj, HttpServletRequest request)throws Exception {
  158. User user = JSONObject.parseObject(obj.toJSONString(), User.class);
  159. String password = "123456";
  160. //因密码用MD5加密,需要对密码进行转化
  161. try {
  162. password = Tools.md5Encryp(password);
  163. user.setPassword(password);
  164. } catch (NoSuchAlgorithmException e) {
  165. logger.error(">>>>>>>>>>>>>>转化MD5字符串错误 :" + e.getMessage());
  166. }
  167. int result=0;
  168. try{
  169. result=userMapper.insertSelective(user);
  170. logService.insertLog("用户",
  171. new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(user.getLoginName()).toString(), request);
  172. }catch(Exception e){
  173. JshException.writeFail(logger, e);
  174. }
  175. return result;
  176. }
  177. @Override
  178. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  179. public int updateUser(JSONObject obj, HttpServletRequest request) throws Exception{
  180. User user = JSONObject.parseObject(obj.toJSONString(), User.class);
  181. int result=0;
  182. try{
  183. result=userMapper.updateByPrimaryKeySelective(user);
  184. logService.insertLog("用户",
  185. new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(user.getLoginName()).toString(), request);
  186. }catch(Exception e){
  187. JshException.writeFail(logger, e);
  188. }
  189. return result;
  190. }
  191. @Override
  192. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  193. public int updateUserByObj(User user) throws Exception{
  194. logService.insertLog("用户",
  195. new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(user.getId()).toString(),
  196. ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
  197. int result=0;
  198. try{
  199. result=userMapper.updateByPrimaryKeySelective(user);
  200. }catch(Exception e){
  201. JshException.writeFail(logger, e);
  202. }
  203. return result;
  204. }
  205. @Override
  206. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  207. public int resetPwd(String md5Pwd, Long id) throws Exception{
  208. int result=0;
  209. logService.insertLog("用户",
  210. new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(id).toString(),
  211. ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
  212. User u = getUser(id);
  213. String loginName = u.getLoginName();
  214. if("admin".equals(loginName)){
  215. logger.info("禁止重置超管密码");
  216. } else {
  217. User user = new User();
  218. user.setId(id);
  219. user.setPassword(md5Pwd);
  220. try{
  221. result=userMapper.updateByPrimaryKeySelective(user);
  222. }catch(Exception e){
  223. JshException.writeFail(logger, e);
  224. }
  225. }
  226. return result;
  227. }
  228. @Override
  229. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  230. public int deleteUser(Long id, HttpServletRequest request)throws Exception {
  231. return batDeleteUser(id.toString());
  232. }
  233. @Override
  234. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  235. public int batchDeleteUser(String ids, HttpServletRequest request)throws Exception {
  236. return batDeleteUser(ids);
  237. }
  238. @Override
  239. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  240. public int batDeleteUser(String ids) throws Exception{
  241. int result=0;
  242. StringBuffer sb = new StringBuffer();
  243. sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
  244. List<User> list = getUserListByIds(ids);
  245. for(User user: list){
  246. if(user.getId().equals(user.getTenantId())) {
  247. logger.error("异常码[{}],异常提示[{}],参数,ids:[{}]",
  248. ExceptionConstants.USER_LIMIT_TENANT_DELETE_CODE,ExceptionConstants.USER_LIMIT_TENANT_DELETE_MSG,ids);
  249. throw new BusinessRunTimeException(ExceptionConstants.USER_LIMIT_TENANT_DELETE_CODE,
  250. ExceptionConstants.USER_LIMIT_TENANT_DELETE_MSG);
  251. }
  252. sb.append("[").append(user.getLoginName()).append("]");
  253. }
  254. logService.insertLog("用户", sb.toString(),
  255. ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
  256. String[] idsArray =ids.split(",");
  257. try{
  258. result=userMapperEx.batDeleteOrUpdateUser(idsArray);
  259. }catch(Exception e){
  260. JshException.writeFail(logger, e);
  261. }
  262. if(result<1){
  263. logger.error("异常码[{}],异常提示[{}],参数,ids:[{}]",
  264. ExceptionConstants.USER_DELETE_FAILED_CODE,ExceptionConstants.USER_DELETE_FAILED_MSG,ids);
  265. throw new BusinessRunTimeException(ExceptionConstants.USER_DELETE_FAILED_CODE,
  266. ExceptionConstants.USER_DELETE_FAILED_MSG);
  267. }
  268. return result;
  269. }
  270. /**
  271. * 校验验证码
  272. * @param code 验证码
  273. * @param uuid 唯一标识
  274. * @return 结果
  275. */
  276. @Override
  277. public void validateCaptcha(String code, String uuid) {
  278. if(StringUtil.isNotEmpty(code) && StringUtil.isNotEmpty(uuid)) {
  279. code = code.trim();
  280. uuid = uuid.trim();
  281. String verifyKey = BusinessConstants.CAPTCHA_CODE_KEY + uuid;
  282. String captcha = redisService.getCacheObject(verifyKey);
  283. redisService.deleteObject(verifyKey);
  284. if (captcha == null) {
  285. logger.error("异常码[{}],异常提示[{}]", ExceptionConstants.USER_JCAPTCHA_EXPIRE_CODE, ExceptionConstants.USER_JCAPTCHA_EXPIRE_MSG);
  286. throw new BusinessRunTimeException(ExceptionConstants.USER_JCAPTCHA_EXPIRE_CODE, ExceptionConstants.USER_JCAPTCHA_EXPIRE_MSG);
  287. }
  288. if (!code.equalsIgnoreCase(captcha)) {
  289. logger.error("异常码[{}],异常提示[{}]", ExceptionConstants.USER_JCAPTCHA_ERROR_CODE, ExceptionConstants.USER_JCAPTCHA_ERROR_MSG);
  290. throw new BusinessRunTimeException(ExceptionConstants.USER_JCAPTCHA_ERROR_CODE, ExceptionConstants.USER_JCAPTCHA_ERROR_MSG);
  291. }
  292. } else {
  293. logger.error("异常码[{}],异常提示[{}]", ExceptionConstants.USER_JCAPTCHA_EMPTY_CODE, ExceptionConstants.USER_JCAPTCHA_EMPTY_MSG);
  294. throw new BusinessRunTimeException(ExceptionConstants.USER_JCAPTCHA_EMPTY_CODE, ExceptionConstants.USER_JCAPTCHA_EMPTY_MSG);
  295. }
  296. }
  297. /**
  298. * 用户登录
  299. * @param loginName
  300. * @param password
  301. * @param request
  302. * @return
  303. * @throws Exception
  304. */
  305. @Override
  306. public Map<String, Object> login(String loginName, String password, HttpServletRequest request) throws Exception {
  307. Map<String, Object> data = new HashMap<>();
  308. String msgTip = "";
  309. User user = null;
  310. //判断用户是否已经登录过,登录过不再处理
  311. Object userId = redisService.getObjectFromSessionByKey(request,"userId");
  312. if (userId != null) {
  313. logger.info("====用户已经登录过, login 方法调用结束====");
  314. msgTip = "user already login";
  315. }
  316. //获取用户状态
  317. int userStatus = -1;
  318. try {
  319. redisService.deleteObjectBySession(request,"userId");
  320. userStatus = validateUser(loginName, password);
  321. } catch (Exception e) {
  322. logger.error(">>>>>>>>>>>>>用户 " + loginName + " 登录 login 方法 访问服务层异常====", e);
  323. msgTip = "access service exception";
  324. }
  325. String token = UUID.randomUUID().toString().replaceAll("-", "") + "";
  326. switch (userStatus) {
  327. case ExceptionCodeConstants.UserExceptionCode.USER_NOT_EXIST:
  328. msgTip = "user is not exist";
  329. break;
  330. case ExceptionCodeConstants.UserExceptionCode.USER_PASSWORD_ERROR:
  331. msgTip = "user password error";
  332. break;
  333. case ExceptionCodeConstants.UserExceptionCode.BLACK_USER:
  334. msgTip = "user is black";
  335. break;
  336. case ExceptionCodeConstants.UserExceptionCode.USER_ACCESS_EXCEPTION:
  337. msgTip = "access service error";
  338. break;
  339. case ExceptionCodeConstants.UserExceptionCode.BLACK_TENANT:
  340. msgTip = "tenant is black";
  341. break;
  342. case ExceptionCodeConstants.UserExceptionCode.EXPIRE_TENANT:
  343. msgTip = "tenant is expire";
  344. break;
  345. case ExceptionCodeConstants.UserExceptionCode.USER_CONDITION_FIT:
  346. msgTip = "user can login";
  347. //验证通过 ,可以登录,放入session,记录登录日志
  348. user = getUserByLoginName(loginName);
  349. if(user.getTenantId()!=null) {
  350. token = token + "_" + user.getTenantId();
  351. }
  352. redisService.storageObjectBySession(token,"userId",user.getId());
  353. break;
  354. default:
  355. break;
  356. }
  357. data.put("msgTip", msgTip);
  358. if(user!=null){
  359. //校验下密码是不是过于简单
  360. boolean pwdSimple = false;
  361. if(user.getPassword().equals(Tools.md5Encryp(BusinessConstants.USER_DEFAULT_PASSWORD))) {
  362. pwdSimple = true;
  363. }
  364. user.setPassword(null);
  365. redisService.storageObjectBySession(token,"clientIp", Tools.getLocalIp(request));
  366. logService.insertLogWithUserId(user.getId(), user.getTenantId(), "用户",
  367. new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_LOGIN).append(user.getLoginName()).toString(),
  368. ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
  369. data.put("token", token);
  370. data.put("user", user);
  371. data.put("roleName",userService.getRoleTypeByUserId(user.getId()).getName());
  372. data.put("pwdSimple", pwdSimple);
  373. }
  374. return data;
  375. }
  376. @Override
  377. public int validateUser(String loginName, String password) throws Exception {
  378. /**默认是可以登录的*/
  379. List<User> list = null;
  380. try {
  381. UserExample example = new UserExample();
  382. example.createCriteria().andLoginNameEqualTo(loginName).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
  383. list = userMapper.selectByExample(example);
  384. if (null != list && list.size() == 0) {
  385. return ExceptionCodeConstants.UserExceptionCode.USER_NOT_EXIST;
  386. } else if(list.size() ==1) {
  387. if(list.get(0).getStatus()!=0) {
  388. return ExceptionCodeConstants.UserExceptionCode.BLACK_USER;
  389. }
  390. }
  391. } catch (Exception e) {
  392. logger.error(">>>>>>>>访问验证用户姓名是否存在后台信息异常", e);
  393. return ExceptionCodeConstants.UserExceptionCode.USER_ACCESS_EXCEPTION;
  394. }
  395. try {
  396. UserExample example = new UserExample();
  397. example.createCriteria().andLoginNameEqualTo(loginName).andPasswordEqualTo(password)
  398. .andStatusEqualTo(BusinessConstants.USER_STATUS_NORMAL).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
  399. list = userMapper.selectByExample(example);
  400. if (null != list && list.size() == 0) {
  401. return ExceptionCodeConstants.UserExceptionCode.USER_PASSWORD_ERROR;
  402. }
  403. } catch (Exception e) {
  404. logger.error(">>>>>>>>>>访问验证用户密码后台信息异常", e);
  405. return ExceptionCodeConstants.UserExceptionCode.USER_ACCESS_EXCEPTION;
  406. }
  407. return ExceptionCodeConstants.UserExceptionCode.USER_CONDITION_FIT;
  408. }
  409. @Override
  410. public User getUserByLoginName(String loginName)throws Exception {
  411. UserExample example = new UserExample();
  412. example.createCriteria().andLoginNameEqualTo(loginName).andStatusEqualTo(BusinessConstants.USER_STATUS_NORMAL)
  413. .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
  414. List<User> list=null;
  415. try{
  416. list= userMapper.selectByExample(example);
  417. }catch(Exception e){
  418. JshException.readFail(logger, e);
  419. }
  420. User user =null;
  421. if(list!=null&&list.size()>0){
  422. user = list.get(0);
  423. }
  424. return user;
  425. }
  426. @Override
  427. public int checkIsNameExist(Long id, String name)throws Exception {
  428. UserExample example = new UserExample();
  429. List<Byte> userStatus = new ArrayList<>();
  430. userStatus.add(BusinessConstants.USER_STATUS_NORMAL);
  431. example.createCriteria().andIdNotEqualTo(id).andLoginNameEqualTo(name).andStatusIn(userStatus)
  432. .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
  433. List<User> list=null;
  434. try{
  435. list= userMapper.selectByExample(example);
  436. }catch(Exception e){
  437. JshException.readFail(logger, e);
  438. }
  439. return list==null?0:list.size();
  440. }
  441. /**
  442. * create by: cjl
  443. * description:
  444. * 获取当前用户信息
  445. * create time: 2019/1/24 10:01
  446. * @Param:
  447. * @return com.jsh.erp.datasource.entities.User
  448. */
  449. @Override
  450. public User getCurrentUser(){
  451. HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
  452. Long userId = Long.parseLong(redisService.getObjectFromSessionByKey(request,"userId").toString());
  453. return getUser(userId);
  454. }
  455. /**
  456. * 根据用户名查询id
  457. * @param loginName
  458. * @return
  459. */
  460. @Override
  461. public Long getIdByLoginName(String loginName) {
  462. Long userId = 0L;
  463. UserExample example = new UserExample();
  464. example.createCriteria().andLoginNameEqualTo(loginName).andStatusEqualTo(BusinessConstants.USER_STATUS_NORMAL)
  465. .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
  466. List<User> list = userMapper.selectByExample(example);
  467. if(list!=null) {
  468. userId = list.get(0).getId();
  469. }
  470. return userId;
  471. }
  472. @Override
  473. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  474. public void addUserAndOrgUserRel(UserEx ue, HttpServletRequest request) throws Exception{
  475. if(BusinessConstants.DEFAULT_MANAGER.equals(ue.getLoginName())) {
  476. throw new BusinessRunTimeException(ExceptionConstants.USER_NAME_LIMIT_USE_CODE,
  477. ExceptionConstants.USER_NAME_LIMIT_USE_MSG);
  478. } else {
  479. logService.insertLog("用户",
  480. BusinessConstants.LOG_OPERATION_TYPE_ADD,
  481. ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
  482. //检查用户名和登录名
  483. checkLoginName(ue);
  484. //新增用户信息
  485. ue= this.addUser(ue);
  486. if(ue==null){
  487. logger.error("异常码[{}],异常提示[{}],参数,[{}]",
  488. ExceptionConstants.USER_ADD_FAILED_CODE,ExceptionConstants.USER_ADD_FAILED_MSG);
  489. throw new BusinessRunTimeException(ExceptionConstants.USER_ADD_FAILED_CODE,
  490. ExceptionConstants.USER_ADD_FAILED_MSG);
  491. }
  492. //用户id,根据用户名查询id
  493. Long userId = getIdByLoginName(ue.getLoginName());
  494. if(ue.getRoleId()!=null){
  495. JSONObject ubObj = new JSONObject();
  496. ubObj.put("type", "UserRole");
  497. ubObj.put("keyid", userId);
  498. ubObj.put("value", "[" + ue.getRoleId() + "]");
  499. userBusinessService.insertUserBusiness(ubObj, request);
  500. }
  501. if(ue.getOrgaId()==null){
  502. //如果没有选择机构,就不建机构和用户的关联关系
  503. return;
  504. }
  505. if(ue.getOrgaId()!=null && "1".equals(ue.getLeaderFlag())){
  506. //检查当前机构是否存在经理
  507. List<User> checkList = userMapperEx.getListByOrgaId(ue.getId(), ue.getOrgaId());
  508. if(checkList.size()>0) {
  509. throw new BusinessRunTimeException(ExceptionConstants.USER_LEADER_IS_EXIST_CODE,
  510. ExceptionConstants.USER_LEADER_IS_EXIST_MSG);
  511. }
  512. }
  513. //新增用户和机构关联关系
  514. OrgaUserRel oul=new OrgaUserRel();
  515. //机构id
  516. oul.setOrgaId(ue.getOrgaId());
  517. oul.setUserId(userId);
  518. //用户在机构中的排序
  519. oul.setUserBlngOrgaDsplSeq(ue.getUserBlngOrgaDsplSeq());
  520. oul=orgaUserRelService.addOrgaUserRel(oul);
  521. if(oul==null){
  522. logger.error("异常码[{}],异常提示[{}],参数,[{}]",
  523. ExceptionConstants.ORGA_USER_REL_ADD_FAILED_CODE,ExceptionConstants.ORGA_USER_REL_ADD_FAILED_MSG);
  524. throw new BusinessRunTimeException(ExceptionConstants.ORGA_USER_REL_ADD_FAILED_CODE,
  525. ExceptionConstants.ORGA_USER_REL_ADD_FAILED_MSG);
  526. }
  527. }
  528. }
  529. @Override
  530. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  531. public UserEx addUser(UserEx ue) throws Exception{
  532. /**
  533. * 新增用户默认设置
  534. * 1、密码默认123456
  535. * 2是否系统自带默认为非系统自带
  536. * 3是否管理者默认为员工
  537. * 4默认用户状态为正常
  538. * */
  539. ue.setPassword(Tools.md5Encryp(BusinessConstants.USER_DEFAULT_PASSWORD));
  540. ue.setIsystem(BusinessConstants.USER_NOT_SYSTEM);
  541. if(ue.getIsmanager()==null){
  542. ue.setIsmanager(BusinessConstants.USER_NOT_MANAGER);
  543. }
  544. ue.setStatus(BusinessConstants.USER_STATUS_NORMAL);
  545. int result=0;
  546. try{
  547. result= userMapper.insertSelective(ue);
  548. }catch(Exception e){
  549. JshException.writeFail(logger, e);
  550. }
  551. if(result>0){
  552. return ue;
  553. }
  554. return null;
  555. }
  556. @Override
  557. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  558. public void registerUser(UserEx ue, Integer manageRoleId, HttpServletRequest request) throws Exception{
  559. /**
  560. * 多次创建事务,事物之间无法协同,应该在入口处创建一个事务以做协调
  561. */
  562. if(BusinessConstants.DEFAULT_MANAGER.equals(ue.getLoginName())) {
  563. throw new BusinessRunTimeException(ExceptionConstants.USER_NAME_LIMIT_USE_CODE,
  564. ExceptionConstants.USER_NAME_LIMIT_USE_MSG);
  565. } else {
  566. ue.setPassword(ue.getPassword());
  567. ue.setIsystem(BusinessConstants.USER_NOT_SYSTEM);
  568. if (ue.getIsmanager() == null) {
  569. ue.setIsmanager(BusinessConstants.USER_NOT_MANAGER);
  570. }
  571. ue.setStatus(BusinessConstants.USER_STATUS_NORMAL);
  572. try{
  573. userMapper.insertSelective(ue);
  574. Long userId = getIdByLoginName(ue.getLoginName());
  575. ue.setId(userId);
  576. }catch(Exception e){
  577. JshException.writeFail(logger, e);
  578. }
  579. //更新租户id
  580. User user = new User();
  581. user.setId(ue.getId());
  582. user.setTenantId(ue.getId());
  583. userService.updateUserTenant(user);
  584. //新增用户与角色的关系
  585. JSONObject ubObj = new JSONObject();
  586. ubObj.put("type", "UserRole");
  587. ubObj.put("keyid", ue.getId());
  588. JSONArray ubArr = new JSONArray();
  589. ubArr.add(manageRoleId);
  590. ubObj.put("value", ubArr.toString());
  591. ubObj.put("tenantId", ue.getId());
  592. userBusinessService.insertUserBusiness(ubObj, null);
  593. //创建租户信息
  594. JSONObject tenantObj = new JSONObject();
  595. tenantObj.put("tenantId", ue.getId());
  596. tenantObj.put("loginName",ue.getLoginName());
  597. tenantObj.put("userNumLimit", ue.getUserNumLimit());
  598. tenantObj.put("expireTime", ue.getExpireTime());
  599. tenantObj.put("remark", ue.getRemark());
  600. Tenant tenant = JSONObject.parseObject(tenantObj.toJSONString(), Tenant.class);
  601. tenant.setCreateTime(new Date());
  602. if(tenant.getUserNumLimit()==null) {
  603. tenant.setUserNumLimit(userNumLimit); //默认用户限制数量
  604. }
  605. if(tenant.getExpireTime()==null) {
  606. tenant.setExpireTime(Tools.addDays(new Date(), tryDayLimit)); //租户允许试用的天数
  607. }
  608. tenantMapper.insertSelective(tenant);
  609. logger.info("===============创建租户信息完成===============");
  610. }
  611. }
  612. @Override
  613. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  614. public void updateUserTenant(User user) throws Exception{
  615. UserExample example = new UserExample();
  616. example.createCriteria().andIdEqualTo(user.getId());
  617. try{
  618. userMapper.updateByPrimaryKeySelective(user);
  619. }catch(Exception e){
  620. JshException.writeFail(logger, e);
  621. }
  622. }
  623. @Override
  624. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  625. public void updateUserAndOrgUserRel(UserEx ue, HttpServletRequest request) throws Exception{
  626. if(BusinessConstants.DEFAULT_MANAGER.equals(ue.getLoginName())) {
  627. throw new BusinessRunTimeException(ExceptionConstants.USER_NAME_LIMIT_USE_CODE,
  628. ExceptionConstants.USER_NAME_LIMIT_USE_MSG);
  629. } else {
  630. logService.insertLog("用户",
  631. new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(ue.getId()).toString(),
  632. ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
  633. //检查用户名和登录名
  634. checkLoginName(ue);
  635. //更新用户信息
  636. ue = this.updateUser(ue);
  637. if (ue == null) {
  638. logger.error("异常码[{}],异常提示[{}],参数,[{}]",
  639. ExceptionConstants.USER_EDIT_FAILED_CODE, ExceptionConstants.USER_EDIT_FAILED_MSG);
  640. throw new BusinessRunTimeException(ExceptionConstants.USER_EDIT_FAILED_CODE,
  641. ExceptionConstants.USER_EDIT_FAILED_MSG);
  642. }
  643. if(ue.getRoleId()!=null){
  644. JSONObject ubObj = new JSONObject();
  645. ubObj.put("type", "UserRole");
  646. ubObj.put("keyid", ue.getId());
  647. ubObj.put("value", "[" + ue.getRoleId() + "]");
  648. Long ubId = userBusinessService.checkIsValueExist("UserRole", ue.getId().toString());
  649. if(ubId!=null) {
  650. ubObj.put("id", ubId);
  651. userBusinessService.updateUserBusiness(ubObj, request);
  652. } else {
  653. userBusinessService.insertUserBusiness(ubObj, request);
  654. }
  655. }
  656. if (ue.getOrgaId() == null) {
  657. //如果没有选择机构,就不建机构和用户的关联关系
  658. return;
  659. }
  660. if(ue.getOrgaId()!=null && "1".equals(ue.getLeaderFlag())){
  661. //检查当前机构是否存在经理
  662. List<User> checkList = userMapperEx.getListByOrgaId(ue.getId(), ue.getOrgaId());
  663. if(checkList.size()>0) {
  664. throw new BusinessRunTimeException(ExceptionConstants.USER_LEADER_IS_EXIST_CODE,
  665. ExceptionConstants.USER_LEADER_IS_EXIST_MSG);
  666. }
  667. }
  668. //更新用户和机构关联关系
  669. OrgaUserRel oul = new OrgaUserRel();
  670. //机构和用户关联关系id
  671. oul.setId(ue.getOrgaUserRelId());
  672. //机构id
  673. oul.setOrgaId(ue.getOrgaId());
  674. //用户id
  675. oul.setUserId(ue.getId());
  676. //用户在机构中的排序
  677. oul.setUserBlngOrgaDsplSeq(ue.getUserBlngOrgaDsplSeq());
  678. if (oul.getId() != null) {
  679. //已存在机构和用户的关联关系,更新
  680. oul = orgaUserRelService.updateOrgaUserRel(oul);
  681. } else {
  682. //不存在机构和用户的关联关系,新建
  683. oul = orgaUserRelService.addOrgaUserRel(oul);
  684. }
  685. if (oul == null) {
  686. logger.error("异常码[{}],异常提示[{}],参数,[{}]",
  687. ExceptionConstants.ORGA_USER_REL_EDIT_FAILED_CODE, ExceptionConstants.ORGA_USER_REL_EDIT_FAILED_MSG);
  688. throw new BusinessRunTimeException(ExceptionConstants.ORGA_USER_REL_EDIT_FAILED_CODE,
  689. ExceptionConstants.ORGA_USER_REL_EDIT_FAILED_MSG);
  690. }
  691. }
  692. }
  693. @Override
  694. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  695. public UserEx updateUser(UserEx ue)throws Exception{
  696. int result =0;
  697. try{
  698. result=userMapper.updateByPrimaryKeySelective(ue);
  699. }catch(Exception e){
  700. JshException.writeFail(logger, e);
  701. }
  702. if(result>0){
  703. return ue;
  704. }
  705. return null;
  706. }
  707. /**
  708. * 检查登录名不能重复
  709. * create time: 2019/3/12 11:36
  710. * @Param: userEx
  711. * @return void
  712. */
  713. @Override
  714. public void checkLoginName(UserEx userEx)throws Exception{
  715. List<User> list=null;
  716. if(userEx==null){
  717. return;
  718. }
  719. Long userId=userEx.getId();
  720. //检查登录名
  721. if(!StringUtils.isEmpty(userEx.getLoginName())){
  722. String loginName=userEx.getLoginName();
  723. list=this.getUserListByloginName(loginName);
  724. if(list!=null&&list.size()>0){
  725. if(list.size()>1){
  726. //超过一条数据存在,该登录名已存在
  727. logger.error("异常码[{}],异常提示[{}],参数,loginName:[{}]",
  728. ExceptionConstants.USER_LOGIN_NAME_ALREADY_EXISTS_CODE,ExceptionConstants.USER_LOGIN_NAME_ALREADY_EXISTS_MSG,loginName);
  729. throw new BusinessRunTimeException(ExceptionConstants.USER_LOGIN_NAME_ALREADY_EXISTS_CODE,
  730. ExceptionConstants.USER_LOGIN_NAME_ALREADY_EXISTS_MSG);
  731. }
  732. //一条数据,新增时抛出异常,修改时和当前的id不同时抛出异常
  733. if(list.size()==1){
  734. if(userId==null||(userId!=null&&!userId.equals(list.get(0).getId()))){
  735. logger.error("异常码[{}],异常提示[{}],参数,loginName:[{}]",
  736. ExceptionConstants.USER_LOGIN_NAME_ALREADY_EXISTS_CODE,ExceptionConstants.USER_LOGIN_NAME_ALREADY_EXISTS_MSG,loginName);
  737. throw new BusinessRunTimeException(ExceptionConstants.USER_LOGIN_NAME_ALREADY_EXISTS_CODE,
  738. ExceptionConstants.USER_LOGIN_NAME_ALREADY_EXISTS_MSG);
  739. }
  740. }
  741. }
  742. }
  743. }
  744. /**
  745. * 通过登录名获取用户列表
  746. * */
  747. @Override
  748. public List<User> getUserListByloginName(String loginName){
  749. List<User> list =null;
  750. try{
  751. list=userMapperEx.getUserListByUserNameOrLoginName(null,loginName);
  752. }catch(Exception e){
  753. JshException.readFail(logger, e);
  754. }
  755. return list;
  756. }
  757. @Override
  758. public List<TreeNodeEx> getOrganizationUserTree()throws Exception {
  759. List<TreeNodeEx> list =null;
  760. try{
  761. list=userMapperEx.getNodeTree();
  762. }catch(Exception e){
  763. JshException.readFail(logger, e);
  764. }
  765. return list;
  766. }
  767. /**
  768. * 根据用户id查询角色信息
  769. * @param userId
  770. * @return
  771. */
  772. @Override
  773. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  774. public Role getRoleTypeByUserId(long userId) throws Exception {
  775. Role role = new Role();
  776. List<UserBusiness> list = userBusinessService.getBasicData(String.valueOf(userId), "UserRole");
  777. UserBusiness ub = null;
  778. if(list.size() > 0) {
  779. ub = list.get(0);
  780. String values = ub.getValue();
  781. String roleId = null;
  782. if(values!=null) {
  783. values = values.replaceAll("\\[\\]",",").replace("[","").replace("]","");
  784. }
  785. String [] valueArray=values.split(",");
  786. if(valueArray.length>0) {
  787. roleId = valueArray[0];
  788. }
  789. role = roleService.getRoleWithoutTenant(Long.parseLong(roleId));
  790. }
  791. return role;
  792. }
  793. /**
  794. * 获取用户id
  795. * @param request
  796. * @return
  797. */
  798. @Override
  799. public Long getUserId(HttpServletRequest request) throws Exception{
  800. Object userIdObj = redisService.getObjectFromSessionByKey(request,"userId");
  801. Long userId = null;
  802. if(userIdObj != null) {
  803. userId = Long.parseLong(userIdObj.toString());
  804. }
  805. return userId;
  806. }
  807. /**
  808. * 用户的按钮权限
  809. * @param userId
  810. * @return
  811. * @throws Exception
  812. */
  813. @Override
  814. public JSONArray getBtnStrArrById(Long userId) throws Exception {
  815. JSONArray btnStrArr = new JSONArray();
  816. List<UserBusiness> userRoleList = userBusinessService.getBasicData(userId.toString(), "UserRole");
  817. if(userRoleList!=null && userRoleList.size()>0) {
  818. String roleValue = userRoleList.get(0).getValue();
  819. if(StringUtil.isNotEmpty(roleValue) && roleValue.indexOf("[")>-1 && roleValue.indexOf("]")>-1){
  820. roleValue = roleValue.replace("[", "").replace("]", ""); //角色id-单个
  821. List<UserBusiness> roleFunctionsList = userBusinessService.getBasicData(roleValue, "RoleFunctions");
  822. if(roleFunctionsList!=null && roleFunctionsList.size()>0) {
  823. String btnStr = roleFunctionsList.get(0).getBtnStr();
  824. if(StringUtil.isNotEmpty(btnStr)){
  825. btnStrArr = JSONArray.parseArray(btnStr);
  826. }
  827. }
  828. }
  829. }
  830. //将数组中的funId转为url
  831. JSONArray btnStrWithUrlArr = new JSONArray();
  832. if(btnStrArr.size()>0) {
  833. List<Function> functionList = functionService.getFunction();
  834. Map<Long, String> functionMap = new HashMap<>();
  835. for (Function function: functionList) {
  836. functionMap.put(function.getId(), function.getUrl());
  837. }
  838. for (Object obj : btnStrArr) {
  839. JSONObject btnStrObj = JSONObject.parseObject(obj.toString());
  840. Long funId = btnStrObj.getLong("funId");
  841. JSONObject btnStrWithUrlObj = new JSONObject();
  842. btnStrWithUrlObj.put("url", functionMap.get(funId));
  843. btnStrWithUrlObj.put("btnStr", btnStrObj.getString("btnStr"));
  844. btnStrWithUrlArr.add(btnStrWithUrlObj);
  845. }
  846. }
  847. return btnStrWithUrlArr;
  848. }
  849. @Override
  850. @Transactional(value = "transactionManager", rollbackFor = Exception.class)
  851. public int batchSetStatus(Byte status, String ids, HttpServletRequest request)throws Exception {
  852. int result=0;
  853. List<User> list = getUserListByIds(ids);
  854. //选中的用户的数量
  855. int selectUserSize = list.size();
  856. //查询启用状态的用户的数量
  857. int enableUserSize = getUser(request).size();
  858. User userInfo = userService.getCurrentUser();
  859. Tenant tenant = tenantService.getTenantByTenantId(userInfo.getTenantId());
  860. if(tenant!=null) {
  861. if (selectUserSize + enableUserSize > tenant.getUserNumLimit() && status == 0) {
  862. throw new BusinessParamCheckingException(ExceptionConstants.USER_ENABLE_OVER_LIMIT_FAILED_CODE,
  863. ExceptionConstants.USER_ENABLE_OVER_LIMIT_FAILED_MSG);
  864. }
  865. }
  866. StringBuilder userStr = new StringBuilder();
  867. List<Long> idList = new ArrayList<>();
  868. for(User user: list) {
  869. if(user.getId().equals(user.getTenantId())) {
  870. //租户不能进行禁用
  871. } else {
  872. idList.add(user.getId());
  873. userStr.append(user.getLoginName()).append(" ");
  874. }
  875. }
  876. String statusStr ="";
  877. if(status == 0) {
  878. statusStr ="批量启用";
  879. } else if(status == 2) {
  880. statusStr ="批量禁用";
  881. }
  882. if(idList.size()>0) {
  883. User user = new User();
  884. user.setStatus(status);
  885. UserExample example = new UserExample();
  886. example.createCriteria().andIdIn(idList);
  887. result = userMapper.updateByExampleSelective(user, example);
  888. logService.insertLog("用户",
  889. new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(userStr).append("-").append(statusStr).toString(),
  890. ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
  891. } else {
  892. result = 1;
  893. }
  894. return result;
  895. }
  896. @Override
  897. public User getUserByWeixinCode(String weixinCode) throws Exception {
  898. String weixinUrl = platformConfigService.getPlatformConfigByKey("weixinUrl").getPlatformValue();
  899. String weixinAppid = platformConfigService.getPlatformConfigByKey("weixinAppid").getPlatformValue();
  900. String weixinSecret = platformConfigService.getPlatformConfigByKey("weixinSecret").getPlatformValue();
  901. String url = weixinUrl + "?appid=" + weixinAppid + "&secret=" + weixinSecret + "&js_code=" + weixinCode
  902. + "&grant_type=authorization_code";
  903. JSONObject jsonObject = HttpClient.httpGet(url);
  904. if(jsonObject!=null) {
  905. String weixinOpenId = jsonObject.getString("openid");
  906. if(StringUtil.isNotEmpty(weixinOpenId)) {
  907. return userMapperEx.getUserByWeixinOpenId(weixinOpenId);
  908. }
  909. }
  910. return null;
  911. }
  912. @Override
  913. public int weixinBind(String loginName, String password, String weixinCode) throws Exception {
  914. String weixinUrl = platformConfigService.getPlatformConfigByKey("weixinUrl").getPlatformValue();
  915. String weixinAppid = platformConfigService.getPlatformConfigByKey("weixinAppid").getPlatformValue();
  916. String weixinSecret = platformConfigService.getPlatformConfigByKey("weixinSecret").getPlatformValue();
  917. String url = weixinUrl + "?appid=" + weixinAppid + "&secret=" + weixinSecret + "&js_code=" + weixinCode
  918. + "&grant_type=authorization_code";
  919. JSONObject jsonObject = HttpClient.httpGet(url);
  920. if(jsonObject!=null) {
  921. String weixinOpenId = jsonObject.getString("openid");
  922. if(StringUtil.isNotEmpty(weixinOpenId)) {
  923. return userMapperEx.updateUserWithWeixinOpenId(loginName, password, weixinOpenId);
  924. }
  925. }
  926. return 0;
  927. }
  928. /**
  929. * 根据用户id回去审批用户id
  930. * @param uid 用户id
  931. * @param isParent 是否查询父级 true查询,false不查询
  932. * @return
  933. */
  934. @Override
  935. public Long getAuditUserIds(Long uid, boolean isParent) {
  936. Organization organization = orgaUserRelService.getOrganizationByUid(uid);
  937. Long orgaId = organization.getId();
  938. if (isParent && organization.getParentId() != null){
  939. orgaId = organization.getParentId();
  940. }
  941. return userMapper.getAuditUserIds(orgaId);
  942. }
  943. }