feat(主子表): 引用驱动联动(选物料→带出单价/规格) onEvent setValue

子表引用列渲染 picker select,选中后 onEvent.change → setValue 按映射把所选引用行的列
自动带出到同行其它子列。隔离 Playwright 钉死正确形态:单选 select 的 selectedItems 是
被选 Option 对象本身(非数组),value=${event.data.selectedItems.<src>} 绝不可加 [0]
(上一会话 fill 失败真因);目标列 id=<col>_${index} 挂列上,needConfirm:false 下仍被命中。

- PageBlueprintChild: Linkage(refColumn,List<Fill>) / Fill(target,source) 模型 + 兼容构造
- PageBlueprintCompiler: 引用子列→select(source=/api/picker/{ref}/list, options=${items},
  _label/_id)+onEvent setValue;目标列挂 id;effectiveFills 剔除派生目标/同目标去重/
  仅合法引用 refColumn 渲 select(对抗评审加固,防 setValue 落空与串台)
- TypedPageSchemaValidator: 仅 onEvent.<event>.actions[] 锚定放行 setValue 白名单(D3 门收窄)
- DesignFeatureController: childLinkage Object 容错解析 + COLUMN_IDENT 标识符白名单防注入
- 测试: 编译/校验/控制器联动 + 派生冲突/去重/非引用 健壮性 + 防注入 400

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-20 22:28:24 +08:00
parent 3e4264d9e0
commit 63e6522f3b
8 changed files with 512 additions and 9 deletions

View File

@@ -12,6 +12,22 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public final class TypedPageSchemaValidator { public final class TypedPageSchemaValidator {
/**
* onEvent 动作白名单:onEvent.&lt;event&gt;.actions[] 里的 action 对象自身无绑定组件 type({@code actionType}
* 直挂),故不能按「组件支持的 actionType」校验,否则恒判 ACTION_WITHOUT_COMPONENT→400。这里按窄白名单
* 放行——当前仅 {@code setValue}(引用驱动联动 选物料→带出单价/规格 所需)。属 D3 安全门,新增动作须评审。
*/
private static final Set<String> EVENT_ACTIONS = Set.of("setValue");
/**
* onEvent 动作数组路径锚点:仅 {@code ...onEvent.<event>.actions[<idx>]} 才算事件动作上下文(放行白名单动作)。
* 用锚定正则而非 {@code path.contains(".actions[")} 子串——后者会误把任意名为 actions 的数组(如 dialog/form
* 底部 actions[])当事件动作。dialog/form 底部按钮本带 type:button(componentType 非空) 不走此分支,但锚点
* 收窄可堵住「把无 type 的裸 setValue 塞进非 onEvent 的 actions[] 蒙混过闸」(对抗评审 D3 门加固)。
*/
private static final java.util.regex.Pattern ON_EVENT_ACTION_PATH =
java.util.regex.Pattern.compile(".*\\.onEvent\\.[A-Za-z0-9_]+\\.actions\\[\\d+]$");
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final PageComponentRegistry registry; private final PageComponentRegistry registry;
@@ -79,6 +95,12 @@ public final class TypedPageSchemaValidator {
if (!actionType.isBlank()) { if (!actionType.isBlank()) {
usedActions.add(actionType); usedActions.add(actionType);
if (componentType.isBlank()) { if (componentType.isBlank()) {
// 无绑定组件 type 的 action 对象:仅当处于 onEvent.<event>.actions[<idx>] 且在事件动作白名单内
// 才放行(联动 setValue);否则维持 ACTION_WITHOUT_COMPONENT。dialog/drawer 底部按钮带 type:button
// 不走此分支,照常按组件支持的动作校验,故 dialog footer 动作不受影响。
if (ON_EVENT_ACTION_PATH.matcher(path).matches() && EVENT_ACTIONS.contains(actionType)) {
return;
}
issues.add(new TypedPageSchemaIssue(path + ".actionType", "ACTION_WITHOUT_COMPONENT", issues.add(new TypedPageSchemaIssue(path + ".actionType", "ACTION_WITHOUT_COMPONENT",
"actionType 必须绑定到有 type 的组件")); "actionType 必须绑定到有 type 的组件"));
} else if (!registry.supportsAction(componentType, actionType)) { } else if (!registry.supportsAction(componentType, actionType)) {

View File

@@ -19,6 +19,7 @@ import java.util.List;
* @param displayField 子表显示字段(预留;当前仅作元信息) * @param displayField 子表显示字段(预留;当前仅作元信息)
* @param fields 子表可编辑列(每列经 controlType 映射为 quickEdit 控件) * @param fields 子表可编辑列(每列经 controlType 映射为 quickEdit 控件)
* @param derived 派生列(目标列名 + 算术公式,公式引用同行其它子列) * @param derived 派生列(目标列名 + 算术公式,公式引用同行其它子列)
* @param linkages 引用驱动联动(选某引用子列 → 自动带出同行其它子列,如 选物料→单价/规格)
*/ */
public record PageBlueprintChild( public record PageBlueprintChild(
String childTable, String childTable,
@@ -26,24 +27,33 @@ public record PageBlueprintChild(
String displayField, String displayField,
List<PageBlueprintField> fields, List<PageBlueprintField> fields,
List<DerivedColumn> derived, List<DerivedColumn> derived,
List<RollupColumn> rollups) { List<RollupColumn> rollups,
List<Linkage> linkages) {
public PageBlueprintChild { public PageBlueprintChild {
fields = fields == null ? List.of() : List.copyOf(fields); fields = fields == null ? List.of() : List.copyOf(fields);
derived = derived == null ? List.of() : List.copyOf(derived); derived = derived == null ? List.of() : List.copyOf(derived);
rollups = rollups == null ? List.of() : List.copyOf(rollups); rollups = rollups == null ? List.of() : List.copyOf(rollups);
linkages = linkages == null ? List.of() : List.copyOf(linkages);
} }
/** 4-arg 兼容构造:无派生列、无汇总。保持既有调用方/测试零改。 */ /** 4-arg 兼容构造:无派生列、无汇总、无联动。保持既有调用方/测试零改。 */
public PageBlueprintChild(String childTable, String listColumn, String displayField, public PageBlueprintChild(String childTable, String listColumn, String displayField,
List<PageBlueprintField> fields) { List<PageBlueprintField> fields) {
this(childTable, listColumn, displayField, fields, List.of(), List.of()); this(childTable, listColumn, displayField, fields, List.of(), List.of(), List.of());
} }
/** 5-arg 兼容构造:有派生列、无汇总。 */ /** 5-arg 兼容构造:有派生列、无汇总、无联动。 */
public PageBlueprintChild(String childTable, String listColumn, String displayField, public PageBlueprintChild(String childTable, String listColumn, String displayField,
List<PageBlueprintField> fields, List<DerivedColumn> derived) { List<PageBlueprintField> fields, List<DerivedColumn> derived) {
this(childTable, listColumn, displayField, fields, derived, List.of()); this(childTable, listColumn, displayField, fields, derived, List.of(), List.of());
}
/** 6-arg 兼容构造:有派生列、有汇总、无联动。保持既有调用方/测试零改。 */
public PageBlueprintChild(String childTable, String listColumn, String displayField,
List<PageBlueprintField> fields, List<DerivedColumn> derived,
List<RollupColumn> rollups) {
this(childTable, listColumn, displayField, fields, derived, rollups, List.of());
} }
/** 某子列名是否为派生列(编译器据此渲染只读 tpl 而非 quickEdit 输入)。 */ /** 某子列名是否为派生列(编译器据此渲染只读 tpl 而非 quickEdit 输入)。 */
@@ -72,6 +82,19 @@ public record PageBlueprintChild(
return null; return null;
} }
/** 某子列名是否为联动「源引用列」(编译器据此把该列渲染成 picker select + onEvent 联动填充)。 */
public Linkage linkageFor(String refColumn) {
if (refColumn == null) {
return null;
}
for (Linkage l : linkages) {
if (refColumn.equalsIgnoreCase(l.refColumn())) {
return l;
}
}
return null;
}
/** /**
* 单个派生列:{@code column} 目标列名(须为子表真实列),{@code formula} 算术公式 * 单个派生列:{@code column} 目标列名(须为子表真实列),{@code formula} 算术公式
* (引用同行其它子列名,如 {@code ITEMQTY*ITEMPRICE})。 * (引用同行其它子列名,如 {@code ITEMQTY*ITEMPRICE})。
@@ -86,4 +109,25 @@ public record PageBlueprintChild(
*/ */
public record RollupColumn(String masterColumn, String childColumn, String agg) { public record RollupColumn(String masterColumn, String childColumn, String agg) {
} }
/**
* 引用驱动联动:子表某「引用列」{@code refColumn}(type=reference,须有 referenceTable)渲染成 picker select;
* 选中后按 {@code fills} 自动把所选引用实体行的列带出到同行其它子列(如 选物料→单价/规格)。
*
* <p>编译器据此对 refColumn 列发 {@code type:select + source(/api/picker/{ref}/list) + onEvent.change},
* 每条 fill 生成一个 {@code setValue componentId=<target>_${index} value=${event.data.selectedItems.<source>}}
* (单选 select 的 change 事件 selectedItems 即被选 Option 整行;隔离 Playwright 已验证,非数组不可加 [0])。
*
* @param refColumn 联动源:子表引用列名(须为 type=reference 且有 referenceTable 的子字段)
* @param fills 带出映射:每条 {目标子列 ← 引用实体行的源列}
*/
public record Linkage(String refColumn, List<Fill> fills) {
public Linkage {
fills = fills == null ? List.of() : List.copyOf(fills);
}
}
/** 单条带出:{@code targetColumn}(子表真实列)= 所选引用行的 {@code sourceColumn} 列值。 */
public record Fill(String targetColumn, String sourceColumn) {
}
} }

View File

@@ -18,6 +18,9 @@ public final class PageBlueprintCompiler {
/** 标准审计/系统列:系统自管,不进表单/列表/子表可编辑单元格(杂乱且非用户可编辑)。 */ /** 标准审计/系统列:系统自管,不进表单/列表/子表可编辑单元格(杂乱且非用户可编辑)。 */
private static final java.util.Set<String> SYSTEM_COLUMNS = java.util.Set.of( private static final java.util.Set<String> SYSTEM_COLUMNS = java.util.Set.of(
"VERSION", "CREATETIME", "UPDATETIME", "CREATEBY", "UPDATEBY", "ISACTIVE"); "VERSION", "CREATETIME", "UPDATETIME", "CREATEBY", "UPDATEBY", "ISACTIVE");
/** 表名标识符白名单:referenceTable 会拼进 picker URL,须为合法标识符(防非 HTTP 调用方传脏值进 URL)。 */
private static final java.util.regex.Pattern TABLE_IDENT =
java.util.regex.Pattern.compile("[A-Za-z][A-Za-z0-9_]{0,63}");
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
@@ -158,6 +161,19 @@ public final class PageBlueprintCompiler {
table.put("staticOn", "${__readonly}"); table.put("staticOn", "${__readonly}");
ArrayNode columns = table.putArray("columns"); ArrayNode columns = table.putArray("columns");
String childPk = child.childTable() + "_ID"; String childPk = child.childTable() + "_ID";
// 联动目标子列集合:这些列要挂 id=<col>_${index} 供 setValue componentId 命中(id 挂列上已验证可用)。
// ★ 只计入「有效联动」(refColumn 是合法引用列、且目标列是真实可填子列、非派生只读列) 的目标,
// 否则会给不会被 setValue 命中的列挂死 id(派生目标→渲成 tpl 无 id 致 setValue 落空,对抗评审揪出)。
java.util.Set<String> linkageTargets = new java.util.HashSet<>();
for (PageBlueprintField field : child.fields()) {
PageBlueprintChild.Linkage l = child.linkageFor(field.name());
if (l == null || !isLinkageSource(field)) {
continue;
}
for (PageBlueprintChild.Fill f : effectiveFills(child, l)) {
linkageTargets.add(f.targetColumn().toUpperCase(Locale.ROOT));
}
}
for (PageBlueprintField field : child.fields()) { for (PageBlueprintField field : child.fields()) {
// 排除子表标准审计列(子表PK/VERSION/CREATETIME/...):不渲成可编辑单元格,避免子表过宽杂乱。 // 排除子表标准审计列(子表PK/VERSION/CREATETIME/...):不渲成可编辑单元格,避免子表过宽杂乱。
if (isSystemColumn(field.name(), childPk)) { if (isSystemColumn(field.name(), childPk)) {
@@ -167,7 +183,11 @@ public final class PageBlueprintCompiler {
col.put("name", field.name()); col.put("name", field.name());
col.put("label", field.label()); col.put("label", field.label());
PageBlueprintChild.DerivedColumn derived = child.derivedFor(field.name()); PageBlueprintChild.DerivedColumn derived = child.derivedFor(field.name());
if (derived != null) { PageBlueprintChild.Linkage linkage = child.linkageFor(field.name());
if (linkage != null && isLinkageSource(field)) {
// 联动源引用列:picker select + onEvent.change 自动带出(隔离 Playwright 已验证形态)。
applyLinkageSelect(col, child, field, linkage);
} else if (derived != null) {
// 派生列:只读 tpl 计算单元格,amis 按 ${公式} 实时预览(非表单项→不提交); // 派生列:只读 tpl 计算单元格,amis 按 ${公式} 实时预览(非表单项→不提交);
// 落库由写流 ?__derive= 服务端权威逐行求值(绕开 input-table 前端竞态)。 // 落库由写流 ?__derive= 服务端权威逐行求值(绕开 input-table 前端竞态)。
// ★ quickEdit:false 必加:amis input-table 在 needConfirm:false 下会给「每一列」强注默认 // ★ quickEdit:false 必加:amis input-table 在 needConfirm:false 下会给「每一列」强注默认
@@ -177,6 +197,11 @@ public final class PageBlueprintCompiler {
col.put("tpl", "${" + derived.formula() + "}"); col.put("tpl", "${" + derived.formula() + "}");
col.put("quickEdit", false); col.put("quickEdit", false);
} else { } else {
// 普通可编辑子列;若是联动目标列,挂 id=<col>_${index} 供 onEvent setValue 命中
// (needConfirm:false 下 id 挂列上、配合显式 quickEdit type 仍被命中,隔离 Playwright 已验证)。
if (linkageTargets.contains(field.name().toUpperCase(Locale.ROOT))) {
col.put("id", field.name() + "_${index}");
}
ObjectNode quickEdit = col.putObject("quickEdit"); ObjectNode quickEdit = col.putObject("quickEdit");
quickEdit.put("type", controlType(field.type())); quickEdit.put("type", controlType(field.type()));
quickEdit.put("name", field.name()); quickEdit.put("name", field.name());
@@ -185,6 +210,68 @@ public final class PageBlueprintCompiler {
return table; return table;
} }
/**
* 联动源引用列:渲染成 picker select(不包 quickEdit —— needConfirm:false 下 amis columnToQuickEdit 对
* 「列 type 为表单项」的列整列保留含 onEvent,隔离 Playwright 已验证此形态可触发联动)。
* source=/api/picker/{referenceTable}/list 取整行 items 作 options(responseData options:${items}),
* labelField/valueField=_label/_id;选中后 onEvent.change 对每条 fill 发
* setValue componentId=&lt;target&gt;_${index} value=${event.data.selectedItems.&lt;source&gt;}。
*
* <p>★ 单选 select 的 change 事件 selectedItems = 被选 Option 整行对象本身(非数组,不可加 [0]),
* 这是上一会话联动 fill 失败的真因(用了 selectedItems[0])——隔离 Playwright 钉死。
*/
private void applyLinkageSelect(ObjectNode col, PageBlueprintChild child,
PageBlueprintField field, PageBlueprintChild.Linkage linkage) {
col.put("type", "select");
ObjectNode source = col.putObject("source");
source.put("method", "get");
source.put("url", "/api/picker/" + field.referenceTable() + "/list");
source.putObject("responseData").put("options", "${items}");
col.put("labelField", "_label");
col.put("valueField", "_id");
col.put("searchable", true);
ArrayNode actions = col.putObject("onEvent").putObject("change").putArray("actions");
for (PageBlueprintChild.Fill fill : effectiveFills(child, linkage)) {
ObjectNode act = actions.addObject();
act.put("actionType", "setValue");
act.put("componentId", fill.targetColumn() + "_${index}");
act.putObject("args").put("value",
"${event.data.selectedItems." + fill.sourceColumn() + "}");
}
}
/** 字段是否可作联动「源引用列」:type=reference 且 referenceTable 为合法表标识符。 */
private static boolean isLinkageSource(PageBlueprintField field) {
return "reference".equals(field.type())
&& field.referenceTable() != null
&& TABLE_IDENT.matcher(field.referenceTable()).matches();
}
/**
* 联动有效带出映射:剔除 ①目标/源列空 ②目标列是派生列(只读 tpl 无可填表单项 id→setValue 落空)
* ③重复目标列(同一目标多次→重复 setValue/重复 id,amis 反模式)。一处计算,linkageTargets 与
* applyLinkageSelect 共用,保证「挂 id 的列」与「发 setValue 的列」严格一致(对抗评审揪出的串台风险)。
*/
private static List<PageBlueprintChild.Fill> effectiveFills(PageBlueprintChild child,
PageBlueprintChild.Linkage linkage) {
List<PageBlueprintChild.Fill> out = new ArrayList<>();
java.util.Set<String> seen = new java.util.HashSet<>();
for (PageBlueprintChild.Fill f : linkage.fills()) {
if (f.targetColumn() == null || f.targetColumn().isBlank()
|| f.sourceColumn() == null || f.sourceColumn().isBlank()) {
continue;
}
if (child.derivedFor(f.targetColumn()) != null) {
continue; // 目标列是派生只读列:不可填,剔除(否则 setValue 命中不存在的组件)
}
if (!seen.add(f.targetColumn().toUpperCase(Locale.ROOT))) {
continue; // 同一目标列只保留首条带出
}
out.add(f);
}
return out;
}
/** /**
* 主子表写流表单 api:基础 {@code post:/api/flow/<TABLE><verb>};子表声明派生列时追加 URL 编码的 * 主子表写流表单 api:基础 {@code post:/api/flow/<TABLE><verb>};子表声明派生列时追加 URL 编码的
* {@code ?__derive=<listColumn>|<目标列>=<公式>|...},由 {@code RecipeDerivedFieldComputer} 落库前 * {@code ?__derive=<listColumn>|<目标列>=<公式>|...},由 {@code RecipeDerivedFieldComputer} 落库前

View File

@@ -67,7 +67,7 @@ public final class RecipePageComposer {
a.referenceTable(), a.displayColumn())); a.referenceTable(), a.displayColumn()));
} }
return new PageBlueprintChild(spec.childTable().trim(), spec.listColumn().trim(), null, return new PageBlueprintChild(spec.childTable().trim(), spec.listColumn().trim(), null,
childFields, spec.childDerived(), spec.childRollup()); childFields, spec.childDerived(), spec.childRollup(), spec.childLinkage());
} }
private static String deriveDisplayField(List<AttrSpec> attrs) { private static String deriveDisplayField(List<AttrSpec> attrs) {
@@ -104,12 +104,24 @@ public final class RecipePageComposer {
String listColumn, String listColumn,
List<AttrSpec> childAttributes, List<AttrSpec> childAttributes,
List<PageBlueprintChild.DerivedColumn> childDerived, List<PageBlueprintChild.DerivedColumn> childDerived,
List<PageBlueprintChild.RollupColumn> childRollup) { List<PageBlueprintChild.RollupColumn> childRollup,
List<PageBlueprintChild.Linkage> childLinkage) {
public Spec { public Spec {
attributes = attributes == null ? List.of() : List.copyOf(attributes); attributes = attributes == null ? List.of() : List.copyOf(attributes);
childAttributes = childAttributes == null ? List.of() : List.copyOf(childAttributes); childAttributes = childAttributes == null ? List.of() : List.copyOf(childAttributes);
childDerived = childDerived == null ? List.of() : List.copyOf(childDerived); childDerived = childDerived == null ? List.of() : List.copyOf(childDerived);
childRollup = childRollup == null ? List.of() : List.copyOf(childRollup); childRollup = childRollup == null ? List.of() : List.copyOf(childRollup);
childLinkage = childLinkage == null ? List.of() : List.copyOf(childLinkage);
}
/** 12-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,
List<PageBlueprintChild.RollupColumn> childRollup) {
this(tableName, entityName, recipe, title, displayField, pageSize, attributes,
childTable, listColumn, childAttributes, childDerived, childRollup, List.of());
} }
/** 7-arg 兼容构造:单表/树 recipe 无子表。保持既有调用方/测试零改。 */ /** 7-arg 兼容构造:单表/树 recipe 无子表。保持既有调用方/测试零改。 */

View File

@@ -59,6 +59,9 @@ public class DesignFeatureController {
java.util.regex.Pattern.compile("[A-Za-z0-9_+\\-*/(). ]+"); java.util.regex.Pattern.compile("[A-Za-z0-9_+\\-*/(). ]+");
/** 支持的父级汇总函数。 */ /** 支持的父级汇总函数。 */
private static final Set<String> ROLLUP_AGGS = Set.of("SUM", "COUNT", "AVG", "MIN", "MAX"); private static final Set<String> ROLLUP_AGGS = Set.of("SUM", "COUNT", "AVG", "MIN", "MAX");
/** 列名标识符白名单:大写字母开头,仅大写/数字/下划线。联动列名会拼进 ${...} 表达式与 componentId,须防注入。 */
private static final java.util.regex.Pattern COLUMN_IDENT =
java.util.regex.Pattern.compile("[A-Z][A-Z0-9_]{0,40}");
private final PageSchemaWriter pageSchemaWriter; private final PageSchemaWriter pageSchemaWriter;
private final EntityAttributeReader attributeReader; private final EntityAttributeReader attributeReader;
@@ -153,6 +156,8 @@ public class DesignFeatureController {
List<RecipePageComposer.AttrSpec> childSpecAttrs = new ArrayList<>(); List<RecipePageComposer.AttrSpec> childSpecAttrs = new ArrayList<>();
List<PageBlueprintChild.DerivedColumn> childDerivedCols = new ArrayList<>(); List<PageBlueprintChild.DerivedColumn> childDerivedCols = new ArrayList<>();
List<PageBlueprintChild.RollupColumn> childRollupCols = new ArrayList<>(); List<PageBlueprintChild.RollupColumn> childRollupCols = new ArrayList<>();
List<PageBlueprintChild.Linkage> childLinkageCols = new ArrayList<>();
Set<String> childRefCols = new HashSet<>(); // 子表引用列(type=reference 且有 referenceTable,排除 FK 回链列)
if (masterDetail) { if (masterDetail) {
childTable = req.childTable.trim(); childTable = req.childTable.trim();
String linkColumn = req.linkColumn.trim(); String linkColumn = req.linkColumn.trim();
@@ -180,6 +185,10 @@ public class DesignFeatureController {
if (linkColumn.equalsIgnoreCase(a.column())) { if (linkColumn.equalsIgnoreCase(a.column())) {
continue; continue;
} }
// 记录子表的(非回链)引用列:仅这些列可作为引用驱动联动的「源引用列」。
if ("reference".equals(a.type()) && a.referenceTable() != null && !a.referenceTable().isBlank()) {
childRefCols.add(a.column().toUpperCase(Locale.ROOT));
}
childSpecAttrs.add(new RecipePageComposer.AttrSpec( childSpecAttrs.add(new RecipePageComposer.AttrSpec(
a.column(), a.display(), a.type(), a.required(), a.referenceTable(), null)); a.column(), a.display(), a.type(), a.required(), a.referenceTable(), null));
} }
@@ -236,12 +245,63 @@ public class DesignFeatureController {
} }
} }
} }
// 引用驱动联动:refColumn 须为子表「引用列」(type=reference,排除回链 FK);fills[*].target 须为子表真实列
// 且 !=refColumn;source=引用实体列名(标识符白名单,不验其在引用实体存在——错填仅「空填」非「写错值」)。
// childLinkage 同 childDerived/childRollup 用 Object 容错(前端 combo 未触碰发空串/占位串则忽略);
// 列名违标识符白名单一律 400(列名会拼进 ${...} 表达式与 componentId,防注入)。
if (req.childLinkage instanceof List<?> linkageList) {
for (Object item : linkageList) {
if (!(item instanceof Map<?, ?> m)) {
continue;
}
Object refObj = m.get("refColumn");
if (refObj == null || isBlank(refObj.toString())) {
continue;
}
String ref = refObj.toString().trim().toUpperCase(Locale.ROOT);
if (!COLUMN_IDENT.matcher(ref).matches()) {
return ResponseEntity.badRequest().body(fail("联动引用列名非法(须大写字母开头标识符): " + ref));
}
// refColumn 必须是子表引用列,否则该联动无源 select 可挂 → 静默忽略。
if (!childRefCols.contains(ref)) {
continue;
}
if (!(m.get("fills") instanceof List<?> fillsList)) {
continue;
}
List<PageBlueprintChild.Fill> fills = new ArrayList<>();
for (Object fo : fillsList) {
if (!(fo instanceof Map<?, ?> fm)) {
continue;
}
Object tObj = fm.get("target");
Object sObj = fm.get("source");
if (tObj == null || sObj == null || isBlank(tObj.toString()) || isBlank(sObj.toString())) {
continue;
}
String target = tObj.toString().trim().toUpperCase(Locale.ROOT);
String source = sObj.toString().trim().toUpperCase(Locale.ROOT);
if (!COLUMN_IDENT.matcher(target).matches() || !COLUMN_IDENT.matcher(source).matches()) {
return ResponseEntity.badRequest().body(
fail("联动带出列名非法(须大写字母开头标识符): " + target + "←" + source));
}
// 目标列须为子表真实列、且不能是引用源列自身。源列不验在引用实体存在(错填仅空填,非写错值)。
if (!childCols.contains(target) || target.equals(ref)) {
continue;
}
fills.add(new PageBlueprintChild.Fill(target, source));
}
if (!fills.isEmpty()) {
childLinkageCols.add(new PageBlueprintChild.Linkage(ref, fills));
}
}
}
} }
ObjectNode schema = composer.compose(new RecipePageComposer.Spec( ObjectNode schema = composer.compose(new RecipePageComposer.Spec(
req.tableName.trim(), entityNameOf(req), recipe, req.title.trim(), req.tableName.trim(), entityNameOf(req), recipe, req.title.trim(),
displayField, pageSize, specAttrs, childTable, listColumn, childSpecAttrs, displayField, pageSize, specAttrs, childTable, listColumn, childSpecAttrs,
childDerivedCols, childRollupCols)); childDerivedCols, childRollupCols, childLinkageCols));
String schemaJson; String schemaJson;
try { try {
@@ -441,5 +501,8 @@ public class DesignFeatureController {
// master-detail-v1 父级汇总:如 [{masterColumn:"TOTAL",childColumn:"AMOUNT",agg:"SUM"}], // master-detail-v1 父级汇总:如 [{masterColumn:"TOTAL",childColumn:"AMOUNT",agg:"SUM"}],
// 编译为主表只读 SUM 预览 + 写流 __rollup。同 childDerived 用 Object 容错。 // 编译为主表只读 SUM 预览 + 写流 __rollup。同 childDerived 用 Object 容错。
public Object childRollup; public Object childRollup;
// master-detail-v1 引用驱动联动:如 [{refColumn:"ITEMID",fills:[{target:"ITEMPRICE",source:"PRICE"},...]}],
// 编译为子表 refColumn 列的 picker select + onEvent 自动带出。同上用 Object 容错。
public Object childLinkage;
} }
} }

View File

@@ -81,4 +81,85 @@ class TypedPageSchemaValidatorTest {
assertFalse(report.valid()); assertFalse(report.valid());
assertEquals("ROOT_TYPE_NOT_PAGE", report.issues().get(0).code()); assertEquals("ROOT_TYPE_NOT_PAGE", report.issues().get(0).code());
} }
@Test
void allowsSetValueInsideOnEventActions() {
// 引用驱动联动:select 列 onEvent.change.actions[].setValue(action 对象无绑定组件 type),
// 经 EVENT_ACTIONS 白名单放行,不应判 ACTION_WITHOUT_COMPONENT。
TypedPageSchemaReport report = validator.validate("""
{
"type": "page",
"body": {"type": "form", "body": [{
"type": "select", "name": "ITEMID",
"onEvent": {"change": {"actions": [
{"actionType": "setValue", "componentId": "PRICE_${index}", "args": {"value": "${event.data.selectedItems.PRICE}"}}
]}}
}]}
}
""");
assertTrue(report.valid(), "onEvent setValue 应过校验, issues=" + report.issues());
assertTrue(report.usedActions().contains("setValue"));
}
@Test
void rejectsUnknownActionInsideOnEventActions() {
// 白名单收窄:onEvent 动作里非 setValue 的动作(如 reload)仍判 ACTION_WITHOUT_COMPONENT(D3 安全门)。
TypedPageSchemaReport report = validator.validate("""
{
"type": "page",
"body": {"type": "form", "body": [{
"type": "select", "name": "X",
"onEvent": {"change": {"actions": [{"actionType": "reload", "componentId": "Y"}]}}
}]}
}
""");
assertFalse(report.valid());
assertEquals("ACTION_WITHOUT_COMPONENT", report.issues().get(0).code());
}
@Test
void stillRejectsActionWithoutComponentOutsideEventActions() {
// 回归守卫:非 .actions[ 路径下、无组件 type 的 actionType 仍判 ACTION_WITHOUT_COMPONENT。
TypedPageSchemaReport report = validator.validate("""
{"type":"page","body":{"actionType":"setValue"}}
""");
assertFalse(report.valid());
assertEquals("ACTION_WITHOUT_COMPONENT", report.issues().get(0).code());
}
@Test
void rejectsBareSetValueSmuggledIntoNonOnEventActionsArray() {
// 路径锚点收窄(对抗评审 D3 加固):把无 type 的裸 setValue 塞进非 onEvent 的 actions[](如 form 底部
// actions[])应仍判 ACTION_WITHOUT_COMPONENT——只有 onEvent.<event>.actions[] 才放行白名单动作。
TypedPageSchemaReport report = validator.validate("""
{
"type": "page",
"body": {"type": "form", "actions": [
{"actionType": "setValue", "componentId": "X"}
]}
}
""");
assertFalse(report.valid());
assertEquals("ACTION_WITHOUT_COMPONENT", report.issues().get(0).code());
}
@Test
void dialogFooterButtonActionsStillValidatedByComponent() {
// .actions[ 下若是带 type:button 的底部按钮,仍走「组件支持的动作」校验(不被 EVENT_ACTIONS 旁路),
// 保证 dialog/drawer footer 动作不受影响。
TypedPageSchemaReport report = validator.validate("""
{
"type": "page",
"body": {"type": "form", "actions": [
{"type": "button", "actionType": "submit"}
]}
}
""");
assertTrue(report.valid(), "dialog footer button submit 应过校验, issues=" + report.issues());
}
} }

View File

@@ -339,6 +339,131 @@ class PageBlueprintCompilerTest {
assertEquals("input-text", bodyByName((ArrayNode) addForm.path("body"), "TITLE").path("type").asText()); assertEquals("input-text", bodyByName((ArrayNode) addForm.path("body"), "TITLE").path("type").asText());
} }
@Test
@DisplayName("master-detail-v1 引用驱动联动: 子表引用列渲染 picker select + onEvent.change setValue 带出兄弟列, 目标列挂 id=<col>_${index}")
void compilesMasterDetailWithReferenceLinkage() {
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)),
true, true, true, 20,
new PageBlueprintChild("EIP4AI_PURCHASE_ITEM", "DETAILS", "ITEMID",
List.of(
// 源引用列(指向物料实体)
new PageBlueprintField("ITEMID", "物料", "reference", true, false, true,
"EIP4AI_MATERIAL", null),
// 被带出目标列
new PageBlueprintField("ITEMPRICE", "单价", "number", false, false, true),
new PageBlueprintField("ITEMSPEC", "规格", "string", false, false, true)),
List.of(), List.of(),
List.of(new PageBlueprintChild.Linkage("ITEMID", List.of(
new PageBlueprintChild.Fill("ITEMPRICE", "PRICE"),
new PageBlueprintChild.Fill("ITEMSPEC", "SPEC"))))));
ObjectNode schema = new PageBlueprintCompiler(MAPPER).compile(blueprint);
ObjectNode addForm = (ObjectNode) ((ArrayNode) schema.path("body").path("headerToolbar"))
.get(0).path("dialog").path("body");
ArrayNode cols = (ArrayNode) findByType((ArrayNode) addForm.path("body"), "input-table").path("columns");
// 源引用列 ITEMID = picker select(不含 quickEdit)。
ObjectNode item = colByName(cols, "ITEMID");
assertEquals("select", item.path("type").asText());
assertEquals("/api/picker/EIP4AI_MATERIAL/list", item.path("source").path("url").asText());
assertEquals("${items}", item.path("source").path("responseData").path("options").asText());
assertEquals("_label", item.path("labelField").asText());
assertEquals("_id", item.path("valueField").asText());
assertTrue(item.path("quickEdit").isMissingNode(), "select 源列不应再包 quickEdit");
// onEvent.change → 两条 setValue,componentId=<target>_${index},value=${event.data.selectedItems.<source>}(无 [0])。
ArrayNode actions = (ArrayNode) item.path("onEvent").path("change").path("actions");
assertEquals(2, actions.size());
assertEquals("setValue", actions.get(0).path("actionType").asText());
assertEquals("ITEMPRICE_${index}", actions.get(0).path("componentId").asText());
assertEquals("${event.data.selectedItems.PRICE}", actions.get(0).path("args").path("value").asText());
assertEquals("ITEMSPEC_${index}", actions.get(1).path("componentId").asText());
assertEquals("${event.data.selectedItems.SPEC}", actions.get(1).path("args").path("value").asText());
// 目标列挂 id=<col>_${index}(供 setValue componentId 命中),且仍是可编辑 quickEdit。
ObjectNode price = colByName(cols, "ITEMPRICE");
assertEquals("ITEMPRICE_${index}", price.path("id").asText());
assertEquals("input-number", price.path("quickEdit").path("type").asText());
ObjectNode spec = colByName(cols, "ITEMSPEC");
assertEquals("ITEMSPEC_${index}", spec.path("id").asText());
assertEquals("input-text", spec.path("quickEdit").path("type").asText());
// ★ 联动产物必须过严格 typed 校验(onEvent setValue 经 EVENT_ACTIONS 白名单放行)。
try {
String json = MAPPER.writeValueAsString(schema);
com.eip4.platform.metadata.schema.TypedPageSchemaReport report =
com.eip4.platform.metadata.schema.TypedPageSchemaValidator.defaults().validate(json);
assertTrue(report.valid(), "联动 schema 应过 typed 校验, issues=" + report.issues());
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
throw new RuntimeException(e);
}
}
@Test
@DisplayName("联动健壮性: 派生目标列剔除/重复目标去重/非引用 refColumn 不渲 select 也不泄漏 id")
void linkageRobustnessDerivedDedupAndNonReference() {
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)),
true, true, true, 20,
new PageBlueprintChild("EIP4AI_PURCHASE_ITEM", "DETAILS", "ITEMID",
List.of(
new PageBlueprintField("ITEMID", "物料", "reference", true, false, true,
"EIP4AI_MATERIAL", null),
new PageBlueprintField("ITEMPRICE", "单价", "number", false, false, true),
new PageBlueprintField("DISC", "折后", "number", false, false, true),
new PageBlueprintField("NOTREF", "随便", "string", false, false, true),
new PageBlueprintField("TGT", "目标", "number", false, false, true)),
// DISC 是派生列
List.of(new PageBlueprintChild.DerivedColumn("DISC", "ITEMPRICE/10")),
List.of(),
List.of(
// L1: refColumn=ITEMID(合法引用)。fills: ITEMPRICE 出现两次(去重)、DISC 是派生列(剔除)。
new PageBlueprintChild.Linkage("ITEMID", List.of(
new PageBlueprintChild.Fill("ITEMPRICE", "PRICE"),
new PageBlueprintChild.Fill("ITEMPRICE", "PRICE2"),
new PageBlueprintChild.Fill("DISC", "DISCRATE"))),
// L2: refColumn=NOTREF(非引用)→不渲 select、TGT 也不该挂 id。
new PageBlueprintChild.Linkage("NOTREF", List.of(
new PageBlueprintChild.Fill("TGT", "X"))))));
ObjectNode schema = new PageBlueprintCompiler(MAPPER).compile(blueprint);
ObjectNode addForm = (ObjectNode) ((ArrayNode) schema.path("body").path("headerToolbar"))
.get(0).path("dialog").path("body");
ArrayNode cols = (ArrayNode) findByType((ArrayNode) addForm.path("body"), "input-table").path("columns");
// ITEMID select:onEvent 仅 1 条 setValue(ITEMPRICE←PRICE;重复 ITEMPRICE 去重、派生 DISC 剔除)。
ObjectNode item = colByName(cols, "ITEMID");
assertEquals("select", item.path("type").asText());
ArrayNode actions = (ArrayNode) item.path("onEvent").path("change").path("actions");
assertEquals(1, actions.size(), "重复目标去重 + 派生目标剔除后应只剩 1 条 setValue");
assertEquals("ITEMPRICE_${index}", actions.get(0).path("componentId").asText());
assertEquals("${event.data.selectedItems.PRICE}", actions.get(0).path("args").path("value").asText());
// ITEMPRICE 是有效目标 → 挂 id;DISC 是派生列 → tpl 只读、绝不挂 id。
assertEquals("ITEMPRICE_${index}", colByName(cols, "ITEMPRICE").path("id").asText());
ObjectNode disc = colByName(cols, "DISC");
assertEquals("tpl", disc.path("type").asText());
assertTrue(disc.path("id").isMissingNode(), "派生目标列绝不挂 id(否则 setValue 落空)");
// NOTREF 非引用 → 渲普通可编辑列(非 select),无 onEvent;其目标 TGT 不该挂 id。
ObjectNode notRef = colByName(cols, "NOTREF");
assertEquals("input-text", notRef.path("quickEdit").path("type").asText());
assertTrue(notRef.path("onEvent").isMissingNode(), "非引用 refColumn 不应渲 onEvent select");
assertTrue(colByName(cols, "TGT").path("id").isMissingNode(), "非法联动的目标列不应泄漏 id");
}
@Test @Test
@DisplayName("排除标准审计列: 主键/VERSION/CREATETIME/UPDATETIME/CREATEBY/UPDATEBY/ISACTIVE 不进列表/表单,业务列保留;编辑表单仍带 hidden 主键") @DisplayName("排除标准审计列: 主键/VERSION/CREATETIME/UPDATETIME/CREATEBY/UPDATEBY/ISACTIVE 不进列表/表单,业务列保留;编辑表单仍带 hidden 主键")
void excludesSystemColumnsFromFormsAndList() { void excludesSystemColumnsFromFormsAndList() {

View File

@@ -141,6 +141,75 @@ class DesignFeatureControllerTest {
org.mockito.Mockito.verifyNoInteractions(linker); org.mockito.Mockito.verifyNoInteractions(linker);
} }
@Test
@DisplayName("6. master-detail 引用驱动联动: 子表引用列 refColumn → 产物含 picker select + onEvent setValue 带出兄弟列")
void compileMasterDetailWithLinkage() {
PageSchemaWriter writer = mock(PageSchemaWriter.class);
when(writer.upsertStandard(anyString(), anyString(), anyString(), anyString())).thenReturn("etag-lk");
EntityAttributeReader reader = mock(EntityAttributeReader.class);
when(reader.read("EIP4AI_PO")).thenReturn(new EntityAttributes(
"EIP4AI_PO", "TITLE", List.of(
new EntityAttribute("TITLE", "标题", "string", true, null))));
when(reader.read("EIP4AI_PO_ITEM")).thenReturn(new EntityAttributes(
"EIP4AI_PO_ITEM", "ITEMID", List.of(
new EntityAttribute("ITEMID", "物料", "reference", true, "EIP4AI_MATERIAL"),
new EntityAttribute("ITEMPRICE", "单价", "number", false, null),
new EntityAttribute("ITEMSPEC", "规格", "string", false, null),
new EntityAttribute("EIP4AI_PO_ID", "主表", "reference", false, "EIP4AI_PO"))));
var body = new DesignFeatureController.CompileRequest();
body.tableName = "EIP4AI_PO";
body.recipe = "master-detail-v1";
body.title = "采购单";
body.childTable = "EIP4AI_PO_ITEM";
body.linkColumn = "EIP4AI_PO_ID";
body.listColumn = "DETAILS";
body.childLinkage = List.of(Map.of("refColumn", "ITEMID", "fills", List.of(
Map.of("target", "ITEMPRICE", "source", "PRICE"),
Map.of("target", "ITEMSPEC", "source", "SPEC"))));
ResponseEntity<Map<String, Object>> resp = controller(writer, reader).compile(body);
assertEquals(200, resp.getStatusCode().value());
ArgumentCaptor<String> schemaCap = ArgumentCaptor.forClass(String.class);
verify(writer).upsertStandard(anyString(), eq("采购单"), schemaCap.capture(), anyString());
String schema = schemaCap.getValue();
assertTrue(schema.contains("/api/picker/EIP4AI_MATERIAL/list"), schema);
assertTrue(schema.contains("\"setValue\""), schema);
assertTrue(schema.contains("ITEMPRICE_${index}"), schema);
assertTrue(schema.contains("${event.data.selectedItems.PRICE}"), schema);
assertTrue(schema.contains("${event.data.selectedItems.SPEC}"), schema);
}
@Test
@DisplayName("7. 联动列名非法(防注入)→400: source 含非标识符字符(拼进 ${...} 表达式必须拒)")
void compileMasterDetailLinkageRejectsIllegalColumnName() {
PageSchemaWriter writer = mock(PageSchemaWriter.class);
EntityAttributeReader reader = mock(EntityAttributeReader.class);
when(reader.read("EIP4AI_PO")).thenReturn(new EntityAttributes(
"EIP4AI_PO", "TITLE", List.of(new EntityAttribute("TITLE", "标题", "string", true, null))));
when(reader.read("EIP4AI_PO_ITEM")).thenReturn(new EntityAttributes(
"EIP4AI_PO_ITEM", "ITEMID", List.of(
new EntityAttribute("ITEMID", "物料", "reference", true, "EIP4AI_MATERIAL"),
new EntityAttribute("ITEMPRICE", "单价", "number", false, null),
new EntityAttribute("EIP4AI_PO_ID", "主表", "reference", false, "EIP4AI_PO"))));
var body = new DesignFeatureController.CompileRequest();
body.tableName = "EIP4AI_PO";
body.recipe = "master-detail-v1";
body.title = "采购单";
body.childTable = "EIP4AI_PO_ITEM";
body.linkColumn = "EIP4AI_PO_ID";
body.listColumn = "DETAILS";
// source 含 ';' → 标识符白名单拒,防注入进 ${event.data.selectedItems.<source>}。
body.childLinkage = List.of(Map.of("refColumn", "ITEMID", "fills", List.of(
Map.of("target", "ITEMPRICE", "source", "PRICE;DROP"))));
ResponseEntity<Map<String, Object>> resp = controller(writer, reader).compile(body);
assertEquals(400, resp.getStatusCode().value());
org.mockito.Mockito.verifyNoInteractions(writer);
}
@Test @Test
@DisplayName("3. 装配回归:有两个构造器时,生产构造器必须 @Autowired,否则 Spring 回退无参构造启动崩(live e2e 揪出)") @DisplayName("3. 装配回归:有两个构造器时,生产构造器必须 @Autowired,否则 Spring 回退无参构造启动崩(live e2e 揪出)")
void productionConstructorIsAutowired() { void productionConstructorIsAutowired() {