Слияние части C этапа 2 (сертификаты, сверка, история, chargeback, fraud)

This commit is contained in:
2026-11-23 16:58:46 +03:00
32 changed files with 2620 additions and 38 deletions

View File

@@ -5,6 +5,8 @@ import { join } from "node:path";
import type { Logger, Pool } from "khb_common";
import type { ClaudeRunner } from "./claude-runner.js";
import type { DriveStore } from "./drive.js";
import { ingestCertificate } from "./certificates-ingest.js";
import { normalizeVendorName } from "./vendor-name.js";
import type { MailAttachment, MailMessage, MailSource } from "./gmail.js";
export interface InvoiceIngestDeps {
@@ -27,10 +29,17 @@ export interface InvoiceIngestResult {
/** Писем без инвойса. */
skipped: number;
errors: number;
/** Страховых сертификатов сохранено (только если были; процесс «Страховые сертификаты подрядчиков», шаг 2). */
certificates?: number;
}
export interface RecognizedInvoice {
is_invoice: boolean;
/** invoice, certificate (страховой сертификат), other. Нет в ответе агента - выводится из is_invoice. */
document_type?: "invoice" | "certificate" | "other";
/** Для сертификата: страховая компания и дата окончания полиса (YYYY-MM-DD); vendor_name - застрахованный подрядчик. */
insurer?: string | null;
valid_until?: string | null;
vendor_name: string | null;
invoice_number: string | null;
invoice_date: string | null;
@@ -41,19 +50,7 @@ export interface RecognizedInvoice {
// ----------------------------------------------------------------- нормализация и разбор
const COMPANY_SUFFIX = new Set(["llc", "inc", "corp", "co", "ltd", "company", "corporation", "incorporated", "lp", "llp", "pllc"]);
/** Имя вендора для сравнения: регистр, знаки, юридические суффиксы. */
export function normalizeVendorName(s: string | null | undefined): string {
const words = (s ?? "")
.toLowerCase()
.replace(/&/g, " and ")
.replace(/[^a-z0-9а-яё]+/g, " ")
.split(" ")
.filter(Boolean);
while (words.length > 1 && COMPANY_SUFFIX.has(words[words.length - 1]!)) words.pop();
return words.join(" ");
}
export { normalizeVendorName };
const STREET_WORDS: Record<string, string> = { street: "st", avenue: "ave", road: "rd", drive: "dr", lane: "ln", court: "ct", boulevard: "blvd", place: "pl", terrace: "ter", circle: "cir", way: "way" };
@@ -102,14 +99,19 @@ export function parseRecognition(stdout: string): RecognizedInvoice {
} catch (e) {
throw new Error(`агент вернул невалидный JSON: ${(e as Error).message}`);
}
if (typeof j.is_invoice !== "boolean") throw new Error("в JSON агента нет поля is_invoice");
const docType = j.document_type === "invoice" || j.document_type === "certificate" || j.document_type === "other" ? j.document_type : undefined;
if (typeof j.is_invoice !== "boolean" && !docType) throw new Error("в JSON агента нет поля is_invoice");
const isInvoice = typeof j.is_invoice === "boolean" ? j.is_invoice && docType !== "certificate" : docType === "invoice";
const lines = Array.isArray(j.lines)
? j.lines
.filter((l): l is Record<string, unknown> => !!l && typeof l === "object")
.map((l) => ({ description: str(l.description) ?? "", amount: parseAmount(l.amount) }))
: null;
return {
is_invoice: j.is_invoice,
is_invoice: isInvoice,
document_type: docType ?? (isInvoice ? "invoice" : "other"),
insurer: str(j.insurer),
valid_until: parseDate(j.valid_until),
vendor_name: str(j.vendor_name),
invoice_number: str(j.invoice_number) ?? (typeof j.invoice_number === "number" ? String(j.invoice_number) : null),
invoice_date: parseDate(j.invoice_date),
@@ -132,6 +134,8 @@ export function buildRecognitionPrompt(pdfPath: string, mail: { from: string; su
`Прочитай PDF-файл ${pdfPath} (письмо от ${mail.from}, тема «${mail.subject}») и верни ТОЛЬКО один JSON-объект, без пояснений и без markdown.`,
"Поля JSON:",
'- is_invoice: true, если документ - счёт/инвойс подрядчика к оплате; false для всего остального (КП, чек, страховка, реклама и т.п.)',
'- document_type: "invoice" (счёт к оплате), "certificate" (страховой сертификат, например ACORD certificate of liability insurance) или "other"',
"- для certificate: vendor_name - застрахованный подрядчик (Insured), insurer - страховая компания, valid_until - дата окончания действия полиса YYYY-MM-DD (если полисов несколько, самая ранняя дата окончания); остальные поля инвойса можно оставить null",
"- vendor_name: название компании, которая выставила счёт (не получатель)",
"- invoice_number: номер счёта",
"- invoice_date: дата счёта в формате YYYY-MM-DD",
@@ -236,17 +240,31 @@ async function recognize(deps: InvoiceIngestDeps, msg: MailMessage, att: MailAtt
}
/** Результат по одному вложению: created - новая запись; existing - запись уже есть; none - не инвойс. */
async function processAttachment(deps: InvoiceIngestDeps, msg: MailMessage, att: MailAttachment, index: number): Promise<"created" | "existing" | "none"> {
async function processAttachment(deps: InvoiceIngestDeps, msg: MailMessage, att: MailAttachment, index: number): Promise<"created" | "existing" | "certificate" | "none"> {
const { pool } = deps;
const id = invoiceReviewId(msg.id, index, att.filename);
const ex = await pool.query(
"select 1 from acc_invoices_review where id = $1 union all select 1 from acc_invoices_review_history where id = $1 union all select 1 from acc_invoices where id = $1",
`select 1 from acc_invoices_review where id = $1 union all select 1 from acc_invoices_review_history where id = $1 union all select 1 from acc_invoices where id = $1
union all select 1 from acc_insurance_certificates where id = $1 union all select 1 from acc_certificates_review where id = $1
union all select 1 from acc_certificates_review_history where id = $1`,
[id],
);
if (ex.rowCount) return "existing";
const bytes = await att.getBytes();
const rec = await recognize(deps, msg, att, bytes);
if (rec.document_type === "certificate") {
// Процесс «Страховые сертификаты подрядчиков», шаг 2: файл в папку «Страховки», запись в acc_insurance_certificates
const vendor = await resolveVendor(pool, rec.vendor_name);
const refDate = rec.valid_until ? new Date(`${rec.valid_until}T00:00:00Z`) : msg.receivedAt;
const folder = await deps.drive.ensureFolder(["Страховки", safeName(rec.vendor_name ?? "Без вендора"), ym(refDate)]);
const file = await deps.drive.upload(att.filename, att.mime || "application/pdf", bytes, folder);
await ingestCertificate(pool, {
id, messageId: msg.id, driveFileId: file.id, vendorName: rec.vendor_name, vendorQboId: vendor.id, insurer: rec.insurer ?? null,
validUntil: rec.valid_until ?? null, now: deps.now(),
});
return "certificate";
}
if (!rec.is_invoice) return "none";
const resolved = await resolveAll(pool, rec);
@@ -277,7 +295,7 @@ async function processAttachment(deps: InvoiceIngestDeps, msg: MailMessage, att:
return "created";
}
async function markMail(pool: Pool, messageId: string, result: "invoice" | "skipped" | "error", details: unknown): Promise<void> {
async function markMail(pool: Pool, messageId: string, result: "invoice" | "certificate" | "skipped" | "error", details: unknown): Promise<void> {
await pool.query(
`insert into acc_mail_processed (message_id, result, details) values ($1,$2,$3::jsonb)
on conflict (message_id) do update set result = excluded.result, details = excluded.details, processed_at = now()`,
@@ -298,15 +316,22 @@ export async function runInvoiceIngest(deps: InvoiceIngestDeps): Promise<Invoice
const pdfs = msg.attachments.filter((a) => a.mime.toLowerCase() === "application/pdf" || a.filename.toLowerCase().endsWith(".pdf"));
let invoices = 0;
let created = 0;
let certificates = 0;
for (const [i, att] of pdfs.entries()) {
const r = await processAttachment(deps, msg, att, i);
if (r === "certificate") {
certificates++;
out.certificates = (out.certificates ?? 0) + 1;
continue;
}
if (r !== "none") invoices++;
if (r === "created") {
created++;
out.created++;
}
}
if (invoices > 0) await markMail(pool, msg.id, "invoice", { attachments: pdfs.length, invoices, created });
if (invoices > 0) await markMail(pool, msg.id, "invoice", { attachments: pdfs.length, invoices, created, certificates });
else if (certificates > 0) await markMail(pool, msg.id, "certificate", { attachments: pdfs.length, certificates });
else {
out.skipped++;
await markMail(pool, msg.id, "skipped", { attachments: pdfs.length, reason: pdfs.length ? "не инвойс" : "нет PDF" });