import type { FastifyInstance } from "fastify"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { createTestDb, testDatabaseUrl, type TestDb } from "khb_common"; import { buildApi } from "./http-api.js"; import { ReviewTools } from "./mcp.js"; import { runFraudWeekly } from "./chargeback.js"; import { STAGE2_TOOLS } from "./stage2-tool-defs.js"; const url = testDatabaseUrl(); const d = url ? describe : describe.skip; d("chargeback и fraud (временная БД)", () => { let db: TestDb; let app: FastifyInstance; let tools: ReviewTools; let manager: string, yulia: string, anastasia: string; const NOW = new Date("2026-11-23T12:00:00Z"); const auth = { authorization: "Bearer svc-token" }; let contractA: string; let contractOther: string; const post = async (path: string, payload: Record) => { const r = await app.inject({ method: "POST", url: path, headers: auth, payload }); return { status: r.statusCode, body: r.json() as Record }; }; const call = (who: string, name: string, args: Record = {}) => tools.call(who, name, args); const errOf = async (p: Promise): Promise => { try { await p; } catch (e) { return (e as Error).message; } return "NO ERROR"; }; const start = (over: Record = {}) => post("/chargeback/start", { daily_log_id: "DL1", daily_log_url: "https://app.jobtread.com/dl/1", job_id: "J1", vendor_name: "Window Co LLC", description: "окна протекают", reported_by: manager, ...over }); const task = async (cbId: string) => (await db.pool.query("select id, kind, assignee_role, problem_highlight from acc_manual_review where ref_id = $1", [cbId])).rows[0]; const contract = async (id = contractA) => (await db.pool.query("select retained_amount::float8 as r, paid_amount::float8 as p, total_amount::float8 as t from acc_contracts where id = $1", [id])).rows[0]; const invoice = async (amount: number, project = "C1") => (await db.pool.query( `insert into acc_invoices (id, source_message_id, drive_file_id, vendor_name, invoice_date, amount, project_customer_id) values (gen_random_uuid(),'m','f','Fix Co','2026-11-10',$1,$2) returning id`, [amount, project])).rows[0].id as string; beforeAll(async () => { db = await createTestDb(url!); const mk = async (name: string) => (await db.pool.query("insert into person (display_name) values ($1) returning id", [name])).rows[0].id as string; manager = await mk("Менеджер"); yulia = await mk("Юля"); anastasia = await mk("Анастасия"); const settings = { http: { host: "127.0.0.1", port: 0, token: "svc-token" }, reviewers: [{ personId: yulia, roles: ["accountant" as const] }, { personId: anastasia, roles: ["accountant" as const, "cfo" as const] }], mcp: { enabled: false, staticTokens: [] }, }; app = buildApi({ pool: db.pool, settings, jobs: { "invoices-mail": async () => 1, finalize: async () => 1, categorize: async () => 1, summary: async () => 1 } }); tools = new ReviewTools({ pool: db.pool, settings, now: () => NOW }); }); afterAll(async () => { await app?.close(); await db?.drop(); }); beforeEach(async () => { await db.pool.query("truncate acc_chargeback, acc_manual_review, acc_invoices, acc_contracts, acc_categorization_review, acc_categorization_review_original, acc_categorization_review_history, acc_receipts cascade"); contractA = (await db.pool.query( "insert into acc_contracts (vendor_name, vendor_qbo_id, project_customer_id, jt_job_id, total_amount, paid_amount) values ('Window Co','V1','C1','J1',10000,2000) returning id")).rows[0].id; contractOther = (await db.pool.query( "insert into acc_contracts (vendor_name, project_customer_id, jt_job_id, total_amount) values ('Roof Co','C1','J1',5000) returning id")).rows[0].id; }); describe("ручки для ассистента менеджера", () => { it("закрыты токеном сервиса", async () => { for (const p of ["/chargeback/find", "/chargeback/start", "/chargeback/close", "/chargeback/add-log"]) { expect((await app.inject({ method: "POST", url: p, payload: {} })).statusCode).toBe(401); } }); it("start: строка claimed, контракт найден по проекту JobTread и подрядчику, задача cfo; повтор по daily_log_id не плодит дубль", async () => { const r = await start(); expect(r.status).toBe(200); expect(r.body.result).toBe("created"); const cb = r.body.chargeback; expect(cb).toMatchObject({ kind: "contract", status: "claimed", contract_id: contractA, defect_daily_log_id: "DL1", defect_description: "окна протекают", reported_by: manager, contract_vendor_name: "Window Co", contract_remaining: 8000 }); expect(await task(cb.id)).toMatchObject({ kind: "chargeback", assignee_role: "cfo" }); expect((await task(cb.id)).problem_highlight).toContain("окна протекают"); const again = await start({ description: "другое описание" }); expect(again.body).toMatchObject({ result: "existing", chargeback: { id: cb.id, defect_description: "окна протекают" } }); expect((await db.pool.query("select count(*)::int as n from acc_chargeback")).rows[0].n).toBe(1); expect((await db.pool.query("select count(*)::int as n from acc_manual_review")).rows[0].n).toBe(1); }); it("start: нет подходящего контракта - кандидаты; с contract_id создаётся; чужой контракт и неверные данные - 4xx", async () => { const r = await start({ vendor_name: "Plumbing Inc" }); expect(r.body.result).toBe("candidates"); expect(r.body.candidates.map((c: any) => c.vendor_name).sort()).toEqual(["Roof Co", "Window Co"]); expect((await db.pool.query("select count(*)::int as n from acc_chargeback")).rows[0].n).toBe(0); const ok = await start({ vendor_name: "Plumbing Inc", contract_id: contractOther }); expect(ok.body).toMatchObject({ result: "created", chargeback: { contract_id: contractOther } }); // неоднозначность: два контракта подрядчика на проекте await db.pool.query("insert into acc_contracts (vendor_name, project_customer_id, jt_job_id, total_amount, stage) values ('Roof Co','C1','J1',100,'phase 2')"); const amb = await start({ daily_log_id: "DL2", vendor_name: "Roof Co" }); expect(amb.body.result).toBe("candidates"); expect(amb.body.candidates).toHaveLength(2); expect((await start({ daily_log_id: "" })).status).toBe(400); expect((await start({ daily_log_id: "DL3", contract_id: "00000000-0000-0000-0000-000000000000" })).status).toBe(404); expect((await start({ daily_log_id: "DL4", reported_by: "00000000-0000-0000-0000-000000000000" })).status).toBe(400); expect((await start({ daily_log_id: "DL5", reported_by: "не uuid" })).status).toBe(400); }); it("close: строка closed с причиной «менеджер закрыл вопрос», задачи нет, повтор идемпотентен", async () => { const r = await post("/chargeback/close", { daily_log_id: "DL1", daily_log_url: "u", job_id: "J1", vendor_name: "Window Co", description: "x", reported_by: manager }); expect(r.body).toMatchObject({ result: "created", chargeback: { status: "closed", close_reason: "менеджер закрыл вопрос", kind: "contract" } }); expect(await task(r.body.chargeback.id)).toBeUndefined(); const again = await post("/chargeback/close", { daily_log_id: "DL1", job_id: "J1", vendor_name: "Window Co" }); expect(again.body.result).toBe("existing"); // а start по закрытому дефекту ничего не создаёт и не открывает заново const s = await start(); expect(s.body).toMatchObject({ result: "existing", chargeback: { status: "closed" } }); expect((await db.pool.query("select count(*)::int as n from acc_manual_review")).rows[0].n).toBe(0); }); it("find: по проекту и подрядчику, в том числе закрытые; add-log без дублей", async () => { expect((await post("/chargeback/find", { job_id: "J1", vendor_name: "Window Co" })).body.rows).toEqual([]); const cb = (await start()).body.chargeback; const closed = (await post("/chargeback/close", { daily_log_id: "DL2", job_id: "J1", vendor_name: "Roof Co" })).body.chargeback; const win = (await post("/chargeback/find", { job_id: "J1", vendor_name: "window co llc" })).body.rows; expect(win.map((x: any) => x.id)).toEqual([cb.id]); expect((await post("/chargeback/find", { job_id: "J1" })).body.rows).toHaveLength(2); expect((await post("/chargeback/find", { job_id: "J1", vendor_name: "Roof Co" })).body.rows[0]).toMatchObject({ id: closed.id, status: "closed" }); expect((await post("/chargeback/find", { job_id: "J1", daily_log_id: "DL1" })).body.rows).toHaveLength(1); expect((await post("/chargeback/find", { vendor_name: "x" })).status).toBe(400); const a1 = await post("/chargeback/add-log", { chargeback_id: cb.id, daily_log_url: "https://app.jobtread.com/dl/2" }); expect(a1.body).toMatchObject({ added: true, chargeback: { extra_daily_logs: ["https://app.jobtread.com/dl/2"] } }); const a2 = await post("/chargeback/add-log", { chargeback_id: cb.id, daily_log_url: "https://app.jobtread.com/dl/2" }); expect(a2.body.added).toBe(false); expect((await post("/chargeback/add-log", { chargeback_id: cb.id, daily_log_url: "https://app.jobtread.com/dl/1" })).body.added).toBe(false); // первый лог - не extra expect((await post("/chargeback/add-log", { chargeback_id: "00000000-0000-0000-0000-000000000000", daily_log_url: "u" })).status).toBe(404); }); }); describe("решения Юли и Анастасии (MCP) и пересчёт контракта", () => { it("полный путь: decide -> link_invoice -> confirm; удержание уменьшает остаток; закрытие при нулевом остатке", async () => { const cb = (await start()).body.chargeback; const id = cb.id as string; // права: решает только cfo expect(await errOf(call(yulia, "acc_chargeback_decide", { id, decision: "approve" }))).toContain("Нужна роль cfo"); expect(await errOf(call(manager, "acc_chargeback_list"))).toContain("Доступ запрещён"); // шаг 4 const dec = await call(anastasia, "acc_chargeback_decide", { id: id.slice(0, 8), decision: "approve", fix_vendor_name: "Fix Co" }); expect(dec.chargeback).toMatchObject({ status: "approved", decided_by: anastasia, fix_vendor_name: "Fix Co" }); expect(await task(id)).toMatchObject({ assignee_role: "accountant" }); expect(await errOf(call(anastasia, "acc_chargeback_decide", { id, decision: "reject" }))).toContain("уже принято"); // шаг 6: инвойс подрядчика Б const inv = await invoice(3000); expect(await errOf(call(yulia, "acc_chargeback_link_invoice", { id, invoice_id: await invoice(1000, "C2") }))).toContain("другому проекту"); expect(await errOf(call(yulia, "acc_chargeback_link_invoice", { id, invoice_id: inv, retained_amount: 3500 }))).toContain("больше суммы инвойса"); expect(await errOf(call(yulia, "acc_chargeback_link_invoice", { id, invoice_id: "00000000-0000-0000-0000-000000000000" }))).toContain("не найден"); const link = await call(yulia, "acc_chargeback_link_invoice", { id, invoice_id: inv }); expect(link.chargeback).toMatchObject({ status: "fix_invoiced", fix_invoice_id: inv, retained_amount: 3000 }); expect(await task(id)).toMatchObject({ assignee_role: "cfo" }); expect((await contract()).r).toBe(0); // пока не подтверждено - контракт не уменьшен // шаг 7-8 expect(await errOf(call(yulia, "acc_chargeback_confirm", { id }))).toContain("Нужна роль cfo"); const conf = await call(anastasia, "acc_chargeback_confirm", { id, retained_amount: 2800 }); expect(conf.chargeback).toMatchObject({ status: "applied", retained_amount: 2800, confirmed_by: anastasia, contract_retained: 2800, contract_remaining: 5200 }); expect(await contract()).toEqual({ r: 2800, p: 2000, t: 10000 }); expect(await task(id)).toMatchObject({ assignee_role: "accountant" }); // сообщить подрядчику А в JobTread // шаг 11: остаток по контракту const bal = (await call(yulia, "acc_contract_balance", { vendor_name: "window" })) as any; expect(bal.contracts[0]).toMatchObject({ total_amount: 10000, retained_amount: 2800, paid_amount: 2000, remaining: 5200 }); // очередь показывает дело chargeback const list = (await call(anastasia, "acc_review_list", { kind: "chargeback" })) as any; expect(list.tasks).toHaveLength(1); expect(list.tasks[0].review).toMatchObject({ id, status: "applied" }); const got = (await call(yulia, "acc_review_get", { id: (await task(id)).id })) as any; expect(got.review.status).toBe("applied"); expect(got.original).toBeNull(); expect(await errOf(call(yulia, "acc_review_done", { id: (await task(id)).id }))).toContain("acc_chargeback_"); // шаг 12: остаток исчерпан платежами -> строка закрывается автоматически, удержание остаётся учтённым await db.pool.query("update acc_contracts set paid_amount = 7200 where id = $1", [contractA]); const after = (await db.pool.query("select status, close_reason from acc_chargeback where id = $1", [id])).rows[0]; expect(after).toEqual({ status: "closed", close_reason: "остаток по контракту оплачен" }); expect((await contract()).r).toBe(2800); expect(await task(id)).toBeUndefined(); }); it("отклонение закрывает строку и не меняет контракт; ручное закрытие только cfo", async () => { const a = (await start()).body.chargeback.id as string; const rej = await call(anastasia, "acc_chargeback_decide", { id: a, decision: "reject", comment: "гарантия истекла" }); expect(rej.chargeback).toMatchObject({ status: "closed", close_reason: "отклонено: гарантия истекла", decided_by: anastasia }); expect(await task(a)).toBeUndefined(); expect((await contract()).r).toBe(0); const b = (await start({ daily_log_id: "DL9" })).body.chargeback.id as string; expect(await errOf(call(yulia, "acc_chargeback_close", { id: b, reason: "x" }))).toContain("Нужна роль cfo"); const closed = await call(anastasia, "acc_chargeback_close", { id: b, reason: "решили иначе" }); expect((closed.chargeback as any).status).toBe("closed"); expect(await errOf(call(anastasia, "acc_chargeback_close", { id: b, reason: "x" }))).toContain("уже закрыта"); }); it("несколько удержаний суммируются; статус вне applied не учитывается; ручная правка в Mathesar тоже пересчитывает", async () => { const mk = async (log: string, amount: number, status: string) => (await db.pool.query( `insert into acc_chargeback (kind, status, contract_id, defect_daily_log_id, retained_amount, confirmed_at) values ('contract', $1, $2, $3, $4, case when $1 in ('applied') then now() end) returning id`, [status, contractA, log, amount])).rows[0].id as string; const x = await mk("L1", 1000, "applied"); await mk("L2", 500, "applied"); await mk("L3", 700, "fix_invoiced"); expect((await contract()).r).toBe(1500); await db.pool.query("update acc_chargeback set retained_amount = 1200 where id = $1", [x]); expect((await contract()).r).toBe(1700); await db.pool.query("delete from acc_chargeback where id = $1", [x]); expect((await contract()).r).toBe(500); }); it("acc_chargeback_list: фильтры и закрытые", async () => { const a = (await start()).body.chargeback.id as string; await post("/chargeback/close", { daily_log_id: "DL2", job_id: "J1", vendor_name: "Roof Co" }); const open = (await call(yulia, "acc_chargeback_list")) as any; expect(open.rows.map((r: any) => r.id)).toEqual([a]); expect(((await call(yulia, "acc_chargeback_list", { include_closed: true })) as any).rows).toHaveLength(2); expect(((await call(yulia, "acc_chargeback_list", { project_customer_id: "C9" })) as any).rows).toHaveLength(0); expect(((await call(yulia, "acc_chargeback_list", { kind: "card_fraud" })) as any).rows).toHaveLength(0); expect(await errOf(call(yulia, "acc_chargeback_list", { kind: "zzz" }))).toContain("kind"); }); it("инструменты этапа 2 описаны и доступны через tools/list", async () => { const names = STAGE2_TOOLS.map((t) => t.name); expect(names).toEqual(expect.arrayContaining(["acc_chargeback_decide", "acc_chargeback_link_invoice", "acc_chargeback_confirm", "acc_fraud_create", "acc_certificate_request_approve"])); const { TOOLS } = await import("./mcp.js"); for (const n of names) expect(TOOLS.some((t) => t.name === n)).toBe(true); }); }); describe("fraud по карте", () => { const addOp = async (feed: string) => db.pool.query( `insert into acc_categorization_review (feed_txn_id, run_id, run_started_at, suggestion, confidence, problem_highlight) values ($1,'r',now(),'{"vendor":"Linode","amount":500}',60,'первая оплата вендору')`, [feed]); it("создаёт запись с комплектом: операция, чек или «чека нет»; повтор возвращает ту же; задача accountant", async () => { await addOp("F1"); const r = (await call(yulia, "acc_fraud_create", { feed_txn_id: "F1", reason: "чужое", bank: "Chase", file_by: "2026-11-30" })) as any; expect(r.created).toBe(true); expect(r.chargeback).toMatchObject({ kind: "card_fraud", status: "collecting", feed_txn_id: "F1", bank: "Chase", file_by: "2026-11-30", contract_id: null }); expect(r.chargeback.kit.operation.suggestion).toMatchObject({ vendor: "Linode" }); expect(r.chargeback.kit.receipt_note).toBe("чека нет"); expect(await task(r.chargeback.id)).toMatchObject({ kind: "chargeback", assignee_role: "accountant" }); const again = (await call(yulia, "acc_fraud_create", { feed_txn_id: "F1" })) as any; expect(again).toMatchObject({ created: false, chargeback: { id: r.chargeback.id } }); // с чеком await db.pool.query("insert into acc_receipts (drive_file_id, vendor_name, amount, feed_txn_id) values ('rcpt1','Zoom',500,'F2')"); const withReceipt = (await call(yulia, "acc_fraud_create", { feed_txn_id: "F2" })) as any; expect(withReceipt.chargeback.kit.receipt.url).toContain("rcpt1"); expect(withReceipt.chargeback.kit.receipt_note).toBeNull(); // через HTTP тоже const http = await post("/chargeback/fraud", { feed_txn_id: "F3", created_by: yulia }); expect(http.body).toMatchObject({ created: true, chargeback: { kind: "card_fraud", status: "collecting" } }); expect((await post("/chargeback/fraud", { feed_txn_id: "F4", created_by: "нет" })).status).toBe(400); }); it("статусы: collecting -> filed -> refunded -> closed; недопустимые переходы отклоняются; closed убирает задачу", async () => { const id = ((await call(yulia, "acc_fraud_create", { feed_txn_id: "F1" })) as any).chargeback.id as string; expect(await errOf(call(yulia, "acc_fraud_update", { id, status: "refunded" }))).toContain("можно перейти в: filed, closed"); const filed = (await call(yulia, "acc_fraud_update", { id, status: "filed", bank_decision: "заявка принята" })) as any; expect(filed.chargeback).toMatchObject({ status: "filed", bank_decision: "заявка принята" }); expect((await task(id)).problem_highlight).toContain("ждём решения банка"); const ref = (await call(yulia, "acc_fraud_update", { id, status: "refunded", bank_decision: "возврат 500" })) as any; expect(ref.chargeback.status).toBe("refunded"); expect((await task(id)).problem_highlight).toContain("банк вернул деньги"); await call(yulia, "acc_fraud_update", { id, status: "closed" }); expect(await task(id)).toBeUndefined(); expect(await errOf(call(yulia, "acc_fraud_update", { id, status: "filed" }))).toContain("строка закрыта"); // для chargeback к контракту инструмент fraud не подходит const cb = (await start()).body.chargeback.id as string; expect(await errOf(call(yulia, "acc_fraud_update", { id: cb, status: "filed" }))).toContain("не fraud"); }); it("после закрытия по той же операции можно завести новое дело", async () => { const a = ((await call(yulia, "acc_fraud_create", { feed_txn_id: "F1" })) as any).chargeback.id as string; await call(yulia, "acc_fraud_update", { id: a, status: "closed" }); const b = (await call(yulia, "acc_fraud_create", { feed_txn_id: "F1" })) as any; expect(b.created).toBe(true); expect(b.chargeback.id).not.toBe(a); }); it("недельное напоминание: незакрытые и сроки; без незакрытых ничего не шлёт", async () => { const posted: string[] = []; const slack = { post: async (_c: string, t: string) => { posted.push(t); } }; expect(await runFraudWeekly({ pool: db.pool, slack, channelId: "C", now: () => NOW })).toEqual({ sent: false, count: 0 }); const a = ((await call(yulia, "acc_fraud_create", { feed_txn_id: "F1", bank: "Chase", file_by: "2026-11-20" })) as any).chargeback.id as string; await call(yulia, "acc_fraud_create", { feed_txn_id: "F2", file_by: "2026-11-27" }); const c = ((await call(yulia, "acc_fraud_create", { feed_txn_id: "F3" })) as any).chargeback.id as string; await call(yulia, "acc_fraud_update", { id: c, status: "closed" }); const r = await runFraudWeekly({ pool: db.pool, slack, channelId: "C", now: () => NOW }); expect(r).toEqual({ sent: true, count: 2 }); expect(posted[0]).toContain("незакрытых случаев 2"); expect(posted[0]).toContain("операция F1 (Chase): собираем комплект, срок подачи 2026-11-20 ПРОСРОЧЕН на 3 дн."); expect(posted[0]).toContain("операция F2: собираем комплект, срок подачи 2026-11-27 (осталось 4 дн.)"); expect(posted[0]).not.toContain("F3"); void a; }); }); });