Refine report pipeline to support date ranges and recordId reviews

This commit is contained in:
gitea committed 2026-10-16 14:56:11 +08:00
1 parent 64680cd4a0
commit 077ecb050c
11 files changed
+552 -164

No files matched your search

+63 -19
View File
@@ -78,7 +78,7 @@ export async function handleLocalReportCommand(action: "validate" | "render" | "
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成渲染产物。请按 validation.issues 修正后重试。", 1);
}
/** `seal-use report monthly` / `data` — 月度 AI 审核报告。 */
/** `seal-use report generate` / `data` — AI 审核报告。 */
export async function handleReportCommand(
action: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
@@ -86,16 +86,35 @@ export async function handleReportCommand(
args: ParsedArgs
) {
if (action === "data") {
const startDate =
stringOption(args.options["start-date"]) ??
stringOption(args.options.startDate) ??
stringOption(args.options.start) ??
stringOption(args.options.since);
const endDate =
stringOption(args.options["end-date"]) ??
stringOption(args.options.endDate) ??
stringOption(args.options.end) ??
stringOption(args.options.until);
const month = stringOption(args.options.month);
if (!month) {
throw new Error("Usage: seal-use report data --month <YYYY-MM> [--max-runs <n>] [--corp <corpId>]");
if ((!startDate || !endDate) && !month) {
throw usageError(
"Usage: seal-use report data --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--max-runs <n>] [--corp <corpId>]"
);
}
const templates = stringOption(args.options.templates)?.split(/[,;]+/).map((s) => s.trim()).filter(Boolean);
const result = await runCapabilityResult(
"sealReportDataGet",
client,
corp,
{
startDate,
endDate,
month,
templates,
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
}
);
@@ -103,17 +122,36 @@ export async function handleReportCommand(
return;
}
if (action === "monthly" || action === "month") {
if (action === "monthly" || action === "month" || action === "generate") {
const startDate =
stringOption(args.options["start-date"]) ??
stringOption(args.options.startDate) ??
stringOption(args.options.start) ??
stringOption(args.options.since);
const endDate =
stringOption(args.options["end-date"]) ??
stringOption(args.options.endDate) ??
stringOption(args.options.end) ??
stringOption(args.options.until);
const month = stringOption(args.options.month);
if (!month) {
throw new Error("Usage: seal-use report monthly --month <YYYY-MM> [--template <file>] [--report-id <RPT-...>] [--corp <corpId>]");
if ((!startDate || !endDate) && !month) {
throw usageError(
"Usage: seal-use report generate --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--template <file>] [--report-id <RPT-...>] [--corp <corpId>]"
);
}
const templates = stringOption(args.options.templates)?.split(/[,;]+/).map((s) => s.trim()).filter(Boolean);
const result = await runCapabilityResult(
"sealReportMonthlyGet",
client,
corp,
{
startDate,
endDate,
month,
templates,
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),
@@ -141,17 +179,14 @@ export async function handleReportCommand(
if (action === "review") {
const sub = args.command[2]; // set | list
const month = stringOption(args.options.month);
if (!month) {
throw new Error("Usage: seal-use report review <set|list> --month <YYYY-MM> [--sn <SN> --verdict <v>] [--corp <corpId>]");
}
if (sub === "list") {
const reviews = loadReviews(corp.id, month);
const scope = stringOption(args.options.month) ?? stringOption(args.options.scope);
const reviews = loadReviews(corp.id, scope);
printJson({
corpId: corp.id,
month,
file: reviewFilePath(corp.id, month),
...(scope ? { month: scope } : {}),
file: reviewFilePath(corp.id, scope),
count: reviews.size,
reviews: [...reviews.values()]
});
@@ -159,14 +194,23 @@ export async function handleReportCommand(
}
if (sub === "set") {
const sn = stringOption(args.options.sn) ?? stringOption(args.options["document-sn"]);
const recordId =
stringOption(args.options["record-id"]) ??
stringOption(args.options.recordId) ??
stringOption(args.options.id);
const sn =
stringOption(args.options.sn) ??
stringOption(args.options["document-sn"]);
const verdict = stringOption(args.options.verdict);
if (!sn || !verdict) {
throw new Error(
"Usage: seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"
const month = stringOption(args.options.month) ?? stringOption(args.options.scope);
if ((!recordId && !sn) || !verdict) {
throw usageError(
"Usage: seal-use report review set [--record-id <ID>] [--sn <SN>] --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"
);
}
const record = writeReview(corp.id, {
recordId,
sn,
month,
verdict,
@@ -177,8 +221,8 @@ export async function handleReportCommand(
return;
}
throw new Error(`Unknown report review subcommand: ${sub ?? ""}. Use 'set' or 'list'.`);
throw usageError(`Unknown report review subcommand: ${sub ?? ""}. Use 'set' or 'list'.`);
}
throw new Error(`Unknown report command: ${action ?? ""}. Run 'seal-use report --help' for available commands.`);
throw usageError(`Unknown report command: ${action ?? ""}. Run 'seal-use help report' for available commands.`);
}
+20 -18
View File
@@ -654,20 +654,22 @@ export const HELP_REGISTRY: AreaHelp[] = [
description: "Tenant-free local command: calculates proportions and outputs high-fidelity SVG chart."
},
{
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> [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--allow-unreviewed] [--corp <corpId>]"],
name: "generate",
aliases: ["monthly", "month"],
summary: "Fill the audit report template with performance, risk, and approval-run data",
usage: ["seal-use report generate --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--allow-unreviewed] [--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 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: "--start-date <YYYY-MM-DD>", description: "Statistics start date, YYYY-MM-DD (e.g. 2026-08-12)" },
{ flag: "--end-date <YYYY-MM-DD>", description: "Statistics end date, YYYY-MM-DD (e.g. 2026-09-18)" },
{ flag: "--templates <names>", description: "Comma-separated template whitelist; filters blocks and ledger at source" },
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to the Git-managed template embedded in the binary" },
{ flag: "--out <file>", description: "Save Markdown plus local images and Excel/CSV ledgers beside the report; stdout stays JSON" },
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files" },
{ flag: "--report-id <RPT-...>", description: "Custom report id; defaults to RPT-<YYYYMM>-<random>" },
{ flag: "--report-id <RPT-...>", description: "Custom report id; defaults to RPT-<dateTag>-<random>" },
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" },
{ flag: "--allow-unreviewed", description: "Bypass pre-flight adjudication gate to generate draft when unreviewed diverged runs exist" }
],
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."
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). Generates both Markdown report and companion Excel/CSV ledger."
},
{
name: "validate",
@@ -704,25 +706,25 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "review set",
summary: "Record one human adjudication (who was right: AI or human) for a document",
usage: ["seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <v> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"],
summary: "Record one human adjudication (who was right: AI or human) for an approval run or document",
usage: ["seal-use report review set [--record-id <ID>] [--sn <SN>] --verdict <v> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"],
options: [
{ flag: "--month <YYYY-MM>", description: "Statistics month, YYYY-MM (required)" },
{ flag: "--sn <SN>", description: "Document SN to adjudicate (required)" },
{ flag: "--record-id <ID>", description: "Approval run recordId for exact single-run targeting" },
{ flag: "--sn <SN>", description: "Document SN to adjudicate" },
{ flag: "--verdict <v>", description: "ai_correct | human_correct | both_correct | both_wrong | undecided (required)" },
{ flag: "--note <text>", description: "Optional adjudication note" },
{ flag: "--reviewed-by <who>", description: "Optional reviewer name for the audit trail" }
],
description: "Append-only local JSONL per tenant+month (~/.config/seal-use/state/reviews/). Typically adjudicate diverged blocks (AI != human); report monthly joins these to compute human accuracy. No network: writes only the local store."
description: "Append-only local JSONL per tenant (~/.config/seal-use/state/reviews/). Supports exact recordId target or SN. Typically adjudicates diverged blocks or overrides specific agreed runs."
},
{
name: "review list",
summary: "List human adjudications recorded for a tenant+month",
usage: ["seal-use report review list --month <YYYY-MM> [--corp <corpId>]"],
summary: "List human adjudications recorded for a tenant",
usage: ["seal-use report review list [--corp <corpId>]"],
options: [
{ flag: "--month <YYYY-MM>", description: "Statistics month, YYYY-MM (required)" }
{ flag: "--corp <corpId>", description: "Target enterprise corpId" }
],
description: "Reads the local JSONL store and returns all adjudications keyed by SN."
description: "Reads the local JSONL store and returns all adjudications."
}
]
},
@@ -1263,6 +1263,18 @@ describe("sealCapabilities", () => {
expect(res.divergedRuns[0]?.sn).toBe("SN-001");
expect(res.divergedRuns[0]?.triggeredConditions).toContain("缺失发票");
expect(res.charts.vennSvg).toContain("<svg");
const rangeRes = await handler(mockClient, {
startDate: "2026-08-12",
endDate: "2026-09-18",
templates: ["差旅报销"]
}, fakeContext()) as {
period: { start: string; end: string; label?: string };
templateGroups: Array<{ template: string }>;
};
expect(rangeRes.period.start).toBe("2026-08-12");
expect(rangeRes.period.end).toBe("2026-09-18");
expect(rangeRes.templateGroups[0]?.template).toBe("差旅报销");
});
test("deploy hosecloud configure saves integration and rejects missing customApiUrl", async () => {
+53 -6
View File
@@ -7,12 +7,25 @@ export const reportCapabilities = [
{
name: "sealReportMonthlyGet",
description:
"生成月度 AI 审核准确率报告(Markdown)。按模板结构从效能/风险/审批运行接口取数填充,返回填充后的内容与各章节数据完备度;无法从上游取得的口径(人工准确率、失准原因分类)如实标注而非编造",
"生成 AI 审核准确率报告(Markdown)。按模板结构从效能/风险/审批运行接口取数填充,返回填充后的内容与各章节数据完备度;无法从上游取得的口径(人工准确率、失准原因分类)如实标注而非编造",
parameters: z.object({
startDate: z
.string()
.optional()
.describe("统计起始日期 (YYYY-MM-DD)"),
endDate: z
.string()
.optional()
.describe("统计截止日期 (YYYY-MM-DD)"),
month: z
.string()
.regex(/^\d{4}-\d{2}$/)
.describe("统计月份,YYYY-MM"),
.optional()
.describe("统计月份 (YYYY-MM,可选快捷方式)"),
templates: z
.array(z.string())
.optional()
.describe("单据模板白名单列表(可选,未指定则统计全量单据模板)"),
templatePath: z
.string()
.optional()
@@ -32,11 +45,23 @@ export const reportCapabilities = [
}),
handler: async (
client: KyInstance,
params: { month: string; templatePath?: string; reportId?: string; maxRuns?: number; allowUnreviewed?: boolean },
params: {
startDate?: string;
endDate?: string;
month?: string;
templates?: string[];
templatePath?: string;
reportId?: string;
maxRuns?: number;
allowUnreviewed?: boolean;
},
context: CapabilityContext
) =>
buildMonthlyReport(client, {
startDate: params.startDate,
endDate: params.endDate,
month: params.month,
templates: params.templates,
corp: { id: context.corp.id, name: context.corp.name },
templatePath: params.templatePath,
reportId: params.reportId,
@@ -47,12 +72,25 @@ export const reportCapabilities = [
{
name: "sealReportDataGet",
description:
"获取月度 AI 审核报告的轻量纯结构化数据包(效能指标、分模板统计、风险标签、人机分歧单据列表与单个触发条件)。不依赖 Markdown 模板,供 Agent 交互复核或填充文档",
"获取 AI 审核报告的轻量纯结构化数据包(效能指标、分模板统计、风险标签、人机分歧单据列表与单个触发条件)。不依赖 Markdown 模板,供 Agent 交互复核或填充文档",
parameters: z.object({
startDate: z
.string()
.optional()
.describe("统计起始日期 (YYYY-MM-DD)"),
endDate: z
.string()
.optional()
.describe("统计截止日期 (YYYY-MM-DD)"),
month: z
.string()
.regex(/^\d{4}-\d{2}$/)
.describe("统计月份,YYYY-MM"),
.optional()
.describe("统计月份 (YYYY-MM,可选快捷方式)"),
templates: z
.array(z.string())
.optional()
.describe("单据模板白名单列表(可选,未指定则统计全量单据模板)"),
maxRuns: z
.number()
.int()
@@ -63,11 +101,20 @@ export const reportCapabilities = [
}),
handler: async (
client: KyInstance,
params: { month: string; maxRuns?: number },
params: {
startDate?: string;
endDate?: string;
month?: string;
templates?: string[];
maxRuns?: number;
},
context: CapabilityContext
) =>
getMonthlyReportData(client, {
startDate: params.startDate,
endDate: params.endDate,
month: params.month,
templates: params.templates,
corp: { id: context.corp.id, name: context.corp.name },
maxRuns: params.maxRuns
})
+13 -4
View File
@@ -1,5 +1,6 @@
import ExcelJS from "exceljs";
import type { ReportBlock, ReportData } from "../pipeline/collect.js";
import { ReviewsMap, type ReviewRecord } from "../pipeline/review-store.js";
function csvEscape(val: string | number | undefined): string {
if (val === undefined || val === null) return "";
@@ -28,10 +29,11 @@ function formatVerdict(block: ReportBlock): string {
}
/**
* 构建带 UTF-8 BOM 的月度跑批与人工复核明细台账 CSV
* 构建带 UTF-8 BOM 的跑批与人工复核明细台账 CSV
*/
export function buildReportLedgerCsv(data: ReportData): string {
const headers = [
"审核ID(recordId)",
"单据编号(SN)",
"单据模板",
"单据标题/事由",
@@ -49,8 +51,11 @@ export function buildReportLedgerCsv(data: ReportData): string {
];
const rows = data.blocks.map((block) => {
const review = data.reviews.get(block.sn);
const review = data.reviews instanceof ReviewsMap
? data.reviews.get({ recordId: block.recordId, sn: block.sn })
: (data.reviews as Map<string, ReviewRecord>).get(block.sn);
return [
block.recordId || "—",
block.sn,
block.template || "—",
block.title || "—",
@@ -72,7 +77,7 @@ export function buildReportLedgerCsv(data: ReportData): string {
}
/**
* 构建双 Sheet 的专业月度跑批与复核台账 Excel (.xlsx)
* 构建双 Sheet 的专业跑批与复核台账 Excel (.xlsx)
*/
export async function buildReportLedgerXlsx(data: ReportData): Promise<Buffer> {
const workbook = new ExcelJS.Workbook();
@@ -84,6 +89,7 @@ export async function buildReportLedgerXlsx(data: ReportData): Promise<Buffer> {
});
detailSheet.columns = [
{ header: "审核ID(recordId)", key: "recordId", width: 28 },
{ header: "单据编号(SN)", key: "sn", width: 16 },
{ header: "单据模板", key: "template", width: 20 },
{ header: "单据标题/事由", key: "title", width: 32 },
@@ -107,8 +113,11 @@ export async function buildReportLedgerXlsx(data: ReportData): Promise<Buffer> {
headerRow.height = 24;
for (const block of data.blocks) {
const review = data.reviews.get(block.sn);
const review = data.reviews instanceof ReviewsMap
? data.reviews.get({ recordId: block.recordId, sn: block.sn })
: (data.reviews as Map<string, ReviewRecord>).get(block.sn);
const row = detailSheet.addRow({
recordId: block.recordId || "—",
sn: block.sn,
template: block.template || "—",
title: block.title || "—",
+119 -46
View File
@@ -1,9 +1,10 @@
import type { KyInstance } from "ky";
import * as api from "../../api.js";
import { formatBeijingIso } from "../../../../core/config/timestamps.js";
import { validationError } from "../../../../core/errors.js";
import type { ApprovalRun } from "../../types.js";
import type { ReportDemand } from "./describe.js";
import { loadReviews, type ReviewRecord } from "./review-store.js";
import { loadReviews, ReviewsMap, type ReviewRecord } from "./review-store.js";
/** 单据在决策空间里的极性:同意为正向、驳回/终止为反向,用于比对 AI 与人工是否同向。 */
type Polarity = "pass" | "reject" | "unknown";
@@ -31,7 +32,7 @@ export type ReportBlock = {
aiSummary: string | undefined;
humanComment: string | undefined;
conditions?: string[];
/** 本地人工裁决结论(若该 SN 已 review),来自 review-store */
/** 本地人工裁决结论(来自 review-store,支持 recordId 与 sn 双键匹配) */
verdict?: ReviewRecord["verdict"];
reviewNote?: string;
reviewedBy?: string;
@@ -52,7 +53,7 @@ export type ReportTemplateGroup = {
export type ReportData = {
/** 报告信息表要用的上下文 */
period: { start: string; end: string; month: string };
period: { start: string; end: string; label?: string; month?: string };
corp: { id: string; name: string };
/** 需求 → 是否已按需取数(渲染器据此判断该章节数据完备度) */
fetched: Record<ReportDemand, boolean>;
@@ -71,8 +72,8 @@ export type ReportData = {
};
blocks: ReportBlock[];
templateGroups: ReportTemplateGroup[];
/** 该租户该月的人工裁决(SN → 记录),由 review-store 载入,用于回填人工准确率 */
reviews: Map<string, ReviewRecord>;
/** 该租户的人工裁决集合,由 review-store 载入 */
reviews: ReviewsMap | Map<string, ReviewRecord>;
/** 人工审核准确率(%):仅当本地裁决覆盖样本时有值 */
humanAccuracy?: number;
/** 章节数据完备性标记,渲染时逐节如实写入 */
@@ -88,24 +89,80 @@ export type ReportData = {
};
export type CollectOptions = {
month: string; // YYYY-MM
startDate?: string;
endDate?: string;
month?: string; // 兼容旧单月参数
corp: { id: string; name: string };
/** 单据模板白名单,未指定则拉取全量模板 */
templates?: string[];
/** 用于拉明细分块的上限,防御性封顶 */
maxRuns?: number;
/** 是否载入本地人工裁决(默认载入);关掉则 humanAccuracy 恒为不可得 */
loadReviews?: boolean;
};
function monthRange(month: string): { startDate: string; endDate: string; startIsoDate: string; endIsoDate: string } {
const [y, m] = month.split("-").map(Number);
if (!y || !m) throw new Error(`Invalid month "${month}", expected YYYY-MM`);
const start = Date.UTC(y, m - 1, 1);
const end = Date.UTC(y, m, 1) - 1;
const lastDay = new Date(y, m, 0).getDate();
const pad = (n: number) => String(n).padStart(2, "0");
const startIsoDate = `${y}-${pad(m)}-01`;
const endIsoDate = `${y}-${pad(m)}-${pad(lastDay)}`;
return { startDate: String(start), endDate: String(end), startIsoDate, endIsoDate };
export function resolveReportPeriod(options: {
startDate?: string | number;
endDate?: string | number;
month?: string;
}): {
startDate: string;
endDate: string;
startIsoDate: string;
endIsoDate: string;
startBeijingIso: string;
endBeijingIso: string;
periodLabel: string;
month?: string;
} {
if (options.startDate && options.endDate) {
const sStr = String(options.startDate).slice(0, 10);
const eStr = String(options.endDate).slice(0, 10);
const sTs = Date.parse(`${sStr}T00:00:00+08:00`);
const eTs = Date.parse(`${eStr}T23:59:59.999+08:00`);
if (Number.isNaN(sTs) || Number.isNaN(eTs)) {
throw validationError(`Invalid date range: "${options.startDate}" to "${options.endDate}"`);
}
const startIsoDate = sStr;
const endIsoDate = eStr;
const startBeijingIso = formatBeijingIso(sTs);
const endBeijingIso = formatBeijingIso(eTs);
const periodLabel = `${startIsoDate} ~ ${endIsoDate}`;
const month = startIsoDate.slice(0, 7) === endIsoDate.slice(0, 7) ? startIsoDate.slice(0, 7) : `${startIsoDate.slice(0, 7)}~${endIsoDate.slice(0, 7)}`;
return {
startDate: String(sTs),
endDate: String(eTs),
startIsoDate,
endIsoDate,
startBeijingIso,
endBeijingIso,
periodLabel,
month
};
}
if (options.month) {
const [y, m] = options.month.split("-").map(Number);
if (!y || !m) throw validationError(`Invalid month "${options.month}", expected YYYY-MM`);
const start = Date.UTC(y, m - 1, 1);
const end = Date.UTC(y, m, 1) - 1;
const lastDay = new Date(y, m, 0).getDate();
const pad = (n: number) => String(n).padStart(2, "0");
const startIsoDate = `${y}-${pad(m)}-01`;
const endIsoDate = `${y}-${pad(m)}-${pad(lastDay)}`;
return {
startDate: String(start),
endDate: String(end),
startIsoDate,
endIsoDate,
startBeijingIso: formatBeijingIso(start),
endBeijingIso: formatBeijingIso(end),
periodLabel: `${startIsoDate} ~ ${endIsoDate}`,
month: options.month
};
}
throw validationError("缺少统计起止时间:请指定 startDate 和 endDate(如 2026-08-12 至 2026-09-18)");
}
/** 拉取报告所需数据。只取 demand 需要的部分,模板没提到的章节不发请求。 */
@@ -114,7 +171,7 @@ export async function collectReportData(
demands: Set<ReportDemand>,
options: CollectOptions
): Promise<ReportData> {
const range = monthRange(options.month);
const range = resolveReportPeriod(options);
const maxRuns = Math.min(options.maxRuns ?? 500, 500);
const fetched: Record<ReportDemand, boolean> = {
performance: false,
@@ -126,17 +183,18 @@ export async function collectReportData(
const data: ReportData = {
period: {
start: formatBeijingIso(Number(range.startDate)),
end: formatBeijingIso(Number(range.endDate)),
month: options.month
start: range.startBeijingIso,
end: range.endBeijingIso,
label: range.periodLabel,
month: range.month
},
corp: options.corp,
fetched,
blocks: [],
templateGroups: [],
reviews: options.loadReviews === false
? new Map()
: loadReviews(options.corp.id, options.month),
? new ReviewsMap()
: loadReviews(options.corp.id),
notes: {
humanAccuracyAvailable: false,
failureRateAvailable: false,
@@ -209,7 +267,7 @@ export async function collectReportData(
if (records.length < 100) break;
}
const blocks: ReportBlock[] = runs.map((record) => {
let blocks: ReportBlock[] = runs.map((record) => {
const summary = summarizeLocal(record);
const aiPolarity = polarityOf(summary.aiDecision);
const humanPolarity = polarityOf(summary.humanResult);
@@ -236,6 +294,12 @@ export async function collectReportData(
conditions: summary.conditions
};
});
if (options.templates && options.templates.length > 0) {
const allowed = new Set(options.templates.map((t) => t.trim()));
blocks = blocks.filter((b) => allowed.has(b.template));
}
data.blocks = blocks;
fetched.blocks = true;
} catch {
@@ -244,9 +308,9 @@ export async function collectReportData(
}
data.notes.failureRateAvailable = data.performance !== undefined;
data.notes.mismatchCategoriesAvailable = false; // 失准原因分类默认无上游字段,除非本地复核已全覆盖
data.notes.mismatchCategoriesAvailable = false;
// 4. 人工裁决回填:把本地 review 挂到 blocks,并据此算人工准确率与复核后的 AI 准确率
// 4. 人工裁决回填:支持 recordId 精确匹配与 sn 业务自然键匹配
if (data.reviews.size > 0) {
let reviewed = 0;
let diverged = 0;
@@ -254,48 +318,57 @@ export async function collectReportData(
let humanRight = 0;
let completedCount = 0;
let completedReviewed = 0;
let completedAiRight = 0;
let completedHumanRight = 0;
for (const block of data.blocks) {
if (block.agreement !== "unknown") completedCount += 1;
const review = data.reviews.get(block.sn);
const review = data.reviews instanceof ReviewsMap
? data.reviews.get({ recordId: block.recordId, sn: block.sn })
: data.reviews.get(block.sn);
if (review) {
block.verdict = review.verdict;
block.reviewNote = review.note;
block.reviewedBy = review.reviewedBy;
reviewed += 1;
if (block.agreement === "diverged") diverged += 1;
if (review.verdict === "human_correct" || review.verdict === "both_correct") humanRight += 1;
if (review.verdict === "ai_correct" || review.verdict === "both_correct") aiRight += 1;
if (block.agreement !== "unknown") {
completedReviewed += 1;
if (review.verdict === "human_correct" || review.verdict === "both_correct") completedHumanRight += 1;
if (review.verdict === "ai_correct" || review.verdict === "both_correct") completedAiRight += 1;
}
}
if (block.agreement !== "unknown") {
const v = block.verdict;
if (v === "both_correct" || (!v && block.agreement === "agreed")) {
aiRight += 1;
humanRight += 1;
} else if (v === "ai_correct" || (!v && block.agreement === "diverged")) {
aiRight += 1;
} else if (v === "human_correct") {
humanRight += 1;
}
}
}
if (reviewed > 0) {
const useCompletedScope = completedCount > 0 && completedReviewed >= completedCount;
const denom = useCompletedScope ? completedReviewed : reviewed;
const hRight = useCompletedScope ? completedHumanRight : humanRight;
const aRight = useCompletedScope ? completedAiRight : aiRight;
const divergedCount = data.blocks.filter((b) => b.agreement === "diverged").length;
const unreviewedDiverged = data.blocks.filter((b) => b.agreement === "diverged" && !b.verdict).length;
data.notes.reviewedCount = denom;
data.notes.divergedCount = diverged;
data.humanAccuracy = Number(((hRight / denom) * 100).toFixed(2));
data.notes.humanAccuracyAvailable = true;
data.notes.reviewedCount = completedCount > 0 ? completedCount : reviewed;
data.notes.divergedCount = divergedCount;
// 当本地复核已覆盖全量完结单据时,统一以完结复核口径(D1 + D2 + D4)更新 AI 准确率与有效样本量,消除“分歧单两头扣分”
if (useCompletedScope && data.performance) {
data.performance.approvalCount = denom;
data.performance.accuracy = Number(((aRight / denom) * 100).toFixed(2));
data.notes.mismatchCategoriesAvailable = true;
if (completedCount > 0) {
data.humanAccuracy = Number(((humanRight / completedCount) * 100).toFixed(2));
data.notes.humanAccuracyAvailable = true;
if (unreviewedDiverged === 0 && data.performance) {
data.performance.approvalCount = completedCount;
data.performance.accuracy = Number(((aiRight / completedCount) * 100).toFixed(2));
data.notes.mismatchCategoriesAvailable = true;
}
}
}
}
// 5. 分模板统计(在 review 挂载后聚合,以便携带分模板的 AI/人工准确率与同意:驳回比例)
// 5. 分模板统计(在 review 挂载后聚合,携带分模板的 AI/人工准确率)
if (demands.has("templateGroups") && data.blocks.length > 0) {
const byTemplate = new Map<string, ReportTemplateGroup>();
for (const block of data.blocks) {
+22 -10
View File
@@ -2,17 +2,23 @@ import type { KyInstance } from "ky";
import { collectReportData } from "./collect.js";
import { renderVennAccuracySvg } from "../charts/venn.js";
export type MonthlyReportDataOptions = {
month: string; // YYYY-MM
export type ReportDataOptions = {
startDate?: string;
endDate?: string;
month?: string;
corp: { id: string; name: string };
templates?: string[];
maxRuns?: number;
};
export type MonthlyReportDataOptions = ReportDataOptions;
export type MonthlyReportDataResult = {
period: {
month: string;
start: string;
end: string;
label?: string;
month?: string;
};
corp: {
id: string;
@@ -100,12 +106,12 @@ export type MonthlyReportDataResult = {
};
/**
* 获取月度报告的纯结构化数据包。
* 获取审核报告的纯结构化数据包。
* 不依赖 Markdown 模板,输出统一可直接消费的业务指标、分模板统计、待裁决分歧单据池与维恩图资产。
*/
export async function getMonthlyReportData(
client: KyInstance,
options: MonthlyReportDataOptions
options: ReportDataOptions
): Promise<MonthlyReportDataResult> {
const demands = new Set<"performance" | "riskStats" | "riskDetails" | "blocks" | "templateGroups">([
"performance",
@@ -116,8 +122,11 @@ export async function getMonthlyReportData(
]);
const data = await collectReportData(client, demands, {
startDate: options.startDate,
endDate: options.endDate,
month: options.month,
corp: options.corp,
templates: options.templates,
maxRuns: options.maxRuns
});
@@ -192,7 +201,7 @@ export async function getMonthlyReportData(
const templateGroups = data.templateGroups.map((g) => {
const evaluated = g.evaluated ?? g.total;
const aiAccuracy = evaluated > 0 && g.aiCorrect !== undefined ? Number(((g.aiCorrect / evaluated) * 100).toFixed(2)) : undefined;
const groupAiAccuracy = evaluated > 0 && g.aiCorrect !== undefined ? Number(((g.aiCorrect / evaluated) * 100).toFixed(2)) : undefined;
const humanAccuracy = evaluated > 0 && g.humanCorrect !== undefined ? Number(((g.humanCorrect / evaluated) * 100).toFixed(2)) : undefined;
const automationRate = g.total > 0 ? Number(((g.agreed / g.total) * 100).toFixed(2)) : undefined;
const bothAccurateRate = evaluated > 0 && g.bothCorrect !== undefined ? Number(((g.bothCorrect / evaluated) * 100).toFixed(2)) : undefined;
@@ -206,7 +215,7 @@ export async function getMonthlyReportData(
evaluated,
agreed: g.agreed,
diverged: g.diverged,
aiAccuracy,
aiAccuracy: groupAiAccuracy,
humanAccuracy,
automationRate,
humanPassRatio,
@@ -262,7 +271,8 @@ export async function getMonthlyReportData(
period: {
month: data.period.month,
start: data.period.start.slice(0, 10),
end: data.period.end.slice(0, 10)
end: data.period.end.slice(0, 10),
label: data.period.label
},
corp: data.corp,
metrics: {
@@ -296,10 +306,12 @@ export async function getMonthlyReportData(
vennSvg
},
nextActions: {
reviewSet: `seal-use report review set --month ${data.period.month} --sn <SN> --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> --corp ${data.corp.id}`,
reviewList: `seal-use report review list --month ${data.period.month} --corp ${data.corp.id}`,
reviewSet: `seal-use report review set --sn <SN> --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> --corp ${data.corp.id}`,
reviewList: `seal-use report review list --corp ${data.corp.id}`,
validate: "seal-use report validate <报告文件.md>",
render: "seal-use report render <报告文件.md> --out build/<报告文件>"
}
};
}
export const getReportData = getMonthlyReportData;
+26 -9
View File
@@ -11,9 +11,13 @@ import { renderMonthlyReport, type RenderOptions } from "./render.js";
import { renderVennAccuracySvg } from "../charts/venn.js";
import { buildReportLedgerCsv, buildReportLedgerXlsx } from "../export/ledger.js";
export type MonthlyReportOptions = {
month: string; // YYYY-MM
export type ReportOptions = {
startDate?: string;
endDate?: string;
month?: string; // 兼容旧单月参数
corp: { id: string; name: string };
/** 单据模板白名单列表(可选,未指定则拉取全量模板) */
templates?: string[];
/** 模板路径;缺省用仓内内置 monthly.md,随二进制内嵌 */
templatePath?: string;
reportId?: string;
@@ -22,8 +26,11 @@ export type MonthlyReportOptions = {
allowUnreviewed?: boolean;
};
export type MonthlyReportOptions = ReportOptions;
export type MonthlyReportResult = {
month: string;
period: ReportData["period"];
month?: string;
corpId: string;
reportId: string;
templatePath: string;
@@ -45,10 +52,10 @@ export type MonthlyReportResult = {
};
};
/** 一次调用产出填充好的月度报告 Markdown。模板皮与数据骨解耦:见 describe.ts。 */
/** 一次调用产出填充好的审核报告 Markdown。模板皮与数据骨解耦:见 describe.ts。 */
export async function buildMonthlyReport(
client: KyInstance,
options: MonthlyReportOptions
options: ReportOptions
): Promise<MonthlyReportResult> {
const templatePath = options.templatePath
? resolve(options.templatePath)
@@ -64,8 +71,11 @@ export async function buildMonthlyReport(
const demands = new Set(plans.flatMap((plan) => plan.demands));
const data = await collectReportData(client, demands, {
startDate: options.startDate,
endDate: options.endDate,
month: options.month,
corp: options.corp,
templates: options.templates,
maxRuns: options.maxRuns
});
@@ -75,17 +85,21 @@ export async function buildMonthlyReport(
if (unreviewedDiverged.length > 0 && !options.allowUnreviewed) {
const snList = unreviewedDiverged.slice(0, 3).map((b) => b.sn).join(", ");
const more = unreviewedDiverged.length > 3 ? ` 等共 ${unreviewedDiverged.length} 笔` : "";
const periodArg = options.startDate && options.endDate
? `--start-date ${options.startDate} --end-date ${options.endDate}`
: options.month ? `--month ${options.month}` : "";
throw new CliError(
`前置业务门禁拦截:检测到 ${unreviewedDiverged.length} 笔人机分歧单据尚未完成复核裁决(如 ${snList}${more})。\n` +
`为保证报告结论的真实性与合规性,出具正式报告前必须完成人机分歧裁决。\n` +
`请先执行 'seal-use report data --month ${options.month} --corp ${options.corp.id}' 审查分歧单据,并使用 'seal-use report review set' 录入裁决结论。\n` +
`请先执行 'seal-use report data ${periodArg} --corp ${options.corp.id}' 审查分歧单据,并使用 'seal-use report review set' 录入裁决结论。\n` +
`(若确需生成未定稿的内部预览草稿,请添加 --allow-unreviewed 参数继续)。`,
1,
`seal-use report data --month ${options.month} --corp ${options.corp.id}`
`seal-use report data ${periodArg} --corp ${options.corp.id}`
);
}
const reportId = options.reportId ?? `RPT-${options.month.replace("-", "")}-${randomBytes(3).toString("hex").toUpperCase()}`;
const dateTag = (data.period.month || `${data.period.start.slice(0, 10)}_${data.period.end.slice(0, 10)}`).replace(/[-~]/g, "");
const reportId = options.reportId ?? `RPT-${dateTag}-${randomBytes(3).toString("hex").toUpperCase()}`;
const renderOptions: RenderOptions = {
reportId,
corpName: options.corp.name
@@ -124,7 +138,8 @@ export async function buildMonthlyReport(
}
return {
month: options.month,
period: data.period,
month: data.period.month,
corpId: options.corp.id,
reportId,
templatePath,
@@ -143,3 +158,5 @@ export async function buildMonthlyReport(
}
};
}
export const buildReport = buildMonthlyReport;
+8 -4
View File
@@ -55,7 +55,8 @@ export function renderMonthlyReport(
plans: SectionPlan[],
options: RenderOptions = {}
): string {
const reportId = options.reportId ?? `RPT-${data.period.month.replace("-", "")}-${randomSuffix()}`;
const dateTag = (data.period.month || `${data.period.start.slice(0, 10)}_${data.period.end.slice(0, 10)}`).replace(/[-~]/g, "");
const reportId = options.reportId ?? `RPT-${dateTag}-${randomSuffix()}`;
const corpName = options.corpName ?? data.corp.name;
const generatedAt = options.generatedAt ?? beijingToday();
const ctx: FillContext = { reportId, corpName, generatedAt, reportStatus: options.reportStatus };
@@ -103,7 +104,7 @@ export function renderMonthlyReport(
// 报告信息表:统计期间与生成日期按真实统计口径补齐
result = result.replace(
/(\| 统计期间 \| )[^\n|]+/,
`$1${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)}`
`$1${data.period.label || `${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)}`}`
);
result = result.replace(/(\| 生成日期 \| )[^\n|]+/, `$1${ctx.generatedAt}`);
return result;
@@ -111,11 +112,14 @@ export function renderMonthlyReport(
function fillInline(text: string, data: ReportData, ctx: FillContext): string {
let result = text;
const monthNum = parseInt(data.period.month.slice(5), 10);
const monthNum = data.period.month ? parseInt(data.period.month.slice(5), 10) : NaN;
const monthStr = Number.isFinite(monthNum) ? `${monthNum}月` : "";
if (monthStr) {
result = result.replace(/# 【[^】]+】\d+月AI审核准确率报告/, `# 【${ctx.corpName}】${monthStr}AI审核准确率报告`);
result = result.replace(/《\d+月单据审批质量审计报告_全量看板\.xlsx》/g, `《${monthStr}单据审批质量审计报告_全量看板.xlsx》`);
} else {
result = result.replace(/# 【[^】]+】\d+月AI审核准确率报告/, `# 【${ctx.corpName}】AI审核准确率报告`);
result = result.replace(/《\d+月单据审批质量审计报告_全量看板\.xlsx》/g, "《单据审批质量审计报告_全量看板.xlsx》");
}
result = result.replace(/【[^】]+】(?=\S*月)/, `【${ctx.corpName}】`);
result = result.replaceAll("模板企业", ctx.corpName);
@@ -440,7 +444,7 @@ function replacementRows(
: (dist ? `(${dist})` : "");
return [
["数据来源", "客户授权的已完成历史审批单据"],
["统计期间", `${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)} 期间单据`],
["统计期间", `${data.period.label || `${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)}`} 期间单据`],
["单据模板", data.templateGroups.length
? `涵盖 ${data.templateGroups.map((g) => g.template).slice(0, 6).join("、")} 等 **${data.templateGroups.length} 类**业务单据模板`
: "*(单据模板分布待取数)*"],
@@ -339,7 +339,7 @@ describe("review store + human accuracy join", () => {
expect(data.humanAccuracy).toBe(50);
const csv = buildReportLedgerCsv(data);
expect(csv.startsWith("\uFEFF单据编号(SN),单据模板")).toBe(true);
expect(csv.startsWith("\uFEFF审核ID(recordId),单据编号(SN),单据模板")).toBe(true);
expect(csv).toContain("对公付款");
expect(csv).toContain("张山具体的报销单标题A");
@@ -490,6 +490,105 @@ describe("getMonthlyReportData", () => {
expect(out).toContain("华南大区");
expect(out).toContain("缺失要求凭证");
});
test("supports custom date range (e.g. 2026-08-12 to 2026-09-18) without month constraint", async () => {
let calledStart = "";
let calledEnd = "";
const fakeClient = {
get: async (_url: string, opts?: { searchParams?: URLSearchParams }) => {
calledStart = opts?.searchParams?.get("startDate") ?? "";
calledEnd = opts?.searchParams?.get("endDate") ?? "";
return { json: async () => ({ data: { records: [], total: 0 } }) };
},
post: async () => ({ json: async () => ({ data: { approvalCount: 0 } }) })
} as never;
const res = await getMonthlyReportData(fakeClient, {
startDate: "2026-08-12",
endDate: "2026-09-18",
corp: { id: "corp-a", name: "A企业" }
});
expect(res.period.start).toBe("2026-08-12");
expect(res.period.end).toBe("2026-09-18");
expect(res.period.label).toBe("2026-08-12 ~ 2026-09-18");
expect(calledStart).toBe(String(Date.parse("2026-08-12T00:00:00+08:00")));
expect(calledEnd).toBe(String(Date.parse("2026-09-18T23:59:59.999+08:00")));
});
test("filters data.blocks and templateGroups by template whitelist at the source", async () => {
const runs = [
{ id: "r1", sourceDocumentSN: "SN1", result: { decision: "同意" }, pipelineData: { humanResult: "同意" }, document: { fields: [{ key: "specificationId", value: "差旅报销" }] } },
{ id: "r2", sourceDocumentSN: "SN2", result: { decision: "同意" }, pipelineData: { humanResult: "同意" }, document: { fields: [{ key: "specificationId", value: "采购付款" }] } },
{ id: "r3", sourceDocumentSN: "SN3", result: { decision: "同意" }, pipelineData: { humanResult: "同意" }, document: { fields: [{ key: "specificationId", value: "车辆津贴" }] } },
{ id: "r4", sourceDocumentSN: "SN4", result: { decision: "同意" }, pipelineData: { humanResult: "同意" }, document: { fields: [{ key: "specificationId", value: "招待费报销" }] } }
];
const fakeClient = {
get: async () => ({ json: async () => ({ data: { records: runs, total: 4 } }) }),
post: async () => ({ json: async () => ({ data: { approvalCount: 4 } }) })
} as never;
// 虽拉到 4 种模板,但指定只保留 2 种
const res = await getMonthlyReportData(fakeClient, {
startDate: "2026-08-12",
endDate: "2026-09-18",
corp: { id: "corp-a", name: "A企业" },
templates: ["差旅报销", "采购付款"]
});
expect(res.templateGroups).toHaveLength(2);
expect(res.templateGroups.map((g) => g.template).sort()).toEqual(["差旅报销", "采购付款"]);
expect(res.agreedRunsSample.every((b) => ["差旅报销", "采购付款"].includes(b.template))).toBe(true);
});
test("reviews by recordId specifically overrides an agreed block to AI correct and decrements human accuracy", async () => {
// 写入裁决:针对 r1 这条运行记录(AI 驳回,人工也驳回),指名道姓覆盖为 AI 正确、人工失准
writeReview("corp-override", {
recordId: "run-both-reject-1",
sn: "SN-AGREED",
verdict: "ai_correct",
note: "人工随口驳回,AI 依据合规条款驳回正确"
});
const runs = [
{
id: "run-both-reject-1",
sourceDocumentSN: "SN-AGREED",
result: { decision: "驳回", summary: "缺少合规凭证" },
pipelineData: { humanResult: "驳回" },
document: { fields: [{ key: "specificationId", value: "费用报销" }] }
},
{
id: "run-both-approve-2",
sourceDocumentSN: "SN-AGREED-2",
result: { decision: "同意" },
pipelineData: { humanResult: "同意" },
document: { fields: [{ key: "specificationId", value: "费用报销" }] }
}
];
const fakeClient = {
get: async () => ({ json: async () => ({ data: { records: runs, total: 2 } }) }),
post: async () => ({ json: async () => ({ data: { approvalCount: 2 } }) })
} as never;
const res = await getMonthlyReportData(fakeClient, {
startDate: "2026-08-12",
endDate: "2026-09-18",
corp: { id: "corp-override", name: "覆写测试企业" }
});
// run-both-reject-1 原本双方一致驳回,被覆盖为 ai_correct:
// AI 准确率 = 2/2 = 100%
// 人工准确率 = 1/2 = 50%
expect(res.metrics.aiAccuracy).toBe(100);
expect(res.metrics.humanAccuracy).toBe(50);
const group = res.templateGroups[0]!;
expect(group.aiAccuracy).toBe(100);
expect(group.humanAccuracy).toBe(50);
});
});
+116 -47
View File
@@ -1,16 +1,16 @@
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { validationError } from "../../../../core/errors.js";
import { SEAL_STATE_DIR } from "../../../../core/paths.js";
/**
* 人工裁决的本地持久化(JSONL,按 租户 × 月份 分片)。
* 人工裁决的本地持久化(JSONL,按租户分片,支持 recordId 与 SN 双键检索)。
*
* 为什么是 JSONL:跨周 review 天然是**追加**场景——每审一批写一批,不整文件重写,
* 为什么是 JSONL:跨周期 review 天然是追加写入场景——每审一批写一批,不整文件重写,
* 避免并发覆盖;单行一条记录,可直接 tail/grep/手改,也可被 CLI 批量导入。
* 为什么按租户+月份分片:租户隔离、月度报告天然对应一个文件、文件不会无限膨胀。
*
* 一条记录 = 一个 SN 在某个月被人工裁决一次的结果。同一 SN 重复裁决时,
* 以**最后一条**为准(loadReviews 归并时后写覆盖先写)。
* 为什么按租户分片:租户天然数据隔离。
* 标识符规则:优先以具体审核运行 ID(recordId)精确定位单次审核;同时支持单据 SN 作为业务自然键。
* 后写覆盖先写。
*/
/** 人工裁决结论:谁对。both_* 覆盖"一致但仍复核"与"分歧后判定双方各有对错"的场景。 */
@@ -22,10 +22,12 @@ export type ReviewVerdict =
| "undecided"; // 已 review 但暂无法判定(保留占位,后续可改判)
export type ReviewRecord = {
/** 合思/源单据 SN(裁决的自然键) */
sn: string;
/** 裁决所属统计月 YYYY-MM(与 report monthly 的 month 对齐) */
month: string;
/** 审核运行记录 ID(精确裁决键) */
recordId?: string;
/** 合思/源单据 SN(业务自然键) */
sn?: string;
/** 裁决所属统计周期或月份(可选留痕) */
month?: string;
verdict: ReviewVerdict;
/** 裁决人(可选,留痕用) */
reviewedBy?: string;
@@ -43,33 +45,72 @@ const VERDICTS: ReadonlySet<string> = new Set([
"undecided"
]);
import { SEAL_STATE_DIR } from "../../../../core/paths.js";
export class ReviewsMap {
readonly byRecordId = new Map<string, ReviewRecord>();
readonly bySn = new Map<string, ReviewRecord>();
readonly records: ReviewRecord[] = [];
set(key: string, record: ReviewRecord): this {
this.records.push(record);
if (record.recordId) this.byRecordId.set(record.recordId, record);
if (record.sn) this.bySn.set(record.sn, record);
if (!record.recordId && !record.sn) {
this.bySn.set(key, record);
}
return this;
}
get(key: { recordId?: string; sn?: string } | string | undefined): ReviewRecord | undefined {
if (!key) return undefined;
if (typeof key === "string") {
return this.byRecordId.get(key) ?? this.bySn.get(key);
}
if (key.recordId && this.byRecordId.has(key.recordId)) {
return this.byRecordId.get(key.recordId);
}
if (key.sn && this.bySn.has(key.sn)) {
return this.bySn.get(key.sn);
}
return undefined;
}
has(key: { recordId?: string; sn?: string } | string): boolean {
return this.get(key) !== undefined;
}
get size(): number {
return new Set([...this.byRecordId.keys(), ...this.bySn.keys()]).size;
}
values(): IterableIterator<ReviewRecord> {
const unique = new Map<string, ReviewRecord>();
for (const r of this.records) {
const id = r.recordId ? `rec:${r.recordId}` : `sn:${r.sn}`;
unique.set(id, r);
}
return unique.values();
}
}
const REVIEWS_DIR_ENV = "SEAL_USE_REVIEWS_DIR";
/** 裁决存储根目录:~/.config/seal-use/state/reviews/(租户 = 文件名前缀)。可用 SEAL_USE_REVIEWS_DIR 覆盖(测试/隔离)。 */
/** 裁决存储根目录:~/.config/seal-use/state/reviews/。可用 SEAL_USE_REVIEWS_DIR 覆盖(测试/隔离)。 */
export function reviewsDir(): string {
const configured = process.env[REVIEWS_DIR_ENV]?.trim();
if (configured) return configured;
return join(SEAL_STATE_DIR, "reviews");
}
/** 分片路径:<reviewsDir>/<corpId>-<YYYY-MM>.jsonl */
export function reviewFilePath(corpId: string, month: string): string {
return join(reviewsDir(), `${sanitizeCorpId(corpId)}-${month}.jsonl`);
/** 分片路径:<reviewsDir>/<corpId>[-<scope>].jsonl */
export function reviewFilePath(corpId: string, scope?: string): string {
const cleanCorp = sanitizeCorpId(corpId);
return scope ? join(reviewsDir(), `${cleanCorp}-${scope}.jsonl`) : join(reviewsDir(), `${cleanCorp}.jsonl`);
}
function sanitizeCorpId(corpId: string): string {
// corpId 可能含路径分隔符等非法字符,压成安全片段
return corpId.replace(/[^a-zA-Z0-9._-]/g, "_");
}
function assertMonth(month: string): void {
if (!/^\d{4}-\d{2}$/.test(month)) {
throw validationError(`Invalid month "${month}", expected YYYY-MM`);
}
}
function assertVerdict(verdict: string): asserts verdict is ReviewVerdict {
if (!VERDICTS.has(verdict)) {
throw validationError(
@@ -79,59 +120,87 @@ function assertVerdict(verdict: string): asserts verdict is ReviewVerdict {
}
/**
* 读取某租户某月的全部裁决,按 SN 归并(同一 SN 后写覆盖先写)。文件不存在返回空 Map。
* 读取某租户的全部裁决。若指定 scope(如月份),则仅读取该分片;否则读取该租户的主文件与各分片文件。按后写覆盖先写。
*/
export function loadReviews(corpId: string, month: string): Map<string, ReviewRecord> {
assertMonth(month);
const filePath = reviewFilePath(corpId, month);
const reviews = new Map<string, ReviewRecord>();
if (!existsSync(filePath)) return reviews;
export function loadReviews(corpId: string, scope?: string): ReviewsMap {
const reviews = new ReviewsMap();
const sanitized = sanitizeCorpId(corpId);
const targetDir = reviewsDir();
if (!existsSync(targetDir)) return reviews;
const lines = readFileSync(filePath, "utf8").split("\n");
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) continue;
const targetFile = reviewFilePath(corpId, scope);
const filesToRead: string[] = [];
if (scope) {
if (existsSync(targetFile)) filesToRead.push(targetFile);
} else {
if (existsSync(targetFile)) filesToRead.push(targetFile);
try {
const parsed = JSON.parse(trimmed) as ReviewRecord;
if (parsed && typeof parsed.sn === "string" && VERDICTS.has(parsed.verdict)) {
reviews.set(parsed.sn, parsed); // 后写覆盖先写
const allFiles = readdirSync(targetDir);
for (const f of allFiles) {
if (f.startsWith(`${sanitized}-`) && f.endsWith(".jsonl")) {
filesToRead.push(join(targetDir, f));
}
}
} catch {
// 跳过损坏行:单行坏数据不应让整个裁决集不可读
}
} catch {}
}
for (const filePath of filesToRead) {
try {
const lines = readFileSync(filePath, "utf8").split("\n");
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) continue;
try {
const parsed = JSON.parse(trimmed) as ReviewRecord;
if (parsed && (parsed.recordId || parsed.sn) && VERDICTS.has(parsed.verdict)) {
reviews.set(parsed.recordId ?? parsed.sn!, parsed);
}
} catch {}
}
} catch {}
}
return reviews;
}
/**
* 追加写一条裁决到磁盘(真正的落盘入口)。corpId 由调用方显式传入(sn 与租户无关,文件按租户分片)。
* 追加写一条裁决到磁盘(支持 recordId 与 sn)。
*/
export function writeReview(
corpId: string,
input: {
sn: string;
month: string;
recordId?: string;
sn?: string;
month?: string;
scope?: string;
verdict: string;
reviewedBy?: string;
note?: string;
recordedAt?: string;
}
): ReviewRecord {
const recordId = input.recordId?.trim();
const sn = input.sn?.trim();
if (!sn) throw validationError("sn is required for a review record");
assertMonth(input.month);
if (!recordId && !sn) {
throw validationError("At least one of recordId or sn is required for a review record");
}
if (input.month && !/^\d{4}-\d{2}$/.test(input.month)) {
throw validationError(`Invalid month "${input.month}", expected YYYY-MM`);
}
assertVerdict(input.verdict);
const record: ReviewRecord = {
sn,
month: input.month,
...(recordId ? { recordId } : {}),
...(sn ? { sn } : {}),
...(input.month ? { month: input.month } : {}),
verdict: input.verdict,
...(input.reviewedBy?.trim() ? { reviewedBy: input.reviewedBy.trim() } : {}),
...(input.note?.trim() ? { note: input.note.trim() } : {}),
recordedAt: input.recordedAt ?? new Date().toISOString().slice(0, 19).replace("T", " ")
};
const filePath = reviewFilePath(corpId, input.month);
const scope = input.scope ?? input.month;
const filePath = reviewFilePath(corpId, scope);
mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 });
appendFileSync(filePath, JSON.stringify(record) + "\n", { encoding: "utf-8", mode: 0o600 });
return record;