diff --git a/docs/proposed/modules/quickbooks_bookkeeper/intuit_requirements.md b/docs/proposed/modules/quickbooks_bookkeeper/intuit_requirements.md index e955a25..eff0057 100644 --- a/docs/proposed/modules/quickbooks_bookkeeper/intuit_requirements.md +++ b/docs/proposed/modules/quickbooks_bookkeeper/intuit_requirements.md @@ -6,7 +6,7 @@ Выполняет Юрий в самом конце, на последней развёрнутой версии. Статусы: TBD, затем дата и done (ставлю я со слов Юрия «успех»). Всё делается в обычном браузере. Основная точка входа: страница тестов по секретной ссылке (адрес в `temp_keys/qbo_tests_url.txt`, вида https://services.khbuild.freeddns.org/api/qbo/tests/<секрет>): кнопки Статус, Подключить, Отключить, Синхронизация и поле заметки. Ничего вводить не нужно: секрет входит в адрес и выводится из служебного токена; без правильного адреса страница и действия недоступны (404). -- M1. TBD. Подключение, отключение, повторное подключение на sandbox (анкета: Authorization 1). На странице тестов: (а) «Отключить», «Статус» (connected: false), «Подключить», в открывшейся вкладке Intuit войти администратором, выбрать sandbox-компанию, Connect; ожидается страница «QuickBooks подключён», затем «Статус» (connected: true) и «Синхронизация» проходит. (б) В https://app.sandbox.qbo.intuit.com отключить приложение (Apps, KHBuild_assistant, Disconnect); на странице тестов «Синхронизация»: ожидается 409 reauth_needed; затем «Отключить». (в) «Подключить» заново, пройти авторизацию, «Синхронизация» проходит. +- M1. TBD (в работе: 2026-11-23 06:31-06:32 UTC по журналу nginx выполнено «Отключить», «Статус» connected: false, «Подключить», возврат Intuit с 302 на страницу «подключён», «Статус» connected: true; остаётся «Синхронизация» и пункты б, в; с этой версии действия страницы тестов пишутся в журнал qbo_auth записью «ручной тест»). Подключение, отключение, повторное подключение на sandbox (анкета: Authorization 1). На странице тестов: (а) «Отключить», «Статус» (connected: false), «Подключить», в открывшейся вкладке Intuit войти администратором, выбрать sandbox-компанию, Connect; ожидается страница «QuickBooks подключён», затем «Статус» (connected: true) и «Синхронизация» проходит. (б) В https://app.sandbox.qbo.intuit.com отключить приложение (Apps, KHBuild_assistant, Disconnect); на странице тестов «Синхронизация»: ожидается 409 reauth_needed; затем «Отключить». (в) «Подключить» заново, пройти авторизацию, «Синхронизация» проходит. - M2. TBD. Вебхуки (анкета: Accounting API 4). 2026-11-23 Юрий отправил тест из портала (показал SUCCESS), но наш сервер ответил 415 из-за типа `application/cloudevents+json`; исправлено в тот же день (парсер и тест), тест из портала нужно повторить. В https://developer.intuit.com приложение KHBuild_assistant, Webhooks, вкладка development: «Send test event», событие `qbo.bill.created.v1`, Send. Проверка по логам: я. - M3. TBD. Изменение данных доходит до зеркала. В https://app.sandbox.qbo.intuit.com создать Bill (Expenses, Bills, Add bill), на странице тестов в поле заметки написать, что создано (сумма, вендор), «Отправить». Проверка по таблицам `qbo_*`: я. - M4. TBD. Страницы (окно инкогнито): https://services.khbuild.freeddns.org/legal/index.html, а также privacy.html, eula.html, connect.html, disconnect.html по тому же пути; текст читается, контакты верны. diff --git a/packages/qbo_auth/src/http-api.ts b/packages/qbo_auth/src/http-api.ts index 4eba59a..91153a3 100644 --- a/packages/qbo_auth/src/http-api.ts +++ b/packages/qbo_auth/src/http-api.ts @@ -18,7 +18,11 @@ 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, sync?: QboSync, webhook?: WebhookOptions): FastifyInstance { +export interface AuditLog { + info(obj: Record, msg: string): void; +} + +export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?: WebhookOptions, audit?: AuditLog): FastifyInstance { const app = Fastify(); // тело вебхука нужно целиком (подпись считается по сырой строке) app.addContentTypeParser("application/json", { parseAs: "string" }, (req, body, done) => { @@ -62,18 +66,38 @@ export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?: */ const tests = (req: { params: unknown }): boolean => (req.params as { slug?: string }).slug === slug; app.get("/tests/:slug", async (req, reply) => (tests(req) ? reply.type("text/html").send(TESTS_PAGE) : reply.code(404).send({ error: "not_found" }))); - app.get("/tests/:slug/status", async (req, reply) => (tests(req) ? auth.status() : reply.code(404).send({ error: "not_found" }))); - app.post("/tests/:slug/connect", async (req, reply) => (tests(req) ? auth.startConnect() : reply.code(404).send({ error: "not_found" }))); - app.post("/tests/:slug/disconnect", async (req, reply) => (tests(req) ? auth.disconnect() : reply.code(404).send({ error: "not_found" }))); + app.get("/tests/:slug/status", async (req, reply) => { + if (!tests(req)) return reply.code(404).send({ error: "not_found" }); + const st = await auth.status(); + audit?.info({ action: "status", connected: st.connected, status: "status" in st ? st.status : "not_connected" }, "ручной тест"); + return st; + }); + app.post("/tests/:slug/connect", async (req, reply) => { + if (!tests(req)) return reply.code(404).send({ error: "not_found" }); + const r = await auth.startConnect(); + audit?.info({ action: "connect", result: "ссылка авторизации выдана" }, "ручной тест"); + return r; + }); + app.post("/tests/:slug/disconnect", async (req, reply) => { + if (!tests(req)) return reply.code(404).send({ error: "not_found" }); + const r = await auth.disconnect(); + audit?.info({ action: "disconnect", ...r }, "ручной тест"); + return r; + }); app.post("/tests/:slug/sync", async (req, reply) => { if (!tests(req)) return reply.code(404).send({ error: "not_found" }); 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({ full: false }); + audit?.info({ action: "sync", result: r.status, http: r.status === "ok" ? 200 : 502 }, "ручной тест"); 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 }); + if (e instanceof ReauthNeeded) { + audit?.info({ action: "sync", result: "reauth_needed", http: 409 }, "ручной тест"); + return reply.code(409).send({ error: "reauth_needed", message: e.message }); + } + audit?.info({ action: "sync", result: "sync_failed", http: 502 }, "ручной тест"); req.log.error({ err: String(e) }, "sync (tests)"); return reply.code(502).send({ error: "sync_failed" }); } @@ -83,7 +107,7 @@ export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?: if (!tests(req)) return reply.code(404).send({ error: "not_found" }); const text = String((req.body as { text?: string } | undefined)?.text ?? "").slice(0, 500).trim(); if (!text) return reply.code(400).send({ error: "empty" }); - req.log.info({ note: text }, "заметка ручного теста"); + audit?.info({ action: "note", note: text }, "ручной тест"); return { ok: true }; }); @@ -93,8 +117,10 @@ export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?: const q = req.query as { code?: string; state?: string; realmId?: string; error?: string }; try { await auth.handleCallback(q); + audit?.info({ action: "callback", result: "подключено" }, "ручной тест"); return reply.redirect("/api/qbo/connected?ok=1", 302); } catch (e) { + audit?.info({ action: "callback", result: "отклонено", reason: String(e).slice(0, 160) }, "ручной тест"); req.log.warn({ err: String(e) }, "callback отклонён"); return reply.redirect("/api/qbo/connected?ok=0", 302); } diff --git a/packages/qbo_auth/src/main.ts b/packages/qbo_auth/src/main.ts index 06deed3..664c179 100644 --- a/packages/qbo_auth/src/main.ts +++ b/packages/qbo_auth/src/main.ts @@ -49,7 +49,7 @@ const app = buildApi(auth, s.http.token, sync, { log.info({ count: events.length, entities: [...new Set(events.map((e) => `${e.name}:${e.operation}`))].slice(0, 20) }, "вебхук QuickBooks"); trigger.poke(); }, -}); +}, log); { const n = await store.encryptExistingRealms().catch((e) => (log.error({ err: String(e) }, "шифрование realm_id"), 0)); if (n) log.info({ rows: n }, "realm_id зашифрован в существующих записях"); diff --git a/packages/qbo_auth/src/webhook.test.ts b/packages/qbo_auth/src/webhook.test.ts index 92bbbc6..a54f5d7 100644 --- a/packages/qbo_auth/src/webhook.test.ts +++ b/packages/qbo_auth/src/webhook.test.ts @@ -32,7 +32,8 @@ describe("вебхук Intuit", () => { }); it("страница тестов: только по секретному адресу, заголовки без кэша, заметка принимается", async () => { - const app = buildApi({} as QboAuth, "svc"); + const audit = { info: vi.fn() }; + const app = buildApi({} as QboAuth, "svc", undefined, undefined, audit); const slug = testsSlug("svc"); expect(slug).toMatch(/^[0-9a-f]{32}$/); expect((await app.inject({ url: "/tests/wrong" })).statusCode).toBe(404); @@ -46,6 +47,7 @@ describe("вебхук Intuit", () => { const h = { "content-type": "application/json" }; expect((await app.inject({ method: "POST", url: `/tests/${slug}/note`, headers: h, payload: { text: "Bill 12.50" } })).statusCode).toBe(200); expect((await app.inject({ method: "POST", url: `/tests/${slug}/note`, headers: h, payload: { text: " " } })).statusCode).toBe(400); + expect(audit.info).toHaveBeenCalledWith({ action: "note", note: "Bill 12.50" }, "ручной тест"); }); it("вебхук с типом application/cloudevents+json принимается (раньше было 415)", async () => {