accounting_automation: инвойс в письме в любом виде (тело, вложения любых типов, zip); тесты; approved и snapshot документов
All checks were successful
ci / test (push) Successful in 45s
ci / deploy (push) Successful in 2m44s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 18:07:57 +03:00
parent a274c9c163
commit d6d203dea3
254 changed files with 3788 additions and 50 deletions

View File

@@ -1,7 +1,9 @@
import { createHash } from "node:crypto";
import { mkdir, rm, writeFile } from "node:fs/promises";
import { execFile } from "node:child_process";
import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
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 type { DriveStore } from "./drive.js";
@@ -131,7 +133,8 @@ export function invoiceReviewId(messageId: string, index: number, filename: stri
export function buildRecognitionPrompt(pdfPath: string, mail: { from: string; subject: string }): string {
return [
"Ты распознаёшь счета (invoice) подрядчиков строительной компании.",
`Прочитай PDF-файл ${pdfPath} (письмо от ${mail.from}, тема «${mail.subject}») и верни ТОЛЬКО один JSON-объект, без пояснений и без markdown.`,
`Прочитай файл ${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"',
@@ -225,11 +228,51 @@ 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 path = join(dir, "invoice.pdf");
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 });
if (!res.ok) throw new Error(`Claude не отработал (код ${res.exitCode}${res.timedOut ? ", таймаут" : ""}): ${res.stderr.slice(0, 200)}`);
@@ -258,7 +301,7 @@ async function processAttachment(deps: InvoiceIngestDeps, msg: MailMessage, att:
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);
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(),
@@ -280,7 +323,7 @@ async function processAttachment(deps: InvoiceIngestDeps, msg: MailMessage, att:
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);
const file = await deps.drive.upload(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,
@@ -313,7 +356,14 @@ export async function runInvoiceIngest(deps: InvoiceIngestDeps): Promise<Invoice
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"));
// документы письма: вложения любого читаемого вида, содержимое 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;
@@ -330,11 +380,30 @@ export async function runInvoiceIngest(deps: InvoiceIngestDeps): Promise<Invoice
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: pdfs.length ? "не инвойс" : "нет PDF" });
await markMail(pool, msg.id, "skipped", { attachments: pdfs.length, reason: "не инвойс" });
}
} catch (e) {
out.errors++;