TreeGrid 树模板渲染:运行时构树端点 + 左树右表联动(QA 剩余成规模代码缺口)

106 个 tree 模板此前转换成占位 input-tree + 不存在的 /api/template/{id}/tree|list 端点
(404/400),左树右表全不可用。本次打通:

后端 TemplateTreeController(新)— GET /api/template/{treetemplateRef}/tree:
- 解析树模板 XML(<node>+<nextnodes><levelnode entityid parentid>),按"全层级行装进单一
  id→节点映射、按各级 parentid 列值链父"的算法构嵌套树——支持自嵌套(PARENTID)与跨实体
  (如分类→事件 MEMORABILIASORTID)。display 取 isentitydisplay 列、value=原始主键(供右表过滤)、
  节点封顶 5000、标识符 IDENT 守卫。返 amis input-tree options。

转换器 convertTreeGrid:
- 左树 source=/api/template/{ref}/tree(运行时构树),onEvent.change→reload 右表。
- 右表改用合成搜索流 /api/flow/{gridTable}_SEARCH?{rcol}=${tree}(复用既有、按选中树节点过滤;
  原 /api/template/{id}/list 是不存在端点)。右表列取自 gridtemplate 引用模板的 <display>
  (loadRefDisplayColumns 跨模板只读 1 次,仅列定义)。
- 布局修正:flex/items 误用 → grid/columns({md,body} 是 grid 栅格格式,flex 会「找不到渲染器」)。

验证:converter 60 测过;运行时 /api/template/{大事记分类树}/tree 返 4 分类×事件子节点正确层级;
浏览器(查看大事记管理)左树渲染分类层级 + 右表列出,点叶子节点 onEvent 触发右表
reload 携 EVENTID=节点 UUID。重转后分级 SUCCESS 283→328(tree 模板升级)。已重导入 sys_page_schema。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-13 20:29:39 +08:00
parent d3986031d2
commit 433772015a
4 changed files with 371 additions and 59 deletions

View File

@@ -0,0 +1,242 @@
package com.eip4.platform.metadata.web;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* 树模板数据源端点(TreeGrid 左树)。转换器对 {@code <tree>} 的 treetemplate 引用产出
* {@code source=/api/template/{treetemplateRef}/tree}(见 TemplateToAmisConverter.convertTreeGrid),
* 本端点把该树模板渲染成 amis {@code input-tree} 的嵌套 options。
*
* <p><b>树模型(老引擎 view_template &lt;tree&gt;)</b>:{@code <node entityid>} 为根级,
* {@code <nextnodes><levelnode entityid parentid>} 声明各子级——<b>跨多实体、按各级 parentid 列链接</b>
* (如「大事记分类」自嵌套 PARENTID,其下「事件」按 MEMORABILIASORTID 挂到分类)。
*
* <p><b>构树算法</b>:把所有层级的行装进单一 {@code id→节点} 映射(id 归一化大写去空白),再按各行所在
* 层级的 parentid 列值找父节点(父在任意层级皆可,id 全局唯一)——父在则挂为 children,否则为根。
* 一次性 eager 构建(树/分类表通常小);节点总数封顶 {@code MAX_NODES},超限截断并 WARN。
* 每个节点 {@code value}=原始主键(供右表 {@code ?rcol=${tree}} 过滤),{@code label}=实体显示列。
*/
@RestController
public class TemplateTreeController {
private static final Logger log = LoggerFactory.getLogger(TemplateTreeController.class);
private static final Pattern IDENT = Pattern.compile("^[A-Za-z0-9_]+$");
private static final int MAX_NODES = 5000;
private static final String[] NAME_FALLBACKS = {"NAME", "SORT_NAME", "FULLNAME", "TITLE", "SUBJECT", "DISPLAYNAME"};
private final JdbcTemplate jdbcTemplate;
public TemplateTreeController(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/** 树层级:实体表 + 该级的 parentid 列(null=该级行为根)。 */
private record Level(String table, String parentCol) {}
/** 构树中间节点:opt 是即将返回的 amis option(含 children),parentRef 是归一化的父键。 */
private static final class Node {
final Map<String, Object> opt = new LinkedHashMap<>();
final List<Map<String, Object>> children = new ArrayList<>();
String parentRef;
}
@GetMapping("/api/template/{templateId}/tree")
public Map<String, Object> tree(@PathVariable String templateId) {
List<Map<String, Object>> options = new ArrayList<>();
try {
List<Level> levels = resolveLevels(templateId);
Map<String, Node> byId = new LinkedHashMap<>();
List<Node> order = new ArrayList<>();
for (Level lv : levels) {
if (order.size() >= MAX_NODES) {
log.warn("[TREE] {} 节点超 {} 截断", templateId, MAX_NODES);
break;
}
loadLevel(lv, byId, order);
}
for (Node n : order) {
Node parent = n.parentRef != null ? byId.get(n.parentRef) : null;
if (parent != null && parent != n) {
parent.children.add(n.opt);
} else {
options.add(n.opt);
}
}
} catch (DataAccessException ex) {
log.warn("[TREE] 构树失败 template={}: {}", templateId, ex.getMessage());
}
Map<String, Object> data = new LinkedHashMap<>();
data.put("options", options);
Map<String, Object> resp = new LinkedHashMap<>();
resp.put("status", 0);
resp.put("msg", "");
resp.put("data", data);
return resp;
}
/** 解析树模板 XML → 各层级(实体表 + parentid 列)。entityId→tablename;同实体取有 parentid 的声明(自嵌套)。 */
private List<Level> resolveLevels(String templateId) {
List<String> xmls = jdbcTemplate.queryForList(
"SELECT xml::text FROM eip3.view_template WHERE view_template_id = ? AND xml IS NOT NULL",
String.class, templateId);
if (xmls.isEmpty() || xmls.get(0) == null || xmls.get(0).isBlank()) {
return List.of();
}
// entityId → parentCol(后写覆盖:levelnode 的 parentid 优先于根节点的 null)
Map<String, String> entityParent = new LinkedHashMap<>();
try {
Document doc = DocumentHelper.parseText(xmls.get(0).trim());
Element root = doc.getRootElement();
Element node = root.element("node");
if (node != null) {
putEntity(entityParent, node.attributeValue("entityid"), node.attributeValue("parentid"));
Element nexts = node.element("nextnodes");
if (nexts != null) {
for (Element ln : nexts.elements("levelnode")) {
putEntity(entityParent, ln.attributeValue("entityid"), ln.attributeValue("parentid"));
}
}
}
} catch (Exception e) {
log.warn("[TREE] 解析树 XML 失败 template={}: {}", templateId, e.getMessage());
return List.of();
}
List<Level> levels = new ArrayList<>();
for (Map.Entry<String, String> e : entityParent.entrySet()) {
String table = tableOfEntity(e.getKey());
if (table != null && IDENT.matcher(table).matches()) {
levels.add(new Level(table, e.getValue()));
}
}
return levels;
}
private static void putEntity(Map<String, String> map, String entityId, String parentCol) {
if (entityId == null || entityId.isBlank()) {
return;
}
String pc = parentCol != null && !parentCol.isBlank() && IDENT.matcher(parentCol).matches()
? parentCol.toUpperCase() : null;
// 已有非空 parentCol 时不被 null 覆盖(保留自嵌套声明)
if (!map.containsKey(entityId) || (pc != null && map.get(entityId) == null)) {
map.put(entityId, pc);
}
}
private String tableOfEntity(String entityId) {
try {
List<String> t = jdbcTemplate.queryForList(
"SELECT tablename FROM eip3.sys_entity WHERE UPPER(sys_entity_id) = UPPER(?)",
String.class, entityId);
return t.isEmpty() ? null : (t.get(0) == null ? null : t.get(0).toUpperCase());
} catch (DataAccessException ex) {
return null;
}
}
/** 加载一个层级的行,装进 byId/order。key/display/parent 列均经 IDENT 守卫;display 解析失败回落主键。 */
private void loadLevel(Level lv, Map<String, Node> byId, List<Node> order) {
String table = lv.table();
String keyCol = table + "_ID";
String displayCol = displayColumn(table, keyCol);
if (!IDENT.matcher(keyCol).matches() || !IDENT.matcher(displayCol).matches()) {
return;
}
String parentCol = lv.parentCol();
StringBuilder sql = new StringBuilder("SELECT ").append(keyCol).append(" AS k, ")
.append(displayCol).append(" AS lbl");
if (parentCol != null) {
sql.append(", ").append(parentCol).append(" AS pref");
}
sql.append(" FROM eip3.").append(table);
try {
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql.toString());
for (Map<String, Object> r : rows) {
if (order.size() >= MAX_NODES) {
break;
}
Object rawKey = r.get("k");
if (rawKey == null) {
continue;
}
String idNorm = String.valueOf(rawKey).trim().toUpperCase();
Object lbl = r.get("lbl");
String label = lbl != null && !String.valueOf(lbl).isBlank()
? String.valueOf(lbl).trim() : String.valueOf(rawKey).trim();
Node n = new Node();
n.opt.put("label", label);
n.opt.put("value", String.valueOf(rawKey).trim()); // 原始主键(供右表过滤)
n.opt.put("children", n.children);
Object pref = parentCol != null ? r.get("pref") : null;
n.parentRef = pref != null && !String.valueOf(pref).isBlank()
? String.valueOf(pref).trim().toUpperCase() : null;
// 同 id 跨级去重(自嵌套时同实体只装一次)
if (!byId.containsKey(idNorm)) {
byId.put(idNorm, n);
order.add(n);
}
}
} catch (DataAccessException ex) {
log.warn("[TREE] 加载层级失败 table={}: {}", table, ex.getMessage());
}
}
/** 实体显示列:isentitydisplay=1 → 物理名称列回落 → 主键。守卫物理存在(防虚拟列)。 */
private String displayColumn(String table, String keyCol) {
Set<String> phys = physicalColumns(table);
String entityDisplay = null;
try {
List<String> cols = jdbcTemplate.queryForList(
"SELECT UPPER(ea.columnname) FROM eip3.sys_entityattribute ea "
+ "JOIN eip3.sys_entity e ON UPPER(e.sys_entity_id) = UPPER(ea.entityid) "
+ "WHERE UPPER(e.tablename) = ? AND ea.isentitydisplay = 1",
String.class, table);
if (!cols.isEmpty()) {
entityDisplay = cols.get(0);
}
} catch (DataAccessException ignore) {
// 回落
}
if (entityDisplay != null && physExists(phys, entityDisplay)) {
return entityDisplay;
}
for (String cand : NAME_FALLBACKS) {
if (physExists(phys, cand)) {
return cand;
}
}
return keyCol;
}
private Set<String> physicalColumns(String table) {
try {
return new LinkedHashSet<>(jdbcTemplate.queryForList(
"SELECT UPPER(column_name) FROM information_schema.columns "
+ "WHERE table_schema='eip3' AND UPPER(table_name)=?",
String.class, table));
} catch (DataAccessException ex) {
return Set.of();
}
}
private static boolean physExists(Set<String> phys, String colUpper) {
return phys.isEmpty() || phys.contains(colUpper);
}
}