diff --git a/AGENTS.md b/AGENTS.md index 2f249ec5..05a690df 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)。 ### 核心模块 @@ -36,7 +36,7 @@ Flow Engine 是一个企业级工作流引擎,基于 Java 17 和 Spring Boot 3 ### 服务编排模式(FlowService) -`FlowService`(`flow-engine-framework/.../service/FlowService.java`)是 `@Transactional` 业务入口,共 8 个入口方法(detail / processNodes / create / action / revoke / delete / urge / resetSubProcess)。**每个流程操作对应一个独立的 `FlowXxxService`**(`FlowCreateService` / `FlowActionService` / `FlowRevokeService` / `FlowDeleteService` / `FlowUrgeService` / `FlowDetailService` / `FlowProcessNodeService` / `FlowSubProcessResetService` / `FlowSubProcessResultService` / `FlowDelayTriggerService` / `OperatorAssignmentService` 等),通过 `IRepositoryHolder` 注入依赖,且每次操作前调用 `FlowOperatorLocalThreadCache.getInstance().clear()` 与 `FlowRuntimeScriptLocalCache` 清理线程缓存。新增流程操作应沿用此模式:新建 `FlowXxxService(request, repositoryHolder)`,并在 `FlowService` 暴露一个入口方法。 +`FlowService`(`flow-engine-framework/.../service/FlowService.java`)是 `@Transactional` 业务入口,共 10 个入口方法(detail / processNodes / create / action / revoke / delete / urge / resetSubProcess / reissue / forceSync)。**每个流程操作对应一个独立的 `FlowXxxService`**(`FlowCreateService` / `FlowActionService` / `FlowRevokeService` / `FlowDeleteService` / `FlowUrgeService` / `FlowDetailService` / `FlowProcessNodeService` / `FlowSubProcessResetService` / `FlowSubProcessResultService` / `FlowDelayTriggerService` / `OperatorAssignmentService` 等),通过 `IRepositoryHolder` 注入依赖,且每次操作前调用 `FlowOperatorLocalThreadCache.getInstance().clear()` 与 `FlowRuntimeScriptLocalCache` 清理线程缓存。新增流程操作应沿用此模式:新建 `FlowXxxService(request, repositoryHolder)`,并在 `FlowService` 暴露一个入口方法。 ### 仓储持有者(IRepositoryHolder) @@ -62,9 +62,9 @@ REST 层通过请求参数 `mockKey` 分流到 Mock 实例(见 `FlowRecordCont - `ActionManager` 持有节点动作 - 节点类型常量见 `StartNode.NODE_TYPE`(= `NodeType.START.name()`),`FlowRecord.isNodeType(String)` 用于按类型判定 -### 事件(IFlowEvent + EventPusher) +### 事件(IFlowEvent + FlowEventPublisher) -11 种事件:开始 / 待办 / 已办 / 完成 / 催办 / 撤销(`FlowRecordRevokeEvent`)/ 删除(`FlowRecordDeleteEvent`)/ 子流程重置(`FlowSubProcessResetEvent`)/ 减签(`FlowRecordReduceAuditEvent`)/ 二次发起(`FlowRecordReissueEvent`)/ 保存(`FlowRecordSaveEvent`,由 `FlowRecordSaveService.saveAll()` 按实际落库记录逐条推送)。操作完成后用 `FlowEventPublisher.push(event)` 推送(**禁止**直接调用 `EventPusher`);引入 starter 时由 `SpringFlowEventPublisher` 保证「事务提交后投递 + 按 `eventKey()`(默认 processId)分区串行」,未注册实现时自动回退 `EventPusher`。记录类事件携带 `FlowRecord` + `mock` 标记,重置事件携带新旧聚合组快照。外部可用 Spring `@EventListener` 订阅。 +12 种事件:开始 / 待办 / 已办 / 完成 / 催办 / 撤销(`FlowRecordRevokeEvent`)/ 删除(`FlowRecordDeleteEvent`)/ 子流程重置(`FlowSubProcessResetEvent`)/ 减签(`FlowRecordReduceAuditEvent`)/ 二次发起(`FlowRecordReissueEvent`)/ 保存(`FlowRecordSaveEvent`,由 `FlowRecordSaveService.saveAll()` 按实际落库记录逐条推送)/ 强制同步(`FlowRecordForceSyncEvent`,每个被同步实例一条)。操作完成后用 `FlowEventPublisher.push(event)` 推送(**禁止**直接调用 `EventPusher`);引入 starter 时由 `SpringFlowEventPublisher` 保证「事务提交后投递 + 按 `eventKey()`(默认 processId)分区串行」,未注册实现时自动回退 `EventPusher`。记录类事件携带 `FlowRecord` + `mock` 标记,重置事件携带新旧聚合组快照。外部可用 Spring `@EventListener` 订阅。 ### API 模块划分 @@ -110,9 +110,35 @@ cd flow-engine-example && mvn spring-boot:run ### 基本规范 - **与用户沟通及编写文档时,所有内容必须使用中文表述** +- **修改任何文档前必须先读 [文档编写与维护规范](./docs/conventions/docs/documentation.md)**:四类文档各有唯一归属,过程记录不入 `conventions/`,代码是唯一事实源 - **在每次修改代码以后,要执行本地化的编译验证确保代码没有错误** - Java 代码遵循 Spring Boot 规范 +### 模型设计(分层 → 职责 → 抽象 → 实现) + +写新类 / 改结构前必须遵守 [docs/conventions/design/model-design.md](./docs/conventions/design/model-design.md),顺序不可颠倒: + +0. **分层**:先判它属于业务(Domain)/ 数据(Repository)/ 技术细节(Infrastructure)哪一层,包位置对不对;Domain 不得依赖 JPA、HTTP、脚本引擎、上传格式处理;数据层不写业务判断。 +1. **职责**:一句话说清它为什么存在(不含「和」);三条边界(谁能调用 / 依赖谁 / 返回值归谁)明确;名字能反推职责。 +2. **抽象**:共性提炼为唯一真源(不是复用,是唯一真源);会变的部分与不变的部分分开;不跨抽象层取字段。 +3. **实现与命名**:按调用方的使用方式选模式(对象 / 策略 / 工厂 / Context / 事件 / 网关 / 仓储),命名必须体现模式;模式反推拆分。 +4. **形态**:禁止「空私有构造 + 公有静态方法」的工具类;上下文一律**构造注入**;**一个对象一个公有入口**;静态方法只允许无状态纯计算与类型自身语义;`private static` 可变字段必须收敛到 `XxxContext` / `XxxCache`。 + +同一规则在包 / 类 / 方法三个尺度上递归适用,评审时追问:**这一层的职责和上一层是不是同一个粒度?** + +验收两条:**易维护**(新增一种能力 = 加文件,不改老流程的 `if`)+ **可验证**(新增先有失败用例;重构只能改调用形式,断言零改动)。 + +### 多身份(Operator Identity) + +改 `com.codingapi.flow.operator` 或任何涉及「人员 + 身份」的代码前,必须先读 [多身份参与模型](./docs/capabilities/flow-engine-framework/operator-identity.md)。四条硬线: + +- **不得新增** `(long operatorId, String identity)` 形式的公开签名,一律传 `OperatorKey`; +- 「是否同一参与人」只允许调 `OperatorKey#matches(..., mode)`,禁止内联 id/identity 比较; +- 参与人键(缓存键 / Map 键 / 去重键)只允许由 `OperatorKey#key()` 产生,禁止自行拼字符串; +- 匹配模式只能改变**判定**,不得在方法体里读 `matchMode()` 去改变**数据格式**(待办合并键、响应去重键)。 + +接入方式与落库口径见 [集成说明](./docs/Integration/operator-identity.md)。 + ### 测试规范 本项目后端采用 JUnit 5 进行单元测试。 diff --git a/CLAUDE.md b/CLAUDE.md index 669c9eeb..4b98225a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ ## 项目概述 -Flow Engine 是一个企业级工作流引擎,基于 Java 17 和 Spring Boot 3.5.9 构建(当前版本 0.1.0-SNAPSHOT)。 +Flow Engine 是一个企业级工作流引擎,基于 Java 17 和 Spring Boot 3.5.9 构建(当前版本 0.3.0-SNAPSHOT)。 ### 核心模块 @@ -36,7 +36,7 @@ Flow Engine 是一个企业级工作流引擎,基于 Java 17 和 Spring Boot 3 ### 服务编排模式(FlowService) -`FlowService`(`flow-engine-framework/.../service/FlowService.java`)是 `@Transactional` 业务入口,共 8 个入口方法(detail / processNodes / create / action / revoke / delete / urge / resetSubProcess)。**每个流程操作对应一个独立的 `FlowXxxService`**(`FlowCreateService` / `FlowActionService` / `FlowRevokeService` / `FlowDeleteService` / `FlowUrgeService` / `FlowDetailService` / `FlowProcessNodeService` / `FlowSubProcessResetService` / `FlowSubProcessResultService` / `FlowDelayTriggerService` / `OperatorAssignmentService` 等),通过 `IRepositoryHolder` 注入依赖,且每次操作前调用 `FlowOperatorLocalThreadCache.getInstance().clear()` 与 `FlowRuntimeScriptLocalCache` 清理线程缓存。新增流程操作应沿用此模式:新建 `FlowXxxService(request, repositoryHolder)`,并在 `FlowService` 暴露一个入口方法。 +`FlowService`(`flow-engine-framework/.../service/FlowService.java`)是 `@Transactional` 业务入口,共 10 个入口方法(detail / processNodes / create / action / revoke / delete / urge / resetSubProcess / reissue / forceSync)。**每个流程操作对应一个独立的 `FlowXxxService`**(`FlowCreateService` / `FlowActionService` / `FlowRevokeService` / `FlowDeleteService` / `FlowUrgeService` / `FlowDetailService` / `FlowProcessNodeService` / `FlowSubProcessResetService` / `FlowSubProcessResultService` / `FlowReissueService` / `FlowForceSyncService` / `FlowDelayTriggerService` / `OperatorAssignmentService` 等),通过 `IRepositoryHolder` 注入依赖,且每次操作前调用 `FlowOperatorLocalThreadCache.getInstance().clear()` 与 `FlowRuntimeScriptLocalCache` 清理线程缓存。新增流程操作应沿用此模式:新建 `FlowXxxService(request, repositoryHolder)`,并在 `FlowService` 暴露一个入口方法。 ### 仓储持有者(IRepositoryHolder) @@ -62,9 +62,9 @@ REST 层通过请求参数 `mockKey` 分流到 Mock 实例(见 `FlowRecordCont - `ActionManager` 持有节点动作 - 节点类型常量见 `StartNode.NODE_TYPE`(= `NodeType.START.name()`),`FlowRecord.isNodeType(String)` 用于按类型判定 -### 事件(IFlowEvent + EventPusher) +### 事件(IFlowEvent + FlowEventPublisher) -9 种事件:开始 / 待办 / 已办 / 完成 / 催办 / 撤销(`FlowRecordRevokeEvent`)/ 删除(`FlowRecordDeleteEvent`)/ 减签(`FlowRecordReduceAuditEvent`)/ 子流程重置(`FlowSubProcessResetEvent`)。操作完成后用 `EventPusher.push(event)` 推送;记录类事件携带 `FlowRecord` + `mock` 标记,重置事件携带新旧聚合组快照。外部可用 Spring `@EventListener` 订阅。 +12 种事件:开始 / 待办 / 已办 / 完成 / 催办 / 撤销(`FlowRecordRevokeEvent`)/ 删除(`FlowRecordDeleteEvent`)/ 减签(`FlowRecordReduceAuditEvent`)/ 子流程重置(`FlowSubProcessResetEvent`)/ 二次发起(`FlowRecordReissueEvent`)/ 保存(`FlowRecordSaveEvent`)/ 强制同步(`FlowRecordForceSyncEvent`)。操作完成后用 `FlowEventPublisher.push(event)` 推送(**禁止**直接调用 `EventPusher`);引入 starter 时由 `SpringFlowEventPublisher` 保证「事务提交后投递 + 按 `eventKey()` 分区串行」,未注册实现时自动回退 `EventPusher`。记录类事件携带 `FlowRecord` + `mock` 标记,重置事件携带新旧聚合组快照。外部可用 Spring `@EventListener` 订阅。 ### API 模块划分 @@ -103,9 +103,35 @@ cd flow-engine-example && mvn spring-boot:run ### 基本规范 - **与用户沟通及编写文档时,所有内容必须使用中文表述** +- **修改任何文档前必须先读 [文档编写与维护规范](./docs/conventions/docs/documentation.md)**:四类文档各有唯一归属,过程记录不入 `conventions/`,代码是唯一事实源 - **在每次修改代码以后,要执行本地化的编译验证确保代码没有错误** - Java 代码遵循 Spring Boot 规范 +### 模型设计(分层 → 职责 → 抽象 → 实现) + +写新类 / 改结构前必须遵守 [docs/conventions/design/model-design.md](./docs/conventions/design/model-design.md),顺序不可颠倒: + +0. **分层**:先判它属于业务(Domain)/ 数据(Repository)/ 技术细节(Infrastructure)哪一层,包位置对不对;Domain 不得依赖 JPA、HTTP、脚本引擎、上传格式处理;数据层不写业务判断。 +1. **职责**:一句话说清它为什么存在(不含「和」);三条边界(谁能调用 / 依赖谁 / 返回值归谁)明确;名字能反推职责。 +2. **抽象**:共性提炼为唯一真源(不是复用,是唯一真源);会变的部分与不变的部分分开;不跨抽象层取字段。 +3. **实现与命名**:按调用方的使用方式选模式(对象 / 策略 / 工厂 / Context / 事件 / 网关 / 仓储),命名必须体现模式;模式反推拆分。 +4. **形态**:禁止「空私有构造 + 公有静态方法」的工具类;上下文一律**构造注入**;**一个对象一个公有入口**;静态方法只允许无状态纯计算与类型自身语义;`private static` 可变字段必须收敛到 `XxxContext` / `XxxCache`。 + +同一规则在包 / 类 / 方法三个尺度上递归适用,评审时追问:**这一层的职责和上一层是不是同一个粒度?** + +验收两条:**易维护**(新增一种能力 = 加文件,不改老流程的 `if`)+ **可验证**(新增先有失败用例;重构只能改调用形式,断言零改动)。 + +### 多身份(Operator Identity) + +改 `com.codingapi.flow.operator` 或任何涉及「人员 + 身份」的代码前,必须先读 [多身份参与模型](./docs/capabilities/flow-engine-framework/operator-identity.md)。四条硬线: + +- **不得新增** `(long operatorId, String identity)` 形式的公开签名,一律传 `OperatorKey`; +- 「是否同一参与人」只允许调 `OperatorKey#matches(..., mode)`,禁止内联 id/identity 比较; +- 参与人键(缓存键 / Map 键 / 去重键)只允许由 `OperatorKey#key()` 产生,禁止自行拼字符串; +- 匹配模式只能改变**判定**,不得在方法体里读 `matchMode()` 去改变**数据格式**(待办合并键、响应去重键)。 + +接入方式与落库口径见 [集成说明](./docs/Integration/operator-identity.md)。 + ### 测试规范 本项目后端采用 JUnit 5 进行单元测试。 diff --git a/README.md b/README.md index 575283dd..6cb3d5b7 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ flow-engine ├── flow-engine-framework # 核心流程引擎框架 ├── flow-engine-starter # Spring Boot 自动配置入口 ├── flow-engine-starter-api # REST API 层(命令操作:create / action / revoke / delete / urge / detail / processNodes / subProcess/reset,含节点视图脚本接口) -├── flow-engine-starter-infra # 持久化层(JPA 实体、11 个仓储实现、含达梦方言) +├── flow-engine-starter-infra # 持久化层(JPA 实体、12 个仓储实现、含达梦方言) ├── flow-engine-starter-query # 查询层(流程记录与流程定义只读 API) ├── flow-engine-example # 示例应用(H2/达梦数据库、JWT 认证、端口 8090) └── flow-frontend # 前端项目(独立 Git 仓库,PC + 移动端,详见下文“前端模块架构”) @@ -53,7 +53,7 @@ flow-engine | `manager` | 管理器层:动作、节点、策略、操作者管理 | | `session` | 执行上下文:FlowSession、FlowAdvice、IRepositoryHolder | | `record` | 流程记录:FlowRecord、FlowTodoRecord、FlowTodoMerge | -| `repository` | 12 个仓储接口(持久化抽象,由 infra 模块实现) | +| `repository` | 13 个仓储接口(持久化抽象,由 infra 模块实现) | | `event` | 9 种流程事件:开始 / 待办 / 已办 / 完成 / 催办 / 撤销 / 删除 / 减签 / 子流程重置 | | `exception` | 框架异常体系:异常基类 + 6 种具体异常(验证 / 未找到 / 状态 / 权限 / 执行 / 导入导出) | | `form` | 表单系统:字段定义、数据校验、字段权限、值转换 | diff --git a/docs/Integration/README.md b/docs/Integration/README.md index 7d770cc8..3a87169f 100644 --- a/docs/Integration/README.md +++ b/docs/Integration/README.md @@ -8,7 +8,7 @@ |------|------|----------| | `flow-engine-framework` | 核心引擎:节点/动作/策略/脚本/服务/仓储接口(Spring 无关的领域核心) | 只读,一般不改动 | | `flow-engine-starter` | Spring Boot 自动配置入口,把引擎单例与 Spring 容器打通 | 直接依赖 | -| `flow-engine-starter-infra` | JPA 持久化实现(11 张 `t_flow_*` 表 + 11 个仓储实现) | 可直接依赖;也可自行实现仓储接口替换 | +| `flow-engine-starter-infra` | JPA 持久化实现(11 张 `t_flow_*` 表 + 12 个仓储实现) | 可直接依赖;也可自行实现仓储接口替换 | | `flow-engine-starter-api` | 命令 REST API(发起/审批/撤销/催办/删除 + 流程设计 CRUD) | 可选依赖 | | `flow-engine-starter-query` | 查询 REST API(待办/已办/抄送/全部列表) | 可选依赖 | | `flow-engine-example` | 下游集成范本(用户体系、事件订阅、脚本仓储、安全) | 参考实现 | @@ -23,7 +23,7 @@ | 2 | `IFlowOperator` 实现类 | 用户实体/DTO,实现 `getUserId/getName/isFlowManager/forwardOperator` | [流程用户体系](./user-integration.md) | | 3 | `NodeViewJavaScriptRepository` | 节点视图 JS 持久化(infra 不提供,需自建) | [仓储抽象](./repository-integration.md) | | 4 | 脚本持久化:`GroovyScriptRepository`、`TempGroovyScriptRepository` | Groovy 脚本落库(外部 starter-script 的 SPI) | [仓储抽象](./repository-integration.md) | -| 5 | 11 个仓储接口(仅当不引入 `flow-engine-starter-infra` 时) | 自行实现存储 | [仓储抽象](./repository-integration.md) | +| 5 | 13 个仓储接口(仅当不引入 `flow-engine-starter-infra` 时) | 自行实现存储 | [仓储抽象](./repository-integration.md) | ## 文档目录 @@ -31,10 +31,11 @@ |------|------| | [快速开始](./quick-start.md) | 最小集成步骤:引入依赖 → 提供 Bean → 编写流程 → 发起流程 | | [流程用户体系](./user-integration.md) | `FlowOperatorGateway` / `IFlowOperator` / `GatewayContext` / 线程缓存 / 当前登录人 | +| [多身份参与](./operator-identity.md) | 同一人员多身份:身份 SPI、请求声明、查询范围、判定模式(`USER_ONLY`/`STRICT`)、升级 DDL | | [流程默认脚本](./script-integration.md) | 12 种脚本类型、`GroovyScriptRequest` 完整 API、`$bind`、默认脚本替换、脚本生命周期 | -| [流程事件机制](./event-integration.md) | 9 种事件、`EventPusher`、`IHandler` 订阅、异步分发管道、事务变体、推送时机 | -| [仓储抽象与持久化](./repository-integration.md) | `IRepositoryHolder`、12 个仓储接口(含 11 个 JPA 实现 + 需自行实现的 `NodeViewJavaScriptRepository`)、脚本仓储、锁机制 | -| [Spring Boot 自动配置](./auto-configuration.md) | `AutoConfiguration` 8 个 Bean、4 个 Register、必选/可选 Bean 清单 | +| [流程事件机制](./event-integration.md) | 12 种事件、`FlowEventPublisher`、`IHandler` 订阅、异步分发管道、事务变体、推送时机 | +| [仓储抽象与持久化](./repository-integration.md) | `IRepositoryHolder`、13 个仓储接口(含 12 个 JPA 实现 + 需自行实现的 `NodeViewJavaScriptRepository`)、脚本仓储、锁机制 | +| [Spring Boot 自动配置](./auto-configuration.md) | `AutoConfiguration` 10 个 Bean、5 个启动注册器、必选/可选 Bean 清单、配置项 | | [REST API](./rest-api.md) | 5 个 Controller、`mockKey`/`operatorId` 分流机制、请求/响应结构 | | [Mock 模式](./mock-mode.md) | 全内存沙箱 `MockInstance`、15 分钟过期、接入方式 | | [节点/动作/策略扩展](./extension-points.md) | 19 种节点 × 9 种动作 × 15 种节点策略 × 2 种流程策略,扩展方式 | @@ -53,25 +54,27 @@ | `FlowScriptContext` | 脚本 `$bind` 上下文(`IBeanFactory`) | `FlowScriptContextRegister` | | `FlowIDGeneratorGatewayContext` | ID 生成器(可替换扩展点) | 默认内建,可选替换 | | `NodeViewJavaScriptCacheContext` | 节点视图 JS 缓存(15 分钟) | `NodeViewJavaScriptCacheContextRegister` | -| `FlowOperatorLocalThreadCache` | 操作人线程缓存 | 引擎内部使用 | +| `FlowOperatorLocalThreadCache` | 操作人线程缓存(键含身份) | 引擎内部使用 | | `FlowRuntimeScriptLocalCache` | 脚本快照线程缓存 | 引擎内部使用 | +| `OperatorIdentityContext` | 身份匹配模式(可变全局配置,默认 `STRICT`) | `OperatorIdentityConfigurer`(starter 启动时写入) | | `MockInstanceFactory` | Mock 沙箱工厂 | api 模块调用 | ### 执行链路 ``` REST 请求 → FlowRecordController - (mockKey 分流 Mock / 生产;operatorId 覆盖当前用户) + (mockKey 分流 Mock / 生产;operatorId 覆盖当前用户;X-Operator-Identity 声明身份) → FlowService(@Transactional,清线程缓存) - → FlowXxxService(create / action / revoke / delete / urge / detail) + → FlowXxxService(create / action / revoke / delete / urge / detail / + processNodes / resetSubProcess / reissue / forceSync) → FlowSession(不可变会话)→ 节点 handle → 动作 run → 策略执行 → repositoryHolder.saveRecords(落库) - → EventPusher.push(推送事件,异步) + → FlowEventPublisher.push(推送事件;starter 下事务提交后按流程分区串行) ``` ## 版本约定 -- 引擎版本:`0.1.0-SNAPSHOT`(根 pom `revision`) +- 引擎版本:`0.3.0-SNAPSHOT`(根 pom `revision`) - 外部框架依赖(根 pom `codingapi.framework.version = 17.3.1`): - `com.codingapi.springboot:springboot-starter` —— 事件体系(`EventPusher`/`IHandler`)、`UserContext`、`LocaleMessageException` - `com.codingapi.springboot:springboot-starter-script` —— Groovy 脚本引擎(`GroovyScript`/注解/仓储 SPI) diff --git a/docs/Integration/auto-configuration.md b/docs/Integration/auto-configuration.md index ed34ff7f..5b1b61af 100644 --- a/docs/Integration/auto-configuration.md +++ b/docs/Integration/auto-configuration.md @@ -9,16 +9,20 @@ - `META-INF/spring.factories` → `EnableAutoConfiguration=com.codingapi.flow.AutoConfiguration` - `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports` → `com.codingapi.flow.AutoConfiguration` -`AutoConfiguration` 为 `@Configuration`,**无 `@ConditionalOnMissingBean`、无条件注解** —— 构造函数依赖的 Bean 缺失将导致启动失败。 +`AutoConfiguration` 为 `@Configuration` + `@EnableConfigurationProperties(FlowProperties.class)`(issue #297 起)。 +除 `SpringFlowEventPublisher`(带 `@ConditionalOnMissingBean` / `@ConditionalOnProperty`)外**无条件注解** —— +所需 Bean 缺失将导致启动失败。 ## 2. 注册的 Bean 全清单 | @Bean | 依赖 | 作用 | |---|---|---| +| `OperatorIdentityConfigurer` | `FlowProperties` | 启动时把 `codingapi.flow.identity.match-mode` 写入 framework 的 `OperatorIdentityContext`(issue #297 / #311 P3) | | `NodeViewJavaScriptCacheContextRegister` | **`NodeViewJavaScriptRepository`** | 构造器内执行 `NodeViewJavaScriptCacheContext.getInstance().setNodeViewJavaScriptRepository(repo)`(15 分钟缓存上下文) | | `GatewayContextRegister` | **`FlowOperatorGateway`** | 把操作人网关灌入 `GatewayContext` 单例(`InitializingBean`) | | `FlowScriptContextRegister` | `ApplicationContext` + **`FlowOperatorGateway`** + `FlowRecordRepository` | 给 `FlowScriptContext` 单例设置 `IBeanFactory`(转发 Spring 容器,脚本 `$bind` 依赖) | | `RepositoryHolderContextRegister` | `WorkflowService` + `FlowRecordService` + 6 个仓储 + `GatewayContextRegister` | 把 8 个依赖灌入 `RepositoryHolderContext` 单例(`InitializingBean`) | +| `SpringFlowEventPublisher` | `ApplicationContext` | 事务提交后投递 + 按流程 id 分区串行(可用 `codingapi.flow.event.ordered=false` 关闭,关闭后回退事件框架直投;`IFlowEvent.eventKey()` 默认取 `processId`,强制同步/子流程重置事件取主流程 id) | | `FlowRecordService` | `FlowTodoRecordRepository` + `FlowTodoMergeRepository` + `FlowRecordRepository` | 记录服务 Bean | | `WorkflowService` | `WorkflowVersionRepository` + `WorkflowRepository` + `WorkflowRuntimeRepository` | 流程设计服务 Bean | | `FlowService` | `RepositoryHolderContextRegister`(仅保证顺序) | `new FlowService(RepositoryHolderContext.getInstance())`,业务入口 | @@ -29,6 +33,13 @@ 全部位于 `flow-engine-starter/src/main/java/com/codingapi/flow/register/`,均实现 `InitializingBean`: ```java +// OperatorIdentityConfigurer(issue #297 / #311 P3) +@Override +public void afterPropertiesSet() { + // framework 不依赖 Spring,模式通过静态持有者传递 + OperatorIdentityContext.getInstance().use(flowProperties.getIdentity().getMatchMode()); +} + // GatewayContextRegister @Override public void afterPropertiesSet() { @@ -72,7 +83,7 @@ public void afterPropertiesSet() { | 1 | `FlowOperatorGateway` | 对接应用用户体系(`get`/`findByIds`) | `GatewayContextRegister` → `GatewayContext`;同时被 `FlowScriptContextRegister`、api Controller 依赖 | | 2 | `IFlowOperator` 实现类 | 用户实体/DTO | 由 Gateway 返回,经 `FlowOperatorLocalThreadCache` 缓存 | | 3 | `NodeViewJavaScriptRepository` | 节点视图 JS 持久化(infra 无实现) | `NodeViewJavaScriptCacheContextRegister` 构造器 | -| 4 | 11 个仓储接口实现 | 引入 `flow-engine-starter-infra` 则自动提供;否则自行实现 | `RepositoryHolderContextRegister` / `FlowRecordService` / `WorkflowService` | +| 4 | 13 个仓储接口实现 | 引入 `flow-engine-starter-infra` 则自动提供;否则自行实现 | `RepositoryHolderContextRegister` / `FlowRecordService` / `WorkflowService` | | 5 | `GroovyScriptRepository` + `TempGroovyScriptRepository` | 脚本持久化 SPI(外部 starter-script) | 自注册到对应 `*RepositoryContext` 单例 | ### 可选(有默认实现 / 按需替换) @@ -89,6 +100,7 @@ public void afterPropertiesSet() { | 配置前缀 | 作用 | |---|---| +| `codingapi.flow.identity.match-mode` | 身份匹配模式:`USER_ONLY`(starter 默认,办理只比人员)/ `STRICT`(人员+身份,framework 默认)。启动时生效,不支持热切换(issue #297) | | `codingapi.script.tempValidTime` | 临时脚本有效期(默认 15 分钟) | | `codingapi.script.shellMaxCacheSize` | 脚本编译缓存上限(默认 10240) | | `codingapi.framework.handler-thread-pool-size` | 异步事件线程池大小(默认 20) | diff --git a/docs/Integration/event-integration.md b/docs/Integration/event-integration.md index 0abb0702..66f1ef35 100644 --- a/docs/Integration/event-integration.md +++ b/docs/Integration/event-integration.md @@ -27,7 +27,7 @@ public interface IAsyncEvent extends IEvent {} // 异步事件标记 ← 同步/异步由 `DomainEventContext.push` 的 `instanceof` 判定:`IAsyncEvent` → 异步(线程池执行);`ISyncEvent`/裸 `IEvent` → 同步(发布线程内联执行)。 -### 1.2 十一种事件 +### 1.2 十二种事件 记录类事件均携带 `FlowRecord`(或当前记录)与 `boolean mock` 标记(Mock 模式为 `true`)。 @@ -44,6 +44,7 @@ public interface IAsyncEvent extends IEvent {} // 异步事件标记 ← | `FlowSubProcessResetEvent` | 子流程数据重置(issue #219) | `SubProcessRecord oldRecord, SubProcessRecord newRecord, long resetRecordId, IFlowOperator resetOperator, boolean mock` | `getOldRecord()` / `getNewRecord()` / `getResetRecordId()` / `getResetOperator()` / `isMock()` | | `FlowRecordReissueEvent` | 已完成流程二次发起(issue #272) | `FlowRecord sourceRecord, FlowRecord newRecord, IFlowOperator operator, boolean mock` | `getSourceRecord()` / `getNewRecord()` / `getOperator()` / `isMock()` | | `FlowRecordSaveEvent` | 流程记录保存(每条实际落库记录,issue #280) | `FlowRecord, boolean mock` | `getFlowRecord()` / `isMock()` | +| `FlowRecordForceSyncEvent` | 运行中实例强制同步最新流程设计(issue #281) | `FlowRecord flowRecord, long oldWorkRuntimeId, long newWorkRuntimeId, boolean mock` | `getFlowRecord()` / `getOldWorkRuntimeId()` / `getNewWorkRuntimeId()` / `isMock()` | **子流程重置事件订阅须知**: @@ -71,7 +72,7 @@ public class FlowRecordUrgeEvent implements IFlowEvent { `FlowRecord`(`flow-engine-framework/.../record/FlowRecord.java`)提供: - 基本信息:`getId()`、`getProcessId()`、`getWorkTitle()`、`getWorkCode()`、`getNodeId()`、`getNodeType()`、`getNodeName()`、`getTitle()`、`getFormData()`(`Map`) -- 操作人:`getCurrentOperatorId/Name()`、`getSubmitOperatorId/Name()`、`getCreateOperatorId/Name()`、`getForwardOperatorId/Name()` +- 操作人:`getCurrentOperatorId/Name/Identity()`、`getSubmitOperatorId/Name/Identity()`、`getCreateOperatorId/Name/Identity()`、`getForwardOperatorId/Name/Identity()`、`getHandleOperatorId/Name/Identity()`(办理人,issue #306) - 状态:`isTodo()`、`isDone()`、`isFinish()`、`isAutoDone()`、`isShow()`、`isNotEndNode()`、`isPendingApproval()`(待审批,含顺序审批未激活的隐藏记录) - 抄送标记:`isNotify()` - 动作:`getActionId()`、`getActionType()`、`getActionName()`、`getAdvice()` @@ -134,6 +135,7 @@ public class EventPusher { | `FlowSubProcessResetService.reset()` | 被作废记录链逐条 `RevokeEvent` + 子流程重置 `SubProcessResetEvent`;重建实例经 `FlowCreateService` 推送各自的 `StartEvent` + `TodoEvent` | | `FlowReissueService.reissue()` | 二次发起 `ReissueEvent` + 新流程经 `FlowCreateService` 推送的 `StartEvent` + `TodoEvent` | | `FlowRecordSaveService.saveAll()` | 本次实际落库的每条记录 `SaveEvent`(结束节点虚拟记录不落库,不推送) | +| `FlowForceSyncService.forceSync()` | 每个被同步实例一条 `ForceSyncEvent`(旧 → 新运行时快照 id) | > 事件在业务数据保存之后推送,且引入 starter 时会在**事务提交后**才投递给订阅方(见 4.5),保证订阅方回查到的记录已持久化。 diff --git a/docs/Integration/extension-points.md b/docs/Integration/extension-points.md index 7d669f2f..b859af94 100644 --- a/docs/Integration/extension-points.md +++ b/docs/Integration/extension-points.md @@ -145,7 +145,7 @@ IFlowAction#run | 类 | 用途 | |---|---| -| `NodeStrategyManager` | 节点全部策略的门面:`loadOperators(session)`、`getMaxOperatorCount()`、`getOperatorSelectType()`、`generateTitle(session)`、`errorTrigger(session)`、`getFieldPermissions()`、`isAdviceRequired()` 等 | +| `NodeStrategyManager` | 节点全部策略的门面:`loadOperators(session)`、`getMaxOperatorCount()`、`getOperatorSelectType()`、`generateTitle(session)`、`errorTrigger(session)`(返回 `ErrorThrow`,含 `NODE` / `OPERATORS` / `PROMPT` 三种处理方式)、`getFieldPermissions()`、`isAdviceRequired()` 等 | | `ActionManager` | 动作管理:`filterActions(session)`、`getActionById(id)`、`getActionByType(type)`、`verifySession(session)` | | `OperatorManager` | 操作人集合:`isEmpty()`、`match(operator)`、`getOperator(userId)` | | `WorkflowStrategyManager` | 流程策略:`isEnableInterfere()`、`verifyOperator` | @@ -157,7 +157,7 @@ IFlowAction#run | 子类 | 典型工厂方法与错误场景 | |---|---| -| `FlowValidationException` | `fieldReadOnly`(字段只读)、`operatorCountExceeded(nodeId, max)`(超出最大可选人数)、`operatorOutOfRange`(超出可选范围)、`required` 等 | +| `FlowValidationException` | `fieldReadOnly`(字段只读)、`operatorCountExceeded(nodeId, max)`(超出最大可选人数)、`operatorOutOfRange`(超出可选范围)、`nextNodeOperatorEmpty(nodeId, nodeName, message)`(下一节点无审批人且配置为异常提示,issue #296)、`required` 等 | | `FlowExecutionException` | `scriptExecutionError`、`routerNodeNotFound`、`operatorCountExceeded`、`invalidJumpTarget(nodeType)`、`errorTriggerLoop`、`subProcessLoop`、`addAuditOperatorAlreadyInTodo`、`reduceAuditSingleApprover`、`reduceAuditTargetNotFound` 等 | | `FlowStateException` | `repositoryNotRegistered`、`recordAlreadyDone`、`operatorNotMatch`、`workflowAlreadyDisable`、`recordNotSupportRevoke` 等 | | `FlowNotFoundException` | `workflow(workCode)`、`record(recordId)`、`node(nodeId)`、`operator(operatorId)`、`action(actionId)` | diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md new file mode 100644 index 00000000..5df26680 --- /dev/null +++ b/docs/Integration/operator-identity.md @@ -0,0 +1,461 @@ +# 多身份参与(Operator Identity) + +> 面向业务项目的集成说明,对应 issue #288(身份标识)与 issue #297(身份语义收口)。 +> 引擎只负责**透传、存储与比较**身份标识,不解释其业务语义,也不内建组织模型。 +> 身份**默认不作为办理权限**:它服务脚本与留痕,不阻断「同一个人办理自己的待办」(见 4.4 / 4.6)。 + +## 1. 解决什么问题 + +一个用户可能同时隶属多个部门(或身兼多个岗位),在不同事项上以不同身份参与流程: + +| 差异类型 | 例子 | +|----------|------| +| 节点 / 分支差异 | user1 在 department1 发起需要「组长审核」,在 department2 发起则直接「部门经理审核」 | +| 人员差异 | department1 的经理是 boss1,department2 的经理是 boss2 | +| 待办差异 | user1 在 department1 / department2 各有一条待办,不能合并成一条(`STRICT` 模式;`USER_ONLY` 下按人合并) | + +0.2.x 的引擎只认 `userId`:记录、待办、权限判定全部按 userId 比较,上述场景无法表达。 + +## 2. 模型 + +身份标识是一个**不透明字符串**,由下游定义取值,框架只做四件事: + +1. 从 `IFlowOperator#getIdentity()` 读取; +2. 落库到流程记录与待办; +3. 在需要区分参与人时按 `(userId, identity)` 比较——**是否把身份作为「能否办理」的条件由匹配模式决定** + (默认只比 `userId`,见 4.4 / 4.6); +4. 透传给 Groovy 脚本与 REST 响应。 + +约定:`null` 与空串等价,均表示**默认身份**(`OperatorIdentity.DEFAULT`)。未启用多身份的业务、以及 0.3.0 之前的历史数据,全部落在默认身份上,行为与历史完全一致。 + +```java +public interface IFlowOperator extends IUser { + + long getUserId(); + + String getName(); + + boolean isFlowManager(); + + IFlowOperator forwardOperator(GroovyScriptRequest request); + + /** + * 身份标识,空串表示默认身份。框架不解释语义。 + */ + default String getIdentity() { + return OperatorIdentity.DEFAULT.value(); + } +} +``` + +`getIdentity()` 是 `default` 方法,**下游存量实现类无需改动即可编译**。 + +> 身份只保存 `identity` 这一个不透明字符串:不落库附加属性、不冻结身份名称。 +> 需要「部门名称」等展示信息时,由宿主持有身份 → 名称的映射自行渲染,框架不提供该字段。 + +## 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.of(identity).isDefault()) { + return user; + } + // 必须复制:直接改写实体会污染持久化上下文 / 线程缓存,导致同一 id 的两个身份互相覆盖 + return user.withIdentity(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)` | + +> 引擎做了两层兜底,保证「没覆盖」不会静默丢身份: +> +> 1. **单条路径**:`GatewayContext#getFlowOperator(id, identity)`、发起(`FlowCreateService`)与审批(`FlowActionService`)三个入口都会做运行期检查——请求声明了非默认身份、但回查到的操作者身份为空时,按 `(人员id, 身份)` 去重输出一条 WARN; +> 2. **批量路径**:`GatewayContext#findByIds(ids, identity)` 发现批量结果身份不符时,逐条回退到单条按身份取人(正确实现会返回带身份的副本,未实现则触发上面的 WARN),同时不把身份不符的对象登记进线程缓存,避免污染后续按身份的读取。 + +### 3.3 请求声明身份 + +REST 接口通过**请求头** `X-Operator-Identity` 声明当前身份(issue #301):未传时取当前登录操作者的身份; +若同时用 `operatorId` 覆盖了人员,身份归默认身份(避免出现「人员与身份错配」的副本)。 +显式选择「默认身份」时传空值(`X-Operator-Identity:`),与「未携带」区分。 + +> ⚠️ **不要用 query 参数 `operatorIdentity` 传身份**:引擎的部分查询接口(如 `/api/query/workflow/list`) +> 用 `SearchRequest` 接收请求,会把所有 query 参数当作实体过滤字段解析,多一个 `operatorIdentity` 就会抛 +> `Field operatorIdentity not found in class hierarchy`,页面直接 500。 +> 为兼容旧调用方,服务端仍保留 query 读取(非 `SearchRequest` 接口可用),但请求头优先。 + +```bash +# 以 department1 的身份发起(身份随记录落库:create_operator_identity) +curl -X POST 'http://host/api/cmd/record/create' \ + -H 'X-Operator-Identity: department1' \ + -H 'Content-Type: application/json' -d '{...}' + +# 查看待办:默认跨身份,X-Operator-Identity 只是「本次操作身份」上下文,不影响返回范围 +curl 'http://host/api/query/record/todo?operatorId=1' -H 'X-Operator-Identity: department1' + +# 只想看「落在 department1 下」的待办时,显式锁定身份(见 4.3) +curl 'http://host/api/query/record/todo?operatorId=1' \ + -H 'X-Operator-Identity: department1' \ + -H 'X-Identity-Scope: LOCKED' +``` + +| 请求头 | 取值 | 说明 | +|---|---|---| +| `X-Operator-Identity` | 身份标识 / 空串 | 当前操作/查看的身份,空串表示显式默认身份 | +| `X-Identity-Scope` | `ALL` / `LOCKED` | 查询范围:默认跨身份,`LOCKED` 只看当前身份 | +| `X-Lock-Identity` | `true` / `false` | `X-Identity-Scope` 的等价简写 | + +编程式 API 中对应各请求对象的 `operatorIdentity` 字段: + +| 请求对象 | 字段 | +|----------|------| +| `FlowCreateRequest` | `operatorIdentity` | +| `FlowAdviceBody`(`FlowActionRequest.advice`) | `operatorIdentity` | +| `FlowRevokeRequest` / `FlowDeleteRequest` / `FlowUrgeRequest` | `operatorIdentity` | +| `FlowDetailRequest` / `FlowProcessNodeRequest` | `operatorIdentity` | +| `FlowReissueRequest` / `FlowForceSyncRequest` / `FlowSubProcessResetRequest` | `operatorIdentity` | + +**为节点指定同一人的多个身份**:`INITIATOR_SELECT` / `APPROVER_SELECT` 节点原有 `operatorSelectMap`(`节点ID -> List`)无法表达「同一人员以两个身份参与」,新增 `operatorSelectOperators`(`节点ID -> List`),每项为 `(operatorId, identity)`: + +```java +// 发起时指定(FlowCreateRequest) +createRequest.setOperatorSelectOperators(Map.of(approvalNodeId, List.of( + OperatorKey.of(2L, "department1"), + OperatorKey.of(2L, "department2")))); + +// 审批意见里指定(FlowAdviceBody,用于「审批时选择下一步审批人」的节点) +advice.setOperatorSelectOperators(Map.of(nextNodeId, List.of(OperatorKey.of(3L, "department1")))); +``` + +- 同一人员的两个身份是**两项**参与人,不会被去重合并;完全相同的二元组才去重; +- `operatorSelectOperators` 优先于存量的 `operatorSelectMap`,两者都不传则不落分配关系; +- 存量调用方继续使用 `operatorSelectMap`,按默认身份处理,无需改动; +- 二次发起(reissue)会连同身份一起复制源流程的人员设定,避免重走后退化到默认身份。 + +### 3.4 在脚本中使用身份 + +**读取身份**:`GroovyScriptRequest` 提供三个函数(常用于条件脚本): + +| 脚本函数 | 含义 | +|----------|------| +| `getCurrentOperatorIdentity()` | 当前操作者身份 | +| `getCreatedOperatorIdentity()` | 流程发起人身份 | +| `getSubmitOperatorIdentity()` | 流程提交人身份 | + +节点/分支差异(条件脚本): + +```groovy +def run(request) { + // department1 需要组长审核,其他身份直接进入部门经理审批 + return request.getCurrentOperatorIdentity() == 'department1' +} +``` + +**产出参与人**(取人脚本,以及异常脚本的 `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 [request.getCreatedOperatorKey()] + if (identity == 'department2') return [$bind.getOperatorKey(boss2Id, 'department2')] + return [defaultBossId] +} +``` + +让某人以指定身份参与: + +```groovy +def run(request) { + // 让 user2 以 department1 的身份成为审批人(记录里落的就是 department1) + return [$bind.getOperatorByIdentity(2, 'department1')] +} +``` + +复用上一节点审批人(含身份): + +```groovy +def run(request) { + return request.findPreviousNodeOperators() +} +``` + +## 4. 引擎侧行为 + +### 4.1 记录与待办落库 + +| 表 | 新增列 | +|----|--------| +| `t_flow_record` | `create_operator_identity`、`submit_operator_identity`、`current_operator_identity`、`forward_operator_identity`、`interfered_operator_identity`、`handle_operator_identity` | +| `t_flow_todo_record` | `create_operator_identity`、`submit_operator_identity`、`current_operator_identity` | + +「办理人」另有两列非身份字段(issue #306):`handle_operator_id`、`handle_operator_name`,与 `handle_operator_identity` 一起记录**谁以什么身份办理了这条记录**。待办表不加这三列——待办尚未办理,没有办理人语义。 + +只存身份标识本身,**不落库任何附加属性**(避免为 5 组操作者各加一个 JSON 快照列,也避免身份名称被冻结在历史数据里)。展示名称仍取操作者姓名;需要展示身份名称时由宿主按 `identity` 自行映射。 + +升级脚本见 [sql/0.3.0-operator-identity.sql](./sql/0.3.0-operator-identity.sql)。 + +### 4.2 待办合并键(由匹配模式决定) + +`FlowRecord#getTodoKey()` 的格式: + +| 模式 | 身份 | 合并键 | +|------|------|--------| +| `USER_ONLY` | 任意 | `{operatorId}-{workRuntimeId}-{nodeId}`(身份不参与) | +| `STRICT` | 默认身份 | `{operatorId}-{workRuntimeId}-{nodeId}`(与 0.2.x 完全一致) | +| `STRICT` | 非空身份 | `{operatorId}-{workRuntimeId}-{nodeId}#{identity}` | + +`USER_ONLY` 下身份不参与合并:身份只是脚本与留痕信息,同一个人的两个身份在同一节点是**一个参与人**, +否则同一个人会在待办列表里出现两条同样的待办。`STRICT` 下两个身份是独立参与人,必须分键, +其中默认身份保持历史格式是刻意的:升级瞬间仍在运行的流程,其存量待办行是旧格式键, +若统一改格式会导致新流转算出的键查不到旧行 → 重复生成待办、合并关系断裂。 + +> 切换匹配模式后,存量待办的键仍是旧格式,合并组会一分为二,属预期行为; +> 需要收拢时执行 `FlowTodoMigrateService` 重建待办快照。 + +### 4.3 查询范围(默认跨身份,可显式锁定) + +身份不是权限,同一个人在不同身份下的待办都属于他自己。因此查询默认**按人员 id 返回全部身份**的数据: + +- `/api/query/record/todo|done|notify` 默认不带身份条件,`operatorIdentity` 只作为身份上下文(展示、后续操作),不会隐式改变查询范围; +- 需要「锁定当前身份查看」时显式传 `identityScope=LOCKED`(或 `lockIdentity=true`),此时按 `coalesce(currentOperatorIdentity, '') = :identity` 过滤,历史 NULL 行视为默认身份; +- `identityScope` 只接受 `ALL` / `LOCKED`,其他值在入口即报参数错误,避免拼写错误静默放宽范围。 + +因此宿主始终携带 `operatorIdentity` 也不会导致待办「消失」——这是 issue #297 修正的关键行为。 + +**Mock 链路同口径**:带 `mockKey` 的 REST 调用走 `FlowRecordQueryMockService`,待办 / 抄送 / 已办同时保留「跨身份」与「按身份」两套重载,前端联调与真实库路径行为一致。 + +> **自定义查询实现注意**:`FlowRecordQueryService` 里带身份的三个方法是 `default` 方法,默认直接退化为「只按人员」的旧方法。 +> 自己实现该接口(不用 starter-query 提供的 `FlowRecordQueryServiceImpl`)时,若不覆盖它们, +> `identityScope=LOCKED` 会**静默退化**为跨身份查询——功能看似正常,但「锁定身份查看」不生效。 + +### 4.4 办理权限判定(可配置模式) + +「当前用户能否办理/撤回/催办/减签某条记录」统一由 `OperatorIdentityContext` 判定(原 `OperatorIdentityPolicy`,issue #311 P3 改名;它只持有模式,判定规则唯一落在 `OperatorKey#matches`),模式可配置: + +| 模式 | 判定 | 适用 | +|------|------|------| +| `USER_ONLY`(starter 默认) | 只比 `userId` | 身份只服务脚本与留痕,同人换身份可互相办理 | +| `STRICT`(framework 默认) | 比 `userId + identity` | 需要把身份当作独立参与人隔离的场景 | + +覆盖范围(不允许再出现散落的双条件判断): + +- 审批动作的参与人校验(`WorkflowStrategyManager#verifyOperator`) +- 撤销、删除、催办、子流程重置的记录归属校验 +- 减签的目标匹配与「不能减自己」判定 +- 加签的「是否已在待办队列中」查重(`USER_ONLY` 下同人换身份视为同一人,拒绝重复加签) +- 提交人 == 审批人的自动通过判定 +- 流程干预人识别(`USER_ONLY` 下同人换身份不算干预) +- 详情页 `currentNodeOperators` 的去重与「排除当前操作人」判定 + +`OperatorManager`、操作者线程缓存、网关缓存的 `(userId, identity)` 键仍保持严格匹配——它们解决的是「取到哪一个带身份的操作者实例」,不是权限问题。 + +留痕口径(`USER_ONLY` 下同人换身份不算「被干预」,因此不会写 `interferedOperator*`): + +| 字段 | 语义 | 写入时机 | +|------|------|----------| +| `currentOperatorId/Name/Identity` | 这条待办的**归属**人(由取人脚本决定) | 记录生成时;办结后**不变** | +| `submitOperatorId/Name/Identity` | **创建这条记录时**的上游提交人 | 记录生成时 | +| `handleOperatorId/Name/Identity` | **本次办理人**——谁、以什么身份办的 | 办结动作(通过 / 拒绝 / 退回 / 转办 / 委派);暂存与抄送刷新不写 | + +因此「办结」不会改写归属身份,只额外留下办理人三元组。 + +> **issue #306 之前的行为**:办理动作不写任何身份字段,最后一步办理人身份**无处落地**——没有下游记录可以承载 +> `submitOperator*`,于是「张三以 `department2` 审批通过」在库里只能看到 `department1`(待办归属)或默认身份。 +> 中间节点只能跳一条到下游记录的 `submitOperatorIdentity` 间接推断,且要求下游是同一个人。 +> 升级后请以 `handleOperator*` 作为「已办是谁办的」的唯一口径。 + +`FlowRecord#markHandleOperator(IFlowOperator)` 由办结动作显式调用,**不在 `update()` 内隐式写入**:`update()` 同时服务于 +暂存(`SaveAction`,`pass=false`)与抄送刷新(`notifyRecord`),隐式写入会把暂存人、抄送接收人误记成办理人。 + +### 4.5 身份写入约束 + +落库前统一经 `OperatorIdentity.of(raw).validate()`: + +| 约束 | 原因 | +|------|------| +| 长度 ≤ 64 | 与 DDL `VARCHAR(64)` 及实体 `@Column(length = 64)` 对齐 | +| 不含 `#` | 与待办合并键的身份后缀分隔符冲突 | +| 不含控制字符 | 内部缓存键以控制字符拼接 | + +读取路径仍用宽松的 `OperatorIdentity.of(raw)`(仅把 `null`/空串归一化为默认身份,不做校验),历史数据不会被拦住;请求入口(REST 的两个 `operatorIdentity` 来源)同样会先经 `validate()` 校验,非法值在入口即被拒绝。 + +人员分配表 `t_flow_operator_assignment` **无需改表**:身份编码在 `operatorIds` JSON 列内。全部为默认身份时保持历史格式 `[1,2,3]`;存在非默认身份时写 `[{"operatorId":2,"identity":"department1"}]`,读取端同时兼容两种格式。 + +### 4.6 身份匹配模式配置(issue #297) + +配置类 `com.codingapi.flow.properties.FlowProperties` 位于 `flow-engine-starter`,启动时由 `OperatorIdentityConfigurer` 写入 framework 的 `OperatorIdentityContext`: + +```properties +# 不限制身份(starter 默认):同一个人换身份仍可办理自己的待办 +codingapi.flow.identity.match-mode=USER_ONLY + +# 严格模式:办理时要求人员与身份都匹配(framework 未配置时的默认值) +# codingapi.flow.identity.match-mode=STRICT +``` + +- 只依赖 `flow-engine-framework`(不使用 starter)的接入方不配置时保持 `STRICT`,升级零感知; +- 通过 starter 接入时默认 `USER_ONLY`,如需恢复 #288 的隔离语义显式配 `STRICT`; +- 模式在启动时生效,不支持运行期热切换(避免同一实例内出现混合判定)。 + +## 5. 兼容性与限制 + +| 项 | 说明 | +|----|------| +| 存量数据 | 新列为 NULL,按默认身份读取,**无需回填** | +| 回滚 | 仅新增 nullable 列,旧版本不映射新列,可直接回滚 | +| 工作流定义 | 与身份无关,导入导出不受影响 | +| 身份长度 | ≤ 64 字符;内部参与人键以控制字符 `U+0001` 拼接(`OperatorKey.KEY_SEPARATOR`,不对业务暴露),身份本身不允许包含 `#`(待办合并键后缀保留字符),入口与落库双处校验 | +| 待办索引 | 实体未声明 `@Index`,大表请按 DDL 脚本手工加索引 | +| 默认取人脚本 | issue #303 起新建节点的默认脚本返回 `OperatorKey`(创建者以发起身份参与);存量流程定义中的旧脚本不受影响,不迁移 | +| 办理人留痕 | issue #306 起 `handle_operator_*` 记录办理人与办理身份;存量记录为空,前端回退到 `current_operator_identity` 展示,行为与升级前一致;如需回填,按 `finish_time` 与下游 `submit_operator_*` 推断,引擎不做自动迁移 | +| 不做的事 | 引擎不建组织模型、不做身份授权校验(「user1 能否以 department1 身份操作」由业务侧保证)、不冻结身份名称 | + +> 身份是一个**不透明字符串**,不要尝试在引擎里比较它的业务含义;需要「部门名称」等展示信息,由宿主维护 `identity → 名称` 的映射自行渲染(框架不提供附加属性字段)。 + +### 5.1 启用身份的时机(重要) + +「存量数据无需回填」只说明**数据**是兼容的,不代表**行为**会自动兼容。在 `STRICT` 模式下,判定与查询口径是 +`(人员id, 身份)` 严格匹配,因此当某个用户开始携带非空身份后,他在存量「默认身份」数据上的表现是: + +| 场景 | 表现 | +|------|------| +| 待办 / 已办 / 抄送列表 | 存量默认身份记录**不再出现在该身份的列表里**(按身份隔离的必然结果) | +| 处置存量待办 | 记录身份为默认身份,当前身份 != 默认身份 → 判权不通过,操作被拒绝 | +| 待办合并 | 旧格式键(无 `#identity`)与新键不互通,不会合并到同一条待办(`STRICT`;`USER_ONLY` 按人合并,不受影响) | + +> 上表是 `STRICT` 模式下的表现。**starter 默认的 `USER_ONLY`(issue #297)下前两条不成立**: +> 列表按人员跨身份返回、判权只比人员,因此打开身份不需要过渡窗口;只有显式配置 `STRICT` +> 或查询传 `identityScope=LOCKED` 时才回到上表口径(详见 4.3 / 4.6)。 + +**在 `STRICT` 模式下不要在全量用户上一次性打开身份。** 推荐三种过渡方式: + +1. **先用 `USER_ONLY`**(starter 默认):列表跨身份、判权只比人员,存量默认身份待办与新建的带身份事项可以同时办理, + 不需要停机或回填;确认业务上确实需要「身份作为独立参与人」时再切 `STRICT`(最省事,推荐); +2. **只对新流程启用**:存量在途流程继续以默认身份办结,新流程带身份发起; +3. **一次性回填**:把运行中流程的 `*_operator_identity` 回填为操作者当期身份,需要停机窗口与全量校验。 + +前端应提供「选择 / 切回默认身份」的入口(示例工程见 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`(移动端)都已打通端到端验证, +**首次启动会自动生成一套演示数据**(`IdentityDemoInitializer`,流程编码 `identity-demo`,已有该流程时跳过,不重复造数): + +| 账号 | 密码 | 待办(审批人 · 身份) | +|------|------|----------------------| +| `user1`(张三) | `123456` | 张三 · 默认身份 / 张三 · `department1` | +| `user2`(李四) | `123456` | 李四 · `department2` | +| `admin` | `admin` | 无(三条流程的发起人) | + +验证步骤(`USER_ONLY` 默认模式): + +1. 启动后端:`cd flow-engine-example && mvn -o spring-boot:run`(端口 8090); +2. 启动前端:`cd flow-frontend && pnpm -F @flow-example/app-pc dev`(PC,代理 `/api` 到 8090) + 或 `pnpm -F @flow-example/app-mobile dev`(移动端,端口 3002); +3. 用 `user1` / `123456` 登录 → 「待办中心」:**2 条待办同时出现**(「身份」列分别为「默认身份」和 `department1`), + 说明列表默认跨身份; +4. 切换操作身份(PC 为右下角「操作身份(演示)」卡片,移动端为待办页顶部「操作身份」横条)→ 页面自动刷新: + **待办条数不变**,因为身份不影响可见范围;仅本次操作携带的身份变化; +5. 用 `department1` 身份去审批那条落在「默认身份」上的待办 → **可以办理**(`USER_ONLY` 只比人员); + 办理后新记录的 `submitOperatorIdentity` 记录本次操作身份; +6. 想验证 #288 的严格隔离语义:配置 `codingapi.flow.identity.match-mode=STRICT`,查询时传 + `identityScope=LOCKED`,此时步骤 4 才会变成「只显示当前身份下的记录」,跨身份办理也会被拒绝 + (`state.operator.notMatch`)。 + +示例的 `User.identity` 是 `@Transient`(运行期身份,不落库),由 `FlowOperatorGateway#get(id, identity)` / +`findByIds(ids, identity)` 返回带身份的副本。真实项目把身份选项换成自己的组织模型即可。 + +### 5.3 常见疑问:为什么「审批人是 admin」却在自己的待办里找不到 + +> 默认 `USER_ONLY` + 跨身份查询下**不会再出现**这个问题,本节保留给 `STRICT` 模式与 `identityScope=LOCKED` 的场景。 + +发起流程时由发起人设定的审批人,目前**只带人员 id、身份为默认身份**(`OperatorKey.ofDefault`), +不会继承发起人当前的身份。于是会出现: + +- 发起人 A 以 `department1` 身份发起,指定审批人 `admin`; +- 该待办落在 **`(admin, 默认身份)`**,而不是 `(admin, department1)`; +- 在 `STRICT` 模式或锁定身份的查询下,如果 `admin` 此时界面上停在 `department1`,就会看不到这条, + 看起来像「待办丢了」。 + +排查顺序: + +1. 看记录行的「身份」列(或 `currentOperatorIdentity` 字段)确认待办实际归属的身份; +2. 去掉 `identityScope=LOCKED`(默认就是跨身份)或把当前身份切回**默认身份**再看待办; +3. 需要「审批人也带身份」的场景,请通过 `OperatorKey.of(operatorId, identity)` 写入分配数据, + `OperatorLoadStrategy` 会按 `(人员id, 身份)` 批量回查。 + +> 前端接入建议:把当前**操作身份**常显在页面上(示例 PC 在右下角卡片、移动端在待办页顶部横条), +> 并且**只把身份参数注入流程引擎接口**(`flow-core` 的 `HttpClient.defaultQueryParamsPathPrefixes` 默认 `/api/`)。 +> 注入到宿主自有接口会污染其查询参数解析,例如基于 `SearchRequest` 的列表接口会抛 +> `Field operatorIdentity not found in class hierarchy`。 + diff --git a/docs/Integration/programmatic-api.md b/docs/Integration/programmatic-api.md index dc969c67..6e08738f 100644 --- a/docs/Integration/programmatic-api.md +++ b/docs/Integration/programmatic-api.md @@ -16,6 +16,8 @@ public class FlowService { void delete(FlowDeleteRequest request); // 删除(仅未流转实例) void urge(FlowUrgeRequest request); // 催办 void resetSubProcess(FlowSubProcessResetRequest request); // 子流程数据重置(独立接口) + long reissue(FlowReissueRequest request); // 已完成流程二次发起 → 新记录 id + FlowForceSyncResult forceSync(FlowForceSyncRequest request); // 运行中实例强制同步最新设计 } ``` @@ -28,6 +30,8 @@ request.setOperatorId(1001L); request.setActionId(startSaveActionId); request.setFormData(Map.of("days", 3)); request.setOperatorSelectMap(Map.of(approvalNodeId, List.of(1002L))); +// 需要「同一人员的多个身份」时改用 operatorSelectOperators(优先于 operatorSelectMap) +// request.setOperatorSelectOperators(Map.of(approvalNodeId, List.of(OperatorKey.of(1002L, "department1")))); long recordId = flowService.create(request); ``` @@ -36,13 +40,14 @@ long recordId = flowService.create(request); ```java FlowActionRequest request = new FlowActionRequest(); request.setRecordId(recordId); -request.setOperatorId(1001L); request.setFormData(Map.of("days", 3)); FlowAdviceBody advice = new FlowAdviceBody(); advice.setActionId(passActionId); advice.setAdvice("同意"); advice.setSignKey("signature"); +advice.setOperatorId(1001L); // 操作人属于 advice,FlowActionRequest 没有该字段 +advice.setOperatorIdentity("department1"); // 可选:本次操作身份(默认身份传空串/null) request.setAdvice(advice); ActionResponse response = flowService.action(request); @@ -101,6 +106,12 @@ Page findAll(PageRequest request); // Page findTodoRecordPage(long userId, PageRequest request); // 待办 Page findNotifyRecordPage(long userId, PageRequest request); // 抄送 Page findDoneRecordPage(long userId, PageRequest request); // 已办 +Page findRunningInstancePage(String workCode, String title, PageRequest request); // 运行中实例(强制同步用) + +// 带身份的重载:均为 default,默认退化为「只按人员」;实现方需覆盖才能让 identityScope=LOCKED 生效 +default Page findTodoRecordPage(long userId, String identity, PageRequest request); +default Page findNotifyRecordPage(long userId, String identity, PageRequest request); +default Page findDoneRecordPage(long userId, String identity, PageRequest request); ``` 生产实现由 `flow-engine-starter-query` 提供(JPA);Mock 由 `FlowRecordQueryMockService` 提供。 diff --git a/docs/Integration/quick-start.md b/docs/Integration/quick-start.md index ff903670..7d060e02 100644 --- a/docs/Integration/quick-start.md +++ b/docs/Integration/quick-start.md @@ -12,28 +12,28 @@ com.codingapi.flow flow-engine-starter - 0.1.0-SNAPSHOT + 0.3.0-SNAPSHOT com.codingapi.flow flow-engine-starter-infra - 0.1.0-SNAPSHOT + 0.3.0-SNAPSHOT com.codingapi.flow flow-engine-starter-api - 0.1.0-SNAPSHOT + 0.3.0-SNAPSHOT com.codingapi.flow flow-engine-starter-query - 0.1.0-SNAPSHOT + 0.3.0-SNAPSHOT ``` @@ -135,13 +135,15 @@ long recordId = flowService.create(request); // 返回首条流程记录 id ## 7. 审批流转 ```java +import com.codingapi.flow.pojo.body.FlowAdviceBody; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.response.ActionResponse; FlowActionRequest actionRequest = new FlowActionRequest(); actionRequest.setRecordId(recordId); -actionRequest.setOperatorId(1001L); -// advice: actionId + advice 文本 + 可选 forwardOperators/backNodeId 等 +actionRequest.setFormData(Map.of("days", 3)); +// 操作人经 advice 传入(FlowActionRequest 本身没有 operatorId 字段) +actionRequest.setAdvice(new FlowAdviceBody(passActionId, "同意", 1001L)); ActionResponse response = flowService.action(actionRequest); ``` diff --git a/docs/Integration/repository-integration.md b/docs/Integration/repository-integration.md index 42dec50f..3ac4f73d 100644 --- a/docs/Integration/repository-integration.md +++ b/docs/Integration/repository-integration.md @@ -42,10 +42,10 @@ public interface IRepositoryHolder { | 实现 | 场景 | 说明 | |---|---|---| -| `RepositoryHolderContext`(`context/` 包,单例) | 生产 | 由 starter 的 `RepositoryHolderContextRegister` 注册 7 个依赖;操作人读取委托 `GatewayContext`;记录保存委托 `FlowRecordService` | +| `RepositoryHolderContext`(`context/` 包,单例) | 生产 | 由 starter 的 `RepositoryHolderContextRegister` 注册 8 个依赖;操作人读取委托 `GatewayContext`;记录保存委托 `FlowRecordService` | | `MockRepositoryHolder`(`mock/` 包) | Mock 沙箱 | 构造时 new 出 9 个内存仓储 + `FlowRecordService`/`WorkflowService`,每个 Mock 实例独立一份(见 [Mock 模式](./mock-mode.md)) | -## 2. 仓储接口(12 个) +## 2. 仓储接口(13 个) 文件:`flow-engine-framework/src/main/java/com/codingapi/flow/repository/` @@ -152,6 +152,14 @@ public interface UrgeIntervalRepository { UrgeInterval getLatest(String processId, long recordId); void save(UrgeInterval urgeInterval); } + +/** 二次发起来源记录(issue #272) */ +public interface FlowReissueRepository { + void save(FlowReissueRecord record); + List findBySourceRecordId(long sourceRecordId); + List findBySourceProcessId(String sourceProcessId); + List findByNewProcessId(String newProcessId); +} ``` ## 3. JPA 实现(`flow-engine-starter-infra`) @@ -161,7 +169,7 @@ public interface UrgeIntervalRepository { - `AutoConfiguration`:`@ConditionalOnClass(name = "org.springframework.data.jpa.repository.JpaRepository")` + `@Import(FlowJpaPackageRegistrar.class)`。 - `FlowJpaPackageRegistrar`(`ImportBeanDefinitionRegistrar`)调用 `AutoConfigurationPackages.register(registry, "com.codingapi.flow.infra")`,让宿主应用的 JPA 扫描覆盖引擎实体与仓储包 —— **业务方无需配置 `@EntityScan`**。 -### 3.2 仓储实现(11 个 Bean) +### 3.2 仓储实现(12 个 Bean) | Bean | 实现类 | |---|---| @@ -176,6 +184,7 @@ public interface UrgeIntervalRepository { | `flowTodoMargeRepository`(bean 名 marge) | `FlowTodoMergeRepositoryImpl` | | `flowOperatorAssignmentRepository` | `FlowOperatorAssignmentRepositoryImpl` | | `subProcessRepository` | `SubProcessRepositoryImpl` | +| `flowReissueRepository` | `FlowReissueRepositoryImpl` | > ⚠️ **infra 不提供** `NodeViewJavaScriptRepository` 与 `FlowOperatorGateway` 的实现,必须由业务方提供。 @@ -234,7 +243,7 @@ public class GroovyScriptRepositoryImpl implements GroovyScriptRepository, Initi ## 6. 替换存储 - **引入 `flow-engine-starter-infra`**:开箱即用(推荐)。 -- **不引入 infra**:自行实现 12 个仓储接口 + `NodeViewJavaScriptRepository` 为 Spring Bean 即可。starter 的 `RepositoryHolderContextRegister` 会自动注入。framework 测试包(`src/test/java/com/codingapi/flow/repository/`)提供了一套内存实现可作参考。 +- **不引入 infra**:自行实现 12 个有 JPA 实现的仓储接口 + `NodeViewJavaScriptRepository`(共 13 个)为 Spring Bean 即可。starter 的 `RepositoryHolderContextRegister` 会自动注入。framework 测试包(`src/test/java/com/codingapi/flow/repository/`)提供了一套内存实现可作参考。 ## 7. 离线/最小装配(脱离 Spring) diff --git a/docs/Integration/rest-api.md b/docs/Integration/rest-api.md index 9a65f134..16803334 100644 --- a/docs/Integration/rest-api.md +++ b/docs/Integration/rest-api.md @@ -17,6 +17,20 @@ operatorId 请求参数 → 存在 → 使用该 id 作为当前操作人 - `mockKey` 经 `MockInstanceFactory.getInstance().getMockInstance(key)` 解析(见 [Mock 模式](./mock-mode.md))。 - `operatorId` 覆盖便于无登录态集成与测试(如 curl 直接带 `?operatorId=1`)。 +`operatorIdentity` 与 `operatorId` 对称(详见 [多身份参与](./operator-identity.md)),解析顺序为 +**请求头 `X-Operator-Identity` → 请求参数 `operatorIdentity` → 登录操作者自身身份**: + +``` +X-Operator-Identity 请求头 或 operatorIdentity 请求参数 + → 存在 → 先校验后作为当前身份(空串 = 显式默认身份) + → 不存在且 operatorId 存在 → 归默认身份(避免人员与身份错配) + → 都不存在 → 取登录操作者自身身份 +``` + +- 命令接口携带它,决定**本次操作身份**(写入 `create_operator_identity` / `submit_operator_identity`)与脚本上下文; +- 查询接口携带它**不改变返回范围**(默认跨身份),需要按身份收敛时另传 `identityScope=LOCKED`(见第 4 节); +- 非法值(超长、含 `#`、含控制字符)在入口即被拒绝。 + ## 2. 命令操作(`/api/cmd/record`) `flow-engine-starter-api/src/main/java/com/codingapi/flow/api/controller/FlowRecordController.java` @@ -28,10 +42,24 @@ operatorId 请求参数 → 存在 → 使用该 id 作为当前操作人 | POST | `/api/cmd/record/create` | `FlowCreateRequest` | `SingleResponse` | 发起流程,返回首条记录 id | | POST | `/api/cmd/record/action` | `FlowActionRequest` | `SingleResponse` | 执行动作(通过/拒绝/加签/减签/委派/退回/转办/自定义/保存) | | POST | `/api/cmd/record/subProcess/reset` | `FlowSubProcessResetRequest` | `Response` | 子流程数据重置(独立接口,需子流程节点开启重置能力) | +| POST | `/api/cmd/record/reissue` | `FlowReissueRequest` | `SingleResponse` | 已完成流程二次发起(仅流程管理员),返回新流程记录 id | +| POST | `/api/cmd/record/forceSync` | `FlowForceSyncRequest` | `SingleResponse` | 运行中实例强制同步最新流程设计(按选中实例换绑运行时快照) | | POST | `/api/cmd/record/urge` | `IdRequest` | `Response` | 催办 | | POST | `/api/cmd/record/revoke` | `IdRequest` | `Response` | 撤销 | | POST | `/api/cmd/record/delete` | `IdRequest` | `Response` | 删除(仅未流转实例,开始节点) | +### 2.1 异常触发(`errorTrigger`)的三种语义 + +`ErrorThrow` 按脚本返回值分流,历史写法保持兼容: + +| 脚本返回 | 类型 | 提交时行为 | +|---|---|---| +| `'节点id'` 或 `[type:'node', node:'节点id']` | NODE | 跳转到指定节点 | +| `[1,2]` / `1` 或 `[type:'operators', operators:[1,2]]` | OPERATORS | 使用指定人员兜底 | +| `[type:'prompt', message:'...']` | PROMPT | 阻断本次操作,抛 `validation.node.operatorEmpty` 并回滚 | + +默认脚本已改为 PROMPT(`ScriptDefaultConstants.SCRIPT_DEFAULT_ERROR_TRIGGER`),文案可由业务方实现 `IScriptRegistry#getErrorTriggerScript` 并调用 `ScriptRegistryContext#setRegistry` 覆盖。 + ## 3. 流程设计(`/api/cmd/workflow`) `flow-engine-starter-api/src/main/java/com/codingapi/flow/api/controller/WorkflowController.java` @@ -61,10 +89,21 @@ operatorId 请求参数 → 存在 → 使用该 id 作为当前操作人 | 方法 | 路径 | 参数 | 响应 | 说明 | |---|---|---|---|---| -| GET | `/api/query/record/list` | `SearchRequest`(current/pageSize) | `MultiResponse` | 全部流程记录(按 id 降序) | -| GET | `/api/query/record/todo` | `SearchRequest` | `MultiResponse` | 我的待办 | -| GET | `/api/query/record/notify` | `SearchRequest` | `MultiResponse` | 我的抄送 | -| GET | `/api/query/record/done` | `SearchRequest` | `MultiResponse` | 我的已办 | +| GET | `/api/query/record/list` | `SearchRequest`(current/pageSize) | `MultiResponse` | 全部流程记录(按 id 降序,不区分人员/身份) | +| GET | `/api/query/record/todo` | `SearchRequest` + 身份参数(见下) | `MultiResponse` | 我的待办(默认跨身份) | +| GET | `/api/query/record/notify` | 同上 | `MultiResponse` | 我的抄送(默认跨身份) | +| GET | `/api/query/record/done` | 同上 | `MultiResponse` | 我的已办(默认跨身份) | +| GET | `/api/query/record/running` | `FlowInstanceQueryRequest`:`workCode`(必填)/ `title` / `current` / `pageSize` | `MultiResponse` | 指定流程编码下运行中的实例(强制同步选择范围,issue #281) | + +查询身份范围(`todo` / `done` / `notify` 通用,issue #297): + +| 参数 | 取值 | 默认 | 说明 | +|---|---|---|---| +| `identityScope` | `ALL` / `LOCKED` | `ALL` | `ALL` 只按人员过滤(跨身份全量);`LOCKED` 追加 `coalesce(identity,'') = :identity` | +| `lockIdentity` | `true` / `false` | `false` | 等价写法,`identityScope` 存在时以 `identityScope` 为准 | +| `operatorIdentity` | 任意合法身份 | 登录操作者身份 | 仅作为身份上下文,`ALL` 下不影响返回结果 | + +非法 `identityScope` 值在入口即报 `validation.parameter.identityScope`,避免拼写错误静默放宽范围。 `FlowRecordQueryService`(`flow-engine-framework/.../query/FlowRecordQueryService.java`): @@ -74,6 +113,12 @@ public interface FlowRecordQueryService { Page findTodoRecordPage(long userId, PageRequest request); Page findNotifyRecordPage(long userId, PageRequest request); Page findDoneRecordPage(long userId, PageRequest request); + + // 带身份的重载:均为 default,默认退化为上面的「只按人员」方法。 + // 需要 identityScope=LOCKED 生效时,实现方必须覆盖。 + default Page findTodoRecordPage(long userId, String identity, PageRequest request) { ... } + default Page findNotifyRecordPage(long userId, String identity, PageRequest request) { ... } + default Page findDoneRecordPage(long userId, String identity, PageRequest request) { ... } } ``` @@ -117,11 +162,15 @@ public interface FlowRecordQueryService { "actionId": "开始节点 SAVE 动作 id", "formData": { "days": 3, "reason": "年假" }, "operatorId": 1001, - "operatorSelectMap": { "approvalNodeId": [1002, 1003] } + "operatorIdentity": "department1", + "operatorSelectMap": { "approvalNodeId": [1002, 1003] }, + "operatorSelectOperators": { "approvalNodeId": [{ "operatorId": 1002, "identity": "department1" }] } } ``` -- `operatorSelectMap`:发起人设定操作人(`OperatorLoadStrategy.INITIATOR_SELECT` 节点),key 为节点 id,value 为操作人 id 列表。 +- `operatorIdentity`:本次发起身份,落库到 `create_operator_identity`(REST 层实际以请求头 `X-Operator-Identity` 优先)。 +- `operatorSelectMap`:发起人设定操作人(`OperatorLoadStrategy.INITIATOR_SELECT` 节点),key 为节点 id,value 为操作人 id 列表(默认身份)。 +- `operatorSelectOperators`:携带身份的同一能力,元素为 `(operatorId, identity)`;**优先于** `operatorSelectMap`,同一人员的两个身份不会被合并。 ### `FlowActionRequest` @@ -133,14 +182,18 @@ public interface FlowRecordQueryService { "actionId": "PASS 动作 id", "advice": "同意", "signKey": "签名", + "operatorId": 1001, + "operatorIdentity": "department1", "forwardOperatorIds": [1002], "backNodeId": "退回目标节点 id", - "operatorSelectMap": {} + "operatorSelectMap": {}, + "operatorSelectOperators": {} } } ``` - `actionId` 决定执行动作(PASS/REJECT/ADD_AUDIT/REDUCE_AUDIT/DELEGATE/RETURN/TRANSFER/CUSTOM/SAVE)。 +- 操作人与身份在 `advice` 内(`operatorId` / `operatorIdentity`),`FlowActionRequest` 顶层没有这两个字段;为兼容旧调用方,REST 层会用 `operatorId` 请求参数与当前身份覆盖 `advice` 中的值。 - `forwardOperatorIds`:加签/减签/委派/转办的目标操作人。 - `backNodeId`:退回动作的目标节点(仅 Start/Approval/Handle 可退回)。 - 减签每次只能处理一条记录,目标必须是该流程实例当前节点的其他待审批人。 @@ -189,25 +242,31 @@ public interface FlowRecordQueryService { | 动作 | `actions`(当前可见) / `actionList`(全部) | | 人员 | `createOperator` / `currentOperator` / `currentNodeOperators` | | 待办与状态 | `todos` / `mergeable` / `flowState` / `recordState` | -| 其他 | `histories` / `nodes` / `revoke` / `urge` / `resetSubProcess` | +| 其他 | `histories` / `nodes` / `backNodes` / `revoke` / `urge` / `resetSubProcess` / `reissue` | | 字段/标记 | 说明 | |---|---| | `currentNodeOperators` | 当前节点实例仍待审批的人员(去重、排除当前操作人、含未激活隐藏记录);减签候选人来源,按单条记录计算,不可跨流程合并 | | `actions[].batchable` | 是否支持合并批量提交(当前仅 `REDUCE_AUDIT` 为 `false`);仅响应附加、不落库;旧服务端缺省按 `true` | | `resetSubProcess` | 当前待办位于开启重置能力且已汇聚完成的子流程锁定节点时为 `true` | +| `reissue` | 已完成流程且当前操作人为流程管理员时为 `true`(可二次发起) | | 合并审批展示 | `mergeable && todos.length > 1` 时隐藏 `batchable=false` 的动作;进入单条流程后按该记录的 `actions` / `currentNodeOperators` 展示并提交 | ### `FlowRecordContent`(列表响应,字段摘要) ``` processId / workflowRuntimeId / workTitle / workCode / nodeId / nodeType / nodeName -title / readTime / currentOperatorId / currentOperatorName -submitOperatorId / submitOperatorName / createTime -createOperatorId / createOperatorName / todoKey / margeCount / mergeable +title / readTime / currentOperatorId / currentOperatorName / currentOperatorIdentity +submitOperatorId / submitOperatorName / submitOperatorIdentity +createOperatorId / createOperatorName / createOperatorIdentity +handleOperatorId / handleOperatorName / handleOperatorIdentity +createTime / todoKey / margeCount / mergeable recordId / timeoutTime / recordState / flowState / notify ``` +> `currentOperator*` 是待办**归属人**(办结后不变);`handleOperator*` 是**实际办理人**(办结动作写入,issue #306)。 +> 已办列表展示「谁以什么身份办理」应优先取 `handleOperator*`,历史数据为空时回退 `currentOperator*`。 + ## 9. 响应包装 | 类 | 结构 | diff --git a/docs/Integration/script-integration.md b/docs/Integration/script-integration.md index ac8f35e6..e4459967 100644 --- a/docs/Integration/script-integration.md +++ b/docs/Integration/script-integration.md @@ -33,7 +33,7 @@ | `TriggerScript` | 触发节点执行副作用(忽略返回值) | `TriggerStrategy` | | `SubProcessScript` | 生成子流程发起请求(返回 `FlowCreateRequest` 或集合) | `SubProcessStrategy` | | `SubProcessResultScript` | 判定子流程是否全部结束 | `SubProcessStrategy` | -| `OperatorLoadScript` | 加载节点操作人(返回用户 id 列表) | `OperatorLoadStrategy` | +| `OperatorLoadScript` | 加载节点操作人(返回 `List` / `List` / `List`,可混用,见下) | `OperatorLoadStrategy` | | `OperatorMatchScript` | 校验发起人是否允许发起流程 | `Workflow.matchCreatedOperator` | | `ErrorTriggerScript` | 匹配不到操作人时的兜底(跳节点 / 兜底操作人) | `ErrorTriggerStrategy` | | `ActionDisplayScript` | 控制动作是否展示 | `ActionDisplay.show` | @@ -73,6 +73,15 @@ request.getCreatedOperator() / getCreatedOperatorId() / getCreatedOperatorName() request.getSubmitOperator() / getSubmitOperatorId() / getSubmitOperatorName() // 流程提交人 request.getCurrentOperator() / getCurrentOperatorId() / getCurrentOperatorName() // 当前审批人 request.findPreviousNodeOperatorIds() // List 上一节点实际审批人 id(排除自动办结) +request.findPreviousNodeOperators() // List 上一节点实际审批人(含身份) + +// 身份(issue #288 / #303) +request.getCreatedOperatorIdentity() // 创建者身份(空串 = 默认身份) +request.getCurrentOperatorIdentity() // 当前操作者身份 +request.getSubmitOperatorIdentity() // 提交人身份 +request.getCreatedOperatorKey() // OperatorKey(人员 + 身份) +request.getCurrentOperatorKey() +request.getSubmitOperatorKey() ``` **节点与流程控制** @@ -113,13 +122,35 @@ $bind.getBean(MyService.class) // 获取 Spring Bean 实例 $bind.getBean("beanName", MyService.class) $bind.getBeans(MyService.class) // 获取全部实现 $bind.getRecordById(recordId) // 按 id 获取流程记录 FlowRecord -$bind.getOperatorById(userId) // 获取操作人 +$bind.getOperatorById(userId) // 获取操作人(默认身份) +$bind.getOperatorByIdentity(userId, identity) // 按身份回查操作人(issue #288) +$bind.getOperatorKey(userId, identity) // 只构造 OperatorKey,不回查(issue #303) $bind.findOperatorsByIds([1L, 2L, 3L]) // 批量获取操作人 ``` `$bind` 的后端是 `FlowScriptContext` 单例,其 `IBeanFactory` 由 starter 的 `FlowScriptContextRegister` 注入(转发到 Spring 容器)。 -### 2.3 `GroovyWorkflowRequest`(发起匹配请求) +### 2.3 取人脚本(`OperatorLoadScript`)的返回形态 + +取人脚本允许三种返回形态,并可在同一列表中混用(逐元素判定,由 `OperatorScriptResultResolver` 统一解析): + +| 形态 | 示例 | 身份来源 | 是否回查 | +|------|------|----------|----------| +| `List` | `return [1, 2]` | 默认身份 | 是(按默认身份批量) | +| `List` | `return [request.getCreatedOperatorKey()]` | `OperatorKey.identity()` | 是(按身份分组批量) | +| `List` | `return [$bind.getOperatorByIdentity(2, 'department1')]` | 对象自带 `getIdentity()` | 否,直接采用 | + +约定: + +- 顶层可写单值(`return request.getCreatedOperatorId()`),按单元素处理; +- 非正数人员 id(存量脚本用 `[-1]` 表示「无审批人」)会被跳过,不抛异常; +- 其他非法元素抛 `FlowValidationException`,消息带脚本类型、元素类型与元素内容; +- 默认模板为 `return [request.getCreatedOperatorKey()]`(创建者以发起身份参与); + 存量流程定义里的旧脚本 `return [request.getCreatedOperatorId()]` 行为不变,仍落默认身份。 + +详见 [多身份参与](./operator-identity.md) 3.4。 + +### 2.4 `GroovyWorkflowRequest`(发起匹配请求) 文件:`flow-engine-framework/.../script/request/GroovyWorkflowRequest.java` @@ -140,9 +171,9 @@ request.getWorkflow() // Workflow 对象(可访问 form/nodes 等) | `SCRIPT_DEFAULT_ACTION_DISPLAY` | 默认显示 | — | `def run(request){ return true; }` | | `SCRIPT_DEFAULT_ACTION_REJECT` | 返回开始节点 | `{"type":"START"}` | `def run(request){ return request.getStartNode().getId(); }` | | `SCRIPT_DEFAULT_CONDITION` | 默认条件(允许执行) | — | `def run(request){ return true; }` | -| `SCRIPT_DEFAULT_ERROR_TRIGGER` | 回退至开始节点 | `{"type":"node","node":"START"}` | `def run(request){ return request.getStartNode().getId(); }` | +| `SCRIPT_DEFAULT_ERROR_TRIGGER` | 异常提示 | `{"type":"prompt"}` | `def run(request){ return [type:'prompt', message:'流程未匹配到审批人,无法继续处理,请联系流程管理员'] }` | | `SCRIPT_DEFAULT_NODE_TITLE` | 你有一条待办 | — | `def run(request){ return '你有一条待办' }` | -| `SCRIPT_DEFAULT_OPERATOR_LOAD` | 流程创建者 | `{"type":"creator"}` | `def run(request){ return [request.getCreatedOperatorId()] }` | +| `SCRIPT_DEFAULT_OPERATOR_LOAD` | 流程创建者 | `{"type":"creator"}` | `def run(request){ return [request.getCreatedOperatorKey()] }` | | `SCRIPT_DEFAULT_OPERATOR_MATCH` | 任意用户 | `{"type":"any"}` | `def run(request){ return true }` | | `SCRIPT_DEFAULT_ROUTER` | 发起节点 | `{"node":"START"}` | `def run(request){ return request.getStartNode().getId(); }` | | `SCRIPT_DEFAULT_SUB_PROCESS` | 创建当前流程 | — | `def run(request){ return request.toCreateRequest() }` | diff --git a/docs/Integration/sql/0.3.0-operator-identity.sql b/docs/Integration/sql/0.3.0-operator-identity.sql new file mode 100644 index 00000000..e0b4b3ac --- /dev/null +++ b/docs/Integration/sql/0.3.0-operator-identity.sql @@ -0,0 +1,97 @@ +-- ============================================================================= +-- 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; + + +-- ----------------------------------------------------------------------------- +-- 1.1 流程记录表:办理人三列(issue #306) +-- ----------------------------------------------------------------------------- +-- 背景:此前记录被办结时不写任何身份字段,current_operator_identity 保留的是「待办归属身份」, +-- submit_operator_identity 只表示「创建该记录时的上游提交人」,最后一步办理人身份因此无处可落。 +-- 语义:handle_operator_* = 本次实际办理人的 (id, 名称, 身份),暂存与抄送刷新不写入。 +-- 兼容:与 current_operator_identity 并存、互不覆盖;历史数据为 NULL,前端可回退到 current_operator_identity。 +ALTER TABLE t_flow_record ADD COLUMN handle_operator_id BIGINT NULL; +ALTER TABLE t_flow_record ADD COLUMN handle_operator_name VARCHAR(255) NULL; +ALTER TABLE t_flow_record ADD COLUMN handle_operator_identity VARCHAR(64) NULL; + + +-- ----------------------------------------------------------------------------- +-- 2. 待办表:发起 / 提交 / 当前 三组操作者的身份 +-- ----------------------------------------------------------------------------- +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; + + +-- ----------------------------------------------------------------------------- +-- 2.1 人员分配表:无需改表(issue #288 衍生 / #292) +-- ----------------------------------------------------------------------------- +-- 「发起人设定 / 审批人设定」节点的分配关系存在 t_flow_operator_assignment.operator_ids (JSON) 中。 +-- 身份编码在该 JSON 内部完成,无需新增列、无需回填: +-- 全部默认身份 -> [1,2,3] (保持历史格式) +-- 存在指定身份 -> [{"operatorId":2,"identity":"department1"}] +-- 读取端同时兼容两种格式;存量环境不执行本段语句即可正常升级。 + + +-- ----------------------------------------------------------------------------- +-- 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..46987443 100644 --- a/docs/Integration/user-integration.md +++ b/docs/Integration/user-integration.md @@ -14,12 +14,27 @@ 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); + + /** 按 (ids, identity) 批量取用户,default 退化为 findByIds(ids);多身份场景需一并覆盖 */ + default List findByIds(List ids, String identity) { + return findByIds(ids); + } } ``` 引擎所有「按 id 取用户 / 批量取用户」的请求都汇聚到这个接口。**框架不提供默认实现**(`flow-engine-starter-infra` 也不提供),必须由业务方提供一个 Spring Bean。 +> 同一人员以多个身份参与流程时(例如同时隶属两个部门),需要覆盖 `get(long, String)`; +> 流程树、人员设定等批量路径还需要覆盖 `findByIds(List, String)`,只覆盖单条会让批量路径退化为默认身份。 +> 详见 [多身份参与](./operator-identity.md) 3.2。 + ### 1.2 `IFlowOperator`(流程操作人) 文件:`flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java` @@ -36,12 +51,18 @@ public interface IFlowOperator extends IUser { String getName(); // 用户名称 boolean isFlowManager(); // 流程管理员可强制干预流程 IFlowOperator forwardOperator(GroovyScriptRequest request); // 转交审批人;无需转交返回 null + + /** 身份标识,空串表示默认身份(default 方法,存量实现无需改动) */ + default String getIdentity() { + return OperatorIdentity.DEFAULT.value(); + } } ``` 要点: - 父接口 `IUser`(来自外部依赖 `com.codingapi.springboot:springboot-starter`)为**空标记接口**,无需实现任何方法。 +- `getIdentity()` 是 `default` 方法,返回 `null` 或空串都表示默认身份;多身份场景需覆盖它(见 [多身份参与](./operator-identity.md))。 - `isFlowManager()` 返回 `true` 表示流程管理员:开启干预策略时,管理员可强制审批他人待办(见 [扩展点](./extension-points.md#工作流策略))。 - `forwardOperator(request)` 实现「转交审批」(转办链):返回转交目标操作人,无需转交时返回 `null`。引擎在审批时调用 `session.loadFinalForwardOperator(...)` 递归解析转交链。 @@ -64,7 +85,8 @@ public class GatewayContext { ``` - **注入方式**:`GatewayContext.getInstance().setFlowOperatorGateway(bean)`,由 starter 的 `GatewayContextRegister`(`InitializingBean`)在启动时执行。 -- **线程缓存** `FlowOperatorLocalThreadCache`(`flow-engine-framework/.../cache/FlowOperatorLocalThreadCache.java`):`ThreadLocal>`,未命中时调用网关并回写;`find` 会过滤 null/<=0 的 id、去重、保序返回(保证多人审批顺序稳定)。`FlowService` 每个操作入口都会 `clear()` 该缓存。 +- **线程缓存** `FlowOperatorLocalThreadCache`(`flow-engine-framework/.../cache/FlowOperatorLocalThreadCache.java`):`ThreadLocal>`,未命中时调用网关并回写;`find` 会过滤 null/<=0 的 id、去重、保序返回(保证多人审批顺序稳定)。缓存键由 `OperatorKey#key()` 生成,**含身份**。`FlowService` 每个操作入口都会 `clear()` 该缓存。 +- **带身份的读取**:`GatewayContext.getFlowOperator(userId, identity)` / `findByIds(ids, identity)` 是新增重载;批量结果身份不符时会逐条回退单条按身份回查(见 [多身份参与](./operator-identity.md) 3.2)。 ## 3. 集成示例(完整可运行) diff --git a/docs/capabilities/flow-engine-framework/flow-service.md b/docs/capabilities/flow-engine-framework/flow-service.md index 487843ae..7aad24a5 100644 --- a/docs/capabilities/flow-engine-framework/flow-service.md +++ b/docs/capabilities/flow-engine-framework/flow-service.md @@ -21,6 +21,8 @@ symbols: - FlowDeleteService - FlowSubProcessResetService - FlowSubProcessResultService + - FlowReissueService + - FlowForceSyncService - SubProcessSessionFactory - OperatorAssignmentService - WorkflowGroovyScriptUtils @@ -31,7 +33,7 @@ content_hash: 48847288af1a4551b8327e398d01a8ec4de643dce1c049b90dcdc8ad0134df3b 提供流程引擎的业务服务层,将复杂的流程操作封装为高内聚的服务接口,解决以下问题: -- **流程操作入口**:`FlowService` 作为流程审批操作的统一入口,支持创建、审批、撤销、删除、催办、子流程重置 +- **流程操作入口**:`FlowService` 作为流程审批操作的统一入口,支持创建、审批、撤销、删除、催办、子流程重置、二次发起、强制同步 - **流程设计管理**:`WorkflowService` 管理流程定义的 CRUD 和版本操作 - **职责分离**:每种操作由独立的 Service 实现(如 `FlowActionService`、`FlowCreateService`),保持单一职责 - **线程安全**:每次操作前通过 `FlowOperatorLocalThreadCache.clear()` 与 `FlowRuntimeScriptLocalCache.clear()` 清理线程缓存 @@ -50,6 +52,8 @@ content_hash: 48847288af1a4551b8327e398d01a8ec4de643dce1c049b90dcdc8ad0134df3b | `detail(FlowDetailRequest)` | 查询流程详情 | | `processNodes(FlowProcessNodeRequest)` | 查询流程节点记录 | | `resetSubProcess(FlowSubProcessResetRequest)` | 子流程数据重置(独立接口,REST 端点 `POST /api/cmd/record/subProcess/reset`) | +| `reissue(FlowReissueRequest)` | 已完成流程二次发起(仅流程管理员,REST 端点 `POST /api/cmd/record/reissue`),返回新流程记录 id | +| `forceSync(FlowForceSyncRequest)` | 运行中实例强制同步最新流程设计(REST 端点 `POST /api/cmd/record/forceSync`),返回每个实例的同步结果 | ### WorkflowService — 流程设计管理 @@ -74,8 +78,10 @@ content_hash: 48847288af1a4551b8327e398d01a8ec4de643dce1c049b90dcdc8ad0134df3b | `FlowRecordSaveService` | 保存流程记录和待办合并关系,并按实际落库记录推送 `FlowRecordSaveEvent`(issue #280) | | `FlowSubProcessResetService` | 子流程数据重置(旧聚合组作废、实例继承/重建) | | `FlowSubProcessResultService` | 子流程完成后回写父流程并生成待办/已办 | +| `FlowReissueService` | 已完成流程二次发起:复制源流程表单与人员设定,新流程停在开始节点 | +| `FlowForceSyncService` | 运行中实例强制同步最新流程设计:校验结构一致性后换绑运行时快照 | | `SubProcessSessionFactory` | 子流程会话构建(按聚合组/实例定位记录) | -| `OperatorAssignmentService` | 操作者分配服务 | +| `OperatorAssignmentService` | 操作者分配服务(实例对象,构造注入 `FlowSession`,提供 `hasAssignment` / `assign`) | ## 使用实例 diff --git a/docs/capabilities/flow-engine-framework/gateway-context.md b/docs/capabilities/flow-engine-framework/gateway-context.md index 34dae184..365ad028 100644 --- a/docs/capabilities/flow-engine-framework/gateway-context.md +++ b/docs/capabilities/flow-engine-framework/gateway-context.md @@ -42,6 +42,10 @@ public interface FlowOperatorGateway { } ``` +> 多身份场景还需覆盖两个 `default` 重载 `get(long, String)` 与 `findByIds(List, String)`; +> 不覆盖时它们退化为忽略身份的上面两个方法,请求里声明的身份不会写入记录。 +> 详见 [多身份参与](../../Integration/operator-identity.md) 3.2。 + ### 缓存机制 - 每次 `FlowService` 操作前调用 `FlowOperatorLocalThreadCache.clear()` 清理缓存 diff --git a/docs/capabilities/flow-engine-framework/operator-assignment.md b/docs/capabilities/flow-engine-framework/operator-assignment.md index 8e1d7156..50333a1f 100644 --- a/docs/capabilities/flow-engine-framework/operator-assignment.md +++ b/docs/capabilities/flow-engine-framework/operator-assignment.md @@ -1,13 +1,14 @@ --- name: flow-engine-framework/operator-assignment module: flow-engine-framework -description: 操作人分配能力,支持发起人/审批人设定的分配校验与落库 +description: 操作人分配能力,支持发起人/审批人设定的分配校验与落库(含身份) status: 已实现 scope: 后端 source: 项目自有 import: "com.codingapi.flow:flow-engine-framework" symbols: - OperatorAssignmentService + - OperatorSelections - FlowOperatorAssignmentRepository content_hash: f502894911c6aa57e630d8ae047de982d1b7833e635de334e5abafb33b73a48e --- @@ -16,9 +17,11 @@ content_hash: f502894911c6aa57e630d8ae047de982d1b7833e635de334e5abafb33b73a48e 提供操作人分配(发起人设定 / 审批人设定)的校验与持久化能力: -- **范围校验**:目标节点配置了可选人员范围时,校验所选人员是否全部落在范围内,越界抛出 `FlowValidationException.operatorOutOfRange` -- **分配落库**:校验通过后按流程实例与节点保存选定的操作人 ID 列表 +- **已设定判定**:`hasAssignment(nodeId)` 汇总三种来源(本次意见的 `operatorSelectMap`、本次意见的 `operatorSelectOperators`、此前已落库的分配),避免流程在开始节点反复要求选人 +- **范围与人数校验**:所选人数超过 `maxOperatorCount` 抛 `FlowValidationException.operatorCountExceeded`;目标节点配置了可选人员范围时,越界抛 `operatorOutOfRange`(范围按人员 id 判定,不区分身份) +- **分配落库**:按流程实例与节点保存选定的参与人(人员 id + 身份) - **幂等保存**:同一节点重复设定时覆盖旧分配 +- **两种表达形式的优先级**:`OperatorSelections` 收口「携带身份的分配优先于仅人员 id 的分配」,调用方不再各自写 `if (keys != null) ...` ## 如何使用 @@ -26,20 +29,34 @@ content_hash: f502894911c6aa57e630d8ae047de982d1b7833e635de334e5abafb33b73a48e | 组件 | 职责 | |------|------| -| `OperatorAssignmentService` | 静态服务,提供 `validateAndSave(baseSession, processId, operatorSelectMap)` 校验并保存操作人分配 | -| `FlowOperatorAssignmentRepository` | 操作人分配仓储接口,定义 `save(processId, nodeId, operatorIds)` 与 `findOperatorIds(processId, nodeId)` | -| `FlowValidationException.operatorOutOfRange` | 所选人员越界时抛出的异常 | +| `OperatorAssignmentService` | 实例对象(构造注入 `FlowSession`),提供 `hasAssignment(nodeId)` 与 `assign(processId, selections)` | +| `OperatorSelections` | 操作人选择集合(节点 id → `List`),`of(byOperators, byOperatorIds)` 归并两种请求表达 | +| `FlowOperatorAssignmentRepository` | 分配仓储:`save` / `findOperatorIds`(仅人员)+ `saveOperators` / `findOperators`(含身份,default 退化) | +| `IRepositoryHolder` | 对外业务方法:`saveOperatorAssignments(processId, nodeId, List)` / `findAssignedOperators(processId, nodeId)` | ### 校验规则 -- `operatorSelectMap` 为空时直接返回,不做处理 -- 通过 `node.strategyManager().loadOperatorRange(session)` 加载节点可选人员范围;范围为空(未配置脚本或脚本执行结果为空)表示不限范围,跳过校验 -- 范围非空时,所选人员必须全部落在范围内,否则抛出异常 +- 选择集合为空时直接返回,不做处理 +- 同一人员的两个身份是两项参与人,不去重合并;完全相同的 `(人员id, 身份)` 才去重 +- 人数上限:`maxOperatorCount >= 0` 时校验,`-1` 表示不限制 +- 范围校验:`node.strategyManager().loadOperatorRange(session)` 为空表示不限范围;非空时按 `operatorId` 判定是否在范围内 ## 使用实例 ```java -// 在 FlowCreateService / FlowActionService 中调用 -Map> operatorSelectMap = request.getOperatorSelectMap(); -OperatorAssignmentService.validateAndSave(baseSession, processId, operatorSelectMap); -``` \ No newline at end of file +// 发起路径(FlowCreateService):请求字段 → 选择集合 +OperatorSelections selections = OperatorSelections.of( + request.getOperatorSelectOperators(), // Map>,优先 + request.getOperatorSelectMap()); // Map>,按默认身份 +new OperatorAssignmentService(session).assign(processId, selections); + +// 办理路径(FlowActionService):选择集合来自本次审批意见 +new OperatorAssignmentService(session).assign(flowRecord.getProcessId(), + OperatorSelections.of(advice.getOperatorSelectOperators(), advice.getOperatorSelectMap())); + +// 判定节点是否已设定(PassAction / InitiatorSelectNodeService) +boolean assigned = new OperatorAssignmentService(flowSession).hasAssignment(node.getId()); +``` + +> 该类在 issue #311 P4 由「静态工具类 + `validateAndSave(baseSession, processId, operatorSelectMap)`」改为构造注入的对象: +> 会话是它唯一的依赖,`processId` 与选择集合随调用传入。旧写法已不存在。 diff --git a/docs/capabilities/flow-engine-framework/operator-identity.md b/docs/capabilities/flow-engine-framework/operator-identity.md new file mode 100644 index 00000000..8122fee7 --- /dev/null +++ b/docs/capabilities/flow-engine-framework/operator-identity.md @@ -0,0 +1,80 @@ +# 多身份参与模型(Operator Identity) + +> 模块:flow-engine-framework · 包:`com.codingapi.flow.operator` 及其调用方 +> 前置:[模型设计三层法](../../conventions/design/model-design.md) +> 本文只回答「身份这件事在代码里由谁负责」;接入步骤、请求头、落库列、模式配置见 [集成说明](../../Integration/operator-identity.md)。 + +## 解决什么问题 + +一个人员可能同时隶属多个部门或身兼多个岗位,在不同事项上以不同身份参与流程。 +引擎不建组织模型、不解释身份语义,只做四件事:**透传、存储、比较、留给脚本使用**。 + +身份取值是一个**不透明字符串**,`null` 与空串等价,均表示默认身份。 +默认身份下引擎行为与单身份版本完全一致。 + +## 模型构成 + +包 `com.codingapi.flow.operator` 内为身份的全部模型;`OperatorManager` 与 `TodoMergeKey` 因分别承担「人员集合」与「待办合并键」职责,放在各自所属的包。 + +| 类型 | 位置 | 职责 | 公有入口 | +|---|---|---|---| +| `OperatorIdentity` | `operator` | 身份值对象(不可变),负责归一化与合法性校验 | `of(String)` / `of(IFlowOperator)`、`value()`、`isDefault()`、`validate()`、`same(OperatorIdentity)` | +| `OperatorKey` | `operator` | 参与人标识值对象 `(人员id, 身份)`,参与人概念的**唯一载体** | `of(long, String)`、`ofDefault(long)`、`of(IFlowOperator)`、`matches(OperatorKey, OperatorIdentityMatchMode)`、`identityEquals(String)`、`key()`、`key(OperatorIdentityMatchMode)` | +| `OperatorIdentityMatchMode` | `operator` | 匹配模式策略,自己回答「是否同一人」与「身份是否区分参与人」 | `match(OperatorKey, OperatorKey)`、`identityDistinguishes()`、`parse(String)` | +| `OperatorIdentityContext` | `operator` | 全局模式持有者(可变单例),把配置注入框架 | `getInstance()`、`use(mode)`、`matchMode()`、`matches(OperatorKey, OperatorKey)`、`sameOperator(IFlowOperator, IFlowOperator)` | +| `OperatorSelections` | `operator` | 操作人选择集合,收口「节点 → 参与人列表」并统一「带身份优先于仅 id」 | `of(...)`、`empty()`、`isEmpty()`、`hasSelection(String)`、`nodeIds()`、`of(String)` | +| `IFlowOperator` | `operator` | 流程参与用户,身份来源为 `getIdentity()`(default 方法,返回默认身份) | `getUserId()`、`getName()`、`isFlowManager()`、`forwardOperator(...)`、`getIdentity()` | +| `OperatorManager` | `manager` | 参与人集合,回答「这个人在不在这批人里」 | `new OperatorManager(List)`、`match(IFlowOperator)`、`isEmpty()` | +| `TodoMergeKey` | `record` | 待办合并复合键(参与人 + 运行时 + 节点),键格式的唯一定义点 | `of(...)`、`value()` | +| `OperatorIdentityHeader` | `flow-engine-starter-api` 的 `api` 包 | 请求头契约与「头优先于 query」解析,属接入层 | `resolve(...)` 与三个头名常量 | +| `OperatorIdentityWarnLog` | `diagnostic` | 身份未透传时的告警去重输出 | `getInstance()`、`warnOnce(...)` | + +## 两个唯一真源 + +身份体系只有两个必须集中的判断点,其余能力都建立在它们之上: + +| 判断 | 唯一入口 | 禁止的替代写法 | +|---|---|---| +| 两个参与人是否为同一人 | `OperatorKey#matches(other, mode)` | `a.getUserId() == b.getUserId() && a.getIdentity().equals(b.getIdentity())` | +| 参与人键(缓存键 / Map 键 / 去重键) | `OperatorKey#key(mode)` | 自行 `id + 分隔符 + identity` | + +待办合并键是**复合键**(参与人 + 运行时 + 节点),由 `TodoMergeKey#value()` 独立回答,不复用 `OperatorKey#key()`,但同样只允许一个定义点。 + +## 匹配模式 + +| 模式 | 判定 | 身份是否区分参与人 | 默认场景 | +|---|---|---|---| +| `STRICT` | 人员 + 身份都一致 | 是(键带身份后缀) | 只依赖 framework 时的默认值 | +| `USER_ONLY` | 只比人员 | 否(键不带后缀) | 通过 starter 接入时的默认值 | + +模式是**策略**,不是分支条件:新增一种模式只需实现枚举常量,不得在使用方写 `if (mode == ...)`。 + +模式只能改变**判定**,不能改变**数据格式**。键格式(是否追加身份后缀)只允许在键模型内部依据 `identityDistinguishes()` 决定,业务类不得在方法体里读 `matchMode()` 后自己拼字符串。 + +## 设计约束 + +改动本模型或其调用方时必须满足以下四条: + +1. **成对传递**:新增或修改的公开方法签名不得出现 `(long operatorId, String identity)`,一律传 `OperatorKey`。拆开传会让「一个人」在签名层面消失,调用方随时可能漏传身份。 +2. **判定收口**:任何「这个人是不是那条记录上的人」的判断必须经过 `OperatorKey#matches`,或接受 `IFlowOperator` 的 `OperatorIdentityContext#sameOperator` 重载。 +3. **键收口**:缓存键、Map 键、去重键只由 `OperatorKey#key(mode)` 产生;分隔符常量只允许一处声明;待办合并键只由 `TodoMergeKey#value()` 产生。 +4. **分层**:身份解析属接入层(HTTP 头约定),不得放进领域包;告警去重属可观测性,放在 `diagnostic` 包。领域包不得感知 HTTP。 + +身份比较恒为**严格口径**的地方:`OperatorManager`、操作者线程缓存、网关缓存的键。它们解决的是「取到哪一个带身份的操作者实例」,与「谁有权办理」是两个问题,不受匹配模式放宽。 + +## 相关测试 + +| 测试类 | 覆盖 | +|---|---| +| `OperatorKeyTest` | 归一化、相等、`matches`、`key()` 格式 | +| `OperatorIdentityContextTest` | 模式切换与判定 | +| `OperatorSelectionsTest` | 「带身份优先于仅 id」的收口 | +| `TodoMergeKeyTest` | 合并键在两种模式下的格式 | +| `OperatorManagerTest` | 参与人集合匹配 | +| `OperatorIdentityWarnLogTest` | 告警去重归属实例 | + +## 关联 + +- 接入与行为口径:[集成说明](../../Integration/operator-identity.md) +- 事务与脚本身份函数:[脚本集成](../../Integration/script-integration.md) +- 改写本模型的前置规范:[模型设计三层法](../../conventions/design/model-design.md) diff --git a/docs/capabilities/flow-engine-framework/repository.md b/docs/capabilities/flow-engine-framework/repository.md index 8677a110..5de5b04a 100644 --- a/docs/capabilities/flow-engine-framework/repository.md +++ b/docs/capabilities/flow-engine-framework/repository.md @@ -18,6 +18,7 @@ symbols: - DelayTaskRepository - UrgeIntervalRepository - NodeViewJavaScriptRepository + - FlowReissueRepository - IRepositoryHolder content_hash: 057987ed8ab209759993dfc2792699ccdcd110a1c291ffd49fea7af09e1af895 --- @@ -48,6 +49,7 @@ content_hash: 057987ed8ab209759993dfc2792699ccdcd110a1c291ffd49fea7af09e1af895 | `UrgeIntervalRepository` | 催办间隔配置的 CRUD | | `NodeViewJavaScriptRepository` | 节点视图 JS 脚本的 CRUD | | `SubProcessRepository` | 子流程执行记录的 CRUD(子流程聚合持久化依赖) | +| `FlowReissueRepository` | 二次发起来源记录与关系查询(issue #272) | ### IRepositoryHolder diff --git a/docs/capabilities/flow-engine-framework/script.md b/docs/capabilities/flow-engine-framework/script.md index 0c896465..2526a4c3 100644 --- a/docs/capabilities/flow-engine-framework/script.md +++ b/docs/capabilities/flow-engine-framework/script.md @@ -73,6 +73,19 @@ ScriptRegistryContext.getInstance().setRegistry(new IScriptRegistry() { }); ``` +### 异常触发脚本(errorTrigger)返回格式 + +节点取人为空时执行,按返回值分流为三种处理方式(前两种为历史能力,`prompt` 为 issue #296 新增): + +| 返回值 | 处理方式 | 说明 | +|---|---|---| +| `[type:'prompt', message:'...']` | 异常提示 | 阻断本次操作并展示文案,事务回滚;默认脚本即此形式 | +| `[type:'node', node:'节点id']` | 指定节点 | 跳转到指定节点继续办理 | +| `[type:'operators', operators:[1,2]]` | 指定人员 | 使用给定人员兜底,继续生成记录 | +| `'节点id'` / `[1,2]` / `1` | 兼容写法 | 依次等价于 `node` / `operators` / 单个人员,历史脚本无需改动 | + +Map 未声明 `type` 时按 `message` → `node` → `operators` 的顺序推断。`@SCRIPT_META` 应与返回类型一致(如 `{"type":"prompt"}`),设计器据此渲染配置面板;`getErrorTriggerScript()` 的默认实现返回「异常提示」,业务方可通过 `ScriptRegistryContext#setRegistry` 整体覆盖文案或改为其他处理方式。 + ### 脚本执行上下文 `FlowScriptContext` 承载脚本的 `$bind` 上下文,内部持有 `IBeanFactory` 字段并委托其实现(具体实现由 starter 的 `FlowScriptContextRegister` 装配),供 Groovy 脚本以 `$bind.getBean(...)`、`$bind.getRecordById(...)`、`$bind.getOperatorById(...)` 等方式访问 Spring 容器中的 Bean、流程记录与操作者信息;脚本的实际执行由 `FlowScriptRuntimeContext` 结合 spring-boot 的 `GroovyScript` 完成。 diff --git a/docs/capabilities/flow-engine-starter/auto-configuration.md b/docs/capabilities/flow-engine-starter/auto-configuration.md index 547e5adf..5adb655b 100644 --- a/docs/capabilities/flow-engine-starter/auto-configuration.md +++ b/docs/capabilities/flow-engine-starter/auto-configuration.md @@ -35,7 +35,7 @@ content_hash: cead1cab34f0a1357e650ae764b4f008247c530ad9b4eff0cd0ffeb9c93d44e3 | 模块 | AutoConfiguration 职责 | |------|----------------------| -| `flow-engine-starter` | 注册 8 个 Bean:`NodeViewJavaScriptCacheContextRegister`、`FlowDelayTaskRunner`、`GatewayContextRegister`、`FlowScriptContextRegister`、`RepositoryHolderContextRegister`、`FlowRecordService`、`WorkflowService`、`FlowService` | +| `flow-engine-starter` | 注册 10 个 Bean:`OperatorIdentityConfigurer`、`NodeViewJavaScriptCacheContextRegister`、`FlowDelayTaskRunner`、`GatewayContextRegister`、`FlowScriptContextRegister`、`RepositoryHolderContextRegister`、`SpringFlowEventPublisher`、`FlowRecordService`、`WorkflowService`、`FlowService` | | `flow-engine-starter-api` | 注册 REST Controller(`WorkflowController` 等) | | `flow-engine-starter-infra` | 注册 JPA Repository 实现、数据库实体 | | `flow-engine-starter-query` | 注册查询服务(`FlowRecordQueryService` 等) | diff --git a/docs/capabilities/index.md b/docs/capabilities/index.md index e6b15be8..20fa5e71 100644 --- a/docs/capabilities/index.md +++ b/docs/capabilities/index.md @@ -17,6 +17,7 @@ | [flow-engine-framework/node](./flow-engine-framework/node.md) | flow-engine-framework | 流程节点体系,包含 19 种节点类型、节点接口层次和节点工厂 | 后端 | 项目自有 | | [flow-engine-framework/node-view-javascript](./flow-engine-framework/node-view-javascript.md) | flow-engine-framework | 节点视图脚本能力,支持视图脚本的缓存、保存与查询(含缓存自动清理) | 后端 | 项目自有 | | [flow-engine-framework/operator-assignment](./flow-engine-framework/operator-assignment.md) | flow-engine-framework | 操作人分配能力,支持发起人/审批人设定的分配校验与落库 | 后端 | 项目自有 | +| [flow-engine-framework/operator-identity](./flow-engine-framework/operator-identity.md) | flow-engine-framework | 多身份参与模型,身份值对象、参与人标识、匹配模式策略与两个唯一真源(相等判定、键生成) | 后端 | 项目自有 | | [flow-engine-framework/repository](./flow-engine-framework/repository.md) | flow-engine-framework | 仓储抽象层,定义流程引擎的持久化接口和仓储持有者上下文 | 后端 | 项目自有 | | [flow-engine-framework/script](./flow-engine-framework/script.md) | flow-engine-framework | Groovy 脚本运行时,包含脚本注册表、脚本类型封装和脚本执行上下文 | 后端 | 项目自有 | | [flow-engine-framework/sub-process](./flow-engine-framework/sub-process.md) | flow-engine-framework | 子流程聚合执行能力,支持批量创建、主流程等待、脚本结果判定、异常跳转与数据重置(退回重走) | 后端 | 项目自有 | @@ -31,4 +32,4 @@ --- -**统计**: 共 22 篇 — 已实现 22 / 计划中 0 / 已废弃 0 +**统计**: 共 23 篇 — 已实现 23 / 计划中 0 / 已废弃 0 diff --git a/docs/capabilities/springboot/ioc.md b/docs/capabilities/springboot/ioc.md index f3e68471..07a0bfad 100644 --- a/docs/capabilities/springboot/ioc.md +++ b/docs/capabilities/springboot/ioc.md @@ -16,7 +16,7 @@ framework_version: "3.5.9" - **依赖注入**:容器管理 Bean 之间的依赖关系。本项目不使用 `@Autowired` / `@Inject` 注解,统一通过 Lombok `@AllArgsConstructor` 构造器注入(如 `WorkflowController`、`WorkflowService`、各 `RepositoryImpl`) - **Bean 生命周期管理**:容器统一管理 Bean 的创建、初始化和销毁 - **AOP 支持**:框架提供 `@Aspect` 横切关注点能力(本项目未使用) -- **事件发布**:不使用 Spring `ApplicationEventPublisher`,事件系统为自研 `IFlowEvent` + `EventPusher`(`flow-engine-framework/event/` 下 9 种事件类,操作完成后通过 `EventPusher.push(event)` 推送) +- **事件发布**:不使用 Spring `ApplicationEventPublisher`,事件系统为自研 `IFlowEvent` + `FlowEventPublisher`(`flow-engine-framework/event/` 下 12 个事件类,操作完成后通过 `FlowEventPublisher.push(event)` 推送;引入 starter 时由 `SpringFlowEventPublisher` 在事务提交后按流程分区串行投递) - **自动配置**:通过 `@Configuration` + `@Conditional` 实现条件化 Bean 注册 ## 如何使用 diff --git a/docs/conventions/design/model-design.md b/docs/conventions/design/model-design.md new file mode 100644 index 00000000..d023648e --- /dev/null +++ b/docs/conventions/design/model-design.md @@ -0,0 +1,453 @@ +--- +name: design/model-design +module: design +description: 模型设计三层法 — 职责 → 抽象 → 实现;垂直按 DDD 分层(业务/数据/技术),水平按包/类/方法递归;以易维护与可验证为验收 +status: 已实现 +scope: 通用 +source: 项目自有 +--- + +## 为什么要有这套约束 + +一个有生命力的软件,成本不在写,在**持续维护**。而持续维护只靠两套机制撑着: + +**一、可验证性 —— 先对,再好** + +所有代码先是对的,然后再追求好的;反过来不成立。架构再漂亮,业务算错了就是负资产。这是 TDD 的机制依据:先写失败用例(证明问题存在),再写实现(证明问题解决),最后才谈结构。 + +**二、易维护性 —— 读得懂 + 改得小** + +- **读得懂**:调用方只读一个方法签名就能用对,不需要通读整个类; +- **改得小**:新增能力时**加代码**,而不是**改老代码**(开闭原则)。 + +两者的关系不是并列:**可验证性是底线,易维护性是上限。** 冲突时先保正确性——没有用例守护的「漂亮重构」,是在拿线上功能赌审美。 + +三层设计正好各服务一个目标,这也是为什么顺序不能颠倒: + +| 设计层 | 服务的目标 | 失效时的症状 | +|---|---|---| +| 职责 | 读得懂 | 类名说不清它干什么,看代码要读到最后一行 | +| 抽象 | 改得小 | 每加一种情况都改主流程,回归面积越来越大 | +| 实现与命名 | 可验证 | 依赖无法替换,测一个分支要起整套环境 | + +第三条最容易被忽略:**能不能测,往往不是测试写得好不好,而是依赖有没有被注入。** 静态工具类把依赖藏在参数甚至方法体里,测试就只能构造整个世界。 + +顺序反过来——先想好「这里用个策略模式」再去找职责——只会得到为了模式而模式的空壳。 + +## 两个正交维度 + +模型设计的定位是二维的,缺任何一维都定不准一个类: + +``` + 垂直:DDD 分层(谁不许碰谁) + 业务 Domain + 数据 Repository + 技术细节 Infrastructure + ▲ + │ 每一格内部,都按「职责 → 抽象 → 实现」三步走 + │ + 水平:尺度 包 ──────────┼────────── 类 ────────── 方法 +``` + +### 垂直:业务 / 数据 / 技术细节 + +DDD 的核心不是聚合根、不是值对象,是**分层**:把业务、数据、技术细节分开,各自只对自己负责。业务整合完全通过模型完成,数据是 Repository 的事,技术细节落在 infrastructure。 + +| 层 | 职责 | 本仓库对应 | 禁止 | +|---|---|---|---| +| 业务(Domain) | 业务规则与状态流转,纯模型 | `node` `action` `strategy` `workflow` `record` `operator` `form` `service`(编排)`event` | JPA 注解、SQL、HTTP、脚本引擎调用 | +| 数据(Repository) | 领域对象的持久化与查询 | `repository`(接口)+ `flow-engine-starter-infra`(JPA 实现、Convertor) | 承载业务判断 | +| 技术细节(Infrastructure) | 框架接入、序列化、脚本运行时、REST | `flow-engine-starter`(自动配置)、`starter-api`、`starter-query`、`script/runtime`、`javscript` | 被 Domain 反向依赖 | + +判据:**换掉一个技术选型(ORM、脚本引擎、Web 框架),业务模型应当零改动。** 做不到,说明某一层已经把另一层焊死了。 + +### 三处已知渗透(登记,不要求立刻改) + +1. **`IRepositoryHolder` 一个端口暴露了四种角色**:`XxxRepository`(数据)、`FlowService` / `FlowRecordService` / `WorkflowService`(业务编排)、`FlowOperatorGateway`(外部能力)、`createDelayTriggerService(...)`(工厂方法)。调用方从类型上已经看不出自己站在哪一层——这和「工具类返回值没有归属」是同一个病:**端口没有层**。 + +2. **`flow-engine-framework` 直接依赖 `springboot-starter-script`(Groovy 运行时)。** `script` 包本质是「领域规则的可配置化表达」,但它的执行引擎是技术细节。理想形态是 Domain 只依赖 `IScriptExecutor` 端口,Groovy 实现留在 infrastructure。 + +3. **`WorkflowService.importWorkflow` 调 `Base64Utils.toJson(body)` 做 base64 + `data:` 前缀剥离。** 上传格式属于接入层,却出现在业务服务里;而 `Base64Utils` 这个名字承诺「Base64 编解码」,方法却叫 `toJson` 且只做解码,返回的其实是原始文本——名字、方法名、实际职责三者都不一致。它的异常分支 `base64.substring(0, 30)` 在长度不足 30 时还会抛 `StringIndexOutOfBoundsException`,因为这段代码没有测试守护。 + +这三处不是「架构错了」,是历史包袱。规范的作用是:**新增代码不得再加深渗透**,存量按 #309 的节奏处理。 + +## 第一层:职责 + +### 一句话职责 + +能用一句**不含「和」**的话说清楚。说不清,说明职责还没定,此时不该开始写代码。 + +`OperatorScriptResultResolver` 内部有五个步骤(归一化、类型判定、id 校验、分组回查、按序还原),但它只有一个职责:**把脚本返回值解析为参与人列表**。步骤多不等于职责多;职责多才叫职责多。 + +### 职责的三条边界 + +1. **谁能调用它**(可见性)——`public` 就是一份对外契约,改签名等于改契约; +2. **它能调用谁**(依赖方向)——依赖必须单向。`FlowSession` 调 `OperatorLoadScript`,`OperatorLoadScript` 就不能反向读 `FlowSession` 的私有状态; +3. **它产出什么,归谁**(返回值归属)——这是静态工具类的死穴:返回值放哪都行,所以谁都不对它负责。 + +第 3 条是「工具类责任漂移」的根因。`OperatorScriptResultResolver.resolve(...)` 返回的 `List`,从签名上看不出属于谁;一旦改成对象,返回值天然挂在这个对象的一次完整动作上。 + +### 职责 ≠ 功能清单 + +反例(现存): + +```java +public class OperatorAssignmentService { + private OperatorAssignmentService() { } + + public static boolean hasAssignment(FlowSession session, String nodeId) { ... } + public static ... // 另外两个方法与 hasAssignment 互不相关 +} +``` + +它没有状态、没有依赖,三个方法彼此无关。这不是一个模型,是一个函数集合借用了「Service」的名字。它真实需要的职责只是「判断某节点是否已分配操作人」——一个方法、一个对象,其余归回调用方或 `FlowSession`。 + +硬判据:**把类里所有公有方法排成一列,如果它们共享的只有包名,那它们不是一个类的职责。** + +### 命名必须能反推职责 + +名字是调用方看到的第一份文档,也是唯一一定会被读到的文档: + +- `XxxService` 承诺:有业务语义、有协作依赖、可被编排; +- `XxxPolicy` 承诺:只做判定,不持有状态; +- `XxxGateway` 承诺:外部系统边界,可能失败; +- `XxxContext` 承诺:进程内唯一状态; +- `XxxRepository` 承诺:只做存取。 + +名字与实际不符,后续所有人都会按名字用错,而且没有人会去读实现来纠正。`OperatorIdentityPolicy` 同时是全局配置持有者(`private static volatile matchMode`)和判定逻辑,`Policy` 这个后缀掩盖了它是单例状态;`Base64Utils` 则把一个上传格式的解码伪装成了通用编解码工具。 + +## 第二层:抽象 + +### 三个提问 + +1. **共性**:这段行为在本工程里还有谁需要? +2. **差异**:变的是什么,不变的是什么? +3. **层次**:这个对象和它的协作者,在同一个抽象层级上吗? + +### 共性:什么时候该提炼 + +不是「有两处相似就抽」,那是过早抽象。触发条件只有两条: + +- 同一个概念被 ≥2 个协作者以**相同语义**需要。例:「脚本返回值 → 参与人」被取人脚本、异常脚本、上一节点取人、分配回查四处需要,且语义完全一致 → 必须提炼成唯一模型,否则会出现四份各自演化的实现(本仓库历史上确实演化了三份)。 +- 或者它是某条业务规则的**唯一定义点**。例:身份匹配策略。即使只有一处调用,也需要一个地方回答「什么算同一个人」,否则今天在审批里放宽、明天在撤回里收紧,就会出现「能审批但不能撤回」的半开状态。 + +判断口径:**复用不是目的,唯一真源才是。** + +### 差异:抽象点落在「变化频率相同」处 + +Parnas 的信息隐藏原则:模块边界应该沿着「可能变化的方向」切。 + +取人脚本返回值这个例子: + +| 部分 | 变化频率 | 归属 | +|---|---|---| +| 脚本返回形态(Long / OperatorKey / IFlowOperator,未来可能再加) | 高 | 下沉为元素类型(`Direct` / `Pending`) | +| 解析骨架(归一化 → 逐元素 → 批量回查 → 按序还原) | 低 | 留在主流程 | + +把两者塞进同一个 `resolve()` 的后果是可量化的:新增一种返回形态,要改主流程、要重新回归全部 12 个用例。拆开之后,新增形态 = 新增一个元素类型,主流程不动。 + +判据:**会变的部分和不变的部分放在同一个类里,等于让不变的部分陪着变的部分一起回归。** + +### 开闭原则:抽象的验收形式 + +「改得小」不是感觉,可以数出来: + +- **合格**:新增一种能力,改动 = 新增 1 个文件(或 1 个实现类),老流程零改动; +- **不合格**:新增一种能力,要改 `resolve()` / `process()` 里的 `if` 链或 `switch` 分支。 + +正例:新增加签动作 = 新增一个 `Action` 子类,`ActionManager` 只做登记;新增一种脚本返回形态 = 新增元素类型,主流程不动。 + +反例:`resolve()` 里那条 5 分支的 `instanceof` 链——每加一种形态都必须改主流程(#308 要修的就是这个)。 + +**抽象的目的,是让「新增」落在新类型上,而不是落在老方法的 `if` 里。** + +### 抽象层级不能混 + +跨层调用只能向下,不能向上: + +``` +Workflow(流程定义) + └── IFlowNode(节点) + └── NodeStrategy(节点行为) + └── Action(动作) +``` + +混层的典型症状:**方法参数里出现比自己高一层或低一层的对象,而只是为了取一个字段。** + +- 节点级对象持有 `Workflow` 并自己遍历节点 → 该在 Workflow 层提供能力; +- `Workflow` 里出现「单个节点某个审批人的解析细节」 → 该在节点层。 + +这类代码通常能跑,但一旦上层结构变化,下层全部要跟着改。 + +### 抽象不足与过度 + +| | 症状 | 后果 | +|---|---|---| +| 不足 | 每种差异一个 `if (x instanceof ...)` + `continue`,新增形态改主流程 | 主流程越来越长,回归成本线性上升 | +| 过度 | 为一种差异建一套继承;只有一个实现的接口;`XxxFactory` 只 `new` 一个类 | 读代码要跳五层才看到一行有效逻辑 | + +判据:**抽象的数量应该等于「真正独立变化的原因」的数量。** 多一个是负担,少一个是耦合。 + +## 第三层:实现方式与使用方式 + +### 使用方式决定类的能力 + +调用方怎么用它,决定它应该长成什么样。这不是「选个模式显得专业」,而是把使用契约固化下来: + +| 调用方的需要 | 形态 | 命名 | 本仓库实例 | +|---|---|---|---| +| 带着上下文做一次转换 | 对象,构造注入 | `XxxResolver` / `Parser` / `Loader` | `OperatorLoadScript` | +| 按 key 切换不同实现 | 策略 + 注册表 | `XxxStrategy` | `RevokeStrategy`、`OperatorLoadStrategy` | +| 只关心对象怎么创建 | 工厂 / 构建者 | `XxxFactory` / `XxxBuilder` | `NodeFactory`、`ActionBuilder` | +| 全局唯一状态 | 单例 | `XxxContext` / `Cache` / `Registry` | `RepositoryHolderContext` | +| 已发生事实的通告 | 事件 | `XxxEvent` + `EventPusher` | `FlowRecordSaveEvent` | +| 外部系统能力(可能失败) | 网关 | `XxxGateway` | `FlowOperatorGateway` | +| 数据存取 | 仓储 | `XxxRepository` | `FlowRecordRepository` | +| 业务编排入口 | 服务 | `FlowXxxService` | `FlowActionService` | + +### 命名即契约 + +模式选定后,命名必须体现模式。理由是可读性,但收益比可读性更大:**命名是对使用者的用法约束。** + +- `Repository` —— 只做存取。里面出现业务判断,就是职责错位,而不是「顺手封一下」; +- `Gateway` —— 外部边界,允许失败。调用方看到这个名字就该处理异常,而不是假设它一定返回; +- `Event` —— 已发生的事实,不可变,不承载「希望别人做什么」; +- `Service` —— 业务编排,必须有依赖。**出现空私有构造 + `public static`,直接判为缺陷**; +- `Context` —— 进程内单例状态,非线程安全要在注释里说明。 + +### 模式是拆分的依据 + +一个类里同时出现多种模式的痕迹——既是策略实现、又做缓存、又提供静态创建入口——至少是三个模型。 + +反过来也成立:**模式选不出来,通常不是「这个类还不需要设计」,而是职责没拆开。** + +现存错配: + +| 类 | 名字承诺 | 实际职责 | 修法 | +|---|---|---|---| +| `OperatorAssignmentService` | 业务服务 | 3 个互不相关的静态方法 | 收为 1 个判定方法,挂到 `FlowSession` 或独立对象 | +| `OperatorIdentityPolicy` | 只做判定 | 6 个静态方法 + 全局可变配置 | 拆 `...PolicyContext`(配置)+ 判定对象 | +| `OperatorIdentityGuard` | 运行期检查 | 静态去重缓存 + 告警 | 缓存归 Context,检查归对象 | +| `OperatorScriptResultResolver` | 解析器 | 静态工具类(4 个重载) | 构造注入对象 + 元素类型(#308) | +| `Base64Utils` | Base64 编解码 | 上传格式解码(`data:` 前缀剥离) | 移到接入层,改名为上传格式解析器 | + +## 水平:职责的尺度递归 + +模型不止是类,也是包;不止是包,也是方法。**单一职责是同一条规则在不同尺度上的应用,不是三套规则。** + +| 尺度 | 问什么 | 不合格信号 | +|---|---|---| +| 包 | 这个包因为什么而变? | 两个包的类总因同一需求一起改(该合并);一个包里两组类从不一起改(该拆) | +| 类 | 这个类因为什么而变? | 类注释里出现「以及」「同时」「顺便」 | +| 方法 | 这个方法做几步? | 超过 40 行、有注释分区(`// 1. xxx`)、有 `instanceof` 链、参数超过 4 个 | + +评审时追问一句:**这一层的职责,和上一层的职责,是不是同一个粒度?** + +粒度错位的典型:Controller 里写业务规则(该在 Service)、Service 里拼查询条件(该在 Repository)、Repository 里抛业务异常(该在 Service)。这三种代码都能编译通过、也都能跑,但每一处都让边界变得不可信。 + +## 代码形态:对象优先 + +前三层定完之后,形态是自然结果。以下四条是第三层的落地约束。 + +1. **有上下文的行为,必须落在对象上。** + 需要仓储、会话、配置、脚本类型、当前操作者等「跨调用稳定」的数据,用构造注入变成字段;不要每次调用再传一遍。 + +2. **一个对象一个公有入口。** + 公有方法的数量 = 调用方必须做的选择次数。出现多个近义重载,说明入参没有归位:能靠构造注入消灭的,消灭掉;消灭不了的,拆成两个类。 + +3. **依赖不进方法签名。** + 构造函数注入过的依赖,不得再出现在方法参数中。方法参数只放「每次调用真正会变」的入参。 + +4. **静态方法只用于两类场景。** + - 无状态纯计算:`Math.max`、`isNumeric(String)` + - 类型自身的语义:`OperatorKey.of(...)`、`OperatorIdentity.of(...)` + + 凡是要读外部状态、要回查、要抛业务异常的,都不属于这两类。 + +### 改造前 / 改造后 + +```java +// 前:静态工具类,4 个重载,上下文靠参数传 +public final class OperatorScriptResultResolver { + private OperatorScriptResultResolver() { } + public static List resolve(FlowSession session, Object result) { ... } + public static List resolve(FlowSession session, Object result, String scriptType) { ... } + public static List resolve(IRepositoryHolder holder, Object result) { ... } + public static List resolve(IRepositoryHolder holder, Object result, String scriptType) { ... } +} +``` + +```java +// 后:对象,上下文进字段,一个公有入口 +public class OperatorScriptResultResolver { + + private final IRepositoryHolder repositoryHolder; + private final String scriptType; + + public OperatorScriptResultResolver(FlowSession session, String scriptType) { + this(session.getRepositoryHolder(), scriptType); + } + + public OperatorScriptResultResolver(IRepositoryHolder repositoryHolder, String scriptType) { + this.repositoryHolder = repositoryHolder; + this.scriptType = scriptType; + } + + /** 唯一公有入口 */ + public List resolve(Object scriptResult) { ... } + + private List parse(Object scriptResult) { ... } + private Map load(List keys) { ... } +} +``` + +### 元素对象化(第二层的抽象结果) + +```java +sealed interface OperatorScriptElement { + record Direct(IFlowOperator operator) implements OperatorScriptElement { } + record Pending(OperatorKey key) implements OperatorScriptElement { } +} +``` + +每个元素自己回答「我是什么、我是否有效」;主流程只剩 `parse → load → 按序还原`。这是第二层(差异下沉)自然导出的结构,不是单纯为了消除 `if`。 + +## 可验证性:先对,再好 + +架构质量的上限由业务正确性决定,而正确性只能由用例证明。落地为三条硬规矩: + +1. **新增能力先写失败用例。** 没有红灯,就没有「问题存在」的证明,绿灯也就没有意义。 +2. **重构的验收 = 行为契约零变化 + 既有断言语义零改动。** 只允许改调用形式(如 `resolve(...)` → `new Resolver(...).resolve(...)`),不允许顺手改断言。#308 的 12 个用例就按这条验收。 +3. **端口(接口)只在「依赖在测试里无法真实构造」时引入**:时间、外部系统、随机数、网络、文件系统。 + - 正例:`FlowOperatorGateway`(外部用户体系)、`IRepositoryHolder`(数据库) + - 反例:给一段纯计算逻辑加接口 + 实现,只为在测试里 mock 它 + + **不要为了可测而抽象。** 每个端口都是一层间接,可读性要为它付费。 + +第 3 条是「抽象过度」在可验证性上的镜像:抽象解决「测不了」,不解决「测得慢」。 + +## 判定流程 + +写新类 / 改结构前按顺序过一遍,能答完再动手: + +``` +A0 分层 + 这个模型属于业务 / 数据 / 技术细节哪一层?包位置对吗? + 是否在反向依赖(Domain 引技术、数据层写业务判断)? + +A 职责 + A1 能用一句不含「和」的话说清它负责什么吗? + └─ 不能 → 停;若答案是「一堆工具方法」,说明没有模型,不该建类 + A2 谁能调用它 / 它依赖谁 / 返回值归谁,三条边界都清楚吗? + A3 公有方法排成一列,它们共享的是状态,还是只有包名? + +B 抽象 + B1 这段行为的共性,工程里还有谁需要?是否需要唯一真源? + B2 变的部分和不变的部分,是否被放进了同一个类? + B3 新增一种情况时,是加文件还是改老方法的 if?(开闭验收) + B4 对象与协作者是否在同一抽象层级? + +C 实现与使用 + C1 调用方怎么用它?据此选定模式 + C2 命名是否体现了这个模式,且与实际职责一致? + +D 形态 + D1 是否存在跨调用共享的上下文 → 必须构造注入 + D2 公有方法是否 > 1 且需调用方选择 → 收敛入口或拆类 + D3 依赖是否出现在方法签名里 → 改为字段 + D4 是否存在 static 可变字段 → 必须是 Context 单例 + +E 可验证 + E1 不起整套环境,能不能验证这一个行为? + E2 重构有没有既有用例守护?断言是否零改动? + E3 新增的端口是否必要(依赖是否真的无法真实构造)? +``` + +> 一句话判据:**如果调用方必须先读完整个类才能用对一个方法,这个类就写错了。** + +## 允许的例外 + +以下形态不算违规,但**必须在类注释中写明属于哪一类**: + +| 形态 | 允许理由 | 示例 | +|---|---|---| +| `XxxContext` / `XxxCache` / `XxxRegistry` 单例 | 全局唯一状态持有者,`getInstance()` 是唯一入口 | `RepositoryHolderContext`、`FlowRuntimeScriptLocalCache` | +| `XxxFactory` / `XxxBuilder` | 静态方法只负责创建对象,不承载业务行为 | `NodeFactory`、`ActionBuilder` | +| 值对象自身的语义 | 行为与类型强内聚,无外部依赖 | `OperatorKey.of/ofDefault`、`OperatorIdentity.of` | +| 枚举 / 常量类 | 无行为 | `OperatorIdentityMatchMode` | +| 框架要求的空构造 | 序列化 / `IMapConvertor` 反射需要 | `ActionDisplay`、实体类 | +| 单入口、无依赖的算法 | 只有 1 个公有方法,签名即语义 | `WorkflowStructureVerifier.compare` | + +判断标准只有一条:**这个类的所有公有方法,是否都不需要外部上下文、且调用方不存在选择困难。** 有一条不满足,就不是例外。 + +注意:例外只豁免**形态**,不豁免**分层**与**命名**。一个静态方法放错层、起错名,照样是缺陷。 + +## 命名红线 + +| 后缀 | 要求 | +|---|---| +| `XxxResolver` / `Parser` / `Loader` / `Evaluator` | 必须是对象,构造注入依赖 | +| `XxxService` | 必须有实例状态或构造注入依赖;空私有构造 + `public static` 直接判为缺陷 | +| `XxxContext` / `Cache` / `Registry` | 只允许 `getInstance()` 一个静态入口 | +| `XxxFactory` / `Builder` | 内部不得执行回查、落库等业务流程 | +| `XxxUtil` / `Utils` / `Helper` / `Tool` | **禁止新增**;存量遇到时改成对象或归入正确的层,而不是继续加方法 | + +## 评审清单 + +**分层** +- [ ] 模型的包位置与 DDD 层一致;Domain 里没有 JPA / SQL / HTTP / 上传格式 / 脚本引擎调用 +- [ ] 数据层没有业务判断;技术层没有被 Domain 反向依赖 + +**职责** +- [ ] 一句话说清职责,且不含「和」 +- [ ] 三条边界(谁能调 / 依赖谁 / 返回值归谁)明确 +- [ ] 公有方法排成一列,共享的不只是包名 + +**抽象** +- [ ] 共性是唯一真源,不是复制粘贴的产物 +- [ ] 会变的部分与不变的部分已经分开 +- [ ] 新增一种情况是「加文件」而不是「改 if」(开闭验收) +- [ ] 没有为取一个字段而跨抽象层 +- [ ] 没有为「一种差异」建一套继承或一个单实现接口 + +**实现与命名** +- [ ] 命名体现了所选模式,且与实际职责一致 +- [ ] 一个类里没有出现两种以上模式的痕迹 +- [ ] 新类注释里有一行用法示例 + +**形态** +- [ ] 依赖经构造注入,未出现在方法签名 +- [ ] 公有入口唯一;多个近义重载已收敛 +- [ ] 无 `private static` 可变字段 +- [ ] 主流程方法未超过 40 行,无 3 个以上 `instanceof` 分支 + +**可验证** +- [ ] 不起整套环境即可验证该行为 +- [ ] 新增能力有先行的失败用例;重构有既有用例守护且断言零改动 +- [ ] 新增的端口是必要的(依赖确实无法真实构造) + +## 自检命令 + +列出仓库中「空私有构造 + 公有静态方法」的候选类,逐个对照例外清单: + +```bash +for f in $(grep -rl "private [A-Z][A-Za-z0-9_]*() {" --include="*.java" . | grep "src/main/java"); do + n=$(grep -c "public static" "$f") + [ "$n" -gt 0 ] && echo "$n $f" +done | sort -rn +``` + +查分层渗透(Domain 模块里不该出现的依赖): + +```bash +grep -rn "jakarta.persistence\|org.springframework.web\|GroovyScript" \ + flow-engine-framework/src/main/java +``` + +包边界与抽象层无法靠命令判定,只能靠人:**这个包里的类,是不是因为同一个原因而修改?** + +## 关联 + +- 样板改造:#308 `OperatorScriptResultResolver` +- 存量盘点(含三处分层渗透的处置):#309 +- 讨论来源:#310 diff --git a/docs/conventions/docs/documentation.md b/docs/conventions/docs/documentation.md new file mode 100644 index 00000000..e01cd40d --- /dev/null +++ b/docs/conventions/docs/documentation.md @@ -0,0 +1,135 @@ +# 文档编写与维护规范 + +> 模块:docs · 范围:仓库内全部 Markdown / HTML 文档 +> 前置:[模型设计三层法](../design/model-design.md)。本文是它在**文档尺度**上的应用:先分层,再定职责,再定验收。 + +## 为什么需要这条规范 + +文档腐化从来不是「写得少」,而是**写错了地方**和**写的时候没对账**。本仓库出现过两类典型问题: + +1. **过程文档混进规范目录** —— 「改造前的现状」「P1~P5 分批」「落地记录」被写成规范。它描述的是过去发生的事,不是「以后必须怎么做」,读的人无法据此判定对错,改完代码后它还会变成误导。 +2. **计数与签名凭记忆写** —— 「12 个仓储接口」「9 种事件」「`setOperatorId()`」在代码变更后全部失真,而这类错误在评审时看不出来,只有照着写代码的人才会踩坑。 + +因此本规范只解决两件事:**文档放在哪**,**写进去的事实怎么保证是真的**。 + +## 1. 四类文档,各只有一个归属 + +| 目录 | 回答的问题 | 时效 | 允许写 | 禁止写 | +|---|---|---|---|---| +| `docs/Integration/` | 别人怎么把引擎接进自己的系统 | 随公开 API 变 | 集成步骤、配置项、请求/响应示例、升级与迁移指引 | 内部实现细节、改造历史、未发布计划 | +| `docs/capabilities/` | 引擎**现在**有哪些能力、由谁提供 | 随代码变 | 当前类/方法/职责、设计约束、相关测试 | 计划、issue 时间线、已删除的旧实现 | +| `docs/conventions/` | 做改动**必须**遵守什么规则 | 长期稳定 | 可判定的规则、禁止清单、提交前自查 | 过程记录、改造批次、落地总结、API 迁移表 | +| `docs/manual/` | 使用者怎么操作 | 随发布变 | 操作步骤、界面说明 | 内部类名与包路径 | +| `README.md` / `AGENTS.md` / `CLAUDE.md` | 导航与约束摘要 | 随结构变 | 目录地图、命令、**指向性链接** | 长篇幅正文(应链接到上述四类) | + +判据一句话:**照着能做的 → Integration;能查到「有什么」的 → capabilities;能判定「这样做对不对」的 → conventions;其余不进 `docs/`。** + +同一事实只允许有一个归属。`README` 与 `AGENTS` 里出现的规则必须是摘要 + 链接,正文在 `conventions/` 内维护。 + +## 2. 过程文档不进 `conventions/` + +以下内容属于 issue / PR / release notes,**不属于规范**: + +- 改造前的现状盘点、问题清单; +- 分批计划(P1/P2/…)、批次验收记录; +- 「落地记录」「已完成项」; +- API 改名迁移对照表(这类内容属于 Integration 的升级说明)。 + +改造完成后只保留两份产物: + +1. **现在是什么** → `capabilities/`(模型、职责、唯一真源); +2. **以后必须怎么做** → `conventions/`(可判定的规则)。 + +需要保留历史对照时,写进对应 issue 的关闭评论。判断方法很简单:**一段文字里如果出现「改造前」「已删除」「已改名」「原 xxx」,它就不是规范。** + +## 3. 代码是唯一事实源 + +文档中出现的类名、方法签名、配置键、REST 路径、表名、字段名,必须能在代码里检索到。 + +提交前对本文档涉及的全部标识符做一次检索: + +```bash +# 类名/方法名是否存在 +grep -rn "OperatorKey#matches" --include=*.java . + +# REST 路径是否存在 +grep -rn "/api/cmd/record/reissue" --include=*.java . + +# 配置键是否存在 +grep -rn "codingapi.flow.identity.match-mode" --include=*.java --include=*.properties . +``` + +禁止: + +- 把接口/类的完整签名抄进文档当说明(腐化最快的一种写法); +- 凭记忆写字段名、参数名; +- 用「应该会」「大概」描述行为。 + +推荐写法:**入口 + 关键约束 + 代码路径**。例如写「`FlowService` 是唯一事务入口」并给出文件路径,而不是把 10 个方法签名贴一遍。 + +## 4. 计数必须可复算 + +「N 个仓储接口」「N 种事件」「N 个 Bean」「N 种节点」这类数字,每次新增能力都会失真。 + +优先级从高到低: + +1. **不写数量,直接列举** —— 列举本身就是事实,新增时自然会看到要补一行; +2. **必须写数量时,附复算命令** —— 例如 `13 个仓储接口(ls .../repository/*.java | wc -l)`; +3. **禁止模糊量词** —— 「约 N 个」「等等」「若干」在核对时无法判定真假。 + +## 5. 版本号只出现在两个位置 + +`pom.xml` 的 `` 是唯一来源。文档中只允许 [快速开始](../../Integration/quick-start.md) 与 `docs/manual/` 出现具体版本号,且必须与 `pom.xml` 一致: + +```bash +grep -n "" pom.xml +grep -rn "0\.[0-9]\.0-SNAPSHOT" docs/ +``` + +除这两处外,正文一律用「当前版本」表述。 + +## 6. 索引文件按格式维护,不重写 + +`docs/capabilities/index.md` 与 `docs/conventions/index.md` 是目录索引: + +- 新增文档必须同批补一行,表格列含义(名称 / 模块 / 描述 / 范围 / 来源)保持不变; +- 删除文档必须同批删除对应行,并更新末尾统计; +- 不调整排序规则、不改表头、不重新组织分组。 + +索引行的「描述」用一句话说清这篇文档回答什么问题,不复制标题。 + +## 7. 代码与文档同批提交 + +不允许「先提交代码,文档下次补」。按下表判断本次改动必须连带更新哪些文档: + +| 代码改动 | 必须同批更新 | +|---|---| +| 新增 / 删除 / 改路径的 REST 端点 | `Integration/rest-api.md` | +| 新增 / 重命名配置项 | `Integration/auto-configuration.md` | +| 新增 / 删除公开类或公开方法 | `capabilities/<模块>/` 对应文档 | +| 新增事件类型 | `Integration/event-integration.md` + `capabilities/` | +| 新增 / 删除仓储接口或表 | `Integration/repository-integration.md` | +| 修改一条既有规则 | `conventions/<域>/` | +| 调整模块划分 | `README.md` + `AGENTS.md` | +| 版本号变更 | `Integration/quick-start.md` + `docs/manual/` | + +提交信息里注明本次同时修正了哪些文档,便于回溯。 + +## 8. 写作形式 + +- **中文**,与技术术语混排时保留代码标识符原文; +- 表格优先于长段落:核对时逐行比对,比读段落可靠; +- 每篇开头三行内给出:模块、范围、前置文档(或「无前置」); +- 标题层级不超过三级,避免把结构写成大纲; +- 示例代码只保留能说明问题的最短片段,完整用法指向源码; +- 不写「我们将」「计划」「后续考虑」「暂时」—— 这些属于 issue。 + +## 9. 提交前自查 + +1. 文档里出现的类名、方法名、路径、配置键,**逐个 grep 过**了吗? +2. 所有数字都能**当场复算**吗? +3. 有没有「改造前 / 已删除 / 已改名 / 落地记录」的叙述?有 → 移到 issue。 +4. 这次改了代码,第 7 节表格里对应的文档**改了吗**? +5. 新增或删除文档,`index.md` 补行 / 删行了吗? + +五问全过,文档才算与代码对齐。 diff --git a/docs/conventions/index.md b/docs/conventions/index.md index e3e83e9e..80805e32 100644 --- a/docs/conventions/index.md +++ b/docs/conventions/index.md @@ -6,8 +6,10 @@ | 名称 | 模块 | 描述 | 范围 | 来源 | |------|------|------|------|------| +| [design/model-design](./design/model-design.md) | design | 模型设计三层法 — 职责 → 抽象 → 实现;垂直按 DDD 分层(业务/数据/技术),水平按包/类/方法递归;以易维护与可验证为验收 | 通用 | 项目自有 | +| [docs/documentation](./docs/documentation.md) | docs | 文档编写与维护规范 — 四类文档各有唯一归属;过程记录不入规范;代码是唯一事实源;计数可复算;代码与文档同批提交 | 通用 | 项目自有 | | [workflow/github-issue](./workflow/github-issue.md) | workflow | GitHub Issue 标准处理流程 — 定位分析 → 回复 issue → worktree 修复 → 推送特性分支 → 推送后回复 | 通用 | 项目自有 | --- -**统计**: 共 1 篇 — 已实现 1 / 计划中 0 / 已废弃 0 +**统计**: 共 3 篇 — 已实现 3 / 计划中 0 / 已废弃 0 diff --git a/docs/manual/README.md b/docs/manual/README.md index 981b338c..179ce334 100644 --- a/docs/manual/README.md +++ b/docs/manual/README.md @@ -16,7 +16,7 @@ Flow Engine 是企业级工作流引擎,采用前后端分离架构:后端 ## 当前版本 -- 版本号:`0.1.0-SNAPSHOT`(前后端对齐) +- 版本号:`0.3.0-SNAPSHOT`(前后端对齐) - 后端:JDK 17 / Spring Boot 3.5.9 / Spring Data JPA(默认 H2,支持达梦 DM) - 前端:React 18 / TypeScript 5 / pnpm 10 / antd 6(PC)/ antd-mobile 5(移动)/ @flowgram.ai 1.0.8 diff --git a/docs/manual/integration-manual.html b/docs/manual/integration-manual.html index bf5aa23d..ee9b031d 100644 --- a/docs/manual/integration-manual.html +++ b/docs/manual/integration-manual.html @@ -90,7 +90,7 @@

Flow Engine 集成手册

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

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

目录

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

2.1 一站式引入(推荐)

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

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

diff --git a/flow-engine-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..0cbc7e5b 100644 --- a/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java +++ b/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java @@ -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,19 @@ public class User implements IFlowOperator { private String account; private String password; + /** + * 当前身份标识(issue #288)。 + * + *

同一个人员可能隶属多个部门/岗位,以不同身份参与流程。身份是**运行期选择**而非用户主数据, + * 因此不落库({@link Transient});由 {@code FlowOperatorGateway#get(id, identity)} 按身份返回 + * 携带该标识的用户副本,示例前端通过请求参数 {@code operatorIdentity} 声明当前身份。 + * 不参与 {@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 +89,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..0e595a31 100644 --- a/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java +++ b/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java @@ -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.of(identity).isDefault()) { + return get(id); + } + User user = userRepository.getUserById(id); + return user == null ? null : user.withIdentity(OperatorIdentity.of(identity).value()); + } + @Override public List findByIds(List ids) { return userRepository.findUserByIdIn(ids) @@ -27,4 +45,22 @@ public List findByIds(List ids) { .toList(); } + /** + * 按统一身份批量获取操作者(issue #288 衍生 / #293)。 + * + *

批量重载同样必须返回携带身份的副本:只覆盖单条 {@code get(id, identity)} 时, + * 流程树、人员设定等批量路径会把身份退化为默认身份。 + */ + @Override + public List findByIds(List ids, String identity) { + if (OperatorIdentity.of(identity).isDefault()) { + return findByIds(ids); + } + String normalized = OperatorIdentity.of(identity).value(); + return userRepository.findUserByIdIn(ids) + .stream() + .map(user -> (IFlowOperator) user.withIdentity(normalized)) + .toList(); + } + } diff --git a/flow-engine-example/src/main/java/com/codingapi/example/runner/AdminInitializer.java b/flow-engine-example/src/main/java/com/codingapi/example/runner/AdminInitializer.java index eb9ffe13..9df771db 100644 --- a/flow-engine-example/src/main/java/com/codingapi/example/runner/AdminInitializer.java +++ b/flow-engine-example/src/main/java/com/codingapi/example/runner/AdminInitializer.java @@ -5,10 +5,18 @@ import lombok.AllArgsConstructor; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; +import org.springframework.core.annotation.Order; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; +/** + * 内置管理员账号初始化。 + * + *

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

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

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

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

初始化是幂等的:流程编码已存在时直接跳过,不会重复造数据。 + * 不需要演示数据时可通过 {@code flow.example.identity-demo-enabled=false} 关闭。 + */ +@Slf4j +@Service +@Order(20) +@AllArgsConstructor +@ConditionalOnProperty(prefix = "flow.example", name = "identity-demo-enabled", havingValue = "true", matchIfMissing = true) +public class IdentityDemoInitializer implements ApplicationRunner { + + /** + * 演示流程编码,同时作为「是否已初始化」的幂等标记 + */ + public static final String WORKFLOW_CODE = "identity-demo"; + + /** + * 演示流程标题 + */ + public static final String WORKFLOW_TITLE = "身份标识验证流程"; + + /** + * 演示账号:张三 + */ + public static final String ACCOUNT_ZHANGSAN = "user1"; + + /** + * 演示账号:李四 + */ + public static final String ACCOUNT_LISI = "user2"; + + /** + * 演示账号统一密码 + */ + public static final String DEMO_PASSWORD = "123456"; + + /** + * 演示身份:部门一 + */ + public static final String IDENTITY_DEPARTMENT1 = "department1"; + + /** + * 演示身份:部门二 + */ + public static final String IDENTITY_DEPARTMENT2 = "department2"; + + private final UserRepository userRepository; + private final PasswordEncoder passwordEncoder; + private final WorkflowService workflowService; + private final FlowService flowService; + + @Override + public void run(ApplicationArguments args) { + try { + if (workflowService.getWorkflowByCode(WORKFLOW_CODE) != null) { + return; + } + User admin = userRepository.getUserByAccount(User.ADMIN_ACCOUNT); + if (admin == null) { + log.warn("[identity-demo] 未找到 admin 账号,跳过演示数据初始化"); + return; + } + User zhangsan = ensureUser(ACCOUNT_ZHANGSAN, "张三"); + User lisi = ensureUser(ACCOUNT_LISI, "李四"); + + ApprovalNode approvalNode = buildWorkflow(admin); + + // 张三 · 默认身份:切到非默认身份后这条待办不再可见 + createAndSubmit(admin, null, approvalNode.getId(), + OperatorKey.ofDefault(zhangsan.getUserId()), "默认身份审批人"); + // 张三 · department1:只有切换到 department1 才可见 + createAndSubmit(admin, IDENTITY_DEPARTMENT1, approvalNode.getId(), + OperatorKey.of(zhangsan.getUserId(), IDENTITY_DEPARTMENT1), "部门一身份审批人"); + // 李四 · department2:用于验证「别人的身份看不到我的待办」 + createAndSubmit(admin, IDENTITY_DEPARTMENT2, approvalNode.getId(), + OperatorKey.of(lisi.getUserId(), IDENTITY_DEPARTMENT2), "部门二身份审批人"); + + log.info("[identity-demo] 演示数据初始化完成:流程编码={},账号={}/{}(密码 {})", + WORKFLOW_CODE, ACCOUNT_ZHANGSAN, ACCOUNT_LISI, DEMO_PASSWORD); + } catch (Exception e) { + // 演示数据失败不能阻塞应用启动 + log.warn("[identity-demo] 演示数据初始化失败:{}", e.getMessage(), e); + } + } + + /** + * 创建演示流程定义,返回审批节点(其 id 用于发起时指定审批人) + */ + private ApprovalNode buildWorkflow(User admin) { + FlowForm form = FlowFormBuilder.builder() + .name(WORKFLOW_TITLE) + .code(WORKFLOW_CODE) + .addField("申请事项", "subject", DataType.STRING) + .addField("备注", "remark", DataType.STRING) + .build(); + + FormFieldPermissionsBuilder permissions = FormFieldPermissionsBuilder.builder() + .addPermission(WORKFLOW_CODE, "subject", PermissionType.WRITE) + .addPermission(WORKFLOW_CODE, "remark", PermissionType.WRITE); + + StartNode startNode = StartNode.builder() + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(permissions.build())) + .build()) + .build(); + + // 审批人由发起人在发起时指定(INITIATOR_SELECT),因此可以指定「某人 + 某个身份」 + ApprovalNode approvalNode = ApprovalNode.builder() + .name("审批节点") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(permissions.build())) + .addStrategy(OperatorLoadStrategy.initiatorSelectStrategy()) + .build()) + .build(); + + EndNode endNode = EndNode.builder().build(); + + Workflow workflow = WorkflowBuilder.builder() + .title(WORKFLOW_TITLE) + .code(WORKFLOW_CODE) + .createdOperator(admin) + .form(form) + .addNode(startNode) + .addNode(approvalNode) + .addNode(endNode) + .build(); + + workflowService.saveWorkflow(workflow, true); + return approvalNode; + } + + /** + * 以指定身份发起流程,并提交开始节点把待办投给「审批人 + 审批身份」 + * + * @param initiator 发起人 + * @param identity 发起人身份(null 表示默认身份) + * @param approvalNodeId 审批节点 id + * @param approver 审批人(人员 + 身份) + * @param subject 申请事项 + */ + private void createAndSubmit(User initiator, String identity, String approvalNodeId, + OperatorKey approver, String subject) { + Workflow workflow = workflowService.getWorkflowByCode(WORKFLOW_CODE); + StartNode startNode = (StartNode) workflow.getStartNode(); + String actionId = startNode.actionManager().getActions().get(0).id(); + Map formData = Map.of("subject", subject, "remark", "身份标识演示数据"); + + FlowCreateRequest createRequest = new FlowCreateRequest(); + createRequest.setWorkCode(WORKFLOW_CODE); + createRequest.setFormData(formData); + createRequest.setActionId(actionId); + createRequest.setOperatorId(initiator.getUserId()); + createRequest.setOperatorIdentity(identity); + createRequest.setOperatorSelectOperators(Map.of(approvalNodeId, List.of(approver))); + long recordId = flowService.create(createRequest); + + // 提交开始节点:这一步才真正把待办写入审批人的待办列表(带审批身份) + FlowActionRequest actionRequest = createRequest.toActionRequest(recordId); + flowService.action(actionRequest); + } + + /** + * 按账号取用户,不存在则创建(密码为 {@value #DEMO_PASSWORD}) + */ + private User ensureUser(String account, String name) { + User user = userRepository.getUserByAccount(account); + if (user != null) { + return user; + } + user = new User(); + user.setAccount(account); + user.setName(name); + user.setPassword(DEMO_PASSWORD); + user.setFlowManager(false); + user.encodePassword(passwordEncoder); + return userRepository.save(user); + } +} diff --git a/flow-engine-example/src/main/resources/application.properties b/flow-engine-example/src/main/resources/application.properties index 4cc12d8c..b804af8e 100644 --- a/flow-engine-example/src/main/resources/application.properties +++ b/flow-engine-example/src/main/resources/application.properties @@ -16,4 +16,9 @@ spring.jpa.properties.hibernate.order_updates=true spring.main.allow-bean-definition-overriding=true codingapi.security.jwt.enable=true +# 身份匹配模式(issue #297): +# USER_ONLY(starter 默认)= 身份只服务脚本与留痕,同一个人换身份仍可办理自己的待办 +# STRICT = 办理时要求人员与身份都匹配(issue #288 的隔离语义) +# codingapi.flow.identity.match-mode=STRICT + codingapi.security.ignore-urls=/open/**,/#/**,/,/**.css,/**.js,/**.svg,/**.png,/**.ico diff --git a/flow-engine-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..ded008cf 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/AddAuditAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/AddAuditAction.java @@ -12,6 +12,8 @@ import com.codingapi.flow.manager.OperatorManager; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentityContext; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.script.node.OperatorLoadScript; import com.codingapi.flow.session.FlowSession; @@ -23,8 +25,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; /** * 加签 @@ -146,6 +146,10 @@ public void run(FlowSession flowSession) { *

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

「是否已存在」统一由 {@link OperatorIdentityContext} 判定(issue #295): + * 严格模式下同一人的另一身份是独立参与人,可以加签;仅按人员模式下同一个人已经待办, + * 再加签只会给自己多生成一条重复待办,因此拒绝。 + * * @param flowSession 当前会话 * @param auditOperators 本次加签的人员 */ @@ -153,35 +157,37 @@ private void verifyNotInTodoQueue(FlowSession flowSession, List a if (auditOperators == null || auditOperators.isEmpty()) { return; } - Set pendingOperatorIds = pendingOperatorIds(flowSession); - if (pendingOperatorIds.isEmpty()) { + List pendingRecords = pendingRecords(flowSession); + if (pendingRecords.isEmpty()) { return; } for (IFlowOperator auditOperator : auditOperators) { - if (pendingOperatorIds.contains(auditOperator.getUserId())) { + boolean alreadyPending = pendingRecords.stream().anyMatch(record -> + OperatorIdentityContext.getInstance() + .matches(OperatorKey.of(auditOperator), record.currentOperatorKey())); + if (alreadyPending) { throw FlowExecutionException.addAuditOperatorAlreadyInTodo(auditOperator.getUserId()); } } } /** - * 当前节点实例中仍有待办的人员id集合。 + * 当前节点实例中仍有待办的审批记录。 * *

仓储按 {@code (fromId, nodeId)} 查询节点记录,开始节点({@code fromId = 0})等场景可能 * 命中其他流程实例的记录,必须按 {@code processId} 限定,避免误判其他流程的待办人员。 */ - private Set pendingOperatorIds(FlowSession flowSession) { + private List pendingRecords(FlowSession flowSession) { FlowRecord currentRecord = flowSession.getCurrentRecord(); List currentNodeRecords = flowSession.getCurrentNodeRecords(); if (currentRecord == null || currentNodeRecords == null) { - return Set.of(); + return List.of(); } return currentNodeRecords.stream() .filter(Objects::nonNull) .filter(record -> currentRecord.getProcessId().equals(record.getProcessId())) .filter(FlowRecord::isPendingApproval) - .map(FlowRecord::getCurrentOperatorId) - .collect(Collectors.toSet()); + .toList(); } public static AddAuditAction fromMap(Map data) { diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/DelegateAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/DelegateAction.java index ccbd99f2..ecd87247 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/DelegateAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/DelegateAction.java @@ -73,6 +73,7 @@ public void run(FlowSession flowSession) { FlowRecord currentRecord = flowSession.getCurrentRecord(); currentRecord.update(flowSession, true); + currentRecord.markHandleOperator(flowSession.getCurrentOperator()); recordList.add(currentRecord); flowEvents.add(new FlowRecordDoneEvent(currentRecord, flowSession.isMock())); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java index ed069947..5a4b5194 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java @@ -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); } } } @@ -140,6 +141,7 @@ public void run(FlowSession flowSession) { boolean isFinish = currentNode.isFinish(flowSession); currentRecord.update(flowSession, true); + currentRecord.markHandleOperator(flowSession.getCurrentOperator()); // 添加流程结束事件 flowEvents.add(new FlowRecordDoneEvent(currentRecord, flowSession.isMock())); recordList.add(currentRecord); @@ -203,7 +205,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 +218,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); @@ -259,11 +263,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 (!new OperatorAssignmentService(flowSession).hasAssignment(node.getId())) { List range = node.strategyManager() .loadOperatorRange(flowSession.updateSession(node)); result.add(new NodeOption(node, range)); @@ -281,12 +285,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/ReduceAuditAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReduceAuditAction.java index 76cb04f2..69ed9d32 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReduceAuditAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReduceAuditAction.java @@ -13,6 +13,9 @@ 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.operator.OperatorIdentityContext; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.script.node.OperatorLoadScript; import com.codingapi.flow.session.FlowSession; @@ -170,12 +173,18 @@ 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).value(); + // 自己不能被自己减签:按身份匹配策略判断(USER_ONLY 下同人换身份仍视为自己) + if (OperatorIdentityContext.getInstance() + .matches(OperatorKey.of(target), currentRecord.currentOperatorKey())) { throw FlowExecutionException.reduceAuditOwnRecord(); } + // 减签的生效范围同样由策略决定:STRICT 下按「人 + 身份」,USER_ONLY 下按「人」 List matchedRecords = currentNodeRecords.stream() .filter(FlowRecord::isPendingApproval) - .filter(record -> record.getCurrentOperatorId() == targetOperatorId) + .filter(record -> OperatorIdentityContext.getInstance() + .matches(OperatorKey.of(targetOperatorId, targetOperatorIdentity), + record.currentOperatorKey())) .toList(); if (matchedRecords.isEmpty()) { throw FlowExecutionException.reduceAuditTargetNotFound(targetOperatorId); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/RejectAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/RejectAction.java index ca7db511..5c06bfd7 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/RejectAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/RejectAction.java @@ -100,6 +100,7 @@ public void run(FlowSession flowSession) { FlowRecord flowRecord = flowSession.getCurrentRecord(); flowRecord.update(flowSession, true); + flowRecord.markHandleOperator(flowSession.getCurrentOperator()); recordList.add(flowRecord); // 当前审批为已办状态 diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReturnAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReturnAction.java index 268cda80..14195421 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReturnAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReturnAction.java @@ -54,6 +54,7 @@ public void run(FlowSession flowSession) { FlowRecord currentRecord = flowSession.getCurrentRecord(); currentRecord.update(flowSession, true); + currentRecord.markHandleOperator(flowSession.getCurrentOperator()); recordList.add(currentRecord); flowEvents.add(new FlowRecordDoneEvent(currentRecord,flowSession.isMock())); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/TransferAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/TransferAction.java index 8d2a085b..0eec025e 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/TransferAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/TransferAction.java @@ -82,6 +82,7 @@ public void run(FlowSession flowSession) { FlowRecord currentRecord = flowSession.getCurrentRecord(); currentRecord.update(flowSession, true); + currentRecord.markHandleOperator(flowSession.getCurrentOperator()); recordList.add(currentRecord); flowEvents.add(new FlowRecordDoneEvent(currentRecord,flowSession.isMock())); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/service/InitiatorSelectNodeService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/service/InitiatorSelectNodeService.java index bbe536fc..24072133 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/service/InitiatorSelectNodeService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/service/InitiatorSelectNodeService.java @@ -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 (!new OperatorAssignmentService(this.flowSession).hasAssignment(node.getId())) { List range = node.strategyManager() .loadOperatorRange(this.flowSession.updateSession(node)); operatorSelectNodes.add(new NodeOption(node, range)); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java b/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java index 57a994ca..84c32cf8 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java @@ -1,6 +1,8 @@ package com.codingapi.flow.cache; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorKey; import lombok.Getter; import java.util.ArrayList; @@ -9,9 +11,18 @@ 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; + private final ThreadLocal> cache; private FlowOperatorLocalThreadCache() { this.cache = new ThreadLocal<>(); @@ -20,42 +31,106 @@ private FlowOperatorLocalThreadCache() { @Getter private final static FlowOperatorLocalThreadCache instance = new FlowOperatorLocalThreadCache(); + /** + * 拼装缓存键。 + * + *

键格式由 {@link OperatorKey#key()} 唯一定义:缓存键就是参与人键, + * 本类不再自己声明分隔符,也不自己做归一化。 + */ + private static String cacheKey(long userId, String identity) { + return OperatorKey.of(userId, identity).key(); + } 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).value()), 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.value(), 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); + // 非默认身份且下游未按身份返回副本时,加载结果的身份与缓存键不一致。 + // 此时不能登记,否则同线程后续按该身份的读取都会命中这个错误身份的对象(issue #288 评审修复)。 + if (operator != null && isIdentityMatched(operator, identity)) { + operatorCaches.put(key, operator); this.cache.set(operatorCaches); } return operator; } + /** + * 判断加载结果的身份是否与请求的身份一致。 + * + *

默认身份的读取保持历史行为(批量路径与单条路径都以默认身份为标识无关入口), + * 只有「请求了非默认身份、但拿回的却是另一个身份」才视为不一致。 + */ + private static boolean isIdentityMatched(IFlowOperator operator, String requestedIdentity) { + if (OperatorIdentity.of(requestedIdentity).isDefault()) { + return true; + } + return OperatorKey.of(operator).identityEquals(requestedIdentity); + } + /** + * 批量读取操作者(默认身份)。 + * + *

批量加载没有身份维度(下游网关的 {@code findByIds} 只按 id 查询), + * 因此这里固定使用默认身份作为缓存键,与历史行为一致。 + */ public List find(List ids, IFlowOperatorFinder flowOperatorFinder) { + return this.find(ids, OperatorIdentity.DEFAULT.value(), 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; } @@ -68,17 +143,26 @@ public List find(List ids, IFlowOperatorFinder flowOperator return null; } - Map operatorCaches = this.getCache(); + String normalizedIdentity = OperatorIdentity.of(identity).value(); + + Map operatorCaches = this.getCache(); List queryIds = ids.stream() - .filter((id) -> !operatorCaches.containsKey(id)) + .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) { - operatorCaches.put(operator.getUserId(), operator); + // 结果按「请求身份」登记,而不是操作者对象自带身份: + // 调用方是按该身份发起查询的,登记键必须与读取键一致,否则读取时必然落空。 + // 但「请求了非默认身份、对象却是另一个身份」时不能登记——否则该身份键被错误对象污染, + // 同线程后续按身份的单条读取会直接命中它,身份被静默替换(issue #288 评审修复)。 + if (!isIdentityMatched(operator, normalizedIdentity)) { + continue; + } + operatorCaches.put(cacheKey(operator.getUserId(), normalizedIdentity), operator); } this.cache.set(operatorCaches); } @@ -87,7 +171,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, 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 863e783d..7e112be0 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java @@ -3,10 +3,16 @@ 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 com.codingapi.flow.diagnostic.OperatorIdentityWarnLog; import lombok.Getter; import lombok.Setter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; public class GatewayContext { @@ -20,12 +26,74 @@ 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.value()); + } + + /** + * 按人员 id 与身份获取操作者(issue #288)。 + * + *

身份为空({@code null}/空串)时与 {@link #getFlowOperator(long)} 完全等价, + * 保证存量调用链行为不变。 + * + * @param userId 人员 id + * @param identity 身份标识 + * @return 操作者 + */ + public IFlowOperator getFlowOperator(long userId, String identity) { + IFlowOperator operator = FlowOperatorLocalThreadCache.getInstance() + .get(userId, identity, () -> flowOperatorGateway.get(userId, identity)); + // 下游未覆盖带身份的取人方法时身份会被静默丢弃,这里补一条去重告警(issue #288 衍生 / #294) + OperatorIdentityWarnLog.getInstance().warnOnce(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) { + List operators = FlowOperatorLocalThreadCache.getInstance() + .find(ids, identity, (idList) -> flowOperatorGateway.findByIds(idList, identity)); + if (OperatorIdentity.of(identity).isDefault()) { + return operators; + } + // 下游未覆盖带身份的批量重载时,批量结果会退化为默认身份(findByIds(ids) 的返回), + // 这里逐条回退到单条按身份取人:正确实现会返回带身份的副本,未实现则由 OperatorIdentityWarnLog 告警。 + // 不做这一层兜底时,批量路径会把身份静默丢弃,且不会产生任何日志(issue #288 评审修复)。 + Map operatorById = new HashMap<>(); + if (operators != null) { + for (IFlowOperator operator : operators) { + operatorById.put(operator.getUserId(), operator); + } + } + List result = new ArrayList<>(); + for (Long id : new LinkedHashSet<>(ids)) { + IFlowOperator operator = operatorById.get(id); + if (operator == null || !OperatorIdentity.of(operator).same(OperatorIdentity.of(identity))) { + operator = this.getFlowOperator(id, identity); + } + if (operator != null) { + result.add(operator); + } + } + return result; + } + } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/context/RepositoryHolderContext.java b/flow-engine-framework/src/main/java/com/codingapi/flow/context/RepositoryHolderContext.java index 079e7b38..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,11 +134,21 @@ 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); } + @Override + public IFlowOperator getOperatorById(long id, String identity) { + return GatewayContext.getInstance().getFlowOperator(id, identity); + } + @Override public FlowOperatorGateway getFlowOperatorGateway() { return new FlowOperatorGateway() { @@ -146,10 +157,20 @@ 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); } + + @Override + public List findByIds(List ids, String identity) { + return GatewayContext.getInstance().findByIds(ids, identity); + } }; } @@ -213,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/diagnostic/OperatorIdentityWarnLog.java b/flow-engine-framework/src/main/java/com/codingapi/flow/diagnostic/OperatorIdentityWarnLog.java new file mode 100644 index 00000000..3f60c7e2 --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/diagnostic/OperatorIdentityWarnLog.java @@ -0,0 +1,86 @@ +package com.codingapi.flow.diagnostic; + +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorKey; +import lombok.extern.slf4j.Slf4j; + +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * 身份透传效果告警(issue #288 衍生 / #294 / #311 P5)。 + * + *

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

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

状态归属:告警去重记录是实例字段而不是静态集合——全局静态可变状态会让测试互相污染, + * 并迫使代码暴露「清空缓存」这种只为测试服务的入口。需要隔离的场景直接 {@code new} 一个实例即可。 + */ +@Slf4j +public final class OperatorIdentityWarnLog { + + /** + * 告警去重记录的条目上限 + */ + private static final int MAX_WARN_KEYS = 256; + + private static final OperatorIdentityWarnLog INSTANCE = new OperatorIdentityWarnLog(); + + private final Set warnedKeys = ConcurrentHashMap.newKeySet(); + + /** + * 全局默认实例(生产使用) + * + * @return 告警器实例 + */ + public static OperatorIdentityWarnLog getInstance() { + return INSTANCE; + } + + /** + * 检查身份透传是否生效:请求的是非默认身份、但回查到操作者的身份为空时输出告警。 + * + * @param operatorId 人员 id + * @param requestedIdentity 请求声明的身份 + * @param resolved 回查到的操作者,可能为 {@code null} + * @return true 表示本次实际输出了告警(同一 {@code (人员, 身份)} 只会返回一次 true) + */ + public boolean warnOnce(long operatorId, String requestedIdentity, IFlowOperator resolved) { + if (!needWarn(requestedIdentity, resolved)) { + return false; + } + if (warnedKeys.size() >= MAX_WARN_KEYS) { + return false; + } + // 去重键就是参与人键,格式由 OperatorKey 唯一定义 + if (!warnedKeys.add(OperatorKey.of(operatorId, requestedIdentity).key())) { + return false; + } + log.warn("流程操作者身份未生效:人员[{}] 请求身份[{}],但回查到的操作者身份为空。" + + "请确认下游已覆盖 FlowOperatorGateway#get(id, identity) 与 IRepositoryHolder#getOperatorById(id, identity)," + + "否则同一人员的多身份将全部退化为默认身份(issue #288)。", + operatorId, OperatorIdentity.of(requestedIdentity).value()); + return true; + } + + /** + * 是否需要告警:请求身份非默认,且回查结果的身份为默认。 + * + * @param requestedIdentity 请求声明的身份 + * @param resolved 回查到的操作者 + * @return true 表示需要告警 + */ + static boolean needWarn(String requestedIdentity, IFlowOperator resolved) { + if (OperatorIdentity.of(requestedIdentity).isDefault()) { + return false; + } + if (resolved == null) { + return false; + } + return OperatorIdentity.of(resolved).isDefault(); + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/error/ErrorThrow.java b/flow-engine-framework/src/main/java/com/codingapi/flow/error/ErrorThrow.java index b0be709d..4bb8af11 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/error/ErrorThrow.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/error/ErrorThrow.java @@ -3,31 +3,119 @@ import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; import lombok.Getter; -import lombok.Setter; import java.util.List; /** * 异常流程配置,在节点没有匹配到人员时触发 - * 异常时可以指定跳转到的节点或者指定默认的审批人员,两者二选一,优先以跳转的节点为准 + *

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

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

+ * 提示信息优先使用流程配置的文案;未配置时回落为带节点名称的默认文案。 + * + * @param nodeId 节点 id + * @param nodeName 节点名称 + * @param message 流程配置的提示信息,可为空 + * @return exception + */ + public static FlowValidationException nextNodeOperatorEmpty(String nodeId, String nodeName, String message) { + String text = (message == null || message.isBlank()) + ? String.format("No operator matched for node '%s' (id: %s), the flow cannot continue", + nodeName, nodeId) + : message; + return new FlowValidationException("validation.node.operatorEmpty", text); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/gateway/FlowOperatorGateway.java b/flow-engine-framework/src/main/java/com/codingapi/flow/gateway/FlowOperatorGateway.java index 24f15795..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 @@ -9,8 +9,51 @@ */ 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); + /** + * 按人员 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/manager/OperatorManager.java b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/OperatorManager.java index 943da887..8b21db2b 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/manager/OperatorManager.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/OperatorManager.java @@ -1,49 +1,67 @@ package com.codingapi.flow.manager; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import lombok.Getter; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; import java.util.Objects; +import java.util.Set; /** - * 节点操作者管理 + * 节点操作者管理(参与人集合)。 + * + *

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

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

按 {@code (userId, identity)} 严格匹配,不受运行时匹配模式影响: + * 这里回答的是「节点配置的人里有没有他」。配置项本身就是「某个人以某个身份参与」, + * 放宽到只比 id 会让「配置了部门A的张三」被部门B的张三命中,属于越权。 + * + * @param operator 待判定的操作者 + * @return true 表示在配置的参与人集合中 + */ public boolean match(IFlowOperator operator) { - return operatorIds.contains(operator.getUserId()); - } - - - public IFlowOperator getOperator(long userId) { - for (IFlowOperator operator : operators) { - if (operator.getUserId() == userId) { - return operator; - } + if (operator == null) { + return false; } - return null; + return keys.contains(OperatorKey.of(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..cef81b6c 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/manager/WorkflowStrategyManager.java @@ -2,6 +2,9 @@ import com.codingapi.flow.exception.FlowStateException; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityContext; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.strategy.workflow.IWorkflowStrategy; import com.codingapi.flow.strategy.workflow.InterfereStrategy; import lombok.AllArgsConstructor; @@ -45,19 +48,39 @@ public T getStrategy(Class clazz) { } /** - * 验证操作者 + * 验证操作者(默认身份) * * @param currentOperator 当前操作者 * @param recordOperatorId 记录操作者id */ public void verifyOperator(IFlowOperator currentOperator, long recordOperatorId) { + this.verifyOperator(currentOperator, recordOperatorId, OperatorIdentity.DEFAULT.value()); + } + + /** + * 验证操作者。 + * + *

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

    + *
  • {@code STRICT}:参与人由 {@code (userId, identity)} 共同决定(issue #288);
  • + *
  • {@code USER_ONLY}:只校验 userId,同一人换身份依然可以办理自己的待办。
  • + *
+ * + * @param currentOperator 当前操作者 + * @param recordOperatorId 记录操作者id + * @param recordOperatorIdentity 记录操作者身份标识,{@code null} 与空串等价 + */ + public void verifyOperator(IFlowOperator currentOperator, long recordOperatorId, String recordOperatorIdentity) { + OperatorKey currentKey = currentOperator == null ? null : OperatorKey.of(currentOperator); + boolean operatorMatched = OperatorIdentityContext.getInstance() + .matches(currentKey, OperatorKey.of(recordOperatorId, recordOperatorIdentity)); 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..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) { @@ -77,10 +78,20 @@ 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); } + + @Override + public List findByIds(List ids, String identity) { + return GatewayContext.getInstance().findByIds(ids, identity); + } }; } @@ -109,11 +120,21 @@ 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); } + @Override + public IFlowOperator getOperatorById(long id, String identity) { + return this.flowOperatorGateway.get(id, identity); + } + @Override public void saveDelayTask(DelayTask delayTask) { this.delayTaskRepository.save(delayTask); @@ -181,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..2636157f 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowRecordRepositoryMockImpl.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowRecordRepositoryMockImpl.java @@ -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.of(identity).value(); + return cache.values().stream() + .filter(flowRecord -> flowRecord.getCurrentOperatorId() == operatorId + && flowRecord.isDone() + && OperatorIdentity.of(flowRecord.getCurrentOperatorIdentity()).same(OperatorIdentity.of(normalized))) + .toList(); + } + + /** + * 按 {@code (审批人, 身份)} 查询抄送(issue #288 衍生 / #291),口径与 JPA 一致。 + */ + public List findNotifyByOperator(long operatorId, String identity) { + String normalized = OperatorIdentity.of(identity).value(); + return cache.values().stream() + .filter(flowRecord -> flowRecord.getCurrentOperatorId() == operatorId + && flowRecord.isNotify() + && !flowRecord.isRevoked() + && !flowRecord.isHidden() + && OperatorIdentity.of(flowRecord.getCurrentOperatorIdentity()).same(OperatorIdentity.of(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..a48940ce 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowTodoRecordRepositoryMockImpl.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowTodoRecordRepositoryMockImpl.java @@ -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.of(identity).value(); + return cache.values().stream() + .filter(record -> record.getCurrentOperatorId() == operatorId + && OperatorIdentity.of(record.getCurrentOperatorIdentity()).same(OperatorIdentity.of(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/node/BaseAuditNode.java b/flow-engine-framework/src/main/java/com/codingapi/flow/node/BaseAuditNode.java index 9dd9bf2f..6932e3af 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/node/BaseAuditNode.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/node/BaseAuditNode.java @@ -11,6 +11,9 @@ 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.operator.OperatorIdentityContext; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.strategy.node.MultiOperatorAuditStrategy; @@ -232,6 +235,11 @@ private List generateCurrentRecords(FlowSession session, Set if(errorThrow==null){ throw FlowValidationException.nodeRequired("errorTrigger"); } + // 异常提示(issue #296):阻断本次操作并把提示信息交给调用方,避免默认「回退至开始节点」 + // 造成发起人误以为流程已正常流转 + if(errorThrow.isPrompt()){ + throw FlowValidationException.nextNodeOperatorEmpty(this.getId(), this.getName(), errorThrow.getMessage()); + } if(errorThrow.isNode()){ IFlowNode errorNode = errorThrow.getNode(); // 抄送/子流程节点不产生有效记录,跳转会静默停滞 @@ -249,6 +257,10 @@ private List generateCurrentRecords(FlowSession session, Set } return errorNode.generateCurrentRecords(errorSession); }else { + // 指定人员兜底:结果为空视为配置无效,否则会生成空记录让流程静默停滞 + if (!errorThrow.hasOperators()) { + throw FlowValidationException.nodeRequired("errorTrigger"); + } operatorManager = new OperatorManager(errorThrow.getOperators()); } } @@ -261,12 +273,16 @@ private List generateCurrentRecords(FlowSession session, Set // 即当前节点待办记录"处理(resetAddAudit、先清后存等),自动通过的留痕记录落库/事件副作用会破坏其语义。 if (nodeStrategyManager.isSameOperatorAutoPass() && session.getCurrentOperator() != null - && session.getCurrentOperator().getUserId() == session.getSubmitOperatorId() + && OperatorIdentityContext.getInstance().matches( + OperatorKey.of(session.getCurrentOperator()), + OperatorKey.of(session.getSubmitOperatorId(), OperatorIdentity.of(session.getSubmitOperator()).value())) && session.getCurrentAction() != null && ActionType.PASS.name().equalsIgnoreCase(session.getCurrentAction().type())) { long submitOperatorId = session.getSubmitOperatorId(); + String submitOperatorIdentity = OperatorIdentity.of(session.getSubmitOperator()).value(); operators = operators.stream() - .filter(operator -> operator.getUserId() != submitOperatorId) + .filter(operator -> !OperatorIdentityContext.getInstance() + .matches(OperatorKey.of(operator), OperatorKey.of(submitOperatorId, submitOperatorIdentity))) .toList(); // 全部审批人均与提交人一致,当前节点自动通过:生成留痕记录并继续向后续节点生成记录(issue #226) if (operators.isEmpty()) { diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/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/operator/IFlowOperator.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java index b868fb69..4ebca4ce 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/IFlowOperator.java @@ -5,6 +5,9 @@ /** * 流程参与用户 + * + *

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

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

    + *
  • 返回空串或 null 表示「默认身份」,与未启用多身份的历史行为完全一致;
  • + *
  • 同一用户的不同身份在流程中被视为不同的参与人。
  • + *
+ * + * @return 身份标识,默认返回空串 + * @see OperatorIdentity + */ + default String getIdentity() { + return OperatorIdentity.DEFAULT.value(); + } + + + /** * 是否流程管理员 * 流程管理员可以强制干预流程 diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java new file mode 100644 index 00000000..2d4b4ac3 --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentity.java @@ -0,0 +1,157 @@ +package com.codingapi.flow.operator; + +import com.codingapi.flow.exception.FlowValidationException; + +import java.util.Objects; + +/** + * 身份标识(值对象)。 + * + *

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

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

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

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

实体列宽与本常量对齐,避免「自动建表 255 / 手工建表 64」两种环境行为不一致导致截断。 + */ + public static final int MAX_LENGTH = 64; + + /** + * 身份保留字符:供各类「身份参与拼接」的键格式使用(当前为待办合并键的身份后缀)。 + * + *

身份本身不允许包含该字符,否则「身份」与「键后缀」语义无法区分。 + * 该常量是本仓库唯一声明,键模型({@code TodoMergeKey})引用它,不再各自声明。 + */ + public static final String RESERVED_KEY_MARK = "#"; + + private final String value; + + private OperatorIdentity(String value) { + this.value = value; + } + + /** + * 由原始值构造身份,{@code null} 与空串归一化为 {@link #DEFAULT}。 + * + * @param raw 原始身份标识 + * @return 身份值对象,不为 {@code null} + */ + public static OperatorIdentity of(String raw) { + if (raw == null || raw.isEmpty()) { + return DEFAULT; + } + return new OperatorIdentity(raw); + } + + /** + * 读取操作者的身份,操作者为 {@code null} 时返回默认身份。 + * + * @param operator 流程参与用户,可为 {@code null} + * @return 身份值对象 + */ + public static OperatorIdentity of(IFlowOperator operator) { + return operator == null ? DEFAULT : of(operator.getIdentity()); + } + + /** + * 身份原始值(已归一化,不为 {@code null})。 + * + * @return 身份标识,默认身份为空串 + */ + public String value() { + return value; + } + + /** + * 是否为默认身份。 + * + * @return true 表示默认身份(原 {@code null} 或空串) + */ + public boolean isDefault() { + return value.isEmpty(); + } + + /** + * 校验身份是否可作为持久化值(写入 / 落库前调用)。 + * + *

约束: + *

    + *
  • 长度不超过 {@link #MAX_LENGTH},与 DDL 列宽一致;
  • + *
  • 不允许包含 {@link #RESERVED_KEY_MARK},否则与待办合并键的后缀语义冲突;
  • + *
  • 不允许包含控制字符,避免污染内部以控制字符拼接的缓存键。
  • + *
+ * + * @return 校验通过的自身,便于链式取值 + * @throws FlowValidationException 身份标识不合法 + */ + public OperatorIdentity validate() { + if (value.length() > MAX_LENGTH) { + throw FlowValidationException.operatorIdentityTooLong(value.length(), MAX_LENGTH); + } + if (value.contains(RESERVED_KEY_MARK)) { + throw FlowValidationException.operatorIdentityInvalid(RESERVED_KEY_MARK); + } + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (Character.isISOControl(c)) { + throw FlowValidationException.operatorIdentityInvalid("\\u" + Integer.toHexString(c)); + } + } + return this; + } + + /** + * 判断是否为同一身份({@code null} 与空串等价由 {@link #of(String)} 保证)。 + * + * @param other 另一个身份 + * @return true 表示同一身份 + */ + public boolean same(OperatorIdentity other) { + return other != null && value.equals(other.value); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof OperatorIdentity that)) { + return false; + } + return value.equals(that.value); + } + + @Override + public int hashCode() { + return Objects.hash(value); + } + + @Override + public String toString() { + return value; + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityContext.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityContext.java new file mode 100644 index 00000000..f7c0aeab --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorIdentityContext.java @@ -0,0 +1,88 @@ +package com.codingapi.flow.operator; + +/** + * 身份匹配上下文(原 {@code OperatorIdentityPolicy},issue #297 / #311 P3)。 + * + *

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

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

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

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

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

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

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

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

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

该判定决定「参与人键」与「待办合并键」是否携带身份后缀,是键模型的唯一入参, + * 调用方不得自行按模式拼键。 + * + * @return true 表示参与人由 {@code (人员id, 身份)} 共同标识 + */ + public abstract boolean identityDistinguishes(); + + /** + * 宽松解析配置值,兼容 {@code USER_ONLY}、{@code user-only}、{@code user_only} 等写法。 + * + * @param value 配置值 + * @return 匹配模式,无法识别时返回 {@code null} + */ + public static OperatorIdentityMatchMode parse(String value) { + if (value == null || value.isBlank()) { + return null; + } + String normalized = value.trim().replace('-', '_').toUpperCase(); + for (OperatorIdentityMatchMode mode : values()) { + if (mode.name().equals(normalized)) { + return mode; + } + } + return null; + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java new file mode 100644 index 00000000..ba5d4994 --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorKey.java @@ -0,0 +1,123 @@ +package com.codingapi.flow.operator; + +/** + * 操作者标识二元组 {@code (人员id, 身份)}(issue #288 衍生 / #292)。 + * + *

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

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

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

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

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

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

{@link OperatorIdentityMatchMode#USER_ONLY} 下同一个人只算一个参与人,键退化为人员 id; + * 严格口径下按 {@code (人员id, 身份)} 区分。调用方不得自行判断模式后拼键。 + * + * @param mode 匹配模式 + * @return 参与人键 + */ + public String key(OperatorIdentityMatchMode mode) { + if (!mode.identityDistinguishes()) { + return String.valueOf(operatorId); + } + return operatorId + KEY_SEPARATOR + identity; + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorSelections.java b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorSelections.java new file mode 100644 index 00000000..658c671a --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/operator/OperatorSelections.java @@ -0,0 +1,111 @@ +package com.codingapi.flow.operator; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * 操作人选择集合:节点 id → 选定的参与人列表。 + * + *

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

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

优先级是整体的,不是逐节点的:只要携带身份的分配非空,就以它为准, + * 仅人员 id 的分配整体忽略。这与「请求只会用其中一种形式」的调用约定一致。 + * + * @param byOperators 携带身份的分配,可为 {@code null} + * @param byOperatorIds 仅人员 id 的分配,可为 {@code null} + * @return 选择集合 + */ + public static OperatorSelections of(Map> byOperators, + Map> byOperatorIds) { + if (byOperators != null && !byOperators.isEmpty()) { + return new OperatorSelections(copy(byOperators)); + } + if (byOperatorIds == null || byOperatorIds.isEmpty()) { + return empty(); + } + Map> converted = new LinkedHashMap<>(); + byOperatorIds.forEach((nodeId, operatorIds) -> { + if (operatorIds == null || operatorIds.isEmpty()) { + return; + } + converted.put(nodeId, operatorIds.stream().map(OperatorKey::ofDefault).toList()); + }); + return new OperatorSelections(converted); + } + + /** + * 空选择 + * + * @return 空集合 + */ + public static OperatorSelections empty() { + return new OperatorSelections(Map.of()); + } + + public boolean isEmpty() { + return byNode.isEmpty(); + } + + /** + * 该节点是否有选择 + * + * @param nodeId 节点 id + * @return true 表示该节点选了人 + */ + public boolean hasSelection(String nodeId) { + List selected = byNode.get(nodeId); + return selected != null && !selected.isEmpty(); + } + + /** + * 全部节点 id + * + * @return 节点 id 集合,保持插入顺序 + */ + public Set nodeIds() { + return new LinkedHashSet<>(byNode.keySet()); + } + + /** + * 该节点选择的参与人 + * + * @param nodeId 节点 id + * @return 参与人列表,无选择时返回空列表 + */ + public List of(String nodeId) { + List selected = byNode.get(nodeId); + return selected == null ? List.of() : selected; + } + + private static Map> copy(Map> source) { + Map> copied = new LinkedHashMap<>(); + source.forEach((nodeId, operators) -> { + if (operators == null || operators.isEmpty()) { + return; + } + copied.put(nodeId, List.copyOf(operators)); + }); + return Collections.unmodifiableMap(copied); + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/body/FlowAdviceBody.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/body/FlowAdviceBody.java index 4096c314..a0f6775f 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/body/FlowAdviceBody.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/body/FlowAdviceBody.java @@ -2,6 +2,8 @@ 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; @@ -45,6 +47,14 @@ public class FlowAdviceBody { */ private long operatorId; + /** + * 操作者身份标识(issue #288) + *

同一人员可能以不同身份审批同一流程,框架只透传该标识;为空表示默认身份。 + * + * @see com.codingapi.flow.operator.OperatorIdentity + */ + private String operatorIdentity; + /** * 退回节点 */ @@ -57,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; @@ -72,11 +89,13 @@ 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()).value(); this.signKey = flowSession.getAdvice().getSignKey(); this.backNodeId = flowSession.getAdvice().getBackNode() != null ? flowSession.getAdvice().getBackNode().getId() : null; this.manualNodeId = flowSession.getAdvice().getManualNode() != null ? flowSession.getAdvice().getManualNode().getId() : null; 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 b0798384..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 @@ -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(); @@ -54,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 f6bcc001..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; @@ -33,6 +34,12 @@ public class FlowCreateRequest { */ private long operatorId; + /** + * 操作者身份标识(issue #288) + *

框架不解释身份语义,只透传;为空表示默认身份,与历史行为一致。 + */ + private String operatorIdentity; + /** * 父流程id,系统自动赋值 */ @@ -41,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; + /** * 手动传入的流程标题(子流程实例区分用);为空时回落流程定义标题 */ @@ -55,7 +70,9 @@ 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()); + adviceBody.setOperatorSelectOperators(this.getOperatorSelectOperators()); flowActionRequest.setAdvice(adviceBody); flowActionRequest.verify(); return flowActionRequest; 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..f470e59c 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDeleteRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDeleteRequest.java @@ -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.value()); + } + 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..15f71b84 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDetailRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowDetailRequest.java @@ -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.value()); } public FlowDetailRequest(String id, long operatorId) { + this(id, operatorId, OperatorIdentity.DEFAULT.value()); + } + + 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..6fb11ca7 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowProcessNodeRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowProcessNodeRequest.java @@ -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.value(), formData); } public FlowProcessNodeRequest(String id, long operatorId, Map formData) { + this(id, operatorId, OperatorIdentity.DEFAULT.value(), 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..b7f71fde 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowRevokeRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowRevokeRequest.java @@ -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.value()); + } + 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..ee5ab335 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowUrgeRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowUrgeRequest.java @@ -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.value()); + } + public void verify() { if (recordId <= 0) { throw FlowValidationException.required("recordId"); 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..cf75ffbf 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowContent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowContent.java @@ -8,6 +8,8 @@ import com.codingapi.flow.manager.NodeStrategyManager; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentityContext; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.workflow.Workflow; @@ -309,17 +311,41 @@ private List loadCurrentNodeOperators(FlowSession flowSession) { if (currentRecord == null || currentNodeRecords == null) { return List.of(); } - long currentOperatorId = currentRecord.getCurrentOperatorId(); - Map operators = new LinkedHashMap<>(); + return resolveCurrentNodeOperators(currentRecord, currentNodeRecords); + } + + /** + * 计算当前节点实例中的待审批人员(按参与人去重,排除当前操作人)。 + * + *

去重口径由身份匹配策略决定(issue #297):{@code STRICT} 下参与人由 + * {@code (人员id, 身份)} 共同标识(issue #288 衍生 / #290);{@code USER_ONLY} 下同一个人 + * 只算一个参与人。 + * + * @param currentRecord 当前流程记录(用于取当前操作人与其身份) + * @param currentNodeRecords 当前节点的流程记录 + * @return 待审批人员列表(保持记录顺序) + */ + static List resolveCurrentNodeOperators(FlowRecord currentRecord, List currentNodeRecords) { + 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; + } + // 排除当前操作人时按身份匹配策略判断(issue #297):USER_ONLY 下同一人换身份仍视为本人 + if (OperatorIdentityContext.getInstance() + .matches(currentRecord.currentOperatorKey(), record.currentOperatorKey())) { continue; } - operators.putIfAbsent(record.getCurrentOperatorId(), - new FlowOperator(record.getCurrentOperatorId(), record.getCurrentOperatorName())); + // 去重键就是参与人键:USER_ONLY 下同一个人只展示一次,STRICT 下按 (人员id, 身份) 区分。 + // 键格式由 OperatorKey 唯一定义,这里不再判断模式后自行拼接。 + String operatorKey = record.currentOperatorKey() + .key(OperatorIdentityContext.getInstance().matchMode()); + operators.putIfAbsent(operatorKey, + new FlowOperator(record.getCurrentOperatorId(), record.getCurrentOperatorName(), + record.getCurrentOperatorIdentity())); } return List.copyOf(operators.values()); } @@ -336,7 +362,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 +379,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 +405,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..37d2a2af 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowOperator.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowOperator.java @@ -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.value()); + } + + public FlowOperator(long id, String name, String identity) { + this.id = id; + this.name = name; + this.identity = OperatorIdentity.of(identity).value(); + } + public FlowOperator(IFlowOperator flowOperator) { this.id = flowOperator.getUserId(); this.name = flowOperator.getName(); + this.identity = OperatorIdentity.of(flowOperator).value(); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowRecordContent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowRecordContent.java index 37739d88..01eb9d44 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowRecordContent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/pojo/response/FlowRecordContent.java @@ -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,26 @@ public class FlowRecordContent { */ private String createOperatorName; + /** + * 发起者身份标识(issue #288) + */ + private String createOperatorIdentity; + + /** + * 办理人Id(issue #306),记录办结时的实际办理人 + */ + private Long handleOperatorId; + + /** + * 办理人名称(issue #306) + */ + private String handleOperatorName; + + /** + * 办理人身份标识(issue #306),空串表示默认身份 + */ + private String handleOperatorIdentity; + /** * 合并记录id,当存在合并记录数据时待办记录数量不会增加,内容会更新至最新的待办数据信息。 * {@link FlowRecord#getTodoKey()} @@ -137,11 +168,17 @@ public static FlowRecordContent convert(FlowRecord record){ content.setReadTime(record.getReadTime()); content.setCurrentOperatorId(record.getCurrentOperatorId()); content.setCurrentOperatorName(record.getCurrentOperatorName()); + content.setCurrentOperatorIdentity(OperatorIdentity.of(record.getCurrentOperatorIdentity()).value()); content.setSubmitOperatorId(record.getSubmitOperatorId()); content.setSubmitOperatorName(record.getSubmitOperatorName()); + content.setSubmitOperatorIdentity(OperatorIdentity.of(record.getSubmitOperatorIdentity()).value()); content.setCreateTime(record.getCreateTime()); content.setCreateOperatorId(record.getCreateOperatorId()); content.setCreateOperatorName(record.getCreateOperatorName()); + content.setCreateOperatorIdentity(OperatorIdentity.of(record.getCreateOperatorIdentity()).value()); + content.setHandleOperatorId(record.getHandleOperatorId()); + content.setHandleOperatorName(record.getHandleOperatorName()); + content.setHandleOperatorIdentity(OperatorIdentity.of(record.getHandleOperatorIdentity()).value()); content.setMergeable(record.isMergeable()); content.setRecordId(record.getId()); content.setTimeoutTime(record.getTimeoutTime()); @@ -164,11 +201,14 @@ public static FlowRecordContent convert(FlowTodoRecord todoRecord){ content.setReadTime(todoRecord.getReadTime()); content.setCurrentOperatorId(todoRecord.getCurrentOperatorId()); content.setCurrentOperatorName(todoRecord.getCurrentOperatorName()); + content.setCurrentOperatorIdentity(OperatorIdentity.of(todoRecord.getCurrentOperatorIdentity()).value()); content.setSubmitOperatorId(todoRecord.getSubmitOperatorId()); content.setSubmitOperatorName(todoRecord.getSubmitOperatorName()); + content.setSubmitOperatorIdentity(OperatorIdentity.of(todoRecord.getSubmitOperatorIdentity()).value()); content.setCreateTime(todoRecord.getCreateTime()); content.setCreateOperatorId(todoRecord.getCreateOperatorId()); content.setCreateOperatorName(todoRecord.getCreateOperatorName()); + content.setCreateOperatorIdentity(OperatorIdentity.of(todoRecord.getCreateOperatorIdentity()).value()); content.setTodoKey(todoRecord.getTodoKey()); content.setMargeCount(todoRecord.getMargeCount()); content.setMergeable(todoRecord.isMergeable()); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/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 bd0fa18e..cd00624a 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowRecord.java @@ -1,6 +1,7 @@ package com.codingapi.flow.record; import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.exception.FlowStateException; import com.codingapi.flow.exception.FlowValidationException; import com.codingapi.flow.form.FormData; import com.codingapi.flow.generator.FlowIDGeneratorGatewayContext; @@ -9,6 +10,10 @@ 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.operator.OperatorIdentityMatchMode; +import com.codingapi.flow.operator.OperatorIdentityContext; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.session.FlowAdvice; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; @@ -43,6 +48,11 @@ public class FlowRecord { public static int SATE_FLOW_ERROR = 3; public static int SATE_FLOW_DELETE = 4; + /** + * 待办合并键中身份后缀的分隔符(issue #288)。 + *

仅在身份非空时追加,默认身份不使用,保证存量键格式不变。 + */ + /** * 记录id */ @@ -266,6 +276,53 @@ 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; + + /** + * 办理人Id(issue #306) + *

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

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

合并依据由 {@link RecordMergeStrategy.MergeType} 决定: @@ -275,19 +332,32 @@ public class FlowRecord { *

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

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

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

    模式切换后存量待办的键仍为旧格式,合并组会一分为二,属预期行为: + * 需要收拢时执行 {@code FlowTodoMigrateService} 重建待办快照即可。 */ public String getTodoKey() { - if (mergeable) { - long mergeOperatorId; - switch (mergeType) { - case CREATOR -> mergeOperatorId = createOperatorId; - case SUBMITTER -> mergeOperatorId = submitOperatorId; - default -> mergeOperatorId = currentOperatorId; - } - return String.format("%s-%s-%s", mergeOperatorId, workRuntimeId, nodeId); - } else { + if (!mergeable) { return String.valueOf(id); } + // 「谁参与合并」是领域决策,留在这里;「键怎么拼」是键格式,交给 TodoMergeKey。 + OperatorKey mergeOperator = switch (mergeType) { + case CREATOR -> OperatorKey.of(createOperatorId, createOperatorIdentity); + case SUBMITTER -> OperatorKey.of(submitOperatorId, submitOperatorIdentity); + default -> OperatorKey.of(currentOperatorId, currentOperatorIdentity); + }; + return TodoMergeKey.of(mergeOperator, workRuntimeId, nodeId, OperatorIdentityContext.getInstance().matchMode()).value(); } @@ -326,12 +396,18 @@ public FlowRecord(FlowSession flowSession, int nodeOrder) { this.processId = FlowIDGeneratorGatewayContext.getInstance().generateProcessId(); this.createOperatorId = flowSession.getCreatedOperator().getUserId(); this.createOperatorName = flowSession.getCreatedOperator().getName(); + this.createOperatorIdentity = OperatorIdentity.of(flowSession.getCreatedOperator()).value(); + // 身份字段统一以空串兜底,避免出现 null 与空串两种「默认身份」表达 + this.forwardOperatorIdentity = OperatorIdentity.DEFAULT.value(); + this.interferedOperatorIdentity = OperatorIdentity.DEFAULT.value(); + this.handleOperatorIdentity = OperatorIdentity.DEFAULT.value(); // 是否转交之后的人来审批的判断 if (currentOperator.equals(sourceOperator)) { this.forwardOperatorId = 0; } else { this.forwardOperatorId = sourceOperator.getUserId(); this.forwardOperatorName = sourceOperator.getName(); + this.forwardOperatorIdentity = OperatorIdentity.of(sourceOperator).value(); } this.recordState = SATE_RECORD_TODO; this.actionId = action.id(); @@ -340,9 +416,11 @@ public FlowRecord(FlowSession flowSession, int nodeOrder) { this.currentOperatorId = currentOperator.getUserId(); this.currentOperatorName = currentOperator.getName(); + this.currentOperatorIdentity = OperatorIdentity.of(currentOperator).value(); this.submitOperatorId = flowSession.getSubmitOperatorId(); this.submitOperatorName = flowSession.getSubmitOperatorName(); + this.submitOperatorIdentity = OperatorIdentity.of(flowSession.getSubmitOperator()).value(); this.advice = flowSession.getAdvice().getAdvice(); this.signKey = flowSession.getAdvice().getSignKey(); @@ -485,6 +563,33 @@ public void verify() { } } + /** + * 记录上「当前办理人」的参与人标识。 + * + *

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

    撤回 / 催办 / 删除 / 子流程重置四个入口共用这一条领域规则(issue #297): + * 身份是否参与判定由 {@link OperatorIdentityContext} 统一控制, + * 各服务不再各自比较 {@code operatorId + identity}。 + * + * @param operator 请求发起人标识 + */ + public void verifyOperator(OperatorKey operator) { + if (!OperatorIdentityContext.getInstance().matches(operator, currentOperatorKey())) { + throw FlowStateException.operatorNotMatch(); + } + } + /** * 是否异常 */ @@ -555,10 +660,15 @@ 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) { + // 设置流程干预人信息,流程干预只能由流程管理员才能操作。 + // 是否属于「他人代办」由身份匹配策略决定(issue #297):USER_ONLY 下同一人换身份办理不算干预, + // STRICT 下仍按 (userId, identity) 判定(issue #288)。 + OperatorKey currentOperator = flowSession.getCurrentOperator() == null + ? null : OperatorKey.of(flowSession.getCurrentOperator()); + if (!OperatorIdentityContext.getInstance().matches(currentOperator, currentOperatorKey())) { this.interferedOperatorId = flowSession.getCurrentOperator().getUserId(); this.interferedOperatorName = flowSession.getCurrentOperator().getName(); + this.interferedOperatorIdentity = OperatorIdentity.of(flowSession.getCurrentOperator()).value(); } if (flowAdvice != null) { @@ -567,6 +677,28 @@ public void update(FlowSession flowSession, boolean pass) { } } + /** + * 记录本次办理人(issue #306)。 + * + *

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

    不修改 {@link #currentOperatorId} / {@link #currentOperatorIdentity}: + * 待办归属身份在办结后仍需保留(见 docs/Integration/operator-identity.md §4.4)。 + * + * @param operator 本次实际办理人 + */ + public void markHandleOperator(IFlowOperator operator) { + if (operator == null) { + return; + } + this.handleOperatorId = operator.getUserId(); + this.handleOperatorName = operator.getName(); + this.handleOperatorIdentity = OperatorIdentity.of(operator).value(); + } + public void clearNotify(){ this.readable = false; this.readTime = 0; @@ -574,6 +706,8 @@ public void clearNotify(){ this.signKey = null; this.notify = true; this.forwardOperatorId = 0; + // 转交身份必须同步清零,否则身份会残留在记录上,被后续复用带出错误的参与人身份(issue #288 衍生 / #294) + this.forwardOperatorIdentity = OperatorIdentity.DEFAULT.value(); } @@ -694,6 +828,7 @@ public FlowRecord create(FlowSession flowSession) { FlowRecord flowRecord = new FlowRecord(flowSession, 0); flowRecord.currentOperatorId = flowSession.getCurrentOperator().getUserId(); flowRecord.currentOperatorName = flowSession.getCurrentOperator().getName(); + flowRecord.currentOperatorIdentity = OperatorIdentity.of(flowSession.getCurrentOperator()).value(); return flowRecord; } @@ -734,6 +869,18 @@ public void newRecord() { this.setAdvice(null); this.setSignKey(null); this.setActionId(null); + // 新记录尚未被办理,不能继承上游记录的办理人信息(issue #306) + this.clearHandleOperator(); + } + + /** + * 清空办理人信息(issue #306)。 + *

    记录回到「未办理」状态时调用,避免复用记录对象时把上一位办理人带到新的待办上。 + */ + public void clearHandleOperator() { + this.handleOperatorId = 0; + this.handleOperatorName = null; + this.handleOperatorIdentity = OperatorIdentity.DEFAULT.value(); } /** diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowTodoRecord.java b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowTodoRecord.java index 09206513..ce847a13 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowTodoRecord.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/record/FlowTodoRecord.java @@ -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.of(flowRecord.getCurrentOperatorIdentity()).value(); + this.submitOperatorIdentity = OperatorIdentity.of(flowRecord.getSubmitOperatorIdentity()).value(); + this.createOperatorIdentity = OperatorIdentity.of(flowRecord.getCreateOperatorIdentity()).value(); this.todoKey = flowRecord.getTodoKey(); this.mergeable = flowRecord.isMergeable(); this.recordId = flowRecord.getId(); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/record/TodoMergeKey.java b/flow-engine-framework/src/main/java/com/codingapi/flow/record/TodoMergeKey.java new file mode 100644 index 00000000..0b72d50d --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/record/TodoMergeKey.java @@ -0,0 +1,68 @@ +package com.codingapi.flow.record; + +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityMatchMode; +import com.codingapi.flow.operator.OperatorKey; + +/** + * 待办合并键(issue #295 / #311 P2)。 + * + *

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

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

    格式: + *

      + *
    • 基础段 {@code {人员id}-{workRuntimeId}-{nodeId}}(历史格式,不可变);
    • + *
    • {@link OperatorIdentityMatchMode#STRICT} 且身份非默认时追加 {@code #identity};
    • + *
    • 默认身份不追加,保证升级过程中存量待办的合并关系不断裂。
    • + *
    + * + * @param operator 参与人标识 + * @param workRuntimeId 流程运行时实例 id + * @param nodeId 节点 id + * @param mode 参与人判定模式,决定键是否区分身份 + */ +public record TodoMergeKey(OperatorKey operator, long workRuntimeId, String nodeId, OperatorIdentityMatchMode mode) { + + /** + * 基础段之间的分隔符 + */ + static final String SEGMENT_SEPARATOR = "-"; + + /** + * 构建待办合并键 + * + * @param operator 参与人标识 + * @param workRuntimeId 流程运行时实例 id + * @param nodeId 节点 id + * @param mode 参与人判定模式 + * @return 待办合并键 + */ + public static TodoMergeKey of(OperatorKey operator, long workRuntimeId, String nodeId, + OperatorIdentityMatchMode mode) { + return new TodoMergeKey(operator, workRuntimeId, nodeId, mode); + } + + /** + * 生成待办合并键字符串 + * + * @return 合并键 + */ + public String value() { + String base = operator.operatorId() + SEGMENT_SEPARATOR + workRuntimeId + SEGMENT_SEPARATOR + nodeId; + if (!mode.identityDistinguishes()) { + // 按人合并:身份只是脚本与留痕信息,参与合并会让同一人出现多条待办 + return base; + } + if (operator.identity().isEmpty()) { + // 默认身份保持历史键格式,保证存量待办不断裂 + return base; + } + return base + OperatorIdentity.RESERVED_KEY_MARK + operator.identity(); + } +} diff --git a/flow-engine-framework/src/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/script/ScriptDefaultConstants.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/ScriptDefaultConstants.java index 1b944ae5..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 @@ -48,13 +48,17 @@ def run(request){ """; /** - * 默认异常触发脚本 + * 默认异常触发脚本(issue #296) + *

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

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

      + *
    • {@code Map}:{@code [type:'prompt', message:'...']} 异常提示,或 {@code [type:'node', node:'节点id']} / + * {@code [type:'operators', operators:[1,2]]} 显式声明类型;
    • + *
    • {@code String}:跳转节点 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; @@ -32,30 +48,71 @@ public ErrorThrow execute(FlowSession session) { Object value = FlowScriptRuntimeContext.getInstance() .getGroovyScript(script) .invoke(Map.of("$bind", new GroovyScriptBind(FlowScriptContext.getInstance())), request); - if(value instanceof String){ - String nodeId = (String) value; + if (value instanceof Map map) { + return parseMap(session, map); + } + if (value instanceof String nodeId) { ErrorThrow errorThrow = new ErrorThrow(); errorThrow.setNode(session.getNode(nodeId)); return errorThrow; } - if(value instanceof List){ - List userIds =(List) value; - List operatorIds = new ArrayList<>(); - for(Object userId:userIds){ - operatorIds.add(Long.parseLong(String.valueOf(userId))); + if (value instanceof List operators) { + return parseOperators(session, operators); + } + + ErrorThrow errorThrow = new ErrorThrow(); + errorThrow.setOperators( + new OperatorScriptResultResolver(session.getRepositoryHolder(), SCRIPT_TYPE).resolve(value)); + return errorThrow; + + } + + /** + * 解析 Map 形式的返回值 + * + * @param session 当前会话 + * @param map 脚本返回值 + * @return 异常处理配置 + */ + private ErrorThrow parseMap(FlowSession session, Map map) { + String type = map.get("type") == null ? null : String.valueOf(map.get("type")); + if (ErrorThrow.Type.PROMPT.name().equalsIgnoreCase(type) || "prompt".equalsIgnoreCase(type)) { + Object message = map.get("message"); + return ErrorThrow.prompt(message == null ? null : String.valueOf(message)); + } + if (ErrorThrow.Type.NODE.name().equalsIgnoreCase(type)) { + Object nodeId = map.get("node"); + ErrorThrow errorThrow = new ErrorThrow(); + errorThrow.setNode(nodeId == null ? null : session.getNode(String.valueOf(nodeId))); + return errorThrow; + } + if (ErrorThrow.Type.OPERATORS.name().equalsIgnoreCase(type)) { + Object operators = map.get("operators"); + if (operators instanceof List userIds) { + return parseOperators(session, userIds); } + return new ErrorThrow(); + } + // 未声明 type 时按字段存在性推断:message 优先(提示),其次 node,最后 operators + if (map.get("message") != null) { + return ErrorThrow.prompt(String.valueOf(map.get("message"))); + } + if (map.get("node") != null) { ErrorThrow errorThrow = new ErrorThrow(); - errorThrow.setOperators(session.getRepositoryHolder().findOperatorByIds(operatorIds)); + errorThrow.setNode(session.getNode(String.valueOf(map.get("node")))); return errorThrow; } + if (map.get("operators") instanceof List userIds) { + return parseOperators(session, userIds); + } + return new ErrorThrow(); + } - long userId = Long.parseLong(String.valueOf(value)); + private ErrorThrow parseOperators(FlowSession session, List operators) { ErrorThrow errorThrow = new ErrorThrow(); - List operatorList = new ArrayList<>(); - operatorList.add(session.getRepositoryHolder().getOperatorById(userId)); - errorThrow.setOperators(operatorList); + errorThrow.setOperators( + new OperatorScriptResultResolver(session.getRepositoryHolder(), SCRIPT_TYPE).resolve(operators)); return errorThrow; - } /** diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/OperatorLoadScript.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/OperatorLoadScript.java index 9ee3780d..2b51e4b0 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/OperatorLoadScript.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/node/OperatorLoadScript.java @@ -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 new OperatorScriptResultResolver(session.getRepositoryHolder(), SCRIPT_TYPE).resolve(scriptResult); } /** diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptElement.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptElement.java new file mode 100644 index 00000000..e984ec6d --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptElement.java @@ -0,0 +1,74 @@ +package com.codingapi.flow.script.operator; + +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; + +import java.util.Map; + +/** + * 取人脚本返回值的元素(issue #303 / #311 P4)。 + * + *

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

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

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

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

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

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

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

      + *
    1. 归一化:集合 / 数组 / 单值 / {@code null} 统一为元素列表;
    2. + *
    3. 元素化:每个元素判定为 {@link OperatorScriptElement.Direct}(直接采用) + * 或 {@link OperatorScriptElement.Pending}(按身份回查);
    4. + *
    5. 批量回查:{@link PendingOperators} 按身份分组一次查完,再按脚本返回顺序还原。
    6. + *
    + * 允许同一列表内混用三种形态;输出顺序与脚本返回一致,保证多人审批的执行顺序稳定。 + * + * @see OperatorScriptElement + * @see PendingOperators + */ +public final class OperatorScriptResultResolver { + + private final IRepositoryHolder repositoryHolder; + + /** + * 脚本类型标识,仅用于异常上下文 + */ + private final String scriptType; + + /** + * @param repositoryHolder 仓储持有者,用于按身份回查参与人 + * @param scriptType 脚本类型标识(如 {@code operatorLoad} / {@code errorTrigger}),用于异常上下文 + */ + public OperatorScriptResultResolver(IRepositoryHolder repositoryHolder, String scriptType) { + this.repositoryHolder = repositoryHolder; + this.scriptType = scriptType; + } + + /** + * 解析脚本返回值。 + * + * @param scriptResult 脚本返回值,支持集合 / 数组 / 单值 / {@code null} + * @return 流程参与人列表,顺序与脚本返回一致 + * @throws FlowValidationException 返回值中存在不支持的元素 + */ + public List resolve(Object scriptResult) { + List elements = parse(scriptResult); + if (elements.isEmpty()) { + return List.of(); + } + PendingOperators pendingOperators = new PendingOperators(repositoryHolder); + for (OperatorScriptElement element : elements) { + if (element instanceof OperatorScriptElement.Pending pending) { + pendingOperators.collect(pending.key()); + } + } + Map resolved = pendingOperators.load(); + + List operators = new ArrayList<>(elements.size()); + for (OperatorScriptElement element : elements) { + IFlowOperator operator = element.resolveFrom(resolved); + if (operator != null) { + operators.add(operator); + } + } + return operators; + } + + /** + * 把脚本返回值解析为元素列表,跳过「无人员」的元素。 + */ + private List parse(Object scriptResult) { + List values = toValues(scriptResult); + List elements = new ArrayList<>(values.size()); + for (Object value : values) { + OperatorScriptElement element = toElement(value); + if (element != null && element.hasParticipant()) { + elements.add(element); + } + } + return elements; + } + + /** + * 单个返回值 → 元素;{@code null} 与空串返回 {@code null}(表示该元素无人员)。 + */ + private OperatorScriptElement toElement(Object value) { + if (value == null) { + return null; + } + if (value instanceof IFlowOperator operator) { + return new OperatorScriptElement.Direct(operator); + } + if (value instanceof OperatorKey key) { + return new OperatorScriptElement.Pending(key); + } + if (value instanceof Number number) { + return new OperatorScriptElement.Pending(OperatorKey.ofDefault(toUserId(number, value))); + } + if (value instanceof CharSequence text) { + String trimmed = text.toString().trim(); + if (trimmed.isEmpty()) { + return null; + } + if (!isNumeric(trimmed)) { + throw FlowValidationException.operatorScriptResultInvalid( + scriptType, value.getClass().getName(), trimmed); + } + return new OperatorScriptElement.Pending(OperatorKey.ofDefault(parseUserId(trimmed, value))); + } + throw FlowValidationException.operatorScriptResultInvalid( + scriptType, value.getClass().getName(), String.valueOf(value)); + } + + /** + * 把脚本返回值归一化为元素列表:集合 / 数组 / 单值 / {@code null} + */ + private List toValues(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 values = new ArrayList<>(length); + for (int i = 0; i < length; i++) { + values.add(Array.get(scriptResult, i)); + } + return values; + } + List values = new ArrayList<>(1); + values.add(scriptResult); + return values; + } + + private long toUserId(Number number, Object element) { + 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 long parseUserId(String value, Object element) { + try { + return Long.parseLong(value); + } catch (NumberFormatException e) { + throw FlowValidationException.operatorScriptResultInvalid( + scriptType, element.getClass().getName(), value); + } + } + + private 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; + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/PendingOperators.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/PendingOperators.java new file mode 100644 index 00000000..9e6dc06b --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/PendingOperators.java @@ -0,0 +1,74 @@ +package com.codingapi.flow.script.operator; + +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; +import com.codingapi.flow.session.IRepositoryHolder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * 待回查的参与人集合(issue #303 / #311 P4)。 + * + *

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

    它替代了原先散在解析器里的 {@code batchResolve(...)} 私有函数: + * 键集合与仓储都是它自己的状态,因此只需一个公有入口 {@link #load()}。 + */ +final class PendingOperators { + + private final IRepositoryHolder repositoryHolder; + + /** + * 用有序集合去重:同一 {@code (人员, 身份)} 只查一次,且保持首次出现顺序 + */ + private final Set keys = new LinkedHashSet<>(); + + PendingOperators(IRepositoryHolder repositoryHolder) { + this.repositoryHolder = repositoryHolder; + } + + /** + * 收集待回查的参与人标识 + * + * @param key 参与人标识 + */ + void collect(OperatorKey key) { + keys.add(key); + } + + /** + * 按身份分组批量回查。 + * + * @return 参与人索引,键为 {@link OperatorKey#key()} + */ + Map load() { + if (keys.isEmpty()) { + return Map.of(); + } + Map> operatorIdsByIdentity = new LinkedHashMap<>(); + for (OperatorKey key : keys) { + operatorIdsByIdentity + .computeIfAbsent(key.identity(), identity -> new ArrayList<>()) + .add(key.operatorId()); + } + Map resolved = new HashMap<>(); + operatorIdsByIdentity.forEach((identity, operatorIds) -> { + List operators = repositoryHolder.findOperatorByIds(operatorIds, identity); + if (operators == null) { + return; + } + for (IFlowOperator operator : operators) { + resolved.put(OperatorKey.of(operator.getUserId(), identity).key(), operator); + } + }); + return resolved; + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptBind.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptBind.java index b8f89a44..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; @@ -58,6 +59,22 @@ 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 = "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 d030ffaf..c730d788 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptRequest.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/request/GroovyScriptRequest.java @@ -4,6 +4,8 @@ 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.operator.OperatorKey; import com.codingapi.flow.pojo.request.FlowCreateRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; @@ -215,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(); + } + /** * 获取当前操作对象 */ @@ -281,6 +300,70 @@ public String getSubmitOperatorName() { } + /** + * 流程创建者身份标识(issue #288) + *

    身份标识由下游自定义,框架不做解释;空串表示默认身份。 + * 可用于按部门、岗位等身份差异决定节点分支。 + * + * @return 创建者身份标识 + */ + @ScriptFunction(name = "getCreatedOperatorIdentity", description = "获取流程创建者身份标识") + public String getCreatedOperatorIdentity() { + return OperatorIdentity.of(this.createdOperator).value(); + } + + /** + * 流程审批者身份标识(issue #288) + * + * @return 当前审批者身份标识 + */ + @ScriptFunction(name = "getCurrentOperatorIdentity", description = "获取流程审批者身份标识") + public String getCurrentOperatorIdentity() { + return OperatorIdentity.of(this.currentOperator).value(); + } + + /** + * 流程提交人身份标识(issue #288) + * + * @return 提交人身份标识 + */ + @ScriptFunction(name = "getSubmitOperatorIdentity", description = "获取流程提交人身份标识") + public String getSubmitOperatorIdentity() { + return OperatorIdentity.of(this.submitOperator).value(); + } + + /** + * 流程创建者标识(人员id + 身份,issue #303) + *

    取人脚本默认返回该对象,保证创建者以「发起时的身份」参与流程,而不是退化为默认身份。 + * + * @return 创建者标识 + */ + @ScriptFunction(name = "getCreatedOperatorKey", description = "获取流程创建者标识(含身份)") + public OperatorKey getCreatedOperatorKey() { + return OperatorKey.of(this.createdOperator.getUserId(), OperatorIdentity.of(this.createdOperator).value()); + } + + /** + * 流程审批者标识(人员id + 身份,issue #303) + * + * @return 当前审批者标识 + */ + @ScriptFunction(name = "getCurrentOperatorKey", description = "获取流程审批者标识(含身份)") + public OperatorKey getCurrentOperatorKey() { + return OperatorKey.of(this.currentOperator.getUserId(), OperatorIdentity.of(this.currentOperator).value()); + } + + /** + * 流程提交人标识(人员id + 身份,issue #303) + * + * @return 提交人标识 + */ + @ScriptFunction(name = "getSubmitOperatorKey", description = "获取流程提交人标识(含身份)") + public OperatorKey getSubmitOperatorKey() { + return OperatorKey.of(this.submitOperator.getUserId(), OperatorIdentity.of(this.submitOperator).value()); + } + + /** * 获取开始节点 * 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); 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..e04d2ef2 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java @@ -11,6 +11,8 @@ import com.codingapi.flow.manager.WorkflowStrategyManager; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.diagnostic.OperatorIdentityWarnLog; +import com.codingapi.flow.operator.OperatorSelections; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.response.ActionResponse; import com.codingapi.flow.record.FlowRecord; @@ -53,8 +55,11 @@ 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()); + // 审批入口同样检查身份是否真的生效,避免下游未覆盖带身份的取人方法时静默降级(issue #288 评审修复) + OperatorIdentityWarnLog.getInstance().warnOnce(request.getAdvice().getOperatorId(), request.getAdvice().getOperatorIdentity(), currentOperator); if (currentOperator == null) { throw FlowNotFoundException.operator(request.getAdvice().getOperatorId()); } @@ -66,7 +71,10 @@ public ActionResponse action() { throw FlowStateException.recordAlreadyDone(); } - IFlowOperator createdOperator = flowOperatorGateway.get(flowRecord.getCreateOperatorId()); + // 发起人按记录中的身份回查,避免同一 id 的不同身份拿到同一个操作者实例 + IFlowOperator createdOperator = flowOperatorGateway.get( + flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity()); + OperatorIdentityWarnLog.getInstance().warnOnce(flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity(), createdOperator); WorkflowRuntime workflowRuntime = workflowService.getWorkflowRuntime(flowRecord.getWorkRuntimeId()); if (workflowRuntime == null) { @@ -78,7 +86,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) { @@ -97,10 +105,9 @@ public ActionResponse action() { FlowSession session = flowRecord.createFlowSession(this.repositoryHolder,workflow,currentOperator,createdOperator,currentOperator,formData,flowAdvice); // 校验并持久化 APPROVER_SELECT 节点的操作人分配(含可选人员范围校验) - if (flowAdvice.getOperatorSelectMap() != null - && !flowAdvice.getOperatorSelectMap().isEmpty()) { - OperatorAssignmentService.validateAndSave(session, flowRecord.getProcessId(), flowAdvice.getOperatorSelectMap()); - } + // 「携带身份的分配优先」这条规则由 OperatorSelections 统一判断(issue #288 衍生 / #292) + new OperatorAssignmentService(session).assign(flowRecord.getProcessId(), + OperatorSelections.of(flowAdvice.getOperatorSelectOperators(), flowAdvice.getOperatorSelectMap())); // 验证会话 currentNode.verifySession(session); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowCreateService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowCreateService.java index 7f0de567..9392363c 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowCreateService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowCreateService.java @@ -14,6 +14,8 @@ import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.node.nodes.StartNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.diagnostic.OperatorIdentityWarnLog; +import com.codingapi.flow.operator.OperatorSelections; import com.codingapi.flow.pojo.request.FlowCreateRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.WorkflowService; @@ -57,8 +59,10 @@ 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()); + // 发起入口同样要检查身份是否真的生效:下游未覆盖带身份的取人方法时身份会被静默丢弃(issue #288 评审修复) + OperatorIdentityWarnLog.getInstance().warnOnce(request.getOperatorId(), request.getOperatorIdentity(), currentOperator); if (!workflow.matchCreatedOperator(currentOperator)) { throw FlowPermissionException.accessDenied("create workflow"); } @@ -91,11 +95,11 @@ public long create() { } // 校验并持久化 INITIATOR_SELECT 节点的操作人分配(含可选人员范围校验) - if (request.getOperatorSelectMap() != null - && !request.getOperatorSelectMap().isEmpty() - && !flowRecords.isEmpty()) { + // 携带身份的分配优先:同一人员的两个身份是两项,不会被合并(issue #288 衍生 / #292) + if (!flowRecords.isEmpty()) { String processId = flowRecords.get(0).getProcessId(); - OperatorAssignmentService.validateAndSave(session, processId, request.getOperatorSelectMap()); + new OperatorAssignmentService(session).assign(processId, + OperatorSelections.of(request.getOperatorSelectOperators(), request.getOperatorSelectMap())); } repositoryHolder.saveRecords(flowRecords); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/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..ce2d62f3 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDeleteService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDeleteService.java @@ -6,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.OperatorKey; import com.codingapi.flow.pojo.request.FlowDeleteRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.FlowRecordService; @@ -60,10 +61,8 @@ public void delete() { if (afterRecords != null && !afterRecords.isEmpty()) { throw FlowStateException.recordAlreadyRunning(); } - // 权限校验:仅允许当前待办处理人删除 - if (currentRecord.getCurrentOperatorId() != request.getOperatorId()) { - throw FlowStateException.operatorNotMatch(); - } + // 权限校验:仅允许当前待办处理人删除;身份是否参与判定由策略决定(issue #297) + currentRecord.verifyOperator(OperatorKey.of(request.getOperatorId(), request.getOperatorIdentity())); // 删除流程记录及其关联待办 flowRecordService.deleteFlowRecord(currentRecord); // 推送删除事件 diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/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..b42ef942 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java @@ -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,40 +104,72 @@ 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.of(identity).value(); + } + + 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; } 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(operator.getUserId(), 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.of(identity).value(), key -> new LinkedHashSet<>()) + .add(operatorId); } public List processNodes() { @@ -398,7 +431,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); @@ -451,21 +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(operatorId)) - .distinct() - .toList(); - if (operatorIds.isEmpty()) { - return; - } - List operatorList = this.repositoryHolder.findOperatorByIds(operatorIds); - if (operatorList != null) { - operatorList.forEach(operator -> this.recordOperatorMap.put(operator.getUserId(), operator)); - } + this.preloadRecordOperators(records); } private record ParentSubProcessContext(FlowRecord parentRecord, @@ -499,7 +518,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 +528,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 +541,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 +580,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 +689,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 +712,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 +784,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..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; @@ -84,7 +85,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 +105,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,12 +152,14 @@ 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())) { createRequest.setWorkTitle(sourceRecord.getWorkTitle()); } - createRequest.setOperatorSelectMap(this.loadOperatorSelectMap(workflow, sourceRecord.getProcessId())); + createRequest.setOperatorSelectOperators(this.loadOperatorSelectOperators(workflow, sourceRecord.getProcessId())); return createRequest; } @@ -173,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/FlowRevokeService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowRevokeService.java index e9724c05..a82dd76f 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowRevokeService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowRevokeService.java @@ -11,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.OperatorKey; import com.codingapi.flow.pojo.request.FlowRevokeRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.FlowRecordService; @@ -68,9 +69,8 @@ public void revoke() { throw FlowStateException.recordNotSupportRevoke(); } long currentOperatorId = currentRecord.getCurrentOperatorId(); - if (currentOperatorId != request.getOperatorId()) { - throw FlowStateException.operatorNotMatch(); - } + // 是否要求身份一致由身份匹配策略决定(issue #297):USER_ONLY 下同一人换身份仍可撤回自己的办理 + currentRecord.verifyOperator(OperatorKey.of(request.getOperatorId(), request.getOperatorIdentity())); WorkflowRuntime workflowRuntime = workflowService.getWorkflowRuntime(currentRecord.getWorkRuntimeId()); if (workflowRuntime == null) { throw FlowNotFoundException.workflow(currentRecord.getWorkRuntimeId() + " not found"); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResetService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResetService.java index 93384453..70fcbb5c 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResetService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResetService.java @@ -12,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.OperatorKey; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.request.FlowCreateRequest; import com.codingapi.flow.pojo.request.FlowSubProcessResetRequest; @@ -73,9 +74,8 @@ public void reset() { if (!currentRecord.isTodo()) { throw FlowStateException.recordAlreadyDone(); } - if (currentRecord.getCurrentOperatorId() != request.getOperatorId()) { - throw FlowStateException.operatorNotMatch(); - } + // issue #297:身份是否参与判定由 OperatorIdentityContext 统一控制 + currentRecord.verifyOperator(OperatorKey.of(request.getOperatorId(), request.getOperatorIdentity())); WorkflowRuntime workflowRuntime = workflowService.getWorkflowRuntime(currentRecord.getWorkRuntimeId()); if (workflowRuntime == null) { @@ -181,7 +181,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..5297747a 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowUrgeService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowUrgeService.java @@ -11,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.OperatorKey; import com.codingapi.flow.pojo.request.FlowUrgeRequest; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.FlowRecordService; @@ -60,10 +61,8 @@ public void urge() { throw FlowStateException.recordNotSupportRevoke(); } - long currentOperatorId = currentRecord.getCurrentOperatorId(); - if (currentOperatorId != request.getOperatorId()) { - throw FlowStateException.operatorNotMatch(); - } + // issue #297:身份是否参与判定由 OperatorIdentityContext 统一控制 + currentRecord.verifyOperator(OperatorKey.of(request.getOperatorId(), request.getOperatorIdentity())); UrgeInterval urgeInterval = repositoryHolder.getLatestUrgeInterval(currentRecord.getProcessId(), request.getRecordId()); if (urgeInterval != null) { @@ -79,7 +78,8 @@ public void urge() { } } - IFlowOperator currentOperator = flowOperatorGateway.get(currentOperatorId); + IFlowOperator currentOperator = flowOperatorGateway.get( + currentRecord.getCurrentOperatorId(), request.getOperatorIdentity()); List todoRecords = flowRecordService.findFlowRecordTodoRecords(currentRecord.getProcessId()); // 保存催办记录 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..d6849c3e 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/OperatorAssignmentService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/OperatorAssignmentService.java @@ -3,6 +3,10 @@ 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.operator.OperatorSelections; +import com.codingapi.flow.record.FlowRecord; +import com.codingapi.flow.session.FlowAdvice; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; import com.codingapi.flow.workflow.Workflow; @@ -13,53 +17,115 @@ import java.util.stream.Collectors; /** - * 操作人分配服务 - *

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

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

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

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

      + *
    • {@link #hasAssignment(String)} —— 该节点是否已经设定操作人;
    • + *
    • {@link #assign(String)} —— 校验并保存本次分配。
    • + *
    + * 「携带身份的分配优先于仅人员 id 的分配」这条规则收在 {@link #selections()} 里, + * 调用方不再自己 if/else 二选一。 */ public class OperatorAssignmentService { - private OperatorAssignmentService() { + private final FlowSession session; + + /** + * @param session 当前流程会话,分配所依据的上下文 + */ + public OperatorAssignmentService(FlowSession session) { + this.session = session; + } + + /** + * 判断指定节点是否已经设定操作人(issue #288 衍生 / #292)。 + * + *

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

      + *
    1. 本次意见携带的存量 {@code operatorSelectMap};
    2. + *
    3. 本次意见携带的 {@code operatorSelectOperators}(含身份);
    4. + *
    5. 此前(典型为发起时)已持久化的节点分配关系。
    6. + *
    + * 只检查第 1 项会把「发起时预置的分配」和「按身份设定的分配」误判为未设定, + * 使 {@code PassAction} 反复返回 OPERATOR_SELECT,流程停滞在开始节点。 + * + * @param nodeId 节点 ID + * @return 是否已设定操作人 + */ + public boolean hasAssignment(String nodeId) { + if (currentSelections().hasSelection(nodeId)) { + 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(); } /** - * 校验并保存操作人分配。 - *

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

    数量校验:节点配置了最大可选人数(maxOperatorCount ≥ 0)时,所选人数超过上限则抛出异常。 * 当目标节点配置了可选人员范围(范围非空)时,校验所选人员是否全部落在范围内,越界则抛出异常; * 范围为空(未配置脚本或脚本执行结果为空)表示不限范围,跳过校验。 * - * @param baseSession 基准会话,用于派生目标节点会话以执行范围脚本 - * @param processId 流程实例ID - * @param operatorSelectMap 节点ID -> 选定的操作人ID列表 + *

    同一人员的两个身份是两项参与人,不做合并;完全相同的 {@code (人员id, 身份)} 会被去重。 + * + * @param processId 流程实例 ID + * @param selections 本次请求的选择集合(发起与办理两条路径来源不同,因此显式传入) */ - public static void validateAndSave(FlowSession baseSession, String processId, - Map> operatorSelectMap) { - if (operatorSelectMap == null || operatorSelectMap.isEmpty()) { + public void assign(String processId, OperatorSelections selections) { + if (selections == null || selections.isEmpty()) { return; } - Workflow workflow = baseSession.getWorkflow(); - IRepositoryHolder repositoryHolder = baseSession.getRepositoryHolder(); - operatorSelectMap.forEach((nodeId, operatorIds) -> { + Workflow workflow = session.getWorkflow(); + IRepositoryHolder repositoryHolder = session.getRepositoryHolder(); + for (String nodeId : selections.nodeIds()) { + List selected = selections.of(nodeId).stream().distinct().toList(); + if (selected.isEmpty()) { + continue; + } IFlowNode node = workflow.getFlowNode(nodeId); // 校验可选人数上限(-1 表示不限制) int maxOperatorCount = node.strategyManager().getMaxOperatorCount(); - if (maxOperatorCount >= 0 && operatorIds.size() > maxOperatorCount) { + if (maxOperatorCount >= 0 && selected.size() > maxOperatorCount) { throw FlowValidationException.operatorCountExceeded(nodeId, maxOperatorCount); } List range = node.strategyManager() - .loadOperatorRange(baseSession.updateSession(node)); + .loadOperatorRange(session.updateSession(node)); if (range != null && !range.isEmpty()) { + // 范围校验按人员 id 判定:范围表达的是「可选哪些人」,不区分身份 Set allowedIds = range.stream() .map(IFlowOperator::getUserId) .collect(Collectors.toSet()); - for (Long operatorId : operatorIds) { - if (!allowedIds.contains(operatorId)) { + for (OperatorKey operator : selected) { + if (!allowedIds.contains(operator.operatorId())) { throw FlowValidationException.operatorOutOfRange(nodeId); } } } - repositoryHolder.saveOperatorAssignment(processId, nodeId, operatorIds); - }); + repositoryHolder.saveOperatorAssignments(processId, nodeId, selected); + } + } + + /** + * 会话当前携带的选择(办理路径的会话一定带意见;发起路径可能没有) + */ + private OperatorSelections currentSelections() { + FlowAdvice advice = session.getAdvice(); + if (advice == null) { + return OperatorSelections.empty(); + } + return OperatorSelections.of(advice.getOperatorSelectOperators(), advice.getOperatorSelectMap()); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/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/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/FlowSession.java b/flow-engine-framework/src/main/java/com/codingapi/flow/session/FlowSession.java index 920bfe1c..d5a6c94d 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/session/FlowSession.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/session/FlowSession.java @@ -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 new OperatorScriptResultResolver(repositoryHolder, "previousNode").resolve(operatorKeys); + } + + /** + * 查询上一节点实际审批过的流程记录:直接前驱校验 + 排除自动跳过(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/session/IRepositoryHolder.java b/flow-engine-framework/src/main/java/com/codingapi/flow/session/IRepositoryHolder.java index 9680baa2..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; @@ -88,13 +89,42 @@ 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); + } + + /** + * 按统一身份批量获取流程操作人(issue #288 衍生 / #293)。 + * + *

    用于一批人员以同一身份参与流程的场景,避免逐条回查。 + * 默认实现忽略身份、退化为 {@link #findOperatorByIds(List)},下游存量实现无需改动。 + * + * @param ids 人员 id 列表 + * @param identity 身份标识,{@code null} 与空串等价(默认身份) + * @return 流程操作人列表 + */ + default List findOperatorByIds(List ids, String identity) { + return findOperatorByIds(ids); + } + /** * 保存延迟任务 @@ -215,4 +245,34 @@ public interface IRepositoryHolder { * @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..f45b25c8 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java @@ -3,8 +3,11 @@ 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.script.operator.OperatorScriptResultResolver; import com.codingapi.flow.session.FlowSession; +import com.codingapi.flow.session.IRepositoryHolder; import lombok.Getter; import lombok.NoArgsConstructor; @@ -51,18 +54,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 +74,17 @@ public OperatorManager loadOperators(FlowSession flowSession) { return new OperatorManager(operatorLoadScript.execute(flowSession)); } + /** + * 按 {@code (人员id, 身份)} 加载已分配的操作人(issue #288 衍生 / #292)。 + * + *

    回查逻辑统一由 {@link OperatorScriptResultResolver} 提供:按身份分组批量回查, + * 返回顺序与分配顺序一致,保证多人审批的执行顺序稳定。 + */ + private List loadAssignedOperators(IRepositoryHolder repositoryHolder, + List assignedOperators) { + return new OperatorScriptResultResolver(repositoryHolder, "operatorAssignment").resolve(assignedOperators); + } + /** * 计算该节点的可选人员范围(用于发起人/审批人设定模式)。 * 复用 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..fae6ed5a --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java @@ -0,0 +1,177 @@ +package com.codingapi.flow.cache; + +import com.codingapi.flow.context.GatewayContext; +import com.codingapi.flow.gateway.FlowOperatorGateway; +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +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.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +/** + * 按身份批量取人的缓存与网关契约测试(issue #288 衍生 / #293、#295)。 + * + *

    批量加载必须按 {@code (id, identity)} 隔离缓存,否则同一批人以不同身份参与时 + * 会命中同一个对象,身份串味;同时验证未覆盖新方法的存量网关能安全退化为按 id 批量查询。 + */ +class FlowOperatorBulkIdentityTest { + + private FlowOperatorLocalThreadCache cache; + + private FlowOperatorGateway previousGateway; + + @BeforeEach + void setUp() { + cache = FlowOperatorLocalThreadCache.getInstance(); + cache.clear(); + previousGateway = GatewayContext.getInstance().getFlowOperatorGateway(); + } + + @AfterEach + void tearDown() { + // GatewayContext 是全局单例,用例结束后必须还原,避免影响其他用例 + GatewayContext.getInstance().setFlowOperatorGateway(previousGateway); + cache.clear(); + } + + /** + * 测试目标:两个身份分别回源、分别命中缓存,互不覆盖。 + * 前置条件:缓存为空,人员 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.value(), + 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)).value()); + } + + /** + * 测试目标:下游只覆盖单条按身份取人、未覆盖批量重载时,批量路径必须回退到单条取人拿回正确身份。 + * 前置条件:网关实现 {@code get(id, identity)}(返回带身份的副本)但复用默认的批量重载。 + * 执行步骤:经 GatewayContext 批量按身份取人,再按同一身份单条取人。 + * 期望断言:批量结果携带请求身份(不是被静默降级为默认身份),且缓存没有被错误对象污染。 + */ + @Test + void should_fall_back_to_single_load_when_gateway_has_no_bulk_identity_override() { + FlowOperatorGateway partialGateway = new FlowOperatorGateway() { + @Override + public IFlowOperator get(long id) { + return new User(id, "user" + id); + } + + @Override + public IFlowOperator get(long id, String identity) { + return User.withIdentity(id, "user" + id, identity); + } + + @Override + public List findByIds(List ids) { + return ids.stream().map(id -> (IFlowOperator) new User(id, "user" + id)).toList(); + } + }; + + GatewayContext.getInstance().setFlowOperatorGateway(partialGateway); + + List operators = GatewayContext.getInstance().findByIds(List.of(1L), "department1"); + + assertEquals(1, operators.size()); + assertEquals("department1", OperatorIdentity.of(operators.get(0)).value(), + "批量路径不能把请求身份静默降级为默认身份"); + // 单条读取必须命中同一个带身份的对象,说明缓存未被默认身份的对象污染 + assertEquals("department1", + OperatorIdentity.of(FlowOperatorLocalThreadCache.getInstance().get(1, "department1", () -> null)).value()); + } + + /** + * 测试目标:单条加载拿回身份不一致的对象时不登记缓存(避免污染身份键)。 + * 前置条件:缓存为空,加载器返回默认身份对象。 + * 执行步骤:以非默认身份读取一次,再用正确身份的加载器读一次。 + * 期望断言:第一次返回默认身份对象但不缓存,第二次能拿到正确的身份对象。 + */ + @Test + void should_not_cache_single_load_result_with_mismatched_identity() { + User defaultUser = new User(7, "user7"); + User identityUser = User.withIdentity(7, "user7", "department1"); + + IFlowOperator first = cache.get(7, "department1", () -> defaultUser); + assertSame(defaultUser, first); + assertNull(cache.get(7, "department1", () -> null), "身份不一致的加载结果不能登记缓存"); + + IFlowOperator second = cache.get(7, "department1", () -> identityUser); + assertSame(identityUser, second); + assertSame(identityUser, cache.get(7, "department1", () -> null)); + } +} diff --git a/flow-engine-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/diagnostic/OperatorIdentityWarnLogTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/diagnostic/OperatorIdentityWarnLogTest.java new file mode 100644 index 00000000..a43943e3 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/diagnostic/OperatorIdentityWarnLogTest.java @@ -0,0 +1,65 @@ +package com.codingapi.flow.diagnostic; + +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 身份透传告警测试(#294 / #311 P5)。 + * + *

    每个用例用独立实例:去重状态归属实例,测试之间不需要「清空缓存」这种静态清理入口。 + */ +class OperatorIdentityWarnLogTest { + + private final OperatorIdentityWarnLog warnLog = new OperatorIdentityWarnLog(); + + @Test + void should_warn_when_requested_identity_is_dropped() { + User resolved = new User(1, "lorne"); + + assertTrue(warnLog.warnOnce(1, "department1", resolved)); + } + + @Test + void should_warn_once_per_participant() { + User resolved = new User(1, "lorne"); + + assertTrue(warnLog.warnOnce(1, "department1", resolved)); + assertFalse(warnLog.warnOnce(1, "department1", resolved), "同一参与人不应重复告警"); + assertTrue(warnLog.warnOnce(1, "department2", resolved), "不同身份应各自告警一次"); + } + + @Test + void should_not_warn_for_default_identity_or_missing_operator() { + User resolved = new User(1, "lorne"); + + assertFalse(warnLog.warnOnce(1, OperatorIdentity.DEFAULT.value(), resolved)); + assertFalse(warnLog.warnOnce(1, null, resolved)); + assertFalse(warnLog.warnOnce(1, "department1", null)); + } + + @Test + void should_not_warn_when_downstream_carries_identity() { + User resolved = User.withIdentity(1, "lorne", "department1"); + + assertFalse(warnLog.warnOnce(1, "department1", resolved)); + } + + @Test + void should_cap_warn_keys_to_avoid_log_flood() { + User resolved = new User(1, "lorne"); + + int warned = 0; + for (int i = 0; i < 300; i++) { + if (warnLog.warnOnce(1, "department" + i, resolved)) { + warned++; + } + } + + assertTrue(warned <= 256, "去重记录应有上限,实际告警次数:" + warned); + assertTrue(warned > 0); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java b/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java index ab213887..e83e9f2f 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java @@ -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.of(identity).isDefault()) { + return user; + } + return user.asIdentity(identity); + } + @Override public List findByIds(List ids) { return cache.values().stream().filter(user -> ids.contains(user.getUserId())) @@ -25,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.of(identity).isDefault()) { + 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/manager/OperatorManagerTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/manager/OperatorManagerTest.java new file mode 100644 index 00000000..745b44f0 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/manager/OperatorManagerTest.java @@ -0,0 +1,76 @@ +package com.codingapi.flow.manager; + +import com.codingapi.flow.operator.OperatorIdentityMatchMode; +import com.codingapi.flow.operator.OperatorIdentityContext; +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 参与人集合测试(#311 P1)。 + * + *

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

    上下文只负责「持有模式 + 把模式传给 OperatorKey」,因此这里断言的是 + * 「模式生效范围」与「判定唯一真源」,而不是比较细节(那属于 {@link OperatorKeyTest})。 + */ +class OperatorIdentityContextTest { + + private final OperatorIdentityContext context = OperatorIdentityContext.getInstance(); + + @AfterEach + void tearDown() { + context.use(OperatorIdentityMatchMode.STRICT); + } + + @Test + void should_default_to_strict_mode_for_framework_only_usage() { + assertEquals(OperatorIdentityMatchMode.STRICT, context.matchMode()); + assertFalse(context.matches( + OperatorKey.of(1, "department1"), OperatorKey.of(1, "department2"))); + } + + @Test + void should_compare_only_user_id_in_user_only_mode() { + context.use(OperatorIdentityMatchMode.USER_ONLY); + + assertTrue(context.matches(OperatorKey.of(1, "department1"), OperatorKey.of(1, "department2"))); + assertTrue(context.matches(OperatorKey.of(1, ""), OperatorKey.of(1, "department2"))); + assertFalse(context.matches(OperatorKey.of(2, "boss"), OperatorKey.of(1, "department1"))); + assertFalse(context.matches(null, OperatorKey.of(1, "department1"))); + } + + @Test + void should_delegate_matching_to_operator_key_instead_of_reimplementing() { + for (OperatorIdentityMatchMode mode : OperatorIdentityMatchMode.values()) { + context.use(mode); + for (String leftIdentity : new String[]{"", "department1", "department2"}) { + for (String rightIdentity : new String[]{"", "department1", "department2"}) { + OperatorKey left = OperatorKey.of(1, leftIdentity); + OperatorKey right = OperatorKey.of(1, rightIdentity); + assertEquals(left.matches(right, mode), context.matches(left, right), + "上下文的判定必须与 OperatorKey 的策略判定完全一致:" + mode); + } + } + } + } + + @Test + void should_treat_same_user_as_same_operator_only_when_mode_allows() { + User a = User.withIdentity(1, "user1", "department1"); + User b = User.withIdentity(1, "user1", "department2"); + + assertFalse(context.sameOperator(a, b)); + + context.use(OperatorIdentityMatchMode.USER_ONLY); + assertTrue(context.sameOperator(a, b)); + assertFalse(context.sameOperator(a, new User(2, "boss"))); + assertFalse(context.sameOperator(a, null)); + } + + @Test + void should_fall_back_to_strict_when_configured_with_null() { + context.use(OperatorIdentityMatchMode.USER_ONLY); + + context.use(null); + + assertEquals(OperatorIdentityMatchMode.STRICT, context.matchMode()); + } + + @Test + void should_parse_mode_leniently() { + assertEquals(OperatorIdentityMatchMode.USER_ONLY, OperatorIdentityMatchMode.parse("user-only")); + assertEquals(OperatorIdentityMatchMode.USER_ONLY, OperatorIdentityMatchMode.parse(" USER_ONLY ")); + assertEquals(OperatorIdentityMatchMode.STRICT, OperatorIdentityMatchMode.parse("strict")); + assertNull(OperatorIdentityMatchMode.parse(null)); + assertNull(OperatorIdentityMatchMode.parse(" ")); + assertNull(OperatorIdentityMatchMode.parse("unknown")); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityTest.java new file mode 100644 index 00000000..7837914d --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorIdentityTest.java @@ -0,0 +1,121 @@ +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 static org.junit.jupiter.api.Assertions.*; + +/** + * 身份标识归一化规则测试。 + * + *

    约定的核心规则:null 与空串等价,统一视为「默认身份」(issue #288)。 + */ +class OperatorIdentityTest { + + @Test + void should_normalize_null_to_empty() { + // given + String identity = null; + + // when + String normalized = OperatorIdentity.of(identity).value(); + + // then + assertEquals("", normalized); + } + + @Test + void should_keep_identity_value() { + // given + String identity = "department1"; + + // when + String normalized = OperatorIdentity.of(identity).value(); + + // then + assertEquals("department1", normalized); + } + + @Test + void should_treat_null_and_empty_as_default() { + assertTrue(OperatorIdentity.of((String) null).isDefault()); + assertTrue(OperatorIdentity.of("").isDefault()); + assertFalse(OperatorIdentity.of("department1").isDefault()); + } + + @Test + void should_compare_identities_null_safe() { + assertTrue(OperatorIdentity.of((String) null).same(OperatorIdentity.of(""))); + assertTrue(OperatorIdentity.of("department1").same(OperatorIdentity.of("department1"))); + assertFalse(OperatorIdentity.of("department1").same(OperatorIdentity.of("department2"))); + assertFalse(OperatorIdentity.of((String) null).same(OperatorIdentity.of("department1"))); + } + + @Test + void should_read_identity_from_operator_and_handle_null_operator() { + // given + IFlowOperator operator = new User(1, "张三"); + + // when & then + assertEquals("", OperatorIdentity.of(operator).value()); + assertEquals("", OperatorIdentity.of((String) null).value()); + } + + @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()); + } + + @Test + void should_allow_downstream_override_identity() { + // given + IFlowOperator operator = new IdentityUser(1, "张三", "department1"); + + // when & then + assertEquals("department1", OperatorIdentity.of(operator).value()); + } + + /** + * 模拟下游自定义身份的操作者实现。 + */ + 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; + } + + } +} 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..86963659 --- /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.value(), OperatorIdentity.of((String) null).validate().value()); + assertEquals("", OperatorIdentity.of("").validate().value()); + } + + @Test + void should_accept_identity_at_max_length() { + String identity = "a".repeat(OperatorIdentity.MAX_LENGTH); + + assertEquals(identity, OperatorIdentity.of(identity).validate().value()); + } + + @Test + void should_reject_identity_longer_than_max_length() { + String identity = "a".repeat(OperatorIdentity.MAX_LENGTH + 1); + + FlowValidationException exception = assertThrows(FlowValidationException.class, + () -> OperatorIdentity.of(identity).validate().value()); + assertTrue(exception.getMessage().contains("exceeds the max length"), exception.getMessage()); + } + + @Test + void should_reject_identity_containing_merge_key_separator() { + FlowValidationException exception = assertThrows(FlowValidationException.class, + () -> OperatorIdentity.of("department1#manager").validate().value()); + + assertTrue(exception.getMessage().contains("illegal character"), exception.getMessage()); + } + + @Test + void should_reject_identity_containing_control_character() { + FlowValidationException exception = assertThrows(FlowValidationException.class, + () -> OperatorIdentity.of("department\u00011").validate().value()); + + assertTrue(exception.getMessage().contains("illegal character"), exception.getMessage()); + } + + @Test + void should_keep_normalize_lenient_for_existing_data() { + // 存量数据可能含非法字符,读取路径必须保持宽松,不能因为校验把历史流程读崩 + assertSame("department1#manager", OperatorIdentity.of("department1#manager").value()); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorKeyTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorKeyTest.java new file mode 100644 index 00000000..f0e731f0 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorKeyTest.java @@ -0,0 +1,98 @@ +package com.codingapi.flow.operator; + +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 参与人标识测试:锁住「同一参与人判定」与「参与人键」的唯一真源 + * (issue #297 / #311 P1、P2)。 + * + *

    断言的是契约而非实现:无论判定逻辑将来挪到哪,这些行为都必须成立。 + */ +class OperatorKeyTest { + + @Test + void should_judge_same_identity_as_same_participant_in_strict_mode() { + OperatorKey department1 = OperatorKey.of(1, "department1"); + + assertTrue(department1.matches(OperatorKey.of(1, "department1"), OperatorIdentityMatchMode.STRICT)); + assertFalse(department1.matches(OperatorKey.of(1, "department2"), OperatorIdentityMatchMode.STRICT), + "严格口径下同一人员的不同身份是两个参与人"); + assertFalse(department1.matches(OperatorKey.of(2, "department1"), OperatorIdentityMatchMode.STRICT), + "身份相同但人员不同,不是同一参与人"); + } + + @Test + void should_judge_same_user_as_same_participant_in_user_only_mode() { + OperatorKey department1 = OperatorKey.of(1, "department1"); + + assertTrue(department1.matches(OperatorKey.of(1, "department2"), OperatorIdentityMatchMode.USER_ONLY)); + assertFalse(department1.matches(OperatorKey.of(2, "department1"), OperatorIdentityMatchMode.USER_ONLY)); + } + + @Test + void should_treat_null_and_blank_identity_as_default() { + OperatorKey expected = OperatorKey.ofDefault(1); + + assertEquals(expected, OperatorKey.of(1, null)); + assertEquals(expected, OperatorKey.of(1, "")); + assertTrue(expected.matches(OperatorKey.of(1, null), OperatorIdentityMatchMode.STRICT)); + } + + @Test + void should_return_false_when_matching_null_participant() { + assertFalse(OperatorKey.ofDefault(1).matches(null, OperatorIdentityMatchMode.STRICT)); + assertFalse(OperatorKey.ofDefault(1).matches(null, OperatorIdentityMatchMode.USER_ONLY)); + } + + @Test + void should_build_participant_from_operator() { + User user = User.withIdentity(7, "user7", "department3"); + + OperatorKey key = OperatorKey.of(user); + + assertEquals(7, key.operatorId()); + assertEquals("department3", key.identity()); + } + + @Test + void should_compare_identity_independently_of_user_id() { + OperatorKey key = OperatorKey.of(1, "department1"); + + assertTrue(key.identityEquals("department1")); + assertFalse(key.identityEquals(null), "非默认身份不应等于默认身份"); + assertTrue(OperatorKey.ofDefault(2).identityEquals(null)); + assertTrue(OperatorKey.ofDefault(2).identityEquals("")); + } + + @Test + void should_generate_distinct_keys_per_participant_in_strict_mode() { + String department1 = OperatorKey.of(1, "department1").key(); + String department2 = OperatorKey.of(1, "department2").key(); + + assertNotEquals(department1, department2, "严格口径下两个身份必须是两个键"); + assertEquals(department1, OperatorKey.of(1, "department1").key()); + } + + @Test + void should_collapse_identity_in_join_key_when_mode_ignores_identity() { + assertEquals(OperatorKey.of(1, "department1").key(OperatorIdentityMatchMode.USER_ONLY), + OperatorKey.of(1, "department2").key(OperatorIdentityMatchMode.USER_ONLY), + "仅人员模式下同一个人只应有一个键"); + assertEquals("1", OperatorKey.of(1, "department1").key(OperatorIdentityMatchMode.USER_ONLY)); + } + + @Test + void should_not_collide_when_identity_contains_key_like_characters() { + // 键分隔符必须是「业务身份不可能包含」的字符。身份若含普通分隔符(- 或 #), + // 拼出来的键不能与另一个参与人的键相同,否则缓存与去重会互相污染。 + assertNotEquals(OperatorKey.of(1, "a#b").key(), OperatorKey.of(1, "a").key()); + assertNotEquals(OperatorKey.of(1, "a-b").key(), OperatorKey.of(1, "a").key()); + assertNotEquals(OperatorKey.of(1, "").key(), OperatorKey.of(1, "a").key()); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorSelectionsTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorSelectionsTest.java new file mode 100644 index 00000000..07d19c49 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/operator/OperatorSelectionsTest.java @@ -0,0 +1,84 @@ +package com.codingapi.flow.operator; + +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 操作人选择集合测试(#311 P4)。 + * + *

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

    锁住三件事:基础段格式不可变、严格模式追加身份、仅人员模式不追加。 + */ +class TodoMergeKeyTest { + + @Test + void should_keep_historical_format_for_default_identity() { + String key = TodoMergeKey.of(OperatorKey.ofDefault(1), 100L, "node1", OperatorIdentityMatchMode.STRICT).value(); + + assertEquals("1-100-node1", key); + } + + @Test + void should_append_identity_suffix_in_strict_mode() { + String key = TodoMergeKey.of(OperatorKey.of(1, "department1"), 100L, "node1", + OperatorIdentityMatchMode.STRICT).value(); + + assertEquals("1-100-node1#department1", key); + } + + @Test + void should_not_append_identity_in_user_only_mode() { + String key = TodoMergeKey.of(OperatorKey.of(1, "department1"), 100L, "node1", + OperatorIdentityMatchMode.USER_ONLY).value(); + + assertEquals("1-100-node1", key); + } + + @Test + void should_merge_two_identities_into_one_key_only_when_mode_ignores_identity() { + TodoMergeKey department1 = TodoMergeKey.of(OperatorKey.of(1, "department1"), 100L, "node1", + OperatorIdentityMatchMode.USER_ONLY); + TodoMergeKey department2 = TodoMergeKey.of(OperatorKey.of(1, "department2"), 100L, "node1", + OperatorIdentityMatchMode.USER_ONLY); + + assertEquals(department1.value(), department2.value()); + + assertNotEquals( + TodoMergeKey.of(OperatorKey.of(1, "department1"), 100L, "node1", OperatorIdentityMatchMode.STRICT).value(), + TodoMergeKey.of(OperatorKey.of(1, "department2"), 100L, "node1", OperatorIdentityMatchMode.STRICT).value()); + } + + @Test + void should_distinguish_node_and_runtime() { + String base = TodoMergeKey.of(OperatorKey.ofDefault(1), 100L, "node1", OperatorIdentityMatchMode.STRICT).value(); + + assertNotEquals(base, + TodoMergeKey.of(OperatorKey.ofDefault(1), 101L, "node1", OperatorIdentityMatchMode.STRICT).value()); + assertNotEquals(base, + TodoMergeKey.of(OperatorKey.ofDefault(1), 100L, "node2", OperatorIdentityMatchMode.STRICT).value()); + } +} 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..0d527738 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/repository/CopyOnReadFlowRecordRepository.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/repository/CopyOnReadFlowRecordRepository.java @@ -142,6 +142,14 @@ 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(), + record.getHandleOperatorId(), + record.getHandleOperatorName(), + record.getHandleOperatorIdentity()); } } \ No newline at end of file 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/ErrorTriggerScriptTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/script/ErrorTriggerScriptTest.java index fbe455da..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 @@ -3,37 +3,51 @@ import com.codingapi.flow.builder.FormFieldPermissionsBuilder; import com.codingapi.flow.builder.NodeStrategyBuilder; import com.codingapi.flow.error.ErrorThrow; +import com.codingapi.flow.factory.MyFlowServiceFactory; import com.codingapi.flow.form.DataType; import com.codingapi.flow.form.FlowForm; -import com.codingapi.flow.form.FormData; import com.codingapi.flow.form.FlowFormBuilder; +import com.codingapi.flow.form.FormData; import com.codingapi.flow.form.permission.PermissionType; import com.codingapi.flow.node.nodes.ApprovalNode; import com.codingapi.flow.node.nodes.EndNode; import com.codingapi.flow.node.nodes.StartNode; import com.codingapi.flow.script.factory.FlowGroovyScriptFactory; import com.codingapi.flow.script.node.ErrorTriggerScript; -import com.codingapi.flow.factory.MyFlowServiceFactory; +import com.codingapi.flow.script.registry.DefaultScriptRegistry; +import com.codingapi.flow.script.registry.IScriptRegistry; +import com.codingapi.flow.script.registry.ScriptRegistryContext; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.strategy.node.FormFieldPermissionStrategy; import com.codingapi.flow.strategy.node.OperatorLoadStrategy; import com.codingapi.flow.user.User; import com.codingapi.flow.workflow.Workflow; import com.codingapi.flow.workflow.WorkflowBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +/** + * 异常触发脚本测试(issue #296) + *

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

    元素只回答两个问题:我是否指向一个有效参与人、我从回查结果里对应谁。 + * 解析主流程因此不再需要 {@code instanceof} 分支。 + */ +class OperatorScriptElementTest { + + @Test + void should_treat_direct_operator_as_participant_only_when_user_id_positive() { + assertTrue(new OperatorScriptElement.Direct(User.withIdentity(1, "user1", "department1")).hasParticipant()); + assertFalse(new OperatorScriptElement.Direct(new User(0, "nobody")).hasParticipant()); + assertFalse(new OperatorScriptElement.Direct(new User(-1, "none")).hasParticipant()); + } + + @Test + void should_treat_pending_key_as_participant_only_when_user_id_positive() { + assertTrue(new OperatorScriptElement.Pending(OperatorKey.of(1, "department1")).hasParticipant()); + assertFalse(new OperatorScriptElement.Pending(OperatorKey.ofDefault(0)).hasParticipant()); + assertFalse(new OperatorScriptElement.Pending(OperatorKey.ofDefault(-1)).hasParticipant()); + } + + @Test + void should_return_direct_operator_without_lookup() { + IFlowOperator operator = User.withIdentity(1, "user1", "department1"); + + IFlowOperator resolved = new OperatorScriptElement.Direct(operator).resolveFrom(Map.of()); + + assertSame(operator, resolved); + } + + @Test + void should_lookup_pending_key_by_participant_key() { + IFlowOperator operator = User.withIdentity(1, "user1", "department1"); + OperatorScriptElement.Pending pending = new OperatorScriptElement.Pending(OperatorKey.of(1, "department1")); + + assertSame(operator, pending.resolveFrom(Map.of(OperatorKey.of(1, "department1").key(), operator))); + assertNull(pending.resolveFrom(Map.of()), "回查不到时返回 null,由调用方跳过"); + } + + @Test + void should_distinguish_two_identities_of_same_user_when_resolving() { + IFlowOperator department1 = User.withIdentity(1, "user1", "department1"); + IFlowOperator department2 = User.withIdentity(1, "user1", "department2"); + Map resolved = Map.of( + OperatorKey.of(1, "department1").key(), department1, + OperatorKey.of(1, "department2").key(), department2); + + assertSame(department1, new OperatorScriptElement.Pending(OperatorKey.of(1, "department1")).resolveFrom(resolved)); + assertSame(department2, new OperatorScriptElement.Pending(OperatorKey.of(1, "department2")).resolveFrom(resolved)); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java new file mode 100644 index 00000000..8440d2c6 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java @@ -0,0 +1,252 @@ +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 = 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.value(), operators.get(0).getIdentity()); + assertEquals(OperatorIdentity.DEFAULT.value(), operators.get(1).getIdentity()); + } + + /** + * 新形态:{@code OperatorKey} 按身份回查,身份落到操作者上 + */ + @Test + void should_apply_identity_when_script_returns_operator_keys() { + List operators = 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.value(), operators.get(1).getIdentity()); + } + + /** + * 新形态:{@code IFlowOperator} 直接采用,不发生任何回查 + */ + @Test + void should_use_operator_instance_directly_without_query() { + IFlowOperator operator = User.withIdentity(2, "张三", "department1"); + + List operators = 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 = resolve( + countingHolder.proxy(), + Arrays.asList(2L, OperatorKey.of(1, "department2"), direct)); + + assertEquals(3, operators.size()); + assertEquals(2, operators.get(0).getUserId()); + assertEquals(OperatorIdentity.DEFAULT.value(), operators.get(0).getIdentity()); + assertEquals(1, operators.get(1).getUserId()); + assertEquals("department2", operators.get(1).getIdentity()); + assertSame(direct, operators.get(2)); + assertEquals("department3", operators.get(2).getIdentity()); + } + + /** + * 顶层单值:脚本不写 {@code []} 也能用 + */ + @Test + void should_wrap_single_value_as_single_element() { + List operators = 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(resolve(countingHolder.proxy(), null).isEmpty()); + assertTrue(resolve(countingHolder.proxy(), List.of()).isEmpty()); + } + + /** + * 列表内的 {@code null} 元素跳过,不中断其余元素 + */ + @Test + void should_skip_null_elements() { + List operators = 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 = 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, + () -> 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 = resolve( + countingHolder.proxy(), List.of("2")); + + assertEquals(1, operators.size()); + assertEquals(2, operators.get(0).getUserId()); + assertEquals(OperatorIdentity.DEFAULT.value(), operators.get(0).getIdentity()); + } + + /** + * 非正数人员 id(存量脚本用 {@code -1} 表示「无审批人」)跳过,不抛异常 + */ + @Test + void should_skip_non_positive_user_id() { + List operators = 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() { + 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 List resolve(IRepositoryHolder repositoryHolder, Object scriptResult) { + return new OperatorScriptResultResolver(repositoryHolder, "operatorLoad").resolve(scriptResult); + } + + /** + * 统计回查次数的仓储代理,用于断言「对象形态不回查」与「按身份分组批量回查」 + */ + 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/script/request/GroovyScriptBindIdentityTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/script/request/GroovyScriptBindIdentityTest.java new file mode 100644 index 00000000..d0f8e82e --- /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).value()); + } + + /** + * 测试目标:默认身份与历史单参方法等价(向后兼容)。 + * 前置条件:人员 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.value()); + + assertNotNull(legacy); + assertNotNull(byIdentity); + assertEquals(OperatorIdentity.of(legacy).value(), OperatorIdentity.of(byIdentity).value()); + assertEquals("", OperatorIdentity.of(byIdentity).value()); + } + + /** + * 测试目标:同一人员的两个身份是不同的参与人。 + * 前置条件:人员 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).value()); + assertEquals("department2", OperatorIdentity.of(department2).value()); + // 再次取 department1 仍应是同一个带身份的对象,不能被 department2 覆盖 + assertEquals("department1", OperatorIdentity.of(bind.getOperatorByIdentity(2, "department1")).value()); + } +} 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..55049f76 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowOperatorIdentityRecordTest.java @@ -0,0 +1,218 @@ +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.operator.OperatorIdentity; +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()); + } + + /** + * 场景:抄送记录被复用(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.value(), record.getForwardOperatorIdentity()); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowSubProcessResetServiceTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowSubProcessResetServiceTest.java index 2687d8a9..9e016825 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowSubProcessResetServiceTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowSubProcessResetServiceTest.java @@ -23,6 +23,8 @@ import com.codingapi.flow.node.nodes.ParallelNode; import com.codingapi.flow.node.nodes.StartNode; import com.codingapi.flow.node.nodes.SubProcessNode; +import com.codingapi.flow.operator.OperatorIdentityMatchMode; +import com.codingapi.flow.operator.OperatorIdentityContext; import com.codingapi.flow.pojo.body.FlowAdviceBody; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.request.FlowCreateRequest; @@ -56,6 +58,7 @@ import java.util.Map; import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -114,6 +117,11 @@ void resetEventContext() throws Exception { field.set(instance, null); } + @AfterEach + void resetIdentityPolicy() { + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.STRICT); + } + /** * 测试目标:验证在最终审批节点重置选中的 1 个子流程实例后,主流程重新等待, * 重建实例完成后主流程恢复并可正常走完。 @@ -540,6 +548,67 @@ void shouldRejectResetWhenOperatorMismatchOrRecordNotTodo() { "已办结记录不能重置"); } + /** + * 测试目标:USER_ONLY 模式下,同一人以另一身份重置子流程视为合法操作人(身份不阻断同人操作)。 + * 前置条件:主流程停在最终审批待办,两个子流程实例全部放行;记录登记的是默认身份。 + * 执行步骤:以 department1 身份调用重置接口(选中 1 个实例)。 + * 期望断言:不抛异常,旧聚合组被取代并产生新聚合组。 + */ + @Test + void shouldAllowResetWithOtherIdentityOfSameOperatorInUserOnlyMode() { + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); + FlowRecord finalTodo = prepareResetAtFinalApproval(); + + SubProcessRecord passedGroup = factory.subProcessRepository + .findByParentProcessId(parentProcessId(finalTodo)).get(0); + List processIds = List.of(passedGroup.getInstances().get(0).getProcessId()); + FlowSubProcessResetRequest request = new FlowSubProcessResetRequest( + finalTodo.getId(), finalOperator.getUserId(), processIds); + request.setOperatorIdentity("department1"); + + assertDoesNotThrow(() -> factory.flowService.resetSubProcess(request)); + assertTrue(factory.subProcessRepository + .findByParentProcessIdAndNodeId(parentProcessId(finalTodo), subProcessNode.getId()) + .get(0).isSuperseded(), + "重置成功后旧聚合组应被取代"); + } + + /** + * 测试目标:STRICT 模式下,同一人以另一身份不能重置子流程(身份是独立参与人)。 + * 前置条件:主流程停在最终审批待办,两个子流程实例全部放行;记录登记的是默认身份。 + * 执行步骤:以 department1 身份调用重置接口。 + * 期望断言:抛出状态异常,旧聚合组未被取代。 + */ + @Test + void shouldRejectResetWithOtherIdentityOfSameOperatorInStrictMode() { + FlowRecord finalTodo = prepareResetAtFinalApproval(); + + SubProcessRecord passedGroup = factory.subProcessRepository + .findByParentProcessId(parentProcessId(finalTodo)).get(0); + List processIds = List.of(passedGroup.getInstances().get(0).getProcessId()); + FlowSubProcessResetRequest request = new FlowSubProcessResetRequest( + finalTodo.getId(), finalOperator.getUserId(), processIds); + request.setOperatorIdentity("department1"); + + assertThrows(FlowStateException.class, () -> factory.flowService.resetSubProcess(request)); + assertFalse(factory.subProcessRepository + .findByParentProcessIdAndNodeId(parentProcessId(finalTodo), subProcessNode.getId()) + .get(0).isSuperseded(), + "拒绝重置时旧聚合组不能被取代"); + } + + /** + * 准备可重置现场:子流程全部放行后,返回主流程最终审批待办。 + */ + private FlowRecord prepareResetAtFinalApproval() { + buildParentWorkflow(true); + createAndSubmitParent(); + List childTodos = todos(childOperator, childApproval); + approve(childTodos.get(0), passAction(childApproval), childOperator, childTodos.get(0).getFormData()); + approve(childTodos.get(1), passAction(childApproval), childOperator, childTodos.get(1).getFormData()); + return todos(finalOperator, finalApproval).get(0); + } + /** * 测试目标:验证子流程后接并行分支时,合并节点锁定为第一个分支节点, * 仅锁定节点的待办可重置,兄弟分支被拒绝;重置作废全部分支记录链,重走后可正常走完。 diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/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/HandleOperatorIdentityFlowTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/HandleOperatorIdentityFlowTest.java new file mode 100644 index 00000000..735e746d --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/HandleOperatorIdentityFlowTest.java @@ -0,0 +1,290 @@ +package com.codingapi.flow.service; + +import com.codingapi.flow.action.ActionType; +import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.action.actions.CustomAction; +import com.codingapi.flow.builder.ActionBuilder; +import com.codingapi.flow.builder.FormFieldPermissionsBuilder; +import com.codingapi.flow.builder.NodeStrategyBuilder; +import com.codingapi.flow.context.GatewayContext; +import com.codingapi.flow.factory.MyFlowServiceFactory; +import com.codingapi.flow.form.DataType; +import com.codingapi.flow.form.FlowForm; +import com.codingapi.flow.form.FlowFormBuilder; +import com.codingapi.flow.form.permission.PermissionType; +import com.codingapi.flow.node.nodes.ApprovalNode; +import com.codingapi.flow.node.nodes.EndNode; +import com.codingapi.flow.node.nodes.StartNode; +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorIdentityMatchMode; +import com.codingapi.flow.operator.OperatorIdentityContext; +import com.codingapi.flow.pojo.body.FlowAdviceBody; +import com.codingapi.flow.pojo.request.FlowActionRequest; +import com.codingapi.flow.pojo.request.FlowCreateRequest; +import com.codingapi.flow.record.FlowRecord; +import com.codingapi.flow.script.factory.FlowGroovyScriptFactory; +import com.codingapi.flow.strategy.node.FormFieldPermissionStrategy; +import com.codingapi.flow.strategy.node.OperatorLoadStrategy; +import com.codingapi.flow.strategy.node.RevokeStrategy; +import com.codingapi.flow.user.User; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.WorkflowBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 办理人身份留痕的流程级测试(issue #306)。 + * + *

    核心回归:记录被办结后必须留下「本次办理人」的 {@code handleOperatorId/Name/Identity}, + * 与「待办归属身份」{@code currentOperatorIdentity} 互不覆盖。此前 {@code update()} 不写任何身份字段, + * 导致最后一步办理身份(没有下游记录可承载)彻底丢失。 + */ +class HandleOperatorIdentityFlowTest { + + private static final long INITIATOR = 1; + private static final long APPROVER = 2; + + private static final String DEPARTMENT_1 = "department1"; + private static final String DEPARTMENT_2 = "department2"; + + private MyFlowServiceFactory factory; + private final Map data = Map.of("name", "lorne"); + + @BeforeEach + void setUp() { + // issue #297:USER_ONLY 下同一人换身份可以办理自己的待办,与 issue #306 的复现场景一致 + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); + factory = new MyFlowServiceFactory(); + factory.userGateway.save(new User(INITIATOR, "initiator")); + factory.userGateway.save(new User(APPROVER, "approver")); + GatewayContext.getInstance().setFlowOperatorGateway(factory.userGateway); + } + + @AfterEach + void tearDown() { + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.STRICT); + } + + /** + * 测试目标:最后一步办理时,办理人身份必须留痕。 + * 前置条件:Start -> Approval(审批人固定为 APPROVER) -> End,开始节点归属身份为 department1、审批人归属为默认身份。 + * 执行步骤:department1 发起并提交,APPROVER 以 department2 身份审批通过(流程结束,无下游记录)。 + * 期望断言:该记录 currentOperatorIdentity 仍为空(归属身份不被改写), + * handleOperatorId=APPROVER、handleOperatorIdentity=department2。 + */ + @Test + void should_record_handle_operator_when_finishing_last_step() { + Workflow workflow = saveFlow("handle-identity-last", APPROVER); + + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + FlowRecord approvalRecord = todoRecordOf(APPROVER); + assertEquals(OperatorIdentity.DEFAULT.value(), approvalRecord.getCurrentOperatorIdentity(), + "固定审批人脚本只返回 id,归属身份应为默认身份"); + + pass(workflow, approvalRecord.getId(), APPROVER, DEPARTMENT_2); + + FlowRecord done = factory.flowRecordRepository.get(approvalRecord.getId()); + assertTrue(done.isDone(), "记录应已办结"); + assertEquals(OperatorIdentity.DEFAULT.value(), done.getCurrentOperatorIdentity(), + "归属身份不能被办理行为改写"); + assertEquals(APPROVER, done.getHandleOperatorId(), "办理人应留痕"); + assertEquals("approver", done.getHandleOperatorName(), "办理人名称应留痕"); + assertEquals(DEPARTMENT_2, done.getHandleOperatorIdentity(), "办理人身份应留痕"); + } + + /** + * 测试目标:中间节点办理同样留痕,且与下游记录的提交身份一致。 + * 前置条件:Start -> Approval1(APPROVER) -> Approval2(INITIATOR) -> End。 + * 执行步骤:department1 发起,APPROVER 以 department2 通过中间节点。 + * 期望断言:中间记录 handleOperatorIdentity=department2;下游待办的 submitOperatorIdentity=department2。 + */ + @Test + void should_record_handle_operator_when_finishing_middle_step() { + Workflow workflow = saveTwoApprovalFlow("handle-identity-middle"); + + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + FlowRecord middleRecord = todoRecordOf(APPROVER); + pass(workflow, middleRecord.getId(), APPROVER, DEPARTMENT_2); + + FlowRecord done = factory.flowRecordRepository.get(middleRecord.getId()); + assertEquals(DEPARTMENT_2, done.getHandleOperatorIdentity(), "中间节点办理身份应留痕"); + + FlowRecord nextRecord = todoRecordOf(INITIATOR); + assertEquals(DEPARTMENT_2, nextRecord.getSubmitOperatorIdentity(), + "下游记录的提交身份应与办理身份一致"); + } + + /** + * 测试目标:暂存不是办理,不得写入办理人。 + * 前置条件:同上单审批节点流程,APPROVER 存在待办。 + * 执行步骤:APPROVER 以 department2 身份执行「保存」动作。 + * 期望断言:记录仍为待办,handleOperator* 保持默认空值。 + */ + @Test + void should_not_record_handle_operator_when_saving_draft() { + Workflow workflow = saveFlow("handle-identity-save", APPROVER); + + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + FlowRecord approvalRecord = todoRecordOf(APPROVER); + save(workflow, approvalRecord.getId(), APPROVER, DEPARTMENT_2); + + FlowRecord saved = factory.flowRecordRepository.get(approvalRecord.getId()); + assertTrue(saved.isTodo(), "暂存后记录仍为待办"); + assertEquals(0L, saved.getHandleOperatorId(), "暂存不应写办理人 id"); + assertEquals(OperatorIdentity.DEFAULT.value(), saved.getHandleOperatorIdentity(), "暂存不应写办理人身份"); + } + + // ==================== 流程构建 ==================== + + /** + * 构建 Start(可撤回) -> Approval(指定审批人) -> End 的流程。 + */ + private Workflow saveFlow(String code, long... approverIds) { + StartNode startNode = startNode(code); + ApprovalNode approvalNode = approvalNode(code, "审批", approverIds); + + Workflow workflow = WorkflowBuilder.builder() + .title("办理人身份留痕流程") + .code(code) + .createdOperator(new User(INITIATOR, "initiator")) + .form(form(code)) + .addNode(startNode) + .addNode(approvalNode) + .addNode(EndNode.builder().build()) + .build(); + factory.workflowService.saveWorkflow(workflow); + return workflow; + } + + /** + * 构建 Start(可撤回) -> Approval1(APPROVER) -> Approval2(INITIATOR) -> End 的流程。 + */ + private Workflow saveTwoApprovalFlow(String code) { + Workflow workflow = WorkflowBuilder.builder() + .title("办理人身份留痕流程") + .code(code) + .createdOperator(new User(INITIATOR, "initiator")) + .form(form(code)) + .addNode(startNode(code)) + .addNode(approvalNode(code, "一级审批", APPROVER)) + .addNode(approvalNode(code, "二级审批", INITIATOR)) + .addNode(EndNode.builder().build()) + .build(); + factory.workflowService.saveWorkflow(workflow); + return workflow; + } + + private StartNode startNode(String code) { + return StartNode.builder() + .strategies(NodeStrategyBuilder.builder() + .addStrategy(fieldPermission(code)) + .addStrategy(new RevokeStrategy(true, RevokeStrategy.Type.REVOKE_CURRENT)) + .build()) + .actions(ActionBuilder.builder() + .addAction(CustomAction.defaultAction()) + .build()) + .build(); + } + + private ApprovalNode approvalNode(String code, String name, long... approverIds) { + return ApprovalNode.builder() + .name(name) + .strategies(NodeStrategyBuilder.builder() + .addStrategy(fieldPermission(code)) + .addStrategy(new OperatorLoadStrategy(FlowGroovyScriptFactory + .createOperatorLoadScript("def run(request){return [" + joinIds(approverIds) + "]}") + .getKey())) + .build()) + .build(); + } + + private String joinIds(long... ids) { + return Arrays.stream(ids).mapToObj(String::valueOf).collect(Collectors.joining(",")); + } + + private FlowForm form(String code) { + return FlowFormBuilder.builder() + .name("办理人身份留痕流程") + .code(code) + .addField("请假人", "name", DataType.STRING) + .build(); + } + + private FormFieldPermissionStrategy fieldPermission(String code) { + return new FormFieldPermissionStrategy(FormFieldPermissionsBuilder.builder() + .addPermission(code, "name", PermissionType.WRITE) + .build()); + } + + // ==================== 动作入口 ==================== + + private long createFlow(Workflow workflow, String operatorIdentity) { + FlowCreateRequest request = new FlowCreateRequest(); + request.setWorkCode(workflow.getCode()); + request.setFormData(data); + request.setActionId(startAction(workflow).id()); + request.setOperatorId(INITIATOR); + request.setOperatorIdentity(operatorIdentity); + return factory.flowService.create(request); + } + + private void submit(Workflow workflow, long recordId, String operatorIdentity) { + doAction(workflow, recordId, startAction(workflow), INITIATOR, operatorIdentity); + } + + private void pass(Workflow workflow, long recordId, long operatorId, String operatorIdentity) { + IFlowAction passAction = approvalAction(workflow, ActionType.PASS); + doAction(workflow, recordId, passAction, operatorId, operatorIdentity); + } + + private void save(Workflow workflow, long recordId, long operatorId, String operatorIdentity) { + IFlowAction saveAction = approvalAction(workflow, ActionType.SAVE); + doAction(workflow, recordId, saveAction, operatorId, operatorIdentity); + } + + private void doAction(Workflow workflow, long recordId, IFlowAction action, long operatorId, String operatorIdentity) { + FlowAdviceBody advice = new FlowAdviceBody(action.id(), action.title(), operatorId); + advice.setOperatorIdentity(operatorIdentity); + FlowActionRequest request = new FlowActionRequest(); + request.setFormData(data); + request.setRecordId(recordId); + request.setAdvice(advice); + factory.flowService.action(request); + } + + private IFlowAction startAction(Workflow workflow) { + return workflow.getStartNode().actionManager().getActions().get(0); + } + + /** + * 取审批节点的指定类型动作(只取第一个审批节点,二级流程的审批动作保持一致)。 + */ + private IFlowAction approvalAction(Workflow workflow, ActionType actionType) { + return workflow.getNodes().stream() + .filter(node -> node instanceof ApprovalNode) + .findFirst() + .map(node -> node.actionManager().getActionByType(actionType.name())) + .orElseThrow(); + } + + private FlowRecord todoRecordOf(long operatorId) { + List records = factory.flowRecordRepository.findTodoByOperator(operatorId); + assertEquals(1, records.size(), "操作人应有且仅有一条待办"); + return records.get(0); + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityBoundaryTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityBoundaryTest.java new file mode 100644 index 00000000..d3603a16 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityBoundaryTest.java @@ -0,0 +1,596 @@ +package com.codingapi.flow.service; + +import com.codingapi.flow.action.ActionType; +import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.action.actions.CustomAction; +import com.codingapi.flow.builder.ActionBuilder; +import com.codingapi.flow.builder.FormFieldPermissionsBuilder; +import com.codingapi.flow.builder.NodeStrategyBuilder; +import com.codingapi.flow.context.GatewayContext; +import com.codingapi.flow.exception.FlowExecutionException; +import com.codingapi.flow.exception.FlowStateException; +import com.codingapi.flow.factory.MyFlowServiceFactory; +import com.codingapi.flow.form.DataType; +import com.codingapi.flow.form.FlowForm; +import com.codingapi.flow.form.FlowFormBuilder; +import com.codingapi.flow.form.permission.PermissionType; +import com.codingapi.flow.node.nodes.ApprovalNode; +import com.codingapi.flow.node.nodes.EndNode; +import com.codingapi.flow.node.nodes.StartNode; +import com.codingapi.flow.operator.OperatorIdentityMatchMode; +import com.codingapi.flow.operator.OperatorIdentityContext; +import com.codingapi.flow.pojo.body.FlowAdviceBody; +import com.codingapi.flow.pojo.request.FlowActionRequest; +import com.codingapi.flow.pojo.request.FlowCreateRequest; +import com.codingapi.flow.pojo.request.FlowRevokeRequest; +import com.codingapi.flow.pojo.request.FlowUrgeRequest; +import com.codingapi.flow.record.FlowRecord; +import com.codingapi.flow.script.factory.FlowGroovyScriptFactory; +import com.codingapi.flow.strategy.node.FormFieldPermissionStrategy; +import com.codingapi.flow.strategy.node.MultiOperatorAuditStrategy; +import com.codingapi.flow.strategy.node.OperatorLoadStrategy; +import com.codingapi.flow.strategy.node.RevokeStrategy; +import com.codingapi.flow.strategy.node.SameOperatorAuditStrategy; +import com.codingapi.flow.user.User; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.WorkflowBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 身份边界行为测试(issue #295 缺口 2 / 3 / 4 / 7)。 + * + *

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

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

    覆盖点: + *

      + *
    1. 撤回 / 催办的身份归属校验({@code FlowRevokeService} / {@code FlowUrgeService});
    2. + *
    3. 加签同人异身份查重、减签身份维度({@code AddAuditAction} / {@code ReduceAuditAction});
    4. + *
    5. 转交 {@code forwardOperatorIdentity} 落库、同人换身份办理不记干预;
    6. + *
    7. {@code BaseAuditNode} 同人自动通过的身份过滤。
    8. + *
    + */ +class OperatorIdentityBoundaryTest { + + private static final long INITIATOR = 1; + private static final long APPROVER = 2; + private static final long SECOND_APPROVER = 3; + + private static final String DEPARTMENT_1 = "department1"; + private static final String DEPARTMENT_2 = "department2"; + + private MyFlowServiceFactory factory; + private final Map data = Map.of("name", "lorne"); + + @BeforeEach + void setUp() { + factory = new MyFlowServiceFactory(); + factory.userGateway.save(new User(INITIATOR, "initiator")); + factory.userGateway.save(new User(APPROVER, "approver")); + factory.userGateway.save(new User(SECOND_APPROVER, "second")); + GatewayContext.getInstance().setFlowOperatorGateway(factory.userGateway); + } + + @AfterEach + void tearDown() { + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.STRICT); + } + + // ==================== 缺口 2:撤回 / 催办的身份归属 ==================== + + /** + * 测试目标:USER_ONLY 模式下,同一人换身份仍可撤回自己提交的记录。 + * 前置条件:发起人以 department1 发起并提交,流程停在审批节点待办。 + * 执行步骤:以 department2 身份撤回发起记录。 + * 期望断言:不抛异常,发起记录回到待办,审批待办被撤销。 + */ + @Test + void should_allow_revoke_with_other_identity_in_user_only_mode() { + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); + Workflow workflow = saveFlow("identity-revoke-user-only", APPROVER); + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + assertDoesNotThrow(() -> factory.flowService.revoke( + new FlowRevokeRequest(startRecordId, INITIATOR, DEPARTMENT_2))); + + assertTrue(factory.flowRecordRepository.get(startRecordId).isTodo(), "撤回后发起记录应回到待办"); + assertEquals(0, factory.flowRecordRepository.findTodoByOperator(APPROVER).size(), + "审批待办应被撤销"); + } + + /** + * 测试目标:STRICT 模式下,同一人换身份不能撤回记录(身份是独立参与人)。 + * 前置条件:发起人以 department1 发起并提交。 + * 执行步骤:以 department2 身份撤回发起记录。 + * 期望断言:抛出状态异常,记录仍为已办。 + */ + @Test + void should_reject_revoke_with_other_identity_in_strict_mode() { + Workflow workflow = saveFlow("identity-revoke-strict", APPROVER); + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + assertThrows(FlowStateException.class, () -> factory.flowService.revoke( + new FlowRevokeRequest(startRecordId, INITIATOR, DEPARTMENT_2))); + assertFalse(factory.flowRecordRepository.get(startRecordId).isTodo(), "拒绝撤回时记录保持已办"); + } + + /** + * 测试目标:USER_ONLY 模式下,同一人换身份仍可催办自己提交的记录。 + * 前置条件:发起人以 department1 发起并提交。 + * 执行步骤:以 department2 身份催办。 + * 期望断言:不抛异常。 + */ + @Test + void should_allow_urge_with_other_identity_in_user_only_mode() { + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); + Workflow workflow = saveFlow("identity-urge-user-only", APPROVER); + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + assertDoesNotThrow(() -> factory.flowService.urge( + new FlowUrgeRequest(startRecordId, INITIATOR, DEPARTMENT_2))); + } + + /** + * 测试目标:STRICT 模式下,同一人换身份不能催办记录。 + * 前置条件:发起人以 department1 发起并提交。 + * 执行步骤:以 department2 身份催办。 + * 期望断言:抛出状态异常。 + */ + @Test + void should_reject_urge_with_other_identity_in_strict_mode() { + Workflow workflow = saveFlow("identity-urge-strict", APPROVER); + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + assertThrows(FlowStateException.class, () -> factory.flowService.urge( + new FlowUrgeRequest(startRecordId, INITIATOR, DEPARTMENT_2))); + } + + // ==================== 缺口 3:加签 / 减签的身份维度 ==================== + + /** + * 测试目标:USER_ONLY 模式下,为「同一人」加签会被拒绝(该人已在节点待办队列中)。 + * 前置条件:审批记录归属 approver + department1;网关回退为默认身份,加签目标解析为 (approver, 默认身份)。 + * 执行步骤:以 department1 身份对当前记录加签,目标为同一人。 + * 期望断言:抛出执行异常,节点记录数不变。 + */ + @Test + void should_reject_add_audit_for_same_user_in_user_only_mode() { + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); + prepareApprovalRecordWithIdentity("identity-add-audit-user-only"); + FlowRecord approvalRecord = currentApprovalRecord(); + + assertThrows(FlowExecutionException.class, () -> addAudit(APPROVER, DEPARTMENT_1, APPROVER)); + assertEquals(1, recordsOfNode(approvalRecord).size(), "拒绝加签时不应新增记录"); + } + + /** + * 测试目标:STRICT 模式下,加签目标携带默认身份时与 (approver, department1) 不是同一参与人,允许加签。 + * 前置条件:审批记录归属 approver + department1;网关回退为默认身份。 + * 执行步骤:以 department1 身份加签同一人员(默认身份)。 + * 期望断言:不抛异常,节点上新增一条该人员的记录。 + */ + @Test + void should_allow_add_audit_for_same_user_with_other_identity_in_strict_mode() { + prepareApprovalRecordWithIdentity("identity-add-audit-strict"); + FlowRecord approvalRecord = currentApprovalRecord(); + + assertDoesNotThrow(() -> addAudit(APPROVER, DEPARTMENT_1, APPROVER)); + assertEquals(2, recordsOfNode(approvalRecord).size(), "STRICT 下另一身份应视为独立参与人"); + } + + /** + * 测试目标:USER_ONLY 模式下,减签按「人」生效,可以撤下同一人员以另一身份持有的待办。 + * 前置条件:审批节点依次审批 b1(默认身份)、b2(department2);网关中 b2 回退为默认身份。 + * 执行步骤:b1 以默认身份减签 b2(目标解析为默认身份)。 + * 期望断言:b2 的记录被撤销,b2 不再有待办。 + */ + @Test + void should_reduce_pending_record_of_same_user_with_other_identity_in_user_only_mode() { + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); + FlowRecord secondRecord = prepareSequenceApproval("identity-reduce-user-only"); + + assertDoesNotThrow(() -> reduceAudit(APPROVER, SECOND_APPROVER)); + + assertTrue(factory.flowRecordRepository.get(secondRecord.getId()).isRevoked(), + "USER_ONLY 下应按人撤下该待办"); + assertEquals(0, factory.flowRecordRepository.findTodoByOperator(SECOND_APPROVER).size()); + } + + /** + * 测试目标:STRICT 模式下,减签目标身份不一致时视为目标不存在。 + * 前置条件:审批节点依次审批 b1(默认身份)、b2(department2);网关中 b2 回退为默认身份。 + * 执行步骤:b1 减签 b2(目标解析为默认身份)。 + * 期望断言:抛出执行异常,b2 的记录保持待审批。 + */ + @Test + void should_reject_reduce_when_target_identity_differs_in_strict_mode() { + FlowRecord secondRecord = prepareSequenceApproval("identity-reduce-strict"); + + assertThrows(FlowExecutionException.class, () -> reduceAudit(APPROVER, SECOND_APPROVER)); + + assertTrue(factory.flowRecordRepository.get(secondRecord.getId()).isPendingApproval(), + "STRICT 下身份不一致不应命中目标记录"); + } + + // ==================== 缺口 4:转交身份落库 / 同人换身份不算干预 ==================== + + /** + * 测试目标:转交后新记录的操作人身份记录被转交人的身份。 + * 前置条件:网关中 second 携带 department2 身份,审批记录归属 approver。 + * 执行步骤:approver 将待办转交给 second。 + * 期望断言:新记录的操作人身份为 department2。 + */ + @Test + void should_record_forward_operator_identity_when_transfer_target_carries_identity() { + factory.userGateway.save(User.withIdentity(SECOND_APPROVER, "second", DEPARTMENT_2)); + Workflow workflow = saveFlow("identity-transfer", APPROVER); + long startRecordId = createFlow(workflow, ""); + submit(workflow, startRecordId, ""); + + FlowRecord approvalRecord = currentApprovalRecord(); + transfer(approvalRecord, APPROVER, SECOND_APPROVER); + + FlowRecord transferred = factory.flowRecordRepository.findTodoByOperator(SECOND_APPROVER).get(0); + assertEquals(DEPARTMENT_2, transferred.getCurrentOperatorIdentity(), "新记录操作人应携带目标身份"); + } + + /** + * 测试目标:人员存在转交链时,新记录落库被转交人(源操作人)的身份。 + * 前置条件:approver 携带 department1 身份并把待办转交给 second(department2)。 + * 执行步骤:发起并提交,使审批节点按转交链生成记录。 + * 期望断言:记录归属 second(department2),转交人字段为 approver + department1。 + */ + @Test + void should_record_forward_operator_identity_from_forward_chain() { + factory.userGateway.save(new ForwardingUser(APPROVER, "approver", DEPARTMENT_1, + User.withIdentity(SECOND_APPROVER, "second", DEPARTMENT_2))); + Workflow workflow = saveFlow("identity-forward-chain", APPROVER); + long startRecordId = createFlow(workflow, ""); + submit(workflow, startRecordId, ""); + + FlowRecord forwarded = todoRecordOf(SECOND_APPROVER); + assertEquals(DEPARTMENT_2, forwarded.getCurrentOperatorIdentity(), "转交链末端操作人身份应落库"); + assertEquals(APPROVER, forwarded.getForwardOperatorId()); + assertEquals(DEPARTMENT_1, forwarded.getForwardOperatorIdentity(), "被转交人身份应落库"); + } + + /** + * 测试目标:USER_ONLY 模式下,同一人换身份办理自己的记录不算流程干预,且操作身份被留痕。 + * 前置条件:发起人以 department1 发起,开始节点记录归属 (initiator, department1)。 + * 执行步骤:以 department2 身份提交开始节点记录。 + * 期望断言:不抛异常,干预人字段保持默认空串,流转出的记录提交人身份为 department2。 + */ + @Test + void should_not_record_interfere_when_same_user_uses_other_identity() { + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); + Workflow workflow = saveFlow("identity-interfere", APPROVER); + long startRecordId = createFlow(workflow, DEPARTMENT_1); + + assertDoesNotThrow(() -> submit(workflow, startRecordId, DEPARTMENT_2)); + + FlowRecord record = factory.flowRecordRepository.get(startRecordId); + assertEquals(0, record.getInterferedOperatorId(), "同人换身份办理不应记为干预"); + assertEquals("", record.getInterferedOperatorIdentity(), "干预人身份应保持默认空串"); + assertEquals(DEPARTMENT_2, currentApprovalRecord().getSubmitOperatorIdentity(), "操作身份应留痕"); + } + + // ==================== 缺口 7:同人自动通过的身份过滤 ==================== + + /** + * 测试目标:USER_ONLY 模式下,提交人换身份后仍视为同人,审批节点自动通过。 + * 前置条件:审批节点唯一审批人为提交人本人(网关默认身份),开启相同人员自动审批; + * 提交时声明 department1,使记录上的提交人身份与审批人身份不同。 + * 执行步骤:发起并提交到审批节点。 + * 期望断言:提交人不再有审批待办,流程直接流转到下游审批节点。 + */ + @Test + void should_auto_pass_when_same_user_uses_other_identity_in_user_only_mode() { + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); + Workflow workflow = saveAutoPassFlow("identity-auto-pass-user-only"); + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + assertEquals(0, factory.flowRecordRepository.findTodoByOperator(INITIATOR).size(), + "同人自动通过后提交人不应有审批待办"); + assertEquals(1, factory.flowRecordRepository.findTodoByOperator(APPROVER).size(), + "流程应直接流转到下游审批节点"); + } + + /** + * 测试目标:STRICT 模式下,提交人与审批人身份不一致时不自动通过,仍生成审批待办。 + * 前置条件:审批节点唯一审批人为提交人本人(网关默认身份),开启相同人员自动审批; + * 提交时声明 department1。 + * 执行步骤:发起并提交到审批节点。 + * 期望断言:提交人以默认身份获得一条审批待办,流程未向下流转。 + */ + @Test + void should_not_auto_pass_when_same_user_uses_other_identity_in_strict_mode() { + Workflow workflow = saveAutoPassFlow("identity-auto-pass-strict"); + long startRecordId = createFlow(workflow, DEPARTMENT_1); + submit(workflow, startRecordId, DEPARTMENT_1); + + assertEquals(1, factory.flowRecordRepository.findTodoByOperator(INITIATOR).size(), + "STRICT 下身份不一致不应自动通过"); + assertEquals(0, factory.flowRecordRepository.findTodoByOperator(APPROVER).size(), + "流程不应流转到下游审批节点"); + } + + // ==================== 流程构建 ==================== + + /** + * 构建 Start(可撤回) -> Approval(指定审批人,多人为依次审批) -> End 的流程。 + */ + private Workflow saveFlow(String code, long... approverIds) { + StartNode startNode = startNode(code); + NodeStrategyBuilder builder = NodeStrategyBuilder.builder() + .addStrategy(fieldPermission(code)) + .addStrategy(new OperatorLoadStrategy(FlowGroovyScriptFactory + .createOperatorLoadScript("def run(request){return [" + joinIds(approverIds) + "]}") + .getKey())); + if (approverIds.length > 1) { + builder.addStrategy(new MultiOperatorAuditStrategy(MultiOperatorAuditStrategy.Type.SEQUENCE, 0f)); + } + ApprovalNode approvalNode = ApprovalNode.builder() + .name("审批") + .strategies(builder.build()) + .build(); + Workflow workflow = WorkflowBuilder.builder() + .title("身份边界流程") + .code(code) + .createdOperator(new User(INITIATOR, "initiator")) + .form(form(code)) + .addNode(startNode) + .addNode(approvalNode) + .addNode(EndNode.builder().build()) + .build(); + factory.workflowService.saveWorkflow(workflow); + return workflow; + } + + /** + * 构建 Start -> Approval(提交人本人, 相同人员自动审批) -> Approval(下游审批人) -> End 的流程。 + */ + private Workflow saveAutoPassFlow(String code) { + StartNode startNode = startNode(code); + ApprovalNode selfNode = ApprovalNode.builder() + .name("同人审批") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(fieldPermission(code)) + .addStrategy(new OperatorLoadStrategy(FlowGroovyScriptFactory + .createOperatorLoadScript("def run(request){return [" + INITIATOR + "]}") + .getKey())) + .addStrategy(new SameOperatorAuditStrategy(SameOperatorAuditStrategy.Type.AUTO_PASS)) + .build()) + .build(); + ApprovalNode nextNode = ApprovalNode.builder() + .name("下游审批") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(fieldPermission(code)) + .addStrategy(new OperatorLoadStrategy(FlowGroovyScriptFactory + .createOperatorLoadScript("def run(request){return [" + APPROVER + "]}") + .getKey())) + .build()) + .build(); + Workflow workflow = WorkflowBuilder.builder() + .title("同人自动通过流程") + .code(code) + .createdOperator(new User(INITIATOR, "initiator")) + .form(form(code)) + .addNode(startNode) + .addNode(selfNode) + .addNode(nextNode) + .addNode(EndNode.builder().build()) + .build(); + factory.workflowService.saveWorkflow(workflow); + return workflow; + } + + private StartNode startNode(String code) { + return StartNode.builder() + .strategies(NodeStrategyBuilder.builder() + .addStrategy(fieldPermission(code)) + .addStrategy(new RevokeStrategy(true, RevokeStrategy.Type.REVOKE_CURRENT)) + .build()) + .actions(ActionBuilder.builder() + .addAction(CustomAction.defaultAction()) + .build()) + .build(); + } + + private FlowForm form(String code) { + return FlowFormBuilder.builder() + .name("身份边界流程") + .code(code) + .addField("请假人", "name", DataType.STRING) + .build(); + } + + private FormFieldPermissionStrategy fieldPermission(String code) { + return new FormFieldPermissionStrategy(FormFieldPermissionsBuilder.builder() + .addPermission(code, "name", PermissionType.WRITE) + .build()); + } + + private String joinIds(long... ids) { + StringBuilder builder = new StringBuilder(); + for (long id : ids) { + if (!builder.isEmpty()) { + builder.append(','); + } + builder.append(id); + } + return builder.toString(); + } + + // ==================== 场景准备 ==================== + + /** + * 让审批记录归属 {@code (approver, department1)},随后把网关中的 approver 回退为默认身份, + * 使加签 / 减签目标解析为 {@code (approver, 默认身份)}——即「记录上的身份与网关默认身份不同」。 + */ + private void prepareApprovalRecordWithIdentity(String code) { + factory.userGateway.save(User.withIdentity(APPROVER, "approver", DEPARTMENT_1)); + Workflow workflow = saveFlow(code, APPROVER); + long startRecordId = createFlow(workflow, ""); + submit(workflow, startRecordId, ""); + assertEquals(DEPARTMENT_1, currentApprovalRecord().getCurrentOperatorIdentity(), + "审批记录应携带 department1 身份"); + // 网关回退:后续动作的目标人员按默认身份解析 + factory.userGateway.save(new User(APPROVER, "approver")); + } + + /** + * 构建依次审批流程并推进到审批节点:b1 为默认身份、b2 携带 department2, + * 随后把网关中的 b2 回退为默认身份;返回 b2 的待审批记录。 + */ + private FlowRecord prepareSequenceApproval(String code) { + factory.userGateway.save(User.withIdentity(SECOND_APPROVER, "second", DEPARTMENT_2)); + Workflow workflow = saveFlow(code, APPROVER, SECOND_APPROVER); + long startRecordId = createFlow(workflow, ""); + submit(workflow, startRecordId, ""); + + FlowRecord secondRecord = pendingRecordOf(SECOND_APPROVER); + assertEquals(DEPARTMENT_2, secondRecord.getCurrentOperatorIdentity(), + "b2 的记录应携带 department2 身份"); + // 网关回退:减签目标按默认身份解析 + factory.userGateway.save(new User(SECOND_APPROVER, "second")); + return secondRecord; + } + + // ==================== 动作入口 ==================== + + private long createFlow(Workflow workflow, String operatorIdentity) { + FlowCreateRequest request = new FlowCreateRequest(); + request.setWorkCode(workflow.getCode()); + request.setFormData(data); + request.setActionId(startAction(workflow).id()); + request.setOperatorId(INITIATOR); + request.setOperatorIdentity(operatorIdentity); + return factory.flowService.create(request); + } + + private void submit(Workflow workflow, long recordId, String operatorIdentity) { + FlowAdviceBody advice = new FlowAdviceBody(startAction(workflow).id(), "提交", INITIATOR); + advice.setOperatorIdentity(operatorIdentity); + FlowActionRequest request = new FlowActionRequest(); + request.setFormData(data); + request.setRecordId(recordId); + request.setAdvice(advice); + factory.flowService.action(request); + } + + private void addAudit(long operatorId, String operatorIdentity, long targetOperatorId) { + FlowRecord record = todoRecordOf(operatorId); + FlowAdviceBody advice = new FlowAdviceBody( + actionOf(record, ActionType.ADD_AUDIT).id(), "加签", operatorId); + advice.setOperatorIdentity(operatorIdentity); + advice.setForwardOperatorIds(List.of(targetOperatorId)); + FlowActionRequest request = new FlowActionRequest(); + request.setFormData(data); + request.setRecordId(record.getId()); + request.setAdvice(advice); + factory.flowService.action(request); + } + + private void reduceAudit(long operatorId, long targetOperatorId) { + FlowRecord record = todoRecordOf(operatorId); + FlowAdviceBody advice = new FlowAdviceBody( + actionOf(record, ActionType.REDUCE_AUDIT).id(), "减签", operatorId); + advice.setForwardOperatorIds(List.of(targetOperatorId)); + FlowActionRequest request = new FlowActionRequest(); + request.setFormData(data); + request.setRecordId(record.getId()); + request.setAdvice(advice); + factory.flowService.action(request); + } + + private void transfer(FlowRecord record, long operatorId, long targetOperatorId) { + FlowAdviceBody advice = new FlowAdviceBody( + actionOf(record, ActionType.TRANSFER).id(), "转交", operatorId); + advice.setForwardOperatorIds(List.of(targetOperatorId)); + FlowActionRequest request = new FlowActionRequest(); + request.setFormData(data); + request.setRecordId(record.getId()); + request.setAdvice(advice); + factory.flowService.action(request); + } + + // ==================== 断言 / 查询助手 ==================== + + private IFlowAction startAction(Workflow workflow) { + return workflow.getStartNode().actionManager().getActions().get(0); + } + + private IFlowAction actionOf(FlowRecord record, ActionType type) { + IFlowAction action = workflowOf(record).getFlowNode(record.getNodeId()) + .actionManager().getActionByType(type.name()); + assertTrue(action != null, "节点缺少动作:" + type); + return action; + } + + private Workflow workflowOf(FlowRecord record) { + return factory.workflowService.getWorkflowRuntime(record.getWorkRuntimeId()).toWorkflow(); + } + + private FlowRecord todoRecordOf(long operatorId) { + List records = factory.flowRecordRepository.findTodoByOperator(operatorId); + assertEquals(1, records.size(), "操作人应有且仅有一条待办"); + return records.get(0); + } + + /** + * 当前审批节点上 approver 的待办记录。 + */ + private FlowRecord currentApprovalRecord() { + return todoRecordOf(APPROVER); + } + + /** + * 指定人员在当前流程实例中的待审批记录(含顺序审批里尚未激活的隐藏记录)。 + */ + private FlowRecord pendingRecordOf(long operatorId) { + FlowRecord current = todoRecordOf(APPROVER); + return factory.flowRecordRepository.findCurrentNodeRecords(current.getFromId(), current.getNodeId()) + .stream() + .filter(FlowRecord::isPendingApproval) + .filter(record -> record.getCurrentOperatorId() == operatorId) + .findFirst().orElseThrow(); + } + + /** + * 同一节点实例上的全部记录(含顺序审批里尚未激活的隐藏记录)。 + */ + private List recordsOfNode(FlowRecord anyRecord) { + return factory.flowRecordRepository.findCurrentNodeRecords(anyRecord.getFromId(), anyRecord.getNodeId()); + } + + /** + * 携带转交链的人员:源操作人以指定身份存在,且把待办转交给 {@code forwardOperator}。 + */ + private static final class ForwardingUser extends User { + + private ForwardingUser(long userId, String name, String identity, User forwardOperator) { + super(userId, name, false, forwardOperator, identity); + } + } +} 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/service/OperatorIdentityUserOnlyPermissionTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityUserOnlyPermissionTest.java new file mode 100644 index 00000000..fe797324 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/OperatorIdentityUserOnlyPermissionTest.java @@ -0,0 +1,193 @@ +package com.codingapi.flow.service; + +import com.codingapi.flow.action.IFlowAction; +import com.codingapi.flow.action.actions.CustomAction; +import com.codingapi.flow.builder.ActionBuilder; +import com.codingapi.flow.builder.FormFieldPermissionsBuilder; +import com.codingapi.flow.builder.NodeStrategyBuilder; +import com.codingapi.flow.context.GatewayContext; +import com.codingapi.flow.exception.FlowStateException; +import com.codingapi.flow.factory.MyFlowServiceFactory; +import com.codingapi.flow.form.DataType; +import com.codingapi.flow.form.FlowForm; +import com.codingapi.flow.form.FlowFormBuilder; +import com.codingapi.flow.form.permission.PermissionType; +import com.codingapi.flow.manager.WorkflowStrategyManager; +import com.codingapi.flow.node.nodes.ApprovalNode; +import com.codingapi.flow.node.nodes.EndNode; +import com.codingapi.flow.node.nodes.StartNode; +import com.codingapi.flow.operator.OperatorIdentityMatchMode; +import com.codingapi.flow.operator.OperatorIdentityContext; +import com.codingapi.flow.pojo.body.FlowAdviceBody; +import com.codingapi.flow.pojo.request.FlowActionRequest; +import com.codingapi.flow.pojo.request.FlowCreateRequest; +import com.codingapi.flow.pojo.request.FlowDeleteRequest; +import com.codingapi.flow.record.FlowRecord; +import com.codingapi.flow.script.factory.FlowGroovyScriptFactory; +import com.codingapi.flow.strategy.node.FormFieldPermissionStrategy; +import com.codingapi.flow.strategy.node.OperatorLoadStrategy; +import com.codingapi.flow.strategy.workflow.InterfereStrategy; +import com.codingapi.flow.user.User; +import com.codingapi.flow.workflow.Workflow; +import com.codingapi.flow.workflow.WorkflowBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 不限制身份模式下的办理权限测试(issue #297)。 + * + *

    身份只用于脚本执行与留痕:同一个人的两个身份不再互相阻断办理; + * 不同的人仍然被拒绝。严格模式的既有语义由 {@link OperatorIdentityPermissionTest} 覆盖。 + */ +class OperatorIdentityUserOnlyPermissionTest { + + private MyFlowServiceFactory factory; + private Workflow workflow; + + @BeforeEach + void setUp() { + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.USER_ONLY); + + User user1 = User.withIdentity(1, "user1", "department1"); + User boss = new User(2, "boss"); + factory = new MyFlowServiceFactory(); + factory.userGateway.save(user1); + factory.userGateway.save(boss); + GatewayContext.getInstance().setFlowOperatorGateway(factory.userGateway); + + FlowForm form = FlowFormBuilder.builder() + .name("请假流程") + .code("leave-user-only") + .addField("请假人", "name", DataType.STRING) + .build(); + + FormFieldPermissionsBuilder permissions = FormFieldPermissionsBuilder.builder() + .addPermission("leave-user-only", "name", PermissionType.WRITE); + + StartNode startNode = StartNode.builder() + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(permissions.build())) + .build()) + .actions(ActionBuilder.builder() + .addAction(CustomAction.defaultAction()) + .build()) + .build(); + + ApprovalNode approvalNode = ApprovalNode.builder() + .name("经理审批") + .strategies(NodeStrategyBuilder.builder() + .addStrategy(new FormFieldPermissionStrategy(permissions.build())) + .addStrategy(new OperatorLoadStrategy( + FlowGroovyScriptFactory.createOperatorLoadScript("def run(request){return [2]}").getKey())) + .build()) + .build(); + + EndNode endNode = EndNode.builder().build(); + + workflow = WorkflowBuilder.builder() + .title("请假流程") + .code("leave-user-only") + .createdOperator(user1) + .form(form) + .addNode(startNode) + .addNode(approvalNode) + .addNode(endNode) + .build(); + factory.workflowService.saveWorkflow(workflow); + } + + @AfterEach + void tearDown() { + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.STRICT); + } + + private Map formData() { + return Map.of("name", "lorne"); + } + + private List startActions() { + return workflow.getStartNode().actionManager().getActions(); + } + + private long createFlow(String operatorIdentity) { + FlowCreateRequest request = new FlowCreateRequest(); + request.setWorkCode(workflow.getCode()); + request.setFormData(formData()); + request.setActionId(startActions().get(0).id()); + request.setOperatorId(1); + request.setOperatorIdentity(operatorIdentity); + return factory.flowService.create(request); + } + + private void action(long recordId, long operatorId, String operatorIdentity) { + FlowActionRequest actionRequest = new FlowActionRequest(); + actionRequest.setFormData(formData()); + actionRequest.setRecordId(recordId); + FlowAdviceBody advice = new FlowAdviceBody(startActions().get(0).id(), "同意", operatorId); + advice.setOperatorIdentity(operatorIdentity); + actionRequest.setAdvice(advice); + factory.flowService.action(actionRequest); + } + + /** + * 单元层面:USER_ONLY 下只比人员,忽略身份;换一个人仍然拒绝。 + */ + @Test + void should_match_only_user_id_in_user_only_mode() { + WorkflowStrategyManager manager = new WorkflowStrategyManager(List.of(new InterfereStrategy())); + + assertDoesNotThrow(() -> manager.verifyOperator(User.withIdentity(1, "user1", "department1"), 1, "department2")); + assertDoesNotThrow(() -> manager.verifyOperator(User.withIdentity(1, "user1", "department2"), 1, "")); + assertThrows(FlowStateException.class, + () -> manager.verifyOperator(User.withIdentity(2, "boss", "department1"), 1, "department1")); + } + + /** + * 审批:同一人换身份可以办理自己的待办,且本次操作身份被留痕到后续记录。 + */ + @Test + void should_allow_action_with_other_identity_and_record_submit_identity() { + long recordId = createFlow("department1"); + FlowRecord record = factory.flowRecordRepository.get(recordId); + assertEquals("department1", record.getCurrentOperatorIdentity()); + + assertDoesNotThrow(() -> action(recordId, 1, "department2")); + assertFalse(factory.flowRecordRepository.get(recordId).isTodo(), "同人换身份办理后应已办结"); + + List bossTodos = factory.flowRecordRepository.findTodoByOperator(2); + assertEquals(1, bossTodos.size()); + assertEquals("department2", bossTodos.get(0).getSubmitOperatorIdentity(), + "提交人身份应记录本次操作携带的身份"); + } + + /** + * 审批:其他人以任何身份都不能办理不属于自己的待办。 + */ + @Test + void should_reject_other_user_in_user_only_mode() { + long recordId = createFlow("department1"); + + assertThrows(FlowStateException.class, () -> action(recordId, 2, "department1")); + assertTrue(factory.flowRecordRepository.get(recordId).isTodo()); + } + + /** + * 删除:同一人换身份可以删除自己的待办。 + */ + @Test + void should_allow_delete_with_other_identity() { + long recordId = createFlow("department1"); + + assertDoesNotThrow(() -> factory.flowService.delete(new FlowDeleteRequest(recordId, 1, "department2"))); + } +} diff --git a/flow-engine-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); + } +} 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..f28343bf 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/user/User.java @@ -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; public class User implements IFlowOperator { @@ -9,24 +10,47 @@ public class User implements IFlowOperator { 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); + } + + /** + * 返回同一用户以指定身份参与的副本(保留管理员、转交人等属性) + */ + public User asIdentity(String identity) { + return new User(userId, name, manager, forwardOperator, OperatorIdentity.of(identity).value()); } @Override @@ -44,6 +68,12 @@ public boolean isFlowManager() { return manager; } + @Override + public String getIdentity() { + return identity; + } + + @Override public IFlowOperator forwardOperator(GroovyScriptRequest request) { return forwardOperator; diff --git a/flow-engine-starter-api/src/main/java/com/codingapi/flow/api/OperatorIdentityHeader.java b/flow-engine-starter-api/src/main/java/com/codingapi/flow/api/OperatorIdentityHeader.java new file mode 100644 index 00000000..d1583e7a --- /dev/null +++ b/flow-engine-starter-api/src/main/java/com/codingapi/flow/api/OperatorIdentityHeader.java @@ -0,0 +1,49 @@ +package com.codingapi.flow.api; + +/** + * 身份请求头契约(issue #301 / #311 P5)。 + * + *

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

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

    为兼容旧前端与 curl 直连,服务端仍保留 query 读取,但请求头优先。 + */ +public final class OperatorIdentityHeader { + + /** + * 当前身份的请求头名称 + */ + public static final String OPERATOR_IDENTITY = "X-Operator-Identity"; + + /** + * 查询身份范围的请求头名称,取值 {@code ALL} / {@code LOCKED} + */ + public static final String IDENTITY_SCOPE = "X-Identity-Scope"; + + /** + * 是否锁定身份查询的请求头名称,取值 {@code true} / {@code false} + */ + public static final String LOCK_IDENTITY = "X-Lock-Identity"; + + private OperatorIdentityHeader() { + } + + /** + * 选取身份原始值:请求头优先,其次请求参数。 + * + * @param headerValue 请求头中的原始值,未携带时为 {@code null} + * @param parameterValue 请求参数中的原始值 + * @param parameterPresent 请求参数是否显式出现(区分「未传」与「传了空串」) + * @return 原始值;两者都未携带时返回 {@code null} + */ + public static String resolve(String headerValue, String parameterValue, boolean parameterPresent) { + if (headerValue != null) { + return headerValue; + } + return parameterPresent ? parameterValue : null; + } +} diff --git a/flow-engine-starter-api/src/main/java/com/codingapi/flow/api/controller/FlowRecordController.java b/flow-engine-starter-api/src/main/java/com/codingapi/flow/api/controller/FlowRecordController.java index d07e170b..dc465c93 100644 --- a/flow-engine-starter-api/src/main/java/com/codingapi/flow/api/controller/FlowRecordController.java +++ b/flow-engine-starter-api/src/main/java/com/codingapi/flow/api/controller/FlowRecordController.java @@ -3,6 +3,8 @@ import com.codingapi.flow.mock.MockInstance; import com.codingapi.flow.mock.MockInstanceFactory; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.api.OperatorIdentityHeader; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.pojo.request.*; import com.codingapi.flow.pojo.response.ActionResponse; import com.codingapi.flow.pojo.response.FlowContent; @@ -53,27 +55,58 @@ private long loadCurrentOperatorId() { } } + /** + * 当前操作人的身份标识(issue #288 / #301)。 + * + *

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

    之所以以请求头优先:查询接口用 {@code SearchRequest} 接收请求,会把 query 参数当作实体 + * 过滤字段解析,身份放在 query 会让列表接口直接 500(issue #301)。 + */ + private String loadCurrentOperatorIdentity() { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + String raw = OperatorIdentityHeader.resolve( + request.getHeader(OperatorIdentityHeader.OPERATOR_IDENTITY), + request.getParameter("operatorIdentity"), + request.getParameterMap().containsKey("operatorIdentity")); + if (raw != null) { + // 入口即校验:长度 / 分隔符 / 控制字符不合法时直接拒绝,避免拖到落库阶段才失败 + return OperatorIdentity.of(raw).validate().value(); + } + // 覆盖了 operatorId(联调、无登录态场景)时不再继承登录用户的身份, + // 否则会得到「目标人员 + 当前登录人身份」的错配组合(issue #288 评审修复) + if (StringUtils.hasText(request.getParameter("operatorId"))) { + return OperatorIdentity.DEFAULT.value(); + } + IFlowOperator current = (IFlowOperator) UserContext.getInstance().current(); + return current == null ? OperatorIdentity.DEFAULT.value() : OperatorIdentity.of(current).value(); + } + @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 +115,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 +123,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 +132,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 +140,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 +154,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 +168,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 +181,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-api/src/test/java/com/codingapi/flow/api/OperatorIdentityHeaderTest.java b/flow-engine-starter-api/src/test/java/com/codingapi/flow/api/OperatorIdentityHeaderTest.java new file mode 100644 index 00000000..3f927864 --- /dev/null +++ b/flow-engine-starter-api/src/test/java/com/codingapi/flow/api/OperatorIdentityHeaderTest.java @@ -0,0 +1,70 @@ +package com.codingapi.flow.api; + +import com.codingapi.flow.exception.FlowValidationException; +import com.codingapi.flow.operator.OperatorIdentity; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * 身份取值优先级测试(issue #301)。 + * + *

    背景:身份原先只从 query 参数读取,而引擎查询接口用 {@code SearchRequest} 接收请求, + * 会把 query 参数当成实体过滤字段,导致 + * {@code Field operatorIdentity not found in class hierarchy}。 + * 改为请求头优先,同时保留 query 兼容。 + */ +class OperatorIdentityHeaderTest { + + @Test + void should_prefer_header_over_parameter() { + // given:请求头与 query 同时携带,且取值不同 + String header = "department1"; + String parameter = "department2"; + + // when + String raw = OperatorIdentityHeader.resolve(header, parameter, true); + + // then:请求头优先 + assertEquals("department1", OperatorIdentity.of(raw).validate().value()); + } + + @Test + void should_fallback_to_parameter_when_header_absent() { + // given:仅 query 携带(旧前端 / curl 直连) + // when + String raw = OperatorIdentityHeader.resolve(null, "department1", true); + + // then + assertEquals("department1", OperatorIdentity.of(raw).validate().value()); + } + + @Test + void should_return_null_when_neither_present() { + // given / when:两者都未携带,交由调用方回退到登录用户身份 + String raw = OperatorIdentityHeader.resolve(null, null, false); + + // then + assertNull(raw); + } + + @Test + void should_treat_empty_header_as_default_identity() { + // given:显式选择「默认身份」时请求头为空串,需要与「未携带」区分 + // when + String raw = OperatorIdentityHeader.resolve("", "department1", true); + + // then:空串表示默认身份,不能回退到 query + assertEquals(OperatorIdentity.DEFAULT.value(), OperatorIdentity.of(raw).validate().value()); + } + + @Test + void should_reject_invalid_identity_from_header() { + // given:请求头携带非法身份(包含合并键分隔符) + // when / then:入口即拒绝,避免污染落库与缓存键 + String raw = OperatorIdentityHeader.resolve("department#1", null, false); + assertThrows(FlowValidationException.class, () -> OperatorIdentity.of(raw).validate().value()); + } +} diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertor.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertor.java index 56a0442e..3370ba16 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertor.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertor.java @@ -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.of(todoRecord.getCurrentOperatorIdentity()).value()); content.setSubmitOperatorId(todoRecord.getSubmitOperatorId()); content.setSubmitOperatorName(todoRecord.getSubmitOperatorName()); + content.setSubmitOperatorIdentity(OperatorIdentity.of(todoRecord.getSubmitOperatorIdentity()).value()); content.setCreateTime(todoRecord.getCreateTime()); content.setCreateOperatorId(todoRecord.getCreateOperatorId()); content.setCreateOperatorName(todoRecord.getCreateOperatorName()); + content.setCreateOperatorIdentity(OperatorIdentity.of(todoRecord.getCreateOperatorIdentity()).value()); content.setTodoKey(todoRecord.getTodoKey()); content.setMargeCount(todoRecord.getMargeCount()); content.setMergeable(todoRecord.getMergeable()); @@ -51,17 +55,24 @@ public static FlowRecordContent convert(FlowRecordEntity record){ content.setReadTime(record.getReadTime()); content.setCurrentOperatorId(record.getCurrentOperatorId()); content.setCurrentOperatorName(record.getCurrentOperatorName()); + content.setCurrentOperatorIdentity(OperatorIdentity.of(record.getCurrentOperatorIdentity()).value()); content.setSubmitOperatorId(record.getSubmitOperatorId()); content.setSubmitOperatorName(record.getSubmitOperatorName()); + content.setSubmitOperatorIdentity(OperatorIdentity.of(record.getSubmitOperatorIdentity()).value()); content.setCreateTime(record.getCreateTime()); content.setCreateOperatorId(record.getCreateOperatorId()); content.setCreateOperatorName(record.getCreateOperatorName()); + content.setCreateOperatorIdentity(OperatorIdentity.of(record.getCreateOperatorIdentity()).value()); content.setMergeable(record.getMergeable()); content.setRecordId(record.getId()); content.setTimeoutTime(record.getTimeoutTime()); content.setRecordState(record.getRecordState()); content.setFlowState(record.getFlowState()); content.setNotify(record.getNotify()); + // issue #306:已办列表的办理人(历史数据为空,身份统一归一化为默认身份) + content.setHandleOperatorId(record.getHandleOperatorId()); + content.setHandleOperatorName(record.getHandleOperatorName()); + content.setHandleOperatorIdentity(OperatorIdentity.of(record.getHandleOperatorIdentity()).value()); return content; } } diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java index 9e34a9cf..31c030f0 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowRecordConvertor.java @@ -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,17 @@ public static FlowRecord convert(FlowRecordEntity entity) { entity.getDelegateId(), entity.getParallelId(), entity.getParallelBranchNodeId(), - entity.getParallelBranchTotal()); + entity.getParallelBranchTotal(), + // issue #288:历史数据 identity 列为 null,读取时统一归一化为默认身份 + OperatorIdentity.of(entity.getCreateOperatorIdentity()).value(), + OperatorIdentity.of(entity.getSubmitOperatorIdentity()).value(), + OperatorIdentity.of(entity.getCurrentOperatorIdentity()).value(), + OperatorIdentity.of(entity.getForwardOperatorIdentity()).value(), + OperatorIdentity.of(entity.getInterferedOperatorIdentity()).value(), + // issue #306:办理人(历史数据为空) + entity.getHandleOperatorId() == null ? 0L : entity.getHandleOperatorId(), + entity.getHandleOperatorName(), + OperatorIdentity.of(entity.getHandleOperatorIdentity()).value()); } public static FlowRecordEntity convert(FlowRecord record) { @@ -120,6 +131,15 @@ public static FlowRecordEntity convert(FlowRecord record) { entity.setParallelId(record.getParallelId()); entity.setParallelBranchNodeId(record.getParallelBranchNodeId()); entity.setParallelBranchTotal(record.getParallelBranchTotal()); + // 写入前统一校验:长度与 DDL 列宽一致、禁止合并键分隔符与控制字符(issue #288 衍生 / #294) + entity.setCreateOperatorIdentity(OperatorIdentity.of(record.getCreateOperatorIdentity()).validate().value()); + entity.setSubmitOperatorIdentity(OperatorIdentity.of(record.getSubmitOperatorIdentity()).validate().value()); + entity.setCurrentOperatorIdentity(OperatorIdentity.of(record.getCurrentOperatorIdentity()).validate().value()); + entity.setForwardOperatorIdentity(OperatorIdentity.of(record.getForwardOperatorIdentity()).validate().value()); + entity.setInterferedOperatorIdentity(OperatorIdentity.of(record.getInterferedOperatorIdentity()).validate().value()); + entity.setHandleOperatorId(record.getHandleOperatorId()); + entity.setHandleOperatorName(record.getHandleOperatorName()); + entity.setHandleOperatorIdentity(OperatorIdentity.of(record.getHandleOperatorIdentity()).validate().value()); return entity; } diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowTodoRecordConvertor.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowTodoRecordConvertor.java index 7de8f9c9..965d9a0c 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowTodoRecordConvertor.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowTodoRecordConvertor.java @@ -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.of(entity.getCurrentOperatorIdentity()).value(), + OperatorIdentity.of(entity.getSubmitOperatorIdentity()).value(), + OperatorIdentity.of(entity.getCreateOperatorIdentity()).value() ); } @@ -66,6 +71,10 @@ public static FlowTodoRecordEntity convert(FlowTodoRecord record){ entity.setMergeable(record.isMergeable()); entity.setRecordId(record.getRecordId()); entity.setTimeoutTime(record.getTimeoutTime()); + // 写入前统一校验:长度与 DDL 列宽一致、禁止合并键分隔符与控制字符(issue #288 衍生 / #294) + entity.setCurrentOperatorIdentity(OperatorIdentity.of(record.getCurrentOperatorIdentity()).validate().value()); + entity.setSubmitOperatorIdentity(OperatorIdentity.of(record.getSubmitOperatorIdentity()).validate().value()); + entity.setCreateOperatorIdentity(OperatorIdentity.of(record.getCreateOperatorIdentity()).validate().value()); return entity; } } diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/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 9e8c8764..af362361 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowRecordEntity.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowRecordEntity.java @@ -1,5 +1,6 @@ package com.codingapi.flow.infra.entity; +import com.codingapi.flow.operator.OperatorIdentity; import jakarta.persistence.*; import lombok.Data; @@ -100,6 +101,12 @@ public class FlowRecordEntity { */ private String currentOperatorName; + /** + * 当前审批人身份标识(issue #288),空值等价默认身份 + */ + @Column(length = OperatorIdentity.MAX_LENGTH) + private String currentOperatorIdentity; + /** * 提交审批人Id */ @@ -110,6 +117,12 @@ public class FlowRecordEntity { */ private String submitOperatorName; + /** + * 提交审批人身份标识(issue #288),空值等价默认身份 + */ + @Column(length = OperatorIdentity.MAX_LENGTH) + private String submitOperatorIdentity; + /** * 代替的审批人 */ @@ -120,6 +133,12 @@ public class FlowRecordEntity { */ private String forwardOperatorName; + /** + * 代替的审批人身份标识(issue #288),空值等价默认身份 + */ + @Column(length = OperatorIdentity.MAX_LENGTH) + private String forwardOperatorIdentity; + /** * 有那个节点退回的 */ @@ -180,6 +199,12 @@ public class FlowRecordEntity { */ private String createOperatorName; + /** + * 发起者身份标识(issue #288),空值等价默认身份 + */ + @Column(length = OperatorIdentity.MAX_LENGTH) + private String createOperatorIdentity; + /** * 异常信息 */ @@ -208,6 +233,28 @@ public class FlowRecordEntity { */ private String interferedOperatorName; + /** + * 被干预的用户身份标识(issue #288),空值等价默认身份 + */ + @Column(length = OperatorIdentity.MAX_LENGTH) + private String interferedOperatorIdentity; + + /** + * 办理人Id(issue #306),记录办结时的实际办理人,暂存与抄送不写入 + */ + private Long handleOperatorId; + + /** + * 办理人名称(issue #306) + */ + private String handleOperatorName; + + /** + * 办理人身份标识(issue #306),空值等价默认身份 + */ + @Column(length = OperatorIdentity.MAX_LENGTH) + private String handleOperatorIdentity; + /** * 委托记录id */ 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..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; @@ -68,6 +69,12 @@ public class FlowTodoRecordEntity { */ private String currentOperatorName; + /** + * 当前审批人身份标识(issue #288),空值等价默认身份 + */ + @Column(length = OperatorIdentity.MAX_LENGTH) + private String currentOperatorIdentity; + /** * 提交审批人Id */ @@ -78,6 +85,12 @@ public class FlowTodoRecordEntity { */ private String submitOperatorName; + /** + * 提交审批人身份标识(issue #288),空值等价默认身份 + */ + @Column(length = OperatorIdentity.MAX_LENGTH) + private String submitOperatorIdentity; + /** * 创建时间 */ @@ -92,6 +105,12 @@ public class FlowTodoRecordEntity { */ private String createOperatorName; + /** + * 发起者身份标识(issue #288),空值等价默认身份 + */ + @Column(length = OperatorIdentity.MAX_LENGTH) + private String createOperatorIdentity; + /** * 合并记录id,当存在合并记录数据时待办记录数量不会增加,内容会更新至最新的待办数据信息。 * {@link FlowRecord#getTodoKey()} 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-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..3a72890c 100644 --- a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowOperatorAssignmentRepositoryImpl.java +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowOperatorAssignmentRepositoryImpl.java @@ -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.of(operator.identity()).isDefault()); + 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; + } } diff --git a/flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertorTest.java b/flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertorTest.java new file mode 100644 index 00000000..013b6d93 --- /dev/null +++ b/flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowRecordContentConvertorTest.java @@ -0,0 +1,105 @@ +package com.codingapi.flow.infra.convert; + +import com.codingapi.flow.infra.entity.FlowRecordEntity; +import com.codingapi.flow.pojo.response.FlowRecordContent; +import com.codingapi.flow.record.FlowRecord; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * 已办列表响应映射测试(issue #306)。 + * + *

    查询层({@code FlowRecordQueryServiceImpl})把 JPA 实体直接交给 + * {@link FlowRecordContentConvertor#convert(FlowRecordEntity)} 组装列表数据, + * 不走领域对象链路。因此「办理人」三字段必须在该转换器里显式映射, + * 否则已办列表拿到的永远是 null,前端只能回退到待办归属人。 + */ +class FlowRecordContentConvertorTest { + + /** + * 构造字段完整的流程记录实体,避免转换时的拆箱 NPE 干扰断言。 + */ + private FlowRecordEntity newRecordEntity() { + FlowRecordEntity entity = new FlowRecordEntity(); + entity.setId(2L); + entity.setWorkRuntimeId(1L); + entity.setWorkTitle("身份标识验证流程"); + entity.setWorkCode("identity-demo"); + entity.setNodeId("approval"); + entity.setNodeType("APPROVAL"); + entity.setNodeName("审批节点"); + entity.setTitle("你有一条待办"); + entity.setFromId(0L); + entity.setParentId(0L); + entity.setReadTime(0L); + entity.setCurrentOperatorId(2L); + entity.setCurrentOperatorName("张三"); + entity.setSubmitOperatorId(1L); + entity.setForwardOperatorId(0L); + entity.setNodeOrder(0); + entity.setHidden(false); + entity.setRevoked(false); + entity.setNotify(false); + entity.setRecordState(FlowRecord.SATE_RECORD_DONE); + entity.setFlowState(FlowRecord.SATE_FLOW_FINISH); + entity.setUpdateTime(0L); + entity.setCreateTime(0L); + entity.setFinishTime(0L); + entity.setReadable(false); + entity.setCreateOperatorId(1L); + entity.setTimeoutTime(0L); + entity.setMergeable(false); + entity.setInterferedOperatorId(0L); + entity.setDelegateId(0L); + entity.setParallelBranchTotal(0); + return entity; + } + + /** + * 测试目标:已办记录的办理人(人 + 身份)必须出现在列表响应里。 + * 前置条件:实体带有本次办理人信息(张三以 department1 身份办理)。 + * 执行步骤:实体 → 列表响应对象。 + * 期望断言:办理人 id / 名称 / 身份与实体一致,且不与待办归属人混淆。 + */ + @Test + void should_expose_handle_operator_for_done_record() { + FlowRecordEntity entity = newRecordEntity(); + entity.setCurrentOperatorIdentity(""); + entity.setCreateOperatorIdentity(""); + entity.setHandleOperatorId(2L); + entity.setHandleOperatorName("张三"); + entity.setHandleOperatorIdentity("department1"); + + FlowRecordContent content = FlowRecordContentConvertor.convert(entity); + + assertAll( + () -> assertEquals(2L, content.getHandleOperatorId()), + () -> assertEquals("张三", content.getHandleOperatorName()), + () -> assertEquals("department1", content.getHandleOperatorIdentity()), + // 待办归属身份保持原样,办理身份不覆盖它 + () -> assertEquals("", content.getCurrentOperatorIdentity()) + ); + } + + /** + * 测试目标:升级前的存量已办记录(办理人列为空)不报错、不伪造数据。 + * 前置条件:实体 handle 三字段均为 null。 + * 执行步骤:实体 → 列表响应对象。 + * 期望断言:id / 名称保持 null,身份归一化为空串,前端据此回退待办归属人。 + */ + @Test + void should_keep_handle_operator_empty_for_legacy_done_record() { + FlowRecordEntity entity = newRecordEntity(); + + FlowRecordContent content = FlowRecordContentConvertor.convert(entity); + + assertAll( + () -> assertNull(content.getHandleOperatorId()), + () -> assertNull(content.getHandleOperatorName()), + () -> assertEquals("", content.getHandleOperatorIdentity()) + ); + } +} 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()) + ); + } +} diff --git a/flow-engine-starter-query/pom.xml b/flow-engine-starter-query/pom.xml index 10b52e53..be24a19d 100644 --- a/flow-engine-starter-query/pom.xml +++ b/flow-engine-starter-query/pom.xml @@ -27,6 +27,12 @@ com.codingapi.flow flow-engine-starter-infra + + + + com.codingapi.flow + flow-engine-starter-api + diff --git a/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java b/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java index 854db4e5..e14a518d 100644 --- a/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java +++ b/flow-engine-starter-query/src/main/java/com/codingapi/flow/query/controller/FlowRecordQueryController.java @@ -4,6 +4,8 @@ import com.codingapi.flow.mock.MockInstance; import com.codingapi.flow.mock.MockInstanceFactory; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.api.OperatorIdentityHeader; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.pojo.response.FlowRecordContent; import com.codingapi.flow.query.FlowRecordQueryService; import com.codingapi.flow.query.pojo.FlowInstanceQueryRequest; @@ -53,6 +55,82 @@ private long loadCurrentOperatorId(){ } } + /** + * 当前操作人身份标识(issue #288 / #297 / #301)。 + * + *

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

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

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

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

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

    参数优先取请求头({@code X-Identity-Scope} / {@code X-Lock-Identity}), + * 避免被 {@code SearchRequest} 当成实体字段解析(issue #301)。 + */ + private boolean isIdentityLocked() { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + String scope = OperatorIdentityHeader.resolve( + request.getHeader(OperatorIdentityHeader.IDENTITY_SCOPE), + request.getParameter(IDENTITY_SCOPE_PARAM), + request.getParameterMap().containsKey(IDENTITY_SCOPE_PARAM)); + if (!StringUtils.hasText(scope)) { + String locked = OperatorIdentityHeader.resolve( + request.getHeader(OperatorIdentityHeader.LOCK_IDENTITY), + request.getParameter(LOCK_IDENTITY_PARAM), + request.getParameterMap().containsKey(LOCK_IDENTITY_PARAM)); + return "true".equalsIgnoreCase(locked); + } + String normalized = scope.trim().toUpperCase(); + if (IDENTITY_SCOPE_ALL.equals(normalized)) { + return false; + } + if (IDENTITY_SCOPE_LOCKED.equals(normalized)) { + return true; + } + throw FlowValidationException.invalidParameter(IDENTITY_SCOPE_PARAM, scope, + IDENTITY_SCOPE_ALL + " / " + IDENTITY_SCOPE_LOCKED); + } /** * 全部流程记录接口 @@ -67,36 +145,57 @@ public MultiResponse list(SearchRequest request) { /** * 我的待办记录 + * + *

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

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

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

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

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

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

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

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

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

    starter 是业务接入的默认入口,默认不限制身份;框架自身的默认值仍是严格模式, + * 两者通过 {@link OperatorIdentityConfigurer} 在启动时衔接。 + */ +class FlowPropertiesTest { + + @AfterEach + void tearDown() { + OperatorIdentityContext.getInstance().use(OperatorIdentityMatchMode.STRICT); + } + + @Test + void should_default_to_user_only_mode() { + FlowProperties properties = new FlowProperties(); + assertEquals(OperatorIdentityMatchMode.USER_ONLY, properties.getIdentity().getMatchMode()); + } + + @Test + void should_apply_configured_mode_to_framework() { + FlowProperties properties = new FlowProperties(); + properties.getIdentity().setMatchMode(OperatorIdentityMatchMode.STRICT); + + new OperatorIdentityConfigurer(properties).afterPropertiesSet(); + + assertEquals(OperatorIdentityMatchMode.STRICT, OperatorIdentityContext.getInstance().matchMode()); + } +} diff --git a/flow-frontend b/flow-frontend index 068dc13b..7fd4b0ad 160000 --- a/flow-frontend +++ b/flow-frontend @@ -1 +1 @@ -Subproject commit 068dc13b853ea31de56558995e8f494d8b311f62 +Subproject commit 7fd4b0ad190636baf9ffb6ce1b3e6fee10f317e6 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