fix(script): 执行前给 item 注入枚举显示值——修枚举显示串比较类脚本(文件归档)

老 EIP-3 行选中事件传给脚本的 item(grid 行)里枚举列携带的是显示串(如 ISPLACE=「未归档」),
而 loadPOJO().toMap()(poMap)给裸码。改写后脚本据此分工:数值比较走 poMap.get("STATUS"),
显示串比较走 item['ISPLACE'] == "未归档"。EIP4 的 _SEARCH 合成流只把裸码平展进 amis 行 →
item['ISPLACE']=0(非「未归档」) → 比较永假 → 文件归档等永不点亮(全库 285 处
item['COL']=="显示串" 同病;全库 0 处 item[COL]==数字,数值比较一律走 poMap)。

修(通用):
- EnumDisplayResolver:元数据驱动(SYS_ENTITYATTRIBUTE referenceid IN ENUMERATE/STATUS +
  enumeratetype → SYS_ENUMERATE codevalue→codedes),就地把 item 枚举列裸码换成显示串。
  表名优先入参,否则从 item 的 <TABLE>_ID 主键反推;非数字码/无对应值不覆写(幂等安全);
  三层 Caffeine 缓存。
- ScriptExecuteController.executeTemplateRewritten:runWithFacade 前 enrichItem(null,item)。
  加 @Autowired 3 参构造 + 兼容 2 参构造(自建 resolver)。
- PoInfoCacheInvalidator:属性变更同步 enumDisplayResolver.evictAll()(与 userColumnResolver
  同钩子)。

测试:EnumDisplayResolverTest +5、ScriptExecuteControllerTest +1(枚举注入使按钮点亮)、
PoInfoCacheInvalidatorTest 3 参构造适配。运行时实证:POST /api/script/execute-template
传 ISPLACE:0 → item 富化为「未归档」→ enabled 文件归档;ISPLACE:3 → 「已归档」→ 文件归档
不点亮(控制对照)。浏览器选中未归档新闻行→文件归档点亮可点。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-14 19:10:57 +08:00
parent dc4c07ecf4
commit 81cb17bb9a
6 changed files with 407 additions and 6 deletions

View File

@@ -0,0 +1,209 @@
package com.eip4.platform.metadata.flow;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
/**
* 枚举列显示值解析器(脚本 item 上下文:onselectedscript 脚本比较枚举<b>显示串</b>而非裸码)。
*
* <p><b>问题</b>:老 EIP-3 系统行选中事件传给脚本的 {@code item}(grid 行)里,枚举列携带的是
* <b>显示串</b>(如 ISPLACE=「未归档」),而 {@code loadPOJO().toMap()}({@code poMap})给的是
* <b>裸码</b>(0/1/2/3)。改写后脚本据此分工:数值比较走 {@code poMap.get("STATUS")}(裸码),
* 显示串比较走 {@code item['ISPLACE'] == "未归档"}(显示串)。EIP4 的 {@code _SEARCH} 合成流只把
* 裸码平展进 amis 行,{@code item['ISPLACE']} 遂是 {@code 0}(非「未归档」)→ 比较永假 → 文件归档
* 等按钮永不点亮(全库 285 处 {@code item['COL'] == "显示串"} 同病)。
*
* <p><b>修</b>:脚本执行前({@code ScriptExecuteController.executeTemplateRewritten})就地把 {@code item}
* 里枚举列的<b>裸码替换为显示串</b>,复刻老系统 {@code item} 语义。<b>仅覆盖枚举列</b>(元数据
* {@code SYS_ENTITYATTRIBUTE.referenceid IN ('ENUMERATE','STATUS')} + {@code enumeratetype}),引用列/普通列
* 不动;全库脚本零处用 {@code item['COL'] == <数字>}(数值比较一律走 poMap),故覆写安全。
*
* <p><b>元数据驱动</b>:表名由 {@code item} 里的主键列 {@code <TABLE>_ID} 反推;列→枚举类型由
* {@code SYS_ENTITYATTRIBUTE} 查;枚举类型 {@code (codevalue→codedes)} 由 {@code SYS_ENUMERATE} 查。
* 三层均 Caffeine 缓存,失效跟 {@link UserColumnResolver#evictAll} 同钩子(见 MetaController)。
*/
@Component
public class EnumDisplayResolver {
private static final Logger log = LoggerFactory.getLogger(EnumDisplayResolver.class);
/** 合法标识符(表/列名)守卫:元数据来源,仍防御性校验。 */
private static final java.util.regex.Pattern IDENT = java.util.regex.Pattern.compile("^[A-Za-z0-9_]+$");
private final JdbcTemplate jdbcTemplate;
/** 源表(大写) → {枚举列名(大写) → 枚举类型id}。空 map 亦缓存,避免重复查元数据。 */
private final Cache<String, Map<String, String>> enumColsByTable = Caffeine.newBuilder()
.maximumSize(2_000)
.build();
/** 枚举类型id(大写) → {codevalue字符串 → codedes(显示串)}。 */
private final Cache<String, Map<String, String>> enumValuesByType = Caffeine.newBuilder()
.maximumSize(2_000)
.build();
public EnumDisplayResolver(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* 就地把 {@code item} 里枚举列的裸码替换为显示串(复刻老系统 grid 行 item 语义)。
*
* <p>表名优先用入参 {@code table}(调用方已知时),否则从 {@code item} 的主键列 {@code <TABLE>_ID} 反推。
* 任何步骤失败均静默跳过(绝不影响脚本主执行路径,至多回退到「按钮不点亮」的旧行为)。
*
* @param table 实体表名(可 null/空 → 从 item 反推)
* @param item 脚本 item 上下文(amis 选中行;就地修改)
*/
public void enrichItem(String table, Map<String, Object> item) {
if (item == null || item.isEmpty()) {
return;
}
String tbl = (table != null && !table.isBlank()) ? table : inferTableFromItem(item);
if (tbl == null) {
return;
}
Map<String, String> enumCols;
try {
enumCols = enumColumnsForTable(tbl);
} catch (RuntimeException ex) {
log.warn("[ENUM-DISP] 解析枚举列失败 table={}: {} → item 不富化", tbl, ex.getMessage());
return;
}
if (enumCols.isEmpty()) {
return;
}
// item 的 key 可能是任意大小写;建一个 大写key→原key 映射以就地改回原 key。
Map<String, String> upperToRaw = new HashMap<>();
for (String k : item.keySet()) {
upperToRaw.putIfAbsent(k.toUpperCase(), k);
}
for (Map.Entry<String, String> e : enumCols.entrySet()) {
String colUpper = e.getKey();
String rawKey = upperToRaw.get(colUpper);
if (rawKey == null) {
continue; // item 无此列
}
Object code = item.get(rawKey);
String codeKey = normalizeCode(code);
if (codeKey == null) {
continue; // 空值 / 已是显示串(非数字码)→ 不动
}
Map<String, String> valueMap = enumValuesForType(e.getValue());
String display = valueMap.get(codeKey);
if (display != null && !display.isBlank()) {
item.put(rawKey, display); // 裸码 → 显示串(复刻老系统 item 语义)
}
}
}
/** 从 item 的主键列 {@code <TABLE>_ID} 反推表名(取首个匹配 {@code ^[A-Z0-9_]+_ID$} 且去后缀合法的 key)。 */
private String inferTableFromItem(Map<String, Object> item) {
for (String k : item.keySet()) {
String up = k.toUpperCase();
if (up.endsWith("_ID") && up.length() > 3) {
String tbl = up.substring(0, up.length() - 3);
// 排除引用列(如 USERSEND_ID/NEWS_ID):只接受其值 == 当前行主键的那一个不易判,
// 但主键列约定为 <TABLE>_ID 且 item 里通常只有一个表的主键;取首个合法标识符即可。
if (IDENT.matcher(tbl).matches() && !tbl.isBlank()) {
return tbl;
}
}
}
return null;
}
/** 源表 → {枚举列 → 枚举类型id}。referenceid IN (ENUMERATE,STATUS) 且 enumeratetype 非空的列。 */
private Map<String, String> enumColumnsForTable(String table) {
return enumColsByTable.get(table.toUpperCase(), this::queryEnumColumns);
}
private Map<String, String> queryEnumColumns(String upperTable) {
Map<String, String> map = new LinkedHashMap<>();
try {
List<Map<String, Object>> rows = jdbcTemplate.queryForList(
"SELECT UPPER(ea.columnname) AS col, ea.enumeratetype AS etype "
+ "FROM eip3.sys_entityattribute ea "
+ "JOIN eip3.sys_entity e ON UPPER(e.sys_entity_id) = UPPER(ea.entityid) "
+ "WHERE UPPER(e.tablename) = ? "
+ "AND UPPER(ea.referenceid) IN ('ENUMERATE','STATUS') "
+ "AND ea.enumeratetype IS NOT NULL AND ea.enumeratetype <> ''",
upperTable);
for (Map<String, Object> r : rows) {
String col = String.valueOf(r.get("col"));
String etype = r.get("etype") == null ? null : String.valueOf(r.get("etype")).trim();
if (etype != null && !etype.isBlank()) {
map.put(col, etype);
}
}
} catch (org.springframework.dao.DataAccessException ex) {
log.warn("[ENUM-DISP] 解析枚举列失败 table={}: {}", upperTable, ex.getMessage());
}
return map.isEmpty() ? Collections.emptyMap() : map;
}
/** 枚举类型id → {codevalue字符串 → codedes}。 */
private Map<String, String> enumValuesForType(String enumType) {
return enumValuesByType.get(enumType.toUpperCase(), k -> queryEnumValues(enumType));
}
private Map<String, String> queryEnumValues(String enumType) {
Map<String, String> map = new LinkedHashMap<>();
try {
List<Map<String, Object>> rows = jdbcTemplate.queryForList(
"SELECT codevalue, codedes FROM eip3.sys_enumerate "
+ "WHERE UPPER(sys_enumeratetype_id) = ? AND isactive = 1 ORDER BY orderasc",
enumType.toUpperCase());
for (Map<String, Object> r : rows) {
Object cv = r.get("codevalue");
Object cd = r.get("codedes");
if (cv != null && cd != null) {
map.put(String.valueOf(cv).trim(), String.valueOf(cd).trim());
}
}
} catch (org.springframework.dao.DataAccessException ex) {
log.warn("[ENUM-DISP] 加载枚举值失败 type={}: {}", enumType, ex.getMessage());
}
return map.isEmpty() ? Collections.emptyMap() : map;
}
/**
* 归一化枚举码为查表 key:仅当值是「整数码」(数字或数字字符串)时返回其整数字符串,否则 null。
* 非数字(已是显示串/UUID/日期等)→ null(不覆写,幂等安全)。
*/
private static String normalizeCode(Object code) {
if (code == null) {
return null;
}
if (code instanceof Number n) {
return String.valueOf(n.intValue());
}
String s = String.valueOf(code).trim();
if (s.isEmpty()) {
return null;
}
// 允许 "0" / "3" / "3.0" 形态;非纯整数(含中文/字母)→ 不当枚举码处理
try {
return String.valueOf((int) Double.parseDouble(s));
} catch (NumberFormatException e) {
return null;
}
}
/** 失效全部缓存(与 /api/meta/evict 钩子对齐)。 */
public void evictAll() {
enumColsByTable.invalidateAll();
enumValuesByType.invalidateAll();
}
}

View File

@@ -5,6 +5,7 @@ import org.springframework.stereotype.Component;
import com.dsasp.server.common.dataDic.bean.AbstractPOJOInfo;
import com.dsasp.server.common.dataDic.bean.POJOInfo;
import com.dsasp.server.dataDic.bean.POInfo;
import com.eip4.platform.metadata.flow.EnumDisplayResolver;
import com.eip4.platform.metadata.flow.UserColumnResolver;
import com.eip4.platform.metadata.security.IdentifierWhitelist;
@@ -25,11 +26,14 @@ public class PoInfoCacheInvalidator {
private final IdentifierWhitelist identifierWhitelist;
private final UserColumnResolver userColumnResolver;
private final EnumDisplayResolver enumDisplayResolver;
public PoInfoCacheInvalidator(IdentifierWhitelist identifierWhitelist,
UserColumnResolver userColumnResolver) {
UserColumnResolver userColumnResolver,
EnumDisplayResolver enumDisplayResolver) {
this.identifierWhitelist = identifierWhitelist;
this.userColumnResolver = userColumnResolver;
this.enumDisplayResolver = enumDisplayResolver;
}
/**
@@ -59,6 +63,8 @@ public class PoInfoCacheInvalidator {
identifierWhitelist.evict(upper);
// read-path D1=603:属性变更可能改动列的 referenceid(用户引用与否),同步失效用户引用列缓存
userColumnResolver.evictTable(upper);
// 小修#2:属性变更可能改动列的枚举类型/枚举值 → 失效枚举显示值缓存(粒度小,全量失效即可)
enumDisplayResolver.evictAll();
}
/**

View File

@@ -9,6 +9,7 @@ import javax.script.Bindings;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@@ -16,6 +17,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.dsasp.server.dataDic.binding.ScriptingEnginesManager;
import com.eip4.platform.metadata.flow.EnumDisplayResolver;
import com.eip4.platform.metadata.script.RewrittenScriptStore;
import com.eip4.platform.metadata.script.ScriptFacade;
@@ -38,10 +40,20 @@ public class ScriptExecuteController {
private final JdbcTemplate jdbcTemplate;
private final RewrittenScriptStore rewrittenScriptStore;
/** 小修#2:脚本执行前给 item 注入枚举列显示串(复刻老系统 grid 行 item 语义),修 {@code item['ISPLACE']=="未归档"} 类脚本。 */
private final EnumDisplayResolver enumDisplayResolver;
public ScriptExecuteController(JdbcTemplate jdbcTemplate, RewrittenScriptStore rewrittenScriptStore) {
@Autowired
public ScriptExecuteController(JdbcTemplate jdbcTemplate, RewrittenScriptStore rewrittenScriptStore,
EnumDisplayResolver enumDisplayResolver) {
this.jdbcTemplate = jdbcTemplate;
this.rewrittenScriptStore = rewrittenScriptStore;
this.enumDisplayResolver = enumDisplayResolver;
}
/** 兼容旧 2 参构造(单测/旧接线):从 jdbcTemplate 自建枚举显示值解析器。 */
public ScriptExecuteController(JdbcTemplate jdbcTemplate, RewrittenScriptStore rewrittenScriptStore) {
this(jdbcTemplate, rewrittenScriptStore, new EnumDisplayResolver(jdbcTemplate));
}
/**
@@ -148,6 +160,12 @@ public class ScriptExecuteController {
resp.put("note", "改写后脚本未找到,按无联动处理(no-op): templateId=" + templateId + " seq=" + seq);
return resp;
}
// 小修#2:脚本执行前把 item 里枚举列的裸码换成显示串(复刻老系统 grid 行 item 语义),使
// onselectedscript 里 `item['ISPLACE'] == "未归档"` 类显示串比较成立(否则裸码 0 != "未归档"
// → 文件归档等按钮永不点亮)。表名从 item 的 <TABLE>_ID 主键反推;失败静默跳过不影响主路径。
if (enumDisplayResolver != null) {
enumDisplayResolver.enrichItem(null, item);
}
resp.put("templateId", templateId);
resp.put("seq", seq);
try {