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
package cn.iocoder.yudao.module.hrm.service.approval;
 
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.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.hrm.controller.admin.approval.vo.HrmRegularizeApplicationPageReqVO;
import cn.iocoder.yudao.module.hrm.controller.admin.approval.vo.HrmRegularizeApplicationRespVO;
import cn.iocoder.yudao.module.hrm.controller.admin.approval.vo.HrmRegularizeApplicationSaveReqVO;
import cn.iocoder.yudao.module.hrm.dal.dataobject.approval.HrmRegularizeApplicationDO;
import cn.iocoder.yudao.module.hrm.dal.dataobject.employee.HrmEmployeeDO;
import cn.iocoder.yudao.module.hrm.dal.mysql.approval.HrmRegularizeApplicationMapper;
import cn.iocoder.yudao.module.hrm.dal.mysql.employee.HrmEmployeeMapper;
import cn.iocoder.yudao.module.hrm.dal.redis.HrmNoRedisDAO;
import cn.iocoder.yudao.module.hrm.enums.HrmAuditStatusEnum;
import cn.iocoder.yudao.module.hrm.enums.HrmEmploymentTypeEnum;
import cn.iocoder.yudao.module.system.api.approval.ApprovalConfigApi;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.PostApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.dept.dto.PostRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
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.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
 
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.hrm.enums.ErrorCodeConstants.*;
 
/**
 * 转正申请 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
@Slf4j
public class HrmRegularizeApplicationServiceImpl implements HrmRegularizeApplicationService {
 
    /**
     * 转正申请审批的业务类型编码
     *
     * 与 system_approval_config.biz_type 对应,审批人在「系统管理 - 审批配置」中维护。
     */
    private static final String REGULARIZE_APPROVE_BIZ_TYPE = "hrm_regularize_approve";
 
    /**
     * 员工状态:在职
     */
    private static final Integer EMPLOYEE_STATUS_ACTIVE = 1;
 
    /**
     * 用工性质:正式
     */
    private static final Integer EMPLOYMENT_TYPE_FORMAL = 1;
 
    @Resource
    private HrmRegularizeApplicationMapper regularizeApplicationMapper;
    @Resource
    private HrmNoRedisDAO noRedisDAO;
    @Resource
    private DeptApi deptApi;
    @Resource
    private PostApi postApi;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private ApprovalConfigApi approvalConfigApi;
    @Resource
    private HrmEmployeeMapper employeeMapper;
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createRegularizeApplication(HrmRegularizeApplicationSaveReqVO createReqVO) {
        Long userId = createReqVO.getUserId();
        if (userId == null) {
            userId = getCurrentUserId();
        }
        HrmRegularizeApplicationDO existing = regularizeApplicationMapper.selectByUserIdAndStatusNot(userId,
                HrmAuditStatusEnum.CANCEL.getStatus());
        if (existing != null) {
            throw exception(REGULARIZE_APPLICATION_EXISTS);
        }
        String no = generateUniqueNo();
        AdminUserRespDTO user = adminUserApi.getUser(userId);
        if (user == null) {
            userId = getCurrentUserId();
            user = adminUserApi.getUser(userId);
        }
        HrmRegularizeApplicationDO application = BeanUtils.toBean(createReqVO, HrmRegularizeApplicationDO.class);
        application.setNo(no);
        application.setUserId(userId);
        application.setDeptId(createReqVO.getDeptId() != null ? createReqVO.getDeptId()
                : (user != null ? user.getDeptId() : null));
        application.setStatus(HrmAuditStatusEnum.DRAFT.getStatus());
        regularizeApplicationMapper.insert(application);
        return application.getId();
    }
 
    private Long getCurrentUserId() {
        return SecurityFrameworkUtils.getLoginUserId();
    }
 
    private String generateUniqueNo() {
        String no = noRedisDAO.generateRegularizeApplicationNo();
        if (regularizeApplicationMapper.selectByNo(no) != null) {
            return generateUniqueNo();
        }
        return no;
    }
 
    @Override
    public void updateRegularizeApplication(HrmRegularizeApplicationSaveReqVO updateReqVO) {
        HrmRegularizeApplicationDO application = validateRegularizeApplicationExists(updateReqVO.getId());
        if (!Objects.equals(application.getStatus(), HrmAuditStatusEnum.DRAFT.getStatus())) {
            throw exception(REGULARIZE_APPLICATION_UPDATE_FAIL_NOT_DRAFT);
        }
        HrmRegularizeApplicationDO updateObj = BeanUtils.toBean(updateReqVO, HrmRegularizeApplicationDO.class);
        regularizeApplicationMapper.updateById(updateObj);
    }
 
    @Override
    public void deleteRegularizeApplication(Long id) {
        HrmRegularizeApplicationDO application = validateRegularizeApplicationExists(id);
        if (!Objects.equals(application.getStatus(), HrmAuditStatusEnum.DRAFT.getStatus())) {
            throw exception(REGULARIZE_APPLICATION_UPDATE_FAIL_NOT_DRAFT);
        }
        regularizeApplicationMapper.deleteById(id);
    }
 
    private HrmRegularizeApplicationDO validateRegularizeApplicationExists(Long id) {
        HrmRegularizeApplicationDO application = regularizeApplicationMapper.selectById(id);
        if (application == null) {
            throw exception(REGULARIZE_APPLICATION_NOT_EXISTS);
        }
        return application;
    }
 
    @Override
    public HrmRegularizeApplicationDO getRegularizeApplication(Long id) {
        return regularizeApplicationMapper.selectById(id);
    }
 
    @Override
    public HrmRegularizeApplicationRespVO getRegularizeApplicationDetail(Long id) {
        HrmRegularizeApplicationDO application = getRegularizeApplication(id);
        if (application == null) {
            return null;
        }
        HrmRegularizeApplicationRespVO respVO = BeanUtils.toBean(application, HrmRegularizeApplicationRespVO.class);
        fillUserNames(respVO, application);
        if (application.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(application.getDeptId());
            if (dept != null) {
                respVO.setDeptName(dept.getName());
            }
        }
        if (application.getPostId() != null) {
            Map<Long, PostRespDTO> postMap = postApi.getPostMap(Collections.singleton(application.getPostId()));
            PostRespDTO post = postMap.get(application.getPostId());
            if (post != null) {
                respVO.setPostName(post.getName());
            }
        }
        respVO.setEmploymentTypeName(HrmEmploymentTypeEnum.getNameByType(application.getEmploymentType()));
        respVO.setStatusName(HrmAuditStatusEnum.getNameByStatus(application.getStatus()));
        return respVO;
    }
 
    private void fillUserNames(HrmRegularizeApplicationRespVO respVO, HrmRegularizeApplicationDO application) {
        if (application.getUserId() != null) {
            AdminUserRespDTO user = adminUserApi.getUser(application.getUserId());
            if (user != null) {
                respVO.setUserName(user.getNickname());
            }
        }
    }
 
    @Override
    public PageResult<HrmRegularizeApplicationRespVO> getRegularizeApplicationPage(HrmRegularizeApplicationPageReqVO pageReqVO) {
        PageResult<HrmRegularizeApplicationDO> pageResult = regularizeApplicationMapper.selectPage(pageReqVO);
        if (pageResult.getList().isEmpty()) {
            return new PageResult<>(Collections.emptyList(), pageResult.getTotal());
        }
        Set<Long> userIds = pageResult.getList().stream()
                .map(HrmRegularizeApplicationDO::getUserId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(userIds);
        Set<Long> deptIds = pageResult.getList().stream()
                .map(HrmRegularizeApplicationDO::getDeptId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMap(deptIds);
        Set<Long> postIds = pageResult.getList().stream()
                .map(HrmRegularizeApplicationDO::getPostId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        Map<Long, PostRespDTO> postMap = postApi.getPostMap(postIds);
        List<HrmRegularizeApplicationRespVO> list = pageResult.getList().stream().map(app -> {
            HrmRegularizeApplicationRespVO vo = BeanUtils.toBean(app, HrmRegularizeApplicationRespVO.class);
            if (app.getUserId() != null && userMap.containsKey(app.getUserId())) {
                vo.setUserName(userMap.get(app.getUserId()).getNickname());
            }
            if (app.getDeptId() != null && deptMap.containsKey(app.getDeptId())) {
                vo.setDeptName(deptMap.get(app.getDeptId()).getName());
            }
            if (app.getPostId() != null && postMap.containsKey(app.getPostId())) {
                vo.setPostName(postMap.get(app.getPostId()).getName());
            }
            vo.setEmploymentTypeName(HrmEmploymentTypeEnum.getNameByType(app.getEmploymentType()));
            vo.setStatusName(HrmAuditStatusEnum.getNameByStatus(app.getStatus()));
            return vo;
        }).collect(Collectors.toList());
        return new PageResult<>(list, pageResult.getTotal());
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitRegularizeApplication(Long id) {
        // 1. 校验存在 + 可提交状态(草稿 / 审核不通过)
        HrmRegularizeApplicationDO application = validateRegularizeApplicationExists(id);
        if (!Objects.equals(application.getStatus(), HrmAuditStatusEnum.DRAFT.getStatus())
                && !Objects.equals(application.getStatus(), HrmAuditStatusEnum.REJECT.getStatus())) {
            throw exception(REGULARIZE_APPLICATION_SUBMIT_FAIL_NOT_EDITABLE);
        }
 
        // 2. 校验审批配置已启用且配置了有效审批人(未配置时抛出带明确提示的业务异常)
        approvalConfigApi.validateApprovalEnabledAndGetApprovers(REGULARIZE_APPROVE_BIZ_TYPE);
 
        // 3. 状态置为审批中,并清空上一轮审核结果,避免残留「审核不通过」的原因
        regularizeApplicationMapper.submitAndResetAuditInfo(id, HrmAuditStatusEnum.PROCESS.getStatus());
    }
 
    @Override
    public Set<Long> getRegularizeApplicationApproverUserIds() {
        return approvalConfigApi.getApproverUserIds(REGULARIZE_APPROVE_BIZ_TYPE);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditRegularizeApplication(Long id, Boolean pass, String reviewRemark) {
        // 1. 校验存在
        HrmRegularizeApplicationDO application = validateRegularizeApplicationExists(id);
        // 2. 校验处于审批中状态
        if (!Objects.equals(application.getStatus(), HrmAuditStatusEnum.PROCESS.getStatus())) {
            throw exception(REGULARIZE_APPLICATION_AUDIT_FAIL_NOT_PROCESS);
        }
        // 3. 校验当前登录用户是该业务类型的审批人(或签:任一人均可审核)
        Long userId = getLoginUserId();
        approvalConfigApi.validateApprover(REGULARIZE_APPROVE_BIZ_TYPE, userId);
        // 4. 审核不通过:必须填写原因,状态置为审核不通过,退回提交人修改后可重新提交
        if (!Boolean.TRUE.equals(pass)) {
            if (StrUtil.isBlank(reviewRemark)) {
                throw exception(REGULARIZE_APPLICATION_AUDIT_REJECT_REASON_REQUIRED);
            }
            regularizeApplicationMapper.auditRegularizeApplication(id, HrmAuditStatusEnum.REJECT.getStatus(),
                    userId, getUserNickname(userId), reviewRemark);
            return;
        }
        // 5. 审核通过:记录审核人与审核意见,状态置为审核通过
        regularizeApplicationMapper.auditRegularizeApplication(id, HrmAuditStatusEnum.APPROVE.getStatus(),
                userId, getUserNickname(userId), reviewRemark);
 
        // 6. 审核通过后置业务逻辑:回写员工主档(状态=在职,用工性质=正式,转正日期 = 拟转正日期或当天)
        writeBackEmployee(application);
    }
 
    /**
     * 审核通过后回写员工主档
     *
     * @param application 转正申请
     */
    private void writeBackEmployee(HrmRegularizeApplicationDO application) {
        HrmEmployeeDO employee = employeeMapper.selectByUserId(application.getUserId());
        if (employee == null) {
            log.warn("[writeBackEmployee] 转正申请({}) 用户({}) 未找到员工档案,跳过回写", application.getId(), application.getUserId());
            return;
        }
        LocalDate regularDate = application.getExpectedDate() != null ? application.getExpectedDate() : LocalDate.now();
        employeeMapper.updateById(HrmEmployeeDO.builder()
                .id(employee.getId())
                .employeeStatus(EMPLOYEE_STATUS_ACTIVE)
                .employmentType(EMPLOYMENT_TYPE_FORMAL)
                .regularDate(regularDate)
                .build());
    }
 
    /**
     * 获取用户昵称
     *
     * @param userId 用户编号
     * @return 昵称,用户不存在时返回 null
     */
    private String getUserNickname(Long userId) {
        if (userId == null) {
            return null;
        }
        AdminUserRespDTO user = adminUserApi.getUser(userId);
        return user == null ? null : user.getNickname();
    }
 
}