feat(design): POST /api/design/recipe/compile 单步端点(建物2)·服务端生成 templateId+严格 typed 闸+唯一真相落标准层
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -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)。
|
||||
*
|
||||
* <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
|
||||
|
||||
/** 生产构造(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<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();
|
||||
}
|
||||
|
||||
// ===== 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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user