Files
khb_microservices/packages/khbuild_assistant_prep/src/chargeback/chargeback.test.ts
2026-11-23 20:00:33 +03:00

55 lines
4.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { describe, expect, it } from "vitest";
import { runKhbChargeback } from "../tools/khb-chargeback.js";
import { chargebackToken, checkChargebackAuth, forwardChargeback } from "./proxy.js";
import { loadPrompt } from "../agents/prompts.js";
const cfg = { url: "http://acc:8096/", token: "svc-token", secret: "0123456789abcdef0123" };
describe("chargeback: токен и передача в accounting_automation", () => {
it("токен привязан к менеджеру; чужой person id и чужой префикс (khb-mail) не проходят", () => {
const t = chargebackToken(cfg.secret, "m1");
expect(checkChargebackAuth(cfg.secret, "m1", `Bearer ${t}`)).toBe(true);
expect(checkChargebackAuth(cfg.secret, "m2", `Bearer ${t}`)).toBe(false);
expect(checkChargebackAuth(cfg.secret, "m1", undefined)).toBe(false);
});
it("start и close получают reported_by из токена, а не от агента; find и add-log - без подстановки", async () => {
const seen: { url: string; auth: string; body: Record<string, unknown> }[] = [];
const f = (async (url: string, init: RequestInit) => {
seen.push({ url, auth: String((init.headers as Record<string, string>).authorization), body: JSON.parse(String(init.body)) });
return new Response(JSON.stringify({ result: "created" }), { status: 200 });
}) as unknown as typeof fetch;
await forwardChargeback(cfg, "start", "mgr-1", { daily_log_id: "d1", reported_by: "someone-else" }, f);
await forwardChargeback(cfg, "close", "mgr-1", { daily_log_id: "d1" }, f);
await forwardChargeback(cfg, "find", "mgr-1", { job_id: "j" }, f);
expect(seen[0]).toMatchObject({ url: "http://acc:8096/chargeback/start", auth: "Bearer svc-token", body: { reported_by: "mgr-1" } });
expect(seen[1]!.body.reported_by).toBe("mgr-1");
expect(seen[2]!.body).toEqual({ job_id: "j" });
expect((await forwardChargeback(cfg, "fraud", "mgr-1", {}, f)).status).toBe(404); // fraud агенту менеджера не отдаётся
});
it("команда khb-chargeback: параметры -> тело, ошибка сервиса -> код 1", async () => {
let sent: { url: string; body: unknown } | null = null;
const env = { KHB_CB_URL: "http://svc", KHB_CB_TOKEN: "t", KHB_CB_CALLER: "m1" };
const out: string[] = [];
const err: string[] = [];
const ok = (async (url: string, init: RequestInit) => ((sent = { url, body: JSON.parse(String(init.body)) }), new Response("{\"ok\":1}", { status: 200 }))) as unknown as typeof fetch;
expect(await runKhbChargeback(["start", "--daily-log", "d1", "--daily-log-url", "u", "--job", "j", "--vendor", "ACME", "--description", "leak"], env, (s) => out.push(s), (s) => err.push(s), ok)).toBe(0);
expect(sent).toEqual({ url: "http://svc/chargeback/start", body: { daily_log_id: "d1", daily_log_url: "u", job_id: "j", vendor_name: "ACME", description: "leak" } });
const bad = (async () => new Response("{\"error\":\"x\"}", { status: 400 })) as unknown as typeof fetch;
expect(await runKhbChargeback(["find", "--job", "j"], env, () => undefined, (s) => err.push(s), bad)).toBe(1);
expect(await runKhbChargeback(["find", "--bogus", "1"], env, () => undefined, (s) => err.push(s), ok)).toBe(2);
expect(await runKhbChargeback(["find"], {}, () => undefined, (s) => err.push(s), ok)).toBe(2);
});
it("промт менеджера: три варианта, отсрочка не закрывает, один дефект - один chargeback", () => {
const t = loadPrompt("p-manager-dialog.md", { media_dir: "/m" }, "proposed");
expect(t).toContain("## Chargeback к контракту подрядчика");
for (const c of ["khb-chargeback find", "khb-chargeback start", "khb-chargeback close", "khb-chargeback add-log"]) expect(t).toContain(c);
expect(t).toContain("Создаём chargeback");
expect(t).toContain("Считай вопрос закрытым");
expect(t).toContain("отсрочка, не закрытие");
expect(t).toContain("один дефект - один chargeback");
});
});