qbo_auth: страница ручных тестов /tests, разбор CloudEvents в вебхуке; список тестовых событий
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
39
docs/agent_memories/08-qbo-webhook-test-events.md
Normal file
39
docs/agent_memories/08-qbo-webhook-test-events.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# Тестовые события вебхуков Intuit (portal, Send test event)
|
||||
|
||||
Портал Intuit (приложение KHBuild_assistant, Webhooks, development) включён в формате **cloud events** («Enable cloud event payload format»): тело содержит `type` вида `qbo.bill.created.v1`, `intuitentityid`, `intuitaccountid` (realm). `parseWebhook` в `qbo_auth` понимает оба формата (классический eventNotifications и CloudEvents, объект или массив).
|
||||
|
||||
Для теста M2 слать: `qbo.bill.created.v1` (Bill входит в подписки). Ожидаем 200 от `/api/qbo/webhook` и в логах `khb-qbo-auth` запись «вебхук QuickBooks».
|
||||
|
||||
Полный список типов, доступных в «Send test event» (шаблон `qbo.<объект>.<действие>.v1`):
|
||||
- account: created, deleted, merged, updated
|
||||
- bill: created, deleted, updated
|
||||
- billpayment: created, deleted, updated, void
|
||||
- budget: created, updated
|
||||
- changeorder: created, deleted, updated
|
||||
- class: created, deleted, merged, updated
|
||||
- creditmemo: created, deleted, emailed, updated, void
|
||||
- currency: created, deleted, updated
|
||||
- customer: created, deleted, merged, updated
|
||||
- department: created, merged, updated
|
||||
- deposit: created, deleted, updated
|
||||
- employee: created, deleted, merged, updated
|
||||
- estimate: created, deleted, emailed, updated
|
||||
- invoice: created, deleted, emailed, updated, void
|
||||
- item: created, deleted, merged, updated
|
||||
- journalcode: created, updated
|
||||
- journalentry: created, deleted, updated
|
||||
- payment: created, deleted, emailed, updated, void
|
||||
- paymentmethod: created, merged, updated
|
||||
- preferences: updated
|
||||
- purchase: created, deleted, updated, void
|
||||
- purchaseorder: created, deleted, emailed, updated
|
||||
- refundreceipt: created, deleted, emailed, updated, void
|
||||
- salesreceipt: created, deleted, emailed, updated, void
|
||||
- taxagency: created, updated
|
||||
- term: created, updated
|
||||
- timeactivity: created, deleted, updated
|
||||
- transfer: created, deleted, updated, void
|
||||
- vendor: created, deleted, merged, updated
|
||||
- vendorcredit: created, deleted, updated
|
||||
|
||||
Страница ручных тестов: `https://services.khbuild.freeddns.org/api/qbo/tests` (форма открыта, действия требуют токен qbo_auth).
|
||||
@@ -1,6 +1,7 @@
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import { QboAuth, ReauthNeeded } from "./service.js";
|
||||
import type { QboSync } from "./sync.js";
|
||||
import { TESTS_PAGE } from "./tests-page.js";
|
||||
import { parseWebhook, verifyWebhook } from "./webhook.js";
|
||||
|
||||
export interface WebhookOptions {
|
||||
@@ -29,7 +30,7 @@ export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?:
|
||||
});
|
||||
app.addHook("onRequest", async (req, reply) => {
|
||||
const path = req.url.split("?")[0];
|
||||
if (path === "/healthz" || path === "/callback" || path === "/webhook") return;
|
||||
if (path === "/healthz" || path === "/callback" || path === "/webhook" || path === "/tests") return;
|
||||
if (req.headers.authorization !== `Bearer ${token}`) return reply.code(401).send({ error: "unauthorized" });
|
||||
});
|
||||
|
||||
@@ -43,6 +44,31 @@ export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?:
|
||||
return reply.code(200).send({ ok: true, events: events.length });
|
||||
});
|
||||
|
||||
/** Страница ручных тестов (форма открыта, действия /tests/* закрыты Bearer-токеном). Наружу: /api/qbo/tests. */
|
||||
app.get("/tests", async (_req, reply) => reply.type("text/html").send(TESTS_PAGE));
|
||||
app.get("/tests/status", async () => auth.status());
|
||||
app.post("/tests/connect", async () => auth.startConnect());
|
||||
app.post("/tests/disconnect", async () => auth.disconnect());
|
||||
app.post("/tests/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({ full: false });
|
||||
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 (tests)");
|
||||
return reply.code(502).send({ error: "sync_failed" });
|
||||
}
|
||||
});
|
||||
/** Заметка администратора о ручном тесте: пишется в журнал сервиса. */
|
||||
app.post("/tests/note", async (req, reply) => {
|
||||
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 }, "заметка ручного теста");
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
app.get("/healthz", async () => ({ ok: true, time: new Date().toISOString() }));
|
||||
|
||||
app.get("/callback", async (req, reply) => {
|
||||
|
||||
31
packages/qbo_auth/src/tests-page.ts
Normal file
31
packages/qbo_auth/src/tests-page.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
/** Страница ручных тестов для администратора (/api/qbo/tests). Сама страница открыта (только форма), все действия требуют служебный токен qbo_auth, который вводится в поле и хранится в sessionStorage браузера. */
|
||||
export const TESTS_PAGE = `<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Тесты qbo_auth</title>
|
||||
<style>body{font:15px/1.5 system-ui,sans-serif;max-width:760px;margin:24px auto;padding:0 16px}button{margin:4px 4px 4px 0;padding:6px 12px}input,textarea{width:100%;box-sizing:border-box;margin:4px 0}pre{background:#f3f4f6;padding:10px;white-space:pre-wrap;word-break:break-all}h2{margin-top:24px}</style></head><body>
|
||||
<h1>Ручные тесты QuickBooks (qbo_auth)</h1>
|
||||
<p>Служебный токен qbo_auth (хранится только в этой вкладке):</p>
|
||||
<input id="tok" type="password" autocomplete="off" placeholder="токен">
|
||||
<h2>M1. Подключение</h2>
|
||||
<p>1) «Отключить» (удаляет токены и отзывает их у Intuit). 2) «Подключить» и пройти авторизацию в открывшейся вкладке. 3) «Статус». 4) Отключите приложение в QuickBooks (Apps, KHBuild_assistant, Disconnect) и нажмите «Синхронизация»: ожидается 409 reauth_needed.</p>
|
||||
<button data-a="status" data-m="GET">Статус</button>
|
||||
<button data-a="connect" data-m="POST">Подключить</button>
|
||||
<button data-a="disconnect" data-m="POST">Отключить</button>
|
||||
<button data-a="sync" data-m="POST">Синхронизация</button>
|
||||
<h2>M3. Заметка</h2>
|
||||
<p>Например: «создал Bill на сумму 123.45 для вендора X».</p>
|
||||
<textarea id="note" rows="2" maxlength="500"></textarea>
|
||||
<button id="send">Отправить</button>
|
||||
<pre id="out">Результат появится здесь.</pre>
|
||||
<script>
|
||||
const $=id=>document.getElementById(id), out=$('out');
|
||||
try{$('tok').value=sessionStorage.getItem('qbo_tok')||''}catch(e){}
|
||||
async function call(a,m,body){
|
||||
try{sessionStorage.setItem('qbo_tok',$('tok').value)}catch(e){}
|
||||
out.textContent='...';
|
||||
const r=await fetch('/api/qbo/tests/'+a,{method:m,headers:{'Authorization':'Bearer '+$('tok').value,'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined});
|
||||
const t=await r.text(); let j; try{j=JSON.parse(t)}catch(e){}
|
||||
out.textContent=r.status+' '+(j?JSON.stringify(j,null,2):t);
|
||||
if(a==='connect'&&j&&j.url){const l=document.createElement('a');l.href=j.url;l.target='_blank';l.textContent='Открыть авторизацию Intuit';out.appendChild(document.createElement('br'));out.appendChild(l);window.open(j.url,'_blank')}
|
||||
}
|
||||
document.querySelectorAll('button[data-a]').forEach(b=>b.onclick=()=>call(b.dataset.a,b.dataset.m));
|
||||
$('send').onclick=()=>call('note','POST',{text:$('note').value}).then(()=>{$('note').value=''});
|
||||
</script></body></html>`;
|
||||
@@ -25,6 +25,22 @@ describe("вебхук Intuit", () => {
|
||||
expect(parseWebhook("{}")).toEqual([]);
|
||||
});
|
||||
|
||||
it("разбор CloudEvents: один объект и массив", () => {
|
||||
const ev = { specversion: "1.0", type: "qbo.bill.created.v1", intuitentityid: "7", intuitaccountid: "R1" };
|
||||
expect(parseWebhook(JSON.stringify(ev))).toEqual([{ realmId: "R1", name: "Bill", id: "7", operation: "Create" }]);
|
||||
expect(parseWebhook(JSON.stringify([ev, { ...ev, type: "qbo.vendor.deleted.v1", intuitentityid: "8" }])).map((e) => `${e.name}:${e.operation}`)).toEqual(["Bill:Create", "Vendor:Delete"]);
|
||||
});
|
||||
|
||||
it("страница /tests открыта, действия /tests/* закрыты токеном, заметка принимается", async () => {
|
||||
const app = buildApi({} as QboAuth, "svc");
|
||||
expect((await app.inject({ url: "/tests" })).statusCode).toBe(200);
|
||||
expect((await app.inject({ url: "/tests/status" })).statusCode).toBe(401);
|
||||
expect((await app.inject({ method: "POST", url: "/tests/disconnect" })).statusCode).toBe(401);
|
||||
const h = { authorization: "Bearer svc", "content-type": "application/json" };
|
||||
expect((await app.inject({ method: "POST", url: "/tests/note", headers: h, payload: { text: "Bill 12.50" } })).statusCode).toBe(200);
|
||||
expect((await app.inject({ method: "POST", url: "/tests/note", headers: h, payload: { text: " " } })).statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("маршрут /webhook: без токенов 503, плохая подпись 401, верная 200 и вызов onEvents без Bearer-токена сервиса", async () => {
|
||||
const onEvents = vi.fn();
|
||||
const auth = {} as QboAuth;
|
||||
|
||||
@@ -17,13 +17,22 @@ export interface WebhookEntity {
|
||||
operation: string;
|
||||
}
|
||||
|
||||
/** Плоский список изменённых объектов из тела вебхука; чужой формат даёт пустой список. */
|
||||
const CE_OPS: Record<string, string> = { created: "Create", updated: "Update", deleted: "Delete", merged: "Merge", void: "Void", emailed: "Emailed" };
|
||||
|
||||
/** Плоский список изменённых объектов из тела вебхука: классический формат (eventNotifications) и CloudEvents (type вида qbo.bill.created.v1, один объект или массив); чужой формат даёт пустой список. */
|
||||
export function parseWebhook(rawBody: string): WebhookEntity[] {
|
||||
try {
|
||||
const j = JSON.parse(rawBody) as { eventNotifications?: Array<{ realmId?: string; dataChangeEvent?: { entities?: Array<{ name?: string; id?: string; operation?: string }> } }> };
|
||||
return (j.eventNotifications ?? []).flatMap((n) =>
|
||||
const j = JSON.parse(rawBody) as unknown;
|
||||
const classic = (j as { eventNotifications?: Array<{ realmId?: string; dataChangeEvent?: { entities?: Array<{ name?: string; id?: string; operation?: string }> } }> }).eventNotifications;
|
||||
const out: WebhookEntity[] = (classic ?? []).flatMap((n) =>
|
||||
(n.dataChangeEvent?.entities ?? []).map((e) => ({ realmId: String(n.realmId ?? ""), name: String(e.name ?? ""), id: String(e.id ?? ""), operation: String(e.operation ?? "") })),
|
||||
);
|
||||
for (const e of Array.isArray(j) ? j : [j]) {
|
||||
const c = e as { type?: string; intuitentityid?: string; intuitaccountid?: string };
|
||||
const m = /^qbo\.([a-z]+)\.([a-z]+)\.v\d+$/.exec(String(c?.type ?? ""));
|
||||
if (m && m[1] && m[2]) out.push({ realmId: String(c.intuitaccountid ?? ""), name: m[1].charAt(0).toUpperCase() + m[1].slice(1), id: String(c.intuitentityid ?? ""), operation: CE_OPS[m[2]] ?? m[2] });
|
||||
}
|
||||
return out;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user