feat: wire my started workflow tasks

This commit is contained in:
2026-06-18 08:11:36 +08:00
parent f736d33a20
commit 61f31527bc
17 changed files with 806 additions and 15 deletions

View File

@@ -3,9 +3,11 @@ package com.eip4.flowservice.api;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.flowable.engine.HistoryService;
import org.flowable.engine.IdentityService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
@@ -37,11 +39,15 @@ public class FlowController {
/** 默认审批流程 key:命名流程定义未部署时回退到此,保「提交审批」闭环可走(dev 无客户 BPMN 时)。 */
private static final String DEFAULT_APPROVAL_KEY = "EIP4_DEFAULT_APPROVAL";
private static final int STATUS_PROCESSING = 2;
private static final Set<String> WITHDRAW_COMMENT_WHITELIST =
Set.of("回退", "主动召回", "更换任务处理人员");
private final TaskService taskService;
private final RuntimeService runtimeService;
private final HistoryService historyService;
private final RepositoryService repositoryService;
private final IdentityService identityService;
private final JdbcTemplate bizJdbc;
private final com.eip4.flowservice.wf.FormKeyResolver formKeyResolver;
private final com.eip4.flowservice.wf.StartFormKeyResolver startFormKeyResolver;
@@ -49,22 +55,23 @@ public class FlowController {
@org.springframework.beans.factory.annotation.Autowired
public FlowController(TaskService taskService, RuntimeService runtimeService,
HistoryService historyService, RepositoryService repositoryService,
JdbcTemplate bizJdbc, com.eip4.flowservice.wf.FormKeyResolver formKeyResolver,
IdentityService identityService, JdbcTemplate bizJdbc, com.eip4.flowservice.wf.FormKeyResolver formKeyResolver,
com.eip4.flowservice.wf.StartFormKeyResolver startFormKeyResolver) {
this.taskService = taskService;
this.runtimeService = runtimeService;
this.historyService = historyService;
this.repositoryService = repositoryService;
this.identityService = identityService;
this.bizJdbc = bizJdbc;
this.formKeyResolver = formKeyResolver;
this.startFormKeyResolver = startFormKeyResolver;
}
/** 兼容老单测的五参构造(无解析器:就地构造)。生产由 Spring 走七参构造。 */
/** 兼容老单测的五参构造(无解析器:就地构造)。生产由 Spring 走八参构造。 */
public FlowController(TaskService taskService, RuntimeService runtimeService,
HistoryService historyService, RepositoryService repositoryService,
JdbcTemplate bizJdbc) {
this(taskService, runtimeService, historyService, repositoryService, bizJdbc,
this(taskService, runtimeService, historyService, repositoryService, null, bizJdbc,
new com.eip4.flowservice.wf.FormKeyResolver(historyService),
new com.eip4.flowservice.wf.StartFormKeyResolver(repositoryService));
}
@@ -207,11 +214,44 @@ public class FlowController {
}
}
@GetMapping("/process/started")
@Operation(summary = "我发起的流程实例",
description = "按 startedBy 查询历史流程实例,返回流程实例、业务主键、起止时间与当前活动任务。"
+ "供转换页「我的发起任务」聚合成 VIEW_ACT_PROCESS_* 旧字段。")
public List<ProcessInstanceDto> started(
@RequestParam(required = false) String startedBy,
@RequestParam(defaultValue = "0") int firstResult,
@RequestParam(defaultValue = "50") int maxResults) {
var q = historyService.createHistoricProcessInstanceQuery();
if (startedBy != null && !startedBy.isBlank()) {
q = q.startedBy(startedBy.trim());
}
return q.orderByProcessInstanceStartTime().desc()
.listPage(firstResult, maxResults)
.stream()
.map(hpi -> {
ProcessInstance runtime = runtimeService.createProcessInstanceQuery()
.processInstanceId(hpi.getId()).singleResult();
List<org.flowable.task.api.Task> activeTasks = taskService.createTaskQuery()
.processInstanceId(hpi.getId()).active().list();
return ProcessInstanceDto.of(hpi, runtime, activeTasks);
})
.collect(Collectors.toList());
}
@PostMapping("/process/start")
@Operation(summary = "发起流程", description = "按 processDefinitionKey 或 processDefinitionId 发起,可带 businessKey 与变量")
public ResponseEntity<ProcessInstanceDto> start(@RequestBody Requests.StartRequest req) {
if (req == null) {
return ResponseEntity.badRequest().build();
}
ProcessInstance pi;
String startUserId = trimToNull(req.startUserId);
boolean bindStartUser = identityService != null && startUserId != null;
try {
if (bindStartUser) {
identityService.setAuthenticatedUserId(startUserId);
}
if (req.processDefinitionId != null && !req.processDefinitionId.isBlank()) {
pi = runtimeService.startProcessInstanceById(req.processDefinitionId, req.businessKey, req.variables);
} else if (req.processDefinitionKey != null && !req.processDefinitionKey.isBlank()) {
@@ -237,6 +277,10 @@ public class FlowController {
"[起流失败] key={} id={} bizKey={} 变量类型[{}]: {}",
req.processDefinitionKey, req.processDefinitionId, req.businessKey, varTypes, e.toString(), e);
throw e;
} finally {
if (bindStartUser) {
identityService.setAuthenticatedUserId(null);
}
}
return ResponseEntity.ok(ProcessInstanceDto.of(pi));
}
@@ -452,6 +496,90 @@ public class FlowController {
return ResponseEntity.ok(r);
}
@PostMapping("/process/{processInstanceId}/withdraw")
@Operation(summary = "发起人撤回",
description = "对齐老 MySendTaskComponent + activebackProcess:按流程实例找当前活动任务,"
+ "若已有非白名单审批意见则拒绝;否则移动回发起/起始节点、记「主动召回」评论并挂起流程实例。")
public ResponseEntity<Map<String, Object>> withdraw(@PathVariable String processInstanceId,
@RequestBody(required = false) Requests.ActionRequest req) {
String pid = processInstanceId == null ? "" : processInstanceId.trim();
if (pid.isBlank()) {
return ResponseEntity.badRequest().body(errorBody("processInstanceId 不能为空"));
}
List<org.flowable.task.api.Task> activeTasks = taskService.createTaskQuery()
.processInstanceId(pid).active().orderByTaskCreateTime().asc().list();
if (activeTasks == null || activeTasks.isEmpty()) {
return ResponseEntity.status(org.springframework.http.HttpStatus.CONFLICT)
.body(errorBody("该任务无法撤回,请检查!"));
}
ProcessInstance pi = runtimeService.createProcessInstanceQuery()
.processInstanceId(pid).singleResult();
var hpi = historyService.createHistoricProcessInstanceQuery()
.processInstanceId(pid).singleResult();
String businessKey = firstNonBlank(pi == null ? null : pi.getBusinessKey(),
hpi == null ? null : hpi.getBusinessKey());
Integer status = businessStatus(businessKey);
if (status != null && status != STATUS_PROCESSING) {
return ResponseEntity.status(org.springframework.http.HttpStatus.CONFLICT)
.body(errorBody("该任务无法撤回,请检查!"));
}
if (hasDisallowedFlowComment(pid)) {
return ResponseEntity.status(org.springframework.http.HttpStatus.CONFLICT)
.body(errorBody("该任务已流转,无法撤回!"));
}
String targetKey = trimToNull(hpi == null ? null : hpi.getStartActivityId());
if (targetKey == null) {
targetKey = firstHistoricTaskKey(pid);
}
if (targetKey == null) {
return ResponseEntity.status(org.springframework.http.HttpStatus.CONFLICT)
.body(errorBody("该任务无法撤回,请检查!"));
}
String comment = firstNonBlank(req == null ? null : req.comment, "主动召回");
taskService.addComment(activeTasks.get(0).getId(), pid, comment);
try {
runtimeService.setVariable(pid, "approveResult", "withdraw");
} catch (RuntimeException ignore) {
/* 变量写入失败不阻断撤回 */
}
List<String> currentKeys = activeTasks.stream()
.map(org.flowable.task.api.Task::getTaskDefinitionKey)
.filter(s -> s != null && !s.isBlank())
.distinct()
.toList();
try {
if (!currentKeys.isEmpty()
&& !(currentKeys.size() == 1 && targetKey.equals(currentKeys.get(0)))) {
runtimeService.createChangeActivityStateBuilder()
.processInstanceId(pid)
.moveActivityIdsToSingleActivityId(currentKeys, targetKey)
.changeState();
}
if (pi == null || !pi.isSuspended()) {
runtimeService.suspendProcessInstanceById(pid);
}
} catch (RuntimeException e) {
org.slf4j.LoggerFactory.getLogger(FlowController.class)
.error("[撤回失败] pid={} active={} → {}: {}", pid, currentKeys, targetKey, e.toString());
Map<String, Object> err = errorBody("该任务无法撤回,请检查!");
err.put("detail", e.getMessage());
return ResponseEntity.status(org.springframework.http.HttpStatus.CONFLICT).body(err);
}
Map<String, Object> r = new java.util.LinkedHashMap<>();
r.put("withdrawn", true);
r.put("targetKey", targetKey);
r.put("businessKey", businessKey);
r.put("processInstanceId", pid);
return ResponseEntity.ok(r);
}
@GetMapping("/process/{processInstanceId}/trace")
@Operation(summary = "流程轨迹", description = "返回该流程实例所有历史任务节点(含当前活动节点),按开始时间升序。每节点包含办理人姓名(经 sys_user 反查)、审批意见(Flowable 评论)、办理结果变量。")
public ResponseEntity<List<TraceNodeDto>> trace(@PathVariable String processInstanceId) {
@@ -557,6 +685,68 @@ public class FlowController {
}
}
private boolean hasDisallowedFlowComment(String processInstanceId) {
try {
List<org.flowable.engine.task.Comment> comments =
taskService.getProcessInstanceComments(processInstanceId, "comment");
if (comments == null) {
return false;
}
for (org.flowable.engine.task.Comment c : comments) {
String msg = trimToNull(c.getFullMessage());
if (msg != null && !WITHDRAW_COMMENT_WHITELIST.contains(msg)) {
return true;
}
}
} catch (RuntimeException ignored) {
return false;
}
return false;
}
private String firstHistoricTaskKey(String processInstanceId) {
List<HistoricTaskInstance> first = historyService.createHistoricTaskInstanceQuery()
.processInstanceId(processInstanceId).orderByHistoricTaskInstanceStartTime().asc().listPage(0, 1);
return first == null || first.isEmpty() ? null : trimToNull(first.get(0).getTaskDefinitionKey());
}
private Integer businessStatus(String businessKey) {
String bk = trimToNull(businessKey);
if (bk == null) {
return null;
}
try {
return bizJdbc.query(
"SELECT DATASTATUS FROM SYS_DATASTATUS WHERE BUSINESSKEY = ?",
rs -> rs.next() ? rs.getInt(1) : null,
bk);
} catch (RuntimeException ignored) {
return null;
}
}
private static String firstNonBlank(String... values) {
for (String value : values) {
String s = trimToNull(value);
if (s != null) {
return s;
}
}
return null;
}
private static String trimToNull(String value) {
String s = value == null ? null : value.trim();
return s == null || s.isBlank() ? null : s;
}
private static Map<String, Object> errorBody(String msg) {
Map<String, Object> err = new java.util.LinkedHashMap<>();
err.put("status", 1);
err.put("msg", msg);
return err;
}
@GetMapping("/process-definitions/count")
@Operation(summary = "流程定义计数", description = "启动后定义加载自检(预期 1,509)")
public long processDefinitionCount() {

View File

@@ -1,6 +1,10 @@
package com.eip4.flowservice.api;
import java.util.List;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
/**
* 流程实例 DTO(发起流程出参)。
@@ -9,7 +13,13 @@ public class ProcessInstanceDto {
public String id;
public String processDefinitionId;
public String processDefinitionKey;
public String processDefinitionName;
public String businessKey;
public String startUserId;
public Long startTimeMillis;
public Long endTimeMillis;
public List<String> activeTaskNames = List.of();
public List<String> activeTaskAssignees = List.of();
public boolean ended;
public boolean suspended;
@@ -18,9 +28,40 @@ public class ProcessInstanceDto {
d.id = pi.getId();
d.processDefinitionId = pi.getProcessDefinitionId();
d.processDefinitionKey = pi.getProcessDefinitionKey();
d.processDefinitionName = pi.getProcessDefinitionName();
d.businessKey = pi.getBusinessKey();
d.startUserId = pi.getStartUserId();
d.startTimeMillis = pi.getStartTime() != null ? pi.getStartTime().getTime() : null;
d.ended = pi.isEnded();
d.suspended = pi.isSuspended();
return d;
}
public static ProcessInstanceDto of(HistoricProcessInstance hpi, ProcessInstance runtime,
List<Task> activeTasks) {
ProcessInstanceDto d = new ProcessInstanceDto();
d.id = hpi.getId();
d.processDefinitionId = hpi.getProcessDefinitionId();
d.processDefinitionKey = hpi.getProcessDefinitionKey();
d.processDefinitionName = hpi.getProcessDefinitionName();
d.businessKey = hpi.getBusinessKey();
d.startUserId = hpi.getStartUserId();
d.startTimeMillis = hpi.getStartTime() != null ? hpi.getStartTime().getTime() : null;
d.endTimeMillis = hpi.getEndTime() != null ? hpi.getEndTime().getTime() : null;
d.ended = hpi.getEndTime() != null;
d.suspended = runtime != null && runtime.isSuspended();
if (activeTasks != null && !activeTasks.isEmpty()) {
d.activeTaskNames = activeTasks.stream()
.map(Task::getName)
.filter(s -> s != null && !s.isBlank())
.distinct()
.toList();
d.activeTaskAssignees = activeTasks.stream()
.map(Task::getAssignee)
.filter(s -> s != null && !s.isBlank())
.distinct()
.toList();
}
return d;
}
}

View File

@@ -15,6 +15,8 @@ public final class Requests {
public String processDefinitionKey;
public String processDefinitionId;
public String businessKey;
/** 当前发起人 userId;用于 Flowable 历史实例 startedBy,支撑“我的发起任务”。 */
public String startUserId;
public Map<String, Object> variables;
}

View File

@@ -6,6 +6,7 @@ import java.util.Map;
import javax.sql.DataSource;
import org.flowable.engine.HistoryService;
import org.flowable.engine.IdentityService;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
@@ -88,4 +89,9 @@ public class FlowableEngineConfig {
public HistoryService historyService(ProcessEngine engine) {
return engine.getHistoryService();
}
@Bean
public IdentityService identityService(ProcessEngine engine) {
return engine.getIdentityService();
}
}

View File

@@ -3,6 +3,7 @@ package com.eip4.flowservice.api;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@@ -11,10 +12,16 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.flowable.engine.HistoryService;
import org.flowable.engine.IdentityService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.history.HistoricProcessInstanceQuery;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.runtime.ProcessInstanceQuery;
import org.flowable.engine.runtime.ChangeActivityStateBuilder;
import org.flowable.engine.task.Comment;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.junit.jupiter.api.BeforeEach;
@@ -41,15 +48,26 @@ class FlowControllerTest {
@Mock
RepositoryService repositoryService;
@Mock
IdentityService identityService;
@Mock
TaskQuery taskQuery;
@Mock
ProcessInstanceQuery processInstanceQuery;
@Mock
HistoricProcessInstanceQuery historicProcessInstanceQuery;
@Mock
ChangeActivityStateBuilder changeActivityStateBuilder;
@Mock
JdbcTemplate bizJdbc;
MockMvc mvc;
@BeforeEach
void setUp() {
FlowController controller = new FlowController(taskService, runtimeService, historyService, repositoryService, bizJdbc);
FlowController controller = new FlowController(taskService, runtimeService, historyService, repositoryService,
identityService, bizJdbc,
new com.eip4.flowservice.wf.FormKeyResolver(historyService),
new com.eip4.flowservice.wf.StartFormKeyResolver(repositoryService));
mvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@@ -70,10 +88,12 @@ class FlowControllerTest {
mvc.perform(post("/api/flow/process/start")
.contentType("application/json")
.content("{\"processDefinitionKey\":\"leaveProcess\",\"businessKey\":\"biz-9\"}"))
.content("{\"processDefinitionKey\":\"leaveProcess\",\"businessKey\":\"biz-9\",\"startUserId\":\"U1\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value("pi-1"))
.andExpect(jsonPath("$.processDefinitionKey").value("leaveProcess"));
verify(identityService).setAuthenticatedUserId("U1");
verify(identityService).setAuthenticatedUserId((String) null);
}
@Test
@@ -99,6 +119,90 @@ class FlowControllerTest {
verify(runtimeService).activateProcessInstanceById("pi-3");
}
@Test
void 撤回流程_移动回起始节点并挂起实例() throws Exception {
Task task = org.mockito.Mockito.mock(Task.class);
when(task.getId()).thenReturn("T1");
when(task.getTaskDefinitionKey()).thenReturn("approve");
when(taskService.createTaskQuery()).thenReturn(taskQuery);
when(taskQuery.processInstanceId("PI-1")).thenReturn(taskQuery);
when(taskQuery.active()).thenReturn(taskQuery);
when(taskQuery.orderByTaskCreateTime()).thenReturn(taskQuery);
when(taskQuery.asc()).thenReturn(taskQuery);
when(taskQuery.list()).thenReturn(java.util.List.of(task));
ProcessInstance pi = org.mockito.Mockito.mock(ProcessInstance.class);
when(pi.getBusinessKey()).thenReturn("BK-1");
when(pi.isSuspended()).thenReturn(false);
when(runtimeService.createProcessInstanceQuery()).thenReturn(processInstanceQuery);
when(processInstanceQuery.processInstanceId("PI-1")).thenReturn(processInstanceQuery);
when(processInstanceQuery.singleResult()).thenReturn(pi);
HistoricProcessInstance hpi = org.mockito.Mockito.mock(HistoricProcessInstance.class);
when(hpi.getBusinessKey()).thenReturn("BK-1");
when(hpi.getStartActivityId()).thenReturn("startEvent");
when(historyService.createHistoricProcessInstanceQuery()).thenReturn(historicProcessInstanceQuery);
when(historicProcessInstanceQuery.processInstanceId("PI-1")).thenReturn(historicProcessInstanceQuery);
when(historicProcessInstanceQuery.singleResult()).thenReturn(hpi);
when(bizJdbc.query(anyString(), any(org.springframework.jdbc.core.ResultSetExtractor.class), eq("BK-1")))
.thenReturn(2);
when(runtimeService.createChangeActivityStateBuilder()).thenReturn(changeActivityStateBuilder);
when(changeActivityStateBuilder.processInstanceId("PI-1")).thenReturn(changeActivityStateBuilder);
when(changeActivityStateBuilder.moveActivityIdsToSingleActivityId(java.util.List.of("approve"), "startEvent"))
.thenReturn(changeActivityStateBuilder);
mvc.perform(post("/api/flow/process/PI-1/withdraw")
.contentType("application/json")
.content("{}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.withdrawn").value(true))
.andExpect(jsonPath("$.businessKey").value("BK-1"))
.andExpect(jsonPath("$.targetKey").value("startEvent"));
verify(taskService).addComment("T1", "PI-1", "主动召回");
verify(changeActivityStateBuilder).changeState();
verify(runtimeService).suspendProcessInstanceById("PI-1");
}
@Test
void 撤回流程_已有非白名单意见则拒绝() throws Exception {
Task task = org.mockito.Mockito.mock(Task.class);
when(taskService.createTaskQuery()).thenReturn(taskQuery);
when(taskQuery.processInstanceId("PI-2")).thenReturn(taskQuery);
when(taskQuery.active()).thenReturn(taskQuery);
when(taskQuery.orderByTaskCreateTime()).thenReturn(taskQuery);
when(taskQuery.asc()).thenReturn(taskQuery);
when(taskQuery.list()).thenReturn(java.util.List.of(task));
ProcessInstance pi = org.mockito.Mockito.mock(ProcessInstance.class);
when(pi.getBusinessKey()).thenReturn("BK-2");
when(runtimeService.createProcessInstanceQuery()).thenReturn(processInstanceQuery);
when(processInstanceQuery.processInstanceId("PI-2")).thenReturn(processInstanceQuery);
when(processInstanceQuery.singleResult()).thenReturn(pi);
HistoricProcessInstance hpi = org.mockito.Mockito.mock(HistoricProcessInstance.class);
when(hpi.getBusinessKey()).thenReturn("BK-2");
when(historyService.createHistoricProcessInstanceQuery()).thenReturn(historicProcessInstanceQuery);
when(historicProcessInstanceQuery.processInstanceId("PI-2")).thenReturn(historicProcessInstanceQuery);
when(historicProcessInstanceQuery.singleResult()).thenReturn(hpi);
when(bizJdbc.query(anyString(), any(org.springframework.jdbc.core.ResultSetExtractor.class), eq("BK-2")))
.thenReturn(2);
Comment comment = org.mockito.Mockito.mock(Comment.class);
when(comment.getFullMessage()).thenReturn("同意");
when(taskService.getProcessInstanceComments("PI-2", "comment"))
.thenReturn(java.util.List.of(comment));
mvc.perform(post("/api/flow/process/PI-2/withdraw")
.contentType("application/json")
.content("{}"))
.andExpect(status().isConflict())
.andExpect(jsonPath("$.msg").value("该任务已流转,无法撤回!"));
verify(runtimeService, never()).createChangeActivityStateBuilder();
verify(taskService, never()).addComment(eq("T1"), eq("PI-2"), anyString());
}
@Test
void 委托缺少受托人返回400() throws Exception {
mvc.perform(post("/api/flow/tasks/task-7/delegate")