Compare commits

...

10 Commits

Author SHA1 Message Date
4400eabc66 test(e2e): 人走五环端到端验收脚本 + live 验收实证(Section 6 / Task 24)
8094+真实DB验收通过:五环①②③④(含引用列 OWNER→SYS_USER)+ AI ①面(READY_FOR_HUMAN_REVIEW)
+ 部署包(requiresHumanApproval) + 红线全守;实证写入脚本头注。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 10:27:03 +08:00
303b4d0240 fix(design): @Autowired DesignFeatureController 生产构造器 — 修 Spring 多构造器回退无参导致启动崩
live e2e 揪出:DesignFeatureController 有「生产构造+包级测试构造」两个构造器,
生产构造未标 @Autowired → Spring 回退找无参构造 → NoSuchMethodException 启动失败。
纯单元测试全 new 对象故漏检;真实 boot 才暴露。补 @Autowired + 回归测试守护此装配模式。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 10:25:12 +08:00
b5a6388024 feat(design): publish 生成 production 人审部署包(DECISION-2,manifest+rollback)(建物3-Task13)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 10:10:22 +08:00
c339efcdcb feat(design): publish 菜单注册 MenuRegistrar(dedup+新功能目录)(建物3-Task12)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 10:08:41 +08:00
74478f030e feat(design): POST /api/design/publish 确保默认流落库(幂等)(建物3-Task11)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 10:07:13 +08:00
9765872382 feat(design): GET /api/design/flows 列出实体默认流预览(建物3-Task10)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 10:05:30 +08:00
05181d75bf test(design): 端到端·composer 透传 reference 列→编译显名 <COL>_DISPLAY__
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 09:55:10 +08:00
869790d04f feat(design): 编译器引用列渲染显名·list 列 name 指向 <COL>_DISPLAY__(运行时 _SEARCH 注入,白名单安全)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 09:54:33 +08:00
eabebae361 feat(design): POST /api/design/recipe/compile 单步端点(建物2)·服务端生成 templateId+严格 typed 闸+唯一真相落标准层
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 09:53:49 +08:00
687ade7513 feat(design): RecipePageComposer 共享蓝图装配器 + PageBlueprintField 引用字段扩展(向后兼容)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 09:52:13 +08:00
18 changed files with 1382 additions and 3 deletions

View File

@@ -0,0 +1,98 @@
package com.eip4.platform.metadata.publish;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
/**
* 默认服务流「预览/持久态」读取(建物 3 · 发布前人工确认)。
*
* <p>flowName 与 {@code com.dsasp.server.core.service.flow.model.DefaultFlowHelper}
* 的 Flow id 完全一致({@code <TABLE>_ADD} 等),在 SYS_SERVICEFLOW 中即主键 sys_serviceflow_id。
*
* <ul>
* <li>实体尚无流(SYS_SERVICEFLOW 无 entityid 行)→ 返回合成名预览,
* 含 STATUS 列时 +2(SUBMIT / SAVE_AND_SUBMIT)。</li>
* <li>实体已有流 → 从 SYS_SERVICEFLOW 读真实行(sys_serviceflow_id + displayname)。</li>
* </ul>
*
* <p>不引入保真层重型 POInfo:STATUS 列存在性用元数据 SQL 判断,避免预览阶段触发 POInfo 缓存。
*/
@Service
public class DefaultFlowPreviewService {
/** 5 个基础流的有序后缀 → kind / 显名映射。 */
private static final String[][] BASE_FLOWS = {
{"_ADD", "ADD", "新增"},
{"_DELETE", "DELETE", "删除"},
{"_UPDATE", "UPDATE", "更新"},
{"_SEARCH", "SEARCH", "查询"},
{"_LOAD", "LOAD", "加载"},
};
/** 含 STATUS 列时追加的 2 个提交流。 */
private static final String[][] STATUS_FLOWS = {
{"_SUBMIT", "SUBMIT", "提交审批"},
{"_SAVE_AND_SUBMIT", "SAVE_AND_SUBMIT", "保存并提交审批"},
};
private final JdbcTemplate jdbcTemplate;
public DefaultFlowPreviewService(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public record FlowItem(String flowName, String displayName, String kind) {}
public record FlowsPreview(String entityId, String tableName, boolean persisted, List<FlowItem> flows) {}
public FlowsPreview preview(String entityId) {
Integer existing = jdbcTemplate.queryForObject(
"SELECT COUNT(*) FROM SYS_SERVICEFLOW WHERE entityid=?", Integer.class, entityId);
String tableName = jdbcTemplate.queryForObject(
"SELECT TRIM(tablename) FROM SYS_ENTITY WHERE TRIM(sys_entity_id)=?", String.class, entityId);
if (existing != null && existing >= 1) {
return new FlowsPreview(entityId, tableName, true, persistedFlows(entityId));
}
return new FlowsPreview(entityId, tableName, false, synthesizedFlows(entityId, tableName));
}
private List<FlowItem> synthesizedFlows(String entityId, String tableName) {
List<FlowItem> out = new ArrayList<>();
for (String[] f : BASE_FLOWS) {
out.add(new FlowItem(tableName + f[0], tableName + " " + f[2], f[1]));
}
Integer hasStatus = jdbcTemplate.queryForObject(
"SELECT COUNT(*) FROM SYS_ENTITYATTRIBUTE WHERE entityid=? AND UPPER(TRIM(columnname))='STATUS'",
Integer.class, entityId);
if (hasStatus != null && hasStatus >= 1) {
for (String[] f : STATUS_FLOWS) {
out.add(new FlowItem(tableName + f[0], tableName + " " + f[2], f[1]));
}
}
return out;
}
private List<FlowItem> persistedFlows(String entityId) {
List<Map<String, Object>> rows = jdbcTemplate.queryForList(
"SELECT TRIM(sys_serviceflow_id) AS fid, displayname FROM SYS_SERVICEFLOW WHERE entityid=?"
+ " ORDER BY sys_serviceflow_id", entityId);
List<FlowItem> out = new ArrayList<>();
for (Map<String, Object> r : rows) {
String fid = String.valueOf(r.get("fid"));
String display = r.get("displayname") == null ? fid : String.valueOf(r.get("displayname"));
out.add(new FlowItem(fid, display, kindOf(fid)));
}
return out;
}
private static String kindOf(String flowName) {
int us = flowName.indexOf('_');
if (us < 0) {
return "UNKNOWN";
}
return flowName.substring(us + 1);
}
}

View File

@@ -0,0 +1,21 @@
package com.eip4.platform.metadata.publish;
import java.util.List;
import java.util.Map;
/**
* Production 人审部署包(建物 3 · DECISION-2)。
*
* <p>与 platform-ai 的 {@code AiDeploymentPackage} 同形精简版:
* 不含 taskId/changeSetId/runEvidence(人走五环无 AiTask 上下文),其余字段一致。
* 恒 requiresHumanApproval=true —— 生产上线走既有人审流程,本包不执行任何生产 SQL。
*/
public record DeploymentPackage(
String status,
boolean requiresHumanApproval,
long generatedAt,
Map<String, Object> manifest,
List<String> sqlStatements,
List<String> rollbackSqlStatements,
List<String> warnings) {
}

View File

@@ -0,0 +1,111 @@
package com.eip4.platform.metadata.publish;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
/**
* 平台内自包含 production 部署包生成器(建物 3 · DECISION-2)。
*
* <p>不依赖 platform-ai(依赖图:platform-ai → platform-metadata,反向不可)。
* 从发布编排上下文合成 change-set,产出与 AiDeploymentPackage 同形的 {@link DeploymentPackage}。
* 产物为 production 人审草稿:manifest + 顺序 SQL(page_schema / serviceflow / menu)+ 对称 rollback。
* 实体 DDL 因不在此处掌握列定义,以占位 + warning 提示人工补全,恒 requiresHumanApproval=true。
*/
@Service
public class DeploymentPackageBuilder {
/** 发布编排上下文 → 部署包输入。 */
public record Input(
String entityId,
String tableName,
String templateId,
String menuName,
String menuId,
List<String> flows) {
}
public DeploymentPackage build(Input in) {
long now = System.currentTimeMillis();
Map<String, Object> manifest = new LinkedHashMap<>();
manifest.put("entityId", in.entityId());
manifest.put("templateId", in.templateId());
manifest.put("tableName", in.tableName());
manifest.put("menuId", in.menuId());
manifest.put("menuName", in.menuName());
manifest.put("flowCount", in.flows() == null ? 0 : in.flows().size());
manifest.put("flows", in.flows() == null ? List.of() : List.copyOf(in.flows()));
manifest.put("generatedAt", now);
manifest.put("source", "design-publish");
List<String> sql = new ArrayList<>();
sql.add("-- [1] 实体 DDL:本平台内 net-new 实体由元数据引擎建表,"
+ "生产环境请人工从源库导出 CREATE TABLE " + in.tableName() + " 及索引后置入此处。");
sql.add("-- [2] 标准层页面 schema(唯一真相 PageSchemaWriter.upsertStandard 的等价 SQL):");
sql.add("-- 生产请用导出的 schema JSON 替换 :schemaJson 占位");
// 列名严格对齐唯一写口 PageSchemaWriter.upsertStandard:
// (template_id, name, schema_json, schema_etag, version, update_time) + ON CONFLICT(template_id)。
// sys_page_schema 无 layer/updateby/updatetime 列,勿用(评审 §B.9-6 已核)。
sql.add("INSERT INTO sys_page_schema(template_id, name, schema_json, schema_etag, version, update_time)"
+ " VALUES(" + sqlString(in.templateId()) + ", " + sqlString(in.menuName())
+ ", :schemaJson, :schemaEtag, 1, " + now + ")"
+ " ON CONFLICT (template_id) DO UPDATE SET schema_json=EXCLUDED.schema_json,"
+ " schema_etag=EXCLUDED.schema_etag, version=sys_page_schema.version+1,"
+ " update_time=EXCLUDED.update_time;");
sql.add("-- [3] 默认服务流:生产请用导出的 contentxml 替换 :contentxml 占位");
if (in.flows() != null) {
for (String flow : in.flows()) {
sql.add("INSERT INTO sys_serviceflow(sys_serviceflow_id, displayname, contentxml, entityid)"
+ " VALUES(" + sqlString(flow) + ", " + sqlString(flow) + ", :contentxml, "
+ sqlString(in.entityId()) + ")"
+ " ON CONFLICT (sys_serviceflow_id) DO NOTHING;");
}
}
sql.add("-- [4] 功能菜单:生产请替换 ${parentMenuId}/${menuRoot} 为目标环境的菜单父节点");
sql.add("INSERT INTO sys_menu(sys_menu_id, name, parentid, view_templateid, typename, menuroot, seq,"
+ " isactive, version, createtime, createby, updatetime, updateby)"
+ " VALUES(" + sqlString(in.menuId()) + ", " + sqlString(in.menuName())
+ ", ${parentMenuId}, " + sqlString(in.templateId()) + ", '功能菜单', ${menuRoot}, 0,"
+ " 1, 0, " + now + ", 'DESIGN_PUBLISH', " + now + ", 'DESIGN_PUBLISH')"
+ " ON CONFLICT (sys_menu_id) DO NOTHING;");
List<String> rollback = new ArrayList<>();
rollback.add("UPDATE sys_menu SET isactive=0, updatetime=" + now
+ ", updateby='DESIGN_PUBLISH_ROLLBACK', version=version+1"
+ " WHERE TRIM(view_templateid)=" + sqlString(in.templateId()) + ";");
rollback.add("DELETE FROM sys_page_schema WHERE template_id=" + sqlString(in.templateId()) + ";");
if (in.flows() != null && !in.flows().isEmpty()) {
List<String> quoted = new ArrayList<>();
for (String flow : in.flows()) {
quoted.add(sqlString(flow));
}
rollback.add("DELETE FROM sys_serviceflow WHERE sys_serviceflow_id IN ("
+ String.join(", ", quoted) + ");");
}
rollback.add("-- 实体 DELETE:人工确认后 DELETE /api/meta/entity/" + in.tableName()
+ "(含物理表 DROP),并清理 SYS_ENTITY/SYS_ENTITYATTRIBUTE 元数据。");
List<String> warnings = new ArrayList<>();
warnings.add("实体 DDL 与 schema_json/contentxml 为占位,生产部署前须由人工从本地库导出真实定义置入。");
warnings.add("sys_menu 的 ${parentMenuId}/${menuRoot} 须替换为生产环境目标菜单父节点。");
warnings.add("本部署包恒人审:生产上线走既有人工审核流程,平台不自动在生产执行任何 SQL。");
return new DeploymentPackage(
"READY_FOR_HUMAN_REVIEW",
true,
now,
manifest,
List.copyOf(sql),
List.copyOf(rollback),
List.copyOf(warnings));
}
private static String sqlString(String value) {
String text = value == null ? "" : value;
return "'" + text.replace("'", "''") + "'";
}
}

View File

@@ -0,0 +1,104 @@
package com.eip4.platform.metadata.publish;
import java.util.List;
import java.util.UUID;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
/**
* 平台内菜单注册唯一入口(建物 3 · 发布编排)。
*
* <p>镜像 {@code AiLocalReleaseExecutor.applyMenu / ensureAiMenuParent}:
* dedup by view_templateid(同一页面只挂一条菜单,重复发布走 UPDATE 而非新建),
* parentMenuId 为空时自动 ensure/复用顶级目录「新功能」(人走五环语义;AI 链用「AI Agent」)。
*/
@Service
public class MenuRegistrar {
private static final String NEW_FEATURE_DIR = "新功能";
private final JdbcTemplate jdbcTemplate;
public MenuRegistrar(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* 注册/更新功能菜单。
*
* @param templateId 页面标准层 templateId(写入 sys_menu.view_templateid)
* @param menuName 菜单显示名
* @param parentMenuId 上级菜单 id;为空则自动挂到「新功能」顶级目录
* @param operator 操作人(写入 createby/updateby)
* @return sys_menu_id(新建则为新 UUID,命中则为既有 id)—— 幂等保证
*/
public String register(String templateId, String menuName, String parentMenuId, String operator) {
List<String> existing = jdbcTemplate.queryForList(
"SELECT TRIM(sys_menu_id) FROM sys_menu WHERE TRIM(view_templateid)=? AND isactive=1",
String.class, templateId);
long now = System.currentTimeMillis();
if (!existing.isEmpty()) {
String menuId = existing.get(0);
jdbcTemplate.update(
"UPDATE sys_menu SET name=?, view_templateid=?, updatetime=?, updateby=?, version=version+1"
+ " WHERE TRIM(sys_menu_id)=?",
menuName, templateId, now, operator, menuId);
return menuId;
}
String parentId = parentMenuId;
String menuRoot;
if (parentId == null || parentId.isBlank()) {
ParentMenu parent = ensureNewFeatureParent();
parentId = parent.parentId();
menuRoot = parent.menuRoot();
} else {
List<String> roots = jdbcTemplate.queryForList(
"SELECT TRIM(menuroot) FROM sys_menu WHERE TRIM(sys_menu_id)=?", String.class, parentId);
menuRoot = roots.isEmpty() ? null : roots.get(0);
}
String menuId = UUID.randomUUID().toString();
jdbcTemplate.update(
"INSERT INTO sys_menu(sys_menu_id, name, parentid, view_templateid, typename, menuroot, seq,"
+ " isactive, version, createtime, createby, updatetime, updateby)"
+ " VALUES(?,?,?,?,?,?,?,1,0,?,?,?,?)",
menuId, menuName, parentId, templateId, "功能菜单",
(menuRoot == null || menuRoot.isBlank()) ? null : menuRoot, 0,
now, operator, now, operator);
return menuId;
}
private ParentMenu ensureNewFeatureParent() {
List<String> existingDir = jdbcTemplate.queryForList(
"SELECT TRIM(sys_menu_id) FROM sys_menu WHERE name='" + NEW_FEATURE_DIR
+ "' AND parentid IS NULL AND isactive=1 ORDER BY seq LIMIT 1",
String.class);
if (!existingDir.isEmpty()) {
List<String> roots = jdbcTemplate.queryForList(
"SELECT TRIM(menuroot) FROM sys_menu WHERE TRIM(sys_menu_id)=?",
String.class, existingDir.get(0));
return new ParentMenu(existingDir.get(0), roots.isEmpty() ? "" : roots.get(0));
}
List<String> roots = jdbcTemplate.queryForList(
"SELECT TRIM(sys_menu_root_id) FROM sys_menu_root WHERE isactive=1 ORDER BY seq LIMIT 1",
String.class);
if (roots.isEmpty()) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "缺少 sys_menu_root,不能自动挂载菜单");
}
String root = roots.get(0);
String dirId = UUID.randomUUID().toString();
long now = System.currentTimeMillis();
jdbcTemplate.update(
"INSERT INTO sys_menu(sys_menu_id, name, parentid, view_templateid, typename, menuroot, seq,"
+ " isactive, version, createtime, createby, updatetime, updateby)"
+ " VALUES(?,?,NULL,NULL,?,?,?,1,0,?,?,?,?)",
dirId, NEW_FEATURE_DIR, "目录", root, 9999, now, "DESIGN_PUBLISH", now, "DESIGN_PUBLISH");
return new ParentMenu(dirId, root);
}
private record ParentMenu(String parentId, String menuRoot) {}
}

View File

@@ -0,0 +1,69 @@
package com.eip4.platform.metadata.publish;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.springframework.stereotype.Service;
import com.dsasp.server.common.util.UserSession;
import com.eip4.platform.metadata.flow.FlowServiceWithSynthesis;
/**
* 发布编排(建物 3):发布按钮一次性完成 ①确保默认流落库 ②注册菜单 ③生成 production 部署包。
*
* <p>红线:本类只 live-apply 到当前连接库(菜单/流),生产部署包恒人审、不在此执行生产 SQL。
*/
@Service
public class PublishOrchestrator {
private final FlowServiceWithSynthesis flowService;
private final MenuRegistrar menuRegistrar; // Task 12 注入
private final DeploymentPackageBuilder deploymentPackageBuilder; // Task 13 注入
private final DefaultFlowPreviewService flowPreviewService; // flowNames 回填(复用 Task 10 预览服务)
public PublishOrchestrator(FlowServiceWithSynthesis flowService,
MenuRegistrar menuRegistrar,
DeploymentPackageBuilder deploymentPackageBuilder,
DefaultFlowPreviewService flowPreviewService) {
this.flowService = flowService;
this.menuRegistrar = menuRegistrar;
this.deploymentPackageBuilder = deploymentPackageBuilder;
this.flowPreviewService = flowPreviewService;
}
/**
* 确保实体的 5(+2) 条默认服务流落库(幂等)。
*
* @return true 表示本次新建了默认流;false 表示实体已有流(幂等无操作)。
*/
public boolean ensureFlows(String entityId) {
Properties ctx = UserSession.getAdmin();
return flowService.addDefaultFlowService(entityId, ctx);
}
/** 注册/更新功能菜单,返回 sys_menu_id(幂等)。 */
public String registerMenu(String templateId, String menuName, String parentMenuId, String operator) {
return menuRegistrar.register(templateId, menuName, parentMenuId, operator);
}
/** generateDeploymentPackage != false 时生成 production 人审部署包;否则返回 null。 */
public DeploymentPackage buildDeploymentPackage(String entityId, String tableName, String templateId,
String menuName, String menuId,
List<String> flows, boolean generate) {
if (!generate) {
return null;
}
return deploymentPackageBuilder.build(new DeploymentPackageBuilder.Input(
entityId, tableName, templateId, menuName, menuId, flows));
}
/** 返回实体当前持久化的流名列表(发布后读 SYS_SERVICEFLOW,经 Task 10 预览服务)。 */
public List<String> flowNames(String entityId) {
List<String> out = new ArrayList<>();
for (DefaultFlowPreviewService.FlowItem f : flowPreviewService.preview(entityId).flows()) {
out.add(f.flowName());
}
return out;
}
}

View File

@@ -120,13 +120,24 @@ public final class PageBlueprintCompiler {
continue;
}
ObjectNode column = columns.addObject();
column.put("name", field.name());
column.put("name", listColumnName(field));
column.put("label", field.label());
applyColumnRender(column, field.type());
}
return columns;
}
/**
* 列表列 name 解析:引用列改指 {@code <COL>_DISPLAY__}(运行时 _SEARCH 流注入显名,house-style,
* 见 FlowController.resolveRows / PickerController),其余列用原字段名。修「引用列显裸 id」。
*/
private static String listColumnName(PageBlueprintField field) {
if ("reference".equals(field.type()) && field.name() != null && !field.name().isBlank()) {
return field.name() + "_DISPLAY__";
}
return field.name();
}
/**
* 列渲染类型(对齐转换器 house-style):布尔列 → mapping(是/否),日期/时间列 → date/datetime
* 格式化;string/integer/number 保持纯文本(amis 默认渲染即正确)。纯由 blueprint field type
@@ -150,6 +161,11 @@ public final class PageBlueprintCompiler {
column.put("type", "datetime");
column.put("format", "YYYY-MM-DD HH:mm:ss");
}
case "reference" -> {
// 引用列:列 name 已在 listColumnName 改指 <COL>_DISPLAY__(运行时 _SEARCH 流
// 经 UserColumnResolver.resolveRows 注入显名)。此处保持纯文本渲染即可,
// 不引入新 amis 组件类型 → TypedPageSchemaValidator 白名单平凡通过。
}
default -> {
// string / integer / number:纯文本默认渲染即可。
}
@@ -259,7 +275,7 @@ public final class PageBlueprintCompiler {
continue;
}
ObjectNode column = columns.addObject();
column.put("name", field.name());
column.put("name", listColumnName(field));
column.put("label", field.label());
applyColumnRender(column, field.type());
}

View File

@@ -6,5 +6,13 @@ public record PageBlueprintField(
String type,
boolean required,
boolean listVisible,
boolean formVisible) {
boolean formVisible,
String referenceTable,
String displayColumn) {
/** 6-arg 兼容构造:非引用字段(referenceTable/displayColumn 置空)。保持既有调用方/测试零改。 */
public PageBlueprintField(String name, String label, String type,
boolean required, boolean listVisible, boolean formVisible) {
this(name, label, type, required, listVisible, formVisible, null, null);
}
}

View File

@@ -0,0 +1,94 @@
package com.eip4.platform.metadata.schema.blueprint;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* 共享蓝图装配器:实体属性 → 受控 {@link PageBlueprint} → {@link PageBlueprintCompiler#compile}。
*
* <p>人工单步端点(DesignFeatureController)与未来 AI 路径共用同一装配口径(DRY),UI/UE 规则集中在
* recipe/compiler 而非散落在调用方。本类不写库、不校验白名单(严格 typed 闸在端点层),只负责装配+编译。
*
* <p>装配口径镜像 {@code AiFeatureDraftGenerator.pageBlueprint}:tree-crud 的 PARENTID 列 listVisible=false;
* displayField 缺省回退首个 NAME/required 列。引用字段(type=reference + referenceTable/displayColumn)
* 透传到 {@link PageBlueprintField},由 compiler 渲染显名列(见 applyColumnRender)。
*/
public final class RecipePageComposer {
private final PageBlueprintCompiler compiler;
public RecipePageComposer(ObjectMapper objectMapper) {
this.compiler = new PageBlueprintCompiler(objectMapper);
}
public ObjectNode compose(Spec spec) {
if (spec == null) {
throw new IllegalArgumentException("compose spec 不能为空");
}
PageBlueprint blueprint = toBlueprint(spec);
return compiler.compile(blueprint);
}
PageBlueprint toBlueprint(Spec spec) {
List<PageBlueprintField> fields = new ArrayList<>();
for (AttrSpec attr : spec.attributes()) {
boolean treeParentField = PageBlueprint.RECIPE_TREE_CRUD.equals(spec.recipe())
&& "PARENTID".equals(attr.column());
fields.add(new PageBlueprintField(
attr.column(), attr.display(), attr.type(),
attr.required(), !treeParentField, true,
attr.referenceTable(), attr.displayColumn()));
}
String displayField = firstNonBlank(spec.displayField(), deriveDisplayField(spec.attributes()));
int pageSize = spec.pageSize() < 1 ? 20 : spec.pageSize();
// templateId 由端点层服务端生成;compose 阶段用占位(compiler.validate 只要求非空)。
return new PageBlueprint(
PageBlueprint.VERSION, spec.recipe(),
"compose-placeholder", spec.title(), spec.tableName(), spec.entityName(),
spec.tableName() + "_ID", displayField, fields,
true, true, true, pageSize);
}
private static String deriveDisplayField(List<AttrSpec> attrs) {
for (AttrSpec a : attrs) {
if ("NAME".equals(a.column()) || a.required()) {
return a.column();
}
}
return attrs.isEmpty() ? "NAME" : attrs.get(0).column();
}
private static String firstNonBlank(String preferred, String fallback) {
if (preferred != null && !preferred.isBlank()) {
return preferred.trim();
}
return fallback;
}
/** 装配输入:等价于 GET /api/meta/entity/{table}/attributes 的读取结果 + recipe/title/displayField/pageSize。 */
public record Spec(
String tableName,
String entityName,
String recipe,
String title,
String displayField,
int pageSize,
List<AttrSpec> attributes) {
public Spec {
attributes = attributes == null ? List.of() : List.copyOf(attributes);
}
}
/** 单个实体属性。referenceTable/displayColumn 仅引用列非空(type=reference)。 */
public record AttrSpec(
String column,
String display,
String type,
boolean required,
String referenceTable,
String displayColumn) {
}
}

View File

@@ -0,0 +1,320 @@
package com.eip4.platform.metadata.web;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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.PageSchemaWriter;
import com.eip4.platform.metadata.schema.TypedPageSchemaReport;
import com.eip4.platform.metadata.schema.TypedPageSchemaValidator;
import com.eip4.platform.metadata.schema.blueprint.PageBlueprint;
import com.eip4.platform.metadata.schema.blueprint.RecipePageComposer;
import com.eip4.platform.metadata.web.EntityAttributeReader.EntityAttribute;
import com.eip4.platform.metadata.web.EntityAttributeReader.EntityAttributes;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
/**
* 设计中心新建(人走五环)单步端点(建物 2)。
*
* <p>{@code POST /api/design/recipe/compile}:读实体属性 → RecipePageComposer 装配+编译 → 服务端生成
* templateId → 严格 typed 校验(recipe 产物受白名单约束,必须过;不过 400)→ PageSchemaWriter.upsertStandard
* 落标准层(唯一真相,无裸 INSERT)。本端点不触发审批/发布(发布在 /api/design/publish,恒人审)。
*/
@Tag(name = "设计中心新建", description = "人走五环 · recipe→默认页→落标准层单步端点(建物 2)")
@RestController
@RequestMapping("/api/design")
public class DesignFeatureController {
private static final Logger log = LoggerFactory.getLogger(DesignFeatureController.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private final PageSchemaWriter pageSchemaWriter;
private final EntityAttributeReader attributeReader;
private final RecipePageComposer composer;
private final TypedPageSchemaValidator strictValidator;
private final JdbcTemplate jdbcTemplate; // 仅 requireAdmin 用
private final boolean skipAdminCheck; // 仅单测置 true
private final com.eip4.platform.metadata.publish.DefaultFlowPreviewService flowPreviewService; // Task 10
private final com.eip4.platform.metadata.publish.PublishOrchestrator publishOrchestrator; // Task 11-13
/** 生产构造(Spring 注入)。 */
@Autowired
public DesignFeatureController(JdbcTemplate jdbcTemplate,
PageSchemaWriter pageSchemaWriter,
EntityAttributeReader attributeReader,
com.eip4.platform.metadata.publish.DefaultFlowPreviewService flowPreviewService,
com.eip4.platform.metadata.publish.PublishOrchestrator publishOrchestrator) {
this.jdbcTemplate = jdbcTemplate;
this.pageSchemaWriter = pageSchemaWriter;
this.attributeReader = attributeReader;
this.flowPreviewService = flowPreviewService;
this.publishOrchestrator = publishOrchestrator;
this.composer = new RecipePageComposer(MAPPER);
this.strictValidator = TypedPageSchemaValidator.defaults();
this.skipAdminCheck = false;
}
/** 包级测试构造:脱库 + 可旁路 admin 门禁(发布编排依赖在 compile 单测中置 null)。 */
DesignFeatureController(PageSchemaWriter pageSchemaWriter,
EntityAttributeReader attributeReader,
boolean skipAdminCheck) {
this.jdbcTemplate = null;
this.pageSchemaWriter = pageSchemaWriter;
this.attributeReader = attributeReader;
this.flowPreviewService = null;
this.publishOrchestrator = null;
this.composer = new RecipePageComposer(MAPPER);
this.strictValidator = TypedPageSchemaValidator.defaults();
this.skipAdminCheck = skipAdminCheck;
}
@Operation(summary = "recipe 编译默认页并落标准层(仅管理员)",
description = "服务端生成 templateId;严格 typed 校验不过 400;写入只走 PageSchemaWriter.upsertStandard")
@PostMapping("/recipe/compile")
public ResponseEntity<Map<String, Object>> compile(@RequestBody CompileRequest req) {
requireAdmin();
if (req == null || isBlank(req.tableName) || isBlank(req.title)) {
return ResponseEntity.badRequest().body(fail("tableName 和 title 不能为空"));
}
String recipe = isBlank(req.recipe) ? PageBlueprint.RECIPE_MAINTENANCE_CRUD : req.recipe.trim();
if (!PageBlueprint.RECIPE_MAINTENANCE_CRUD.equals(recipe)
&& !PageBlueprint.RECIPE_TREE_CRUD.equals(recipe)) {
return ResponseEntity.badRequest().body(fail("不支持的 recipe: " + recipe));
}
int pageSize = req.pageSize == null || req.pageSize < 1 ? 20 : req.pageSize;
// 1. 读实体属性
EntityAttributes attrs;
try {
attrs = attributeReader.read(req.tableName.trim());
} catch (DataAccessException ex) {
return ResponseEntity.badRequest().body(fail("读取实体属性失败:" + ex.getMessage()));
}
if (attrs == null || attrs.columns().isEmpty()) {
return ResponseEntity.badRequest().body(fail("实体无可用属性: " + req.tableName));
}
// 2. 装配 + 编译(引用字段透传 referenceTable)
List<RecipePageComposer.AttrSpec> specAttrs = new ArrayList<>();
for (EntityAttribute a : attrs.columns()) {
specAttrs.add(new RecipePageComposer.AttrSpec(
a.column(), a.display(), a.type(), a.required(), a.referenceTable(), null));
}
String displayField = isBlank(req.displayField) ? attrs.displayColumn() : req.displayField.trim();
ObjectNode schema = composer.compose(new RecipePageComposer.Spec(
req.tableName.trim(), entityNameOf(req), recipe, req.title.trim(),
displayField, pageSize, specAttrs));
String schemaJson;
try {
schemaJson = MAPPER.writeValueAsString(schema);
} catch (JsonProcessingException ex) {
return ResponseEntity.internalServerError().body(fail("schema 序列化失败"));
}
// 3. 严格 typed 校验(recipe 产物白名单约束,必须过;不过 400)
TypedPageSchemaReport report = strictValidator.validate(schemaJson);
if (!report.valid()) {
Map<String, Object> data = new LinkedHashMap<>();
data.put("issues", report.issues());
return ResponseEntity.badRequest().body(fail("recipe 产物 typed 校验未通过(应为白名单组件)", data));
}
// 4. 服务端生成 templateId(绝不用调用方指定值,避免 UPSERT 覆盖既有页)
String templateId = "design-" + req.tableName.trim().toLowerCase(Locale.ROOT).replace('_', '-')
+ "-" + UUID.randomUUID().toString().substring(0, 8);
// 5. 经唯一真相 writer 落标准层
String etag;
try {
etag = pageSchemaWriter.upsertStandard(templateId, req.title.trim(), schemaJson, currentUserId());
} catch (DataAccessException ex) {
log.error("[design-compile] 标准层写入失败 templateId={}: {}", templateId, ex.getMessage());
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
.body(fail("标准层写入失败:" + ex.getMessage()));
}
Map<String, Object> data = new LinkedHashMap<>();
data.put("templateId", templateId);
data.put("etag", etag);
log.info("[design-compile] operator={} table={} recipe={} templateId={}",
currentUserId(), req.tableName, recipe, templateId);
return ResponseEntity.ok(ok("默认页已编译并落标准层", data));
}
private static String entityNameOf(CompileRequest req) {
return isBlank(req.entityName) ? req.title.trim() : req.entityName.trim();
}
@Operation(summary = "列出实体的 5(+2) 条默认服务流供人工确认(仅管理员)",
description = "未落库则合成预览(含 STATUS 列 +2),已落库则读 SYS_SERVICEFLOW 真实行")
@org.springframework.web.bind.annotation.GetMapping("/flows")
public Map<String, Object> flows(
@org.springframework.web.bind.annotation.RequestParam("entityId") String entityId) {
requireAdmin();
com.eip4.platform.metadata.publish.DefaultFlowPreviewService.FlowsPreview p =
flowPreviewService.preview(entityId);
List<Map<String, Object>> flowList = new ArrayList<>();
for (com.eip4.platform.metadata.publish.DefaultFlowPreviewService.FlowItem f : p.flows()) {
Map<String, Object> m = new LinkedHashMap<>();
m.put("flowName", f.flowName());
m.put("displayName", f.displayName());
m.put("kind", f.kind());
flowList.add(m);
}
Map<String, Object> data = new LinkedHashMap<>();
data.put("entityId", p.entityId());
data.put("tableName", p.tableName());
data.put("persisted", p.persisted());
data.put("flows", flowList);
Map<String, Object> resp = new LinkedHashMap<>();
resp.put("status", 0);
resp.put("data", data);
return resp;
}
@Operation(summary = "发布:确保默认流落库 + 注册菜单 + 产 production 人审部署包(仅管理员)",
description = "对当前连接库 live-apply(流/菜单),生产部署包恒人审,不在此执行生产 SQL")
@PostMapping("/publish")
public Map<String, Object> publish(@RequestBody Map<String, Object> body) {
requireAdmin();
String entityId = requireDesignString(body, "entityId");
String tableName = requireDesignString(body, "tableName");
String templateId = requireDesignString(body, "templateId");
String menuName = requireDesignString(body, "menuName");
String operator = currentUserId();
boolean flowsCreated = publishOrchestrator.ensureFlows(entityId);
Map<String, Object> data = new LinkedHashMap<>();
data.put("entityId", entityId);
data.put("tableName", tableName);
data.put("templateId", templateId);
data.put("flowsCreated", flowsCreated);
data.put("flows", publishOrchestrator.flowNames(entityId));
String parentMenuId = body.get("parentMenuId") == null ? null : body.get("parentMenuId").toString().trim();
String menuId = publishOrchestrator.registerMenu(templateId, menuName, parentMenuId, operator);
data.put("menuId", menuId);
boolean generatePkg = !(Boolean.FALSE.equals(body.get("generateDeploymentPackage")));
@SuppressWarnings("unchecked")
List<String> flowsForPkg = (List<String>) data.get("flows");
com.eip4.platform.metadata.publish.DeploymentPackage pkg = publishOrchestrator.buildDeploymentPackage(
entityId, tableName, templateId, menuName, menuId, flowsForPkg, generatePkg);
if (pkg != null) {
Map<String, Object> pkgMap = new LinkedHashMap<>();
pkgMap.put("status", pkg.status());
pkgMap.put("requiresHumanApproval", pkg.requiresHumanApproval());
pkgMap.put("generatedAt", pkg.generatedAt());
pkgMap.put("manifest", pkg.manifest());
pkgMap.put("sqlStatements", pkg.sqlStatements());
pkgMap.put("rollbackSqlStatements", pkg.rollbackSqlStatements());
pkgMap.put("warnings", pkg.warnings());
data.put("deploymentPackage", pkgMap);
}
Map<String, Object> resp = new LinkedHashMap<>();
resp.put("status", 0);
resp.put("data", data);
return resp;
}
private static String requireDesignString(Map<String, Object> body, String key) {
Object v = body == null ? null : body.get(key);
if (v == null || v.toString().isBlank()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "缺少必填参数: " + key);
}
return v.toString().trim();
}
// ===== admin 门禁(逐字对齐 PageSchemaController.requireAdmin / currentUserId)=====
private void requireAdmin() {
if (skipAdminCheck) {
return;
}
java.util.Properties ctx = UserSession.get();
if (ctx == null) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "未登录,禁止访问设计端点");
}
String cu = ctx.getProperty(LoggedInUser.CURRENTUSER, "").trim();
if (cu.isEmpty()) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "未登录,禁止访问设计端点");
}
if ("ADMIN".equalsIgnoreCase(cu)) {
return;
}
Integer cnt = jdbcTemplate.queryForObject(
"SELECT COUNT(*) FROM sys_user WHERE TRIM(sys_user_id)=? AND TRIM(account)='admin'",
Integer.class, cu);
if (cnt == null || cnt == 0) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "仅系统管理员可执行设计端点");
}
}
private static String currentUserId() {
java.util.Properties ctx = UserSession.get();
if (ctx == null) return "UNKNOWN";
String u = ctx.getProperty(LoggedInUser.CURRENTUSER, "UNKNOWN");
return u.isBlank() ? "UNKNOWN" : u.trim();
}
private static boolean isBlank(String s) {
return s == null || s.isBlank();
}
private static Map<String, Object> ok(String msg, Map<String, Object> data) {
Map<String, Object> r = new LinkedHashMap<>();
r.put("status", 0);
r.put("msg", msg);
if (data != null) r.put("data", data);
return r;
}
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;
}
/** POST /api/design/recipe/compile 请求体。 */
public static class CompileRequest {
public String tableName;
public String recipe;
public String title;
public String entityName;
public String displayField;
public Integer pageSize;
}
}

View File

@@ -0,0 +1,56 @@
package com.eip4.platform.metadata.web;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import com.eip4.platform.metadata.meta.EntityAttributesService;
/**
* 读实体属性给设计单步端点用,等价 GET /api/meta/entity/{table}/attributes 的 data 部分。
*
* <p>第 1 节已提供属性服务 bean({@link EntityAttributesService});本默认实现委托它,契约不变。
* 引用列 type=="reference" 且 referenceTable 非空,由第 1 节 createEntity 写入的 SYS_REFERENCE 行驱动。
*/
public interface EntityAttributeReader {
EntityAttributes read(String tableName);
record EntityAttributes(String tablename, String displayColumn, List<EntityAttribute> columns) {
public EntityAttributes {
columns = columns == null ? List.of() : List.copyOf(columns);
}
}
record EntityAttribute(String column, String display, String type,
boolean required, String referenceTable) {
}
/**
* 默认实现:委托第 1 节 Task 2 抽出的 {@link EntityAttributesService}(@Component)。
* 【评审 §B.9-3】真实表是 SYS_ENTITYATTRIBUTE(无 table_name 列,靠 entityid ⋈ SYS_ENTITY 过滤),
* 列名是 columnname/displayname/referenceid/ismandatory/entitydisplayseq;引用列的目标表名须由
* REFERENCEID(36 位 uuid)经 {@code DataDicService.getReferenceEntityTableName} 反解——纯 JdbcTemplate 做不到。
* 故本类不自写 SQL,统一委托第 1 节的服务 bean,保证人工 compile 与 GET /api/meta/entity/{table}/attributes 同源同结果。
*/
@Component
class DelegatingEntityAttributeReader implements EntityAttributeReader {
private final EntityAttributesService service; // 第 1 节 Task 2 产出,见 §B.9-3
public DelegatingEntityAttributeReader(EntityAttributesService service) {
this.service = service;
}
@Override
public EntityAttributes read(String tableName) {
EntityAttributesService.Result r = service.read(tableName); // {tablename, displayColumn, columns[]}
List<EntityAttribute> cols = new ArrayList<>();
for (EntityAttributesService.Column c : r.columns()) {
// c.referenceTable() 已由 service 经 getReferenceEntityTableName 反解(引用列非空,否则 null)
cols.add(new EntityAttribute(c.column(), c.display(), c.type(), c.mandatory(), c.referenceTable()));
}
return new EntityAttributes(r.tablename(), r.displayColumn(), cols);
}
}
}

View File

@@ -0,0 +1,58 @@
package com.eip4.platform.metadata.publish;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;
class DefaultFlowPreviewServiceTest {
@Test
void synthesizesFiveFlowsWhenNoServiceflowAndNoStatusColumn() {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
// 无持久流
when(jdbc.queryForObject(
eq("SELECT COUNT(*) FROM SYS_SERVICEFLOW WHERE entityid=?"),
eq(Integer.class), eq("ENT-1"))).thenReturn(0);
// 实体表名
when(jdbc.queryForObject(
eq("SELECT TRIM(tablename) FROM SYS_ENTITY WHERE TRIM(sys_entity_id)=?"),
eq(String.class), eq("ENT-1"))).thenReturn("DEMO_TBL");
// 无 STATUS 列
when(jdbc.queryForObject(
eq("SELECT COUNT(*) FROM SYS_ENTITYATTRIBUTE WHERE entityid=? AND UPPER(TRIM(columnname))='STATUS'"),
eq(Integer.class), eq("ENT-1"))).thenReturn(0);
DefaultFlowPreviewService svc = new DefaultFlowPreviewService(jdbc);
DefaultFlowPreviewService.FlowsPreview preview = svc.preview("ENT-1");
assertThat(preview.persisted()).isFalse();
assertThat(preview.tableName()).isEqualTo("DEMO_TBL");
assertThat(preview.flows()).extracting(DefaultFlowPreviewService.FlowItem::flowName)
.containsExactly("DEMO_TBL_ADD", "DEMO_TBL_DELETE", "DEMO_TBL_UPDATE",
"DEMO_TBL_SEARCH", "DEMO_TBL_LOAD");
assertThat(preview.flows().get(0).kind()).isEqualTo("ADD");
}
@Test
void synthesizesSevenFlowsWhenStatusColumnPresent() {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
when(jdbc.queryForObject(
eq("SELECT COUNT(*) FROM SYS_SERVICEFLOW WHERE entityid=?"),
eq(Integer.class), eq("ENT-2"))).thenReturn(0);
when(jdbc.queryForObject(
eq("SELECT TRIM(tablename) FROM SYS_ENTITY WHERE TRIM(sys_entity_id)=?"),
eq(String.class), eq("ENT-2"))).thenReturn("OA_DOC");
when(jdbc.queryForObject(
eq("SELECT COUNT(*) FROM SYS_ENTITYATTRIBUTE WHERE entityid=? AND UPPER(TRIM(columnname))='STATUS'"),
eq(Integer.class), eq("ENT-2"))).thenReturn(1);
DefaultFlowPreviewService.FlowsPreview p = new DefaultFlowPreviewService(jdbc).preview("ENT-2");
assertThat(p.flows()).extracting(DefaultFlowPreviewService.FlowItem::flowName)
.contains("OA_DOC_SUBMIT", "OA_DOC_SAVE_AND_SUBMIT");
assertThat(p.flows()).hasSize(7);
}
}

View File

@@ -0,0 +1,38 @@
package com.eip4.platform.metadata.publish;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.jupiter.api.Test;
class DeploymentPackageBuilderTest {
@Test
void buildProducesManifestRollbackAndRequiresHumanApproval() {
DeploymentPackageBuilder builder = new DeploymentPackageBuilder();
DeploymentPackageBuilder.Input input = new DeploymentPackageBuilder.Input(
"ENT-1", "DEMO_TBL", "TPL-1", "演示功能", "MENU-1",
List.of("DEMO_TBL_ADD", "DEMO_TBL_UPDATE", "DEMO_TBL_SEARCH",
"DEMO_TBL_DELETE", "DEMO_TBL_LOAD"));
DeploymentPackage pkg = builder.build(input);
assertThat(pkg.requiresHumanApproval()).isTrue();
assertThat(pkg.status()).isEqualTo("READY_FOR_HUMAN_REVIEW");
assertThat(pkg.manifest()).containsKeys("entityId", "templateId", "tableName", "menuId", "flowCount");
assertThat(pkg.manifest().get("flowCount")).isEqualTo(5);
// SQL 草稿覆盖四类工件
assertThat(pkg.sqlStatements()).anyMatch(s -> s.contains("sys_page_schema"));
assertThat(pkg.sqlStatements()).anyMatch(s -> s.contains("sys_serviceflow"));
assertThat(pkg.sqlStatements()).anyMatch(s -> s.contains("sys_menu"));
// §B.9-6: 真实列对齐——sys_page_schema 无 layer 列,SQL 不得出现 'layer'
assertThat(pkg.sqlStatements()).noneMatch(s -> s.contains("layer"));
// rollback 对称且含 DELETE
assertThat(pkg.rollbackSqlStatements()).anyMatch(s -> s.contains("DELETE FROM sys_page_schema"));
assertThat(pkg.rollbackSqlStatements()).anyMatch(s -> s.contains("DELETE FROM sys_serviceflow"));
assertThat(pkg.rollbackSqlStatements()).anyMatch(s -> s.contains("sys_menu"));
// 生产 DDL 由人工补全 → warning
assertThat(pkg.warnings()).isNotEmpty();
}
}

View File

@@ -0,0 +1,62 @@
package com.eip4.platform.metadata.publish;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;
class MenuRegistrarTest {
@Test
void firstRegisterInsertsOneRowUnderNewFeatureParent() {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
// dedup 查:无现有菜单
when(jdbc.queryForList(
eq("SELECT TRIM(sys_menu_id) FROM sys_menu WHERE TRIM(view_templateid)=? AND isactive=1"),
eq(String.class), eq("TPL-1"))).thenReturn(List.of());
// ensure '新功能' 目录:已存在,返回其 id
when(jdbc.queryForList(
eq("SELECT TRIM(sys_menu_id) FROM sys_menu WHERE name='新功能' AND parentid IS NULL AND isactive=1 ORDER BY seq LIMIT 1"),
eq(String.class))).thenReturn(List.of("DIR-NEW"));
when(jdbc.queryForList(
eq("SELECT TRIM(menuroot) FROM sys_menu WHERE TRIM(sys_menu_id)=?"),
eq(String.class), eq("DIR-NEW"))).thenReturn(List.of("ROOT-1"));
MenuRegistrar reg = new MenuRegistrar(jdbc);
String menuId = reg.register("TPL-1", "演示功能", null, "admin");
assertThat(menuId).isNotBlank();
// 校验 INSERT 被调用一次(11 个绑定参数,含 templateId / parentId / menuRoot)。
verify(jdbc, times(1)).update(
anyString(),
eq(menuId), eq("演示功能"), eq("DIR-NEW"), eq("TPL-1"),
eq("功能菜单"), eq("ROOT-1"), eq(0),
any(), eq("admin"), any(), eq("admin"));
}
@Test
void republishDedupsByTemplateIdAndUpdatesInsteadOfInsert() {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
when(jdbc.queryForList(
eq("SELECT TRIM(sys_menu_id) FROM sys_menu WHERE TRIM(view_templateid)=? AND isactive=1"),
eq(String.class), eq("TPL-1"))).thenReturn(List.of("MENU-EXIST"));
MenuRegistrar reg = new MenuRegistrar(jdbc);
String menuId = reg.register("TPL-1", "演示功能改名", null, "admin");
assertThat(menuId).isEqualTo("MENU-EXIST");
// 命中 → 不查 '新功能' 目录、不 INSERT,只 UPDATE(5 个绑定参数)。
verify(jdbc, times(1)).update(
org.mockito.ArgumentMatchers.contains("UPDATE sys_menu"),
eq("演示功能改名"), eq("TPL-1"), any(), eq("admin"), eq("MENU-EXIST"));
}
}

View File

@@ -0,0 +1,38 @@
package com.eip4.platform.metadata.publish;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import com.eip4.platform.metadata.flow.FlowServiceWithSynthesis;
class PublishFlowEnsureTest {
@Test
void ensureFlowsDelegatesToAddDefaultFlowServiceAndReportsCreated() {
FlowServiceWithSynthesis flowService = mock(FlowServiceWithSynthesis.class);
when(flowService.addDefaultFlowService(eq("ENT-9"), any(Properties.class))).thenReturn(true);
PublishOrchestrator orch = new PublishOrchestrator(flowService, null, null, null);
boolean created = orch.ensureFlows("ENT-9");
assertThat(created).isTrue();
verify(flowService).addDefaultFlowService(eq("ENT-9"), any(Properties.class));
}
@Test
void ensureFlowsReturnsFalseWhenFlowsAlreadyPresent() {
FlowServiceWithSynthesis flowService = mock(FlowServiceWithSynthesis.class);
when(flowService.addDefaultFlowService(eq("ENT-9"), any(Properties.class))).thenReturn(false);
PublishOrchestrator orch = new PublishOrchestrator(flowService, null, null, null);
assertThat(orch.ensureFlows("ENT-9")).isFalse();
}
}

View File

@@ -191,4 +191,34 @@ class PageBlueprintCompilerTest {
assertThrows(IllegalArgumentException.class, () -> new PageBlueprintCompiler(MAPPER).compile(blueprint));
}
@Test
@DisplayName("引用列渲染显名: list 列 name 指向 <COL>_DISPLAY__(运行时 _SEARCH 注入显名),非裸 id")
void referenceColumnRendersDisplayName() {
PageBlueprint blueprint = new PageBlueprint(
PageBlueprint.VERSION,
PageBlueprint.RECIPE_MAINTENANCE_CRUD,
"eip4ai-order",
"订单维护",
"EIP4AI_ORDER",
"订单",
"EIP4AI_ORDER_ID",
"ORDERNO",
List.of(
new PageBlueprintField("ORDERNO", "订单号", "string", true, true, true, null, null),
// 引用列:指向 EIP4AI_CUSTOMER,显名列 NAME
new PageBlueprintField("CUSTOMERID", "客户", "reference", false, true, true,
"EIP4AI_CUSTOMER", "NAME")),
true, true, true, 20);
ObjectNode schema = new PageBlueprintCompiler(MAPPER).compile(blueprint);
ArrayNode columns = (ArrayNode) schema.path("body").path("columns");
assertEquals(2, columns.size());
assertEquals("ORDERNO", columns.get(0).path("name").asText());
// 引用列:name 改指显名列,label 仍是业务标签,纯文本(无特殊 type → typed 白名单安全)。
assertEquals("CUSTOMERID_DISPLAY__", columns.get(1).path("name").asText());
assertEquals("客户", columns.get(1).path("label").asText());
assertTrue(columns.get(1).path("type").asText().isBlank());
}
}

View File

@@ -0,0 +1,100 @@
package com.eip4.platform.metadata.schema.blueprint;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
class RecipePageComposerTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private final RecipePageComposer composer = new RecipePageComposer(MAPPER);
@Test
@DisplayName("1. compose maintenance-crud → crud.api == /api/flow/<TABLE>_SEARCH,列= listVisible 业务列")
void composesMaintenanceCrud() {
RecipePageComposer.Spec spec = new RecipePageComposer.Spec(
"EIP4AI_CUSTOMER", "客户", PageBlueprint.RECIPE_MAINTENANCE_CRUD,
"客户维护", "NAME", 20,
List.of(
new RecipePageComposer.AttrSpec("NAME", "名称", "string", true, null, null),
new RecipePageComposer.AttrSpec("LEVEL", "等级", "integer", false, null, null)));
ObjectNode page = composer.compose(spec);
assertEquals("page", page.path("type").asText());
assertEquals("客户维护", page.path("title").asText());
ObjectNode crud = (ObjectNode) page.path("body");
assertEquals("/api/flow/EIP4AI_CUSTOMER_SEARCH", crud.path("api").asText());
ArrayNode columns = (ArrayNode) crud.path("columns");
assertEquals(2, columns.size());
assertEquals("NAME", columns.get(0).path("name").asText());
assertEquals("LEVEL", columns.get(1).path("name").asText());
}
@Test
@DisplayName("2. compose tree-crud → 注入 PARENTID 字段且列表不显示该列")
void composesTreeCrudWithParent() {
RecipePageComposer.Spec spec = new RecipePageComposer.Spec(
"EIP4AI_CATEGORY", "分类", PageBlueprint.RECIPE_TREE_CRUD,
"分类维护", "NAME", 20,
List.of(
new RecipePageComposer.AttrSpec("NAME", "名称", "string", true, null, null),
new RecipePageComposer.AttrSpec("PARENTID", "上级", "string", false, null, null)));
ObjectNode page = composer.compose(spec);
ObjectNode crud = (ObjectNode) page.path("body");
assertEquals("eip4aiCategoryTreeCrud", crud.path("name").asText());
// 业务列里不含 PARENTID(compiler.treeColumns 跳过 PARENTID),但保留「操作」列。
ArrayNode columns = (ArrayNode) crud.path("columns");
boolean hasParentColumn = false;
for (int i = 0; i < columns.size(); i++) {
if ("PARENTID".equals(columns.get(i).path("name").asText())) {
hasParentColumn = true;
}
}
assertTrue(!hasParentColumn);
}
@Test
@DisplayName("3. displayField 省略时回退首个 NAME/required 列")
void derivesDisplayFieldWhenBlank() {
RecipePageComposer.Spec spec = new RecipePageComposer.Spec(
"EIP4AI_ITEM", "条目", PageBlueprint.RECIPE_MAINTENANCE_CRUD,
"条目维护", null, 20,
List.of(
new RecipePageComposer.AttrSpec("CODE", "编码", "string", false, null, null),
new RecipePageComposer.AttrSpec("NAME", "名称", "string", true, null, null)));
ObjectNode page = composer.compose(spec);
// displayField 回退到 NAME,filter 兜底用它(此处只需 compose 成功不抛)。
assertEquals("page", page.path("type").asText());
}
@Test
@DisplayName("4. 端到端: compose 含 reference 列的页 → list 列 name 显名 <COL>_DISPLAY__")
void composeRendersReferenceDisplayEndToEnd() {
RecipePageComposer.Spec spec = new RecipePageComposer.Spec(
"EIP4AI_ORDER", "订单", PageBlueprint.RECIPE_MAINTENANCE_CRUD,
"订单维护", "ORDERNO", 20,
List.of(
new RecipePageComposer.AttrSpec("ORDERNO", "订单号", "string", true, null, null),
// 引用列:referenceTable 非空 + type=reference(端点层从 EntityAttribute 透传而来)
new RecipePageComposer.AttrSpec("CUSTOMERID", "客户", "reference", false,
"EIP4AI_CUSTOMER", "NAME")));
ObjectNode page = composer.compose(spec);
ArrayNode columns = (ArrayNode) page.path("body").path("columns");
assertEquals("ORDERNO", columns.get(0).path("name").asText());
assertEquals("CUSTOMERID_DISPLAY__", columns.get(1).path("name").asText());
assertEquals("客户", columns.get(1).path("label").asText());
}
}

View File

@@ -0,0 +1,89 @@
package com.eip4.platform.metadata.web;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.http.ResponseEntity;
import com.eip4.platform.metadata.schema.PageSchemaWriter;
import com.eip4.platform.metadata.web.EntityAttributeReader.EntityAttributes;
import com.eip4.platform.metadata.web.EntityAttributeReader.EntityAttribute;
class DesignFeatureControllerTest {
private DesignFeatureController controller(PageSchemaWriter writer, EntityAttributeReader reader) {
// 包级测试构造:跳过 admin 门禁(生产构造恒走 requireAdmin)。
return new DesignFeatureController(writer, reader, true);
}
@Test
@DisplayName("1. compile 返回服务端生成的 design- 前缀 templateId,并经 writer 落标准层一次")
void compileGeneratesTemplateIdAndWritesOnce() {
PageSchemaWriter writer = mock(PageSchemaWriter.class);
when(writer.upsertStandard(anyString(), anyString(), anyString(), anyString()))
.thenReturn("etag-deadbeef");
EntityAttributeReader reader = mock(EntityAttributeReader.class);
when(reader.read("EIP4AI_CUSTOMER")).thenReturn(new EntityAttributes(
"EIP4AI_CUSTOMER", "NAME", List.of(
new EntityAttribute("NAME", "名称", "string", true, null),
new EntityAttribute("LEVEL", "等级", "integer", false, null))));
var body = new DesignFeatureController.CompileRequest();
body.tableName = "EIP4AI_CUSTOMER";
body.recipe = "maintenance-crud-v1";
body.title = "客户维护";
body.pageSize = 20;
ResponseEntity<Map<String, Object>> resp = controller(writer, reader).compile(body);
assertEquals(200, resp.getStatusCode().value());
@SuppressWarnings("unchecked")
Map<String, Object> data = (Map<String, Object>) resp.getBody().get("data");
String tid = String.valueOf(data.get("templateId"));
assertTrue(tid.startsWith("design-eip4ai-customer-"), "templateId=" + tid);
assertEquals("etag-deadbeef", data.get("etag"));
// 标准层只经 writer 写一次,且 templateId == 返回值(非调用方指定)。
ArgumentCaptor<String> tidCap = ArgumentCaptor.forClass(String.class);
verify(writer).upsertStandard(tidCap.capture(), eq("客户维护"), anyString(), anyString());
assertEquals(tid, tidCap.getValue());
}
@Test
@DisplayName("2. tableName/title 为空 → 400,不读实体不写库")
void blankArgsRejected() {
PageSchemaWriter writer = mock(PageSchemaWriter.class);
EntityAttributeReader reader = mock(EntityAttributeReader.class);
var body = new DesignFeatureController.CompileRequest();
body.tableName = " ";
body.recipe = "maintenance-crud-v1";
body.title = "x";
ResponseEntity<Map<String, Object>> resp = controller(writer, reader).compile(body);
assertEquals(400, resp.getStatusCode().value());
}
@Test
@DisplayName("3. 装配回归:有两个构造器时,生产构造器必须 @Autowired,否则 Spring 回退无参构造启动崩(live e2e 揪出)")
void productionConstructorIsAutowired() {
// 本控制器同时有「生产构造」与「包级测试构造」两个构造器。
// Spring 对多构造器类必须靠 @Autowired 指定注入构造,否则找无参构造 → NoSuchMethodException 启动失败。
long autowired = java.util.Arrays.stream(DesignFeatureController.class.getDeclaredConstructors())
.filter(c -> c.isAnnotationPresent(org.springframework.beans.factory.annotation.Autowired.class))
.count();
assertEquals(1, autowired,
"DesignFeatureController 有多个构造器,生产构造器必须且仅一个标 @Autowired");
}
}

67
scripts/five-ring-acceptance.sh Executable file
View File

@@ -0,0 +1,67 @@
#!/usr/bin/env bash
# 人走五环建新功能 · 端到端验收脚本(实施计划 Section 6 / Task 24)
#
# 用法:先以 dev profile 启动后端(连 PG15 @5433/eip4dev),再跑本脚本:
# JAVA_HOME=/opt/homebrew/opt/openjdk@21 mvn -pl platform-app -am install -DskipTests
# java -jar platform-app/target/platform-app-0.1.0-SNAPSHOT.jar --spring.profiles.active=dev --server.port=8094 &
# BASE=http://localhost:8094 bash scripts/five-ring-acceptance.sh
#
# ── 2026-06-20 LIVE 验收实证(8094 + 真实 DB eip4dev,新代码全 23 任务 + @Autowired 修复)──
# 环①② 建实体 EIP4PT_FR_DEMO:status:0,9 字段含引用列 OWNER→SYS_USER(真建 SYS_REFERENCE + DDL 外键),表+索引落库
# attributes 端点:OWNER 反解 type=reference / referenceTable=SYS_USER(DECISION-1 端到端通)
# 环③ /api/design/recipe/compile:服务端生成 templateId=design-eip4pt-fr-demo-<8hex>,页 crud.api=/api/flow/EIP4PT_FR_DEMO_SEARCH,经 PageSchemaWriter 落标准层
# 环④ /api/design/flows:预览 5 流(ADD/UPDATE/SEARCH/DELETE/LOAD);/api/design/publish:flowsCreated=true、落 5 流 + 菜单节点
# + deploymentPackage{requiresHumanApproval:true, status:READY_FOR_HUMAN_REVIEW, 12 SQL, 4 rollback, 含 layer 列=false}
# 页面列表 /api/flow/EIP4PT_FR_DEMO_SEARCH:status:0(五流真可用)
# AI ①面 /api/ai/features/auto-develop:status=READY_FOR_HUMAN_REVIEW、PAGE_SCHEMA draft.targetId=<templateId>(进设计器 handoff)、requiresHumanApproval=true
# 红线全守:发布不自动执行生产 SQL(仅 live-apply 当前库 + 人审部署包);AI 产物恒 READY_FOR_HUMAN_REVIEW;标准层写仅经 PageSchemaWriter
# 验收后清理:DELETE /api/meta/entity/{EIP4PT_*} + psql 清 sys_page_schema/sys_menu/sys_serviceflow 测试行(残留 0)
set -euo pipefail
BASE=${BASE:-http://localhost:8094}
ACCT=${ACCT:-admin}; PW=${PW:-111111}
jqpy() { python3 -c "import sys,json;d=json.load(sys.stdin,strict=False);print(eval(\"d$1\"))"; }
TOK=$(curl -s -X POST "$BASE/api/auth/login" -H 'Content-Type: application/json' \
-d "{\"account\":\"$ACCT\",\"password\":\"$PW\"}" | jqpy "['token']")
H=(-H "Authorization: Bearer $TOK" -H 'Content-Type: application/json')
echo "[login] token len=${#TOK}"
echo "[环①②] 建实体 EIP4PT_FR_DEMO(含引用列 OWNER→SYS_USER)"
EID=$(curl -s -X POST "$BASE/api/meta/entity" "${H[@]}" -d '{
"tablename":"EIP4PT_FR_DEMO","name":"五环演示","description":"五环验收",
"attributes":[{"column":"TITLE","display":"标题","type":"string","length":200,"mandatory":true},
{"column":"OWNER","display":"负责人","type":"reference","referenceTable":"SYS_USER"}]}' | jqpy "['data']['entityId']")
echo " entityId=$EID"
curl -s "$BASE/api/meta/entity/EIP4PT_FR_DEMO/attributes" "${H[@]}" | jqpy "['data']['columns']"
echo "[环③] recipe 编译落标准层"
TID=$(curl -s -X POST "$BASE/api/design/recipe/compile" "${H[@]}" \
-d '{"tableName":"EIP4PT_FR_DEMO","recipe":"maintenance-crud-v1","title":"五环演示","displayField":"TITLE"}' | jqpy "['data']['templateId']")
echo " templateId=$TID"
curl -s "$BASE/api/page/schema/$TID" "${H[@]}" | jqpy "['body']['api']"
echo "[环④] 预览五流 + 发布"
curl -s "$BASE/api/design/flows?entityId=$EID" "${H[@]}" | jqpy "['data']['flows']"
curl -s -X POST "$BASE/api/design/publish" "${H[@]}" \
-d "{\"entityId\":\"$EID\",\"tableName\":\"EIP4PT_FR_DEMO\",\"templateId\":\"$TID\",\"menuName\":\"五环演示\",\"generateDeploymentPackage\":true}" \
| jqpy "['data']"
echo "[页面列表] /api/flow/EIP4PT_FR_DEMO_SEARCH"
curl -s -X POST "$BASE/api/flow/EIP4PT_FR_DEMO_SEARCH" "${H[@]}" -d '{}' | jqpy "['status']"
echo "[AI ①面] auto-develop(确定性,非 LLM)"
curl -s -X POST "$BASE/api/ai/features/auto-develop" "${H[@]}" --max-time 120 -d '{
"feature":{"objective":"AI演示","featureName":"AI演示","tableName":"EIP4PT_AIDEMO","entityName":"AI演示","menuName":"AI演示",
"fields":[{"column":"NAME","label":"名称","type":"string","length":100,"required":true}],"pageRecipe":"maintenance-crud-v1"},
"baseUrl":"'"$BASE"'","generateDeploymentPackage":true}' -o /tmp/ai-run.json
python3 - <<'PY'
import json; d=json.load(open('/tmp/ai-run.json'),strict=False)
ps=[x for x in d.get('development',{}).get('drafts',[]) if x.get('artifactType')=='PAGE_SCHEMA']
print(' status=',d.get('status'),' PAGE_SCHEMA.targetId=',ps[0].get('targetId') if ps else None,
' requiresHumanApproval=',d.get('deploymentPackage',{}).get('requiresHumanApproval'))
PY
echo "[清理] 删测试实体(EIP4 前缀门)"
for T in EIP4PT_FR_DEMO EIP4PT_AIDEMO; do curl -s -X DELETE "$BASE/api/meta/entity/$T" "${H[@]}"; echo; done
echo " 注:sys_page_schema/sys_menu/sys_serviceflow 净新行无运行时删除端点(§F follow-up),需手工 psql 清。"
echo "[完成] 五环 + AI ①面 端到端验收通过。"