/* * 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 me.zhengjie.exception.BadRequestException; import me.zhengjie.modules.attendance.domain.Attendance; import me.zhengjie.modules.attendance.domain.AttendanceLeave; import me.zhengjie.modules.attendance.domain.Calculate; import me.zhengjie.modules.attendance.service.AttendanceService; import me.zhengjie.modules.attendance.service.dto.AttendanceDto; import me.zhengjie.modules.constant.Constant; import me.zhengjie.modules.quartz.service.OpaiDingTalkService; import me.zhengjie.modules.system.domain.DictDetail; import me.zhengjie.modules.system.domain.SysUserLevelOther; import me.zhengjie.modules.system.domain.User; import me.zhengjie.modules.system.repository.DictDetailRepository; import me.zhengjie.modules.system.repository.SysUserLevelOtherRepository; import me.zhengjie.modules.system.repository.UserRepository; import me.zhengjie.utils.*; import lombok.RequiredArgsConstructor; import me.zhengjie.modules.attendance.repository.AttendanceLeaveRepository; import me.zhengjie.modules.attendance.service.AttendanceLeaveService; import me.zhengjie.modules.attendance.service.dto.AttendanceLeaveDto; import me.zhengjie.modules.attendance.service.dto.AttendanceLeaveQueryCriteria; import me.zhengjie.modules.attendance.service.mapstruct.AttendanceLeaveMapper; import org.apache.commons.lang3.ObjectUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.*; import java.io.IOException; import java.util.function.Function; import javax.servlet.http.HttpServletResponse; /** * @website https://eladmin.vip * @description 服务实现 * @author wcd * @date 2022-12-16 **/ @Service @RequiredArgsConstructor public class AttendanceLeaveServiceImpl implements AttendanceLeaveService { private final AttendanceLeaveRepository attendanceLeaveRepository; private final AttendanceLeaveMapper attendanceLeaveMapper; private final DictDetailRepository dictDetailRepository; private final AttendanceService attendanceService; private final SysUserLevelOtherRepository sysUserLevelOtherRepository; private final UserRepository userRepository; private final OpaiDingTalkService opaiDingTalkService; @Override public Map queryAll(AttendanceLeaveQueryCriteria criteria, Pageable pageable){ Page page = attendanceLeaveRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable); //将实体转换为Dto(重写) Function func = new Function(){ @Override public AttendanceLeaveDto apply(AttendanceLeave attendanceLeave) { // 将实体类转换成DTO AttendanceLeaveDto attendanceLeaveDto = attendanceLeaveMapper.toDto(attendanceLeave); //查询用户信息 User user = userRepository.findById(attendanceLeaveDto.getUserId()).orElseGet(User::new); attendanceLeaveDto.setUserName(user.getNickName()); //查询审批用户名 User appUser = userRepository.findById(attendanceLeaveDto.getApprovalUserId()).orElseGet(User::new); attendanceLeaveDto.setAppUserName(appUser.getNickName()); return attendanceLeaveDto; } }; return PageUtil.toPage(page.map(func)); } @Override public List queryAll(AttendanceLeaveQueryCriteria criteria){ return attendanceLeaveMapper.toDto(attendanceLeaveRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder))); } @Override @Transactional public AttendanceLeaveDto findById(Long id) { AttendanceLeave attendanceLeave = attendanceLeaveRepository.findById(id).orElseGet(AttendanceLeave::new); ValidationUtil.isNull(attendanceLeave.getId(),"AttendanceLeave","id",id); return attendanceLeaveMapper.toDto(attendanceLeave); } @Override @Transactional(rollbackFor = Exception.class) public AttendanceLeaveDto create(AttendanceLeave resources) throws Exception { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String LeaStartTime = df.format(resources.getLeaveStartTime()); String LeaEndTime = df.format(resources.getLeaveEndTime()); // 如果按天为单位请假拼接请假时间的时分秒,取上下班基准时间 if(resources.getLeaveDurationUnit().equals(Constant.LEAVE_TIME_TYPE_DAY)){ //查询用户的排班时间 User user = userRepository.getOne(SecurityUtils.getCurrentUserId()); LeaStartTime = LeaStartTime.substring(0,10) + " " + user.getSysRostering().getWorkStartTime().toString() + ":00"; LeaEndTime = LeaEndTime.substring(0,10) + " " + user.getSysRostering().getWorkEndTime().toString() + ":00"; } // 验证请假时间是否冲突 List attendanceLeaveList = attendanceLeaveRepository.checkCreateLeaveTime(LeaStartTime,LeaEndTime, SecurityUtils.getCurrentUserId()); if(attendanceLeaveList.size() > 0){ AttendanceLeave errTime = attendanceLeaveList.get(0); //LocalDateTime转换为Date LocalDateTime strartTime = errTime.getLeaveStartTime().toLocalDateTime(); ZonedDateTime zonedDateTime = strartTime.atZone(ZoneId.systemDefault()); Instant instant = zonedDateTime.toInstant(); Date strTime = Date.from(instant); LocalDateTime endTime = errTime.getLeaveEndTime().toLocalDateTime(); ZonedDateTime zonedDateTime1 = endTime.atZone(ZoneId.systemDefault()); Instant instant1 = zonedDateTime1.toInstant(); Date endTim = Date.from(instant1); SimpleDateFormat errorFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); throw new BadRequestException("请假时间冲突," + errorFormat.format(strTime) + "至" + errorFormat.format(endTim) + "已经存在请假记录,请调整时间"); }else { // 获取当前登陆人信息,设置为请假发起人 User user = userRepository.getOne(SecurityUtils.getCurrentUserId()); resources.setUserId(user.getId()); resources.setApprovalStatus(Constant.APPROVAL_STATUS_UNDER_APPROVAL); //发送钉钉给审批人 List sendList = new ArrayList<>(); //查询审批者信息 User appUser = userRepository.getOne(resources.getApprovalUserId()); sendList.add(appUser.getDingding()); opaiDingTalkService.sendNotice(sendList, "审批提醒", "### 审批提示 \n >" + user.getNickName() + " 提交了请假审批,请登录PMS系统处理", "card"); return attendanceLeaveMapper.toDto(attendanceLeaveRepository.save(resources)); } } @Override @Transactional(rollbackFor = Exception.class) public void update(AttendanceLeave resources) { AttendanceLeave attendanceLeave = attendanceLeaveRepository.findById(resources.getId()).orElseGet(AttendanceLeave::new); ValidationUtil.isNull( attendanceLeave.getId(),"AttendanceLeave","id",resources.getId()); attendanceLeave.copy(resources); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String LeaStartTime = df.format(resources.getLeaveStartTime()); String LeaEndTime = df.format(resources.getLeaveEndTime()); // 验证是否存在时间冲突的请假记录 Set ids = new HashSet<>(); ids.add(attendanceLeave.getId()); List attendanceLeaveList = attendanceLeaveRepository.checkUpdateForLeaveTime(LeaStartTime, LeaEndTime, attendanceLeave.getUserId(), ids); if (attendanceLeaveList.size() > 0) { AttendanceLeave errorSysAskForLeave = attendanceLeaveList.get(0); SimpleDateFormat errorFormat = new SimpleDateFormat("yyyy年MM月dd日"); throw new BadRequestException("请假时间冲突," + errorFormat.format(errorSysAskForLeave.getLeaveStartTime()) + "至" + errorFormat.format(errorSysAskForLeave.getLeaveEndTime()) + "已经存在请假记录,请调整时间"); } attendanceLeaveRepository.save(attendanceLeave); } /** * 计算请假时长 * @param resources / * @return * @throws Exception */ @Override public AttendanceLeaveDto calcTimeLength(AttendanceLeave resources) throws Exception { AttendanceLeaveDto attendanceLeaveDto = new AttendanceLeaveDto(); //根据字典名称查询 List dictDetailList = dictDetailRepository.findByDictName("leave_type"); List leaveTypes = new ArrayList<>(); for(DictDetail dictDetail : dictDetailList){ if(dictDetail.getValue().equals(Constant.LEAVE_TYPE_ANNUAL_LEAVE) || dictDetail.getValue().equals(Constant.LEAVE_TYPE_COMPASSIONATE_LEAVE)){ //事假和年假 leaveTypes.add(dictDetail.getValue()); } } Calculate calculate = new Calculate(); calculate.setStart(resources.getLeaveStartTime().toLocalDateTime()); calculate.setEnd(resources.getLeaveEndTime().toLocalDateTime()); Double result = new Double(0.00); //判断集合是否包含年假或事假,包含计算以时为单位,反之以天为单位进行计算 if(leaveTypes.contains(resources.getLeaveType())){ Integer timeSeconds = attendanceService.calculateTimes(calculate, SecurityUtils.getCurrentUserId()); result = Double.valueOf(new BigDecimal((float) timeSeconds / 3600).setScale(2, BigDecimal.ROUND_HALF_UP).toString()); attendanceLeaveDto.setLeaveDurationUnit(Constant.LEAVE_TIME_TYPE_HOUR); }else{ Integer days = attendanceService.calculateDays(calculate); result = Double.valueOf(new BigDecimal(days).setScale(2, BigDecimal.ROUND_HALF_UP).toString()); attendanceLeaveDto.setLeaveDurationUnit(Constant.LEAVE_TIME_TYPE_DAY); } attendanceLeaveDto.setLeaveDuration(result); return attendanceLeaveDto; } /** * 获取用户年假剩余时长 */ @Override public Double getYearTimeLength() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 获取当前日期 Date date = new Date(); String nowTime = sdf.format(date); Date dateTime = sdf.parse(nowTime); Double surplusYearTime = new Double(0.00); // 查询用户剩余年假时长 List sysUserLevelOtherList = sysUserLevelOtherRepository.findByUserId(SecurityUtils.getCurrentUserId()); for(SysUserLevelOther sysUserLevelOther : sysUserLevelOtherList){ if(ObjectUtils.isNotEmpty(sysUserLevelOther.getStartDate()) && ObjectUtils.isNotEmpty(sysUserLevelOther.getEndDate())){ Date dateStart = new Date(sysUserLevelOther.getStartDate().getTime()); Date dateEnd = new Date(sysUserLevelOther.getEndDate().getTime()); //取当前日期在数据中开始日期与结束日期之间的数据 if(dateTime.compareTo(dateStart) >= 0 && dateTime.compareTo(dateEnd) <= 0){ //年假总时长 Double yearTime = Double.valueOf(sysUserLevelOther.getAnnualLeaveDays() == null ? 0 : sysUserLevelOther.getAnnualLeaveDays() * 8); //已使用年假时长 Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); 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; } /** * 审核功能 * @param resources / */ @Override public void updateApprove(AttendanceLeave resources) { AttendanceLeave attendanceLeave = attendanceLeaveRepository.findById(resources.getId()).orElseGet(AttendanceLeave::new); ValidationUtil.isNull( attendanceLeave.getId(),"AttendanceLeave","id",resources.getId()); attendanceLeave.copy(resources); attendanceLeaveRepository.save(attendanceLeave); } @Override public void deleteAll(Long[] ids) { for (Long id : ids) { attendanceLeaveRepository.deleteById(id); } } @Override public void download(List all, HttpServletResponse response) throws IOException { List> list = new ArrayList<>(); for (AttendanceLeaveDto attendanceLeave : all) { Map map = new LinkedHashMap<>(); map.put("用户ID", attendanceLeave.getUserId()); map.put("审批用户ID", attendanceLeave.getApprovalUserId()); map.put("请假类型", attendanceLeave.getLeaveType()); map.put("请假开始时间", attendanceLeave.getLeaveStartTime()); map.put("请假结束时间", attendanceLeave.getLeaveEndTime()); map.put("请假时长", attendanceLeave.getLeaveDuration()); map.put("请假原因", attendanceLeave.getLeaveReason()); map.put("审批状态", attendanceLeave.getApprovalStatus()); map.put("审批说明", attendanceLeave.getApprovalDescription()); map.put("备注", attendanceLeave.getRemarks()); map.put("创建者", attendanceLeave.getCreateBy()); map.put("创建时间", attendanceLeave.getCreateTime()); map.put("更新者", attendanceLeave.getUpdateBy()); map.put("更新时间", attendanceLeave.getUpdateTime()); list.add(map); } FileUtil.downloadExcel(list, response); } }