import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { createTestDb, testDatabaseUrl, type TestDb } from "khb_common"; import { buildHistoryReport, runHistoryWeekly } from "./history-report.js"; const url = testDatabaseUrl(); const d = url ? describe : describe.skip; d("разбор истории правок (временная БД)", () => { let db: TestDb; const NOW = new Date("2026-11-23T12:00:00Z"); const ago = (days: number): Date => new Date(NOW.getTime() - days * 86_400_000); const inv = async (vendor: string, project: string | null, changed: Record, closedDaysAgo = 1) => db.pool.query( `insert into acc_invoices_review_history (id, source_message_id, drive_file_id, vendor_name, project_customer_id, closed_at, changed_fields) values (gen_random_uuid(), 'm', 'f', $1, $2, $3, $4::jsonb)`, [vendor, project, ago(closedDaysAgo), JSON.stringify(changed)], ); const cat = async (feed: string, suggestion: unknown, changed: Record) => db.pool.query( `insert into acc_categorization_review_history (feed_txn_id, run_id, run_started_at, suggestion, closed_at, changed_fields) values ($1, 'run', now(), $2::jsonb, $3, $4::jsonb)`, [feed, JSON.stringify(suggestion), ago(1), JSON.stringify(changed)], ); beforeAll(async () => { db = await createTestDb(url!); }); afterAll(async () => { await db?.drop(); }); beforeEach(async () => { await db.pool.query("truncate acc_invoices_review_history, acc_categorization_review_history, acc_certificates_review_history, qbo_customer"); }); it("пустая неделя: короткий отчёт без анализа", async () => { const r = await buildHistoryReport(db.pool, NOW); expect(r.text).toContain("анализировать нечего"); expect(r.stats.every((x) => x.total === 0)).toBe(true); }); it("доли без изменений, поля, вендоры, проекты и кандидаты в правила; записи старше недели не учитываются", async () => { await db.pool.query("insert into qbo_customer (realm_id, id, display_name, is_job, raw) values ('r','C1','734 Placido Ave',true,'{}')"); for (let i = 0; i < 3; i++) await inv("ACME Plumbing", "C1", { project_customer_id: { old: null, new: "C7" } }); await inv("ACME Plumbing", "C1", { amount: { old: 1, new: 2 } }); await inv("Twin Co", "C2", {}); await inv("Twin Co", "C2", {}); await inv("Old Co", "C9", { amount: { old: 1, new: 2 } }, 9); // за пределами недели // категоризация: люди трижды меняют счёт у Home Depot с Materials на Tools for (let i = 0; i < 3; i++) { await cat(`f${i}`, { vendor: "Home Depot", account: "Tools" }, { suggestion: { old: { vendor: "Home Depot", account: "Materials" }, new: { vendor: "Home Depot", account: "Tools" } } }); } await cat("f9", { vendor: "Lowes", account: "A" }, {}); await db.pool.query( `insert into acc_certificates_review_history (id, vendor_name, closed_at, changed_fields) values (gen_random_uuid(), 'Cert Co', $1, '{"expires_on":{"old":null,"new":"2027-01-01"}}'::jsonb)`, [ago(2)], ); const r = await buildHistoryReport(db.pool, NOW); const [invS, catS, certS] = r.stats; expect(invS).toMatchObject({ total: 6, unchanged: 2 }); expect(invS!.fields[0]).toEqual({ field: "project_customer_id", n: 3 }); expect(invS!.vendors[0]).toEqual({ vendor: "ACME Plumbing", changed: 4, total: 4 }); expect(invS!.projects[0]).toEqual({ project: "734 Placido Ave", changed: 4 }); expect(invS!.candidates).toEqual([{ n: 3, text: "у «ACME Plumbing» поле project_customer_id исправляют на «C7» (3 раз): правило распознавания" }]); expect(catS).toMatchObject({ total: 4, unchanged: 1 }); expect(catS!.candidates[0]).toMatchObject({ n: 3 }); expect(catS!.candidates[0]!.text).toContain("у «Home Depot» автомат ставит счёт «Materials», люди исправляют на «Tools»"); expect(certS).toMatchObject({ total: 1, unchanged: 0 }); // общий текст expect(r.text).toContain("Закрыто записей: 11, принято без изменений: 3 (27%)."); expect(r.text).toContain("Инвойсы: закрыто 6, без изменений 2 (33%)."); expect(r.text).toContain("Чаще всего правят поля: project_customer_id (3), amount (1)."); expect(r.text).toContain("Кандидаты в правила"); expect(r.text).not.toContain("Old Co"); }); it("нет повторов - кандидатов в правила нет", async () => { await inv("A", "C1", { amount: { old: 1, new: 2 } }); await inv("B", "C1", { amount: { old: 1, new: 2 } }); const r = await buildHistoryReport(db.pool, NOW); expect(r.text).toContain("Кандидатов в правила нет"); }); it("отчёт уходит в Slack Анастасии", async () => { await inv("A", "C1", {}); const posted: { channel: string; text: string }[] = []; const res = await runHistoryWeekly({ pool: db.pool, channelId: "CANA", now: () => NOW, slack: { post: async (channel, text) => { posted.push({ channel, text }); } } }); expect(res).toEqual({ sent: true, total: 1, candidates: 0 }); expect(posted).toHaveLength(1); expect(posted[0]!.channel).toBe("CANA"); expect(posted[0]!.text).toContain("Разбор истории правок за неделю 16.11.2026 - 23.11.2026"); }); });