feat(report): JOR(jatools)报表引擎重宿主 — platform-report 后端 + /api/report 端点

EIP3 真报表=jatools JOR 套打模板(非 amis 表格)。本批次把报表引擎重宿主进 EIP4
(复用客户已持有的预编译引擎 jar,非移植 900 源文件;非重建引擎)。Phase 1 后端完成+真验。

- platform-report 模块:18 个预编译 jar(jatools 引擎 + 改造版 BeanShell + itext/jxl/
  jsqlparser/jfreechart/barcode4j/zxing/…)经项目内 local-repo(install-libs.sh)正常依赖,
  打进 fat jar(BOOT-INF/lib 已确认,非 system scope)。
- ReportService:走 jatools.engine.ReportJob(查询参数 setParameter→declareExternalVariables
  →SQL ${PARAM});headless(java.awt.headless)。三格式 HTML/PDF/XLS。
- JatoolsConfig:把 EIP4 spring.datasource 注入引擎 System2.properties(无 CWD 文件依赖)+
  注册 CJK 字体供 PDF。
- ReportController:GET /api/report/render/{templateId}?format=html|pdf|xls&<查询参数>;
  按 templateId 从 view_template(type=200)的 <reportfile> CDATA 取 JOR 渲染;?tpl= dev 覆盖。
- SecurityConfig:X-Frame-Options DENY→SAMEORIGIN(报表查看器同源 iframe 内嵌;生产 nginx 单源)。

真验:全 reactor mvn clean install 绿(0 失败);8093 端点 GET /api/report/render/{id} 三格式
HTTP 200(HTML 48K/PDF 106K/XLS 21K);查询参数 PROJECTID 流进 SQL 48×;浏览器内 amis 菜单页
(查询表单+iframe 查看器)渲染出 JOR 套打报表(在建工程项目收付款信息表,公式列/分组小计/签字栏)。

边界:Phase 2 前端「报表页 body 换查看器」当前以单页 sys_page_schema 运行态改动演示(非本提交代码);
铺到全部 339 张 type=200 报表页 = Phase 3(转换器侧生成查看器 body)。数据保真须对完整客户库验证
(eip4dev 为部分 dev 库,部分报表源表缺)。design 见 docs/plans/2026-06-25-报表迁移-JOR引擎重宿主-design.md。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-25 17:56:50 +08:00
parent 2ff826505f
commit 702b5e9229
100 changed files with 1181 additions and 0 deletions

View File

@@ -0,0 +1,143 @@
package com.eip4.platform.report;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.DefaultFontMapper;
import jatools.engine.System2;
/**
* 把 jatools 引擎所需配置在启动时注入 {@code jatools.engine.System2}。
*
* <p>背景:引擎通过 {@code System2.getProperty(name)} 读配置 —— 其实现是:若静态字段
* {@code System2.properties} 为 null,则按 {@code 工作目录/[WEB-INF/]jatools.properties}
* 用 {@code FileInputStream} 加载(依赖进程 CWD,脆弱)。{@code System2.properties} 是
* <b>public static</b> 字段,故这里直接构造一份 {@link java.util.PropertyResourceBundle}
* 赋值给它,彻底绕开文件加载。
*
* <p>注入的键:
* <ul>
* <li>{@code timeformat} / {@code dayformat} / {@code company} —— 系统变量(NOW/TODAY/COMPANY)</li>
* <li>{@code font.dirs} —— 字体目录(加 macOS 与 Linux 路径,服务端版式/中文保真)</li>
* <li>{@code DBJdbcUrl} / {@code DBUser} / {@code DBPassword} —— 报表模板 {@code <Connection>}
* 里的 {@code ${property("DBJdbcUrl")}} 等,必须解析到 EIP4 数据源</li>
* </ul>
* DB 三键默认取 EIP4 的 {@code spring.datasource.*};本地验证默认指向 dev 库
* {@code jdbc:postgresql://localhost:5433/eip4dev?currentSchema=eip3}(用户 zhengwr,无密码)。
*/
@Component
public class JatoolsConfig {
private static final Logger log = LoggerFactory.getLogger(JatoolsConfig.class);
@Value("${spring.datasource.url:jdbc:postgresql://localhost:5433/eip4dev?currentSchema=eip3}")
private String jdbcUrl;
@Value("${spring.datasource.username:zhengwr}")
private String dbUser;
@Value("${spring.datasource.password:}")
private String dbPassword;
@Value("${eip4.report.company:EIP4}")
private String company;
/**
* PDF 导出兜底字体(CJK 保真)候选路径,按序探测,取首个可加载者注册为
* iText {@code DefaultFontMapper.defaultFont}。覆盖 macOS(本地验证)与常见 Linux 路径。
* {@code .ttc} 字体集需 {@code ,索引} 后缀(如 {@code ,0})。
*/
private static final String[] PDF_FALLBACK_FONTS = {
// macOS
"/System/Library/Fonts/STHeiti Light.ttc,0",
"/System/Library/Fonts/Supplemental/Songti.ttc,0",
"/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
"/Library/Fonts/Arial Unicode.ttf",
// Linux(常见中文字体包)
"/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc,0",
"/usr/share/fonts/wenquanyi/wqy-zenhei/wqy-zenhei.ttc,0",
"/usr/share/fonts/truetype/arphic/uming.ttc,0",
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc,0",
"/usr/share/fonts/google-noto-cjk/NotoSansCJK-Regular.ttc,0"
};
private volatile boolean initialized = false;
@PostConstruct
public synchronized void init() {
if (initialized) {
return;
}
Properties p = new Properties();
// 日期/时间格式(对齐 EIP3 jatools.properties)
p.setProperty("timeformat", "hh:mm:ss");
p.setProperty("dayformat", "yyyy-MM-dd");
p.setProperty("company", company == null ? "EIP4" : company);
// 字体目录:覆盖 macOS(本地验证)与 Linux(生产部署),服务端 Graphics2D 版式/中文保真
p.setProperty("font.dirs",
"/System/Library/Fonts;/Library/Fonts;"
+ "/usr/share/fonts;/usr/share/fonts/truetype;/usr/local/share/fonts");
// 报表模板 <Connection> 解析到 EIP4 数据源
p.setProperty("DBJdbcUrl", jdbcUrl == null ? "" : jdbcUrl);
p.setProperty("DBUser", dbUser == null ? "" : dbUser);
p.setProperty("DBPassword", dbPassword == null ? "" : dbPassword);
try {
// PropertyResourceBundle 用 ISO-8859-1 读字节流;键值均 ASCII,安全。
ByteArrayOutputStream baos = new ByteArrayOutputStream();
p.store(baos, "EIP4 injected jatools config");
System2.properties = new java.util.PropertyResourceBundle(
new ByteArrayInputStream(baos.toByteArray()));
log.info("jatools 配置已注入 System2.properties: DBJdbcUrl={}, DBUser={}", jdbcUrl, dbUser);
} catch (Exception e) {
throw new IllegalStateException("注入 jatools System2 配置失败: " + e.getMessage(), e);
}
registerPdfFallbackFont();
initialized = true;
}
/**
* PDF 导出兜底字体注册。EIP3 引擎 {@code _Job.printAsPDF} 用 iText 无参 {@code createGraphics}
* (空 {@code DefaultFontMapper}),AWT 逻辑字体(Dialog 等)无映射会抛"既找不到字体...也找不到默认字体"。
* iText {@code DefaultFontMapper.awtToPdf} 在找不到具名字体时会回落到 {@code defaultFont}(静态字段),
* 故注册一个 CJK TrueType 作 defaultFont 即可让 PDF 不崩,并尽量保中文。最佳努力,失败仅告警。
*/
private void registerPdfFallbackFont() {
for (String spec : PDF_FALLBACK_FONTS) {
String path = spec.contains(",") ? spec.substring(0, spec.indexOf(',')) : spec;
if (!new java.io.File(path).isFile()) {
continue;
}
try {
BaseFont bf = BaseFont.createFont(spec, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
DefaultFontMapper.defaultFont = bf;
log.info("PDF 兜底字体已注册(DefaultFontMapper.defaultFont): {}", spec);
return;
} catch (Exception e) {
log.debug("PDF 兜底字体加载失败,跳过: {} ({})", spec, e.getMessage());
}
}
log.warn("未找到可用 CJK 兜底字体,PDF 导出可能因字体缺失失败;HTML/XLS 不受影响。候选: {}",
String.join(", ", PDF_FALLBACK_FONTS));
}
/** 供 {@link ReportService} 构造时确保配置已就绪(@PostConstruct 顺序保险)。 */
public void ensureInitialized() {
if (!initialized) {
init();
}
}
}

View File

@@ -0,0 +1,130 @@
package com.eip4.platform.report;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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 org.springframework.web.server.ResponseStatusException;
import jakarta.servlet.http.HttpServletRequest;
/**
* 报表渲染端点。
*
* <p>{@code GET /api/report/render/{templateId}?format=html|pdf|xls&<查询参数...>}
* → 把 {@code templateId} 解析为 JOR 模板 .xml → {@link ReportService#render} → 返回
* 渲染产物(HTML/PDF/XLS)。除 {@code format}/{@code tpl} 外的全部查询参数原样作为报表参数
* 透传(报表 SQL 里的 {@code ${PARAM}} 据此绑定)。
*
* <p>模板解析(v1):
* <ul>
* <li>{@code ?tpl=<绝对路径>} —— 验证/演示用,直接指定 .xml 绝对路径(仅 dev/local 便利)。</li>
* <li>否则把 {@code templateId} 当作相对 {@code eip4.report.templates-dir} 的路径解析,
* 默认基目录指向 EIP3 report 根。Phase 3 改为查 {@code sys_report_template} 表。</li>
* </ul>
*
* <p>注:不与既有 {@code /api/report/menu-tree}(platform-metadata)冲突 —— 该控制器只占
* {@code /api/report/render/**}。安全:这是 {@code /api/**} 端点,在 dev/local/ci 宽松链下放行,
* 严格 profile 下走 {@code authenticated()},沿用既有安全模型,无需改 SecurityConfig。
*/
@RestController
public class ReportController {
private static final Logger log = LoggerFactory.getLogger(ReportController.class);
private final ReportService reportService;
private final ReportTemplateRepository templateRepository;
@Value("${eip4.report.templates-dir:/Users/zhengwr/workspace/EIP-3.0}")
private String templatesDir;
public ReportController(ReportService reportService,
ReportTemplateRepository templateRepository) {
this.reportService = reportService;
this.templateRepository = templateRepository;
}
@GetMapping("/api/report/render/{templateId}")
public ResponseEntity<byte[]> render(@PathVariable("templateId") String templateId,
@RequestParam(value = "format", required = false, defaultValue = "html") String format,
@RequestParam(value = "tpl", required = false) String tplPath,
HttpServletRequest request) {
Map<String, String> params = collectReportParams(request);
ReportService.Format fmt = ReportService.Format.parse(format);
byte[] body;
try {
if (tplPath != null && !tplPath.isBlank()) {
// dev/演示覆盖:直接渲染指定 .xml 文件(可为 JOR 文档或 view_template 外壳)。
Path xml = resolveTemplate(templateId, tplPath);
try (InputStream is = Files.newInputStream(xml)) {
body = reportService.render(is, params, format);
}
} else {
// 标准路径:按 templateId 从 view_template(type=200) 取 JOR 文档并渲染。
String jorXml = templateRepository.loadJorXml(templateId);
body = reportService.render(jorXml, params, format);
}
} catch (ReportTemplateRepository.ReportTemplateNotFoundException e) {
log.warn("报表模板未找到 templateId={} : {}", templateId, e.getMessage());
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage(), e);
} catch (ReportService.ReportRenderException e) {
log.warn("报表渲染失败 templateId={} tpl={} : {}", templateId, tplPath, e.getMessage());
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage(), e);
} catch (ResponseStatusException e) {
throw e;
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR,
"读取/渲染报表模板失败: " + e.getMessage(), e);
}
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(fmt.contentType()))
.body(body);
}
/** templateId / ?tpl 解析为模板文件路径。 */
private Path resolveTemplate(String templateId, String tplPath) {
Path xml;
if (tplPath != null && !tplPath.isBlank()) {
xml = Path.of(tplPath);
} else {
String rel = templateId;
if (!rel.toLowerCase().endsWith(".xml")) {
rel = rel + ".xml";
}
xml = Path.of(templatesDir).resolve(rel);
}
if (!Files.isRegularFile(xml)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND,
"报表模板未找到: " + xml);
}
return xml;
}
/** 除 format/tpl 外的查询参数 = 报表参数(只取第一个值)。 */
private Map<String, String> collectReportParams(HttpServletRequest request) {
Map<String, String> params = new LinkedHashMap<>();
request.getParameterMap().forEach((name, values) -> {
if ("format".equals(name) || "tpl".equals(name)) {
return;
}
if (values != null && values.length > 0) {
params.put(name, values[0]);
}
});
return params;
}
}

View File

@@ -0,0 +1,154 @@
package com.eip4.platform.report;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import jatools.ReportDocument;
import jatools.engine.ReportJob;
import jatools.io.FileResourceOutputFactory;
import jatools.io.ResourceOutputFactory;
/**
* EIP3 JOR(jatools)报表引擎的 headless 渲染服务。
*
* <p>用预编译成品 {@code jatools.jar} 把 JOR 套打模板(.xml)在无界面环境下渲染为
* HTML / PDF / XLS。复刻 EIP3 {@code jatools.server.ReportExporter} 的纯引擎核心,
* 去掉所有 {@code com.dsasp.*} 应用胶水(SysConfig/POJOCRUDService/UserSession 等)。
*
* <p>渲染通道 = {@code jatools.engine.ReportJob}(而非 {@code LocalReportJob}):
* {@code ReportJob} 的 print 路径内部经 {@code ReportPrinter.declareExternalVariables}
* 把 {@link ReportJob#setParameter} 设入的查询参数声明为脚本变量,报表 SQL 里的
* {@code ${PARAM}} / {@code ${iif(PARAM,...)}} 由此绑定。{@code LocalReportJob} 不做这一步,
* 故必须走 {@code ReportJob}。
*
* <p>jatools 配置(timeformat / dayformat / company / font.dirs / DB 连接键)由
* {@link JatoolsConfig} 在 Bean 构造时注入 {@code jatools.engine.System2.properties}。
*/
@Service
public class ReportService {
private static final Logger log = LoggerFactory.getLogger(ReportService.class);
static {
// 引擎大量触及 java.awt(版式度量/图表/字体),无显示环境必须 headless。
System.setProperty("java.awt.headless", "true");
}
public ReportService(JatoolsConfig jatoolsConfig) {
// 触发 JatoolsConfig 构造(@PostConstruct 注入 System2 配置)先于任何渲染。
jatoolsConfig.ensureInitialized();
}
/** 支持的导出格式。 */
public enum Format {
HTML, PDF, XLS;
static Format parse(String s) {
if (s == null || s.isBlank()) {
return HTML;
}
return switch (s.trim().toLowerCase()) {
case "html", "dhtml", "htm" -> HTML;
case "pdf" -> PDF;
case "xls", "xlsx", "excel" -> XLS;
default -> throw new IllegalArgumentException("不支持的报表格式: " + s);
};
}
public String contentType() {
return switch (this) {
case HTML -> "text/html;charset=UTF-8";
case PDF -> "application/pdf";
case XLS -> "application/vnd.ms-excel";
};
}
}
/**
* 渲染一张 JOR 报表模板。
*
* @param templateXml 模板 XML 输入流(JOR .xml,如 EIP3 report 目录里的套打模板)
* @param params 查询参数(name → value);报表 SQL 中的 {@code ${PARAM}} 由此绑定
* @param format {@code html} / {@code pdf} / {@code xls}(大小写不敏感)
* @return 渲染产物字节(HTML 为 UTF-8 文本字节)
*/
/**
* 渲染一张 JOR 报表模板(从 JOR XML 字符串)。等同 {@link #render(InputStream, Map, String)},
* 便于直接喂从 DB({@code view_template}) 抽出的 JOR 文档。
*
* @param jorXml JOR 文档文本(以 {@code <jatools}/{@code <?xml ...><jatools} 开头)
*/
public byte[] render(String jorXml, Map<String, String> params, String format) {
return render(new ByteArrayInputStream(jorXml.getBytes(StandardCharsets.UTF_8)), params, format);
}
public byte[] render(InputStream templateXml, Map<String, String> params, String format) {
Format fmt = Format.parse(format);
File tmpDir = null;
try {
ReportDocument doc = ReportDocument.load(templateXml);
ReportJob job = new ReportJob(doc);
if (params != null) {
for (Map.Entry<String, String> e : params.entrySet()) {
if (e.getKey() != null) {
job.setParameter(e.getKey(), e.getValue());
}
}
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
switch (fmt) {
case HTML -> {
// HTML 内嵌图片等资源经 ResourceOutputFactory 落到临时目录(替代 servlet 会话沉淀)。
tmpDir = Files.createTempDirectory("eip4-report-").toFile();
ResourceOutputFactory imp = new FileResourceOutputFactory(tmpDir);
OutputStreamWriter writer = new OutputStreamWriter(out, StandardCharsets.UTF_8);
job.printAsDHTML(imp, writer);
writer.flush();
}
case PDF -> job.printAsPDF(out);
case XLS -> job.printAsXLS(out);
}
return out.toByteArray();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new ReportRenderException("报表渲染失败 (format=" + fmt + "): " + e.getMessage(), e);
} finally {
deleteQuietly(tmpDir);
}
}
private static void deleteQuietly(File dir) {
if (dir == null || !dir.exists()) {
return;
}
File[] kids = dir.listFiles();
if (kids != null) {
for (File k : kids) {
deleteQuietly(k);
}
}
if (!dir.delete()) {
log.debug("临时目录清理失败(忽略): {}", dir);
}
}
/** 报表渲染异常(包裹 jatools 引擎抛出的受检异常)。 */
public static class ReportRenderException extends RuntimeException {
public ReportRenderException(String message, Throwable cause) {
super(message, cause);
}
}
}

View File

@@ -0,0 +1,100 @@
package com.eip4.platform.report;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
/**
* 按 {@code templateId} 从 EIP3 {@code view_template} 表(type=200 报表)取出可渲染的 JOR 模板。
*
* <p>{@code view_template.xml}(PG xml 列)对 type=200 行的结构:
* <pre>{@code
* <report entityid=... templateid=...>
* <display><field .../>...</display> <!-- 列定义 -->
* <reportfile><![CDATA[ <jatools ...>...ReportDocument... ]]></reportfile> <!-- 真正的 JOR 文档 -->
* <field name=... uitype=.../> <!-- 查询条件字段 -->
* </report>
* }</pre>
* 本类抽取 {@code <reportfile>...</reportfile>} 内层文本(剥掉 CDATA 包裹),得到以 {@code <jatools}
* 开头、含 {@code ReportDocument} 的 JOR 文档,交给 {@link ReportService#render} 渲染。
*/
@Repository
public class ReportTemplateRepository {
private static final Logger log = LoggerFactory.getLogger(ReportTemplateRepository.class);
/** 仅取 type=200 的报表模板;schema 限定到 eip3(模板/页面表所在 schema)。 */
private static final String LOAD_SQL =
"SELECT xml::text FROM eip3.view_template WHERE trim(view_template_id) = ? AND type = 200";
private final JdbcTemplate jdbcTemplate;
public ReportTemplateRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* 按 templateId 加载并抽取 JOR 文档。
*
* @param templateId {@code view_template.view_template_id}(允许含两端空白,内部 trim)
* @return 可渲染的 JOR XML(以 {@code <jatools}/{@code <?xml ...><jatools} 开头),找不到/无 reportfile 时抛出
*/
public String loadJorXml(String templateId) {
String id = templateId == null ? "" : templateId.trim();
List<String> rows = jdbcTemplate.queryForList(LOAD_SQL, String.class, id);
if (rows.isEmpty()) {
throw new ReportTemplateNotFoundException("未找到 type=200 报表模板: view_template_id=" + id);
}
String reportXml = rows.get(0);
if (reportXml == null || reportXml.isBlank()) {
throw new ReportTemplateNotFoundException("报表模板 xml 为空: view_template_id=" + id);
}
String jor = extractReportFile(reportXml);
if (jor == null) {
throw new ReportTemplateNotFoundException(
"报表模板缺少 <reportfile> JOR 文档: view_template_id=" + id);
}
log.debug("已加载 JOR 模板 templateId={} reportXmlBytes={} jorBytes={}", id, reportXml.length(), jor.length());
return jor;
}
/**
* 从 {@code <report>} 外壳里抽出 {@code <reportfile>} 内层 JOR 文档。
*
* <p>内层通常被 {@code <![CDATA[ ... ]]>} 包裹;剥掉 CDATA 后即得以 {@code <?xml ...><jatools ...>}
* 开头的 jatools ReportDocument。无 {@code <reportfile>} 节点时返回 {@code null}。
*/
static String extractReportFile(String reportXml) {
int open = reportXml.indexOf("<reportfile");
if (open < 0) {
return null;
}
int gt = reportXml.indexOf('>', open);
if (gt < 0) {
return null;
}
int close = reportXml.indexOf("</reportfile>", gt);
if (close < 0) {
return null;
}
String inner = reportXml.substring(gt + 1, close).trim();
if (inner.startsWith("<![CDATA[")) {
inner = inner.substring("<![CDATA[".length());
if (inner.endsWith("]]>")) {
inner = inner.substring(0, inner.length() - "]]>".length());
}
inner = inner.trim();
}
return inner.isEmpty() ? null : inner;
}
/** 模板未找到 / 无法抽取 JOR 文档。 */
public static class ReportTemplateNotFoundException extends RuntimeException {
public ReportTemplateNotFoundException(String message) {
super(message);
}
}
}