gaoluyang
昨天 ef3cbc1c6882786e8218b08be3e52ea44587f03b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package cn.iocoder.yudao.module.hrm.service.attendance;
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.hrm.controller.admin.attendance.vo.HrmAttendanceSummaryPageReqVO;
import cn.iocoder.yudao.module.hrm.dal.dataobject.attendance.HrmAttendanceHolidayDO;
import cn.iocoder.yudao.module.hrm.dal.dataobject.attendance.HrmAttendanceRecordDO;
import cn.iocoder.yudao.module.hrm.dal.dataobject.attendance.HrmAttendanceSummaryDO;
import cn.iocoder.yudao.module.hrm.dal.dataobject.employee.HrmEmployeeDO;
import cn.iocoder.yudao.module.hrm.dal.mysql.attendance.HrmAttendanceRecordMapper;
import cn.iocoder.yudao.module.hrm.dal.mysql.attendance.HrmAttendanceSummaryMapper;
import cn.iocoder.yudao.module.hrm.enums.HrmAttendanceClockTypeEnum;
import cn.iocoder.yudao.module.hrm.enums.HrmAttendanceHolidayTypeEnum;
import cn.iocoder.yudao.module.hrm.service.employee.HrmEmployeeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
 
import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
/**
 * 考勤统计汇总 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
@Slf4j
public class HrmAttendanceSummaryServiceImpl implements HrmAttendanceSummaryService {
 
    @Resource
    private HrmAttendanceSummaryMapper attendanceSummaryMapper;
    @Resource
    private HrmAttendanceRecordMapper attendanceRecordMapper;
    @Resource
    private HrmEmployeeService employeeService;
    @Resource
    private HrmAttendanceHolidayService attendanceHolidayService;
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void generateMonthlySummary(Long userId, String yearMonth) {
        // 1. 解析年月,获取该月起始日期
        YearMonth ym = YearMonth.parse(yearMonth);
        LocalDate startDate = ym.atDay(1);
        LocalDate endDate = ym.atEndOfMonth();
 
        // 2. 获取员工信息
        HrmEmployeeDO employee = employeeService.getEmployee(userId);
        if (employee == null) {
            log.warn("[generateMonthlySummary] 员工不存在: {}", userId);
            return;
        }
 
        // 3. 查询该月所有考勤记录
        List<HrmAttendanceRecordDO> records = attendanceRecordMapper.selectListByUserIdAndDateBetween(userId, startDate, endDate);
 
        // 4. 计算应出勤天数(工作日数量)
        int workDays = calculateWorkDays(startDate, endDate);
 
        // 5. 统计各项数据
        int lateCount = 0;
        int earlyCount = 0;
        int absentCount = 0;
        BigDecimal overtimeHours = BigDecimal.ZERO;
        int actualDays = 0;
 
        for (HrmAttendanceRecordDO record : records) {
            // 统计迟到
            if (HrmAttendanceClockTypeEnum.LATE.getType().equals(record.getClockInType())) {
                lateCount++;
            }
            // 统计早退
            if (HrmAttendanceClockTypeEnum.EARLY.getType().equals(record.getClockOutType())) {
                earlyCount++;
            }
            // 统计缺卡
            if (HrmAttendanceClockTypeEnum.MISSING.getType().equals(record.getClockInType())) {
                absentCount++;
            }
            if (HrmAttendanceClockTypeEnum.MISSING.getType().equals(record.getClockOutType())) {
                absentCount++;
            }
            // 累计加班时长
            if (record.getOvertimeHours() != null) {
                overtimeHours = overtimeHours.add(record.getOvertimeHours());
            }
            // 统计实际出勤天数(有正常打卡记录)
            if (record.getClockInTime() != null || record.getClockOutTime() != null) {
                actualDays++;
            }
        }
 
        // 6. 保存或更新汇总记录
        HrmAttendanceSummaryDO summary = attendanceSummaryMapper.selectByUserIdAndYearMonth(userId, yearMonth);
        if (summary == null) {
            summary = HrmAttendanceSummaryDO.builder()
                    .userId(userId)
                    .deptId(employee.getDeptId())
                    .yearMonth(yearMonth)
                    .workDays(workDays)
                    .actualDays(actualDays)
                    .lateCount(lateCount)
                    .earlyCount(earlyCount)
                    .absentCount(absentCount)
                    .overtimeHours(overtimeHours)
                    .leaveHours(BigDecimal.ZERO)
                    .build();
            attendanceSummaryMapper.insert(summary);
        } else {
            summary.setWorkDays(workDays);
            summary.setActualDays(actualDays);
            summary.setLateCount(lateCount);
            summary.setEarlyCount(earlyCount);
            summary.setAbsentCount(absentCount);
            summary.setOvertimeHours(overtimeHours);
            attendanceSummaryMapper.updateById(summary);
        }
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void generateDeptMonthlySummary(Long deptId, String yearMonth) {
        // 获取部门所有在职员工
        List<HrmEmployeeDO> employees = employeeService.getEmployeeList(null);
        if (CollUtil.isEmpty(employees)) {
            return;
        }
        // 筛选部门员工
        List<HrmEmployeeDO> deptEmployees = employees.stream()
                .filter(e -> deptId.equals(e.getDeptId()))
                .toList();
        for (HrmEmployeeDO employee : deptEmployees) {
            generateMonthlySummary(employee.getId(), yearMonth);
        }
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void generateAllMonthlySummary(String yearMonth) {
        // 获取所有在职员工
        List<HrmEmployeeDO> employees = employeeService.getEmployeeList(null);
        if (CollUtil.isEmpty(employees)) {
            return;
        }
        for (HrmEmployeeDO employee : employees) {
            generateMonthlySummary(employee.getId(), yearMonth);
        }
    }
 
    /**
     * 计算应出勤天数(工作日数量)
     *
     * 一次取出区间内节假日配置,避免逐日查询。
     */
    private int calculateWorkDays(LocalDate startDate, LocalDate endDate) {
        Map<LocalDate, Integer> holidayTypeMap = attendanceHolidayService
                .getAttendanceHolidayListByDateRange(startDate, endDate)
                .stream()
                .collect(Collectors.toMap(HrmAttendanceHolidayDO::getDate, HrmAttendanceHolidayDO::getType,
                        (a, b) -> a));
        int workDays = 0;
        LocalDate current = startDate;
        while (!current.isAfter(endDate)) {
            Integer holidayType = holidayTypeMap.get(current);
            boolean work;
            if (holidayType != null) {
                // 有节假日配置时按配置判断:休息日不算应出勤,工作日计入(含调休上班的周末)
                work = HrmAttendanceHolidayTypeEnum.WORK_DAY.getType().equals(holidayType);
            } else {
                DayOfWeek dayOfWeek = current.getDayOfWeek();
                work = dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY;
            }
            if (work) {
                workDays++;
            }
            current = current.plusDays(1);
        }
        return workDays;
    }
 
    /**
     * 节假日配置变更后,已有汇总的应出勤天数会与最新配置不一致。
     * 查询汇总时按最新节假日重算一次并回写,保证「应出勤天数」始终关联节假日配置。
     */
    private void refreshWorkDaysOfMonth(String yearMonth) {
        if (StrUtil.isBlank(yearMonth)) {
            return;
        }
        try {
            YearMonth ym = YearMonth.parse(yearMonth);
            attendanceSummaryMapper.updateWorkDaysByYearMonth(yearMonth,
                    calculateWorkDays(ym.atDay(1), ym.atEndOfMonth()));
        } catch (Exception ex) {
            // 刷新失败不影响查询本身,记录日志即可
            log.warn("[refreshWorkDaysOfMonth][yearMonth({}) 刷新应出勤天数失败]", yearMonth, ex);
        }
    }
 
    @Override
    public PageResult<HrmAttendanceSummaryDO> getAttendanceSummaryPage(HrmAttendanceSummaryPageReqVO pageReqVO) {
        // 查询前按最新节假日重算该月应出勤天数
        refreshWorkDaysOfMonth(pageReqVO.getYearMonth());
        return attendanceSummaryMapper.selectPage(pageReqVO, new LambdaQueryWrapperX<HrmAttendanceSummaryDO>()
                .eqIfPresent(HrmAttendanceSummaryDO::getUserId, pageReqVO.getUserId())
                .eqIfPresent(HrmAttendanceSummaryDO::getDeptId, pageReqVO.getDeptId())
                .eqIfPresent(HrmAttendanceSummaryDO::getYearMonth, pageReqVO.getYearMonth())
                .orderByDesc(HrmAttendanceSummaryDO::getYearMonth)
                .orderByAsc(HrmAttendanceSummaryDO::getDeptId));
    }
 
    @Override
    public HrmAttendanceSummaryDO getMonthlySummary(Long userId, String yearMonth) {
        return attendanceSummaryMapper.selectByUserIdAndYearMonth(userId, yearMonth);
    }
 
    @Override
    public List<HrmAttendanceSummaryDO> getDeptMonthlySummaryList(Long deptId, String yearMonth) {
        // 查询前按最新节假日重算该月应出勤天数
        refreshWorkDaysOfMonth(yearMonth);
        return attendanceSummaryMapper.selectListByDeptIdAndYearMonth(deptId, yearMonth);
    }
 
}