From 0bbe3ac971a3eaf0ba0cc542a4bbef86da7c9e13 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Mon, 16 Nov 2026 20:50:40 +0800 Subject: [PATCH 1/6] =?UTF-8?q?fix:=20=E9=80=80=E5=9B=9E=E5=80=99=E9=80=89?= =?UTF-8?q?=E8=8A=82=E7=82=B9=E6=94=B9=E4=B8=BA=E5=9F=BA=E4=BA=8E=E6=89=A7?= =?UTF-8?q?=E8=A1=8C=E5=8E=86=E5=8F=B2=E5=B9=B6=E6=94=B6=E7=B4=A7=E9=80=80?= =?UTF-8?q?=E5=9B=9E=E6=A0=A1=E9=AA=8C=20(framework)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - FlowContent 新增 backNodes:只包含当前记录真实执行过的历史节点, 倒序去重保证"最近经过的节点"优先(停留在 C 时为 B、A), 且没有候选时不向展示按钮集合下发 RETURN,修正开始节点 "退回按钮可点但提交必然失败"的错误交互(issue #270) - BackNodeHelper 新增 historyBackNodes,按记录 id 正序倒序遍历历史记录, 同一节点多次执行只保留最近一次,未执行的分支节点天然被排除 - ActionManager 收紧 RETURN 校验:开始节点不支持退回; 退回目标必须存在于当前记录的历史执行链(并行/条件分支中 "结构上不是下游但从未执行"的节点同样被拒绝) - FlowStateException 新增 nodeNotSupportReturn / backNodeNotInHistory - BaseAction.show 兼容缺少 display 配置的旧流程数据,避免详情接口空指针 - 新增 FlowIssue270ReturnNodeControlTest(历史候选、最近优先、未执行分支拒绝、开始节点) Closes #270 --- .../com/codingapi/flow/action/BaseAction.java | 4 +- .../flow/exception/FlowStateException.java | 21 ++ .../codingapi/flow/manager/ActionManager.java | 34 ++ .../flow/node/helper/BackNodeHelper.java | 67 +++- .../flow/pojo/response/FlowContent.java | 31 +- .../flow/service/impl/FlowDetailService.java | 22 ++ .../FlowIssue270ReturnNodeControlTest.java | 343 ++++++++++++++++++ 7 files changed, 513 insertions(+), 9 deletions(-) create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowIssue270ReturnNodeControlTest.java diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/BaseAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/BaseAction.java index be57296d..60f77b1f 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/BaseAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/BaseAction.java @@ -48,7 +48,9 @@ public ActionDisplay display() { @Override public boolean show(FlowSession flowSession) { - return this.display.show(flowSession); + // 兼容早期设计/导入的流程数据:动作缺少 display 配置时按默认展示处理, + // 与 ActionDisplay 未配置展示脚本即展示的口径一致,避免详情接口空指针 + return this.display == null || this.display.show(flowSession); } @Override diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowStateException.java b/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowStateException.java index cbe2599c..aac905ea 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowStateException.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowStateException.java @@ -109,6 +109,27 @@ public static FlowStateException nodeNotSupportRevoke() { return new FlowStateException("node.notSupportRevoke", "Node not support revoke"); } + + /** + * Node not support return (start node has no history node to return) + * + * @return exception + */ + public static FlowStateException nodeNotSupportReturn() { + return new FlowStateException("node.notSupportReturn", "Node not support return"); + } + + /** + * Return target node is not executed in current process + * + * @param nodeId node id + * @return exception + */ + public static FlowStateException backNodeNotInHistory(String nodeId) { + return new FlowStateException("node.backNode.notInHistory", + String.format("Return target node %s is not in the executed history", nodeId)); + } + /** * Record not support urge * diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/manager/ActionManager.java b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/ActionManager.java index e775e0bc..39d01fbf 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/manager/ActionManager.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/ActionManager.java @@ -2,6 +2,7 @@ import com.codingapi.flow.action.IFlowAction; import com.codingapi.flow.action.actions.*; +import com.codingapi.flow.exception.FlowStateException; import com.codingapi.flow.exception.FlowValidationException; import com.codingapi.flow.form.FlowForm; import com.codingapi.flow.node.IFlowNode; @@ -9,6 +10,7 @@ import com.codingapi.flow.node.nodes.EndNode; import com.codingapi.flow.node.nodes.HandleNode; import com.codingapi.flow.node.nodes.StartNode; +import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowAdvice; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.workflow.Workflow; @@ -146,6 +148,10 @@ public void verifySession(FlowSession session) { } IFlowNode backNode = flowAdvice.getBackNode(); IFlowNode currentNode = session.getCurrentNode(); + // 开始节点没有任何历史节点,不存在可退回目标,直接拒绝(issue #270) + if (StartNode.NODE_TYPE.equals(currentNode.getType())) { + throw FlowStateException.nodeNotSupportReturn(); + } if (currentNode.equals(backNode)) { throw FlowValidationException.required("backNode"); } @@ -159,10 +165,38 @@ public void verifySession(FlowSession session) { || backNode.getType().equals(HandleNode.NODE_TYPE))) { throw FlowValidationException.required("backNode"); } + // 退回目标必须是当前记录真实执行过的历史节点: + // 并行、条件分支中"结构上不是下游但实际没走过"的节点同样不可退回(issue #270) + verifyBackNodeExecuted(session, backNode); } } + /** + * 校验退回目标是否为当前记录真实执行过的历史节点。 + * + *

仅靠“目标不是当前节点的下游”不足以约束退回:并行、条件分支里存在“不是下游但从未执行”的节点, + * 跳转到此类节点会让流程进入未走过的路径。这里以当前记录之前的历史记录为唯一依据, + * 与详情接口输出的可退回节点({@code FlowContent.backNodes})保持同一口径(issue #270)。

+ * + * @param session 当前会话 + * @param backNode 退回目标节点 + */ + private void verifyBackNodeExecuted(FlowSession session, IFlowNode backNode) { + FlowRecord currentRecord = session.getCurrentRecord(); + if (currentRecord == null) { + throw FlowValidationException.required("backNode"); + } + boolean executed = session.getRepositoryHolder() + .getFlowRecordService() + .findFlowRecordBeforeRecords(currentRecord.getProcessId(), currentRecord.getId()) + .stream() + .anyMatch(record -> backNode.getId().equals(record.getNodeId())); + if (!executed) { + throw FlowStateException.backNodeNotInHistory(backNode.getId()); + } + } + /** * 校验审批意见是否必填。 * diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/node/helper/BackNodeHelper.java b/flow-engine-framework/src/main/java/com/codingapi/flow/node/helper/BackNodeHelper.java index 32f82a5b..16d50298 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/node/helper/BackNodeHelper.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/node/helper/BackNodeHelper.java @@ -4,32 +4,39 @@ import com.codingapi.flow.node.nodes.ApprovalNode; import com.codingapi.flow.node.nodes.HandleNode; import com.codingapi.flow.node.nodes.StartNode; +import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.workflow.Workflow; import lombok.Getter; import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; import java.util.List; +import java.util.Set; public class BackNodeHelper { + /** + * 允许作为退回目标的节点类型:只有会产生真实审批记录的节点才可退回, + * 抄送、子流程、路由等节点退出时会静默停滞,不参与退回。 + */ + private static final Set BACK_NODE_TYPES = Set.of( + StartNode.NODE_TYPE, + ApprovalNode.NODE_TYPE, + HandleNode.NODE_TYPE); + private final Workflow workflow; private final IFlowNode currentNode; @Getter private final List backNodes; - private final List backNodeTypes = new ArrayList<>(); - public BackNodeHelper(Workflow workflow, IFlowNode currentNode) { this.workflow = workflow; this.currentNode = currentNode; this.backNodes = new ArrayList<>(); - this.backNodeTypes.add(StartNode.NODE_TYPE); - this.backNodeTypes.add(ApprovalNode.NODE_TYPE); - this.backNodeTypes.add(HandleNode.NODE_TYPE); - IFlowNode startNode = workflow.getStartNode(); this.backNodes.add(startNode); @@ -41,7 +48,7 @@ private void fetchBackNodes(IFlowNode targetNode) { List nextNodes = workflow.nextNodes(targetNode); if (!nextNodes.contains(currentNode)) { for (IFlowNode nextNode : nextNodes) { - if (this.backNodeTypes.contains(nextNode.getType())) { + if (BACK_NODE_TYPES.contains(nextNode.getType())) { this.backNodes.add(nextNode); } this.fetchBackNodes(nextNode); @@ -49,4 +56,50 @@ private void fetchBackNodes(IFlowNode targetNode) { } } + /** + * 按真实执行历史计算可退回节点。 + * + *

退回只能回到当前记录实际经过的节点,因此候选来源是当前记录之前的历史记录, + * 而不是流程定义的全量节点(issue #270):

+ *
    + *
  • 历史记录按记录 id 正序排列后倒序遍历,保证“最近经过的节点”排在第一位 + * (例如停留在 C 节点时得到 B、A);
  • + *
  • 同一节点多次执行(退回后重新提交)只保留最近一次,避免重复选项;
  • + *
  • 当前节点自身不可作为退回目标,未执行过的分支节点自然不会出现。
  • + *
+ * + * @param workflow 当前流程定义 + * @param beforeRecords 当前记录之前的历史记录(可乱序) + * @param currentNodeId 当前记录所在节点 id + * @return 可退回节点,最近优先 + */ + public static List historyBackNodes(Workflow workflow, + List beforeRecords, + String currentNodeId) { + if (beforeRecords == null || beforeRecords.isEmpty()) { + return new ArrayList<>(); + } + List sortedRecords = beforeRecords.stream() + .sorted(Comparator.comparingLong(FlowRecord::getId)) + .toList(); + + List historyBackNodes = new ArrayList<>(); + Set visitedNodeIds = new HashSet<>(); + for (int i = sortedRecords.size() - 1; i >= 0; i--) { + String nodeId = sortedRecords.get(i).getNodeId(); + if (!visitedNodeIds.add(nodeId)) { + continue; + } + if (nodeId.equals(currentNodeId)) { + continue; + } + IFlowNode node = workflow.getFlowNode(nodeId); + if (node == null || !BACK_NODE_TYPES.contains(node.getType())) { + continue; + } + historyBackNodes.add(node); + } + return historyBackNodes; + } + } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowContent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowContent.java index 183770ef..2be97fc9 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowContent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowContent.java @@ -1,5 +1,6 @@ package com.codingapi.flow.pojo.response; +import com.codingapi.flow.action.ActionType; import com.codingapi.flow.action.IFlowAction; import com.codingapi.flow.form.FlowForm; import com.codingapi.flow.form.permission.FormFieldPermission; @@ -176,6 +177,15 @@ public class FlowContent { */ private List nodes; + /** + * 可退回节点。 + * + *

只包含当前记录真实执行过的历史节点(剔除当前节点),并按“最近经过的节点”优先排序, + * 供退回弹框直接渲染候选列表;为空表示当前记录没有可退回的节点(如开始节点)。 + * 与 {@link #nodes} 的全量流程定义节点区分,避免前端从定义节点中截取导致越界选择(issue #270)。

+ */ + private List backNodes; + /** * 支持撤销 */ @@ -227,7 +237,7 @@ public void pushCurrentNode(FlowSession flowSession) { if (currentNode != null) { ActionManager actionManager = currentNode.actionManager(); NodeStrategyManager strategyManager = currentNode.strategyManager(); - this.actions = toActionMaps(actionManager.filterActions(flowSession)); + this.actions = filterUnsupportedActions(toActionMaps(actionManager.filterActions(flowSession))); this.actionList = toActionMaps(actionManager.getActions()); this.adviceRequired = strategyManager.isAdviceRequired(); this.signRequired = strategyManager.isSignRequired(); @@ -244,6 +254,25 @@ public void pushCurrentNode(FlowSession flowSession) { } } + /** + * 过滤当前不可执行的按钮。 + * + *

没有任何可退回节点时(开始节点或流程首个节点),退回动作不应出现在展示按钮集合中, + * 否则会出现“按钮可点但提交必然失败”的错误交互(issue #270)。 + * {@link #actionList} 仍保留节点配置的全部按钮,前端按展示集合自行隐藏。

+ * + * @param actions 节点过滤后的展示动作 + * @return 过滤后的展示动作 + */ + private List> filterUnsupportedActions(List> actions) { + if (this.backNodes != null && !this.backNodes.isEmpty()) { + return actions; + } + return actions.stream() + .filter(action -> !ActionType.RETURN.name().equals(action.get("type"))) + .toList(); + } + /** * 输出动作配置,并附加运行期能力标记。 * diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDetailService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDetailService.java index 6d8a3552..10ba61c1 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDetailService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDetailService.java @@ -6,9 +6,11 @@ import com.codingapi.flow.form.FlowForm; import com.codingapi.flow.form.FormData; import com.codingapi.flow.node.IFlowNode; +import com.codingapi.flow.node.helper.BackNodeHelper; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.pojo.request.FlowDetailRequest; import com.codingapi.flow.pojo.response.FlowContent; +import com.codingapi.flow.pojo.response.NodeOption; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.FlowRecordService; import com.codingapi.flow.service.WorkflowService; @@ -145,9 +147,29 @@ private void loadCurrentNode() { this.flowContent.pushCurrentNode(this.flowSession); } + /** + * 加载可退回节点。 + * + *

候选来自当前记录真实执行过的历史记录(而不是流程定义的全量节点), + * 由 {@link BackNodeHelper#historyBackNodes} 按最近优先输出,供前端直接渲染退回候选列表。 + * 必须在 {@link #loadCurrentNode()} 之前执行:没有可退回节点时,退回按钮不会下发到展示按钮集合。

+ */ + private void loadBackNodes() { + if (this.flowRecord == null) { + this.flowContent.setBackNodes(List.of()); + return; + } + List beforeRecords = flowRecordService.findFlowRecordBeforeRecords( + this.flowRecord.getProcessId(), this.flowRecord.getId()); + List backNodes = BackNodeHelper.historyBackNodes( + this.workflow, beforeRecords, this.flowRecord.getNodeId()); + this.flowContent.setBackNodes(backNodes.stream().map(NodeOption::new).toList()); + } + public FlowContent create() { this.loadCurrentOperator(); this.loadWorkflow(); + this.loadBackNodes(); this.loadCurrentNode(); this.loadTodoFlowRecords(); this.loadHistoryRecords(); diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowIssue270ReturnNodeControlTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowIssue270ReturnNodeControlTest.java new file mode 100644 index 00000000..6d2f72ec --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowIssue270ReturnNodeControlTest.java @@ -0,0 +1,343 @@ +package com.codingapi.flow.service; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.codingapi.flow.action.ActionType; +import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.action.actions.PassAction; +import com.codingapi.flow.action.actions.ReturnAction; +import com.codingapi.flow.builder.ActionBuilder; +import com.codingapi.flow.builder.FormFieldPermissionsBuilder; +import com.codingapi.flow.builder.NodeStrategyBuilder; +import com.codingapi.flow.context.GatewayContext; +import com.codingapi.flow.exception.FlowException; +import com.codingapi.flow.factory.MyFlowServiceFactory; +import com.codingapi.flow.form.DataType; +import com.codingapi.flow.form.FlowForm; +import com.codingapi.flow.form.FlowFormBuilder; +import com.codingapi.flow.form.permission.PermissionType; +import com.codingapi.flow.node.IFlowNode; +import com.codingapi.flow.node.nodes.ApprovalNode; +import com.codingapi.flow.node.nodes.ConditionBranchNode; +import com.codingapi.flow.node.nodes.ConditionElseBranchNode; +import com.codingapi.flow.node.nodes.ConditionNode; +import com.codingapi.flow.node.nodes.EndNode; +import com.codingapi.flow.node.nodes.StartNode; +import com.codingapi.flow.pojo.body.FlowAdviceBody; +import com.codingapi.flow.pojo.request.FlowActionRequest; +import com.codingapi.flow.pojo.request.FlowCreateRequest; +import com.codingapi.flow.pojo.request.FlowDetailRequest; +import com.codingapi.flow.pojo.response.FlowContent; +import com.codingapi.flow.pojo.response.NodeOption; +import com.codingapi.flow.record.FlowRecord; +import com.codingapi.flow.script.factory.FlowGroovyScriptFactory; +import com.codingapi.flow.strategy.node.FormFieldPermissionStrategy; +import com.codingapi.flow.strategy.node.MultiOperatorAuditStrategy; +import com.codingapi.flow.strategy.node.OperatorLoadStrategy; +import com.codingapi.flow.user.User; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.WorkflowBuilder; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * issue #270 退回节点的操作控制。 + * + *

流程设计:A(开始) -> B(审批) -> C(审批) -> D(结束),B、C 均开启退回动作。 + * + *

    + *
  • 可退回节点只能来自当前记录真实执行过的历史节点,且按“最近优先”排序;
  • + *
  • 未执行过的分支节点不能作为退回目标(即使它不是当前节点的下游);
  • + *
  • 开始节点没有可退回节点,不对外展示退回动作。
  • + *
+ */ +class FlowIssue270ReturnNodeControlTest { + + private final MyFlowServiceFactory factory = new MyFlowServiceFactory(); + + /** + * 线性流程:B 节点待办只能退回 A,C 节点待办按“最近优先”返回 B、A。 + */ + @Test + void detailShouldProvideHistoryBackNodesNearestFirst() { + // given:A -> B(b1、b2 或签) -> C(c1) -> D + User a1 = new User(1, "a1"); + User b1 = new User(2, "b1"); + User b2 = new User(3, "b2"); + User c1 = new User(4, "c1"); + registerUsers(a1, b1, b2, c1); + + StartNode startNode = startNode(); + ApprovalNode bNode = approvalNode("B审批", "[2,3]", + new MultiOperatorAuditStrategy(MultiOperatorAuditStrategy.Type.ANY, 0), true); + ApprovalNode cNode = approvalNode("C审批", "[4]", null, true); + Workflow workflow = saveWorkflow(a1, startNode, bNode, cNode, EndNode.builder().build()); + Map data = data(); + + // when:流程提交到 B 节点 + startAndSubmit(workflow, startNode, a1, data); + FlowContent bDetail = detail(todoOf(b1, bNode), b1); + + // then:B 节点只能退回开始节点 + assertEquals(List.of(startNode.getId()), backNodeIds(bDetail), "B 节点只应能退回开始节点"); + + // when:b1 审批通过,流程提交到 C 节点 + pass(todoOf(b1, bNode), bNode, b1, data); + FlowContent cDetail = detail(todoOf(c1, cNode), c1); + + // then:C 节点可退回 B、A,且最近的 B 排第一,不包含当前节点与结束节点 + assertEquals(List.of(bNode.getId(), startNode.getId()), backNodeIds(cDetail), + "C 节点可退回节点应为 B、A(最近优先)"); + assertEquals(List.of("B审批", "开始节点"), backNodeNames(cDetail)); + } + + /** + * 条件分支:未执行的分支节点不能作为退回目标,也不应出现在可退回列表中。 + */ + @Test + void shouldRejectBackNodeNotExecutedInConditionBranch() { + // given:A -> B -> 条件(days<=3 走 D,否则走 E) -> F -> 结束,本次数据命中 D 分支 + User a1 = new User(1, "a1"); + User b1 = new User(2, "b1"); + User d1 = new User(3, "d1"); + User e1 = new User(4, "e1"); + User f1 = new User(5, "f1"); + registerUsers(a1, b1, d1, e1, f1); + + StartNode startNode = startNode(); + ApprovalNode bNode = approvalNode("B审批", "[2]", null, true); + ApprovalNode dNode = approvalNode("D审批", "[3]", null, true); + ApprovalNode eNode = approvalNode("E审批", "[4]", null, true); + ApprovalNode fNode = approvalNode("F审批", "[5]", null, true); + + ConditionBranchNode hitBranch = ConditionBranchNode.builder() + .name("命中分支") + .conditionScript(FlowGroovyScriptFactory.createConditionScript( + "def run(request){return request.getFormData('days') <= 3}").getKey()) + .order(1) + .blocks(dNode) + .build(); + ConditionElseBranchNode elseBranch = ConditionElseBranchNode.builder() + .name("else分支") + .order(2) + .blocks(eNode) + .build(); + ConditionNode conditionNode = ConditionNode.builder() + .name("条件控制") + .blocks(hitBranch, elseBranch) + .build(); + + Workflow workflow = saveWorkflow(a1, startNode, bNode, conditionNode, fNode, + EndNode.builder().build()); + Map data = data(); + + startAndSubmit(workflow, startNode, a1, data); + pass(todoOf(b1, bNode), bNode, b1, data); + pass(todoOf(d1, dNode), dNode, d1, data); + FlowRecord fTodo = todoOf(f1, fNode); + + // then 1:可退回节点只包含执行过的 D、B、A,未执行的 E 不在其中 + FlowContent fDetail = detail(fTodo, f1); + assertEquals(List.of("D审批", "B审批", "开始节点"), backNodeNames(fDetail), + "未执行的分支节点不应出现在可退回列表中"); + + // then 2:即使绕过前端直接指定未执行过的 E,也必须被拒绝 + assertThrows(FlowException.class, + () -> returnTo(fTodo, fNode, f1, eNode, data), + "退回到未执行过的节点必须被拒绝"); + } + + /** + * 开始节点即使被配置了退回动作,也不应对外暴露退回按钮与候选节点。 + */ + @Test + void startNodeShouldNotExposeReturnAction() { + // given:A -> B -> D,并在开始节点的流程定义 JSON 中写入 RETURN(模拟设计器按钮配置) + User a1 = new User(1, "a1"); + User b1 = new User(2, "b1"); + registerUsers(a1, b1); + + StartNode startNode = startNode(); + ApprovalNode bNode = approvalNode("B审批", "[2]", null, false); + Workflow workflow = saveWorkflow(a1, startNode, bNode, EndNode.builder().build()); + + JSONObject json = JSONObject.parseObject(workflow.toJson()); + JSONArray nodes = json.getJSONArray("nodes"); + JSONObject startJson = nodes.getJSONObject(0); + JSONObject returnAction = new JSONObject(); + returnAction.put("id", "start-return-action"); + returnAction.put("type", ActionType.RETURN.name()); + returnAction.put("title", "退回"); + returnAction.put("enable", true); + startJson.getJSONArray("actions").add(returnAction); + Workflow parsed = Workflow.formJson(json.toJSONString()); + factory.workflowService.saveWorkflow(parsed); + + // when:发起流程后停留在开始节点 + FlowRecord startTodo = create(parsed, a1, data()); + FlowContent detail = detail(startTodo, a1); + + // then 1:开始节点不展示退回动作,也没有可退回节点 + assertTrue(detail.getBackNodes() == null || detail.getBackNodes().isEmpty(), + "开始节点不应有可退回节点"); + assertFalse(detail.getActions().stream() + .anyMatch(action -> ActionType.RETURN.name().equals(action.get("type"))), + "开始节点不应下发退回按钮"); + assertFalse(parsed.getStartNode().actionManager().getActions().stream() + .noneMatch(action -> ActionType.RETURN.name().equals(action.type())), + "前置条件:开始节点确实配置了退回动作"); + + // then 2:直接调用退回接口同样被拒绝 + IFlowNode parsedStartNode = parsed.getStartNode(); + IFlowNode parsedBNode = parsed.getFlowNode(bNode.getId()); + assertThrows(FlowException.class, () -> returnTo(startTodo, parsedStartNode, a1, parsedBNode, data()), + "开始节点发起退回必须被拒绝"); + } + + // ==================== 流程装配 ==================== + + private void registerUsers(User... users) { + for (User user : users) { + factory.userGateway.save(user); + } + GatewayContext.getInstance().setFlowOperatorGateway(factory.userGateway); + } + + private FlowForm form() { + return FlowFormBuilder.builder() + .name("issue270") + .code("issue270") + .addField("name", "name", DataType.STRING) + .addField("days", "days", DataType.INTEGER) + .build(); + } + + private Map data() { + return Map.of("name", "lorne", "days", 1); + } + + private FormFieldPermissionStrategy perm() { + return new FormFieldPermissionStrategy(FormFieldPermissionsBuilder.builder() + .addPermission("issue270", "name", PermissionType.WRITE) + .addPermission("issue270", "days", PermissionType.WRITE) + .build()); + } + + private StartNode startNode() { + return StartNode.builder() + .strategies(NodeStrategyBuilder.builder() + .addStrategy(perm()) + .build()) + .build(); + } + + private ApprovalNode approvalNode(String name, String operatorIds, + MultiOperatorAuditStrategy auditStrategy, boolean withReturn) { + NodeStrategyBuilder strategyBuilder = NodeStrategyBuilder.builder() + .addStrategy(perm()) + .addStrategy(new OperatorLoadStrategy( + FlowGroovyScriptFactory.createOperatorLoadScript("def run(request){return " + operatorIds + "}") + .getKey())); + if (auditStrategy != null) { + strategyBuilder.addStrategy(auditStrategy); + } + ActionBuilder actionBuilder = ActionBuilder.builder().addAction(PassAction.defaultAction()); + if (withReturn) { + actionBuilder.addAction(ReturnAction.defaultAction()); + } + return ApprovalNode.builder() + .name(name) + .strategies(strategyBuilder.build()) + .actions(actionBuilder.build()) + .build(); + } + + private Workflow saveWorkflow(User creator, IFlowNode... nodes) { + WorkflowBuilder builder = WorkflowBuilder.builder() + .title("issue270") + .code("issue270") + .createdOperator(creator) + .form(form()); + for (IFlowNode node : nodes) { + builder.addNode(node); + } + Workflow workflow = builder.build(); + factory.workflowService.saveWorkflow(workflow); + return workflow; + } + + // ==================== 操作与断言 ==================== + + private FlowRecord create(Workflow workflow, User operator, Map data) { + List startActions = workflow.getStartNode().actionManager().getActions(); + FlowCreateRequest createRequest = new FlowCreateRequest(); + createRequest.setWorkCode(workflow.getCode()); + createRequest.setFormData(data); + createRequest.setActionId(startActions.get(0).id()); + createRequest.setOperatorId(operator.getUserId()); + factory.flowService.create(createRequest); + return todoOf(operator, workflow.getStartNode()); + } + + private void startAndSubmit(Workflow workflow, StartNode startNode, User user, Map data) { + create(workflow, user, data); + pass(todoOf(user, startNode), startNode, user, data); + } + + private void pass(FlowRecord record, IFlowNode node, User operator, Map data) { + IFlowAction action = node.actionManager().getActions().stream() + .filter(item -> ActionType.PASS.name().equals(item.type())) + .findFirst().orElseThrow(); + flowAction(record, operator, action, data, "同意"); + } + + private void returnTo(FlowRecord record, IFlowNode node, User operator, + IFlowNode backNode, Map data) { + IFlowAction action = node.actionManager().getActions().stream() + .filter(item -> ActionType.RETURN.name().equals(item.type())) + .findFirst().orElseThrow(); + FlowActionRequest request = new FlowActionRequest(); + request.setFormData(data); + request.setRecordId(record.getId()); + FlowAdviceBody adviceBody = new FlowAdviceBody(action.id(), "退回", operator.getUserId()); + adviceBody.setBackNodeId(backNode.getId()); + request.setAdvice(adviceBody); + factory.flowService.action(request); + } + + private void flowAction(FlowRecord record, User operator, IFlowAction action, + Map data, String advice) { + FlowActionRequest request = new FlowActionRequest(); + request.setFormData(data); + request.setRecordId(record.getId()); + request.setAdvice(new FlowAdviceBody(action.id(), advice, operator.getUserId())); + factory.flowService.action(request); + } + + private FlowContent detail(FlowRecord record, User operator) { + return factory.flowService.detail(new FlowDetailRequest(record.getId(), operator.getUserId())); + } + + private List backNodeIds(FlowContent detail) { + return detail.getBackNodes().stream().map(NodeOption::getId).toList(); + } + + private List backNodeNames(FlowContent detail) { + return detail.getBackNodes().stream().map(NodeOption::getName).toList(); + } + + private FlowRecord todoOf(User user, IFlowNode node) { + List list = factory.flowRecordRepository.findTodoByOperator(user.getUserId()).stream() + .filter(record -> node.getId().equals(record.getNodeId())) + .toList(); + assertEquals(1, list.size(), user.getName() + " 在 " + node.getName() + " 应有且仅有一条待办"); + return list.get(0); + } +} From d31e03211401a0c719e7750997f2ab56ac87cfa8 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Mon, 16 Nov 2026 22:15:18 +0800 Subject: [PATCH 2/6] =?UTF-8?q?feat:=20=E5=B7=B2=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E6=B5=81=E7=A8=8B=E6=94=AF=E6=8C=81=E4=BA=8C=E6=AC=A1=E5=8F=91?= =?UTF-8?q?=E8=B5=B7=20(framework=20+=20infra=20+=20api)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 FlowReissueService:仅流程管理员可对已正常完成(FINISH)的流程执行二次发起 - 复制源流程表单数据通过标准创建流程重新发起,新流程停在开始节点成为原发起人的待办, 不自动提交;源流程记录、待办与历史记录不做任何改写 - 新增关系记录 FlowReissueRecord / t_flow_record_reissue 及仓储(JPA + Mock)与达梦序列 - 新增 FlowRecordReissueEvent,供业务方同步已落库数据状态 - 详情接口新增 reissue 标识,新增 POST /api/cmd/record/reissue - 补充单元测试与集成文档 Closes #272 --- docs/Integration/auto-configuration.md | 4 +- docs/Integration/repository-integration.md | 5 +- .../src/main/resources/sql/dm-sequences.sql | 13 + .../flow/context/RepositoryHolderContext.java | 10 +- .../flow/domain/FlowReissueRecord.java | 95 +++++ .../flow/event/FlowRecordReissueEvent.java | 34 ++ .../flow/exception/FlowStateException.java | 10 + .../flow/mock/MockRepositoryHolder.java | 2 + .../FlowReissueRepositoryMockImpl.java | 44 ++ .../flow/pojo/request/FlowReissueRequest.java | 53 +++ .../flow/pojo/response/FlowContent.java | 7 + .../repository/FlowReissueRepository.java | 42 ++ .../codingapi/flow/service/FlowService.java | 16 + .../flow/service/impl/FlowDetailService.java | 2 + .../flow/service/impl/FlowReissueService.java | 192 +++++++++ .../flow/session/IRepositoryHolder.java | 6 + .../factory/CopyOnReadFlowServiceFactory.java | 3 +- .../flow/factory/MyFlowServiceFactory.java | 5 +- .../flow/service/FlowReissueServiceTest.java | 382 ++++++++++++++++++ .../api/controller/FlowRecordController.java | 13 + .../flow/infra/AutoConfiguration.java | 5 + .../convert/FlowReissueRecordConvertor.java | 72 ++++ .../infra/entity/FlowReissueRecordEntity.java | 98 +++++ .../FlowReissueRecordEntityRepository.java | 36 ++ .../impl/FlowReissueRepositoryImpl.java | 55 +++ .../FlowReissueRecordConvertorTest.java | 56 +++ .../com/codingapi/flow/AutoConfiguration.java | 2 + .../RepositoryHolderContextRegister.java | 4 +- 28 files changed, 1257 insertions(+), 9 deletions(-) create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/domain/FlowReissueRecord.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReissueEvent.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowReissueRepositoryMockImpl.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowReissueRequest.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/repository/FlowReissueRepository.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowReissueService.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowReissueServiceTest.java create mode 100644 flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowReissueRecordConvertor.java create mode 100644 flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowReissueRecordEntity.java create mode 100644 flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/jpa/FlowReissueRecordEntityRepository.java create mode 100644 flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowReissueRepositoryImpl.java create mode 100644 flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowReissueRecordConvertorTest.java diff --git a/docs/Integration/auto-configuration.md b/docs/Integration/auto-configuration.md index 99b4fac6..ed34ff7f 100644 --- a/docs/Integration/auto-configuration.md +++ b/docs/Integration/auto-configuration.md @@ -18,7 +18,7 @@ | `NodeViewJavaScriptCacheContextRegister` | **`NodeViewJavaScriptRepository`** | 构造器内执行 `NodeViewJavaScriptCacheContext.getInstance().setNodeViewJavaScriptRepository(repo)`(15 分钟缓存上下文) | | `GatewayContextRegister` | **`FlowOperatorGateway`** | 把操作人网关灌入 `GatewayContext` 单例(`InitializingBean`) | | `FlowScriptContextRegister` | `ApplicationContext` + **`FlowOperatorGateway`** + `FlowRecordRepository` | 给 `FlowScriptContext` 单例设置 `IBeanFactory`(转发 Spring 容器,脚本 `$bind` 依赖) | -| `RepositoryHolderContextRegister` | `WorkflowService` + `FlowRecordService` + 5 个仓储 + `GatewayContextRegister` | 把 7 个依赖灌入 `RepositoryHolderContext` 单例(`InitializingBean`) | +| `RepositoryHolderContextRegister` | `WorkflowService` + `FlowRecordService` + 6 个仓储 + `GatewayContextRegister` | 把 8 个依赖灌入 `RepositoryHolderContext` 单例(`InitializingBean`) | | `FlowRecordService` | `FlowTodoRecordRepository` + `FlowTodoMergeRepository` + `FlowRecordRepository` | 记录服务 Bean | | `WorkflowService` | `WorkflowVersionRepository` + `WorkflowRepository` + `WorkflowRuntimeRepository` | 流程设计服务 Bean | | `FlowService` | `RepositoryHolderContextRegister`(仅保证顺序) | `new FlowService(RepositoryHolderContext.getInstance())`,业务入口 | @@ -42,7 +42,7 @@ public void afterPropertiesSet() { workflowService, flowRecordService, parallelBranchRepository, delayTaskRepository, urgeIntervalRepository, flowOperatorAssignmentRepository, - subProcessRepository); + subProcessRepository, flowReissueRepository); } // FlowScriptContextRegister diff --git a/docs/Integration/repository-integration.md b/docs/Integration/repository-integration.md index 88da4a50..42dec50f 100644 --- a/docs/Integration/repository-integration.md +++ b/docs/Integration/repository-integration.md @@ -194,6 +194,7 @@ public interface UrgeIntervalRepository { | `UrgeIntervalEntity` | `t_flow_urge_interval` | | `FlowOperatorAssignmentEntity` | `t_flow_operator_assignment` | | `SubProcessRecordEntity` | `t_flow_sub_process_record` | +| `FlowReissueRecordEntity` | `t_flow_record_reissue`(已完成流程二次发起关系) | Spring Data 仓储接口位于 `jpa/` 包,全部继承外部 `FastRepository`(来自 `springboot-starter-data-fast`)。 @@ -233,7 +234,7 @@ public class GroovyScriptRepositoryImpl implements GroovyScriptRepository, Initi ## 6. 替换存储 - **引入 `flow-engine-starter-infra`**:开箱即用(推荐)。 -- **不引入 infra**:自行实现 11 个仓储接口 + `NodeViewJavaScriptRepository` 为 Spring Bean 即可。starter 的 `RepositoryHolderContextRegister` 会自动注入。framework 测试包(`src/test/java/com/codingapi/flow/repository/`)提供了一套内存实现可作参考。 +- **不引入 infra**:自行实现 12 个仓储接口 + `NodeViewJavaScriptRepository` 为 Spring Bean 即可。starter 的 `RepositoryHolderContextRegister` 会自动注入。framework 测试包(`src/test/java/com/codingapi/flow/repository/`)提供了一套内存实现可作参考。 ## 7. 离线/最小装配(脱离 Spring) @@ -245,7 +246,7 @@ RepositoryHolderContext.getInstance().register( workflowService, flowRecordService, parallelBranchRepository, delayTaskRepository, urgeIntervalRepository, flowOperatorAssignmentRepository, - subProcessRepository); + subProcessRepository, flowReissueRepository); // 2. 注册操作人网关 GatewayContext.getInstance().setFlowOperatorGateway(userGateway); ``` \ No newline at end of file diff --git a/flow-engine-example/src/main/resources/sql/dm-sequences.sql b/flow-engine-example/src/main/resources/sql/dm-sequences.sql index 0c4b20bd..f5ca5220 100644 --- a/flow-engine-example/src/main/resources/sql/dm-sequences.sql +++ b/flow-engine-example/src/main/resources/sql/dm-sequences.sql @@ -6,6 +6,7 @@ -- t_flow_todo_record -> t_flow_todo_record_seq -- t_flow_todo_marge -> t_flow_todo_marge_seq -- t_flow_sub_process_record-> t_flow_sub_process_record_seq +-- t_flow_record_reissue -> t_flow_record_reissue_seq -- -- 序列名 / 步长 与实体 @SequenceGenerator(sequenceName=..., allocationSize=50) 严格一致, -- 请勿修改,否则 hibernate 会在 insert 时报“无法解析的成员访问表达式[...NEXTVAL]”或出现主键重复。 @@ -70,5 +71,17 @@ BEGIN END; EXECUTE IMMEDIATE 'CREATE SEQUENCE t_flow_sub_process_record_seq INCREMENT BY 50 START WITH ' || v_start; END IF; + + -- ---------- 5. t_flow_record_reissue_seq ---------- + SELECT COUNT(*) INTO v_cnt FROM all_sequences + WHERE sequence_name = 'T_FLOW_RECORD_REISSUE_SEQ' AND sequence_owner = USER; + IF v_cnt = 0 THEN + BEGIN + SELECT NVL(MAX(id), 0) + 1 INTO v_start FROM t_flow_record_reissue; + EXCEPTION WHEN OTHERS THEN + v_start := 1; + END; + EXECUTE IMMEDIATE 'CREATE SEQUENCE t_flow_record_reissue_seq INCREMENT BY 50 START WITH ' || v_start; + END IF; END; / \ No newline at end of file diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/context/RepositoryHolderContext.java b/flow-engine-framework/src/main/java/com/codingapi/flow/context/RepositoryHolderContext.java index 47577af6..079e7b38 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/context/RepositoryHolderContext.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/context/RepositoryHolderContext.java @@ -8,6 +8,7 @@ import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.repository.DelayTaskRepository; import com.codingapi.flow.repository.FlowOperatorAssignmentRepository; +import com.codingapi.flow.repository.FlowReissueRepository; import com.codingapi.flow.repository.ParallelBranchRepository; import com.codingapi.flow.repository.SubProcessRepository; import com.codingapi.flow.repository.UrgeIntervalRepository; @@ -47,6 +48,8 @@ private RepositoryHolderContext() { private FlowOperatorAssignmentRepository flowOperatorAssignmentRepository; @Getter private SubProcessRepository subProcessRepository; + @Getter + private FlowReissueRepository flowReissueRepository; /** * 是否已经注册成功 @@ -58,7 +61,8 @@ public boolean isRegistered() { && flowRecordService != null && urgeIntervalRepository != null && flowOperatorAssignmentRepository != null - && subProcessRepository != null; + && subProcessRepository != null + && flowReissueRepository != null; } @@ -74,7 +78,8 @@ public void register(WorkflowService workflowService, DelayTaskRepository delayTaskRepository, UrgeIntervalRepository urgeIntervalRepository, FlowOperatorAssignmentRepository flowOperatorAssignmentRepository, - SubProcessRepository subProcessRepository) { + SubProcessRepository subProcessRepository, + FlowReissueRepository flowReissueRepository) { this.workflowService = workflowService; this.flowRecordService = flowRecordService; this.parallelBranchRepository = parallelBranchRepository; @@ -82,6 +87,7 @@ public void register(WorkflowService workflowService, this.urgeIntervalRepository = urgeIntervalRepository; this.flowOperatorAssignmentRepository = flowOperatorAssignmentRepository; this.subProcessRepository = subProcessRepository; + this.flowReissueRepository = flowReissueRepository; } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/domain/FlowReissueRecord.java b/flow-engine-framework/src/main/java/com/codingapi/flow/domain/FlowReissueRecord.java new file mode 100644 index 00000000..e725877d --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/domain/FlowReissueRecord.java @@ -0,0 +1,95 @@ +package com.codingapi.flow.domain; + +import lombok.Getter; +import lombok.Setter; + +/** + * 已完成流程的二次发起关系记录。 + * + *

用于记录「哪条已完成的流程记录被二次发起过、新流程是哪一条」,据此可分析出实际被废止的流程。 + * 二次发起不会改写源流程记录:新流程是重新创建的独立流程实例(新的流程id), + * 源流程记录、待办与历史记录全部保持原样可查。

+ */ +@Getter +public class FlowReissueRecord { + + /** + * 主键 + */ + @Setter + private long id; + + /** + * 被二次发起的源流程记录id + */ + private final long sourceRecordId; + + /** + * 被二次发起的源流程id + */ + private final String sourceProcessId; + + /** + * 二次发起产生的新流程记录id + */ + private final long newRecordId; + + /** + * 二次发起产生的新流程id + */ + private final String newProcessId; + + /** + * 流程编码 + */ + private final String workCode; + + /** + * 源流程所处的运行时版本id + */ + private final long workRuntimeId; + + /** + * 执行二次发起的操作人(流程管理员) + */ + private final long operatorId; + + /** + * 执行二次发起的操作人名称 + */ + private final String operatorName; + + /** + * 操作时间(毫秒时间戳) + */ + private final long createTime; + + /** + * 二次发起说明 + */ + private final String advice; + + public FlowReissueRecord(long id, + long sourceRecordId, + String sourceProcessId, + long newRecordId, + String newProcessId, + String workCode, + long workRuntimeId, + long operatorId, + String operatorName, + long createTime, + String advice) { + this.id = id; + this.sourceRecordId = sourceRecordId; + this.sourceProcessId = sourceProcessId; + this.newRecordId = newRecordId; + this.newProcessId = newProcessId; + this.workCode = workCode; + this.workRuntimeId = workRuntimeId; + this.operatorId = operatorId; + this.operatorName = operatorName; + this.createTime = createTime; + this.advice = advice; + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReissueEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReissueEvent.java new file mode 100644 index 00000000..0aceeede --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReissueEvent.java @@ -0,0 +1,34 @@ +package com.codingapi.flow.event; + +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.record.FlowRecord; +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** + * 流程二次发起事件 + *

+ * 仅当流程管理员对已正常完成的流程记录执行二次发起时触发:源流程记录保持不变, + * 新流程以源流程的表单数据重新创建并停在开始节点。业务方可据此调整已落库的业务数据状态。 + */ +@Getter +@AllArgsConstructor +public class FlowRecordReissueEvent implements IFlowEvent { + + /** + * 被二次发起的源流程记录(已完成) + */ + private final FlowRecord sourceRecord; + + /** + * 二次发起产生的新流程记录(开始节点待办) + */ + private final FlowRecord newRecord; + + /** + * 执行二次发起的操作人(流程管理员) + */ + private final IFlowOperator operator; + + private final boolean mock; +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowStateException.java b/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowStateException.java index aac905ea..5012ae5a 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowStateException.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowStateException.java @@ -209,6 +209,16 @@ public static FlowStateException subProcessResetScriptMismatch(int expected, int + "but the original group has %d instances", actual, expected)); } + /** + * Record not support reissue (only a normally finished record can be reissued) + * + * @return exception + */ + public static FlowStateException recordNotSupportReissue() { + return new FlowStateException("state.record.notSupportReissue", + "Flow record is not finished normally, reissue not allowed"); + } + /** * Workflow script not found when executing a node or action * diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/MockRepositoryHolder.java b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/MockRepositoryHolder.java index 4f844639..f1d31875 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/MockRepositoryHolder.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/MockRepositoryHolder.java @@ -38,6 +38,7 @@ public class MockRepositoryHolder implements IRepositoryHolder { private final WorkflowService workflowService; private final FlowOperatorGateway flowOperatorGateway; private final SubProcessRepository subProcessRepository; + private final FlowReissueRepository flowReissueRepository; private final Map> operatorAssignmentCache = new HashMap<>(); public MockRepositoryHolder(FlowOperatorGateway flowOperatorGateway, @@ -50,6 +51,7 @@ public MockRepositoryHolder(FlowOperatorGateway flowOperatorGateway, this.parallelBranchRepository = new ParallelBranchRepositoryMockImpl(); this.urgeIntervalRepository = new UrgeIntervalRepositoryMockImpl(); this.subProcessRepository = new SubProcessRepositoryMockImpl(); + this.flowReissueRepository = new FlowReissueRepositoryMockImpl(); this.workflowRepository = workflowRepository; this.workflowRuntimeRepository = new WorkflowRuntimeRepositoryMockImpl(); this.workflowVersionRepository = new WorkflowVersionRepositoryMockImpl(); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowReissueRepositoryMockImpl.java b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowReissueRepositoryMockImpl.java new file mode 100644 index 00000000..1687f344 --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowReissueRepositoryMockImpl.java @@ -0,0 +1,44 @@ +package com.codingapi.flow.mock.repository; + +import com.codingapi.flow.domain.FlowReissueRecord; +import com.codingapi.flow.repository.FlowReissueRepository; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class FlowReissueRepositoryMockImpl implements FlowReissueRepository { + + private final Map cache = new LinkedHashMap<>(); + private long nextId = 1; + + @Override + public synchronized void save(FlowReissueRecord record) { + if (record.getId() == 0) { + // 使用单调递增 id,避免与已存在的记录主键冲突 + record.setId(nextId++); + } + cache.put(record.getId(), record); + } + + @Override + public synchronized List findBySourceRecordId(long sourceRecordId) { + return cache.values().stream() + .filter(record -> record.getSourceRecordId() == sourceRecordId) + .toList(); + } + + @Override + public synchronized List findBySourceProcessId(String sourceProcessId) { + return cache.values().stream() + .filter(record -> record.getSourceProcessId().equals(sourceProcessId)) + .toList(); + } + + @Override + public synchronized List findByNewProcessId(String newProcessId) { + return cache.values().stream() + .filter(record -> record.getNewProcessId().equals(newProcessId)) + .toList(); + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowReissueRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowReissueRequest.java new file mode 100644 index 00000000..71d95170 --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowReissueRequest.java @@ -0,0 +1,53 @@ +package com.codingapi.flow.pojo.request; + +import com.codingapi.flow.exception.FlowValidationException; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Map; + +/** + * 已完成流程的二次发起请求(独立接口,不属于常规审批动作)。 + * + *

二次发起以「已正常完成的流程记录」为目标:复制源流程的表单数据创建一条全新的流程, + * 新流程停在开始节点成为发起人的待办,由发起人调整数据后重新提交执行。 + * 源流程记录不做任何改写(不作废、不迁移数据)。

+ */ +@Data +@NoArgsConstructor +public class FlowReissueRequest { + + /** + * 被二次发起的源流程记录id(必须是已正常完成的流程记录) + */ + private long sourceRecordId; + + /** + * 操作者(必须是流程管理员) + */ + private long operatorId; + + /** + * 二次发起时使用的表单数据;为空时按源流程记录的表单数据复制 + */ + private Map formData; + + /** + * 二次发起说明 + */ + private String advice; + + public FlowReissueRequest(long sourceRecordId, long operatorId) { + this.sourceRecordId = sourceRecordId; + this.operatorId = operatorId; + } + + public void verify() { + if (sourceRecordId <= 0) { + throw FlowValidationException.required("sourceRecordId"); + } + if (operatorId <= 0) { + throw FlowValidationException.required("operatorId"); + } + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowContent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowContent.java index 2be97fc9..8a935f29 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowContent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowContent.java @@ -203,6 +203,13 @@ public class FlowContent { */ private boolean resetSubProcess; + /** + * 支持二次发起(独立能力标识,非审批动作)。 + *

仅当当前记录已正常完成且操作人为流程管理员时为 true;前端可据此在已办详情中 + * 展示「重新发起」入口,调用 {@code /api/cmd/record/reissue} 接口。

+ */ + private boolean reissue; + /** * 设置操作动作按钮 * diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/repository/FlowReissueRepository.java b/flow-engine-framework/src/main/java/com/codingapi/flow/repository/FlowReissueRepository.java new file mode 100644 index 00000000..7fc71283 --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/repository/FlowReissueRepository.java @@ -0,0 +1,42 @@ +package com.codingapi.flow.repository; + +import com.codingapi.flow.domain.FlowReissueRecord; + +import java.util.List; + +/** + * 已完成流程二次发起关系仓库。 + */ +public interface FlowReissueRepository { + + /** + * 保存二次发起关系记录(新增或更新)。 + * + * @param record 二次发起关系记录 + */ + void save(FlowReissueRecord record); + + /** + * 按源流程记录id查询二次发起关系,按记录id升序。 + * + * @param sourceRecordId 源流程记录id + * @return 二次发起关系记录列表 + */ + List findBySourceRecordId(long sourceRecordId); + + /** + * 按源流程id查询二次发起关系,按记录id升序。 + * + * @param sourceProcessId 源流程id + * @return 二次发起关系记录列表 + */ + List findBySourceProcessId(String sourceProcessId); + + /** + * 按新流程id查询二次发起关系,按记录id升序。 + * + * @param newProcessId 新流程id + * @return 二次发起关系记录列表 + */ + List findByNewProcessId(String newProcessId); +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/FlowService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/FlowService.java index 8a48d60d..9fa0e45e 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/FlowService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/FlowService.java @@ -130,4 +130,20 @@ public void resetSubProcess(FlowSubProcessResetRequest request) { new FlowSubProcessResetService(request, this.repositoryHolder); flowSubProcessResetService.reset(); } + + /** + * 已完成流程二次发起(独立接口,不属于常规审批动作)。 + *

+ * 复制已正常完成的流程记录的表单数据重新创建一条流程,新流程停在开始节点成为发起人的待办, + * 由发起人调整数据后重新提交执行;源流程记录不做任何改写。仅流程管理员可执行。 + * + * @param request 二次发起请求 + * @return 新流程的开始节点记录id + */ + public long reissue(FlowReissueRequest request) { + FlowOperatorLocalThreadCache.getInstance().clear(); + FlowRuntimeScriptLocalCache.getInstance().clear(); + FlowReissueService flowReissueService = new FlowReissueService(request, this.repositoryHolder); + return flowReissueService.reissue(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDetailService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDetailService.java index 10ba61c1..fc9f362e 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDetailService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDetailService.java @@ -92,6 +92,8 @@ public FlowContent detail() { // 子流程重置为独立能力(非审批动作):仅当当前待办位于已开启重置能力、 // 且已汇聚完成的子流程下游时携带标识,由前端自行决定交互呈现 flowContent.setResetSubProcess(FlowSubProcessResetService.canReset(flowRecord, repositoryHolder)); + // 二次发起为独立能力(非审批动作):仅当记录已正常完成且当前操作人为流程管理员时携带标识 + flowContent.setReissue(FlowReissueService.canReissue(flowRecord, currentOperator)); return flowContent; } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowReissueService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowReissueService.java new file mode 100644 index 00000000..5f1b56c2 --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowReissueService.java @@ -0,0 +1,192 @@ +package com.codingapi.flow.service.impl; + +import com.codingapi.flow.action.ActionType; +import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.domain.FlowReissueRecord; +import com.codingapi.flow.event.FlowRecordReissueEvent; +import com.codingapi.flow.exception.FlowNotFoundException; +import com.codingapi.flow.exception.FlowPermissionException; +import com.codingapi.flow.exception.FlowStateException; +import com.codingapi.flow.mock.MockRepositoryHolder; +import com.codingapi.flow.node.IFlowNode; +import com.codingapi.flow.node.nodes.StartNode; +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.pojo.request.FlowCreateRequest; +import com.codingapi.flow.pojo.request.FlowReissueRequest; +import com.codingapi.flow.record.FlowRecord; +import com.codingapi.flow.repository.FlowReissueRepository; +import com.codingapi.flow.service.FlowRecordService; +import com.codingapi.flow.service.WorkflowService; +import com.codingapi.flow.session.IRepositoryHolder; +import com.codingapi.flow.strategy.node.OperatorLoadStrategy; +import com.codingapi.flow.strategy.node.OperatorSelectType; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.runtime.WorkflowRuntime; +import com.codingapi.springboot.framework.event.EventPusher; +import org.springframework.util.StringUtils; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 已完成流程的二次发起服务(独立接口,不属于常规审批动作)。 + * + *

二次发起以「已正常完成(flowState = FINISH)的流程记录」为目标,仅流程管理员可执行。 + * 处理方式为复制源流程记录的表单数据,重新走一遍标准的流程创建过程:新流程拥有独立流程id, + * 创建后停在开始节点成为原发起人的待办,由发起人调整数据后重新提交执行。 + * 源流程记录、待办与历史记录不做任何改写,重发关系通过 {@link FlowReissueRecord} 单独留痕。

+ */ +public class FlowReissueService { + + private final FlowReissueRequest request; + private final IRepositoryHolder repositoryHolder; + private final FlowRecordService flowRecordService; + private final WorkflowService workflowService; + private final FlowReissueRepository reissueRepository; + + public FlowReissueService(FlowReissueRequest request, IRepositoryHolder repositoryHolder) { + this.request = request; + this.repositoryHolder = repositoryHolder; + this.flowRecordService = repositoryHolder.getFlowRecordService(); + this.workflowService = repositoryHolder.getWorkflowService(); + this.reissueRepository = repositoryHolder.getFlowReissueRepository(); + } + + /** + * 判断指定流程记录对当前操作人是否具备二次发起能力。 + * + *

仅「已正常完成」的流程记录且操作人为流程管理员时开放;终止(未通过结束)、 + * 运行中、异常与已删除的流程均不允许二次发起。

+ * + * @param flowRecord 流程记录 + * @param currentOperator 当前操作人 + * @return 是否可二次发起 + */ + public static boolean canReissue(FlowRecord flowRecord, IFlowOperator currentOperator) { + if (flowRecord == null || currentOperator == null) { + return false; + } + return currentOperator.isFlowManager() + && flowRecord.getFlowState() == FlowRecord.SATE_FLOW_FINISH; + } + + /** + * 执行二次发起。 + * + * @return 新流程的开始节点记录id + */ + public long reissue() { + request.verify(); + + FlowRecord sourceRecord = flowRecordService.getFlowRecord(request.getSourceRecordId()); + if (sourceRecord == null) { + throw FlowNotFoundException.record(request.getSourceRecordId()); + } + + IFlowOperator operator = repositoryHolder.getOperatorById(request.getOperatorId()); + if (operator == null) { + throw FlowNotFoundException.operator(request.getOperatorId()); + } + if (!operator.isFlowManager()) { + throw FlowPermissionException.accessDenied("reissue flow record"); + } + if (sourceRecord.getFlowState() != FlowRecord.SATE_FLOW_FINISH) { + throw FlowStateException.recordNotSupportReissue(); + } + + WorkflowRuntime workflowRuntime = workflowService.getWorkflowRuntime(sourceRecord.getWorkRuntimeId()); + if (workflowRuntime == null) { + throw FlowNotFoundException.workflow(sourceRecord.getWorkRuntimeId() + " not found"); + } + // 运行时快照不携带启用状态,流程是否被禁用交由创建环节按最新流程定义校验 + Workflow workflow = workflowRuntime.toWorkflow(); + + // 新流程沿用源流程的发起人,二次发起后的待办回到发起人,由发起人调整数据后重新提交 + long initiatorId = sourceRecord.getCreateOperatorId(); + if (repositoryHolder.getOperatorById(initiatorId) == null) { + throw FlowNotFoundException.operator(initiatorId); + } + + FlowCreateRequest createRequest = this.buildCreateRequest(workflow, sourceRecord); + long newRecordId = repositoryHolder.createFlowService().create(createRequest); + FlowRecord newRecord = flowRecordService.getFlowRecord(newRecordId); + if (newRecord == null) { + throw FlowNotFoundException.record(newRecordId); + } + + FlowReissueRecord reissueRecord = new FlowReissueRecord( + 0, + sourceRecord.getId(), + sourceRecord.getProcessId(), + newRecord.getId(), + newRecord.getProcessId(), + workflow.getCode(), + sourceRecord.getWorkRuntimeId(), + operator.getUserId(), + operator.getName(), + System.currentTimeMillis(), + request.getAdvice()); + reissueRepository.save(reissueRecord); + + boolean mock = repositoryHolder instanceof MockRepositoryHolder; + EventPusher.push(new FlowRecordReissueEvent(sourceRecord, newRecord, operator, mock)); + return newRecordId; + } + + /** + * 构建二次发起的流程创建请求。 + * + *

创建动作用开始节点的保存动作(不存在时退化为开始节点的首个动作), + * 保证新流程创建后停在开始节点成为待办,不会自动提交到下一节点。

+ */ + private FlowCreateRequest buildCreateRequest(Workflow workflow, FlowRecord sourceRecord) { + StartNode startNode = (StartNode) workflow.getStartNode(); + IFlowAction action = startNode.actionManager().getActionByType(ActionType.SAVE.name()); + if (action == null) { + action = startNode.actionManager().getFirstAction(); + } + + FlowCreateRequest createRequest = new FlowCreateRequest(); + createRequest.setWorkCode(workflow.getCode()); + createRequest.setActionId(action.id()); + createRequest.setOperatorId(sourceRecord.getCreateOperatorId()); + createRequest.setFormData(this.loadFormData(sourceRecord)); + // 沿用源流程的自定义标题(如子流程实例区分标题),保持重发前后的业务标识一致 + if (StringUtils.hasText(sourceRecord.getWorkTitle())) { + createRequest.setWorkTitle(sourceRecord.getWorkTitle()); + } + createRequest.setOperatorSelectMap(this.loadOperatorSelectMap(workflow, sourceRecord.getProcessId())); + return createRequest; + } + + /** + * 复制源流程记录的表单数据;请求中提供了表单数据时以其为准。 + */ + private Map loadFormData(FlowRecord sourceRecord) { + Map requestFormData = request.getFormData(); + if (requestFormData != null && !requestFormData.isEmpty()) { + return new HashMap<>(requestFormData); + } + Map sourceFormData = sourceRecord.getFormData(); + return sourceFormData == null ? new HashMap<>() : new HashMap<>(sourceFormData); + } + + /** + * 复制源流程「发起人设定 / 审批人设定」节点的操作人分配,保证重走时人员设定与首次发起一致。 + */ + private Map> loadOperatorSelectMap(Workflow workflow, String sourceProcessId) { + Map> operatorSelectMap = new HashMap<>(); + for (IFlowNode node : workflow.getNodes()) { + OperatorLoadStrategy strategy = node.strategyManager().getStrategy(OperatorLoadStrategy.class); + if (strategy == null || strategy.getSelectType() == OperatorSelectType.SCRIPT) { + continue; + } + List operatorIds = repositoryHolder.findAssignedOperatorIds(sourceProcessId, node.getId()); + if (operatorIds != null && !operatorIds.isEmpty()) { + operatorSelectMap.put(node.getId(), operatorIds); + } + } + return operatorSelectMap; + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/session/IRepositoryHolder.java b/flow-engine-framework/src/main/java/com/codingapi/flow/session/IRepositoryHolder.java index 308db229..9680baa2 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/session/IRepositoryHolder.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/session/IRepositoryHolder.java @@ -5,6 +5,7 @@ import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.record.FlowRecord; +import com.codingapi.flow.repository.FlowReissueRepository; import com.codingapi.flow.repository.SubProcessRepository; import com.codingapi.flow.service.FlowRecordService; import com.codingapi.flow.service.FlowService; @@ -24,6 +25,11 @@ public interface IRepositoryHolder { */ SubProcessRepository getSubProcessRepository(); + /** + * 获取已完成流程二次发起关系仓库。 + */ + FlowReissueRepository getFlowReissueRepository(); + /** * 获取流程设计服务 */ diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/factory/CopyOnReadFlowServiceFactory.java b/flow-engine-framework/src/test/java/com/codingapi/flow/factory/CopyOnReadFlowServiceFactory.java index 7ee3d548..a8c67111 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/factory/CopyOnReadFlowServiceFactory.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/factory/CopyOnReadFlowServiceFactory.java @@ -22,7 +22,8 @@ public CopyOnReadFlowServiceFactory() { flowRecordRepository = new CopyOnReadFlowRecordRepository(); flowRecordService = new FlowRecordService(flowTodoRecordRepository, flowTodoMergeRepository, flowRecordRepository); RepositoryHolderContext.getInstance().register(workflowService, flowRecordService, parallelBranchRepository, - delayTaskRepository, urgeIntervalRepository, flowOperatorAssignmentRepository, subProcessRepository); + delayTaskRepository, urgeIntervalRepository, flowOperatorAssignmentRepository, subProcessRepository, + reissueRepository); repositoryHolder = RepositoryHolderContext.getInstance(); this.flowService = new FlowService(this.repositoryHolder); } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/factory/MyFlowServiceFactory.java b/flow-engine-framework/src/test/java/com/codingapi/flow/factory/MyFlowServiceFactory.java index 2cbd5113..df77a042 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/factory/MyFlowServiceFactory.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/factory/MyFlowServiceFactory.java @@ -23,6 +23,7 @@ public class MyFlowServiceFactory { public UrgeIntervalRepository urgeIntervalRepository; public FlowOperatorAssignmentRepository flowOperatorAssignmentRepository; public SubProcessRepository subProcessRepository; + public FlowReissueRepository reissueRepository; public WorkflowService workflowService; public FlowRecordService flowRecordService; public FlowService flowService; @@ -41,11 +42,13 @@ public MyFlowServiceFactory() { urgeIntervalRepository = new UrgeIntervalRepositoryImpl(); flowOperatorAssignmentRepository = new FlowOperatorAssignmentRepositoryImpl(); subProcessRepository = new com.codingapi.flow.mock.repository.SubProcessRepositoryMockImpl(); + reissueRepository = new com.codingapi.flow.mock.repository.FlowReissueRepositoryMockImpl(); workflowService = new WorkflowService(workflowVersionRepository, workflowRepository, workflowRuntimeRepository); flowRecordService = new FlowRecordService(flowTodoRecordRepository, flowTodoMergeRepository, flowRecordRepository); RepositoryHolderContext.getInstance().register(workflowService, flowRecordService, parallelBranchRepository, - delayTaskRepository, urgeIntervalRepository, flowOperatorAssignmentRepository, subProcessRepository); + delayTaskRepository, urgeIntervalRepository, flowOperatorAssignmentRepository, subProcessRepository, + reissueRepository); repositoryHolder = RepositoryHolderContext.getInstance(); this.flowService = new FlowService(this.repositoryHolder); diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowReissueServiceTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowReissueServiceTest.java new file mode 100644 index 00000000..cbe3eeb0 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowReissueServiceTest.java @@ -0,0 +1,382 @@ +package com.codingapi.flow.service; + +import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.builder.FormFieldPermissionsBuilder; +import com.codingapi.flow.builder.NodeStrategyBuilder; +import com.codingapi.flow.domain.FlowReissueRecord; +import com.codingapi.flow.event.FlowRecordReissueEvent; +import com.codingapi.flow.exception.FlowPermissionException; +import com.codingapi.flow.exception.FlowStateException; +import com.codingapi.flow.factory.MyFlowServiceFactory; +import com.codingapi.flow.form.DataType; +import com.codingapi.flow.form.FlowForm; +import com.codingapi.flow.form.FlowFormBuilder; +import com.codingapi.flow.form.permission.PermissionType; +import com.codingapi.flow.node.IFlowNode; +import com.codingapi.flow.node.nodes.ApprovalNode; +import com.codingapi.flow.node.nodes.EndNode; +import com.codingapi.flow.node.nodes.StartNode; +import com.codingapi.flow.pojo.body.FlowAdviceBody; +import com.codingapi.flow.pojo.request.FlowActionRequest; +import com.codingapi.flow.pojo.request.FlowCreateRequest; +import com.codingapi.flow.pojo.request.FlowDetailRequest; +import com.codingapi.flow.pojo.request.FlowReissueRequest; +import com.codingapi.flow.pojo.response.FlowContent; +import com.codingapi.flow.record.FlowRecord; +import com.codingapi.flow.script.factory.FlowGroovyScriptFactory; +import com.codingapi.flow.service.impl.FlowReissueService; +import com.codingapi.flow.strategy.node.FormFieldPermissionStrategy; +import com.codingapi.flow.strategy.node.OperatorLoadStrategy; +import com.codingapi.flow.user.User; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.WorkflowBuilder; +import com.codingapi.springboot.framework.event.DomainEvent; +import com.codingapi.springboot.framework.event.IEvent; +import com.codingapi.springboot.framework.event.SpringEventInitializer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationEvent; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 已完成流程二次发起场景测试(issue #272)。 + * + *

流程:开始 -> 审批 -> 结束。流程正常走完后,由流程管理员对已完成的流程记录发起 + * 「二次发起」:复制源记录的表单数据创建一条全新流程,新流程停在开始节点成为发起人的待办, + * 源流程记录保持原样不做任何改写,同时写入一条重发关系记录并推送二次发起事件。

+ */ +class FlowReissueServiceTest { + + private static final String FORM_CODE = "reissue-form"; + private static final String WORK_CODE = "reissue-workflow"; + + private MyFlowServiceFactory factory; + private User initiator; + private User approver; + private User manager; + private FlowForm form; + private StartNode start; + private ApprovalNode approval; + + private final List capturedEvents = new ArrayList<>(); + + @BeforeEach + void setUp() throws Exception { + factory = new MyFlowServiceFactory(); + initiator = saveUser(1, "发起人", false); + approver = saveUser(2, "审批人", false); + manager = saveUser(3, "流程管理员", true); + form = FlowFormBuilder.builder() + .name("二次发起测试表单") + .code(FORM_CODE) + .addField("业务内容", "content", DataType.STRING) + .build(); + start = StartNode.builder() + .name("开始节点") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(FormFieldPermissionsBuilder.builder() + .addPermission(FORM_CODE, "content", PermissionType.WRITE) + .build())) + .build()) + .build(); + String operatorScript = "def run(request){return [" + approver.getUserId() + "]}"; + approval = ApprovalNode.builder() + .name("审批节点") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(FormFieldPermissionsBuilder.builder() + .addPermission(FORM_CODE, "content", PermissionType.READ) + .build())) + .addStrategy(new OperatorLoadStrategy( + FlowGroovyScriptFactory.createOperatorLoadScript(operatorScript).getKey())) + .build()) + .build(); + Workflow workflow = WorkflowBuilder.builder() + .title("二次发起测试流程") + .code(WORK_CODE) + .createdOperator(initiator) + .form(form) + .addNode(start) + .addNode(approval) + .addNode(EndNode.builder().name("结束节点").build()) + .build(); + factory.workflowService.saveWorkflow(workflow); + initEventCapture(); + } + + @AfterEach + void resetEventContext() throws Exception { + Class clazz = Class.forName("com.codingapi.springboot.framework.event.DomainEventContext"); + java.lang.reflect.Method getInstance = clazz.getDeclaredMethod("getInstance"); + getInstance.setAccessible(true); + Object instance = getInstance.invoke(null); + Field field = clazz.getDeclaredField("context"); + field.setAccessible(true); + field.set(instance, null); + } + + /** + * 测试目标:流程管理员对已完成流程执行二次发起后,新流程停在开始节点成为发起人的待办。 + * 前置条件:流程已正常走完(flowState = FINISH),操作人为流程管理员。 + * 执行步骤:调用二次发起 → 查看新建记录与源记录。 + * 期望断言:新流程为独立 processId 且处于待办;待办人是原发起人;表单数据与源记录一致; + * 源记录保持已完成、未作废、数据不变。 + */ + @Test + void shouldCreateNewTodoFlowAtStartNodeWhenManagerReissuesFinishedFlow() { + long sourceRecordId = finishFlow("原始数据"); + FlowRecord sourceRecord = factory.flowRecordRepository.get(sourceRecordId); + String sourceProcessId = sourceRecord.getProcessId(); + + long newRecordId = reissue(sourceRecordId, manager, null); + + FlowRecord newRecord = factory.flowRecordRepository.get(newRecordId); + FlowRecord sourceAfter = factory.flowRecordRepository.get(sourceRecordId); + assertAll("二次发起后的新流程与源流程", + () -> assertNotEquals(sourceRecordId, newRecordId, "应创建一条全新的流程记录"), + () -> assertNotEquals(sourceProcessId, newRecord.getProcessId(), "新流程应使用独立流程id"), + () -> assertTrue(newRecord.isTodo(), "新流程应停在开始节点等待提交"), + () -> assertEquals(start.getId(), newRecord.getNodeId(), "新流程应位于开始节点"), + () -> assertEquals(initiator.getUserId(), newRecord.getCurrentOperatorId(), + "待办应回到原发起人"), + () -> assertEquals(initiator.getUserId(), newRecord.getCreateOperatorId(), + "新流程的创建者应沿用原发起人"), + () -> assertEquals("原始数据", newRecord.getFormData().get("content"), + "应复制源流程的表单数据"), + () -> assertEquals(FlowRecord.SATE_FLOW_RUNNING, newRecord.getFlowState()), + () -> assertEquals(FlowRecord.SATE_FLOW_FINISH, sourceAfter.getFlowState(), + "源流程状态不应被改写"), + () -> assertFalse(sourceAfter.isRevoked(), "源流程记录不应被作废"), + () -> assertEquals("原始数据", sourceAfter.getFormData().get("content"), + "源流程表单数据不应被改写")); + } + + /** + * 测试目标:二次发起写入重发关系记录并推送二次发起事件。 + * 前置条件:流程已正常走完,操作人为流程管理员。 + * 执行步骤:调用二次发起 → 查询关系记录与捕获的事件。 + * 期望断言:关系记录关联源记录、新记录、操作人与流程编码;事件携带源记录、新记录与操作人。 + */ + @Test + void shouldRecordReissueRelationAndPushReissueEvent() { + long sourceRecordId = finishFlow("原始数据"); + FlowRecord sourceRecord = factory.flowRecordRepository.get(sourceRecordId); + + long newRecordId = reissueWithAdvice(sourceRecordId, manager, "业务数据有误,重新发起"); + + List relations = factory.reissueRepository.findBySourceRecordId(sourceRecordId); + assertEquals(1, relations.size(), "应写入一条重发关系记录"); + FlowReissueRecord relation = relations.get(0); + FlowRecord newRecord = factory.flowRecordRepository.get(newRecordId); + assertAll("重发关系记录内容", + () -> assertEquals(sourceRecordId, relation.getSourceRecordId()), + () -> assertEquals(sourceRecord.getProcessId(), relation.getSourceProcessId()), + () -> assertEquals(newRecordId, relation.getNewRecordId()), + () -> assertEquals(newRecord.getProcessId(), relation.getNewProcessId()), + () -> assertEquals(WORK_CODE, relation.getWorkCode()), + () -> assertEquals(manager.getUserId(), relation.getOperatorId(), "应记录执行二次发起的管理员"), + () -> assertEquals("业务数据有误,重新发起", relation.getAdvice())); + + FlowRecordReissueEvent event = capturedEvents.stream() + .filter(FlowRecordReissueEvent.class::isInstance) + .map(FlowRecordReissueEvent.class::cast) + .findFirst() + .orElseThrow(() -> new AssertionError("应推送二次发起事件")); + assertAll("二次发起事件内容", + () -> assertEquals(sourceRecordId, event.getSourceRecord().getId()), + () -> assertEquals(newRecordId, event.getNewRecord().getId()), + () -> assertEquals(manager.getUserId(), event.getOperator().getUserId()), + () -> assertFalse(event.isMock())); + } + + /** + * 测试目标:二次发起时允许用请求中的表单数据覆盖复制的数据。 + * 前置条件:流程已正常走完。 + * 执行步骤:携带修正后的表单数据调用二次发起。 + * 期望断言:新流程使用请求中的表单数据,源流程数据保持不变。 + */ + @Test + void shouldUseOverriddenFormDataWhenRequestProvidesIt() { + long sourceRecordId = finishFlow("原始数据"); + + long newRecordId = reissue(sourceRecordId, manager, Map.of("content", "修正后的数据")); + + assertEquals("修正后的数据", + factory.flowRecordRepository.get(newRecordId).getFormData().get("content")); + assertEquals("原始数据", + factory.flowRecordRepository.get(sourceRecordId).getFormData().get("content"), + "源流程表单数据不应被改写"); + } + + /** + * 测试目标:二次发起后的新流程可以正常重新执行一遍。 + * 前置条件:管理员已对已完成流程执行二次发起。 + * 执行步骤:发起人提交新流程 → 审批人审批通过 → 查看新流程状态。 + * 期望断言:新流程正常结束,源流程保持已完成状态。 + */ + @Test + void shouldRunNewFlowAgainAfterReissue() { + long sourceRecordId = finishFlow("原始数据"); + long newRecordId = reissue(sourceRecordId, manager, null); + FlowRecord newStartRecord = factory.flowRecordRepository.get(newRecordId); + + approve(newStartRecord, passAction(start), initiator, newStartRecord.getFormData()); + FlowRecord approvalTodo = todos(approver, approval).get(0); + approve(approvalTodo, passAction(approval), approver, approvalTodo.getFormData()); + + assertAll("新流程重新走完", + () -> assertEquals(FlowRecord.SATE_FLOW_FINISH, + factory.flowRecordRepository.get(approvalTodo.getId()).getFlowState()), + () -> assertEquals(FlowRecord.SATE_FLOW_FINISH, + factory.flowRecordRepository.get(sourceRecordId).getFlowState(), + "源流程仍保持已完成")); + } + + /** + * 测试目标:只有流程管理员可以执行二次发起。 + * 前置条件:流程已正常走完,操作人为普通发起人。 + * 执行步骤:普通用户调用二次发起。 + * 期望断言:抛出权限异常,且不产生新的流程记录。 + */ + @Test + void shouldRejectReissueWhenOperatorIsNotFlowManager() { + long sourceRecordId = finishFlow("原始数据"); + int before = factory.flowRecordRepository.findProcessRecords( + factory.flowRecordRepository.get(sourceRecordId).getProcessId()).size(); + + assertThrows(FlowPermissionException.class, () -> reissue(sourceRecordId, initiator, null)); + assertEquals(before, factory.flowRecordRepository.findProcessRecords( + factory.flowRecordRepository.get(sourceRecordId).getProcessId()).size(), + "被拒绝时不应产生新的流程记录"); + } + + /** + * 测试目标:只有已正常完成的流程才允许二次发起。 + * 前置条件:流程停在开始节点待办(运行中)。 + * 执行步骤:流程管理员对运行中的记录调用二次发起。 + * 期望断言:抛出状态异常。 + */ + @Test + void shouldRejectReissueWhenSourceRecordIsStillRunning() { + long runningRecordId = create(Map.of("content", "运行中数据")); + + assertThrows(FlowStateException.class, () -> reissue(runningRecordId, manager, null)); + } + + /** + * 测试目标:详情接口按「已正常完成 + 流程管理员」下发二次发起标识。 + * 前置条件:流程已正常走完。 + * 执行步骤:分别以流程管理员与普通发起人身份查看已完成流程详情。 + * 期望断言:管理员为 true,普通用户为 false。 + */ + @Test + void shouldExposeReissueFlagOnlyForFlowManagerOnFinishedRecord() { + long sourceRecordId = finishFlow("原始数据"); + + FlowContent managerView = detail(sourceRecordId, manager); + FlowContent initiatorView = detail(sourceRecordId, initiator); + + assertAll("详情接口的二次发起标识", + () -> assertTrue(managerView.isReissue()), + () -> assertFalse(initiatorView.isReissue())); + } + + /** + * 测试目标:终止(未通过结束)的流程不开放二次发起。 + * 前置条件:源记录流程状态为 SATE_FLOW_DONE。 + * 执行步骤:调用 canReissue 判定。 + * 期望断言:返回 false(仅 SATE_FLOW_FINISH 允许)。 + */ + @Test + void shouldNotAllowReissueForTerminatedFlow() { + FlowRecord terminated = Mockito.mock(FlowRecord.class); + Mockito.when(terminated.getFlowState()).thenReturn(FlowRecord.SATE_FLOW_DONE); + + assertFalse(FlowReissueService.canReissue(terminated, manager)); + } + + private long finishFlow(String content) { + Map data = Map.of("content", content); + long recordId = create(data); + approve(factory.flowRecordRepository.get(recordId), passAction(start), initiator, data); + FlowRecord approvalTodo = todos(approver, approval).get(0); + approve(approvalTodo, passAction(approval), approver, approvalTodo.getFormData()); + return recordId; + } + + private long create(Map data) { + FlowCreateRequest request = new FlowCreateRequest(); + request.setWorkCode(WORK_CODE); + request.setOperatorId(initiator.getUserId()); + request.setActionId(passAction(start).id()); + request.setFormData(data); + return factory.flowService.create(request); + } + + private long reissue(long sourceRecordId, User operator, Map formData) { + FlowReissueRequest request = new FlowReissueRequest(sourceRecordId, operator.getUserId()); + request.setFormData(formData); + return factory.flowService.reissue(request); + } + + private long reissueWithAdvice(long sourceRecordId, User operator, String advice) { + FlowReissueRequest request = new FlowReissueRequest(sourceRecordId, operator.getUserId()); + request.setAdvice(advice); + return factory.flowService.reissue(request); + } + + private FlowContent detail(long recordId, User operator) { + return factory.flowService.detail( + new FlowDetailRequest(String.valueOf(recordId), operator.getUserId())); + } + + private void approve(FlowRecord record, IFlowAction action, User operator, Map data) { + FlowActionRequest request = new FlowActionRequest(); + request.setRecordId(record.getId()); + request.setFormData(data); + request.setAdvice(new FlowAdviceBody(action.id(), "同意", operator.getUserId())); + factory.flowService.action(request); + } + + private List todos(User operator, IFlowNode node) { + return factory.flowRecordRepository.findTodoByOperator(operator.getUserId()).stream() + .filter(record -> record.getNodeId().equals(node.getId())) + .toList(); + } + + private IFlowAction passAction(IFlowNode node) { + return node.actionManager().getActions().stream() + .filter(action -> "PASS".equals(action.type())) + .findFirst() + .orElseThrow(); + } + + private User saveUser(long id, String name, boolean manager) { + User user = new User(id, name, manager); + factory.userGateway.save(user); + return user; + } + + private void initEventCapture() throws Exception { + ApplicationContext mockContext = Mockito.mock(ApplicationContext.class); + Mockito.doAnswer(invocation -> { + DomainEvent domainEvent = invocation.getArgument(0); + capturedEvents.add(domainEvent.getEvent()); + return null; + }).when(mockContext).publishEvent(Mockito.any(ApplicationEvent.class)); + new SpringEventInitializer(mockContext).afterPropertiesSet(); + } +} diff --git a/flow-engine-starter-api/src/main/java/com/codingapi/flow/api/controller/FlowRecordController.java b/flow-engine-starter-api/src/main/java/com/codingapi/flow/api/controller/FlowRecordController.java index 3b36fe1c..eeff8b7b 100644 --- a/flow-engine-starter-api/src/main/java/com/codingapi/flow/api/controller/FlowRecordController.java +++ b/flow-engine-starter-api/src/main/java/com/codingapi/flow/api/controller/FlowRecordController.java @@ -126,4 +126,17 @@ public Response resetSubProcess(@RequestBody FlowSubProcessResetRequest request) return Response.buildSuccess(); } + /** + * 已完成流程二次发起(独立接口,不属于常规审批动作)。 + *

仅流程管理员可对已正常完成的流程记录执行,详情数据中的 {@code reissue} 标识字段 + * 表明当前记录是否具备该能力。新流程停在开始节点成为发起人的待办,源流程记录不做改写。

+ */ + @PostMapping("/reissue") + public SingleResponse reissue(@RequestBody FlowReissueRequest request) { + FlowService flowService = this.loadFlowService(); + long operatorId = loadCurrentOperatorId(); + request.setOperatorId(operatorId); + return SingleResponse.of(flowService.reissue(request)); + } + } diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/AutoConfiguration.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/AutoConfiguration.java index 64a49349..4927c922 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/AutoConfiguration.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/AutoConfiguration.java @@ -68,4 +68,9 @@ public SubProcessRepository subProcessRepository(SubProcessRecordEntityRepositor return new SubProcessRepositoryImpl(repository); } + @Bean + public FlowReissueRepository flowReissueRepository(FlowReissueRecordEntityRepository repository) { + return new FlowReissueRepositoryImpl(repository); + } + } diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowReissueRecordConvertor.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowReissueRecordConvertor.java new file mode 100644 index 00000000..5a928652 --- /dev/null +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowReissueRecordConvertor.java @@ -0,0 +1,72 @@ +package com.codingapi.flow.infra.convert; + +import com.codingapi.flow.domain.FlowReissueRecord; +import com.codingapi.flow.infra.entity.FlowReissueRecordEntity; + +/** + * 已完成流程二次发起关系的领域对象与持久化实体互转工具。 + */ +public class FlowReissueRecordConvertor { + + private FlowReissueRecordConvertor() { + } + + /** + * 持久化实体转换为领域对象。 + * + * @param entity 持久化实体 + * @return 领域对象;实体为 null 时返回 null + */ + public static FlowReissueRecord convert(FlowReissueRecordEntity entity) { + if (entity == null) { + return null; + } + return new FlowReissueRecord( + entity.getId(), + entity.getSourceRecordId(), + entity.getSourceProcessId(), + entity.getNewRecordId(), + entity.getNewProcessId(), + entity.getWorkCode(), + entity.getWorkRuntimeId(), + entity.getOperatorId(), + entity.getOperatorName(), + entity.getCreateTime(), + entity.getAdvice()); + } + + /** + * 领域对象转换为持久化实体(新建)。 + * + * @param record 领域对象 + * @return 持久化实体 + */ + public static FlowReissueRecordEntity convert(FlowReissueRecord record) { + FlowReissueRecordEntity entity = new FlowReissueRecordEntity(); + return convert(record, entity); + } + + /** + * 领域对象转换为持久化实体(可复用已有实体)。 + * + * @param record 领域对象 + * @param entity 待填充的持久化实体(记录已持久化时携带主键) + * @return 填充后的持久化实体 + */ + public static FlowReissueRecordEntity convert(FlowReissueRecord record, FlowReissueRecordEntity entity) { + if (record.getId() > 0) { + entity.setId(record.getId()); + } + entity.setSourceRecordId(record.getSourceRecordId()); + entity.setSourceProcessId(record.getSourceProcessId()); + entity.setNewRecordId(record.getNewRecordId()); + entity.setNewProcessId(record.getNewProcessId()); + entity.setWorkCode(record.getWorkCode()); + entity.setWorkRuntimeId(record.getWorkRuntimeId()); + entity.setOperatorId(record.getOperatorId()); + entity.setOperatorName(record.getOperatorName()); + entity.setCreateTime(record.getCreateTime()); + entity.setAdvice(record.getAdvice()); + return entity; + } +} diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowReissueRecordEntity.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowReissueRecordEntity.java new file mode 100644 index 00000000..75a5f5d1 --- /dev/null +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowReissueRecordEntity.java @@ -0,0 +1,98 @@ +package com.codingapi.flow.infra.entity; + +import com.codingapi.flow.domain.FlowReissueRecord; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.Version; +import lombok.Data; + +/** + * 已完成流程二次发起关系持久化实体,对应表 {@code t_flow_record_reissue}。 + * + *

与领域对象 {@link FlowReissueRecord} 一一对应:记录「哪条已完成的流程记录被二次发起过、 + * 新流程是哪一条」,据此可分析出实际被废止的流程。

+ */ +@Data +@Entity +@Table(name = "t_flow_record_reissue") +public class FlowReissueRecordEntity { + + /** + * 主键,由序列生成(替代数据库自增,配合 hibernate 批插降低批量往返) + */ + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "flow_reissue_record_seq") + @SequenceGenerator(name = "flow_reissue_record_seq", sequenceName = "t_flow_record_reissue_seq", allocationSize = 50) + private Long id; + + /** + * 被二次发起的源流程记录id + */ + @Column(nullable = false) + private Long sourceRecordId; + + /** + * 被二次发起的源流程id + */ + @Column(nullable = false) + private String sourceProcessId; + + /** + * 二次发起产生的新流程记录id + */ + @Column(nullable = false) + private Long newRecordId; + + /** + * 二次发起产生的新流程id + */ + @Column(nullable = false) + private String newProcessId; + + /** + * 流程编码 + */ + @Column(nullable = false) + private String workCode; + + /** + * 源流程所处的运行时版本id + */ + @Column(nullable = false) + private Long workRuntimeId; + + /** + * 执行二次发起的操作人(流程管理员) + */ + @Column(nullable = false) + private Long operatorId; + + /** + * 执行二次发起的操作人名称 + */ + @Column + private String operatorName; + + /** + * 操作时间(毫秒时间戳) + */ + @Column(nullable = false) + private Long createTime; + + /** + * 二次发起说明 + */ + @Column + private String advice; + + /** + * 乐观锁版本号(由 JPA {@link Version} 自动维护) + */ + @Version + private Long version; +} diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/jpa/FlowReissueRecordEntityRepository.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/jpa/FlowReissueRecordEntityRepository.java new file mode 100644 index 00000000..f0a8492d --- /dev/null +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/jpa/FlowReissueRecordEntityRepository.java @@ -0,0 +1,36 @@ +package com.codingapi.flow.infra.jpa; + +import com.codingapi.flow.infra.entity.FlowReissueRecordEntity; +import com.codingapi.springboot.fast.jpa.repository.FastRepository; + +import java.util.List; + +/** + * 已完成流程二次发起关系实体的 JPA 仓储接口。 + */ +public interface FlowReissueRecordEntityRepository extends FastRepository { + + /** + * 按源流程记录id查询,按记录id升序。 + * + * @param sourceRecordId 源流程记录id + * @return 二次发起关系实体列表 + */ + List findBySourceRecordIdOrderById(long sourceRecordId); + + /** + * 按源流程id查询,按记录id升序。 + * + * @param sourceProcessId 源流程id + * @return 二次发起关系实体列表 + */ + List findBySourceProcessIdOrderById(String sourceProcessId); + + /** + * 按新流程id查询,按记录id升序。 + * + * @param newProcessId 新流程id + * @return 二次发起关系实体列表 + */ + List findByNewProcessIdOrderById(String newProcessId); +} diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowReissueRepositoryImpl.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowReissueRepositoryImpl.java new file mode 100644 index 00000000..72bdb9fa --- /dev/null +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowReissueRepositoryImpl.java @@ -0,0 +1,55 @@ +package com.codingapi.flow.infra.repository.impl; + +import com.codingapi.flow.domain.FlowReissueRecord; +import com.codingapi.flow.infra.convert.FlowReissueRecordConvertor; +import com.codingapi.flow.infra.entity.FlowReissueRecordEntity; +import com.codingapi.flow.infra.jpa.FlowReissueRecordEntityRepository; +import com.codingapi.flow.repository.FlowReissueRepository; +import lombok.AllArgsConstructor; + +import java.util.List; + +/** + * 已完成流程二次发起关系仓库的 JPA 实现。 + */ +@AllArgsConstructor +public class FlowReissueRepositoryImpl implements FlowReissueRepository { + + private final FlowReissueRecordEntityRepository repository; + + /** + * 保存二次发起关系: + * 已持久化的记录(id 大于 0)更新到已有实体,否则新建实体; + * 保存后回写生成的主键。 + */ + @Override + public void save(FlowReissueRecord record) { + FlowReissueRecordEntity entity = record.getId() > 0 + ? repository.findById(record.getId()).orElseGet(FlowReissueRecordEntity::new) + : new FlowReissueRecordEntity(); + FlowReissueRecordConvertor.convert(record, entity); + repository.save(entity); + record.setId(entity.getId()); + } + + @Override + public List findBySourceRecordId(long sourceRecordId) { + return repository.findBySourceRecordIdOrderById(sourceRecordId).stream() + .map(FlowReissueRecordConvertor::convert) + .toList(); + } + + @Override + public List findBySourceProcessId(String sourceProcessId) { + return repository.findBySourceProcessIdOrderById(sourceProcessId).stream() + .map(FlowReissueRecordConvertor::convert) + .toList(); + } + + @Override + public List findByNewProcessId(String newProcessId) { + return repository.findByNewProcessIdOrderById(newProcessId).stream() + .map(FlowReissueRecordConvertor::convert) + .toList(); + } +} diff --git a/flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowReissueRecordConvertorTest.java b/flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowReissueRecordConvertorTest.java new file mode 100644 index 00000000..d7fd943a --- /dev/null +++ b/flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowReissueRecordConvertorTest.java @@ -0,0 +1,56 @@ +package com.codingapi.flow.infra.convert; + +import com.codingapi.flow.domain.FlowReissueRecord; +import com.codingapi.flow.infra.entity.FlowReissueRecordEntity; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +class FlowReissueRecordConvertorTest { + + /** + * 测试目标:验证二次发起关系记录可在领域对象与持久化对象之间完整往返。 + * 前置条件:持久化对象携带源流程、新流程、操作人等信息。 + * 执行步骤:转换为领域对象,再回写到一个新建的持久化对象。 + * 期望断言:全部业务字段不丢失;回写已有实体时保留原实体与版本号。 + */ + @Test + void shouldRoundTripReissueRecord() { + FlowReissueRecordEntity entity = new FlowReissueRecordEntity(); + entity.setId(10L); + entity.setSourceRecordId(21L); + entity.setSourceProcessId("source-process"); + entity.setNewRecordId(31L); + entity.setNewProcessId("new-process"); + entity.setWorkCode("reissue-workflow"); + entity.setWorkRuntimeId(41L); + entity.setOperatorId(51L); + entity.setOperatorName("流程管理员"); + entity.setCreateTime(1000L); + entity.setAdvice("业务数据有误,重新发起"); + entity.setVersion(7L); + + FlowReissueRecord record = FlowReissueRecordConvertor.convert(entity); + + assertAll("实体转换为领域对象", + () -> assertEquals(10L, record.getId()), + () -> assertEquals(21L, record.getSourceRecordId()), + () -> assertEquals("source-process", record.getSourceProcessId()), + () -> assertEquals(31L, record.getNewRecordId()), + () -> assertEquals("new-process", record.getNewProcessId()), + () -> assertEquals("reissue-workflow", record.getWorkCode()), + () -> assertEquals(41L, record.getWorkRuntimeId()), + () -> assertEquals(51L, record.getOperatorId()), + () -> assertEquals("流程管理员", record.getOperatorName()), + () -> assertEquals(1000L, record.getCreateTime()), + () -> assertEquals("业务数据有误,重新发起", record.getAdvice())); + + FlowReissueRecordEntity converted = FlowReissueRecordConvertor.convert(record, entity); + + assertSame(entity, converted, "回写时应复用已有实体"); + assertEquals(7L, converted.getVersion(), "回写不应覆盖乐观锁版本号"); + assertEquals(record.getNewProcessId(), converted.getNewProcessId()); + } +} diff --git a/flow-engine-starter/src/main/java/com/codingapi/flow/AutoConfiguration.java b/flow-engine-starter/src/main/java/com/codingapi/flow/AutoConfiguration.java index 7dbaab48..3f38be72 100644 --- a/flow-engine-starter/src/main/java/com/codingapi/flow/AutoConfiguration.java +++ b/flow-engine-starter/src/main/java/com/codingapi/flow/AutoConfiguration.java @@ -53,6 +53,7 @@ public RepositoryHolderContextRegister repositoryHolderContextRegister( UrgeIntervalRepository urgeIntervalRepository, FlowOperatorAssignmentRepository flowOperatorAssignmentRepository, SubProcessRepository subProcessRepository, + FlowReissueRepository flowReissueRepository, GatewayContextRegister gatewayContextRegister ) { return new RepositoryHolderContextRegister( @@ -63,6 +64,7 @@ public RepositoryHolderContextRegister repositoryHolderContextRegister( urgeIntervalRepository, flowOperatorAssignmentRepository, subProcessRepository, + flowReissueRepository, gatewayContextRegister ); } diff --git a/flow-engine-starter/src/main/java/com/codingapi/flow/register/RepositoryHolderContextRegister.java b/flow-engine-starter/src/main/java/com/codingapi/flow/register/RepositoryHolderContextRegister.java index bb23a957..330cb2ab 100644 --- a/flow-engine-starter/src/main/java/com/codingapi/flow/register/RepositoryHolderContextRegister.java +++ b/flow-engine-starter/src/main/java/com/codingapi/flow/register/RepositoryHolderContextRegister.java @@ -18,6 +18,7 @@ public class RepositoryHolderContextRegister implements InitializingBean { private final UrgeIntervalRepository urgeIntervalRepository; private final FlowOperatorAssignmentRepository flowOperatorAssignmentRepository; private final SubProcessRepository subProcessRepository; + private final FlowReissueRepository flowReissueRepository; private final GatewayContextRegister gatewayContextRegister; @Override @@ -30,7 +31,8 @@ public void afterPropertiesSet() throws Exception { delayTaskRepository, urgeIntervalRepository, flowOperatorAssignmentRepository, - subProcessRepository + subProcessRepository, + flowReissueRepository ); } } From d5376c4d80f66445020a25d97a5d37fc780cf2ca Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Mon, 16 Nov 2026 22:48:15 +0800 Subject: [PATCH 3/6] =?UTF-8?q?feat:=20=E6=B5=81=E7=A8=8B=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E7=BB=9F=E4=B8=80=E8=B5=B0=20FlowEventPublisher?= =?UTF-8?q?=EF=BC=8C=E4=BF=9D=E8=AF=81=E6=8F=90=E4=BA=A4=E5=90=8E=E6=8A=95?= =?UTF-8?q?=E9=80=92=E4=B8=8E=E6=8C=89=E6=B5=81=E7=A8=8B=E4=B8=B2=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 IFlowEventPublisher SPI 与 FlowEventPublisher 门面;IFlowEvent 增加 eventKey() 分区键(默认 processId) - 引擎内全部事件推送点由 EventPusher 收敛到 FlowEventPublisher,未注册实现时自动回退,行为不变 - starter 新增 SpringFlowEventPublisher:事务 afterCommit 投递(回滚不投递)、按 eventKey 分区单线程串行、 同步执行 handler 以获得确定顺序、单 handler 异常不影响后续事件 - 新增配置 codingapi.flow.event.ordered(默认开启) - 补充发布门面与发布器单元测试,更新事件集成文档与 AGENTS.md Closes #274 --- AGENTS.md | 2 +- docs/Integration/event-integration.md | 58 +++-- .../flow/action/actions/AddAuditAction.java | 4 +- .../flow/action/actions/DelegateAction.java | 4 +- .../flow/action/actions/PassAction.java | 4 +- .../action/actions/ReduceAuditAction.java | 4 +- .../flow/action/actions/RejectAction.java | 4 +- .../flow/action/actions/ReturnAction.java | 4 +- .../flow/action/actions/TransferAction.java | 4 +- .../flow/event/FlowEventPublisher.java | 56 +++++ .../flow/event/FlowRecordDeleteEvent.java | 8 + .../flow/event/FlowRecordDoneEvent.java | 8 +- .../flow/event/FlowRecordFinishEvent.java | 8 + .../event/FlowRecordReduceAuditEvent.java | 8 + .../flow/event/FlowRecordRevokeEvent.java | 8 + .../flow/event/FlowRecordStartEvent.java | 8 + .../flow/event/FlowRecordTodoEvent.java | 8 + .../flow/event/FlowRecordUrgeEvent.java | 8 + .../flow/event/FlowSubProcessResetEvent.java | 8 + .../com/codingapi/flow/event/IFlowEvent.java | 11 + .../flow/event/IFlowEventPublisher.java | 22 ++ .../codingapi/flow/node/BaseAuditNode.java | 4 +- .../codingapi/flow/node/nodes/EndNode.java | 4 +- .../flow/service/impl/FlowCreateService.java | 4 +- .../flow/service/impl/FlowDeleteService.java | 4 +- .../flow/service/impl/FlowRevokeService.java | 4 +- .../impl/FlowSubProcessResetService.java | 6 +- .../impl/FlowSubProcessResultService.java | 4 +- .../flow/service/impl/FlowUrgeService.java | 4 +- .../flow/event/FlowEventPublisherTest.java | 133 ++++++++++ .../com/codingapi/flow/AutoConfiguration.java | 15 ++ .../flow/event/SpringFlowEventPublisher.java | 140 +++++++++++ .../event/SpringFlowEventPublisherTest.java | 238 ++++++++++++++++++ 33 files changed, 761 insertions(+), 48 deletions(-) create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowEventPublisher.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/event/IFlowEventPublisher.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/event/FlowEventPublisherTest.java create mode 100644 flow-engine-starter/src/main/java/com/codingapi/flow/event/SpringFlowEventPublisher.java create mode 100644 flow-engine-starter/src/test/java/com/codingapi/flow/event/SpringFlowEventPublisherTest.java diff --git a/AGENTS.md b/AGENTS.md index 3949a874..dd8895a4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -64,7 +64,7 @@ REST 层通过请求参数 `mockKey` 分流到 Mock 实例(见 `FlowRecordCont ### 事件(IFlowEvent + EventPusher) -9 种事件:开始 / 待办 / 已办 / 完成 / 催办 / 撤销(`FlowRecordRevokeEvent`)/ 删除(`FlowRecordDeleteEvent`)/ 子流程重置(`FlowSubProcessResetEvent`)/ 减签(`FlowRecordReduceAuditEvent`)。操作完成后用 `EventPusher.push(event)` 推送;记录类事件携带 `FlowRecord` + `mock` 标记,重置事件携带新旧聚合组快照。外部可用 Spring `@EventListener` 订阅。 +9 种事件:开始 / 待办 / 已办 / 完成 / 催办 / 撤销(`FlowRecordRevokeEvent`)/ 删除(`FlowRecordDeleteEvent`)/ 子流程重置(`FlowSubProcessResetEvent`)/ 减签(`FlowRecordReduceAuditEvent`)。操作完成后用 `FlowEventPublisher.push(event)` 推送(**禁止**直接调用 `EventPusher`);引入 starter 时由 `SpringFlowEventPublisher` 保证「事务提交后投递 + 按 `eventKey()`(默认 processId)分区串行」,未注册实现时自动回退 `EventPusher`。记录类事件携带 `FlowRecord` + `mock` 标记,重置事件携带新旧聚合组快照。外部可用 Spring `@EventListener` 订阅。 ### API 模块划分 diff --git a/docs/Integration/event-integration.md b/docs/Integration/event-integration.md index 68a27679..ce9527a2 100644 --- a/docs/Integration/event-integration.md +++ b/docs/Integration/event-integration.md @@ -76,7 +76,23 @@ public class FlowRecordUrgeEvent implements IFlowEvent { - 并行:`getParallelId()`、`getParallelBranchNodeId()`、`getParallelBranchTotal()` - 时间:`getCreateTime()`、`getUpdateTime()`、`getFinishTime()`、`getTimeoutTime()` -## 2. 推送:`EventPusher` +## 2. 推送:`FlowEventPublisher`(引擎内统一入口) + +引擎内部**不再直接调用** `EventPusher`,统一走 `com.codingapi.flow.event.FlowEventPublisher`: + +```java +FlowEventPublisher.push(new FlowRecordStartEvent(flowRecord, session.isMock())); +``` + +`FlowEventPublisher` 是门面,行为取决于是否注册了发布器实现(`IFlowEventPublisher`): + +| 场景 | 行为 | +|---|---| +| 引入 `flow-engine-starter`(默认) | 由 `SpringFlowEventPublisher` 投递:**事务提交后**才投递、按 `IFlowEvent.eventKey()`(默认流程id)分区**串行**,见 4.5 | +| 仅使用 framework / 单元测试 | **回退**为 `EventPusher.push`,与旧版本行为一致 | +| 配置 `codingapi.flow.event.ordered=false` | 不注册实现,回退为 `EventPusher.push` | + +底层 `EventPusher`(回退路径)语义: ```java package com.codingapi.springboot.framework.event; @@ -96,12 +112,6 @@ public class EventPusher { } ``` -调用方式(引擎内部统一使用单参形式): - -```java -EventPusher.push(new FlowRecordStartEvent(flowRecord, session.isMock())); -``` - ### 引擎内推送事件的位置 | 位置 | 推送内容 | @@ -184,17 +194,22 @@ public class MyFlowRecordUrgeEventHandler implements IHandler ApplicationHandlerUtils.handler(event)) - 同步:内联执行 - → 按 order() 排序,按泛型匹配执行所有 IHandler +业务代码 → FlowEventPublisher.push(event) + → SpringFlowEventPublisher.push + → 有事务:登记 TransactionSynchronization#afterCommit(提交后才投递;回滚不投递) + → 无事务:立即投递 + → 按 eventKey(默认 processId)散列到单线程分区(同流程串行、跨流程并行) + → ApplicationContext.publishEvent(new DomainEvent(event, sync=true, traceId)) + → SpringDefaultEventHandler.dispatch(同步分支) + → 在分区线程内按 order() 排序,按泛型匹配执行所有 IHandler + → handler 异常仅记录日志,不阻塞同分区后续事件 ``` +回退路径(未注册发布器):`EventPusher.push → DomainEventContext.push → ...` 与旧版本一致。 + ### 4.1 循环事件检测 - 同一 traceId 内,同类事件再次 push 会抛 `EventLoopException`(防止事件→动作→事件的无限循环)。 @@ -214,6 +229,19 @@ public class MyFlowRecordUrgeEventHandler implements IHandler !isEndNodeTodoEvent(event)) - .forEach(EventPusher::push); + .forEach(FlowEventPublisher::push); } /** diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReduceAuditAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReduceAuditAction.java index c2ecbec0..76cb04f2 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReduceAuditAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReduceAuditAction.java @@ -18,7 +18,7 @@ import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; import com.codingapi.flow.strategy.node.MultiOperatorAuditStrategy; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import org.springframework.util.StringUtils; import java.util.ArrayList; @@ -155,7 +155,7 @@ public void run(FlowSession flowSession) { // 循序审批的链路由通过时的「最近一条更大 nodeOrder」激活保证,撤销中间记录不需要额外补链 repositoryHolder.saveRecords(saveRecords); - flowEvents.forEach(EventPusher::push); + flowEvents.forEach(FlowEventPublisher::push); } /** diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/RejectAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/RejectAction.java index b60cdfc7..ca7db511 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/RejectAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/RejectAction.java @@ -15,7 +15,7 @@ import com.codingapi.flow.script.action.ActionRejectScript; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import lombok.Getter; import java.util.ArrayList; @@ -129,7 +129,7 @@ public void run(FlowSession flowSession) { // 结束节点的虚拟记录不是真实业务待办,其 Todo 事件推送业务订阅方前需拦截 flowEvents.stream() .filter(event -> !isEndNodeTodoEvent(event)) - .forEach(EventPusher::push); + .forEach(FlowEventPublisher::push); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReturnAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReturnAction.java index e0096645..268cda80 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReturnAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReturnAction.java @@ -12,7 +12,7 @@ import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import java.util.ArrayList; import java.util.List; @@ -78,7 +78,7 @@ public void run(FlowSession flowSession) { repositoryHolder.saveRecords(recordList); - flowEvents.forEach(EventPusher::push); + flowEvents.forEach(FlowEventPublisher::push); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/TransferAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/TransferAction.java index 744ac54b..8d2a085b 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/TransferAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/TransferAction.java @@ -15,7 +15,7 @@ import com.codingapi.flow.script.node.OperatorLoadScript; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import org.springframework.util.StringUtils; import java.util.ArrayList; @@ -107,7 +107,7 @@ public void run(FlowSession flowSession) { } repositoryHolder.saveRecords(recordList); - flowEvents.forEach(EventPusher::push); + flowEvents.forEach(FlowEventPublisher::push); } @Override diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowEventPublisher.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowEventPublisher.java new file mode 100644 index 00000000..fde0104e --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowEventPublisher.java @@ -0,0 +1,56 @@ +package com.codingapi.flow.event; + +import com.codingapi.springboot.framework.event.EventPusher; + +/** + * 流程事件发布门面。 + * + *

引擎内统一使用该门面推送事件(不再直接调用 {@code EventPusher.push}):

+ *
    + *
  • 已注册 {@link IFlowEventPublisher}(如 starter 提供的实现)时,交由实现投递, + * 可获得「事务提交后投递 + 按流程串行」的语义;
  • + *
  • 未注册时回退为 {@code EventPusher.push},与旧版本行为完全一致 + * (仅使用 framework、单元测试等场景)。
  • + *
+ */ +public class FlowEventPublisher { + + private static volatile IFlowEventPublisher publisher; + + private FlowEventPublisher() { + } + + /** + * 注册事件发布器实现(由 starter 初始化时调用)。 + * + * @param eventPublisher 事件发布器 + */ + public static void register(IFlowEventPublisher eventPublisher) { + publisher = eventPublisher; + } + + /** + * 注销事件发布器实现,恢复为直接调用 {@code EventPusher}(测试或关闭能力时使用)。 + * + * @param eventPublisher 待注销的事件发布器,仅当其为当前实现时才生效 + */ + public static void unregister(IFlowEventPublisher eventPublisher) { + if (publisher == eventPublisher) { + publisher = null; + } + } + + /** + * 推送流程事件。 + * + * @param event 流程事件 + */ + public static void push(IFlowEvent event) { + IFlowEventPublisher eventPublisher = publisher; + if (eventPublisher == null) { + EventPusher.push(event); + return; + } + eventPublisher.push(event); + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordDeleteEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordDeleteEvent.java index cb6d1a6a..ba0bebf4 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordDeleteEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordDeleteEvent.java @@ -16,4 +16,12 @@ public class FlowRecordDeleteEvent implements IFlowEvent { private final FlowRecord flowRecord; private final boolean mock; + + /** + * 事件分区键:同一流程内的事件按顺序投递 + */ + @Override + public String eventKey() { + return flowRecord.getProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordDoneEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordDoneEvent.java index 642d6ef1..f8ce2d34 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordDoneEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordDoneEvent.java @@ -15,6 +15,12 @@ public class FlowRecordDoneEvent implements IFlowEvent { private final boolean mock; - + /** + * 事件分区键:同一流程内的事件按顺序投递 + */ + @Override + public String eventKey() { + return flowRecord.getProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordFinishEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordFinishEvent.java index 6db604ce..b3fefa5d 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordFinishEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordFinishEvent.java @@ -14,4 +14,12 @@ public class FlowRecordFinishEvent implements IFlowEvent { private final FlowRecord flowRecord; private final boolean mock; + + /** + * 事件分区键:同一流程内的事件按顺序投递 + */ + @Override + public String eventKey() { + return flowRecord.getProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReduceAuditEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReduceAuditEvent.java index 0d989210..3a571d70 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReduceAuditEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReduceAuditEvent.java @@ -28,4 +28,12 @@ public class FlowRecordReduceAuditEvent implements IFlowEvent { * 是否为模拟环境 */ private final boolean mock; + + /** + * 事件分区键:同一流程内的事件按顺序投递 + */ + @Override + public String eventKey() { + return flowRecord.getProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordRevokeEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordRevokeEvent.java index c92aacc9..16bd0895 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordRevokeEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordRevokeEvent.java @@ -22,4 +22,12 @@ public class FlowRecordRevokeEvent implements IFlowEvent { * 是否为模拟环境 */ private final boolean mock; + + /** + * 事件分区键:同一流程内的事件按顺序投递 + */ + @Override + public String eventKey() { + return currentRecord.getProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordStartEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordStartEvent.java index 0cf3ab4e..802f7ed4 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordStartEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordStartEvent.java @@ -14,4 +14,12 @@ public class FlowRecordStartEvent implements IFlowEvent { private final FlowRecord flowRecord; private final boolean mock; + + /** + * 事件分区键:同一流程内的事件按顺序投递 + */ + @Override + public String eventKey() { + return flowRecord.getProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordTodoEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordTodoEvent.java index 553324ba..98b24067 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordTodoEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordTodoEvent.java @@ -14,4 +14,12 @@ public class FlowRecordTodoEvent implements IFlowEvent { private final FlowRecord flowRecord; private final boolean mock; + + /** + * 事件分区键:同一流程内的事件按顺序投递 + */ + @Override + public String eventKey() { + return flowRecord.getProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordUrgeEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordUrgeEvent.java index 892bb59a..e3e54ecb 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordUrgeEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordUrgeEvent.java @@ -18,4 +18,12 @@ public class FlowRecordUrgeEvent implements IFlowEvent { private final boolean mock; + /** + * 事件分区键:同一流程内的事件按顺序投递 + */ + @Override + public String eventKey() { + return flowRecord.getProcessId(); + } + } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowSubProcessResetEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowSubProcessResetEvent.java index 1b496667..dd55d716 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowSubProcessResetEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowSubProcessResetEvent.java @@ -44,4 +44,12 @@ public class FlowSubProcessResetEvent implements IFlowEvent { * 是否模拟环境 */ private final boolean mock; + + /** + * 事件分区键:按主流程id串行投递 + */ + @Override + public String eventKey() { + return oldRecord == null ? null : oldRecord.getParentProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/IFlowEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/IFlowEvent.java index 343f9621..f1c99ce6 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/IFlowEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/IFlowEvent.java @@ -9,4 +9,15 @@ public interface IFlowEvent extends IAsyncEvent { boolean isMock(); + /** + * 事件分区键,用于保证同一流程内的事件按产生顺序投递。 + * + *

默认为流程id({@code processId}):同一流程的事件严格串行,不同流程可并行。 + * 无法确定流程id的事件返回 null,归入同一默认分区。

+ * + * @return 分区键 + */ + default String eventKey() { + return null; + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/IFlowEventPublisher.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/IFlowEventPublisher.java new file mode 100644 index 00000000..6fbaca0a --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/IFlowEventPublisher.java @@ -0,0 +1,22 @@ +package com.codingapi.flow.event; + +/** + * 流程事件发布器(SPI)。 + * + *

引擎内部所有事件推送都经过 {@link FlowEventPublisher},由该接口的实现决定投递时机与顺序。 + * 由 starter 模块提供 Spring 实现(事务提交后投递、按流程串行);未注册实现时 + * {@link FlowEventPublisher} 回退为直接调用底层 {@code EventPusher},行为与旧版本一致。

+ */ +public interface IFlowEventPublisher { + + /** + * 发布流程事件。 + * + *

实现方须保证:有活动事务时在事务提交后才真正投递、同一 {@link IFlowEvent#eventKey()} + * 的事件按推送顺序投递。

+ * + * @param event 流程事件 + */ + void push(IFlowEvent event); + +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/node/BaseAuditNode.java b/flow-engine-framework/src/main/java/com/codingapi/flow/node/BaseAuditNode.java index 2c19c6b9..9dd9bf2f 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/node/BaseAuditNode.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/node/BaseAuditNode.java @@ -14,7 +14,7 @@ import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.strategy.node.MultiOperatorAuditStrategy; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -350,7 +350,7 @@ private List autoPassAndGenerateNextNodeRecords(FlowSession session, // 本记录作为后续节点记录的前驱,fromId 链经过当前节点 session.setCurrentRecord(autoPassRecord); records.addAll(this.generateNextNodeRecords(session)); - EventPusher.push(new FlowRecordDoneEvent(autoPassRecord, session.isMock())); + FlowEventPublisher.push(new FlowRecordDoneEvent(autoPassRecord, session.isMock())); return records; } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/node/nodes/EndNode.java b/flow-engine-framework/src/main/java/com/codingapi/flow/node/nodes/EndNode.java index 3749bab2..14d5f771 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/node/nodes/EndNode.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/node/nodes/EndNode.java @@ -12,7 +12,7 @@ import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; import com.codingapi.flow.service.impl.FlowSubProcessResultService; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import java.util.ArrayList; import java.util.List; @@ -72,7 +72,7 @@ public void fillNewRecord(FlowSession session, FlowRecord flowRecord) { // 子流程结束后同步执行主流程结果确认,保证 Mock 与生产环境行为一致。 new FlowSubProcessResultService(latestRecord, repositoryHolder).complete(); // 流程是否正常结束 - EventPusher.push(new FlowRecordFinishEvent(latestRecord, session.isMock())); + FlowEventPublisher.push(new FlowRecordFinishEvent(latestRecord, session.isMock())); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowCreateService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowCreateService.java index db5a5621..7f0de567 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowCreateService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowCreateService.java @@ -21,7 +21,7 @@ import com.codingapi.flow.session.IRepositoryHolder; import com.codingapi.flow.workflow.Workflow; import com.codingapi.flow.workflow.runtime.WorkflowRuntime; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import org.springframework.util.StringUtils; import java.util.ArrayList; @@ -108,7 +108,7 @@ public long create() { // 推送事件 for (IFlowEvent event : events) { - EventPusher.push(event); + FlowEventPublisher.push(event); } FlowRecord currentRecord = flowRecords.get(0); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDeleteService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDeleteService.java index 66d32ebb..a0cfa86e 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDeleteService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDeleteService.java @@ -10,7 +10,7 @@ import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.FlowRecordService; import com.codingapi.flow.session.IRepositoryHolder; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import java.util.List; @@ -67,6 +67,6 @@ public void delete() { // 删除流程记录及其关联待办 flowRecordService.deleteFlowRecord(currentRecord); // 推送删除事件 - EventPusher.push(new FlowRecordDeleteEvent(currentRecord, repositoryHolder instanceof MockRepositoryHolder)); + FlowEventPublisher.push(new FlowRecordDeleteEvent(currentRecord, repositoryHolder instanceof MockRepositoryHolder)); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowRevokeService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowRevokeService.java index c9e31db0..e9724c05 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowRevokeService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowRevokeService.java @@ -19,7 +19,7 @@ import com.codingapi.flow.strategy.node.RevokeStrategy; import com.codingapi.flow.workflow.Workflow; import com.codingapi.flow.workflow.runtime.WorkflowRuntime; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import java.util.ArrayList; import java.util.HashSet; @@ -143,7 +143,7 @@ public void revoke() { } repositoryHolder.saveRecords(recordList); - flowEvents.forEach(EventPusher::push); + flowEvents.forEach(FlowEventPublisher::push); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResetService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResetService.java index d913015d..93384453 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResetService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResetService.java @@ -25,7 +25,7 @@ import com.codingapi.flow.strategy.node.SubProcessStrategy; import com.codingapi.flow.workflow.Workflow; import com.codingapi.flow.workflow.runtime.WorkflowRuntime; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import java.util.ArrayList; import java.util.Comparator; @@ -183,9 +183,9 @@ public void reset() { boolean mock = repositoryHolder instanceof MockRepositoryHolder; IFlowOperator resetOperator = repositoryHolder.getOperatorById(request.getOperatorId()); for (FlowRecord invalidatedRecord : invalidatedRecords) { - EventPusher.push(new FlowRecordRevokeEvent(invalidatedRecord, mock)); + FlowEventPublisher.push(new FlowRecordRevokeEvent(invalidatedRecord, mock)); } - EventPusher.push(new FlowSubProcessResetEvent( + FlowEventPublisher.push(new FlowSubProcessResetEvent( currentGroup.snapshot(), newGroup.snapshot(), currentRecord.getId(), diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResultService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResultService.java index b96fa8db..d8b22562 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResultService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResultService.java @@ -16,7 +16,7 @@ import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; import com.codingapi.flow.strategy.node.SubProcessStrategy; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import java.util.ArrayList; import java.util.List; @@ -120,6 +120,6 @@ private void save(List records, List events) { if (!records.isEmpty()) { repositoryHolder.saveRecords(records); } - events.forEach(EventPusher::push); + events.forEach(FlowEventPublisher::push); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowUrgeService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowUrgeService.java index bbb2870e..ea07c009 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowUrgeService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowUrgeService.java @@ -19,7 +19,7 @@ import com.codingapi.flow.strategy.workflow.UrgeStrategy; import com.codingapi.flow.workflow.Workflow; import com.codingapi.flow.workflow.runtime.WorkflowRuntime; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import java.util.ArrayList; import java.util.List; @@ -91,6 +91,6 @@ public void urge() { flowEvents.add(new FlowRecordUrgeEvent(todoRecord, currentOperator,repositoryHolder instanceof MockRepositoryHolder)); } - flowEvents.forEach(EventPusher::push); + flowEvents.forEach(FlowEventPublisher::push); } } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/event/FlowEventPublisherTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/event/FlowEventPublisherTest.java new file mode 100644 index 00000000..6a4638ba --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/event/FlowEventPublisherTest.java @@ -0,0 +1,133 @@ +package com.codingapi.flow.event; + +import com.codingapi.springboot.framework.event.DomainEvent; +import com.codingapi.springboot.framework.event.IEvent; +import com.codingapi.springboot.framework.event.SpringEventInitializer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationEvent; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class FlowEventPublisherTest { + + private final List capturedEvents = new ArrayList<>(); + + private static class TestFlowEvent implements IFlowEvent { + + private final String eventKey; + private final boolean mock; + + private TestFlowEvent(String eventKey, boolean mock) { + this.eventKey = eventKey; + this.mock = mock; + } + + @Override + public boolean isMock() { + return mock; + } + + @Override + public String eventKey() { + return eventKey; + } + } + + private static class RecordPublisher implements IFlowEventPublisher { + + private final List events = new ArrayList<>(); + + @Override + public void push(IFlowEvent event) { + events.add(event); + } + } + + @AfterEach + void clearEventContext() throws Exception { + Class clazz = Class.forName("com.codingapi.springboot.framework.event.DomainEventContext"); + java.lang.reflect.Method getInstance = clazz.getDeclaredMethod("getInstance"); + getInstance.setAccessible(true); + Object instance = getInstance.invoke(null); + Field field = clazz.getDeclaredField("context"); + field.setAccessible(true); + field.set(instance, null); + } + + /** + * 测试目标:未注册发布器实现时,事件推送仍走底层 EventPusher,行为与旧版本一致。 + * 前置条件:未注册 IFlowEventPublisher。 + * 执行步骤:通过门面推送一个事件。 + * 期望断言:事件被发布到底层事件框架。 + */ + @Test + void shouldDelegateToEventPusherWhenNoPublisherRegistered() throws Exception { + initEventCapture(); + + TestFlowEvent event = new TestFlowEvent("process-1", false); + FlowEventPublisher.push(event); + + assertEquals(1, capturedEvents.size(), "未注册发布器时应回退到底层 EventPusher"); + assertTrue(capturedEvents.get(0) == event, "推送的应为同一个事件实例"); + } + + /** + * 测试目标:注册发布器实现后,事件由实现投递,不再直接进入底层事件框架。 + * 前置条件:调用 register 注册自定义发布器。 + * 执行步骤:通过门面推送事件。 + * 期望断言:实现收到事件,底层事件框架无感知。 + */ + @Test + void shouldDelegateToRegisteredPublisher() throws Exception { + initEventCapture(); + RecordPublisher publisher = new RecordPublisher(); + FlowEventPublisher.register(publisher); + try { + TestFlowEvent event = new TestFlowEvent("process-2", true); + FlowEventPublisher.push(event); + + assertEquals(1, publisher.events.size(), "应交由注册的实现投递"); + assertTrue(publisher.events.get(0) == event); + assertTrue(capturedEvents.isEmpty(), "注册实现后不应再直接推送到底层框架"); + } finally { + FlowEventPublisher.unregister(publisher); + } + } + + /** + * 测试目标:注销发布器实现后,事件推送恢复为底层 EventPusher。 + * 前置条件:先注册再注销自定义发布器。 + * 执行步骤:通过门面推送事件。 + * 期望断言:重新回退到底层事件框架。 + */ + @Test + void shouldFallbackToEventPusherAfterUnregister() throws Exception { + initEventCapture(); + RecordPublisher publisher = new RecordPublisher(); + FlowEventPublisher.register(publisher); + FlowEventPublisher.unregister(publisher); + + FlowEventPublisher.push(new TestFlowEvent("process-3", false)); + + assertTrue(publisher.events.isEmpty(), "注销后不应再调用已注销的实现"); + assertEquals(1, capturedEvents.size(), "注销后应回退到底层 EventPusher"); + } + + private void initEventCapture() throws Exception { + ApplicationContext context = Mockito.mock(ApplicationContext.class); + Mockito.doAnswer(invocation -> { + DomainEvent domainEvent = invocation.getArgument(0); + capturedEvents.add(domainEvent.getEvent()); + return null; + }).when(context).publishEvent(Mockito.any(ApplicationEvent.class)); + new SpringEventInitializer(context).afterPropertiesSet(); + } +} diff --git a/flow-engine-starter/src/main/java/com/codingapi/flow/AutoConfiguration.java b/flow-engine-starter/src/main/java/com/codingapi/flow/AutoConfiguration.java index 7dbaab48..1d0de03a 100644 --- a/flow-engine-starter/src/main/java/com/codingapi/flow/AutoConfiguration.java +++ b/flow-engine-starter/src/main/java/com/codingapi/flow/AutoConfiguration.java @@ -1,6 +1,8 @@ package com.codingapi.flow; import com.codingapi.flow.context.RepositoryHolderContext; +import com.codingapi.flow.event.IFlowEventPublisher; +import com.codingapi.flow.event.SpringFlowEventPublisher; import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.register.NodeViewJavaScriptCacheContextRegister; import com.codingapi.flow.register.RepositoryHolderContextRegister; @@ -11,6 +13,8 @@ import com.codingapi.flow.service.FlowRecordService; import com.codingapi.flow.service.FlowService; import com.codingapi.flow.service.WorkflowService; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -35,6 +39,17 @@ public GatewayContextRegister gatewayContextRegister(FlowOperatorGateway flowOpe return new GatewayContextRegister(flowOperatorGateway); } + /** + * 流程事件发布器:事务提交后投递 + 按流程id分区串行(issue #274)。 + * 可通过 codingapi.flow.event.ordered=false 关闭,关闭后回退为直接推送到事件框架。 + */ + @Bean + @ConditionalOnMissingBean(IFlowEventPublisher.class) + @ConditionalOnProperty(value = "codingapi.flow.event.ordered", matchIfMissing = true) + public SpringFlowEventPublisher flowEventPublisher(ApplicationContext applicationContext) { + return new SpringFlowEventPublisher(applicationContext); + } + @Bean public FlowScriptContextRegister flowScriptContextRegister( ApplicationContext spring, diff --git a/flow-engine-starter/src/main/java/com/codingapi/flow/event/SpringFlowEventPublisher.java b/flow-engine-starter/src/main/java/com/codingapi/flow/event/SpringFlowEventPublisher.java new file mode 100644 index 00000000..f8386ead --- /dev/null +++ b/flow-engine-starter/src/main/java/com/codingapi/flow/event/SpringFlowEventPublisher.java @@ -0,0 +1,140 @@ +package com.codingapi.flow.event; + +import com.codingapi.springboot.framework.event.DomainEvent; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.ApplicationContext; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * 流程事件发布器的 Spring 实现(issue #274)。 + * + *

解决两个长期存在的一致性风险:

+ *
    + *
  1. 事务可见性:有活动事务时,事件通过 {@link TransactionSynchronization#afterCommit()} + * 在事务提交后才投递,订阅方回查数据库一定能读到流程记录/待办/关系数据;事务回滚则不投递。
  2. + *
  3. 投递顺序:按 {@link IFlowEvent#eventKey()}(默认流程id)散列到固定的单线程分区, + * 同一流程的事件严格按产生顺序投递,不同流程可并行;投递时使用同步事件 + * ({@code DomainEvent(sync=true)})在分区线程内完成 handler 调用,避免再落入底层线程池导致乱序。
  4. + *
+ * + *

与底层 {@code EventPusher} 的关系:未注册本实现时(仅使用 framework、单元测试等场景), + * {@link FlowEventPublisher} 直接回退 {@code EventPusher.push},行为与旧版本一致。 + * handler 抛出异常时只记录日志,不阻塞同分区后续事件的投递。

+ */ +@Slf4j +public class SpringFlowEventPublisher implements IFlowEventPublisher, InitializingBean, DisposableBean { + + /** + * 默认分区数:分区内串行、分区间并行 + */ + private static final int DEFAULT_PARTITION_SIZE = 4; + + private final ApplicationContext applicationContext; + + private final ExecutorService[] partitions; + + public SpringFlowEventPublisher(ApplicationContext applicationContext) { + this(applicationContext, DEFAULT_PARTITION_SIZE); + } + + public SpringFlowEventPublisher(ApplicationContext applicationContext, int partitionSize) { + this.applicationContext = applicationContext; + int size = Math.max(1, partitionSize); + this.partitions = new ExecutorService[size]; + } + + @Override + public void afterPropertiesSet() { + for (int i = 0; i < partitions.length; i++) { + partitions[i] = Executors.newSingleThreadExecutor(new FlowEventThreadFactory(i)); + } + FlowEventPublisher.register(this); + log.info("SpringFlowEventPublisher success initial, partitions:{}", partitions.length); + } + + @Override + public void push(IFlowEvent event) { + if (event == null) { + return; + } + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + dispatch(event); + } + }); + return; + } + dispatch(event); + } + + /** + * 提交事件到对应分区:分区的单线程执行器天然保证「先提交先执行」。 + */ + private void dispatch(IFlowEvent event) { + String eventKey = event.eventKey(); + int index = eventKey == null ? 0 : Math.floorMod(eventKey.hashCode(), partitions.length); + partitions[index].execute(() -> publish(event)); + } + + /** + * 以同步事件方式投递,使 handler 在当前分区线程内执行完毕,从而获得确定顺序。 + */ + private void publish(IFlowEvent event) { + try { + applicationContext.publishEvent(new DomainEvent(event, true, generateTraceId())); + } catch (Exception e) { + log.error("flow event dispatch failed, eventType:{}, eventKey:{}", + event.getClass().getName(), safeEventKey(event), e); + } + } + + private String safeEventKey(IFlowEvent event) { + try { + return event.eventKey(); + } catch (Exception e) { + return null; + } + } + + private String generateTraceId() { + return UUID.randomUUID().toString().replace("-", ""); + } + + @Override + public void destroy() { + FlowEventPublisher.unregister(this); + for (ExecutorService partition : partitions) { + if (partition != null) { + partition.shutdown(); + } + } + } + + private static class FlowEventThreadFactory implements ThreadFactory { + + private final int index; + private final AtomicInteger counter = new AtomicInteger(1); + + private FlowEventThreadFactory(int index) { + this.index = index; + } + + @Override + public Thread newThread(Runnable runnable) { + Thread thread = new Thread(runnable, "flow-event-dispatch-" + index + "-" + counter.getAndIncrement()); + thread.setDaemon(true); + return thread; + } + } +} diff --git a/flow-engine-starter/src/test/java/com/codingapi/flow/event/SpringFlowEventPublisherTest.java b/flow-engine-starter/src/test/java/com/codingapi/flow/event/SpringFlowEventPublisherTest.java new file mode 100644 index 00000000..4ad772e9 --- /dev/null +++ b/flow-engine-starter/src/test/java/com/codingapi/flow/event/SpringFlowEventPublisherTest.java @@ -0,0 +1,238 @@ +package com.codingapi.flow.event; + +import com.codingapi.springboot.framework.event.DomainEvent; +import com.codingapi.springboot.framework.event.IHandler; +import com.codingapi.springboot.framework.event.SpringDefaultEventHandler; +import com.codingapi.springboot.framework.properties.FrameworkProperties; +import com.codingapi.springboot.framework.properties.PropertiesContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationEvent; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 流程事件发布器(提交后投递 + 分区串行)测试。 + */ +class SpringFlowEventPublisherTest { + + private static final List HANDLED = new CopyOnWriteArrayList<>(); + private static final List HANDLED_THREADS = new CopyOnWriteArrayList<>(); + private static volatile int slowEventId = -1; + private static volatile int failEventId = -1; + + private static ApplicationContext applicationContext; + + private SpringFlowEventPublisher publisher; + + static class TestFlowEvent implements IFlowEvent { + + private final int id; + private final String eventKey; + private final boolean mock; + + private TestFlowEvent(int id, String eventKey, boolean mock) { + this.id = id; + this.eventKey = eventKey; + this.mock = mock; + } + + @Override + public boolean isMock() { + return mock; + } + + @Override + public String eventKey() { + return eventKey; + } + } + + static class Recorder implements IHandler { + + @Override + public void handler(TestFlowEvent event) { + if (event.id == slowEventId) { + sleep(80); + } + if (event.id == failEventId) { + throw new IllegalStateException("handler error, eventId:" + event.id); + } + HANDLED.add(event.id); + HANDLED_THREADS.add(Thread.currentThread().getName()); + } + } + + @BeforeAll + static void initEventFramework() throws Exception { + PropertiesContext.getInstance().setProperties(new FrameworkProperties()); + SpringDefaultEventHandler eventHandler = new SpringDefaultEventHandler(List.of(new Recorder())); + eventHandler.afterPropertiesSet(); + + applicationContext = Mockito.mock(ApplicationContext.class); + Mockito.doAnswer(invocation -> { + DomainEvent domainEvent = invocation.getArgument(0); + eventHandler.dispatch(domainEvent); + return null; + }).when(applicationContext).publishEvent(Mockito.any(ApplicationEvent.class)); + } + + @AfterEach + void tearDown() { + if (publisher != null) { + publisher.destroy(); + publisher = null; + } + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + HANDLED.clear(); + HANDLED_THREADS.clear(); + slowEventId = -1; + failEventId = -1; + } + + /** + * 测试目标:事务内推送的事件必须等事务提交后才投递给订阅方。 + * 前置条件:存在活动事务同步。 + * 执行步骤:事务内连续推送两个事件 → 提交前观察 → afterCommit 后观察。 + * 期望断言:提交前无任何 handler 执行;提交后按产生顺序依次执行。 + */ + @Test + void shouldDispatchOnlyAfterCommit() throws Exception { + publisher = newPublisher(); + TransactionSynchronizationManager.initSynchronization(); + + publisher.push(new TestFlowEvent(1, "process-a", false)); + publisher.push(new TestFlowEvent(2, "process-a", false)); + + assertTrue(HANDLED.isEmpty(), "事务提交前不应投递事件"); + + commit(); + + awaitHandled(2); + assertEquals(List.of(1, 2), HANDLED, "提交后应按产生顺序投递"); + } + + /** + * 测试目标:事务回滚时事件不应投递。 + * 前置条件:存在活动事务同步。 + * 执行步骤:事务内推送事件 → 回滚(不触发 afterCommit)。 + * 期望断言:订阅方始终收不到事件。 + */ + @Test + void shouldNotDispatchWhenTransactionRolledBack() throws Exception { + publisher = newPublisher(); + TransactionSynchronizationManager.initSynchronization(); + + publisher.push(new TestFlowEvent(1, "process-b", false)); + for (TransactionSynchronization synchronization : TransactionSynchronizationManager.getSynchronizations()) { + synchronization.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); + } + + sleep(150); + assertTrue(HANDLED.isEmpty(), "事务回滚后不应投递事件"); + } + + /** + * 测试目标:同一流程(相同 eventKey)的事件严格按推送顺序投递,即使先推送的事件处理较慢。 + * 前置条件:存在活动事务同步,首个事件 handler 耗时 80ms。 + * 执行步骤:推送三个同 eventKey 事件 → 提交。 + * 期望断言:handler 执行顺序与推送顺序一致。 + */ + @Test + void shouldKeepOrderForSameEventKey() throws Exception { + publisher = newPublisher(); + slowEventId = 1; + TransactionSynchronizationManager.initSynchronization(); + + publisher.push(new TestFlowEvent(1, "process-c", false)); + publisher.push(new TestFlowEvent(2, "process-c", false)); + publisher.push(new TestFlowEvent(3, "process-c", false)); + + commit(); + + awaitHandled(3); + assertEquals(List.of(1, 2, 3), HANDLED, "同一分区内必须按推送顺序执行"); + } + + /** + * 测试目标:无事务上下文时(如定时任务、mock 调用)事件立即投递。 + * 前置条件:不存在活动事务同步。 + * 执行步骤:直接推送事件。 + * 期望断言:订阅方收到事件,且执行线程为事件投递线程。 + */ + @Test + void shouldDispatchImmediatelyWithoutTransaction() throws Exception { + publisher = newPublisher(); + + publisher.push(new TestFlowEvent(1, "process-d", true)); + + awaitHandled(1); + assertEquals(List.of(1), HANDLED); + assertTrue(HANDLED_THREADS.get(0).startsWith("flow-event-dispatch-"), + "应在事件投递线程内执行,实际线程:" + HANDLED_THREADS.get(0)); + } + + /** + * 测试目标:单个事件的 handler 异常不应阻塞同分区后续事件。 + * 前置条件:首个事件的 handler 抛出异常。 + * 执行步骤:推送两个同 eventKey 事件 → 提交。 + * 期望断言:第二个事件仍被正常处理。 + */ + @Test + void shouldContinueDispatchWhenHandlerThrows() throws Exception { + publisher = newPublisher(); + failEventId = 1; + TransactionSynchronizationManager.initSynchronization(); + + publisher.push(new TestFlowEvent(1, "process-e", false)); + publisher.push(new TestFlowEvent(2, "process-e", false)); + + commit(); + + awaitHandled(1); + sleep(100); + assertEquals(List.of(2), HANDLED, "handler 异常不应影响后续事件投递"); + } + + private SpringFlowEventPublisher newPublisher() throws Exception { + SpringFlowEventPublisher eventPublisher = new SpringFlowEventPublisher(applicationContext, 1); + eventPublisher.afterPropertiesSet(); + return eventPublisher; + } + + private void commit() { + List synchronizations = + new ArrayList<>(TransactionSynchronizationManager.getSynchronizations()); + for (TransactionSynchronization synchronization : synchronizations) { + synchronization.afterCommit(); + } + TransactionSynchronizationManager.clearSynchronization(); + } + + private void awaitHandled(int expected) throws InterruptedException { + long deadline = System.currentTimeMillis() + 3000; + while (System.currentTimeMillis() < deadline && HANDLED.size() < expected) { + sleep(10); + } + } + + private static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +} From 4340d724cddfca287185686ac98d6a1632e33735 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Mon, 16 Nov 2026 23:00:26 +0800 Subject: [PATCH 4/6] =?UTF-8?q?fix:=20=E4=BA=8C=E6=AC=A1=E5=8F=91=E8=B5=B7?= =?UTF-8?q?=E4=BA=8B=E4=BB=B6=E6=8E=A5=E5=85=A5=20FlowEventPublisher?= =?UTF-8?q?=EF=BC=8C=E8=A1=A5=E9=BD=90=E4=BA=8B=E4=BB=B6=E5=88=86=E5=8C=BA?= =?UTF-8?q?=E9=94=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - FlowReissueService 改走 FlowEventPublisher,避免绕过 #274 的「提交后投递 + 按流程串行」保障 - FlowRecordReissueEvent 实现 eventKey(),按二次发起后的新流程id分区 - 补充回归测试(事件必须经由发布器投递且带分区键) - 更新事件集成文档与 AGENTS.md:10 种事件、推送位置、顺序与可见性说明 Refs #272, #274 --- AGENTS.md | 4 +-- docs/Integration/event-integration.md | 10 +++--- .../flow/event/FlowRecordReissueEvent.java | 8 +++++ .../flow/service/impl/FlowReissueService.java | 4 +-- .../flow/service/FlowReissueServiceTest.java | 35 +++++++++++++++++++ 5 files changed, 53 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index dd8895a4..5e02d38e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -64,11 +64,11 @@ REST 层通过请求参数 `mockKey` 分流到 Mock 实例(见 `FlowRecordCont ### 事件(IFlowEvent + EventPusher) -9 种事件:开始 / 待办 / 已办 / 完成 / 催办 / 撤销(`FlowRecordRevokeEvent`)/ 删除(`FlowRecordDeleteEvent`)/ 子流程重置(`FlowSubProcessResetEvent`)/ 减签(`FlowRecordReduceAuditEvent`)。操作完成后用 `FlowEventPublisher.push(event)` 推送(**禁止**直接调用 `EventPusher`);引入 starter 时由 `SpringFlowEventPublisher` 保证「事务提交后投递 + 按 `eventKey()`(默认 processId)分区串行」,未注册实现时自动回退 `EventPusher`。记录类事件携带 `FlowRecord` + `mock` 标记,重置事件携带新旧聚合组快照。外部可用 Spring `@EventListener` 订阅。 +10 种事件:开始 / 待办 / 已办 / 完成 / 催办 / 撤销(`FlowRecordRevokeEvent`)/ 删除(`FlowRecordDeleteEvent`)/ 子流程重置(`FlowSubProcessResetEvent`)/ 减签(`FlowRecordReduceAuditEvent`)/ 二次发起(`FlowRecordReissueEvent`)。操作完成后用 `FlowEventPublisher.push(event)` 推送(**禁止**直接调用 `EventPusher`);引入 starter 时由 `SpringFlowEventPublisher` 保证「事务提交后投递 + 按 `eventKey()`(默认 processId)分区串行」,未注册实现时自动回退 `EventPusher`。记录类事件携带 `FlowRecord` + `mock` 标记,重置事件携带新旧聚合组快照。外部可用 Spring `@EventListener` 订阅。 ### API 模块划分 -- **命令操作**:`flow-engine-starter-api` — `FlowRecordController`(`/api/cmd/record`:create / action / revoke / delete / urge / detail / processNodes / subProcess/reset)、`WorkflowController`(`/api/cmd/workflow`:流程设计 CRUD 及导入导出)与 `NodeViewJavaScriptController`(`/api/cmd/node-view`:节点视图脚本 getScript / save) +- **命令操作**:`flow-engine-starter-api` — `FlowRecordController`(`/api/cmd/record`:create / action / revoke / delete / urge / detail / processNodes / subProcess/reset / reissue)、`WorkflowController`(`/api/cmd/workflow`:流程设计 CRUD 及导入导出)与 `NodeViewJavaScriptController`(`/api/cmd/node-view`:节点视图脚本 getScript / save) - **查询**:`flow-engine-starter-query` — `FlowRecordQueryController`(`/api/query/record`:list / todo / done / notify)与 `WorkflowQueryController`(`/api/query/workflow`:list / options / versions) - **持久化**:`flow-engine-starter-infra` — JPA 实体与仓储实现(含达梦方言) diff --git a/docs/Integration/event-integration.md b/docs/Integration/event-integration.md index ce9527a2..8a54d4e3 100644 --- a/docs/Integration/event-integration.md +++ b/docs/Integration/event-integration.md @@ -27,7 +27,7 @@ public interface IAsyncEvent extends IEvent {} // 异步事件标记 ← 同步/异步由 `DomainEventContext.push` 的 `instanceof` 判定:`IAsyncEvent` → 异步(线程池执行);`ISyncEvent`/裸 `IEvent` → 同步(发布线程内联执行)。 -### 1.2 九种事件 +### 1.2 十种事件 记录类事件均携带 `FlowRecord`(或当前记录)与 `boolean mock` 标记(Mock 模式为 `true`)。 @@ -42,13 +42,14 @@ public interface IAsyncEvent extends IEvent {} // 异步事件标记 ← | `FlowRecordDeleteEvent` | 删除未流转实例(开始节点) | `FlowRecord, boolean mock` | `getFlowRecord()` / `isMock()` | | `FlowRecordReduceAuditEvent` | 减签(每条被撤下的记录) | `FlowRecord, long reduceOperatorId, boolean mock` | `getFlowRecord()` / `getReduceOperatorId()` / `isMock()` | | `FlowSubProcessResetEvent` | 子流程数据重置(issue #219) | `SubProcessRecord oldRecord, SubProcessRecord newRecord, long resetRecordId, IFlowOperator resetOperator, boolean mock` | `getOldRecord()` / `getNewRecord()` / `getResetRecordId()` / `getResetOperator()` / `isMock()` | +| `FlowRecordReissueEvent` | 已完成流程二次发起(issue #272) | `FlowRecord sourceRecord, FlowRecord newRecord, IFlowOperator operator, boolean mock` | `getSourceRecord()` / `getNewRecord()` / `getOperator()` / `isMock()` | **子流程重置事件订阅须知**: | 关注点 | 约定 | |---|---| | 新旧聚合组 | `oldRecord` 为被取代的旧聚合组快照(含全部旧实例流程id);`newRecord` 为新聚合组,继承实例沿用原流程id、重建实例为新流程id,重建实例的 `getSourceProcessId()` 指向被替换的旧实例 | -| 收敛方式 | 事件异步、到达顺序不保证(同时伴随 `RevokeEvent`/`StartEvent`/`TodoEvent`);按「同一 `parentRecordId` + 节点维度下最大聚合组 id 为活跃组」幂等覆盖,禁止增量累加 | +| 收敛方式 | 引入 starter 时同一主流程的事件按产生顺序串行到达(同时伴随 `RevokeEvent`/`StartEvent`/`TodoEvent`);仍建议按「同一 `parentRecordId` + 节点维度下最大聚合组 id 为活跃组」幂等覆盖,禁止增量累加 | | 丢事件对账 | `oldRecord` id 与订阅方当前活跃组不一致时,视为丢事件,调用 `/api/cmd/record/processNodes` 全量对账 | | 旧数据 | 旧实例记录不删除(仅标记聚合组已取代),订阅方需自行将旧流程id数据标记失效 | @@ -130,8 +131,9 @@ public class EventPusher { | `FlowRevokeService.revoke()` | 当前记录恢复待办 `TodoEvent` + 被撤销后置记录 `RevokeEvent` | | `FlowDeleteService.delete()` | `DeleteEvent` | | `FlowSubProcessResetService.reset()` | 被作废记录链逐条 `RevokeEvent` + 子流程重置 `SubProcessResetEvent`;重建实例经 `FlowCreateService` 推送各自的 `StartEvent` + `TodoEvent` | +| `FlowReissueService.reissue()` | 二次发起 `ReissueEvent` + 新流程经 `FlowCreateService` 推送的 `StartEvent` + `TodoEvent` | -> 事件在 `repositoryHolder.saveRecords(...)` **落库之后**推送,保证订阅方看到的记录已持久化。 +> 事件在业务数据保存之后推送,且引入 starter 时会在**事务提交后**才投递给订阅方(见 4.5),保证订阅方回查到的记录已持久化。 ### 结束节点虚拟记录拦截 @@ -140,7 +142,7 @@ public class EventPusher { ```java flowEvents.stream() .filter(event -> !isEndNodeTodoEvent(event)) - .forEach(EventPusher::push); + .forEach(FlowEventPublisher::push); private boolean isEndNodeTodoEvent(IFlowEvent event) { return event instanceof FlowRecordTodoEvent todoEvent diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReissueEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReissueEvent.java index 0aceeede..4d0001cb 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReissueEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReissueEvent.java @@ -31,4 +31,12 @@ public class FlowRecordReissueEvent implements IFlowEvent { private final IFlowOperator operator; private final boolean mock; + + /** + * 事件分区键:按二次发起后新流程的流程id串行投递 + */ + @Override + public String eventKey() { + return newRecord == null ? null : newRecord.getProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowReissueService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowReissueService.java index 5f1b56c2..41534d53 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowReissueService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowReissueService.java @@ -3,6 +3,7 @@ import com.codingapi.flow.action.ActionType; import com.codingapi.flow.action.IFlowAction; import com.codingapi.flow.domain.FlowReissueRecord; +import com.codingapi.flow.event.FlowEventPublisher; import com.codingapi.flow.event.FlowRecordReissueEvent; import com.codingapi.flow.exception.FlowNotFoundException; import com.codingapi.flow.exception.FlowPermissionException; @@ -22,7 +23,6 @@ import com.codingapi.flow.strategy.node.OperatorSelectType; import com.codingapi.flow.workflow.Workflow; import com.codingapi.flow.workflow.runtime.WorkflowRuntime; -import com.codingapi.springboot.framework.event.EventPusher; import org.springframework.util.StringUtils; import java.util.HashMap; @@ -130,7 +130,7 @@ public long reissue() { reissueRepository.save(reissueRecord); boolean mock = repositoryHolder instanceof MockRepositoryHolder; - EventPusher.push(new FlowRecordReissueEvent(sourceRecord, newRecord, operator, mock)); + FlowEventPublisher.push(new FlowRecordReissueEvent(sourceRecord, newRecord, operator, mock)); return newRecordId; } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowReissueServiceTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowReissueServiceTest.java index cbe3eeb0..f7f6ae85 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowReissueServiceTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowReissueServiceTest.java @@ -4,7 +4,10 @@ import com.codingapi.flow.builder.FormFieldPermissionsBuilder; import com.codingapi.flow.builder.NodeStrategyBuilder; import com.codingapi.flow.domain.FlowReissueRecord; +import com.codingapi.flow.event.FlowEventPublisher; import com.codingapi.flow.event.FlowRecordReissueEvent; +import com.codingapi.flow.event.IFlowEvent; +import com.codingapi.flow.event.IFlowEventPublisher; import com.codingapi.flow.exception.FlowPermissionException; import com.codingapi.flow.exception.FlowStateException; import com.codingapi.flow.factory.MyFlowServiceFactory; @@ -294,6 +297,38 @@ void shouldExposeReissueFlagOnlyForFlowManagerOnFinishedRecord() { () -> assertFalse(initiatorView.isReissue())); } + /** + * 测试目标:二次发起产生的事件必须走 {@link FlowEventPublisher},不得绕过发布器直接推送到事件框架。 + * 前置条件:注册一个记录型事件发布器(模拟 starter 的 SpringFlowEventPublisher)。 + * 执行步骤:对已完成流程执行二次发起 → 查看发布器收到的事件。 + * 期望断言:新流程的事件(开始/待办/二次发起)全部经由发布器投递,且二次发起事件的分区键为新流程id。 + */ + @Test + void shouldPublishReissueEventThroughFlowEventPublisher() { + long sourceRecordId = finishFlow("原始数据"); + List published = new ArrayList<>(); + IFlowEventPublisher publisher = published::add; + FlowEventPublisher.register(publisher); + try { + long newRecordId = reissue(sourceRecordId, manager, null); + FlowRecord newRecord = factory.flowRecordRepository.get(newRecordId); + + FlowRecordReissueEvent reissueEvent = published.stream() + .filter(FlowRecordReissueEvent.class::isInstance) + .map(FlowRecordReissueEvent.class::cast) + .findFirst() + .orElseThrow(() -> new AssertionError("二次发起事件应经由 FlowEventPublisher 投递")); + assertAll("事件走发布器与分区键", + () -> assertTrue(published.stream().allMatch(event -> event.eventKey() != null), + "所有事件都应带有分区键"), + () -> assertEquals(newRecord.getProcessId(), reissueEvent.eventKey(), + "二次发起事件应按新流程id分区"), + () -> assertEquals(newRecordId, reissueEvent.getNewRecord().getId())); + } finally { + FlowEventPublisher.unregister(publisher); + } + } + /** * 测试目标:终止(未通过结束)的流程不开放二次发起。 * 前置条件:源记录流程状态为 SATE_FLOW_DONE。 From 5977a2864a3e8f58d21f117010360793fe93964b Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Mon, 16 Nov 2026 23:41:50 +0800 Subject: [PATCH 5/6] =?UTF-8?q?chore(deps):=20=E5=8D=87=E7=BA=A7=20springb?= =?UTF-8?q?oot-framework=20=E8=87=B3=2017.3.3=20=E5=B9=B6=E8=A1=A5?= =?UTF-8?q?=E5=85=85=E4=BA=8B=E4=BB=B6=E6=8A=95=E9=80=92=E9=9B=86=E6=88=90?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - codingapi.framework.version 17.3.2 -> 17.3.3(含 #222 异步事件顺序与可见性修复) - 新增 SpringFlowEventPublisherIntegrationTest:真实 Spring 上下文 + 真实事务同步, 验证「提交后投递、同流程严格顺序、回滚不投递、无事务立即投递、handler 运行在事件分区线程」 - 升级后全量测试通过 Refs #274 --- ...ringFlowEventPublisherIntegrationTest.java | 208 ++++++++++++++++++ pom.xml | 2 +- 2 files changed, 209 insertions(+), 1 deletion(-) create mode 100644 flow-engine-starter/src/test/java/com/codingapi/flow/event/SpringFlowEventPublisherIntegrationTest.java diff --git a/flow-engine-starter/src/test/java/com/codingapi/flow/event/SpringFlowEventPublisherIntegrationTest.java b/flow-engine-starter/src/test/java/com/codingapi/flow/event/SpringFlowEventPublisherIntegrationTest.java new file mode 100644 index 00000000..a8a1bd68 --- /dev/null +++ b/flow-engine-starter/src/test/java/com/codingapi/flow/event/SpringFlowEventPublisherIntegrationTest.java @@ -0,0 +1,208 @@ +package com.codingapi.flow.event; + +import com.codingapi.springboot.framework.event.IHandler; +import com.codingapi.springboot.framework.event.SpringDefaultEventHandler; +import com.codingapi.springboot.framework.properties.FrameworkProperties; +import com.codingapi.springboot.framework.properties.PropertiesContext; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionTemplate; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 事件发布器与底层事件框架(17.3.3 起默认 {@code @TransactionalEventListener(AFTER_COMMIT, fallbackExecution)}) + * 的集成测试:使用真实 Spring 上下文与真实事务同步机制,验证 + * 「事务提交后才投递 + 同流程严格按顺序 + 回滚不投递 + 在事件分区线程内执行」。 + * + *

与 {@link SpringFlowEventPublisherTest} 的区别:后者直接调用 handler,本测试经过 + * Spring 的事件多播与事务监听器装配,覆盖两套机制的交互。

+ */ +class SpringFlowEventPublisherIntegrationTest { + + private static final List HANDLED = new CopyOnWriteArrayList<>(); + private static final List HANDLED_THREADS = new CopyOnWriteArrayList<>(); + + /** + * 上下文只创建一次:底层 ApplicationHandlerUtils 是静态注册表,反复创建上下文会重复注册 handler + */ + private static AnnotationConfigApplicationContext context; + private static PlatformTransactionManager transactionManager; + + private SpringFlowEventPublisher publisher; + + static class RecEvent implements IFlowEvent { + + private final int id; + private final String eventKey; + private final boolean mock; + + RecEvent(int id, String eventKey, boolean mock) { + this.id = id; + this.eventKey = eventKey; + this.mock = mock; + } + + @Override + public boolean isMock() { + return mock; + } + + @Override + public String eventKey() { + return eventKey; + } + } + + @Configuration + static class TestConfig { + + @Bean + public PlatformTransactionManager transactionManager() { + return new NoopTransactionManager(); + } + + @Bean + public IHandler recEventHandler() { + return event -> { + HANDLED.add(event.id); + HANDLED_THREADS.add(Thread.currentThread().getName()); + }; + } + + @Bean + public SpringDefaultEventHandler springDefaultEventHandler(List handlers) { + return new SpringDefaultEventHandler(handlers); + } + } + + /** + * 无实际资源的事务管理器:仅驱动 Spring 的事务同步(begin/commit/rollback)流程。 + */ + static class NoopTransactionManager extends AbstractPlatformTransactionManager { + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + } + + @Override + protected void doRollback(DefaultTransactionStatus status) { + } + } + + @BeforeAll + static void initContext() { + PropertiesContext.getInstance().setProperties(new FrameworkProperties()); + context = new AnnotationConfigApplicationContext(TestConfig.class); + transactionManager = context.getBean(PlatformTransactionManager.class); + } + + @AfterAll + static void closeContext() { + if (context != null) { + context.close(); + } + } + + @BeforeEach + void setUp() { + HANDLED.clear(); + HANDLED_THREADS.clear(); + publisher = new SpringFlowEventPublisher(context, 1); + publisher.afterPropertiesSet(); + } + + @AfterEach + void tearDown() { + if (publisher != null) { + publisher.destroy(); + } + } + + /** + * 测试目标:事务内推送的事件在提交后才由订阅方处理,且同一流程(同 eventKey)严格按顺序。 + * 前置条件:真实 Spring 上下文 + 真实事务同步 + 事件发布器已注册。 + * 执行步骤:事务内连续推送两个事件 → 提交前观察 → 提交后观察。 + * 期望断言:提交前无 handler 执行;提交后按推送顺序执行,且执行线程为事件分区线程。 + */ + @Test + void shouldDispatchAfterCommitInOrderThroughSpringListener() throws Exception { + TransactionTemplate template = new TransactionTemplate(transactionManager); + + template.executeWithoutResult(status -> { + publisher.push(new RecEvent(1, "process-integration", false)); + publisher.push(new RecEvent(2, "process-integration", false)); + assertTrue(HANDLED.isEmpty(), "事务提交前不应有 handler 执行"); + }); + + awaitHandled(2); + assertEquals(List.of(1, 2), HANDLED, "提交后应按推送顺序投递"); + assertTrue(HANDLED_THREADS.stream().allMatch(name -> name.startsWith("flow-event-dispatch-")), + "handler 应在事件分区线程内执行,实际:" + HANDLED_THREADS); + } + + /** + * 测试目标:事务回滚时不投递任何事件。 + * 前置条件:同上。 + * 执行步骤:事务内推送事件后抛出异常触发回滚。 + * 期望断言:订阅方始终收不到事件。 + */ + @Test + void shouldNotDispatchWhenTransactionRolledBack() throws Exception { + TransactionTemplate template = new TransactionTemplate(transactionManager); + + assertThrows(IllegalStateException.class, () -> template.executeWithoutResult(status -> { + publisher.push(new RecEvent(3, "process-rollback", false)); + throw new IllegalStateException("rollback"); + })); + + Thread.sleep(300); + assertTrue(HANDLED.isEmpty(), "事务回滚后不应投递事件"); + } + + /** + * 测试目标:无事务时的事件立即投递(模拟 mock 模式 / 定时任务)。 + * 前置条件:不在事务上下文中。 + * 执行步骤:直接推送事件。 + * 期望断言:订阅方收到事件。 + */ + @Test + void shouldDispatchImmediatelyWithoutTransaction() throws Exception { + publisher.push(new RecEvent(4, "process-no-tx", true)); + + awaitHandled(1); + assertEquals(List.of(4), HANDLED); + } + + private void awaitHandled(int expected) throws InterruptedException { + long deadline = System.currentTimeMillis() + 3000; + while (System.currentTimeMillis() < deadline && HANDLED.size() < expected) { + Thread.sleep(10); + } + } +} diff --git a/pom.xml b/pom.xml index 37d62c63..4d68ca98 100644 --- a/pom.xml +++ b/pom.xml @@ -36,7 +36,7 @@ 2.17.0 3.20.0 1.2.0 - 17.3.2 + 17.3.3 From c3cf27138040d4af5ae885828cfbef2d06acb8d2 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Mon, 16 Nov 2026 23:48:55 +0800 Subject: [PATCH 6/6] Update flow-frontend to latest main --- flow-frontend | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flow-frontend b/flow-frontend index 0f8cd6d1..32c27061 160000 --- a/flow-frontend +++ b/flow-frontend @@ -1 +1 @@ -Subproject commit 0f8cd6d152b57131f4338d17da20103141bbf0f5 +Subproject commit 32c2706159efda764f2d3856581b236f2c0791f8