From eabebae361cb0db28a33e6504e7f917e112991d4 Mon Sep 17 00:00:00 2001 From: zhengwr Date: Sat, 20 Jun 2026 09:53:49 +0800 Subject: [PATCH] =?UTF-8?q?feat(design):=20POST=20/api/design/recipe/compi?= =?UTF-8?q?le=20=E5=8D=95=E6=AD=A5=E7=AB=AF=E7=82=B9(=E5=BB=BA=E7=89=A92)?= =?UTF-8?q?=C2=B7=E6=9C=8D=E5=8A=A1=E7=AB=AF=E7=94=9F=E6=88=90=20templateI?= =?UTF-8?q?d+=E4=B8=A5=E6=A0=BC=20typed=20=E9=97=B8+=E5=94=AF=E4=B8=80?= =?UTF-8?q?=E7=9C=9F=E7=9B=B8=E8=90=BD=E6=A0=87=E5=87=86=E5=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 4.8 (1M context) --- .../metadata/web/DesignFeatureController.java | 228 ++++++++++++++++++ .../metadata/web/EntityAttributeReader.java | 56 +++++ .../web/DesignFeatureControllerTest.java | 77 ++++++ 3 files changed, 361 insertions(+) create mode 100644 platform-metadata/src/main/java/com/eip4/platform/metadata/web/DesignFeatureController.java create mode 100644 platform-metadata/src/main/java/com/eip4/platform/metadata/web/EntityAttributeReader.java create mode 100644 platform-metadata/src/test/java/com/eip4/platform/metadata/web/DesignFeatureControllerTest.java diff --git a/platform-metadata/src/main/java/com/eip4/platform/metadata/web/DesignFeatureController.java b/platform-metadata/src/main/java/com/eip4/platform/metadata/web/DesignFeatureController.java new file mode 100644 index 0000000..25680ee --- /dev/null +++ b/platform-metadata/src/main/java/com/eip4/platform/metadata/web/DesignFeatureController.java @@ -0,0 +1,228 @@ +package com.eip4.platform.metadata.web; + +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)。 + * + *

{@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 + + /** 生产构造(Spring 注入)。 */ + public DesignFeatureController(JdbcTemplate jdbcTemplate, + PageSchemaWriter pageSchemaWriter, + EntityAttributeReader attributeReader) { + this.jdbcTemplate = jdbcTemplate; + this.pageSchemaWriter = pageSchemaWriter; + this.attributeReader = attributeReader; + this.composer = new RecipePageComposer(MAPPER); + this.strictValidator = TypedPageSchemaValidator.defaults(); + this.skipAdminCheck = false; + } + + /** 包级测试构造:脱库 + 可旁路 admin 门禁。 */ + DesignFeatureController(PageSchemaWriter pageSchemaWriter, + EntityAttributeReader attributeReader, + boolean skipAdminCheck) { + this.jdbcTemplate = null; + this.pageSchemaWriter = pageSchemaWriter; + this.attributeReader = attributeReader; + 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> 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 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 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 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(); + } + + // ===== 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 ok(String msg, Map data) { + Map r = new LinkedHashMap<>(); + r.put("status", 0); + r.put("msg", msg); + if (data != null) r.put("data", data); + return r; + } + + private static Map fail(String msg) { + return fail(msg, null); + } + + private static Map fail(String msg, Map data) { + Map 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; + } +} diff --git a/platform-metadata/src/main/java/com/eip4/platform/metadata/web/EntityAttributeReader.java b/platform-metadata/src/main/java/com/eip4/platform/metadata/web/EntityAttributeReader.java new file mode 100644 index 0000000..a5bfb8d --- /dev/null +++ b/platform-metadata/src/main/java/com/eip4/platform/metadata/web/EntityAttributeReader.java @@ -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 部分。 + * + *

第 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 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 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); + } + } +} diff --git a/platform-metadata/src/test/java/com/eip4/platform/metadata/web/DesignFeatureControllerTest.java b/platform-metadata/src/test/java/com/eip4/platform/metadata/web/DesignFeatureControllerTest.java new file mode 100644 index 0000000..cbe5d23 --- /dev/null +++ b/platform-metadata/src/test/java/com/eip4/platform/metadata/web/DesignFeatureControllerTest.java @@ -0,0 +1,77 @@ +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> resp = controller(writer, reader).compile(body); + + assertEquals(200, resp.getStatusCode().value()); + @SuppressWarnings("unchecked") + Map data = (Map) 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 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> resp = controller(writer, reader).compile(body); + assertEquals(400, resp.getStatusCode().value()); + } +}