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 1/5] =?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 2/5] =?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 3/5] =?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 4/5] =?UTF-8?q?feat(script):=20=E8=84=9A=E6=9C=AC=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E6=8C=89=E8=BA=AB=E4=BB=BD=E8=8E=B7=E5=8F=96=E6=93=8D?= =?UTF-8?q?=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 5/5] =?UTF-8?q?fix(identity):=20=E8=A1=A5=E9=BD=90=20issue?= =?UTF-8?q?=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; + } }