399 lines
17 KiB
TypeScript
399 lines
17 KiB
TypeScript
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";
|
|
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
|
import { outputOptions, printJson } from "../printer.js";
|
|
import { CliError, usageError } from "../../core/errors.js";
|
|
import { isCorpDisabledError } from "../../core/config/active.js";
|
|
import {
|
|
BUILTIN_MONTHLY_TEMPLATE,
|
|
exportReportPackage,
|
|
renderReportFile,
|
|
renderVennAccuracySvg,
|
|
saveReportMarkdown,
|
|
validateReportFile,
|
|
loadReviews,
|
|
reviewFilePath,
|
|
writeReview,
|
|
countUnreviewedDivergences,
|
|
listUnreviewedDivergences,
|
|
dismissDivergencePrompt,
|
|
type MonthlyReportResult,
|
|
buildReportLedgerCsv,
|
|
buildReportLedgerXlsx,
|
|
loadReportDataFromLedger,
|
|
collectReportData,
|
|
type ReportData
|
|
} from "../../domains/seal/reports/index.js";
|
|
import type { ParsedArgs } from "../types.js";
|
|
|
|
/** Tenant-free commands: dispatch these before resolving enterprise configuration or authentication. */
|
|
export async function handleLocalReportCommand(action: string | undefined, args: ParsedArgs) {
|
|
if (Boolean(args.options.ledger) || action === "review") {
|
|
const corpId = stringOption(args.options.corp) ?? stringOption(args.options.corpId) ?? "local-ledger";
|
|
let corp: CorpConfig;
|
|
try {
|
|
const { selectCorp } = await import("../helpers.js");
|
|
corp = selectCorp(corpId);
|
|
} catch (error) {
|
|
// Ledger/review work is tenant-free, but if the caller explicitly named a
|
|
// disabled enterprise, the block must still stand instead of falling back.
|
|
if (isCorpDisabledError(error)) throw error;
|
|
corp = {
|
|
corpId,
|
|
id: corpId,
|
|
name: corpId,
|
|
corpName: corpId,
|
|
source: { source: "seal", sealUrl: "" }
|
|
} as unknown as CorpConfig;
|
|
}
|
|
await handleReportCommand(action, {} as any, corp, args);
|
|
return;
|
|
}
|
|
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 参数。");
|
|
if (action === "validate") {
|
|
const result = await validateReportFile(file);
|
|
printJson(result, outputOptions(args.options));
|
|
if (!result.valid) throw new CliError("报告校验未通过,请按 issues 修正后重试。", 1);
|
|
return;
|
|
}
|
|
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
|
if (!out) throw usageError(`Usage: seal-use report ${action} <报告文件.md> --out <${action === "export" ? "目标文件夹" : "产物路径词干"}>`);
|
|
const glossary = args.options["no-glossary"] ? false : booleanOption(args.options.glossary) ?? true;
|
|
if (action === "export") {
|
|
const result = await exportReportPackage(file, {
|
|
out, format: stringOption(args.options.format), width: numberOption(args.options.width),
|
|
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite),
|
|
glossary
|
|
});
|
|
printJson(result, outputOptions(args.options));
|
|
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成完整导出包。请按 validation.issues 修正后重试。", 1);
|
|
return;
|
|
}
|
|
const result = await renderReportFile(file, {
|
|
out, format: stringOption(args.options.format), width: numberOption(args.options.width),
|
|
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite),
|
|
glossary
|
|
});
|
|
printJson(result, outputOptions(args.options));
|
|
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成渲染产物。请按 validation.issues 修正后重试。", 1);
|
|
}
|
|
|
|
function resolveMaxRuns(args: ParsedArgs): number | undefined {
|
|
return (
|
|
numberOption(args.options.limit) ??
|
|
numberOption(args.options.n) ??
|
|
numberOption(args.options.count) ??
|
|
numberOption(args.options["max-runs"]) ??
|
|
numberOption(args.options.maxRuns)
|
|
);
|
|
}
|
|
|
|
/** `seal-use report generate` / `ledger` / `data` — AI 审核报告。 */
|
|
export async function handleReportCommand(
|
|
action: string | undefined,
|
|
client: Awaited<ReturnType<typeof createSealClient>>,
|
|
corp: CorpConfig,
|
|
args: ParsedArgs
|
|
) {
|
|
if (action === "ledger") {
|
|
const ledgerPath = stringOption(args.options.ledger);
|
|
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
|
const format = (stringOption(args.options.format) ?? (out?.endsWith(".csv") ? "csv" : "xlsx")).toLowerCase();
|
|
|
|
let data: ReportData;
|
|
if (ledgerPath) {
|
|
data = await loadReportDataFromLedger(ledgerPath, { corp: { id: corp.id, name: corp.name } });
|
|
} else {
|
|
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 ((!startDate || !endDate) && !month) {
|
|
throw usageError(
|
|
"Usage: seal-use report ledger --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--limit <n>] [--out <file.xlsx|csv>] [--corp <corpId>]"
|
|
);
|
|
}
|
|
|
|
const templates = stringOption(args.options.templates)?.split(/[,;]+/).map((s) => s.trim()).filter(Boolean);
|
|
data = await collectReportData(client, new Set(["blocks", "templateGroups", "performance"]), {
|
|
startDate,
|
|
endDate,
|
|
month,
|
|
corp: { id: corp.id, name: corp.name },
|
|
templates,
|
|
maxRuns: resolveMaxRuns(args)
|
|
});
|
|
}
|
|
|
|
const outFile = out ?? `台账-${corp.id}-${(data.period.label ?? data.period.start).replace(/[^0-9A-Za-z_-]/g, "_")}.${format === "csv" ? "csv" : "xlsx"}`;
|
|
const targetPath = resolve(outFile);
|
|
if (format === "csv") {
|
|
const csvContent = buildReportLedgerCsv(data);
|
|
writeFileSync(targetPath, csvContent, "utf8");
|
|
} else {
|
|
const xlsxBuffer = await buildReportLedgerXlsx(data);
|
|
writeFileSync(targetPath, xlsxBuffer);
|
|
}
|
|
|
|
const divergedCount = data.blocks.filter((b) => b.agreement === "diverged").length;
|
|
const unreviewedDiverged = data.blocks.filter((b) => b.agreement === "diverged" && !b.verdict).length;
|
|
|
|
printJson({
|
|
file: targetPath,
|
|
format: format === "csv" ? "csv" : "xlsx",
|
|
corpId: corp.id,
|
|
period: data.period,
|
|
totalBlocks: data.blocks.length,
|
|
templates: [...new Set(data.blocks.map((b) => b.template))],
|
|
divergedCount,
|
|
unreviewedDiverged,
|
|
next: {
|
|
reviewTip: "可在 Excel 中直接编辑'复核定性裁决'列(填写:AI判断正确 / 人工判断错误,或人工判断正确 / AI判定误判),也可直接剔除不需要的模板行",
|
|
generate: `seal-use report generate --ledger '${targetPath}' --corp ${corp.id} --out reports/报告.md`
|
|
}
|
|
}, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
if (action === "data") {
|
|
const ledgerPath = stringOption(args.options.ledger);
|
|
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 (!ledgerPath && (!startDate || !endDate) && !month) {
|
|
throw usageError(
|
|
"Usage: seal-use report data (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--limit <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,
|
|
ledgerPath,
|
|
maxRuns: resolveMaxRuns(args)
|
|
}
|
|
);
|
|
printJson(result, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
if (action === "monthly" || action === "month" || action === "generate") {
|
|
const ledgerPath = stringOption(args.options.ledger);
|
|
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 (!ledgerPath && (!startDate || !endDate) && !month) {
|
|
throw usageError(
|
|
"Usage: seal-use report generate (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--limit <n>] [--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,
|
|
ledgerPath,
|
|
templatePath: stringOption(args.options.template),
|
|
reportId: stringOption(args.options["report-id"]) ?? stringOption(args.options.reportId),
|
|
maxRuns: resolveMaxRuns(args),
|
|
allowUnreviewed: booleanOption(args.options["allow-unreviewed"]) ?? booleanOption(args.options.force)
|
|
}
|
|
) as MonthlyReportResult;
|
|
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
|
if (out) {
|
|
const saved = saveReportMarkdown(
|
|
result.content,
|
|
result.templatePath,
|
|
out,
|
|
booleanOption(args.options.overwrite),
|
|
result.dynamicAssets,
|
|
result.companionFiles
|
|
);
|
|
const quotedFile = `'${saved.file.replace(/'/g, "'\\''")}'`;
|
|
printJson({ ...result, content: undefined, dynamicAssets: undefined, companionFiles: undefined, ...saved, next: {
|
|
validate: `seal-use report validate ${quotedFile}`,
|
|
render: `seal-use report render ${quotedFile} --out build/report`
|
|
} }, outputOptions(args.options));
|
|
} else printJson({ ...result, dynamicAssets: undefined, companionFiles: undefined }, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
if (action === "review") {
|
|
const sub = args.command[2]; // set | list | import
|
|
|
|
if (sub === "unreviewed" || sub === "pending" || sub === "triage") {
|
|
const limit = numberOption(args.options.limit) ?? 20;
|
|
const all = booleanOption(args.options.all);
|
|
const days = all ? 0 : (numberOption(args.options.days) ?? 30);
|
|
const items = listUnreviewedDivergences(corp.id, limit, days);
|
|
printJson({
|
|
corpId: corp.id,
|
|
corpName: corp.name,
|
|
window: {
|
|
recencyDays: days > 0 ? days : "all",
|
|
promptThrottleHours: 5,
|
|
storage: "~/.config/seal-use/state/reviews.sqlite"
|
|
},
|
|
count: items.length,
|
|
totalPending: countUnreviewedDivergences(corp.id, days),
|
|
divergences: items,
|
|
guidance:
|
|
"Agent 上下文说明:\n" +
|
|
"1. 数据来源:上述分歧来自本地 SQLite (~/.config/seal-use/state/reviews.sqlite),由报表或审批流发现 AI 与人工结论相反,仅保存在用户本机,不上传云端。\n" +
|
|
"2. 频控规则:CLI 默认只关注近 30 天内单据(排除陈年旧账),且每 5 小时滑动窗口最多提醒一次。\n" +
|
|
"3. 交互流程:请在完成主任务后以简短摘要向用户征询;用户确认后执行 'seal-use report review set --corp <corpId> --sn <SN> --verdict <ai_correct|manual_correct|both_correct|both_wrong|unclear>' 回写;用户表示暂不处理时,立即执行 'seal-use report review dismiss --corp <corpId> --hours 24' 静音 24 小时,切勿重复打扰。"
|
|
}, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
if (sub === "dismiss") {
|
|
const hours = numberOption(args.options.hours) ?? 24;
|
|
const until = dismissDivergencePrompt(corp.id, hours);
|
|
printJson({
|
|
corpId: corp.id,
|
|
dismissed: true,
|
|
dismissedUntil: new Date(until).toISOString(),
|
|
message: `已为企业「${corp.name}」静音分歧提醒 ${hours} 小时。在此期间不会重复向用户提示。`
|
|
}, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
if (sub === "list") {
|
|
const scope = stringOption(args.options.month) ?? stringOption(args.options.scope);
|
|
const reviews = loadReviews(corp.id, scope);
|
|
printJson({
|
|
corpId: corp.id,
|
|
...(scope ? { month: scope } : {}),
|
|
file: reviewFilePath(corp.id, scope),
|
|
count: reviews.size,
|
|
reviews: [...reviews.values()]
|
|
});
|
|
return;
|
|
}
|
|
|
|
if (sub === "import") {
|
|
const file = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.ledger);
|
|
if (!file) throw usageError("Usage: seal-use report review import <台账.xlsx|csv> --corp <corpId>");
|
|
const ledgerData = await loadReportDataFromLedger(file, { corp: { id: corp.id, name: corp.name } });
|
|
let imported = 0;
|
|
for (const rev of ledgerData.reviews.values()) {
|
|
writeReview(corp.id, rev);
|
|
imported++;
|
|
}
|
|
printJson({
|
|
corpId: corp.id,
|
|
file: resolve(file),
|
|
importedCount: imported,
|
|
totalBlocks: ledgerData.blocks.length
|
|
}, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
if (sub === "set") {
|
|
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);
|
|
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,
|
|
note: stringOption(args.options.note),
|
|
reviewedBy: stringOption(args.options["reviewed-by"]) ?? stringOption(args.options.reviewedBy)
|
|
});
|
|
printJson({ corpId: corp.id, file: reviewFilePath(corp.id, month), record });
|
|
return;
|
|
}
|
|
|
|
throw usageError(`Unknown report review subcommand: ${sub ?? ""}. Use 'set', 'list', 'unreviewed', 'dismiss', or 'import'.`);
|
|
}
|
|
|
|
throw usageError(`Unknown report command: ${action ?? ""}. Run 'seal-use help report' for available commands.`);
|
|
}
|