From 4d730af0447c686133130d0116a0fa3dd82c2dca Mon Sep 17 00:00:00 2001
From: BAOLH <baolh@yhzhg.cn>
Date: Tue, 10 Nov 2026 01:41:03 +0000
Subject: [PATCH] Merge branch 'wcd-2411-update' into wcd

---
 eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/impl/AttendanceOvertimeServiceImpl.java |  620 +++++++++++++++++++++++++++++++++++--------------------
 1 files changed, 390 insertions(+), 230 deletions(-)

diff --git a/eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/impl/AttendanceOvertimeServiceImpl.java b/eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/impl/AttendanceOvertimeServiceImpl.java
index f9d2448..d1b4e5a 100644
--- a/eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/impl/AttendanceOvertimeServiceImpl.java
+++ b/eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/attendance/service/impl/AttendanceOvertimeServiceImpl.java
@@ -1,231 +1,391 @@
-/*
-*  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.attendance.service.impl;
-
-import lombok.RequiredArgsConstructor;
-import me.zhengjie.exception.BadRequestException;
-import me.zhengjie.modules.attendance.domain.*;
-import me.zhengjie.modules.attendance.repository.AttendanceOvertimeRepository;
-import me.zhengjie.modules.attendance.repository.AttendanceRepository;
-import me.zhengjie.modules.attendance.service.AttendanceOvertimeService;
-import me.zhengjie.modules.attendance.service.dto.AttendanceGoOutDto;
-import me.zhengjie.modules.attendance.service.dto.AttendanceOvertimeDto;
-import me.zhengjie.modules.attendance.service.dto.AttendanceOvertimeQueryCriteria;
-import me.zhengjie.modules.attendance.service.mapstruct.AttendanceOvertimeMapper;
-import me.zhengjie.modules.constant.Constant;
-import me.zhengjie.modules.quartz.service.OpaiDingTalkService;
-import me.zhengjie.modules.system.domain.Role;
-import me.zhengjie.modules.system.domain.SysRostering;
-import me.zhengjie.modules.system.domain.User;
-import me.zhengjie.modules.system.repository.UserRepository;
-import me.zhengjie.utils.*;
-import org.apache.commons.lang3.ObjectUtils;
-import org.springframework.data.domain.Page;
-import org.springframework.data.domain.Pageable;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.math.BigDecimal;
-import java.text.SimpleDateFormat;
-import java.time.Duration;
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Function;
-
-/**
-* @website https://eladmin.vip
-* @description 服务实现
-* @author weicd
-* @date 2023-11-24
-**/
-@Service
-@RequiredArgsConstructor
-public class AttendanceOvertimeServiceImpl implements AttendanceOvertimeService {
-
-    private final AttendanceOvertimeRepository attendanceOvertimeRepository;
-    private final AttendanceOvertimeMapper attendanceOvertimeMapper;
-    private final AttendanceRepository attendanceRepository;
-    private final UserRepository userRepository;
-    private final OpaiDingTalkService opaiDingTalkService;
-
-    @Override
-    public Map<String,Object> queryAll(AttendanceOvertimeQueryCriteria criteria, Pageable pageable){
-        Page<AttendanceOvertime> page = attendanceOvertimeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
-        //将实体转换为Dto(重写)
-        Function<AttendanceOvertime, AttendanceOvertimeDto> func = new Function<AttendanceOvertime, AttendanceOvertimeDto>(){
-
-            @Override
-            public AttendanceOvertimeDto apply(AttendanceOvertime attendanceOvertime) {
-                // 将实体类转换成DTO
-                AttendanceOvertimeDto attendanceOvertimeDto = attendanceOvertimeMapper.toDto(attendanceOvertime);
-                //查询用户信息
-                User user = userRepository.findById(attendanceOvertimeDto.getUserId()).orElseGet(User::new);
-                attendanceOvertimeDto.setUserName(user.getNickName());
-                //查询审批用户名
-                User appUser = userRepository.findById(attendanceOvertimeDto.getApprovalUserId()).orElseGet(User::new);
-                attendanceOvertimeDto.setAppUserName(appUser.getNickName());
-                return attendanceOvertimeDto;
-            }
-        };
-        return PageUtil.toPage(page.map(func));
-    }
-
-    @Override
-    public List<AttendanceOvertimeDto> queryAll(AttendanceOvertimeQueryCriteria criteria){
-        return attendanceOvertimeMapper.toDto(attendanceOvertimeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
-    }
-
-    @Override
-    @Transactional
-    public AttendanceOvertimeDto findById(Long id) {
-        AttendanceOvertime attendanceOvertime = attendanceOvertimeRepository.findById(id).orElseGet(AttendanceOvertime::new);
-        ValidationUtil.isNull(attendanceOvertime.getId(),"AttendanceOvertime","id",id);
-        return attendanceOvertimeMapper.toDto(attendanceOvertime);
-    }
-
-    @Override
-    @Transactional(rollbackFor = Exception.class)
-    public AttendanceOvertimeDto create(AttendanceOvertime resources) throws Exception {
-
-        //查询考勤表是否有记录
-        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-        String attDate = sdf.format(resources.getOvertimeStartTime());
-//        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(),attDate.substring(0,10));
-//        if(ObjectUtils.isEmpty(attendance)){
-//            throw new BadRequestException("考勤记录不存在");
-//        }
-
-        resources.setApprovalStatus(Constant.OVERTIME_APPROVAL);
-
-        //发送给审批者
-        List<String> sendList = new ArrayList<>();
-        //查询申请人信息
-        User user = userRepository.getOne(resources.getUserId());
-        //查询审批者信息
-        User appUser = userRepository.getOne(resources.getApprovalUserId());
-        sendList.add(appUser.getDingding());
-        opaiDingTalkService.sendNotice(sendList, "审批提醒", "### 审批提示 \n  >" + user.getNickName() + " 提交了加班审批,请登录PMS系统处理", "card");
-
-        return attendanceOvertimeMapper.toDto(attendanceOvertimeRepository.save(resources));
-    }
-
-    @Override
-    @Transactional(rollbackFor = Exception.class)
-    public void update(AttendanceOvertime resources) {
-        AttendanceOvertime attendanceOvertime = attendanceOvertimeRepository.findById(resources.getId()).orElseGet(AttendanceOvertime::new);
-        ValidationUtil.isNull( attendanceOvertime.getId(),"AttendanceOvertime","id",resources.getId());
-        attendanceOvertime.copy(resources);
-
-        //审核通过或者退回不能修改
-        if(attendanceOvertime.getApprovalStatus().equals(Constant.OVERTIME_PASS) || attendanceOvertime.getApprovalStatus().equals(Constant.OVERTIME_RETURN)){
-            throw new BadRequestException("审核通过或退回的不能进行修改");
-        }
-
-        //获取当前登入人信息
-        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 (!Long.valueOf(resources.getUserId()).equals(SecurityUtils.getCurrentUserId())){
-                throw new BadRequestException("只能修改自己的记录");
-            }
-        }
-
-        //查询考勤表是否有记录
-        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-//        String attDate = sdf.format(resources.getOvertimeStartTime());
-//        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(),attDate.substring(0,10));
-//        if(ObjectUtils.isEmpty(attendance)){
-//            throw new BadRequestException("考勤记录不存在");
-//        }
-
-        attendanceOvertimeRepository.save(attendanceOvertime);
-    }
-
-    @Override
-    public void deleteAll(Long[] ids) {
-        for (Long id : ids) {
-            attendanceOvertimeRepository.deleteById(id);
-        }
-    }
-
-    @Override
-    public void download(List<AttendanceOvertimeDto> all, HttpServletResponse response) throws IOException {
-        List<Map<String, Object>> list = new ArrayList<>();
-        for (AttendanceOvertimeDto attendanceOvertime : all) {
-            Map<String,Object> map = new LinkedHashMap<>();
-            map.put("用户ID", attendanceOvertime.getUserId());
-            map.put("审批用户ID", attendanceOvertime.getApprovalUserId());
-            map.put("加班开始时间", attendanceOvertime.getOvertimeStartTime());
-            map.put("加班结束时间", attendanceOvertime.getOvertimeEndTime());
-            map.put("加班时长", attendanceOvertime.getOvertimeDuration());
-            map.put("加班时长单位", attendanceOvertime.getOvertimeDurationUnit());
-            map.put("审批状态", attendanceOvertime.getApprovalStatus());
-            map.put("审批说明", attendanceOvertime.getApprovalDescription());
-            map.put("备注", attendanceOvertime.getRemarks());
-            list.add(map);
-        }
-        FileUtil.downloadExcel(list, response);
-    }
-
-    /**
-     * 计算加班时长
-     * @param resources
-     * @return
-     */
-    @Override
-    public AttendanceOvertimeDto calcTimeLength(AttendanceOvertime resources) {
-        AttendanceOvertimeDto attendanceOvertimeDto = new AttendanceOvertimeDto();
-        User userInfo = userRepository.getOne(resources.getUserId());
-        SysRostering sysRostering = userInfo.getSysRostering();
-
-        long minutes = 0;
-
-        if ((resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().isBefore(sysRostering.getLunchStartTime()) || resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchStartTime()))
-                && (resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().isAfter(sysRostering.getLunchEndTime()) || resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchEndTime()) )) {
-            minutes = Duration.between(resources.getOvertimeStartTime().toLocalDateTime(), resources.getOvertimeEndTime().toLocalDateTime()).toMinutes() - 60;
-        } else if (resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().isBefore(sysRostering.getLunchStartTime()) || resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchStartTime()) ||
-                resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().isAfter(sysRostering.getLunchEndTime()) || resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchEndTime())) {
-            minutes = Duration.between(resources.getOvertimeStartTime().toLocalDateTime(), resources.getOvertimeEndTime().toLocalDateTime()).toMinutes();
-        } else if (resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().isBefore(sysRostering.getLunchStartTime()) && resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().isAfter(sysRostering.getLunchStartTime()) &&
-                (resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchEndTime()) || resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().isBefore(sysRostering.getLunchEndTime()))){
-            minutes = Duration.between(resources.getOvertimeStartTime().toLocalDateTime().toLocalTime(), sysRostering.getLunchStartTime()).toMinutes();
-        } else if ((resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().isBefore(sysRostering.getLunchStartTime()) || resources.getOvertimeStartTime().toLocalDateTime().toLocalTime().equals(sysRostering.getLunchStartTime())) && resources.getOvertimeEndTime().toLocalDateTime().toLocalTime().isAfter(sysRostering.getLunchEndTime())) {
-            minutes = Duration.between(sysRostering.getLunchEndTime(), resources.getOvertimeEndTime().toLocalDateTime()).toMinutes();
-        }
-
-        double hours = new BigDecimal((double) minutes / 60).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
-
-        attendanceOvertimeDto.setOvertimeDuration(hours);
-        return attendanceOvertimeDto;
-    }
-
-    /**
-     * 审核
-     * @param resources /
-     */
-    @Override
-    public void updateApprove(AttendanceOvertime resources) {
-        AttendanceOvertime attendanceOvertime = attendanceOvertimeRepository.findById(resources.getId()).orElseGet(AttendanceOvertime::new);
-        ValidationUtil.isNull( attendanceOvertime.getId(),"AttendanceOvertime","id",resources.getId());
-        attendanceOvertime.copy(resources);
-        attendanceOvertimeRepository.save(attendanceOvertime);
-    }
+/*
+*  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.attendance.service.impl;
+
+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.mapstruct.ApproveEventMapper;
+import me.zhengjie.modules.attendance.domain.*;
+import me.zhengjie.modules.attendance.repository.AttendanceGoOutRepository;
+import me.zhengjie.modules.attendance.repository.AttendanceOvertimeRepository;
+import me.zhengjie.modules.attendance.repository.AttendanceRepository;
+import me.zhengjie.modules.attendance.repository.OvertimeConsumedRecordRepository;
+import me.zhengjie.modules.attendance.service.AttendanceOvertimeService;
+import me.zhengjie.modules.attendance.service.dto.*;
+import me.zhengjie.modules.attendance.service.mapstruct.AttendanceOvertimeMapper;
+import me.zhengjie.modules.constant.Constant;
+import me.zhengjie.modules.salary.domain.NewSalary;
+import me.zhengjie.modules.salary.repository.NewSalaryRepository;
+import me.zhengjie.modules.system.domain.*;
+import me.zhengjie.modules.system.repository.DictDetailRepository;
+import me.zhengjie.modules.system.repository.SysConfigHolidayRepository;
+import me.zhengjie.modules.system.repository.UserRepository;
+import me.zhengjie.utils.*;
+import org.apache.commons.lang3.ObjectUtils;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.Pageable;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.sql.Timestamp;
+import java.time.*;
+import java.time.format.DateTimeFormatter;
+import java.time.temporal.ChronoUnit;
+import java.util.*;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/**
+* @website https://eladmin.vip
+* @description 服务实现
+* @author weicd
+* @date 2023-11-24
+**/
+@Service
+@RequiredArgsConstructor
+public class AttendanceOvertimeServiceImpl implements AttendanceOvertimeService {
+
+    private final AttendanceOvertimeRepository attendanceOvertimeRepository;
+    private final AttendanceOvertimeMapper attendanceOvertimeMapper;
+    private final AttendanceRepository attendanceRepository;
+    private final DictDetailRepository dictDetailRepository;
+    private final UserRepository userRepository;
+    private final SysConfigHolidayRepository sysConfigHolidayRepository;
+    private final ApproveEventRepository approveEventRepository;
+    private final OvertimeConsumedRecordRepository overtimeConsumedRecordRepository;
+    private final AttendanceGoOutRepository attendanceGoOutRepository;
+    private final NewSalaryRepository newSalaryRepository;
+    private final ApproveEventMapper approveEventMapper;
+    private final TemplateControlFieldService templateControlFieldService;
+
+    @Override
+    public Map<String,Object> queryAll(AttendanceOvertimeQueryCriteria criteria, Pageable pageable){
+        Page<AttendanceOvertime> page = attendanceOvertimeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
+        //将实体转换为Dto(重写)
+        Function<AttendanceOvertime, AttendanceOvertimeDto> func = new Function<AttendanceOvertime, AttendanceOvertimeDto>(){
+
+            @Override
+            public AttendanceOvertimeDto apply(AttendanceOvertime attendanceOvertime) {
+                // 将实体类转换成DTO
+                AttendanceOvertimeDto attendanceOvertimeDto = attendanceOvertimeMapper.toDto(attendanceOvertime);
+                //查询用户信息
+                User user = userRepository.findById(attendanceOvertimeDto.getUserId()).orElseGet(User::new);
+                attendanceOvertimeDto.setUserName(user.getNickName());
+                //查询审批用户名
+                User appUser = userRepository.findById(attendanceOvertimeDto.getApprovalUserId()).orElseGet(User::new);
+                attendanceOvertimeDto.setAppUserName(appUser.getNickName());
+
+                // 查询企微最新审批变化记录
+                if (ObjectUtils.isNotEmpty(attendanceOvertime.getWecomEventId())) {
+                    ApproveEvent event = approveEventRepository.findById(attendanceOvertime.getWecomEventId()).orElseGet(ApproveEvent::new);
+                    attendanceOvertimeDto.setEvent(approveEventMapper.toDto(event));
+                }
+
+                return attendanceOvertimeDto;
+            }
+        };
+        return PageUtil.toPage(page.map(func));
+    }
+
+    @Override
+    public List<AttendanceOvertimeDto> queryAll(AttendanceOvertimeQueryCriteria criteria) {
+        List<AttendanceOvertimeDto> attendanceOvertimeDtoList = attendanceOvertimeMapper.toDto(attendanceOvertimeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
+        attendanceOvertimeDtoList.forEach(attendanceOvertimeDto -> {
+            //查询用户信息
+            User user = userRepository.findById(attendanceOvertimeDto.getUserId()).orElseGet(User::new);
+            attendanceOvertimeDto.setUserName(user.getNickName());
+            //查询审批用户名
+            User appUser = userRepository.findById(attendanceOvertimeDto.getApprovalUserId()).orElseGet(User::new);
+            attendanceOvertimeDto.setAppUserName(appUser.getNickName());
+        });
+        return attendanceOvertimeDtoList;
+    }
+
+    @Override
+    @Transactional
+    public AttendanceOvertimeDto findById(Long id) {
+        AttendanceOvertime attendanceOvertime = attendanceOvertimeRepository.findById(id).orElseGet(AttendanceOvertime::new);
+        ValidationUtil.isNull(attendanceOvertime.getId(),"AttendanceOvertime","id",id);
+        return attendanceOvertimeMapper.toDto(attendanceOvertime);
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public AttendanceOvertimeDto create(AttendanceOvertime resources) {
+//        // 查询考勤表是否有记录
+//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+//        String attDate = sdf.format(resources.getOvertimeStartTime());
+//        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(),attDate.substring(0,10));
+//        if(ObjectUtils.isEmpty(attendance)){
+//            throw new BadRequestException("考勤记录不存在");
+//        }
+
+        // 检验数据
+        checkPrecondition(resources);
+
+        // 查询日期配置
+        SysConfigHoliday sysConfigHoliday = sysConfigHolidayRepository.findByHolidayDate(resources.getOvertimeStartTime().toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
+        if (sysConfigHoliday != null && sysConfigHoliday.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS)) {
+            resources.setDateType(Constant.DATE_TYPE_LEGAL_HOLIDAYS);
+        } else {
+            resources.setDateType(Constant.DATE_TYPE_WEEKEND);
+        }
+        resources.setApprovalStatus(Constant.OVERTIME_APPROVAL);
+        resources.setRemainingDuration(resources.getOvertimeDuration());
+
+        // 判断是否提交企微审批
+        List<DictDetail> siteTypes = dictDetailRepository.findByDictName(Constant.APPROVAL_SITE_TYPE).stream().filter(siteType -> siteType.getValue().toLowerCase().equals("wecom")).collect(Collectors.toList());
+        if (siteTypes.size() > 0) {
+            String approvalWeComId = userRepository.findById(resources.getApprovalUserId()).orElse(new User()).getWeComId();
+            // 添加企微申请参数
+            resources.setWecomDateType(ElAdminConstant.Constant.TEMPLATE_DATE_RANGE_TYPE_HOUR);
+            resources.setWecomDuration(String.valueOf(new BigDecimal(resources.getOvertimeDuration()).multiply(new BigDecimal(3600)).longValue()));
+            resources.setWecomAttendanceType("5");
+            resources.setWecomApproveWecomId(approvalWeComId);
+            // 提交申请
+            String weComId = userRepository.findById(resources.getUserId()).orElse(new User()).getWeComId();
+            Map<String, String> approvalResultMap = templateControlFieldService.createWecomApproval(resources, weComId);
+            if (approvalResultMap.containsKey("spNo")) {
+                resources.setWecomSpNo(approvalResultMap.get("spNo"));
+            } else {
+                throw new BadRequestException(approvalResultMap.containsKey("error") ? approvalResultMap.get("error") : "企微申请提交失败");
+            }
+        }
+
+        return attendanceOvertimeMapper.toDto(attendanceOvertimeRepository.save(resources));
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public void update(AttendanceOvertime resources) {
+        AttendanceOvertime attendanceOvertime = attendanceOvertimeRepository.findById(resources.getId()).orElseGet(AttendanceOvertime::new);
+        ValidationUtil.isNull( attendanceOvertime.getId(),"AttendanceOvertime","id",resources.getId());
+        attendanceOvertime.copy(resources);
+
+        // 审核通过或者退回不能修改
+        if(attendanceOvertime.getApprovalStatus().equals(Constant.OVERTIME_PASS) || attendanceOvertime.getApprovalStatus().equals(Constant.OVERTIME_RETURN)){
+            throw new BadRequestException("审核通过或退回的不能进行修改");
+        }
+
+        // 检验数据
+        checkPrecondition(resources);
+
+        SysConfigHoliday sysConfigHoliday = sysConfigHolidayRepository.findByHolidayDate(resources.getOvertimeStartTime().toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
+        if (sysConfigHoliday != null && sysConfigHoliday.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS)) {
+            resources.setDateType(Constant.DATE_TYPE_LEGAL_HOLIDAYS);
+        } else {
+            resources.setDateType(Constant.DATE_TYPE_WEEKEND);
+        }
+
+        //获取当前登入人信息
+        User user1 = userRepository.getOne(SecurityUtils.getCurrentUserId());
+        Role role = user1.getRoles().iterator().next();
+        // 除超管、总经理只能修改自己信息
+        if (!Constant.SUPER_LEVEL_LIST.contains(Long.valueOf(role.getLevel()))) {
+            if (!Long.valueOf(resources.getUserId()).equals(SecurityUtils.getCurrentUserId())){
+                throw new BadRequestException("只能修改自己的记录");
+            }
+        }
+
+//        //查询考勤表是否有记录
+//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+//        String attDate = sdf.format(resources.getOvertimeStartTime());
+//        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(),attDate.substring(0,10));
+//        if(ObjectUtils.isEmpty(attendance)){
+//            throw new BadRequestException("考勤记录不存在");
+//        }
+
+        attendanceOvertimeRepository.save(attendanceOvertime);
+    }
+
+    @Override
+    public void deleteAll(Long[] ids) {
+        for (Long id : ids) {
+            attendanceOvertimeRepository.deleteById(id);
+        }
+    }
+
+    @Override
+    public void download(List<AttendanceOvertimeDto> all, HttpServletResponse response) throws IOException {
+        List<Map<String, Object>> list = new ArrayList<>();
+        for (AttendanceOvertimeDto attendanceOvertime : all) {
+            String overtimeStatus = attendanceOvertime.getApprovalStatus() != null ? dictDetailRepository.findByDictNameAndValue("overtime_status", attendanceOvertime.getApprovalStatus()).getLabel() : "";
+            Map<String,Object> map = new LinkedHashMap<>();
+            map.put("申请者", attendanceOvertime.getUserName());
+            map.put("审批者", attendanceOvertime.getAppUserName());
+            map.put("加班开始时间", attendanceOvertime.getOvertimeStartTime());
+            map.put("加班结束时间", attendanceOvertime.getOvertimeEndTime());
+            map.put("加班时长", attendanceOvertime.getOvertimeDuration());
+            map.put("加班时长单位", attendanceOvertime.getOvertimeDurationUnit());
+            map.put("审批状态", overtimeStatus);
+            map.put("审批说明", attendanceOvertime.getApprovalDescription());
+            map.put("备注", attendanceOvertime.getRemarks());
+            list.add(map);
+        }
+        FileUtil.downloadExcel(list, response);
+    }
+
+    /**
+     * 计算加班时长
+     * @param resources
+     * @return
+     */
+    @Override
+    public AttendanceOvertimeDto calcTimeLength(AttendanceOvertime resources) {
+        AttendanceOvertimeDto attendanceOvertimeDto = new AttendanceOvertimeDto();
+        User userInfo = userRepository.getOne(resources.getUserId());
+        SysRostering sysRostering = userInfo.getSysRostering();
+
+        // 获取开始与结束之间所有的日期
+        List<LocalDate> allDates = new ArrayList<>();
+        LocalDate currentDate = resources.getOvertimeStartTime().toLocalDateTime().toLocalDate();
+        while (!currentDate.isAfter(resources.getOvertimeEndTime().toLocalDateTime().toLocalDate())) {
+            allDates.add(currentDate);
+            currentDate = currentDate.plusDays(1);
+        }
+        // 先排除工作日、日期类型为工作日的休息日(节假日和双休日)
+        List<SysConfigHoliday> sysConfigHolidays = sysConfigHolidayRepository.findByHolidayDateBetween(Timestamp.valueOf(resources.getOvertimeStartTime().toLocalDateTime().toLocalDate().atStartOfDay()), Timestamp.valueOf(resources.getOvertimeEndTime().toLocalDateTime().toLocalDate().atStartOfDay()));
+        Map<LocalDate, String> sysConfigHolidaysMap = sysConfigHolidays.stream().collect(Collectors.toMap(sch -> sch.getHolidayDate().toLocalDateTime().toLocalDate(), SysConfigHoliday::getDateType));
+        List<LocalDate> overtimeDates = allDates;
+
+        List<Calculate> resultParts = new ArrayList<>();
+        List<Calculate> attendanceOvertimeParts = new ArrayList<>();
+        List<Calculate> breakParts = new ArrayList<>();
+        for (LocalDate date : overtimeDates) {
+            // 休息时间管理
+            if ((sysConfigHolidaysMap.containsKey(date) && sysConfigHolidaysMap.get(date).equals(Constant.DATE_TYPE_WEEKDAY)) ||
+                    (!(sysConfigHolidaysMap.containsKey(date) && (sysConfigHolidaysMap.get(date).equals(Constant.DATE_TYPE_WEEKEND) || sysConfigHolidaysMap.get(date).equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS))) && !(date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY))
+            ) {
+                // 工作日(过0点上班时间和下班后30分钟,未过0点跳过统计)
+                if (overtimeDates.size() > 1) {
+                    breakParts.add(new Calculate(date.atTime(sysRostering.getWorkStartTime()), date.atTime(sysRostering.getWorkEndTime()).plusMinutes(30)));
+                } else {
+                    continue;
+                }
+            } else {
+                // 休息日(午休和下班后30分钟)
+                breakParts.add(new Calculate(date.atTime(sysRostering.getLunchStartTime()), date.atTime(sysRostering.getLunchEndTime())));
+                breakParts.add(new Calculate(date.atTime(sysRostering.getWorkEndTime()), date.atTime(sysRostering.getWorkEndTime()).plusMinutes(30)));
+            }
+
+            // 全部加班时间管理
+            LocalDateTime startTime = date.atStartOfDay();
+            LocalDateTime endTime = date.atTime(LocalTime.MAX);
+            if (resources.getOvertimeStartTime().toLocalDateTime().toLocalDate().equals(date)) {
+                startTime = resources.getOvertimeStartTime().toLocalDateTime();
+            }
+            if (resources.getOvertimeEndTime().toLocalDateTime().toLocalDate().equals(date)) {
+                endTime = resources.getOvertimeEndTime().toLocalDateTime();
+            }
+            attendanceOvertimeParts.add(new Calculate(startTime, endTime));
+        }
+        attendanceOvertimeParts.stream().sorted().reduce(new Stack<Calculate>(), (result, current) -> {
+            // 删除重复时间,合并相连的时间段
+            if (result.empty()) {
+                result.push(current);
+                return result;
+            }
+            Calculate last = result.peek();
+            if (last.getEnd().isBefore(current.getStart())) {
+                result.push(current);
+            } else if (last.getEnd().isBefore(current.getEnd())) {
+                last.setEnd(current.getEnd());
+            }
+            return result;
+        }, (o1, o2) -> null).forEach(calculate -> {
+            List<Calculate> currentParts = new ArrayList<>();
+            currentParts.add(calculate);
+            // 去除休息时间:午休、下班后30分钟等
+            for (Calculate breakPart : breakParts) {
+                List<Calculate> tempParts = new ArrayList<>();
+                for (Calculate current : currentParts) {
+                    if ((current.getStart().isBefore(breakPart.getStart()) && current.getEnd().isAfter(breakPart.getStart()))
+                            || (current.getStart().isBefore(breakPart.getEnd()) && current.getEnd().isAfter(breakPart.getEnd()))) {
+                        Calculate calculate1 = new Calculate(current.getStart(), breakPart.getStart());
+                        Calculate calculate2 = new Calculate(breakPart.getEnd(), current.getEnd());
+                        if (calculate1.getStart().isBefore(calculate1.getEnd())) {
+                            tempParts.add(calculate1);
+                        }
+                        if (calculate2.getStart().isBefore(calculate2.getEnd())) {
+                            tempParts.add(calculate2);
+                        }
+                    } else {
+                        tempParts.add(current);
+                    }
+                }
+                currentParts = tempParts;
+            }
+            // 将处理完所有休息区间后的结果添加到最终结果
+            resultParts.addAll(currentParts);
+
+        });
+
+        BigDecimal resultTime = resultParts.stream()
+                .map(calculate -> ChronoUnit.SECONDS.between(calculate.getStart(), calculate.getEnd()))
+                .reduce(new BigDecimal(0),
+                        (total, current) -> total.add(BigDecimal.valueOf(current)),
+                        BigDecimal::add)
+                .divide(BigDecimal.valueOf(3600), 2, RoundingMode.HALF_UP
+                );
+
+        attendanceOvertimeDto.setOvertimeDuration(resultTime.max(BigDecimal.ZERO).doubleValue());
+        return attendanceOvertimeDto;
+    }
+
+    /**
+     * 审核
+     * @param resources /
+     */
+    @Override
+    public void updateApprove(AttendanceOvertime resources) {
+        AttendanceOvertime attendanceOvertime = attendanceOvertimeRepository.findById(resources.getId()).orElseGet(AttendanceOvertime::new);
+        ValidationUtil.isNull( attendanceOvertime.getId(),"AttendanceOvertime","id",resources.getId());
+        attendanceOvertime.copy(resources);
+        if (attendanceOvertime.getApprovalStatus().equals(Constant.OVERTIME_APPROVAL) || attendanceOvertime.getApprovalStatus().equals(Constant.OVERTIME_RETURN)) {
+            OvertimeConsumedRecordQueryCriteria consumedCriteria = new OvertimeConsumedRecordQueryCriteria();
+            consumedCriteria.setOvertimeId(attendanceOvertime.getId());
+            Long haveCount = overtimeConsumedRecordRepository.count((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, consumedCriteria, criteriaBuilder));
+            if (haveCount > 0) {
+                throw new BadRequestException("调休时长已占用,不可撤销");
+            }
+        }
+        attendanceOvertimeRepository.save(attendanceOvertime);
+    }
+
+    public void checkPrecondition(AttendanceOvertime resources) {
+        // 验证是否有对应的考勤或外出记录
+        Attendance attendance = attendanceRepository.findAllByUserIdAndAttendanceDate(resources.getUserId(), resources.getOvertimeStartTime().toLocalDateTime().toLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
+        List<AttendanceGoOut> attendanceGoOutList = attendanceGoOutRepository.findByUserAndDate(resources.getUserId(), resources.getOvertimeStartTime().toLocalDateTime(), resources.getOvertimeEndTime().toLocalDateTime());
+        Boolean attendanceFlag = attendance == null || attendance.getActualWorkStartTime() == null || attendance.getActualWorkEndTime() == null || attendance.getActualWorkStartTime().toLocalDateTime().compareTo(resources.getOvertimeStartTime().toLocalDateTime()) > 0 || attendance.getActualWorkEndTime().toLocalDateTime().compareTo(resources.getOvertimeEndTime().toLocalDateTime()) < 0;
+        Boolean attendanceGoOutFlag = attendanceGoOutList.isEmpty() || resources.getOvertimeDuration() > attendanceGoOutList.stream().collect(Collectors.summingDouble(AttendanceGoOut::getOutDuration)) || resources.getOvertimeStartTime().compareTo(attendanceGoOutList.stream().map(AttendanceGoOut::getOutStartTime).min(Timestamp::compareTo).orElse(null)) < 0 || resources.getOvertimeEndTime().compareTo(attendanceGoOutList.stream().map(AttendanceGoOut::getOutEndTime).max(Timestamp::compareTo).orElse(null)) > 0;
+        if (attendanceFlag && attendanceGoOutFlag) {
+            throw new BadRequestException("缺少对应的考勤记录或外出记录。");
+        }
+
+        // 验证工资是否已结算(如已结算不可创建,因调休可能会和加班时间重合)
+        List<NewSalary> salaryList = newSalaryRepository.findByUserIdAndSalaryYearMonth(resources.getUserId(), Timestamp.valueOf(resources.getOvertimeStartTime().toLocalDateTime().toLocalDate().withDayOfMonth(1).atStartOfDay()));
+        if (salaryList.size() > 0) {
+            throw new BadRequestException("该月工资信息已生成,请确认后重试。");
+        }
+    }
 }
\ No newline at end of file

--
Gitblit v1.9.3