feat(approval): WfTemplate 数据驱动审批界面 + ApprovalDrawer + load/action 保真层执行

审批按钮/业务表单由 WfTemplate(view_wftemplate) 数据驱动取代写死。flowable-service 加 ApprovalContextDto + FormKeyResolver/StartFormKeyResolver(form_key 历史回补:运行任务经 (procDefId,taskDefKey) 查 act_hi_taskinst 回补)。flow-gateway 加 ApprovalController(审批上下文聚合)+WfTemplateService(模板按 buttonId 解析 servicename)+BusinessRecordLoader(直调 flowExcuteService 加载业务记录,4s 超时守护防挂死→loadPOJO 退化);action 按 buttonId 重解析 servicename 全字段执行。FlowController/FlowableClient/GatewayRequests/TodoController 接审批上下文与 reject/reback。WfTemplateServiceTest 覆盖。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-16 14:08:32 +08:00
parent cd133aa11d
commit 33fda4541d
15 changed files with 1419 additions and 4 deletions

View File

@@ -25,6 +25,8 @@
<dependencies>
<!-- 业务摘要经引擎 loadPOJO 只读(SYS_DATASTATUS 映射 + 业务表标题字段);回写经 JdbcTemplate -->
<dependency><groupId>com.eip4</groupId><artifactId>platform-legacy-core</artifactId></dependency>
<!-- 审批业务表单引用列 id→名解析:复用全站统一的 UserColumnResolver(避免重复实现,口径一致) -->
<dependency><groupId>com.eip4</groupId><artifactId>platform-metadata</artifactId></dependency>
<!-- 待办聚合从 JWT 上下文取 userId / roles(候选组待办) -->
<dependency><groupId>com.eip4</groupId><artifactId>platform-auth</artifactId></dependency>

View File

@@ -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 服务流入参」统一来源。
*
* <p><b>为何要它(实测踩坑)</b>:老审批页用 WfTemplate 的 {@code <load>} 服务流载入单据(含引用列 id→名、
* 子表层级,比裸读实体更忠实)。但<b>部分 load 服务流会挂死</b>(实测 {@code PM_PUB_SAFETYRECTIFICATION_LOAD}
* 卡 30s+ 不返回,疑 groovy 死循环/坏子表)。若把它直接当表单数据源,审批页会一直转圈。
*
* <p><b>策略</b>:①优先跑 load 服务流,但用 {@value #LOAD_FLOW_TIMEOUT_MS}ms 超时硬上限(独立线程 +
* {@link Future#get(long, TimeUnit)})防挂死;②超时/异常/无 load → 退化为 {@code POJOCRUDService.loadPOJO}
* (可靠、待办聚合一直在用)。两者都把 {@link GeneralPOJO} 拍平成可 JSON 序列化的 Map。
*
* <p>用真实用户上下文取不到(超时线程非请求线程,{@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(对齐老审批页的「表单加载服务」)。
*
* <p>数据源优先级:①WfTemplate 节点显式 {@code <load>} 服务流(最贴该节点);②否则<b>表的标准表单加载服务
* {@code <TABLE>_LOAD}</b>(约定式,100/104 业务表都有——这才是老审批页真正调的「表单加载服务」,
* 含接收人/子表/引用,loadPOJO 取不到);③前两者失败/超时 → loadPOJO(层级) 兜底。均带 4s 超时守护防挂死。
*/
public Map<String, Object> load(String loadScript, String table, String businessKey) {
if (table == null || table.isBlank() || businessKey == null || businessKey.isBlank()) {
return new LinkedHashMap<>();
}
String t = table.trim();
// 显式 <load> 优先;空则退到约定式 <TABLE>_LOAD(即审批表单加载服务)
String effectiveLoad = (loadScript != null && !loadScript.isBlank())
? loadScript : t.toUpperCase() + "_LOAD";
Map<String, Object> viaFlow = tryLoadFlow(effectiveLoad, t, businessKey);
if (viaFlow != null && !viaFlow.isEmpty()) {
return viaFlow;
}
return loadViaPojo(t, businessKey);
}
/** 跑 load 服务流(超时硬上限)。成功返回拍平记录;无 load/超时/异常/空 → null(调用方退化 loadPOJO)。 */
private Map<String, Object> tryLoadFlow(String loadScript, String table, String businessKey) {
if (loadScript == null || loadScript.isBlank()) {
return null;
}
Future<Map<String, Object>> future = timeoutPool.submit(() -> {
Map<String, Object> in = new HashMap<>();
in.put(table.toUpperCase() + "_ID", businessKey); // load 流主键入参名约定 = <TABLE>_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<String, Object> 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<String, Object> 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<String, Object> 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<Object> 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<String, Object> castMap(Object o) {
return (Map<String, Object>) o;
}
}

View File

@@ -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 驱动审批界面的后端核心。
*
* <p><b>背景</b>:老系统整个审批界面由 {@code view_wftemplate}(1016 行已迁移)数据驱动——
* 按钮、页面加载脚本、业务表单视图全在模板 XML 里,随节点定制。新系统此前把这些全写死,
* 完全没用迁移过来的模板。本服务把模板读出来、解析成结构化元数据,交给 approval-meta 端点。
*
* <p><b>XML 结构</b>(实测):
* <pre>{@code
* <form entityid="…" pageid="…">
* <load><method servicename="…"/></load> <!-- 页面加载脚本(保真层服务流名) -->
* <toolbar showsend="false">
* <action id="…" label="同意" type="approve"><method servicename=""/></action>
* <action id="…" label="退回" type="reback"><method servicename=""/></action>
* </toolbar>
* <fields>…</fields> <!-- 业务表单视图(实测用到的 286 模板均空) -->
* </form>
* }</pre>
*
* <p><b>数据源</b>:注入应用主 {@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<Button> buttons, String loadScript, boolean showsend,
String pageid, String entityid) {
public static final WfTemplateMeta EMPTY = new WfTemplateMeta(List.of(), null, false, null, null);
public boolean hasButtons() {
return buttons != null && !buttons.isEmpty();
}
}
/**
* 按 formKey(= view_wftemplate_id)取并解析模板。无对应模板/解析失败 → {@link WfTemplateMeta#EMPTY}。
*/
public WfTemplateMeta parse(String formKey) {
if (formKey == null || formKey.isBlank()) {
return WfTemplateMeta.EMPTY;
}
String xml = readXml(formKey.trim());
if (xml == null || xml.isBlank()) {
return WfTemplateMeta.EMPTY;
}
return parseXml(xml);
}
/**
* 解析「生效表单模板」(对齐老 {@code TaskDetailPage.initPage}):任务节点模板有 pageid 则用它;
* 否则(裸节点,只配按钮无页面)<b>回退到开始节点模板</b>——其 pageid(展示页)+ {@code <load>}(加载服务)
* + 只读脚本才是真正的审批表单定义。两者都无 pageid → 仍返任务模板(页面走业务表 editform 兜底)。
*
* <p>只决定「表单」(pageid/loadScript/showsend)的来源;按钮仍以任务节点模板为准(保留节点定制 label)。
*/
public WfTemplateMeta effectiveFormMeta(WfTemplateMeta taskMeta, String startFormKey) {
if (taskMeta != null && taskMeta.pageid() != null) {
return taskMeta;
}
if (startFormKey != null && !startFormKey.isBlank()) {
WfTemplateMeta start = parse(startFormKey);
if (start.pageid() != null) {
return start;
}
}
return taskMeta != null ? taskMeta : WfTemplateMeta.EMPTY;
}
/** view_wftemplate_id → xml 文本(cast 防 PG xml 类型映射歧义)。无行/异常返回 null。 */
private String readXml(String id) {
try {
return jdbcTemplate.query(
"SELECT CAST(xml AS text) FROM view_wftemplate WHERE view_wftemplate_id = ?",
rs -> rs.next() ? rs.getString(1) : null, id);
} catch (RuntimeException e) {
log.debug("view_wftemplate 读取降级(id={}): {}", id, e.getMessage());
return null;
}
}
/** DOM 解析模板 XML(禁 DOCTYPE/外部实体,防 XXE)。public 供单测直接验证解析(纯函数)。 */
public WfTemplateMeta parseXml(String xml) {
try {
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
f.setFeature("http://xml.org/sax/features/external-general-entities", false);
f.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
f.setExpandEntityReferences(false);
DocumentBuilder b = f.newDocumentBuilder();
org.w3c.dom.Document doc = b.parse(new InputSource(new StringReader(xml)));
Element form = doc.getDocumentElement(); // <form ...>
String pageid = attr(form, "pageid");
String entityid = attr(form, "entityid");
// <toolbar showsend><action ...>
boolean showsend = false;
List<Button> buttons = new ArrayList<>();
Element toolbar = firstChildElement(form, "toolbar");
if (toolbar != null) {
showsend = "true".equalsIgnoreCase(attr(toolbar, "showsend"));
NodeList actions = toolbar.getElementsByTagName("action");
for (int i = 0; i < actions.getLength(); i++) {
Element a = (Element) actions.item(i);
String svc = null;
Element method = firstChildElement(a, "method");
if (method != null) {
svc = attr(method, "servicename");
}
buttons.add(new Button(attr(a, "id"), attr(a, "label"), attr(a, "type"),
(svc != null && !svc.isBlank()) ? svc : null));
}
}
// <load><method servicename>
String loadScript = null;
Element load = firstChildElement(form, "load");
if (load != null) {
Element method = firstChildElement(load, "method");
if (method != null) {
String svc = attr(method, "servicename");
loadScript = (svc != null && !svc.isBlank()) ? svc : null;
}
}
return new WfTemplateMeta(buttons, loadScript, showsend,
blankToNull(pageid), blankToNull(entityid));
} catch (Exception e) {
log.warn("WfTemplate XML 解析失败,降级默认按钮: {}", e.toString());
return WfTemplateMeta.EMPTY;
}
}
/**
* 业务表单模板 id 解析(<b>统一口径</b>,对齐全站「转换器 → sys_page_schema editform」解析)。
*
* <p>优先级:①WfTemplate 自带 pageid(最贴节点)命中 sys_page_schema → 用之;②否则回退该业务表的
* <b>标准编辑表单</b>(sys_entity→view_templateentity→view_template type=7 EDITFORM)且命中 sys_page_schema
* 的——即全站「查看完整单据」用的同一张表单。两者都没有 → null(前端极简降级)。
*
* <p>修掉的缺陷:此前只认 WfTemplate pageid(286 模板仅约 21% 命中),导致大量审批单退化成裸列名摘要;
* 改走统一 editform 后,绝大多数业务单据都渲染带中文标签的正经只读表单。
*/
public String resolveBusinessFormTemplateId(String pageid, String businessTable) {
if (pageid != null && existsInPageSchema(pageid)) {
return pageid;
}
if (businessTable == null || businessTable.isBlank()) {
return null;
}
try {
return jdbcTemplate.query(
"SELECT vte.templateid FROM sys_entity se "
+ "JOIN view_templateentity vte ON vte.entityid = se.sys_entity_id "
+ "JOIN view_template vt ON vt.view_template_id = vte.templateid "
+ "WHERE UPPER(se.tablename) = UPPER(?) AND vt.type = 7 "
+ "AND vte.templateid IN (SELECT template_id FROM sys_page_schema) "
+ "ORDER BY vte.templateid LIMIT 1",
rs -> rs.next() ? rs.getString(1) : null, businessTable.trim());
} catch (RuntimeException e) {
log.debug("业务表单 editform 解析降级(table={}): {}", businessTable, e.getMessage());
return null;
}
}
/**
* 业务表 → 友好中文名({@code sys_entity.name}),供审批界面显「业务单据(施工方案审批)」而非裸表名。
* 无对应实体名 → null(前端则只显「业务单据」)。
*/
public String entityDisplayName(String table) {
if (table == null || table.isBlank()) {
return null;
}
try {
return jdbcTemplate.query(
"SELECT name FROM sys_entity WHERE UPPER(tablename) = UPPER(?) AND name IS NOT NULL "
+ "ORDER BY (CASE WHEN isactive = 1 THEN 0 ELSE 1 END) LIMIT 1",
rs -> rs.next() ? rs.getString(1) : null, table.trim());
} catch (RuntimeException e) {
return null;
}
}
/**
* 该模板 id 是否在 sys_page_schema 有可渲染的 amis schema(决定业务表单能否用 WfTemplate pageid 渲染)。
*/
public boolean existsInPageSchema(String templateId) {
if (templateId == null || templateId.isBlank()) {
return false;
}
try {
Integer c = jdbcTemplate.queryForObject(
"SELECT count(*) FROM sys_page_schema WHERE template_id = ?", Integer.class, templateId.trim());
return c != null && c > 0;
} catch (RuntimeException e) {
return false;
}
}
// ---------------------------------------------------------------- DOM 小工具
private static String attr(Element e, String name) {
if (e == null) {
return null;
}
String v = e.getAttribute(name);
return v == null || v.isEmpty() ? null : v;
}
/** 取 parent 下第一个指定标签名的<b>直接</b>子元素(避免 getElementsByTagName 递归取到孙节点)。 */
private static Element firstChildElement(Element parent, String tag) {
NodeList children = parent.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node n = children.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE && tag.equals(n.getNodeName())) {
return (Element) n;
}
}
return null;
}
private static String blankToNull(String s) {
return s == null || s.isBlank() ? null : s;
}
}

View File

@@ -0,0 +1,22 @@
package com.eip4.platform.flowgateway.client;
/**
* flowable-service {@code GET /api/flow/tasks/{taskId}/approval-context} 的网关侧出参映射。
*
* <p>聚合返回 WfTemplate 驱动审批界面所需的引擎事实:formKey(= view_wftemplate_id,经引擎侧
* {@code FormKeyResolver} 历史回补)、businessKey、实例状态。字段贴 flowable-service 的同名 DTO。
*/
public class ApprovalContextDto {
public boolean found;
public String taskId;
public String taskName;
public String formKey;
/** 开始节点 formKey:任务节点是裸模板(无pageid)时回退到它(对齐老 getStartFormKey)。 */
public String startFormKey;
public String processInstanceId;
public String processDefinitionId;
public String taskDefinitionKey;
public String businessKey;
public boolean ended;
public boolean suspended;
}

View File

@@ -83,8 +83,52 @@ public class FlowableClient {
* @param variables 提交变量,可为 null
*/
public void complete(String taskId, Map<String, Object> variables) {
post("办理", "/api/flow/tasks/" + taskId + "/complete",
variables == null ? Map.of() : Map.of("variables", variables), Void.class);
complete(taskId, variables, null);
}
/**
* 办理(complete)任务,带审批意见。comment 非空时经引擎 addComment 记入流程评论(供轨迹)。
*/
public void complete(String taskId, Map<String, Object> variables, String comment) {
Map<String, Object> body = new java.util.LinkedHashMap<>();
if (variables != null) {
body.put("variables", variables);
}
if (comment != null && !comment.isBlank()) {
body.put("comment", comment);
}
post("办理", "/api/flow/tasks/" + taskId + "/complete", body, Void.class);
}
/**
* 任务审批上下文(formKey/businessKey/实例状态)。对应 flowable-service
* {@code GET /api/flow/tasks/{taskId}/approval-context}。任务不存在返回 found=false。
*/
public ApprovalContextDto approvalContext(String taskId) {
return execute("审批上下文", () -> restClient.get()
.uri("/api/flow/tasks/{id}/approval-context", taskId)
.retrieve()
.body(ApprovalContextDto.class));
}
/**
* 拒绝(终止流程)。对应 flowable-service {@code POST /api/flow/tasks/{taskId}/reject}。
* 返回体含 businessKey/processEnded,供 gateway 回写 SYS_DATASTATUS=4。
*/
@SuppressWarnings("unchecked")
public Map<String, Object> reject(String taskId, String comment) {
return post("拒绝", "/api/flow/tasks/" + taskId + "/reject",
comment == null ? Map.of() : Map.of("comment", comment), Map.class);
}
/**
* 退回(发起人/起始节点)。对应 flowable-service {@code POST /api/flow/tasks/{taskId}/reback}。
* 返回体含 businessKey,供 gateway 回写 SYS_DATASTATUS=5;流程结构不支持跳转时引擎 409 透传。
*/
@SuppressWarnings("unchecked")
public Map<String, Object> reback(String taskId, String comment) {
return post("退回", "/api/flow/tasks/" + taskId + "/reback",
comment == null ? Map.of() : Map.of("comment", comment), Map.class);
}
/** 发起流程(processDefinitionKey 或 processDefinitionId 二选一,可带 businessKey 与变量)。 */
@@ -103,6 +147,17 @@ public class FlowableClient {
.body(new ParameterizedTypeReference<List<TraceNodeDto>>() {}));
}
/**
* 按业务主键(=流程 businessKey)查最近一次流程实例的轨迹。
* 对应 flowable-service {@code GET /api/flow/process/business/{businessKey}/trace}。
*/
public List<TraceNodeDto> traceByBusiness(String businessKey) {
return execute("业务轨迹", () -> restClient.get()
.uri("/api/flow/process/business/{bk}/trace", businessKey)
.retrieve()
.body(new ParameterizedTypeReference<List<TraceNodeDto>>() {}));
}
/**
* 委托(delegate)任务给指定用户。
* 对应 flowable-service {@code POST /api/flow/tasks/{taskId}/delegate}。

View File

@@ -0,0 +1,398 @@
package com.eip4.platform.flowgateway.web;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.dsasp.server.common.core.service.FlowExcuteService;
import com.dsasp.server.common.util.UserSession;
import com.dsasp.server.common.workflow.service.ProcessCoreService;
import com.eip4.platform.flowgateway.aggregate.BusinessRecordLoader;
import com.eip4.platform.flowgateway.aggregate.BusinessSummaryService;
import com.eip4.platform.flowgateway.aggregate.WfTemplateService;
import com.eip4.platform.flowgateway.aggregate.WfTemplateService.WfTemplateMeta;
import com.eip4.platform.flowgateway.client.ApprovalContextDto;
import com.eip4.platform.flowgateway.client.FlowableClient;
import com.eip4.platform.flowgateway.client.ProcessInstanceDto;
import com.eip4.platform.flowgateway.writeback.StatusWriteback;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
/**
* WfTemplate 驱动审批门面:把老系统数据驱动的审批界面在新架构还原。
*
* <p><b>解决的根因</b>:新待办/审批界面此前把按钮、脚本、业务表单全写死/丢弃,完全没用迁移过来的
* 1016 个 {@code view_wftemplate}。本控制器提供两个端点把审批界面交还给模板数据:
* <ul>
* <li>{@code GET /api/task/{taskId}/approval-meta} —— 按任务 formKey 解析 WfTemplate,返回
* 动态按钮 + 加载脚本 + 业务表单模板 id;formKey 经引擎侧 {@code FormKeyResolver} 历史回补
* (运行库 form_key 几乎全空,靠 (procDefId,taskDefKey) 回查历史,实测可补 99.98%)。</li>
* <li>{@code POST /api/task/{taskId}/action} —— 按按钮 type 分派引擎操作并回写业务状态
* (approve→3/2、reject→4 终止、reback→5 退回、agent→委托)。</li>
* </ul>
*
* <p>无 formKey / 无模板 / 引擎降级时回退默认按钮(同意 approve / 驳回 reject),不让审批不可用。
* 与已有 {@code TodoController}(complete/delegate/trace)并存,本控制器是其 WfTemplate 数据驱动升级。
*/
@Tag(name = "WfTemplate 驱动审批", description = "动态审批按钮/脚本/业务表单 + 按 type 分派引擎动作")
@RestController
public class ApprovalController {
/** 无模板时的默认按钮(同意/驳回),保审批始终可办理。 */
private static final List<Map<String, Object>> DEFAULT_BUTTONS = List.of(
buttonMap("_approve", "同意", "approve", null),
buttonMap("_reject", "驳回", "reject", null));
private static final Logger log = LoggerFactory.getLogger(ApprovalController.class);
private final FlowableClient flowableClient;
private final WfTemplateService wfTemplateService;
private final BusinessSummaryService businessSummaryService;
private final StatusWriteback statusWriteback;
/** 保真层服务流引擎:WfTemplate action 自定义 servicename 的执行入口(对齐老 TaskProcessService)。 */
private final FlowExcuteService flowExcuteService;
/** 业务记录载入器:表单数据 + action 服务流入参的统一来源(load 流超时守护 → loadPOJO 退化)。 */
private final BusinessRecordLoader businessRecordLoader;
/** 引用列 id→名解析器(全站统一):业务表单数据载入后补 {@code <COL>_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<Map<String, Object>> 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<String, Object> 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 来自生效表单模板(裸节点取开始节点的 <load>)
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 的 <load> 服务流(含引用列 id→名、子表,"
+ "对齐老审批页),4s 超时硬上限防挂死,超时/异常退化 loadPOJO。返回 amis 单记录契约 {status:0,data:{...record}}。")
@GetMapping("/api/task/{taskId}/business-data")
public ResponseEntity<Map<String, Object>> businessData(@PathVariable String taskId) {
ApprovalContextDto ctx = flowableClient.approvalContext(taskId);
Map<String, Object> 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);
}
// 生效表单模板的 <load>(裸节点取开始节点配置的加载服务,对齐老审批页)
WfTemplateMeta formMeta = wfTemplateService.effectiveFormMeta(
wfTemplateService.parse(ctx.formKey), ctx.startFormKey);
String table = businessSummaryService.summarize(ctx.businessKey).tableName();
Map<String, Object> record = businessRecordLoader.load(formMeta.loadScript(), table, ctx.businessKey);
// 引用列 id→名(全站统一口径):主表 + 子表行补 <COL>_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<String, Object> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<String, Object> svcMap = new HashMap<>(businessRecordLoader.load(formMeta.loadScript(), table, businessKey));
if (table != null && businessKey != null) {
svcMap.put(table.toUpperCase() + "_ID", businessKey); // 主键入参名约定 = <TABLE>_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<String, Object> 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<Map<String, Object>> approve(String taskId, GatewayRequests.ApprovalActionRequest req) {
Map<String, Object> 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<String, Object> 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<Map<String, Object>> reject(String taskId, GatewayRequests.ApprovalActionRequest req) {
Map<String, Object> 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<String, Object> 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<Map<String, Object>> reback(String taskId, GatewayRequests.ApprovalActionRequest req) {
Map<String, Object> 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<String, Object> 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<Map<String, Object>> agent(String taskId, GatewayRequests.ApprovalActionRequest req) {
if (req.targetUserId == null || req.targetUserId.isBlank()) {
return badRequest("转办需指定 targetUserId");
}
flowableClient.delegate(taskId, req.targetUserId.trim());
Map<String, Object> 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<Map<String, Object>> buttonsToMaps(WfTemplateMeta meta) {
List<Map<String, Object>> 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<String, Object> buttonMap(String id, String label, String type, String servicename) {
Map<String, Object> m = new LinkedHashMap<>();
m.put("id", id);
m.put("label", label);
m.put("type", type);
m.put("servicename", servicename);
return m;
}
private static Map<String, Object> ok(String action) {
Map<String, Object> r = new LinkedHashMap<>();
r.put("action", action);
return r;
}
private static ResponseEntity<Map<String, Object>> badRequest(String msg) {
Map<String, Object> r = new LinkedHashMap<>();
r.put("status", 1);
r.put("msg", msg);
return ResponseEntity.badRequest().body(r);
}
private static String strOf(Map<String, Object> 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) ? "协办" : "转阅";
}
}

View File

@@ -35,4 +35,23 @@ public final class GatewayRequests {
public static class DelegateRequest {
public String delegateUserId;
}
/**
* WfTemplate 驱动审批的统一动作请求({@code POST /api/task/{id}/action})。
*
* <p>{@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;
}
}

View File

@@ -115,6 +115,14 @@ public class TodoController {
return ResponseEntity.ok(nodes);
}
@Operation(summary = "按业务主键查流程轨迹",
description = "列表行只有业务主键(=流程 businessKey),按 businessKey 反查最近一次历史流程实例的审批轨迹(供列表「查看审批」按钮);无对应流程返回空列表")
@GetMapping("/api/flow/business/{businessKey}/trace")
public ResponseEntity<List<TraceNodeDto>> traceByBusiness(@PathVariable String businessKey) {
List<TraceNodeDto> nodes = flowableClient.traceByBusiness(businessKey);
return ResponseEntity.ok(nodes);
}
@Operation(summary = "委托任务", description = "将任务委托给指定用户(delegateUserId),assignee 变受托人,owner 记原办理人")
@PostMapping("/api/task/{id}/delegate")
public ResponseEntity<Map<String, Object>> delegate(@PathVariable String id,

View File

@@ -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 = """
<form entityid="ENT-1" pageid="PAGE-1">
<load><method servicename="TEST_LOAD"/></load>
<toolbar showsend="false">
<action id="a1" label="确认施工方案" type="approve"><method servicename="DO_APPROVE"/></action>
<action id="a2" label="拒绝" type="reject"><method servicename=""/></action>
<action id="a3" label="退回" type="reback"><method servicename=""/></action>
</toolbar>
</form>
""";
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 = """
<form>
<toolbar showsend="true">
<action id="a1" label="同意" type="approve"><method servicename=""/></action>
</toolbar>
</form>
""";
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("<form><toolbar> not closed");
assertThat(m.hasButtons()).isFalse();
assertThat(m).isEqualTo(WfTemplateMeta.EMPTY);
}
}