diff --git a/src/cli/commands/report.ts b/src/cli/commands/report.ts index 31ce4c9..bcb599e 100644 --- a/src/cli/commands/report.ts +++ b/src/cli/commands/report.ts @@ -116,7 +116,8 @@ export async function handleReportCommand( month, 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) + maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns), + allowUnreviewed: booleanOption(args.options["allow-unreviewed"]) ?? booleanOption(args.options.force) } ) as MonthlyReportResult; const out = stringOption(args.options.out) ?? stringOption(args.options.o); diff --git a/src/cli/help.ts b/src/cli/help.ts index 6d79b9a..6f6d30c 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -657,14 +657,15 @@ export const HELP_REGISTRY: AreaHelp[] = [ name: "monthly", aliases: ["month"], summary: "Fill the monthly report template with performance, risk, and approval-run data", - usage: ["seal-use report monthly --month [--out <报告.md>] [--template ] [--report-id ] [--max-runs ] [--corp ]"], + usage: ["seal-use report monthly --month [--out <报告.md>] [--template ] [--report-id ] [--max-runs ] [--allow-unreviewed] [--corp ]"], options: [ { flag: "--month ", description: "Statistics month, e.g. 2026-08 (required)" }, { flag: "--template ", description: "Custom template Markdown path; defaults to the Git-managed template embedded in the binary, independent of cwd" }, { flag: "--out ", 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 ", description: "Custom report id; defaults to RPT--" }, - { flag: "--max-runs ", description: "Cap approval-run detail fetch, default 500 (max 500)" } + { flag: "--max-runs ", 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." }, diff --git a/src/cli/parser.ts b/src/cli/parser.ts index 4738cd3..ae355c7 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -23,7 +23,7 @@ import { usageError } from "./errors.js"; // Read with booleanOption(...) / Boolean(...) / presence check. export const BOOLEAN_FLAGS = new Set([ - "V", "add", "all", "as-hose", "attachments", "auto", + "V", "add", "all", "allow-unreviewed", "allowUnreviewed", "as-hose", "attachments", "auto", "auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only", "completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache", "download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled", @@ -86,7 +86,7 @@ export const VALUE_FLAGS = new Set([ // Registered flags. Unknown flags are rejected. export const KNOWN_FLAGS = new Set([ - "V", "access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "add", "all", "app-key", + "V", "access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "add", "all", "allow-unreviewed", "allowUnreviewed", "app-key", "app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto", "auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId", "bg-save", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome", diff --git a/src/domains/seal/capabilities/reports.ts b/src/domains/seal/capabilities/reports.ts index a53455a..1bf2372 100644 --- a/src/domains/seal/capabilities/reports.ts +++ b/src/domains/seal/capabilities/reports.ts @@ -24,11 +24,15 @@ export const reportCapabilities = [ .positive() .max(500) .optional() - .describe("拉取审批运行明细分块的上限,默认 500") + .describe("拉取审批运行明细分块的上限,默认 500"), + allowUnreviewed: z + .boolean() + .optional() + .describe("是否跳过前置裁决门禁(当存在未裁决的分歧单时强行出具草稿,默认 false)") }), handler: async ( client: KyInstance, - params: { month: string; templatePath?: string; reportId?: string; maxRuns?: number }, + params: { month: string; templatePath?: string; reportId?: string; maxRuns?: number; allowUnreviewed?: boolean }, context: CapabilityContext ) => buildMonthlyReport(client, { @@ -36,7 +40,8 @@ export const reportCapabilities = [ corp: { id: context.corp.id, name: context.corp.name }, templatePath: params.templatePath, reportId: params.reportId, - maxRuns: params.maxRuns + maxRuns: params.maxRuns, + allowUnreviewed: params.allowUnreviewed }) }, { diff --git a/src/domains/seal/reports/export/ledger.ts b/src/domains/seal/reports/export/ledger.ts index 43d7aab..e314b20 100644 --- a/src/domains/seal/reports/export/ledger.ts +++ b/src/domains/seal/reports/export/ledger.ts @@ -20,9 +20,10 @@ function formatVerdict(block: ReportBlock): string { if (block.agreement === "unknown") return "待人工审批完结"; const v = block.verdict; if (v === "both_correct" || (!v && block.agreement === "agreed")) return "双方一致正确 (D1/D2)"; - if (v === "ai_correct" || (!v && block.agreement === "diverged")) return "AI 依规正确 / 人工失准 (D4)"; + if (v === "ai_correct") return "AI 依规正确 / 人工失准 (D4)"; if (v === "human_correct") return "人工合理 / AI 失准"; if (v === "both_wrong") return "双方均失准"; + if (v === "undecided") return "存疑待定"; return "待复核"; } diff --git a/src/domains/seal/reports/pipeline/monthly.ts b/src/domains/seal/reports/pipeline/monthly.ts index bf7c28f..28a237d 100644 --- a/src/domains/seal/reports/pipeline/monthly.ts +++ b/src/domains/seal/reports/pipeline/monthly.ts @@ -2,7 +2,7 @@ import type { KyInstance } from "ky"; import { existsSync, readFileSync } from "node:fs"; import { randomBytes } from "node:crypto"; import { resolve } from "node:path"; -import { validationError } from "../../../../core/errors.js"; +import { CliError, validationError } from "../../../../core/errors.js"; import { BUILTIN_MONTHLY_TEMPLATE, BUILTIN_TEMPLATE_PATH } from "../templates/resources.js"; import { describeTemplate } from "./describe.js"; import { collectReportData, type ReportData } from "./collect.js"; @@ -18,6 +18,8 @@ export type MonthlyReportOptions = { templatePath?: string; reportId?: string; maxRuns?: number; + /** 是否跳过前置裁决门禁(当存在未裁决的分歧单时强行出具草稿,默认 false) */ + allowUnreviewed?: boolean; }; export type MonthlyReportResult = { @@ -67,6 +69,22 @@ export async function buildMonthlyReport( maxRuns: options.maxRuns }); + const unreviewedDiverged = data.blocks.filter( + (b) => b.agreement === "diverged" && !b.verdict + ); + if (unreviewedDiverged.length > 0 && !options.allowUnreviewed) { + const snList = unreviewedDiverged.slice(0, 3).map((b) => b.sn).join(", "); + const more = unreviewedDiverged.length > 3 ? ` 等共 ${unreviewedDiverged.length} 笔` : ""; + 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` + + `(若确需生成未定稿的内部预览草稿,请添加 --allow-unreviewed 参数继续)。`, + 1, + `seal-use report data --month ${options.month} --corp ${options.corp.id}` + ); + } + const reportId = options.reportId ?? `RPT-${options.month.replace("-", "")}-${randomBytes(3).toString("hex").toUpperCase()}`; const renderOptions: RenderOptions = { reportId, diff --git a/src/domains/seal/reports/pipeline/reports.test.ts b/src/domains/seal/reports/pipeline/reports.test.ts index 3ad0c0c..b5deecd 100644 --- a/src/domains/seal/reports/pipeline/reports.test.ts +++ b/src/domains/seal/reports/pipeline/reports.test.ts @@ -8,6 +8,7 @@ import { renderMonthlyReport } from "./render.js"; import { loadReviews, writeReview, reviewFilePath } from "./review-store.js"; import { buildReportLedgerCsv, buildReportLedgerXlsx } from "../export/ledger.js"; import { getMonthlyReportData } from "./data.js"; +import { buildMonthlyReport } from "./monthly.js"; const TEMPLATE = join(import.meta.dirname, "..", "templates", "monthly.md"); @@ -424,6 +425,30 @@ describe("getMonthlyReportData", () => { expect(data.nextActions.reviewSet).toContain("seal-use report review set"); expect(data.nextActions.validate).toBe("seal-use report validate <报告文件.md>"); }); + + test("blocks buildMonthlyReport when unreviewed diverged runs exist", async () => { + const runs = [ + { id: "r1", sourceDocumentSN: "DIVERGED-01", result: { decision: "同意" }, pipelineData: { humanResult: "驳回" } } + ]; + const fakeClient = { + get: async () => ({ json: async () => ({ data: { records: runs, total: 1 } }) }) + } as never; + + await expect( + buildMonthlyReport(fakeClient, { + month: "2026-08", + corp: { id: "corp-gate-test", name: "门禁测试企业" } + }) + ).rejects.toThrow("前置业务门禁拦截:检测到 1 笔人机分歧单据尚未完成复核裁决"); + + // With allowUnreviewed: true, it should bypass the gate + const draft = await buildMonthlyReport(fakeClient, { + month: "2026-08", + corp: { id: "corp-gate-test", name: "门禁测试企业" }, + allowUnreviewed: true + }); + expect(draft.content).toBeDefined(); + }); }); diff --git a/src/domains/seal/reports/validate/validate.test.ts b/src/domains/seal/reports/validate/validate.test.ts index db5b528..184b9f0 100644 --- a/src/domains/seal/reports/validate/validate.test.ts +++ b/src/domains/seal/reports/validate/validate.test.ts @@ -63,4 +63,14 @@ describe("native report validator", () => { expect(check(valid + "\n1、2、70\n$$\\frac{1}{2} = 70\\%$$\n").issues).toContainEqual(expect.objectContaining({ code: "NM005" })) expect(check(valid + "\n$$123456$$\n").issues).toContainEqual(expect.objectContaining({ code: "NM005", message: "公式中的数值 123456 在正文别处找不到,可能与数据脱节" })) }) + test("checks companion ledger CSV and blocks when unreviewed records exist", () => { + const dir = mkdtempSync(join(tmpdir(), "validate-ledger-")) + dirs.push(dir) + const md = join(dir, "报告.md") + writeFileSync(md, valid) + writeFileSync(join(dir, "报告-明细台账.csv"), "SN,单据模板,人机一致性,复核定性结论\nS1,对公,分歧,待复核\n") + const res = validateReportDocument(md) + expect(res.valid).toBe(false) + expect(res.issues).toContainEqual(expect.objectContaining({ code: "LD001" })) + }) }) diff --git a/src/domains/seal/reports/validate/validate.ts b/src/domains/seal/reports/validate/validate.ts index 250ec32..a7ad9e7 100644 --- a/src/domains/seal/reports/validate/validate.ts +++ b/src/domains/seal/reports/validate/validate.ts @@ -196,5 +196,25 @@ export function validateReportDocument(file: string): ReportValidation { if (!outside.includes(token)) error("NM005", `公式中的数值 ${token} 在正文别处找不到,可能与数据脱节`) } } + + // 6. 配套台账勾稽门禁(若同目录下存在配套交付的明细台账 CSV) + const baseStem = path.replace(/\.md$/, "") + const ledgerCsvPath = existsSync(`${baseStem}-明细台账.csv`) + ? `${baseStem}-明细台账.csv` + : existsSync(resolve(dirname(path), "明细台账.csv")) + ? resolve(dirname(path), "明细台账.csv") + : null + + if (ledgerCsvPath) { + const csvContent = readFileSync(ledgerCsvPath, "utf8") + const csvRows = csvContent.trim().split("\n").slice(1) + const unreviewedRows = csvRows.filter((r) => + r.split(",").map((c) => c.replace(/^["'\s]+|["'\s]+$/g, "")).includes("待复核") + ) + if (unreviewedRows.length > 0) { + error("LD001", `配套台账(${ledgerCsvPath.split("/").pop()})中存在 ${unreviewedRows.length} 笔未裁决单据(标记为「待复核」),正式交付前必须完成全量裁决`) + } + } + return report }