import { afterEach, beforeEach, describe, expect, it } from "vitest"; import type { FastifyInstance } from "fastify"; import { buildApp } from "../src/app.ts"; import { createMockProdamus, mockProdamusWebhook } from "../src/modules/billing/mock-prodamus.ts"; import { runBillingSweep } from "../src/modules/billing/sweep.ts"; import { createTestDb } from "./helpers/db.ts"; let app: FastifyInstance; let db: Awaited>; let clock = 0; const JSON_H = { "content-type": "application/json" }; const FORM_H = { "content-type": "application/x-www-form-urlencoded" }; const PASS = "correct-horse-9"; beforeEach(async () => { clock = Date.parse("2026-11-10T10:00:00Z"); db = await createTestDb(); app = await buildApp({ db, accounts: { now: () => clock }, billing: { provider: createMockProdamus() } }); }); afterEach(async () => app.close()); interface Auth { cookie: string; csrf: string } async function register(url: string, payload: object): Promise { const res = await app.inject({ method: "POST", url, payload, headers: JSON_H }); expect(res.statusCode).toBe(201); return { cookie: String(res.headers["set-cookie"]).split(";")[0] ?? "", csrf: (res.json() as { csrfToken: string }).csrfToken }; } const buyer = (email = "anna@example.com") => register("/api/auth/register", { email, password: PASS }); const orgAdmin = () => register("/api/auth/register-org", { orgName: "Корп", email: "boss@corp.ru", password: PASS }); const h = (a: Auth) => ({ ...JSON_H, cookie: a.cookie, "x-csrf-token": a.csrf }); const order = (a: Auth, payload: object) => app.inject({ method: "POST", url: "/api/orders", payload, headers: h(a) }); const entitlements = async (a: Auth) => (await app.inject({ method: "GET", url: "/api/entitlements", headers: { cookie: a.cookie } })).json() as { productId: string; status: string; validUntil: string | null }[]; function webhook(fields: Record, sign?: string) { const w = mockProdamusWebhook(fields); return app.inject({ method: "POST", url: "/api/billing/webhook", payload: w.body, headers: { ...FORM_H, sign: sign ?? w.sign } }); } const paid = (orderId: string, id: string, sum = "4900.00") => ({ order_id: id, order_num: orderId, sum, payment_status: "success" }); async function buy(a: Auth, productId = "kit-basic") { const res = await order(a, { productId }); expect(res.statusCode).toBe(201); return res.json() as { orderId: string; amountKopecks: number; paymentUrl: string }; } describe("Requirement: Создание заказа", () => { it("Scenario: Заказ разового комплекта", async () => { const a = await buyer(); const res = await order(a, { productId: "kit-basic" }); expect(res.statusCode).toBe(201); const body = res.json() as { amountKopecks: number; currency: string; status: string; paymentUrl: string }; expect(body).toMatchObject({ amountKopecks: 490000, currency: "RUB", status: "pending" }); expect(body.paymentUrl).toContain("https://mock-shop.payform.ru/"); expect(body.paymentUrl).toContain("signature="); expect((await db.query("SELECT 1 FROM orders WHERE status = 'pending' AND amount_kopecks = 490000")).rows).toHaveLength(1); }); it("Scenario: Цена от клиента игнорируется", async () => { const a = await buyer(); const res = await order(a, { productId: "kit-basic", amount: 1 }); expect(res.statusCode).toBe(201); expect((res.json() as { amountKopecks: number }).amountKopecks).toBe(490000); }); it("Scenario: Неизвестный товар или нет входа", async () => { const guest = await app.inject({ method: "POST", url: "/api/orders", payload: { productId: "kit-basic" }, headers: JSON_H }); expect(guest.statusCode).toBe(401); expect(guest.json()).toEqual({ error: "unauthenticated" }); const a = await buyer(); expect((await order(a, { productId: "nope" })).statusCode).toBe(404); }); it("Scenario: Подписка организации — только org_admin", async () => { const a = await buyer(); expect((await order(a, { productId: "trainer-monthly" })).statusCode).toBe(403); const boss = await orgAdmin(); expect((await order(boss, { productId: "trainer-monthly" })).statusCode).toBe(201); }); }); describe("Requirement: Вебхук оплаты", () => { it("Scenario: Успешная оплата выдаёт доступ", async () => { const a = await buyer(); const o = await buy(a); const res = await webhook(paid(o.orderId, "p1")); expect(res.statusCode).toBe(200); expect((await db.query("SELECT status FROM orders")).rows).toEqual([{ status: "paid" }]); expect(await entitlements(a)).toEqual([{ productId: "kit-basic", status: "active", validUntil: null }]); }); it("Scenario: Неверная подпись", async () => { const a = await buyer(); const o = await buy(a); const res = await webhook(paid(o.orderId, "p1"), "deadbeef"); expect(res.statusCode).toBe(400); expect(res.json()).toEqual({ error: "bad_signature" }); expect((await db.query("SELECT status FROM orders")).rows).toEqual([{ status: "pending" }]); expect(await entitlements(a)).toEqual([]); }); it("Scenario: Повторный вебхук", async () => { const a = await buyer(); const o2 = await buy(a); await webhook(paid(o2.orderId, "p1")); const again = await webhook(paid(o2.orderId, "p1")); expect(again.statusCode).toBe(200); expect(again.json()).toEqual({ status: "duplicate" }); expect((await db.query("SELECT 1 FROM entitlements")).rows).toHaveLength(1); expect((await db.query("SELECT 1 FROM payments")).rows).toHaveLength(1); }); it("Scenario: Сумма не совпала", async () => { const a = await buyer(); const o = await buy(a); const res = await webhook(paid(o.orderId, "p1", "1.00")); expect(res.statusCode).toBe(200); expect((await db.query("SELECT status FROM payments")).rows).toEqual([{ status: "rejected" }]); expect((await db.query("SELECT status FROM orders")).rows).toEqual([{ status: "pending" }]); expect(await entitlements(a)).toEqual([]); }); it("Scenario: Валюта не рубли", async () => { const a = await buyer(); const o = await buy(a); await webhook({ ...paid(o.orderId, "p1"), currency: "usd" }); expect(await entitlements(a)).toEqual([]); }); }); describe("Requirement: Подписки", () => { const sub = async () => { const boss = await orgAdmin(); const o = await buy(boss, "trainer-monthly"); return { boss, o }; }; it("Scenario: Продление", async () => { const { boss, o } = await sub(); clock = Date.parse("2026-11-01T00:00:00Z"); await app.close(); app = await buildApp({ db, accounts: { now: () => clock }, billing: { provider: createMockProdamus() } }); await webhook(paid(o.orderId, "p1", "1500.00")); const first = (await db.query<{ valid_until: Date }>("SELECT valid_until FROM entitlements")).rows[0]?.valid_until; expect(new Date(first as Date).toISOString()).toBe("2026-12-01T00:00:00.000Z"); // следующее списание того же заказа: новый id платежа await webhook(paid(o.orderId, "p2", "1500.00")); const second = (await db.query<{ valid_until: Date }>("SELECT valid_until FROM entitlements")).rows[0]?.valid_until; expect(new Date(second as Date).toISOString()).toBe("2027-01-01T00:00:00.000Z"); void boss; }); it("Scenario: Отключение при неоплате", async () => { const { boss, o } = await sub(); await webhook(paid(o.orderId, "p1", "1500.00")); await db.query("UPDATE entitlements SET valid_until = '2026-12-01T00:00:00Z'"); const none = { expiring: () => undefined }; await runBillingSweep(db, new Date("2026-12-03T00:00:00Z"), none); expect((await entitlements(boss)).map((e) => e.status)).toEqual(["active"]); const r = await runBillingSweep(db, new Date("2026-12-05T00:00:00Z"), none); expect(r.suspended).toBe(1); expect(await entitlements(boss)).toEqual([]); expect((await db.query("SELECT status FROM entitlements")).rows).toEqual([{ status: "suspended" }]); }); it("Scenario: Напоминание", async () => { const { o } = await sub(); await webhook(paid(o.orderId, "p1", "1500.00")); await db.query("UPDATE entitlements SET valid_until = '2026-12-01T00:00:00Z'"); const sent: string[] = []; const notifier = { expiring: (n: { offerId: string }) => void sent.push(n.offerId) }; expect((await runBillingSweep(db, new Date("2026-11-27T00:00:00Z"), notifier)).reminded).toBe(0); expect((await runBillingSweep(db, new Date("2026-11-28T00:00:00Z"), notifier)).reminded).toBe(1); expect((await runBillingSweep(db, new Date("2026-11-29T00:00:00Z"), notifier)).reminded).toBe(0); expect(sent).toEqual(["trainer-monthly"]); }); }); describe("Requirement: Проверка доступа", () => { it("Scenario: Список доступов", async () => { const a = await buyer(); const o = await buy(a); await webhook(paid(o.orderId, "p1")); expect(await entitlements(a)).toMatchObject([{ productId: "kit-basic", status: "active" }]); }); it("Scenario: Чужие доступы не видны", async () => { const a = await buyer(); const b = await buyer("bob@example.com"); const o = await buy(a); await webhook(paid(o.orderId, "p1")); expect(await entitlements(b)).toEqual([]); }); it("Scenario: Без входа", async () => { expect((await app.inject({ method: "GET", url: "/api/entitlements" })).statusCode).toBe(401); }); });