feat: add AI tree CRUD recipe

This commit is contained in:
2026-06-17 13:03:38 +08:00
parent 2b0b673ce9
commit 718c5a5b9b
17 changed files with 675 additions and 46 deletions

View File

@@ -25,6 +25,7 @@ public record PageBlueprint(
public static final int VERSION = 1;
public static final String RECIPE_MAINTENANCE_CRUD = "maintenance-crud-v1";
public static final String RECIPE_TREE_CRUD = "tree-crud-v1";
public PageBlueprint {
fields = fields == null ? List.of() : List.copyOf(fields);

View File

@@ -22,6 +22,9 @@ public final class PageBlueprintCompiler {
if (PageBlueprint.RECIPE_MAINTENANCE_CRUD.equals(blueprint.recipe())) {
return maintenanceCrud(blueprint);
}
if (PageBlueprint.RECIPE_TREE_CRUD.equals(blueprint.recipe())) {
return treeCrud(blueprint);
}
throw new IllegalArgumentException("Unsupported page recipe: " + blueprint.recipe());
}
@@ -29,8 +32,7 @@ public final class PageBlueprintCompiler {
ObjectNode page = objectMapper.createObjectNode();
page.put("type", "page");
page.put("title", blueprint.title());
ArrayNode body = page.putArray("body");
ObjectNode crud = body.addObject();
ObjectNode crud = page.putObject("body");
String crudName = lowerCamel(blueprint.tableName()) + "Crud";
crud.put("type", "crud");
crud.put("name", crudName);
@@ -65,6 +67,46 @@ public final class PageBlueprintCompiler {
return page;
}
private ObjectNode treeCrud(PageBlueprint blueprint) {
ObjectNode page = objectMapper.createObjectNode();
page.put("type", "page");
page.put("title", blueprint.title());
ObjectNode crud = page.putObject("body");
String crudName = lowerCamel(blueprint.tableName()) + "TreeCrud";
crud.put("type", "crud");
crud.put("name", crudName);
crud.put("syncLocation", false);
crud.put("childrenColumnName", "children");
ObjectNode api = crud.putObject("api");
api.put("method", "get");
api.put("url", "/api/entity/" + blueprint.tableName()
+ "/tree?parentKey=PARENTID&idKey=" + blueprint.primaryKey() + "&perPage=2000");
api.put("adaptor", "return payload;");
ArrayNode headerToolbar = crud.putArray("headerToolbar");
if (blueprint.allowCreate()) {
ObjectNode addButton = headerToolbar.addObject();
addButton.put("type", "button");
addButton.put("label", "新增顶级" + blueprint.entityName());
addButton.put("level", "primary");
addButton.put("icon", "fa fa-plus");
addButton.put("actionType", "dialog");
ObjectNode addDialog = addButton.putObject("dialog");
addDialog.put("title", "新增顶级" + blueprint.entityName());
ObjectNode addForm = addDialog.putObject("body");
addForm.put("type", "form");
addForm.put("api", "post:/api/entity/" + blueprint.tableName() + "/save");
addForm.put("reload", crudName);
ArrayNode controls = formControlsExcluding(blueprint, false, "PARENTID");
controls.add(hidden("PARENTID", ""));
addForm.set("body", controls);
}
headerToolbar.add(reloadButton(crudName));
crud.putArray("footerToolbar");
crud.set("columns", treeColumns(blueprint, crudName));
return page;
}
private ArrayNode columns(PageBlueprint blueprint, String crudName) {
ArrayNode columns = objectMapper.createArrayNode();
for (PageBlueprintField field : blueprint.fields()) {
@@ -92,6 +134,69 @@ public final class PageBlueprintCompiler {
return columns;
}
private ArrayNode treeColumns(PageBlueprint blueprint, String crudName) {
ArrayNode columns = objectMapper.createArrayNode();
for (PageBlueprintField field : blueprint.fields()) {
if (!field.listVisible() || "PARENTID".equals(field.name())) {
continue;
}
ObjectNode column = columns.addObject();
column.put("name", field.name());
column.put("label", field.label());
}
ObjectNode op = columns.addObject();
op.put("type", "operation");
op.put("label", "操作");
op.put("width", 240);
ArrayNode buttons = op.putArray("buttons");
if (blueprint.allowCreate()) {
addChildAction(blueprint, buttons, crudName);
}
if (blueprint.allowEdit()) {
addTreeEditAction(blueprint, buttons, crudName);
}
if (blueprint.allowDelete()) {
addDeleteAction(blueprint, buttons, crudName);
}
return columns;
}
private void addChildAction(PageBlueprint blueprint, ArrayNode buttons, String crudName) {
ObjectNode addChild = buttons.addObject();
addChild.put("type", "button");
addChild.put("label", "加子" + blueprint.entityName());
addChild.put("level", "link");
addChild.put("actionType", "dialog");
ObjectNode dialog = addChild.putObject("dialog");
dialog.put("title", "在${" + blueprint.displayField() + "}下新增" + blueprint.entityName());
ObjectNode form = dialog.putObject("body");
form.put("type", "form");
form.put("api", "post:/api/entity/" + blueprint.tableName() + "/save");
form.put("reload", crudName);
ArrayNode controls = objectMapper.createArrayNode();
controls.add(hidden("PARENTID", "${" + blueprint.primaryKey() + "}"));
controls.addAll(formControlsExcluding(blueprint, false, "PARENTID"));
form.set("body", controls);
}
private void addTreeEditAction(PageBlueprint blueprint, ArrayNode buttons, String crudName) {
ObjectNode edit = buttons.addObject();
edit.put("type", "button");
edit.put("label", "编辑");
edit.put("level", "link");
edit.put("actionType", "dialog");
ObjectNode editDialog = edit.putObject("dialog");
editDialog.put("title", "编辑${" + blueprint.displayField() + "}");
ObjectNode editForm = editDialog.putObject("body");
editForm.put("type", "form");
editForm.put("api", "post:/api/entity/" + blueprint.tableName() + "/save");
editForm.put("reload", crudName);
ArrayNode editControls = formControlsExcluding(blueprint, true, "PARENTID");
editControls.add(hidden("PARENTID", "${PARENTID}"));
editControls.add(hidden(blueprint.primaryKey(), "${" + blueprint.primaryKey() + "}"));
editForm.set("body", editControls);
}
private void addEditAction(PageBlueprint blueprint, ArrayNode buttons) {
ObjectNode edit = buttons.addObject();
edit.put("type", "button");
@@ -129,9 +234,13 @@ public final class PageBlueprintCompiler {
}
private ArrayNode formControls(PageBlueprint blueprint, boolean bindCurrentRow) {
return formControlsExcluding(blueprint, bindCurrentRow);
}
private ArrayNode formControlsExcluding(PageBlueprint blueprint, boolean bindCurrentRow, String... excludedFields) {
ArrayNode controls = objectMapper.createArrayNode();
for (PageBlueprintField field : blueprint.fields()) {
if (!field.formVisible()) {
if (!field.formVisible() || isExcluded(field.name(), excludedFields)) {
continue;
}
ObjectNode c = controls.addObject();
@@ -148,6 +257,25 @@ public final class PageBlueprintCompiler {
return controls;
}
private ObjectNode hidden(String name, String value) {
ObjectNode hidden = objectMapper.createObjectNode();
hidden.put("type", "hidden");
hidden.put("name", name);
hidden.put("value", value);
return hidden;
}
private ObjectNode reloadButton(String target) {
ObjectNode button = objectMapper.createObjectNode();
button.put("type", "button");
button.put("label", "刷新");
button.put("level", "link");
button.put("icon", "fa fa-refresh");
button.put("actionType", "reload");
button.put("target", target);
return button;
}
private void validate(PageBlueprint blueprint) {
if (blueprint == null) {
throw new IllegalArgumentException("Page blueprint is required");
@@ -155,7 +283,8 @@ public final class PageBlueprintCompiler {
if (blueprint.schemaVersion() != PageBlueprint.VERSION) {
throw new IllegalArgumentException("Unsupported page blueprint version: " + blueprint.schemaVersion());
}
if (!PageBlueprint.RECIPE_MAINTENANCE_CRUD.equals(blueprint.recipe())) {
if (!PageBlueprint.RECIPE_MAINTENANCE_CRUD.equals(blueprint.recipe())
&& !PageBlueprint.RECIPE_TREE_CRUD.equals(blueprint.recipe())) {
throw new IllegalArgumentException("Unsupported page recipe: " + blueprint.recipe());
}
required(blueprint.templateId(), "templateId");
@@ -179,6 +308,10 @@ public final class PageBlueprintCompiler {
if (!displayFieldExists) {
throw new IllegalArgumentException("displayField must match one blueprint field");
}
if (PageBlueprint.RECIPE_TREE_CRUD.equals(blueprint.recipe())
&& blueprint.fields().stream().noneMatch(field -> "PARENTID".equals(field.name()))) {
throw new IllegalArgumentException("tree-crud-v1 requires PARENTID field");
}
if (blueprint.pageSize() < 1 || blueprint.pageSize() > 200) {
throw new IllegalArgumentException("pageSize must be between 1 and 200");
}
@@ -200,6 +333,15 @@ public final class PageBlueprintCompiler {
};
}
private static boolean isExcluded(String fieldName, String... excludedFields) {
for (String excluded : excludedFields) {
if (excluded.equals(fieldName)) {
return true;
}
}
return false;
}
private static String lowerCamel(String table) {
String[] parts = table.toLowerCase(Locale.ROOT).split("_+");
StringBuilder sb = new StringBuilder(parts[0]);

View File

@@ -24,7 +24,7 @@ public final class PageRecipeRegistry {
}
public static PageRecipeRegistry defaults() {
return new PageRecipeRegistry(List.of(maintenanceCrud()));
return new PageRecipeRegistry(List.of(maintenanceCrud(), treeCrud()));
}
public Optional<PageRecipeDefinition> find(String recipe) {
@@ -49,6 +49,7 @@ public final class PageRecipeRegistry {
}
return switch (blueprint.recipe()) {
case PageBlueprint.RECIPE_MAINTENANCE_CRUD -> new PageBlueprintCompiler(objectMapper).compile(blueprint);
case PageBlueprint.RECIPE_TREE_CRUD -> new PageBlueprintCompiler(objectMapper).compile(blueprint);
default -> throw new IllegalArgumentException("Unsupported page recipe: " + blueprint.recipe());
};
}
@@ -67,4 +68,19 @@ public final class PageRecipeRegistry {
"boolean", "switch"),
List.of("page-recipe", "typed-page-schema", "amis-schema", "local-smoke", "playwright-render"));
}
private static PageRecipeDefinition treeCrud() {
return new PageRecipeDefinition(
PageBlueprint.RECIPE_TREE_CRUD,
PageBlueprint.VERSION,
"EIP4 tree CRUD page",
Map.of(
"string", "input-text",
"integer", "input-number",
"number", "input-number",
"date", "input-date",
"datetime", "input-datetime",
"boolean", "switch"),
List.of("page-recipe", "typed-page-schema", "amis-schema", "local-smoke", "playwright-render"));
}
}

View File

@@ -108,6 +108,51 @@ public class EntityController {
return resp;
}
/**
* 树形查询:GET /api/entity/{table}/tree?parentKey=PARENTID&idKey={TABLE}_ID。
*
* <p>用于 AI page recipe `tree-crud-v1` 和通用树表页面。端点仍走实体白名单和引擎查询,
* 只在现代层把平面结果组装为 amis tree/crud 可消费的 {@code children} 层级。
*/
@GetMapping("/{table}/tree")
public Map<String, Object> tree(@PathVariable String table,
@RequestParam(defaultValue = "PARENTID") String parentKey,
@RequestParam(required = false) String idKey,
@RequestParam(defaultValue = "2000") int perPage,
@RequestParam(required = false) String asUser,
@RequestParam(required = false) String roles,
@RequestParam(required = false) String asDepart,
@RequestParam(required = false) String asOrg,
@RequestParam(required = false) String orderBy,
@RequestParam(required = false) String orderDir) {
String t = table.toUpperCase();
identifierWhitelist.requireLegalTable(t);
String idCol = idKey == null || idKey.isBlank() ? t + "_ID" : idKey.toUpperCase();
String parentCol = parentKey == null || parentKey.isBlank() ? "PARENTID" : parentKey.toUpperCase();
identifierWhitelist.requireLegalColumn(t, idCol, "树主键列");
identifierWhitelist.requireLegalColumn(t, parentCol, "树父级列");
Properties ctx = buildCtx(asUser, roles, asDepart, asOrg);
Map<String, Object> cond = new HashMap<>();
cond.put(POJOCRUDService.PAGE_START, 0);
cond.put(POJOCRUDService.PAGE_SIZE, Math.max(1, Math.min(perPage, 10000)));
applyOrder(cond, t, orderBy, orderDir);
Map<String, Object> result = pojoCRUDService.listSelect(cond, t, ctx);
List<Map<String, Object>> flat = toRows(result.get(POJOCRUDService.LIST_RESULT));
List<Map<String, Object>> roots = buildTree(flat, idCol, parentCol);
Map<String, Object> data = new HashMap<>();
data.put("items", roots);
data.put("total", flat.size());
Map<String, Object> resp = new HashMap<>();
resp.put("status", 0);
resp.put("msg", "");
resp.put("data", data);
return resp;
}
/**
* 单条加载:GET /api/entity/{table}/{id}[?pageId=]
*
@@ -231,6 +276,49 @@ public class EntityController {
return row;
}
@SuppressWarnings("unchecked")
private static List<Map<String, Object>> buildTree(List<Map<String, Object>> flat, String idKey, String parentKey) {
Map<String, Map<String, Object>> byId = new LinkedHashMap<>();
for (Map<String, Object> row : flat) {
String id = text(rowValue(row, idKey));
if (id.isBlank()) {
id = text(row.get("_id"));
}
if (!id.isBlank()) {
byId.put(id, row);
}
}
List<Map<String, Object>> roots = new ArrayList<>();
for (Map<String, Object> row : flat) {
String parentId = text(rowValue(row, parentKey));
Map<String, Object> parent = parentId.isBlank() ? null : byId.get(parentId);
if (parent == null || parent == row) {
roots.add(row);
continue;
}
List<Map<String, Object>> children = (List<Map<String, Object>>) parent.computeIfAbsent(
"children", ignored -> new ArrayList<Map<String, Object>>());
children.add(row);
}
return roots;
}
private static Object rowValue(Map<String, Object> row, String key) {
if (row.containsKey(key)) {
return row.get(key);
}
for (Map.Entry<String, Object> entry : row.entrySet()) {
if (key.equalsIgnoreCase(entry.getKey())) {
return entry.getValue();
}
}
return null;
}
private static String text(Object value) {
return value == null ? "" : String.valueOf(value).trim();
}
/**
* 去 CHAR 列尾部补白:DB CHAR(n) 主键/引用值带尾空格(如 {@code "MESSAGE "}),而
* picker 选项 {@code _id}(PickerController 已 .trim())与表单提交值均为无补白形态。表单加载

View File

@@ -39,7 +39,7 @@ class PageBlueprintCompilerTest {
assertEquals("page", schema.path("type").asText());
assertEquals("合同类型维护", schema.path("title").asText());
ObjectNode crud = (ObjectNode) schema.path("body").get(0);
ObjectNode crud = (ObjectNode) schema.path("body");
assertEquals("crud", crud.path("type").asText());
assertEquals("eip4aiContractTypeCrud", crud.path("name").asText());
assertEquals("/api/entity/EIP4AI_CONTRACT_TYPE/list?page=${page}&perPage=${perPage}",
@@ -55,6 +55,46 @@ class PageBlueprintCompilerTest {
.path("className").asText());
}
@Test
@DisplayName("tree-crud-v1 编译为 EIP4 标准 amis 树表维护页")
void compilesTreeCrudRecipe() {
PageBlueprint blueprint = new PageBlueprint(
PageBlueprint.VERSION,
PageBlueprint.RECIPE_TREE_CRUD,
"eip4ai-category",
"分类维护",
"EIP4AI_CATEGORY",
"分类",
"EIP4AI_CATEGORY_ID",
"NAME",
List.of(
new PageBlueprintField("NAME", "名称", "string", true, true, true),
new PageBlueprintField("PARENTID", "上级", "string", false, false, true),
new PageBlueprintField("SEQ", "排序", "integer", false, true, true)),
true,
true,
true,
20);
ObjectNode schema = new PageBlueprintCompiler(MAPPER).compile(blueprint);
ObjectNode crud = (ObjectNode) schema.path("body");
assertEquals("crud", crud.path("type").asText());
assertEquals("eip4aiCategoryTreeCrud", crud.path("name").asText());
assertEquals("children", crud.path("childrenColumnName").asText());
assertEquals("/api/entity/EIP4AI_CATEGORY/tree?parentKey=PARENTID&idKey=EIP4AI_CATEGORY_ID&perPage=2000",
crud.path("api").path("url").asText());
assertEquals("新增顶级分类", crud.path("headerToolbar").get(0).path("label").asText());
assertEquals("reload", crud.path("headerToolbar").get(1).path("actionType").asText());
assertEquals("eip4aiCategoryTreeCrud", crud.path("headerToolbar").get(1).path("target").asText());
assertEquals("操作", crud.path("columns").get(2).path("label").asText());
assertEquals("加子分类", crud.path("columns").get(2).path("buttons").get(0).path("label").asText());
assertEquals("PARENTID", crud.path("columns").get(2).path("buttons").get(0)
.path("dialog").path("body").path("body").get(0).path("name").asText());
assertEquals("text-danger", crud.path("columns").get(2).path("buttons").get(2)
.path("className").asText());
}
@Test
@DisplayName("不支持的 recipe 会被拒绝")
void rejectsUnsupportedRecipe() {
@@ -75,4 +115,25 @@ class PageBlueprintCompilerTest {
assertThrows(IllegalArgumentException.class, () -> new PageBlueprintCompiler(MAPPER).compile(blueprint));
}
@Test
@DisplayName("tree-crud-v1 必须声明 PARENTID 字段")
void rejectsTreeCrudWithoutParentField() {
PageBlueprint blueprint = new PageBlueprint(
PageBlueprint.VERSION,
PageBlueprint.RECIPE_TREE_CRUD,
"tpl",
"标题",
"EIP4AI_T",
"实体",
"EIP4AI_T_ID",
"NAME",
List.of(new PageBlueprintField("NAME", "名称", "string", true, true, true)),
true,
true,
true,
20);
assertThrows(IllegalArgumentException.class, () -> new PageBlueprintCompiler(MAPPER).compile(blueprint));
}
}

View File

@@ -40,6 +40,17 @@ class PageRecipeValidatorTest {
assertTrue(report.messages().get(0).contains("$.title"));
}
@Test
@DisplayName("page recipe 校验接受 tree-crud-v1 输出")
void acceptsTreeCrudRecipeOutput() {
PageBlueprint blueprint = treeBlueprint();
ObjectNode schema = new PageBlueprintCompiler(MAPPER).compile(blueprint);
PageRecipeValidationReport report = validator.validate(blueprint, schema);
assertTrue(report.valid());
}
private static PageBlueprint blueprint() {
return new PageBlueprint(
PageBlueprint.VERSION,
@@ -58,4 +69,23 @@ class PageRecipeValidatorTest {
true,
20);
}
private static PageBlueprint treeBlueprint() {
return new PageBlueprint(
PageBlueprint.VERSION,
PageBlueprint.RECIPE_TREE_CRUD,
"eip4ai-category",
"分类维护",
"EIP4AI_CATEGORY",
"分类",
"EIP4AI_CATEGORY_ID",
"NAME",
List.of(
new PageBlueprintField("NAME", "名称", "string", true, true, true),
new PageBlueprintField("PARENTID", "上级", "string", false, false, true)),
true,
true,
true,
20);
}
}

View File

@@ -104,6 +104,36 @@ class EntityControllerWhitelistTest {
verify(wl).requireLegalColumn(eq(TABLE), eq("ORDERNO"), eq("排序列"));
}
@Test
@SuppressWarnings("unchecked")
void tree查询组装children并校验树列() {
IdentifierWhitelist wl = mock(IdentifierWhitelist.class);
POJOCRUDService engine = mock(POJOCRUDService.class);
Map<String, Object> engineResult = new HashMap<>();
engineResult.put(POJOCRUDService.LIST_RESULT, List.of(
treeRow("root-1", "", "根节点"),
treeRow("child-1", "root-1", "子节点")));
engineResult.put(POJOCRUDService.PAGE_COUNT, 2L);
when(engine.listSelect(any(), eq(TABLE), any(Properties.class))).thenReturn(engineResult);
EntityController c = new EntityController(engine, wl,
mock(org.springframework.jdbc.core.JdbcTemplate.class), mock(PickerController.class));
Map<String, Object> resp = c.tree(TABLE, "PARENTID", "EIP4PT_ORDER_ID",
2000, null, null, null, null, null, null);
assertEquals(0, resp.get("status"));
Map<String, Object> data = (Map<String, Object>) resp.get("data");
List<Map<String, Object>> roots = (List<Map<String, Object>>) data.get("items");
assertEquals(1, roots.size());
assertEquals("根节点", roots.get(0).get("NAME"));
List<Map<String, Object>> children = (List<Map<String, Object>>) roots.get(0).get("children");
assertEquals(1, children.size());
assertEquals("子节点", children.get(0).get("NAME"));
verify(wl).requireLegalTable(TABLE);
verify(wl).requireLegalColumn(TABLE, "EIP4PT_ORDER_ID", "树主键列");
verify(wl).requireLegalColumn(TABLE, "PARENTID", "树父级列");
}
@Test
@SuppressWarnings("unchecked")
void 保留键不过白名单只放行() {
@@ -145,6 +175,19 @@ class EntityControllerWhitelistTest {
return p;
}
private static GeneralPOJO treeRow(String id, String parentId, String name) {
GeneralPOJO p = mock(GeneralPOJO.class);
when(p.get_ID()).thenReturn(id);
when(p.get_ColumnCount()).thenReturn(3);
when(p.get_ColumnName(0)).thenReturn("EIP4PT_ORDER_ID");
when(p.get_Value(0)).thenReturn(id);
when(p.get_ColumnName(1)).thenReturn("PARENTID");
when(p.get_Value(1)).thenReturn(parentId);
when(p.get_ColumnName(2)).thenReturn("NAME");
when(p.get_Value(2)).thenReturn(name);
return p;
}
@Test
@SuppressWarnings("unchecked")
void load带pageId_SelectDialog字段返对象() {