import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { createTestDb, testDatabaseUrl, type TestDb } from "khb_common"; import { diffWithOriginal, runFinalize } from "./finalize.js"; import { buildDailySummary, postDailySummary, twoWorkdaysAgo } from "./summary.js"; import { createSlackPoster } from "./slack.js"; const url = testDatabaseUrl(); const d = url ? describe : describe.skip; const TABLES = [ "acc_manual_review", "acc_invoices_review", "acc_categorization_review", "acc_certificates_review", "acc_invoices_review_original", "acc_categorization_review_original", "acc_certificates_review_original", "acc_invoices_review_history", "acc_categorization_review_history", "acc_certificates_review_history", "acc_invoices", "acc_insurance_certificates", "acc_receipt_search", ]; d("завершение ручного разбора и сводка (временная БД)", () => { let db: TestDb; let notes: string[]; const later = (sec = 7200) => () => new Date(Date.now() + sec * 1000); const fin = (over: Partial[0]> = {}) => runFinalize({ pool: db.pool, now: later(), notify: (t) => { notes.push(t); }, ...over }); const q = async (sql: string, p: unknown[] = []) => (await db.pool.query(sql, p)).rows; async function newInvoice(over: Record = {}): Promise { const r = { vendor_name: "ACME Plumbing", invoice_date: "2026-11-01", amount: 1000, project_customer_id: "proj-1", ...over }; const rows = await q( `insert into acc_invoices_review (source_message_id, drive_file_id, vendor_name, invoice_date, amount, project_customer_id, lines) values ('msg-1', 'file-1', $1, $2, $3, $4, '[{"d":"работа"}]') returning id`, [r.vendor_name, r.invoice_date, r.amount, r.project_customer_id], ); return rows[0].id; } beforeAll(async () => { db = await createTestDb(url!); }); afterAll(async () => { await db?.drop(); }); beforeEach(async () => { notes = []; await q(`truncate ${TABLES.join(", ")} cascade`); }); it("полный путь инвойса: review -> done -> acc_invoices, history с changed_fields, очередь пуста", async () => { const id = await newInvoice(); expect(await q("select kind from acc_manual_review")).toEqual([{ kind: "invoice" }]); await q("update acc_invoices_review set amount = 1200, vendor_name = 'ACME Plumbing LLC', done = true, done_by = 'Anastasia' where id = $1", [id]); const res = await fin(); expect(res.finalized).toEqual({ invoices: 1, categorization: 0, certificates: 0 }); expect(res.rejected).toEqual([]); expect(res.errors).toEqual([]); const inv = await q("select * from acc_invoices where id = $1", [id]); expect(inv).toHaveLength(1); expect(inv[0]).toMatchObject({ stage: "checking", vendor_name: "ACME Plumbing LLC", source_message_id: "msg-1", drive_file_id: "file-1", project_customer_id: "proj-1" }); expect(Number(inv[0].amount)).toBe(1200); const h = await q("select * from acc_invoices_review_history where id = $1", [id]); expect(h).toHaveLength(1); expect(h[0].closed_by).toBe("Anastasia"); expect(h[0].closed_at).toBeInstanceOf(Date); expect(Number(h[0].amount)).toBe(1200); expect(h[0].changed_fields).toEqual({ amount: { old: 1000, new: 1200 }, vendor_name: { old: "ACME Plumbing", new: "ACME Plumbing LLC" }, }); // оригинал остался как записал автомат expect(Number((await q("select amount from acc_invoices_review_original where id = $1", [id]))[0].amount)).toBe(1000); expect(await q("select 1 from acc_invoices_review where id = $1", [id])).toHaveLength(0); expect(await q("select 1 from acc_manual_review")).toHaveLength(0); expect(notes).toEqual([]); }); it("отказ валидации: снимает done, пишет причину, уведомляет, запись остаётся в очереди", async () => { const id = await newInvoice({ vendor_name: "tbd", project_customer_id: null }); await q("update acc_invoices_review set done = true, done_by = 'Yulia' where id = $1", [id]); const res = await fin(); expect(res.finalized.invoices).toBe(0); expect(res.rejected).toHaveLength(1); expect(res.rejected[0]).toMatchObject({ kind: "invoices", id }); expect(res.rejected[0].reason).toContain("vendor_name"); expect(res.rejected[0].reason).toContain("project_customer_id"); const r = (await q("select done, problem_highlight from acc_invoices_review where id = $1", [id]))[0]; expect(r.done).toBe(false); expect(r.problem_highlight).toContain("vendor_name"); expect(notes).toHaveLength(1); expect(notes[0]).toContain("Yulia"); expect(notes[0]).toContain("vendor_name"); expect(await q("select 1 from acc_invoices_review_history")).toHaveLength(0); expect(await q("select 1 from acc_invoices")).toHaveLength(0); // триггер синхронизировал проблему в очереди expect((await q("select problem_highlight from acc_manual_review"))[0].problem_highlight).toContain("vendor_name"); // done снят: повторный запуск ничего не делает и не шлёт новых уведомлений const again = await fin(); expect(again.rejected).toEqual([]); expect(notes).toHaveLength(1); }); it("сумма не больше нуля отклоняется", async () => { const id = await newInvoice({ amount: 0 }); await q("update acc_invoices_review set done = true where id = $1", [id]); const res = await fin(); expect(res.rejected[0]?.reason).toContain("сумма"); }); it("запись моложе задержки не трогается", async () => { const id = await newInvoice(); await q("update acc_invoices_review set done = true where id = $1", [id]); const young = await fin({ delaySeconds: 3600, now: () => new Date() }); expect(young.finalized.invoices).toBe(0); expect(young.rejected).toEqual([]); expect(await q("select 1 from acc_invoices_review where id = $1 and done", [id])).toHaveLength(1); // по умолчанию задержка 30 секунд: через минуту запись обрабатывается const old = await fin({ now: later(60) }); expect(old.finalized.invoices).toBe(1); }); it("запись без done не обрабатывается", async () => { await newInvoice(); const res = await fin(); expect(res.finalized).toEqual({ invoices: 0, categorization: 0, certificates: 0 }); expect(await q("select 1 from acc_manual_review")).toHaveLength(1); }); it("категоризация: только фиксируется результат, очередь очищается", async () => { await q( `insert into acc_categorization_review (feed_txn_id, run_id, run_started_at, suggestion, confidence, problem_highlight) values ('tx-1', 'run-1', now(), '{"account":"Materials"}', 80, 'ждёт документ')`, ); expect(await q("select kind from acc_manual_review")).toEqual([{ kind: "categorization" }]); await q("update acc_categorization_review set done = true, done_by = 'Anastasia' where feed_txn_id = 'tx-1'"); const res = await fin(); expect(res.finalized).toEqual({ invoices: 0, categorization: 1, certificates: 0 }); const h = await q("select closed_by, changed_fields, suggestion from acc_categorization_review_history where feed_txn_id = 'tx-1'"); expect(h).toHaveLength(1); expect(h[0].closed_by).toBe("Anastasia"); expect(h[0].changed_fields).toEqual({}); // problem_highlight и done - служебные, правкой не считаются expect(h[0].suggestion).toEqual({ account: "Materials" }); expect(await q("select 1 from acc_categorization_review")).toHaveLength(0); expect(await q("select 1 from acc_manual_review")).toHaveLength(0); }); it("сертификат: обновляет существующий, создаёт новый, отклоняет пустой", async () => { const [{ id: certId }] = await q( "insert into acc_insurance_certificates (vendor_name, valid_until, drive_file_id) values ('Roofers Inc', '2026-11-20', 'f-1') returning id", ); // 1) указан certificate_id await q("insert into acc_certificates_review (vendor_name, certificate_id, expires_on, problem_highlight) values ('Roofers Inc', $1, '2026-11-20', 'истекает через 5 дней')", [certId]); // 2) без certificate_id, но у вендора сертификат есть (ищется по имени) // 3) вендора нет вовсе: создаётся запись await q("insert into acc_certificates_review (vendor_name, expires_on) values ('New Vendor', '2027-01-31')"); // 4) ни срока, ни сертификата await q("insert into acc_certificates_review (vendor_name) values ('Empty Vendor')"); await q("update acc_certificates_review set expires_on = '2027-06-30', done = true, done_by = 'Anastasia' where vendor_name = 'Roofers Inc'"); await q("update acc_certificates_review set done = true where vendor_name in ('New Vendor', 'Empty Vendor')"); const res = await fin(); expect(res.finalized.certificates).toBe(2); expect(res.rejected).toHaveLength(1); expect(res.rejected[0].reason).toContain("expires_on"); const roofers = await q("select to_char(valid_until, 'YYYY-MM-DD') v from acc_insurance_certificates where id = $1", [certId]); expect(roofers[0].v).toBe("2027-06-30"); const created = await q("select to_char(valid_until, 'YYYY-MM-DD') v, drive_file_id from acc_insurance_certificates where vendor_name = 'New Vendor'"); expect(created).toEqual([{ v: "2027-01-31", drive_file_id: "manual" }]); const h = await q("select changed_fields from acc_certificates_review_history where vendor_name = 'Roofers Inc'"); expect(h[0].changed_fields).toEqual({ expires_on: { old: "2026-11-20", new: "2027-06-30" } }); // осталась только отклонённая запись expect((await q("select vendor_name from acc_certificates_review")).map((r) => r.vendor_name)).toEqual(["Empty Vendor"]); }); it("повторный запуск идемпотентен", async () => { const id = await newInvoice(); await q("update acc_invoices_review set done = true where id = $1", [id]); expect((await fin()).finalized.invoices).toBe(1); const again = await fin(); expect(again.finalized).toEqual({ invoices: 0, categorization: 0, certificates: 0 }); expect(await q("select 1 from acc_invoices_review_history")).toHaveLength(1); expect(await q("select 1 from acc_invoices")).toHaveLength(1); }); it("вернувшийся в разбор инвойс обновляет запись реестра, не меняя статус", async () => { const id = await newInvoice(); await q("update acc_invoices_review set done = true where id = $1", [id]); await fin(); await q("update acc_invoices set stage = 'to_approve' where id = $1", [id]); // повторный разбор с тем же id (например, расхождение с QuickBooks) await q( `insert into acc_invoices_review (id, source_message_id, drive_file_id, vendor_name, invoice_date, amount, project_customer_id, done) values ($1, 'msg-1', 'file-1', 'ACME Plumbing', '2026-11-01', 1500, 'proj-1', true)`, [id]); const res = await fin(); expect(res.errors).toEqual([]); expect(res.finalized.invoices).toBe(1); const inv = (await q("select stage, amount from acc_invoices where id = $1", [id]))[0]; expect(inv.stage).toBe("to_approve"); expect(Number(inv.amount)).toBe(1500); expect(await q("select 1 from acc_invoices_review_history where id = $1", [id])).toHaveLength(2); }); it("параллельный запуск двух finalize: каждая запись обработана ровно один раз", async () => { const ids: string[] = []; for (let i = 0; i < 6; i++) ids.push(await newInvoice({ vendor_name: `V${i}` })); await q("update acc_invoices_review set done = true"); const [a, b] = await Promise.all([fin(), fin()]); expect(a.errors).toEqual([]); expect(b.errors).toEqual([]); expect(a.finalized.invoices + b.finalized.invoices).toBe(6); expect(await q("select 1 from acc_invoices_review_history")).toHaveLength(6); expect(await q("select 1 from acc_invoices")).toHaveLength(6); expect(await q("select 1 from acc_invoices_review")).toHaveLength(0); expect(await q("select 1 from acc_manual_review")).toHaveLength(0); }); it("diffWithOriginal: служебные поля и равные значения не попадают в различия", () => { const cur = { id: "1", amount: 5, lines: [{ a: 1 }], done: true, updated_at: "x", problem_highlight: null }; const org = { id: "1", amount: 5, lines: [{ a: 1 }], done: false, updated_at: "y", problem_highlight: "p" }; expect(diffWithOriginal(cur, org)).toEqual({}); expect(diffWithOriginal({ ...cur, amount: 6 }, org)).toEqual({ amount: { old: 5, new: 6 } }); expect(diffWithOriginal(cur, null)).toEqual({}); }); // ------------------------------------------------------------------ сводка const NOW = new Date("2026-11-17T15:00:00Z"); // вторник, 17:00 по Кипру const TZ = "Asia/Nicosia"; async function seedSummary() { const mr = (kind: string, ref: string, role: string, problem: string | null, created: string, snoozed: string | null = null) => q( `insert into acc_manual_review (kind, ref_table, ref_id, assignee_role, problem_highlight, created_at, snoozed_until) values ($1, $2, $3, $4, $5, $6, $7)`, [kind, `acc_${kind}_review`, ref, role, problem, created, snoozed], ); await mr("invoice", "i1", "accountant", "проект неясен", "2026-11-10T09:00:00Z"); // старше 2 рабочих дней await mr("invoice", "i2", "accountant", null, "2026-11-17T09:00:00Z"); await mr("categorization", "c1", "accountant", "ждёт документ", "2026-11-16T09:00:00Z"); await mr("categorization", "c2", "accountant", "подозрение на дубль", "2026-11-16T09:00:00Z"); await mr("categorization", "c3", "cfo", null, "2026-11-16T09:00:00Z"); await mr("certificate", "s1", "accountant", "истекает через 5 дней", "2026-11-17T09:00:00Z"); await mr("categorization", "c4", "accountant", "нужен человек", "2026-11-17T09:00:00Z", "2026-11-25T00:00:00Z"); // отложена: не считается const hist = (table: string, key: string, by: string, created: string, closed: string, changed: string | null) => q( table === "acc_invoices_review_history" ? `insert into ${table} (source_message_id, drive_file_id, closed_by, created_at, closed_at, changed_fields) values ('m', 'f', $1, $2, $3, $4::jsonb)` : `insert into ${table} (${key}, run_id, run_started_at, closed_by, created_at, closed_at, changed_fields) values (gen_random_uuid()::text, 'r', now(), $1, $2, $3, $4::jsonb)`, [by, created, closed, changed], ); // вчера (16.11 по Кипру): 3 закрытия, 2 из них без правок, среднее время (2 + 4 + 1) / 3 = 2 ч 20 мин await hist("acc_invoices_review_history", "id", "Anastasia", "2026-11-16T08:00:00Z", "2026-11-16T10:00:00Z", "{}"); await hist("acc_invoices_review_history", "id", "Anastasia", "2026-11-16T06:00:00Z", "2026-11-16T10:00:00Z", '{"amount":{"old":1,"new":2}}'); await hist("acc_categorization_review_history", "feed_txn_id", "Yulia", "2026-11-16T09:00:00Z", "2026-11-16T10:00:00Z", null); // не вчера await hist("acc_invoices_review_history", "id", "Anastasia", "2026-11-14T08:00:00Z", "2026-11-15T10:00:00Z", "{}"); await hist("acc_invoices_review_history", "id", "Anastasia", "2026-11-17T08:00:00Z", "2026-11-17T10:00:00Z", "{}"); } it("сводка на заготовленных данных: числа и формулировки", async () => { await seedSummary(); const text = await buildDailySummary(db.pool, NOW, TZ, { mathesarUrl: "https://mathesar.example/queue", bankFeedUrl: "https://qbo.example/feed" }); expect(text).toContain("Сводка бухгалтерского помощника на 17.11.2026"); expect(text).toContain("В очереди ручного разбора: 6 задач"); expect(text).toContain("- инвойсы: 2, из них с проблемой: 1"); expect(text).toContain("- категоризация: 3, из них с проблемой: 2"); expect(text).toContain("- сертификаты: 1, из них с проблемой: 1"); expect(text).toContain("бухгалтер (accountant) - 5"); expect(text).toContain("Анастасия (cfo) - 1"); expect(text).toContain("Отложено до даты повторного показа: 1"); expect(text).toContain("Категоризация: ждёт документ - 1; подозрение на дубль - 1; нужен человек - 0"); expect(text).toContain("https://qbo.example/feed"); expect(text).toContain("Очередь в Mathesar: https://mathesar.example/queue"); expect(text).toContain("За вчера (16.11.2026):"); expect(text).toContain("закрыто: 3 задачи (Anastasia - 2, Yulia - 1)"); expect(text).toContain("закрыто без правок автомата: 2 из 3 (67%)"); expect(text).toContain("среднее время от создания задачи до закрытия: 2 ч 20 мин"); expect(text).toContain("ждут больше 2 рабочих дней: 1"); }); it("сводка на пустых данных не падает", async () => { const text = await buildDailySummary(db.pool, NOW, TZ); expect(text).toContain("В очереди ручного разбора: 0 задач"); expect(text).toContain("закрытых задач не было"); expect(text).toContain("ждут больше 2 рабочих дней: 0"); expect(text).not.toContain("Mathesar"); }); it("twoWorkdaysAgo пропускает выходные", () => { expect(twoWorkdaysAgo(new Date("2026-11-17T15:00:00Z"), TZ).toISOString()).toBe("2026-11-13T15:00:00.000Z"); // вт -> пт expect(twoWorkdaysAgo(new Date("2026-11-18T15:00:00Z"), TZ).toISOString()).toBe("2026-11-16T15:00:00.000Z"); // ср -> пн }); it("postDailySummary отправляет сводку в канал; SlackPoster вызывает chat.postMessage", async () => { const calls: { url: string; init: RequestInit }[] = []; const fakeFetch = (async (u: string, init: RequestInit) => { calls.push({ url: u, init }); return new Response(JSON.stringify({ ok: true }), { status: 200 }); }) as unknown as typeof fetch; const slack = createSlackPoster({ botToken: "xoxb-test", fetchImpl: fakeFetch }); const text = await postDailySummary({ pool: db.pool, slack, channelId: "C123", now: () => NOW, tz: TZ }); expect(calls).toHaveLength(1); expect(calls[0].url).toBe("https://slack.com/api/chat.postMessage"); expect((calls[0].init.headers as Record).authorization).toBe("Bearer xoxb-test"); expect(JSON.parse(calls[0].init.body as string)).toEqual({ channel: "C123", text }); const bad = createSlackPoster({ botToken: "x", fetchImpl: (async () => new Response(JSON.stringify({ ok: false, error: "channel_not_found" }))) as unknown as typeof fetch }); await expect(bad.post("C", "t")).rejects.toThrow("channel_not_found"); }); });