/** * invoice-model.ts — 发票字段模型、XML/文本正则抽取、金额勾稽校验(纯逻辑,零依赖)。 * * 该模块按国内增值税电子发票(数电票/全电发票)的实际字段规范自写: * - XML 附件(offlineinvoice / Envelope)优先:通过候选标签白名单(中英双语)抽取字段; * - 文本层兜底:标签定位 + 正则(票号 \d{8,20}、金额/税额/价税合计、日期、双方名称); * - 勾稽校验:价税合计 = 金额 + 税额(容差 0.01); * - confidence:XML 直读=高,正则=中,关键字段缺失=低并列出缺失清单。 * * 本模块不 import 任何外部运行时依赖(仅类型安全),可被离线测试直接执行。 */ /** 购买方 / 销售方信息。 */ export interface InvoiceParty { /** 名称(默认空串表示字段缺失)。 */ name: string /** 税号。 */ taxId: string } /** 一条校验结果(勾稽、字段合法性等)。 */ export interface InvoiceCheck { label: string ok: boolean detail?: string } /** 抽取来源。 */ export type InvoiceSourceMethod = 'xml' | 'regex' | 'mixed' /** 置信度:XML 直读=high,正则=medium,关键字段缺失=low。 */ export type InvoiceConfidence = 'high' | 'medium' | 'low' /** 结构化发票数据(DSH 会话内流转的唯一业务对象)。 */ export interface InvoiceData { /** 发票代码(全电发票可为空)。 */ invoiceCode: string /** 发票号码(至少 8 位数字)。 */ invoiceNumber: string /** 金额(不含税)。 */ amount: number /** 税额。 */ tax: number /** 价税合计。 */ total: number /** 开票日期 YYYY-MM-DD。 */ issueDate: string buyer: InvoiceParty seller: InvoiceParty /** 查验平台网址(可选,默认不发起任何查验请求)。 */ verifyUrl?: string /** 费用类别(汇总时按类别小计;未指定为 undefined,归入"未分类")。 */ category?: string /** 校验结果列表(勾稽等)。 */ checks: InvoiceCheck[] /** 抽取来源元信息。 */ source: { /** 源文件名(basename)。 */ file: string method: InvoiceSourceMethod confidence: InvoiceConfidence /** 缺失字段清单(关键字段缺失会拉低 confidence)。 */ missing: string[] /** 文本正则路径命中的规则名(仅用于诊断)。 */ matchedRules?: string[] } } /** 解析出的原始字段(值为抽取出的字符串,未做数值/日期归一)。 */ export interface RawInvoiceFields { invoiceCode?: string invoiceNumber?: string amount?: string tax?: string total?: string issueDate?: string buyerName?: string buyerTaxId?: string sellerName?: string sellerTaxId?: string verifyUrl?: string } /** 关键字段:缺失会拉低 confidence / 影响勾稽与汇总。 */ export const KEY_FIELDS = ['invoiceNumber', 'amount', 'tax', 'total'] as const /** 勾稽容差(元)。 */ export const TOTAL_TOLERANCE = 0.01 /** 数值型候选标签(XML 附件标签名,中英双语,按国内数电票常见 Schema 收集)。 */ const NUMERIC_TAG_CANDIDATES: Record<'invoiceCode' | 'invoiceNumber' | 'amount' | 'tax' | 'total', string[]> = { invoiceCode: ['发票代码', 'InvoiceCode', 'FPDM'], invoiceNumber: ['发票号码', 'InvoiceNo', 'InvoiceNumber', 'FPHM'], amount: ['金额', 'TaxExclusiveAmount', 'AmountWithoutTax', 'PretaxAmount', 'KCE', 'Amount'], tax: ['税额', 'TaxAmount', 'TotalTaxAmount', 'SE'], total: ['价税合计', 'TaxInclusiveAmount', 'AmountWithTax', 'InvoiceAmount', 'FPHJJE', 'Total'], } /** 文本型候选标签。 */ const TEXT_TAG_CANDIDATES: Record<'issueDate' | 'buyerName' | 'buyerTaxId' | 'sellerName' | 'sellerTaxId' | 'verifyUrl', string[]> = { issueDate: ['开票日期', 'IssueDate', 'BillingDate', 'KPRQ', 'InvoiceDate'], buyerName: ['购买方名称', 'BuyerName', 'PurchaserName', 'GMFMC'], buyerTaxId: ['购买方纳税人识别号', 'BuyerTaxId', 'PurchaserTaxId', 'GMFSBH'], sellerName: ['销售方名称', 'SellerName', 'SupplierName', 'XSFMC'], sellerTaxId: ['销售方纳税人识别号', 'SellerTaxId', 'SupplierTaxId', 'XSFSBH'], verifyUrl: ['查验平台网址', 'VerifyUrl', 'CheckUrl', 'CZPT'], } /** * 金额字符串归一:去掉 ¥/¥/逗号/空白,支持可选负号(红字发票), * 返回有限数值;无法解析返回 null。 */ export function normalizeMoney(raw: string): number | null { const cleaned = raw.replace(/[¥¥,,\s]/g, '') if (!/^-?\d+(\.\d+)?$/.test(cleaned)) return null const n = Number(cleaned) return Number.isFinite(n) ? n : null } /** * 日期字符串归一为 YYYY-MM-DD。接受 20240105 / 2024-01-05 / 2024年01月05日 等。 * 解析失败返回 null。 */ export function normalizeDate(raw: string): string | null { const m = /(\d{4})[-年.\/]?(\d{1,2})[-月.\/]?(\d{1,2})日?/.exec(raw.trim()) if (!m) return null const y = m[1] const mo = String(Number(m[2])).padStart(2, '0') const d = String(Number(m[3])).padStart(2, '0') if (Number(mo) < 1 || Number(mo) > 12 || Number(d) < 1 || Number(d) > 31) return null return `${y}-${mo}-${d}` } /** * 收集 XML 中所有"叶子"双标签 value(value 内不含子标签): * 以栈配对开始/结束标签,从最内层向外记录叶子值,保序、去重(同名标签取第一个)。 * 不依赖任何 DOM 解析器,兼容中英文标签名。 */ export function collectXmlTags(xml: string): Map { const map = new Map() const tagRe = /<\/?([A-Za-z_\u4e00-\u9fa5A-Z][A-Za-z0-9_\u4e00-\u9fa5.\-]*)(?:\s[^>]*)?>/g const stack: { tag: string; contentStart: number }[] = [] let m: RegExpExecArray | null while ((m = tagRe.exec(xml)) !== null) { const token = m[0] const tag = m[1] if (token.startsWith('= 0; i--) { if (stack[i].tag === tag) { found = i break } } if (found >= 0) { const open = stack[found] stack.length = found const content = xml.slice(open.contentStart, m.index) // 叶子:内容不含子标签 if (!content.includes('<') && content.trim().length > 0 && !map.has(tag)) { map.set(tag, content.trim()) } } } else if (!token.endsWith('/>')) { stack.push({ tag, contentStart: m.index + token.length }) } } return map } /** 依候选标签白名单从 XML 标签表抽取原始字段。 */ export function fieldsFromXmlTags(tags: Map): RawInvoiceFields { const fields: RawInvoiceFields = {} for (const [field, candidates] of Object.entries(NUMERIC_TAG_CANDIDATES) as [keyof RawInvoiceFields, string[]][]) { for (const tag of candidates) { const value = tags.get(tag) if (value !== undefined && normalizeMoney(value) !== null) { fields[field] = value break } } } for (const [field, candidates] of Object.entries(TEXT_TAG_CANDIDATES)) { for (const tag of candidates) { const value = tags.get(tag) if (value !== undefined && value.length > 0) { fields[field as keyof RawInvoiceFields] = value break } } } return fields } // --------------------------------------------------------------------------- // 文本层正则规则(无 XML 时的兜底路径) // --------------------------------------------------------------------------- /** 正则抽取结果:字段 + 命中规则名。 */ export interface TextParseResult { fields: RawInvoiceFields matchedRules: string[] } /** * 从 PDF 文本层抽取发票字段。规则按标签定位 + 正则: * - 票号 \d{8,20}(发票号码 / 发票代码标签后); * - 金额/税额/价税合计:标签后(大写…小写)括号段跳过,取小写数值; * - 开票日期、双方名称、纳税人识别号、查验平台网址。 */ export function parseInvoiceFromText(text: string): TextParseResult { const fields: RawInvoiceFields = {} const matchedRules: string[] = [] // 压缩连续空白,避免"标签 值"匹配失败;t1 再把换行抹平为空格, // 使【金额(大写)…\n(小写)¥x】之类跨行写法也能被金额规则匹配到。 const t = text.replace(/[ \t\u00a0]+/g, ' ') const t1 = t.replace(/\n/g, ' ') // 发票代码 / 发票号码:\d{8,20},先号码后代码 let m = /发票号码[:: ]*([0-9]{8,20})/.exec(t) if (m) { fields.invoiceNumber = m[1] matchedRules.push('invoiceNumber') } // 兜底:无"发票号码"标签时取文本中全部 8-20 位数字里最长者(全电票号 20 位, // 通常长于发票代码;无发票语义的普通文档会因其他关键字段缺失而降 confidence)。 if (!fields.invoiceNumber) { const nums = [...t.matchAll(/[0-9]{8,20}/g)].map((x) => x[0]) const best = nums.sort((a, b) => b.length - a.length)[0] if (best !== undefined && t.includes('发票')) { fields.invoiceNumber = best matchedRules.push('invoiceNumber-fallback') } } m = /发票代码[:: ]*([0-9]{6,20})/.exec(t) if (m) { fields.invoiceCode = m[1] matchedRules.push('invoiceCode') } // 日期:2024年01月05日 / 2024-01-05 m = /开票日期[:: ]*(\d{4})[年\-.\/](\d{1,2})[月\-.\/](\d{1,2})日?/.exec(t) if (m) { const normalized = normalizeDate(`${m[1]}-${m[2]}-${m[3]}`) if (normalized) { fields.issueDate = normalized matchedRules.push('issueDate') } } // 金额 / 税额 / 价税合计:标签后允许 ≤2 个(大写)…(小写)括号段(段间可含大写金额 // 等非数字文本),再取数值。forbidBefore 为可选的"禁止前缀"字符类:'金额'/'税额' 是 // '合计金额'/'合计税额' 等标签的后缀,直接以标签子串匹配会命中合计行——真实版式里 // "合计金额…(小写)¥价税合计数值" 会把价税合计误绑成金额。故金额/税额排除 // '合/计/价/税' 前缀(合计金额、价税合计金额),价税合计以精确标签单独处理。 const moneyRule = (label: string, forbidBefore?: string): string | null => { const head = forbidBefore ? `(? TOTAL_TOLERANCE ? `(差 ${diff.toFixed(2)})` : ''}`, }) checks.push({ label: '金额/税额非负', ok: invoice.amount >= 0 && invoice.tax >= 0, detail: `金额 ${invoice.amount.toFixed(2)} / 税额 ${invoice.tax.toFixed(2)}` }) checks.push({ label: '票号格式', ok: /^[0-9]{8,20}$/.test(invoice.invoiceNumber), detail: invoice.invoiceNumber || '(空)' }) checks.push({ label: '开票日期格式', ok: invoice.issueDate === '' || /^\d{4}-\d{2}-\d{2}$/.test(invoice.issueDate), detail: invoice.issueDate || '(空)' }) return checks } /** XML 路径解析:从结构化 XML 抽取字段并装配(可选文本层补齐,method 变 mixed)。 */ export function parseInvoiceFromXml(xml: string, fileName: string, fallbackText?: string): InvoiceData { const tags = collectXmlTags(xml) const fields = fieldsFromXmlTags(tags) let method: InvoiceSourceMethod = 'xml' let matchedRules: string[] | undefined // XML 缺关键字段且提供文本层时:正则补齐(method -> mixed) const missingKeys = missingKeyFields(fields) if (missingKeys.length > 0 && fallbackText && fallbackText.trim().length > 0) { const textResult = parseInvoiceFromText(fallbackText) matchedRules = textResult.matchedRules for (const key of missingKeys) { const fieldKey = key === '发票号码' ? 'invoiceNumber' : key === '金额' ? 'amount' : key === '税额' ? 'tax' : 'total' const value = textResult.fields[fieldKey as keyof RawInvoiceFields] if (value !== undefined && (fieldKey === 'invoiceNumber' || normalizeMoney(value) !== null)) { fields[fieldKey as keyof RawInvoiceFields] = value } } if (missingKeyFields(fields).length === 0) method = 'mixed' } return buildInvoice(fields, fileName, method, matchedRules) } /** 文本正则路径解析。 */ export function parseInvoiceFromTextLines(text: string, fileName: string): InvoiceData { const { fields, matchedRules } = parseInvoiceFromText(text) return buildInvoice(fields, fileName, 'regex', matchedRules) }