package cn.iocoder.yudao.module.hrm.service.approval; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ObjUtil; 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.bpm.api.task.BpmProcessInstanceApi; import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO; import cn.iocoder.yudao.module.bpm.dal.dataobject.definition.BpmProcessDefinitionInfoDO; import cn.iocoder.yudao.module.bpm.service.definition.BpmCategoryService; import cn.iocoder.yudao.module.bpm.service.definition.BpmProcessDefinitionService; import cn.iocoder.yudao.module.hrm.controller.admin.approval.vo.HrmResignationApplicationPageReqVO; import cn.iocoder.yudao.module.hrm.controller.admin.approval.vo.HrmResignationApplicationRespVO; import cn.iocoder.yudao.module.hrm.controller.admin.approval.vo.HrmResignationApplicationSaveReqVO; import cn.iocoder.yudao.module.hrm.controller.admin.approval.vo.HrmResignationHandoverReqVO; import cn.iocoder.yudao.module.hrm.controller.admin.employee.vo.HrmEmployeeSaveReqVO; import cn.iocoder.yudao.module.hrm.dal.dataobject.approval.HrmResignationApplicationDO; import cn.iocoder.yudao.module.hrm.dal.dataobject.employee.HrmEmployeeDO; import cn.iocoder.yudao.module.hrm.dal.mysql.approval.HrmResignationApplicationMapper; import cn.iocoder.yudao.module.hrm.dal.redis.HrmNoRedisDAO; import cn.iocoder.yudao.module.hrm.enums.HrmAuditStatusEnum; import cn.iocoder.yudao.module.hrm.enums.HrmEmployeeStatusEnum; import cn.iocoder.yudao.module.hrm.enums.HrmResignationTypeEnum; import cn.iocoder.yudao.module.hrm.service.employee.HrmEmployeeService; import cn.iocoder.yudao.module.hrm.service.handover.HrmUserHandoverService; 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.storage.StorageAttachmentApi; 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.flowable.engine.repository.ProcessDefinition; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet; import static cn.iocoder.yudao.module.hrm.enums.ErrorCodeConstants.*; /** * 离职申请 Service 实现类 * * @author 超级管理员 */ @Service @Validated @Slf4j public class HrmResignationApplicationServiceImpl implements HrmResignationApplicationService { private static final Integer HANDOVER_STATUS_NOT_STARTED = 0; private static final Integer HANDOVER_STATUS_IN_PROGRESS = 10; private static final Integer HANDOVER_STATUS_COMPLETED = 20; @Resource private HrmResignationApplicationMapper resignationApplicationMapper; @Resource private HrmNoRedisDAO noRedisDAO; @Resource private DeptApi deptApi; @Resource private AdminUserApi adminUserApi; @Resource private BpmProcessInstanceApi bpmProcessInstanceApi; @Resource private BpmCategoryService bpmCategoryService; @Resource private StorageAttachmentApi storageAttachmentApi; @Resource private BpmProcessDefinitionService bpmProcessDefinitionService; @Resource private HrmUserHandoverService handoverService; @Resource private HrmEmployeeService employeeService; @Override @Transactional(rollbackFor = Exception.class) public Long createResignationApplication(HrmResignationApplicationSaveReqVO createReqVO) { // 1. 解析申请人:优先按前端选择的员工(employeeId)反查档案,拿到 system_users.id Long userId = createReqVO.getUserId(); Long employeeId = createReqVO.getEmployeeId(); HrmEmployeeDO employee = null; if (employeeId != null) { employee = employeeService.getEmployee(employeeId); } if (employee == null && userId != null) { // 约定 user_id 存 system_users.id;历史数据也有存「员工主键」的,两种都兼容 employee = employeeService.getEmployeeByUserId(userId); if (employee == null) { employee = employeeService.getEmployee(userId); } } if (employee != null && employee.getUserId() != null) { userId = employee.getUserId(); } if (userId == null) { userId = getCurrentUserId(); } HrmResignationApplicationDO existing = resignationApplicationMapper.selectByUserIdAndStatusNot(userId, HrmAuditStatusEnum.CANCEL.getStatus()); if (existing != null) { throw exception(RESIGNATION_APPLICATION_EXISTS); } String no = generateUniqueNo(); AdminUserRespDTO user = adminUserApi.getUser(userId); if (user == null) { userId = getCurrentUserId(); user = adminUserApi.getUser(userId); } HrmResignationApplicationDO application = BeanUtils.toBean(createReqVO, HrmResignationApplicationDO.class); application.setNo(no); application.setUserId(userId); // 部门:优先用请求里的,其次员工档案,最后用户档案 Long deptId = createReqVO.getDeptId(); if (deptId == null && employee != null) { deptId = employee.getDeptId(); } if (deptId == null && user != null) { deptId = user.getDeptId(); } application.setDeptId(deptId); application.setStatus(HrmAuditStatusEnum.DRAFT.getStatus()); application.setHandoverStatus(HANDOVER_STATUS_NOT_STARTED); resignationApplicationMapper.insert(application); storageAttachmentApi.bindAttachments("file", "hrm_resignation_application", application.getId(), createReqVO.getBlobIds()); return application.getId(); } private Long getCurrentUserId() { return 1L; } private String generateUniqueNo() { String no = noRedisDAO.generateResignationApplicationNo(); if (resignationApplicationMapper.selectByNo(no) != null) { return generateUniqueNo(); } return no; } @Override public void updateResignationApplication(HrmResignationApplicationSaveReqVO updateReqVO) { HrmResignationApplicationDO application = validateResignationApplicationExists(updateReqVO.getId()); if (!Objects.equals(application.getStatus(), HrmAuditStatusEnum.DRAFT.getStatus())) { throw exception(RESIGNATION_APPLICATION_UPDATE_FAIL_NOT_DRAFT); } HrmResignationApplicationDO updateObj = BeanUtils.toBean(updateReqVO, HrmResignationApplicationDO.class); resignationApplicationMapper.updateById(updateObj); storageAttachmentApi.updateAttachments("file", "hrm_resignation_application", updateReqVO.getId(), updateReqVO.getBlobIds()); } @Override public void deleteResignationApplication(Long id) { HrmResignationApplicationDO application = validateResignationApplicationExists(id); if (!Objects.equals(application.getStatus(), HrmAuditStatusEnum.DRAFT.getStatus())) { throw exception(RESIGNATION_APPLICATION_UPDATE_FAIL_NOT_DRAFT); } storageAttachmentApi.deleteAttachmentsByRecord("hrm_resignation_application", id); resignationApplicationMapper.deleteById(id); } private HrmResignationApplicationDO validateResignationApplicationExists(Long id) { HrmResignationApplicationDO application = resignationApplicationMapper.selectById(id); if (application == null) { throw exception(RESIGNATION_APPLICATION_NOT_EXISTS); } return application; } @Override public HrmResignationApplicationDO getResignationApplication(Long id) { return resignationApplicationMapper.selectById(id); } @Override public HrmResignationApplicationRespVO getResignationApplicationDetail(Long id) { HrmResignationApplicationDO application = getResignationApplication(id); if (application == null) { return null; } HrmResignationApplicationRespVO respVO = BeanUtils.toBean(application, HrmResignationApplicationRespVO.class); fillUserNames(respVO, application); if (application.getDeptId() != null) { DeptRespDTO dept = deptApi.getDept(application.getDeptId()); if (dept != null) { respVO.setDeptName(dept.getName()); } } respVO.setResignationTypeName(HrmResignationTypeEnum.getNameByStatus(application.getResignationType())); respVO.setHandoverStatusName(getHandoverStatusName(application.getHandoverStatus())); respVO.setStatusName(HrmAuditStatusEnum.getNameByStatus(application.getStatus())); respVO.setAttachmentList(storageAttachmentApi.listAttachments("hrm_resignation_application", id)); return respVO; } private void fillUserNames(HrmResignationApplicationRespVO respVO, HrmResignationApplicationDO application) { Set userIds = Set.of(application.getUserId(), application.getHandoverUserId()) .stream().filter(Objects::nonNull).collect(Collectors.toSet()); Map userMap = adminUserApi.getUserMap(userIds); if (application.getUserId() != null && userMap.containsKey(application.getUserId())) { respVO.setUserName(userMap.get(application.getUserId()).getNickname()); } if (application.getHandoverUserId() != null && userMap.containsKey(application.getHandoverUserId())) { respVO.setHandoverUserName(userMap.get(application.getHandoverUserId()).getNickname()); } } private String getHandoverStatusName(Integer handoverStatus) { if (handoverStatus == null) { return ""; } if (Objects.equals(handoverStatus, HANDOVER_STATUS_NOT_STARTED)) { return "未开始"; } if (Objects.equals(handoverStatus, HANDOVER_STATUS_IN_PROGRESS)) { return "进行中"; } if (Objects.equals(handoverStatus, HANDOVER_STATUS_COMPLETED)) { return "已完成"; } return ""; } @Override public PageResult getResignationApplicationPage(HrmResignationApplicationPageReqVO pageReqVO) { PageResult pageResult = resignationApplicationMapper.selectPage(pageReqVO); if (pageResult.getList().isEmpty()) { return new PageResult<>(Collections.emptyList(), pageResult.getTotal()); } Set userIds = pageResult.getList().stream() .flatMap(app -> Stream.of(app.getUserId(), app.getHandoverUserId())) .filter(Objects::nonNull) .collect(Collectors.toSet()); Map userMap = adminUserApi.getUserMap(userIds); Set deptIds = pageResult.getList().stream() .map(HrmResignationApplicationDO::getDeptId) .filter(Objects::nonNull) .collect(Collectors.toSet()); Map deptMap = deptApi.getDeptMap(deptIds); List list = pageResult.getList().stream().map(app -> { HrmResignationApplicationRespVO vo = BeanUtils.toBean(app, HrmResignationApplicationRespVO.class); if (app.getUserId() != null && userMap.containsKey(app.getUserId())) { vo.setUserName(userMap.get(app.getUserId()).getNickname()); } if (app.getHandoverUserId() != null && userMap.containsKey(app.getHandoverUserId())) { vo.setHandoverUserName(userMap.get(app.getHandoverUserId()).getNickname()); } if (app.getDeptId() != null && deptMap.containsKey(app.getDeptId())) { vo.setDeptName(deptMap.get(app.getDeptId()).getName()); } vo.setResignationTypeName(HrmResignationTypeEnum.getNameByStatus(app.getResignationType())); vo.setHandoverStatusName(getHandoverStatusName(app.getHandoverStatus())); vo.setStatusName(HrmAuditStatusEnum.getNameByStatus(app.getStatus())); return vo; }).collect(Collectors.toList()); return new PageResult<>(list, pageResult.getTotal()); } @Override @Transactional(rollbackFor = Exception.class) public void submitResignationApplication(Long id, String processDefinitionKey, Long userId) { HrmResignationApplicationDO application = validateResignationApplicationExists(id); if (ObjUtil.notEqual(application.getStatus(), HrmAuditStatusEnum.DRAFT.getStatus())) { throw exception(RESIGNATION_APPLICATION_SUBMIT_FAIL_NOT_DRAFT); } validateApproveCategoryAndProcessDefinition(); // 前端不传流程定义 Key 时,自动取该审批分类下最新版本的活跃流程,避免「请求参数缺失:processDefinitionKey」 if (StrUtil.isBlank(processDefinitionKey)) { processDefinitionKey = resolveActiveProcessDefinitionKey(); } ProcessDefinition processDefinition = bpmProcessDefinitionService.getActiveProcessDefinition(processDefinitionKey); if (processDefinition == null) { throw exception(RESIGNATION_APPLICATION_BPM_PROCESS_DEFINITION_NOT_EXISTS); } String processInstanceId = bpmProcessInstanceApi.createProcessInstance(userId, new BpmProcessInstanceCreateReqDTO() .setProcessDefinitionKey(processDefinition.getKey()).setBusinessKey(String.valueOf(id))); resignationApplicationMapper.updateById(HrmResignationApplicationDO.builder() .id(id) .processInstanceId(processInstanceId) .status(HrmAuditStatusEnum.PROCESS.getStatus()) .build()); } private void validateApproveCategoryAndProcessDefinition() { List codes = Collections.singletonList(APPROVE_CATEGORY_CODE); Map categoryMap = bpmCategoryService.getCategoryMap(codes); if (!categoryMap.containsKey(APPROVE_CATEGORY_CODE)) { throw exception(RESIGNATION_APPLICATION_BPM_PROCESS_DEFINITION_NOT_EXISTS); } List definitionInfoList = bpmProcessDefinitionService .getProcessDefinitionInfoListByCategory(APPROVE_CATEGORY_CODE); if (CollUtil.isEmpty(definitionInfoList)) { throw exception(RESIGNATION_APPLICATION_BPM_PROCESS_DEFINITION_NOT_EXISTS); } Set processDefinitionIds = convertSet(definitionInfoList, BpmProcessDefinitionInfoDO::getProcessDefinitionId); List processDefinitions = bpmProcessDefinitionService.getProcessDefinitionList(processDefinitionIds); boolean hasActiveDefinition = processDefinitions.stream().anyMatch(pd -> !pd.isSuspended()); if (!hasActiveDefinition) { throw exception(RESIGNATION_APPLICATION_BPM_PROCESS_DEFINITION_NOT_EXISTS); } } @Override public List> getApproveProcessDefinitionList() { validateApproveCategoryAndProcessDefinition(); List definitionInfoList = bpmProcessDefinitionService .getProcessDefinitionInfoListByCategory(APPROVE_CATEGORY_CODE); Set processDefinitionIds = convertSet(definitionInfoList, BpmProcessDefinitionInfoDO::getProcessDefinitionId); List processDefinitions = bpmProcessDefinitionService.getProcessDefinitionList(processDefinitionIds); Map latestVersionMap = new HashMap<>(); for (ProcessDefinition pd : processDefinitions) { if (pd.isSuspended()) continue; ProcessDefinition existing = latestVersionMap.get(pd.getKey()); if (existing == null || pd.getVersion() > existing.getVersion()) { latestVersionMap.put(pd.getKey(), pd); } } List> result = new ArrayList<>(); for (ProcessDefinition pd : latestVersionMap.values()) { Map item = new HashMap<>(); item.put("id", pd.getId()); item.put("key", pd.getKey()); item.put("name", pd.getName()); item.put("version", pd.getVersion()); result.add(item); } return result; } @Override public void updateResignationApplicationAuditStatus(Long id, Integer status) { HrmResignationApplicationDO application = validateResignationApplicationExists(id); if (!Objects.equals(application.getStatus(), HrmAuditStatusEnum.PROCESS.getStatus())) { log.error("[updateResignationApplicationAuditStatus][application({}) 不处于审批中,无法更新审批结果({})]", id, status); throw exception(RESIGNATION_APPLICATION_UPDATE_AUDIT_STATUS_FAIL_NOT_PROCESS); } resignationApplicationMapper.updateById(HrmResignationApplicationDO.builder() .id(id) .status(status) .approveTime(java.time.LocalDateTime.now()) .build()); // 审批通过:员工状态改成「离职」,同步到员工管理 if (HrmAuditStatusEnum.APPROVE.getStatus().equals(status)) { syncEmployeeResigned(application); } } /** * 取离职审批分类下最新版本的活跃流程定义 Key */ private String resolveActiveProcessDefinitionKey() { List definitionInfoList = bpmProcessDefinitionService .getProcessDefinitionInfoListByCategory(APPROVE_CATEGORY_CODE); if (CollUtil.isEmpty(definitionInfoList)) { throw exception(RESIGNATION_APPLICATION_BPM_PROCESS_DEFINITION_NOT_EXISTS); } Set processDefinitionIds = convertSet(definitionInfoList, BpmProcessDefinitionInfoDO::getProcessDefinitionId); List processDefinitions = bpmProcessDefinitionService.getProcessDefinitionList(processDefinitionIds); return processDefinitions.stream() .filter(pd -> !pd.isSuspended()) .max(Comparator.comparingInt(ProcessDefinition::getVersion)) .map(ProcessDefinition::getKey) .orElseThrow(() -> exception(RESIGNATION_APPLICATION_BPM_PROCESS_DEFINITION_NOT_EXISTS)); } /** * 离职审批通过后,把员工档案的状态改成「离职」,同步到员工管理 * *

走 updateEmployee 而不是直接改表,这样 system_users 侧也会一起同步。 */ private void syncEmployeeResigned(HrmResignationApplicationDO application) { try { HrmEmployeeDO employee = employeeService.getEmployeeByUserId(application.getUserId()); if (employee == null) { employee = employeeService.getEmployee(application.getUserId()); } if (employee == null) { log.warn("[syncEmployeeResigned][离职申请({}) 找不到员工档案,跳过状态同步]", application.getId()); return; } HrmEmployeeSaveReqVO updateReqVO = BeanUtils.toBean(employee, HrmEmployeeSaveReqVO.class); updateReqVO.setEmployeeStatus(HrmEmployeeStatusEnum.LEAVE.getStatus()); employeeService.updateEmployee(updateReqVO); log.info("[syncEmployeeResigned][离职申请({}) 已将员工({}) 状态改为离职]", application.getId(), employee.getName()); } catch (Exception ex) { // 同步失败不应该阻断审批状态落库,只记录日志 log.error("[syncEmployeeResigned][离职申请({}) 同步员工状态失败]", application.getId(), ex); } } @Override public HrmResignationApplicationDO getResignationApplicationByProcessInstanceId(String processInstanceId) { return resignationApplicationMapper.selectByProcessInstanceId(processInstanceId); } @Override @Transactional(rollbackFor = Exception.class) public void updateHandoverStatus(HrmResignationHandoverReqVO reqVO) { HrmResignationApplicationDO application = validateResignationApplicationExists(reqVO.getId()); resignationApplicationMapper.updateById(HrmResignationApplicationDO.builder() .id(reqVO.getId()) .handoverStatus(reqVO.getHandoverStatus()) .build()); // 交接完成时,创建用户数据交接映射 if (Objects.equals(reqVO.getHandoverStatus(), HANDOVER_STATUS_COMPLETED) && application.getHandoverUserId() != null) { handoverService.createHandover( application.getUserId(), application.getHandoverUserId(), application.getId()); } } }