/* * Copyright 2019-2020 Zheng Jie * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.zhengjie.modules.system.service.impl; import lombok.RequiredArgsConstructor; import me.zhengjie.config.FileProperties; import me.zhengjie.exception.BadRequestException; import me.zhengjie.modules.security.service.OnlineUserService; import me.zhengjie.modules.security.service.UserCacheManager; import me.zhengjie.modules.system.domain.SysLevel; import me.zhengjie.modules.system.domain.SysUserLevelWage; import me.zhengjie.modules.system.domain.User; import me.zhengjie.exception.EntityExistException; import me.zhengjie.exception.EntityNotFoundException; import me.zhengjie.modules.system.repository.SysLevelRepository; import me.zhengjie.modules.system.repository.SysUserLevelWageRepository; import me.zhengjie.modules.system.repository.UserRepository; import me.zhengjie.modules.system.service.UserService; import me.zhengjie.modules.system.service.dto.*; import me.zhengjie.modules.system.service.mapstruct.SysUserLevelWageMapper; import me.zhengjie.modules.system.service.mapstruct.UserLoginMapper; import me.zhengjie.modules.system.service.mapstruct.UserMapper; import me.zhengjie.utils.*; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import javax.validation.constraints.NotBlank; import java.io.File; import java.io.IOException; import java.sql.Timestamp; import java.util.*; import java.util.stream.Collectors; /** * @author Zheng Jie * @date 2018-11-23 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "user") public class UserServiceImpl implements UserService { private final UserRepository userRepository; private final UserMapper userMapper; private final FileProperties properties; private final RedisUtils redisUtils; private final UserCacheManager userCacheManager; private final OnlineUserService onlineUserService; private final UserLoginMapper userLoginMapper; private final SysLevelRepository sysLevelRepository; private final SysUserLevelWageRepository sysUserLevelWageRepository; @Override public Object queryAll(UserQueryCriteria criteria, Pageable pageable) { Page page = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable); return PageUtil.toPage(page.map(userMapper::toDto)); } @Override public List queryAll(UserQueryCriteria criteria) { List users = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)); return userMapper.toDto(users); } @Override @Cacheable(key = "'id:' + #p0") @Transactional(rollbackFor = Exception.class) public UserDto findById(long id) { User user = userRepository.findById(id).orElseGet(User::new); ValidationUtil.isNull(user.getId(), "User", "id", id); return userMapper.toDto(user); } @Override @Transactional(rollbackFor = Exception.class) public void create(User resources) { if (userRepository.findByUsername(resources.getUsername()) != null) { throw new EntityExistException(User.class, "username", resources.getUsername()); } if (userRepository.findByEmail(resources.getEmail()) != null) { throw new EntityExistException(User.class, "email", resources.getEmail()); } if (userRepository.findByPhone(resources.getPhone()) != null) { throw new EntityExistException(User.class, "phone", resources.getPhone()); } userRepository.save(resources); // 判断用户级别变更 checkUserLevel(resources.getId(), null, resources.getLevelId()); } @Override @Transactional(rollbackFor = Exception.class) public void update(User resources) throws Exception { User user = userRepository.findById(resources.getId()).orElseGet(User::new); ValidationUtil.isNull(user.getId(), "User", "id", resources.getId()); User user1 = userRepository.findByUsername(resources.getUsername()); User user2 = userRepository.findByEmail(resources.getEmail()); User user3 = userRepository.findByPhone(resources.getPhone()); if (user1 != null && !user.getId().equals(user1.getId())) { throw new EntityExistException(User.class, "username", resources.getUsername()); } if (user2 != null && !user.getId().equals(user2.getId())) { throw new EntityExistException(User.class, "email", resources.getEmail()); } if (user3 != null && !user.getId().equals(user3.getId())) { throw new EntityExistException(User.class, "phone", resources.getPhone()); } // 如果用户的角色改变 if (!resources.getRoles().equals(user.getRoles())) { redisUtils.del(CacheKey.DATA_USER + resources.getId()); redisUtils.del(CacheKey.MENU_USER + resources.getId()); redisUtils.del(CacheKey.ROLE_AUTH + resources.getId()); } // 修改部门会影响 数据权限 if (!Objects.equals(resources.getDept(),user.getDept())) { redisUtils.del(CacheKey.DATA_USER + resources.getId()); } // 如果用户被禁用,则清除用户登录信息 if(!resources.getEnabled()){ onlineUserService.kickOutForUsername(resources.getUsername()); } // 临时旧用户级别ID Long tempOldLevelId = user.getLevelId();; user.setUsername(resources.getUsername()); user.setEmail(resources.getEmail()); user.setEnabled(resources.getEnabled()); user.setRoles(resources.getRoles()); user.setDept(resources.getDept()); user.setJobs(resources.getJobs()); user.setPhone(resources.getPhone()); user.setNickName(resources.getNickName()); user.setGender(resources.getGender()); user.setBirthday(resources.getBirthday()); user.setAddress(resources.getAddress()); user.setDingding(resources.getDingding()); user.setSysRostering(resources.getSysRostering()); user.setLevelId(resources.getLevelId()); // 临时新用户级别ID Long tempNewLevelId = user.getLevelId(); userRepository.save(user); // 判断用户级别变更 checkUserLevel(user.getId(), tempOldLevelId, tempNewLevelId); // 清除缓存 delCaches(user.getId(), user.getUsername()); } @Override @Transactional(rollbackFor = Exception.class) public void updateCenter(User resources) { User user = userRepository.findById(resources.getId()).orElseGet(User::new); User user1 = userRepository.findByPhone(resources.getPhone()); if (user1 != null && !user.getId().equals(user1.getId())) { throw new EntityExistException(User.class, "phone", resources.getPhone()); } user.setNickName(resources.getNickName()); user.setPhone(resources.getPhone()); user.setGender(resources.getGender()); userRepository.save(user); // 清理缓存 delCaches(user.getId(), user.getUsername()); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Set ids) { for (Long id : ids) { // 清理缓存 UserDto user = findById(id); delCaches(user.getId(), user.getUsername()); } userRepository.deleteAllByIdIn(ids); } @Override public UserDto findByName(String userName) { User user = userRepository.findByUsername(userName); if (user == null) { throw new EntityNotFoundException(User.class, "name", userName); } else { return userMapper.toDto(user); } } @Override public UserLoginDto getLoginData(String userName) { User user = userRepository.findByUsername(userName); if (user == null) { throw new EntityNotFoundException(User.class, "name", userName); } else { return userLoginMapper.toDto(user); } } @Override @Transactional(rollbackFor = Exception.class) public void updatePass(String username, String pass) { userRepository.updatePass(username, pass, new Date()); flushCache(username); } @Override @Transactional(rollbackFor = Exception.class) public Map updateAvatar(MultipartFile multipartFile) { // 文件大小验证 FileUtil.checkSize(properties.getAvatarMaxSize(), multipartFile.getSize()); // 验证文件上传的格式 String image = "gif jpg png jpeg"; String fileType = FileUtil.getExtensionName(multipartFile.getOriginalFilename()); if(fileType != null && !image.contains(fileType)){ throw new BadRequestException("文件格式错误!, 仅支持 " + image +" 格式"); } User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername()); String oldPath = user.getAvatarPath(); File file = FileUtil.upload(multipartFile, properties.getPath().getAvatar()); user.setAvatarPath(Objects.requireNonNull(file).getPath()); user.setAvatarName(file.getName()); userRepository.save(user); if (StringUtils.isNotBlank(oldPath)) { FileUtil.del(oldPath); } @NotBlank String username = user.getUsername(); flushCache(username); return new HashMap(1) {{ put("avatar", file.getName()); }}; } @Override @Transactional(rollbackFor = Exception.class) public void updateEmail(String username, String email) { userRepository.updateEmail(username, email); flushCache(username); } /** * 查询在职员工 * @return */ @Override public List getUsers() { List List = userRepository.findAllByEnabled(true); return List; } @Override public void download(List queryAll, HttpServletResponse response) throws IOException { List> list = new ArrayList<>(); for (UserDto userDTO : queryAll) { List roles = userDTO.getRoles().stream().map(RoleSmallDto::getName).collect(Collectors.toList()); String levelName = userDTO.getLevelId() != null ? sysLevelRepository.findById(userDTO.getLevelId()).orElseGet(SysLevel::new).getName() : ""; Map map = new LinkedHashMap<>(); map.put("用户名", userDTO.getUsername()); map.put("角色", roles); map.put("部门", userDTO.getDept().getName()); map.put("岗位", userDTO.getJobs().stream().map(JobSmallDto::getName).collect(Collectors.toList())); map.put("邮箱", userDTO.getEmail()); map.put("钉钉号", userDTO.getDingding()); map.put("排班", userDTO.getSysRostering().getName()); map.put("级别", levelName); map.put("状态", userDTO.getEnabled() ? "启用" : "禁用"); map.put("手机号码", userDTO.getPhone()); map.put("修改密码的时间", userDTO.getPwdResetTime()); map.put("创建日期", userDTO.getCreateTime()); list.add(map); } FileUtil.downloadExcel(list, response); } /** * 清理缓存 * * @param id / */ public void delCaches(Long id, String username) { redisUtils.del(CacheKey.USER_ID + id); flushCache(username); } /** * 清理 登陆时 用户缓存信息 * * @param username / */ private void flushCache(String username) { userCacheManager.cleanUserCache(username); } /** * 判断用户级别变更 * @param userId * @param oldLevelId * @param newLevelId */ private void checkUserLevel(Long userId, Long oldLevelId, Long newLevelId) { // 判断新旧用户级别ID是否相等 if (oldLevelId == null) { // 创建用户级别工资 createSysUserLevelWage(userId, newLevelId); } else if (oldLevelId != newLevelId) { // 旧用户级别工资 SysUserLevelWage oldSysUserLevelWage = sysUserLevelWageRepository.findLastByUserId(userId); // 判断旧用户级别工资是否为空 if (oldSysUserLevelWage != null && oldSysUserLevelWage.getId() != null) { // 旧用户级别工资 oldSysUserLevelWage.setEndDate(new Timestamp(new Date().getTime())); // 保存 sysUserLevelWageRepository.save(oldSysUserLevelWage); } // 创建用户级别工资 createSysUserLevelWage(userId, newLevelId); } else { } } /** * 创建用户级别工资 * @param userId * @param levelId */ private void createSysUserLevelWage(Long userId, Long levelId) { // 级别 SysLevel sysLevel = sysLevelRepository.findById(levelId).orElseGet(SysLevel::new); // 用户级别工资 SysUserLevelWage sysUserLevelWage = new SysUserLevelWage(); sysUserLevelWage.setUserId(userId); sysUserLevelWage.setLevelId(levelId); sysUserLevelWage.setStartDate(new Timestamp(new Date().getTime())); sysUserLevelWage.setLevelWage(sysLevel.getLevelWage()); sysUserLevelWage.setBasicWageProportion(sysLevel.getBasicWageProportion()); sysUserLevelWage.setAchievementsWageProportion(sysLevel.getAchievementsWageProportion()); sysUserLevelWage.setPerformanceWageProportion(sysLevel.getPerformanceWageProportion()); sysUserLevelWage.setTeamWageProportion(sysLevel.getTeamWageProportion()); // 保存 sysUserLevelWageRepository.save(sysUserLevelWage); } }