package com.oda.apps.iplm.service.impl;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Slf4j
@Service
public class TaskTransferService {
@Autowired
private TaskService taskService;
/**
* 直接转办给新人(适用于已签收/认领的任务)
*/
@Transactional(rollbackFor = Exception.class)
public void reassign(String taskId, String newAssignee) {
Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
if (task == null) throw new RuntimeException("任务不存在:" + taskId);
taskService.setAssignee(taskId, newAssignee);
taskService.addComment(taskId, task.getProcessInstanceId(),
"转办:" + task.getAssignee() + " → " + newAssignee);
log.info("转办 {}/{} : {} → {}", taskId, task.getName(), task.getAssignee(), newAssignee);
}
/**
* 替换候选人池:移除旧人,加入新人
* 适用场景:任务没人认领,离职的人从候选人池移除,新人加进去
*/
@Transactional(rollbackFor = Exception.class)
public void replaceCandidate(String taskId, String oldUser, String newUser) {
Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
if (task == null) throw new RuntimeException("任务不存在:" + taskId);
// 如果旧人已经签收了,一并转交
if (StrUtil.isNotBlank(task.getAssignee()) && task.getAssignee().equals(oldUser)) {
taskService.setAssignee(taskId, newUser);
}
taskService.deleteCandidateUser(taskId, oldUser);
taskService.addCandidateUser(taskId, newUser);
taskService.addComment(taskId, task.getProcessInstanceId(),
"候选人变更:" + oldUser + " → " + newUser);
log.info("候选人变更 {}/{} : {} → {}", taskId, task.getName(), oldUser, newUser);
}
/**
* 通过流程实例ID转办
*/
@Transactional(rollbackFor = Exception.class)
public void transferByProcessInstance(String processInstanceId, String oldUser, String newUser) {
List<Task> tasks = taskService.createTaskQuery()
.processInstanceId(processInstanceId)
.active()
.list();
for (Task task : tasks) {
if (StrUtil.isNotBlank(task.getAssignee()) && task.getAssignee().equals(oldUser)) {
taskService.setAssignee(task.getId(), newUser);
}
taskService.deleteCandidateUser(task.getId(), oldUser);
taskService.addCandidateUser(task.getId(), newUser);
}
log.info("流程 {} 转办:{} → {}", processInstanceId, oldUser, newUser);
}
}
@Autowired
private TaskTransferService taskTransferService;
// 场景一:任务已被离职的人签收,直接转给新人
taskTransferService.reassign(taskId, "新人LoginName");
// 场景二:任务还在候选人池,替换候选人
taskTransferService.replaceCandidate(taskId, "离职人LoginName", "新人LoginName");
// 场景三:只有流程实例ID,不知道taskId
taskTransferService.transferByProcessInstance(processInstanceId, "离职人LoginName", "新人LoginName");