BAOLH
2026-11-10 4d730af0447c686133130d0116a0fa3dd82c2dca
eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/impl/AttendanceLeaveServiceImpl.java
@@ -15,21 +15,18 @@
*/
package me.zhengjie.modules.attendance.service.impl;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.approval.domain.ApproveEvent;
import me.zhengjie.modules.approval.repository.ApproveEventRepository;
import me.zhengjie.modules.approval.service.TemplateControlFieldService;
import me.zhengjie.modules.approval.service.TemplateService;
import me.zhengjie.modules.approval.service.mapstruct.ApproveEventMapper;
import me.zhengjie.modules.attendance.domain.*;
import me.zhengjie.modules.attendance.repository.*;
import me.zhengjie.modules.attendance.service.AttendanceLeaveService;
import me.zhengjie.modules.attendance.service.AttendanceService;
import me.zhengjie.modules.attendance.service.dto.AttendanceLeaveDto;
import me.zhengjie.modules.attendance.service.dto.AttendanceLeaveQueryCriteria;
import me.zhengjie.modules.attendance.service.dto.AttendanceOvertimeQueryCriteria;
import me.zhengjie.modules.attendance.service.dto.OvertimeConsumedRecordQueryCriteria;
import me.zhengjie.modules.attendance.service.dto.*;
import me.zhengjie.modules.attendance.service.mapstruct.AttendanceLeaveMapper;
import me.zhengjie.modules.constant.Constant;
import me.zhengjie.modules.quartz.service.impl.WeComServiceImpl;
@@ -38,6 +35,9 @@
import me.zhengjie.modules.system.repository.SysConfigHolidayRepository;
import me.zhengjie.modules.system.repository.SysUserLevelOtherRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.treatment.domain.CmnLevel;
import me.zhengjie.modules.treatment.repository.CmnLevelRepository;
import me.zhengjie.modules.treatment.service.dto.CmnLevelQueryCriteria;
import me.zhengjie.utils.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Page;
@@ -50,6 +50,7 @@
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@@ -76,16 +77,18 @@
    private final SysUserLevelOtherRepository sysUserLevelOtherRepository;
    private final UserRepository userRepository;
    private final SysConfigHolidayRepository sysConfigHolidayRepository;
    private final AttendanceRepository attendanceRepository;
    private final AttendanceGoOutRepository attendanceGoOutRepository;
    private final AttendanceBusinessTravelRepository attendanceBusinessTravelRepository;
    private final AttendanceOvertimeRepository attendanceOvertimeRepository;
    private final ApproveEventRepository approveEventRepository;
    private final OvertimeConsumedRecordRepository overtimeConsumedRecordRepository;
    private final AnnualLeaveRecordRepository annualLeaveRecordRepository;
    private final CmnLevelRepository cmnLevelRepository;
    private final ApproveEventMapper approveEventMapper;
    private final WeComServiceImpl weComService;
    private final TemplateService templateService;
    private final TemplateControlFieldService templateControlFieldService;
    private final DateTimeFormatter ymFormatter = DateTimeFormatter.ofPattern("yyyy-MM");
    @Override
    public Map<String,Object> queryAll(AttendanceLeaveQueryCriteria criteria, Pageable pageable){
@@ -309,8 +312,8 @@
        //获取当前登入人信息
        User user1 = userRepository.getOne(SecurityUtils.getCurrentUserId());
        Role role = user1.getRoles().iterator().next();
        //除超管、总经理只能修改自己信息
        if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
        // 除超管、总经理只能修改自己信息
        if (!Constant.SUPER_LEVEL_LIST.contains(Long.valueOf(role.getLevel()))){
            if (!Long.valueOf(resources.getUserId()).equals(SecurityUtils.getCurrentUserId())){
                throw new BadRequestException("只能修改自己的记录");
            }
@@ -469,6 +472,9 @@
            Integer timeSeconds = attendanceService.calculateTimes(calculate, SecurityUtils.getCurrentUserId(), resources.getLeaveType().equals(Constant.LEAVE_TYPE_LACTATION_LEAVE) ? 1 : null);
            result = Double.valueOf(new BigDecimal((float) timeSeconds / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            attendanceLeaveDto.setLeaveDurationUnit(Constant.LEAVE_TIME_TYPE_HOUR);
            if (result < 1) {
                throw new BadRequestException("请假时间不可低于1小时");
            }
        } else {
            // 以天为单位计算
            Integer days = attendanceService.calculateDays(calculate);
@@ -483,54 +489,35 @@
     * 获取用户年假剩余时长
     */
    @Override
    public Double getYearTimeLength(Long userId) {
        //获取年假剩余(新)
        Double surplusYearTime = new Double(0.00);
        // 根据用户查询
        List<SysUserLevelOther> sysUserLevelOtherList = sysUserLevelOtherRepository.findByUserId(userId);
        if (sysUserLevelOtherList.size() > 0) {
            for (SysUserLevelOther sysUserLevelOther : sysUserLevelOtherList) {
                // 获取今年
                int year = Calendar.getInstance().get(Calendar.YEAR);
                if (!sysUserLevelOther.getYearMonth().isEmpty() && sysUserLevelOther.getYearMonth().substring(0,4).equals(String.valueOf(year))) {
                    //年假总时长
                    Double yearTime = Double.valueOf(sysUserLevelOther.getAnnualLeaveDays() == null ? 0 : sysUserLevelOther.getAnnualLeaveDays() * 8);
                    String startTime = year + "-01-01 00:00:00";
                    String endTime = year + "-12-31 23:59:59";
                    Double usedYearTime = attendanceLeaveRepository.getSurplusYearTime(sysUserLevelOther.getUserId(), startTime, endTime);
                    surplusYearTime = yearTime - (usedYearTime == null ? 0.0 : usedYearTime);
                }
            }
        }
        return surplusYearTime;
    }
    /**
     * 获取用户年假剩余时长
     */
    @Override
    public Double getYearTimeLength(Long userId, String year) {
        //获取年假剩余(新)
        Double surplusYearTime = new Double(0.00);
        // 根据用户查询
        List<SysUserLevelOther> sysUserLevelOtherList = sysUserLevelOtherRepository.findByUserId(userId);
        if (sysUserLevelOtherList.size() > 0) {
            for (SysUserLevelOther sysUserLevelOther : sysUserLevelOtherList) {
                if (!sysUserLevelOther.getYearMonth().isEmpty() && sysUserLevelOther.getYearMonth().substring(0,4).equals(String.valueOf(year))) {
                    //年假总时长
                    Double yearTime = Double.valueOf(sysUserLevelOther.getAnnualLeaveDays() == null ? 0 : sysUserLevelOther.getAnnualLeaveDays() * 8);
                    String startTime = year + "-01-01 00:00:00";
                    String endTime = year + "-12-31 23:59:59";
                    Double usedYearTime = attendanceLeaveRepository.getSurplusYearTime(sysUserLevelOther.getUserId(), startTime, endTime);
                    surplusYearTime = yearTime - (usedYearTime == null ? 0.0 : usedYearTime);
                }
        // 默认参数
        LocalDate targetDate;
        if (StringUtils.isBlank(year)) {
            // 未指定年度
            targetDate = LocalDate.now();
        } else {
            // 指定年度
            if (LocalDate.now().getYear() == Integer.parseInt(year)) {
                // 当年
                targetDate = LocalDate.now();
            } else {
                // 往年
                targetDate = LocalDate.now().withYear(Integer.parseInt(year)).plusYears(1).withDayOfYear(1).minusDays(1);
            }
        }
        return surplusYearTime;
        // 年假配额
        BigDecimal surplusYearTime = BigDecimal.valueOf(getAnnualLeaveQuota(userId, year));
        // 当年使用年假时长
        String startTime = targetDate.withDayOfYear(1).atTime(4, 0, 0, 0).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String endTime = targetDate.withDayOfYear(1).plusYears(1).atTime(3, 59, 59, 0).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Double usedYearTime = attendanceLeaveRepository.getSurplusYearTime(userId, startTime, endTime);
        // 计算本年度剩余年假时长
        surplusYearTime = surplusYearTime.subtract(new BigDecimal(usedYearTime == null ? 0.0 : usedYearTime));
        return surplusYearTime.doubleValue();
    }
    /**
@@ -659,8 +646,8 @@
            Role role = user.getRoles().iterator().next();
            //根据id查询记录
            Optional<AttendanceLeave> attendanceLeave1 = attendanceLeaveRepository.findById(id);
            //除超管、总经理只能删除自己信息
            if(role.getId() != Constant.ROLE_LEVEL_SUPER && role.getId() != Constant.ROLE_LEVEL_GENERAL){
            // 除超管、总经理只能删除自己信息
            if(!Constant.SUPER_LEVEL_LIST.contains(Long.valueOf(role.getLevel()))){
                if (!Long.valueOf(attendanceLeave1.get().getUserId()).equals(SecurityUtils.getCurrentUserId())){
                    throw new BadRequestException("只能删除自己的记录");
                }
@@ -732,6 +719,168 @@
    }
    /**
     * 结算去年剩余年假
     */
    @Override
    public Double settlementLastYearTime(Long userId, String year) {
        // 默认参数
        LocalDate targetDate;
        if (StringUtils.isBlank(year)) {
            // 未指定年度
            targetDate = LocalDate.now();
        } else {
            // 指定年度
            if (LocalDate.now().getYear() == Integer.parseInt(year)) {
                // 当年
                targetDate = LocalDate.now();
            } else {
                // 往年
                targetDate = LocalDate.now().withYear(Integer.parseInt(year)).plusYears(1).withDayOfYear(1).minusDays(1);
            }
        }
        // 年假配额
        BigDecimal surplusYearTime = BigDecimal.valueOf(getAnnualLeaveQuota(userId, year));
        // 判断是否已结算
        AnnualLeaveRecordQueryCriteria settlementCriteria = new AnnualLeaveRecordQueryCriteria();
        settlementCriteria.setUserId(userId);
        settlementCriteria.setYear(String.valueOf(targetDate.getYear()));
        AnnualLeaveRecord annualLeaveRecord = annualLeaveRecordRepository.findOne((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, settlementCriteria, criteriaBuilder)).orElse(null);
        if (annualLeaveRecord == null) {
            // 当年使用年假时长
            String startTime = targetDate.withDayOfYear(1).atTime(4, 0, 0, 0).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String endTime = targetDate.withDayOfYear(1).plusYears(1).atTime(3, 59, 59, 0).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            Double usedYearTime = attendanceLeaveRepository.getSurplusYearTime(userId, startTime, endTime);
            // 计算本年度剩余年假时长
            surplusYearTime = surplusYearTime.subtract(new BigDecimal(usedYearTime == null ? 0.0 : usedYearTime));
            AnnualLeaveRecord lastRecord = new AnnualLeaveRecord();
            lastRecord.setUserId(userId);
            lastRecord.setYear(String.valueOf(targetDate.getYear()));
            lastRecord.setSurplusHour(surplusYearTime.doubleValue());
            annualLeaveRecordRepository.save(lastRecord);
            if (lastRecord.getSurplusHour() >= 1) {
                // 剩余年假大于1H时转为调休保存
                AttendanceOvertime attendanceOvertime = new AttendanceOvertime();
                attendanceOvertime.setUserId(userId);
                attendanceOvertime.setApprovalUserId(0L);
                attendanceOvertime.setOvertimeStartTime(Timestamp.valueOf(targetDate.plusYears(1).withDayOfYear(1).atTime(4, 0, 1)));
                attendanceOvertime.setOvertimeEndTime(Timestamp.valueOf(targetDate.plusYears(1).withDayOfYear(1).atTime(4, 0, 2)));
                attendanceOvertime.setOvertimeDuration(surplusYearTime.setScale(0, RoundingMode.DOWN).doubleValue());
                // 设置为休息日普通结算
                attendanceOvertime.setDateType(Constant.DATE_TYPE_WEEKEND);
                attendanceOvertime.setApprovalStatus(Constant.OVERTIME_PASS);
                attendanceOvertime.setRemarks(targetDate.getYear() + "年度年假结算剩余转换");
                attendanceOvertime.setRemainingDuration(surplusYearTime.setScale(0, RoundingMode.DOWN).doubleValue());
                attendanceOvertimeRepository.save(attendanceOvertime);
            }
        } else {
            return annualLeaveRecord.getSurplusHour();
        }
        return surplusYearTime.doubleValue();
    }
    /**
     * 获取年度年假额度
     */
    @Override
    public Double getAnnualLeaveQuota(Long userId, String year) {
        // 默认参数
        LocalDate targetDate;
        if (StringUtils.isBlank(year)) {
            // 未指定年度
            targetDate = LocalDate.now();
        } else {
            // 指定年度
            if (LocalDate.now().getYear() == Integer.parseInt(year)) {
                // 当年
                targetDate = LocalDate.now();
            } else {
                // 往年
                targetDate = LocalDate.now().withYear(Integer.parseInt(year)).plusYears(1).withDayOfYear(1).minusDays(1);
            }
        }
        // 获取年假剩余(新)
        BigDecimal surplusYearTime = BigDecimal.ZERO;
        // 判断年份是否在用户创建之前
        User user = userRepository.findById(userId).orElse(null);
        if (targetDate.getYear() < user.getCreateTime().toLocalDateTime().getYear()) {
            return surplusYearTime.doubleValue();
        }
        // 判断用户是否为实习生(实习生无年假)
        CmnLevelQueryCriteria levelQueryCriteria = new CmnLevelQueryCriteria();
        levelQueryCriteria.setName("实习");
        List<CmnLevel> internshipLevelList = cmnLevelRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, levelQueryCriteria, criteriaBuilder));
        if (internshipLevelList.size() > 0) {
            internshipLevelList.stream().map(CmnLevel::getId).collect(Collectors.toList());
            SysUserLevelOther targetSysUserLevelOther = sysUserLevelOtherRepository.findByUserIdAndData(userId, targetDate.format(DateTimeFormatter.ofPattern("yyyy-MM")));
            if (targetSysUserLevelOther != null && internshipLevelList.stream().map(CmnLevel::getId).anyMatch(id -> id.equals(targetSysUserLevelOther.getLevelId()))) {
                return surplusYearTime.doubleValue();
            }
        }
        // 根据用户查询
        List<SysUserLevelOther> sysUserLevelOtherList = sysUserLevelOtherRepository.findByUserId(userId);
        YearMonth targetYearMonth = YearMonth.from(targetDate);
        SysUserLevelOther sysUserLevelOther = sysUserLevelOtherList.stream().filter(sulo -> {
            if (StringUtils.isNotBlank(sulo.getYearMonth())) {
                YearMonth yearMonth = YearMonth.parse(sulo.getYearMonth(), ymFormatter);
                return targetYearMonth.compareTo(yearMonth) >= 0;
            }
            return false;
        }).sorted(Comparator.comparing(SysUserLevelOther::getYearMonth).reversed()).findFirst().orElse(null);
        if (sysUserLevelOther != null) {
            // 年假可用时长
            BigDecimal yearTime = new BigDecimal(sysUserLevelOther.getAnnualLeaveDays() == null ? 0 : sysUserLevelOther.getAnnualLeaveDays() * 8);
            // 当年的需要等比例扣除(刚转正的情况)
            yearTime = calcRemainingYearTime(user, targetDate, yearTime, internshipLevelList, sysUserLevelOtherList);
            surplusYearTime = yearTime;
        }
        return surplusYearTime.doubleValue();
    }
    /**
     * 计算剩余年假
     * @param user / 用户信息
     * @param targetDate / 目标日期
     * @param yearTime / 年假总时长
     * @param internshipLevelList / 实习等级记录
     * @param sysUserLevelOtherList / 用户等级记录
     * @return
     */
    public BigDecimal calcRemainingYearTime(User user, LocalDate targetDate, BigDecimal yearTime, List<CmnLevel> internshipLevelList, List<SysUserLevelOther> sysUserLevelOtherList) {
        // 正式入职日期(无实习期按照账户创建时间计算)
        YearMonth firstRegularYearMonth = YearMonth.from(user.getCreateTime().toLocalDateTime());
        if (CollectionUtils.isNotEmpty(internshipLevelList) && CollectionUtils.isNotEmpty(sysUserLevelOtherList)) {
            List<Long> internshipLevelIds = internshipLevelList.stream().map(CmnLevel::getId).collect(Collectors.toList());
            YearMonth internshipYearMonth = sysUserLevelOtherList.stream()
                    .filter(sulo -> internshipLevelIds.contains(sulo.getLevelId()))
                    .map(sulo -> YearMonth.parse(sulo.getYearMonth(), ymFormatter))
                    .sorted(Comparator.reverseOrder()).findFirst().orElse(null);
            if (internshipYearMonth != null) {
                firstRegularYearMonth = sysUserLevelOtherList.stream()
                        .map(sulo -> YearMonth.parse(sulo.getYearMonth(), ymFormatter))
                        .filter(ym -> ym.compareTo(internshipYearMonth) > 0)
                        .sorted().findFirst().orElse(YearMonth.from(user.getCreateTime().toLocalDateTime()));
            }
        }
        if (firstRegularYearMonth != null && targetDate.getYear() == firstRegularYearMonth.getYear()) {
            return yearTime.multiply(BigDecimal.valueOf(12).subtract(BigDecimal.valueOf(firstRegularYearMonth.getMonthValue()).subtract(BigDecimal.ONE))).divide(BigDecimal.valueOf(12), 1, RoundingMode.DOWN);
        }
        return yearTime;
    }
    /**
     * 调休假扣除方法
     * @param attendanceLeave
     * @param onlyRollback