accounting_automation: этап 1 бухгалтерской автоматизации (инвойсы из почты, категоризация, ручной разбор, MCP), интервальные задания scheduler, миграции 033/034/038
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
290
packages/accounting_automation/src/mcp.int.test.ts
Normal file
290
packages/accounting_automation/src/mcp.int.test.ts
Normal file
@@ -0,0 +1,290 @@
|
||||
import Fastify from "fastify";
|
||||
import { exportJWK, generateKeyPair, SignJWT, createLocalJWKSet } from "jose";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
|
||||
import { keycloakVerifier } from "./mcp-auth.js";
|
||||
import { ReviewTools, registerMcp, type McpDeps } from "./mcp.js";
|
||||
|
||||
const url = testDatabaseUrl();
|
||||
const d = url ? describe : describe.skip;
|
||||
|
||||
const ISSUER = "https://sso.example.test/realms/khb";
|
||||
const TOKEN_A = "token-accountant-0123456789";
|
||||
const TOKEN_CFO = "token-cfo-0123456789abcd";
|
||||
const NOW = new Date("2026-11-17T12:00:00Z");
|
||||
|
||||
d("MCP бухгалтерии (временная БД)", () => {
|
||||
let db: TestDb;
|
||||
let accountant: string; // только роль accountant
|
||||
let cfo: string; // accountant + cfo
|
||||
let stranger: string; // не в reviewers
|
||||
let kc: string; // person с email из Keycloak, роль accountant
|
||||
let settings: McpDeps["settings"];
|
||||
let tools: ReviewTools;
|
||||
let signer: Awaited<ReturnType<typeof generateKeyPair>>["privateKey"];
|
||||
let verifyJwt: McpDeps["verifyJwt"];
|
||||
|
||||
const call = (who: string, name: string, args: Record<string, unknown> = {}) => tools.call(who, name, args);
|
||||
const errOf = async (p: Promise<unknown>): Promise<string> => {
|
||||
try {
|
||||
await p;
|
||||
} catch (e) {
|
||||
return (e as Error).message;
|
||||
}
|
||||
return "NO ERROR";
|
||||
};
|
||||
const addInvoice = async (extra: Record<string, unknown> = {}) => {
|
||||
const r = await db.pool.query(
|
||||
`insert into acc_invoices_review (source_message_id, drive_file_id, vendor_name, amount, problem_highlight)
|
||||
values ('m1', 'drv1', $1, 100, $2) returning id`,
|
||||
[extra.vendor ?? "Vendor A", extra.problem ?? null],
|
||||
);
|
||||
return (await db.pool.query("select id from acc_manual_review where ref_id = $1", [r.rows[0].id])).rows[0].id as string;
|
||||
};
|
||||
const addCat = async (feed: string, problem: string | null = null) => {
|
||||
await db.pool.query(
|
||||
`insert into acc_categorization_review (feed_txn_id, run_id, run_started_at, suggestion, confidence, problem_highlight)
|
||||
values ($1, 'run1', now(), '{"account":"Materials"}', 80, $2)`,
|
||||
[feed, problem],
|
||||
);
|
||||
return (await db.pool.query("select id from acc_manual_review where ref_id = $1", [feed])).rows[0].id as string;
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
db = await createTestDb(url!);
|
||||
const mk = async (name: string, email: string, extra = "null", active = true) =>
|
||||
(await db.pool.query("insert into person (display_name, email, additional_emails, is_active) values ($1, $2, $3, $4) returning id", [name, email, extra === "null" ? null : extra, active])).rows[0].id as string;
|
||||
accountant = await mk("Юля", "yulia@khbuild.pro");
|
||||
cfo = await mk("Анастасия", "anastasia@khbuild.pro");
|
||||
stranger = await mk("Чужой", "x@khbuild.pro");
|
||||
kc = await mk("KC", "kc@khbuild.pro", "other@gmail.com; kc.alias@gmail.com");
|
||||
await mk("Неактивный", "off@khbuild.pro", "null", false);
|
||||
settings = {
|
||||
reviewers: [
|
||||
{ personId: accountant, roles: ["accountant"] },
|
||||
{ personId: cfo, roles: ["accountant", "cfo"] },
|
||||
{ personId: kc, roles: ["accountant"] },
|
||||
],
|
||||
mcp: { enabled: true, issuer: ISSUER, staticTokens: [{ token: TOKEN_A, personId: accountant }, { token: TOKEN_CFO, personId: cfo }, { token: "token-stranger-0123456789", personId: stranger }] },
|
||||
};
|
||||
tools = new ReviewTools({ pool: db.pool, settings, now: () => NOW });
|
||||
const { privateKey, publicKey } = await generateKeyPair("RS256");
|
||||
signer = privateKey;
|
||||
const jwk = { ...(await exportJWK(publicKey)), kid: "k1", alg: "RS256", use: "sig" };
|
||||
verifyJwt = keycloakVerifier(ISSUER, createLocalJWKSet({ keys: [jwk] }));
|
||||
});
|
||||
afterAll(async () => {
|
||||
await db?.drop();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await db.pool.query("truncate acc_manual_review, acc_invoices_review, acc_invoices_review_original, acc_categorization_review, acc_categorization_review_original, acc_certificates_review, acc_certificates_review_original cascade");
|
||||
});
|
||||
|
||||
describe("чистый слой", () => {
|
||||
it("без записи в reviewers доступ запрещён, пустые reviewers - тоже", async () => {
|
||||
expect(await errOf(call(stranger, "acc_review_list"))).toContain("Доступ запрещён");
|
||||
const empty = new ReviewTools({ pool: db.pool, settings: { reviewers: [] }, now: () => NOW });
|
||||
expect(await errOf(empty.call(cfo, "acc_review_list", {}))).toContain("Доступ запрещён");
|
||||
});
|
||||
|
||||
it("список: видимость по ролям, сортировка с проблемой вперёд, данные строк, ссылка на файл", async () => {
|
||||
await addInvoice();
|
||||
const withProblem = await addCat("f1", "ждёт документ");
|
||||
const cfoTask = await addCat("f2");
|
||||
await db.pool.query("update acc_manual_review set assignee_role = 'cfo' where id = $1", [cfoTask]);
|
||||
const y = (await call(accountant, "acc_review_list")) as { total: number; tasks: Array<Record<string, any>> };
|
||||
expect(y.total).toBe(2);
|
||||
expect(y.tasks[0].id).toBe(withProblem);
|
||||
expect(y.tasks[0].review.feed_txn_id).toBe("f1");
|
||||
expect(y.tasks[0].review.run_id).toBe("run1");
|
||||
expect(y.tasks[0].review.confidence).toBe(80);
|
||||
expect(y.tasks[0].problem_highlight).toBe("ждёт документ");
|
||||
expect(y.tasks[1].kind).toBe("invoice");
|
||||
expect(y.tasks[1].file_url).toBe("https://drive.google.com/file/d/drv1/view");
|
||||
expect(y.tasks.map((t) => t.id)).not.toContain(cfoTask);
|
||||
const a = (await call(cfo, "acc_review_list")) as { total: number };
|
||||
expect(a.total).toBe(3);
|
||||
const onlyCfo = (await call(cfo, "acc_review_list", { role: "cfo" })) as { tasks: Array<{ id: string }> };
|
||||
expect(onlyCfo.tasks.map((t) => t.id)).toEqual([cfoTask]);
|
||||
expect(await errOf(call(accountant, "acc_review_list", { role: "cfo" }))).toContain("нет роли cfo");
|
||||
const k = (await call(cfo, "acc_review_list", { kind: "invoice" })) as { total: number };
|
||||
expect(k.total).toBe(1);
|
||||
});
|
||||
|
||||
it("отложенные скрыты, include_snoozed их показывает; выполненные скрыты", async () => {
|
||||
const t1 = await addInvoice();
|
||||
const t2 = await addInvoice();
|
||||
await call(accountant, "acc_review_snooze", { id: t1, until: "2026-11-20" });
|
||||
expect(((await call(accountant, "acc_review_list")) as { total: number }).total).toBe(1);
|
||||
expect(((await call(accountant, "acc_review_list", { include_snoozed: true })) as { total: number }).total).toBe(2);
|
||||
await call(accountant, "acc_review_done", { id: t2 });
|
||||
expect(((await call(accountant, "acc_review_list")) as { total: number }).total).toBe(0);
|
||||
expect(await errOf(call(accountant, "acc_review_snooze", { id: t1, until: "2026-11-01" }))).toContain("в будущем");
|
||||
expect(await errOf(call(accountant, "acc_review_snooze", { id: t1, until: "завтра" }))).toContain("until");
|
||||
});
|
||||
|
||||
it("get: задача, строка, original, изменённые поля, ссылка", async () => {
|
||||
const t = await addInvoice();
|
||||
await call(accountant, "acc_review_update", { id: t, fields: { vendor_name: "Vendor B" } });
|
||||
const g = (await call(accountant, "acc_review_get", { id: t })) as Record<string, any>;
|
||||
expect(g.review.vendor_name).toBe("Vendor B");
|
||||
expect(g.original.vendor_name).toBe("Vendor A");
|
||||
expect(g.changed_fields).toEqual(["vendor_name"]);
|
||||
expect(g.file_url).toBe("https://drive.google.com/file/d/drv1/view");
|
||||
expect(await errOf(call(accountant, "acc_review_get", { id: "not-uuid" }))).toContain("uuid");
|
||||
});
|
||||
|
||||
it("update: белый список, типы, null, запрет чужих колонок", async () => {
|
||||
const t = await addInvoice();
|
||||
const r = (await call(accountant, "acc_review_update", {
|
||||
id: t,
|
||||
fields: { invoice_number: "INV-7", invoice_date: "2026-11-01", amount: "250.5", lines: [{ what: "work", sum: 250.5 }], problem_highlight: null },
|
||||
})) as { review: Record<string, any> };
|
||||
expect(r.review.invoice_number).toBe("INV-7");
|
||||
expect(r.review.invoice_date).toBe("2026-11-01");
|
||||
expect(r.review.amount).toBe(250.5);
|
||||
expect(r.review.lines).toEqual([{ what: "work", sum: 250.5 }]);
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { done: true } }))).toContain("править нельзя");
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { drive_file_id: "x" } }))).toContain("править нельзя");
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { invoice_date: "01.11.2026" } }))).toContain("YYYY-MM-DD");
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { amount: "abc" } }))).toContain("число");
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: {} }))).toContain("fields");
|
||||
// отказ откатывает всю правку целиком
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { vendor_name: "ZZ", amount: "bad" } }))).toContain("amount");
|
||||
expect((await db.pool.query("select vendor_name from acc_invoices_review")).rows[0].vendor_name).toBe("Vendor A");
|
||||
// категоризация и сертификат
|
||||
const c = await addCat("f9");
|
||||
const cr = (await call(accountant, "acc_review_update", { id: c, fields: { suggestion: { account: "Tools" }, confidence: 55, problem_highlight: "проверить" } })) as { review: Record<string, any> };
|
||||
expect(cr.review.suggestion).toEqual({ account: "Tools" });
|
||||
expect(cr.review.confidence).toBe(55);
|
||||
expect((await db.pool.query("select problem_highlight from acc_manual_review where id = $1", [c])).rows[0].problem_highlight).toBe("проверить");
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: c, fields: { confidence: 101 } }))).toContain("0..100");
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: c, fields: { run_id: "x" } }))).toContain("править нельзя");
|
||||
await db.pool.query("insert into acc_certificates_review (vendor_name) values ('V')");
|
||||
const cert = (await db.pool.query("select id from acc_manual_review where kind = 'certificate'")).rows[0].id;
|
||||
const ce = (await call(accountant, "acc_review_update", { id: cert, fields: { expires_on: "2027-01-31", vendor_qbo_id: "q1" } })) as { review: Record<string, any> };
|
||||
expect(ce.review.expires_on).toBe("2027-01-31");
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: cert, fields: { amount: 1 } }))).toContain("править нельзя");
|
||||
});
|
||||
|
||||
it("чужая роль: нельзя читать, править, закрывать; cfo-задачу категоризации закрывает только cfo", async () => {
|
||||
const t = await addCat("f3");
|
||||
await db.pool.query("update acc_manual_review set assignee_role = 'cfo' where id = $1", [t]);
|
||||
for (const n of ["acc_review_get", "acc_review_done", "acc_review_return", "acc_review_snooze", "acc_review_handoff", "acc_review_update"]) {
|
||||
const m = await errOf(call(accountant, n, { id: t, until: "2026-12-01", reason: "r", role: "accountant", fields: { confidence: 1 } }));
|
||||
expect(m, n).toContain("роли cfo");
|
||||
}
|
||||
expect(await errOf(call(accountant, "acc_review_done", { id: t }))).toMatch(/cfo/);
|
||||
await call(cfo, "acc_review_done", { id: t });
|
||||
const row = (await db.pool.query("select done, done_by from acc_categorization_review")).rows[0];
|
||||
expect(row).toEqual({ done: true, done_by: cfo });
|
||||
});
|
||||
|
||||
it("done: отмечает done и done_by, повтор - ошибка; нет задачи - ошибка", async () => {
|
||||
const t = await addInvoice();
|
||||
await call(accountant, "acc_review_done", { id: t });
|
||||
expect((await db.pool.query("select done, done_by from acc_invoices_review")).rows[0]).toEqual({ done: true, done_by: accountant });
|
||||
expect(await errOf(call(accountant, "acc_review_done", { id: t }))).toContain("уже отмечена");
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { vendor_name: "Q" } }))).toContain("уже отмечена");
|
||||
expect(await errOf(call(accountant, "acc_review_done", { id: "00000000-0000-4000-8000-000000000000" }))).toContain("не найдена");
|
||||
});
|
||||
|
||||
it("handoff меняет роль и дописывает комментарий; return возвращает accountant с причиной и снимает snooze", async () => {
|
||||
const t = await addCat("f4", "крупная сумма");
|
||||
const h = (await call(accountant, "acc_review_handoff", { id: t, role: "cfo", comment: "сумма $6000" })) as { task: Record<string, any> };
|
||||
expect(h.task.assignee_role).toBe("cfo");
|
||||
expect(h.task.problem_highlight).toBe("крупная сумма | Передано accountant -> cfo: сумма $6000");
|
||||
expect((await db.pool.query("select problem_highlight from acc_categorization_review")).rows[0].problem_highlight).toContain("сумма $6000");
|
||||
// после передачи accountant задачу больше не видит
|
||||
expect(await errOf(call(accountant, "acc_review_get", { id: t }))).toContain("роли cfo");
|
||||
expect(await errOf(call(cfo, "acc_review_handoff", { id: t, role: "cfo" }))).toContain("уже назначена");
|
||||
expect(await errOf(call(cfo, "acc_review_handoff", { id: t, role: "boss" }))).toContain("role");
|
||||
await call(cfo, "acc_review_snooze", { id: t, until: "2026-12-01" });
|
||||
const r = (await call(cfo, "acc_review_return", { id: t, reason: "нет документа" })) as { task: Record<string, any> };
|
||||
expect(r.task.assignee_role).toBe("accountant");
|
||||
expect(r.task.snoozed_until).toBeNull();
|
||||
expect(r.task.problem_highlight).toBe("Возвращено: нет документа");
|
||||
expect(await errOf(call(cfo, "acc_review_return", { id: t, reason: " " }))).toContain("причина");
|
||||
});
|
||||
|
||||
it("вид без review-таблицы: виден, но правка и закрытие запрещены; handoff/return работают", async () => {
|
||||
const t = (await db.pool.query("insert into acc_manual_review (kind, ref_table, ref_id) values ('chargeback', 'acc_chargeback', 'x1') returning id")).rows[0].id;
|
||||
expect(((await call(accountant, "acc_review_list")) as { total: number }).total).toBe(1);
|
||||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { a: 1 } }))).toContain("не предусмотрена");
|
||||
expect(await errOf(call(accountant, "acc_review_done", { id: t }))).toContain("нельзя");
|
||||
await call(accountant, "acc_review_return", { id: t, reason: "уточнить" });
|
||||
expect((await db.pool.query("select problem_highlight from acc_manual_review where id = $1", [t])).rows[0].problem_highlight).toBe("Возвращено: уточнить");
|
||||
});
|
||||
});
|
||||
|
||||
describe("HTTP", () => {
|
||||
const post = async (headers: Record<string, string>, payload: unknown, deps: Partial<McpDeps> = {}) => {
|
||||
const app = Fastify();
|
||||
registerMcp(app, { pool: db.pool, settings, now: () => NOW, verifyJwt, ...deps });
|
||||
const res = await app.inject({ method: "POST", url: "/mcp", headers, payload: payload as object });
|
||||
await app.close();
|
||||
return res;
|
||||
};
|
||||
const rpc = (method: string, params?: unknown, id: number | undefined = 1) => ({ jsonrpc: "2.0", id, method, params });
|
||||
const bearer = (t: string) => ({ authorization: `Bearer ${t}` });
|
||||
const jwt = (claims: Record<string, unknown>, opts: { iss?: string; exp?: string } = {}) =>
|
||||
new SignJWT(claims).setProtectedHeader({ alg: "RS256", kid: "k1" }).setIssuer(opts.iss ?? ISSUER).setIssuedAt().setExpirationTime(opts.exp ?? "5m").sign(signer);
|
||||
|
||||
it("без токена и с неверным токеном - 401", async () => {
|
||||
const a = await post({}, rpc("initialize"));
|
||||
expect(a.statusCode).toBe(401);
|
||||
expect(a.headers["www-authenticate"]).toBe("Bearer");
|
||||
expect((await post(bearer("wrong-token-wrong-token"), rpc("initialize"))).statusCode).toBe(401);
|
||||
expect((await post({ authorization: "Basic abc" }, rpc("initialize"))).statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("initialize, notifications/initialized, ping, tools/list", async () => {
|
||||
const i = await post(bearer(TOKEN_A), rpc("initialize", { protocolVersion: "2025-03-26" }));
|
||||
expect(i.statusCode).toBe(200);
|
||||
expect(i.json().result.serverInfo.name).toBe("khb-accounting");
|
||||
expect((await post(bearer(TOKEN_A), { jsonrpc: "2.0", method: "notifications/initialized" })).statusCode).toBe(202);
|
||||
expect(((await post(bearer(TOKEN_A), rpc("ping"))).json()).result).toEqual({});
|
||||
const l = (await post(bearer(TOKEN_A), rpc("tools/list"))).json();
|
||||
expect(l.result.tools.map((t: { name: string }) => t.name)).toEqual([
|
||||
"acc_review_list", "acc_review_get", "acc_review_update", "acc_review_done", "acc_review_handoff", "acc_review_return", "acc_review_snooze",
|
||||
]);
|
||||
expect((await post(bearer(TOKEN_A), rpc("nope"))).json().error.code).toBe(-32601);
|
||||
});
|
||||
|
||||
it("tools/call со статическим токеном: список, ошибка доступа - isError", async () => {
|
||||
await addInvoice();
|
||||
const ok = (await post(bearer(TOKEN_A), rpc("tools/call", { name: "acc_review_list", arguments: {} }))).json();
|
||||
expect(ok.result.isError).toBeUndefined();
|
||||
expect(JSON.parse(ok.result.content[0].text).total).toBe(1);
|
||||
const denied = (await post(bearer("token-stranger-0123456789"), rpc("tools/call", { name: "acc_review_list", arguments: {} }))).json();
|
||||
expect(denied.result.isError).toBe(true);
|
||||
expect(denied.result.content[0].text).toContain("Доступ запрещён");
|
||||
const bad = (await post(bearer(TOKEN_A), rpc("tools/call", { name: "acc_review_get", arguments: { id: "x" } }))).json();
|
||||
expect(bad.result.isError).toBe(true);
|
||||
});
|
||||
|
||||
it("JWT Keycloak: person по основной и дополнительной почте; чужой email - 403; плохие токены - 401", async () => {
|
||||
await addInvoice();
|
||||
const call = { name: "acc_review_list", arguments: {} };
|
||||
for (const email of ["kc@khbuild.pro", "KC.Alias@gmail.com", "other@gmail.com"]) {
|
||||
const r = await post(bearer(await jwt({ email, email_verified: true })), rpc("tools/call", call));
|
||||
expect(r.statusCode, email).toBe(200);
|
||||
expect(JSON.parse(r.json().result.content[0].text).total).toBe(1);
|
||||
}
|
||||
expect((await post(bearer(await jwt({ email: "nobody@x.com" })), rpc("tools/call", call))).statusCode).toBe(403);
|
||||
expect((await post(bearer(await jwt({ email: "off@khbuild.pro" })), rpc("tools/call", call))).statusCode).toBe(403);
|
||||
expect((await post(bearer(await jwt({ email: "kc@khbuild.pro", email_verified: false })), rpc("tools/call", call))).statusCode).toBe(401);
|
||||
expect((await post(bearer(await jwt({})), rpc("tools/call", call))).statusCode).toBe(401);
|
||||
expect((await post(bearer(await jwt({ email: "kc@khbuild.pro" }, { iss: "https://evil.test/realms/x" })), rpc("tools/call", call))).statusCode).toBe(401);
|
||||
expect((await post(bearer(await jwt({ email: "kc@khbuild.pro" }, { exp: "-1m" })), rpc("tools/call", call))).statusCode).toBe(401);
|
||||
const other = await generateKeyPair("RS256");
|
||||
const forged = await new SignJWT({ email: "kc@khbuild.pro" }).setProtectedHeader({ alg: "RS256", kid: "k1" }).setIssuer(ISSUER).setExpirationTime("5m").sign(other.privateKey);
|
||||
expect((await post(bearer(forged), rpc("tools/call", call))).statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("mcp.enabled=false: маршрут не регистрируется", async () => {
|
||||
const r = await post(bearer(TOKEN_A), rpc("ping"), { settings: { ...settings, mcp: { ...settings.mcp, enabled: false } } });
|
||||
expect(r.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user