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

@@ -11,6 +11,9 @@ export interface MailMessage {
subject: string;
receivedAt: Date;
attachments: MailAttachment[];
/** Тело письма: HTML и/или текст (инвойс может быть прямо в письме). */
bodyHtml?: string;
bodyText?: string;
}
export interface MailSource {
/** Письма ящика invoices@ с PDF-вложениями, которых нет в acc_mail_processed. */
@@ -21,6 +24,7 @@ export const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.readonly";
const API = "https://gmail.googleapis.com/gmail/v1/users/me";
interface GmailPart {
headers?: { name: string; value: string }[];
filename?: string;
mimeType?: string;
body?: { attachmentId?: string; data?: string; size?: number };
@@ -36,14 +40,21 @@ export interface GmailMessageJson {
export function parseGmailMessage(m: GmailMessageJson, fetchAttachment: (attachmentId: string) => Promise<Buffer>): MailMessage {
const header = (n: string) => m.payload?.headers?.find((h) => h.name.toLowerCase() === n)?.value ?? "";
const attachments: MailAttachment[] = [];
let bodyHtml = "";
let bodyText = "";
const walk = (p: GmailPart | undefined): void => {
if (!p) return;
const name = p.filename ?? "";
const isPdf = (p.mimeType ?? "").toLowerCase() === "application/pdf" || name.toLowerCase().endsWith(".pdf");
if (name && isPdf && p.body) {
const mime = (p.mimeType ?? "application/octet-stream").toLowerCase();
const inlineImage = mime.startsWith("image/") && (p.headers ?? []).some((h) => h.name.toLowerCase() === "content-id");
if (name && p.body && !inlineImage) {
const { attachmentId, data } = p.body;
if (data) attachments.push({ filename: name, mime: "application/pdf", getBytes: async () => Buffer.from(data, "base64url") });
else if (attachmentId) attachments.push({ filename: name, mime: "application/pdf", getBytes: () => fetchAttachment(attachmentId) });
if (data) attachments.push({ filename: name, mime, getBytes: async () => Buffer.from(data, "base64url") });
else if (attachmentId) attachments.push({ filename: name, mime, getBytes: () => fetchAttachment(attachmentId) });
} else if (!name && p.body?.data && (mime === "text/html" || mime === "text/plain")) {
const t = Buffer.from(p.body.data, "base64url").toString("utf8");
if (mime === "text/html") bodyHtml += t;
else bodyText += t;
}
for (const c of p.parts ?? []) walk(c);
};
@@ -54,6 +65,8 @@ export function parseGmailMessage(m: GmailMessageJson, fetchAttachment: (attachm
subject: header("subject"),
receivedAt: new Date(Number(m.internalDate ?? 0)),
attachments,
...(bodyHtml ? { bodyHtml } : {}),
...(bodyText ? { bodyText } : {}),
};
}
@@ -86,7 +99,7 @@ export class GmailClient implements MailSource {
const out: MailMessage[] = [];
let pageToken: string | undefined;
do {
const params: Record<string, string> = { q: this.o.query ?? "has:attachment filename:pdf", maxResults: "50" };
const params: Record<string, string> = { q: this.o.query ?? "", maxResults: "50" };
if (this.o.includeSpam) params.includeSpamTrash = "true";
if (pageToken) params.pageToken = pageToken;
const list = await this.get<{ messages?: { id: string }[]; nextPageToken?: string }>("/messages", params);
@@ -96,7 +109,7 @@ export class GmailClient implements MailSource {
if (done.has(id)) continue;
const m = await this.get<GmailMessageJson>(`/messages/${id}`, { format: "full" });
const msg = parseGmailMessage(m, (aid) => this.fetchAttachment(id, aid));
if (msg.attachments.length) out.push(msg);
out.push(msg);
if (out.length >= limit) return out;
}
pageToken = list.nextPageToken;

View File

@@ -65,16 +65,17 @@ describe("Gmail: разбор ответов", () => {
},
};
it("parseGmailMessage: заголовки, PDF-вложения, дата", async () => {
it("parseGmailMessage: заголовки, вложения любых типов, тело письма, дата", async () => {
const m = parseGmailMessage(msgJson, async (id) => Buffer.from(`bytes-${id}`));
expect(m).toMatchObject({ id: "m1", from: "Bob <bob@vendor.com>", subject: "Invoice 42" });
expect(m.receivedAt.toISOString()).toBe("2026-01-01T00:00:00.000Z");
expect(m.attachments.map((a) => a.filename)).toEqual(["inv.pdf", "inline.PDF"]);
expect(m.attachments.map((a) => a.filename)).toEqual(["inv.pdf", "photo.jpg", "inline.PDF"]);
expect(m.bodyText).toBe("hi");
expect((await m.attachments[0].getBytes()).toString()).toBe("bytes-att1");
expect((await m.attachments[1].getBytes()).toString()).toBe("PDFDATA");
expect((await m.attachments[2].getBytes()).toString()).toBe("PDFDATA");
});
it("GmailClient.listUnprocessed: пропускает обработанные, сторонние письма без PDF и берёт вложения", async () => {
it("GmailClient.listUnprocessed: пропускает обработанные, берёт все остальные письма (в том числе без вложений)", async () => {
const urls: string[] = [];
const fetchFn = (async (url: string, init: RequestInit) => {
urls.push(url);
@@ -92,9 +93,9 @@ describe("Gmail: разбор ответов", () => {
} } as unknown as GoogleAuth;
const c = new GmailClient({ auth, user: "invoices@khbuild.pro", processedIds: async () => new Set(["m0"]), fetchFn });
const list = await c.listUnprocessed(10);
expect(list.map((m) => m.id)).toEqual(["m1"]);
expect(list.map((m) => m.id)).toEqual(["m1", "m2"]);
expect((await list[0].attachments[0].getBytes()).toString()).toBe("PDF1");
expect(decodeURIComponent(urls[0])).toContain("q=has:attachment+filename:pdf".replace(/\+/g, "+"));
expect(decodeURIComponent(urls[0])).not.toContain("has:attachment");
});
});

View File

@@ -49,7 +49,7 @@ d("загрузка инвойсов из почты (временная БД,
};
const claude: ClaudeRunner = async (o) => {
claudeCalls++;
const path = /(\S+invoice\.pdf)/.exec(o.prompt)![1];
const path = /(\S+invoice\.[a-z]+)/.exec(o.prompt)![1];
const text = readFileSync(path, "utf8"); // файл должен существовать во время вызова
const a = answers[text];
return a === undefined ? { ok: false, stdout: "", stderr: "boom", exitCode: 1, timedOut: false } : { ok: true, stdout: a, stderr: "", exitCode: 0, timedOut: false };
@@ -184,4 +184,17 @@ d("загрузка инвойсов из почты (временная БД,
expect((await reviews()).map((x) => x.invoice_number)).toEqual(["A1", "C1"]);
expect(uploads).toHaveLength(2);
});
it("инвойс в теле письма (без вложений) и во вложении docx: письмо читается целиком, тип файла любой", async () => {
answers["<p>Invoice 77, total 500</p>"] = inv({ invoice_number: "BODY-77", amount: 500 });
const bodyOnly: MailMessage = { id: "mb", from: "bob@vendor.com", subject: "Invoice", receivedAt: new Date("2026-03-05T12:00:00Z"), attachments: [], bodyHtml: "<p>Invoice 77, total 500</p>" };
answers.docxtext = inv({ invoice_number: "DOCX-1" });
const withDocx: MailMessage = { id: "md", from: "bob@vendor.com", subject: "Invoice", receivedAt: new Date("2026-03-05T12:00:00Z"), attachments: [{ filename: "счёт.docx", mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", getBytes: async () => Buffer.from("docxtext") }], bodyText: "см. вложение" };
const noInvoice: MailMessage = { id: "mn", from: "x@y.com", subject: "Hello", receivedAt: new Date("2026-03-05T12:00:00Z"), attachments: [], bodyText: "привет" };
answers["привет"] = JSON.stringify({ is_invoice: false });
const r = await run([bodyOnly, withDocx, noInvoice]);
expect(r).toMatchObject({ processed: 3, created: 2, skipped: 1, errors: 0 });
expect((await reviews()).map((x) => x.invoice_number).sort()).toEqual(["BODY-77", "DOCX-1"]);
expect(uploads.map((u) => u.name).sort()).toEqual(["letter.html", "счёт.docx"]);
});
});

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++;

View File

@@ -295,7 +295,7 @@ d("MCP бухгалтерии (временная БД)", () => {
expect(((await post(bearer(TOKEN_A), rpc("ping"))).json()).result).toEqual({ resultType: "complete" });
const l = (await post(bearer(TOKEN_A), rpc("tools/list"))).json();
expect(l.result.tools.map((t: { name: string }) => t.name).slice(0, 8)).toEqual([
"acc_review_list", "acc_review_get", "acc_review_update", "acc_review_done", "acc_review_handoff", "acc_review_return", "acc_review_batch", "acc_review_snooze",
"acc_review_list", "acc_review_get", "acc_review_update", "acc_review_done", "acc_review_handoff", "acc_review_return", "acc_receipt_allow_without", "acc_review_batch",
]);
const tl = l.result.tools as Array<{ name: string; annotations?: { readOnlyHint?: boolean }; _meta?: { ui?: { resourceUri?: string } } }>;
expect(tl.find((t) => t.name === "acc_review_list")?.annotations?.readOnlyHint).toBe(true);

View File

@@ -32,7 +32,7 @@ export const accountingSchema = z.object({
/** Поиск писем в ящике: только письма, пришедшие на группу invoice@ (или алиас invoices@), с PDF. */
/** Искать письма и в «Спаме» (Gmail при этом захватывает и корзину). */
gmailIncludeSpam: z.boolean().default(false),
gmailQuery: z.string().default("has:attachment filename:pdf (to:invoice@khbuild.pro OR cc:invoice@khbuild.pro OR to:invoices@khbuild.pro OR cc:invoices@khbuild.pro)"),
gmailQuery: z.string().default("(to:invoice@khbuild.pro OR cc:invoice@khbuild.pro OR to:invoices@khbuild.pro OR cc:invoices@khbuild.pro)"),
/** Корневая папка Google Drive для инвойсов, чеков и т.д. (подпапки создаются сервисом). */
rootFolderId: z.string().optional(),
})