F2-7: 审批办理 UI 后端——trace/delegate 端点增补

- flowable-service:新增 GET /api/flow/process/{id}/trace(历史任务节点+
  审批意见+结果,biz 库不可达时用户名 1s 超时降级),TraceNodeDto;
  biz 数据源加 connectionTimeout/socketTimeout 快速失败
- platform-flow-gateway:FlowableClient 增加 trace/delegate 方法;
  TodoController 增加 /api/flow/process/{id}/trace 和 /api/task/{id}/delegate
  网关透传端点;GatewayRequests.DelegateRequest;TraceNodeDto 镜像
- 单测:TraceAndDelegateTest 3 个(MockRestServiceServer),全套 34/34 通过
- application-dev.yml:eip4.flow.read-timeout-ms=60000 适配慢查询

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-06-11 23:09:11 +08:00
parent b0657a7765
commit 6dbb205e94
9 changed files with 279 additions and 2 deletions

View File

@@ -1,6 +1,8 @@
package com.eip4.flowservice.api; package com.eip4.flowservice.api;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.flowable.engine.HistoryService; import org.flowable.engine.HistoryService;
@@ -8,7 +10,9 @@ import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService; import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService; import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance; import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
@@ -35,13 +39,16 @@ public class FlowController {
private final RuntimeService runtimeService; private final RuntimeService runtimeService;
private final HistoryService historyService; private final HistoryService historyService;
private final RepositoryService repositoryService; private final RepositoryService repositoryService;
private final JdbcTemplate bizJdbc;
public FlowController(TaskService taskService, RuntimeService runtimeService, public FlowController(TaskService taskService, RuntimeService runtimeService,
HistoryService historyService, RepositoryService repositoryService) { HistoryService historyService, RepositoryService repositoryService,
JdbcTemplate bizJdbc) {
this.taskService = taskService; this.taskService = taskService;
this.runtimeService = runtimeService; this.runtimeService = runtimeService;
this.historyService = historyService; this.historyService = historyService;
this.repositoryService = repositoryService; this.repositoryService = repositoryService;
this.bizJdbc = bizJdbc;
} }
@GetMapping("/tasks/todo") @GetMapping("/tasks/todo")
@@ -218,6 +225,92 @@ public class FlowController {
return ResponseEntity.ok(t != null ? TaskDto.of(t) : null); return ResponseEntity.ok(t != null ? TaskDto.of(t) : null);
} }
@GetMapping("/process/{processInstanceId}/trace")
@Operation(summary = "流程轨迹", description = "返回该流程实例所有历史任务节点(含当前活动节点),按开始时间升序。每节点包含办理人姓名(经 sys_user 反查)、审批意见(Flowable 评论)、办理结果变量。")
public ResponseEntity<List<TraceNodeDto>> trace(@PathVariable String processInstanceId) {
// 1. 历史任务列表(Flowable 引擎库,不涉及 biz 库)
List<HistoricTaskInstance> histTasks = historyService.createHistoricTaskInstanceQuery()
.processInstanceId(processInstanceId)
.orderByHistoricTaskInstanceStartTime().asc()
.list();
// 2. 当前活动任务 id 集合
java.util.Set<String> activeTasks = taskService.createTaskQuery()
.processInstanceId(processInstanceId)
.list()
.stream().map(t -> t.getId())
.collect(java.util.stream.Collectors.toSet());
// 3. 流程级 approveResult 变量(查一次,避免 N+1)
String processResult = null;
try {
org.flowable.variable.api.history.HistoricVariableInstance var =
historyService.createHistoricVariableInstanceQuery()
.processInstanceId(processInstanceId)
.variableName("approveResult")
.singleResult();
if (var != null && var.getValue() != null) {
processResult = String.valueOf(var.getValue());
}
} catch (Exception ignored) { /* 变量不存在时静默降级 */ }
// 4. 流程级所有审批意见(按任务 id 聚合,避免 N+1)
java.util.Map<String, String> commentMap = new java.util.HashMap<>();
try {
List<org.flowable.engine.task.Comment> allComments =
taskService.getProcessInstanceComments(processInstanceId, "comment");
if (allComments != null) {
for (org.flowable.engine.task.Comment c : allComments) {
commentMap.putIfAbsent(c.getTaskId(), c.getFullMessage());
}
}
} catch (Exception ignored) { /* comment 查询失败不影响主流程 */ }
// 5. 组装节点(用户名查 biz 库,超时降级为 userId)
List<TraceNodeDto> nodes = new ArrayList<>();
for (HistoricTaskInstance ht : histTasks) {
TraceNodeDto node = new TraceNodeDto();
node.taskId = ht.getId();
node.taskName = ht.getName();
node.assignee = ht.getAssignee();
node.assigneeName = lookupUserName(ht.getAssignee());
node.startTime = ht.getStartTime() != null ? ht.getStartTime().getTime() : null;
node.endTime = ht.getEndTime() != null ? ht.getEndTime().getTime() : null;
node.current = activeTasks.contains(ht.getId());
node.comment = commentMap.get(ht.getId());
node.result = processResult;
nodes.add(node);
}
return ResponseEntity.ok(nodes);
}
/**
* 经 sys_user 表反查用户姓名;biz 库连不上时 1s 超时降级返回 userId。
* 用独立线程 + Future.get(timeout) 保证不阻塞主流程(biz 库离线时快速失败)。
*/
private String lookupUserName(String userId) {
if (userId == null || userId.isBlank()) {
return userId;
}
java.util.concurrent.Future<String> future =
java.util.concurrent.Executors.newSingleThreadExecutor().submit(() -> {
try {
List<String> names = bizJdbc.query(
"SELECT name FROM sys_user WHERE sys_user_id = ?",
(rs, n) -> rs.getString("name"), userId);
return names.isEmpty() || names.get(0) == null ? userId : names.get(0).trim();
} catch (Exception e) {
return userId;
}
});
try {
return future.get(1, java.util.concurrent.TimeUnit.SECONDS);
} catch (Exception e) {
future.cancel(true);
return userId; // biz 库不可达(dev 192.168.20.68:5435 离线)→ 降级
}
}
@GetMapping("/process-definitions/count") @GetMapping("/process-definitions/count")
@Operation(summary = "流程定义计数", description = "启动后定义加载自检(预期 1,509)") @Operation(summary = "流程定义计数", description = "启动后定义加载自检(预期 1,509)")
public long processDefinitionCount() { public long processDefinitionCount() {

View File

@@ -0,0 +1,30 @@
package com.eip4.flowservice.api;
/**
* 流程轨迹节点 DTO —— 每条历史任务对应一个节点。
*
* <p>供 {@code GET /api/flow/process/{processInstanceId}/trace} 出参聚合使用。
* 字段语义:
* <ul>
* <li>{@code taskId} Flowable 历史任务 id</li>
* <li>{@code taskName} 节点名称(如「接收交底(项目部)」)</li>
* <li>{@code assignee} 办理人 userId(历史任务 assignee)</li>
* <li>{@code assigneeName}办理人姓名(经 sys_user 表反查,查不到回退 userId)</li>
* <li>{@code comment} 审批意见(Flowable 任务评论,若无则为 null)</li>
* <li>{@code result} 办理结果(变量 approveResult 或 comment type,如 agree/reject)</li>
* <li>{@code startTime} 节点开始时间(毫秒 epoch)</li>
* <li>{@code endTime} 节点结束时间(毫秒 epoch);null 表示当前活动节点</li>
* <li>{@code current} 是否为当前活动节点(未结束)</li>
* </ul>
*/
public class TraceNodeDto {
public String taskId;
public String taskName;
public String assignee;
public String assigneeName;
public String comment;
public String result;
public Long startTime;
public Long endTime;
public boolean current;
}

View File

@@ -26,12 +26,15 @@ flowable:
biz: biz:
datasource: datasource:
# 本地验证:客户库副本 192.168.20.68:5435,schema eip3,ceshi 只读 # 本地验证:客户库副本 192.168.20.68:5435,schema eip3,ceshi 只读
jdbc-url: ${BIZ_JDBC_URL:jdbc:postgresql://192.168.20.68:5435/postgres?currentSchema=eip3} jdbc-url: ${BIZ_JDBC_URL:jdbc:postgresql://192.168.20.68:5435/postgres?currentSchema=eip3&connectTimeout=2&socketTimeout=3}
username: ${BIZ_JDBC_USER:ceshi} username: ${BIZ_JDBC_USER:ceshi}
password: ${BIZ_JDBC_PASS:ceshi} password: ${BIZ_JDBC_PASS:ceshi}
driver-class-name: org.postgresql.Driver driver-class-name: org.postgresql.Driver
# 业务库只读纪律:Hikari 只读连接 # 业务库只读纪律:Hikari 只读连接
read-only: true read-only: true
# F2-7:biz 库离线时 lookupUserName 快速失败(不等 socket 超时),连接超时 3s
connection-timeout: 3000
initialization-fail-timeout: -1
# ===== 生产单库分 schema 形态(架构第三节,配置示意)===== # ===== 生产单库分 schema 形态(架构第三节,配置示意)=====
# 生产为同一 PG 库、不同 schema:ACT_ 表在 flowable schema、业务表在 business schema。 # 生产为同一 PG 库、不同 schema:ACT_ 表在 flowable schema、业务表在 business schema。

View File

@@ -37,6 +37,12 @@ eip4:
# F1-4b:改写后脚本根目录(工作目录为 platform-app/,tools/ 在上层) # F1-4b:改写后脚本根目录(工作目录为 platform-app/,tools/ 在上层)
rewritten-root: ../tools/s3_rewriter/output/rewritten rewritten-root: ../tools/s3_rewriter/output/rewritten
flow:
# F2-7:flowable-service 部分查询慢(历史任务+候选人解析),放大超时
read-timeout-ms: 60000
connect-timeout-ms: 3000
max-retries: 0
logging: logging:
level: level:
com.dsasp: DEBUG com.dsasp: DEBUG

View File

@@ -104,6 +104,26 @@ public class FlowableClient {
return post("发起", "/api/flow/process/start", startRequest, ProcessInstanceDto.class); return post("发起", "/api/flow/process/start", startRequest, ProcessInstanceDto.class);
} }
/**
* 查流程轨迹(历史任务节点列表,含办理人姓名/意见/结果)。
* 对应 flowable-service {@code GET /api/flow/process/{processInstanceId}/trace}。
*/
public List<TraceNodeDto> trace(String processInstanceId) {
return execute("轨迹", () -> restClient.get()
.uri("/api/flow/process/{id}/trace", processInstanceId)
.retrieve()
.body(new ParameterizedTypeReference<List<TraceNodeDto>>() {}));
}
/**
* 委托(delegate)任务给指定用户。
* 对应 flowable-service {@code POST /api/flow/tasks/{taskId}/delegate}。
*/
public void delegate(String taskId, String delegateUserId) {
post("委托", "/api/flow/tasks/" + taskId + "/delegate",
Map.of("delegateUserId", delegateUserId), Void.class);
}
/** /**
* 查流程实例(供办理后判定是否结束以回写业务状态)。 * 查流程实例(供办理后判定是否结束以回写业务状态)。
* 实例不存在(404)返回 null;运行中 {@code ended=false},已结束 {@code ended=true}。 * 实例不存在(404)返回 null;运行中 {@code ended=false},已结束 {@code ended=true}。

View File

@@ -0,0 +1,16 @@
package com.eip4.platform.flowgateway.client;
/**
* 流程轨迹节点 DTO(镜像 flowable-service TraceNodeDto 出参,经网关透传给前端)。
*/
public class TraceNodeDto {
public String taskId;
public String taskName;
public String assignee;
public String assigneeName;
public String comment;
public String result;
public Long startTime;
public Long endTime;
public boolean current;
}

View File

@@ -30,4 +30,9 @@ public final class GatewayRequests {
public String businessKey; public String businessKey;
public Map<String, Object> variables; public Map<String, Object> variables;
} }
/** 委托(delegate)请求。 */
public static class DelegateRequest {
public String delegateUserId;
}
} }

View File

@@ -18,6 +18,7 @@ import com.eip4.platform.flowgateway.aggregate.TodoAggregator;
import com.eip4.platform.flowgateway.aggregate.TodoItem; import com.eip4.platform.flowgateway.aggregate.TodoItem;
import com.eip4.platform.flowgateway.client.FlowableClient; import com.eip4.platform.flowgateway.client.FlowableClient;
import com.eip4.platform.flowgateway.client.ProcessInstanceDto; import com.eip4.platform.flowgateway.client.ProcessInstanceDto;
import com.eip4.platform.flowgateway.client.TraceNodeDto;
import com.eip4.platform.flowgateway.writeback.StatusWriteback; import com.eip4.platform.flowgateway.writeback.StatusWriteback;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
@@ -107,6 +108,27 @@ public class TodoController {
return ResponseEntity.ok(flowableClient.start(body)); return ResponseEntity.ok(flowableClient.start(body));
} }
@Operation(summary = "流程轨迹", description = "返回流程实例的历史任务节点(含当前活动节点),按开始时间升序;包含办理人姓名/审批意见/办理结果")
@GetMapping("/api/flow/process/{processInstanceId}/trace")
public ResponseEntity<List<TraceNodeDto>> trace(@PathVariable String processInstanceId) {
List<TraceNodeDto> nodes = flowableClient.trace(processInstanceId);
return ResponseEntity.ok(nodes);
}
@Operation(summary = "委托任务", description = "将任务委托给指定用户(delegateUserId),assignee 变受托人,owner 记原办理人")
@PostMapping("/api/task/{id}/delegate")
public ResponseEntity<Map<String, Object>> delegate(@PathVariable String id,
@RequestBody GatewayRequests.DelegateRequest req) {
if (req == null || req.delegateUserId == null || req.delegateUserId.isBlank()) {
return ResponseEntity.badRequest().build();
}
flowableClient.delegate(id, req.delegateUserId);
Map<String, Object> resp = new HashMap<>();
resp.put("delegated", true);
resp.put("delegateUserId", req.delegateUserId);
return ResponseEntity.ok(resp);
}
/** 实例不存在(已被清理)按"已结束"处理(complete 后无运行实例即流程终结)。 */ /** 实例不存在(已被清理)按"已结束"处理(complete 后无运行实例即流程终结)。 */
private boolean isProcessEnded(String processInstanceId) { private boolean isProcessEnded(String processInstanceId) {
ProcessInstanceDto pi = flowableClient.processInstance(processInstanceId); ProcessInstanceDto pi = flowableClient.processInstance(processInstanceId);

View File

@@ -0,0 +1,82 @@
package com.eip4.platform.flowgateway;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;
import com.eip4.platform.flowgateway.client.FlowGatewayProperties;
import com.eip4.platform.flowgateway.client.FlowableClient;
import com.eip4.platform.flowgateway.client.TraceNodeDto;
/**
* 流程轨迹 + 委托端点网关层单测(MockRestServiceServer 验证 URL 和出参解析)。
*/
class TraceAndDelegateTest {
private FlowGatewayProperties props() {
FlowGatewayProperties p = new FlowGatewayProperties();
p.setBaseUrl("http://localhost:8089");
p.setMaxRetries(0);
p.setRetryBackoffMs(1);
return p;
}
@Test
void trace_正常返回_节点列表解析() {
FlowGatewayProperties p = props();
RestClient.Builder builder = RestClient.builder().baseUrl(p.getBaseUrl());
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
String body = "[{\"taskId\":\"T1\",\"taskName\":\"接收交底(项目部)\",\"assignee\":\"U1\","
+ "\"assigneeName\":\"张三\",\"comment\":\"同意\",\"result\":\"agree\","
+ "\"startTime\":1700000000000,\"endTime\":1700001000000,\"current\":false}]";
server.expect(requestTo("http://localhost:8089/api/flow/process/P1/trace"))
.andRespond(withSuccess(body, MediaType.APPLICATION_JSON));
FlowableClient client = new FlowableClient(builder.build(), p);
List<TraceNodeDto> nodes = client.trace("P1");
assertThat(nodes).hasSize(1);
assertThat(nodes.get(0).taskId).isEqualTo("T1");
assertThat(nodes.get(0).assigneeName).isEqualTo("张三");
assertThat(nodes.get(0).comment).isEqualTo("同意");
assertThat(nodes.get(0).result).isEqualTo("agree");
assertThat(nodes.get(0).current).isFalse();
server.verify();
}
@Test
void trace_空列表_正常返回() {
FlowGatewayProperties p = props();
RestClient.Builder builder = RestClient.builder().baseUrl(p.getBaseUrl());
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
server.expect(requestTo("http://localhost:8089/api/flow/process/P-EMPTY/trace"))
.andRespond(withSuccess("[]", MediaType.APPLICATION_JSON));
FlowableClient client = new FlowableClient(builder.build(), p);
List<TraceNodeDto> nodes = client.trace("P-EMPTY");
assertThat(nodes).isEmpty();
server.verify();
}
@Test
void delegate_正常_发送delegateUserId() {
FlowGatewayProperties p = props();
RestClient.Builder builder = RestClient.builder().baseUrl(p.getBaseUrl());
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
server.expect(requestTo("http://localhost:8089/api/flow/tasks/T1/delegate"))
.andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));
FlowableClient client = new FlowableClient(builder.build(), p);
// 不抛异常即为通过
client.delegate("T1", "U2");
server.verify();
}
}