diff --git a/platform-converter/src/main/java/com/eip4/platform/converter/TemplateToAmisConverter.java b/platform-converter/src/main/java/com/eip4/platform/converter/TemplateToAmisConverter.java index e74f1e2..1d9eed9 100644 --- a/platform-converter/src/main/java/com/eip4/platform/converter/TemplateToAmisConverter.java +++ b/platform-converter/src/main/java/com/eip4/platform/converter/TemplateToAmisConverter.java @@ -2063,39 +2063,34 @@ public class TemplateToAmisConverter { continue; } formItems.set(i, buildAttachmentField(item, upper, pkCol)); - result.note("WS-D 附件字段 " + item.get("name") + " → service 容器(已有附件只读下载列表 " - + "/api/file/list?tableName=" + upper + "&businessKey=${" + pkCol + "} + 保留上传控件)"); + result.note("WS-D 附件字段 " + item.get("name") + " → input-file 双态(staticOn ${__readonly}: " + + "查看只读显名可下载/编辑可增删; 上传 receiver 带 tableName=" + upper + + "&businessKey=${" + pkCol + "} 关联本记录)"); } } - /** 构造附件 service 容器:已有附件下载列表(each) + 原上传控件(input-file)。 */ + /** + * 附件字段(input-file)配置为查看/编辑双态单组件: + * + * 已有附件由后端按 amis 契约 {@code [{id,name,value,url}]} 返回(FlowController 响应边界 + * {@code resolveAttachmentFields} 把保真层大写 {@code SYS_DOC_ID/FILENAME} 归一为小写), + * input-file 默认字段({@code name/value/url})即可显名+下载,无需额外 service/each 容器。 + */ private static Map buildAttachmentField(Map uploadItem, String upperTable, String pkCol) { - // 已有附件下载链接(文件名(大小KB)),下载走 FileController.download(Content-Disposition: attachment) - Map link = new LinkedHashMap<>(); - link.put("type", "tpl"); - link.put("tpl", "${name}(${sizeKb}KB)"); - - Map each = new LinkedHashMap<>(); - each.put("type", "each"); - each.put("name", "items"); // service api data.items - each.put("placeholder", "无附件"); - each.put("items", link); - - Map service = new LinkedHashMap<>(); - service.put("type", "service"); - // 业务键绑表单主键;空主键(新增态)时 list 端点返空,不误列 - service.put("api", "get:/api/file/list?tableName=" + upperTable + "&businessKey=${" + pkCol + "}"); - // M4:service.name 与内层 input-file 同名(皆 DOCUMENT)。service.name 仅作布局归位 key - // (供
把本容器排到正确位置),表单实际取值由内层 input-file 绑定; - // amis 容忍二者同名(外层 service 不抢绑该字段值)——已浏览器实证(查看页附件下载列表+上传控件正常)。 - service.put("name", uploadItem.get("name")); // 保
归位 - service.put("label", uploadItem.get("label")); - List> body = new ArrayList<>(); - body.add(each); - body.add(uploadItem); // 保留上传控件(编辑态加附件;static 态自禁用) - service.put("body", body); - return service; // type=service → isWideField 判宽控件独占整行 + uploadItem.put("receiver", + "/api/file/upload?tableName=" + upperTable + "&businessKey=${" + pkCol + "}"); + uploadItem.put("staticOn", "${__readonly}"); + // 提交时保留附件对象数组(而非默认 joinValues 拼成的逗号串):保真层 + // POJOServiceImpl.updateAttachments 要求 DOCUMENT 是 List,String 会 ClassCastException。 + // 由 FlowController 写路径把对象数组归一为 [{SYS_DOC_ID:id}] 供保真层按 id 对账(增/留/删)。 + uploadItem.put("joinValues", false); + uploadItem.put("extractValue", false); + return uploadItem; } /** diff --git a/platform-converter/src/test/java/com/eip4/platform/converter/TemplateToAmisConverterTest.java b/platform-converter/src/test/java/com/eip4/platform/converter/TemplateToAmisConverterTest.java index 7e65aec..f494cef 100644 --- a/platform-converter/src/test/java/com/eip4/platform/converter/TemplateToAmisConverterTest.java +++ b/platform-converter/src/test/java/com/eip4/platform/converter/TemplateToAmisConverterTest.java @@ -1813,8 +1813,8 @@ class TemplateToAmisConverterTest { @SuppressWarnings("unchecked") void form_附件字段MultiFileUploadField转inputFile() { // F2-8 实证:MultiFileUploadField / FileUploadField → input-file(receiver + downloadUrl) - // WS-D D.2:附件字段进而被包进 service 容器(已有附件下载列表 + 上传控件), - // 内层 input-file 契约不变(receiver/downloadUrl/multiple)。 + // Tier1:附件字段就是单个 input-file 双态组件(staticOn ${__readonly}: 查看只读可下载/编辑可增删), + // receiver 带 tableName+businessKey 使编辑态上传关联本记录。 String pageXml = "" + "" + "" @@ -1829,20 +1829,20 @@ class TemplateToAmisConverterTest { List> items = flattenFormBody(form); assertEquals(3, items.size()); - // MultiFileUploadField → service 容器;内层 input-file multiple=true + // MultiFileUploadField → 单个 input-file(双态),multiple=true,receiver 带业务键,staticOn 只读 Map docField = items.get(1); - Map docUpload = attachmentUploadOf(docField); - assertEquals("input-file", docUpload.get("type")); - assertEquals("/api/file/upload", docUpload.get("receiver")); - assertEquals("/api/file/${id}", docUpload.get("downloadUrl")); - assertEquals(true, docUpload.get("multiple")); + assertEquals("input-file", docField.get("type")); + assertEquals("/api/file/upload?tableName=PM_DEMO&businessKey=${PM_DEMO_ID}", docField.get("receiver")); + assertEquals("/api/file/${id}", docField.get("downloadUrl")); + assertEquals(true, docField.get("multiple")); + assertEquals("${__readonly}", docField.get("staticOn")); - // FileUploadField → service 容器;内层 input-file 无 multiple + // FileUploadField → 单个 input-file,无 multiple Map singleField = items.get(2); - Map singleUpload = attachmentUploadOf(singleField); - assertEquals("input-file", singleUpload.get("type")); - assertEquals("/api/file/upload", singleUpload.get("receiver")); - assertNull(singleUpload.get("multiple")); + assertEquals("input-file", singleField.get("type")); + assertEquals("/api/file/upload?tableName=PM_DEMO&businessKey=${PM_DEMO_ID}", singleField.get("receiver")); + assertNull(singleField.get("multiple")); + assertEquals("${__readonly}", singleField.get("staticOn")); // 映射台账中有 input-file 记录 assertTrue(notes.stream().anyMatch(n -> n.contains("input-file"))); @@ -1850,9 +1850,10 @@ class TemplateToAmisConverterTest { @Test @SuppressWarnings("unchecked") - void form_附件字段_查看态只读下载列表() { - // WS-D D.2:附件字段(input-file) → service 容器(api 按业务 id 拉 /api/file/list, - // each 渲染已有附件下载链接 + 保留上传控件),对齐老系统查看页附件可下载列表。 + void form_附件字段_查看编辑双态单组件() { + // Tier1:附件字段 = 单个 input-file 双态组件。查看(${__readonly}=真)静态只读显名可下载、 + // 编辑可增删;已有附件由后端按 amis 契约 [{id,name,value,url}] 返回 + // (FlowController.resolveAttachmentFields 把保真层大写 SYS_DOC_ID/FILENAME 归一),无需 service/each。 String pageXml = "" + "" + ""; @@ -1865,25 +1866,16 @@ class TemplateToAmisConverterTest { List> items = flattenFormBody(form); Map doc = items.get(0); - // 附件容器:service,按业务 id 拉已有附件,name=DOCUMENT(保布局归位),label=附件 - assertEquals("service", doc.get("type")); + assertEquals("input-file", doc.get("type")); assertEquals("DOCUMENT", doc.get("name")); assertEquals("附件", doc.get("label")); - assertEquals("get:/api/file/list?tableName=PM_DEMO&businessKey=${PM_DEMO_ID}", doc.get("api")); - - List> svcBody = (List>) doc.get("body"); - assertEquals(2, svcBody.size()); - // (1) each 渲染已有附件下载列表 - Map each = svcBody.get(0); - assertEquals("each", each.get("type")); - assertEquals("items", each.get("name")); - Map link = (Map) each.get("items"); - assertEquals("tpl", link.get("type")); - assertTrue(String.valueOf(link.get("tpl")).contains("/api/file/${id}"), "下载链接指向 FileController.download"); - assertTrue(String.valueOf(link.get("tpl")).contains("${name}"), "显示文件名"); - assertTrue(String.valueOf(link.get("tpl")).contains("${sizeKb}"), "显示大小KB"); - // (2) 保留上传控件 - assertEquals("input-file", svcBody.get(1).get("type")); + assertEquals("${__readonly}", doc.get("staticOn"), "查看态静态只读、编辑态可增删"); + assertEquals("/api/file/upload?tableName=PM_DEMO&businessKey=${PM_DEMO_ID}", doc.get("receiver")); + assertEquals("/api/file/${id}", doc.get("downloadUrl")); + assertNull(doc.get("api"), "不再用 service/each 容器"); + // 提交为对象数组(非 joinValues 逗号串),供保真层 updateAttachments 按 SYS_DOC_ID 对账 + assertEquals(false, doc.get("joinValues"), "提交附件对象数组而非逗号串"); + assertEquals(false, doc.get("extractValue"), "保留对象(含 url 签名)供写路径归一"); } @Test @@ -1916,18 +1908,6 @@ class TemplateToAmisConverterTest { assertNull(doc.get("api"), "降级时不应配 /api/file/list(表名不可靠)"); } - /** 从 WS-D 附件 service 容器里取内层上传控件(input-file)。 */ - @SuppressWarnings("unchecked") - private static Map attachmentUploadOf(Map attachmentField) { - assertEquals("service", attachmentField.get("type"), "附件字段应被包进 service 容器"); - List> svcBody = (List>) attachmentField.get("body"); - for (Map b : svcBody) { - if ("input-file".equals(b.get("type"))) { - return b; - } - } - throw new AssertionError("附件 service 容器内未找到 input-file 上传控件"); - } @Test @SuppressWarnings("unchecked") @@ -1951,12 +1931,13 @@ class TemplateToAmisConverterTest { // PasswordField → input-password(不再明文 input-text) assertEquals("input-password", items.get(1).get("type")); - // SingleFileUploadField → input-file 单文件(无 multiple);WS-D 包进 service 容器,内层 input-file - Map certUpload = attachmentUploadOf(items.get(2)); + // SingleFileUploadField → 单个 input-file 单文件(无 multiple),双态 staticOn ${__readonly} + Map certUpload = items.get(2); assertEquals("input-file", certUpload.get("type")); - assertEquals("/api/file/upload", certUpload.get("receiver")); + assertEquals("/api/file/upload?tableName=PM_DEMO&businessKey=${PM_DEMO_ID}", certUpload.get("receiver")); assertEquals("/api/file/${id}", certUpload.get("downloadUrl")); assertNull(certUpload.get("multiple")); + assertEquals("${__readonly}", certUpload.get("staticOn")); // DateField → input-date(复用 PopupDateField 无时分支) assertEquals("input-date", items.get(3).get("type")); @@ -4134,10 +4115,10 @@ class TemplateToAmisConverterTest { assertEquals("group", row2.get("type"), "落单窄字段也包 group(保持行结构一致)"); assertEquals(1, ((List) row2.get("body")).size()); - // 附件字段(WS-D)包进 service 容器,仍作宽控件独占整行;内层含 input-file 上传控件 - assertEquals("service", rows.get(3).get("type"), "附件 service 容器独占整行(宽控件)"); - assertEquals("DOC", rows.get(3).get("name"), "附件容器保留字段 name 以归位布局"); - assertTrue(rows.get(3).toString().contains("input-file"), "附件容器内保留上传控件"); + // 附件字段(Tier1)= 单个 input-file 双态组件,input-file 本即宽控件独占整行 + assertEquals("input-file", rows.get(3).get("type"), "附件 input-file 独占整行(宽控件)"); + assertEquals("DOC", rows.get(3).get("name"), "附件字段保留 name 以归位布局"); + assertEquals("${__readonly}", rows.get(3).get("staticOn"), "查看只读/编辑可增删"); assertEquals("textarea", rows.get(4).get("type")); // actions 仍为空(单按钮契约不变) diff --git a/platform-metadata/src/main/java/com/eip4/platform/metadata/web/FileController.java b/platform-metadata/src/main/java/com/eip4/platform/metadata/web/FileController.java index 2435c9d..84af709 100644 --- a/platform-metadata/src/main/java/com/eip4/platform/metadata/web/FileController.java +++ b/platform-metadata/src/main/java/com/eip4/platform/metadata/web/FileController.java @@ -132,7 +132,7 @@ public class FileController { "INSERT INTO sys_doc(sys_doc_id,tablename,businesskey,filename,fileext," + "filesize,filepath,md5hash,createby,createtime,updateby,updatetime,isactive,version)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,1,0)", - docId, tableName.toUpperCase(), businessKey, + docId, tableName.toUpperCase(), padBusinessKey(businessKey), originalName, ext, (int) Math.min(fileSize, Integer.MAX_VALUE), relativePath, md5, "system", now, "system", now); } catch (Exception e) { @@ -143,6 +143,7 @@ public class FileController { Map data = new LinkedHashMap<>(); data.put("id", docId); + data.put("value", docId); // amis input-file valueField=value:上传后对象即带提交值(写路径按 id 归一) data.put("name", originalName); data.put("url", "/api/file/" + docId); data.put("size", fileSize); @@ -292,6 +293,23 @@ public class FileController { } } + /** + * 业务主键右补白到 36 位,对齐保真层引擎的 CHAR(36) 主键语义。 + * + *

保真层 {@code FileServiceImpl.getDoc} 用 {@code businesskey = po.get_ID()} 精确匹配查附件, + * 而引擎把记录主键按 {@code CHAR(36)} 处理({@code get_ID()} 返回右补空格到 36 位)。新上传若按 + * 去白 32 位 hex 存 {@code businesskey},则 {@code loadDoc}(查看/编辑 {@code _LOAD} 走它)永远读不到 + * → 附件“存不上”。故入库前归一为 {@code rtrim 后右补到 36 位};已是 36 位 dashed-UUID 主键不变; + * 超 36 位(理论不会)原样保留。{@code /api/file/list} 用 {@code rtrim(businesskey)} 比对,padding 无影响。 + */ + private static String padBusinessKey(String key) { + if (key == null) { + return null; + } + String trimmed = key.trim(); + return trimmed.length() <= 36 ? String.format("%-36s", trimmed) : trimmed; + } + private static String extractExt(String filename) { if (filename == null || !filename.contains(".")) { return ""; diff --git a/platform-metadata/src/main/java/com/eip4/platform/metadata/web/FlowController.java b/platform-metadata/src/main/java/com/eip4/platform/metadata/web/FlowController.java index 31c85d7..9825b2c 100644 --- a/platform-metadata/src/main/java/com/eip4/platform/metadata/web/FlowController.java +++ b/platform-metadata/src/main/java/com/eip4/platform/metadata/web/FlowController.java @@ -302,6 +302,10 @@ public class FlowController { */ private ResponseEntity> run(String id, Map map, boolean isPost, String egTpl) { ResolvedFlow resolved = flowNameResolver.resolve(id); + // 写路径附件归一:修改流 → [{SYS_DOC_ID}](保真层对账);新建流 → 捕获 docId 并从 map 剥离, + // 待保存后用返回主键改挂(见 relinkInsertedAttachments)。 + List insertAttachmentIds = isPost + ? normalizeAttachmentFieldsForWrite(map, id) : List.of(); return switch (resolved.type()) { case UUID_PASSTHROUGH -> { @@ -370,6 +374,8 @@ public class FlowController { } Properties ctx = currentCtx(); Object output = withEngineContext(ctx, () -> flowExcuteService.excute(map, ctx, id)); + // 新建流:把上传时 businesskey=UNKNOWN 的附件改挂到本次新建记录的主键(无孤儿、无复制)。 + relinkInsertedAttachments(id, output, insertAttachmentIds); yield ok(output, null, egTpl); } case SYNTHESIZED -> { @@ -440,6 +446,7 @@ public class FlowController { // read-path issue D1=603:把元数据标记为用户引用的列 id/工号 → 姓名(仅在已知数据源实体的合成搜索流上) resolveUserColumns(data, table); resolveReferenceFields(data, egTpl); + resolveAttachmentFields(data); Map resp = new LinkedHashMap<>(); resp.put("status", 0); resp.put("msg", ""); @@ -520,6 +527,226 @@ public class FlowController { } } + /** + * 附件字段(DOCUMENT/Binary)契约归一:保真层 {@code loadDoc} 把附件列加载为大写键 + * ({@code SYS_DOC_ID/FILENAME/FILESIZE})的 Map 列表,amis input-file 默认认小写 + * {@code name/value/url} → 渲成无名空白项、点不开。此处在响应边界统一成 amis 契约 + * {@code [{id,value,name,url,sizeKb}]}(零改 {@code com.dsasp}),使附件 input-file 双态可用: + * 查看(只读)态显名可下载、编辑态可增删。覆盖主记录 + 一层子表行的附件列。 + */ + @SuppressWarnings("unchecked") + private static void resolveAttachmentFields(Object data) { + if (!(data instanceof Map m0)) { + return; + } + Map map = (Map) m0; + if (map.get("items") instanceof List) { + return; // 列表/crud 形态不加载附件 + } + Object resultObj = map.get("result"); + Map record = resultObj instanceof Map r ? (Map) r : map; + normalizeAttachmentsInRow(record); + for (Object v : record.values()) { + if (v instanceof List sub) { + for (Object o : sub) { + if (o instanceof Map row) { + normalizeAttachmentsInRow((Map) row); + } + } + } + } + } + + /** 就地把行内「附件列」(值为含 {@code SYS_DOC_ID} 的 Map 列表)转为 amis input-file 契约。 */ + @SuppressWarnings("unchecked") + private static void normalizeAttachmentsInRow(Map row) { + for (Map.Entry e : row.entrySet()) { + if (!(e.getValue() instanceof List list) || !isAttachmentList(list)) { + continue; + } + List> out = new ArrayList<>(); + for (Object o : list) { + if (!(o instanceof Map a0)) { + continue; + } + Map a = (Map) a0; + Object idRaw = a.get("SYS_DOC_ID"); + if (idRaw == null) { + continue; + } + String id = String.valueOf(idRaw).trim(); + long size = toLong(a.get("FILESIZE")); + Map file = new LinkedHashMap<>(); + file.put("id", id); + file.put("value", id); // input-file 提交值 = sys_doc id + file.put("name", a.get("FILENAME")); + file.put("url", "/api/file/" + id); + file.put("sizeKb", size > 0 ? Math.max(1, (size + 1023) / 1024) : 0); + out.add(file); + } + e.setValue(out); + } + } + + /** 附件列签名:非空且首元素是含 {@code SYS_DOC_ID} 的 Map({@code loadDoc} 产物,附件专属)。 */ + private static boolean isAttachmentList(List list) { + return !list.isEmpty() + && list.get(0) instanceof Map m + && m.containsKey("SYS_DOC_ID"); + } + + /** + * 写路径附件字段归一({@link #resolveAttachmentFields} 的逆向):amis input-file + * ({@code joinValues:false, extractValue:false})提交的是附件对象数组 {@code [{id,value,name,url,...}]}, + * 而保真层 {@code POJOServiceImpl.updateAttachments} 期望 {@code List} 且按 {@code SYS_DOC_ID} 键对账 + * (提交 String 逗号串 → {@code ClassCastException};缺 {@code SYS_DOC_ID} → 误当新附件重复插入)。 + * 此处把带 amis 附件签名({@code url} 形如 {@code /api/file/{id}})的整列就地转为 {@code [{SYS_DOC_ID:id}]}, + * 使保真层正确「保留已存 / 软删移除 / 不重复插入已上传」。零改 {@code com.dsasp}。 + * + *

空数组保留为空 {@code List}({@code updateAttachments} 据此软删全部已存附件 = 用户清空附件); + * 子表行(大写业务列、无 {@code /api/file/} url)整列不匹配签名 → 不动。 + */ + @SuppressWarnings("unchecked") + private static List normalizeAttachmentFieldsForWrite(Map map, String flowId) { + if (map == null) { + return List.of(); + } + boolean insert = isInsertFlow(flowId); + List capturedIds = new ArrayList<>(); + List keysToRemove = new ArrayList<>(); + for (Map.Entry e : map.entrySet()) { + if (!(e.getValue() instanceof List list) || list.isEmpty()) { + continue; + } + if (!list.stream().allMatch(FlowController::isAmisAttachmentItem)) { + continue; + } + if (insert) { + // 新建:文件上传时 sys_doc 已落库(businesskey=UNKNOWN,因新建态尚无主键)。记下 docId + // 待保存后用引擎返回的新主键 UPDATE 改挂(见 relinkInsertedAttachments),并从写入 map + // 移除该字段——不走保真层插入路径(saveAttachments 会复制一条、留下 UNKNOWN 孤儿)。 + for (Object o : list) { + String docId = attachmentDocId((Map) o); + if (docId != null && !docId.isBlank()) { + capturedIds.add(docId); + } + } + keysToRemove.add(e.getKey()); + } else { + // 修改:→ [{SYS_DOC_ID}] 交保真层 updateAttachments 对账(保留已存/软删移除/已上传不重复插)。 + List> legacy = new ArrayList<>(); + for (Object o : list) { + String docId = attachmentDocId((Map) o); + if (docId != null && !docId.isBlank()) { + Map m = new LinkedHashMap<>(); + m.put("SYS_DOC_ID", docId); + legacy.add(m); + } + } + e.setValue(legacy); + } + } + for (String k : keysToRemove) { + map.remove(k); + } + return capturedIds; + } + + /** + * 新建保存后把上传的附件改挂到新记录主键:{@code UPDATE sys_doc SET businesskey=新主键} + * (直接改挂、非复制 → 无 UNKNOWN 孤儿)。新主键取引擎返回 {@code result._ID}; + * 仅改 {@code businesskey} 仍为 {@code UNKNOWN/空} 的未挂行(防误挂他人已挂附件)。businesskey 右补白 + * 到 36 位对齐保真层 {@code getDoc}(CHAR(36) 主键)。 + */ + @SuppressWarnings("unchecked") + private void relinkInsertedAttachments(String flowId, Object output, List docIds) { + if (docIds == null || docIds.isEmpty() || jdbcTemplate == null) { + return; + } + String table = insertFlowTable(flowId); + if (table == null) { + return; + } + // 原始 output 的 result 多为 GeneralPOJO(非 Map),先归一展平再取主键列。 + Object normalized = normalize(output); + Object res = (normalized instanceof Map m && m.get("result") instanceof Map r) ? r : normalized; + if (!(res instanceof Map rm)) { + return; + } + Object pk = ((Map) rm).get(table + "_ID"); + if (pk == null || String.valueOf(pk).isBlank()) { + return; + } + String businessKey = String.format("%-36s", String.valueOf(pk).trim()); + for (String docId : docIds) { + try { + jdbcTemplate.update( + "UPDATE sys_doc SET businesskey = ?, tablename = ? WHERE sys_doc_id = ? " + + "AND rtrim(businesskey) IN ('UNKNOWN', '') AND isactive = 1", + businessKey, table, docId.trim()); + } catch (Exception ex) { + log.warn("[FLOW] 附件改挂失败 docId={} → {}: {}", docId, table, ex.toString()); + } + } + } + + /** 插入流名 {@code
_ADD/_INSERT/_NEW} → 业务表名 {@code
};非插入流返回 null。 */ + private static String insertFlowTable(String flowId) { + if (flowId == null) { + return null; + } + String u = flowId.toUpperCase(); + for (String suf : new String[] {"_ADD", "_INSERT", "_NEW"}) { + if (u.endsWith(suf)) { + return u.substring(0, u.length() - suf.length()); + } + } + return null; + } + + /** 插入流判定:服务流名以 {@code _ADD/_INSERT/_NEW} 结尾。 */ + private static boolean isInsertFlow(String flowId) { + return insertFlowTable(flowId) != null; + } + + /** amis 附件对象签名:Map 且 {@code url} 形如 {@code /api/file/...}(附件专属,子表行不会命中)。 */ + private static boolean isAmisAttachmentItem(Object o) { + return o instanceof Map m + && m.get("url") instanceof String s + && s.contains("/api/file/"); + } + + /** 从 amis 附件对象提取 sys_doc id:优先 {@code value},回退 {@code url} 末段,再回退 {@code id} + * (新上传对象 id 被 amis 改写为本地 guid,故 id 优先级最低)。 */ + private static String attachmentDocId(Map item) { + Object v = item.get("value"); + if (v != null && !String.valueOf(v).isBlank()) { + return String.valueOf(v).trim(); + } + if (item.get("url") instanceof String s) { + int i = s.lastIndexOf('/'); + if (i >= 0 && i < s.length() - 1) { + return s.substring(i + 1).trim(); + } + } + Object id = item.get("id"); + return id == null ? null : String.valueOf(id).trim(); + } + + private static long toLong(Object v) { + if (v instanceof Number n) { + return n.longValue(); + } + if (v == null) { + return 0; + } + try { + return Long.parseLong(String.valueOf(v).trim()); + } catch (NumberFormatException ex) { + return 0; + } + } + /** view_page 里的可编辑引用字段:列名(大写) + dialogid(picker 数据源) + 是否多选。 */ private record RefField(String name, String dialogid, boolean multi) {} diff --git a/platform-metadata/src/test/java/com/eip4/platform/metadata/web/FileControllerTest.java b/platform-metadata/src/test/java/com/eip4/platform/metadata/web/FileControllerTest.java index 2952775..1800ba2 100644 --- a/platform-metadata/src/test/java/com/eip4/platform/metadata/web/FileControllerTest.java +++ b/platform-metadata/src/test/java/com/eip4/platform/metadata/web/FileControllerTest.java @@ -4,12 +4,16 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -20,6 +24,7 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.http.ResponseEntity; import org.springframework.jdbc.core.JdbcOperations; +import org.springframework.mock.web.MockMultipartFile; /** * WS-D D.2 FileController.list(按业务 id 列已有附件)单测(mock JdbcTemplate,不连库)。 @@ -142,4 +147,39 @@ class FileControllerTest { assertEquals(evilTable.trim().toUpperCase(), boundArgs.get(0)); assertEquals(evilKey.trim(), boundArgs.get(1)); } + + @Test + @DisplayName("6. upload businesskey 右补白到 36 位(对齐保真层 CHAR(36) 主键;否则 loadDoc 查不到新附件)") + void uploadPadsBusinessKeyTo36() throws Exception { + Path tmpRoot = Files.createTempDirectory("eip4-file-test"); + FileController c = new FileController(jdbc, tmpRoot.toString()); + MockMultipartFile file = new MockMultipartFile("file", "新附件.txt", "text/plain", + "hello".getBytes(StandardCharsets.UTF_8)); + + // 先挂 thenAnswer 捕获 INSERT 变长绑定参数(docId, tableName, businesskey, ...); + // 变长参兼容「展开」与「Object[] 数组」两种形态。 + List bound = new java.util.ArrayList<>(); + when(jdbc.update(anyString(), any(Object[].class))).thenAnswer(inv -> { + Object[] all = inv.getArguments(); + for (int i = 1; i < all.length; i++) { + if (all[i] instanceof Object[] arr) { + for (Object x : arr) { + bound.add(x); + } + } else { + bound.add(all[i]); + } + } + return 1; + }); + + ResponseEntity> resp = + c.upload(file, "oa_newsmanage", "4028803441ba7914014249d52dfa39bb"); + + assertEquals(0, resp.getBody().get("status")); + assertEquals("OA_NEWSMANAGE", bound.get(1), "tableName 入库前大写"); + String businesskey = (String) bound.get(2); + assertEquals(36, businesskey.length(), "businesskey 右补白到 36 位(保真层 CHAR(36) 主键语义)"); + assertEquals("4028803441ba7914014249d52dfa39bb", businesskey.trim(), "去白后等于原业务键"); + } } diff --git a/platform-metadata/src/test/java/com/eip4/platform/metadata/web/FlowControllerTest.java b/platform-metadata/src/test/java/com/eip4/platform/metadata/web/FlowControllerTest.java index bf7b462..333a951 100644 --- a/platform-metadata/src/test/java/com/eip4/platform/metadata/web/FlowControllerTest.java +++ b/platform-metadata/src/test/java/com/eip4/platform/metadata/web/FlowControllerTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; 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.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -203,6 +204,127 @@ class FlowControllerTest { assertEquals("姓名u3", owner.get("_label")); } + @Test + @DisplayName("4c. load 响应附件列(大写 SYS_DOC_ID/FILENAME) → 归一为 amis input-file 契约 {id,value,name,url,sizeKb}") + @SuppressWarnings("unchecked") + void postLoadNormalizesAttachmentContract() { + String flowId = "OA_NEWSMANAGE_LOAD"; + Map doc1 = new LinkedHashMap<>(); + doc1.put("SYS_DOC_ID", "doc-1 "); // 末尾 CHAR 补白,归一时应 trim + doc1.put("FILENAME", "图片1.jpg"); + doc1.put("FILESIZE", 43000); + Map record = new LinkedHashMap<>(); + record.put("TITLE", "测试"); + record.put("DOCUMENT", new ArrayList<>(List.of(doc1))); + Map output = new LinkedHashMap<>(); + output.put("result", record); + + FlowExcuteService engine = mock(FlowExcuteService.class); + when(engine.excute(any(), any(), eq(flowId))).thenReturn(output); + FlowController controller = new FlowController(engine, resolverReturning(flowId, namedHit())); + + ResponseEntity> resp = controller.executePost(flowId, null, new HashMap<>()); + Map data = (Map) resp.getBody().get("data"); + Map loaded = (Map) data.get("result"); + List> docs = (List>) loaded.get("DOCUMENT"); + assertEquals(1, docs.size()); + Map f = docs.get(0); + assertEquals("doc-1", f.get("id"), "trim CHAR 补白"); + assertEquals("doc-1", f.get("value"), "提交值=sys_doc id"); + assertEquals("图片1.jpg", f.get("name")); + assertEquals("/api/file/doc-1", f.get("url")); + assertEquals(42L, f.get("sizeKb"), "ceil(43000/1024)=42"); + } + + @Test + @DisplayName("4d. 写流附件字段归一:amis 对象数组 → [{SYS_DOC_ID}](保真层 updateAttachments 契约,防 ClassCast/重复插入)") + @SuppressWarnings("unchecked") + void postWriteNormalizesAttachmentToLegacyList() { + String flowId = "OA_NEWSMANAGE_UPDATE"; + FlowExcuteService engine = mock(FlowExcuteService.class); + ArgumentCaptor> mapCap = ArgumentCaptor.forClass(Map.class); + when(engine.excute(mapCap.capture(), any(), eq(flowId))).thenReturn(new LinkedHashMap<>()); + FlowController controller = new FlowController(engine, resolverReturning(flowId, namedHit())); + + Map doc1 = new LinkedHashMap<>(); + doc1.put("id", "d1"); + doc1.put("value", "d1"); + doc1.put("name", "a.jpg"); + doc1.put("url", "/api/file/d1"); + Map doc2 = new LinkedHashMap<>(); // 无 id/value → 回退 url 末段解析 + doc2.put("name", "b.jpg"); + doc2.put("url", "/api/file/d2"); + Map body = new LinkedHashMap<>(); + body.put("TITLE", "t"); + body.put("DOCUMENT", new ArrayList<>(List.of(doc1, doc2))); + + controller.executePost(flowId, null, body); + + Map sentToEngine = mapCap.getValue(); + List> docs = (List>) sentToEngine.get("DOCUMENT"); + assertEquals(2, docs.size()); + assertEquals("d1", docs.get(0).get("SYS_DOC_ID")); + assertEquals("d2", docs.get(1).get("SYS_DOC_ID"), "无 id 时从 url 末段解析"); + assertEquals(java.util.Set.of("SYS_DOC_ID"), docs.get(0).keySet(), "归一后仅保留 SYS_DOC_ID"); + assertEquals("t", sentToEngine.get("TITLE"), "非附件字段不动"); + } + + @Test + @DisplayName("4e. 新建流附件:从写入 map 剥离 DOCUMENT;保存后用返回新主键 UPDATE sys_doc 改挂(无孤儿、无复制)") + @SuppressWarnings("unchecked") + void postInsertRelinksAttachmentToNewPk() { + String flowId = "OA_NEWSMANAGE_ADD"; + Map result = new LinkedHashMap<>(); + result.put("OA_NEWSMANAGE_ID", "newpk-123"); + Map output = new LinkedHashMap<>(); + output.put("result", result); + FlowExcuteService engine = mock(FlowExcuteService.class); + ArgumentCaptor> mapCap = ArgumentCaptor.forClass(Map.class); + when(engine.excute(mapCap.capture(), any(), eq(flowId))).thenReturn(output); + + JdbcTemplate jdbc = mock(JdbcTemplate.class); + List upd = new ArrayList<>(); + String[] sql = new String[1]; + when(jdbc.update(any(String.class), any(Object[].class))).thenAnswer(inv -> { + sql[0] = inv.getArgument(0); + Object[] a = inv.getArguments(); + for (int i = 1; i < a.length; i++) { + if (a[i] instanceof Object[] arr) { + for (Object x : arr) { + upd.add(x); + } + } else { + upd.add(a[i]); + } + } + return 1; + }); + FlowController controller = new FlowController(engine, resolverReturning(flowId, namedWrite()), + null, null, null, null, jdbc, null); + + Map up = new LinkedHashMap<>(); + up.put("id", "local-guid"); // amis 上传后把 id 改写为本地 guid(不可用) + up.put("value", "doc-new"); // 提交值 = sys_doc id + up.put("name", "a.jpg"); + up.put("url", "/api/file/doc-new"); + Map body = new LinkedHashMap<>(); + body.put("TITLE", "t"); + body.put("DOCUMENT", new ArrayList<>(List.of(up))); + + controller.executePost(flowId, null, body); + + // 1) 发给引擎的 map 已剥掉 DOCUMENT(保真层插入路径不碰附件 → 无复制/孤儿) + assertNull(mapCap.getValue().get("DOCUMENT"), "新建时 DOCUMENT 从写入 map 剥离"); + assertEquals("t", mapCap.getValue().get("TITLE")); + // 2) 保存后改挂:UPDATE sys_doc.businesskey = 新主键(36 位补白) + assertNotNull(sql[0]); + assertTrue(sql[0].contains("UPDATE sys_doc SET businesskey"), "应改挂 sys_doc: " + sql[0]); + assertEquals(36, ((String) upd.get(0)).length(), "businesskey 右补白到 36"); + assertEquals("newpk-123", ((String) upd.get(0)).trim()); + assertEquals("OA_NEWSMANAGE", upd.get(1)); + assertEquals("doc-new", upd.get(2)); + } + @Test @DisplayName("4b. 无 JWT 上下文时,读流执行期间临时绑定 ADMIN UserSession,执行后清理") void readFlowBindsAdminUserSessionWhenMissing() {