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

@@ -51,10 +51,31 @@ java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar ai auto-develop \
--field NAME:名称:string:100:true \
--field CODE:编码:string:64:true \
--field ENABLED:启用:boolean::false \
--page-recipe maintenance-crud-v1 \
--max-repair-attempts 2 \
--output target/ai-runs/customer-level.json
```
树形维护页使用 `tree-crud-v1`。如果字段列表没有显式提供 `PARENTID`,生成器会自动补一个父级字段,
页面使用 `/api/entity/{table}/tree?parentKey=PARENTID&idKey={table}_ID&perPage=2000`
作为树数据接口,并把 `PARENTID` 从树列表列中隐藏:
```bash
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar ai auto-develop \
--base-url http://localhost:8093 \
--objective "新增组织分类树形维护功能" \
--feature-name "组织分类维护" \
--table-name EIP4AI_ORG_CATEGORY \
--entity-name "组织分类" \
--template-id eip4ai-org-category \
--menu-name "组织分类维护" \
--field NAME:名称:string:100:true \
--field CODE:编码:string:64:true \
--page-recipe tree-crud-v1 \
--max-repair-attempts 2 \
--output target/ai-runs/org-category-tree.json
```
本地门禁通过后,可以把最终变更包封装成功能包快照,并保存一个里程碑 revision:
```bash
@@ -88,6 +109,7 @@ curl -X POST http://localhost:8093/api/ai/features/auto-develop \
"entityName": "客户等级",
"templateId": "eip4ai-customer-level",
"menuName": "客户等级维护",
"pageRecipe": "maintenance-crud-v1",
"fields": [
{"column": "NAME", "label": "名称", "type": "string", "length": 100, "required": true},
{"column": "CODE", "label": "编码", "type": "string", "length": 64, "required": true},
@@ -105,6 +127,7 @@ curl -X POST http://localhost:8093/api/ai/features/auto-develop \
2. 读取 `/api/ai/page-recipes` 中的 EIP4 页面 recipe,确认当前页面类型的 UI/UE 约束。
3. 生成 `ENTITY`、`PAGE_SCHEMA`、`SERVICEFLOW`、`MENU`、`TEST` 草稿。`PAGE_SCHEMA`
先生成 EIP4 PageBlueprint,再由平台编译器输出 amis schema;草稿 metadata 保留 blueprint 证据。
未指定 `feature.pageRecipe` 时默认使用 `maintenance-crud-v1`;树形维护页应指定 `tree-crud-v1`。
4. 对草稿执行基础门禁,包括 page-recipe、amis schema、typed page schema、服务流 XML、实体字段和 smoke 计划。
5. 生成待人审 `AiChangeSet`。
6. 生成 release plan。

View File

@@ -18,6 +18,7 @@ EIP4 的 AI Agent 不直接自由生成 amis JSON。Agent 应先生成 EIP4 Page
- `platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeRegistry.java`
- `platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeValidator.java`
- `platform-ai/src/main/resources/ai/page-recipes/maintenance-crud-v1.yaml`
- `platform-ai/src/main/resources/ai/page-recipes/tree-crud-v1.yaml`
AI 可查询入口:
@@ -50,7 +51,7 @@ AI 自动开发链路中的 `PAGE_SCHEMA` 草稿仍然保存编译后的 amis sc
标准输出结构:
- 顶层 `type=page`
- `body[0]` 为 `crud`
- `body` 为 `crud`
- `crud.name` 固定为 `{lowerCamel(tableName)}Crud`
- `crud.syncLocation=false`
- 列表 API 固定为 `/api/entity/{table}/list?page=${page}&perPage=${perPage}`
@@ -64,6 +65,29 @@ AI 自动开发链路中的 `PAGE_SCHEMA` 草稿仍然保存编译后的 amis sc
- 页大小默认 `20`
- `footerToolbar` 固定包含 `statistics` 和 `pagination`
## Recipe: tree-crud-v1
适用范围:
- 自引用层级实体维护页
- 实体必须包含 `PARENTID` 字段
- 覆盖树形列表、新增顶级节点、加子节点、编辑、删除
标准输出结构:
- 顶层 `type=page`
- `body` 为 `crud`
- `crud.name` 固定为 `{lowerCamel(tableName)}TreeCrud`
- `crud.childrenColumnName=children`
- 列表 API 固定为 `/api/entity/{table}/tree?parentKey=PARENTID&idKey={primaryKey}&perPage=2000`
- 新增顶级按钮位于 `headerToolbar[0]`
- 新增顶级按钮使用 `level=primary`、`icon=fa fa-plus`、`actionType=dialog`
- 操作列按钮顺序固定为:加子项、编辑、删除
- 加子项表单必须隐藏写入 `PARENTID=${primaryKey}`
- 编辑表单必须保留隐藏主键和 `PARENTID`
- 删除按钮使用 `className=text-danger`、`actionType=ajax`、`confirmText`
- 树数据端点返回 `data.items` 层级数组,每个节点的子节点字段为 `children`
字段映射:
- `string` -> `input-text`
@@ -78,7 +102,6 @@ AI 自动开发链路中的 `PAGE_SCHEMA` 草稿仍然保存编译后的 amis sc
本阶段只解决“AI 生成维护类 CRUD 页时走受控 recipe”。还未覆盖:
- 主子表页面
- 树表页面
- 审批办理页面
- 看板、日历、图表、报表页
- 复杂字段分组
@@ -97,7 +120,7 @@ AI 自动开发链路中的 `PAGE_SCHEMA` 草稿仍然保存编译后的 amis sc
## 后续演进
1. 增加 `master-detail-v1`、`tree-crud-v1`、`approval-task-v1` recipe。
1. 增加 `master-detail-v1`、`approval-task-v1` recipe。
2. 让设计器 overlay 保存也能记录对应 blueprint 或 template 来源。
3. 在功能包中导出 blueprint,线上部署包继续导出编译后的 amis schema。
4. Playwright E2E 从 recipe 反推出应验证的 UI 行为。

View File

@@ -17,6 +17,7 @@
- 页面 templateId
- 菜单名称
- 字段列表
- 页面配方,可省略。默认 `maintenance-crud-v1`;树形维护页使用 `tree-crud-v1`
字段格式:
@@ -46,10 +47,29 @@ java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar ai auto-develop \
--field NAME:名称:string:100:true \
--field CODE:编码:string:64:true \
--field ENABLED:启用:boolean::false \
--page-recipe maintenance-crud-v1 \
--max-repair-attempts 2 \
--output target/ai-runs/customer-level.json
```
树形维护页示例:
```bash
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar ai auto-develop \
--base-url http://localhost:8084 \
--objective "新增组织分类树形维护功能" \
--feature-name "组织分类维护" \
--table-name EIP4AI_ORG_CATEGORY \
--entity-name "组织分类" \
--template-id eip4ai-org-category \
--menu-name "组织分类维护" \
--field NAME:名称:string:100:true \
--field CODE:编码:string:64:true \
--page-recipe tree-crud-v1 \
--max-repair-attempts 2 \
--output target/ai-runs/org-category-tree.json
```
## 通过标准
- `applyStatus` 为 `PASSED`。
@@ -57,6 +77,7 @@ java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar ai auto-develop \
- 最终状态为 `READY_FOR_HUMAN_REVIEW`。
- 部署包存在且 `requiresHumanApproval=true`。
- 页面 schema 只能使用组件能力表中注册的组件和动作。
- `PAGE_SCHEMA` 草稿必须声明并通过 `page-recipe` 门禁;普通维护页为 `maintenance-crud-v1`,树形维护页为 `tree-crud-v1`。
## 页面 schema 校验

View File

@@ -9,5 +9,16 @@ public record AiFeatureRequest(
String entityName,
String templateId,
String menuName,
List<AiFeatureField> fields) {
List<AiFeatureField> fields,
String pageRecipe) {
public AiFeatureRequest(String objective,
String featureName,
String tableName,
String entityName,
String templateId,
String menuName,
List<AiFeatureField> fields) {
this(objective, featureName, tableName, entityName, templateId, menuName, fields, null);
}
}

View File

@@ -81,10 +81,12 @@ public class AiFeatureDraftGenerator {
private PageBlueprint pageBlueprint(FeatureSpec spec) {
List<PageBlueprintField> fields = new ArrayList<>();
for (FieldSpec field : spec.fields()) {
boolean treeParentField = PageBlueprint.RECIPE_TREE_CRUD.equals(spec.pageRecipe())
&& "PARENTID".equals(field.column());
fields.add(new PageBlueprintField(field.column(), field.label(), field.type(),
field.required(), true, true));
field.required(), !treeParentField, true));
}
return new PageBlueprint(PageBlueprint.VERSION, PageBlueprint.RECIPE_MAINTENANCE_CRUD,
return new PageBlueprint(PageBlueprint.VERSION, spec.pageRecipe(),
spec.templateId(), spec.featureName(), spec.tableName(), spec.entityName(),
spec.tableName() + "_ID", displayColumn(spec), fields,
true, true, true, 20);
@@ -129,7 +131,12 @@ public class AiFeatureDraftGenerator {
root.put("publishTarget", "local-smoke");
ArrayNode tests = root.putArray("smokeTests");
addSmoke(tests, "page-schema", "GET", "/api/page/schema/" + spec.templateId(), 200);
addSmoke(tests, "entity-list", "GET", "/api/entity/" + spec.tableName() + "/list?page=1&perPage=20", 200);
if (PageBlueprint.RECIPE_TREE_CRUD.equals(spec.pageRecipe())) {
addSmoke(tests, "entity-tree", "GET", "/api/entity/" + spec.tableName()
+ "/tree?parentKey=PARENTID&idKey=" + spec.tableName() + "_ID&perPage=2000", 200);
} else {
addSmoke(tests, "entity-list", "GET", "/api/entity/" + spec.tableName() + "/list?page=1&perPage=20", 200);
}
addSmoke(tests, "flow-search", "GET", "/api/flow/" + spec.tableName() + "_SEARCH?page=1&perPage=20", 200);
ObjectNode create = addSmoke(tests, "entity-create", "POST",
"/api/entity/" + spec.tableName() + "/save", 200);
@@ -152,7 +159,9 @@ public class AiFeatureDraftGenerator {
private ObjectNode sampleEntityBody(FeatureSpec spec) {
ObjectNode body = objectMapper.createObjectNode();
for (FieldSpec field : spec.fields()) {
switch (field.type()) {
if ("PARENTID".equals(field.column())) {
body.put(field.column(), "");
} else switch (field.type()) {
case "integer" -> body.put(field.column(), 1);
case "number" -> body.put(field.column(), 1.0);
case "date" -> body.put(field.column(), "2026-01-01");
@@ -173,11 +182,12 @@ public class AiFeatureDraftGenerator {
String entityName = firstText(request == null ? null : request.entityName(), feature, table);
String templateId = normalizeTemplateId(request == null ? null : request.templateId(), table);
String menuName = firstText(request == null ? null : request.menuName(), feature);
List<FieldSpec> fields = normalizeFields(request == null ? null : request.fields());
return new FeatureSpec(feature, table, entityName, templateId, menuName, fields);
String pageRecipe = normalizePageRecipe(request == null ? null : request.pageRecipe());
List<FieldSpec> fields = normalizeFields(request == null ? null : request.fields(), pageRecipe);
return new FeatureSpec(feature, table, entityName, templateId, menuName, pageRecipe, fields);
}
private List<FieldSpec> normalizeFields(List<AiFeatureField> input) {
private List<FieldSpec> normalizeFields(List<AiFeatureField> input, String pageRecipe) {
List<AiFeatureField> raw = input == null ? List.of() : input;
List<FieldSpec> out = new ArrayList<>();
Set<String> seen = new LinkedHashSet<>();
@@ -195,9 +205,24 @@ public class AiFeatureDraftGenerator {
out.add(new FieldSpec("NAME", "名称", "string", 100, true));
out.add(new FieldSpec("DESCRIPTION", "描述", "string", 500, false));
}
if (PageBlueprint.RECIPE_TREE_CRUD.equals(pageRecipe) && seen.add("PARENTID")) {
out.add(new FieldSpec("PARENTID", "上级", "string", 64, false));
}
return List.copyOf(out);
}
private static String normalizePageRecipe(String raw) {
String recipe = raw == null ? "" : raw.trim();
if (recipe.isBlank()) {
return PageBlueprint.RECIPE_MAINTENANCE_CRUD;
}
if (PageBlueprint.RECIPE_MAINTENANCE_CRUD.equals(recipe)
|| PageBlueprint.RECIPE_TREE_CRUD.equals(recipe)) {
return recipe;
}
throw new IllegalArgumentException("Unsupported pageRecipe: " + recipe);
}
private static String normalizeTable(String raw, String seed) {
String table = raw == null ? "" : raw.trim().toUpperCase(Locale.ROOT);
table = table.replaceAll("[^A-Z0-9_]", "_").replaceAll("_+", "_");
@@ -302,6 +327,7 @@ public class AiFeatureDraftGenerator {
String entityName,
String templateId,
String menuName,
String pageRecipe,
List<FieldSpec> fields) {
}

View File

@@ -6,35 +6,35 @@ compiler: com.eip4.platform.metadata.schema.blueprint.PageBlueprintCompiler
amis:
rootType: page
body:
- type: crud
syncLocation: false
perPage: 20
apiPattern: /api/entity/{tableName}/list?page=${page}&perPage=${perPage}
headerToolbar:
- addButton:
label: 新增
level: primary
icon: fa fa-plus
type: crud
syncLocation: false
perPage: 20
apiPattern: /api/entity/{tableName}/list?page=${page}&perPage=${perPage}
headerToolbar:
- addButton:
label: 新增
level: primary
icon: fa fa-plus
actionType: dialog
formApiPattern: post:/api/entity/{tableName}/save
- pagination
footerToolbar:
- statistics
- pagination
operationColumn:
label: 操作
width: 180
actions:
- edit:
level: link
actionType: dialog
formApiPattern: post:/api/entity/{tableName}/save
- pagination
footerToolbar:
- statistics
- pagination
operationColumn:
label: 操作
width: 180
actions:
- edit:
level: link
actionType: dialog
formApiPattern: post:/api/entity/{tableName}/save
- delete:
level: link
className: text-danger
actionType: ajax
confirmText: 确认删除该记录?
apiPattern: /api/entity/{tableName}/delete
- delete:
level: link
className: text-danger
actionType: ajax
confirmText: 确认删除该记录?
apiPattern: /api/entity/{tableName}/delete
fieldMappings:
string: input-text
integer: input-number

View File

@@ -0,0 +1,62 @@
schemaVersion: 1
recipe: tree-crud-v1
title: EIP4 tree CRUD page
purpose: 自引用层级实体维护页,覆盖树形列表、新增顶级、加子项、编辑、删除。
compiler: com.eip4.platform.metadata.schema.blueprint.PageBlueprintCompiler
requirements:
parentField: PARENTID
childrenColumnName: children
amis:
rootType: page
body:
type: crud
syncLocation: false
childrenColumnName: children
apiPattern: /api/entity/{tableName}/tree?parentKey=PARENTID&idKey={primaryKey}&perPage=2000
headerToolbar:
- addRootButton:
labelPattern: 新增顶级{entityName}
level: primary
icon: fa fa-plus
actionType: dialog
formApiPattern: post:/api/entity/{tableName}/save
- reloadButton:
label: 刷新
level: link
icon: fa fa-refresh
actionType: reload
targetPattern: "{crudName}"
footerToolbar: []
operationColumn:
label: 操作
width: 240
actions:
- addChild:
labelPattern: 加子{entityName}
level: link
actionType: dialog
parentBinding: PARENTID=${primaryKey}
formApiPattern: post:/api/entity/{tableName}/save
- edit:
level: link
actionType: dialog
formApiPattern: post:/api/entity/{tableName}/save
- delete:
level: link
className: text-danger
actionType: ajax
confirmText: 确认删除该记录?
apiPattern: /api/entity/{tableName}/delete
fieldMappings:
string: input-text
integer: input-number
number: input-number
date: input-date
datetime: input-datetime
boolean: switch
gates:
- page-recipe
- typed-page-schema
- amis-schema
- local-smoke
- playwright-render

View File

@@ -3,6 +3,7 @@ package com.eip4.platform.ai.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
@@ -44,7 +45,7 @@ class AiFeatureDraftGeneratorTest {
.findFirst().orElseThrow();
assertEquals("maintenance-crud-v1", pageSchema.metadata().get("pageRecipe"));
assertEquals(1, pageSchema.metadata().get("pageBlueprintVersion"));
assertEquals("crud", pageSchema.payload().path("body").get(0).path("type").asText());
assertEquals("crud", pageSchema.payload().path("body").path("type").asText());
@SuppressWarnings("unchecked")
Map<String, Object> blueprint = (Map<String, Object>) pageSchema.metadata().get("pageBlueprint");
assertEquals("EIP4AI_CONTRACT_TYPE", blueprint.get("tableName"));
@@ -78,4 +79,78 @@ class AiFeatureDraftGeneratorTest {
assertNotNull(entity.payload().path("attributes").get(0));
assertEquals("NAME", entity.payload().path("attributes").get(0).path("column").asText());
}
@Test
@DisplayName("树形配方生成 tree-crud 页面和树接口 smoke")
void generatesTreeCrudFeatureDrafts() {
AiFeatureDraftGenerator generator = new AiFeatureDraftGenerator(MAPPER);
var drafts = generator.generate(new AiFeatureRequest(
"新增组织分类维护",
"组织分类维护",
"EIP4AI_ORG_CATEGORY",
"组织分类",
"eip4ai-org-category",
"组织分类维护",
List.of(
new AiFeatureField("NAME", "名称", "string", 100, true),
new AiFeatureField("CODE", "编码", "string", 64, true)),
"tree-crud-v1"));
var entity = drafts.stream().filter(d -> d.artifactType() == AiArtifactType.ENTITY)
.findFirst().orElseThrow();
assertTrue(hasAttribute(entity.payload().path("attributes"), "PARENTID"));
var pageSchema = drafts.stream().filter(d -> d.artifactType() == AiArtifactType.PAGE_SCHEMA)
.findFirst().orElseThrow();
assertEquals("tree-crud-v1", pageSchema.metadata().get("pageRecipe"));
assertEquals("crud", pageSchema.payload().path("body").path("type").asText());
assertEquals("children", pageSchema.payload().path("body").path("childrenColumnName").asText());
assertEquals("/api/entity/EIP4AI_ORG_CATEGORY/tree?parentKey=PARENTID&idKey=EIP4AI_ORG_CATEGORY_ID&perPage=2000",
pageSchema.payload().path("body").path("api").path("url").asText());
assertFalse(hasColumn(pageSchema.payload().path("body").path("columns"), "PARENTID"));
var test = drafts.stream().filter(d -> d.artifactType() == AiArtifactType.TEST)
.findFirst().orElseThrow();
assertEquals("entity-tree", test.payload().path("smokeTests").get(1).path("name").asText());
assertEquals("/api/entity/EIP4AI_ORG_CATEGORY/tree?parentKey=PARENTID&idKey=EIP4AI_ORG_CATEGORY_ID&perPage=2000",
test.payload().path("smokeTests").get(1).path("url").asText());
assertEquals("", test.payload().path("smokeTests").get(3).path("requestBody").path("PARENTID").asText());
}
@Test
@DisplayName("未知页面配方不静默降级")
void rejectsUnknownPageRecipe() {
AiFeatureDraftGenerator generator = new AiFeatureDraftGenerator(MAPPER);
assertThrows(IllegalArgumentException.class, () -> generator.generate(new AiFeatureRequest(
"新增客户等级维护",
"客户等级维护",
"EIP4AI_CUSTOMER_LEVEL",
"客户等级",
"eip4ai-customer-level",
"客户等级维护",
List.of(new AiFeatureField("NAME", "名称", "string", 100, true)),
"unknown-recipe")));
}
private static boolean hasAttribute(Iterable<?> attributes, String column) {
for (Object attribute : attributes) {
if (attribute instanceof com.fasterxml.jackson.databind.JsonNode node
&& column.equals(node.path("column").asText())) {
return true;
}
}
return false;
}
private static boolean hasColumn(Iterable<?> columns, String name) {
for (Object column : columns) {
if (column instanceof com.fasterxml.jackson.databind.JsonNode node
&& name.equals(node.path("name").asText())) {
return true;
}
}
return false;
}
}

View File

@@ -632,6 +632,10 @@ public final class Eip4Cli {
for (String field : fields) {
fieldNodes.add(parseField(field));
}
String pageRecipe = options.single("page-recipe");
if (pageRecipe != null && !pageRecipe.isBlank()) {
feature.put("pageRecipe", pageRecipe);
}
return root;
}
@@ -872,7 +876,7 @@ public final class Eip4Cli {
eip4 env use --name NAME
eip4 env current
eip4 env status [--env NAME|--base-url URL|--all]
eip4 ai auto-develop --objective TEXT --feature-name NAME --table-name TABLE --entity-name NAME --template-id ID --menu-name NAME --field column:label:type[:length][:required]
eip4 ai auto-develop --objective TEXT --feature-name NAME --table-name TABLE --entity-name NAME --template-id ID --menu-name NAME --field column:label:type[:length][:required] [--page-recipe maintenance-crud-v1|tree-crud-v1]
eip4 release diff --left FILE --right FILE
eip4 release export --package-file FILE --output FILE
eip4 release import-preview --package-file FILE
@@ -934,6 +938,7 @@ public final class Eip4Cli {
Optional:
--env NAME
--base-url URL
--page-recipe maintenance-crud-v1|tree-crud-v1
--max-repair-attempts N
--no-deployment-package
--yes

View File

@@ -84,6 +84,7 @@ class Eip4CliTest {
"--menu-name", "客户等级维护",
"--field", "NAME:名称:string:100:true",
"--field", "ENABLED:启用:boolean::false",
"--page-recipe", "tree-crud-v1",
"--max-repair-attempts", "3",
"--no-deployment-package",
"--output", output.toString());
@@ -95,6 +96,7 @@ class Eip4CliTest {
assertEquals(3, client.body.path("maxRepairAttempts").asInt());
JsonNode feature = client.body.path("feature");
assertEquals("EIP4AI_CUSTOMER_LEVEL", feature.path("tableName").asText());
assertEquals("tree-crud-v1", feature.path("pageRecipe").asText());
assertEquals(2, feature.path("fields").size());
assertEquals("NAME", feature.path("fields").get(0).path("column").asText());
assertEquals(100, feature.path("fields").get(0).path("length").asInt());

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字段返对象() {