diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md index b978d9d3..62901d3e 100644 --- a/docs/Integration/operator-identity.md +++ b/docs/Integration/operator-identity.md @@ -159,7 +159,7 @@ advice.setOperatorSelectOperators(Map.of(nextNodeId, List.of(OperatorKey.of(3L, ### 3.4 在脚本中使用身份 -`GroovyScriptRequest` 新增三个函数: +**读取身份**:`GroovyScriptRequest` 提供三个函数(常用于条件脚本): | 脚本函数 | 含义 | |----------|------| @@ -176,18 +176,57 @@ def run(request) { } ``` +**产出参与人**(取人脚本,以及异常脚本的 `operators`)支持三种返回形态,允许在同一列表内混用(逐元素判定): + +| 形态 | 示例 | 身份来源 | 是否回查 | +|------|------|----------|----------| +| `List` | `return [1, 2]` | 默认身份 | 是(按默认身份批量) | +| `List` | `return [request.getCreatedOperatorKey()]` | `OperatorKey.identity()` | 是(按身份分组批量) | +| `List` | `return [$bind.getOperatorByIdentity(2, 'department1')]` | 对象自带 `getIdentity()` | **否**,直接采用 | + +约定: + +- 三种形态由 `OperatorScriptResultResolver` 统一解析,回查按身份分组批量执行、结果按脚本返回顺序输出; +- 顶层可写单值(`return request.getCreatedOperatorId()`),按单元素处理; +- 非正数的人员 id(存量脚本用 `[-1]` 表示「无审批人」)会被跳过,不抛异常; +- 其他非法元素抛 `FlowValidationException`,消息带脚本类型、元素类型与元素内容(不再出现 `NumberFormatException`)。 + +**默认模板(issue #303 起)**:新建节点的取人脚本为 + +```groovy +// @SCRIPT_TITLE 流程创建者 +// @SCRIPT_META {"type":"creator"} +def run(request){ + return [request.getCreatedOperatorKey()] +} +``` + +创建者以**发起时的身份**参与流程。存量流程定义里的旧脚本(`return [request.getCreatedOperatorId()]`)行为不变,仍落默认身份;需要身份时把脚本改为 `getCreatedOperatorKey()`。 + +构造带身份的人员标识: + +| 脚本函数 | 返回 | 说明 | +|----------|------|------| +| `request.getCreatedOperatorKey()` | `OperatorKey` | 创建者 + 创建时身份 | +| `request.getCurrentOperatorKey()` | `OperatorKey` | 当前审批人 + 当前身份 | +| `request.getSubmitOperatorKey()` | `OperatorKey` | 提交人 + 提交时身份 | +| `$bind.getOperatorKey(userId, identity)` | `OperatorKey` | 只构造标识,不回查 | +| `request.findPreviousNodeOperators()` | `List` | 上一节点实际审批人,含身份 | +| `$bind.getOperatorByIdentity(userId, identity)` | `IFlowOperator` | 回查得到带身份的操作者 | +| `request.findPreviousNodeOperatorIds()` | `List` | 上一节点审批人 id(不含身份,保留兼容) | + 人员差异(审批人脚本): ```groovy def run(request) { def identity = request.getCreatedOperatorIdentity() - if (identity == 'department1') return [boss1Id] - if (identity == 'department2') return [boss2Id] + if (identity == 'department1') return [request.getCreatedOperatorKey()] + if (identity == 'department2') return [$bind.getOperatorKey(boss2Id, 'department2')] return [defaultBossId] } ``` -需要「让某人以指定身份参与」时,用 `$bind.getOperatorByIdentity(id, identity)` 拿到带身份的操作者: +让某人以指定身份参与: ```groovy def run(request) { @@ -196,6 +235,14 @@ def run(request) { } ``` +复用上一节点审批人(含身份): + +```groovy +def run(request) { + return request.findPreviousNodeOperators() +} +``` + ## 4. 引擎侧行为 ### 4.1 记录与待办落库 @@ -305,6 +352,7 @@ codingapi.flow.identity.match-mode=USER_ONLY | 工作流定义 | 与身份无关,导入导出不受影响 | | 身份长度 | ≤ 64 字符(复合 key 用 `:` 拼接),入口与落库双处校验 | | 待办索引 | 实体未声明 `@Index`,大表请按 DDL 脚本手工加索引 | +| 默认取人脚本 | issue #303 起新建节点的默认脚本返回 `OperatorKey`(创建者以发起身份参与);存量流程定义中的旧脚本不受影响,不迁移 | | 不做的事 | 引擎不建组织模型、不做身份授权校验(「user1 能否以 department1 身份操作」由业务侧保证)、不冻结身份名称 | > 身份是一个**不透明字符串**,不要尝试在引擎里比较它的业务含义;需要「部门名称」等展示信息,由宿主维护 `identity → 名称` 的映射自行渲染(框架不提供附加属性字段)。 @@ -334,6 +382,11 @@ codingapi.flow.identity.match-mode=USER_ONLY 前端应提供「选择 / 切回默认身份」的入口(示例工程见 5.2):`STRICT` 或锁定身份查看时,用户仍能处理存量事项; 默认 `USER_ONLY` 下它的作用是声明**本次操作身份**(脚本上下文与留痕),不影响能看到哪些数据。 +> **默认取人脚本升级(issue #303)**:新建节点的默认取人脚本已从 `[request.getCreatedOperatorId()]` +> 改为 `[request.getCreatedOperatorKey()]`,创建者以**发起时的身份**参与。因此同一条流程在升级前后发起的实例, +> 创建者节点的身份可能不同(旧实例为默认身份)。这是「身份跟随发起上下文」的预期行为,不做数据迁移; +> 存量流程定义中的脚本文本是独立保存的,不会被自动改写。 + ### 5.2 示例工程如何验证 `flow-engine-example` + `flow-frontend` 的 `apps/app-pc`(PC)与 `apps/app-mobile`(移动端)都已打通端到端验证, diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java b/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java index f089295f..dfad0f91 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/exception/FlowValidationException.java @@ -170,6 +170,26 @@ public static FlowValidationException invalidParameter(String fieldName, String String.format("Parameter %s has invalid value '%s', expected %s", fieldName, value, expected)); } + /** + * 取人脚本返回值中存在不支持的元素(issue #303)。 + * + *

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

diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/ScriptDefaultConstants.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/ScriptDefaultConstants.java index c4632d3d..efcd2c6c 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/ScriptDefaultConstants.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/ScriptDefaultConstants.java @@ -74,12 +74,15 @@ def run(request){ /** * 默认人员加载脚本 + * + *

返回 {@code OperatorKey}(人员id + 身份),创建者以「发起时的身份」参与流程, + * 不会退化为默认身份(issue #303)。 */ public static final String SCRIPT_DEFAULT_OPERATOR_LOAD = """ // @SCRIPT_TITLE 流程创建者 // @SCRIPT_META {"type":"creator"} def run(request){ - return [request.getCreatedOperatorId()] + return [request.getCreatedOperatorKey()] } """; diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/factory/FlowGroovyScriptFactory.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/factory/FlowGroovyScriptFactory.java index 835fa602..5ffaad7b 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/factory/FlowGroovyScriptFactory.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/factory/FlowGroovyScriptFactory.java @@ -157,8 +157,13 @@ public static GroovyScript createOperatorLoadScript(String script) { String key = FlowIDGeneratorGatewayContext.getInstance().generateFlowScriptKey(); String description = """ 匹配人员列表脚本 - 传入对象为 GroovyScriptRequest 对象,返回数据格式为 List<Long> 类型,即 long[] 数组格式,每一个 long 的 id 数据为一个人员的 id,示例格式为 [1,2,3]。 - 返回的人员 id 将会作为匹配人员信息,作为流程的审批者。 + 传入对象为 GroovyScriptRequest 对象,返回数据格式支持三种,且允许在同一列表中混用: +

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    核心回归:以 {@code department1} 身份发起流程,审批人由「流程创建者」脚本产生时, + * 审批记录的 {@code currentOperatorIdentity} 必须是 {@code department1},而不是退化为默认身份。 + */ +class OperatorScriptIdentityFlowTest { + + private static final long INITIATOR = 1; + private static final long APPROVER = 2; + + private static final String DEPARTMENT_1 = "department1"; + private static final String DEPARTMENT_2 = "department2"; + + private MyFlowServiceFactory factory; + private final Map data = Map.of("name", "lorne"); + + @BeforeEach + void setUp() { + factory = new MyFlowServiceFactory(); + factory.userGateway.save(new User(INITIATOR, "initiator")); + factory.userGateway.save(new User(APPROVER, "approver")); + GatewayContext.getInstance().setFlowOperatorGateway(factory.userGateway); + } + + /** + * 测试目标:创建者脚本返回 {@code OperatorKey} 时,审批记录落创建时的身份。 + * 前置条件:流程为 Start -> Approval(脚本返回 request.getCreatedOperatorKey()) -> End。 + * 执行步骤:以 department1 身份发起并提交。 + * 期望断言:审批待办记录的 currentOperatorIdentity 为 department1。 + */ + @Test + void should_land_created_identity_when_operator_script_returns_operator_key() { + Workflow workflow = saveCreatorScriptFlow("script-identity-creator"); + + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + FlowRecord approvalRecord = todoRecordOf(INITIATOR); + assertEquals(INITIATOR, approvalRecord.getCurrentOperatorId()); + assertEquals(DEPARTMENT_1, approvalRecord.getCurrentOperatorIdentity(), + "审批人身份应跟随创建时的身份"); + } + + /** + * 测试目标:同一流程换身份发起,落库身份跟随发起身份。 + * 前置条件:同 {@link #should_land_created_identity_when_operator_script_returns_operator_key()}。 + * 执行步骤:以 department2 身份发起并提交。 + * 期望断言:审批待办记录的 currentOperatorIdentity 为 department2。 + */ + @Test + void should_land_identity_of_current_creation_when_created_with_another_identity() { + Workflow workflow = saveCreatorScriptFlow("script-identity-creator-2"); + + long startRecordId = createFlow(workflow, DEPARTMENT_2); + submit(workflow, startRecordId, DEPARTMENT_2); + + assertEquals(DEPARTMENT_2, todoRecordOf(INITIATOR).getCurrentOperatorIdentity()); + } + + /** + * 测试目标:{@code request.findPreviousNodeOperators()} 在无上一节点时安全返回空列表。 + * 前置条件:取人脚本运行在开始节点,不存在前驱审批记录。 + * 执行步骤:执行脚本。 + * 期望断言:返回空列表,不抛异常。 + */ + @Test + void should_return_empty_previous_operators_at_start_node() { + Workflow workflow = saveCreatorScriptFlow("script-identity-previous"); + IFlowNode startNode = workflow.getStartNode(); + + OperatorLoadStrategy startStrategy = new OperatorLoadStrategy(FlowGroovyScriptFactory + .createOperatorLoadScript("def run(request){return request.findPreviousNodeOperators()}") + .getKey()); + FormData formData = new FormData(form("script-identity-previous")); + formData.getDataBody().set("name", "lorne"); + com.codingapi.flow.session.FlowSession session = com.codingapi.flow.session.FlowSession.startSession( + factory.repositoryHolder, new User(INITIATOR, "initiator"), workflow, startNode, + startAction(workflow), formData, 0); + + assertTrue(startStrategy.loadOperators(session).getOperators().isEmpty()); + } + + // ==================== 流程构建 ==================== + + /** + * 构建 Start(可撤回) -> Approval(创建者脚本,返回带身份的 OperatorKey) -> End 的流程。 + */ + private Workflow saveCreatorScriptFlow(String code) { + StartNode startNode = StartNode.builder() + .strategies(NodeStrategyBuilder.builder() + .addStrategy(fieldPermission(code)) + .addStrategy(new RevokeStrategy(true, RevokeStrategy.Type.REVOKE_CURRENT)) + .build()) + .actions(ActionBuilder.builder() + .addAction(CustomAction.defaultAction()) + .build()) + .build(); + + ApprovalNode approvalNode = ApprovalNode.builder() + .name("创建者审批") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(fieldPermission(code)) + .addStrategy(new OperatorLoadStrategy(FlowGroovyScriptFactory + .createOperatorLoadScript("def run(request){return [request.getCreatedOperatorKey()]}") + .getKey())) + .build()) + .build(); + + Workflow workflow = WorkflowBuilder.builder() + .title("取人脚本身份流程") + .code(code) + .createdOperator(new User(INITIATOR, "initiator")) + .form(form(code)) + .addNode(startNode) + .addNode(approvalNode) + .addNode(EndNode.builder().build()) + .build(); + factory.workflowService.saveWorkflow(workflow); + return workflow; + } + + private FlowForm form(String code) { + return FlowFormBuilder.builder() + .name("取人脚本身份流程") + .code(code) + .addField("请假人", "name", DataType.STRING) + .build(); + } + + private FormFieldPermissionStrategy fieldPermission(String code) { + return new FormFieldPermissionStrategy(FormFieldPermissionsBuilder.builder() + .addPermission(code, "name", PermissionType.WRITE) + .build()); + } + + // ==================== 动作入口 ==================== + + private long createFlow(Workflow workflow, String operatorIdentity) { + FlowCreateRequest request = new FlowCreateRequest(); + request.setWorkCode(workflow.getCode()); + request.setFormData(data); + request.setActionId(startAction(workflow).id()); + request.setOperatorId(INITIATOR); + request.setOperatorIdentity(operatorIdentity); + return factory.flowService.create(request); + } + + private void submit(Workflow workflow, long recordId, String operatorIdentity) { + FlowAdviceBody advice = new FlowAdviceBody(startAction(workflow).id(), "提交", INITIATOR); + advice.setOperatorIdentity(operatorIdentity); + FlowActionRequest request = new FlowActionRequest(); + request.setFormData(data); + request.setRecordId(recordId); + request.setAdvice(advice); + factory.flowService.action(request); + } + + private IFlowAction startAction(Workflow workflow) { + return workflow.getStartNode().actionManager().getActions().get(0); + } + + private FlowRecord todoRecordOf(long operatorId) { + List records = factory.flowRecordRepository.findTodoByOperator(operatorId); + assertEquals(1, records.size(), "操作人应有且仅有一条待办"); + return records.get(0); + } +}