feat(主子表): 派生字段(金额=数量×单价) compute-on-save + tpl 实时预览
零引擎改动:UI 派生列只读 tpl ${公式} 实时预览(quickEdit:false),服务端权威
经写流 ?__derive= 用安全算术求值器逐行 compute-on-save 落库(复用 ?__egtpl=
同款轨道,绕开 amis input-table 前端竞态)。
- RecipeArithmeticEvaluator: 纯算术递归下降/BigDecimal,无任意代码执行;含递归
深度(64)+表达式长度(512)护栏,防深嵌套 StackOverflowError(Error 逃兜底)DoS
- RecipeDerivedFieldComputer: 子表数组逐行求值写回,逐格错误隔离不阻断保存
- PageBlueprintChild.derived + 编译器派生列(tpl + quickEdit:false + 表单 api
URL 编码 __derive);RecipePageComposer/DesignFeatureController 贯通 childDerived
(Object 容错避免 Jackson 400;公式字符白名单拒 |/=/; 防静默写错值)
- FlowController.executePost 接 __derive(9 参 @Autowired + 反射回归测试)
对抗评审(36 agent)揪修 3 真 bug:amis needConfirm:false 强注 quickEdit 需显式
false 才保留 tpl 预览;求值器深嵌套 Error 逃逐行兜底;公式 | 破坏 spec 切分。
+9 单测,curl live e2e 含负控 PASS,Playwright 3/3。
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,197 @@
|
|||||||
|
package com.eip4.platform.metadata.flow;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.MathContext;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 极小安全算术求值器——recipe 派生字段服务端 compute-on-save 专用(如 金额=数量×单价)。
|
||||||
|
*
|
||||||
|
* <p>只支持 {@code + - * / ( )}、数字字面量、列名(标识符,从当前行 map 解析)。<b>无任意代码执行</b>
|
||||||
|
* (不走 Groovy/JS/EL 引擎,杜绝注入面),故公式来源即便最终来自设计者输入也安全。递归下降解析,
|
||||||
|
* BigDecimal 计算(金额场景精度安全)。
|
||||||
|
*
|
||||||
|
* <p>取值约定:列名 → 行 map 同名值,{@code null}/空白当 {@code 0}(缺失操作数=0,合理);
|
||||||
|
* 数字(Number)精确转 BigDecimal;非空非数字字符串 → 抛 {@link NumberFormatException}
|
||||||
|
* (交由调用方逐行兜底跳过,绝不静默写错值)。除零、畸形表达式均抛异常。
|
||||||
|
*/
|
||||||
|
public final class RecipeArithmeticEvaluator {
|
||||||
|
|
||||||
|
private static final MathContext MC = MathContext.DECIMAL64;
|
||||||
|
/** 表达式长度上限:防超长合法表达式 × 大子表逐行求值的 CPU 放大 DoS。 */
|
||||||
|
private static final int MAX_EXPR_LEN = 512;
|
||||||
|
/** 递归嵌套深度上限:防深嵌套括号/连续一元符触发 StackOverflowError(Error 会逃过逐行兜底→500 DoS)。 */
|
||||||
|
private static final int MAX_DEPTH = 64;
|
||||||
|
|
||||||
|
/** 求值 {@code expr},列名从 {@code row} 解析。空/超长/畸形/嵌套过深/除零/非数字操作数 → 抛运行时异常。 */
|
||||||
|
public BigDecimal eval(String expr, Map<String, Object> row) {
|
||||||
|
if (expr == null || expr.isBlank()) {
|
||||||
|
throw new IllegalArgumentException("空表达式");
|
||||||
|
}
|
||||||
|
if (expr.length() > MAX_EXPR_LEN) {
|
||||||
|
throw new IllegalArgumentException("表达式过长(>" + MAX_EXPR_LEN + ")");
|
||||||
|
}
|
||||||
|
Parser p = new Parser(expr, row == null ? Map.of() : row);
|
||||||
|
BigDecimal result = p.parseExpression();
|
||||||
|
p.expectEnd();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 递归下降:expression = term (('+'|'-') term)* ; term = factor (('*'|'/') factor)* 。 */
|
||||||
|
private static final class Parser {
|
||||||
|
private final String s;
|
||||||
|
private final Map<String, Object> row;
|
||||||
|
private int pos;
|
||||||
|
private int depth;
|
||||||
|
|
||||||
|
Parser(String s, Map<String, Object> row) {
|
||||||
|
this.s = s;
|
||||||
|
this.row = row;
|
||||||
|
}
|
||||||
|
|
||||||
|
BigDecimal parseExpression() {
|
||||||
|
BigDecimal v = parseTerm();
|
||||||
|
while (true) {
|
||||||
|
char op = peekOp();
|
||||||
|
if (op == '+') {
|
||||||
|
pos++;
|
||||||
|
v = v.add(parseTerm(), MC);
|
||||||
|
} else if (op == '-') {
|
||||||
|
pos++;
|
||||||
|
v = v.subtract(parseTerm(), MC);
|
||||||
|
} else {
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private BigDecimal parseTerm() {
|
||||||
|
BigDecimal v = parseFactor();
|
||||||
|
while (true) {
|
||||||
|
char op = peekOp();
|
||||||
|
if (op == '*') {
|
||||||
|
pos++;
|
||||||
|
v = v.multiply(parseFactor(), MC);
|
||||||
|
} else if (op == '/') {
|
||||||
|
pos++;
|
||||||
|
BigDecimal d = parseFactor();
|
||||||
|
if (d.signum() == 0) {
|
||||||
|
throw new ArithmeticException("除零");
|
||||||
|
}
|
||||||
|
v = v.divide(d, 10, RoundingMode.HALF_UP).stripTrailingZeros();
|
||||||
|
} else {
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private BigDecimal parseFactor() {
|
||||||
|
// 嵌套深度护栏:递增进、try/finally 递出,反映当前栈深而非总调用数;超限抛 RuntimeException
|
||||||
|
// (会被 RecipeDerivedFieldComputer 逐行兜底吞掉),避免 StackOverflowError(Error)逃过兜底致 500。
|
||||||
|
if (++depth > MAX_DEPTH) {
|
||||||
|
throw new IllegalArgumentException("表达式嵌套过深(>" + MAX_DEPTH + ")");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
skipWs();
|
||||||
|
if (pos >= s.length()) {
|
||||||
|
throw new IllegalArgumentException("表达式提前结束: " + s);
|
||||||
|
}
|
||||||
|
char c = s.charAt(pos);
|
||||||
|
if (c == '-') {
|
||||||
|
pos++;
|
||||||
|
return parseFactor().negate();
|
||||||
|
}
|
||||||
|
if (c == '+') {
|
||||||
|
pos++;
|
||||||
|
return parseFactor();
|
||||||
|
}
|
||||||
|
if (c == '(') {
|
||||||
|
pos++;
|
||||||
|
BigDecimal v = parseExpression();
|
||||||
|
skipWs();
|
||||||
|
if (pos >= s.length() || s.charAt(pos) != ')') {
|
||||||
|
throw new IllegalArgumentException("缺右括号: " + s);
|
||||||
|
}
|
||||||
|
pos++;
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
if (c == '.' || Character.isDigit(c)) {
|
||||||
|
return parseNumber();
|
||||||
|
}
|
||||||
|
if (Character.isLetter(c) || c == '_') {
|
||||||
|
return resolve(parseIdentifier());
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException("非法字符 '" + c + "' @ " + pos + " in " + s);
|
||||||
|
} finally {
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private BigDecimal parseNumber() {
|
||||||
|
int start = pos;
|
||||||
|
while (pos < s.length() && (Character.isDigit(s.charAt(pos)) || s.charAt(pos) == '.')) {
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
return new BigDecimal(s.substring(start, pos));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String parseIdentifier() {
|
||||||
|
int start = pos;
|
||||||
|
while (pos < s.length()
|
||||||
|
&& (Character.isLetterOrDigit(s.charAt(pos)) || s.charAt(pos) == '_')) {
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
return s.substring(start, pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 列名 → 行值 → BigDecimal。null/空白当 0;Number 精确;非空非数字字符串抛 NumberFormatException。 */
|
||||||
|
private BigDecimal resolve(String name) {
|
||||||
|
Object v = row.get(name);
|
||||||
|
if (v == null) {
|
||||||
|
// 大小写兜底(保真层有时回大写键)。
|
||||||
|
for (Map.Entry<String, Object> e : row.entrySet()) {
|
||||||
|
if (name.equalsIgnoreCase(e.getKey())) {
|
||||||
|
v = e.getValue();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (v == null) {
|
||||||
|
return BigDecimal.ZERO;
|
||||||
|
}
|
||||||
|
if (v instanceof BigDecimal bd) {
|
||||||
|
return bd;
|
||||||
|
}
|
||||||
|
if (v instanceof Number n) {
|
||||||
|
return new BigDecimal(n.toString());
|
||||||
|
}
|
||||||
|
String str = v.toString().trim();
|
||||||
|
if (str.isEmpty()) {
|
||||||
|
return BigDecimal.ZERO;
|
||||||
|
}
|
||||||
|
return new BigDecimal(str); // 非数字 → NumberFormatException,交由调用方逐行兜底
|
||||||
|
}
|
||||||
|
|
||||||
|
private char peekOp() {
|
||||||
|
skipWs();
|
||||||
|
if (pos >= s.length()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return s.charAt(pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void skipWs() {
|
||||||
|
while (pos < s.length() && Character.isWhitespace(s.charAt(pos))) {
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void expectEnd() {
|
||||||
|
skipWs();
|
||||||
|
if (pos != s.length()) {
|
||||||
|
throw new IllegalArgumentException("表达式有多余内容 @ " + pos + ": " + s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
package com.eip4.platform.metadata.flow;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* recipe 主子表写流 compute-on-save:落库前对提交 map 的子表数组逐行补算派生字段
|
||||||
|
* (如 金额=数量×单价),服务端权威,绕开 amis input-table 前端 onEvent 的 React setState 竞态。
|
||||||
|
*
|
||||||
|
* <p>与 {@link EditGridDerivedFieldComputer}(迁移页·读 view_page XML 跑 Groovy)不同:本组件服务
|
||||||
|
* <b>新建 recipe 页</b>——派生公式由设计中心编译时以 {@code ?__derive=} 透传,无 view_page 依赖、无
|
||||||
|
* 存储改造。求值走 {@link RecipeArithmeticEvaluator}(纯算术、无任意代码执行)。
|
||||||
|
*
|
||||||
|
* <p>spec 格式(Spring @RequestParam 已 URL 解码):{@code "LISTCOL|TARGET1=EXPR1|TARGET2=EXPR2"}。
|
||||||
|
* 首段为子表列名(amis input-table 的 name,如 DETAILS),其后每段 {@code 目标列=公式}。同一行内
|
||||||
|
* 按声明顺序应用,后者可引用前者刚算出的结果(如 含税=金额*1.13)。
|
||||||
|
*
|
||||||
|
* <p>纪律:任一行任一列求值失败(非数字操作数/除零/畸形)只跳过该格并告警,绝不静默写错值、绝不阻断
|
||||||
|
* 保存(派生字段缺失好过保存失败)。零改 {@code com.dsasp}。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class RecipeDerivedFieldComputer {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(RecipeDerivedFieldComputer.class);
|
||||||
|
|
||||||
|
private final RecipeArithmeticEvaluator evaluator = new RecipeArithmeticEvaluator();
|
||||||
|
|
||||||
|
/** 就地为提交 map 补算 recipe 派生字段。spec 空 / 无子表数组 → 无操作。 */
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public void enrich(Map<String, Object> map, String deriveSpec) {
|
||||||
|
if (map == null || deriveSpec == null || deriveSpec.isBlank()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
String[] parts = deriveSpec.split("\\|");
|
||||||
|
if (parts.length < 2) {
|
||||||
|
return; // 无 target=expr 段
|
||||||
|
}
|
||||||
|
String listColumn = parts[0].trim();
|
||||||
|
Object listObj = caseInsensitiveGet(map, listColumn);
|
||||||
|
if (!(listObj instanceof List<?> rawRows) || rawRows.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
List<String[]> specs = new ArrayList<>();
|
||||||
|
for (int i = 1; i < parts.length; i++) {
|
||||||
|
String seg = parts[i];
|
||||||
|
int eq = seg.indexOf('=');
|
||||||
|
if (eq <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String target = seg.substring(0, eq).trim();
|
||||||
|
String expr = seg.substring(eq + 1).trim();
|
||||||
|
if (!target.isEmpty() && !expr.isEmpty()) {
|
||||||
|
specs.add(new String[] {target, expr});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (specs.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (Object r : rawRows) {
|
||||||
|
if (!(r instanceof Map)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Map<String, Object> rowMap = (Map<String, Object>) r;
|
||||||
|
for (String[] sp : specs) {
|
||||||
|
try {
|
||||||
|
BigDecimal val = evaluator.eval(sp[1], rowMap);
|
||||||
|
rowMap.put(sp[0], val); // 写回:后续派生列可引用本列结果
|
||||||
|
} catch (RuntimeException ex) {
|
||||||
|
log.warn("[RecipeDerived] 跳过 {}={} : {}", sp[0], sp[1], ex.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("[RecipeDerived] compute-on-save 跳过 spec={}: {}", deriveSpec, e.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Object caseInsensitiveGet(Map<String, Object> map, String key) {
|
||||||
|
if (map.containsKey(key)) {
|
||||||
|
return map.get(key);
|
||||||
|
}
|
||||||
|
for (Map.Entry<String, Object> e : map.entrySet()) {
|
||||||
|
if (key.equalsIgnoreCase(e.getKey())) {
|
||||||
|
return e.getValue();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,18 +10,51 @@ import java.util.List;
|
|||||||
* 保真层默认流 _ADD/_UPDATE 经 LIST 属性级联落子表(已实测)。编辑态经 _LOAD 回显
|
* 保真层默认流 _ADD/_UPDATE 经 LIST 属性级联落子表(已实测)。编辑态经 _LOAD 回显
|
||||||
* data.result.{@code listColumn} 的子行。
|
* data.result.{@code listColumn} 的子行。
|
||||||
*
|
*
|
||||||
|
* <p>{@link #derived} 声明派生列(如 金额=数量×单价):编译器把这些列渲染成只读 {@code tpl} 计算单元格
|
||||||
|
* (amis 实时预览),并在写流表单 api 上以 {@code ?__derive=} 透传公式,由
|
||||||
|
* {@code RecipeDerivedFieldComputer} 落库前服务端逐行权威求值(绕开前端竞态)。
|
||||||
|
*
|
||||||
* @param childTable 子表表名(普通实体 tabletype=1)
|
* @param childTable 子表表名(普通实体 tabletype=1)
|
||||||
* @param listColumn 主表 LIST 属性列名(amis input-table 的 name,如 DETAILS)
|
* @param listColumn 主表 LIST 属性列名(amis input-table 的 name,如 DETAILS)
|
||||||
* @param displayField 子表显示字段(预留;当前仅作元信息)
|
* @param displayField 子表显示字段(预留;当前仅作元信息)
|
||||||
* @param fields 子表可编辑列(每列经 controlType 映射为 quickEdit 控件)
|
* @param fields 子表可编辑列(每列经 controlType 映射为 quickEdit 控件)
|
||||||
|
* @param derived 派生列(目标列名 + 算术公式,公式引用同行其它子列)
|
||||||
*/
|
*/
|
||||||
public record PageBlueprintChild(
|
public record PageBlueprintChild(
|
||||||
String childTable,
|
String childTable,
|
||||||
String listColumn,
|
String listColumn,
|
||||||
String displayField,
|
String displayField,
|
||||||
List<PageBlueprintField> fields) {
|
List<PageBlueprintField> fields,
|
||||||
|
List<DerivedColumn> derived) {
|
||||||
|
|
||||||
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 4-arg 兼容构造:无派生列。保持既有调用方/测试零改。 */
|
||||||
|
public PageBlueprintChild(String childTable, String listColumn, String displayField,
|
||||||
|
List<PageBlueprintField> fields) {
|
||||||
|
this(childTable, listColumn, displayField, fields, List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 某子列名是否为派生列(编译器据此渲染只读 tpl 而非 quickEdit 输入)。 */
|
||||||
|
public DerivedColumn derivedFor(String column) {
|
||||||
|
if (column == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (DerivedColumn d : derived) {
|
||||||
|
if (column.equalsIgnoreCase(d.column())) {
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单个派生列:{@code column} 目标列名(须为子表真实列),{@code formula} 算术公式
|
||||||
|
* (引用同行其它子列名,如 {@code ITEMQTY*ITEMPRICE})。
|
||||||
|
*/
|
||||||
|
public record DerivedColumn(String column, String formula) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package com.eip4.platform.metadata.schema.blueprint;
|
package com.eip4.platform.metadata.schema.blueprint;
|
||||||
|
|
||||||
|
import java.net.URLEncoder;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
@@ -87,7 +89,7 @@ public final class PageBlueprintCompiler {
|
|||||||
addDialog.put("size", "lg");
|
addDialog.put("size", "lg");
|
||||||
ObjectNode addForm = addDialog.putObject("body");
|
ObjectNode addForm = addDialog.putObject("body");
|
||||||
addForm.put("type", "form");
|
addForm.put("type", "form");
|
||||||
addForm.put("api", "post:/api/flow/" + blueprint.tableName() + "_ADD");
|
addForm.put("api", masterDetailFormApi(blueprint, "_ADD"));
|
||||||
addForm.put("reload", crudName);
|
addForm.put("reload", crudName);
|
||||||
ArrayNode controls = formControls(blueprint, false);
|
ArrayNode controls = formControls(blueprint, false);
|
||||||
controls.add(childInputTable(blueprint.child()));
|
controls.add(childInputTable(blueprint.child()));
|
||||||
@@ -108,7 +110,7 @@ public final class PageBlueprintCompiler {
|
|||||||
dialog.put("size", "lg");
|
dialog.put("size", "lg");
|
||||||
ObjectNode editForm = dialog.putObject("body");
|
ObjectNode editForm = dialog.putObject("body");
|
||||||
editForm.put("type", "form");
|
editForm.put("type", "form");
|
||||||
editForm.put("api", "post:/api/flow/" + blueprint.tableName() + "_UPDATE");
|
editForm.put("api", masterDetailFormApi(blueprint, "_UPDATE"));
|
||||||
editForm.put("reload", crudName);
|
editForm.put("reload", crudName);
|
||||||
// 经 _LOAD 回显主+子行(data.result.<listColumn>=子行,已实测)。
|
// 经 _LOAD 回显主+子行(data.result.<listColumn>=子行,已实测)。
|
||||||
ObjectNode initApi = editForm.putObject("initApi");
|
ObjectNode initApi = editForm.putObject("initApi");
|
||||||
@@ -144,13 +146,54 @@ public final class PageBlueprintCompiler {
|
|||||||
ObjectNode col = columns.addObject();
|
ObjectNode col = columns.addObject();
|
||||||
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());
|
||||||
|
if (derived != null) {
|
||||||
|
// 派生列:只读 tpl 计算单元格,amis 按 ${公式} 实时预览(非表单项→不提交);
|
||||||
|
// 落库由写流 ?__derive= 服务端权威逐行求值(绕开 input-table 前端竞态)。
|
||||||
|
// ★ quickEdit:false 必加:amis input-table 在 needConfirm:false 下会给「每一列」强注默认
|
||||||
|
// quickEdit(input-text),把列自带 type:tpl 丢弃→新增/编辑态渲染成可编辑空框而非只读预览;
|
||||||
|
// 仅当列显式 quickEdit===false 才跳过强注,保留 tpl 实时预览(对抗评审 HIGH 揪出)。
|
||||||
|
col.put("type", "tpl");
|
||||||
|
col.put("tpl", "${" + derived.formula() + "}");
|
||||||
|
col.put("quickEdit", false);
|
||||||
|
} else {
|
||||||
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());
|
||||||
}
|
}
|
||||||
|
}
|
||||||
return table;
|
return table;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 主子表写流表单 api:基础 {@code post:/api/flow/<TABLE><verb>};子表声明派生列时追加 URL 编码的
|
||||||
|
* {@code ?__derive=<listColumn>|<目标列>=<公式>|...},由 {@code RecipeDerivedFieldComputer} 落库前
|
||||||
|
* 服务端逐行权威求算(如 金额=数量×单价),与 UI tpl 预览同源公式。
|
||||||
|
*/
|
||||||
|
private static String masterDetailFormApi(PageBlueprint blueprint, String verb) {
|
||||||
|
String api = "post:/api/flow/" + blueprint.tableName() + verb;
|
||||||
|
String derive = deriveSpec(blueprint.child());
|
||||||
|
if (derive != null) {
|
||||||
|
api += "?__derive=" + URLEncoder.encode(derive, StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
return api;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 派生 spec:{@code DETAILS|MONEY=QTY*PRICE|TAXED=MONEY*1.13};无派生列返回 null。公式去空白保 URL 安全。 */
|
||||||
|
private static String deriveSpec(PageBlueprintChild child) {
|
||||||
|
if (child == null || child.derived().isEmpty()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
StringBuilder sb = new StringBuilder(child.listColumn());
|
||||||
|
for (PageBlueprintChild.DerivedColumn d : child.derived()) {
|
||||||
|
if (d.column() == null || d.column().isBlank() || d.formula() == null || d.formula().isBlank()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
sb.append('|').append(d.column().trim()).append('=').append(d.formula().replaceAll("\\s+", ""));
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 单表维护页,对齐转换器 house-style:
|
* 单表维护页,对齐转换器 house-style:
|
||||||
* <ul>
|
* <ul>
|
||||||
|
|||||||
@@ -66,7 +66,8 @@ public final class RecipePageComposer {
|
|||||||
a.required(), false, true,
|
a.required(), false, true,
|
||||||
a.referenceTable(), a.displayColumn()));
|
a.referenceTable(), a.displayColumn()));
|
||||||
}
|
}
|
||||||
return new PageBlueprintChild(spec.childTable().trim(), spec.listColumn().trim(), null, childFields);
|
return new PageBlueprintChild(spec.childTable().trim(), spec.listColumn().trim(), null,
|
||||||
|
childFields, spec.childDerived());
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String deriveDisplayField(List<AttrSpec> attrs) {
|
private static String deriveDisplayField(List<AttrSpec> attrs) {
|
||||||
@@ -101,17 +102,27 @@ public final class RecipePageComposer {
|
|||||||
List<AttrSpec> attributes,
|
List<AttrSpec> attributes,
|
||||||
String childTable,
|
String childTable,
|
||||||
String listColumn,
|
String listColumn,
|
||||||
List<AttrSpec> childAttributes) {
|
List<AttrSpec> childAttributes,
|
||||||
|
List<PageBlueprintChild.DerivedColumn> childDerived) {
|
||||||
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 7-arg 兼容构造:单表/树 recipe 无子表。保持既有调用方/测试零改。 */
|
/** 7-arg 兼容构造:单表/树 recipe 无子表。保持既有调用方/测试零改。 */
|
||||||
public Spec(String tableName, String entityName, String recipe, String title,
|
public Spec(String tableName, String entityName, String recipe, String title,
|
||||||
String displayField, int pageSize, List<AttrSpec> attributes) {
|
String displayField, int pageSize, List<AttrSpec> attributes) {
|
||||||
this(tableName, entityName, recipe, title, displayField, pageSize, attributes,
|
this(tableName, entityName, recipe, title, displayField, pageSize, attributes,
|
||||||
null, null, List.of());
|
null, null, List.of(), List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,10 +3,12 @@ package com.eip4.platform.metadata.web;
|
|||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@@ -27,6 +29,7 @@ import com.eip4.platform.metadata.schema.PageSchemaWriter;
|
|||||||
import com.eip4.platform.metadata.schema.TypedPageSchemaReport;
|
import com.eip4.platform.metadata.schema.TypedPageSchemaReport;
|
||||||
import com.eip4.platform.metadata.schema.TypedPageSchemaValidator;
|
import com.eip4.platform.metadata.schema.TypedPageSchemaValidator;
|
||||||
import com.eip4.platform.metadata.schema.blueprint.PageBlueprint;
|
import com.eip4.platform.metadata.schema.blueprint.PageBlueprint;
|
||||||
|
import com.eip4.platform.metadata.schema.blueprint.PageBlueprintChild;
|
||||||
import com.eip4.platform.metadata.schema.blueprint.RecipePageComposer;
|
import com.eip4.platform.metadata.schema.blueprint.RecipePageComposer;
|
||||||
import com.eip4.platform.metadata.web.EntityAttributeReader.EntityAttribute;
|
import com.eip4.platform.metadata.web.EntityAttributeReader.EntityAttribute;
|
||||||
import com.eip4.platform.metadata.web.EntityAttributeReader.EntityAttributes;
|
import com.eip4.platform.metadata.web.EntityAttributeReader.EntityAttributes;
|
||||||
@@ -51,6 +54,9 @@ public class DesignFeatureController {
|
|||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(DesignFeatureController.class);
|
private static final Logger log = LoggerFactory.getLogger(DesignFeatureController.class);
|
||||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||||
|
/** 派生公式字符白名单:列名/数字/+ - * / ( ) . 与空白。拒 '|' '=' 等防 __derive 段切分被破坏。 */
|
||||||
|
private static final java.util.regex.Pattern DERIVED_FORMULA =
|
||||||
|
java.util.regex.Pattern.compile("[A-Za-z0-9_+\\-*/(). ]+");
|
||||||
|
|
||||||
private final PageSchemaWriter pageSchemaWriter;
|
private final PageSchemaWriter pageSchemaWriter;
|
||||||
private final EntityAttributeReader attributeReader;
|
private final EntityAttributeReader attributeReader;
|
||||||
@@ -141,6 +147,7 @@ public class DesignFeatureController {
|
|||||||
String childTable = null;
|
String childTable = null;
|
||||||
String listColumn = null;
|
String listColumn = null;
|
||||||
List<RecipePageComposer.AttrSpec> childSpecAttrs = new ArrayList<>();
|
List<RecipePageComposer.AttrSpec> childSpecAttrs = new ArrayList<>();
|
||||||
|
List<PageBlueprintChild.DerivedColumn> childDerivedCols = new ArrayList<>();
|
||||||
if (masterDetail) {
|
if (masterDetail) {
|
||||||
childTable = req.childTable.trim();
|
childTable = req.childTable.trim();
|
||||||
String linkColumn = req.linkColumn.trim();
|
String linkColumn = req.linkColumn.trim();
|
||||||
@@ -161,7 +168,9 @@ public class DesignFeatureController {
|
|||||||
if (childAttrs == null || childAttrs.columns().isEmpty()) {
|
if (childAttrs == null || childAttrs.columns().isEmpty()) {
|
||||||
return ResponseEntity.badRequest().body(fail("子表无可用属性: " + childTable));
|
return ResponseEntity.badRequest().body(fail("子表无可用属性: " + childTable));
|
||||||
}
|
}
|
||||||
|
Set<String> childCols = new HashSet<>();
|
||||||
for (EntityAttribute a : childAttrs.columns()) {
|
for (EntityAttribute a : childAttrs.columns()) {
|
||||||
|
childCols.add(a.column().toUpperCase(Locale.ROOT));
|
||||||
// 子表的外键引用列(指回主表)不作为可编辑子列展示。
|
// 子表的外键引用列(指回主表)不作为可编辑子列展示。
|
||||||
if (linkColumn.equalsIgnoreCase(a.column())) {
|
if (linkColumn.equalsIgnoreCase(a.column())) {
|
||||||
continue;
|
continue;
|
||||||
@@ -169,11 +178,38 @@ public class DesignFeatureController {
|
|||||||
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));
|
||||||
}
|
}
|
||||||
|
// 派生列:目标列须为子表真实列(否则引擎落库会因未知列报错),公式非空;非法项静默忽略。
|
||||||
|
// childDerived 容错按 Object 接(见 CompileRequest):仅当为 List<{column,formula}> 才解析,
|
||||||
|
// 其余形态(未解析占位串/空串/null)一律忽略——装饰性可选字段绝不 400 掉核心编译。
|
||||||
|
if (req.childDerived instanceof List<?> derivedList) {
|
||||||
|
for (Object item : derivedList) {
|
||||||
|
if (!(item instanceof Map<?, ?> m)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Object colObj = m.get("column");
|
||||||
|
Object fObj = m.get("formula");
|
||||||
|
if (colObj == null || fObj == null
|
||||||
|
|| isBlank(colObj.toString()) || isBlank(fObj.toString())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String col = colObj.toString().trim().toUpperCase(Locale.ROOT);
|
||||||
|
String formula = fObj.toString().trim();
|
||||||
|
// 公式字符白名单:仅列名/数字/+ - * / ( ) . 与空白。拒 '|' '=' ';' 等——'|' 会破坏
|
||||||
|
// __derive 段切分致「部分公式」被静默当完整公式求值落库(违反「绝不静默写错值」红线)。
|
||||||
|
if (!DERIVED_FORMULA.matcher(formula).matches()) {
|
||||||
|
return ResponseEntity.badRequest().body(fail(
|
||||||
|
"派生公式含非法字符(仅允许列名/数字/+ - * / ( ) .): " + formula));
|
||||||
|
}
|
||||||
|
if (childCols.contains(col)) {
|
||||||
|
childDerivedCols.add(new PageBlueprintChild.DerivedColumn(col, formula));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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));
|
||||||
|
|
||||||
String schemaJson;
|
String schemaJson;
|
||||||
try {
|
try {
|
||||||
@@ -366,5 +402,9 @@ public class DesignFeatureController {
|
|||||||
public String linkColumn;
|
public String linkColumn;
|
||||||
public String listColumn;
|
public String listColumn;
|
||||||
public String listLabel;
|
public String listLabel;
|
||||||
|
// master-detail-v1 派生列:如 [{column:"MONEY",formula:"QTY*PRICE"}],编译为只读 tpl + 写流 __derive。
|
||||||
|
// 按 Object 容错接收:前端 combo 未触碰时 amis 可能发未解析占位串/空串,那种情况 Jackson 映射进
|
||||||
|
// List 会 400 掉整个编译;用 Object 接、控制器仅在确为 List<{column,formula}> 时解析,其余忽略。
|
||||||
|
public Object childDerived;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ import com.dsasp.server.common.util.UserSession;
|
|||||||
import com.eip4.platform.metadata.flow.EditGridDerivedFieldComputer;
|
import com.eip4.platform.metadata.flow.EditGridDerivedFieldComputer;
|
||||||
import com.eip4.platform.metadata.flow.FlowInputCoercer;
|
import com.eip4.platform.metadata.flow.FlowInputCoercer;
|
||||||
import com.eip4.platform.metadata.flow.FlowNameResolver;
|
import com.eip4.platform.metadata.flow.FlowNameResolver;
|
||||||
|
import com.eip4.platform.metadata.flow.RecipeDerivedFieldComputer;
|
||||||
import com.eip4.platform.metadata.flow.FlowNameResolver.ResolvedFlow;
|
import com.eip4.platform.metadata.flow.FlowNameResolver.ResolvedFlow;
|
||||||
import com.eip4.platform.metadata.flow.FlowReadWriteClassifier;
|
import com.eip4.platform.metadata.flow.FlowReadWriteClassifier;
|
||||||
import com.eip4.platform.metadata.flow.UserColumnResolver;
|
import com.eip4.platform.metadata.flow.UserColumnResolver;
|
||||||
@@ -80,17 +81,20 @@ public class FlowController {
|
|||||||
private final FlowInputCoercer inputCoercer;
|
private final FlowInputCoercer inputCoercer;
|
||||||
/** A1 compute-on-save:写流执行前为 editgrid 子表补算派生字段(金额/总额)。可空(老单测构造)。 */
|
/** A1 compute-on-save:写流执行前为 editgrid 子表补算派生字段(金额/总额)。可空(老单测构造)。 */
|
||||||
private final EditGridDerivedFieldComputer editGridComputer;
|
private final EditGridDerivedFieldComputer editGridComputer;
|
||||||
|
/** recipe 主子表写流 compute-on-save:?__derive= 透传时落库前逐行补派生字段。可空(老单测构造)。 */
|
||||||
|
private final RecipeDerivedFieldComputer recipeDerivedComputer;
|
||||||
/** 编辑弹窗 load:把 picker 默认值裸 id 解析成 {_id,_label}。可空(老单测构造)。 */
|
/** 编辑弹窗 load:把 picker 默认值裸 id 解析成 {_id,_label}。可空(老单测构造)。 */
|
||||||
private final JdbcTemplate jdbcTemplate;
|
private final JdbcTemplate jdbcTemplate;
|
||||||
private final PickerController pickerController;
|
private final PickerController pickerController;
|
||||||
|
|
||||||
/** Spring 注入入口(8 参:读写分类器 + 类型强制器 + editgrid 派生字段补算器 + picker 默认值解析)。
|
/** Spring 注入入口(9 参:读写分类器 + 类型强制器 + editgrid/recipe 派生补算器 + picker 默认值解析)。
|
||||||
* 多构造器场景须显式 @Autowired 指明注入构造,否则 Spring 回退无参构造致启动失败。 */
|
* 多构造器场景须显式 @Autowired 指明注入构造,否则 Spring 回退无参构造致启动失败。 */
|
||||||
@org.springframework.beans.factory.annotation.Autowired
|
@org.springframework.beans.factory.annotation.Autowired
|
||||||
public FlowController(FlowExcuteService flowExcuteService, FlowNameResolver flowNameResolver,
|
public FlowController(FlowExcuteService flowExcuteService, FlowNameResolver flowNameResolver,
|
||||||
UserColumnResolver userColumnResolver, FlowReadWriteClassifier classifier,
|
UserColumnResolver userColumnResolver, FlowReadWriteClassifier classifier,
|
||||||
FlowInputCoercer inputCoercer, EditGridDerivedFieldComputer editGridComputer,
|
FlowInputCoercer inputCoercer, EditGridDerivedFieldComputer editGridComputer,
|
||||||
JdbcTemplate jdbcTemplate, PickerController pickerController) {
|
JdbcTemplate jdbcTemplate, PickerController pickerController,
|
||||||
|
RecipeDerivedFieldComputer recipeDerivedComputer) {
|
||||||
this.flowExcuteService = flowExcuteService;
|
this.flowExcuteService = flowExcuteService;
|
||||||
this.flowNameResolver = flowNameResolver;
|
this.flowNameResolver = flowNameResolver;
|
||||||
this.userColumnResolver = userColumnResolver;
|
this.userColumnResolver = userColumnResolver;
|
||||||
@@ -99,6 +103,16 @@ public class FlowController {
|
|||||||
this.editGridComputer = editGridComputer;
|
this.editGridComputer = editGridComputer;
|
||||||
this.jdbcTemplate = jdbcTemplate;
|
this.jdbcTemplate = jdbcTemplate;
|
||||||
this.pickerController = pickerController;
|
this.pickerController = pickerController;
|
||||||
|
this.recipeDerivedComputer = recipeDerivedComputer;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 兼容老单测/旧调用的八参构造(无 recipe 派生补算器)。生产由 Spring 走九参构造。 */
|
||||||
|
public FlowController(FlowExcuteService flowExcuteService, FlowNameResolver flowNameResolver,
|
||||||
|
UserColumnResolver userColumnResolver, FlowReadWriteClassifier classifier,
|
||||||
|
FlowInputCoercer inputCoercer, EditGridDerivedFieldComputer editGridComputer,
|
||||||
|
JdbcTemplate jdbcTemplate, PickerController pickerController) {
|
||||||
|
this(flowExcuteService, flowNameResolver, userColumnResolver, classifier, inputCoercer,
|
||||||
|
editGridComputer, jdbcTemplate, pickerController, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 兼容老单测的六参构造(无 picker 默认值解析)。生产由 Spring 走八参构造。 */
|
/** 兼容老单测的六参构造(无 picker 默认值解析)。生产由 Spring 走八参构造。 */
|
||||||
@@ -162,6 +176,7 @@ public class FlowController {
|
|||||||
@Operation(summary = "执行服务流(POST):JSON body 作为入参 map,返回流输出 JSON")
|
@Operation(summary = "执行服务流(POST):JSON body 作为入参 map,返回流输出 JSON")
|
||||||
public ResponseEntity<Map<String, Object>> executePost(@PathVariable String id,
|
public ResponseEntity<Map<String, Object>> executePost(@PathVariable String id,
|
||||||
@RequestParam(value = "__egtpl", required = false) String egTpl,
|
@RequestParam(value = "__egtpl", required = false) String egTpl,
|
||||||
|
@RequestParam(value = "__derive", required = false) String derive,
|
||||||
@RequestBody(required = false) Map<String, Object> body) {
|
@RequestBody(required = false) Map<String, Object> body) {
|
||||||
Map<String, Object> map = body == null ? new HashMap<>() : new HashMap<>(body);
|
Map<String, Object> map = body == null ? new HashMap<>() : new HashMap<>(body);
|
||||||
applyPaging(map);
|
applyPaging(map);
|
||||||
@@ -170,6 +185,11 @@ public class FlowController {
|
|||||||
if (egTpl != null && !egTpl.isBlank() && editGridComputer != null) {
|
if (egTpl != null && !egTpl.isBlank() && editGridComputer != null) {
|
||||||
editGridComputer.enrich(map, egTpl);
|
editGridComputer.enrich(map, egTpl);
|
||||||
}
|
}
|
||||||
|
// recipe 主子表 compute-on-save:?__derive=LIST|TARGET=EXPR 时落库前逐行补算派生字段(新建页路径,
|
||||||
|
// 无 view_page 依赖;与 UI tpl 预览同源公式,服务端权威绕开前端竞态)。无 __derive 自然无操作。
|
||||||
|
if (derive != null && !derive.isBlank() && recipeDerivedComputer != null) {
|
||||||
|
recipeDerivedComputer.enrich(map, derive);
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
return run(id, map, true, egTpl);
|
return run(id, map, true, egTpl);
|
||||||
} catch (RuntimeException ex) {
|
} catch (RuntimeException ex) {
|
||||||
@@ -177,6 +197,11 @@ public class FlowController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 兼容老单测的三参入口(无 __derive);HTTP 入口走带 __derive 的四参方法。 */
|
||||||
|
ResponseEntity<Map<String, Object>> executePost(String id, String egTpl, Map<String, Object> body) {
|
||||||
|
return executePost(id, egTpl, null, body);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 引擎执行异常 → 优雅错误响应({@code 200 + status:1 + 友好 msg}),而非裸 500 Spring 错误页。
|
* 引擎执行异常 → 优雅错误响应({@code 200 + status:1 + 友好 msg}),而非裸 500 Spring 错误页。
|
||||||
* 缘由(QA 巡检发现):部分实体已在 SYS_ENTITY 登记但物理表/视图在当前库缺失(如 VIEW_* 报表视图),
|
* 缘由(QA 巡检发现):部分实体已在 SYS_ENTITY 登记但物理表/视图在当前库缺失(如 VIEW_* 报表视图),
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
package com.eip4.platform.metadata.flow;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RecipeArithmeticEvaluator 单测:极小安全算术求值器(recipe 派生字段服务端 compute-on-save 用)。
|
||||||
|
* 不连库、纯函数:只认 + - * / ( ) 、数字字面量、列名(从行 map 解析)。无任意代码执行。
|
||||||
|
*/
|
||||||
|
class RecipeArithmeticEvaluatorTest {
|
||||||
|
|
||||||
|
private final RecipeArithmeticEvaluator eval = new RecipeArithmeticEvaluator();
|
||||||
|
|
||||||
|
private static Map<String, Object> row(Object... kv) {
|
||||||
|
Map<String, Object> m = new HashMap<>();
|
||||||
|
for (int i = 0; i < kv.length; i += 2) {
|
||||||
|
m.put((String) kv[i], kv[i + 1]);
|
||||||
|
}
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("纯字面量乘法 3*5=15")
|
||||||
|
void literalMultiply() {
|
||||||
|
assertEquals(0, new BigDecimal("15").compareTo(eval.eval("3*5", Map.of())));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("列名相乘:金额=数量×单价(行 map 取值)")
|
||||||
|
void columnsMultiply() {
|
||||||
|
BigDecimal r = eval.eval("ITEMQTY*ITEMPRICE", row("ITEMQTY", 3, "ITEMPRICE", new BigDecimal("12.5")));
|
||||||
|
assertEquals(0, new BigDecimal("37.5").compareTo(r));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("字符串数字操作数被强转(amis 常提交字符串)")
|
||||||
|
void stringOperandsCoerced() {
|
||||||
|
BigDecimal r = eval.eval("ITEMQTY*ITEMPRICE", row("ITEMQTY", "4", "ITEMPRICE", "2.5"));
|
||||||
|
assertEquals(0, new BigDecimal("10").compareTo(r));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("加减与运算优先级、括号")
|
||||||
|
void precedenceAndParens() {
|
||||||
|
assertEquals(0, new BigDecimal("14").compareTo(eval.eval("2+3*4", Map.of())));
|
||||||
|
assertEquals(0, new BigDecimal("20").compareTo(eval.eval("(2+3)*4", Map.of())));
|
||||||
|
assertEquals(0, new BigDecimal("1").compareTo(eval.eval("A-B+C", row("A", 5, "B", 6, "C", 2))));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("除法(HALF_UP,去尾零)")
|
||||||
|
void division() {
|
||||||
|
assertEquals(0, new BigDecimal("2.5").compareTo(eval.eval("A/B", row("A", 5, "B", 2))));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("缺失/空操作数当 0")
|
||||||
|
void missingOperandIsZero() {
|
||||||
|
assertEquals(0, BigDecimal.ZERO.compareTo(eval.eval("MISSING*2", row("ITEMQTY", 3))));
|
||||||
|
assertEquals(0, new BigDecimal("3").compareTo(eval.eval("A+B", row("A", 3, "B", ""))));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("一元负号")
|
||||||
|
void unaryMinus() {
|
||||||
|
assertEquals(0, new BigDecimal("-6").compareTo(eval.eval("-2*3", Map.of())));
|
||||||
|
assertEquals(0, new BigDecimal("1").compareTo(eval.eval("3+-2", Map.of())));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("非数字字符串操作数 → 抛错(交由 computer 逐行兜底跳过,绝不静默写 0)")
|
||||||
|
void nonNumericStringThrows() {
|
||||||
|
assertThrows(RuntimeException.class, () -> eval.eval("A*2", row("A", "abc")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("畸形表达式 → 抛错")
|
||||||
|
void malformedThrows() {
|
||||||
|
assertThrows(RuntimeException.class, () -> eval.eval("3*", Map.of()));
|
||||||
|
assertThrows(RuntimeException.class, () -> eval.eval("(3+2", Map.of()));
|
||||||
|
assertThrows(RuntimeException.class, () -> eval.eval("", Map.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("除零 → 抛错")
|
||||||
|
void divByZeroThrows() {
|
||||||
|
assertThrows(RuntimeException.class, () -> eval.eval("A/B", row("A", 5, "B", 0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("深嵌套括号 → 抛 RuntimeException(非 StackOverflowError,确保被逐行兜底捕获)")
|
||||||
|
void deepNestingThrowsRuntimeNotStackOverflow() {
|
||||||
|
String deep = "(".repeat(300) + "1" + ")".repeat(300);
|
||||||
|
// 必须是 RuntimeException(IllegalArgumentException),不能是 StackOverflowError(Error)
|
||||||
|
assertThrows(RuntimeException.class, () -> eval.eval(deep, Map.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("连续一元负号过深 → 抛 RuntimeException(非 StackOverflowError)")
|
||||||
|
void deepUnaryThrowsRuntime() {
|
||||||
|
String deep = "-".repeat(300) + "1";
|
||||||
|
assertThrows(RuntimeException.class, () -> eval.eval(deep, Map.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("超长表达式 → 抛错(防 CPU 放大 DoS)")
|
||||||
|
void overlongExpressionThrows() {
|
||||||
|
String longExpr = "1" + "+1".repeat(400); // > 512 字符
|
||||||
|
assertThrows(RuntimeException.class, () -> eval.eval(longExpr, Map.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("适度嵌套(远低于上限)正常求值")
|
||||||
|
void moderateNestingOk() {
|
||||||
|
assertEquals(0, new BigDecimal("20").compareTo(eval.eval("((((2+3))))*4", Map.of())));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
package com.eip4.platform.metadata.flow;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RecipeDerivedFieldComputer 单测:recipe 主子表写流 compute-on-save 逐行补派生字段。
|
||||||
|
* 纯函数(无 jdbc):解析 "LIST|TARGET=EXPR|..." 对提交 map 的子表数组逐行算并写回。
|
||||||
|
*/
|
||||||
|
class RecipeDerivedFieldComputerTest {
|
||||||
|
|
||||||
|
private final RecipeDerivedFieldComputer computer = new RecipeDerivedFieldComputer();
|
||||||
|
|
||||||
|
private static Map<String, Object> row(Object... kv) {
|
||||||
|
Map<String, Object> m = new HashMap<>();
|
||||||
|
for (int i = 0; i < kv.length; i += 2) {
|
||||||
|
m.put((String) kv[i], kv[i + 1]);
|
||||||
|
}
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private static List<Map<String, Object>> rows(Map<String, Object> map, String listCol) {
|
||||||
|
return (List<Map<String, Object>>) map.get(listCol);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("逐行补金额=数量×单价")
|
||||||
|
void enrichRowAmounts() {
|
||||||
|
Map<String, Object> map = new HashMap<>();
|
||||||
|
List<Map<String, Object>> details = new ArrayList<>();
|
||||||
|
details.add(row("ITEMNAME", "水泥", "ITEMQTY", 3, "ITEMPRICE", "10"));
|
||||||
|
details.add(row("ITEMNAME", "钢筋", "ITEMQTY", "2", "ITEMPRICE", new BigDecimal("12.5")));
|
||||||
|
map.put("DETAILS", details);
|
||||||
|
|
||||||
|
computer.enrich(map, "DETAILS|AMOUNT=ITEMQTY*ITEMPRICE");
|
||||||
|
|
||||||
|
assertEquals(0, new BigDecimal("30").compareTo((BigDecimal) rows(map, "DETAILS").get(0).get("AMOUNT")));
|
||||||
|
assertEquals(0, new BigDecimal("25").compareTo((BigDecimal) rows(map, "DETAILS").get(1).get("AMOUNT")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("多派生列:金额 + 含税")
|
||||||
|
void multipleDerived() {
|
||||||
|
Map<String, Object> map = new HashMap<>();
|
||||||
|
map.put("DETAILS", new ArrayList<>(List.of(row("ITEMQTY", 2, "ITEMPRICE", 100))));
|
||||||
|
|
||||||
|
computer.enrich(map, "DETAILS|AMOUNT=ITEMQTY*ITEMPRICE|TAXED=AMOUNT*1.13");
|
||||||
|
|
||||||
|
// AMOUNT 先算(同一行内顺序应用,后者可引用前者结果)
|
||||||
|
assertEquals(0, new BigDecimal("200").compareTo((BigDecimal) rows(map, "DETAILS").get(0).get("AMOUNT")));
|
||||||
|
assertEquals(0, new BigDecimal("226").compareTo((BigDecimal) rows(map, "DETAILS").get(0).get("TAXED")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("某行公式出错(非数字操作数)只跳过该行该列,其余行照算")
|
||||||
|
void rowErrorIsolated() {
|
||||||
|
Map<String, Object> map = new HashMap<>();
|
||||||
|
List<Map<String, Object>> details = new ArrayList<>();
|
||||||
|
details.add(row("ITEMQTY", "abc", "ITEMPRICE", 10)); // 非数字 → 跳过
|
||||||
|
details.add(row("ITEMQTY", 4, "ITEMPRICE", 10)); // 正常
|
||||||
|
map.put("DETAILS", details);
|
||||||
|
|
||||||
|
computer.enrich(map, "DETAILS|AMOUNT=ITEMQTY*ITEMPRICE");
|
||||||
|
|
||||||
|
assertNull(rows(map, "DETAILS").get(0).get("AMOUNT"));
|
||||||
|
assertEquals(0, new BigDecimal("40").compareTo((BigDecimal) rows(map, "DETAILS").get(1).get("AMOUNT")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("大小写不敏感匹配子表列")
|
||||||
|
void caseInsensitiveListColumn() {
|
||||||
|
Map<String, Object> map = new HashMap<>();
|
||||||
|
map.put("details", new ArrayList<>(List.of(row("ITEMQTY", 5, "ITEMPRICE", 3))));
|
||||||
|
computer.enrich(map, "DETAILS|AMOUNT=ITEMQTY*ITEMPRICE");
|
||||||
|
assertEquals(0, new BigDecimal("15").compareTo((BigDecimal) rows(map, "details").get(0).get("AMOUNT")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("无子表数组 / 空 spec / null → 无操作不抛")
|
||||||
|
void noopCases() {
|
||||||
|
Map<String, Object> empty = new HashMap<>();
|
||||||
|
computer.enrich(empty, "DETAILS|AMOUNT=ITEMQTY*ITEMPRICE"); // 无 DETAILS
|
||||||
|
assertTrue(empty.isEmpty());
|
||||||
|
computer.enrich(null, "DETAILS|AMOUNT=X"); // null map
|
||||||
|
Map<String, Object> m = new HashMap<>();
|
||||||
|
m.put("DETAILS", new ArrayList<>(List.of(row("A", 1))));
|
||||||
|
computer.enrich(m, null); // null spec
|
||||||
|
computer.enrich(m, " "); // 空 spec
|
||||||
|
computer.enrich(m, "DETAILS"); // 无 target=expr
|
||||||
|
assertNull(rows(m, "DETAILS").get(0).get("AMOUNT"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
|
|||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.net.URLDecoder;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import org.junit.jupiter.api.DisplayName;
|
import org.junit.jupiter.api.DisplayName;
|
||||||
@@ -245,6 +247,63 @@ class PageBlueprintCompilerTest {
|
|||||||
assertEquals("DETAILS", editChild.path("name").asText());
|
assertEquals("DETAILS", editChild.path("name").asText());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("master-detail-v1 派生列: 渲染只读 tpl 计算单元格(无 quickEdit) + 表单 api 透传 URL 编码 __derive")
|
||||||
|
void compilesMasterDetailWithDerivedColumn() {
|
||||||
|
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", "ITEMNAME",
|
||||||
|
List.of(
|
||||||
|
new PageBlueprintField("ITEMNAME", "物料", "string", true, false, true),
|
||||||
|
new PageBlueprintField("QTY", "数量", "integer", false, false, true),
|
||||||
|
new PageBlueprintField("PRICE", "单价", "number", false, false, true),
|
||||||
|
new PageBlueprintField("MONEY", "金额", "number", false, false, true)),
|
||||||
|
List.of(new PageBlueprintChild.DerivedColumn("MONEY", "QTY*PRICE"))));
|
||||||
|
|
||||||
|
ObjectNode schema = new PageBlueprintCompiler(MAPPER).compile(blueprint);
|
||||||
|
ArrayNode header = (ArrayNode) schema.path("body").path("headerToolbar");
|
||||||
|
|
||||||
|
// 新增表单 api 透传 __derive(URL 编码);解码后 = DETAILS|MONEY=QTY*PRICE。
|
||||||
|
ObjectNode addForm = (ObjectNode) header.get(0).path("dialog").path("body");
|
||||||
|
String addApi = addForm.path("api").asText();
|
||||||
|
assertTrue(addApi.contains("__derive="), "新增表单 api 应带 __derive");
|
||||||
|
String derive = URLDecoder.decode(addApi.replaceAll(".*__derive=", ""), StandardCharsets.UTF_8);
|
||||||
|
assertEquals("DETAILS|MONEY=QTY*PRICE", derive);
|
||||||
|
|
||||||
|
// 派生列 MONEY = 只读 tpl 计算单元格(${QTY*PRICE}),无 quickEdit;其余列仍 quickEdit。
|
||||||
|
ArrayNode cols = (ArrayNode) findByType((ArrayNode) addForm.path("body"), "input-table").path("columns");
|
||||||
|
ObjectNode money = colByName(cols, "MONEY");
|
||||||
|
assertEquals("tpl", money.path("type").asText());
|
||||||
|
assertEquals("${QTY*PRICE}", money.path("tpl").asText());
|
||||||
|
// quickEdit 必须显式 false(否则 amis needConfirm:false 会强注可编辑框覆盖 tpl 预览)。
|
||||||
|
assertTrue(money.path("quickEdit").isBoolean() && !money.path("quickEdit").asBoolean(),
|
||||||
|
"派生列 quickEdit 必须为显式 false");
|
||||||
|
assertEquals("input-number", colByName(cols, "QTY").path("quickEdit").path("type").asText());
|
||||||
|
assertEquals("input-text", colByName(cols, "ITEMNAME").path("quickEdit").path("type").asText());
|
||||||
|
|
||||||
|
// 编辑表单 api 同样带 __derive(_UPDATE 也要服务端补算)。
|
||||||
|
ObjectNode editForm = (ObjectNode) header.get(1).path("dialog").path("body");
|
||||||
|
assertTrue(editForm.path("api").asText().contains("__derive="), "编辑表单 api 应带 __derive");
|
||||||
|
}
|
||||||
|
|
||||||
|
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())) {
|
||||||
|
return (ObjectNode) cols.get(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new AssertionError("no column name=" + name);
|
||||||
|
}
|
||||||
|
|
||||||
private static ObjectNode findByType(ArrayNode arr, String type) {
|
private static ObjectNode findByType(ArrayNode arr, String type) {
|
||||||
for (int i = 0; i < arr.size(); i++) {
|
for (int i = 0; i < arr.size(); i++) {
|
||||||
if (type.equals(arr.get(i).path("type").asText())) {
|
if (type.equals(arr.get(i).path("type").asText())) {
|
||||||
|
|||||||
@@ -977,6 +977,26 @@ class FlowControllerTest {
|
|||||||
FlowController.businessMessage(new ValidationException("该记录已经被删除,请重新选择!")));
|
FlowController.businessMessage(new ValidationException("该记录已经被删除,请重新选择!")));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("装配回归:多构造器下生产构造必须且仅一个标 @Autowired,且为最多参(含 RecipeDerivedFieldComputer)"
|
||||||
|
+ ",否则 Spring 回退无参构造启动崩(DesignFeatureController live e2e 已踩过)")
|
||||||
|
void productionConstructorIsAutowired() {
|
||||||
|
java.util.List<java.lang.reflect.Constructor<?>> autowired =
|
||||||
|
java.util.Arrays.stream(FlowController.class.getDeclaredConstructors())
|
||||||
|
.filter(c -> c.isAnnotationPresent(
|
||||||
|
org.springframework.beans.factory.annotation.Autowired.class))
|
||||||
|
.toList();
|
||||||
|
assertEquals(1, autowired.size(),
|
||||||
|
"FlowController 多构造器,生产构造器必须且仅一个标 @Autowired");
|
||||||
|
int max = java.util.Arrays.stream(FlowController.class.getDeclaredConstructors())
|
||||||
|
.mapToInt(java.lang.reflect.Constructor::getParameterCount).max().orElse(0);
|
||||||
|
assertEquals(max, autowired.get(0).getParameterCount(),
|
||||||
|
"@Autowired 应落在最多参(全依赖)的生产构造器上");
|
||||||
|
assertTrue(java.util.Arrays.asList(autowired.get(0).getParameterTypes())
|
||||||
|
.contains(com.eip4.platform.metadata.flow.RecipeDerivedFieldComputer.class),
|
||||||
|
"生产构造器应注入 RecipeDerivedFieldComputer(__derive 派生字段补算)");
|
||||||
|
}
|
||||||
|
|
||||||
/** ADMIN 上下文桩(CURRENTUSER=ADMIN)。 */
|
/** ADMIN 上下文桩(CURRENTUSER=ADMIN)。 */
|
||||||
private static Properties adminCtx() {
|
private static Properties adminCtx() {
|
||||||
Properties p = new Properties();
|
Properties p = new Properties();
|
||||||
|
|||||||
131
scripts/master-detail-derived-acceptance.sh
Normal file
131
scripts/master-detail-derived-acceptance.sh
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 主子表派生字段 · live e2e 验收:建主+子(含 AMOUNT 列) → compile master-detail-v1 携 childDerived
|
||||||
|
# (AMOUNT=ITEMQTY*ITEMPRICE) → publish → 主表 _ADD 报子行(不带 AMOUNT) → _LOAD 断言落库 AMOUNT=数量×单价。
|
||||||
|
# 证明点:① 带 ?__derive= 时服务端逐行权威算 AMOUNT;② 负控不带 __derive 则 AMOUNT 空(确属服务端补算非客户端传入)。
|
||||||
|
set -euo pipefail
|
||||||
|
BASE=${BASE:-http://localhost:8094}
|
||||||
|
ACCT=${ACCT:-admin}; PW=${PW:-111111}
|
||||||
|
TS=$(date +%s)
|
||||||
|
M="EIP4PT_DRV${TS}M"; C="EIP4PT_DRV${TS}C"
|
||||||
|
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} master=$M child=$C"
|
||||||
|
|
||||||
|
echo "[建主实体] $M (TITLE)"
|
||||||
|
MEID=$(curl -s -X POST "$BASE/api/meta/entity" "${H[@]}" -d '{
|
||||||
|
"tablename":"'"$M"'","name":"派生采购","attributes":[
|
||||||
|
{"column":"TITLE","display":"标题","type":"string","length":200,"mandatory":true}]}' | jqpy "['data']['entityId']")
|
||||||
|
echo " masterEntityId=$MEID"
|
||||||
|
|
||||||
|
echo "[建子实体] $C (ITEMNAME/ITEMQTY/ITEMPRICE/AMOUNT, tabletype=1, masterTable=$M)"
|
||||||
|
curl -s -X POST "$BASE/api/meta/entity" "${H[@]}" -d '{
|
||||||
|
"tablename":"'"$C"'","name":"派生明细","tabletype":1,"masterTable":"'"$M"'","attributes":[
|
||||||
|
{"column":"ITEMNAME","display":"物料","type":"string","length":100,"mandatory":true},
|
||||||
|
{"column":"ITEMQTY","display":"数量","type":"integer"},
|
||||||
|
{"column":"ITEMPRICE","display":"单价","type":"number"},
|
||||||
|
{"column":"AMOUNT","display":"金额","type":"number"}]}' | jqpy "['data']['entityId']" >/dev/null
|
||||||
|
echo " child created"
|
||||||
|
|
||||||
|
echo "[环③ compile] master-detail-v1 + childDerived AMOUNT=ITEMQTY*ITEMPRICE"
|
||||||
|
TID=$(curl -s -X POST "$BASE/api/design/recipe/compile" "${H[@]}" -d '{
|
||||||
|
"tableName":"'"$M"'","recipe":"master-detail-v1","title":"派生采购主子","displayField":"TITLE",
|
||||||
|
"childTable":"'"$C"'","linkColumn":"MASTERID","listColumn":"DETAILS","listLabel":"明细",
|
||||||
|
"childDerived":[{"column":"AMOUNT","formula":"ITEMQTY*ITEMPRICE"}]}' | jqpy "['data']['templateId']")
|
||||||
|
echo " templateId=$TID"
|
||||||
|
echo " [校验] 生成页表单 api 应含 __derive、子表 AMOUNT 列应为 tpl:"
|
||||||
|
curl -s "$BASE/api/page/schema/$TID" "${H[@]}" -o /tmp/md-derived-schema.json
|
||||||
|
python3 - <<'PY'
|
||||||
|
import json
|
||||||
|
d=json.load(open('/tmp/md-derived-schema.json'),strict=False)
|
||||||
|
import re
|
||||||
|
s=json.dumps(d,ensure_ascii=False)
|
||||||
|
print(" __derive in api:", "__derive" in s)
|
||||||
|
# 找 input-table 的 AMOUNT 列
|
||||||
|
def walk(n):
|
||||||
|
if isinstance(n,dict):
|
||||||
|
if n.get('type')=='input-table':
|
||||||
|
for c in n.get('columns',[]):
|
||||||
|
if c.get('name')=='AMOUNT':
|
||||||
|
print(" AMOUNT 列 type=",c.get('type')," tpl=",c.get('tpl'))
|
||||||
|
for v in n.values(): walk(v)
|
||||||
|
elif isinstance(n,list):
|
||||||
|
for v in n: walk(v)
|
||||||
|
walk(d)
|
||||||
|
PY
|
||||||
|
|
||||||
|
echo "[环④ publish] 五流 + 菜单"
|
||||||
|
curl -s -X POST "$BASE/api/design/publish" "${H[@]}" \
|
||||||
|
-d "{\"entityId\":\"$MEID\",\"tableName\":\"$M\",\"templateId\":\"$TID\",\"menuName\":\"派生采购主子\",\"generateDeploymentPackage\":true}" \
|
||||||
|
| jqpy "['data']['flowsCreated']" | sed 's/^/ flowsCreated=/'
|
||||||
|
|
||||||
|
echo "[_ADD 带 __derive] 子行不带 AMOUNT,服务端应逐行算 30 / 25"
|
||||||
|
ADD=$(curl -s -X POST "$BASE/api/flow/${M}_ADD?__derive=DETAILS%7CAMOUNT%3DITEMQTY*ITEMPRICE" "${H[@]}" -d '{
|
||||||
|
"TITLE":"采购单A","DETAILS":[
|
||||||
|
{"ITEMNAME":"水泥","ITEMQTY":3,"ITEMPRICE":10},
|
||||||
|
{"ITEMNAME":"钢筋","ITEMQTY":2,"ITEMPRICE":12.5}]}')
|
||||||
|
echo " _ADD status=$(echo "$ADD" | jqpy "['status']")"
|
||||||
|
|
||||||
|
echo "[_ADD 负控 不带 __derive] 子行 AMOUNT 应留空(证明 AMOUNT 来自服务端而非客户端)"
|
||||||
|
curl -s -X POST "$BASE/api/flow/${M}_ADD" "${H[@]}" -d '{
|
||||||
|
"TITLE":"采购单B","DETAILS":[{"ITEMNAME":"砂石","ITEMQTY":5,"ITEMPRICE":4}]}' | jqpy "['status']" | sed 's/^/ 负控 _ADD status=/'
|
||||||
|
|
||||||
|
echo "[_SEARCH] 取主记录 id"
|
||||||
|
curl -s -X POST "$BASE/api/flow/${M}_SEARCH" "${H[@]}" -d '{}' -o /tmp/md-derived-search.json
|
||||||
|
echo " _SEARCH status=$(jqpy "['status']" </tmp/md-derived-search.json)"
|
||||||
|
|
||||||
|
echo "[_LOAD 断言] 采购单A 子行 AMOUNT=30/25;采购单B 子行 AMOUNT 空"
|
||||||
|
python3 - "$BASE" "$TOK" "$M" <<'PY'
|
||||||
|
import json,sys,urllib.request
|
||||||
|
base,tok,M=sys.argv[1],sys.argv[2],sys.argv[3]
|
||||||
|
def post(path,body):
|
||||||
|
req=urllib.request.Request(base+path,data=json.dumps(body).encode(),
|
||||||
|
headers={'Authorization':'Bearer '+tok,'Content-Type':'application/json'})
|
||||||
|
return json.load(urllib.request.urlopen(req),strict=False)
|
||||||
|
search=json.load(open('/tmp/md-derived-search.json'),strict=False)
|
||||||
|
data=search.get('data',{})
|
||||||
|
print(" [debug] data keys=",list(data.keys()) if isinstance(data,dict) else type(data))
|
||||||
|
rows=data.get('items') or data.get('result') or data.get('rows') or data.get('list') or data.get('records') or []
|
||||||
|
if isinstance(rows,dict): rows=rows.get('items') or rows.get('rows') or rows.get('records') or rows.get('list') or []
|
||||||
|
print(" [debug] rows len=",len(rows), " row0 keys=",list(rows[0].keys()) if rows else None)
|
||||||
|
pk=M+'_ID'
|
||||||
|
_dbg=[True]
|
||||||
|
def load_details(rid):
|
||||||
|
r=post('/api/flow/%s_LOAD'%M,{pk:rid})
|
||||||
|
res=r.get('data',{}).get('result',r.get('data',{}))
|
||||||
|
if isinstance(res,list): res=res[0] if res else {}
|
||||||
|
if _dbg[0]:
|
||||||
|
_dbg[0]=False
|
||||||
|
print(" [debug] _LOAD data keys=",list(r.get('data',{}).keys())," result keys=",list(res.keys()) if isinstance(res,dict) else type(res))
|
||||||
|
return res.get('DETAILS') or res.get('details') or []
|
||||||
|
ok=True; found_a=False; found_b=False
|
||||||
|
for row in rows:
|
||||||
|
rid=row.get(pk) or row.get(pk.lower())
|
||||||
|
title=row.get('TITLE') or row.get('title')
|
||||||
|
if not rid: continue
|
||||||
|
det=load_details(str(rid).strip())
|
||||||
|
amts=[d.get('AMOUNT') if isinstance(d,dict) else None for d in det]
|
||||||
|
print(" %s id=%s DETAILS.AMOUNT=%s"%(title,str(rid).strip(),amts))
|
||||||
|
if title=='采购单A':
|
||||||
|
found_a=True
|
||||||
|
got=sorted([float(a) for a in amts if a not in (None,'')])
|
||||||
|
if got!=[25.0,30.0]:
|
||||||
|
ok=False; print(" ✗ 期望 [25,30] 实得",got)
|
||||||
|
else: print(" ✓ 服务端派生 AMOUNT=数量×单价 正确")
|
||||||
|
if title=='采购单B':
|
||||||
|
found_b=True
|
||||||
|
if any(a not in (None,'') for a in amts):
|
||||||
|
ok=False; print(" ✗ 负控应为空,实得",amts)
|
||||||
|
else: print(" ✓ 负控 AMOUNT 空(确属服务端补算)")
|
||||||
|
if not found_a:
|
||||||
|
ok=False; print(" ✗ 未在 _SEARCH 结果中找到采购单A → 断言根本没跑(假 PASS 风险)")
|
||||||
|
print("RESULT:", "PASS" if (ok and found_a and found_b) else "FAIL")
|
||||||
|
PY
|
||||||
|
|
||||||
|
echo "[清理] 删测试主/子实体(EIP4 前缀门)"
|
||||||
|
curl -s -X DELETE "$BASE/api/meta/entity/$C" "${H[@]}" >/dev/null; echo " child deleted"
|
||||||
|
curl -s -X DELETE "$BASE/api/meta/entity/$M" "${H[@]}" >/dev/null; echo " master deleted"
|
||||||
|
echo "[完成] 主子表派生字段 live e2e 验收(残留 RV/页/菜单/流需 psql 清,见末尾)"
|
||||||
|
echo "TID=$TID M=$M C=$C"
|
||||||
Reference in New Issue
Block a user