From 4ff79b2735e56e0024231b5bb6012a834c628fc7 Mon Sep 17 00:00:00 2001 From: Yuri Yaryshev Date: Mon, 30 Nov 2026 06:54:05 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9D=D0=BE=D1=87=D0=BD=D0=BE=D0=B5=20=D0=B7?= =?UTF-8?q?=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5=20spam-rescue:=20=D0=B2?= =?UTF-8?q?=D0=BE=D0=B7=D0=B2=D1=80=D0=B0=D1=82=20=D0=B8=D0=BD=D0=B2=D0=BE?= =?UTF-8?q?=D0=B9=D1=81=D0=BE=D0=B2=20=D0=B8=D0=B7=20=D0=A1=D0=BF=D0=B0?= =?UTF-8?q?=D0=BC=D0=B0=20(=D1=81=D0=BB=D0=BE=D0=B2=D0=B0=20=D0=BF=D1=80?= =?UTF-8?q?=D0=BE=D0=B5=D0=BA=D1=82=D0=BE=D0=B2/=D0=BA=D0=BB=D0=B8=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=D0=BE=D0=B2/=D0=B2=D0=B5=D0=BD=D0=B4=D0=BE=D1=80?= =?UTF-8?q?=D0=BE=D0=B2,=20=D0=B1=D0=B5=D0=BB=D1=8B=D0=B9=20=D1=81=D0=BF?= =?UTF-8?q?=D0=B8=D1=81=D0=BE=D0=BA,=20=D1=84=D0=B8=D0=BB=D1=8C=D1=82?= =?UTF-8?q?=D1=80=D1=8B=20Gmail),=20=D0=BC=D0=B8=D0=B3=D1=80=D0=B0=D1=86?= =?UTF-8?q?=D0=B8=D1=8F=20075?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- .../accounting_automation/src/http-api.ts | 4 +- packages/accounting_automation/src/main.ts | 5 + .../accounting_automation/src/settings.ts | 2 + .../src/spam-rescue.test.ts | 29 +++ .../accounting_automation/src/spam-rescue.ts | 229 ++++++++++++++++++ .../migrations/075_acc_mail_whitelist.sql | 21 ++ 6 files changed, 289 insertions(+), 1 deletion(-) create mode 100644 packages/accounting_automation/src/spam-rescue.test.ts create mode 100644 packages/accounting_automation/src/spam-rescue.ts create mode 100644 packages/khb_common/migrations/075_acc_mail_whitelist.sql diff --git a/packages/accounting_automation/src/http-api.ts b/packages/accounting_automation/src/http-api.ts index 7df42d5..38e6404 100644 --- a/packages/accounting_automation/src/http-api.ts +++ b/packages/accounting_automation/src/http-api.ts @@ -31,8 +31,10 @@ export interface JobHandlers { "history-weekly"?: () => Promise; /** Еженедельное напоминание о незакрытых fraud по картам. */ "fraud-weekly"?: () => Promise; + /** Ночной возврат инвойсов из Спама (письма на invoice@ со словами проектов, клиентов, вендоров; белый список). */ + "spam-rescue"?: () => Promise; } -export const JOB_NAMES = ["invoices-mail", "finalize", "categorize", "summary", "fraud-flags", "invoice-check", "invoice-paid", "invoice-reconcile", "receipts-slack", "receipt-search", "receipt-weekly-report", "certificates", "reconcile-monthly", "history-weekly", "fraud-weekly"] as const; +export const JOB_NAMES = ["invoices-mail", "finalize", "categorize", "summary", "fraud-flags", "invoice-check", "invoice-paid", "invoice-reconcile", "receipts-slack", "receipt-search", "receipt-weekly-report", "certificates", "reconcile-monthly", "history-weekly", "fraud-weekly", "spam-rescue"] as const; export interface ApiDeps { pool: Pool; diff --git a/packages/accounting_automation/src/main.ts b/packages/accounting_automation/src/main.ts index 963139a..dde74a2 100644 --- a/packages/accounting_automation/src/main.ts +++ b/packages/accounting_automation/src/main.ts @@ -14,6 +14,7 @@ import { runInvoicePaid } from "./invoice-paid.js"; import { runInvoiceReconcile } from "./invoice-reconcile.js"; import { GmailClient } from "./gmail.js"; import { GoogleAuth } from "./google.js"; +import { runSpamRescue } from "./spam-rescue.js"; import { runHistoryWeekly } from "./history-report.js"; import { makeClaudeStatementReader, runMonthlyReconcile } from "./reconcile.js"; import { buildApi } from "./http-api.js"; @@ -153,6 +154,10 @@ const app = buildApi({ }, "history-weekly": () => runHistoryWeekly({ pool, ...reportSlack() }), "fraud-weekly": () => runFraudWeekly({ pool, ...reportSlack() }), + "spam-rescue": async () => { + if (!auth || !s.google) throw new Error("не настроены google (ключ сервисного аккаунта)"); + return runSpamRescue({ pool, auth, log, mailboxes: s.google.spamRescue.mailboxes, sourceMailbox: s.google.gmailUser, dryRun: s.google.spamRescue.dryRun }); + }, summary: async () => { if (!slack || !s.slack) throw new Error("не настроен slack (botToken, accountingChannelId)"); const options = { nonWorkdays: await nonWorkdays(), mathesarUrl: s.mathesarUrl, bankFeedUrl: s.receipts.qboBankingUrl }; diff --git a/packages/accounting_automation/src/settings.ts b/packages/accounting_automation/src/settings.ts index 680b540..a2da95a 100644 --- a/packages/accounting_automation/src/settings.ts +++ b/packages/accounting_automation/src/settings.ts @@ -32,6 +32,8 @@ export const accountingSchema = z.object({ /** Поиск писем в ящике: только письма, пришедшие на группу invoice@ (или алиас invoices@), с PDF. */ /** Искать письма и в «Спаме» (Gmail при этом захватывает и корзину). */ gmailIncludeSpam: z.boolean().default(false), + /** Ящики, где ночное задание spam-rescue возвращает инвойсы из Спама; dryRun - только журнал (по умолчанию). */ + spamRescue: z.object({ mailboxes: z.array(z.string()).default(["agents@khbuild.pro", "yuri@khbuild.pro", "nastia@khbuild.pro", "arthur@khbuild.pro"]), dryRun: z.boolean().default(true) }).default({}), gmailQuery: z.string().default("(to:invoice@khbuild.pro OR cc:invoice@khbuild.pro OR to:invoices@khbuild.pro OR cc:invoices@khbuild.pro OR deliveredto:invoice@khbuild.pro OR deliveredto:invoices@khbuild.pro)"), /** Корневая папка Google Drive для инвойсов, чеков и т.д. (подпапки создаются сервисом). */ rootFolderId: z.string().optional(), diff --git a/packages/accounting_automation/src/spam-rescue.test.ts b/packages/accounting_automation/src/spam-rescue.test.ts new file mode 100644 index 0000000..5c32ac3 --- /dev/null +++ b/packages/accounting_automation/src/spam-rescue.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; +import { decide, normalizeTerm, projectNumberOf, senderEmail, type RescueRules } from "./spam-rescue.js"; + +const rules: RescueRules = { whitelist: new Set(["billing@ok.com"]), terms: ["dumpster dudez", "united rentals"], projectNumbers: ["734", "256"] }; +const mail = (o: Partial<{ from: string; subject: string; snippet: string; recipients: string }>) => ({ id: "1", from: "x ", subject: "", snippet: "", recipients: "invoice@khbuild.pro", ...o }); + +describe("spam-rescue decide", () => { + it("слово вендора + invoice@ -> вернуть", () => { + expect(decide(mail({ subject: "You have a new invoice #2814", from: "'Dumpster Dudez of Greater Tampa' via Invoice " }), rules).rescue).toBe(true); + }); + it("номер проекта", () => { + expect(decide(mail({ subject: "Invoice for 734 Placido" }), rules).rescue).toBe(true); + expect(decide(mail({ subject: "Order 17345" }), rules).rescue).toBe(false); + }); + it("не на invoice@ - не трогаем, если нет белого списка", () => { + expect(decide(mail({ subject: "734", recipients: "nastia@khbuild.pro" }), rules).rescue).toBe(false); + expect(decide(mail({ from: "a ", recipients: "nastia@khbuild.pro" }), rules).rescue).toBe(true); + }); + it("без слов - остаётся в спаме", () => { + expect(decide(mail({ subject: "Win a prize" }), rules).rescue).toBe(false); + }); + it("помощники", () => { + expect(senderEmail('"A" ')).toBe("a@b.com"); + expect(normalizeTerm("Dumpster Dudez LLC")).toBe("dumpster dudez"); + expect(normalizeTerm("AB Inc")).toBeNull(); + expect(projectNumberOf("734 Placido Way NE")).toBe("734"); + expect(projectNumberOf("44.01")).toBeNull(); + }); +}); diff --git a/packages/accounting_automation/src/spam-rescue.ts b/packages/accounting_automation/src/spam-rescue.ts new file mode 100644 index 0000000..b684478 --- /dev/null +++ b/packages/accounting_automation/src/spam-rescue.ts @@ -0,0 +1,229 @@ +import type { Logger, Pool } from "khb_common"; +import type { FetchFn, GoogleAuth } from "./google.js"; + +/** + * Ночное задание `spam-rescue` (идея Юрия, 2026-11-30): письма на invoice@, попавшие в Спам, возвращаются во «Входящие», + * если в них есть слово из списка (проект, клиент, вендор) или отправитель в белом списке. Белый список растёт из одобренных + * Анастасией инвойсов; для таких адресов создаётся фильтр Gmail «не отправлять в Спам». dryRun - только журнал, письма не трогаем. + */ + +export const GMAIL_MODIFY_SCOPE = "https://www.googleapis.com/auth/gmail.modify"; +export const GMAIL_FILTERS_SCOPE = "https://www.googleapis.com/auth/gmail.settings.basic"; +const API = "https://gmail.googleapis.com/gmail/v1/users/me"; + +export interface SpamMail { + id: string; + from: string; + subject: string; + snippet: string; + /** To + Cc + Delivered-To одной строкой. */ + recipients: string; +} + +export interface RescueRules { + whitelist: ReadonlySet; + /** Слова в нижнем регистре. */ + terms: readonly string[]; + /** Номера проектов (3+ цифр). */ + projectNumbers: readonly string[]; +} + +const COMPANY_SUFFIX = /\b(llc|l\.l\.c|inc|incorporated|corp|corporation|co|company|ltd|of greater tampa|services|group)\b\.?/g; + +/** Адрес отправителя из заголовка From. */ +export function senderEmail(from: string): string { + const m = from.match(/<([^>]+)>/); + return (m ? m[1]! : from).trim().toLowerCase(); +} + +/** Слово для сравнения: имя без формы собственности, не короче 4 символов. */ +export function normalizeTerm(name: string): string | null { + const t = name.toLowerCase().replace(COMPANY_SUFFIX, " ").replace(/[^a-z0-9а-яё&.\- ]+/g, " ").replace(/\s+/g, " ").trim(); + return t.length >= 4 ? t : null; +} + +/** Номер проекта из имени («734 Placido Way NE» -> 734); только 3+ цифр. */ +export function projectNumberOf(name: string): string | null { + const m = name.match(/\b\d{3,}\b/); + return m ? m[0] : null; +} + +export type RescueDecision = { rescue: boolean; reason: string }; + +/** Правило Юрия: адресат invoice@ + (слово или номер проекта); белый список - всегда возвращаем. */ +export function decide(mail: SpamMail, rules: RescueRules): RescueDecision { + const sender = senderEmail(mail.from); + if (rules.whitelist.has(sender)) return { rescue: true, reason: `белый список: ${sender}` }; + if (!/\binvoices?@khbuild\.pro\b/i.test(mail.recipients)) return { rescue: false, reason: "не на invoice@" }; + const hay = `${mail.from} ${mail.subject} ${mail.snippet}`.toLowerCase(); + for (const n of rules.projectNumbers) if (new RegExp(`(^|[^0-9])${n}([^0-9]|$)`).test(hay)) return { rescue: true, reason: `проект ${n}` }; + for (const t of rules.terms) if (hay.includes(t)) return { rescue: true, reason: `слово «${t}»` }; + return { rescue: false, reason: "нет слов из списка" }; +} + +export async function loadRules(pool: Pool): Promise { + const wl = await pool.query<{ email: string }>("select email from acc_mail_whitelist"); + const terms = new Set(); + const numbers = new Set(); + const add = (s: string | null | undefined): void => { + const n = s ? normalizeTerm(s) : null; + if (n) terms.add(n); + }; + const vendors = await pool.query<{ display_name: string | null; company_name: string | null }>("select display_name, company_name from qbo_vendor where active"); + for (const v of vendors.rows) { + add(v.display_name); + add(v.company_name); + } + const customers = await pool.query<{ display_name: string | null; is_job: boolean }>("select display_name, is_job from qbo_customer where active"); + for (const c of customers.rows) { + if (c.is_job) { + const n = c.display_name ? projectNumberOf(c.display_name) : null; + if (n) numbers.add(n); + } else add(c.display_name); + } + const extra = await pool.query<{ term: string }>("select term from acc_mail_keywords"); + for (const e of extra.rows) { + const t = e.term.toLowerCase().trim(); + if (/^\d{3,}$/.test(t)) numbers.add(t); + else if (t.length >= 3) terms.add(t); + } + return { whitelist: new Set(wl.rows.map((r) => r.email.toLowerCase())), terms: [...terms], projectNumbers: [...numbers] }; +} + +export interface RescueOptions { + pool: Pool; + auth: GoogleAuth; + log: Logger; + mailboxes: string[]; + /** Ящик, где лежат письма, по которым создан acc_invoices (id писем из него). */ + sourceMailbox: string; + dryRun: boolean; + fetchFn?: FetchFn; + /** Сколько дней назад смотреть (Gmail удаляет спам через 30 дней). */ + days?: number; +} +export interface RescueResult { + dryRun: boolean; + mailboxes: Record; + rescued: { mailbox: string; from: string; subject: string; reason: string }[]; + whitelistAdded: string[]; + filtersCreated: number; +} + +type Headers = { name: string; value: string }[]; + +class Mailbox { + constructor(private user: string, private auth: GoogleAuth, private fetchFn: FetchFn) {} + async call(method: string, path: string, body?: unknown): Promise { + const token = await this.auth.getAccessToken([GMAIL_MODIFY_SCOPE, GMAIL_FILTERS_SCOPE], this.user); + const res = await this.fetchFn(`${API}${path}`, { + method, + headers: { authorization: `Bearer ${token}`, ...(body ? { "content-type": "application/json" } : {}) }, + body: body ? JSON.stringify(body) : undefined, + }); + const text = await res.text(); + if (!res.ok) throw new Error(`Gmail ${this.user} ${path.split("?")[0]} ${res.status}: ${text.slice(0, 200)}`); + return text ? (JSON.parse(text) as T) : ({} as T); + } + async listSpam(days: number): Promise { + const out: SpamMail[] = []; + let pageToken = ""; + do { + const q = new URLSearchParams({ includeSpamTrash: "true", labelIds: "SPAM", maxResults: "100", q: `newer_than:${days}d` }); + if (pageToken) q.set("pageToken", pageToken); + const l = await this.call<{ messages?: { id: string }[]; nextPageToken?: string }>("GET", `/messages?${q}`); + for (const m of l.messages ?? []) { + const r = await this.call<{ snippet?: string; payload?: { headers?: Headers } }>( + "GET", + `/messages/${m.id}?format=metadata&metadataHeaders=From&metadataHeaders=Subject&metadataHeaders=To&metadataHeaders=Cc&metadataHeaders=Delivered-To`, + ); + const h = (n: string): string => (r.payload?.headers ?? []).filter((x) => x.name.toLowerCase() === n).map((x) => x.value).join(", "); + out.push({ id: m.id, from: h("from"), subject: h("subject"), snippet: r.snippet ?? "", recipients: `${h("to")}, ${h("cc")}, ${h("delivered-to")}` }); + } + pageToken = l.nextPageToken ?? ""; + } while (pageToken); + return out; + } + async unspam(id: string): Promise { + await this.call("POST", `/messages/${id}/modify`, { addLabelIds: ["INBOX"], removeLabelIds: ["SPAM"] }); + } + async fromOf(id: string): Promise { + const r = await this.call<{ payload?: { headers?: Headers } }>("GET", `/messages/${id}?format=metadata&metadataHeaders=From`); + return (r.payload?.headers ?? []).find((x) => x.name.toLowerCase() === "from")?.value ?? ""; + } + async ensureNeverSpamFilter(email: string): Promise { + const l = await this.call<{ filter?: { criteria?: { from?: string }; action?: { removeLabelIds?: string[] } }[] }>("GET", "/settings/filters"); + if ((l.filter ?? []).some((f) => f.criteria?.from?.toLowerCase() === email && f.action?.removeLabelIds?.includes("SPAM"))) return false; + await this.call("POST", "/settings/filters", { criteria: { from: email }, action: { removeLabelIds: ["SPAM"] } }); + return true; + } +} + +/** Новые адреса белого списка из одобренных инвойсов (acc_invoices - сюда строки попадают после done Анастасии). */ +async function learnWhitelist(o: RescueOptions, src: Mailbox, res: RescueResult): Promise { + const { rows } = await o.pool.query<{ source_message_id: string; decided_by: string | null }>( + `select distinct on (source_message_id) source_message_id, decided_by from acc_invoices + where source_message_id is not null and coalesce(conclusion,'') !~* '(reject|отклон)' order by source_message_id, created_at`, + ); + for (const r of rows) { + let from: string; + try { + from = await src.fromOf(r.source_message_id); + } catch { + continue; // письмо недоступно в этом ящике + } + const email = senderEmail(from); + if (!email.includes("@") || email.endsWith("@khbuild.pro")) continue; + const name = from.match(/^"?([^"<]+?)"?\s* { + const fetchFn = o.fetchFn ?? fetch; + const res: RescueResult = { dryRun: o.dryRun, mailboxes: {}, rescued: [], whitelistAdded: [], filtersCreated: 0 }; + try { + await learnWhitelist(o, new Mailbox(o.sourceMailbox, o.auth, fetchFn), res); + } catch (e) { + o.log.error({ err: String(e) }, "белый список не пополнен"); + } + const rules = await loadRules(o.pool); + const wl = await o.pool.query<{ email: string; filter_mailboxes: string[] }>("select email, filter_mailboxes from acc_mail_whitelist"); + for (const user of o.mailboxes) { + const box = new Mailbox(user, o.auth, fetchFn); + const st = { spam: 0, rescued: 0, errors: 0 }; + res.mailboxes[user] = st; + try { + const spam = await box.listSpam(o.days ?? 30); + st.spam = spam.length; + for (const mail of spam) { + const d = decide(mail, rules); + if (!d.rescue) continue; + try { + if (!o.dryRun) await box.unspam(mail.id); + st.rescued++; + res.rescued.push({ mailbox: user, from: mail.from, subject: mail.subject, reason: d.reason }); + o.log.info({ mailbox: user, from: mail.from, subject: mail.subject, reason: d.reason, dryRun: o.dryRun }, "письмо из спама возвращено"); + } catch (e) { + st.errors++; + o.log.error({ err: String(e), mailbox: user, id: mail.id }, "не удалось вернуть письмо из спама"); + } + } + if (!o.dryRun) { + for (const w of wl.rows) { + if (w.filter_mailboxes.includes(user)) continue; + if (await box.ensureNeverSpamFilter(w.email)) res.filtersCreated++; + await o.pool.query("update acc_mail_whitelist set filter_mailboxes = array_append(filter_mailboxes, $2) where email = $1", [w.email, user]); + } + } + } catch (e) { + st.errors++; + o.log.error({ err: String(e), mailbox: user }, "ящик не обработан (проверьте делегирование gmail.modify и gmail.settings.basic)"); + } + } + return res; +} diff --git a/packages/khb_common/migrations/075_acc_mail_whitelist.sql b/packages/khb_common/migrations/075_acc_mail_whitelist.sql new file mode 100644 index 0000000..6c2b886 --- /dev/null +++ b/packages/khb_common/migrations/075_acc_mail_whitelist.sql @@ -0,0 +1,21 @@ +-- Ночное задание spam-rescue: письма на invoice@, попавшие в Спам, возвращаются во «Входящие»; одобренные Анастасией отправители -> белый список. +-- acc_mail_whitelist: точные адреса (не домены). filter_mailboxes - ящики, где уже создан фильтр Gmail «не отправлять в Спам». +create table if not exists acc_mail_whitelist ( + email text primary key, + display_name text, + source text not null default 'manual', -- 'manual' | 'approved-invoice' + source_message_id text, + approved_by text, + note text, + filter_mailboxes text[] not null default '{}', + created_at timestamptz not null default now() +); +-- acc_mail_keywords: дополнительные слова вручную (основной список слов берётся из qbo_vendor/qbo_customer без дублирования). +create table if not exists acc_mail_keywords ( + term text primary key, + kind text not null default 'other', -- 'project' | 'client' | 'vendor' | 'other' + note text, + created_at timestamptz not null default now() +); +alter table acc_mail_whitelist enable row level security; +alter table acc_mail_keywords enable row level security;