diff --git a/flowable-service/src/main/java/com/eip4/flowservice/api/ApprovalContextDto.java b/flowable-service/src/main/java/com/eip4/flowservice/api/ApprovalContextDto.java new file mode 100644 index 0000000..43009ad --- /dev/null +++ b/flowable-service/src/main/java/com/eip4/flowservice/api/ApprovalContextDto.java @@ -0,0 +1,29 @@ +package com.eip4.flowservice.api; + +/** + * 任务审批上下文(供 gateway 解析 WfTemplate 驱动审批界面)。 + * + *

聚合一次性返回办理审批所需的引擎侧事实:formKey(= view_wftemplate_id,已经 {@code FormKeyResolver} + * 历史回补)、业务主键/表、实例状态。gateway 据 formKey 查 view_wftemplate 得按钮/脚本/业务表单。 + */ +public class ApprovalContextDto { + /** 是否查到任务(运行中或历史)。 */ + public boolean found; + /** 任务 id。 */ + public String taskId; + /** 任务名(节点名)。 */ + public String taskName; + /** formKey = view_wftemplate_id(已历史回补;解析不到为 null → gateway 降级默认按钮)。 */ + public String formKey; + /** 开始节点 formKey(BPMN startEvent activiti:formKey)。任务节点是裸模板(无pageid)时 gateway 回退到它(对齐老 getStartFormKey)。 */ + public String startFormKey; + public String processInstanceId; + public String processDefinitionId; + public String taskDefinitionKey; + /** 流程业务主键(= 业务记录 PK;从实例反查)。 */ + public String businessKey; + /** 流程实例是否已结束。 */ + public boolean ended; + /** 任务/实例是否挂起(挂起不可办理)。 */ + public boolean suspended; +} diff --git a/flowable-service/src/main/java/com/eip4/flowservice/api/FlowController.java b/flowable-service/src/main/java/com/eip4/flowservice/api/FlowController.java index 538d174..6b9d1b5 100644 --- a/flowable-service/src/main/java/com/eip4/flowservice/api/FlowController.java +++ b/flowable-service/src/main/java/com/eip4/flowservice/api/FlowController.java @@ -43,15 +43,30 @@ public class FlowController { private final HistoryService historyService; private final RepositoryService repositoryService; private final JdbcTemplate bizJdbc; + private final com.eip4.flowservice.wf.FormKeyResolver formKeyResolver; + private final com.eip4.flowservice.wf.StartFormKeyResolver startFormKeyResolver; + @org.springframework.beans.factory.annotation.Autowired public FlowController(TaskService taskService, RuntimeService runtimeService, HistoryService historyService, RepositoryService repositoryService, - JdbcTemplate bizJdbc) { + JdbcTemplate bizJdbc, com.eip4.flowservice.wf.FormKeyResolver formKeyResolver, + com.eip4.flowservice.wf.StartFormKeyResolver startFormKeyResolver) { this.taskService = taskService; this.runtimeService = runtimeService; this.historyService = historyService; this.repositoryService = repositoryService; this.bizJdbc = bizJdbc; + this.formKeyResolver = formKeyResolver; + this.startFormKeyResolver = startFormKeyResolver; + } + + /** 兼容老单测的五参构造(无解析器:就地构造)。生产由 Spring 走七参构造。 */ + public FlowController(TaskService taskService, RuntimeService runtimeService, + HistoryService historyService, RepositoryService repositoryService, + JdbcTemplate bizJdbc) { + this(taskService, runtimeService, historyService, repositoryService, bizJdbc, + new com.eip4.flowservice.wf.FormKeyResolver(historyService), + new com.eip4.flowservice.wf.StartFormKeyResolver(repositoryService)); } @PostMapping("/deploy") @@ -227,8 +242,12 @@ public class FlowController { } @PostMapping("/tasks/{taskId}/complete") - @Operation(summary = "办理任务", description = "complete 任务,可带提交变量。挂起实例的任务会被引擎拒绝(语义回归)") + @Operation(summary = "办理任务", description = "complete 任务,可带提交变量与审批意见(comment 经 addComment 记入流程评论供轨迹展示)。挂起实例的任务会被引擎拒绝(语义回归)") public ResponseEntity complete(@PathVariable String taskId, @RequestBody(required = false) Requests.CompleteRequest req) { + // 审批意见落流程评论(对齐老 passProcess 的 addComment;complete 后任务消失,故先记) + if (req != null && req.comment != null && !req.comment.isBlank()) { + addTaskComment(taskId, req.comment); + } if (req != null && req.variables != null) { taskService.complete(taskId, req.variables); } else { @@ -237,6 +256,18 @@ public class FlowController { return ResponseEntity.noContent().build(); } + /** 记审批意见为流程评论(轨迹经 getProcessInstanceComments 读)。任务不存在则静默跳过。 */ + private void addTaskComment(String taskId, String comment) { + try { + var t = taskService.createTaskQuery().taskId(taskId).singleResult(); + String pid = t != null ? t.getProcessInstanceId() : null; + taskService.addComment(taskId, pid, comment); + } catch (RuntimeException e) { + org.slf4j.LoggerFactory.getLogger(FlowController.class) + .warn("[审批意见] addComment 失败 taskId={}: {}", taskId, e.toString()); + } + } + @GetMapping("/process/{processInstanceId}") @Operation(summary = "查实例", description = "查流程实例:运行中返回 ended=false;已结束返回历史实例 ended=true;不存在 404。供 gateway 办理后判定流程是否结束以回写业务状态") public ResponseEntity processInstance(@PathVariable String processInstanceId) { @@ -285,6 +316,142 @@ public class FlowController { return ResponseEntity.ok(t != null ? TaskDto.of(t) : null); } + @GetMapping("/tasks/{taskId}/approval-context") + @Operation(summary = "任务审批上下文", + description = "聚合返回 WfTemplate 驱动审批界面所需事实:formKey(=view_wftemplate_id,经 FormKeyResolver 历史回补)、" + + "businessKey、processInstanceId、taskDefinitionKey、实例是否结束/挂起。任务不存在返回 found=false(前端降级)。" + + "运行中任务优先,查不到回退历史任务(供已办查看)。") + public ResponseEntity approvalContext(@PathVariable String taskId) { + ApprovalContextDto dto = new ApprovalContextDto(); + dto.taskId = taskId; + var t = taskService.createTaskQuery().taskId(taskId).singleResult(); + if (t != null) { + dto.found = true; + dto.taskName = t.getName(); + dto.processInstanceId = t.getProcessInstanceId(); + dto.processDefinitionId = t.getProcessDefinitionId(); + dto.taskDefinitionKey = t.getTaskDefinitionKey(); + dto.suspended = t.isSuspended(); + dto.formKey = formKeyResolver.resolve(t.getFormKey(), t.getProcessDefinitionId(), t.getTaskDefinitionKey()); + dto.startFormKey = startFormKeyResolver.resolve(t.getProcessDefinitionId()); + ProcessInstance pi = runtimeService.createProcessInstanceQuery() + .processInstanceId(t.getProcessInstanceId()).singleResult(); + if (pi != null) { + dto.businessKey = pi.getBusinessKey(); + dto.ended = false; + } + return ResponseEntity.ok(dto); + } + // 运行库无 → 历史任务(已办查看仍要解析 WfTemplate 显业务表单/轨迹) + HistoricTaskInstance ht = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult(); + if (ht == null) { + dto.found = false; + return ResponseEntity.ok(dto); + } + dto.found = true; + dto.taskName = ht.getName(); + dto.processInstanceId = ht.getProcessInstanceId(); + dto.processDefinitionId = ht.getProcessDefinitionId(); + dto.taskDefinitionKey = ht.getTaskDefinitionKey(); + dto.formKey = formKeyResolver.resolve(ht.getFormKey(), ht.getProcessDefinitionId(), ht.getTaskDefinitionKey()); + dto.startFormKey = startFormKeyResolver.resolve(ht.getProcessDefinitionId()); + var hpi = historyService.createHistoricProcessInstanceQuery() + .processInstanceId(ht.getProcessInstanceId()).singleResult(); + if (hpi != null) { + dto.businessKey = hpi.getBusinessKey(); + dto.ended = hpi.getEndTime() != null; + } + return ResponseEntity.ok(dto); + } + + @PostMapping("/tasks/{taskId}/reject") + @Operation(summary = "拒绝(终止流程)", + description = "对齐老 ProcessCoreServiceImpl.endProcess:审批拒绝=终止整个流程实例(deleteProcessInstance)," + + "记审批意见为评论、置 approveResult=reject 供轨迹。返回 businessKey/processEnded 供 gateway 回写 SYS_DATASTATUS=4(驳回)。") + public ResponseEntity> reject(@PathVariable String taskId, + @RequestBody(required = false) Requests.ActionRequest req) { + var t = taskService.createTaskQuery().taskId(taskId).singleResult(); + if (t == null) { + return ResponseEntity.notFound().build(); + } + String pid = t.getProcessInstanceId(); + ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(pid).singleResult(); + String businessKey = pi != null ? pi.getBusinessKey() : null; + String comment = req != null ? req.comment : null; + boolean hasComment = comment != null && !comment.isBlank(); + if (hasComment) { + taskService.addComment(taskId, pid, comment); + } + try { + runtimeService.setVariable(pid, "approveResult", "reject"); + } catch (RuntimeException ignore) { + /* 变量写入失败不阻断终止 */ + } + runtimeService.deleteProcessInstance(pid, hasComment ? comment : "审批拒绝"); + Map r = new java.util.LinkedHashMap<>(); + r.put("rejected", true); + r.put("processEnded", true); + r.put("businessKey", businessKey); + r.put("processInstanceId", pid); + return ResponseEntity.ok(r); + } + + @PostMapping("/tasks/{taskId}/reback") + @Operation(summary = "退回(发起人/起始节点)", + description = "对齐老 ProcessCoreServiceImpl.backProcess(isStart):把执行流退回到流程最早的历史任务节点(发起/拟稿节点)。" + + "用 changeActivityState moveActivityIdTo;记意见、置 approveResult=reback。返回 businessKey 供 gateway 回写 SYS_DATASTATUS=5(重新提交)。" + + "无法定位目标或已在起始节点 → 409。") + public ResponseEntity> reback(@PathVariable String taskId, + @RequestBody(required = false) Requests.ActionRequest req) { + var t = taskService.createTaskQuery().taskId(taskId).singleResult(); + if (t == null) { + return ResponseEntity.notFound().build(); + } + String pid = t.getProcessInstanceId(); + String currentKey = t.getTaskDefinitionKey(); + ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(pid).singleResult(); + String businessKey = pi != null ? pi.getBusinessKey() : null; + String comment = req != null ? req.comment : null; + boolean hasComment = comment != null && !comment.isBlank(); + if (hasComment) { + taskService.addComment(taskId, pid, comment); + } + // 退回目标 = 流程最早的历史任务节点(发起/拟稿节点) + List first = historyService.createHistoricTaskInstanceQuery() + .processInstanceId(pid).orderByHistoricTaskInstanceStartTime().asc().listPage(0, 1); + String targetKey = first.isEmpty() ? null : first.get(0).getTaskDefinitionKey(); + if (targetKey == null || targetKey.equals(currentKey)) { + Map err = new java.util.LinkedHashMap<>(); + err.put("status", 1); + err.put("msg", "已在起始节点或无法定位退回目标节点"); + return ResponseEntity.status(org.springframework.http.HttpStatus.CONFLICT).body(err); + } + try { + runtimeService.setVariable(pid, "approveResult", "reback"); + } catch (RuntimeException ignore) { + /* 变量写入失败不阻断退回 */ + } + try { + runtimeService.createChangeActivityStateBuilder() + .processInstanceId(pid) + .moveActivityIdTo(currentKey, targetKey) + .changeState(); + } catch (RuntimeException e) { + org.slf4j.LoggerFactory.getLogger(FlowController.class) + .error("[退回失败] pid={} {}→{}: {}", pid, currentKey, targetKey, e.toString()); + Map err = new java.util.LinkedHashMap<>(); + err.put("status", 1); + err.put("msg", "退回失败(流程结构不支持该跳转): " + e.getMessage()); + return ResponseEntity.status(org.springframework.http.HttpStatus.CONFLICT).body(err); + } + Map r = new java.util.LinkedHashMap<>(); + r.put("reback", true); + r.put("targetKey", targetKey); + r.put("businessKey", businessKey); + r.put("processInstanceId", pid); + return ResponseEntity.ok(r); + } + @GetMapping("/process/{processInstanceId}/trace") @Operation(summary = "流程轨迹", description = "返回该流程实例所有历史任务节点(含当前活动节点),按开始时间升序。每节点包含办理人姓名(经 sys_user 反查)、审批意见(Flowable 评论)、办理结果变量。") public ResponseEntity> trace(@PathVariable String processInstanceId) { @@ -344,6 +511,25 @@ public class FlowController { return ResponseEntity.ok(nodes); } + @GetMapping("/process/business/{businessKey}/trace") + @Operation(summary = "按业务主键查流程轨迹", + description = "列表行只有业务主键(=流程 businessKey),本端点按 businessKey 反查最近一次历史流程实例," + + "再复用 trace 组装审批轨迹(供列表「查看审批」按钮)。无对应流程 → 返回空列表(前端显「暂无审批记录」)。") + public ResponseEntity> traceByBusinessKey(@PathVariable String businessKey) { + if (businessKey == null || businessKey.isBlank()) { + return ResponseEntity.ok(new ArrayList<>()); + } + // 一个业务主键可能多次提交(驳回后重提)→ 取最近一次历史实例的轨迹。 + var list = historyService.createHistoricProcessInstanceQuery() + .processInstanceBusinessKey(businessKey.trim()) + .orderByProcessInstanceStartTime().desc() + .list(); + if (list == null || list.isEmpty()) { + return ResponseEntity.ok(new ArrayList<>()); + } + return trace(list.get(0).getId()); + } + /** * 经 sys_user 表反查用户姓名;biz 库连不上时 1s 超时降级返回 userId。 * 用独立线程 + Future.get(timeout) 保证不阻塞主流程(biz 库离线时快速失败)。 diff --git a/flowable-service/src/main/java/com/eip4/flowservice/api/Requests.java b/flowable-service/src/main/java/com/eip4/flowservice/api/Requests.java index 0544e74..8be35bf 100644 --- a/flowable-service/src/main/java/com/eip4/flowservice/api/Requests.java +++ b/flowable-service/src/main/java/com/eip4/flowservice/api/Requests.java @@ -21,6 +21,8 @@ public final class Requests { /** 办理(complete)任务。 */ public static class CompleteRequest { public Map variables; + /** 审批意见(非空则经 taskService.addComment 记入流程评论,供轨迹展示)。 */ + public String comment; } /** 委托(delegate)任务。 */ @@ -28,6 +30,17 @@ public final class Requests { public String delegateUserId; } + /** + * 审批动作(reject 拒绝终止 / reback 退回发起)通用入参。 + * 对齐老 {@code TaskProcessService}:意见记评论,targetUserId 供 agent/assist/circulated 指定对象。 + */ + public static class ActionRequest { + /** 审批意见(记入流程评论)。 */ + public String comment; + /** 目标用户(转办/协办/转阅用;reject/reback 不需要)。 */ + public String targetUserId; + } + /** * F2-6 JWT 瘦身:待办查询 body(替代 GET candidateGroup 多值参数, * 避免多角色用户 URL 超 8KB Tomcat 默认限制)。 diff --git a/flowable-service/src/main/java/com/eip4/flowservice/api/TaskDto.java b/flowable-service/src/main/java/com/eip4/flowservice/api/TaskDto.java index 2556825..498c06b 100644 --- a/flowable-service/src/main/java/com/eip4/flowservice/api/TaskDto.java +++ b/flowable-service/src/main/java/com/eip4/flowservice/api/TaskDto.java @@ -16,6 +16,12 @@ public class TaskDto { public String taskDefinitionKey; /** 流程业务主键(Flowable 6.8.1 Task/HistoricTaskInstance 接口无此字段,由查询侧从实例补全;供 gateway 聚合业务摘要)。 */ public String businessKey; + /** + * 任务表单 key(= view_wftemplate_id,WfTemplate 驱动审批界面的钥匙)。 + * 取 {@code task.getFormKey()};运行中任务该字段多为空(迁移仅落 HI 行未回填 RU.form_key_), + * 由查询侧 {@code FormKeyResolver} 按 (procDefId, taskDefKey) 从历史回补(实测 99.98% 可补)。 + */ + public String formKey; public Long createTimeMillis; public Long endTimeMillis; public boolean suspended; @@ -29,6 +35,7 @@ public class TaskDto { d.processInstanceId = t.getProcessInstanceId(); d.processDefinitionId = t.getProcessDefinitionId(); d.taskDefinitionKey = t.getTaskDefinitionKey(); + d.formKey = t.getFormKey(); d.createTimeMillis = t.getCreateTime() != null ? t.getCreateTime().getTime() : null; d.suspended = t.isSuspended(); return d; @@ -43,6 +50,7 @@ public class TaskDto { d.processInstanceId = t.getProcessInstanceId(); d.processDefinitionId = t.getProcessDefinitionId(); d.taskDefinitionKey = t.getTaskDefinitionKey(); + d.formKey = t.getFormKey(); d.createTimeMillis = t.getCreateTime() != null ? t.getCreateTime().getTime() : null; d.endTimeMillis = t.getEndTime() != null ? t.getEndTime().getTime() : null; return d; diff --git a/flowable-service/src/main/java/com/eip4/flowservice/wf/FormKeyResolver.java b/flowable-service/src/main/java/com/eip4/flowservice/wf/FormKeyResolver.java new file mode 100644 index 0000000..d67d7fb --- /dev/null +++ b/flowable-service/src/main/java/com/eip4/flowservice/wf/FormKeyResolver.java @@ -0,0 +1,74 @@ +package com.eip4.flowservice.wf; + +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +import org.flowable.engine.HistoryService; +import org.flowable.task.api.history.HistoricTaskInstance; +import org.springframework.stereotype.Component; + +/** + * 任务 formKey(= view_wftemplate_id)解析器:WfTemplate 驱动审批界面的钥匙。 + * + *

根因(已实测坐实):迁移把老 activiti 历史任务整表搬进 {@code act_hi_taskinst} + * (form_key_ 覆盖 56900/56905 ≈ 99.99%),但运行中任务表 {@code act_ru_task} 的 form_key_ + * 几乎全空(9378 中仅 57 带值 ≈ 0.6%)——迁移未回填运行库该列。于是 {@code task.getFormKey()} + * 对绝大多数待办返空,数据驱动审批退化为默认按钮,等于没用 1016 个 WfTemplate。 + * + *

回补策略:同一 userTask 定义(同 procDefId + taskDefKey)的 formKey 恒定,故运行任务 + * 缺 formKey 时,按 {@code (processDefinitionId, taskDefinitionKey)} 从历史表回查一行非空 formKey。 + * 实测可回补 9376/9378 ≈ 99.98% 的运行任务,且回查出的 286 个去重 formKey 100% 命中 view_wftemplate。 + * 对齐老系统 {@code FormService.getTaskFormKey(procDefId, taskDefKey)} 的取法(老靠 BPMN,本系统迁移后 + * BPMN 未带 formKey,故改走等价的历史回查)。 + * + *

结果带进程内缓存(同定义重复命中,待办列表常多任务共享定义),命中即定,不重复查历史。 + */ +@Component +public class FormKeyResolver { + + /** 缓存键分隔符(procDefId 与 taskDefKey 均不含此控制字符)。 */ + private static final String SEP = "\n"; + + private final HistoryService historyService; + private final ConcurrentHashMap cache = new ConcurrentHashMap<>(); + + public FormKeyResolver(HistoryService historyService) { + this.historyService = historyService; + } + + /** + * 解析任务 formKey:运行时值非空则直接用;否则按 (procDefId, taskDefKey) 历史回补。 + * + * @param runtimeFormKey {@code task.getFormKey()} 的原值(可空) + * @return formKey(= view_wftemplate_id);无法解析返回 null(调用方降级默认按钮) + */ + public String resolve(String runtimeFormKey, String processDefinitionId, String taskDefinitionKey) { + if (notBlank(runtimeFormKey)) { + return runtimeFormKey; + } + if (!notBlank(processDefinitionId) || !notBlank(taskDefinitionKey)) { + return null; + } + String cacheKey = processDefinitionId + SEP + taskDefinitionKey; + // computeIfAbsent 不缓存 null:回查不到则每次重查(可接受,命中后即缓存)。 + return cache.computeIfAbsent(cacheKey, k -> resolveFromHistory(processDefinitionId, taskDefinitionKey)); + } + + /** 按 (procDefId, taskDefKey) 取一行非空 formKey 的历史任务。取小页扫描,避免全量加载。 */ + private String resolveFromHistory(String processDefinitionId, String taskDefinitionKey) { + List rows = historyService.createHistoricTaskInstanceQuery() + .processDefinitionId(processDefinitionId) + .taskDefinitionKey(taskDefinitionKey) + .listPage(0, 10); + for (HistoricTaskInstance ht : rows) { + if (notBlank(ht.getFormKey())) { + return ht.getFormKey(); + } + } + return null; + } + + private static boolean notBlank(String s) { + return s != null && !s.isBlank(); + } +} diff --git a/flowable-service/src/main/java/com/eip4/flowservice/wf/StartFormKeyResolver.java b/flowable-service/src/main/java/com/eip4/flowservice/wf/StartFormKeyResolver.java new file mode 100644 index 0000000..2645718 --- /dev/null +++ b/flowable-service/src/main/java/com/eip4/flowservice/wf/StartFormKeyResolver.java @@ -0,0 +1,121 @@ +package com.eip4.flowservice.wf; + +import java.io.InputStream; +import java.util.concurrent.ConcurrentHashMap; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.flowable.bpmn.model.BpmnModel; +import org.flowable.bpmn.model.FlowElement; +import org.flowable.bpmn.model.StartEvent; +import org.flowable.engine.RepositoryService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +/** + * 流程「开始节点」formKey 解析器(= 老审批页对裸节点的回退依据)。 + * + *

为何需要它(对齐老 {@code TaskDetailPage.initPage}):老系统取任务 formKey 后,若该 WfTemplate + * 没有 pageid(裸审批节点,只配按钮),就回退到 {@code FormService.getStartFormKey(procDef)}——即流程 + * 开始节点的 formKey,其 WfTemplate 才有真正的 pageid(展示页)+ {@code }(加载服务)+ 只读脚本。 + * + *

取值:迁移后的 BPMN 用 activiti 命名空间 {@code activiti:formKey}(flowable 的 + * {@code task.getFormKey()} 读不到它,故运行库 form_key_ 全空)。本类先试 flowable 的 {@link BpmnModel} + * (部分版本能读 activiti:formKey),读不到再直接解析 BPMN XML 资源取 {@code } 的 formKey + * (activiti/flowable/无前缀三种命名空间都试)。结果按 procDefId 缓存(流程定义不可变)。 + */ +@Component +public class StartFormKeyResolver { + + private static final Logger log = LoggerFactory.getLogger(StartFormKeyResolver.class); + + private static final String NS_ACTIVITI = "http://activiti.org/bpmn"; + private static final String NS_FLOWABLE = "http://flowable.org/bpmn"; + + private final RepositoryService repositoryService; + private final ConcurrentHashMap cache = new ConcurrentHashMap<>(); + + public StartFormKeyResolver(RepositoryService repositoryService) { + this.repositoryService = repositoryService; + } + + /** 取流程开始节点 formKey;解析不到返回 null(调用方不回退)。 */ + public String resolve(String processDefinitionId) { + if (processDefinitionId == null || processDefinitionId.isBlank()) { + return null; + } + return cache.computeIfAbsent(processDefinitionId, this::resolveUncached); + } + + private String resolveUncached(String procDefId) { + String viaModel = fromBpmnModel(procDefId); + if (notBlank(viaModel)) { + return viaModel; + } + return fromXmlResource(procDefId); + } + + /** 经 flowable BpmnModel 取开始节点 formKey(若该版本把 activiti:formKey 读进模型)。 */ + private String fromBpmnModel(String procDefId) { + try { + BpmnModel model = repositoryService.getBpmnModel(procDefId); + if (model == null || model.getMainProcess() == null) { + return null; + } + for (FlowElement el : model.getMainProcess().getFlowElements()) { + if (el instanceof StartEvent se && notBlank(se.getFormKey())) { + return se.getFormKey(); + } + } + } catch (RuntimeException e) { + log.debug("BpmnModel 取开始 formKey 失败(转 XML 解析) procDef={}: {}", procDefId, e.toString()); + } + return null; + } + + /** 直接解析 BPMN XML 资源取 startEvent 的 formKey(activiti/flowable/无前缀都试)。 */ + private String fromXmlResource(String procDefId) { + try (InputStream is = repositoryService.getProcessModel(procDefId)) { + if (is == null) { + return null; + } + DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); + f.setNamespaceAware(true); + f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + DocumentBuilder b = f.newDocumentBuilder(); + org.w3c.dom.Document doc = b.parse(is); + NodeList starts = doc.getElementsByTagNameNS("*", "startEvent"); + if (starts.getLength() == 0) { + return null; + } + Element se = (Element) starts.item(0); + String fk = firstNonBlank( + se.getAttributeNS(NS_ACTIVITI, "formKey"), + se.getAttributeNS(NS_FLOWABLE, "formKey"), + se.getAttribute("formKey"), + se.getAttribute("activiti:formKey"), + se.getAttribute("flowable:formKey")); + return notBlank(fk) ? fk : null; + } catch (Exception e) { + log.warn("解析 BPMN XML 取开始 formKey 失败 procDef={}: {}", procDefId, e.toString()); + return null; + } + } + + private static String firstNonBlank(String... vals) { + for (String v : vals) { + if (notBlank(v)) { + return v; + } + } + return null; + } + + private static boolean notBlank(String s) { + return s != null && !s.isBlank(); + } +} diff --git a/platform-flow-gateway/pom.xml b/platform-flow-gateway/pom.xml index 90bb530..bad508b 100644 --- a/platform-flow-gateway/pom.xml +++ b/platform-flow-gateway/pom.xml @@ -25,6 +25,8 @@ com.eip4platform-legacy-core + + com.eip4platform-metadata com.eip4platform-auth diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/BusinessRecordLoader.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/BusinessRecordLoader.java new file mode 100644 index 0000000..02e56a7 --- /dev/null +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/BusinessRecordLoader.java @@ -0,0 +1,154 @@ +package com.eip4.platform.flowgateway.aggregate; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import com.dsasp.server.common.core.service.FlowExcuteService; +import com.dsasp.server.common.dataDic.bean.GeneralPOJO; +import com.dsasp.server.common.dataDic.service.POJOCRUDService; +import com.dsasp.server.common.util.UserSession; + +/** + * 业务记录载入器:WfTemplate 驱动审批的「业务表单数据 / action 服务流入参」统一来源。 + * + *

为何要它(实测踩坑):老审批页用 WfTemplate 的 {@code } 服务流载入单据(含引用列 id→名、 + * 子表层级,比裸读实体更忠实)。但部分 load 服务流会挂死(实测 {@code PM_PUB_SAFETYRECTIFICATION_LOAD} + * 卡 30s+ 不返回,疑 groovy 死循环/坏子表)。若把它直接当表单数据源,审批页会一直转圈。 + * + *

策略:①优先跑 load 服务流,但用 {@value #LOAD_FLOW_TIMEOUT_MS}ms 超时硬上限(独立线程 + + * {@link Future#get(long, TimeUnit)})防挂死;②超时/异常/无 load → 退化为 {@code POJOCRUDService.loadPOJO} + * (可靠、待办聚合一直在用)。两者都把 {@link GeneralPOJO} 拍平成可 JSON 序列化的 Map。 + * + *

用真实用户上下文取不到(超时线程非请求线程,{@code UserSession.get()} 是 ThreadLocal)→ 统一用 + * {@code UserSession.getAdmin()} 载入(只读、全字段;写侧权限由 action 服务流自身的执行上下文把关)。 + */ +@Service +public class BusinessRecordLoader { + + private static final Logger log = LoggerFactory.getLogger(BusinessRecordLoader.class); + + /** load 服务流超时硬上限(部分流挂死,超此即放弃转 loadPOJO)。 */ + private static final long LOAD_FLOW_TIMEOUT_MS = 4000; + /** 拍平递归深度上限(防子表互引成环)。 */ + private static final int MAX_DEPTH = 8; + + private final FlowExcuteService flowExcuteService; + private final POJOCRUDService pojoCRUDService; + /** 守护线程池:给 load 服务流套超时(挂死的流线程被丢弃,不拖累请求线程)。 */ + private final ExecutorService timeoutPool = Executors.newCachedThreadPool(r -> { + Thread t = new Thread(r, "wf-load-timeout"); + t.setDaemon(true); + return t; + }); + + public BusinessRecordLoader(FlowExcuteService flowExcuteService, POJOCRUDService pojoCRUDService) { + this.flowExcuteService = flowExcuteService; + this.pojoCRUDService = pojoCRUDService; + } + + /** + * 载入业务记录为平面 Map(对齐老审批页的「表单加载服务」)。 + * + *

数据源优先级:①WfTemplate 节点显式 {@code } 服务流(最贴该节点);②否则表的标准表单加载服务 + * {@code _LOAD}(约定式,100/104 业务表都有——这才是老审批页真正调的「表单加载服务」, + * 含接收人/子表/引用,loadPOJO 取不到);③前两者失败/超时 → loadPOJO(层级) 兜底。均带 4s 超时守护防挂死。 + */ + public Map load(String loadScript, String table, String businessKey) { + if (table == null || table.isBlank() || businessKey == null || businessKey.isBlank()) { + return new LinkedHashMap<>(); + } + String t = table.trim(); + // 显式 优先;空则退到约定式
_LOAD(即审批表单加载服务) + String effectiveLoad = (loadScript != null && !loadScript.isBlank()) + ? loadScript : t.toUpperCase() + "_LOAD"; + Map viaFlow = tryLoadFlow(effectiveLoad, t, businessKey); + if (viaFlow != null && !viaFlow.isEmpty()) { + return viaFlow; + } + return loadViaPojo(t, businessKey); + } + + /** 跑 load 服务流(超时硬上限)。成功返回拍平记录;无 load/超时/异常/空 → null(调用方退化 loadPOJO)。 */ + private Map tryLoadFlow(String loadScript, String table, String businessKey) { + if (loadScript == null || loadScript.isBlank()) { + return null; + } + Future> future = timeoutPool.submit(() -> { + Map in = new HashMap<>(); + in.put(table.toUpperCase() + "_ID", businessKey); // load 流主键入参名约定 =
_ID(tableName 有 initValue) + Object out = flowExcuteService.excute(in, UserSession.getAdmin(), loadScript); + Object rec = (out instanceof Map m) ? m.get("result") : out; + Object flat = flatten(rec, 0); + return flat instanceof Map ? castMap(flat) : null; + }); + try { + return future.get(LOAD_FLOW_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (Exception e) { + future.cancel(true); + log.warn("[业务记录] load 服务流超时/失败,退化 loadPOJO loadScript={} bk={}: {}", + loadScript, businessKey, e.getClass().getSimpleName()); + return null; + } + } + + /** 退化路径:可靠的 loadPOJO(层级=true,尽量带上子表,比无层级更接近表单所需)。 */ + private Map loadViaPojo(String table, String businessKey) { + try { + GeneralPOJO p = pojoCRUDService.loadPOJO(businessKey, table.toUpperCase(), UserSession.getAdmin(), true); + Object flat = flatten(p, 0); + return flat instanceof Map ? castMap(flat) : new LinkedHashMap<>(); + } catch (RuntimeException e) { + log.debug("[业务记录] loadPOJO 降级(table={} bk={}): {}", table, businessKey, e.getMessage()); + return new LinkedHashMap<>(); + } + } + + /** GeneralPOJO/容器 → 可 JSON 序列化的平面结构(深度受限,防环;对齐 metadata FlowController.normalize 口径)。 */ + private static Object flatten(Object value, int depth) { + if (depth > MAX_DEPTH) { + return (value instanceof GeneralPOJO || value instanceof Map || value instanceof List) ? null : value; + } + if (value instanceof GeneralPOJO p) { + Map row = new LinkedHashMap<>(); + for (int i = 0; i < p.get_ColumnCount(); i++) { + row.put(p.get_ColumnName(i), flatten(p.get_Value(i), depth + 1)); + } + return row; + } + if (value instanceof Map m) { + Map out = new LinkedHashMap<>(); + for (Map.Entry e : m.entrySet()) { + out.put(String.valueOf(e.getKey()), flatten(e.getValue(), depth + 1)); + } + return out; + } + if (value instanceof List list) { + List out = new ArrayList<>(list.size()); + for (Object o : list) { + out.add(flatten(o, depth + 1)); + } + return out; + } + // CHAR(36) 主键/外键 PG 以尾空格补白返回,致 picker/select 值匹配不上 option → 去补白 + if (value instanceof String s && s.length() != s.stripTrailing().length()) { + return s.stripTrailing(); + } + return value; + } + + @SuppressWarnings("unchecked") + private static Map castMap(Object o) { + return (Map) o; + } +} diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/WfTemplateService.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/WfTemplateService.java new file mode 100644 index 0000000..ccdd8ad --- /dev/null +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/WfTemplateService.java @@ -0,0 +1,257 @@ +package com.eip4.platform.flowgateway.aggregate; + +import java.io.StringReader; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; + +/** + * WfTemplate(审批流转模板)读取 + 解析服务:WfTemplate 驱动审批界面的后端核心。 + * + *

背景:老系统整个审批界面由 {@code view_wftemplate}(1016 行已迁移)数据驱动—— + * 按钮、页面加载脚本、业务表单视图全在模板 XML 里,随节点定制。新系统此前把这些全写死, + * 完全没用迁移过来的模板。本服务把模板读出来、解析成结构化元数据,交给 approval-meta 端点。 + * + *

XML 结构(实测): + *

{@code
+ * 
+ * + * + * + * + * + * … + * + * }
+ * + *

数据源:注入应用主 {@code JdbcTemplate}(与 {@link BusinessSummaryService}/ + * {@link PageTemplateService} 同源,连业务库 eip3 schema),只读 {@code view_wftemplate} 与 + * {@code sys_page_schema}。任何缺失/异常一律降级(返回 {@link WfTemplateMeta#EMPTY}),不抛。 + */ +@Service +public class WfTemplateService { + + private static final Logger log = LoggerFactory.getLogger(WfTemplateService.class); + + private final JdbcTemplate jdbcTemplate; + + public WfTemplateService(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + /** 一个审批按钮(toolbar/action)。 */ + public record Button(String id, String label, String type, String servicename) { + } + + /** 解析后的模板元数据。 */ + public record WfTemplateMeta(List

_DISPLAY__} 显示名。 */ + private final com.eip4.platform.metadata.flow.UserColumnResolver userColumnResolver; + + public ApprovalController(FlowableClient flowableClient, WfTemplateService wfTemplateService, + BusinessSummaryService businessSummaryService, StatusWriteback statusWriteback, + FlowExcuteService flowExcuteService, BusinessRecordLoader businessRecordLoader, + com.eip4.platform.metadata.flow.UserColumnResolver userColumnResolver) { + this.flowableClient = flowableClient; + this.wfTemplateService = wfTemplateService; + this.businessSummaryService = businessSummaryService; + this.statusWriteback = statusWriteback; + this.flowExcuteService = flowExcuteService; + this.businessRecordLoader = businessRecordLoader; + this.userColumnResolver = userColumnResolver; + } + + @Operation(summary = "审批元数据(WfTemplate 驱动)", + description = "任务 formKey(历史回补)→ view_wftemplate 解析按钮/加载脚本/业务表单模板 id;" + + "无模板回退默认按钮(同意/驳回)。formTemplateId 仅当模板 pageid 在 sys_page_schema 有 amis schema 时返回(前端据此渲染只读业务单据)。") + @GetMapping("/api/task/{taskId}/approval-meta") + public ResponseEntity> approvalMeta(@PathVariable String taskId) { + ApprovalContextDto ctx = flowableClient.approvalContext(taskId); + WfTemplateMeta taskMeta = ctx == null ? WfTemplateMeta.EMPTY : wfTemplateService.parse(ctx.formKey); + // 生效表单模板:任务节点裸模板(无pageid)→回退开始节点模板(对齐老 TaskDetailPage)。按钮仍用任务模板。 + WfTemplateMeta formMeta = wfTemplateService.effectiveFormMeta(taskMeta, ctx == null ? null : ctx.startFormKey); + + Map resp = new LinkedHashMap<>(); + resp.put("found", ctx != null && ctx.found); + resp.put("taskId", taskId); + resp.put("taskName", ctx == null ? null : ctx.taskName); + resp.put("formKey", ctx == null ? null : ctx.formKey); + // 按钮优先任务节点模板(保留节点定制 label),空则用生效表单模板,再空回退默认 + WfTemplateMeta btnMeta = taskMeta.hasButtons() ? taskMeta : formMeta; + resp.put("buttons", btnMeta.hasButtons() ? buttonsToMaps(btnMeta) : DEFAULT_BUTTONS); + resp.put("buttonsSource", btnMeta.hasButtons() ? "wftemplate" : "default"); + // 加载服务/showsend 来自生效表单模板(裸节点取开始节点的 ) + resp.put("loadScript", formMeta.loadScript()); + resp.put("showsend", formMeta.showsend()); + + String businessKey = ctx == null ? null : ctx.businessKey; + resp.put("businessKey", businessKey); + String businessTable = businessKey == null ? null + : businessSummaryService.summarize(businessKey).tableName(); + resp.put("businessTable", businessTable); + // 友好中文名(sys_entity.name),前端显「业务单据(施工方案审批)」而非裸表名 + resp.put("businessTableName", wfTemplateService.entityDisplayName(businessTable)); + resp.put("processInstanceId", ctx == null ? null : ctx.processInstanceId); + resp.put("ended", ctx != null && ctx.ended); + resp.put("suspended", ctx != null && ctx.suspended); + + // 业务表单页面:生效表单模板(任务/开始节点)的 pageid 命中 sys_page_schema 优先——即老审批页用的同一张页面; + // 都没有再退该业务表标准 editform。前端据此渲染只读业务单据。 + resp.put("formTemplateId", wfTemplateService.resolveBusinessFormTemplateId(formMeta.pageid(), businessTable)); + return ResponseEntity.ok(resp); + } + + @Operation(summary = "审批业务单据数据(保真层 load 流,超时退化 loadPOJO)", + description = "前端只读业务表单的数据源。优先跑 WfTemplate 的 服务流(含引用列 id→名、子表," + + "对齐老审批页),4s 超时硬上限防挂死,超时/异常退化 loadPOJO。返回 amis 单记录契约 {status:0,data:{...record}}。") + @GetMapping("/api/task/{taskId}/business-data") + public ResponseEntity> businessData(@PathVariable String taskId) { + ApprovalContextDto ctx = flowableClient.approvalContext(taskId); + Map envelope = new LinkedHashMap<>(); + envelope.put("status", 0); + envelope.put("msg", ""); + if (ctx == null || ctx.businessKey == null) { + envelope.put("data", new LinkedHashMap<>()); + return ResponseEntity.ok(envelope); + } + // 生效表单模板的 (裸节点取开始节点配置的加载服务,对齐老审批页) + WfTemplateMeta formMeta = wfTemplateService.effectiveFormMeta( + wfTemplateService.parse(ctx.formKey), ctx.startFormKey); + String table = businessSummaryService.summarize(ctx.businessKey).tableName(); + Map record = businessRecordLoader.load(formMeta.loadScript(), table, ctx.businessKey); + // 引用列 id→名(全站统一口径):主表 + 子表行补 _DISPLAY__,前端引用列显名不显 id + if (table != null && record != null && !record.isEmpty()) { + try { + userColumnResolver.resolveFormRecord(table, record); + } catch (RuntimeException e) { + log.debug("[审批表单] 引用列解析降级 table={}: {}", table, e.toString()); + } + // 多选人员列(值为 id 列表,如接收人 NOTICEDRAFTPEOPLES,元数据未登记为引用列单值解析漏掉)→ 解析为姓名串 + try { + for (Map.Entry e : new java.util.ArrayList<>(record.entrySet())) { + if (e.getValue() instanceof List list && !list.isEmpty() && list.get(0) instanceof String) { + record.put(e.getKey() + "_DISPLAY__", userColumnResolver.joinUserDisplayNames(list)); + } + } + } catch (RuntimeException e) { + log.debug("[审批表单] 多选人员列解析降级 table={}: {}", table, e.toString()); + } + } + envelope.put("data", record); + return ResponseEntity.ok(envelope); + } + + @Operation(summary = "审批动作分派(按 WfTemplate 按钮 type)", + description = "approve=complete+回写 SYS_DATASTATUS(结束 3/未结束 2);reject=终止流程+回写 4;" + + "reback=退回发起+回写 5;agent=委托给 targetUserId。协办/转阅暂未实现(返回 400)。") + @PostMapping("/api/task/{taskId}/action") + public ResponseEntity> action(@PathVariable String taskId, + @RequestBody GatewayRequests.ApprovalActionRequest req) { + if (req == null || req.actionType == null || req.actionType.isBlank()) { + return badRequest("actionType 不能为空"); + } + String type = req.actionType.trim().toLowerCase(); + + // 自定义服务流(WfTemplate action 的 servicename):核心动作前执行(对齐老 TaskProcessService: + // 服务先跑,异常则整个动作中止,不推进流程)。服务名服务器侧按 buttonId 重解析,不信前端直传。 + ResponseEntity> svcErr = runActionServiceIfAny(taskId, req); + if (svcErr != null) { + return svcErr; + } + + return switch (type) { + case "approve" -> approve(taskId, req); + case "reject" -> reject(taskId, req); + case "reback" -> reback(taskId, req); + case "agent" -> agent(taskId, req); + case "assist", "circulated" -> badRequest("暂不支持「" + labelOf(type) + "」,请用转办(agent)"); + default -> badRequest("未知审批动作: " + type); + }; + } + + /** + * 若该按钮(buttonId)在 WfTemplate 配了 servicename,核心动作前调保真层服务流执行(对齐老 + * {@code TaskProcessServiceImpl.approve}:{@code if(!empty(method)) flowExcuteService.excute(map,ctx,method)})。 + * 用真实用户上下文({@link UserSession#get()})以使写侧数据权限/拟稿人生效。服务抛异常 → 返回错误中止动作。 + * + * @return 非 null = 服务执行失败的错误响应(中止动作);null = 无服务流或执行成功(继续核心动作) + */ + private ResponseEntity> runActionServiceIfAny(String taskId, + GatewayRequests.ApprovalActionRequest req) { + if (req.buttonId == null || req.buttonId.isBlank()) { + return null; // 无 buttonId → 无从解析服务名(默认按钮无 servicename) + } + ApprovalContextDto ctx = flowableClient.approvalContext(taskId); + String formKey = ctx == null ? null : ctx.formKey; + WfTemplateMeta meta = wfTemplateService.parse(formKey); + String servicename = servicenameForButton(meta, req.buttonId); + if (servicename == null) { + return null; // 该按钮未配自定义服务 → 直接核心动作 + } + String businessKey = req.businessKey != null ? req.businessKey : (ctx == null ? null : ctx.businessKey); + String table = resolveTable(req.tableName, businessKey); + + // 入参基底 = 完整业务记录。写服务流(如 *_UPDATE)需全字段;只传主键会把其余列写空(老系统提交的是表单全量记录)。 + // load 用生效表单模板(裸节点取开始节点配置);经 BusinessRecordLoader 载入(超时守护 → loadPOJO 退化)。 + WfTemplateMeta formMeta = wfTemplateService.effectiveFormMeta(meta, ctx == null ? null : ctx.startFormKey); + Map svcMap = new HashMap<>(businessRecordLoader.load(formMeta.loadScript(), table, businessKey)); + if (table != null && businessKey != null) { + svcMap.put(table.toUpperCase() + "_ID", businessKey); // 主键入参名约定 =
_ID + } + if (businessKey != null) { + svcMap.put("businessKey", businessKey); + } + if (req.comment != null && !req.comment.isBlank()) { + svcMap.put("comment", req.comment); + } + try { + flowExcuteService.excute(svcMap, currentCtx(), servicename); + log.info("[审批服务] 执行成功 servicename={} taskId={} bk={} 字段数={}", servicename, taskId, businessKey, svcMap.size()); + return null; + } catch (RuntimeException e) { + log.warn("[审批服务] 执行失败 servicename={} taskId={}: {}", servicename, taskId, e.toString()); + Map err = new LinkedHashMap<>(); + err.put("status", 1); + err.put("msg", "审批服务执行失败,动作已中止: " + safeMsg(e)); + return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(err); + } + } + + /** 在已解析的模板里按 buttonId 找该按钮的 servicename(与 WfTemplateService.servicenameForButton 同义,复用已 parse 的 meta 省一次解析)。 */ + private static String servicenameForButton(WfTemplateMeta meta, String buttonId) { + for (WfTemplateService.Button b : meta.buttons()) { + if (buttonId.equals(b.id())) { + return b.servicename(); + } + } + return null; + } + + /** 当前请求的引擎上下文(JwtAuthFilter 绑真实用户 → 写侧数据权限/拟稿人生效),无绑定回退 ADMIN。 */ + private static Properties currentCtx() { + Properties bound = UserSession.get(); + return bound != null ? bound : UserSession.getAdmin(); + } + + /** 异常消息脱敏:只透出短、单行、无技术标记的消息(避免泄露 SQL/栈),否则给通用文案。 */ + private static String safeMsg(Throwable e) { + String m = e.getMessage(); + if (m == null) { + return "服务内部错误"; + } + String s = m.trim(); + if (s.isEmpty() || s.length() > 100 || s.indexOf('\n') >= 0 + || s.toLowerCase().matches(".*(exception|sql|java\\.|com\\.dsasp|null).*")) { + return "服务内部错误"; + } + return s; + } + + // ---------------------------------------------------------------- 分派实现 + + /** 同意:complete(approveResult=agree)+记意见,按实例是否结束回写 SYS_DATASTATUS(3 通过/2 处理中)。 */ + private ResponseEntity> approve(String taskId, GatewayRequests.ApprovalActionRequest req) { + Map vars = new LinkedHashMap<>(); + vars.put("approveResult", "agree"); + flowableClient.complete(taskId, vars, req.comment); + + boolean ended = isProcessEnded(req.processInstanceId); + String table = resolveTable(req.tableName, req.businessKey); + boolean written = statusWriteback.afterComplete(req.businessKey, table, ended); + + Map r = ok("approve"); + r.put("completed", true); + r.put("processEnded", ended); + r.put("statusWritten", written); + return ResponseEntity.ok(r); + } + + /** 拒绝:终止流程(引擎 deleteProcessInstance)+回写 SYS_DATASTATUS=4(驳回)。 */ + private ResponseEntity> reject(String taskId, GatewayRequests.ApprovalActionRequest req) { + Map engine = flowableClient.reject(taskId, req.comment); + String businessKey = req.businessKey != null ? req.businessKey : strOf(engine, "businessKey"); + boolean written = writeStatus(businessKey, req.tableName, ProcessCoreService.STATUS_NOPASS); + + Map r = ok("reject"); + r.put("rejected", true); + r.put("processEnded", true); + r.put("statusWritten", written); + return ResponseEntity.ok(r); + } + + /** 退回:退回发起节点(引擎 changeActivityState)+回写 SYS_DATASTATUS=5(重新提交)。引擎 409 透传。 */ + private ResponseEntity> reback(String taskId, GatewayRequests.ApprovalActionRequest req) { + Map engine = flowableClient.reback(taskId, req.comment); + String businessKey = req.businessKey != null ? req.businessKey : strOf(engine, "businessKey"); + boolean written = writeStatus(businessKey, req.tableName, ProcessCoreService.STATUS_RESUBMIT); + + Map r = ok("reback"); + r.put("reback", true); + r.put("targetKey", strOf(engine, "targetKey")); + r.put("statusWritten", written); + return ResponseEntity.ok(r); + } + + /** 转办:委托给 targetUserId(assignee 变受托人)。 */ + private ResponseEntity> agent(String taskId, GatewayRequests.ApprovalActionRequest req) { + if (req.targetUserId == null || req.targetUserId.isBlank()) { + return badRequest("转办需指定 targetUserId"); + } + flowableClient.delegate(taskId, req.targetUserId.trim()); + Map r = ok("agent"); + r.put("delegated", true); + r.put("targetUserId", req.targetUserId.trim()); + return ResponseEntity.ok(r); + } + + // ---------------------------------------------------------------- 小工具 + + /** 直接回写业务状态(reject/reback 是显式终态转移,不走单调守卫)。businessKey 空则不写。 */ + private boolean writeStatus(String businessKey, String tableName, int status) { + if (businessKey == null || businessKey.isBlank()) { + return false; + } + statusWriteback.updateStatus(businessKey, resolveTable(tableName, businessKey), status); + return true; + } + + /** tableName 缺省时按 businessKey 反查(SYS_DATASTATUS)。 */ + private String resolveTable(String provided, String businessKey) { + if (provided != null && !provided.isBlank()) { + return provided; + } + if (businessKey == null || businessKey.isBlank()) { + return null; + } + return businessSummaryService.summarize(businessKey).tableName(); + } + + /** 实例不存在(已被清理)视为已结束。 */ + private boolean isProcessEnded(String processInstanceId) { + if (processInstanceId == null || processInstanceId.isBlank()) { + return false; + } + ProcessInstanceDto pi = flowableClient.processInstance(processInstanceId); + return pi == null || pi.ended; + } + + private static List> buttonsToMaps(WfTemplateMeta meta) { + List> list = new ArrayList<>(); + for (WfTemplateService.Button b : meta.buttons()) { + list.add(buttonMap(b.id(), b.label(), b.type(), b.servicename())); + } + return list; + } + + private static Map buttonMap(String id, String label, String type, String servicename) { + Map m = new LinkedHashMap<>(); + m.put("id", id); + m.put("label", label); + m.put("type", type); + m.put("servicename", servicename); + return m; + } + + private static Map ok(String action) { + Map r = new LinkedHashMap<>(); + r.put("action", action); + return r; + } + + private static ResponseEntity> badRequest(String msg) { + Map r = new LinkedHashMap<>(); + r.put("status", 1); + r.put("msg", msg); + return ResponseEntity.badRequest().body(r); + } + + private static String strOf(Map m, String key) { + Object v = m == null ? null : m.get(key); + return v == null ? null : String.valueOf(v); + } + + private static String labelOf(String type) { + return "assist".equals(type) ? "协办" : "转阅"; + } +} diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/GatewayRequests.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/GatewayRequests.java index df79967..2f1c010 100644 --- a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/GatewayRequests.java +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/GatewayRequests.java @@ -35,4 +35,23 @@ public final class GatewayRequests { public static class DelegateRequest { public String delegateUserId; } + + /** + * WfTemplate 驱动审批的统一动作请求({@code POST /api/task/{id}/action})。 + * + *

{@code actionType} 来自 WfTemplate 按钮的 type:approve/reject/reback/agent/assist/circulated。 + * 网关按 type 分派到引擎对应操作并回写 SYS_DATASTATUS。businessKey/processInstanceId/tableName + * 供回写定位(缺 tableName 时网关按 businessKey 反查)。 + */ + public static class ApprovalActionRequest { + public String actionType; + /** WfTemplate 按钮 id:服务器侧据此重解析该按钮的 servicename(自定义服务流)并执行,不信前端直传服务名。 */ + public String buttonId; + public String comment; + /** 转办/协办/转阅的目标用户。 */ + public String targetUserId; + public String businessKey; + public String processInstanceId; + public String tableName; + } } diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/TodoController.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/TodoController.java index ee9300a..8c9bbe3 100644 --- a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/TodoController.java +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/TodoController.java @@ -115,6 +115,14 @@ public class TodoController { return ResponseEntity.ok(nodes); } + @Operation(summary = "按业务主键查流程轨迹", + description = "列表行只有业务主键(=流程 businessKey),按 businessKey 反查最近一次历史流程实例的审批轨迹(供列表「查看审批」按钮);无对应流程返回空列表") + @GetMapping("/api/flow/business/{businessKey}/trace") + public ResponseEntity> traceByBusiness(@PathVariable String businessKey) { + List nodes = flowableClient.traceByBusiness(businessKey); + return ResponseEntity.ok(nodes); + } + @Operation(summary = "委托任务", description = "将任务委托给指定用户(delegateUserId),assignee 变受托人,owner 记原办理人") @PostMapping("/api/task/{id}/delegate") public ResponseEntity> delegate(@PathVariable String id, diff --git a/platform-flow-gateway/src/test/java/com/eip4/platform/flowgateway/WfTemplateServiceTest.java b/platform-flow-gateway/src/test/java/com/eip4/platform/flowgateway/WfTemplateServiceTest.java new file mode 100644 index 0000000..85eccac --- /dev/null +++ b/platform-flow-gateway/src/test/java/com/eip4/platform/flowgateway/WfTemplateServiceTest.java @@ -0,0 +1,69 @@ +package com.eip4.platform.flowgateway; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +import com.eip4.platform.flowgateway.aggregate.WfTemplateService; +import com.eip4.platform.flowgateway.aggregate.WfTemplateService.WfTemplateMeta; + +/** + * WfTemplate XML 解析单测:锁定按钮(label/type/servicename)、加载脚本、showsend、pageid/entityid 的提取, + * 以及空/坏 XML 的优雅降级(WfTemplate 驱动审批界面的核心解析)。 + */ +class WfTemplateServiceTest { + + private final WfTemplateService svc = new WfTemplateService(null); // 解析不触 JdbcTemplate + + @Test + void parsesButtonsLoadScriptAndFormRefs() { + String xml = """ + + + + + + + + + """; + WfTemplateMeta m = svc.parseXml(xml); + + assertThat(m.buttons()).hasSize(3); + assertThat(m.buttons().get(0).id()).isEqualTo("a1"); // buttonId:action 端点据此重解析 servicename + assertThat(m.buttons().get(0).label()).isEqualTo("确认施工方案"); // 定制 label,不写死 + assertThat(m.buttons().get(0).type()).isEqualTo("approve"); + assertThat(m.buttons().get(0).servicename()).isEqualTo("DO_APPROVE"); + assertThat(m.buttons().get(1).type()).isEqualTo("reject"); + assertThat(m.buttons().get(1).servicename()).isNull(); // 空 servicename → null + assertThat(m.buttons().get(2).type()).isEqualTo("reback"); + assertThat(m.loadScript()).isEqualTo("TEST_LOAD"); + assertThat(m.showsend()).isFalse(); + assertThat(m.pageid()).isEqualTo("PAGE-1"); + assertThat(m.entityid()).isEqualTo("ENT-1"); + assertThat(m.hasButtons()).isTrue(); + } + + @Test + void showsendTrueAndNoLoad() { + String xml = """ +
+ + + + + """; + WfTemplateMeta m = svc.parseXml(xml); + assertThat(m.showsend()).isTrue(); + assertThat(m.loadScript()).isNull(); + assertThat(m.pageid()).isNull(); + assertThat(m.buttons()).hasSize(1); + } + + @Test + void badXmlDegradesToEmpty() { + WfTemplateMeta m = svc.parseXml("
not closed"); + assertThat(m.hasButtons()).isFalse(); + assertThat(m).isEqualTo(WfTemplateMeta.EMPTY); + } +}