From a5199a0385dc397eee1121cbcf6c40586f9b0bc0 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Mon, 23 Nov 2026 21:30:04 +0800 Subject: [PATCH 01/35] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=E8=80=85=E8=BA=AB=E4=BB=BD=E6=A0=87=E8=AF=86=E7=9A=84?= =?UTF-8?q?=E5=AD=98=E5=82=A8=E4=B8=8E=E8=84=9A=E6=9C=AC=E8=AF=BB=E5=8F=96?= =?UTF-8?q?=EF=BC=88issue=20#288=20P1=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - IFlowOperator 新增 default getIdentity()/getIdentityAttributes(),下游存量实现零改动即可编译 - 新增 OperatorIdentity:null 与空串统一归一化为默认身份,供全链路比较与存储复用 - FlowRecord 增加发起/提交/当前/转交/干预五组身份字段,FlowTodoRecord 增加三组身份字段 - FlowRecordEntity/FlowTodoRecordEntity 与 Convertor 双向映射,历史数据 identity 为 null 时读取归一化为空串 - GroovyScriptRequest 暴露 getCreatedOperatorIdentity/getCurrentOperatorIdentity/getSubmitOperatorIdentity - FlowOperator 响应体携带身份,保留 (id, name) 双参构造器保证下游源码兼容 - P1 不改变任何判定逻辑与待办合并键格式,identity 为空时行为与历史一致 Closes #288 --- .../flow/operator/IFlowOperator.java | 36 ++++ .../flow/operator/OperatorIdentity.java | 66 ++++++ .../flow/pojo/response/FlowContent.java | 15 +- .../flow/pojo/response/FlowOperator.java | 25 ++- .../com/codingapi/flow/record/FlowRecord.java | 38 ++++ .../codingapi/flow/record/FlowTodoRecord.java | 22 ++ .../script/request/GroovyScriptRequest.java | 34 +++ .../flow/operator/OperatorIdentityTest.java | 131 ++++++++++++ .../flow/pojo/response/FlowOperatorTest.java | 60 ++++++ .../CopyOnReadFlowRecordRepository.java | 7 +- .../GroovyScriptRequestIdentityTest.java | 94 +++++++++ .../FlowOperatorIdentityRecordTest.java | 194 ++++++++++++++++++ .../java/com/codingapi/flow/user/User.java | 34 ++- .../infra/convert/FlowRecordConvertor.java | 14 +- .../convert/FlowTodoRecordConvertor.java | 10 +- .../flow/infra/entity/FlowRecordEntity.java | 25 +++ .../infra/entity/FlowTodoRecordEntity.java | 15 ++ .../FlowRecordIdentityConvertorTest.java | 152 ++++++++++++++ 18 files changed, 959 insertions(+), 13 deletions(-) create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityTest.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/pojo/response/FlowOperatorTest.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/script/request/GroovyScriptRequestIdentityTest.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowOperatorIdentityRecordTest.java create mode 100644 flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowRecordIdentityConvertorTest.java diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java index b868fb69..a52d75e0 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java @@ -3,8 +3,13 @@ import com.codingapi.flow.script.request.GroovyScriptRequest; import com.codingapi.springboot.framework.user.IUser; +import java.util.Map; + /** * 流程参与用户 + * + *

支持同一用户以多种身份参与流程(issue #288):身份标识由下游业务自定义, + * 框架不解释其含义,仅做透传、存储与比较。 */ public interface IFlowOperator extends IUser { @@ -24,6 +29,37 @@ public interface IFlowOperator extends IUser { String getName(); + /** + * 获取身份标识 + * + *

身份标识的取值语义由下游自定义(部门 id、岗位编码或复合标识均可), + * 框架只做透传、存储与比较,不做任何解释。 + *

+ * + * @return 身份标识,默认返回空串 + * @see OperatorIdentity + */ + default String getIdentity() { + return OperatorIdentity.DEFAULT; + } + + + /** + * 获取身份附加属性 + * + *

供 Groovy 脚本与前端展示使用的动态字段(如部门名称、岗位名称), + * 下游可自由定义 key/value。框架只透传,不落库、不参与任何引擎判定。 + * + * @return 身份附加属性,默认返回空集合 + */ + default Map getIdentityAttributes() { + return Map.of(); + } + + /** * 是否流程管理员 * 流程管理员可以强制干预流程 diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java new file mode 100644 index 00000000..b31beb23 --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java @@ -0,0 +1,66 @@ +package com.codingapi.flow.operator; + +/** + * 身份标识归一化工具。 + * + *

流程引擎不解释身份标识的业务语义,只做透传、存储与比较。为了让「存量数据」与 + * 「未启用多身份的业务」保持完全一致的行为,统一约定: + *

+ * + * @see IFlowOperator#getIdentity() + */ +public final class OperatorIdentity { + + /** + * 默认身份标识 + */ + public static final String DEFAULT = ""; + + private OperatorIdentity() { + } + + /** + * 归一化身份标识:null 转为空串,其余原样返回。 + * + * @param identity 原始身份标识 + * @return 归一化后的身份标识,不为 null + */ + public static String normalize(String identity) { + return identity == null ? DEFAULT : identity; + } + + /** + * 是否为默认身份(null 或空串)。 + * + * @param identity 身份标识 + * @return true 表示默认身份 + */ + public static boolean isDefault(String identity) { + return normalize(identity).isEmpty(); + } + + /** + * 读取操作者的身份标识,操作者为 null 时返回默认身份。 + * + * @param operator 流程参与用户 + * @return 归一化后的身份标识 + */ + public static String of(IFlowOperator operator) { + return operator == null ? DEFAULT : normalize(operator.getIdentity()); + } + + /** + * 判断两个身份标识是否相同(null 安全)。 + * + * @param left 身份标识 + * @param right 身份标识 + * @return true 表示同一身份 + */ + public static boolean same(String left, String right) { + return normalize(left).equals(normalize(right)); + } +} 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 8a935f29..055c70a5 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 @@ -319,7 +319,8 @@ private List loadCurrentNodeOperators(FlowSession flowSession) { continue; } operators.putIfAbsent(record.getCurrentOperatorId(), - new FlowOperator(record.getCurrentOperatorId(), record.getCurrentOperatorName())); + new FlowOperator(record.getCurrentOperatorId(), record.getCurrentOperatorName(), + record.getCurrentOperatorIdentity())); } return List.copyOf(operators.values()); } @@ -336,7 +337,8 @@ public void pushWorkflow(Workflow workflow) { public void pushRecords(FlowRecord record, List mergeRecords) { this.recordId = record.getId(); this.processId = record.getProcessId(); - this.createOperator = new FlowOperator(record.getCreateOperatorId(), record.getCreateOperatorName()); + this.createOperator = new FlowOperator(record.getCreateOperatorId(), record.getCreateOperatorName(), + record.getCreateOperatorIdentity()); this.mergeable = record.isTodo() && record.isMergeable(); this.flowState = record.getFlowState(); this.recordState = record.getRecordState(); @@ -352,8 +354,10 @@ public void pushRecords(FlowRecord record, List mergeRecords) { body.setNodeId(item.getNodeId()); body.setNodeName(item.getNodeName()); body.setNodeType(item.getNodeType()); - body.setSubmitOperator(new FlowOperator(item.getSubmitOperatorId(), item.getSubmitOperatorName())); - body.setCreatedOperator(new FlowOperator(item.getCreateOperatorId(), item.getCreateOperatorName())); + body.setSubmitOperator(new FlowOperator(item.getSubmitOperatorId(), item.getSubmitOperatorName(), + item.getSubmitOperatorIdentity())); + body.setCreatedOperator(new FlowOperator(item.getCreateOperatorId(), item.getCreateOperatorName(), + item.getCreateOperatorIdentity())); body.setTitle(item.getTitle()); body.setData(item.getFormData()); body.setRecordState(item.getRecordState()); @@ -376,7 +380,8 @@ public void pushHistory(Workflow workflow, List historyRecords) { history.setNodeId(item.getNodeId()); history.setNodeType(item.getNodeType()); history.setUpdateTime(item.getUpdateTime()); - history.setCurrentOperator(new FlowOperator(item.getCurrentOperatorId(), item.getCurrentOperatorName())); + history.setCurrentOperator(new FlowOperator(item.getCurrentOperatorId(), item.getCurrentOperatorName(), + item.getCurrentOperatorIdentity())); this.histories.add(history); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowOperator.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowOperator.java index 82a61b1c..fa499a29 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowOperator.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowOperator.java @@ -1,21 +1,42 @@ package com.codingapi.flow.pojo.response; import com.codingapi.flow.operator.IFlowOperator; -import lombok.AllArgsConstructor; +import com.codingapi.flow.operator.OperatorIdentity; import lombok.Data; /** * 流程审批人 + * + *

响应体为公开契约:保留 (id, name) 双参构造器保证下游源码兼容, + * 身份标识通过新增构造器或 setter 补充(issue #288)。 */ @Data -@AllArgsConstructor public class FlowOperator { private long id; private String name; + /** + * 身份标识,空串表示默认身份 + */ + private String identity; + + /** + * 兼容历史调用方的双参构造器,身份为默认身份 + */ + public FlowOperator(long id, String name) { + this(id, name, OperatorIdentity.DEFAULT); + } + + public FlowOperator(long id, String name, String identity) { + this.id = id; + this.name = name; + this.identity = OperatorIdentity.normalize(identity); + } + public FlowOperator(IFlowOperator flowOperator) { this.id = flowOperator.getUserId(); this.name = flowOperator.getName(); + this.identity = OperatorIdentity.of(flowOperator); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java index bd0fa18e..8471cf13 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java @@ -9,6 +9,7 @@ import com.codingapi.flow.node.nodes.EndNode; import com.codingapi.flow.node.nodes.NotifyNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.session.FlowAdvice; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; @@ -266,6 +267,34 @@ public class FlowRecord { */ private int parallelBranchTotal; + /** + * 发起者身份标识(issue #288) + *

框架不解释其语义,空串表示默认身份,与未启用多身份的历史数据完全一致。 + * + * @see com.codingapi.flow.operator.OperatorIdentity + */ + private String createOperatorIdentity; + + /** + * 提交审批人身份标识(issue #288) + */ + private String submitOperatorIdentity; + + /** + * 当前审批人身份标识(issue #288) + */ + private String currentOperatorIdentity; + + /** + * 代替的审批人身份标识(issue #288) + */ + private String forwardOperatorIdentity; + + /** + * 被干预的用户身份标识(issue #288) + */ + private String interferedOperatorIdentity; + /** * 数据合并的依据,当开启时值为固定值,否则为随机数据 *

合并依据由 {@link RecordMergeStrategy.MergeType} 决定: @@ -326,12 +355,17 @@ public FlowRecord(FlowSession flowSession, int nodeOrder) { this.processId = FlowIDGeneratorGatewayContext.getInstance().generateProcessId(); this.createOperatorId = flowSession.getCreatedOperator().getUserId(); this.createOperatorName = flowSession.getCreatedOperator().getName(); + this.createOperatorIdentity = OperatorIdentity.of(flowSession.getCreatedOperator()); + // 身份字段统一以空串兜底,避免出现 null 与空串两种「默认身份」表达 + this.forwardOperatorIdentity = OperatorIdentity.DEFAULT; + this.interferedOperatorIdentity = OperatorIdentity.DEFAULT; // 是否转交之后的人来审批的判断 if (currentOperator.equals(sourceOperator)) { this.forwardOperatorId = 0; } else { this.forwardOperatorId = sourceOperator.getUserId(); this.forwardOperatorName = sourceOperator.getName(); + this.forwardOperatorIdentity = OperatorIdentity.of(sourceOperator); } this.recordState = SATE_RECORD_TODO; this.actionId = action.id(); @@ -340,9 +374,11 @@ public FlowRecord(FlowSession flowSession, int nodeOrder) { this.currentOperatorId = currentOperator.getUserId(); this.currentOperatorName = currentOperator.getName(); + this.currentOperatorIdentity = OperatorIdentity.of(currentOperator); this.submitOperatorId = flowSession.getSubmitOperatorId(); this.submitOperatorName = flowSession.getSubmitOperatorName(); + this.submitOperatorIdentity = OperatorIdentity.of(flowSession.getSubmitOperator()); this.advice = flowSession.getAdvice().getAdvice(); this.signKey = flowSession.getAdvice().getSignKey(); @@ -559,6 +595,7 @@ public void update(FlowSession flowSession, boolean pass) { if (flowSession.getCurrentOperator().getUserId() != this.currentOperatorId) { this.interferedOperatorId = flowSession.getCurrentOperator().getUserId(); this.interferedOperatorName = flowSession.getCurrentOperator().getName(); + this.interferedOperatorIdentity = OperatorIdentity.of(flowSession.getCurrentOperator()); } if (flowAdvice != null) { @@ -694,6 +731,7 @@ public FlowRecord create(FlowSession flowSession) { FlowRecord flowRecord = new FlowRecord(flowSession, 0); flowRecord.currentOperatorId = flowSession.getCurrentOperator().getUserId(); flowRecord.currentOperatorName = flowSession.getCurrentOperator().getName(); + flowRecord.currentOperatorIdentity = OperatorIdentity.of(flowSession.getCurrentOperator()); return flowRecord; } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowTodoRecord.java b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowTodoRecord.java index 09206513..1ef55639 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowTodoRecord.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowTodoRecord.java @@ -1,5 +1,6 @@ package com.codingapi.flow.record; +import com.codingapi.flow.operator.OperatorIdentity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @@ -120,6 +121,24 @@ public class FlowTodoRecord { */ private long timeoutTime; + /** + * 当前审批人身份标识(issue #288) + *

框架不解释其语义,空串表示默认身份,与未启用多身份的历史数据完全一致。 + * + * @see com.codingapi.flow.operator.OperatorIdentity + */ + private String currentOperatorIdentity; + + /** + * 提交审批人身份标识(issue #288) + */ + private String submitOperatorIdentity; + + /** + * 发起者身份标识(issue #288) + */ + private String createOperatorIdentity; + public FlowTodoRecord(FlowRecord flowRecord) { this.update(flowRecord); @@ -144,6 +163,9 @@ public void update(FlowRecord flowRecord) { this.createTime = flowRecord.getCreateTime(); this.createOperatorId = flowRecord.getCreateOperatorId(); this.createOperatorName = flowRecord.getCreateOperatorName(); + this.currentOperatorIdentity = OperatorIdentity.normalize(flowRecord.getCurrentOperatorIdentity()); + this.submitOperatorIdentity = OperatorIdentity.normalize(flowRecord.getSubmitOperatorIdentity()); + this.createOperatorIdentity = OperatorIdentity.normalize(flowRecord.getCreateOperatorIdentity()); this.todoKey = flowRecord.getTodoKey(); this.mergeable = flowRecord.isMergeable(); this.recordId = flowRecord.getId(); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptRequest.java index d030ffaf..84bb2e02 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptRequest.java @@ -4,6 +4,7 @@ import com.codingapi.flow.form.FormData; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.pojo.request.FlowCreateRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; @@ -281,6 +282,39 @@ public String getSubmitOperatorName() { } + /** + * 流程创建者身份标识(issue #288) + *

身份标识由下游自定义,框架不做解释;空串表示默认身份。 + * 可用于按部门、岗位等身份差异决定节点分支。 + * + * @return 创建者身份标识 + */ + @ScriptFunction(name = "getCreatedOperatorIdentity", description = "获取流程创建者身份标识") + public String getCreatedOperatorIdentity() { + return OperatorIdentity.of(this.createdOperator); + } + + /** + * 流程审批者身份标识(issue #288) + * + * @return 当前审批者身份标识 + */ + @ScriptFunction(name = "getCurrentOperatorIdentity", description = "获取流程审批者身份标识") + public String getCurrentOperatorIdentity() { + return OperatorIdentity.of(this.currentOperator); + } + + /** + * 流程提交人身份标识(issue #288) + * + * @return 提交人身份标识 + */ + @ScriptFunction(name = "getSubmitOperatorIdentity", description = "获取流程提交人身份标识") + public String getSubmitOperatorIdentity() { + return OperatorIdentity.of(this.submitOperator); + } + + /** * 获取开始节点 * diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityTest.java new file mode 100644 index 00000000..73265cb6 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityTest.java @@ -0,0 +1,131 @@ +package com.codingapi.flow.operator; + +import com.codingapi.flow.script.request.GroovyScriptRequest; +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.Test; + +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.assertTrue; + +/** + * 身份标识归一化规则测试。 + * + *

约定的核心规则:null 与空串等价,统一视为「默认身份」(issue #288)。 + */ +class OperatorIdentityTest { + + @Test + void should_normalize_null_to_empty() { + // given + String identity = null; + + // when + String normalized = OperatorIdentity.normalize(identity); + + // then + assertEquals("", normalized); + } + + @Test + void should_keep_identity_value() { + // given + String identity = "department1"; + + // when + String normalized = OperatorIdentity.normalize(identity); + + // then + assertEquals("department1", normalized); + } + + @Test + void should_treat_null_and_empty_as_default() { + assertTrue(OperatorIdentity.isDefault(null)); + assertTrue(OperatorIdentity.isDefault("")); + assertFalse(OperatorIdentity.isDefault("department1")); + } + + @Test + void should_compare_identities_null_safe() { + assertTrue(OperatorIdentity.same(null, "")); + assertTrue(OperatorIdentity.same("department1", "department1")); + assertFalse(OperatorIdentity.same("department1", "department2")); + assertFalse(OperatorIdentity.same(null, "department1")); + } + + @Test + void should_read_identity_from_operator_and_handle_null_operator() { + // given + IFlowOperator operator = new User(1, "张三"); + + // when & then + assertEquals("", OperatorIdentity.of(operator)); + assertEquals("", OperatorIdentity.of(null)); + } + + @Test + void should_provide_default_identity_on_operator_interface() { + // given:未实现身份的存量操作者(测试 User 未覆盖 default 方法) + IFlowOperator operator = new IFlowOperator() { + @Override + public long getUserId() { + return 1; + } + + @Override + public String getName() { + return "张三"; + } + + @Override + public boolean isFlowManager() { + return false; + } + + @Override + public IFlowOperator forwardOperator(GroovyScriptRequest request) { + return null; + } + }; + + // when & then:默认身份为空串,附加属性为空集合,保证存量实现零改动可用 + assertEquals("", operator.getIdentity()); + assertTrue(operator.getIdentityAttributes().isEmpty()); + } + + @Test + void should_allow_downstream_override_identity() { + // given + IFlowOperator operator = new IdentityUser(1, "张三", "department1"); + + // when & then + assertEquals("department1", OperatorIdentity.of(operator)); + assertEquals("部门一", operator.getIdentityAttributes().get("deptName")); + } + + /** + * 模拟下游自定义身份的操作者实现。 + */ + private static class IdentityUser extends User { + + private final String identity; + + IdentityUser(long userId, String name, String identity) { + super(userId, name); + this.identity = identity; + } + + @Override + public String getIdentity() { + return identity; + } + + @Override + public Map getIdentityAttributes() { + return Map.of("deptName", "部门一"); + } + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/pojo/response/FlowOperatorTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/pojo/response/FlowOperatorTest.java new file mode 100644 index 00000000..35a0aba8 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/pojo/response/FlowOperatorTest.java @@ -0,0 +1,60 @@ +package com.codingapi.flow.pojo.response; + +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * 响应体操作者身份字段测试(issue #288 P1)。 + * + *

响应体为公开契约,必须保留双参构造器以保证下游实现源码兼容。 + */ +class FlowOperatorTest { + + /** + * 测试目标:存量双参构造器仍然可用,身份默认空串。 + * 前置条件:使用 (id, name) 构造。 + * 执行步骤:读取身份。 + * 期望断言:身份为空串,不出现 null。 + */ + @Test + void should_keep_two_args_constructor_and_default_identity() { + FlowOperator operator = new FlowOperator(1L, "张三"); + + assertEquals(1L, operator.getId()); + assertEquals("张三", operator.getName()); + assertEquals("", operator.getIdentity()); + } + + /** + * 测试目标:由流程操作者构建响应体时携带身份。 + * 前置条件:操作者身份为 department1。 + * 执行步骤:构造响应体。 + * 期望断言:id、名称、身份均正确。 + */ + @Test + void should_take_identity_from_flow_operator() { + IFlowOperator user = User.withIdentity(2, "boss", "department2"); + + FlowOperator operator = new FlowOperator(user); + + assertEquals(2L, operator.getId()); + assertEquals("boss", operator.getName()); + assertEquals("department2", operator.getIdentity()); + } + + /** + * 测试目标:三参构造器支持从记录直接还原带身份的响应体。 + * 前置条件:记录中保存了审批人 id、名称与身份。 + * 执行步骤:构造响应体。 + * 期望断言:身份被正确设置。 + */ + @Test + void should_support_three_args_constructor() { + FlowOperator operator = new FlowOperator(3L, "lorne", "department3"); + + assertEquals("department3", operator.getIdentity()); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/repository/CopyOnReadFlowRecordRepository.java b/flow-engine-framework/src/test/java/com/codingapi/flow/repository/CopyOnReadFlowRecordRepository.java index 13f43cb0..2ee38d02 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/repository/CopyOnReadFlowRecordRepository.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/repository/CopyOnReadFlowRecordRepository.java @@ -142,6 +142,11 @@ private static FlowRecord copy(FlowRecord record) { record.getDelegateId(), record.getParallelId(), record.getParallelBranchNodeId(), - record.getParallelBranchTotal()); + record.getParallelBranchTotal(), + record.getCreateOperatorIdentity(), + record.getSubmitOperatorIdentity(), + record.getCurrentOperatorIdentity(), + record.getForwardOperatorIdentity(), + record.getInterferedOperatorIdentity()); } } \ No newline at end of file diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/script/request/GroovyScriptRequestIdentityTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/script/request/GroovyScriptRequestIdentityTest.java new file mode 100644 index 00000000..eceaf2c8 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/script/request/GroovyScriptRequestIdentityTest.java @@ -0,0 +1,94 @@ +package com.codingapi.flow.script.request; + +import com.codingapi.flow.factory.MyFlowServiceFactory; +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.script.factory.FlowGroovyScriptFactory; +import com.codingapi.flow.script.node.NodeTitleScript; +import com.codingapi.flow.session.FlowSession; +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * 脚本请求对象的身份标识透传测试(issue #288 P1)。 + * + *

验证下游可通过 Groovy 脚本读取发起人 / 提交人 / 当前审批人的身份标识, + * 用于实现节点分支差异与人员差异。 + */ +class GroovyScriptRequestIdentityTest { + + private final MyFlowServiceFactory factory = new MyFlowServiceFactory(); + + private FlowSession session(IFlowOperator current, IFlowOperator created, IFlowOperator submit) { + return new FlowSession( + factory.repositoryHolder, + current, + created, + submit, + null, + null, + null, + null, + null, + null, + 0, + null + ); + } + + /** + * 测试目标:请求对象直接读取三类操作者的身份标识。 + * 前置条件:当前审批人、发起人、提交人分别带不同身份。 + * 执行步骤:由会话构建 GroovyScriptRequest 并读取身份。 + * 期望断言:三个身份方法分别返回各自身份。 + */ + @Test + void should_expose_identity_getters() { + IFlowOperator current = User.withIdentity(2, "boss", "department2"); + IFlowOperator created = User.withIdentity(1, "user1", "department1"); + + GroovyScriptRequest request = new GroovyScriptRequest(session(current, created, created)); + + assertEquals("department2", request.getCurrentOperatorIdentity()); + assertEquals("department1", request.getCreatedOperatorIdentity()); + assertEquals("department1", request.getSubmitOperatorIdentity()); + } + + /** + * 测试目标:存量用户未实现身份时,脚本读取到默认身份(空串)而非 null。 + * 前置条件:三类操作者均未覆盖 getIdentity()。 + * 执行步骤:构建请求并读取身份。 + * 期望断言:三个身份方法均返回空串。 + */ + @Test + void should_return_default_identity_when_operator_has_no_identity() { + IFlowOperator user = new User(1, "user1"); + + GroovyScriptRequest request = new GroovyScriptRequest(session(user, user, user)); + + assertEquals("", request.getCurrentOperatorIdentity()); + assertEquals("", request.getCreatedOperatorIdentity()); + assertEquals("", request.getSubmitOperatorIdentity()); + } + + /** + * 测试目标:Groovy 脚本内可通过 request 读取当前审批人身份(节点分支差异的基础能力)。 + * 前置条件:当前审批人身份为 department2。 + * 执行步骤:执行节点标题脚本返回身份标识。 + * 期望断言:脚本返回 department2。 + */ + @Test + void should_read_identity_in_groovy_script() { + IFlowOperator current = User.withIdentity(2, "boss", "department2"); + IFlowOperator created = User.withIdentity(1, "user1", "department1"); + + NodeTitleScript script = new NodeTitleScript( + FlowGroovyScriptFactory.createNodeTitleScript("def run(request){return request.getCurrentOperatorIdentity()}") + .getKey()); + + String identity = script.execute(session(current, created, created)); + + assertEquals("department2", identity); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowOperatorIdentityRecordTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowOperatorIdentityRecordTest.java new file mode 100644 index 00000000..34c6174c --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowOperatorIdentityRecordTest.java @@ -0,0 +1,194 @@ +package com.codingapi.flow.service; + +import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.action.actions.CustomAction; +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.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.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.record.FlowRecord; +import com.codingapi.flow.record.FlowTodoRecord; +import com.codingapi.flow.script.factory.FlowGroovyScriptFactory; +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 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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 流程记录身份标识落库测试(issue #288 P1)。 + * + *

P1 只做身份透传与存储,不改变任何判定逻辑:身份为空时记录行为与历史完全一致。 + */ +class FlowOperatorIdentityRecordTest { + + private MyFlowServiceFactory newFactory(User... users) { + MyFlowServiceFactory factory = new MyFlowServiceFactory(); + for (User user : users) { + factory.userGateway.save(user); + } + GatewayContext.getInstance().setFlowOperatorGateway(factory.userGateway); + return factory; + } + + private Workflow buildLeaveWorkflow(MyFlowServiceFactory factory, User creator) { + FlowForm form = FlowFormBuilder.builder() + .name("请假流程") + .code("leave") + .addField("请假人", "name", DataType.STRING) + .addField("请假天数", "days", DataType.INTEGER) + .build(); + + StartNode startNode = StartNode.builder() + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(FormFieldPermissionsBuilder.builder() + .addPermission("leave", "name", PermissionType.WRITE) + .addPermission("leave", "days", PermissionType.WRITE) + .build())) + .build()) + .actions(ActionBuilder.builder() + .addAction(CustomAction.defaultAction()) + .build()) + .build(); + + ApprovalNode bossNode = ApprovalNode.builder() + .name("经理审批") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(FormFieldPermissionsBuilder.builder() + .addPermission("leave", "name", PermissionType.WRITE) + .addPermission("leave", "days", PermissionType.WRITE) + .build())) + .addStrategy(new OperatorLoadStrategy( + FlowGroovyScriptFactory.createOperatorLoadScript("def run(request){return [2]}").getKey())) + .build()) + .build(); + + EndNode endNode = EndNode.builder().build(); + + Workflow workflow = WorkflowBuilder.builder() + .title("请假流程") + .code("leave") + .createdOperator(creator) + .form(form) + .addNode(startNode) + .addNode(bossNode) + .addNode(endNode) + .build(); + + factory.workflowService.saveWorkflow(workflow); + return workflow; + } + + private Map formData() { + return Map.of("name", "lorne", "days", 1); + } + + private List startActions(Workflow workflow) { + return workflow.getStartNode().actionManager().getActions(); + } + + private long createAtStartNode(MyFlowServiceFactory factory, Workflow workflow, User user) { + FlowCreateRequest createRequest = new FlowCreateRequest(); + createRequest.setWorkCode(workflow.getCode()); + createRequest.setFormData(formData()); + createRequest.setActionId(startActions(workflow).get(0).id()); + createRequest.setOperatorId(user.getUserId()); + return factory.flowService.create(createRequest); + } + + /** + * 场景:发起人带身份发起流程 → 开始节点记录与待办记录都落发起人身份。 + */ + @Test + void should_store_creator_identity_on_start_record_and_todo() { + User creator = User.withIdentity(1, "user1", "department1"); + User boss = User.withIdentity(2, "boss", "department2"); + MyFlowServiceFactory factory = newFactory(creator, boss); + + Workflow workflow = buildLeaveWorkflow(factory, creator); + long recordId = createAtStartNode(factory, workflow, creator); + + FlowRecord record = factory.flowRecordRepository.get(recordId); + assertNotNull(record); + assertEquals("department1", record.getCreateOperatorIdentity()); + assertEquals("department1", record.getSubmitOperatorIdentity()); + assertEquals("department1", record.getCurrentOperatorIdentity()); + assertEquals("", record.getForwardOperatorIdentity()); + assertEquals("", record.getInterferedOperatorIdentity()); + + List todos = factory.flowTodoRecordRepository.findByOperatorId(creator.getUserId()); + assertEquals(1, todos.size()); + FlowTodoRecord todo = todos.get(0); + assertEquals("department1", todo.getCreateOperatorIdentity()); + assertEquals("department1", todo.getSubmitOperatorIdentity()); + assertEquals("department1", todo.getCurrentOperatorIdentity()); + } + + /** + * 场景:存量用户未实现身份 → 全部落默认身份(空串),与历史行为一致。 + */ + @Test + void should_store_default_identity_when_operator_has_no_identity() { + User creator = new User(1, "user1"); + User boss = new User(2, "boss"); + MyFlowServiceFactory factory = newFactory(creator, boss); + + Workflow workflow = buildLeaveWorkflow(factory, creator); + long recordId = createAtStartNode(factory, workflow, creator); + + FlowRecord record = factory.flowRecordRepository.get(recordId); + assertNotNull(record); + assertTrue(record.getCreateOperatorIdentity().isEmpty()); + assertTrue(record.getSubmitOperatorIdentity().isEmpty()); + assertTrue(record.getCurrentOperatorIdentity().isEmpty()); + } + + /** + * 场景:发起人办理后流转到审批人 → 新记录的当前审批人身份来自审批人自身,发起/提交身份保持不变。 + */ + @Test + void should_store_approver_identity_after_pass() { + User creator = User.withIdentity(1, "user1", "department1"); + User boss = User.withIdentity(2, "boss", "department2"); + MyFlowServiceFactory factory = newFactory(creator, boss); + + Workflow workflow = buildLeaveWorkflow(factory, creator); + long recordId = createAtStartNode(factory, workflow, creator); + + FlowActionRequest actionRequest = new FlowActionRequest(); + actionRequest.setFormData(formData()); + actionRequest.setRecordId(recordId); + actionRequest.setAdvice(new FlowAdviceBody(startActions(workflow).get(0).id(), "同意", creator.getUserId())); + factory.flowService.action(actionRequest); + + List bossTodos = factory.flowRecordRepository.findTodoByOperator(boss.getUserId()); + assertEquals(1, bossTodos.size()); + FlowRecord bossRecord = bossTodos.get(0); + assertEquals("department2", bossRecord.getCurrentOperatorIdentity()); + assertEquals("department1", bossRecord.getCreateOperatorIdentity()); + assertEquals("department1", bossRecord.getSubmitOperatorIdentity()); + + List bossTodoRecords = factory.flowTodoRecordRepository.findByOperatorId(boss.getUserId()); + assertEquals(1, bossTodoRecords.size()); + assertEquals("department2", bossTodoRecords.get(0).getCurrentOperatorIdentity()); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java b/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java index 19ce3952..727a43f1 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java @@ -3,30 +3,48 @@ import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.script.request.GroovyScriptRequest; +import java.util.Map; + public class User implements IFlowOperator { private final long userId; private final String name; private final boolean manager; private final User forwardOperator; + /** + * 身份标识(issue #288),为空表示默认身份 + */ + private final String identity; public User(long userId, String name) { - this(userId, name, false, null); + this(userId, name, false, null, ""); } public User(long userId, String name, boolean manager) { - this(userId, name, manager, null); + this(userId, name, manager, null, ""); } public User(long userId, String name, User forwardOperator) { - this(userId, name, false, forwardOperator); + this(userId, name, false, forwardOperator, ""); } public User(long userId, String name, boolean manager, User forwardOperator) { + this(userId, name, manager, forwardOperator, ""); + } + + protected User(long userId, String name, boolean manager, User forwardOperator, String identity) { this.userId = userId; this.name = name; this.manager = manager; this.forwardOperator = forwardOperator; + this.identity = identity; + } + + /** + * 创建带身份标识的用户(测试多身份场景) + */ + public static User withIdentity(long userId, String name, String identity) { + return new User(userId, name, false, null, identity); } @Override @@ -44,6 +62,16 @@ public boolean isFlowManager() { return manager; } + @Override + public String getIdentity() { + return identity; + } + + @Override + public Map getIdentityAttributes() { + return identity == null || identity.isEmpty() ? Map.of() : Map.of("identityName", identity); + } + @Override public IFlowOperator forwardOperator(GroovyScriptRequest request) { return forwardOperator; diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java index 9e34a9cf..07448756 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java @@ -2,6 +2,7 @@ import com.codingapi.flow.infra.entity.FlowRecordEntity; import com.codingapi.flow.infra.entity.convert.MapConvertor; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.strategy.node.RecordMergeStrategy; @@ -61,7 +62,13 @@ public static FlowRecord convert(FlowRecordEntity entity) { entity.getDelegateId(), entity.getParallelId(), entity.getParallelBranchNodeId(), - entity.getParallelBranchTotal()); + entity.getParallelBranchTotal(), + // issue #288:历史数据 identity 列为 null,读取时统一归一化为默认身份 + OperatorIdentity.normalize(entity.getCreateOperatorIdentity()), + OperatorIdentity.normalize(entity.getSubmitOperatorIdentity()), + OperatorIdentity.normalize(entity.getCurrentOperatorIdentity()), + OperatorIdentity.normalize(entity.getForwardOperatorIdentity()), + OperatorIdentity.normalize(entity.getInterferedOperatorIdentity())); } public static FlowRecordEntity convert(FlowRecord record) { @@ -120,6 +127,11 @@ public static FlowRecordEntity convert(FlowRecord record) { entity.setParallelId(record.getParallelId()); entity.setParallelBranchNodeId(record.getParallelBranchNodeId()); entity.setParallelBranchTotal(record.getParallelBranchTotal()); + entity.setCreateOperatorIdentity(OperatorIdentity.normalize(record.getCreateOperatorIdentity())); + entity.setSubmitOperatorIdentity(OperatorIdentity.normalize(record.getSubmitOperatorIdentity())); + entity.setCurrentOperatorIdentity(OperatorIdentity.normalize(record.getCurrentOperatorIdentity())); + entity.setForwardOperatorIdentity(OperatorIdentity.normalize(record.getForwardOperatorIdentity())); + entity.setInterferedOperatorIdentity(OperatorIdentity.normalize(record.getInterferedOperatorIdentity())); return entity; } diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowTodoRecordConvertor.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowTodoRecordConvertor.java index 7de8f9c9..8339d93f 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowTodoRecordConvertor.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowTodoRecordConvertor.java @@ -1,6 +1,7 @@ package com.codingapi.flow.infra.convert; import com.codingapi.flow.infra.entity.FlowTodoRecordEntity; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.record.FlowTodoRecord; public class FlowTodoRecordConvertor { @@ -31,7 +32,11 @@ public static FlowTodoRecord convert(FlowTodoRecordEntity entity){ entity.getMargeCount(), entity.getMergeable(), entity.getRecordId(), - entity.getTimeoutTime() + entity.getTimeoutTime(), + // issue #288:历史数据 identity 列为 null,读取时统一归一化为默认身份 + OperatorIdentity.normalize(entity.getCurrentOperatorIdentity()), + OperatorIdentity.normalize(entity.getSubmitOperatorIdentity()), + OperatorIdentity.normalize(entity.getCreateOperatorIdentity()) ); } @@ -66,6 +71,9 @@ public static FlowTodoRecordEntity convert(FlowTodoRecord record){ entity.setMergeable(record.isMergeable()); entity.setRecordId(record.getRecordId()); entity.setTimeoutTime(record.getTimeoutTime()); + entity.setCurrentOperatorIdentity(OperatorIdentity.normalize(record.getCurrentOperatorIdentity())); + entity.setSubmitOperatorIdentity(OperatorIdentity.normalize(record.getSubmitOperatorIdentity())); + entity.setCreateOperatorIdentity(OperatorIdentity.normalize(record.getCreateOperatorIdentity())); return entity; } } diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowRecordEntity.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowRecordEntity.java index 9e8c8764..498f54cd 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowRecordEntity.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowRecordEntity.java @@ -100,6 +100,11 @@ public class FlowRecordEntity { */ private String currentOperatorName; + /** + * 当前审批人身份标识(issue #288),空值等价默认身份 + */ + private String currentOperatorIdentity; + /** * 提交审批人Id */ @@ -110,6 +115,11 @@ public class FlowRecordEntity { */ private String submitOperatorName; + /** + * 提交审批人身份标识(issue #288),空值等价默认身份 + */ + private String submitOperatorIdentity; + /** * 代替的审批人 */ @@ -120,6 +130,11 @@ public class FlowRecordEntity { */ private String forwardOperatorName; + /** + * 代替的审批人身份标识(issue #288),空值等价默认身份 + */ + private String forwardOperatorIdentity; + /** * 有那个节点退回的 */ @@ -180,6 +195,11 @@ public class FlowRecordEntity { */ private String createOperatorName; + /** + * 发起者身份标识(issue #288),空值等价默认身份 + */ + private String createOperatorIdentity; + /** * 异常信息 */ @@ -208,6 +228,11 @@ public class FlowRecordEntity { */ private String interferedOperatorName; + /** + * 被干预的用户身份标识(issue #288),空值等价默认身份 + */ + private String interferedOperatorIdentity; + /** * 委托记录id */ diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowTodoRecordEntity.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowTodoRecordEntity.java index 69387f30..e29cc601 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowTodoRecordEntity.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowTodoRecordEntity.java @@ -68,6 +68,11 @@ public class FlowTodoRecordEntity { */ private String currentOperatorName; + /** + * 当前审批人身份标识(issue #288),空值等价默认身份 + */ + private String currentOperatorIdentity; + /** * 提交审批人Id */ @@ -78,6 +83,11 @@ public class FlowTodoRecordEntity { */ private String submitOperatorName; + /** + * 提交审批人身份标识(issue #288),空值等价默认身份 + */ + private String submitOperatorIdentity; + /** * 创建时间 */ @@ -92,6 +102,11 @@ public class FlowTodoRecordEntity { */ private String createOperatorName; + /** + * 发起者身份标识(issue #288),空值等价默认身份 + */ + private String createOperatorIdentity; + /** * 合并记录id,当存在合并记录数据时待办记录数量不会增加,内容会更新至最新的待办数据信息。 * {@link FlowRecord#getTodoKey()} diff --git a/flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowRecordIdentityConvertorTest.java b/flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowRecordIdentityConvertorTest.java new file mode 100644 index 00000000..c229f53f --- /dev/null +++ b/flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowRecordIdentityConvertorTest.java @@ -0,0 +1,152 @@ +package com.codingapi.flow.infra.convert; + +import com.codingapi.flow.infra.entity.FlowRecordEntity; +import com.codingapi.flow.infra.entity.FlowTodoRecordEntity; +import com.codingapi.flow.record.FlowRecord; +import com.codingapi.flow.record.FlowTodoRecord; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * 流程记录身份字段的持久化映射测试(issue #288 P1)。 + * + *

覆盖两点:历史数据(identity 列为 null)读取为默认身份;身份在实体与领域对象之间不丢失。 + */ +class FlowRecordIdentityConvertorTest { + + /** + * 构造字段完整的流程记录实体,避免转换时的拆箱 NPE 干扰身份断言。 + */ + private FlowRecordEntity newRecordEntity() { + FlowRecordEntity entity = new FlowRecordEntity(); + entity.setId(1L); + entity.setWorkRuntimeId(1L); + entity.setWorkTitle("请假流程"); + entity.setWorkCode("leave"); + entity.setNodeId("start"); + entity.setNodeType("START"); + entity.setNodeName("开始"); + entity.setTitle("请假流程"); + entity.setFromId(0L); + entity.setParentId(0L); + entity.setReadTime(0L); + entity.setCurrentOperatorId(1L); + entity.setSubmitOperatorId(1L); + entity.setForwardOperatorId(0L); + entity.setNodeOrder(0); + entity.setHidden(false); + entity.setRevoked(false); + entity.setNotify(false); + entity.setRecordState(0); + entity.setFlowState(0); + entity.setUpdateTime(0L); + entity.setCreateTime(0L); + entity.setFinishTime(0L); + entity.setReadable(false); + entity.setCreateOperatorId(1L); + entity.setTimeoutTime(0L); + entity.setMergeable(false); + entity.setInterferedOperatorId(0L); + entity.setDelegateId(0L); + entity.setParallelBranchTotal(0); + return entity; + } + + /** + * 构造字段完整的待办记录实体。 + */ + private FlowTodoRecordEntity newTodoEntity() { + FlowTodoRecordEntity entity = new FlowTodoRecordEntity(); + entity.setId(1L); + entity.setWorkflowRuntimeId(1L); + entity.setReadTime(0L); + entity.setCurrentOperatorId(1L); + entity.setSubmitOperatorId(1L); + entity.setCreateTime(0L); + entity.setCreateOperatorId(1L); + entity.setMargeCount(0); + entity.setMergeable(false); + entity.setRecordId(1L); + entity.setTimeoutTime(0L); + return entity; + } + + /** + * 测试目标:历史数据没有 identity 列值时,读取后统一为默认身份(空串)。 + * 前置条件:实体 identity 字段全部为 null(升级前的存量数据)。 + * 执行步骤:实体 → 领域对象。 + * 期望断言:五组操作者身份均为空串,不出现 null。 + */ + @Test + void should_read_null_identity_as_default_for_legacy_record() { + FlowRecordEntity entity = newRecordEntity(); + + FlowRecord record = FlowRecordConvertor.convert(entity); + + assertAll( + () -> assertEquals("", record.getCreateOperatorIdentity()), + () -> assertEquals("", record.getSubmitOperatorIdentity()), + () -> assertEquals("", record.getCurrentOperatorIdentity()), + () -> assertEquals("", record.getForwardOperatorIdentity()), + () -> assertEquals("", record.getInterferedOperatorIdentity()) + ); + } + + /** + * 测试目标:身份标识在实体与领域对象之间双向转换不丢失。 + * 前置条件:实体带有五组不同的身份标识。 + * 执行步骤:实体 → 领域对象 → 实体。 + * 期望断言:两组身份值完全一致。 + */ + @Test + void should_round_trip_identity() { + FlowRecordEntity entity = newRecordEntity(); + entity.setCreateOperatorIdentity("department1"); + entity.setSubmitOperatorIdentity("department1"); + entity.setCurrentOperatorIdentity("department2"); + entity.setForwardOperatorIdentity("department3"); + entity.setInterferedOperatorIdentity("department4"); + + FlowRecord record = FlowRecordConvertor.convert(entity); + FlowRecordEntity roundTrip = FlowRecordConvertor.convert(record); + + assertAll( + () -> assertEquals("department1", record.getCreateOperatorIdentity()), + () -> assertEquals("department2", roundTrip.getCurrentOperatorIdentity()), + () -> assertEquals("department3", roundTrip.getForwardOperatorIdentity()), + () -> assertEquals("department4", roundTrip.getInterferedOperatorIdentity()) + ); + } + + /** + * 测试目标:待办记录的历史数据同样读取为默认身份,且身份可往返。 + * 前置条件:待办实体 identity 为 null 与有值两种情况。 + * 执行步骤:实体 → 领域对象 → 实体。 + * 期望断言:null 归一化为空串,有值身份保持。 + */ + @Test + void should_map_todo_record_identity() { + FlowTodoRecordEntity legacyEntity = newTodoEntity(); + FlowTodoRecord legacyTodo = FlowTodoRecordConvertor.convert(legacyEntity); + assertEquals("", legacyTodo.getCurrentOperatorIdentity()); + assertEquals("", legacyTodo.getSubmitOperatorIdentity()); + assertEquals("", legacyTodo.getCreateOperatorIdentity()); + + FlowTodoRecordEntity entity = newTodoEntity(); + entity.setId(2L); + entity.setCurrentOperatorIdentity("department2"); + entity.setSubmitOperatorIdentity("department1"); + entity.setCreateOperatorIdentity("department1"); + + FlowTodoRecord todo = FlowTodoRecordConvertor.convert(entity); + FlowTodoRecordEntity roundTrip = FlowTodoRecordConvertor.convert(todo); + + assertAll( + () -> assertEquals("department2", todo.getCurrentOperatorIdentity()), + () -> assertEquals("department1", roundTrip.getSubmitOperatorIdentity()), + () -> assertEquals("department1", roundTrip.getCreateOperatorIdentity()) + ); + } +} From 6e71220c798fd5a951739452c9953a450e74670c Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Mon, 23 Nov 2026 21:30:38 +0800 Subject: [PATCH 02/35] =?UTF-8?q?chore(release):=20=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E5=8F=B7=E5=8D=87=E7=BA=A7=E8=87=B3=200.3.0-SNAPSHOT=EF=BC=88?= =?UTF-8?q?=E4=B8=AD=E7=89=88=E6=9C=AC=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit issue #288 引入身份标识并将在 P2/P3 改变待办查询与审批判定语义, 属于行为变更,按中版本升级:0.2.x → 0.3.0。 - pom.xml:revision 默认值 0.1.0-SNAPSHOT(陈旧)→ 0.3.0-SNAPSHOT - AGENTS.md:同步当前版本描述 - 前端 flow-frontend 将在前端改造完成时一并升级至 0.3.0 并锁定版本号 Closes #288 --- AGENTS.md | 2 +- pom.xml | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2f249ec5..79843b7a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ ## 项目概述 -Flow Engine 是一个企业级工作流引擎,基于 Java 17 和 Spring Boot 3.5.9 构建(当前版本 0.1.0-SNAPSHOT)。 +Flow Engine 是一个企业级工作流引擎,基于 Java 17 和 Spring Boot 3.5.9 构建(当前版本 0.3.0-SNAPSHOT)。 ### 核心模块 diff --git a/pom.xml b/pom.xml index 03803276..3cc5c7b7 100644 --- a/pom.xml +++ b/pom.xml @@ -20,8 +20,9 @@ - - 0.1.0-SNAPSHOT + + + 0.3.0-SNAPSHOT yyyy-MM-dd HH:mm:ss From 07425ab2d1de04870f2eb763cb4cc701a992dd46 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Mon, 23 Nov 2026 21:51:19 +0800 Subject: [PATCH 03/35] =?UTF-8?q?feat:=20=E6=93=8D=E4=BD=9C=E8=80=85?= =?UTF-8?q?=E8=BA=AB=E4=BB=BD=E6=A0=87=E8=AF=86=E7=9A=84=E8=AF=B7=E6=B1=82?= =?UTF-8?q?=E9=80=8F=E4=BC=A0=E3=80=81=E5=BE=85=E5=8A=9E=E9=9A=94=E7=A6=BB?= =?UTF-8?q?=E4=B8=8E=E5=AE=A1=E6=89=B9=E5=88=A4=E5=AE=9A=EF=BC=88issue=20#?= =?UTF-8?q?288=20P2/P3=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P2 透传与隔离: - FlowOperatorGateway 新增 default get(id, identity),下游存量实现零改动;IRepositoryHolder 同步新增 getOperatorById(id, identity) - FlowOperatorLocalThreadCache 缓存键由 userId 升级为 (userId, identity),同一人两个身份不再串味 - 请求体统一支持 operatorIdentity:create/action/revoke/delete/urge/detail/processNodes/reissue/forceSync/subProcessReset - REST 层新增 operatorIdentity 参数(与 operatorId 对称),未传时取当前登录操作者身份 - getTodoKey 采用兼容追加策略:默认身份保持历史格式,非空身份追加 #identity,升级中的存量待办合并关系不断裂 - 待办/已办/抄送查询按 (operatorId, identity) 过滤,默认身份用 coalesce(identity,'') 覆盖历史 NULL 行 - FlowRecordContent 列表响应补充发起/提交/当前三组身份,供前端列表展示 P3 判定升级为 (userId, identity): - WorkflowStrategyManager.verifyOperator 增加身份比较(审批参与人校验) - 撤销/删除/催办/子流程重置的记录归属校验加入身份 - OperatorManager(加签/减签/转交/委托)按人员+身份匹配 - 加签待办队列查重、减签目标解析按 (userId, identity) 去重 - 提交人==审批人的自动通过判定、流程干预人识别加入身份 - 详情/流程树/延迟触发/子流程会话/转交/delegate 等按记录身份回查操作者 文档与升级: - 新增 docs/Integration/operator-identity.md(模型、SPI、请求参数、脚本用法、兼容性与限制) - 新增 docs/Integration/sql/0.3.0-operator-identity.sql(加列 + 索引建议 + 达梦说明 + 自检 SQL) - 示例工程 FlowOperatorGatewayImpl/User 提供身份参考实现(返回带身份的副本,避免污染持久化上下文) 验证:./mvnw clean install 全量通过,453 个用例 0 失败(framework 430 / infra 6 / api 2 / starter 8 / example 7)。 新增用例 13 个:待办合并键身份维度 4、缓存身份隔离 4、审批判定身份 3、待办查询身份隔离(含历史 NULL)2。 Closes #288 --- docs/Integration/README.md | 1 + docs/Integration/operator-identity.md | 188 +++++++++++++++++ .../sql/0.3.0-operator-identity.sql | 75 +++++++ docs/Integration/user-integration.md | 8 + .../com/codingapi/example/entity/User.java | 43 ++++ .../gateway/impl/FlowOperatorGatewayImpl.java | 18 ++ .../example/FlowTodoIdentityQueryTest.java | 185 +++++++++++++++++ .../flow/action/actions/AddAuditAction.java | 20 +- .../flow/action/actions/PassAction.java | 6 +- .../action/actions/ReduceAuditAction.java | 10 +- .../cache/FlowOperatorLocalThreadCache.java | 74 +++++-- .../flow/context/GatewayContext.java | 24 ++- .../flow/context/RepositoryHolderContext.java | 10 + .../flow/gateway/FlowOperatorGateway.java | 27 +++ .../flow/manager/OperatorManager.java | 36 +++- .../flow/manager/WorkflowStrategyManager.java | 24 ++- .../flow/mock/MockRepositoryHolder.java | 10 + .../codingapi/flow/node/BaseAuditNode.java | 7 +- .../codingapi/flow/node/nodes/StartNode.java | 5 +- .../flow/pojo/body/FlowAdviceBody.java | 10 + .../flow/pojo/request/FlowActionRequest.java | 11 + .../flow/pojo/request/FlowCreateRequest.java | 7 + .../flow/pojo/request/FlowDeleteRequest.java | 13 ++ .../flow/pojo/request/FlowDetailRequest.java | 17 +- .../pojo/request/FlowForceSyncRequest.java | 5 + .../pojo/request/FlowProcessNodeRequest.java | 19 +- .../flow/pojo/request/FlowReissueRequest.java | 5 + .../flow/pojo/request/FlowRevokeRequest.java | 13 ++ .../request/FlowSubProcessResetRequest.java | 5 + .../flow/pojo/request/FlowUrgeRequest.java | 13 ++ .../flow/pojo/response/FlowRecordContent.java | 22 ++ .../flow/query/FlowRecordQueryService.java | 29 +++ .../com/codingapi/flow/record/FlowRecord.java | 44 +++- .../flow/service/impl/FlowActionService.java | 11 +- .../flow/service/impl/FlowCreateService.java | 4 +- .../service/impl/FlowDelayTriggerService.java | 9 +- .../flow/service/impl/FlowDeleteService.java | 6 +- .../flow/service/impl/FlowDetailService.java | 8 +- .../service/impl/FlowForceSyncService.java | 2 +- .../service/impl/FlowProcessNodeService.java | 57 +++-- .../flow/service/impl/FlowReissueService.java | 6 +- .../flow/service/impl/FlowRevokeService.java | 5 +- .../impl/FlowSubProcessResetService.java | 6 +- .../flow/service/impl/FlowUrgeService.java | 6 +- .../impl/SubProcessSessionFactory.java | 9 +- .../flow/session/IRepositoryHolder.java | 17 +- .../FlowOperatorLocalThreadCacheTest.java | 85 ++++++++ .../flow/gateway/impl/UserGateway.java | 14 ++ .../flow/service/FlowTodoKeyIdentityTest.java | 196 ++++++++++++++++++ .../OperatorIdentityPermissionTest.java | 182 ++++++++++++++++ .../java/com/codingapi/flow/user/User.java | 8 + .../api/controller/FlowRecordController.java | 51 +++-- .../convert/FlowRecordContentConvertor.java | 7 + .../infra/jpa/FlowRecordEntityRepository.java | 34 +++ .../jpa/FlowTodoRecordEntityRepository.java | 19 ++ .../controller/FlowRecordQueryController.java | 27 ++- .../service/FlowRecordQueryServiceImpl.java | 22 ++ 57 files changed, 1661 insertions(+), 114 deletions(-) create mode 100644 docs/Integration/operator-identity.md create mode 100644 docs/Integration/sql/0.3.0-operator-identity.sql create mode 100644 flow-engine-example/src/test/java/com/codingapi/example/FlowTodoIdentityQueryTest.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCacheTest.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowTodoKeyIdentityTest.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityPermissionTest.java diff --git a/docs/Integration/README.md b/docs/Integration/README.md index 7d770cc8..e1be4345 100644 --- a/docs/Integration/README.md +++ b/docs/Integration/README.md @@ -31,6 +31,7 @@ |------|------| | [快速开始](./quick-start.md) | 最小集成步骤:引入依赖 → 提供 Bean → 编写流程 → 发起流程 | | [流程用户体系](./user-integration.md) | `FlowOperatorGateway` / `IFlowOperator` / `GatewayContext` / 线程缓存 / 当前登录人 | +| [多身份参与](./operator-identity.md) | 同一人员多身份:身份 SPI、请求声明、待办隔离、判定规则、升级 DDL | | [流程默认脚本](./script-integration.md) | 12 种脚本类型、`GroovyScriptRequest` 完整 API、`$bind`、默认脚本替换、脚本生命周期 | | [流程事件机制](./event-integration.md) | 9 种事件、`EventPusher`、`IHandler` 订阅、异步分发管道、事务变体、推送时机 | | [仓储抽象与持久化](./repository-integration.md) | `IRepositoryHolder`、12 个仓储接口(含 11 个 JPA 实现 + 需自行实现的 `NodeViewJavaScriptRepository`)、脚本仓储、锁机制 | diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md new file mode 100644 index 00000000..9f5ee36d --- /dev/null +++ b/docs/Integration/operator-identity.md @@ -0,0 +1,188 @@ +# 多身份参与(Operator Identity) + +> 面向业务项目的集成说明,对应 issue #288。引擎只负责**透传、存储与比较**身份标识,不解释其业务语义,也不内建组织模型。 + +## 1. 解决什么问题 + +一个用户可能同时隶属多个部门(或身兼多个岗位),在不同事项上以不同身份参与流程: + +| 差异类型 | 例子 | +|----------|------| +| 节点 / 分支差异 | user1 在 department1 发起需要「组长审核」,在 department2 发起则直接「部门经理审核」 | +| 人员差异 | department1 的经理是 boss1,department2 的经理是 boss2 | +| 待办差异 | user1 在 department1 / department2 各有一条待办,不能合并成一条 | + +0.2.x 的引擎只认 `userId`:记录、待办、权限判定全部按 userId 比较,上述场景无法表达。 + +## 2. 模型 + +身份标识是一个**不透明字符串**,由下游定义取值,框架只做四件事: + +1. 从 `IFlowOperator#getIdentity()` 读取; +2. 落库到流程记录与待办; +3. 在判定时按 `(userId, identity)` 比较; +4. 透传给 Groovy 脚本与 REST 响应。 + +约定:`null` 与空串等价,均表示**默认身份**(`OperatorIdentity.DEFAULT`)。未启用多身份的业务、以及 0.3.0 之前的历史数据,全部落在默认身份上,行为与历史完全一致。 + +```java +public interface IFlowOperator extends IUser { + + long getUserId(); + + String getName(); + + /** + * 身份标识,空串表示默认身份。框架不解释语义。 + */ + default String getIdentity() { + return OperatorIdentity.DEFAULT; + } + + /** + * 身份的附加属性(部门名、岗位名等),只透传给脚本与前端,不参与引擎判定,不落库。 + */ + default Map getIdentityAttributes() { + return Map.of(); + } +} +``` + +两个方法都是 `default`,**下游存量实现类无需改动即可编译**。 + +## 3. 下游需要做什么 + +### 3.1 实现身份(可选) + +```java +public class User implements IFlowOperator { + + private String identity; // 运行期选择,通常不落用户主表 + + @Override + public String getIdentity() { + return identity; + } +} +``` + +### 3.2 让网关按身份返回操作者(关键) + +```java +@Override +public IFlowOperator get(long id, String identity) { + User user = userRepository.getUserById(id); + if (user == null || OperatorIdentity.isDefault(identity)) { + return user; + } + // 必须复制:直接改写实体会污染持久化上下文 / 线程缓存,导致同一 id 的两个身份互相覆盖 + return user.withIdentity(identity); +} +``` + +> `get(long, String)` 在接口上是 `default` 方法,默认退化为 `get(id)`(忽略身份)。**不实现它时,请求里声明的身份不会被写入记录** —— 引擎的身份来源是操作者对象本身,而不是请求参数。多身份场景必须实现此方法。 + +### 3.3 请求声明身份 + +REST 接口支持 `operatorIdentity` 参数(与 `operatorId` 对称):未传时取当前登录操作者的身份。 + +```bash +# 以 department1 的身份发起 +curl -X POST 'http://host/api/cmd/record/create?operatorIdentity=department1' \ + -H 'Content-Type: application/json' -d '{...}' + +# 以 department1 的身份查看待办 +curl 'http://host/api/query/record/todo?operatorId=1&operatorIdentity=department1' +``` + +编程式 API 中对应各请求对象的 `operatorIdentity` 字段: + +| 请求对象 | 字段 | +|----------|------| +| `FlowCreateRequest` | `operatorIdentity` | +| `FlowAdviceBody`(`FlowActionRequest.advice`) | `operatorIdentity` | +| `FlowRevokeRequest` / `FlowDeleteRequest` / `FlowUrgeRequest` | `operatorIdentity` | +| `FlowDetailRequest` / `FlowProcessNodeRequest` | `operatorIdentity` | +| `FlowReissueRequest` / `FlowForceSyncRequest` / `FlowSubProcessResetRequest` | `operatorIdentity` | + +### 3.4 在脚本中使用身份 + +`GroovyScriptRequest` 新增三个函数: + +| 脚本函数 | 含义 | +|----------|------| +| `getCurrentOperatorIdentity()` | 当前操作者身份 | +| `getCreatedOperatorIdentity()` | 流程发起人身份 | +| `getSubmitOperatorIdentity()` | 流程提交人身份 | + +节点/分支差异(条件脚本): + +```groovy +def run(request) { + // department1 需要组长审核,其他身份直接进入部门经理审批 + return request.getCurrentOperatorIdentity() == 'department1' +} +``` + +人员差异(审批人脚本): + +```groovy +def run(request) { + def identity = request.getCreatedOperatorIdentity() + if (identity == 'department1') return [boss1Id] + if (identity == 'department2') return [boss2Id] + return [defaultBossId] +} +``` + +## 4. 引擎侧行为 + +### 4.1 记录与待办落库 + +| 表 | 新增列 | +|----|--------| +| `t_flow_record` | `create_operator_identity`、`submit_operator_identity`、`current_operator_identity`、`forward_operator_identity`、`interfered_operator_identity` | +| `t_flow_todo_record` | `create_operator_identity`、`submit_operator_identity`、`current_operator_identity` | + +只存身份标识本身,`getIdentityAttributes()` 的附加属性**不落库**(避免 5 个 JSON 快照列,也避免身份名称被冻结在历史数据里)。展示名称仍取操作者姓名。 + +升级脚本见 [sql/0.3.0-operator-identity.sql](./sql/0.3.0-operator-identity.sql)。 + +### 4.2 待办合并键(兼容追加) + +`FlowRecord#getTodoKey()` 的格式: + +| 身份 | 合并键 | +|------|--------| +| 默认身份 | `{operatorId}-{workRuntimeId}-{nodeId}`(与 0.2.x 完全一致) | +| 非空身份 | `{operatorId}-{workRuntimeId}-{nodeId}#{identity}` | + +默认身份保持历史格式是刻意的:升级瞬间仍在运行的流程,其存量待办行是旧格式键,若统一改格式会导致新流转算出的键查不到旧行 → 重复生成待办、合并关系断裂。 + +### 4.3 查询隔离 + +待办 / 已办 / 抄送查询按 `(currentOperatorId, currentOperatorIdentity)` 过滤,默认身份的条件写成 `coalesce(identity, '') = ''`,保证历史 NULL 行仍能被查到(否则升级后存量待办会从列表中消失)。 + +### 4.4 判定升级为 `(userId, identity)` + +以下判定统一由「只比 userId」升级为「比 userId + identity」,身份为空时与历史等价: + +- 审批动作的参与人校验(`WorkflowStrategyManager#verifyOperator`) +- 撤销、删除、催办、子流程重置的记录归属校验 +- 加签 / 减签 / 转交 / 委托的人员匹配(`OperatorManager`) +- 提交人 == 审批人的自动通过判定 +- 流程干预人识别 +- 操作者线程缓存与网关缓存的键 + +## 5. 兼容性与限制 + +| 项 | 说明 | +|----|------| +| 存量数据 | 新列为 NULL,按默认身份读取,**无需回填** | +| 回滚 | 仅新增 nullable 列,旧版本不映射新列,可直接回滚 | +| 工作流定义 | 与身份无关,导入导出不受影响 | +| 身份长度 | 建议 ≤ 64 字符(复合 key 用 `:` 拼接) | +| 待办索引 | 实体未声明 `@Index`,大表请按 DDL 脚本手工加索引 | +| 不做的事 | 引擎不建组织模型、不做身份授权校验(「user1 能否以 department1 身份操作」由业务侧保证)、不冻结身份名称 | + +> 身份是一个**不透明字符串**,不要尝试在引擎里比较它的业务含义;需要「部门名称」等展示信息,请用 `getIdentityAttributes()` 或按身份回查组织数据。 diff --git a/docs/Integration/sql/0.3.0-operator-identity.sql b/docs/Integration/sql/0.3.0-operator-identity.sql new file mode 100644 index 00000000..afa11162 --- /dev/null +++ b/docs/Integration/sql/0.3.0-operator-identity.sql @@ -0,0 +1,75 @@ +-- ============================================================================= +-- flow-engine 0.3.0 升级脚本:操作者身份标识(issue #288) +-- ============================================================================= +-- 背景: +-- 同一人员可同时隶属多个部门/岗位,以不同「身份」参与同一个流程。 +-- 0.3.0 起框架在记录与待办上保存身份标识(不解释语义,由下游定义取值)。 +-- +-- 兼容性: +-- 1. 仅新增 nullable 列,不修改、不删除任何既有列,旧版本程序不映射新列,可安全回滚。 +-- 2. 历史数据的新列为 NULL,引擎按「null 与空串等价 = 默认身份」读取,无需数据回填。 +-- 3. 待办合并键在默认身份下保持历史格式,仅非空身份追加 "#identity" 后缀, +-- 升级瞬间仍在运行的流程不会出现待办重复或合并关系断裂。 +-- +-- 使用方式: +-- - 使用 ddl-auto=update 的环境会自动加列,本脚本用于「手工管理表结构」的生产环境; +-- - 索引请按实际数据量与慢查询情况选择性执行(见文末)。 +-- ============================================================================= + + +-- ----------------------------------------------------------------------------- +-- 1. 流程记录表:发起 / 提交 / 当前 / 转交 / 干预 五组操作者的身份 +-- ----------------------------------------------------------------------------- +ALTER TABLE t_flow_record ADD COLUMN create_operator_identity VARCHAR(64) NULL; +ALTER TABLE t_flow_record ADD COLUMN submit_operator_identity VARCHAR(64) NULL; +ALTER TABLE t_flow_record ADD COLUMN current_operator_identity VARCHAR(64) NULL; +ALTER TABLE t_flow_record ADD COLUMN forward_operator_identity VARCHAR(64) NULL; +ALTER TABLE t_flow_record ADD COLUMN interfered_operator_identity VARCHAR(64) NULL; + + +-- ----------------------------------------------------------------------------- +-- 2. 待办表:发起 / 提交 / 当前 三组操作者的身份 +-- ----------------------------------------------------------------------------- +ALTER TABLE t_flow_todo_record ADD COLUMN create_operator_identity VARCHAR(64) NULL; +ALTER TABLE t_flow_todo_record ADD COLUMN submit_operator_identity VARCHAR(64) NULL; +ALTER TABLE t_flow_todo_record ADD COLUMN current_operator_identity VARCHAR(64) NULL; + + +-- ----------------------------------------------------------------------------- +-- 3. 索引(可选,按需执行) +-- ----------------------------------------------------------------------------- +-- 3.1 待办列表查询:where current_operator_id = ? and coalesce(current_operator_identity,'') = ? +-- 数据量超过 100 万的待办表建议加此联合索引;小表可暂不加。 +-- 注意:coalesce 会导致该列无法命中普通索引,因此索引列顺序把 operator_id 放前面, +-- 由 operator_id 做范围收敛,身份列做回表过滤。 +-- CREATE INDEX idx_todo_operator_identity +-- ON t_flow_todo_record (current_operator_id, current_operator_identity); + +-- 3.2 已办 / 抄送列表查询(同上,命中 t_flow_record) +-- CREATE INDEX idx_record_operator_identity +-- ON t_flow_record (current_operator_id, current_operator_identity, record_state); + + +-- ----------------------------------------------------------------------------- +-- 4. 达梦(DM)环境补充说明 +-- ----------------------------------------------------------------------------- +-- 达梦上 Hibernate 的 ddl-auto=update 对【加列】是可靠的(仅新增 nullable 列,不涉及序列), +-- 但生产环境仍建议按本脚本手工执行。达梦语法与上文一致,字段类型可用 VARCHAR(64); +-- 若字符集配置为 UTF-8,VARCHAR(64) 即 64 个字符,足以容纳「部门id」「部门id:岗位编码」等复合身份。 +-- 达梦不支持 `coalesce` 走索引,索引策略同上(operator_id 在前)。 + + +-- ----------------------------------------------------------------------------- +-- 5. 升级后自检(可选) +-- ----------------------------------------------------------------------------- +-- 4.1 身份列是否都已创建(不同数据库查询 information_schema 的写法略有差异) +-- SELECT table_name, column_name +-- FROM information_schema.columns +-- WHERE column_name LIKE '%operator_identity' +-- ORDER BY table_name, column_name; + +-- 4.2 待办合并键格式抽查:默认身份应为 "id-runtime-node",非空身份应带 "#identity" 后缀 +-- SELECT current_operator_id, current_operator_identity, todo_key +-- FROM t_flow_todo_record +-- ORDER BY id DESC +-- LIMIT 20; diff --git a/docs/Integration/user-integration.md b/docs/Integration/user-integration.md index 8e5a0cb6..ae1b1e72 100644 --- a/docs/Integration/user-integration.md +++ b/docs/Integration/user-integration.md @@ -14,12 +14,20 @@ package com.codingapi.flow.gateway; /** 流程操作者防腐层 */ public interface FlowOperatorGateway { IFlowOperator get(long id); + + /** 按 (id, identity) 取用户,default 退化为 get(id);多身份场景需覆盖(见「多身份参与」) */ + default IFlowOperator get(long id, String identity) { + return get(id); + } + List findByIds(List ids); } ``` 引擎所有「按 id 取用户 / 批量取用户」的请求都汇聚到这个接口。**框架不提供默认实现**(`flow-engine-starter-infra` 也不提供),必须由业务方提供一个 Spring Bean。 +> 同一人员以多个身份参与流程时(例如同时隶属两个部门),需要覆盖 `get(long, String)`,详见 [多身份参与](./operator-identity.md)。 + ### 1.2 `IFlowOperator`(流程操作人) 文件:`flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java` diff --git a/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java b/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java index 7e8eab6f..dce7554d 100644 --- a/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java +++ b/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java @@ -8,6 +8,7 @@ import com.codingapi.springboot.script.annotation.ScriptType; import jakarta.persistence.*; import lombok.Data; +import lombok.EqualsAndHashCode; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.List; @@ -37,6 +38,18 @@ public class User implements IFlowOperator { private String account; private String password; + /** + * 当前身份标识(issue #288)。 + * + *

同一个人员可能隶属多个部门/岗位,以不同身份参与流程。身份是**运行期选择**而非用户主数据, + * 因此不落库;由 {@code FlowOperatorGateway#get(id, identity)} 按身份返回携带该标识的用户副本。 + * 不参与 {@code equals/hashCode},避免同一 id 的两个身份副本被判定为不同用户。 + */ + @Transient + @EqualsAndHashCode.Exclude + @ScriptField(name = "identity", description = "当前身份标识") + private String identity; + public static User admin(PasswordEncoder passwordEncoder) { User user = new User(); @@ -75,6 +88,36 @@ public boolean isFlowManager() { return flowManager!=null && flowManager ; } + /** + * 当前身份标识,空串表示默认身份(issue #288)。 + */ + @Override + @ScriptFunction(name = "getIdentity", description = "获取当前身份标识") + public String getIdentity() { + return identity; + } + + /** + * 返回携带指定身份的副本。 + * + *

必须复制而不是直接改写实体:JPA 返回的是持久化上下文中的共享实例, + * 直接写入 {@code identity} 会让同一 id 的两个身份互相覆盖(缓存串味)。 + * + * @param identity 身份标识 + * @return 带身份的副本 + */ + public User withIdentity(String identity) { + User copy = new User(); + copy.id = this.id; + copy.name = this.name; + copy.flowManager = this.flowManager; + copy.flowOperatorId = this.flowOperatorId; + copy.account = this.account; + copy.password = this.password; + copy.identity = identity; + return copy; + } + @Override public IFlowOperator forwardOperator(GroovyScriptRequest request) { if (flowOperatorId != null && flowOperatorId > 0) { diff --git a/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java b/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java index ca79b81f..d133ca0d 100644 --- a/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java +++ b/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java @@ -1,8 +1,10 @@ package com.codingapi.example.gateway.impl; +import com.codingapi.example.entity.User; import com.codingapi.example.repository.UserRepository; import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import lombok.AllArgsConstructor; import org.springframework.stereotype.Repository; @@ -19,6 +21,22 @@ public IFlowOperator get(long id) { return userRepository.getUserById(id); } + /** + * 按身份获取操作者(issue #288)。 + * + *

示例组织模型里身份就是「以哪个部门/岗位的身份参与流程」,不属于用户主数据, + * 因此这里返回携带身份标识的**用户副本**,而不改写持久化上下文中的实体实例。 + * 真实项目应把身份替换为自己的组织模型(例如按部门 id 查询岗位任职关系)。 + */ + @Override + public IFlowOperator get(long id, String identity) { + if (OperatorIdentity.isDefault(identity)) { + return get(id); + } + User user = userRepository.getUserById(id); + return user == null ? null : user.withIdentity(OperatorIdentity.normalize(identity)); + } + @Override public List findByIds(List ids) { return userRepository.findUserByIdIn(ids) diff --git a/flow-engine-example/src/test/java/com/codingapi/example/FlowTodoIdentityQueryTest.java b/flow-engine-example/src/test/java/com/codingapi/example/FlowTodoIdentityQueryTest.java new file mode 100644 index 00000000..50e96393 --- /dev/null +++ b/flow-engine-example/src/test/java/com/codingapi/example/FlowTodoIdentityQueryTest.java @@ -0,0 +1,185 @@ +package com.codingapi.example; + +import com.codingapi.example.entity.User; +import com.codingapi.example.repository.UserRepository; +import com.codingapi.flow.builder.FormFieldPermissionsBuilder; +import com.codingapi.flow.builder.NodeStrategyBuilder; +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.infra.entity.FlowTodoRecordEntity; +import com.codingapi.flow.infra.jpa.FlowTodoRecordEntityRepository; +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.request.FlowCreateRequest; +import com.codingapi.flow.service.FlowService; +import com.codingapi.flow.service.WorkflowService; +import com.codingapi.flow.strategy.node.FormFieldPermissionStrategy; +import com.codingapi.flow.strategy.node.OperatorLoadStrategy; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.WorkflowBuilder; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.PageRequest; +import org.springframework.test.context.TestPropertySource; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 待办查询的身份隔离测试(issue #288 P2)。 + * + *

校验两件事: + *

    + *
  1. 身份条件真正落到 SQL 上(不是内存过滤);
  2. + *
  3. 历史数据身份列为 {@code NULL} 时,按默认身份查询仍然能查到——否则升级瞬间 + * 所有存量待办都会从用户列表里消失。
  4. + *
+ */ +@SpringBootTest +@TestPropertySource(properties = "spring.datasource.url=jdbc:h2:mem:flow-todo-identity-test;DB_CLOSE_DELAY=-1") +class FlowTodoIdentityQueryTest { + + @Autowired + private FlowService flowService; + + @Autowired + private WorkflowService workflowService; + + @Autowired + private UserRepository userRepository; + + @Autowired + private FlowTodoRecordEntityRepository flowTodoRecordEntityRepository; + + /** + * 历史数据(身份为 NULL)必须能被默认身份查到,且不会串到非默认身份的查询结果里。 + */ + @Test + void should_match_null_identity_as_default_for_legacy_rows() { + long operatorId = 880001L; + + FlowTodoRecordEntity legacy = new FlowTodoRecordEntity(); + legacy.setProcessId("legacy-process"); + legacy.setWorkflowRuntimeId(1L); + legacy.setWorkCode("legacy"); + legacy.setNodeId("start"); + legacy.setNodeType("START"); + legacy.setNodeName("开始"); + legacy.setTitle("历史待办"); + legacy.setCurrentOperatorId(operatorId); + legacy.setCurrentOperatorName("user1"); + legacy.setCurrentOperatorIdentity(null); + legacy.setTodoKey(operatorId + "-1-start"); + legacy.setMargeCount(0); + legacy.setMergeable(false); + legacy.setRecordId(1L); + legacy.setCreateTime(System.currentTimeMillis()); + flowTodoRecordEntityRepository.save(legacy); + + FlowTodoRecordEntity department1 = new FlowTodoRecordEntity(); + department1.setProcessId("department1-process"); + department1.setWorkflowRuntimeId(1L); + department1.setWorkCode("leave"); + department1.setNodeId("start"); + department1.setNodeType("START"); + department1.setNodeName("开始"); + department1.setTitle("部门1待办"); + department1.setCurrentOperatorId(operatorId); + department1.setCurrentOperatorName("user1"); + department1.setCurrentOperatorIdentity("department1"); + department1.setTodoKey(operatorId + "-1-start#department1"); + department1.setMargeCount(0); + department1.setMergeable(false); + department1.setRecordId(2L); + department1.setCreateTime(System.currentTimeMillis()); + flowTodoRecordEntityRepository.save(department1); + + PageRequest page = PageRequest.of(0, 10); + + // 默认身份:只命中身份为 NULL 的历史行 + assertEquals(1, flowTodoRecordEntityRepository + .findTodoRecordPageByIdentity(operatorId, "", page).getTotalElements()); + // 空串与 NULL 等价,不能把非默认身份的行也带出来 + assertEquals(0, flowTodoRecordEntityRepository + .findTodoRecordPageByIdentity(operatorId, "department2", page).getTotalElements()); + // 非默认身份:只命中自己的行 + assertEquals(1, flowTodoRecordEntityRepository + .findTodoRecordPageByIdentity(operatorId, "department1", page).getTotalElements()); + } + + /** + * 端到端:以指定身份发起流程 → 待办按身份落库 → 按身份可查、按默认身份查不到。 + */ + @Test + void should_persist_identity_and_query_todo_by_identity() { + User admin = userRepository.getUserByAccount(User.ADMIN_ACCOUNT); + String code = "identity-" + System.nanoTime(); + + FlowForm form = FlowFormBuilder.builder() + .name("身份测试流程") + .code(code) + .addField("事由", "reason", DataType.STRING) + .build(); + + FormFieldPermissionsBuilder permissions = FormFieldPermissionsBuilder.builder() + .addPermission(code, "reason", PermissionType.WRITE); + + StartNode startNode = StartNode.builder() + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(permissions.build())) + .build()) + .build(); + + ApprovalNode approvalNode = ApprovalNode.builder() + .name("经理审批") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(permissions.build())) + .addStrategy(OperatorLoadStrategy.initiatorSelectStrategy()) + .build()) + .build(); + + EndNode endNode = EndNode.builder().build(); + + Workflow workflow = WorkflowBuilder.builder() + .title("身份测试流程") + .code(code) + .createdOperator(admin) + .form(form) + .addNode(startNode) + .addNode(approvalNode) + .addNode(endNode) + .build(); + workflowService.saveWorkflow(workflow); + + FlowCreateRequest createRequest = new FlowCreateRequest(); + createRequest.setWorkCode(workflow.getCode()); + createRequest.setFormData(Map.of("reason", "测试身份")); + createRequest.setActionId(startNode.actionManager().getActions().get(0).id()); + createRequest.setOperatorId(admin.getUserId()); + createRequest.setOperatorIdentity("department1"); + + PageRequest page = PageRequest.of(0, 50); + // 用增量断言,避免同一上下文中其他用例的待办影响计数 + long identityBefore = flowTodoRecordEntityRepository + .findTodoRecordPageByIdentity(admin.getUserId(), "department1", page).getTotalElements(); + long defaultBefore = flowTodoRecordEntityRepository + .findTodoRecordPageByIdentity(admin.getUserId(), "", page).getTotalElements(); + + long recordId = flowService.create(createRequest); + assertTrue(recordId > 0, "流程创建应成功并返回记录id"); + + long identityAfter = flowTodoRecordEntityRepository + .findTodoRecordPageByIdentity(admin.getUserId(), "department1", page).getTotalElements(); + long defaultAfter = flowTodoRecordEntityRepository + .findTodoRecordPageByIdentity(admin.getUserId(), "", page).getTotalElements(); + + assertEquals(identityBefore + 1, identityAfter, "带身份的待办应能按身份查到"); + assertEquals(defaultBefore, defaultAfter, "带身份的待办不应出现在默认身份列表里"); + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/AddAuditAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/AddAuditAction.java index 60232cd9..12fa25c1 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/AddAuditAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/AddAuditAction.java @@ -12,6 +12,7 @@ import com.codingapi.flow.manager.OperatorManager; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.script.node.OperatorLoadScript; import com.codingapi.flow.session.FlowSession; @@ -153,24 +154,31 @@ private void verifyNotInTodoQueue(FlowSession flowSession, List a if (auditOperators == null || auditOperators.isEmpty()) { return; } - Set pendingOperatorIds = pendingOperatorIds(flowSession); - if (pendingOperatorIds.isEmpty()) { + Set pendingOperators = pendingOperatorKeys(flowSession); + if (pendingOperators.isEmpty()) { return; } for (IFlowOperator auditOperator : auditOperators) { - if (pendingOperatorIds.contains(auditOperator.getUserId())) { + if (pendingOperators.contains(operatorKey(auditOperator.getUserId(), OperatorIdentity.of(auditOperator)))) { throw FlowExecutionException.addAuditOperatorAlreadyInTodo(auditOperator.getUserId()); } } } /** - * 当前节点实例中仍有待办的人员id集合。 + * 参与人键:{@code userId + identity},同一人员的不同身份是不同参与人(issue #288) + */ + private static String operatorKey(long userId, String identity) { + return userId + "\u0001" + OperatorIdentity.normalize(identity); + } + + /** + * 当前节点实例中仍有待办的参与人键集合(userId + identity)。 * *

仓储按 {@code (fromId, nodeId)} 查询节点记录,开始节点({@code fromId = 0})等场景可能 * 命中其他流程实例的记录,必须按 {@code processId} 限定,避免误判其他流程的待办人员。 */ - private Set pendingOperatorIds(FlowSession flowSession) { + private Set pendingOperatorKeys(FlowSession flowSession) { FlowRecord currentRecord = flowSession.getCurrentRecord(); List currentNodeRecords = flowSession.getCurrentNodeRecords(); if (currentRecord == null || currentNodeRecords == null) { @@ -180,7 +188,7 @@ private Set pendingOperatorIds(FlowSession flowSession) { .filter(Objects::nonNull) .filter(record -> currentRecord.getProcessId().equals(record.getProcessId())) .filter(FlowRecord::isPendingApproval) - .map(FlowRecord::getCurrentOperatorId) + .map(record -> operatorKey(record.getCurrentOperatorId(), record.getCurrentOperatorIdentity())) .collect(Collectors.toSet()); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java index ed069947..4dea88cb 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java @@ -203,7 +203,8 @@ public void run(FlowSession flowSession) { // 是否转交审批人的流程 if (isFinish && currentRecord.isForward()) { - IFlowOperator forwardOperator = repositoryHolder.getOperatorById(currentRecord.getForwardOperatorId()); + IFlowOperator forwardOperator = repositoryHolder.getOperatorById( + currentRecord.getForwardOperatorId(), currentRecord.getForwardOperatorIdentity()); FlowRecord notifyRecord = currentRecord.create(flowSession.updateSession(forwardOperator)); notifyRecord.notifyRecord(flowSession.updateSession(forwardOperator)); // 如果不存储这个记录,若下一流程是结束流程时,无法更新流程状态为结束状态。 @@ -215,7 +216,8 @@ public void run(FlowSession flowSession) { // 多人审批时其他待办可能尚未完成,若只在 isFinish 时返回,委派记录会永久滞留(issue #239) if (currentRecord.isDelegate()) { FlowRecord delegateRecord = repositoryHolder.getRecordById(currentRecord.getDelegateId()); - IFlowOperator delegateOperator = repositoryHolder.getOperatorById(delegateRecord.getCurrentOperatorId()); + IFlowOperator delegateOperator = repositoryHolder.getOperatorById( + delegateRecord.getCurrentOperatorId(), delegateRecord.getCurrentOperatorIdentity()); FlowRecord rebackRecord = delegateRecord.create(flowSession.updateSession(delegateOperator)); // 返回记录同样归属原委托记录的节点实例与审批槽位(issue #239) rebackRecord.inheritNodeInstance(delegateRecord); 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 76cb04f2..7783e755 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 @@ -13,6 +13,7 @@ import com.codingapi.flow.node.BaseAuditNode; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.script.node.OperatorLoadScript; import com.codingapi.flow.session.FlowSession; @@ -170,12 +171,17 @@ private List resolveTargetRecords(List targets, List targetRecords = new ArrayList<>(); for (IFlowOperator target : targets) { long targetOperatorId = target.getUserId(); - if (targetOperatorId == currentRecord.getCurrentOperatorId()) { + String targetOperatorIdentity = OperatorIdentity.of(target); + // 自己不能被自己减签:按 (userId, identity) 判断,避免把另一身份的待办当成自己的 + if (targetOperatorId == currentRecord.getCurrentOperatorId() + && OperatorIdentity.same(targetOperatorIdentity, currentRecord.getCurrentOperatorIdentity())) { throw FlowExecutionException.reduceAuditOwnRecord(); } + // 减签按「人 + 身份」生效:同一人员的另一个身份仍然是独立参与人,不能被顺带撤销 List matchedRecords = currentNodeRecords.stream() .filter(FlowRecord::isPendingApproval) - .filter(record -> record.getCurrentOperatorId() == targetOperatorId) + .filter(record -> record.getCurrentOperatorId() == targetOperatorId + && OperatorIdentity.same(record.getCurrentOperatorIdentity(), targetOperatorIdentity)) .toList(); if (matchedRecords.isEmpty()) { throw FlowExecutionException.reduceAuditTargetNotFound(targetOperatorId); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java b/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java index 57a994ca..333568e8 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java @@ -1,6 +1,7 @@ package com.codingapi.flow.cache; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import lombok.Getter; import java.util.ArrayList; @@ -9,9 +10,23 @@ import java.util.Map; import java.util.function.Supplier; +/** + * 流程操作者线程缓存。 + * + *

同一个人员可以以不同「身份」参与流程(issue #288),因此缓存键必须是 + * {@code (userId, identity)} 二元组而不是 userId:以身份为维度隔离后,同一 id 的 + * 两个身份各自缓存各自的 {@link IFlowOperator} 实例,不会互相串味。 + * + *

身份为 {@code null}/{@code ""}(默认身份)时与历史行为等价,等同于只按 userId 缓存。 + */ public class FlowOperatorLocalThreadCache { - private final ThreadLocal> cache; + /** + * userId 与 identity 之间的分隔符;使用不可见控制字符,避免与业务身份标识冲突 + */ + private static final String KEY_SEPARATOR = "\u0001"; + + private final ThreadLocal> cache; private FlowOperatorLocalThreadCache() { this.cache = new ThreadLocal<>(); @@ -20,41 +35,71 @@ private FlowOperatorLocalThreadCache() { @Getter private final static FlowOperatorLocalThreadCache instance = new FlowOperatorLocalThreadCache(); + /** + * 拼装缓存键,身份统一归一化,保证 {@code null} 与空串命中同一条缓存 + */ + private static String cacheKey(long userId, String identity) { + return userId + KEY_SEPARATOR + OperatorIdentity.normalize(identity); + } public void clear() { this.cache.remove(); } - private Map getCache() { - Map operatorCaches = this.cache.get(); + private Map getCache() { + Map operatorCaches = this.cache.get(); if (operatorCaches == null) { operatorCaches = new HashMap<>(); } return operatorCaches; } + /** + * 将操作者写入缓存,缓存键取自操作者自身的身份标识。 + */ public void sync(IFlowOperator flowOperator) { - Map operatorCaches = this.getCache(); - operatorCaches.put(flowOperator.getUserId(), flowOperator); + Map operatorCaches = this.getCache(); + operatorCaches.put(cacheKey(flowOperator.getUserId(), OperatorIdentity.of(flowOperator)), flowOperator); this.cache.set(operatorCaches); } + /** + * 读取操作者(默认身份)。 + */ public IFlowOperator get(long id, Supplier operatorLoader) { - Map operatorCaches = this.getCache(); - IFlowOperator operator = operatorCaches.get(id); + return this.get(id, OperatorIdentity.DEFAULT, operatorLoader); + } + + /** + * 按身份读取操作者,未命中时通过 {@code operatorLoader} 加载并回填缓存。 + * + * @param id 人员 id + * @param identity 身份标识,{@code null} 与空串等价 + * @param operatorLoader 缓存未命中时的加载器 + * @return 操作者,加载不到时返回 {@code null} + */ + public IFlowOperator get(long id, String identity, Supplier operatorLoader) { + Map operatorCaches = this.getCache(); + String key = cacheKey(id, identity); + IFlowOperator operator = operatorCaches.get(key); if (operator != null) { return operator; } operator = operatorLoader.get(); if (operator != null) { - operatorCaches.put(id, operator); + operatorCaches.put(key, operator); this.cache.set(operatorCaches); } return operator; } - + /** + * 批量读取操作者(默认身份)。 + * + *

批量加载没有身份维度(下游网关的 {@code findByIds} 只按 id 查询), + * 因此这里固定使用默认身份作为缓存键,与历史行为一致。 + */ public List find(List ids, IFlowOperatorFinder flowOperatorFinder) { if (ids == null || ids.isEmpty()) { return null; @@ -68,17 +113,20 @@ public List find(List ids, IFlowOperatorFinder flowOperator return null; } - Map operatorCaches = this.getCache(); + Map operatorCaches = this.getCache(); List queryIds = ids.stream() - .filter((id) -> !operatorCaches.containsKey(id)) + .filter((id) -> !operatorCaches.containsKey(cacheKey(id, OperatorIdentity.DEFAULT))) .toList(); if (!queryIds.isEmpty()) { List newOperatorList = flowOperatorFinder.find(queryIds); if (newOperatorList != null && !newOperatorList.isEmpty()) { for (IFlowOperator operator : newOperatorList) { - operatorCaches.put(operator.getUserId(), operator); + // 批量加载是「按 id 查询」的标识无关路径:结果统一登记在默认身份键下, + // 与下面按默认身份读取保持一致。否则下游返回自带身份的操作者会被登记到身份键, + // 读取时按默认键取不到,表现为「审批人为空」。 + operatorCaches.put(cacheKey(operator.getUserId(), OperatorIdentity.DEFAULT), operator); } this.cache.set(operatorCaches); } @@ -87,7 +135,7 @@ public List find(List ids, IFlowOperatorFinder flowOperator // 按入参 ids 顺序返回,避免缓存命中情况影响结果顺序,保证多人审批顺序稳定 List operatorList = new ArrayList<>(); for (long id : ids) { - IFlowOperator operator = operatorCaches.get(id); + IFlowOperator operator = operatorCaches.get(cacheKey(id, OperatorIdentity.DEFAULT)); if (operator != null) { operatorList.add(operator); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java b/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java index 863e783d..4409e116 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java @@ -3,6 +3,7 @@ import com.codingapi.flow.cache.FlowOperatorLocalThreadCache; import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import lombok.Getter; import lombok.Setter; @@ -20,8 +21,29 @@ private GatewayContext() { @Getter private FlowOperatorGateway flowOperatorGateway; + /** + * 按人员 id 获取操作者(默认身份)。 + * + * @param userId 人员 id + * @return 操作者 + */ public IFlowOperator getFlowOperator(long userId) { - return FlowOperatorLocalThreadCache.getInstance().get(userId,()->flowOperatorGateway.get(userId)); + return this.getFlowOperator(userId, OperatorIdentity.DEFAULT); + } + + /** + * 按人员 id 与身份获取操作者(issue #288)。 + * + *

身份为空({@code null}/空串)时与 {@link #getFlowOperator(long)} 完全等价, + * 保证存量调用链行为不变。 + * + * @param userId 人员 id + * @param identity 身份标识 + * @return 操作者 + */ + public IFlowOperator getFlowOperator(long userId, String identity) { + return FlowOperatorLocalThreadCache.getInstance() + .get(userId, identity, () -> flowOperatorGateway.get(userId, identity)); } public List findByIds(List ids) { 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 079e7b38..ea535b15 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 @@ -138,6 +138,11 @@ public IFlowOperator getOperatorById(long id) { return GatewayContext.getInstance().getFlowOperator(id); } + @Override + public IFlowOperator getOperatorById(long id, String identity) { + return GatewayContext.getInstance().getFlowOperator(id, identity); + } + @Override public FlowOperatorGateway getFlowOperatorGateway() { return new FlowOperatorGateway() { @@ -146,6 +151,11 @@ public IFlowOperator get(long id) { return GatewayContext.getInstance().getFlowOperator(id); } + @Override + public IFlowOperator get(long id, String identity) { + return GatewayContext.getInstance().getFlowOperator(id, identity); + } + @Override public List findByIds(List ids) { return GatewayContext.getInstance().findByIds(ids); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/gateway/FlowOperatorGateway.java b/flow-engine-framework/src/main/java/com/codingapi/flow/gateway/FlowOperatorGateway.java index 24f15795..bc4e64a2 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/gateway/FlowOperatorGateway.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/gateway/FlowOperatorGateway.java @@ -9,8 +9,35 @@ */ public interface FlowOperatorGateway { + /** + * 按人员 id 获取操作者(默认身份)。 + * + * @param id 人员 id + * @return 操作者 + */ IFlowOperator get(long id); + /** + * 按人员 id 与身份获取操作者(issue #288)。 + * + *

同一个人员可能以多个身份参与流程(例如同时隶属两个部门),身份由下游自行定义语义, + * 框架只透传。该方法提供 {@code default} 实现:下游存量实现无需改动即可编译, + * 行为退化为忽略身份、等同于 {@link #get(long)}。需要支持多身份时再覆盖此方法。 + * + * @param id 人员 id + * @param identity 身份标识,{@code null} 与空串等价(默认身份) + * @return 操作者 + */ + default IFlowOperator get(long id, String identity) { + return get(id); + } + + /** + * 按人员 id 批量获取操作者(默认身份)。 + * + * @param ids 人员 id 列表 + * @return 操作者列表 + */ List findByIds(List ids); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/manager/OperatorManager.java b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/OperatorManager.java index 943da887..e23960c7 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/manager/OperatorManager.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/OperatorManager.java @@ -1,6 +1,7 @@ package com.codingapi.flow.manager; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import lombok.Getter; import java.util.ArrayList; @@ -9,12 +10,14 @@ /** * 节点操作者管理 + * + *

参与人由 {@code (userId, identity)} 共同标识(issue #288):同一个人员的两个身份 + * 是两个不同的参与人,匹配与查找都必须带上身份。身份为空时与历史「只比 userId」等价。 */ public class OperatorManager { @Getter private final List operators; - private final List operatorIds; public OperatorManager(List operators) { if(operators!=null && !operators.isEmpty()) { @@ -22,25 +25,40 @@ public OperatorManager(List operators) { }else { this.operators = new ArrayList<>(); } - if(!this.operators.isEmpty()) { - this.operatorIds = this.operators.stream().map(IFlowOperator::getUserId).toList(); - }else { - this.operatorIds = new ArrayList<>(); - } } public boolean isEmpty() { return operators.isEmpty(); } + /** + * 判断操作者是否在节点配置的操作者列表中(按 userId + identity 匹配) + */ public boolean match(IFlowOperator operator) { - return operatorIds.contains(operator.getUserId()); + if (operator == null) { + return false; + } + return this.getOperator(operator.getUserId(), OperatorIdentity.of(operator)) != null; } - + /** + * 按人员 id 查找操作者(默认身份) + */ public IFlowOperator getOperator(long userId) { + return this.getOperator(userId, OperatorIdentity.DEFAULT); + } + + /** + * 按 {@code (userId, identity)} 查找操作者 + * + * @param userId 人员 id + * @param identity 身份标识,{@code null} 与空串等价 + * @return 匹配的操作者,不存在时返回 {@code null} + */ + public IFlowOperator getOperator(long userId, String identity) { for (IFlowOperator operator : operators) { - if (operator.getUserId() == userId) { + if (operator.getUserId() == userId + && OperatorIdentity.same(OperatorIdentity.of(operator), identity)) { return operator; } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java index 200b82d2..429b5ddd 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java @@ -2,6 +2,7 @@ import com.codingapi.flow.exception.FlowStateException; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.strategy.workflow.IWorkflowStrategy; import com.codingapi.flow.strategy.workflow.InterfereStrategy; import lombok.AllArgsConstructor; @@ -45,19 +46,36 @@ public T getStrategy(Class clazz) { } /** - * 验证操作者 + * 验证操作者(默认身份) * * @param currentOperator 当前操作者 * @param recordOperatorId 记录操作者id */ public void verifyOperator(IFlowOperator currentOperator, long recordOperatorId) { + this.verifyOperator(currentOperator, recordOperatorId, OperatorIdentity.DEFAULT); + } + + /** + * 验证操作者。 + * + *

参与人由 {@code (userId, identity)} 共同决定(issue #288):同一个人员的两个身份是 + * 两个不同的参与人,只比 userId 会让 user1 以 department1 的身份操作 department2 的待办。 + * 身份为空时与历史「只比 userId」的行为完全一致。 + * + * @param currentOperator 当前操作者 + * @param recordOperatorId 记录操作者id + * @param recordOperatorIdentity 记录操作者身份标识,{@code null} 与空串等价 + */ + public void verifyOperator(IFlowOperator currentOperator, long recordOperatorId, String recordOperatorIdentity) { + boolean operatorMatched = recordOperatorId == currentOperator.getUserId() + && OperatorIdentity.same(recordOperatorIdentity, OperatorIdentity.of(currentOperator)); if (!this.isEnableInterfere()) { - if (recordOperatorId != currentOperator.getUserId()) { + if (!operatorMatched) { throw FlowStateException.operatorNotMatch(); } } else { if (!currentOperator.isFlowManager()) { - if (recordOperatorId != currentOperator.getUserId()) { + if (!operatorMatched) { throw FlowStateException.operatorNotMatch(); } } 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 55260e90..068d6456 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 @@ -77,6 +77,11 @@ public IFlowOperator get(long id) { return GatewayContext.getInstance().getFlowOperator(id); } + @Override + public IFlowOperator get(long id, String identity) { + return GatewayContext.getInstance().getFlowOperator(id, identity); + } + @Override public List findByIds(List ids) { return GatewayContext.getInstance().findByIds(ids); @@ -114,6 +119,11 @@ public IFlowOperator getOperatorById(long id) { return this.flowOperatorGateway.get(id); } + @Override + public IFlowOperator getOperatorById(long id, String identity) { + return this.flowOperatorGateway.get(id, identity); + } + @Override public void saveDelayTask(DelayTask delayTask) { this.delayTaskRepository.save(delayTask); 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 9dd9bf2f..256c5ddb 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 @@ -11,6 +11,7 @@ import com.codingapi.flow.manager.NodeStrategyManager; import com.codingapi.flow.manager.OperatorManager; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.strategy.node.MultiOperatorAuditStrategy; @@ -262,11 +263,15 @@ private List generateCurrentRecords(FlowSession session, Set if (nodeStrategyManager.isSameOperatorAutoPass() && session.getCurrentOperator() != null && session.getCurrentOperator().getUserId() == session.getSubmitOperatorId() + && OperatorIdentity.same(OperatorIdentity.of(session.getCurrentOperator()), + OperatorIdentity.of(session.getSubmitOperator())) && session.getCurrentAction() != null && ActionType.PASS.name().equalsIgnoreCase(session.getCurrentAction().type())) { long submitOperatorId = session.getSubmitOperatorId(); + String submitOperatorIdentity = OperatorIdentity.of(session.getSubmitOperator()); operators = operators.stream() - .filter(operator -> operator.getUserId() != submitOperatorId) + .filter(operator -> operator.getUserId() != submitOperatorId + || !OperatorIdentity.same(OperatorIdentity.of(operator), submitOperatorIdentity)) .toList(); // 全部审批人均与提交人一致,当前节点自动通过:生成留痕记录并继续向后续节点生成记录(issue #226) if (operators.isEmpty()) { diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/node/nodes/StartNode.java b/flow-engine-framework/src/main/java/com/codingapi/flow/node/nodes/StartNode.java index 4e8dd5a3..cb827bb9 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/node/nodes/StartNode.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/node/nodes/StartNode.java @@ -87,8 +87,9 @@ public List generateCurrentRecords(FlowSession session) { session.setCurrentRecord(flowRecord); records.add(flowRecord); } else { - // 获取流程创建者 - IFlowOperator creatorOperator = GatewayContext.getInstance().getFlowOperator(currentRecord.getCreateOperatorId()); + // 获取流程创建者(按记录中的身份回查,issue #288) + IFlowOperator creatorOperator = GatewayContext.getInstance() + .getFlowOperator(currentRecord.getCreateOperatorId(), currentRecord.getCreateOperatorIdentity()); FlowRecord flowRecord = new FlowRecord(session.updateSession(creatorOperator), 0); // 异常跳转或退回到开始节点时生成的是一条新的待办,尚未执行任何审批动作, // 不能继承触发该跳转的上游审批意见、签名及 PASS/RETURN 等动作信息。 diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/body/FlowAdviceBody.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/body/FlowAdviceBody.java index 4096c314..e149c8ac 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/body/FlowAdviceBody.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/body/FlowAdviceBody.java @@ -2,6 +2,7 @@ import com.codingapi.flow.exception.FlowValidationException; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.session.FlowSession; import lombok.Data; import lombok.NoArgsConstructor; @@ -45,6 +46,14 @@ public class FlowAdviceBody { */ private long operatorId; + /** + * 操作者身份标识(issue #288) + *

同一人员可能以不同身份审批同一流程,框架只透传该标识;为空表示默认身份。 + * + * @see com.codingapi.flow.operator.OperatorIdentity + */ + private String operatorIdentity; + /** * 退回节点 */ @@ -72,6 +81,7 @@ public FlowAdviceBody(FlowSession flowSession) { this.actionId = flowSession.getCurrentAction().id(); this.advice = flowSession.getAdvice().getAdvice(); this.operatorId = flowSession.getCurrentOperator().getUserId(); + this.operatorIdentity = OperatorIdentity.of(flowSession.getCurrentOperator()); this.signKey = flowSession.getAdvice().getSignKey(); this.backNodeId = flowSession.getAdvice().getBackNode() != null ? flowSession.getAdvice().getBackNode().getId() : null; this.manualNodeId = flowSession.getAdvice().getManualNode() != null ? flowSession.getAdvice().getManualNode().getId() : null; diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowActionRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowActionRequest.java index b0798384..20f762f5 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowActionRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowActionRequest.java @@ -37,6 +37,17 @@ public void updateOperatorId(long operatorId) { } } + /** + * 覆盖审批人的身份标识(issue #288),由接口层统一注入当前会话声明的身份 + * + * @param operatorIdentity 身份标识,{@code null} 与空串等价(默认身份) + */ + public void updateOperatorIdentity(String operatorIdentity) { + if (advice != null) { + advice.setOperatorIdentity(operatorIdentity); + } + } + public FlowAdvice toFlowAdvice(Workflow workflow, IFlowAction flowAction) { FlowAdvice flowAdvice = new FlowAdvice(); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowCreateRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowCreateRequest.java index f6bcc001..7f333728 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowCreateRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowCreateRequest.java @@ -33,6 +33,12 @@ public class FlowCreateRequest { */ private long operatorId; + /** + * 操作者身份标识(issue #288) + *

框架不解释身份语义,只透传;为空表示默认身份,与历史行为一致。 + */ + private String operatorIdentity; + /** * 父流程id,系统自动赋值 */ @@ -55,6 +61,7 @@ public FlowActionRequest toActionRequest(long recordId) { flowActionRequest.setFormData(this.getFormData()); flowActionRequest.setRecordId(recordId); FlowAdviceBody adviceBody = new FlowAdviceBody(this.getActionId(), null, this.getOperatorId()); + adviceBody.setOperatorIdentity(this.getOperatorIdentity()); adviceBody.setOperatorSelectMap(this.getOperatorSelectMap()); flowActionRequest.setAdvice(adviceBody); flowActionRequest.verify(); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDeleteRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDeleteRequest.java index ad11ac97..51d41a6b 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDeleteRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDeleteRequest.java @@ -1,6 +1,7 @@ package com.codingapi.flow.pojo.request; import com.codingapi.flow.exception.FlowValidationException; +import com.codingapi.flow.operator.OperatorIdentity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -24,6 +25,18 @@ public class FlowDeleteRequest { */ private long operatorId; + /** + * 操作者身份标识(issue #288),为空表示默认身份 + */ + private String operatorIdentity; + + /** + * 兼容历史调用的双参构造(默认身份) + */ + public FlowDeleteRequest(long recordId, long operatorId) { + this(recordId, operatorId, OperatorIdentity.DEFAULT); + } + public void verify() { if (recordId <= 0) { throw FlowValidationException.required("recordId"); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDetailRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDetailRequest.java index 3f89d6c3..0ee3299d 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDetailRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDetailRequest.java @@ -1,5 +1,6 @@ package com.codingapi.flow.pojo.request; +import com.codingapi.flow.operator.OperatorIdentity; import lombok.Data; import lombok.NoArgsConstructor; @@ -17,18 +18,30 @@ public class FlowDetailRequest { * 流程的操作人Id */ private long operatorId; + /** + * 流程操作人的身份标识(issue #288),为空表示默认身份 + */ + private String operatorIdentity; public boolean isCreateWorkflow() { return !id.matches("^[0-9]+$"); } public FlowDetailRequest(long id,long operatorId){ - this.id = String.valueOf(id); - this.operatorId = operatorId; + this(id, operatorId, OperatorIdentity.DEFAULT); } public FlowDetailRequest(String id, long operatorId) { + this(id, operatorId, OperatorIdentity.DEFAULT); + } + + public FlowDetailRequest(long id, long operatorId, String operatorIdentity) { + this(String.valueOf(id), operatorId, operatorIdentity); + } + + public FlowDetailRequest(String id, long operatorId, String operatorIdentity) { this.id = id; this.operatorId = operatorId; + this.operatorIdentity = operatorIdentity; } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowForceSyncRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowForceSyncRequest.java index 5dec98f3..f3cab011 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowForceSyncRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowForceSyncRequest.java @@ -32,6 +32,11 @@ public class FlowForceSyncRequest { */ private long operatorId; + /** + * 操作者身份标识(issue #288),为空表示默认身份 + */ + private String operatorIdentity; + public FlowForceSyncRequest(String workCode, List processIds, long operatorId) { this.workCode = workCode; this.processIds = processIds; diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowProcessNodeRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowProcessNodeRequest.java index 8bb3c941..b0f97d42 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowProcessNodeRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowProcessNodeRequest.java @@ -1,5 +1,6 @@ package com.codingapi.flow.pojo.request; +import com.codingapi.flow.operator.OperatorIdentity; import lombok.Data; import lombok.NoArgsConstructor; @@ -21,6 +22,11 @@ public class FlowProcessNodeRequest { */ private long operatorId; + /** + * 流程操作人的身份标识(issue #288),为空表示默认身份 + */ + private String operatorIdentity; + /** * 表单数据 */ @@ -28,14 +34,21 @@ public class FlowProcessNodeRequest { public FlowProcessNodeRequest(long id, long operatorId, Map formData) { - this.id = String.valueOf(id); - this.operatorId = operatorId; - this.formData = formData; + this(id, operatorId, OperatorIdentity.DEFAULT, formData); } public FlowProcessNodeRequest(String id, long operatorId, Map formData) { + this(id, operatorId, OperatorIdentity.DEFAULT, formData); + } + + public FlowProcessNodeRequest(long id, long operatorId, String operatorIdentity, Map formData) { + this(String.valueOf(id), operatorId, operatorIdentity, formData); + } + + public FlowProcessNodeRequest(String id, long operatorId, String operatorIdentity, Map formData) { this.id = id; this.operatorId = operatorId; + this.operatorIdentity = operatorIdentity; this.formData = formData; } 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 index 71d95170..6d01eefe 100644 --- 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 @@ -27,6 +27,11 @@ public class FlowReissueRequest { */ private long operatorId; + /** + * 操作者身份标识(issue #288),为空表示默认身份 + */ + private String operatorIdentity; + /** * 二次发起时使用的表单数据;为空时按源流程记录的表单数据复制 */ diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowRevokeRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowRevokeRequest.java index b4e44384..fece10db 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowRevokeRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowRevokeRequest.java @@ -1,6 +1,7 @@ package com.codingapi.flow.pojo.request; import com.codingapi.flow.exception.FlowValidationException; +import com.codingapi.flow.operator.OperatorIdentity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -22,6 +23,18 @@ public class FlowRevokeRequest { */ private long operatorId; + /** + * 操作者身份标识(issue #288),为空表示默认身份 + */ + private String operatorIdentity; + + /** + * 兼容历史调用的双参构造(默认身份) + */ + public FlowRevokeRequest(long recordId, long operatorId) { + this(recordId, operatorId, OperatorIdentity.DEFAULT); + } + public void verify() { if (recordId <= 0) { throw FlowValidationException.required("recordId"); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowSubProcessResetRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowSubProcessResetRequest.java index 11274557..29ced21b 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowSubProcessResetRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowSubProcessResetRequest.java @@ -28,6 +28,11 @@ public class FlowSubProcessResetRequest { */ private long operatorId; + /** + * 操作者身份标识(issue #288),为空表示默认身份 + */ + private String operatorIdentity; + /** * 选中重建的子流程实例流程id列表(须同属一个已完成聚合组,且非空) */ diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowUrgeRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowUrgeRequest.java index 810a9bda..d5051b9c 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowUrgeRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowUrgeRequest.java @@ -1,6 +1,7 @@ package com.codingapi.flow.pojo.request; import com.codingapi.flow.exception.FlowValidationException; +import com.codingapi.flow.operator.OperatorIdentity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -22,6 +23,18 @@ public class FlowUrgeRequest { */ private long operatorId; + /** + * 操作者身份标识(issue #288),为空表示默认身份 + */ + private String operatorIdentity; + + /** + * 兼容历史调用的双参构造(默认身份) + */ + public FlowUrgeRequest(long recordId, long operatorId) { + this(recordId, operatorId, OperatorIdentity.DEFAULT); + } + public void verify() { if (recordId <= 0) { throw FlowValidationException.required("recordId"); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowRecordContent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowRecordContent.java index 37739d88..c0e85522 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowRecordContent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowRecordContent.java @@ -1,5 +1,6 @@ package com.codingapi.flow.pojo.response; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.record.FlowTodoRecord; import lombok.Data; @@ -60,6 +61,11 @@ public class FlowRecordContent { */ private String currentOperatorName; + /** + * 当前审批人身份标识(issue #288),空串表示默认身份 + */ + private String currentOperatorIdentity; + /** * 提交审批人Id */ @@ -70,6 +76,11 @@ public class FlowRecordContent { */ private String submitOperatorName; + /** + * 提交审批人身份标识(issue #288) + */ + private String submitOperatorIdentity; + /** * 创建时间 */ @@ -84,6 +95,11 @@ public class FlowRecordContent { */ private String createOperatorName; + /** + * 发起者身份标识(issue #288) + */ + private String createOperatorIdentity; + /** * 合并记录id,当存在合并记录数据时待办记录数量不会增加,内容会更新至最新的待办数据信息。 * {@link FlowRecord#getTodoKey()} @@ -137,11 +153,14 @@ public static FlowRecordContent convert(FlowRecord record){ content.setReadTime(record.getReadTime()); content.setCurrentOperatorId(record.getCurrentOperatorId()); content.setCurrentOperatorName(record.getCurrentOperatorName()); + content.setCurrentOperatorIdentity(OperatorIdentity.normalize(record.getCurrentOperatorIdentity())); content.setSubmitOperatorId(record.getSubmitOperatorId()); content.setSubmitOperatorName(record.getSubmitOperatorName()); + content.setSubmitOperatorIdentity(OperatorIdentity.normalize(record.getSubmitOperatorIdentity())); content.setCreateTime(record.getCreateTime()); content.setCreateOperatorId(record.getCreateOperatorId()); content.setCreateOperatorName(record.getCreateOperatorName()); + content.setCreateOperatorIdentity(OperatorIdentity.normalize(record.getCreateOperatorIdentity())); content.setMergeable(record.isMergeable()); content.setRecordId(record.getId()); content.setTimeoutTime(record.getTimeoutTime()); @@ -164,11 +183,14 @@ public static FlowRecordContent convert(FlowTodoRecord todoRecord){ content.setReadTime(todoRecord.getReadTime()); content.setCurrentOperatorId(todoRecord.getCurrentOperatorId()); content.setCurrentOperatorName(todoRecord.getCurrentOperatorName()); + content.setCurrentOperatorIdentity(OperatorIdentity.normalize(todoRecord.getCurrentOperatorIdentity())); content.setSubmitOperatorId(todoRecord.getSubmitOperatorId()); content.setSubmitOperatorName(todoRecord.getSubmitOperatorName()); + content.setSubmitOperatorIdentity(OperatorIdentity.normalize(todoRecord.getSubmitOperatorIdentity())); content.setCreateTime(todoRecord.getCreateTime()); content.setCreateOperatorId(todoRecord.getCreateOperatorId()); content.setCreateOperatorName(todoRecord.getCreateOperatorName()); + content.setCreateOperatorIdentity(OperatorIdentity.normalize(todoRecord.getCreateOperatorIdentity())); content.setTodoKey(todoRecord.getTodoKey()); content.setMargeCount(todoRecord.getMargeCount()); content.setMergeable(todoRecord.isMergeable()); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/query/FlowRecordQueryService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/query/FlowRecordQueryService.java index ae73c3e4..0821ff2d 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/query/FlowRecordQueryService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/query/FlowRecordQueryService.java @@ -17,6 +17,35 @@ public interface FlowRecordQueryService { Page findDoneRecordPage(long userId, PageRequest request); + /** + * 按 {@code (审批人, 身份)} 查询待办(issue #288)。 + * + *

默认实现忽略身份、退化为 {@link #findTodoRecordPage(long, PageRequest)}, + * 保证下游自定义实现无需改动即可编译;需要多身份隔离时覆盖此方法。 + * + * @param userId 审批人 id + * @param identity 身份标识,{@code null} 与空串等价(默认身份) + * @param request 分页 + * @return 待办分页 + */ + default Page findTodoRecordPage(long userId, String identity, PageRequest request) { + return findTodoRecordPage(userId, request); + } + + /** + * 按 {@code (审批人, 身份)} 查询抄送(issue #288),默认忽略身份。 + */ + default Page findNotifyRecordPage(long userId, String identity, PageRequest request) { + return findNotifyRecordPage(userId, request); + } + + /** + * 按 {@code (审批人, 身份)} 查询已办(issue #288),默认忽略身份。 + */ + default Page findDoneRecordPage(long userId, String identity, PageRequest request) { + return findDoneRecordPage(userId, request); + } + /** * 查询指定流程编码下运行中的流程实例(以开始节点记录代表一个实例) * diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java index 8471cf13..45492c95 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java @@ -44,6 +44,12 @@ public class FlowRecord { public static int SATE_FLOW_ERROR = 3; public static int SATE_FLOW_DELETE = 4; + /** + * 待办合并键中身份后缀的分隔符(issue #288)。 + *

仅在身份非空时追加,默认身份不使用,保证存量键格式不变。 + */ + private static final String IDENTITY_KEY_SUFFIX = "#"; + /** * 记录id */ @@ -304,16 +310,40 @@ public class FlowRecord { *

  • SUBMITTER — 提交人合并,按 {@link FlowRecord#submitOperatorId}
  • * * 相同依据字段 + {@link FlowRecord#workRuntimeId} + {@link FlowRecord#nodeId} 的数据合并到一条记录上。 + * + *

    多身份场景(issue #288):同一人员的两个身份是不同的参与人,合并键必须带上身份, + * 否则两个身份的待办会被合并成一条。为避免破坏存量数据,采用**兼容追加**策略: + *

      + *
    • 默认身份(空)— 键格式保持历史原样 {@code {operatorId}-{workRuntimeId}-{nodeId}}, + * 升级瞬间仍在运行的流程,其待办行仍是旧格式键,合并关系不会断裂;
    • + *
    • 非空身份 — 追加 {@code #identity} 后缀,与默认身份、其他身份天然隔离。
    • + *
    */ public String getTodoKey() { if (mergeable) { long mergeOperatorId; + String mergeOperatorIdentity; switch (mergeType) { - case CREATOR -> mergeOperatorId = createOperatorId; - case SUBMITTER -> mergeOperatorId = submitOperatorId; - default -> mergeOperatorId = currentOperatorId; + case CREATOR -> { + mergeOperatorId = createOperatorId; + mergeOperatorIdentity = createOperatorIdentity; + } + case SUBMITTER -> { + mergeOperatorId = submitOperatorId; + mergeOperatorIdentity = submitOperatorIdentity; + } + default -> { + mergeOperatorId = currentOperatorId; + mergeOperatorIdentity = currentOperatorIdentity; + } + } + String todoKey = String.format("%s-%s-%s", mergeOperatorId, workRuntimeId, nodeId); + String identity = OperatorIdentity.normalize(mergeOperatorIdentity); + // 默认身份保持历史键格式,保证升级过程中存量待办的合并关系不断裂 + if (identity.isEmpty()) { + return todoKey; } - return String.format("%s-%s-%s", mergeOperatorId, workRuntimeId, nodeId); + return todoKey + IDENTITY_KEY_SUFFIX + identity; } else { return String.valueOf(id); } @@ -591,8 +621,10 @@ public void update(FlowSession flowSession, boolean pass) { this.updateTime = System.currentTimeMillis(); this.recordState = pass ? SATE_RECORD_DONE : SATE_RECORD_TODO; - // 设置流程干预人信息,流程干预只能由流程管理员才能操作 - if (flowSession.getCurrentOperator().getUserId() != this.currentOperatorId) { + // 设置流程干预人信息,流程干预只能由流程管理员才能操作。 + // 参与人由 (userId, identity) 共同标识:同一人员以另一个身份办理,同样属于干预(issue #288) + if (flowSession.getCurrentOperator().getUserId() != this.currentOperatorId + || !OperatorIdentity.same(OperatorIdentity.of(flowSession.getCurrentOperator()), this.currentOperatorIdentity)) { this.interferedOperatorId = flowSession.getCurrentOperator().getUserId(); this.interferedOperatorName = flowSession.getCurrentOperator().getName(); this.interferedOperatorIdentity = OperatorIdentity.of(flowSession.getCurrentOperator()); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java index 3bf5262f..39359a2c 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java @@ -53,8 +53,9 @@ public ActionResponse action() { ActionResponseContext.getInstance().clear(); request.verify(); - // 验证当前用户 - IFlowOperator currentOperator = flowOperatorGateway.get(request.getAdvice().getOperatorId()); + // 验证当前用户(按请求声明的身份加载,issue #288) + IFlowOperator currentOperator = flowOperatorGateway.get( + request.getAdvice().getOperatorId(), request.getAdvice().getOperatorIdentity()); if (currentOperator == null) { throw FlowNotFoundException.operator(request.getAdvice().getOperatorId()); } @@ -66,7 +67,9 @@ public ActionResponse action() { throw FlowStateException.recordAlreadyDone(); } - IFlowOperator createdOperator = flowOperatorGateway.get(flowRecord.getCreateOperatorId()); + // 发起人按记录中的身份回查,避免同一 id 的不同身份拿到同一个操作者实例 + IFlowOperator createdOperator = flowOperatorGateway.get( + flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity()); WorkflowRuntime workflowRuntime = workflowService.getWorkflowRuntime(flowRecord.getWorkRuntimeId()); if (workflowRuntime == null) { @@ -78,7 +81,7 @@ public ActionResponse action() { long recordOperatorId = flowRecord.getCurrentOperatorId(); WorkflowStrategyManager workflowStrategyManager = workflow.strategyManager(); - workflowStrategyManager.verifyOperator(currentOperator, recordOperatorId); + workflowStrategyManager.verifyOperator(currentOperator, recordOperatorId, flowRecord.getCurrentOperatorIdentity()); IFlowNode currentNode = workflow.getFlowNode(flowRecord.getNodeId()); if (currentNode == null) { 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 7f0de567..95bc734c 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 @@ -57,8 +57,8 @@ public long create() { // 获取或创建运行时快照 WorkflowRuntime workflowRuntime = workflowService.getOrCreateWorkflowRuntime(workflow); FlowRuntimeScriptLocalCache.getInstance().set(workflowRuntime.getScripts()); - // 验证当前用户 - IFlowOperator currentOperator = flowOperatorGateway.get(request.getOperatorId()); + // 验证当前用户(按请求声明的身份加载,同一人不同身份是不同参与人) + IFlowOperator currentOperator = flowOperatorGateway.get(request.getOperatorId(), request.getOperatorIdentity()); if (!workflow.matchCreatedOperator(currentOperator)) { throw FlowPermissionException.accessDenied("create workflow"); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDelayTriggerService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDelayTriggerService.java index a0027ca9..3d7ec688 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDelayTriggerService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDelayTriggerService.java @@ -60,9 +60,12 @@ public void trigger() { Workflow workflow = workflowRuntime.toWorkflow(); IFlowNode currentNode = workflow.getFlowNode(flowRecord.getNodeId()); - IFlowOperator createdOperator = flowOperatorGateway.get(flowRecord.getCreateOperatorId()); - IFlowOperator submitOperator = flowOperatorGateway.get(flowRecord.getSubmitOperatorId()); - IFlowOperator currentOperator = flowOperatorGateway.get(flowRecord.getCurrentOperatorId()); + IFlowOperator createdOperator = flowOperatorGateway.get( + flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity()); + IFlowOperator submitOperator = flowOperatorGateway.get( + flowRecord.getSubmitOperatorId(), flowRecord.getSubmitOperatorIdentity()); + IFlowOperator currentOperator = flowOperatorGateway.get( + flowRecord.getCurrentOperatorId(), flowRecord.getCurrentOperatorIdentity()); IFlowAction flowAction = currentNode.actionManager().getActionById(flowRecord.getActionId()); // 延迟任务固化的前驱记录可能为相同人员自动通过的留痕记录(无审批动作,actionId=null,issue #226): // 以该记录所在审批节点的通过动作兜底恢复流转,避免 NPE 使流程永久停滞在延迟节点 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 a0cfa86e..e18f24f5 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 @@ -6,6 +6,7 @@ import com.codingapi.flow.exception.FlowStateException; import com.codingapi.flow.mock.MockRepositoryHolder; import com.codingapi.flow.node.nodes.StartNode; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.pojo.request.FlowDeleteRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.FlowRecordService; @@ -60,8 +61,9 @@ public void delete() { if (afterRecords != null && !afterRecords.isEmpty()) { throw FlowStateException.recordAlreadyRunning(); } - // 权限校验:仅允许当前待办处理人删除 - if (currentRecord.getCurrentOperatorId() != request.getOperatorId()) { + // 权限校验:仅允许当前待办处理人删除;同一人的不同身份是不同参与人(issue #288) + if (currentRecord.getCurrentOperatorId() != request.getOperatorId() + || !OperatorIdentity.same(currentRecord.getCurrentOperatorIdentity(), request.getOperatorIdentity())) { throw FlowStateException.operatorNotMatch(); } // 删除流程记录及其关联待办 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 fc9f362e..086aa8c9 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 @@ -37,7 +37,7 @@ public class FlowDetailService { public FlowDetailService(FlowDetailRequest request, IRepositoryHolder repositoryHolder) { this.request = request; - this.currentOperator = repositoryHolder.getOperatorById(request.getOperatorId()); + this.currentOperator = repositoryHolder.getOperatorById(request.getOperatorId(), request.getOperatorIdentity()); this.flowRecordService = repositoryHolder.getFlowRecordService(); this.workflowService = repositoryHolder.getWorkflowService(); this.repositoryHolder = repositoryHolder; @@ -74,9 +74,11 @@ public FlowContent detail() { repositoryHolder.saveRecord(flowRecord); } - IFlowOperator createOperator = repositoryHolder.getOperatorById(flowRecord.getCreateOperatorId()); + IFlowOperator createOperator = repositoryHolder.getOperatorById( + flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity()); - IFlowOperator submitOperator = repositoryHolder.getOperatorById(flowRecord.getSubmitOperatorId()); + IFlowOperator submitOperator = repositoryHolder.getOperatorById( + flowRecord.getSubmitOperatorId(), flowRecord.getSubmitOperatorIdentity()); FlowForm flowForm = workflow.getForm(); FormData formData = new FormData(flowForm); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowForceSyncService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowForceSyncService.java index 8b6d1d7c..610ccdd8 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowForceSyncService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowForceSyncService.java @@ -62,7 +62,7 @@ public FlowForceSyncResult sync() { // 最新设计必须通过校验,避免把不合法的设计同步给运行实例 latestWorkflow.verify(); - IFlowOperator operator = repositoryHolder.getOperatorById(request.getOperatorId()); + IFlowOperator operator = repositoryHolder.getOperatorById(request.getOperatorId(), request.getOperatorIdentity()); if (operator == null) { throw FlowNotFoundException.operator(request.getOperatorId()); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java index 5e50d9da..4975b99e 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java @@ -18,6 +18,7 @@ import com.codingapi.flow.node.nodes.StartNode; import com.codingapi.flow.node.nodes.SubProcessNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.pojo.request.FlowProcessNodeRequest; import com.codingapi.flow.pojo.response.ProcessNode; import com.codingapi.flow.record.FlowRecord; @@ -58,8 +59,8 @@ public class FlowProcessNodeService { // 工作流树按块深度优先展开后的展示顺序 private final Map displayNodeOrderMap; - // 流程审批记录列表 - private final Map recordOperatorMap; + // 流程审批记录列表,key 为 (userId, identity) 二元组:同一人的不同身份需要区分(issue #288) + private final Map recordOperatorMap; private final List recordList; private final List subProcessRecordList; @@ -103,15 +104,23 @@ private boolean isCreateWorkflow() { return !id.matches("^[0-9]+$"); } - private IFlowOperator loadRecordOperator(long operatorId) { - IFlowOperator flowOperator = this.recordOperatorMap.get(operatorId); + /** + * 操作者缓存键:同一人员的不同身份必须区分缓存,避免身份串味(issue #288) + */ + private static String recordOperatorKey(long operatorId, String identity) { + return operatorId + "\u0001" + OperatorIdentity.normalize(identity); + } + + private IFlowOperator loadRecordOperator(long operatorId, String identity) { + String cacheKey = recordOperatorKey(operatorId, identity); + IFlowOperator flowOperator = this.recordOperatorMap.get(cacheKey); if (flowOperator != null) { return flowOperator; } - flowOperator = this.repositoryHolder.getOperatorById(operatorId); + flowOperator = this.repositoryHolder.getOperatorById(operatorId, identity); if (flowOperator != null) { - this.recordOperatorMap.put(flowOperator.getUserId(), flowOperator); + this.recordOperatorMap.put(cacheKey, flowOperator); } return flowOperator; } @@ -134,7 +143,7 @@ private void fetchFlowRecordOperatorList() { List operatorList = this.repositoryHolder.findOperatorByIds(operatorIds); if (operatorList != null && !operatorList.isEmpty()) { for (IFlowOperator operator : operatorList) { - this.recordOperatorMap.put(operator.getUserId(), operator); + this.recordOperatorMap.put(recordOperatorKey(operator.getUserId(), OperatorIdentity.of(operator)), operator); } } } @@ -398,7 +407,7 @@ private List loadParentHistory(ParentSubProcessContext context) { for (List recordGroup : this.loadRecordPath(context.parentRecord(), parentRecords)) { List operators = recordGroup.stream() .map(record -> new ProcessNode.FlowRecordOperator( - record, this.loadRecordOperator(record.getCurrentOperatorId()))) + record, this.loadRecordOperator(record.getCurrentOperatorId(), record.getCurrentOperatorIdentity()))) .toList(); ProcessNode parentProcessNode = ProcessNode.createByRecord(operators, context.parentWorkflow()); parentProcessNode.setParentProcessRecord(true); @@ -456,7 +465,8 @@ private void fetchFlowRecordOperatorList(List records) { record.getCreateOperatorId(), record.getCurrentOperatorId(), record.getSubmitOperatorId())) - .filter(operatorId -> operatorId > 0 && !this.recordOperatorMap.containsKey(operatorId)) + .filter(operatorId -> operatorId > 0 + && !this.recordOperatorMap.containsKey(recordOperatorKey(operatorId, OperatorIdentity.DEFAULT))) .distinct() .toList(); if (operatorIds.isEmpty()) { @@ -464,7 +474,8 @@ private void fetchFlowRecordOperatorList(List records) { } List operatorList = this.repositoryHolder.findOperatorByIds(operatorIds); if (operatorList != null) { - operatorList.forEach(operator -> this.recordOperatorMap.put(operator.getUserId(), operator)); + operatorList.forEach(operator -> this.recordOperatorMap.put( + recordOperatorKey(operator.getUserId(), OperatorIdentity.of(operator)), operator)); } } @@ -499,7 +510,7 @@ private List loadLatestRecords() { private void loadNextData() { if (this.flowRecord == null) { IFlowNode currentNode = this.workflow.getStartNode(); - IFlowOperator currentOperator = this.loadRecordOperator(this.request.getOperatorId()); + IFlowOperator currentOperator = this.loadRecordOperator(this.request.getOperatorId(), this.request.getOperatorIdentity()); FlowSession flowSession = this.buildFlowSession(null, currentNode, currentOperator, currentOperator, currentOperator, 0); List flowRecords = currentNode.generateCurrentRecords(flowSession); FlowRecord startRecord = flowRecords.get(0); @@ -509,7 +520,7 @@ private void loadNextData() { this.fetchFlowNode(flowSession); } else { List todoLatestRecords = this.loadLatestRecords(); - IFlowOperator currentOperator = this.loadRecordOperator(this.request.getOperatorId()); + IFlowOperator currentOperator = this.loadRecordOperator(this.request.getOperatorId(), this.request.getOperatorIdentity()); if (!todoLatestRecords.isEmpty()) { // 同一节点存在多条待办(如会签/或签)时,向后预览只需按节点遍历一次, // 否则下游节点会随待办条数被重复展示 @@ -522,8 +533,10 @@ private void loadNextData() { } for (FlowRecord todoRecord : nodeTodoMap.values()) { IFlowNode currentNode = this.workflow.getFlowNode(todoRecord.getNodeId()); - IFlowOperator createOperator = this.loadRecordOperator(todoRecord.getCreateOperatorId()); - IFlowOperator submitOperator = this.loadRecordOperator(todoRecord.getSubmitOperatorId()); + IFlowOperator createOperator = this.loadRecordOperator( + todoRecord.getCreateOperatorId(), todoRecord.getCreateOperatorIdentity()); + IFlowOperator submitOperator = this.loadRecordOperator( + todoRecord.getSubmitOperatorId(), todoRecord.getSubmitOperatorIdentity()); FlowSession flowSession = this.buildFlowSession(todoRecord, currentNode, currentOperator, createOperator, submitOperator, todoRecord.getWorkRuntimeId()); this.fetchFlowNodeReadOnly(flowSession); @@ -559,8 +572,10 @@ private void loadWaitingSubProcessNextData(IFlowOperator currentOperator) { sourceAction = sourceNode.actionManager().getAction(PassAction.class); } IFlowNode subProcessNode = this.workflow.getFlowNode(subProcessRecord.getNodeId()); - IFlowOperator createOperator = this.loadRecordOperator(parentRecord.getCreateOperatorId()); - IFlowOperator submitOperator = this.loadRecordOperator(parentRecord.getSubmitOperatorId()); + IFlowOperator createOperator = this.loadRecordOperator( + parentRecord.getCreateOperatorId(), parentRecord.getCreateOperatorIdentity()); + IFlowOperator submitOperator = this.loadRecordOperator( + parentRecord.getSubmitOperatorId(), parentRecord.getSubmitOperatorIdentity()); FormData formData = new FormData(this.workflow.getForm()); formData.reset(this.request.getFormData()); @@ -666,7 +681,7 @@ private void addFlowNode(IFlowNode flowNode, FlowSession flowSession) { if (flowNode instanceof StartNode) { List operators = new ArrayList<>(); - IFlowOperator currentOperator = this.loadRecordOperator(this.request.getOperatorId()); + IFlowOperator currentOperator = this.loadRecordOperator(this.request.getOperatorId(), this.request.getOperatorIdentity()); operators.add(currentOperator); this.previewNodeList.add(ProcessNode.createByNode(flowNode, OperatorSelectType.SCRIPT, operators)); } else { @@ -689,7 +704,10 @@ private void addFlowNode(IFlowNode flowNode, FlowSession flowSession) { private interface IFlowOperatorGateway { - IFlowOperator getFlowOperator(long operatorId); + /** + * 按 (userId, identity) 加载操作者,同一人的不同身份需要返回不同实例(issue #288) + */ + IFlowOperator getFlowOperator(long operatorId, String identity); } private static class FlowRecordOrderService { @@ -758,7 +776,8 @@ public void fetch(long formId) { for (List group : groupList.values()) { this.consumer.accept(group.stream() .map(record -> new ProcessNode.FlowRecordOperator( - record, flowOperatorGateway.getFlowOperator(record.getCurrentOperatorId()))) + record, flowOperatorGateway.getFlowOperator( + record.getCurrentOperatorId(), record.getCurrentOperatorIdentity()))) .toList()); for (FlowRecord item : group) { this.fetch(item.getId()); 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 41534d53..c69eba1a 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 @@ -84,7 +84,7 @@ public long reissue() { throw FlowNotFoundException.record(request.getSourceRecordId()); } - IFlowOperator operator = repositoryHolder.getOperatorById(request.getOperatorId()); + IFlowOperator operator = repositoryHolder.getOperatorById(request.getOperatorId(), request.getOperatorIdentity()); if (operator == null) { throw FlowNotFoundException.operator(request.getOperatorId()); } @@ -104,7 +104,7 @@ public long reissue() { // 新流程沿用源流程的发起人,二次发起后的待办回到发起人,由发起人调整数据后重新提交 long initiatorId = sourceRecord.getCreateOperatorId(); - if (repositoryHolder.getOperatorById(initiatorId) == null) { + if (repositoryHolder.getOperatorById(initiatorId, sourceRecord.getCreateOperatorIdentity()) == null) { throw FlowNotFoundException.operator(initiatorId); } @@ -151,6 +151,8 @@ private FlowCreateRequest buildCreateRequest(Workflow workflow, FlowRecord sourc createRequest.setWorkCode(workflow.getCode()); createRequest.setActionId(action.id()); createRequest.setOperatorId(sourceRecord.getCreateOperatorId()); + // 沿用源流程发起人的身份,保证二次发起后的参与人与源流程一致(issue #288) + createRequest.setOperatorIdentity(sourceRecord.getCreateOperatorIdentity()); createRequest.setFormData(this.loadFormData(sourceRecord)); // 沿用源流程的自定义标题(如子流程实例区分标题),保持重发前后的业务标识一致 if (StringUtils.hasText(sourceRecord.getWorkTitle())) { 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 e9724c05..31082bb5 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 @@ -11,6 +11,7 @@ import com.codingapi.flow.manager.NodeStrategyManager; import com.codingapi.flow.mock.MockRepositoryHolder; import com.codingapi.flow.node.IFlowNode; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.pojo.request.FlowRevokeRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.FlowRecordService; @@ -68,7 +69,9 @@ public void revoke() { throw FlowStateException.recordNotSupportRevoke(); } long currentOperatorId = currentRecord.getCurrentOperatorId(); - if (currentOperatorId != request.getOperatorId()) { + // 同一人的不同身份是不同参与人:身份也必须一致,否则 user1 可以用 department1 的身份撤回 department2 的办理(issue #288) + if (currentOperatorId != request.getOperatorId() + || !OperatorIdentity.same(currentRecord.getCurrentOperatorIdentity(), request.getOperatorIdentity())) { throw FlowStateException.operatorNotMatch(); } WorkflowRuntime workflowRuntime = workflowService.getWorkflowRuntime(currentRecord.getWorkRuntimeId()); 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 93384453..48cfa8ec 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 @@ -12,6 +12,7 @@ import com.codingapi.flow.mock.MockRepositoryHolder; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.request.FlowCreateRequest; import com.codingapi.flow.pojo.request.FlowSubProcessResetRequest; @@ -73,7 +74,8 @@ public void reset() { if (!currentRecord.isTodo()) { throw FlowStateException.recordAlreadyDone(); } - if (currentRecord.getCurrentOperatorId() != request.getOperatorId()) { + if (currentRecord.getCurrentOperatorId() != request.getOperatorId() + || !OperatorIdentity.same(currentRecord.getCurrentOperatorIdentity(), request.getOperatorIdentity())) { throw FlowStateException.operatorNotMatch(); } @@ -181,7 +183,7 @@ public void reset() { } boolean mock = repositoryHolder instanceof MockRepositoryHolder; - IFlowOperator resetOperator = repositoryHolder.getOperatorById(request.getOperatorId()); + IFlowOperator resetOperator = repositoryHolder.getOperatorById(request.getOperatorId(), request.getOperatorIdentity()); for (FlowRecord invalidatedRecord : invalidatedRecords) { FlowEventPublisher.push(new FlowRecordRevokeEvent(invalidatedRecord, mock)); } 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 ea07c009..5cf78f49 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 @@ -11,6 +11,7 @@ import com.codingapi.flow.manager.WorkflowStrategyManager; import com.codingapi.flow.mock.MockRepositoryHolder; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.pojo.request.FlowUrgeRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.FlowRecordService; @@ -61,7 +62,8 @@ public void urge() { } long currentOperatorId = currentRecord.getCurrentOperatorId(); - if (currentOperatorId != request.getOperatorId()) { + if (currentOperatorId != request.getOperatorId() + || !OperatorIdentity.same(currentRecord.getCurrentOperatorIdentity(), request.getOperatorIdentity())) { throw FlowStateException.operatorNotMatch(); } @@ -79,7 +81,7 @@ public void urge() { } } - IFlowOperator currentOperator = flowOperatorGateway.get(currentOperatorId); + IFlowOperator currentOperator = flowOperatorGateway.get(currentOperatorId, request.getOperatorIdentity()); List todoRecords = flowRecordService.findFlowRecordTodoRecords(currentRecord.getProcessId()); // 保存催办记录 diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/SubProcessSessionFactory.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/SubProcessSessionFactory.java index d2befe42..5b28a547 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/SubProcessSessionFactory.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/SubProcessSessionFactory.java @@ -60,9 +60,12 @@ public static FlowSession createParentSession(SubProcessRecord subProcessRecord, if (action == null && parentRecord.isAutoDone()) { action = sourceNode.actionManager().getAction(PassAction.class); } - IFlowOperator currentOperator = repositoryHolder.getOperatorById(parentRecord.getCurrentOperatorId()); - IFlowOperator createdOperator = repositoryHolder.getOperatorById(parentRecord.getCreateOperatorId()); - IFlowOperator submitOperator = repositoryHolder.getOperatorById(parentRecord.getSubmitOperatorId()); + IFlowOperator currentOperator = repositoryHolder.getOperatorById( + parentRecord.getCurrentOperatorId(), parentRecord.getCurrentOperatorIdentity()); + IFlowOperator createdOperator = repositoryHolder.getOperatorById( + parentRecord.getCreateOperatorId(), parentRecord.getCreateOperatorIdentity()); + IFlowOperator submitOperator = repositoryHolder.getOperatorById( + parentRecord.getSubmitOperatorId(), parentRecord.getSubmitOperatorIdentity()); FormData formData = new FormData(workflow.getForm()); formData.reset(parentRecord.getFormData()); FlowAdvice advice = parentRecord.toAdvice(workflow); 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 9680baa2..da776037 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 @@ -88,13 +88,28 @@ public interface IRepositoryHolder { /** - * 获取流程操作人 + * 获取流程操作人(默认身份) * * @param id 人员id * @return 流程操作人 */ IFlowOperator getOperatorById(long id); + /** + * 按身份获取流程操作人(issue #288) + * + *

    同一个人员可能以不同身份参与流程,按记录回查操作者时必须带上记录里的身份, + * 否则同一 id 的不同身份会拿到同一个操作者实例。 + * 默认实现忽略身份、退化为 {@link #getOperatorById(long)},下游存量实现无需改动。 + * + * @param id 人员id + * @param identity 身份标识,{@code null} 与空串等价(默认身份) + * @return 流程操作人 + */ + default IFlowOperator getOperatorById(long id, String identity) { + return getOperatorById(id); + } + /** * 保存延迟任务 diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCacheTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCacheTest.java new file mode 100644 index 00000000..4cb9dfee --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCacheTest.java @@ -0,0 +1,85 @@ +package com.codingapi.flow.cache; + +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +/** + * 操作者线程缓存的身份维度测试(issue #288 P2)。 + * + *

    缓存键必须是 {@code (userId, identity)}:以 userId 为唯一键时,同一人员的两个身份 + * 会命中同一个缓存对象,身份「串味」——department2 的审批人可能拿到 department1 的身份。 + */ +class FlowOperatorLocalThreadCacheTest { + + private FlowOperatorLocalThreadCache cache; + + @BeforeEach + void setUp() { + cache = FlowOperatorLocalThreadCache.getInstance(); + cache.clear(); + } + + /** + * 同一 userId 的两个身份必须分别缓存,互不覆盖。 + */ + @Test + void should_isolate_cache_by_identity() { + User department1 = User.withIdentity(1, "user1", "department1"); + User department2 = User.withIdentity(1, "user1", "department2"); + + cache.sync(department1); + cache.sync(department2); + + assertSame(department1, cache.get(1, "department1", () -> null)); + assertSame(department2, cache.get(1, "department2", () -> null)); + assertNotSame(cache.get(1, "department1", () -> null), cache.get(1, "department2", () -> null)); + } + + /** + * null 与空串等价:命中同一条默认身份缓存。 + */ + @Test + void should_treat_null_and_empty_identity_as_same_key() { + User defaultUser = new User(1, "user1"); + cache.sync(defaultUser); + + assertSame(defaultUser, cache.get(1, null, () -> null)); + assertSame(defaultUser, cache.get(1, "", () -> null)); + assertSame(defaultUser, cache.get(1, () -> null)); + } + + /** + * 身份未命中时走加载器,且加载结果按请求的身份登记。 + */ + @Test + void should_load_and_cache_by_requested_identity() { + User loaded = User.withIdentity(2, "user2", "department9"); + + IFlowOperator operator = cache.get(2, "department9", () -> loaded); + + assertSame(loaded, operator); + assertSame(loaded, cache.get(2, "department9", () -> null)); + // 另一个身份不会命中该缓存 + assertNull(cache.get(2, "department1", () -> null)); + } + + /** + * 批量加载是标识无关路径:结果登记在默认身份键下,避免「审批人为空」。 + */ + @Test + void should_cache_bulk_load_result_under_default_identity() { + User identityUser = User.withIdentity(3, "user3", "department1"); + + var list = cache.find(java.util.List.of(3L), ids -> java.util.List.of(identityUser)); + + assertEquals(1, list.size()); + assertSame(identityUser, cache.get(3, () -> null)); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java b/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java index ab213887..3ca0b1b9 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java @@ -2,6 +2,7 @@ import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.user.User; import java.util.HashMap; @@ -18,6 +19,19 @@ public IFlowOperator get(long id) { return cache.get(id); } + /** + * 按身份返回用户副本,模拟下游「同一人员以不同身份参与流程」的组织模型(issue #288)。 + *

    未声明身份时返回缓存中的用户本身,保持 P1 用例「用户自带默认身份」的行为。 + */ + @Override + public IFlowOperator get(long id, String identity) { + User user = cache.get(id); + if (user == null || OperatorIdentity.isDefault(identity)) { + return user; + } + return user.asIdentity(identity); + } + @Override public List findByIds(List ids) { return cache.values().stream().filter(user -> ids.contains(user.getUserId())) diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowTodoKeyIdentityTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowTodoKeyIdentityTest.java new file mode 100644 index 00000000..8ffeb329 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowTodoKeyIdentityTest.java @@ -0,0 +1,196 @@ +package com.codingapi.flow.service; + +import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.action.actions.CustomAction; +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.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.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.record.FlowRecord; +import com.codingapi.flow.record.FlowTodoRecord; +import com.codingapi.flow.script.factory.FlowGroovyScriptFactory; +import com.codingapi.flow.strategy.node.FormFieldPermissionStrategy; +import com.codingapi.flow.strategy.node.OperatorLoadStrategy; +import com.codingapi.flow.strategy.node.RecordMergeStrategy; +import com.codingapi.flow.user.User; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.WorkflowBuilder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Comparator; +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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 待办合并键的身份维度测试(issue #288 P2)。 + * + *

    核心约定(兼容追加策略):默认身份保持历史键格式,只有非空身份才追加身份后缀, + * 这样升级瞬间仍在运行的流程,其存量待办行仍是旧格式键,合并关系不会断裂。 + */ +class FlowTodoKeyIdentityTest { + + private static final long CREATOR_ID = 9; + private static final long APPROVER_ID = 1; + + private MyFlowServiceFactory factory; + private Workflow workflow; + + @BeforeEach + void setUp() { + User creator = new User(CREATOR_ID, "creator"); + factory = new MyFlowServiceFactory(); + factory.userGateway.save(creator); + GatewayContext.getInstance().setFlowOperatorGateway(factory.userGateway); + + FlowForm form = FlowFormBuilder.builder() + .name("请假流程") + .code("leave-todo-key") + .addField("请假人", "name", DataType.STRING) + .build(); + + FormFieldPermissionsBuilder permissions = FormFieldPermissionsBuilder.builder() + .addPermission("leave-todo-key", "name", PermissionType.WRITE); + + StartNode startNode = StartNode.builder() + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(permissions.build())) + .build()) + .actions(ActionBuilder.builder() + .addAction(CustomAction.defaultAction()) + .build()) + .build(); + + // 开启审批人合并:同一节点、同一审批人、同一运行时快照下的记录合并成一条待办 + ApprovalNode approvalNode = ApprovalNode.builder() + .name("经理审批") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(permissions.build())) + .addStrategy(new OperatorLoadStrategy( + FlowGroovyScriptFactory.createOperatorLoadScript("def run(request){return [1]}").getKey())) + .addStrategy(new RecordMergeStrategy(true, RecordMergeStrategy.MergeType.APPROVER)) + .build()) + .build(); + + EndNode endNode = EndNode.builder().build(); + + workflow = WorkflowBuilder.builder() + .title("请假流程") + .code("leave-todo-key") + .createdOperator(creator) + .form(form) + .addNode(startNode) + .addNode(approvalNode) + .addNode(endNode) + .build(); + factory.workflowService.saveWorkflow(workflow); + } + + private Map formData() { + return Map.of("name", "lorne"); + } + + private List startActions() { + return workflow.getStartNode().actionManager().getActions(); + } + + /** + * 发起流程并办理,让流程流转到审批节点;返回审批节点上的待办记录。 + * + * @param approverIdentity 审批人以哪个身份参与(通过网关切换默认用户身份生效) + */ + private FlowRecord createAndPassToApprover(String approverIdentity) { + // 切换审批人的默认身份:审批人由节点脚本按 id 加载(默认身份),因此这里替换网关中的用户实例 + factory.userGateway.save(User.withIdentity(APPROVER_ID, "user1", approverIdentity)); + + FlowCreateRequest createRequest = new FlowCreateRequest(); + createRequest.setWorkCode(workflow.getCode()); + createRequest.setFormData(formData()); + createRequest.setActionId(startActions().get(0).id()); + createRequest.setOperatorId(CREATOR_ID); + long recordId = factory.flowService.create(createRequest); + + FlowActionRequest actionRequest = new FlowActionRequest(); + actionRequest.setFormData(formData()); + actionRequest.setRecordId(recordId); + actionRequest.setAdvice(new FlowAdviceBody(startActions().get(0).id(), "提交", CREATOR_ID)); + factory.flowService.action(actionRequest); + + List todos = factory.flowRecordRepository.findTodoByOperator(APPROVER_ID); + assertFalse(todos.isEmpty(), "审批节点应生成一条待办"); + // 多次调用时待办可能累积,返回本次最新生成的那条 + return todos.stream().max(Comparator.comparingLong(FlowRecord::getId)).orElseThrow(); + } + + /** + * 默认身份:合并键必须是历史格式 {@code operatorId-workRuntimeId-nodeId},不带任何后缀。 + */ + @Test + void should_keep_legacy_todo_key_format_for_default_identity() { + FlowRecord record = createAndPassToApprover(""); + + assertTrue(record.isMergeable(), "审批节点应开启合并"); + String expected = String.format("%s-%s-%s", + record.getCurrentOperatorId(), record.getWorkRuntimeId(), record.getNodeId()); + assertEquals(expected, record.getTodoKey()); + assertTrue(record.getTodoKey().indexOf('#') < 0, "默认身份不应携带身份后缀"); + } + + /** + * 非空身份:合并键在历史格式后追加 {@code #identity},与默认身份、其他身份天然隔离。 + */ + @Test + void should_append_identity_suffix_for_non_default_identity() { + FlowRecord record = createAndPassToApprover("department1"); + + assertTrue(record.isMergeable(), "审批节点应开启合并"); + String expected = String.format("%s-%s-%s#department1", + record.getCurrentOperatorId(), record.getWorkRuntimeId(), record.getNodeId()); + assertEquals(expected, record.getTodoKey()); + } + + /** + * 同一人员的两个身份不能合并成一条待办:否则 department1 的待办会被 department2 覆盖。 + */ + @Test + void should_not_merge_two_identities_of_same_user() { + createAndPassToApprover("department1"); + createAndPassToApprover("department2"); + + List todos = factory.flowTodoRecordRepository.findByOperatorId(APPROVER_ID); + assertEquals(2, todos.size(), "两个身份应各自保留一条待办"); + assertTrue(todos.stream().anyMatch(todo -> todo.getTodoKey().endsWith("#department1"))); + assertTrue(todos.stream().anyMatch(todo -> todo.getTodoKey().endsWith("#department2"))); + } + + /** + * 同一身份的重复流转仍然合并:身份维度不破坏原有的合并语义。 + */ + @Test + void should_still_merge_records_with_same_identity() { + createAndPassToApprover("department1"); + createAndPassToApprover("department1"); + + List todos = factory.flowTodoRecordRepository.findByOperatorId(APPROVER_ID); + assertEquals(1, todos.size(), "同一身份应合并为一条待办"); + assertEquals(2, todos.get(0).getMargeCount()); + assertNotNull(todos.get(0).getTodoKey()); + assertTrue(todos.get(0).getTodoKey().endsWith("#department1")); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityPermissionTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityPermissionTest.java new file mode 100644 index 00000000..3c9b46d2 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityPermissionTest.java @@ -0,0 +1,182 @@ +package com.codingapi.flow.service; + +import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.action.actions.CustomAction; +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.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.manager.WorkflowStrategyManager; +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.FlowDeleteRequest; +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.OperatorLoadStrategy; +import com.codingapi.flow.strategy.workflow.InterfereStrategy; +import com.codingapi.flow.user.User; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.WorkflowBuilder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 审批判定的身份维度测试(issue #288 P3)。 + * + *

    同一人员的两个身份是**两个不同的参与人**:user1 以 department1 的身份不能办理 + * department2 的待办、不能撤销/删除对方身份的记录。身份为空时行为与历史完全一致。 + */ +class OperatorIdentityPermissionTest { + + private MyFlowServiceFactory factory; + private Workflow workflow; + + @BeforeEach + void setUp() { + User user1 = User.withIdentity(1, "user1", "department1"); + User boss = new User(2, "boss"); + factory = new MyFlowServiceFactory(); + factory.userGateway.save(user1); + factory.userGateway.save(boss); + GatewayContext.getInstance().setFlowOperatorGateway(factory.userGateway); + + FlowForm form = FlowFormBuilder.builder() + .name("请假流程") + .code("leave-identity") + .addField("请假人", "name", DataType.STRING) + .build(); + + FormFieldPermissionsBuilder permissions = FormFieldPermissionsBuilder.builder() + .addPermission("leave-identity", "name", PermissionType.WRITE); + + StartNode startNode = StartNode.builder() + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(permissions.build())) + .build()) + .actions(ActionBuilder.builder() + .addAction(CustomAction.defaultAction()) + .build()) + .build(); + + ApprovalNode approvalNode = ApprovalNode.builder() + .name("经理审批") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(permissions.build())) + .addStrategy(new OperatorLoadStrategy( + FlowGroovyScriptFactory.createOperatorLoadScript("def run(request){return [2]}").getKey())) + .build()) + .build(); + + EndNode endNode = EndNode.builder().build(); + + workflow = WorkflowBuilder.builder() + .title("请假流程") + .code("leave-identity") + .createdOperator(user1) + .form(form) + .addNode(startNode) + .addNode(approvalNode) + .addNode(endNode) + .build(); + factory.workflowService.saveWorkflow(workflow); + } + + private Map formData() { + return Map.of("name", "lorne"); + } + + private List startActions() { + return workflow.getStartNode().actionManager().getActions(); + } + + private long createFlow(String operatorIdentity) { + FlowCreateRequest request = new FlowCreateRequest(); + request.setWorkCode(workflow.getCode()); + request.setFormData(formData()); + request.setActionId(startActions().get(0).id()); + request.setOperatorId(1); + request.setOperatorIdentity(operatorIdentity); + return factory.flowService.create(request); + } + + private void action(long recordId, String operatorIdentity) { + FlowActionRequest actionRequest = new FlowActionRequest(); + actionRequest.setFormData(formData()); + actionRequest.setRecordId(recordId); + FlowAdviceBody advice = new FlowAdviceBody(startActions().get(0).id(), "同意", 1); + advice.setOperatorIdentity(operatorIdentity); + actionRequest.setAdvice(advice); + factory.flowService.action(actionRequest); + } + + /** + * 单元层面:同一 userId、不同身份必须判定为不匹配。 + */ + @Test + void should_reject_same_user_with_other_identity_in_strategy_manager() { + InterfereStrategy interfereStrategy = new InterfereStrategy(); + interfereStrategy.setEnable(false); + WorkflowStrategyManager manager = new WorkflowStrategyManager(List.of(interfereStrategy)); + + assertDoesNotThrow(() -> manager.verifyOperator(User.withIdentity(1, "user1", "department1"), 1, "department1")); + assertThrows(FlowStateException.class, + () -> manager.verifyOperator(User.withIdentity(1, "user1", "department1"), 1, "department2")); + // 身份为空(默认身份)时与历史行为一致 + assertDoesNotThrow(() -> manager.verifyOperator(new User(1, "user1"), 1, "")); + assertDoesNotThrow(() -> manager.verifyOperator(new User(1, "user1"), 1, null)); + assertThrows(FlowStateException.class, + () -> manager.verifyOperator(User.withIdentity(1, "user1", "department1"), 1, null)); + } + + /** + * 审批:以另一个身份办理同一人的待办必须被拒绝,以记录中的身份办理则放行。 + */ + @Test + void should_reject_action_with_other_identity() { + long recordId = createFlow("department1"); + FlowRecord record = factory.flowRecordRepository.get(recordId); + assertEquals("department1", record.getCurrentOperatorIdentity()); + + assertThrows(FlowStateException.class, () -> action(recordId, "department2")); + // 被拒绝后记录仍为待办,用正确身份可以正常继续 + assertTrue(factory.flowRecordRepository.get(recordId).isTodo()); + assertDoesNotThrow(() -> action(recordId, "department1")); + + List bossTodos = factory.flowRecordRepository.findTodoByOperator(2); + assertEquals(1, bossTodos.size()); + } + + /** + * 删除:以另一个身份删除同一人的待办必须被拒绝。 + */ + @Test + void should_reject_delete_with_other_identity() { + long recordId = createFlow("department1"); + + assertThrows(FlowStateException.class, () -> factory.flowService.delete( + new FlowDeleteRequest(recordId, 1, "department2"))); + assertTrue(factory.flowRecordRepository.get(recordId).isTodo()); + + assertDoesNotThrow(() -> factory.flowService.delete( + new FlowDeleteRequest(recordId, 1, "department1"))); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java b/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java index 727a43f1..6b455b9a 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java @@ -1,6 +1,7 @@ package com.codingapi.flow.user; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.script.request.GroovyScriptRequest; import java.util.Map; @@ -47,6 +48,13 @@ public static User withIdentity(long userId, String name, String identity) { return new User(userId, name, false, null, identity); } + /** + * 返回同一用户以指定身份参与的副本(保留管理员、转交人等属性) + */ + public User asIdentity(String identity) { + return new User(userId, name, manager, forwardOperator, OperatorIdentity.normalize(identity)); + } + @Override public long getUserId() { return userId; 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 d07e170b..db53663b 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 @@ -3,6 +3,7 @@ import com.codingapi.flow.mock.MockInstance; import com.codingapi.flow.mock.MockInstanceFactory; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.pojo.request.*; import com.codingapi.flow.pojo.response.ActionResponse; import com.codingapi.flow.pojo.response.FlowContent; @@ -53,27 +54,45 @@ private long loadCurrentOperatorId() { } } + /** + * 当前操作人的身份标识(issue #288)。 + * + *

    与 {@link #loadCurrentOperatorId()} 对称:优先取请求参数 {@code operatorIdentity}, + * 其次取当前登录操作者自身的身份。身份是会话级信息,因此统一在这里解析后注入各请求对象, + * 避免每个接口各自解析导致行为不一致。 + */ + private String loadCurrentOperatorIdentity() { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + if (request.getParameterMap().containsKey("operatorIdentity")) { + return OperatorIdentity.normalize(request.getParameter("operatorIdentity")); + } + IFlowOperator current = (IFlowOperator) UserContext.getInstance().current(); + return current == null ? OperatorIdentity.DEFAULT : OperatorIdentity.of(current); + } + @GetMapping("/detail") public SingleResponse detail(IdRequest idRequest) { FlowService flowService = this.loadFlowService(); long operatorId = loadCurrentOperatorId(); - return SingleResponse.of(flowService.detail(new FlowDetailRequest(idRequest.getStringId(), operatorId))); + return SingleResponse.of(flowService.detail( + new FlowDetailRequest(idRequest.getStringId(), operatorId, loadCurrentOperatorIdentity()))); } @PostMapping("/processNodes") public MultiResponse processNodes(@RequestBody FlowProcessNodeRequest request) { FlowService flowService = this.loadFlowService(); - long operatorId = loadCurrentOperatorId(); - request.setOperatorId(operatorId); + request.setOperatorId(loadCurrentOperatorId()); + request.setOperatorIdentity(loadCurrentOperatorIdentity()); return MultiResponse.of(flowService.processNodes(request)); } @PostMapping("/create") public SingleResponse create(@RequestBody FlowCreateRequest request) { FlowService flowService = this.loadFlowService(); - long operatorId = loadCurrentOperatorId(); - request.setOperatorId(operatorId); + request.setOperatorId(loadCurrentOperatorId()); + request.setOperatorIdentity(loadCurrentOperatorIdentity()); return SingleResponse.of(flowService.create(request)); } @@ -82,7 +101,7 @@ public SingleResponse create(@RequestBody FlowCreateRequest request) { public Response urge(@RequestBody IdRequest request) { FlowService flowService = this.loadFlowService(); long operatorId = loadCurrentOperatorId(); - flowService.urge(new FlowUrgeRequest(request.getLongId(), operatorId)); + flowService.urge(new FlowUrgeRequest(request.getLongId(), operatorId, loadCurrentOperatorIdentity())); return Response.buildSuccess(); } @@ -90,7 +109,7 @@ public Response urge(@RequestBody IdRequest request) { public Response revoke(@RequestBody IdRequest request) { FlowService flowService = this.loadFlowService(); long operatorId = loadCurrentOperatorId(); - flowService.revoke(new FlowRevokeRequest(request.getLongId(), operatorId)); + flowService.revoke(new FlowRevokeRequest(request.getLongId(), operatorId, loadCurrentOperatorIdentity())); return Response.buildSuccess(); } @@ -99,7 +118,7 @@ public Response revoke(@RequestBody IdRequest request) { public Response delete(@RequestBody IdRequest request) { FlowService flowService = this.loadFlowService(); long operatorId = loadCurrentOperatorId(); - flowService.delete(new FlowDeleteRequest(request.getLongId(), operatorId)); + flowService.delete(new FlowDeleteRequest(request.getLongId(), operatorId, loadCurrentOperatorIdentity())); return Response.buildSuccess(); } @@ -107,8 +126,8 @@ public Response delete(@RequestBody IdRequest request) { @PostMapping("/action") public SingleResponse action(@RequestBody FlowActionRequest request) { FlowService flowService = this.loadFlowService(); - long operatorId = loadCurrentOperatorId(); - request.updateOperatorId(operatorId); + request.updateOperatorId(loadCurrentOperatorId()); + request.updateOperatorIdentity(loadCurrentOperatorIdentity()); ActionResponse response = flowService.action(request); return SingleResponse.of(response); } @@ -121,8 +140,8 @@ public SingleResponse action(@RequestBody FlowActionRequest requ @PostMapping("/subProcess/reset") public Response resetSubProcess(@RequestBody FlowSubProcessResetRequest request) { FlowService flowService = this.loadFlowService(); - long operatorId = loadCurrentOperatorId(); - request.setOperatorId(operatorId); + request.setOperatorId(loadCurrentOperatorId()); + request.setOperatorIdentity(loadCurrentOperatorIdentity()); flowService.resetSubProcess(request); return Response.buildSuccess(); } @@ -135,8 +154,8 @@ public Response resetSubProcess(@RequestBody FlowSubProcessResetRequest request) @PostMapping("/reissue") public SingleResponse reissue(@RequestBody FlowReissueRequest request) { FlowService flowService = this.loadFlowService(); - long operatorId = loadCurrentOperatorId(); - request.setOperatorId(operatorId); + request.setOperatorId(loadCurrentOperatorId()); + request.setOperatorIdentity(loadCurrentOperatorIdentity()); return SingleResponse.of(flowService.reissue(request)); } @@ -148,8 +167,8 @@ public SingleResponse reissue(@RequestBody FlowReissueRequest request) { @PostMapping("/forceSync") public SingleResponse forceSync(@RequestBody FlowForceSyncRequest request) { FlowService flowService = this.loadFlowService(); - long operatorId = loadCurrentOperatorId(); - request.setOperatorId(operatorId); + request.setOperatorId(loadCurrentOperatorId()); + request.setOperatorIdentity(loadCurrentOperatorIdentity()); return SingleResponse.of(flowService.forceSync(request)); } diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertor.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertor.java index 56a0442e..3d44a16b 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertor.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertor.java @@ -2,6 +2,7 @@ import com.codingapi.flow.infra.entity.FlowRecordEntity; import com.codingapi.flow.infra.entity.FlowTodoRecordEntity; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.pojo.response.FlowRecordContent; import com.codingapi.flow.record.FlowRecord; @@ -21,11 +22,14 @@ public static FlowRecordContent convert(FlowTodoRecordEntity todoRecord){ content.setReadTime(todoRecord.getReadTime()); content.setCurrentOperatorId(todoRecord.getCurrentOperatorId()); content.setCurrentOperatorName(todoRecord.getCurrentOperatorName()); + content.setCurrentOperatorIdentity(OperatorIdentity.normalize(todoRecord.getCurrentOperatorIdentity())); content.setSubmitOperatorId(todoRecord.getSubmitOperatorId()); content.setSubmitOperatorName(todoRecord.getSubmitOperatorName()); + content.setSubmitOperatorIdentity(OperatorIdentity.normalize(todoRecord.getSubmitOperatorIdentity())); content.setCreateTime(todoRecord.getCreateTime()); content.setCreateOperatorId(todoRecord.getCreateOperatorId()); content.setCreateOperatorName(todoRecord.getCreateOperatorName()); + content.setCreateOperatorIdentity(OperatorIdentity.normalize(todoRecord.getCreateOperatorIdentity())); content.setTodoKey(todoRecord.getTodoKey()); content.setMargeCount(todoRecord.getMargeCount()); content.setMergeable(todoRecord.getMergeable()); @@ -51,11 +55,14 @@ public static FlowRecordContent convert(FlowRecordEntity record){ content.setReadTime(record.getReadTime()); content.setCurrentOperatorId(record.getCurrentOperatorId()); content.setCurrentOperatorName(record.getCurrentOperatorName()); + content.setCurrentOperatorIdentity(OperatorIdentity.normalize(record.getCurrentOperatorIdentity())); content.setSubmitOperatorId(record.getSubmitOperatorId()); content.setSubmitOperatorName(record.getSubmitOperatorName()); + content.setSubmitOperatorIdentity(OperatorIdentity.normalize(record.getSubmitOperatorIdentity())); content.setCreateTime(record.getCreateTime()); content.setCreateOperatorId(record.getCreateOperatorId()); content.setCreateOperatorName(record.getCreateOperatorName()); + content.setCreateOperatorIdentity(OperatorIdentity.normalize(record.getCreateOperatorIdentity())); content.setMergeable(record.getMergeable()); content.setRecordId(record.getId()); content.setTimeoutTime(record.getTimeoutTime()); diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/jpa/FlowRecordEntityRepository.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/jpa/FlowRecordEntityRepository.java index 8cb8b521..b6520f0a 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/jpa/FlowRecordEntityRepository.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/jpa/FlowRecordEntityRepository.java @@ -5,6 +5,7 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import java.util.List; @@ -42,6 +43,39 @@ public interface FlowRecordEntityRepository extends FastRepository findNotifyRecordPage(long operatorId, PageRequest pageRequest); + /** + * 按 {@code (审批人, 身份)} 分页查询待办记录(issue #288)。 + * + *

    {@code coalesce(..., '')} 保证历史数据的 NULL 身份被当作默认身份命中, + * 否则升级后存量待办会从列表中消失。 + */ + @Query("from FlowRecordEntity r where r.currentOperatorId = :operatorId " + + "and coalesce(r.currentOperatorIdentity, '') = :identity " + + "and (r.recordState = 0 and r.flowState = 0 and r.hidden=false and r.revoked = false)") + Page findTodoRecordPageByIdentity(@Param("operatorId") long operatorId, + @Param("identity") String identity, + PageRequest pageRequest); + + /** + * 按 {@code (审批人, 身份)} 分页查询已办记录(issue #288)。 + */ + @Query("from FlowRecordEntity r where r.currentOperatorId = :operatorId " + + "and coalesce(r.currentOperatorIdentity, '') = :identity " + + "and (r.recordState = 1 and r.hidden=false and r.revoked = false)") + Page findDoneRecordPageByIdentity(@Param("operatorId") long operatorId, + @Param("identity") String identity, + PageRequest pageRequest); + + /** + * 按 {@code (审批人, 身份)} 分页查询抄送记录(issue #288)。 + */ + @Query("from FlowRecordEntity r where r.currentOperatorId = :operatorId " + + "and coalesce(r.currentOperatorIdentity, '') = :identity " + + "and r.notify = true and r.hidden=false and r.revoked = false") + Page findNotifyRecordPageByIdentity(@Param("operatorId") long operatorId, + @Param("identity") String identity, + PageRequest pageRequest); + /** * 按流程编码查询运行中的流程实例(以开始节点记录代表一个实例),用于强制同步时选择实例范围。 * diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/jpa/FlowTodoRecordEntityRepository.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/jpa/FlowTodoRecordEntityRepository.java index b6153b47..11290618 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/jpa/FlowTodoRecordEntityRepository.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/jpa/FlowTodoRecordEntityRepository.java @@ -5,6 +5,7 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import java.util.List; @@ -18,4 +19,22 @@ public interface FlowTodoRecordEntityRepository extends FastRepository findTodoRecordPage(long currentOperatorId, PageRequest pageRequest); + + /** + * 按 {@code (审批人, 身份)} 分页查询待办(issue #288)。 + * + *

    {@code coalesce(..., '')} 是刻意为之:历史数据的身份列是 NULL, + * 若直接写 {@code identity = :identity},升级后所有存量待办都会从用户列表中消失。 + * 归一化后「NULL 与空串」都命中默认身份,与引擎内的 {@code OperatorIdentity} 约定一致。 + * + * @param currentOperatorId 当前审批人 id + * @param identity 身份标识(已归一化,默认身份为空串) + * @param pageRequest 分页 + * @return 待办分页 + */ + @Query("from FlowTodoRecordEntity r where r.currentOperatorId = :operatorId " + + "and coalesce(r.currentOperatorIdentity, '') = :identity") + Page findTodoRecordPageByIdentity(@Param("operatorId") long currentOperatorId, + @Param("identity") String identity, + PageRequest pageRequest); } diff --git a/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java b/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java index 854db4e5..ead13803 100644 --- a/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java +++ b/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java @@ -4,6 +4,7 @@ import com.codingapi.flow.mock.MockInstance; import com.codingapi.flow.mock.MockInstanceFactory; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.pojo.response.FlowRecordContent; import com.codingapi.flow.query.FlowRecordQueryService; import com.codingapi.flow.query.pojo.FlowInstanceQueryRequest; @@ -53,6 +54,23 @@ private long loadCurrentOperatorId(){ } } + /** + * 当前操作人身份标识(issue #288)。 + * + *

    优先取请求参数 {@code operatorIdentity}(宿主可通过它声明「我以哪个身份查看」), + * 其次取当前登录操作者自身的身份,都为空时表示默认身份。 + */ + private String loadCurrentOperatorIdentity(){ + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + String key = request.getParameter("operatorIdentity"); + if(request.getParameterMap().containsKey("operatorIdentity")) { + return OperatorIdentity.normalize(key); + } + IFlowOperator current = (IFlowOperator) UserContext.getInstance().current(); + return current == null ? OperatorIdentity.DEFAULT : OperatorIdentity.of(current); + } + /** * 全部流程记录接口 @@ -71,9 +89,10 @@ public MultiResponse list(SearchRequest request) { @GetMapping("/todo") public MultiResponse todo(SearchRequest request) { long operatorId = loadCurrentOperatorId(); + String operatorIdentity = loadCurrentOperatorIdentity(); FlowRecordQueryService flowRecordQueryService = loadFlowService(); PageRequest pageRequest = PageRequest.of(request.getCurrent(), request.getPageSize()).withSort(Sort.by("id").descending()); - return MultiResponse.of(flowRecordQueryService.findTodoRecordPage(operatorId,pageRequest)); + return MultiResponse.of(flowRecordQueryService.findTodoRecordPage(operatorId,operatorIdentity,pageRequest)); } /** @@ -82,9 +101,10 @@ public MultiResponse todo(SearchRequest request) { @GetMapping("/notify") public MultiResponse notify(SearchRequest request) { long operatorId = loadCurrentOperatorId(); + String operatorIdentity = loadCurrentOperatorIdentity(); FlowRecordQueryService flowRecordQueryService = loadFlowService(); PageRequest pageRequest = PageRequest.of(request.getCurrent(), request.getPageSize()).withSort(Sort.by("id").descending()); - return MultiResponse.of(flowRecordQueryService.findNotifyRecordPage(operatorId,pageRequest)); + return MultiResponse.of(flowRecordQueryService.findNotifyRecordPage(operatorId,operatorIdentity,pageRequest)); } @@ -94,9 +114,10 @@ public MultiResponse notify(SearchRequest request) { @GetMapping("/done") public MultiResponse done(SearchRequest request) { long operatorId = loadCurrentOperatorId(); + String operatorIdentity = loadCurrentOperatorIdentity(); FlowRecordQueryService flowRecordQueryService = loadFlowService(); PageRequest pageRequest = PageRequest.of(request.getCurrent(), request.getPageSize()).withSort(Sort.by("id").descending()); - return MultiResponse.of(flowRecordQueryService.findDoneRecordPage(operatorId,pageRequest)); + return MultiResponse.of(flowRecordQueryService.findDoneRecordPage(operatorId,operatorIdentity,pageRequest)); } /** diff --git a/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/service/FlowRecordQueryServiceImpl.java b/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/service/FlowRecordQueryServiceImpl.java index 217ed822..2b3181e5 100644 --- a/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/service/FlowRecordQueryServiceImpl.java +++ b/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/service/FlowRecordQueryServiceImpl.java @@ -5,6 +5,7 @@ import com.codingapi.flow.infra.entity.FlowTodoRecordEntity; import com.codingapi.flow.infra.jpa.FlowRecordEntityRepository; import com.codingapi.flow.infra.jpa.FlowTodoRecordEntityRepository; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.pojo.response.FlowRecordContent; import com.codingapi.flow.query.FlowRecordQueryService; import lombok.AllArgsConstructor; @@ -33,6 +34,13 @@ public Page findTodoRecordPage(long userId, PageRequest reque } + @Override + public Page findTodoRecordPage(long userId, String identity, PageRequest request) { + Page page = flowTodoRecordEntityRepository.findTodoRecordPageByIdentity( + userId, OperatorIdentity.normalize(identity), request.withSort(Sort.by("id").descending())); + return page.map(FlowRecordContentConvertor::convert); + } + @Override public Page findNotifyRecordPage(long userId, PageRequest request) { Page page =flowRecordEntityRepository.findNotifyRecordPage(userId,request.withSort(Sort.by("id").descending())); @@ -40,12 +48,26 @@ public Page findNotifyRecordPage(long userId, PageRequest req } + @Override + public Page findNotifyRecordPage(long userId, String identity, PageRequest request) { + Page page = flowRecordEntityRepository.findNotifyRecordPageByIdentity( + userId, OperatorIdentity.normalize(identity), request.withSort(Sort.by("id").descending())); + return page.map(FlowRecordContentConvertor::convert); + } + @Override public Page findDoneRecordPage(long userId, PageRequest request) { Page page =flowRecordEntityRepository.findDoneRecordPage(userId,request.withSort(Sort.by("id").descending())); return page.map(FlowRecordContentConvertor::convert); } + @Override + public Page findDoneRecordPage(long userId, String identity, PageRequest request) { + Page page = flowRecordEntityRepository.findDoneRecordPageByIdentity( + userId, OperatorIdentity.normalize(identity), request.withSort(Sort.by("id").descending())); + return page.map(FlowRecordContentConvertor::convert); + } + @Override public Page findRunningInstancePage(String workCode, String title, PageRequest request) { PageRequest pageRequest = request.withSort(Sort.by("id").descending()); From 785910838f5740b44d7eda43b320d4fd8c324487 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Mon, 23 Nov 2026 21:53:46 +0800 Subject: [PATCH 04/35] =?UTF-8?q?feat(script):=20=E8=84=9A=E6=9C=AC?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E6=8C=89=E8=BA=AB=E4=BB=BD=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E8=80=85=EF=BC=88issue=20#288=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - IBeanFactory / FlowScriptContext 新增 getOperatorById(userId, identity),default 实现走 GatewayContext - GroovyScriptBind 新增 $bind.getOperatorByIdentity(userId, identity),脚本可让指定人员以指定身份参与, 例如审批人脚本返回 [$bind.getOperatorByIdentity(2, 'department1')] - 文档补充脚本用法示例 --- docs/Integration/operator-identity.md | 9 +++++++++ .../flow/script/request/GroovyScriptBind.java | 8 ++++++++ .../flow/script/runtime/FlowScriptContext.java | 7 +++++++ .../flow/script/runtime/IBeanFactory.java | 14 ++++++++++++++ 4 files changed, 38 insertions(+) diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md index 9f5ee36d..1a1e70ae 100644 --- a/docs/Integration/operator-identity.md +++ b/docs/Integration/operator-identity.md @@ -135,6 +135,15 @@ def run(request) { } ``` +需要「让某人以指定身份参与」时,用 `$bind.getOperatorByIdentity(id, identity)` 拿到带身份的操作者: + +```groovy +def run(request) { + // 让 user2 以 department1 的身份成为审批人(记录里落的就是 department1) + return [$bind.getOperatorByIdentity(2, 'department1')] +} +``` + ## 4. 引擎侧行为 ### 4.1 记录与待办落库 diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptBind.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptBind.java index b8f89a44..4da88028 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptBind.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptBind.java @@ -58,6 +58,14 @@ public IFlowOperator getOperatorById(@ScriptParameter(description = "用户id") return context.getOperatorById(userId); } + @ScriptFunction( + name = "getOperatorByIdentity", + description = "根据用户id与身份标识获取流程用户对象(issue #288),身份为空表示默认身份") + public IFlowOperator getOperatorByIdentity(@ScriptParameter(description = "用户id") long userId, + @ScriptParameter(description = "身份标识") String identity) { + return context.getOperatorById(userId, identity); + } + @ScriptFunction( name = "findOperatorsByIds", description = "根据用户id获取流程用户列表" diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/runtime/FlowScriptContext.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/runtime/FlowScriptContext.java index 2d4ccaec..7bdc3612 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/runtime/FlowScriptContext.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/runtime/FlowScriptContext.java @@ -44,6 +44,13 @@ public IFlowOperator getOperatorById(long userId) { return beanFactory.getOperatorById(userId); } + /** + * 按 {@code (userId, identity)} 获取操作者(issue #288) + */ + public IFlowOperator getOperatorById(long userId, String identity) { + return beanFactory.getOperatorById(userId, identity); + } + public List findOperatorsByIds(List ids) { return beanFactory.findOperatorsByIds(ids); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/runtime/IBeanFactory.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/runtime/IBeanFactory.java index 88282e8d..bd072789 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/runtime/IBeanFactory.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/runtime/IBeanFactory.java @@ -28,6 +28,20 @@ default IFlowOperator getOperatorById(long userId) { return GatewayContext.getInstance().getFlowOperator(userId); } + /** + * 按 {@code (userId, identity)} 获取操作者(issue #288)。 + * + *

    脚本需要「让某人以指定身份参与」时使用,例如审批人脚本返回 + * {@code [$bind.getOperatorByIdentity(2, 'department1')]}。 + * + * @param userId 人员 id + * @param identity 身份标识,{@code null} 与空串等价(默认身份) + * @return 操作者 + */ + default IFlowOperator getOperatorById(long userId, String identity) { + return GatewayContext.getInstance().getFlowOperator(userId, identity); + } + default List findOperatorsByIds(List ids) { return GatewayContext.getInstance().findByIds(ids); From 9af745fc3fa5cc36f4213b29156149eb31bc1e92 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Mon, 23 Nov 2026 23:06:07 +0800 Subject: [PATCH 05/35] =?UTF-8?q?fix(identity):=20=E8=A1=A5=E9=BD=90=20iss?= =?UTF-8?q?ue=20#288=20=E4=BB=A3=E7=A0=81=E8=AF=84=E5=AE=A1=E5=8F=91?= =?UTF-8?q?=E7=8E=B0=E7=9A=84=E5=81=8F=E7=A6=BB=E4=B8=8E=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=BC=BA=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 基于 PR #289 的评审结论,修复 6 个衍生问题并补齐用例: #290 详情页 currentNodeOperators 改为按 (人员id, 身份) 复合键去重, 排除当前操作人时也同时比较身份,避免同一人的第二个身份被吞掉。 #291 Mock 待办 / 已办 / 抄送查询补齐身份隔离重载,与真实 JPA 口径一致 (历史 NULL 身份按默认身份命中),带 mockKey 的联调不再串味。 #292 人员指定支持 (人员id, 身份) 二元组:新增 OperatorKey 与 operatorSelectOperators,分配表 JSON 兼容 [1,2,3] 与对象数组两种格式, 无需新增列 / DDL;PassAction 与 InitiatorSelectNodeService 统一用 hasAssignment 判定,兼容存量 map、新字段及发起时已落库的分配; 二次发起连同身份一起复制。 #293 网关与仓储持有者补批量取人身份重载,线程缓存按 (id, identity) 隔离; 流程树改为按记录身份分组预加载,消除多身份场景的 N+1 回查。 #294 新增 OperatorIdentity.validate(长度 64 / 禁止 # 与控制字符), 实体列宽与 DDL 对齐;落库前校验、读取仍宽松; 新增 OperatorIdentityGuard 对身份静默降级输出去重 WARN; clearNotify 同步清理 forwardOperatorIdentity。 #295 新增 25 个用例:多身份真实流程、Mock 查询隔离、脚本按身份取人、 批量身份缓存、身份校验与告警、转交身份清理、当前节点待审批人。 全量 478 用例 0 失败(原 453)。 文档:operator-identity.md 补充批量重载、人员指定、Mock 口径与写入约束; 升级 SQL 说明人员分配表无需改表。 Refs #290, #291, #292, #293, #294, #295 --- docs/Integration/operator-identity.md | 41 ++++ .../sql/0.3.0-operator-identity.sql | 10 + .../flow/action/actions/PassAction.java | 17 +- .../service/InitiatorSelectNodeService.java | 8 +- .../cache/FlowOperatorLocalThreadCache.java | 31 ++- .../flow/context/GatewayContext.java | 21 +- .../flow/context/RepositoryHolderContext.java | 21 ++ .../exception/FlowValidationException.java | 23 +++ .../flow/gateway/FlowOperatorGateway.java | 16 ++ .../flow/mock/MockRepositoryHolder.java | 26 ++- .../FlowRecordRepositoryMockImpl.java | 27 +++ .../FlowTodoRecordRepositoryMockImpl.java | 15 ++ .../service/FlowRecordQueryMockService.java | 32 +++ .../flow/operator/OperatorIdentity.java | 47 +++++ .../flow/operator/OperatorIdentityGuard.java | 77 +++++++ .../codingapi/flow/operator/OperatorKey.java | 52 +++++ .../flow/pojo/body/FlowAdviceBody.java | 9 + .../flow/pojo/request/FlowActionRequest.java | 3 +- .../flow/pojo/request/FlowCreateRequest.java | 10 + .../flow/pojo/response/FlowContent.java | 29 ++- .../com/codingapi/flow/record/FlowRecord.java | 2 + .../FlowOperatorAssignmentRepository.java | 30 +++ .../flow/service/impl/FlowActionService.java | 10 +- .../flow/service/impl/FlowCreateService.java | 16 +- .../service/impl/FlowProcessNodeService.java | 70 ++++--- .../flow/service/impl/FlowReissueService.java | 20 +- .../impl/OperatorAssignmentService.java | 84 +++++++- .../codingapi/flow/session/FlowAdvice.java | 8 + .../flow/session/IRepositoryHolder.java | 45 +++++ .../strategy/node/OperatorLoadStrategy.java | 52 ++++- .../cache/FlowOperatorBulkIdentityTest.java | 107 ++++++++++ .../flow/gateway/impl/UserGateway.java | 15 ++ .../FlowRecordQueryMockIdentityTest.java | 109 ++++++++++ .../operator/OperatorIdentityGuardTest.java | 59 ++++++ .../OperatorIdentityValidationTest.java | 62 ++++++ .../FlowCurrentNodeOperatorsIdentityTest.java | 190 ++++++++++++++++++ .../FlowOperatorAssignmentRepositoryImpl.java | 16 +- .../request/GroovyScriptBindIdentityTest.java | 86 ++++++++ .../FlowOperatorIdentityRecordTest.java | 24 +++ .../infra/convert/FlowRecordConvertor.java | 11 +- .../convert/FlowTodoRecordConvertor.java | 7 +- .../entity/FlowOperatorAssignmentEntity.java | 6 +- .../flow/infra/entity/FlowRecordEntity.java | 6 + .../infra/entity/FlowTodoRecordEntity.java | 4 + .../FlowOperatorAssignmentRepositoryImpl.java | 68 ++++++- 45 files changed, 1519 insertions(+), 103 deletions(-) create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityGuard.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/mock/service/FlowRecordQueryMockIdentityTest.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityGuardTest.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityValidationTest.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/pojo/response/FlowCurrentNodeOperatorsIdentityTest.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/script/request/GroovyScriptBindIdentityTest.java diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md index 1a1e70ae..08313370 100644 --- a/docs/Integration/operator-identity.md +++ b/docs/Integration/operator-identity.md @@ -82,6 +82,16 @@ public IFlowOperator get(long id, String identity) { > `get(long, String)` 在接口上是 `default` 方法,默认退化为 `get(id)`(忽略身份)。**不实现它时,请求里声明的身份不会被写入记录** —— 引擎的身份来源是操作者对象本身,而不是请求参数。多身份场景必须实现此方法。 +批量取人同样提供了两个 `default` 重载,用于流程树与人员设定场景(建议一并覆盖,避免同一批人按身份回查时退化为默认身份): + +| 接口 | 新增方法 | 未覆盖时的行为 | +|------|----------|----------------| +| `FlowOperatorGateway` | `findByIds(List, String)` | 退化为 `findByIds(ids)` | +| `IRepositoryHolder` | `findOperatorByIds(List, String)` | 退化为 `findOperatorByIds(ids)` | +| `IRepositoryHolder` | `getOperatorById(long, String)` | 退化为 `getOperatorById(id)` | + +> 引擎在 `GatewayContext#getFlowOperator(id, identity)` 处做运行期检查:请求声明了非默认身份、但回查到的操作者身份为空时,会按 `(人员id, 身份)` 去重输出一条 WARN,提示下游未覆盖带身份的取人方法。这类问题原先是**静默降级**(按身份查待办直接返回空列表),集成阶段极难定位。 + ### 3.3 请求声明身份 REST 接口支持 `operatorIdentity` 参数(与 `operatorId` 对称):未传时取当前登录操作者的身份。 @@ -105,6 +115,19 @@ curl 'http://host/api/query/record/todo?operatorId=1&operatorIdentity=department | `FlowDetailRequest` / `FlowProcessNodeRequest` | `operatorIdentity` | | `FlowReissueRequest` / `FlowForceSyncRequest` / `FlowSubProcessResetRequest` | `operatorIdentity` | +**为节点指定同一人的多个身份**:`INITIATOR_SELECT` / `APPROVER_SELECT` 节点原有 `operatorSelectMap`(`节点ID -> List`)无法表达「同一人员以两个身份参与」,新增 `operatorSelectOperators`(`节点ID -> List`),每项为 `(operatorId, identity)`: + +```java +createRequest.setOperatorSelectOperators(Map.of(approvalNodeId, List.of( + OperatorKey.of(2L, "department1"), + OperatorKey.of(2L, "department2")))); +``` + +- 同一人员的两个身份是**两项**参与人,不会被去重合并;完全相同的二元组才去重; +- `operatorSelectOperators` 优先于存量的 `operatorSelectMap`,两者都不传则不落分配关系; +- 存量调用方继续使用 `operatorSelectMap`,按默认身份处理,无需改动; +- 二次发起(reissue)会连同身份一起复制源流程的人员设定,避免重走后退化到默认身份。 + ### 3.4 在脚本中使用身份 `GroovyScriptRequest` 新增三个函数: @@ -172,6 +195,8 @@ def run(request) { 待办 / 已办 / 抄送查询按 `(currentOperatorId, currentOperatorIdentity)` 过滤,默认身份的条件写成 `coalesce(identity, '') = ''`,保证历史 NULL 行仍能被查到(否则升级后存量待办会从列表中消失)。 +**Mock 链路同口径**:带 `mockKey` 的 REST 调用走 `FlowRecordQueryMockService`,三个查询的 `identity` 重载均已实现(待办 / 抄送 / 已办),不会再退化成按 id 全量返回。前端联调与真实库路径行为一致。 + ### 4.4 判定升级为 `(userId, identity)` 以下判定统一由「只比 userId」升级为「比 userId + identity」,身份为空时与历史等价: @@ -182,6 +207,22 @@ def run(request) { - 提交人 == 审批人的自动通过判定 - 流程干预人识别 - 操作者线程缓存与网关缓存的键 +- 详情页 `currentNodeOperators`(待审批人 / 减签候选)的去重与「排除当前操作人」判定 +- 流程树批量登记操作者:按记录里的身份分组回查,与单条读取口径一致(避免 N+1) + +### 4.5 身份写入约束 + +落库前统一经 `OperatorIdentity.validate()`: + +| 约束 | 原因 | +|------|------| +| 长度 ≤ 64 | 与 DDL `VARCHAR(64)` 及实体 `@Column(length = 64)` 对齐 | +| 不含 `#` | 与待办合并键的身份后缀分隔符冲突 | +| 不含控制字符 | 内部缓存键以控制字符拼接 | + +读取路径仍用宽松的 `normalize()`(仅 null → 空串),历史数据不会被校验拦住。 + +人员分配表 `t_flow_operator_assignment` **无需改表**:身份编码在 `operatorIds` JSON 列内。全部为默认身份时保持历史格式 `[1,2,3]`;存在非默认身份时写 `[{"operatorId":2,"identity":"department1"}]`,读取端同时兼容两种格式。 ## 5. 兼容性与限制 diff --git a/docs/Integration/sql/0.3.0-operator-identity.sql b/docs/Integration/sql/0.3.0-operator-identity.sql index afa11162..7a207227 100644 --- a/docs/Integration/sql/0.3.0-operator-identity.sql +++ b/docs/Integration/sql/0.3.0-operator-identity.sql @@ -35,6 +35,16 @@ ALTER TABLE t_flow_todo_record ADD COLUMN submit_operator_identity VARCHAR(64) ALTER TABLE t_flow_todo_record ADD COLUMN current_operator_identity VARCHAR(64) NULL; +-- ----------------------------------------------------------------------------- +-- 2.1 人员分配表:无需改表(issue #288 衍生 / #292) +-- ----------------------------------------------------------------------------- +-- 「发起人设定 / 审批人设定」节点的分配关系存在 t_flow_operator_assignment.operator_ids (JSON) 中。 +-- 身份编码在该 JSON 内部完成,无需新增列、无需回填: +-- 全部默认身份 -> [1,2,3] (保持历史格式) +-- 存在指定身份 -> [{"operatorId":2,"identity":"department1"}] +-- 读取端同时兼容两种格式;存量环境不执行本段语句即可正常升级。 + + -- ----------------------------------------------------------------------------- -- 3. 索引(可选,按需执行) -- ----------------------------------------------------------------------------- diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java index 4dea88cb..bca7e0c9 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java @@ -20,6 +20,7 @@ import com.codingapi.flow.pojo.response.ActionResponse; import com.codingapi.flow.pojo.response.NodeOption; import com.codingapi.flow.record.FlowRecord; +import com.codingapi.flow.service.impl.OperatorAssignmentService; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; import com.codingapi.flow.strategy.node.MultiOperatorAuditStrategy; @@ -110,8 +111,8 @@ public void run(FlowSession flowSession) { } // 检查操作人选择:若存在需要手动设定操作人的节点且尚未设定,则提示用户 + // 判定统一交给 OperatorAssignmentService,兼容存量 map / 含身份的新字段 / 已落库的分配 List operatorSelectNodes = new ArrayList<>(); - Map> operatorSelectMap = flowSession.getAdvice().getOperatorSelectMap(); if (currentNode.getType().equalsIgnoreCase(StartNode.NODE_TYPE)) { // 发起人设定模式:开始节点提交时,扫描整个工作流中所有 INITIATOR_SELECT 节点 operatorSelectNodes.addAll(this.loadInitiatorSelectNodes(flowSession)); @@ -121,14 +122,14 @@ public void run(FlowSession flowSession) { // 只判断直接下游节点会漏掉分支内的 APPROVER_SELECT 节点(issue #259) if (nextNodes != null) { for (IFlowNode nextNode : nextNodes) { - collectApproverSelectNodes(flowSession, nextNode, operatorSelectMap, operatorSelectNodes); + collectApproverSelectNodes(flowSession, nextNode, operatorSelectNodes); } } } else { // 审批人设定模式:审批节点提交时,检查下游节点是否有 APPROVER_SELECT if (nextNodes != null) { for (IFlowNode nextNode : nextNodes) { - collectApproverSelectNodes(flowSession, nextNode, operatorSelectMap, operatorSelectNodes); + collectApproverSelectNodes(flowSession, nextNode, operatorSelectNodes); } } } @@ -261,11 +262,11 @@ public void run(FlowSession flowSession) { * 分支内的后续节点由该分支上前一个节点提交时再提示 * */ - private void collectApproverSelectNodes(FlowSession flowSession, IFlowNode node, Map> operatorSelectMap, List result) { + private void collectApproverSelectNodes(FlowSession flowSession, IFlowNode node, List result) { OperatorSelectType selectType = node.strategyManager().getOperatorSelectType(); if (selectType == OperatorSelectType.APPROVER_SELECT) { - if (operatorSelectMap == null || !operatorSelectMap.containsKey(node.getId()) - || operatorSelectMap.get(node.getId()).isEmpty()) { + // 兼容存量 map、含身份的新字段,以及发起时已落库的分配(issue #288 衍生 / #292) + if (!OperatorAssignmentService.hasAssignment(flowSession, node.getId())) { List range = node.strategyManager() .loadOperatorRange(flowSession.updateSession(node)); result.add(new NodeOption(node, range)); @@ -283,12 +284,12 @@ private void collectApproverSelectNodes(FlowSession flowSession, IFlowNode node, blocks = blocks.get(0).filterBranches(blocks, flowSession); } for (IFlowNode block : blocks) { - collectApproverSelectNodes(flowSession, block, operatorSelectMap, result); + collectApproverSelectNodes(flowSession, block, result); } } else if (nodeState.isBranchNode()) { // 分支节点:仅检查分支的首个节点,分支内后续节点由前序节点提交时再提示(issue #231) for (IFlowNode firstNode : nodeState.getFirstBlocks()) { - collectApproverSelectNodes(flowSession, firstNode, operatorSelectMap, result); + collectApproverSelectNodes(flowSession, firstNode, result); } } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/service/InitiatorSelectNodeService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/service/InitiatorSelectNodeService.java index bbe536fc..c5cd516f 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/service/InitiatorSelectNodeService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/service/InitiatorSelectNodeService.java @@ -3,24 +3,22 @@ import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.pojo.response.NodeOption; +import com.codingapi.flow.service.impl.OperatorAssignmentService; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.strategy.node.OperatorSelectType; import lombok.Getter; import java.util.ArrayList; import java.util.List; -import java.util.Map; public class InitiatorSelectNodeService { @Getter private final List operatorSelectNodes = new ArrayList<>(); - private final Map> operatorSelectMap; private final FlowSession flowSession; public InitiatorSelectNodeService(FlowSession flowSession) { this.flowSession = flowSession; - this.operatorSelectMap = flowSession.getAdvice().getOperatorSelectMap(); } @@ -35,8 +33,8 @@ private void appendNodes(List currentNodes) { for (IFlowNode node : currentNodes) { OperatorSelectType selectType = node.strategyManager().getOperatorSelectType(); if (selectType == OperatorSelectType.INITIATOR_SELECT) { - if (operatorSelectMap == null || !operatorSelectMap.containsKey(node.getId()) - || operatorSelectMap.get(node.getId()).isEmpty()) { + // 兼容存量 map、含身份的新字段,以及发起时已落库的分配(issue #288 衍生 / #292) + if (!OperatorAssignmentService.hasAssignment(this.flowSession, node.getId())) { List range = node.strategyManager() .loadOperatorRange(this.flowSession.updateSession(node)); operatorSelectNodes.add(new NodeOption(node, range)); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java b/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java index 333568e8..6638e104 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java @@ -101,6 +101,22 @@ public IFlowOperator get(long id, String identity, Supplier opera * 因此这里固定使用默认身份作为缓存键,与历史行为一致。 */ public List find(List ids, IFlowOperatorFinder flowOperatorFinder) { + return this.find(ids, OperatorIdentity.DEFAULT, flowOperatorFinder); + } + + /** + * 按身份批量读取操作者(issue #288 衍生 / #293)。 + * + *

    用于「一批人员以同一个身份参与流程」的场景(例如同一部门下的多个审批人): + * 结果登记在 {@code (id, identity)} 键下,按同一身份读取时可直接命中, + * 避免同一批人员被逐条回查。 + * + * @param ids 人员 id 列表 + * @param identity 身份标识,{@code null} 与空串等价 + * @param operatorFinder 缓存未命中时的批量加载器 + * @return 操作者列表(按入参 ids 顺序,加载不到的 id 会被跳过) + */ + public List find(List ids, String identity, IFlowOperatorFinder operatorFinder) { if (ids == null || ids.isEmpty()) { return null; } @@ -113,20 +129,21 @@ public List find(List ids, IFlowOperatorFinder flowOperator return null; } + String normalizedIdentity = OperatorIdentity.normalize(identity); + Map operatorCaches = this.getCache(); List queryIds = ids.stream() - .filter((id) -> !operatorCaches.containsKey(cacheKey(id, OperatorIdentity.DEFAULT))) + .filter((id) -> !operatorCaches.containsKey(cacheKey(id, normalizedIdentity))) .toList(); if (!queryIds.isEmpty()) { - List newOperatorList = flowOperatorFinder.find(queryIds); + List newOperatorList = operatorFinder.find(queryIds); if (newOperatorList != null && !newOperatorList.isEmpty()) { for (IFlowOperator operator : newOperatorList) { - // 批量加载是「按 id 查询」的标识无关路径:结果统一登记在默认身份键下, - // 与下面按默认身份读取保持一致。否则下游返回自带身份的操作者会被登记到身份键, - // 读取时按默认键取不到,表现为「审批人为空」。 - operatorCaches.put(cacheKey(operator.getUserId(), OperatorIdentity.DEFAULT), operator); + // 结果按「请求身份」登记,而不是操作者对象自带身份: + // 调用方是按该身份发起查询的,登记键必须与读取键一致,否则读取时必然落空 + operatorCaches.put(cacheKey(operator.getUserId(), normalizedIdentity), operator); } this.cache.set(operatorCaches); } @@ -135,7 +152,7 @@ public List find(List ids, IFlowOperatorFinder flowOperator // 按入参 ids 顺序返回,避免缓存命中情况影响结果顺序,保证多人审批顺序稳定 List operatorList = new ArrayList<>(); for (long id : ids) { - IFlowOperator operator = operatorCaches.get(cacheKey(id, OperatorIdentity.DEFAULT)); + IFlowOperator operator = operatorCaches.get(cacheKey(id, normalizedIdentity)); if (operator != null) { operatorList.add(operator); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java b/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java index 4409e116..502a277f 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java @@ -4,6 +4,7 @@ import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityGuard; import lombok.Getter; import lombok.Setter; @@ -42,12 +43,30 @@ public IFlowOperator getFlowOperator(long userId) { * @return 操作者 */ public IFlowOperator getFlowOperator(long userId, String identity) { - return FlowOperatorLocalThreadCache.getInstance() + IFlowOperator operator = FlowOperatorLocalThreadCache.getInstance() .get(userId, identity, () -> flowOperatorGateway.get(userId, identity)); + // 下游未覆盖带身份的取人方法时身份会被静默丢弃,这里补一条去重告警(issue #288 衍生 / #294) + OperatorIdentityGuard.check(userId, identity, operator); + return operator; } public List findByIds(List ids) { return FlowOperatorLocalThreadCache.getInstance().find(ids,(idList)-> flowOperatorGateway.findByIds(idList)); } + /** + * 按身份批量获取操作者(issue #288 衍生 / #293)。 + * + *

    整批人员使用同一个身份,结果按 {@code (id, identity)} 缓存, + * 避免多身份场景下同一批人员被逐条回查。 + * + * @param ids 人员 id 列表 + * @param identity 身份标识,{@code null} 与空串等价(默认身份) + * @return 操作者列表 + */ + public List findByIds(List ids, String identity) { + return FlowOperatorLocalThreadCache.getInstance() + .find(ids, identity, (idList) -> flowOperatorGateway.findByIds(idList, identity)); + } + } 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 ea535b15..45a74067 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 @@ -5,6 +5,7 @@ import com.codingapi.flow.exception.FlowStateException; import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.repository.DelayTaskRepository; import com.codingapi.flow.repository.FlowOperatorAssignmentRepository; @@ -133,6 +134,11 @@ public List findOperatorByIds(List ids) { return GatewayContext.getInstance().findByIds(ids); } + @Override + public List findOperatorByIds(List ids, String identity) { + return GatewayContext.getInstance().findByIds(ids, identity); + } + public IFlowOperator getOperatorById(long id) { return GatewayContext.getInstance().getFlowOperator(id); @@ -160,6 +166,11 @@ public IFlowOperator get(long id, String identity) { public List findByIds(List ids) { return GatewayContext.getInstance().findByIds(ids); } + + @Override + public List findByIds(List ids, String identity) { + return GatewayContext.getInstance().findByIds(ids, identity); + } }; } @@ -223,8 +234,18 @@ public void saveOperatorAssignment(String processId, String nodeId, List o flowOperatorAssignmentRepository.save(processId, nodeId, operatorIds); } + @Override + public void saveOperatorAssignments(String processId, String nodeId, List operators) { + flowOperatorAssignmentRepository.saveOperators(processId, nodeId, operators); + } + @Override public List findAssignedOperatorIds(String processId, String nodeId) { return flowOperatorAssignmentRepository.findOperatorIds(processId, nodeId); } + + @Override + public List findAssignedOperators(String processId, String nodeId) { + return flowOperatorAssignmentRepository.findOperators(processId, nodeId); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java b/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java index d7f9d03a..a0ac5ebb 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java @@ -133,4 +133,27 @@ public static FlowValidationException operatorCountExceeded(String nodeId, int m return new FlowValidationException("validation.operator.countExceeded", String.format("Selected operators for node '%s' exceed the max count %d", nodeId, maxOperatorCount)); } + + /** + * Operator identity exceeds the max length + * + * @param actualLength actual length + * @param maxLength max length + * @return exception + */ + public static FlowValidationException operatorIdentityTooLong(int actualLength, int maxLength) { + return new FlowValidationException("validation.operator.identity.tooLong", + String.format("Operator identity length %d exceeds the max length %d", actualLength, maxLength)); + } + + /** + * Operator identity contains an illegal character + * + * @param illegalCharacter illegal character description + * @return exception + */ + public static FlowValidationException operatorIdentityInvalid(String illegalCharacter) { + return new FlowValidationException("validation.operator.identity.invalid", + String.format("Operator identity contains an illegal character: %s", illegalCharacter)); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/gateway/FlowOperatorGateway.java b/flow-engine-framework/src/main/java/com/codingapi/flow/gateway/FlowOperatorGateway.java index bc4e64a2..5fba066f 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/gateway/FlowOperatorGateway.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/gateway/FlowOperatorGateway.java @@ -40,4 +40,20 @@ default IFlowOperator get(long id, String identity) { */ List findByIds(List ids); + /** + * 按人员 id 与统一身份批量获取操作者(issue #288 衍生 / #293)。 + * + *

    适用于「同一批人员以同一个身份参与流程」的场景(如同一部门下的多个审批人), + * 避免逐条调用 {@link #get(long, String)} 造成 N+1 回查。 + * 默认实现忽略身份、退化为 {@link #findByIds(List)},下游存量实现无需改动即可编译; + * 需要支持多身份时再覆盖此方法。 + * + * @param ids 人员 id 列表 + * @param identity 身份标识,{@code null} 与空串等价(默认身份) + * @return 操作者列表 + */ + default List findByIds(List ids, String identity) { + return findByIds(ids); + } + } 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 068d6456..3ae48e11 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 @@ -6,6 +6,7 @@ import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.mock.repository.*; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.repository.*; import com.codingapi.flow.service.FlowRecordService; @@ -39,7 +40,7 @@ public class MockRepositoryHolder implements IRepositoryHolder { private final FlowOperatorGateway flowOperatorGateway; private final SubProcessRepository subProcessRepository; private final FlowReissueRepository flowReissueRepository; - private final Map> operatorAssignmentCache = new HashMap<>(); + private final Map> operatorAssignmentCache = new HashMap<>(); public MockRepositoryHolder(FlowOperatorGateway flowOperatorGateway, WorkflowRepository workflowRepository) { @@ -86,6 +87,11 @@ public IFlowOperator get(long id, String identity) { public List findByIds(List ids) { return GatewayContext.getInstance().findByIds(ids); } + + @Override + public List findByIds(List ids, String identity) { + return GatewayContext.getInstance().findByIds(ids, identity); + } }; } @@ -114,6 +120,11 @@ public List findOperatorByIds(List ids) { return this.flowOperatorGateway.findByIds(ids); } + @Override + public List findOperatorByIds(List ids, String identity) { + return this.flowOperatorGateway.findByIds(ids, identity); + } + @Override public IFlowOperator getOperatorById(long id) { return this.flowOperatorGateway.get(id); @@ -191,11 +202,22 @@ public List findDelayTasks() { @Override public void saveOperatorAssignment(String processId, String nodeId, List operatorIds) { - operatorAssignmentCache.put(processId + ":" + nodeId, new ArrayList<>(operatorIds)); + this.saveOperatorAssignments(processId, nodeId, + operatorIds.stream().map(OperatorKey::ofDefault).toList()); + } + + @Override + public void saveOperatorAssignments(String processId, String nodeId, List operators) { + operatorAssignmentCache.put(processId + ":" + nodeId, new ArrayList<>(operators)); } @Override public List findAssignedOperatorIds(String processId, String nodeId) { + return this.findAssignedOperators(processId, nodeId).stream().map(OperatorKey::operatorId).toList(); + } + + @Override + public List findAssignedOperators(String processId, String nodeId) { return operatorAssignmentCache.getOrDefault(processId + ":" + nodeId, Collections.emptyList()); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowRecordRepositoryMockImpl.java b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowRecordRepositoryMockImpl.java index 3696516c..cb91259b 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowRecordRepositoryMockImpl.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowRecordRepositoryMockImpl.java @@ -1,5 +1,6 @@ package com.codingapi.flow.mock.repository; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.repository.FlowRecordRepository; @@ -42,6 +43,32 @@ public List findNotifyByOperator(long operatorId) { return cache.values().stream().filter(flowRecord -> flowRecord.getCurrentOperatorId() == operatorId && flowRecord.isNotify() && !flowRecord.isRevoked() && !flowRecord.isHidden()).toList(); } + /** + * 按 {@code (审批人, 身份)} 查询已办(issue #288 衍生 / #291),口径与 JPA 一致。 + */ + public List findDoneByOperator(long operatorId, String identity) { + String normalized = OperatorIdentity.normalize(identity); + return cache.values().stream() + .filter(flowRecord -> flowRecord.getCurrentOperatorId() == operatorId + && flowRecord.isDone() + && OperatorIdentity.same(flowRecord.getCurrentOperatorIdentity(), normalized)) + .toList(); + } + + /** + * 按 {@code (审批人, 身份)} 查询抄送(issue #288 衍生 / #291),口径与 JPA 一致。 + */ + public List findNotifyByOperator(long operatorId, String identity) { + String normalized = OperatorIdentity.normalize(identity); + return cache.values().stream() + .filter(flowRecord -> flowRecord.getCurrentOperatorId() == operatorId + && flowRecord.isNotify() + && !flowRecord.isRevoked() + && !flowRecord.isHidden() + && OperatorIdentity.same(flowRecord.getCurrentOperatorIdentity(), normalized)) + .toList(); + } + @Override public void save(FlowRecord flowRecord) { diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowTodoRecordRepositoryMockImpl.java b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowTodoRecordRepositoryMockImpl.java index b966b0ec..9e7e26e5 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowTodoRecordRepositoryMockImpl.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowTodoRecordRepositoryMockImpl.java @@ -1,5 +1,6 @@ package com.codingapi.flow.mock.repository; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.record.FlowTodoRecord; import com.codingapi.flow.repository.FlowTodoRecordRepository; @@ -73,6 +74,20 @@ public List findByOperatorId(long operatorId) { return cache.values().stream().filter(record -> record.getCurrentOperatorId() == operatorId).toList(); } + /** + * 按 {@code (审批人, 身份)} 查询待办(issue #288 衍生 / #291)。 + * + *

    口径与 JPA 的 {@code coalesce(currentOperatorIdentity, '') = :identity} 一致: + * 历史记录身份为 {@code null} 时按默认身份命中。 + */ + public List findByOperatorId(long operatorId, String identity) { + String normalized = OperatorIdentity.normalize(identity); + return cache.values().stream() + .filter(record -> record.getCurrentOperatorId() == operatorId + && OperatorIdentity.same(record.getCurrentOperatorIdentity(), normalized)) + .toList(); + } + public List findAll() { return cache.values().stream().toList(); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/service/FlowRecordQueryMockService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/service/FlowRecordQueryMockService.java index 9d250f73..ba9f6b33 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/service/FlowRecordQueryMockService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/service/FlowRecordQueryMockService.java @@ -67,6 +67,18 @@ public Page findTodoRecordPage(long userId, PageRequest reque return this.toPage(recordList, request); } + /** + * 按 {@code (审批人, 身份)} 查询待办(issue #288 衍生 / #291)。 + * + *

    Mock 链路与真实 JPA 链路必须口径一致,否则带 {@code mockKey} 的前端联调会看到串味数据。 + */ + @Override + public Page findTodoRecordPage(long userId, String identity, PageRequest request) { + FlowTodoRecordRepositoryMockImpl flowTodoRecordRepositoryMock = (FlowTodoRecordRepositoryMockImpl) mockRepositoryHolder.getFlowTodoRecordRepository(); + List recordList = flowTodoRecordRepositoryMock.findByOperatorId(userId, identity).stream().map(FlowRecordContent::convert).toList(); + return this.toPage(recordList, request); + } + @Override public Page findNotifyRecordPage(long userId, PageRequest request) { FlowRecordRepositoryMockImpl flowRecordRepositoryMock = (FlowRecordRepositoryMockImpl) mockRepositoryHolder.getFlowRecordRepository(); @@ -74,6 +86,16 @@ public Page findNotifyRecordPage(long userId, PageRequest req return toPage(recordList, request); } + /** + * 按 {@code (审批人, 身份)} 查询抄送(issue #288 衍生 / #291)。 + */ + @Override + public Page findNotifyRecordPage(long userId, String identity, PageRequest request) { + FlowRecordRepositoryMockImpl flowRecordRepositoryMock = (FlowRecordRepositoryMockImpl) mockRepositoryHolder.getFlowRecordRepository(); + List recordList = flowRecordRepositoryMock.findNotifyByOperator(userId, identity).stream().map(FlowRecordContent::convert).toList(); + return toPage(recordList, request); + } + @Override public Page findDoneRecordPage(long userId, PageRequest request) { FlowRecordRepositoryMockImpl flowRecordRepositoryMock = (FlowRecordRepositoryMockImpl) mockRepositoryHolder.getFlowRecordRepository(); @@ -81,6 +103,16 @@ public Page findDoneRecordPage(long userId, PageRequest reque return toPage(recordList, request); } + /** + * 按 {@code (审批人, 身份)} 查询已办(issue #288 衍生 / #291)。 + */ + @Override + public Page findDoneRecordPage(long userId, String identity, PageRequest request) { + FlowRecordRepositoryMockImpl flowRecordRepositoryMock = (FlowRecordRepositoryMockImpl) mockRepositoryHolder.getFlowRecordRepository(); + List recordList = flowRecordRepositoryMock.findDoneByOperator(userId, identity).stream().map(FlowRecordContent::convert).toList(); + return toPage(recordList, request); + } + @Override public Page findRunningInstancePage(String workCode, String title, PageRequest request) { FlowRecordRepositoryMockImpl flowRecordRepositoryMock = (FlowRecordRepositoryMockImpl) mockRepositoryHolder.getFlowRecordRepository(); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java index b31beb23..afe2c645 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java @@ -1,5 +1,7 @@ package com.codingapi.flow.operator; +import com.codingapi.flow.exception.FlowValidationException; + /** * 身份标识归一化工具。 * @@ -20,6 +22,20 @@ public final class OperatorIdentity { */ public static final String DEFAULT = ""; + /** + * 身份标识最大长度,与 DDL({@code VARCHAR(64)})保持一致。 + * + *

    实体列宽与本常量对齐,避免「自动建表 255 / 手工建表 64」两种环境行为不一致导致截断。 + */ + public static final int MAX_LENGTH = 64; + + /** + * 待办合并键中用于拼接身份的分隔符。 + * + *

    身份本身不允许包含该字符,否则「身份」与「合并键后缀」语义无法区分。 + */ + public static final String KEY_SEPARATOR = "#"; + private OperatorIdentity() { } @@ -33,6 +49,37 @@ public static String normalize(String identity) { return identity == null ? DEFAULT : identity; } + /** + * 校验并归一化身份标识(写入 / 落库前调用)。 + * + *

    约束: + *

      + *
    • 长度不超过 {@link #MAX_LENGTH},与 DDL 列宽一致;
    • + *
    • 不允许包含 {@link #KEY_SEPARATOR},否则与待办合并键的后缀语义冲突;
    • + *
    • 不允许包含控制字符,避免污染内部以控制字符拼接的缓存键。
    • + *
    + * + * @param identity 原始身份标识,{@code null} 与空串等价(默认身份) + * @return 归一化后的身份标识 + * @throws FlowValidationException 身份标识不合法 + */ + public static String validate(String identity) { + String normalized = normalize(identity); + if (normalized.length() > MAX_LENGTH) { + throw FlowValidationException.operatorIdentityTooLong(normalized.length(), MAX_LENGTH); + } + if (normalized.contains(KEY_SEPARATOR)) { + throw FlowValidationException.operatorIdentityInvalid(KEY_SEPARATOR); + } + for (int i = 0; i < normalized.length(); i++) { + char c = normalized.charAt(i); + if (Character.isISOControl(c)) { + throw FlowValidationException.operatorIdentityInvalid("\\u" + Integer.toHexString(c)); + } + } + return normalized; + } + /** * 是否为默认身份(null 或空串)。 * diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityGuard.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityGuard.java new file mode 100644 index 00000000..4d212a15 --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityGuard.java @@ -0,0 +1,77 @@ +package com.codingapi.flow.operator; + +import lombok.extern.slf4j.Slf4j; + +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * 身份透传效果检查器(issue #288 衍生 / #294)。 + * + *

    框架通过 {@code default} 方法为身份能力提供向后兼容的退化实现,当下游没有覆盖带身份的取人方法时, + * 身份会被静默丢弃:请求里带的是「部门A」,落库却变成默认身份,前端按身份查待办会得到空列表, + * 且没有任何异常或日志。这类问题在集成阶段极难定位,因此在这里补一条运行期告警。 + * + *

    告警按 {@code (人员id, 身份)} 去重,并对条目总量设上限,避免高频调用场景刷爆日志或占用内存。 + */ +@Slf4j +public final class OperatorIdentityGuard { + + /** + * 告警去重记录的条目上限 + */ + private static final int MAX_WARN_KEYS = 256; + + private static final String KEY_SEPARATOR = "\u0001"; + + private static final Set WARNED_KEYS = ConcurrentHashMap.newKeySet(); + + private OperatorIdentityGuard() { + } + + /** + * 检查身份透传是否生效:请求的为非默认身份、但回查到操作者的身份为空时输出告警。 + * + * @param operatorId 人员 id + * @param requestedIdentity 请求声明的身份 + * @param resolved 回查到的操作者,可能为 {@code null} + * @return true 表示本次实际输出了告警(同一 {@code (人员, 身份)} 只会返回一次 true) + */ + public static boolean check(long operatorId, String requestedIdentity, IFlowOperator resolved) { + if (!needWarn(requestedIdentity, resolved)) { + return false; + } + if (WARNED_KEYS.size() >= MAX_WARN_KEYS) { + return false; + } + String key = operatorId + KEY_SEPARATOR + OperatorIdentity.normalize(requestedIdentity); + if (!WARNED_KEYS.add(key)) { + return false; + } + log.warn("流程操作者身份未生效:人员[{}] 请求身份[{}],但回查到的操作者身份为空。" + + "请确认下游已覆盖 FlowOperatorGateway#get(id, identity) 与 IRepositoryHolder#getOperatorById(id, identity)," + + "否则同一人员的多身份将全部退化为默认身份(issue #288)。", + operatorId, OperatorIdentity.normalize(requestedIdentity)); + return true; + } + + /** + * 是否需要告警:请求身份非默认,且回查结果的身份为默认。 + */ + static boolean needWarn(String requestedIdentity, IFlowOperator resolved) { + if (OperatorIdentity.isDefault(requestedIdentity)) { + return false; + } + if (resolved == null) { + return false; + } + return OperatorIdentity.isDefault(OperatorIdentity.of(resolved)); + } + + /** + * 清空告警去重记录,仅用于测试隔离。 + */ + public static void resetWarnedCache() { + WARNED_KEYS.clear(); + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java new file mode 100644 index 00000000..308b4942 --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java @@ -0,0 +1,52 @@ +package com.codingapi.flow.operator; + +/** + * 操作者标识二元组 {@code (人员id, 身份)}(issue #288 衍生 / #292)。 + * + *

    同一个人员可以以不同身份参与流程,因此凡是「指向某个参与人」的持久化数据或批量参数, + * 都不能只保存人员 id。该类型用于人员分配(发起人设定 / 审批人设定)等需要显式携带身份的场景。 + * + *

    身份统一经 {@link OperatorIdentity#normalize(String)} 归一化,{@code null} 与空串等价。 + * + * @param operatorId 人员 id + * @param identity 身份标识(默认身份为空串) + */ +public record OperatorKey(long operatorId, String identity) { + + /** + * 紧凑构造:身份统一归一化,保证 {@code null} 与空串等价 + */ + public OperatorKey { + identity = OperatorIdentity.normalize(identity); + } + + /** + * 构建操作者标识 + * + * @param operatorId 人员 id + * @param identity 身份标识,{@code null} 与空串等价 + * @return 操作者标识 + */ + public static OperatorKey of(long operatorId, String identity) { + return new OperatorKey(operatorId, identity); + } + + /** + * 构建默认身份的操作者标识 + * + * @param operatorId 人员 id + * @return 操作者标识 + */ + public static OperatorKey ofDefault(long operatorId) { + return new OperatorKey(operatorId, OperatorIdentity.DEFAULT); + } + + /** + * 组装可直接用于比较 / 缓存键的字符串 + * + * @return {@code 人员id + '#' + 身份} + */ + public String key() { + return operatorId + OperatorIdentity.KEY_SEPARATOR + identity; + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/body/FlowAdviceBody.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/body/FlowAdviceBody.java index e149c8ac..54350ecf 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/body/FlowAdviceBody.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/body/FlowAdviceBody.java @@ -3,6 +3,7 @@ import com.codingapi.flow.exception.FlowValidationException; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.session.FlowSession; import lombok.Data; import lombok.NoArgsConstructor; @@ -66,9 +67,16 @@ public class FlowAdviceBody { /** * 操作人手动选择映射(节点ID -> 操作人ID列表) + *

    存量字段,仅表达人员 id(默认身份)。 */ private Map> operatorSelectMap; + /** + * 操作人手动选择映射,携带身份(issue #288 衍生 / #292) + *

    节点ID -> 选定操作人列表,每项为 {@code (人员id, 身份)},优先于 {@link #operatorSelectMap}。 + */ + private Map> operatorSelectOperators; + public FlowAdviceBody(String actionId, String advice, long operatorId) { this.actionId = actionId; @@ -87,6 +95,7 @@ public FlowAdviceBody(FlowSession flowSession) { this.manualNodeId = flowSession.getAdvice().getManualNode() != null ? flowSession.getAdvice().getManualNode().getId() : null; this.forwardOperatorIds = flowSession.getAdvice().getForwardOperators() != null ? flowSession.getAdvice().getForwardOperators().stream().map(IFlowOperator::getUserId).toList() : null; this.operatorSelectMap = flowSession.getAdvice().getOperatorSelectMap(); + this.operatorSelectOperators = flowSession.getAdvice().getOperatorSelectOperators(); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowActionRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowActionRequest.java index 20f762f5..fed286e9 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowActionRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowActionRequest.java @@ -65,8 +65,9 @@ public FlowAdvice toFlowAdvice(Workflow workflow, IFlowAction flowAction) { flowAdvice.setManualNode(workflow.getFlowNode(advice.getManualNodeId())); } - // 传递操作人手动选择映射 + // 传递操作人手动选择映射(含身份,issue #288 衍生 / #292) flowAdvice.setOperatorSelectMap(advice.getOperatorSelectMap()); + flowAdvice.setOperatorSelectOperators(advice.getOperatorSelectOperators()); return flowAdvice; } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowCreateRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowCreateRequest.java index 7f333728..d67fdbc7 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowCreateRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowCreateRequest.java @@ -1,6 +1,7 @@ package com.codingapi.flow.pojo.request; import com.codingapi.flow.exception.FlowValidationException; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.pojo.body.FlowAdviceBody; import lombok.Data; @@ -47,9 +48,17 @@ public class FlowCreateRequest { /** * 发起人手动设定的操作人映射(节点ID -> 操作人ID列表) * 用于 INITIATOR_SELECT 模式的节点 + *

    存量字段,仅表达人员 id(默认身份);需要携带身份时使用 {@link #operatorSelectOperators}。 */ private Map> operatorSelectMap; + /** + * 发起人手动设定的操作人映射,携带身份(issue #288 衍生 / #292) + *

    节点ID -> 选定操作人列表,每项为 {@code (人员id, 身份)};同一人员的两个身份是两项,不会被合并。 + * 该字段优先于 {@link #operatorSelectMap},两者都不传则不落分配关系。 + */ + private Map> operatorSelectOperators; + /** * 手动传入的流程标题(子流程实例区分用);为空时回落流程定义标题 */ @@ -63,6 +72,7 @@ public FlowActionRequest toActionRequest(long recordId) { FlowAdviceBody adviceBody = new FlowAdviceBody(this.getActionId(), null, this.getOperatorId()); adviceBody.setOperatorIdentity(this.getOperatorIdentity()); adviceBody.setOperatorSelectMap(this.getOperatorSelectMap()); + adviceBody.setOperatorSelectOperators(this.getOperatorSelectOperators()); flowActionRequest.setAdvice(adviceBody); flowActionRequest.verify(); return flowActionRequest; 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 055c70a5..e41b8626 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 @@ -8,6 +8,7 @@ import com.codingapi.flow.manager.NodeStrategyManager; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.workflow.Workflow; @@ -309,16 +310,38 @@ private List loadCurrentNodeOperators(FlowSession flowSession) { if (currentRecord == null || currentNodeRecords == null) { return List.of(); } + return resolveCurrentNodeOperators(currentRecord, currentNodeRecords); + } + + /** + * 计算当前节点实例中的待审批人员(按参与人去重,排除当前操作人)。 + * + *

    参与人由 {@code (人员id, 身份)} 共同标识:同一人员的两个身份是两个人,去重键必须带身份, + * 只按人员 id 去重会把另一个身份吞掉(issue #288 衍生 / #290)。 + * + * @param currentRecord 当前流程记录(用于取当前操作人与其身份) + * @param currentNodeRecords 当前节点的流程记录 + * @return 待审批人员列表(保持记录顺序) + */ + static List resolveCurrentNodeOperators(FlowRecord currentRecord, List currentNodeRecords) { long currentOperatorId = currentRecord.getCurrentOperatorId(); - Map operators = new LinkedHashMap<>(); + // 同一人员的不同身份是不同参与人,去重键必须是 (人员id, 身份) + Map operators = new LinkedHashMap<>(); for (FlowRecord record : currentNodeRecords) { if (record == null || !currentRecord.getProcessId().equals(record.getProcessId())) { continue; } - if (!record.isPendingApproval() || record.getCurrentOperatorId() == currentOperatorId) { + if (!record.isPendingApproval()) { + continue; + } + // 排除当前操作人时必须同时比较身份:同一人以另一个身份待审批时仍应出现在列表中 + if (record.getCurrentOperatorId() == currentOperatorId + && OperatorIdentity.same(record.getCurrentOperatorIdentity(), currentRecord.getCurrentOperatorIdentity())) { continue; } - operators.putIfAbsent(record.getCurrentOperatorId(), + String operatorKey = record.getCurrentOperatorId() + OperatorIdentity.KEY_SEPARATOR + + OperatorIdentity.normalize(record.getCurrentOperatorIdentity()); + operators.putIfAbsent(operatorKey, new FlowOperator(record.getCurrentOperatorId(), record.getCurrentOperatorName(), record.getCurrentOperatorIdentity())); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java index 45492c95..bdfb421e 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java @@ -643,6 +643,8 @@ public void clearNotify(){ this.signKey = null; this.notify = true; this.forwardOperatorId = 0; + // 转交身份必须同步清零,否则身份会残留在记录上,被后续复用带出错误的参与人身份(issue #288 衍生 / #294) + this.forwardOperatorIdentity = OperatorIdentity.DEFAULT; } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/repository/FlowOperatorAssignmentRepository.java b/flow-engine-framework/src/main/java/com/codingapi/flow/repository/FlowOperatorAssignmentRepository.java index b4ad2b42..7bc24141 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/repository/FlowOperatorAssignmentRepository.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/repository/FlowOperatorAssignmentRepository.java @@ -1,5 +1,7 @@ package com.codingapi.flow.repository; +import com.codingapi.flow.operator.OperatorKey; + import java.util.List; /** @@ -24,4 +26,32 @@ public interface FlowOperatorAssignmentRepository { * @return 操作人 ID 列表,不存在时返回空列表 */ List findOperatorIds(String processId, String nodeId); + + /** + * 保存操作人分配,携带身份标识(issue #288 衍生 / #292)。 + * + *

    {@link OperatorKey} 与 {@code List} 泛型擦除后签名相同,无法重载,因此单独命名。 + * 默认实现忽略身份、退化为 {@link #save(String, String, List)},存量实现无需改动即可编译, + * 但会丢失身份;需要支持多身份时覆盖此方法。 + * + * @param processId 流程实例唯一标识 + * @param nodeId 节点 ID + * @param operators 操作人列表(含身份) + */ + default void saveOperators(String processId, String nodeId, List operators) { + save(processId, nodeId, operators.stream().map(OperatorKey::operatorId).toList()); + } + + /** + * 查询指定节点的已分配操作人列表(含身份,issue #288 衍生 / #292)。 + * + *

    默认实现退化为 {@link #findOperatorIds(String, String)},返回的操作人身份均为默认身份。 + * + * @param processId 流程实例唯一标识 + * @param nodeId 节点 ID + * @return 操作人列表,不存在时返回空列表 + */ + default List findOperators(String processId, String nodeId) { + return findOperatorIds(processId, nodeId).stream().map(OperatorKey::ofDefault).toList(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java index 39359a2c..f84e3195 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java @@ -100,9 +100,15 @@ public ActionResponse action() { FlowSession session = flowRecord.createFlowSession(this.repositoryHolder,workflow,currentOperator,createdOperator,currentOperator,formData,flowAdvice); // 校验并持久化 APPROVER_SELECT 节点的操作人分配(含可选人员范围校验) - if (flowAdvice.getOperatorSelectMap() != null + if (flowAdvice.getOperatorSelectOperators() != null + && !flowAdvice.getOperatorSelectOperators().isEmpty()) { + // 携带身份的分配优先(issue #288 衍生 / #292) + OperatorAssignmentService.validateAndSaveOperators(session, flowRecord.getProcessId(), + flowAdvice.getOperatorSelectOperators()); + } else if (flowAdvice.getOperatorSelectMap() != null && !flowAdvice.getOperatorSelectMap().isEmpty()) { - OperatorAssignmentService.validateAndSave(session, flowRecord.getProcessId(), flowAdvice.getOperatorSelectMap()); + OperatorAssignmentService.validateAndSave(session, flowRecord.getProcessId(), + flowAdvice.getOperatorSelectMap()); } // 验证会话 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 95bc734c..ae715f65 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 @@ -91,11 +91,19 @@ public long create() { } // 校验并持久化 INITIATOR_SELECT 节点的操作人分配(含可选人员范围校验) - if (request.getOperatorSelectMap() != null - && !request.getOperatorSelectMap().isEmpty() - && !flowRecords.isEmpty()) { + boolean hasSelectOperators = request.getOperatorSelectOperators() != null + && !request.getOperatorSelectOperators().isEmpty(); + boolean hasSelectIds = request.getOperatorSelectMap() != null + && !request.getOperatorSelectMap().isEmpty(); + if ((hasSelectOperators || hasSelectIds) && !flowRecords.isEmpty()) { String processId = flowRecords.get(0).getProcessId(); - OperatorAssignmentService.validateAndSave(session, processId, request.getOperatorSelectMap()); + if (hasSelectOperators) { + // 携带身份的分配优先:同一人员的两个身份是两项,不会被合并(issue #288 衍生 / #292) + OperatorAssignmentService.validateAndSaveOperators(session, processId, + request.getOperatorSelectOperators()); + } else { + OperatorAssignmentService.validateAndSave(session, processId, request.getOperatorSelectMap()); + } } repositoryHolder.saveRecords(flowRecords); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java index 4975b99e..aa789a07 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java @@ -126,26 +126,50 @@ private IFlowOperator loadRecordOperator(long operatorId, String identity) { } private void fetchFlowRecordOperatorList() { - List operatorIds = new ArrayList<>(); + this.preloadRecordOperators(this.recordList); + } - for (FlowRecord flowRecord : this.recordList) { - if (!operatorIds.contains(flowRecord.getCreateOperatorId())) { - operatorIds.add(flowRecord.getCreateOperatorId()); - } - if (!operatorIds.contains(flowRecord.getCurrentOperatorId())) { - operatorIds.add(flowRecord.getCurrentOperatorId()); + /** + * 按 {@code (人员id, 记录中的身份)} 分组批量加载操作者(issue #288 衍生 / #293)。 + * + *

    登记缓存时使用的身份必须与读取端 {@link #loadRecordOperator(long, String)} 一致(都取记录里的身份), + * 否则批量结果读不到,会退化成逐条回查网关。按身份分组后,每个身份只发一次批量请求, + * 多身份流程树不会产生 N+1。 + */ + private void preloadRecordOperators(List records) { + if (records == null || records.isEmpty()) { + return; + } + Map> operatorIdsByIdentity = new LinkedHashMap<>(); + for (FlowRecord record : records) { + addOperatorRef(operatorIdsByIdentity, record.getCreateOperatorId(), record.getCreateOperatorIdentity()); + addOperatorRef(operatorIdsByIdentity, record.getCurrentOperatorId(), record.getCurrentOperatorIdentity()); + addOperatorRef(operatorIdsByIdentity, record.getSubmitOperatorId(), record.getSubmitOperatorIdentity()); + } + operatorIdsByIdentity.forEach((identity, operatorIds) -> { + List queryIds = operatorIds.stream() + .filter(operatorId -> !this.recordOperatorMap.containsKey(recordOperatorKey(operatorId, identity))) + .toList(); + if (queryIds.isEmpty()) { + return; } - if (!operatorIds.contains(flowRecord.getSubmitOperatorId())) { - operatorIds.add(flowRecord.getSubmitOperatorId()); + List operatorList = this.repositoryHolder.findOperatorByIds(queryIds, identity); + if (operatorList == null || operatorList.isEmpty()) { + return; } - } - - List operatorList = this.repositoryHolder.findOperatorByIds(operatorIds); - if (operatorList != null && !operatorList.isEmpty()) { for (IFlowOperator operator : operatorList) { - this.recordOperatorMap.put(recordOperatorKey(operator.getUserId(), OperatorIdentity.of(operator)), operator); + this.recordOperatorMap.put(recordOperatorKey(operator.getUserId(), identity), operator); } + }); + } + + private static void addOperatorRef(Map> operatorIdsByIdentity, long operatorId, String identity) { + if (operatorId <= 0) { + return; } + operatorIdsByIdentity + .computeIfAbsent(OperatorIdentity.normalize(identity), key -> new LinkedHashSet<>()) + .add(operatorId); } public List processNodes() { @@ -460,23 +484,7 @@ private Map loadSubProcessWorkTitles(List record } private void fetchFlowRecordOperatorList(List records) { - List operatorIds = records.stream() - .flatMap(record -> java.util.stream.Stream.of( - record.getCreateOperatorId(), - record.getCurrentOperatorId(), - record.getSubmitOperatorId())) - .filter(operatorId -> operatorId > 0 - && !this.recordOperatorMap.containsKey(recordOperatorKey(operatorId, OperatorIdentity.DEFAULT))) - .distinct() - .toList(); - if (operatorIds.isEmpty()) { - return; - } - List operatorList = this.repositoryHolder.findOperatorByIds(operatorIds); - if (operatorList != null) { - operatorList.forEach(operator -> this.recordOperatorMap.put( - recordOperatorKey(operator.getUserId(), OperatorIdentity.of(operator)), operator)); - } + this.preloadRecordOperators(records); } private record ParentSubProcessContext(FlowRecord parentRecord, 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 c69eba1a..214edf6f 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 @@ -12,6 +12,7 @@ import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.node.nodes.StartNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.pojo.request.FlowCreateRequest; import com.codingapi.flow.pojo.request.FlowReissueRequest; import com.codingapi.flow.record.FlowRecord; @@ -158,7 +159,7 @@ private FlowCreateRequest buildCreateRequest(Workflow workflow, FlowRecord sourc if (StringUtils.hasText(sourceRecord.getWorkTitle())) { createRequest.setWorkTitle(sourceRecord.getWorkTitle()); } - createRequest.setOperatorSelectMap(this.loadOperatorSelectMap(workflow, sourceRecord.getProcessId())); + createRequest.setOperatorSelectOperators(this.loadOperatorSelectOperators(workflow, sourceRecord.getProcessId())); return createRequest; } @@ -175,20 +176,23 @@ private Map loadFormData(FlowRecord sourceRecord) { } /** - * 复制源流程「发起人设定 / 审批人设定」节点的操作人分配,保证重走时人员设定与首次发起一致。 + * 复制源流程「发起人设定 / 审批人设定」节点的操作人分配(含身份),保证重走时人员设定与首次发起一致。 + * + *

    身份必须一起复制:同一人员的两个身份是两项参与人,只复制 id 会让重走后的审批人退化到默认身份 + * (issue #288 衍生 / #292)。 */ - private Map> loadOperatorSelectMap(Workflow workflow, String sourceProcessId) { - Map> operatorSelectMap = new HashMap<>(); + private Map> loadOperatorSelectOperators(Workflow workflow, String sourceProcessId) { + Map> operatorSelectOperators = 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); + List operators = repositoryHolder.findAssignedOperators(sourceProcessId, node.getId()); + if (operators != null && !operators.isEmpty()) { + operatorSelectOperators.put(node.getId(), operators); } } - return operatorSelectMap; + return operatorSelectOperators; } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/OperatorAssignmentService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/OperatorAssignmentService.java index 8e0d022e..e7a4e5c7 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/OperatorAssignmentService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/OperatorAssignmentService.java @@ -3,10 +3,14 @@ import com.codingapi.flow.exception.FlowValidationException; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; +import com.codingapi.flow.record.FlowRecord; +import com.codingapi.flow.session.FlowAdvice; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; import com.codingapi.flow.workflow.Workflow; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -23,11 +27,42 @@ private OperatorAssignmentService() { } /** - * 校验并保存操作人分配。 - *

    - * 数量校验:节点配置了最大可选人数(maxOperatorCount >= 0)时,所选人数超过上限则抛出异常。 - * 当目标节点配置了可选人员范围(范围非空)时,校验所选人员是否全部落在范围内,越界则抛出异常; - * 范围为空(未配置脚本或脚本执行结果为空)表示不限范围,跳过校验。 + * 判断指定节点是否已经设定操作人(issue #288 衍生 / #292)。 + * + *

    三种来源任一非空即视为已设定: + *

      + *
    1. 本次意见携带的存量 {@code operatorSelectMap};
    2. + *
    3. 本次意见携带的 {@code operatorSelectOperators}(含身份);
    4. + *
    5. 此前(典型为发起时)已持久化的节点分配关系。
    6. + *
    + * 只检查第 1 项会把「发起时预置的分配」和「按身份设定的分配」误判为未设定, + * 使 {@code PassAction} 反复返回 OPERATOR_SELECT,流程停滞在开始节点。 + * + * @param session 当前流程会话 + * @param nodeId 节点 ID + * @return 是否已设定操作人 + */ + public static boolean hasAssignment(FlowSession session, String nodeId) { + FlowAdvice advice = session.getAdvice(); + Map> idSelections = advice.getOperatorSelectMap(); + if (idSelections != null && idSelections.get(nodeId) != null && !idSelections.get(nodeId).isEmpty()) { + return true; + } + Map> selections = advice.getOperatorSelectOperators(); + if (selections != null && selections.get(nodeId) != null && !selections.get(nodeId).isEmpty()) { + return true; + } + FlowRecord currentRecord = session.getCurrentRecord(); + if (currentRecord == null || currentRecord.getProcessId() == null) { + return false; + } + List assigned = session.getRepositoryHolder() + .findAssignedOperators(currentRecord.getProcessId(), nodeId); + return assigned != null && !assigned.isEmpty(); + } + + /** + * 校验并保存操作人分配(仅人员 id,默认身份)。 * * @param baseSession 基准会话,用于派生目标节点会话以执行范围脚本 * @param processId 流程实例ID @@ -38,28 +73,57 @@ public static void validateAndSave(FlowSession baseSession, String processId, if (operatorSelectMap == null || operatorSelectMap.isEmpty()) { return; } + Map> selections = new LinkedHashMap<>(); + operatorSelectMap.forEach((nodeId, operatorIds) -> + selections.put(nodeId, operatorIds.stream().map(OperatorKey::ofDefault).toList())); + validateAndSaveOperators(baseSession, processId, selections); + } + + /** + * 校验并保存操作人分配,携带身份(issue #288 衍生 / #292)。 + *

    + * 数量校验:节点配置了最大可选人数(maxOperatorCount >= 0)时,所选人数超过上限则抛出异常。 + * 当目标节点配置了可选人员范围(范围非空)时,校验所选人员是否全部落在范围内,越界则抛出异常; + * 范围为空(未配置脚本或脚本执行结果为空)表示不限范围,跳过校验。 + *

    + * 同一人员的两个身份是两项参与人,不做合并;完全相同的 {@code (人员id, 身份)} 会被去重。 + * + * @param baseSession 基准会话,用于派生目标节点会话以执行范围脚本 + * @param processId 流程实例ID + * @param operatorSelectOperators 节点ID -> 选定的操作人列表(含身份) + */ + public static void validateAndSaveOperators(FlowSession baseSession, String processId, + Map> operatorSelectOperators) { + if (operatorSelectOperators == null || operatorSelectOperators.isEmpty()) { + return; + } Workflow workflow = baseSession.getWorkflow(); IRepositoryHolder repositoryHolder = baseSession.getRepositoryHolder(); - operatorSelectMap.forEach((nodeId, operatorIds) -> { + operatorSelectOperators.forEach((nodeId, operators) -> { + if (operators == null || operators.isEmpty()) { + return; + } + List selections = operators.stream().distinct().toList(); IFlowNode node = workflow.getFlowNode(nodeId); // 校验可选人数上限(-1 表示不限制) int maxOperatorCount = node.strategyManager().getMaxOperatorCount(); - if (maxOperatorCount >= 0 && operatorIds.size() > maxOperatorCount) { + if (maxOperatorCount >= 0 && selections.size() > maxOperatorCount) { throw FlowValidationException.operatorCountExceeded(nodeId, maxOperatorCount); } List range = node.strategyManager() .loadOperatorRange(baseSession.updateSession(node)); if (range != null && !range.isEmpty()) { + // 范围校验按人员 id 判定:范围表达的是「可选哪些人」,不区分身份 Set allowedIds = range.stream() .map(IFlowOperator::getUserId) .collect(Collectors.toSet()); - for (Long operatorId : operatorIds) { - if (!allowedIds.contains(operatorId)) { + for (OperatorKey operator : selections) { + if (!allowedIds.contains(operator.operatorId())) { throw FlowValidationException.operatorOutOfRange(nodeId); } } } - repositoryHolder.saveOperatorAssignment(processId, nodeId, operatorIds); + repositoryHolder.saveOperatorAssignments(processId, nodeId, selections); }); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/session/FlowAdvice.java b/flow-engine-framework/src/main/java/com/codingapi/flow/session/FlowAdvice.java index 5d1542ca..deb022e1 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/session/FlowAdvice.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/session/FlowAdvice.java @@ -3,6 +3,7 @@ import com.codingapi.flow.action.IFlowAction; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import lombok.Data; import lombok.NoArgsConstructor; @@ -48,9 +49,16 @@ public class FlowAdvice { /** * 操作人手动选择映射(节点ID -> 操作人ID列表) * 用于 INITIATOR_SELECT / APPROVER_SELECT 模式 + *

    存量字段,仅表达人员 id(默认身份)。 */ private Map> operatorSelectMap; + /** + * 操作人手动选择映射,携带身份(节点ID -> 选定的操作人列表,issue #288 衍生 / #292) + *

    每项为 {@code (人员id, 身份)},优先于 {@link #operatorSelectMap}。 + */ + private Map> operatorSelectOperators; + public FlowAdvice(String advice) { this.advice = advice; 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 da776037..dd86e508 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 @@ -4,6 +4,7 @@ import com.codingapi.flow.domain.UrgeInterval; import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.repository.FlowReissueRepository; import com.codingapi.flow.repository.SubProcessRepository; @@ -110,6 +111,20 @@ default IFlowOperator getOperatorById(long id, String identity) { return getOperatorById(id); } + /** + * 按统一身份批量获取流程操作人(issue #288 衍生 / #293)。 + * + *

    用于一批人员以同一身份参与流程的场景,避免逐条回查。 + * 默认实现忽略身份、退化为 {@link #findOperatorByIds(List)},下游存量实现无需改动。 + * + * @param ids 人员 id 列表 + * @param identity 身份标识,{@code null} 与空串等价(默认身份) + * @return 流程操作人列表 + */ + default List findOperatorByIds(List ids, String identity) { + return findOperatorByIds(ids); + } + /** * 保存延迟任务 @@ -230,4 +245,34 @@ default IFlowOperator getOperatorById(long id, String identity) { * @return 操作人 ID 列表(未分配时返回空列表) */ List findAssignedOperatorIds(String processId, String nodeId); + + /** + * 保存节点操作人手动分配信息,携带身份(issue #288 衍生 / #292)。 + * + *

    {@link OperatorKey} 与 {@code List} 泛型擦除后签名相同, + * 无法重载,因此单独命名。默认实现忽略身份、退化为 + * {@link #saveOperatorAssignment(String, String, List)},下游存量实现无需改动即可编译。 + * + * @param processId 流程实例唯一标识 + * @param nodeId 节点 ID + * @param operators 操作人列表(含身份) + */ + default void saveOperatorAssignments(String processId, String nodeId, List operators) { + this.saveOperatorAssignment(processId, nodeId, operators.stream() + .map(OperatorKey::operatorId).toList()); + } + + /** + * 查询节点已分配的操作人列表,携带身份(issue #288 衍生 / #292)。 + * + *

    默认实现退化为 {@link #findAssignedOperatorIds(String, String)},返回的操作人身份均为默认身份。 + * + * @param processId 流程实例唯一标识 + * @param nodeId 节点 ID + * @return 操作人列表(未分配时返回空列表) + */ + default List findAssignedOperators(String processId, String nodeId) { + return this.findAssignedOperatorIds(processId, nodeId).stream() + .map(OperatorKey::ofDefault).toList(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java b/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java index d419193a..d0618a07 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java @@ -3,11 +3,16 @@ import com.codingapi.flow.common.IMapConvertor; import com.codingapi.flow.manager.OperatorManager; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.script.node.OperatorLoadScript; import com.codingapi.flow.session.FlowSession; +import com.codingapi.flow.session.IRepositoryHolder; import lombok.Getter; import lombok.NoArgsConstructor; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -51,18 +56,17 @@ public void copy(INodeStrategy target) { public OperatorManager loadOperators(FlowSession flowSession) { if (selectType == OperatorSelectType.INITIATOR_SELECT || selectType == OperatorSelectType.APPROVER_SELECT) { - // 从持久化存储中读取预先分配的操作人 ID 列表 + // 从持久化存储中读取预先分配的操作人(含身份,issue #288 衍生 / #292) String processId = flowSession.getCurrentRecord() != null ? flowSession.getCurrentRecord().getProcessId() : null; String nodeId = flowSession.getCurrentNode().getId(); if (processId != null) { - List operatorIds = flowSession.getRepositoryHolder() - .findAssignedOperatorIds(processId, nodeId); - if (!operatorIds.isEmpty()) { - List operators = flowSession.getRepositoryHolder() - .findOperatorByIds(operatorIds); - return new OperatorManager(operators); + List assignedOperators = flowSession.getRepositoryHolder() + .findAssignedOperators(processId, nodeId); + if (!assignedOperators.isEmpty()) { + return new OperatorManager(this.loadAssignedOperators( + flowSession.getRepositoryHolder(), assignedOperators)); } } // 未找到分配数据时返回空列表(触发 errorTrigger 逻辑) @@ -72,6 +76,40 @@ public OperatorManager loadOperators(FlowSession flowSession) { return new OperatorManager(operatorLoadScript.execute(flowSession)); } + /** + * 按 {@code (人员id, 身份)} 加载已分配的操作人(issue #288 衍生 / #292)。 + * + *

    按身份分组批量回查,避免逐个 {@code getOperatorById} 造成 N+1; + * 返回顺序与分配顺序一致,保证多人审批的执行顺序稳定。 + */ + private List loadAssignedOperators(IRepositoryHolder repositoryHolder, + List assignedOperators) { + Map> operatorIdsByIdentity = new LinkedHashMap<>(); + for (OperatorKey operator : assignedOperators) { + operatorIdsByIdentity + .computeIfAbsent(operator.identity(), key -> new ArrayList<>()) + .add(operator.operatorId()); + } + Map operatorMap = new HashMap<>(); + operatorIdsByIdentity.forEach((identity, operatorIds) -> { + List operators = repositoryHolder.findOperatorByIds(operatorIds, identity); + if (operators == null) { + return; + } + for (IFlowOperator operator : operators) { + operatorMap.put(OperatorKey.of(operator.getUserId(), identity).key(), operator); + } + }); + List result = new ArrayList<>(assignedOperators.size()); + for (OperatorKey operator : assignedOperators) { + IFlowOperator flowOperator = operatorMap.get(operator.key()); + if (flowOperator != null) { + result.add(flowOperator); + } + } + return result; + } + /** * 计算该节点的可选人员范围(用于发起人/审批人设定模式)。 * 复用 operatorLoadScript 执行脚本得到候选人;脚本为空或执行结果为空均视为不限范围(可选任意人)。 diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java new file mode 100644 index 00000000..4d8da08a --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java @@ -0,0 +1,107 @@ +package com.codingapi.flow.cache; + +import com.codingapi.flow.gateway.FlowOperatorGateway; +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +/** + * 按身份批量取人的缓存与网关契约测试(issue #288 衍生 / #293、#295)。 + * + *

    批量加载必须按 {@code (id, identity)} 隔离缓存,否则同一批人以不同身份参与时 + * 会命中同一个对象,身份串味;同时验证未覆盖新方法的存量网关能安全退化为按 id 批量查询。 + */ +class FlowOperatorBulkIdentityTest { + + private FlowOperatorLocalThreadCache cache; + + @BeforeEach + void setUp() { + cache = FlowOperatorLocalThreadCache.getInstance(); + cache.clear(); + } + + /** + * 测试目标:两个身份分别回源、分别命中缓存,互不覆盖。 + * 前置条件:缓存为空,人员 1 有两个身份副本。 + * 执行步骤:以两个身份各批量加载一次,再重复加载第一个身份。 + * 期望断言:返回各自的操作者;重复加载命中缓存不回源,回源次数为 2。 + */ + @Test + void should_isolate_bulk_load_by_identity() { + User department1 = User.withIdentity(1, "user1", "department1"); + User department2 = User.withIdentity(1, "user1", "department2"); + AtomicInteger loads = new AtomicInteger(); + + List first = cache.find(List.of(1L), "department1", ids -> { + loads.incrementAndGet(); + return List.of(department1); + }); + List second = cache.find(List.of(1L), "department2", ids -> { + loads.incrementAndGet(); + return List.of(department2); + }); + List again = cache.find(List.of(1L), "department1", ids -> { + loads.incrementAndGet(); + return List.of(); + }); + + assertEquals(1, first.size()); + assertEquals(1, second.size()); + assertSame(department1, first.get(0)); + assertSame(department2, second.get(0)); + assertSame(department1, again.get(0)); + assertEquals(2, loads.get(), "同一身份重复加载应命中缓存"); + } + + /** + * 测试目标:默认身份的批量加载与历史单参 {@code find} 等价。 + * 前置条件:缓存为空。 + * 执行步骤:用三参重载、identity 传空串加载。 + * 期望断言:结果与默认身份键下的缓存一致。 + */ + @Test + void should_share_cache_with_legacy_bulk_load_for_default_identity() { + User user = new User(3, "user3"); + + List loaded = cache.find(List.of(3L), OperatorIdentity.DEFAULT, + ids -> List.of(user)); + + assertEquals(1, loaded.size()); + assertSame(user, cache.get(3, () -> null)); + } + + /** + * 测试目标:下游未覆盖身份重载时安全退化为按 id 批量查询(向后兼容硬约束)。 + * 前置条件:网关只实现两个抽象方法。 + * 执行步骤:调用带身份的默认方法。 + * 期望断言:返回按 id 查询的结果,编译与行为均不破坏。 + */ + @Test + void should_degrade_to_plain_find_by_ids_when_gateway_not_overridden() { + FlowOperatorGateway legacyGateway = new FlowOperatorGateway() { + @Override + public IFlowOperator get(long id) { + return new User(id, "user" + id); + } + + @Override + public List findByIds(List ids) { + return ids.stream().map(id -> (IFlowOperator) new User(id, "user" + id)).toList(); + } + }; + + List operators = legacyGateway.findByIds(List.of(1L, 2L), "department1"); + + assertEquals(2, operators.size()); + assertEquals("", OperatorIdentity.of(operators.get(0))); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java b/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java index 3ca0b1b9..a7a7cbc4 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java @@ -39,6 +39,21 @@ public List findByIds(List ids) { .toList(); } + /** + * 按统一身份批量返回用户副本,与 {@link #get(long, String)} 口径一致(issue #288 衍生 / #293)。 + */ + @Override + public List findByIds(List ids, String identity) { + List operators = this.findByIds(ids); + if (OperatorIdentity.isDefault(identity)) { + return operators; + } + return operators.stream() + .map(operator -> operator instanceof User user + ? (IFlowOperator) user.asIdentity(identity) : operator) + .toList(); + } + public void save(User user) { cache.put(user.getUserId(), user); diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/mock/service/FlowRecordQueryMockIdentityTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/mock/service/FlowRecordQueryMockIdentityTest.java new file mode 100644 index 00000000..91f0062b --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/mock/service/FlowRecordQueryMockIdentityTest.java @@ -0,0 +1,109 @@ +package com.codingapi.flow.mock.service; + +import com.codingapi.flow.gateway.impl.UserGateway; +import com.codingapi.flow.mock.MockRepositoryHolder; +import com.codingapi.flow.mock.repository.FlowTodoRecordRepositoryMockImpl; +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.pojo.response.FlowRecordContent; +import com.codingapi.flow.record.FlowTodoRecord; +import com.codingapi.flow.repository.WorkflowRepositoryImpl; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Mock 查询链路的身份隔离测试(issue #288 衍生 / #291、#295)。 + * + *

    带 {@code mockKey} 的 REST 调用走 Mock 仓储,若三个查询重载退化成按 id 查询, + * 同一人员的多个身份数据会串在一起,与真实 JPA 链路口径不一致。 + */ +class FlowRecordQueryMockIdentityTest { + + private static final long OPERATOR_ID = 5; + private static final PageRequest PAGE = PageRequest.of(0, 10); + + private FlowRecordQueryMockService queryService; + private FlowTodoRecordRepositoryMockImpl todoRepository; + + @BeforeEach + void setUp() { + MockRepositoryHolder holder = new MockRepositoryHolder(new UserGateway(), new WorkflowRepositoryImpl()); + todoRepository = (FlowTodoRecordRepositoryMockImpl) holder.getFlowTodoRecordRepository(); + queryService = new FlowRecordQueryMockService(holder); + } + + private static FlowTodoRecord todo(long id, long operatorId, String identity) { + return new FlowTodoRecord( + id, "process-" + id, 1L, "测试流程", "test-code", "node-1", "APPROVAL", "审批节点", "标题", + 0L, operatorId, "审批人", 0L, "", 0L, 0L, "", "todo-key-" + id, + 0, false, id, 0L, + identity, "", ""); + } + + /** + * 测试目标:按身份查询只返回该身份的待办。 + * 前置条件:同一人员存在默认 / department1 / department2 三条待办,另有他人一条。 + * 执行步骤:分别以 department1、department2 查询。 + * 期望断言:各返回 1 条,且返回内容的身份正确。 + */ + @Test + void should_filter_todo_by_identity() { + todoRepository.save(todo(1, OPERATOR_ID, "")); + todoRepository.save(todo(2, OPERATOR_ID, "department1")); + todoRepository.save(todo(3, OPERATOR_ID, "department2")); + todoRepository.save(todo(4, 6, "department1")); + + Page d1 = queryService.findTodoRecordPage(OPERATOR_ID, "department1", PAGE); + Page d2 = queryService.findTodoRecordPage(OPERATOR_ID, "department2", PAGE); + + assertEquals(1, d1.getTotalElements()); + assertEquals(1, d2.getTotalElements()); + assertEquals("department1", d1.getContent().get(0).getCurrentOperatorIdentity()); + assertEquals("department2", d2.getContent().get(0).getCurrentOperatorIdentity()); + } + + /** + * 测试目标:历史记录身份为 null 时按默认身份命中(与 JPA coalesce 口径一致)。 + * 前置条件:一条默认身份待办、一条身份为 null 的历史待办、一条非空身份待办。 + * 执行步骤:以 null/空串查询默认身份。 + * 期望断言:命中 2 条,非空身份那条不混入。 + */ + @Test + void should_treat_null_identity_as_default_for_legacy_records() { + todoRepository.save(todo(1, OPERATOR_ID, "")); + todoRepository.save(todo(2, OPERATOR_ID, null)); + todoRepository.save(todo(3, OPERATOR_ID, "department1")); + + Page byNull = queryService.findTodoRecordPage(OPERATOR_ID, null, PAGE); + Page byEmpty = queryService.findTodoRecordPage(OPERATOR_ID, OperatorIdentity.DEFAULT, PAGE); + + assertEquals(2, byNull.getTotalElements()); + assertEquals(2, byEmpty.getTotalElements()); + } + + /** + * 测试目标:存量单参查询保持不过滤身份的行为。 + * 前置条件:同一人员三条不同身份待办、他人一条。 + * 执行步骤:调用历史签名 findTodoRecordPage(userId, request)。 + * 期望断言:返回该人员全部 3 条,不含他人记录。 + */ + @Test + void should_keep_legacy_query_unfiltered() { + todoRepository.save(todo(1, OPERATOR_ID, "")); + todoRepository.save(todo(2, OPERATOR_ID, "department1")); + todoRepository.save(todo(3, OPERATOR_ID, "department2")); + todoRepository.save(todo(4, 6, "department1")); + + Page legacy = queryService.findTodoRecordPage(OPERATOR_ID, PAGE); + + assertEquals(3, legacy.getTotalElements()); + List identities = legacy.getContent().stream() + .map(FlowRecordContent::getCurrentOperatorIdentity).toList(); + assertEquals(3, identities.size()); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityGuardTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityGuardTest.java new file mode 100644 index 00000000..9f6399db --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityGuardTest.java @@ -0,0 +1,59 @@ +package com.codingapi.flow.operator; + +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 身份透传告警测试(issue #288 衍生 / #294)。 + * + *

    下游不覆盖带身份的取人方法时,身份会被静默丢弃,前端按身份查待办会得到空列表。 + * 这里验证告警条件与去重:只在「请求身份非默认、回查结果身份为默认」时告警,且同一参与人只告警一次。 + */ +class OperatorIdentityGuardTest { + + @BeforeEach + void setUp() { + OperatorIdentityGuard.resetWarnedCache(); + } + + @Test + void should_warn_when_requested_identity_is_lost() { + User resolved = new User(1, "user1"); + + assertTrue(OperatorIdentityGuard.check(1, "department1", resolved)); + } + + @Test + void should_warn_only_once_for_same_operator_and_identity() { + User resolved = new User(1, "user1"); + + assertTrue(OperatorIdentityGuard.check(1, "department1", resolved)); + assertFalse(OperatorIdentityGuard.check(1, "department1", resolved), "同一参与人不应重复告警"); + assertTrue(OperatorIdentityGuard.check(1, "department2", resolved), "不同身份应各自告警一次"); + } + + @Test + void should_not_warn_for_default_identity() { + User resolved = new User(1, "user1"); + + assertFalse(OperatorIdentityGuard.check(1, OperatorIdentity.DEFAULT, resolved)); + assertFalse(OperatorIdentityGuard.check(1, null, resolved)); + } + + @Test + void should_not_warn_when_gateway_honors_identity() { + User resolved = User.withIdentity(1, "user1", "department1"); + + assertFalse(OperatorIdentityGuard.check(1, "department1", resolved)); + } + + @Test + void should_not_warn_when_operator_not_found() { + // 查不到人属于另一种错误(由上层按需处理),不应在这里刷身份告警 + assertFalse(OperatorIdentityGuard.check(1, "department1", null)); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityValidationTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityValidationTest.java new file mode 100644 index 00000000..66fa3701 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityValidationTest.java @@ -0,0 +1,62 @@ +package com.codingapi.flow.operator; + +import com.codingapi.flow.exception.FlowValidationException; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 身份标识校验测试(issue #288 衍生 / #294)。 + * + *

    校验的目标是让「内存里的身份」与「数据库里的身份」语义一致: + * 长度上限与 DDL 列宽对齐,禁止与待办合并键后缀冲突的字符与控制字符。 + */ +class OperatorIdentityValidationTest { + + @Test + void should_normalize_null_to_default_and_keep_empty() { + assertEquals(OperatorIdentity.DEFAULT, OperatorIdentity.validate(null)); + assertEquals("", OperatorIdentity.validate("")); + } + + @Test + void should_accept_identity_at_max_length() { + String identity = "a".repeat(OperatorIdentity.MAX_LENGTH); + + assertEquals(identity, OperatorIdentity.validate(identity)); + } + + @Test + void should_reject_identity_longer_than_max_length() { + String identity = "a".repeat(OperatorIdentity.MAX_LENGTH + 1); + + FlowValidationException exception = assertThrows(FlowValidationException.class, + () -> OperatorIdentity.validate(identity)); + assertTrue(exception.getMessage().contains("exceeds the max length"), exception.getMessage()); + } + + @Test + void should_reject_identity_containing_merge_key_separator() { + FlowValidationException exception = assertThrows(FlowValidationException.class, + () -> OperatorIdentity.validate("department1#manager")); + + assertTrue(exception.getMessage().contains("illegal character"), exception.getMessage()); + } + + @Test + void should_reject_identity_containing_control_character() { + FlowValidationException exception = assertThrows(FlowValidationException.class, + () -> OperatorIdentity.validate("department\u00011")); + + assertTrue(exception.getMessage().contains("illegal character"), exception.getMessage()); + } + + @Test + void should_keep_normalize_lenient_for_existing_data() { + // 存量数据可能含非法字符,读取路径必须保持宽松,不能因为校验把历史流程读崩 + assertSame("department1#manager", OperatorIdentity.normalize("department1#manager")); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/pojo/response/FlowCurrentNodeOperatorsIdentityTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/pojo/response/FlowCurrentNodeOperatorsIdentityTest.java new file mode 100644 index 00000000..251a7d71 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/pojo/response/FlowCurrentNodeOperatorsIdentityTest.java @@ -0,0 +1,190 @@ +package com.codingapi.flow.pojo.response; + +import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.action.actions.CustomAction; +import com.codingapi.flow.builder.ActionBuilder; +import com.codingapi.flow.builder.NodeStrategyBuilder; +import com.codingapi.flow.context.GatewayContext; +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.node.nodes.ApprovalNode; +import com.codingapi.flow.node.nodes.EndNode; +import com.codingapi.flow.node.nodes.StartNode; +import com.codingapi.flow.operator.OperatorKey; +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.record.FlowRecord; +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.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 当前节点待审批人的身份维度测试(issue #288 衍生 / #290、#292)。 + * + *

    同一个人员以两个身份被指定到同一节点时: + *

      + *
    • 分配关系必须保存两项 {@code (人员id, 身份)};
    • + *
    • 节点必须生成两条待办记录,身份各自独立;
    • + *
    • 详情页的当前节点待审批人列表必须同时出现两个身份(只按人员 id 去重会吞掉一个)。
    • + *
    + */ +class FlowCurrentNodeOperatorsIdentityTest { + + private static final long CREATOR_ID = 1; + private static final long APPROVER_ID = 2; + private static final String IDENTITY_ONE = "department1"; + private static final String IDENTITY_TWO = "department2"; + + private MyFlowServiceFactory factory; + private Workflow workflow; + private ApprovalNode approvalNode; + + @BeforeEach + void setUp() { + User creator = new User(CREATOR_ID, "creator"); + User approver = new User(APPROVER_ID, "user1"); + factory = new MyFlowServiceFactory(); + factory.userGateway.save(creator); + factory.userGateway.save(approver); + GatewayContext.getInstance().setFlowOperatorGateway(factory.userGateway); + + String workCode = "identity-current-operators"; + FlowForm form = FlowFormBuilder.builder() + .name("多身份流程") + .code(workCode) + .addField("标题", "title", DataType.STRING) + .build(); + + StartNode startNode = StartNode.builder() + .actions(ActionBuilder.builder() + .addAction(CustomAction.defaultAction()) + .build()) + .build(); + + approvalNode = ApprovalNode.builder() + .name("经理审批") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(OperatorLoadStrategy.initiatorSelectStrategy()) + // 并签:两个身份同时在岗,避免默认顺序审批把第二条记录隐藏 + .addStrategy(new MultiOperatorAuditStrategy( + MultiOperatorAuditStrategy.Type.MERGE, 1.0f)) + .build()) + .build(); + + workflow = WorkflowBuilder.builder() + .title("多身份流程") + .code(workCode) + .createdOperator(creator) + .form(form) + .addNode(startNode) + .addNode(approvalNode) + .addNode(EndNode.builder().build()) + .build(); + factory.workflowService.saveWorkflow(workflow); + } + + private Map formData() { + return Map.of("title", "同一人两个身份"); + } + + /** + * 发起流程,并在开始节点把审批节点的操作人指定为「同一人的两个身份」。 + */ + private String createWithTwoIdentities() { + List startActions = workflow.getStartNode().actionManager().getActions(); + + FlowCreateRequest createRequest = new FlowCreateRequest(); + createRequest.setWorkCode(workflow.getCode()); + createRequest.setFormData(formData()); + createRequest.setActionId(startActions.get(0).id()); + createRequest.setOperatorId(CREATOR_ID); + createRequest.setOperatorSelectOperators(Map.of(approvalNode.getId(), List.of( + OperatorKey.of(APPROVER_ID, IDENTITY_ONE), + OperatorKey.of(APPROVER_ID, IDENTITY_TWO)))); + factory.flowService.create(createRequest); + + List creatorRecords = factory.flowRecordRepository.findTodoByOperator(CREATOR_ID); + assertEquals(1, creatorRecords.size(), "发起后应有一条发起人待办"); + + FlowActionRequest actionRequest = new FlowActionRequest(); + actionRequest.setFormData(formData()); + actionRequest.setRecordId(creatorRecords.get(0).getId()); + actionRequest.setAdvice(new FlowAdviceBody(startActions.get(0).id(), "提交", CREATOR_ID)); + factory.flowService.action(actionRequest); + + return creatorRecords.get(0).getProcessId(); + } + + @Test + void should_persist_two_identities_of_same_operator() { + String processId = createWithTwoIdentities(); + + List assigned = factory.flowOperatorAssignmentRepository + .findOperators(processId, approvalNode.getId()); + + assertEquals(2, assigned.size(), "同一人的两个身份应各自保存一项"); + assertTrue(assigned.contains(OperatorKey.of(APPROVER_ID, IDENTITY_ONE))); + assertTrue(assigned.contains(OperatorKey.of(APPROVER_ID, IDENTITY_TWO))); + } + + @Test + void should_keep_legacy_id_view_for_assignment() { + String processId = createWithTwoIdentities(); + + List legacyIds = factory.flowOperatorAssignmentRepository + .findOperatorIds(processId, approvalNode.getId()); + + assertEquals(List.of(APPROVER_ID, APPROVER_ID), legacyIds, "存量按 id 读取的口径不变"); + } + + @Test + void should_create_one_record_per_identity() { + String processId = createWithTwoIdentities(); + + List records = factory.flowRecordRepository.findProcessRecords(processId).stream() + .filter(record -> approvalNode.getId().equals(record.getNodeId())) + .toList(); + + assertEquals(2, records.size(), "每个身份都应生成一条审批记录"); + assertEquals(Set.of(IDENTITY_ONE, IDENTITY_TWO), + records.stream().map(FlowRecord::getCurrentOperatorIdentity).collect(java.util.stream.Collectors.toSet())); + } + + /** + * 详情页当前节点待审批人:同一人的两个身份必须同时出现,且当前操作人只排除「同人同身份」。 + */ + @Test + void should_list_both_identities_in_current_node_operators() { + String processId = createWithTwoIdentities(); + + List nodeRecords = factory.flowRecordRepository.findProcessRecords(processId).stream() + .filter(record -> approvalNode.getId().equals(record.getNodeId())) + .toList(); + assertEquals(2, nodeRecords.size()); + + FlowRecord currentRecord = nodeRecords.stream() + .filter(record -> IDENTITY_ONE.equals(record.getCurrentOperatorIdentity())) + .findFirst() + .orElseThrow(); + + List operators = FlowContent.resolveCurrentNodeOperators(currentRecord, nodeRecords); + + assertEquals(1, operators.size(), "同一人的另一个身份仍应出现在待审批人列表中"); + assertEquals(IDENTITY_TWO, operators.get(0).getIdentity()); + assertEquals(APPROVER_ID, operators.get(0).getId()); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/repository/FlowOperatorAssignmentRepositoryImpl.java b/flow-engine-framework/src/test/java/com/codingapi/flow/repository/FlowOperatorAssignmentRepositoryImpl.java index 4a94d1e6..391d1dce 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/repository/FlowOperatorAssignmentRepositoryImpl.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/repository/FlowOperatorAssignmentRepositoryImpl.java @@ -1,5 +1,7 @@ package com.codingapi.flow.repository; +import com.codingapi.flow.operator.OperatorKey; + import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -7,7 +9,7 @@ public class FlowOperatorAssignmentRepositoryImpl implements FlowOperatorAssignmentRepository { - private final Map> cache = new HashMap<>(); + private final Map> cache = new HashMap<>(); private String key(String processId, String nodeId) { return processId + ":" + nodeId; @@ -15,11 +17,21 @@ private String key(String processId, String nodeId) { @Override public void save(String processId, String nodeId, List operatorIds) { - cache.put(key(processId, nodeId), operatorIds); + this.saveOperators(processId, nodeId, operatorIds.stream().map(OperatorKey::ofDefault).toList()); } @Override public List findOperatorIds(String processId, String nodeId) { + return this.findOperators(processId, nodeId).stream().map(OperatorKey::operatorId).toList(); + } + + @Override + public void saveOperators(String processId, String nodeId, List operators) { + cache.put(key(processId, nodeId), operators); + } + + @Override + public List findOperators(String processId, String nodeId) { return cache.getOrDefault(key(processId, nodeId), Collections.emptyList()); } } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/script/request/GroovyScriptBindIdentityTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/script/request/GroovyScriptBindIdentityTest.java new file mode 100644 index 00000000..ead4b3c4 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/script/request/GroovyScriptBindIdentityTest.java @@ -0,0 +1,86 @@ +package com.codingapi.flow.script.request; + +import com.codingapi.flow.context.GatewayContext; +import com.codingapi.flow.factory.MyFlowServiceFactory; +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.cache.FlowOperatorLocalThreadCache; +import com.codingapi.flow.script.runtime.FlowScriptContext; +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; + +/** + * 脚本绑定对象 {@code $bind.getOperatorByIdentity} 测试(issue #288 衍生 / #295)。 + * + *

    P3 提交新增的脚本能力此前零用例:验证按身份取到的是带身份的操作者, + * 同一人员的两个身份互不串味,且默认身份与历史 {@code getOperatorById} 完全等价。 + */ +class GroovyScriptBindIdentityTest { + + private MyFlowServiceFactory factory; + private GroovyScriptBind bind; + + @BeforeEach + void setUp() { + factory = new MyFlowServiceFactory(); + factory.userGateway.save(new User(2, "user2")); + GatewayContext.getInstance().setFlowOperatorGateway(factory.userGateway); + FlowOperatorLocalThreadCache.getInstance().clear(); + bind = new GroovyScriptBind(FlowScriptContext.getInstance()); + } + + /** + * 测试目标:脚本按身份取人返回带身份的操作者。 + * 前置条件:人员 2 已注册。 + * 执行步骤:调用 $bind.getOperatorByIdentity(2, 'department1')。 + * 期望断言:返回对象的人员 id 为 2、身份为 department1。 + */ + @Test + void should_load_operator_with_requested_identity() { + IFlowOperator operator = bind.getOperatorByIdentity(2, "department1"); + + assertNotNull(operator); + assertEquals(2, operator.getUserId()); + assertEquals("department1", OperatorIdentity.of(operator)); + } + + /** + * 测试目标:默认身份与历史单参方法等价(向后兼容)。 + * 前置条件:人员 2 已注册。 + * 执行步骤:分别用 getOperatorById 与 getOperatorByIdentity(2, "") 取人。 + * 期望断言:两者身份均为默认身份空串。 + */ + @Test + void should_keep_default_identity_equivalent_to_legacy_method() { + IFlowOperator legacy = bind.getOperatorById(2); + IFlowOperator byIdentity = bind.getOperatorByIdentity(2, OperatorIdentity.DEFAULT); + + assertNotNull(legacy); + assertNotNull(byIdentity); + assertEquals(OperatorIdentity.of(legacy), OperatorIdentity.of(byIdentity)); + assertEquals("", OperatorIdentity.of(byIdentity)); + } + + /** + * 测试目标:同一人员的两个身份是不同的参与人。 + * 前置条件:人员 2 已注册。 + * 执行步骤:连续以 department1 / department2 取人。 + * 期望断言:两个对象不同,身份各自独立(缓存按 (id, identity) 隔离)。 + */ + @Test + void should_isolate_two_identities_of_same_operator() { + IFlowOperator department1 = bind.getOperatorByIdentity(2, "department1"); + IFlowOperator department2 = bind.getOperatorByIdentity(2, "department2"); + + assertNotSame(department1, department2); + assertEquals("department1", OperatorIdentity.of(department1)); + assertEquals("department2", OperatorIdentity.of(department2)); + // 再次取 department1 仍应是同一个带身份的对象,不能被 department2 覆盖 + assertEquals("department1", OperatorIdentity.of(bind.getOperatorByIdentity(2, "department1"))); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowOperatorIdentityRecordTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowOperatorIdentityRecordTest.java index 34c6174c..fe964b30 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowOperatorIdentityRecordTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowOperatorIdentityRecordTest.java @@ -14,6 +14,7 @@ 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.operator.OperatorIdentity; import com.codingapi.flow.pojo.body.FlowAdviceBody; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.request.FlowCreateRequest; @@ -191,4 +192,27 @@ void should_store_approver_identity_after_pass() { assertEquals(1, bossTodoRecords.size()); assertEquals("department2", bossTodoRecords.get(0).getCurrentOperatorIdentity()); } + + /** + * 场景:抄送记录被复用(clearNotify)时,转交身份必须与转交人 id 一起清零, + * 否则旧身份会残留在记录上,被后续流转带出错误的参与人身份(issue #288 衍生 / #294)。 + */ + @Test + void should_clear_forward_identity_when_notify_is_reset() { + User creator = new User(1, "user1"); + User boss = new User(2, "boss"); + MyFlowServiceFactory factory = newFactory(creator, boss); + Workflow workflow = buildLeaveWorkflow(factory, creator); + long recordId = createAtStartNode(factory, workflow, creator); + + FlowRecord record = factory.flowRecordRepository.get(recordId); + assertNotNull(record); + record.setForwardOperatorId(9); + record.setForwardOperatorIdentity("department9"); + + record.clearNotify(); + + assertEquals(0, record.getForwardOperatorId()); + assertEquals(OperatorIdentity.DEFAULT, record.getForwardOperatorIdentity()); + } } diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java index 07448756..3f956f12 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java @@ -127,11 +127,12 @@ public static FlowRecordEntity convert(FlowRecord record) { entity.setParallelId(record.getParallelId()); entity.setParallelBranchNodeId(record.getParallelBranchNodeId()); entity.setParallelBranchTotal(record.getParallelBranchTotal()); - entity.setCreateOperatorIdentity(OperatorIdentity.normalize(record.getCreateOperatorIdentity())); - entity.setSubmitOperatorIdentity(OperatorIdentity.normalize(record.getSubmitOperatorIdentity())); - entity.setCurrentOperatorIdentity(OperatorIdentity.normalize(record.getCurrentOperatorIdentity())); - entity.setForwardOperatorIdentity(OperatorIdentity.normalize(record.getForwardOperatorIdentity())); - entity.setInterferedOperatorIdentity(OperatorIdentity.normalize(record.getInterferedOperatorIdentity())); + // 写入前统一校验:长度与 DDL 列宽一致、禁止合并键分隔符与控制字符(issue #288 衍生 / #294) + entity.setCreateOperatorIdentity(OperatorIdentity.validate(record.getCreateOperatorIdentity())); + entity.setSubmitOperatorIdentity(OperatorIdentity.validate(record.getSubmitOperatorIdentity())); + entity.setCurrentOperatorIdentity(OperatorIdentity.validate(record.getCurrentOperatorIdentity())); + entity.setForwardOperatorIdentity(OperatorIdentity.validate(record.getForwardOperatorIdentity())); + entity.setInterferedOperatorIdentity(OperatorIdentity.validate(record.getInterferedOperatorIdentity())); return entity; } diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowTodoRecordConvertor.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowTodoRecordConvertor.java index 8339d93f..f30b65a5 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowTodoRecordConvertor.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowTodoRecordConvertor.java @@ -71,9 +71,10 @@ public static FlowTodoRecordEntity convert(FlowTodoRecord record){ entity.setMergeable(record.isMergeable()); entity.setRecordId(record.getRecordId()); entity.setTimeoutTime(record.getTimeoutTime()); - entity.setCurrentOperatorIdentity(OperatorIdentity.normalize(record.getCurrentOperatorIdentity())); - entity.setSubmitOperatorIdentity(OperatorIdentity.normalize(record.getSubmitOperatorIdentity())); - entity.setCreateOperatorIdentity(OperatorIdentity.normalize(record.getCreateOperatorIdentity())); + // 写入前统一校验:长度与 DDL 列宽一致、禁止合并键分隔符与控制字符(issue #288 衍生 / #294) + entity.setCurrentOperatorIdentity(OperatorIdentity.validate(record.getCurrentOperatorIdentity())); + entity.setSubmitOperatorIdentity(OperatorIdentity.validate(record.getSubmitOperatorIdentity())); + entity.setCreateOperatorIdentity(OperatorIdentity.validate(record.getCreateOperatorIdentity())); return entity; } } diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowOperatorAssignmentEntity.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowOperatorAssignmentEntity.java index 592b1946..5b7bcd75 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowOperatorAssignmentEntity.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowOperatorAssignmentEntity.java @@ -29,7 +29,11 @@ public class FlowOperatorAssignmentEntity { private String nodeId; /** - * 操作人 ID 列表(JSON 格式,如 [1,2,3]) + * 操作人分配列表(JSON 格式,issue #288 衍生 / #292)。 + * + *

    历史格式:{@code [1,2,3]},全部按默认身份处理; + * 含身份格式:{@code [{"operatorId":2,"identity":"department1"}]}。 + * 两种格式由仓储实现透明兼容,因此本列无需新增身份字段、无需升级 DDL。 */ @Lob @Column(nullable = false) diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowRecordEntity.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowRecordEntity.java index 498f54cd..7e7a306a 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowRecordEntity.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowRecordEntity.java @@ -1,5 +1,6 @@ package com.codingapi.flow.infra.entity; +import com.codingapi.flow.operator.OperatorIdentity; import jakarta.persistence.*; import lombok.Data; @@ -103,6 +104,7 @@ public class FlowRecordEntity { /** * 当前审批人身份标识(issue #288),空值等价默认身份 */ + @Column(length = OperatorIdentity.MAX_LENGTH) private String currentOperatorIdentity; /** @@ -118,6 +120,7 @@ public class FlowRecordEntity { /** * 提交审批人身份标识(issue #288),空值等价默认身份 */ + @Column(length = OperatorIdentity.MAX_LENGTH) private String submitOperatorIdentity; /** @@ -133,6 +136,7 @@ public class FlowRecordEntity { /** * 代替的审批人身份标识(issue #288),空值等价默认身份 */ + @Column(length = OperatorIdentity.MAX_LENGTH) private String forwardOperatorIdentity; /** @@ -198,6 +202,7 @@ public class FlowRecordEntity { /** * 发起者身份标识(issue #288),空值等价默认身份 */ + @Column(length = OperatorIdentity.MAX_LENGTH) private String createOperatorIdentity; /** @@ -231,6 +236,7 @@ public class FlowRecordEntity { /** * 被干预的用户身份标识(issue #288),空值等价默认身份 */ + @Column(length = OperatorIdentity.MAX_LENGTH) private String interferedOperatorIdentity; /** diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowTodoRecordEntity.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowTodoRecordEntity.java index e29cc601..bdd36e88 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowTodoRecordEntity.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowTodoRecordEntity.java @@ -1,5 +1,6 @@ package com.codingapi.flow.infra.entity; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.record.FlowRecord; import jakarta.persistence.*; import lombok.Data; @@ -71,6 +72,7 @@ public class FlowTodoRecordEntity { /** * 当前审批人身份标识(issue #288),空值等价默认身份 */ + @Column(length = OperatorIdentity.MAX_LENGTH) private String currentOperatorIdentity; /** @@ -86,6 +88,7 @@ public class FlowTodoRecordEntity { /** * 提交审批人身份标识(issue #288),空值等价默认身份 */ + @Column(length = OperatorIdentity.MAX_LENGTH) private String submitOperatorIdentity; /** @@ -105,6 +108,7 @@ public class FlowTodoRecordEntity { /** * 发起者身份标识(issue #288),空值等价默认身份 */ + @Column(length = OperatorIdentity.MAX_LENGTH) private String createOperatorIdentity; /** diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowOperatorAssignmentRepositoryImpl.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowOperatorAssignmentRepositoryImpl.java index 66cfb8f9..03ca222f 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowOperatorAssignmentRepositoryImpl.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowOperatorAssignmentRepositoryImpl.java @@ -1,11 +1,16 @@ package com.codingapi.flow.infra.repository.impl; import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONArray; +import com.alibaba.fastjson2.JSONObject; import com.codingapi.flow.infra.entity.FlowOperatorAssignmentEntity; import com.codingapi.flow.infra.jpa.FlowOperatorAssignmentEntityRepository; +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.repository.FlowOperatorAssignmentRepository; import lombok.AllArgsConstructor; +import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; @@ -17,18 +22,75 @@ public class FlowOperatorAssignmentRepositoryImpl implements FlowOperatorAssignm @Override public void save(String processId, String nodeId, List operatorIds) { + this.saveOperators(processId, nodeId, operatorIds.stream().map(OperatorKey::ofDefault).toList()); + } + + @Override + public List findOperatorIds(String processId, String nodeId) { + return this.findOperators(processId, nodeId).stream().map(OperatorKey::operatorId).toList(); + } + + /** + * 保存分配关系,携带身份(issue #288 衍生 / #292)。 + * + *

    持久化格式保持向后兼容:全部为默认身份时仍写历史格式 {@code [1,2,3]}; + * 存在非默认身份时写 {@code [{"operatorId":1,"identity":"department1"}]}, + * 存量读取方(只认 id 数组)在最常见的默认身份场景下不受影响。 + */ + @Override + public void saveOperators(String processId, String nodeId, List operators) { Optional existing = jpa.findByProcessIdAndNodeId(processId, nodeId); FlowOperatorAssignmentEntity entity = existing.orElseGet(FlowOperatorAssignmentEntity::new); entity.setProcessId(processId); entity.setNodeId(nodeId); - entity.setOperatorIds(JSON.toJSONString(operatorIds)); + entity.setOperatorIds(toJson(operators)); jpa.save(entity); } + /** + * 读取分配关系,携带身份(issue #288 衍生 / #292)。 + * + *

    同时兼容历史格式 {@code [1,2,3]}(按默认身份处理)与带身份格式。 + */ @Override - public List findOperatorIds(String processId, String nodeId) { + public List findOperators(String processId, String nodeId) { return jpa.findByProcessIdAndNodeId(processId, nodeId) - .map(e -> JSON.parseArray(e.getOperatorIds(), Long.class)) + .map(e -> fromJson(e.getOperatorIds())) .orElse(Collections.emptyList()); } + + private static String toJson(List operators) { + boolean hasIdentity = operators.stream().anyMatch(operator -> !OperatorIdentity.isDefault(operator.identity())); + if (!hasIdentity) { + // 默认身份保持历史格式,避免存量读取方(按 id 数组解析)失效 + return JSON.toJSONString(operators.stream().map(OperatorKey::operatorId).toList()); + } + JSONArray array = new JSONArray(); + for (OperatorKey operator : operators) { + JSONObject item = new JSONObject(); + item.put("operatorId", operator.operatorId()); + item.put("identity", operator.identity()); + array.add(item); + } + return array.toJSONString(); + } + + private static List fromJson(String text) { + JSONArray array = JSON.parseArray(text); + if (array == null || array.isEmpty()) { + return Collections.emptyList(); + } + List operators = new ArrayList<>(array.size()); + for (int i = 0; i < array.size(); i++) { + Object item = array.get(i); + if (item instanceof JSONObject jsonObject) { + operators.add(OperatorKey.of( + jsonObject.getLongValue("operatorId"), + jsonObject.getString("identity"))); + } else if (item instanceof Number number) { + operators.add(OperatorKey.ofDefault(number.longValue())); + } + } + return operators; + } } From f71ff2043aa6fb60f2c842a445faab69834d1f8e Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Wed, 2 Dec 2026 14:34:10 +0800 Subject: [PATCH 06/35] =?UTF-8?q?refactor(identity):=20=E6=94=B6=E6=95=9B?= =?UTF-8?q?=E8=BA=AB=E4=BB=BD=E6=A0=87=E8=AF=86=E6=89=A9=E5=B1=95=E7=82=B9?= =?UTF-8?q?=E5=B9=B6=E5=90=8C=E6=AD=A5=E5=89=8D=E7=AB=AF=E5=AD=90=E6=A8=A1?= =?UTF-8?q?=E5=9D=97=EF=BC=88issue=20#288=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 移除 IFlowOperator#getIdentityAttributes 扩展点及对应测试断言 - 示例用户实体 identity 字段改为持久化,不再标记 @Transient - 更新 flow-frontend 子模块指针 --- .../java/com/codingapi/example/entity/User.java | 1 - .../com/codingapi/flow/operator/IFlowOperator.java | 14 -------------- .../flow/operator/OperatorIdentityTest.java | 12 +----------- .../test/java/com/codingapi/flow/user/User.java | 6 ------ flow-frontend | 2 +- 5 files changed, 2 insertions(+), 33 deletions(-) diff --git a/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java b/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java index dce7554d..b2b655c6 100644 --- a/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java +++ b/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java @@ -45,7 +45,6 @@ public class User implements IFlowOperator { * 因此不落库;由 {@code FlowOperatorGateway#get(id, identity)} 按身份返回携带该标识的用户副本。 * 不参与 {@code equals/hashCode},避免同一 id 的两个身份副本被判定为不同用户。 */ - @Transient @EqualsAndHashCode.Exclude @ScriptField(name = "identity", description = "当前身份标识") private String identity; diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java index a52d75e0..344d387d 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java @@ -3,8 +3,6 @@ import com.codingapi.flow.script.request.GroovyScriptRequest; import com.codingapi.springboot.framework.user.IUser; -import java.util.Map; - /** * 流程参与用户 * @@ -47,18 +45,6 @@ default String getIdentity() { } - /** - * 获取身份附加属性 - * - *

    供 Groovy 脚本与前端展示使用的动态字段(如部门名称、岗位名称), - * 下游可自由定义 key/value。框架只透传,不落库、不参与任何引擎判定。 - * - * @return 身份附加属性,默认返回空集合 - */ - default Map getIdentityAttributes() { - return Map.of(); - } - /** * 是否流程管理员 diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityTest.java index 73265cb6..fdc516ff 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityTest.java @@ -4,11 +4,7 @@ import com.codingapi.flow.user.User; import org.junit.jupiter.api.Test; -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.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * 身份标识归一化规则测试。 @@ -93,7 +89,6 @@ public IFlowOperator forwardOperator(GroovyScriptRequest request) { // when & then:默认身份为空串,附加属性为空集合,保证存量实现零改动可用 assertEquals("", operator.getIdentity()); - assertTrue(operator.getIdentityAttributes().isEmpty()); } @Test @@ -103,7 +98,6 @@ void should_allow_downstream_override_identity() { // when & then assertEquals("department1", OperatorIdentity.of(operator)); - assertEquals("部门一", operator.getIdentityAttributes().get("deptName")); } /** @@ -123,9 +117,5 @@ public String getIdentity() { return identity; } - @Override - public Map getIdentityAttributes() { - return Map.of("deptName", "部门一"); - } } } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java b/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java index 6b455b9a..16016d9f 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java @@ -4,8 +4,6 @@ import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.script.request.GroovyScriptRequest; -import java.util.Map; - public class User implements IFlowOperator { private final long userId; @@ -75,10 +73,6 @@ public String getIdentity() { return identity; } - @Override - public Map getIdentityAttributes() { - return identity == null || identity.isEmpty() ? Map.of() : Map.of("identityName", identity); - } @Override public IFlowOperator forwardOperator(GroovyScriptRequest request) { diff --git a/flow-frontend b/flow-frontend index 068dc13b..875b7a7f 160000 --- a/flow-frontend +++ b/flow-frontend @@ -1 +1 @@ -Subproject commit 068dc13b853ea31de56558995e8f494d8b311f62 +Subproject commit 875b7a7f58d744b7ab08bf0d92256207d073d025 From e80934cecce5016a2d173864b5c32de691cb0541 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Wed, 2 Dec 2026 14:49:40 +0800 Subject: [PATCH 07/35] =?UTF-8?q?fix(identity):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E6=89=B9=E9=87=8F=E5=8F=96=E4=BA=BA=E8=BA=AB=E4=BB=BD=E4=B8=A2?= =?UTF-8?q?=E5=A4=B1=E4=B8=8E=E5=85=A5=E5=8F=A3=E6=A0=A1=E9=AA=8C=E7=BC=BA?= =?UTF-8?q?=E5=8F=A3=EF=BC=88issue=20#288=20=E8=AF=84=E5=AE=A1=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 批量取人:下游未覆盖 findByIds(ids, identity) 时逐条回退到按身份单条取人, 身份不符的结果不再登记线程缓存,避免污染同线程后续按身份的读取 (示例工程只覆盖单条 get 时会静默丢失身份,现已由用例守住) - 发起 / 审批入口补 OperatorIdentityGuard 降级告警 - REST 入口:operatorIdentity 参数在入口校验;覆盖 operatorId 时不再继承登录用户身份, 避免「目标人员 + 登录人身份」错配 - 示例:User.identity 恢复 @Transient(运行期身份),网关补 findByIds(ids, identity) 参考实现 - 文档:清理已移除的 getIdentityAttributes,补「启用身份的时机」迁移指引与示例验证步骤 --- docs/Integration/operator-identity.md | 61 ++++++++++++---- .../com/codingapi/example/entity/User.java | 4 +- .../gateway/impl/FlowOperatorGatewayImpl.java | 18 +++++ .../cache/FlowOperatorLocalThreadCache.java | 24 ++++++- .../flow/context/GatewayContext.java | 29 +++++++- .../flow/service/impl/FlowActionService.java | 4 ++ .../flow/service/impl/FlowCreateService.java | 3 + .../cache/FlowOperatorBulkIdentityTest.java | 70 +++++++++++++++++++ .../api/controller/FlowRecordController.java | 8 ++- .../controller/FlowRecordQueryController.java | 8 ++- flow-frontend | 2 +- 11 files changed, 210 insertions(+), 21 deletions(-) diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md index 08313370..b6978119 100644 --- a/docs/Integration/operator-identity.md +++ b/docs/Integration/operator-identity.md @@ -32,23 +32,23 @@ public interface IFlowOperator extends IUser { String getName(); + boolean isFlowManager(); + + IFlowOperator forwardOperator(GroovyScriptRequest request); + /** * 身份标识,空串表示默认身份。框架不解释语义。 */ default String getIdentity() { return OperatorIdentity.DEFAULT; } - - /** - * 身份的附加属性(部门名、岗位名等),只透传给脚本与前端,不参与引擎判定,不落库。 - */ - default Map getIdentityAttributes() { - return Map.of(); - } } ``` -两个方法都是 `default`,**下游存量实现类无需改动即可编译**。 +`getIdentity()` 是 `default` 方法,**下游存量实现类无需改动即可编译**。 + +> 身份只保存 `identity` 这一个不透明字符串:不落库附加属性、不冻结身份名称。 +> 需要「部门名称」等展示信息时,由宿主持有身份 → 名称的映射自行渲染,框架不提供该字段。 ## 3. 下游需要做什么 @@ -90,7 +90,10 @@ public IFlowOperator get(long id, String identity) { | `IRepositoryHolder` | `findOperatorByIds(List, String)` | 退化为 `findOperatorByIds(ids)` | | `IRepositoryHolder` | `getOperatorById(long, String)` | 退化为 `getOperatorById(id)` | -> 引擎在 `GatewayContext#getFlowOperator(id, identity)` 处做运行期检查:请求声明了非默认身份、但回查到的操作者身份为空时,会按 `(人员id, 身份)` 去重输出一条 WARN,提示下游未覆盖带身份的取人方法。这类问题原先是**静默降级**(按身份查待办直接返回空列表),集成阶段极难定位。 +> 引擎做了两层兜底,保证「没覆盖」不会静默丢身份: +> +> 1. **单条路径**:`GatewayContext#getFlowOperator(id, identity)`、发起(`FlowCreateService`)与审批(`FlowActionService`)三个入口都会做运行期检查——请求声明了非默认身份、但回查到的操作者身份为空时,按 `(人员id, 身份)` 去重输出一条 WARN; +> 2. **批量路径**:`GatewayContext#findByIds(ids, identity)` 发现批量结果身份不符时,逐条回退到单条按身份取人(正确实现会返回带身份的副本,未实现则触发上面的 WARN),同时不把身份不符的对象登记进线程缓存,避免污染后续按身份的读取。 ### 3.3 请求声明身份 @@ -176,7 +179,7 @@ def run(request) { | `t_flow_record` | `create_operator_identity`、`submit_operator_identity`、`current_operator_identity`、`forward_operator_identity`、`interfered_operator_identity` | | `t_flow_todo_record` | `create_operator_identity`、`submit_operator_identity`、`current_operator_identity` | -只存身份标识本身,`getIdentityAttributes()` 的附加属性**不落库**(避免 5 个 JSON 快照列,也避免身份名称被冻结在历史数据里)。展示名称仍取操作者姓名。 +只存身份标识本身,**不落库任何附加属性**(避免为 5 组操作者各加一个 JSON 快照列,也避免身份名称被冻结在历史数据里)。展示名称仍取操作者姓名;需要展示身份名称时由宿主按 `identity` 自行映射。 升级脚本见 [sql/0.3.0-operator-identity.sql](./sql/0.3.0-operator-identity.sql)。 @@ -220,7 +223,7 @@ def run(request) { | 不含 `#` | 与待办合并键的身份后缀分隔符冲突 | | 不含控制字符 | 内部缓存键以控制字符拼接 | -读取路径仍用宽松的 `normalize()`(仅 null → 空串),历史数据不会被校验拦住。 +读取路径仍用宽松的 `normalize()`(仅 null → 空串),历史数据不会被校验拦住;请求入口(REST 的两个 `operatorIdentity` 参数)同样会先校验,非法值在入口即被拒绝。 人员分配表 `t_flow_operator_assignment` **无需改表**:身份编码在 `operatorIds` JSON 列内。全部为默认身份时保持历史格式 `[1,2,3]`;存在非默认身份时写 `[{"operatorId":2,"identity":"department1"}]`,读取端同时兼容两种格式。 @@ -231,8 +234,40 @@ def run(request) { | 存量数据 | 新列为 NULL,按默认身份读取,**无需回填** | | 回滚 | 仅新增 nullable 列,旧版本不映射新列,可直接回滚 | | 工作流定义 | 与身份无关,导入导出不受影响 | -| 身份长度 | 建议 ≤ 64 字符(复合 key 用 `:` 拼接) | +| 身份长度 | ≤ 64 字符(复合 key 用 `:` 拼接),入口与落库双处校验 | | 待办索引 | 实体未声明 `@Index`,大表请按 DDL 脚本手工加索引 | | 不做的事 | 引擎不建组织模型、不做身份授权校验(「user1 能否以 department1 身份操作」由业务侧保证)、不冻结身份名称 | -> 身份是一个**不透明字符串**,不要尝试在引擎里比较它的业务含义;需要「部门名称」等展示信息,请用 `getIdentityAttributes()` 或按身份回查组织数据。 +> 身份是一个**不透明字符串**,不要尝试在引擎里比较它的业务含义;需要「部门名称」等展示信息,由宿主维护 `identity → 名称` 的映射自行渲染(框架不提供附加属性字段)。 + +### 5.1 启用身份的时机(重要) + +「存量数据无需回填」只说明**数据**是兼容的,不代表**行为**会自动兼容。判定与查询口径是 +`(人员id, 身份)` 严格匹配,因此当某个用户开始携带非空身份后,他在存量「默认身份」数据上的表现是: + +| 场景 | 表现 | +|------|------| +| 待办 / 已办 / 抄送列表 | 存量默认身份记录**不再出现在该身份的列表里**(按身份隔离的必然结果) | +| 处置存量待办 | 记录身份为默认身份,当前身份 != 默认身份 → 判权不通过,操作被拒绝 | +| 待办合并 | 旧格式键(无 `#identity`)与新键不互通,不会合并到同一条待办 | + +**因此不要在全量用户上一次性打开身份。** 推荐三种过渡方式: + +1. **只对新流程启用**:存量在途流程继续以默认身份办结,新流程带身份发起(最省事,推荐); +2. **兼容开关**:查询与判权时把默认身份作为兜底(`identity = X OR identity = ''`),过渡期打开、收尾时关闭; +3. **一次性回填**:把运行中流程的 `*_operator_identity` 回填为操作者当期身份,需要停机窗口与全量校验。 + +前端应提供「切回默认身份」的入口(示例工程见 5.2),让用户仍能处理存量事项。 + +### 5.2 示例工程如何验证 + +`flow-engine-example` + `flow-frontend` 的 `apps/app-pc` 已打通端到端验证: + +1. 启动后端(`cd flow-engine-example && mvn spring-boot:run`,端口 8090)与前端(`pnpm dev:app-pc`); +2. 登录后页面右下角有「身份切换(演示)」:选 `department1` → 切换,页面会刷新; +3. 以该身份发起一条流程(待办中心 → 发起流程),再切到 `department2` 发起一条; +4. 回到「我的待办」:两条流程各自只在自己的身份下可见,列表的「身份」列显示对应标识; +5. 切回「默认身份」可以看到此前用默认身份产生的历史记录。 + +示例的 `User.identity` 是 `@Transient`(运行期身份,不落库),由 `FlowOperatorGateway#get(id, identity)` / +`findByIds(ids, identity)` 返回带身份的副本。真实项目把身份选项换成自己的组织模型即可。 diff --git a/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java b/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java index b2b655c6..0cbc7e5b 100644 --- a/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java +++ b/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java @@ -42,9 +42,11 @@ public class User implements IFlowOperator { * 当前身份标识(issue #288)。 * *

    同一个人员可能隶属多个部门/岗位,以不同身份参与流程。身份是**运行期选择**而非用户主数据, - * 因此不落库;由 {@code FlowOperatorGateway#get(id, identity)} 按身份返回携带该标识的用户副本。 + * 因此不落库({@link Transient});由 {@code FlowOperatorGateway#get(id, identity)} 按身份返回 + * 携带该标识的用户副本,示例前端通过请求参数 {@code operatorIdentity} 声明当前身份。 * 不参与 {@code equals/hashCode},避免同一 id 的两个身份副本被判定为不同用户。 */ + @Transient @EqualsAndHashCode.Exclude @ScriptField(name = "identity", description = "当前身份标识") private String identity; diff --git a/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java b/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java index d133ca0d..133f4516 100644 --- a/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java +++ b/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java @@ -45,4 +45,22 @@ public List findByIds(List ids) { .toList(); } + /** + * 按统一身份批量获取操作者(issue #288 衍生 / #293)。 + * + *

    批量重载同样必须返回携带身份的副本:只覆盖单条 {@code get(id, identity)} 时, + * 流程树、人员设定等批量路径会把身份退化为默认身份。 + */ + @Override + public List findByIds(List ids, String identity) { + if (OperatorIdentity.isDefault(identity)) { + return findByIds(ids); + } + String normalized = OperatorIdentity.normalize(identity); + return userRepository.findUserByIdIn(ids) + .stream() + .map(user -> (IFlowOperator) user.withIdentity(normalized)) + .toList(); + } + } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java b/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java index 6638e104..79a247c0 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java @@ -87,13 +87,28 @@ public IFlowOperator get(long id, String identity, Supplier opera } operator = operatorLoader.get(); - if (operator != null) { + // 非默认身份且下游未按身份返回副本时,加载结果的身份与缓存键不一致。 + // 此时不能登记,否则同线程后续按该身份的读取都会命中这个错误身份的对象(issue #288 评审修复)。 + if (operator != null && isIdentityMatched(operator, identity)) { operatorCaches.put(key, operator); this.cache.set(operatorCaches); } return operator; } + /** + * 判断加载结果的身份是否与请求的身份一致。 + * + *

    默认身份的读取保持历史行为(批量路径与单条路径都以默认身份为标识无关入口), + * 只有「请求了非默认身份、但拿回的却是另一个身份」才视为不一致。 + */ + private static boolean isIdentityMatched(IFlowOperator operator, String requestedIdentity) { + if (OperatorIdentity.isDefault(requestedIdentity)) { + return true; + } + return OperatorIdentity.same(OperatorIdentity.of(operator), requestedIdentity); + } + /** * 批量读取操作者(默认身份)。 * @@ -142,7 +157,12 @@ public List find(List ids, String identity, IFlowOperatorFi if (newOperatorList != null && !newOperatorList.isEmpty()) { for (IFlowOperator operator : newOperatorList) { // 结果按「请求身份」登记,而不是操作者对象自带身份: - // 调用方是按该身份发起查询的,登记键必须与读取键一致,否则读取时必然落空 + // 调用方是按该身份发起查询的,登记键必须与读取键一致,否则读取时必然落空。 + // 但「请求了非默认身份、对象却是另一个身份」时不能登记——否则该身份键被错误对象污染, + // 同线程后续按身份的单条读取会直接命中它,身份被静默替换(issue #288 评审修复)。 + if (!isIdentityMatched(operator, normalizedIdentity)) { + continue; + } operatorCaches.put(cacheKey(operator.getUserId(), normalizedIdentity), operator); } this.cache.set(operatorCaches); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java b/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java index 502a277f..910bf46d 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java @@ -8,7 +8,11 @@ import lombok.Getter; import lombok.Setter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; public class GatewayContext { @@ -65,8 +69,31 @@ public List findByIds(List ids) { * @return 操作者列表 */ public List findByIds(List ids, String identity) { - return FlowOperatorLocalThreadCache.getInstance() + List operators = FlowOperatorLocalThreadCache.getInstance() .find(ids, identity, (idList) -> flowOperatorGateway.findByIds(idList, identity)); + if (OperatorIdentity.isDefault(identity)) { + return operators; + } + // 下游未覆盖带身份的批量重载时,批量结果会退化为默认身份(findByIds(ids) 的返回), + // 这里逐条回退到单条按身份取人:正确实现会返回带身份的副本,未实现则由 OperatorIdentityGuard 告警。 + // 不做这一层兜底时,批量路径会把身份静默丢弃,且不会产生任何日志(issue #288 评审修复)。 + Map operatorById = new HashMap<>(); + if (operators != null) { + for (IFlowOperator operator : operators) { + operatorById.put(operator.getUserId(), operator); + } + } + List result = new ArrayList<>(); + for (Long id : new LinkedHashSet<>(ids)) { + IFlowOperator operator = operatorById.get(id); + if (operator == null || !OperatorIdentity.same(OperatorIdentity.of(operator), identity)) { + operator = this.getFlowOperator(id, identity); + } + if (operator != null) { + result.add(operator); + } + } + return result; } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java index f84e3195..b96f41ac 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java @@ -11,6 +11,7 @@ import com.codingapi.flow.manager.WorkflowStrategyManager; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentityGuard; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.response.ActionResponse; import com.codingapi.flow.record.FlowRecord; @@ -56,6 +57,8 @@ public ActionResponse action() { // 验证当前用户(按请求声明的身份加载,issue #288) IFlowOperator currentOperator = flowOperatorGateway.get( request.getAdvice().getOperatorId(), request.getAdvice().getOperatorIdentity()); + // 审批入口同样检查身份是否真的生效,避免下游未覆盖带身份的取人方法时静默降级(issue #288 评审修复) + OperatorIdentityGuard.check(request.getAdvice().getOperatorId(), request.getAdvice().getOperatorIdentity(), currentOperator); if (currentOperator == null) { throw FlowNotFoundException.operator(request.getAdvice().getOperatorId()); } @@ -70,6 +73,7 @@ public ActionResponse action() { // 发起人按记录中的身份回查,避免同一 id 的不同身份拿到同一个操作者实例 IFlowOperator createdOperator = flowOperatorGateway.get( flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity()); + OperatorIdentityGuard.check(flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity(), createdOperator); WorkflowRuntime workflowRuntime = workflowService.getWorkflowRuntime(flowRecord.getWorkRuntimeId()); if (workflowRuntime == null) { 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 ae715f65..a1918a55 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 @@ -14,6 +14,7 @@ import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.node.nodes.StartNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentityGuard; import com.codingapi.flow.pojo.request.FlowCreateRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.WorkflowService; @@ -59,6 +60,8 @@ public long create() { FlowRuntimeScriptLocalCache.getInstance().set(workflowRuntime.getScripts()); // 验证当前用户(按请求声明的身份加载,同一人不同身份是不同参与人) IFlowOperator currentOperator = flowOperatorGateway.get(request.getOperatorId(), request.getOperatorIdentity()); + // 发起入口同样要检查身份是否真的生效:下游未覆盖带身份的取人方法时身份会被静默丢弃(issue #288 评审修复) + OperatorIdentityGuard.check(request.getOperatorId(), request.getOperatorIdentity(), currentOperator); if (!workflow.matchCreatedOperator(currentOperator)) { throw FlowPermissionException.accessDenied("create workflow"); } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java index 4d8da08a..fbce2feb 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java @@ -1,9 +1,11 @@ package com.codingapi.flow.cache; +import com.codingapi.flow.context.GatewayContext; import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.user.User; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -11,6 +13,7 @@ import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; /** @@ -23,10 +26,20 @@ class FlowOperatorBulkIdentityTest { private FlowOperatorLocalThreadCache cache; + private FlowOperatorGateway previousGateway; + @BeforeEach void setUp() { cache = FlowOperatorLocalThreadCache.getInstance(); cache.clear(); + previousGateway = GatewayContext.getInstance().getFlowOperatorGateway(); + } + + @AfterEach + void tearDown() { + // GatewayContext 是全局单例,用例结束后必须还原,避免影响其他用例 + GatewayContext.getInstance().setFlowOperatorGateway(previousGateway); + cache.clear(); } /** @@ -104,4 +117,61 @@ public List findByIds(List ids) { assertEquals(2, operators.size()); assertEquals("", OperatorIdentity.of(operators.get(0))); } + + /** + * 测试目标:下游只覆盖单条按身份取人、未覆盖批量重载时,批量路径必须回退到单条取人拿回正确身份。 + * 前置条件:网关实现 {@code get(id, identity)}(返回带身份的副本)但复用默认的批量重载。 + * 执行步骤:经 GatewayContext 批量按身份取人,再按同一身份单条取人。 + * 期望断言:批量结果携带请求身份(不是被静默降级为默认身份),且缓存没有被错误对象污染。 + */ + @Test + void should_fall_back_to_single_load_when_gateway_has_no_bulk_identity_override() { + FlowOperatorGateway partialGateway = new FlowOperatorGateway() { + @Override + public IFlowOperator get(long id) { + return new User(id, "user" + id); + } + + @Override + public IFlowOperator get(long id, String identity) { + return User.withIdentity(id, "user" + id, identity); + } + + @Override + public List findByIds(List ids) { + return ids.stream().map(id -> (IFlowOperator) new User(id, "user" + id)).toList(); + } + }; + + GatewayContext.getInstance().setFlowOperatorGateway(partialGateway); + + List operators = GatewayContext.getInstance().findByIds(List.of(1L), "department1"); + + assertEquals(1, operators.size()); + assertEquals("department1", OperatorIdentity.of(operators.get(0)), + "批量路径不能把请求身份静默降级为默认身份"); + // 单条读取必须命中同一个带身份的对象,说明缓存未被默认身份的对象污染 + assertEquals("department1", + OperatorIdentity.of(FlowOperatorLocalThreadCache.getInstance().get(1, "department1", () -> null))); + } + + /** + * 测试目标:单条加载拿回身份不一致的对象时不登记缓存(避免污染身份键)。 + * 前置条件:缓存为空,加载器返回默认身份对象。 + * 执行步骤:以非默认身份读取一次,再用正确身份的加载器读一次。 + * 期望断言:第一次返回默认身份对象但不缓存,第二次能拿到正确的身份对象。 + */ + @Test + void should_not_cache_single_load_result_with_mismatched_identity() { + User defaultUser = new User(7, "user7"); + User identityUser = User.withIdentity(7, "user7", "department1"); + + IFlowOperator first = cache.get(7, "department1", () -> defaultUser); + assertSame(defaultUser, first); + assertNull(cache.get(7, "department1", () -> null), "身份不一致的加载结果不能登记缓存"); + + IFlowOperator second = cache.get(7, "department1", () -> identityUser); + assertSame(identityUser, second); + assertSame(identityUser, cache.get(7, "department1", () -> null)); + } } 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 db53663b..d54cd745 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 @@ -65,7 +65,13 @@ private String loadCurrentOperatorIdentity() { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpServletRequest request = attributes.getRequest(); if (request.getParameterMap().containsKey("operatorIdentity")) { - return OperatorIdentity.normalize(request.getParameter("operatorIdentity")); + // 入口即校验:长度 / 分隔符 / 控制字符不合法时直接拒绝,避免拖到落库阶段才失败 + return OperatorIdentity.validate(request.getParameter("operatorIdentity")); + } + // 覆盖了 operatorId(联调、无登录态场景)时不再继承登录用户的身份, + // 否则会得到「目标人员 + 当前登录人身份」的错配组合(issue #288 评审修复) + if (StringUtils.hasText(request.getParameter("operatorId"))) { + return OperatorIdentity.DEFAULT; } IFlowOperator current = (IFlowOperator) UserContext.getInstance().current(); return current == null ? OperatorIdentity.DEFAULT : OperatorIdentity.of(current); diff --git a/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java b/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java index ead13803..353abddf 100644 --- a/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java +++ b/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java @@ -63,9 +63,13 @@ private long loadCurrentOperatorId(){ private String loadCurrentOperatorIdentity(){ ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpServletRequest request = attributes.getRequest(); - String key = request.getParameter("operatorIdentity"); if(request.getParameterMap().containsKey("operatorIdentity")) { - return OperatorIdentity.normalize(key); + // 入口即校验,与命令侧口径一致(issue #288 评审修复) + return OperatorIdentity.validate(request.getParameter("operatorIdentity")); + } + // 覆盖了 operatorId(联调、无登录态场景)时不再继承登录用户的身份,避免人员与身份错配 + if(StringUtils.hasText(request.getParameter("operatorId"))) { + return OperatorIdentity.DEFAULT; } IFlowOperator current = (IFlowOperator) UserContext.getInstance().current(); return current == null ? OperatorIdentity.DEFAULT : OperatorIdentity.of(current); diff --git a/flow-frontend b/flow-frontend index 875b7a7f..31f7eea3 160000 --- a/flow-frontend +++ b/flow-frontend @@ -1 +1 @@ -Subproject commit 875b7a7f58d744b7ab08bf0d92256207d073d025 +Subproject commit 31f7eea3eff48ffdabca6fec28041b2c1599cc97 From 1066281f24c3c293177067eee3c5ca1e246ebf81 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Wed, 2 Dec 2026 15:05:49 +0800 Subject: [PATCH 08/35] =?UTF-8?q?feat(example):=20=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E7=94=9F=E6=88=90=E8=BA=AB=E4=BB=BD=E6=A0=87=E8=AF=86=E6=BC=94?= =?UTF-8?q?=E7=A4=BA=E6=95=B0=E6=8D=AE=EF=BC=8C=E4=BE=BF=E4=BA=8E=E5=89=8D?= =?UTF-8?q?=E5=90=8E=E7=AB=AF=E5=8F=AF=E8=A7=86=E5=8C=96=E9=AA=8C=E8=AF=81?= =?UTF-8?q?=EF=BC=88issue=20#288=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 IdentityDemoInitializer:首次启动创建演示账号 user1/user2(密码 123456)与 流程 identity-demo,并以三种身份组合各发起一条流程,把待办投给 「张三·默认身份」「张三·department1」「李四·department2」 - 幂等:流程编码已存在时跳过;可通过 flow.example.identity-demo-enabled=false 关闭 - AdminInitializer 显式 @Order(10),保证 admin 先于依赖它的初始化器创建 - 文档 5.2 补充演示账号、验证步骤与前端 dev 启动方式 --- docs/Integration/operator-identity.md | 23 +- .../example/runner/AdminInitializer.java | 8 + .../runner/IdentityDemoInitializer.java | 233 ++++++++++++++++++ 3 files changed, 258 insertions(+), 6 deletions(-) create mode 100644 flow-engine-example/src/main/java/com/codingapi/example/runner/IdentityDemoInitializer.java diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md index b6978119..2dd6898f 100644 --- a/docs/Integration/operator-identity.md +++ b/docs/Integration/operator-identity.md @@ -261,13 +261,24 @@ def run(request) { ### 5.2 示例工程如何验证 -`flow-engine-example` + `flow-frontend` 的 `apps/app-pc` 已打通端到端验证: +`flow-engine-example` + `flow-frontend` 的 `apps/app-pc` 已打通端到端验证,**首次启动会自动生成一套演示数据** +(`IdentityDemoInitializer`,流程编码 `identity-demo`,已有该流程时跳过,不重复造数): -1. 启动后端(`cd flow-engine-example && mvn spring-boot:run`,端口 8090)与前端(`pnpm dev:app-pc`); -2. 登录后页面右下角有「身份切换(演示)」:选 `department1` → 切换,页面会刷新; -3. 以该身份发起一条流程(待办中心 → 发起流程),再切到 `department2` 发起一条; -4. 回到「我的待办」:两条流程各自只在自己的身份下可见,列表的「身份」列显示对应标识; -5. 切回「默认身份」可以看到此前用默认身份产生的历史记录。 +| 账号 | 密码 | 待办(审批人 · 身份) | +|------|------|----------------------| +| `user1`(张三) | `123456` | 张三 · 默认身份 / 张三 · `department1` | +| `user2`(李四) | `123456` | 李四 · `department2` | +| `admin` | `admin` | 无(三条流程的发起人) | + +验证步骤: + +1. 启动后端:`cd flow-engine-example && mvn -o spring-boot:run`(端口 8090); +2. 启动前端:`cd flow-frontend && pnpm -F @flow-example/app-pc dev`(开发服务器已把 `/api` 代理到 8090); +3. 用 `user1` / `123456` 登录 → 「待办中心」:默认身份下只有 1 条待办,「身份」列为「默认身份」; +4. 页面右下角「身份切换(演示)」输入 `department1` → 切换(页面自动刷新):待办变成另一条,「身份」列显示 `department1`; +5. 切到 `department2`:待办为空——那是 `user2` 的待办,验证「同一人不同身份、不同人不同身份」都不串; +6. 用错误身份点「办理」会被拒绝(`state.operator.notMatch`),用匹配身份才能审批通过。 示例的 `User.identity` 是 `@Transient`(运行期身份,不落库),由 `FlowOperatorGateway#get(id, identity)` / `findByIds(ids, identity)` 返回带身份的副本。真实项目把身份选项换成自己的组织模型即可。 + diff --git a/flow-engine-example/src/main/java/com/codingapi/example/runner/AdminInitializer.java b/flow-engine-example/src/main/java/com/codingapi/example/runner/AdminInitializer.java index eb9ffe13..9df771db 100644 --- a/flow-engine-example/src/main/java/com/codingapi/example/runner/AdminInitializer.java +++ b/flow-engine-example/src/main/java/com/codingapi/example/runner/AdminInitializer.java @@ -5,10 +5,18 @@ import lombok.AllArgsConstructor; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; +import org.springframework.core.annotation.Order; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; +/** + * 内置管理员账号初始化。 + * + *

    必须早于其它依赖 admin 的数据初始化执行(例如 {@code IdentityDemoInitializer} 用它作为流程创建人), + * 因此显式声明 {@link Order};未声明时优先级最低,会在其它 Initializer 之后执行。 + */ @Service +@Order(10) @AllArgsConstructor public class AdminInitializer implements ApplicationRunner { diff --git a/flow-engine-example/src/main/java/com/codingapi/example/runner/IdentityDemoInitializer.java b/flow-engine-example/src/main/java/com/codingapi/example/runner/IdentityDemoInitializer.java new file mode 100644 index 00000000..634a5265 --- /dev/null +++ b/flow-engine-example/src/main/java/com/codingapi/example/runner/IdentityDemoInitializer.java @@ -0,0 +1,233 @@ +package com.codingapi.example.runner; + +import com.codingapi.example.entity.User; +import com.codingapi.example.repository.UserRepository; +import com.codingapi.flow.builder.FormFieldPermissionsBuilder; +import com.codingapi.flow.builder.NodeStrategyBuilder; +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.nodes.ApprovalNode; +import com.codingapi.flow.node.nodes.EndNode; +import com.codingapi.flow.node.nodes.StartNode; +import com.codingapi.flow.operator.OperatorKey; +import com.codingapi.flow.pojo.request.FlowActionRequest; +import com.codingapi.flow.pojo.request.FlowCreateRequest; +import com.codingapi.flow.service.FlowService; +import com.codingapi.flow.service.WorkflowService; +import com.codingapi.flow.strategy.node.FormFieldPermissionStrategy; +import com.codingapi.flow.strategy.node.OperatorLoadStrategy; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.WorkflowBuilder; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.core.annotation.Order; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * 身份标识(issue #288)可视化验证数据初始化。 + * + *

    示例工程默认只有 admin 一个账号、没有任何流程数据,登录后待办页永远是空列表, + * 无法直观看到「同一人员以不同身份参与流程、待办按身份隔离」的效果。这里在首次启动时 + * 生成一套最小可验证数据: + * + *

      + *
    1. 创建演示账号 {@code user1}(张三)、{@code user2}(李四),密码统一 {@code 123456};
    2. + *
    3. 创建流程「身份标识验证流程」(编码 {@value #WORKFLOW_CODE}):开始 → 审批(发起人设定审批人)→ 结束;
    4. + *
    5. 以 admin 分别用三种身份组合发起并提交三条流程,把待办分别投给: + *
        + *
      • 张三 · 默认身份
      • + *
      • 张三 · department1
      • + *
      • 李四 · department2
      • + *
      + *
    6. + *
    + * + *

    验证方式:用 user1 登录,在页面右下角切换身份为「默认身份」与「department1」, + * 待办列表应分别只出现对应身份的那一条;切到「department2」应为空(那是李四的待办)。 + * + *

    初始化是幂等的:流程编码已存在时直接跳过,不会重复造数据。 + * 不需要演示数据时可通过 {@code flow.example.identity-demo-enabled=false} 关闭。 + */ +@Slf4j +@Service +@Order(20) +@AllArgsConstructor +@ConditionalOnProperty(prefix = "flow.example", name = "identity-demo-enabled", havingValue = "true", matchIfMissing = true) +public class IdentityDemoInitializer implements ApplicationRunner { + + /** + * 演示流程编码,同时作为「是否已初始化」的幂等标记 + */ + public static final String WORKFLOW_CODE = "identity-demo"; + + /** + * 演示流程标题 + */ + public static final String WORKFLOW_TITLE = "身份标识验证流程"; + + /** + * 演示账号:张三 + */ + public static final String ACCOUNT_ZHANGSAN = "user1"; + + /** + * 演示账号:李四 + */ + public static final String ACCOUNT_LISI = "user2"; + + /** + * 演示账号统一密码 + */ + public static final String DEMO_PASSWORD = "123456"; + + /** + * 演示身份:部门一 + */ + public static final String IDENTITY_DEPARTMENT1 = "department1"; + + /** + * 演示身份:部门二 + */ + public static final String IDENTITY_DEPARTMENT2 = "department2"; + + private final UserRepository userRepository; + private final PasswordEncoder passwordEncoder; + private final WorkflowService workflowService; + private final FlowService flowService; + + @Override + public void run(ApplicationArguments args) { + try { + if (workflowService.getWorkflowByCode(WORKFLOW_CODE) != null) { + return; + } + User admin = userRepository.getUserByAccount(User.ADMIN_ACCOUNT); + if (admin == null) { + log.warn("[identity-demo] 未找到 admin 账号,跳过演示数据初始化"); + return; + } + User zhangsan = ensureUser(ACCOUNT_ZHANGSAN, "张三"); + User lisi = ensureUser(ACCOUNT_LISI, "李四"); + + ApprovalNode approvalNode = buildWorkflow(admin); + + // 张三 · 默认身份:切到非默认身份后这条待办不再可见 + createAndSubmit(admin, null, approvalNode.getId(), + OperatorKey.ofDefault(zhangsan.getUserId()), "默认身份审批人"); + // 张三 · department1:只有切换到 department1 才可见 + createAndSubmit(admin, IDENTITY_DEPARTMENT1, approvalNode.getId(), + OperatorKey.of(zhangsan.getUserId(), IDENTITY_DEPARTMENT1), "部门一身份审批人"); + // 李四 · department2:用于验证「别人的身份看不到我的待办」 + createAndSubmit(admin, IDENTITY_DEPARTMENT2, approvalNode.getId(), + OperatorKey.of(lisi.getUserId(), IDENTITY_DEPARTMENT2), "部门二身份审批人"); + + log.info("[identity-demo] 演示数据初始化完成:流程编码={},账号={}/{}(密码 {})", + WORKFLOW_CODE, ACCOUNT_ZHANGSAN, ACCOUNT_LISI, DEMO_PASSWORD); + } catch (Exception e) { + // 演示数据失败不能阻塞应用启动 + log.warn("[identity-demo] 演示数据初始化失败:{}", e.getMessage(), e); + } + } + + /** + * 创建演示流程定义,返回审批节点(其 id 用于发起时指定审批人) + */ + private ApprovalNode buildWorkflow(User admin) { + FlowForm form = FlowFormBuilder.builder() + .name(WORKFLOW_TITLE) + .code(WORKFLOW_CODE) + .addField("申请事项", "subject", DataType.STRING) + .addField("备注", "remark", DataType.STRING) + .build(); + + FormFieldPermissionsBuilder permissions = FormFieldPermissionsBuilder.builder() + .addPermission(WORKFLOW_CODE, "subject", PermissionType.WRITE) + .addPermission(WORKFLOW_CODE, "remark", PermissionType.WRITE); + + StartNode startNode = StartNode.builder() + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(permissions.build())) + .build()) + .build(); + + // 审批人由发起人在发起时指定(INITIATOR_SELECT),因此可以指定「某人 + 某个身份」 + ApprovalNode approvalNode = ApprovalNode.builder() + .name("审批节点") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(permissions.build())) + .addStrategy(OperatorLoadStrategy.initiatorSelectStrategy()) + .build()) + .build(); + + EndNode endNode = EndNode.builder().build(); + + Workflow workflow = WorkflowBuilder.builder() + .title(WORKFLOW_TITLE) + .code(WORKFLOW_CODE) + .createdOperator(admin) + .form(form) + .addNode(startNode) + .addNode(approvalNode) + .addNode(endNode) + .build(); + + workflowService.saveWorkflow(workflow, true); + return approvalNode; + } + + /** + * 以指定身份发起流程,并提交开始节点把待办投给「审批人 + 审批身份」 + * + * @param initiator 发起人 + * @param identity 发起人身份(null 表示默认身份) + * @param approvalNodeId 审批节点 id + * @param approver 审批人(人员 + 身份) + * @param subject 申请事项 + */ + private void createAndSubmit(User initiator, String identity, String approvalNodeId, + OperatorKey approver, String subject) { + Workflow workflow = workflowService.getWorkflowByCode(WORKFLOW_CODE); + StartNode startNode = (StartNode) workflow.getStartNode(); + String actionId = startNode.actionManager().getActions().get(0).id(); + Map formData = Map.of("subject", subject, "remark", "身份标识演示数据"); + + FlowCreateRequest createRequest = new FlowCreateRequest(); + createRequest.setWorkCode(WORKFLOW_CODE); + createRequest.setFormData(formData); + createRequest.setActionId(actionId); + createRequest.setOperatorId(initiator.getUserId()); + createRequest.setOperatorIdentity(identity); + createRequest.setOperatorSelectOperators(Map.of(approvalNodeId, List.of(approver))); + long recordId = flowService.create(createRequest); + + // 提交开始节点:这一步才真正把待办写入审批人的待办列表(带审批身份) + FlowActionRequest actionRequest = createRequest.toActionRequest(recordId); + flowService.action(actionRequest); + } + + /** + * 按账号取用户,不存在则创建(密码为 {@value #DEMO_PASSWORD}) + */ + private User ensureUser(String account, String name) { + User user = userRepository.getUserByAccount(account); + if (user != null) { + return user; + } + user = new User(); + user.setAccount(account); + user.setName(name); + user.setPassword(DEMO_PASSWORD); + user.setFlowManager(false); + user.encodePassword(passwordEncoder); + return userRepository.save(user); + } +} From e278740e40b05e860c349fcdf6a76603c3b27eb0 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Wed, 2 Dec 2026 15:39:15 +0800 Subject: [PATCH 09/35] =?UTF-8?q?docs(identity):=20=E8=A1=A5=E5=85=85?= =?UTF-8?q?=E3=80=8C=E5=AE=A1=E6=89=B9=E4=BA=BA=E5=BE=85=E5=8A=9E=E8=90=BD?= =?UTF-8?q?=E5=9C=A8=E9=BB=98=E8=AE=A4=E8=BA=AB=E4=BB=BD=E3=80=8D=E7=9A=84?= =?UTF-8?q?=E6=8E=92=E6=9F=A5=E8=AF=B4=E6=98=8E=E5=B9=B6=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E5=89=8D=E7=AB=AF=E5=AD=90=E6=A8=A1=E5=9D=97=EF=BC=88issue=20#?= =?UTF-8?q?288=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 5.3:发起人设定审批人只带人员 id(OperatorKey.ofDefault),不继承发起人身份, 导致「审批人是 admin 却看不到待办」;给出排查顺序与 OperatorKey.of 带身份的写法 - 记录前端接入约定:身份参数只注入 /api/ 前缀的引擎接口,避免污染宿主接口的查询参数解析 --- docs/Integration/operator-identity.md | 21 +++++++++++++++++++++ flow-frontend | 2 +- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md index 2dd6898f..b447f366 100644 --- a/docs/Integration/operator-identity.md +++ b/docs/Integration/operator-identity.md @@ -282,3 +282,24 @@ def run(request) { 示例的 `User.identity` 是 `@Transient`(运行期身份,不落库),由 `FlowOperatorGateway#get(id, identity)` / `findByIds(ids, identity)` 返回带身份的副本。真实项目把身份选项换成自己的组织模型即可。 +### 5.3 常见疑问:为什么「审批人是 admin」却在自己的待办里找不到 + +发起流程时由发起人设定的审批人,目前**只带人员 id、身份为默认身份**(`OperatorKey.ofDefault`), +不会继承发起人当前的身份。于是会出现: + +- 发起人 A 以 `department1` 身份发起,指定审批人 `admin`; +- 该待办落在 **`(admin, 默认身份)`**,而不是 `(admin, department1)`; +- 如果 `admin` 此时界面上停在 `department1`,待办列表按身份过滤后就看不到这条,看起来像「待办丢了」。 + +排查顺序: + +1. 看记录行的「身份」列(或 `currentOperatorIdentity` 字段)确认待办实际归属的身份; +2. 把当前身份切回**默认身份**再看待办; +3. 需要「审批人也带身份」的场景,请通过 `OperatorKey.of(operatorId, identity)` 写入分配数据, + `OperatorLoadStrategy` 会按 `(人员id, 身份)` 批量回查。 + +> 前端接入建议:把当前身份常显在页面(示例工程在待办页顶部有提示条), +> 并且**只把身份参数注入流程引擎接口**(`flow-core` 的 `HttpClient.defaultQueryParamsPathPrefixes` 默认 `/api/`)。 +> 注入到宿主自有接口会污染其查询参数解析,例如基于 `SearchRequest` 的列表接口会抛 +> `Field operatorIdentity not found in class hierarchy`。 + diff --git a/flow-frontend b/flow-frontend index 31f7eea3..4fb6dcc6 160000 --- a/flow-frontend +++ b/flow-frontend @@ -1 +1 @@ -Subproject commit 31f7eea3eff48ffdabca6fec28041b2c1599cc97 +Subproject commit 4fb6dcc669816d40f04fb3d355f49f1ae3460721 From 9dab8a97f4f5dcf60106526b93e0b38cc6d100ea Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Wed, 2 Dec 2026 16:21:21 +0800 Subject: [PATCH 10/35] =?UTF-8?q?feat(identity):=20=E8=BA=AB=E4=BB=BD?= =?UTF-8?q?=E5=8F=AA=E4=BD=9C=E7=94=A8=E4=BA=8E=E8=84=9A=E6=9C=AC=E4=B8=8E?= =?UTF-8?q?=E7=95=99=E7=97=95=EF=BC=8C=E5=8A=9E=E7=90=86=E6=9D=83=E9=99=90?= =?UTF-8?q?=E6=8C=89=E4=BA=BA=E5=91=98=E5=88=A4=E5=AE=9A=EF=BC=88issue=20#?= =?UTF-8?q?297=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 OperatorIdentityMatchMode(STRICT / USER_ONLY)与 OperatorIdentityPolicy,收口审批、撤回、催办、删除、子流程重置、减签、干预留痕、同人自动通过、详情页待审批人匹配等判定 - starter 新增 FlowProperties(codingapi.flow.identity.match-mode,默认 USER_ONLY),启动时由 OperatorIdentityPolicyRegister 写入 framework;framework 默认仍为 STRICT - 查询接口新增 identityScope(ALL / LOCKED,默认 ALL),operatorIdentity 不再隐式过滤,前端携带身份不会导致待办消失 - 文档补充查询范围、判定模式与留痕口径;新增策略与跨身份办理单测 --- docs/Integration/operator-identity.md | 51 ++++- .../src/main/resources/application.properties | 5 + .../action/actions/ReduceAuditAction.java | 14 +- .../exception/FlowValidationException.java | 13 ++ .../flow/manager/WorkflowStrategyManager.java | 12 +- .../codingapi/flow/node/BaseAuditNode.java | 9 +- .../operator/OperatorIdentityMatchMode.java | 49 +++++ .../flow/operator/OperatorIdentityPolicy.java | 104 ++++++++++ .../flow/pojo/response/FlowContent.java | 21 +- .../com/codingapi/flow/record/FlowRecord.java | 7 +- .../flow/service/impl/FlowDeleteService.java | 8 +- .../flow/service/impl/FlowRevokeService.java | 8 +- .../impl/FlowSubProcessResetService.java | 7 +- .../flow/service/impl/FlowUrgeService.java | 7 +- .../operator/OperatorIdentityPolicyTest.java | 63 ++++++ ...peratorIdentityUserOnlyPermissionTest.java | 193 ++++++++++++++++++ .../controller/FlowRecordQueryController.java | 66 +++++- .../com/codingapi/flow/AutoConfiguration.java | 11 + .../flow/properties/FlowProperties.java | 44 ++++ .../OperatorIdentityPolicyRegister.java | 23 +++ .../flow/properties/FlowPropertiesTest.java | 39 ++++ 21 files changed, 698 insertions(+), 56 deletions(-) create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityMatchMode.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityPolicy.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityPolicyTest.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityUserOnlyPermissionTest.java create mode 100644 flow-engine-starter/src/main/java/com/codingapi/flow/properties/FlowProperties.java create mode 100644 flow-engine-starter/src/main/java/com/codingapi/flow/register/OperatorIdentityPolicyRegister.java create mode 100644 flow-engine-starter/src/test/java/com/codingapi/flow/properties/FlowPropertiesTest.java diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md index b447f366..b6a2a3ce 100644 --- a/docs/Integration/operator-identity.md +++ b/docs/Integration/operator-identity.md @@ -194,24 +194,39 @@ def run(request) { 默认身份保持历史格式是刻意的:升级瞬间仍在运行的流程,其存量待办行是旧格式键,若统一改格式会导致新流转算出的键查不到旧行 → 重复生成待办、合并关系断裂。 -### 4.3 查询隔离 +### 4.3 查询范围(默认跨身份,可显式锁定) -待办 / 已办 / 抄送查询按 `(currentOperatorId, currentOperatorIdentity)` 过滤,默认身份的条件写成 `coalesce(identity, '') = ''`,保证历史 NULL 行仍能被查到(否则升级后存量待办会从列表中消失)。 +身份不是权限,同一个人在不同身份下的待办都属于他自己。因此查询默认**按人员 id 返回全部身份**的数据: -**Mock 链路同口径**:带 `mockKey` 的 REST 调用走 `FlowRecordQueryMockService`,三个查询的 `identity` 重载均已实现(待办 / 抄送 / 已办),不会再退化成按 id 全量返回。前端联调与真实库路径行为一致。 +- `/api/query/record/todo|done|notify` 默认不带身份条件,`operatorIdentity` 只作为身份上下文(展示、后续操作),不会隐式改变查询范围; +- 需要「锁定当前身份查看」时显式传 `identityScope=LOCKED`(或 `lockIdentity=true`),此时按 `coalesce(currentOperatorIdentity, '') = :identity` 过滤,历史 NULL 行视为默认身份; +- `identityScope` 只接受 `ALL` / `LOCKED`,其他值在入口即报参数错误,避免拼写错误静默放宽范围。 -### 4.4 判定升级为 `(userId, identity)` +因此宿主始终携带 `operatorIdentity` 也不会导致待办「消失」——这是 issue #297 修正的关键行为。 -以下判定统一由「只比 userId」升级为「比 userId + identity」,身份为空时与历史等价: +**Mock 链路同口径**:带 `mockKey` 的 REST 调用走 `FlowRecordQueryMockService`,待办 / 抄送 / 已办同时保留「跨身份」与「按身份」两套重载,前端联调与真实库路径行为一致。 + +### 4.4 办理权限判定(可配置模式) + +「当前用户能否办理/撤回/催办/减签某条记录」统一由 `OperatorIdentityPolicy` 判定,模式可配置: + +| 模式 | 判定 | 适用 | +|------|------|------| +| `USER_ONLY`(starter 默认) | 只比 `userId` | 身份只服务脚本与留痕,同人换身份可互相办理 | +| `STRICT`(framework 默认) | 比 `userId + identity` | 需要把身份当作独立参与人隔离的场景 | + +覆盖范围(不允许再出现散落的双条件判断): - 审批动作的参与人校验(`WorkflowStrategyManager#verifyOperator`) - 撤销、删除、催办、子流程重置的记录归属校验 -- 加签 / 减签 / 转交 / 委托的人员匹配(`OperatorManager`) +- 减签的目标匹配与「不能减自己」判定 - 提交人 == 审批人的自动通过判定 -- 流程干预人识别 -- 操作者线程缓存与网关缓存的键 -- 详情页 `currentNodeOperators`(待审批人 / 减签候选)的去重与「排除当前操作人」判定 -- 流程树批量登记操作者:按记录里的身份分组回查,与单条读取口径一致(避免 N+1) +- 流程干预人识别(`USER_ONLY` 下同人换身份不算干预) +- 详情页 `currentNodeOperators` 的去重与「排除当前操作人」判定 + +`OperatorManager`、操作者线程缓存、网关缓存的 `(userId, identity)` 键仍保持严格匹配——它们解决的是「取到哪一个带身份的操作者实例」,不是权限问题。 + +留痕口径:被办理记录保留其归属身份(`currentOperatorIdentity`,由取人脚本决定),本次操作携带的身份写入下游新生成记录的 `submitOperatorIdentity`;`USER_ONLY` 下同人换身份不算「被干预」,因此不会写 `interferedOperator*`。 ### 4.5 身份写入约束 @@ -227,6 +242,22 @@ def run(request) { 人员分配表 `t_flow_operator_assignment` **无需改表**:身份编码在 `operatorIds` JSON 列内。全部为默认身份时保持历史格式 `[1,2,3]`;存在非默认身份时写 `[{"operatorId":2,"identity":"department1"}]`,读取端同时兼容两种格式。 +### 4.6 身份匹配模式配置(issue #297) + +配置类 `com.codingapi.flow.properties.FlowProperties` 位于 `flow-engine-starter`,启动时由 `OperatorIdentityPolicyRegister` 写入 framework: + +```properties +# 不限制身份(starter 默认):同一个人换身份仍可办理自己的待办 +codingapi.flow.identity.match-mode=USER_ONLY + +# 严格模式:办理时要求人员与身份都匹配(framework 未配置时的默认值) +# codingapi.flow.identity.match-mode=STRICT +``` + +- 只依赖 `flow-engine-framework`(不使用 starter)的接入方不配置时保持 `STRICT`,升级零感知; +- 通过 starter 接入时默认 `USER_ONLY`,如需恢复 #288 的隔离语义显式配 `STRICT`; +- 模式在启动时生效,不支持运行期热切换(避免同一实例内出现混合判定)。 + ## 5. 兼容性与限制 | 项 | 说明 | diff --git a/flow-engine-example/src/main/resources/application.properties b/flow-engine-example/src/main/resources/application.properties index 4cc12d8c..b804af8e 100644 --- a/flow-engine-example/src/main/resources/application.properties +++ b/flow-engine-example/src/main/resources/application.properties @@ -16,4 +16,9 @@ spring.jpa.properties.hibernate.order_updates=true spring.main.allow-bean-definition-overriding=true codingapi.security.jwt.enable=true +# 身份匹配模式(issue #297): +# USER_ONLY(starter 默认)= 身份只服务脚本与留痕,同一个人换身份仍可办理自己的待办 +# STRICT = 办理时要求人员与身份都匹配(issue #288 的隔离语义) +# codingapi.flow.identity.match-mode=STRICT + codingapi.security.ignore-urls=/open/**,/#/**,/,/**.css,/**.js,/**.svg,/**.png,/**.ico 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 7783e755..14391dbf 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 @@ -14,6 +14,7 @@ import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityPolicy; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.script.node.OperatorLoadScript; import com.codingapi.flow.session.FlowSession; @@ -172,16 +173,17 @@ private List resolveTargetRecords(List targets, for (IFlowOperator target : targets) { long targetOperatorId = target.getUserId(); String targetOperatorIdentity = OperatorIdentity.of(target); - // 自己不能被自己减签:按 (userId, identity) 判断,避免把另一身份的待办当成自己的 - if (targetOperatorId == currentRecord.getCurrentOperatorId() - && OperatorIdentity.same(targetOperatorIdentity, currentRecord.getCurrentOperatorIdentity())) { + // 自己不能被自己减签:按身份匹配策略判断(USER_ONLY 下同人换身份仍视为自己) + if (OperatorIdentityPolicy.matches(target, currentRecord.getCurrentOperatorId(), + currentRecord.getCurrentOperatorIdentity())) { throw FlowExecutionException.reduceAuditOwnRecord(); } - // 减签按「人 + 身份」生效:同一人员的另一个身份仍然是独立参与人,不能被顺带撤销 + // 减签的生效范围同样由策略决定:STRICT 下按「人 + 身份」,USER_ONLY 下按「人」 List matchedRecords = currentNodeRecords.stream() .filter(FlowRecord::isPendingApproval) - .filter(record -> record.getCurrentOperatorId() == targetOperatorId - && OperatorIdentity.same(record.getCurrentOperatorIdentity(), targetOperatorIdentity)) + .filter(record -> OperatorIdentityPolicy.matches( + targetOperatorId, targetOperatorIdentity, + record.getCurrentOperatorId(), record.getCurrentOperatorIdentity())) .toList(); if (matchedRecords.isEmpty()) { throw FlowExecutionException.reduceAuditTargetNotFound(targetOperatorId); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java b/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java index a0ac5ebb..5d94d45d 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java @@ -156,4 +156,17 @@ public static FlowValidationException operatorIdentityInvalid(String illegalChar return new FlowValidationException("validation.operator.identity.invalid", String.format("Operator identity contains an illegal character: %s", illegalCharacter)); } + + /** + * 参数取值不在允许范围内(issue #297,例如 {@code identityScope} 传了未知值) + * + * @param fieldName 参数名 + * @param value 实际取值 + * @param expected 允许的取值说明 + * @return exception + */ + public static FlowValidationException invalidParameter(String fieldName, String value, String expected) { + return new FlowValidationException("validation.parameter." + fieldName, + String.format("Parameter %s has invalid value '%s', expected %s", fieldName, value, expected)); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java index 429b5ddd..d8082837 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java @@ -3,6 +3,7 @@ import com.codingapi.flow.exception.FlowStateException; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityPolicy; import com.codingapi.flow.strategy.workflow.IWorkflowStrategy; import com.codingapi.flow.strategy.workflow.InterfereStrategy; import lombok.AllArgsConstructor; @@ -58,17 +59,18 @@ public void verifyOperator(IFlowOperator currentOperator, long recordOperatorId) /** * 验证操作者。 * - *

    参与人由 {@code (userId, identity)} 共同决定(issue #288):同一个人员的两个身份是 - * 两个不同的参与人,只比 userId 会让 user1 以 department1 的身份操作 department2 的待办。 - * 身份为空时与历史「只比 userId」的行为完全一致。 + *

    是否要求身份一致由 {@link OperatorIdentityPolicy} 决定(issue #297): + *

      + *
    • {@code STRICT}:参与人由 {@code (userId, identity)} 共同决定(issue #288);
    • + *
    • {@code USER_ONLY}:只校验 userId,同一人换身份依然可以办理自己的待办。
    • + *
    * * @param currentOperator 当前操作者 * @param recordOperatorId 记录操作者id * @param recordOperatorIdentity 记录操作者身份标识,{@code null} 与空串等价 */ public void verifyOperator(IFlowOperator currentOperator, long recordOperatorId, String recordOperatorIdentity) { - boolean operatorMatched = recordOperatorId == currentOperator.getUserId() - && OperatorIdentity.same(recordOperatorIdentity, OperatorIdentity.of(currentOperator)); + boolean operatorMatched = OperatorIdentityPolicy.matches(currentOperator, recordOperatorId, recordOperatorIdentity); if (!this.isEnableInterfere()) { if (!operatorMatched) { throw FlowStateException.operatorNotMatch(); 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 256c5ddb..713a5ec4 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 @@ -12,6 +12,7 @@ import com.codingapi.flow.manager.OperatorManager; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityPolicy; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.strategy.node.MultiOperatorAuditStrategy; @@ -262,16 +263,14 @@ private List generateCurrentRecords(FlowSession session, Set // 即当前节点待办记录"处理(resetAddAudit、先清后存等),自动通过的留痕记录落库/事件副作用会破坏其语义。 if (nodeStrategyManager.isSameOperatorAutoPass() && session.getCurrentOperator() != null - && session.getCurrentOperator().getUserId() == session.getSubmitOperatorId() - && OperatorIdentity.same(OperatorIdentity.of(session.getCurrentOperator()), - OperatorIdentity.of(session.getSubmitOperator())) + && OperatorIdentityPolicy.matches(session.getCurrentOperator(), + session.getSubmitOperatorId(), OperatorIdentity.of(session.getSubmitOperator())) && session.getCurrentAction() != null && ActionType.PASS.name().equalsIgnoreCase(session.getCurrentAction().type())) { long submitOperatorId = session.getSubmitOperatorId(); String submitOperatorIdentity = OperatorIdentity.of(session.getSubmitOperator()); operators = operators.stream() - .filter(operator -> operator.getUserId() != submitOperatorId - || !OperatorIdentity.same(OperatorIdentity.of(operator), submitOperatorIdentity)) + .filter(operator -> !OperatorIdentityPolicy.matches(operator, submitOperatorId, submitOperatorIdentity)) .toList(); // 全部审批人均与提交人一致,当前节点自动通过:生成留痕记录并继续向后续节点生成记录(issue #226) if (operators.isEmpty()) { diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityMatchMode.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityMatchMode.java new file mode 100644 index 00000000..08db9d83 --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityMatchMode.java @@ -0,0 +1,49 @@ +package com.codingapi.flow.operator; + +/** + * 身份参与「办理权限」判定的模式(issue #297)。 + * + *

    身份的本质作用是给流程脚本提供上下文(例如 a 身份对应的领导是 L1、b 身份对应 L2), + * 并在流程记录上留痕。它不应该成为「同一个人能否办理自己待办」的拦路石,因此把 + * 「身份是否参与权限判定」抽成可配置项: + *

      + *
    • {@link #STRICT}:{@code userId + identity} 必须同时一致才允许办理(issue #288 的语义,框架默认);
    • + *
    • {@link #USER_ONLY}:只校验 {@code userId},身份仅用于脚本执行与留痕(推荐业务默认)。
    • + *
    + * + *

    模式由 starter 通过 {@code codingapi.flow.identity.match-mode} 配置,并在启动时写入 + * {@link OperatorIdentityPolicy},框架内部所有涉及「能否办理」的判断统一读取该策略。 + * + * @see OperatorIdentityPolicy + */ +public enum OperatorIdentityMatchMode { + + /** + * 严格模式:人员与身份都必须匹配。 + */ + STRICT, + + /** + * 仅人员模式:只要求是同一个人,不限制其当前身份。 + */ + USER_ONLY; + + /** + * 宽松解析配置值,兼容 {@code USER_ONLY}、{@code user-only}、{@code user_only} 等写法。 + * + * @param value 配置值 + * @return 匹配模式,无法识别时返回 {@code null} + */ + public static OperatorIdentityMatchMode parse(String value) { + if (value == null || value.isBlank()) { + return null; + } + String normalized = value.trim().replace('-', '_').toUpperCase(); + for (OperatorIdentityMatchMode mode : values()) { + if (mode.name().equals(normalized)) { + return mode; + } + } + return null; + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityPolicy.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityPolicy.java new file mode 100644 index 00000000..0daaeb7e --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityPolicy.java @@ -0,0 +1,104 @@ +package com.codingapi.flow.operator; + +/** + * 身份匹配策略(issue #297)。 + * + *

    所有「当前用户能否办理/撤回/催办/减签某条流程记录」的判断都必须经过本类, + * 禁止在业务代码里直接写 {@code userId == ... && OperatorIdentity.same(...)}, + * 否则会出现「能审批但不能撤回」「同人换身份被误记为干预」这类半开状态。 + * + *

    默认 {@link OperatorIdentityMatchMode#STRICT},由 starter 在启动时按配置覆盖 + * ({@code codingapi.flow.identity.match-mode},starter 侧默认 {@code USER_ONLY})。 + * 只使用 framework 的接入方不配置时保持历史行为。 + * + * @see OperatorIdentityMatchMode + */ +public final class OperatorIdentityPolicy { + + private static volatile OperatorIdentityMatchMode matchMode = OperatorIdentityMatchMode.STRICT; + + private OperatorIdentityPolicy() { + } + + /** + * 当前生效的匹配模式。 + * + * @return 匹配模式,不为 null + */ + public static OperatorIdentityMatchMode matchMode() { + return matchMode; + } + + /** + * 设置匹配模式,{@code null} 表示回到框架默认(严格模式)。 + * + * @param mode 匹配模式 + */ + public static void setMatchMode(OperatorIdentityMatchMode mode) { + matchMode = mode == null ? OperatorIdentityMatchMode.STRICT : mode; + } + + /** + * 恢复框架默认模式,主要供测试清理静态状态。 + */ + public static void reset() { + matchMode = OperatorIdentityMatchMode.STRICT; + } + + /** + * 当前用户是否就是记录上的参与人(可办理该记录)。 + * + * @param current 当前操作者 + * @param recordOperatorId 记录上的参与人 id + * @param recordOperatorIdentity 记录上的参与人身份 + * @return true 表示允许办理 + */ + public static boolean matches(IFlowOperator current, long recordOperatorId, String recordOperatorIdentity) { + if (current == null) { + return false; + } + return matches(current.getUserId(), OperatorIdentity.of(current), recordOperatorId, recordOperatorIdentity); + } + + /** + * 判断两个 {@code (id, identity)} 是否代表同一个参与人。 + * + *

    {@link OperatorIdentityMatchMode#USER_ONLY} 下只比较 id;{@link OperatorIdentityMatchMode#STRICT} + * 下要求 id 与身份同时一致。 + * + * @param currentOperatorId 当前操作者 id + * @param currentOperatorIdentity 当前操作者身份 + * @param recordOperatorId 记录上的参与人 id + * @param recordOperatorIdentity 记录上的参与人身份 + * @return true 表示匹配 + */ + public static boolean matches(long currentOperatorId, + String currentOperatorIdentity, + long recordOperatorId, + String recordOperatorIdentity) { + if (currentOperatorId != recordOperatorId) { + return false; + } + if (matchMode == OperatorIdentityMatchMode.USER_ONLY) { + return true; + } + return OperatorIdentity.same(currentOperatorIdentity, recordOperatorIdentity); + } + + /** + * 判断两个人员对象是否代表「同一个人」在当前模式下可互相替代。 + * + *

    用于同人自动通过(#224/#226)等「按人合并」的场景:严格模式按人员 + 身份, + * 仅人员模式按人员 id。 + * + * @param left 人员 + * @param right 人员 + * @return true 表示同一参与人 + */ + public static boolean sameOperator(IFlowOperator left, IFlowOperator right) { + if (left == null || right == null) { + return false; + } + return matches(left.getUserId(), OperatorIdentity.of(left), right.getUserId(), OperatorIdentity.of(right)); + } +} 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 e41b8626..33c3f168 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 @@ -9,6 +9,8 @@ import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityMatchMode; +import com.codingapi.flow.operator.OperatorIdentityPolicy; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.workflow.Workflow; @@ -316,16 +318,15 @@ private List loadCurrentNodeOperators(FlowSession flowSession) { /** * 计算当前节点实例中的待审批人员(按参与人去重,排除当前操作人)。 * - *

    参与人由 {@code (人员id, 身份)} 共同标识:同一人员的两个身份是两个人,去重键必须带身份, - * 只按人员 id 去重会把另一个身份吞掉(issue #288 衍生 / #290)。 + *

    去重口径由身份匹配策略决定(issue #297):{@code STRICT} 下参与人由 + * {@code (人员id, 身份)} 共同标识(issue #288 衍生 / #290);{@code USER_ONLY} 下同一个人 + * 只算一个参与人。 * * @param currentRecord 当前流程记录(用于取当前操作人与其身份) * @param currentNodeRecords 当前节点的流程记录 * @return 待审批人员列表(保持记录顺序) */ static List resolveCurrentNodeOperators(FlowRecord currentRecord, List currentNodeRecords) { - long currentOperatorId = currentRecord.getCurrentOperatorId(); - // 同一人员的不同身份是不同参与人,去重键必须是 (人员id, 身份) Map operators = new LinkedHashMap<>(); for (FlowRecord record : currentNodeRecords) { if (record == null || !currentRecord.getProcessId().equals(record.getProcessId())) { @@ -334,12 +335,16 @@ static List resolveCurrentNodeOperators(FlowRecord currentRecord, if (!record.isPendingApproval()) { continue; } - // 排除当前操作人时必须同时比较身份:同一人以另一个身份待审批时仍应出现在列表中 - if (record.getCurrentOperatorId() == currentOperatorId - && OperatorIdentity.same(record.getCurrentOperatorIdentity(), currentRecord.getCurrentOperatorIdentity())) { + // 排除当前操作人时按身份匹配策略判断(issue #297):USER_ONLY 下同一人换身份仍视为本人 + if (OperatorIdentityPolicy.matches(currentRecord.getCurrentOperatorId(), + currentRecord.getCurrentOperatorIdentity(), + record.getCurrentOperatorId(), record.getCurrentOperatorIdentity())) { continue; } - String operatorKey = record.getCurrentOperatorId() + OperatorIdentity.KEY_SEPARATOR + // USER_ONLY 下同一个人只展示一次;STRICT 下按 (人员id, 身份) 区分 + String operatorKey = OperatorIdentityPolicy.matchMode() == OperatorIdentityMatchMode.USER_ONLY + ? String.valueOf(record.getCurrentOperatorId()) + : record.getCurrentOperatorId() + OperatorIdentity.KEY_SEPARATOR + OperatorIdentity.normalize(record.getCurrentOperatorIdentity()); operators.putIfAbsent(operatorKey, new FlowOperator(record.getCurrentOperatorId(), record.getCurrentOperatorName(), diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java index bdfb421e..0bd61ed0 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java @@ -10,6 +10,7 @@ import com.codingapi.flow.node.nodes.NotifyNode; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityPolicy; import com.codingapi.flow.session.FlowAdvice; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; @@ -622,9 +623,9 @@ public void update(FlowSession flowSession, boolean pass) { this.recordState = pass ? SATE_RECORD_DONE : SATE_RECORD_TODO; // 设置流程干预人信息,流程干预只能由流程管理员才能操作。 - // 参与人由 (userId, identity) 共同标识:同一人员以另一个身份办理,同样属于干预(issue #288) - if (flowSession.getCurrentOperator().getUserId() != this.currentOperatorId - || !OperatorIdentity.same(OperatorIdentity.of(flowSession.getCurrentOperator()), this.currentOperatorIdentity)) { + // 是否属于「他人代办」由身份匹配策略决定(issue #297):USER_ONLY 下同一人换身份办理不算干预, + // STRICT 下仍按 (userId, identity) 判定(issue #288)。 + if (!OperatorIdentityPolicy.matches(flowSession.getCurrentOperator(), this.currentOperatorId, this.currentOperatorIdentity)) { this.interferedOperatorId = flowSession.getCurrentOperator().getUserId(); this.interferedOperatorName = flowSession.getCurrentOperator().getName(); this.interferedOperatorIdentity = OperatorIdentity.of(flowSession.getCurrentOperator()); 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 e18f24f5..7504e72a 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 @@ -6,7 +6,7 @@ import com.codingapi.flow.exception.FlowStateException; import com.codingapi.flow.mock.MockRepositoryHolder; import com.codingapi.flow.node.nodes.StartNode; -import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityPolicy; import com.codingapi.flow.pojo.request.FlowDeleteRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.FlowRecordService; @@ -61,9 +61,9 @@ public void delete() { if (afterRecords != null && !afterRecords.isEmpty()) { throw FlowStateException.recordAlreadyRunning(); } - // 权限校验:仅允许当前待办处理人删除;同一人的不同身份是不同参与人(issue #288) - if (currentRecord.getCurrentOperatorId() != request.getOperatorId() - || !OperatorIdentity.same(currentRecord.getCurrentOperatorIdentity(), request.getOperatorIdentity())) { + // 权限校验:仅允许当前待办处理人删除;身份是否参与判定由策略决定(issue #297) + if (!OperatorIdentityPolicy.matches(request.getOperatorId(), request.getOperatorIdentity(), + currentRecord.getCurrentOperatorId(), currentRecord.getCurrentOperatorIdentity())) { throw FlowStateException.operatorNotMatch(); } // 删除流程记录及其关联待办 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 31082bb5..4f64f759 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 @@ -11,7 +11,7 @@ import com.codingapi.flow.manager.NodeStrategyManager; import com.codingapi.flow.mock.MockRepositoryHolder; import com.codingapi.flow.node.IFlowNode; -import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityPolicy; import com.codingapi.flow.pojo.request.FlowRevokeRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.FlowRecordService; @@ -69,9 +69,9 @@ public void revoke() { throw FlowStateException.recordNotSupportRevoke(); } long currentOperatorId = currentRecord.getCurrentOperatorId(); - // 同一人的不同身份是不同参与人:身份也必须一致,否则 user1 可以用 department1 的身份撤回 department2 的办理(issue #288) - if (currentOperatorId != request.getOperatorId() - || !OperatorIdentity.same(currentRecord.getCurrentOperatorIdentity(), request.getOperatorIdentity())) { + // 是否要求身份一致由身份匹配策略决定(issue #297):USER_ONLY 下同一人换身份仍可撤回自己的办理 + if (!OperatorIdentityPolicy.matches(request.getOperatorId(), request.getOperatorIdentity(), + currentOperatorId, currentRecord.getCurrentOperatorIdentity())) { throw FlowStateException.operatorNotMatch(); } WorkflowRuntime workflowRuntime = workflowService.getWorkflowRuntime(currentRecord.getWorkRuntimeId()); 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 48cfa8ec..22ae6e1f 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 @@ -12,7 +12,7 @@ import com.codingapi.flow.mock.MockRepositoryHolder; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; -import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityPolicy; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.request.FlowCreateRequest; import com.codingapi.flow.pojo.request.FlowSubProcessResetRequest; @@ -74,8 +74,9 @@ public void reset() { if (!currentRecord.isTodo()) { throw FlowStateException.recordAlreadyDone(); } - if (currentRecord.getCurrentOperatorId() != request.getOperatorId() - || !OperatorIdentity.same(currentRecord.getCurrentOperatorIdentity(), request.getOperatorIdentity())) { + // issue #297:身份是否参与判定由 OperatorIdentityPolicy 统一控制 + if (!OperatorIdentityPolicy.matches(request.getOperatorId(), request.getOperatorIdentity(), + currentRecord.getCurrentOperatorId(), currentRecord.getCurrentOperatorIdentity())) { throw FlowStateException.operatorNotMatch(); } 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 5cf78f49..3ed3da1d 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 @@ -11,7 +11,7 @@ import com.codingapi.flow.manager.WorkflowStrategyManager; import com.codingapi.flow.mock.MockRepositoryHolder; import com.codingapi.flow.operator.IFlowOperator; -import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityPolicy; import com.codingapi.flow.pojo.request.FlowUrgeRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.FlowRecordService; @@ -62,8 +62,9 @@ public void urge() { } long currentOperatorId = currentRecord.getCurrentOperatorId(); - if (currentOperatorId != request.getOperatorId() - || !OperatorIdentity.same(currentRecord.getCurrentOperatorIdentity(), request.getOperatorIdentity())) { + // issue #297:身份是否参与判定由 OperatorIdentityPolicy 统一控制 + if (!OperatorIdentityPolicy.matches(request.getOperatorId(), request.getOperatorIdentity(), + currentOperatorId, currentRecord.getCurrentOperatorIdentity())) { throw FlowStateException.operatorNotMatch(); } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityPolicyTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityPolicyTest.java new file mode 100644 index 00000000..a7c02ce1 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityPolicyTest.java @@ -0,0 +1,63 @@ +package com.codingapi.flow.operator; + +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 身份匹配策略测试(issue #297)。 + */ +class OperatorIdentityPolicyTest { + + @AfterEach + void tearDown() { + OperatorIdentityPolicy.reset(); + } + + @Test + void should_default_to_strict_mode_for_framework_only_usage() { + assertEquals(OperatorIdentityMatchMode.STRICT, OperatorIdentityPolicy.matchMode()); + assertFalse(OperatorIdentityPolicy.matches( + User.withIdentity(1, "user1", "department1"), 1, "department2")); + } + + @Test + void should_compare_only_user_id_in_user_only_mode() { + OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + + assertTrue(OperatorIdentityPolicy.matches( + User.withIdentity(1, "user1", "department1"), 1, "department2")); + assertTrue(OperatorIdentityPolicy.matches( + User.withIdentity(1, "user1", ""), 1, "department2")); + assertFalse(OperatorIdentityPolicy.matches( + User.withIdentity(2, "boss", "department1"), 1, "department1")); + assertFalse(OperatorIdentityPolicy.matches((IFlowOperator) null, 1, "department1")); + } + + @Test + void should_treat_same_user_as_same_operator_only_when_mode_allows() { + User a = User.withIdentity(1, "user1", "department1"); + User b = User.withIdentity(1, "user1", "department2"); + + assertFalse(OperatorIdentityPolicy.sameOperator(a, b)); + + OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + assertTrue(OperatorIdentityPolicy.sameOperator(a, b)); + assertFalse(OperatorIdentityPolicy.sameOperator(a, new User(2, "boss"))); + } + + @Test + void should_parse_mode_leniently() { + assertEquals(OperatorIdentityMatchMode.USER_ONLY, OperatorIdentityMatchMode.parse("user-only")); + assertEquals(OperatorIdentityMatchMode.USER_ONLY, OperatorIdentityMatchMode.parse(" USER_ONLY ")); + assertEquals(OperatorIdentityMatchMode.STRICT, OperatorIdentityMatchMode.parse("strict")); + assertNull(OperatorIdentityMatchMode.parse(null)); + assertNull(OperatorIdentityMatchMode.parse(" ")); + assertNull(OperatorIdentityMatchMode.parse("unknown")); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityUserOnlyPermissionTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityUserOnlyPermissionTest.java new file mode 100644 index 00000000..a8561f8f --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityUserOnlyPermissionTest.java @@ -0,0 +1,193 @@ +package com.codingapi.flow.service; + +import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.action.actions.CustomAction; +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.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.manager.WorkflowStrategyManager; +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.operator.OperatorIdentityMatchMode; +import com.codingapi.flow.operator.OperatorIdentityPolicy; +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.FlowDeleteRequest; +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.OperatorLoadStrategy; +import com.codingapi.flow.strategy.workflow.InterfereStrategy; +import com.codingapi.flow.user.User; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.WorkflowBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +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 #297)。 + * + *

    身份只用于脚本执行与留痕:同一个人的两个身份不再互相阻断办理; + * 不同的人仍然被拒绝。严格模式的既有语义由 {@link OperatorIdentityPermissionTest} 覆盖。 + */ +class OperatorIdentityUserOnlyPermissionTest { + + private MyFlowServiceFactory factory; + private Workflow workflow; + + @BeforeEach + void setUp() { + OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + + User user1 = User.withIdentity(1, "user1", "department1"); + User boss = new User(2, "boss"); + factory = new MyFlowServiceFactory(); + factory.userGateway.save(user1); + factory.userGateway.save(boss); + GatewayContext.getInstance().setFlowOperatorGateway(factory.userGateway); + + FlowForm form = FlowFormBuilder.builder() + .name("请假流程") + .code("leave-user-only") + .addField("请假人", "name", DataType.STRING) + .build(); + + FormFieldPermissionsBuilder permissions = FormFieldPermissionsBuilder.builder() + .addPermission("leave-user-only", "name", PermissionType.WRITE); + + StartNode startNode = StartNode.builder() + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(permissions.build())) + .build()) + .actions(ActionBuilder.builder() + .addAction(CustomAction.defaultAction()) + .build()) + .build(); + + ApprovalNode approvalNode = ApprovalNode.builder() + .name("经理审批") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(permissions.build())) + .addStrategy(new OperatorLoadStrategy( + FlowGroovyScriptFactory.createOperatorLoadScript("def run(request){return [2]}").getKey())) + .build()) + .build(); + + EndNode endNode = EndNode.builder().build(); + + workflow = WorkflowBuilder.builder() + .title("请假流程") + .code("leave-user-only") + .createdOperator(user1) + .form(form) + .addNode(startNode) + .addNode(approvalNode) + .addNode(endNode) + .build(); + factory.workflowService.saveWorkflow(workflow); + } + + @AfterEach + void tearDown() { + OperatorIdentityPolicy.reset(); + } + + private Map formData() { + return Map.of("name", "lorne"); + } + + private List startActions() { + return workflow.getStartNode().actionManager().getActions(); + } + + private long createFlow(String operatorIdentity) { + FlowCreateRequest request = new FlowCreateRequest(); + request.setWorkCode(workflow.getCode()); + request.setFormData(formData()); + request.setActionId(startActions().get(0).id()); + request.setOperatorId(1); + request.setOperatorIdentity(operatorIdentity); + return factory.flowService.create(request); + } + + private void action(long recordId, long operatorId, String operatorIdentity) { + FlowActionRequest actionRequest = new FlowActionRequest(); + actionRequest.setFormData(formData()); + actionRequest.setRecordId(recordId); + FlowAdviceBody advice = new FlowAdviceBody(startActions().get(0).id(), "同意", operatorId); + advice.setOperatorIdentity(operatorIdentity); + actionRequest.setAdvice(advice); + factory.flowService.action(actionRequest); + } + + /** + * 单元层面:USER_ONLY 下只比人员,忽略身份;换一个人仍然拒绝。 + */ + @Test + void should_match_only_user_id_in_user_only_mode() { + WorkflowStrategyManager manager = new WorkflowStrategyManager(List.of(new InterfereStrategy())); + + assertDoesNotThrow(() -> manager.verifyOperator(User.withIdentity(1, "user1", "department1"), 1, "department2")); + assertDoesNotThrow(() -> manager.verifyOperator(User.withIdentity(1, "user1", "department2"), 1, "")); + assertThrows(FlowStateException.class, + () -> manager.verifyOperator(User.withIdentity(2, "boss", "department1"), 1, "department1")); + } + + /** + * 审批:同一人换身份可以办理自己的待办,且本次操作身份被留痕到后续记录。 + */ + @Test + void should_allow_action_with_other_identity_and_record_submit_identity() { + long recordId = createFlow("department1"); + FlowRecord record = factory.flowRecordRepository.get(recordId); + assertEquals("department1", record.getCurrentOperatorIdentity()); + + assertDoesNotThrow(() -> action(recordId, 1, "department2")); + assertFalse(factory.flowRecordRepository.get(recordId).isTodo(), "同人换身份办理后应已办结"); + + List bossTodos = factory.flowRecordRepository.findTodoByOperator(2); + assertEquals(1, bossTodos.size()); + assertEquals("department2", bossTodos.get(0).getSubmitOperatorIdentity(), + "提交人身份应记录本次操作携带的身份"); + } + + /** + * 审批:其他人以任何身份都不能办理不属于自己的待办。 + */ + @Test + void should_reject_other_user_in_user_only_mode() { + long recordId = createFlow("department1"); + + assertThrows(FlowStateException.class, () -> action(recordId, 2, "department1")); + assertTrue(factory.flowRecordRepository.get(recordId).isTodo()); + } + + /** + * 删除:同一人换身份可以删除自己的待办。 + */ + @Test + void should_allow_delete_with_other_identity() { + long recordId = createFlow("department1"); + + assertDoesNotThrow(() -> factory.flowService.delete(new FlowDeleteRequest(recordId, 1, "department2"))); + } +} diff --git a/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java b/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java index 353abddf..7093e1b5 100644 --- a/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java +++ b/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java @@ -55,10 +55,13 @@ private long loadCurrentOperatorId(){ } /** - * 当前操作人身份标识(issue #288)。 + * 当前操作人身份标识(issue #288 / #297)。 * - *

    优先取请求参数 {@code operatorIdentity}(宿主可通过它声明「我以哪个身份查看」), + *

    优先取请求参数 {@code operatorIdentity}(宿主声明「我以哪个身份操作/查看」), * 其次取当前登录操作者自身的身份,都为空时表示默认身份。 + * + *

    该值只作为身份上下文使用:它不会隐式改变查询范围——查询是否按身份过滤由 + * {@code identityScope} 显式控制,因此宿主始终携带它也不会导致待办「消失」。 */ private String loadCurrentOperatorIdentity(){ ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); @@ -76,6 +79,41 @@ private String loadCurrentOperatorIdentity(){ } + /** + * 查询身份范围参数(issue #297)。 + * + *

    查询默认不按身份过滤:身份只用于脚本与留痕,同一个人在不同身份下的待办都属于他自己。 + * 需要「锁定当前身份查看」时显式传 {@code identityScope=LOCKED}(或 {@code lockIdentity=true})。 + */ + private static final String IDENTITY_SCOPE_PARAM = "identityScope"; + private static final String IDENTITY_SCOPE_ALL = "ALL"; + private static final String IDENTITY_SCOPE_LOCKED = "LOCKED"; + private static final String LOCK_IDENTITY_PARAM = "lockIdentity"; + + /** + * 是否锁定身份查询。 + * + *

    注意:{@code operatorIdentity} 只表示「本次操作/查看的身份上下文」, + * 不再隐式决定查询范围。宿主仍然可以一直携带它,不会影响返回结果。 + */ + private boolean isIdentityLocked() { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + String scope = request.getParameter(IDENTITY_SCOPE_PARAM); + if (!StringUtils.hasText(scope)) { + return "true".equalsIgnoreCase(request.getParameter(LOCK_IDENTITY_PARAM)); + } + String normalized = scope.trim().toUpperCase(); + if (IDENTITY_SCOPE_ALL.equals(normalized)) { + return false; + } + if (IDENTITY_SCOPE_LOCKED.equals(normalized)) { + return true; + } + throw FlowValidationException.invalidParameter(IDENTITY_SCOPE_PARAM, scope, + IDENTITY_SCOPE_ALL + " / " + IDENTITY_SCOPE_LOCKED); + } + /** * 全部流程记录接口 */ @@ -89,39 +127,57 @@ public MultiResponse list(SearchRequest request) { /** * 我的待办记录 + * + *

    默认返回当前用户全部身份的待办;{@code identityScope=LOCKED} 时只返回指定身份的待办。 */ @GetMapping("/todo") public MultiResponse todo(SearchRequest request) { long operatorId = loadCurrentOperatorId(); + boolean identityLocked = isIdentityLocked(); String operatorIdentity = loadCurrentOperatorIdentity(); FlowRecordQueryService flowRecordQueryService = loadFlowService(); PageRequest pageRequest = PageRequest.of(request.getCurrent(), request.getPageSize()).withSort(Sort.by("id").descending()); - return MultiResponse.of(flowRecordQueryService.findTodoRecordPage(operatorId,operatorIdentity,pageRequest)); + if (identityLocked) { + return MultiResponse.of(flowRecordQueryService.findTodoRecordPage(operatorId, operatorIdentity, pageRequest)); + } + return MultiResponse.of(flowRecordQueryService.findTodoRecordPage(operatorId, pageRequest)); } /** * 我的抄送记录 + * + *

    默认返回当前用户全部身份的抄送;{@code identityScope=LOCKED} 时只返回指定身份的抄送。 */ @GetMapping("/notify") public MultiResponse notify(SearchRequest request) { long operatorId = loadCurrentOperatorId(); + boolean identityLocked = isIdentityLocked(); String operatorIdentity = loadCurrentOperatorIdentity(); FlowRecordQueryService flowRecordQueryService = loadFlowService(); PageRequest pageRequest = PageRequest.of(request.getCurrent(), request.getPageSize()).withSort(Sort.by("id").descending()); - return MultiResponse.of(flowRecordQueryService.findNotifyRecordPage(operatorId,operatorIdentity,pageRequest)); + if (identityLocked) { + return MultiResponse.of(flowRecordQueryService.findNotifyRecordPage(operatorId, operatorIdentity, pageRequest)); + } + return MultiResponse.of(flowRecordQueryService.findNotifyRecordPage(operatorId, pageRequest)); } /** * 我的已办记录 + * + *

    默认返回当前用户全部身份的已办;{@code identityScope=LOCKED} 时只返回指定身份的已办。 */ @GetMapping("/done") public MultiResponse done(SearchRequest request) { long operatorId = loadCurrentOperatorId(); + boolean identityLocked = isIdentityLocked(); String operatorIdentity = loadCurrentOperatorIdentity(); FlowRecordQueryService flowRecordQueryService = loadFlowService(); PageRequest pageRequest = PageRequest.of(request.getCurrent(), request.getPageSize()).withSort(Sort.by("id").descending()); - return MultiResponse.of(flowRecordQueryService.findDoneRecordPage(operatorId,operatorIdentity,pageRequest)); + if (identityLocked) { + return MultiResponse.of(flowRecordQueryService.findDoneRecordPage(operatorId, operatorIdentity, pageRequest)); + } + return MultiResponse.of(flowRecordQueryService.findDoneRecordPage(operatorId, pageRequest)); } /** 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 4e391145..3b4624d1 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 @@ -4,7 +4,9 @@ import com.codingapi.flow.event.IFlowEventPublisher; import com.codingapi.flow.event.SpringFlowEventPublisher; import com.codingapi.flow.gateway.FlowOperatorGateway; +import com.codingapi.flow.properties.FlowProperties; import com.codingapi.flow.register.NodeViewJavaScriptCacheContextRegister; +import com.codingapi.flow.register.OperatorIdentityPolicyRegister; import com.codingapi.flow.register.RepositoryHolderContextRegister; import com.codingapi.flow.register.FlowScriptContextRegister; import com.codingapi.flow.register.GatewayContextRegister; @@ -15,14 +17,23 @@ import com.codingapi.flow.service.WorkflowService; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration +@EnableConfigurationProperties(FlowProperties.class) public class AutoConfiguration { + /** + * 身份匹配策略:启动时把 {@code codingapi.flow.identity.match-mode} 写入 framework(issue #297)。 + */ + @Bean + public OperatorIdentityPolicyRegister operatorIdentityPolicyRegister(FlowProperties flowProperties) { + return new OperatorIdentityPolicyRegister(flowProperties); + } @Bean public NodeViewJavaScriptCacheContextRegister nodeViewJavaScriptCacheContextRegister(NodeViewJavaScriptRepository nodeViewJavaScriptRepository){ return new NodeViewJavaScriptCacheContextRegister(nodeViewJavaScriptRepository); diff --git a/flow-engine-starter/src/main/java/com/codingapi/flow/properties/FlowProperties.java b/flow-engine-starter/src/main/java/com/codingapi/flow/properties/FlowProperties.java new file mode 100644 index 00000000..45ccab8b --- /dev/null +++ b/flow-engine-starter/src/main/java/com/codingapi/flow/properties/FlowProperties.java @@ -0,0 +1,44 @@ +package com.codingapi.flow.properties; + +import com.codingapi.flow.operator.OperatorIdentityMatchMode; +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * 流程引擎配置(issue #297)。 + * + *

    配置前缀 {@code codingapi.flow},启动时由 {@code AutoConfiguration} 写入框架层的 + * {@link com.codingapi.flow.operator.OperatorIdentityPolicy}。 + * + *

    示例({@code application.properties}): + *

    + * # 不限制身份模式(默认):同一个人换身份仍可办理自己的待办
    + * codingapi.flow.identity.match-mode=USER_ONLY
    + * # 严格模式:办理时要求人员与身份都匹配
    + * codingapi.flow.identity.match-mode=STRICT
    + * 
    + */ +@Getter +@Setter +@ConfigurationProperties(prefix = "codingapi.flow") +public class FlowProperties { + + /** + * 身份相关配置 + */ + private Identity identity = new Identity(); + + @Getter + @Setter + public static class Identity { + + /** + * 身份匹配模式,默认 {@link OperatorIdentityMatchMode#USER_ONLY}。 + * + *

    身份只用于脚本执行与留痕,不作为「同一个人能否办理自己待办」的限制。 + * 如需恢复 #288 的严格语义(人员 + 身份都必须一致),显式配置为 {@code STRICT}。 + */ + private OperatorIdentityMatchMode matchMode = OperatorIdentityMatchMode.USER_ONLY; + } +} diff --git a/flow-engine-starter/src/main/java/com/codingapi/flow/register/OperatorIdentityPolicyRegister.java b/flow-engine-starter/src/main/java/com/codingapi/flow/register/OperatorIdentityPolicyRegister.java new file mode 100644 index 00000000..78b9d27e --- /dev/null +++ b/flow-engine-starter/src/main/java/com/codingapi/flow/register/OperatorIdentityPolicyRegister.java @@ -0,0 +1,23 @@ +package com.codingapi.flow.register; + +import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.properties.FlowProperties; +import lombok.AllArgsConstructor; +import org.springframework.beans.factory.InitializingBean; + +/** + * 把 Spring 配置里的身份匹配模式写入框架层(issue #297)。 + * + *

    framework 不依赖 Spring,模式只能通过 {@link OperatorIdentityPolicy} 的静态持有者传递; + * 本注册器在容器启动时完成注入,与 {@link GatewayContextRegister} 的初始化方式保持一致。 + */ +@AllArgsConstructor +public class OperatorIdentityPolicyRegister implements InitializingBean { + + private final FlowProperties flowProperties; + + @Override + public void afterPropertiesSet() { + OperatorIdentityPolicy.setMatchMode(flowProperties.getIdentity().getMatchMode()); + } +} diff --git a/flow-engine-starter/src/test/java/com/codingapi/flow/properties/FlowPropertiesTest.java b/flow-engine-starter/src/test/java/com/codingapi/flow/properties/FlowPropertiesTest.java new file mode 100644 index 00000000..8d1ae86a --- /dev/null +++ b/flow-engine-starter/src/test/java/com/codingapi/flow/properties/FlowPropertiesTest.java @@ -0,0 +1,39 @@ +package com.codingapi.flow.properties; + +import com.codingapi.flow.operator.OperatorIdentityMatchMode; +import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.register.OperatorIdentityPolicyRegister; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * starter 配置默认值与注册器测试(issue #297)。 + * + *

    starter 是业务接入的默认入口,默认不限制身份;框架自身的默认值仍是严格模式, + * 两者通过 {@link OperatorIdentityPolicyRegister} 在启动时衔接。 + */ +class FlowPropertiesTest { + + @AfterEach + void tearDown() { + OperatorIdentityPolicy.reset(); + } + + @Test + void should_default_to_user_only_mode() { + FlowProperties properties = new FlowProperties(); + assertEquals(OperatorIdentityMatchMode.USER_ONLY, properties.getIdentity().getMatchMode()); + } + + @Test + void should_apply_configured_mode_to_framework() { + FlowProperties properties = new FlowProperties(); + properties.getIdentity().setMatchMode(OperatorIdentityMatchMode.STRICT); + + new OperatorIdentityPolicyRegister(properties).afterPropertiesSet(); + + assertEquals(OperatorIdentityMatchMode.STRICT, OperatorIdentityPolicy.matchMode()); + } +} From b6531c0f60dd0388d47c2f5bc604e2a8e1b4b0d9 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Wed, 2 Dec 2026 16:31:36 +0800 Subject: [PATCH 11/35] =?UTF-8?q?chore(example):=20=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E5=89=8D=E7=AB=AF=E5=AD=90=E6=A8=A1=E5=9D=97=EF=BC=88=E8=BA=AB?= =?UTF-8?q?=E4=BB=BD=E6=8F=90=E7=A4=BA=E6=94=B9=E4=B8=BA=E6=93=8D=E4=BD=9C?= =?UTF-8?q?=E8=BA=AB=E4=BB=BD=E5=8F=A3=E5=BE=84=EF=BC=8Cissue=20#297?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- flow-frontend | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flow-frontend b/flow-frontend index 4fb6dcc6..a1edbccb 160000 --- a/flow-frontend +++ b/flow-frontend @@ -1 +1 @@ -Subproject commit 4fb6dcc669816d40f04fb3d355f49f1ae3460721 +Subproject commit a1edbccb8a096d4cd2a04aefa7851e08d44ed1c7 From 9d8796ecb1ed243692ed86f314f3d668781e2b15 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Wed, 2 Dec 2026 16:36:53 +0800 Subject: [PATCH 12/35] =?UTF-8?q?docs(identity):=20=E7=A4=BA=E4=BE=8B?= =?UTF-8?q?=E9=AA=8C=E8=AF=81=E6=AD=A5=E9=AA=A4=E6=94=B9=E4=B8=BA=E8=B7=A8?= =?UTF-8?q?=E8=BA=AB=E4=BB=BD=E5=8F=A3=E5=BE=84=E5=B9=B6=E8=A1=A5=E5=85=85?= =?UTF-8?q?=E7=A7=BB=E5=8A=A8=E7=AB=AF=E5=85=A5=E5=8F=A3=EF=BC=88issue=20#?= =?UTF-8?q?297=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/Integration/operator-identity.md | 35 ++++++++++++++++++--------- flow-frontend | 2 +- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md index b6a2a3ce..bce46422 100644 --- a/docs/Integration/operator-identity.md +++ b/docs/Integration/operator-identity.md @@ -282,6 +282,10 @@ codingapi.flow.identity.match-mode=USER_ONLY | 处置存量待办 | 记录身份为默认身份,当前身份 != 默认身份 → 判权不通过,操作被拒绝 | | 待办合并 | 旧格式键(无 `#identity`)与新键不互通,不会合并到同一条待办 | +> 上表是 `STRICT` 模式下的表现。**starter 默认的 `USER_ONLY`(issue #297)下前两条不成立**: +> 列表按人员跨身份返回、判权只比人员,因此打开身份不需要过渡窗口;只有显式配置 `STRICT` +> 或查询传 `identityScope=LOCKED` 时才回到上表口径(详见 4.3 / 4.6)。 + **因此不要在全量用户上一次性打开身份。** 推荐三种过渡方式: 1. **只对新流程启用**:存量在途流程继续以默认身份办结,新流程带身份发起(最省事,推荐); @@ -292,8 +296,8 @@ codingapi.flow.identity.match-mode=USER_ONLY ### 5.2 示例工程如何验证 -`flow-engine-example` + `flow-frontend` 的 `apps/app-pc` 已打通端到端验证,**首次启动会自动生成一套演示数据** -(`IdentityDemoInitializer`,流程编码 `identity-demo`,已有该流程时跳过,不重复造数): +`flow-engine-example` + `flow-frontend` 的 `apps/app-pc`(PC)与 `apps/app-mobile`(移动端)都已打通端到端验证, +**首次启动会自动生成一套演示数据**(`IdentityDemoInitializer`,流程编码 `identity-demo`,已有该流程时跳过,不重复造数): | 账号 | 密码 | 待办(审批人 · 身份) | |------|------|----------------------| @@ -301,35 +305,44 @@ codingapi.flow.identity.match-mode=USER_ONLY | `user2`(李四) | `123456` | 李四 · `department2` | | `admin` | `admin` | 无(三条流程的发起人) | -验证步骤: +验证步骤(`USER_ONLY` 默认模式): 1. 启动后端:`cd flow-engine-example && mvn -o spring-boot:run`(端口 8090); -2. 启动前端:`cd flow-frontend && pnpm -F @flow-example/app-pc dev`(开发服务器已把 `/api` 代理到 8090); -3. 用 `user1` / `123456` 登录 → 「待办中心」:默认身份下只有 1 条待办,「身份」列为「默认身份」; -4. 页面右下角「身份切换(演示)」输入 `department1` → 切换(页面自动刷新):待办变成另一条,「身份」列显示 `department1`; -5. 切到 `department2`:待办为空——那是 `user2` 的待办,验证「同一人不同身份、不同人不同身份」都不串; -6. 用错误身份点「办理」会被拒绝(`state.operator.notMatch`),用匹配身份才能审批通过。 +2. 启动前端:`cd flow-frontend && pnpm -F @flow-example/app-pc dev`(PC,代理 `/api` 到 8090) + 或 `pnpm -F @flow-example/app-mobile dev`(移动端,端口 3002); +3. 用 `user1` / `123456` 登录 → 「待办中心」:**2 条待办同时出现**(「身份」列分别为「默认身份」和 `department1`), + 说明列表默认跨身份; +4. 切换操作身份(PC 为右下角「操作身份(演示)」卡片,移动端为待办页顶部「操作身份」横条)→ 页面自动刷新: + **待办条数不变**,因为身份不影响可见范围;仅本次操作携带的身份变化; +5. 用 `department1` 身份去审批那条落在「默认身份」上的待办 → **可以办理**(`USER_ONLY` 只比人员); + 办理后新记录的 `submitOperatorIdentity` 记录本次操作身份; +6. 想验证 #288 的严格隔离语义:配置 `codingapi.flow.identity.match-mode=STRICT`,查询时传 + `identityScope=LOCKED`,此时步骤 4 才会变成「只显示当前身份下的记录」,跨身份办理也会被拒绝 + (`state.operator.notMatch`)。 示例的 `User.identity` 是 `@Transient`(运行期身份,不落库),由 `FlowOperatorGateway#get(id, identity)` / `findByIds(ids, identity)` 返回带身份的副本。真实项目把身份选项换成自己的组织模型即可。 ### 5.3 常见疑问:为什么「审批人是 admin」却在自己的待办里找不到 +> 默认 `USER_ONLY` + 跨身份查询下**不会再出现**这个问题,本节保留给 `STRICT` 模式与 `identityScope=LOCKED` 的场景。 + 发起流程时由发起人设定的审批人,目前**只带人员 id、身份为默认身份**(`OperatorKey.ofDefault`), 不会继承发起人当前的身份。于是会出现: - 发起人 A 以 `department1` 身份发起,指定审批人 `admin`; - 该待办落在 **`(admin, 默认身份)`**,而不是 `(admin, department1)`; -- 如果 `admin` 此时界面上停在 `department1`,待办列表按身份过滤后就看不到这条,看起来像「待办丢了」。 +- 在 `STRICT` 模式或锁定身份的查询下,如果 `admin` 此时界面上停在 `department1`,就会看不到这条, + 看起来像「待办丢了」。 排查顺序: 1. 看记录行的「身份」列(或 `currentOperatorIdentity` 字段)确认待办实际归属的身份; -2. 把当前身份切回**默认身份**再看待办; +2. 去掉 `identityScope=LOCKED`(默认就是跨身份)或把当前身份切回**默认身份**再看待办; 3. 需要「审批人也带身份」的场景,请通过 `OperatorKey.of(operatorId, identity)` 写入分配数据, `OperatorLoadStrategy` 会按 `(人员id, 身份)` 批量回查。 -> 前端接入建议:把当前身份常显在页面(示例工程在待办页顶部有提示条), +> 前端接入建议:把当前**操作身份**常显在页面上(示例 PC 在右下角卡片、移动端在待办页顶部横条), > 并且**只把身份参数注入流程引擎接口**(`flow-core` 的 `HttpClient.defaultQueryParamsPathPrefixes` 默认 `/api/`)。 > 注入到宿主自有接口会污染其查询参数解析,例如基于 `SearchRequest` 的列表接口会抛 > `Field operatorIdentity not found in class hierarchy`。 diff --git a/flow-frontend b/flow-frontend index a1edbccb..775d07b0 160000 --- a/flow-frontend +++ b/flow-frontend @@ -1 +1 @@ -Subproject commit a1edbccb8a096d4cd2a04aefa7851e08d44ed1c7 +Subproject commit 775d07b0481c98d1423744a396f9d0f7ceef1150 From bf841cbf8b42f155a9abf7c9639f5c6386d47854 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Wed, 2 Dec 2026 16:51:27 +0800 Subject: [PATCH 13/35] =?UTF-8?q?docs(identity):=20=E5=85=A8=E9=87=8F?= =?UTF-8?q?=E5=AF=B9=E9=BD=90=E8=BA=AB=E4=BB=BD=E7=9B=B8=E5=85=B3=E6=96=87?= =?UTF-8?q?=E6=A1=A3=E4=B8=8E=E4=BB=A3=E7=A0=81=E7=8E=B0=E7=8A=B6=EF=BC=88?= =?UTF-8?q?issue=20#297=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - operator-identity:补查询范围(identityScope)、判定模式(USER_ONLY/STRICT)口径,修正过渡建议与 3.3 请求示例,补充自定义 FlowRecordQueryService 未覆盖身份重载会导致 LOCKED 静默退化 - rest-api:补 operatorIdentity 解析规则、查询身份范围参数表、FlowRecordQueryService 身份重载说明 - auto-configuration:补 OperatorIdentityPolicyRegister 与 SpringFlowEventPublisher、配置项 codingapi.flow.identity.match-mode,修正条件注解描述 - capabilities/gateway-context:补多身份需覆盖的网关 default 重载 - Integration/README:更新文档索引描述与 Bean/Register 数量 --- docs/Integration/README.md | 4 +- docs/Integration/auto-configuration.md | 14 ++++++- docs/Integration/operator-identity.md | 37 ++++++++++++++----- docs/Integration/rest-api.md | 36 ++++++++++++++++-- .../flow-engine-framework/gateway-context.md | 4 ++ 5 files changed, 78 insertions(+), 17 deletions(-) diff --git a/docs/Integration/README.md b/docs/Integration/README.md index e1be4345..90d02763 100644 --- a/docs/Integration/README.md +++ b/docs/Integration/README.md @@ -31,11 +31,11 @@ |------|------| | [快速开始](./quick-start.md) | 最小集成步骤:引入依赖 → 提供 Bean → 编写流程 → 发起流程 | | [流程用户体系](./user-integration.md) | `FlowOperatorGateway` / `IFlowOperator` / `GatewayContext` / 线程缓存 / 当前登录人 | -| [多身份参与](./operator-identity.md) | 同一人员多身份:身份 SPI、请求声明、待办隔离、判定规则、升级 DDL | +| [多身份参与](./operator-identity.md) | 同一人员多身份:身份 SPI、请求声明、查询范围、判定模式(`USER_ONLY`/`STRICT`)、升级 DDL | | [流程默认脚本](./script-integration.md) | 12 种脚本类型、`GroovyScriptRequest` 完整 API、`$bind`、默认脚本替换、脚本生命周期 | | [流程事件机制](./event-integration.md) | 9 种事件、`EventPusher`、`IHandler` 订阅、异步分发管道、事务变体、推送时机 | | [仓储抽象与持久化](./repository-integration.md) | `IRepositoryHolder`、12 个仓储接口(含 11 个 JPA 实现 + 需自行实现的 `NodeViewJavaScriptRepository`)、脚本仓储、锁机制 | -| [Spring Boot 自动配置](./auto-configuration.md) | `AutoConfiguration` 8 个 Bean、4 个 Register、必选/可选 Bean 清单 | +| [Spring Boot 自动配置](./auto-configuration.md) | `AutoConfiguration` 10 个 Bean、5 个 Register、必选/可选 Bean 清单、配置项 | | [REST API](./rest-api.md) | 5 个 Controller、`mockKey`/`operatorId` 分流机制、请求/响应结构 | | [Mock 模式](./mock-mode.md) | 全内存沙箱 `MockInstance`、15 分钟过期、接入方式 | | [节点/动作/策略扩展](./extension-points.md) | 19 种节点 × 9 种动作 × 15 种节点策略 × 2 种流程策略,扩展方式 | diff --git a/docs/Integration/auto-configuration.md b/docs/Integration/auto-configuration.md index ed34ff7f..6c46e192 100644 --- a/docs/Integration/auto-configuration.md +++ b/docs/Integration/auto-configuration.md @@ -9,16 +9,20 @@ - `META-INF/spring.factories` → `EnableAutoConfiguration=com.codingapi.flow.AutoConfiguration` - `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports` → `com.codingapi.flow.AutoConfiguration` -`AutoConfiguration` 为 `@Configuration`,**无 `@ConditionalOnMissingBean`、无条件注解** —— 构造函数依赖的 Bean 缺失将导致启动失败。 +`AutoConfiguration` 为 `@Configuration` + `@EnableConfigurationProperties(FlowProperties.class)`(issue #297 起)。 +除 `SpringFlowEventPublisher`(带 `@ConditionalOnMissingBean` / `@ConditionalOnProperty`)外**无条件注解** —— +所需 Bean 缺失将导致启动失败。 ## 2. 注册的 Bean 全清单 | @Bean | 依赖 | 作用 | |---|---|---| +| `OperatorIdentityPolicyRegister` | `FlowProperties` | 启动时把 `codingapi.flow.identity.match-mode` 写入 framework 的 `OperatorIdentityPolicy`(issue #297) | | `NodeViewJavaScriptCacheContextRegister` | **`NodeViewJavaScriptRepository`** | 构造器内执行 `NodeViewJavaScriptCacheContext.getInstance().setNodeViewJavaScriptRepository(repo)`(15 分钟缓存上下文) | | `GatewayContextRegister` | **`FlowOperatorGateway`** | 把操作人网关灌入 `GatewayContext` 单例(`InitializingBean`) | | `FlowScriptContextRegister` | `ApplicationContext` + **`FlowOperatorGateway`** + `FlowRecordRepository` | 给 `FlowScriptContext` 单例设置 `IBeanFactory`(转发 Spring 容器,脚本 `$bind` 依赖) | | `RepositoryHolderContextRegister` | `WorkflowService` + `FlowRecordService` + 6 个仓储 + `GatewayContextRegister` | 把 8 个依赖灌入 `RepositoryHolderContext` 单例(`InitializingBean`) | +| `SpringFlowEventPublisher` | `ApplicationContext` | 事务提交后投递 + 按流程 id 分区串行(可用 `codingapi.flow.event.ordered=false` 关闭,关闭后回退事件框架直投) | | `FlowRecordService` | `FlowTodoRecordRepository` + `FlowTodoMergeRepository` + `FlowRecordRepository` | 记录服务 Bean | | `WorkflowService` | `WorkflowVersionRepository` + `WorkflowRepository` + `WorkflowRuntimeRepository` | 流程设计服务 Bean | | `FlowService` | `RepositoryHolderContextRegister`(仅保证顺序) | `new FlowService(RepositoryHolderContext.getInstance())`,业务入口 | @@ -29,6 +33,13 @@ 全部位于 `flow-engine-starter/src/main/java/com/codingapi/flow/register/`,均实现 `InitializingBean`: ```java +// OperatorIdentityPolicyRegister(issue #297) +@Override +public void afterPropertiesSet() { + // framework 不依赖 Spring,模式通过静态持有者传递 + OperatorIdentityPolicy.setMatchMode(flowProperties.getIdentity().getMatchMode()); +} + // GatewayContextRegister @Override public void afterPropertiesSet() { @@ -89,6 +100,7 @@ public void afterPropertiesSet() { | 配置前缀 | 作用 | |---|---| +| `codingapi.flow.identity.match-mode` | 身份匹配模式:`USER_ONLY`(starter 默认,办理只比人员)/ `STRICT`(人员+身份,framework 默认)。启动时生效,不支持热切换(issue #297) | | `codingapi.script.tempValidTime` | 临时脚本有效期(默认 15 分钟) | | `codingapi.script.shellMaxCacheSize` | 脚本编译缓存上限(默认 10240) | | `codingapi.framework.handler-thread-pool-size` | 异步事件线程池大小(默认 20) | diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md index bce46422..d661a73e 100644 --- a/docs/Integration/operator-identity.md +++ b/docs/Integration/operator-identity.md @@ -1,6 +1,8 @@ # 多身份参与(Operator Identity) -> 面向业务项目的集成说明,对应 issue #288。引擎只负责**透传、存储与比较**身份标识,不解释其业务语义,也不内建组织模型。 +> 面向业务项目的集成说明,对应 issue #288(身份标识)与 issue #297(身份语义收口)。 +> 引擎只负责**透传、存储与比较**身份标识,不解释其业务语义,也不内建组织模型。 +> 身份**默认不作为办理权限**:它服务脚本与留痕,不阻断「同一个人办理自己的待办」(见 4.4 / 4.6)。 ## 1. 解决什么问题 @@ -20,7 +22,8 @@ 1. 从 `IFlowOperator#getIdentity()` 读取; 2. 落库到流程记录与待办; -3. 在判定时按 `(userId, identity)` 比较; +3. 在需要区分参与人时按 `(userId, identity)` 比较——**是否把身份作为「能否办理」的条件由匹配模式决定** + (默认只比 `userId`,见 4.4 / 4.6); 4. 透传给 Groovy 脚本与 REST 响应。 约定:`null` 与空串等价,均表示**默认身份**(`OperatorIdentity.DEFAULT`)。未启用多身份的业务、以及 0.3.0 之前的历史数据,全部落在默认身份上,行为与历史完全一致。 @@ -97,15 +100,19 @@ public IFlowOperator get(long id, String identity) { ### 3.3 请求声明身份 -REST 接口支持 `operatorIdentity` 参数(与 `operatorId` 对称):未传时取当前登录操作者的身份。 +REST 接口支持 `operatorIdentity` 参数(与 `operatorId` 对称):未传时取当前登录操作者的身份;若同时用 `operatorId` +覆盖了人员,身份归默认身份(避免出现「人员与身份错配」的副本)。 ```bash -# 以 department1 的身份发起 +# 以 department1 的身份发起(身份随记录落库:create_operator_identity) curl -X POST 'http://host/api/cmd/record/create?operatorIdentity=department1' \ -H 'Content-Type: application/json' -d '{...}' -# 以 department1 的身份查看待办 +# 查看待办:默认跨身份,operatorIdentity 只是「本次操作身份」上下文,不影响返回范围 curl 'http://host/api/query/record/todo?operatorId=1&operatorIdentity=department1' + +# 只想看「落在 department1 下」的待办时,显式锁定身份(见 4.3) +curl 'http://host/api/query/record/todo?operatorId=1&operatorIdentity=department1&identityScope=LOCKED' ``` 编程式 API 中对应各请求对象的 `operatorIdentity` 字段: @@ -121,9 +128,13 @@ curl 'http://host/api/query/record/todo?operatorId=1&operatorIdentity=department **为节点指定同一人的多个身份**:`INITIATOR_SELECT` / `APPROVER_SELECT` 节点原有 `operatorSelectMap`(`节点ID -> List`)无法表达「同一人员以两个身份参与」,新增 `operatorSelectOperators`(`节点ID -> List`),每项为 `(operatorId, identity)`: ```java +// 发起时指定(FlowCreateRequest) createRequest.setOperatorSelectOperators(Map.of(approvalNodeId, List.of( OperatorKey.of(2L, "department1"), OperatorKey.of(2L, "department2")))); + +// 审批意见里指定(FlowAdviceBody,用于「审批时选择下一步审批人」的节点) +advice.setOperatorSelectOperators(Map.of(nextNodeId, List.of(OperatorKey.of(3L, "department1")))); ``` - 同一人员的两个身份是**两项**参与人,不会被去重合并;完全相同的二元组才去重; @@ -206,6 +217,10 @@ def run(request) { **Mock 链路同口径**:带 `mockKey` 的 REST 调用走 `FlowRecordQueryMockService`,待办 / 抄送 / 已办同时保留「跨身份」与「按身份」两套重载,前端联调与真实库路径行为一致。 +> **自定义查询实现注意**:`FlowRecordQueryService` 里带身份的三个方法是 `default` 方法,默认直接退化为「只按人员」的旧方法。 +> 自己实现该接口(不用 starter-query 提供的 `FlowRecordQueryServiceImpl`)时,若不覆盖它们, +> `identityScope=LOCKED` 会**静默退化**为跨身份查询——功能看似正常,但「锁定身份查看」不生效。 + ### 4.4 办理权限判定(可配置模式) 「当前用户能否办理/撤回/催办/减签某条记录」统一由 `OperatorIdentityPolicy` 判定,模式可配置: @@ -273,7 +288,7 @@ codingapi.flow.identity.match-mode=USER_ONLY ### 5.1 启用身份的时机(重要) -「存量数据无需回填」只说明**数据**是兼容的,不代表**行为**会自动兼容。判定与查询口径是 +「存量数据无需回填」只说明**数据**是兼容的,不代表**行为**会自动兼容。在 `STRICT` 模式下,判定与查询口径是 `(人员id, 身份)` 严格匹配,因此当某个用户开始携带非空身份后,他在存量「默认身份」数据上的表现是: | 场景 | 表现 | @@ -286,13 +301,15 @@ codingapi.flow.identity.match-mode=USER_ONLY > 列表按人员跨身份返回、判权只比人员,因此打开身份不需要过渡窗口;只有显式配置 `STRICT` > 或查询传 `identityScope=LOCKED` 时才回到上表口径(详见 4.3 / 4.6)。 -**因此不要在全量用户上一次性打开身份。** 推荐三种过渡方式: +**在 `STRICT` 模式下不要在全量用户上一次性打开身份。** 推荐三种过渡方式: -1. **只对新流程启用**:存量在途流程继续以默认身份办结,新流程带身份发起(最省事,推荐); -2. **兼容开关**:查询与判权时把默认身份作为兜底(`identity = X OR identity = ''`),过渡期打开、收尾时关闭; +1. **先用 `USER_ONLY`**(starter 默认):列表跨身份、判权只比人员,存量默认身份待办与新建的带身份事项可以同时办理, + 不需要停机或回填;确认业务上确实需要「身份作为独立参与人」时再切 `STRICT`(最省事,推荐); +2. **只对新流程启用**:存量在途流程继续以默认身份办结,新流程带身份发起; 3. **一次性回填**:把运行中流程的 `*_operator_identity` 回填为操作者当期身份,需要停机窗口与全量校验。 -前端应提供「切回默认身份」的入口(示例工程见 5.2),让用户仍能处理存量事项。 +前端应提供「选择 / 切回默认身份」的入口(示例工程见 5.2):`STRICT` 或锁定身份查看时,用户仍能处理存量事项; +默认 `USER_ONLY` 下它的作用是声明**本次操作身份**(脚本上下文与留痕),不影响能看到哪些数据。 ### 5.2 示例工程如何验证 diff --git a/docs/Integration/rest-api.md b/docs/Integration/rest-api.md index 9a65f134..9990a163 100644 --- a/docs/Integration/rest-api.md +++ b/docs/Integration/rest-api.md @@ -17,6 +17,18 @@ operatorId 请求参数 → 存在 → 使用该 id 作为当前操作人 - `mockKey` 经 `MockInstanceFactory.getInstance().getMockInstance(key)` 解析(见 [Mock 模式](./mock-mode.md))。 - `operatorId` 覆盖便于无登录态集成与测试(如 curl 直接带 `?operatorId=1`)。 +`operatorIdentity` 与 `operatorId` 对称(详见 [多身份参与](./operator-identity.md)): + +``` +operatorIdentity → 存在 → 校验后作为当前身份(空串 = 默认身份) + → 不存在且 operatorId 存在 → 归默认身份(避免人员与身份错配) + → 都不存在 → 取登录操作者自身身份 +``` + +- 命令接口携带它,决定**本次操作身份**(写入 `create_operator_identity` / `submit_operator_identity`)与脚本上下文; +- 查询接口携带它**不改变返回范围**(默认跨身份),需要按身份收敛时另传 `identityScope=LOCKED`(见第 4 节); +- 非法值(超长、含 `#`、含控制字符)在入口即被拒绝。 + ## 2. 命令操作(`/api/cmd/record`) `flow-engine-starter-api/src/main/java/com/codingapi/flow/api/controller/FlowRecordController.java` @@ -61,10 +73,20 @@ operatorId 请求参数 → 存在 → 使用该 id 作为当前操作人 | 方法 | 路径 | 参数 | 响应 | 说明 | |---|---|---|---|---| -| GET | `/api/query/record/list` | `SearchRequest`(current/pageSize) | `MultiResponse` | 全部流程记录(按 id 降序) | -| GET | `/api/query/record/todo` | `SearchRequest` | `MultiResponse` | 我的待办 | -| GET | `/api/query/record/notify` | `SearchRequest` | `MultiResponse` | 我的抄送 | -| GET | `/api/query/record/done` | `SearchRequest` | `MultiResponse` | 我的已办 | +| GET | `/api/query/record/list` | `SearchRequest`(current/pageSize) | `MultiResponse` | 全部流程记录(按 id 降序,不区分人员/身份) | +| GET | `/api/query/record/todo` | `SearchRequest` + 身份参数(见下) | `MultiResponse` | 我的待办(默认跨身份) | +| GET | `/api/query/record/notify` | 同上 | `MultiResponse` | 我的抄送(默认跨身份) | +| GET | `/api/query/record/done` | 同上 | `MultiResponse` | 我的已办(默认跨身份) | + +查询身份范围(`todo` / `done` / `notify` 通用,issue #297): + +| 参数 | 取值 | 默认 | 说明 | +|---|---|---|---| +| `identityScope` | `ALL` / `LOCKED` | `ALL` | `ALL` 只按人员过滤(跨身份全量);`LOCKED` 追加 `coalesce(identity,'') = :identity` | +| `lockIdentity` | `true` / `false` | `false` | 等价写法,`identityScope` 存在时以 `identityScope` 为准 | +| `operatorIdentity` | 任意合法身份 | 登录操作者身份 | 仅作为身份上下文,`ALL` 下不影响返回结果 | + +非法 `identityScope` 值在入口即报 `validation.parameter.identityScope`,避免拼写错误静默放宽范围。 `FlowRecordQueryService`(`flow-engine-framework/.../query/FlowRecordQueryService.java`): @@ -74,6 +96,12 @@ public interface FlowRecordQueryService { Page findTodoRecordPage(long userId, PageRequest request); Page findNotifyRecordPage(long userId, PageRequest request); Page findDoneRecordPage(long userId, PageRequest request); + + // 带身份的重载:均为 default,默认退化为上面的「只按人员」方法。 + // 需要 identityScope=LOCKED 生效时,实现方必须覆盖。 + default Page findTodoRecordPage(long userId, String identity, PageRequest request) { ... } + default Page findNotifyRecordPage(long userId, String identity, PageRequest request) { ... } + default Page findDoneRecordPage(long userId, String identity, PageRequest request) { ... } } ``` diff --git a/docs/capabilities/flow-engine-framework/gateway-context.md b/docs/capabilities/flow-engine-framework/gateway-context.md index 34dae184..365ad028 100644 --- a/docs/capabilities/flow-engine-framework/gateway-context.md +++ b/docs/capabilities/flow-engine-framework/gateway-context.md @@ -42,6 +42,10 @@ public interface FlowOperatorGateway { } ``` +> 多身份场景还需覆盖两个 `default` 重载 `get(long, String)` 与 `findByIds(List, String)`; +> 不覆盖时它们退化为忽略身份的上面两个方法,请求里声明的身份不会写入记录。 +> 详见 [多身份参与](../../Integration/operator-identity.md) 3.2。 + ### 缓存机制 - 每次 `FlowService` 操作前调用 `FlowOperatorLocalThreadCache.clear()` 清理缓存 From 06e98479b6a2f27580cfed595bf85bd64b6123b8 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Wed, 2 Dec 2026 16:51:45 +0800 Subject: [PATCH 14/35] =?UTF-8?q?docs(user-integration):=20=E8=A1=A5?= =?UTF-8?q?=E5=85=85=20findByIds(ids,=20identity)=20=E9=87=8D=E8=BD=BD?= =?UTF-8?q?=E8=AF=B4=E6=98=8E=EF=BC=88issue=20#297=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/Integration/user-integration.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/Integration/user-integration.md b/docs/Integration/user-integration.md index ae1b1e72..3e1f489a 100644 --- a/docs/Integration/user-integration.md +++ b/docs/Integration/user-integration.md @@ -21,12 +21,19 @@ public interface FlowOperatorGateway { } List findByIds(List ids); + + /** 按 (ids, identity) 批量取用户,default 退化为 findByIds(ids);多身份场景需一并覆盖 */ + default List findByIds(List ids, String identity) { + return findByIds(ids); + } } ``` 引擎所有「按 id 取用户 / 批量取用户」的请求都汇聚到这个接口。**框架不提供默认实现**(`flow-engine-starter-infra` 也不提供),必须由业务方提供一个 Spring Bean。 -> 同一人员以多个身份参与流程时(例如同时隶属两个部门),需要覆盖 `get(long, String)`,详见 [多身份参与](./operator-identity.md)。 +> 同一人员以多个身份参与流程时(例如同时隶属两个部门),需要覆盖 `get(long, String)`; +> 流程树、人员设定等批量路径还需要覆盖 `findByIds(List, String)`,只覆盖单条会让批量路径退化为默认身份。 +> 详见 [多身份参与](./operator-identity.md) 3.2。 ### 1.2 `IFlowOperator`(流程操作人) From 0fda1600b3c075d8f83062af104814b01fc982dc Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Wed, 2 Dec 2026 16:52:12 +0800 Subject: [PATCH 15/35] =?UTF-8?q?docs(example):=20=E6=BC=94=E7=A4=BA?= =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96=E5=99=A8=E6=B3=A8=E9=87=8A=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E8=B7=A8=E8=BA=AB=E4=BB=BD=E5=8F=A3=E5=BE=84=EF=BC=88?= =?UTF-8?q?issue=20#297=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../example/runner/IdentityDemoInitializer.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/flow-engine-example/src/main/java/com/codingapi/example/runner/IdentityDemoInitializer.java b/flow-engine-example/src/main/java/com/codingapi/example/runner/IdentityDemoInitializer.java index 634a5265..0aca92f2 100644 --- a/flow-engine-example/src/main/java/com/codingapi/example/runner/IdentityDemoInitializer.java +++ b/flow-engine-example/src/main/java/com/codingapi/example/runner/IdentityDemoInitializer.java @@ -36,8 +36,7 @@ * 身份标识(issue #288)可视化验证数据初始化。 * *

    示例工程默认只有 admin 一个账号、没有任何流程数据,登录后待办页永远是空列表, - * 无法直观看到「同一人员以不同身份参与流程、待办按身份隔离」的效果。这里在首次启动时 - * 生成一套最小可验证数据: + * 无法直观看到「同一人员以不同身份参与流程」的效果。这里在首次启动时生成一套最小可验证数据: * *

      *
    1. 创建演示账号 {@code user1}(张三)、{@code user2}(李四),密码统一 {@code 123456};
    2. @@ -51,8 +50,11 @@ * *
    * - *

    验证方式:用 user1 登录,在页面右下角切换身份为「默认身份」与「department1」, - * 待办列表应分别只出现对应身份的那一条;切到「department2」应为空(那是李四的待办)。 + *

    验证方式(默认 {@code USER_ONLY} + 跨身份查询,issue #297):用 user1 登录,「待办中心」应同时出现 + * 张三 · 默认身份与 张三 · department1 两条;切换「操作身份」只改变本次操作身份(脚本上下文与留痕), + * 不改变列表范围——用 department1 的身份也能审批那条落在默认身份上的待办。 + * 想验证 #288 的隔离语义,配置 {@code codingapi.flow.identity.match-mode=STRICT} 并传 + * {@code identityScope=LOCKED},此时列表才会只出现当前身份的那一条。 * *

    初始化是幂等的:流程编码已存在时直接跳过,不会重复造数据。 * 不需要演示数据时可通过 {@code flow.example.identity-demo-enabled=false} 关闭。 From 5573905c64c2fd332889e93818c29eba2bc8a994 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Wed, 2 Dec 2026 17:26:01 +0800 Subject: [PATCH 16/35] =?UTF-8?q?test(identity):=20=E8=A1=A5=E9=BD=90?= =?UTF-8?q?=E8=BA=AB=E4=BB=BD=E8=BE=B9=E7=95=8C=E7=94=A8=E4=BE=8B=E5=B9=B6?= =?UTF-8?q?=E6=94=B6=E5=8F=A3=E5=90=88=E5=B9=B6=E9=94=AE/=E5=8A=A0?= =?UTF-8?q?=E7=AD=BE=E6=9F=A5=E9=87=8D=EF=BC=88Closes=20#295=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 待办合并键由匹配模式决定:USER_ONLY 按人合并(身份不进键),STRICT 保持 历史兼容追加格式,避免同一人出现两条重复待办 - 加签「是否已在待办队列」改由 OperatorIdentityPolicy 判定:USER_ONLY 下 同人换身份视为同一人,拒绝重复加签;STRICT 下仍按 (人, 身份) 区分 - 新增 OperatorIdentityBoundaryTest(13 例):撤回/催办、加签/减签、 转交与干预留痕、同人自动通过的 USER_ONLY / STRICT 双模式断言 - FlowSubProcessResetServiceTest 补 2 例:子流程重置的身份归属校验 - 同步 operator-identity.md 4.2 / 4.4 / 5.1 口径 --- docs/Integration/operator-identity.md | 24 +- .../flow/action/actions/AddAuditAction.java | 33 +- .../com/codingapi/flow/record/FlowRecord.java | 21 +- .../FlowSubProcessResetServiceTest.java | 69 ++ .../service/OperatorIdentityBoundaryTest.java | 596 ++++++++++++++++++ 5 files changed, 712 insertions(+), 31 deletions(-) create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityBoundaryTest.java diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md index d661a73e..409b957c 100644 --- a/docs/Integration/operator-identity.md +++ b/docs/Integration/operator-identity.md @@ -12,7 +12,7 @@ |----------|------| | 节点 / 分支差异 | user1 在 department1 发起需要「组长审核」,在 department2 发起则直接「部门经理审核」 | | 人员差异 | department1 的经理是 boss1,department2 的经理是 boss2 | -| 待办差异 | user1 在 department1 / department2 各有一条待办,不能合并成一条 | +| 待办差异 | user1 在 department1 / department2 各有一条待办,不能合并成一条(`STRICT` 模式;`USER_ONLY` 下按人合并) | 0.2.x 的引擎只认 `userId`:记录、待办、权限判定全部按 userId 比较,上述场景无法表达。 @@ -194,16 +194,23 @@ def run(request) { 升级脚本见 [sql/0.3.0-operator-identity.sql](./sql/0.3.0-operator-identity.sql)。 -### 4.2 待办合并键(兼容追加) +### 4.2 待办合并键(由匹配模式决定) `FlowRecord#getTodoKey()` 的格式: -| 身份 | 合并键 | -|------|--------| -| 默认身份 | `{operatorId}-{workRuntimeId}-{nodeId}`(与 0.2.x 完全一致) | -| 非空身份 | `{operatorId}-{workRuntimeId}-{nodeId}#{identity}` | +| 模式 | 身份 | 合并键 | +|------|------|--------| +| `USER_ONLY` | 任意 | `{operatorId}-{workRuntimeId}-{nodeId}`(身份不参与) | +| `STRICT` | 默认身份 | `{operatorId}-{workRuntimeId}-{nodeId}`(与 0.2.x 完全一致) | +| `STRICT` | 非空身份 | `{operatorId}-{workRuntimeId}-{nodeId}#{identity}` | -默认身份保持历史格式是刻意的:升级瞬间仍在运行的流程,其存量待办行是旧格式键,若统一改格式会导致新流转算出的键查不到旧行 → 重复生成待办、合并关系断裂。 +`USER_ONLY` 下身份不参与合并:身份只是脚本与留痕信息,同一个人的两个身份在同一节点是**一个参与人**, +否则同一个人会在待办列表里出现两条同样的待办。`STRICT` 下两个身份是独立参与人,必须分键, +其中默认身份保持历史格式是刻意的:升级瞬间仍在运行的流程,其存量待办行是旧格式键, +若统一改格式会导致新流转算出的键查不到旧行 → 重复生成待办、合并关系断裂。 + +> 切换匹配模式后,存量待办的键仍是旧格式,合并组会一分为二,属预期行为; +> 需要收拢时执行 `FlowTodoMigrateService` 重建待办快照。 ### 4.3 查询范围(默认跨身份,可显式锁定) @@ -235,6 +242,7 @@ def run(request) { - 审批动作的参与人校验(`WorkflowStrategyManager#verifyOperator`) - 撤销、删除、催办、子流程重置的记录归属校验 - 减签的目标匹配与「不能减自己」判定 +- 加签的「是否已在待办队列中」查重(`USER_ONLY` 下同人换身份视为同一人,拒绝重复加签) - 提交人 == 审批人的自动通过判定 - 流程干预人识别(`USER_ONLY` 下同人换身份不算干预) - 详情页 `currentNodeOperators` 的去重与「排除当前操作人」判定 @@ -295,7 +303,7 @@ codingapi.flow.identity.match-mode=USER_ONLY |------|------| | 待办 / 已办 / 抄送列表 | 存量默认身份记录**不再出现在该身份的列表里**(按身份隔离的必然结果) | | 处置存量待办 | 记录身份为默认身份,当前身份 != 默认身份 → 判权不通过,操作被拒绝 | -| 待办合并 | 旧格式键(无 `#identity`)与新键不互通,不会合并到同一条待办 | +| 待办合并 | 旧格式键(无 `#identity`)与新键不互通,不会合并到同一条待办(`STRICT`;`USER_ONLY` 按人合并,不受影响) | > 上表是 `STRICT` 模式下的表现。**starter 默认的 `USER_ONLY`(issue #297)下前两条不成立**: > 列表按人员跨身份返回、判权只比人员,因此打开身份不需要过渡窗口;只有显式配置 `STRICT` diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/AddAuditAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/AddAuditAction.java index 12fa25c1..933299f9 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/AddAuditAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/AddAuditAction.java @@ -12,7 +12,7 @@ import com.codingapi.flow.manager.OperatorManager; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; -import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityPolicy; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.script.node.OperatorLoadScript; import com.codingapi.flow.session.FlowSession; @@ -24,8 +24,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; /** * 加签 @@ -147,6 +145,10 @@ public void run(FlowSession flowSession) { *

    待办队列指当前节点实例中尚未办理的审批记录:包括顺序审批里尚未激活的隐藏记录 * (它们后续会按序号激活为待办),但不包括已办、已撤销以及已结束流程的记录。 * + *

    「是否已存在」统一由 {@link OperatorIdentityPolicy} 判定(issue #295): + * 严格模式下同一人的另一身份是独立参与人,可以加签;仅按人员模式下同一个人已经待办, + * 再加签只会给自己多生成一条重复待办,因此拒绝。 + * * @param flowSession 当前会话 * @param auditOperators 本次加签的人员 */ @@ -154,42 +156,37 @@ private void verifyNotInTodoQueue(FlowSession flowSession, List a if (auditOperators == null || auditOperators.isEmpty()) { return; } - Set pendingOperators = pendingOperatorKeys(flowSession); - if (pendingOperators.isEmpty()) { + List pendingRecords = pendingRecords(flowSession); + if (pendingRecords.isEmpty()) { return; } for (IFlowOperator auditOperator : auditOperators) { - if (pendingOperators.contains(operatorKey(auditOperator.getUserId(), OperatorIdentity.of(auditOperator)))) { + boolean alreadyPending = pendingRecords.stream().anyMatch(record -> + OperatorIdentityPolicy.matches(auditOperator, + record.getCurrentOperatorId(), record.getCurrentOperatorIdentity())); + if (alreadyPending) { throw FlowExecutionException.addAuditOperatorAlreadyInTodo(auditOperator.getUserId()); } } } /** - * 参与人键:{@code userId + identity},同一人员的不同身份是不同参与人(issue #288) - */ - private static String operatorKey(long userId, String identity) { - return userId + "\u0001" + OperatorIdentity.normalize(identity); - } - - /** - * 当前节点实例中仍有待办的参与人键集合(userId + identity)。 + * 当前节点实例中仍有待办的审批记录。 * *

    仓储按 {@code (fromId, nodeId)} 查询节点记录,开始节点({@code fromId = 0})等场景可能 * 命中其他流程实例的记录,必须按 {@code processId} 限定,避免误判其他流程的待办人员。 */ - private Set pendingOperatorKeys(FlowSession flowSession) { + private List pendingRecords(FlowSession flowSession) { FlowRecord currentRecord = flowSession.getCurrentRecord(); List currentNodeRecords = flowSession.getCurrentNodeRecords(); if (currentRecord == null || currentNodeRecords == null) { - return Set.of(); + return List.of(); } return currentNodeRecords.stream() .filter(Objects::nonNull) .filter(record -> currentRecord.getProcessId().equals(record.getProcessId())) .filter(FlowRecord::isPendingApproval) - .map(record -> operatorKey(record.getCurrentOperatorId(), record.getCurrentOperatorIdentity())) - .collect(Collectors.toSet()); + .toList(); } public static AddAuditAction fromMap(Map data) { diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java index 0bd61ed0..ebd6cd91 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java @@ -10,6 +10,7 @@ import com.codingapi.flow.node.nodes.NotifyNode; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityMatchMode; import com.codingapi.flow.operator.OperatorIdentityPolicy; import com.codingapi.flow.session.FlowAdvice; import com.codingapi.flow.session.FlowSession; @@ -312,13 +313,19 @@ public class FlowRecord { * * 相同依据字段 + {@link FlowRecord#workRuntimeId} + {@link FlowRecord#nodeId} 的数据合并到一条记录上。 * - *

    多身份场景(issue #288):同一人员的两个身份是不同的参与人,合并键必须带上身份, - * 否则两个身份的待办会被合并成一条。为避免破坏存量数据,采用**兼容追加**策略: + *

    合并键是否包含身份由 {@link OperatorIdentityPolicy} 的匹配模式决定(issue #295): *

      - *
    • 默认身份(空)— 键格式保持历史原样 {@code {operatorId}-{workRuntimeId}-{nodeId}}, - * 升级瞬间仍在运行的流程,其待办行仍是旧格式键,合并关系不会断裂;
    • - *
    • 非空身份 — 追加 {@code #identity} 后缀,与默认身份、其他身份天然隔离。
    • + *
    • {@link OperatorIdentityMatchMode#USER_ONLY}(starter 默认)— 身份不参与合并, + * 同一人的两个身份在同一节点视为**一个参与人**,只保留一条待办。这也是「身份不是权限、 + * 同人可任意身份办理」语义的必然结果,否则同一个人会在列表里出现两条同样的待办;
    • + *
    • {@link OperatorIdentityMatchMode#STRICT}(framework 默认)— 身份是独立参与人, + * 键必须带上身份,否则两个身份的待办会被合并成一条。为避免破坏存量数据,采用**兼容追加**策略: + * 默认身份(空)保持历史键格式 {@code {operatorId}-{workRuntimeId}-{nodeId}}, + * 非空身份追加 {@code #identity} 后缀。
    • *
    + * + *

    模式切换后存量待办的键仍为旧格式,合并组会一分为二,属预期行为: + * 需要收拢时执行 {@code FlowTodoMigrateService} 重建待办快照即可。 */ public String getTodoKey() { if (mergeable) { @@ -339,6 +346,10 @@ public String getTodoKey() { } } String todoKey = String.format("%s-%s-%s", mergeOperatorId, workRuntimeId, nodeId); + // 按人合并:身份只是脚本与留痕信息,不参与合并键,否则同一人会出现多条待办 + if (OperatorIdentityPolicy.matchMode() == OperatorIdentityMatchMode.USER_ONLY) { + return todoKey; + } String identity = OperatorIdentity.normalize(mergeOperatorIdentity); // 默认身份保持历史键格式,保证升级过程中存量待办的合并关系不断裂 if (identity.isEmpty()) { diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowSubProcessResetServiceTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowSubProcessResetServiceTest.java index 2687d8a9..4a454da2 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowSubProcessResetServiceTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowSubProcessResetServiceTest.java @@ -23,6 +23,8 @@ import com.codingapi.flow.node.nodes.ParallelNode; import com.codingapi.flow.node.nodes.StartNode; import com.codingapi.flow.node.nodes.SubProcessNode; +import com.codingapi.flow.operator.OperatorIdentityMatchMode; +import com.codingapi.flow.operator.OperatorIdentityPolicy; import com.codingapi.flow.pojo.body.FlowAdviceBody; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.request.FlowCreateRequest; @@ -56,6 +58,7 @@ import java.util.Map; import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -114,6 +117,11 @@ void resetEventContext() throws Exception { field.set(instance, null); } + @AfterEach + void resetIdentityPolicy() { + OperatorIdentityPolicy.reset(); + } + /** * 测试目标:验证在最终审批节点重置选中的 1 个子流程实例后,主流程重新等待, * 重建实例完成后主流程恢复并可正常走完。 @@ -540,6 +548,67 @@ void shouldRejectResetWhenOperatorMismatchOrRecordNotTodo() { "已办结记录不能重置"); } + /** + * 测试目标:USER_ONLY 模式下,同一人以另一身份重置子流程视为合法操作人(身份不阻断同人操作)。 + * 前置条件:主流程停在最终审批待办,两个子流程实例全部放行;记录登记的是默认身份。 + * 执行步骤:以 department1 身份调用重置接口(选中 1 个实例)。 + * 期望断言:不抛异常,旧聚合组被取代并产生新聚合组。 + */ + @Test + void shouldAllowResetWithOtherIdentityOfSameOperatorInUserOnlyMode() { + OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + FlowRecord finalTodo = prepareResetAtFinalApproval(); + + SubProcessRecord passedGroup = factory.subProcessRepository + .findByParentProcessId(parentProcessId(finalTodo)).get(0); + List processIds = List.of(passedGroup.getInstances().get(0).getProcessId()); + FlowSubProcessResetRequest request = new FlowSubProcessResetRequest( + finalTodo.getId(), finalOperator.getUserId(), processIds); + request.setOperatorIdentity("department1"); + + assertDoesNotThrow(() -> factory.flowService.resetSubProcess(request)); + assertTrue(factory.subProcessRepository + .findByParentProcessIdAndNodeId(parentProcessId(finalTodo), subProcessNode.getId()) + .get(0).isSuperseded(), + "重置成功后旧聚合组应被取代"); + } + + /** + * 测试目标:STRICT 模式下,同一人以另一身份不能重置子流程(身份是独立参与人)。 + * 前置条件:主流程停在最终审批待办,两个子流程实例全部放行;记录登记的是默认身份。 + * 执行步骤:以 department1 身份调用重置接口。 + * 期望断言:抛出状态异常,旧聚合组未被取代。 + */ + @Test + void shouldRejectResetWithOtherIdentityOfSameOperatorInStrictMode() { + FlowRecord finalTodo = prepareResetAtFinalApproval(); + + SubProcessRecord passedGroup = factory.subProcessRepository + .findByParentProcessId(parentProcessId(finalTodo)).get(0); + List processIds = List.of(passedGroup.getInstances().get(0).getProcessId()); + FlowSubProcessResetRequest request = new FlowSubProcessResetRequest( + finalTodo.getId(), finalOperator.getUserId(), processIds); + request.setOperatorIdentity("department1"); + + assertThrows(FlowStateException.class, () -> factory.flowService.resetSubProcess(request)); + assertFalse(factory.subProcessRepository + .findByParentProcessIdAndNodeId(parentProcessId(finalTodo), subProcessNode.getId()) + .get(0).isSuperseded(), + "拒绝重置时旧聚合组不能被取代"); + } + + /** + * 准备可重置现场:子流程全部放行后,返回主流程最终审批待办。 + */ + private FlowRecord prepareResetAtFinalApproval() { + buildParentWorkflow(true); + createAndSubmitParent(); + List childTodos = todos(childOperator, childApproval); + approve(childTodos.get(0), passAction(childApproval), childOperator, childTodos.get(0).getFormData()); + approve(childTodos.get(1), passAction(childApproval), childOperator, childTodos.get(1).getFormData()); + return todos(finalOperator, finalApproval).get(0); + } + /** * 测试目标:验证子流程后接并行分支时,合并节点锁定为第一个分支节点, * 仅锁定节点的待办可重置,兄弟分支被拒绝;重置作废全部分支记录链,重走后可正常走完。 diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityBoundaryTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityBoundaryTest.java new file mode 100644 index 00000000..2a8bbdae --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityBoundaryTest.java @@ -0,0 +1,596 @@ +package com.codingapi.flow.service; + +import com.codingapi.flow.action.ActionType; +import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.action.actions.CustomAction; +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.FlowExecutionException; +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.nodes.ApprovalNode; +import com.codingapi.flow.node.nodes.EndNode; +import com.codingapi.flow.node.nodes.StartNode; +import com.codingapi.flow.operator.OperatorIdentityMatchMode; +import com.codingapi.flow.operator.OperatorIdentityPolicy; +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.FlowRevokeRequest; +import com.codingapi.flow.pojo.request.FlowUrgeRequest; +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.strategy.node.RevokeStrategy; +import com.codingapi.flow.strategy.node.SameOperatorAuditStrategy; +import com.codingapi.flow.user.User; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.WorkflowBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +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 #295 缺口 2 / 3 / 4 / 7)。 + * + *

    统一约定:身份不是权限,只是脚本执行与留痕信息。是否把「同一人的两个身份」当作同一参与人, + * 由 {@link OperatorIdentityPolicy} 的匹配模式决定: + *

      + *
    • {@link OperatorIdentityMatchMode#USER_ONLY}:按人匹配,同人换身份可以办理自己的待办, + * 加签 / 减签也按人判定;
    • + *
    • {@link OperatorIdentityMatchMode#STRICT}:按 (人, 身份) 匹配,两个身份是独立参与人。
    • + *
    + * + *

    覆盖点: + *

      + *
    1. 撤回 / 催办的身份归属校验({@code FlowRevokeService} / {@code FlowUrgeService});
    2. + *
    3. 加签同人异身份查重、减签身份维度({@code AddAuditAction} / {@code ReduceAuditAction});
    4. + *
    5. 转交 {@code forwardOperatorIdentity} 落库、同人换身份办理不记干预;
    6. + *
    7. {@code BaseAuditNode} 同人自动通过的身份过滤。
    8. + *
    + */ +class OperatorIdentityBoundaryTest { + + private static final long INITIATOR = 1; + private static final long APPROVER = 2; + private static final long SECOND_APPROVER = 3; + + private static final String DEPARTMENT_1 = "department1"; + private static final String DEPARTMENT_2 = "department2"; + + private MyFlowServiceFactory factory; + private final Map data = Map.of("name", "lorne"); + + @BeforeEach + void setUp() { + factory = new MyFlowServiceFactory(); + factory.userGateway.save(new User(INITIATOR, "initiator")); + factory.userGateway.save(new User(APPROVER, "approver")); + factory.userGateway.save(new User(SECOND_APPROVER, "second")); + GatewayContext.getInstance().setFlowOperatorGateway(factory.userGateway); + } + + @AfterEach + void tearDown() { + OperatorIdentityPolicy.reset(); + } + + // ==================== 缺口 2:撤回 / 催办的身份归属 ==================== + + /** + * 测试目标:USER_ONLY 模式下,同一人换身份仍可撤回自己提交的记录。 + * 前置条件:发起人以 department1 发起并提交,流程停在审批节点待办。 + * 执行步骤:以 department2 身份撤回发起记录。 + * 期望断言:不抛异常,发起记录回到待办,审批待办被撤销。 + */ + @Test + void should_allow_revoke_with_other_identity_in_user_only_mode() { + OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + Workflow workflow = saveFlow("identity-revoke-user-only", APPROVER); + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + assertDoesNotThrow(() -> factory.flowService.revoke( + new FlowRevokeRequest(startRecordId, INITIATOR, DEPARTMENT_2))); + + assertTrue(factory.flowRecordRepository.get(startRecordId).isTodo(), "撤回后发起记录应回到待办"); + assertEquals(0, factory.flowRecordRepository.findTodoByOperator(APPROVER).size(), + "审批待办应被撤销"); + } + + /** + * 测试目标:STRICT 模式下,同一人换身份不能撤回记录(身份是独立参与人)。 + * 前置条件:发起人以 department1 发起并提交。 + * 执行步骤:以 department2 身份撤回发起记录。 + * 期望断言:抛出状态异常,记录仍为已办。 + */ + @Test + void should_reject_revoke_with_other_identity_in_strict_mode() { + Workflow workflow = saveFlow("identity-revoke-strict", APPROVER); + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + assertThrows(FlowStateException.class, () -> factory.flowService.revoke( + new FlowRevokeRequest(startRecordId, INITIATOR, DEPARTMENT_2))); + assertFalse(factory.flowRecordRepository.get(startRecordId).isTodo(), "拒绝撤回时记录保持已办"); + } + + /** + * 测试目标:USER_ONLY 模式下,同一人换身份仍可催办自己提交的记录。 + * 前置条件:发起人以 department1 发起并提交。 + * 执行步骤:以 department2 身份催办。 + * 期望断言:不抛异常。 + */ + @Test + void should_allow_urge_with_other_identity_in_user_only_mode() { + OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + Workflow workflow = saveFlow("identity-urge-user-only", APPROVER); + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + assertDoesNotThrow(() -> factory.flowService.urge( + new FlowUrgeRequest(startRecordId, INITIATOR, DEPARTMENT_2))); + } + + /** + * 测试目标:STRICT 模式下,同一人换身份不能催办记录。 + * 前置条件:发起人以 department1 发起并提交。 + * 执行步骤:以 department2 身份催办。 + * 期望断言:抛出状态异常。 + */ + @Test + void should_reject_urge_with_other_identity_in_strict_mode() { + Workflow workflow = saveFlow("identity-urge-strict", APPROVER); + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + assertThrows(FlowStateException.class, () -> factory.flowService.urge( + new FlowUrgeRequest(startRecordId, INITIATOR, DEPARTMENT_2))); + } + + // ==================== 缺口 3:加签 / 减签的身份维度 ==================== + + /** + * 测试目标:USER_ONLY 模式下,为「同一人」加签会被拒绝(该人已在节点待办队列中)。 + * 前置条件:审批记录归属 approver + department1;网关回退为默认身份,加签目标解析为 (approver, 默认身份)。 + * 执行步骤:以 department1 身份对当前记录加签,目标为同一人。 + * 期望断言:抛出执行异常,节点记录数不变。 + */ + @Test + void should_reject_add_audit_for_same_user_in_user_only_mode() { + OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + prepareApprovalRecordWithIdentity("identity-add-audit-user-only"); + FlowRecord approvalRecord = currentApprovalRecord(); + + assertThrows(FlowExecutionException.class, () -> addAudit(APPROVER, DEPARTMENT_1, APPROVER)); + assertEquals(1, recordsOfNode(approvalRecord).size(), "拒绝加签时不应新增记录"); + } + + /** + * 测试目标:STRICT 模式下,加签目标携带默认身份时与 (approver, department1) 不是同一参与人,允许加签。 + * 前置条件:审批记录归属 approver + department1;网关回退为默认身份。 + * 执行步骤:以 department1 身份加签同一人员(默认身份)。 + * 期望断言:不抛异常,节点上新增一条该人员的记录。 + */ + @Test + void should_allow_add_audit_for_same_user_with_other_identity_in_strict_mode() { + prepareApprovalRecordWithIdentity("identity-add-audit-strict"); + FlowRecord approvalRecord = currentApprovalRecord(); + + assertDoesNotThrow(() -> addAudit(APPROVER, DEPARTMENT_1, APPROVER)); + assertEquals(2, recordsOfNode(approvalRecord).size(), "STRICT 下另一身份应视为独立参与人"); + } + + /** + * 测试目标:USER_ONLY 模式下,减签按「人」生效,可以撤下同一人员以另一身份持有的待办。 + * 前置条件:审批节点依次审批 b1(默认身份)、b2(department2);网关中 b2 回退为默认身份。 + * 执行步骤:b1 以默认身份减签 b2(目标解析为默认身份)。 + * 期望断言:b2 的记录被撤销,b2 不再有待办。 + */ + @Test + void should_reduce_pending_record_of_same_user_with_other_identity_in_user_only_mode() { + OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + FlowRecord secondRecord = prepareSequenceApproval("identity-reduce-user-only"); + + assertDoesNotThrow(() -> reduceAudit(APPROVER, SECOND_APPROVER)); + + assertTrue(factory.flowRecordRepository.get(secondRecord.getId()).isRevoked(), + "USER_ONLY 下应按人撤下该待办"); + assertEquals(0, factory.flowRecordRepository.findTodoByOperator(SECOND_APPROVER).size()); + } + + /** + * 测试目标:STRICT 模式下,减签目标身份不一致时视为目标不存在。 + * 前置条件:审批节点依次审批 b1(默认身份)、b2(department2);网关中 b2 回退为默认身份。 + * 执行步骤:b1 减签 b2(目标解析为默认身份)。 + * 期望断言:抛出执行异常,b2 的记录保持待审批。 + */ + @Test + void should_reject_reduce_when_target_identity_differs_in_strict_mode() { + FlowRecord secondRecord = prepareSequenceApproval("identity-reduce-strict"); + + assertThrows(FlowExecutionException.class, () -> reduceAudit(APPROVER, SECOND_APPROVER)); + + assertTrue(factory.flowRecordRepository.get(secondRecord.getId()).isPendingApproval(), + "STRICT 下身份不一致不应命中目标记录"); + } + + // ==================== 缺口 4:转交身份落库 / 同人换身份不算干预 ==================== + + /** + * 测试目标:转交后新记录的操作人身份记录被转交人的身份。 + * 前置条件:网关中 second 携带 department2 身份,审批记录归属 approver。 + * 执行步骤:approver 将待办转交给 second。 + * 期望断言:新记录的操作人身份为 department2。 + */ + @Test + void should_record_forward_operator_identity_when_transfer_target_carries_identity() { + factory.userGateway.save(User.withIdentity(SECOND_APPROVER, "second", DEPARTMENT_2)); + Workflow workflow = saveFlow("identity-transfer", APPROVER); + long startRecordId = createFlow(workflow, ""); + submit(workflow, startRecordId, ""); + + FlowRecord approvalRecord = currentApprovalRecord(); + transfer(approvalRecord, APPROVER, SECOND_APPROVER); + + FlowRecord transferred = factory.flowRecordRepository.findTodoByOperator(SECOND_APPROVER).get(0); + assertEquals(DEPARTMENT_2, transferred.getCurrentOperatorIdentity(), "新记录操作人应携带目标身份"); + } + + /** + * 测试目标:人员存在转交链时,新记录落库被转交人(源操作人)的身份。 + * 前置条件:approver 携带 department1 身份并把待办转交给 second(department2)。 + * 执行步骤:发起并提交,使审批节点按转交链生成记录。 + * 期望断言:记录归属 second(department2),转交人字段为 approver + department1。 + */ + @Test + void should_record_forward_operator_identity_from_forward_chain() { + factory.userGateway.save(new ForwardingUser(APPROVER, "approver", DEPARTMENT_1, + User.withIdentity(SECOND_APPROVER, "second", DEPARTMENT_2))); + Workflow workflow = saveFlow("identity-forward-chain", APPROVER); + long startRecordId = createFlow(workflow, ""); + submit(workflow, startRecordId, ""); + + FlowRecord forwarded = todoRecordOf(SECOND_APPROVER); + assertEquals(DEPARTMENT_2, forwarded.getCurrentOperatorIdentity(), "转交链末端操作人身份应落库"); + assertEquals(APPROVER, forwarded.getForwardOperatorId()); + assertEquals(DEPARTMENT_1, forwarded.getForwardOperatorIdentity(), "被转交人身份应落库"); + } + + /** + * 测试目标:USER_ONLY 模式下,同一人换身份办理自己的记录不算流程干预,且操作身份被留痕。 + * 前置条件:发起人以 department1 发起,开始节点记录归属 (initiator, department1)。 + * 执行步骤:以 department2 身份提交开始节点记录。 + * 期望断言:不抛异常,干预人字段保持默认空串,流转出的记录提交人身份为 department2。 + */ + @Test + void should_not_record_interfere_when_same_user_uses_other_identity() { + OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + Workflow workflow = saveFlow("identity-interfere", APPROVER); + long startRecordId = createFlow(workflow, DEPARTMENT_1); + + assertDoesNotThrow(() -> submit(workflow, startRecordId, DEPARTMENT_2)); + + FlowRecord record = factory.flowRecordRepository.get(startRecordId); + assertEquals(0, record.getInterferedOperatorId(), "同人换身份办理不应记为干预"); + assertEquals("", record.getInterferedOperatorIdentity(), "干预人身份应保持默认空串"); + assertEquals(DEPARTMENT_2, currentApprovalRecord().getSubmitOperatorIdentity(), "操作身份应留痕"); + } + + // ==================== 缺口 7:同人自动通过的身份过滤 ==================== + + /** + * 测试目标:USER_ONLY 模式下,提交人换身份后仍视为同人,审批节点自动通过。 + * 前置条件:审批节点唯一审批人为提交人本人(网关默认身份),开启相同人员自动审批; + * 提交时声明 department1,使记录上的提交人身份与审批人身份不同。 + * 执行步骤:发起并提交到审批节点。 + * 期望断言:提交人不再有审批待办,流程直接流转到下游审批节点。 + */ + @Test + void should_auto_pass_when_same_user_uses_other_identity_in_user_only_mode() { + OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + Workflow workflow = saveAutoPassFlow("identity-auto-pass-user-only"); + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + assertEquals(0, factory.flowRecordRepository.findTodoByOperator(INITIATOR).size(), + "同人自动通过后提交人不应有审批待办"); + assertEquals(1, factory.flowRecordRepository.findTodoByOperator(APPROVER).size(), + "流程应直接流转到下游审批节点"); + } + + /** + * 测试目标:STRICT 模式下,提交人与审批人身份不一致时不自动通过,仍生成审批待办。 + * 前置条件:审批节点唯一审批人为提交人本人(网关默认身份),开启相同人员自动审批; + * 提交时声明 department1。 + * 执行步骤:发起并提交到审批节点。 + * 期望断言:提交人以默认身份获得一条审批待办,流程未向下流转。 + */ + @Test + void should_not_auto_pass_when_same_user_uses_other_identity_in_strict_mode() { + Workflow workflow = saveAutoPassFlow("identity-auto-pass-strict"); + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + assertEquals(1, factory.flowRecordRepository.findTodoByOperator(INITIATOR).size(), + "STRICT 下身份不一致不应自动通过"); + assertEquals(0, factory.flowRecordRepository.findTodoByOperator(APPROVER).size(), + "流程不应流转到下游审批节点"); + } + + // ==================== 流程构建 ==================== + + /** + * 构建 Start(可撤回) -> Approval(指定审批人,多人为依次审批) -> End 的流程。 + */ + private Workflow saveFlow(String code, long... approverIds) { + StartNode startNode = startNode(code); + NodeStrategyBuilder builder = NodeStrategyBuilder.builder() + .addStrategy(fieldPermission(code)) + .addStrategy(new OperatorLoadStrategy(FlowGroovyScriptFactory + .createOperatorLoadScript("def run(request){return [" + joinIds(approverIds) + "]}") + .getKey())); + if (approverIds.length > 1) { + builder.addStrategy(new MultiOperatorAuditStrategy(MultiOperatorAuditStrategy.Type.SEQUENCE, 0f)); + } + ApprovalNode approvalNode = ApprovalNode.builder() + .name("审批") + .strategies(builder.build()) + .build(); + Workflow workflow = WorkflowBuilder.builder() + .title("身份边界流程") + .code(code) + .createdOperator(new User(INITIATOR, "initiator")) + .form(form(code)) + .addNode(startNode) + .addNode(approvalNode) + .addNode(EndNode.builder().build()) + .build(); + factory.workflowService.saveWorkflow(workflow); + return workflow; + } + + /** + * 构建 Start -> Approval(提交人本人, 相同人员自动审批) -> Approval(下游审批人) -> End 的流程。 + */ + private Workflow saveAutoPassFlow(String code) { + StartNode startNode = startNode(code); + ApprovalNode selfNode = ApprovalNode.builder() + .name("同人审批") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(fieldPermission(code)) + .addStrategy(new OperatorLoadStrategy(FlowGroovyScriptFactory + .createOperatorLoadScript("def run(request){return [" + INITIATOR + "]}") + .getKey())) + .addStrategy(new SameOperatorAuditStrategy(SameOperatorAuditStrategy.Type.AUTO_PASS)) + .build()) + .build(); + ApprovalNode nextNode = ApprovalNode.builder() + .name("下游审批") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(fieldPermission(code)) + .addStrategy(new OperatorLoadStrategy(FlowGroovyScriptFactory + .createOperatorLoadScript("def run(request){return [" + APPROVER + "]}") + .getKey())) + .build()) + .build(); + Workflow workflow = WorkflowBuilder.builder() + .title("同人自动通过流程") + .code(code) + .createdOperator(new User(INITIATOR, "initiator")) + .form(form(code)) + .addNode(startNode) + .addNode(selfNode) + .addNode(nextNode) + .addNode(EndNode.builder().build()) + .build(); + factory.workflowService.saveWorkflow(workflow); + return workflow; + } + + private StartNode startNode(String code) { + return StartNode.builder() + .strategies(NodeStrategyBuilder.builder() + .addStrategy(fieldPermission(code)) + .addStrategy(new RevokeStrategy(true, RevokeStrategy.Type.REVOKE_CURRENT)) + .build()) + .actions(ActionBuilder.builder() + .addAction(CustomAction.defaultAction()) + .build()) + .build(); + } + + private FlowForm form(String code) { + return FlowFormBuilder.builder() + .name("身份边界流程") + .code(code) + .addField("请假人", "name", DataType.STRING) + .build(); + } + + private FormFieldPermissionStrategy fieldPermission(String code) { + return new FormFieldPermissionStrategy(FormFieldPermissionsBuilder.builder() + .addPermission(code, "name", PermissionType.WRITE) + .build()); + } + + private String joinIds(long... ids) { + StringBuilder builder = new StringBuilder(); + for (long id : ids) { + if (!builder.isEmpty()) { + builder.append(','); + } + builder.append(id); + } + return builder.toString(); + } + + // ==================== 场景准备 ==================== + + /** + * 让审批记录归属 {@code (approver, department1)},随后把网关中的 approver 回退为默认身份, + * 使加签 / 减签目标解析为 {@code (approver, 默认身份)}——即「记录上的身份与网关默认身份不同」。 + */ + private void prepareApprovalRecordWithIdentity(String code) { + factory.userGateway.save(User.withIdentity(APPROVER, "approver", DEPARTMENT_1)); + Workflow workflow = saveFlow(code, APPROVER); + long startRecordId = createFlow(workflow, ""); + submit(workflow, startRecordId, ""); + assertEquals(DEPARTMENT_1, currentApprovalRecord().getCurrentOperatorIdentity(), + "审批记录应携带 department1 身份"); + // 网关回退:后续动作的目标人员按默认身份解析 + factory.userGateway.save(new User(APPROVER, "approver")); + } + + /** + * 构建依次审批流程并推进到审批节点:b1 为默认身份、b2 携带 department2, + * 随后把网关中的 b2 回退为默认身份;返回 b2 的待审批记录。 + */ + private FlowRecord prepareSequenceApproval(String code) { + factory.userGateway.save(User.withIdentity(SECOND_APPROVER, "second", DEPARTMENT_2)); + Workflow workflow = saveFlow(code, APPROVER, SECOND_APPROVER); + long startRecordId = createFlow(workflow, ""); + submit(workflow, startRecordId, ""); + + FlowRecord secondRecord = pendingRecordOf(SECOND_APPROVER); + assertEquals(DEPARTMENT_2, secondRecord.getCurrentOperatorIdentity(), + "b2 的记录应携带 department2 身份"); + // 网关回退:减签目标按默认身份解析 + factory.userGateway.save(new User(SECOND_APPROVER, "second")); + return secondRecord; + } + + // ==================== 动作入口 ==================== + + private long createFlow(Workflow workflow, String operatorIdentity) { + FlowCreateRequest request = new FlowCreateRequest(); + request.setWorkCode(workflow.getCode()); + request.setFormData(data); + request.setActionId(startAction(workflow).id()); + request.setOperatorId(INITIATOR); + request.setOperatorIdentity(operatorIdentity); + return factory.flowService.create(request); + } + + private void submit(Workflow workflow, long recordId, String operatorIdentity) { + FlowAdviceBody advice = new FlowAdviceBody(startAction(workflow).id(), "提交", INITIATOR); + advice.setOperatorIdentity(operatorIdentity); + FlowActionRequest request = new FlowActionRequest(); + request.setFormData(data); + request.setRecordId(recordId); + request.setAdvice(advice); + factory.flowService.action(request); + } + + private void addAudit(long operatorId, String operatorIdentity, long targetOperatorId) { + FlowRecord record = todoRecordOf(operatorId); + FlowAdviceBody advice = new FlowAdviceBody( + actionOf(record, ActionType.ADD_AUDIT).id(), "加签", operatorId); + advice.setOperatorIdentity(operatorIdentity); + advice.setForwardOperatorIds(List.of(targetOperatorId)); + FlowActionRequest request = new FlowActionRequest(); + request.setFormData(data); + request.setRecordId(record.getId()); + request.setAdvice(advice); + factory.flowService.action(request); + } + + private void reduceAudit(long operatorId, long targetOperatorId) { + FlowRecord record = todoRecordOf(operatorId); + FlowAdviceBody advice = new FlowAdviceBody( + actionOf(record, ActionType.REDUCE_AUDIT).id(), "减签", operatorId); + advice.setForwardOperatorIds(List.of(targetOperatorId)); + FlowActionRequest request = new FlowActionRequest(); + request.setFormData(data); + request.setRecordId(record.getId()); + request.setAdvice(advice); + factory.flowService.action(request); + } + + private void transfer(FlowRecord record, long operatorId, long targetOperatorId) { + FlowAdviceBody advice = new FlowAdviceBody( + actionOf(record, ActionType.TRANSFER).id(), "转交", operatorId); + advice.setForwardOperatorIds(List.of(targetOperatorId)); + FlowActionRequest request = new FlowActionRequest(); + request.setFormData(data); + request.setRecordId(record.getId()); + request.setAdvice(advice); + factory.flowService.action(request); + } + + // ==================== 断言 / 查询助手 ==================== + + private IFlowAction startAction(Workflow workflow) { + return workflow.getStartNode().actionManager().getActions().get(0); + } + + private IFlowAction actionOf(FlowRecord record, ActionType type) { + IFlowAction action = workflowOf(record).getFlowNode(record.getNodeId()) + .actionManager().getActionByType(type.name()); + assertTrue(action != null, "节点缺少动作:" + type); + return action; + } + + private Workflow workflowOf(FlowRecord record) { + return factory.workflowService.getWorkflowRuntime(record.getWorkRuntimeId()).toWorkflow(); + } + + private FlowRecord todoRecordOf(long operatorId) { + List records = factory.flowRecordRepository.findTodoByOperator(operatorId); + assertEquals(1, records.size(), "操作人应有且仅有一条待办"); + return records.get(0); + } + + /** + * 当前审批节点上 approver 的待办记录。 + */ + private FlowRecord currentApprovalRecord() { + return todoRecordOf(APPROVER); + } + + /** + * 指定人员在当前流程实例中的待审批记录(含顺序审批里尚未激活的隐藏记录)。 + */ + private FlowRecord pendingRecordOf(long operatorId) { + FlowRecord current = todoRecordOf(APPROVER); + return factory.flowRecordRepository.findCurrentNodeRecords(current.getFromId(), current.getNodeId()) + .stream() + .filter(FlowRecord::isPendingApproval) + .filter(record -> record.getCurrentOperatorId() == operatorId) + .findFirst().orElseThrow(); + } + + /** + * 同一节点实例上的全部记录(含顺序审批里尚未激活的隐藏记录)。 + */ + private List recordsOfNode(FlowRecord anyRecord) { + return factory.flowRecordRepository.findCurrentNodeRecords(anyRecord.getFromId(), anyRecord.getNodeId()); + } + + /** + * 携带转交链的人员:源操作人以指定身份存在,且把待办转交给 {@code forwardOperator}。 + */ + private static final class ForwardingUser extends User { + + private ForwardingUser(long userId, String name, String identity, User forwardOperator) { + super(userId, name, false, forwardOperator, identity); + } + } +} From e35c8f97c070009941a5cbcbbc7d0f6713b24016 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Wed, 2 Dec 2026 20:25:25 +0800 Subject: [PATCH 17/35] =?UTF-8?q?feat(#296):=20=E6=96=B0=E5=A2=9E=E4=B8=8B?= =?UTF-8?q?=E4=B8=80=E8=8A=82=E7=82=B9=E5=AE=A1=E6=89=B9=E4=BA=BA=E9=A2=84?= =?UTF-8?q?=E6=A3=80=E4=B8=8E=E5=BC=82=E5=B8=B8=E6=8F=90=E7=A4=BA=E5=A4=84?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ErrorThrow 增加 PROMPT 类型与 message 字段,NODE/OPERATORS 语义保持不变 - ErrorTriggerScript 支持 Map 返回值(prompt/node/operators),兼容 String/List/Number 历史写法 - 默认 errorTrigger 由「回退至开始节点」改为「异常提示」,业务方可通过 IScriptRegistry 覆盖文案 - BaseAuditNode 在取人为空且配置为 PROMPT 时阻断操作,抛出 validation.node.operatorEmpty - 新增 FlowPrecheckService 与 POST /api/cmd/record/precheck,只预测直接下一节点,只读不落库 - 补充 ErrorTriggerScriptTest、FlowPrecheckServiceTest - 更新 REST 接口文档 Closes #296 --- docs/Integration/rest-api.md | 47 ++++ .../com/codingapi/flow/error/ErrorThrow.java | 98 +++++++- .../exception/FlowValidationException.java | 18 ++ .../codingapi/flow/node/BaseAuditNode.java | 9 + .../pojo/request/FlowPrecheckRequest.java | 60 +++++ .../flow/pojo/response/PrecheckNode.java | 79 ++++++ .../flow/script/ScriptDefaultConstants.java | 12 +- .../flow/script/node/ErrorTriggerScript.java | 78 +++++- .../codingapi/flow/service/FlowService.java | 16 ++ .../service/impl/FlowPrecheckService.java | 195 +++++++++++++++ .../flow/script/ErrorTriggerScriptTest.java | 153 ++++++++++-- .../flow/service/FlowPrecheckServiceTest.java | 227 ++++++++++++++++++ .../api/controller/FlowRecordController.java | 16 ++ 13 files changed, 972 insertions(+), 36 deletions(-) create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowPrecheckRequest.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/PrecheckNode.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowPrecheckService.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowPrecheckServiceTest.java diff --git a/docs/Integration/rest-api.md b/docs/Integration/rest-api.md index 9990a163..b1f66a10 100644 --- a/docs/Integration/rest-api.md +++ b/docs/Integration/rest-api.md @@ -39,11 +39,58 @@ operatorIdentity → 存在 → 校验后作为当前身份(空串 = 默认身 | POST | `/api/cmd/record/processNodes` | `FlowProcessNodeRequest` | `MultiResponse` | 流程流转节点预览 | | POST | `/api/cmd/record/create` | `FlowCreateRequest` | `SingleResponse` | 发起流程,返回首条记录 id | | POST | `/api/cmd/record/action` | `FlowActionRequest` | `SingleResponse` | 执行动作(通过/拒绝/加签/减签/委派/退回/转办/自定义/保存) | +| POST | `/api/cmd/record/precheck` | `FlowPrecheckRequest` | `MultiResponse` | 下一节点审批人预检(只读,见 §2.1) | | POST | `/api/cmd/record/subProcess/reset` | `FlowSubProcessResetRequest` | `Response` | 子流程数据重置(独立接口,需子流程节点开启重置能力) | | POST | `/api/cmd/record/urge` | `IdRequest` | `Response` | 催办 | | POST | `/api/cmd/record/revoke` | `IdRequest` | `Response` | 撤销 | | POST | `/api/cmd/record/delete` | `IdRequest` | `Response` | 删除(仅未流转实例,开始节点) | +### 2.1 下一节点预检(`/api/cmd/record/precheck`,issue #296) + +提交前预测**直接下一节点**的审批人来源,用于在发起/审批页提示用户或让用户补选人员。只读:不生成记录/待办、不写分配关系、不推事件。 + +请求 `FlowPrecheckRequest`: + +| 字段 | 说明 | +|---|---| +| `workCode` | 发起场景传流程编码 | +| `recordId` | 审批场景传当前待办记录 id(优先于 `workCode`) | +| `actionId` | 本次动作 id | +| `formData` | 表单数据,用于执行取人脚本与分支条件 | +| `operatorId` / `operatorIdentity` | 由接口层按当前会话注入 | + +响应 `PrecheckNode`(分支多时返回多条): + +| 字段 | 说明 | +|---|---| +| `nodeId` / `nodeName` / `nodeType` | 下一节点信息 | +| `selectType` | `SCRIPT` / `INITIATOR_SELECT` / `APPROVER_SELECT` | +| `resolved` | 审批人是否已确定 | +| `operators` | 已解析出的审批人 | +| `candidates` | 需要用户选择时的可选范围;为空表示不限范围 | +| `maxOperatorCount` | 最大可选人数,-1 不限 | +| `selectable` | 是否需要用户为该节点选择审批人 | +| `error` | 预检是否出现脚本异常(不中断调用方) | +| `message` | 透传的异常提示文案(`errorTrigger=prompt` 时) | + +判定口径: + +- `SCRIPT` 且取人脚本返回空 → `resolved=false`、`selectable=false`,`message` 为流程配置的提示文案; +- `INITIATOR_SELECT` / `APPROVER_SELECT` 且尚无分配数据 → `resolved=false`、`selectable=true`,`candidates` 为范围脚本结果; +- 预检不因人员为空抛业务异常,是否阻断由调用方决定。 + +### 2.2 异常触发(`errorTrigger`)的三种语义 + +`ErrorThrow` 按脚本返回值分流,历史写法保持兼容: + +| 脚本返回 | 类型 | 提交时行为 | +|---|---|---| +| `'节点id'` 或 `[type:'node', node:'节点id']` | NODE | 跳转到指定节点 | +| `[1,2]` / `1` 或 `[type:'operators', operators:[1,2]]` | OPERATORS | 使用指定人员兜底 | +| `[type:'prompt', message:'...']` | PROMPT | 阻断本次操作,抛 `validation.node.operatorEmpty` 并回滚 | + +默认脚本已改为 PROMPT(`ScriptDefaultConstants.SCRIPT_DEFAULT_ERROR_TRIGGER`),文案可由业务方实现 `IScriptRegistry#getErrorTriggerScript` 并调用 `ScriptRegistryContext#setRegistry` 覆盖。 + ## 3. 流程设计(`/api/cmd/workflow`) `flow-engine-starter-api/src/main/java/com/codingapi/flow/api/controller/WorkflowController.java` diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/error/ErrorThrow.java b/flow-engine-framework/src/main/java/com/codingapi/flow/error/ErrorThrow.java index b0be709d..4bb8af11 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/error/ErrorThrow.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/error/ErrorThrow.java @@ -3,31 +3,119 @@ import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; import lombok.Getter; -import lombok.Setter; import java.util.List; /** * 异常流程配置,在节点没有匹配到人员时触发 - * 异常时可以指定跳转到的节点或者指定默认的审批人员,两者二选一,优先以跳转的节点为准 + *

    + * 三种处理方式(issue #296): + *

      + *
    1. {@link Type#NODE}:跳转到指定节点;
    2. + *
    3. {@link Type#OPERATORS}:使用指定的默认审批人员;
    4. + *
    5. {@link Type#PROMPT}:不跳转也不兜底,阻断本次操作并把提示信息交给调用方展示。
    6. + *
    + * 前两种为历史能力,保持既有语义;{@link Type#PROMPT} 为新增语义,用于避免「静默回退到开始节点」 + * 造成发起人误以为流程已正常流转。 */ -@Setter @Getter public class ErrorThrow { + /** + * 异常处理类型 + */ + public enum Type { + /** + * 跳转节点 + */ + NODE, + /** + * 指定默认审批人员 + */ + OPERATORS, + /** + * 异常提示(阻断并提示) + */ + PROMPT + } + + /** + * 异常处理类型,未显式设置时由 {@link #isNode()} 等语义方法按字段推导 + */ + private Type type; + /** * 跳转的节点 */ private IFlowNode node; + /** * 默认审批人员 */ private List operators; /** - * 是否为节点 + * 异常提示信息,仅 {@link Type#PROMPT} 使用 + */ + private String message; + + public void setType(Type type) { + this.type = type; + } + + public void setNode(IFlowNode node) { + this.node = node; + if (node != null) { + this.type = Type.NODE; + } + } + + public void setOperators(List operators) { + this.operators = operators; + if (operators != null && !operators.isEmpty()) { + this.type = Type.OPERATORS; + } + } + + public void setMessage(String message) { + this.message = message; + if (this.node == null && (this.operators == null || this.operators.isEmpty())) { + this.type = Type.PROMPT; + } + } + + /** + * 创建异常提示结果 + * + * @param message 提示信息,为空时由调用方使用兜底文案 + * @return 异常提示配置 + */ + public static ErrorThrow prompt(String message) { + ErrorThrow errorThrow = new ErrorThrow(); + errorThrow.message = message; + // 即使文案为空也保持 PROMPT 语义:类型由配置决定,不由文案是否为空决定 + errorThrow.type = Type.PROMPT; + return errorThrow; + } + + /** + * 是否为节点跳转 */ public boolean isNode() { - return node!=null; + return node != null; + } + + /** + * 是否为异常提示 + */ + public boolean isPrompt() { + return type == Type.PROMPT; + } + + /** + * 是否指定了默认审批人员 + */ + public boolean hasOperators() { + return operators != null && !operators.isEmpty(); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java b/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java index 5d94d45d..f089295f 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java @@ -169,4 +169,22 @@ public static FlowValidationException invalidParameter(String fieldName, String return new FlowValidationException("validation.parameter." + fieldName, String.format("Parameter %s has invalid value '%s', expected %s", fieldName, value, expected)); } + + /** + * 节点未匹配到审批人且异常处理配置为「异常提示」,需要阻断本次操作(issue #296)。 + *

    + * 提示信息优先使用流程配置的文案;未配置时回落为带节点名称的默认文案。 + * + * @param nodeId 节点 id + * @param nodeName 节点名称 + * @param message 流程配置的提示信息,可为空 + * @return exception + */ + public static FlowValidationException nextNodeOperatorEmpty(String nodeId, String nodeName, String message) { + String text = (message == null || message.isBlank()) + ? String.format("No operator matched for node '%s' (id: %s), the flow cannot continue", + nodeName, nodeId) + : message; + return new FlowValidationException("validation.node.operatorEmpty", text); + } } 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 713a5ec4..edfccef6 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 @@ -234,6 +234,11 @@ private List generateCurrentRecords(FlowSession session, Set if(errorThrow==null){ throw FlowValidationException.nodeRequired("errorTrigger"); } + // 异常提示(issue #296):阻断本次操作并把提示信息交给调用方,避免默认「回退至开始节点」 + // 造成发起人误以为流程已正常流转 + if(errorThrow.isPrompt()){ + throw FlowValidationException.nextNodeOperatorEmpty(this.getId(), this.getName(), errorThrow.getMessage()); + } if(errorThrow.isNode()){ IFlowNode errorNode = errorThrow.getNode(); // 抄送/子流程节点不产生有效记录,跳转会静默停滞 @@ -251,6 +256,10 @@ private List generateCurrentRecords(FlowSession session, Set } return errorNode.generateCurrentRecords(errorSession); }else { + // 指定人员兜底:结果为空视为配置无效,否则会生成空记录让流程静默停滞 + if (!errorThrow.hasOperators()) { + throw FlowValidationException.nodeRequired("errorTrigger"); + } operatorManager = new OperatorManager(errorThrow.getOperators()); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowPrecheckRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowPrecheckRequest.java new file mode 100644 index 00000000..fb548b2c --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowPrecheckRequest.java @@ -0,0 +1,60 @@ +package com.codingapi.flow.pojo.request; + +import com.codingapi.flow.exception.FlowValidationException; +import lombok.Data; +import org.springframework.util.StringUtils; + +import java.util.Map; + +/** + * 流程预检请求(issue #296) + *

    + * 用于在发起或提交前预测直接下一节点的审批人,不产生任何写入。 + * 发起场景传 {@code workCode},审批场景传 {@code recordId};两者同时存在时以 {@code recordId} 为准。 + */ +@Data +public class FlowPrecheckRequest { + + /** + * 流程定义编码(发起场景) + */ + private String workCode; + + /** + * 当前待办记录 id(审批场景) + */ + private long recordId; + + /** + * 本次操作的动作 id,用于解析当前节点的动作上下文 + */ + private String actionId; + + /** + * 表单数据,用于执行取人脚本与分支条件 + */ + private Map formData; + + /** + * 操作者 id,由接口层注入 + */ + private long operatorId; + + /** + * 操作者身份标识,由接口层注入 + */ + private String operatorIdentity; + + /** + * 是否为发起场景 + */ + public boolean isCreateScene() { + return recordId <= 0; + } + + public void verify() { + if (recordId <= 0 && !StringUtils.hasText(workCode)) { + throw FlowValidationException.required("workCode"); + } + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/PrecheckNode.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/PrecheckNode.java new file mode 100644 index 00000000..1ebad116 --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/PrecheckNode.java @@ -0,0 +1,79 @@ +package com.codingapi.flow.pojo.response; + +import com.codingapi.flow.operator.IFlowOperator; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +/** + * 下一节点审批人预检结果(issue #296) + *

    + * 用于把「下一节点的人从哪来、是否已确定、还需要谁选」如实告诉调用方: + *

      + *
    • {@code SCRIPT}:人员由取人脚本解析,{@code resolved=true} 时 {@code operators} 有值;
    • + *
    • {@code INITIATOR_SELECT} / {@code APPROVER_SELECT}:人员尚未指定时 + * {@code resolved=false}、{@code selectable=true},{@code candidates} 为可选范围 + * (为空表示不限范围,可选任意人)。
    • + *
    + * 预检只读,不生成记录、不推送事件,也不因人员为空抛业务异常; + * {@code message} 仅透传流程配置的异常提示文案。 + */ +@Data +public class PrecheckNode { + + /** + * 节点 id + */ + private String nodeId; + + /** + * 节点名称 + */ + private String nodeName; + + /** + * 节点类型 + */ + private String nodeType; + + /** + * 操作人选择方式:SCRIPT / INITIATOR_SELECT / APPROVER_SELECT + */ + private String selectType; + + /** + * 审批人是否已确定 + */ + private boolean resolved; + + /** + * 已确定/解析出的审批人 + */ + private List operators = new ArrayList<>(); + + /** + * 可选人员范围,仅 {@code resolved=false} 且需要用户选择时有意义;为空表示不限范围 + */ + private List candidates = new ArrayList<>(); + + /** + * 最大可选人数,-1 表示不限制 + */ + private int maxOperatorCount = -1; + + /** + * 是否需要用户为该节点选择审批人 + */ + private boolean selectable; + + /** + * 预检过程是否出现异常(脚本执行失败等),异常不会中断其余节点 + */ + private boolean error; + + /** + * 异常提示文案或预检失败原因 + */ + private String message; +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/ScriptDefaultConstants.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/ScriptDefaultConstants.java index 1b944ae5..c4632d3d 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/ScriptDefaultConstants.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/ScriptDefaultConstants.java @@ -48,13 +48,17 @@ def run(request){ """; /** - * 默认异常触发脚本 + * 默认异常触发脚本(issue #296) + *

    + * 默认行为为「异常提示」:不跳转、不兜底,阻断本次操作并提示用户,避免历史默认的 + * 「回退至开始节点」让发起人误以为流程已正常流转。业务方可通过 + * {@code ScriptRegistryContext#setRegistry} 覆盖文案或改为指定节点/指定人员。 */ public static final String SCRIPT_DEFAULT_ERROR_TRIGGER = """ - // @SCRIPT_TITLE 回退至开始节点 - // @SCRIPT_META {"type":"node","node":"START"} + // @SCRIPT_TITLE 异常提示 + // @SCRIPT_META {"type":"prompt"} def run(request){ - return request.getStartNode().getId(); + return [type:'prompt', message:'流程未匹配到审批人,无法继续处理,请联系流程管理员'] } """; diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/ErrorTriggerScript.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/ErrorTriggerScript.java index d95b6157..7b53600d 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/ErrorTriggerScript.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/ErrorTriggerScript.java @@ -19,6 +19,16 @@ /** * 异常触发脚本 + *

    + * 返回值支持四种写法(issue #296): + *

      + *
    • {@code Map}:{@code [type:'prompt', message:'...']} 异常提示,或 {@code [type:'node', node:'节点id']} / + * {@code [type:'operators', operators:[1,2]]} 显式声明类型;
    • + *
    • {@code String}:跳转节点 id(历史写法);
    • + *
    • {@code List}:默认审批人员 id 列表(历史写法);
    • + *
    • {@code Number}:单个默认审批人员 id(历史写法)。
    • + *
    + * 历史写法全部保持兼容。 */ @AllArgsConstructor public class ErrorTriggerScript { @@ -32,21 +42,16 @@ public ErrorThrow execute(FlowSession session) { Object value = FlowScriptRuntimeContext.getInstance() .getGroovyScript(script) .invoke(Map.of("$bind", new GroovyScriptBind(FlowScriptContext.getInstance())), request); - if(value instanceof String){ - String nodeId = (String) value; + if (value instanceof Map map) { + return parseMap(session, map); + } + if (value instanceof String nodeId) { ErrorThrow errorThrow = new ErrorThrow(); errorThrow.setNode(session.getNode(nodeId)); return errorThrow; } - if(value instanceof List){ - List userIds =(List) value; - List operatorIds = new ArrayList<>(); - for(Object userId:userIds){ - operatorIds.add(Long.parseLong(String.valueOf(userId))); - } - ErrorThrow errorThrow = new ErrorThrow(); - errorThrow.setOperators(session.getRepositoryHolder().findOperatorByIds(operatorIds)); - return errorThrow; + if (value instanceof List userIds) { + return parseOperators(session, userIds); } long userId = Long.parseLong(String.valueOf(value)); @@ -58,6 +63,57 @@ public ErrorThrow execute(FlowSession session) { } + /** + * 解析 Map 形式的返回值 + * + * @param session 当前会话 + * @param map 脚本返回值 + * @return 异常处理配置 + */ + private ErrorThrow parseMap(FlowSession session, Map map) { + String type = map.get("type") == null ? null : String.valueOf(map.get("type")); + if (ErrorThrow.Type.PROMPT.name().equalsIgnoreCase(type) || "prompt".equalsIgnoreCase(type)) { + Object message = map.get("message"); + return ErrorThrow.prompt(message == null ? null : String.valueOf(message)); + } + if (ErrorThrow.Type.NODE.name().equalsIgnoreCase(type)) { + Object nodeId = map.get("node"); + ErrorThrow errorThrow = new ErrorThrow(); + errorThrow.setNode(nodeId == null ? null : session.getNode(String.valueOf(nodeId))); + return errorThrow; + } + if (ErrorThrow.Type.OPERATORS.name().equalsIgnoreCase(type)) { + Object operators = map.get("operators"); + if (operators instanceof List userIds) { + return parseOperators(session, userIds); + } + return new ErrorThrow(); + } + // 未声明 type 时按字段存在性推断:message 优先(提示),其次 node,最后 operators + if (map.get("message") != null) { + return ErrorThrow.prompt(String.valueOf(map.get("message"))); + } + if (map.get("node") != null) { + ErrorThrow errorThrow = new ErrorThrow(); + errorThrow.setNode(session.getNode(String.valueOf(map.get("node")))); + return errorThrow; + } + if (map.get("operators") instanceof List userIds) { + return parseOperators(session, userIds); + } + return new ErrorThrow(); + } + + private ErrorThrow parseOperators(FlowSession session, List userIds) { + List operatorIds = new ArrayList<>(); + for (Object userId : userIds) { + operatorIds.add(Long.parseLong(String.valueOf(userId))); + } + ErrorThrow errorThrow = new ErrorThrow(); + errorThrow.setOperators(session.getRepositoryHolder().findOperatorByIds(operatorIds)); + return errorThrow; + } + /** * 默认节点脚本 */ 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 547fa3dc..1d8a1b9a 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 @@ -6,6 +6,7 @@ import com.codingapi.flow.pojo.response.ActionResponse; import com.codingapi.flow.pojo.response.FlowContent; import com.codingapi.flow.pojo.response.FlowForceSyncResult; +import com.codingapi.flow.pojo.response.PrecheckNode; import com.codingapi.flow.pojo.response.ProcessNode; import com.codingapi.flow.service.impl.*; import com.codingapi.flow.session.IRepositoryHolder; @@ -79,6 +80,21 @@ public ActionResponse action(FlowActionRequest request) { return flowActionService.action(); } + /** + * 流程预检(issue #296) + *

    + * 预测直接下一节点的审批人来源,供发起/审批前提示用户;只读,不产生记录、待办、分配关系与事件。 + * + * @param request 预检请求(发起场景传 workCode,审批场景传 recordId) + * @return 下一节点预检结果 + */ + public List precheck(FlowPrecheckRequest request) { + FlowOperatorLocalThreadCache.getInstance().clear(); + FlowRuntimeScriptLocalCache.getInstance().clear(); + FlowPrecheckService flowPrecheckService = new FlowPrecheckService(request, this.repositoryHolder); + return flowPrecheckService.precheck(); + } + /** * 撤销流程 * diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowPrecheckService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowPrecheckService.java new file mode 100644 index 00000000..8310b75b --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowPrecheckService.java @@ -0,0 +1,195 @@ +package com.codingapi.flow.service.impl; + +import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.cache.FlowRuntimeScriptLocalCache; +import com.codingapi.flow.error.ErrorThrow; +import com.codingapi.flow.exception.FlowNotFoundException; +import com.codingapi.flow.exception.FlowPermissionException; +import com.codingapi.flow.exception.FlowStateException; +import com.codingapi.flow.form.FormData; +import com.codingapi.flow.gateway.FlowOperatorGateway; +import com.codingapi.flow.manager.OperatorManager; +import com.codingapi.flow.node.IFlowNode; +import com.codingapi.flow.node.nodes.StartNode; +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentityGuard; +import com.codingapi.flow.pojo.request.FlowPrecheckRequest; +import com.codingapi.flow.pojo.response.PrecheckNode; +import com.codingapi.flow.record.FlowRecord; +import com.codingapi.flow.service.FlowRecordService; +import com.codingapi.flow.service.WorkflowService; +import com.codingapi.flow.session.FlowAdvice; +import com.codingapi.flow.session.FlowSession; +import com.codingapi.flow.session.IRepositoryHolder; +import com.codingapi.flow.strategy.node.OperatorSelectType; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.runtime.WorkflowRuntime; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * 流程预检服务(issue #296) + *

    + * 预测直接下一节点的审批人来源,供发起页/审批页在提交前提示用户。 + * 只复用取人脚本与人员范围脚本的既有能力,不生成记录、不推送事件、不写分配关系, + * 也不因为人员为空抛业务异常——空结果本身就是要交给业务层展示的信息。 + */ +public class FlowPrecheckService { + + private final FlowPrecheckRequest request; + private final IRepositoryHolder repositoryHolder; + private final FlowOperatorGateway flowOperatorGateway; + private final FlowRecordService flowRecordService; + private final WorkflowService workflowService; + + public FlowPrecheckService(FlowPrecheckRequest request, IRepositoryHolder repositoryHolder) { + this.request = request; + this.repositoryHolder = repositoryHolder; + this.flowOperatorGateway = repositoryHolder.getFlowOperatorGateway(); + this.flowRecordService = repositoryHolder.getFlowRecordService(); + this.workflowService = repositoryHolder.getWorkflowService(); + } + + public List precheck() { + request.verify(); + FlowSession session = request.isCreateScene() ? createSession() : actionSession(); + List nextNodes = session.matchNextNodes(); + if (nextNodes == null || nextNodes.isEmpty()) { + return List.of(); + } + List result = new ArrayList<>(nextNodes.size()); + for (IFlowNode nextNode : nextNodes) { + result.add(inspect(nextNode, session)); + } + return result; + } + + /** + * 发起场景:与 {@code FlowCreateService} 同口径地构建会话,但不保存任何数据。 + */ + private FlowSession createSession() { + Workflow workflow = workflowService.getWorkflowByCode(request.getWorkCode()); + if (workflow == null) { + throw FlowNotFoundException.workflow(request.getWorkCode()); + } + if (workflow.isDisable()) { + throw FlowStateException.workflowAlreadyDisable(request.getWorkCode()); + } + workflow.verify(); + // 预检只读:运行时快照不存在时就地构造,不落库(getOrCreate 会写入) + WorkflowRuntime workflowRuntime = workflowService.getWorkflowRuntime(workflow.getId(), workflow.getUpdatedTime()); + if (workflowRuntime == null) { + workflowRuntime = new WorkflowRuntime(workflow); + } + FlowRuntimeScriptLocalCache.getInstance().set(workflowRuntime.getScripts()); + + IFlowOperator currentOperator = loadCurrentOperator(); + if (!workflow.matchCreatedOperator(currentOperator)) { + throw FlowPermissionException.accessDenied("create workflow"); + } + FormData formData = new FormData(workflow.getForm()); + formData.reset(request.getFormData() == null ? Map.of() : request.getFormData()); + + StartNode startNode = (StartNode) workflow.getStartNode(); + IFlowAction action = startNode.actionManager().getActionById(request.getActionId()); + return FlowSession.startSession(repositoryHolder, currentOperator, workflow, startNode, action, + formData, workflowRuntime.getId()); + } + + /** + * 审批场景:只能预检当前用户有权办理的待办,避免越权读取下游人员信息。 + */ + private FlowSession actionSession() { + FlowRecord flowRecord = flowRecordService.getFlowRecord(request.getRecordId()); + if (flowRecord == null) { + throw FlowNotFoundException.record(request.getRecordId()); + } + if (!flowRecord.isTodo()) { + throw FlowStateException.recordAlreadyDone(); + } + IFlowOperator currentOperator = loadCurrentOperator(); + + WorkflowRuntime workflowRuntime = workflowService.getWorkflowRuntime(flowRecord.getWorkRuntimeId()); + if (workflowRuntime == null) { + throw FlowNotFoundException.workflow(flowRecord.getWorkRuntimeId() + " not found"); + } + FlowRuntimeScriptLocalCache.getInstance().set(workflowRuntime.getScripts()); + Workflow workflow = workflowRuntime.toWorkflow(); + + workflow.strategyManager().verifyOperator(currentOperator, flowRecord.getCurrentOperatorId(), + flowRecord.getCurrentOperatorIdentity()); + + IFlowNode currentNode = workflow.getFlowNode(flowRecord.getNodeId()); + if (currentNode == null) { + throw FlowNotFoundException.node(flowRecord.getNodeId()); + } + IFlowOperator createdOperator = flowOperatorGateway.get(flowRecord.getCreateOperatorId(), + flowRecord.getCreateOperatorIdentity()); + OperatorIdentityGuard.check(flowRecord.getCreateOperatorId(), + flowRecord.getCreateOperatorIdentity(), createdOperator); + + FormData formData = new FormData(workflow.getForm()); + Map data = request.getFormData() != null + ? request.getFormData() + : (flowRecord.getFormData() == null ? Map.of() : flowRecord.getFormData()); + formData.reset(data); + + FlowAdvice advice = new FlowAdvice(); + advice.setAction(currentNode.actionManager().getActionById(request.getActionId())); + return flowRecord.createFlowSession(repositoryHolder, workflow, currentOperator, createdOperator, + currentOperator, formData, advice); + } + + private IFlowOperator loadCurrentOperator() { + IFlowOperator currentOperator = flowOperatorGateway.get(request.getOperatorId(), request.getOperatorIdentity()); + OperatorIdentityGuard.check(request.getOperatorId(), request.getOperatorIdentity(), currentOperator); + if (currentOperator == null) { + throw FlowNotFoundException.operator(request.getOperatorId()); + } + return currentOperator; + } + + /** + * 检查单个下一节点:人员从哪来、是否已确定、是否需要用户选择。 + */ + private PrecheckNode inspect(IFlowNode node, FlowSession session) { + PrecheckNode result = new PrecheckNode(); + result.setNodeId(node.getId()); + result.setNodeName(node.getName()); + result.setNodeType(node.getType()); + OperatorSelectType selectType = node.strategyManager().getOperatorSelectType(); + OperatorSelectType actualSelectType = selectType == null ? OperatorSelectType.SCRIPT : selectType; + result.setSelectType(actualSelectType.name()); + result.setMaxOperatorCount(node.strategyManager().getMaxOperatorCount()); + + FlowSession nodeSession = session.updateSession(node); + try { + OperatorManager operatorManager = node.strategyManager().loadOperators(nodeSession); + if (!operatorManager.isEmpty()) { + result.setResolved(true); + result.setOperators(operatorManager.getOperators()); + return result; + } + if (actualSelectType == OperatorSelectType.INITIATOR_SELECT + || actualSelectType == OperatorSelectType.APPROVER_SELECT) { + // 设定模式在提交前本就没有分配数据,返回可选范围让业务方渲染选择器; + // 范围为空表示不限范围(可选任意人) + result.setCandidates(node.strategyManager().loadOperatorRange(nodeSession)); + result.setSelectable(true); + return result; + } + // 脚本模式取人为空:透传「异常提示」文案,预检本身不阻断 + ErrorThrow errorThrow = node.strategyManager().errorTrigger(nodeSession); + if (errorThrow != null && errorThrow.isPrompt()) { + result.setMessage(errorThrow.getMessage()); + } + } catch (Exception e) { + // 预检不中断调用方:单个节点脚本异常以结果形式返回 + result.setError(true); + result.setMessage(e.getMessage()); + } + return result; + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/script/ErrorTriggerScriptTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/script/ErrorTriggerScriptTest.java index fbe455da..5089edee 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/script/ErrorTriggerScriptTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/script/ErrorTriggerScriptTest.java @@ -3,37 +3,51 @@ import com.codingapi.flow.builder.FormFieldPermissionsBuilder; import com.codingapi.flow.builder.NodeStrategyBuilder; import com.codingapi.flow.error.ErrorThrow; +import com.codingapi.flow.factory.MyFlowServiceFactory; import com.codingapi.flow.form.DataType; import com.codingapi.flow.form.FlowForm; -import com.codingapi.flow.form.FormData; import com.codingapi.flow.form.FlowFormBuilder; +import com.codingapi.flow.form.FormData; import com.codingapi.flow.form.permission.PermissionType; 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.script.factory.FlowGroovyScriptFactory; import com.codingapi.flow.script.node.ErrorTriggerScript; -import com.codingapi.flow.factory.MyFlowServiceFactory; +import com.codingapi.flow.script.registry.DefaultScriptRegistry; +import com.codingapi.flow.script.registry.IScriptRegistry; +import com.codingapi.flow.script.registry.ScriptRegistryContext; import com.codingapi.flow.session.FlowSession; 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 org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +/** + * 异常触发脚本测试(issue #296) + *

    + * 覆盖四种返回值解析、默认脚本的「异常提示」语义,以及业务方通过脚本注册中心覆盖默认文案。 + */ class ErrorTriggerScriptTest { private final MyFlowServiceFactory factory = new MyFlowServiceFactory(); + private IScriptRegistry originRegistry; + private FlowSession flowSession; + private User user; - @Test - void execute() { - User user = new User(1, "lorne"); + @BeforeEach + void setUp() { + originRegistry = ScriptRegistryContext.getInstance().getRegistry(); + user = new User(1, "lorne"); factory.userGateway.save(user); FlowForm form = FlowFormBuilder.builder() @@ -85,22 +99,129 @@ void execute() { FormData data = new FormData(form); data.getDataBody().set("name", "张三").set("days", 10).set("reason", "事由"); - FlowSession flowSession = FlowSession.startSession(factory.repositoryHolder,user, workflow, startNode, startNode.getActions().get(0), data, 0); + flowSession = FlowSession.startSession(factory.repositoryHolder, user, workflow, startNode, + startNode.getActions().get(0), data, 0); + } + + @AfterEach + void tearDown() { + if (originRegistry != null) { + ScriptRegistryContext.getInstance().setRegistry(originRegistry); + } + } + + /** + * 默认脚本返回异常提示,不再静默回退到开始节点 + */ + @Test + void should_return_prompt_when_default_script_executed() { + ErrorThrow errorThrow = ErrorTriggerScript.defaultScript().execute(flowSession); + + assertTrue(errorThrow.isPrompt()); + assertFalse(errorThrow.isNode()); + assertFalse(errorThrow.hasOperators()); + assertNotNull(errorThrow.getMessage()); + assertTrue(errorThrow.getMessage().contains("审批人")); + } + + /** + * 历史写法:返回节点 id 时仍按节点跳转解析 + */ + @Test + void should_parse_node_when_script_returns_string() { + String script = """ + def run(request){ + return request.getStartNode().getId(); + } + """; + ErrorTriggerScript errorTriggerScript = new ErrorTriggerScript( + FlowGroovyScriptFactory.createErrorTriggerScript(script).getKey()); + + ErrorThrow errorThrow = errorTriggerScript.execute(flowSession); - ErrorTriggerScript errorNodeTriggerScript = ErrorTriggerScript.defaultScript(); - ErrorThrow errorThrow = errorNodeTriggerScript.execute(flowSession); assertTrue(errorThrow.isNode()); - assertEquals(startNode.getId(), errorThrow.getNode().getId()); + assertEquals(flowSession.getWorkflow().getStartNode().getId(), errorThrow.getNode().getId()); + } + /** + * 历史写法:返回人员 id 列表时按默认审批人兜底 + */ + @Test + void should_parse_operators_when_script_returns_list() { String script = """ - def run(request){ - return request.getCreatedOperatorId(); - } - """; + def run(request){ + return [request.getCreatedOperatorId()]; + } + """; + ErrorTriggerScript errorTriggerScript = new ErrorTriggerScript( + FlowGroovyScriptFactory.createErrorTriggerScript(script).getKey()); + + ErrorThrow errorThrow = errorTriggerScript.execute(flowSession); - ErrorTriggerScript errorOperatorTriggerScript = new ErrorTriggerScript(FlowGroovyScriptFactory.createErrorTriggerScript(script).getKey()); - errorThrow = errorOperatorTriggerScript.execute(flowSession); assertFalse(errorThrow.isNode()); + assertFalse(errorThrow.isPrompt()); assertEquals(user, errorThrow.getOperators().get(0)); } -} \ No newline at end of file + + /** + * 历史写法:返回单个人员 id 时按默认审批人兜底 + */ + @Test + void should_parse_operator_when_script_returns_number() { + String script = """ + def run(request){ + return request.getCreatedOperatorId(); + } + """; + ErrorTriggerScript errorTriggerScript = new ErrorTriggerScript( + FlowGroovyScriptFactory.createErrorTriggerScript(script).getKey()); + + ErrorThrow errorThrow = errorTriggerScript.execute(flowSession); + + assertFalse(errorThrow.isNode()); + assertFalse(errorThrow.isPrompt()); + assertEquals(user, errorThrow.getOperators().get(0)); + } + + /** + * 新写法:Map 形式声明异常提示与文案 + */ + @Test + void should_parse_prompt_when_script_returns_map() { + String script = """ + def run(request){ + return [type:'prompt', message:'下一节点没有可用审批人']; + } + """; + ErrorTriggerScript errorTriggerScript = new ErrorTriggerScript( + FlowGroovyScriptFactory.createErrorTriggerScript(script).getKey()); + + ErrorThrow errorThrow = errorTriggerScript.execute(flowSession); + + assertTrue(errorThrow.isPrompt()); + assertEquals("下一节点没有可用审批人", errorThrow.getMessage()); + } + + /** + * 业务方可以整体替换默认提示文案,而不只是改配置项 + */ + @Test + void should_use_custom_default_message_when_registry_overridden() { + ScriptRegistryContext.getInstance().setRegistry(new DefaultScriptRegistry() { + @Override + public String getErrorTriggerScript() { + String script = """ + def run(request){ + return [type:'prompt', message:'业务方自定义提示:请联系流程管理员']; + } + """; + return FlowGroovyScriptFactory.createErrorTriggerScript(script).getKey(); + } + }); + + ErrorThrow errorThrow = ErrorTriggerScript.defaultScript().execute(flowSession); + + assertTrue(errorThrow.isPrompt()); + assertEquals("业务方自定义提示:请联系流程管理员", errorThrow.getMessage()); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowPrecheckServiceTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowPrecheckServiceTest.java new file mode 100644 index 00000000..66e39a7f --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowPrecheckServiceTest.java @@ -0,0 +1,227 @@ +package com.codingapi.flow.service; + +import com.codingapi.flow.builder.NodeStrategyBuilder; +import com.codingapi.flow.exception.FlowValidationException; +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.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.FlowPrecheckRequest; +import com.codingapi.flow.pojo.response.PrecheckNode; +import com.codingapi.flow.strategy.node.OperatorLoadStrategy; +import com.codingapi.flow.strategy.node.OperatorSelectType; +import com.codingapi.flow.user.User; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.WorkflowBuilder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * 流程预检测试(issue #296) + *

    + * 覆盖三种取人方式的预检结果、只读约束,以及「异常提示」在提交时的阻断行为。 + */ +class FlowPrecheckServiceTest { + + private MyFlowServiceFactory factory; + private User creator; + private User approver; + + @BeforeEach + void setUp() { + factory = new MyFlowServiceFactory(); + creator = new User(1, "发起人"); + approver = new User(2, "审批人"); + factory.userGateway.save(creator); + factory.userGateway.save(approver); + } + + private Map formData() { + return Map.of("title", "预检测试"); + } + + private Workflow buildWorkflow(String code, OperatorLoadStrategy approvalStrategy) { + FlowForm form = FlowFormBuilder.builder() + .name("预检流程") + .code(code) + .addField("标题", "title", DataType.STRING) + .build(); + + StartNode startNode = StartNode.builder().build(); + ApprovalNode approvalNode = ApprovalNode.builder() + .name("审批节点") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(approvalStrategy) + .build()) + .build(); + EndNode endNode = EndNode.builder().build(); + + Workflow workflow = WorkflowBuilder.builder() + .title("预检流程") + .code(code) + .createdOperator(creator) + .form(form) + .addNode(startNode) + .addNode(approvalNode) + .addNode(endNode) + .build(); + factory.workflowService.saveWorkflow(workflow); + return workflow; + } + + private FlowPrecheckRequest createSceneRequest(Workflow workflow) { + FlowPrecheckRequest request = new FlowPrecheckRequest(); + request.setWorkCode(workflow.getCode()); + request.setActionId(workflow.getStartNode().actionManager().getActions().get(0).id()); + request.setFormData(formData()); + request.setOperatorId(creator.getUserId()); + return request; + } + + private long createAtStartNode(Workflow workflow) { + FlowCreateRequest createRequest = new FlowCreateRequest(); + createRequest.setWorkCode(workflow.getCode()); + createRequest.setFormData(formData()); + createRequest.setActionId(workflow.getStartNode().actionManager().getActions().get(0).id()); + createRequest.setOperatorId(creator.getUserId()); + return factory.flowService.create(createRequest); + } + + /** + * 脚本模式已解析出人员:resolved=true,operators 有值,无需用户选择 + */ + @Test + void should_resolve_operators_when_script_matched() { + Workflow workflow = buildWorkflow("precheck-script", + new OperatorLoadStrategy("def run(request){return [2]}")); + + List nodes = factory.flowService.precheck(createSceneRequest(workflow)); + + assertEquals(1, nodes.size()); + PrecheckNode node = nodes.get(0); + assertEquals(OperatorSelectType.SCRIPT.name(), node.getSelectType()); + assertTrue(node.isResolved()); + assertFalse(node.isSelectable()); + assertEquals(1, node.getOperators().size()); + assertEquals(approver.getUserId(), node.getOperators().get(0).getUserId()); + } + + /** + * 脚本模式未匹配到人员:resolved=false,并透传默认的异常提示文案(预检本身不抛异常) + */ + @Test + void should_return_prompt_message_when_script_matched_nothing() { + Workflow workflow = buildWorkflow("precheck-empty", + new OperatorLoadStrategy("def run(request){return []}")); + + List nodes = factory.flowService.precheck(createSceneRequest(workflow)); + + assertEquals(1, nodes.size()); + PrecheckNode node = nodes.get(0); + assertFalse(node.isResolved()); + assertFalse(node.isSelectable()); + assertTrue(node.getOperators().isEmpty()); + assertNotNull(node.getMessage()); + assertTrue(node.getMessage().contains("审批人")); + } + + /** + * 发起人设定:尚无分配数据,返回可选范围并标记需要用户选择 + */ + @Test + void should_return_candidates_when_initiator_select() { + Workflow workflow = buildWorkflow("precheck-initiator", + OperatorLoadStrategy.initiatorSelectStrategy("def run(request){return [2]}", 1)); + + List nodes = factory.flowService.precheck(createSceneRequest(workflow)); + + assertEquals(1, nodes.size()); + PrecheckNode node = nodes.get(0); + assertEquals(OperatorSelectType.INITIATOR_SELECT.name(), node.getSelectType()); + assertFalse(node.isResolved()); + assertTrue(node.isSelectable()); + assertEquals(1, node.getMaxOperatorCount()); + assertEquals(1, node.getCandidates().size()); + assertEquals(approver.getUserId(), node.getCandidates().get(0).getUserId()); + } + + /** + * 审批人设定:同样返回可选范围,语义与发起人设定一致 + */ + @Test + void should_return_candidates_when_approver_select() { + Workflow workflow = buildWorkflow("precheck-approver", + OperatorLoadStrategy.approverSelectStrategy("def run(request){return [2]}", 1)); + + List nodes = factory.flowService.precheck(createSceneRequest(workflow)); + + assertEquals(1, nodes.size()); + PrecheckNode node = nodes.get(0); + assertEquals(OperatorSelectType.APPROVER_SELECT.name(), node.getSelectType()); + assertFalse(node.isResolved()); + assertTrue(node.isSelectable()); + assertEquals(1, node.getCandidates().size()); + } + + /** + * 审批场景按 recordId 预检直接下一节点,且不产生任何记录/待办 + */ + @Test + void should_precheck_next_node_by_record_and_keep_readonly() { + Workflow workflow = buildWorkflow("precheck-record", + new OperatorLoadStrategy("def run(request){return [2]}")); + long recordId = createAtStartNode(workflow); + + int todoBefore = factory.flowRecordRepository.findTodoByOperator(creator.getUserId()).size(); + int todoRecordBefore = factory.flowTodoRecordRepository.findByOperatorId(creator.getUserId()).size(); + + FlowPrecheckRequest request = new FlowPrecheckRequest(); + request.setRecordId(recordId); + request.setActionId(workflow.getStartNode().actionManager().getActions().get(0).id()); + request.setFormData(formData()); + request.setOperatorId(creator.getUserId()); + + List nodes = factory.flowService.precheck(request); + + assertEquals(1, nodes.size()); + assertTrue(nodes.get(0).isResolved()); + // 只读:预检前后记录与待办数量不变 + assertEquals(todoBefore, factory.flowRecordRepository.findTodoByOperator(creator.getUserId()).size()); + assertEquals(todoRecordBefore, factory.flowTodoRecordRepository.findByOperatorId(creator.getUserId()).size()); + } + + /** + * 默认异常处理为「异常提示」:提交时直接阻断并抛出带文案的业务异常,不再静默回退到开始节点 + */ + @Test + void should_block_action_when_next_node_has_no_operator_and_prompt_configured() { + Workflow workflow = buildWorkflow("precheck-block", + new OperatorLoadStrategy("def run(request){return []}")); + long recordId = createAtStartNode(workflow); + + FlowActionRequest actionRequest = new FlowActionRequest(); + actionRequest.setRecordId(recordId); + actionRequest.setFormData(formData()); + actionRequest.setAdvice(new FlowAdviceBody( + workflow.getStartNode().actionManager().getActions().get(0).id(), "同意", creator.getUserId())); + + FlowValidationException exception = assertThrows(FlowValidationException.class, + () -> factory.flowService.action(actionRequest)); + + assertNotNull(exception.getMessage()); + assertTrue(exception.getMessage().contains("审批人")); + // 流程没有被推进到下一节点:不存在审批人的待办 + assertTrue(factory.flowRecordRepository.findTodoByOperator(approver.getUserId()).isEmpty()); + } +} 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 d54cd745..0396aa0c 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 @@ -8,6 +8,7 @@ import com.codingapi.flow.pojo.response.ActionResponse; import com.codingapi.flow.pojo.response.FlowContent; import com.codingapi.flow.pojo.response.FlowForceSyncResult; +import com.codingapi.flow.pojo.response.PrecheckNode; import com.codingapi.flow.pojo.response.ProcessNode; import com.codingapi.flow.service.FlowService; import com.codingapi.springboot.framework.dto.request.IdRequest; @@ -138,6 +139,21 @@ public SingleResponse action(@RequestBody FlowActionRequest requ return SingleResponse.of(response); } + /** + * 下一节点审批人预检(issue #296)。 + *

    + * 发起场景传 {@code workCode},审批场景传 {@code recordId};只预测直接下一节点, + * 只读不写,人员为空也不抛业务异常,由调用方根据 {@code selectType} / {@code resolved} + * / {@code candidates} / {@code message} 决定提示或补选。

    + */ + @PostMapping("/precheck") + public MultiResponse precheck(@RequestBody FlowPrecheckRequest request) { + FlowService flowService = this.loadFlowService(); + request.setOperatorId(loadCurrentOperatorId()); + request.setOperatorIdentity(loadCurrentOperatorIdentity()); + return MultiResponse.of(flowService.precheck(request)); + } + /** * 子流程数据重置(独立接口,不属于常规审批动作)。 *

    仅当子流程节点开启重置能力且当前记录位于其下游时可调用, From 6d924191816113886bc0addf629759a165f08e2e Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Wed, 2 Dec 2026 20:29:03 +0800 Subject: [PATCH 18/35] =?UTF-8?q?docs(#296):=20=E8=A1=A5=E5=85=85=E9=A2=84?= =?UTF-8?q?=E6=A3=80=E8=83=BD=E5=8A=9B=E6=96=87=E6=A1=A3=E4=B8=8E=E5=BC=82?= =?UTF-8?q?=E5=B8=B8=E6=8F=90=E7=A4=BA=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 capabilities/flow-engine-framework/flow-precheck.md,说明预检语义、返回结构与只读约束 - script.md 补充 errorTrigger 四种返回格式与 prompt 处理方式 - flow-service.md 入口表补 precheck - extension-points.md 补 ErrorThrow 三种类型与 nextNodeOperatorEmpty - 同步 capabilities 索引 Refs #296 --- docs/Integration/extension-points.md | 4 +- .../flow-engine-framework/flow-precheck.md | 80 +++++++++++++++++++ .../flow-engine-framework/flow-service.md | 3 +- .../flow-engine-framework/script.md | 13 +++ docs/capabilities/index.md | 3 +- 5 files changed, 99 insertions(+), 4 deletions(-) create mode 100644 docs/capabilities/flow-engine-framework/flow-precheck.md diff --git a/docs/Integration/extension-points.md b/docs/Integration/extension-points.md index 7d669f2f..b859af94 100644 --- a/docs/Integration/extension-points.md +++ b/docs/Integration/extension-points.md @@ -145,7 +145,7 @@ IFlowAction#run | 类 | 用途 | |---|---| -| `NodeStrategyManager` | 节点全部策略的门面:`loadOperators(session)`、`getMaxOperatorCount()`、`getOperatorSelectType()`、`generateTitle(session)`、`errorTrigger(session)`、`getFieldPermissions()`、`isAdviceRequired()` 等 | +| `NodeStrategyManager` | 节点全部策略的门面:`loadOperators(session)`、`getMaxOperatorCount()`、`getOperatorSelectType()`、`generateTitle(session)`、`errorTrigger(session)`(返回 `ErrorThrow`,含 `NODE` / `OPERATORS` / `PROMPT` 三种处理方式)、`getFieldPermissions()`、`isAdviceRequired()` 等 | | `ActionManager` | 动作管理:`filterActions(session)`、`getActionById(id)`、`getActionByType(type)`、`verifySession(session)` | | `OperatorManager` | 操作人集合:`isEmpty()`、`match(operator)`、`getOperator(userId)` | | `WorkflowStrategyManager` | 流程策略:`isEnableInterfere()`、`verifyOperator` | @@ -157,7 +157,7 @@ IFlowAction#run | 子类 | 典型工厂方法与错误场景 | |---|---| -| `FlowValidationException` | `fieldReadOnly`(字段只读)、`operatorCountExceeded(nodeId, max)`(超出最大可选人数)、`operatorOutOfRange`(超出可选范围)、`required` 等 | +| `FlowValidationException` | `fieldReadOnly`(字段只读)、`operatorCountExceeded(nodeId, max)`(超出最大可选人数)、`operatorOutOfRange`(超出可选范围)、`nextNodeOperatorEmpty(nodeId, nodeName, message)`(下一节点无审批人且配置为异常提示,issue #296)、`required` 等 | | `FlowExecutionException` | `scriptExecutionError`、`routerNodeNotFound`、`operatorCountExceeded`、`invalidJumpTarget(nodeType)`、`errorTriggerLoop`、`subProcessLoop`、`addAuditOperatorAlreadyInTodo`、`reduceAuditSingleApprover`、`reduceAuditTargetNotFound` 等 | | `FlowStateException` | `repositoryNotRegistered`、`recordAlreadyDone`、`operatorNotMatch`、`workflowAlreadyDisable`、`recordNotSupportRevoke` 等 | | `FlowNotFoundException` | `workflow(workCode)`、`record(recordId)`、`node(nodeId)`、`operator(operatorId)`、`action(actionId)` | diff --git a/docs/capabilities/flow-engine-framework/flow-precheck.md b/docs/capabilities/flow-engine-framework/flow-precheck.md new file mode 100644 index 00000000..d6903ab7 --- /dev/null +++ b/docs/capabilities/flow-engine-framework/flow-precheck.md @@ -0,0 +1,80 @@ +--- +name: flow-engine-framework/flow-precheck +module: flow-engine-framework +description: 下一节点审批人预检能力,提交前预测直接下一节点的人员来源并返回可选范围与提示文案 +status: 已实现 +scope: 后端 +source: 项目自有 +import: "com.codingapi.flow:flow-engine-framework" +symbols: + - FlowPrecheckService + - FlowPrecheckRequest + - PrecheckNode +--- + +## 解决什么问题 + +流程在提交时才执行下一节点的取人脚本,脚本取不到人时若走异常跳转(历史默认回退到开始节点),发起人会看到「提交成功」而实际流程原地未动。预检把这件事提前暴露: + +- **提前告知**:提交前返回直接下一节点的人员来源、是否已确定、还需谁选; +- **区分语义**:`SCRIPT`(脚本解析)与 `INITIATOR_SELECT` / `APPROVER_SELECT`(设定模式)返回不同结构,设定模式返回可选范围而不是空列表; +- **透传异常提示**:异常处理配置为 `prompt` 时把流程配置的文案带回,由业务层决定如何展示; +- **只读**:不生成记录、待办、分配关系,不推送事件,人员为空也不抛业务异常。 + +## 如何使用 + +### 核心组件 + +| 组件 | 职责 | +|------|------| +| `FlowService#precheck(FlowPrecheckRequest)` | 服务入口,清理线程缓存后委派给 `FlowPrecheckService` | +| `FlowPrecheckService` | 构建只读会话、匹配直接下一节点、逐节点解析人员来源 | +| `FlowPrecheckRequest` | 入参:发起场景传 `workCode`,审批场景传 `recordId`,可带 `formData` / `actionId` / `operatorId` | +| `PrecheckNode` | 出参:`nodeId` / `nodeName` / `nodeType` / `selectType` / `resolved` / `operators` / `candidates` / `maxOperatorCount` / `selectable` / `error` / `message` | + +### REST 端点 + +`POST /api/cmd/record/precheck`(`flow-engine-starter-api`,返回 `MultiResponse`) + +### 返回语义 + +| `selectType` | `resolved` | `candidates` | 含义 | +|---|---|---|---| +| `SCRIPT` | `true` | 空 | 取人脚本已解析出人员,`operators` 有值 | +| `SCRIPT` | `false` | 空 | 脚本未取到人,`message` 透传异常提示文案(若配置为 `prompt`) | +| `INITIATOR_SELECT` / `APPROVER_SELECT` | `false` | 可选范围,空表示不限 | 需用户为该节点指定审批人,`selectable=true` | + +### 使用实例 + +```java +// 发起场景:提交前预检下一节点 +FlowPrecheckRequest request = new FlowPrecheckRequest(); +request.setWorkCode("leave-request"); +request.setOperatorId(currentUserId); +request.setFormData(formData); +request.setActionId(actionId); +List nodes = flowService.precheck(request); + +for (PrecheckNode node : nodes) { + if (node.isSelectable() && !node.isResolved()) { + // 需要用户选择审批人,用 node.getCandidates() 渲染选择器 + } else if (node.getMessage() != null) { + // 展示异常提示,阻断提交 + } +} +``` + +## 关键实现 + +- 复用 `FlowSession#matchNextNodes()`,只预测**直接下一节点**,不做全链路递归; +- 发起场景会话与 `FlowCreateService` 同口径构建,但运行时快照不存在时 `new WorkflowRuntime(workflow)` 就地构造,**不落库**; +- 审批场景通过 `workflow.strategyManager().verifyOperator` 与 `OperatorIdentityGuard` 校验权限,避免越权读取下游人员; +- 单节点脚本异常被捕获为 `error=true` + `message`,不中断其余节点,也不向调用方抛业务异常。 + +## 相关文件 + +- `flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowPrecheckService.java` +- `flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowPrecheckRequest.java` +- `flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/PrecheckNode.java` +- `flow-engine-starter-api/src/main/java/com/codingapi/flow/api/controller/FlowRecordController.java` +- 测试:`flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowPrecheckServiceTest.java` diff --git a/docs/capabilities/flow-engine-framework/flow-service.md b/docs/capabilities/flow-engine-framework/flow-service.md index 487843ae..2fedf728 100644 --- a/docs/capabilities/flow-engine-framework/flow-service.md +++ b/docs/capabilities/flow-engine-framework/flow-service.md @@ -31,7 +31,7 @@ content_hash: 48847288af1a4551b8327e398d01a8ec4de643dce1c049b90dcdc8ad0134df3b 提供流程引擎的业务服务层,将复杂的流程操作封装为高内聚的服务接口,解决以下问题: -- **流程操作入口**:`FlowService` 作为流程审批操作的统一入口,支持创建、审批、撤销、删除、催办、子流程重置 +- **流程操作入口**:`FlowService` 作为流程审批操作的统一入口,支持创建、审批、撤销、删除、催办、子流程重置与下一节点预检 - **流程设计管理**:`WorkflowService` 管理流程定义的 CRUD 和版本操作 - **职责分离**:每种操作由独立的 Service 实现(如 `FlowActionService`、`FlowCreateService`),保持单一职责 - **线程安全**:每次操作前通过 `FlowOperatorLocalThreadCache.clear()` 与 `FlowRuntimeScriptLocalCache.clear()` 清理线程缓存 @@ -50,6 +50,7 @@ content_hash: 48847288af1a4551b8327e398d01a8ec4de643dce1c049b90dcdc8ad0134df3b | `detail(FlowDetailRequest)` | 查询流程详情 | | `processNodes(FlowProcessNodeRequest)` | 查询流程节点记录 | | `resetSubProcess(FlowSubProcessResetRequest)` | 子流程数据重置(独立接口,REST 端点 `POST /api/cmd/record/subProcess/reset`) | +| `precheck(FlowPrecheckRequest)` | 下一节点审批人预检(只读,REST 端点 `POST /api/cmd/record/precheck`) | ### WorkflowService — 流程设计管理 diff --git a/docs/capabilities/flow-engine-framework/script.md b/docs/capabilities/flow-engine-framework/script.md index 0c896465..2526a4c3 100644 --- a/docs/capabilities/flow-engine-framework/script.md +++ b/docs/capabilities/flow-engine-framework/script.md @@ -73,6 +73,19 @@ ScriptRegistryContext.getInstance().setRegistry(new IScriptRegistry() { }); ``` +### 异常触发脚本(errorTrigger)返回格式 + +节点取人为空时执行,按返回值分流为三种处理方式(前两种为历史能力,`prompt` 为 issue #296 新增): + +| 返回值 | 处理方式 | 说明 | +|---|---|---| +| `[type:'prompt', message:'...']` | 异常提示 | 阻断本次操作并展示文案,事务回滚;默认脚本即此形式 | +| `[type:'node', node:'节点id']` | 指定节点 | 跳转到指定节点继续办理 | +| `[type:'operators', operators:[1,2]]` | 指定人员 | 使用给定人员兜底,继续生成记录 | +| `'节点id'` / `[1,2]` / `1` | 兼容写法 | 依次等价于 `node` / `operators` / 单个人员,历史脚本无需改动 | + +Map 未声明 `type` 时按 `message` → `node` → `operators` 的顺序推断。`@SCRIPT_META` 应与返回类型一致(如 `{"type":"prompt"}`),设计器据此渲染配置面板;`getErrorTriggerScript()` 的默认实现返回「异常提示」,业务方可通过 `ScriptRegistryContext#setRegistry` 整体覆盖文案或改为其他处理方式。 + ### 脚本执行上下文 `FlowScriptContext` 承载脚本的 `$bind` 上下文,内部持有 `IBeanFactory` 字段并委托其实现(具体实现由 starter 的 `FlowScriptContextRegister` 装配),供 Groovy 脚本以 `$bind.getBean(...)`、`$bind.getRecordById(...)`、`$bind.getOperatorById(...)` 等方式访问 Spring 容器中的 Bean、流程记录与操作者信息;脚本的实际执行由 `FlowScriptRuntimeContext` 结合 spring-boot 的 `GroovyScript` 完成。 diff --git a/docs/capabilities/index.md b/docs/capabilities/index.md index e6b15be8..975dadae 100644 --- a/docs/capabilities/index.md +++ b/docs/capabilities/index.md @@ -10,6 +10,7 @@ | [flow-engine-framework/action](./flow-engine-framework/action.md) | flow-engine-framework | 流程动作体系,包含 9 种动作类型、动作接口和动作工厂 | 后端 | 项目自有 | | [flow-engine-framework/delay](./flow-engine-framework/delay.md) | flow-engine-framework | 延迟任务调度能力,支持延迟节点的定时触发、任务持久化与共享调度线程 | 后端 | 项目自有 | | [flow-engine-framework/exception](./flow-engine-framework/exception.md) | flow-engine-framework | 流程异常体系,包含异常基类和 6 种业务异常子类 | 后端 | 项目自有 | +| [flow-engine-framework/flow-precheck](./flow-engine-framework/flow-precheck.md) | flow-engine-framework | 下一节点审批人预检能力,提交前预测直接下一节点的人员来源并返回可选范围与提示文案 | 后端 | 项目自有 | | [flow-engine-framework/flow-service](./flow-engine-framework/flow-service.md) | flow-engine-framework | 流程服务层,封装流程的创建、审批、撤销、催办等核心业务操作 | 后端 | 项目自有 | | [flow-engine-framework/gateway-context](./flow-engine-framework/gateway-context.md) | flow-engine-framework | 网关上下文,提供操作者网关的注入和线程级缓存 | 后端 | 项目自有 | | [flow-engine-framework/node-manager](./flow-engine-framework/node-manager.md) | flow-engine-framework | 流程节点管理器,负责节点查找、下一节点计算和节点状态管理 | 后端 | 项目自有 | @@ -31,4 +32,4 @@ --- -**统计**: 共 22 篇 — 已实现 22 / 计划中 0 / 已废弃 0 +**统计**: 共 23 篇 — 已实现 23 / 计划中 0 / 已废弃 0 From 7758b01c62e6f42efc8e48fb357c44306348ea42 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Wed, 2 Dec 2026 21:33:02 +0800 Subject: [PATCH 19/35] =?UTF-8?q?refactor(#296):=20=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E6=A1=86=E6=9E=B6=E5=86=85=E7=BD=AE=E7=9A=84=E4=B8=8B=E4=B8=80?= =?UTF-8?q?=E8=8A=82=E7=82=B9=E9=A2=84=E6=A3=80=EF=BC=8C=E4=BA=A4=E7=94=B1?= =?UTF-8?q?=E4=B8=9A=E5=8A=A1=E8=87=AA=E8=A1=8C=E6=8E=A7=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 预检属于业务侧的交互决策,框架不应内置。框架只需要在异常处理配置为 「异常提示」时返回可展示的错误信息,由业务层决定如何呈现与是否阻断。 - 删除 FlowPrecheckService / FlowPrecheckRequest / PrecheckNode 及其测试 - 移除 FlowService#precheck 与 POST /api/cmd/record/precheck - 回退 REST 文档中的预检章节,保留 errorTrigger 三种语义说明 - 移除 capabilities 中的 flow-precheck 文档,索引回退为 22 篇 - 保留 ErrorThrow.PROMPT、ErrorTriggerScript Map 解析、默认脚本与提交侧阻断 Refs #296 --- docs/Integration/rest-api.md | 37 +-- .../flow-engine-framework/flow-precheck.md | 80 ------ .../flow-engine-framework/flow-service.md | 3 +- docs/capabilities/index.md | 3 +- .../pojo/request/FlowPrecheckRequest.java | 60 ----- .../flow/pojo/response/PrecheckNode.java | 79 ------ .../codingapi/flow/service/FlowService.java | 16 -- .../service/impl/FlowPrecheckService.java | 195 --------------- .../flow/service/FlowPrecheckServiceTest.java | 227 ------------------ .../api/controller/FlowRecordController.java | 16 -- 10 files changed, 3 insertions(+), 713 deletions(-) delete mode 100644 docs/capabilities/flow-engine-framework/flow-precheck.md delete mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowPrecheckRequest.java delete mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/PrecheckNode.java delete mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowPrecheckService.java delete mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowPrecheckServiceTest.java diff --git a/docs/Integration/rest-api.md b/docs/Integration/rest-api.md index b1f66a10..f2c5bb86 100644 --- a/docs/Integration/rest-api.md +++ b/docs/Integration/rest-api.md @@ -39,47 +39,12 @@ operatorIdentity → 存在 → 校验后作为当前身份(空串 = 默认身 | POST | `/api/cmd/record/processNodes` | `FlowProcessNodeRequest` | `MultiResponse` | 流程流转节点预览 | | POST | `/api/cmd/record/create` | `FlowCreateRequest` | `SingleResponse` | 发起流程,返回首条记录 id | | POST | `/api/cmd/record/action` | `FlowActionRequest` | `SingleResponse` | 执行动作(通过/拒绝/加签/减签/委派/退回/转办/自定义/保存) | -| POST | `/api/cmd/record/precheck` | `FlowPrecheckRequest` | `MultiResponse` | 下一节点审批人预检(只读,见 §2.1) | | POST | `/api/cmd/record/subProcess/reset` | `FlowSubProcessResetRequest` | `Response` | 子流程数据重置(独立接口,需子流程节点开启重置能力) | | POST | `/api/cmd/record/urge` | `IdRequest` | `Response` | 催办 | | POST | `/api/cmd/record/revoke` | `IdRequest` | `Response` | 撤销 | | POST | `/api/cmd/record/delete` | `IdRequest` | `Response` | 删除(仅未流转实例,开始节点) | -### 2.1 下一节点预检(`/api/cmd/record/precheck`,issue #296) - -提交前预测**直接下一节点**的审批人来源,用于在发起/审批页提示用户或让用户补选人员。只读:不生成记录/待办、不写分配关系、不推事件。 - -请求 `FlowPrecheckRequest`: - -| 字段 | 说明 | -|---|---| -| `workCode` | 发起场景传流程编码 | -| `recordId` | 审批场景传当前待办记录 id(优先于 `workCode`) | -| `actionId` | 本次动作 id | -| `formData` | 表单数据,用于执行取人脚本与分支条件 | -| `operatorId` / `operatorIdentity` | 由接口层按当前会话注入 | - -响应 `PrecheckNode`(分支多时返回多条): - -| 字段 | 说明 | -|---|---| -| `nodeId` / `nodeName` / `nodeType` | 下一节点信息 | -| `selectType` | `SCRIPT` / `INITIATOR_SELECT` / `APPROVER_SELECT` | -| `resolved` | 审批人是否已确定 | -| `operators` | 已解析出的审批人 | -| `candidates` | 需要用户选择时的可选范围;为空表示不限范围 | -| `maxOperatorCount` | 最大可选人数,-1 不限 | -| `selectable` | 是否需要用户为该节点选择审批人 | -| `error` | 预检是否出现脚本异常(不中断调用方) | -| `message` | 透传的异常提示文案(`errorTrigger=prompt` 时) | - -判定口径: - -- `SCRIPT` 且取人脚本返回空 → `resolved=false`、`selectable=false`,`message` 为流程配置的提示文案; -- `INITIATOR_SELECT` / `APPROVER_SELECT` 且尚无分配数据 → `resolved=false`、`selectable=true`,`candidates` 为范围脚本结果; -- 预检不因人员为空抛业务异常,是否阻断由调用方决定。 - -### 2.2 异常触发(`errorTrigger`)的三种语义 +### 2.1 异常触发(`errorTrigger`)的三种语义 `ErrorThrow` 按脚本返回值分流,历史写法保持兼容: diff --git a/docs/capabilities/flow-engine-framework/flow-precheck.md b/docs/capabilities/flow-engine-framework/flow-precheck.md deleted file mode 100644 index d6903ab7..00000000 --- a/docs/capabilities/flow-engine-framework/flow-precheck.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -name: flow-engine-framework/flow-precheck -module: flow-engine-framework -description: 下一节点审批人预检能力,提交前预测直接下一节点的人员来源并返回可选范围与提示文案 -status: 已实现 -scope: 后端 -source: 项目自有 -import: "com.codingapi.flow:flow-engine-framework" -symbols: - - FlowPrecheckService - - FlowPrecheckRequest - - PrecheckNode ---- - -## 解决什么问题 - -流程在提交时才执行下一节点的取人脚本,脚本取不到人时若走异常跳转(历史默认回退到开始节点),发起人会看到「提交成功」而实际流程原地未动。预检把这件事提前暴露: - -- **提前告知**:提交前返回直接下一节点的人员来源、是否已确定、还需谁选; -- **区分语义**:`SCRIPT`(脚本解析)与 `INITIATOR_SELECT` / `APPROVER_SELECT`(设定模式)返回不同结构,设定模式返回可选范围而不是空列表; -- **透传异常提示**:异常处理配置为 `prompt` 时把流程配置的文案带回,由业务层决定如何展示; -- **只读**:不生成记录、待办、分配关系,不推送事件,人员为空也不抛业务异常。 - -## 如何使用 - -### 核心组件 - -| 组件 | 职责 | -|------|------| -| `FlowService#precheck(FlowPrecheckRequest)` | 服务入口,清理线程缓存后委派给 `FlowPrecheckService` | -| `FlowPrecheckService` | 构建只读会话、匹配直接下一节点、逐节点解析人员来源 | -| `FlowPrecheckRequest` | 入参:发起场景传 `workCode`,审批场景传 `recordId`,可带 `formData` / `actionId` / `operatorId` | -| `PrecheckNode` | 出参:`nodeId` / `nodeName` / `nodeType` / `selectType` / `resolved` / `operators` / `candidates` / `maxOperatorCount` / `selectable` / `error` / `message` | - -### REST 端点 - -`POST /api/cmd/record/precheck`(`flow-engine-starter-api`,返回 `MultiResponse`) - -### 返回语义 - -| `selectType` | `resolved` | `candidates` | 含义 | -|---|---|---|---| -| `SCRIPT` | `true` | 空 | 取人脚本已解析出人员,`operators` 有值 | -| `SCRIPT` | `false` | 空 | 脚本未取到人,`message` 透传异常提示文案(若配置为 `prompt`) | -| `INITIATOR_SELECT` / `APPROVER_SELECT` | `false` | 可选范围,空表示不限 | 需用户为该节点指定审批人,`selectable=true` | - -### 使用实例 - -```java -// 发起场景:提交前预检下一节点 -FlowPrecheckRequest request = new FlowPrecheckRequest(); -request.setWorkCode("leave-request"); -request.setOperatorId(currentUserId); -request.setFormData(formData); -request.setActionId(actionId); -List nodes = flowService.precheck(request); - -for (PrecheckNode node : nodes) { - if (node.isSelectable() && !node.isResolved()) { - // 需要用户选择审批人,用 node.getCandidates() 渲染选择器 - } else if (node.getMessage() != null) { - // 展示异常提示,阻断提交 - } -} -``` - -## 关键实现 - -- 复用 `FlowSession#matchNextNodes()`,只预测**直接下一节点**,不做全链路递归; -- 发起场景会话与 `FlowCreateService` 同口径构建,但运行时快照不存在时 `new WorkflowRuntime(workflow)` 就地构造,**不落库**; -- 审批场景通过 `workflow.strategyManager().verifyOperator` 与 `OperatorIdentityGuard` 校验权限,避免越权读取下游人员; -- 单节点脚本异常被捕获为 `error=true` + `message`,不中断其余节点,也不向调用方抛业务异常。 - -## 相关文件 - -- `flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowPrecheckService.java` -- `flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowPrecheckRequest.java` -- `flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/PrecheckNode.java` -- `flow-engine-starter-api/src/main/java/com/codingapi/flow/api/controller/FlowRecordController.java` -- 测试:`flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowPrecheckServiceTest.java` diff --git a/docs/capabilities/flow-engine-framework/flow-service.md b/docs/capabilities/flow-engine-framework/flow-service.md index 2fedf728..487843ae 100644 --- a/docs/capabilities/flow-engine-framework/flow-service.md +++ b/docs/capabilities/flow-engine-framework/flow-service.md @@ -31,7 +31,7 @@ content_hash: 48847288af1a4551b8327e398d01a8ec4de643dce1c049b90dcdc8ad0134df3b 提供流程引擎的业务服务层,将复杂的流程操作封装为高内聚的服务接口,解决以下问题: -- **流程操作入口**:`FlowService` 作为流程审批操作的统一入口,支持创建、审批、撤销、删除、催办、子流程重置与下一节点预检 +- **流程操作入口**:`FlowService` 作为流程审批操作的统一入口,支持创建、审批、撤销、删除、催办、子流程重置 - **流程设计管理**:`WorkflowService` 管理流程定义的 CRUD 和版本操作 - **职责分离**:每种操作由独立的 Service 实现(如 `FlowActionService`、`FlowCreateService`),保持单一职责 - **线程安全**:每次操作前通过 `FlowOperatorLocalThreadCache.clear()` 与 `FlowRuntimeScriptLocalCache.clear()` 清理线程缓存 @@ -50,7 +50,6 @@ content_hash: 48847288af1a4551b8327e398d01a8ec4de643dce1c049b90dcdc8ad0134df3b | `detail(FlowDetailRequest)` | 查询流程详情 | | `processNodes(FlowProcessNodeRequest)` | 查询流程节点记录 | | `resetSubProcess(FlowSubProcessResetRequest)` | 子流程数据重置(独立接口,REST 端点 `POST /api/cmd/record/subProcess/reset`) | -| `precheck(FlowPrecheckRequest)` | 下一节点审批人预检(只读,REST 端点 `POST /api/cmd/record/precheck`) | ### WorkflowService — 流程设计管理 diff --git a/docs/capabilities/index.md b/docs/capabilities/index.md index 975dadae..e6b15be8 100644 --- a/docs/capabilities/index.md +++ b/docs/capabilities/index.md @@ -10,7 +10,6 @@ | [flow-engine-framework/action](./flow-engine-framework/action.md) | flow-engine-framework | 流程动作体系,包含 9 种动作类型、动作接口和动作工厂 | 后端 | 项目自有 | | [flow-engine-framework/delay](./flow-engine-framework/delay.md) | flow-engine-framework | 延迟任务调度能力,支持延迟节点的定时触发、任务持久化与共享调度线程 | 后端 | 项目自有 | | [flow-engine-framework/exception](./flow-engine-framework/exception.md) | flow-engine-framework | 流程异常体系,包含异常基类和 6 种业务异常子类 | 后端 | 项目自有 | -| [flow-engine-framework/flow-precheck](./flow-engine-framework/flow-precheck.md) | flow-engine-framework | 下一节点审批人预检能力,提交前预测直接下一节点的人员来源并返回可选范围与提示文案 | 后端 | 项目自有 | | [flow-engine-framework/flow-service](./flow-engine-framework/flow-service.md) | flow-engine-framework | 流程服务层,封装流程的创建、审批、撤销、催办等核心业务操作 | 后端 | 项目自有 | | [flow-engine-framework/gateway-context](./flow-engine-framework/gateway-context.md) | flow-engine-framework | 网关上下文,提供操作者网关的注入和线程级缓存 | 后端 | 项目自有 | | [flow-engine-framework/node-manager](./flow-engine-framework/node-manager.md) | flow-engine-framework | 流程节点管理器,负责节点查找、下一节点计算和节点状态管理 | 后端 | 项目自有 | @@ -32,4 +31,4 @@ --- -**统计**: 共 23 篇 — 已实现 23 / 计划中 0 / 已废弃 0 +**统计**: 共 22 篇 — 已实现 22 / 计划中 0 / 已废弃 0 diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowPrecheckRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowPrecheckRequest.java deleted file mode 100644 index fb548b2c..00000000 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowPrecheckRequest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.codingapi.flow.pojo.request; - -import com.codingapi.flow.exception.FlowValidationException; -import lombok.Data; -import org.springframework.util.StringUtils; - -import java.util.Map; - -/** - * 流程预检请求(issue #296) - *

    - * 用于在发起或提交前预测直接下一节点的审批人,不产生任何写入。 - * 发起场景传 {@code workCode},审批场景传 {@code recordId};两者同时存在时以 {@code recordId} 为准。 - */ -@Data -public class FlowPrecheckRequest { - - /** - * 流程定义编码(发起场景) - */ - private String workCode; - - /** - * 当前待办记录 id(审批场景) - */ - private long recordId; - - /** - * 本次操作的动作 id,用于解析当前节点的动作上下文 - */ - private String actionId; - - /** - * 表单数据,用于执行取人脚本与分支条件 - */ - private Map formData; - - /** - * 操作者 id,由接口层注入 - */ - private long operatorId; - - /** - * 操作者身份标识,由接口层注入 - */ - private String operatorIdentity; - - /** - * 是否为发起场景 - */ - public boolean isCreateScene() { - return recordId <= 0; - } - - public void verify() { - if (recordId <= 0 && !StringUtils.hasText(workCode)) { - throw FlowValidationException.required("workCode"); - } - } -} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/PrecheckNode.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/PrecheckNode.java deleted file mode 100644 index 1ebad116..00000000 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/PrecheckNode.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.codingapi.flow.pojo.response; - -import com.codingapi.flow.operator.IFlowOperator; -import lombok.Data; - -import java.util.ArrayList; -import java.util.List; - -/** - * 下一节点审批人预检结果(issue #296) - *

    - * 用于把「下一节点的人从哪来、是否已确定、还需要谁选」如实告诉调用方: - *

      - *
    • {@code SCRIPT}:人员由取人脚本解析,{@code resolved=true} 时 {@code operators} 有值;
    • - *
    • {@code INITIATOR_SELECT} / {@code APPROVER_SELECT}:人员尚未指定时 - * {@code resolved=false}、{@code selectable=true},{@code candidates} 为可选范围 - * (为空表示不限范围,可选任意人)。
    • - *
    - * 预检只读,不生成记录、不推送事件,也不因人员为空抛业务异常; - * {@code message} 仅透传流程配置的异常提示文案。 - */ -@Data -public class PrecheckNode { - - /** - * 节点 id - */ - private String nodeId; - - /** - * 节点名称 - */ - private String nodeName; - - /** - * 节点类型 - */ - private String nodeType; - - /** - * 操作人选择方式:SCRIPT / INITIATOR_SELECT / APPROVER_SELECT - */ - private String selectType; - - /** - * 审批人是否已确定 - */ - private boolean resolved; - - /** - * 已确定/解析出的审批人 - */ - private List operators = new ArrayList<>(); - - /** - * 可选人员范围,仅 {@code resolved=false} 且需要用户选择时有意义;为空表示不限范围 - */ - private List candidates = new ArrayList<>(); - - /** - * 最大可选人数,-1 表示不限制 - */ - private int maxOperatorCount = -1; - - /** - * 是否需要用户为该节点选择审批人 - */ - private boolean selectable; - - /** - * 预检过程是否出现异常(脚本执行失败等),异常不会中断其余节点 - */ - private boolean error; - - /** - * 异常提示文案或预检失败原因 - */ - private String message; -} 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 1d8a1b9a..547fa3dc 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 @@ -6,7 +6,6 @@ import com.codingapi.flow.pojo.response.ActionResponse; import com.codingapi.flow.pojo.response.FlowContent; import com.codingapi.flow.pojo.response.FlowForceSyncResult; -import com.codingapi.flow.pojo.response.PrecheckNode; import com.codingapi.flow.pojo.response.ProcessNode; import com.codingapi.flow.service.impl.*; import com.codingapi.flow.session.IRepositoryHolder; @@ -80,21 +79,6 @@ public ActionResponse action(FlowActionRequest request) { return flowActionService.action(); } - /** - * 流程预检(issue #296) - *

    - * 预测直接下一节点的审批人来源,供发起/审批前提示用户;只读,不产生记录、待办、分配关系与事件。 - * - * @param request 预检请求(发起场景传 workCode,审批场景传 recordId) - * @return 下一节点预检结果 - */ - public List precheck(FlowPrecheckRequest request) { - FlowOperatorLocalThreadCache.getInstance().clear(); - FlowRuntimeScriptLocalCache.getInstance().clear(); - FlowPrecheckService flowPrecheckService = new FlowPrecheckService(request, this.repositoryHolder); - return flowPrecheckService.precheck(); - } - /** * 撤销流程 * diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowPrecheckService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowPrecheckService.java deleted file mode 100644 index 8310b75b..00000000 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowPrecheckService.java +++ /dev/null @@ -1,195 +0,0 @@ -package com.codingapi.flow.service.impl; - -import com.codingapi.flow.action.IFlowAction; -import com.codingapi.flow.cache.FlowRuntimeScriptLocalCache; -import com.codingapi.flow.error.ErrorThrow; -import com.codingapi.flow.exception.FlowNotFoundException; -import com.codingapi.flow.exception.FlowPermissionException; -import com.codingapi.flow.exception.FlowStateException; -import com.codingapi.flow.form.FormData; -import com.codingapi.flow.gateway.FlowOperatorGateway; -import com.codingapi.flow.manager.OperatorManager; -import com.codingapi.flow.node.IFlowNode; -import com.codingapi.flow.node.nodes.StartNode; -import com.codingapi.flow.operator.IFlowOperator; -import com.codingapi.flow.operator.OperatorIdentityGuard; -import com.codingapi.flow.pojo.request.FlowPrecheckRequest; -import com.codingapi.flow.pojo.response.PrecheckNode; -import com.codingapi.flow.record.FlowRecord; -import com.codingapi.flow.service.FlowRecordService; -import com.codingapi.flow.service.WorkflowService; -import com.codingapi.flow.session.FlowAdvice; -import com.codingapi.flow.session.FlowSession; -import com.codingapi.flow.session.IRepositoryHolder; -import com.codingapi.flow.strategy.node.OperatorSelectType; -import com.codingapi.flow.workflow.Workflow; -import com.codingapi.flow.workflow.runtime.WorkflowRuntime; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * 流程预检服务(issue #296) - *

    - * 预测直接下一节点的审批人来源,供发起页/审批页在提交前提示用户。 - * 只复用取人脚本与人员范围脚本的既有能力,不生成记录、不推送事件、不写分配关系, - * 也不因为人员为空抛业务异常——空结果本身就是要交给业务层展示的信息。 - */ -public class FlowPrecheckService { - - private final FlowPrecheckRequest request; - private final IRepositoryHolder repositoryHolder; - private final FlowOperatorGateway flowOperatorGateway; - private final FlowRecordService flowRecordService; - private final WorkflowService workflowService; - - public FlowPrecheckService(FlowPrecheckRequest request, IRepositoryHolder repositoryHolder) { - this.request = request; - this.repositoryHolder = repositoryHolder; - this.flowOperatorGateway = repositoryHolder.getFlowOperatorGateway(); - this.flowRecordService = repositoryHolder.getFlowRecordService(); - this.workflowService = repositoryHolder.getWorkflowService(); - } - - public List precheck() { - request.verify(); - FlowSession session = request.isCreateScene() ? createSession() : actionSession(); - List nextNodes = session.matchNextNodes(); - if (nextNodes == null || nextNodes.isEmpty()) { - return List.of(); - } - List result = new ArrayList<>(nextNodes.size()); - for (IFlowNode nextNode : nextNodes) { - result.add(inspect(nextNode, session)); - } - return result; - } - - /** - * 发起场景:与 {@code FlowCreateService} 同口径地构建会话,但不保存任何数据。 - */ - private FlowSession createSession() { - Workflow workflow = workflowService.getWorkflowByCode(request.getWorkCode()); - if (workflow == null) { - throw FlowNotFoundException.workflow(request.getWorkCode()); - } - if (workflow.isDisable()) { - throw FlowStateException.workflowAlreadyDisable(request.getWorkCode()); - } - workflow.verify(); - // 预检只读:运行时快照不存在时就地构造,不落库(getOrCreate 会写入) - WorkflowRuntime workflowRuntime = workflowService.getWorkflowRuntime(workflow.getId(), workflow.getUpdatedTime()); - if (workflowRuntime == null) { - workflowRuntime = new WorkflowRuntime(workflow); - } - FlowRuntimeScriptLocalCache.getInstance().set(workflowRuntime.getScripts()); - - IFlowOperator currentOperator = loadCurrentOperator(); - if (!workflow.matchCreatedOperator(currentOperator)) { - throw FlowPermissionException.accessDenied("create workflow"); - } - FormData formData = new FormData(workflow.getForm()); - formData.reset(request.getFormData() == null ? Map.of() : request.getFormData()); - - StartNode startNode = (StartNode) workflow.getStartNode(); - IFlowAction action = startNode.actionManager().getActionById(request.getActionId()); - return FlowSession.startSession(repositoryHolder, currentOperator, workflow, startNode, action, - formData, workflowRuntime.getId()); - } - - /** - * 审批场景:只能预检当前用户有权办理的待办,避免越权读取下游人员信息。 - */ - private FlowSession actionSession() { - FlowRecord flowRecord = flowRecordService.getFlowRecord(request.getRecordId()); - if (flowRecord == null) { - throw FlowNotFoundException.record(request.getRecordId()); - } - if (!flowRecord.isTodo()) { - throw FlowStateException.recordAlreadyDone(); - } - IFlowOperator currentOperator = loadCurrentOperator(); - - WorkflowRuntime workflowRuntime = workflowService.getWorkflowRuntime(flowRecord.getWorkRuntimeId()); - if (workflowRuntime == null) { - throw FlowNotFoundException.workflow(flowRecord.getWorkRuntimeId() + " not found"); - } - FlowRuntimeScriptLocalCache.getInstance().set(workflowRuntime.getScripts()); - Workflow workflow = workflowRuntime.toWorkflow(); - - workflow.strategyManager().verifyOperator(currentOperator, flowRecord.getCurrentOperatorId(), - flowRecord.getCurrentOperatorIdentity()); - - IFlowNode currentNode = workflow.getFlowNode(flowRecord.getNodeId()); - if (currentNode == null) { - throw FlowNotFoundException.node(flowRecord.getNodeId()); - } - IFlowOperator createdOperator = flowOperatorGateway.get(flowRecord.getCreateOperatorId(), - flowRecord.getCreateOperatorIdentity()); - OperatorIdentityGuard.check(flowRecord.getCreateOperatorId(), - flowRecord.getCreateOperatorIdentity(), createdOperator); - - FormData formData = new FormData(workflow.getForm()); - Map data = request.getFormData() != null - ? request.getFormData() - : (flowRecord.getFormData() == null ? Map.of() : flowRecord.getFormData()); - formData.reset(data); - - FlowAdvice advice = new FlowAdvice(); - advice.setAction(currentNode.actionManager().getActionById(request.getActionId())); - return flowRecord.createFlowSession(repositoryHolder, workflow, currentOperator, createdOperator, - currentOperator, formData, advice); - } - - private IFlowOperator loadCurrentOperator() { - IFlowOperator currentOperator = flowOperatorGateway.get(request.getOperatorId(), request.getOperatorIdentity()); - OperatorIdentityGuard.check(request.getOperatorId(), request.getOperatorIdentity(), currentOperator); - if (currentOperator == null) { - throw FlowNotFoundException.operator(request.getOperatorId()); - } - return currentOperator; - } - - /** - * 检查单个下一节点:人员从哪来、是否已确定、是否需要用户选择。 - */ - private PrecheckNode inspect(IFlowNode node, FlowSession session) { - PrecheckNode result = new PrecheckNode(); - result.setNodeId(node.getId()); - result.setNodeName(node.getName()); - result.setNodeType(node.getType()); - OperatorSelectType selectType = node.strategyManager().getOperatorSelectType(); - OperatorSelectType actualSelectType = selectType == null ? OperatorSelectType.SCRIPT : selectType; - result.setSelectType(actualSelectType.name()); - result.setMaxOperatorCount(node.strategyManager().getMaxOperatorCount()); - - FlowSession nodeSession = session.updateSession(node); - try { - OperatorManager operatorManager = node.strategyManager().loadOperators(nodeSession); - if (!operatorManager.isEmpty()) { - result.setResolved(true); - result.setOperators(operatorManager.getOperators()); - return result; - } - if (actualSelectType == OperatorSelectType.INITIATOR_SELECT - || actualSelectType == OperatorSelectType.APPROVER_SELECT) { - // 设定模式在提交前本就没有分配数据,返回可选范围让业务方渲染选择器; - // 范围为空表示不限范围(可选任意人) - result.setCandidates(node.strategyManager().loadOperatorRange(nodeSession)); - result.setSelectable(true); - return result; - } - // 脚本模式取人为空:透传「异常提示」文案,预检本身不阻断 - ErrorThrow errorThrow = node.strategyManager().errorTrigger(nodeSession); - if (errorThrow != null && errorThrow.isPrompt()) { - result.setMessage(errorThrow.getMessage()); - } - } catch (Exception e) { - // 预检不中断调用方:单个节点脚本异常以结果形式返回 - result.setError(true); - result.setMessage(e.getMessage()); - } - return result; - } -} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowPrecheckServiceTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowPrecheckServiceTest.java deleted file mode 100644 index 66e39a7f..00000000 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowPrecheckServiceTest.java +++ /dev/null @@ -1,227 +0,0 @@ -package com.codingapi.flow.service; - -import com.codingapi.flow.builder.NodeStrategyBuilder; -import com.codingapi.flow.exception.FlowValidationException; -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.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.FlowPrecheckRequest; -import com.codingapi.flow.pojo.response.PrecheckNode; -import com.codingapi.flow.strategy.node.OperatorLoadStrategy; -import com.codingapi.flow.strategy.node.OperatorSelectType; -import com.codingapi.flow.user.User; -import com.codingapi.flow.workflow.Workflow; -import com.codingapi.flow.workflow.WorkflowBuilder; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.*; - -/** - * 流程预检测试(issue #296) - *

    - * 覆盖三种取人方式的预检结果、只读约束,以及「异常提示」在提交时的阻断行为。 - */ -class FlowPrecheckServiceTest { - - private MyFlowServiceFactory factory; - private User creator; - private User approver; - - @BeforeEach - void setUp() { - factory = new MyFlowServiceFactory(); - creator = new User(1, "发起人"); - approver = new User(2, "审批人"); - factory.userGateway.save(creator); - factory.userGateway.save(approver); - } - - private Map formData() { - return Map.of("title", "预检测试"); - } - - private Workflow buildWorkflow(String code, OperatorLoadStrategy approvalStrategy) { - FlowForm form = FlowFormBuilder.builder() - .name("预检流程") - .code(code) - .addField("标题", "title", DataType.STRING) - .build(); - - StartNode startNode = StartNode.builder().build(); - ApprovalNode approvalNode = ApprovalNode.builder() - .name("审批节点") - .strategies(NodeStrategyBuilder.builder() - .addStrategy(approvalStrategy) - .build()) - .build(); - EndNode endNode = EndNode.builder().build(); - - Workflow workflow = WorkflowBuilder.builder() - .title("预检流程") - .code(code) - .createdOperator(creator) - .form(form) - .addNode(startNode) - .addNode(approvalNode) - .addNode(endNode) - .build(); - factory.workflowService.saveWorkflow(workflow); - return workflow; - } - - private FlowPrecheckRequest createSceneRequest(Workflow workflow) { - FlowPrecheckRequest request = new FlowPrecheckRequest(); - request.setWorkCode(workflow.getCode()); - request.setActionId(workflow.getStartNode().actionManager().getActions().get(0).id()); - request.setFormData(formData()); - request.setOperatorId(creator.getUserId()); - return request; - } - - private long createAtStartNode(Workflow workflow) { - FlowCreateRequest createRequest = new FlowCreateRequest(); - createRequest.setWorkCode(workflow.getCode()); - createRequest.setFormData(formData()); - createRequest.setActionId(workflow.getStartNode().actionManager().getActions().get(0).id()); - createRequest.setOperatorId(creator.getUserId()); - return factory.flowService.create(createRequest); - } - - /** - * 脚本模式已解析出人员:resolved=true,operators 有值,无需用户选择 - */ - @Test - void should_resolve_operators_when_script_matched() { - Workflow workflow = buildWorkflow("precheck-script", - new OperatorLoadStrategy("def run(request){return [2]}")); - - List nodes = factory.flowService.precheck(createSceneRequest(workflow)); - - assertEquals(1, nodes.size()); - PrecheckNode node = nodes.get(0); - assertEquals(OperatorSelectType.SCRIPT.name(), node.getSelectType()); - assertTrue(node.isResolved()); - assertFalse(node.isSelectable()); - assertEquals(1, node.getOperators().size()); - assertEquals(approver.getUserId(), node.getOperators().get(0).getUserId()); - } - - /** - * 脚本模式未匹配到人员:resolved=false,并透传默认的异常提示文案(预检本身不抛异常) - */ - @Test - void should_return_prompt_message_when_script_matched_nothing() { - Workflow workflow = buildWorkflow("precheck-empty", - new OperatorLoadStrategy("def run(request){return []}")); - - List nodes = factory.flowService.precheck(createSceneRequest(workflow)); - - assertEquals(1, nodes.size()); - PrecheckNode node = nodes.get(0); - assertFalse(node.isResolved()); - assertFalse(node.isSelectable()); - assertTrue(node.getOperators().isEmpty()); - assertNotNull(node.getMessage()); - assertTrue(node.getMessage().contains("审批人")); - } - - /** - * 发起人设定:尚无分配数据,返回可选范围并标记需要用户选择 - */ - @Test - void should_return_candidates_when_initiator_select() { - Workflow workflow = buildWorkflow("precheck-initiator", - OperatorLoadStrategy.initiatorSelectStrategy("def run(request){return [2]}", 1)); - - List nodes = factory.flowService.precheck(createSceneRequest(workflow)); - - assertEquals(1, nodes.size()); - PrecheckNode node = nodes.get(0); - assertEquals(OperatorSelectType.INITIATOR_SELECT.name(), node.getSelectType()); - assertFalse(node.isResolved()); - assertTrue(node.isSelectable()); - assertEquals(1, node.getMaxOperatorCount()); - assertEquals(1, node.getCandidates().size()); - assertEquals(approver.getUserId(), node.getCandidates().get(0).getUserId()); - } - - /** - * 审批人设定:同样返回可选范围,语义与发起人设定一致 - */ - @Test - void should_return_candidates_when_approver_select() { - Workflow workflow = buildWorkflow("precheck-approver", - OperatorLoadStrategy.approverSelectStrategy("def run(request){return [2]}", 1)); - - List nodes = factory.flowService.precheck(createSceneRequest(workflow)); - - assertEquals(1, nodes.size()); - PrecheckNode node = nodes.get(0); - assertEquals(OperatorSelectType.APPROVER_SELECT.name(), node.getSelectType()); - assertFalse(node.isResolved()); - assertTrue(node.isSelectable()); - assertEquals(1, node.getCandidates().size()); - } - - /** - * 审批场景按 recordId 预检直接下一节点,且不产生任何记录/待办 - */ - @Test - void should_precheck_next_node_by_record_and_keep_readonly() { - Workflow workflow = buildWorkflow("precheck-record", - new OperatorLoadStrategy("def run(request){return [2]}")); - long recordId = createAtStartNode(workflow); - - int todoBefore = factory.flowRecordRepository.findTodoByOperator(creator.getUserId()).size(); - int todoRecordBefore = factory.flowTodoRecordRepository.findByOperatorId(creator.getUserId()).size(); - - FlowPrecheckRequest request = new FlowPrecheckRequest(); - request.setRecordId(recordId); - request.setActionId(workflow.getStartNode().actionManager().getActions().get(0).id()); - request.setFormData(formData()); - request.setOperatorId(creator.getUserId()); - - List nodes = factory.flowService.precheck(request); - - assertEquals(1, nodes.size()); - assertTrue(nodes.get(0).isResolved()); - // 只读:预检前后记录与待办数量不变 - assertEquals(todoBefore, factory.flowRecordRepository.findTodoByOperator(creator.getUserId()).size()); - assertEquals(todoRecordBefore, factory.flowTodoRecordRepository.findByOperatorId(creator.getUserId()).size()); - } - - /** - * 默认异常处理为「异常提示」:提交时直接阻断并抛出带文案的业务异常,不再静默回退到开始节点 - */ - @Test - void should_block_action_when_next_node_has_no_operator_and_prompt_configured() { - Workflow workflow = buildWorkflow("precheck-block", - new OperatorLoadStrategy("def run(request){return []}")); - long recordId = createAtStartNode(workflow); - - FlowActionRequest actionRequest = new FlowActionRequest(); - actionRequest.setRecordId(recordId); - actionRequest.setFormData(formData()); - actionRequest.setAdvice(new FlowAdviceBody( - workflow.getStartNode().actionManager().getActions().get(0).id(), "同意", creator.getUserId())); - - FlowValidationException exception = assertThrows(FlowValidationException.class, - () -> factory.flowService.action(actionRequest)); - - assertNotNull(exception.getMessage()); - assertTrue(exception.getMessage().contains("审批人")); - // 流程没有被推进到下一节点:不存在审批人的待办 - assertTrue(factory.flowRecordRepository.findTodoByOperator(approver.getUserId()).isEmpty()); - } -} 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 0396aa0c..d54cd745 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 @@ -8,7 +8,6 @@ import com.codingapi.flow.pojo.response.ActionResponse; import com.codingapi.flow.pojo.response.FlowContent; import com.codingapi.flow.pojo.response.FlowForceSyncResult; -import com.codingapi.flow.pojo.response.PrecheckNode; import com.codingapi.flow.pojo.response.ProcessNode; import com.codingapi.flow.service.FlowService; import com.codingapi.springboot.framework.dto.request.IdRequest; @@ -139,21 +138,6 @@ public SingleResponse action(@RequestBody FlowActionRequest requ return SingleResponse.of(response); } - /** - * 下一节点审批人预检(issue #296)。 - *

    - * 发起场景传 {@code workCode},审批场景传 {@code recordId};只预测直接下一节点, - * 只读不写,人员为空也不抛业务异常,由调用方根据 {@code selectType} / {@code resolved} - * / {@code candidates} / {@code message} 决定提示或补选。

    - */ - @PostMapping("/precheck") - public MultiResponse precheck(@RequestBody FlowPrecheckRequest request) { - FlowService flowService = this.loadFlowService(); - request.setOperatorId(loadCurrentOperatorId()); - request.setOperatorIdentity(loadCurrentOperatorIdentity()); - return MultiResponse.of(flowService.precheck(request)); - } - /** * 子流程数据重置(独立接口,不属于常规审批动作)。 *

    仅当子流程节点开启重置能力且当前记录位于其下游时可调用, From 99346c7c0c87d30f7833b94aadccb1d0cc80edbb Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Thu, 3 Dec 2026 08:51:50 +0800 Subject: [PATCH 20/35] =?UTF-8?q?fix(#301):=20=E8=BA=AB=E4=BB=BD=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E8=AF=B7=E6=B1=82=E5=A4=B4=E4=BC=A0=E9=80=92=EF=BC=8C?= =?UTF-8?q?=E9=81=BF=E5=85=8D=E6=B1=A1=E6=9F=93=20SearchRequest=20?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 身份原先前端以 query 参数 operatorIdentity 注入所有 /api/ 请求,而引擎的 /api/query/workflow/list 用 SearchRequest 接收请求,会把 query 参数当作实体 过滤字段解析,直接抛 Field operatorIdentity not found in class hierarchy。 - OperatorIdentity 新增 X-Operator-Identity / X-Identity-Scope / X-Lock-Identity 请求头常量与 pick()(请求头优先、区分「未携带」与「显式空串」) - FlowRecordController、FlowRecordQueryController 身份解析改为请求头优先, 保留 query 读取以兼容旧调用方 - 查询身份范围(identityScope / lockIdentity)同步支持请求头 - 更新 operator-identity 文档与 curl 示例 - 新增 OperatorIdentityHeaderResolveTest 覆盖优先级与非法值拒绝 Closes #301 --- docs/Integration/operator-identity.md | 27 ++++++-- .../flow/operator/OperatorIdentity.java | 36 ++++++++++ .../OperatorIdentityHeaderResolveTest.java | 69 +++++++++++++++++++ .../api/controller/FlowRecordController.java | 19 +++-- .../controller/FlowRecordQueryController.java | 31 +++++++-- 5 files changed, 163 insertions(+), 19 deletions(-) create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityHeaderResolveTest.java diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md index 409b957c..b978d9d3 100644 --- a/docs/Integration/operator-identity.md +++ b/docs/Integration/operator-identity.md @@ -100,21 +100,36 @@ public IFlowOperator get(long id, String identity) { ### 3.3 请求声明身份 -REST 接口支持 `operatorIdentity` 参数(与 `operatorId` 对称):未传时取当前登录操作者的身份;若同时用 `operatorId` -覆盖了人员,身份归默认身份(避免出现「人员与身份错配」的副本)。 +REST 接口通过**请求头** `X-Operator-Identity` 声明当前身份(issue #301):未传时取当前登录操作者的身份; +若同时用 `operatorId` 覆盖了人员,身份归默认身份(避免出现「人员与身份错配」的副本)。 +显式选择「默认身份」时传空值(`X-Operator-Identity:`),与「未携带」区分。 + +> ⚠️ **不要用 query 参数 `operatorIdentity` 传身份**:引擎的部分查询接口(如 `/api/query/workflow/list`) +> 用 `SearchRequest` 接收请求,会把所有 query 参数当作实体过滤字段解析,多一个 `operatorIdentity` 就会抛 +> `Field operatorIdentity not found in class hierarchy`,页面直接 500。 +> 为兼容旧调用方,服务端仍保留 query 读取(非 `SearchRequest` 接口可用),但请求头优先。 ```bash # 以 department1 的身份发起(身份随记录落库:create_operator_identity) -curl -X POST 'http://host/api/cmd/record/create?operatorIdentity=department1' \ +curl -X POST 'http://host/api/cmd/record/create' \ + -H 'X-Operator-Identity: department1' \ -H 'Content-Type: application/json' -d '{...}' -# 查看待办:默认跨身份,operatorIdentity 只是「本次操作身份」上下文,不影响返回范围 -curl 'http://host/api/query/record/todo?operatorId=1&operatorIdentity=department1' +# 查看待办:默认跨身份,X-Operator-Identity 只是「本次操作身份」上下文,不影响返回范围 +curl 'http://host/api/query/record/todo?operatorId=1' -H 'X-Operator-Identity: department1' # 只想看「落在 department1 下」的待办时,显式锁定身份(见 4.3) -curl 'http://host/api/query/record/todo?operatorId=1&operatorIdentity=department1&identityScope=LOCKED' +curl 'http://host/api/query/record/todo?operatorId=1' \ + -H 'X-Operator-Identity: department1' \ + -H 'X-Identity-Scope: LOCKED' ``` +| 请求头 | 取值 | 说明 | +|---|---|---| +| `X-Operator-Identity` | 身份标识 / 空串 | 当前操作/查看的身份,空串表示显式默认身份 | +| `X-Identity-Scope` | `ALL` / `LOCKED` | 查询范围:默认跨身份,`LOCKED` 只看当前身份 | +| `X-Lock-Identity` | `true` / `false` | `X-Identity-Scope` 的等价简写 | + 编程式 API 中对应各请求对象的 `operatorIdentity` 字段: | 请求对象 | 字段 | diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java index afe2c645..06ff49f4 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java @@ -36,9 +36,45 @@ public final class OperatorIdentity { */ public static final String KEY_SEPARATOR = "#"; + /** + * 当前身份的请求头名称(issue #301)。 + * + *

    身份是请求上下文,不应放在 query 中:引擎的查询接口用 {@code SearchRequest} 接收请求, + * 会把所有 query 参数当作实体过滤字段解析,多一个 {@code operatorIdentity} 就会抛 + * {@code Field operatorIdentity not found in class hierarchy}。 + * + *

    为兼容旧前端与 curl 直连,服务端仍保留 query 读取,但请求头优先。 + */ + public static final String HEADER_OPERATOR_IDENTITY = "X-Operator-Identity"; + + /** + * 查询身份范围的请求头名称,取值 {@code ALL} / {@code LOCKED}(issue #301) + */ + public static final String HEADER_IDENTITY_SCOPE = "X-Identity-Scope"; + + /** + * 是否锁定身份查询的请求头名称,取值 {@code true} / {@code false}(issue #301) + */ + public static final String HEADER_LOCK_IDENTITY = "X-Lock-Identity"; + private OperatorIdentity() { } + /** + * 选取身份原始值:请求头优先,其次请求参数(issue #301)。 + * + * @param headerValue 请求头中的原始值,未携带时为 {@code null} + * @param parameterValue 请求参数中的原始值 + * @param parameterPresent 请求参数是否显式出现(区分「未传」与「传了空串」) + * @return 原始值;两者都未携带时返回 {@code null} + */ + public static String pick(String headerValue, String parameterValue, boolean parameterPresent) { + if (headerValue != null) { + return headerValue; + } + return parameterPresent ? parameterValue : null; + } + /** * 归一化身份标识:null 转为空串,其余原样返回。 * diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityHeaderResolveTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityHeaderResolveTest.java new file mode 100644 index 00000000..a568bc70 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityHeaderResolveTest.java @@ -0,0 +1,69 @@ +package com.codingapi.flow.operator; + +import com.codingapi.flow.exception.FlowValidationException; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * 身份取值优先级测试(issue #301)。 + * + *

    背景:身份原先只从 query 参数读取,而引擎查询接口用 {@code SearchRequest} 接收请求, + * 会把 query 参数当成实体过滤字段,导致 + * {@code Field operatorIdentity not found in class hierarchy}。 + * 改为请求头优先,同时保留 query 兼容。 + */ +class OperatorIdentityHeaderResolveTest { + + @Test + void should_prefer_header_over_parameter() { + // given:请求头与 query 同时携带,且取值不同 + String header = "department1"; + String parameter = "department2"; + + // when + String raw = OperatorIdentity.pick(header, parameter, true); + + // then:请求头优先 + assertEquals("department1", OperatorIdentity.validate(raw)); + } + + @Test + void should_fallback_to_parameter_when_header_absent() { + // given:仅 query 携带(旧前端 / curl 直连) + // when + String raw = OperatorIdentity.pick(null, "department1", true); + + // then + assertEquals("department1", OperatorIdentity.validate(raw)); + } + + @Test + void should_return_null_when_neither_present() { + // given / when:两者都未携带,交由调用方回退到登录用户身份 + String raw = OperatorIdentity.pick(null, null, false); + + // then + assertNull(raw); + } + + @Test + void should_treat_empty_header_as_default_identity() { + // given:显式选择「默认身份」时请求头为空串,需要与「未携带」区分 + // when + String raw = OperatorIdentity.pick("", "department1", true); + + // then:空串表示默认身份,不能回退到 query + assertEquals(OperatorIdentity.DEFAULT, OperatorIdentity.validate(raw)); + } + + @Test + void should_reject_invalid_identity_from_header() { + // given:请求头携带非法身份(包含合并键分隔符) + // when / then:入口即拒绝,避免污染落库与缓存键 + String raw = OperatorIdentity.pick("department#1", null, false); + assertThrows(FlowValidationException.class, () -> OperatorIdentity.validate(raw)); + } +} 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 d54cd745..2455dc2a 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 @@ -55,18 +55,25 @@ private long loadCurrentOperatorId() { } /** - * 当前操作人的身份标识(issue #288)。 + * 当前操作人的身份标识(issue #288 / #301)。 * - *

    与 {@link #loadCurrentOperatorId()} 对称:优先取请求参数 {@code operatorIdentity}, - * 其次取当前登录操作者自身的身份。身份是会话级信息,因此统一在这里解析后注入各请求对象, - * 避免每个接口各自解析导致行为不一致。 + *

    与 {@link #loadCurrentOperatorId()} 对称:优先取请求头 {@code X-Operator-Identity}, + * 其次取请求参数 {@code operatorIdentity}(兼容旧前端与 curl 直连),最后取当前登录操作者自身的身份。 + * 身份是会话级信息,因此统一在这里解析后注入各请求对象,避免每个接口各自解析导致行为不一致。 + * + *

    之所以以请求头优先:查询接口用 {@code SearchRequest} 接收请求,会把 query 参数当作实体 + * 过滤字段解析,身份放在 query 会让列表接口直接 500(issue #301)。 */ private String loadCurrentOperatorIdentity() { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpServletRequest request = attributes.getRequest(); - if (request.getParameterMap().containsKey("operatorIdentity")) { + String raw = OperatorIdentity.pick( + request.getHeader(OperatorIdentity.HEADER_OPERATOR_IDENTITY), + request.getParameter("operatorIdentity"), + request.getParameterMap().containsKey("operatorIdentity")); + if (raw != null) { // 入口即校验:长度 / 分隔符 / 控制字符不合法时直接拒绝,避免拖到落库阶段才失败 - return OperatorIdentity.validate(request.getParameter("operatorIdentity")); + return OperatorIdentity.validate(raw); } // 覆盖了 operatorId(联调、无登录态场景)时不再继承登录用户的身份, // 否则会得到「目标人员 + 当前登录人身份」的错配组合(issue #288 评审修复) diff --git a/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java b/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java index 7093e1b5..56269bb0 100644 --- a/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java +++ b/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java @@ -55,10 +55,13 @@ private long loadCurrentOperatorId(){ } /** - * 当前操作人身份标识(issue #288 / #297)。 + * 当前操作人身份标识(issue #288 / #297 / #301)。 * - *

    优先取请求参数 {@code operatorIdentity}(宿主声明「我以哪个身份操作/查看」), - * 其次取当前登录操作者自身的身份,都为空时表示默认身份。 + *

    优先取请求头 {@code X-Operator-Identity},其次取请求参数 {@code operatorIdentity} + * (兼容旧前端与 curl 直连),最后取当前登录操作者自身的身份,都为空时表示默认身份。 + * + *

    以请求头优先的原因:本控制器的列表接口用 {@code SearchRequest} 接收请求,会把 query + * 参数当作实体过滤字段解析,身份放在 query 会让待办/已办/抄送/列表接口直接 500(issue #301)。 * *

    该值只作为身份上下文使用:它不会隐式改变查询范围——查询是否按身份过滤由 * {@code identityScope} 显式控制,因此宿主始终携带它也不会导致待办「消失」。 @@ -66,9 +69,13 @@ private long loadCurrentOperatorId(){ private String loadCurrentOperatorIdentity(){ ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpServletRequest request = attributes.getRequest(); - if(request.getParameterMap().containsKey("operatorIdentity")) { + String raw = OperatorIdentity.pick( + request.getHeader(OperatorIdentity.HEADER_OPERATOR_IDENTITY), + request.getParameter("operatorIdentity"), + request.getParameterMap().containsKey("operatorIdentity")); + if(raw != null) { // 入口即校验,与命令侧口径一致(issue #288 评审修复) - return OperatorIdentity.validate(request.getParameter("operatorIdentity")); + return OperatorIdentity.validate(raw); } // 覆盖了 operatorId(联调、无登录态场景)时不再继承登录用户的身份,避免人员与身份错配 if(StringUtils.hasText(request.getParameter("operatorId"))) { @@ -95,13 +102,23 @@ private String loadCurrentOperatorIdentity(){ * *

    注意:{@code operatorIdentity} 只表示「本次操作/查看的身份上下文」, * 不再隐式决定查询范围。宿主仍然可以一直携带它,不会影响返回结果。 + * + *

    参数优先取请求头({@code X-Identity-Scope} / {@code X-Lock-Identity}), + * 避免被 {@code SearchRequest} 当成实体字段解析(issue #301)。 */ private boolean isIdentityLocked() { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpServletRequest request = attributes.getRequest(); - String scope = request.getParameter(IDENTITY_SCOPE_PARAM); + String scope = OperatorIdentity.pick( + request.getHeader(OperatorIdentity.HEADER_IDENTITY_SCOPE), + request.getParameter(IDENTITY_SCOPE_PARAM), + request.getParameterMap().containsKey(IDENTITY_SCOPE_PARAM)); if (!StringUtils.hasText(scope)) { - return "true".equalsIgnoreCase(request.getParameter(LOCK_IDENTITY_PARAM)); + String locked = OperatorIdentity.pick( + request.getHeader(OperatorIdentity.HEADER_LOCK_IDENTITY), + request.getParameter(LOCK_IDENTITY_PARAM), + request.getParameterMap().containsKey(LOCK_IDENTITY_PARAM)); + return "true".equalsIgnoreCase(locked); } String normalized = scope.trim().toUpperCase(); if (IDENTITY_SCOPE_ALL.equals(normalized)) { From 4520112fee77ffb00445e4a33d7b6de388554834 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Thu, 3 Dec 2026 15:29:35 +0800 Subject: [PATCH 21/35] =?UTF-8?q?feat:=20=E5=8F=96=E4=BA=BA=E8=84=9A?= =?UTF-8?q?=E6=9C=AC=E6=94=AF=E6=8C=81=E8=BF=94=E5=9B=9E=20OperatorKey=20?= =?UTF-8?q?=E4=B8=8E=E6=93=8D=E4=BD=9C=E8=80=85=E5=AF=B9=E8=B1=A1=20(issue?= =?UTF-8?q?=20#303)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 脚本返回值不再被强转为 Long,统一由 OperatorScriptResultResolver 解析, 支持 List(默认身份)、List(按身份回查)、 List(直接采用)三种形态,允许同一列表混用。 - 新增 OperatorScriptResultResolver:按身份分组批量回查、按脚本顺序输出, 非正数 id(存量 -1 表示无审批人)跳过,非法元素抛 FlowValidationException - OperatorLoadScript / ErrorTriggerScript 统一走解析器 - OperatorLoadStrategy 的分配回查逻辑下沉到解析器 - 脚本 API:request.getCreatedOperatorKey / getCurrentOperatorKey / getSubmitOperatorKey / findPreviousNodeOperators,$bind.getOperatorKey - FlowSession 新增 loadPreviousNodeOperators(保留记录上的身份) - 脚本工厂的描述同步三种返回形态 Refs #303 --- .../exception/FlowValidationException.java | 20 ++ .../factory/FlowGroovyScriptFactory.java | 14 +- .../flow/script/node/ErrorTriggerScript.java | 29 +- .../flow/script/node/OperatorLoadScript.java | 18 +- .../OperatorScriptResultResolver.java | 274 ++++++++++++++++++ .../flow/script/request/GroovyScriptBind.java | 9 + .../script/request/GroovyScriptRequest.java | 49 ++++ .../codingapi/flow/session/FlowSession.java | 37 ++- .../strategy/node/OperatorLoadStrategy.java | 31 +- .../flow/script/ErrorTriggerScriptTest.java | 69 +++++ .../script/node/OperatorLoadScriptTest.java | 193 ++++++++++++ .../OperatorScriptResultResolverTest.java | 245 ++++++++++++++++ .../OperatorScriptIdentityFlowTest.java | 206 +++++++++++++ 13 files changed, 1137 insertions(+), 57 deletions(-) create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptResultResolver.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/script/node/OperatorLoadScriptTest.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorScriptIdentityFlowTest.java diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java b/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java index f089295f..dfad0f91 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java @@ -170,6 +170,26 @@ public static FlowValidationException invalidParameter(String fieldName, String String.format("Parameter %s has invalid value '%s', expected %s", fieldName, value, expected)); } + /** + * 取人脚本返回值中存在不支持的元素(issue #303)。 + * + *

    替代原先的 {@code NumberFormatException}:脚本写出非法返回值时给出脚本类型、 + * 元素类型与元素内容,便于定位是哪个脚本、返回了什么。 + * + * @param scriptType 脚本类型标识(如 {@code operatorLoad} / {@code errorTrigger}) + * @param elementType 不支持的元素类型 + * @param elementValue 不支持的元素内容 + * @return exception + */ + public static FlowValidationException operatorScriptResultInvalid(String scriptType, + String elementType, + String elementValue) { + return new FlowValidationException("validation.operator.scriptResult.invalid", + String.format("Unsupported operator script result element from %s: %s (%s), " + + "supported forms: List, List, List", + scriptType, elementType, elementValue)); + } + /** * 节点未匹配到审批人且异常处理配置为「异常提示」,需要阻断本次操作(issue #296)。 *

    diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/factory/FlowGroovyScriptFactory.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/factory/FlowGroovyScriptFactory.java index 835fa602..5ffaad7b 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/factory/FlowGroovyScriptFactory.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/factory/FlowGroovyScriptFactory.java @@ -157,8 +157,13 @@ public static GroovyScript createOperatorLoadScript(String script) { String key = FlowIDGeneratorGatewayContext.getInstance().generateFlowScriptKey(); String description = """ 匹配人员列表脚本 - 传入对象为 GroovyScriptRequest 对象,返回数据格式为 List<Long> 类型,即 long[] 数组格式,每一个 long 的 id 数据为一个人员的 id,示例格式为 [1,2,3]。 - 返回的人员 id 将会作为匹配人员信息,作为流程的审批者。 + 传入对象为 GroovyScriptRequest 对象,返回数据格式支持三种,且允许在同一列表中混用: +

      +
    • List<Long>:人员 id 列表(默认身份),示例 [1,2,3];
    • +
    • List<OperatorKey>:带身份的人员标识,示例 [request.getCreatedOperatorKey()]、[$bind.getOperatorKey(2,'department1')];
    • +
    • List<IFlowOperator>:操作者对象,直接采用且不回查,示例 [$bind.getOperatorByIdentity(2,'department1')]、request.findPreviousNodeOperators()。
    • +
    + 返回的人员将会作为该节点的审批者,身份随记录落库。 """; GroovyScript groovyScript = GroovyScript.builder(key) @@ -203,10 +208,11 @@ public static GroovyScript createErrorTriggerScript(String script) { String description = """ 异常触发脚本 脚本说明:所谓的异常脚本,是指流程在执行时没有匹配到审批人员时触发的情况。 - 传入对象为 GroovyScriptRequest 对象,返回数据格式为 Object 类型,实际支持两种数据结构: + 传入对象为 GroovyScriptRequest 对象,返回数据格式为 Object 类型,实际支持以下数据结构:
    • String 格式:对应的节点 id(nodeId)。当返回字符串类型的节点 id 时,出现异常时会跳转到对应的节点上执行审批。
    • -
    • List<Long> 格式:即 long[] 格式,示例:return [1,2,3]。当返回 List<Long> 格式时,代表指定审批人员,即当异常时将会将这个流程转交给指定的这些人员来审批。
    • +
    • 人员列表格式:支持 List<Long>(默认身份,示例 return [1,2,3])、List<OperatorKey>(带身份,示例 return [request.getCreatedOperatorKey()])、List<IFlowOperator>(对象直接采用,示例 return [$bind.getOperatorByIdentity(2,'department1')])。当返回人员列表时,代表指定审批人员,即当异常时将会将这个流程转交给指定的这些人员来审批。
    • +
    • Map 格式:[type:'prompt', message:'...'] 异常提示,或 [type:'node', node:'节点id']、[type:'operators', operators:[...]] 显式声明类型。
    """; diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/ErrorTriggerScript.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/ErrorTriggerScript.java index 7b53600d..3cd36c7b 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/ErrorTriggerScript.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/ErrorTriggerScript.java @@ -1,7 +1,7 @@ package com.codingapi.flow.script.node; import com.codingapi.flow.error.ErrorThrow; -import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.script.operator.OperatorScriptResultResolver; import com.codingapi.flow.script.registry.ScriptRegistryContext; import com.codingapi.flow.script.request.GroovyScriptBind; import com.codingapi.flow.script.request.GroovyScriptRequest; @@ -12,7 +12,6 @@ import lombok.AllArgsConstructor; import lombok.Getter; -import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -25,14 +24,21 @@ *
  • {@code Map}:{@code [type:'prompt', message:'...']} 异常提示,或 {@code [type:'node', node:'节点id']} / * {@code [type:'operators', operators:[1,2]]} 显式声明类型;
  • *
  • {@code String}:跳转节点 id(历史写法);
  • - *
  • {@code List}:默认审批人员 id 列表(历史写法);
  • + *
  • {@code List}:默认审批人员列表(历史写法);
  • *
  • {@code Number}:单个默认审批人员 id(历史写法)。
  • * + * 人员列表经 {@link OperatorScriptResultResolver} 解析,支持 {@code List} / + * {@code List} / {@code List} 三种元素形态(issue #303)。 * 历史写法全部保持兼容。 */ @AllArgsConstructor public class ErrorTriggerScript { + /** + * 脚本类型标识,用于解析异常上下文 + */ + private static final String SCRIPT_TYPE = "errorTrigger"; + @Getter @GroovyScript private final String script; @@ -50,15 +56,12 @@ public ErrorThrow execute(FlowSession session) { errorThrow.setNode(session.getNode(nodeId)); return errorThrow; } - if (value instanceof List userIds) { - return parseOperators(session, userIds); + if (value instanceof List operators) { + return parseOperators(session, operators); } - long userId = Long.parseLong(String.valueOf(value)); ErrorThrow errorThrow = new ErrorThrow(); - List operatorList = new ArrayList<>(); - operatorList.add(session.getRepositoryHolder().getOperatorById(userId)); - errorThrow.setOperators(operatorList); + errorThrow.setOperators(OperatorScriptResultResolver.resolve(session, value, SCRIPT_TYPE)); return errorThrow; } @@ -104,13 +107,9 @@ private ErrorThrow parseMap(FlowSession session, Map map) { return new ErrorThrow(); } - private ErrorThrow parseOperators(FlowSession session, List userIds) { - List operatorIds = new ArrayList<>(); - for (Object userId : userIds) { - operatorIds.add(Long.parseLong(String.valueOf(userId))); - } + private ErrorThrow parseOperators(FlowSession session, List operators) { ErrorThrow errorThrow = new ErrorThrow(); - errorThrow.setOperators(session.getRepositoryHolder().findOperatorByIds(operatorIds)); + errorThrow.setOperators(OperatorScriptResultResolver.resolve(session, operators, SCRIPT_TYPE)); return errorThrow; } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/OperatorLoadScript.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/OperatorLoadScript.java index 9ee3780d..14f2d730 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/OperatorLoadScript.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/OperatorLoadScript.java @@ -1,6 +1,7 @@ package com.codingapi.flow.script.node; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.script.operator.OperatorScriptResultResolver; import com.codingapi.flow.script.registry.ScriptRegistryContext; import com.codingapi.flow.script.request.GroovyScriptBind; import com.codingapi.flow.script.request.GroovyScriptRequest; @@ -11,16 +12,23 @@ import lombok.AllArgsConstructor; import lombok.Getter; -import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 人员加载脚本 + * + *

    返回值经 {@link OperatorScriptResultResolver} 解析,支持 {@code List} / + * {@code List} / {@code List}(issue #303)。 */ @AllArgsConstructor public class OperatorLoadScript { + /** + * 脚本类型标识,用于解析异常上下文 + */ + private static final String SCRIPT_TYPE = "operatorLoad"; + @Getter @GroovyScript @@ -28,14 +36,10 @@ public class OperatorLoadScript { public List execute(FlowSession session) { GroovyScriptRequest request = new GroovyScriptRequest(session); - List userIds = FlowScriptRuntimeContext.getInstance() + Object scriptResult = FlowScriptRuntimeContext.getInstance() .getGroovyScript(script) .invoke(Map.of("$bind", new GroovyScriptBind(FlowScriptContext.getInstance())), request); - List operatorIds = new ArrayList<>(); - for (Object userId : userIds) { - operatorIds.add(Long.parseLong(String.valueOf(userId))); - } - return session.getRepositoryHolder().findOperatorByIds(operatorIds); + return OperatorScriptResultResolver.resolve(session, scriptResult, SCRIPT_TYPE); } /** diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptResultResolver.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptResultResolver.java new file mode 100644 index 00000000..f5c193fa --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptResultResolver.java @@ -0,0 +1,274 @@ +package com.codingapi.flow.script.operator; + +import com.codingapi.flow.exception.FlowValidationException; +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; +import com.codingapi.flow.session.FlowSession; +import com.codingapi.flow.session.IRepositoryHolder; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * 取人脚本返回值解析器(issue #303)。 + * + *

    负责把脚本返回值统一解析为 {@link IFlowOperator} 列表,是「脚本返回值 → 流程参与人」的唯一边界。 + * 支持三种元素形态,允许同一列表内混用,逐元素判定: + *

      + *
    1. {@link IFlowOperator} —— 直接采用,不回查,身份取对象自带的 {@code getIdentity()};
    2. + *
    3. {@link OperatorKey} —— 按身份分组批量回查,身份取 {@code key.identity()};
    4. + *
    5. {@link Number}(含纯数字字符串)—— 按默认身份批量回查,保持存量脚本行为。
    6. + *
    + * + *

    顶层允许非集合的单值(自动包装为单元素列表)与 {@code null}(视为无人员), + * 便于存量脚本 {@code return request.getCreatedOperatorId()} 继续可用。 + * + *

    非正数的人员 id(存量脚本用 {@code -1} 表示「无审批人」)视为「该元素无人员」,直接跳过, + * 不抛异常,保证「未匹配到审批人」仍由下游的异常处理逻辑接管。 + * + *

    回查按身份分组批量执行,避免逐个回查造成 N+1;结果按脚本返回顺序重排, + * 保证多人审批的执行顺序稳定。 + * + * @see OperatorKey + */ +public final class OperatorScriptResultResolver { + + /** + * 默认脚本类型标识,仅用于异常上下文 + */ + private static final String DEFAULT_SCRIPT_TYPE = "operatorScript"; + + private OperatorScriptResultResolver() { + } + + /** + * 解析脚本返回值(从会话中取仓储)。 + * + * @param session 流程会话,不能为空 + * @param scriptResult 脚本返回值,支持集合 / 数组 / 单值 / {@code null} + * @return 流程参与人列表,顺序与脚本返回一致 + */ + public static List resolve(FlowSession session, Object scriptResult) { + return resolve(session.getRepositoryHolder(), scriptResult, DEFAULT_SCRIPT_TYPE); + } + + /** + * 解析脚本返回值(从会话中取仓储,指定脚本类型用于异常上下文)。 + * + * @param session 流程会话 + * @param scriptResult 脚本返回值 + * @param scriptType 脚本类型标识 + * @return 流程参与人列表 + */ + public static List resolve(FlowSession session, Object scriptResult, String scriptType) { + return resolve(session.getRepositoryHolder(), scriptResult, scriptType); + } + + /** + * 解析脚本返回值(指定仓储)。 + * + * @param repositoryHolder 仓储持有者 + * @param scriptResult 脚本返回值 + * @return 流程参与人列表 + */ + public static List resolve(IRepositoryHolder repositoryHolder, Object scriptResult) { + return resolve(repositoryHolder, scriptResult, DEFAULT_SCRIPT_TYPE); + } + + /** + * 解析脚本返回值(指定仓储与脚本类型,用于异常上下文)。 + * + * @param repositoryHolder 仓储持有者 + * @param scriptResult 脚本返回值 + * @param scriptType 脚本类型标识(如 {@code operatorLoad} / {@code errorTrigger}) + * @return 流程参与人列表 + * @throws FlowValidationException 返回值中存在不支持的元素 + */ + public static List resolve(IRepositoryHolder repositoryHolder, + Object scriptResult, + String scriptType) { + List elements = toElements(scriptResult); + if (elements.isEmpty()) { + return List.of(); + } + + List slots = new ArrayList<>(elements.size()); + List pendingKeys = new ArrayList<>(); + for (Object element : elements) { + if (element == null) { + continue; + } + if (element instanceof IFlowOperator operator) { + if (!hasUserId(operator.getUserId())) { + continue; + } + slots.add(new Slot(operator, null)); + continue; + } + if (element instanceof OperatorKey key) { + if (!hasUserId(key.operatorId())) { + continue; + } + slots.add(new Slot(null, key)); + pendingKeys.add(key); + continue; + } + if (element instanceof Number number) { + long userId = toUserId(number, element, scriptType); + if (!hasUserId(userId)) { + continue; + } + OperatorKey key = OperatorKey.ofDefault(userId); + slots.add(new Slot(null, key)); + pendingKeys.add(key); + continue; + } + if (element instanceof CharSequence text) { + String value = text.toString().trim(); + if (value.isEmpty()) { + continue; + } + if (!isNumeric(value)) { + throw FlowValidationException.operatorScriptResultInvalid( + scriptType, element.getClass().getName(), value); + } + long userId = parseUserId(value, element, scriptType); + if (!hasUserId(userId)) { + continue; + } + OperatorKey key = OperatorKey.ofDefault(userId); + slots.add(new Slot(null, key)); + pendingKeys.add(key); + continue; + } + throw FlowValidationException.operatorScriptResultInvalid( + scriptType, element.getClass().getName(), String.valueOf(element)); + } + + if (slots.isEmpty()) { + return List.of(); + } + + Map resolved = batchResolve(repositoryHolder, pendingKeys); + List operators = new ArrayList<>(slots.size()); + for (Slot slot : slots) { + if (slot.operator() != null) { + operators.add(slot.operator()); + continue; + } + IFlowOperator operator = resolved.get(slot.key().key()); + if (operator != null) { + operators.add(operator); + } + } + return operators; + } + + /** + * 按身份分组批量回查,返回以 {@link OperatorKey#key()} 为键的操作者索引。 + * + * @param repositoryHolder 仓储持有者 + * @param keys 待回查的操作者标识 + * @return 操作者索引 + */ + private static Map batchResolve(IRepositoryHolder repositoryHolder, + List keys) { + if (keys.isEmpty()) { + return Map.of(); + } + Map> operatorIdsByIdentity = new LinkedHashMap<>(); + for (OperatorKey key : keys) { + operatorIdsByIdentity + .computeIfAbsent(key.identity(), identity -> new ArrayList<>()) + .add(key.operatorId()); + } + Map operatorMap = new HashMap<>(); + operatorIdsByIdentity.forEach((identity, operatorIds) -> { + List operators = repositoryHolder.findOperatorByIds(operatorIds, identity); + if (operators == null) { + return; + } + for (IFlowOperator operator : operators) { + operatorMap.put(OperatorKey.of(operator.getUserId(), identity).key(), operator); + } + }); + return operatorMap; + } + + /** + * 把脚本返回值归一化为元素列表:集合 / 数组 / 单值 / {@code null} + */ + private static List toElements(Object scriptResult) { + if (scriptResult == null) { + return List.of(); + } + if (scriptResult instanceof Collection collection) { + return new ArrayList<>(collection); + } + if (scriptResult.getClass().isArray()) { + int length = Array.getLength(scriptResult); + List elements = new ArrayList<>(length); + for (int i = 0; i < length; i++) { + elements.add(Array.get(scriptResult, i)); + } + return elements; + } + List elements = new ArrayList<>(1); + elements.add(scriptResult); + return elements; + } + + private static long toUserId(Number number, Object element, String scriptType) { + double value = number.doubleValue(); + long userId = number.longValue(); + if (value != (double) userId) { + throw FlowValidationException.operatorScriptResultInvalid( + scriptType, element.getClass().getName(), String.valueOf(element)); + } + return userId; + } + + private static long parseUserId(String value, Object element, String scriptType) { + try { + return Long.parseLong(value); + } catch (NumberFormatException e) { + throw FlowValidationException.operatorScriptResultInvalid( + scriptType, element.getClass().getName(), value); + } + } + + /** + * 是否为有效人员 id。非正数(如存量脚本用 {@code -1} 表示「无审批人」)视为「该元素无人员」, + * 直接跳过,保持历史行为并让下游继续走「未匹配到审批人」的异常处理。 + */ + private static boolean hasUserId(long userId) { + return userId > 0; + } + + private static boolean isNumeric(String value) { + if (value.isEmpty()) { + return false; + } + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (i == 0 && c == '-') { + continue; + } + if (!Character.isDigit(c)) { + return false; + } + } + return true; + } + + /** + * 输出位置的占位:直接采用的对象,或待回查的标识 + */ + private record Slot(IFlowOperator operator, OperatorKey key) { + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptBind.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptBind.java index 4da88028..ce93d22d 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptBind.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptBind.java @@ -1,6 +1,7 @@ package com.codingapi.flow.script.request; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.script.runtime.FlowScriptContext; import com.codingapi.springboot.script.annotation.ScriptFunction; @@ -66,6 +67,14 @@ public IFlowOperator getOperatorByIdentity(@ScriptParameter(description = "用 return context.getOperatorById(userId, identity); } + @ScriptFunction( + name = "getOperatorKey", + description = "根据用户id与身份标识构造操作者标识(不回查),可直接作为取人脚本返回值(issue #303)") + public OperatorKey getOperatorKey(@ScriptParameter(description = "用户id") long userId, + @ScriptParameter(description = "身份标识") String identity) { + return OperatorKey.of(userId, identity); + } + @ScriptFunction( name = "findOperatorsByIds", description = "根据用户id获取流程用户列表" diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptRequest.java index 84bb2e02..92675416 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptRequest.java @@ -5,6 +5,7 @@ import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.pojo.request.FlowCreateRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; @@ -216,6 +217,23 @@ public List findPreviousNodeOperatorIds() { return this.flowSession.loadPreviousNodeOperatorIds(); } + /** + * 获取上一节点的审批人员列表(含身份,issue #303)。 + *

    由 {@link FlowSession#loadPreviousNodeOperators()} 提供能力,此处仅做透传。 + * 与 {@link #findPreviousNodeOperatorIds()} 的区别:返回带身份的操作者,可直接作为取人脚本返回值。 + *

    +     * def run(request){
    +     *     return request.findPreviousNodeOperators()
    +     * }
    +     * 
    + * + * @return 上一节点的审批人员列表,无法确定时返回空列表 + */ + @ScriptFunction(name = "findPreviousNodeOperators", description = "获取上一节点审批人员列表(含身份)") + public List findPreviousNodeOperators() { + return this.flowSession.loadPreviousNodeOperators(); + } + /** * 获取当前操作对象 */ @@ -314,6 +332,37 @@ public String getSubmitOperatorIdentity() { return OperatorIdentity.of(this.submitOperator); } + /** + * 流程创建者标识(人员id + 身份,issue #303) + *

    取人脚本默认返回该对象,保证创建者以「发起时的身份」参与流程,而不是退化为默认身份。 + * + * @return 创建者标识 + */ + @ScriptFunction(name = "getCreatedOperatorKey", description = "获取流程创建者标识(含身份)") + public OperatorKey getCreatedOperatorKey() { + return OperatorKey.of(this.createdOperator.getUserId(), OperatorIdentity.of(this.createdOperator)); + } + + /** + * 流程审批者标识(人员id + 身份,issue #303) + * + * @return 当前审批者标识 + */ + @ScriptFunction(name = "getCurrentOperatorKey", description = "获取流程审批者标识(含身份)") + public OperatorKey getCurrentOperatorKey() { + return OperatorKey.of(this.currentOperator.getUserId(), OperatorIdentity.of(this.currentOperator)); + } + + /** + * 流程提交人标识(人员id + 身份,issue #303) + * + * @return 提交人标识 + */ + @ScriptFunction(name = "getSubmitOperatorKey", description = "获取流程提交人标识(含身份)") + public OperatorKey getSubmitOperatorKey() { + return OperatorKey.of(this.submitOperator.getUserId(), OperatorIdentity.of(this.submitOperator)); + } + /** * 获取开始节点 diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/session/FlowSession.java b/flow-engine-framework/src/main/java/com/codingapi/flow/session/FlowSession.java index 920bfe1c..465221ff 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/session/FlowSession.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/session/FlowSession.java @@ -11,16 +11,19 @@ import com.codingapi.flow.mock.MockRepositoryHolder; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; 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.record.FlowRecord; +import com.codingapi.flow.script.operator.OperatorScriptResultResolver; import com.codingapi.flow.script.request.GroovyScriptRequest; import com.codingapi.flow.workflow.Workflow; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; +import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; @@ -156,6 +159,37 @@ public boolean isMock() { * @return 上一节点的审批人员Id列表,无法确定时返回空列表 */ public List loadPreviousNodeOperatorIds() { + return findPreviousNodeRecords() + .stream() + .map(FlowRecord::getCurrentOperatorId) + .distinct() + .sorted() + .toList(); + } + + /** + * 获取上一节点的审批人员列表(含身份,issue #303)。 + * + *

    记录筛选口径与 {@link #loadPreviousNodeOperatorIds()} 完全一致(直接前驱 + 排除自动跳过), + * 区别是保留记录的 {@code currentOperatorIdentity},按 {@code (人员id, 身份)} 回查操作者, + * 供取人脚本复用前序节点审批人时不再退化为默认身份。 + * + * @return 上一节点的审批人员列表,无法确定时返回空列表 + */ + public List loadPreviousNodeOperators() { + List operatorKeys = findPreviousNodeRecords() + .stream() + .map(record -> OperatorKey.of(record.getCurrentOperatorId(), record.getCurrentOperatorIdentity())) + .distinct() + .sorted(Comparator.comparingLong(OperatorKey::operatorId).thenComparing(OperatorKey::identity)) + .toList(); + return OperatorScriptResultResolver.resolve(repositoryHolder, operatorKeys, "previousNode"); + } + + /** + * 查询上一节点实际审批过的流程记录:直接前驱校验 + 排除自动跳过(issue #188 / #303)。 + */ + private List findPreviousNodeRecords() { if (currentRecord == null || currentNode == null) { return List.of(); } @@ -174,9 +208,6 @@ public List loadPreviousNodeOperatorIds() { return repositoryHolder.findCurrentNodeRecords(nodeInstanceFromId, currentRecord.getNodeId()) .stream() .filter(record -> !record.isAutoDone()) - .map(FlowRecord::getCurrentOperatorId) - .distinct() - .sorted() .toList(); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java b/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java index d0618a07..1af2c12c 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java @@ -5,14 +5,12 @@ import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.script.node.OperatorLoadScript; +import com.codingapi.flow.script.operator.OperatorScriptResultResolver; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; import lombok.Getter; import lombok.NoArgsConstructor; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -79,35 +77,12 @@ public OperatorManager loadOperators(FlowSession flowSession) { /** * 按 {@code (人员id, 身份)} 加载已分配的操作人(issue #288 衍生 / #292)。 * - *

    按身份分组批量回查,避免逐个 {@code getOperatorById} 造成 N+1; + *

    回查逻辑统一由 {@link OperatorScriptResultResolver} 提供:按身份分组批量回查, * 返回顺序与分配顺序一致,保证多人审批的执行顺序稳定。 */ private List loadAssignedOperators(IRepositoryHolder repositoryHolder, List assignedOperators) { - Map> operatorIdsByIdentity = new LinkedHashMap<>(); - for (OperatorKey operator : assignedOperators) { - operatorIdsByIdentity - .computeIfAbsent(operator.identity(), key -> new ArrayList<>()) - .add(operator.operatorId()); - } - Map operatorMap = new HashMap<>(); - operatorIdsByIdentity.forEach((identity, operatorIds) -> { - List operators = repositoryHolder.findOperatorByIds(operatorIds, identity); - if (operators == null) { - return; - } - for (IFlowOperator operator : operators) { - operatorMap.put(OperatorKey.of(operator.getUserId(), identity).key(), operator); - } - }); - List result = new ArrayList<>(assignedOperators.size()); - for (OperatorKey operator : assignedOperators) { - IFlowOperator flowOperator = operatorMap.get(operator.key()); - if (flowOperator != null) { - result.add(flowOperator); - } - } - return result; + return OperatorScriptResultResolver.resolve(repositoryHolder, assignedOperators, "operatorAssignment"); } /** diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/script/ErrorTriggerScriptTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/script/ErrorTriggerScriptTest.java index 5089edee..db736f8e 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/script/ErrorTriggerScriptTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/script/ErrorTriggerScriptTest.java @@ -224,4 +224,73 @@ def run(request){ assertTrue(errorThrow.isPrompt()); assertEquals("业务方自定义提示:请联系流程管理员", errorThrow.getMessage()); } + + /** + * 新写法:operators 返回 OperatorKey 列表,身份随记录落库(issue #303) + */ + @Test + void should_apply_identity_when_operators_returned_as_operator_keys() { + FlowSession identitySession = sessionWithIdentity("department1"); + String script = """ + def run(request){ + return [request.getCreatedOperatorKey()]; + } + """; + ErrorTriggerScript errorTriggerScript = new ErrorTriggerScript( + FlowGroovyScriptFactory.createErrorTriggerScript(script).getKey()); + + ErrorThrow errorThrow = errorTriggerScript.execute(identitySession); + + assertFalse(errorThrow.isNode()); + assertFalse(errorThrow.isPrompt()); + assertEquals(1, errorThrow.getOperators().size()); + assertEquals(1, errorThrow.getOperators().get(0).getUserId()); + assertEquals("department1", errorThrow.getOperators().get(0).getIdentity()); + } + + /** + * 新写法:operators 直接返回带身份的操作者对象(issue #303) + */ + @Test + void should_apply_identity_when_operators_returned_as_operator_objects() { + FlowSession identitySession = sessionWithIdentity("department1"); + String script = """ + def run(request){ + return [$bind.getOperatorByIdentity(1, 'department2')]; + } + """; + ErrorTriggerScript errorTriggerScript = new ErrorTriggerScript( + FlowGroovyScriptFactory.createErrorTriggerScript(script).getKey()); + + ErrorThrow errorThrow = errorTriggerScript.execute(identitySession); + + assertEquals(1, errorThrow.getOperators().size()); + assertEquals("department2", errorThrow.getOperators().get(0).getIdentity()); + } + + /** + * 新写法:operators 返回单个 OperatorKey(非列表),按单元素处理(issue #303) + */ + @Test + void should_apply_identity_when_single_operator_key_returned() { + FlowSession identitySession = sessionWithIdentity("department1"); + String script = """ + def run(request){ + return $bind.getOperatorKey(1, 'department2'); + } + """; + ErrorTriggerScript errorTriggerScript = new ErrorTriggerScript( + FlowGroovyScriptFactory.createErrorTriggerScript(script).getKey()); + + ErrorThrow errorThrow = errorTriggerScript.execute(identitySession); + + assertEquals(1, errorThrow.getOperators().size()); + assertEquals("department2", errorThrow.getOperators().get(0).getIdentity()); + } + + private FlowSession sessionWithIdentity(String identity) { + return FlowSession.startSession(factory.repositoryHolder, user.asIdentity(identity), + flowSession.getWorkflow(), flowSession.getCurrentNode(), flowSession.getCurrentAction(), + flowSession.getFormData(), 0); + } } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/script/node/OperatorLoadScriptTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/script/node/OperatorLoadScriptTest.java new file mode 100644 index 00000000..00158bee --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/script/node/OperatorLoadScriptTest.java @@ -0,0 +1,193 @@ +package com.codingapi.flow.script.node; + +import com.codingapi.flow.exception.FlowValidationException; +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.FormData; +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.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.script.factory.FlowGroovyScriptFactory; +import com.codingapi.flow.session.FlowSession; +import com.codingapi.flow.user.User; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.WorkflowBuilder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 取人脚本返回值测试(issue #303) + * + *

    覆盖三种返回形态在脚本层的实际执行结果:{@code List}(默认身份)、 + * {@code List}(带身份)、{@code List}(直接采用)。 + */ +class OperatorLoadScriptTest { + + private final MyFlowServiceFactory factory = new MyFlowServiceFactory(); + + private User creator; + private FlowSession flowSession; + + @BeforeEach + void setUp() { + // 网关按 (人员id, 身份) 返回不同实例:缓存里存默认身份用户,创建者是它的 department1 副本 + User base = new User(1, "lorne"); + factory.userGateway.save(base); + factory.userGateway.save(new User(2, "张三")); + creator = base.asIdentity("department1"); + + FlowForm form = FlowFormBuilder.builder() + .name("请假流程") + .code("leave") + .addField("请假人", "name", DataType.STRING) + .build(); + + StartNode startNode = StartNode.builder().build(); + ApprovalNode approvalNode = ApprovalNode.builder().name("经理审批").build(); + EndNode endNode = EndNode.builder().build(); + + Workflow workflow = WorkflowBuilder.builder() + .title("请假流程") + .code("leave") + .createdOperator(creator) + .form(form) + .addNode(startNode) + .addNode(approvalNode) + .addNode(endNode) + .build(); + + FormData data = new FormData(form); + data.getDataBody().set("name", "张三"); + + flowSession = FlowSession.startSession(factory.repositoryHolder, creator, workflow, startNode, + startNode.getActions().get(0), data, 0); + } + + /** + * 存量写法:返回人员 id 列表,默认身份 + */ + @Test + void should_keep_default_identity_when_script_returns_ids() { + List operators = execute(""" + def run(request){ + return [request.getCreatedOperatorId()] + } + """); + + assertEquals(1, operators.size()); + assertEquals(1, operators.get(0).getUserId()); + assertEquals(OperatorIdentity.DEFAULT, operators.get(0).getIdentity()); + } + + /** + * 新默认写法:创建者以「发起时的身份」参与,身份不再丢失 + */ + @Test + void should_apply_created_identity_when_script_returns_operator_key() { + List operators = execute(""" + def run(request){ + return [request.getCreatedOperatorKey()] + } + """); + + assertEquals(1, operators.size()); + assertEquals(1, operators.get(0).getUserId()); + assertEquals("department1", operators.get(0).getIdentity()); + } + + /** + * 文档 §3.4 写法:直接返回带身份的操作者对象,不再抛 NumberFormatException + */ + @Test + void should_use_operator_object_when_script_returns_bind_operator() { + List operators = execute(""" + def run(request){ + return [$bind.getOperatorByIdentity(2, 'department1')] + } + """); + + assertEquals(1, operators.size()); + assertEquals(2, operators.get(0).getUserId()); + assertEquals("department1", operators.get(0).getIdentity()); + } + + /** + * 显式二元组:$bind.getOperatorKey 只构造标识,由解析器按身份回查 + */ + @Test + void should_apply_identity_when_script_returns_bind_key() { + List operators = execute(""" + def run(request){ + return [$bind.getOperatorKey(2, 'department2')] + } + """); + + assertEquals(1, operators.size()); + assertEquals(2, operators.get(0).getUserId()); + assertEquals("department2", operators.get(0).getIdentity()); + } + + /** + * 单值与带身份写法混用,顺序保持脚本返回顺序 + */ + @Test + void should_keep_script_order_when_forms_mixed() { + List operators = execute(""" + def run(request){ + return [$bind.getOperatorKey(2, 'department2'), request.getCreatedOperatorId()] + } + """); + + assertEquals(2, operators.size()); + assertEquals(2, operators.get(0).getUserId()); + assertEquals("department2", operators.get(0).getIdentity()); + assertEquals(1, operators.get(1).getUserId()); + assertEquals(OperatorIdentity.DEFAULT, operators.get(1).getIdentity()); + } + + /** + * 脚本不写 {@code []} 时按单元素处理,保持存量脚本可用 + */ + @Test + void should_wrap_single_value_when_script_returns_id() { + List operators = execute(""" + def run(request){ + return request.getCreatedOperatorId() + } + """); + + assertEquals(1, operators.size()); + assertEquals(1, operators.get(0).getUserId()); + } + + /** + * 非法返回值给出带上下文的校验异常,而不是 NumberFormatException + */ + @Test + void should_throw_validation_exception_when_script_returns_unsupported_element() { + FlowValidationException exception = assertThrows(FlowValidationException.class, () -> execute(""" + def run(request){ + return ['abc'] + } + """)); + + assertTrue(exception.getMessage().contains("operatorLoad"), exception.getMessage()); + assertTrue(exception.getMessage().contains("abc"), exception.getMessage()); + } + + private List execute(String script) { + OperatorLoadScript operatorLoadScript = new OperatorLoadScript( + FlowGroovyScriptFactory.createOperatorLoadScript(script).getKey()); + return operatorLoadScript.execute(flowSession); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java new file mode 100644 index 00000000..257ff554 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java @@ -0,0 +1,245 @@ +package com.codingapi.flow.script.operator; + +import com.codingapi.flow.exception.FlowValidationException; +import com.codingapi.flow.factory.MyFlowServiceFactory; +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorKey; +import com.codingapi.flow.session.IRepositoryHolder; +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Proxy; +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 取人脚本返回值解析测试(issue #303) + * + *

    解析器只服务三种返回形态:{@code List}(默认身份)、{@code List}(按身份回查)、 + * {@code List}(直接采用)。同一列表内允许混用,逐元素判定。 + */ +class OperatorScriptResultResolverTest { + + private MyFlowServiceFactory factory; + private User user1; + private User user2; + private CountingRepositoryHolder countingHolder; + + @BeforeEach + void setUp() { + factory = new MyFlowServiceFactory(); + user1 = new User(1, "lorne"); + user2 = new User(2, "张三"); + factory.userGateway.save(user1); + factory.userGateway.save(user2); + countingHolder = new CountingRepositoryHolder(factory.repositoryHolder); + } + + /** + * 存量形态:纯 {@code List} 保持默认身份,且顺序与脚本返回一致 + */ + @Test + void should_keep_default_identity_and_order_when_script_returns_user_ids() { + List operators = OperatorScriptResultResolver.resolve( + countingHolder.proxy(), List.of(2L, 1L)); + + assertEquals(2, operators.size()); + assertEquals(2, operators.get(0).getUserId()); + assertEquals(1, operators.get(1).getUserId()); + assertEquals(OperatorIdentity.DEFAULT, operators.get(0).getIdentity()); + assertEquals(OperatorIdentity.DEFAULT, operators.get(1).getIdentity()); + } + + /** + * 新形态:{@code OperatorKey} 按身份回查,身份落到操作者上 + */ + @Test + void should_apply_identity_when_script_returns_operator_keys() { + List operators = OperatorScriptResultResolver.resolve( + countingHolder.proxy(), + List.of(OperatorKey.of(2, "department1"), OperatorKey.of(1, null))); + + assertEquals(2, operators.size()); + assertEquals(2, operators.get(0).getUserId()); + assertEquals("department1", operators.get(0).getIdentity()); + assertEquals(1, operators.get(1).getUserId()); + assertEquals(OperatorIdentity.DEFAULT, operators.get(1).getIdentity()); + } + + /** + * 新形态:{@code IFlowOperator} 直接采用,不发生任何回查 + */ + @Test + void should_use_operator_instance_directly_without_query() { + IFlowOperator operator = User.withIdentity(2, "张三", "department1"); + + List operators = OperatorScriptResultResolver.resolve( + countingHolder.proxy(), List.of(operator)); + + assertEquals(1, operators.size()); + assertSame(operator, operators.get(0)); + assertEquals(0, countingHolder.batchQueryCount); + assertEquals(0, countingHolder.singleQueryCount); + } + + /** + * 同一列表混用三种形态,按脚本返回顺序输出 + */ + @Test + void should_resolve_mixed_forms_and_keep_script_order() { + IFlowOperator direct = User.withIdentity(1, "lorne", "department3"); + + List operators = OperatorScriptResultResolver.resolve( + countingHolder.proxy(), + Arrays.asList(2L, OperatorKey.of(1, "department2"), direct)); + + assertEquals(3, operators.size()); + assertEquals(2, operators.get(0).getUserId()); + assertEquals(OperatorIdentity.DEFAULT, operators.get(0).getIdentity()); + assertEquals(1, operators.get(1).getUserId()); + assertEquals("department2", operators.get(1).getIdentity()); + assertSame(direct, operators.get(2)); + assertEquals("department3", operators.get(2).getIdentity()); + } + + /** + * 顶层单值:脚本不写 {@code []} 也能用 + */ + @Test + void should_wrap_single_value_as_single_element() { + List operators = OperatorScriptResultResolver.resolve(countingHolder.proxy(), 2L); + + assertEquals(1, operators.size()); + assertEquals(2, operators.get(0).getUserId()); + } + + /** + * {@code null} 与空列表都表示「无人员」,不报错 + */ + @Test + void should_return_empty_when_result_is_null_or_empty() { + assertTrue(OperatorScriptResultResolver.resolve(countingHolder.proxy(), null).isEmpty()); + assertTrue(OperatorScriptResultResolver.resolve(countingHolder.proxy(), List.of()).isEmpty()); + } + + /** + * 列表内的 {@code null} 元素跳过,不中断其余元素 + */ + @Test + void should_skip_null_elements() { + List operators = OperatorScriptResultResolver.resolve( + countingHolder.proxy(), Arrays.asList(null, 2L)); + + assertEquals(1, operators.size()); + assertEquals(2, operators.get(0).getUserId()); + } + + /** + * 同一人的不同身份是两个参与人,不能被去重 + */ + @Test + void should_not_merge_same_user_with_different_identity() { + List operators = OperatorScriptResultResolver.resolve( + countingHolder.proxy(), + List.of(OperatorKey.of(1, "department1"), OperatorKey.of(1, "department2"))); + + assertEquals(2, operators.size()); + assertEquals("department1", operators.get(0).getIdentity()); + assertEquals("department2", operators.get(1).getIdentity()); + } + + /** + * 不支持的元素抛出带上下文的校验异常,而不是 {@code NumberFormatException} + */ + @Test + void should_throw_validation_exception_when_element_unsupported() { + FlowValidationException exception = assertThrows(FlowValidationException.class, + () -> OperatorScriptResultResolver.resolve(countingHolder.proxy(), List.of(new Object()))); + + assertTrue(exception.getMessage().contains("java.lang.Object"), + "异常消息应包含不支持的元素类型,实际:" + exception.getMessage()); + assertTrue(exception.getMessage().contains("OperatorKey"), + "异常消息应提示支持的返回形态,实际:" + exception.getMessage()); + } + + /** + * 数字字符串按人员 id 处理(Groovy 从表单/下游取到的 id 常是 String) + */ + @Test + void should_parse_numeric_string_as_user_id() { + List operators = OperatorScriptResultResolver.resolve( + countingHolder.proxy(), List.of("2")); + + assertEquals(1, operators.size()); + assertEquals(2, operators.get(0).getUserId()); + assertEquals(OperatorIdentity.DEFAULT, operators.get(0).getIdentity()); + } + + /** + * 非正数人员 id(存量脚本用 {@code -1} 表示「无审批人」)跳过,不抛异常 + */ + @Test + void should_skip_non_positive_user_id() { + List operators = OperatorScriptResultResolver.resolve( + countingHolder.proxy(), List.of(-1L, 2L)); + + assertEquals(1, operators.size()); + assertEquals(2, operators.get(0).getUserId()); + } + + /** + * 批量回查按身份分组执行,避免逐个回查(N+1) + */ + @Test + void should_query_in_batches_grouped_by_identity() { + OperatorScriptResultResolver.resolve(countingHolder.proxy(), List.of( + OperatorKey.of(1, "department1"), + OperatorKey.of(2, "department1"), + OperatorKey.of(1, "department2"), + 2L)); + + assertEquals(3, countingHolder.batchQueryCount); + assertEquals(0, countingHolder.singleQueryCount); + } + + /** + * 统计回查次数的仓储代理,用于断言「对象形态不回查」与「按身份分组批量回查」 + */ + private static final class CountingRepositoryHolder { + + private final IRepositoryHolder delegate; + private int batchQueryCount; + private int singleQueryCount; + + private CountingRepositoryHolder(IRepositoryHolder delegate) { + this.delegate = delegate; + } + + private IRepositoryHolder proxy() { + return (IRepositoryHolder) Proxy.newProxyInstance( + IRepositoryHolder.class.getClassLoader(), + new Class[]{IRepositoryHolder.class}, + (proxy, method, args) -> { + switch (method.getName()) { + case "findOperatorByIds" -> batchQueryCount++; + case "getOperatorById" -> singleQueryCount++; + default -> { + } + } + try { + return method.invoke(delegate, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + }); + } + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorScriptIdentityFlowTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorScriptIdentityFlowTest.java new file mode 100644 index 00000000..b210c7f0 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorScriptIdentityFlowTest.java @@ -0,0 +1,206 @@ +package com.codingapi.flow.service; + +import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.action.actions.CustomAction; +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.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.FormData; +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.record.FlowRecord; +import com.codingapi.flow.script.factory.FlowGroovyScriptFactory; +import com.codingapi.flow.strategy.node.FormFieldPermissionStrategy; +import com.codingapi.flow.strategy.node.OperatorLoadStrategy; +import com.codingapi.flow.strategy.node.RevokeStrategy; +import com.codingapi.flow.user.User; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.WorkflowBuilder; +import org.junit.jupiter.api.BeforeEach; +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.assertTrue; + +/** + * 取人脚本身份落库的流程级测试(issue #303)。 + * + *

    核心回归:以 {@code department1} 身份发起流程,审批人由「流程创建者」脚本产生时, + * 审批记录的 {@code currentOperatorIdentity} 必须是 {@code department1},而不是退化为默认身份。 + */ +class OperatorScriptIdentityFlowTest { + + private static final long INITIATOR = 1; + private static final long APPROVER = 2; + + private static final String DEPARTMENT_1 = "department1"; + private static final String DEPARTMENT_2 = "department2"; + + private MyFlowServiceFactory factory; + private final Map data = Map.of("name", "lorne"); + + @BeforeEach + void setUp() { + factory = new MyFlowServiceFactory(); + factory.userGateway.save(new User(INITIATOR, "initiator")); + factory.userGateway.save(new User(APPROVER, "approver")); + GatewayContext.getInstance().setFlowOperatorGateway(factory.userGateway); + } + + /** + * 测试目标:创建者脚本返回 {@code OperatorKey} 时,审批记录落创建时的身份。 + * 前置条件:流程为 Start -> Approval(脚本返回 request.getCreatedOperatorKey()) -> End。 + * 执行步骤:以 department1 身份发起并提交。 + * 期望断言:审批待办记录的 currentOperatorIdentity 为 department1。 + */ + @Test + void should_land_created_identity_when_operator_script_returns_operator_key() { + Workflow workflow = saveCreatorScriptFlow("script-identity-creator"); + + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + FlowRecord approvalRecord = todoRecordOf(INITIATOR); + assertEquals(INITIATOR, approvalRecord.getCurrentOperatorId()); + assertEquals(DEPARTMENT_1, approvalRecord.getCurrentOperatorIdentity(), + "审批人身份应跟随创建时的身份"); + } + + /** + * 测试目标:同一流程换身份发起,落库身份跟随发起身份。 + * 前置条件:同 {@link #should_land_created_identity_when_operator_script_returns_operator_key()}。 + * 执行步骤:以 department2 身份发起并提交。 + * 期望断言:审批待办记录的 currentOperatorIdentity 为 department2。 + */ + @Test + void should_land_identity_of_current_creation_when_created_with_another_identity() { + Workflow workflow = saveCreatorScriptFlow("script-identity-creator-2"); + + long startRecordId = createFlow(workflow, DEPARTMENT_2); + submit(workflow, startRecordId, DEPARTMENT_2); + + assertEquals(DEPARTMENT_2, todoRecordOf(INITIATOR).getCurrentOperatorIdentity()); + } + + /** + * 测试目标:{@code request.findPreviousNodeOperators()} 在无上一节点时安全返回空列表。 + * 前置条件:取人脚本运行在开始节点,不存在前驱审批记录。 + * 执行步骤:执行脚本。 + * 期望断言:返回空列表,不抛异常。 + */ + @Test + void should_return_empty_previous_operators_at_start_node() { + Workflow workflow = saveCreatorScriptFlow("script-identity-previous"); + IFlowNode startNode = workflow.getStartNode(); + + OperatorLoadStrategy startStrategy = new OperatorLoadStrategy(FlowGroovyScriptFactory + .createOperatorLoadScript("def run(request){return request.findPreviousNodeOperators()}") + .getKey()); + FormData formData = new FormData(form("script-identity-previous")); + formData.getDataBody().set("name", "lorne"); + com.codingapi.flow.session.FlowSession session = com.codingapi.flow.session.FlowSession.startSession( + factory.repositoryHolder, new User(INITIATOR, "initiator"), workflow, startNode, + startAction(workflow), formData, 0); + + assertTrue(startStrategy.loadOperators(session).getOperators().isEmpty()); + } + + // ==================== 流程构建 ==================== + + /** + * 构建 Start(可撤回) -> Approval(创建者脚本,返回带身份的 OperatorKey) -> End 的流程。 + */ + private Workflow saveCreatorScriptFlow(String code) { + StartNode startNode = StartNode.builder() + .strategies(NodeStrategyBuilder.builder() + .addStrategy(fieldPermission(code)) + .addStrategy(new RevokeStrategy(true, RevokeStrategy.Type.REVOKE_CURRENT)) + .build()) + .actions(ActionBuilder.builder() + .addAction(CustomAction.defaultAction()) + .build()) + .build(); + + ApprovalNode approvalNode = ApprovalNode.builder() + .name("创建者审批") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(fieldPermission(code)) + .addStrategy(new OperatorLoadStrategy(FlowGroovyScriptFactory + .createOperatorLoadScript("def run(request){return [request.getCreatedOperatorKey()]}") + .getKey())) + .build()) + .build(); + + Workflow workflow = WorkflowBuilder.builder() + .title("取人脚本身份流程") + .code(code) + .createdOperator(new User(INITIATOR, "initiator")) + .form(form(code)) + .addNode(startNode) + .addNode(approvalNode) + .addNode(EndNode.builder().build()) + .build(); + factory.workflowService.saveWorkflow(workflow); + return workflow; + } + + private FlowForm form(String code) { + return FlowFormBuilder.builder() + .name("取人脚本身份流程") + .code(code) + .addField("请假人", "name", DataType.STRING) + .build(); + } + + private FormFieldPermissionStrategy fieldPermission(String code) { + return new FormFieldPermissionStrategy(FormFieldPermissionsBuilder.builder() + .addPermission(code, "name", PermissionType.WRITE) + .build()); + } + + // ==================== 动作入口 ==================== + + private long createFlow(Workflow workflow, String operatorIdentity) { + FlowCreateRequest request = new FlowCreateRequest(); + request.setWorkCode(workflow.getCode()); + request.setFormData(data); + request.setActionId(startAction(workflow).id()); + request.setOperatorId(INITIATOR); + request.setOperatorIdentity(operatorIdentity); + return factory.flowService.create(request); + } + + private void submit(Workflow workflow, long recordId, String operatorIdentity) { + FlowAdviceBody advice = new FlowAdviceBody(startAction(workflow).id(), "提交", INITIATOR); + advice.setOperatorIdentity(operatorIdentity); + FlowActionRequest request = new FlowActionRequest(); + request.setFormData(data); + request.setRecordId(recordId); + request.setAdvice(advice); + factory.flowService.action(request); + } + + private IFlowAction startAction(Workflow workflow) { + return workflow.getStartNode().actionManager().getActions().get(0); + } + + private FlowRecord todoRecordOf(long operatorId) { + List records = factory.flowRecordRepository.findTodoByOperator(operatorId); + assertEquals(1, records.size(), "操作人应有且仅有一条待办"); + return records.get(0); + } +} From 99204c18c2cd3c3194a75b58c8e561bca720a7f2 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Thu, 3 Dec 2026 15:33:07 +0800 Subject: [PATCH 22/35] =?UTF-8?q?feat:=20=E9=BB=98=E8=AE=A4=E5=8F=96?= =?UTF-8?q?=E4=BA=BA=E8=84=9A=E6=9C=AC=E8=BF=94=E5=9B=9E=20OperatorKey?= =?UTF-8?q?=EF=BC=8C=E5=88=9B=E5=BB=BA=E8=80=85=E8=BA=AB=E4=BB=BD=E9=9A=8F?= =?UTF-8?q?=E5=8F=91=E8=B5=B7=E8=90=BD=E5=BA=93=20(issue=20#303)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ScriptDefaultConstants 默认取人脚本改为 [request.getCreatedOperatorKey()] - operator-identity.md §3.4 补齐三种返回形态、默认模板、Key 构造 API 与 findPreviousNodeOperators 用法;§5 补默认脚本升级的兼容说明 Closes #303 --- docs/Integration/operator-identity.md | 61 +++++++++++++++++-- .../flow/script/ScriptDefaultConstants.java | 5 +- 2 files changed, 61 insertions(+), 5 deletions(-) diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md index b978d9d3..62901d3e 100644 --- a/docs/Integration/operator-identity.md +++ b/docs/Integration/operator-identity.md @@ -159,7 +159,7 @@ advice.setOperatorSelectOperators(Map.of(nextNodeId, List.of(OperatorKey.of(3L, ### 3.4 在脚本中使用身份 -`GroovyScriptRequest` 新增三个函数: +**读取身份**:`GroovyScriptRequest` 提供三个函数(常用于条件脚本): | 脚本函数 | 含义 | |----------|------| @@ -176,18 +176,57 @@ def run(request) { } ``` +**产出参与人**(取人脚本,以及异常脚本的 `operators`)支持三种返回形态,允许在同一列表内混用(逐元素判定): + +| 形态 | 示例 | 身份来源 | 是否回查 | +|------|------|----------|----------| +| `List` | `return [1, 2]` | 默认身份 | 是(按默认身份批量) | +| `List` | `return [request.getCreatedOperatorKey()]` | `OperatorKey.identity()` | 是(按身份分组批量) | +| `List` | `return [$bind.getOperatorByIdentity(2, 'department1')]` | 对象自带 `getIdentity()` | **否**,直接采用 | + +约定: + +- 三种形态由 `OperatorScriptResultResolver` 统一解析,回查按身份分组批量执行、结果按脚本返回顺序输出; +- 顶层可写单值(`return request.getCreatedOperatorId()`),按单元素处理; +- 非正数的人员 id(存量脚本用 `[-1]` 表示「无审批人」)会被跳过,不抛异常; +- 其他非法元素抛 `FlowValidationException`,消息带脚本类型、元素类型与元素内容(不再出现 `NumberFormatException`)。 + +**默认模板(issue #303 起)**:新建节点的取人脚本为 + +```groovy +// @SCRIPT_TITLE 流程创建者 +// @SCRIPT_META {"type":"creator"} +def run(request){ + return [request.getCreatedOperatorKey()] +} +``` + +创建者以**发起时的身份**参与流程。存量流程定义里的旧脚本(`return [request.getCreatedOperatorId()]`)行为不变,仍落默认身份;需要身份时把脚本改为 `getCreatedOperatorKey()`。 + +构造带身份的人员标识: + +| 脚本函数 | 返回 | 说明 | +|----------|------|------| +| `request.getCreatedOperatorKey()` | `OperatorKey` | 创建者 + 创建时身份 | +| `request.getCurrentOperatorKey()` | `OperatorKey` | 当前审批人 + 当前身份 | +| `request.getSubmitOperatorKey()` | `OperatorKey` | 提交人 + 提交时身份 | +| `$bind.getOperatorKey(userId, identity)` | `OperatorKey` | 只构造标识,不回查 | +| `request.findPreviousNodeOperators()` | `List` | 上一节点实际审批人,含身份 | +| `$bind.getOperatorByIdentity(userId, identity)` | `IFlowOperator` | 回查得到带身份的操作者 | +| `request.findPreviousNodeOperatorIds()` | `List` | 上一节点审批人 id(不含身份,保留兼容) | + 人员差异(审批人脚本): ```groovy def run(request) { def identity = request.getCreatedOperatorIdentity() - if (identity == 'department1') return [boss1Id] - if (identity == 'department2') return [boss2Id] + if (identity == 'department1') return [request.getCreatedOperatorKey()] + if (identity == 'department2') return [$bind.getOperatorKey(boss2Id, 'department2')] return [defaultBossId] } ``` -需要「让某人以指定身份参与」时,用 `$bind.getOperatorByIdentity(id, identity)` 拿到带身份的操作者: +让某人以指定身份参与: ```groovy def run(request) { @@ -196,6 +235,14 @@ def run(request) { } ``` +复用上一节点审批人(含身份): + +```groovy +def run(request) { + return request.findPreviousNodeOperators() +} +``` + ## 4. 引擎侧行为 ### 4.1 记录与待办落库 @@ -305,6 +352,7 @@ codingapi.flow.identity.match-mode=USER_ONLY | 工作流定义 | 与身份无关,导入导出不受影响 | | 身份长度 | ≤ 64 字符(复合 key 用 `:` 拼接),入口与落库双处校验 | | 待办索引 | 实体未声明 `@Index`,大表请按 DDL 脚本手工加索引 | +| 默认取人脚本 | issue #303 起新建节点的默认脚本返回 `OperatorKey`(创建者以发起身份参与);存量流程定义中的旧脚本不受影响,不迁移 | | 不做的事 | 引擎不建组织模型、不做身份授权校验(「user1 能否以 department1 身份操作」由业务侧保证)、不冻结身份名称 | > 身份是一个**不透明字符串**,不要尝试在引擎里比较它的业务含义;需要「部门名称」等展示信息,由宿主维护 `identity → 名称` 的映射自行渲染(框架不提供附加属性字段)。 @@ -334,6 +382,11 @@ codingapi.flow.identity.match-mode=USER_ONLY 前端应提供「选择 / 切回默认身份」的入口(示例工程见 5.2):`STRICT` 或锁定身份查看时,用户仍能处理存量事项; 默认 `USER_ONLY` 下它的作用是声明**本次操作身份**(脚本上下文与留痕),不影响能看到哪些数据。 +> **默认取人脚本升级(issue #303)**:新建节点的默认取人脚本已从 `[request.getCreatedOperatorId()]` +> 改为 `[request.getCreatedOperatorKey()]`,创建者以**发起时的身份**参与。因此同一条流程在升级前后发起的实例, +> 创建者节点的身份可能不同(旧实例为默认身份)。这是「身份跟随发起上下文」的预期行为,不做数据迁移; +> 存量流程定义中的脚本文本是独立保存的,不会被自动改写。 + ### 5.2 示例工程如何验证 `flow-engine-example` + `flow-frontend` 的 `apps/app-pc`(PC)与 `apps/app-mobile`(移动端)都已打通端到端验证, diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/ScriptDefaultConstants.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/ScriptDefaultConstants.java index c4632d3d..efcd2c6c 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/ScriptDefaultConstants.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/ScriptDefaultConstants.java @@ -74,12 +74,15 @@ def run(request){ /** * 默认人员加载脚本 + * + *

    返回 {@code OperatorKey}(人员id + 身份),创建者以「发起时的身份」参与流程, + * 不会退化为默认身份(issue #303)。 */ public static final String SCRIPT_DEFAULT_OPERATOR_LOAD = """ // @SCRIPT_TITLE 流程创建者 // @SCRIPT_META {"type":"creator"} def run(request){ - return [request.getCreatedOperatorId()] + return [request.getCreatedOperatorKey()] } """; From 81a2bc0eb5d370e701b3d018f8f636fa4d2e289b Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Thu, 3 Dec 2026 16:03:49 +0800 Subject: [PATCH 23/35] =?UTF-8?q?feat:=20=E8=AE=B0=E5=BD=95=E5=8A=9E?= =?UTF-8?q?=E7=90=86=E4=BA=BA=E4=B8=8E=E5=8A=9E=E7=90=86=E8=BA=AB=E4=BB=BD?= =?UTF-8?q?=EF=BC=8C=E8=A1=A5=E9=BD=90=E5=B7=B2=E5=8A=9E=E7=95=99=E7=97=95?= =?UTF-8?q?=20(issue=20#306)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 办结动作此前不写任何身份字段:current_* 是待办归属、submit_* 是创建该记录时的上游提交人, 最后一步办理身份因此没有落点。新增 handle_operator_id/name/identity 三元组,由办结动作显式写入。 - FlowRecord 新增 handleOperator 三元组与 markHandleOperator / clearHandleOperator - Pass / Return / Reject / Transfer / Delegate 办结后写入;SaveAction 暂存与 notifyRecord 抄送不写 - FlowRecordEntity / FlowRecordConvertor / FlowRecordContent 补齐映射(存量数据为空) - DDL 脚本补三列,operator-identity.md 更新留痕口径 Closes #306 --- docs/Integration/operator-identity.md | 23 +- .../sql/0.3.0-operator-identity.sql | 12 + .../flow/action/actions/DelegateAction.java | 1 + .../flow/action/actions/PassAction.java | 1 + .../flow/action/actions/RejectAction.java | 1 + .../flow/action/actions/ReturnAction.java | 1 + .../flow/action/actions/TransferAction.java | 1 + .../flow/pojo/response/FlowRecordContent.java | 18 ++ .../com/codingapi/flow/record/FlowRecord.java | 54 ++++ .../CopyOnReadFlowRecordRepository.java | 5 +- .../HandleOperatorIdentityFlowTest.java | 290 ++++++++++++++++++ .../infra/convert/FlowRecordConvertor.java | 9 +- .../flow/infra/entity/FlowRecordEntity.java | 16 + 13 files changed, 428 insertions(+), 4 deletions(-) create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/service/HandleOperatorIdentityFlowTest.java diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md index 62901d3e..316487d0 100644 --- a/docs/Integration/operator-identity.md +++ b/docs/Integration/operator-identity.md @@ -249,9 +249,11 @@ def run(request) { | 表 | 新增列 | |----|--------| -| `t_flow_record` | `create_operator_identity`、`submit_operator_identity`、`current_operator_identity`、`forward_operator_identity`、`interfered_operator_identity` | +| `t_flow_record` | `create_operator_identity`、`submit_operator_identity`、`current_operator_identity`、`forward_operator_identity`、`interfered_operator_identity`、`handle_operator_identity` | | `t_flow_todo_record` | `create_operator_identity`、`submit_operator_identity`、`current_operator_identity` | +「办理人」另有两列非身份字段(issue #306):`handle_operator_id`、`handle_operator_name`,与 `handle_operator_identity` 一起记录**谁以什么身份办理了这条记录**。待办表不加这三列——待办尚未办理,没有办理人语义。 + 只存身份标识本身,**不落库任何附加属性**(避免为 5 组操作者各加一个 JSON 快照列,也避免身份名称被冻结在历史数据里)。展示名称仍取操作者姓名;需要展示身份名称时由宿主按 `identity` 自行映射。 升级脚本见 [sql/0.3.0-operator-identity.sql](./sql/0.3.0-operator-identity.sql)。 @@ -311,7 +313,23 @@ def run(request) { `OperatorManager`、操作者线程缓存、网关缓存的 `(userId, identity)` 键仍保持严格匹配——它们解决的是「取到哪一个带身份的操作者实例」,不是权限问题。 -留痕口径:被办理记录保留其归属身份(`currentOperatorIdentity`,由取人脚本决定),本次操作携带的身份写入下游新生成记录的 `submitOperatorIdentity`;`USER_ONLY` 下同人换身份不算「被干预」,因此不会写 `interferedOperator*`。 +留痕口径(`USER_ONLY` 下同人换身份不算「被干预」,因此不会写 `interferedOperator*`): + +| 字段 | 语义 | 写入时机 | +|------|------|----------| +| `currentOperatorId/Name/Identity` | 这条待办的**归属**人(由取人脚本决定) | 记录生成时;办结后**不变** | +| `submitOperatorId/Name/Identity` | **创建这条记录时**的上游提交人 | 记录生成时 | +| `handleOperatorId/Name/Identity` | **本次办理人**——谁、以什么身份办的 | 办结动作(通过 / 拒绝 / 退回 / 转办 / 委派);暂存与抄送刷新不写 | + +因此「办结」不会改写归属身份,只额外留下办理人三元组。 + +> **issue #306 之前的行为**:办理动作不写任何身份字段,最后一步办理人身份**无处落地**——没有下游记录可以承载 +> `submitOperator*`,于是「张三以 `department2` 审批通过」在库里只能看到 `department1`(待办归属)或默认身份。 +> 中间节点只能跳一条到下游记录的 `submitOperatorIdentity` 间接推断,且要求下游是同一个人。 +> 升级后请以 `handleOperator*` 作为「已办是谁办的」的唯一口径。 + +`FlowRecord#markHandleOperator(IFlowOperator)` 由办结动作显式调用,**不在 `update()` 内隐式写入**:`update()` 同时服务于 +暂存(`SaveAction`,`pass=false`)与抄送刷新(`notifyRecord`),隐式写入会把暂存人、抄送接收人误记成办理人。 ### 4.5 身份写入约束 @@ -353,6 +371,7 @@ codingapi.flow.identity.match-mode=USER_ONLY | 身份长度 | ≤ 64 字符(复合 key 用 `:` 拼接),入口与落库双处校验 | | 待办索引 | 实体未声明 `@Index`,大表请按 DDL 脚本手工加索引 | | 默认取人脚本 | issue #303 起新建节点的默认脚本返回 `OperatorKey`(创建者以发起身份参与);存量流程定义中的旧脚本不受影响,不迁移 | +| 办理人留痕 | issue #306 起 `handle_operator_*` 记录办理人与办理身份;存量记录为空,前端回退到 `current_operator_identity` 展示,行为与升级前一致;如需回填,按 `finish_time` 与下游 `submit_operator_*` 推断,引擎不做自动迁移 | | 不做的事 | 引擎不建组织模型、不做身份授权校验(「user1 能否以 department1 身份操作」由业务侧保证)、不冻结身份名称 | > 身份是一个**不透明字符串**,不要尝试在引擎里比较它的业务含义;需要「部门名称」等展示信息,由宿主维护 `identity → 名称` 的映射自行渲染(框架不提供附加属性字段)。 diff --git a/docs/Integration/sql/0.3.0-operator-identity.sql b/docs/Integration/sql/0.3.0-operator-identity.sql index 7a207227..e0b4b3ac 100644 --- a/docs/Integration/sql/0.3.0-operator-identity.sql +++ b/docs/Integration/sql/0.3.0-operator-identity.sql @@ -27,6 +27,18 @@ ALTER TABLE t_flow_record ADD COLUMN forward_operator_identity VARCHAR(64) NU ALTER TABLE t_flow_record ADD COLUMN interfered_operator_identity VARCHAR(64) NULL; +-- ----------------------------------------------------------------------------- +-- 1.1 流程记录表:办理人三列(issue #306) +-- ----------------------------------------------------------------------------- +-- 背景:此前记录被办结时不写任何身份字段,current_operator_identity 保留的是「待办归属身份」, +-- submit_operator_identity 只表示「创建该记录时的上游提交人」,最后一步办理人身份因此无处可落。 +-- 语义:handle_operator_* = 本次实际办理人的 (id, 名称, 身份),暂存与抄送刷新不写入。 +-- 兼容:与 current_operator_identity 并存、互不覆盖;历史数据为 NULL,前端可回退到 current_operator_identity。 +ALTER TABLE t_flow_record ADD COLUMN handle_operator_id BIGINT NULL; +ALTER TABLE t_flow_record ADD COLUMN handle_operator_name VARCHAR(255) NULL; +ALTER TABLE t_flow_record ADD COLUMN handle_operator_identity VARCHAR(64) NULL; + + -- ----------------------------------------------------------------------------- -- 2. 待办表:发起 / 提交 / 当前 三组操作者的身份 -- ----------------------------------------------------------------------------- diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/DelegateAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/DelegateAction.java index ccbd99f2..ecd87247 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/DelegateAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/DelegateAction.java @@ -73,6 +73,7 @@ public void run(FlowSession flowSession) { FlowRecord currentRecord = flowSession.getCurrentRecord(); currentRecord.update(flowSession, true); + currentRecord.markHandleOperator(flowSession.getCurrentOperator()); recordList.add(currentRecord); flowEvents.add(new FlowRecordDoneEvent(currentRecord, flowSession.isMock())); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java index bca7e0c9..e39830c4 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java @@ -141,6 +141,7 @@ public void run(FlowSession flowSession) { boolean isFinish = currentNode.isFinish(flowSession); currentRecord.update(flowSession, true); + currentRecord.markHandleOperator(flowSession.getCurrentOperator()); // 添加流程结束事件 flowEvents.add(new FlowRecordDoneEvent(currentRecord, flowSession.isMock())); recordList.add(currentRecord); 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 ca7db511..5c06bfd7 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 @@ -100,6 +100,7 @@ public void run(FlowSession flowSession) { FlowRecord flowRecord = flowSession.getCurrentRecord(); flowRecord.update(flowSession, true); + flowRecord.markHandleOperator(flowSession.getCurrentOperator()); recordList.add(flowRecord); // 当前审批为已办状态 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 268cda80..14195421 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 @@ -54,6 +54,7 @@ public void run(FlowSession flowSession) { FlowRecord currentRecord = flowSession.getCurrentRecord(); currentRecord.update(flowSession, true); + currentRecord.markHandleOperator(flowSession.getCurrentOperator()); recordList.add(currentRecord); flowEvents.add(new FlowRecordDoneEvent(currentRecord,flowSession.isMock())); 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 8d2a085b..0eec025e 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 @@ -82,6 +82,7 @@ public void run(FlowSession flowSession) { FlowRecord currentRecord = flowSession.getCurrentRecord(); currentRecord.update(flowSession, true); + currentRecord.markHandleOperator(flowSession.getCurrentOperator()); recordList.add(currentRecord); flowEvents.add(new FlowRecordDoneEvent(currentRecord,flowSession.isMock())); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowRecordContent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowRecordContent.java index c0e85522..38c5b5e4 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowRecordContent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowRecordContent.java @@ -100,6 +100,21 @@ public class FlowRecordContent { */ private String createOperatorIdentity; + /** + * 办理人Id(issue #306),记录办结时的实际办理人 + */ + private Long handleOperatorId; + + /** + * 办理人名称(issue #306) + */ + private String handleOperatorName; + + /** + * 办理人身份标识(issue #306),空串表示默认身份 + */ + private String handleOperatorIdentity; + /** * 合并记录id,当存在合并记录数据时待办记录数量不会增加,内容会更新至最新的待办数据信息。 * {@link FlowRecord#getTodoKey()} @@ -161,6 +176,9 @@ public static FlowRecordContent convert(FlowRecord record){ content.setCreateOperatorId(record.getCreateOperatorId()); content.setCreateOperatorName(record.getCreateOperatorName()); content.setCreateOperatorIdentity(OperatorIdentity.normalize(record.getCreateOperatorIdentity())); + content.setHandleOperatorId(record.getHandleOperatorId()); + content.setHandleOperatorName(record.getHandleOperatorName()); + content.setHandleOperatorIdentity(OperatorIdentity.normalize(record.getHandleOperatorIdentity())); content.setMergeable(record.isMergeable()); content.setRecordId(record.getId()); content.setTimeoutTime(record.getTimeoutTime()); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java index ebd6cd91..785886a3 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java @@ -303,6 +303,25 @@ public class FlowRecord { */ private String interferedOperatorIdentity; + /** + * 办理人Id(issue #306) + *

    记录被办结时,本次实际办理人的用户 id;暂存与抄送刷新不写入。 + */ + private long handleOperatorId; + + /** + * 办理人名称(issue #306) + */ + private String handleOperatorName; + + /** + * 办理人身份标识(issue #306) + *

    本次办理时使用的身份,空串表示默认身份。与「待办归属身份」 + * {@link FlowRecord#currentOperatorIdentity} 互不覆盖:办结不改变待办归属, + * 只额外留下「谁以什么身份办的」。 + */ + private String handleOperatorIdentity; + /** * 数据合并的依据,当开启时值为固定值,否则为随机数据 *

    合并依据由 {@link RecordMergeStrategy.MergeType} 决定: @@ -401,6 +420,7 @@ public FlowRecord(FlowSession flowSession, int nodeOrder) { // 身份字段统一以空串兜底,避免出现 null 与空串两种「默认身份」表达 this.forwardOperatorIdentity = OperatorIdentity.DEFAULT; this.interferedOperatorIdentity = OperatorIdentity.DEFAULT; + this.handleOperatorIdentity = OperatorIdentity.DEFAULT; // 是否转交之后的人来审批的判断 if (currentOperator.equals(sourceOperator)) { this.forwardOperatorId = 0; @@ -648,6 +668,28 @@ public void update(FlowSession flowSession, boolean pass) { } } + /** + * 记录本次办理人(issue #306)。 + * + *

    必须由「真正办结」的动作显式调用(通过 / 拒绝 / 退回 / 转办 / 委派)。 + * 暂存({@link com.codingapi.flow.action.actions.SaveAction})与抄送刷新 + * ({@link #notifyRecord(com.codingapi.flow.session.FlowSession)})只是刷新记录内容、 + * 并未产生办理结果,因此不能写入,否则会把暂存人、抄送接收人误记为办理人。 + * + *

    不修改 {@link #currentOperatorId} / {@link #currentOperatorIdentity}: + * 待办归属身份在办结后仍需保留(见 docs/Integration/operator-identity.md §4.4)。 + * + * @param operator 本次实际办理人 + */ + public void markHandleOperator(IFlowOperator operator) { + if (operator == null) { + return; + } + this.handleOperatorId = operator.getUserId(); + this.handleOperatorName = operator.getName(); + this.handleOperatorIdentity = OperatorIdentity.of(operator); + } + public void clearNotify(){ this.readable = false; this.readTime = 0; @@ -818,6 +860,18 @@ public void newRecord() { this.setAdvice(null); this.setSignKey(null); this.setActionId(null); + // 新记录尚未被办理,不能继承上游记录的办理人信息(issue #306) + this.clearHandleOperator(); + } + + /** + * 清空办理人信息(issue #306)。 + *

    记录回到「未办理」状态时调用,避免复用记录对象时把上一位办理人带到新的待办上。 + */ + public void clearHandleOperator() { + this.handleOperatorId = 0; + this.handleOperatorName = null; + this.handleOperatorIdentity = OperatorIdentity.DEFAULT; } /** diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/repository/CopyOnReadFlowRecordRepository.java b/flow-engine-framework/src/test/java/com/codingapi/flow/repository/CopyOnReadFlowRecordRepository.java index 2ee38d02..0d527738 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/repository/CopyOnReadFlowRecordRepository.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/repository/CopyOnReadFlowRecordRepository.java @@ -147,6 +147,9 @@ private static FlowRecord copy(FlowRecord record) { record.getSubmitOperatorIdentity(), record.getCurrentOperatorIdentity(), record.getForwardOperatorIdentity(), - record.getInterferedOperatorIdentity()); + record.getInterferedOperatorIdentity(), + record.getHandleOperatorId(), + record.getHandleOperatorName(), + record.getHandleOperatorIdentity()); } } \ No newline at end of file diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/HandleOperatorIdentityFlowTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/HandleOperatorIdentityFlowTest.java new file mode 100644 index 00000000..72649123 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/HandleOperatorIdentityFlowTest.java @@ -0,0 +1,290 @@ +package com.codingapi.flow.service; + +import com.codingapi.flow.action.ActionType; +import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.action.actions.CustomAction; +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.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.nodes.ApprovalNode; +import com.codingapi.flow.node.nodes.EndNode; +import com.codingapi.flow.node.nodes.StartNode; +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityMatchMode; +import com.codingapi.flow.operator.OperatorIdentityPolicy; +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.record.FlowRecord; +import com.codingapi.flow.script.factory.FlowGroovyScriptFactory; +import com.codingapi.flow.strategy.node.FormFieldPermissionStrategy; +import com.codingapi.flow.strategy.node.OperatorLoadStrategy; +import com.codingapi.flow.strategy.node.RevokeStrategy; +import com.codingapi.flow.user.User; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.WorkflowBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 办理人身份留痕的流程级测试(issue #306)。 + * + *

    核心回归:记录被办结后必须留下「本次办理人」的 {@code handleOperatorId/Name/Identity}, + * 与「待办归属身份」{@code currentOperatorIdentity} 互不覆盖。此前 {@code update()} 不写任何身份字段, + * 导致最后一步办理身份(没有下游记录可承载)彻底丢失。 + */ +class HandleOperatorIdentityFlowTest { + + private static final long INITIATOR = 1; + private static final long APPROVER = 2; + + private static final String DEPARTMENT_1 = "department1"; + private static final String DEPARTMENT_2 = "department2"; + + private MyFlowServiceFactory factory; + private final Map data = Map.of("name", "lorne"); + + @BeforeEach + void setUp() { + // issue #297:USER_ONLY 下同一人换身份可以办理自己的待办,与 issue #306 的复现场景一致 + OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + factory = new MyFlowServiceFactory(); + factory.userGateway.save(new User(INITIATOR, "initiator")); + factory.userGateway.save(new User(APPROVER, "approver")); + GatewayContext.getInstance().setFlowOperatorGateway(factory.userGateway); + } + + @AfterEach + void tearDown() { + OperatorIdentityPolicy.reset(); + } + + /** + * 测试目标:最后一步办理时,办理人身份必须留痕。 + * 前置条件:Start -> Approval(审批人固定为 APPROVER) -> End,开始节点归属身份为 department1、审批人归属为默认身份。 + * 执行步骤:department1 发起并提交,APPROVER 以 department2 身份审批通过(流程结束,无下游记录)。 + * 期望断言:该记录 currentOperatorIdentity 仍为空(归属身份不被改写), + * handleOperatorId=APPROVER、handleOperatorIdentity=department2。 + */ + @Test + void should_record_handle_operator_when_finishing_last_step() { + Workflow workflow = saveFlow("handle-identity-last", APPROVER); + + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + FlowRecord approvalRecord = todoRecordOf(APPROVER); + assertEquals(OperatorIdentity.DEFAULT, approvalRecord.getCurrentOperatorIdentity(), + "固定审批人脚本只返回 id,归属身份应为默认身份"); + + pass(workflow, approvalRecord.getId(), APPROVER, DEPARTMENT_2); + + FlowRecord done = factory.flowRecordRepository.get(approvalRecord.getId()); + assertTrue(done.isDone(), "记录应已办结"); + assertEquals(OperatorIdentity.DEFAULT, done.getCurrentOperatorIdentity(), + "归属身份不能被办理行为改写"); + assertEquals(APPROVER, done.getHandleOperatorId(), "办理人应留痕"); + assertEquals("approver", done.getHandleOperatorName(), "办理人名称应留痕"); + assertEquals(DEPARTMENT_2, done.getHandleOperatorIdentity(), "办理人身份应留痕"); + } + + /** + * 测试目标:中间节点办理同样留痕,且与下游记录的提交身份一致。 + * 前置条件:Start -> Approval1(APPROVER) -> Approval2(INITIATOR) -> End。 + * 执行步骤:department1 发起,APPROVER 以 department2 通过中间节点。 + * 期望断言:中间记录 handleOperatorIdentity=department2;下游待办的 submitOperatorIdentity=department2。 + */ + @Test + void should_record_handle_operator_when_finishing_middle_step() { + Workflow workflow = saveTwoApprovalFlow("handle-identity-middle"); + + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + FlowRecord middleRecord = todoRecordOf(APPROVER); + pass(workflow, middleRecord.getId(), APPROVER, DEPARTMENT_2); + + FlowRecord done = factory.flowRecordRepository.get(middleRecord.getId()); + assertEquals(DEPARTMENT_2, done.getHandleOperatorIdentity(), "中间节点办理身份应留痕"); + + FlowRecord nextRecord = todoRecordOf(INITIATOR); + assertEquals(DEPARTMENT_2, nextRecord.getSubmitOperatorIdentity(), + "下游记录的提交身份应与办理身份一致"); + } + + /** + * 测试目标:暂存不是办理,不得写入办理人。 + * 前置条件:同上单审批节点流程,APPROVER 存在待办。 + * 执行步骤:APPROVER 以 department2 身份执行「保存」动作。 + * 期望断言:记录仍为待办,handleOperator* 保持默认空值。 + */ + @Test + void should_not_record_handle_operator_when_saving_draft() { + Workflow workflow = saveFlow("handle-identity-save", APPROVER); + + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + FlowRecord approvalRecord = todoRecordOf(APPROVER); + save(workflow, approvalRecord.getId(), APPROVER, DEPARTMENT_2); + + FlowRecord saved = factory.flowRecordRepository.get(approvalRecord.getId()); + assertTrue(saved.isTodo(), "暂存后记录仍为待办"); + assertEquals(0L, saved.getHandleOperatorId(), "暂存不应写办理人 id"); + assertEquals(OperatorIdentity.DEFAULT, saved.getHandleOperatorIdentity(), "暂存不应写办理人身份"); + } + + // ==================== 流程构建 ==================== + + /** + * 构建 Start(可撤回) -> Approval(指定审批人) -> End 的流程。 + */ + private Workflow saveFlow(String code, long... approverIds) { + StartNode startNode = startNode(code); + ApprovalNode approvalNode = approvalNode(code, "审批", approverIds); + + Workflow workflow = WorkflowBuilder.builder() + .title("办理人身份留痕流程") + .code(code) + .createdOperator(new User(INITIATOR, "initiator")) + .form(form(code)) + .addNode(startNode) + .addNode(approvalNode) + .addNode(EndNode.builder().build()) + .build(); + factory.workflowService.saveWorkflow(workflow); + return workflow; + } + + /** + * 构建 Start(可撤回) -> Approval1(APPROVER) -> Approval2(INITIATOR) -> End 的流程。 + */ + private Workflow saveTwoApprovalFlow(String code) { + Workflow workflow = WorkflowBuilder.builder() + .title("办理人身份留痕流程") + .code(code) + .createdOperator(new User(INITIATOR, "initiator")) + .form(form(code)) + .addNode(startNode(code)) + .addNode(approvalNode(code, "一级审批", APPROVER)) + .addNode(approvalNode(code, "二级审批", INITIATOR)) + .addNode(EndNode.builder().build()) + .build(); + factory.workflowService.saveWorkflow(workflow); + return workflow; + } + + private StartNode startNode(String code) { + return StartNode.builder() + .strategies(NodeStrategyBuilder.builder() + .addStrategy(fieldPermission(code)) + .addStrategy(new RevokeStrategy(true, RevokeStrategy.Type.REVOKE_CURRENT)) + .build()) + .actions(ActionBuilder.builder() + .addAction(CustomAction.defaultAction()) + .build()) + .build(); + } + + private ApprovalNode approvalNode(String code, String name, long... approverIds) { + return ApprovalNode.builder() + .name(name) + .strategies(NodeStrategyBuilder.builder() + .addStrategy(fieldPermission(code)) + .addStrategy(new OperatorLoadStrategy(FlowGroovyScriptFactory + .createOperatorLoadScript("def run(request){return [" + joinIds(approverIds) + "]}") + .getKey())) + .build()) + .build(); + } + + private String joinIds(long... ids) { + return Arrays.stream(ids).mapToObj(String::valueOf).collect(Collectors.joining(",")); + } + + private FlowForm form(String code) { + return FlowFormBuilder.builder() + .name("办理人身份留痕流程") + .code(code) + .addField("请假人", "name", DataType.STRING) + .build(); + } + + private FormFieldPermissionStrategy fieldPermission(String code) { + return new FormFieldPermissionStrategy(FormFieldPermissionsBuilder.builder() + .addPermission(code, "name", PermissionType.WRITE) + .build()); + } + + // ==================== 动作入口 ==================== + + private long createFlow(Workflow workflow, String operatorIdentity) { + FlowCreateRequest request = new FlowCreateRequest(); + request.setWorkCode(workflow.getCode()); + request.setFormData(data); + request.setActionId(startAction(workflow).id()); + request.setOperatorId(INITIATOR); + request.setOperatorIdentity(operatorIdentity); + return factory.flowService.create(request); + } + + private void submit(Workflow workflow, long recordId, String operatorIdentity) { + doAction(workflow, recordId, startAction(workflow), INITIATOR, operatorIdentity); + } + + private void pass(Workflow workflow, long recordId, long operatorId, String operatorIdentity) { + IFlowAction passAction = approvalAction(workflow, ActionType.PASS); + doAction(workflow, recordId, passAction, operatorId, operatorIdentity); + } + + private void save(Workflow workflow, long recordId, long operatorId, String operatorIdentity) { + IFlowAction saveAction = approvalAction(workflow, ActionType.SAVE); + doAction(workflow, recordId, saveAction, operatorId, operatorIdentity); + } + + private void doAction(Workflow workflow, long recordId, IFlowAction action, long operatorId, String operatorIdentity) { + FlowAdviceBody advice = new FlowAdviceBody(action.id(), action.title(), operatorId); + advice.setOperatorIdentity(operatorIdentity); + FlowActionRequest request = new FlowActionRequest(); + request.setFormData(data); + request.setRecordId(recordId); + request.setAdvice(advice); + factory.flowService.action(request); + } + + private IFlowAction startAction(Workflow workflow) { + return workflow.getStartNode().actionManager().getActions().get(0); + } + + /** + * 取审批节点的指定类型动作(只取第一个审批节点,二级流程的审批动作保持一致)。 + */ + private IFlowAction approvalAction(Workflow workflow, ActionType actionType) { + return workflow.getNodes().stream() + .filter(node -> node instanceof ApprovalNode) + .findFirst() + .map(node -> node.actionManager().getActionByType(actionType.name())) + .orElseThrow(); + } + + private FlowRecord todoRecordOf(long operatorId) { + List records = factory.flowRecordRepository.findTodoByOperator(operatorId); + assertEquals(1, records.size(), "操作人应有且仅有一条待办"); + return records.get(0); + } +} diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java index 3f956f12..02d35e71 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java @@ -68,7 +68,11 @@ public static FlowRecord convert(FlowRecordEntity entity) { OperatorIdentity.normalize(entity.getSubmitOperatorIdentity()), OperatorIdentity.normalize(entity.getCurrentOperatorIdentity()), OperatorIdentity.normalize(entity.getForwardOperatorIdentity()), - OperatorIdentity.normalize(entity.getInterferedOperatorIdentity())); + OperatorIdentity.normalize(entity.getInterferedOperatorIdentity()), + // issue #306:办理人(历史数据为空) + entity.getHandleOperatorId() == null ? 0L : entity.getHandleOperatorId(), + entity.getHandleOperatorName(), + OperatorIdentity.normalize(entity.getHandleOperatorIdentity())); } public static FlowRecordEntity convert(FlowRecord record) { @@ -133,6 +137,9 @@ public static FlowRecordEntity convert(FlowRecord record) { entity.setCurrentOperatorIdentity(OperatorIdentity.validate(record.getCurrentOperatorIdentity())); entity.setForwardOperatorIdentity(OperatorIdentity.validate(record.getForwardOperatorIdentity())); entity.setInterferedOperatorIdentity(OperatorIdentity.validate(record.getInterferedOperatorIdentity())); + entity.setHandleOperatorId(record.getHandleOperatorId()); + entity.setHandleOperatorName(record.getHandleOperatorName()); + entity.setHandleOperatorIdentity(OperatorIdentity.validate(record.getHandleOperatorIdentity())); return entity; } diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowRecordEntity.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowRecordEntity.java index 7e7a306a..af362361 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowRecordEntity.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowRecordEntity.java @@ -239,6 +239,22 @@ public class FlowRecordEntity { @Column(length = OperatorIdentity.MAX_LENGTH) private String interferedOperatorIdentity; + /** + * 办理人Id(issue #306),记录办结时的实际办理人,暂存与抄送不写入 + */ + private Long handleOperatorId; + + /** + * 办理人名称(issue #306) + */ + private String handleOperatorName; + + /** + * 办理人身份标识(issue #306),空值等价默认身份 + */ + @Column(length = OperatorIdentity.MAX_LENGTH) + private String handleOperatorIdentity; + /** * 委托记录id */ From aae77b045ce9225acba085c05f2cf7ac617db44c Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Thu, 3 Dec 2026 16:14:31 +0800 Subject: [PATCH 24/35] =?UTF-8?q?fix(#306):=20=E5=B7=B2=E5=8A=9E=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E8=A1=A5=E9=BD=90=E5=8A=9E=E7=90=86=E4=BA=BA=E6=98=A0?= =?UTF-8?q?=E5=B0=84=EF=BC=8C=E4=BF=AE=E5=A4=8D=20handle=20=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=E6=81=92=E4=B8=BA=20null?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 查询层通过 FlowRecordContentConvertor.convert(FlowRecordEntity) 组装列表数据, 不走领域对象链路;本次只改了领域对象与实体映射,漏了该转换器, 导致已落库的办理人/办理身份在已办、全部流程列表始终返回 null, 前端只能回退到待办归属人。 - 转换器补 handleOperatorId/Name/Identity 映射(存量数据身份归一化为空串) - 新增 FlowRecordContentConvertorTest 覆盖已办记录与存量记录两种情况 --- .../convert/FlowRecordContentConvertor.java | 4 + .../FlowRecordContentConvertorTest.java | 105 ++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertorTest.java diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertor.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertor.java index 3d44a16b..b1810559 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertor.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertor.java @@ -69,6 +69,10 @@ public static FlowRecordContent convert(FlowRecordEntity record){ content.setRecordState(record.getRecordState()); content.setFlowState(record.getFlowState()); content.setNotify(record.getNotify()); + // issue #306:已办列表的办理人(历史数据为空,身份统一归一化为默认身份) + content.setHandleOperatorId(record.getHandleOperatorId()); + content.setHandleOperatorName(record.getHandleOperatorName()); + content.setHandleOperatorIdentity(OperatorIdentity.normalize(record.getHandleOperatorIdentity())); return content; } } diff --git a/flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertorTest.java b/flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertorTest.java new file mode 100644 index 00000000..013b6d93 --- /dev/null +++ b/flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertorTest.java @@ -0,0 +1,105 @@ +package com.codingapi.flow.infra.convert; + +import com.codingapi.flow.infra.entity.FlowRecordEntity; +import com.codingapi.flow.pojo.response.FlowRecordContent; +import com.codingapi.flow.record.FlowRecord; +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.assertNull; + +/** + * 已办列表响应映射测试(issue #306)。 + * + *

    查询层({@code FlowRecordQueryServiceImpl})把 JPA 实体直接交给 + * {@link FlowRecordContentConvertor#convert(FlowRecordEntity)} 组装列表数据, + * 不走领域对象链路。因此「办理人」三字段必须在该转换器里显式映射, + * 否则已办列表拿到的永远是 null,前端只能回退到待办归属人。 + */ +class FlowRecordContentConvertorTest { + + /** + * 构造字段完整的流程记录实体,避免转换时的拆箱 NPE 干扰断言。 + */ + private FlowRecordEntity newRecordEntity() { + FlowRecordEntity entity = new FlowRecordEntity(); + entity.setId(2L); + entity.setWorkRuntimeId(1L); + entity.setWorkTitle("身份标识验证流程"); + entity.setWorkCode("identity-demo"); + entity.setNodeId("approval"); + entity.setNodeType("APPROVAL"); + entity.setNodeName("审批节点"); + entity.setTitle("你有一条待办"); + entity.setFromId(0L); + entity.setParentId(0L); + entity.setReadTime(0L); + entity.setCurrentOperatorId(2L); + entity.setCurrentOperatorName("张三"); + entity.setSubmitOperatorId(1L); + entity.setForwardOperatorId(0L); + entity.setNodeOrder(0); + entity.setHidden(false); + entity.setRevoked(false); + entity.setNotify(false); + entity.setRecordState(FlowRecord.SATE_RECORD_DONE); + entity.setFlowState(FlowRecord.SATE_FLOW_FINISH); + entity.setUpdateTime(0L); + entity.setCreateTime(0L); + entity.setFinishTime(0L); + entity.setReadable(false); + entity.setCreateOperatorId(1L); + entity.setTimeoutTime(0L); + entity.setMergeable(false); + entity.setInterferedOperatorId(0L); + entity.setDelegateId(0L); + entity.setParallelBranchTotal(0); + return entity; + } + + /** + * 测试目标:已办记录的办理人(人 + 身份)必须出现在列表响应里。 + * 前置条件:实体带有本次办理人信息(张三以 department1 身份办理)。 + * 执行步骤:实体 → 列表响应对象。 + * 期望断言:办理人 id / 名称 / 身份与实体一致,且不与待办归属人混淆。 + */ + @Test + void should_expose_handle_operator_for_done_record() { + FlowRecordEntity entity = newRecordEntity(); + entity.setCurrentOperatorIdentity(""); + entity.setCreateOperatorIdentity(""); + entity.setHandleOperatorId(2L); + entity.setHandleOperatorName("张三"); + entity.setHandleOperatorIdentity("department1"); + + FlowRecordContent content = FlowRecordContentConvertor.convert(entity); + + assertAll( + () -> assertEquals(2L, content.getHandleOperatorId()), + () -> assertEquals("张三", content.getHandleOperatorName()), + () -> assertEquals("department1", content.getHandleOperatorIdentity()), + // 待办归属身份保持原样,办理身份不覆盖它 + () -> assertEquals("", content.getCurrentOperatorIdentity()) + ); + } + + /** + * 测试目标:升级前的存量已办记录(办理人列为空)不报错、不伪造数据。 + * 前置条件:实体 handle 三字段均为 null。 + * 执行步骤:实体 → 列表响应对象。 + * 期望断言:id / 名称保持 null,身份归一化为空串,前端据此回退待办归属人。 + */ + @Test + void should_keep_handle_operator_empty_for_legacy_done_record() { + FlowRecordEntity entity = newRecordEntity(); + + FlowRecordContent content = FlowRecordContentConvertor.convert(entity); + + assertAll( + () -> assertNull(content.getHandleOperatorId()), + () -> assertNull(content.getHandleOperatorName()), + () -> assertEquals("", content.getHandleOperatorIdentity()) + ); + } +} From 89bc6989efe85cdde5dfe8ce5189039b659e8f31 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Thu, 3 Dec 2026 16:37:57 +0800 Subject: [PATCH 25/35] =?UTF-8?q?chore(example):=20=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E5=89=8D=E7=AB=AF=E5=AD=90=E6=A8=A1=E5=9D=97=EF=BC=88=E5=BE=85?= =?UTF-8?q?=E5=8A=9E=E5=88=97=E8=A1=A8=E5=90=88=E5=B9=B6=E4=B8=BA=E3=80=8C?= =?UTF-8?q?=E5=8A=9E=E7=90=86=E4=BA=BA=E3=80=8D=E5=88=97=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 前端 flow-frontend dev 已合入 PR #91(a8f5ff5e): - 待办/已办列表的「审批人」+「身份」两列合并为「办理人」(名字 + 身份标签), 消除同一列在待办与已办下语义漂移的歧义 - 移动端已办改为优先取 handle_operator_name/identity,修复已办显示待办归属人的问题 - PC 补齐列宽并启用横向滚动,避免窄窗口中文列名竖排 子模块指针由 775d07b0 更新到 a8f5ff5e。 --- flow-frontend | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flow-frontend b/flow-frontend index 775d07b0..a8f5ff5e 160000 --- a/flow-frontend +++ b/flow-frontend @@ -1 +1 @@ -Subproject commit 775d07b0481c98d1423744a396f9d0f7ceef1150 +Subproject commit a8f5ff5ef0bb84093c530ca1c7ca7a47f3e85024 From e93c2268a6d3bd42870516cb19073a0086c48e2d Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Thu, 3 Dec 2026 17:47:44 +0800 Subject: [PATCH 26/35] =?UTF-8?q?docs(conventions):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E8=AE=BE=E8=AE=A1=E4=B8=89=E5=B1=82=E6=B3=95?= =?UTF-8?q?=E4=B8=8E=E5=A4=9A=E8=BA=AB=E4=BB=BD=E8=AF=AD=E4=B9=89=E5=A5=91?= =?UTF-8?q?=E7=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - design/model-design.md:职责 → 抽象 → 实现;DDD 分层 × 尺度递归;以易维护与可验证为验收 - domain/operator-identity.md:参与人相等与参与人键各只有一个定义点;匹配模式影响键时须经键模型 - AGENTS.md / CLAUDE.md 同步强制条款,规范索引注册 Refs #310, #311 --- AGENTS.md | 27 ++ CLAUDE.md | 27 ++ docs/conventions/design/model-design.md | 453 +++++++++++++++++++ docs/conventions/domain/operator-identity.md | 150 ++++++ docs/conventions/index.md | 4 +- 5 files changed, 660 insertions(+), 1 deletion(-) create mode 100644 docs/conventions/design/model-design.md create mode 100644 docs/conventions/domain/operator-identity.md diff --git a/AGENTS.md b/AGENTS.md index 79843b7a..9b01e46e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -113,6 +113,33 @@ cd flow-engine-example && mvn spring-boot:run - **在每次修改代码以后,要执行本地化的编译验证确保代码没有错误** - Java 代码遵循 Spring Boot 规范 +### 模型设计(分层 → 职责 → 抽象 → 实现) + +写新类 / 改结构前必须遵守 [docs/conventions/design/model-design.md](./docs/conventions/design/model-design.md),顺序不可颠倒: + +0. **分层**:先判它属于业务(Domain)/ 数据(Repository)/ 技术细节(Infrastructure)哪一层,包位置对不对;Domain 不得依赖 JPA、HTTP、脚本引擎、上传格式处理;数据层不写业务判断。 +1. **职责**:一句话说清它为什么存在(不含「和」);三条边界(谁能调用 / 依赖谁 / 返回值归谁)明确;名字能反推职责。 +2. **抽象**:共性提炼为唯一真源(不是复用,是唯一真源);会变的部分与不变的部分分开;不跨抽象层取字段。 +3. **实现与命名**:按调用方的使用方式选模式(对象 / 策略 / 工厂 / Context / 事件 / 网关 / 仓储),命名必须体现模式;模式反推拆分。 +4. **形态**:禁止「空私有构造 + 公有静态方法」的工具类;上下文一律**构造注入**;**一个对象一个公有入口**;静态方法只允许无状态纯计算与类型自身语义;`private static` 可变字段必须收敛到 `XxxContext` / `XxxCache`。 + +同一规则在包 / 类 / 方法三个尺度上递归适用,评审时追问:**这一层的职责和上一层是不是同一个粒度?** + +验收两条:**易维护**(新增一种能力 = 加文件,不改老流程的 `if`)+ **可验证**(新增先有失败用例;重构只能改调用形式,断言零改动)。 + +### 多身份(Operator Identity) + +改 `com.codingapi.flow.operator` 或任何涉及「人员 + 身份」的代码前,必须遵守 [docs/conventions/domain/operator-identity.md](./docs/conventions/domain/operator-identity.md)。四条硬线: + +- **不得新增** `(long operatorId, String identity)` 形式的公开签名,一律传 `OperatorKey`; +- 「是否同一参与人」只允许调 `OperatorKey#matches(..., mode)`,禁止内联 id/identity 比较; +- 参与人键(缓存键 / Map 键 / 去重键)只允许由 `OperatorKey#key()` 产生,禁止自行拼字符串; +- 匹配模式只能改变**判定**,不得在方法体里读 `matchMode()` 去改变**数据格式**(待办合并键、响应去重键)。 + +提交前四问见规范正文;分批改造顺序 P1 相等收敛 → P2 键收敛 → P3 模式策略化 → P4 对象化 → P5 类型化,每批行为零变化且断言不改。 + +存量待改造清单见 issue #309,样板改造见 issue #308。 + ### 测试规范 本项目后端采用 JUnit 5 进行单元测试。 diff --git a/CLAUDE.md b/CLAUDE.md index 669c9eeb..54fbebe2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -106,6 +106,33 @@ cd flow-engine-example && mvn spring-boot:run - **在每次修改代码以后,要执行本地化的编译验证确保代码没有错误** - Java 代码遵循 Spring Boot 规范 +### 模型设计(分层 → 职责 → 抽象 → 实现) + +写新类 / 改结构前必须遵守 [docs/conventions/design/model-design.md](./docs/conventions/design/model-design.md),顺序不可颠倒: + +0. **分层**:先判它属于业务(Domain)/ 数据(Repository)/ 技术细节(Infrastructure)哪一层,包位置对不对;Domain 不得依赖 JPA、HTTP、脚本引擎、上传格式处理;数据层不写业务判断。 +1. **职责**:一句话说清它为什么存在(不含「和」);三条边界(谁能调用 / 依赖谁 / 返回值归谁)明确;名字能反推职责。 +2. **抽象**:共性提炼为唯一真源(不是复用,是唯一真源);会变的部分与不变的部分分开;不跨抽象层取字段。 +3. **实现与命名**:按调用方的使用方式选模式(对象 / 策略 / 工厂 / Context / 事件 / 网关 / 仓储),命名必须体现模式;模式反推拆分。 +4. **形态**:禁止「空私有构造 + 公有静态方法」的工具类;上下文一律**构造注入**;**一个对象一个公有入口**;静态方法只允许无状态纯计算与类型自身语义;`private static` 可变字段必须收敛到 `XxxContext` / `XxxCache`。 + +同一规则在包 / 类 / 方法三个尺度上递归适用,评审时追问:**这一层的职责和上一层是不是同一个粒度?** + +验收两条:**易维护**(新增一种能力 = 加文件,不改老流程的 `if`)+ **可验证**(新增先有失败用例;重构只能改调用形式,断言零改动)。 + +### 多身份(Operator Identity) + +改 `com.codingapi.flow.operator` 或任何涉及「人员 + 身份」的代码前,必须遵守 [docs/conventions/domain/operator-identity.md](./docs/conventions/domain/operator-identity.md)。四条硬线: + +- **不得新增** `(long operatorId, String identity)` 形式的公开签名,一律传 `OperatorKey`; +- 「是否同一参与人」只允许调 `OperatorKey#matches(..., mode)`,禁止内联 id/identity 比较; +- 参与人键(缓存键 / Map 键 / 去重键)只允许由 `OperatorKey#key()` 产生,禁止自行拼字符串; +- 匹配模式只能改变**判定**,不得在方法体里读 `matchMode()` 去改变**数据格式**(待办合并键、响应去重键)。 + +提交前四问见规范正文;分批改造顺序 P1 相等收敛 → P2 键收敛 → P3 模式策略化 → P4 对象化 → P5 类型化,每批行为零变化且断言不改。 + +存量待改造清单见 issue #309,样板改造见 issue #308。 + ### 测试规范 本项目后端采用 JUnit 5 进行单元测试。 diff --git a/docs/conventions/design/model-design.md b/docs/conventions/design/model-design.md new file mode 100644 index 00000000..24fea040 --- /dev/null +++ b/docs/conventions/design/model-design.md @@ -0,0 +1,453 @@ +--- +name: design/model-design +module: design +description: 模型设计三层法 — 职责 → 抽象 → 实现;垂直按 DDD 分层(业务/数据/技术),水平按包/类/方法递归;以易维护与可验证为验收 +status: 已实现 +scope: 通用 +source: 项目自有 +--- + +## 为什么要有这套约束 + +一个有生命力的软件,成本不在写,在**持续维护**。而持续维护只靠两套机制撑着: + +**一、可验证性 —— 先对,再好** + +所有代码先是对的,然后再追求好的;反过来不成立。架构再漂亮,业务算错了就是负资产。这是 TDD 的机制依据:先写失败用例(证明问题存在),再写实现(证明问题解决),最后才谈结构。 + +**二、易维护性 —— 读得懂 + 改得小** + +- **读得懂**:调用方只读一个方法签名就能用对,不需要通读整个类; +- **改得小**:新增能力时**加代码**,而不是**改老代码**(开闭原则)。 + +两者的关系不是并列:**可验证性是底线,易维护性是上限。** 冲突时先保正确性——没有用例守护的「漂亮重构」,是在拿线上功能赌审美。 + +三层设计正好各服务一个目标,这也是为什么顺序不能颠倒: + +| 设计层 | 服务的目标 | 失效时的症状 | +|---|---|---| +| 职责 | 读得懂 | 类名说不清它干什么,看代码要读到最后一行 | +| 抽象 | 改得小 | 每加一种情况都改主流程,回归面积越来越大 | +| 实现与命名 | 可验证 | 依赖无法替换,测一个分支要起整套环境 | + +第三条最容易被忽略:**能不能测,往往不是测试写得好不好,而是依赖有没有被注入。** 静态工具类把依赖藏在参数甚至方法体里,测试就只能构造整个世界。 + +顺序反过来——先想好「这里用个策略模式」再去找职责——只会得到为了模式而模式的空壳。 + +## 两个正交维度 + +模型设计的定位是二维的,缺任何一维都定不准一个类: + +``` + 垂直:DDD 分层(谁不许碰谁) + 业务 Domain + 数据 Repository + 技术细节 Infrastructure + ▲ + │ 每一格内部,都按「职责 → 抽象 → 实现」三步走 + │ + 水平:尺度 包 ──────────┼────────── 类 ────────── 方法 +``` + +### 垂直:业务 / 数据 / 技术细节 + +DDD 的核心不是聚合根、不是值对象,是**分层**:把业务、数据、技术细节分开,各自只对自己负责。业务整合完全通过模型完成,数据是 Repository 的事,技术细节落在 infrastructure。 + +| 层 | 职责 | 本仓库对应 | 禁止 | +|---|---|---|---| +| 业务(Domain) | 业务规则与状态流转,纯模型 | `node` `action` `strategy` `workflow` `record` `operator` `form` `service`(编排)`event` | JPA 注解、SQL、HTTP、脚本引擎调用 | +| 数据(Repository) | 领域对象的持久化与查询 | `repository`(接口)+ `flow-engine-starter-infra`(JPA 实现、Convertor) | 承载业务判断 | +| 技术细节(Infrastructure) | 框架接入、序列化、脚本运行时、REST | `flow-engine-starter`(自动配置)、`starter-api`、`starter-query`、`script/runtime`、`javscript` | 被 Domain 反向依赖 | + +判据:**换掉一个技术选型(ORM、脚本引擎、Web 框架),业务模型应当零改动。** 做不到,说明某一层已经把另一层焊死了。 + +### 三处已知渗透(登记,不要求立刻改) + +1. **`IRepositoryHolder` 一个端口暴露了四种角色**:`XxxRepository`(数据)、`FlowService` / `FlowRecordService` / `WorkflowService`(业务编排)、`FlowOperatorGateway`(外部能力)、`createDelayTriggerService(...)`(工厂方法)。调用方从类型上已经看不出自己站在哪一层——这和「工具类返回值没有归属」是同一个病:**端口没有层**。 + +2. **`flow-engine-framework` 直接依赖 `springboot-starter-script`(Groovy 运行时)。** `script` 包本质是「领域规则的可配置化表达」,但它的执行引擎是技术细节。理想形态是 Domain 只依赖 `IScriptExecutor` 端口,Groovy 实现留在 infrastructure。 + +3. **`WorkflowService.importWorkflow` 调 `Base64Utils.toJson(body)` 做 base64 + `data:` 前缀剥离。** 上传格式属于接入层,却出现在业务服务里;而 `Base64Utils` 这个名字承诺「Base64 编解码」,方法却叫 `toJson` 且只做解码,返回的其实是原始文本——名字、方法名、实际职责三者都不一致。它的异常分支 `base64.substring(0, 30)` 在长度不足 30 时还会抛 `StringIndexOutOfBoundsException`,因为这段代码没有测试守护。 + +这三处不是「架构错了」,是历史包袱。规范的作用是:**新增代码不得再加深渗透**,存量按 #309 的节奏处理。 + +## 第一层:职责 + +### 一句话职责 + +能用一句**不含「和」**的话说清楚。说不清,说明职责还没定,此时不该开始写代码。 + +`OperatorScriptResultResolver` 内部有五个步骤(归一化、类型判定、id 校验、分组回查、按序还原),但它只有一个职责:**把脚本返回值解析为参与人列表**。步骤多不等于职责多;职责多才叫职责多。 + +### 职责的三条边界 + +1. **谁能调用它**(可见性)——`public` 就是一份对外契约,改签名等于改契约; +2. **它能调用谁**(依赖方向)——依赖必须单向。`FlowSession` 调 `OperatorLoadScript`,`OperatorLoadScript` 就不能反向读 `FlowSession` 的私有状态; +3. **它产出什么,归谁**(返回值归属)——这是静态工具类的死穴:返回值放哪都行,所以谁都不对它负责。 + +第 3 条是「工具类责任漂移」的根因。`OperatorScriptResultResolver.resolve(...)` 返回的 `List`,从签名上看不出属于谁;一旦改成对象,返回值天然挂在这个对象的一次完整动作上。 + +### 职责 ≠ 功能清单 + +反例(现存): + +```java +public class OperatorAssignmentService { + private OperatorAssignmentService() { } + + public static boolean hasAssignment(FlowSession session, String nodeId) { ... } + public static ... // 另外两个方法与 hasAssignment 互不相关 +} +``` + +它没有状态、没有依赖,三个方法彼此无关。这不是一个模型,是一个函数集合借用了「Service」的名字。它真实需要的职责只是「判断某节点是否已分配操作人」——一个方法、一个对象,其余归回调用方或 `FlowSession`。 + +硬判据:**把类里所有公有方法排成一列,如果它们共享的只有包名,那它们不是一个类的职责。** + +### 命名必须能反推职责 + +名字是调用方看到的第一份文档,也是唯一一定会被读到的文档: + +- `XxxService` 承诺:有业务语义、有协作依赖、可被编排; +- `XxxPolicy` 承诺:只做判定,不持有状态; +- `XxxGateway` 承诺:外部系统边界,可能失败; +- `XxxContext` 承诺:进程内唯一状态; +- `XxxRepository` 承诺:只做存取。 + +名字与实际不符,后续所有人都会按名字用错,而且没有人会去读实现来纠正。`OperatorIdentityPolicy` 同时是全局配置持有者(`private static volatile matchMode`)和判定逻辑,`Policy` 这个后缀掩盖了它是单例状态;`Base64Utils` 则把一个上传格式的解码伪装成了通用编解码工具。 + +## 第二层:抽象 + +### 三个提问 + +1. **共性**:这段行为在本工程里还有谁需要? +2. **差异**:变的是什么,不变的是什么? +3. **层次**:这个对象和它的协作者,在同一个抽象层级上吗? + +### 共性:什么时候该提炼 + +不是「有两处相似就抽」,那是过早抽象。触发条件只有两条: + +- 同一个概念被 ≥2 个协作者以**相同语义**需要。例:「脚本返回值 → 参与人」被取人脚本、异常脚本、上一节点取人、分配回查四处需要,且语义完全一致 → 必须提炼成唯一模型,否则会出现四份各自演化的实现(本仓库历史上确实演化了三份)。 +- 或者它是某条业务规则的**唯一定义点**。例:身份匹配策略。即使只有一处调用,也需要一个地方回答「什么算同一个人」,否则今天在审批里放宽、明天在撤回里收紧,就会出现「能审批但不能撤回」的半开状态。 + +判断口径:**复用不是目的,唯一真源才是。** + +### 差异:抽象点落在「变化频率相同」处 + +Parnas 的信息隐藏原则:模块边界应该沿着「可能变化的方向」切。 + +取人脚本返回值这个例子: + +| 部分 | 变化频率 | 归属 | +|---|---|---| +| 脚本返回形态(Long / OperatorKey / IFlowOperator,未来可能再加) | 高 | 下沉为元素类型(`Direct` / `Pending`) | +| 解析骨架(归一化 → 逐元素 → 批量回查 → 按序还原) | 低 | 留在主流程 | + +把两者塞进同一个 `resolve()` 的后果是可量化的:新增一种返回形态,要改主流程、要重新回归全部 12 个用例。拆开之后,新增形态 = 新增一个元素类型,主流程不动。 + +判据:**会变的部分和不变的部分放在同一个类里,等于让不变的部分陪着变的部分一起回归。** + +### 开闭原则:抽象的验收形式 + +「改得小」不是感觉,可以数出来: + +- **合格**:新增一种能力,改动 = 新增 1 个文件(或 1 个实现类),老流程零改动; +- **不合格**:新增一种能力,要改 `resolve()` / `process()` 里的 `if` 链或 `switch` 分支。 + +正例:新增加签动作 = 新增一个 `Action` 子类,`ActionManager` 只做登记;新增一种脚本返回形态 = 新增元素类型,主流程不动。 + +反例:`resolve()` 里那条 5 分支的 `instanceof` 链——每加一种形态都必须改主流程(#308 要修的就是这个)。 + +**抽象的目的,是让「新增」落在新类型上,而不是落在老方法的 `if` 里。** + +### 抽象层级不能混 + +跨层调用只能向下,不能向上: + +``` +Workflow(流程定义) + └── IFlowNode(节点) + └── NodeStrategy(节点行为) + └── Action(动作) +``` + +混层的典型症状:**方法参数里出现比自己高一层或低一层的对象,而只是为了取一个字段。** + +- 节点级对象持有 `Workflow` 并自己遍历节点 → 该在 Workflow 层提供能力; +- `Workflow` 里出现「单个节点某个审批人的解析细节」 → 该在节点层。 + +这类代码通常能跑,但一旦上层结构变化,下层全部要跟着改。 + +### 抽象不足与过度 + +| | 症状 | 后果 | +|---|---|---| +| 不足 | 每种差异一个 `if (x instanceof ...)` + `continue`,新增形态改主流程 | 主流程越来越长,回归成本线性上升 | +| 过度 | 为一种差异建一套继承;只有一个实现的接口;`XxxFactory` 只 `new` 一个类 | 读代码要跳五层才看到一行有效逻辑 | + +判据:**抽象的数量应该等于「真正独立变化的原因」的数量。** 多一个是负担,少一个是耦合。 + +## 第三层:实现方式与使用方式 + +### 使用方式决定类的能力 + +调用方怎么用它,决定它应该长成什么样。这不是「选个模式显得专业」,而是把使用契约固化下来: + +| 调用方的需要 | 形态 | 命名 | 本仓库实例 | +|---|---|---|---| +| 带着上下文做一次转换 | 对象,构造注入 | `XxxResolver` / `Parser` / `Loader` | `OperatorLoadScript` | +| 按 key 切换不同实现 | 策略 + 注册表 | `XxxStrategy` | `RevokeStrategy`、`OperatorLoadStrategy` | +| 只关心对象怎么创建 | 工厂 / 构建者 | `XxxFactory` / `XxxBuilder` | `NodeFactory`、`ActionBuilder` | +| 全局唯一状态 | 单例 | `XxxContext` / `Cache` / `Registry` | `RepositoryHolderContext` | +| 已发生事实的通告 | 事件 | `XxxEvent` + `EventPusher` | `FlowRecordSaveEvent` | +| 外部系统能力(可能失败) | 网关 | `XxxGateway` | `FlowOperatorGateway` | +| 数据存取 | 仓储 | `XxxRepository` | `FlowRecordRepository` | +| 业务编排入口 | 服务 | `FlowXxxService` | `FlowActionService` | + +### 命名即契约 + +模式选定后,命名必须体现模式。理由是可读性,但收益比可读性更大:**命名是对使用者的用法约束。** + +- `Repository` —— 只做存取。里面出现业务判断,就是职责错位,而不是「顺手封一下」; +- `Gateway` —— 外部边界,允许失败。调用方看到这个名字就该处理异常,而不是假设它一定返回; +- `Event` —— 已发生的事实,不可变,不承载「希望别人做什么」; +- `Service` —— 业务编排,必须有依赖。**出现空私有构造 + `public static`,直接判为缺陷**; +- `Context` —— 进程内单例状态,非线程安全要在注释里说明。 + +### 模式是拆分的依据 + +一个类里同时出现多种模式的痕迹——既是策略实现、又做缓存、又提供静态创建入口——至少是三个模型。 + +反过来也成立:**模式选不出来,通常不是「这个类还不需要设计」,而是职责没拆开。** + +现存错配: + +| 类 | 名字承诺 | 实际职责 | 修法 | +|---|---|---|---| +| `OperatorAssignmentService` | 业务服务 | 3 个互不相关的静态方法 | 收为 1 个判定方法,挂到 `FlowSession` 或独立对象 | +| `OperatorIdentityPolicy` | 只做判定 | 6 个静态方法 + 全局可变配置 | 拆 `...PolicyContext`(配置)+ 判定对象 | +| `OperatorIdentityGuard` | 运行期检查 | 静态去重缓存 + 告警 | 缓存归 Context,检查归对象 | +| `OperatorScriptResultResolver` | 解析器 | 静态工具类(4 个重载) | 构造注入对象 + 元素类型(#308) | +| `Base64Utils` | Base64 编解码 | 上传格式解码(`data:` 前缀剥离) | 移到接入层,改名为上传格式解析器 | + +## 水平:职责的尺度递归 + +模型不止是类,也是包;不止是包,也是方法。**单一职责是同一条规则在不同尺度上的应用,不是三套规则。** + +| 尺度 | 问什么 | 不合格信号 | +|---|---|---| +| 包 | 这个包因为什么而变? | 两个包的类总因同一需求一起改(该合并);一个包里两组类从不一起改(该拆) | +| 类 | 这个类因为什么而变? | 类注释里出现「以及」「同时」「顺便」 | +| 方法 | 这个方法做几步? | 超过 40 行、有注释分区(`// 1. xxx`)、有 `instanceof` 链、参数超过 4 个 | + +评审时追问一句:**这一层的职责,和上一层的职责,是不是同一个粒度?** + +粒度错位的典型:Controller 里写业务规则(该在 Service)、Service 里拼查询条件(该在 Repository)、Repository 里抛业务异常(该在 Service)。这三种代码都能编译通过、也都能跑,但每一处都让边界变得不可信。 + +## 代码形态:对象优先 + +前三层定完之后,形态是自然结果。以下四条是第三层的落地约束。 + +1. **有上下文的行为,必须落在对象上。** + 需要仓储、会话、配置、脚本类型、当前操作者等「跨调用稳定」的数据,用构造注入变成字段;不要每次调用再传一遍。 + +2. **一个对象一个公有入口。** + 公有方法的数量 = 调用方必须做的选择次数。出现多个近义重载,说明入参没有归位:能靠构造注入消灭的,消灭掉;消灭不了的,拆成两个类。 + +3. **依赖不进方法签名。** + 构造函数注入过的依赖,不得再出现在方法参数中。方法参数只放「每次调用真正会变」的入参。 + +4. **静态方法只用于两类场景。** + - 无状态纯计算:`Math.max`、`isNumeric(String)` + - 类型自身的语义:`OperatorKey.of(...)`、`OperatorIdentity.normalize(...)` + + 凡是要读外部状态、要回查、要抛业务异常的,都不属于这两类。 + +### 改造前 / 改造后 + +```java +// 前:静态工具类,4 个重载,上下文靠参数传 +public final class OperatorScriptResultResolver { + private OperatorScriptResultResolver() { } + public static List resolve(FlowSession session, Object result) { ... } + public static List resolve(FlowSession session, Object result, String scriptType) { ... } + public static List resolve(IRepositoryHolder holder, Object result) { ... } + public static List resolve(IRepositoryHolder holder, Object result, String scriptType) { ... } +} +``` + +```java +// 后:对象,上下文进字段,一个公有入口 +public class OperatorScriptResultResolver { + + private final IRepositoryHolder repositoryHolder; + private final String scriptType; + + public OperatorScriptResultResolver(FlowSession session, String scriptType) { + this(session.getRepositoryHolder(), scriptType); + } + + public OperatorScriptResultResolver(IRepositoryHolder repositoryHolder, String scriptType) { + this.repositoryHolder = repositoryHolder; + this.scriptType = scriptType; + } + + /** 唯一公有入口 */ + public List resolve(Object scriptResult) { ... } + + private List parse(Object scriptResult) { ... } + private Map load(List keys) { ... } +} +``` + +### 元素对象化(第二层的抽象结果) + +```java +sealed interface OperatorScriptElement { + record Direct(IFlowOperator operator) implements OperatorScriptElement { } + record Pending(OperatorKey key) implements OperatorScriptElement { } +} +``` + +每个元素自己回答「我是什么、我是否有效」;主流程只剩 `parse → load → 按序还原`。这是第二层(差异下沉)自然导出的结构,不是单纯为了消除 `if`。 + +## 可验证性:先对,再好 + +架构质量的上限由业务正确性决定,而正确性只能由用例证明。落地为三条硬规矩: + +1. **新增能力先写失败用例。** 没有红灯,就没有「问题存在」的证明,绿灯也就没有意义。 +2. **重构的验收 = 行为契约零变化 + 既有断言语义零改动。** 只允许改调用形式(如 `resolve(...)` → `new Resolver(...).resolve(...)`),不允许顺手改断言。#308 的 12 个用例就按这条验收。 +3. **端口(接口)只在「依赖在测试里无法真实构造」时引入**:时间、外部系统、随机数、网络、文件系统。 + - 正例:`FlowOperatorGateway`(外部用户体系)、`IRepositoryHolder`(数据库) + - 反例:给一段纯计算逻辑加接口 + 实现,只为在测试里 mock 它 + + **不要为了可测而抽象。** 每个端口都是一层间接,可读性要为它付费。 + +第 3 条是「抽象过度」在可验证性上的镜像:抽象解决「测不了」,不解决「测得慢」。 + +## 判定流程 + +写新类 / 改结构前按顺序过一遍,能答完再动手: + +``` +A0 分层 + 这个模型属于业务 / 数据 / 技术细节哪一层?包位置对吗? + 是否在反向依赖(Domain 引技术、数据层写业务判断)? + +A 职责 + A1 能用一句不含「和」的话说清它负责什么吗? + └─ 不能 → 停;若答案是「一堆工具方法」,说明没有模型,不该建类 + A2 谁能调用它 / 它依赖谁 / 返回值归谁,三条边界都清楚吗? + A3 公有方法排成一列,它们共享的是状态,还是只有包名? + +B 抽象 + B1 这段行为的共性,工程里还有谁需要?是否需要唯一真源? + B2 变的部分和不变的部分,是否被放进了同一个类? + B3 新增一种情况时,是加文件还是改老方法的 if?(开闭验收) + B4 对象与协作者是否在同一抽象层级? + +C 实现与使用 + C1 调用方怎么用它?据此选定模式 + C2 命名是否体现了这个模式,且与实际职责一致? + +D 形态 + D1 是否存在跨调用共享的上下文 → 必须构造注入 + D2 公有方法是否 > 1 且需调用方选择 → 收敛入口或拆类 + D3 依赖是否出现在方法签名里 → 改为字段 + D4 是否存在 static 可变字段 → 必须是 Context 单例 + +E 可验证 + E1 不起整套环境,能不能验证这一个行为? + E2 重构有没有既有用例守护?断言是否零改动? + E3 新增的端口是否必要(依赖是否真的无法真实构造)? +``` + +> 一句话判据:**如果调用方必须先读完整个类才能用对一个方法,这个类就写错了。** + +## 允许的例外 + +以下形态不算违规,但**必须在类注释中写明属于哪一类**: + +| 形态 | 允许理由 | 示例 | +|---|---|---| +| `XxxContext` / `XxxCache` / `XxxRegistry` 单例 | 全局唯一状态持有者,`getInstance()` 是唯一入口 | `RepositoryHolderContext`、`FlowRuntimeScriptLocalCache` | +| `XxxFactory` / `XxxBuilder` | 静态方法只负责创建对象,不承载业务行为 | `NodeFactory`、`ActionBuilder` | +| 值对象自身的语义 | 行为与类型强内聚,无外部依赖 | `OperatorKey.of/ofDefault`、`OperatorIdentity.normalize` | +| 枚举 / 常量类 | 无行为 | `OperatorIdentityMatchMode` | +| 框架要求的空构造 | 序列化 / `IMapConvertor` 反射需要 | `ActionDisplay`、实体类 | +| 单入口、无依赖的算法 | 只有 1 个公有方法,签名即语义 | `WorkflowStructureVerifier.compare` | + +判断标准只有一条:**这个类的所有公有方法,是否都不需要外部上下文、且调用方不存在选择困难。** 有一条不满足,就不是例外。 + +注意:例外只豁免**形态**,不豁免**分层**与**命名**。一个静态方法放错层、起错名,照样是缺陷。 + +## 命名红线 + +| 后缀 | 要求 | +|---|---| +| `XxxResolver` / `Parser` / `Loader` / `Evaluator` | 必须是对象,构造注入依赖 | +| `XxxService` | 必须有实例状态或构造注入依赖;空私有构造 + `public static` 直接判为缺陷 | +| `XxxContext` / `Cache` / `Registry` | 只允许 `getInstance()` 一个静态入口 | +| `XxxFactory` / `Builder` | 内部不得执行回查、落库等业务流程 | +| `XxxUtil` / `Utils` / `Helper` / `Tool` | **禁止新增**;存量遇到时改成对象或归入正确的层,而不是继续加方法 | + +## 评审清单 + +**分层** +- [ ] 模型的包位置与 DDD 层一致;Domain 里没有 JPA / SQL / HTTP / 上传格式 / 脚本引擎调用 +- [ ] 数据层没有业务判断;技术层没有被 Domain 反向依赖 + +**职责** +- [ ] 一句话说清职责,且不含「和」 +- [ ] 三条边界(谁能调 / 依赖谁 / 返回值归谁)明确 +- [ ] 公有方法排成一列,共享的不只是包名 + +**抽象** +- [ ] 共性是唯一真源,不是复制粘贴的产物 +- [ ] 会变的部分与不变的部分已经分开 +- [ ] 新增一种情况是「加文件」而不是「改 if」(开闭验收) +- [ ] 没有为取一个字段而跨抽象层 +- [ ] 没有为「一种差异」建一套继承或一个单实现接口 + +**实现与命名** +- [ ] 命名体现了所选模式,且与实际职责一致 +- [ ] 一个类里没有出现两种以上模式的痕迹 +- [ ] 新类注释里有一行用法示例 + +**形态** +- [ ] 依赖经构造注入,未出现在方法签名 +- [ ] 公有入口唯一;多个近义重载已收敛 +- [ ] 无 `private static` 可变字段 +- [ ] 主流程方法未超过 40 行,无 3 个以上 `instanceof` 分支 + +**可验证** +- [ ] 不起整套环境即可验证该行为 +- [ ] 新增能力有先行的失败用例;重构有既有用例守护且断言零改动 +- [ ] 新增的端口是必要的(依赖确实无法真实构造) + +## 自检命令 + +列出仓库中「空私有构造 + 公有静态方法」的候选类,逐个对照例外清单: + +```bash +for f in $(grep -rl "private [A-Z][A-Za-z0-9_]*() {" --include="*.java" . | grep "src/main/java"); do + n=$(grep -c "public static" "$f") + [ "$n" -gt 0 ] && echo "$n $f" +done | sort -rn +``` + +查分层渗透(Domain 模块里不该出现的依赖): + +```bash +grep -rn "jakarta.persistence\|org.springframework.web\|GroovyScript" \ + flow-engine-framework/src/main/java +``` + +包边界与抽象层无法靠命令判定,只能靠人:**这个包里的类,是不是因为同一个原因而修改?** + +## 关联 + +- 样板改造:#308 `OperatorScriptResultResolver` +- 存量盘点(含三处分层渗透的处置):#309 +- 讨论来源:#310 diff --git a/docs/conventions/domain/operator-identity.md b/docs/conventions/domain/operator-identity.md new file mode 100644 index 00000000..24c1fef6 --- /dev/null +++ b/docs/conventions/domain/operator-identity.md @@ -0,0 +1,150 @@ +# 多身份语义契约(Operator Identity) + +> 模块:domain · 范围:`com.codingapi.flow.operator` 及其全部调用方 +> 前置:[模型设计三层法](../design/model-design.md)。本文只回答一件事:**「身份」这个语义,谁说了算。** + +## 为什么单独立规矩 + +身份是参与人的第二维标识(#288)。它与普通字段的差别在四点: + +1. **贯穿所有读写路径**:待办、已办、匹配、撤回、催办、减签、子流程重置; +2. **有默认值**:`null` 与空串都表示「默认身份」,必须与存量行为完全等价; +3. **有全局开关**:匹配模式(`STRICT` / `USER_ONLY`)改变「谁算同一个人」; +4. **参与持久化键**:待办合并键、缓存键、去重键都由 `(人员id, 身份)` 派生。 + +第 3、4 点叠加后产生一个结构性风险:**改一个配置项,会改变已落库数据的主键语义**。`FlowRecord#getTodoKey()` 的注释里已经承认这一点——切换模式后存量待办合并组一分为二,需要 `FlowTodoMigrateService` 重建。风险根源不是配置本身,而是「键怎么拼」没有唯一归属。 + +#297 的实际故障(能审批却不能撤回)就是同一个语义出现两个答案的直接后果:审批路径按 `(id, 身份)` 判,撤回路径按 `id` 判。 + +## 现状:一个语义,多处置实现 + +### 参与人键(拼字符串)5 处,分隔符 4 份声明 + +| 位置 | 拼法 | 分隔符来源 | +|---|---|---| +| `OperatorKey#key()` | `operatorId + sep + identity` | 引用 `OperatorIdentity.KEY_SEPARATOR` = `#` | +| `FlowOperatorLocalThreadCache#cacheKey()` | `userId + sep + normalize(identity)` | 自己声明 `"\u0001"` | +| `OperatorIdentityGuard#check()` | `operatorId + sep + normalize(identity)` | 自己又声明一份 `"\u0001"` | +| `FlowContent#resolveCurrentNodeOperators()` | `id + "#" + normalize(identity)` | 引用 `KEY_SEPARATOR`,且 `USER_ONLY` 下改用裸 `id` | +| `FlowRecord#getTodoKey()` | `todoKey + "#" + identity` | 自己声明 `IDENTITY_KEY_SUFFIX` = `#` | + +**4 份常量声明、2 种字符、2 处需要先读匹配模式再决定格式。** + +### 「是否同一参与人」5 处入口 + +| 位置 | 判定方式 | +|---|---| +| `OperatorIdentity#same()` | 归一化后字符串相等(唯一实现) | +| `OperatorIdentityPolicy#matches()` | 先比 `id`,再按模式决定是否比身份 | +| `OperatorManager#getOperator()` | 内联 `id == id && same(...)` | +| `FlowOperatorLocalThreadCache#isIdentityMatched()` | 内联 `isDefault` 特判 + `same(...)` | +| `OperatorKey` record `equals` | 隐式依赖紧凑构造里的归一化 | + +### 关键判断 + +这两张表不是「代码重复」这么轻的问题,而是**同一业务规则存在多个定义点**: + +- 加一种匹配模式,要改 5 处中的 3 处(`Policy#matches`、`FlowRecord#getTodoKey`、`FlowContent`),漏一处就是半开状态; +- 改一次键格式,要同步 5 个类 + 1 个迁移服务; +- 想给「参与人键」加能力(带版本、可逆、可解析),没有挂载点。 + +按 [模型设计三层法](../design/model-design.md) 复盘这一族类: + +- **职责**:名字承诺了不属于它们的事。`Policy` 承诺策略却在做全局配置;`Guard` 承诺守卫却只做告警去重;`OperatorIdentity` 承诺身份类型却是一堆静态函数。 +- **抽象**:「参与人相等」与「参与人键」是两个变化频率相同的概念,各自都该独立成模型,现在却散落在使用者里。 +- **实现**:身份以裸 `String` 在 359 处流转,所以每一处都要重复「归一化 + 比较 + 拼接」,也就必然长成静态函数集合。 + +**结论**:这一族类的病根不是「用了静态方法」,是**身份没有成为类型**。形态问题只是症状。 + +## 契约 + +### H1 参与人标识必须成对传递 + +新增或修改的公开方法签名,**不得**再出现 `(long operatorId, String identity)` 这种「把一个人拆成两个参数」的形式,必须传 `OperatorKey`。 + +理由:拆开传会让「一个人」这个整体在签名层面消失,调用方随时可能漏传身份,编译器不会拦。这正是 359 处裸 `String` 的成因。存量签名在 P1/P2 中逐步收敛,但不得在新增代码里扩大。 + +### H2 同一参与人的判定只有一个入口 + +```java +OperatorKey#matches(OperatorKey other, OperatorIdentityMatchMode mode) +``` + +任何「这个人是不是那条记录上的人」的判断,都必须经过它(或接受 `IFlowOperator` 的重载)。 + +**禁止**在业务代码里写 `a.getUserId() == b.getUserId() && OperatorIdentity.same(...)`。写入即缺陷,不需要讨论。 + +### H3 参与人键只有一个生成点 + +```java +OperatorKey#key() +``` + +缓存键、Map 键、去重键一律由它产生。**禁止**任何类自行 `a + 分隔符 + b`;分隔符常量只允许**一处声明**。当前 4 份声明(`#` × 2、`\u0001` × 2)在 P2 收敛为 1 份。 + +待办合并键是复合键(参与人 + 运行时 + 节点),由独立的键模型回答,不复用 `key()`,但同样只能有一个定义点。 + +### H4 匹配模式只能改变判定,不能改变存储键格式 + +匹配模式是**运行时配置**,不得直接参与持久化键的构造。 + +当前 `FlowRecord#getTodoKey()` 与 `FlowContent` 都在方法体里读 `matchMode()` 并切换键格式——等于「重启改配置,历史数据的待办合并语义就变了」,而且不可逆。P2 的处置: + +1. 把「键是否含身份」下沉到键模型内部,作为一条显式规则(默认身份不加后缀,保证存量键不断裂); +2. 业务类不再自己判断模式; +3. 迁移服务复用同一个键模型,避免「拼法与迁移不同源」。 + +### H5 命名即契约(本域) + +| 名字 | 必须是什么 | 当前状态 | +|---|---|---| +| `OperatorIdentity` | 身份值对象(不可变,`of` 构造,`equals` 判等) | 名不副实:静态工具类 + 常量集合(P5) | +| `OperatorKey` | 参与人标识值对象,承载 `matches` 与 `key` | 形态对,能力缺(P1/P2) | +| `OperatorIdentityMatchMode` | 策略:自己回答 `match` | 名不副实:被外部 `if` 判断的枚举(P3) | +| `OperatorIdentityContext` | 全局配置持有(可变单例) | 名称错位:现在叫 `OperatorIdentityPolicy`(P3) | +| `OperatorManager` | 参与人集合,一个查找入口 | 有默认身份重载,入口未收敛(P1) | +| `OperatorIdentityGuard` | —— | 名不副实:告警去重属可观测性,不属领域(P5 移出) | + +### H6 分层:身份解析属接入层 + +`OperatorIdentity#pick(headerValue, parameterValue, parameterPresent)` 实现的是「请求头优先于 query」的 HTTP 约定,属接入层。放在 domain 包里,等于让领域模型知道 HTTP 头存在,违反「换掉 Web 框架业务模型零改动」。 + +P5 移到 `flow-engine-starter-api`,`OperatorIdentityTest` / `OperatorIdentityHeaderResolveTest` 随之迁移。 + +## 判定流程(提交前四问) + +1. **有没有新增 `(long id, String identity)` 签名?** 有 → 改传 `OperatorKey`。 +2. **有没有自己判断「是不是同一个人」?** 有 → 改 `OperatorKey#matches`。 +3. **有没有自己拼参与人键?** 有 → 改 `OperatorKey#key`。 +4. **有没有在方法体里读匹配模式?** 有 → 这条规则应下沉进键或判定模型。 + +四问全否,才算符合本契约。 + +## 分批改造 + +原则:**先收敛语义(纯委托、行为零变化),再改结构,最后类型化。** 每批独立可回滚。 + +| 批次 | 范围 | 行为变化 | 验收 | +|---|---|---|---| +| **P0**(本次) | 本文档 + 索引 + `AGENTS.md` / `CLAUDE.md` 一条指向 | 无(零代码) | 文档评审通过 | +| **P1 相等收敛** | `OperatorKey` 增 `matches`;`Policy#matches`、`Policy#sameOperator`、`OperatorManager`、`FlowOperatorLocalThreadCache#isIdentityMatched` 全部委托;`OperatorManager` 去掉默认身份重载 | 无 | 32 个身份相关测试类断言零修改 | +| **P2 键收敛** | `OperatorKey#key()` 成为唯一参与人键生成点;cache / guard / `FlowContent` 改用它;分隔符常量收敛为 1 份;新增待办合并键模型,`FlowRecord#getTodoKey()` 委托它 | 无(键值逐个比对) | `FlowTodoKeyIdentityTest`、`FlowOperatorBulkIdentityTest`、`FlowRecordIdentityConvertorTest` 零修改 | +| **P3 模式策略化** | `OperatorIdentityMatchMode` 实现 `match`;`OperatorIdentityPolicy` → `OperatorIdentityContext`;`reset()` → `use(mode)` | 无(`use` 仅影响测试写法) | `OperatorIdentityPolicyTest` 改名适配 | +| **P4 对象化** | `OperatorScriptResultResolver`(#308)、`OperatorAssignmentService` 改构造注入 | 无 | 见 #308 的 7 条契约 | +| **P5 类型化** | `OperatorIdentity` → 值对象;`pick` 移接入层;`Guard` 移出领域包 | 公开 API 变更,需版本说明 | 全量测试 + 集成方迁移说明 | + +**P1~P4 统一验收口径**:`./mvnw test` 全绿,且现有测试的**断言一行不改**。改断言等于改行为契约,必须单独说明理由。 + +## 禁止清单 + +- ❌ 新增静态工具类处理身份(回到 [模型设计三层法](../design/model-design.md) 的老问题) +- ❌ 业务类内联 `userId == ... && identity.equals(...)` +- ❌ 自行拼接参与人键 +- ❌ 在方法体里读 `matchMode()` 决定数据格式 +- ❌ 给 `OperatorManager` 补「默认身份」重载 +- ❌ 为测试暴露 `reset()` 这类静态状态清理方法(应通过构造注入或显式作用域隔离) + +## 关联 + +- 多身份引入 #288 · 参与人二元标识 #290 · 分配携带身份 #292 · 批量按身份回取 #293 · 身份透传告警 #294 · 匹配策略 #297 · 身份请求头 #301 · 脚本返回值多形态 #303 +- #308 解析器对象化(P4)· #309 存量盘点(本契约覆盖其中 4 项)· #310 模型设计三层法 diff --git a/docs/conventions/index.md b/docs/conventions/index.md index e3e83e9e..7d0ce111 100644 --- a/docs/conventions/index.md +++ b/docs/conventions/index.md @@ -6,8 +6,10 @@ | 名称 | 模块 | 描述 | 范围 | 来源 | |------|------|------|------|------| +| [design/model-design](./design/model-design.md) | design | 模型设计三层法 — 职责 → 抽象 → 实现;垂直按 DDD 分层(业务/数据/技术),水平按包/类/方法递归;以易维护与可验证为验收 | 通用 | 项目自有 | +| [domain/operator-identity](./domain/operator-identity.md) | domain | 多身份语义契约 — 参与人相等与参与人键各只有一个定义点;匹配模式只改判定不改存储键格式;P0~P5 分批收敛 | `com.codingapi.flow.operator` 及其调用方 | 项目自有 | | [workflow/github-issue](./workflow/github-issue.md) | workflow | GitHub Issue 标准处理流程 — 定位分析 → 回复 issue → worktree 修复 → 推送特性分支 → 推送后回复 | 通用 | 项目自有 | --- -**统计**: 共 1 篇 — 已实现 1 / 计划中 0 / 已废弃 0 +**统计**: 共 3 篇 — 已实现 3 / 计划中 0 / 已废弃 0 From 4e597cecdb14d611cd0978ad97585c3a4ee9db3c Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Thu, 3 Dec 2026 17:50:47 +0800 Subject: [PATCH 27/35] =?UTF-8?q?refactor(operator):=20=E5=8F=82=E4=B8=8E?= =?UTF-8?q?=E4=BA=BA=E5=88=A4=E5=AE=9A=E4=B8=8E=E5=8F=82=E4=B8=8E=E4=BA=BA?= =?UTF-8?q?=E9=94=AE=E6=94=B6=E6=95=9B=E5=88=B0=20OperatorKey?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P1 相等收敛: - OperatorKey 新增 matches(key, mode) / identityEquals(identity) / of(IFlowOperator) - OperatorIdentityMatchMode 由「被外部 if 判断的枚举」改为策略,自己实现 match 与 identityDistinguishes - OperatorIdentityPolicy#matches/sameOperator 改为委托,删除重复的 id+身份比较逻辑 - OperatorManager 去掉 getOperator(long) / getOperator(long,String) 两个重叠重载,收为一个 match(IFlowOperator) - FlowOperatorLocalThreadCache#isIdentityMatched 改为委托 identityEquals P2 键收敛(参与人键部分): - OperatorKey#key() 成为唯一键生成点,分隔符常量收敛为 1 份(改为 U+0001,身份不可能包含) - OperatorKey#key(mode) 承接「模式是否区分身份」,调用方不再自行判断模式后拼键 - 缓存键、身份告警去重键、当前节点待审批人去重键全部改用 OperatorKey - 删除 4 份重复的分隔符声明(cache/guard/todoKey/FlowContent 各自一份) 行为零变化:现有身份相关测试断言未修改。 Refs #311 --- .../cache/FlowOperatorLocalThreadCache.java | 15 ++- .../flow/manager/OperatorManager.java | 62 ++++++------ .../flow/operator/OperatorIdentityGuard.java | 5 +- .../operator/OperatorIdentityMatchMode.java | 58 +++++++++-- .../flow/operator/OperatorIdentityPolicy.java | 36 ++++--- .../codingapi/flow/operator/OperatorKey.java | 79 ++++++++++++++- .../flow/pojo/response/FlowContent.java | 12 +-- .../flow/manager/OperatorManagerTest.java | 76 ++++++++++++++ .../flow/operator/OperatorKeyTest.java | 98 +++++++++++++++++++ 9 files changed, 369 insertions(+), 72 deletions(-) create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/manager/OperatorManagerTest.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorKeyTest.java diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java b/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java index 79a247c0..a822455a 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java @@ -2,6 +2,7 @@ import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorKey; import lombok.Getter; import java.util.ArrayList; @@ -21,11 +22,6 @@ */ public class FlowOperatorLocalThreadCache { - /** - * userId 与 identity 之间的分隔符;使用不可见控制字符,避免与业务身份标识冲突 - */ - private static final String KEY_SEPARATOR = "\u0001"; - private final ThreadLocal> cache; private FlowOperatorLocalThreadCache() { @@ -36,10 +32,13 @@ private FlowOperatorLocalThreadCache() { private final static FlowOperatorLocalThreadCache instance = new FlowOperatorLocalThreadCache(); /** - * 拼装缓存键,身份统一归一化,保证 {@code null} 与空串命中同一条缓存 + * 拼装缓存键。 + * + *

    键格式由 {@link OperatorKey#key()} 唯一定义:缓存键就是参与人键, + * 本类不再自己声明分隔符,也不自己做归一化。 */ private static String cacheKey(long userId, String identity) { - return userId + KEY_SEPARATOR + OperatorIdentity.normalize(identity); + return OperatorKey.of(userId, identity).key(); } public void clear() { @@ -106,7 +105,7 @@ private static boolean isIdentityMatched(IFlowOperator operator, String requeste if (OperatorIdentity.isDefault(requestedIdentity)) { return true; } - return OperatorIdentity.same(OperatorIdentity.of(operator), requestedIdentity); + return OperatorKey.of(operator).identityEquals(requestedIdentity); } /** diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/manager/OperatorManager.java b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/OperatorManager.java index e23960c7..8b21db2b 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/manager/OperatorManager.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/OperatorManager.java @@ -1,30 +1,47 @@ package com.codingapi.flow.manager; import com.codingapi.flow.operator.IFlowOperator; -import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorKey; import lombok.Getter; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; import java.util.Objects; +import java.util.Set; /** - * 节点操作者管理 + * 节点操作者管理(参与人集合)。 * *

    参与人由 {@code (userId, identity)} 共同标识(issue #288):同一个人员的两个身份 - * 是两个不同的参与人,匹配与查找都必须带上身份。身份为空时与历史「只比 userId」等价。 + * 是两个不同的参与人,查找必须带上身份。身份为空时与历史「只比 userId」等价。 + * + *

    集合语义只有两个动作:构建时把列表归一化为 {@link OperatorKey} 集合, + * 查询时判断「某人是否在集合中」。因此只有一个公有查询入口 + * {@link #match(IFlowOperator)},不再提供「按 id 查、按 id + 身份查」这类互相重叠的重载—— + * 那会让调用方每次都要先做一次选择。 */ public class OperatorManager { @Getter private final List operators; + /** + * 参与人索引,用于 O(1) 判定 + */ + private final Set keys; + public OperatorManager(List operators) { - if(operators!=null && !operators.isEmpty()) { + if (operators != null && !operators.isEmpty()) { this.operators = operators.stream().filter(Objects::nonNull).toList(); - }else { + } else { this.operators = new ArrayList<>(); } + Set keySet = new HashSet<>(this.operators.size()); + for (IFlowOperator operator : this.operators) { + keySet.add(OperatorKey.of(operator)); + } + this.keys = keySet; } public boolean isEmpty() { @@ -32,36 +49,19 @@ public boolean isEmpty() { } /** - * 判断操作者是否在节点配置的操作者列表中(按 userId + identity 匹配) + * 判断操作者是否在节点配置的操作者列表中。 + * + *

    按 {@code (userId, identity)} 严格匹配,不受运行时匹配模式影响: + * 这里回答的是「节点配置的人里有没有他」。配置项本身就是「某个人以某个身份参与」, + * 放宽到只比 id 会让「配置了部门A的张三」被部门B的张三命中,属于越权。 + * + * @param operator 待判定的操作者 + * @return true 表示在配置的参与人集合中 */ public boolean match(IFlowOperator operator) { if (operator == null) { return false; } - return this.getOperator(operator.getUserId(), OperatorIdentity.of(operator)) != null; - } - - /** - * 按人员 id 查找操作者(默认身份) - */ - public IFlowOperator getOperator(long userId) { - return this.getOperator(userId, OperatorIdentity.DEFAULT); - } - - /** - * 按 {@code (userId, identity)} 查找操作者 - * - * @param userId 人员 id - * @param identity 身份标识,{@code null} 与空串等价 - * @return 匹配的操作者,不存在时返回 {@code null} - */ - public IFlowOperator getOperator(long userId, String identity) { - for (IFlowOperator operator : operators) { - if (operator.getUserId() == userId - && OperatorIdentity.same(OperatorIdentity.of(operator), identity)) { - return operator; - } - } - return null; + return keys.contains(OperatorKey.of(operator)); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityGuard.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityGuard.java index 4d212a15..7af189c8 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityGuard.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityGuard.java @@ -22,8 +22,6 @@ public final class OperatorIdentityGuard { */ private static final int MAX_WARN_KEYS = 256; - private static final String KEY_SEPARATOR = "\u0001"; - private static final Set WARNED_KEYS = ConcurrentHashMap.newKeySet(); private OperatorIdentityGuard() { @@ -44,7 +42,8 @@ public static boolean check(long operatorId, String requestedIdentity, IFlowOper if (WARNED_KEYS.size() >= MAX_WARN_KEYS) { return false; } - String key = operatorId + KEY_SEPARATOR + OperatorIdentity.normalize(requestedIdentity); + // 去重键就是参与人键,格式由 OperatorKey 唯一定义 + String key = OperatorKey.of(operatorId, requestedIdentity).key(); if (!WARNED_KEYS.add(key)) { return false; } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityMatchMode.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityMatchMode.java index 08db9d83..0de16f34 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityMatchMode.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityMatchMode.java @@ -1,32 +1,76 @@ package com.codingapi.flow.operator; /** - * 身份参与「办理权限」判定的模式(issue #297)。 + * 身份参与「参与人判定」的模式(issue #297)。 * *

    身份的本质作用是给流程脚本提供上下文(例如 a 身份对应的领导是 L1、b 身份对应 L2), * 并在流程记录上留痕。它不应该成为「同一个人能否办理自己待办」的拦路石,因此把 - * 「身份是否参与权限判定」抽成可配置项: + * 「身份是否参与参与人判定」抽成可配置项。 + * + *

    本枚举是策略:判定行为由各常量自己回答({@link #match(OperatorKey, OperatorKey)}、 + * {@link #identityDistinguishes()}),调用方不得用 {@code if (mode == ...)} 再分支, + * 否则新增一种模式就要改动所有使用者。 *

      - *
    • {@link #STRICT}:{@code userId + identity} 必须同时一致才允许办理(issue #288 的语义,框架默认);
    • + *
    • {@link #STRICT}:{@code userId + identity} 必须同时一致(issue #288 的语义,框架默认);
    • *
    • {@link #USER_ONLY}:只校验 {@code userId},身份仅用于脚本执行与留痕(推荐业务默认)。
    • *
    * *

    模式由 starter 通过 {@code codingapi.flow.identity.match-mode} 配置,并在启动时写入 - * {@link OperatorIdentityPolicy},框架内部所有涉及「能否办理」的判断统一读取该策略。 + * {@link OperatorIdentityContext},框架内部所有涉及「是否同一参与人」的判断统一读取该策略。 * - * @see OperatorIdentityPolicy + * @see OperatorIdentityContext */ public enum OperatorIdentityMatchMode { /** * 严格模式:人员与身份都必须匹配。 */ - STRICT, + STRICT { + @Override + public boolean match(OperatorKey left, OperatorKey right) { + return left.operatorId() == right.operatorId() + && left.identityEquals(right.identity()); + } + + @Override + public boolean identityDistinguishes() { + return true; + } + }, /** * 仅人员模式:只要求是同一个人,不限制其当前身份。 */ - USER_ONLY; + USER_ONLY { + @Override + public boolean match(OperatorKey left, OperatorKey right) { + return left.operatorId() == right.operatorId(); + } + + @Override + public boolean identityDistinguishes() { + return false; + } + }; + + /** + * 判断两个参与人标识是否为同一参与人。 + * + * @param left 参与人标识 + * @param right 参与人标识 + * @return true 表示同一参与人 + */ + public abstract boolean match(OperatorKey left, OperatorKey right); + + /** + * 身份是否区分参与人。 + * + *

    该判定决定「参与人键」与「待办合并键」是否携带身份后缀,是键模型的唯一入参, + * 调用方不得自行按模式拼键。 + * + * @return true 表示参与人由 {@code (人员id, 身份)} 共同标识 + */ + public abstract boolean identityDistinguishes(); /** * 宽松解析配置值,兼容 {@code USER_ONLY}、{@code user-only}、{@code user_only} 等写法。 diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityPolicy.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityPolicy.java index 0daaeb7e..959f68b2 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityPolicy.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityPolicy.java @@ -4,9 +4,12 @@ * 身份匹配策略(issue #297)。 * *

    所有「当前用户能否办理/撤回/催办/减签某条流程记录」的判断都必须经过本类, - * 禁止在业务代码里直接写 {@code userId == ... && OperatorIdentity.same(...)}, + * 禁止在业务代码里直接写 {@code userId == ... && identity.equals(...)}, * 否则会出现「能审批但不能撤回」「同人换身份被误记为干预」这类半开状态。 * + *

    判定逻辑本身不在这里:由 {@link OperatorKey#matches(OperatorKey, OperatorIdentityMatchMode)} + * 回答,本类只负责「持有当前模式 + 把模式传下去」。比较逻辑只有一份定义点。 + * *

    默认 {@link OperatorIdentityMatchMode#STRICT},由 starter 在启动时按配置覆盖 * ({@code codingapi.flow.identity.match-mode},starter 侧默认 {@code USER_ONLY})。 * 只使用 framework 的接入方不配置时保持历史行为。 @@ -48,8 +51,8 @@ public static void reset() { /** * 当前用户是否就是记录上的参与人(可办理该记录)。 * - * @param current 当前操作者 - * @param recordOperatorId 记录上的参与人 id + * @param current 当前操作者 + * @param recordOperatorId 记录上的参与人 id * @param recordOperatorIdentity 记录上的参与人身份 * @return true 表示允许办理 */ @@ -57,14 +60,14 @@ public static boolean matches(IFlowOperator current, long recordOperatorId, Stri if (current == null) { return false; } - return matches(current.getUserId(), OperatorIdentity.of(current), recordOperatorId, recordOperatorIdentity); + return matches(OperatorKey.of(current), OperatorKey.of(recordOperatorId, recordOperatorIdentity)); } /** * 判断两个 {@code (id, identity)} 是否代表同一个参与人。 * - *

    {@link OperatorIdentityMatchMode#USER_ONLY} 下只比较 id;{@link OperatorIdentityMatchMode#STRICT} - * 下要求 id 与身份同时一致。 + *

    判定本身由 {@link OperatorKey#matches(OperatorKey, OperatorIdentityMatchMode)} 回答, + * 本方法只负责把「当前生效的模式」传下去,不重复实现比较逻辑。 * * @param currentOperatorId 当前操作者 id * @param currentOperatorIdentity 当前操作者身份 @@ -76,13 +79,22 @@ public static boolean matches(long currentOperatorId, String currentOperatorIdentity, long recordOperatorId, String recordOperatorIdentity) { - if (currentOperatorId != recordOperatorId) { + return matches(OperatorKey.of(currentOperatorId, currentOperatorIdentity), + OperatorKey.of(recordOperatorId, recordOperatorIdentity)); + } + + /** + * 按当前模式判定两个参与人标识是否同一参与人。 + * + * @param left 参与人标识 + * @param right 参与人标识 + * @return true 表示同一参与人 + */ + public static boolean matches(OperatorKey left, OperatorKey right) { + if (left == null) { return false; } - if (matchMode == OperatorIdentityMatchMode.USER_ONLY) { - return true; - } - return OperatorIdentity.same(currentOperatorIdentity, recordOperatorIdentity); + return left.matches(right, matchMode); } /** @@ -99,6 +111,6 @@ public static boolean sameOperator(IFlowOperator left, IFlowOperator right) { if (left == null || right == null) { return false; } - return matches(left.getUserId(), OperatorIdentity.of(left), right.getUserId(), OperatorIdentity.of(right)); + return matches(OperatorKey.of(left), OperatorKey.of(right)); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java index 308b4942..42df0d25 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java @@ -6,13 +6,31 @@ *

    同一个人员可以以不同身份参与流程,因此凡是「指向某个参与人」的持久化数据或批量参数, * 都不能只保存人员 id。该类型用于人员分配(发起人设定 / 审批人设定)等需要显式携带身份的场景。 * - *

    身份统一经 {@link OperatorIdentity#normalize(String)} 归一化,{@code null} 与空串等价。 + *

    本类是「参与人」这一概念的唯一载体(见 {@code docs/conventions/domain/operator-identity.md}): + *

      + *
    • {@link #matches(OperatorKey, OperatorIdentityMatchMode)} —— 「是否同一个人」的唯一判定入口;
    • + *
    • {@link #key(OperatorIdentityMatchMode)} —— 参与人键(缓存键 / Map 键 / 去重键)的唯一生成点;
    • + *
    • {@link #identityEquals(String)} —— 身份相等的唯一判定入口。
    • + *
    + * 禁止在业务代码里内联 {@code userId == ... && identity.equals(...)},也禁止自行拼接参与人键。 + * + *

    身份统一经 {@link OperatorIdentity#normalize(String)} 归一化,{@code null} 与空串等价; + * 归一化在紧凑构造中完成,因此 {@link #equals(Object)} 即是「严格口径下是否为同一参与人」。 * * @param operatorId 人员 id * @param identity 身份标识(默认身份为空串) */ public record OperatorKey(long operatorId, String identity) { + /** + * 参与人键中人员 id 与身份的分隔符。 + * + *

    选用不可见控制字符:身份来自请求头,可能未经 {@link OperatorIdentity#validate(String)} 校验, + * 因此键的分隔符必须取「业务身份永远不可能包含」的字符,避免 {@code (1,"a#b")} 与 {@code (1,"a")} 撞键。 + * 该常量是本仓库唯一的分隔符声明,其它类不得再声明自己的分隔符。 + */ + static final String KEY_SEPARATOR = "\u0001"; + /** * 紧凑构造:身份统一归一化,保证 {@code null} 与空串等价 */ @@ -42,11 +60,64 @@ public static OperatorKey ofDefault(long operatorId) { } /** - * 组装可直接用于比较 / 缓存键的字符串 + * 由流程参与人构建操作者标识 + * + * @param operator 流程参与人,不能为空 + * @return 操作者标识 + */ + public static OperatorKey of(IFlowOperator operator) { + return new OperatorKey(operator.getUserId(), operator.getIdentity()); + } + + /** + * 判断是否为同一个参与人(唯一的「同一个人」判定入口)。 + * + *

    口径由匹配模式决定:{@link OperatorIdentityMatchMode#STRICT} 要求人员与身份同时一致; + * {@link OperatorIdentityMatchMode#USER_ONLY} 只比较人员 id。 + * + * @param other 另一个参与人标识 + * @param mode 匹配模式 + * @return true 表示同一参与人 + */ + public boolean matches(OperatorKey other, OperatorIdentityMatchMode mode) { + if (other == null) { + return false; + } + return mode.match(this, other); + } + + /** + * 身份是否等于给定值(唯一的身份相等入口,与人员 id 无关)。 + * + * @param otherIdentity 待比较的身份,{@code null} 与空串等价 + * @return true 表示同一身份 + */ + public boolean identityEquals(String otherIdentity) { + return identity.equals(OperatorIdentity.normalize(otherIdentity)); + } + + /** + * 参与人键(缓存键 / Map 键 / 去重键的唯一生成点,严格口径)。 * - * @return {@code 人员id + '#' + 身份} + * @return {@code 人员id + 分隔符 + 身份} */ public String key() { - return operatorId + OperatorIdentity.KEY_SEPARATOR + identity; + return key(OperatorIdentityMatchMode.STRICT); + } + + /** + * 按匹配模式生成参与人键。 + * + *

    {@link OperatorIdentityMatchMode#USER_ONLY} 下同一个人只算一个参与人,键退化为人员 id; + * 严格口径下按 {@code (人员id, 身份)} 区分。调用方不得自行判断模式后拼键。 + * + * @param mode 匹配模式 + * @return 参与人键 + */ + public String key(OperatorIdentityMatchMode mode) { + if (!mode.identityDistinguishes()) { + return String.valueOf(operatorId); + } + return operatorId + KEY_SEPARATOR + identity; } } 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 33c3f168..1be462fb 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 @@ -8,9 +8,8 @@ import com.codingapi.flow.manager.NodeStrategyManager; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; -import com.codingapi.flow.operator.OperatorIdentity; -import com.codingapi.flow.operator.OperatorIdentityMatchMode; import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.workflow.Workflow; @@ -341,11 +340,10 @@ static List resolveCurrentNodeOperators(FlowRecord currentRecord, record.getCurrentOperatorId(), record.getCurrentOperatorIdentity())) { continue; } - // USER_ONLY 下同一个人只展示一次;STRICT 下按 (人员id, 身份) 区分 - String operatorKey = OperatorIdentityPolicy.matchMode() == OperatorIdentityMatchMode.USER_ONLY - ? String.valueOf(record.getCurrentOperatorId()) - : record.getCurrentOperatorId() + OperatorIdentity.KEY_SEPARATOR - + OperatorIdentity.normalize(record.getCurrentOperatorIdentity()); + // 去重键就是参与人键:USER_ONLY 下同一个人只展示一次,STRICT 下按 (人员id, 身份) 区分。 + // 键格式由 OperatorKey 唯一定义,这里不再判断模式后自行拼接。 + String operatorKey = OperatorKey.of(record.getCurrentOperatorId(), + record.getCurrentOperatorIdentity()).key(OperatorIdentityPolicy.matchMode()); operators.putIfAbsent(operatorKey, new FlowOperator(record.getCurrentOperatorId(), record.getCurrentOperatorName(), record.getCurrentOperatorIdentity())); diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/manager/OperatorManagerTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/manager/OperatorManagerTest.java new file mode 100644 index 00000000..beb69dcf --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/manager/OperatorManagerTest.java @@ -0,0 +1,76 @@ +package com.codingapi.flow.manager; + +import com.codingapi.flow.operator.OperatorIdentityMatchMode; +import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 参与人集合测试(#311 P1)。 + * + *

    锁住一条容易被误改的语义:配置匹配不随运行时匹配模式放宽。 + * 节点配置的是「某个人以某个身份参与」,如果把 USER_ONLY 也套到配置匹配上, + * 「配置了部门A的张三」会被部门B的张三命中,属于越权。 + */ +class OperatorManagerTest { + + @AfterEach + void tearDown() { + OperatorIdentityPolicy.reset(); + } + + @Test + void should_match_by_user_and_identity() { + OperatorManager manager = new OperatorManager(List.of(User.withIdentity(1, "user1", "department1"))); + + assertTrue(manager.match(User.withIdentity(1, "user1", "department1"))); + assertFalse(manager.match(User.withIdentity(1, "user1", "department2"))); + assertFalse(manager.match(User.withIdentity(2, "boss", "department1"))); + } + + @Test + void should_match_default_identity_equivalently_for_null_and_blank() { + OperatorManager manager = new OperatorManager(List.of(new User(1, "user1"))); + + assertTrue(manager.match(User.withIdentity(1, "user1", null))); + assertTrue(manager.match(User.withIdentity(1, "user1", ""))); + assertFalse(manager.match(User.withIdentity(1, "user1", "department1"))); + } + + @Test + void should_not_widen_config_matching_in_user_only_mode() { + OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + OperatorManager manager = new OperatorManager(List.of(User.withIdentity(1, "user1", "department1"))); + + assertTrue(manager.match(User.withIdentity(1, "user1", "department1"))); + assertFalse(manager.match(User.withIdentity(1, "user1", "department2")), + "配置匹配按严格口径,运行时模式不得放宽"); + } + + @Test + void should_ignore_null_operator_and_null_list() { + assertFalse(new OperatorManager(null).match(User.withIdentity(1, "user1", "department1"))); + assertFalse(new OperatorManager(List.of()).match(User.withIdentity(1, "user1", "department1"))); + assertTrue(new OperatorManager(null).isEmpty()); + } + + @Test + void should_filter_null_operators_from_source_list() { + List source = new ArrayList<>(); + source.add(null); + source.add(User.withIdentity(1, "user1", "department1")); + source.add(null); + + OperatorManager manager = new OperatorManager(source); + + assertTrue(manager.isEmpty() == false); + assertTrue(manager.match(User.withIdentity(1, "user1", "department1"))); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorKeyTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorKeyTest.java new file mode 100644 index 00000000..f0e731f0 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorKeyTest.java @@ -0,0 +1,98 @@ +package com.codingapi.flow.operator; + +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.Test; + +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.assertTrue; + +/** + * 参与人标识测试:锁住「同一参与人判定」与「参与人键」的唯一真源 + * (issue #297 / #311 P1、P2)。 + * + *

    断言的是契约而非实现:无论判定逻辑将来挪到哪,这些行为都必须成立。 + */ +class OperatorKeyTest { + + @Test + void should_judge_same_identity_as_same_participant_in_strict_mode() { + OperatorKey department1 = OperatorKey.of(1, "department1"); + + assertTrue(department1.matches(OperatorKey.of(1, "department1"), OperatorIdentityMatchMode.STRICT)); + assertFalse(department1.matches(OperatorKey.of(1, "department2"), OperatorIdentityMatchMode.STRICT), + "严格口径下同一人员的不同身份是两个参与人"); + assertFalse(department1.matches(OperatorKey.of(2, "department1"), OperatorIdentityMatchMode.STRICT), + "身份相同但人员不同,不是同一参与人"); + } + + @Test + void should_judge_same_user_as_same_participant_in_user_only_mode() { + OperatorKey department1 = OperatorKey.of(1, "department1"); + + assertTrue(department1.matches(OperatorKey.of(1, "department2"), OperatorIdentityMatchMode.USER_ONLY)); + assertFalse(department1.matches(OperatorKey.of(2, "department1"), OperatorIdentityMatchMode.USER_ONLY)); + } + + @Test + void should_treat_null_and_blank_identity_as_default() { + OperatorKey expected = OperatorKey.ofDefault(1); + + assertEquals(expected, OperatorKey.of(1, null)); + assertEquals(expected, OperatorKey.of(1, "")); + assertTrue(expected.matches(OperatorKey.of(1, null), OperatorIdentityMatchMode.STRICT)); + } + + @Test + void should_return_false_when_matching_null_participant() { + assertFalse(OperatorKey.ofDefault(1).matches(null, OperatorIdentityMatchMode.STRICT)); + assertFalse(OperatorKey.ofDefault(1).matches(null, OperatorIdentityMatchMode.USER_ONLY)); + } + + @Test + void should_build_participant_from_operator() { + User user = User.withIdentity(7, "user7", "department3"); + + OperatorKey key = OperatorKey.of(user); + + assertEquals(7, key.operatorId()); + assertEquals("department3", key.identity()); + } + + @Test + void should_compare_identity_independently_of_user_id() { + OperatorKey key = OperatorKey.of(1, "department1"); + + assertTrue(key.identityEquals("department1")); + assertFalse(key.identityEquals(null), "非默认身份不应等于默认身份"); + assertTrue(OperatorKey.ofDefault(2).identityEquals(null)); + assertTrue(OperatorKey.ofDefault(2).identityEquals("")); + } + + @Test + void should_generate_distinct_keys_per_participant_in_strict_mode() { + String department1 = OperatorKey.of(1, "department1").key(); + String department2 = OperatorKey.of(1, "department2").key(); + + assertNotEquals(department1, department2, "严格口径下两个身份必须是两个键"); + assertEquals(department1, OperatorKey.of(1, "department1").key()); + } + + @Test + void should_collapse_identity_in_join_key_when_mode_ignores_identity() { + assertEquals(OperatorKey.of(1, "department1").key(OperatorIdentityMatchMode.USER_ONLY), + OperatorKey.of(1, "department2").key(OperatorIdentityMatchMode.USER_ONLY), + "仅人员模式下同一个人只应有一个键"); + assertEquals("1", OperatorKey.of(1, "department1").key(OperatorIdentityMatchMode.USER_ONLY)); + } + + @Test + void should_not_collide_when_identity_contains_key_like_characters() { + // 键分隔符必须是「业务身份不可能包含」的字符。身份若含普通分隔符(- 或 #), + // 拼出来的键不能与另一个参与人的键相同,否则缓存与去重会互相污染。 + assertNotEquals(OperatorKey.of(1, "a#b").key(), OperatorKey.of(1, "a").key()); + assertNotEquals(OperatorKey.of(1, "a-b").key(), OperatorKey.of(1, "a").key()); + assertNotEquals(OperatorKey.of(1, "").key(), OperatorKey.of(1, "a").key()); + } +} From 352c114883a2bd7a3c3974eb809f3a2735461258 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Thu, 3 Dec 2026 17:52:13 +0800 Subject: [PATCH 28/35] =?UTF-8?q?refactor(record):=20=E5=BE=85=E5=8A=9E?= =?UTF-8?q?=E5=90=88=E5=B9=B6=E9=94=AE=E6=8A=BD=E5=87=BA=20TodoMergeKey?= =?UTF-8?q?=EF=BC=8C=E9=94=AE=E6=A0=BC=E5=BC=8F=E5=8F=AA=E6=9C=89=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E5=AE=9A=E4=B9=89=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 record/TodoMergeKey:基础段 {人员id}-{workRuntimeId}-{nodeId} 不可变, 严格模式且身份非默认时追加 #identity,仅人员模式不追加 - FlowRecord#getTodoKey() 只保留「谁参与合并」的领域决策,键拼装委托 TodoMergeKey - 删除 FlowRecord 自declared 的 IDENTITY_KEY_SUFFIX 与手写 String.format 拼装 - OperatorIdentity.KEY_SEPARATOR 更名为 RESERVED_KEY_MARK,语义明确为「身份保留字符」, TodoMergeKey 引用同一常量 - 新增 TodoMergeKeyTest 锁住三种格式 Refs #311 --- .../flow/operator/OperatorIdentity.java | 13 ++-- .../com/codingapi/flow/record/FlowRecord.java | 39 +++-------- .../codingapi/flow/record/TodoMergeKey.java | 68 +++++++++++++++++++ .../flow/record/TodoMergeKeyTest.java | 63 +++++++++++++++++ 4 files changed, 147 insertions(+), 36 deletions(-) create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/record/TodoMergeKey.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/record/TodoMergeKeyTest.java diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java index 06ff49f4..cf1bc55a 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java @@ -30,11 +30,12 @@ public final class OperatorIdentity { public static final int MAX_LENGTH = 64; /** - * 待办合并键中用于拼接身份的分隔符。 + * 身份保留字符:供各类「身份参与拼接」的键格式使用(当前为待办合并键的身份后缀)。 * - *

    身份本身不允许包含该字符,否则「身份」与「合并键后缀」语义无法区分。 + *

    身份本身不允许包含该字符,否则「身份」与「键后缀」语义无法区分。 + * 该常量是本仓库唯一声明,键模型({@code TodoMergeKey})引用它,不再各自声明。 */ - public static final String KEY_SEPARATOR = "#"; + public static final String RESERVED_KEY_MARK = "#"; /** * 当前身份的请求头名称(issue #301)。 @@ -91,7 +92,7 @@ public static String normalize(String identity) { *

    约束: *

      *
    • 长度不超过 {@link #MAX_LENGTH},与 DDL 列宽一致;
    • - *
    • 不允许包含 {@link #KEY_SEPARATOR},否则与待办合并键的后缀语义冲突;
    • + *
    • 不允许包含 {@link #RESERVED_KEY_MARK},否则与待办合并键的后缀语义冲突;
    • *
    • 不允许包含控制字符,避免污染内部以控制字符拼接的缓存键。
    • *
    * @@ -104,8 +105,8 @@ public static String validate(String identity) { if (normalized.length() > MAX_LENGTH) { throw FlowValidationException.operatorIdentityTooLong(normalized.length(), MAX_LENGTH); } - if (normalized.contains(KEY_SEPARATOR)) { - throw FlowValidationException.operatorIdentityInvalid(KEY_SEPARATOR); + if (normalized.contains(RESERVED_KEY_MARK)) { + throw FlowValidationException.operatorIdentityInvalid(RESERVED_KEY_MARK); } for (int i = 0; i < normalized.length(); i++) { char c = normalized.charAt(i); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java index 785886a3..a2b30a2b 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java @@ -12,6 +12,7 @@ import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.operator.OperatorIdentityMatchMode; import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.session.FlowAdvice; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; @@ -50,7 +51,6 @@ public class FlowRecord { * 待办合并键中身份后缀的分隔符(issue #288)。 *

    仅在身份非空时追加,默认身份不使用,保证存量键格式不变。 */ - private static final String IDENTITY_KEY_SUFFIX = "#"; /** * 记录id @@ -347,37 +347,16 @@ public class FlowRecord { * 需要收拢时执行 {@code FlowTodoMigrateService} 重建待办快照即可。 */ public String getTodoKey() { - if (mergeable) { - long mergeOperatorId; - String mergeOperatorIdentity; - switch (mergeType) { - case CREATOR -> { - mergeOperatorId = createOperatorId; - mergeOperatorIdentity = createOperatorIdentity; - } - case SUBMITTER -> { - mergeOperatorId = submitOperatorId; - mergeOperatorIdentity = submitOperatorIdentity; - } - default -> { - mergeOperatorId = currentOperatorId; - mergeOperatorIdentity = currentOperatorIdentity; - } - } - String todoKey = String.format("%s-%s-%s", mergeOperatorId, workRuntimeId, nodeId); - // 按人合并:身份只是脚本与留痕信息,不参与合并键,否则同一人会出现多条待办 - if (OperatorIdentityPolicy.matchMode() == OperatorIdentityMatchMode.USER_ONLY) { - return todoKey; - } - String identity = OperatorIdentity.normalize(mergeOperatorIdentity); - // 默认身份保持历史键格式,保证升级过程中存量待办的合并关系不断裂 - if (identity.isEmpty()) { - return todoKey; - } - return todoKey + IDENTITY_KEY_SUFFIX + identity; - } else { + if (!mergeable) { return String.valueOf(id); } + // 「谁参与合并」是领域决策,留在这里;「键怎么拼」是键格式,交给 TodoMergeKey。 + OperatorKey mergeOperator = switch (mergeType) { + case CREATOR -> OperatorKey.of(createOperatorId, createOperatorIdentity); + case SUBMITTER -> OperatorKey.of(submitOperatorId, submitOperatorIdentity); + default -> OperatorKey.of(currentOperatorId, currentOperatorIdentity); + }; + return TodoMergeKey.of(mergeOperator, workRuntimeId, nodeId, OperatorIdentityPolicy.matchMode()).value(); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/record/TodoMergeKey.java b/flow-engine-framework/src/main/java/com/codingapi/flow/record/TodoMergeKey.java new file mode 100644 index 00000000..0b72d50d --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/record/TodoMergeKey.java @@ -0,0 +1,68 @@ +package com.codingapi.flow.record; + +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityMatchMode; +import com.codingapi.flow.operator.OperatorKey; + +/** + * 待办合并键(issue #295 / #311 P2)。 + * + *

    待办合并键是复合键:参与人 + 运行时实例 + 节点,与参与人键({@link OperatorKey#key()}) + * 不是同一个东西,因此单独成为一个模型,而不是在业务方法里手拼字符串。 + * + *

    本类是「待办合并键格式」的唯一定义点:格式规则(含是否追加身份后缀)全部收在这里, + * {@code FlowRecord#getTodoKey()} 与 {@code FlowTodoMigrateService} 都复用它。 + * 这样「拼法」与「迁移」才不会各自漂移——历史上模式切换导致合并组一分为二、 + * 需要重建快照,根因就是键格式散在业务代码里。 + * + *

    格式: + *

      + *
    • 基础段 {@code {人员id}-{workRuntimeId}-{nodeId}}(历史格式,不可变);
    • + *
    • {@link OperatorIdentityMatchMode#STRICT} 且身份非默认时追加 {@code #identity};
    • + *
    • 默认身份不追加,保证升级过程中存量待办的合并关系不断裂。
    • + *
    + * + * @param operator 参与人标识 + * @param workRuntimeId 流程运行时实例 id + * @param nodeId 节点 id + * @param mode 参与人判定模式,决定键是否区分身份 + */ +public record TodoMergeKey(OperatorKey operator, long workRuntimeId, String nodeId, OperatorIdentityMatchMode mode) { + + /** + * 基础段之间的分隔符 + */ + static final String SEGMENT_SEPARATOR = "-"; + + /** + * 构建待办合并键 + * + * @param operator 参与人标识 + * @param workRuntimeId 流程运行时实例 id + * @param nodeId 节点 id + * @param mode 参与人判定模式 + * @return 待办合并键 + */ + public static TodoMergeKey of(OperatorKey operator, long workRuntimeId, String nodeId, + OperatorIdentityMatchMode mode) { + return new TodoMergeKey(operator, workRuntimeId, nodeId, mode); + } + + /** + * 生成待办合并键字符串 + * + * @return 合并键 + */ + public String value() { + String base = operator.operatorId() + SEGMENT_SEPARATOR + workRuntimeId + SEGMENT_SEPARATOR + nodeId; + if (!mode.identityDistinguishes()) { + // 按人合并:身份只是脚本与留痕信息,参与合并会让同一人出现多条待办 + return base; + } + if (operator.identity().isEmpty()) { + // 默认身份保持历史键格式,保证存量待办不断裂 + return base; + } + return base + OperatorIdentity.RESERVED_KEY_MARK + operator.identity(); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/record/TodoMergeKeyTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/record/TodoMergeKeyTest.java new file mode 100644 index 00000000..aaf034a8 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/record/TodoMergeKeyTest.java @@ -0,0 +1,63 @@ +package com.codingapi.flow.record; + +import com.codingapi.flow.operator.OperatorIdentityMatchMode; +import com.codingapi.flow.operator.OperatorKey; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * 待办合并键测试(#311 P2)。 + * + *

    锁住三件事:基础段格式不可变、严格模式追加身份、仅人员模式不追加。 + */ +class TodoMergeKeyTest { + + @Test + void should_keep_historical_format_for_default_identity() { + String key = TodoMergeKey.of(OperatorKey.ofDefault(1), 100L, "node1", OperatorIdentityMatchMode.STRICT).value(); + + assertEquals("1-100-node1", key); + } + + @Test + void should_append_identity_suffix_in_strict_mode() { + String key = TodoMergeKey.of(OperatorKey.of(1, "department1"), 100L, "node1", + OperatorIdentityMatchMode.STRICT).value(); + + assertEquals("1-100-node1#department1", key); + } + + @Test + void should_not_append_identity_in_user_only_mode() { + String key = TodoMergeKey.of(OperatorKey.of(1, "department1"), 100L, "node1", + OperatorIdentityMatchMode.USER_ONLY).value(); + + assertEquals("1-100-node1", key); + } + + @Test + void should_merge_two_identities_into_one_key_only_when_mode_ignores_identity() { + TodoMergeKey department1 = TodoMergeKey.of(OperatorKey.of(1, "department1"), 100L, "node1", + OperatorIdentityMatchMode.USER_ONLY); + TodoMergeKey department2 = TodoMergeKey.of(OperatorKey.of(1, "department2"), 100L, "node1", + OperatorIdentityMatchMode.USER_ONLY); + + assertEquals(department1.value(), department2.value()); + + assertNotEquals( + TodoMergeKey.of(OperatorKey.of(1, "department1"), 100L, "node1", OperatorIdentityMatchMode.STRICT).value(), + TodoMergeKey.of(OperatorKey.of(1, "department2"), 100L, "node1", OperatorIdentityMatchMode.STRICT).value()); + } + + @Test + void should_distinguish_node_and_runtime() { + String base = TodoMergeKey.of(OperatorKey.ofDefault(1), 100L, "node1", OperatorIdentityMatchMode.STRICT).value(); + + assertNotEquals(base, + TodoMergeKey.of(OperatorKey.ofDefault(1), 101L, "node1", OperatorIdentityMatchMode.STRICT).value()); + assertNotEquals(base, + TodoMergeKey.of(OperatorKey.ofDefault(1), 100L, "node2", OperatorIdentityMatchMode.STRICT).value()); + } +} From 33a69ef7fe96c15480cb0d51bb4e22174c97593e Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Thu, 3 Dec 2026 17:55:35 +0800 Subject: [PATCH 29/35] =?UTF-8?q?refactor(operator):=20OperatorIdentityPol?= =?UTF-8?q?icy=20=E6=94=B9=E4=B8=BA=20OperatorIdentityContext=EF=BC=8C?= =?UTF-8?q?=E5=8C=B9=E9=85=8D=E6=A8=A1=E5=BC=8F=E7=AD=96=E7=95=A5=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P3 模式策略化: - OperatorIdentityPolicy → OperatorIdentityContext:它只持有当前模式并传递,判定逻辑不再复制一份 - 删除 reset()(测试专用静态清理),改为 use(mode),测试显式设定与还原 - 4 处「请求人 vs 记录当前办理人」的重复校验收敛为 FlowRecord#verifyOperator(OperatorKey) - 新增 FlowRecord#currentOperatorKey(),调用方不再把 (id, identity) 拆开传 - 8 个调用点改为 OperatorKey + Context,方法体里不再有 if (mode == USER_ONLY) - starter: OperatorIdentityPolicyRegister → OperatorIdentityConfigurer 行为零变化:framework 全量 539 个测试通过。 Refs #311 --- .../flow/action/actions/AddAuditAction.java | 9 +- .../action/actions/ReduceAuditAction.java | 13 +- .../flow/manager/WorkflowStrategyManager.java | 9 +- .../codingapi/flow/node/BaseAuditNode.java | 11 +- .../operator/OperatorIdentityContext.java | 88 +++++++++++++ .../flow/operator/OperatorIdentityPolicy.java | 116 ------------------ .../flow/pojo/response/FlowContent.java | 11 +- .../com/codingapi/flow/record/FlowRecord.java | 38 +++++- .../flow/service/impl/FlowDeleteService.java | 7 +- .../flow/service/impl/FlowRevokeService.java | 7 +- .../impl/FlowSubProcessResetService.java | 9 +- .../flow/service/impl/FlowUrgeService.java | 13 +- .../flow/manager/OperatorManagerTest.java | 6 +- .../operator/OperatorIdentityContextTest.java | 90 ++++++++++++++ .../operator/OperatorIdentityPolicyTest.java | 63 ---------- .../FlowSubProcessResetServiceTest.java | 6 +- .../HandleOperatorIdentityFlowTest.java | 6 +- .../service/OperatorIdentityBoundaryTest.java | 18 +-- ...peratorIdentityUserOnlyPermissionTest.java | 6 +- .../com/codingapi/flow/AutoConfiguration.java | 6 +- .../flow/properties/FlowProperties.java | 2 +- ...r.java => OperatorIdentityConfigurer.java} | 15 ++- .../flow/properties/FlowPropertiesTest.java | 12 +- 23 files changed, 294 insertions(+), 267 deletions(-) create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityContext.java delete mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityPolicy.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityContextTest.java delete mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityPolicyTest.java rename flow-engine-starter/src/main/java/com/codingapi/flow/register/{OperatorIdentityPolicyRegister.java => OperatorIdentityConfigurer.java} (50%) diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/AddAuditAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/AddAuditAction.java index 933299f9..ded008cf 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/AddAuditAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/AddAuditAction.java @@ -12,7 +12,8 @@ import com.codingapi.flow.manager.OperatorManager; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; -import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorIdentityContext; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.script.node.OperatorLoadScript; import com.codingapi.flow.session.FlowSession; @@ -145,7 +146,7 @@ public void run(FlowSession flowSession) { *

    待办队列指当前节点实例中尚未办理的审批记录:包括顺序审批里尚未激活的隐藏记录 * (它们后续会按序号激活为待办),但不包括已办、已撤销以及已结束流程的记录。 * - *

    「是否已存在」统一由 {@link OperatorIdentityPolicy} 判定(issue #295): + *

    「是否已存在」统一由 {@link OperatorIdentityContext} 判定(issue #295): * 严格模式下同一人的另一身份是独立参与人,可以加签;仅按人员模式下同一个人已经待办, * 再加签只会给自己多生成一条重复待办,因此拒绝。 * @@ -162,8 +163,8 @@ private void verifyNotInTodoQueue(FlowSession flowSession, List a } for (IFlowOperator auditOperator : auditOperators) { boolean alreadyPending = pendingRecords.stream().anyMatch(record -> - OperatorIdentityPolicy.matches(auditOperator, - record.getCurrentOperatorId(), record.getCurrentOperatorIdentity())); + OperatorIdentityContext.getInstance() + .matches(OperatorKey.of(auditOperator), record.currentOperatorKey())); if (alreadyPending) { throw FlowExecutionException.addAuditOperatorAlreadyInTodo(auditOperator.getUserId()); } 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 14391dbf..3e248d2a 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 @@ -14,7 +14,8 @@ import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; -import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorIdentityContext; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.script.node.OperatorLoadScript; import com.codingapi.flow.session.FlowSession; @@ -174,16 +175,16 @@ private List resolveTargetRecords(List targets, long targetOperatorId = target.getUserId(); String targetOperatorIdentity = OperatorIdentity.of(target); // 自己不能被自己减签:按身份匹配策略判断(USER_ONLY 下同人换身份仍视为自己) - if (OperatorIdentityPolicy.matches(target, currentRecord.getCurrentOperatorId(), - currentRecord.getCurrentOperatorIdentity())) { + if (OperatorIdentityContext.getInstance() + .matches(OperatorKey.of(target), currentRecord.currentOperatorKey())) { throw FlowExecutionException.reduceAuditOwnRecord(); } // 减签的生效范围同样由策略决定:STRICT 下按「人 + 身份」,USER_ONLY 下按「人」 List matchedRecords = currentNodeRecords.stream() .filter(FlowRecord::isPendingApproval) - .filter(record -> OperatorIdentityPolicy.matches( - targetOperatorId, targetOperatorIdentity, - record.getCurrentOperatorId(), record.getCurrentOperatorIdentity())) + .filter(record -> OperatorIdentityContext.getInstance() + .matches(OperatorKey.of(targetOperatorId, targetOperatorIdentity), + record.currentOperatorKey())) .toList(); if (matchedRecords.isEmpty()) { throw FlowExecutionException.reduceAuditTargetNotFound(targetOperatorId); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java index d8082837..aa94fb90 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java @@ -3,7 +3,8 @@ import com.codingapi.flow.exception.FlowStateException; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; -import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorIdentityContext; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.strategy.workflow.IWorkflowStrategy; import com.codingapi.flow.strategy.workflow.InterfereStrategy; import lombok.AllArgsConstructor; @@ -59,7 +60,7 @@ public void verifyOperator(IFlowOperator currentOperator, long recordOperatorId) /** * 验证操作者。 * - *

    是否要求身份一致由 {@link OperatorIdentityPolicy} 决定(issue #297): + *

    是否要求身份一致由 {@link OperatorIdentityContext} 决定(issue #297): *

      *
    • {@code STRICT}:参与人由 {@code (userId, identity)} 共同决定(issue #288);
    • *
    • {@code USER_ONLY}:只校验 userId,同一人换身份依然可以办理自己的待办。
    • @@ -70,7 +71,9 @@ public void verifyOperator(IFlowOperator currentOperator, long recordOperatorId) * @param recordOperatorIdentity 记录操作者身份标识,{@code null} 与空串等价 */ public void verifyOperator(IFlowOperator currentOperator, long recordOperatorId, String recordOperatorIdentity) { - boolean operatorMatched = OperatorIdentityPolicy.matches(currentOperator, recordOperatorId, recordOperatorIdentity); + OperatorKey currentKey = currentOperator == null ? null : OperatorKey.of(currentOperator); + boolean operatorMatched = OperatorIdentityContext.getInstance() + .matches(currentKey, OperatorKey.of(recordOperatorId, recordOperatorIdentity)); if (!this.isEnableInterfere()) { if (!operatorMatched) { throw FlowStateException.operatorNotMatch(); 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 edfccef6..3b2fc1f9 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 @@ -12,7 +12,8 @@ import com.codingapi.flow.manager.OperatorManager; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; -import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorIdentityContext; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.strategy.node.MultiOperatorAuditStrategy; @@ -272,14 +273,16 @@ private List generateCurrentRecords(FlowSession session, Set // 即当前节点待办记录"处理(resetAddAudit、先清后存等),自动通过的留痕记录落库/事件副作用会破坏其语义。 if (nodeStrategyManager.isSameOperatorAutoPass() && session.getCurrentOperator() != null - && OperatorIdentityPolicy.matches(session.getCurrentOperator(), - session.getSubmitOperatorId(), OperatorIdentity.of(session.getSubmitOperator())) + && OperatorIdentityContext.getInstance().matches( + OperatorKey.of(session.getCurrentOperator()), + OperatorKey.of(session.getSubmitOperatorId(), OperatorIdentity.of(session.getSubmitOperator()))) && session.getCurrentAction() != null && ActionType.PASS.name().equalsIgnoreCase(session.getCurrentAction().type())) { long submitOperatorId = session.getSubmitOperatorId(); String submitOperatorIdentity = OperatorIdentity.of(session.getSubmitOperator()); operators = operators.stream() - .filter(operator -> !OperatorIdentityPolicy.matches(operator, submitOperatorId, submitOperatorIdentity)) + .filter(operator -> !OperatorIdentityContext.getInstance() + .matches(OperatorKey.of(operator), OperatorKey.of(submitOperatorId, submitOperatorIdentity))) .toList(); // 全部审批人均与提交人一致,当前节点自动通过:生成留痕记录并继续向后续节点生成记录(issue #226) if (operators.isEmpty()) { diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityContext.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityContext.java new file mode 100644 index 00000000..f7c0aeab --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityContext.java @@ -0,0 +1,88 @@ +package com.codingapi.flow.operator; + +/** + * 身份匹配上下文(原 {@code OperatorIdentityPolicy},issue #297 / #311 P3)。 + * + *

      它只做两件事:持有当前生效的匹配模式,并把该模式传给 + * {@link OperatorKey#matches(OperatorKey, OperatorIdentityMatchMode)}。 + * 判定逻辑不在这里——比较规则只有 {@link OperatorKey} 一个定义点。 + * + *

      命名说明:这里没有「策略」——策略是 {@link OperatorIdentityMatchMode},它自己回答怎么比; + * 本类是可变全局配置,属于 Context。原先叫 {@code Policy} 会让人以为可以扩展判定规则, + * 实际只能换一个开关。 + * + *

      模式由 starter 在启动时按配置写入({@code codingapi.flow.identity.match-mode}, + * starter 侧默认 {@code USER_ONLY});只使用 framework 的接入方不配置时保持 {@code STRICT}。 + * + *

      框架不依赖 Spring,因此配置只能通过这个单例传递。可变全局状态是它唯一的代价, + * 因此不提供 {@code reset()} 这类「测试专用」入口——测试直接用 {@link #use} 显式设定与还原。 + * + * @see OperatorIdentityMatchMode + */ +public final class OperatorIdentityContext { + + private static final OperatorIdentityContext INSTANCE = new OperatorIdentityContext(); + + private volatile OperatorIdentityMatchMode matchMode = OperatorIdentityMatchMode.STRICT; + + private OperatorIdentityContext() { + } + + /** + * 全局唯一实例 + * + * @return 上下文实例 + */ + public static OperatorIdentityContext getInstance() { + return INSTANCE; + } + + /** + * 当前生效的匹配模式。 + * + * @return 匹配模式,不为 null + */ + public OperatorIdentityMatchMode matchMode() { + return matchMode; + } + + /** + * 切换匹配模式,{@code null} 表示回到框架默认(严格模式)。 + * + * @param mode 匹配模式 + */ + public void use(OperatorIdentityMatchMode mode) { + this.matchMode = mode == null ? OperatorIdentityMatchMode.STRICT : mode; + } + + /** + * 判断两个参与人标识是否为同一参与人。 + * + * @param current 当前参与人,{@code null} 表示无操作者,直接判定为不匹配 + * @param target 目标参与人 + * @return true 表示同一参与人 + */ + public boolean matches(OperatorKey current, OperatorKey target) { + if (current == null) { + return false; + } + return current.matches(target, matchMode); + } + + /** + * 判断两个人员对象是否代表「同一个人」在当前模式下可互相替代。 + * + *

      用于同人自动通过(#224/#226)等「按人合并」的场景:严格模式按人员 + 身份, + * 仅人员模式按人员 id。 + * + * @param left 人员 + * @param right 人员 + * @return true 表示同一参与人 + */ + public boolean sameOperator(IFlowOperator left, IFlowOperator right) { + if (left == null || right == null) { + return false; + } + return matches(OperatorKey.of(left), OperatorKey.of(right)); + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityPolicy.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityPolicy.java deleted file mode 100644 index 959f68b2..00000000 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityPolicy.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.codingapi.flow.operator; - -/** - * 身份匹配策略(issue #297)。 - * - *

      所有「当前用户能否办理/撤回/催办/减签某条流程记录」的判断都必须经过本类, - * 禁止在业务代码里直接写 {@code userId == ... && identity.equals(...)}, - * 否则会出现「能审批但不能撤回」「同人换身份被误记为干预」这类半开状态。 - * - *

      判定逻辑本身不在这里:由 {@link OperatorKey#matches(OperatorKey, OperatorIdentityMatchMode)} - * 回答,本类只负责「持有当前模式 + 把模式传下去」。比较逻辑只有一份定义点。 - * - *

      默认 {@link OperatorIdentityMatchMode#STRICT},由 starter 在启动时按配置覆盖 - * ({@code codingapi.flow.identity.match-mode},starter 侧默认 {@code USER_ONLY})。 - * 只使用 framework 的接入方不配置时保持历史行为。 - * - * @see OperatorIdentityMatchMode - */ -public final class OperatorIdentityPolicy { - - private static volatile OperatorIdentityMatchMode matchMode = OperatorIdentityMatchMode.STRICT; - - private OperatorIdentityPolicy() { - } - - /** - * 当前生效的匹配模式。 - * - * @return 匹配模式,不为 null - */ - public static OperatorIdentityMatchMode matchMode() { - return matchMode; - } - - /** - * 设置匹配模式,{@code null} 表示回到框架默认(严格模式)。 - * - * @param mode 匹配模式 - */ - public static void setMatchMode(OperatorIdentityMatchMode mode) { - matchMode = mode == null ? OperatorIdentityMatchMode.STRICT : mode; - } - - /** - * 恢复框架默认模式,主要供测试清理静态状态。 - */ - public static void reset() { - matchMode = OperatorIdentityMatchMode.STRICT; - } - - /** - * 当前用户是否就是记录上的参与人(可办理该记录)。 - * - * @param current 当前操作者 - * @param recordOperatorId 记录上的参与人 id - * @param recordOperatorIdentity 记录上的参与人身份 - * @return true 表示允许办理 - */ - public static boolean matches(IFlowOperator current, long recordOperatorId, String recordOperatorIdentity) { - if (current == null) { - return false; - } - return matches(OperatorKey.of(current), OperatorKey.of(recordOperatorId, recordOperatorIdentity)); - } - - /** - * 判断两个 {@code (id, identity)} 是否代表同一个参与人。 - * - *

      判定本身由 {@link OperatorKey#matches(OperatorKey, OperatorIdentityMatchMode)} 回答, - * 本方法只负责把「当前生效的模式」传下去,不重复实现比较逻辑。 - * - * @param currentOperatorId 当前操作者 id - * @param currentOperatorIdentity 当前操作者身份 - * @param recordOperatorId 记录上的参与人 id - * @param recordOperatorIdentity 记录上的参与人身份 - * @return true 表示匹配 - */ - public static boolean matches(long currentOperatorId, - String currentOperatorIdentity, - long recordOperatorId, - String recordOperatorIdentity) { - return matches(OperatorKey.of(currentOperatorId, currentOperatorIdentity), - OperatorKey.of(recordOperatorId, recordOperatorIdentity)); - } - - /** - * 按当前模式判定两个参与人标识是否同一参与人。 - * - * @param left 参与人标识 - * @param right 参与人标识 - * @return true 表示同一参与人 - */ - public static boolean matches(OperatorKey left, OperatorKey right) { - if (left == null) { - return false; - } - return left.matches(right, matchMode); - } - - /** - * 判断两个人员对象是否代表「同一个人」在当前模式下可互相替代。 - * - *

      用于同人自动通过(#224/#226)等「按人合并」的场景:严格模式按人员 + 身份, - * 仅人员模式按人员 id。 - * - * @param left 人员 - * @param right 人员 - * @return true 表示同一参与人 - */ - public static boolean sameOperator(IFlowOperator left, IFlowOperator right) { - if (left == null || right == null) { - return false; - } - return matches(OperatorKey.of(left), OperatorKey.of(right)); - } -} 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 1be462fb..cf75ffbf 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 @@ -8,7 +8,7 @@ import com.codingapi.flow.manager.NodeStrategyManager; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; -import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorIdentityContext; import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; @@ -335,15 +335,14 @@ static List resolveCurrentNodeOperators(FlowRecord currentRecord, continue; } // 排除当前操作人时按身份匹配策略判断(issue #297):USER_ONLY 下同一人换身份仍视为本人 - if (OperatorIdentityPolicy.matches(currentRecord.getCurrentOperatorId(), - currentRecord.getCurrentOperatorIdentity(), - record.getCurrentOperatorId(), record.getCurrentOperatorIdentity())) { + if (OperatorIdentityContext.getInstance() + .matches(currentRecord.currentOperatorKey(), record.currentOperatorKey())) { continue; } // 去重键就是参与人键:USER_ONLY 下同一个人只展示一次,STRICT 下按 (人员id, 身份) 区分。 // 键格式由 OperatorKey 唯一定义,这里不再判断模式后自行拼接。 - String operatorKey = OperatorKey.of(record.getCurrentOperatorId(), - record.getCurrentOperatorIdentity()).key(OperatorIdentityPolicy.matchMode()); + String operatorKey = record.currentOperatorKey() + .key(OperatorIdentityContext.getInstance().matchMode()); operators.putIfAbsent(operatorKey, new FlowOperator(record.getCurrentOperatorId(), record.getCurrentOperatorName(), record.getCurrentOperatorIdentity())); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java index a2b30a2b..34a46ded 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java @@ -1,6 +1,7 @@ package com.codingapi.flow.record; import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.exception.FlowStateException; import com.codingapi.flow.exception.FlowValidationException; import com.codingapi.flow.form.FormData; import com.codingapi.flow.generator.FlowIDGeneratorGatewayContext; @@ -11,7 +12,7 @@ import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.operator.OperatorIdentityMatchMode; -import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorIdentityContext; import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.session.FlowAdvice; import com.codingapi.flow.session.FlowSession; @@ -332,7 +333,7 @@ public class FlowRecord { *

    * 相同依据字段 + {@link FlowRecord#workRuntimeId} + {@link FlowRecord#nodeId} 的数据合并到一条记录上。 * - *

    合并键是否包含身份由 {@link OperatorIdentityPolicy} 的匹配模式决定(issue #295): + *

    合并键是否包含身份由 {@link OperatorIdentityContext} 的匹配模式决定(issue #295): *

      *
    • {@link OperatorIdentityMatchMode#USER_ONLY}(starter 默认)— 身份不参与合并, * 同一人的两个身份在同一节点视为**一个参与人**,只保留一条待办。这也是「身份不是权限、 @@ -356,7 +357,7 @@ public String getTodoKey() { case SUBMITTER -> OperatorKey.of(submitOperatorId, submitOperatorIdentity); default -> OperatorKey.of(currentOperatorId, currentOperatorIdentity); }; - return TodoMergeKey.of(mergeOperator, workRuntimeId, nodeId, OperatorIdentityPolicy.matchMode()).value(); + return TodoMergeKey.of(mergeOperator, workRuntimeId, nodeId, OperatorIdentityContext.getInstance().matchMode()).value(); } @@ -562,6 +563,33 @@ public void verify() { } } + /** + * 记录上「当前办理人」的参与人标识。 + * + *

      参与人由 {@code (人员id, 身份)} 共同标识(issue #288),凡是拿记录上的人做判断的地方, + * 都应先取得该标识,而不是把两个字段拆开传。 + * + * @return 当前办理人标识 + */ + public OperatorKey currentOperatorKey() { + return OperatorKey.of(currentOperatorId, currentOperatorIdentity); + } + + /** + * 校验该记录只能由给定参与人操作,否则抛出 {@code operatorNotMatch}。 + * + *

      撤回 / 催办 / 删除 / 子流程重置四个入口共用这一条领域规则(issue #297): + * 身份是否参与判定由 {@link OperatorIdentityContext} 统一控制, + * 各服务不再各自比较 {@code operatorId + identity}。 + * + * @param operator 请求发起人标识 + */ + public void verifyOperator(OperatorKey operator) { + if (!OperatorIdentityContext.getInstance().matches(operator, currentOperatorKey())) { + throw FlowStateException.operatorNotMatch(); + } + } + /** * 是否异常 */ @@ -635,7 +663,9 @@ public void update(FlowSession flowSession, boolean pass) { // 设置流程干预人信息,流程干预只能由流程管理员才能操作。 // 是否属于「他人代办」由身份匹配策略决定(issue #297):USER_ONLY 下同一人换身份办理不算干预, // STRICT 下仍按 (userId, identity) 判定(issue #288)。 - if (!OperatorIdentityPolicy.matches(flowSession.getCurrentOperator(), this.currentOperatorId, this.currentOperatorIdentity)) { + OperatorKey currentOperator = flowSession.getCurrentOperator() == null + ? null : OperatorKey.of(flowSession.getCurrentOperator()); + if (!OperatorIdentityContext.getInstance().matches(currentOperator, currentOperatorKey())) { this.interferedOperatorId = flowSession.getCurrentOperator().getUserId(); this.interferedOperatorName = flowSession.getCurrentOperator().getName(); this.interferedOperatorIdentity = OperatorIdentity.of(flowSession.getCurrentOperator()); 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 7504e72a..ce2d62f3 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 @@ -6,7 +6,7 @@ import com.codingapi.flow.exception.FlowStateException; import com.codingapi.flow.mock.MockRepositoryHolder; import com.codingapi.flow.node.nodes.StartNode; -import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.pojo.request.FlowDeleteRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.FlowRecordService; @@ -62,10 +62,7 @@ public void delete() { throw FlowStateException.recordAlreadyRunning(); } // 权限校验:仅允许当前待办处理人删除;身份是否参与判定由策略决定(issue #297) - if (!OperatorIdentityPolicy.matches(request.getOperatorId(), request.getOperatorIdentity(), - currentRecord.getCurrentOperatorId(), currentRecord.getCurrentOperatorIdentity())) { - throw FlowStateException.operatorNotMatch(); - } + currentRecord.verifyOperator(OperatorKey.of(request.getOperatorId(), request.getOperatorIdentity())); // 删除流程记录及其关联待办 flowRecordService.deleteFlowRecord(currentRecord); // 推送删除事件 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 4f64f759..a82dd76f 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 @@ -11,7 +11,7 @@ import com.codingapi.flow.manager.NodeStrategyManager; import com.codingapi.flow.mock.MockRepositoryHolder; import com.codingapi.flow.node.IFlowNode; -import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.pojo.request.FlowRevokeRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.FlowRecordService; @@ -70,10 +70,7 @@ public void revoke() { } long currentOperatorId = currentRecord.getCurrentOperatorId(); // 是否要求身份一致由身份匹配策略决定(issue #297):USER_ONLY 下同一人换身份仍可撤回自己的办理 - if (!OperatorIdentityPolicy.matches(request.getOperatorId(), request.getOperatorIdentity(), - currentOperatorId, currentRecord.getCurrentOperatorIdentity())) { - throw FlowStateException.operatorNotMatch(); - } + currentRecord.verifyOperator(OperatorKey.of(request.getOperatorId(), request.getOperatorIdentity())); WorkflowRuntime workflowRuntime = workflowService.getWorkflowRuntime(currentRecord.getWorkRuntimeId()); if (workflowRuntime == null) { throw FlowNotFoundException.workflow(currentRecord.getWorkRuntimeId() + " not found"); 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 22ae6e1f..70fcbb5c 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 @@ -12,7 +12,7 @@ import com.codingapi.flow.mock.MockRepositoryHolder; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; -import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.request.FlowCreateRequest; import com.codingapi.flow.pojo.request.FlowSubProcessResetRequest; @@ -74,11 +74,8 @@ public void reset() { if (!currentRecord.isTodo()) { throw FlowStateException.recordAlreadyDone(); } - // issue #297:身份是否参与判定由 OperatorIdentityPolicy 统一控制 - if (!OperatorIdentityPolicy.matches(request.getOperatorId(), request.getOperatorIdentity(), - currentRecord.getCurrentOperatorId(), currentRecord.getCurrentOperatorIdentity())) { - throw FlowStateException.operatorNotMatch(); - } + // issue #297:身份是否参与判定由 OperatorIdentityContext 统一控制 + currentRecord.verifyOperator(OperatorKey.of(request.getOperatorId(), request.getOperatorIdentity())); WorkflowRuntime workflowRuntime = workflowService.getWorkflowRuntime(currentRecord.getWorkRuntimeId()); if (workflowRuntime == null) { 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 3ed3da1d..5297747a 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 @@ -11,7 +11,7 @@ import com.codingapi.flow.manager.WorkflowStrategyManager; import com.codingapi.flow.mock.MockRepositoryHolder; import com.codingapi.flow.operator.IFlowOperator; -import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.pojo.request.FlowUrgeRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.FlowRecordService; @@ -61,12 +61,8 @@ public void urge() { throw FlowStateException.recordNotSupportRevoke(); } - long currentOperatorId = currentRecord.getCurrentOperatorId(); - // issue #297:身份是否参与判定由 OperatorIdentityPolicy 统一控制 - if (!OperatorIdentityPolicy.matches(request.getOperatorId(), request.getOperatorIdentity(), - currentOperatorId, currentRecord.getCurrentOperatorIdentity())) { - throw FlowStateException.operatorNotMatch(); - } + // issue #297:身份是否参与判定由 OperatorIdentityContext 统一控制 + currentRecord.verifyOperator(OperatorKey.of(request.getOperatorId(), request.getOperatorIdentity())); UrgeInterval urgeInterval = repositoryHolder.getLatestUrgeInterval(currentRecord.getProcessId(), request.getRecordId()); if (urgeInterval != null) { @@ -82,7 +78,8 @@ public void urge() { } } - IFlowOperator currentOperator = flowOperatorGateway.get(currentOperatorId, request.getOperatorIdentity()); + IFlowOperator currentOperator = flowOperatorGateway.get( + currentRecord.getCurrentOperatorId(), request.getOperatorIdentity()); List todoRecords = flowRecordService.findFlowRecordTodoRecords(currentRecord.getProcessId()); // 保存催办记录 diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/manager/OperatorManagerTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/manager/OperatorManagerTest.java index beb69dcf..745b44f0 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/manager/OperatorManagerTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/manager/OperatorManagerTest.java @@ -1,7 +1,7 @@ package com.codingapi.flow.manager; import com.codingapi.flow.operator.OperatorIdentityMatchMode; -import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorIdentityContext; import com.codingapi.flow.user.User; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; @@ -23,7 +23,7 @@ class OperatorManagerTest { @AfterEach void tearDown() { - OperatorIdentityPolicy.reset(); + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.STRICT); } @Test @@ -46,7 +46,7 @@ void should_match_default_identity_equivalently_for_null_and_blank() { @Test void should_not_widen_config_matching_in_user_only_mode() { - OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); OperatorManager manager = new OperatorManager(List.of(User.withIdentity(1, "user1", "department1"))); assertTrue(manager.match(User.withIdentity(1, "user1", "department1"))); diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityContextTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityContextTest.java new file mode 100644 index 00000000..d0ec5537 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityContextTest.java @@ -0,0 +1,90 @@ +package com.codingapi.flow.operator; + +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 身份匹配上下文测试(issue #297 / #311 P3)。 + * + *

      上下文只负责「持有模式 + 把模式传给 OperatorKey」,因此这里断言的是 + * 「模式生效范围」与「判定唯一真源」,而不是比较细节(那属于 {@link OperatorKeyTest})。 + */ +class OperatorIdentityContextTest { + + private final OperatorIdentityContext context = OperatorIdentityContext.getInstance(); + + @AfterEach + void tearDown() { + context.use(OperatorIdentityMatchMode.STRICT); + } + + @Test + void should_default_to_strict_mode_for_framework_only_usage() { + assertEquals(OperatorIdentityMatchMode.STRICT, context.matchMode()); + assertFalse(context.matches( + OperatorKey.of(1, "department1"), OperatorKey.of(1, "department2"))); + } + + @Test + void should_compare_only_user_id_in_user_only_mode() { + context.use(OperatorIdentityMatchMode.USER_ONLY); + + assertTrue(context.matches(OperatorKey.of(1, "department1"), OperatorKey.of(1, "department2"))); + assertTrue(context.matches(OperatorKey.of(1, ""), OperatorKey.of(1, "department2"))); + assertFalse(context.matches(OperatorKey.of(2, "boss"), OperatorKey.of(1, "department1"))); + assertFalse(context.matches(null, OperatorKey.of(1, "department1"))); + } + + @Test + void should_delegate_matching_to_operator_key_instead_of_reimplementing() { + for (OperatorIdentityMatchMode mode : OperatorIdentityMatchMode.values()) { + context.use(mode); + for (String leftIdentity : new String[]{"", "department1", "department2"}) { + for (String rightIdentity : new String[]{"", "department1", "department2"}) { + OperatorKey left = OperatorKey.of(1, leftIdentity); + OperatorKey right = OperatorKey.of(1, rightIdentity); + assertEquals(left.matches(right, mode), context.matches(left, right), + "上下文的判定必须与 OperatorKey 的策略判定完全一致:" + mode); + } + } + } + } + + @Test + void should_treat_same_user_as_same_operator_only_when_mode_allows() { + User a = User.withIdentity(1, "user1", "department1"); + User b = User.withIdentity(1, "user1", "department2"); + + assertFalse(context.sameOperator(a, b)); + + context.use(OperatorIdentityMatchMode.USER_ONLY); + assertTrue(context.sameOperator(a, b)); + assertFalse(context.sameOperator(a, new User(2, "boss"))); + assertFalse(context.sameOperator(a, null)); + } + + @Test + void should_fall_back_to_strict_when_configured_with_null() { + context.use(OperatorIdentityMatchMode.USER_ONLY); + + context.use(null); + + assertEquals(OperatorIdentityMatchMode.STRICT, context.matchMode()); + } + + @Test + void should_parse_mode_leniently() { + assertEquals(OperatorIdentityMatchMode.USER_ONLY, OperatorIdentityMatchMode.parse("user-only")); + assertEquals(OperatorIdentityMatchMode.USER_ONLY, OperatorIdentityMatchMode.parse(" USER_ONLY ")); + assertEquals(OperatorIdentityMatchMode.STRICT, OperatorIdentityMatchMode.parse("strict")); + assertNull(OperatorIdentityMatchMode.parse(null)); + assertNull(OperatorIdentityMatchMode.parse(" ")); + assertNull(OperatorIdentityMatchMode.parse("unknown")); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityPolicyTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityPolicyTest.java deleted file mode 100644 index a7c02ce1..00000000 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityPolicyTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.codingapi.flow.operator; - -import com.codingapi.flow.user.User; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * 身份匹配策略测试(issue #297)。 - */ -class OperatorIdentityPolicyTest { - - @AfterEach - void tearDown() { - OperatorIdentityPolicy.reset(); - } - - @Test - void should_default_to_strict_mode_for_framework_only_usage() { - assertEquals(OperatorIdentityMatchMode.STRICT, OperatorIdentityPolicy.matchMode()); - assertFalse(OperatorIdentityPolicy.matches( - User.withIdentity(1, "user1", "department1"), 1, "department2")); - } - - @Test - void should_compare_only_user_id_in_user_only_mode() { - OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); - - assertTrue(OperatorIdentityPolicy.matches( - User.withIdentity(1, "user1", "department1"), 1, "department2")); - assertTrue(OperatorIdentityPolicy.matches( - User.withIdentity(1, "user1", ""), 1, "department2")); - assertFalse(OperatorIdentityPolicy.matches( - User.withIdentity(2, "boss", "department1"), 1, "department1")); - assertFalse(OperatorIdentityPolicy.matches((IFlowOperator) null, 1, "department1")); - } - - @Test - void should_treat_same_user_as_same_operator_only_when_mode_allows() { - User a = User.withIdentity(1, "user1", "department1"); - User b = User.withIdentity(1, "user1", "department2"); - - assertFalse(OperatorIdentityPolicy.sameOperator(a, b)); - - OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); - assertTrue(OperatorIdentityPolicy.sameOperator(a, b)); - assertFalse(OperatorIdentityPolicy.sameOperator(a, new User(2, "boss"))); - } - - @Test - void should_parse_mode_leniently() { - assertEquals(OperatorIdentityMatchMode.USER_ONLY, OperatorIdentityMatchMode.parse("user-only")); - assertEquals(OperatorIdentityMatchMode.USER_ONLY, OperatorIdentityMatchMode.parse(" USER_ONLY ")); - assertEquals(OperatorIdentityMatchMode.STRICT, OperatorIdentityMatchMode.parse("strict")); - assertNull(OperatorIdentityMatchMode.parse(null)); - assertNull(OperatorIdentityMatchMode.parse(" ")); - assertNull(OperatorIdentityMatchMode.parse("unknown")); - } -} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowSubProcessResetServiceTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowSubProcessResetServiceTest.java index 4a454da2..9e016825 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowSubProcessResetServiceTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowSubProcessResetServiceTest.java @@ -24,7 +24,7 @@ import com.codingapi.flow.node.nodes.StartNode; import com.codingapi.flow.node.nodes.SubProcessNode; import com.codingapi.flow.operator.OperatorIdentityMatchMode; -import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorIdentityContext; import com.codingapi.flow.pojo.body.FlowAdviceBody; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.request.FlowCreateRequest; @@ -119,7 +119,7 @@ void resetEventContext() throws Exception { @AfterEach void resetIdentityPolicy() { - OperatorIdentityPolicy.reset(); + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.STRICT); } /** @@ -556,7 +556,7 @@ void shouldRejectResetWhenOperatorMismatchOrRecordNotTodo() { */ @Test void shouldAllowResetWithOtherIdentityOfSameOperatorInUserOnlyMode() { - OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); FlowRecord finalTodo = prepareResetAtFinalApproval(); SubProcessRecord passedGroup = factory.subProcessRepository diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/HandleOperatorIdentityFlowTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/HandleOperatorIdentityFlowTest.java index 72649123..ef811bbf 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/service/HandleOperatorIdentityFlowTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/HandleOperatorIdentityFlowTest.java @@ -17,7 +17,7 @@ import com.codingapi.flow.node.nodes.StartNode; import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.operator.OperatorIdentityMatchMode; -import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorIdentityContext; import com.codingapi.flow.pojo.body.FlowAdviceBody; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.request.FlowCreateRequest; @@ -62,7 +62,7 @@ class HandleOperatorIdentityFlowTest { @BeforeEach void setUp() { // issue #297:USER_ONLY 下同一人换身份可以办理自己的待办,与 issue #306 的复现场景一致 - OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); factory = new MyFlowServiceFactory(); factory.userGateway.save(new User(INITIATOR, "initiator")); factory.userGateway.save(new User(APPROVER, "approver")); @@ -71,7 +71,7 @@ void setUp() { @AfterEach void tearDown() { - OperatorIdentityPolicy.reset(); + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.STRICT); } /** diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityBoundaryTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityBoundaryTest.java index 2a8bbdae..d3603a16 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityBoundaryTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityBoundaryTest.java @@ -18,7 +18,7 @@ import com.codingapi.flow.node.nodes.EndNode; import com.codingapi.flow.node.nodes.StartNode; import com.codingapi.flow.operator.OperatorIdentityMatchMode; -import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorIdentityContext; import com.codingapi.flow.pojo.body.FlowAdviceBody; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.request.FlowCreateRequest; @@ -51,7 +51,7 @@ * 身份边界行为测试(issue #295 缺口 2 / 3 / 4 / 7)。 * *

      统一约定:身份不是权限,只是脚本执行与留痕信息。是否把「同一人的两个身份」当作同一参与人, - * 由 {@link OperatorIdentityPolicy} 的匹配模式决定: + * 由 {@link OperatorIdentityContext} 的匹配模式决定: *

        *
      • {@link OperatorIdentityMatchMode#USER_ONLY}:按人匹配,同人换身份可以办理自己的待办, * 加签 / 减签也按人判定;
      • @@ -89,7 +89,7 @@ void setUp() { @AfterEach void tearDown() { - OperatorIdentityPolicy.reset(); + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.STRICT); } // ==================== 缺口 2:撤回 / 催办的身份归属 ==================== @@ -102,7 +102,7 @@ void tearDown() { */ @Test void should_allow_revoke_with_other_identity_in_user_only_mode() { - OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); Workflow workflow = saveFlow("identity-revoke-user-only", APPROVER); long startRecordId = createFlow(workflow, DEPARTMENT_1); submit(workflow, startRecordId, DEPARTMENT_1); @@ -140,7 +140,7 @@ void should_reject_revoke_with_other_identity_in_strict_mode() { */ @Test void should_allow_urge_with_other_identity_in_user_only_mode() { - OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); Workflow workflow = saveFlow("identity-urge-user-only", APPROVER); long startRecordId = createFlow(workflow, DEPARTMENT_1); submit(workflow, startRecordId, DEPARTMENT_1); @@ -175,7 +175,7 @@ void should_reject_urge_with_other_identity_in_strict_mode() { */ @Test void should_reject_add_audit_for_same_user_in_user_only_mode() { - OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); prepareApprovalRecordWithIdentity("identity-add-audit-user-only"); FlowRecord approvalRecord = currentApprovalRecord(); @@ -206,7 +206,7 @@ void should_allow_add_audit_for_same_user_with_other_identity_in_strict_mode() { */ @Test void should_reduce_pending_record_of_same_user_with_other_identity_in_user_only_mode() { - OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); FlowRecord secondRecord = prepareSequenceApproval("identity-reduce-user-only"); assertDoesNotThrow(() -> reduceAudit(APPROVER, SECOND_APPROVER)); @@ -282,7 +282,7 @@ void should_record_forward_operator_identity_from_forward_chain() { */ @Test void should_not_record_interfere_when_same_user_uses_other_identity() { - OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); Workflow workflow = saveFlow("identity-interfere", APPROVER); long startRecordId = createFlow(workflow, DEPARTMENT_1); @@ -305,7 +305,7 @@ void should_not_record_interfere_when_same_user_uses_other_identity() { */ @Test void should_auto_pass_when_same_user_uses_other_identity_in_user_only_mode() { - OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); Workflow workflow = saveAutoPassFlow("identity-auto-pass-user-only"); long startRecordId = createFlow(workflow, DEPARTMENT_1); submit(workflow, startRecordId, DEPARTMENT_1); diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityUserOnlyPermissionTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityUserOnlyPermissionTest.java index a8561f8f..fe797324 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityUserOnlyPermissionTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityUserOnlyPermissionTest.java @@ -17,7 +17,7 @@ import com.codingapi.flow.node.nodes.EndNode; import com.codingapi.flow.node.nodes.StartNode; import com.codingapi.flow.operator.OperatorIdentityMatchMode; -import com.codingapi.flow.operator.OperatorIdentityPolicy; +import com.codingapi.flow.operator.OperatorIdentityContext; import com.codingapi.flow.pojo.body.FlowAdviceBody; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.request.FlowCreateRequest; @@ -56,7 +56,7 @@ class OperatorIdentityUserOnlyPermissionTest { @BeforeEach void setUp() { - OperatorIdentityPolicy.setMatchMode(OperatorIdentityMatchMode.USER_ONLY); + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); User user1 = User.withIdentity(1, "user1", "department1"); User boss = new User(2, "boss"); @@ -108,7 +108,7 @@ void setUp() { @AfterEach void tearDown() { - OperatorIdentityPolicy.reset(); + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.STRICT); } private Map formData() { 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 3b4624d1..7800fb07 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 @@ -6,7 +6,7 @@ import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.properties.FlowProperties; import com.codingapi.flow.register.NodeViewJavaScriptCacheContextRegister; -import com.codingapi.flow.register.OperatorIdentityPolicyRegister; +import com.codingapi.flow.register.OperatorIdentityConfigurer; import com.codingapi.flow.register.RepositoryHolderContextRegister; import com.codingapi.flow.register.FlowScriptContextRegister; import com.codingapi.flow.register.GatewayContextRegister; @@ -31,8 +31,8 @@ public class AutoConfiguration { * 身份匹配策略:启动时把 {@code codingapi.flow.identity.match-mode} 写入 framework(issue #297)。 */ @Bean - public OperatorIdentityPolicyRegister operatorIdentityPolicyRegister(FlowProperties flowProperties) { - return new OperatorIdentityPolicyRegister(flowProperties); + public OperatorIdentityConfigurer operatorIdentityConfigurer(FlowProperties flowProperties) { + return new OperatorIdentityConfigurer(flowProperties); } @Bean public NodeViewJavaScriptCacheContextRegister nodeViewJavaScriptCacheContextRegister(NodeViewJavaScriptRepository nodeViewJavaScriptRepository){ diff --git a/flow-engine-starter/src/main/java/com/codingapi/flow/properties/FlowProperties.java b/flow-engine-starter/src/main/java/com/codingapi/flow/properties/FlowProperties.java index 45ccab8b..ebd91eba 100644 --- a/flow-engine-starter/src/main/java/com/codingapi/flow/properties/FlowProperties.java +++ b/flow-engine-starter/src/main/java/com/codingapi/flow/properties/FlowProperties.java @@ -9,7 +9,7 @@ * 流程引擎配置(issue #297)。 * *

        配置前缀 {@code codingapi.flow},启动时由 {@code AutoConfiguration} 写入框架层的 - * {@link com.codingapi.flow.operator.OperatorIdentityPolicy}。 + * {@link com.codingapi.flow.operator.OperatorIdentityContext}。 * *

        示例({@code application.properties}): *

        diff --git a/flow-engine-starter/src/main/java/com/codingapi/flow/register/OperatorIdentityPolicyRegister.java b/flow-engine-starter/src/main/java/com/codingapi/flow/register/OperatorIdentityConfigurer.java
        similarity index 50%
        rename from flow-engine-starter/src/main/java/com/codingapi/flow/register/OperatorIdentityPolicyRegister.java
        rename to flow-engine-starter/src/main/java/com/codingapi/flow/register/OperatorIdentityConfigurer.java
        index 78b9d27e..1295b649 100644
        --- a/flow-engine-starter/src/main/java/com/codingapi/flow/register/OperatorIdentityPolicyRegister.java
        +++ b/flow-engine-starter/src/main/java/com/codingapi/flow/register/OperatorIdentityConfigurer.java
        @@ -1,23 +1,26 @@
         package com.codingapi.flow.register;
         
        -import com.codingapi.flow.operator.OperatorIdentityPolicy;
        +import com.codingapi.flow.operator.OperatorIdentityContext;
         import com.codingapi.flow.properties.FlowProperties;
         import lombok.AllArgsConstructor;
         import org.springframework.beans.factory.InitializingBean;
         
         /**
        - * 把 Spring 配置里的身份匹配模式写入框架层(issue #297)。
        + * 把 Spring 配置里的身份匹配模式写入框架层(issue #297 / #311 P3)。
          *
        - * 

        framework 不依赖 Spring,模式只能通过 {@link OperatorIdentityPolicy} 的静态持有者传递; - * 本注册器在容器启动时完成注入,与 {@link GatewayContextRegister} 的初始化方式保持一致。 + *

        framework 不依赖 Spring,模式只能通过 {@link OperatorIdentityContext} 这个单例传递; + * 本配置器在容器启动时完成写入,与 {@link GatewayContextRegister} 的初始化方式保持一致。 + * + *

        命名从 {@code Register} 改为 {@code Configurer}:它做的事情是「把配置写进上下文」, + * 不是注册 Bean。 */ @AllArgsConstructor -public class OperatorIdentityPolicyRegister implements InitializingBean { +public class OperatorIdentityConfigurer implements InitializingBean { private final FlowProperties flowProperties; @Override public void afterPropertiesSet() { - OperatorIdentityPolicy.setMatchMode(flowProperties.getIdentity().getMatchMode()); + OperatorIdentityContext.getInstance().use(flowProperties.getIdentity().getMatchMode()); } } diff --git a/flow-engine-starter/src/test/java/com/codingapi/flow/properties/FlowPropertiesTest.java b/flow-engine-starter/src/test/java/com/codingapi/flow/properties/FlowPropertiesTest.java index 8d1ae86a..37e82826 100644 --- a/flow-engine-starter/src/test/java/com/codingapi/flow/properties/FlowPropertiesTest.java +++ b/flow-engine-starter/src/test/java/com/codingapi/flow/properties/FlowPropertiesTest.java @@ -1,8 +1,8 @@ package com.codingapi.flow.properties; import com.codingapi.flow.operator.OperatorIdentityMatchMode; -import com.codingapi.flow.operator.OperatorIdentityPolicy; -import com.codingapi.flow.register.OperatorIdentityPolicyRegister; +import com.codingapi.flow.operator.OperatorIdentityContext; +import com.codingapi.flow.register.OperatorIdentityConfigurer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; @@ -12,13 +12,13 @@ * starter 配置默认值与注册器测试(issue #297)。 * *

        starter 是业务接入的默认入口,默认不限制身份;框架自身的默认值仍是严格模式, - * 两者通过 {@link OperatorIdentityPolicyRegister} 在启动时衔接。 + * 两者通过 {@link OperatorIdentityConfigurer} 在启动时衔接。 */ class FlowPropertiesTest { @AfterEach void tearDown() { - OperatorIdentityPolicy.reset(); + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.STRICT); } @Test @@ -32,8 +32,8 @@ void should_apply_configured_mode_to_framework() { FlowProperties properties = new FlowProperties(); properties.getIdentity().setMatchMode(OperatorIdentityMatchMode.STRICT); - new OperatorIdentityPolicyRegister(properties).afterPropertiesSet(); + new OperatorIdentityConfigurer(properties).afterPropertiesSet(); - assertEquals(OperatorIdentityMatchMode.STRICT, OperatorIdentityPolicy.matchMode()); + assertEquals(OperatorIdentityMatchMode.STRICT, OperatorIdentityContext.getInstance().matchMode()); } } From b892682f5e4a32f2b2473d01c2a57ae9deaf11d6 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Thu, 3 Dec 2026 17:59:38 +0800 Subject: [PATCH 30/35] =?UTF-8?q?refactor(operator):=20=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E5=99=A8=E4=B8=8E=E5=88=86=E9=85=8D=E6=9C=8D=E5=8A=A1=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E6=9E=84=E9=80=A0=E6=B3=A8=E5=85=A5=E7=9A=84=E5=AF=B9?= =?UTF-8?q?=E8=B1=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P4 对象化(#308、#311): - OperatorScriptResultResolver:4 个静态 resolve 重载 → 构造注入 (IRepositoryHolder, scriptType) + 单个 resolve(result) - 解析主流程拆为「归一化 → 元素化 → 批量回查 → 按序还原」,五段 instanceof + continue 下沉为元素对象 - 新增 OperatorScriptElement(sealed,Direct/Pending 各自回答「是否有效」「对应谁」) - 新增 PendingOperators:键集合 + 仓储即状态,按身份分组一次查完,替代原 batchResolve 私有函数 - OperatorAssignmentService:静态函数集合 → 构造注入 FlowSession;hasAssignment(nodeId) / assign(processId, selections) - 新增 OperatorSelections:两种表达形式(id / key)归并为一种,携带身份优先的规则只有一个定义点 - FlowActionService / FlowCreateService 的 if-else 二选一消失,改为传 OperatorSelections 行为零变化:framework 全量 550 个测试通过(含新增 20 个)。 Closes #308 --- .../flow/action/actions/PassAction.java | 2 +- .../service/InitiatorSelectNodeService.java | 2 +- .../flow/operator/OperatorSelections.java | 111 ++++++++ .../flow/script/node/ErrorTriggerScript.java | 6 +- .../flow/script/node/OperatorLoadScript.java | 2 +- .../operator/OperatorScriptElement.java | 74 +++++ .../OperatorScriptResultResolver.java | 259 ++++++------------ .../script/operator/PendingOperators.java | 74 +++++ .../flow/service/impl/FlowActionService.java | 14 +- .../flow/service/impl/FlowCreateService.java | 17 +- .../impl/OperatorAssignmentService.java | 110 ++++---- .../codingapi/flow/session/FlowSession.java | 2 +- .../strategy/node/OperatorLoadStrategy.java | 2 +- .../flow/operator/OperatorSelectionsTest.java | 84 ++++++ .../operator/OperatorScriptElementTest.java | 66 +++++ .../OperatorScriptResultResolverTest.java | 33 ++- 16 files changed, 590 insertions(+), 268 deletions(-) create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorSelections.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptElement.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/PendingOperators.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorSelectionsTest.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptElementTest.java diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java index e39830c4..5a4b5194 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java @@ -267,7 +267,7 @@ private void collectApproverSelectNodes(FlowSession flowSession, IFlowNode node, OperatorSelectType selectType = node.strategyManager().getOperatorSelectType(); if (selectType == OperatorSelectType.APPROVER_SELECT) { // 兼容存量 map、含身份的新字段,以及发起时已落库的分配(issue #288 衍生 / #292) - if (!OperatorAssignmentService.hasAssignment(flowSession, node.getId())) { + if (!new OperatorAssignmentService(flowSession).hasAssignment(node.getId())) { List range = node.strategyManager() .loadOperatorRange(flowSession.updateSession(node)); result.add(new NodeOption(node, range)); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/service/InitiatorSelectNodeService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/service/InitiatorSelectNodeService.java index c5cd516f..24072133 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/service/InitiatorSelectNodeService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/service/InitiatorSelectNodeService.java @@ -34,7 +34,7 @@ private void appendNodes(List currentNodes) { OperatorSelectType selectType = node.strategyManager().getOperatorSelectType(); if (selectType == OperatorSelectType.INITIATOR_SELECT) { // 兼容存量 map、含身份的新字段,以及发起时已落库的分配(issue #288 衍生 / #292) - if (!OperatorAssignmentService.hasAssignment(this.flowSession, node.getId())) { + if (!new OperatorAssignmentService(this.flowSession).hasAssignment(node.getId())) { List range = node.strategyManager() .loadOperatorRange(this.flowSession.updateSession(node)); operatorSelectNodes.add(new NodeOption(node, range)); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorSelections.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorSelections.java new file mode 100644 index 00000000..658c671a --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorSelections.java @@ -0,0 +1,111 @@ +package com.codingapi.flow.operator; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * 操作人选择集合:节点 id → 选定的参与人列表。 + * + *

        它存在的唯一理由是:同一个信息在请求里有两种表达—— + * {@code Map>}(只表达人员,默认身份)和 + * {@code Map>}(表达人员 + 身份)。 + * + *

        「携带身份的表达式优先」是一条业务规则,必须只有一个定义点,否则调用方会各自写 + * {@code if (keys != null) ... else ...},两处一旦不一致就会出现「带身份设定被忽略」。 + * 因此把这条优先级收进本类,调用方只负责把两边的原始数据交进来。 + */ +public final class OperatorSelections { + + private final Map> byNode; + + private OperatorSelections(Map> byNode) { + this.byNode = byNode; + } + + /** + * 归并两种表达形式:携带身份的分配优先,其次仅人员 id 的分配(按默认身份)。 + * + *

        优先级是整体的,不是逐节点的:只要携带身份的分配非空,就以它为准, + * 仅人员 id 的分配整体忽略。这与「请求只会用其中一种形式」的调用约定一致。 + * + * @param byOperators 携带身份的分配,可为 {@code null} + * @param byOperatorIds 仅人员 id 的分配,可为 {@code null} + * @return 选择集合 + */ + public static OperatorSelections of(Map> byOperators, + Map> byOperatorIds) { + if (byOperators != null && !byOperators.isEmpty()) { + return new OperatorSelections(copy(byOperators)); + } + if (byOperatorIds == null || byOperatorIds.isEmpty()) { + return empty(); + } + Map> converted = new LinkedHashMap<>(); + byOperatorIds.forEach((nodeId, operatorIds) -> { + if (operatorIds == null || operatorIds.isEmpty()) { + return; + } + converted.put(nodeId, operatorIds.stream().map(OperatorKey::ofDefault).toList()); + }); + return new OperatorSelections(converted); + } + + /** + * 空选择 + * + * @return 空集合 + */ + public static OperatorSelections empty() { + return new OperatorSelections(Map.of()); + } + + public boolean isEmpty() { + return byNode.isEmpty(); + } + + /** + * 该节点是否有选择 + * + * @param nodeId 节点 id + * @return true 表示该节点选了人 + */ + public boolean hasSelection(String nodeId) { + List selected = byNode.get(nodeId); + return selected != null && !selected.isEmpty(); + } + + /** + * 全部节点 id + * + * @return 节点 id 集合,保持插入顺序 + */ + public Set nodeIds() { + return new LinkedHashSet<>(byNode.keySet()); + } + + /** + * 该节点选择的参与人 + * + * @param nodeId 节点 id + * @return 参与人列表,无选择时返回空列表 + */ + public List of(String nodeId) { + List selected = byNode.get(nodeId); + return selected == null ? List.of() : selected; + } + + private static Map> copy(Map> source) { + Map> copied = new LinkedHashMap<>(); + source.forEach((nodeId, operators) -> { + if (operators == null || operators.isEmpty()) { + return; + } + copied.put(nodeId, List.copyOf(operators)); + }); + return Collections.unmodifiableMap(copied); + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/ErrorTriggerScript.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/ErrorTriggerScript.java index 3cd36c7b..7ebd702a 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/ErrorTriggerScript.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/ErrorTriggerScript.java @@ -61,7 +61,8 @@ public ErrorThrow execute(FlowSession session) { } ErrorThrow errorThrow = new ErrorThrow(); - errorThrow.setOperators(OperatorScriptResultResolver.resolve(session, value, SCRIPT_TYPE)); + errorThrow.setOperators( + new OperatorScriptResultResolver(session.getRepositoryHolder(), SCRIPT_TYPE).resolve(value)); return errorThrow; } @@ -109,7 +110,8 @@ private ErrorThrow parseMap(FlowSession session, Map map) { private ErrorThrow parseOperators(FlowSession session, List operators) { ErrorThrow errorThrow = new ErrorThrow(); - errorThrow.setOperators(OperatorScriptResultResolver.resolve(session, operators, SCRIPT_TYPE)); + errorThrow.setOperators( + new OperatorScriptResultResolver(session.getRepositoryHolder(), SCRIPT_TYPE).resolve(operators)); return errorThrow; } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/OperatorLoadScript.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/OperatorLoadScript.java index 14f2d730..2b51e4b0 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/OperatorLoadScript.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/OperatorLoadScript.java @@ -39,7 +39,7 @@ public List execute(FlowSession session) { Object scriptResult = FlowScriptRuntimeContext.getInstance() .getGroovyScript(script) .invoke(Map.of("$bind", new GroovyScriptBind(FlowScriptContext.getInstance())), request); - return OperatorScriptResultResolver.resolve(session, scriptResult, SCRIPT_TYPE); + return new OperatorScriptResultResolver(session.getRepositoryHolder(), SCRIPT_TYPE).resolve(scriptResult); } /** diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptElement.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptElement.java new file mode 100644 index 00000000..e984ec6d --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptElement.java @@ -0,0 +1,74 @@ +package com.codingapi.flow.script.operator; + +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; + +import java.util.Map; + +/** + * 取人脚本返回值的元素(issue #303 / #311 P4)。 + * + *

        脚本可以返回三种元素形态,但差异只在「怎么拿到参与人」这一件事上: + *

          + *
        • {@link Direct} —— 返回值本身就是参与人对象,直接采用,不回查;
        • + *
        • {@link Pending} —— 返回值只是一个 {@link OperatorKey},需要按身份批量回查。
        • + *
        + * 差异收敛到这两个实现后,解析主流程不再需要五段 {@code instanceof} + {@code continue}, + * 只需「解析成元素 → 批量回查 → 按序还原」三步。 + */ +sealed interface OperatorScriptElement { + + /** + * 该元素是否指向一个有效参与人。 + * + *

        非正数人员 id(存量脚本用 {@code -1} 表示「无审批人」)视为「该元素无人员」, + * 由主流程跳过,不抛异常——「未匹配到审批人」仍由下游异常处理接管。 + * + * @return true 表示该元素指向一个有效参与人 + */ + boolean hasParticipant(); + + /** + * 从回查结果中取出该元素对应的参与人。 + * + * @param resolved 回查结果,以 {@link OperatorKey#key()} 为键 + * @return 参与人;回查不到时返回 {@code null} + */ + IFlowOperator resolveFrom(Map resolved); + + /** + * 直接采用形态:脚本返回的已经是参与人对象(含其身份),不回查。 + * + * @param operator 参与人对象 + */ + record Direct(IFlowOperator operator) implements OperatorScriptElement { + + @Override + public boolean hasParticipant() { + return operator.getUserId() > 0; + } + + @Override + public IFlowOperator resolveFrom(Map resolved) { + return operator; + } + } + + /** + * 待回查形态:脚本只给出 {@code (人员id, 身份)},参与人对象需要从仓储回查。 + * + * @param key 参与人标识 + */ + record Pending(OperatorKey key) implements OperatorScriptElement { + + @Override + public boolean hasParticipant() { + return key.operatorId() > 0; + } + + @Override + public IFlowOperator resolveFrom(Map resolved) { + return resolved.get(key.key()); + } + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptResultResolver.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptResultResolver.java index f5c193fa..5d9ac9cb 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptResultResolver.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptResultResolver.java @@ -3,165 +3,79 @@ import com.codingapi.flow.exception.FlowValidationException; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorKey; -import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** - * 取人脚本返回值解析器(issue #303)。 + * 取人脚本返回值解析器(issue #303 / #311 P4)。 * - *

        负责把脚本返回值统一解析为 {@link IFlowOperator} 列表,是「脚本返回值 → 流程参与人」的唯一边界。 - * 支持三种元素形态,允许同一列表内混用,逐元素判定: - *

          - *
        1. {@link IFlowOperator} —— 直接采用,不回查,身份取对象自带的 {@code getIdentity()};
        2. - *
        3. {@link OperatorKey} —— 按身份分组批量回查,身份取 {@code key.identity()};
        4. - *
        5. {@link Number}(含纯数字字符串)—— 按默认身份批量回查,保持存量脚本行为。
        6. - *
        + *

        职责唯一:把脚本返回值解析为 {@link IFlowOperator} 列表,是 + * 「脚本返回值 → 流程参与人」的唯一边界。 * - *

        顶层允许非集合的单值(自动包装为单元素列表)与 {@code null}(视为无人员), - * 便于存量脚本 {@code return request.getCreatedOperatorId()} 继续可用。 + *

        依赖(仓储、脚本类型)经构造注入,一次构造完成一次解析: + *

        {@code
        + * new OperatorScriptResultResolver(holder, "operatorLoad").resolve(scriptResult);
        + * }
        + * 调用方不需要在多个重载之间做选择,也不需要每次把仓储再传一遍。 * - *

        非正数的人员 id(存量脚本用 {@code -1} 表示「无审批人」)视为「该元素无人员」,直接跳过, - * 不抛异常,保证「未匹配到审批人」仍由下游的异常处理逻辑接管。 - * - *

        回查按身份分组批量执行,避免逐个回查造成 N+1;结果按脚本返回顺序重排, - * 保证多人审批的执行顺序稳定。 + *

        解析分三步,每一步都由独立对象承载: + *

          + *
        1. 归一化:集合 / 数组 / 单值 / {@code null} 统一为元素列表;
        2. + *
        3. 元素化:每个元素判定为 {@link OperatorScriptElement.Direct}(直接采用) + * 或 {@link OperatorScriptElement.Pending}(按身份回查);
        4. + *
        5. 批量回查:{@link PendingOperators} 按身份分组一次查完,再按脚本返回顺序还原。
        6. + *
        + * 允许同一列表内混用三种形态;输出顺序与脚本返回一致,保证多人审批的执行顺序稳定。 * - * @see OperatorKey + * @see OperatorScriptElement + * @see PendingOperators */ public final class OperatorScriptResultResolver { - /** - * 默认脚本类型标识,仅用于异常上下文 - */ - private static final String DEFAULT_SCRIPT_TYPE = "operatorScript"; - - private OperatorScriptResultResolver() { - } + private final IRepositoryHolder repositoryHolder; /** - * 解析脚本返回值(从会话中取仓储)。 - * - * @param session 流程会话,不能为空 - * @param scriptResult 脚本返回值,支持集合 / 数组 / 单值 / {@code null} - * @return 流程参与人列表,顺序与脚本返回一致 + * 脚本类型标识,仅用于异常上下文 */ - public static List resolve(FlowSession session, Object scriptResult) { - return resolve(session.getRepositoryHolder(), scriptResult, DEFAULT_SCRIPT_TYPE); - } + private final String scriptType; /** - * 解析脚本返回值(从会话中取仓储,指定脚本类型用于异常上下文)。 - * - * @param session 流程会话 - * @param scriptResult 脚本返回值 - * @param scriptType 脚本类型标识 - * @return 流程参与人列表 + * @param repositoryHolder 仓储持有者,用于按身份回查参与人 + * @param scriptType 脚本类型标识(如 {@code operatorLoad} / {@code errorTrigger}),用于异常上下文 */ - public static List resolve(FlowSession session, Object scriptResult, String scriptType) { - return resolve(session.getRepositoryHolder(), scriptResult, scriptType); + public OperatorScriptResultResolver(IRepositoryHolder repositoryHolder, String scriptType) { + this.repositoryHolder = repositoryHolder; + this.scriptType = scriptType; } /** - * 解析脚本返回值(指定仓储)。 + * 解析脚本返回值。 * - * @param repositoryHolder 仓储持有者 - * @param scriptResult 脚本返回值 - * @return 流程参与人列表 - */ - public static List resolve(IRepositoryHolder repositoryHolder, Object scriptResult) { - return resolve(repositoryHolder, scriptResult, DEFAULT_SCRIPT_TYPE); - } - - /** - * 解析脚本返回值(指定仓储与脚本类型,用于异常上下文)。 - * - * @param repositoryHolder 仓储持有者 - * @param scriptResult 脚本返回值 - * @param scriptType 脚本类型标识(如 {@code operatorLoad} / {@code errorTrigger}) - * @return 流程参与人列表 + * @param scriptResult 脚本返回值,支持集合 / 数组 / 单值 / {@code null} + * @return 流程参与人列表,顺序与脚本返回一致 * @throws FlowValidationException 返回值中存在不支持的元素 */ - public static List resolve(IRepositoryHolder repositoryHolder, - Object scriptResult, - String scriptType) { - List elements = toElements(scriptResult); + public List resolve(Object scriptResult) { + List elements = parse(scriptResult); if (elements.isEmpty()) { return List.of(); } - - List slots = new ArrayList<>(elements.size()); - List pendingKeys = new ArrayList<>(); - for (Object element : elements) { - if (element == null) { - continue; - } - if (element instanceof IFlowOperator operator) { - if (!hasUserId(operator.getUserId())) { - continue; - } - slots.add(new Slot(operator, null)); - continue; - } - if (element instanceof OperatorKey key) { - if (!hasUserId(key.operatorId())) { - continue; - } - slots.add(new Slot(null, key)); - pendingKeys.add(key); - continue; - } - if (element instanceof Number number) { - long userId = toUserId(number, element, scriptType); - if (!hasUserId(userId)) { - continue; - } - OperatorKey key = OperatorKey.ofDefault(userId); - slots.add(new Slot(null, key)); - pendingKeys.add(key); - continue; + PendingOperators pendingOperators = new PendingOperators(repositoryHolder); + for (OperatorScriptElement element : elements) { + if (element instanceof OperatorScriptElement.Pending pending) { + pendingOperators.collect(pending.key()); } - if (element instanceof CharSequence text) { - String value = text.toString().trim(); - if (value.isEmpty()) { - continue; - } - if (!isNumeric(value)) { - throw FlowValidationException.operatorScriptResultInvalid( - scriptType, element.getClass().getName(), value); - } - long userId = parseUserId(value, element, scriptType); - if (!hasUserId(userId)) { - continue; - } - OperatorKey key = OperatorKey.ofDefault(userId); - slots.add(new Slot(null, key)); - pendingKeys.add(key); - continue; - } - throw FlowValidationException.operatorScriptResultInvalid( - scriptType, element.getClass().getName(), String.valueOf(element)); } + Map resolved = pendingOperators.load(); - if (slots.isEmpty()) { - return List.of(); - } - - Map resolved = batchResolve(repositoryHolder, pendingKeys); - List operators = new ArrayList<>(slots.size()); - for (Slot slot : slots) { - if (slot.operator() != null) { - operators.add(slot.operator()); - continue; - } - IFlowOperator operator = resolved.get(slot.key().key()); + List operators = new ArrayList<>(elements.size()); + for (OperatorScriptElement element : elements) { + IFlowOperator operator = element.resolveFrom(resolved); if (operator != null) { operators.add(operator); } @@ -170,40 +84,55 @@ public static List resolve(IRepositoryHolder repositoryHolder, } /** - * 按身份分组批量回查,返回以 {@link OperatorKey#key()} 为键的操作者索引。 - * - * @param repositoryHolder 仓储持有者 - * @param keys 待回查的操作者标识 - * @return 操作者索引 + * 把脚本返回值解析为元素列表,跳过「无人员」的元素。 */ - private static Map batchResolve(IRepositoryHolder repositoryHolder, - List keys) { - if (keys.isEmpty()) { - return Map.of(); + private List parse(Object scriptResult) { + List values = toValues(scriptResult); + List elements = new ArrayList<>(values.size()); + for (Object value : values) { + OperatorScriptElement element = toElement(value); + if (element != null && element.hasParticipant()) { + elements.add(element); + } } - Map> operatorIdsByIdentity = new LinkedHashMap<>(); - for (OperatorKey key : keys) { - operatorIdsByIdentity - .computeIfAbsent(key.identity(), identity -> new ArrayList<>()) - .add(key.operatorId()); + return elements; + } + + /** + * 单个返回值 → 元素;{@code null} 与空串返回 {@code null}(表示该元素无人员)。 + */ + private OperatorScriptElement toElement(Object value) { + if (value == null) { + return null; + } + if (value instanceof IFlowOperator operator) { + return new OperatorScriptElement.Direct(operator); + } + if (value instanceof OperatorKey key) { + return new OperatorScriptElement.Pending(key); + } + if (value instanceof Number number) { + return new OperatorScriptElement.Pending(OperatorKey.ofDefault(toUserId(number, value))); } - Map operatorMap = new HashMap<>(); - operatorIdsByIdentity.forEach((identity, operatorIds) -> { - List operators = repositoryHolder.findOperatorByIds(operatorIds, identity); - if (operators == null) { - return; + if (value instanceof CharSequence text) { + String trimmed = text.toString().trim(); + if (trimmed.isEmpty()) { + return null; } - for (IFlowOperator operator : operators) { - operatorMap.put(OperatorKey.of(operator.getUserId(), identity).key(), operator); + if (!isNumeric(trimmed)) { + throw FlowValidationException.operatorScriptResultInvalid( + scriptType, value.getClass().getName(), trimmed); } - }); - return operatorMap; + return new OperatorScriptElement.Pending(OperatorKey.ofDefault(parseUserId(trimmed, value))); + } + throw FlowValidationException.operatorScriptResultInvalid( + scriptType, value.getClass().getName(), String.valueOf(value)); } /** * 把脚本返回值归一化为元素列表:集合 / 数组 / 单值 / {@code null} */ - private static List toElements(Object scriptResult) { + private List toValues(Object scriptResult) { if (scriptResult == null) { return List.of(); } @@ -212,18 +141,18 @@ private static List toElements(Object scriptResult) { } if (scriptResult.getClass().isArray()) { int length = Array.getLength(scriptResult); - List elements = new ArrayList<>(length); + List values = new ArrayList<>(length); for (int i = 0; i < length; i++) { - elements.add(Array.get(scriptResult, i)); + values.add(Array.get(scriptResult, i)); } - return elements; + return values; } - List elements = new ArrayList<>(1); - elements.add(scriptResult); - return elements; + List values = new ArrayList<>(1); + values.add(scriptResult); + return values; } - private static long toUserId(Number number, Object element, String scriptType) { + private long toUserId(Number number, Object element) { double value = number.doubleValue(); long userId = number.longValue(); if (value != (double) userId) { @@ -233,7 +162,7 @@ private static long toUserId(Number number, Object element, String scriptType) { return userId; } - private static long parseUserId(String value, Object element, String scriptType) { + private long parseUserId(String value, Object element) { try { return Long.parseLong(value); } catch (NumberFormatException e) { @@ -242,15 +171,7 @@ private static long parseUserId(String value, Object element, String scriptType) } } - /** - * 是否为有效人员 id。非正数(如存量脚本用 {@code -1} 表示「无审批人」)视为「该元素无人员」, - * 直接跳过,保持历史行为并让下游继续走「未匹配到审批人」的异常处理。 - */ - private static boolean hasUserId(long userId) { - return userId > 0; - } - - private static boolean isNumeric(String value) { + private boolean isNumeric(String value) { if (value.isEmpty()) { return false; } @@ -265,10 +186,4 @@ private static boolean isNumeric(String value) { } return true; } - - /** - * 输出位置的占位:直接采用的对象,或待回查的标识 - */ - private record Slot(IFlowOperator operator, OperatorKey key) { - } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/PendingOperators.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/PendingOperators.java new file mode 100644 index 00000000..9e6dc06b --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/PendingOperators.java @@ -0,0 +1,74 @@ +package com.codingapi.flow.script.operator; + +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; +import com.codingapi.flow.session.IRepositoryHolder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * 待回查的参与人集合(issue #303 / #311 P4)。 + * + *

        负责「一批 {@link OperatorKey} → 一批 {@link IFlowOperator}」的回查: + * 先按身份分组,再一次批量查询,避免逐个回查造成 N+1;回查结果以 + * {@link OperatorKey#key()} 为键建立索引,供调用方按原顺序还原。 + * + *

        它替代了原先散在解析器里的 {@code batchResolve(...)} 私有函数: + * 键集合与仓储都是它自己的状态,因此只需一个公有入口 {@link #load()}。 + */ +final class PendingOperators { + + private final IRepositoryHolder repositoryHolder; + + /** + * 用有序集合去重:同一 {@code (人员, 身份)} 只查一次,且保持首次出现顺序 + */ + private final Set keys = new LinkedHashSet<>(); + + PendingOperators(IRepositoryHolder repositoryHolder) { + this.repositoryHolder = repositoryHolder; + } + + /** + * 收集待回查的参与人标识 + * + * @param key 参与人标识 + */ + void collect(OperatorKey key) { + keys.add(key); + } + + /** + * 按身份分组批量回查。 + * + * @return 参与人索引,键为 {@link OperatorKey#key()} + */ + Map load() { + if (keys.isEmpty()) { + return Map.of(); + } + Map> operatorIdsByIdentity = new LinkedHashMap<>(); + for (OperatorKey key : keys) { + operatorIdsByIdentity + .computeIfAbsent(key.identity(), identity -> new ArrayList<>()) + .add(key.operatorId()); + } + Map resolved = new HashMap<>(); + operatorIdsByIdentity.forEach((identity, operatorIds) -> { + List operators = repositoryHolder.findOperatorByIds(operatorIds, identity); + if (operators == null) { + return; + } + for (IFlowOperator operator : operators) { + resolved.put(OperatorKey.of(operator.getUserId(), identity).key(), operator); + } + }); + return resolved; + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java index b96f41ac..a63e01b2 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java @@ -12,6 +12,7 @@ import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentityGuard; +import com.codingapi.flow.operator.OperatorSelections; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.response.ActionResponse; import com.codingapi.flow.record.FlowRecord; @@ -104,16 +105,9 @@ public ActionResponse action() { FlowSession session = flowRecord.createFlowSession(this.repositoryHolder,workflow,currentOperator,createdOperator,currentOperator,formData,flowAdvice); // 校验并持久化 APPROVER_SELECT 节点的操作人分配(含可选人员范围校验) - if (flowAdvice.getOperatorSelectOperators() != null - && !flowAdvice.getOperatorSelectOperators().isEmpty()) { - // 携带身份的分配优先(issue #288 衍生 / #292) - OperatorAssignmentService.validateAndSaveOperators(session, flowRecord.getProcessId(), - flowAdvice.getOperatorSelectOperators()); - } else if (flowAdvice.getOperatorSelectMap() != null - && !flowAdvice.getOperatorSelectMap().isEmpty()) { - OperatorAssignmentService.validateAndSave(session, flowRecord.getProcessId(), - flowAdvice.getOperatorSelectMap()); - } + // 「携带身份的分配优先」这条规则由 OperatorSelections 统一判断(issue #288 衍生 / #292) + new OperatorAssignmentService(session).assign(flowRecord.getProcessId(), + OperatorSelections.of(flowAdvice.getOperatorSelectOperators(), flowAdvice.getOperatorSelectMap())); // 验证会话 currentNode.verifySession(session); 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 a1918a55..fa65fdb6 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 @@ -15,6 +15,7 @@ import com.codingapi.flow.node.nodes.StartNode; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentityGuard; +import com.codingapi.flow.operator.OperatorSelections; import com.codingapi.flow.pojo.request.FlowCreateRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.WorkflowService; @@ -94,19 +95,11 @@ public long create() { } // 校验并持久化 INITIATOR_SELECT 节点的操作人分配(含可选人员范围校验) - boolean hasSelectOperators = request.getOperatorSelectOperators() != null - && !request.getOperatorSelectOperators().isEmpty(); - boolean hasSelectIds = request.getOperatorSelectMap() != null - && !request.getOperatorSelectMap().isEmpty(); - if ((hasSelectOperators || hasSelectIds) && !flowRecords.isEmpty()) { + // 携带身份的分配优先:同一人员的两个身份是两项,不会被合并(issue #288 衍生 / #292) + if (!flowRecords.isEmpty()) { String processId = flowRecords.get(0).getProcessId(); - if (hasSelectOperators) { - // 携带身份的分配优先:同一人员的两个身份是两项,不会被合并(issue #288 衍生 / #292) - OperatorAssignmentService.validateAndSaveOperators(session, processId, - request.getOperatorSelectOperators()); - } else { - OperatorAssignmentService.validateAndSave(session, processId, request.getOperatorSelectMap()); - } + new OperatorAssignmentService(session).assign(processId, + OperatorSelections.of(request.getOperatorSelectOperators(), request.getOperatorSelectMap())); } repositoryHolder.saveRecords(flowRecords); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/OperatorAssignmentService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/OperatorAssignmentService.java index e7a4e5c7..d6849c3e 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/OperatorAssignmentService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/OperatorAssignmentService.java @@ -4,26 +4,44 @@ import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorKey; +import com.codingapi.flow.operator.OperatorSelections; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowAdvice; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; import com.codingapi.flow.workflow.Workflow; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** - * 操作人分配服务 - *

        - * 负责发起人设定 / 审批人设定时的操作人分配落库,并在节点配置了可选人员范围时校验所选人员是否越界。 + * 操作人分配服务。 + * + *

        职责:发起人设定 / 审批人设定时,校验并落库操作人分配;节点配置了可选人员范围时, + * 校验所选人员是否越界。 + * + *

        依赖(流程会话、仓储、工作流)经构造注入:分配总是发生在「某次流程操作」之内, + * 会话就是这个操作的上下文,因此不需要每次调用再传一遍。 + * + *

        两个公有入口各对应一个动作: + *

          + *
        • {@link #hasAssignment(String)} —— 该节点是否已经设定操作人;
        • + *
        • {@link #assign(String)} —— 校验并保存本次分配。
        • + *
        + * 「携带身份的分配优先于仅人员 id 的分配」这条规则收在 {@link #selections()} 里, + * 调用方不再自己 if/else 二选一。 */ public class OperatorAssignmentService { - private OperatorAssignmentService() { + private final FlowSession session; + + /** + * @param session 当前流程会话,分配所依据的上下文 + */ + public OperatorAssignmentService(FlowSession session) { + this.session = session; } /** @@ -38,18 +56,11 @@ private OperatorAssignmentService() { * 只检查第 1 项会把「发起时预置的分配」和「按身份设定的分配」误判为未设定, * 使 {@code PassAction} 反复返回 OPERATOR_SELECT,流程停滞在开始节点。 * - * @param session 当前流程会话 - * @param nodeId 节点 ID + * @param nodeId 节点 ID * @return 是否已设定操作人 */ - public static boolean hasAssignment(FlowSession session, String nodeId) { - FlowAdvice advice = session.getAdvice(); - Map> idSelections = advice.getOperatorSelectMap(); - if (idSelections != null && idSelections.get(nodeId) != null && !idSelections.get(nodeId).isEmpty()) { - return true; - } - Map> selections = advice.getOperatorSelectOperators(); - if (selections != null && selections.get(nodeId) != null && !selections.get(nodeId).isEmpty()) { + public boolean hasAssignment(String nodeId) { + if (currentSelections().hasSelection(nodeId)) { return true; } FlowRecord currentRecord = session.getCurrentRecord(); @@ -62,68 +73,59 @@ public static boolean hasAssignment(FlowSession session, String nodeId) { } /** - * 校验并保存操作人分配(仅人员 id,默认身份)。 + * 校验并保存本次操作人分配。 * - * @param baseSession 基准会话,用于派生目标节点会话以执行范围脚本 - * @param processId 流程实例ID - * @param operatorSelectMap 节点ID -> 选定的操作人ID列表 - */ - public static void validateAndSave(FlowSession baseSession, String processId, - Map> operatorSelectMap) { - if (operatorSelectMap == null || operatorSelectMap.isEmpty()) { - return; - } - Map> selections = new LinkedHashMap<>(); - operatorSelectMap.forEach((nodeId, operatorIds) -> - selections.put(nodeId, operatorIds.stream().map(OperatorKey::ofDefault).toList())); - validateAndSaveOperators(baseSession, processId, selections); - } - - /** - * 校验并保存操作人分配,携带身份(issue #288 衍生 / #292)。 - *

        - * 数量校验:节点配置了最大可选人数(maxOperatorCount >= 0)时,所选人数超过上限则抛出异常。 + *

        数量校验:节点配置了最大可选人数(maxOperatorCount ≥ 0)时,所选人数超过上限则抛出异常。 * 当目标节点配置了可选人员范围(范围非空)时,校验所选人员是否全部落在范围内,越界则抛出异常; * 范围为空(未配置脚本或脚本执行结果为空)表示不限范围,跳过校验。 - *

        - * 同一人员的两个身份是两项参与人,不做合并;完全相同的 {@code (人员id, 身份)} 会被去重。 * - * @param baseSession 基准会话,用于派生目标节点会话以执行范围脚本 - * @param processId 流程实例ID - * @param operatorSelectOperators 节点ID -> 选定的操作人列表(含身份) + *

        同一人员的两个身份是两项参与人,不做合并;完全相同的 {@code (人员id, 身份)} 会被去重。 + * + * @param processId 流程实例 ID + * @param selections 本次请求的选择集合(发起与办理两条路径来源不同,因此显式传入) */ - public static void validateAndSaveOperators(FlowSession baseSession, String processId, - Map> operatorSelectOperators) { - if (operatorSelectOperators == null || operatorSelectOperators.isEmpty()) { + public void assign(String processId, OperatorSelections selections) { + if (selections == null || selections.isEmpty()) { return; } - Workflow workflow = baseSession.getWorkflow(); - IRepositoryHolder repositoryHolder = baseSession.getRepositoryHolder(); - operatorSelectOperators.forEach((nodeId, operators) -> { - if (operators == null || operators.isEmpty()) { - return; + Workflow workflow = session.getWorkflow(); + IRepositoryHolder repositoryHolder = session.getRepositoryHolder(); + for (String nodeId : selections.nodeIds()) { + List selected = selections.of(nodeId).stream().distinct().toList(); + if (selected.isEmpty()) { + continue; } - List selections = operators.stream().distinct().toList(); IFlowNode node = workflow.getFlowNode(nodeId); // 校验可选人数上限(-1 表示不限制) int maxOperatorCount = node.strategyManager().getMaxOperatorCount(); - if (maxOperatorCount >= 0 && selections.size() > maxOperatorCount) { + if (maxOperatorCount >= 0 && selected.size() > maxOperatorCount) { throw FlowValidationException.operatorCountExceeded(nodeId, maxOperatorCount); } List range = node.strategyManager() - .loadOperatorRange(baseSession.updateSession(node)); + .loadOperatorRange(session.updateSession(node)); if (range != null && !range.isEmpty()) { // 范围校验按人员 id 判定:范围表达的是「可选哪些人」,不区分身份 Set allowedIds = range.stream() .map(IFlowOperator::getUserId) .collect(Collectors.toSet()); - for (OperatorKey operator : selections) { + for (OperatorKey operator : selected) { if (!allowedIds.contains(operator.operatorId())) { throw FlowValidationException.operatorOutOfRange(nodeId); } } } - repositoryHolder.saveOperatorAssignments(processId, nodeId, selections); - }); + repositoryHolder.saveOperatorAssignments(processId, nodeId, selected); + } + } + + /** + * 会话当前携带的选择(办理路径的会话一定带意见;发起路径可能没有) + */ + private OperatorSelections currentSelections() { + FlowAdvice advice = session.getAdvice(); + if (advice == null) { + return OperatorSelections.empty(); + } + return OperatorSelections.of(advice.getOperatorSelectOperators(), advice.getOperatorSelectMap()); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/session/FlowSession.java b/flow-engine-framework/src/main/java/com/codingapi/flow/session/FlowSession.java index 465221ff..d5a6c94d 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/session/FlowSession.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/session/FlowSession.java @@ -183,7 +183,7 @@ public List loadPreviousNodeOperators() { .distinct() .sorted(Comparator.comparingLong(OperatorKey::operatorId).thenComparing(OperatorKey::identity)) .toList(); - return OperatorScriptResultResolver.resolve(repositoryHolder, operatorKeys, "previousNode"); + return new OperatorScriptResultResolver(repositoryHolder, "previousNode").resolve(operatorKeys); } /** diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java b/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java index 1af2c12c..f45b25c8 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java @@ -82,7 +82,7 @@ public OperatorManager loadOperators(FlowSession flowSession) { */ private List loadAssignedOperators(IRepositoryHolder repositoryHolder, List assignedOperators) { - return OperatorScriptResultResolver.resolve(repositoryHolder, assignedOperators, "operatorAssignment"); + return new OperatorScriptResultResolver(repositoryHolder, "operatorAssignment").resolve(assignedOperators); } /** diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorSelectionsTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorSelectionsTest.java new file mode 100644 index 00000000..07d19c49 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorSelectionsTest.java @@ -0,0 +1,84 @@ +package com.codingapi.flow.operator; + +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +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.assertTrue; + +/** + * 操作人选择集合测试(#311 P4)。 + * + *

        锁住「携带身份的分配优先」这条业务规则:它只能有一个定义点, + * 否则调用方各自 if/else,一旦不一致就会出现「带身份的设定被静默忽略」。 + */ +class OperatorSelectionsTest { + + @Test + void should_prefer_identity_carrying_selections_over_ids() { + Map> byOperators = Map.of("node1", List.of(OperatorKey.of(1, "department1"))); + Map> byIds = Map.of("node2", List.of(2L)); + + OperatorSelections selections = OperatorSelections.of(byOperators, byIds); + + assertTrue(selections.hasSelection("node1")); + assertFalse(selections.hasSelection("node2"), "携带身份的分配非空时,仅 id 的分配整体忽略"); + assertEquals(1, selections.nodeIds().size()); + } + + @Test + void should_convert_ids_to_default_identity_when_identity_absent() { + Map> byIds = new LinkedHashMap<>(); + byIds.put("node1", List.of(2L, 3L)); + + OperatorSelections selections = OperatorSelections.of(null, byIds); + + assertEquals(List.of(OperatorKey.ofDefault(2), OperatorKey.ofDefault(3)), selections.of("node1")); + assertTrue(selections.of("node1").stream().allMatch(key -> key.identity().isEmpty())); + } + + @Test + void should_be_empty_when_both_forms_absent() { + assertTrue(OperatorSelections.of(null, null).isEmpty()); + assertTrue(OperatorSelections.of(Map.of(), Map.of()).isEmpty()); + assertTrue(OperatorSelections.empty().isEmpty()); + assertFalse(OperatorSelections.empty().hasSelection("node1")); + assertTrue(OperatorSelections.empty().of("node1").isEmpty()); + } + + @Test + void should_skip_empty_node_selections() { + Map> byIds = new LinkedHashMap<>(); + byIds.put("node1", List.of()); + byIds.put("node2", List.of(5L)); + + OperatorSelections selections = OperatorSelections.of(null, byIds); + + assertFalse(selections.hasSelection("node1")); + assertEquals(List.of("node2"), List.copyOf(selections.nodeIds())); + } + + @Test + void should_not_merge_two_identities_of_same_user() { + OperatorSelections selections = OperatorSelections.of( + Map.of("node1", List.of(OperatorKey.of(1, "department1"), OperatorKey.of(1, "department2"))), + null); + + assertEquals(2, selections.of("node1").size(), "同一人的两个身份是两项参与人,不做合并"); + } + + @Test + void should_keep_selected_operators_untouched() { + IFlowOperator department1 = User.withIdentity(1, "user1", "department1"); + + OperatorSelections selections = OperatorSelections.of( + Map.of("node1", List.of(OperatorKey.of(department1))), null); + + assertEquals(OperatorKey.of(1, "department1"), selections.of("node1").get(0)); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptElementTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptElementTest.java new file mode 100644 index 00000000..1ca76657 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptElementTest.java @@ -0,0 +1,66 @@ +package com.codingapi.flow.script.operator; + +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 脚本返回元素测试(#311 P4)。 + * + *

        元素只回答两个问题:我是否指向一个有效参与人、我从回查结果里对应谁。 + * 解析主流程因此不再需要 {@code instanceof} 分支。 + */ +class OperatorScriptElementTest { + + @Test + void should_treat_direct_operator_as_participant_only_when_user_id_positive() { + assertTrue(new OperatorScriptElement.Direct(User.withIdentity(1, "user1", "department1")).hasParticipant()); + assertFalse(new OperatorScriptElement.Direct(new User(0, "nobody")).hasParticipant()); + assertFalse(new OperatorScriptElement.Direct(new User(-1, "none")).hasParticipant()); + } + + @Test + void should_treat_pending_key_as_participant_only_when_user_id_positive() { + assertTrue(new OperatorScriptElement.Pending(OperatorKey.of(1, "department1")).hasParticipant()); + assertFalse(new OperatorScriptElement.Pending(OperatorKey.ofDefault(0)).hasParticipant()); + assertFalse(new OperatorScriptElement.Pending(OperatorKey.ofDefault(-1)).hasParticipant()); + } + + @Test + void should_return_direct_operator_without_lookup() { + IFlowOperator operator = User.withIdentity(1, "user1", "department1"); + + IFlowOperator resolved = new OperatorScriptElement.Direct(operator).resolveFrom(Map.of()); + + assertSame(operator, resolved); + } + + @Test + void should_lookup_pending_key_by_participant_key() { + IFlowOperator operator = User.withIdentity(1, "user1", "department1"); + OperatorScriptElement.Pending pending = new OperatorScriptElement.Pending(OperatorKey.of(1, "department1")); + + assertSame(operator, pending.resolveFrom(Map.of(OperatorKey.of(1, "department1").key(), operator))); + assertNull(pending.resolveFrom(Map.of()), "回查不到时返回 null,由调用方跳过"); + } + + @Test + void should_distinguish_two_identities_of_same_user_when_resolving() { + IFlowOperator department1 = User.withIdentity(1, "user1", "department1"); + IFlowOperator department2 = User.withIdentity(1, "user1", "department2"); + Map resolved = Map.of( + OperatorKey.of(1, "department1").key(), department1, + OperatorKey.of(1, "department2").key(), department2); + + assertSame(department1, new OperatorScriptElement.Pending(OperatorKey.of(1, "department1")).resolveFrom(resolved)); + assertSame(department2, new OperatorScriptElement.Pending(OperatorKey.of(1, "department2")).resolveFrom(resolved)); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java index 257ff554..41c35c37 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java @@ -48,7 +48,7 @@ void setUp() { */ @Test void should_keep_default_identity_and_order_when_script_returns_user_ids() { - List operators = OperatorScriptResultResolver.resolve( + List operators = resolve( countingHolder.proxy(), List.of(2L, 1L)); assertEquals(2, operators.size()); @@ -63,7 +63,7 @@ void should_keep_default_identity_and_order_when_script_returns_user_ids() { */ @Test void should_apply_identity_when_script_returns_operator_keys() { - List operators = OperatorScriptResultResolver.resolve( + List operators = resolve( countingHolder.proxy(), List.of(OperatorKey.of(2, "department1"), OperatorKey.of(1, null))); @@ -81,7 +81,7 @@ void should_apply_identity_when_script_returns_operator_keys() { void should_use_operator_instance_directly_without_query() { IFlowOperator operator = User.withIdentity(2, "张三", "department1"); - List operators = OperatorScriptResultResolver.resolve( + List operators = resolve( countingHolder.proxy(), List.of(operator)); assertEquals(1, operators.size()); @@ -97,7 +97,7 @@ void should_use_operator_instance_directly_without_query() { void should_resolve_mixed_forms_and_keep_script_order() { IFlowOperator direct = User.withIdentity(1, "lorne", "department3"); - List operators = OperatorScriptResultResolver.resolve( + List operators = resolve( countingHolder.proxy(), Arrays.asList(2L, OperatorKey.of(1, "department2"), direct)); @@ -115,7 +115,7 @@ void should_resolve_mixed_forms_and_keep_script_order() { */ @Test void should_wrap_single_value_as_single_element() { - List operators = OperatorScriptResultResolver.resolve(countingHolder.proxy(), 2L); + List operators = resolve(countingHolder.proxy(), 2L); assertEquals(1, operators.size()); assertEquals(2, operators.get(0).getUserId()); @@ -126,8 +126,8 @@ void should_wrap_single_value_as_single_element() { */ @Test void should_return_empty_when_result_is_null_or_empty() { - assertTrue(OperatorScriptResultResolver.resolve(countingHolder.proxy(), null).isEmpty()); - assertTrue(OperatorScriptResultResolver.resolve(countingHolder.proxy(), List.of()).isEmpty()); + assertTrue(resolve(countingHolder.proxy(), null).isEmpty()); + assertTrue(resolve(countingHolder.proxy(), List.of()).isEmpty()); } /** @@ -135,7 +135,7 @@ void should_return_empty_when_result_is_null_or_empty() { */ @Test void should_skip_null_elements() { - List operators = OperatorScriptResultResolver.resolve( + List operators = resolve( countingHolder.proxy(), Arrays.asList(null, 2L)); assertEquals(1, operators.size()); @@ -147,7 +147,7 @@ void should_skip_null_elements() { */ @Test void should_not_merge_same_user_with_different_identity() { - List operators = OperatorScriptResultResolver.resolve( + List operators = resolve( countingHolder.proxy(), List.of(OperatorKey.of(1, "department1"), OperatorKey.of(1, "department2"))); @@ -162,7 +162,7 @@ void should_not_merge_same_user_with_different_identity() { @Test void should_throw_validation_exception_when_element_unsupported() { FlowValidationException exception = assertThrows(FlowValidationException.class, - () -> OperatorScriptResultResolver.resolve(countingHolder.proxy(), List.of(new Object()))); + () -> resolve(countingHolder.proxy(), List.of(new Object()))); assertTrue(exception.getMessage().contains("java.lang.Object"), "异常消息应包含不支持的元素类型,实际:" + exception.getMessage()); @@ -175,7 +175,7 @@ void should_throw_validation_exception_when_element_unsupported() { */ @Test void should_parse_numeric_string_as_user_id() { - List operators = OperatorScriptResultResolver.resolve( + List operators = resolve( countingHolder.proxy(), List.of("2")); assertEquals(1, operators.size()); @@ -188,7 +188,7 @@ void should_parse_numeric_string_as_user_id() { */ @Test void should_skip_non_positive_user_id() { - List operators = OperatorScriptResultResolver.resolve( + List operators = resolve( countingHolder.proxy(), List.of(-1L, 2L)); assertEquals(1, operators.size()); @@ -200,7 +200,7 @@ void should_skip_non_positive_user_id() { */ @Test void should_query_in_batches_grouped_by_identity() { - OperatorScriptResultResolver.resolve(countingHolder.proxy(), List.of( + resolve(countingHolder.proxy(), List.of( OperatorKey.of(1, "department1"), OperatorKey.of(2, "department1"), OperatorKey.of(1, "department2"), @@ -210,6 +210,13 @@ void should_query_in_batches_grouped_by_identity() { assertEquals(0, countingHolder.singleQueryCount); } + /** + * 一次解析 = 一个解析器实例:仓储经构造注入,调用方只传返回值 + */ + private static List resolve(IRepositoryHolder repositoryHolder, Object scriptResult) { + return new OperatorScriptResultResolver(repositoryHolder, "operatorLoad").resolve(scriptResult); + } + /** * 统计回查次数的仓储代理,用于断言「对象形态不回查」与「按身份分组批量回查」 */ From 28a4d6a8e4e259c2edbe5bffb7a59e617a78e1fa Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Thu, 3 Dec 2026 18:05:39 +0800 Subject: [PATCH 31/35] =?UTF-8?q?refactor(operator):=20OperatorIdentity=20?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E5=80=BC=E5=AF=B9=E8=B1=A1=EF=BC=8C=E8=BA=AB?= =?UTF-8?q?=E4=BB=BD=E8=A7=A3=E6=9E=90=E4=B8=8E=E5=91=8A=E8=AD=A6=E7=A7=BB?= =?UTF-8?q?=E5=87=BA=E9=A2=86=E5=9F=9F=E5=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P5 类型化(#311): - OperatorIdentity:静态工具类 + 常量集合 → 不可变值对象(of / value / isDefault / validate / equals) - 归一化、判等、校验收为实例语义,全仓调用点迁移为 of(x).value() / .isDefault() / .equals(...) - OperatorIdentity.pick 与三个请求头常量移入接入层 OperatorIdentityHeader(starter-api), 查询侧复用同一份常量(query → api 依赖) - OperatorIdentityGuard → diagnostic.OperatorIdentityWarnLog:可观测性组件移出领域包, 去重状态由静态集合改为实例字段,删除测试专用 resetWarnedCache() - 规范文档同步落地记录与 API 变更清单 行为零变化:全仓 6 个模块测试通过(framework 554)。 Refs #311 --- docs/conventions/domain/operator-identity.md | 85 +++++++--- .../gateway/impl/FlowOperatorGatewayImpl.java | 8 +- .../action/actions/ReduceAuditAction.java | 2 +- .../cache/FlowOperatorLocalThreadCache.java | 10 +- .../flow/context/GatewayContext.java | 12 +- .../OperatorIdentityWarnLog.java} | 54 ++++--- .../flow/manager/WorkflowStrategyManager.java | 2 +- .../FlowRecordRepositoryMockImpl.java | 8 +- .../FlowTodoRecordRepositoryMockImpl.java | 4 +- .../codingapi/flow/node/BaseAuditNode.java | 4 +- .../flow/operator/IFlowOperator.java | 2 +- .../flow/operator/OperatorIdentity.java | 147 +++++++++--------- .../codingapi/flow/operator/OperatorKey.java | 10 +- .../flow/pojo/body/FlowAdviceBody.java | 2 +- .../flow/pojo/request/FlowDeleteRequest.java | 2 +- .../flow/pojo/request/FlowDetailRequest.java | 4 +- .../pojo/request/FlowProcessNodeRequest.java | 4 +- .../flow/pojo/request/FlowRevokeRequest.java | 2 +- .../flow/pojo/request/FlowUrgeRequest.java | 2 +- .../flow/pojo/response/FlowOperator.java | 6 +- .../flow/pojo/response/FlowRecordContent.java | 14 +- .../com/codingapi/flow/record/FlowRecord.java | 24 +-- .../codingapi/flow/record/FlowTodoRecord.java | 6 +- .../script/request/GroovyScriptRequest.java | 12 +- .../flow/service/impl/FlowActionService.java | 6 +- .../flow/service/impl/FlowCreateService.java | 4 +- .../service/impl/FlowProcessNodeService.java | 4 +- .../cache/FlowOperatorBulkIdentityTest.java | 8 +- .../OperatorIdentityWarnLogTest.java | 65 ++++++++ .../flow/gateway/impl/UserGateway.java | 4 +- .../FlowRecordQueryMockIdentityTest.java | 2 +- .../operator/OperatorIdentityGuardTest.java | 59 ------- .../flow/operator/OperatorIdentityTest.java | 24 +-- .../OperatorIdentityValidationTest.java | 14 +- .../script/node/OperatorLoadScriptTest.java | 4 +- .../OperatorScriptResultResolverTest.java | 10 +- .../request/GroovyScriptBindIdentityTest.java | 14 +- .../FlowOperatorIdentityRecordTest.java | 2 +- .../HandleOperatorIdentityFlowTest.java | 6 +- .../java/com/codingapi/flow/user/User.java | 2 +- .../flow/api/OperatorIdentityHeader.java | 49 ++++++ .../api/controller/FlowRecordController.java | 11 +- .../flow/api/OperatorIdentityHeaderTest.java | 23 +-- .../convert/FlowRecordContentConvertor.java | 14 +- .../infra/convert/FlowRecordConvertor.java | 24 +-- .../convert/FlowTodoRecordConvertor.java | 12 +- .../FlowOperatorAssignmentRepositoryImpl.java | 2 +- flow-engine-starter-query/pom.xml | 6 + .../controller/FlowRecordQueryController.java | 19 +-- .../service/FlowRecordQueryServiceImpl.java | 6 +- 50 files changed, 472 insertions(+), 348 deletions(-) rename flow-engine-framework/src/main/java/com/codingapi/flow/{operator/OperatorIdentityGuard.java => diagnostic/OperatorIdentityWarnLog.java} (52%) create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/diagnostic/OperatorIdentityWarnLogTest.java delete mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityGuardTest.java create mode 100644 flow-engine-starter-api/src/main/java/com/codingapi/flow/api/OperatorIdentityHeader.java rename flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityHeaderResolveTest.java => flow-engine-starter-api/src/test/java/com/codingapi/flow/api/OperatorIdentityHeaderTest.java (69%) diff --git a/docs/conventions/domain/operator-identity.md b/docs/conventions/domain/operator-identity.md index 24c1fef6..7b262f16 100644 --- a/docs/conventions/domain/operator-identity.md +++ b/docs/conventions/domain/operator-identity.md @@ -16,7 +16,7 @@ #297 的实际故障(能审批却不能撤回)就是同一个语义出现两个答案的直接后果:审批路径按 `(id, 身份)` 判,撤回路径按 `id` 判。 -## 现状:一个语义,多处置实现 +## 改造前的现状(记录用:一个语义,多处置实现) ### 参与人键(拼字符串)5 处,分隔符 4 份声明 @@ -56,6 +56,8 @@ **结论**:这一族类的病根不是「用了静态方法」,是**身份没有成为类型**。形态问题只是症状。 +> 上述问题已在 `refactor/operator-identity` 分支按 P1~P5 处理完毕,落地结果见文末「落地记录」。 + ## 契约 ### H1 参与人标识必须成对传递 @@ -84,32 +86,37 @@ OperatorKey#key() 待办合并键是复合键(参与人 + 运行时 + 节点),由独立的键模型回答,不复用 `key()`,但同样只能有一个定义点。 -### H4 匹配模式只能改变判定,不能改变存储键格式 +### H4 匹配模式影响键时,必须经由键模型 + +匹配模式确实会改变存储键的语义:`USER_ONLY` 下同一人的两个身份必须合并成一条待办,`STRICT` 下必须分开。这是业务事实,不可能靠「禁止」消除。 -匹配模式是**运行时配置**,不得直接参与持久化键的构造。 +因此本条的约束不是「不许影响」,而是**影响的方式必须唯一且集中**: -当前 `FlowRecord#getTodoKey()` 与 `FlowContent` 都在方法体里读 `matchMode()` 并切换键格式——等于「重启改配置,历史数据的待办合并语义就变了」,而且不可逆。P2 的处置: +1. 键格式(含是否追加身份后缀)只允许在键模型内部决定,业务类不得在方法体里读 `matchMode()` 后自己拼字符串; +2. 键模型只接收一个布尔语义(`OperatorIdentityMatchMode#identityDistinguishes()`),不接收整个模式再自己分支; +3. 迁移服务必须复用同一个键模型,避免「拼法与迁移不同源」——历史上模式切换导致合并组一分为二、需要重建快照,根因就是这一点。 -1. 把「键是否含身份」下沉到键模型内部,作为一条显式规则(默认身份不加后缀,保证存量键不断裂); -2. 业务类不再自己判断模式; -3. 迁移服务复用同一个键模型,避免「拼法与迁移不同源」。 +落地:`OperatorKey#key(mode)` 与 `TodoMergeKey#value()` 是两个键格式的唯一定义点。 ### H5 命名即契约(本域) -| 名字 | 必须是什么 | 当前状态 | +| 名字 | 必须是什么 | 状态 | |---|---|---| -| `OperatorIdentity` | 身份值对象(不可变,`of` 构造,`equals` 判等) | 名不副实:静态工具类 + 常量集合(P5) | -| `OperatorKey` | 参与人标识值对象,承载 `matches` 与 `key` | 形态对,能力缺(P1/P2) | -| `OperatorIdentityMatchMode` | 策略:自己回答 `match` | 名不副实:被外部 `if` 判断的枚举(P3) | -| `OperatorIdentityContext` | 全局配置持有(可变单例) | 名称错位:现在叫 `OperatorIdentityPolicy`(P3) | -| `OperatorManager` | 参与人集合,一个查找入口 | 有默认身份重载,入口未收敛(P1) | -| `OperatorIdentityGuard` | —— | 名不副实:告警去重属可观测性,不属领域(P5 移出) | +| `OperatorIdentity` | 身份值对象(不可变,`of` 构造,`value()` 取值,`equals` 判等) | ✅ 已改造 | +| `OperatorKey` | 参与人标识值对象,承载 `matches` / `key(mode)` / `identityEquals` | ✅ 已改造 | +| `OperatorSelections` | 操作人选择集合,收口「带身份优先于仅 id」 | ✅ 新增 | +| `TodoMergeKey` | 待办合并键(复合键),键格式唯一定义点 | ✅ 新增 | +| `OperatorIdentityMatchMode` | 策略:自己回答 `match` 与 `identityDistinguishes` | ✅ 已改造 | +| `OperatorIdentityContext` | 全局配置持有(可变单例),原 `OperatorIdentityPolicy` | ✅ 已改造 | +| `OperatorManager` | 参与人集合,一个查询入口 `match(IFlowOperator)` | ✅ 已改造 | +| `OperatorIdentityHeader` | 请求头契约与「头优先于 query」解析,位于接入层 | ✅ 已移出 | +| `OperatorIdentityWarnLog` | 身份透传告警(可观测性),去重状态归属实例 | ✅ 已移出 | ### H6 分层:身份解析属接入层 `OperatorIdentity#pick(headerValue, parameterValue, parameterPresent)` 实现的是「请求头优先于 query」的 HTTP 约定,属接入层。放在 domain 包里,等于让领域模型知道 HTTP 头存在,违反「换掉 Web 框架业务模型零改动」。 -P5 移到 `flow-engine-starter-api`,`OperatorIdentityTest` / `OperatorIdentityHeaderResolveTest` 随之迁移。 +P5 移到 `flow-engine-starter-api` 的 `com.codingapi.flow.api.OperatorIdentityHeader`,`OperatorIdentityHeaderTest` 随之迁移;查询侧复用同一份常量(`flow-engine-starter-query` 依赖 `flow-engine-starter-api`)。 ## 判定流程(提交前四问) @@ -126,12 +133,12 @@ P5 移到 `flow-engine-starter-api`,`OperatorIdentityTest` / `OperatorIdentity | 批次 | 范围 | 行为变化 | 验收 | |---|---|---|---| -| **P0**(本次) | 本文档 + 索引 + `AGENTS.md` / `CLAUDE.md` 一条指向 | 无(零代码) | 文档评审通过 | -| **P1 相等收敛** | `OperatorKey` 增 `matches`;`Policy#matches`、`Policy#sameOperator`、`OperatorManager`、`FlowOperatorLocalThreadCache#isIdentityMatched` 全部委托;`OperatorManager` 去掉默认身份重载 | 无 | 32 个身份相关测试类断言零修改 | -| **P2 键收敛** | `OperatorKey#key()` 成为唯一参与人键生成点;cache / guard / `FlowContent` 改用它;分隔符常量收敛为 1 份;新增待办合并键模型,`FlowRecord#getTodoKey()` 委托它 | 无(键值逐个比对) | `FlowTodoKeyIdentityTest`、`FlowOperatorBulkIdentityTest`、`FlowRecordIdentityConvertorTest` 零修改 | -| **P3 模式策略化** | `OperatorIdentityMatchMode` 实现 `match`;`OperatorIdentityPolicy` → `OperatorIdentityContext`;`reset()` → `use(mode)` | 无(`use` 仅影响测试写法) | `OperatorIdentityPolicyTest` 改名适配 | -| **P4 对象化** | `OperatorScriptResultResolver`(#308)、`OperatorAssignmentService` 改构造注入 | 无 | 见 #308 的 7 条契约 | -| **P5 类型化** | `OperatorIdentity` → 值对象;`pick` 移接入层;`Guard` 移出领域包 | 公开 API 变更,需版本说明 | 全量测试 + 集成方迁移说明 | +| **P0** ✅ | 本文档 + 索引 + `AGENTS.md` / `CLAUDE.md` 一条指向 | 无(零代码) | 文档评审通过 | +| **P1 相等收敛** ✅ | `OperatorKey` 增 `matches`;`Policy#matches`、`Policy#sameOperator`、`OperatorManager`、`FlowOperatorLocalThreadCache#isIdentityMatched` 全部委托;`OperatorManager` 去掉默认身份重载 | 无 | 32 个身份相关测试类断言零修改 | +| **P2 键收敛** ✅ | `OperatorKey#key()` 成为唯一参与人键生成点;cache / guard / `FlowContent` 改用它;分隔符常量收敛为 1 份;新增待办合并键模型,`FlowRecord#getTodoKey()` 委托它 | 无(键值逐个比对) | `FlowTodoKeyIdentityTest`、`FlowOperatorBulkIdentityTest`、`FlowRecordIdentityConvertorTest` 零修改 | +| **P3 模式策略化** ✅ | `OperatorIdentityMatchMode` 实现 `match`;`OperatorIdentityPolicy` → `OperatorIdentityContext`;`reset()` → `use(mode)` | 无(`use` 仅影响测试写法) | `OperatorIdentityPolicyTest` 改名适配 | +| **P4 对象化** ✅ | `OperatorScriptResultResolver`(#308)、`OperatorAssignmentService` 改构造注入 | 无 | 见 #308 的 7 条契约 | +| **P5 类型化** ✅ | `OperatorIdentity` → 值对象;`pick` 移接入层;`Guard` 移出领域包 | 公开 API 变更,需版本说明 | 全量测试 + 集成方迁移说明 | **P1~P4 统一验收口径**:`./mvnw test` 全绿,且现有测试的**断言一行不改**。改断言等于改行为契约,必须单独说明理由。 @@ -148,3 +155,39 @@ P5 移到 `flow-engine-starter-api`,`OperatorIdentityTest` / `OperatorIdentity - 多身份引入 #288 · 参与人二元标识 #290 · 分配携带身份 #292 · 批量按身份回取 #293 · 身份透传告警 #294 · 匹配策略 #297 · 身份请求头 #301 · 脚本返回值多形态 #303 - #308 解析器对象化(P4)· #309 存量盘点(本契约覆盖其中 4 项)· #310 模型设计三层法 + +## 落地记录(P1~P5,`refactor/operator-identity`) + +### 语义收敛 + +| 原来 | 现在 | +|---|---| +| 5 处拼参与人键、4 份分隔符声明 | `OperatorKey#key(mode)` 唯一定义,分隔符常量 1 份(U+0001) | +| 5 处判「是否同一人」 | `OperatorKey#matches(other, mode)` 唯一入口,`OperatorIdentityMatchMode` 是策略 | +| `FlowRecord#getTodoKey()` 手拼合并键 | `TodoMergeKey#value()` 唯一定义,`FlowRecord` 只决定「谁参与合并」 | +| 4 个服务各自 `if (!matches(...)) throw` | `FlowRecord#verifyOperator(OperatorKey)` | +| `FlowActionService` / `FlowCreateService` 各自 if-else 二选一 | `OperatorSelections` 收口「带身份优先」 | +| `FlowContent` 判断模式后拼去重键 | `OperatorKey#key(mode)` | + +### API 变更(集成方需注意) + +| 变更 | 影响 | +|---|---| +| `OperatorIdentity` 由静态工具类改为值对象 | `normalize(x)` → `of(x).value()`;`isDefault(x)` → `of(x).isDefault()`;`same(a,b)` → `of(a).equals(of(b))`;`validate(x)` → `of(x).validate().value()`;`DEFAULT` 取字符串用 `DEFAULT.value()` | +| `OperatorIdentityPolicy` → `OperatorIdentityContext` | `setMatchMode(m)` → `getInstance().use(m)`;`matchMode()` → `getInstance().matchMode()`;`reset()` 删除(测试用 `use(STRICT)`) | +| `OperatorIdentityGuard` → `diagnostic.OperatorIdentityWarnLog` | `check(...)` → `getInstance().warnOnce(...)`;去重状态归属实例,测试用 `new` 隔离 | +| `OperatorIdentity.pick` → `api.OperatorIdentityHeader.resolve` | 仅接入层使用;`OPERATOR_IDENTITY` / `IDENTITY_SCOPE` / `LOCK_IDENTITY` 常量随之迁移 | +| `OperatorScriptResultResolver.resolve(holder, result, type)` | `new OperatorScriptResultResolver(holder, type).resolve(result)` | +| `OperatorAssignmentService.validateAndSave*` | `new OperatorAssignmentService(session).assign(processId, selections)` | +| `OperatorManager.getOperator(long[, String])` | `match(IFlowOperator)`(配置匹配固定严格口径,不随运行时模式放宽) | + +### 验收 + +- `./mvnw test` 全绿:framework 554 / 全仓 6 个模块通过 +- 现有身份相关测试的断言未因行为变化而修改;仅因 API 形态变化改了调用形式 +- 新增测试:`OperatorKeyTest`、`OperatorManagerTest`、`TodoMergeKeyTest`、`OperatorIdentityContextTest`、`OperatorScriptElementTest`、`OperatorSelectionsTest`、`OperatorIdentityWarnLogTest` + +### 未做(需单独版本窗口) + +`OperatorIdentity` 值对象已在位,但 `OperatorKey` 内部仍以 `String` 存身份(`identity()` 返回 `String`)。 +把 `OperatorKey` 的字段改为 `OperatorIdentity` 属公开签名变更,影响约百处调用,按 H1 的渐进策略留待后续版本。 diff --git a/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java b/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java index 133f4516..0e595a31 100644 --- a/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java +++ b/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java @@ -30,11 +30,11 @@ public IFlowOperator get(long id) { */ @Override public IFlowOperator get(long id, String identity) { - if (OperatorIdentity.isDefault(identity)) { + if (OperatorIdentity.of(identity).isDefault()) { return get(id); } User user = userRepository.getUserById(id); - return user == null ? null : user.withIdentity(OperatorIdentity.normalize(identity)); + return user == null ? null : user.withIdentity(OperatorIdentity.of(identity).value()); } @Override @@ -53,10 +53,10 @@ public List findByIds(List ids) { */ @Override public List findByIds(List ids, String identity) { - if (OperatorIdentity.isDefault(identity)) { + if (OperatorIdentity.of(identity).isDefault()) { return findByIds(ids); } - String normalized = OperatorIdentity.normalize(identity); + String normalized = OperatorIdentity.of(identity).value(); return userRepository.findUserByIdIn(ids) .stream() .map(user -> (IFlowOperator) user.withIdentity(normalized)) 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 3e248d2a..69ed9d32 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 @@ -173,7 +173,7 @@ private List resolveTargetRecords(List targets, List targetRecords = new ArrayList<>(); for (IFlowOperator target : targets) { long targetOperatorId = target.getUserId(); - String targetOperatorIdentity = OperatorIdentity.of(target); + String targetOperatorIdentity = OperatorIdentity.of(target).value(); // 自己不能被自己减签:按身份匹配策略判断(USER_ONLY 下同人换身份仍视为自己) if (OperatorIdentityContext.getInstance() .matches(OperatorKey.of(target), currentRecord.currentOperatorKey())) { diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java b/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java index a822455a..84c32cf8 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java @@ -58,7 +58,7 @@ private Map getCache() { */ public void sync(IFlowOperator flowOperator) { Map operatorCaches = this.getCache(); - operatorCaches.put(cacheKey(flowOperator.getUserId(), OperatorIdentity.of(flowOperator)), flowOperator); + operatorCaches.put(cacheKey(flowOperator.getUserId(), OperatorIdentity.of(flowOperator).value()), flowOperator); this.cache.set(operatorCaches); } @@ -66,7 +66,7 @@ public void sync(IFlowOperator flowOperator) { * 读取操作者(默认身份)。 */ public IFlowOperator get(long id, Supplier operatorLoader) { - return this.get(id, OperatorIdentity.DEFAULT, operatorLoader); + return this.get(id, OperatorIdentity.DEFAULT.value(), operatorLoader); } /** @@ -102,7 +102,7 @@ public IFlowOperator get(long id, String identity, Supplier opera * 只有「请求了非默认身份、但拿回的却是另一个身份」才视为不一致。 */ private static boolean isIdentityMatched(IFlowOperator operator, String requestedIdentity) { - if (OperatorIdentity.isDefault(requestedIdentity)) { + if (OperatorIdentity.of(requestedIdentity).isDefault()) { return true; } return OperatorKey.of(operator).identityEquals(requestedIdentity); @@ -115,7 +115,7 @@ private static boolean isIdentityMatched(IFlowOperator operator, String requeste * 因此这里固定使用默认身份作为缓存键,与历史行为一致。 */ public List find(List ids, IFlowOperatorFinder flowOperatorFinder) { - return this.find(ids, OperatorIdentity.DEFAULT, flowOperatorFinder); + return this.find(ids, OperatorIdentity.DEFAULT.value(), flowOperatorFinder); } /** @@ -143,7 +143,7 @@ public List find(List ids, String identity, IFlowOperatorFi return null; } - String normalizedIdentity = OperatorIdentity.normalize(identity); + String normalizedIdentity = OperatorIdentity.of(identity).value(); Map operatorCaches = this.getCache(); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java b/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java index 910bf46d..7e112be0 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java @@ -4,7 +4,7 @@ import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; -import com.codingapi.flow.operator.OperatorIdentityGuard; +import com.codingapi.flow.diagnostic.OperatorIdentityWarnLog; import lombok.Getter; import lombok.Setter; @@ -33,7 +33,7 @@ private GatewayContext() { * @return 操作者 */ public IFlowOperator getFlowOperator(long userId) { - return this.getFlowOperator(userId, OperatorIdentity.DEFAULT); + return this.getFlowOperator(userId, OperatorIdentity.DEFAULT.value()); } /** @@ -50,7 +50,7 @@ public IFlowOperator getFlowOperator(long userId, String identity) { IFlowOperator operator = FlowOperatorLocalThreadCache.getInstance() .get(userId, identity, () -> flowOperatorGateway.get(userId, identity)); // 下游未覆盖带身份的取人方法时身份会被静默丢弃,这里补一条去重告警(issue #288 衍生 / #294) - OperatorIdentityGuard.check(userId, identity, operator); + OperatorIdentityWarnLog.getInstance().warnOnce(userId, identity, operator); return operator; } @@ -71,11 +71,11 @@ public List findByIds(List ids) { public List findByIds(List ids, String identity) { List operators = FlowOperatorLocalThreadCache.getInstance() .find(ids, identity, (idList) -> flowOperatorGateway.findByIds(idList, identity)); - if (OperatorIdentity.isDefault(identity)) { + if (OperatorIdentity.of(identity).isDefault()) { return operators; } // 下游未覆盖带身份的批量重载时,批量结果会退化为默认身份(findByIds(ids) 的返回), - // 这里逐条回退到单条按身份取人:正确实现会返回带身份的副本,未实现则由 OperatorIdentityGuard 告警。 + // 这里逐条回退到单条按身份取人:正确实现会返回带身份的副本,未实现则由 OperatorIdentityWarnLog 告警。 // 不做这一层兜底时,批量路径会把身份静默丢弃,且不会产生任何日志(issue #288 评审修复)。 Map operatorById = new HashMap<>(); if (operators != null) { @@ -86,7 +86,7 @@ public List findByIds(List ids, String identity) { List result = new ArrayList<>(); for (Long id : new LinkedHashSet<>(ids)) { IFlowOperator operator = operatorById.get(id); - if (operator == null || !OperatorIdentity.same(OperatorIdentity.of(operator), identity)) { + if (operator == null || !OperatorIdentity.of(operator).same(OperatorIdentity.of(identity))) { operator = this.getFlowOperator(id, identity); } if (operator != null) { diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityGuard.java b/flow-engine-framework/src/main/java/com/codingapi/flow/diagnostic/OperatorIdentityWarnLog.java similarity index 52% rename from flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityGuard.java rename to flow-engine-framework/src/main/java/com/codingapi/flow/diagnostic/OperatorIdentityWarnLog.java index 7af189c8..3f60c7e2 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityGuard.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/diagnostic/OperatorIdentityWarnLog.java @@ -1,76 +1,86 @@ -package com.codingapi.flow.operator; +package com.codingapi.flow.diagnostic; +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorKey; import lombok.extern.slf4j.Slf4j; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** - * 身份透传效果检查器(issue #288 衍生 / #294)。 + * 身份透传效果告警(issue #288 衍生 / #294 / #311 P5)。 * *

        框架通过 {@code default} 方法为身份能力提供向后兼容的退化实现,当下游没有覆盖带身份的取人方法时, * 身份会被静默丢弃:请求里带的是「部门A」,落库却变成默认身份,前端按身份查待办会得到空列表, - * 且没有任何异常或日志。这类问题在集成阶段极难定位,因此在这里补一条运行期告警。 + * 且没有任何异常或日志。这类问题在集成阶段极难定位,因此补一条运行期告警。 * - *

        告警按 {@code (人员id, 身份)} 去重,并对条目总量设上限,避免高频调用场景刷爆日志或占用内存。 + *

        它是可观测性组件,不是领域类型,因此位于 {@code diagnostic} 包,不参与任何业务判定。 + * + *

        状态归属:告警去重记录是实例字段而不是静态集合——全局静态可变状态会让测试互相污染, + * 并迫使代码暴露「清空缓存」这种只为测试服务的入口。需要隔离的场景直接 {@code new} 一个实例即可。 */ @Slf4j -public final class OperatorIdentityGuard { +public final class OperatorIdentityWarnLog { /** * 告警去重记录的条目上限 */ private static final int MAX_WARN_KEYS = 256; - private static final Set WARNED_KEYS = ConcurrentHashMap.newKeySet(); + private static final OperatorIdentityWarnLog INSTANCE = new OperatorIdentityWarnLog(); + + private final Set warnedKeys = ConcurrentHashMap.newKeySet(); - private OperatorIdentityGuard() { + /** + * 全局默认实例(生产使用) + * + * @return 告警器实例 + */ + public static OperatorIdentityWarnLog getInstance() { + return INSTANCE; } /** - * 检查身份透传是否生效:请求的为非默认身份、但回查到操作者的身份为空时输出告警。 + * 检查身份透传是否生效:请求的是非默认身份、但回查到操作者的身份为空时输出告警。 * * @param operatorId 人员 id * @param requestedIdentity 请求声明的身份 * @param resolved 回查到的操作者,可能为 {@code null} * @return true 表示本次实际输出了告警(同一 {@code (人员, 身份)} 只会返回一次 true) */ - public static boolean check(long operatorId, String requestedIdentity, IFlowOperator resolved) { + public boolean warnOnce(long operatorId, String requestedIdentity, IFlowOperator resolved) { if (!needWarn(requestedIdentity, resolved)) { return false; } - if (WARNED_KEYS.size() >= MAX_WARN_KEYS) { + if (warnedKeys.size() >= MAX_WARN_KEYS) { return false; } // 去重键就是参与人键,格式由 OperatorKey 唯一定义 - String key = OperatorKey.of(operatorId, requestedIdentity).key(); - if (!WARNED_KEYS.add(key)) { + if (!warnedKeys.add(OperatorKey.of(operatorId, requestedIdentity).key())) { return false; } log.warn("流程操作者身份未生效:人员[{}] 请求身份[{}],但回查到的操作者身份为空。" + "请确认下游已覆盖 FlowOperatorGateway#get(id, identity) 与 IRepositoryHolder#getOperatorById(id, identity)," + "否则同一人员的多身份将全部退化为默认身份(issue #288)。", - operatorId, OperatorIdentity.normalize(requestedIdentity)); + operatorId, OperatorIdentity.of(requestedIdentity).value()); return true; } /** * 是否需要告警:请求身份非默认,且回查结果的身份为默认。 + * + * @param requestedIdentity 请求声明的身份 + * @param resolved 回查到的操作者 + * @return true 表示需要告警 */ static boolean needWarn(String requestedIdentity, IFlowOperator resolved) { - if (OperatorIdentity.isDefault(requestedIdentity)) { + if (OperatorIdentity.of(requestedIdentity).isDefault()) { return false; } if (resolved == null) { return false; } - return OperatorIdentity.isDefault(OperatorIdentity.of(resolved)); - } - - /** - * 清空告警去重记录,仅用于测试隔离。 - */ - public static void resetWarnedCache() { - WARNED_KEYS.clear(); + return OperatorIdentity.of(resolved).isDefault(); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java index aa94fb90..cef81b6c 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java @@ -54,7 +54,7 @@ public T getStrategy(Class clazz) { * @param recordOperatorId 记录操作者id */ public void verifyOperator(IFlowOperator currentOperator, long recordOperatorId) { - this.verifyOperator(currentOperator, recordOperatorId, OperatorIdentity.DEFAULT); + this.verifyOperator(currentOperator, recordOperatorId, OperatorIdentity.DEFAULT.value()); } /** diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowRecordRepositoryMockImpl.java b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowRecordRepositoryMockImpl.java index cb91259b..2636157f 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowRecordRepositoryMockImpl.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowRecordRepositoryMockImpl.java @@ -47,11 +47,11 @@ public List findNotifyByOperator(long operatorId) { * 按 {@code (审批人, 身份)} 查询已办(issue #288 衍生 / #291),口径与 JPA 一致。 */ public List findDoneByOperator(long operatorId, String identity) { - String normalized = OperatorIdentity.normalize(identity); + String normalized = OperatorIdentity.of(identity).value(); return cache.values().stream() .filter(flowRecord -> flowRecord.getCurrentOperatorId() == operatorId && flowRecord.isDone() - && OperatorIdentity.same(flowRecord.getCurrentOperatorIdentity(), normalized)) + && OperatorIdentity.of(flowRecord.getCurrentOperatorIdentity()).same(OperatorIdentity.of(normalized))) .toList(); } @@ -59,13 +59,13 @@ public List findDoneByOperator(long operatorId, String identity) { * 按 {@code (审批人, 身份)} 查询抄送(issue #288 衍生 / #291),口径与 JPA 一致。 */ public List findNotifyByOperator(long operatorId, String identity) { - String normalized = OperatorIdentity.normalize(identity); + String normalized = OperatorIdentity.of(identity).value(); return cache.values().stream() .filter(flowRecord -> flowRecord.getCurrentOperatorId() == operatorId && flowRecord.isNotify() && !flowRecord.isRevoked() && !flowRecord.isHidden() - && OperatorIdentity.same(flowRecord.getCurrentOperatorIdentity(), normalized)) + && OperatorIdentity.of(flowRecord.getCurrentOperatorIdentity()).same(OperatorIdentity.of(normalized))) .toList(); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowTodoRecordRepositoryMockImpl.java b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowTodoRecordRepositoryMockImpl.java index 9e7e26e5..a48940ce 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowTodoRecordRepositoryMockImpl.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowTodoRecordRepositoryMockImpl.java @@ -81,10 +81,10 @@ public List findByOperatorId(long operatorId) { * 历史记录身份为 {@code null} 时按默认身份命中。 */ public List findByOperatorId(long operatorId, String identity) { - String normalized = OperatorIdentity.normalize(identity); + String normalized = OperatorIdentity.of(identity).value(); return cache.values().stream() .filter(record -> record.getCurrentOperatorId() == operatorId - && OperatorIdentity.same(record.getCurrentOperatorIdentity(), normalized)) + && OperatorIdentity.of(record.getCurrentOperatorIdentity()).same(OperatorIdentity.of(normalized))) .toList(); } 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 3b2fc1f9..6932e3af 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 @@ -275,11 +275,11 @@ private List generateCurrentRecords(FlowSession session, Set && session.getCurrentOperator() != null && OperatorIdentityContext.getInstance().matches( OperatorKey.of(session.getCurrentOperator()), - OperatorKey.of(session.getSubmitOperatorId(), OperatorIdentity.of(session.getSubmitOperator()))) + OperatorKey.of(session.getSubmitOperatorId(), OperatorIdentity.of(session.getSubmitOperator()).value())) && session.getCurrentAction() != null && ActionType.PASS.name().equalsIgnoreCase(session.getCurrentAction().type())) { long submitOperatorId = session.getSubmitOperatorId(); - String submitOperatorIdentity = OperatorIdentity.of(session.getSubmitOperator()); + String submitOperatorIdentity = OperatorIdentity.of(session.getSubmitOperator()).value(); operators = operators.stream() .filter(operator -> !OperatorIdentityContext.getInstance() .matches(OperatorKey.of(operator), OperatorKey.of(submitOperatorId, submitOperatorIdentity))) diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java index 344d387d..4ebca4ce 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java @@ -41,7 +41,7 @@ public interface IFlowOperator extends IUser { * @see OperatorIdentity */ default String getIdentity() { - return OperatorIdentity.DEFAULT; + return OperatorIdentity.DEFAULT.value(); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java index cf1bc55a..2d4b4ac3 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java @@ -2,25 +2,36 @@ import com.codingapi.flow.exception.FlowValidationException; +import java.util.Objects; + /** - * 身份标识归一化工具。 + * 身份标识(值对象)。 * - *

        流程引擎不解释身份标识的业务语义,只做透传、存储与比较。为了让「存量数据」与 + *

        流程引擎不解释身份的业务语义,只做透传、存储与比较。为了让「存量数据」与 * 「未启用多身份的业务」保持完全一致的行为,统一约定: *

          - *
        • {@code null} 与空串等价,均视为「默认身份」;
        • - *
        • 所有身份读取、写入、比较前都必须经过 {@link #normalize(String)},禁止直接使用原始值比较;
        • + *
        • {@code null} 与空串等价,均视为 {@link #DEFAULT 默认身份};
        • + *
        • 所有身份读取、写入、比较前都必须经过本类型({@link #of(String)} 完成归一化),禁止直接比较原始值;
        • *
        • 默认身份的存取不改变既有数据格式(例如待办合并键在默认身份下保持历史格式)。
        • *
        * + *

        本类型是身份的唯一载体:{@link #of} 构造、{@link #value()} 取值、 + * {@link #same(OperatorIdentity)} / {@link #equals(Object)} 判等、{@link #validate()} 校验。 + * 原先散在静态方法上的 {@code normalize / isDefault / same / validate} + * 已收为实例语义,身份不再是一个「可以随处比较的字符串」。 + * + *

        HTTP 请求头解析不在本类——那是接入层契约, + * 见 {@code com.codingapi.flow.api.OperatorIdentityHeader}。 + * * @see IFlowOperator#getIdentity() + * @see OperatorKey */ public final class OperatorIdentity { /** - * 默认身份标识 + * 默认身份({@code null} 与空串归一化后的结果) */ - public static final String DEFAULT = ""; + public static final OperatorIdentity DEFAULT = new OperatorIdentity(""); /** * 身份标识最大长度,与 DDL({@code VARCHAR(64)})保持一致。 @@ -37,57 +48,55 @@ public final class OperatorIdentity { */ public static final String RESERVED_KEY_MARK = "#"; - /** - * 当前身份的请求头名称(issue #301)。 - * - *

        身份是请求上下文,不应放在 query 中:引擎的查询接口用 {@code SearchRequest} 接收请求, - * 会把所有 query 参数当作实体过滤字段解析,多一个 {@code operatorIdentity} 就会抛 - * {@code Field operatorIdentity not found in class hierarchy}。 - * - *

        为兼容旧前端与 curl 直连,服务端仍保留 query 读取,但请求头优先。 - */ - public static final String HEADER_OPERATOR_IDENTITY = "X-Operator-Identity"; + private final String value; + + private OperatorIdentity(String value) { + this.value = value; + } /** - * 查询身份范围的请求头名称,取值 {@code ALL} / {@code LOCKED}(issue #301) + * 由原始值构造身份,{@code null} 与空串归一化为 {@link #DEFAULT}。 + * + * @param raw 原始身份标识 + * @return 身份值对象,不为 {@code null} */ - public static final String HEADER_IDENTITY_SCOPE = "X-Identity-Scope"; + public static OperatorIdentity of(String raw) { + if (raw == null || raw.isEmpty()) { + return DEFAULT; + } + return new OperatorIdentity(raw); + } /** - * 是否锁定身份查询的请求头名称,取值 {@code true} / {@code false}(issue #301) + * 读取操作者的身份,操作者为 {@code null} 时返回默认身份。 + * + * @param operator 流程参与用户,可为 {@code null} + * @return 身份值对象 */ - public static final String HEADER_LOCK_IDENTITY = "X-Lock-Identity"; - - private OperatorIdentity() { + public static OperatorIdentity of(IFlowOperator operator) { + return operator == null ? DEFAULT : of(operator.getIdentity()); } /** - * 选取身份原始值:请求头优先,其次请求参数(issue #301)。 + * 身份原始值(已归一化,不为 {@code null})。 * - * @param headerValue 请求头中的原始值,未携带时为 {@code null} - * @param parameterValue 请求参数中的原始值 - * @param parameterPresent 请求参数是否显式出现(区分「未传」与「传了空串」) - * @return 原始值;两者都未携带时返回 {@code null} + * @return 身份标识,默认身份为空串 */ - public static String pick(String headerValue, String parameterValue, boolean parameterPresent) { - if (headerValue != null) { - return headerValue; - } - return parameterPresent ? parameterValue : null; + public String value() { + return value; } /** - * 归一化身份标识:null 转为空串,其余原样返回。 + * 是否为默认身份。 * - * @param identity 原始身份标识 - * @return 归一化后的身份标识,不为 null + * @return true 表示默认身份(原 {@code null} 或空串) */ - public static String normalize(String identity) { - return identity == null ? DEFAULT : identity; + public boolean isDefault() { + return value.isEmpty(); } /** - * 校验并归一化身份标识(写入 / 落库前调用)。 + * 校验身份是否可作为持久化值(写入 / 落库前调用)。 * *

        约束: *

          @@ -96,55 +105,53 @@ public static String normalize(String identity) { *
        • 不允许包含控制字符,避免污染内部以控制字符拼接的缓存键。
        • *
        * - * @param identity 原始身份标识,{@code null} 与空串等价(默认身份) - * @return 归一化后的身份标识 + * @return 校验通过的自身,便于链式取值 * @throws FlowValidationException 身份标识不合法 */ - public static String validate(String identity) { - String normalized = normalize(identity); - if (normalized.length() > MAX_LENGTH) { - throw FlowValidationException.operatorIdentityTooLong(normalized.length(), MAX_LENGTH); + public OperatorIdentity validate() { + if (value.length() > MAX_LENGTH) { + throw FlowValidationException.operatorIdentityTooLong(value.length(), MAX_LENGTH); } - if (normalized.contains(RESERVED_KEY_MARK)) { + if (value.contains(RESERVED_KEY_MARK)) { throw FlowValidationException.operatorIdentityInvalid(RESERVED_KEY_MARK); } - for (int i = 0; i < normalized.length(); i++) { - char c = normalized.charAt(i); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); if (Character.isISOControl(c)) { throw FlowValidationException.operatorIdentityInvalid("\\u" + Integer.toHexString(c)); } } - return normalized; + return this; } /** - * 是否为默认身份(null 或空串)。 + * 判断是否为同一身份({@code null} 与空串等价由 {@link #of(String)} 保证)。 * - * @param identity 身份标识 - * @return true 表示默认身份 + * @param other 另一个身份 + * @return true 表示同一身份 */ - public static boolean isDefault(String identity) { - return normalize(identity).isEmpty(); + public boolean same(OperatorIdentity other) { + return other != null && value.equals(other.value); } - /** - * 读取操作者的身份标识,操作者为 null 时返回默认身份。 - * - * @param operator 流程参与用户 - * @return 归一化后的身份标识 - */ - public static String of(IFlowOperator operator) { - return operator == null ? DEFAULT : normalize(operator.getIdentity()); + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof OperatorIdentity that)) { + return false; + } + return value.equals(that.value); } - /** - * 判断两个身份标识是否相同(null 安全)。 - * - * @param left 身份标识 - * @param right 身份标识 - * @return true 表示同一身份 - */ - public static boolean same(String left, String right) { - return normalize(left).equals(normalize(right)); + @Override + public int hashCode() { + return Objects.hash(value); + } + + @Override + public String toString() { + return value; } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java index 42df0d25..d150f280 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java @@ -14,7 +14,7 @@ * * 禁止在业务代码里内联 {@code userId == ... && identity.equals(...)},也禁止自行拼接参与人键。 * - *

        身份统一经 {@link OperatorIdentity#normalize(String)} 归一化,{@code null} 与空串等价; + *

        身份统一经 {@link OperatorIdentity#of(String)} 归一化,{@code null} 与空串等价; * 归一化在紧凑构造中完成,因此 {@link #equals(Object)} 即是「严格口径下是否为同一参与人」。 * * @param operatorId 人员 id @@ -25,7 +25,7 @@ public record OperatorKey(long operatorId, String identity) { /** * 参与人键中人员 id 与身份的分隔符。 * - *

        选用不可见控制字符:身份来自请求头,可能未经 {@link OperatorIdentity#validate(String)} 校验, + *

        选用不可见控制字符:身份来自请求头,可能未经 {@link OperatorIdentity#validate()} 校验, * 因此键的分隔符必须取「业务身份永远不可能包含」的字符,避免 {@code (1,"a#b")} 与 {@code (1,"a")} 撞键。 * 该常量是本仓库唯一的分隔符声明,其它类不得再声明自己的分隔符。 */ @@ -35,7 +35,7 @@ public record OperatorKey(long operatorId, String identity) { * 紧凑构造:身份统一归一化,保证 {@code null} 与空串等价 */ public OperatorKey { - identity = OperatorIdentity.normalize(identity); + identity = OperatorIdentity.of(identity).value(); } /** @@ -56,7 +56,7 @@ public static OperatorKey of(long operatorId, String identity) { * @return 操作者标识 */ public static OperatorKey ofDefault(long operatorId) { - return new OperatorKey(operatorId, OperatorIdentity.DEFAULT); + return new OperatorKey(operatorId, OperatorIdentity.DEFAULT.value()); } /** @@ -93,7 +93,7 @@ public boolean matches(OperatorKey other, OperatorIdentityMatchMode mode) { * @return true 表示同一身份 */ public boolean identityEquals(String otherIdentity) { - return identity.equals(OperatorIdentity.normalize(otherIdentity)); + return identity.equals(OperatorIdentity.of(otherIdentity).value()); } /** diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/body/FlowAdviceBody.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/body/FlowAdviceBody.java index 54350ecf..a0f6775f 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/body/FlowAdviceBody.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/body/FlowAdviceBody.java @@ -89,7 +89,7 @@ public FlowAdviceBody(FlowSession flowSession) { this.actionId = flowSession.getCurrentAction().id(); this.advice = flowSession.getAdvice().getAdvice(); this.operatorId = flowSession.getCurrentOperator().getUserId(); - this.operatorIdentity = OperatorIdentity.of(flowSession.getCurrentOperator()); + this.operatorIdentity = OperatorIdentity.of(flowSession.getCurrentOperator()).value(); this.signKey = flowSession.getAdvice().getSignKey(); this.backNodeId = flowSession.getAdvice().getBackNode() != null ? flowSession.getAdvice().getBackNode().getId() : null; this.manualNodeId = flowSession.getAdvice().getManualNode() != null ? flowSession.getAdvice().getManualNode().getId() : null; diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDeleteRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDeleteRequest.java index 51d41a6b..f470e59c 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDeleteRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDeleteRequest.java @@ -34,7 +34,7 @@ public class FlowDeleteRequest { * 兼容历史调用的双参构造(默认身份) */ public FlowDeleteRequest(long recordId, long operatorId) { - this(recordId, operatorId, OperatorIdentity.DEFAULT); + this(recordId, operatorId, OperatorIdentity.DEFAULT.value()); } public void verify() { diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDetailRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDetailRequest.java index 0ee3299d..15f71b84 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDetailRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDetailRequest.java @@ -28,11 +28,11 @@ public boolean isCreateWorkflow() { } public FlowDetailRequest(long id,long operatorId){ - this(id, operatorId, OperatorIdentity.DEFAULT); + this(id, operatorId, OperatorIdentity.DEFAULT.value()); } public FlowDetailRequest(String id, long operatorId) { - this(id, operatorId, OperatorIdentity.DEFAULT); + this(id, operatorId, OperatorIdentity.DEFAULT.value()); } public FlowDetailRequest(long id, long operatorId, String operatorIdentity) { diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowProcessNodeRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowProcessNodeRequest.java index b0f97d42..6fb11ca7 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowProcessNodeRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowProcessNodeRequest.java @@ -34,11 +34,11 @@ public class FlowProcessNodeRequest { public FlowProcessNodeRequest(long id, long operatorId, Map formData) { - this(id, operatorId, OperatorIdentity.DEFAULT, formData); + this(id, operatorId, OperatorIdentity.DEFAULT.value(), formData); } public FlowProcessNodeRequest(String id, long operatorId, Map formData) { - this(id, operatorId, OperatorIdentity.DEFAULT, formData); + this(id, operatorId, OperatorIdentity.DEFAULT.value(), formData); } public FlowProcessNodeRequest(long id, long operatorId, String operatorIdentity, Map formData) { diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowRevokeRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowRevokeRequest.java index fece10db..b7f71fde 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowRevokeRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowRevokeRequest.java @@ -32,7 +32,7 @@ public class FlowRevokeRequest { * 兼容历史调用的双参构造(默认身份) */ public FlowRevokeRequest(long recordId, long operatorId) { - this(recordId, operatorId, OperatorIdentity.DEFAULT); + this(recordId, operatorId, OperatorIdentity.DEFAULT.value()); } public void verify() { diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowUrgeRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowUrgeRequest.java index d5051b9c..ee5ab335 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowUrgeRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowUrgeRequest.java @@ -32,7 +32,7 @@ public class FlowUrgeRequest { * 兼容历史调用的双参构造(默认身份) */ public FlowUrgeRequest(long recordId, long operatorId) { - this(recordId, operatorId, OperatorIdentity.DEFAULT); + this(recordId, operatorId, OperatorIdentity.DEFAULT.value()); } public void verify() { diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowOperator.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowOperator.java index fa499a29..37d2a2af 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowOperator.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowOperator.java @@ -25,18 +25,18 @@ public class FlowOperator { * 兼容历史调用方的双参构造器,身份为默认身份 */ public FlowOperator(long id, String name) { - this(id, name, OperatorIdentity.DEFAULT); + this(id, name, OperatorIdentity.DEFAULT.value()); } public FlowOperator(long id, String name, String identity) { this.id = id; this.name = name; - this.identity = OperatorIdentity.normalize(identity); + this.identity = OperatorIdentity.of(identity).value(); } public FlowOperator(IFlowOperator flowOperator) { this.id = flowOperator.getUserId(); this.name = flowOperator.getName(); - this.identity = OperatorIdentity.of(flowOperator); + this.identity = OperatorIdentity.of(flowOperator).value(); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowRecordContent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowRecordContent.java index 38c5b5e4..01eb9d44 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowRecordContent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowRecordContent.java @@ -168,17 +168,17 @@ public static FlowRecordContent convert(FlowRecord record){ content.setReadTime(record.getReadTime()); content.setCurrentOperatorId(record.getCurrentOperatorId()); content.setCurrentOperatorName(record.getCurrentOperatorName()); - content.setCurrentOperatorIdentity(OperatorIdentity.normalize(record.getCurrentOperatorIdentity())); + content.setCurrentOperatorIdentity(OperatorIdentity.of(record.getCurrentOperatorIdentity()).value()); content.setSubmitOperatorId(record.getSubmitOperatorId()); content.setSubmitOperatorName(record.getSubmitOperatorName()); - content.setSubmitOperatorIdentity(OperatorIdentity.normalize(record.getSubmitOperatorIdentity())); + content.setSubmitOperatorIdentity(OperatorIdentity.of(record.getSubmitOperatorIdentity()).value()); content.setCreateTime(record.getCreateTime()); content.setCreateOperatorId(record.getCreateOperatorId()); content.setCreateOperatorName(record.getCreateOperatorName()); - content.setCreateOperatorIdentity(OperatorIdentity.normalize(record.getCreateOperatorIdentity())); + content.setCreateOperatorIdentity(OperatorIdentity.of(record.getCreateOperatorIdentity()).value()); content.setHandleOperatorId(record.getHandleOperatorId()); content.setHandleOperatorName(record.getHandleOperatorName()); - content.setHandleOperatorIdentity(OperatorIdentity.normalize(record.getHandleOperatorIdentity())); + content.setHandleOperatorIdentity(OperatorIdentity.of(record.getHandleOperatorIdentity()).value()); content.setMergeable(record.isMergeable()); content.setRecordId(record.getId()); content.setTimeoutTime(record.getTimeoutTime()); @@ -201,14 +201,14 @@ public static FlowRecordContent convert(FlowTodoRecord todoRecord){ content.setReadTime(todoRecord.getReadTime()); content.setCurrentOperatorId(todoRecord.getCurrentOperatorId()); content.setCurrentOperatorName(todoRecord.getCurrentOperatorName()); - content.setCurrentOperatorIdentity(OperatorIdentity.normalize(todoRecord.getCurrentOperatorIdentity())); + content.setCurrentOperatorIdentity(OperatorIdentity.of(todoRecord.getCurrentOperatorIdentity()).value()); content.setSubmitOperatorId(todoRecord.getSubmitOperatorId()); content.setSubmitOperatorName(todoRecord.getSubmitOperatorName()); - content.setSubmitOperatorIdentity(OperatorIdentity.normalize(todoRecord.getSubmitOperatorIdentity())); + content.setSubmitOperatorIdentity(OperatorIdentity.of(todoRecord.getSubmitOperatorIdentity()).value()); content.setCreateTime(todoRecord.getCreateTime()); content.setCreateOperatorId(todoRecord.getCreateOperatorId()); content.setCreateOperatorName(todoRecord.getCreateOperatorName()); - content.setCreateOperatorIdentity(OperatorIdentity.normalize(todoRecord.getCreateOperatorIdentity())); + content.setCreateOperatorIdentity(OperatorIdentity.of(todoRecord.getCreateOperatorIdentity()).value()); content.setTodoKey(todoRecord.getTodoKey()); content.setMargeCount(todoRecord.getMargeCount()); content.setMergeable(todoRecord.isMergeable()); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java index 34a46ded..cd00624a 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java @@ -396,18 +396,18 @@ public FlowRecord(FlowSession flowSession, int nodeOrder) { this.processId = FlowIDGeneratorGatewayContext.getInstance().generateProcessId(); this.createOperatorId = flowSession.getCreatedOperator().getUserId(); this.createOperatorName = flowSession.getCreatedOperator().getName(); - this.createOperatorIdentity = OperatorIdentity.of(flowSession.getCreatedOperator()); + this.createOperatorIdentity = OperatorIdentity.of(flowSession.getCreatedOperator()).value(); // 身份字段统一以空串兜底,避免出现 null 与空串两种「默认身份」表达 - this.forwardOperatorIdentity = OperatorIdentity.DEFAULT; - this.interferedOperatorIdentity = OperatorIdentity.DEFAULT; - this.handleOperatorIdentity = OperatorIdentity.DEFAULT; + this.forwardOperatorIdentity = OperatorIdentity.DEFAULT.value(); + this.interferedOperatorIdentity = OperatorIdentity.DEFAULT.value(); + this.handleOperatorIdentity = OperatorIdentity.DEFAULT.value(); // 是否转交之后的人来审批的判断 if (currentOperator.equals(sourceOperator)) { this.forwardOperatorId = 0; } else { this.forwardOperatorId = sourceOperator.getUserId(); this.forwardOperatorName = sourceOperator.getName(); - this.forwardOperatorIdentity = OperatorIdentity.of(sourceOperator); + this.forwardOperatorIdentity = OperatorIdentity.of(sourceOperator).value(); } this.recordState = SATE_RECORD_TODO; this.actionId = action.id(); @@ -416,11 +416,11 @@ public FlowRecord(FlowSession flowSession, int nodeOrder) { this.currentOperatorId = currentOperator.getUserId(); this.currentOperatorName = currentOperator.getName(); - this.currentOperatorIdentity = OperatorIdentity.of(currentOperator); + this.currentOperatorIdentity = OperatorIdentity.of(currentOperator).value(); this.submitOperatorId = flowSession.getSubmitOperatorId(); this.submitOperatorName = flowSession.getSubmitOperatorName(); - this.submitOperatorIdentity = OperatorIdentity.of(flowSession.getSubmitOperator()); + this.submitOperatorIdentity = OperatorIdentity.of(flowSession.getSubmitOperator()).value(); this.advice = flowSession.getAdvice().getAdvice(); this.signKey = flowSession.getAdvice().getSignKey(); @@ -668,7 +668,7 @@ public void update(FlowSession flowSession, boolean pass) { if (!OperatorIdentityContext.getInstance().matches(currentOperator, currentOperatorKey())) { this.interferedOperatorId = flowSession.getCurrentOperator().getUserId(); this.interferedOperatorName = flowSession.getCurrentOperator().getName(); - this.interferedOperatorIdentity = OperatorIdentity.of(flowSession.getCurrentOperator()); + this.interferedOperatorIdentity = OperatorIdentity.of(flowSession.getCurrentOperator()).value(); } if (flowAdvice != null) { @@ -696,7 +696,7 @@ public void markHandleOperator(IFlowOperator operator) { } this.handleOperatorId = operator.getUserId(); this.handleOperatorName = operator.getName(); - this.handleOperatorIdentity = OperatorIdentity.of(operator); + this.handleOperatorIdentity = OperatorIdentity.of(operator).value(); } public void clearNotify(){ @@ -707,7 +707,7 @@ public void clearNotify(){ this.notify = true; this.forwardOperatorId = 0; // 转交身份必须同步清零,否则身份会残留在记录上,被后续复用带出错误的参与人身份(issue #288 衍生 / #294) - this.forwardOperatorIdentity = OperatorIdentity.DEFAULT; + this.forwardOperatorIdentity = OperatorIdentity.DEFAULT.value(); } @@ -828,7 +828,7 @@ public FlowRecord create(FlowSession flowSession) { FlowRecord flowRecord = new FlowRecord(flowSession, 0); flowRecord.currentOperatorId = flowSession.getCurrentOperator().getUserId(); flowRecord.currentOperatorName = flowSession.getCurrentOperator().getName(); - flowRecord.currentOperatorIdentity = OperatorIdentity.of(flowSession.getCurrentOperator()); + flowRecord.currentOperatorIdentity = OperatorIdentity.of(flowSession.getCurrentOperator()).value(); return flowRecord; } @@ -880,7 +880,7 @@ public void newRecord() { public void clearHandleOperator() { this.handleOperatorId = 0; this.handleOperatorName = null; - this.handleOperatorIdentity = OperatorIdentity.DEFAULT; + this.handleOperatorIdentity = OperatorIdentity.DEFAULT.value(); } /** diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowTodoRecord.java b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowTodoRecord.java index 1ef55639..ce847a13 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowTodoRecord.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowTodoRecord.java @@ -163,9 +163,9 @@ public void update(FlowRecord flowRecord) { this.createTime = flowRecord.getCreateTime(); this.createOperatorId = flowRecord.getCreateOperatorId(); this.createOperatorName = flowRecord.getCreateOperatorName(); - this.currentOperatorIdentity = OperatorIdentity.normalize(flowRecord.getCurrentOperatorIdentity()); - this.submitOperatorIdentity = OperatorIdentity.normalize(flowRecord.getSubmitOperatorIdentity()); - this.createOperatorIdentity = OperatorIdentity.normalize(flowRecord.getCreateOperatorIdentity()); + this.currentOperatorIdentity = OperatorIdentity.of(flowRecord.getCurrentOperatorIdentity()).value(); + this.submitOperatorIdentity = OperatorIdentity.of(flowRecord.getSubmitOperatorIdentity()).value(); + this.createOperatorIdentity = OperatorIdentity.of(flowRecord.getCreateOperatorIdentity()).value(); this.todoKey = flowRecord.getTodoKey(); this.mergeable = flowRecord.isMergeable(); this.recordId = flowRecord.getId(); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptRequest.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptRequest.java index 92675416..c730d788 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptRequest.java @@ -309,7 +309,7 @@ public String getSubmitOperatorName() { */ @ScriptFunction(name = "getCreatedOperatorIdentity", description = "获取流程创建者身份标识") public String getCreatedOperatorIdentity() { - return OperatorIdentity.of(this.createdOperator); + return OperatorIdentity.of(this.createdOperator).value(); } /** @@ -319,7 +319,7 @@ public String getCreatedOperatorIdentity() { */ @ScriptFunction(name = "getCurrentOperatorIdentity", description = "获取流程审批者身份标识") public String getCurrentOperatorIdentity() { - return OperatorIdentity.of(this.currentOperator); + return OperatorIdentity.of(this.currentOperator).value(); } /** @@ -329,7 +329,7 @@ public String getCurrentOperatorIdentity() { */ @ScriptFunction(name = "getSubmitOperatorIdentity", description = "获取流程提交人身份标识") public String getSubmitOperatorIdentity() { - return OperatorIdentity.of(this.submitOperator); + return OperatorIdentity.of(this.submitOperator).value(); } /** @@ -340,7 +340,7 @@ public String getSubmitOperatorIdentity() { */ @ScriptFunction(name = "getCreatedOperatorKey", description = "获取流程创建者标识(含身份)") public OperatorKey getCreatedOperatorKey() { - return OperatorKey.of(this.createdOperator.getUserId(), OperatorIdentity.of(this.createdOperator)); + return OperatorKey.of(this.createdOperator.getUserId(), OperatorIdentity.of(this.createdOperator).value()); } /** @@ -350,7 +350,7 @@ public OperatorKey getCreatedOperatorKey() { */ @ScriptFunction(name = "getCurrentOperatorKey", description = "获取流程审批者标识(含身份)") public OperatorKey getCurrentOperatorKey() { - return OperatorKey.of(this.currentOperator.getUserId(), OperatorIdentity.of(this.currentOperator)); + return OperatorKey.of(this.currentOperator.getUserId(), OperatorIdentity.of(this.currentOperator).value()); } /** @@ -360,7 +360,7 @@ public OperatorKey getCurrentOperatorKey() { */ @ScriptFunction(name = "getSubmitOperatorKey", description = "获取流程提交人标识(含身份)") public OperatorKey getSubmitOperatorKey() { - return OperatorKey.of(this.submitOperator.getUserId(), OperatorIdentity.of(this.submitOperator)); + return OperatorKey.of(this.submitOperator.getUserId(), OperatorIdentity.of(this.submitOperator).value()); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java index a63e01b2..e04d2ef2 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java @@ -11,7 +11,7 @@ import com.codingapi.flow.manager.WorkflowStrategyManager; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; -import com.codingapi.flow.operator.OperatorIdentityGuard; +import com.codingapi.flow.diagnostic.OperatorIdentityWarnLog; import com.codingapi.flow.operator.OperatorSelections; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.response.ActionResponse; @@ -59,7 +59,7 @@ public ActionResponse action() { IFlowOperator currentOperator = flowOperatorGateway.get( request.getAdvice().getOperatorId(), request.getAdvice().getOperatorIdentity()); // 审批入口同样检查身份是否真的生效,避免下游未覆盖带身份的取人方法时静默降级(issue #288 评审修复) - OperatorIdentityGuard.check(request.getAdvice().getOperatorId(), request.getAdvice().getOperatorIdentity(), currentOperator); + OperatorIdentityWarnLog.getInstance().warnOnce(request.getAdvice().getOperatorId(), request.getAdvice().getOperatorIdentity(), currentOperator); if (currentOperator == null) { throw FlowNotFoundException.operator(request.getAdvice().getOperatorId()); } @@ -74,7 +74,7 @@ public ActionResponse action() { // 发起人按记录中的身份回查,避免同一 id 的不同身份拿到同一个操作者实例 IFlowOperator createdOperator = flowOperatorGateway.get( flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity()); - OperatorIdentityGuard.check(flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity(), createdOperator); + OperatorIdentityWarnLog.getInstance().warnOnce(flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity(), createdOperator); WorkflowRuntime workflowRuntime = workflowService.getWorkflowRuntime(flowRecord.getWorkRuntimeId()); if (workflowRuntime == null) { 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 fa65fdb6..9392363c 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 @@ -14,7 +14,7 @@ import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.node.nodes.StartNode; import com.codingapi.flow.operator.IFlowOperator; -import com.codingapi.flow.operator.OperatorIdentityGuard; +import com.codingapi.flow.diagnostic.OperatorIdentityWarnLog; import com.codingapi.flow.operator.OperatorSelections; import com.codingapi.flow.pojo.request.FlowCreateRequest; import com.codingapi.flow.record.FlowRecord; @@ -62,7 +62,7 @@ public long create() { // 验证当前用户(按请求声明的身份加载,同一人不同身份是不同参与人) IFlowOperator currentOperator = flowOperatorGateway.get(request.getOperatorId(), request.getOperatorIdentity()); // 发起入口同样要检查身份是否真的生效:下游未覆盖带身份的取人方法时身份会被静默丢弃(issue #288 评审修复) - OperatorIdentityGuard.check(request.getOperatorId(), request.getOperatorIdentity(), currentOperator); + OperatorIdentityWarnLog.getInstance().warnOnce(request.getOperatorId(), request.getOperatorIdentity(), currentOperator); if (!workflow.matchCreatedOperator(currentOperator)) { throw FlowPermissionException.accessDenied("create workflow"); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java index aa789a07..b42ef942 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java @@ -108,7 +108,7 @@ private boolean isCreateWorkflow() { * 操作者缓存键:同一人员的不同身份必须区分缓存,避免身份串味(issue #288) */ private static String recordOperatorKey(long operatorId, String identity) { - return operatorId + "\u0001" + OperatorIdentity.normalize(identity); + return operatorId + "\u0001" + OperatorIdentity.of(identity).value(); } private IFlowOperator loadRecordOperator(long operatorId, String identity) { @@ -168,7 +168,7 @@ private static void addOperatorRef(Map> operatorIdsByIdentity, return; } operatorIdsByIdentity - .computeIfAbsent(OperatorIdentity.normalize(identity), key -> new LinkedHashSet<>()) + .computeIfAbsent(OperatorIdentity.of(identity).value(), key -> new LinkedHashSet<>()) .add(operatorId); } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java index fbce2feb..fae6ed5a 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java @@ -85,7 +85,7 @@ void should_isolate_bulk_load_by_identity() { void should_share_cache_with_legacy_bulk_load_for_default_identity() { User user = new User(3, "user3"); - List loaded = cache.find(List.of(3L), OperatorIdentity.DEFAULT, + List loaded = cache.find(List.of(3L), OperatorIdentity.DEFAULT.value(), ids -> List.of(user)); assertEquals(1, loaded.size()); @@ -115,7 +115,7 @@ public List findByIds(List ids) { List operators = legacyGateway.findByIds(List.of(1L, 2L), "department1"); assertEquals(2, operators.size()); - assertEquals("", OperatorIdentity.of(operators.get(0))); + assertEquals("", OperatorIdentity.of(operators.get(0)).value()); } /** @@ -148,11 +148,11 @@ public List findByIds(List ids) { List operators = GatewayContext.getInstance().findByIds(List.of(1L), "department1"); assertEquals(1, operators.size()); - assertEquals("department1", OperatorIdentity.of(operators.get(0)), + assertEquals("department1", OperatorIdentity.of(operators.get(0)).value(), "批量路径不能把请求身份静默降级为默认身份"); // 单条读取必须命中同一个带身份的对象,说明缓存未被默认身份的对象污染 assertEquals("department1", - OperatorIdentity.of(FlowOperatorLocalThreadCache.getInstance().get(1, "department1", () -> null))); + OperatorIdentity.of(FlowOperatorLocalThreadCache.getInstance().get(1, "department1", () -> null)).value()); } /** diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/diagnostic/OperatorIdentityWarnLogTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/diagnostic/OperatorIdentityWarnLogTest.java new file mode 100644 index 00000000..a43943e3 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/diagnostic/OperatorIdentityWarnLogTest.java @@ -0,0 +1,65 @@ +package com.codingapi.flow.diagnostic; + +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 身份透传告警测试(#294 / #311 P5)。 + * + *

        每个用例用独立实例:去重状态归属实例,测试之间不需要「清空缓存」这种静态清理入口。 + */ +class OperatorIdentityWarnLogTest { + + private final OperatorIdentityWarnLog warnLog = new OperatorIdentityWarnLog(); + + @Test + void should_warn_when_requested_identity_is_dropped() { + User resolved = new User(1, "lorne"); + + assertTrue(warnLog.warnOnce(1, "department1", resolved)); + } + + @Test + void should_warn_once_per_participant() { + User resolved = new User(1, "lorne"); + + assertTrue(warnLog.warnOnce(1, "department1", resolved)); + assertFalse(warnLog.warnOnce(1, "department1", resolved), "同一参与人不应重复告警"); + assertTrue(warnLog.warnOnce(1, "department2", resolved), "不同身份应各自告警一次"); + } + + @Test + void should_not_warn_for_default_identity_or_missing_operator() { + User resolved = new User(1, "lorne"); + + assertFalse(warnLog.warnOnce(1, OperatorIdentity.DEFAULT.value(), resolved)); + assertFalse(warnLog.warnOnce(1, null, resolved)); + assertFalse(warnLog.warnOnce(1, "department1", null)); + } + + @Test + void should_not_warn_when_downstream_carries_identity() { + User resolved = User.withIdentity(1, "lorne", "department1"); + + assertFalse(warnLog.warnOnce(1, "department1", resolved)); + } + + @Test + void should_cap_warn_keys_to_avoid_log_flood() { + User resolved = new User(1, "lorne"); + + int warned = 0; + for (int i = 0; i < 300; i++) { + if (warnLog.warnOnce(1, "department" + i, resolved)) { + warned++; + } + } + + assertTrue(warned <= 256, "去重记录应有上限,实际告警次数:" + warned); + assertTrue(warned > 0); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java b/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java index a7a7cbc4..e83e9f2f 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java @@ -26,7 +26,7 @@ public IFlowOperator get(long id) { @Override public IFlowOperator get(long id, String identity) { User user = cache.get(id); - if (user == null || OperatorIdentity.isDefault(identity)) { + if (user == null || OperatorIdentity.of(identity).isDefault()) { return user; } return user.asIdentity(identity); @@ -45,7 +45,7 @@ public List findByIds(List ids) { @Override public List findByIds(List ids, String identity) { List operators = this.findByIds(ids); - if (OperatorIdentity.isDefault(identity)) { + if (OperatorIdentity.of(identity).isDefault()) { return operators; } return operators.stream() diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/mock/service/FlowRecordQueryMockIdentityTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/mock/service/FlowRecordQueryMockIdentityTest.java index 91f0062b..c8bf2c3d 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/mock/service/FlowRecordQueryMockIdentityTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/mock/service/FlowRecordQueryMockIdentityTest.java @@ -80,7 +80,7 @@ void should_treat_null_identity_as_default_for_legacy_records() { todoRepository.save(todo(3, OPERATOR_ID, "department1")); Page byNull = queryService.findTodoRecordPage(OPERATOR_ID, null, PAGE); - Page byEmpty = queryService.findTodoRecordPage(OPERATOR_ID, OperatorIdentity.DEFAULT, PAGE); + Page byEmpty = queryService.findTodoRecordPage(OPERATOR_ID, OperatorIdentity.DEFAULT.value(), PAGE); assertEquals(2, byNull.getTotalElements()); assertEquals(2, byEmpty.getTotalElements()); diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityGuardTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityGuardTest.java deleted file mode 100644 index 9f6399db..00000000 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityGuardTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.codingapi.flow.operator; - -import com.codingapi.flow.user.User; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * 身份透传告警测试(issue #288 衍生 / #294)。 - * - *

        下游不覆盖带身份的取人方法时,身份会被静默丢弃,前端按身份查待办会得到空列表。 - * 这里验证告警条件与去重:只在「请求身份非默认、回查结果身份为默认」时告警,且同一参与人只告警一次。 - */ -class OperatorIdentityGuardTest { - - @BeforeEach - void setUp() { - OperatorIdentityGuard.resetWarnedCache(); - } - - @Test - void should_warn_when_requested_identity_is_lost() { - User resolved = new User(1, "user1"); - - assertTrue(OperatorIdentityGuard.check(1, "department1", resolved)); - } - - @Test - void should_warn_only_once_for_same_operator_and_identity() { - User resolved = new User(1, "user1"); - - assertTrue(OperatorIdentityGuard.check(1, "department1", resolved)); - assertFalse(OperatorIdentityGuard.check(1, "department1", resolved), "同一参与人不应重复告警"); - assertTrue(OperatorIdentityGuard.check(1, "department2", resolved), "不同身份应各自告警一次"); - } - - @Test - void should_not_warn_for_default_identity() { - User resolved = new User(1, "user1"); - - assertFalse(OperatorIdentityGuard.check(1, OperatorIdentity.DEFAULT, resolved)); - assertFalse(OperatorIdentityGuard.check(1, null, resolved)); - } - - @Test - void should_not_warn_when_gateway_honors_identity() { - User resolved = User.withIdentity(1, "user1", "department1"); - - assertFalse(OperatorIdentityGuard.check(1, "department1", resolved)); - } - - @Test - void should_not_warn_when_operator_not_found() { - // 查不到人属于另一种错误(由上层按需处理),不应在这里刷身份告警 - assertFalse(OperatorIdentityGuard.check(1, "department1", null)); - } -} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityTest.java index fdc516ff..7837914d 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityTest.java @@ -19,7 +19,7 @@ void should_normalize_null_to_empty() { String identity = null; // when - String normalized = OperatorIdentity.normalize(identity); + String normalized = OperatorIdentity.of(identity).value(); // then assertEquals("", normalized); @@ -31,7 +31,7 @@ void should_keep_identity_value() { String identity = "department1"; // when - String normalized = OperatorIdentity.normalize(identity); + String normalized = OperatorIdentity.of(identity).value(); // then assertEquals("department1", normalized); @@ -39,17 +39,17 @@ void should_keep_identity_value() { @Test void should_treat_null_and_empty_as_default() { - assertTrue(OperatorIdentity.isDefault(null)); - assertTrue(OperatorIdentity.isDefault("")); - assertFalse(OperatorIdentity.isDefault("department1")); + assertTrue(OperatorIdentity.of((String) null).isDefault()); + assertTrue(OperatorIdentity.of("").isDefault()); + assertFalse(OperatorIdentity.of("department1").isDefault()); } @Test void should_compare_identities_null_safe() { - assertTrue(OperatorIdentity.same(null, "")); - assertTrue(OperatorIdentity.same("department1", "department1")); - assertFalse(OperatorIdentity.same("department1", "department2")); - assertFalse(OperatorIdentity.same(null, "department1")); + assertTrue(OperatorIdentity.of((String) null).same(OperatorIdentity.of(""))); + assertTrue(OperatorIdentity.of("department1").same(OperatorIdentity.of("department1"))); + assertFalse(OperatorIdentity.of("department1").same(OperatorIdentity.of("department2"))); + assertFalse(OperatorIdentity.of((String) null).same(OperatorIdentity.of("department1"))); } @Test @@ -58,8 +58,8 @@ void should_read_identity_from_operator_and_handle_null_operator() { IFlowOperator operator = new User(1, "张三"); // when & then - assertEquals("", OperatorIdentity.of(operator)); - assertEquals("", OperatorIdentity.of(null)); + assertEquals("", OperatorIdentity.of(operator).value()); + assertEquals("", OperatorIdentity.of((String) null).value()); } @Test @@ -97,7 +97,7 @@ void should_allow_downstream_override_identity() { IFlowOperator operator = new IdentityUser(1, "张三", "department1"); // when & then - assertEquals("department1", OperatorIdentity.of(operator)); + assertEquals("department1", OperatorIdentity.of(operator).value()); } /** diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityValidationTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityValidationTest.java index 66fa3701..86963659 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityValidationTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityValidationTest.java @@ -18,15 +18,15 @@ class OperatorIdentityValidationTest { @Test void should_normalize_null_to_default_and_keep_empty() { - assertEquals(OperatorIdentity.DEFAULT, OperatorIdentity.validate(null)); - assertEquals("", OperatorIdentity.validate("")); + assertEquals(OperatorIdentity.DEFAULT.value(), OperatorIdentity.of((String) null).validate().value()); + assertEquals("", OperatorIdentity.of("").validate().value()); } @Test void should_accept_identity_at_max_length() { String identity = "a".repeat(OperatorIdentity.MAX_LENGTH); - assertEquals(identity, OperatorIdentity.validate(identity)); + assertEquals(identity, OperatorIdentity.of(identity).validate().value()); } @Test @@ -34,14 +34,14 @@ void should_reject_identity_longer_than_max_length() { String identity = "a".repeat(OperatorIdentity.MAX_LENGTH + 1); FlowValidationException exception = assertThrows(FlowValidationException.class, - () -> OperatorIdentity.validate(identity)); + () -> OperatorIdentity.of(identity).validate().value()); assertTrue(exception.getMessage().contains("exceeds the max length"), exception.getMessage()); } @Test void should_reject_identity_containing_merge_key_separator() { FlowValidationException exception = assertThrows(FlowValidationException.class, - () -> OperatorIdentity.validate("department1#manager")); + () -> OperatorIdentity.of("department1#manager").validate().value()); assertTrue(exception.getMessage().contains("illegal character"), exception.getMessage()); } @@ -49,7 +49,7 @@ void should_reject_identity_containing_merge_key_separator() { @Test void should_reject_identity_containing_control_character() { FlowValidationException exception = assertThrows(FlowValidationException.class, - () -> OperatorIdentity.validate("department\u00011")); + () -> OperatorIdentity.of("department\u00011").validate().value()); assertTrue(exception.getMessage().contains("illegal character"), exception.getMessage()); } @@ -57,6 +57,6 @@ void should_reject_identity_containing_control_character() { @Test void should_keep_normalize_lenient_for_existing_data() { // 存量数据可能含非法字符,读取路径必须保持宽松,不能因为校验把历史流程读崩 - assertSame("department1#manager", OperatorIdentity.normalize("department1#manager")); + assertSame("department1#manager", OperatorIdentity.of("department1#manager").value()); } } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/script/node/OperatorLoadScriptTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/script/node/OperatorLoadScriptTest.java index 00158bee..6aa834bb 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/script/node/OperatorLoadScriptTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/script/node/OperatorLoadScriptTest.java @@ -86,7 +86,7 @@ def run(request){ assertEquals(1, operators.size()); assertEquals(1, operators.get(0).getUserId()); - assertEquals(OperatorIdentity.DEFAULT, operators.get(0).getIdentity()); + assertEquals(OperatorIdentity.DEFAULT.value(), operators.get(0).getIdentity()); } /** @@ -152,7 +152,7 @@ def run(request){ assertEquals(2, operators.get(0).getUserId()); assertEquals("department2", operators.get(0).getIdentity()); assertEquals(1, operators.get(1).getUserId()); - assertEquals(OperatorIdentity.DEFAULT, operators.get(1).getIdentity()); + assertEquals(OperatorIdentity.DEFAULT.value(), operators.get(1).getIdentity()); } /** diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java index 41c35c37..8440d2c6 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java @@ -54,8 +54,8 @@ void should_keep_default_identity_and_order_when_script_returns_user_ids() { assertEquals(2, operators.size()); assertEquals(2, operators.get(0).getUserId()); assertEquals(1, operators.get(1).getUserId()); - assertEquals(OperatorIdentity.DEFAULT, operators.get(0).getIdentity()); - assertEquals(OperatorIdentity.DEFAULT, operators.get(1).getIdentity()); + assertEquals(OperatorIdentity.DEFAULT.value(), operators.get(0).getIdentity()); + assertEquals(OperatorIdentity.DEFAULT.value(), operators.get(1).getIdentity()); } /** @@ -71,7 +71,7 @@ void should_apply_identity_when_script_returns_operator_keys() { assertEquals(2, operators.get(0).getUserId()); assertEquals("department1", operators.get(0).getIdentity()); assertEquals(1, operators.get(1).getUserId()); - assertEquals(OperatorIdentity.DEFAULT, operators.get(1).getIdentity()); + assertEquals(OperatorIdentity.DEFAULT.value(), operators.get(1).getIdentity()); } /** @@ -103,7 +103,7 @@ void should_resolve_mixed_forms_and_keep_script_order() { assertEquals(3, operators.size()); assertEquals(2, operators.get(0).getUserId()); - assertEquals(OperatorIdentity.DEFAULT, operators.get(0).getIdentity()); + assertEquals(OperatorIdentity.DEFAULT.value(), operators.get(0).getIdentity()); assertEquals(1, operators.get(1).getUserId()); assertEquals("department2", operators.get(1).getIdentity()); assertSame(direct, operators.get(2)); @@ -180,7 +180,7 @@ void should_parse_numeric_string_as_user_id() { assertEquals(1, operators.size()); assertEquals(2, operators.get(0).getUserId()); - assertEquals(OperatorIdentity.DEFAULT, operators.get(0).getIdentity()); + assertEquals(OperatorIdentity.DEFAULT.value(), operators.get(0).getIdentity()); } /** diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/script/request/GroovyScriptBindIdentityTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/script/request/GroovyScriptBindIdentityTest.java index ead4b3c4..d0f8e82e 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/script/request/GroovyScriptBindIdentityTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/script/request/GroovyScriptBindIdentityTest.java @@ -46,7 +46,7 @@ void should_load_operator_with_requested_identity() { assertNotNull(operator); assertEquals(2, operator.getUserId()); - assertEquals("department1", OperatorIdentity.of(operator)); + assertEquals("department1", OperatorIdentity.of(operator).value()); } /** @@ -58,12 +58,12 @@ void should_load_operator_with_requested_identity() { @Test void should_keep_default_identity_equivalent_to_legacy_method() { IFlowOperator legacy = bind.getOperatorById(2); - IFlowOperator byIdentity = bind.getOperatorByIdentity(2, OperatorIdentity.DEFAULT); + IFlowOperator byIdentity = bind.getOperatorByIdentity(2, OperatorIdentity.DEFAULT.value()); assertNotNull(legacy); assertNotNull(byIdentity); - assertEquals(OperatorIdentity.of(legacy), OperatorIdentity.of(byIdentity)); - assertEquals("", OperatorIdentity.of(byIdentity)); + assertEquals(OperatorIdentity.of(legacy).value(), OperatorIdentity.of(byIdentity).value()); + assertEquals("", OperatorIdentity.of(byIdentity).value()); } /** @@ -78,9 +78,9 @@ void should_isolate_two_identities_of_same_operator() { IFlowOperator department2 = bind.getOperatorByIdentity(2, "department2"); assertNotSame(department1, department2); - assertEquals("department1", OperatorIdentity.of(department1)); - assertEquals("department2", OperatorIdentity.of(department2)); + assertEquals("department1", OperatorIdentity.of(department1).value()); + assertEquals("department2", OperatorIdentity.of(department2).value()); // 再次取 department1 仍应是同一个带身份的对象,不能被 department2 覆盖 - assertEquals("department1", OperatorIdentity.of(bind.getOperatorByIdentity(2, "department1"))); + assertEquals("department1", OperatorIdentity.of(bind.getOperatorByIdentity(2, "department1")).value()); } } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowOperatorIdentityRecordTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowOperatorIdentityRecordTest.java index fe964b30..55049f76 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowOperatorIdentityRecordTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowOperatorIdentityRecordTest.java @@ -213,6 +213,6 @@ void should_clear_forward_identity_when_notify_is_reset() { record.clearNotify(); assertEquals(0, record.getForwardOperatorId()); - assertEquals(OperatorIdentity.DEFAULT, record.getForwardOperatorIdentity()); + assertEquals(OperatorIdentity.DEFAULT.value(), record.getForwardOperatorIdentity()); } } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/HandleOperatorIdentityFlowTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/HandleOperatorIdentityFlowTest.java index ef811bbf..735e746d 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/service/HandleOperatorIdentityFlowTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/HandleOperatorIdentityFlowTest.java @@ -89,14 +89,14 @@ void should_record_handle_operator_when_finishing_last_step() { submit(workflow, startRecordId, DEPARTMENT_1); FlowRecord approvalRecord = todoRecordOf(APPROVER); - assertEquals(OperatorIdentity.DEFAULT, approvalRecord.getCurrentOperatorIdentity(), + assertEquals(OperatorIdentity.DEFAULT.value(), approvalRecord.getCurrentOperatorIdentity(), "固定审批人脚本只返回 id,归属身份应为默认身份"); pass(workflow, approvalRecord.getId(), APPROVER, DEPARTMENT_2); FlowRecord done = factory.flowRecordRepository.get(approvalRecord.getId()); assertTrue(done.isDone(), "记录应已办结"); - assertEquals(OperatorIdentity.DEFAULT, done.getCurrentOperatorIdentity(), + assertEquals(OperatorIdentity.DEFAULT.value(), done.getCurrentOperatorIdentity(), "归属身份不能被办理行为改写"); assertEquals(APPROVER, done.getHandleOperatorId(), "办理人应留痕"); assertEquals("approver", done.getHandleOperatorName(), "办理人名称应留痕"); @@ -146,7 +146,7 @@ void should_not_record_handle_operator_when_saving_draft() { FlowRecord saved = factory.flowRecordRepository.get(approvalRecord.getId()); assertTrue(saved.isTodo(), "暂存后记录仍为待办"); assertEquals(0L, saved.getHandleOperatorId(), "暂存不应写办理人 id"); - assertEquals(OperatorIdentity.DEFAULT, saved.getHandleOperatorIdentity(), "暂存不应写办理人身份"); + assertEquals(OperatorIdentity.DEFAULT.value(), saved.getHandleOperatorIdentity(), "暂存不应写办理人身份"); } // ==================== 流程构建 ==================== diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java b/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java index 16016d9f..f28343bf 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java @@ -50,7 +50,7 @@ public static User withIdentity(long userId, String name, String identity) { * 返回同一用户以指定身份参与的副本(保留管理员、转交人等属性) */ public User asIdentity(String identity) { - return new User(userId, name, manager, forwardOperator, OperatorIdentity.normalize(identity)); + return new User(userId, name, manager, forwardOperator, OperatorIdentity.of(identity).value()); } @Override diff --git a/flow-engine-starter-api/src/main/java/com/codingapi/flow/api/OperatorIdentityHeader.java b/flow-engine-starter-api/src/main/java/com/codingapi/flow/api/OperatorIdentityHeader.java new file mode 100644 index 00000000..d1583e7a --- /dev/null +++ b/flow-engine-starter-api/src/main/java/com/codingapi/flow/api/OperatorIdentityHeader.java @@ -0,0 +1,49 @@ +package com.codingapi.flow.api; + +/** + * 身份请求头契约(issue #301 / #311 P5)。 + * + *

        身份是请求上下文,不属于领域模型:领域只认识 {@code OperatorIdentity} 值, + * 不知道它是从请求头还是别处来的。因此「读哪个头、头与 query 谁优先」这类约定放在接入层。 + * + *

        为什么不放 query 参数:引擎的查询接口用 {@code SearchRequest} 接收请求, + * 会把所有 query 参数当作实体过滤字段解析,多一个 {@code operatorIdentity} 就会抛 + * {@code Field operatorIdentity not found in class hierarchy}。 + * + *

        为兼容旧前端与 curl 直连,服务端仍保留 query 读取,但请求头优先。 + */ +public final class OperatorIdentityHeader { + + /** + * 当前身份的请求头名称 + */ + public static final String OPERATOR_IDENTITY = "X-Operator-Identity"; + + /** + * 查询身份范围的请求头名称,取值 {@code ALL} / {@code LOCKED} + */ + public static final String IDENTITY_SCOPE = "X-Identity-Scope"; + + /** + * 是否锁定身份查询的请求头名称,取值 {@code true} / {@code false} + */ + public static final String LOCK_IDENTITY = "X-Lock-Identity"; + + private OperatorIdentityHeader() { + } + + /** + * 选取身份原始值:请求头优先,其次请求参数。 + * + * @param headerValue 请求头中的原始值,未携带时为 {@code null} + * @param parameterValue 请求参数中的原始值 + * @param parameterPresent 请求参数是否显式出现(区分「未传」与「传了空串」) + * @return 原始值;两者都未携带时返回 {@code null} + */ + public static String resolve(String headerValue, String parameterValue, boolean parameterPresent) { + if (headerValue != null) { + return headerValue; + } + return parameterPresent ? parameterValue : null; + } +} 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 2455dc2a..dc465c93 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 @@ -3,6 +3,7 @@ import com.codingapi.flow.mock.MockInstance; import com.codingapi.flow.mock.MockInstanceFactory; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.api.OperatorIdentityHeader; import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.pojo.request.*; import com.codingapi.flow.pojo.response.ActionResponse; @@ -67,21 +68,21 @@ private long loadCurrentOperatorId() { private String loadCurrentOperatorIdentity() { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpServletRequest request = attributes.getRequest(); - String raw = OperatorIdentity.pick( - request.getHeader(OperatorIdentity.HEADER_OPERATOR_IDENTITY), + String raw = OperatorIdentityHeader.resolve( + request.getHeader(OperatorIdentityHeader.OPERATOR_IDENTITY), request.getParameter("operatorIdentity"), request.getParameterMap().containsKey("operatorIdentity")); if (raw != null) { // 入口即校验:长度 / 分隔符 / 控制字符不合法时直接拒绝,避免拖到落库阶段才失败 - return OperatorIdentity.validate(raw); + return OperatorIdentity.of(raw).validate().value(); } // 覆盖了 operatorId(联调、无登录态场景)时不再继承登录用户的身份, // 否则会得到「目标人员 + 当前登录人身份」的错配组合(issue #288 评审修复) if (StringUtils.hasText(request.getParameter("operatorId"))) { - return OperatorIdentity.DEFAULT; + return OperatorIdentity.DEFAULT.value(); } IFlowOperator current = (IFlowOperator) UserContext.getInstance().current(); - return current == null ? OperatorIdentity.DEFAULT : OperatorIdentity.of(current); + return current == null ? OperatorIdentity.DEFAULT.value() : OperatorIdentity.of(current).value(); } @GetMapping("/detail") diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityHeaderResolveTest.java b/flow-engine-starter-api/src/test/java/com/codingapi/flow/api/OperatorIdentityHeaderTest.java similarity index 69% rename from flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityHeaderResolveTest.java rename to flow-engine-starter-api/src/test/java/com/codingapi/flow/api/OperatorIdentityHeaderTest.java index a568bc70..3f927864 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityHeaderResolveTest.java +++ b/flow-engine-starter-api/src/test/java/com/codingapi/flow/api/OperatorIdentityHeaderTest.java @@ -1,6 +1,7 @@ -package com.codingapi.flow.operator; +package com.codingapi.flow.api; import com.codingapi.flow.exception.FlowValidationException; +import com.codingapi.flow.operator.OperatorIdentity; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -15,7 +16,7 @@ * {@code Field operatorIdentity not found in class hierarchy}。 * 改为请求头优先,同时保留 query 兼容。 */ -class OperatorIdentityHeaderResolveTest { +class OperatorIdentityHeaderTest { @Test void should_prefer_header_over_parameter() { @@ -24,26 +25,26 @@ void should_prefer_header_over_parameter() { String parameter = "department2"; // when - String raw = OperatorIdentity.pick(header, parameter, true); + String raw = OperatorIdentityHeader.resolve(header, parameter, true); // then:请求头优先 - assertEquals("department1", OperatorIdentity.validate(raw)); + assertEquals("department1", OperatorIdentity.of(raw).validate().value()); } @Test void should_fallback_to_parameter_when_header_absent() { // given:仅 query 携带(旧前端 / curl 直连) // when - String raw = OperatorIdentity.pick(null, "department1", true); + String raw = OperatorIdentityHeader.resolve(null, "department1", true); // then - assertEquals("department1", OperatorIdentity.validate(raw)); + assertEquals("department1", OperatorIdentity.of(raw).validate().value()); } @Test void should_return_null_when_neither_present() { // given / when:两者都未携带,交由调用方回退到登录用户身份 - String raw = OperatorIdentity.pick(null, null, false); + String raw = OperatorIdentityHeader.resolve(null, null, false); // then assertNull(raw); @@ -53,17 +54,17 @@ void should_return_null_when_neither_present() { void should_treat_empty_header_as_default_identity() { // given:显式选择「默认身份」时请求头为空串,需要与「未携带」区分 // when - String raw = OperatorIdentity.pick("", "department1", true); + String raw = OperatorIdentityHeader.resolve("", "department1", true); // then:空串表示默认身份,不能回退到 query - assertEquals(OperatorIdentity.DEFAULT, OperatorIdentity.validate(raw)); + assertEquals(OperatorIdentity.DEFAULT.value(), OperatorIdentity.of(raw).validate().value()); } @Test void should_reject_invalid_identity_from_header() { // given:请求头携带非法身份(包含合并键分隔符) // when / then:入口即拒绝,避免污染落库与缓存键 - String raw = OperatorIdentity.pick("department#1", null, false); - assertThrows(FlowValidationException.class, () -> OperatorIdentity.validate(raw)); + String raw = OperatorIdentityHeader.resolve("department#1", null, false); + assertThrows(FlowValidationException.class, () -> OperatorIdentity.of(raw).validate().value()); } } diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertor.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertor.java index b1810559..3370ba16 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertor.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertor.java @@ -22,14 +22,14 @@ public static FlowRecordContent convert(FlowTodoRecordEntity todoRecord){ content.setReadTime(todoRecord.getReadTime()); content.setCurrentOperatorId(todoRecord.getCurrentOperatorId()); content.setCurrentOperatorName(todoRecord.getCurrentOperatorName()); - content.setCurrentOperatorIdentity(OperatorIdentity.normalize(todoRecord.getCurrentOperatorIdentity())); + content.setCurrentOperatorIdentity(OperatorIdentity.of(todoRecord.getCurrentOperatorIdentity()).value()); content.setSubmitOperatorId(todoRecord.getSubmitOperatorId()); content.setSubmitOperatorName(todoRecord.getSubmitOperatorName()); - content.setSubmitOperatorIdentity(OperatorIdentity.normalize(todoRecord.getSubmitOperatorIdentity())); + content.setSubmitOperatorIdentity(OperatorIdentity.of(todoRecord.getSubmitOperatorIdentity()).value()); content.setCreateTime(todoRecord.getCreateTime()); content.setCreateOperatorId(todoRecord.getCreateOperatorId()); content.setCreateOperatorName(todoRecord.getCreateOperatorName()); - content.setCreateOperatorIdentity(OperatorIdentity.normalize(todoRecord.getCreateOperatorIdentity())); + content.setCreateOperatorIdentity(OperatorIdentity.of(todoRecord.getCreateOperatorIdentity()).value()); content.setTodoKey(todoRecord.getTodoKey()); content.setMargeCount(todoRecord.getMargeCount()); content.setMergeable(todoRecord.getMergeable()); @@ -55,14 +55,14 @@ public static FlowRecordContent convert(FlowRecordEntity record){ content.setReadTime(record.getReadTime()); content.setCurrentOperatorId(record.getCurrentOperatorId()); content.setCurrentOperatorName(record.getCurrentOperatorName()); - content.setCurrentOperatorIdentity(OperatorIdentity.normalize(record.getCurrentOperatorIdentity())); + content.setCurrentOperatorIdentity(OperatorIdentity.of(record.getCurrentOperatorIdentity()).value()); content.setSubmitOperatorId(record.getSubmitOperatorId()); content.setSubmitOperatorName(record.getSubmitOperatorName()); - content.setSubmitOperatorIdentity(OperatorIdentity.normalize(record.getSubmitOperatorIdentity())); + content.setSubmitOperatorIdentity(OperatorIdentity.of(record.getSubmitOperatorIdentity()).value()); content.setCreateTime(record.getCreateTime()); content.setCreateOperatorId(record.getCreateOperatorId()); content.setCreateOperatorName(record.getCreateOperatorName()); - content.setCreateOperatorIdentity(OperatorIdentity.normalize(record.getCreateOperatorIdentity())); + content.setCreateOperatorIdentity(OperatorIdentity.of(record.getCreateOperatorIdentity()).value()); content.setMergeable(record.getMergeable()); content.setRecordId(record.getId()); content.setTimeoutTime(record.getTimeoutTime()); @@ -72,7 +72,7 @@ public static FlowRecordContent convert(FlowRecordEntity record){ // issue #306:已办列表的办理人(历史数据为空,身份统一归一化为默认身份) content.setHandleOperatorId(record.getHandleOperatorId()); content.setHandleOperatorName(record.getHandleOperatorName()); - content.setHandleOperatorIdentity(OperatorIdentity.normalize(record.getHandleOperatorIdentity())); + content.setHandleOperatorIdentity(OperatorIdentity.of(record.getHandleOperatorIdentity()).value()); return content; } } diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java index 02d35e71..31c030f0 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java @@ -64,15 +64,15 @@ public static FlowRecord convert(FlowRecordEntity entity) { entity.getParallelBranchNodeId(), entity.getParallelBranchTotal(), // issue #288:历史数据 identity 列为 null,读取时统一归一化为默认身份 - OperatorIdentity.normalize(entity.getCreateOperatorIdentity()), - OperatorIdentity.normalize(entity.getSubmitOperatorIdentity()), - OperatorIdentity.normalize(entity.getCurrentOperatorIdentity()), - OperatorIdentity.normalize(entity.getForwardOperatorIdentity()), - OperatorIdentity.normalize(entity.getInterferedOperatorIdentity()), + OperatorIdentity.of(entity.getCreateOperatorIdentity()).value(), + OperatorIdentity.of(entity.getSubmitOperatorIdentity()).value(), + OperatorIdentity.of(entity.getCurrentOperatorIdentity()).value(), + OperatorIdentity.of(entity.getForwardOperatorIdentity()).value(), + OperatorIdentity.of(entity.getInterferedOperatorIdentity()).value(), // issue #306:办理人(历史数据为空) entity.getHandleOperatorId() == null ? 0L : entity.getHandleOperatorId(), entity.getHandleOperatorName(), - OperatorIdentity.normalize(entity.getHandleOperatorIdentity())); + OperatorIdentity.of(entity.getHandleOperatorIdentity()).value()); } public static FlowRecordEntity convert(FlowRecord record) { @@ -132,14 +132,14 @@ public static FlowRecordEntity convert(FlowRecord record) { entity.setParallelBranchNodeId(record.getParallelBranchNodeId()); entity.setParallelBranchTotal(record.getParallelBranchTotal()); // 写入前统一校验:长度与 DDL 列宽一致、禁止合并键分隔符与控制字符(issue #288 衍生 / #294) - entity.setCreateOperatorIdentity(OperatorIdentity.validate(record.getCreateOperatorIdentity())); - entity.setSubmitOperatorIdentity(OperatorIdentity.validate(record.getSubmitOperatorIdentity())); - entity.setCurrentOperatorIdentity(OperatorIdentity.validate(record.getCurrentOperatorIdentity())); - entity.setForwardOperatorIdentity(OperatorIdentity.validate(record.getForwardOperatorIdentity())); - entity.setInterferedOperatorIdentity(OperatorIdentity.validate(record.getInterferedOperatorIdentity())); + entity.setCreateOperatorIdentity(OperatorIdentity.of(record.getCreateOperatorIdentity()).validate().value()); + entity.setSubmitOperatorIdentity(OperatorIdentity.of(record.getSubmitOperatorIdentity()).validate().value()); + entity.setCurrentOperatorIdentity(OperatorIdentity.of(record.getCurrentOperatorIdentity()).validate().value()); + entity.setForwardOperatorIdentity(OperatorIdentity.of(record.getForwardOperatorIdentity()).validate().value()); + entity.setInterferedOperatorIdentity(OperatorIdentity.of(record.getInterferedOperatorIdentity()).validate().value()); entity.setHandleOperatorId(record.getHandleOperatorId()); entity.setHandleOperatorName(record.getHandleOperatorName()); - entity.setHandleOperatorIdentity(OperatorIdentity.validate(record.getHandleOperatorIdentity())); + entity.setHandleOperatorIdentity(OperatorIdentity.of(record.getHandleOperatorIdentity()).validate().value()); return entity; } diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowTodoRecordConvertor.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowTodoRecordConvertor.java index f30b65a5..965d9a0c 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowTodoRecordConvertor.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowTodoRecordConvertor.java @@ -34,9 +34,9 @@ public static FlowTodoRecord convert(FlowTodoRecordEntity entity){ entity.getRecordId(), entity.getTimeoutTime(), // issue #288:历史数据 identity 列为 null,读取时统一归一化为默认身份 - OperatorIdentity.normalize(entity.getCurrentOperatorIdentity()), - OperatorIdentity.normalize(entity.getSubmitOperatorIdentity()), - OperatorIdentity.normalize(entity.getCreateOperatorIdentity()) + OperatorIdentity.of(entity.getCurrentOperatorIdentity()).value(), + OperatorIdentity.of(entity.getSubmitOperatorIdentity()).value(), + OperatorIdentity.of(entity.getCreateOperatorIdentity()).value() ); } @@ -72,9 +72,9 @@ public static FlowTodoRecordEntity convert(FlowTodoRecord record){ entity.setRecordId(record.getRecordId()); entity.setTimeoutTime(record.getTimeoutTime()); // 写入前统一校验:长度与 DDL 列宽一致、禁止合并键分隔符与控制字符(issue #288 衍生 / #294) - entity.setCurrentOperatorIdentity(OperatorIdentity.validate(record.getCurrentOperatorIdentity())); - entity.setSubmitOperatorIdentity(OperatorIdentity.validate(record.getSubmitOperatorIdentity())); - entity.setCreateOperatorIdentity(OperatorIdentity.validate(record.getCreateOperatorIdentity())); + entity.setCurrentOperatorIdentity(OperatorIdentity.of(record.getCurrentOperatorIdentity()).validate().value()); + entity.setSubmitOperatorIdentity(OperatorIdentity.of(record.getSubmitOperatorIdentity()).validate().value()); + entity.setCreateOperatorIdentity(OperatorIdentity.of(record.getCreateOperatorIdentity()).validate().value()); return entity; } } diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowOperatorAssignmentRepositoryImpl.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowOperatorAssignmentRepositoryImpl.java index 03ca222f..3a72890c 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowOperatorAssignmentRepositoryImpl.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowOperatorAssignmentRepositoryImpl.java @@ -60,7 +60,7 @@ public List findOperators(String processId, String nodeId) { } private static String toJson(List operators) { - boolean hasIdentity = operators.stream().anyMatch(operator -> !OperatorIdentity.isDefault(operator.identity())); + boolean hasIdentity = operators.stream().anyMatch(operator -> !OperatorIdentity.of(operator.identity()).isDefault()); if (!hasIdentity) { // 默认身份保持历史格式,避免存量读取方(按 id 数组解析)失效 return JSON.toJSONString(operators.stream().map(OperatorKey::operatorId).toList()); diff --git a/flow-engine-starter-query/pom.xml b/flow-engine-starter-query/pom.xml index 10b52e53..be24a19d 100644 --- a/flow-engine-starter-query/pom.xml +++ b/flow-engine-starter-query/pom.xml @@ -27,6 +27,12 @@ com.codingapi.flow flow-engine-starter-infra + + + + com.codingapi.flow + flow-engine-starter-api + diff --git a/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java b/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java index 56269bb0..e14a518d 100644 --- a/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java +++ b/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java @@ -4,6 +4,7 @@ import com.codingapi.flow.mock.MockInstance; import com.codingapi.flow.mock.MockInstanceFactory; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.api.OperatorIdentityHeader; import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.pojo.response.FlowRecordContent; import com.codingapi.flow.query.FlowRecordQueryService; @@ -69,20 +70,20 @@ private long loadCurrentOperatorId(){ private String loadCurrentOperatorIdentity(){ ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpServletRequest request = attributes.getRequest(); - String raw = OperatorIdentity.pick( - request.getHeader(OperatorIdentity.HEADER_OPERATOR_IDENTITY), + String raw = OperatorIdentityHeader.resolve( + request.getHeader(OperatorIdentityHeader.OPERATOR_IDENTITY), request.getParameter("operatorIdentity"), request.getParameterMap().containsKey("operatorIdentity")); if(raw != null) { // 入口即校验,与命令侧口径一致(issue #288 评审修复) - return OperatorIdentity.validate(raw); + return OperatorIdentity.of(raw).validate().value(); } // 覆盖了 operatorId(联调、无登录态场景)时不再继承登录用户的身份,避免人员与身份错配 if(StringUtils.hasText(request.getParameter("operatorId"))) { - return OperatorIdentity.DEFAULT; + return OperatorIdentity.DEFAULT.value(); } IFlowOperator current = (IFlowOperator) UserContext.getInstance().current(); - return current == null ? OperatorIdentity.DEFAULT : OperatorIdentity.of(current); + return current == null ? OperatorIdentity.DEFAULT.value() : OperatorIdentity.of(current).value(); } @@ -109,13 +110,13 @@ private String loadCurrentOperatorIdentity(){ private boolean isIdentityLocked() { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpServletRequest request = attributes.getRequest(); - String scope = OperatorIdentity.pick( - request.getHeader(OperatorIdentity.HEADER_IDENTITY_SCOPE), + String scope = OperatorIdentityHeader.resolve( + request.getHeader(OperatorIdentityHeader.IDENTITY_SCOPE), request.getParameter(IDENTITY_SCOPE_PARAM), request.getParameterMap().containsKey(IDENTITY_SCOPE_PARAM)); if (!StringUtils.hasText(scope)) { - String locked = OperatorIdentity.pick( - request.getHeader(OperatorIdentity.HEADER_LOCK_IDENTITY), + String locked = OperatorIdentityHeader.resolve( + request.getHeader(OperatorIdentityHeader.LOCK_IDENTITY), request.getParameter(LOCK_IDENTITY_PARAM), request.getParameterMap().containsKey(LOCK_IDENTITY_PARAM)); return "true".equalsIgnoreCase(locked); diff --git a/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/service/FlowRecordQueryServiceImpl.java b/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/service/FlowRecordQueryServiceImpl.java index 2b3181e5..c124b104 100644 --- a/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/service/FlowRecordQueryServiceImpl.java +++ b/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/service/FlowRecordQueryServiceImpl.java @@ -37,7 +37,7 @@ public Page findTodoRecordPage(long userId, PageRequest reque @Override public Page findTodoRecordPage(long userId, String identity, PageRequest request) { Page page = flowTodoRecordEntityRepository.findTodoRecordPageByIdentity( - userId, OperatorIdentity.normalize(identity), request.withSort(Sort.by("id").descending())); + userId, OperatorIdentity.of(identity).value(), request.withSort(Sort.by("id").descending())); return page.map(FlowRecordContentConvertor::convert); } @@ -51,7 +51,7 @@ public Page findNotifyRecordPage(long userId, PageRequest req @Override public Page findNotifyRecordPage(long userId, String identity, PageRequest request) { Page page = flowRecordEntityRepository.findNotifyRecordPageByIdentity( - userId, OperatorIdentity.normalize(identity), request.withSort(Sort.by("id").descending())); + userId, OperatorIdentity.of(identity).value(), request.withSort(Sort.by("id").descending())); return page.map(FlowRecordContentConvertor::convert); } @@ -64,7 +64,7 @@ public Page findDoneRecordPage(long userId, PageRequest reque @Override public Page findDoneRecordPage(long userId, String identity, PageRequest request) { Page page = flowRecordEntityRepository.findDoneRecordPageByIdentity( - userId, OperatorIdentity.normalize(identity), request.withSort(Sort.by("id").descending())); + userId, OperatorIdentity.of(identity).value(), request.withSort(Sort.by("id").descending())); return page.map(FlowRecordContentConvertor::convert); } From 694c23885b2bd53852fca6c7879bd942f330fb1e Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Thu, 3 Dec 2026 18:06:28 +0800 Subject: [PATCH 32/35] =?UTF-8?q?docs(conventions):=20=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=E9=AA=8C=E6=94=B6=E8=AE=B0=E5=BD=95=E4=B8=AD=E7=9A=84=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E6=95=B0=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/conventions/domain/operator-identity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/conventions/domain/operator-identity.md b/docs/conventions/domain/operator-identity.md index 7b262f16..c08e5959 100644 --- a/docs/conventions/domain/operator-identity.md +++ b/docs/conventions/domain/operator-identity.md @@ -183,7 +183,7 @@ P5 移到 `flow-engine-starter-api` 的 `com.codingapi.flow.api.OperatorIdentity ### 验收 -- `./mvnw test` 全绿:framework 554 / 全仓 6 个模块通过 +- `./mvnw test` 全绿:framework 545、infra 8、api 7、starter 10、example 7,合计 577 - 现有身份相关测试的断言未因行为变化而修改;仅因 API 形态变化改了调用形式 - 新增测试:`OperatorKeyTest`、`OperatorManagerTest`、`TodoMergeKeyTest`、`OperatorIdentityContextTest`、`OperatorScriptElementTest`、`OperatorSelectionsTest`、`OperatorIdentityWarnLogTest` From 24190867791b32ec04fabed7638e3990318300c1 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Thu, 3 Dec 2026 19:53:10 +0800 Subject: [PATCH 33/35] 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 a8f5ff5e..3fbe89e7 160000 --- a/flow-frontend +++ b/flow-frontend @@ -1 +1 @@ -Subproject commit a8f5ff5ef0bb84093c530ca1c7ca7a47f3e85024 +Subproject commit 3fbe89e7178244251ac28d0fba89b13bb26e85d4 From acb4dfb81ee88f0f1da35a4d51d6c8144095553a Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Thu, 3 Dec 2026 20:22:26 +0800 Subject: [PATCH 34/35] =?UTF-8?q?docs:=20=E9=87=8D=E6=9E=84=E8=BA=AB?= =?UTF-8?q?=E4=BB=BD=E6=96=87=E6=A1=A3=E5=BD=92=E5=B1=9E=E5=B9=B6=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E6=96=87=E6=A1=A3=E7=BC=96=E5=86=99=E8=A7=84=E8=8C=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 删除 docs/conventions/domain/operator-identity.md:内容为改造前现状、 P1~P5 分批计划与落地记录,属过程文档,不满足「可判定规则」的定位 - 新增 docs/capabilities/flow-engine-framework/operator-identity.md: 当前模型构成、两个唯一真源(相等判定 / 键生成)、匹配模式、设计约束 - 新增 docs/conventions/docs/documentation.md:四类文档各有唯一归属、 过程记录不入规范、代码是唯一事实源、计数可复算、代码与文档同批提交 - AGENTS/CLAUDE 基本规范与 OperatorKey javadoc 的引用改到能力文档 - 同步修正 20 份文档中与 dev 代码不一致的事实:身份体系(请求头、 OperatorKey、身份脚本函数)、办理人留痕、事件 12 种、仓储 13 接口、 FlowService 10 入口、配置类改名、版本号 0.3.0-SNAPSHOT - flow-frontend 指针更新(多身份接入与 HttpClient 扩展点文档) --- AGENTS.md | 13 +- CLAUDE.md | 15 +- README.md | 4 +- docs/Integration/README.md | 22 +- docs/Integration/auto-configuration.md | 10 +- docs/Integration/event-integration.md | 6 +- docs/Integration/operator-identity.md | 14 +- docs/Integration/programmatic-api.md | 13 +- docs/Integration/quick-start.md | 14 +- docs/Integration/repository-integration.md | 17 +- docs/Integration/rest-api.md | 37 +++- docs/Integration/script-integration.md | 41 +++- docs/Integration/user-integration.md | 9 +- .../flow-engine-framework/flow-service.md | 10 +- .../operator-assignment.md | 43 ++-- .../operator-identity.md | 80 ++++++++ .../flow-engine-framework/repository.md | 2 + .../flow-engine-starter/auto-configuration.md | 2 +- docs/capabilities/index.md | 3 +- docs/capabilities/springboot/ioc.md | 2 +- docs/conventions/design/model-design.md | 4 +- docs/conventions/docs/documentation.md | 135 ++++++++++++ docs/conventions/domain/operator-identity.md | 193 ------------------ docs/conventions/index.md | 2 +- docs/manual/README.md | 2 +- docs/manual/integration-manual.html | 4 +- .../codingapi/flow/operator/OperatorKey.java | 2 +- flow-frontend | 2 +- 28 files changed, 415 insertions(+), 286 deletions(-) create mode 100644 docs/capabilities/flow-engine-framework/operator-identity.md create mode 100644 docs/conventions/docs/documentation.md delete mode 100644 docs/conventions/domain/operator-identity.md diff --git a/AGENTS.md b/AGENTS.md index 9b01e46e..05a690df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,7 +36,7 @@ Flow Engine 是一个企业级工作流引擎,基于 Java 17 和 Spring Boot 3 ### 服务编排模式(FlowService) -`FlowService`(`flow-engine-framework/.../service/FlowService.java`)是 `@Transactional` 业务入口,共 8 个入口方法(detail / processNodes / create / action / revoke / delete / urge / resetSubProcess)。**每个流程操作对应一个独立的 `FlowXxxService`**(`FlowCreateService` / `FlowActionService` / `FlowRevokeService` / `FlowDeleteService` / `FlowUrgeService` / `FlowDetailService` / `FlowProcessNodeService` / `FlowSubProcessResetService` / `FlowSubProcessResultService` / `FlowDelayTriggerService` / `OperatorAssignmentService` 等),通过 `IRepositoryHolder` 注入依赖,且每次操作前调用 `FlowOperatorLocalThreadCache.getInstance().clear()` 与 `FlowRuntimeScriptLocalCache` 清理线程缓存。新增流程操作应沿用此模式:新建 `FlowXxxService(request, repositoryHolder)`,并在 `FlowService` 暴露一个入口方法。 +`FlowService`(`flow-engine-framework/.../service/FlowService.java`)是 `@Transactional` 业务入口,共 10 个入口方法(detail / processNodes / create / action / revoke / delete / urge / resetSubProcess / reissue / forceSync)。**每个流程操作对应一个独立的 `FlowXxxService`**(`FlowCreateService` / `FlowActionService` / `FlowRevokeService` / `FlowDeleteService` / `FlowUrgeService` / `FlowDetailService` / `FlowProcessNodeService` / `FlowSubProcessResetService` / `FlowSubProcessResultService` / `FlowDelayTriggerService` / `OperatorAssignmentService` 等),通过 `IRepositoryHolder` 注入依赖,且每次操作前调用 `FlowOperatorLocalThreadCache.getInstance().clear()` 与 `FlowRuntimeScriptLocalCache` 清理线程缓存。新增流程操作应沿用此模式:新建 `FlowXxxService(request, repositoryHolder)`,并在 `FlowService` 暴露一个入口方法。 ### 仓储持有者(IRepositoryHolder) @@ -62,9 +62,9 @@ REST 层通过请求参数 `mockKey` 分流到 Mock 实例(见 `FlowRecordCont - `ActionManager` 持有节点动作 - 节点类型常量见 `StartNode.NODE_TYPE`(= `NodeType.START.name()`),`FlowRecord.isNodeType(String)` 用于按类型判定 -### 事件(IFlowEvent + EventPusher) +### 事件(IFlowEvent + FlowEventPublisher) -11 种事件:开始 / 待办 / 已办 / 完成 / 催办 / 撤销(`FlowRecordRevokeEvent`)/ 删除(`FlowRecordDeleteEvent`)/ 子流程重置(`FlowSubProcessResetEvent`)/ 减签(`FlowRecordReduceAuditEvent`)/ 二次发起(`FlowRecordReissueEvent`)/ 保存(`FlowRecordSaveEvent`,由 `FlowRecordSaveService.saveAll()` 按实际落库记录逐条推送)。操作完成后用 `FlowEventPublisher.push(event)` 推送(**禁止**直接调用 `EventPusher`);引入 starter 时由 `SpringFlowEventPublisher` 保证「事务提交后投递 + 按 `eventKey()`(默认 processId)分区串行」,未注册实现时自动回退 `EventPusher`。记录类事件携带 `FlowRecord` + `mock` 标记,重置事件携带新旧聚合组快照。外部可用 Spring `@EventListener` 订阅。 +12 种事件:开始 / 待办 / 已办 / 完成 / 催办 / 撤销(`FlowRecordRevokeEvent`)/ 删除(`FlowRecordDeleteEvent`)/ 子流程重置(`FlowSubProcessResetEvent`)/ 减签(`FlowRecordReduceAuditEvent`)/ 二次发起(`FlowRecordReissueEvent`)/ 保存(`FlowRecordSaveEvent`,由 `FlowRecordSaveService.saveAll()` 按实际落库记录逐条推送)/ 强制同步(`FlowRecordForceSyncEvent`,每个被同步实例一条)。操作完成后用 `FlowEventPublisher.push(event)` 推送(**禁止**直接调用 `EventPusher`);引入 starter 时由 `SpringFlowEventPublisher` 保证「事务提交后投递 + 按 `eventKey()`(默认 processId)分区串行」,未注册实现时自动回退 `EventPusher`。记录类事件携带 `FlowRecord` + `mock` 标记,重置事件携带新旧聚合组快照。外部可用 Spring `@EventListener` 订阅。 ### API 模块划分 @@ -110,6 +110,7 @@ cd flow-engine-example && mvn spring-boot:run ### 基本规范 - **与用户沟通及编写文档时,所有内容必须使用中文表述** +- **修改任何文档前必须先读 [文档编写与维护规范](./docs/conventions/docs/documentation.md)**:四类文档各有唯一归属,过程记录不入 `conventions/`,代码是唯一事实源 - **在每次修改代码以后,要执行本地化的编译验证确保代码没有错误** - Java 代码遵循 Spring Boot 规范 @@ -129,16 +130,14 @@ cd flow-engine-example && mvn spring-boot:run ### 多身份(Operator Identity) -改 `com.codingapi.flow.operator` 或任何涉及「人员 + 身份」的代码前,必须遵守 [docs/conventions/domain/operator-identity.md](./docs/conventions/domain/operator-identity.md)。四条硬线: +改 `com.codingapi.flow.operator` 或任何涉及「人员 + 身份」的代码前,必须先读 [多身份参与模型](./docs/capabilities/flow-engine-framework/operator-identity.md)。四条硬线: - **不得新增** `(long operatorId, String identity)` 形式的公开签名,一律传 `OperatorKey`; - 「是否同一参与人」只允许调 `OperatorKey#matches(..., mode)`,禁止内联 id/identity 比较; - 参与人键(缓存键 / Map 键 / 去重键)只允许由 `OperatorKey#key()` 产生,禁止自行拼字符串; - 匹配模式只能改变**判定**,不得在方法体里读 `matchMode()` 去改变**数据格式**(待办合并键、响应去重键)。 -提交前四问见规范正文;分批改造顺序 P1 相等收敛 → P2 键收敛 → P3 模式策略化 → P4 对象化 → P5 类型化,每批行为零变化且断言不改。 - -存量待改造清单见 issue #309,样板改造见 issue #308。 +接入方式与落库口径见 [集成说明](./docs/Integration/operator-identity.md)。 ### 测试规范 diff --git a/CLAUDE.md b/CLAUDE.md index 54fbebe2..4b98225a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ ## 项目概述 -Flow Engine 是一个企业级工作流引擎,基于 Java 17 和 Spring Boot 3.5.9 构建(当前版本 0.1.0-SNAPSHOT)。 +Flow Engine 是一个企业级工作流引擎,基于 Java 17 和 Spring Boot 3.5.9 构建(当前版本 0.3.0-SNAPSHOT)。 ### 核心模块 @@ -36,7 +36,7 @@ Flow Engine 是一个企业级工作流引擎,基于 Java 17 和 Spring Boot 3 ### 服务编排模式(FlowService) -`FlowService`(`flow-engine-framework/.../service/FlowService.java`)是 `@Transactional` 业务入口,共 8 个入口方法(detail / processNodes / create / action / revoke / delete / urge / resetSubProcess)。**每个流程操作对应一个独立的 `FlowXxxService`**(`FlowCreateService` / `FlowActionService` / `FlowRevokeService` / `FlowDeleteService` / `FlowUrgeService` / `FlowDetailService` / `FlowProcessNodeService` / `FlowSubProcessResetService` / `FlowSubProcessResultService` / `FlowDelayTriggerService` / `OperatorAssignmentService` 等),通过 `IRepositoryHolder` 注入依赖,且每次操作前调用 `FlowOperatorLocalThreadCache.getInstance().clear()` 与 `FlowRuntimeScriptLocalCache` 清理线程缓存。新增流程操作应沿用此模式:新建 `FlowXxxService(request, repositoryHolder)`,并在 `FlowService` 暴露一个入口方法。 +`FlowService`(`flow-engine-framework/.../service/FlowService.java`)是 `@Transactional` 业务入口,共 10 个入口方法(detail / processNodes / create / action / revoke / delete / urge / resetSubProcess / reissue / forceSync)。**每个流程操作对应一个独立的 `FlowXxxService`**(`FlowCreateService` / `FlowActionService` / `FlowRevokeService` / `FlowDeleteService` / `FlowUrgeService` / `FlowDetailService` / `FlowProcessNodeService` / `FlowSubProcessResetService` / `FlowSubProcessResultService` / `FlowReissueService` / `FlowForceSyncService` / `FlowDelayTriggerService` / `OperatorAssignmentService` 等),通过 `IRepositoryHolder` 注入依赖,且每次操作前调用 `FlowOperatorLocalThreadCache.getInstance().clear()` 与 `FlowRuntimeScriptLocalCache` 清理线程缓存。新增流程操作应沿用此模式:新建 `FlowXxxService(request, repositoryHolder)`,并在 `FlowService` 暴露一个入口方法。 ### 仓储持有者(IRepositoryHolder) @@ -62,9 +62,9 @@ REST 层通过请求参数 `mockKey` 分流到 Mock 实例(见 `FlowRecordCont - `ActionManager` 持有节点动作 - 节点类型常量见 `StartNode.NODE_TYPE`(= `NodeType.START.name()`),`FlowRecord.isNodeType(String)` 用于按类型判定 -### 事件(IFlowEvent + EventPusher) +### 事件(IFlowEvent + FlowEventPublisher) -9 种事件:开始 / 待办 / 已办 / 完成 / 催办 / 撤销(`FlowRecordRevokeEvent`)/ 删除(`FlowRecordDeleteEvent`)/ 减签(`FlowRecordReduceAuditEvent`)/ 子流程重置(`FlowSubProcessResetEvent`)。操作完成后用 `EventPusher.push(event)` 推送;记录类事件携带 `FlowRecord` + `mock` 标记,重置事件携带新旧聚合组快照。外部可用 Spring `@EventListener` 订阅。 +12 种事件:开始 / 待办 / 已办 / 完成 / 催办 / 撤销(`FlowRecordRevokeEvent`)/ 删除(`FlowRecordDeleteEvent`)/ 减签(`FlowRecordReduceAuditEvent`)/ 子流程重置(`FlowSubProcessResetEvent`)/ 二次发起(`FlowRecordReissueEvent`)/ 保存(`FlowRecordSaveEvent`)/ 强制同步(`FlowRecordForceSyncEvent`)。操作完成后用 `FlowEventPublisher.push(event)` 推送(**禁止**直接调用 `EventPusher`);引入 starter 时由 `SpringFlowEventPublisher` 保证「事务提交后投递 + 按 `eventKey()` 分区串行」,未注册实现时自动回退 `EventPusher`。记录类事件携带 `FlowRecord` + `mock` 标记,重置事件携带新旧聚合组快照。外部可用 Spring `@EventListener` 订阅。 ### API 模块划分 @@ -103,6 +103,7 @@ cd flow-engine-example && mvn spring-boot:run ### 基本规范 - **与用户沟通及编写文档时,所有内容必须使用中文表述** +- **修改任何文档前必须先读 [文档编写与维护规范](./docs/conventions/docs/documentation.md)**:四类文档各有唯一归属,过程记录不入 `conventions/`,代码是唯一事实源 - **在每次修改代码以后,要执行本地化的编译验证确保代码没有错误** - Java 代码遵循 Spring Boot 规范 @@ -122,16 +123,14 @@ cd flow-engine-example && mvn spring-boot:run ### 多身份(Operator Identity) -改 `com.codingapi.flow.operator` 或任何涉及「人员 + 身份」的代码前,必须遵守 [docs/conventions/domain/operator-identity.md](./docs/conventions/domain/operator-identity.md)。四条硬线: +改 `com.codingapi.flow.operator` 或任何涉及「人员 + 身份」的代码前,必须先读 [多身份参与模型](./docs/capabilities/flow-engine-framework/operator-identity.md)。四条硬线: - **不得新增** `(long operatorId, String identity)` 形式的公开签名,一律传 `OperatorKey`; - 「是否同一参与人」只允许调 `OperatorKey#matches(..., mode)`,禁止内联 id/identity 比较; - 参与人键(缓存键 / Map 键 / 去重键)只允许由 `OperatorKey#key()` 产生,禁止自行拼字符串; - 匹配模式只能改变**判定**,不得在方法体里读 `matchMode()` 去改变**数据格式**(待办合并键、响应去重键)。 -提交前四问见规范正文;分批改造顺序 P1 相等收敛 → P2 键收敛 → P3 模式策略化 → P4 对象化 → P5 类型化,每批行为零变化且断言不改。 - -存量待改造清单见 issue #309,样板改造见 issue #308。 +接入方式与落库口径见 [集成说明](./docs/Integration/operator-identity.md)。 ### 测试规范 diff --git a/README.md b/README.md index 575283dd..6cb3d5b7 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ flow-engine ├── flow-engine-framework # 核心流程引擎框架 ├── flow-engine-starter # Spring Boot 自动配置入口 ├── flow-engine-starter-api # REST API 层(命令操作:create / action / revoke / delete / urge / detail / processNodes / subProcess/reset,含节点视图脚本接口) -├── flow-engine-starter-infra # 持久化层(JPA 实体、11 个仓储实现、含达梦方言) +├── flow-engine-starter-infra # 持久化层(JPA 实体、12 个仓储实现、含达梦方言) ├── flow-engine-starter-query # 查询层(流程记录与流程定义只读 API) ├── flow-engine-example # 示例应用(H2/达梦数据库、JWT 认证、端口 8090) └── flow-frontend # 前端项目(独立 Git 仓库,PC + 移动端,详见下文“前端模块架构”) @@ -53,7 +53,7 @@ flow-engine | `manager` | 管理器层:动作、节点、策略、操作者管理 | | `session` | 执行上下文:FlowSession、FlowAdvice、IRepositoryHolder | | `record` | 流程记录:FlowRecord、FlowTodoRecord、FlowTodoMerge | -| `repository` | 12 个仓储接口(持久化抽象,由 infra 模块实现) | +| `repository` | 13 个仓储接口(持久化抽象,由 infra 模块实现) | | `event` | 9 种流程事件:开始 / 待办 / 已办 / 完成 / 催办 / 撤销 / 删除 / 减签 / 子流程重置 | | `exception` | 框架异常体系:异常基类 + 6 种具体异常(验证 / 未找到 / 状态 / 权限 / 执行 / 导入导出) | | `form` | 表单系统:字段定义、数据校验、字段权限、值转换 | diff --git a/docs/Integration/README.md b/docs/Integration/README.md index 90d02763..3a87169f 100644 --- a/docs/Integration/README.md +++ b/docs/Integration/README.md @@ -8,7 +8,7 @@ |------|------|----------| | `flow-engine-framework` | 核心引擎:节点/动作/策略/脚本/服务/仓储接口(Spring 无关的领域核心) | 只读,一般不改动 | | `flow-engine-starter` | Spring Boot 自动配置入口,把引擎单例与 Spring 容器打通 | 直接依赖 | -| `flow-engine-starter-infra` | JPA 持久化实现(11 张 `t_flow_*` 表 + 11 个仓储实现) | 可直接依赖;也可自行实现仓储接口替换 | +| `flow-engine-starter-infra` | JPA 持久化实现(11 张 `t_flow_*` 表 + 12 个仓储实现) | 可直接依赖;也可自行实现仓储接口替换 | | `flow-engine-starter-api` | 命令 REST API(发起/审批/撤销/催办/删除 + 流程设计 CRUD) | 可选依赖 | | `flow-engine-starter-query` | 查询 REST API(待办/已办/抄送/全部列表) | 可选依赖 | | `flow-engine-example` | 下游集成范本(用户体系、事件订阅、脚本仓储、安全) | 参考实现 | @@ -23,7 +23,7 @@ | 2 | `IFlowOperator` 实现类 | 用户实体/DTO,实现 `getUserId/getName/isFlowManager/forwardOperator` | [流程用户体系](./user-integration.md) | | 3 | `NodeViewJavaScriptRepository` | 节点视图 JS 持久化(infra 不提供,需自建) | [仓储抽象](./repository-integration.md) | | 4 | 脚本持久化:`GroovyScriptRepository`、`TempGroovyScriptRepository` | Groovy 脚本落库(外部 starter-script 的 SPI) | [仓储抽象](./repository-integration.md) | -| 5 | 11 个仓储接口(仅当不引入 `flow-engine-starter-infra` 时) | 自行实现存储 | [仓储抽象](./repository-integration.md) | +| 5 | 13 个仓储接口(仅当不引入 `flow-engine-starter-infra` 时) | 自行实现存储 | [仓储抽象](./repository-integration.md) | ## 文档目录 @@ -33,9 +33,9 @@ | [流程用户体系](./user-integration.md) | `FlowOperatorGateway` / `IFlowOperator` / `GatewayContext` / 线程缓存 / 当前登录人 | | [多身份参与](./operator-identity.md) | 同一人员多身份:身份 SPI、请求声明、查询范围、判定模式(`USER_ONLY`/`STRICT`)、升级 DDL | | [流程默认脚本](./script-integration.md) | 12 种脚本类型、`GroovyScriptRequest` 完整 API、`$bind`、默认脚本替换、脚本生命周期 | -| [流程事件机制](./event-integration.md) | 9 种事件、`EventPusher`、`IHandler` 订阅、异步分发管道、事务变体、推送时机 | -| [仓储抽象与持久化](./repository-integration.md) | `IRepositoryHolder`、12 个仓储接口(含 11 个 JPA 实现 + 需自行实现的 `NodeViewJavaScriptRepository`)、脚本仓储、锁机制 | -| [Spring Boot 自动配置](./auto-configuration.md) | `AutoConfiguration` 10 个 Bean、5 个 Register、必选/可选 Bean 清单、配置项 | +| [流程事件机制](./event-integration.md) | 12 种事件、`FlowEventPublisher`、`IHandler` 订阅、异步分发管道、事务变体、推送时机 | +| [仓储抽象与持久化](./repository-integration.md) | `IRepositoryHolder`、13 个仓储接口(含 12 个 JPA 实现 + 需自行实现的 `NodeViewJavaScriptRepository`)、脚本仓储、锁机制 | +| [Spring Boot 自动配置](./auto-configuration.md) | `AutoConfiguration` 10 个 Bean、5 个启动注册器、必选/可选 Bean 清单、配置项 | | [REST API](./rest-api.md) | 5 个 Controller、`mockKey`/`operatorId` 分流机制、请求/响应结构 | | [Mock 模式](./mock-mode.md) | 全内存沙箱 `MockInstance`、15 分钟过期、接入方式 | | [节点/动作/策略扩展](./extension-points.md) | 19 种节点 × 9 种动作 × 15 种节点策略 × 2 种流程策略,扩展方式 | @@ -54,25 +54,27 @@ | `FlowScriptContext` | 脚本 `$bind` 上下文(`IBeanFactory`) | `FlowScriptContextRegister` | | `FlowIDGeneratorGatewayContext` | ID 生成器(可替换扩展点) | 默认内建,可选替换 | | `NodeViewJavaScriptCacheContext` | 节点视图 JS 缓存(15 分钟) | `NodeViewJavaScriptCacheContextRegister` | -| `FlowOperatorLocalThreadCache` | 操作人线程缓存 | 引擎内部使用 | +| `FlowOperatorLocalThreadCache` | 操作人线程缓存(键含身份) | 引擎内部使用 | | `FlowRuntimeScriptLocalCache` | 脚本快照线程缓存 | 引擎内部使用 | +| `OperatorIdentityContext` | 身份匹配模式(可变全局配置,默认 `STRICT`) | `OperatorIdentityConfigurer`(starter 启动时写入) | | `MockInstanceFactory` | Mock 沙箱工厂 | api 模块调用 | ### 执行链路 ``` REST 请求 → FlowRecordController - (mockKey 分流 Mock / 生产;operatorId 覆盖当前用户) + (mockKey 分流 Mock / 生产;operatorId 覆盖当前用户;X-Operator-Identity 声明身份) → FlowService(@Transactional,清线程缓存) - → FlowXxxService(create / action / revoke / delete / urge / detail) + → FlowXxxService(create / action / revoke / delete / urge / detail / + processNodes / resetSubProcess / reissue / forceSync) → FlowSession(不可变会话)→ 节点 handle → 动作 run → 策略执行 → repositoryHolder.saveRecords(落库) - → EventPusher.push(推送事件,异步) + → FlowEventPublisher.push(推送事件;starter 下事务提交后按流程分区串行) ``` ## 版本约定 -- 引擎版本:`0.1.0-SNAPSHOT`(根 pom `revision`) +- 引擎版本:`0.3.0-SNAPSHOT`(根 pom `revision`) - 外部框架依赖(根 pom `codingapi.framework.version = 17.3.1`): - `com.codingapi.springboot:springboot-starter` —— 事件体系(`EventPusher`/`IHandler`)、`UserContext`、`LocaleMessageException` - `com.codingapi.springboot:springboot-starter-script` —— Groovy 脚本引擎(`GroovyScript`/注解/仓储 SPI) diff --git a/docs/Integration/auto-configuration.md b/docs/Integration/auto-configuration.md index 6c46e192..5b1b61af 100644 --- a/docs/Integration/auto-configuration.md +++ b/docs/Integration/auto-configuration.md @@ -17,12 +17,12 @@ | @Bean | 依赖 | 作用 | |---|---|---| -| `OperatorIdentityPolicyRegister` | `FlowProperties` | 启动时把 `codingapi.flow.identity.match-mode` 写入 framework 的 `OperatorIdentityPolicy`(issue #297) | +| `OperatorIdentityConfigurer` | `FlowProperties` | 启动时把 `codingapi.flow.identity.match-mode` 写入 framework 的 `OperatorIdentityContext`(issue #297 / #311 P3) | | `NodeViewJavaScriptCacheContextRegister` | **`NodeViewJavaScriptRepository`** | 构造器内执行 `NodeViewJavaScriptCacheContext.getInstance().setNodeViewJavaScriptRepository(repo)`(15 分钟缓存上下文) | | `GatewayContextRegister` | **`FlowOperatorGateway`** | 把操作人网关灌入 `GatewayContext` 单例(`InitializingBean`) | | `FlowScriptContextRegister` | `ApplicationContext` + **`FlowOperatorGateway`** + `FlowRecordRepository` | 给 `FlowScriptContext` 单例设置 `IBeanFactory`(转发 Spring 容器,脚本 `$bind` 依赖) | | `RepositoryHolderContextRegister` | `WorkflowService` + `FlowRecordService` + 6 个仓储 + `GatewayContextRegister` | 把 8 个依赖灌入 `RepositoryHolderContext` 单例(`InitializingBean`) | -| `SpringFlowEventPublisher` | `ApplicationContext` | 事务提交后投递 + 按流程 id 分区串行(可用 `codingapi.flow.event.ordered=false` 关闭,关闭后回退事件框架直投) | +| `SpringFlowEventPublisher` | `ApplicationContext` | 事务提交后投递 + 按流程 id 分区串行(可用 `codingapi.flow.event.ordered=false` 关闭,关闭后回退事件框架直投;`IFlowEvent.eventKey()` 默认取 `processId`,强制同步/子流程重置事件取主流程 id) | | `FlowRecordService` | `FlowTodoRecordRepository` + `FlowTodoMergeRepository` + `FlowRecordRepository` | 记录服务 Bean | | `WorkflowService` | `WorkflowVersionRepository` + `WorkflowRepository` + `WorkflowRuntimeRepository` | 流程设计服务 Bean | | `FlowService` | `RepositoryHolderContextRegister`(仅保证顺序) | `new FlowService(RepositoryHolderContext.getInstance())`,业务入口 | @@ -33,11 +33,11 @@ 全部位于 `flow-engine-starter/src/main/java/com/codingapi/flow/register/`,均实现 `InitializingBean`: ```java -// OperatorIdentityPolicyRegister(issue #297) +// OperatorIdentityConfigurer(issue #297 / #311 P3) @Override public void afterPropertiesSet() { // framework 不依赖 Spring,模式通过静态持有者传递 - OperatorIdentityPolicy.setMatchMode(flowProperties.getIdentity().getMatchMode()); + OperatorIdentityContext.getInstance().use(flowProperties.getIdentity().getMatchMode()); } // GatewayContextRegister @@ -83,7 +83,7 @@ public void afterPropertiesSet() { | 1 | `FlowOperatorGateway` | 对接应用用户体系(`get`/`findByIds`) | `GatewayContextRegister` → `GatewayContext`;同时被 `FlowScriptContextRegister`、api Controller 依赖 | | 2 | `IFlowOperator` 实现类 | 用户实体/DTO | 由 Gateway 返回,经 `FlowOperatorLocalThreadCache` 缓存 | | 3 | `NodeViewJavaScriptRepository` | 节点视图 JS 持久化(infra 无实现) | `NodeViewJavaScriptCacheContextRegister` 构造器 | -| 4 | 11 个仓储接口实现 | 引入 `flow-engine-starter-infra` 则自动提供;否则自行实现 | `RepositoryHolderContextRegister` / `FlowRecordService` / `WorkflowService` | +| 4 | 13 个仓储接口实现 | 引入 `flow-engine-starter-infra` 则自动提供;否则自行实现 | `RepositoryHolderContextRegister` / `FlowRecordService` / `WorkflowService` | | 5 | `GroovyScriptRepository` + `TempGroovyScriptRepository` | 脚本持久化 SPI(外部 starter-script) | 自注册到对应 `*RepositoryContext` 单例 | ### 可选(有默认实现 / 按需替换) diff --git a/docs/Integration/event-integration.md b/docs/Integration/event-integration.md index 0abb0702..66f1ef35 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`)。 @@ -44,6 +44,7 @@ public interface IAsyncEvent extends IEvent {} // 异步事件标记 ← | `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()` | | `FlowRecordSaveEvent` | 流程记录保存(每条实际落库记录,issue #280) | `FlowRecord, boolean mock` | `getFlowRecord()` / `isMock()` | +| `FlowRecordForceSyncEvent` | 运行中实例强制同步最新流程设计(issue #281) | `FlowRecord flowRecord, long oldWorkRuntimeId, long newWorkRuntimeId, boolean mock` | `getFlowRecord()` / `getOldWorkRuntimeId()` / `getNewWorkRuntimeId()` / `isMock()` | **子流程重置事件订阅须知**: @@ -71,7 +72,7 @@ public class FlowRecordUrgeEvent implements IFlowEvent { `FlowRecord`(`flow-engine-framework/.../record/FlowRecord.java`)提供: - 基本信息:`getId()`、`getProcessId()`、`getWorkTitle()`、`getWorkCode()`、`getNodeId()`、`getNodeType()`、`getNodeName()`、`getTitle()`、`getFormData()`(`Map`) -- 操作人:`getCurrentOperatorId/Name()`、`getSubmitOperatorId/Name()`、`getCreateOperatorId/Name()`、`getForwardOperatorId/Name()` +- 操作人:`getCurrentOperatorId/Name/Identity()`、`getSubmitOperatorId/Name/Identity()`、`getCreateOperatorId/Name/Identity()`、`getForwardOperatorId/Name/Identity()`、`getHandleOperatorId/Name/Identity()`(办理人,issue #306) - 状态:`isTodo()`、`isDone()`、`isFinish()`、`isAutoDone()`、`isShow()`、`isNotEndNode()`、`isPendingApproval()`(待审批,含顺序审批未激活的隐藏记录) - 抄送标记:`isNotify()` - 动作:`getActionId()`、`getActionType()`、`getActionName()`、`getAdvice()` @@ -134,6 +135,7 @@ public class EventPusher { | `FlowSubProcessResetService.reset()` | 被作废记录链逐条 `RevokeEvent` + 子流程重置 `SubProcessResetEvent`;重建实例经 `FlowCreateService` 推送各自的 `StartEvent` + `TodoEvent` | | `FlowReissueService.reissue()` | 二次发起 `ReissueEvent` + 新流程经 `FlowCreateService` 推送的 `StartEvent` + `TodoEvent` | | `FlowRecordSaveService.saveAll()` | 本次实际落库的每条记录 `SaveEvent`(结束节点虚拟记录不落库,不推送) | +| `FlowForceSyncService.forceSync()` | 每个被同步实例一条 `ForceSyncEvent`(旧 → 新运行时快照 id) | > 事件在业务数据保存之后推送,且引入 starter 时会在**事务提交后**才投递给订阅方(见 4.5),保证订阅方回查到的记录已持久化。 diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md index 316487d0..5df26680 100644 --- a/docs/Integration/operator-identity.md +++ b/docs/Integration/operator-identity.md @@ -43,7 +43,7 @@ public interface IFlowOperator extends IUser { * 身份标识,空串表示默认身份。框架不解释语义。 */ default String getIdentity() { - return OperatorIdentity.DEFAULT; + return OperatorIdentity.DEFAULT.value(); } } ``` @@ -75,7 +75,7 @@ public class User implements IFlowOperator { @Override public IFlowOperator get(long id, String identity) { User user = userRepository.getUserById(id); - if (user == null || OperatorIdentity.isDefault(identity)) { + if (user == null || OperatorIdentity.of(identity).isDefault()) { return user; } // 必须复制:直接改写实体会污染持久化上下文 / 线程缓存,导致同一 id 的两个身份互相覆盖 @@ -294,7 +294,7 @@ def run(request) { ### 4.4 办理权限判定(可配置模式) -「当前用户能否办理/撤回/催办/减签某条记录」统一由 `OperatorIdentityPolicy` 判定,模式可配置: +「当前用户能否办理/撤回/催办/减签某条记录」统一由 `OperatorIdentityContext` 判定(原 `OperatorIdentityPolicy`,issue #311 P3 改名;它只持有模式,判定规则唯一落在 `OperatorKey#matches`),模式可配置: | 模式 | 判定 | 适用 | |------|------|------| @@ -333,7 +333,7 @@ def run(request) { ### 4.5 身份写入约束 -落库前统一经 `OperatorIdentity.validate()`: +落库前统一经 `OperatorIdentity.of(raw).validate()`: | 约束 | 原因 | |------|------| @@ -341,13 +341,13 @@ def run(request) { | 不含 `#` | 与待办合并键的身份后缀分隔符冲突 | | 不含控制字符 | 内部缓存键以控制字符拼接 | -读取路径仍用宽松的 `normalize()`(仅 null → 空串),历史数据不会被校验拦住;请求入口(REST 的两个 `operatorIdentity` 参数)同样会先校验,非法值在入口即被拒绝。 +读取路径仍用宽松的 `OperatorIdentity.of(raw)`(仅把 `null`/空串归一化为默认身份,不做校验),历史数据不会被拦住;请求入口(REST 的两个 `operatorIdentity` 来源)同样会先经 `validate()` 校验,非法值在入口即被拒绝。 人员分配表 `t_flow_operator_assignment` **无需改表**:身份编码在 `operatorIds` JSON 列内。全部为默认身份时保持历史格式 `[1,2,3]`;存在非默认身份时写 `[{"operatorId":2,"identity":"department1"}]`,读取端同时兼容两种格式。 ### 4.6 身份匹配模式配置(issue #297) -配置类 `com.codingapi.flow.properties.FlowProperties` 位于 `flow-engine-starter`,启动时由 `OperatorIdentityPolicyRegister` 写入 framework: +配置类 `com.codingapi.flow.properties.FlowProperties` 位于 `flow-engine-starter`,启动时由 `OperatorIdentityConfigurer` 写入 framework 的 `OperatorIdentityContext`: ```properties # 不限制身份(starter 默认):同一个人换身份仍可办理自己的待办 @@ -368,7 +368,7 @@ codingapi.flow.identity.match-mode=USER_ONLY | 存量数据 | 新列为 NULL,按默认身份读取,**无需回填** | | 回滚 | 仅新增 nullable 列,旧版本不映射新列,可直接回滚 | | 工作流定义 | 与身份无关,导入导出不受影响 | -| 身份长度 | ≤ 64 字符(复合 key 用 `:` 拼接),入口与落库双处校验 | +| 身份长度 | ≤ 64 字符;内部参与人键以控制字符 `U+0001` 拼接(`OperatorKey.KEY_SEPARATOR`,不对业务暴露),身份本身不允许包含 `#`(待办合并键后缀保留字符),入口与落库双处校验 | | 待办索引 | 实体未声明 `@Index`,大表请按 DDL 脚本手工加索引 | | 默认取人脚本 | issue #303 起新建节点的默认脚本返回 `OperatorKey`(创建者以发起身份参与);存量流程定义中的旧脚本不受影响,不迁移 | | 办理人留痕 | issue #306 起 `handle_operator_*` 记录办理人与办理身份;存量记录为空,前端回退到 `current_operator_identity` 展示,行为与升级前一致;如需回填,按 `finish_time` 与下游 `submit_operator_*` 推断,引擎不做自动迁移 | diff --git a/docs/Integration/programmatic-api.md b/docs/Integration/programmatic-api.md index dc969c67..6e08738f 100644 --- a/docs/Integration/programmatic-api.md +++ b/docs/Integration/programmatic-api.md @@ -16,6 +16,8 @@ public class FlowService { void delete(FlowDeleteRequest request); // 删除(仅未流转实例) void urge(FlowUrgeRequest request); // 催办 void resetSubProcess(FlowSubProcessResetRequest request); // 子流程数据重置(独立接口) + long reissue(FlowReissueRequest request); // 已完成流程二次发起 → 新记录 id + FlowForceSyncResult forceSync(FlowForceSyncRequest request); // 运行中实例强制同步最新设计 } ``` @@ -28,6 +30,8 @@ request.setOperatorId(1001L); request.setActionId(startSaveActionId); request.setFormData(Map.of("days", 3)); request.setOperatorSelectMap(Map.of(approvalNodeId, List.of(1002L))); +// 需要「同一人员的多个身份」时改用 operatorSelectOperators(优先于 operatorSelectMap) +// request.setOperatorSelectOperators(Map.of(approvalNodeId, List.of(OperatorKey.of(1002L, "department1")))); long recordId = flowService.create(request); ``` @@ -36,13 +40,14 @@ long recordId = flowService.create(request); ```java FlowActionRequest request = new FlowActionRequest(); request.setRecordId(recordId); -request.setOperatorId(1001L); request.setFormData(Map.of("days", 3)); FlowAdviceBody advice = new FlowAdviceBody(); advice.setActionId(passActionId); advice.setAdvice("同意"); advice.setSignKey("signature"); +advice.setOperatorId(1001L); // 操作人属于 advice,FlowActionRequest 没有该字段 +advice.setOperatorIdentity("department1"); // 可选:本次操作身份(默认身份传空串/null) request.setAdvice(advice); ActionResponse response = flowService.action(request); @@ -101,6 +106,12 @@ Page findAll(PageRequest request); // Page findTodoRecordPage(long userId, PageRequest request); // 待办 Page findNotifyRecordPage(long userId, PageRequest request); // 抄送 Page findDoneRecordPage(long userId, PageRequest request); // 已办 +Page findRunningInstancePage(String workCode, String title, PageRequest request); // 运行中实例(强制同步用) + +// 带身份的重载:均为 default,默认退化为「只按人员」;实现方需覆盖才能让 identityScope=LOCKED 生效 +default Page findTodoRecordPage(long userId, String identity, PageRequest request); +default Page findNotifyRecordPage(long userId, String identity, PageRequest request); +default Page findDoneRecordPage(long userId, String identity, PageRequest request); ``` 生产实现由 `flow-engine-starter-query` 提供(JPA);Mock 由 `FlowRecordQueryMockService` 提供。 diff --git a/docs/Integration/quick-start.md b/docs/Integration/quick-start.md index ff903670..7d060e02 100644 --- a/docs/Integration/quick-start.md +++ b/docs/Integration/quick-start.md @@ -12,28 +12,28 @@ com.codingapi.flow flow-engine-starter - 0.1.0-SNAPSHOT + 0.3.0-SNAPSHOT com.codingapi.flow flow-engine-starter-infra - 0.1.0-SNAPSHOT + 0.3.0-SNAPSHOT com.codingapi.flow flow-engine-starter-api - 0.1.0-SNAPSHOT + 0.3.0-SNAPSHOT com.codingapi.flow flow-engine-starter-query - 0.1.0-SNAPSHOT + 0.3.0-SNAPSHOT ``` @@ -135,13 +135,15 @@ long recordId = flowService.create(request); // 返回首条流程记录 id ## 7. 审批流转 ```java +import com.codingapi.flow.pojo.body.FlowAdviceBody; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.response.ActionResponse; FlowActionRequest actionRequest = new FlowActionRequest(); actionRequest.setRecordId(recordId); -actionRequest.setOperatorId(1001L); -// advice: actionId + advice 文本 + 可选 forwardOperators/backNodeId 等 +actionRequest.setFormData(Map.of("days", 3)); +// 操作人经 advice 传入(FlowActionRequest 本身没有 operatorId 字段) +actionRequest.setAdvice(new FlowAdviceBody(passActionId, "同意", 1001L)); ActionResponse response = flowService.action(actionRequest); ``` diff --git a/docs/Integration/repository-integration.md b/docs/Integration/repository-integration.md index 42dec50f..3ac4f73d 100644 --- a/docs/Integration/repository-integration.md +++ b/docs/Integration/repository-integration.md @@ -42,10 +42,10 @@ public interface IRepositoryHolder { | 实现 | 场景 | 说明 | |---|---|---| -| `RepositoryHolderContext`(`context/` 包,单例) | 生产 | 由 starter 的 `RepositoryHolderContextRegister` 注册 7 个依赖;操作人读取委托 `GatewayContext`;记录保存委托 `FlowRecordService` | +| `RepositoryHolderContext`(`context/` 包,单例) | 生产 | 由 starter 的 `RepositoryHolderContextRegister` 注册 8 个依赖;操作人读取委托 `GatewayContext`;记录保存委托 `FlowRecordService` | | `MockRepositoryHolder`(`mock/` 包) | Mock 沙箱 | 构造时 new 出 9 个内存仓储 + `FlowRecordService`/`WorkflowService`,每个 Mock 实例独立一份(见 [Mock 模式](./mock-mode.md)) | -## 2. 仓储接口(12 个) +## 2. 仓储接口(13 个) 文件:`flow-engine-framework/src/main/java/com/codingapi/flow/repository/` @@ -152,6 +152,14 @@ public interface UrgeIntervalRepository { UrgeInterval getLatest(String processId, long recordId); void save(UrgeInterval urgeInterval); } + +/** 二次发起来源记录(issue #272) */ +public interface FlowReissueRepository { + void save(FlowReissueRecord record); + List findBySourceRecordId(long sourceRecordId); + List findBySourceProcessId(String sourceProcessId); + List findByNewProcessId(String newProcessId); +} ``` ## 3. JPA 实现(`flow-engine-starter-infra`) @@ -161,7 +169,7 @@ public interface UrgeIntervalRepository { - `AutoConfiguration`:`@ConditionalOnClass(name = "org.springframework.data.jpa.repository.JpaRepository")` + `@Import(FlowJpaPackageRegistrar.class)`。 - `FlowJpaPackageRegistrar`(`ImportBeanDefinitionRegistrar`)调用 `AutoConfigurationPackages.register(registry, "com.codingapi.flow.infra")`,让宿主应用的 JPA 扫描覆盖引擎实体与仓储包 —— **业务方无需配置 `@EntityScan`**。 -### 3.2 仓储实现(11 个 Bean) +### 3.2 仓储实现(12 个 Bean) | Bean | 实现类 | |---|---| @@ -176,6 +184,7 @@ public interface UrgeIntervalRepository { | `flowTodoMargeRepository`(bean 名 marge) | `FlowTodoMergeRepositoryImpl` | | `flowOperatorAssignmentRepository` | `FlowOperatorAssignmentRepositoryImpl` | | `subProcessRepository` | `SubProcessRepositoryImpl` | +| `flowReissueRepository` | `FlowReissueRepositoryImpl` | > ⚠️ **infra 不提供** `NodeViewJavaScriptRepository` 与 `FlowOperatorGateway` 的实现,必须由业务方提供。 @@ -234,7 +243,7 @@ public class GroovyScriptRepositoryImpl implements GroovyScriptRepository, Initi ## 6. 替换存储 - **引入 `flow-engine-starter-infra`**:开箱即用(推荐)。 -- **不引入 infra**:自行实现 12 个仓储接口 + `NodeViewJavaScriptRepository` 为 Spring Bean 即可。starter 的 `RepositoryHolderContextRegister` 会自动注入。framework 测试包(`src/test/java/com/codingapi/flow/repository/`)提供了一套内存实现可作参考。 +- **不引入 infra**:自行实现 12 个有 JPA 实现的仓储接口 + `NodeViewJavaScriptRepository`(共 13 个)为 Spring Bean 即可。starter 的 `RepositoryHolderContextRegister` 会自动注入。framework 测试包(`src/test/java/com/codingapi/flow/repository/`)提供了一套内存实现可作参考。 ## 7. 离线/最小装配(脱离 Spring) diff --git a/docs/Integration/rest-api.md b/docs/Integration/rest-api.md index f2c5bb86..16803334 100644 --- a/docs/Integration/rest-api.md +++ b/docs/Integration/rest-api.md @@ -17,10 +17,12 @@ operatorId 请求参数 → 存在 → 使用该 id 作为当前操作人 - `mockKey` 经 `MockInstanceFactory.getInstance().getMockInstance(key)` 解析(见 [Mock 模式](./mock-mode.md))。 - `operatorId` 覆盖便于无登录态集成与测试(如 curl 直接带 `?operatorId=1`)。 -`operatorIdentity` 与 `operatorId` 对称(详见 [多身份参与](./operator-identity.md)): +`operatorIdentity` 与 `operatorId` 对称(详见 [多身份参与](./operator-identity.md)),解析顺序为 +**请求头 `X-Operator-Identity` → 请求参数 `operatorIdentity` → 登录操作者自身身份**: ``` -operatorIdentity → 存在 → 校验后作为当前身份(空串 = 默认身份) +X-Operator-Identity 请求头 或 operatorIdentity 请求参数 + → 存在 → 先校验后作为当前身份(空串 = 显式默认身份) → 不存在且 operatorId 存在 → 归默认身份(避免人员与身份错配) → 都不存在 → 取登录操作者自身身份 ``` @@ -40,6 +42,8 @@ operatorIdentity → 存在 → 校验后作为当前身份(空串 = 默认身 | POST | `/api/cmd/record/create` | `FlowCreateRequest` | `SingleResponse` | 发起流程,返回首条记录 id | | POST | `/api/cmd/record/action` | `FlowActionRequest` | `SingleResponse` | 执行动作(通过/拒绝/加签/减签/委派/退回/转办/自定义/保存) | | POST | `/api/cmd/record/subProcess/reset` | `FlowSubProcessResetRequest` | `Response` | 子流程数据重置(独立接口,需子流程节点开启重置能力) | +| POST | `/api/cmd/record/reissue` | `FlowReissueRequest` | `SingleResponse` | 已完成流程二次发起(仅流程管理员),返回新流程记录 id | +| POST | `/api/cmd/record/forceSync` | `FlowForceSyncRequest` | `SingleResponse` | 运行中实例强制同步最新流程设计(按选中实例换绑运行时快照) | | POST | `/api/cmd/record/urge` | `IdRequest` | `Response` | 催办 | | POST | `/api/cmd/record/revoke` | `IdRequest` | `Response` | 撤销 | | POST | `/api/cmd/record/delete` | `IdRequest` | `Response` | 删除(仅未流转实例,开始节点) | @@ -89,6 +93,7 @@ operatorIdentity → 存在 → 校验后作为当前身份(空串 = 默认身 | GET | `/api/query/record/todo` | `SearchRequest` + 身份参数(见下) | `MultiResponse` | 我的待办(默认跨身份) | | GET | `/api/query/record/notify` | 同上 | `MultiResponse` | 我的抄送(默认跨身份) | | GET | `/api/query/record/done` | 同上 | `MultiResponse` | 我的已办(默认跨身份) | +| GET | `/api/query/record/running` | `FlowInstanceQueryRequest`:`workCode`(必填)/ `title` / `current` / `pageSize` | `MultiResponse` | 指定流程编码下运行中的实例(强制同步选择范围,issue #281) | 查询身份范围(`todo` / `done` / `notify` 通用,issue #297): @@ -157,11 +162,15 @@ public interface FlowRecordQueryService { "actionId": "开始节点 SAVE 动作 id", "formData": { "days": 3, "reason": "年假" }, "operatorId": 1001, - "operatorSelectMap": { "approvalNodeId": [1002, 1003] } + "operatorIdentity": "department1", + "operatorSelectMap": { "approvalNodeId": [1002, 1003] }, + "operatorSelectOperators": { "approvalNodeId": [{ "operatorId": 1002, "identity": "department1" }] } } ``` -- `operatorSelectMap`:发起人设定操作人(`OperatorLoadStrategy.INITIATOR_SELECT` 节点),key 为节点 id,value 为操作人 id 列表。 +- `operatorIdentity`:本次发起身份,落库到 `create_operator_identity`(REST 层实际以请求头 `X-Operator-Identity` 优先)。 +- `operatorSelectMap`:发起人设定操作人(`OperatorLoadStrategy.INITIATOR_SELECT` 节点),key 为节点 id,value 为操作人 id 列表(默认身份)。 +- `operatorSelectOperators`:携带身份的同一能力,元素为 `(operatorId, identity)`;**优先于** `operatorSelectMap`,同一人员的两个身份不会被合并。 ### `FlowActionRequest` @@ -173,14 +182,18 @@ public interface FlowRecordQueryService { "actionId": "PASS 动作 id", "advice": "同意", "signKey": "签名", + "operatorId": 1001, + "operatorIdentity": "department1", "forwardOperatorIds": [1002], "backNodeId": "退回目标节点 id", - "operatorSelectMap": {} + "operatorSelectMap": {}, + "operatorSelectOperators": {} } } ``` - `actionId` 决定执行动作(PASS/REJECT/ADD_AUDIT/REDUCE_AUDIT/DELEGATE/RETURN/TRANSFER/CUSTOM/SAVE)。 +- 操作人与身份在 `advice` 内(`operatorId` / `operatorIdentity`),`FlowActionRequest` 顶层没有这两个字段;为兼容旧调用方,REST 层会用 `operatorId` 请求参数与当前身份覆盖 `advice` 中的值。 - `forwardOperatorIds`:加签/减签/委派/转办的目标操作人。 - `backNodeId`:退回动作的目标节点(仅 Start/Approval/Handle 可退回)。 - 减签每次只能处理一条记录,目标必须是该流程实例当前节点的其他待审批人。 @@ -229,25 +242,31 @@ public interface FlowRecordQueryService { | 动作 | `actions`(当前可见) / `actionList`(全部) | | 人员 | `createOperator` / `currentOperator` / `currentNodeOperators` | | 待办与状态 | `todos` / `mergeable` / `flowState` / `recordState` | -| 其他 | `histories` / `nodes` / `revoke` / `urge` / `resetSubProcess` | +| 其他 | `histories` / `nodes` / `backNodes` / `revoke` / `urge` / `resetSubProcess` / `reissue` | | 字段/标记 | 说明 | |---|---| | `currentNodeOperators` | 当前节点实例仍待审批的人员(去重、排除当前操作人、含未激活隐藏记录);减签候选人来源,按单条记录计算,不可跨流程合并 | | `actions[].batchable` | 是否支持合并批量提交(当前仅 `REDUCE_AUDIT` 为 `false`);仅响应附加、不落库;旧服务端缺省按 `true` | | `resetSubProcess` | 当前待办位于开启重置能力且已汇聚完成的子流程锁定节点时为 `true` | +| `reissue` | 已完成流程且当前操作人为流程管理员时为 `true`(可二次发起) | | 合并审批展示 | `mergeable && todos.length > 1` 时隐藏 `batchable=false` 的动作;进入单条流程后按该记录的 `actions` / `currentNodeOperators` 展示并提交 | ### `FlowRecordContent`(列表响应,字段摘要) ``` processId / workflowRuntimeId / workTitle / workCode / nodeId / nodeType / nodeName -title / readTime / currentOperatorId / currentOperatorName -submitOperatorId / submitOperatorName / createTime -createOperatorId / createOperatorName / todoKey / margeCount / mergeable +title / readTime / currentOperatorId / currentOperatorName / currentOperatorIdentity +submitOperatorId / submitOperatorName / submitOperatorIdentity +createOperatorId / createOperatorName / createOperatorIdentity +handleOperatorId / handleOperatorName / handleOperatorIdentity +createTime / todoKey / margeCount / mergeable recordId / timeoutTime / recordState / flowState / notify ``` +> `currentOperator*` 是待办**归属人**(办结后不变);`handleOperator*` 是**实际办理人**(办结动作写入,issue #306)。 +> 已办列表展示「谁以什么身份办理」应优先取 `handleOperator*`,历史数据为空时回退 `currentOperator*`。 + ## 9. 响应包装 | 类 | 结构 | diff --git a/docs/Integration/script-integration.md b/docs/Integration/script-integration.md index ac8f35e6..e4459967 100644 --- a/docs/Integration/script-integration.md +++ b/docs/Integration/script-integration.md @@ -33,7 +33,7 @@ | `TriggerScript` | 触发节点执行副作用(忽略返回值) | `TriggerStrategy` | | `SubProcessScript` | 生成子流程发起请求(返回 `FlowCreateRequest` 或集合) | `SubProcessStrategy` | | `SubProcessResultScript` | 判定子流程是否全部结束 | `SubProcessStrategy` | -| `OperatorLoadScript` | 加载节点操作人(返回用户 id 列表) | `OperatorLoadStrategy` | +| `OperatorLoadScript` | 加载节点操作人(返回 `List` / `List` / `List`,可混用,见下) | `OperatorLoadStrategy` | | `OperatorMatchScript` | 校验发起人是否允许发起流程 | `Workflow.matchCreatedOperator` | | `ErrorTriggerScript` | 匹配不到操作人时的兜底(跳节点 / 兜底操作人) | `ErrorTriggerStrategy` | | `ActionDisplayScript` | 控制动作是否展示 | `ActionDisplay.show` | @@ -73,6 +73,15 @@ request.getCreatedOperator() / getCreatedOperatorId() / getCreatedOperatorName() request.getSubmitOperator() / getSubmitOperatorId() / getSubmitOperatorName() // 流程提交人 request.getCurrentOperator() / getCurrentOperatorId() / getCurrentOperatorName() // 当前审批人 request.findPreviousNodeOperatorIds() // List 上一节点实际审批人 id(排除自动办结) +request.findPreviousNodeOperators() // List 上一节点实际审批人(含身份) + +// 身份(issue #288 / #303) +request.getCreatedOperatorIdentity() // 创建者身份(空串 = 默认身份) +request.getCurrentOperatorIdentity() // 当前操作者身份 +request.getSubmitOperatorIdentity() // 提交人身份 +request.getCreatedOperatorKey() // OperatorKey(人员 + 身份) +request.getCurrentOperatorKey() +request.getSubmitOperatorKey() ``` **节点与流程控制** @@ -113,13 +122,35 @@ $bind.getBean(MyService.class) // 获取 Spring Bean 实例 $bind.getBean("beanName", MyService.class) $bind.getBeans(MyService.class) // 获取全部实现 $bind.getRecordById(recordId) // 按 id 获取流程记录 FlowRecord -$bind.getOperatorById(userId) // 获取操作人 +$bind.getOperatorById(userId) // 获取操作人(默认身份) +$bind.getOperatorByIdentity(userId, identity) // 按身份回查操作人(issue #288) +$bind.getOperatorKey(userId, identity) // 只构造 OperatorKey,不回查(issue #303) $bind.findOperatorsByIds([1L, 2L, 3L]) // 批量获取操作人 ``` `$bind` 的后端是 `FlowScriptContext` 单例,其 `IBeanFactory` 由 starter 的 `FlowScriptContextRegister` 注入(转发到 Spring 容器)。 -### 2.3 `GroovyWorkflowRequest`(发起匹配请求) +### 2.3 取人脚本(`OperatorLoadScript`)的返回形态 + +取人脚本允许三种返回形态,并可在同一列表中混用(逐元素判定,由 `OperatorScriptResultResolver` 统一解析): + +| 形态 | 示例 | 身份来源 | 是否回查 | +|------|------|----------|----------| +| `List` | `return [1, 2]` | 默认身份 | 是(按默认身份批量) | +| `List` | `return [request.getCreatedOperatorKey()]` | `OperatorKey.identity()` | 是(按身份分组批量) | +| `List` | `return [$bind.getOperatorByIdentity(2, 'department1')]` | 对象自带 `getIdentity()` | 否,直接采用 | + +约定: + +- 顶层可写单值(`return request.getCreatedOperatorId()`),按单元素处理; +- 非正数人员 id(存量脚本用 `[-1]` 表示「无审批人」)会被跳过,不抛异常; +- 其他非法元素抛 `FlowValidationException`,消息带脚本类型、元素类型与元素内容; +- 默认模板为 `return [request.getCreatedOperatorKey()]`(创建者以发起身份参与); + 存量流程定义里的旧脚本 `return [request.getCreatedOperatorId()]` 行为不变,仍落默认身份。 + +详见 [多身份参与](./operator-identity.md) 3.4。 + +### 2.4 `GroovyWorkflowRequest`(发起匹配请求) 文件:`flow-engine-framework/.../script/request/GroovyWorkflowRequest.java` @@ -140,9 +171,9 @@ request.getWorkflow() // Workflow 对象(可访问 form/nodes 等) | `SCRIPT_DEFAULT_ACTION_DISPLAY` | 默认显示 | — | `def run(request){ return true; }` | | `SCRIPT_DEFAULT_ACTION_REJECT` | 返回开始节点 | `{"type":"START"}` | `def run(request){ return request.getStartNode().getId(); }` | | `SCRIPT_DEFAULT_CONDITION` | 默认条件(允许执行) | — | `def run(request){ return true; }` | -| `SCRIPT_DEFAULT_ERROR_TRIGGER` | 回退至开始节点 | `{"type":"node","node":"START"}` | `def run(request){ return request.getStartNode().getId(); }` | +| `SCRIPT_DEFAULT_ERROR_TRIGGER` | 异常提示 | `{"type":"prompt"}` | `def run(request){ return [type:'prompt', message:'流程未匹配到审批人,无法继续处理,请联系流程管理员'] }` | | `SCRIPT_DEFAULT_NODE_TITLE` | 你有一条待办 | — | `def run(request){ return '你有一条待办' }` | -| `SCRIPT_DEFAULT_OPERATOR_LOAD` | 流程创建者 | `{"type":"creator"}` | `def run(request){ return [request.getCreatedOperatorId()] }` | +| `SCRIPT_DEFAULT_OPERATOR_LOAD` | 流程创建者 | `{"type":"creator"}` | `def run(request){ return [request.getCreatedOperatorKey()] }` | | `SCRIPT_DEFAULT_OPERATOR_MATCH` | 任意用户 | `{"type":"any"}` | `def run(request){ return true }` | | `SCRIPT_DEFAULT_ROUTER` | 发起节点 | `{"node":"START"}` | `def run(request){ return request.getStartNode().getId(); }` | | `SCRIPT_DEFAULT_SUB_PROCESS` | 创建当前流程 | — | `def run(request){ return request.toCreateRequest() }` | diff --git a/docs/Integration/user-integration.md b/docs/Integration/user-integration.md index 3e1f489a..46987443 100644 --- a/docs/Integration/user-integration.md +++ b/docs/Integration/user-integration.md @@ -51,12 +51,18 @@ public interface IFlowOperator extends IUser { String getName(); // 用户名称 boolean isFlowManager(); // 流程管理员可强制干预流程 IFlowOperator forwardOperator(GroovyScriptRequest request); // 转交审批人;无需转交返回 null + + /** 身份标识,空串表示默认身份(default 方法,存量实现无需改动) */ + default String getIdentity() { + return OperatorIdentity.DEFAULT.value(); + } } ``` 要点: - 父接口 `IUser`(来自外部依赖 `com.codingapi.springboot:springboot-starter`)为**空标记接口**,无需实现任何方法。 +- `getIdentity()` 是 `default` 方法,返回 `null` 或空串都表示默认身份;多身份场景需覆盖它(见 [多身份参与](./operator-identity.md))。 - `isFlowManager()` 返回 `true` 表示流程管理员:开启干预策略时,管理员可强制审批他人待办(见 [扩展点](./extension-points.md#工作流策略))。 - `forwardOperator(request)` 实现「转交审批」(转办链):返回转交目标操作人,无需转交时返回 `null`。引擎在审批时调用 `session.loadFinalForwardOperator(...)` 递归解析转交链。 @@ -79,7 +85,8 @@ public class GatewayContext { ``` - **注入方式**:`GatewayContext.getInstance().setFlowOperatorGateway(bean)`,由 starter 的 `GatewayContextRegister`(`InitializingBean`)在启动时执行。 -- **线程缓存** `FlowOperatorLocalThreadCache`(`flow-engine-framework/.../cache/FlowOperatorLocalThreadCache.java`):`ThreadLocal>`,未命中时调用网关并回写;`find` 会过滤 null/<=0 的 id、去重、保序返回(保证多人审批顺序稳定)。`FlowService` 每个操作入口都会 `clear()` 该缓存。 +- **线程缓存** `FlowOperatorLocalThreadCache`(`flow-engine-framework/.../cache/FlowOperatorLocalThreadCache.java`):`ThreadLocal>`,未命中时调用网关并回写;`find` 会过滤 null/<=0 的 id、去重、保序返回(保证多人审批顺序稳定)。缓存键由 `OperatorKey#key()` 生成,**含身份**。`FlowService` 每个操作入口都会 `clear()` 该缓存。 +- **带身份的读取**:`GatewayContext.getFlowOperator(userId, identity)` / `findByIds(ids, identity)` 是新增重载;批量结果身份不符时会逐条回退单条按身份回查(见 [多身份参与](./operator-identity.md) 3.2)。 ## 3. 集成示例(完整可运行) diff --git a/docs/capabilities/flow-engine-framework/flow-service.md b/docs/capabilities/flow-engine-framework/flow-service.md index 487843ae..7aad24a5 100644 --- a/docs/capabilities/flow-engine-framework/flow-service.md +++ b/docs/capabilities/flow-engine-framework/flow-service.md @@ -21,6 +21,8 @@ symbols: - FlowDeleteService - FlowSubProcessResetService - FlowSubProcessResultService + - FlowReissueService + - FlowForceSyncService - SubProcessSessionFactory - OperatorAssignmentService - WorkflowGroovyScriptUtils @@ -31,7 +33,7 @@ content_hash: 48847288af1a4551b8327e398d01a8ec4de643dce1c049b90dcdc8ad0134df3b 提供流程引擎的业务服务层,将复杂的流程操作封装为高内聚的服务接口,解决以下问题: -- **流程操作入口**:`FlowService` 作为流程审批操作的统一入口,支持创建、审批、撤销、删除、催办、子流程重置 +- **流程操作入口**:`FlowService` 作为流程审批操作的统一入口,支持创建、审批、撤销、删除、催办、子流程重置、二次发起、强制同步 - **流程设计管理**:`WorkflowService` 管理流程定义的 CRUD 和版本操作 - **职责分离**:每种操作由独立的 Service 实现(如 `FlowActionService`、`FlowCreateService`),保持单一职责 - **线程安全**:每次操作前通过 `FlowOperatorLocalThreadCache.clear()` 与 `FlowRuntimeScriptLocalCache.clear()` 清理线程缓存 @@ -50,6 +52,8 @@ content_hash: 48847288af1a4551b8327e398d01a8ec4de643dce1c049b90dcdc8ad0134df3b | `detail(FlowDetailRequest)` | 查询流程详情 | | `processNodes(FlowProcessNodeRequest)` | 查询流程节点记录 | | `resetSubProcess(FlowSubProcessResetRequest)` | 子流程数据重置(独立接口,REST 端点 `POST /api/cmd/record/subProcess/reset`) | +| `reissue(FlowReissueRequest)` | 已完成流程二次发起(仅流程管理员,REST 端点 `POST /api/cmd/record/reissue`),返回新流程记录 id | +| `forceSync(FlowForceSyncRequest)` | 运行中实例强制同步最新流程设计(REST 端点 `POST /api/cmd/record/forceSync`),返回每个实例的同步结果 | ### WorkflowService — 流程设计管理 @@ -74,8 +78,10 @@ content_hash: 48847288af1a4551b8327e398d01a8ec4de643dce1c049b90dcdc8ad0134df3b | `FlowRecordSaveService` | 保存流程记录和待办合并关系,并按实际落库记录推送 `FlowRecordSaveEvent`(issue #280) | | `FlowSubProcessResetService` | 子流程数据重置(旧聚合组作废、实例继承/重建) | | `FlowSubProcessResultService` | 子流程完成后回写父流程并生成待办/已办 | +| `FlowReissueService` | 已完成流程二次发起:复制源流程表单与人员设定,新流程停在开始节点 | +| `FlowForceSyncService` | 运行中实例强制同步最新流程设计:校验结构一致性后换绑运行时快照 | | `SubProcessSessionFactory` | 子流程会话构建(按聚合组/实例定位记录) | -| `OperatorAssignmentService` | 操作者分配服务 | +| `OperatorAssignmentService` | 操作者分配服务(实例对象,构造注入 `FlowSession`,提供 `hasAssignment` / `assign`) | ## 使用实例 diff --git a/docs/capabilities/flow-engine-framework/operator-assignment.md b/docs/capabilities/flow-engine-framework/operator-assignment.md index 8e1d7156..50333a1f 100644 --- a/docs/capabilities/flow-engine-framework/operator-assignment.md +++ b/docs/capabilities/flow-engine-framework/operator-assignment.md @@ -1,13 +1,14 @@ --- name: flow-engine-framework/operator-assignment module: flow-engine-framework -description: 操作人分配能力,支持发起人/审批人设定的分配校验与落库 +description: 操作人分配能力,支持发起人/审批人设定的分配校验与落库(含身份) status: 已实现 scope: 后端 source: 项目自有 import: "com.codingapi.flow:flow-engine-framework" symbols: - OperatorAssignmentService + - OperatorSelections - FlowOperatorAssignmentRepository content_hash: f502894911c6aa57e630d8ae047de982d1b7833e635de334e5abafb33b73a48e --- @@ -16,9 +17,11 @@ content_hash: f502894911c6aa57e630d8ae047de982d1b7833e635de334e5abafb33b73a48e 提供操作人分配(发起人设定 / 审批人设定)的校验与持久化能力: -- **范围校验**:目标节点配置了可选人员范围时,校验所选人员是否全部落在范围内,越界抛出 `FlowValidationException.operatorOutOfRange` -- **分配落库**:校验通过后按流程实例与节点保存选定的操作人 ID 列表 +- **已设定判定**:`hasAssignment(nodeId)` 汇总三种来源(本次意见的 `operatorSelectMap`、本次意见的 `operatorSelectOperators`、此前已落库的分配),避免流程在开始节点反复要求选人 +- **范围与人数校验**:所选人数超过 `maxOperatorCount` 抛 `FlowValidationException.operatorCountExceeded`;目标节点配置了可选人员范围时,越界抛 `operatorOutOfRange`(范围按人员 id 判定,不区分身份) +- **分配落库**:按流程实例与节点保存选定的参与人(人员 id + 身份) - **幂等保存**:同一节点重复设定时覆盖旧分配 +- **两种表达形式的优先级**:`OperatorSelections` 收口「携带身份的分配优先于仅人员 id 的分配」,调用方不再各自写 `if (keys != null) ...` ## 如何使用 @@ -26,20 +29,34 @@ content_hash: f502894911c6aa57e630d8ae047de982d1b7833e635de334e5abafb33b73a48e | 组件 | 职责 | |------|------| -| `OperatorAssignmentService` | 静态服务,提供 `validateAndSave(baseSession, processId, operatorSelectMap)` 校验并保存操作人分配 | -| `FlowOperatorAssignmentRepository` | 操作人分配仓储接口,定义 `save(processId, nodeId, operatorIds)` 与 `findOperatorIds(processId, nodeId)` | -| `FlowValidationException.operatorOutOfRange` | 所选人员越界时抛出的异常 | +| `OperatorAssignmentService` | 实例对象(构造注入 `FlowSession`),提供 `hasAssignment(nodeId)` 与 `assign(processId, selections)` | +| `OperatorSelections` | 操作人选择集合(节点 id → `List`),`of(byOperators, byOperatorIds)` 归并两种请求表达 | +| `FlowOperatorAssignmentRepository` | 分配仓储:`save` / `findOperatorIds`(仅人员)+ `saveOperators` / `findOperators`(含身份,default 退化) | +| `IRepositoryHolder` | 对外业务方法:`saveOperatorAssignments(processId, nodeId, List)` / `findAssignedOperators(processId, nodeId)` | ### 校验规则 -- `operatorSelectMap` 为空时直接返回,不做处理 -- 通过 `node.strategyManager().loadOperatorRange(session)` 加载节点可选人员范围;范围为空(未配置脚本或脚本执行结果为空)表示不限范围,跳过校验 -- 范围非空时,所选人员必须全部落在范围内,否则抛出异常 +- 选择集合为空时直接返回,不做处理 +- 同一人员的两个身份是两项参与人,不去重合并;完全相同的 `(人员id, 身份)` 才去重 +- 人数上限:`maxOperatorCount >= 0` 时校验,`-1` 表示不限制 +- 范围校验:`node.strategyManager().loadOperatorRange(session)` 为空表示不限范围;非空时按 `operatorId` 判定是否在范围内 ## 使用实例 ```java -// 在 FlowCreateService / FlowActionService 中调用 -Map> operatorSelectMap = request.getOperatorSelectMap(); -OperatorAssignmentService.validateAndSave(baseSession, processId, operatorSelectMap); -``` \ No newline at end of file +// 发起路径(FlowCreateService):请求字段 → 选择集合 +OperatorSelections selections = OperatorSelections.of( + request.getOperatorSelectOperators(), // Map>,优先 + request.getOperatorSelectMap()); // Map>,按默认身份 +new OperatorAssignmentService(session).assign(processId, selections); + +// 办理路径(FlowActionService):选择集合来自本次审批意见 +new OperatorAssignmentService(session).assign(flowRecord.getProcessId(), + OperatorSelections.of(advice.getOperatorSelectOperators(), advice.getOperatorSelectMap())); + +// 判定节点是否已设定(PassAction / InitiatorSelectNodeService) +boolean assigned = new OperatorAssignmentService(flowSession).hasAssignment(node.getId()); +``` + +> 该类在 issue #311 P4 由「静态工具类 + `validateAndSave(baseSession, processId, operatorSelectMap)`」改为构造注入的对象: +> 会话是它唯一的依赖,`processId` 与选择集合随调用传入。旧写法已不存在。 diff --git a/docs/capabilities/flow-engine-framework/operator-identity.md b/docs/capabilities/flow-engine-framework/operator-identity.md new file mode 100644 index 00000000..8122fee7 --- /dev/null +++ b/docs/capabilities/flow-engine-framework/operator-identity.md @@ -0,0 +1,80 @@ +# 多身份参与模型(Operator Identity) + +> 模块:flow-engine-framework · 包:`com.codingapi.flow.operator` 及其调用方 +> 前置:[模型设计三层法](../../conventions/design/model-design.md) +> 本文只回答「身份这件事在代码里由谁负责」;接入步骤、请求头、落库列、模式配置见 [集成说明](../../Integration/operator-identity.md)。 + +## 解决什么问题 + +一个人员可能同时隶属多个部门或身兼多个岗位,在不同事项上以不同身份参与流程。 +引擎不建组织模型、不解释身份语义,只做四件事:**透传、存储、比较、留给脚本使用**。 + +身份取值是一个**不透明字符串**,`null` 与空串等价,均表示默认身份。 +默认身份下引擎行为与单身份版本完全一致。 + +## 模型构成 + +包 `com.codingapi.flow.operator` 内为身份的全部模型;`OperatorManager` 与 `TodoMergeKey` 因分别承担「人员集合」与「待办合并键」职责,放在各自所属的包。 + +| 类型 | 位置 | 职责 | 公有入口 | +|---|---|---|---| +| `OperatorIdentity` | `operator` | 身份值对象(不可变),负责归一化与合法性校验 | `of(String)` / `of(IFlowOperator)`、`value()`、`isDefault()`、`validate()`、`same(OperatorIdentity)` | +| `OperatorKey` | `operator` | 参与人标识值对象 `(人员id, 身份)`,参与人概念的**唯一载体** | `of(long, String)`、`ofDefault(long)`、`of(IFlowOperator)`、`matches(OperatorKey, OperatorIdentityMatchMode)`、`identityEquals(String)`、`key()`、`key(OperatorIdentityMatchMode)` | +| `OperatorIdentityMatchMode` | `operator` | 匹配模式策略,自己回答「是否同一人」与「身份是否区分参与人」 | `match(OperatorKey, OperatorKey)`、`identityDistinguishes()`、`parse(String)` | +| `OperatorIdentityContext` | `operator` | 全局模式持有者(可变单例),把配置注入框架 | `getInstance()`、`use(mode)`、`matchMode()`、`matches(OperatorKey, OperatorKey)`、`sameOperator(IFlowOperator, IFlowOperator)` | +| `OperatorSelections` | `operator` | 操作人选择集合,收口「节点 → 参与人列表」并统一「带身份优先于仅 id」 | `of(...)`、`empty()`、`isEmpty()`、`hasSelection(String)`、`nodeIds()`、`of(String)` | +| `IFlowOperator` | `operator` | 流程参与用户,身份来源为 `getIdentity()`(default 方法,返回默认身份) | `getUserId()`、`getName()`、`isFlowManager()`、`forwardOperator(...)`、`getIdentity()` | +| `OperatorManager` | `manager` | 参与人集合,回答「这个人在不在这批人里」 | `new OperatorManager(List)`、`match(IFlowOperator)`、`isEmpty()` | +| `TodoMergeKey` | `record` | 待办合并复合键(参与人 + 运行时 + 节点),键格式的唯一定义点 | `of(...)`、`value()` | +| `OperatorIdentityHeader` | `flow-engine-starter-api` 的 `api` 包 | 请求头契约与「头优先于 query」解析,属接入层 | `resolve(...)` 与三个头名常量 | +| `OperatorIdentityWarnLog` | `diagnostic` | 身份未透传时的告警去重输出 | `getInstance()`、`warnOnce(...)` | + +## 两个唯一真源 + +身份体系只有两个必须集中的判断点,其余能力都建立在它们之上: + +| 判断 | 唯一入口 | 禁止的替代写法 | +|---|---|---| +| 两个参与人是否为同一人 | `OperatorKey#matches(other, mode)` | `a.getUserId() == b.getUserId() && a.getIdentity().equals(b.getIdentity())` | +| 参与人键(缓存键 / Map 键 / 去重键) | `OperatorKey#key(mode)` | 自行 `id + 分隔符 + identity` | + +待办合并键是**复合键**(参与人 + 运行时 + 节点),由 `TodoMergeKey#value()` 独立回答,不复用 `OperatorKey#key()`,但同样只允许一个定义点。 + +## 匹配模式 + +| 模式 | 判定 | 身份是否区分参与人 | 默认场景 | +|---|---|---|---| +| `STRICT` | 人员 + 身份都一致 | 是(键带身份后缀) | 只依赖 framework 时的默认值 | +| `USER_ONLY` | 只比人员 | 否(键不带后缀) | 通过 starter 接入时的默认值 | + +模式是**策略**,不是分支条件:新增一种模式只需实现枚举常量,不得在使用方写 `if (mode == ...)`。 + +模式只能改变**判定**,不能改变**数据格式**。键格式(是否追加身份后缀)只允许在键模型内部依据 `identityDistinguishes()` 决定,业务类不得在方法体里读 `matchMode()` 后自己拼字符串。 + +## 设计约束 + +改动本模型或其调用方时必须满足以下四条: + +1. **成对传递**:新增或修改的公开方法签名不得出现 `(long operatorId, String identity)`,一律传 `OperatorKey`。拆开传会让「一个人」在签名层面消失,调用方随时可能漏传身份。 +2. **判定收口**:任何「这个人是不是那条记录上的人」的判断必须经过 `OperatorKey#matches`,或接受 `IFlowOperator` 的 `OperatorIdentityContext#sameOperator` 重载。 +3. **键收口**:缓存键、Map 键、去重键只由 `OperatorKey#key(mode)` 产生;分隔符常量只允许一处声明;待办合并键只由 `TodoMergeKey#value()` 产生。 +4. **分层**:身份解析属接入层(HTTP 头约定),不得放进领域包;告警去重属可观测性,放在 `diagnostic` 包。领域包不得感知 HTTP。 + +身份比较恒为**严格口径**的地方:`OperatorManager`、操作者线程缓存、网关缓存的键。它们解决的是「取到哪一个带身份的操作者实例」,与「谁有权办理」是两个问题,不受匹配模式放宽。 + +## 相关测试 + +| 测试类 | 覆盖 | +|---|---| +| `OperatorKeyTest` | 归一化、相等、`matches`、`key()` 格式 | +| `OperatorIdentityContextTest` | 模式切换与判定 | +| `OperatorSelectionsTest` | 「带身份优先于仅 id」的收口 | +| `TodoMergeKeyTest` | 合并键在两种模式下的格式 | +| `OperatorManagerTest` | 参与人集合匹配 | +| `OperatorIdentityWarnLogTest` | 告警去重归属实例 | + +## 关联 + +- 接入与行为口径:[集成说明](../../Integration/operator-identity.md) +- 事务与脚本身份函数:[脚本集成](../../Integration/script-integration.md) +- 改写本模型的前置规范:[模型设计三层法](../../conventions/design/model-design.md) diff --git a/docs/capabilities/flow-engine-framework/repository.md b/docs/capabilities/flow-engine-framework/repository.md index 8677a110..5de5b04a 100644 --- a/docs/capabilities/flow-engine-framework/repository.md +++ b/docs/capabilities/flow-engine-framework/repository.md @@ -18,6 +18,7 @@ symbols: - DelayTaskRepository - UrgeIntervalRepository - NodeViewJavaScriptRepository + - FlowReissueRepository - IRepositoryHolder content_hash: 057987ed8ab209759993dfc2792699ccdcd110a1c291ffd49fea7af09e1af895 --- @@ -48,6 +49,7 @@ content_hash: 057987ed8ab209759993dfc2792699ccdcd110a1c291ffd49fea7af09e1af895 | `UrgeIntervalRepository` | 催办间隔配置的 CRUD | | `NodeViewJavaScriptRepository` | 节点视图 JS 脚本的 CRUD | | `SubProcessRepository` | 子流程执行记录的 CRUD(子流程聚合持久化依赖) | +| `FlowReissueRepository` | 二次发起来源记录与关系查询(issue #272) | ### IRepositoryHolder diff --git a/docs/capabilities/flow-engine-starter/auto-configuration.md b/docs/capabilities/flow-engine-starter/auto-configuration.md index 547e5adf..5adb655b 100644 --- a/docs/capabilities/flow-engine-starter/auto-configuration.md +++ b/docs/capabilities/flow-engine-starter/auto-configuration.md @@ -35,7 +35,7 @@ content_hash: cead1cab34f0a1357e650ae764b4f008247c530ad9b4eff0cd0ffeb9c93d44e3 | 模块 | AutoConfiguration 职责 | |------|----------------------| -| `flow-engine-starter` | 注册 8 个 Bean:`NodeViewJavaScriptCacheContextRegister`、`FlowDelayTaskRunner`、`GatewayContextRegister`、`FlowScriptContextRegister`、`RepositoryHolderContextRegister`、`FlowRecordService`、`WorkflowService`、`FlowService` | +| `flow-engine-starter` | 注册 10 个 Bean:`OperatorIdentityConfigurer`、`NodeViewJavaScriptCacheContextRegister`、`FlowDelayTaskRunner`、`GatewayContextRegister`、`FlowScriptContextRegister`、`RepositoryHolderContextRegister`、`SpringFlowEventPublisher`、`FlowRecordService`、`WorkflowService`、`FlowService` | | `flow-engine-starter-api` | 注册 REST Controller(`WorkflowController` 等) | | `flow-engine-starter-infra` | 注册 JPA Repository 实现、数据库实体 | | `flow-engine-starter-query` | 注册查询服务(`FlowRecordQueryService` 等) | diff --git a/docs/capabilities/index.md b/docs/capabilities/index.md index e6b15be8..20fa5e71 100644 --- a/docs/capabilities/index.md +++ b/docs/capabilities/index.md @@ -17,6 +17,7 @@ | [flow-engine-framework/node](./flow-engine-framework/node.md) | flow-engine-framework | 流程节点体系,包含 19 种节点类型、节点接口层次和节点工厂 | 后端 | 项目自有 | | [flow-engine-framework/node-view-javascript](./flow-engine-framework/node-view-javascript.md) | flow-engine-framework | 节点视图脚本能力,支持视图脚本的缓存、保存与查询(含缓存自动清理) | 后端 | 项目自有 | | [flow-engine-framework/operator-assignment](./flow-engine-framework/operator-assignment.md) | flow-engine-framework | 操作人分配能力,支持发起人/审批人设定的分配校验与落库 | 后端 | 项目自有 | +| [flow-engine-framework/operator-identity](./flow-engine-framework/operator-identity.md) | flow-engine-framework | 多身份参与模型,身份值对象、参与人标识、匹配模式策略与两个唯一真源(相等判定、键生成) | 后端 | 项目自有 | | [flow-engine-framework/repository](./flow-engine-framework/repository.md) | flow-engine-framework | 仓储抽象层,定义流程引擎的持久化接口和仓储持有者上下文 | 后端 | 项目自有 | | [flow-engine-framework/script](./flow-engine-framework/script.md) | flow-engine-framework | Groovy 脚本运行时,包含脚本注册表、脚本类型封装和脚本执行上下文 | 后端 | 项目自有 | | [flow-engine-framework/sub-process](./flow-engine-framework/sub-process.md) | flow-engine-framework | 子流程聚合执行能力,支持批量创建、主流程等待、脚本结果判定、异常跳转与数据重置(退回重走) | 后端 | 项目自有 | @@ -31,4 +32,4 @@ --- -**统计**: 共 22 篇 — 已实现 22 / 计划中 0 / 已废弃 0 +**统计**: 共 23 篇 — 已实现 23 / 计划中 0 / 已废弃 0 diff --git a/docs/capabilities/springboot/ioc.md b/docs/capabilities/springboot/ioc.md index f3e68471..07a0bfad 100644 --- a/docs/capabilities/springboot/ioc.md +++ b/docs/capabilities/springboot/ioc.md @@ -16,7 +16,7 @@ framework_version: "3.5.9" - **依赖注入**:容器管理 Bean 之间的依赖关系。本项目不使用 `@Autowired` / `@Inject` 注解,统一通过 Lombok `@AllArgsConstructor` 构造器注入(如 `WorkflowController`、`WorkflowService`、各 `RepositoryImpl`) - **Bean 生命周期管理**:容器统一管理 Bean 的创建、初始化和销毁 - **AOP 支持**:框架提供 `@Aspect` 横切关注点能力(本项目未使用) -- **事件发布**:不使用 Spring `ApplicationEventPublisher`,事件系统为自研 `IFlowEvent` + `EventPusher`(`flow-engine-framework/event/` 下 9 种事件类,操作完成后通过 `EventPusher.push(event)` 推送) +- **事件发布**:不使用 Spring `ApplicationEventPublisher`,事件系统为自研 `IFlowEvent` + `FlowEventPublisher`(`flow-engine-framework/event/` 下 12 个事件类,操作完成后通过 `FlowEventPublisher.push(event)` 推送;引入 starter 时由 `SpringFlowEventPublisher` 在事务提交后按流程分区串行投递) - **自动配置**:通过 `@Configuration` + `@Conditional` 实现条件化 Bean 注册 ## 如何使用 diff --git a/docs/conventions/design/model-design.md b/docs/conventions/design/model-design.md index 24fea040..d023648e 100644 --- a/docs/conventions/design/model-design.md +++ b/docs/conventions/design/model-design.md @@ -260,7 +260,7 @@ Workflow(流程定义) 4. **静态方法只用于两类场景。** - 无状态纯计算:`Math.max`、`isNumeric(String)` - - 类型自身的语义:`OperatorKey.of(...)`、`OperatorIdentity.normalize(...)` + - 类型自身的语义:`OperatorKey.of(...)`、`OperatorIdentity.of(...)` 凡是要读外部状态、要回查、要抛业务异常的,都不属于这两类。 @@ -373,7 +373,7 @@ E 可验证 |---|---|---| | `XxxContext` / `XxxCache` / `XxxRegistry` 单例 | 全局唯一状态持有者,`getInstance()` 是唯一入口 | `RepositoryHolderContext`、`FlowRuntimeScriptLocalCache` | | `XxxFactory` / `XxxBuilder` | 静态方法只负责创建对象,不承载业务行为 | `NodeFactory`、`ActionBuilder` | -| 值对象自身的语义 | 行为与类型强内聚,无外部依赖 | `OperatorKey.of/ofDefault`、`OperatorIdentity.normalize` | +| 值对象自身的语义 | 行为与类型强内聚,无外部依赖 | `OperatorKey.of/ofDefault`、`OperatorIdentity.of` | | 枚举 / 常量类 | 无行为 | `OperatorIdentityMatchMode` | | 框架要求的空构造 | 序列化 / `IMapConvertor` 反射需要 | `ActionDisplay`、实体类 | | 单入口、无依赖的算法 | 只有 1 个公有方法,签名即语义 | `WorkflowStructureVerifier.compare` | diff --git a/docs/conventions/docs/documentation.md b/docs/conventions/docs/documentation.md new file mode 100644 index 00000000..e01cd40d --- /dev/null +++ b/docs/conventions/docs/documentation.md @@ -0,0 +1,135 @@ +# 文档编写与维护规范 + +> 模块:docs · 范围:仓库内全部 Markdown / HTML 文档 +> 前置:[模型设计三层法](../design/model-design.md)。本文是它在**文档尺度**上的应用:先分层,再定职责,再定验收。 + +## 为什么需要这条规范 + +文档腐化从来不是「写得少」,而是**写错了地方**和**写的时候没对账**。本仓库出现过两类典型问题: + +1. **过程文档混进规范目录** —— 「改造前的现状」「P1~P5 分批」「落地记录」被写成规范。它描述的是过去发生的事,不是「以后必须怎么做」,读的人无法据此判定对错,改完代码后它还会变成误导。 +2. **计数与签名凭记忆写** —— 「12 个仓储接口」「9 种事件」「`setOperatorId()`」在代码变更后全部失真,而这类错误在评审时看不出来,只有照着写代码的人才会踩坑。 + +因此本规范只解决两件事:**文档放在哪**,**写进去的事实怎么保证是真的**。 + +## 1. 四类文档,各只有一个归属 + +| 目录 | 回答的问题 | 时效 | 允许写 | 禁止写 | +|---|---|---|---|---| +| `docs/Integration/` | 别人怎么把引擎接进自己的系统 | 随公开 API 变 | 集成步骤、配置项、请求/响应示例、升级与迁移指引 | 内部实现细节、改造历史、未发布计划 | +| `docs/capabilities/` | 引擎**现在**有哪些能力、由谁提供 | 随代码变 | 当前类/方法/职责、设计约束、相关测试 | 计划、issue 时间线、已删除的旧实现 | +| `docs/conventions/` | 做改动**必须**遵守什么规则 | 长期稳定 | 可判定的规则、禁止清单、提交前自查 | 过程记录、改造批次、落地总结、API 迁移表 | +| `docs/manual/` | 使用者怎么操作 | 随发布变 | 操作步骤、界面说明 | 内部类名与包路径 | +| `README.md` / `AGENTS.md` / `CLAUDE.md` | 导航与约束摘要 | 随结构变 | 目录地图、命令、**指向性链接** | 长篇幅正文(应链接到上述四类) | + +判据一句话:**照着能做的 → Integration;能查到「有什么」的 → capabilities;能判定「这样做对不对」的 → conventions;其余不进 `docs/`。** + +同一事实只允许有一个归属。`README` 与 `AGENTS` 里出现的规则必须是摘要 + 链接,正文在 `conventions/` 内维护。 + +## 2. 过程文档不进 `conventions/` + +以下内容属于 issue / PR / release notes,**不属于规范**: + +- 改造前的现状盘点、问题清单; +- 分批计划(P1/P2/…)、批次验收记录; +- 「落地记录」「已完成项」; +- API 改名迁移对照表(这类内容属于 Integration 的升级说明)。 + +改造完成后只保留两份产物: + +1. **现在是什么** → `capabilities/`(模型、职责、唯一真源); +2. **以后必须怎么做** → `conventions/`(可判定的规则)。 + +需要保留历史对照时,写进对应 issue 的关闭评论。判断方法很简单:**一段文字里如果出现「改造前」「已删除」「已改名」「原 xxx」,它就不是规范。** + +## 3. 代码是唯一事实源 + +文档中出现的类名、方法签名、配置键、REST 路径、表名、字段名,必须能在代码里检索到。 + +提交前对本文档涉及的全部标识符做一次检索: + +```bash +# 类名/方法名是否存在 +grep -rn "OperatorKey#matches" --include=*.java . + +# REST 路径是否存在 +grep -rn "/api/cmd/record/reissue" --include=*.java . + +# 配置键是否存在 +grep -rn "codingapi.flow.identity.match-mode" --include=*.java --include=*.properties . +``` + +禁止: + +- 把接口/类的完整签名抄进文档当说明(腐化最快的一种写法); +- 凭记忆写字段名、参数名; +- 用「应该会」「大概」描述行为。 + +推荐写法:**入口 + 关键约束 + 代码路径**。例如写「`FlowService` 是唯一事务入口」并给出文件路径,而不是把 10 个方法签名贴一遍。 + +## 4. 计数必须可复算 + +「N 个仓储接口」「N 种事件」「N 个 Bean」「N 种节点」这类数字,每次新增能力都会失真。 + +优先级从高到低: + +1. **不写数量,直接列举** —— 列举本身就是事实,新增时自然会看到要补一行; +2. **必须写数量时,附复算命令** —— 例如 `13 个仓储接口(ls .../repository/*.java | wc -l)`; +3. **禁止模糊量词** —— 「约 N 个」「等等」「若干」在核对时无法判定真假。 + +## 5. 版本号只出现在两个位置 + +`pom.xml` 的 `` 是唯一来源。文档中只允许 [快速开始](../../Integration/quick-start.md) 与 `docs/manual/` 出现具体版本号,且必须与 `pom.xml` 一致: + +```bash +grep -n "" pom.xml +grep -rn "0\.[0-9]\.0-SNAPSHOT" docs/ +``` + +除这两处外,正文一律用「当前版本」表述。 + +## 6. 索引文件按格式维护,不重写 + +`docs/capabilities/index.md` 与 `docs/conventions/index.md` 是目录索引: + +- 新增文档必须同批补一行,表格列含义(名称 / 模块 / 描述 / 范围 / 来源)保持不变; +- 删除文档必须同批删除对应行,并更新末尾统计; +- 不调整排序规则、不改表头、不重新组织分组。 + +索引行的「描述」用一句话说清这篇文档回答什么问题,不复制标题。 + +## 7. 代码与文档同批提交 + +不允许「先提交代码,文档下次补」。按下表判断本次改动必须连带更新哪些文档: + +| 代码改动 | 必须同批更新 | +|---|---| +| 新增 / 删除 / 改路径的 REST 端点 | `Integration/rest-api.md` | +| 新增 / 重命名配置项 | `Integration/auto-configuration.md` | +| 新增 / 删除公开类或公开方法 | `capabilities/<模块>/` 对应文档 | +| 新增事件类型 | `Integration/event-integration.md` + `capabilities/` | +| 新增 / 删除仓储接口或表 | `Integration/repository-integration.md` | +| 修改一条既有规则 | `conventions/<域>/` | +| 调整模块划分 | `README.md` + `AGENTS.md` | +| 版本号变更 | `Integration/quick-start.md` + `docs/manual/` | + +提交信息里注明本次同时修正了哪些文档,便于回溯。 + +## 8. 写作形式 + +- **中文**,与技术术语混排时保留代码标识符原文; +- 表格优先于长段落:核对时逐行比对,比读段落可靠; +- 每篇开头三行内给出:模块、范围、前置文档(或「无前置」); +- 标题层级不超过三级,避免把结构写成大纲; +- 示例代码只保留能说明问题的最短片段,完整用法指向源码; +- 不写「我们将」「计划」「后续考虑」「暂时」—— 这些属于 issue。 + +## 9. 提交前自查 + +1. 文档里出现的类名、方法名、路径、配置键,**逐个 grep 过**了吗? +2. 所有数字都能**当场复算**吗? +3. 有没有「改造前 / 已删除 / 已改名 / 落地记录」的叙述?有 → 移到 issue。 +4. 这次改了代码,第 7 节表格里对应的文档**改了吗**? +5. 新增或删除文档,`index.md` 补行 / 删行了吗? + +五问全过,文档才算与代码对齐。 diff --git a/docs/conventions/domain/operator-identity.md b/docs/conventions/domain/operator-identity.md deleted file mode 100644 index c08e5959..00000000 --- a/docs/conventions/domain/operator-identity.md +++ /dev/null @@ -1,193 +0,0 @@ -# 多身份语义契约(Operator Identity) - -> 模块:domain · 范围:`com.codingapi.flow.operator` 及其全部调用方 -> 前置:[模型设计三层法](../design/model-design.md)。本文只回答一件事:**「身份」这个语义,谁说了算。** - -## 为什么单独立规矩 - -身份是参与人的第二维标识(#288)。它与普通字段的差别在四点: - -1. **贯穿所有读写路径**:待办、已办、匹配、撤回、催办、减签、子流程重置; -2. **有默认值**:`null` 与空串都表示「默认身份」,必须与存量行为完全等价; -3. **有全局开关**:匹配模式(`STRICT` / `USER_ONLY`)改变「谁算同一个人」; -4. **参与持久化键**:待办合并键、缓存键、去重键都由 `(人员id, 身份)` 派生。 - -第 3、4 点叠加后产生一个结构性风险:**改一个配置项,会改变已落库数据的主键语义**。`FlowRecord#getTodoKey()` 的注释里已经承认这一点——切换模式后存量待办合并组一分为二,需要 `FlowTodoMigrateService` 重建。风险根源不是配置本身,而是「键怎么拼」没有唯一归属。 - -#297 的实际故障(能审批却不能撤回)就是同一个语义出现两个答案的直接后果:审批路径按 `(id, 身份)` 判,撤回路径按 `id` 判。 - -## 改造前的现状(记录用:一个语义,多处置实现) - -### 参与人键(拼字符串)5 处,分隔符 4 份声明 - -| 位置 | 拼法 | 分隔符来源 | -|---|---|---| -| `OperatorKey#key()` | `operatorId + sep + identity` | 引用 `OperatorIdentity.KEY_SEPARATOR` = `#` | -| `FlowOperatorLocalThreadCache#cacheKey()` | `userId + sep + normalize(identity)` | 自己声明 `"\u0001"` | -| `OperatorIdentityGuard#check()` | `operatorId + sep + normalize(identity)` | 自己又声明一份 `"\u0001"` | -| `FlowContent#resolveCurrentNodeOperators()` | `id + "#" + normalize(identity)` | 引用 `KEY_SEPARATOR`,且 `USER_ONLY` 下改用裸 `id` | -| `FlowRecord#getTodoKey()` | `todoKey + "#" + identity` | 自己声明 `IDENTITY_KEY_SUFFIX` = `#` | - -**4 份常量声明、2 种字符、2 处需要先读匹配模式再决定格式。** - -### 「是否同一参与人」5 处入口 - -| 位置 | 判定方式 | -|---|---| -| `OperatorIdentity#same()` | 归一化后字符串相等(唯一实现) | -| `OperatorIdentityPolicy#matches()` | 先比 `id`,再按模式决定是否比身份 | -| `OperatorManager#getOperator()` | 内联 `id == id && same(...)` | -| `FlowOperatorLocalThreadCache#isIdentityMatched()` | 内联 `isDefault` 特判 + `same(...)` | -| `OperatorKey` record `equals` | 隐式依赖紧凑构造里的归一化 | - -### 关键判断 - -这两张表不是「代码重复」这么轻的问题,而是**同一业务规则存在多个定义点**: - -- 加一种匹配模式,要改 5 处中的 3 处(`Policy#matches`、`FlowRecord#getTodoKey`、`FlowContent`),漏一处就是半开状态; -- 改一次键格式,要同步 5 个类 + 1 个迁移服务; -- 想给「参与人键」加能力(带版本、可逆、可解析),没有挂载点。 - -按 [模型设计三层法](../design/model-design.md) 复盘这一族类: - -- **职责**:名字承诺了不属于它们的事。`Policy` 承诺策略却在做全局配置;`Guard` 承诺守卫却只做告警去重;`OperatorIdentity` 承诺身份类型却是一堆静态函数。 -- **抽象**:「参与人相等」与「参与人键」是两个变化频率相同的概念,各自都该独立成模型,现在却散落在使用者里。 -- **实现**:身份以裸 `String` 在 359 处流转,所以每一处都要重复「归一化 + 比较 + 拼接」,也就必然长成静态函数集合。 - -**结论**:这一族类的病根不是「用了静态方法」,是**身份没有成为类型**。形态问题只是症状。 - -> 上述问题已在 `refactor/operator-identity` 分支按 P1~P5 处理完毕,落地结果见文末「落地记录」。 - -## 契约 - -### H1 参与人标识必须成对传递 - -新增或修改的公开方法签名,**不得**再出现 `(long operatorId, String identity)` 这种「把一个人拆成两个参数」的形式,必须传 `OperatorKey`。 - -理由:拆开传会让「一个人」这个整体在签名层面消失,调用方随时可能漏传身份,编译器不会拦。这正是 359 处裸 `String` 的成因。存量签名在 P1/P2 中逐步收敛,但不得在新增代码里扩大。 - -### H2 同一参与人的判定只有一个入口 - -```java -OperatorKey#matches(OperatorKey other, OperatorIdentityMatchMode mode) -``` - -任何「这个人是不是那条记录上的人」的判断,都必须经过它(或接受 `IFlowOperator` 的重载)。 - -**禁止**在业务代码里写 `a.getUserId() == b.getUserId() && OperatorIdentity.same(...)`。写入即缺陷,不需要讨论。 - -### H3 参与人键只有一个生成点 - -```java -OperatorKey#key() -``` - -缓存键、Map 键、去重键一律由它产生。**禁止**任何类自行 `a + 分隔符 + b`;分隔符常量只允许**一处声明**。当前 4 份声明(`#` × 2、`\u0001` × 2)在 P2 收敛为 1 份。 - -待办合并键是复合键(参与人 + 运行时 + 节点),由独立的键模型回答,不复用 `key()`,但同样只能有一个定义点。 - -### H4 匹配模式影响键时,必须经由键模型 - -匹配模式确实会改变存储键的语义:`USER_ONLY` 下同一人的两个身份必须合并成一条待办,`STRICT` 下必须分开。这是业务事实,不可能靠「禁止」消除。 - -因此本条的约束不是「不许影响」,而是**影响的方式必须唯一且集中**: - -1. 键格式(含是否追加身份后缀)只允许在键模型内部决定,业务类不得在方法体里读 `matchMode()` 后自己拼字符串; -2. 键模型只接收一个布尔语义(`OperatorIdentityMatchMode#identityDistinguishes()`),不接收整个模式再自己分支; -3. 迁移服务必须复用同一个键模型,避免「拼法与迁移不同源」——历史上模式切换导致合并组一分为二、需要重建快照,根因就是这一点。 - -落地:`OperatorKey#key(mode)` 与 `TodoMergeKey#value()` 是两个键格式的唯一定义点。 - -### H5 命名即契约(本域) - -| 名字 | 必须是什么 | 状态 | -|---|---|---| -| `OperatorIdentity` | 身份值对象(不可变,`of` 构造,`value()` 取值,`equals` 判等) | ✅ 已改造 | -| `OperatorKey` | 参与人标识值对象,承载 `matches` / `key(mode)` / `identityEquals` | ✅ 已改造 | -| `OperatorSelections` | 操作人选择集合,收口「带身份优先于仅 id」 | ✅ 新增 | -| `TodoMergeKey` | 待办合并键(复合键),键格式唯一定义点 | ✅ 新增 | -| `OperatorIdentityMatchMode` | 策略:自己回答 `match` 与 `identityDistinguishes` | ✅ 已改造 | -| `OperatorIdentityContext` | 全局配置持有(可变单例),原 `OperatorIdentityPolicy` | ✅ 已改造 | -| `OperatorManager` | 参与人集合,一个查询入口 `match(IFlowOperator)` | ✅ 已改造 | -| `OperatorIdentityHeader` | 请求头契约与「头优先于 query」解析,位于接入层 | ✅ 已移出 | -| `OperatorIdentityWarnLog` | 身份透传告警(可观测性),去重状态归属实例 | ✅ 已移出 | - -### H6 分层:身份解析属接入层 - -`OperatorIdentity#pick(headerValue, parameterValue, parameterPresent)` 实现的是「请求头优先于 query」的 HTTP 约定,属接入层。放在 domain 包里,等于让领域模型知道 HTTP 头存在,违反「换掉 Web 框架业务模型零改动」。 - -P5 移到 `flow-engine-starter-api` 的 `com.codingapi.flow.api.OperatorIdentityHeader`,`OperatorIdentityHeaderTest` 随之迁移;查询侧复用同一份常量(`flow-engine-starter-query` 依赖 `flow-engine-starter-api`)。 - -## 判定流程(提交前四问) - -1. **有没有新增 `(long id, String identity)` 签名?** 有 → 改传 `OperatorKey`。 -2. **有没有自己判断「是不是同一个人」?** 有 → 改 `OperatorKey#matches`。 -3. **有没有自己拼参与人键?** 有 → 改 `OperatorKey#key`。 -4. **有没有在方法体里读匹配模式?** 有 → 这条规则应下沉进键或判定模型。 - -四问全否,才算符合本契约。 - -## 分批改造 - -原则:**先收敛语义(纯委托、行为零变化),再改结构,最后类型化。** 每批独立可回滚。 - -| 批次 | 范围 | 行为变化 | 验收 | -|---|---|---|---| -| **P0** ✅ | 本文档 + 索引 + `AGENTS.md` / `CLAUDE.md` 一条指向 | 无(零代码) | 文档评审通过 | -| **P1 相等收敛** ✅ | `OperatorKey` 增 `matches`;`Policy#matches`、`Policy#sameOperator`、`OperatorManager`、`FlowOperatorLocalThreadCache#isIdentityMatched` 全部委托;`OperatorManager` 去掉默认身份重载 | 无 | 32 个身份相关测试类断言零修改 | -| **P2 键收敛** ✅ | `OperatorKey#key()` 成为唯一参与人键生成点;cache / guard / `FlowContent` 改用它;分隔符常量收敛为 1 份;新增待办合并键模型,`FlowRecord#getTodoKey()` 委托它 | 无(键值逐个比对) | `FlowTodoKeyIdentityTest`、`FlowOperatorBulkIdentityTest`、`FlowRecordIdentityConvertorTest` 零修改 | -| **P3 模式策略化** ✅ | `OperatorIdentityMatchMode` 实现 `match`;`OperatorIdentityPolicy` → `OperatorIdentityContext`;`reset()` → `use(mode)` | 无(`use` 仅影响测试写法) | `OperatorIdentityPolicyTest` 改名适配 | -| **P4 对象化** ✅ | `OperatorScriptResultResolver`(#308)、`OperatorAssignmentService` 改构造注入 | 无 | 见 #308 的 7 条契约 | -| **P5 类型化** ✅ | `OperatorIdentity` → 值对象;`pick` 移接入层;`Guard` 移出领域包 | 公开 API 变更,需版本说明 | 全量测试 + 集成方迁移说明 | - -**P1~P4 统一验收口径**:`./mvnw test` 全绿,且现有测试的**断言一行不改**。改断言等于改行为契约,必须单独说明理由。 - -## 禁止清单 - -- ❌ 新增静态工具类处理身份(回到 [模型设计三层法](../design/model-design.md) 的老问题) -- ❌ 业务类内联 `userId == ... && identity.equals(...)` -- ❌ 自行拼接参与人键 -- ❌ 在方法体里读 `matchMode()` 决定数据格式 -- ❌ 给 `OperatorManager` 补「默认身份」重载 -- ❌ 为测试暴露 `reset()` 这类静态状态清理方法(应通过构造注入或显式作用域隔离) - -## 关联 - -- 多身份引入 #288 · 参与人二元标识 #290 · 分配携带身份 #292 · 批量按身份回取 #293 · 身份透传告警 #294 · 匹配策略 #297 · 身份请求头 #301 · 脚本返回值多形态 #303 -- #308 解析器对象化(P4)· #309 存量盘点(本契约覆盖其中 4 项)· #310 模型设计三层法 - -## 落地记录(P1~P5,`refactor/operator-identity`) - -### 语义收敛 - -| 原来 | 现在 | -|---|---| -| 5 处拼参与人键、4 份分隔符声明 | `OperatorKey#key(mode)` 唯一定义,分隔符常量 1 份(U+0001) | -| 5 处判「是否同一人」 | `OperatorKey#matches(other, mode)` 唯一入口,`OperatorIdentityMatchMode` 是策略 | -| `FlowRecord#getTodoKey()` 手拼合并键 | `TodoMergeKey#value()` 唯一定义,`FlowRecord` 只决定「谁参与合并」 | -| 4 个服务各自 `if (!matches(...)) throw` | `FlowRecord#verifyOperator(OperatorKey)` | -| `FlowActionService` / `FlowCreateService` 各自 if-else 二选一 | `OperatorSelections` 收口「带身份优先」 | -| `FlowContent` 判断模式后拼去重键 | `OperatorKey#key(mode)` | - -### API 变更(集成方需注意) - -| 变更 | 影响 | -|---|---| -| `OperatorIdentity` 由静态工具类改为值对象 | `normalize(x)` → `of(x).value()`;`isDefault(x)` → `of(x).isDefault()`;`same(a,b)` → `of(a).equals(of(b))`;`validate(x)` → `of(x).validate().value()`;`DEFAULT` 取字符串用 `DEFAULT.value()` | -| `OperatorIdentityPolicy` → `OperatorIdentityContext` | `setMatchMode(m)` → `getInstance().use(m)`;`matchMode()` → `getInstance().matchMode()`;`reset()` 删除(测试用 `use(STRICT)`) | -| `OperatorIdentityGuard` → `diagnostic.OperatorIdentityWarnLog` | `check(...)` → `getInstance().warnOnce(...)`;去重状态归属实例,测试用 `new` 隔离 | -| `OperatorIdentity.pick` → `api.OperatorIdentityHeader.resolve` | 仅接入层使用;`OPERATOR_IDENTITY` / `IDENTITY_SCOPE` / `LOCK_IDENTITY` 常量随之迁移 | -| `OperatorScriptResultResolver.resolve(holder, result, type)` | `new OperatorScriptResultResolver(holder, type).resolve(result)` | -| `OperatorAssignmentService.validateAndSave*` | `new OperatorAssignmentService(session).assign(processId, selections)` | -| `OperatorManager.getOperator(long[, String])` | `match(IFlowOperator)`(配置匹配固定严格口径,不随运行时模式放宽) | - -### 验收 - -- `./mvnw test` 全绿:framework 545、infra 8、api 7、starter 10、example 7,合计 577 -- 现有身份相关测试的断言未因行为变化而修改;仅因 API 形态变化改了调用形式 -- 新增测试:`OperatorKeyTest`、`OperatorManagerTest`、`TodoMergeKeyTest`、`OperatorIdentityContextTest`、`OperatorScriptElementTest`、`OperatorSelectionsTest`、`OperatorIdentityWarnLogTest` - -### 未做(需单独版本窗口) - -`OperatorIdentity` 值对象已在位,但 `OperatorKey` 内部仍以 `String` 存身份(`identity()` 返回 `String`)。 -把 `OperatorKey` 的字段改为 `OperatorIdentity` 属公开签名变更,影响约百处调用,按 H1 的渐进策略留待后续版本。 diff --git a/docs/conventions/index.md b/docs/conventions/index.md index 7d0ce111..80805e32 100644 --- a/docs/conventions/index.md +++ b/docs/conventions/index.md @@ -7,7 +7,7 @@ | 名称 | 模块 | 描述 | 范围 | 来源 | |------|------|------|------|------| | [design/model-design](./design/model-design.md) | design | 模型设计三层法 — 职责 → 抽象 → 实现;垂直按 DDD 分层(业务/数据/技术),水平按包/类/方法递归;以易维护与可验证为验收 | 通用 | 项目自有 | -| [domain/operator-identity](./domain/operator-identity.md) | domain | 多身份语义契约 — 参与人相等与参与人键各只有一个定义点;匹配模式只改判定不改存储键格式;P0~P5 分批收敛 | `com.codingapi.flow.operator` 及其调用方 | 项目自有 | +| [docs/documentation](./docs/documentation.md) | docs | 文档编写与维护规范 — 四类文档各有唯一归属;过程记录不入规范;代码是唯一事实源;计数可复算;代码与文档同批提交 | 通用 | 项目自有 | | [workflow/github-issue](./workflow/github-issue.md) | workflow | GitHub Issue 标准处理流程 — 定位分析 → 回复 issue → worktree 修复 → 推送特性分支 → 推送后回复 | 通用 | 项目自有 | --- diff --git a/docs/manual/README.md b/docs/manual/README.md index 981b338c..179ce334 100644 --- a/docs/manual/README.md +++ b/docs/manual/README.md @@ -16,7 +16,7 @@ Flow Engine 是企业级工作流引擎,采用前后端分离架构:后端 ## 当前版本 -- 版本号:`0.1.0-SNAPSHOT`(前后端对齐) +- 版本号:`0.3.0-SNAPSHOT`(前后端对齐) - 后端:JDK 17 / Spring Boot 3.5.9 / Spring Data JPA(默认 H2,支持达梦 DM) - 前端:React 18 / TypeScript 5 / pnpm 10 / antd 6(PC)/ antd-mobile 5(移动)/ @flowgram.ai 1.0.8 diff --git a/docs/manual/integration-manual.html b/docs/manual/integration-manual.html index bf5aa23d..ee9b031d 100644 --- a/docs/manual/integration-manual.html +++ b/docs/manual/integration-manual.html @@ -90,7 +90,7 @@

        Flow Engine 集成手册

        本手册面向后端与前端开发者,完整介绍如何将 Flow Engine(后端)与 flow-frontend(前端框架)集成到一个企业项目中。涵盖后端 Spring Boot 集成、前端 packages 集成能力、插件扩展机制,以及基于官方示例(后端 flow-engine-example、前端 app-pc / app-mobile)的集成分析。

        -
        适用版本:后端 0.1.0-SNAPSHOT(Java 17 / Spring Boot 3.5.9);前端 0.1.9(React 18 / TypeScript 5 / pnpm 10 monorepo)。
        +
        适用版本:后端 0.3.0-SNAPSHOT(Java 17 / Spring Boot 3.5.9);前端 0.1.9(React 18 / TypeScript 5 / pnpm 10 monorepo)。

        目录

        @@ -222,7 +222,7 @@

        2.1 一站式引入(推荐)

        <dependency>
             <groupId>com.codingapi.flow</groupId>
             <artifactId>flow-engine-starter</artifactId>
        -    <version>0.1.0-SNAPSHOT</version>
        +    <version>0.3.0-SNAPSHOT</version>
         </dependency>

        starter 通过 Spring Boot 自动装配机制注册以下 AutoConfiguration:

        diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java index d150f280..ba5d4994 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java @@ -6,7 +6,7 @@ *

        同一个人员可以以不同身份参与流程,因此凡是「指向某个参与人」的持久化数据或批量参数, * 都不能只保存人员 id。该类型用于人员分配(发起人设定 / 审批人设定)等需要显式携带身份的场景。 * - *

        本类是「参与人」这一概念的唯一载体(见 {@code docs/conventions/domain/operator-identity.md}): + *

        本类是「参与人」这一概念的唯一载体(见 {@code docs/capabilities/flow-engine-framework/operator-identity.md}): *

          *
        • {@link #matches(OperatorKey, OperatorIdentityMatchMode)} —— 「是否同一个人」的唯一判定入口;
        • *
        • {@link #key(OperatorIdentityMatchMode)} —— 参与人键(缓存键 / Map 键 / 去重键)的唯一生成点;
        • diff --git a/flow-frontend b/flow-frontend index 3fbe89e7..d57de25f 160000 --- a/flow-frontend +++ b/flow-frontend @@ -1 +1 @@ -Subproject commit 3fbe89e7178244251ac28d0fba89b13bb26e85d4 +Subproject commit d57de25f7ae84e48a7439ff8532f73b3215e0782 From e04499fe8c5c5ea8b8cdf2027fda59d7b6195c68 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Thu, 3 Dec 2026 20:25:39 +0800 Subject: [PATCH 35/35] 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 d57de25f..7fd4b0ad 160000 --- a/flow-frontend +++ b/flow-frontend @@ -1 +1 @@ -Subproject commit d57de25f7ae84e48a7439ff8532f73b3215e0782 +Subproject commit 7fd4b0ad190636baf9ffb6ce1b3e6fee10f317e6