feat(approval): 审批闭环 P0/流程图/会签 — 协办转阅+BPMN图+scriptUser会签

承接 WfTemplate 数据驱动审批主链路(approve/reject/reback/agent 已 live),补齐缺口:

P0 协办(assist)/转阅(circulated):
- flowable-service 新增 POST /tasks/{id}/assist、/circulate(对齐老 ProcessCoreServiceImpl
  createSubTask/createNewTask:每人建独立任务,父任务记意见,不阻断主流程)
- gateway FlowableClient.assist/circulate + ApprovalController 把 assist/circulated 从 400 改真实分派
- 前端 ApprovalDrawer 多选人弹窗 MultiUserForm
- 对抗审查修复:独立任务沿 parentTaskId 回溯父任务取 businessKey/formKey(否则协办/转阅人
  看不到业务单据,且 processInstanceId(null) 崩 500);assist 父任务 404 守卫;MAX_FANOUT=50;
  @Transactional;转阅改 setFormKey 而非 description

P1 BPMN 流程图查看:
- flowable-service 新 ProcessDiagramController GET /process/{pi}/diagram
  (bpmnXml + 当前/历史活动节点,运行/历史双路取 procDefId,只读)
- gateway FlowableClient.diagram + TodoController 转发
- 前端 bpmn-js 渲染(中文走浏览器字体,当前节点绿/已走过灰),ApprovalDrawer 按需展开

P3 会签(BPMN 多实例):移植 CandidateUsersHandler 的 scriptUser(JUEL)候选人解析分支
(原"精简边界"WARN 降级,致招投标/总包合同/施工技术交底等用 ${APPLYUSERS} 的会签节点被跳过):
单变量直读流程变量 + 复杂表达式回退 flowable 表达式管理器 + 结果归一为去重 userId 列表

测试:flowable-service 56 + gateway 全模块 全绿;前端 tsc 干净 + vitest 83/83 + build。
live e2e(真 eip4flow):协办/转阅各 count:1 且子任务回溯出 businessKey/进目标用户待办;
流程图真 DI 实例渲染;会签起 3 并行任务/全票聚合推进。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-26 08:09:12 +08:00
parent dccca17314
commit 4f9e4abfc2
13 changed files with 1129 additions and 20 deletions

View File

@@ -86,11 +86,11 @@ public class CandidateUsersHandler {
? WfTypes.INITIATORLEADER : WfTypes.INITIATORDEPARTMANAGER;
users = directory.assignmentUser(t, userProperty.getContent(), beforeUser, null);
}else if(WfTypes.SCRIPTUSER.equals(userProperty.getType())){
// 原版经 ScriptingEngines.evaluate(content,"juel",execution) 求值;
// 独立服务不内置服务流脚本引擎(精简边界),WARN 降级,报告登记。
log.warn("candidateUsersHandler: scriptUser(JUEL 脚本)分支独立服务暂未接入,跳过该项"
+ "(影响面≈0.5%/26 处;命中则该任务无此类候选人,生产可监控)");
users = new ArrayList<String>();
// scriptUser:content 为 JUEL 表达式(会签等多实例办理人集合多用此类型,绝大多数形如 ${VARNAME},
// 如招投标/总包合同/施工技术交底会签的 ${APPLYUSERS})。原版经服务流脚本引擎求值;此处优先按
// 单变量名直读流程变量(稳,无命令上下文依赖),复杂表达式回退 flowable 表达式管理器对 execution 求值,
// 结果按 List/数组/逗号分隔串/单值归一为 userId 列表。修复前此分支 WARN 降级返空 → 这类会签节点无办理人被跳过。
users = resolveScriptUsers(runtimeService, processInstanceId, execution, userProperty.getContent());
}else if(WfTypes.PROJECTROLETYPE.equals(userProperty.getType())){
users = directory.getUsersByProjectRole(projectId, userProperty.getContent());
}
@@ -207,6 +207,93 @@ public class CandidateUsersHandler {
}
}
/** {@code ${VAR}} 单变量名匹配(会签 scriptUser 绝大多数为此形态)。 */
private static final java.util.regex.Pattern SINGLE_VAR =
java.util.regex.Pattern.compile("\\$\\{\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*\\}");
/**
* scriptUser 类型办理人解析:content 为 JUEL 表达式。绝大多数(含会签 {@code ${APPLYUSERS}})是单变量名,
* 优先直读该流程变量(稳,无命令上下文依赖);非单变量的复杂表达式回退 flowable 表达式管理器对 execution 求值。
* 结果按 List/数组/逗号分号(全/半角)分隔串/单值归一为去重 userId 列表;解析不出返回空(安全降级)。
*/
protected List<String> resolveScriptUsers(RuntimeService runtimeService, String processInstanceId,
Object execution, String content) {
if (content == null || content.isBlank()) {
return new ArrayList<String>();
}
Object value = null;
String varName = singleVarName(content);
if (varName != null && runtimeService != null && processInstanceId != null) {
value = getVariable(runtimeService, processInstanceId, varName);
}
if (value == null) {
value = evalExpression(execution, content);
}
List<String> users = coerceUserList(value);
if (users.isEmpty()) {
log.warn("candidateUsersHandler: scriptUser 表达式解析出空候选人 content={}(检查流程变量是否已设置)", content);
}
return users;
}
/** 单变量表达式 {@code ${VAR}} → 变量名;非单变量(复杂表达式/含运算)返回 null。 */
static String singleVarName(String content) {
if (content == null) {
return null;
}
java.util.regex.Matcher m = SINGLE_VAR.matcher(content.trim());
return m.matches() ? m.group(1) : null;
}
/** 把表达式求值结果归一为去重 userId 列表:支持 Collection/数组/逗号分号(全角半角)分隔串/单值。 */
static List<String> coerceUserList(Object value) {
List<String> out = new ArrayList<String>();
if (value == null) {
return out;
}
if (value instanceof java.util.Collection<?> col) {
for (Object o : col) {
addUser(out, o);
}
} else if (value instanceof Object[] arr) {
for (Object o : arr) {
addUser(out, o);
}
} else if (value instanceof String s) {
for (String part : s.split("[,;,;\\s]+")) {
addUser(out, part);
}
} else {
addUser(out, value);
}
return out;
}
private static void addUser(List<String> out, Object o) {
if (o == null) {
return;
}
String s = o.toString().trim();
if (!s.isEmpty() && !out.contains(s)) {
out.add(s);
}
}
/** 复杂 JUEL 表达式回退:命令上下文内经 flowable 表达式管理器对 execution(VariableScope)求值。 */
private Object evalExpression(Object execution, String content) {
try {
if (execution instanceof org.flowable.variable.api.delegate.VariableScope vs) {
var pec = org.flowable.engine.impl.context.Context.getProcessEngineConfiguration();
if (pec != null) {
return pec.getExpressionManager().createExpression(content).getValue(vs);
}
}
} catch (Exception e) {
log.warn("candidateUsersHandler: scriptUser 复杂表达式求值失败 content={}: {}", content, e.toString());
}
return null;
}
private static boolean isEmpty(String s) {
return s == null || s.trim().isEmpty();
}

View File

@@ -40,6 +40,8 @@ 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 int MAX_FANOUT = 50;
private static final Set<String> WITHDRAW_COMMENT_WHITELIST =
Set.of("回退", "主动召回", "更换任务处理人员");
@@ -437,6 +439,143 @@ public class FlowController {
return ResponseEntity.ok(t != null ? TaskDto.of(t) : null);
}
@PostMapping("/tasks/{taskId}/assist")
@org.springframework.transaction.annotation.Transactional
@Operation(summary = "协办(加签)",
description = "对齐老 ProcessCoreServiceImpl.createSubTask:为每个目标用户建一条独立子任务"
+ "(assignee=该用户,parentTaskId=当前任务,name=协办,formKey=父任务formKey 以便协办人渲染业务单据),父任务记意见。"
+ "子任务进协办人待办,办毕各自 complete,不阻断主任务办理。父任务不存在 → 404,targetUserIds 为空 → 400,超 "
+ MAX_FANOUT + " 人 → 400。整批 @Transactional 原子。")
public ResponseEntity<Map<String, Object>> assist(@PathVariable String taskId,
@RequestBody(required = false) Requests.ActionRequest req) {
List<String> userIds = targetUserIds(req);
ResponseEntity<Map<String, Object>> bad = validateFanout(userIds, "协办");
if (bad != null) {
return bad;
}
var parent = taskService.createTaskQuery().taskId(taskId).singleResult();
if (parent == null) {
return ResponseEntity.notFound().build();
}
// 协办子任务也带 formKey(取父任务 formKey),使协办人打开能渲染同一业务单据。
String formKey = formKeyResolver.resolve(parent.getFormKey(),
parent.getProcessDefinitionId(), parent.getTaskDefinitionKey());
addCommentIfPresent(taskId, parent, req == null ? null : req.comment);
for (String userId : userIds) {
org.flowable.task.api.Task sub = taskService.newTask();
sub.setAssignee(userId);
sub.setParentTaskId(taskId);
sub.setName("协办");
if (formKey != null) {
sub.setFormKey(formKey);
}
taskService.saveTask(sub);
}
Map<String, Object> r = new java.util.LinkedHashMap<>();
r.put("assisted", true);
r.put("count", userIds.size());
r.put("taskId", taskId);
return ResponseEntity.ok(r);
}
@PostMapping("/tasks/{taskId}/circulate")
@org.springframework.transaction.annotation.Transactional
@Operation(summary = "转阅(抄送)",
description = "对齐老 ProcessCoreServiceImpl.createNewTask:为每个目标用户建一条只读转阅任务"
+ "(name=转阅,assignee=该用户,parentTaskId=当前任务,formKey=父任务formKey 以便转阅人渲染同一业务单据)。"
+ "转阅不阻断、不推进主流程。父任务不存在 → 404,targetUserIds 为空 → 400,超 " + MAX_FANOUT
+ " 人 → 400。整批 @Transactional 原子。")
public ResponseEntity<Map<String, Object>> circulate(@PathVariable String taskId,
@RequestBody(required = false) Requests.ActionRequest req) {
List<String> userIds = targetUserIds(req);
ResponseEntity<Map<String, Object>> bad = validateFanout(userIds, "转阅");
if (bad != null) {
return bad;
}
var parent = taskService.createTaskQuery().taskId(taskId).singleResult();
if (parent == null) {
return ResponseEntity.notFound().build();
}
String formKey = formKeyResolver.resolve(parent.getFormKey(),
parent.getProcessDefinitionId(), parent.getTaskDefinitionKey());
addCommentIfPresent(taskId, parent, req == null ? null : req.comment);
for (String userId : userIds) {
org.flowable.task.api.Task copy = taskService.newTask();
copy.setName("转阅");
copy.setAssignee(userId);
// 用 setFormKey(而非塞 description)使审批渲染路径 FormKeyResolver 直接命中。
if (formKey != null) {
copy.setFormKey(formKey);
}
copy.setParentTaskId(taskId);
taskService.saveTask(copy);
}
Map<String, Object> r = new java.util.LinkedHashMap<>();
r.put("circulated", true);
r.put("count", userIds.size());
r.put("taskId", taskId);
return ResponseEntity.ok(r);
}
/** 协办/转阅派发人数校验:空 → 400「需指定」;超 {@link #MAX_FANOUT} → 400。合法返回 null。 */
private ResponseEntity<Map<String, Object>> validateFanout(List<String> userIds, String verb) {
if (userIds.isEmpty()) {
return ResponseEntity.badRequest().body(errorBody(verb + "需指定 targetUserIds"));
}
if (userIds.size() > MAX_FANOUT) {
return ResponseEntity.badRequest().body(errorBody(verb + "人数超过上限 " + MAX_FANOUT));
}
return null;
}
/** 协办/转阅目标用户:优先 targetUserIds 列表,回退单个 targetUserId;去空白去重。 */
private static List<String> targetUserIds(Requests.ActionRequest req) {
java.util.LinkedHashSet<String> set = new java.util.LinkedHashSet<>();
if (req != null && req.targetUserIds != null) {
for (String u : req.targetUserIds) {
if (u != null && !u.isBlank()) {
set.add(u.trim());
}
}
}
if (req != null && req.targetUserId != null && !req.targetUserId.isBlank()) {
set.add(req.targetUserId.trim());
}
return new java.util.ArrayList<>(set);
}
/** 父任务存在且意见非空时记入流程评论(对齐老 addComment:用父任务的 processInstanceId)。 */
private void addCommentIfPresent(String taskId, org.flowable.task.api.Task parent, String comment) {
if (parent != null && comment != null && !comment.isBlank()) {
taskService.addComment(taskId, parent.getProcessInstanceId(), comment);
}
}
/** 父任务回溯出的业务上下文(供协办/转阅独立任务渲染同一业务单据)。 */
private record ParentContext(String processInstanceId, String formKey,
String processDefinitionId, String taskDefinitionKey) {
}
/** 按 parentTaskId 取父任务的业务上下文:运行库优先,否则历史库;都查不到返回 null。 */
private ParentContext resolveParentContext(String parentTaskId) {
var p = taskService.createTaskQuery().taskId(parentTaskId).singleResult();
if (p != null) {
return new ParentContext(p.getProcessInstanceId(), p.getFormKey(),
p.getProcessDefinitionId(), p.getTaskDefinitionKey());
}
HistoricTaskInstance hp = historyService.createHistoricTaskInstanceQuery()
.taskId(parentTaskId).singleResult();
if (hp != null) {
return new ParentContext(hp.getProcessInstanceId(), hp.getFormKey(),
hp.getProcessDefinitionId(), hp.getTaskDefinitionKey());
}
return null;
}
private static boolean isBlank(String s) {
return s == null || s.isBlank();
}
@GetMapping("/tasks/{taskId}/approval-context")
@Operation(summary = "任务审批上下文",
description = "聚合返回 WfTemplate 驱动审批界面所需事实:formKey(=view_wftemplate_id,经 FormKeyResolver 历史回补)、"
@@ -453,13 +592,48 @@ public class FlowController {
dto.processDefinitionId = t.getProcessDefinitionId();
dto.taskDefinitionKey = t.getTaskDefinitionKey();
dto.suspended = t.isSuspended();
dto.formKey = formKeyResolver.resolve(t.getFormKey(), t.getProcessDefinitionId(), t.getTaskDefinitionKey());
dto.startFormKey = startFormKeyResolver.resolve(t.getProcessDefinitionId());
ProcessInstance pi = runtimeService.createProcessInstanceQuery()
.processInstanceId(t.getProcessInstanceId()).singleResult();
if (pi != null) {
dto.businessKey = pi.getBusinessKey();
dto.ended = false;
String formKeyRaw = t.getFormKey();
String procDefId = t.getProcessDefinitionId();
String taskDefKey = t.getTaskDefinitionKey();
String pid = t.getProcessInstanceId();
// 协办/转阅是独立任务(无 processInstanceId/businessKey):沿 parentTaskId 回溯父任务取业务上下文,
// 使协办人/转阅人打开能渲染同一业务单据。同时避免下面用 null pid 查 runtime 抛 IllegalArgument。
if (isBlank(pid) && !isBlank(t.getParentTaskId())) {
ParentContext pc = resolveParentContext(t.getParentTaskId());
if (pc != null) {
pid = pc.processInstanceId();
if (isBlank(formKeyRaw)) {
formKeyRaw = pc.formKey();
}
if (isBlank(procDefId)) {
procDefId = pc.processDefinitionId();
}
if (isBlank(taskDefKey)) {
taskDefKey = pc.taskDefinitionKey();
}
dto.processInstanceId = pid; // 让前端轨迹/business-data 能定位父流程
}
}
dto.formKey = formKeyResolver.resolve(formKeyRaw, procDefId, taskDefKey);
dto.startFormKey = startFormKeyResolver.resolve(procDefId);
if (!isBlank(pid)) {
ProcessInstance pi = runtimeService.createProcessInstanceQuery()
.processInstanceId(pid).singleResult();
if (pi != null) {
dto.businessKey = pi.getBusinessKey();
dto.ended = false;
} else {
// 父流程可能已进历史(协办/转阅后主流程已结束)
var hpi = historyService.createHistoricProcessInstanceQuery()
.processInstanceId(pid).singleResult();
if (hpi != null) {
dto.businessKey = hpi.getBusinessKey();
dto.ended = hpi.getEndTime() != null;
}
}
}
return ResponseEntity.ok(dto);
}

View File

@@ -0,0 +1,128 @@
package com.eip4.flowservice.api;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
/**
* 流程图(BPMN)查看端点:返回流程定义的 BPMN 2.0 XML + 当前/历史活动节点,供前端 bpmn-js 渲染并高亮。
*
* <p>迁移的 1512 个流程定义中 1501(99.3%)含 BPMNDI 布局段,bpmn-js 可直接据此排版。
* 节点名为中文 → 用前端 bpmn-js(浏览器字体)而非服务端出图(PNG 中文易乱码且需服务器字体)。</p>
*
* <p>只读:仅查询引擎,不改任何流程/任务/业务数据。运行中实例取运行库 procDefId 与当前节点;
* 已结束实例回退历史库取 procDefId(无当前节点)。实例不存在返回 {@code found=false}(前端降级)。</p>
*/
@RestController
@RequestMapping("/api/flow")
@Tag(name = "流程图", description = "BPMN XML + 当前/历史节点(bpmn-js 渲染高亮)")
public class ProcessDiagramController {
private static final Logger log = LoggerFactory.getLogger(ProcessDiagramController.class);
private final RepositoryService repositoryService;
private final RuntimeService runtimeService;
private final HistoryService historyService;
public ProcessDiagramController(RepositoryService repositoryService, RuntimeService runtimeService,
HistoryService historyService) {
this.repositoryService = repositoryService;
this.runtimeService = runtimeService;
this.historyService = historyService;
}
@GetMapping("/process/{processInstanceId}/diagram")
@Operation(summary = "流程图数据",
description = "返回 {found, bpmnXml, activeActivityIds(当前停留), finishedActivityIds(已走过)}。"
+ "运行中实例取运行库 procDefId + getActiveActivityIds;已结束取历史库 procDefId(无当前节点);"
+ "实例不存在 found=false。bpmnXml = repositoryService.getProcessModel(procDefId)。")
public ResponseEntity<Map<String, Object>> diagram(@PathVariable String processInstanceId) {
Map<String, Object> resp = new LinkedHashMap<>();
resp.put("processInstanceId", processInstanceId);
// procDefId:运行库优先(含当前活动节点),否则历史库(已结束)
ProcessInstance pi = runtimeService.createProcessInstanceQuery()
.processInstanceId(processInstanceId).singleResult();
String procDefId = pi != null ? pi.getProcessDefinitionId() : null;
boolean running = pi != null;
if (procDefId == null) {
HistoricProcessInstance hpi = historyService.createHistoricProcessInstanceQuery()
.processInstanceId(processInstanceId).singleResult();
procDefId = hpi != null ? hpi.getProcessDefinitionId() : null;
}
if (procDefId == null) {
resp.put("found", false);
resp.put("activeActivityIds", List.of());
resp.put("finishedActivityIds", List.of());
return ResponseEntity.ok(resp);
}
String bpmnXml = readProcessModel(procDefId);
if (bpmnXml == null) {
resp.put("found", false);
resp.put("activeActivityIds", List.of());
resp.put("finishedActivityIds", List.of());
return ResponseEntity.ok(resp);
}
// 当前停留节点(仅运行中实例有)
List<String> active = running ? safeActiveActivityIds(processInstanceId) : List.of();
// 已走过的历史节点
List<String> finished = historyService.createHistoricActivityInstanceQuery()
.processInstanceId(processInstanceId).finished().list().stream()
.map(a -> a.getActivityId())
.filter(id -> id != null && !id.isBlank())
.distinct()
.collect(Collectors.toList());
resp.put("found", true);
resp.put("bpmnXml", bpmnXml);
resp.put("activeActivityIds", active);
resp.put("finishedActivityIds", finished);
return ResponseEntity.ok(resp);
}
/** 读流程定义 BPMN XML(getProcessModel 返回部署的 BPMN 资源流)。读失败返回 null(前端降级)。 */
private String readProcessModel(String procDefId) {
try (InputStream is = repositoryService.getProcessModel(procDefId)) {
if (is == null) {
return null;
}
return StreamUtils.copyToString(is, StandardCharsets.UTF_8);
} catch (Exception e) {
log.warn("[流程图] 读取 BPMN 失败 procDefId={}: {}", procDefId, e.toString());
return null;
}
}
/** getActiveActivityIds 对已结束/不存在实例会抛异常 → 包裹降级为空。 */
private List<String> safeActiveActivityIds(String processInstanceId) {
try {
List<String> ids = runtimeService.getActiveActivityIds(processInstanceId);
return ids == null ? List.of() : ids;
} catch (RuntimeException e) {
log.debug("[流程图] 取当前节点降级 pi={}: {}", processInstanceId, e.toString());
return List.of();
}
}
}

View File

@@ -39,8 +39,10 @@ public final class Requests {
public static class ActionRequest {
/** 审批意见(记入流程评论)。 */
public String comment;
/** 目标用户(转办/协办/转阅用;reject/reback 不需要)。 */
/** 目标用户(转办用;reject/reback 不需要)。 */
public String targetUserId;
/** 多目标用户(协办/转阅:老系统用 MultiSelectField 选多人,每人各建一条子/转阅任务)。 */
public java.util.List<String> targetUserIds;
}
/**

View File

@@ -0,0 +1,64 @@
package com.dsasp.server.wf.user.assignee;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* scriptUser 会签办理人解析的纯函数单测(同包以访问包级 helper):
* 单变量名提取 + 求值结果归一为 userId 列表。修复前 scriptUser 分支 WARN 降级返空,
* 致招投标/总包合同/施工技术交底等会签节点(集合用 ${APPLYUSERS})无办理人被跳过。
*/
class CandidateUsersScriptUserTest {
@Test
void singleVarName_提取简单变量() {
assertThat(CandidateUsersHandler.singleVarName("${APPLYUSERS}")).isEqualTo("APPLYUSERS");
assertThat(CandidateUsersHandler.singleVarName(" ${ APPLYUSERS } ")).isEqualTo("APPLYUSERS");
}
@Test
void singleVarName_复杂表达式返回null() {
assertThat(CandidateUsersHandler.singleVarName("${a + b}")).isNull();
assertThat(CandidateUsersHandler.singleVarName("${users[0]}")).isNull();
assertThat(CandidateUsersHandler.singleVarName("ADMIN")).isNull();
assertThat(CandidateUsersHandler.singleVarName(null)).isNull();
}
@Test
void coerceUserList_支持List() {
assertThat(CandidateUsersHandler.coerceUserList(List.of("u1", "u2")))
.containsExactly("u1", "u2");
}
@Test
void coerceUserList_支持数组() {
assertThat(CandidateUsersHandler.coerceUserList(new String[] { "u1", "u2" }))
.containsExactly("u1", "u2");
}
@Test
void coerceUserList_逗号分号全角半角分隔串() {
assertThat(CandidateUsersHandler.coerceUserList("u1,u2; u3,u4;u5"))
.containsExactly("u1", "u2", "u3", "u4", "u5");
}
@Test
void coerceUserList_单值() {
assertThat(CandidateUsersHandler.coerceUserList("ADMIN")).containsExactly("ADMIN");
}
@Test
void coerceUserList_去重去空白() {
assertThat(CandidateUsersHandler.coerceUserList(Arrays.asList(" u1 ", "u1", "", "u2", null)))
.containsExactly("u1", "u2");
}
@Test
void coerceUserList_null返回空() {
assertThat(CandidateUsersHandler.coerceUserList(null)).isEmpty();
}
}

View File

@@ -330,4 +330,129 @@ class FlowControllerTest {
.andExpect(status().isOk())
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.content().string("1509"));
}
// ---------------------------------------------------------------- 协办(assist) / 转阅(circulate)
@Test
void 协办缺少目标用户返回400() throws Exception {
mvc.perform(post("/api/flow/tasks/task-9/assist")
.contentType("application/json")
.content("{\"comment\":\"请协助\"}"))
.andExpect(status().isBadRequest());
}
@Test
void 协办为每个目标用户建子任务并记意见() throws Exception {
// 父任务查得(取 processInstanceId 记意见)
when(taskService.createTaskQuery()).thenReturn(taskQuery);
when(taskQuery.taskId("task-9")).thenReturn(taskQuery);
Task parent = org.mockito.Mockito.mock(Task.class);
when(parent.getProcessInstanceId()).thenReturn("pi-9");
when(taskQuery.singleResult()).thenReturn(parent);
// 每次 newTask() 返回一个新子任务桩
Task sub = org.mockito.Mockito.mock(Task.class);
when(taskService.newTask()).thenReturn(sub);
mvc.perform(post("/api/flow/tasks/task-9/assist")
.contentType("application/json")
.content("{\"comment\":\"请协助\",\"targetUserIds\":[\"u-a\",\"u-b\"]}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.assisted").value(true))
.andExpect(jsonPath("$.count").value(2));
// 两个子任务:各设受托人/父任务/名称「协办」后保存
verify(sub).setAssignee("u-a");
verify(sub).setAssignee("u-b");
verify(sub, org.mockito.Mockito.times(2)).setParentTaskId("task-9");
verify(sub, org.mockito.Mockito.times(2)).setName("协办");
verify(taskService, org.mockito.Mockito.times(2)).saveTask(sub);
verify(taskService).addComment("task-9", "pi-9", "请协助");
}
@Test
void 转阅为每个目标用户建转阅任务并存formKey() throws Exception {
when(taskService.createTaskQuery()).thenReturn(taskQuery);
when(taskQuery.taskId("task-10")).thenReturn(taskQuery);
Task parent = org.mockito.Mockito.mock(Task.class);
when(parent.getProcessInstanceId()).thenReturn("pi-10");
when(parent.getFormKey()).thenReturn("wf-tpl-77"); // FormKeyResolver: 原始非空直接返回
when(taskQuery.singleResult()).thenReturn(parent);
Task copy = org.mockito.Mockito.mock(Task.class);
when(taskService.newTask()).thenReturn(copy);
mvc.perform(post("/api/flow/tasks/task-10/circulate")
.contentType("application/json")
.content("{\"comment\":\"请阅\",\"targetUserIds\":[\"u-c\"]}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.circulated").value(true))
.andExpect(jsonPath("$.count").value(1));
verify(copy).setName("转阅");
verify(copy).setAssignee("u-c");
verify(copy).setFormKey("wf-tpl-77"); // 用 setFormKey 而非 description,审批渲染 FormKeyResolver 直接命中
verify(copy).setParentTaskId("task-10");
verify(taskService).saveTask(copy);
}
@Test
void 转阅父任务不存在返回404() throws Exception {
when(taskService.createTaskQuery()).thenReturn(taskQuery);
when(taskQuery.taskId("nope")).thenReturn(taskQuery);
when(taskQuery.singleResult()).thenReturn(null);
mvc.perform(post("/api/flow/tasks/nope/circulate")
.contentType("application/json")
.content("{\"targetUserIds\":[\"u-c\"]}"))
.andExpect(status().isNotFound());
}
@Test
void 协办独立任务approvalContext回溯父任务取业务上下文() throws Exception {
// 协办/转阅建的是独立任务:无 processInstanceId,有 parentTaskId。审批上下文须回溯父任务取 businessKey/formKey,
// 否则协办人/转阅人打开看不到业务单据(code review HIGH 修复点)。
when(taskService.createTaskQuery()).thenReturn(taskQuery);
Task sub = org.mockito.Mockito.mock(Task.class);
when(sub.getName()).thenReturn("协办");
when(sub.getProcessInstanceId()).thenReturn(null);
when(sub.getParentTaskId()).thenReturn("parent-1");
when(sub.getFormKey()).thenReturn(null);
TaskQuery subQuery = org.mockito.Mockito.mock(TaskQuery.class);
when(taskQuery.taskId("sub-1")).thenReturn(subQuery);
when(subQuery.singleResult()).thenReturn(sub);
// 父任务:真实流程任务,带 processInstanceId/formKey
Task parent = org.mockito.Mockito.mock(Task.class);
when(parent.getProcessInstanceId()).thenReturn("pi-1");
when(parent.getFormKey()).thenReturn("wf-77");
when(parent.getProcessDefinitionId()).thenReturn("def-1");
when(parent.getTaskDefinitionKey()).thenReturn("node-a");
TaskQuery parentQuery = org.mockito.Mockito.mock(TaskQuery.class);
when(taskQuery.taskId("parent-1")).thenReturn(parentQuery);
when(parentQuery.singleResult()).thenReturn(parent);
// 父流程实例 businessKey
when(runtimeService.createProcessInstanceQuery()).thenReturn(processInstanceQuery);
when(processInstanceQuery.processInstanceId("pi-1")).thenReturn(processInstanceQuery);
ProcessInstance pi = org.mockito.Mockito.mock(ProcessInstance.class);
when(pi.getBusinessKey()).thenReturn("BK-1");
when(processInstanceQuery.singleResult()).thenReturn(pi);
mvc.perform(get("/api/flow/tasks/sub-1/approval-context"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.found").value(true))
.andExpect(jsonPath("$.formKey").value("wf-77"))
.andExpect(jsonPath("$.businessKey").value("BK-1"))
.andExpect(jsonPath("$.processInstanceId").value("pi-1"));
}
@Test
void 协办超过上限返回400() throws Exception {
StringBuilder ids = new StringBuilder("[");
for (int i = 0; i < 51; i++) {
ids.append(i == 0 ? "" : ",").append("\"u").append(i).append("\"");
}
ids.append("]");
mvc.perform(post("/api/flow/tasks/t/assist")
.contentType("application/json")
.content("{\"targetUserIds\":" + ids + "}"))
.andExpect(status().isBadRequest());
}
}

View File

@@ -0,0 +1,120 @@
package com.eip4.flowservice.api;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricActivityInstanceQuery;
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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
/**
* 流程图端点薄层单测:mock 引擎,验证 BPMN XML 透出 + 当前/历史节点收敛 + 实例不存在降级。
*/
@ExtendWith(MockitoExtension.class)
class ProcessDiagramControllerTest {
@Mock RepositoryService repositoryService;
@Mock RuntimeService runtimeService;
@Mock HistoryService historyService;
@Mock ProcessInstanceQuery processInstanceQuery;
@Mock HistoricProcessInstanceQuery historicProcessInstanceQuery;
@Mock HistoricActivityInstanceQuery historicActivityInstanceQuery;
MockMvc mvc;
@BeforeEach
void setUp() {
ProcessDiagramController controller = new ProcessDiagramController(repositoryService, runtimeService, historyService);
mvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
void 运行中流程返回XML与当前及历史节点() throws Exception {
ProcessInstance pi = org.mockito.Mockito.mock(ProcessInstance.class);
when(pi.getProcessDefinitionId()).thenReturn("def-1");
when(runtimeService.createProcessInstanceQuery()).thenReturn(processInstanceQuery);
when(processInstanceQuery.processInstanceId("pi-1")).thenReturn(processInstanceQuery);
when(processInstanceQuery.singleResult()).thenReturn(pi);
when(runtimeService.getActiveActivityIds("pi-1")).thenReturn(List.of("task_b"));
String xml = "<?xml version=\"1.0\"?><definitions><process id=\"p\"/></definitions>";
when(repositoryService.getProcessModel("def-1"))
.thenReturn(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
HistoricActivityInstance a1 = org.mockito.Mockito.mock(HistoricActivityInstance.class);
when(a1.getActivityId()).thenReturn("task_a");
when(historyService.createHistoricActivityInstanceQuery()).thenReturn(historicActivityInstanceQuery);
when(historicActivityInstanceQuery.processInstanceId("pi-1")).thenReturn(historicActivityInstanceQuery);
when(historicActivityInstanceQuery.finished()).thenReturn(historicActivityInstanceQuery);
when(historicActivityInstanceQuery.list()).thenReturn(List.<HistoricActivityInstance>of(a1));
mvc.perform(get("/api/flow/process/pi-1/diagram"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.found").value(true))
.andExpect(jsonPath("$.bpmnXml").value(xml))
.andExpect(jsonPath("$.activeActivityIds[0]").value("task_b"))
.andExpect(jsonPath("$.finishedActivityIds[0]").value("task_a"));
}
@Test
void 已结束流程走历史取XML无当前节点() throws Exception {
// 运行库查不到
when(runtimeService.createProcessInstanceQuery()).thenReturn(processInstanceQuery);
when(processInstanceQuery.processInstanceId("pi-2")).thenReturn(processInstanceQuery);
when(processInstanceQuery.singleResult()).thenReturn(null);
// 历史库查得 procDefId
HistoricProcessInstance hpi = org.mockito.Mockito.mock(HistoricProcessInstance.class);
when(hpi.getProcessDefinitionId()).thenReturn("def-2");
when(historyService.createHistoricProcessInstanceQuery()).thenReturn(historicProcessInstanceQuery);
when(historicProcessInstanceQuery.processInstanceId("pi-2")).thenReturn(historicProcessInstanceQuery);
when(historicProcessInstanceQuery.singleResult()).thenReturn(hpi);
String xml = "<definitions/>";
when(repositoryService.getProcessModel("def-2"))
.thenReturn(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
when(historyService.createHistoricActivityInstanceQuery()).thenReturn(historicActivityInstanceQuery);
when(historicActivityInstanceQuery.processInstanceId("pi-2")).thenReturn(historicActivityInstanceQuery);
when(historicActivityInstanceQuery.finished()).thenReturn(historicActivityInstanceQuery);
when(historicActivityInstanceQuery.list()).thenReturn(List.<HistoricActivityInstance>of());
mvc.perform(get("/api/flow/process/pi-2/diagram"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.found").value(true))
.andExpect(jsonPath("$.bpmnXml").value(xml))
.andExpect(jsonPath("$.activeActivityIds").isEmpty());
}
@Test
void 实例不存在返回found_false不报错() throws Exception {
when(runtimeService.createProcessInstanceQuery()).thenReturn(processInstanceQuery);
when(processInstanceQuery.processInstanceId(eq("nope"))).thenReturn(processInstanceQuery);
when(processInstanceQuery.singleResult()).thenReturn(null);
when(historyService.createHistoricProcessInstanceQuery()).thenReturn(historicProcessInstanceQuery);
when(historicProcessInstanceQuery.processInstanceId("nope")).thenReturn(historicProcessInstanceQuery);
when(historicProcessInstanceQuery.singleResult()).thenReturn(null);
mvc.perform(get("/api/flow/process/nope/diagram"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.found").value(false));
}
}