/* * 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.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.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.text.SimpleDateFormat; 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; import static cn.hutool.core.date.LocalDateTimeUtil.beginOfDay; import static cn.hutool.core.date.LocalDateTimeUtil.endOfDay; /** * @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 ApproveEventMapper approveEventMapper; private final TemplateControlFieldService templateControlFieldService; @Override public Map queryAll(AttendanceOvertimeQueryCriteria criteria, Pageable pageable){ Page page = attendanceOvertimeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable); //将实体转换为Dto(重写) Function func = new Function(){ @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 queryAll(AttendanceOvertimeQueryCriteria criteria) { List 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("考勤记录不存在"); // } 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); // 判断是否提交企微审批 List 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 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("审核通过或退回的不能进行修改"); } 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(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 all, HttpServletResponse response) throws IOException { List> list = new ArrayList<>(); for (AttendanceOvertimeDto attendanceOvertime : all) { String overtimeStatus = attendanceOvertime.getApprovalStatus() != null ? dictDetailRepository.findByDictNameAndValue("overtime_status", attendanceOvertime.getApprovalStatus()).getLabel() : ""; Map 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 allDates = new ArrayList<>(); LocalDate currentDate = resources.getOvertimeStartTime().toLocalDateTime().toLocalDate(); while (!currentDate.isAfter(resources.getOvertimeEndTime().toLocalDateTime().toLocalDate())) { allDates.add(currentDate); currentDate = currentDate.plusDays(1); } // 先排除工作日、日期类型为工作日的休息日(节假日和双休日) List sysConfigHolidays = sysConfigHolidayRepository.findByHolidayDateBetween(Timestamp.valueOf(resources.getOvertimeStartTime().toLocalDateTime().toLocalDate().atStartOfDay()), Timestamp.valueOf(resources.getOvertimeEndTime().toLocalDateTime().toLocalDate().atStartOfDay())); List overtimeDates = allDates.stream().filter(date -> { List workingHolidays = sysConfigHolidays.stream().filter( sysConfigHoliday -> sysConfigHoliday.getHolidayDate().toLocalDateTime().toLocalDate().equals(date) && sysConfigHoliday.getDateType().equals(Constant.DATE_TYPE_WEEKDAY)).collect(Collectors.toList()); if (!workingHolidays.isEmpty()) { return false; } List holidays = sysConfigHolidays.stream().filter( sysConfigHoliday -> sysConfigHoliday.getHolidayDate().toLocalDateTime().toLocalDate().equals(date) && (sysConfigHoliday.getDateType().equals(Constant.DATE_TYPE_WEEKEND) || sysConfigHoliday.getDateType().equals(Constant.DATE_TYPE_LEGAL_HOLIDAYS))).collect(Collectors.toList()); if (holidays.isEmpty() && !(date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)) { return false; } return true; }).collect(Collectors.toList()); List resultParts = new ArrayList<>(); BigDecimal resultTime = null; List attendanceOvertimeParts = new ArrayList<>(); List breakParts = new ArrayList<>(); for (LocalDate date : overtimeDates) { // 休息时间管理(午休和下班后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(), (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 currentParts = new ArrayList<>(); currentParts.add(calculate); // 去除休息时间:午休、下班后30分钟等 for (Calculate breakPart : breakParts) { List 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); }); 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); attendanceOvertimeRepository.save(attendanceOvertime); } }