一、使用BpmnModel
/**
* @param processInstanceBusinessKey BUSINESS_KEY_
* @param userName 當前用戶
**/
public void rollBackToAssignWoekFlow(String processInstanceBusinessKey, String userName){
ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(processInstanceBusinessKey).singleResult();
if(processInstance == null) {
throw new CustomException("撤回失敗,失敗原因:未查到流程信息!");
}
String processInstanceId = processInstance.getProcessInstanceId();
//獲取流程模型
BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
if (null == bpmnModel) {
throw new CustomException("撤回失敗,失敗原因:未查到流程信息!");
}
Process process = bpmnModel.getProcesses().get(0);
// 當前待辦的任務(激活的任務)
org.activiti.engine.task.Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).active().singleResult();
// 獲取當前節點
FlowNode currentFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(task.getTaskDefinitionKey());
// List<SequenceFlow> outgoingFlows1 = currentFlowNode.getOutgoingFlows();
// 退回的目標節點(當前用戶已辦理的最新節點)
List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId)
.taskAssignee(userName).orderByHistoricTaskInstanceEndTime().desc().list();
HistoricTaskInstance historicTaskInstance = list.get(0);
FlowNode targetFlowNode = (FlowNode) process.getFlowElement(historicTaskInstance.getTaskDefinitionKey());
// 動態創建從當前任務節點到目標節點的連線
SequenceFlow sequenceFlow4 = genarateSequenceFlow("test001","test-name",currentFlowNode,targetFlowNode,null,process);
// currentFlowNode.getOutgoingFlows().clear();
List<SequenceFlow> oldOutgoingFlows = currentFlowNode.getOutgoingFlows();
// 將當前節點的向外連線設置成創建的連線
currentFlowNode.setOutgoingFlows(List.of(sequenceFlow4));
task.setAssignee(userName);
taskService.complete(task.getId()); // 完成任務
currentFlowNode.setOutgoingFlows(oldOutgoingFlows); // 完成任務后將原來的連線設置回當前任務節點
}
二、使用流程圖設計撤回
在設計bpmn流程圖時添加一個排他網關,使用表達式控制流程撤回(想到於退回功能)。