accounting_automation: этап 1 бухгалтерской автоматизации (инвойсы из почты, категоризация, ручной разбор, MCP), интервальные задания scheduler, миграции 033/034/038
All checks were successful
ci / test (push) Successful in 40s
ci / deploy (push) Successful in 2m41s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 08:05:28 +03:00
parent 12e331efe9
commit b422309148
62 changed files with 4278 additions and 148 deletions

View File

@@ -0,0 +1,77 @@
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { createLogger, createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
import type { ClaudeRunner } from "./claude-runner.js";
import { runCategorization } from "./categorize.js";
import { runFinalize } from "./finalize.js";
import { ReviewTools } from "./mcp.js";
import { buildDailySummary } from "./summary.js";
const log = createLogger("test", "silent");
const url = testDatabaseUrl();
const d = url ? describe : describe.skip;
/** Сквозной путь этапа 1: агент предлагает категории -> очередь -> сотрудник в Claude разбирает через MCP -> завершение -> история. */
d("сквозной сценарий категоризации и разбора (временная БД)", () => {
let db: TestDb;
let tools: ReviewTools;
let nastia: string;
beforeAll(async () => {
db = await createTestDb(url!);
nastia = (await db.pool.query("insert into person (display_name, email, role_code) values ('Анастасия', 'nastia@khbuild.pro', 'cfo') returning id")).rows[0].id;
tools = new ReviewTools({
pool: db.pool,
settings: { reviewers: [{ personId: nastia, roles: ["accountant", "cfo"] }], mcp: { enabled: true, staticTokens: [] } },
});
});
afterAll(async () => { await db?.drop(); });
it("от ответа агента до истории правок", async () => {
const claude: ClaudeRunner = async () => ({
ok: true, exitCode: 0, timedOut: false, stderr: "",
stdout: "```json\n" + JSON.stringify({
run_id: "run-e2e",
results: [
{ feed_txn_id: "ok-1", suggestion: { account: "55", project_customer_id: "7", splits: [] }, confidence: 95 },
{ feed_txn_id: "doc-1", suggestion: null, problem_highlight: "ждёт документ" },
],
}) + "\n```",
});
const run = await runCategorization({ pool: db.pool, claude, loadPrompt: async () => "П", realmId: "9341", log });
expect(run).toMatchObject({ status: "ok", inserted: 2 });
// Claude сотрудника: список задач, сначала с проблемой
const list = (await tools.call(nastia, "acc_review_list", {})) as { tasks?: Array<Record<string, unknown>> } & Record<string, unknown>;
const text = JSON.stringify(list);
expect(text).toContain("ok-1");
expect(text).toContain("ждёт документ");
const tasks = (list.tasks ?? (list as unknown as { items: Array<Record<string, unknown>> }).items) as Array<Record<string, unknown>>;
expect(tasks[0]!.problem_highlight).toBe("ждёт документ");
const okTask = tasks.find((t) => JSON.stringify(t).includes("ok-1"))!;
// сотрудник меняет проект и подтверждает
await tools.call(nastia, "acc_review_update", { id: okTask.id, fields: { suggestion: { account: "55", project_customer_id: "8", splits: [] } } });
await tools.call(nastia, "acc_review_done", { id: okTask.id });
// сразу после отметки запись моложе задержки: завершение её не трогает
const notes: string[] = [];
const early = await runFinalize({ pool: db.pool, delaySeconds: 3600, notify: (t) => void notes.push(t) });
expect(early.finalized.categorization).toBe(0);
// после задержки - в историю с различиями, из очереди и review пропадает
const fin = await runFinalize({ pool: db.pool, delaySeconds: 0, notify: (t) => void notes.push(t) });
expect(fin.finalized.categorization).toBe(1);
const hist = (await db.pool.query("select feed_txn_id, closed_by, changed_fields from acc_categorization_review_history")).rows;
expect(hist).toHaveLength(1);
expect(hist[0]).toMatchObject({ feed_txn_id: "ok-1", closed_by: nastia });
expect(JSON.stringify(hist[0].changed_fields)).toContain("suggestion");
expect((await db.pool.query("select feed_txn_id from acc_categorization_review order by 1")).rows.map((r) => r.feed_txn_id)).toEqual(["doc-1"]);
expect((await db.pool.query("select ref_id from acc_manual_review")).rows.map((r) => r.ref_id)).toEqual(["doc-1"]);
// оригинал остаётся как записал автомат
expect((await db.pool.query("select suggestion from acc_categorization_review_original where feed_txn_id = 'ok-1'")).rows[0].suggestion.project_customer_id).toBe("7");
// сводка видит остаток и закрытое
const summary = await buildDailySummary(db.pool, new Date(), "Asia/Nicosia");
expect(summary).toContain("ждёт документ");
});
});