import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { createLogger, createTestDb, testDatabaseUrl, type TestDb } from "khb_common"; import { runFinalize } from "./finalize.js"; import { ReviewTools } from "./mcp.js"; import { allowWithoutReceipt, buildWeeklyReport, runReceiptSearch, runReceiptWeeklyReport, type SearchOptions } from "./receipt-search.js"; import { FakeSlack } from "./fake-slack.js"; import { workdaysBetween } from "./workdays.js"; const url = testDatabaseUrl(); const d = url ? describe : describe.skip; const log = createLogger("test", "silent"); describe("рабочие дни", () => { it("считаются после даты from до to включительно, без выходных и праздников", () => { const fri = new Date("2026-11-13T12:00:00Z"); expect(workdaysBetween(fri, new Date("2026-11-13T20:00:00Z"), "UTC")).toBe(0); expect(workdaysBetween(fri, new Date("2026-11-16T09:00:00Z"), "UTC")).toBe(1); // сб, вс не считаются expect(workdaysBetween(fri, new Date("2026-11-17T09:00:00Z"), "UTC")).toBe(2); expect(workdaysBetween(fri, new Date("2026-11-17T09:00:00Z"), "UTC", new Set(["2026-11-16"]))).toBe(1); expect(workdaysBetween(new Date("2026-11-17T09:00:00Z"), fri, "UTC")).toBe(0); }); }); const ids = { alena: "00000000-0000-0000-0000-0000000000a1", artur: "00000000-0000-0000-0000-0000000000a2", nastia: "00000000-0000-0000-0000-0000000000a3", yulia: "00000000-0000-0000-0000-0000000000a4", dmitry: "00000000-0000-0000-0000-0000000000a5", pm: "00000000-0000-0000-0000-0000000000a6", }; const OPTS: SearchOptions = { tz: "UTC", graceWorkdays: 2, escalationWorkdays: [2, 4, 6, 10], subscriptionVendors: ["linode", "quickbooks"], qboBankingUrl: "https://qbo.example/banking", }; d("поиск чека и проверка расхода без чека (временная БД, фейк Slack)", () => { let db: TestDb; let slack: FakeSlack; const q = async (sql: string, p: unknown[] = []) => (await db.pool.query(sql, p)).rows; const search = (now: string, over: Partial = {}) => runReceiptSearch({ pool: db.pool, slack, now: () => new Date(now), log, nonWorkdays: async () => new Set(), options: { ...OPTS, ...over } }); /** Операция, ждущая документ: строка категоризации (создана at), данные операции в acc_feed_txn. */ async function waiting(id: string, at: string, o: { amount?: number; vendor?: string; card?: string | null; project?: string | null; highlight?: string } = {}): Promise { await q("insert into acc_feed_txn (feed_txn_id, txn_date, amount, vendor_name, card_or_account) values ($1, '2026-11-09', $2, $3, $4)", [id, o.amount ?? 250, o.vendor ?? "Home Depot", o.card === undefined ? "4242" : o.card]); await q( `insert into acc_categorization_review (feed_txn_id, run_id, run_started_at, suggestion, problem_highlight, created_at) values ($1,'r',$2,$3::jsonb,$4,$2)`, [id, at, o.project ? JSON.stringify({ project_customer_id: o.project }) : null, o.highlight ?? "ждёт документ"], ); } beforeAll(async () => { db = await createTestDb(url!); }); afterAll(async () => { await db?.drop(); }); beforeEach(async () => { slack = new FakeSlack(); await q("truncate qbo_purchase, qbo_purchase_line, acc_receipts, acc_receipt_search, acc_feed_txn, acc_manual_review, acc_categorization_review, acc_categorization_review_original, acc_categorization_review_history, acc_card_holders, qbo_customer, assistant_project, construction_manager, person cascade"); await q(`insert into person (id, display_name, slack_user_id, role_code) values ('${ids.alena}', 'Алёна', 'UALENA', 'employee'), ('${ids.artur}', 'Артур', 'UARTUR', 'ceo'), ('${ids.nastia}', 'Анастасия', 'UNASTIA', 'cfo'), ('${ids.yulia}', 'Юля', 'UYULIA', 'accountant'), ('${ids.dmitry}', 'Дмитрий', 'UDMITRY', 'owner'), ('${ids.pm}', 'Менеджер Пётр', 'UPM', 'construction_manager')`); await q("insert into acc_card_holders (card_or_account, person_id) values ('4242', $1)", [ids.alena]); }); it("заведение: старше 2 рабочих дней, подписки и свежие пропускаются; личное сообщение с вопросом и подсказкой", async () => { // пятница 13.11 утром: создана во вторник 10.11 (3 раб. дня), в среду 11.11 (2 раб. дня), в четверг 12.11 (1) await waiting("OLD", "2026-11-10T10:00:00Z", { amount: 250.5 }); await waiting("EDGE", "2026-11-11T10:00:00Z", { vendor: "Lowes" }); await waiting("FRESH", "2026-11-12T10:00:00Z"); await waiting("SUB", "2026-11-10T10:00:00Z", { vendor: "Linode LLC" }); await waiting("OTHER", "2026-11-10T10:00:00Z", { highlight: "подозрение на дубль" }); const r = await search("2026-11-13T07:00:00Z"); expect(r).toMatchObject({ created: 2, asked: 2, subscriptions: 1, noResponsible: 0, errors: 0 }); const rows = await q("select feed_txn_id, responsible_person_id, escalation_level, last_asked_at, asks from acc_receipt_search order by feed_txn_id"); expect(rows.map((x) => x.feed_txn_id)).toEqual(["EDGE", "OLD"]); expect(rows[1]).toMatchObject({ responsible_person_id: ids.alena, escalation_level: 0 }); expect(rows[1].asks).toHaveLength(1); expect(slack.posted[1]!.channel).toBe("DUALENA"); const text = slack.posted.map((p) => p.text).find((t) => t.includes("$250.50"))!; expect(text).toContain("Home Depot"); expect(text).toContain("карта ••4242"); expect(text).toContain("https://qbo.example/banking"); expect(text).toContain("id операции OLD"); // общая ссылка: операция описана id, суммой и датой expect(text).toContain("2026-11-09"); // повторный запуск в тот же день ничего не дублирует const again = await search("2026-11-13T07:30:00Z"); expect(again).toMatchObject({ created: 0, asked: 0 }); expect(slack.posted).toHaveLength(2); }); it("подсказка проекта по истории вендора", async () => { await q("insert into qbo_purchase (realm_id, id, entity_name, raw) select 'r', 'P'||g, 'Home Depot', '{}' from generate_series(1,4) g"); await q("insert into qbo_purchase_line (realm_id, purchase_id, line_no, customer_id, customer_name) select 'r', 'P'||g, 1, 'C1', '734 Placido Ave' from generate_series(1,4) g"); await waiting("OLD", "2026-11-10T10:00:00Z"); await search("2026-11-13T07:00:00Z"); expect(slack.posted[0]!.text).toContain("обычно относится к проекту 734 Placido Ave"); }); it("ответственный не найден (справочники пусты): задача Юле, сразу уровень 3", async () => { await q("truncate acc_card_holders"); await waiting("OLD", "2026-11-10T10:00:00Z", { card: null }); const r = await search("2026-11-13T07:00:00Z"); expect(r).toMatchObject({ created: 1, noResponsible: 1, asked: 0 }); expect(slack.posted).toHaveLength(0); const [s] = await q("select id, escalation_level, responsible_person_id from acc_receipt_search"); expect(s).toMatchObject({ escalation_level: 3, responsible_person_id: null }); const [t] = await q("select kind, assignee_role, problem_highlight from acc_manual_review where ref_id = $1", [s.id]); expect(t).toMatchObject({ kind: "receipt_search", assignee_role: "accountant" }); expect(t.problem_highlight).toContain("Ответственный не найден"); }); it("менеджер проекта из JobTread - ответственный, если держателя нет", async () => { await q("truncate acc_card_holders"); await q("insert into qbo_customer (realm_id, id, display_name, is_job, raw) values ('r','C1','734 Placido Ave',true,'{}')"); await q("insert into sync_source (prefix, name) values ('jt', 'JobTread') on conflict do nothing"); await q("insert into sync_snapshot (started_at, source_prefix, requested_tables) values ('2026-11-01T00:00:00Z', 'jt', '{}') on conflict do nothing"); await q("insert into jt_job (id, name, snapshot_ts) values ('job-pm', '734 Placido Avenue', '2026-11-01T00:00:00Z') on conflict (id) do update set name = excluded.name"); await q("insert into construction_manager (person_id) values ($1)", [ids.pm]); await q("insert into assistant_project (jt_job_id, manager_person_id) values ('job-pm', $1) on conflict (jt_job_id) do update set manager_person_id = excluded.manager_person_id", [ids.pm]); await waiting("OLD", "2026-11-10T10:00:00Z", { card: "9999", project: "C1" }); await search("2026-11-13T07:00:00Z"); expect((await q("select responsible_person_id from acc_receipt_search"))[0].responsible_person_id).toBe(ids.pm); expect(slack.posted[0]!.channel).toBe("DUPM"); }); it("эскалация по цепочке: напоминание +2, руководитель +4, Юля +6, Анастасия +10 рабочих дней", async () => { await waiting("OLD", "2026-11-10T10:00:00Z"); await search("2026-11-13T07:00:00Z"); // пятница: первый вопрос const sid = (await q("select id from acc_receipt_search"))[0].id as string; const level = async () => (await q("select escalation_level from acc_receipt_search"))[0].escalation_level; expect((await search("2026-11-16T07:00:00Z")).escalated).toEqual([0, 0, 0, 0]); // 1 раб. день (понедельник) expect(await level()).toBe(0); // вторник 17.11: 2 раб. дня - напоминание ответственному в ту же ветку const before = slack.posted.length; expect((await search("2026-11-17T07:00:00Z")).escalated).toEqual([1, 0, 0, 0]); expect(await level()).toBe(1); expect(slack.posted).toHaveLength(before + 1); expect(slack.posted[before]!.text).toContain("Напоминание"); expect(slack.posted[before]!.threadTs).toBe(slack.posted[0]!.ts); // тот же день: повторно не напоминает expect((await search("2026-11-17T09:00:00Z")).escalated).toEqual([0, 0, 0, 0]); // четверг 19.11: 4 раб. дня - руководитель (у сотрудника это Артур), копия ответственному const n2 = slack.posted.length; expect((await search("2026-11-19T07:00:00Z")).escalated).toEqual([0, 1, 0, 0]); expect(slack.posted[n2]).toMatchObject({ channel: "DUARTUR" }); expect(slack.posted[n2]!.text).toContain("Алёна"); expect(slack.posted[n2 + 1]!.text).toContain("передан"); expect(slack.posted[n2 + 1]!.channel).toBe("DUALENA"); expect((await q("select asks from acc_receipt_search"))[0].asks).toHaveLength(2); // понедельник 23.11: 6 раб. дней - задача Юле expect((await search("2026-11-23T07:00:00Z")).escalated).toEqual([0, 0, 1, 0]); expect((await q("select assignee_role, kind from acc_manual_review where ref_id = $1", [sid]))[0]).toMatchObject({ assignee_role: "accountant", kind: "receipt_search" }); // пятница 27.11: 10 раб. дней - Анастасия expect((await search("2026-11-27T07:00:00Z")).escalated).toEqual([0, 0, 0, 1]); expect((await q("select assignee_role from acc_manual_review where ref_id = $1", [sid]))[0].assignee_role).toBe("cfo"); expect(await level()).toBe(4); // дальше подниматься некуда expect((await search("2026-12-01T07:00:00Z")).escalated).toEqual([0, 0, 0, 0]); }); it("праздник из calendar_day не считается рабочим днём", async () => { await waiting("OLD", "2026-11-10T10:00:00Z"); await search("2026-11-13T07:00:00Z"); const holidays = async () => new Set(["2026-11-16"]); const r = await runReceiptSearch({ pool: db.pool, slack, now: () => new Date("2026-11-17T07:00:00Z"), log, nonWorkdays: holidays, options: OPTS }); expect(r.escalated).toEqual([0, 0, 0, 0]); // понедельник праздник: только 1 рабочий день }); it("ответ сотрудника останавливает эскалацию; сбой Slack при первом вопросе повторяется на следующий день", async () => { await waiting("OLD", "2026-11-10T10:00:00Z"); const failing = new FakeSlack(); failing.postMessage = async () => { throw new Error("slack down"); }; const r1 = await runReceiptSearch({ pool: db.pool, slack: failing, now: () => new Date("2026-11-13T07:00:00Z"), log, nonWorkdays: async () => new Set(), options: OPTS }); expect(r1).toMatchObject({ created: 1, asked: 0 }); expect((await q("select last_asked_at from acc_receipt_search"))[0].last_asked_at).toBeNull(); const r2 = await search("2026-11-14T07:00:00Z"); expect(r2.asked).toBe(1); await q("update acc_receipt_search set answer = 'personal'"); expect((await search("2026-11-27T07:00:00Z")).escalated).toEqual([0, 0, 0, 0]); }); it("недельный отчёт Анастасии: по сотрудникам, возраст, сумма, уровень", async () => { await q("insert into acc_receipt_search (feed_txn_id, responsible_person_id, amount, vendor_name, escalation_level, created_at) values ('X1', $1, 100, 'Shell', 2, '2026-11-01T00:00:00Z'), ('X2', $1, 50.5, 'Lowes', 0, '2026-11-10T00:00:00Z'), ('X3', null, 10, 'Misc', 3, '2026-11-12T00:00:00Z')", [ids.alena]); await q("insert into acc_receipt_search (feed_txn_id, responsible_person_id, amount, closed_at) values ('X4', $1, 999, now())", [ids.alena]); const text = await buildWeeklyReport(db.pool, new Date("2026-11-15T00:00:00Z")); expect(text).toContain("3 шт., $160.50"); expect(text).toContain("Алёна: 2 шт., $150.50"); expect(text).toContain("$100.00, Shell, 14 дн., уровень 2 (руководитель)"); expect(text).toContain("ответственный не найден: 1 шт."); expect(text).not.toContain("999"); const sent = await runReceiptWeeklyReport({ pool: db.pool, slack, now: () => new Date("2026-11-15T00:00:00Z") }); expect(sent).toMatchObject({ sent: true, to: "UNASTIA", open: 3 }); expect(slack.posted[0]!.channel).toBe("DUNASTIA"); await q("truncate acc_receipt_search"); expect(await buildWeeklyReport(db.pool, new Date())).toContain("нет"); // непринесённых чеков нет - отчёт не отправляется const n = slack.posted.length; expect(await runReceiptWeeklyReport({ pool: db.pool, slack, now: () => new Date("2026-11-15T00:00:00Z") })).toEqual({ sent: false, to: null, open: 0 }); expect(slack.posted).toHaveLength(n); }); it("ссылка на конкретную операцию: шаблон {feed_txn_id} в qboBankingUrl", async () => { await waiting("OLD", "2026-11-10T10:00:00Z"); await search("2026-11-13T07:00:00Z", { qboBankingUrl: "https://qbo.example/banking?txn={feed_txn_id}" }); expect(slack.posted[0]!.text).toContain("Операция в QuickBooks: https://qbo.example/banking?txn=OLD"); expect(slack.posted[0]!.text).not.toContain("id операции"); }); it("у руководителя нет Slack: уровень растёт не молча - задача Юле «нет Slack у ...»", async () => { await q("update person set slack_user_id = null where id = $1", [ids.artur]); await waiting("OLD", "2026-11-10T10:00:00Z"); await search("2026-11-13T07:00:00Z"); const sid = (await q("select id from acc_receipt_search"))[0].id as string; await search("2026-11-17T07:00:00Z"); const n = slack.posted.length; expect((await search("2026-11-19T07:00:00Z")).escalated).toEqual([0, 1, 0, 0]); expect(slack.posted).toHaveLength(n); // писать некому const [task] = await q("select assignee_role, problem_highlight from acc_manual_review where ref_id = $1", [sid]); expect(task.assignee_role).toBe("accountant"); expect(task.problem_highlight).toContain("нет Slack у Артур"); }); describe("расход без чека (шаг 8) при закрытии категоризации", () => { const fin = () => runFinalize({ pool: db.pool, delaySeconds: 0, now: () => new Date(Date.now() + 3600_000), notify: () => {} }); const close = async (id: string) => { await q("update acc_categorization_review set done = true, done_by = 'Юля' where feed_txn_id = $1", [id]); return fin(); }; const hist = async (id: string) => (await q("select 1 from acc_categorization_review_history where feed_txn_id = $1", [id])).length; it("больше $500 без чека не закрывается, даже с согласием; с чеком, инвойсом и неизвестной суммой - закрывается", async () => { await waiting("BIG", "2026-11-10T10:00:00Z", { amount: 800 }); const r = await close("BIG"); expect(r.rejected[0]?.reason).toContain("больше $500.00"); expect(await hist("BIG")).toBe(0); expect((await q("select done from acc_categorization_review where feed_txn_id = 'BIG'"))[0].done).toBe(false); // чек привязан await q("insert into acc_receipts (drive_file_id, feed_txn_id, amount) values ('f', 'BIG', 800)"); expect((await close("BIG")).finalized.categorization).toBe(1); // инвойс указан в предложении await waiting("INV", "2026-11-10T10:00:00Z", { amount: 900 }); await q("update acc_categorization_review set suggestion = '{\"invoice_ids\":[\"i1\"]}' where feed_txn_id = 'INV'"); expect((await close("INV")).finalized.categorization).toBe(1); // операция без проблемы «ждёт документ» не проверяется await waiting("PLAIN", "2026-11-10T10:00:00Z", { amount: 900, highlight: "нужен человек" }); expect((await close("PLAIN")).finalized.categorization).toBe(1); // сумма неизвестна: проверить лимит нечем await q("insert into acc_categorization_review (feed_txn_id, run_id, run_started_at, problem_highlight) values ('NOAMT','r',now(),'ждёт документ')"); expect((await close("NOAMT")).finalized.categorization).toBe(1); }); it("до $500: только с согласия Анастасии (acc_receipt_allow_without); поиск закрывается после проводки", async () => { await waiting("MID", "2026-11-10T10:00:00Z", { amount: 300 }); await search("2026-11-13T07:00:00Z"); const r = await close("MID"); expect(r.rejected[0]?.reason).toContain("согласия Анастасии"); const tools = new ReviewTools({ pool: db.pool, settings: { reviewers: [{ personId: ids.nastia, roles: ["cfo"] }, { personId: ids.yulia, roles: ["accountant"] }] } }); const task = (await q("select id from acc_manual_review where ref_table = 'acc_categorization_review' and ref_id = 'MID'"))[0].id as string; await expect(tools.call(ids.yulia, "acc_receipt_allow_without", { id: task, reason: "потерян" })).rejects.toThrow(/cfo/); await expect(tools.call(ids.nastia, "acc_receipt_allow_without", { id: task, reason: " " })).rejects.toThrow(/причина/); const ok = (await tools.call(ids.nastia, "acc_receipt_allow_without", { id: task, reason: "вендор закрылся" })) as { ok: boolean; amount: number }; expect(ok).toMatchObject({ ok: true, amount: 300 }); expect((await q("select approved_without_receipt_by, approved_reason from acc_receipt_search"))[0]).toMatchObject({ approved_without_receipt_by: ids.nastia, approved_reason: "вендор закрылся" }); expect((await fin()).finalized.categorization).toBe(0); // done снят отклонением: Юля отмечает заново expect((await close("MID")).finalized.categorization).toBe(1); // следующий запуск поиска чека закрывает поиск: операция проведена без чека const r2 = await search("2026-11-14T07:00:00Z"); expect(r2.closed).toBe(1); expect((await q("select closed_at, resolution from acc_receipt_search"))[0].resolution).toBe("проведено без чека (вендор закрылся)"); expect(await q("select 1 from acc_manual_review where ref_table = 'acc_receipt_search'")).toHaveLength(0); }); it("allowWithoutReceipt: лимит, неизвестная операция", async () => { await q("insert into acc_receipt_search (feed_txn_id, amount) values ('S1', 600)"); await expect(allowWithoutReceipt(db.pool, "x", "S1", "причина", 500, new Date())).rejects.toThrow(/больше лимита/); await expect(allowWithoutReceipt(db.pool, "x", "NOPE", "причина", 500, new Date())).rejects.toThrow(/не заведён/); await expect(allowWithoutReceipt(db.pool, "x", "S1", "причина", 1000, new Date())).resolves.toEqual({ amount: 600 }); }); }); });