diff --git a/packages/accounting_automation/src/drive.ts b/packages/accounting_automation/src/drive.ts index 3429f31..9d3dc8b 100644 --- a/packages/accounting_automation/src/drive.ts +++ b/packages/accounting_automation/src/drive.ts @@ -106,6 +106,20 @@ export class DriveClient implements DriveStore { return (await res.json()) as { name: string; mimeType: string }; } + /** Переносит файл в другую папку (и при необходимости переименовывает). */ + async move(fileId: string, folderId: string, newName?: string): Promise { + const id = encodeURIComponent(fileId); + const cur = (await (await this.call(`${API}/files/${id}?fields=parents&supportsAllDrives=true`)).json()) as { parents?: string[] }; + const params = new URLSearchParams({ addParents: folderId, supportsAllDrives: "true", fields: "id" }); + const remove = (cur.parents ?? []).filter((p) => p !== folderId); + if (remove.length) params.set("removeParents", remove.join(",")); + await this.call(`${API}/files/${id}?${params}`, { + method: "PATCH", + headers: { "content-type": "application/json" }, + body: JSON.stringify(newName ? { name: newName } : {}), + }); + } + async download(fileId: string): Promise { const res = await this.call(`${API}/files/${encodeURIComponent(fileId)}?alt=media&supportsAllDrives=true`); return Buffer.from(await res.arrayBuffer()); diff --git a/packages/accounting_automation/src/invoice-filing.test.ts b/packages/accounting_automation/src/invoice-filing.test.ts new file mode 100644 index 0000000..79f5800 --- /dev/null +++ b/packages/accounting_automation/src/invoice-filing.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from "vitest"; +import { invoiceFileName, invoiceFolderPath, methodFolder, monthLabel } from "./invoice-filing.js"; + +describe("раскладка инвойсов на Drive (как «07. Invoices»)", () => { + it("месяц и имя файла", () => { + expect(monthLabel(new Date("2026-11-30T00:00:00Z"))).toBe("November 2026"); + expect(invoiceFileName(1500, "ACME Plumbing LLC", "inv.PDF")).toBe("$1,500.00 ACME Plumbing LLC.pdf"); + expect(invoiceFileName(null, "A/B", "x.pdf")).toBe("A B.pdf"); + }); + it("до оплаты - «Без оплаты», после - по счёту оплаты без номера", () => { + const d = new Date("2026-03-05T00:00:00Z"); + expect(invoiceFolderPath(null, d)).toEqual(["Инвойсы", "Без оплаты", "March 2026"]); + expect(invoiceFolderPath("Capital One 2381", d)).toEqual(["Инвойсы", "Capital One", "March 2026"]); + expect(methodFolder("Bank of America (4455)")).toBe("Bank of America"); + expect(methodFolder("Amex")).toBe("Amex"); + }); +}); diff --git a/packages/accounting_automation/src/invoice-filing.ts b/packages/accounting_automation/src/invoice-filing.ts new file mode 100644 index 0000000..afd49f5 --- /dev/null +++ b/packages/accounting_automation/src/invoice-filing.ts @@ -0,0 +1,76 @@ +import { extname } from "node:path"; +import type { Logger, Pool } from "khb_common"; + +/** + * Раскладка файлов инвойсов на Drive повторяет «7. FINANCE / 07. Invoices» Анастасии (решение Юрия 2026-11-30), но внутри нашей папки: + * Инвойсы / <способ оплаты: Amex, Bank of America, Capital One...> / <Месяц ГГГГ> / «$<сумма> <Вендор>.pdf». + * Пока инвойс не оплачен, способ оплаты неизвестен: папка «Без оплаты». Когда оплата найдена в QuickBooks (acc_invoices.qbo_txn_id), + * файл переносится в папку счёта, которым заплачено (название счёта из qbo_purchase без хвоста с номером). + */ +export const UNPAID_FOLDER = "Без оплаты"; +const LOCK_KEY = 7_340_004; +const BATCH = 30; + +export const safeName = (s: string): string => s.replace(/[\\/:*?"<>|\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, 100) || "_"; + +const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; +export const monthLabel = (d: Date): string => `${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}`; + +/** Название способа оплаты для папки: имя счёта QuickBooks без номера в конце («Capital One 2381» -> «Capital One»). */ +export const methodFolder = (accountName: string | null): string => { + const n = (accountName ?? "").replace(/[\s(#-]*\d{3,}\)?\s*$/, "").trim(); + return n ? safeName(n) : UNPAID_FOLDER; +}; + +export const invoiceFolderPath = (accountName: string | null, date: Date): string[] => ["Инвойсы", accountName ? methodFolder(accountName) : UNPAID_FOLDER, monthLabel(date)]; + +/** «$1,500.00 ACME Plumbing LLC.pdf»: как называет файлы Анастасия («$<сумма> <Вендор>.pdf»). */ +export const invoiceFileName = (amount: number | string | null | undefined, vendor: string | null | undefined, original: string): string => { + const ext = extname(original).toLowerCase() || ".pdf"; + const a = amount == null || amount === "" ? "" : `$${Number(amount).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })} `; + return safeName(`${a}${vendor ?? "Без вендора"}`) + ext; +}; + +export interface FilingDrive { + ensureFolder(pathParts: string[]): Promise; + meta(fileId: string): Promise<{ name: string; mimeType: string }>; + move(fileId: string, folderId: string, newName?: string): Promise; +} + +/** Переносит файлы оплаченных инвойсов из «Без оплаты» в папку способа оплаты. */ +export async function runInvoiceFiling(deps: { pool: Pool; drive: FilingDrive; log: Logger }): Promise<{ moved: number; failed: number }> { + const { pool, drive, log } = deps; + const out = { moved: 0, failed: 0 }; + const c = await pool.connect(); + try { + if (!(await c.query("select pg_try_advisory_lock($1) as ok", [LOCK_KEY])).rows[0].ok) return out; + try { + const { rows } = await pool.query<{ id: string; drive_file_id: string; vendor_name: string; amount: string; paid_on: string; account_name: string }>( + `select i.id, i.drive_file_id, i.vendor_name, i.amount::text, i.paid_on::text, p.account_name + from acc_invoices i join qbo_purchase p on p.id = i.qbo_txn_id + where i.paid_on is not null and p.account_name is not null + and (i.drive_folder is null or i.drive_folder like 'Инвойсы/${UNPAID_FOLDER}/%') + order by i.paid_on limit ${BATCH}`, + ); + for (const r of rows) { + try { + const path = invoiceFolderPath(r.account_name, new Date(`${r.paid_on}T00:00:00Z`)); + if (methodFolder(r.account_name) === UNPAID_FOLDER) continue; + const folder = await drive.ensureFolder(path); + const meta = await drive.meta(r.drive_file_id); + await drive.move(r.drive_file_id, folder, invoiceFileName(r.amount, r.vendor_name, meta.name)); + await pool.query("update acc_invoices set drive_folder = $2 where id = $1", [r.id, path.join("/")]); + out.moved++; + } catch (e) { + out.failed++; + log.error({ invoice: r.id, err: String(e) }, "перенос файла инвойса на Drive не удался"); + } + } + return out; + } finally { + await c.query("select pg_advisory_unlock($1)", [LOCK_KEY]); + } + } finally { + c.release(); + } +} diff --git a/packages/accounting_automation/src/invoices-mail.int.test.ts b/packages/accounting_automation/src/invoices-mail.int.test.ts index f0b60be..4d95d3b 100644 --- a/packages/accounting_automation/src/invoices-mail.int.test.ts +++ b/packages/accounting_automation/src/invoices-mail.int.test.ts @@ -84,7 +84,8 @@ d("загрузка инвойсов из почты (временная БД, expect(row).toMatchObject({ source_message_id: "m1", drive_file_id: "drv-1", vendor_qbo_id: "V1", project_customer_id: "C1", invoice_number: "INV-1", problem_highlight: null }); expect(row.contract_id).toBe("00000000-0000-0000-0000-0000000000c1"); expect(Number(row.amount)).toBe(1500); - expect(uploads[0].folder).toEqual(["Инвойсы", "ACME Plumbing LLC", "2026-03"]); + expect(uploads[0].folder).toEqual(["Инвойсы", "Без оплаты", "March 2026"]); + expect(uploads[0].name).toBe("$1,500.00 ACME Plumbing LLC.pdf"); expect((await db.pool.query("select 1 from acc_invoices_review_original where id = $1", [row.id])).rowCount).toBe(1); expect((await db.pool.query("select kind, ref_id from acc_manual_review")).rows).toEqual([{ kind: "invoice", ref_id: row.id }]); expect((await db.pool.query("select result from acc_mail_processed")).rows).toEqual([{ result: "invoice" }]); diff --git a/packages/accounting_automation/src/invoices-mail.ts b/packages/accounting_automation/src/invoices-mail.ts index e5fa5df..af33e8a 100644 --- a/packages/accounting_automation/src/invoices-mail.ts +++ b/packages/accounting_automation/src/invoices-mail.ts @@ -8,6 +8,7 @@ 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"; @@ -348,8 +349,10 @@ async function processAttachment(deps: InvoiceIngestDeps, msg: MailMessage, att: 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/octet-stream", bytes, folder); + // раскладка как в папке «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, diff --git a/packages/accounting_automation/src/main.ts b/packages/accounting_automation/src/main.ts index 2179fc3..6389efd 100644 --- a/packages/accounting_automation/src/main.ts +++ b/packages/accounting_automation/src/main.ts @@ -18,6 +18,7 @@ import { runSpamRescue } from "./spam-rescue.js"; import { runCategorizePost } from "./categorize-post.js"; import { makeQboClient } from "./qbo-client.js"; import { runQboAttach } from "./qbo-attach.js"; +import { runInvoiceFiling } from "./invoice-filing.js"; import { runHistoryWeekly } from "./history-report.js"; import { makeClaudeStatementReader, runMonthlyReconcile } from "./reconcile.js"; import { buildApi } from "./http-api.js"; @@ -164,7 +165,10 @@ const app = buildApi({ "categorize-post": async () => runCategorizePost({ pool, claude, log, notify }), "qbo-attach": async () => { if (!qbo || !drive) throw new Error("не настроены qbo_auth (токен) или Drive"); - return runQboAttach({ pool, qbo, drive, log }); + const attached = await runQboAttach({ pool, qbo, drive, log }); + // оплаченные инвойсы: файл из «Без оплаты» в папку способа оплаты (раскладка как в «07. Invoices») + const filed = await runInvoiceFiling({ pool, drive, log }); + return { ...attached, filed }; }, "spam-rescue": async () => { if (!auth || !s.google) throw new Error("не настроены google (ключ сервисного аккаунта)"); diff --git a/packages/khb_common/migrations/079_old_invoices.sql b/packages/khb_common/migrations/079_old_invoices.sql index 1f60d1b..d87bdd0 100644 --- a/packages/khb_common/migrations/079_old_invoices.sql +++ b/packages/khb_common/migrations/079_old_invoices.sql @@ -29,3 +29,6 @@ create table if not exists old_invoices ( create index if not exists old_invoices_vendor_idx on old_invoices (vendor_qbo_id, amount); create index if not exists old_invoices_date_idx on old_invoices (invoice_date); alter table old_invoices enable row level security; + +-- Папка файла инвойса на Drive (Инвойсы/<способ оплаты>/<Месяц ГГГГ>); пусто - файл ещё в «Без оплаты» или в старой раскладке +alter table acc_invoices add column if not exists drive_folder text;