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

445 lines
26 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 { execFile } from "node:child_process";
import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { extname, join } from "node:path";
import { promisify } from "node:util";
import type { Logger, Pool } from "khb_common";
import type { ClaudeRunner } from "./claude-runner.js";
import { UNTRUSTED_DOC_ARGS } from "./claude-runner.js";
import type { DriveStore } from "./drive.js";
import { invoiceFileName, invoiceFolderPath } from "./invoice-filing.js";
import { ingestCertificate } from "./certificates-ingest.js";
import { normalizeVendorName } from "./vendor-name.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;
/** Страховых сертификатов сохранено (только если были; процесс «Страховые сертификаты подрядчиков», шаг 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;
amount: number | null;
lines: { description: string; amount: number | null }[] | null;
object_name_or_address: string | null;
}
// ----------------------------------------------------------------- нормализация и разбор
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" };
/** Объект/адрес для сравнения: регистр, знаки, сокращения улиц. */
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}`);
}
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: 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),
amount: parseAmount(j.amount),
lines: lines && lines.length ? lines : null,
object_name_or_address: str(j.object_name_or_address),
};
}
/** Вендор - сама компания (KH Build LLC): такой счёт исходящий. */
export function isOwnCompany(vendorName: string | null | undefined): boolean {
return !!vendorName && /^\s*kh[\s.-]*build\b/i.test(vendorName);
}
/** Детерминированный 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) подрядчиков строительной компании.",
`Прочитай файл ${pdfPath} (письмо от ${mail.from}, тема «${mail.subject}») и верни ТОЛЬКО один JSON-объект, без пояснений и без markdown.`,
"Формат файла определи по расширению: PDF и картинки читай инструментом Read; docx и xlsx - это zip-архивы, распакуй их командой unzip и прочитай XML внутри; html, txt, csv читай как текст (для HTML игнорируй вёрстку и скрипты, смотри на видимый текст и таблицы). Файл может быть и самим письмом (letter.html или letter.txt): инвойс может быть прямо в теле письма.",
"Поля 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",
"- amount: итоговая сумма к оплате, число в долларах",
'- lines: массив строк счёта [{"description": "за что", "amount": число}]',
"- object_name_or_address: название объекта или адрес, к которому относятся работы (Job, Project, Ship to, Site)",
"Нас интересуют только ВХОДЯЩИЕ счета: счёт, который подрядчик или поставщик выставил компании KH Build LLC (мы - плательщик). Счета, которые выставила сама KH Build LLC (клиентам, например «New payment request from KH Build LLC», счета KHB-..., уведомления QuickBooks Payments о получении оплаты), - исходящие: для них is_invoice = false, document_type = \"other\".",
"Если значение в документе не найдено, ставь 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` };
}
export 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 };
}
/**
* Дубль инвойса (тот же вендор и номер): same - сумма та же (повторная отправка или пересылка внутри компании), второй задачи не создаём;
* amount_differs - номер тот же, сумма другая (корректировка счёта): создаём, но подсвечиваем. Смотрим и историю разбора.
*/
async function findDuplicate(pool: Pool, id: string, vendorQboId: string | null, r: RecognizedInvoice): Promise<"same" | "amount_differs" | null> {
if (!r.invoice_number || !r.vendor_name) return null;
const vendorName = normalizeVendorName(r.vendor_name);
let result: "same" | "amount_differs" | null = null;
for (const t of ["acc_invoices", "acc_invoices_review", "acc_invoices_review_history"]) {
const { rows } = await pool.query<{ vendor_name: string | null; vendor_qbo_id: string | null; amount: string | null }>(
`select vendor_name, vendor_qbo_id, amount from ${t} where id <> $1 and invoice_number = $2`,
[id, r.invoice_number],
);
for (const x of rows) {
if (!((vendorQboId && x.vendor_qbo_id === vendorQboId) || normalizeVendorName(x.vendor_name) === vendorName)) continue;
if (r.amount != null && x.amount != null && Number(x.amount) === Number(r.amount)) return "same";
result = "amount_differs";
}
}
return result;
}
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);
// ----------------------------------------------------------------- основной процесс
const run = promisify(execFile);
/** Расширения вложений, которые имеет смысл читать (остальное - календарь, видео и т.п. - пропускаем). */
const DOC_EXT = new Set([".pdf", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".tif", ".tiff", ".docx", ".doc", ".xlsx", ".xls", ".csv", ".txt", ".html", ".htm", ".rtf", ".odt", ".ods", ".zip"]);
const MAX_DOC_BYTES = 25 * 1024 * 1024;
const extOf = (name: string): string => extname(name).toLowerCase();
/** Файлы внутри zip (unzip из системы; один уровень, не больше 20 файлов); нечитаемый архив - пустой список. */
export async function expandZip(att: MailAttachment, tmp: string): Promise<MailAttachment[]> {
const dir = join(tmp, `acc-zip-${createHash("sha1").update(`${att.filename}${Math.random()}`).digest("hex").slice(0, 10)}`);
await mkdir(dir, { recursive: true });
try {
const zipPath = join(dir, "a.zip");
await writeFile(zipPath, await att.getBytes());
const outDir = join(dir, "x");
await mkdir(outDir);
await run("unzip", ["-o", "-q", zipPath, "-d", outDir], { timeout: 60_000 });
const found: { rel: string; abs: string }[] = [];
const walkDir = async (d: string, rel: string): Promise<void> => {
for (const e of await readdir(d, { withFileTypes: true })) {
if (found.length >= 20) return;
if (e.isDirectory()) await walkDir(join(d, e.name), `${rel}${e.name}/`);
else if (DOC_EXT.has(extOf(e.name)) && extOf(e.name) !== ".zip") found.push({ rel: `${rel}${e.name}`, abs: join(d, e.name) });
}
};
await walkDir(outDir, "");
const out: MailAttachment[] = [];
for (const f of found) {
if ((await stat(f.abs)).size > MAX_DOC_BYTES) continue;
const bytes = await readFile(f.abs);
out.push({ filename: `${att.filename}/${f.rel}`, mime: "application/octet-stream", getBytes: async () => bytes });
}
return out;
} catch {
return [];
} finally {
await rm(dir, { recursive: true, force: true });
}
}
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 ext = extOf(att.filename);
const path = join(dir, `invoice${DOC_EXT.has(ext) ? ext : ".bin"}`);
await writeFile(path, bytes);
const res = await deps.claude({ prompt: buildRecognitionPrompt(path, msg), cwd: dir, extraArgs: UNTRUSTED_DOC_ARGS });
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" | "duplicate" | "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
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/octet-stream", 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";
// страховка от ошибки распознавания: счёт, выставленный самой KH Build, - исходящий, в разбор входящих не берём
if (isOwnCompany(rec.vendor_name)) {
deps.log.info({ messageId: msg.id, invoice: rec.invoice_number }, "исходящий счёт KH Build (вендор - мы сами): в разбор входящих не берётся");
return "none";
}
const resolved = await resolveAll(pool, rec);
const problems = [...resolved.problems];
const dup = await findDuplicate(pool, id, resolved.vendorQboId, rec);
if (dup === "same") {
deps.log.info({ messageId: msg.id, vendor: rec.vendor_name, invoice: rec.invoice_number }, "дубль инвойса (вендор, номер и сумма совпали): вторая задача не создаётся");
return "duplicate";
}
if (dup === "amount_differs") 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;
// раскладка как в папке «07. Invoices» Анастасии: способ оплаты / месяц / «$сумма Вендор.pdf»; способ оплаты неизвестен до оплаты - «Без оплаты»,
// после оплаты файл переносится в папку счёта оплаты (invoice-filing.ts)
const folder = await deps.drive.ensureFolder(invoiceFolderPath(null, refDate));
const file = await deps.drive.upload(invoiceFileName(rec.amount, rec.vendor_name, att.filename), att.mime || "application/octet-stream", 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" | "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()`,
[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 {
// документы письма: вложения любого читаемого вида, содержимое zip; тело письма - если во вложениях инвойса нет
const pdfs: MailAttachment[] = [];
for (const a of msg.attachments) {
const ext = extOf(a.filename);
if (!DOC_EXT.has(ext) && !a.mime.toLowerCase().startsWith("image/")) continue;
if (ext === ".zip" || a.mime.toLowerCase().includes("zip")) pdfs.push(...(await expandZip(a, deps.tmpDir ?? tmpdir())));
else pdfs.push(a);
}
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 && certificates === 0 && (msg.bodyHtml || msg.bodyText)) {
const html = Boolean(msg.bodyHtml);
const body: MailAttachment = {
filename: html ? "letter.html" : "letter.txt",
mime: html ? "text/html" : "text/plain",
getBytes: async () => Buffer.from(msg.bodyHtml ?? msg.bodyText ?? "", "utf8"),
};
const r = await processAttachment(deps, msg, body, 9999);
if (r === "certificate") {
certificates++;
out.certificates = (out.certificates ?? 0) + 1;
} else if (r !== "none") {
invoices++;
if (r === "created") {
created++;
out.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: "не инвойс" });
}
} catch (e) {
out.errors++;
log.error({ err: e, messageId: msg.id }, "ошибка обработки письма с инвойсом");
await markMail(pool, msg.id, "error", { message: (e as Error).message });
}
}
return out;
}