Files
khb_microservices/packages/qbo_auth/src/sync.test.ts

199 lines
12 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 { describe, expect, it } from "vitest";
import { SPECS } from "./mirror.js";
import { QboSync, type Q, type SyncDeps } from "./sync.js";
const spec = (e: string) => SPECS.find((s) => s.entity === e)!;
describe("преобразование объектов QuickBooks", () => {
it("Purchase: шапка и строки с счётом и проектом; служебные строки пропускаются", () => {
const o = {
Id: "144", SyncToken: "2", TxnDate: "2026-11-15", PaymentType: "CreditCard", TotalAmt: 34,
AccountRef: { value: "41", name: "Visa" }, EntityRef: { value: "7", name: "Linode", type: "Vendor" }, PrivateNote: "auto:42",
MetaData: { CreateTime: "2026-11-15T10:00:00-05:00", LastUpdatedTime: "2026-11-16T10:00:00-05:00" },
Line: [
{ Id: "1", Amount: 30, Description: "hosting", DetailType: "AccountBasedExpenseLineDetail", AccountBasedExpenseLineDetail: { AccountRef: { value: "55", name: "3.5. Software" }, CustomerRef: { value: "9", name: "Smith:Kitchen" }, BillableStatus: "NotBillable" } },
{ Amount: 4, DetailType: "SubTotalLineDetail" },
{ Id: "2", Amount: 4, DetailType: "AccountBasedExpenseLineDetail", AccountBasedExpenseLineDetail: { AccountRef: { value: "56", name: "Fees" } } },
],
};
const s = spec("Purchase");
expect(s.map(o)).toMatchObject({ id: "144", txn_date: "2026-11-15", payment_type: "CreditCard", account_id: "41", entity_name: "Linode", total_amt: 34, private_note: "auto:42", sync_token: "2" });
const lines = s.lines!.map(o, "144");
expect(lines).toHaveLength(2);
expect(lines[0]).toMatchObject({ purchase_id: "144", line_no: 0, amount: 30, account_id: "55", customer_id: "9", billable_status: "NotBillable" });
expect(lines[1]).toMatchObject({ line_no: 2, account_id: "56", customer_id: null });
});
it("Customer: проект (Job) с родителем; Account: родитель и неактивный", () => {
expect(spec("Customer").map({ Id: "9", DisplayName: "Smith:Kitchen", Job: true, ParentRef: { value: "8" }, Active: true })).toMatchObject({ is_job: true, parent_id: "8" });
expect(spec("Account").map({ Id: "5", Name: "Old", AcctNum: "3.5.", Active: false, ParentRef: { value: "1" } })).toMatchObject({ active: false, acct_num: "3.5.", parent_id: "1" });
});
it("Attachable: ссылки на документы", () => {
const r = spec("Attachable").map({ Id: "3", FileName: "inv.pdf", Size: 1000, AttachableRef: [{ EntityRef: { type: "Purchase", value: "144" } }] });
expect(JSON.parse(r.refs as string)).toEqual([{ type: "Purchase", id: "144" }]);
});
});
/** Заглушки: API QuickBooks с заданными списками и база, запоминающая запросы. */
function setup(data: Record<string, any[]>, opts: { status?: number[] } = {}) {
const sqls: Array<{ sql: string; params?: unknown[] }> = [];
const calls: string[] = [];
const statuses = [...(opts.status ?? [])];
const q: Q = {
query: async (sql, params) => {
sqls.push({ sql, params });
if (sql.startsWith("insert into qbo_sync_run")) return { rows: [{ id: "77" }] };
return { rows: [] };
},
};
let tokenCalls = 0;
const d: SyncDeps = {
tx: (fn) => fn(q),
query: q.query,
getToken: async () => { tokenCalls++; return { accessToken: "at", realmId: "R1", apiBase: "https://api.test" }; },
fetchFn: async (url) => {
calls.push(decodeURIComponent(url));
const st = statuses.shift() ?? 200;
const sql = decodeURIComponent(url);
const ent = /from (\w+)/.exec(sql)![1]!;
const start = Number(/startposition (\d+)/.exec(sql)![1]);
const max = Number(/maxresults (\d+)/.exec(sql)![1]);
return { ok: st < 400, status: st, json: async () => ({ QueryResponse: { [ent]: (data[ent] ?? []).slice(start - 1, start - 1 + max) } }) };
},
environment: "sandbox",
sleep: async () => undefined,
};
return { sync: new QboSync(d), sqls, calls, tokens: () => tokenCalls };
}
describe("загрузка зеркала", () => {
it("грузит все сущности, пишет журнал, чистит исчезнувшие объекты и строки", async () => {
const data = {
Account: [{ Id: "1", Name: "A" }, { Id: "2", Name: "B" }],
Purchase: [{ Id: "144", TxnDate: "2026-11-15", TotalAmt: 5, Line: [{ Amount: 5, AccountBasedExpenseLineDetail: { AccountRef: { value: "1", name: "A" } } }] }],
};
const { sync, sqls, calls } = setup(data);
const r = await sync.run();
expect(r).toMatchObject({ status: "ok", realmId: "R1", runId: 77, counts: { Account: 2, Purchase: 1, Vendor: 0, Customer: 0, Bill: 0, Attachable: 0 } });
expect(calls.find((c) => c.includes("from Account"))).toContain("where Active in (true, false)");
expect(calls.find((c) => c.includes("from Purchase"))).not.toContain("Active");
const text = sqls.map((s) => s.sql);
expect(text.some((s) => s.startsWith("insert into qbo_account") && s.includes("on conflict (realm_id, id) do update"))).toBe(true);
expect(text.some((s) => s.startsWith("delete from qbo_account where realm_id = $1 and not (id = any($2::text[]))"))).toBe(true);
expect(text.some((s) => s.startsWith("insert into qbo_purchase_line"))).toBe(true);
expect(text.some((s) => s.startsWith("delete from qbo_purchase_line where realm_id = $1 and not (purchase_id"))).toBe(true);
expect(text.some((s) => s.includes("update qbo_sync_run set status = 'ok'"))).toBe(true);
});
it("страницы: 1000 объектов -> запрашивает следующую страницу", async () => {
const many = Array.from({ length: 1000 }, (_, i) => ({ Id: String(i), Name: "n" + i }));
const { sync, calls } = setup({ Account: many });
await sync.run();
const pages = calls.filter((c) => c.includes("from Account"));
expect(pages).toHaveLength(2);
expect(pages[0]).toContain("startposition 1 ");
expect(pages[1]).toContain("startposition 1001 ");
});
it("401: один повтор с принудительным обновлением токена; 429: повтор после паузы", async () => {
const { sync, tokens } = setup({}, { status: [401, 429] });
const r = await sync.run();
expect(r.status).toBe("ok");
expect(tokens()).toBeGreaterThanOrEqual(3);
});
it("постоянная ошибка 403: статус error в журнале, исключение не уходит наружу, флаг занятости снимается", async () => {
const { sync, sqls } = setup({}, { status: [403] });
const r = await sync.run();
expect(r.status).toBe("error");
expect(r.error).toContain("403");
expect(sqls.some((s) => s.sql.includes("status = 'error'"))).toBe(true);
expect(sync.isRunning).toBe(false);
});
it("параллельный запуск отклоняется", async () => {
const { sync } = setup({});
const first = sync.run();
await expect(sync.run()).rejects.toThrow(/уже выполняется/);
await first;
});
});
/** Заглушка для режима CDC: история запусков и ответ cdc. */
function setupCdc(opts: { lastAgoMs: number | null; fullAgoMs: number | null; cdc: unknown }) {
const sqls: Array<{ sql: string; params?: unknown[] }> = [];
const calls: string[] = [];
const now = Date.now();
const q: Q = {
query: async (sql, params) => {
sqls.push({ sql, params });
if (sql.startsWith("insert into qbo_sync_run")) return { rows: [{ id: "88" }] };
if (sql.includes("max(started_at)") && sql.includes("'_full'")) return { rows: [{ t: opts.fullAgoMs === null ? null : new Date(now - opts.fullAgoMs).toISOString() }] };
if (sql.includes("max(started_at)")) return { rows: [{ t: opts.lastAgoMs === null ? null : new Date(now - opts.lastAgoMs).toISOString() }] };
return { rows: [] };
},
};
const d: SyncDeps = {
tx: (fn) => fn(q),
query: q.query,
getToken: async () => ({ accessToken: "at", realmId: "R1", apiBase: "https://api.test" }),
fetchFn: async (url) => {
const u = decodeURIComponent(url);
calls.push(u);
if (u.includes("/cdc?")) return { ok: true, status: 200, json: async () => opts.cdc };
return { ok: true, status: 200, json: async () => ({ QueryResponse: {} }) };
},
environment: "sandbox",
sleep: async () => undefined,
};
return { sync: new QboSync(d), sqls, calls };
}
const HOUR = 3600 * 1000;
const DAY = 24 * HOUR;
describe("CDC (инкрементальная загрузка)", () => {
it("есть недавний запуск и полная загрузка: берёт только изменения с нахлёстом, удалённые убирает, полных запросов нет", async () => {
const cdc = { CDCResponse: [{ QueryResponse: [
{ Purchase: [{ Id: "144", TotalAmt: 7, Line: [{ Amount: 7, AccountBasedExpenseLineDetail: { AccountRef: { value: "1" } } }] }, { Id: "145", status: "Deleted", domain: "QBO" }] },
{ Vendor: [{ Id: "7", DisplayName: "V" }] },
] }] };
const { sync, calls, sqls } = setupCdc({ lastAgoMs: 2 * HOUR, fullAgoMs: 2 * DAY, cdc });
const r = await sync.run();
expect(r.status).toBe("ok");
expect(r.counts).toMatchObject({ _cdc: 1, Purchase: 1, Purchase_deleted: 1, Vendor: 1, Account: 0 });
expect(r.counts._full).toBeUndefined();
expect(calls.filter((c) => c.includes("/cdc?"))).toHaveLength(1);
expect(calls.find((c) => c.includes("/cdc?"))).toMatch(/entities=Account,Vendor,Customer,Purchase,Bill,Attachable&changedSince=/);
expect(calls.some((c) => c.includes("select * from"))).toBe(false);
const since = new Date(/changedSince=([^&]+)/.exec(calls.find((c) => c.includes("/cdc?"))!)![1]!).getTime();
expect(Date.now() - since).toBeGreaterThan(2 * HOUR + 4 * 60 * 1000);
const text = sqls.map((s) => s.sql);
expect(text.some((s) => s.startsWith("delete from qbo_purchase where realm_id = $1 and id = any($2::text[])"))).toBe(true);
expect(text.some((s) => s.startsWith("delete from qbo_account where realm_id = $1 and not (id = any"))).toBe(false);
expect(text.some((s) => s.startsWith("insert into qbo_purchase_line"))).toBe(true);
});
it("первый запуск, давняя полная загрузка (> 7 дней), давний запуск (> 25 дней) и full=true - полная загрузка", async () => {
for (const o of [{ lastAgoMs: null, fullAgoMs: null }, { lastAgoMs: HOUR, fullAgoMs: 8 * DAY }, { lastAgoMs: 26 * DAY, fullAgoMs: 26 * DAY }, { lastAgoMs: HOUR, fullAgoMs: null }]) {
const { sync, calls } = setupCdc({ ...o, cdc: {} });
const r = await sync.run();
expect(r.counts._full, JSON.stringify(o)).toBe(1);
expect(calls.some((c) => c.includes("/cdc?"))).toBe(false);
}
const { sync, calls } = setupCdc({ lastAgoMs: HOUR, fullAgoMs: DAY, cdc: {} });
expect((await sync.run({ full: true })).counts._full).toBe(1);
expect(calls.some((c) => c.includes("/cdc?"))).toBe(false);
});
it("CDC достиг лимита 1000 объектов на сущность - откат на полную загрузку", async () => {
const many = Array.from({ length: 1000 }, (_, i) => ({ Id: String(i), Name: "n" + i }));
const { sync, calls } = setupCdc({ lastAgoMs: HOUR, fullAgoMs: DAY, cdc: { CDCResponse: [{ QueryResponse: [{ Account: many }] }] } });
const r = await sync.run();
expect(r.counts._full).toBe(1);
expect(r.counts._cdc).toBeUndefined();
expect(calls.some((c) => c.includes("/cdc?"))).toBe(true);
expect(calls.some((c) => c.includes("select * from Account"))).toBe(true);
});
});