Files
khb_microservices/packages/accounting_automation/src/invoices-mail.ts

322 lines
16 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { createHash } from "node:crypto";
import { mkdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
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 type { MailAttachment, MailMessage, MailSource } from "./gmail.js";
export interface InvoiceIngestDeps {
pool: Pool;
mail: MailSource;
drive: DriveStore;
claude: ClaudeRunner;
now(): Date;
log: Logger;
/** Сколько писем брать за запуск (по умолчанию 20). */
limit?: number;
/** Куда класть временные PDF для чтения агентом (по умолчанию os.tmpdir()). */
tmpDir?: string;
}
export interface InvoiceIngestResult {
/** Писем обработано (любой итог, включая ошибку). */
processed: number;
/** Создано записей acc_invoices_review. */
created: number;
/** Писем без инвойса. */
skipped: number;
errors: number;
}
export interface RecognizedInvoice {
is_invoice: boolean;
vendor_name: string | null;
invoice_number: string | null;
invoice_date: string | null;
amount: number | null;
lines: { description: string; amount: number | null }[] | null;
object_name_or_address: string | null;
}
// ----------------------------------------------------------------- нормализация и разбор
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(" ");
}
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" };
/** Объект/адрес для сравнения: регистр, знаки, сокращения улиц. */
export function normalizeAddress(s: string | null | undefined): string {
return (s ?? "")
.toLowerCase()
.replace(/[^a-z0-9а-яё]+/g, " ")
.split(" ")
.filter(Boolean)
.map((w) => STREET_WORDS[w] ?? w)
.join(" ");
}
/** Ключ «номер дома + первое слово улицы» (например, «734 placido»); null, если номера нет. */
export function addressKey(s: string | null | undefined): string | null {
const m = normalizeAddress(s).match(/(?:^|\s)(\d{1,6})\s+([a-zа-яё0-9]+)/);
return m ? `${m[1]} ${m[2]}` : null;
}
export function parseAmount(v: unknown): number | null {
if (typeof v === "number") return Number.isFinite(v) ? Math.round(v * 100) / 100 : null;
if (typeof v === "string") {
const n = Number(v.replace(/[^0-9.\-]/g, ""));
return v.trim() !== "" && Number.isFinite(n) ? Math.round(n * 100) / 100 : null;
}
return null;
}
function parseDate(v: unknown): string | null {
if (typeof v !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(v)) return null;
const d = new Date(`${v}T00:00:00Z`);
return Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== v ? null : v;
}
const str = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v.trim() : null);
/** Достаёт JSON-объект из ответа агента (допускает ```json-обёртку и текст вокруг). */
export function parseRecognition(stdout: string): RecognizedInvoice {
const a = stdout.indexOf("{");
const b = stdout.lastIndexOf("}");
if (a < 0 || b <= a) throw new Error("агент не вернул JSON");
let j: Record<string, unknown>;
try {
j = JSON.parse(stdout.slice(a, b + 1)) as Record<string, unknown>;
} catch (e) {
throw new Error(`агент вернул невалидный JSON: ${(e as Error).message}`);
}
if (typeof j.is_invoice !== "boolean") throw new Error("в JSON агента нет поля is_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,
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),
amount: parseAmount(j.amount),
lines: lines && lines.length ? lines : null,
object_name_or_address: str(j.object_name_or_address),
};
}
/** Детерминированный uuid записи инвойса: письмо + номер вложения + имя файла (повторный запуск не плодит дубли). */
export function invoiceReviewId(messageId: string, index: number, filename: string): string {
const h = createHash("sha1").update(`${messageId}\n${index}\n${filename}`).digest("hex");
const variant = ((parseInt(h.slice(16, 18), 16) & 0x3f) | 0x80).toString(16).padStart(2, "0");
return `${h.slice(0, 8)}-${h.slice(8, 12)}-5${h.slice(13, 16)}-${variant}${h.slice(18, 20)}-${h.slice(20, 32)}`;
}
export function buildRecognitionPrompt(pdfPath: string, mail: { from: string; subject: string }): string {
return [
"Ты распознаёшь счета (invoice) подрядчиков строительной компании.",
`Прочитай PDF-файл ${pdfPath} (письмо от ${mail.from}, тема «${mail.subject}») и верни ТОЛЬКО один JSON-объект, без пояснений и без markdown.`,
"Поля JSON:",
'- is_invoice: true, если документ - счёт/инвойс подрядчика к оплате; false для всего остального (КП, чек, страховка, реклама и т.п.)',
"- vendor_name: название компании, которая выставила счёт (не получатель)",
"- invoice_number: номер счёта",
"- invoice_date: дата счёта в формате YYYY-MM-DD",
"- amount: итоговая сумма к оплате, число в долларах",
'- lines: массив строк счёта [{"description": "за что", "amount": число}]',
"- object_name_or_address: название объекта или адрес, к которому относятся работы (Job, Project, Ship to, Site)",
"Если значение в документе не найдено, ставь null (не выдумывай).",
].join("\n");
}
// ----------------------------------------------------------------- сопоставление со справочниками
interface Resolved {
vendorQboId: string | null;
projectCustomerId: string | null;
contractId: string | null;
problems: string[];
}
async function resolveVendor(pool: Pool, name: string | null): Promise<{ id: string | null; problem?: string }> {
if (!name) return { id: null };
const want = normalizeVendorName(name);
const { rows } = await pool.query<{ id: string; display_name: string; company_name: string | null }>(
"select distinct id, display_name, company_name from qbo_vendor where active",
);
const ids = new Set<string>();
for (const r of rows) if (normalizeVendorName(r.display_name) === want || (r.company_name && normalizeVendorName(r.company_name) === want)) ids.add(r.id);
if (ids.size === 1) return { id: [...ids][0]! };
if (ids.size > 1) return { id: null, problem: `вендор «${name}» неоднозначен в QuickBooks (${ids.size} совпадений)` };
return { id: null, problem: `вендор «${name}» не найден в QuickBooks` };
}
async function resolveProject(pool: Pool, object: string | null): Promise<{ id: string | null; problem?: string }> {
if (!object) return { id: null, problem: "проект неясен: в инвойсе нет названия объекта или адреса" };
const want = normalizeAddress(object);
const wantKey = addressKey(object);
const { rows } = await pool.query<{ id: string; display_name: string; fully_qualified_name: string | null }>(
"select distinct id, display_name, fully_qualified_name from qbo_customer where is_job and active",
);
const ids = new Set<string>();
for (const r of rows) {
for (const n of [r.display_name, r.fully_qualified_name]) {
if (!n) continue;
const cn = normalizeAddress(n);
if (!cn) continue;
const ck = addressKey(n);
if ((wantKey && ck && wantKey === ck) || cn === want || (cn.length >= 5 && want.includes(cn)) || (want.length >= 5 && cn.includes(want))) {
ids.add(r.id);
break;
}
}
}
if (ids.size === 1) return { id: [...ids][0]! };
return { id: null, problem: `проект неясен (объект в инвойсе: «${object}», совпадений ${ids.size})` };
}
async function resolveAll(pool: Pool, r: RecognizedInvoice): Promise<Resolved> {
const problems: string[] = [];
const v = await resolveVendor(pool, r.vendor_name);
if (v.problem) problems.push(v.problem);
const p = await resolveProject(pool, r.object_name_or_address);
if (p.problem) problems.push(p.problem);
let contractId: string | null = null;
if (v.id && p.id) {
const { rows } = await pool.query<{ id: string }>("select id from acc_contracts where vendor_qbo_id = $1 and project_customer_id = $2", [v.id, p.id]);
if (rows.length === 1) contractId = rows[0]!.id;
else problems.push(rows.length ? "контракт неоднозначен (несколько контрактов вендора на проекте)" : "контракт вендора на этом проекте не найден");
}
return { vendorQboId: v.id, projectCustomerId: p.id, contractId, problems };
}
async function isDuplicate(pool: Pool, id: string, vendorQboId: string | null, r: RecognizedInvoice): Promise<boolean> {
if (!r.invoice_number || r.amount == null || !r.vendor_name) return false;
const vendorName = normalizeVendorName(r.vendor_name);
for (const t of ["acc_invoices", "acc_invoices_review"]) {
const { rows } = await pool.query<{ vendor_name: string | null; vendor_qbo_id: string | null }>(
`select vendor_name, vendor_qbo_id from ${t} where id <> $1 and invoice_number = $2 and amount = $3`,
[id, r.invoice_number, r.amount],
);
if (rows.some((x) => (vendorQboId && x.vendor_qbo_id === vendorQboId) || normalizeVendorName(x.vendor_name) === vendorName)) return true;
}
return false;
}
const safeName = (s: string): string => s.replace(/[\\/:*?"<>|\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, 100) || "_";
const ym = (d: Date): string => d.toISOString().slice(0, 7);
// ----------------------------------------------------------------- основной процесс
async function recognize(deps: InvoiceIngestDeps, msg: MailMessage, att: MailAttachment, bytes: Buffer): Promise<RecognizedInvoice> {
const dir = join(deps.tmpDir ?? tmpdir(), `acc-invoice-${createHash("sha1").update(`${msg.id}${att.filename}${deps.now().getTime()}${Math.random()}`).digest("hex").slice(0, 12)}`);
await mkdir(dir, { recursive: true });
try {
const path = join(dir, "invoice.pdf");
await writeFile(path, bytes);
const res = await deps.claude({ prompt: buildRecognitionPrompt(path, msg), cwd: dir });
if (!res.ok) throw new Error(`Claude не отработал (код ${res.exitCode}${res.timedOut ? ", таймаут" : ""}): ${res.stderr.slice(0, 200)}`);
return parseRecognition(res.stdout);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
/** Результат по одному вложению: created - новая запись; existing - запись уже есть; none - не инвойс. */
async function processAttachment(deps: InvoiceIngestDeps, msg: MailMessage, att: MailAttachment, index: number): Promise<"created" | "existing" | "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",
[id],
);
if (ex.rowCount) return "existing";
const bytes = await att.getBytes();
const rec = await recognize(deps, msg, att, bytes);
if (!rec.is_invoice) return "none";
const resolved = await resolveAll(pool, rec);
const problems = [...resolved.problems];
if (await isDuplicate(pool, id, resolved.vendorQboId, rec)) problems.push("подозрение на дубль (тот же вендор, номер и сумма уже есть)");
const tbd: string[] = [];
if (!rec.vendor_name) tbd.push("vendor_name");
if (!rec.invoice_number) tbd.push("invoice_number");
if (!rec.invoice_date) tbd.push("invoice_date");
if (rec.amount == null) tbd.push("amount");
if (!rec.lines) tbd.push("lines");
if (tbd.length) problems.unshift(`tbd: ${tbd.join(", ")}`);
const refDate = rec.invoice_date ? new Date(`${rec.invoice_date}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 pool.query(
`insert into acc_invoices_review (id, source_message_id, drive_file_id, vendor_name, vendor_qbo_id, invoice_number, invoice_date, amount, lines,
project_customer_id, contract_id, problem_highlight)
values ($1,$2,$3,$4,$5,$6,$7,$8,$9::jsonb,$10,$11,$12)
on conflict (id) do nothing`,
[
id, msg.id, file.id, rec.vendor_name, resolved.vendorQboId, rec.invoice_number, rec.invoice_date, rec.amount,
rec.lines ? JSON.stringify(rec.lines) : null, resolved.projectCustomerId, resolved.contractId, problems.length ? problems.join("; ") : null,
],
);
return "created";
}
async function markMail(pool: Pool, messageId: string, result: "invoice" | "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()`,
[messageId, result, JSON.stringify(details)],
);
}
/** Шаги 4.1-4.3 и 5 процесса «Обработка Invoice от подрядчика»: почта -> Drive -> распознавание -> acc_invoices_review. */
export async function runInvoiceIngest(deps: InvoiceIngestDeps): Promise<InvoiceIngestResult> {
const { pool, log } = deps;
const out: InvoiceIngestResult = { processed: 0, created: 0, skipped: 0, errors: 0 };
const messages = await deps.mail.listUnprocessed(deps.limit ?? 20);
for (const msg of messages) {
const prev = await pool.query<{ result: string }>("select result from acc_mail_processed where message_id = $1", [msg.id]);
if (prev.rows[0] && prev.rows[0].result !== "error") continue;
out.processed++;
try {
const pdfs = msg.attachments.filter((a) => a.mime.toLowerCase() === "application/pdf" || a.filename.toLowerCase().endsWith(".pdf"));
let invoices = 0;
let created = 0;
for (const [i, att] of pdfs.entries()) {
const r = await processAttachment(deps, msg, att, i);
if (r !== "none") invoices++;
if (r === "created") {
created++;
out.created++;
}
}
if (invoices > 0) await markMail(pool, msg.id, "invoice", { attachments: pdfs.length, invoices, created });
else {
out.skipped++;
await markMail(pool, msg.id, "skipped", { attachments: pdfs.length, reason: pdfs.length ? "не инвойс" : "нет PDF" });
}
} catch (e) {
out.errors++;
log.error({ err: e, messageId: msg.id }, "ошибка обработки письма с инвойсом");
await markMail(pool, msg.id, "error", { message: (e as Error).message });
}
}
return out;
}