liu
19 小时以前 76bf0caef9a6f4b7daae7e7b1d09b0c9044aebef
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
package cn.iocoder.yudao.module.hrm.controller.admin.attendance;
 
import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.hrm.controller.admin.attendance.vo.HrmAttendanceRecordImportExcelVO;
import cn.iocoder.yudao.module.hrm.controller.admin.attendance.vo.HrmAttendanceRecordImportReqVO;
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.dal.dataobject.attendance.HrmAttendanceRecordDO;
import cn.iocoder.yudao.module.hrm.dal.dataobject.employee.HrmEmployeeDO;
import cn.iocoder.yudao.module.hrm.service.attendance.HrmAttendanceRecordService;
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 cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
 
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
 
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.hrm.enums.ErrorCodeConstants.EMPLOYEE_NOT_EXISTS;
 
@Tag(name = "管理后台 - HRM 考勤记录")
@RestController
@RequestMapping("/hrm/attendance/record")
@Validated
public class HrmAttendanceRecordController {
 
    @Resource
    private HrmAttendanceRecordService attendanceRecordService;
    @Resource
    private HrmEmployeeService employeeService;
    @Resource
    private DeptApi deptApi;
    @Resource
    private AdminUserApi adminUserApi;
 
    @PostMapping("/clock-in")
    @Operation(summary = "上班打卡")
    @PreAuthorize("@ss.hasPermission('hrm:attendance:clock')")
    public CommonResult<HrmAttendanceRecordRespVO> clockIn(@RequestParam("location") String location) {
        Long loginUserId = getLoginUserId();
        HrmEmployeeDO employee = employeeService.getEmployeeByUserId(loginUserId);
        if (employee == null) {
            throw exception(EMPLOYEE_NOT_EXISTS, "当前用户未关联员工信息,无法打卡");
        }
        HrmAttendanceRecordDO record = attendanceRecordService.clockIn(employee.getId(), LocalDateTime.now(), location);
        HrmAttendanceRecordRespVO respVO = BeanUtils.toBean(record, HrmAttendanceRecordRespVO.class);
        respVO.setUserName(employee.getName());
        if (record.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(record.getDeptId());
            if (dept != null) {
                respVO.setDeptName(dept.getName());
            }
        }
        return success(respVO);
    }
 
    @PostMapping("/clock-out")
    @Operation(summary = "下班打卡")
    @PreAuthorize("@ss.hasPermission('hrm:attendance:clock')")
    public CommonResult<HrmAttendanceRecordRespVO> clockOut(@RequestParam("location") String location) {
        Long loginUserId = getLoginUserId();
        HrmEmployeeDO employee = employeeService.getEmployeeByUserId(loginUserId);
        if (employee == null) {
            throw exception(EMPLOYEE_NOT_EXISTS, "当前用户未关联员工信息,无法打卡");
        }
        HrmAttendanceRecordDO record = attendanceRecordService.clockOut(employee.getId(), LocalDateTime.now(), location);
        HrmAttendanceRecordRespVO respVO = BeanUtils.toBean(record, HrmAttendanceRecordRespVO.class);
        respVO.setUserName(employee.getName());
        if (record.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(record.getDeptId());
            if (dept != null) {
                respVO.setDeptName(dept.getName());
            }
        }
        return success(respVO);
    }
 
    private Long getLoginUserId() {
        return cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId();
    }
 
    @GetMapping("/page")
    @Operation(summary = "获得考勤记录分页")
    @PreAuthorize("@ss.hasPermission('hrm:attendance:query')")
    public CommonResult<PageResult<HrmAttendanceRecordRespVO>> getAttendanceRecordPage(@Valid HrmAttendanceRecordPageReqVO pageReqVO) {
        PageResult<HrmAttendanceRecordDO> pageResult = attendanceRecordService.getAttendanceRecordPage(pageReqVO);
        // 转换为 VO
        List<HrmAttendanceRecordRespVO> list = BeanUtils.toBean(pageResult.getList(), HrmAttendanceRecordRespVO.class);
        // 填充员工和部门信息
        if (CollUtil.isNotEmpty(list)) {
            fillUserInfo(list, pageResult.getList());
        }
        return success(new PageResult<>(list, pageResult.getTotal()));
    }
 
    /**
     * 填充员工和部门信息
     * 注意:考勤记录的 userId 是员工ID,不是系统用户ID
     */
    private void fillUserInfo(List<HrmAttendanceRecordRespVO> respList, List<HrmAttendanceRecordDO> recordList) {
        // 批量获取员工信息(userId 是员工ID)
        Set<Long> employeeIds = recordList.stream()
                .map(HrmAttendanceRecordDO::getUserId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        Map<Long, HrmEmployeeDO> employeeMap = new HashMap<>();
        for (Long employeeId : employeeIds) {
            HrmEmployeeDO employee = employeeService.getEmployee(employeeId);
            if (employee != null) {
                employeeMap.put(employeeId, employee);
            }
        }
        // 批量获取部门信息
        Set<Long> deptIds = recordList.stream()
                .map(HrmAttendanceRecordDO::getDeptId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        Map<Long, DeptRespDTO> deptMap = CollUtil.isEmpty(deptIds) ? Collections.emptyMap() : deptApi.getDeptMap(deptIds);
 
        // 填充信息
        for (HrmAttendanceRecordRespVO respVO : respList) {
            // 通过员工ID获取员工信息,再获取员工姓名
            HrmEmployeeDO employee = employeeMap.get(respVO.getUserId());
            if (employee != null) {
                respVO.setUserName(employee.getName());
                respVO.setPhone(employee.getPhone());
            }
            // 部门名称
            DeptRespDTO dept = deptMap.get(respVO.getDeptId());
            if (dept != null) {
                respVO.setDeptName(dept.getName());
            }
        }
    }
 
    @GetMapping("/get")
    @Operation(summary = "获得考勤记录")
    @Parameter(name = "id", description = "记录ID", required = true)
    @PreAuthorize("@ss.hasPermission('hrm:attendance:query')")
    public CommonResult<HrmAttendanceRecordRespVO> getAttendanceRecord(@RequestParam("id") Long id) {
        HrmAttendanceRecordDO attendanceRecord = attendanceRecordService.getAttendanceRecord(id);
        if (attendanceRecord == null) {
            return success(null);
        }
        HrmAttendanceRecordRespVO respVO = BeanUtils.toBean(attendanceRecord, HrmAttendanceRecordRespVO.class);
        // 填充员工和部门信息(userId 是员工ID)
        if (attendanceRecord.getUserId() != null) {
            HrmEmployeeDO employee = employeeService.getEmployee(attendanceRecord.getUserId());
            if (employee != null) {
                respVO.setUserName(employee.getName());
                respVO.setPhone(employee.getPhone());
            }
        }
        if (attendanceRecord.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(attendanceRecord.getDeptId());
            if (dept != null) {
                respVO.setDeptName(dept.getName());
            }
        }
        return success(respVO);
    }
 
    @GetMapping("/get-import-template")
    @Operation(summary = "下载考勤记录导入模板")
    @PreAuthorize("@ss.hasPermission('hrm:attendance-record:import')")
    public void importTemplate(HttpServletResponse response) throws IOException {
        List<HrmAttendanceRecordImportExcelVO> list = Collections.singletonList(
                HrmAttendanceRecordImportExcelVO.builder()
                        .userName("张三")
                        .phone("13800138000")
                        .date(java.time.LocalDate.of(2026, 1, 15))
                        .clockInTime(java.time.LocalDateTime.of(2026, 1, 15, 8, 30))
                        .clockOutTime(java.time.LocalDateTime.of(2026, 1, 15, 17, 30))
                        .clockInType(1)
                        .clockOutType(1)
                        .location("办公区")
                        .remark("示例数据")
                        .build()
        );
        ExcelUtils.write(response, "考勤导入模板.xls", "考勤记录", HrmAttendanceRecordImportExcelVO.class, list);
    }
 
    @PostMapping("/import")
    @Operation(summary = "导入考勤记录")
    @PreAuthorize("@ss.hasPermission('hrm:attendance-record:import')")
    public CommonResult<String> importExcel(@Valid HrmAttendanceRecordImportReqVO importReqVO) throws IOException {
        List<HrmAttendanceRecordImportExcelVO> list = ExcelUtils.read(importReqVO.getFile(), HrmAttendanceRecordImportExcelVO.class);
        if (CollUtil.isEmpty(list)) {
            return success("没有可导入的数据");
        }
        int successCount = 0;
        Set<String> missingNames = new LinkedHashSet<>();
        Set<String> duplicateNames = new LinkedHashSet<>();
        Set<String> invalidRows = new LinkedHashSet<>();
        for (HrmAttendanceRecordImportExcelVO item : list) {
            if (item.getDate() == null) {
                invalidRows.add((item.getUserName() == null || item.getUserName().isBlank()) ? "未填姓名的行" : "考勤日期为空(" + item.getUserName().trim() + ")");
                continue;
            }
            if (item.getUserName() == null || item.getUserName().isBlank()) {
                invalidRows.add("考勤日期为 " + item.getDate() + " 但未填员工姓名");
                continue;
            }
            List<HrmEmployeeDO> employees = employeeService.getEmployeeListByName(item.getUserName().trim());
            if (employees.isEmpty()) {
                missingNames.add(item.getUserName().trim());
                continue;
            }
            HrmEmployeeDO employee = employees.get(0);
            // 存在多个同名员工时,用手机号区分
            if (employees.size() > 1) {
                String phone = item.getPhone() != null ? item.getPhone().trim() : null;
                List<HrmEmployeeDO> matchedByPhone = new ArrayList<>();
                if (phone != null && !phone.isEmpty()) {
                    for (HrmEmployeeDO emp : employees) {
                        if (phone.equals(emp.getPhone())) {
                            matchedByPhone.add(emp);
                        }
                    }
                }
                if (matchedByPhone.size() == 1) {
                    employee = matchedByPhone.get(0);
                } else {
                    duplicateNames.add(item.getUserName().trim());
                    continue;
                }
            }
            HrmAttendanceRecordDO record = attendanceRecordService.getAttendanceRecordByUserIdAndDate(employee.getId(), item.getDate());
            if (record == null) {
                record = HrmAttendanceRecordDO.builder()
                        .userId(employee.getId()).deptId(employee.getDeptId()).date(item.getDate())
                        .clockInTime(item.getClockInTime()).clockOutTime(item.getClockOutTime())
                        .clockInType(item.getClockInType()).clockOutType(item.getClockOutType())
                        .location(item.getLocation()).remark(item.getRemark())
                        .dataSource(2).build();
                attendanceRecordService.createImportedRecord(record);
            } else if (Boolean.TRUE.equals(importReqVO.getUpdateSupport())) {
                record.setClockInTime(item.getClockInTime());
                record.setClockOutTime(item.getClockOutTime());
                record.setClockInType(item.getClockInType());
                record.setClockOutType(item.getClockOutType());
                record.setLocation(item.getLocation());
                record.setRemark(item.getRemark());
                attendanceRecordService.updateImportedRecord(record);
            }
            successCount++;
        }
        StringBuilder msg = new StringBuilder("成功导入 " + successCount + " 条");
        if (!missingNames.isEmpty()) {
            msg.append(";以下员工不存在,未能导入:").append(String.join("、", missingNames));
        }
        if (!duplicateNames.isEmpty()) {
            msg.append(";以下员工存在多名同名员工,需补充手机号区分,未能导入:").append(String.join("、", duplicateNames));
        }
        if (!invalidRows.isEmpty()) {
            msg.append(";以下记录数据不完整,未能导入:").append(String.join("、", invalidRows));
        }
        return success(msg.toString());
    }
 
    @GetMapping("/export-excel")
    @Operation(summary = "导出考勤记录 Excel")
    @PreAuthorize("@ss.hasPermission('hrm:attendance:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportAttendanceRecordExcel(@Valid HrmAttendanceRecordPageReqVO pageReqVO,
                                              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        PageResult<HrmAttendanceRecordDO> pageResult = attendanceRecordService.getAttendanceRecordPage(pageReqVO);
        List<HrmAttendanceRecordDO> recordList = pageResult.getList();
        // 转换为 VO
        List<HrmAttendanceRecordRespVO> list = BeanUtils.toBean(recordList, HrmAttendanceRecordRespVO.class);
        // 填充员工和部门信息
        if (CollUtil.isNotEmpty(list)) {
            fillUserInfo(list, recordList);
        }
        ExcelUtils.write(response, "考勤记录.xls", "数据", HrmAttendanceRecordRespVO.class, list);
    }
 
}