Зеркало QuickBooks qbo_* (миграция 032) и загрузка POST /sync в qbo_auth, задание scheduler qbo_sync (п.85)
All checks were successful
ci / test (push) Successful in 36s
ci / deploy (push) Successful in 2m33s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 23:32:36 +03:00
parent d8926bc6dc
commit 12e331efe9
7 changed files with 569 additions and 3 deletions

View File

@@ -108,3 +108,4 @@
82. **Письма подрядчикам от агента (10.11.2026)**: менеджер просит ассистента вызвать подрядчика на объект, письмо уходит через команду `khb-mail` (`resolve` - подбор адресата, `send` - отправка), агент письма не пишет и адрес не вводит. Адресат - ровно один подрядчик, назначенный на открытую работу проекта менеджера в графике JobTread; на работе стоит конкретный человек - письмо ему, иначе общий адрес вендора (поле Email вендора, затем email пользователя с названием компании); не один адресат - письмо не отправляется, агент уточняет. Текст по шаблону Артура (английский), код `KHB-ГГММДД-XXXX` в теме и мелким шрифтом в конце. Отправка через Gmail API от имени менеджера (сервисный аккаунт с делегированием на уровне домена, scope `gmail.send`; у менеджера нет ящика в домене - от agents@ с Reply-To), копия agents@ и Артуру, лимит 30 писем в сутки на менеджера, защита от дублей, телефон и email менеджера - из профиля JobTread (нет телефона - письмо уходит без телефона: «email me at…» и только email в подписи; решение Юрия 11.11.2026). Журнал - таблица `contractor_email` (миграция 029: время, адресаты, отправитель, Message-ID, код, ссылка на комментарий) и комментарий к проекту в JobTread; тестовый менеджер - режим dry_run. Описание: `docs/proposed/modules/khbuild_assistant_prep/contractor-email.md`; реализация: `src/mail/`, `tools/khb-mail.ts`, раздел «Письма подрядчикам» в `p-manager-dialog.md`. Разбор входящих ответов - отдельный сервис (сопоставление по Message-ID и коду в теме).
83. **Ручной сбор с ожиданием итога (11.11.2026)**: по багрепорту `bugs/data_collector/bug-on-demand-run-wait-result` `POST /runs` принимает `?wait=true&timeoutSec=` (по умолчанию 120 с, максимум 300): ответ по завершении - `200 {snapshotTs, status ok|error, durationMs, tables[]}`, по таймауту - `202 running`. Если сбор уже идёт, возвращается его `snapshotTs` (`alreadyRunning: true`) и при `wait` ожидается именно он, вместо прежнего `409` (оно осталось для прочих ошибок старта). Без `wait` поведение прежнее. Описано в `data_objects/data_collector/api_objects.md`.
84. **Сервис `qbo_auth` (16.11.2026, по решению Юрия)**: единственный держатель OAuth-токенов QuickBooks Online. Порт 8095, контейнер `khb-qbo-auth`; миграция 031 (`qbo_connection`, `qbo_oauth_state`; токены в БД зашифрованы AES-256-GCM, ключ `qbo_auth.encryptionKey` в settings.json5). Наружу открыт только возврат OAuth `https://services.khbuild.freeddns.org/api/qbo/callback` (одноразовый state); `POST /connect` (ссылка авторизации), `GET /status`, `POST /token` (свежий access token для других сервисов), `POST /keepalive` закрыты токеном сервиса и docker-сетью. Скользящий refresh token обновляется под блокировкой, раз в час проверка (обновление, если старше 20 ч), при `invalid_grant` - статус `reauth_needed` и уведомление ИТ. Режим `sandbox` (ключи development) до production-ключей Intuit. Хост `api.khbuild.freeddns.org` удалён из nginx (был retired); публичные входы сервисов - только `services` по пути `/api/<сервис>/`. Основание и план: `modules/quickbooks_bookkeeper/` (исследование API, предложение).
85. **Зеркало QuickBooks `qbo_*` (16.11.2026, таблицы созданы сразу, согласование позднее)**: миграция 032 - `qbo_account`, `qbo_vendor`, `qbo_customer` (проекты: `is_job`, `parent_id`), `qbo_purchase` + `qbo_purchase_line` (счёт и проект каждой строки), `qbo_bill` + `qbo_bill_line`, `qbo_attachable` (вложения и ссылки на документы), `qbo_sync_run` (журнал). Ключ везде `(realm_id, id)`, полный объект QuickBooks - в `raw jsonb`. Загрузку выполняет `qbo_auth` (временно, до согласования модуля `quickbooks_bookkeeper`): `POST /sync` - полная перезагрузка, исчезнувшие в QuickBooks объекты удаляются из зеркала; задание `qbo_sync` в scheduler ежедневно в 05:40. Только чтение из QuickBooks; зеркало вручную не правится. Пока sandbox (realm 9341458717054536).

View File

@@ -0,0 +1,169 @@
-- Зеркало QuickBooks Online (модуль quickbooks_bookkeeper, пока загружает сервис qbo_auth: POST /sync).
-- Таблицы создаются по предложению docs/proposed/modules/quickbooks_bookkeeper.md (п. 4.2); состав колонок ждёт согласования владельца.
-- Ключ везде (realm_id, id): sandbox и production не смешиваются. Полная запись объекта QuickBooks - в raw (jsonb), чтобы ничего не терять при смене состава колонок.
-- Зеркало только читается из QuickBooks; изменения в QuickBooks делаются отдельным путём (после подтверждения человека), эти таблицы вручную не правятся.
create table if not exists qbo_account (
realm_id text not null,
id text not null,
acct_num text, -- код счёта (например 3.5.)
name text not null,
fully_qualified_name text, -- с родителями: "13. Hard Cost:13.17. Plumbing:..."
account_type text,
account_sub_type text,
classification text, -- Asset / Liability / Equity / Revenue / Expense
parent_id text,
active boolean not null default true,
current_balance numeric(18,2),
sync_token text,
meta_updated timestamptz,
raw jsonb not null,
synced_at timestamptz not null default now(),
primary key (realm_id, id)
);
create table if not exists qbo_vendor (
realm_id text not null,
id text not null,
display_name text not null,
company_name text,
email text,
phone text,
active boolean not null default true,
balance numeric(18,2),
sync_token text,
meta_updated timestamptz,
raw jsonb not null,
synced_at timestamptz not null default now(),
primary key (realm_id, id)
);
-- Клиенты и проекты: проект в QuickBooks - дочерний Customer (is_job = true, parent_id - клиент).
create table if not exists qbo_customer (
realm_id text not null,
id text not null,
display_name text not null,
fully_qualified_name text,
parent_id text,
is_job boolean not null default false,
active boolean not null default true,
balance numeric(18,2),
sync_token text,
meta_updated timestamptz,
raw jsonb not null,
synced_at timestamptz not null default now(),
primary key (realm_id, id)
);
-- Расходы (банк, карта, чек): Purchase.
create table if not exists qbo_purchase (
realm_id text not null,
id text not null,
txn_date date,
payment_type text, -- Cash / Check / CreditCard
account_id text, -- банковский или карточный счёт
account_name text,
entity_id text, -- вендор
entity_name text,
total_amt numeric(18,2),
doc_number text,
private_note text, -- сюда автомат пишет идентификатор предложения (идемпотентность, отметка источника)
sync_token text,
meta_created timestamptz,
meta_updated timestamptz,
raw jsonb not null,
synced_at timestamptz not null default now(),
primary key (realm_id, id)
);
create index if not exists qbo_purchase_date_idx on qbo_purchase (realm_id, txn_date);
create table if not exists qbo_purchase_line (
realm_id text not null,
purchase_id text not null,
line_no int not null,
amount numeric(18,2),
description text,
account_id text, -- счёт учёта строки (категория)
account_name text,
customer_id text, -- проект / клиент строки
customer_name text,
class_id text,
billable_status text,
primary key (realm_id, purchase_id, line_no)
);
create index if not exists qbo_purchase_line_account_idx on qbo_purchase_line (realm_id, account_id);
create index if not exists qbo_purchase_line_customer_idx on qbo_purchase_line (realm_id, customer_id);
-- Счета вендоров.
create table if not exists qbo_bill (
realm_id text not null,
id text not null,
txn_date date,
due_date date,
vendor_id text,
vendor_name text,
total_amt numeric(18,2),
balance numeric(18,2),
doc_number text,
private_note text,
sync_token text,
meta_created timestamptz,
meta_updated timestamptz,
raw jsonb not null,
synced_at timestamptz not null default now(),
primary key (realm_id, id)
);
create table if not exists qbo_bill_line (
realm_id text not null,
bill_id text not null,
line_no int not null,
amount numeric(18,2),
description text,
account_id text,
account_name text,
customer_id text,
customer_name text,
class_id text,
billable_status text,
primary key (realm_id, bill_id, line_no)
);
create index if not exists qbo_bill_line_customer_idx on qbo_bill_line (realm_id, customer_id);
-- Вложения (инвойсы, чеки) и к чему они привязаны: нужны для правила «к клиентскому расходу обязателен документ».
create table if not exists qbo_attachable (
realm_id text not null,
id text not null,
file_name text,
content_type text,
size bigint,
note text,
refs jsonb not null default '[]'::jsonb, -- [{"type":"Purchase","id":"144"}, ...]
sync_token text,
meta_created timestamptz,
raw jsonb not null,
synced_at timestamptz not null default now(),
primary key (realm_id, id)
);
-- Журнал загрузок зеркала.
create table if not exists qbo_sync_run (
id bigserial primary key,
realm_id text,
environment text,
started_at timestamptz not null default now(),
finished_at timestamptz,
status text not null default 'running' check (status in ('running', 'ok', 'error')),
counts jsonb not null default '{}'::jsonb, -- {"Account": 89, "Purchase": 35, ...}
error text
);
alter table qbo_account enable row level security;
alter table qbo_vendor enable row level security;
alter table qbo_customer enable row level security;
alter table qbo_purchase enable row level security;
alter table qbo_purchase_line enable row level security;
alter table qbo_bill enable row level security;
alter table qbo_bill_line enable row level security;
alter table qbo_attachable enable row level security;
alter table qbo_sync_run enable row level security;

View File

@@ -1,5 +1,6 @@
import Fastify, { type FastifyInstance } from "fastify";
import { QboAuth, ReauthNeeded } from "./service.js";
import type { QboSync } from "./sync.js";
const page = (title: string, text: string) =>
`<!doctype html><html lang="ru"><meta charset="utf-8"><meta name="robots" content="noindex"><title>${title}</title><body style="font-family:system-ui;max-width:32rem;margin:4rem auto;padding:0 1rem"><h1>${title}</h1><p>${text}</p></body></html>`;
@@ -8,7 +9,7 @@ const page = (title: string, text: string) =>
* Служебные ручки закрыты токеном (settings.json5 `qbo_auth.http.token`); открыты /healthz и /callback.
* /callback защищён одноразовым state; наружу (nginx services) публикуется только он: /api/qbo/callback.
*/
export function buildApi(auth: QboAuth, token: string): FastifyInstance {
export function buildApi(auth: QboAuth, token: string, sync?: QboSync): FastifyInstance {
const app = Fastify();
app.addHook("onRequest", async (req, reply) => {
const path = req.url.split("?")[0];
@@ -44,6 +45,19 @@ export function buildApi(auth: QboAuth, token: string): FastifyInstance {
return reply.code(502).send({ error: "token_error" });
}
});
/** Полная загрузка зеркала QuickBooks в таблицы qbo_* (вызывает scheduler и ручной запуск). Ждёт итога: 200 ok, 502 ошибка, 409 уже идёт. */
app.post("/sync", async (req, reply) => {
if (!sync) return reply.code(501).send({ error: "sync_not_configured" });
if (sync.isRunning) return reply.code(409).send({ error: "already_running" });
try {
const r = await sync.run();
return reply.code(r.status === "ok" ? 200 : 502).send(r);
} catch (e) {
if (e instanceof ReauthNeeded) return reply.code(409).send({ error: "reauth_needed", message: e.message });
req.log.error({ err: String(e) }, "sync");
return reply.code(502).send({ error: "sync_failed" });
}
});
app.post("/keepalive", async () => ({ result: await auth.keepAlive() }));
return app;
}

View File

@@ -1,9 +1,10 @@
import { createLogger, createPool, itNotify, loadServiceSettings } from "khb_common";
import { createLogger, createPool, itNotify, loadServiceSettings, withTx } from "khb_common";
import { parseKey } from "./crypto.js";
import { buildApi } from "./http-api.js";
import { QboAuth } from "./service.js";
import { qboAuthSchema } from "./settings.js";
import { PgStore } from "./store.js";
import { QboSync } from "./sync.js";
const { common, service: s } = loadServiceSettings("qbo_auth", qboAuthSchema);
const log = createLogger("qbo_auth", common.logLevel);
@@ -22,7 +23,15 @@ const auth = new QboAuth({
},
});
const app = buildApi(auth, s.http.token);
const sync = new QboSync({
tx: (fn) => withTx(pool, fn),
query: (sql, params) => pool.query(sql, params),
getToken: (opts) => auth.getAccessToken(opts),
fetchFn: (url, init) => fetch(url, init),
environment: s.environment,
log: (msg, extra) => log.info(extra ?? {}, msg),
});
const app = buildApi(auth, s.http.token, sync);
await app.listen({ host: s.http.host, port: s.http.port });
log.info({ port: s.http.port, environment: s.environment }, "qbo_auth запущен");

View File

@@ -0,0 +1,115 @@
/** Преобразование объектов QuickBooks в строки таблиц qbo_* (миграция 032). Полный объект всегда сохраняется в raw. */
type Obj = Record<string, any>;
export type Row = Record<string, unknown>;
const ref = (r: Obj | undefined): { id: string | null; name: string | null } => ({ id: r?.value != null ? String(r.value) : null, name: r?.name ?? null });
const money = (v: unknown): number | null => (v === undefined || v === null || v === "" ? null : Number(v));
const ts = (v: unknown): string | null => (typeof v === "string" && v ? v : null);
const date = (v: unknown): string | null => (typeof v === "string" && /^\d{4}-\d{2}-\d{2}/.test(v) ? v.slice(0, 10) : null);
export interface EntitySpec {
/** Имя сущности в QuickBooks (запрос `select * from <name>`). */
entity: string;
table: string;
/** Колонки основной таблицы без realm_id и synced_at. */
columns: string[];
map(o: Obj): Row;
/** Строки дочерней таблицы (строки документа), если есть. */
lines?: { table: string; parentColumn: string; columns: string[]; map(o: Obj, parentId: string): Row[] };
}
const lineRows = (o: Obj, parentId: string, parentColumn: string): Row[] => {
const out: Row[] = [];
(o.Line ?? []).forEach((l: Obj, i: number) => {
const d = l.AccountBasedExpenseLineDetail ?? l.ItemBasedExpenseLineDetail;
if (!d) return; // итоговые и прочие служебные строки в разбивку не входят
const acc = ref(d.AccountRef), cust = ref(d.CustomerRef);
out.push({
[parentColumn]: parentId,
line_no: i,
amount: money(l.Amount),
description: l.Description ?? null,
account_id: acc.id,
account_name: acc.name,
customer_id: cust.id,
customer_name: cust.name,
class_id: ref(d.ClassRef).id,
billable_status: d.BillableStatus ?? null,
});
});
return out;
};
const LINE_COLUMNS = ["line_no", "amount", "description", "account_id", "account_name", "customer_id", "customer_name", "class_id", "billable_status"];
export const SPECS: EntitySpec[] = [
{
entity: "Account",
table: "qbo_account",
columns: ["id", "acct_num", "name", "fully_qualified_name", "account_type", "account_sub_type", "classification", "parent_id", "active", "current_balance", "sync_token", "meta_updated", "raw"],
map: (o) => ({
id: String(o.Id), acct_num: o.AcctNum ?? null, name: o.Name, fully_qualified_name: o.FullyQualifiedName ?? null,
account_type: o.AccountType ?? null, account_sub_type: o.AccountSubType ?? null, classification: o.Classification ?? null,
parent_id: ref(o.ParentRef).id, active: o.Active !== false, current_balance: money(o.CurrentBalance),
sync_token: o.SyncToken ?? null, meta_updated: ts(o.MetaData?.LastUpdatedTime), raw: o,
}),
},
{
entity: "Vendor",
table: "qbo_vendor",
columns: ["id", "display_name", "company_name", "email", "phone", "active", "balance", "sync_token", "meta_updated", "raw"],
map: (o) => ({
id: String(o.Id), display_name: o.DisplayName, company_name: o.CompanyName ?? null, email: o.PrimaryEmailAddr?.Address ?? null,
phone: o.PrimaryPhone?.FreeFormNumber ?? null, active: o.Active !== false, balance: money(o.Balance),
sync_token: o.SyncToken ?? null, meta_updated: ts(o.MetaData?.LastUpdatedTime), raw: o,
}),
},
{
entity: "Customer",
table: "qbo_customer",
columns: ["id", "display_name", "fully_qualified_name", "parent_id", "is_job", "active", "balance", "sync_token", "meta_updated", "raw"],
map: (o) => ({
id: String(o.Id), display_name: o.DisplayName, fully_qualified_name: o.FullyQualifiedName ?? null, parent_id: ref(o.ParentRef).id,
is_job: o.Job === true, active: o.Active !== false, balance: money(o.Balance),
sync_token: o.SyncToken ?? null, meta_updated: ts(o.MetaData?.LastUpdatedTime), raw: o,
}),
},
{
entity: "Purchase",
table: "qbo_purchase",
columns: ["id", "txn_date", "payment_type", "account_id", "account_name", "entity_id", "entity_name", "total_amt", "doc_number", "private_note", "sync_token", "meta_created", "meta_updated", "raw"],
map: (o) => {
const acc = ref(o.AccountRef), ent = ref(o.EntityRef);
return {
id: String(o.Id), txn_date: date(o.TxnDate), payment_type: o.PaymentType ?? null, account_id: acc.id, account_name: acc.name,
entity_id: ent.id, entity_name: ent.name, total_amt: money(o.TotalAmt), doc_number: o.DocNumber ?? null, private_note: o.PrivateNote ?? null,
sync_token: o.SyncToken ?? null, meta_created: ts(o.MetaData?.CreateTime), meta_updated: ts(o.MetaData?.LastUpdatedTime), raw: o,
};
},
lines: { table: "qbo_purchase_line", parentColumn: "purchase_id", columns: LINE_COLUMNS, map: (o, id) => lineRows(o, id, "purchase_id") },
},
{
entity: "Bill",
table: "qbo_bill",
columns: ["id", "txn_date", "due_date", "vendor_id", "vendor_name", "total_amt", "balance", "doc_number", "private_note", "sync_token", "meta_created", "meta_updated", "raw"],
map: (o) => {
const v = ref(o.VendorRef);
return {
id: String(o.Id), txn_date: date(o.TxnDate), due_date: date(o.DueDate), vendor_id: v.id, vendor_name: v.name, total_amt: money(o.TotalAmt),
balance: money(o.Balance), doc_number: o.DocNumber ?? null, private_note: o.PrivateNote ?? null,
sync_token: o.SyncToken ?? null, meta_created: ts(o.MetaData?.CreateTime), meta_updated: ts(o.MetaData?.LastUpdatedTime), raw: o,
};
},
lines: { table: "qbo_bill_line", parentColumn: "bill_id", columns: LINE_COLUMNS, map: (o, id) => lineRows(o, id, "bill_id") },
},
{
entity: "Attachable",
table: "qbo_attachable",
columns: ["id", "file_name", "content_type", "size", "note", "refs", "sync_token", "meta_created", "raw"],
map: (o) => ({
id: String(o.Id), file_name: o.FileName ?? null, content_type: o.ContentType ?? null, size: o.Size != null ? Number(o.Size) : null, note: o.Note ?? null,
refs: JSON.stringify((o.AttachableRef ?? []).map((r: Obj) => ({ type: r.EntityRef?.type ?? null, id: r.EntityRef?.value != null ? String(r.EntityRef.value) : null }))),
sync_token: o.SyncToken ?? null, meta_created: ts(o.MetaData?.CreateTime), raw: o,
}),
},
];

View File

@@ -0,0 +1,121 @@
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;
});
});

View 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;
}
}
}