/** * summary.ts — 汇总结算与报销单渲染(纯逻辑,零第三方依赖)。 * * - summarizeInvoices:合计/税额/价税合计、按类别小计、重复票检测(同票号+同金额); * - renderMarkdown:报销单 Markdown(工作区可直接打开); * - renderXlsx:最小 xlsx(ZIP + OOXML),可由 Excel/WPS/openpyxl 打开; * - buildZip:自写极小 ZIP 打包器(内置 zlib.deflateSync,无任何 npm 依赖)。 */ import { deflateRawSync } from 'node:zlib' import type { InvoiceData } from './invoice-model.ts' // --------------------------------------------------------------------------- // 汇总 // --------------------------------------------------------------------------- /** 汇总合计。 */ export interface SummaryTotals { count: number amount: number tax: number total: number } /** 重复票分组:同票号 + 同金额(保留首张,其余 flagged)。 */ export interface DuplicateGroup { key: string invoiceNumber: string amount: number files: string[] /** 被判定为重复(应剔除)的源文件名。 */ flagged: string[] } /** 按类别小计行。 */ export interface CategoryTotal { category: string count: number amount: number tax: number total: number } /** 完整汇总结果。 */ export interface InvoiceSummary { totals: SummaryTotals byCategory: CategoryTotal[] duplicates: DuplicateGroup[] } /** 金额四舍五入到分。 */ function round2(n: number): number { return Math.round(n * 100) / 100 } /** 汇总结算 + 重复检测。 */ export function summarizeInvoices(invoices: InvoiceData[]): InvoiceSummary { const totals: SummaryTotals = { count: invoices.length, amount: 0, tax: 0, total: 0 } const catMap = new Map() const dupMap = new Map() for (const inv of invoices) { totals.amount = round2(totals.amount + inv.amount) totals.tax = round2(totals.tax + inv.tax) totals.total = round2(totals.total + inv.total) const cat = inv.category ?? '未分类' const entry = catMap.get(cat) ?? { category: cat, count: 0, amount: 0, tax: 0, total: 0 } entry.count += 1 entry.amount = round2(entry.amount + inv.amount) entry.tax = round2(entry.tax + inv.tax) entry.total = round2(entry.total + inv.total) catMap.set(cat, entry) if (/^[0-9]{8,20}$/.test(inv.invoiceNumber)) { const key = `${inv.invoiceNumber}@${inv.amount.toFixed(2)}` const group = dupMap.get(key) ?? { key, invoiceNumber: inv.invoiceNumber, amount: inv.amount, files: [], flagged: [], } group.files.push(inv.source.file) dupMap.set(key, group) } } const duplicates: DuplicateGroup[] = [...dupMap.values()] .filter((g) => g.files.length > 1) .map((g) => ({ ...g, flagged: g.files.slice(1) })) return { totals, byCategory: [...catMap.values()], duplicates } } // --------------------------------------------------------------------------- // Markdown 渲染 // --------------------------------------------------------------------------- /** 渲染报销单 Markdown。 */ export function renderMarkdown(invoices: InvoiceData[], summary: InvoiceSummary, opts?: { title?: string; generatedAt?: string }): string { const title = opts?.title ?? '报销单' const generatedAt = opts?.generatedAt ?? new Date().toISOString() const t = summary.totals const lines: string[] = [] lines.push(`# ${title}`) lines.push('') lines.push(`> 由 dsh-invoice-tools 生成 · ${generatedAt}`) lines.push('> ') lines.push(`> 发票共 **${t.count}** 张,金额合计 **¥${t.amount.toFixed(2)}**,税额合计 **¥${t.tax.toFixed(2)}**,价税合计 **¥${t.total.toFixed(2)}**`) if (summary.duplicates.length > 0) { lines.push('> ') lines.push(`> ⚠ 重复票提示:${summary.duplicates.map((d) => `${d.invoiceNumber}(${d.flagged.join('、')})`).join(';')} —— 建议剔除后报销。`) } lines.push('') lines.push('| # | 发票号码 | 发票代码 | 开票日期 | 销售方 | 金额 | 税额 | 价税合计 | 类别 | 源文件 |') lines.push('| --- | --- | --- | --- | --- | ---: | ---: | ---: | --- | --- |') invoices.forEach((inv, idx) => { const flag = summary.duplicates.some((d) => d.flagged.includes(inv.source.file)) ? ' ⚠重复' : '' lines.push( `| ${idx + 1} | ${inv.invoiceNumber} | ${inv.invoiceCode || '—'} | ${inv.issueDate} | ${inv.seller.name || '—'} | ${inv.amount.toFixed(2)} | ${inv.tax.toFixed(2)} | ${inv.total.toFixed(2)} | ${inv.category ?? '未分类'} | ${inv.source.file}${flag} |`, ) }) lines.push( `| **合计** | | | | | **${t.amount.toFixed(2)}** | **${t.tax.toFixed(2)}** | **${t.total.toFixed(2)}** | | |`, ) if (summary.byCategory.length > 1 || summary.byCategory[0]?.category !== '未分类') { lines.push('') lines.push('## 分类小计') lines.push('') lines.push('| 类别 | 张数 | 金额 | 税额 | 价税合计 |') lines.push('| --- | ---: | ---: | ---: | ---: |') for (const c of summary.byCategory) { lines.push(`| ${c.category} | ${c.count} | ${c.amount.toFixed(2)} | ${c.tax.toFixed(2)} | ${c.total.toFixed(2)} |`) } } lines.push('') lines.push('---') lines.push('') lines.push('报销人:________  审批人:________  日期:________') lines.push('') lines.push('> 隐私说明:发票数据仅在本地会话/工作区流转,本工具不发起任何查验接口请求。') return lines.join('\n') } // --------------------------------------------------------------------------- // 最小 xlsx(含 zip 打包) // --------------------------------------------------------------------------- /** XML 转义。 */ function xmlEscape(s: string): string { return s .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, ''') } function textEncode(str: string): Uint8Array { return new TextEncoder().encode(str) } const CRC_TABLE = (() => { const table = new Uint32Array(256) for (let n = 0; n < 256; n++) { let c = n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1 table[n] = c >>> 0 } return table })() function crc32(bytes: Uint8Array): number { let crc = 0xffffffff for (let i = 0; i < bytes.length; i++) { crc = CRC_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8) } return (crc ^ 0xffffffff) >>> 0 } function dosDateTime(date: Date): { time: number; date: number } { const time = (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1) const d = ((date.getFullYear() - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate() return { time, date: d } } /** 自写极小 ZIP 打包器(store/deflate 混合不可用,统一 deflate,条目名 UTF-8)。 */ export function buildZip(files: { name: string; data: Uint8Array }[]): Uint8Array { const pieces: Uint8Array[] = [] const central: Uint8Array[] = [] let offset = 0 const now = new Date() const { time, date } = dosDateTime(now) for (const file of files) { const nameBytes = textEncode(file.name) const compressed = deflateRawSync(file.data, { level: 6 }) const crc = crc32(file.data) const localHeader = new Uint8Array(30) const dv = new DataView(localHeader.buffer) dv.setUint32(0, 0x04034b50, true) dv.setUint16(4, 20, true) // version needed dv.setUint16(6, 0x0800, true) // UTF-8 flag dv.setUint16(8, 8, true) // method: deflate dv.setUint16(10, time, true) dv.setUint16(12, date, true) dv.setUint32(14, crc, true) dv.setUint32(18, compressed.length, true) dv.setUint32(22, file.data.length, true) dv.setUint16(26, nameBytes.length, true) dv.setUint16(28, 0, true) pieces.push(localHeader, nameBytes, compressed) const cd = new Uint8Array(46) const cdv = new DataView(cd.buffer) cdv.setUint32(0, 0x02014b50, true) cdv.setUint16(4, 20, true) cdv.setUint16(6, 20, true) cdv.setUint16(8, 0x0800, true) cdv.setUint16(10, 8, true) cdv.setUint16(12, time, true) cdv.setUint16(14, date, true) cdv.setUint32(16, crc, true) cdv.setUint32(20, compressed.length, true) cdv.setUint32(24, file.data.length, true) cdv.setUint16(28, nameBytes.length, true) cdv.setUint32(42, offset, true) central.push(cd, nameBytes) offset += 30 + nameBytes.length + compressed.length } const centralSize = central.reduce((acc, c) => acc + c.length, 0) const centralOffset = offset const eocd = new Uint8Array(22) const edv = new DataView(eocd.buffer) edv.setUint32(0, 0x06054b50, true) edv.setUint16(8, files.length, true) edv.setUint16(10, files.length, true) edv.setUint32(12, centralSize, true) edv.setUint32(16, centralOffset, true) const totalLength = offset + centralSize + 22 const out = new Uint8Array(totalLength) let w = 0 for (const p of pieces) { out.set(p, w) w += p.length } for (const c of central) { out.set(c, w) w += c.length } out.set(eocd, w) return out } /** 渲染工作表单元格(inlineStr 字符串 / 原生数字)。 */ function cellXml(ref: string, value: string | number): string { if (typeof value === 'number') { return `${value.toFixed(2)}` } return `${xmlEscape(value)}` } function colName(index: number): string { let n = index let s = '' while (n >= 0) { s = String.fromCharCode(65 + (n % 26)) + s n = Math.floor(n / 26) - 1 } return s } /** 渲染 xlsx 字节(单 sheet"报销单")。 */ export function renderXlsx(invoices: InvoiceData[], summary: InvoiceSummary): Uint8Array { const headers = ['#', '发票号码', '发票代码', '开票日期', '销售方', '购买方', '金额', '税额', '价税合计', '类别', '源文件'] const rows: (string | number)[][] = [] invoices.forEach((inv, idx) => { rows.push([ idx + 1, inv.invoiceNumber, inv.invoiceCode, inv.issueDate, inv.seller.name, inv.buyer.name, inv.amount, inv.tax, inv.total, inv.category ?? '未分类', inv.source.file, ]) }) rows.push(['合计', '', '', '', '', '', summary.totals.amount, summary.totals.tax, summary.totals.total, '', `${summary.totals.count} 张`]) let sheet = '\n' sheet += `` sheet += `${headers.map((h, i) => cellXml(`${colName(i)}1`, h)).join('')}` rows.forEach((row, r) => { const rowNum = r + 2 sheet += `${row.map((v, i) => cellXml(`${colName(i)}${rowNum}`, v)).join('')}` }) sheet += `` const contentTypes = ` ` const rels = ` ` const workbook = ` ` const workbookRels = ` ` const styles = ` ` const core = ` dsh-invoice-tools dsh-invoice-tools ${new Date().toISOString()} ${new Date().toISOString()} ` const app = ` dsh-invoice-tools` return buildZip([ { name: '[Content_Types].xml', data: textEncode(contentTypes) }, { name: '_rels/.rels', data: textEncode(rels) }, { name: 'docProps/core.xml', data: textEncode(core) }, { name: 'docProps/app.xml', data: textEncode(app) }, { name: 'xl/workbook.xml', data: textEncode(workbook) }, { name: 'xl/_rels/workbook.xml.rels', data: textEncode(workbookRels) }, { name: 'xl/styles.xml', data: textEncode(styles) }, { name: 'xl/worksheets/sheet1.xml', data: textEncode(sheet) }, ]) } /** 默认报销单基础文件名(不含扩展名)。 */ export function reimbursementBaseName(date?: Date): string { const d = date ?? new Date() const y = d.getFullYear() const m = String(d.getMonth() + 1).padStart(2, '0') const day = String(d.getDate()).padStart(2, '0') return `报销单-${y}${m}${day}` }