Ночное задание spam-rescue: возврат инвойсов из Спама (слова проектов/клиентов/вендоров, белый список, фильтры Gmail), миграция 075
All checks were successful
ci / test (push) Successful in 49s
ci / deploy (push) Successful in 2m56s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-30 06:54:05 +03:00
parent 9014b5324e
commit 4ff79b2735
6 changed files with 289 additions and 1 deletions

View File

@@ -31,8 +31,10 @@ export interface JobHandlers {
"history-weekly"?: () => Promise<unknown>;
/** Еженедельное напоминание о незакрытых fraud по картам. */
"fraud-weekly"?: () => Promise<unknown>;
/** Ночной возврат инвойсов из Спама (письма на invoice@ со словами проектов, клиентов, вендоров; белый список). */
"spam-rescue"?: () => Promise<unknown>;
}
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;

View File

@@ -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 };

View File

@@ -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(),

View File

@@ -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 <x@y.com>", 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 <i@khbuild.pro>" }), 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 <billing@ok.com>", recipients: "nastia@khbuild.pro" }), rules).rescue).toBe(true);
});
it("без слов - остаётся в спаме", () => {
expect(decide(mail({ subject: "Win a prize" }), rules).rescue).toBe(false);
});
it("помощники", () => {
expect(senderEmail('"A" <A@B.com>')).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();
});
});

View File

@@ -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<string>;
/** Слова в нижнем регистре. */
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<RescueRules> {
const wl = await pool.query<{ email: string }>("select email from acc_mail_whitelist");
const terms = new Set<string>();
const numbers = new Set<string>();
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<string, { spam: number; rescued: number; errors: number }>;
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<T>(method: string, path: string, body?: unknown): Promise<T> {
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<SpamMail[]> {
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<void> {
await this.call("POST", `/messages/${id}/modify`, { addLabelIds: ["INBOX"], removeLabelIds: ["SPAM"] });
}
async fromOf(id: string): Promise<string> {
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<boolean> {
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<void> {
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*</)?.[1] ?? null;
const ins = await o.pool.query(
`insert into acc_mail_whitelist (email, display_name, source, source_message_id, approved_by) values ($1,$2,'approved-invoice',$3,$4) on conflict (email) do nothing`,
[email, name, r.source_message_id, r.decided_by],
);
if (ins.rowCount) res.whitelistAdded.push(email);
}
}
export async function runSpamRescue(o: RescueOptions): Promise<RescueResult> {
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;
}

View File

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