/*
|
* 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.attendance.domain.Attendance;
|
import me.zhengjie.modules.attendance.domain.AttendanceBusinessTravel;
|
import me.zhengjie.modules.attendance.domain.AttendanceGoOut;
|
import me.zhengjie.modules.attendance.repository.AttendanceBusinessTravelRepository;
|
import me.zhengjie.modules.attendance.repository.AttendanceCardreplacementRepository;
|
import me.zhengjie.modules.attendance.repository.AttendanceGoOutRepository;
|
import me.zhengjie.modules.attendance.repository.AttendanceRepository;
|
import me.zhengjie.modules.attendance.service.impl.AttendanceLeaveServiceImpl;
|
import me.zhengjie.modules.constant.Constant;
|
import me.zhengjie.modules.quartz.utils.DateTimeUtil;
|
import me.zhengjie.modules.security.service.OnlineUserService;
|
import me.zhengjie.modules.security.service.UserCacheManager;
|
import me.zhengjie.modules.system.domain.*;
|
import me.zhengjie.exception.EntityExistException;
|
import me.zhengjie.exception.EntityNotFoundException;
|
import me.zhengjie.modules.system.domain.vo.CalendarVo;
|
import me.zhengjie.modules.system.repository.*;
|
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.modules.task.domain.TaskDaliy;
|
import me.zhengjie.modules.task.repository.TaskDaliyRepository;
|
import me.zhengjie.utils.*;
|
import org.apache.commons.lang3.ObjectUtils;
|
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.math.BigDecimal;
|
import java.sql.Timestamp;
|
import java.text.ParseException;
|
import java.text.SimpleDateFormat;
|
import java.time.Duration;
|
import java.time.LocalDate;
|
import java.time.LocalDateTime;
|
import java.time.format.DateTimeFormatter;
|
import java.time.temporal.TemporalAdjusters;
|
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;
|
private final SysUserLevelInsuranceRepository sysUserLevelInsuranceRepository;
|
private final SysUserLevelOtherRepository sysUserLevelOtherRepository;
|
private final AttendanceRepository attendanceRepository;
|
private final TaskDaliyRepository taskDaliyRepository;
|
private final AttendanceLeaveServiceImpl attendanceLeaveService;
|
private final AttendanceCardreplacementRepository attendanceCardreplacementRepository;
|
private final SysConfigProportionRepository sysConfigProportionRepository;
|
private final SysConfigHolidayRepository sysConfigHolidayRepository;
|
private final AttendanceGoOutRepository attendanceGoOutRepository;
|
private final AttendanceBusinessTravelRepository attendanceBusinessTravelRepository;
|
private final SystemSettingRepository systemSettingRepository;
|
|
@Override
|
public Object queryAll(UserQueryCriteria criteria, Pageable pageable) {
|
Page<User> page = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
|
return PageUtil.toPage(page.map(userMapper::toDto));
|
}
|
|
@Override
|
public List<UserDto> queryAll(UserQueryCriteria criteria) {
|
List<User> 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.setCompany(resources.getCompany());
|
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());
|
}
|
|
/**
|
* 获取日历信息
|
* @param month
|
* @return
|
* @throws Exception
|
*/
|
@Override
|
public List<CalendarVo> getUserCalendarInfo(String month) throws Exception {
|
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
|
List<CalendarVo> calendarInfo = new ArrayList<>();
|
List<String> dateList = new ArrayList<>();
|
|
//月份第一天,最后一天
|
LocalDate startDate = LocalDate.parse(month).with(TemporalAdjusters.firstDayOfMonth());
|
LocalDate endDate = LocalDate.parse(month).with(TemporalAdjusters.lastDayOfMonth());
|
//当前登录人
|
Long userId = SecurityUtils.getCurrentUserId();
|
//查询这个范围的考勤记录
|
List<Attendance> attendanceList = attendanceRepository.findAllByUserAndDate(userId,startDate.toString(),endDate.toString());
|
for(Attendance attendance : attendanceList){
|
CalendarVo onDuty = new CalendarVo();
|
onDuty.setDate(df.format(attendance.getAttendanceDate()));
|
onDuty.setTitle(Constant.ATTENDANCE_STATE_NORMAL.equals(formateResult(attendance.getStartClockResults()).get("msg")) ? "上班打卡时间:" + attendance.getActualWorkStartTime().toString() : "上班:" + formateResult(attendance.getStartClockResults()).get("msg"));
|
onDuty.setIsOk((Boolean) formateResult(attendance.getStartClockResults()).get("status"));
|
onDuty.setType(1);
|
CalendarVo offDuty = new CalendarVo();
|
offDuty.setDate(df.format(attendance.getAttendanceDate()));
|
offDuty.setTitle(Constant.ATTENDANCE_STATE_NORMAL.equals(formateResult(attendance.getEndClockResults()).get("msg")) ? "下班打卡时间:" + attendance.getActualWorkEndTime().toString() : "下班:" + formateResult(attendance.getEndClockResults()).get("msg"));
|
offDuty.setIsOk((Boolean) formateResult(attendance.getEndClockResults()).get("status"));
|
offDuty.setType(1);
|
calendarInfo.add(onDuty);
|
calendarInfo.add(offDuty);
|
dateList.add(attendance.getAttendanceDate().toString());
|
}
|
|
//获取应工作时长
|
User user = userRepository.getById(userId);
|
Long duration = (Duration.between(user.getSysRostering().getWorkStartTime(), user.getSysRostering().getWorkEndTime())).toHours();
|
|
//查询日志表
|
List<TaskDaliy> taskDaliyList = taskDaliyRepository.findAllByUserAndDate(userId,startDate,endDate);
|
for (TaskDaliy taskDaliy : taskDaliyList) {
|
CalendarVo daily = new CalendarVo();
|
daily.setDate(taskDaliy.getFillDate().toString());
|
if (dateList.contains(taskDaliy.getFillDate().toString())) {
|
dateList.remove(taskDaliy.getFillDate().toString());
|
}
|
daily.setIsOk(taskDaliy.getConsumedHours().compareTo(new Double(duration - 1)) >= 0 ? true : false);
|
daily.setTitle(taskDaliy.getConsumedHours().compareTo(new Double(duration - 1)) >= 0 ? "工时: " + taskDaliy.getConsumedHours().toString() : "已填工时:" + taskDaliy.getConsumedHours().toString() + " 不满8小时,请补充日报");
|
daily.setType(2);
|
calendarInfo.add(daily);
|
}
|
|
for (String date : dateList) {
|
String type1 = "";
|
String type2 = "";
|
CalendarVo dailyVo = new CalendarVo();
|
dailyVo.setDate(date);
|
for (Attendance attendanceRecord : attendanceList) {
|
type1 = attendanceRecord.getStartClockResults();
|
type2 = attendanceRecord.getEndClockResults();
|
date = date.substring(0,10);
|
if(date.equals(df.format(attendanceRecord.getAttendanceDate())) && type1.equals(Constant.ATTENDANCE_STATE_LEAVE) && type2.equals(Constant.ATTENDANCE_STATE_LEAVE)){
|
dailyVo.setTitle("请假");
|
dailyVo.setIsOk(true);
|
}else if(date.equals(df.format(attendanceRecord.getAttendanceDate())) && type1.equals(Constant.ATTENDANCE_STATE_BUSINESS) && type2.equals(Constant.ATTENDANCE_STATE_BUSINESS)){
|
dailyVo.setTitle("出差");
|
dailyVo.setIsOk(true);
|
}else if(date.equals(df.format(attendanceRecord.getAttendanceDate())) && type1.equals(Constant.ATTENDANCE_STATE_REST) && type2.equals(Constant.ATTENDANCE_STATE_REST)){
|
dailyVo.setTitle("休息");
|
dailyVo.setIsOk(true);
|
}else if(date.equals(df.format(attendanceRecord.getAttendanceDate()))){
|
dailyVo.setTitle("日报未填写,请补充日报");
|
dailyVo.setIsOk(false);
|
}
|
}
|
dailyVo.setType(2);
|
calendarInfo.add(dailyVo);
|
}
|
return calendarInfo;
|
}
|
|
/**
|
* 判断状态
|
* @param result
|
* @return
|
*/
|
public Map formateResult(String result) {
|
Map returnData = new HashMap();
|
switch (result) {
|
case Constant.ATTENDANCE_STATE_NOTSIGNED:
|
returnData.put("msg", "缺卡");
|
returnData.put("status", false);
|
break;
|
case Constant.ATTENDANCE_START_EARLY:
|
returnData.put("msg", "早退");
|
returnData.put("status", false);
|
break;
|
case Constant.ATTENDANCE_START_LATE:
|
returnData.put("msg", "迟到");
|
returnData.put("status", false);
|
break;
|
case Constant.ATTENDANCE_STATE_LACK_OF_TIME:
|
returnData.put("msg", "缺时");
|
returnData.put("status", false);
|
break;
|
case Constant.ATTENDANCE_STATE_LEAVE:
|
returnData.put("msg", "请假");
|
returnData.put("status", true);
|
break;
|
case Constant.ATTENDANCE_STATE_GOOUT:
|
returnData.put("msg", "外出");
|
returnData.put("status", true);
|
break;
|
case Constant.ATTENDANCE_STATE_BUSINESS:
|
returnData.put("msg", "出差");
|
returnData.put("status", true);
|
break;
|
case Constant.ATTENDANCE_STATE_WAITFOR:
|
returnData.put("msg", "等待");
|
returnData.put("status", true);
|
break;
|
case Constant.ATTENDANCE_STATE_REST:
|
returnData.put("msg", "休息");
|
returnData.put("status", true);
|
break;
|
default:
|
returnData.put("msg", result);
|
returnData.put("status", true);
|
}
|
return returnData;
|
}
|
|
/**
|
*获取用户基础信息
|
* @return
|
* @throws ParseException
|
*/
|
@Override
|
public Map getUserBaseInfo() throws ParseException {
|
Long userId = SecurityUtils.getCurrentUserId();
|
Map returnData = new HashMap();
|
LocalDate startDate = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
|
LocalDate endDate = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
|
List<Attendance> attendanceRecordList = attendanceRepository.findAllByUserAndDate(userId, startDate.toString(), endDate.toString());
|
int numDay = 0;
|
for(Attendance attendance : attendanceRecordList){
|
if(!attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_REST) && !attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_REST)){
|
numDay++;
|
}
|
}
|
// 出勤天数
|
returnData.put("onDutyDays", numDay);
|
// 剩余年假
|
Double yearTimes = attendanceLeaveService.getYearTimeLength(userId);
|
returnData.put("annualLeave", yearTimes);
|
// 剩余补卡
|
Calendar calendar = Calendar.getInstance();
|
// 获取当前年
|
int year = calendar.get(Calendar.YEAR);
|
// 获取当前月
|
int month = calendar.get(Calendar.MONTH) + 1;
|
String mouths = "";
|
if(month < 10){
|
mouths = "0" + month;
|
}
|
String baseDate = year + "-" + mouths;
|
// 查询当月的补卡记录的条数
|
Integer count = attendanceCardreplacementRepository.count(userId, baseDate);
|
// 查询配置表的每月补卡次数
|
SysConfigProportion sysConfigProportion = sysConfigProportionRepository.findByTitle("每月可补卡次数");
|
if(count >= sysConfigProportion.getProportion()){
|
returnData.put("cardLeft", 0);
|
}else{
|
returnData.put("cardLeft", (sysConfigProportion.getProportion() - count));
|
}
|
|
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
|
// 法定节假日
|
List<String> holiday = new ArrayList<>();
|
// 天数
|
int shouldWordDays = 0;
|
List<SysConfigHoliday> holidayConfigurationList = sysConfigHolidayRepository.findAll();
|
for (SysConfigHoliday holidayConfiguration : holidayConfigurationList) {
|
if (holidayConfiguration.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS)) {
|
holiday.add(df.format(holidayConfiguration.getHolidayDate()));
|
}
|
}
|
// 获取当月所有日期
|
List<String> dateList = DateTimeUtil.getDayByMonth();
|
Date date1 = new Date();
|
String todayDay = df.format(date1);
|
// 工作日的天数
|
for(String date : dateList){
|
Date isWeekEnd = df.parse(date);
|
calendar.setTime(isWeekEnd);
|
if(isWeekEnd.compareTo(df.parse(todayDay)) <= 0){
|
if(!holiday.contains(date) && calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY){
|
shouldWordDays += 1;
|
}
|
}
|
}
|
int num = shouldWordDays * 8;
|
// 月初到今天应工作时长
|
returnData.put("Time", num);
|
|
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
User user = userRepository.getById(userId);
|
// 考勤上午时间
|
Double attCheckOnDuration = 0.0;
|
// 考勤下午时间
|
Double attCheckOffDuration = 0.0;
|
for(Attendance attendance : attendanceRecordList){
|
// 上班打卡时间不为空并且打卡状态不为出差外出的考勤记录
|
if(ObjectUtils.isNotEmpty(attendance.getActualWorkStartTime()) && !attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_GOOUT) && !attendance.getStartClockResults().equals(Constant.ATTENDANCE_STATE_BUSINESS)){
|
LocalDateTime attCheckOnTime = attendance.getActualWorkStartTime().toLocalDateTime();
|
LocalDateTime scheduleStartTime = LocalDateTime.parse(attendance.getAttendanceDate().toString().substring(0,10) +" " + user.getSysRostering().getLunchStartTime().toString() + ":00",formatter2);
|
if(attCheckOnTime.compareTo(scheduleStartTime) <= 0){
|
// 获得两个时间之间的相差值
|
Duration duration = Duration.between(attCheckOnTime, scheduleStartTime);
|
Long minutes = duration.toMinutes();
|
Double hour = Double.valueOf(String.valueOf(new BigDecimal(Double.valueOf(minutes) / 60).setScale(2, BigDecimal.ROUND_HALF_UP)));
|
attCheckOnDuration = attCheckOnDuration + hour;
|
}
|
}
|
// 下班打卡时间不为空并且打卡状态不为出差外出的考勤记录
|
if(ObjectUtils.isNotEmpty(attendance.getActualWorkEndTime()) && !attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_GOOUT) && !attendance.getEndClockResults().equals(Constant.ATTENDANCE_STATE_BUSINESS)){
|
LocalDateTime attCheckOffTime = attendance.getActualWorkEndTime().toLocalDateTime();
|
LocalDateTime scheduleEndTime = LocalDateTime.parse(attendance.getAttendanceDate().toString().substring(0,10) +" " + user.getSysRostering().getLunchEndTime().toString() + ":00",formatter2);
|
if(attCheckOffTime.compareTo(scheduleEndTime) > 0){
|
// 获得两个时间之间的相差值
|
Duration duration = Duration.between(scheduleEndTime, attCheckOffTime);
|
Long minutes = duration.toMinutes();
|
Double hour = Double.valueOf(String.valueOf(new BigDecimal(Double.valueOf(minutes) / 60 ).setScale(2, BigDecimal.ROUND_HALF_UP)));
|
attCheckOffDuration = attCheckOffDuration + hour;
|
}
|
}
|
}
|
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
|
String startTime = startDate + " " + dateTimeFormatter.format(user.getSysRostering().getWorkStartTime());
|
String endTime = df.format(new Date()) + " " + dateTimeFormatter.format(user.getSysRostering().getWorkEndTime());
|
// 外出时长
|
Double goOutTimes = 0.0;
|
// 查询外出表
|
List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.findByUserAndDate(userId,Timestamp.valueOf(startTime).toLocalDateTime(),Timestamp.valueOf(endTime).toLocalDateTime());
|
for(AttendanceGoOut attendanceGoOut : attendanceGoOutList){
|
goOutTimes = goOutTimes + attendanceGoOut.getOutDuration();
|
}
|
// 出差时长
|
Double bussTimes = 0.0;
|
// 查询出差表
|
List<AttendanceBusinessTravel> attendanceBusinessTravelList = attendanceBusinessTravelRepository.findByUserAndSEDate(userId,Timestamp.valueOf(startDate + " " + "00:00:00").toLocalDateTime(),Timestamp.valueOf(df.format(new Date()) + " " + "00:00:00").toLocalDateTime());
|
for(AttendanceBusinessTravel attendanceBusinessTravel : attendanceBusinessTravelList){
|
bussTimes = bussTimes + attendanceBusinessTravel.getTravelDuration();
|
}
|
returnData.put("Times", attCheckOnDuration + attCheckOffDuration + goOutTimes + (bussTimes * 8));
|
return returnData;
|
}
|
|
@Override
|
@Transactional(rollbackFor = Exception.class)
|
public void delete(Set<Long> 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<String, String> 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<String, String>(1) {{
|
put("avatar", file.getName());
|
}};
|
}
|
|
@Override
|
@Transactional(rollbackFor = Exception.class)
|
public void updateEmail(String username, String email) {
|
userRepository.updateEmail(username, email);
|
flushCache(username);
|
}
|
|
|
@Override
|
public void download(List<UserDto> queryAll, HttpServletResponse response) throws IOException {
|
List<Map<String, Object>> list = new ArrayList<>();
|
for (UserDto userDTO : queryAll) {
|
List<String> roles = userDTO.getRoles().stream().map(RoleSmallDto::getName).collect(Collectors.toList());
|
String levelName = userDTO.getLevelId() != null ? sysLevelRepository.findById(userDTO.getLevelId()).orElseGet(SysLevel::new).getName() : "";
|
SystemSetting systemSetting = systemSettingRepository.findByValue(userDTO.getCompany());
|
Map<String, Object> 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("所属公司", systemSetting == null ? "" : systemSetting.getLabel());
|
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);
|
// 创建用户级别保险
|
createSysUserLevelInsurance(userId, newLevelId);
|
// 创建用户级别其他
|
createSysUserLevelOther(userId, newLevelId);
|
} else if (oldLevelId != newLevelId) {
|
// 旧用户级别工资
|
SysUserLevelWage oldSysUserLevelWage = sysUserLevelWageRepository.findLastByUserId(userId);
|
// 判断旧用户级别工资是否为空
|
if (oldSysUserLevelWage != null && oldSysUserLevelWage.getId() != null) {
|
// 旧日期字符串
|
String oldDateString = oldSysUserLevelWage.getStartDate().toString().substring(0,10);
|
// 获取当前日期
|
Date nowDate = new Date();
|
// 创建Calendar实例
|
Calendar nowCalendar = Calendar.getInstance();
|
// 设置当前时间
|
nowCalendar.setTime(nowDate);
|
// 新日期字符串
|
String nowDateString = new Timestamp(nowCalendar.getTime().getTime()).toString().substring(0,10);
|
// 判断新、旧日期字符串
|
if (oldDateString.equals(nowDateString)) {
|
throw new BadRequestException("每天只能调整一次级别,请明日再试!");
|
}
|
// 设置前一天时间
|
nowCalendar.add(Calendar.DATE, -1);
|
// 旧用户级别工资
|
oldSysUserLevelWage.setEndDate(new Timestamp(nowCalendar.getTime().getTime()));
|
// 保存
|
sysUserLevelWageRepository.save(oldSysUserLevelWage);
|
}
|
// 创建用户级别工资
|
createSysUserLevelWage(userId, newLevelId);
|
// 旧用户级别保险
|
SysUserLevelInsurance oldSysUserLevelInsurance = sysUserLevelInsuranceRepository.findLastByUserId(userId);
|
// 判断旧用户级别保险是否为空
|
if (oldSysUserLevelInsurance != null && oldSysUserLevelInsurance.getId() != null) {
|
// 旧日期字符串
|
String oldDateString = oldSysUserLevelInsurance.getStartDate().toString().substring(0,10);
|
// 获取当前日期
|
Date nowDate = new Date();
|
// 创建Calendar实例
|
Calendar nowCalendar = Calendar.getInstance();
|
// 设置当前时间
|
nowCalendar.setTime(nowDate);
|
// 新日期字符串
|
String nowDateString = new Timestamp(nowCalendar.getTime().getTime()).toString().substring(0,10);
|
// 判断新、旧日期字符串
|
if (oldDateString.equals(nowDateString)) {
|
throw new BadRequestException("每天只能调整一次级别,请明日再试!");
|
}
|
// 设置前一天时间
|
nowCalendar.add(Calendar.DATE, -1);
|
// 旧用户级别保险
|
oldSysUserLevelInsurance.setEndDate(new Timestamp(nowCalendar.getTime().getTime()));
|
// 保存
|
sysUserLevelInsuranceRepository.save(oldSysUserLevelInsurance);
|
}
|
// 创建用户级别保险
|
createSysUserLevelInsurance(userId, newLevelId);
|
// 旧用户级别其他
|
SysUserLevelOther oldSysUserLevelOther = sysUserLevelOtherRepository.findLastByUserId(userId);
|
// 判断旧用户级别其他是否为空
|
if (oldSysUserLevelOther != null && oldSysUserLevelOther.getId() != null) {
|
// 旧日期字符串
|
String oldDateString = oldSysUserLevelOther.getStartDate().toString().substring(0,10);
|
// 获取当前日期
|
Date nowDate = new Date();
|
// 创建Calendar实例
|
Calendar nowCalendar = Calendar.getInstance();
|
// 设置当前时间
|
nowCalendar.setTime(nowDate);
|
// 新日期字符串
|
String nowDateString = new Timestamp(nowCalendar.getTime().getTime()).toString().substring(0,10);
|
// 判断新、旧日期字符串
|
if (oldDateString.equals(nowDateString)) {
|
throw new BadRequestException("每天只能调整一次级别,请明日再试!");
|
}
|
// 设置前一天时间
|
nowCalendar.add(Calendar.DATE, -1);
|
// 旧用户级别保险
|
oldSysUserLevelOther.setEndDate(new Timestamp(nowCalendar.getTime().getTime()));
|
// 保存
|
sysUserLevelOtherRepository.save(oldSysUserLevelOther);
|
}
|
// 创建用户级别其他
|
createSysUserLevelOther(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);
|
}
|
|
// 创建用户级别保险
|
private void createSysUserLevelInsurance(Long userId, Long levelId) {
|
// 级别
|
SysLevel sysLevel = sysLevelRepository.findById(levelId).orElseGet(SysLevel::new);
|
// 用户级别工资
|
SysUserLevelInsurance sysUserLevelInsurance = new SysUserLevelInsurance();
|
sysUserLevelInsurance.setUserId(userId);
|
sysUserLevelInsurance.setLevelId(levelId);
|
sysUserLevelInsurance.setStartDate(new Timestamp(new Date().getTime()));
|
sysUserLevelInsurance.setAccumulationRadix(sysLevel.getAccumulationRadix());
|
sysUserLevelInsurance.setAccumulationPersonalProportion(sysLevel.getAccumulationPersonalProportion());
|
sysUserLevelInsurance.setAccumulationCompanyProportion(sysLevel.getAccumulationCompanyProportion());
|
sysUserLevelInsurance.setPensionRadix(sysLevel.getPensionRadix());
|
sysUserLevelInsurance.setPensionPersonalProportion(sysLevel.getPensionPersonalProportion());
|
sysUserLevelInsurance.setPensionCompanyProportion(sysLevel.getPensionCompanyProportion());
|
sysUserLevelInsurance.setMedicalRadix(sysLevel.getMedicalRadix());
|
sysUserLevelInsurance.setMedicalPersonalProportion(sysLevel.getMedicalPersonalProportion());
|
sysUserLevelInsurance.setMedicalCompanyProportion(sysLevel.getMedicalCompanyProportion());
|
sysUserLevelInsurance.setUnemploymentRadix(sysLevel.getUnemploymentRadix());
|
sysUserLevelInsurance.setUnemploymentPersonalProportion(sysLevel.getUnemploymentPersonalProportion());
|
sysUserLevelInsurance.setUnemploymentCompanyProportion(sysLevel.getUnemploymentCompanyProportion());
|
sysUserLevelInsurance.setMaternityRadix(sysLevel.getMaternityRadix());
|
sysUserLevelInsurance.setMaternityPersonalProportion(sysLevel.getMaternityPersonalProportion());
|
sysUserLevelInsurance.setMaternityCompanyProportion(sysLevel.getMaternityCompanyProportion());
|
sysUserLevelInsurance.setIndustrialInjuryRadix(sysLevel.getIndustrialInjuryRadix());
|
sysUserLevelInsurance.setIndustrialInjuryPersonalProportion(sysLevel.getIndustrialInjuryPersonalProportion());
|
sysUserLevelInsurance.setIndustrialInjuryCompanyProportion(sysLevel.getIndustrialInjuryCompanyProportion());
|
// 保存
|
sysUserLevelInsuranceRepository.save(sysUserLevelInsurance);
|
}
|
|
/**
|
* 创建用户级别其他
|
* @param userId
|
* @param levelId
|
*/
|
private void createSysUserLevelOther(Long userId, Long levelId) {
|
// 级别
|
SysLevel sysLevel = sysLevelRepository.findById(levelId).orElseGet(SysLevel::new);
|
// 用户级别其他
|
SysUserLevelOther sysUserLevelOther = new SysUserLevelOther();
|
sysUserLevelOther.setUserId(userId);
|
sysUserLevelOther.setLevelId(levelId);
|
sysUserLevelOther.setStartDate(new Timestamp(new Date().getTime()));
|
sysUserLevelOther.setPersonalPerformanceProportion(sysLevel.getPersonalPerformanceProportion());
|
sysUserLevelOther.setAnnualLeaveDays(sysLevel.getAnnualLeaveDays());
|
// 保存
|
sysUserLevelOtherRepository.save(sysUserLevelOther);
|
}
|
}
|