Files
khb_microservices/packages/qbo_auth/src/sync.ts
2026-11-23 10:16:11 +03:00

190 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { SPECS, type EntitySpec, type Row } from "./mirror.js";
import { QboApi } from "./api.js";
import { ReauthNeeded } from "./service.js";
import type { FetchFn } from "./oauth.js";
export interface Q {
query(sql: string, params?: unknown[]): Promise<{ rows: any[] }>;
}
export interface SyncDeps {
/** Выполнить fn в транзакции БД. */
tx<T>(fn: (q: Q) => Promise<T>): Promise<T>;
query: Q["query"];
/** Действующий access token (qbo_auth.getAccessToken). */
getToken(opts?: { force?: boolean }): Promise<{ accessToken: string; realmId: string; apiBase: string }>;
fetchFn: (url: string, init: { method: string; headers: Record<string, string>; body?: string }) => ReturnType<FetchFn>;
environment: string;
sleep?: (ms: number) => Promise<void>;
log?: (msg: string, extra?: Record<string, unknown>) => void;
}
const PAGE = 1000;
const CHUNK = 100;
/** QuickBooks по умолчанию отдаёт только активные счета/вендоров/клиентов. */
const WITH_INACTIVE = new Set(["Account", "Vendor", "Customer"]);
/** Полная перезагрузка не реже раз в столько дней (страховка от пропусков CDC). */
const FULL_EVERY_DAYS = 7;
/** CDC хранит изменения не более 30 дней; берём запас. */
const CDC_MAX_DAYS = 25;
/** Нахлёст окна CDC, чтобы не потерять изменения на границе запусков. */
const CDC_OVERLAP_MS = 5 * 60 * 1000;
/** CDC отдаёт не более 1000 объектов на сущность: при достижении лимита - полная загрузка. */
const CDC_LIMIT = 1000;
export interface SyncResult {
runId: number;
realmId: string;
status: "ok" | "error";
counts: Record<string, number>;
error?: string;
durationMs: number;
}
export class QboSync {
private running = false;
constructor(private readonly d: SyncDeps) {
this.api = new QboApi(d);
}
get isRunning(): boolean {
return this.running;
}
private readonly api: QboApi;
/** Вызов API QuickBooks через общий клиент (повторы, разбор Fault, intuit_tid). */
private get(path: string): Promise<any> {
return this.api.get(path);
}
private async fetchAll(entity: string): Promise<any[]> {
const where = WITH_INACTIVE.has(entity) ? " where Active in (true, false)" : "";
const all: any[] = [];
for (let start = 1; ; start += PAGE) {
const sql = `select * from ${entity}${where} startposition ${start} maxresults ${PAGE}`;
const j = await this.get("query?query=" + encodeURIComponent(sql));
const rows: any[] = j?.QueryResponse?.[entity] ?? [];
all.push(...rows);
if (rows.length < PAGE) return all;
}
}
private async insertRows(q: Q, table: string, columns: string[], rows: Row[], extra: Record<string, unknown>, conflict: string): Promise<void> {
const keys = Object.keys(extra);
const cols = [...keys, ...columns];
const updates = columns.filter((c) => !conflict.split(",").map((s) => s.trim()).includes(c));
for (let i = 0; i < rows.length; i += CHUNK) {
const chunk = rows.slice(i, i + CHUNK);
const params: unknown[] = [];
const values = chunk.map((row) => {
const ph = cols.map((c) => {
params.push(c in extra ? extra[c] : row[c] ?? null);
return `$${params.length}`;
});
return `(${ph.join(", ")})`;
});
const hasSynced = table !== "qbo_purchase_line" && table !== "qbo_bill_line";
const set = [...updates.map((c) => `${c} = excluded.${c}`), ...(hasSynced ? ["synced_at = now()"] : [])].join(", ");
const action = set ? `do update set ${set}` : "do nothing";
await q.query(`insert into ${table} (${cols.join(", ")}) values ${values.join(", ")} on conflict (${conflict}) ${action}`, params);
}
}
/** Запись объектов в зеркало. incremental (CDC): только изменённые, удалённые убираются по списку id; иначе полная замена. */
private async store(spec: EntitySpec, realmId: string, objects: any[], incremental?: { deleted: string[] }): Promise<number> {
const rows = objects.map((o) => spec.map(o));
const ids = rows.map((r) => r.id as string);
await this.d.tx(async (q) => {
await this.insertRows(q, spec.table, spec.columns, rows, { realm_id: realmId }, "realm_id, id");
if (incremental) {
if (incremental.deleted.length) {
await q.query(`delete from ${spec.table} where realm_id = $1 and id = any($2::text[])`, [realmId, incremental.deleted]);
if (spec.lines) await q.query(`delete from ${spec.lines.table} where realm_id = $1 and ${spec.lines.parentColumn} = any($2::text[])`, [realmId, incremental.deleted]);
}
} else {
// исчезнувшие в QuickBooks объекты убираем из зеркала
await q.query(`delete from ${spec.table} where realm_id = $1 and not (id = any($2::text[]))`, [realmId, ids]);
}
if (spec.lines) {
const l = spec.lines;
await q.query(`delete from ${l.table} where realm_id = $1 and ${l.parentColumn} = any($2::text[])`, [realmId, ids]);
const lineRows = objects.flatMap((o, i) => l.map(o, ids[i]!));
await this.insertRows(q, l.table, [l.parentColumn, ...l.columns], lineRows, { realm_id: realmId }, `realm_id, ${l.parentColumn}, line_no`);
if (!incremental) await q.query(`delete from ${l.table} where realm_id = $1 and not (${l.parentColumn} = any($2::text[]))`, [realmId, ids]);
}
});
return rows.length;
}
/** Change Data Capture: объекты, изменённые после since. null - лимит CDC достигнут, нужна полная загрузка. */
private async fetchChanges(since: Date): Promise<Map<string, { changed: any[]; deleted: string[] }> | null> {
const entities = SPECS.map((s) => s.entity);
const j = await this.get(`cdc?entities=${entities.join(",")}&changedSince=${encodeURIComponent(since.toISOString())}`);
const out = new Map<string, { changed: any[]; deleted: string[] }>(entities.map((e) => [e, { changed: [], deleted: [] }]));
for (const qr of j?.CDCResponse?.[0]?.QueryResponse ?? []) {
for (const e of entities) {
const arr: any[] = qr?.[e] ?? [];
if (arr.length >= CDC_LIMIT) return null;
for (const o of arr) (o?.status === "Deleted" ? out.get(e)!.deleted.push(String(o.Id)) : out.get(e)!.changed.push(o));
}
}
return out;
}
/** Полная загрузка или инкремент? Инкремент: есть успешный запуск, полная загрузка была не позже FULL_EVERY_DAYS, окно CDC в пределах лимита. */
private async chooseMode(realmId: string, forceFull: boolean): Promise<{ since: Date } | null> {
if (forceFull) return null;
const last = (await this.d.query("select max(started_at) as t from qbo_sync_run where realm_id = $1 and status = 'ok'", [realmId])).rows[0]?.t;
const full = (await this.d.query("select max(started_at) as t from qbo_sync_run where realm_id = $1 and status = 'ok' and counts ? '_full'", [realmId])).rows[0]?.t;
if (!last || !full) return null;
const day = 24 * 3600 * 1000;
if (Date.now() - new Date(full).getTime() > FULL_EVERY_DAYS * day) return null;
if (Date.now() - new Date(last).getTime() > CDC_MAX_DAYS * day) return null;
return { since: new Date(new Date(last).getTime() - CDC_OVERLAP_MS) };
}
/** Загрузка зеркала: по умолчанию инкремент через CDC (изменения с прошлого запуска), полная перезагрузка при первом запуске, раз в неделю, при full=true и при переполнении CDC. Одновременно выполняется только одна. */
async run(opts: { full?: boolean } = {}): Promise<SyncResult> {
if (this.running) throw new Error("загрузка зеркала QuickBooks уже выполняется");
this.running = true;
const started = Date.now();
const counts: Record<string, number> = {};
let runId = 0;
let realmId = "";
try {
const t = await this.d.getToken();
realmId = t.realmId;
const ins = await this.d.query("insert into qbo_sync_run (realm_id, environment) values ($1, $2) returning id", [realmId, this.d.environment]);
runId = Number(ins.rows[0].id);
let changes: Map<string, { changed: any[]; deleted: string[] }> | null = null;
const mode = await this.chooseMode(realmId, opts.full === true);
if (mode) changes = await this.fetchChanges(mode.since);
if (changes) {
counts._cdc = 1;
for (const spec of SPECS) {
const c = changes.get(spec.entity)!;
counts[spec.entity] = await this.store(spec, realmId, c.changed, { deleted: c.deleted });
if (c.deleted.length) counts[spec.entity + "_deleted"] = c.deleted.length;
this.d.log?.("qbo sync cdc", { entity: spec.entity, changed: c.changed.length, deleted: c.deleted.length });
}
} else {
counts._full = 1;
for (const spec of SPECS) {
const objects = await this.fetchAll(spec.entity);
counts[spec.entity] = await this.store(spec, realmId, objects);
this.d.log?.("qbo sync", { entity: spec.entity, count: counts[spec.entity] });
}
}
await this.d.query("update qbo_sync_run set status = 'ok', finished_at = now(), counts = $2 where id = $1", [runId, JSON.stringify(counts)]);
return { runId, realmId, status: "ok", counts, durationMs: Date.now() - started };
} catch (e) {
const error = String((e as Error).message ?? e).slice(0, 500);
if (runId) await this.d.query("update qbo_sync_run set status = 'error', finished_at = now(), counts = $2, error = $3 where id = $1", [runId, JSON.stringify(counts), error]).catch(() => undefined);
if (e instanceof ReauthNeeded) throw e; // вызывающий (HTTP) отвечает 409 reauth_needed
return { runId, realmId, status: "error", counts, error, durationMs: Date.now() - started };
} finally {
this.running = false;
}
}
}