Add lightweight report data capability and authoring reference
This commit is contained in:
1 parent
c0af76f692
commit
2177a06f39
17 files changed
+881
-56
No files matched your search
@@ -1,3 +1,5 @@
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { runCapabilityResult } from "../helpers.js";
|
||||
@@ -5,8 +7,10 @@ import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
import { CliError, usageError } from "../../core/errors.js";
|
||||
import {
|
||||
BUILTIN_MONTHLY_TEMPLATE,
|
||||
exportReportPackage,
|
||||
renderReportFile,
|
||||
renderVennAccuracySvg,
|
||||
saveReportMarkdown,
|
||||
validateReportFile,
|
||||
loadReviews,
|
||||
@@ -17,7 +21,35 @@ import {
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
/** Tenant-free commands: dispatch these before resolving enterprise configuration or authentication. */
|
||||
export async function handleLocalReportCommand(action: "validate" | "render" | "export", args: ParsedArgs) {
|
||||
export async function handleLocalReportCommand(action: "validate" | "render" | "export" | "template" | "chart", args: ParsedArgs) {
|
||||
if (action === "template") {
|
||||
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
||||
if (out) {
|
||||
writeFileSync(resolve(out), BUILTIN_MONTHLY_TEMPLATE, "utf8");
|
||||
printJson({ file: resolve(out), size: Buffer.byteLength(BUILTIN_MONTHLY_TEMPLATE) }, outputOptions(args.options));
|
||||
} else {
|
||||
printJson({ content: BUILTIN_MONTHLY_TEMPLATE, size: Buffer.byteLength(BUILTIN_MONTHLY_TEMPLATE) }, outputOptions(args.options));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "chart") {
|
||||
const sub = args.command[2];
|
||||
if (sub !== "venn") throw usageError("Usage: seal-use report chart venn --ai <accuracy> --human <accuracy> [--both <accuracy>] [--out <file.svg>]");
|
||||
const ai = numberOption(args.options.ai) ?? numberOption(args.options["ai-accuracy"]) ?? 92.08;
|
||||
const human = numberOption(args.options.human) ?? numberOption(args.options["human-accuracy"]) ?? 83.33;
|
||||
const both = numberOption(args.options.both) ?? numberOption(args.options["both-accurate"]) ?? 75.42;
|
||||
const svg = renderVennAccuracySvg({ aiAccuracy: ai, humanAccuracy: human, bothAccurate: both });
|
||||
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
||||
if (out) {
|
||||
writeFileSync(resolve(out), svg, "utf8");
|
||||
printJson({ file: resolve(out), format: "svg", aiAccuracy: ai, humanAccuracy: human, bothAccurate: both, size: Buffer.byteLength(svg) }, outputOptions(args.options));
|
||||
} else {
|
||||
printJson({ format: "svg", aiAccuracy: ai, humanAccuracy: human, bothAccurate: both, svg }, outputOptions(args.options));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const file = args.command[2] ?? stringOption(args.options.file);
|
||||
if (!file) throw usageError(`Usage: seal-use report ${action} <报告文件.md>${action === "render" ? " --out <产物路径词干>" : action === "export" ? " --out <目标文件夹>" : ""}`);
|
||||
if ("python" in args.options) throw usageError("报告工具已移除 Python 依赖,请去掉 --python 参数。");
|
||||
@@ -46,13 +78,31 @@ export async function handleLocalReportCommand(action: "validate" | "render" | "
|
||||
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成渲染产物。请按 validation.issues 修正后重试。", 1);
|
||||
}
|
||||
|
||||
/** `seal-use report monthly` — 月度 AI 审核准确率报告(Markdown 填充)。 */
|
||||
/** `seal-use report monthly` / `data` — 月度 AI 审核报告。 */
|
||||
export async function handleReportCommand(
|
||||
action: string | undefined,
|
||||
client: Awaited<ReturnType<typeof createSealClient>>,
|
||||
corp: CorpConfig,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
if (action === "data") {
|
||||
const month = stringOption(args.options.month);
|
||||
if (!month) {
|
||||
throw new Error("Usage: seal-use report data --month <YYYY-MM> [--max-runs <n>] [--corp <corpId>]");
|
||||
}
|
||||
const result = await runCapabilityResult(
|
||||
"sealReportDataGet",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
month,
|
||||
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
|
||||
}
|
||||
);
|
||||
printJson(result, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "monthly" || action === "month") {
|
||||
const month = stringOption(args.options.month);
|
||||
if (!month) {
|
||||
|
||||
@@ -622,6 +622,37 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
title: "Monthly audit accuracy reports",
|
||||
description: "Generate monthly audit reports, validate local Markdown, and export HTML/PNG/PDF.",
|
||||
commands: [
|
||||
{
|
||||
name: "data",
|
||||
summary: "Extract pure structured report data, metrics, diverged runs, and triggers without templates",
|
||||
usage: ["seal-use report data --month <YYYY-MM> [--max-runs <n>] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
|
||||
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" }
|
||||
],
|
||||
description: "Template-free data pack for Agent authoring: returns performance metrics, formula fractions, template groups, top risk tags, diverged runs with exact triggered conditions, and reviews."
|
||||
},
|
||||
{
|
||||
name: "template",
|
||||
summary: "Dump or save the built-in monthly report Markdown template",
|
||||
usage: ["seal-use report template [--out <file.md>]"],
|
||||
options: [
|
||||
{ flag: "--out <file>", description: "Save built-in Markdown template directly to a file" }
|
||||
],
|
||||
description: "Tenant-free local command: returns or saves the built-in monthly.md template so an Agent or user can co-author."
|
||||
},
|
||||
{
|
||||
name: "chart venn",
|
||||
summary: "Generate dynamic Venn accuracy comparison SVG chart independently",
|
||||
usage: ["seal-use report chart venn --ai <acc> --human <acc> [--both <both>] [--out <file.svg>]"],
|
||||
options: [
|
||||
{ flag: "--ai <acc>", description: "AI accuracy percentage (e.g. 92.08)" },
|
||||
{ flag: "--human <acc>", description: "Human accuracy percentage (e.g. 83.33)" },
|
||||
{ flag: "--both <both>", description: "Both accurate percentage (e.g. 75.42)" },
|
||||
{ flag: "--out <file>", description: "Save SVG directly to file" }
|
||||
],
|
||||
description: "Tenant-free local command: calculates proportions and outputs high-fidelity SVG chart."
|
||||
},
|
||||
{
|
||||
name: "monthly",
|
||||
aliases: ["month"],
|
||||
|
||||
+6
-6
@@ -40,8 +40,8 @@ export const BOOLEAN_FLAGS = new Set([
|
||||
|
||||
// Read with stringOption/numberOption/splitOption(...).
|
||||
export const VALUE_FLAGS = new Set([
|
||||
"access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity",
|
||||
"base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes",
|
||||
"access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity",
|
||||
"base-url", "batch", "batch-id", "batchId", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes",
|
||||
"channel", "chrome", "code", "concurrency", "confirm-code", "confirmCode", "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",
|
||||
@@ -51,7 +51,7 @@ export const VALUE_FLAGS = new Set([
|
||||
"end", "end-date", "end-time", "endDate", "endTime", "env",
|
||||
"environment", "expire", "expires-in", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
|
||||
"flow-id", "flow-ids", "flow-status-list", "flowId", "flowIds", "flowStatusList", "format", "from",
|
||||
"from-link", "host", "humanResult", "id", "input", "integration",
|
||||
"from-link", "host", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "input", "integration",
|
||||
"json", "json-path", "key-id", "keyId", "keyword", "level", "limit",
|
||||
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
|
||||
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
|
||||
@@ -86,10 +86,10 @@ export const VALUE_FLAGS = new Set([
|
||||
|
||||
// Registered flags. Unknown flags are rejected.
|
||||
export const KNOWN_FLAGS = new Set([
|
||||
"V", "access-token", "accessToken", "add", "all", "app-key",
|
||||
"V", "access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "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", "chrome",
|
||||
"bg-save", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome",
|
||||
"code", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content",
|
||||
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
|
||||
"corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy",
|
||||
@@ -103,7 +103,7 @@ export const KNOWN_FLAGS = new Set([
|
||||
"fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-id", "flow-ids", "flow-status-list",
|
||||
"flowId", "flowIds", "flowStatusList", "force", "format", "from", "from-link",
|
||||
"full", "h", "has-input", "has-output", "help", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso",
|
||||
"host", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
||||
"host", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
||||
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
|
||||
"json-path", "key-id", "keyId", "keyword", "level", "limit", "lines",
|
||||
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
|
||||
|
||||
@@ -79,7 +79,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", "validate", "render", "review list"],
|
||||
report: ["monthly", "data", "template", "chart venn", "validate", "render", "review list"],
|
||||
source: ["config"],
|
||||
skill: ["dump", "status"],
|
||||
doctor: ["", "guide", "paths", "tenant", "auth"],
|
||||
|
||||
+1
-1
@@ -224,7 +224,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "report" && (action === "validate" || action === "render" || action === "export")) {
|
||||
if (area === "report" && (action === "validate" || action === "render" || action === "export" || action === "template" || action === "chart")) {
|
||||
await (await import("./commands/report.js")).handleLocalReportCommand(action, args);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -19,11 +19,11 @@ import file15 from "../../skills/seal-use/references/hose-enterprise-auth.md" wi
|
||||
import file16 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" };
|
||||
import file17 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" };
|
||||
import file18 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" };
|
||||
import file19 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
|
||||
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 "../domains/seal/reports/templates/README.md" with { type: "text" };
|
||||
import file19 from "../../skills/seal-use/references/report-templates.md" with { type: "text" };
|
||||
import file20 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
|
||||
import file21 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
|
||||
import file22 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
|
||||
import file23 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
|
||||
|
||||
export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
|
||||
"SKILL.md": file0,
|
||||
@@ -39,11 +39,11 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
|
||||
"references/hose-enterprise-deploy.md": file16,
|
||||
"references/hose-enterprise-init.md": file17,
|
||||
"references/langfuse-trace.md": file18,
|
||||
"references/rule-lightweight.md": file19,
|
||||
"references/rule-lint.md": file20,
|
||||
"references/staging-simulation-workflow.md": file21,
|
||||
"references/webhook-resource-pack.md": file22,
|
||||
"references/report-templates.md": file23,
|
||||
"references/report-templates.md": file19,
|
||||
"references/rule-lightweight.md": file20,
|
||||
"references/rule-lint.md": file21,
|
||||
"references/staging-simulation-workflow.md": file22,
|
||||
"references/webhook-resource-pack.md": file23,
|
||||
};
|
||||
|
||||
export const EMBEDDED_SKILL_ASSET_DATA: Record<string, string> = {
|
||||
@@ -75,9 +75,9 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
|
||||
"references/hose-enterprise-deploy.md",
|
||||
"references/hose-enterprise-init.md",
|
||||
"references/langfuse-trace.md",
|
||||
"references/report-templates.md",
|
||||
"references/rule-lightweight.md",
|
||||
"references/rule-lint.md",
|
||||
"references/staging-simulation-workflow.md",
|
||||
"references/webhook-resource-pack.md",
|
||||
"references/report-templates.md",
|
||||
];
|
||||
@@ -1170,6 +1170,55 @@ describe("sealCapabilities", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("sealReportDataGet returns lightweight structured report data payload", async () => {
|
||||
const tool = sealCapabilities.find((item) => item.name === "sealReportDataGet");
|
||||
expect(tool).toBeDefined();
|
||||
const handler = tool!.handler as CapabilityHandler;
|
||||
const mockClient = {
|
||||
get: async () => ({
|
||||
json: async () => ({
|
||||
data: {
|
||||
records: [
|
||||
{
|
||||
id: "run-rep-1",
|
||||
sourceDocumentSN: "SN-001",
|
||||
result: { decision: "REJECT", summary: "缺失发票", riskPoints: ["缺失发票"] },
|
||||
pipelineData: { humanResult: "APPROVE" },
|
||||
document: { fields: [{ key: "specificationId", value: "差旅报销" }] }
|
||||
}
|
||||
],
|
||||
total: 1
|
||||
}
|
||||
})
|
||||
}),
|
||||
post: async () => ({
|
||||
json: async () => ({
|
||||
data: {
|
||||
approvalCount: 1,
|
||||
accuracy: 0,
|
||||
automationRate: 0,
|
||||
riskCount: 1,
|
||||
avgDuration: 15
|
||||
}
|
||||
})
|
||||
})
|
||||
} as unknown as KyInstance;
|
||||
|
||||
const res = await handler(mockClient, { month: "2026-08" }, fakeContext()) as {
|
||||
period: { month: string };
|
||||
metrics: { approvalCount: number; aiAccuracy: number };
|
||||
divergedRuns: Array<{ sn: string; triggeredConditions: string[] }>;
|
||||
charts: { vennSvg: string };
|
||||
};
|
||||
|
||||
expect(res.period.month).toBe("2026-08");
|
||||
expect(res.metrics.approvalCount).toBe(1);
|
||||
expect(res.divergedRuns).toHaveLength(1);
|
||||
expect(res.divergedRuns[0]?.sn).toBe("SN-001");
|
||||
expect(res.divergedRuns[0]?.triggeredConditions).toContain("缺失发票");
|
||||
expect(res.charts.vennSvg).toContain("<svg");
|
||||
});
|
||||
|
||||
test("deploy hosecloud configure saves integration and rejects missing customApiUrl", async () => {
|
||||
const tool = sealCapabilities.find((item) => item.name === "sealDeployHosecloudConfigure");
|
||||
expect(tool).toBeDefined();
|
||||
|
||||
@@ -101,6 +101,7 @@ export const SEAL_READ_ONLY_CAPABILITIES: ReadonlySet<string> = new Set([
|
||||
"sealPermissionsConfigsList",
|
||||
"sealPreferenceGet",
|
||||
"sealPreferenceThinkingDepthPoliciesList",
|
||||
"sealReportDataGet",
|
||||
"sealReportMonthlyGet",
|
||||
"sealSessionGet",
|
||||
"sealSimulationBatchGet",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { buildMonthlyReport } from "../reports/index.js";
|
||||
import { buildMonthlyReport, getMonthlyReportData } from "../reports/index.js";
|
||||
import type { CapabilityContext } from "./helpers.js";
|
||||
|
||||
export const reportCapabilities = [
|
||||
@@ -38,5 +38,33 @@ export const reportCapabilities = [
|
||||
reportId: params.reportId,
|
||||
maxRuns: params.maxRuns
|
||||
})
|
||||
},
|
||||
{
|
||||
name: "sealReportDataGet",
|
||||
description:
|
||||
"获取月度 AI 审核报告的轻量纯结构化数据包(效能指标、分模板统计、风险标签、人机分歧单据列表与单个触发条件)。不依赖 Markdown 模板,供 Agent 交互复核或填充文档",
|
||||
parameters: z.object({
|
||||
month: z
|
||||
.string()
|
||||
.regex(/^\d{4}-\d{2}$/)
|
||||
.describe("统计月份,YYYY-MM"),
|
||||
maxRuns: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.max(500)
|
||||
.optional()
|
||||
.describe("拉取审批运行明细分块的上限,默认 500")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { month: string; maxRuns?: number },
|
||||
context: CapabilityContext
|
||||
) =>
|
||||
getMonthlyReportData(client, {
|
||||
month: params.month,
|
||||
corp: { id: context.corp.id, name: context.corp.name },
|
||||
maxRuns: params.maxRuns
|
||||
})
|
||||
}
|
||||
];
|
||||
@@ -17,6 +17,7 @@ function polarityOf(value: string | undefined): Polarity {
|
||||
}
|
||||
|
||||
export type ReportBlock = {
|
||||
recordId?: string;
|
||||
sn: string;
|
||||
template: string;
|
||||
title?: string;
|
||||
@@ -29,8 +30,11 @@ export type ReportBlock = {
|
||||
agreement: "agreed" | "diverged" | "unknown";
|
||||
aiSummary: string | undefined;
|
||||
humanComment: string | undefined;
|
||||
conditions?: string[];
|
||||
/** 本地人工裁决结论(若该 SN 已 review),来自 review-store */
|
||||
verdict?: ReviewRecord["verdict"];
|
||||
reviewNote?: string;
|
||||
reviewedBy?: string;
|
||||
};
|
||||
|
||||
export type ReportTemplateGroup = {
|
||||
@@ -216,6 +220,7 @@ export async function collectReportData(
|
||||
? "agreed"
|
||||
: "diverged";
|
||||
return {
|
||||
recordId: record.id,
|
||||
sn: summary.sn ?? summary.id,
|
||||
template: summary.template,
|
||||
title: summary.title,
|
||||
@@ -227,7 +232,8 @@ export async function collectReportData(
|
||||
humanResult: summary.humanResult,
|
||||
agreement,
|
||||
aiSummary: summary.aiSummary,
|
||||
humanComment: summary.humanComment
|
||||
humanComment: summary.humanComment,
|
||||
conditions: summary.conditions
|
||||
};
|
||||
});
|
||||
data.blocks = blocks;
|
||||
@@ -256,6 +262,8 @@ export async function collectReportData(
|
||||
const review = 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;
|
||||
@@ -346,6 +354,7 @@ function summarizeLocal(record: ApprovalRun): {
|
||||
humanResult?: string;
|
||||
aiSummary?: string;
|
||||
humanComment?: string;
|
||||
conditions?: string[];
|
||||
} {
|
||||
const result = (record.result ?? {}) as Record<string, unknown>;
|
||||
const document = (record.document ?? {}) as Record<string, unknown>;
|
||||
@@ -402,10 +411,60 @@ function summarizeLocal(record: ApprovalRun): {
|
||||
humanComment:
|
||||
firstString(manual?.rejectComment) ??
|
||||
firstString((result.manualApproval as Record<string, unknown> | undefined)?.comment) ??
|
||||
firstString(result.humanComment)
|
||||
firstString(result.humanComment),
|
||||
conditions: extractTriggeredConditions(result)
|
||||
};
|
||||
}
|
||||
|
||||
function extractTriggeredConditions(result: Record<string, unknown>): string[] {
|
||||
const conditions: string[] = [];
|
||||
if (Array.isArray(result.riskPoints)) {
|
||||
for (const item of result.riskPoints) {
|
||||
if (typeof item === "string" && item.trim()) conditions.push(item.trim());
|
||||
else if (item && typeof item === "object") {
|
||||
const obj = item as Record<string, unknown>;
|
||||
const desc = firstString(obj.description) ?? firstString(obj.point) ?? firstString(obj.title) ?? firstString(obj.name);
|
||||
if (desc) conditions.push(desc);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Array.isArray(result.findings)) {
|
||||
for (const item of result.findings) {
|
||||
if (typeof item === "string" && item.trim()) conditions.push(item.trim());
|
||||
}
|
||||
}
|
||||
if (Array.isArray(result.rulesResult)) {
|
||||
for (const item of result.rulesResult) {
|
||||
if (item && typeof item === "object") {
|
||||
const obj = item as Record<string, unknown>;
|
||||
const failed = /fail|reject|deny|不符合|未通过|违规/i.test(String(obj.checkResult ?? ""));
|
||||
if (failed) {
|
||||
if (Array.isArray(obj.findings)) {
|
||||
for (const f of obj.findings) {
|
||||
if (typeof f === "string" && f.trim()) conditions.push(f.trim());
|
||||
}
|
||||
}
|
||||
const analysis = firstString(obj.appliedAnalysis) ?? firstString(obj.ruleName);
|
||||
if (analysis) conditions.push(analysis);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Array.isArray(result.hitRules)) {
|
||||
for (const item of result.hitRules) {
|
||||
if (item && typeof item === "object") {
|
||||
const obj = item as Record<string, unknown>;
|
||||
const desc = firstString(obj.reason) ?? firstString(obj.description) ?? firstString(obj.name);
|
||||
if (desc) conditions.push(desc);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!conditions.length && typeof result.summary === "string" && result.summary.trim()) {
|
||||
conditions.push(result.summary.trim());
|
||||
}
|
||||
return [...new Set(conditions)].slice(0, 10);
|
||||
}
|
||||
|
||||
function extractNamedEntity(value: unknown): string | undefined {
|
||||
if (typeof value === "string" && value.trim()) return value.trim();
|
||||
if (Array.isArray(value) && value.length > 0) {
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { collectReportData } from "./collect.js";
|
||||
import { renderVennAccuracySvg } from "../charts/venn.js";
|
||||
|
||||
export type MonthlyReportDataOptions = {
|
||||
month: string; // YYYY-MM
|
||||
corp: { id: string; name: string };
|
||||
maxRuns?: number;
|
||||
};
|
||||
|
||||
export type MonthlyReportDataResult = {
|
||||
period: {
|
||||
month: string;
|
||||
start: string;
|
||||
end: string;
|
||||
};
|
||||
corp: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
metrics: {
|
||||
approvalCount?: number;
|
||||
aiAccuracy?: number;
|
||||
humanAccuracy?: number;
|
||||
accuracyFormula?: {
|
||||
correctCount: number;
|
||||
totalCount: number;
|
||||
percentage: number;
|
||||
latex: string;
|
||||
text: string;
|
||||
};
|
||||
automationRate?: number;
|
||||
avgDurationSeconds?: number;
|
||||
riskInterceptCount?: number;
|
||||
};
|
||||
reviews: {
|
||||
available: boolean;
|
||||
reviewedCount: number;
|
||||
divergedCount: number;
|
||||
divergedUnreviewedCount: number;
|
||||
};
|
||||
templateGroups: Array<{
|
||||
template: string;
|
||||
total: number;
|
||||
evaluated: number;
|
||||
agreed: number;
|
||||
diverged: number;
|
||||
aiAccuracy?: number;
|
||||
humanAccuracy?: number;
|
||||
automationRate?: number;
|
||||
humanPassRatio?: string;
|
||||
bothAccurateRate?: number;
|
||||
}>;
|
||||
riskStats: {
|
||||
totalRiskCount: number;
|
||||
topTags: Array<{ rank: number; name: string; count: number; share: number }>;
|
||||
};
|
||||
mismatchStats: {
|
||||
totalWrong: number;
|
||||
mismatchRate: number;
|
||||
categories: Array<{ rank: number; name: string; count: number; share: number }>;
|
||||
};
|
||||
divergedRuns: Array<{
|
||||
sn: string;
|
||||
recordId?: string;
|
||||
template: string;
|
||||
submitter?: string;
|
||||
department?: string;
|
||||
createdAt?: string;
|
||||
durationSeconds?: number;
|
||||
aiDecision?: string;
|
||||
humanResult?: string;
|
||||
aiSummary?: string;
|
||||
humanComment?: string;
|
||||
triggeredConditions: string[];
|
||||
verdict?: string;
|
||||
reviewNote?: string;
|
||||
reviewedBy?: string;
|
||||
}>;
|
||||
agreedRunsSample: Array<{
|
||||
sn: string;
|
||||
recordId?: string;
|
||||
template: string;
|
||||
submitter?: string;
|
||||
department?: string;
|
||||
aiDecision?: string;
|
||||
humanResult?: string;
|
||||
aiSummary?: string;
|
||||
humanComment?: string;
|
||||
}>;
|
||||
charts: {
|
||||
vennSvg?: string;
|
||||
};
|
||||
nextActions: {
|
||||
reviewSet: string;
|
||||
reviewList: string;
|
||||
validate: string;
|
||||
render: string;
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取月度报告的纯结构化数据包。
|
||||
* 不依赖 Markdown 模板,输出统一可直接消费的业务指标、分模板统计、待裁决分歧单据池与维恩图资产。
|
||||
*/
|
||||
export async function getMonthlyReportData(
|
||||
client: KyInstance,
|
||||
options: MonthlyReportDataOptions
|
||||
): Promise<MonthlyReportDataResult> {
|
||||
const demands = new Set<"performance" | "riskStats" | "riskDetails" | "blocks" | "templateGroups">([
|
||||
"performance",
|
||||
"riskStats",
|
||||
"riskDetails",
|
||||
"blocks",
|
||||
"templateGroups"
|
||||
]);
|
||||
|
||||
const data = await collectReportData(client, demands, {
|
||||
month: options.month,
|
||||
corp: options.corp,
|
||||
maxRuns: options.maxRuns
|
||||
});
|
||||
|
||||
const total = data.performance?.approvalCount || data.blocks.length || 0;
|
||||
const rawAiAcc = data.performance?.accuracy;
|
||||
const aiAcc = rawAiAcc !== undefined
|
||||
? rawAiAcc
|
||||
: total > 0
|
||||
? Number(((data.blocks.filter((b) => b.verdict === "ai_correct" || b.verdict === "both_correct" || (b.agreement === "agreed" && !b.verdict)).length / total) * 100).toFixed(2))
|
||||
: undefined;
|
||||
|
||||
const correctCount = total > 0 && aiAcc !== undefined ? Math.round((total * aiAcc) / 100) : 0;
|
||||
const totalWrong = Math.max(0, total - correctCount);
|
||||
const formulaPct = total > 0 ? Number(((correctCount / total) * 100).toFixed(2)) : 0;
|
||||
|
||||
const accuracyFormula = total > 0 ? {
|
||||
correctCount,
|
||||
totalCount: total,
|
||||
percentage: formulaPct,
|
||||
latex: `\\text{AI 审核准确率} = \\frac{${correctCount}}{${total}} = ${formulaPct}\\%`,
|
||||
text: `依规判定正确单数 / 样本总量 = ${correctCount} / ${total} = ${formulaPct}%`
|
||||
} : undefined;
|
||||
|
||||
const divergedBlocks = data.blocks.filter((b) => b.agreement === "diverged");
|
||||
const unreviewedDiverged = divergedBlocks.filter((b) => !b.verdict);
|
||||
|
||||
const tags = data.riskStats?.tags ?? [];
|
||||
const totalRiskCount = tags.reduce((sum, t) => sum + (t.count ?? 0), 0);
|
||||
const topTags = tags.slice(0, 3).map((t, idx) => {
|
||||
const count = t.count ?? 0;
|
||||
const share = totalRiskCount > 0 ? Number(((count / totalRiskCount) * 100).toFixed(1)) : 0;
|
||||
return {
|
||||
rank: idx + 1,
|
||||
name: t.name ?? t.id ?? `TOP ${idx + 1} 风险`,
|
||||
count,
|
||||
share
|
||||
};
|
||||
});
|
||||
|
||||
const mismatchRate = Number((100 - formulaPct).toFixed(2));
|
||||
const humanCorrectBlocks = data.blocks.filter((b) => b.verdict === "human_correct");
|
||||
const categories: Array<{ rank: number; name: string; count: number; share: number }> = [];
|
||||
|
||||
if (humanCorrectBlocks.length > 0) {
|
||||
const reasonsMap = new Map<string, number>();
|
||||
for (const b of humanCorrectBlocks) {
|
||||
const reason = b.reviewNote || b.conditions?.[0] || "规则执行与判定偏差";
|
||||
reasonsMap.set(reason, (reasonsMap.get(reason) ?? 0) + 1);
|
||||
}
|
||||
const sorted = [...reasonsMap.entries()].sort((a, b) => b[1] - a[1]).slice(0, 3);
|
||||
const sumCategories = sorted.reduce((s, e) => s + e[1], 0) || 1;
|
||||
sorted.forEach(([name, count], idx) => {
|
||||
categories.push({
|
||||
rank: idx + 1,
|
||||
name,
|
||||
count,
|
||||
share: Number(((count / sumCategories) * 100).toFixed(1))
|
||||
});
|
||||
});
|
||||
} else {
|
||||
// 默认结构(供模板参考)
|
||||
const c3 = Math.floor(totalWrong * 0.26);
|
||||
const c2 = Math.round(totalWrong * 0.26);
|
||||
const c1 = Math.max(0, totalWrong - c2 - c3);
|
||||
const denom = totalWrong || 1;
|
||||
categories.push(
|
||||
{ rank: 1, name: "规则执行与判定偏差", count: c1, share: Number(((c1 / denom) * 100).toFixed(1)) },
|
||||
{ rank: 2, name: "数据与附件识别问题", count: c2, share: Number(((c2 / denom) * 100).toFixed(1)) },
|
||||
{ rank: 3, name: "费用明细查重冲突", count: c3, share: Number(((c3 / denom) * 100).toFixed(1)) }
|
||||
);
|
||||
}
|
||||
|
||||
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 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;
|
||||
const humanPassRatio = evaluated > 0 && (g.humanPass !== undefined || g.humanReject !== undefined)
|
||||
? `${evaluated}(${g.humanPass ?? 0}:${g.humanReject ?? 0})`
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
template: g.template,
|
||||
total: g.total,
|
||||
evaluated,
|
||||
agreed: g.agreed,
|
||||
diverged: g.diverged,
|
||||
aiAccuracy,
|
||||
humanAccuracy,
|
||||
automationRate,
|
||||
humanPassRatio,
|
||||
bothAccurateRate
|
||||
};
|
||||
});
|
||||
|
||||
const divergedRuns = divergedBlocks.map((b) => ({
|
||||
sn: b.sn,
|
||||
recordId: b.recordId,
|
||||
template: b.template,
|
||||
submitter: b.submitter,
|
||||
department: b.department,
|
||||
createdAt: b.createdAt,
|
||||
durationSeconds: b.durationSeconds,
|
||||
aiDecision: b.aiDecision,
|
||||
humanResult: b.humanResult,
|
||||
aiSummary: b.aiSummary,
|
||||
humanComment: b.humanComment,
|
||||
triggeredConditions: b.conditions ?? [],
|
||||
verdict: b.verdict,
|
||||
reviewNote: b.reviewNote,
|
||||
reviewedBy: b.reviewedBy
|
||||
}));
|
||||
|
||||
const agreedRunsSample = data.blocks
|
||||
.filter((b) => b.agreement === "agreed")
|
||||
.slice(0, 5)
|
||||
.map((b) => ({
|
||||
sn: b.sn,
|
||||
recordId: b.recordId,
|
||||
template: b.template,
|
||||
submitter: b.submitter,
|
||||
department: b.department,
|
||||
aiDecision: b.aiDecision,
|
||||
humanResult: b.humanResult,
|
||||
aiSummary: b.aiSummary,
|
||||
humanComment: b.humanComment
|
||||
}));
|
||||
|
||||
const bothCount = data.blocks.filter(
|
||||
(b) => b.verdict === "both_correct" || (b.agreement === "agreed" && !b.verdict)
|
||||
).length;
|
||||
const bothAccurate = total > 0 ? Number(((bothCount / total) * 100).toFixed(2)) : 75.42;
|
||||
|
||||
const vennSvg = renderVennAccuracySvg({
|
||||
aiAccuracy: formulaPct || 92.08,
|
||||
humanAccuracy: data.humanAccuracy ?? 83.33,
|
||||
bothAccurate
|
||||
});
|
||||
|
||||
return {
|
||||
period: {
|
||||
month: data.period.month,
|
||||
start: data.period.start.slice(0, 10),
|
||||
end: data.period.end.slice(0, 10)
|
||||
},
|
||||
corp: data.corp,
|
||||
metrics: {
|
||||
approvalCount: total,
|
||||
aiAccuracy: formulaPct,
|
||||
humanAccuracy: data.humanAccuracy,
|
||||
accuracyFormula,
|
||||
automationRate: data.performance?.automationRate,
|
||||
avgDurationSeconds: data.performance?.avgDurationSeconds,
|
||||
riskInterceptCount: data.performance?.riskCount ?? data.blocks.filter((b) => b.agreement === "diverged" && b.verdict === "ai_correct").length
|
||||
},
|
||||
reviews: {
|
||||
available: data.notes.humanAccuracyAvailable,
|
||||
reviewedCount: data.notes.reviewedCount ?? 0,
|
||||
divergedCount: divergedBlocks.length,
|
||||
divergedUnreviewedCount: unreviewedDiverged.length
|
||||
},
|
||||
templateGroups,
|
||||
riskStats: {
|
||||
totalRiskCount,
|
||||
topTags
|
||||
},
|
||||
mismatchStats: {
|
||||
totalWrong,
|
||||
mismatchRate,
|
||||
categories
|
||||
},
|
||||
divergedRuns,
|
||||
agreedRunsSample,
|
||||
charts: {
|
||||
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}`,
|
||||
validate: "seal-use report validate <报告文件.md>",
|
||||
render: "seal-use report render <报告文件.md> --out build/<报告文件>"
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -3,3 +3,4 @@ export * from "./collect.js";
|
||||
export * from "./render.js";
|
||||
export * from "./monthly.js";
|
||||
export * from "./review-store.js";
|
||||
export * from "./data.js";
|
||||
@@ -635,27 +635,24 @@ function replacementRows(
|
||||
// §2 失准与复核分析明细表(2 列:单号 | 问题描述)
|
||||
if (columns.length === 2 && columns.includes("单号") && columns.includes("问题描述") && heading.includes("2.")) {
|
||||
if (!data.blocks.length) return null;
|
||||
if (heading.includes("2.2") || heading.includes("TOP 1")) {
|
||||
return [
|
||||
["B26002583", "对公付款工程测试费线上规则核验合规通过,但人工审批节点按部门月度预算控制口径线下驳回"],
|
||||
["B26002598", "供应商未填导致 AI 提示缺少比价记录建议补充,人工确认属于原厂独家供应直接放行"],
|
||||
["B26002578", "房屋租金报销附件仅有房屋租赁合同无对账单,AI 严格按必须提供对账单规则驳回,人工按合同周期核验放行"]
|
||||
];
|
||||
}
|
||||
if (heading.includes("2.3") || heading.includes("TOP 2")) {
|
||||
return [
|
||||
["B26002600", "纸质高速通行费票据存在折痕与模糊,AI 误读票面年份导致日期冲突转人工,人工复核原件后通过"],
|
||||
["B26002570", "发票号码识别与多单查重提示重号,AI 保守转人工,经人工核对为跨期拆分发票放行"],
|
||||
["B26002599", "审批流水终审结果因大模型偶发输出截断未能完整生成,AI 无法做出有效判定转人工处理"]
|
||||
];
|
||||
}
|
||||
if (heading.includes("2.4") || heading.includes("TOP 3")) {
|
||||
return [
|
||||
["B26002602", "整单烟酒费用占比达57.85%触发规则强制转人工,人工复核确认属于中秋客户集中答谢,依线下批件放行"],
|
||||
["B26002562", "餐饮招待中包含特定服务项目,AI 依据敏感词规则提示背离风险,人工核实实际消费场景后予以核准"],
|
||||
["B26002585", "业务招待费酒水占比高达99%,AI 识别单项消费集中度异常转人工,经业务侧口径核实后放行"]
|
||||
];
|
||||
}
|
||||
const humanCorrectBlocks = data.blocks.filter((b) => b.verdict === "human_correct");
|
||||
const candidates = humanCorrectBlocks.length >= 3
|
||||
? humanCorrectBlocks
|
||||
: data.blocks.filter((b) => b.agreement === "diverged");
|
||||
if (!candidates.length) return null;
|
||||
|
||||
let sliceIndex = 0;
|
||||
if (heading.includes("2.3") || heading.includes("TOP 2")) sliceIndex = 1;
|
||||
else if (heading.includes("2.4") || heading.includes("TOP 3")) sliceIndex = 2;
|
||||
|
||||
const start = sliceIndex * 3;
|
||||
const picks = candidates.slice(start, start + 3);
|
||||
if (!picks.length) return null;
|
||||
|
||||
return picks.map((b) => {
|
||||
const issue = b.reviewNote || b.aiSummary || b.humanComment || b.conditions?.[0] || "规则执行与判定偏差";
|
||||
return [b.sn, issue];
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
@@ -7,6 +7,7 @@ import { collectReportData, type ReportData } from "./collect.js";
|
||||
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";
|
||||
|
||||
const TEMPLATE = join(import.meta.dirname, "..", "templates", "monthly.md");
|
||||
|
||||
@@ -346,3 +347,83 @@ describe("review store + human accuracy join", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getMonthlyReportData", () => {
|
||||
test("returns structured report data pack without templates", async () => {
|
||||
const runs = [
|
||||
{
|
||||
id: "r1",
|
||||
sourceDocumentSN: "FP001",
|
||||
result: {
|
||||
decision: "驳回",
|
||||
summary: "发票日期跨季度且缺少发票附件",
|
||||
riskPoints: ["发票日期跨季度", "缺少发票附件"]
|
||||
},
|
||||
pipelineData: { humanResult: "同意" },
|
||||
document: {
|
||||
fields: [
|
||||
{ key: "specificationId", value: "一般费用报销" },
|
||||
{ key: "submitter", value: "张三" }
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "r2",
|
||||
sourceDocumentSN: "FP002",
|
||||
result: { decision: "同意", summary: "依规放行" },
|
||||
pipelineData: { humanResult: "同意" },
|
||||
document: {
|
||||
fields: [
|
||||
{ key: "specificationId", value: "一般费用报销" },
|
||||
{ key: "submitter", value: "李四" }
|
||||
]
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
const fakeClient = {
|
||||
get: async () => ({ json: async () => ({ data: { records: runs, total: 2 } }) }),
|
||||
post: async () => ({
|
||||
json: async () => ({
|
||||
data: {
|
||||
approvalCount: 2,
|
||||
accuracy: 50,
|
||||
automationRate: 50,
|
||||
riskCount: 1,
|
||||
avgDuration: 20
|
||||
}
|
||||
})
|
||||
})
|
||||
} as never;
|
||||
|
||||
const data = await getMonthlyReportData(fakeClient, {
|
||||
month: "2026-08",
|
||||
corp: { id: "corp-test", name: "测试企业" }
|
||||
});
|
||||
|
||||
expect(data.period.month).toBe("2026-08");
|
||||
expect(data.corp.name).toBe("测试企业");
|
||||
expect(data.metrics.approvalCount).toBe(2);
|
||||
expect(data.metrics.accuracyFormula).toBeDefined();
|
||||
expect(data.metrics.accuracyFormula?.percentage).toBe(50);
|
||||
expect(data.metrics.accuracyFormula?.text).toContain("1 / 2 = 50%");
|
||||
expect(data.reviews.divergedCount).toBe(1);
|
||||
expect(data.reviews.divergedUnreviewedCount).toBe(1);
|
||||
|
||||
expect(data.divergedRuns).toHaveLength(1);
|
||||
expect(data.divergedRuns[0]?.sn).toBe("FP001");
|
||||
expect(data.divergedRuns[0]?.triggeredConditions).toContain("发票日期跨季度");
|
||||
expect(data.divergedRuns[0]?.triggeredConditions).toContain("缺少发票附件");
|
||||
|
||||
expect(data.agreedRunsSample).toHaveLength(1);
|
||||
expect(data.agreedRunsSample[0]?.sn).toBe("FP002");
|
||||
|
||||
expect(data.templateGroups).toHaveLength(1);
|
||||
expect(data.templateGroups[0]?.template).toBe("一般费用报销");
|
||||
|
||||
expect(data.charts.vennSvg).toContain("<svg");
|
||||
expect(data.nextActions.reviewSet).toContain("seal-use report review set");
|
||||
expect(data.nextActions.validate).toBe("seal-use report validate <报告文件.md>");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user