package cn.iocoder.yudao.module.hrm.service.attendance; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.json.JSONUtil; import cn.iocoder.yudao.framework.common.util.object.BeanUtils; import cn.iocoder.yudao.module.hrm.controller.admin.attendance.vo.HrmEmployeeScheduleBatchSaveReqVO; import cn.iocoder.yudao.module.hrm.controller.admin.attendance.vo.HrmEmployeeScheduleBatchSaveRespVO; import cn.iocoder.yudao.module.hrm.controller.admin.attendance.vo.HrmEmployeeScheduleLeaveRespVO; import cn.iocoder.yudao.module.hrm.controller.admin.attendance.vo.HrmEmployeeScheduleListReqVO; import cn.iocoder.yudao.module.hrm.controller.admin.attendance.vo.HrmEmployeeScheduleRespVO; import cn.iocoder.yudao.module.hrm.controller.admin.attendance.vo.HrmEmployeeScheduleSaveReqVO; import cn.iocoder.yudao.module.hrm.dal.dataobject.approval.HrmLeaveApplicationDO; import cn.iocoder.yudao.module.hrm.dal.dataobject.attendance.HrmAttendanceHolidayDO; import cn.iocoder.yudao.module.hrm.dal.dataobject.attendance.HrmEmployeeScheduleDO; import cn.iocoder.yudao.module.hrm.dal.dataobject.attendance.HrmRestModeDO; import cn.iocoder.yudao.module.hrm.dal.dataobject.attendance.HrmShiftDO; import cn.iocoder.yudao.module.hrm.util.HrmRestModeUtils; import cn.iocoder.yudao.module.hrm.dal.dataobject.employee.HrmEmployeeDO; import cn.iocoder.yudao.module.hrm.dal.mysql.approval.HrmLeaveApplicationMapper; import cn.iocoder.yudao.module.hrm.enums.HrmAttendanceHolidayTypeEnum; import cn.iocoder.yudao.module.hrm.enums.HrmLeaveTypeEnum; import cn.iocoder.yudao.module.hrm.enums.HrmRestModeTypeEnum; import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX; import cn.iocoder.yudao.module.hrm.dal.mysql.attendance.HrmEmployeeScheduleMapper; import cn.iocoder.yudao.module.hrm.dal.mysql.attendance.HrmRestModeMapper; import cn.iocoder.yudao.module.hrm.dal.mysql.attendance.HrmShiftMapper; import cn.iocoder.yudao.module.hrm.dal.mysql.employee.HrmEmployeeMapper; import cn.iocoder.yudao.module.system.api.dept.DeptApi; import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO; import jakarta.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.LocalTime; import java.time.YearMonth; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.module.hrm.enums.ErrorCodeConstants.*; /** * 员工排班 Service 实现类 * * @author 超级管理员 */ @Service @Validated public class HrmEmployeeScheduleServiceImpl implements HrmEmployeeScheduleService { @Resource private HrmEmployeeScheduleMapper employeeScheduleMapper; @Resource private HrmEmployeeMapper employeeMapper; @Resource private HrmShiftMapper shiftMapper; @Resource private HrmRestModeMapper restModeMapper; @Resource private DeptApi deptApi; @Resource private HrmAttendanceHolidayService attendanceHolidayService; @Resource private HrmLeaveApplicationMapper leaveApplicationMapper; @Override public List getScheduleList(HrmEmployeeScheduleListReqVO reqVO) { YearMonth yearMonth = YearMonth.parse(reqVO.getYearMonth()); LocalDate startDate = yearMonth.atDay(1); LocalDate endDate = yearMonth.atEndOfMonth(); // 1. 按条件查询排班记录 List list; if (reqVO.getEmployeeId() != null) { list = employeeScheduleMapper.selectListByEmployeeIdAndPeriod(reqVO.getEmployeeId(), startDate, endDate); } else if (reqVO.getDeptId() != null) { // 与员工分页保持一致:选中部门时连带查询所有下级部门的员工 Set deptIds = getSelfAndChildDeptIds(reqVO.getDeptId()); List employees = employeeMapper.selectListByDeptIds(deptIds); Set employeeIds = employees.stream().map(HrmEmployeeDO::getId).collect(Collectors.toSet()); list = CollUtil.isEmpty(employeeIds) ? Collections.emptyList() : employeeScheduleMapper.selectListByEmployeeIdsAndPeriod(employeeIds, startDate, endDate); } else { list = employeeScheduleMapper.selectListByPeriod(startDate, endDate); } if (CollUtil.isEmpty(list)) { return Collections.emptyList(); } // 2. 拼接员工信息与班次信息 Set employeeIds = list.stream().map(HrmEmployeeScheduleDO::getEmployeeId) .filter(Objects::nonNull).collect(Collectors.toSet()); Set shiftIds = list.stream().map(HrmEmployeeScheduleDO::getShiftId) .filter(Objects::nonNull).collect(Collectors.toSet()); Map employeeMap = CollUtil.isEmpty(employeeIds) ? Collections.emptyMap() : employeeMapper.selectBatchIds(employeeIds).stream() .collect(Collectors.toMap(HrmEmployeeDO::getId, Function.identity(), (a, b) -> a)); Map shiftMap = CollUtil.isEmpty(shiftIds) ? Collections.emptyMap() : shiftMapper.selectBatchIds(shiftIds).stream() .collect(Collectors.toMap(HrmShiftDO::getId, Function.identity(), (a, b) -> a)); return list.stream().map(schedule -> { HrmEmployeeScheduleRespVO respVO = new HrmEmployeeScheduleRespVO(); respVO.setId(schedule.getId()); respVO.setEmployeeId(schedule.getEmployeeId()); HrmEmployeeDO employee = schedule.getEmployeeId() == null ? null : employeeMap.get(schedule.getEmployeeId()); if (employee != null) { respVO.setEmployeeName(employee.getName()); respVO.setEmployeeNo(employee.getEmployeeNo()); } respVO.setDate(schedule.getDate()); respVO.setShiftId(schedule.getShiftId()); HrmShiftDO shift = schedule.getShiftId() == null ? null : shiftMap.get(schedule.getShiftId()); if (shift != null) { respVO.setShiftName(shift.getName()); respVO.setShiftColor(shift.getColor()); } respVO.setRemark(schedule.getRemark()); return respVO; }).collect(Collectors.toList()); } @Override @Transactional(rollbackFor = Exception.class) public void saveSchedule(List saveReqVOList) { if (CollUtil.isEmpty(saveReqVOList)) { throw exception(SCHEDULE_ITEM_LIST_EMPTY); } // 1. 校验员工存在 Set employeeIds = saveReqVOList.stream().map(HrmEmployeeScheduleSaveReqVO::getEmployeeId) .collect(Collectors.toSet()); if (CollUtil.isNotEmpty(employeeIds)) { List employees = employeeMapper.selectBatchIds(employeeIds); if (employees.size() != employeeIds.size()) { throw exception(SCHEDULE_EMPLOYEE_NOT_EXISTS); } } // 2. 校验班次存在 Set shiftIds = saveReqVOList.stream().map(HrmEmployeeScheduleSaveReqVO::getShiftId) .filter(Objects::nonNull).collect(Collectors.toSet()); if (CollUtil.isNotEmpty(shiftIds)) { List shifts = shiftMapper.selectBatchIds(shiftIds); if (shifts.size() != shiftIds.size()) { throw exception(SCHEDULE_SHIFT_NOT_EXISTS); } } // 3. 逐条 upsert:有班次则保存,无班次则删除 for (HrmEmployeeScheduleSaveReqVO reqVO : saveReqVOList) { HrmEmployeeScheduleDO existing = employeeScheduleMapper.selectByEmployeeIdAndDate( reqVO.getEmployeeId(), reqVO.getDate()); if (reqVO.getShiftId() == null) { if (existing != null) { employeeScheduleMapper.deleteById(existing.getId()); } } else { if (existing == null) { // 该员工该日期可能是之前被清除(逻辑删除)的排班,唯一索引不含 deleted,直接 insert 会撞唯一键 if (employeeScheduleMapper.reviveDeletedSchedule(reqVO.getEmployeeId(), reqVO.getDate(), reqVO.getShiftId(), reqVO.getRemark()) == 0) { employeeScheduleMapper.insert(BeanUtils.toBean(reqVO, HrmEmployeeScheduleDO.class)); } } else { existing.setShiftId(reqVO.getShiftId()); existing.setRemark(reqVO.getRemark()); employeeScheduleMapper.updateById(existing); } } } } @Override @Transactional(rollbackFor = Exception.class) public HrmEmployeeScheduleBatchSaveRespVO batchSaveSchedule(HrmEmployeeScheduleBatchSaveReqVO reqVO) { // 1. 校验日期范围和班次 if (reqVO.getEndDate().isBefore(reqVO.getStartDate())) { throw exception(SCHEDULE_BATCH_DATE_RANGE_INVALID); } if (reqVO.getShiftId() != null && shiftMapper.selectById(reqVO.getShiftId()) == null) { throw exception(SCHEDULE_SHIFT_NOT_EXISTS); } // 休息模式:按「休息模式」页面配置计算(按星期 / 按周期轮班);未传 restModeId 时兼容旧参数 HrmRestModeDO restMode = reqVO.getRestModeId() == null ? null : restModeMapper.selectById(reqVO.getRestModeId()); if (reqVO.getRestModeId() != null && restMode == null) { throw exception(REST_MODE_NOT_EXISTS, String.valueOf(reqVO.getRestModeId())); } Set restDays = restMode != null ? HrmRestModeUtils.parse(restMode.getRestDays()) : resolveLegacyRestDays(reqVO.getRestMode()); // 2. 确定目标员工:勾选了具体员工时只处理勾选人,否则按部门(含下级)+ 岗位 + 员工状态筛选 List employees = resolveBatchEmployees(reqVO); // 3. 预加载范围内已有排班,避免逐条查询 Set employeeIds = employees.stream().map(HrmEmployeeDO::getId).collect(Collectors.toSet()); Map existingMap = employeeScheduleMapper .selectListByEmployeeIdsAndPeriod(employeeIds, reqVO.getStartDate(), reqVO.getEndDate()) .stream() .collect(Collectors.toMap(item -> scheduleKey(item.getEmployeeId(), item.getDate()), Function.identity(), (a, b) -> a)); // 4. 预加载区间内节假日配置:配置为休息日的当天强制休息,配置为工作日的当天强制排班(可覆盖周末) Map holidayTypeMap = attendanceHolidayService .getAttendanceHolidayListByDateRange(reqVO.getStartDate(), reqVO.getEndDate()) .stream() .collect(Collectors.toMap(HrmAttendanceHolidayDO::getDate, HrmAttendanceHolidayDO::getType, (a, b) -> a)); // 5. 预加载目标员工的已审批请假:请假当天跳过,不排班也不清除已有排班 Map> leaveDateMap = buildLeaveDateMap(employees, reqVO.getStartDate(), reqVO.getEndDate()); // 6. 按日期逐天生成排班:休息日删除原班次,工作日 upsert int itemCount = 0; for (LocalDate date = reqVO.getStartDate(); !date.isAfter(reqVO.getEndDate()); date = date.plusDays(1)) { // 当天是休息还是哪个班次:周期轮班模式下每天可能是白班/夜班/休息,由周期安排决定 ScheduleDayPlan dayPlan = resolveScheduleDay(restMode, restDays, date, holidayTypeMap.get(date), reqVO.getShiftId()); boolean rest = dayPlan.rest() || dayPlan.shiftId() == null; for (HrmEmployeeDO employee : employees) { // 员工当天在请假期内,保持原排班不动 if (leaveDateMap.getOrDefault(employee.getId(), Collections.emptySet()).contains(date)) { continue; } HrmEmployeeScheduleDO existing = existingMap.get(scheduleKey(employee.getId(), date)); if (rest) { if (existing != null) { employeeScheduleMapper.deleteById(existing.getId()); itemCount++; } continue; } if (existing == null) { // 已被清除(逻辑删除)的日期直接 insert 会撞唯一索引,优先复活旧行 if (employeeScheduleMapper.reviveDeletedSchedule(employee.getId(), date, dayPlan.shiftId(), null) > 0) { itemCount++; continue; } HrmEmployeeScheduleDO schedule = new HrmEmployeeScheduleDO(); schedule.setEmployeeId(employee.getId()); schedule.setDate(date); schedule.setShiftId(dayPlan.shiftId()); employeeScheduleMapper.insert(schedule); itemCount++; } else if (!Objects.equals(existing.getShiftId(), dayPlan.shiftId())) { existing.setShiftId(dayPlan.shiftId()); employeeScheduleMapper.updateById(existing); itemCount++; } } } HrmEmployeeScheduleBatchSaveRespVO respVO = new HrmEmployeeScheduleBatchSaveRespVO(); respVO.setEmployeeCount(employees.size()); respVO.setItemCount(itemCount); return respVO; } @Override public List getApprovedLeaveList(LocalDate startDate, LocalDate endDate) { if (startDate == null || endDate == null || endDate.isBefore(startDate)) { return Collections.emptyList(); } List leaves = leaveApplicationMapper.selectApprovedListByTimeRange( startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX), null); if (CollUtil.isEmpty(leaves)) { return Collections.emptyList(); } Set userIds = leaves.stream().map(HrmLeaveApplicationDO::getUserId) .filter(Objects::nonNull).collect(Collectors.toSet()); Map userEmployeeMap = CollUtil.isEmpty(userIds) ? Collections.emptyMap() : employeeMapper.selectList(new LambdaQueryWrapperX() .in(HrmEmployeeDO::getUserId, userIds)).stream() .filter(employee -> employee.getUserId() != null) .collect(Collectors.toMap(HrmEmployeeDO::getUserId, Function.identity(), (a, b) -> a)); return leaves.stream().map(leave -> { HrmEmployeeDO employee = userEmployeeMap.get(leave.getUserId()); if (employee == null) { return null; } HrmEmployeeScheduleLeaveRespVO respVO = new HrmEmployeeScheduleLeaveRespVO(); respVO.setId(leave.getId()); respVO.setEmployeeId(employee.getId()); respVO.setEmployeeName(employee.getName()); respVO.setLeaveType(leave.getLeaveType()); respVO.setLeaveTypeName(HrmLeaveTypeEnum.getNameByStatus(leave.getLeaveType())); respVO.setStartTime(leave.getStartTime()); respVO.setEndTime(leave.getEndTime()); respVO.setDuration(leave.getDuration()); return respVO; }).filter(Objects::nonNull).collect(Collectors.toList()); } /** * 构建「员工ID -> 请假日集合」映射(只取审批通过的请假,且裁剪到排班日期范围内) */ private Map> buildLeaveDateMap(List employees, LocalDate startDate, LocalDate endDate) { Map userEmployeeMap = employees.stream() .filter(employee -> employee.getUserId() != null) .collect(Collectors.toMap(HrmEmployeeDO::getUserId, Function.identity(), (a, b) -> a)); if (userEmployeeMap.isEmpty()) { return Collections.emptyMap(); } List leaves = leaveApplicationMapper.selectApprovedListByTimeRange( startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX), userEmployeeMap.keySet()); if (CollUtil.isEmpty(leaves)) { return Collections.emptyMap(); } Map> result = new HashMap<>(); for (HrmLeaveApplicationDO leave : leaves) { HrmEmployeeDO employee = userEmployeeMap.get(leave.getUserId()); if (employee == null || leave.getStartTime() == null || leave.getEndTime() == null) { continue; } LocalDate from = leave.getStartTime().toLocalDate().isBefore(startDate) ? startDate : leave.getStartTime().toLocalDate(); LocalDate to = leave.getEndTime().toLocalDate().isAfter(endDate) ? endDate : leave.getEndTime().toLocalDate(); Set dates = result.computeIfAbsent(employee.getId(), key -> new HashSet<>()); for (LocalDate date = from; !date.isAfter(to); date = date.plusDays(1)) { dates.add(date); } } return result; } private Set getSelfAndChildDeptIds(Long deptId) { Set deptIds = new LinkedHashSet<>(); deptIds.add(deptId); List childDepts = deptApi.getChildDeptList(deptId); if (CollUtil.isNotEmpty(childDepts)) { childDepts.forEach(dept -> deptIds.add(dept.getId())); } return deptIds; } /** employeeStatus 为空时包含在职和试用,排除离职 */ private boolean matchEmployeeStatus(HrmEmployeeDO employee, Integer employeeStatus) { if (employeeStatus != null) { return Objects.equals(employee.getEmployeeStatus(), employeeStatus); } return !Objects.equals(employee.getEmployeeStatus(), 3); } private boolean matchPost(HrmEmployeeDO employee, Long postId) { if (postId == null) { return true; } if (StrUtil.isBlank(employee.getPostIds())) { return false; } return JSONUtil.toList(employee.getPostIds(), Long.class).contains(postId); } /** * 兼容旧参数:未传 restModeId 时,double-周六日休,single-周日休,其余不休息 */ private Set resolveLegacyRestDays(String restMode) { if ("double".equals(restMode)) { return Set.of(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY); } if ("single".equals(restMode)) { return Set.of(DayOfWeek.SUNDAY); } return Collections.emptySet(); } /** * 计算某一天是休息,还是排哪个班次 * * 规则优先级:节假日配置 > 周期轮班的「当天安排」 > 每周固定休息日。 * 周期轮班里 W 取白班班次、N 取夜班班次;节假日把轮休日调成上班时按白班排。 */ private ScheduleDayPlan resolveScheduleDay(HrmRestModeDO restMode, Set restDays, LocalDate date, Integer holidayType, Long defaultShiftId) { List cycleTokens = getCycleTokens(restMode); boolean cycleMode = !cycleTokens.isEmpty(); Long dayShiftId = cycleMode && restMode.getShiftId() != null ? restMode.getShiftId() : defaultShiftId; Long nightShiftId = cycleMode ? restMode.getNightShiftId() : null; String token = cycleMode ? cycleTokens.get(HrmRestModeUtils.resolveCycleDay(restMode.getCycleStartDate(), restMode.getCycleDays(), date) - 1) : null; // 1. 节假日配置优先:休息日强制休息,工作日强制上班(含调休上班的周末) if (holidayType != null) { if (HrmAttendanceHolidayTypeEnum.REST_DAY.getType().equals(holidayType)) { return ScheduleDayPlan.restPlan(); } boolean night = cycleMode && HrmRestModeUtils.CYCLE_TOKEN_NIGHT.equals(token); return ScheduleDayPlan.workPlan(night && nightShiftId != null ? nightShiftId : dayShiftId); } // 2. 周期轮班:按当天轮到的安排 if (cycleMode) { if (HrmRestModeUtils.CYCLE_TOKEN_REST.equals(token)) { return ScheduleDayPlan.restPlan(); } boolean night = HrmRestModeUtils.CYCLE_TOKEN_NIGHT.equals(token); return ScheduleDayPlan.workPlan(night && nightShiftId != null ? nightShiftId : dayShiftId); } // 3. 按星期:休息日休,其它排默认班次 return restDays.contains(date.getDayOfWeek()) ? ScheduleDayPlan.restPlan() : ScheduleDayPlan.workPlan(defaultShiftId); } /** * 周期轮班的逐天安排;不是周期模式或配置不完整时返回空列表,走「按星期」逻辑 */ private List getCycleTokens(HrmRestModeDO restMode) { if (restMode == null || !HrmRestModeTypeEnum.CYCLE.getType().equals(restMode.getModeType()) || restMode.getCycleStartDate() == null || restMode.getCycleDays() == null) { return Collections.emptyList(); } List tokens = HrmRestModeUtils.parseCyclePattern(restMode.getCyclePattern()); return tokens.size() == restMode.getCycleDays() ? tokens : Collections.emptyList(); } /** * 某天的排班安排:休息,或排指定班次 */ private record ScheduleDayPlan(boolean rest, Long shiftId) { private static ScheduleDayPlan restPlan() { return new ScheduleDayPlan(true, null); } private static ScheduleDayPlan workPlan(Long shiftId) { return new ScheduleDayPlan(false, shiftId); } } /** * 解析批量排班的目标员工 * * 传了 employeeIds 时只对勾选的员工排班(忽略部门/岗位/员工状态);否则按部门(含下级)+ 岗位 + 状态筛选。 */ private List resolveBatchEmployees(HrmEmployeeScheduleBatchSaveReqVO reqVO) { if (CollUtil.isNotEmpty(reqVO.getEmployeeIds())) { Set employeeIds = new LinkedHashSet<>(reqVO.getEmployeeIds()); employeeIds.remove(null); if (employeeIds.isEmpty()) { throw exception(SCHEDULE_BATCH_TARGET_EMPTY); } List employees = employeeMapper.selectBatchIds(employeeIds); if (employees.size() < employeeIds.size()) { throw exception(SCHEDULE_BATCH_EMPLOYEE_IDS_EMPTY, String.valueOf(employeeIds.size()), String.valueOf(employeeIds.size() - employees.size())); } return employees; } if (reqVO.getDeptId() == null) { throw exception(SCHEDULE_BATCH_TARGET_EMPTY); } Set deptIds = getSelfAndChildDeptIds(reqVO.getDeptId()); List employees = employeeMapper.selectListByDeptIds(deptIds).stream() .filter(employee -> matchEmployeeStatus(employee, reqVO.getEmployeeStatus())) .filter(employee -> matchPost(employee, reqVO.getPostId())) .collect(Collectors.toList()); if (CollUtil.isEmpty(employees)) { DeptRespDTO dept = deptApi.getDept(reqVO.getDeptId()); throw exception(SCHEDULE_BATCH_EMPLOYEE_EMPTY, dept == null ? String.valueOf(reqVO.getDeptId()) : dept.getName()); } return employees; } private String scheduleKey(Long employeeId, LocalDate date) { return employeeId + "_" + date; } }