Merge feat/report-export-buttons: 报表查看器 PDF/Excel 导出下载入口
Some checks failed
ci / build-test-parity (push) Has been cancelled

查看器 filter.actions(有查询条件)/headerToolbar(无)加导出 PDF/Excel 按钮,指向 /api/report/render
携当前查询参;端点对 pdf/xls 回 Content-Disposition: attachment + RFC5987 中文文件名(view_template.name),
html 仍 inline。code review 通过(注入中和+RFC5987 收口)。浏览器+curl 真验下载保真。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-25 23:01:56 +08:00
5 changed files with 241 additions and 5 deletions

View File

@@ -3867,12 +3867,35 @@ public class TemplateToAmisConverter {
crud.put("type", "crud"); crud.put("type", "crud");
crud.put("api", "/api/report/frame/" + tid); crud.put("api", "/api/report/frame/" + tid);
crud.put("syncLocation", false); crud.put("syncLocation", false);
crud.put("headerToolbar", new ArrayList<>()); // 报表查看器无新增/批量按钮 List<Object> headerToolbar = new ArrayList<>(); // 报表查看器无新增/批量按钮(导出按钮见下)
crud.put("headerToolbar", headerToolbar);
crud.put("footerToolbar", new ArrayList<>()); // 单行信封,无分页条 crud.put("footerToolbar", new ArrayList<>()); // 单行信封,无分页条
crud.put("affixHeader", false); crud.put("affixHeader", false);
// 导出 PDF/Excel:URL 指向 /api/report/render(端点对 pdf/xls 回 attachment 触发下载),带查询参 ${字段}。
// 有查询条件 → 落 crud.filter.actions(与提交/重置同排,读 filter 实时值,已实测可用);
// 无查询条件 → 落 headerToolbar(无参,导出全量报表)。
String exportParams = buildReportExportParams(filter);
List<Map<String, Object>> exportBtns = List.of(
reportExportButton("导出PDF", "/api/report/render/" + tid + "?format=pdf" + exportParams),
reportExportButton("导出Excel", "/api/report/render/" + tid + "?format=xls" + exportParams));
if (filter != null) { if (filter != null) {
crud.put("filter", filter); crud.put("filter", filter);
crud.put("initFetch", false); // 有查询条件 → 等用户「查询」再加载 crud.put("initFetch", false); // 有查询条件 → 等用户「查询」再加载
List<Map<String, Object>> actions = new ArrayList<>();
Map<String, Object> submit = new LinkedHashMap<>();
submit.put("type", "submit");
submit.put("label", "查询");
submit.put("level", "primary");
Map<String, Object> reset = new LinkedHashMap<>();
reset.put("type", "reset");
reset.put("label", "重置");
actions.add(submit);
actions.add(reset);
actions.addAll(exportBtns);
filter.put("actions", actions);
} else {
headerToolbar.addAll(exportBtns);
} }
// 唯一的 html 列:把回显的 __url 渲成 iframe(JOR HTML 文档独立加载,CSS 隔离保真) // 唯一的 html 列:把回显的 __url 渲成 iframe(JOR HTML 文档独立加载,CSS 隔离保真)
Map<String, Object> col = new LinkedHashMap<>(); Map<String, Object> col = new LinkedHashMap<>();
@@ -3885,11 +3908,43 @@ public class TemplateToAmisConverter {
crud.put("columns", cols); crud.put("columns", cols);
result.note("report 含 JOR 套打版式(" + jorLen + " 字符) → 报表查看器:crud.filter 查询条件 + html 列 iframe 加载 " result.note("report 含 JOR 套打版式(" + jorLen + " 字符) → 报表查看器:crud.filter 查询条件 + html 列 iframe 加载 "
+ "/api/report/render/" + tid + "(jatools 引擎渲染保真版式;图表 ischart 亦由引擎 jfreechart 出图)"); + "/api/report/render/" + tid + "(jatools 引擎渲染保真版式;图表 ischart 亦由引擎 jfreechart 出图)"
+ ";导出 PDF/Excel 按钮指向 render 端点(attachment 下载)");
noteScripts(report, result); noteScripts(report, result);
return page(title, crud); return page(title, crud);
} }
/**
* 报表导出 URL 的查询参串:filter 各字段 → {@code &NAME=${NAME}}(amis 运行时插值为当前 filter 值,
* 与查看器 iframe 同一份查询条件)。无 filter / 无字段 → 空串(导全量报表)。
*/
@SuppressWarnings("unchecked")
private static String buildReportExportParams(Map<String, Object> filter) {
if (filter == null || !(filter.get("body") instanceof List<?> items)) {
return "";
}
StringBuilder sb = new StringBuilder();
for (Object it : items) {
// name 为元数据字段名(UiTypeMapper IDENT,形如 [A-Za-z_]\w*,无 URL 特殊字符),裸拼安全;
// ${name} 须保持字面量(amis 点击时插值为当前 filter 值,值由 amis 自行编码),故此处不可 URL 编码。
if (it instanceof Map<?, ?> m && m.get("name") instanceof String n && !n.isBlank()) {
sb.append('&').append(n).append("=${").append(n).append('}');
}
}
return sb.toString();
}
/** 报表导出按钮:{@code url} 动作 + {@code blank}(新标签打开;render 端点对 pdf/xls 回 attachment 触发下载)。 */
private static Map<String, Object> reportExportButton(String label, String url) {
Map<String, Object> btn = new LinkedHashMap<>();
btn.put("type", "button");
btn.put("label", label);
btn.put("actionType", "url");
btn.put("url", url);
btn.put("blank", true);
return btn;
}
// ────────────────────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────────────────────
// group(分组容器)—— 子模板跨引用 // group(分组容器)—— 子模板跨引用
// ────────────────────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────────────────────

View File

@@ -2771,6 +2771,57 @@ class TemplateToAmisConverterTest {
assertTrue(((String) crud.get("api")).startsWith("/api/flow/PM_X_SEARCH"), "api=" + crud.get("api")); assertTrue(((String) crud.get("api")).startsWith("/api/flow/PM_X_SEARCH"), "api=" + crud.get("api"));
} }
@Test
@SuppressWarnings("unchecked")
void report_viewer_导出按钮落filter_actions带查询参数() {
// 导出 PDF/Excel 落 crud.filter.actions(与查询/重置同排,读 filter 实时值);URL 指向 render 端点 + format + ${字段}
String xml = "<report title='收付款' entityid='e1'>"
+ "<display><field name='A' text='A'/></display>"
+ "<search selectservice='S'>"
+ "<field name='PROJECTID' label='工程名称' uitype='SelectDialog' dialogid='d1' required='true'/>"
+ "</search>"
+ "<reportfile><![CDATA[<jatools>版式占位非空版式占位</jatools>]]></reportfile></report>";
ConversionResult r = converter.convertGraded(xml, "TID-1", "收付款", new ArrayList<>(), noPage);
Map<String, Object> crud = body(r.getSchema());
Map<String, Object> filter = (Map<String, Object>) crud.get("filter");
List<Map<String, Object>> actions = (List<Map<String, Object>>) filter.get("actions");
List<String> labels = actions.stream().map(a -> (String) a.get("label")).toList();
assertTrue(labels.contains("查询") && labels.contains("导出PDF") && labels.contains("导出Excel"),
"actions 应含 查询/导出PDF/导出Excel: " + labels);
// 查询 = submit(触发 crud 重载报表)
assertTrue(actions.stream().anyMatch(a -> "submit".equals(a.get("type")) && "查询".equals(a.get("label"))));
// 导出 PDF:url 动作,指向 render 端点 + format=pdf + 带 filter 字段占位
Map<String, Object> pdf = actions.stream()
.filter(a -> "导出PDF".equals(a.get("label"))).findFirst().orElseThrow();
assertEquals("url", pdf.get("actionType"));
assertEquals(Boolean.TRUE, pdf.get("blank"));
String url = (String) pdf.get("url");
assertTrue(url.startsWith("/api/report/render/TID-1?format=pdf"), url);
assertTrue(url.contains("PROJECTID=${PROJECTID}"), url);
// 导出 Excel:format=xls
Map<String, Object> xls = actions.stream()
.filter(a -> "导出Excel".equals(a.get("label"))).findFirst().orElseThrow();
assertTrue(((String) xls.get("url")).contains("format=xls"), (String) xls.get("url"));
}
@Test
@SuppressWarnings("unchecked")
void report_viewer_无查询条件导出按钮落headerToolbar无参() {
// 无 <search> → filter=null → 导出按钮落 headerToolbar,URL 无查询参(导全量报表)
String xml = "<report title='全量报表' entityid='e1'>"
+ "<display><field name='A' text='A'/></display>"
+ "<reportfile><![CDATA[<jatools>版式占位非空版式占位</jatools>]]></reportfile></report>";
ConversionResult r = converter.convertGraded(xml, "TID-2", "全量报表", new ArrayList<>(), noPage);
Map<String, Object> crud = body(r.getSchema());
assertNull(crud.get("filter"), "无查询条件 filter 应为 null");
List<Map<String, Object>> tb = (List<Map<String, Object>>) crud.get("headerToolbar");
List<String> labels = tb.stream().map(a -> (String) a.get("label")).toList();
assertTrue(labels.contains("导出PDF") && labels.contains("导出Excel"), "headerToolbar 应含导出按钮: " + labels);
Map<String, Object> pdf = tb.stream()
.filter(a -> "导出PDF".equals(a.get("label"))).findFirst().orElseThrow();
assertEquals("/api/report/render/TID-2?format=pdf", pdf.get("url"), "无查询条件 URL 应无查询参");
}
@Test @Test
void report_图表降级() { void report_图表降级() {
String xml = "<report title='图表' entityid='e1'>" String xml = "<report title='图表' entityid='e1'>"

View File

@@ -13,6 +13,7 @@ import java.util.Set;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@@ -94,9 +95,17 @@ public class ReportController {
"读取/渲染报表模板失败: " + e.getMessage(), e); "读取/渲染报表模板失败: " + e.getMessage(), e);
} }
return ResponseEntity.ok() ResponseEntity.BodyBuilder rb = ResponseEntity.ok()
.contentType(MediaType.parseMediaType(fmt.contentType())) .contentType(MediaType.parseMediaType(fmt.contentType()));
.body(body); // pdf/xls(导出按钮)→ attachment 触发下载,文件名取报表名;html(查看器 iframe)→ inline 内嵌。
if (fmt != ReportService.Format.HTML) {
String reportName = templateRepository.loadReportName(templateId);
String disposition = contentDisposition(fmt, reportName, templateId);
if (disposition != null) {
rb.header(HttpHeaders.CONTENT_DISPOSITION, disposition);
}
}
return rb.body(body);
} }
/** /**
@@ -176,6 +185,46 @@ public class ReportController {
return env; return env;
} }
/**
* 构造导出下载的 {@code Content-Disposition} 头值。
* <ul>
* <li>{@code html} → {@code null}(查看器 iframe 内嵌,inline);</li>
* <li>{@code pdf}/{@code xls} → {@code attachment},中文报表名经 RFC5987 {@code filename*=UTF-8''} 编码,
* ASCII 回退 {@code filename="<templateId>.<ext>"}(UUID 安全,老客户端兜底)。</li>
* </ul>
* 文件名经 {@link #sanitizeFilename} 净化(剔除 CRLF/引号/斜杠/控制符),杜绝响应头注入与属性逃逸。纯函数,便于单测。
*/
static String contentDisposition(ReportService.Format fmt, String reportName, String templateId) {
if (fmt == ReportService.Format.HTML) {
return null;
}
String ext = fmt == ReportService.Format.PDF ? "pdf" : "xls";
String base = sanitizeFilename(reportName);
if (base.isEmpty()) {
base = sanitizeFilename(templateId);
}
if (base.isEmpty()) {
base = "report";
}
// RFC5987 ext-value:URLEncoder 是 x-www-form-urlencoded(空格→+,且保留 * 不编码),
// 修正成 RFC5987 attr-char 口径——空格→%20、* →%2A(. - _ 本就是合法 attr-char)。
String encoded = URLEncoder.encode(base + "." + ext, StandardCharsets.UTF_8)
.replace("+", "%20").replace("*", "%2A");
String ascii = sanitizeFilename(templateId == null ? "" : templateId.replaceAll("[^\\x20-\\x7E]", "_"));
if (ascii.isEmpty()) {
ascii = "report";
}
return "attachment; filename=\"" + ascii + "." + ext + "\"; filename*=UTF-8''" + encoded;
}
/** 文件名净化:剔除 CR/LF/引号/反斜杠/正斜杠/控制字符,杜绝响应头注入(CRLF 拆头)与路径/属性逃逸。 */
private static String sanitizeFilename(String s) {
if (s == null) {
return "";
}
return s.replaceAll("[\\r\\n\"\\\\/\\x00-\\x1F\\x7F]", "").trim();
}
/** templateId / ?tpl 解析为模板文件路径。 */ /** templateId / ?tpl 解析为模板文件路径。 */
private Path resolveTemplate(String templateId, String tplPath) { private Path resolveTemplate(String templateId, String tplPath) {
Path xml; Path xml;

View File

@@ -30,6 +30,10 @@ public class ReportTemplateRepository {
private static final String LOAD_SQL = private static final String LOAD_SQL =
"SELECT xml::text FROM eip3.view_template WHERE trim(view_template_id) = ? AND type = 200"; "SELECT xml::text FROM eip3.view_template WHERE trim(view_template_id) = ? AND type = 200";
/** 报表名(view_template.name),供导出文件名;限定 type=200。 */
private static final String NAME_SQL =
"SELECT name FROM eip3.view_template WHERE trim(view_template_id) = ? AND type = 200";
private final JdbcTemplate jdbcTemplate; private final JdbcTemplate jdbcTemplate;
public ReportTemplateRepository(JdbcTemplate jdbcTemplate) { public ReportTemplateRepository(JdbcTemplate jdbcTemplate) {
@@ -61,6 +65,25 @@ public class ReportTemplateRepository {
return jor; return jor;
} }
/**
* 报表名(view_template.name),供导出 PDF/XLS 的文件名。最佳努力:找不到/异常返回 {@code null}
* (导出端点回退用 templateId 作文件名,绝不因取名失败影响渲染)。
*/
public String loadReportName(String templateId) {
String id = templateId == null ? "" : templateId.trim();
try {
List<String> rows = jdbcTemplate.queryForList(NAME_SQL, String.class, id);
if (rows.isEmpty()) {
return null;
}
String name = rows.get(0);
return name == null || name.isBlank() ? null : name.trim();
} catch (RuntimeException e) {
log.debug("取报表名失败 templateId={} : {}", id, e.getMessage());
return null;
}
}
/** /**
* 从 {@code <report>} 外壳里抽出 {@code <reportfile>} 内层 JOR 文档。 * 从 {@code <report>} 外壳里抽出 {@code <reportfile>} 内层 JOR 文档。
* *

View File

@@ -0,0 +1,58 @@
package com.eip4.platform.report;
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 org.junit.jupiter.api.Test;
/**
* 报表导出下载头(Content-Disposition)的纯逻辑单测。
*
* <p>查看器 iframe 用 {@code format=html}(inline,内嵌渲染);导出按钮用 {@code format=pdf|xls}
* → 端点须回 {@code Content-Disposition: attachment} 触发下载,文件名取报表名(中文经 RFC5987
* {@code filename*=UTF-8''} 编码),ASCII 回退用 templateId(UUID,老客户端兜底)。html 不设此头。
*/
class ReportDownloadTest {
@Test
void html_inline_no_disposition() {
assertNull(ReportController.contentDisposition(ReportService.Format.HTML, "在建项目收付款信息表", "tid-1"));
}
@Test
void pdf_attachment_with_rfc5987_cjk_filename() {
String cd = ReportController.contentDisposition(ReportService.Format.PDF, "在建项目收付款信息表", "5558497f-id");
assertTrue(cd.startsWith("attachment;"), cd);
// RFC5987 UTF-8 编码的中文名 + .pdf
assertTrue(cd.contains("filename*=UTF-8''"), cd);
assertTrue(cd.contains("%E5%9C%A8%E5%BB%BA"), cd); // 「在建」UTF-8 %xx
assertTrue(cd.contains(".pdf"), cd);
// ASCII 回退用 templateId(UUID 安全)
assertTrue(cd.contains("filename=\"5558497f-id.pdf\""), cd);
}
@Test
void xls_uses_xls_extension() {
String cd = ReportController.contentDisposition(ReportService.Format.XLS, "报表", "tid");
assertTrue(cd.contains(".xls"), cd);
assertFalse(cd.contains(".pdf"), cd);
}
@Test
void header_injection_neutralized() {
// 报表名含 CRLF/引号/路径分隔 → 必须剔除,杜绝响应头注入(CRLF 拆头)与 filename 属性逃逸
String evil = "a\r\nSet-Cookie: x=1\"/../b";
String cd = ReportController.contentDisposition(ReportService.Format.PDF, evil, "tid");
assertFalse(cd.contains("\r"), "不得含 CR: " + cd);
assertFalse(cd.contains("\n"), "不得含 LF: " + cd);
// ASCII filename 用 templateId(UUID),不被恶意报表名污染、无逃逸引号
assertTrue(cd.contains("filename=\"tid.pdf\""), cd);
}
@Test
void blank_name_falls_back_to_templateId() {
String cd = ReportController.contentDisposition(ReportService.Format.PDF, " ", "tid-xyz");
assertTrue(cd.contains("tid-xyz.pdf"), cd);
}
}