Files
SupplierSystem/server/src/services/invoiceOcrService.ts
T
Ubuntu 5fa2bbfd55
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
fix(audit-20261019): T1-T9 审计修复、存储归属与审计日志列宽
- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14)
- T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9)
- T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4)
- T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8)
- T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15)
- T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8)
- T7 前后端测试与 lint 门禁清零
- T8 应付卡片按关联订单日(口径 A)
- T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
2026-10-19 16:16:51 +08:00

177 lines
6.1 KiB
TypeScript

import { callWithFile, callWithImage, hasRuntimeConfig } from './llmService';
import { resolvePrompt } from './promptRegistryService';
import { getStorageProvider } from './storageProvider';
import { safeStorageFileName, stripStorageBranchPrefix } from './storageBucketConfig';
export interface InvoiceOcrResult {
invoice_no: string | null;
invoice_code: string | null;
invoice_date: string | null;
seller_name: string | null;
seller_tax_no: string | null;
buyer_name: string | null;
buyer_tax_no: string | null;
amount: number | null;
tax_rate: number | null;
tax_amount: number | null;
total_amount: number | null;
items: Array<{ name: string; quantity: number; price: number; amount: number }>;
confidence: number | null;
raw_text: string | null;
}
const SUPPLIER_INVOICE_FOLDER = 'supplier-invoices/';
export function emptyInvoiceOcrResult(): InvoiceOcrResult {
return {
invoice_no: null,
invoice_code: null,
invoice_date: null,
seller_name: null,
seller_tax_no: null,
buyer_name: null,
buyer_tax_no: null,
amount: null,
tax_rate: null,
tax_amount: null,
total_amount: null,
items: [],
confidence: null,
raw_text: null,
};
}
function parseJson(text: string): Record<string, unknown> | null {
const s = text.trim();
const start = s.indexOf('{');
const end = s.lastIndexOf('}');
if (start < 0 || end <= start) return null;
try {
return JSON.parse(s.slice(start, end + 1));
} catch {
return null;
}
}
function normalizeNumber(value: unknown): number | null {
if (value === null || value === undefined) return null;
const num = Number(value);
return Number.isFinite(num) ? num : null;
}
function normalizeItems(raw: unknown): Array<{ name: string; quantity: number; price: number; amount: number }> {
if (!Array.isArray(raw)) return [];
return raw.map((item: Record<string, unknown>) => ({
name: String(item?.name || '').trim(),
quantity: normalizeNumber(item?.quantity) ?? 0,
price: normalizeNumber(item?.price) ?? 0,
amount: normalizeNumber(item?.amount) ?? 0,
}));
}
function resultFromAiText(raw: string | null): InvoiceOcrResult {
if (!raw) return emptyInvoiceOcrResult();
const parsed = parseJson(raw);
if (!parsed) return { ...emptyInvoiceOcrResult(), raw_text: raw };
return {
invoice_no: parsed.invoice_no ? String(parsed.invoice_no).trim() : null,
invoice_code: parsed.invoice_code ? String(parsed.invoice_code).trim() : null,
invoice_date: parsed.invoice_date ? String(parsed.invoice_date).trim() : null,
seller_name: parsed.seller_name ? String(parsed.seller_name).trim() : null,
seller_tax_no: parsed.seller_tax_no ? String(parsed.seller_tax_no).trim() : null,
buyer_name: parsed.buyer_name ? String(parsed.buyer_name).trim() : null,
buyer_tax_no: parsed.buyer_tax_no ? String(parsed.buyer_tax_no).trim() : null,
amount: normalizeNumber(parsed.amount),
tax_rate: normalizeNumber(parsed.tax_rate),
tax_amount: normalizeNumber(parsed.tax_amount),
total_amount: normalizeNumber(parsed.total_amount),
items: normalizeItems(parsed.items),
confidence: normalizeNumber(parsed.confidence),
raw_text: parsed.raw_text ? String(parsed.raw_text) : raw,
};
}
/** 供应商结算发票对象路径,禁止读其它 invoices 子目录 */
export function assertSupplierInvoiceStoragePath(raw: string): string {
const text = String(raw || '').trim();
if (!text) {
throw Object.assign(new Error('缺少发票路径'), { status: 400, code: 'invalid_request' });
}
let safe: string;
try {
safe = safeStorageFileName(text);
} catch {
throw Object.assign(new Error('发票路径无效'), { status: 400, code: 'invalid_request' });
}
// SEC-5:允许新 key 的 `<branch>/` 前缀(校验用去前缀视图,读写仍用完整 key)
if (!stripStorageBranchPrefix(safe).startsWith(SUPPLIER_INVOICE_FOLDER)) {
throw Object.assign(new Error('仅支持 supplier-invoices 发票'), { status: 400, code: 'invalid_request' });
}
return safe;
}
export async function scanInvoice(
imageBase64: string,
branchCode?: string | null
): Promise<InvoiceOcrResult> {
if (!(await hasRuntimeConfig({ branchCode: branchCode || undefined }))) {
return emptyInvoiceOcrResult();
}
try {
const prompt = await resolvePrompt('invoice.ocr', { branchCode });
const raw = await callWithImage(prompt.systemPrompt, imageBase64, {
branchCode: branchCode || undefined,
});
return resultFromAiText(raw);
} catch {
return emptyInvoiceOcrResult();
}
}
/** 与检验报告 PDF 相同:方舟 Files API / callWithFile,不用视觉 */
export async function scanInvoicePdf(
contentBase64: string,
branchCode?: string | null
): Promise<InvoiceOcrResult> {
if (!contentBase64 || !(await hasRuntimeConfig({ branchCode: branchCode || undefined }))) {
return emptyInvoiceOcrResult();
}
try {
const prompt = await resolvePrompt('invoice.ocr', { branchCode });
const dataUrl = contentBase64.startsWith('data:')
? contentBase64
: `data:application/pdf;base64,${contentBase64}`;
const raw = await callWithFile(
`${prompt.systemPrompt}\n当前是 PDF 发票文件,请从文档中抄录字段,只输出 JSON。`,
dataUrl,
{
branchCode: branchCode || undefined,
filename: 'invoice.pdf',
mime: 'application/pdf',
}
);
return resultFromAiText(raw);
} catch {
return emptyInvoiceOcrResult();
}
}
export async function scanInvoiceFromStoredPath(
objectName: string,
branchCode?: string | null
): Promise<InvoiceOcrResult> {
const safe = assertSupplierInvoiceStoragePath(objectName);
const obj = await getStorageProvider().getObject('invoices', safe);
if (!obj?.buffer?.length) {
throw Object.assign(new Error('发票文件不存在或无法读取'), { status: 404, code: 'not_found' });
}
const ext = (safe.split('.').pop() || '').toLowerCase();
const b64 = obj.buffer.toString('base64');
if (ext === 'pdf') {
return scanInvoicePdf(b64, branchCode);
}
const mime = ext === 'png' ? 'image/png' : ext === 'webp' ? 'image/webp' : 'image/jpeg';
return scanInvoice(`data:${mime};base64,${b64}`, branchCode);
}