accounting_automation: этап 1 бухгалтерской автоматизации (инвойсы из почты, категоризация, ручной разбор, MCP), интервальные задания scheduler, миграции 033/034/038
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
108
packages/accounting_automation/src/gmail.ts
Normal file
108
packages/accounting_automation/src/gmail.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import type { FetchFn, GoogleAuth } from "./google.js";
|
||||
|
||||
export interface MailAttachment {
|
||||
filename: string;
|
||||
mime: string;
|
||||
getBytes(): Promise<Buffer>;
|
||||
}
|
||||
export interface MailMessage {
|
||||
id: string;
|
||||
from: string;
|
||||
subject: string;
|
||||
receivedAt: Date;
|
||||
attachments: MailAttachment[];
|
||||
}
|
||||
export interface MailSource {
|
||||
/** Письма ящика invoices@ с PDF-вложениями, которых нет в acc_mail_processed. */
|
||||
listUnprocessed(limit: number): Promise<MailMessage[]>;
|
||||
}
|
||||
|
||||
export const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.readonly";
|
||||
const API = "https://gmail.googleapis.com/gmail/v1/users/me";
|
||||
|
||||
interface GmailPart {
|
||||
filename?: string;
|
||||
mimeType?: string;
|
||||
body?: { attachmentId?: string; data?: string; size?: number };
|
||||
parts?: GmailPart[];
|
||||
}
|
||||
export interface GmailMessageJson {
|
||||
id: string;
|
||||
internalDate?: string;
|
||||
payload?: GmailPart & { headers?: { name: string; value: string }[] };
|
||||
}
|
||||
|
||||
/** Разбор ответа messages.get (format=full) в MailMessage; байты вложений берутся через fetchAttachment. */
|
||||
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[] = [];
|
||||
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 { 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) });
|
||||
}
|
||||
for (const c of p.parts ?? []) walk(c);
|
||||
};
|
||||
walk(m.payload);
|
||||
return {
|
||||
id: m.id,
|
||||
from: header("from"),
|
||||
subject: header("subject"),
|
||||
receivedAt: new Date(Number(m.internalDate ?? 0)),
|
||||
attachments,
|
||||
};
|
||||
}
|
||||
|
||||
/** Gmail REST API: читаем ящик invoices@ от имени пользователя (делегирование домена). */
|
||||
export class GmailClient implements MailSource {
|
||||
constructor(
|
||||
private o: {
|
||||
auth: GoogleAuth;
|
||||
/** Ящик (google.gmailUser). */
|
||||
user: string;
|
||||
/** Какие из id писем уже разобраны (acc_mail_processed, result invoice/skipped). */
|
||||
processedIds: (ids: string[]) => Promise<Set<string>>;
|
||||
fetchFn?: FetchFn;
|
||||
query?: string;
|
||||
},
|
||||
) {}
|
||||
|
||||
private async get<T>(path: string, params: Record<string, string> = {}): Promise<T> {
|
||||
const token = await this.o.auth.getAccessToken([GMAIL_SCOPE], this.o.user);
|
||||
const url = `${API}${path}${Object.keys(params).length ? "?" + new URLSearchParams(params) : ""}`;
|
||||
const res = await (this.o.fetchFn ?? fetch)(url, { headers: { authorization: `Bearer ${token}` } });
|
||||
const text = await res.text();
|
||||
if (!res.ok) throw new Error(`Gmail ${path} ${res.status}: ${text.slice(0, 300)}`);
|
||||
return JSON.parse(text) as T;
|
||||
}
|
||||
|
||||
async listUnprocessed(limit: number): Promise<MailMessage[]> {
|
||||
const out: MailMessage[] = [];
|
||||
let pageToken: string | undefined;
|
||||
do {
|
||||
const params: Record<string, string> = { q: this.o.query ?? "has:attachment filename:pdf", maxResults: "50" };
|
||||
if (pageToken) params.pageToken = pageToken;
|
||||
const list = await this.get<{ messages?: { id: string }[]; nextPageToken?: string }>("/messages", params);
|
||||
const ids = (list.messages ?? []).map((x) => x.id);
|
||||
const done = ids.length ? await this.o.processedIds(ids) : new Set<string>();
|
||||
for (const id of ids) {
|
||||
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);
|
||||
if (out.length >= limit) return out;
|
||||
}
|
||||
pageToken = list.nextPageToken;
|
||||
} while (pageToken);
|
||||
return out;
|
||||
}
|
||||
|
||||
private async fetchAttachment(messageId: string, attachmentId: string): Promise<Buffer> {
|
||||
const a = await this.get<{ data?: string }>(`/messages/${messageId}/attachments/${attachmentId}`);
|
||||
return Buffer.from(a.data ?? "", "base64url");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user