feat(主子表): 父级汇总(总额=子表金额之和) compute-on-save + SUM 实时预览

主表列 = SUM/COUNT/AVG/MIN/MAX(子表某列)。服务端权威:行级派生(__derive)之后再聚合
(?__rollup=主列=AGG:LIST:子列),把子表列聚合写回主 map → 引擎落库;主表单该列只读
static + ${SUM(ARRAYMAP(DETAILS, item => <派生公式或子列>))} 实时预览。

- RecipeDerivedFieldComputer.enrichRollup: 子表列聚合(空集 SUM/COUNT=0,MIN/MAX/AVG 跳过)
- PageBlueprintChild.RollupColumn + 编译器 masterDetailFormControls(汇总列→static SUM 预览,
  被聚合子列若派生则用其公式 item 前缀)+ masterDetailFormApi 拼 __derive&__rollup
- RecipePageComposer/DesignFeatureController 贯通 childRollup(Object 容错;主列须主表真实列、
  子列须子表真实列、agg 白名单 SUM/COUNT/AVG/MIN/MAX)
- FlowController.executePost 接 __rollup(在 __derive 之后,使派生列已算好)

+5 单测,curl live e2e(TOTAL=SUM(明细金额)=55,服务端先逐行派生再聚合)PASS,Playwright 3/3。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-20 17:55:49 +08:00
parent ce544fa65e
commit ba8177e9d4
9 changed files with 474 additions and 14 deletions

View File

@@ -1,6 +1,7 @@
package com.eip4.platform.metadata.flow;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -82,6 +83,98 @@ public class RecipeDerivedFieldComputer {
}
}
/**
* 父级聚合 compute-on-save:把子表某列聚合写回主 map(如 主表总额=SUM(明细.金额))。须在
* {@link #enrich}(行级派生)之后调用,使被聚合的派生列已算好。spec 格式(已 URL 解码):
* {@code "主列=AGG:子表列名:子列|..."},AGG ∈ SUM/COUNT/AVG/MIN/MAX。空子表 → SUM/COUNT=0,
* MIN/MAX/AVG 跳过不写。未知聚合/缺子表列/求值失败 → 跳过并告警,绝不阻断保存。
*/
@SuppressWarnings("unchecked")
public void enrichRollup(Map<String, Object> map, String rollupSpec) {
if (map == null || rollupSpec == null || rollupSpec.isBlank()) {
return;
}
try {
for (String seg : rollupSpec.split("\\|")) {
int eq = seg.indexOf('=');
if (eq <= 0) {
continue;
}
String target = seg.substring(0, eq).trim();
String[] parts = seg.substring(eq + 1).split(":");
if (target.isEmpty() || parts.length != 3) {
continue;
}
String agg = parts[0].trim().toUpperCase();
String listColumn = parts[1].trim();
String childColumn = parts[2].trim();
Object listObj = caseInsensitiveGet(map, listColumn);
if (!(listObj instanceof List<?> rawRows)) {
continue;
}
List<BigDecimal> vals = new ArrayList<>();
for (Object r : rawRows) {
if (r instanceof Map) {
BigDecimal bd = toBigDecimal(caseInsensitiveGet((Map<String, Object>) r, childColumn));
if (bd != null) {
vals.add(bd);
}
}
}
BigDecimal result = aggregate(agg, vals);
if (result != null) {
map.put(target, result);
}
}
} catch (Exception e) {
log.warn("[RecipeRollup] compute-on-save 跳过 spec={}: {}", rollupSpec, e.toString());
}
}
/** 对一组数值做聚合;空集时 SUM/COUNT 返 0,AVG/MIN/MAX 返 null(跳过不写);未知聚合返 null。 */
private static BigDecimal aggregate(String agg, List<BigDecimal> vals) {
switch (agg) {
case "SUM":
return vals.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
case "COUNT":
return BigDecimal.valueOf(vals.size());
case "AVG":
if (vals.isEmpty()) {
return null;
}
BigDecimal sum = vals.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
return sum.divide(BigDecimal.valueOf(vals.size()), 10, RoundingMode.HALF_UP).stripTrailingZeros();
case "MIN":
return vals.stream().min(BigDecimal::compareTo).orElse(null);
case "MAX":
return vals.stream().max(BigDecimal::compareTo).orElse(null);
default:
return null; // 未知聚合 → 跳过
}
}
/** 数值强转:null/空白/非数字 → null(聚合时跳过);Number/字符串数字 → BigDecimal。 */
private static BigDecimal toBigDecimal(Object v) {
if (v == null) {
return null;
}
if (v instanceof BigDecimal bd) {
return bd;
}
if (v instanceof Number n) {
return new BigDecimal(n.toString());
}
String s = v.toString().trim();
if (s.isEmpty()) {
return null;
}
try {
return new BigDecimal(s);
} catch (NumberFormatException ex) {
return null;
}
}
private static Object caseInsensitiveGet(Map<String, Object> map, String key) {
if (map.containsKey(key)) {
return map.get(key);

View File

@@ -25,17 +25,25 @@ public record PageBlueprintChild(
String listColumn,
String displayField,
List<PageBlueprintField> fields,
List<DerivedColumn> derived) {
List<DerivedColumn> derived,
List<RollupColumn> rollups) {
public PageBlueprintChild {
fields = fields == null ? List.of() : List.copyOf(fields);
derived = derived == null ? List.of() : List.copyOf(derived);
rollups = rollups == null ? List.of() : List.copyOf(rollups);
}
/** 4-arg 兼容构造:无派生列。保持既有调用方/测试零改。 */
/** 4-arg 兼容构造:无派生列、无汇总。保持既有调用方/测试零改。 */
public PageBlueprintChild(String childTable, String listColumn, String displayField,
List<PageBlueprintField> fields) {
this(childTable, listColumn, displayField, fields, List.of());
this(childTable, listColumn, displayField, fields, List.of(), List.of());
}
/** 5-arg 兼容构造:有派生列、无汇总。 */
public PageBlueprintChild(String childTable, String listColumn, String displayField,
List<PageBlueprintField> fields, List<DerivedColumn> derived) {
this(childTable, listColumn, displayField, fields, derived, List.of());
}
/** 某子列名是否为派生列(编译器据此渲染只读 tpl 而非 quickEdit 输入)。 */
@@ -51,10 +59,31 @@ public record PageBlueprintChild(
return null;
}
/** 某主列名是否为汇总目标列(编译器据此渲染只读 SUM 预览而非可编辑输入)。 */
public RollupColumn rollupFor(String masterColumn) {
if (masterColumn == null) {
return null;
}
for (RollupColumn r : rollups) {
if (masterColumn.equalsIgnoreCase(r.masterColumn())) {
return r;
}
}
return null;
}
/**
* 单个派生列:{@code column} 目标列名(须为子表真实列),{@code formula} 算术公式
* (引用同行其它子列名,如 {@code ITEMQTY*ITEMPRICE})。
*/
public record DerivedColumn(String column, String formula) {
}
/**
* 单个父级汇总:主表 {@code masterColumn} = {@code agg}(子表 {@code childColumn} 之集)。
* agg ∈ SUM/COUNT/AVG/MIN/MAX(v1 wizard 主推 SUM=总额)。childColumn 可为派生列
* (编译器据此用派生公式构造 UI 实时预览)。
*/
public record RollupColumn(String masterColumn, String childColumn, String agg) {
}
}

View File

@@ -2,6 +2,8 @@ package com.eip4.platform.metadata.schema.blueprint;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -91,7 +93,7 @@ public final class PageBlueprintCompiler {
addForm.put("type", "form");
addForm.put("api", masterDetailFormApi(blueprint, "_ADD"));
addForm.put("reload", crudName);
ArrayNode controls = formControls(blueprint, false);
ArrayNode controls = masterDetailFormControls(blueprint);
controls.add(childInputTable(blueprint.child()));
addForm.set("body", controls);
return addButton;
@@ -120,7 +122,7 @@ public final class PageBlueprintCompiler {
"${" + blueprint.primaryKey() + "}");
// 选中行铺进对话框作用域,主键经 initApi 拉 _LOAD(主+子)。
dialog.putObject("data").put("&", "${selectedItems[0]}");
ArrayNode editControls = formControls(blueprint, false);
ArrayNode editControls = masterDetailFormControls(blueprint);
editControls.add(childInputTable(blueprint.child()));
editControls.add(hidden(blueprint.primaryKey(), "${" + blueprint.primaryKey() + "}"));
editForm.set("body", editControls);
@@ -172,13 +174,90 @@ public final class PageBlueprintCompiler {
*/
private static String masterDetailFormApi(PageBlueprint blueprint, String verb) {
String api = "post:/api/flow/" + blueprint.tableName() + verb;
List<String> qs = new ArrayList<>();
String derive = deriveSpec(blueprint.child());
if (derive != null) {
api += "?__derive=" + URLEncoder.encode(derive, StandardCharsets.UTF_8);
qs.add("__derive=" + URLEncoder.encode(derive, StandardCharsets.UTF_8));
}
String rollup = rollupSpec(blueprint.child());
if (rollup != null) {
qs.add("__rollup=" + URLEncoder.encode(rollup, StandardCharsets.UTF_8));
}
if (!qs.isEmpty()) {
api += "?" + String.join("&", qs);
}
return api;
}
/**
* 主子表主表单控件:普通主列照 controlType 渲染;汇总目标列渲染成只读 {@code static} + SUM 实时预览
* (非表单项不提交,落库由 ?__rollup= 服务端权威,避免前端覆写竞态)。
*/
private ArrayNode masterDetailFormControls(PageBlueprint blueprint) {
PageBlueprintChild child = blueprint.child();
ArrayNode controls = objectMapper.createArrayNode();
for (PageBlueprintField field : blueprint.fields()) {
if (!field.formVisible()) {
continue;
}
PageBlueprintChild.RollupColumn rollup = child == null ? null : child.rollupFor(field.name());
ObjectNode c = controls.addObject();
if (rollup != null) {
c.put("type", "static");
c.put("name", field.name());
c.put("label", field.label());
c.put("tpl", "${" + rollupPreviewExpr(child, rollup) + "}");
} else {
c.put("type", controlType(field.type()));
c.put("name", field.name());
c.put("label", field.label());
if (field.required()) {
c.put("required", true);
}
}
}
return controls;
}
/** 汇总 spec:{@code TOTAL=SUM:DETAILS:AMOUNT|...};无汇总返回 null。 */
private static String rollupSpec(PageBlueprintChild child) {
if (child == null || child.rollups().isEmpty()) {
return null;
}
StringBuilder sb = new StringBuilder();
for (PageBlueprintChild.RollupColumn r : child.rollups()) {
if (r.masterColumn() == null || r.masterColumn().isBlank()
|| r.childColumn() == null || r.childColumn().isBlank()
|| r.agg() == null || r.agg().isBlank()) {
continue;
}
if (sb.length() > 0) {
sb.append('|');
}
sb.append(r.masterColumn().trim()).append('=').append(r.agg().trim().toUpperCase(Locale.ROOT))
.append(':').append(child.listColumn()).append(':').append(r.childColumn().trim());
}
return sb.length() == 0 ? null : sb.toString();
}
/**
* 汇总列 UI 实时预览表达式:{@code SUM(ARRAYMAP(DETAILS, item => <itemExpr>))}。被汇总子列若为派生列
* 则用其算术公式(标识符前缀 item.,因派生列值非表单项不在行数据里);否则直接 {@code item.<子列>}。
*/
private static String rollupPreviewExpr(PageBlueprintChild child, PageBlueprintChild.RollupColumn rollup) {
PageBlueprintChild.DerivedColumn derived = child.derivedFor(rollup.childColumn());
String itemExpr = derived != null
? itemPrefixFormula(derived.formula())
: "item." + rollup.childColumn();
return rollup.agg().trim().toUpperCase(Locale.ROOT)
+ "(ARRAYMAP(" + child.listColumn() + ", item => " + itemExpr + "))";
}
/** 把算术公式里的列名标识符前缀 {@code item.}(用于 amis ARRAYMAP lambda 作用域)。算术公式无函数调用,故字母开头标识符即列名。 */
private static String itemPrefixFormula(String formula) {
return formula.replaceAll("\\s+", "").replaceAll("([A-Za-z_][A-Za-z0-9_]*)", "item.$1");
}
/** 派生 spec:{@code DETAILS|MONEY=QTY*PRICE|TAXED=MONEY*1.13};无派生列返回 null。公式去空白保 URL 安全。 */
private static String deriveSpec(PageBlueprintChild child) {
if (child == null || child.derived().isEmpty()) {

View File

@@ -67,7 +67,7 @@ public final class RecipePageComposer {
a.referenceTable(), a.displayColumn()));
}
return new PageBlueprintChild(spec.childTable().trim(), spec.listColumn().trim(), null,
childFields, spec.childDerived());
childFields, spec.childDerived(), spec.childRollup());
}
private static String deriveDisplayField(List<AttrSpec> attrs) {
@@ -103,26 +103,37 @@ public final class RecipePageComposer {
String childTable,
String listColumn,
List<AttrSpec> childAttributes,
List<PageBlueprintChild.DerivedColumn> childDerived) {
List<PageBlueprintChild.DerivedColumn> childDerived,
List<PageBlueprintChild.RollupColumn> childRollup) {
public Spec {
attributes = attributes == null ? List.of() : List.copyOf(attributes);
childAttributes = childAttributes == null ? List.of() : List.copyOf(childAttributes);
childDerived = childDerived == null ? List.of() : List.copyOf(childDerived);
childRollup = childRollup == null ? List.of() : List.copyOf(childRollup);
}
/** 7-arg 兼容构造:单表/树 recipe 无子表。保持既有调用方/测试零改。 */
public Spec(String tableName, String entityName, String recipe, String title,
String displayField, int pageSize, List<AttrSpec> attributes) {
this(tableName, entityName, recipe, title, displayField, pageSize, attributes,
null, null, List.of(), List.of());
null, null, List.of(), List.of(), List.of());
}
/** 10-arg 兼容构造:master-detail 无派生列。保持既有调用方/测试零改。 */
/** 10-arg 兼容构造:master-detail 无派生列、无汇总。保持既有调用方/测试零改。 */
public Spec(String tableName, String entityName, String recipe, String title,
String displayField, int pageSize, List<AttrSpec> attributes,
String childTable, String listColumn, List<AttrSpec> childAttributes) {
this(tableName, entityName, recipe, title, displayField, pageSize, attributes,
childTable, listColumn, childAttributes, List.of());
childTable, listColumn, childAttributes, List.of(), List.of());
}
/** 11-arg 兼容构造:master-detail 有派生列、无汇总。保持既有调用方/测试零改。 */
public Spec(String tableName, String entityName, String recipe, String title,
String displayField, int pageSize, List<AttrSpec> attributes,
String childTable, String listColumn, List<AttrSpec> childAttributes,
List<PageBlueprintChild.DerivedColumn> childDerived) {
this(tableName, entityName, recipe, title, displayField, pageSize, attributes,
childTable, listColumn, childAttributes, childDerived, List.of());
}
}

View File

@@ -57,6 +57,8 @@ public class DesignFeatureController {
/** 派生公式字符白名单:列名/数字/+ - * / ( ) . 与空白。拒 '|' '=' 等防 __derive 段切分被破坏。 */
private static final java.util.regex.Pattern DERIVED_FORMULA =
java.util.regex.Pattern.compile("[A-Za-z0-9_+\\-*/(). ]+");
/** 支持的父级汇总函数。 */
private static final Set<String> ROLLUP_AGGS = Set.of("SUM", "COUNT", "AVG", "MIN", "MAX");
private final PageSchemaWriter pageSchemaWriter;
private final EntityAttributeReader attributeReader;
@@ -137,7 +139,9 @@ public class DesignFeatureController {
// 2. 装配 + 编译(引用字段透传 referenceTable)
List<RecipePageComposer.AttrSpec> specAttrs = new ArrayList<>();
Set<String> masterCols = new HashSet<>();
for (EntityAttribute a : attrs.columns()) {
masterCols.add(a.column().toUpperCase(Locale.ROOT));
specAttrs.add(new RecipePageComposer.AttrSpec(
a.column(), a.display(), a.type(), a.required(), a.referenceTable(), null));
}
@@ -148,6 +152,7 @@ public class DesignFeatureController {
String listColumn = null;
List<RecipePageComposer.AttrSpec> childSpecAttrs = new ArrayList<>();
List<PageBlueprintChild.DerivedColumn> childDerivedCols = new ArrayList<>();
List<PageBlueprintChild.RollupColumn> childRollupCols = new ArrayList<>();
if (masterDetail) {
childTable = req.childTable.trim();
String linkColumn = req.linkColumn.trim();
@@ -205,11 +210,38 @@ public class DesignFeatureController {
}
}
}
// 父级汇总:主列须为主表真实列、子列须为子表真实列(否则引擎落库丢弃为静默 no-op),
// agg ∈ SUM/COUNT/AVG/MIN/MAX。childRollup 同 childDerived 用 Object 容错,非法项静默忽略。
if (req.childRollup instanceof List<?> rollupList) {
for (Object item : rollupList) {
if (!(item instanceof Map<?, ?> m)) {
continue;
}
Object mcObj = m.get("masterColumn");
Object ccObj = m.get("childColumn");
Object agObj = m.get("agg");
if (mcObj == null || ccObj == null
|| isBlank(mcObj.toString()) || isBlank(ccObj.toString())) {
continue;
}
String master = mcObj.toString().trim().toUpperCase(Locale.ROOT);
String childCol = ccObj.toString().trim().toUpperCase(Locale.ROOT);
String agg = (agObj == null || isBlank(agObj.toString()))
? "SUM" : agObj.toString().trim().toUpperCase(Locale.ROOT);
if (!ROLLUP_AGGS.contains(agg)) {
return ResponseEntity.badRequest().body(fail("不支持的汇总函数(SUM/COUNT/AVG/MIN/MAX): " + agg));
}
if (masterCols.contains(master) && childCols.contains(childCol)) {
childRollupCols.add(new PageBlueprintChild.RollupColumn(master, childCol, agg));
}
}
}
}
ObjectNode schema = composer.compose(new RecipePageComposer.Spec(
req.tableName.trim(), entityNameOf(req), recipe, req.title.trim(),
displayField, pageSize, specAttrs, childTable, listColumn, childSpecAttrs, childDerivedCols));
displayField, pageSize, specAttrs, childTable, listColumn, childSpecAttrs,
childDerivedCols, childRollupCols));
String schemaJson;
try {
@@ -406,5 +438,8 @@ public class DesignFeatureController {
// 按 Object 容错接收:前端 combo 未触碰时 amis 可能发未解析占位串/空串,那种情况 Jackson 映射进
// List 会 400 掉整个编译;用 Object 接、控制器仅在确为 List<{column,formula}> 时解析,其余忽略。
public Object childDerived;
// master-detail-v1 父级汇总:如 [{masterColumn:"TOTAL",childColumn:"AMOUNT",agg:"SUM"}],
// 编译为主表只读 SUM 预览 + 写流 __rollup。同 childDerived 用 Object 容错。
public Object childRollup;
}
}

View File

@@ -177,6 +177,7 @@ public class FlowController {
public ResponseEntity<Map<String, Object>> executePost(@PathVariable String id,
@RequestParam(value = "__egtpl", required = false) String egTpl,
@RequestParam(value = "__derive", required = false) String derive,
@RequestParam(value = "__rollup", required = false) String rollup,
@RequestBody(required = false) Map<String, Object> body) {
Map<String, Object> map = body == null ? new HashMap<>() : new HashMap<>(body);
applyPaging(map);
@@ -190,6 +191,11 @@ public class FlowController {
if (derive != null && !derive.isBlank() && recipeDerivedComputer != null) {
recipeDerivedComputer.enrich(map, derive);
}
// recipe 父级汇总:?__rollup=主列=AGG:LIST:子列 时把子表某列聚合写回主 map(如 总额=SUM(明细.金额))。
// 须在行级派生(__derive)之后,使被聚合的派生列已算好。无 __rollup 自然无操作。
if (rollup != null && !rollup.isBlank() && recipeDerivedComputer != null) {
recipeDerivedComputer.enrichRollup(map, rollup);
}
try {
return run(id, map, true, egTpl);
} catch (RuntimeException ex) {
@@ -197,9 +203,9 @@ public class FlowController {
}
}
/** 兼容老单测的三参入口(无 __derive);HTTP 入口走带 __derive 的四参方法。 */
/** 兼容老单测的三参入口(无 __derive/__rollup);HTTP 入口走带 __derive/__rollup 的五参方法。 */
ResponseEntity<Map<String, Object>> executePost(String id, String egTpl, Map<String, Object> body) {
return executePost(id, egTpl, null, body);
return executePost(id, egTpl, null, null, body);
}
/**

View File

@@ -100,4 +100,63 @@ class RecipeDerivedFieldComputerTest {
computer.enrich(m, "DETAILS"); // 无 target=expr
assertNull(rows(m, "DETAILS").get(0).get("AMOUNT"));
}
// ───────────────────────────────── 父级聚合 enrichRollup
@Test
@DisplayName("聚合 SUM:主表总额=子表金额之和")
void rollupSum() {
Map<String, Object> map = new HashMap<>();
map.put("DETAILS", new ArrayList<>(List.of(
row("AMOUNT", 30), row("AMOUNT", new BigDecimal("25.5")), row("AMOUNT", "4.5"))));
computer.enrichRollup(map, "TOTAL=SUM:DETAILS:AMOUNT");
assertEquals(0, new BigDecimal("60").compareTo((BigDecimal) map.get("TOTAL")));
}
@Test
@DisplayName("聚合 COUNT/AVG/MIN/MAX")
void rollupOtherAggs() {
Map<String, Object> map = new HashMap<>();
map.put("DETAILS", new ArrayList<>(List.of(row("V", 10), row("V", 20), row("V", 30))));
computer.enrichRollup(map, "C=COUNT:DETAILS:V|A=AVG:DETAILS:V|MN=MIN:DETAILS:V|MX=MAX:DETAILS:V");
assertEquals(0, new BigDecimal("3").compareTo((BigDecimal) map.get("C")));
assertEquals(0, new BigDecimal("20").compareTo((BigDecimal) map.get("A")));
assertEquals(0, new BigDecimal("10").compareTo((BigDecimal) map.get("MN")));
assertEquals(0, new BigDecimal("30").compareTo((BigDecimal) map.get("MX")));
}
@Test
@DisplayName("聚合空子表 → SUM=0、COUNT=0;MIN/MAX 空集跳过不写")
void rollupEmptyList() {
Map<String, Object> map = new HashMap<>();
map.put("DETAILS", new ArrayList<>());
computer.enrichRollup(map, "TOTAL=SUM:DETAILS:AMOUNT|C=COUNT:DETAILS:AMOUNT|MN=MIN:DETAILS:AMOUNT");
assertEquals(0, BigDecimal.ZERO.compareTo((BigDecimal) map.get("TOTAL")));
assertEquals(0, BigDecimal.ZERO.compareTo((BigDecimal) map.get("C")));
assertNull(map.get("MN"));
}
@Test
@DisplayName("聚合大小写不敏感子表列;行级派生后再聚合派生列(AMOUNT)")
void rollupAfterDerive() {
Map<String, Object> map = new HashMap<>();
map.put("details", new ArrayList<>(List.of(
row("ITEMQTY", 3, "ITEMPRICE", 10), row("ITEMQTY", 2, "ITEMPRICE", "12.5"))));
computer.enrich(map, "details|AMOUNT=ITEMQTY*ITEMPRICE"); // 先逐行派生 AMOUNT=30/25
computer.enrichRollup(map, "TOTAL=SUM:DETAILS:AMOUNT"); // 再聚合 = 55
assertEquals(0, new BigDecimal("55").compareTo((BigDecimal) map.get("TOTAL")));
}
@Test
@DisplayName("聚合 null/空/坏 spec → 无操作不抛")
void rollupNoop() {
Map<String, Object> m = new HashMap<>();
m.put("DETAILS", new ArrayList<>(List.of(row("AMOUNT", 1))));
computer.enrichRollup(m, null);
computer.enrichRollup(m, " ");
computer.enrichRollup(m, "TOTAL=BADAGG:DETAILS:AMOUNT"); // 未知聚合函数 → 跳过
computer.enrichRollup(m, "TOTAL=SUM:NOPE:AMOUNT"); // 无该子表列 → 跳过
assertNull(m.get("TOTAL"));
computer.enrichRollup(null, "TOTAL=SUM:DETAILS:AMOUNT"); // null map
}
}

View File

@@ -295,6 +295,59 @@ class PageBlueprintCompilerTest {
assertTrue(editForm.path("api").asText().contains("__derive="), "编辑表单 api 应带 __derive");
}
@Test
@DisplayName("master-detail-v1 父级汇总: 主表汇总列渲染只读 static + SUM(ARRAYMAP) 实时预览 + 表单 api 透传 __rollup")
void compilesMasterDetailWithRollup() {
PageBlueprint blueprint = new PageBlueprint(
PageBlueprint.VERSION,
PageBlueprint.RECIPE_MASTER_DETAIL,
"eip4ai-purchase",
"采购申请",
"EIP4AI_PURCHASE",
"采购申请",
"EIP4AI_PURCHASE_ID",
"TITLE",
List.of(
new PageBlueprintField("TITLE", "标题", "string", true, true, true),
new PageBlueprintField("TOTAL", "总额", "number", false, true, true)),
true, true, true, 20,
new PageBlueprintChild("EIP4AI_PURCHASE_ITEM", "DETAILS", "ITEMNAME",
List.of(
new PageBlueprintField("QTY", "数量", "integer", false, false, true),
new PageBlueprintField("PRICE", "单价", "number", false, false, true),
new PageBlueprintField("AMOUNT", "金额", "number", false, false, true)),
List.of(new PageBlueprintChild.DerivedColumn("AMOUNT", "QTY*PRICE")),
List.of(new PageBlueprintChild.RollupColumn("TOTAL", "AMOUNT", "SUM"))));
ObjectNode schema = new PageBlueprintCompiler(MAPPER).compile(blueprint);
ObjectNode addForm = (ObjectNode) ((ArrayNode) schema.path("body").path("headerToolbar"))
.get(0).path("dialog").path("body");
// 表单 api 透传 __rollup(URL 编码);解码后 = TOTAL=SUM:DETAILS:AMOUNT(且仍带 __derive)。
String api = addForm.path("api").asText();
assertTrue(api.contains("__rollup="), "表单 api 应带 __rollup");
assertTrue(api.contains("__derive="), "表单 api 仍应带 __derive");
String rollup = URLDecoder.decode(api.replaceAll(".*__rollup=", "").replaceAll("&.*", ""),
StandardCharsets.UTF_8);
assertEquals("TOTAL=SUM:DETAILS:AMOUNT", rollup);
// 主表汇总列 TOTAL = 只读 static + SUM(ARRAYMAP(...)) 预览(AMOUNT 为派生列→用其公式 item 前缀)。
ObjectNode total = bodyByName((ArrayNode) addForm.path("body"), "TOTAL");
assertEquals("static", total.path("type").asText());
assertEquals("${SUM(ARRAYMAP(DETAILS, item => item.QTY*item.PRICE))}", total.path("tpl").asText());
// 普通主列 TITLE 仍为可编辑输入。
assertEquals("input-text", bodyByName((ArrayNode) addForm.path("body"), "TITLE").path("type").asText());
}
private static ObjectNode bodyByName(ArrayNode body, String name) {
for (int i = 0; i < body.size(); i++) {
if (name.equals(body.get(i).path("name").asText())) {
return (ObjectNode) body.get(i);
}
}
throw new AssertionError("no body control name=" + name);
}
private static ObjectNode colByName(ArrayNode cols, String name) {
for (int i = 0; i < cols.size(); i++) {
if (name.equals(cols.get(i).path("name").asText())) {