liu
10 天以前 82155dd6f2b16fbfb718e636a54e2c9dae31246b
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
package cn.iocoder.yudao.module.hrm.service.attendance;
 
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.hrm.controller.admin.attendance.vo.HrmAttendanceClockReqVO;
import cn.iocoder.yudao.module.hrm.controller.admin.attendance.vo.HrmAttendanceMyStatusRespVO;
import cn.iocoder.yudao.module.hrm.controller.admin.attendance.vo.HrmAttendanceRecordPageReqVO;
import cn.iocoder.yudao.module.hrm.controller.admin.attendance.vo.HrmAttendanceRecordRespVO;
import cn.iocoder.yudao.module.hrm.controller.admin.attendance.vo.HrmAttendanceRuleRespVO;
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.HrmAttendanceRuleDO;
import cn.iocoder.yudao.module.hrm.dal.dataobject.attendance.HrmAttendanceExceptionDO;
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.enums.HrmAttendanceClockTypeEnum;
import cn.iocoder.yudao.module.hrm.enums.HrmAttendanceDataSourceEnum;
import cn.iocoder.yudao.module.hrm.enums.HrmAttendanceExceptionTypeEnum;
import cn.iocoder.yudao.module.hrm.enums.HrmAttendanceHolidayTypeEnum;
import cn.iocoder.yudao.module.hrm.service.employee.HrmEmployeeService;
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.math.BigDecimal;
import java.math.RoundingMode;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
 
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 HrmAttendanceRecordServiceImpl implements HrmAttendanceRecordService {
 
    @Resource
    private HrmAttendanceRecordMapper attendanceRecordMapper;
    @Resource
    private HrmEmployeeService employeeService;
    @Resource
    private HrmAttendanceRuleService attendanceRuleService;
    @Resource
    private HrmAttendanceHolidayService attendanceHolidayService;
    @Resource
    private DeptApi deptApi;
    @Resource
    private cn.iocoder.yudao.module.hrm.service.approval.HrmLeaveQueryService leaveQueryService;
 
    @Override
    public PageResult<HrmAttendanceRecordDO> getAttendanceRecordPage(HrmAttendanceRecordPageReqVO pageReqVO) {
        return attendanceRecordMapper.selectPage(pageReqVO);
    }
 
    @Override
    public HrmAttendanceRecordDO getAttendanceRecord(Long id) {
        return attendanceRecordMapper.selectById(id);
    }
 
    @Override
    public List<HrmAttendanceRecordDO> getAttendanceRecordListByUserIdAndDateBetween(Long userId, String startDate, String endDate) {
        return attendanceRecordMapper.selectListByUserIdAndDateBetween(userId, LocalDate.parse(startDate), LocalDate.parse(endDate));
    }
 
    @Override
    public HrmAttendanceRecordDO getAttendanceRecordByUserIdAndDate(Long userId, LocalDate date) {
        return attendanceRecordMapper.selectByUserIdAndDate(userId, date);
    }
 
    @Override
    public HrmAttendanceMyStatusRespVO getMyStatus(Long loginUserId, LocalDate date) {
        LocalDate queryDate = date != null ? date : LocalDate.now();
        // 1. 登录用户 -> 员工档案
        HrmEmployeeDO employee = employeeService.getEmployeeByUserId(loginUserId);
        if (employee == null) {
            throw exception(ATTENDANCE_EMPLOYEE_NOT_BOUND);
        }
        HrmAttendanceMyStatusRespVO respVO = new HrmAttendanceMyStatusRespVO();
        respVO.setUserId(loginUserId);
        respVO.setEmployeeId(employee.getId());
        respVO.setEmployeeName(employee.getName());
        respVO.setUserName(employee.getName());
        respVO.setDeptId(employee.getDeptId());
        if (employee.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(employee.getDeptId());
            if (dept != null) {
                respVO.setDeptName(dept.getName());
            }
        }
        respVO.setDate(queryDate);
        respVO.setServerTime(LocalDateTime.now());
 
        // 2. 是否工作日 + 休息原因
        boolean workDay = attendanceHolidayService.isWorkDay(queryDate);
        respVO.setWorkDay(workDay);
        if (!workDay) {
            respVO.setRestDayReason(getRestDayReason(queryDate));
        }
 
        // 3. 当前生效规则(部门规则优先,其次全局规则)
        HrmAttendanceRuleDO rule = attendanceRuleService.getAttendanceRuleByDeptId(employee.getDeptId());
        if (rule != null) {
            HrmAttendanceRuleRespVO ruleRespVO = BeanUtils.toBean(rule, HrmAttendanceRuleRespVO.class);
            if (rule.getDeptId() != null) {
                DeptRespDTO ruleDept = deptApi.getDept(rule.getDeptId());
                if (ruleDept != null) {
                    ruleRespVO.setDeptName(ruleDept.getName());
                }
            }
            respVO.setRule(ruleRespVO);
            fillCompatibleRuleFields(respVO, rule);
        }
 
        // 4. 当日考勤记录
        // 考勤记录表存的是系统用户 ID,这里用 loginUserId 而不是员工档案 ID
        HrmAttendanceRecordDO record = attendanceRecordMapper.selectByUserIdAndDate(loginUserId, queryDate);
        if (record != null) {
            respVO.setRecord(buildRecordRespVO(record, employee));
            fillCompatibleRecordFields(respVO, record);
        }
 
        // 4.5 当天请假情况(请假仍允许打卡,但不算迟到/早退/缺卡)
        List<cn.iocoder.yudao.module.hrm.dal.dataobject.approval.HrmLeaveApplicationDO> leaves =
                leaveQueryService.getApprovedLeaveList(loginUserId, queryDate);
        boolean onLeave = !leaves.isEmpty();
        java.math.BigDecimal leaveHours = onLeave ? calcLeaveHours(leaves, rule, queryDate) : java.math.BigDecimal.ZERO;
        respVO.setOnLeave(onLeave);
        respVO.setLeaveHours(leaveHours);
        if (onLeave) {
            List<String> typeNames = leaves.stream()
                    .map(l -> cn.iocoder.yudao.module.hrm.enums.HrmLeaveTypeEnum.getNameByStatus(l.getLeaveType()))
                    .distinct().toList();
            respVO.setLeaveTypeNames(String.join("、", typeNames));
        }
 
        // 5. 当前可打卡状态
        HrmAttendanceMyStatusRespVO.Clockable clockable = buildClockable(workDay, rule, record, queryDate, onLeave);
 
        // 5.1 请假当天:把「可打卡」的提示换成请假说明,但依然允许打卡
        if (onLeave) {
            clockable.setMessage("今日已请假(" + respVO.getLeaveTypeNames() + "),如需上班可正常打卡");
        }
        respVO.setClockable(clockable);
        respVO.setClockInDone(record != null && record.getClockInTime() != null);
        respVO.setClockOutDone(record != null && record.getClockOutTime() != null);
        respVO.setCanClockIn(clockable.getClockIn());
        respVO.setCanClockOut(clockable.getClockOut());
        return respVO;
    }
 
    /** 同时保留旧版 App/Web 使用的平铺规则字段。 */
    private void fillCompatibleRuleFields(HrmAttendanceMyStatusRespVO respVO, HrmAttendanceRuleDO rule) {
        respVO.setRuleName(rule.getName());
        respVO.setWorkStartTime(rule.getWorkStartTime());
        respVO.setWorkEndTime(rule.getWorkEndTime());
        respVO.setLocationRequired(rule.getLocationRequired());
        respVO.setLocationName(rule.getLocationName());
        respVO.setLocationAddress(rule.getLocationAddress());
        respVO.setLongitude(rule.getLongitude());
        respVO.setLatitude(rule.getLatitude());
        respVO.setRadiusMeters(rule.getRadiusMeters());
        respVO.setCoordinateSystem(rule.getCoordinateSystem());
    }
 
    /** 同时保留旧版 App/Web 使用的平铺考勤记录字段。 */
    private void fillCompatibleRecordFields(HrmAttendanceMyStatusRespVO respVO, HrmAttendanceRecordDO record) {
        respVO.setRecordId(record.getId());
        respVO.setClockInTime(record.getClockInTime());
        respVO.setClockOutTime(record.getClockOutTime());
        respVO.setClockInType(record.getClockInType());
        respVO.setClockOutType(record.getClockOutType());
        respVO.setWorkHours(record.getWorkHours());
        respVO.setOvertimeHours(record.getOvertimeHours());
        respVO.setLocation(record.getLocation());
        respVO.setDataSource(record.getDataSource());
    }
 
    /**
     * 把请假信息写入考勤记录(leave_flag / leave_hours / leave_types)
     *
     * @param record 考勤记录
     * @param leaves 当天审批通过的请假单
     * @param rule   考勤规则(用于计算工作时段交集)
     * @param date   考勤日期
     */
    private void applyLeaveInfo(HrmAttendanceRecordDO record,
                                List<cn.iocoder.yudao.module.hrm.dal.dataobject.approval.HrmLeaveApplicationDO> leaves,
                                HrmAttendanceRuleDO rule, LocalDate date) {
        if (leaves == null || leaves.isEmpty()) {
            record.setLeaveFlag(false);
            record.setLeaveHours(BigDecimal.ZERO);
            record.setLeaveTypes(null);
            return;
        }
        record.setLeaveFlag(true);
        record.setLeaveHours(calcLeaveHours(leaves, rule, date));
        record.setLeaveTypes(leaves.stream()
                .map(l -> String.valueOf(l.getLeaveType()))
                .distinct()
                .collect(java.util.stream.Collectors.joining(",")));
    }
 
    /**
     * 计算某天的请假工时
     *
     * <p>把每张请假单的 [start_time, end_time] 与考勤规则的工作时段求交集后累加,
     * 精确到 0.01 小时(36 秒)。无规则时按整天的请假时长折算。</p>
     *
     * <p>例:规则 08:30-17:30,请假单 14:00-18:00 → 交集 14:00-17:30 = 3.5 小时。</p>
     */
    private java.math.BigDecimal calcLeaveHours(
            List<cn.iocoder.yudao.module.hrm.dal.dataobject.approval.HrmLeaveApplicationDO> leaves,
            HrmAttendanceRuleDO rule, LocalDate date) {
        LocalDateTime dayStart = date.atStartOfDay();
        LocalDateTime dayEnd = date.plusDays(1).atStartOfDay();
        // 工作日时段:优先用考勤规则,没配规则就按整天
        LocalDateTime workStart;
        LocalDateTime workEnd;
        if (rule != null && rule.getWorkStartTime() != null && rule.getWorkEndTime() != null) {
            workStart = LocalDateTime.of(date, rule.getWorkStartTime());
            workEnd = LocalDateTime.of(date, rule.getWorkEndTime());
            // 跨零点班次(如 20:00-次日 04:00)
            if (!workEnd.isAfter(workStart)) {
                workEnd = workEnd.plusDays(1);
            }
        } else {
            workStart = dayStart;
            workEnd = dayEnd;
        }
        java.math.BigDecimal total = java.math.BigDecimal.ZERO;
        for (var leave : leaves) {
            if (leave.getStartTime() == null || leave.getEndTime() == null) {
                continue;
            }
            LocalDateTime from = leave.getStartTime().isAfter(workStart) ? leave.getStartTime() : workStart;
            LocalDateTime to = leave.getEndTime().isBefore(workEnd) ? leave.getEndTime() : workEnd;
            if (!to.isAfter(from)) {
                continue;
            }
            long minutes = java.time.Duration.between(from, to).toMinutes();
            total = total.add(java.math.BigDecimal.valueOf(minutes)
                    .divide(java.math.BigDecimal.valueOf(60), 2, java.math.RoundingMode.HALF_UP));
        }
        return total;
    }
 
    /**
     * 休息日原因:优先取节假日配置名称,未配置时按星期给出“周六/周日”
     */
    private String getRestDayReason(LocalDate date) {
        List<HrmAttendanceHolidayDO> holidays = attendanceHolidayService.getAttendanceHolidayListByDateRange(date, date);
        for (HrmAttendanceHolidayDO holiday : holidays) {
            if (HrmAttendanceHolidayTypeEnum.REST_DAY.getType().equals(holiday.getType())) {
                return holiday.getName();
            }
        }
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        if (dayOfWeek == DayOfWeek.SATURDAY) {
            return "周六";
        }
        if (dayOfWeek == DayOfWeek.SUNDAY) {
            return "周日";
        }
        return null;
    }
 
    /**
     * 构建打卡记录返回 VO,补齐打卡类型名称、员工与部门信息
     */
    private HrmAttendanceRecordRespVO buildRecordRespVO(HrmAttendanceRecordDO record, HrmEmployeeDO employee) {
        HrmAttendanceRecordRespVO recordRespVO = BeanUtils.toBean(record, HrmAttendanceRecordRespVO.class);
        recordRespVO.setClockInTypeName(HrmAttendanceClockTypeEnum.getNameByType(record.getClockInType()));
        recordRespVO.setClockOutTypeName(HrmAttendanceClockTypeEnum.getNameByType(record.getClockOutType()));
        if (employee != null) {
            recordRespVO.setUserName(employee.getName());
            recordRespVO.setPhone(employee.getPhone());
        }
        if (record.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(record.getDeptId());
            if (dept != null) {
                recordRespVO.setDeptName(dept.getName());
            }
        }
        return recordRespVO;
    }
 
    /**
     * 根据工作日、考勤规则与当日记录计算可打卡状态
     */
    private HrmAttendanceMyStatusRespVO.Clockable buildClockable(boolean workDay, HrmAttendanceRuleDO rule,
                                                                 HrmAttendanceRecordDO record, LocalDate date,
                                                                 boolean onLeave) {
        HrmAttendanceMyStatusRespVO.Clockable clockable = new HrmAttendanceMyStatusRespVO.Clockable();
        if (!workDay) {
            clockable.setClockIn(false);
            clockable.setClockOut(false);
            clockable.setNextAction("none");
            clockable.setMessage("今日休息,无需打卡");
            return clockable;
        }
        if (rule == null) {
            clockable.setClockIn(false);
            clockable.setClockOut(false);
            clockable.setNextAction("none");
            clockable.setMessage("未配置考勤规则,请联系管理员");
            return clockable;
        }
        // 只有下班卡、没有上班卡:当日已结束,不再允许继续打卡
        if (record != null && record.getClockInTime() == null && record.getClockOutTime() != null) {
            clockable.setClockIn(false);
            clockable.setClockOut(false);
            clockable.setNextAction("none");
            clockable.setMessage("今日缺上班卡,已完成下班打卡");
            return clockable;
        }
        // 今天还没打上班卡
        if (record == null || record.getClockInTime() == null) {
            clockable.setClockIn(true);
            clockable.setClockOut(false);
            clockable.setNextAction("in");
            clockable.setMessage("可上班打卡");
            // 仅当天查询时提示已迟到时长;请假当天不提示迟到
            LocalDateTime now = LocalDateTime.now();
            if (!onLeave && rule.getWorkStartTime() != null && date.equals(now.toLocalDate())) {
                LocalDateTime workStart = LocalDateTime.of(date, rule.getWorkStartTime());
                int lateAllowMinutes = rule.getLateAllowMinutes() != null ? rule.getLateAllowMinutes() : 0;
                if (now.isAfter(workStart.plusMinutes(lateAllowMinutes))) {
                    long lateMinutes = Duration.between(workStart, now).toMinutes();
                    clockable.setMessage("已超过上班时间 " + lateMinutes + " 分钟");
                }
            }
            return clockable;
        }
        // 已打上班卡、未打下班卡
        if (record.getClockOutTime() == null) {
            clockable.setClockIn(false);
            clockable.setClockOut(true);
            clockable.setNextAction("out");
            clockable.setMessage("已上班打卡,可下班打卡");
            return clockable;
        }
        // 上下班卡都已打
        clockable.setClockIn(false);
        clockable.setClockOut(false);
        clockable.setNextAction("none");
        clockable.setMessage("今日已完成打卡");
        return clockable;
    }
 
    @Override
    public void createImportedRecord(HrmAttendanceRecordDO record) {
        // 按考勤规则重算打卡类型与时长,不信任 Excel 填写的值
        fillClockTypes(record);
        fillCalculatedHours(record);
        attendanceRecordMapper.insert(record);
    }
 
    @Override
    public void updateImportedRecord(HrmAttendanceRecordDO record) {
        fillClockTypes(record);
        fillCalculatedHours(record);
        attendanceRecordMapper.updateById(record);
    }
 
    /**
     * 按考勤规则重算上下班打卡类型(正常/迟到/早退),与打卡逻辑保持一致
     */
    private void fillClockTypes(HrmAttendanceRecordDO record) {
        if (record.getDeptId() == null) {
            return;
        }
        HrmAttendanceRuleDO rule = attendanceRuleService.getAttendanceRuleByDeptId(record.getDeptId());
        if (rule == null) {
            return;
        }
        // 上班打卡类型:晚于 上班时间+迟到允许 记为迟到
        if (record.getClockInTime() != null && rule.getWorkStartTime() != null) {
            int lateAllowMinutes = rule.getLateAllowMinutes() != null ? rule.getLateAllowMinutes() : 0;
            LocalTime lateThreshold = rule.getWorkStartTime().plusMinutes(lateAllowMinutes);
            LocalTime clockInOnly = record.getClockInTime().toLocalTime();
            record.setClockInType(clockInOnly.isAfter(lateThreshold)
                    ? HrmAttendanceClockTypeEnum.LATE.getType()
                    : HrmAttendanceClockTypeEnum.NORMAL.getType());
        }
        // 下班打卡类型:早于 下班时间-早退允许 记为早退
        if (record.getClockOutTime() != null && rule.getWorkEndTime() != null) {
            int earlyAllowMinutes = rule.getEarlyAllowMinutes() != null ? rule.getEarlyAllowMinutes() : 0;
            LocalTime earlyThreshold = rule.getWorkEndTime().minusMinutes(earlyAllowMinutes);
            LocalTime clockOutOnly = record.getClockOutTime().toLocalTime();
            record.setClockOutType(clockOutOnly.isBefore(earlyThreshold)
                    ? HrmAttendanceClockTypeEnum.EARLY.getType()
                    : HrmAttendanceClockTypeEnum.NORMAL.getType());
        }
    }
 
    /**
     * 根据上下班打卡时间和考勤规则,计算工作时长与加班时长
     */
    private void fillCalculatedHours(HrmAttendanceRecordDO record) {
        // 工作时长 = 下班打卡时间 - 上班打卡时间(与打卡逻辑一致)
        if (record.getClockInTime() != null && record.getClockOutTime() != null) {
            Duration duration = Duration.between(record.getClockInTime(), record.getClockOutTime());
            BigDecimal workHours = BigDecimal.valueOf(duration.toMinutes())
                    .divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
            record.setWorkHours(workHours);
        }
        // 加班时长:按考勤规则的标准下班时间计算超额部分
        if (record.getClockOutTime() != null && record.getDeptId() != null) {
            HrmAttendanceRuleDO rule = attendanceRuleService.getAttendanceRuleByDeptId(record.getDeptId());
            if (rule != null && rule.getWorkEndTime() != null) {
                LocalTime workEnd = rule.getWorkEndTime();
                LocalDate outDate = record.getClockOutTime().toLocalDate();
                LocalDateTime workEndDateTime = LocalDateTime.of(outDate, workEnd);
                if (record.getClockOutTime().isAfter(workEndDateTime)) {
                    Duration overtimeDuration = Duration.between(workEndDateTime, record.getClockOutTime());
                    BigDecimal overtimeThreshold = rule.getOvertimeThreshold() != null
                            ? rule.getOvertimeThreshold() : BigDecimal.ZERO;
                    BigDecimal overtimeHours = BigDecimal.valueOf(overtimeDuration.toMinutes())
                            .divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
                    record.setOvertimeHours(overtimeHours.compareTo(overtimeThreshold) > 0 ? overtimeHours : BigDecimal.ZERO);
                } else {
                    record.setOvertimeHours(BigDecimal.ZERO);
                }
            } else {
                record.setOvertimeHours(BigDecimal.ZERO);
            }
        }
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public HrmAttendanceClockResult clockIn(Long userId, LocalDateTime clockTime,
                                            HrmAttendanceClockReqVO reqVO, String legacyLocation) {
        LocalDate clockDate = clockTime.toLocalDate();
        // 1. 校验是否工作日
        if (!attendanceHolidayService.isWorkDay(clockDate)) {
            throw exception(ATTENDANCE_CLOCK_FAIL_NOT_WORKDAY);
        }
        // 2. 获取员工信息和考勤规则
        //    注意:入参 userId 实际传的是「员工档案 ID」,
        //    而考勤记录表 / 请假表的 user_id 存的是「系统用户 ID」,必须区分。
        HrmEmployeeDO employee = employeeService.getEmployee(userId);
        if (employee == null) {
            throw exception(EMPLOYEE_NOT_EXISTS);
        }
        Long systemUserId = employee.getUserId();
        HrmAttendanceRuleDO rule = attendanceRuleService.getAttendanceRuleByDeptId(employee.getDeptId());
        if (rule == null) {
            throw exception(ATTENDANCE_CLOCK_FAIL_NO_RULE);
        }
        // 3. 查询当日考勤记录(用系统用户 ID)
        HrmAttendanceRecordDO record = attendanceRecordMapper.selectByUserIdAndDate(systemUserId, clockDate);
        if (record != null && record.getClockInTime() != null) {
            throw exception(ATTENDANCE_CLOCK_ALREADY_CLOCKED);
        }
        // 在任何写库操作前完成定位校验,旧版地点字符串不能绕过范围限制。
        ClockLocation clockLocation = validateClockLocation(rule, reqVO);
        // 3.1 当天请假情况:请假当天允许打卡,但不判定为迟到
        //     注意:方法入参 userId 实为「员工档案 ID」,而请假表存的是「系统用户 ID」,
        //     必须用 employee.getUserId() 才能对上。
        List<cn.iocoder.yudao.module.hrm.dal.dataobject.approval.HrmLeaveApplicationDO> leaves =
                leaveQueryService.getApprovedLeaveList(employee.getUserId(), clockDate);
        boolean onLeave = !leaves.isEmpty();
        // 4. 判断打卡类型
        LocalTime workStartTime = rule.getWorkStartTime();
        int lateAllowMinutes = rule.getLateAllowMinutes() != null ? rule.getLateAllowMinutes() : 0;
        LocalTime lateThreshold = workStartTime.plusMinutes(lateAllowMinutes);
        LocalTime clockTimeOnly = clockTime.toLocalTime();
        Integer clockInType;
        if (onLeave) {
            // 请假当天:只要有打卡就算正常,迟到与否不影响考勤
            clockInType = HrmAttendanceClockTypeEnum.NORMAL.getType();
        } else {
            clockInType = clockTimeOnly.isBefore(lateThreshold) || clockTimeOnly.equals(lateThreshold)
                    ? HrmAttendanceClockTypeEnum.NORMAL.getType()
                    : HrmAttendanceClockTypeEnum.LATE.getType();
        }
        // 5. 创建或更新考勤记录
        if (record == null) {
            record = HrmAttendanceRecordDO.builder()
                    .userId(systemUserId)
                    .deptId(employee.getDeptId())
                    .date(clockDate)
                    .clockInTime(clockTime)
                    .clockInType(clockInType)
                    .dataSource(HrmAttendanceDataSourceEnum.CLOCK.getType())
                    .build();
            applyLeaveInfo(record, leaves, rule, clockDate);
            applyClockLocation(record, rule, clockLocation, legacyLocation, true);
            attendanceRecordMapper.insert(record);
        } else {
            record.setClockInTime(clockTime);
            record.setClockInType(clockInType);
            applyLeaveInfo(record, leaves, rule, clockDate);
            applyClockLocation(record, rule, clockLocation, legacyLocation, true);
            attendanceRecordMapper.updateById(record);
        }
        return new HrmAttendanceClockResult(record, rule,
                clockLocation != null ? clockLocation.distanceMeters() : null);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public HrmAttendanceClockResult clockOut(Long userId, LocalDateTime clockTime,
                                             HrmAttendanceClockReqVO reqVO, String legacyLocation) {
        LocalDate clockDate = clockTime.toLocalDate();
        // 1. 校验是否工作日
        if (!attendanceHolidayService.isWorkDay(clockDate)) {
            throw exception(ATTENDANCE_CLOCK_FAIL_NOT_WORKDAY);
        }
        // 2. 获取员工信息和考勤规则
        HrmEmployeeDO employee = employeeService.getEmployee(userId);
        if (employee == null) {
            throw exception(EMPLOYEE_NOT_EXISTS);
        }
        Long systemUserId = employee.getUserId();
        HrmAttendanceRuleDO rule = attendanceRuleService.getAttendanceRuleByDeptId(employee.getDeptId());
        if (rule == null) {
            throw exception(ATTENDANCE_CLOCK_FAIL_NO_RULE);
        }
        // 3. 查询当日考勤记录(系统用户 ID)
        HrmAttendanceRecordDO record = attendanceRecordMapper.selectByUserIdAndDate(systemUserId, clockDate);
        if (record != null && record.getClockOutTime() != null) {
            throw exception(ATTENDANCE_CLOCK_ALREADY_CLOCKED);
        }
        // 定位不合法时必须在创建“缺上班卡”记录前失败,避免留下脏数据。
        ClockLocation clockLocation = validateClockLocation(rule, reqVO);
        if (record == null) {
            record = HrmAttendanceRecordDO.builder()
                    .userId(systemUserId)
                    .deptId(employee.getDeptId())
                    .date(clockDate)
                    .clockInType(HrmAttendanceClockTypeEnum.MISSING.getType())
                    .dataSource(HrmAttendanceDataSourceEnum.CLOCK.getType())
                    .build();
        }
        // 3.1 当天请假情况:请假当天允许打卡,不判定为早退,也不算缺上班卡
        //     同上:用系统用户 ID 查请假表
        List<cn.iocoder.yudao.module.hrm.dal.dataobject.approval.HrmLeaveApplicationDO> leaves =
                leaveQueryService.getApprovedLeaveList(employee.getUserId(), clockDate);
        boolean onLeave = !leaves.isEmpty();
        if (onLeave && HrmAttendanceClockTypeEnum.MISSING.getType().equals(record.getClockInType())) {
            // 请假当天没打上班卡属于正常(人没来),不应记缺卡
            record.setClockInType(HrmAttendanceClockTypeEnum.LEAVE.getType());
        }
        // 4. 判断打卡类型
        LocalTime workEndTime = rule.getWorkEndTime();
        int earlyAllowMinutes = rule.getEarlyAllowMinutes() != null ? rule.getEarlyAllowMinutes() : 0;
        LocalTime earlyThreshold = workEndTime.minusMinutes(earlyAllowMinutes);
        LocalTime clockTimeOnly = clockTime.toLocalTime();
        Integer clockOutType;
        if (onLeave) {
            // 请假当天:有打卡就算正常
            clockOutType = HrmAttendanceClockTypeEnum.NORMAL.getType();
        } else {
            clockOutType = clockTimeOnly.isAfter(earlyThreshold) || clockTimeOnly.equals(earlyThreshold)
                    ? HrmAttendanceClockTypeEnum.NORMAL.getType()
                    : HrmAttendanceClockTypeEnum.EARLY.getType();
        }
        // 5. 更新考勤记录
        record.setClockOutTime(clockTime);
        record.setClockOutType(clockOutType);
        applyLeaveInfo(record, leaves, rule, clockDate);
        applyClockLocation(record, rule, clockLocation, legacyLocation, false);
        // 6. 计算工作时长
        if (record.getClockInTime() != null) {
            Duration duration = Duration.between(record.getClockInTime(), clockTime);
            BigDecimal workHours = BigDecimal.valueOf(duration.toMinutes())
                    .divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
            record.setWorkHours(workHours);
        }
        if (record.getId() == null) {
            attendanceRecordMapper.insert(record);
        } else {
            attendanceRecordMapper.updateById(record);
        }
        return new HrmAttendanceClockResult(record, rule,
                clockLocation != null ? clockLocation.distanceMeters() : null);
    }
 
    record ClockLocation(BigDecimal longitude, BigDecimal latitude, BigDecimal accuracy,
                         BigDecimal distanceMeters) { }
 
    ClockLocation validateClockLocation(HrmAttendanceRuleDO rule, HrmAttendanceClockReqVO reqVO) {
        boolean required = Boolean.TRUE.equals(rule.getLocationRequired());
        if (required && (StrUtil.isBlank(rule.getLocationName()) || rule.getLongitude() == null
                || rule.getLatitude() == null || rule.getRadiusMeters() == null
                || rule.getRadiusMeters() < 10 || rule.getRadiusMeters() > 5000
                || !"WGS84".equalsIgnoreCase(rule.getCoordinateSystem()))) {
            throw exception(ATTENDANCE_LOCATION_RULE_INVALID);
        }
        if (reqVO == null || reqVO.getLongitude() == null || reqVO.getLatitude() == null
                || reqVO.getAccuracy() == null || StrUtil.isBlank(reqVO.getCoordinateSystem())) {
            if (required) {
                throw exception(ATTENDANCE_LOCATION_REQUIRED);
            }
            return null;
        }
        boolean coordinatesValid = reqVO.getLongitude().compareTo(BigDecimal.valueOf(-180)) >= 0
                && reqVO.getLongitude().compareTo(BigDecimal.valueOf(180)) <= 0
                && reqVO.getLatitude().compareTo(BigDecimal.valueOf(-90)) >= 0
                && reqVO.getLatitude().compareTo(BigDecimal.valueOf(90)) <= 0;
        if (!coordinatesValid) {
            if (required) {
                throw exception(ATTENDANCE_LOCATION_COORDINATE_INVALID);
            }
            return null;
        }
        if (reqVO.getAccuracy().signum() <= 0
                || reqVO.getAccuracy().compareTo(BigDecimal.valueOf(100)) > 0) {
            if (required) {
                throw exception(ATTENDANCE_LOCATION_ACCURACY_INVALID);
            }
            return null;
        }
        if (!"WGS84".equalsIgnoreCase(reqVO.getCoordinateSystem().trim())) {
            if (required) {
                throw exception(ATTENDANCE_LOCATION_SYSTEM_INVALID);
            }
            return null;
        }
        if (!required) {
            return new ClockLocation(reqVO.getLongitude(), reqVO.getLatitude(), reqVO.getAccuracy(), null);
        }
        double rawDistance = haversineMeters(rule.getLongitude().doubleValue(), rule.getLatitude().doubleValue(),
                reqVO.getLongitude().doubleValue(), reqVO.getLatitude().doubleValue());
        BigDecimal roundedDistance = BigDecimal.valueOf(rawDistance).setScale(2, RoundingMode.HALF_UP);
        if (rawDistance > rule.getRadiusMeters()) {
            throw exception(ATTENDANCE_LOCATION_OUT_OF_RANGE, rule.getLocationName(),
                    roundedDistance.toPlainString(), rule.getRadiusMeters());
        }
        return new ClockLocation(reqVO.getLongitude(), reqVO.getLatitude(), reqVO.getAccuracy(), roundedDistance);
    }
 
    static double haversineMeters(double lon1, double lat1, double lon2, double lat2) {
        double latDelta = Math.toRadians(lat2 - lat1);
        double lonDelta = Math.toRadians(lon2 - lon1);
        double a = Math.pow(Math.sin(latDelta / 2), 2)
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
                * Math.pow(Math.sin(lonDelta / 2), 2);
        double bounded = Math.max(0D, Math.min(1D, a));
        return 6_371_000D * 2D * Math.atan2(Math.sqrt(bounded), Math.sqrt(1D - bounded));
    }
 
    private void applyClockLocation(HrmAttendanceRecordDO record, HrmAttendanceRuleDO rule,
                                    ClockLocation location, String legacyLocation, boolean clockIn) {
        if (StrUtil.isNotBlank(rule.getLocationName())) {
            record.setLocation(rule.getLocationName());
        } else if (!Boolean.TRUE.equals(rule.getLocationRequired()) && StrUtil.isNotBlank(legacyLocation)) {
            record.setLocation(legacyLocation);
        }
        if (location == null) {
            return;
        }
        if (clockIn) {
            record.setClockInLongitude(location.longitude());
            record.setClockInLatitude(location.latitude());
            record.setClockInAccuracy(location.accuracy());
            record.setClockInDistance(location.distanceMeters());
            record.setClockInAddress(rule.getLocationAddress());
        } else {
            record.setClockOutLongitude(location.longitude());
            record.setClockOutLatitude(location.latitude());
            record.setClockOutAccuracy(location.accuracy());
            record.setClockOutDistance(location.distanceMeters());
            record.setClockOutAddress(rule.getLocationAddress());
        }
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void supplementClockIn(HrmAttendanceExceptionDO exception) {
        // 仅处理补卡类型
        if (!HrmAttendanceExceptionTypeEnum.SUPPLEMENT.getType().equals(exception.getType())) {
            return;
        }
        LocalDate exceptionDate = exception.getExceptionDate();
        LocalDateTime exceptionTime = exception.getExceptionTime();
        Long userId = exception.getUserId();
        // 查询考勤记录
        HrmAttendanceRecordDO record = attendanceRecordMapper.selectByUserIdAndDate(userId, exceptionDate);
        if (record == null) {
            // 如果没有记录,创建一条
            HrmEmployeeDO employee = employeeService.getEmployee(userId);
            record = HrmAttendanceRecordDO.builder()
                    .userId(userId)
                    .deptId(employee != null ? employee.getDeptId() : exception.getDeptId())
                    .date(exceptionDate)
                    .dataSource(HrmAttendanceDataSourceEnum.SUPPLEMENT.getType())
                    .build();
            attendanceRecordMapper.insert(record);
        }
        // 根据异常时间判断是上班还是下班补卡
        LocalTime time = exceptionTime.toLocalTime();
        if (time.isBefore(LocalTime.of(12, 0))) {
            // 上班补卡
            record.setClockInTime(exceptionTime);
            record.setClockInType(HrmAttendanceClockTypeEnum.NORMAL.getType());
        } else {
            // 下班补卡
            record.setClockOutTime(exceptionTime);
            record.setClockOutType(HrmAttendanceClockTypeEnum.NORMAL.getType());
        }
        // 更新数据来源为补卡审批
        record.setDataSource(HrmAttendanceDataSourceEnum.SUPPLEMENT.getType());
        // 计算工作时长
        if (record.getClockInTime() != null && record.getClockOutTime() != null) {
            Duration duration = Duration.between(record.getClockInTime(), record.getClockOutTime());
            BigDecimal workHours = BigDecimal.valueOf(duration.toMinutes())
                    .divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
            record.setWorkHours(workHours);
        }
        attendanceRecordMapper.updateById(record);
    }
 
}