/** * tools/invoice-summary.ts — invoice_summary 工具:汇总 + 报销单生成。 * * 行为(对照功能规格第 2 条): * - files 缺省时复用 invoice_parse 的解析缓存(key 含会话作用域,见 invoice-parse.ts); * - 汇总结算(合计/税额/按类别)、重复票检测(同票号+同金额); * - 生成报销单文件到工作区(Markdown 直写;xlsx 因 DSH 工作区为文本信道, * 以 base64 文本 (.b64) 落盘,README 提供解码命令)+ 会话内汇总表格; * - 安全:写目标前先 stat/read("已存在目标先 read"),再以版本守卫写入。 */ import { defineTool } from '@deepseek-ai/dsh-tools' import type { Context } from '@deepseek-ai/cordis' import { type InvoiceData } from '../invoice-model.ts' import { cacheScope, parseCache } from './invoice-parse.ts' import { reimbursementBaseName, renderMarkdown, renderXlsx, summarizeInvoices, type InvoiceSummary } from '../summary.ts' export interface InvoiceSummaryResult { invoicesCount: number summary: InvoiceSummary files: { path: string; kind: 'md' | 'xlsx' | 'both'; operation: 'create' | 'update'; size: number }[] xlsxBase64?: string note?: string } /** 金额四舍五入到分(仅用于展示)。 */ function round2(n: number): number { return Math.round(n * 100) / 100 } /** 写文本文件:已存在目标先 read,再带版本守卫写入;不存在则 createIfAbsent。 */ async function writeGuardedText( ctx: Context, relativePath: string, content: string, signal?: AbortSignal, ): Promise<{ operation: 'create' | 'update'; absPath: string }> { const target = await ctx.fs.resolve(relativePath, { signal }) const info = await ctx.fs.stat(target, signal) if (info) { // 已存在目标先 read(遵循 read 策略),再以版本守卫覆盖 await ctx.fs.readText(target, signal) await ctx.fs.writeText(target, content, { kind: 'replaceIfVersion', version: info.version }, signal) return { operation: 'update', absPath: ctx.fs.processPath(target) } } await ctx.fs.writeText(target, content, { kind: 'createIfAbsent' }, signal) return { operation: 'create', absPath: ctx.fs.processPath(target) } } /** 执行汇总 + 报销单生成。 */ export async function runInvoiceSummary( ctx: Context, args: { files?: string[]; out?: 'md' | 'xlsx' | 'both'; categories?: Record }, signal?: AbortSignal, sessionId?: string, ): Promise { // 只可见当前会话作用域的缓存条目(跨会话隔离;无会话 id 时为 global 进程级) const scope = cacheScope(sessionId) const scopePrefix = `${scope}:` let invoices: InvoiceData[] if (args.files !== undefined && args.files.length > 0) { const matched: InvoiceData[] = [] const missing: string[] = [] for (const f of args.files) { const hit = [...parseCache.entries()].find(([key, inv]) => { if (!key.startsWith(scopePrefix)) return false const absPath = key.slice(scopePrefix.length) return absPath === f || absPath.endsWith(`/${f}`) || inv.source.file === f }) if (hit) matched.push(hit[1]) else missing.push(f) } if (missing.length > 0) { throw new Error(`以下文件尚未解析,请先运行 invoice_parse:${missing.join('、')}`) } invoices = matched } else { invoices = [...parseCache.entries()].filter(([key]) => key.startsWith(scopePrefix)).map(([, inv]) => inv) } if (invoices.length === 0) { throw new Error('当前会话没有可汇总的发票:请先运行 invoice_parse,或通过 files 参数指定已解析文件') } // 类别覆盖:按发票号码或源文件名匹配 if (args.categories) { for (const inv of invoices) { const byNo = args.categories[inv.invoiceNumber] const byFile = args.categories[inv.source.file] if (byNo !== undefined) inv.category = byNo else if (byFile !== undefined) inv.category = byFile } } const summary = summarizeInvoices(invoices) const out = args.out ?? 'md' const base = reimbursementBaseName() const files: InvoiceSummaryResult['files'] = [] let xlsxBase64: string | undefined if (out === 'md' || out === 'both') { const md = renderMarkdown(invoices, summary, { generatedAt: new Date().toISOString() }) const res = await writeGuardedText(ctx, `${base}.md`, md, signal) files.push({ path: res.absPath, kind: 'md', operation: res.operation, size: Buffer.byteLength(md, 'utf8') }) } if (out === 'xlsx' || out === 'both') { const xlsxBytes = renderXlsx(invoices, summary) xlsxBase64 = Buffer.from(xlsxBytes).toString('base64') // DSH fs 服务仅提供 UTF-8 文本信道,xlsx 以 base64 文本落盘(README 提供解码命令) const b64Path = `${base}.xlsx.b64` const res = await writeGuardedText(ctx, b64Path, xlsxBase64, signal) files.push({ path: res.absPath, kind: 'xlsx', operation: res.operation, size: Buffer.byteLength(xlsxBase64, 'utf8') }) } return { invoicesCount: invoices.length, summary, files, xlsxBase64, note: '隐私说明:发票数据仅在本机流转,不发起任何查验接口请求(查验为显式 opt-in,默认关闭)。解析缓存按会话隔离——工具无法取得会话上下文时回退为进程级缓存(见 README)。xlsx 以 base64 文本落盘,解码命令见 README。', } } /** 汇总结果会话内渲染。 */ export function renderSummaryResult(result: InvoiceSummaryResult): string { const lines: string[] = [] const t = result.summary.totals lines.push('## 报销单汇总') lines.push('') lines.push(`参与汇总 **${result.invoicesCount}** 张发票:`) lines.push('') lines.push('| 张数 | 金额合计 | 税额合计 | 价税合计 |') lines.push('| ---: | ---: | ---: | ---: |') lines.push(`| ${t.count} | ¥${t.amount.toFixed(2)} | ¥${t.tax.toFixed(2)} | ¥${t.total.toFixed(2)} |`) if (result.summary.byCategory.length > 1 || (result.summary.byCategory[0] && result.summary.byCategory[0].category !== '未分类')) { lines.push('') lines.push('### 按类别小计') lines.push('') lines.push('| 类别 | 张数 | 金额 | 税额 | 价税合计 |') lines.push('| --- | ---: | ---: | ---: | ---: |') for (const c of result.summary.byCategory) { lines.push(`| ${c.category} | ${c.count} | ¥${c.amount.toFixed(2)} | ¥${c.tax.toFixed(2)} | ¥${c.total.toFixed(2)} |`) } } if (result.summary.duplicates.length > 0) { lines.push('') lines.push('### ⚠ 重复票检测') lines.push('') lines.push('| 票号 | 金额 | 文件 | 建议剔除 |') lines.push('| --- | ---: | --- | --- |') for (const d of result.summary.duplicates) { lines.push(`| ${d.invoiceNumber} | ${d.amount.toFixed(2)} | ${d.files.join('、')} | ${d.flagged.join('、')} |`) } } lines.push('') lines.push('### 已生成文件') lines.push('') for (const f of result.files) { lines.push(`- \`${f.path}\`(${f.kind === 'md' ? 'Markdown 报销单' : 'xlsx base64'},${f.operation === 'create' ? '新建' : '已存在并更新'},${(f.size / 1024).toFixed(1)} KB)`) } if (result.xlsxBase64) { lines.push('') lines.push('xlsx 内容以 base64 文本落盘(DSH 工作区为文本信道)。解码命令:`base64 -d 报销单-<日期>.xlsx.b64 > 报销单-<日期>.xlsx`') } if (result.note) lines.push('') if (result.note) lines.push(`> ${result.note}`) return lines.join('\n') } /** 定义 invoice_summary 工具。 */ export function invoiceSummaryTool(ctx: Context) { return defineTool({ name: 'invoice_summary', description: '汇总已解析发票并生成报销单:files 缺省时复用 invoice_parse 的解析缓存(按会话隔离,无会话上下文时为进程级);汇总结算(合计/税额/按类别小计)、重复票检测(同票号+同金额);生成报销单文件到工作区(out=md/xlsx/both,默认 md)。文件经宿主 ctx.fs 服务读写(已存在目标先 read 再版本守卫写入;观察策略由宿主 fs 事件管道统一处理)。', parameters: { files: { type: 'array', items: { type: 'string' }, description: '参与汇总的发票文件(必需已通过 invoice_parse 解析;缺省使用上次 parse 的全部结果)', }, out: { type: 'string', enum: ['md', 'xlsx', 'both'], description: '输出格式:md(默认)| xlsx(base64 文本落盘)| both', }, categories: { type: 'json', description: '费用类别映射(键为发票号码或源文件名,值为类别名),用于按类别小计', }, }, output: { schema: { type: 'object', additionalProperties: false, properties: { invoicesCount: { type: 'integer' }, summary: { type: 'object', additionalProperties: true, properties: {} }, files: { type: 'array', items: { type: 'json' } }, xlsxBase64: { type: 'string' }, note: { type: 'string' }, }, }, render: (_args, value: any) => [{ type: 'text', text: renderSummaryResult(value as InvoiceSummaryResult) }], presentationMeta: (_args, value: any) => ({ kind: 'invoice-summary', title: `报销单汇总 ${value.invoicesCount} 张 · 价税合计 ¥${round2(value.summary.totals.total).toFixed(2)}`, invoicesCount: value.invoicesCount, total: round2(value.summary.totals.total), duplicateCount: value.summary.duplicates.length, files: value.files.map((f: { path: string }) => f.path), }), }, async execute(args, exec) { const sessionId = (exec as unknown as { agent?: { id?: string } } | undefined)?.agent?.id const categories = args.categories as Record | undefined return runInvoiceSummary(ctx, { files: args.files, out: args.out, categories }, exec?.signal, sessionId) as any }, }) }