Ночное задание 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

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