Зеркало QuickBooks qbo_* (миграция 032) и загрузка POST /sync в qbo_auth, задание scheduler qbo_sync (п.85)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
137
packages/qbo_auth/src/sync.ts
Normal file
137
packages/qbo_auth/src/sync.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import { SPECS, type EntitySpec, type Row } from "./mirror.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> }) => 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"]);
|
||||
|
||||
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) {}
|
||||
|
||||
get isRunning(): boolean {
|
||||
return this.running;
|
||||
}
|
||||
|
||||
/** Вызов API QuickBooks: один повтор с принудительным обновлением токена при 401, повторы с паузой при 429/5xx. */
|
||||
private async get(path: string): Promise<any> {
|
||||
const sleep = this.d.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
||||
let force = false;
|
||||
for (let attempt = 0; attempt < 5; attempt++) {
|
||||
const t = await this.d.getToken({ force });
|
||||
const url = `${t.apiBase}/v3/company/${t.realmId}/${path}${path.includes("?") ? "&" : "?"}minorversion=75`;
|
||||
const r = await this.d.fetchFn(url, { method: "GET", headers: { Authorization: "Bearer " + t.accessToken, Accept: "application/json" } });
|
||||
if (r.ok) return r.json();
|
||||
if (r.status === 401 && !force) { force = true; continue; }
|
||||
if (r.status === 429 || r.status >= 500) { await sleep(2000 * (attempt + 1)); continue; }
|
||||
throw new Error(`QuickBooks ${r.status} на ${path.split("?")[0]}`);
|
||||
}
|
||||
throw new Error(`QuickBooks: не удалось выполнить ${path.split("?")[0]} за 5 попыток`);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
private async store(spec: EntitySpec, realmId: string, objects: any[]): 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");
|
||||
// исчезнувшие в 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`);
|
||||
await q.query(`delete from ${l.table} where realm_id = $1 and not (${l.parentColumn} = any($2::text[]))`, [realmId, ids]);
|
||||
}
|
||||
});
|
||||
return rows.length;
|
||||
}
|
||||
|
||||
/** Полная перезагрузка зеркала. Одновременно выполняется только одна. */
|
||||
async run(): 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);
|
||||
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);
|
||||
return { runId, realmId, status: "error", counts, error, durationMs: Date.now() - started };
|
||||
} finally {
|
||||
this.running = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user