fix(converter): scriptKeyToSeq 复刻改写器枚举(C2)+缺脚本 fail-closed/no-op(C1)+去重(I2)

re-review 修 WS-B 两 Critical + 两 Important。

C2(最关键,静默挂错脚本):scriptKeyToSeq 旧实现按 <scripts> 直接子、无长度过滤
1-based 编号,与改写器盘上 seq 枚举不一致 → 多脚本模板挂错 seq。改写器真实枚举
(run_eval.py::load_corpus_db + run_rewrite.py 核实):xpath('//script/text()') 全局
范围(非仅 <scripts> 子)+ strip 后 length<5 跳过(continue 不占号)+ 对保留者
1-based 连续编号。新实现用 selectNodes("//script") 文档序 + getText() + SCRIPT_MIN_LEN=5
过滤 + 连续编号逐位对齐。新增 countKeptScripts 供对齐校验。
- 全库实证(psql eip4dev,721 个有盘模板):新规则 key→seq 总数 701/701 == 盘上文件数
  (旧版 32 模板偏差/1 模板 key 错位 d1f64d77: K_FILTER 旧算 seq=3 盘上无→运行时「未找到」,
  新算 seq=2 命中);999 事件绑定 997 命中盘上文件、2 为悬挂/被过滤 key(C1 fail-closed)。

C1-a(有绑定但文件不存在不挂):attachScriptOnEvent 增 Predicate<Integer> seqExists
重载(converter 不碰 FS,由 BatchConvertCli 注入盘上 existingSeqs);seq 无对应
rewritten/<id>/<seq>.*.groovy 则跳过该绑定(fail-closed)。BatchConvertCli 接线
existingSeqs(镜像 RewrittenScriptStore prefix+.groovy 匹配)+ 重转期对齐校验告警
(转换器算 keyed-script 数 ≠ 盘上文件数则 System.out 提示)。

C1-b(运行时兜底):ScriptExecuteController.executeTemplateRewritten 当 load 返 null/blank
改返 {passed:true, commands:[], commandCount:0}(no-op)而非 {passed:false,error},残余
缺脚本退化为「无联动」而非用户可见 ajax 报错;保留 blank templateId→{passed:false}。

I2(去重):extractEventBindings 按 (eventType,scriptKey) 去重,免同脚本多处绑定致 ajax 双发。

M3/M2:清理 BatchConvertCli javadoc 的 full_auto_index/<scripts> 文档序漂移;bulkActions
删除按钮无 id(enableButton 定位不到)记 note(删除极少被联动启停,不强制修)。

测试:platform-converter 92 绿(TemplateToAmisConverterTest 83 含新增 C2 短脚本跳过/外部
script 计入/keyless 占号、C1-a seqExists、I2 去重;BatchConvertCliTest 9 新建:parseKeyToSeq/
parseEventBindings/parseCountKeptScripts/existingSeqs/attached-seq 命中盘上文件契约)。
platform-metadata ScriptExecuteControllerTest 5 绿(缺 templateId→false / 脚本未找到→no-op 拆分)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-14 15:21:04 +08:00
parent 79eb8e2087
commit 47d03b714b
6 changed files with 418 additions and 32 deletions

View File

@@ -34,9 +34,10 @@ import com.fasterxml.jackson.databind.SerializationFeature;
* *
* <p>WS-B:第 5 参数为改写产物根目录(rewriterDir),传入即启用 onEvent 挂回。挂回不再读 * <p>WS-B:第 5 参数为改写产物根目录(rewriterDir),传入即启用 onEvent 挂回。挂回不再读
* full_auto_index.json,而是从每个模板源 XML 解析事件绑定(onselectedscript/onloadscript → * full_auto_index.json,而是从每个模板源 XML 解析事件绑定(onselectedscript/onloadscript →
* scriptKey)+ {@code <scripts>} 文档序(key→seq),按事件类型调用 * scriptKey)+ scriptKey→seq(复刻改写器枚举:{@code //script} 文档序 + strip&lt;5 跳过 + 1-based 连续),
* {@link TemplateToAmisConverter#attachScriptOnEvent}(onselected→selectedChange / onload→inited), * 按事件类型调用 {@link TemplateToAmisConverter#attachScriptOnEvent}(onselected→selectedChange /
* 覆盖 NO_S3+FULL_AUTO 两类脚本。 * onload→inited),覆盖 NO_S3+FULL_AUTO 两类脚本。仅当盘上确有 {@code rewritten/<id>/<seq>.*.groovy}
* 时才挂该绑定(fail-closed),并对「转换器算 keyed-script 数 vs 盘上文件数」做对齐校验告警。
* *
* <p>用法(本地 eip4dev): * <p>用法(本地 eip4dev):
* <pre>{@code * <pre>{@code
@@ -58,7 +59,7 @@ public final class BatchConvertCli {
private static final String DEFAULT_USER = "ceshi"; private static final String DEFAULT_USER = "ceshi";
private static final String DEFAULT_PASS = "ceshi"; private static final String DEFAULT_PASS = "ceshi";
private static final String DEFAULT_OUT = "转换产物"; private static final String DEFAULT_OUT = "转换产物";
/** 第 5 参数:改写产物根目录(含 full_auto_index.json),为空则不挂 onEvent。 */ /** 第 5 参数:改写产物根目录(含 rewritten/&lt;id&gt;/&lt;seq&gt;.*.groovy),为空则不挂 onEvent。 */
private static final String DEFAULT_REWRITER_DIR = ""; private static final String DEFAULT_REWRITER_DIR = "";
private BatchConvertCli() { private BatchConvertCli() {
@@ -126,7 +127,7 @@ public final class BatchConvertCli {
} }
/** /**
* 从源模板 XML 解析 scriptKey→seq({@code <scripts>} 1-based 文档序,与 rewriter 落盘 seq 对齐)。 * 从源模板 XML 解析 scriptKey→seq(复刻改写器枚举:{@code //script} 文档序 + strip&lt;5 跳过 + 1-based 连续)。
* 委托 {@link TemplateToAmisConverter#scriptKeyToSeq};XML 不可解析则返回空 map。 * 委托 {@link TemplateToAmisConverter#scriptKeyToSeq};XML 不可解析则返回空 map。
*/ */
static Map<String, Integer> parseKeyToSeq(String xml) { static Map<String, Integer> parseKeyToSeq(String xml) {
@@ -139,6 +140,56 @@ public final class BatchConvertCli {
} }
} }
/**
* 从源模板 XML 算「占 seq 的脚本数」(= {@link TemplateToAmisConverter#countKeptScripts}),
* 供与盘上文件数比对的对齐校验(WS-B C2)。XML 不可解析返回 -1(跳过校验)。
*/
static int parseCountKeptScripts(String xml) {
try {
Element root = DocumentHelper.parseText(xml).getRootElement();
return new TemplateToAmisConverter(null).countKeptScripts(root);
} catch (Exception e) {
return -1;
}
}
/**
* 扫描 {@code rewriterDir/<templateId>/} 下落盘的脚本文件,返回其 seq 集合
* (文件名形如 {@code <seq>.<LABEL>.groovy},镜像运行时 {@code RewrittenScriptStore} 的 prefix+后缀匹配)。
* 目录不存在/不可读返回空集合(→ 该模板所有绑定 fail-closed 不挂)。
*/
static java.util.Set<Integer> existingSeqs(Path rewriterDir, String templateId) {
java.util.Set<Integer> seqs = new java.util.HashSet<>();
if (rewriterDir == null || templateId == null) {
return seqs;
}
Path dir = rewriterDir.resolve("rewritten").resolve(templateId);
if (!Files.isDirectory(dir)) {
// 兼容传入已是 rewritten 根的情形
dir = rewriterDir.resolve(templateId);
}
if (!Files.isDirectory(dir)) {
return seqs;
}
try (java.util.stream.Stream<Path> files = Files.list(dir)) {
files.map(p -> p.getFileName().toString())
.filter(n -> n.endsWith(".groovy"))
.forEach(n -> {
int dot = n.indexOf('.');
if (dot > 0) {
try {
seqs.add(Integer.parseInt(n.substring(0, dot)));
} catch (NumberFormatException ignore) {
// 非 <seq>. 前缀的文件忽略
}
}
});
} catch (IOException e) {
return seqs;
}
return seqs;
}
static BatchSummary run(Connection conn, Path outDir) throws IOException, SQLException { static BatchSummary run(Connection conn, Path outDir) throws IOException, SQLException {
return run(conn, outDir, null); return run(conn, outDir, null);
} }
@@ -195,10 +246,18 @@ public final class BatchConvertCli {
// 从源 XML 解析事件绑定(onselected/onload→scriptKey) + scripts 文档序(key→seq), // 从源 XML 解析事件绑定(onselected/onload→scriptKey) + scripts 文档序(key→seq),
// 按事件类型挂到正确 amis 事件(onselected→selectedChange / onload→inited),覆盖 NO_S3+FULL_AUTO。 // 按事件类型挂到正确 amis 事件(onselected→selectedChange / onload→inited),覆盖 NO_S3+FULL_AUTO。
if (attachOnEvent) { if (attachOnEvent) {
// C2 对齐校验:转换器算出的 keyed-script 数 vs 盘上 rewritten/<id>/ 文件数,不一致告警。
java.util.Set<Integer> seqsOnDisk = existingSeqs(rewriterDir, id);
int keptByConverter = parseCountKeptScripts(xml);
if (keptByConverter >= 0 && !seqsOnDisk.isEmpty() && keptByConverter != seqsOnDisk.size()) {
System.out.println("[WS-B][对齐告警] " + id + " 转换器算 keyed-script 数=" + keptByConverter
+ " ≠ 盘上文件数=" + seqsOnDisk.size() + "(seq 枚举可能与改写器偏差,请核对 //script 范围/长度阈值)");
}
List<TemplateToAmisConverter.EventBinding> bindings = parseEventBindings(xml); List<TemplateToAmisConverter.EventBinding> bindings = parseEventBindings(xml);
if (!bindings.isEmpty()) { if (!bindings.isEmpty()) {
Map<String, Integer> keyToSeq = parseKeyToSeq(xml); Map<String, Integer> keyToSeq = parseKeyToSeq(xml);
converter.attachScriptOnEvent(result.getSchema(), id, bindings, keyToSeq); // C1-a:只在盘上确有 rewritten/<id>/<seq>.*.groovy 时才挂该绑定(fail-closed)。
converter.attachScriptOnEvent(result.getSchema(), id, bindings, keyToSeq, seqsOnDisk::contains);
Object body = result.getSchema().get("body"); Object body = result.getSchema().get("body");
if (body instanceof Map && ((Map<?, ?>) body).containsKey("onEvent")) { if (body instanceof Map && ((Map<?, ?>) body).containsKey("onEvent")) {
onEventAttached = true; onEventAttached = true;

View File

@@ -8,6 +8,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Predicate;
import org.dom4j.Document; import org.dom4j.Document;
import org.dom4j.DocumentHelper; import org.dom4j.DocumentHelper;
@@ -489,7 +490,11 @@ public class TemplateToAmisConverter {
.filter(s -> !s.isBlank()) .filter(s -> !s.isBlank())
.findFirst().orElse(""); .findFirst().orElse("");
if (isTrueDeleteButton(btnName)) { if (isTrueDeleteButton(btnName)) {
// 真删除按钮:入 bulkActions(amis 批量操作槽,自动注入 ${ids}=选中行主键逗号串) // 真删除按钮:入 bulkActions(amis 批量操作槽,自动注入 ${ids}=选中行主键逗号串)。
// WS-B M2 note:bulkActions 槽内按钮不设 amis id,故 enableButton("删除",…) 的
// enabled/disabled 指令(componentId=按钮名)无法定位 bulkActions 删除按钮——但实测
// 删除按钮极少被 onselectedscript 联动启停(联动几乎都针对 headerToolbar 业务按钮),
// 暂不强制补 id(amis bulkActions 对自定义 id 的启停支持亦不稳)。
Map<String, Object> del = new LinkedHashMap<>(); Map<String, Object> del = new LinkedHashMap<>();
del.put("type", "button"); del.put("type", "button");
del.put("label", btnName); del.put("label", btnName);
@@ -1713,24 +1718,45 @@ public class TemplateToAmisConverter {
} }
} }
/** rewriter 落盘的脚本最短文本长度阈值(strip 后 &lt; 此值的 {@code <script>} 被跳过、不占 seq)。 */
static final int SCRIPT_MIN_LEN = 5;
/** /**
* 解析 {@code <scripts><script key=...>} 的 key→seq(1-based 文档序,与 rewriter 落盘 seq 对齐)。 * 解析 {@code <script key=...>} 的 key→seq,<b>必须与改写器(tools/s3_rewriter)落盘枚举规则逐位对齐</b>。
* *
* <p>rewriter 落盘路径为 {@code rewritten/<templateId>/<seq>.<LABEL>.groovy},seq 即 * <p>rewriter 落盘路径 {@code rewritten/<templateId>/<seq>.<LABEL>.groovy} 的 seq 由
* view_template.xml {@code <scripts>} 内 {@code <script>} 的 1-based 文档序;本方法重建该映射, * {@code run_eval.py::load_corpus_db} + {@code run_rewrite.py} 共同确定,规则为:
* 供事件绑定 {@code onselectedscript="<scriptKey>"} 反查 seq。 * <ol>
* <li><b>全局范围</b>:抽 {@code xpath('//script/text()')}——文档内<b>所有</b> {@code <script>}(不限 {@code <scripts>} 直接子),按文档序;</li>
* <li><b>长度过滤</b>:脚本文本 strip 后 {@code length < }{@value #SCRIPT_MIN_LEN} 的<b>跳过</b>({@code continue},不占号);</li>
* <li><b>连续编号</b>:对保留者 1-based 连续编号(被跳过者不消耗 seq)。</li>
* </ol>
* 本方法复刻该枚举(dom4j {@code selectNodes("//script")} 文档序 + {@code getText()} 取文本),
* 对每个保留脚本记 {@code @key}(非空)→seq。改写器只按位置编号、不认 key;本映射用 key 反查 seq,
* 供事件绑定 {@code onselectedscript="<scriptKey>"} 找到对应落盘文件。
*
* <p>⚠️ 历史 bug(WS-B C2,已证伪 32 模板偏差/1 模板 key 错位):旧实现按 {@code <scripts>} 直接子、
* 无长度过滤编号——遇 {@code <scripts>} 外的 script 漏号、遇空/极短 script 多占号,导致多脚本模板
* 静默挂错 seq(运行时 load 返 null → 用户见「ajax 动作执行失败」)。
*
* @param root 模板 XML 根元素
* @return key→1-based 连续 seq(仅含非空 key 的保留脚本),无 {@code <script>} 时返回空 map
*/ */
Map<String, Integer> scriptKeyToSeq(Element root) { Map<String, Integer> scriptKeyToSeq(Element root) {
Map<String, Integer> map = new LinkedHashMap<>(); Map<String, Integer> map = new LinkedHashMap<>();
if (root == null) { if (root == null) {
return map; return map;
} }
Element scripts = root.element("scripts");
if (scripts == null) {
return map;
}
int seq = 0; int seq = 0;
for (Element s : scripts.elements("script")) { for (Object node : root.selectNodes("//script")) {
if (!(node instanceof Element s)) {
continue;
}
// getText():取直接文本节点(对纯文本脚本等价于 //script/text()),与 rewriter 取数同源。
String text = s.getText();
if (text == null || text.strip().length() < SCRIPT_MIN_LEN) {
continue; // strip 后 <5 字符 → rewriter 跳过、不占 seq,本方法须一致跳过
}
seq++; seq++;
String key = s.attributeValue("key"); String key = s.attributeValue("key");
if (key != null && !key.isBlank()) { if (key != null && !key.isBlank()) {
@@ -1740,27 +1766,56 @@ public class TemplateToAmisConverter {
return map; return map;
} }
/**
* 转换器算出的「占 seq 的脚本数」(= {@link #scriptKeyToSeq} 的最大 seq),供 BatchConvertCli
* 在重转期与盘上 {@code rewritten/<id>/} 文件数比对、发现残余偏差(WS-B C2 对齐校验)。
*
* @param root 模板 XML 根元素
* @return 保留脚本数(strip 后 ≥{@value #SCRIPT_MIN_LEN} 的 {@code <script>} 数,含 keyless)
*/
int countKeptScripts(Element root) {
if (root == null) {
return 0;
}
int seq = 0;
for (Object node : root.selectNodes("//script")) {
if (node instanceof Element s) {
String text = s.getText();
if (text != null && text.strip().length() >= SCRIPT_MIN_LEN) {
seq++;
}
}
}
return seq;
}
/** /**
* 递归扫描根元素树,收集所有带 {@code onselectedscript}/{@code onloadscript} 属性的元素, * 递归扫描根元素树,收集所有带 {@code onselectedscript}/{@code onloadscript} 属性的元素,
* 产出事件绑定列表(全库 onselected 930 / onload 422 模板;onclick/onchange 为 0,只处理两类)。 * 产出事件绑定列表(全库 onselected 930 / onload 422 模板;onclick/onchange 为 0,只处理两类)。
*
* <p>WS-B I2:同一 {@code (eventType, scriptKey)} 在多个元素重复出现时<b>只收一次</b>(保文档序),
* 避免同一脚本被挂进 onEvent 多次造成 ajax 双发/重放重复。
*/ */
List<EventBinding> extractEventBindings(Element root) { List<EventBinding> extractEventBindings(Element root) {
List<EventBinding> out = new ArrayList<>(); List<EventBinding> out = new ArrayList<>();
if (root != null) { if (root != null) {
collectBindings(root, out); collectBindings(root, out, new LinkedHashSet<>());
} }
return out; return out;
} }
private void collectBindings(Element el, List<EventBinding> out) { private void collectBindings(Element el, List<EventBinding> out, Set<String> seen) {
for (String attr : EVENT_ATTRS) { for (String attr : EVENT_ATTRS) {
String v = el.attributeValue(attr); String v = el.attributeValue(attr);
if (v != null && !v.isBlank()) { if (v != null && !v.isBlank()) {
// I2:按 (eventType,scriptKey) 去重——同绑定多处出现只挂一次
if (seen.add(attr + "" + v)) {
out.add(new EventBinding(attr, v)); out.add(new EventBinding(attr, v));
} }
} }
}
for (Element c : el.elements()) { for (Element c : el.elements()) {
collectBindings(c, out); collectBindings(c, out, seen);
} }
} }
@@ -1789,13 +1844,31 @@ public class TemplateToAmisConverter {
* @param keyToSeq scriptKey→1-based 文档序({@link #scriptKeyToSeq}) * @param keyToSeq scriptKey→1-based 文档序({@link #scriptKeyToSeq})
* @return 同一 pageSchema 引用(已就地挂上 onEvent),便于链式使用 * @return 同一 pageSchema 引用(已就地挂上 onEvent),便于链式使用
*/ */
@SuppressWarnings("unchecked")
public Map<String, Object> attachScriptOnEvent(Map<String, Object> pageSchema, String templateId, public Map<String, Object> attachScriptOnEvent(Map<String, Object> pageSchema, String templateId,
List<EventBinding> bindings, Map<String, Integer> keyToSeq) { List<EventBinding> bindings, Map<String, Integer> keyToSeq) {
// 不注入存在性判定时:默认任何 seq 都视为存在(converter 单测口径——不碰文件系统)。
return attachScriptOnEvent(pageSchema, templateId, bindings, keyToSeq, seq -> true);
}
/**
* {@link #attachScriptOnEvent(Map, String, List, Map)} 的存在性感知重载(WS-B C1-a)。
*
* <p>仅当 {@code seqExists.test(seq)} 为真(即盘上确有 {@code rewritten/<templateId>/<seq>.*.groovy})
* 时才把该绑定挂进 onEvent;否则<b>跳过该绑定(fail-closed)</b>,避免运行时
* {@code RewrittenScriptStore.load} 返 null → ScriptExecuteController 报「改写后脚本未找到」→
* 前端「ajax 动作执行失败」。converter 本身不碰文件系统,存在性由 BatchConvertCli 注入(盘上 ls)。
*
* @param seqExists seq→是否存在对应落盘脚本文件的判定(BatchConvertCli 由 {@code rewriterDir} 注入)
*/
@SuppressWarnings("unchecked")
public Map<String, Object> attachScriptOnEvent(Map<String, Object> pageSchema, String templateId,
List<EventBinding> bindings, Map<String, Integer> keyToSeq,
Predicate<Integer> seqExists) {
if (pageSchema == null || templateId == null || templateId.isBlank() if (pageSchema == null || templateId == null || templateId.isBlank()
|| bindings == null || bindings.isEmpty() || keyToSeq == null) { || bindings == null || bindings.isEmpty() || keyToSeq == null) {
return pageSchema; return pageSchema;
} }
Predicate<Integer> exists = (seqExists != null) ? seqExists : (seq -> true);
Object bodyObj = pageSchema.get("body"); Object bodyObj = pageSchema.get("body");
if (!(bodyObj instanceof Map)) { if (!(bodyObj instanceof Map)) {
return pageSchema; return pageSchema;
@@ -1809,6 +1882,9 @@ public class TemplateToAmisConverter {
if (seq == null) { if (seq == null) {
continue; // 绑定引用了不存在的 scriptKey → 跳过(fail-closed,不挂错脚本) continue; // 绑定引用了不存在的 scriptKey → 跳过(fail-closed,不挂错脚本)
} }
if (!exists.test(seq)) {
continue; // C1-a:盘上无 rewritten/<id>/<seq>.*.groovy → 跳过(fail-closed,免运行时「未找到」)
}
if (ATTR_ON_SELECTED.equals(b.eventType)) { if (ATTR_ON_SELECTED.equals(b.eventType)) {
selectedActions.addAll(scriptActionChain(templateId, seq, "${event.data.selectedItems[0]}")); selectedActions.addAll(scriptActionChain(templateId, seq, "${event.data.selectedItems[0]}"));
} else if (ATTR_ON_LOAD.equals(b.eventType)) { } else if (ATTR_ON_LOAD.equals(b.eventType)) {

View File

@@ -0,0 +1,136 @@
package com.eip4.platform.converter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* WS-B I1:BatchConvertCli 的 XML 解析(parseKeyToSeq / parseEventBindings / parseCountKeptScripts)
* 与盘上存在性(existingSeqs)契约单测。
*
* <p>核心覆盖 C2:scriptKey→seq 必须复刻改写器枚举({@code //script} 全局范围 + strip&lt;5 跳过 +
* 1-based 连续),且「转换器算出的 seq → 盘上确有对应 {@code <seq>.*.groovy}」(C1-a 存在性挂载契约)。
*/
class BatchConvertCliTest {
/** 模拟真实模板 d1f64d77:中段空脚本被改写器跳过 → 第三段 key 落 seq=2(非 3),对齐盘上 2.*.groovy。 */
private static final String MULTI_SCRIPT_XML =
"<crud entityid='e1'>"
+ "<scripts>"
+ "<script key='K_BTN' name='按钮控制'>enableButton(\"发布\",false)</script>" // ≥5 → seq=1
+ "<script key='K_EMPTY' name='空脚本'> </script>" // strip<5 → 跳过
+ "<script key='K_FILTER' name='过滤合同'>setFieldFilter(\"C\")</script>" // ≥5 → seq=2
+ "</scripts>"
+ "<display onselectedscript='K_BTN'><field name='A' text='A'/></display>"
+ "<button onloadscript='K_FILTER' name='查看'/>"
+ "</crud>";
@Test
void parseKeyToSeq_复刻改写器枚举_短脚本跳过且连续编号() {
Map<String, Integer> m = BatchConvertCli.parseKeyToSeq(MULTI_SCRIPT_XML);
assertEquals(1, m.get("K_BTN"));
assertEquals(2, m.get("K_FILTER")); // 跳过空脚本后连续 → seq=2(旧实现会算成 3)
assertNull(m.get("K_EMPTY")); // 短脚本被跳,不进映射
}
@Test
void parseCountKeptScripts_只计保留脚本() {
assertEquals(2, BatchConvertCli.parseCountKeptScripts(MULTI_SCRIPT_XML)); // 空脚本不计
assertEquals(0, BatchConvertCli.parseCountKeptScripts("<crud/>"));
}
@Test
void parseKeyToSeq_不可解析XML返回空() {
assertTrue(BatchConvertCli.parseKeyToSeq("not-xml<<<").isEmpty());
assertEquals(-1, BatchConvertCli.parseCountKeptScripts("not-xml<<<"));
}
@Test
void parseEventBindings_收集onselected与onload并去重() {
List<TemplateToAmisConverter.EventBinding> bs = BatchConvertCli.parseEventBindings(MULTI_SCRIPT_XML);
assertEquals(2, bs.size());
boolean hasSel = false, hasLoad = false;
for (TemplateToAmisConverter.EventBinding b : bs) {
if ("onselectedscript".equals(b.eventType) && "K_BTN".equals(b.scriptKey)) hasSel = true;
if ("onloadscript".equals(b.eventType) && "K_FILTER".equals(b.scriptKey)) hasLoad = true;
}
assertTrue(hasSel);
assertTrue(hasLoad);
}
@Test
void parseEventBindings_不可解析XML返回空() {
assertTrue(BatchConvertCli.parseEventBindings("not-xml<<<").isEmpty());
}
/** existingSeqs:rewriterDir 传 output(含 rewritten/<id>/)时按文件名前缀解析 seq 集合。 */
@Test
void existingSeqs_扫描output根下rewritten子目录(@TempDir Path output) throws IOException {
Path dir = output.resolve("rewritten").resolve("ddb75614");
Files.createDirectories(dir);
writeFile(dir.resolve("1.NO_S3.groovy"), "// h\nenableButton(\"x\")");
writeFile(dir.resolve("2.FULL_AUTO.groovy"), "// h\nsetFieldViewOnly(\"y\",true)");
writeFile(dir.resolve("notes.txt"), "ignore"); // 非 .groovy 忽略
Set<Integer> seqs = BatchConvertCli.existingSeqs(output, "ddb75614");
assertEquals(Set.of(1, 2), seqs);
assertTrue(BatchConvertCli.existingSeqs(output, "no-such").isEmpty());
}
/** existingSeqs:rewriterDir 直接传 rewritten 根(含 <id>/)也能解析。 */
@Test
void existingSeqs_扫描rewritten根下模板目录(@TempDir Path rewritten) throws IOException {
Path dir = rewritten.resolve("tidX");
Files.createDirectories(dir);
writeFile(dir.resolve("3.PARTIAL.groovy"), "// h\nsetFieldFilter(\"z\")");
Set<Integer> seqs = BatchConvertCli.existingSeqs(rewritten, "tidX");
assertEquals(Set.of(3), seqs);
}
@Test
void existingSeqs_目录不存在返回空() {
assertTrue(BatchConvertCli.existingSeqs(Path.of("/no/such/dir"), "x").isEmpty());
assertTrue(BatchConvertCli.existingSeqs(null, "x").isEmpty());
}
/**
* 契约(C1-a + C2 合流):转换器算出的 seq 必须命中盘上文件——以 d1f64d77 结构验证
* K_FILTER→seq=2 命中 {@code 2.*.groovy}(旧 bug 会算成 3 → 盘上无 3.* → 运行时「未找到」)。
*/
@Test
void attached_seq_命中盘上文件契约(@TempDir Path output) throws IOException {
Path dir = output.resolve("rewritten").resolve("d1f64d77");
Files.createDirectories(dir);
writeFile(dir.resolve("1.NO_S3.groovy"), "// h\nenableButton(\"发布\",false)");
writeFile(dir.resolve("2.PARTIAL.groovy"), "// h\nsetFieldFilter(\"C\")");
Map<String, Integer> keyToSeq = BatchConvertCli.parseKeyToSeq(MULTI_SCRIPT_XML);
Set<Integer> seqsOnDisk = BatchConvertCli.existingSeqs(output, "d1f64d77");
List<TemplateToAmisConverter.EventBinding> bindings = BatchConvertCli.parseEventBindings(MULTI_SCRIPT_XML);
// 每个绑定解析出的 seq 都必须存在于盘上(无悬挂、无错位)
for (TemplateToAmisConverter.EventBinding b : bindings) {
Integer seq = keyToSeq.get(b.scriptKey);
assertTrue(seq != null && seqsOnDisk.contains(seq),
"绑定 " + b + " → seq=" + seq + " 应命中盘上文件 " + seqsOnDisk);
}
// 对齐校验:转换器算的保留脚本数 == 盘上文件数
assertEquals(seqsOnDisk.size(), BatchConvertCli.parseCountKeptScripts(MULTI_SCRIPT_XML));
}
private static void writeFile(Path p, String content) throws IOException {
Files.writeString(p, content, StandardCharsets.UTF_8);
}
}

View File

@@ -970,12 +970,12 @@ class TemplateToAmisConverterTest {
// ── WS-B 脚本挂回 onEvent(事件绑定驱动:onselected→selectedChange / onload→inited)────────── // ── WS-B 脚本挂回 onEvent(事件绑定驱动:onselected→selectedChange / onload→inited)──────────
/** Phase 1.1:解析 <scripts><script key> → key→seq(1-based 文档序)。 */ /** Phase 1.1:解析 <script key> → key→seq(1-based 文档序,文本须 ≥5 字符)。 */
@Test @Test
void scriptKeyToSeq_按scripts文档序1based() throws Exception { void scriptKeyToSeq_按文档序1based() throws Exception {
String xml = "<crud><scripts>" String xml = "<crud><scripts>"
+ "<script key=\"K1\" name=\"按钮状态控制\">a</script>" + "<script key=\"K1\" name=\"按钮状态控制\">enableButton(\"x\")</script>"
+ "<script key=\"K2\" name=\"查看只读\">b</script>" + "<script key=\"K2\" name=\"查看只读\">setFieldViewOnly(\"y\")</script>"
+ "</scripts></crud>"; + "</scripts></crud>";
org.dom4j.Element root = org.dom4j.DocumentHelper.parseText(xml).getRootElement(); org.dom4j.Element root = org.dom4j.DocumentHelper.parseText(xml).getRootElement();
Map<String, Integer> m = converter.scriptKeyToSeq(root); Map<String, Integer> m = converter.scriptKeyToSeq(root);
@@ -983,13 +983,63 @@ class TemplateToAmisConverterTest {
assertEquals(2, m.get("K2")); assertEquals(2, m.get("K2"));
} }
/** Phase 1.1:无 <scripts> 段返回空 map(不抛异常)。 */ /** Phase 1.1:无 <script> 返回空 map(不抛异常)。 */
@Test @Test
void scriptKeyToSeq_无scripts段返回空() throws Exception { void scriptKeyToSeq_无script返回空() throws Exception {
org.dom4j.Element root = org.dom4j.DocumentHelper.parseText("<crud/>").getRootElement(); org.dom4j.Element root = org.dom4j.DocumentHelper.parseText("<crud/>").getRootElement();
assertTrue(converter.scriptKeyToSeq(root).isEmpty()); assertTrue(converter.scriptKeyToSeq(root).isEmpty());
} }
/**
* C2 核心:复刻改写器枚举——strip 后 &lt;5 字符的脚本被<b>跳过</b>(不占 seq),
* 后续脚本连续编号。模拟真实模板 d1f64d77(中段空脚本被跳,第三段 key 应落 seq=2 而非 3)。
*/
@Test
void scriptKeyToSeq_短脚本跳过且连续编号() throws Exception {
String xml = "<crud><scripts>"
+ "<script key=\"K_BTN\" name=\"按钮控制\">enableButton(\"发布\",false)</script>" // ≥5 → seq=1
+ "<script key=\"K_EMPTY\" name=\"空脚本\"> </script>" // strip<5 → 跳过
+ "<script key=\"K_FILTER\" name=\"过滤合同\">setFieldFilter(\"C\")</script>" // ≥5 → seq=2(非 3!)
+ "</scripts></crud>";
org.dom4j.Element root = org.dom4j.DocumentHelper.parseText(xml).getRootElement();
Map<String, Integer> m = converter.scriptKeyToSeq(root);
assertEquals(1, m.get("K_BTN"));
assertEquals(2, m.get("K_FILTER")); // 跳过空脚本后连续编号,对齐盘上 2.*.groovy
assertNull(m.get("K_EMPTY")); // 被跳过的短脚本不进映射
assertEquals(2, converter.countKeptScripts(root));
}
/**
* C2 核心:{@code //script} 全局范围——{@code <scripts>} <b>之外</b>的 script 也计入枚举
* (改写器用 xpath('//script'),非仅 <scripts> 直接子;旧实现会漏号)。
*/
@Test
void scriptKeyToSeq_scripts外的script也计入() throws Exception {
String xml = "<crud>"
+ "<scripts><script key=\"K1\">enableButton(\"x\")</script></scripts>"
+ "<panel><script key=\"K2\">setFieldVisible(\"y\")</script></panel>" // <scripts> 外
+ "</crud>";
org.dom4j.Element root = org.dom4j.DocumentHelper.parseText(xml).getRootElement();
Map<String, Integer> m = converter.scriptKeyToSeq(root);
assertEquals(1, m.get("K1"));
assertEquals(2, m.get("K2")); // 旧实现(仅 <scripts> 子)会漏掉 K2
assertEquals(2, converter.countKeptScripts(root));
}
/** C2:keyless 脚本占 seq(不入 key 映射,但消耗号位),保证后续脚本编号对齐盘上文件。 */
@Test
void scriptKeyToSeq_keyless脚本占号() throws Exception {
String xml = "<crud><scripts>"
+ "<script name=\"无key\">enableButton(\"x\")</script>" // 占 seq=1,无 key
+ "<script key=\"K2\" name=\"有key\">setFieldVisible(\"y\")</script>" // seq=2
+ "</scripts></crud>";
org.dom4j.Element root = org.dom4j.DocumentHelper.parseText(xml).getRootElement();
Map<String, Integer> m = converter.scriptKeyToSeq(root);
assertNull(m.get(null)); // keyless 不入映射
assertEquals(2, m.get("K2")); // 但占了号,K2 落 seq=2
assertEquals(2, converter.countKeptScripts(root));
}
/** Phase 1.2:递归收集 onselectedscript / onloadscript 事件绑定。 */ /** Phase 1.2:递归收集 onselectedscript / onloadscript 事件绑定。 */
@Test @Test
void extractEventBindings_收集onselected与onload() throws Exception { void extractEventBindings_收集onselected与onload() throws Exception {
@@ -1130,6 +1180,52 @@ class TemplateToAmisConverterTest {
assertTrue(onEvent.containsKey("inited")); assertTrue(onEvent.containsKey("inited"));
} }
/** C1-a:seqExists 判定——seq 不在「存在集」→ 不挂(fail-closed);在 → 挂。 */
@Test
void attachScriptOnEvent_seq不存在则不挂存在则挂() {
String xml = "<crud entityid='e1'><display><field name='A' text='A'/></display></crud>";
// 绑定:onselected→seq1(不存在)、onload→seq2(存在)
var bindings = List.of(
new TemplateToAmisConverter.EventBinding("onselectedscript", "K1"),
new TemplateToAmisConverter.EventBinding("onloadscript", "K2"));
Map<String, Integer> keyToSeq = Map.of("K1", 1, "K2", 2);
// 只有 seq=2 存在
Map<String, Object> schema = converter.convertGraded(xml, new ArrayList<>(), noPage).getSchema();
converter.attachScriptOnEvent(schema, "tid", bindings, keyToSeq, seq -> seq == 2);
Map<String, Object> onEvent = (Map<String, Object>) body(schema).get("onEvent");
assertFalse(onEvent.containsKey("selectedChange")); // seq=1 缺文件 → 不挂
assertTrue(onEvent.containsKey("inited")); // seq=2 存在 → 挂
// 两者都存在
Map<String, Object> schema2 = converter.convertGraded(xml, new ArrayList<>(), noPage).getSchema();
converter.attachScriptOnEvent(schema2, "tid", bindings, keyToSeq, seq -> true);
Map<String, Object> onEvent2 = (Map<String, Object>) body(schema2).get("onEvent");
assertTrue(onEvent2.containsKey("selectedChange"));
assertTrue(onEvent2.containsKey("inited"));
}
/** I2:同一 (eventType,scriptKey) 在多元素重复出现 → extractEventBindings 只收一次(免 ajax 双发)。 */
@Test
void extractEventBindings_同绑定去重() throws Exception {
String xml = "<crud onselectedscript=\"K1\">"
+ "<display onselectedscript=\"K1\"/>" // 同 (onselected,K1) 重复
+ "<panel onloadscript=\"K2\"/>"
+ "<other onloadscript=\"K2\"/>" // 同 (onload,K2) 重复
+ "<x onselectedscript=\"K2\"/>" // 不同 eventType 同 key → 保留
+ "</crud>";
org.dom4j.Element root = org.dom4j.DocumentHelper.parseText(xml).getRootElement();
List<TemplateToAmisConverter.EventBinding> bs = converter.extractEventBindings(root);
List<String> sig = new ArrayList<>();
for (TemplateToAmisConverter.EventBinding b : bs) {
sig.add(b.eventType + ":" + b.scriptKey);
}
assertEquals(3, sig.size()); // K1×onselected, K2×onload, K2×onselected
assertEquals(1, java.util.Collections.frequency(sig, "onselectedscript:K1"));
assertEquals(1, java.util.Collections.frequency(sig, "onloadscript:K2"));
assertTrue(sig.contains("onselectedscript:K2"));
}
/** Phase 2.2:空入参/空绑定/空 templateId 不挂 onEvent。 */ /** Phase 2.2:空入参/空绑定/空 templateId 不挂 onEvent。 */
@Test @Test
void attachScriptOnEvent_无脚本或空入参不挂onEvent() { void attachScriptOnEvent_无脚本或空入参不挂onEvent() {

View File

@@ -138,8 +138,14 @@ public class ScriptExecuteController {
String script = rewrittenScriptStore.load(templateId, seq); String script = rewrittenScriptStore.load(templateId, seq);
if (script == null || script.isBlank()) { if (script == null || script.isBlank()) {
resp.put("passed", false); // WS-B C1-b:脚本未找到(残余缺脚本/seq 偏差)退化为「无联动」no-op,而非用户可见 ajax 报错。
resp.put("error", "改写后脚本未找到: templateId=" + templateId + " seq=" + seq); // 转换期 fail-closed 已尽量不挂缺文件的绑定;此处兜底任何残余,返空 commands → 前端无动作可重放。
resp.put("templateId", templateId);
resp.put("seq", seq);
resp.put("passed", true);
resp.put("commands", List.of());
resp.put("commandCount", 0);
resp.put("note", "改写后脚本未找到,按无联动处理(no-op): templateId=" + templateId + " seq=" + seq);
return resp; return resp;
} }
resp.put("templateId", templateId); resp.put("templateId", templateId);

View File

@@ -3,6 +3,7 @@ package com.eip4.platform.metadata.web;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@@ -88,21 +89,33 @@ class ScriptExecuteControllerTest {
assertEquals("S-99", args.get("value")); // getFieldValue 从 item 求值闭环 assertEquals("S-99", args.get("value")); // getFieldValue 从 item 求值闭环
} }
/** 缺 templateId 是真错 → passed=false + error(保留)。 */
@Test @Test
void executeTemplateRewritten_缺templateId或脚本未找到时passed为false(@TempDir Path root) { void executeTemplateRewritten_缺templateId时passed为false(@TempDir Path root) {
ScriptExecuteController c = controller(root); ScriptExecuteController c = controller(root);
Map<String, Object> noTid = new LinkedHashMap<>(); Map<String, Object> noTid = new LinkedHashMap<>();
Map<String, Object> r1 = c.executeTemplateRewritten(noTid); Map<String, Object> r1 = c.executeTemplateRewritten(noTid);
assertEquals(Boolean.FALSE, r1.get("passed")); assertEquals(Boolean.FALSE, r1.get("passed"));
assertNotNull(r1.get("error")); assertNotNull(r1.get("error"));
assertTrue(((String) r1.get("error")).contains("templateId"));
}
/** WS-B C1-b:脚本未找到(残余缺脚本/seq 偏差)退化为 no-op(passed=true + 空 commands),不报 ajax 错。 */
@SuppressWarnings("unchecked")
@Test
void executeTemplateRewritten_脚本未找到时退化为noop(@TempDir Path root) {
ScriptExecuteController c = controller(root);
Map<String, Object> missing = new LinkedHashMap<>(); Map<String, Object> missing = new LinkedHashMap<>();
missing.put("templateId", "no-such"); missing.put("templateId", "no-such");
missing.put("seq", 1); missing.put("seq", 1);
Map<String, Object> r2 = c.executeTemplateRewritten(missing); Map<String, Object> r2 = c.executeTemplateRewritten(missing);
assertEquals(Boolean.FALSE, r2.get("passed")); assertEquals(Boolean.TRUE, r2.get("passed")); // no-op,非用户可见报错
assertTrue(((String) r2.get("error")).contains("未找到")); assertNull(r2.get("error")); // 不再返 error
List<Map<String, Object>> cmds = (List<Map<String, Object>>) r2.get("commands");
assertTrue(cmds.isEmpty()); // 空 commands → 前端无动作可重放
assertEquals(0, r2.get("commandCount"));
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")