Files
khb_microservices/packages/accounting_automation/src/drive.ts
Yuri Yaryshev 4c99033f13 accounting_automation, этап 2: страховые сертификаты, сверка выписок, разбор истории правок, chargeback к контракту, fraud
- Миграции 061 (сертификаты: alert_kind, drive_file_id, request_*, acc_invoices.no_insurance) и 062 (acc_chargeback: kind contract|card_fraud,
  колонки contract, триггеры пересчёта acc_contracts.retained_amount и закрытия по остатку).
- Задания certificates, reconcile-monthly, history-weekly, fraud-weekly (JOB_NAMES, main.ts); расписание на сервере не заведено.
- Письма с сертификатами разбирает invoices-mail (document_type certificate); запрос подрядчику - через интерфейс ContractorMessenger
  (пока ручной: текст в request_log, Юля отправляет из JobTread).
- Ручки /chargeback/find|start|close|add-log|fraud для ассистента менеджера; MCP-инструменты acc_chargeback_*, acc_fraud_*,
  acc_contract_balance, acc_certificate_request_approve; очередь показывает задачи вида chargeback.
- Тесты на временной БД (сертификаты, сверка, история правок, chargeback и fraud, служебное API); описание данных в docs/proposed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 16:58:00 +03:00

113 lines
5.2 KiB
TypeScript

import type { FetchFn, GoogleAuth } from "./google.js";
export interface DriveStore {
/** Путь папок внутри корневой папки; создаёт недостающие, возвращает id последней. */
ensureFolder(pathParts: string[]): Promise<string>;
upload(name: string, mime: string, bytes: Buffer, folderId: string): Promise<{ id: string }>;
/** Текст Google-документа (export text/plain). */
exportDocText(docId: string): Promise<string>;
}
export const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
const API = "https://www.googleapis.com/drive/v3";
const UPLOAD = "https://www.googleapis.com/upload/drive/v3/files";
/** Drive REST API v3, общие диски включены (supportsAllDrives). */
export class DriveClient implements DriveStore {
private folderCache = new Map<string, string>();
constructor(private o: { auth: GoogleAuth; rootFolderId: string; fetchFn?: FetchFn }) {}
private async call(url: string, init: RequestInit = {}): Promise<Response> {
const token = await this.o.auth.getAccessToken([DRIVE_SCOPE]);
const res = await (this.o.fetchFn ?? fetch)(url, { ...init, headers: { ...(init.headers ?? {}), authorization: `Bearer ${token}` } });
if (!res.ok) throw new Error(`Drive ${res.status}: ${(await res.text()).slice(0, 300)}`);
return res;
}
async ensureFolder(pathParts: string[]): Promise<string> {
let parent = this.o.rootFolderId;
for (const raw of pathParts) {
const name = raw.trim() || "_";
const ck = `${parent}/${name}`;
const cached = this.folderCache.get(ck);
if (cached) {
parent = cached;
continue;
}
const esc = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
const q = `name='${esc}' and mimeType='application/vnd.google-apps.folder' and '${parent}' in parents and trashed=false`;
const params = new URLSearchParams({ q, fields: "files(id,name)", supportsAllDrives: "true", includeItemsFromAllDrives: "true", pageSize: "2" });
const found = (await (await this.call(`${API}/files?${params}`)).json()) as { files?: { id: string }[] };
let id = found.files?.[0]?.id;
if (!id) {
const created = (await (
await this.call(`${API}/files?supportsAllDrives=true&fields=id`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ name, mimeType: "application/vnd.google-apps.folder", parents: [parent] }),
})
).json()) as { id: string };
id = created.id;
}
this.folderCache.set(ck, id);
parent = id;
}
return parent;
}
async upload(name: string, mime: string, bytes: Buffer, folderId: string): Promise<{ id: string }> {
const boundary = "khb" + Math.random().toString(36).slice(2);
const meta = JSON.stringify({ name, parents: [folderId] });
const body = Buffer.concat([
Buffer.from(`--${boundary}\r\ncontent-type: application/json; charset=UTF-8\r\n\r\n${meta}\r\n--${boundary}\r\ncontent-type: ${mime}\r\n\r\n`),
bytes,
Buffer.from(`\r\n--${boundary}--`),
]);
const res = await this.call(`${UPLOAD}?uploadType=multipart&supportsAllDrives=true&fields=id`, {
method: "POST",
headers: { "content-type": `multipart/related; boundary=${boundary}` },
body,
});
const j = (await res.json()) as { id: string };
return { id: j.id };
}
/** Файлы PDF в папке (по пути от корня) и во вложенных папках (глубина 1); отсутствующая папка - пустой список. */
async listPdfFiles(pathParts: string[]): Promise<{ id: string; name: string }[]> {
const root = await this.ensureFolder(pathParts);
const out: { id: string; name: string }[] = [];
const listIn = async (folder: string, depth: number): Promise<void> => {
let pageToken: string | undefined;
do {
const params = new URLSearchParams({
q: `'${folder}' in parents and trashed=false`,
fields: "nextPageToken,files(id,name,mimeType)",
supportsAllDrives: "true",
includeItemsFromAllDrives: "true",
pageSize: "200",
...(pageToken ? { pageToken } : {}),
});
const j = (await (await this.call(`${API}/files?${params}`)).json()) as { files?: { id: string; name: string; mimeType: string }[]; nextPageToken?: string };
for (const f of j.files ?? []) {
if (f.mimeType === "application/vnd.google-apps.folder") {
if (depth > 0) await listIn(f.id, depth - 1);
} else if (f.mimeType === "application/pdf" || f.name.toLowerCase().endsWith(".pdf")) out.push({ id: f.id, name: f.name });
}
pageToken = j.nextPageToken;
} while (pageToken);
};
await listIn(root, 1);
return out;
}
async download(fileId: string): Promise<Buffer> {
const res = await this.call(`${API}/files/${encodeURIComponent(fileId)}?alt=media&supportsAllDrives=true`);
return Buffer.from(await res.arrayBuffer());
}
async exportDocText(docId: string): Promise<string> {
const res = await this.call(`${API}/files/${encodeURIComponent(docId)}/export?mimeType=${encodeURIComponent("text/plain")}`);
return await res.text();
}
}