From d31e03211401a0c719e7750997f2ab56ac87cfa8 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Mon, 16 Nov 2026 22:15:18 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=B7=B2=E5=AE=8C=E6=88=90=E6=B5=81?= =?UTF-8?q?=E7=A8=8B=E6=94=AF=E6=8C=81=E4=BA=8C=E6=AC=A1=E5=8F=91=E8=B5=B7?= =?UTF-8?q?=20(framework=20+=20infra=20+=20api)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 FlowReissueService:仅流程管理员可对已正常完成(FINISH)的流程执行二次发起 - 复制源流程表单数据通过标准创建流程重新发起,新流程停在开始节点成为原发起人的待办, 不自动提交;源流程记录、待办与历史记录不做任何改写 - 新增关系记录 FlowReissueRecord / t_flow_record_reissue 及仓储(JPA + Mock)与达梦序列 - 新增 FlowRecordReissueEvent,供业务方同步已落库数据状态 - 详情接口新增 reissue 标识,新增 POST /api/cmd/record/reissue - 补充单元测试与集成文档 Closes #272 --- docs/Integration/auto-configuration.md | 4 +- docs/Integration/repository-integration.md | 5 +- .../src/main/resources/sql/dm-sequences.sql | 13 + .../flow/context/RepositoryHolderContext.java | 10 +- .../flow/domain/FlowReissueRecord.java | 95 +++++ .../flow/event/FlowRecordReissueEvent.java | 34 ++ .../flow/exception/FlowStateException.java | 10 + .../flow/mock/MockRepositoryHolder.java | 2 + .../FlowReissueRepositoryMockImpl.java | 44 ++ .../flow/pojo/request/FlowReissueRequest.java | 53 +++ .../flow/pojo/response/FlowContent.java | 7 + .../repository/FlowReissueRepository.java | 42 ++ .../codingapi/flow/service/FlowService.java | 16 + .../flow/service/impl/FlowDetailService.java | 2 + .../flow/service/impl/FlowReissueService.java | 192 +++++++++ .../flow/session/IRepositoryHolder.java | 6 + .../factory/CopyOnReadFlowServiceFactory.java | 3 +- .../flow/factory/MyFlowServiceFactory.java | 5 +- .../flow/service/FlowReissueServiceTest.java | 382 ++++++++++++++++++ .../api/controller/FlowRecordController.java | 13 + .../flow/infra/AutoConfiguration.java | 5 + .../convert/FlowReissueRecordConvertor.java | 72 ++++ .../infra/entity/FlowReissueRecordEntity.java | 98 +++++ .../FlowReissueRecordEntityRepository.java | 36 ++ .../impl/FlowReissueRepositoryImpl.java | 55 +++ .../FlowReissueRecordConvertorTest.java | 56 +++ .../com/codingapi/flow/AutoConfiguration.java | 2 + .../RepositoryHolderContextRegister.java | 4 +- 28 files changed, 1257 insertions(+), 9 deletions(-) create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/domain/FlowReissueRecord.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReissueEvent.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/mock/repository/FlowReissueRepositoryMockImpl.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/pojo/request/FlowReissueRequest.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/repository/FlowReissueRepository.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowReissueService.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowReissueServiceTest.java create mode 100644 flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/convert/FlowReissueRecordConvertor.java create mode 100644 flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/entity/FlowReissueRecordEntity.java create mode 100644 flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/jpa/FlowReissueRecordEntityRepository.java create mode 100644 flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowReissueRepositoryImpl.java create mode 100644 flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowReissueRecordConvertorTest.java diff --git a/docs/Integration/auto-configuration.md b/docs/Integration/auto-configuration.md index 99b4fac6..ed34ff7f 100644 --- a/docs/Integration/auto-configuration.md +++ b/docs/Integration/auto-configuration.md @@ -18,7 +18,7 @@ | `NodeViewJavaScriptCacheContextRegister` | **`NodeViewJavaScriptRepository`** | 构造器内执行 `NodeViewJavaScriptCacheContext.getInstance().setNodeViewJavaScriptRepository(repo)`(15 分钟缓存上下文) | | `GatewayContextRegister` | **`FlowOperatorGateway`** | 把操作人网关灌入 `GatewayContext` 单例(`InitializingBean`) | | `FlowScriptContextRegister` | `ApplicationContext` + **`FlowOperatorGateway`** + `FlowRecordRepository` | 给 `FlowScriptContext` 单例设置 `IBeanFactory`(转发 Spring 容器,脚本 `$bind` 依赖) | -| `RepositoryHolderContextRegister` | `WorkflowService` + `FlowRecordService` + 5 个仓储 + `GatewayContextRegister` | 把 7 个依赖灌入 `RepositoryHolderContext` 单例(`InitializingBean`) | +| `RepositoryHolderContextRegister` | `WorkflowService` + `FlowRecordService` + 6 个仓储 + `GatewayContextRegister` | 把 8 个依赖灌入 `RepositoryHolderContext` 单例(`InitializingBean`) | | `FlowRecordService` | `FlowTodoRecordRepository` + `FlowTodoMergeRepository` + `FlowRecordRepository` | 记录服务 Bean | | `WorkflowService` | `WorkflowVersionRepository` + `WorkflowRepository` + `WorkflowRuntimeRepository` | 流程设计服务 Bean | | `FlowService` | `RepositoryHolderContextRegister`(仅保证顺序) | `new FlowService(RepositoryHolderContext.getInstance())`,业务入口 | @@ -42,7 +42,7 @@ public void afterPropertiesSet() { workflowService, flowRecordService, parallelBranchRepository, delayTaskRepository, urgeIntervalRepository, flowOperatorAssignmentRepository, - subProcessRepository); + subProcessRepository, flowReissueRepository); } // FlowScriptContextRegister diff --git a/docs/Integration/repository-integration.md b/docs/Integration/repository-integration.md index 88da4a50..42dec50f 100644 --- a/docs/Integration/repository-integration.md +++ b/docs/Integration/repository-integration.md @@ -194,6 +194,7 @@ public interface UrgeIntervalRepository { | `UrgeIntervalEntity` | `t_flow_urge_interval` | | `FlowOperatorAssignmentEntity` | `t_flow_operator_assignment` | | `SubProcessRecordEntity` | `t_flow_sub_process_record` | +| `FlowReissueRecordEntity` | `t_flow_record_reissue`(已完成流程二次发起关系) | Spring Data 仓储接口位于 `jpa/` 包,全部继承外部 `FastRepository`(来自 `springboot-starter-data-fast`)。 @@ -233,7 +234,7 @@ public class GroovyScriptRepositoryImpl implements GroovyScriptRepository, Initi ## 6. 替换存储 - **引入 `flow-engine-starter-infra`**:开箱即用(推荐)。 -- **不引入 infra**:自行实现 11 个仓储接口 + `NodeViewJavaScriptRepository` 为 Spring Bean 即可。starter 的 `RepositoryHolderContextRegister` 会自动注入。framework 测试包(`src/test/java/com/codingapi/flow/repository/`)提供了一套内存实现可作参考。 +- **不引入 infra**:自行实现 12 个仓储接口 + `NodeViewJavaScriptRepository` 为 Spring Bean 即可。starter 的 `RepositoryHolderContextRegister` 会自动注入。framework 测试包(`src/test/java/com/codingapi/flow/repository/`)提供了一套内存实现可作参考。 ## 7. 离线/最小装配(脱离 Spring) @@ -245,7 +246,7 @@ RepositoryHolderContext.getInstance().register( workflowService, flowRecordService, parallelBranchRepository, delayTaskRepository, urgeIntervalRepository, flowOperatorAssignmentRepository, - subProcessRepository); + subProcessRepository, flowReissueRepository); // 2. 注册操作人网关 GatewayContext.getInstance().setFlowOperatorGateway(userGateway); ``` \ No newline at end of file diff --git a/flow-engine-example/src/main/resources/sql/dm-sequences.sql b/flow-engine-example/src/main/resources/sql/dm-sequences.sql index 0c4b20bd..f5ca5220 100644 --- a/flow-engine-example/src/main/resources/sql/dm-sequences.sql +++ b/flow-engine-example/src/main/resources/sql/dm-sequences.sql @@ -6,6 +6,7 @@ -- t_flow_todo_record -> t_flow_todo_record_seq -- t_flow_todo_marge -> t_flow_todo_marge_seq -- t_flow_sub_process_record-> t_flow_sub_process_record_seq +-- t_flow_record_reissue -> t_flow_record_reissue_seq -- -- 序列名 / 步长 与实体 @SequenceGenerator(sequenceName=..., allocationSize=50) 严格一致, -- 请勿修改,否则 hibernate 会在 insert 时报“无法解析的成员访问表达式[...NEXTVAL]”或出现主键重复。 @@ -70,5 +71,17 @@ BEGIN END; EXECUTE IMMEDIATE 'CREATE SEQUENCE t_flow_sub_process_record_seq INCREMENT BY 50 START WITH ' || v_start; END IF; + + -- ---------- 5. t_flow_record_reissue_seq ---------- + SELECT COUNT(*) INTO v_cnt FROM all_sequences + WHERE sequence_name = 'T_FLOW_RECORD_REISSUE_SEQ' AND sequence_owner = USER; + IF v_cnt = 0 THEN + BEGIN + SELECT NVL(MAX(id), 0) + 1 INTO v_start FROM t_flow_record_reissue; + EXCEPTION WHEN OTHERS THEN + v_start := 1; + END; + EXECUTE IMMEDIATE 'CREATE SEQUENCE t_flow_record_reissue_seq INCREMENT BY 50 START WITH ' || v_start; + END IF; END; / \ No newline at end of file diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/context/RepositoryHolderContext.java b/flow-engine-framework/src/main/java/com/codingapi/flow/context/RepositoryHolderContext.java index 47577af6..079e7b38 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/context/RepositoryHolderContext.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/context/RepositoryHolderContext.java @@ -8,6 +8,7 @@ import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.repository.DelayTaskRepository; import com.codingapi.flow.repository.FlowOperatorAssignmentRepository; +import com.codingapi.flow.repository.FlowReissueRepository; import com.codingapi.flow.repository.ParallelBranchRepository; import com.codingapi.flow.repository.SubProcessRepository; import com.codingapi.flow.repository.UrgeIntervalRepository; @@ -47,6 +48,8 @@ private RepositoryHolderContext() { private FlowOperatorAssignmentRepository flowOperatorAssignmentRepository; @Getter private SubProcessRepository subProcessRepository; + @Getter + private FlowReissueRepository flowReissueRepository; /** * 是否已经注册成功 @@ -58,7 +61,8 @@ public boolean isRegistered() { && flowRecordService != null && urgeIntervalRepository != null && flowOperatorAssignmentRepository != null - && subProcessRepository != null; + && subProcessRepository != null + && flowReissueRepository != null; } @@ -74,7 +78,8 @@ public void register(WorkflowService workflowService, DelayTaskRepository delayTaskRepository, UrgeIntervalRepository urgeIntervalRepository, FlowOperatorAssignmentRepository flowOperatorAssignmentRepository, - SubProcessRepository subProcessRepository) { + SubProcessRepository subProcessRepository, + FlowReissueRepository flowReissueRepository) { this.workflowService = workflowService; this.flowRecordService = flowRecordService; this.parallelBranchRepository = parallelBranchRepository; @@ -82,6 +87,7 @@ public void register(WorkflowService workflowService, this.urgeIntervalRepository = urgeIntervalRepository; this.flowOperatorAssignmentRepository = flowOperatorAssignmentRepository; this.subProcessRepository = subProcessRepository; + this.flowReissueRepository = flowReissueRepository; } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/domain/FlowReissueRecord.java b/flow-engine-framework/src/main/java/com/codingapi/flow/domain/FlowReissueRecord.java new file mode 100644 index 00000000..e725877d --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/domain/FlowReissueRecord.java @@ -0,0 +1,95 @@ +package com.codingapi.flow.domain; + +import lombok.Getter; +import lombok.Setter; + +/** + * 已完成流程的二次发起关系记录。 + * + *

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+ */ +@Data +@Entity +@Table(name = "t_flow_record_reissue") +public class FlowReissueRecordEntity { + + /** + * 主键,由序列生成(替代数据库自增,配合 hibernate 批插降低批量往返) + */ + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "flow_reissue_record_seq") + @SequenceGenerator(name = "flow_reissue_record_seq", sequenceName = "t_flow_record_reissue_seq", allocationSize = 50) + private Long id; + + /** + * 被二次发起的源流程记录id + */ + @Column(nullable = false) + private Long sourceRecordId; + + /** + * 被二次发起的源流程id + */ + @Column(nullable = false) + private String sourceProcessId; + + /** + * 二次发起产生的新流程记录id + */ + @Column(nullable = false) + private Long newRecordId; + + /** + * 二次发起产生的新流程id + */ + @Column(nullable = false) + private String newProcessId; + + /** + * 流程编码 + */ + @Column(nullable = false) + private String workCode; + + /** + * 源流程所处的运行时版本id + */ + @Column(nullable = false) + private Long workRuntimeId; + + /** + * 执行二次发起的操作人(流程管理员) + */ + @Column(nullable = false) + private Long operatorId; + + /** + * 执行二次发起的操作人名称 + */ + @Column + private String operatorName; + + /** + * 操作时间(毫秒时间戳) + */ + @Column(nullable = false) + private Long createTime; + + /** + * 二次发起说明 + */ + @Column + private String advice; + + /** + * 乐观锁版本号(由 JPA {@link Version} 自动维护) + */ + @Version + private Long version; +} diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/jpa/FlowReissueRecordEntityRepository.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/jpa/FlowReissueRecordEntityRepository.java new file mode 100644 index 00000000..f0a8492d --- /dev/null +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/jpa/FlowReissueRecordEntityRepository.java @@ -0,0 +1,36 @@ +package com.codingapi.flow.infra.jpa; + +import com.codingapi.flow.infra.entity.FlowReissueRecordEntity; +import com.codingapi.springboot.fast.jpa.repository.FastRepository; + +import java.util.List; + +/** + * 已完成流程二次发起关系实体的 JPA 仓储接口。 + */ +public interface FlowReissueRecordEntityRepository extends FastRepository { + + /** + * 按源流程记录id查询,按记录id升序。 + * + * @param sourceRecordId 源流程记录id + * @return 二次发起关系实体列表 + */ + List findBySourceRecordIdOrderById(long sourceRecordId); + + /** + * 按源流程id查询,按记录id升序。 + * + * @param sourceProcessId 源流程id + * @return 二次发起关系实体列表 + */ + List findBySourceProcessIdOrderById(String sourceProcessId); + + /** + * 按新流程id查询,按记录id升序。 + * + * @param newProcessId 新流程id + * @return 二次发起关系实体列表 + */ + List findByNewProcessIdOrderById(String newProcessId); +} diff --git a/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowReissueRepositoryImpl.java b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowReissueRepositoryImpl.java new file mode 100644 index 00000000..72bdb9fa --- /dev/null +++ b/flow-engine-starter-infra/src/main/java/com/codingapi/flow/infra/repository/impl/FlowReissueRepositoryImpl.java @@ -0,0 +1,55 @@ +package com.codingapi.flow.infra.repository.impl; + +import com.codingapi.flow.domain.FlowReissueRecord; +import com.codingapi.flow.infra.convert.FlowReissueRecordConvertor; +import com.codingapi.flow.infra.entity.FlowReissueRecordEntity; +import com.codingapi.flow.infra.jpa.FlowReissueRecordEntityRepository; +import com.codingapi.flow.repository.FlowReissueRepository; +import lombok.AllArgsConstructor; + +import java.util.List; + +/** + * 已完成流程二次发起关系仓库的 JPA 实现。 + */ +@AllArgsConstructor +public class FlowReissueRepositoryImpl implements FlowReissueRepository { + + private final FlowReissueRecordEntityRepository repository; + + /** + * 保存二次发起关系: + * 已持久化的记录(id 大于 0)更新到已有实体,否则新建实体; + * 保存后回写生成的主键。 + */ + @Override + public void save(FlowReissueRecord record) { + FlowReissueRecordEntity entity = record.getId() > 0 + ? repository.findById(record.getId()).orElseGet(FlowReissueRecordEntity::new) + : new FlowReissueRecordEntity(); + FlowReissueRecordConvertor.convert(record, entity); + repository.save(entity); + record.setId(entity.getId()); + } + + @Override + public List findBySourceRecordId(long sourceRecordId) { + return repository.findBySourceRecordIdOrderById(sourceRecordId).stream() + .map(FlowReissueRecordConvertor::convert) + .toList(); + } + + @Override + public List findBySourceProcessId(String sourceProcessId) { + return repository.findBySourceProcessIdOrderById(sourceProcessId).stream() + .map(FlowReissueRecordConvertor::convert) + .toList(); + } + + @Override + public List findByNewProcessId(String newProcessId) { + return repository.findByNewProcessIdOrderById(newProcessId).stream() + .map(FlowReissueRecordConvertor::convert) + .toList(); + } +} diff --git a/flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowReissueRecordConvertorTest.java b/flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowReissueRecordConvertorTest.java new file mode 100644 index 00000000..d7fd943a --- /dev/null +++ b/flow-engine-starter-infra/src/test/java/com/codingapi/flow/infra/convert/FlowReissueRecordConvertorTest.java @@ -0,0 +1,56 @@ +package com.codingapi.flow.infra.convert; + +import com.codingapi.flow.domain.FlowReissueRecord; +import com.codingapi.flow.infra.entity.FlowReissueRecordEntity; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +class FlowReissueRecordConvertorTest { + + /** + * 测试目标:验证二次发起关系记录可在领域对象与持久化对象之间完整往返。 + * 前置条件:持久化对象携带源流程、新流程、操作人等信息。 + * 执行步骤:转换为领域对象,再回写到一个新建的持久化对象。 + * 期望断言:全部业务字段不丢失;回写已有实体时保留原实体与版本号。 + */ + @Test + void shouldRoundTripReissueRecord() { + FlowReissueRecordEntity entity = new FlowReissueRecordEntity(); + entity.setId(10L); + entity.setSourceRecordId(21L); + entity.setSourceProcessId("source-process"); + entity.setNewRecordId(31L); + entity.setNewProcessId("new-process"); + entity.setWorkCode("reissue-workflow"); + entity.setWorkRuntimeId(41L); + entity.setOperatorId(51L); + entity.setOperatorName("流程管理员"); + entity.setCreateTime(1000L); + entity.setAdvice("业务数据有误,重新发起"); + entity.setVersion(7L); + + FlowReissueRecord record = FlowReissueRecordConvertor.convert(entity); + + assertAll("实体转换为领域对象", + () -> assertEquals(10L, record.getId()), + () -> assertEquals(21L, record.getSourceRecordId()), + () -> assertEquals("source-process", record.getSourceProcessId()), + () -> assertEquals(31L, record.getNewRecordId()), + () -> assertEquals("new-process", record.getNewProcessId()), + () -> assertEquals("reissue-workflow", record.getWorkCode()), + () -> assertEquals(41L, record.getWorkRuntimeId()), + () -> assertEquals(51L, record.getOperatorId()), + () -> assertEquals("流程管理员", record.getOperatorName()), + () -> assertEquals(1000L, record.getCreateTime()), + () -> assertEquals("业务数据有误,重新发起", record.getAdvice())); + + FlowReissueRecordEntity converted = FlowReissueRecordConvertor.convert(record, entity); + + assertSame(entity, converted, "回写时应复用已有实体"); + assertEquals(7L, converted.getVersion(), "回写不应覆盖乐观锁版本号"); + assertEquals(record.getNewProcessId(), converted.getNewProcessId()); + } +} diff --git a/flow-engine-starter/src/main/java/com/codingapi/flow/AutoConfiguration.java b/flow-engine-starter/src/main/java/com/codingapi/flow/AutoConfiguration.java index 7dbaab48..3f38be72 100644 --- a/flow-engine-starter/src/main/java/com/codingapi/flow/AutoConfiguration.java +++ b/flow-engine-starter/src/main/java/com/codingapi/flow/AutoConfiguration.java @@ -53,6 +53,7 @@ public RepositoryHolderContextRegister repositoryHolderContextRegister( UrgeIntervalRepository urgeIntervalRepository, FlowOperatorAssignmentRepository flowOperatorAssignmentRepository, SubProcessRepository subProcessRepository, + FlowReissueRepository flowReissueRepository, GatewayContextRegister gatewayContextRegister ) { return new RepositoryHolderContextRegister( @@ -63,6 +64,7 @@ public RepositoryHolderContextRegister repositoryHolderContextRegister( urgeIntervalRepository, flowOperatorAssignmentRepository, subProcessRepository, + flowReissueRepository, gatewayContextRegister ); } diff --git a/flow-engine-starter/src/main/java/com/codingapi/flow/register/RepositoryHolderContextRegister.java b/flow-engine-starter/src/main/java/com/codingapi/flow/register/RepositoryHolderContextRegister.java index bb23a957..330cb2ab 100644 --- a/flow-engine-starter/src/main/java/com/codingapi/flow/register/RepositoryHolderContextRegister.java +++ b/flow-engine-starter/src/main/java/com/codingapi/flow/register/RepositoryHolderContextRegister.java @@ -18,6 +18,7 @@ public class RepositoryHolderContextRegister implements InitializingBean { private final UrgeIntervalRepository urgeIntervalRepository; private final FlowOperatorAssignmentRepository flowOperatorAssignmentRepository; private final SubProcessRepository subProcessRepository; + private final FlowReissueRepository flowReissueRepository; private final GatewayContextRegister gatewayContextRegister; @Override @@ -30,7 +31,8 @@ public void afterPropertiesSet() throws Exception { delayTaskRepository, urgeIntervalRepository, flowOperatorAssignmentRepository, - subProcessRepository + subProcessRepository, + flowReissueRepository ); } }