Merge pull request #220 from yunyingk/mac15/bundle-report-workflow
Bundle report templates and integrate validation and rendering
This commit is contained in:
19 files changed
+588
-77
No files matched your search
@@ -9,6 +9,7 @@
|
||||
"exceljs": "^4.4.0",
|
||||
"iconv-lite": "^0.7.3",
|
||||
"ky": "^2.0.2",
|
||||
"marked": "15.0.12",
|
||||
"pinyin-pro": "^3.29.3",
|
||||
"yauzl": "^3.4.0",
|
||||
"zod": "^4.4.3",
|
||||
@@ -228,6 +229,8 @@
|
||||
|
||||
"lodash.uniq": ["lodash.uniq@4.5.0", "", {}, "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ=="],
|
||||
|
||||
"marked": ["marked@15.0.12", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA=="],
|
||||
|
||||
"minimatch": ["minimatch@10.2.6", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="],
|
||||
|
||||
"mkdirp": ["mkdirp@3.0.1", "", { "bin": { "mkdirp": "dist/cjs/src/bin.js" } }, "sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg=="],
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
"exceljs": "^4.4.0",
|
||||
"iconv-lite": "^0.7.3",
|
||||
"ky": "^2.0.2",
|
||||
"marked": "15.0.12",
|
||||
"pinyin-pro": "^3.29.3",
|
||||
"yauzl": "^3.4.0",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
@@ -7,6 +7,22 @@
|
||||
| `monthly.md` | 模板本体。**可变的皮**:章节标题、表格结构允许增删改名——填充逻辑从标题反推数据需求(`src/domains/seal/reports/describe.ts`),改这里通常不用改代码 |
|
||||
| `assets/` | 报告配图(图 1 数据图、图 2/3 占位图),相对引用,渲染时随 md 一起解析 |
|
||||
| `examples/` | 填充真实数据的成品示例(结构参考 + 测试夹具) |
|
||||
| `validate.py` / `render.py` | 下游工具:结构校验 + HTML/PNG/PDF 渲染。**不进包**,需要时用 `python3 report-templates/validate.py` 执行 |
|
||||
| `validate.py` / `render.py` | 结构校验 + HTML/PNG/PDF 渲染引擎,随 CLI 内嵌,由 `report validate` / `report render` 调用;也保留独立 Python 入口 |
|
||||
|
||||
模板纪律见模板仓库 README:不引入 frontmatter/占位符标记(结构即契约)、正文不含 HTML 注释、表格只换数据行。
|
||||
|
||||
默认模板和配图由本仓库 Git 管理,构建时直接内嵌进二进制;无需原模板仓库、当前目录下的 `report-templates/` 或已安装的 Skill。模板修改通过 PR 合入,再随构建/发版分发。`--template` 仅用于显式覆盖。
|
||||
|
||||
```bash
|
||||
seal-use report monthly --month 2026-08 --corp <corpId> --out reports/报告.md
|
||||
seal-use report validate reports/报告.md
|
||||
seal-use report render reports/报告.md --out build/报告
|
||||
```
|
||||
|
||||
`monthly --out` 保存 Markdown 和同目录的 `<报告名>.assets/` 配图目录,返回文件路径、数据缺口与后续命令;不指定 `--out` 时继续返回 `content`。自定义模板的本地配图也一并复制。已有文件默认拒绝覆盖,显式 `--overwrite` 才允许替换。通用 `--output-file` 仍只保存 JSON,与 `--out` 不同。
|
||||
|
||||
校验、渲染仅操作本地文件,不需要 `--corp`、登录或网络取数。校验失败返回结构化问题、退出码 1,并阻止导出。渲染成功返回产物路径、格式和字节数;HTML 内嵌本地配图及公式资源,可随产物移动。默认产出 HTML、完整长图 PNG、A4 分页 PDF;`--format html|png|pdf` 可选格式,PNG/PDF 同时保留 HTML。
|
||||
|
||||
运行环境:校验和渲染需要 Python 3;PNG/PDF 需要 Chrome/Chromium,PNG 还需要该 Python 环境中的 Pillow。可通过 `--python`、`--chrome` 指定可执行文件。自动发现优先使用 PATH 或 Playwright 缓存中已有的 `chrome-headless-shell`,再查普通 Chrome/Chromium;不自动安装浏览器。CLI 自带 Markdown 解析器,不再运行 `npx`。含公式的报告首次渲染需联网下载 KaTeX 0.16.11 到 `~/.cache/seal-use/report-render/`,之后复用缓存;可用 `SEAL_REPORT_CACHE_DIR` 指定缓存目录。
|
||||
|
||||
配图仍是模板示例/占位图,当前不会按当月数据自动重绘;对外使用前需替换。结构与数值校验通过也不代表示例值或人工裁决已经完备,应同时检查月报返回的 `notes`。
|
||||
+113
-31
@@ -12,13 +12,22 @@ PDF 走 Chrome 打印管线,A4 分页,表头跨页重复、行不跨页截
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import html as html_module
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote
|
||||
|
||||
CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
|
||||
CHROME = ""
|
||||
BROWSER_PROFILE = ""
|
||||
PNG_WIDTH = 1200 # PNG 视口宽度(CSS 像素)
|
||||
PNG_BAND = 14000 # 单次截取的最大高度,超出则分带拼接
|
||||
|
||||
@@ -64,14 +73,37 @@ a { color:#0969da; }
|
||||
"""
|
||||
|
||||
|
||||
def chrome(args: list[str], timeout: int = 300) -> subprocess.CompletedProcess:
|
||||
def chrome(args: list[str], timeout: int = 60) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(
|
||||
[CHROME, "--headless", "--disable-gpu", "--hide-scrollbars",
|
||||
f"--user-data-dir={BROWSER_PROFILE}", "--no-first-run", "--no-default-browser-check",
|
||||
"--run-all-compositor-stages-before-draw", *args],
|
||||
capture_output=True, text=True, timeout=timeout,
|
||||
capture_output=True, text=True, timeout=timeout, check=True,
|
||||
)
|
||||
|
||||
|
||||
def find_chrome(explicit: str | None) -> str:
|
||||
# A dedicated headless shell avoids desktop Chrome startup/shutdown problems on headless hosts.
|
||||
cached_shells = []
|
||||
if not explicit:
|
||||
for root in (Path.home() / "Library/Caches/ms-playwright", Path.home() / ".cache/ms-playwright",
|
||||
Path(os.environ.get("LOCALAPPDATA", "")) / "ms-playwright"):
|
||||
cached_shells.extend(root.glob("chromium_headless_shell-*/chrome-headless-shell-*/chrome-headless-shell*"))
|
||||
cached_shells = sorted((p for p in cached_shells if p.is_file()), key=lambda p: p.stat().st_mtime, reverse=True)
|
||||
candidates = [shutil.which(explicit) or explicit] if explicit else [
|
||||
shutil.which("chrome-headless-shell"), *map(str, cached_shells),
|
||||
*[shutil.which(name) for name in ("google-chrome", "chromium", "chromium-browser", "chrome", "msedge")],
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
||||
str(Path(os.environ.get("PROGRAMFILES", "C:/Program Files")) / "Google/Chrome/Application/chrome.exe"),
|
||||
str(Path(os.environ.get("PROGRAMFILES(X86)", "C:/Program Files (x86)")) / "Microsoft/Edge/Application/msedge.exe"),
|
||||
]
|
||||
for candidate in candidates:
|
||||
if candidate and Path(candidate).is_file() and os.access(candidate, os.X_OK):
|
||||
return candidate
|
||||
raise RuntimeError("未找到 Chrome/Chromium:请安装浏览器,或通过 --chrome <可执行文件> 指定")
|
||||
|
||||
|
||||
def doc_title(md: str, fallback: str) -> str:
|
||||
"""标题取自正文 H1;顺带剥掉可能夹在里面的 HTML 注释。"""
|
||||
m = re.search(r"(?m)^#\s+(.+?)\s*$", md)
|
||||
@@ -92,18 +124,22 @@ def md_to_html(md: str) -> str:
|
||||
return res.stdout
|
||||
|
||||
|
||||
def build_html(src: Path) -> tuple[str, str]:
|
||||
def build_html(src: Path, body_file: str | None = None) -> tuple[str, str]:
|
||||
"""渲染出完整 HTML 文本,返回 (html, 标题)。"""
|
||||
text = src.read_text(encoding="utf-8")
|
||||
body = md_to_html(text)
|
||||
body = Path(body_file).read_text(encoding="utf-8") if body_file else md_to_html(text)
|
||||
base = src.resolve().parent
|
||||
|
||||
# 相对图片路径改为绝对 file:// URI;marked 输出已做一次百分号编码,先 unquote 再转
|
||||
# 本地图片内嵌进 HTML;marked 输出已做一次百分号编码,先 unquote 再转。
|
||||
# 产物移动到其他目录或发送给别人后,仍能显示配图。
|
||||
def absolutize(m: re.Match) -> str:
|
||||
s = m.group(1)
|
||||
if s.startswith(("http://", "https://", "file://", "data:")):
|
||||
return m.group(0)
|
||||
return m.group(0).replace(s, (base / unquote(s)).as_uri(), 1)
|
||||
path = base / html_module.unescape(unquote(s))
|
||||
mime = {".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp"}.get(path.suffix.lower(), "application/octet-stream")
|
||||
data = base64.b64encode(path.read_bytes()).decode("ascii")
|
||||
return m.group(0).replace(s, f"data:{mime};base64,{data}", 1)
|
||||
|
||||
body = re.sub(r'<img src="([^"]+)"', absolutize, body)
|
||||
title = doc_title(text, src.stem)
|
||||
@@ -124,13 +160,28 @@ def build_html(src: Path) -> tuple[str, str]:
|
||||
body = re.sub(r"\$\$(.+?)\$\$", _display, body, flags=re.S)
|
||||
body = re.sub(r"(?<!\\)\$(?!\$)([^$]+?)\$(?!\$)", _inline, body)
|
||||
|
||||
href_css, _ = local_assets("katex.min.css", KATEX_CSS)
|
||||
js_local = [local_assets(n, u) for n, u in (
|
||||
("katex.min.js", KATEX_JS), ("auto-render.min.js", KATEX_AUTO))]
|
||||
math_head, scripts = "", ""
|
||||
if has_math:
|
||||
css_path, _ = local_assets("katex.min.css", KATEX_CSS)
|
||||
math_css = Path(css_path).read_text(encoding="utf-8")
|
||||
font_names = sorted(set(re.findall(r"url\((fonts/[^)]+)\)", math_css)))
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
list(pool.map(lambda name: local_assets(name, KATEX_CSS.rsplit("/", 1)[0] + "/" + name), font_names))
|
||||
# 字体也内嵌,避免 HTML 引用临时脚本目录或缺少 KaTeX 字体。
|
||||
def embed_font(m: re.Match) -> str:
|
||||
name = m.group(1)
|
||||
font_path, _ = local_assets(name, KATEX_CSS.rsplit("/", 1)[0] + "/" + name)
|
||||
mime = "font/woff2" if name.endswith("woff2") else "font/woff" if name.endswith("woff") else "font/ttf"
|
||||
data = base64.b64encode(Path(font_path).read_bytes()).decode("ascii")
|
||||
return f"url(data:{mime};base64,{data})"
|
||||
math_css = re.sub(r"url\((fonts/[^)]+)\)", embed_font, math_css)
|
||||
math_head = f"<style>{math_css}</style>\n"
|
||||
scripts = "\n".join("<script>" + Path(local_assets(n, u)[0]).read_text(encoding="utf-8") + "</script>" for n, u in (
|
||||
("katex.min.js", KATEX_JS), ("auto-render.min.js", KATEX_AUTO)))
|
||||
head = (
|
||||
'<!doctype html>\n<html lang="zh-CN">\n<head>\n<meta charset="utf-8">\n'
|
||||
f"<title>{title}</title>\n"
|
||||
f'<link rel="stylesheet" href="{href_css}">\n'
|
||||
f"<title>{html_module.escape(title)}</title>\n" +
|
||||
math_head +
|
||||
f"<style>{CSS}</style>\n</head>\n"
|
||||
)
|
||||
if has_math:
|
||||
@@ -141,7 +192,6 @@ def build_html(src: Path) -> tuple[str, str]:
|
||||
"throwOnError:false});});</script>"
|
||||
)
|
||||
body += "\n" + init
|
||||
scripts = "\n".join(f'<script src="{u}"></script>' for _, u in js_local)
|
||||
body = scripts + "\n" + body
|
||||
html = head + f"<body>\n{body}\n</body>\n</html>\n"
|
||||
return html, title
|
||||
@@ -149,19 +199,22 @@ def build_html(src: Path) -> tuple[str, str]:
|
||||
|
||||
def local_assets(name: str, url: str) -> tuple[str, str]:
|
||||
"""CDN 资源下载到 .cache/assets 后用本地路径,渲染离线可用;缓存命中不联网。"""
|
||||
d = Path(__file__).resolve().parent.parent / ".cache" / "assets"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
d = Path(os.environ.get("SEAL_REPORT_CACHE_DIR") or Path.home() / ".cache" / "seal-use" / "report-render" / "katex-0.16.11")
|
||||
f = d / name
|
||||
f.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not f.exists() or f.stat().st_size == 0:
|
||||
r = subprocess.run(["curl", "-sSL", "-o", str(f), url], capture_output=True)
|
||||
if not f.exists() or f.stat().st_size == 0:
|
||||
if f.exists():
|
||||
f.unlink()
|
||||
return "", url # 回退 CDN
|
||||
return f.as_uri(), f.as_uri()
|
||||
with urllib.request.urlopen(url, timeout=30) as response:
|
||||
content = response.read()
|
||||
if not content:
|
||||
raise RuntimeError(f"公式资源下载为空:{name}")
|
||||
# 原子写入:并发导出或中途失败不留下半个缓存文件。
|
||||
with tempfile.NamedTemporaryFile(dir=f.parent, delete=False) as temp:
|
||||
temp.write(content)
|
||||
Path(temp.name).replace(f)
|
||||
return str(f), f.as_uri()
|
||||
|
||||
|
||||
def measure_height(html_path: Path) -> int:
|
||||
def measure_height(html_path: Path, width: int = PNG_WIDTH) -> int:
|
||||
"""注入测量脚本,用 dump-dom 取文档真实高度(等待全部图片加载完)。"""
|
||||
probe = html_path.with_name("_measure.html")
|
||||
script = ("<script>window.addEventListener('load',function(){"
|
||||
@@ -171,7 +224,7 @@ def measure_height(html_path: Path) -> int:
|
||||
probe.write_text(html_path.read_text(encoding="utf-8").replace("</body>", script + "</body>"),
|
||||
encoding="utf-8")
|
||||
try:
|
||||
res = chrome(["--virtual-time-budget=30000", "--dump-dom", probe.as_uri()])
|
||||
res = chrome([f"--window-size={width},1000", "--virtual-time-budget=30000", "--dump-dom", probe.as_uri()])
|
||||
finally:
|
||||
probe.unlink(missing_ok=True)
|
||||
hits = re.findall(r"PAGEH:(\d+)", res.stdout)
|
||||
@@ -181,7 +234,7 @@ def measure_height(html_path: Path) -> int:
|
||||
|
||||
|
||||
def render_png(html_path: Path, png_path: Path, width: int = PNG_WIDTH) -> None:
|
||||
h = measure_height(html_path)
|
||||
h = measure_height(html_path, width)
|
||||
uri = html_path.as_uri()
|
||||
if h <= PNG_BAND:
|
||||
chrome([f"--screenshot={png_path}", f"--window-size={width},{h}",
|
||||
@@ -194,7 +247,7 @@ def render_png(html_path: Path, png_path: Path, width: int = PNG_WIDTH) -> None:
|
||||
band_html = html_path.with_name(f"_band{i}.html")
|
||||
band_html.write_text(
|
||||
html_path.read_text(encoding="utf-8").replace(
|
||||
"</style>", f"body{{margin-top:-{offset}px}}</style>", 1),
|
||||
"</head>", f"<style>body{{margin-top:-{offset}px}}</style></head>", 1),
|
||||
encoding="utf-8")
|
||||
out = html_path.parent / f"_band{i}.png"
|
||||
chrome([f"--screenshot={out}", f"--window-size={width},{bh}",
|
||||
@@ -223,10 +276,15 @@ def render_pdf(html_path: Path, pdf_path: Path) -> None:
|
||||
|
||||
|
||||
def main() -> int:
|
||||
global CHROME, BROWSER_PROFILE
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("src")
|
||||
ap.add_argument("-o", "--out", required=True, help="产物路径词干,如 build/模板")
|
||||
ap.add_argument("--width", type=int, default=PNG_WIDTH, help="PNG 视口宽度")
|
||||
ap.add_argument("--format", choices=("all", "html", "png", "pdf"), default="all")
|
||||
ap.add_argument("--body-file", help="CLI 已解析的 HTML 正文;无需 npx")
|
||||
ap.add_argument("--chrome", help="Chrome/Chromium 可执行文件")
|
||||
ap.add_argument("--json", action="store_true")
|
||||
a = ap.parse_args()
|
||||
|
||||
src = Path(a.src)
|
||||
@@ -234,16 +292,33 @@ def main() -> int:
|
||||
stem.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
html_path = stem.with_suffix(".html")
|
||||
html, _ = build_html(src)
|
||||
if a.format != "html":
|
||||
CHROME = find_chrome(a.chrome)
|
||||
if a.format in ("all", "png"):
|
||||
try:
|
||||
import PIL
|
||||
except ImportError as e:
|
||||
raise RuntimeError("PNG 导出需要 Pillow:请在当前 Python 环境安装 Pillow") from e
|
||||
html, _ = build_html(src, a.body_file)
|
||||
html_path.write_text(html, encoding="utf-8")
|
||||
|
||||
png_path = stem.with_suffix(".png")
|
||||
render_png(html_path, png_path, a.width)
|
||||
|
||||
pdf_path = stem.with_suffix(".pdf")
|
||||
render_pdf(html_path, pdf_path)
|
||||
paths = [html_path]
|
||||
with tempfile.TemporaryDirectory(prefix="seal-report-chrome-") as profile:
|
||||
BROWSER_PROFILE = profile
|
||||
if a.format in ("all", "png"):
|
||||
render_png(html_path, png_path, a.width)
|
||||
paths.append(png_path)
|
||||
if a.format in ("all", "pdf"):
|
||||
render_pdf(html_path, pdf_path)
|
||||
paths.append(pdf_path)
|
||||
|
||||
for p in (html_path, png_path, pdf_path):
|
||||
if a.json:
|
||||
print(json.dumps({"artifacts": [{"path": str(p), "format": p.suffix[1:], "bytes": p.stat().st_size} for p in paths]}, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
for p in paths:
|
||||
size = p.stat().st_size
|
||||
extra = ""
|
||||
if p.suffix == ".png":
|
||||
@@ -267,4 +342,11 @@ def main() -> int:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except subprocess.TimeoutExpired:
|
||||
print("浏览器渲染超时。可通过 --chrome 指定可用的 Chrome/Chromium 或 chrome-headless-shell。", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
except Exception as e:
|
||||
print(str(e), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -15,7 +15,10 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote
|
||||
|
||||
SECTION_NUMBERS = ["1", "2", "3", "4", "5", "6", "7"]
|
||||
REQUIRED_INFO_ROWS = {"报告编号", "客户名称", "统计期间", "报告状态", "生成日期"}
|
||||
@@ -155,7 +158,9 @@ def check(path: Path) -> Report:
|
||||
r.n_figs += 1
|
||||
if src.startswith(("http://", "https://")):
|
||||
continue
|
||||
if not (path.parent / src).exists():
|
||||
if src.startswith("data:"):
|
||||
continue
|
||||
if not (path.parent / unquote(src)).exists():
|
||||
r.err("IMG001", f"图片不存在:{src}")
|
||||
|
||||
# 7. 数值自洽(全部从正文推导)
|
||||
@@ -218,14 +223,28 @@ def default_paths() -> list[Path]:
|
||||
|
||||
|
||||
def main() -> int:
|
||||
paths = [Path(a) for a in sys.argv[1:]] or default_paths()
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("paths", nargs="*")
|
||||
ap.add_argument("--json", action="store_true", help="输出机器可读的校验结果")
|
||||
a = ap.parse_args()
|
||||
paths = [Path(p) for p in a.paths] or default_paths()
|
||||
failed = False
|
||||
results = []
|
||||
for p in paths:
|
||||
rep = check(p)
|
||||
print(f"[{'PASS' if rep.ok() else 'FAIL'}] {p} (表格 {rep.n_tables} 个, 图片 {rep.n_figs} 张)")
|
||||
for lv, code, msg in rep.issues:
|
||||
print(f" {lv} {code}: {msg}")
|
||||
if a.json:
|
||||
results.append({
|
||||
"file": str(p.resolve()), "valid": rep.ok(),
|
||||
"tables": rep.n_tables, "figures": rep.n_figs,
|
||||
"issues": [{"level": lv, "code": code, "message": msg} for lv, code, msg in rep.issues],
|
||||
})
|
||||
else:
|
||||
print(f"[{'PASS' if rep.ok() else 'FAIL'}] {p} (表格 {rep.n_tables} 个, 图片 {rep.n_figs} 张)")
|
||||
for lv, code, msg in rep.issues:
|
||||
print(f" {lv} {code}: {msg}")
|
||||
failed |= not rep.ok()
|
||||
if a.json:
|
||||
print(json.dumps(results, ensure_ascii=False))
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
|
||||
@@ -27,6 +27,15 @@ const files = walk(skillRoot).map((fullPath) => ({
|
||||
kind: textExtensions.has(extname(fullPath).toLowerCase()) ? "text" : "asset"
|
||||
}));
|
||||
|
||||
// The skill's report reference is owned by the repository too; install it without maintaining a second copy.
|
||||
const reportReadme = resolve(root, "report-templates", "README.md");
|
||||
files.push({
|
||||
fullPath: reportReadme,
|
||||
relativePath: "report-templates/README.md",
|
||||
importPath: relative(resolve(root, "src", "core"), reportReadme).split("\\").join("/"),
|
||||
kind: "text"
|
||||
});
|
||||
|
||||
const lines = [
|
||||
"// Generated by scripts/generate-embedded-skill.mjs. Do not edit manually.",
|
||||
""
|
||||
|
||||
@@ -131,14 +131,18 @@ seal-use langfuse observation <traceId> <observationId> # 最后才取焦点
|
||||
月度报告一次调用生成,不要手搓 Markdown 表格或串行取数:
|
||||
|
||||
```bash
|
||||
seal-use report monthly --month <YYYY-MM> --corp <corpId>
|
||||
seal-use report monthly --month <YYYY-MM> --corp <corpId> --out reports/报告.md
|
||||
seal-use report validate reports/报告.md
|
||||
seal-use report render reports/报告.md --out build/报告
|
||||
```
|
||||
|
||||
按模板结构(`report-templates/monthly.md`)自动从效能/风险/审批运行接口取数填充,返回填充后的 Markdown、各章节数据完备度(`sections`)与数据缺口标注(`notes`)。要点:
|
||||
|
||||
- **模板是可变的皮**:章节增删改名只要关键词仍命中,取数需求自动跟着走(`src/domains/seal/reports/describe.ts`)。改模板通常不用改代码。
|
||||
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
|
||||
- 结果里的 `next` 给出下游 `validate` / `render` 指引(校验与 HTML/PNG/PDF 渲染用 `report-templates/validate.py`、`render.py`,不进包)。
|
||||
- 默认模板、配图和校验/渲染引擎由仓库 Git 管理并随二进制内嵌,不依赖当前目录或原模板仓库。`--out` 保存 Markdown 与配图;不传则继续返回 `content`。`--output-file` 保存的是 JSON。
|
||||
- 结果里的 `next` 给出 CLI 校验与导出命令。`report validate` / `report render` 不需企业登录;校验失败返回 issues 和退出码 1,阻止导出。`render` 默认产出 HTML / 全长 PNG / A4 PDF,`--format html|png|pdf` 可选格式。已有文件须显式 `--overwrite` 才允许替换。
|
||||
- 本地运行环境:Python 3;PNG/PDF 另需 Chrome/Chromium,PNG 需 Pillow(可用 `--python` / `--chrome` 指定环境)。Markdown 解析已打包,不需 npm/npx;含公式时首次渲染联网缓存 KaTeX。模板配图仍是示例/占位图,对外使用前检查 `notes` 并替换配图。
|
||||
- 只读能力 `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。
|
||||
|
||||
### 人工裁决回填(算出人工审核准确率)
|
||||
|
||||
@@ -1,11 +1,35 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import { runCapabilityResult } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
import { CliError, usageError } from "../../core/errors.js";
|
||||
import { renderReportFile, saveReportMarkdown, validateReportFile } from "../../domains/seal/reports/files.js";
|
||||
import type { MonthlyReportResult } from "../../domains/seal/reports/monthly.js";
|
||||
import { loadReviews, reviewFilePath, writeReview } from "../../domains/seal/reports/review-store.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
/** Tenant-free commands: dispatch these before resolving enterprise configuration or authentication. */
|
||||
export async function handleLocalReportCommand(action: "validate" | "render", args: ParsedArgs) {
|
||||
const file = args.command[2] ?? stringOption(args.options.file);
|
||||
if (!file) throw usageError(`Usage: seal-use report ${action} <报告文件.md>${action === "render" ? " --out <产物路径词干>" : ""}`);
|
||||
const python = stringOption(args.options.python);
|
||||
if (action === "validate") {
|
||||
const result = await validateReportFile(file, { python });
|
||||
printJson(result, outputOptions(args.options));
|
||||
if (!result.valid) throw new CliError("报告校验未通过,请按 issues 修正后重试。", 1);
|
||||
return;
|
||||
}
|
||||
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
||||
if (!out) throw usageError("Usage: seal-use report render <报告文件.md> --out <产物路径词干>");
|
||||
const result = await renderReportFile(file, {
|
||||
out, python, format: stringOption(args.options.format), width: numberOption(args.options.width),
|
||||
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite)
|
||||
});
|
||||
printJson(result, outputOptions(args.options));
|
||||
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成渲染产物。请按 validation.issues 修正后重试。", 1);
|
||||
}
|
||||
|
||||
/** `seal-use report monthly` — 月度 AI 审核准确率报告(Markdown 填充)。 */
|
||||
export async function handleReportCommand(
|
||||
action: string | undefined,
|
||||
@@ -18,7 +42,7 @@ export async function handleReportCommand(
|
||||
if (!month) {
|
||||
throw new Error("Usage: seal-use report monthly --month <YYYY-MM> [--template <file>] [--report-id <RPT-...>] [--corp <corpId>]");
|
||||
}
|
||||
await runCapability(
|
||||
const result = await runCapabilityResult(
|
||||
"sealReportMonthlyGet",
|
||||
client,
|
||||
corp,
|
||||
@@ -27,9 +51,17 @@ export async function handleReportCommand(
|
||||
templatePath: stringOption(args.options.template),
|
||||
reportId: stringOption(args.options["report-id"]) ?? stringOption(args.options.reportId),
|
||||
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
}
|
||||
) as MonthlyReportResult;
|
||||
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
||||
if (out) {
|
||||
const saved = saveReportMarkdown(result.content, result.templatePath, out, booleanOption(args.options.overwrite));
|
||||
const quotedFile = `'${saved.file.replace(/'/g, "'\\''")}'`;
|
||||
printJson({ ...result, content: undefined, ...saved, next: {
|
||||
validate: `seal-use report validate ${quotedFile}`,
|
||||
render: `seal-use report render ${quotedFile} --out build/report`
|
||||
} }, outputOptions(args.options));
|
||||
} else printJson(result, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
+26
-3
@@ -611,21 +611,44 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
{
|
||||
area: "report",
|
||||
title: "Monthly audit accuracy reports",
|
||||
description: "Generate the monthly AI audit accuracy report (Markdown) from a mutable template plus live tenant data.",
|
||||
description: "Generate monthly audit reports, validate local Markdown, and export HTML/PNG/PDF.",
|
||||
commands: [
|
||||
{
|
||||
name: "monthly",
|
||||
aliases: ["month"],
|
||||
summary: "Fill the monthly report template with performance, risk, and approval-run data",
|
||||
usage: ["seal-use report monthly --month <YYYY-MM> [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--corp <corpId>]"],
|
||||
usage: ["seal-use report monthly --month <YYYY-MM> [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
|
||||
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to report-templates/monthly.md" },
|
||||
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to the Git-managed template embedded in the binary, independent of cwd" },
|
||||
{ flag: "--out <file>", description: "Save Markdown plus local images beside the report; stdout stays JSON (without the content field)" },
|
||||
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files" },
|
||||
{ flag: "--report-id <RPT-...>", description: "Custom report id; defaults to RPT-<YYYYMM>-<random>" },
|
||||
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" }
|
||||
],
|
||||
description: "The template is the mutable skin: section headings, tables, and order may change and data demands are inferred from headings (src/domains/seal/reports/describe.ts). Fields with no upstream metric (human accuracy, mismatch categories) keep template sample values and are marked with a warning note instead of fabricated numbers."
|
||||
},
|
||||
{
|
||||
name: "validate",
|
||||
summary: "Check a local report's structure, images, totals, and formulas",
|
||||
usage: ["seal-use report validate <报告.md> [--python <executable>]"],
|
||||
options: [{ flag: "--python <executable>", description: "Python 3 executable; defaults to python3 on PATH" }],
|
||||
description: "Local only: no --corp, credentials, or Seal requests. Returns JSON issues; exit 1 if validation fails."
|
||||
},
|
||||
{
|
||||
name: "render",
|
||||
summary: "Validate and export HTML, full-length PNG, and A4 PDF from local Markdown",
|
||||
usage: ["seal-use report render <报告.md> --out <build/报告> [--format <all|html|png|pdf>]"],
|
||||
options: [
|
||||
{ flag: "--out <stem>", description: "Output filename stem; extensions are appended" },
|
||||
{ flag: "--format <format>", description: "all (default), html, png, or pdf; PNG/PDF also produce HTML" },
|
||||
{ flag: "--width <px>", description: "PNG viewport width, default 1200 (320–5000)" },
|
||||
{ flag: "--python <executable>", description: "Python 3 executable; defaults to python3 on PATH" },
|
||||
{ flag: "--chrome <executable>", description: "Chrome/Chromium executable; otherwise auto-detected" },
|
||||
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files after successful rendering" }
|
||||
],
|
||||
description: "No enterprise login. Validation failure produces JSON issues and no artifacts. Requires Python 3; PNG/PDF also need Chrome/Chromium, PNG needs Pillow. First use of math fetches and caches KaTeX resources. Markdown parsing is bundled, with no runtime npm/npx dependency."
|
||||
},
|
||||
{
|
||||
name: "review set",
|
||||
summary: "Record one human adjudication (who was right: AI or human) for a document",
|
||||
|
||||
+6
-6
@@ -42,7 +42,7 @@ export const BOOLEAN_FLAGS = new Set([
|
||||
export const VALUE_FLAGS = new Set([
|
||||
"access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity",
|
||||
"base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes",
|
||||
"channel", "code", "concurrency", "content", "content-file", "content-hints", "content-type", "contentFile",
|
||||
"channel", "chrome", "code", "concurrency", "content", "content-file", "content-hints", "content-type", "contentFile",
|
||||
"contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date",
|
||||
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
|
||||
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
|
||||
@@ -61,7 +61,7 @@ export const VALUE_FLAGS = new Set([
|
||||
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
|
||||
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
|
||||
"path", "phone", "policyId", "poll-interval", "pollInterval", "port",
|
||||
"prod", "prod-corp", "prodCorp", "purpose", "q", "query",
|
||||
"prod", "prod-corp", "prodCorp", "purpose", "python", "q", "query",
|
||||
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "rejection-num", "rejectionNum",
|
||||
"reviewed-by", "reviewedBy",
|
||||
"report-id",
|
||||
@@ -81,7 +81,7 @@ export const VALUE_FLAGS = new Set([
|
||||
"trace-id", "trace-limit",
|
||||
"type", "until", "url", "userId", "version-name", "versionName",
|
||||
"verdict",
|
||||
"webhook", "workflow-type-id", "workflowTypeId"
|
||||
"webhook", "width", "workflow-type-id", "workflowTypeId"
|
||||
]);
|
||||
|
||||
// Registered flags. Unknown flags are rejected.
|
||||
@@ -89,7 +89,7 @@ export const KNOWN_FLAGS = new Set([
|
||||
"V", "access-token", "accessToken", "add", "all", "app-key",
|
||||
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
|
||||
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
|
||||
"bg-save", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only",
|
||||
"bg-save", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome",
|
||||
"code", "completed-only", "completedOnly", "concurrency", "confirm", "content",
|
||||
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
|
||||
"corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy",
|
||||
@@ -115,7 +115,7 @@ export const KNOWN_FLAGS = new Set([
|
||||
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
|
||||
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
|
||||
"phone", "plain", "policyId", "poll-interval", "pollInterval", "port",
|
||||
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
|
||||
"prod", "prod-corp", "prodCorp", "publish", "purpose", "python", "q",
|
||||
"query", "quiet", "r", "recode", "record-id", "record-ids",
|
||||
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "rejection-num", "rejectionNum", "repo",
|
||||
"report-id",
|
||||
@@ -138,7 +138,7 @@ export const KNOWN_FLAGS = new Set([
|
||||
"to", "to-downloads", "toDownloads", "token", "tokenId", "trace-id", "trace-limit", "type",
|
||||
"until", "url", "userId", "v", "version", "version-name",
|
||||
"verdict",
|
||||
"versionName", "wait", "webhook", "with-expense-extraction", "withExpenseExtraction", "with-flow", "workflow-type-id", "workflowTypeId",
|
||||
"versionName", "wait", "webhook", "width", "with-expense-extraction", "withExpenseExtraction", "with-flow", "workflow-type-id", "workflowTypeId",
|
||||
"workspace", "yes"
|
||||
]);
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
||||
// `analyze` is deliberately absent: it POSTs and starts an analysis server-side, so it is a
|
||||
// mutation despite reading like a query. See SEAL_MUTATING_CAPABILITIES.
|
||||
analytics: ["insight", "risks", "performance", "export"],
|
||||
report: ["monthly", "review list"],
|
||||
report: ["monthly", "validate", "render", "review list"],
|
||||
source: ["config"],
|
||||
skill: ["dump", "status"],
|
||||
doctor: ["", "guide", "paths", "tenant", "auth"],
|
||||
|
||||
@@ -224,6 +224,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "report" && (action === "validate" || action === "render")) {
|
||||
await (await import("./commands/report.js")).handleLocalReportCommand(action, args);
|
||||
return;
|
||||
}
|
||||
|
||||
// Langfuse trace inspection needs no tenant: it authenticates with the
|
||||
// compile-time injected read-only key pair, so it dispatches before corp
|
||||
// selection (like probe/doctor) and never touches a Seal client.
|
||||
|
||||
@@ -23,6 +23,7 @@ import file19 from "../../skills/seal-use/references/rule-lightweight.md" with {
|
||||
import file20 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
|
||||
import file21 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
|
||||
import file22 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
|
||||
import file23 from "../../report-templates/README.md" with { type: "text" };
|
||||
|
||||
export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
|
||||
"SKILL.md": file0,
|
||||
@@ -42,6 +43,7 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
|
||||
"references/rule-lint.md": file20,
|
||||
"references/staging-simulation-workflow.md": file21,
|
||||
"references/webhook-resource-pack.md": file22,
|
||||
"report-templates/README.md": file23,
|
||||
};
|
||||
|
||||
export const EMBEDDED_SKILL_ASSET_DATA: Record<string, string> = {
|
||||
@@ -77,4 +79,5 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
|
||||
"references/rule-lint.md",
|
||||
"references/staging-simulation-workflow.md",
|
||||
"references/webhook-resource-pack.md",
|
||||
"report-templates/README.md",
|
||||
];
|
||||
Vendored
+10
@@ -12,3 +12,13 @@ declare module "*.yml" {
|
||||
const content: string;
|
||||
export default content;
|
||||
}
|
||||
|
||||
declare module "*.py" {
|
||||
const content: string;
|
||||
export default content;
|
||||
}
|
||||
|
||||
declare module "*.svg" {
|
||||
const content: string;
|
||||
export default content;
|
||||
}
|
||||
@@ -16,7 +16,7 @@ export const reportCapabilities = [
|
||||
templatePath: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("自定义模板 Markdown 路径;缺省用 report-templates/monthly.md"),
|
||||
.describe("自定义模板 Markdown 路径;缺省用随 CLI 内嵌的仓内 report-templates/monthly.md,不依赖当前目录"),
|
||||
reportId: z.string().optional().describe("自定义报告编号(RPT-YYYYMM-XXXXXX)"),
|
||||
maxRuns: z
|
||||
.number()
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCli } from "../../../cli/runner.js";
|
||||
import { buildMonthlyReport } from "./monthly.js";
|
||||
import { renderReportFile, saveReportMarkdown, validateReportFile } from "./files.js";
|
||||
import { BUILTIN_MONTHLY_TEMPLATE, BUILTIN_TEMPLATE_PATH } from "./resources.js";
|
||||
|
||||
const dirs: string[] = [];
|
||||
const originalCwd = process.cwd();
|
||||
const originalEnv = { enterprises: process.env.SEAL_USE_ENTERPRISES_DIR, reviews: process.env.SEAL_USE_REVIEWS_DIR };
|
||||
afterEach(() => {
|
||||
process.chdir(originalCwd);
|
||||
for (const [key, value] of Object.entries({ SEAL_USE_ENTERPRISES_DIR: originalEnv.enterprises, SEAL_USE_REVIEWS_DIR: originalEnv.reviews })) {
|
||||
if (value === undefined) delete process.env[key]; else process.env[key] = value;
|
||||
}
|
||||
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function workspace() {
|
||||
const dir = mkdtempSync(join(tmpdir(), "seal-report-test-"));
|
||||
dirs.push(dir);
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = join(dir, "no-enterprises");
|
||||
process.env.SEAL_USE_REVIEWS_DIR = join(dir, "reviews");
|
||||
return dir;
|
||||
}
|
||||
|
||||
const validReport = [
|
||||
"# 本地报告", "", "| 报告信息 | 内容 |", "| --- | --- |",
|
||||
"| 报告编号 | RPT-202608-TEST |", "| 客户名称 | 测试企业 |", "| 统计期间 | 2026-08 |",
|
||||
"| 报告状态 | 草稿 |", "| 生成日期 | 2026-10-12 |", ""
|
||||
].join("\n");
|
||||
|
||||
function localReport(dir: string, content = validReport) {
|
||||
const file = join(dir, "报告.md");
|
||||
writeFileSync(file, content);
|
||||
return file;
|
||||
}
|
||||
|
||||
describe("bundled report templates", () => {
|
||||
test("monthly ignores cwd templates and returns the same generated id as the document", async () => {
|
||||
const dir = workspace();
|
||||
mkdirSync(join(dir, "report-templates"));
|
||||
writeFileSync(join(dir, "report-templates", "monthly.md"), "# IMPOSTOR");
|
||||
process.chdir(dir);
|
||||
const client = { get: async () => ({ json: async () => ({ data: { records: [] } }) }) } as never;
|
||||
const result = await buildMonthlyReport(client, { month: "2026-08", corp: { id: "test-corp", name: "测试企业" } });
|
||||
expect(result.templatePath).toBe(BUILTIN_TEMPLATE_PATH);
|
||||
expect(result.content).not.toContain("IMPOSTOR");
|
||||
expect(result.content).toContain("【测试企业】8月AI审核准确率报告");
|
||||
expect(result.reportId).toMatch(/^RPT-202608-[A-F0-9]{6}$/);
|
||||
expect(result.content).toContain(result.reportId);
|
||||
expect(result.next.validate).toStartWith("seal-use report validate");
|
||||
});
|
||||
|
||||
test("explicit custom template overrides the built-in and missing paths fail locally", async () => {
|
||||
const dir = workspace();
|
||||
const template = join(dir, "custom.md");
|
||||
writeFileSync(template, "# Custom report\n\nUser-owned layout");
|
||||
const client = { get: () => { throw new Error("must not fetch for this template"); } } as never;
|
||||
const result = await buildMonthlyReport(client, { month: "2026-08", templatePath: template, corp: { id: "test", name: "Test" } });
|
||||
expect(result.templatePath).toBe(template);
|
||||
expect(result.content).toContain("User-owned layout");
|
||||
await expect(buildMonthlyReport(client, { month: "2026-08", templatePath: join(dir, "missing.md"), corp: { id: "test", name: "Test" } }))
|
||||
.rejects.toMatchObject({ exitCode: 13 });
|
||||
});
|
||||
|
||||
test("saved built-in Markdown and Chinese assets validate from an unrelated directory", async () => {
|
||||
const dir = workspace();
|
||||
const saved = saveReportMarkdown(BUILTIN_MONTHLY_TEMPLATE, BUILTIN_TEMPLATE_PATH, join(dir, "my 报告.md"));
|
||||
expect(saved.assets).toHaveLength(3);
|
||||
process.chdir(tmpdir());
|
||||
expect(await validateReportFile(saved.file)).toMatchObject({ valid: true, figures: 3, issues: [] });
|
||||
});
|
||||
|
||||
test("custom images with matching basenames are copied separately and leave source files intact", async () => {
|
||||
const dir = workspace();
|
||||
for (const name of ["a", "b"]) {
|
||||
mkdirSync(join(dir, name));
|
||||
writeFileSync(join(dir, name, "图.svg"), `<svg>${name}</svg>`);
|
||||
}
|
||||
const content = validReport + "\n\n\n";
|
||||
const saved = saveReportMarkdown(content, join(dir, "template.md"), join(dir, "export", "report.md"));
|
||||
expect(saved.assets.map((file) => readFileSync(file, "utf8"))).toEqual(["<svg>a</svg>", "<svg>b</svg>"]);
|
||||
expect(readFileSync(join(dir, "a", "图.svg"), "utf8")).toBe("<svg>a</svg>");
|
||||
expect(await validateReportFile(saved.file)).toMatchObject({ valid: true, figures: 2 });
|
||||
});
|
||||
|
||||
test("output collisions are checked before any Markdown or assets are written", () => {
|
||||
const dir = workspace();
|
||||
const file = join(dir, "report.md");
|
||||
writeFileSync(file, "existing");
|
||||
expect(() => saveReportMarkdown(BUILTIN_MONTHLY_TEMPLATE, BUILTIN_TEMPLATE_PATH, file)).toThrow("--overwrite");
|
||||
expect(readFileSync(file, "utf8")).toBe("existing");
|
||||
expect(existsSync(join(dir, "report.assets"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("local report CLI", () => {
|
||||
test("validates without a tenant, and reports failed validation as JSON with exit 1", async () => {
|
||||
const dir = workspace();
|
||||
const good = await runCli(["report", "validate", localReport(dir)]);
|
||||
expect(good.exitCode).toBe(0);
|
||||
expect(JSON.parse(good.stdout)).toMatchObject({ valid: true, issues: [] });
|
||||
const bad = await runCli(["report", "validate", localReport(dir, "# broken\n")]);
|
||||
expect(bad.exitCode).toBe(1);
|
||||
expect(JSON.parse(bad.stdout)).toMatchObject({ valid: false, issues: expect.arrayContaining([expect.objectContaining({ code: "IMG001" })]) });
|
||||
});
|
||||
|
||||
test("renders self-contained HTML without Chrome, npm, or Seal credentials", async () => {
|
||||
const dir = workspace();
|
||||
writeFileSync(join(dir, "image.svg"), '<svg xmlns="http://www.w3.org/2000/svg"><text>hello</text></svg>');
|
||||
const file = localReport(dir, validReport + "\n\n");
|
||||
const out = join(dir, "build", "成品");
|
||||
const result = await runCli(["report", "render", file, "--out", out, "--format", "html", "--chrome", join(dir, "absent")]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ validation: { valid: true }, artifacts: [{ path: out + ".html", format: "html", bytes: expect.any(Number) }] });
|
||||
const html = readFileSync(out + ".html", "utf8");
|
||||
expect(html).toContain("data:image/svg+xml;base64,");
|
||||
expect(html).not.toContain("file://");
|
||||
expect(html).not.toContain("cdn.jsdelivr");
|
||||
expect(html).toContain("测试企业");
|
||||
});
|
||||
|
||||
test("failed validation prevents rendering and returns issues without creating outputs", async () => {
|
||||
const dir = workspace();
|
||||
const out = join(dir, "build", "blocked");
|
||||
const result = await runCli(["report", "render", localReport(dir, "# Invalid"), "--out", out, "--format", "html"]);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ validation: { valid: false }, artifacts: [] });
|
||||
expect(existsSync(join(dir, "build"))).toBe(false);
|
||||
});
|
||||
|
||||
test("missing files, dependencies, malformed formats and width have explicit exit codes", async () => {
|
||||
const dir = workspace();
|
||||
const file = localReport(dir);
|
||||
const cases: Array<[string[], number]> = [
|
||||
[["report", "validate", join(dir, "absent.md")], 13],
|
||||
[["report", "validate", file, "--python", join(dir, "absent-python")], 13],
|
||||
[["report", "render", file], 2],
|
||||
[["report", "render", file, "--out", join(dir, "out"), "--format", "docx"], 2],
|
||||
[["report", "render", file, "--out", join(dir, "out"), "--width", "10"], 2]
|
||||
];
|
||||
for (const [argv, exitCode] of cases) expect((await runCli(argv)).exitCode).toBe(exitCode);
|
||||
});
|
||||
|
||||
test("failed rendering keeps existing outputs even when overwrite was requested", async () => {
|
||||
const dir = workspace();
|
||||
const file = localReport(dir);
|
||||
const out = join(dir, "result");
|
||||
writeFileSync(out + ".html", "existing html");
|
||||
writeFileSync(out + ".pdf", "existing pdf");
|
||||
await expect(renderReportFile(file, { out, format: "pdf", chrome: join(dir, "absent-chrome"), overwrite: true })).rejects.toMatchObject({ exitCode: 13 });
|
||||
expect(readFileSync(out + ".html", "utf8")).toBe("existing html");
|
||||
expect(readFileSync(out + ".pdf", "utf8")).toBe("existing pdf");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
import { constants, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { execFile } from "node:child_process";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, dirname, extname, join, resolve } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { marked } from "marked";
|
||||
import { z } from "zod";
|
||||
import { CliError, usageError, validationError } from "../../../core/errors.js";
|
||||
import { BUILTIN_TEMPLATE_PATH, REPORT_ASSETS, REPORT_SCRIPTS } from "./resources.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const validationSchema = z.object({
|
||||
file: z.string(), valid: z.boolean(), tables: z.number(), figures: z.number(),
|
||||
issues: z.array(z.object({ level: z.enum(["ERROR", "WARN"]), code: z.string(), message: z.string() }))
|
||||
});
|
||||
export type ReportValidation = z.infer<typeof validationSchema>;
|
||||
type LocalToolOptions = { python?: string };
|
||||
export type ReportRenderOptions = LocalToolOptions & {
|
||||
out: string;
|
||||
format?: string;
|
||||
width?: number;
|
||||
chrome?: string;
|
||||
overwrite?: boolean;
|
||||
};
|
||||
|
||||
function inputFile(file: string): string {
|
||||
const path = resolve(file);
|
||||
if (!existsSync(path) || !statSync(path).isFile()) throw validationError(`报告文件不存在或不是文件:${path}`);
|
||||
return path;
|
||||
}
|
||||
|
||||
function checkOutput(path: string, overwrite = false) {
|
||||
if (existsSync(path) && (!overwrite || !statSync(path).isFile())) {
|
||||
throw validationError(`输出已存在或不是文件:${path}。覆盖已有文件须显式传 --overwrite。`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Export the Markdown and its local images together, without changing a custom template's source assets. */
|
||||
export function saveReportMarkdown(content: string, templatePath: string, output: string, overwrite = false) {
|
||||
const file = resolve(output);
|
||||
const assetDir = `${basename(file, extname(file))}.assets`;
|
||||
const files = new Map<string, string | Buffer>();
|
||||
const images = new Map<string, string>();
|
||||
const savedContent = content.replace(/(!\[[^\]]*\]\()([^)\n]+)(\))/g, (match, before: string, source: string, after: string) => {
|
||||
if (/^(?:https?:|data:|file:)/.test(source)) return match;
|
||||
const path = decodeURIComponent(source);
|
||||
let target = images.get(path);
|
||||
if (!target) {
|
||||
target = `${assetDir}/${images.size + 1}-${basename(path)}`;
|
||||
const bundled = templatePath === BUILTIN_TEMPLATE_PATH ? REPORT_ASSETS[path] : undefined;
|
||||
const data = bundled ?? readFileSync(inputFile(resolve(dirname(templatePath), path)));
|
||||
files.set(resolve(dirname(file), target), data);
|
||||
images.set(path, target);
|
||||
}
|
||||
return `${before}${encodeURI(target)}${after}`;
|
||||
});
|
||||
files.set(file, savedContent);
|
||||
for (const path of files.keys()) checkOutput(path, overwrite);
|
||||
for (const [path, data] of files) {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, data, { flag: overwrite ? "w" : "wx" });
|
||||
}
|
||||
return { file, assets: [...files.keys()].filter((path) => path !== file) };
|
||||
}
|
||||
|
||||
async function withTools<T>(options: LocalToolOptions, operation: (dir: string, python: string) => Promise<T>): Promise<T> {
|
||||
const python = Bun.which(options.python ?? "python3");
|
||||
if (!python) throw validationError("报告工具需要 Python 3。请安装 Python 3,或通过 --python <可执行文件> 指定。");
|
||||
const dir = mkdtempSync(join(tmpdir(), "seal-report-tools-"));
|
||||
try {
|
||||
for (const [name, content] of Object.entries(REPORT_SCRIPTS)) writeFileSync(join(dir, name), content);
|
||||
return await operation(dir, python);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function runTool(python: string, args: string[], allowInvalid = false): Promise<unknown> {
|
||||
let stdout: string;
|
||||
try {
|
||||
stdout = (await execute(python, args, { encoding: "utf8", timeout: 600_000, maxBuffer: 16 * 1024 * 1024 })).stdout;
|
||||
} catch (error) {
|
||||
const failure = error as { code?: number; stdout?: string; stderr?: string; message?: string };
|
||||
if (allowInvalid && failure.code === 1 && failure.stdout?.trim()) stdout = failure.stdout;
|
||||
else {
|
||||
const message = failure.stderr?.trim() || failure.message || String(error);
|
||||
if (/^(?:未找到 Chrome\/Chromium|PNG 导出需要 Pillow)/.test(message)) throw validationError(message);
|
||||
throw new CliError(`报告工具执行失败:${message}`, 1);
|
||||
}
|
||||
}
|
||||
return JSON.parse(stdout);
|
||||
}
|
||||
|
||||
async function validateWithTools(file: string, dir: string, python: string): Promise<ReportValidation> {
|
||||
return z.array(validationSchema).length(1).parse(await runTool(python, [join(dir, "validate.py"), "--json", file], true))[0]!;
|
||||
}
|
||||
|
||||
/** Local validation deliberately needs no tenant selection, token, or HTTP client. */
|
||||
export async function validateReportFile(file: string, options: LocalToolOptions = {}): Promise<ReportValidation> {
|
||||
const path = inputFile(file);
|
||||
return withTools(options, (dir, python) => validateWithTools(path, dir, python));
|
||||
}
|
||||
|
||||
/** Preserve the existing Python layout engine while bundling Markdown parsing and returning clean JSON. */
|
||||
export async function renderReportFile(file: string, options: ReportRenderOptions) {
|
||||
const path = inputFile(file);
|
||||
const format = options.format ?? "all";
|
||||
if (!["all", "html", "png", "pdf"].includes(format)) throw usageError("Invalid --format: use all, html, png, or pdf.");
|
||||
const width = options.width ?? 1200;
|
||||
if (!Number.isInteger(width) || width < 320 || width > 5000) throw usageError("Invalid --width: use an integer from 320 to 5000.");
|
||||
const stem = resolve(options.out);
|
||||
const formats = format === "all" ? ["html", "png", "pdf"] : format === "html" ? ["html"] : ["html", format];
|
||||
const destinations = formats.map((extension) => `${stem}.${extension}`);
|
||||
if (destinations.includes(path)) throw validationError("渲染输出不能覆盖报告源文件。");
|
||||
for (const destination of destinations) checkOutput(destination, options.overwrite);
|
||||
return withTools(options, async (dir, python) => {
|
||||
const validation = await validateWithTools(path, dir, python);
|
||||
if (!validation.valid) return { file: path, validation, artifacts: [] };
|
||||
// The same pinned marked major as the original renderer, embedded in the CLI instead of downloaded by npx.
|
||||
const bodyFile = join(dir, "body.html");
|
||||
writeFileSync(bodyFile, marked.parse(readFileSync(path, "utf8"), { async: false }));
|
||||
const args = [join(dir, "render.py"), path, "--out", join(dir, "report"), "--body-file", bodyFile,
|
||||
"--format", format, "--width", String(width), "--json"];
|
||||
if (options.chrome) args.push("--chrome", options.chrome);
|
||||
const rendered = z.object({ artifacts: z.array(z.object({ path: z.string(), format: z.string(), bytes: z.number().positive() })) })
|
||||
.parse(await runTool(python, args));
|
||||
// Publish only after the full requested set succeeds; failed rendering leaves existing outputs intact.
|
||||
mkdirSync(dirname(stem), { recursive: true });
|
||||
const artifacts = rendered.artifacts.map((artifact) => {
|
||||
const destination = `${stem}.${artifact.format}`;
|
||||
copyFileSync(artifact.path, destination, options.overwrite ? 0 : constants.COPYFILE_EXCL);
|
||||
return { ...artifact, path: destination };
|
||||
});
|
||||
return { file: path, validation, artifacts };
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { join, resolve } from "node:path";
|
||||
import { isCompiledBinary } from "../../../core/runtime.js";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { resolve } from "node:path";
|
||||
import { validationError } from "../../../core/errors.js";
|
||||
import { BUILTIN_MONTHLY_TEMPLATE, BUILTIN_TEMPLATE_PATH } from "./resources.js";
|
||||
import { describeTemplate } from "./describe.js";
|
||||
import { collectReportData, type ReportData } from "./collect.js";
|
||||
import { renderMonthlyReport, type RenderOptions } from "./render.js";
|
||||
@@ -9,7 +11,7 @@ import { renderMonthlyReport, type RenderOptions } from "./render.js";
|
||||
export type MonthlyReportOptions = {
|
||||
month: string; // YYYY-MM
|
||||
corp: { id: string; name: string };
|
||||
/** 模板路径;缺省用仓内 report-templates/monthly.md */
|
||||
/** 模板路径;缺省用仓内 report-templates/monthly.md,随二进制内嵌 */
|
||||
templatePath?: string;
|
||||
reportId?: string;
|
||||
maxRuns?: number;
|
||||
@@ -31,15 +33,6 @@ export type MonthlyReportResult = {
|
||||
};
|
||||
};
|
||||
|
||||
function defaultTemplatePath(): string {
|
||||
if (isCompiledBinary()) {
|
||||
// 模板不进包;编译产物用 cwd(与 rules lint --file 的相对路径解析一致)
|
||||
return join(process.cwd(), "report-templates", "monthly.md");
|
||||
}
|
||||
// dev: src/domains/seal/reports → 仓库根
|
||||
return join(import.meta.dirname, "..", "..", "..", "..", "report-templates", "monthly.md");
|
||||
}
|
||||
|
||||
/** 一次调用产出填充好的月度报告 Markdown。模板皮与数据骨解耦:见 describe.ts。 */
|
||||
export async function buildMonthlyReport(
|
||||
client: KyInstance,
|
||||
@@ -47,14 +40,14 @@ export async function buildMonthlyReport(
|
||||
): Promise<MonthlyReportResult> {
|
||||
const templatePath = options.templatePath
|
||||
? resolve(options.templatePath)
|
||||
: defaultTemplatePath();
|
||||
if (!existsSync(templatePath)) {
|
||||
throw new Error(
|
||||
: BUILTIN_TEMPLATE_PATH;
|
||||
if (options.templatePath && !existsSync(templatePath)) {
|
||||
throw validationError(
|
||||
`未找到报告模板: ${templatePath}\n` +
|
||||
`可用 --template <file> 指定路径,或在 report-templates/ 目录下运行。`
|
||||
`可用 --template <file> 指定路径,或省略 --template 使用内置模板。`
|
||||
);
|
||||
}
|
||||
const template = readFileSync(templatePath, "utf8");
|
||||
const template = options.templatePath ? readFileSync(templatePath, "utf8") : BUILTIN_MONTHLY_TEMPLATE;
|
||||
const plans = describeTemplate(template);
|
||||
|
||||
const demands = new Set(plans.flatMap((plan) => plan.demands));
|
||||
@@ -64,13 +57,13 @@ export async function buildMonthlyReport(
|
||||
maxRuns: options.maxRuns
|
||||
});
|
||||
|
||||
const reportId = options.reportId ?? `RPT-${options.month.replace("-", "")}-${randomBytes(3).toString("hex").toUpperCase()}`;
|
||||
const renderOptions: RenderOptions = {
|
||||
reportId: options.reportId,
|
||||
reportId,
|
||||
corpName: options.corp.name
|
||||
};
|
||||
const content = renderMonthlyReport(template, data, plans, renderOptions);
|
||||
|
||||
const reportId = options.reportId ?? `RPT-${options.month.replace("-", "")}-XXXXXX`;
|
||||
return {
|
||||
month: options.month,
|
||||
corpId: options.corp.id,
|
||||
@@ -84,8 +77,8 @@ export async function buildMonthlyReport(
|
||||
notes: data.notes,
|
||||
content,
|
||||
next: {
|
||||
validate: `python3 tools/validate.py <报告文件.md>(校验器与渲染器见 ai-audit-report-template 仓库)`,
|
||||
render: `python3 tools/render.py <报告文件.md> -o build/<报告文件>(产出 HTML / PNG / A4 PDF 三件套)`
|
||||
validate: "seal-use report validate <报告文件.md>",
|
||||
render: "seal-use report render <报告文件.md> --out build/<报告文件>"
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import monthly from "../../../../report-templates/monthly.md" with { type: "text" };
|
||||
import validate from "../../../../report-templates/validate.py" with { type: "text" };
|
||||
import render from "../../../../report-templates/render.py" with { type: "text" };
|
||||
import accuracy from "../../../../report-templates/assets/图1-准确率对比.svg" with { type: "text" };
|
||||
import benefits from "../../../../report-templates/assets/图2-综合效益.svg" with { type: "text" };
|
||||
import screenshot from "../../../../report-templates/assets/图3-示例截图.svg" with { type: "text" };
|
||||
|
||||
// Git owns the source files; Bun embeds these imports in both developer and release binaries.
|
||||
// Loading the built-in template never depends on cwd, a checkout, or skill installation.
|
||||
export const BUILTIN_TEMPLATE_PATH = "builtin:report-templates/monthly.md";
|
||||
export const BUILTIN_MONTHLY_TEMPLATE = monthly;
|
||||
export const REPORT_SCRIPTS = { "validate.py": validate, "render.py": render };
|
||||
export const REPORT_ASSETS: Record<string, string> = {
|
||||
"assets/图1-准确率对比.svg": accuracy,
|
||||
"assets/图2-综合效益.svg": benefits,
|
||||
"assets/图3-示例截图.svg": screenshot
|
||||
};
|
||||
Reference in new issue
Block a user