feat(editgrid): 主子表编辑页可用——默认值/编号+子表选品picker+数值校验+行内脚本引擎+日期coerce+保存端到端

以「办公用品采购申请编辑页」为镜补齐主子表(EditGrid)功能模板转换缺口,子表 editgrid 从「不可用」到可加行/选品/算金额/保存落库。

D 数值校验: UiTypeMapper NumberField 读 vmin/vmax → amis min/max(applyNumberBound)。
B 默认值/编号: FormDefaultsController(/api/form/{table}/defaults)服务端解析 initvalue 宏
  (复用 GetDefaultValueFunction) + {AUTOGENERATECODE}→CodeRuleService.getCode + _DISPLAY__回填;
  LegacyXmlWiring 注册 codeRuleService bean(零改 com.dsasp);转换器添加 dialog 接 defaults + 补 {CURRENTDEPART}。
A 子表行内交互: EditGridScriptRunner(faithful 跑原 Groovy,类型保真,绑定 event/group/group.parent/loadPOJO)
  + EditGridScriptController(/api/script/execute-editgrid-row);转换器 buildEditGridColumns 挂 quickEdit.onEvent.change
  (outputVar/row=${__rendererData}/componentId+index)+子表内只读 SelectDialog→picker 列+addable;input-table/form 加 id。
picker 400 修复: PickerController.resolveByViewTemplate 支持 <tree><treetemplate><gridtemplate> 树+网格选择窗
  (取 gridtemplate 网格实体作数据源),修「子表选用品 400 非法实体」。
日期写流缺口(引擎级通用): FlowInputCoercer 补 DATE/TIME → joda DateTime(毫秒/ISO/yyyy-MM-dd[ HH:mm:ss]),
  修一切含日期列表单写流 ClassCastException(String→DateTime)崩。
compute-on-save: EditGridDerivedFieldComputer(两遍:行内派生→父聚合)+FlowController ?__egtpl= 入口,
  落库前补算 editgrid 派生字段(对 display-only 非列键 no-op,对有派生列模板通用生效)。

验证: 主子表 _ADD 端到端实证落库(master+2子行,FK PURCHASE_ID 自动回填,APPLYDATE coerce 落库);
  picker/默认值浏览器实证;converter 108 + metadata 相关 67 测试绿。

注: 本提交亦携带工作区既有未提交改动(FlowController normalize 深度上限保护等)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-15 11:05:55 +08:00
parent f806653108
commit 13d6b4cdf8
16 changed files with 1923 additions and 75 deletions

View File

@@ -0,0 +1,188 @@
package com.eip4.platform.metadata.flow;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import com.eip4.platform.metadata.script.EditGridScriptRunner;
/**
* A1 compute-on-save:写流持久化前,服务端用 editgrid 行内脚本补算派生字段(如 金额=数量×单价、
* 申请总金额=明细金额之和),绕开 amis input-table 单元格提交与异步 onEvent 的前端竞态,保证落库数据正确。
*
* <p>背景:editgrid 派生字段(MONEY/applyTotalMoney)老引擎靠行内脚本算;新端 onEvent.change 在 amis
* input-table 里与单元格自身提交存在 React setState 竞态,致前端不可靠。本组件在 {@code _ADD/_UPDATE/
* _SAVE_AND_SUBMIT} 写流执行前,对提交 map 里的 editgrid 子表数组逐行 faithful 跑原 Groovy 补派生字段:
* <ol>
* <li><b>Pass 1 行内</b>:逐行跑每段脚本,取 {@code rowSetValues} 合并回该行(如 16b5ead3 算 MONEY);</li>
* <li><b>Pass 2 聚合</b>:用已补全的子表数组跑每段脚本,取 {@code parentSetValues} 合并回主 map
* (如 f0bbf4ce 汇总 applyTotalMoney)。</li>
* </ol>
*
* <p>templateId 由转换器在写流 submit api 上以 {@code ?__egtpl=} 透传;无 editgrid 的模板自然无操作。
* 任意异常吞掉不阻断保存(派生字段缺失好过保存失败)。纪律:零改 {@code com.dsasp}。
*/
@Component
public class EditGridDerivedFieldComputer {
private static final Logger log = LoggerFactory.getLogger(EditGridDerivedFieldComputer.class);
private final JdbcTemplate jdbcTemplate;
public EditGridDerivedFieldComputer(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/** 就地为提交 map 补算 editgrid 派生字段。templateId 空或无 editgrid → 无操作。 */
@SuppressWarnings("unchecked")
public void enrich(Map<String, Object> map, String templateId) {
if (map == null || templateId == null || templateId.isBlank()) {
return;
}
try {
List<EditGridSpec> specs = loadSpecs(templateId.trim());
for (EditGridSpec spec : specs) {
Object listObj = caseInsensitiveGet(map, spec.editgridField);
if (!(listObj instanceof List<?> rawRows) || rawRows.isEmpty() || spec.scriptsByKey.isEmpty()) {
continue;
}
List<Map<String, Object>> rows = new ArrayList<>();
for (Object r : rawRows) {
if (r instanceof Map) {
rows.add((Map<String, Object>) r);
}
}
if (rows.isEmpty()) {
continue;
}
// Pass 1:逐行算行内派生字段(如 MONEY)。
for (Map<String, Object> row : rows) {
for (String key : spec.scriptsByKey.keySet()) {
EditGridScriptRunner runner = new EditGridScriptRunner(
row, map, spec.fieldTypes, spec.changedFieldFor(key));
runner.run("save:" + templateId + ":" + key, spec.scriptsByKey.get(key));
row.putAll(runner.getRowSetValues());
}
}
// Pass 2:用已补全子表数组算父级聚合(如 applyTotalMoney)。取末行作触发上下文。
Map<String, Object> repRow = rows.get(rows.size() - 1);
for (String key : spec.scriptsByKey.keySet()) {
EditGridScriptRunner runner = new EditGridScriptRunner(
repRow, map, spec.fieldTypes, spec.changedFieldFor(key));
runner.run("save:" + templateId + ":" + key, spec.scriptsByKey.get(key));
map.putAll(runner.getParentSetValues());
}
}
} catch (Exception e) {
// 派生字段补算失败不阻断保存(保存比派生字段更关键)。
log.warn("[EditGridDerived] compute-on-save 跳过 templateId={}: {}", templateId, e.toString());
}
}
// ────────────────────────────────────────────── 解析 view_page editgrid 规格
private static final class EditGridSpec {
final String editgridField;
final Map<String, String> fieldTypes = new LinkedHashMap<>(); // 子字段 name → java 类型
final Map<String, String> fieldScript = new LinkedHashMap<>(); // 子字段 name → scriptKey(仅有脚本的)
final Map<String, String> scriptsByKey = new LinkedHashMap<>(); // scriptKey → 脚本正文
EditGridSpec(String editgridField) {
this.editgridField = editgridField;
}
/** 某 scriptKey 的代表「变更字段」:取首个绑定该脚本的子字段(脚本 event/getFieldValue 据此取值)。 */
String changedFieldFor(String scriptKey) {
for (Map.Entry<String, String> e : fieldScript.entrySet()) {
if (scriptKey.equals(e.getValue())) {
return e.getKey();
}
}
return null;
}
}
private List<EditGridSpec> loadSpecs(String templateId) throws Exception {
List<EditGridSpec> specs = new ArrayList<>();
List<Map<String, Object>> rows = jdbcTemplate.queryForList(
"SELECT xml::text AS xml FROM view_page WHERE view_page_id = ?", templateId);
if (rows.isEmpty() || rows.get(0).get("xml") == null) {
return specs;
}
Document page = DocumentHelper.parseText(rows.get(0).get("xml").toString().trim());
Element fields = page.getRootElement().element("fields");
if (fields == null) {
return specs;
}
for (Element f : fields.elements("field")) {
Element tpl = f.element("editgridtemplate");
String name = f.attributeValue("name");
if (tpl == null || name == null || name.isBlank()) {
continue;
}
String tplXml = tpl.getText();
if (tplXml == null || tplXml.isBlank()) {
continue;
}
Element editgrid = DocumentHelper.parseText(tplXml.trim()).getRootElement().element("editgrid");
if (editgrid == null) {
continue;
}
EditGridSpec spec = new EditGridSpec(name);
Set<String> usedKeys = new LinkedHashSet<>();
for (Element sub : editgrid.elements("field")) {
String sn = sub.attributeValue("name");
String type = sub.attributeValue("type");
String script = sub.attributeValue("script", "");
if (sn == null) {
continue;
}
if (type != null) {
spec.fieldTypes.put(sn, type);
}
if (!script.isBlank()) {
spec.fieldScript.put(sn, script.trim());
usedKeys.add(script.trim());
}
}
Element scripts = editgrid.element("scripts");
if (scripts != null) {
for (Element s : scripts.elements("script")) {
String key = s.attributeValue("key");
if (key != null && usedKeys.contains(key.trim())) {
spec.scriptsByKey.put(key.trim(), s.getText());
}
}
}
if (!spec.scriptsByKey.isEmpty()) {
specs.add(spec);
}
}
return specs;
}
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;
}
}

View File

@@ -7,6 +7,9 @@ import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.ISODateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
@@ -338,13 +341,47 @@ public class FlowInputCoercer {
return val;
}
}
case "DATE", "TIME" -> {
// DATE/TIME 列:引擎 GeneralPO 期望 joda DateTime,amis input-date/datetime 提交字符串
// (ISO/时间戳/yyyy-MM-dd[ HH:mm:ss])。原默认不转 → 引擎直接 cast String→DateTime 抛
// ClassCastException,致一切含日期列的表单写流崩。此处 String→joda DateTime(parse 失败保留原值)。
return coerceDate(val.trim(), colName);
}
default -> {
// NVARCHAR/CHAR/TIME/DATE/LIST/BLOB/CODE/UUID-ref 等 → 不动
// NVARCHAR/CHAR/LIST/BLOB/CODE/UUID-ref 等 → 不动
return val;
}
}
}
/** DATE/TIME 字符串 → joda {@link DateTime}:依次试 毫秒时间戳 → ISO → {@code yyyy-MM-dd HH:mm:ss} → {@code yyyy-MM-dd};都失败保留原值。 */
private Object coerceDate(String v, String colName) {
if (v.isEmpty()) {
return v;
}
if (v.matches("-?\\d{12,}")) { // 13 位左右毫秒时间戳
try {
return new DateTime(Long.parseLong(v));
} catch (RuntimeException ignore) {
// 非时间戳 → 继续试格式
}
}
try {
return ISODateTimeFormat.dateTimeParser().withOffsetParsed().parseDateTime(v); // 含 2026-06-15 / ...T...Z / 带偏移
} catch (RuntimeException ignore) {
// 非 ISO → 试本地格式
}
for (String p : new String[] {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"}) {
try {
return DateTimeFormat.forPattern(p).parseDateTime(v);
} catch (RuntimeException ignore) {
// 试下一格式
}
}
log.debug("[FLOW-COERCE] col={} DATE/TIME val='{}' 无法解析为日期, keeping String", colName, v);
return v;
}
/** 失效单表缓存(元数据变更时,与 /api/meta/evict 钩子对齐)。 */
public void evict(String table) {
if (table != null && !table.isBlank()) {

View File

@@ -0,0 +1,246 @@
package com.eip4.platform.metadata.script;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.script.Bindings;
import javax.script.SimpleBindings;
import com.dsasp.server.common.function.GetServicesFunction;
import com.dsasp.server.dataDic.binding.ScriptingEnginesManager;
import groovy.lang.Closure;
/**
* A1 — EditGrid 行内联动脚本的服务端 faithful 执行器(引擎级原语)。
*
* <p>老引擎子表(EditGrid)字段的 {@code script} 属性是「单元格值变化触发的行内联动脚本」
* (如采购明细:数量×单价→金额、选用品→loadPOJO 带出规格单位、金额→汇总主表总额)。这些 Groovy
* 脚本引用 {@code getFieldValue/bindField/event/group/group.parent/GetServicesFunction.loadPOJO}
* 等行/父上下文 API。本执行器零改写地跑原脚本:把 amis 提交的当前行 + 父表单数据域包成 Groovy 绑定,
* 捕获脚本对当前行/父字段的 setValue,返回 {@code rowSetValues}(当前行)+ {@code parentSetValues}
* (主表,如 applyTotalMoney),前端按行/表单作用域回写。
*
* <p>类型保真:amis JSON 数值经 Jackson 落成 Integer/Double,而脚本按老引擎字段声明类型运算
* ({@code new BigDecimal(getFieldValue("AMOUNT"))} 需 Integer、{@code amount.multiply(price)} 需
* BigDecimal)。{@link #coerce} 据 editgrid 子字段 {@code type} 把值强转回声明类型,复刻老引擎
* {@code getFieldValue} 返回类型化值的语义。
*
* <p>纪律:零改 {@code com.dsasp};脚本执行复用引擎 {@link ScriptingEnginesManager},DB 取值
* 复用 {@code GetServicesFunction.loadPOJO}(其内部走 pojoCRUDService + 当前会话)。
*/
public final class EditGridScriptRunner {
private final Map<String, Object> row;
private final Map<String, Object> parent;
private final Map<String, String> fieldTypes;
private final Object changedValue;
private final Map<String, Object> rowSetValues = new LinkedHashMap<>();
private final Map<String, Object> parentSetValues = new LinkedHashMap<>();
public EditGridScriptRunner(Map<String, Object> row, Map<String, Object> parent,
Map<String, String> fieldTypes, String changedField) {
this.row = row != null ? row : new LinkedHashMap<>();
this.parent = parent != null ? parent : new LinkedHashMap<>();
this.fieldTypes = fieldTypes != null ? fieldTypes : Map.of();
this.changedValue = coerce(changedField, this.row.get(changedField));
}
public Map<String, Object> getRowSetValues() {
return rowSetValues;
}
public Map<String, Object> getParentSetValues() {
return parentSetValues;
}
/** 跑一段 editgrid Groovy 脚本,捕获行/父字段 setValue。 */
public void run(String key, String script) {
if (script == null || script.isBlank()) {
return;
}
Bindings b = new SimpleBindings();
// 行级动词(复刻老引擎 group 域内函数)—— 用 Groovy Closure 绑定,脚本方能以 getFieldValue("X") 调用。
bind(b, "getFieldValue", a -> { String f = str(arg(a, 0)); return coerce(f, row.get(f)); });
bind(b, "bindField", a -> { rowSetValues.put(str(arg(a, 0)), arg(a, 1)); row.put(str(arg(a, 0)), arg(a, 1)); return null; });
// 行/父代理对象(group.getField / group.parent.getField)
FieldScope rowScope = new FieldScope(row, rowSetValues);
FieldScope parentScope = new FieldScope(parent, parentSetValues);
b.put("group", new GroupHandle(rowScope, parentScope));
b.put("event", new EventHandle(changedValue));
// DB 取值:GetServicesFunction.loadPOJO(静态委托 pojoCRUDService + UserSession,脚本原样调用)
b.put("GetServicesFunction", new GetServicesFunction());
ScriptingEnginesManager.getScriptingEnginesManager().evaluateGroovy(key, script, b);
}
// ────────────────────────────────────────────── 类型保真
private Object coerce(String field, Object v) {
if (v == null || field == null) {
return v;
}
String type = fieldTypes.get(field);
if (type == null) {
return v;
}
try {
return switch (type) {
case "java.math.BigDecimal" -> v instanceof BigDecimal ? v : new BigDecimal(v.toString().trim());
case "java.lang.Integer" -> v instanceof Integer ? v : Integer.valueOf(new BigDecimal(v.toString().trim()).intValue());
case "java.lang.Long" -> v instanceof Long ? v : Long.valueOf(new BigDecimal(v.toString().trim()).longValue());
case "java.lang.Double" -> v instanceof Double ? v : Double.valueOf(v.toString().trim());
default -> v;
};
} catch (NumberFormatException ignore) {
return v; // 非数值(空串等)→ 原值,脚本自行判 null/""
}
}
private static String str(Object o) {
return o == null ? null : o.toString();
}
// ────────────────────────────────────────────── Groovy 闭包绑定(同 ScriptFacade 口径)
@FunctionalInterface
private interface VerbFn {
Object call(Object[] args);
}
private static void bind(Bindings b, String name, VerbFn fn) {
b.put(name, new Closure<Object>(EditGridScriptRunner.class) {
@SuppressWarnings("unused")
public Object doCall(Object... args) {
return fn.call(args);
}
});
}
private static Object arg(Object[] a, int i) {
return a != null && i < a.length ? a[i] : null;
}
// ────────────────────────────────────────────── Groovy 绑定代理
/** group / group.parent 的字段域:getField(name) → FieldHandle,setValue 收集进对应 *SetValues。 */
private final class FieldScope {
final Map<String, Object> data;
final Map<String, Object> sink;
FieldScope(Map<String, Object> data, Map<String, Object> sink) {
this.data = data;
this.sink = sink;
}
public FieldHandle getField(String name) {
return new FieldHandle(this, name);
}
}
/** group 句柄:getField + parent。 */
public final class GroupHandle {
private final FieldScope rowScope;
private final FieldScope parentScope;
GroupHandle(FieldScope rowScope, FieldScope parentScope) {
this.rowScope = rowScope;
this.parentScope = parentScope;
}
public FieldHandle getField(String name) {
return rowScope.getField(name);
}
/** group.parent → 父表单域(含 applyTotalMoney / GOODSDETAIL 列表)。Groovy {@code group.parent} 经此 getter 解析。 */
public ParentHandle getParent() {
return new ParentHandle(parentScope);
}
}
/** group.parent 句柄:getField(name) → 父字段(applyTotalMoney 等)。 */
public final class ParentHandle {
private final FieldScope scope;
ParentHandle(FieldScope scope) {
this.scope = scope;
}
public FieldHandle getField(String name) {
return scope.getField(name);
}
}
/** 字段句柄:getValue/setValue/setConvertedValue/setReadOnly + getPropertyDataSource(只读切换为 no-op)。 */
public final class FieldHandle {
private final FieldScope scope;
private final String name;
FieldHandle(FieldScope scope, String name) {
this.scope = scope;
this.name = name;
}
public Object getValue() {
return scope.data.get(name);
}
public Object setValue(Object v) {
scope.sink.put(name, v);
scope.data.put(name, v); // 同步本地域,供后续脚本读到
return null;
}
public Object setConvertedValue(Object v) {
return setValue(v);
}
/** 老引擎临时解锁只读以编程赋值;amis 侧由 schema 控只读,此处记录但赋值照常生效 → no-op。 */
public Object setReadOnly(Object readOnly) {
return null;
}
public PropertyDataSourceHandle getPropertyDataSource() {
return new PropertyDataSourceHandle();
}
}
/** field.getPropertyDataSource().setReadOnly(...) 占位(只读切换在 amis 由 schema 控)。 */
public static final class PropertyDataSourceHandle {
public Object setReadOnly(Object readOnly) {
return null;
}
}
/** event.getProperty().getValue() → 变更字段的新值(已类型保真)。 */
public static final class EventHandle {
private final Object value;
EventHandle(Object value) {
this.value = value;
}
public PropertyHandle getProperty() {
return new PropertyHandle(value);
}
}
public static final class PropertyHandle {
private final Object value;
PropertyHandle(Object value) {
this.value = value;
}
public Object getValue() {
return value;
}
}
@SuppressWarnings("unchecked")
public static List<Map<String, Object>> asList(Object o) {
return o instanceof List<?> l ? (List<Map<String, Object>>) l : null;
}
}

View File

@@ -0,0 +1,144 @@
package com.eip4.platform.metadata.web;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.eip4.platform.metadata.script.EditGridScriptRunner;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
/**
* A1 — EditGrid 行内联动脚本执行端点(引擎级原语)。
*
* <p>转换器把子表列的老 {@code script}(单元格 onchange 联动)挂成 amis input-table 列的
* {@code quickEdit.onEvent.change} 动作链:ajax 调本端点,传 {@code templateId/editgridField/
* scriptKey/changedField + 当前行 + 父表单域}。本端点据 {@code (templateId, editgridField, scriptKey)}
* 从 {@code view_page} 的 {@code <editgridtemplate>} 解析脚本正文与子字段类型,经
* {@link EditGridScriptRunner} faithful 跑原 Groovy,返回 {@code rowSetValues}(当前行)+
* {@code parentSetValues}(主表,如 applyTotalMoney)供前端按作用域回写。
*
* <p>契约:{@code POST /api/script/execute-editgrid-row},请求体
* {@code {templateId, editgridField, scriptKey, changedField, row:{...}, parent:{...}}} →
* {@code {status:0, data:{rowSetValues:{...}, parentSetValues:{...}}}}。脚本/字段缺失或执行异常 →
* 返回空 setValues(前端无联动,no-op),不阻断录入。
*/
@RestController
@Tag(name = "子表行内脚本", description = "A1 EditGrid 行内联动脚本服务端 faithful 执行")
public class EditGridScriptController {
private static final Logger log = LoggerFactory.getLogger(EditGridScriptController.class);
private final JdbcTemplate jdbcTemplate;
public EditGridScriptController(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Operation(summary = "执行 EditGrid 行内联动脚本(返回 rowSetValues/parentSetValues)")
@PostMapping("/api/script/execute-editgrid-row")
@SuppressWarnings("unchecked")
public Map<String, Object> execute(@RequestBody Map<String, Object> body) {
Map<String, Object> data = new LinkedHashMap<>();
data.put("rowSetValues", new LinkedHashMap<>());
data.put("parentSetValues", new LinkedHashMap<>());
Map<String, Object> resp = new LinkedHashMap<>();
resp.put("status", 0);
resp.put("msg", "");
resp.put("data", data);
String templateId = str(body.get("templateId"));
String editgridField = str(body.get("editgridField"));
String scriptKey = str(body.get("scriptKey"));
String changedField = str(body.get("changedField"));
Map<String, Object> row = body.get("row") instanceof Map ? (Map<String, Object>) body.get("row") : new LinkedHashMap<>();
Map<String, Object> parent = body.get("parent") instanceof Map ? (Map<String, Object>) body.get("parent") : new LinkedHashMap<>();
if (templateId == null || editgridField == null || scriptKey == null) {
return resp;
}
try {
EditGridSpec spec = loadEditGridSpec(templateId.trim(), editgridField.trim(), scriptKey.trim());
if (spec == null || spec.script == null || spec.script.isBlank()) {
return resp; // 脚本缺失 → no-op
}
EditGridScriptRunner runner = new EditGridScriptRunner(row, parent, spec.fieldTypes, changedField);
runner.run("editgrid:" + templateId + ":" + scriptKey, spec.script);
data.put("rowSetValues", runner.getRowSetValues());
data.put("parentSetValues", runner.getParentSetValues());
} catch (Exception e) {
// 脚本执行异常不阻断录入:返回空 setValues + 记录(不外泄给前端)。
log.warn("[EditGridScript] 执行失败 templateId={} field={} key={}: {}",
templateId, editgridField, scriptKey, e.toString());
}
return resp;
}
// ────────────────────────────────────────────── 脚本/字段类型解析
private record EditGridSpec(String script, Map<String, String> fieldTypes) {}
/** 从 view_page 的 editgridtemplate 解析 (脚本正文, 子字段 name→java类型)。 */
private EditGridSpec loadEditGridSpec(String templateId, String editgridField, String scriptKey) throws Exception {
List<Map<String, Object>> rows = jdbcTemplate.queryForList(
"SELECT xml::text AS xml FROM view_page WHERE view_page_id = ?", templateId);
if (rows.isEmpty() || rows.get(0).get("xml") == null) {
return null;
}
Document page = DocumentHelper.parseText(rows.get(0).get("xml").toString().trim());
Element fields = page.getRootElement().element("fields");
if (fields == null) {
return null;
}
for (Element f : fields.elements("field")) {
if (!editgridField.equalsIgnoreCase(f.attributeValue("name"))
|| f.element("editgridtemplate") == null) {
continue;
}
String tplXml = f.element("editgridtemplate").getText();
if (tplXml == null || tplXml.isBlank()) {
return null;
}
Element editgrid = DocumentHelper.parseText(tplXml.trim()).getRootElement().element("editgrid");
if (editgrid == null) {
return null;
}
Map<String, String> fieldTypes = new LinkedHashMap<>();
for (Element sub : editgrid.elements("field")) {
String name = sub.attributeValue("name");
String type = sub.attributeValue("type");
if (name != null && type != null) {
fieldTypes.put(name, type);
}
}
Element scripts = editgrid.element("scripts");
String script = null;
if (scripts != null) {
for (Element s : scripts.elements("script")) {
if (scriptKey.equals(s.attributeValue("key"))) {
script = s.getText();
break;
}
}
}
return new EditGridSpec(script, fieldTypes);
}
return null;
}
private static String str(Object o) {
return o == null ? null : o.toString();
}
}

View File

@@ -25,6 +25,7 @@ import com.dsasp.server.common.core.service.FlowExcuteService;
import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
import com.dsasp.server.common.dataDic.service.POJOCRUDService;
import com.dsasp.server.common.util.UserSession;
import com.eip4.platform.metadata.flow.EditGridDerivedFieldComputer;
import com.eip4.platform.metadata.flow.FlowInputCoercer;
import com.eip4.platform.metadata.flow.FlowNameResolver;
import com.eip4.platform.metadata.flow.FlowNameResolver.ResolvedFlow;
@@ -71,35 +72,45 @@ public class FlowController {
private final UserColumnResolver userColumnResolver;
private final FlowReadWriteClassifier classifier;
private final FlowInputCoercer inputCoercer;
/** A1 compute-on-save:写流执行前为 editgrid 子表补算派生字段(金额/总额)。可空(老单测构造)。 */
private final EditGridDerivedFieldComputer editGridComputer;
/** Spring 注入入口(5 参:读写分类器 + 类型强制器)。
/** Spring 注入入口(6 参:读写分类器 + 类型强制器 + editgrid 派生字段补算器)。
* 多构造器场景须显式 @Autowired 指明注入构造,否则 Spring 回退无参构造致启动失败。 */
@org.springframework.beans.factory.annotation.Autowired
public FlowController(FlowExcuteService flowExcuteService, FlowNameResolver flowNameResolver,
UserColumnResolver userColumnResolver, FlowReadWriteClassifier classifier,
FlowInputCoercer inputCoercer) {
FlowInputCoercer inputCoercer, EditGridDerivedFieldComputer editGridComputer) {
this.flowExcuteService = flowExcuteService;
this.flowNameResolver = flowNameResolver;
this.userColumnResolver = userColumnResolver;
this.classifier = classifier;
this.inputCoercer = inputCoercer;
this.editGridComputer = editGridComputer;
}
/** 兼容老单测的四参构造(无类型强制器:写流跳过 coerce)。生产由 Spring 走五参构造。 */
/** 兼容老单测的五参构造(无 editgrid 补算器)。生产由 Spring 走六参构造。 */
public FlowController(FlowExcuteService flowExcuteService, FlowNameResolver flowNameResolver,
UserColumnResolver userColumnResolver, FlowReadWriteClassifier classifier,
FlowInputCoercer inputCoercer) {
this(flowExcuteService, flowNameResolver, userColumnResolver, classifier, inputCoercer, null);
}
/** 兼容老单测的四参构造(无类型强制器:写流跳过 coerce)。生产由 Spring 走六参构造。 */
public FlowController(FlowExcuteService flowExcuteService, FlowNameResolver flowNameResolver,
UserColumnResolver userColumnResolver, FlowReadWriteClassifier classifier) {
this(flowExcuteService, flowNameResolver, userColumnResolver, classifier, null);
this(flowExcuteService, flowNameResolver, userColumnResolver, classifier, null, null);
}
/** 兼容老单测的三参构造(无分类器、无类型强制器)。生产由 Spring 走五参构造。 */
/** 兼容老单测的三参构造(无分类器、无类型强制器)。生产由 Spring 走六参构造。 */
public FlowController(FlowExcuteService flowExcuteService, FlowNameResolver flowNameResolver,
UserColumnResolver userColumnResolver) {
this(flowExcuteService, flowNameResolver, userColumnResolver, null, null);
this(flowExcuteService, flowNameResolver, userColumnResolver, null, null, null);
}
/** 兼容老单测的两参构造(无用户列解析、无分类器、无类型强制器)。生产由 Spring 走五参构造。 */
/** 兼容老单测的两参构造(无用户列解析、无分类器、无类型强制器)。生产由 Spring 走六参构造。 */
public FlowController(FlowExcuteService flowExcuteService, FlowNameResolver flowNameResolver) {
this(flowExcuteService, flowNameResolver, null, null, null);
this(flowExcuteService, flowNameResolver, null, null, null, null);
}
/** amis crud 默认每页条数(与前端 amis 默认 perPage 一致)。 */
@@ -123,9 +134,15 @@ public class FlowController {
@PostMapping("/{id}")
@Operation(summary = "执行服务流(POST):JSON body 作为入参 map,返回流输出 JSON")
public ResponseEntity<Map<String, Object>> executePost(@PathVariable String id,
@RequestParam(value = "__egtpl", required = false) String egTpl,
@RequestBody(required = false) Map<String, Object> body) {
Map<String, Object> map = body == null ? new HashMap<>() : new HashMap<>(body);
applyPaging(map);
// A1 compute-on-save:写流 submit 带 ?__egtpl=<view_page_id> 时,落库前补算 editgrid 派生字段
// (金额=数量×单价、申请总金额=明细之和),绕开 amis input-table 前端竞态。无 editgrid 自然无操作。
if (egTpl != null && !egTpl.isBlank() && editGridComputer != null) {
editGridComputer.enrich(map, egTpl);
}
try {
return run(id, map, true);
} catch (RuntimeException ex) {
@@ -425,11 +442,25 @@ public class FlowController {
return id.replaceAll("[^A-Za-z0-9_\\-]", "?");
}
/** 归一化递归深度上限:防嵌套 GeneralPOJO 互引成环时无限递归(正常对象图远浅于此)。 */
private static final int MAX_NORMALIZE_DEPTH = 16;
/** 递归归一化引擎返回值,使之可被 Jackson 序列化(GeneralPOJO 非 bean,需手工展平)。 */
@SuppressWarnings("unchecked")
private Object normalize(Object value) {
return normalize(value, 0);
}
/**
* 深度受限的递归归一化。{@code depth} 超限 → 对 GeneralPOJO/容器返 null(截断),标量原样返
* (防互引成环;正常单据对象图浅于 16 层)。
*/
@SuppressWarnings("unchecked")
private Object normalize(Object value, int depth) {
if (depth > MAX_NORMALIZE_DEPTH) {
return (value instanceof GeneralPOJO || value instanceof Map || value instanceof List) ? null : value;
}
if (value instanceof GeneralPOJO p) {
return toRow(p);
return toRow(p, depth);
}
if (value instanceof Map<?, ?> m) {
// listSelect 结果:{listresult:[...], pagecount:N} → amis {items, total}。
@@ -439,20 +470,20 @@ public class FlowController {
if (m.containsKey(POJOCRUDService.LIST_RESULT) || m.containsKey(POJOCRUDService.PAGE_COUNT)) {
Map<String, Object> data = new LinkedHashMap<>();
Object list = m.get(POJOCRUDService.LIST_RESULT);
data.put("items", list != null ? normalize(list) : new ArrayList<>());
data.put("items", list != null ? normalize(list, depth + 1) : new ArrayList<>());
data.put("total", m.containsKey(POJOCRUDService.PAGE_COUNT) ? m.get(POJOCRUDService.PAGE_COUNT) : 0);
return data;
}
Map<String, Object> out = new LinkedHashMap<>();
for (Map.Entry<?, ?> e : m.entrySet()) {
out.put(String.valueOf(e.getKey()), normalize(e.getValue()));
out.put(String.valueOf(e.getKey()), normalize(e.getValue(), depth + 1));
}
return out;
}
if (value instanceof List<?> list) {
List<Object> out = new ArrayList<>(list.size());
for (Object o : list) {
out.add(normalize(o));
out.add(normalize(o, depth + 1));
}
return out;
}
@@ -461,10 +492,20 @@ public class FlowController {
/** GeneralPOJO 值存于内部数组(非 bean getter),展开为平面 map 供 JSON 序列化。 */
private Map<String, Object> toRow(GeneralPOJO p) {
return toRow(p, 0);
}
/**
* GeneralPOJO → 平面 map(仅 {@code _id} + 实体列)。<b>列值递归 {@link #normalize}</b>:嵌套 GeneralPOJO
* /列表(如 NOTICERECEIVE_LIST)也经 toRow 干净展平,而非被 Jackson 反射序列化原始 GeneralPOJO——后者
* 既泄露内部字段({@code selectBuild}=原始SQL、{@code ctx}=ROLES、{@code mainPO}/{@code _poInfo}),
* 又因内部 typed 字段触 {@code String→Integer} 序列化崩(裸 500,逃 graceful 兜底)。
*/
private Map<String, Object> toRow(GeneralPOJO p, int depth) {
Map<String, Object> row = new LinkedHashMap<>();
row.put("_id", p.get_ID());
for (int i = 0; i < p.get_ColumnCount(); i++) {
row.put(p.get_ColumnName(i), p.get_Value(i));
row.put(p.get_ColumnName(i), normalize(p.get_Value(i), depth + 1));
}
return row;
}

View File

@@ -0,0 +1,173 @@
package com.eip4.platform.metadata.web;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.joda.time.format.DateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.dsasp.server.common.dataDic.service.CodeRuleService;
import com.dsasp.server.common.function.GetDefaultValueFunction;
import com.eip4.platform.metadata.flow.UserColumnResolver;
import com.eip4.platform.metadata.security.IdentifierWhitelist;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
/**
* B — 新建表单默认值/编号服务端解析端点。
*
* <p>老引擎字段 {@code initvalue} 携带宏({@code {CURRENTUSER}/{CURRENTDEPART}/{CURRENTORG}/
* {CURRENTPROJECT}/{CURRENTTIME}/{AUTOGENERATECODE}})。转换器对动态宏只能产出前端表达式
* (且 {@code {CURRENTDEPART}} 漏映射、{@code AUTOGENERATECODE} 诚实降级不塞值),致采购申请等
* 新建时表单号/申请人/申请部门/申请日期全空。本端点在「添加」时服务端 faithful 解析这些宏,
* 复用引擎现成能力:{@link GetDefaultValueFunction}(从 {@code UserSession} 取当前用户/部门/组织/工程/时间)
* + {@link CodeRuleService#getCode}(按 {@code SYS_CODERULE} 规则生成流水号,如 {@code CGSQ-202604-000003})。
* 对用户/部门等引用列同时回填 {@code <COL>_DISPLAY__}(复用 {@link UserColumnResolver}),
* 让只读 SelectDialog(static)显示姓名/名称而非裸 id。
*
* <p>契约:{@code GET /api/form/{table}/defaults?templateId={viewPageId}} →
* {@code {status:0, msg:"", data:{FORMNO:"...", APPLYNAME:"<uid>", APPLYNAME_DISPLAY__:"姓名[工号]", ...}}}。
* 转换器把「添加」dialog 的 service.api 指向本端点(仅新建,不影响「修改」的 {@code _LOAD})。
*
* <p>纪律:零改 {@code com.dsasp};默认值/编号全走引擎能力,不裸 SQL 生成编号。
*/
@RestController
@Tag(name = "表单默认值", description = "B 新建表单 initvalue 宏服务端解析 + AUTOGENERATECODE 流水号")
public class FormDefaultsController {
private static final Logger log = LoggerFactory.getLogger(FormDefaultsController.class);
private final JdbcTemplate jdbcTemplate;
private final CodeRuleService codeRuleService;
private final UserColumnResolver userColumnResolver;
private final IdentifierWhitelist identifierWhitelist;
public FormDefaultsController(JdbcTemplate jdbcTemplate,
CodeRuleService codeRuleService,
UserColumnResolver userColumnResolver,
IdentifierWhitelist identifierWhitelist) {
this.jdbcTemplate = jdbcTemplate;
this.codeRuleService = codeRuleService;
this.userColumnResolver = userColumnResolver;
this.identifierWhitelist = identifierWhitelist;
}
@Operation(summary = "新建表单默认值(initvalue 宏服务端解析 + 编号生成 + 引用列显示名)",
description = "GET /api/form/{table}/defaults?templateId={viewPageId};返回 {status,msg,data:{字段:默认值, 字段_DISPLAY__:显示名}}")
@GetMapping("/api/form/{table}/defaults")
public ResponseEntity<Map<String, Object>> defaults(
@PathVariable String table,
@RequestParam(value = "templateId", required = false) String templateId) {
String t = table.toUpperCase();
identifierWhitelist.requireLegalTable(t);
Map<String, Object> data = new LinkedHashMap<>();
String xml = (templateId == null || templateId.isBlank()) ? null : queryViewPageXml(templateId.trim());
if (xml != null && !xml.isBlank()) {
try {
Document doc = DocumentHelper.parseText(xml.trim());
Element fields = doc.getRootElement().element("fields");
if (fields != null) {
for (Element f : fields.elements("field")) {
String name = f.attributeValue("name");
String iv = f.attributeValue("initvalue");
if (name == null || name.isBlank() || iv == null || iv.isBlank()) {
continue;
}
Object resolved = resolveInitValue(t, name, iv, f.attributeValue("format"));
if (resolved != null) {
data.put(name.toUpperCase(), resolved);
}
}
}
} catch (Exception e) {
log.warn("[FormDefaults] 解析 view_page xml 失败 templateId={}: {}", templateId, e.toString());
}
}
// 引用列(申请人/部门等)补显示值 <COL>_DISPLAY__,让只读 SelectDialog(static) 显示名而非裸 id。
if (!data.isEmpty()) {
try {
List<Map<String, Object>> rows = new ArrayList<>();
rows.add(data);
userColumnResolver.resolveRows(t, rows);
} catch (Exception e) {
log.debug("[FormDefaults] 引用列显示名解析跳过 table={}: {}", t, e.toString());
}
}
Map<String, Object> resp = new LinkedHashMap<>();
resp.put("status", 0);
resp.put("msg", "");
resp.put("data", data);
return ResponseEntity.ok(resp);
}
/**
* 解析单字段 initvalue:动态宏 {@code {TOKEN}} 走引擎 faithful 求值;静态字面量原样返回;
* 未识别 token / 求值失败 → {@code null}(不塞默认值,避免把 token 字面量当初值误显)。
*/
private Object resolveInitValue(String table, String column, String initvalue, String format) {
String v = initvalue.trim();
if (!(v.startsWith("{") && v.endsWith("}"))) {
return v; // 静态字面默认值
}
String token = v.substring(1, v.length() - 1).trim().toUpperCase();
try {
switch (token) {
case "CURRENTUSER":
return GetDefaultValueFunction.getCurrentUserId();
case "CURRENTDEPART":
return GetDefaultValueFunction.getCurrentUserDepartId();
case "CURRENTORG":
return GetDefaultValueFunction.getCurrentUserOrgId();
case "CURRENTPROJECT":
return GetDefaultValueFunction.getCurrentProjectId();
case "CURRENTTIME": {
boolean hasTime = format != null && (format.contains("H") || format.contains("m"));
String pat = hasTime ? "yyyy-MM-dd HH:mm:ss" : "yyyy-MM-dd";
return GetDefaultValueFunction.currentDateTime().toString(DateTimeFormat.forPattern(pat));
}
case "AUTOGENERATECODE":
return codeRuleService.getCode(table, column, new HashMap<>());
default:
log.debug("[FormDefaults] 未识别 initvalue token {}.{}={} → 跳过", table, column, v);
return null;
}
} catch (Exception e) {
// CURRENTUSER 等依赖会话;AUTOGENERATECODE 依赖 SYS_CODERULE 规则。任一缺失/异常 → 降级不塞值。
log.warn("[FormDefaults] {}.{} 宏 {} 解析失败: {}", table, column, v, e.toString());
return null;
}
}
private String queryViewPageXml(String templateId) {
try {
List<Map<String, Object>> rows = jdbcTemplate.queryForList(
"SELECT xml::text AS xml FROM view_page WHERE view_page_id = ?", templateId);
if (!rows.isEmpty()) {
Object xml = rows.get(0).get("xml");
return xml == null ? null : xml.toString();
}
} catch (Exception e) {
log.debug("[FormDefaults] 查 view_page xml 失败 templateId={}: {}", templateId, e.toString());
}
return null;
}
}

View File

@@ -295,6 +295,15 @@ public class PickerController {
entityId = root.elements("node").get(0).attributeValue("entityid");
}
}
// tree+grid 选择窗(<tree><treetemplate entityid><gridtemplate entityid>,如用品档案选择):
// 可选数据是「网格」(gridtemplate 实体,如 OA_OFFICE_GOODS),非左侧分类树。优先 gridtemplate.entityid,
// 回退 treetemplate.entityid。用 //descendant 搜索,容忍嵌套。修「子表选用品 picker 400(非法实体)」。
if (entityId == null || entityId.isBlank()) {
entityId = firstDescendantEntityId(root, "gridtemplate");
}
if (entityId == null || entityId.isBlank()) {
entityId = firstDescendantEntityId(root, "treetemplate");
}
} catch (Exception e) {
return null;
}
@@ -309,6 +318,19 @@ public class PickerController {
return tableName != null ? tableName.toString() : null;
}
/** 取模板 XML 里第一个 {@code <tag entityid="...">} 的 entityid(descendant 搜索,含嵌套);无则 null。 */
private static String firstDescendantEntityId(org.dom4j.Element root, String tag) {
for (Object n : root.selectNodes(".//" + tag + "[@entityid]")) {
if (n instanceof org.dom4j.Element el) {
String eid = el.attributeValue("entityid");
if (eid != null && !eid.isBlank()) {
return eid;
}
}
}
return null;
}
/**
* 选用作 label 的「可读标识列」:优先实体声明的显示列({@code isentitydisplay=1},
* 经 {@link POJOInfo#getDisplayIndex}),回退实体的标识列({@code isidentifier=true}),

View File

@@ -106,7 +106,8 @@ public class TemplateTreeController {
@RequestParam String rcol,
@RequestParam(required = false) String node,
@RequestParam(required = false) String page,
@RequestParam(required = false) String perPage) {
@RequestParam(required = false) String perPage,
@RequestParam Map<String, String> allParams) {
if (!IDENT.matcher(gridTable).matches() || !IDENT.matcher(rcol).matches()) {
Map<String, Object> err = new LinkedHashMap<>();
err.put("status", 1);
@@ -115,6 +116,19 @@ public class TemplateTreeController {
return ResponseEntity.badRequest().body(err);
}
Map<String, Object> body = new HashMap<>();
// 查询过滤:转发非保留 query 参数(gridtemplate <search> 字段值,如 NEWTYPE/TITLE)给合成搜索流。
// 仅放行列名合法(IDENT 白名单)且非空者,防注入;保留参数不转发;不覆盖 rcol 的子树 IN 过滤。
Set<String> reserved = Set.of("treeRef", "gridTable", "rcol", "node", "page", "perPage");
for (Map.Entry<String, String> e : allParams.entrySet()) {
String k = e.getKey();
String v = e.getValue();
if (reserved.contains(k) || k.equalsIgnoreCase(rcol) || v == null || v.isBlank()) {
continue;
}
if (IDENT.matcher(k).matches()) {
body.put(k, v); // 列名合法 → 作搜索流过滤条件(引擎 get_SearchWhereClause 已转义)
}
}
if (node != null && !node.isBlank()) {
List<String> ids;
try {
@@ -133,7 +147,7 @@ public class TemplateTreeController {
if (perPage != null) {
body.put("perPage", perPage);
}
return flowController.executePost(gridTable.toUpperCase() + "_SEARCH", body);
return flowController.executePost(gridTable.toUpperCase() + "_SEARCH", null, body);
}
/** 解析「点中节点 + 全部后代」的原始 id 列表(供右表 IN 过滤)。节点不在树中(陈旧)→ 退化为仅自身。 */