merge ai agent module

This commit is contained in:
2026-06-19 14:01:09 +08:00
112 changed files with 11723 additions and 14 deletions

View File

@@ -0,0 +1,10 @@
package com.eip4.platform.metadata.schema;
import java.util.List;
public record PageComponentDefinition(
String type,
String category,
List<String> capabilities,
List<String> allowedActions) {
}

View File

@@ -0,0 +1,87 @@
package com.eip4.platform.metadata.schema;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public final class PageComponentRegistry {
public static final int VERSION = 1;
private final Map<String, PageComponentDefinition> components;
private PageComponentRegistry(Map<String, PageComponentDefinition> components) {
this.components = Collections.unmodifiableMap(new LinkedHashMap<>(components));
}
public static PageComponentRegistry defaults() {
Map<String, PageComponentDefinition> map = new LinkedHashMap<>();
register(map, "page", "layout", List.of("page-root"), List.of());
register(map, "crud", "data", List.of("list", "pagination", "toolbar", "columns"), List.of());
register(map, "form", "data", List.of("submit", "validation", "api"), List.of("submit", "reset"));
register(map, "operation", "data", List.of("row-actions"), List.of());
register(map, "service", "data", List.of("remote-schema", "remote-data"), List.of());
register(map, "button", "action", List.of("dialog", "ajax", "drawer", "link", "reload"), List.of(
"ajax", "dialog", "drawer", "link", "url", "reload", "submit", "reset", "cancel", "copy",
"download", "toast", "confirm"));
register(map, "tpl", "display", List.of("template-text"), List.of());
register(map, "static", "display", List.of("readonly"), List.of());
register(map, "static-text", "display", List.of("readonly"), List.of());
register(map, "wrapper", "layout", List.of("container"), List.of());
register(map, "container", "layout", List.of("container"), List.of());
register(map, "grid", "layout", List.of("columns"), List.of());
register(map, "hbox", "layout", List.of("columns"), List.of());
register(map, "group", "layout", List.of("form-group"), List.of());
register(map, "input-text", "field", List.of("text", "required"), List.of());
register(map, "textarea", "field", List.of("text", "multiline", "required"), List.of());
register(map, "input-password", "field", List.of("password", "required"), List.of());
register(map, "input-number", "field", List.of("number", "required"), List.of());
register(map, "input-date", "field", List.of("date", "required"), List.of());
register(map, "input-datetime", "field", List.of("datetime", "required"), List.of());
register(map, "input-time", "field", List.of("time", "required"), List.of());
register(map, "input-month", "field", List.of("month", "required"), List.of());
register(map, "input-quarter", "field", List.of("quarter", "required"), List.of());
register(map, "input-year", "field", List.of("year", "required"), List.of());
register(map, "switch", "field", List.of("boolean"), List.of());
register(map, "checkbox", "field", List.of("boolean"), List.of());
register(map, "checkboxes", "field", List.of("multi-option"), List.of());
register(map, "radios", "field", List.of("single-option"), List.of());
register(map, "select", "field", List.of("single-option", "remote-options"), List.of());
register(map, "picker", "field", List.of("dialog-picker", "remote-options"), List.of());
register(map, "input-tree", "field", List.of("tree-options"), List.of());
register(map, "input-tag", "field", List.of("tags"), List.of());
register(map, "input-color", "field", List.of("color"), List.of());
register(map, "input-file", "field", List.of("upload"), List.of());
register(map, "input-image", "field", List.of("image-upload"), List.of());
register(map, "input-table", "field", List.of("editable-table"), List.of());
register(map, "hidden", "field", List.of("hidden-value"), List.of());
return new PageComponentRegistry(map);
}
public boolean supportsComponent(String type) {
return components.containsKey(type);
}
public boolean supportsAction(String componentType, String actionType) {
PageComponentDefinition definition = components.get(componentType);
return definition != null && definition.allowedActions().contains(actionType);
}
public Map<String, PageComponentDefinition> components() {
return components;
}
public Map<String, Object> toResponse() {
Map<String, Object> data = new LinkedHashMap<>();
data.put("schemaVersion", VERSION);
data.put("components", components.values());
return data;
}
private static void register(Map<String, PageComponentDefinition> map, String type, String category,
List<String> capabilities, List<String> allowedActions) {
map.put(type, new PageComponentDefinition(type, category, List.copyOf(capabilities),
List.copyOf(allowedActions)));
}
}

View File

@@ -0,0 +1,4 @@
package com.eip4.platform.metadata.schema;
public record TypedPageSchemaIssue(String path, String code, String message) {
}

View File

@@ -0,0 +1,12 @@
package com.eip4.platform.metadata.schema;
import java.util.List;
import java.util.Set;
public record TypedPageSchemaReport(
int schemaVersion,
boolean valid,
List<TypedPageSchemaIssue> issues,
Set<String> usedComponents,
Set<String> usedActions) {
}

View File

@@ -0,0 +1,125 @@
package com.eip4.platform.metadata.schema;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public final class TypedPageSchemaValidator {
private final ObjectMapper objectMapper;
private final PageComponentRegistry registry;
public TypedPageSchemaValidator(ObjectMapper objectMapper, PageComponentRegistry registry) {
this.objectMapper = objectMapper;
this.registry = registry;
}
public static TypedPageSchemaValidator defaults() {
return new TypedPageSchemaValidator(new ObjectMapper(), PageComponentRegistry.defaults());
}
public TypedPageSchemaReport validate(String schemaJson) {
List<TypedPageSchemaIssue> issues = new ArrayList<>();
Set<String> usedComponents = new LinkedHashSet<>();
Set<String> usedActions = new LinkedHashSet<>();
JsonNode root;
try {
root = objectMapper.readTree(schemaJson);
} catch (JacksonException ex) {
issues.add(new TypedPageSchemaIssue("$", "INVALID_JSON", "schema 不是合法 JSON: " + ex.getOriginalMessage()));
return report(issues, usedComponents, usedActions);
}
if (root == null || !root.isObject()) {
issues.add(new TypedPageSchemaIssue("$", "ROOT_NOT_OBJECT", "页面 schema 根节点必须是 JSON object"));
return report(issues, usedComponents, usedActions);
}
if (!"page".equals(root.path("type").asText(""))) {
issues.add(new TypedPageSchemaIssue("$.type", "ROOT_TYPE_NOT_PAGE", "页面 schema 根节点 type 必须是 page"));
}
visit(root, "$", issues, usedComponents, usedActions);
return report(issues, usedComponents, usedActions);
}
private void visit(JsonNode node, String path, List<TypedPageSchemaIssue> issues,
Set<String> usedComponents, Set<String> usedActions) {
if (node.isObject()) {
validateObject(node, path, issues, usedComponents, usedActions);
node.properties().forEach(entry -> visit(entry.getValue(), childPath(path, entry.getKey()),
issues, usedComponents, usedActions));
return;
}
if (node.isArray()) {
for (int i = 0; i < node.size(); i++) {
visit(node.get(i), path + "[" + i + "]", issues, usedComponents, usedActions);
}
}
}
private void validateObject(JsonNode node, String path, List<TypedPageSchemaIssue> issues,
Set<String> usedComponents, Set<String> usedActions) {
String componentType = node.path("type").asText("");
if (!componentType.isBlank()) {
boolean registeredComponent = registry.supportsComponent(componentType);
boolean componentCandidate = registeredComponent || isComponentCandidate(path, node);
if (componentCandidate) {
usedComponents.add(componentType);
}
if (componentCandidate && !registeredComponent) {
issues.add(new TypedPageSchemaIssue(path + ".type", "UNSUPPORTED_COMPONENT",
"组件未注册: " + componentType));
}
}
String actionType = node.path("actionType").asText("");
if (!actionType.isBlank()) {
usedActions.add(actionType);
if (componentType.isBlank()) {
issues.add(new TypedPageSchemaIssue(path + ".actionType", "ACTION_WITHOUT_COMPONENT",
"actionType 必须绑定到有 type 的组件"));
} else if (!registry.supportsAction(componentType, actionType)) {
issues.add(new TypedPageSchemaIssue(path + ".actionType", "UNSUPPORTED_ACTION",
"组件 " + componentType + " 不支持 actionType: " + actionType));
}
}
}
private boolean isComponentCandidate(String path, JsonNode node) {
return "$".equals(path)
|| path.endsWith(".body")
|| path.contains(".body[")
|| path.contains(".columns[")
|| path.contains(".buttons[")
|| path.contains(".headerToolbar[")
|| path.contains(".footerToolbar[")
|| path.contains(".tabs[")
|| path.contains(".items[")
|| node.has("actionType")
|| node.has("body")
|| node.has("columns")
|| node.has("buttons")
|| node.has("label")
|| node.has("tpl")
|| node.has("dialog")
|| node.has("drawer")
|| node.has("required");
}
private TypedPageSchemaReport report(List<TypedPageSchemaIssue> issues, Set<String> usedComponents,
Set<String> usedActions) {
return new TypedPageSchemaReport(PageComponentRegistry.VERSION, issues.isEmpty(), List.copyOf(issues),
Collections.unmodifiableSet(new LinkedHashSet<>(usedComponents)),
Collections.unmodifiableSet(new LinkedHashSet<>(usedActions)));
}
private String childPath(String path, String field) {
if (field.matches("[A-Za-z_][A-Za-z0-9_]*")) {
return path + "." + field;
}
return path + "['" + field.replace("'", "\\'") + "']";
}
}

View File

@@ -0,0 +1,33 @@
package com.eip4.platform.metadata.schema.blueprint;
import java.util.List;
/**
* EIP4 页面生成蓝图。
*
* <p>AI 和设计器应优先产出本对象,再由平台编译成 amis schema。这样 UI/UE 规则集中在
* recipe/compiler/validator 中,而不是散落在 Agent 提示词里。
*/
public record PageBlueprint(
int schemaVersion,
String recipe,
String templateId,
String title,
String tableName,
String entityName,
String primaryKey,
String displayField,
List<PageBlueprintField> fields,
boolean allowCreate,
boolean allowEdit,
boolean allowDelete,
int pageSize) {
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

@@ -0,0 +1,355 @@
package com.eip4.platform.metadata.schema.blueprint;
import java.util.Locale;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* 把 EIP4 受控 PageBlueprint 编译成当前前端可消费的 amis schema。
*/
public final class PageBlueprintCompiler {
private final ObjectMapper objectMapper;
public PageBlueprintCompiler(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public ObjectNode compile(PageBlueprint blueprint) {
validate(blueprint);
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());
}
private ObjectNode maintenanceCrud(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()) + "Crud";
crud.put("type", "crud");
crud.put("name", crudName);
crud.put("syncLocation", false);
ObjectNode api = crud.putObject("api");
api.put("method", "get");
api.put("url", "/api/entity/" + blueprint.tableName() + "/list?page=${page}&perPage=${perPage}");
api.put("adaptor", "return payload;");
ArrayNode headerToolbar = crud.putArray("headerToolbar");
if (blueprint.allowCreate()) {
ObjectNode addButton = headerToolbar.addObject();
addButton.put("type", "button");
addButton.put("label", "新增");
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.set("body", formControls(blueprint, false));
}
headerToolbar.add("pagination");
ArrayNode footerToolbar = crud.putArray("footerToolbar");
footerToolbar.add("statistics");
footerToolbar.add("pagination");
crud.put("perPage", blueprint.pageSize());
crud.set("columns", columns(blueprint, crudName));
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()) {
if (!field.listVisible()) {
continue;
}
ObjectNode column = columns.addObject();
column.put("name", field.name());
column.put("label", field.label());
}
if (!blueprint.allowEdit() && !blueprint.allowDelete()) {
return columns;
}
ObjectNode op = columns.addObject();
op.put("type", "operation");
op.put("label", "操作");
op.put("width", 180);
ArrayNode buttons = op.putArray("buttons");
if (blueprint.allowEdit()) {
addEditAction(blueprint, buttons);
}
if (blueprint.allowDelete()) {
addDeleteAction(blueprint, buttons, crudName);
}
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");
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");
ArrayNode editControls = formControls(blueprint, true);
ObjectNode hiddenPk = objectMapper.createObjectNode();
hiddenPk.put("type", "hidden");
hiddenPk.put("name", blueprint.primaryKey());
hiddenPk.put("value", "${" + blueprint.primaryKey() + "}");
editControls.add(hiddenPk);
editForm.set("body", editControls);
}
private void addDeleteAction(PageBlueprint blueprint, ArrayNode buttons, String crudName) {
ObjectNode del = buttons.addObject();
del.put("type", "button");
del.put("label", "删除");
del.put("level", "link");
del.put("className", "text-danger");
del.put("actionType", "ajax");
del.put("confirmText", "确认删除该记录?");
ObjectNode delApi = del.putObject("api");
delApi.put("method", "post");
delApi.put("url", "/api/entity/" + blueprint.tableName() + "/delete");
ObjectNode data = delApi.putObject("data");
data.put("id", "${" + blueprint.primaryKey() + "}");
del.put("reload", crudName);
}
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() || isExcluded(field.name(), excludedFields)) {
continue;
}
ObjectNode c = controls.addObject();
c.put("type", controlType(field.type()));
c.put("name", field.name());
c.put("label", field.label());
if (field.required()) {
c.put("required", true);
}
if (bindCurrentRow) {
c.put("value", "${" + field.name() + "}");
}
}
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");
}
if (blueprint.schemaVersion() != PageBlueprint.VERSION) {
throw new IllegalArgumentException("Unsupported page blueprint version: " + blueprint.schemaVersion());
}
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");
required(blueprint.title(), "title");
required(blueprint.tableName(), "tableName");
required(blueprint.entityName(), "entityName");
required(blueprint.primaryKey(), "primaryKey");
required(blueprint.displayField(), "displayField");
if (blueprint.fields() == null || blueprint.fields().isEmpty()) {
throw new IllegalArgumentException("fields must not be empty");
}
boolean displayFieldExists = false;
for (PageBlueprintField field : blueprint.fields()) {
required(field.name(), "field.name");
required(field.label(), "field.label");
required(field.type(), "field.type");
if (field.name().equals(blueprint.displayField())) {
displayFieldExists = true;
}
}
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");
}
}
private static void required(String value, String field) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException(field + " is required");
}
}
private static String controlType(String fieldType) {
return switch (fieldType) {
case "integer", "number" -> "input-number";
case "date" -> "input-date";
case "datetime" -> "input-datetime";
case "boolean" -> "switch";
default -> "input-text";
};
}
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]);
for (int i = 1; i < parts.length; i++) {
if (!parts[i].isBlank()) {
sb.append(Character.toUpperCase(parts[i].charAt(0))).append(parts[i].substring(1));
}
}
return sb.toString();
}
}

View File

@@ -0,0 +1,10 @@
package com.eip4.platform.metadata.schema.blueprint;
public record PageBlueprintField(
String name,
String label,
String type,
boolean required,
boolean listVisible,
boolean formVisible) {
}

View File

@@ -0,0 +1,24 @@
package com.eip4.platform.metadata.schema.blueprint;
import java.util.List;
import java.util.Map;
public record PageRecipeDefinition(
String recipe,
int schemaVersion,
String title,
Map<String, String> fieldMappings,
List<String> gates) {
public PageRecipeDefinition {
if (recipe == null || recipe.isBlank()) {
throw new IllegalArgumentException("recipe is required");
}
if (schemaVersion < 1) {
throw new IllegalArgumentException("schemaVersion must be positive");
}
title = title == null ? "" : title;
fieldMappings = Map.copyOf(fieldMappings == null ? Map.of() : fieldMappings);
gates = List.copyOf(gates == null ? List.of() : gates);
}
}

View File

@@ -0,0 +1,86 @@
package com.eip4.platform.metadata.schema.blueprint;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
public final class PageRecipeRegistry {
private final Map<String, PageRecipeDefinition> recipes;
public PageRecipeRegistry(List<PageRecipeDefinition> definitions) {
Map<String, PageRecipeDefinition> ordered = new LinkedHashMap<>();
for (PageRecipeDefinition definition : definitions == null ? List.<PageRecipeDefinition>of() : definitions) {
PageRecipeDefinition previous = ordered.put(definition.recipe(), definition);
if (previous != null) {
throw new IllegalArgumentException("Duplicate page recipe: " + definition.recipe());
}
}
this.recipes = Map.copyOf(ordered);
}
public static PageRecipeRegistry defaults() {
return new PageRecipeRegistry(List.of(maintenanceCrud(), treeCrud()));
}
public Optional<PageRecipeDefinition> find(String recipe) {
if (recipe == null || recipe.isBlank()) {
return Optional.empty();
}
return Optional.ofNullable(recipes.get(recipe));
}
public boolean supports(String recipe) {
return find(recipe).isPresent();
}
public List<PageRecipeDefinition> definitions() {
return List.copyOf(recipes.values());
}
public ObjectNode compile(PageBlueprint blueprint, ObjectMapper objectMapper) {
if (!supports(blueprint == null ? null : blueprint.recipe())) {
String recipe = blueprint == null ? "" : blueprint.recipe();
throw new IllegalArgumentException("Unsupported page recipe: " + recipe);
}
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());
};
}
private static PageRecipeDefinition maintenanceCrud() {
return new PageRecipeDefinition(
PageBlueprint.RECIPE_MAINTENANCE_CRUD,
PageBlueprint.VERSION,
"EIP4 maintenance 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"));
}
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

@@ -0,0 +1,14 @@
package com.eip4.platform.metadata.schema.blueprint;
import java.util.List;
public record PageRecipeValidationReport(
String recipe,
boolean valid,
List<String> messages) {
public PageRecipeValidationReport {
recipe = recipe == null ? "" : recipe;
messages = List.copyOf(messages == null ? List.of() : messages);
}
}

View File

@@ -0,0 +1,126 @@
package com.eip4.platform.metadata.schema.blueprint;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public final class PageRecipeValidator {
private final ObjectMapper objectMapper;
private final PageRecipeRegistry registry;
public PageRecipeValidator(ObjectMapper objectMapper, PageRecipeRegistry registry) {
this.objectMapper = objectMapper;
this.registry = registry;
}
public static PageRecipeValidator defaults() {
return new PageRecipeValidator(new ObjectMapper(), PageRecipeRegistry.defaults());
}
public PageRecipeValidationReport validate(PageBlueprint blueprint, JsonNode schema) {
List<String> messages = new ArrayList<>();
if (blueprint == null) {
return report("", List.of("pageBlueprint metadata is required when pageRecipe is declared"));
}
String recipe = blueprint.recipe();
registry.find(recipe).ifPresentOrElse(
definition -> {
if (definition.schemaVersion() != blueprint.schemaVersion()) {
messages.add("pageBlueprintVersion 与 recipe 版本不一致: expected="
+ definition.schemaVersion() + ", actual=" + blueprint.schemaVersion());
}
},
() -> messages.add("未注册的 page recipe: " + recipe));
if (schema == null || !schema.isObject()) {
messages.add("PAGE_SCHEMA payload 顶层必须是 JSON object");
return report(recipe, messages);
}
if (messages.isEmpty()) {
try {
JsonNode expected = registry.compile(blueprint, objectMapper);
if (!expected.equals(schema)) {
String difference = firstDifference(expected, schema, "$");
messages.add("PAGE_SCHEMA payload 与 recipe 编译结果不一致"
+ (difference == null ? "" : ": " + difference));
}
} catch (IllegalArgumentException ex) {
messages.add(ex.getMessage());
}
}
return report(recipe, messages);
}
private static PageRecipeValidationReport report(String recipe, List<String> messages) {
return new PageRecipeValidationReport(recipe, messages.isEmpty(), messages.stream().limit(20).toList());
}
private static String firstDifference(JsonNode expected, JsonNode actual, String path) {
if (expected == null && actual == null) {
return null;
}
if (expected == null || actual == null) {
return path + " expected=" + valueSummary(expected) + ", actual=" + valueSummary(actual);
}
if (expected.isObject() && actual.isObject()) {
Iterator<Map.Entry<String, JsonNode>> fields = expected.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> entry = fields.next();
JsonNode actualChild = actual.get(entry.getKey());
if (actualChild == null) {
return child(path, entry.getKey()) + " missing";
}
String difference = firstDifference(entry.getValue(), actualChild, child(path, entry.getKey()));
if (difference != null) {
return difference;
}
}
Iterator<String> actualNames = actual.fieldNames();
while (actualNames.hasNext()) {
String name = actualNames.next();
if (!expected.has(name)) {
return child(path, name) + " unexpected=" + valueSummary(actual.get(name));
}
}
return null;
}
if (expected.isArray() && actual.isArray()) {
if (expected.size() != actual.size()) {
return path + " array size expected=" + expected.size() + ", actual=" + actual.size();
}
for (int i = 0; i < expected.size(); i++) {
String difference = firstDifference(expected.get(i), actual.get(i), path + "[" + i + "]");
if (difference != null) {
return difference;
}
}
return null;
}
if (!expected.equals(actual)) {
return path + " expected=" + valueSummary(expected) + ", actual=" + valueSummary(actual);
}
return null;
}
private static String child(String path, String field) {
if (field.matches("[A-Za-z_][A-Za-z0-9_]*")) {
return path + "." + field;
}
return path + "['" + field.replace("'", "\\'") + "']";
}
private static String valueSummary(JsonNode node) {
if (node == null || node.isNull()) {
return "null";
}
String text = node.isTextual() ? node.asText() : node.toString();
if (text.length() > 80) {
return text.substring(0, 77) + "...";
}
return text;
}
}

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

@@ -92,7 +92,7 @@ public class MetaController {
// 属性模板:取 SYS_USERGROUP.NAME 属性行做默认值载体
Map<String, Object> attrTpl = loadAttrTemplate(idOf(tplEnt));
List<Map<String, Object>> created = new ArrayList<>();
List<GeneralPOJO> created = new ArrayList<>();
// 标准列
created.add(saveAttr(attrTpl, entityId, table + "_ID", "主键", "CHAR", 36, true, true, ctx));
created.add(saveAttr(attrTpl, entityId, "VERSION", "版本", "INTEGER", null, true, false, ctx));
@@ -125,9 +125,9 @@ public class MetaController {
}
}
// 动态建表
Entity newEnt = (Entity) dataDicService.getSYSEntity(entityId);
String ddl = newEnt.createTableSql();
// 动态建表前先清刚保存实体/属性带来的 POInfo 缓存,保证后续读写立即拿到新字段。
cacheInvalidator.evictByEntityId(entityId, table);
String ddl = createTableDdl(table, created);
dataDicService.executeCreateSql(ddl);
// P1-5:建表后按元数据补索引(外键 uuid 列 + UPDATETIME),引擎只建表不建索引
@@ -224,9 +224,9 @@ public class MetaController {
return resp;
}
private Map<String, Object> saveAttr(Map<String, Object> tpl, String entityId, String col,
String display, String ref, Integer len,
boolean mandatory, boolean isKey, Properties ctx) {
private GeneralPOJO saveAttr(Map<String, Object> tpl, String entityId, String col,
String display, String ref, Integer len,
boolean mandatory, boolean isKey, Properties ctx) {
Map<String, Object> m = new HashMap<>(tpl);
m.remove("SYS_ENTITYATTRIBUTE_ID");
m.put("ENTITYID", entityId);
@@ -243,8 +243,100 @@ public class MetaController {
} else {
m.remove("FIELDLENGTH");
}
pojoCRUDService.save(m, "SYS_ENTITYATTRIBUTE", ctx);
return Map.of("column", col, "type", ref);
return pojoCRUDService.save(m, "SYS_ENTITYATTRIBUTE", ctx);
}
static String createTableDdl(String table, List<GeneralPOJO> attrs) {
if (attrs == null || attrs.isEmpty()) {
throw new IllegalStateException("实体属性为空,无法建表: " + table);
}
StringBuilder sql = new StringBuilder();
StringBuilder unique = new StringBuilder();
StringBuilder combUnique = new StringBuilder();
sql.append("CREATE TABLE ").append(table).append("\n");
sql.append("(\n");
for (GeneralPOJO attr : attrs) {
appendColumnDdl(table, attr, sql, unique, combUnique);
}
sql.append(unique);
if (!combUnique.isEmpty()) {
sql.append(combUnique).append("), \n");
}
sql.append("primary key (").append(table).append("_ID)\n");
sql.append("); \n");
return sql.toString();
}
private static void appendColumnDdl(String table, GeneralPOJO attr, StringBuilder sql,
StringBuilder unique, StringBuilder combUnique) {
if (attr.get_ValueAsBoolean("ISREADONLY")) {
return;
}
String ref = value(attr, "REFERENCEID");
if ("LIST".equals(ref) || "BLOB".equals(ref) || "STATUS".equals(ref)) {
return;
}
String col = value(attr, "COLUMNNAME");
if (col == null || !col.matches("[A-Z][A-Z0-9_]{1,60}")) {
throw new IllegalStateException("实体字段名不合法: " + col);
}
if ("CREATEBY".equals(col) || "UPDATEBY".equals(col) || "ORGID".equals(col) || "DEPARTID".equals(col)) {
sql.append(col).append(" character(36) ");
} else if ("NVARCHAR".equals(ref) || "CODE".equals(ref)) {
int length = positiveInt(attr.get_Value("FIELDLENGTH"), 100);
sql.append(col).append(" character varying(").append(length).append(") ");
} else if ("INTEGER".equals(ref) || "BOOLEAN".equals(ref) || "ENUMERATE".equals(ref)) {
sql.append(col).append(" integer ");
} else if ("DECIMAL".equals(ref) || "MONEY".equals(ref)) {
sql.append(col).append(" numeric(18,6) ");
} else if ("DATE".equals(ref) || "TIME".equals(ref)) {
sql.append(col).append(" bigint ");
} else if ("CHAR".equals(ref)) {
sql.append(col).append(" character(36) ");
} else {
sql.append(col).append(" character(36) REFERENCES ").append(table);
}
if (attr.get_ValueAsBoolean("ISMANDATORY")) {
sql.append(" NOT NULL ");
}
String defValue = value(attr, "DEFAULTVALUE");
if (defValue != null && !defValue.isBlank()
&& ("INTEGER".equals(ref) || "BOOLEAN".equals(ref) || "DECIMAL".equals(ref) || "MONEY".equals(ref))) {
sql.append(" DEFAULT ").append(defValue);
}
sql.append(", \n");
if (attr.get_ValueAsBoolean("ISIDENTIFIER")) {
unique.append(" unique (").append(col).append("), \n");
} else if (attr.get_ValueAsBoolean("ISCOMBIDENTIFIER")) {
if (combUnique.isEmpty()) {
combUnique.append(" unique (");
} else {
combUnique.append(",");
}
combUnique.append(col);
}
}
private static int positiveInt(Object value, int defaultValue) {
if (value instanceof Number n && n.intValue() > 0) {
return n.intValue();
}
if (value != null) {
try {
int parsed = Integer.parseInt(value.toString());
if (parsed > 0) {
return parsed;
}
} catch (NumberFormatException ignore) {
return defaultValue;
}
}
return defaultValue;
}
private static String value(GeneralPOJO po, String column) {
Object value = po.get_Value(column);
return value == null ? null : value.toString();
}
private Map<String, Object> loadAttrTemplate(String tplEntityId) {

View File

@@ -10,6 +10,7 @@ import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
@@ -19,6 +20,7 @@ import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
@@ -28,6 +30,9 @@ import org.springframework.web.server.ResponseStatusException;
import com.dsasp.server.common.user.service.LoggedInUser;
import com.dsasp.server.common.util.UserSession;
import com.eip4.platform.metadata.schema.PageComponentRegistry;
import com.eip4.platform.metadata.schema.TypedPageSchemaReport;
import com.eip4.platform.metadata.schema.TypedPageSchemaValidator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
@@ -68,9 +73,36 @@ public class PageSchemaController {
public static final String HEADER_SCHEMA_LAYER = "X-Schema-Layer";
private final JdbcTemplate jdbcTemplate;
private final PageComponentRegistry componentRegistry;
private final TypedPageSchemaValidator typedSchemaValidator;
@Autowired
public PageSchemaController(JdbcTemplate jdbcTemplate) {
this(jdbcTemplate, PageComponentRegistry.defaults());
}
PageSchemaController(JdbcTemplate jdbcTemplate, PageComponentRegistry componentRegistry) {
this.jdbcTemplate = jdbcTemplate;
this.componentRegistry = componentRegistry;
this.typedSchemaValidator = new TypedPageSchemaValidator(SCHEMA_MAPPER, componentRegistry);
}
@Operation(summary = "查询 typed page schema 组件能力表",
description = "AI Agent 和设计器共用;未注册组件不能保存为 overlay。")
@GetMapping("/api/page/schema/components")
public ResponseEntity<Map<String, Object>> components() {
return ResponseEntity.ok(ok("component registry", componentRegistry.toResponse()));
}
@Operation(summary = "校验 typed page schema",
description = "校验根类型、组件注册和 actionType 能力;不写库。")
@PostMapping("/api/page/schema/validate")
public ResponseEntity<Map<String, Object>> validateSchema(@RequestBody String schemaJsonRaw) {
TypedPageSchemaReport report = typedSchemaValidator.validate(schemaJsonRaw == null ? "" : schemaJsonRaw);
if (!report.valid()) {
return ResponseEntity.badRequest().body(fail("typed schema 校验失败", validationData(report)));
}
return ResponseEntity.ok(ok("typed schema 校验通过", validationData(report)));
}
// ================================================================ GET 读取
@@ -149,6 +181,10 @@ public class PageSchemaController {
if (schemaJsonRaw == null || schemaJsonRaw.isBlank()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "请求体不能为空");
}
TypedPageSchemaReport validation = typedSchemaValidator.validate(schemaJsonRaw);
if (!validation.valid()) {
return ResponseEntity.badRequest().body(fail("typed schema 校验失败", validationData(validation)));
}
// 计算 overlay etag
String overlayEtag = sha256(schemaJsonRaw);
@@ -483,9 +519,24 @@ public class PageSchemaController {
}
private static Map<String, Object> fail(String msg) {
return fail(msg, null);
}
private static Map<String, Object> fail(String msg, Map<String, Object> data) {
Map<String, Object> r = new LinkedHashMap<>();
r.put("status", 1);
r.put("msg", msg);
if (data != null) r.put("data", data);
return r;
}
private static Map<String, Object> validationData(TypedPageSchemaReport report) {
Map<String, Object> data = new LinkedHashMap<>();
data.put("schemaVersion", report.schemaVersion());
data.put("valid", report.valid());
data.put("issues", report.issues());
data.put("usedComponents", report.usedComponents());
data.put("usedActions", report.usedActions());
return data;
}
}

View File

@@ -0,0 +1,84 @@
package com.eip4.platform.metadata.schema;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class TypedPageSchemaValidatorTest {
private final TypedPageSchemaValidator validator = TypedPageSchemaValidator.defaults();
@Test
void acceptsRegisteredCrudFormAndButtonActions() {
TypedPageSchemaReport report = validator.validate("""
{
"type": "page",
"body": [{
"type": "crud",
"columns": [{
"type": "operation",
"buttons": [
{"type": "button", "actionType": "dialog", "dialog": {"body": {"type": "form"}}},
{"type": "button", "actionType": "ajax"}
]
}]
}]
}
""");
assertTrue(report.valid());
assertTrue(report.usedComponents().contains("crud"));
assertTrue(report.usedActions().contains("dialog"));
assertTrue(report.usedActions().contains("ajax"));
}
@Test
void rejectsUnsupportedComponent() {
TypedPageSchemaReport report = validator.validate("""
{"type":"page","body":{"type":"unknown-widget"}}
""");
assertFalse(report.valid());
assertEquals("UNSUPPORTED_COMPONENT", report.issues().get(0).code());
assertTrue(report.issues().get(0).path().contains("$.body.type"));
}
@Test
void ignoresNonComponentTypeFieldsInConfigurationObjects() {
TypedPageSchemaReport report = validator.validate("""
{
"type": "page",
"body": {
"type": "crud",
"api": {"type": "json", "method": "get", "url": "/api/entity/EIP4AI_DEMO/list"}
}
}
""");
assertTrue(report.valid());
assertTrue(report.usedComponents().contains("crud"));
assertFalse(report.usedComponents().contains("json"));
}
@Test
void rejectsUnsupportedActionForComponent() {
TypedPageSchemaReport report = validator.validate("""
{"type":"page","body":{"type":"form","actionType":"dialog"}}
""");
assertFalse(report.valid());
assertEquals("UNSUPPORTED_ACTION", report.issues().get(0).code());
}
@Test
void requiresPageRoot() {
TypedPageSchemaReport report = validator.validate("""
{"type":"crud"}
""");
assertFalse(report.valid());
assertEquals("ROOT_TYPE_NOT_PAGE", report.issues().get(0).code());
}
}

View File

@@ -0,0 +1,139 @@
package com.eip4.platform.metadata.schema.blueprint;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
class PageBlueprintCompilerTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
@DisplayName("maintenance-crud-v1 编译为 EIP4 标准 amis CRUD 页")
void compilesMaintenanceCrudRecipe() {
PageBlueprint blueprint = new PageBlueprint(
PageBlueprint.VERSION,
PageBlueprint.RECIPE_MAINTENANCE_CRUD,
"eip4ai-contract-type",
"合同类型维护",
"EIP4AI_CONTRACT_TYPE",
"合同类型",
"EIP4AI_CONTRACT_TYPE_ID",
"NAME",
List.of(
new PageBlueprintField("NAME", "名称", "string", true, true, true),
new PageBlueprintField("ENABLED", "启用", "boolean", false, true, true)),
true,
true,
true,
20);
ObjectNode schema = new PageBlueprintCompiler(MAPPER).compile(blueprint);
assertEquals("page", schema.path("type").asText());
assertEquals("合同类型维护", schema.path("title").asText());
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}",
crud.path("api").path("url").asText());
assertEquals("新增", crud.path("headerToolbar").get(0).path("label").asText());
assertEquals("post:/api/entity/EIP4AI_CONTRACT_TYPE/save",
crud.path("headerToolbar").get(0).path("dialog").path("body").path("api").asText());
assertEquals("switch", crud.path("headerToolbar").get(0).path("dialog").path("body")
.path("body").get(1).path("type").asText());
assertEquals("hidden", crud.path("columns").get(2).path("buttons").get(0).path("dialog")
.path("body").path("body").get(2).path("type").asText());
assertEquals("text-danger", crud.path("columns").get(2).path("buttons").get(1)
.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() {
PageBlueprint blueprint = new PageBlueprint(
PageBlueprint.VERSION,
"dashboard-v9",
"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));
}
@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

@@ -0,0 +1,91 @@
package com.eip4.platform.metadata.schema.blueprint;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
class PageRecipeValidatorTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private final PageRecipeValidator validator = new PageRecipeValidator(MAPPER, PageRecipeRegistry.defaults());
@Test
@DisplayName("page recipe 校验接受 compiler 标准输出")
void acceptsCompiledRecipeOutput() {
PageBlueprint blueprint = blueprint();
ObjectNode schema = new PageBlueprintCompiler(MAPPER).compile(blueprint);
PageRecipeValidationReport report = validator.validate(blueprint, schema);
assertTrue(report.valid());
}
@Test
@DisplayName("page recipe 校验拒绝被篡改的 schema")
void rejectsSchemaThatDiffersFromCompilerOutput() {
PageBlueprint blueprint = blueprint();
ObjectNode schema = new PageBlueprintCompiler(MAPPER).compile(blueprint);
schema.put("title", "被篡改标题");
PageRecipeValidationReport report = validator.validate(blueprint, schema);
assertFalse(report.valid());
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,
PageBlueprint.RECIPE_MAINTENANCE_CRUD,
"eip4ai-contract-type",
"合同类型维护",
"EIP4AI_CONTRACT_TYPE",
"合同类型",
"EIP4AI_CONTRACT_TYPE_ID",
"NAME",
List.of(
new PageBlueprintField("NAME", "名称", "string", true, true, true),
new PageBlueprintField("ENABLED", "启用", "boolean", false, true, true)),
true,
true,
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字段返对象() {

View File

@@ -0,0 +1,40 @@
package com.eip4.platform.metadata.web;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
class MetaControllerDdlTest {
@Test
@DisplayName("运行态实体 DDL 按旧引擎类型规则生成主键、字符串和布尔列")
void createTableDdlUsesSavedAttributes() {
String ddl = MetaController.createTableDdl("EIP4AI_RT_DEMO", List.of(
attr("EIP4AI_RT_DEMO_ID", "CHAR", null, true),
attr("NAME", "NVARCHAR", 100, true),
attr("ENABLED", "BOOLEAN", null, false)
));
assertTrue(ddl.contains("CREATE TABLE EIP4AI_RT_DEMO"));
assertTrue(ddl.contains("EIP4AI_RT_DEMO_ID character(36) NOT NULL"));
assertTrue(ddl.contains("NAME character varying(100) NOT NULL"));
assertTrue(ddl.contains("ENABLED integer"));
assertTrue(ddl.contains("primary key (EIP4AI_RT_DEMO_ID)"));
}
private static GeneralPOJO attr(String column, String referenceId, Integer length, boolean mandatory) {
GeneralPOJO po = mock(GeneralPOJO.class);
when(po.get_Value("COLUMNNAME")).thenReturn(column);
when(po.get_Value("REFERENCEID")).thenReturn(referenceId);
when(po.get_Value("FIELDLENGTH")).thenReturn(length);
when(po.get_ValueAsBoolean("ISMANDATORY")).thenReturn(mandatory);
return po;
}
}

View File

@@ -390,6 +390,46 @@ class PageSchemaControllerTest {
assertTrue(hash.matches("[0-9a-f]{64}"));
}
@Test
@DisplayName("18. 组件能力表端点返回 schemaVersion 和已注册组件")
void componentRegistryEndpoint() {
PageSchemaController c = new PageSchemaController(mock(JdbcTemplate.class));
var resp = c.components();
assertEquals(HttpStatus.OK, resp.getStatusCode());
assertEquals(0, resp.getBody().get("status"));
assertTrue(resp.getBody().toString().contains("schemaVersion"));
assertTrue(resp.getBody().toString().contains("crud"));
}
@Test
@DisplayName("19. typed schema 校验端点拒绝未注册组件")
void validateSchemaRejectsUnsupportedComponent() {
PageSchemaController c = new PageSchemaController(mock(JdbcTemplate.class));
var resp = c.validateSchema("{\"type\":\"page\",\"body\":{\"type\":\"evil-widget\"}}");
assertEquals(HttpStatus.BAD_REQUEST, resp.getStatusCode());
assertEquals(1, resp.getBody().get("status"));
assertTrue(resp.getBody().toString().contains("UNSUPPORTED_COMPONENT"));
}
@Test
@DisplayName("20. PUT overlay 先做 typed schema 校验,失败时不写库")
void putOverlayRejectsUnsupportedComponentBeforeWrite() {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
PageSchemaController c = new PageSchemaController(jdbc);
setAdminSession();
var resp = c.putOverlay(TID, "{\"type\":\"page\",\"body\":{\"type\":\"evil-widget\"}}");
assertEquals(HttpStatus.BAD_REQUEST, resp.getStatusCode());
assertTrue(resp.getBody().toString().contains("UNSUPPORTED_COMPONENT"));
verify(jdbc, never()).update(anyString(), any(), any(), any(), any(), any(), any());
clearSession();
}
// ── Session 工具 ─────────────────────────────────────────────────────────
private static void setAdminSession() {

View File

@@ -0,0 +1,20 @@
package com.eip4.platform.metadata.web;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.jdbc.core.JdbcTemplate;
class PageSchemaControllerWiringTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withBean(JdbcTemplate.class, () -> mock(JdbcTemplate.class))
.withUserConfiguration(PageSchemaController.class);
@Test
void springUsesJdbcTemplateConstructor() {
contextRunner.run(context -> assertThat(context).hasSingleBean(PageSchemaController.class));
}
}