CLT-4: биллинг Prodamus — заказы, вебхук, доступы, подписки
All checks were successful
All checks were successful
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
f6ae1ed6c1
commit
e2e4752f06
@ -13,6 +13,7 @@
|
||||
## Соглашения
|
||||
- Модули продукта — Fastify-плагины в src/modules/<имя>, регистрируются в buildApp() (src/app.ts). Тесты через app.inject(), названия тестов совпадают со сценариями спеки. Ошибки наружу — только `{"error":"<код>"}`. В логах — только метод и путь, без IP и query. HTML выводить через escapeHtml.
|
||||
- БД: интерфейс Db/TxDb (src/db/db.ts), миграции migrations/NNNN_*.sql через node dist/db/migrate.js (deploy.migrate); тесты на PGlite (test/helpers/db.ts), без DATABASE_URL модуль accounts не регистрируется. Пароли argon2id (@node-rs/argon2), сессии — SHA-256 токена в БД, CSRF через X-CSRF-Token.
|
||||
- Биллинг (CLT-4): src/modules/billing, провайдер Prodamus за PaymentProvider; без PRODAMUS_SECRET_KEY+PRODAMUS_PAY_URL модуль не регистрируется. Цены/офферы — offers.ts (копейки), тесты на mock-prodamus.ts. Алгоритм подписи (HMAC-SHA256, PHP-json) сверить на тестовом магазине Prodamus.
|
||||
|
||||
## Решения
|
||||
- CLT-1: стек Node 22 + TS + Fastify одобрен PM. Порядок: CLT-2 (БД/учётки) → CLT-4 (биллинг) → CLT-5 (комплекты); AI-модули CLT-6..8 ждут CLT-3 (политика ПДн, 152-ФЗ). Платёжный провайдер не выбран — вопрос к PM в CLT-4.
|
||||
|
||||
@ -14,6 +14,10 @@ services:
|
||||
SENTRY_ENVIRONMENT: "${SENTRY_ENVIRONMENT:-dev}"
|
||||
# Postgres стенда. POSTGRES_PASSWORD — из secrets Actions (запросить у PM); не из репозитория.
|
||||
DATABASE_URL: "postgres://app:${POSTGRES_PASSWORD:-app}@db:5432/app"
|
||||
# Prodamus: ключ и адрес магазина — из secrets Actions; без них биллинг не включается.
|
||||
PRODAMUS_SECRET_KEY: "${PRODAMUS_SECRET_KEY:-}"
|
||||
PRODAMUS_PAY_URL: "${PRODAMUS_PAY_URL:-}"
|
||||
PUBLIC_BASE_URL: "${PUBLIC_BASE_URL:-}"
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
|
||||
43
migrations/0003_billing.sql
Normal file
43
migrations/0003_billing.sql
Normal file
@ -0,0 +1,43 @@
|
||||
CREATE TABLE orders (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid REFERENCES users (id) ON DELETE SET NULL,
|
||||
org_id uuid REFERENCES organizations (id) ON DELETE SET NULL,
|
||||
offer_id text NOT NULL,
|
||||
amount_kopecks bigint NOT NULL CHECK (amount_kopecks > 0),
|
||||
currency text NOT NULL DEFAULT 'RUB',
|
||||
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'paid')),
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX orders_user_id_idx ON orders (user_id);
|
||||
|
||||
CREATE TABLE payments (
|
||||
id uuid PRIMARY KEY,
|
||||
provider_payment_id text NOT NULL UNIQUE,
|
||||
order_id uuid NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
|
||||
amount_kopecks bigint NOT NULL,
|
||||
currency text NOT NULL,
|
||||
status text NOT NULL CHECK (status IN ('accepted', 'rejected')),
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE entitlements (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid REFERENCES users (id) ON DELETE CASCADE,
|
||||
org_id uuid REFERENCES organizations (id) ON DELETE CASCADE,
|
||||
offer_id text NOT NULL,
|
||||
status text NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
|
||||
valid_until timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CHECK ((user_id IS NULL) <> (org_id IS NULL))
|
||||
);
|
||||
CREATE UNIQUE INDEX entitlements_user_offer_idx ON entitlements (user_id, offer_id) WHERE user_id IS NOT NULL;
|
||||
CREATE UNIQUE INDEX entitlements_org_offer_idx ON entitlements (org_id, offer_id) WHERE org_id IS NOT NULL;
|
||||
|
||||
CREATE TABLE billing_notifications (
|
||||
id uuid PRIMARY KEY,
|
||||
entitlement_id uuid NOT NULL REFERENCES entitlements (id) ON DELETE CASCADE,
|
||||
kind text NOT NULL,
|
||||
valid_until timestamptz NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (entitlement_id, kind, valid_until)
|
||||
);
|
||||
@ -16,7 +16,13 @@
|
||||
|
||||
#### Scenario: Неизвестный товар или нет входа
|
||||
- **WHEN** гость отправляет POST /api/orders
|
||||
- **THEN** ответ 401 `{"error":"unauthorized"}`
|
||||
- **THEN** ответ 401 `{"error":"unauthenticated"}`
|
||||
- **AND** для вошедшего с неизвестным `productId` ответ 404 `{"error":"not_found"}`
|
||||
|
||||
#### Scenario: Подписка организации — только org_admin
|
||||
- **GIVEN** вошедший покупатель без организации
|
||||
- **WHEN** он заказывает «trainer-monthly»
|
||||
- **THEN** ответ 403 `{"error":"forbidden"}`
|
||||
|
||||
### Requirement: Вебхук оплаты
|
||||
Система SHALL принимать вебхук Prodamus только с валидной подписью, обрабатывать каждый id платежа ровно один раз и сверять сумму и валюту с заказом.
|
||||
@ -38,6 +44,10 @@
|
||||
- **THEN** ответ 200
|
||||
- **AND** доступ не дублируется
|
||||
|
||||
#### Scenario: Валюта не рубли
|
||||
- **WHEN** приходит подписанный вебхук с валютой USD
|
||||
- **THEN** доступ не выдаётся
|
||||
|
||||
#### Scenario: Сумма не совпала
|
||||
- **GIVEN** заказ на 4900 ₽
|
||||
- **WHEN** приходит подписанный вебхук на 1 ₽
|
||||
@ -0,0 +1,16 @@
|
||||
## 1. Данные
|
||||
- [x] 1.1 Миграция 0003_billing.sql: orders, payments, entitlements, billing_notifications
|
||||
- [x] 1.2 Цены в копейках — в offers.ts (предложения биллинга)
|
||||
|
||||
## 2. Провайдер
|
||||
- [x] 2.1 Интерфейс PaymentProvider, prodamus.ts (подпись, ссылка), mockProdamus
|
||||
|
||||
## 3. Модуль billing
|
||||
- [x] 3.1 POST /api/orders, GET /api/entitlements
|
||||
- [x] 3.2 Вебхук: подпись, идемпотентность, сверка, выдача доступа
|
||||
- [x] 3.3 Подписки: продление, sweep (напоминания, отключение)
|
||||
- [x] 3.4 Регистрация в buildApp, env PRODAMUS_*
|
||||
|
||||
## 4. Тесты и завершение
|
||||
- [x] 4.1 Тесты по сценариям спеки
|
||||
- [x] 4.2 Проверки, память, archive, PR
|
||||
@ -1,16 +0,0 @@
|
||||
## 1. Данные
|
||||
- [ ] 1.1 Миграция 0003_billing.sql: orders, payments, entitlements, billing_notifications
|
||||
- [ ] 1.2 Цены в копейках в каталоге товаров
|
||||
|
||||
## 2. Провайдер
|
||||
- [ ] 2.1 Интерфейс PaymentProvider, prodamus.ts (подпись, ссылка), mockProdamus
|
||||
|
||||
## 3. Модуль billing
|
||||
- [ ] 3.1 POST /api/orders, GET /api/entitlements
|
||||
- [ ] 3.2 Вебхук: подпись, идемпотентность, сверка, выдача доступа
|
||||
- [ ] 3.3 Подписки: продление, sweep (напоминания, отключение)
|
||||
- [ ] 3.4 Регистрация в buildApp, env PRODAMUS_*
|
||||
|
||||
## 4. Тесты и завершение
|
||||
- [ ] 4.1 Тесты по сценариям спеки
|
||||
- [ ] 4.2 Проверки, память, archive, PR
|
||||
90
openspec/specs/billing/spec.md
Normal file
90
openspec/specs/billing/spec.md
Normal file
@ -0,0 +1,90 @@
|
||||
# billing Specification
|
||||
|
||||
## Purpose
|
||||
TBD - created by archiving change clt-4-billing-and-access. Update Purpose after archive.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Создание заказа
|
||||
Система SHALL создавать заказ только для аутентифицированного пользователя, беря цену и валюту из серверного каталога, и возвращать ссылку на оплату Prodamus.
|
||||
|
||||
#### Scenario: Заказ разового комплекта
|
||||
- **GIVEN** вошедший покупатель «anna» и товар «kit-basic» ценой 4900 ₽ в каталоге
|
||||
- **WHEN** она отправляет POST /api/orders с `{"productId":"kit-basic"}`
|
||||
- **THEN** создаётся заказ на 490000 копеек в рублях со статусом `pending`
|
||||
- **AND** в ответе есть ссылка на оплату
|
||||
|
||||
#### Scenario: Цена от клиента игнорируется
|
||||
- **GIVEN** вошедший покупатель
|
||||
- **WHEN** он отправляет POST /api/orders с `{"productId":"kit-basic","amount":1}`
|
||||
- **THEN** сумма заказа берётся из каталога
|
||||
|
||||
#### Scenario: Неизвестный товар или нет входа
|
||||
- **WHEN** гость отправляет POST /api/orders
|
||||
- **THEN** ответ 401 `{"error":"unauthenticated"}`
|
||||
- **AND** для вошедшего с неизвестным `productId` ответ 404 `{"error":"not_found"}`
|
||||
|
||||
#### Scenario: Подписка организации — только org_admin
|
||||
- **GIVEN** вошедший покупатель без организации
|
||||
- **WHEN** он заказывает «trainer-monthly»
|
||||
- **THEN** ответ 403 `{"error":"forbidden"}`
|
||||
|
||||
### Requirement: Вебхук оплаты
|
||||
Система SHALL принимать вебхук Prodamus только с валидной подписью, обрабатывать каждый id платежа ровно один раз и сверять сумму и валюту с заказом.
|
||||
|
||||
#### Scenario: Успешная оплата выдаёт доступ
|
||||
- **GIVEN** заказ `pending` на 490000 копеек
|
||||
- **WHEN** приходит вебхук с верной подписью, статусом success и суммой 4900 RUB
|
||||
- **THEN** заказ становится `paid`
|
||||
- **AND** у покупателя появляется доступ к «kit-basic»
|
||||
|
||||
#### Scenario: Неверная подпись
|
||||
- **WHEN** приходит вебхук с неверной подписью
|
||||
- **THEN** ответ 400 `{"error":"bad_signature"}`
|
||||
- **AND** заказ и доступы не меняются
|
||||
|
||||
#### Scenario: Повторный вебхук
|
||||
- **GIVEN** платёж с id «p1» уже обработан
|
||||
- **WHEN** приходит тот же вебхук ещё раз
|
||||
- **THEN** ответ 200
|
||||
- **AND** доступ не дублируется
|
||||
|
||||
#### Scenario: Валюта не рубли
|
||||
- **WHEN** приходит подписанный вебхук с валютой USD
|
||||
- **THEN** доступ не выдаётся
|
||||
|
||||
#### Scenario: Сумма не совпала
|
||||
- **GIVEN** заказ на 4900 ₽
|
||||
- **WHEN** приходит подписанный вебхук на 1 ₽
|
||||
- **THEN** платёж помечается `rejected`, доступ не выдаётся
|
||||
|
||||
### Requirement: Подписки
|
||||
Система SHALL продлевать доступ подписки при каждом успешном платеже, напоминать о скором окончании и отключать доступ при неоплате после льготного периода.
|
||||
|
||||
#### Scenario: Продление
|
||||
- **GIVEN** подписка «trainer» с доступом до 2026-12-01
|
||||
- **WHEN** приходит успешный платёж за следующий период
|
||||
- **THEN** доступ действует до 2027-01-01
|
||||
|
||||
#### Scenario: Отключение при неоплате
|
||||
- **GIVEN** подписка с `valid_until` 2026-12-01 и без нового платежа
|
||||
- **WHEN** наступает 2026-12-05
|
||||
- **THEN** доступ получает статус `suspended`
|
||||
|
||||
#### Scenario: Напоминание
|
||||
- **GIVEN** подписка с `valid_until` 2026-12-01
|
||||
- **WHEN** наступает 2026-11-28
|
||||
- **THEN** создаётся одно напоминание (повторный запуск не дублирует)
|
||||
|
||||
### Requirement: Проверка доступа
|
||||
Система SHALL отдавать вошедшему пользователю его активные доступы.
|
||||
|
||||
#### Scenario: Список доступов
|
||||
- **GIVEN** покупатель с оплаченным «kit-basic»
|
||||
- **WHEN** он запрашивает GET /api/entitlements
|
||||
- **THEN** в ответе есть «kit-basic» со статусом `active`
|
||||
|
||||
#### Scenario: Чужие доступы не видны
|
||||
- **GIVEN** два покупателя, оплатил только первый
|
||||
- **WHEN** второй запрашивает GET /api/entitlements
|
||||
- **THEN** список пуст
|
||||
@ -3,6 +3,7 @@ import helmet from "@fastify/helmet";
|
||||
import { captureError } from "./sentry.ts";
|
||||
import type { TxDb } from "./db/db.ts";
|
||||
import { accountsModule, type AccountsOptions } from "./modules/accounts/index.ts";
|
||||
import { billingModule, type BillingOptions } from "./modules/billing/index.ts";
|
||||
import { catalogModule, type CatalogOptions } from "./modules/catalog/index.ts";
|
||||
|
||||
export const BODY_LIMIT = 1024 * 1024;
|
||||
@ -13,6 +14,8 @@ export interface AppOptions {
|
||||
/** БД; без неё модуль учётных записей не регистрируется. */
|
||||
db?: TxDb;
|
||||
accounts?: Omit<AccountsOptions, "db">;
|
||||
/** Платёжный провайдер; без БД или провайдера модуль биллинга не регистрируется. */
|
||||
billing?: Omit<BillingOptions, "db">;
|
||||
}
|
||||
|
||||
const CLIENT_ERROR_CODES: Record<number, string> = {
|
||||
@ -75,6 +78,7 @@ export async function buildApp(opts: AppOptions = {}): Promise<FastifyInstance>
|
||||
|
||||
if (opts.db) {
|
||||
await app.register(accountsModule, { ...opts.accounts, db: opts.db });
|
||||
if (opts.billing) await app.register(billingModule, { now: opts.accounts?.now, ...opts.billing, db: opts.db });
|
||||
}
|
||||
|
||||
return app;
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { initSentry, flushSentry } from "./sentry.ts";
|
||||
import { buildApp } from "./app.ts";
|
||||
import { createPool } from "./db/db.ts";
|
||||
import { createProdamus } from "./modules/billing/prodamus.ts";
|
||||
import { parsePort } from "./config.ts";
|
||||
|
||||
async function main(): Promise<void> {
|
||||
@ -15,8 +16,10 @@ async function main(): Promise<void> {
|
||||
initSentry();
|
||||
const databaseUrl = process.env.DATABASE_URL;
|
||||
const db = databaseUrl ? createPool(databaseUrl) : undefined;
|
||||
const { PRODAMUS_SECRET_KEY: secretKey, PRODAMUS_PAY_URL: payUrl } = process.env;
|
||||
const app = await buildApp({
|
||||
db,
|
||||
billing: secretKey && payUrl ? { provider: createProdamus({ secretKey, payUrl }), publicBaseUrl: process.env.PUBLIC_BASE_URL } : undefined,
|
||||
logger: {
|
||||
level: process.env.LOG_LEVEL ?? "info",
|
||||
// В логах — только метод и путь: без IP клиента, query и заголовков (ПДн).
|
||||
|
||||
@ -22,8 +22,8 @@ export interface AccountsOptions {
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
type Role = "buyer" | "org_admin" | "operator";
|
||||
interface SessionUser {
|
||||
export type Role = "buyer" | "org_admin" | "operator";
|
||||
export interface SessionUser {
|
||||
id: string;
|
||||
email: string;
|
||||
role: Role;
|
||||
@ -42,6 +42,19 @@ function parseCookies(header: string | undefined): Record<string, string> {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Пользователь по cookie сессии (без проверки CSRF); null — нет или истекла. */
|
||||
export async function loadSessionUser(db: Db, req: FastifyRequest, now: () => number = Date.now): Promise<SessionUser | null> {
|
||||
const token = parseCookies(req.headers.cookie)[COOKIE];
|
||||
if (!token) return null;
|
||||
const r = await db.query<{ id: string; email: string; role: Role; org_id: string | null; csrf_token: string }>(
|
||||
`SELECT u.id, u.email, u.role, u.org_id, s.csrf_token FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id WHERE s.token_hash = $1 AND s.expires_at > $2`,
|
||||
[hashToken(token), new Date(now())],
|
||||
);
|
||||
const row = r.rows[0];
|
||||
return row ? { id: row.id, email: row.email, role: row.role, orgId: row.org_id, csrf: row.csrf_token } : null;
|
||||
}
|
||||
|
||||
/** Удаляет истёкшие сессии; возвращает их число. */
|
||||
export async function purgeExpiredSessions(db: Db): Promise<number> {
|
||||
const r = await db.query("DELETE FROM sessions WHERE expires_at <= now()");
|
||||
@ -76,17 +89,7 @@ export async function accountsModule(app: FastifyInstance, opts: AccountsOptions
|
||||
return csrf;
|
||||
}
|
||||
|
||||
async function loadSession(req: FastifyRequest): Promise<SessionUser | null> {
|
||||
const token = parseCookies(req.headers.cookie)[COOKIE];
|
||||
if (!token) return null;
|
||||
const r = await db.query<{ id: string; email: string; role: Role; org_id: string | null; csrf_token: string }>(
|
||||
`SELECT u.id, u.email, u.role, u.org_id, s.csrf_token FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id WHERE s.token_hash = $1 AND s.expires_at > $2`,
|
||||
[hashToken(token), new Date(now())],
|
||||
);
|
||||
const row = r.rows[0];
|
||||
return row ? { id: row.id, email: row.email, role: row.role, orgId: row.org_id, csrf: row.csrf_token } : null;
|
||||
}
|
||||
const loadSession = (req: FastifyRequest): Promise<SessionUser | null> => loadSessionUser(db, req, now);
|
||||
|
||||
/** Требует сессию и CSRF-токен; при отказе отвечает сам и возвращает null. */
|
||||
async function authed(req: FastifyRequest, reply: FastifyReply, csrf: boolean): Promise<SessionUser | null> {
|
||||
|
||||
156
src/modules/billing/index.ts
Normal file
156
src/modules/billing/index.ts
Normal file
@ -0,0 +1,156 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { FastifyInstance, FastifyReply } from "fastify";
|
||||
import type { Db, TxDb } from "../../db/db.ts";
|
||||
import { captureError } from "../../sentry.ts";
|
||||
import { loadSessionUser } from "../accounts/index.ts";
|
||||
import { OFFERS, type Offer } from "./offers.ts";
|
||||
import type { PaymentEvent, PaymentProvider } from "./prodamus.ts";
|
||||
import { runBillingSweep, type Notifier } from "./sweep.ts";
|
||||
|
||||
export interface BillingOptions {
|
||||
db: TxDb;
|
||||
provider: PaymentProvider;
|
||||
/** Публичный адрес сервиса (для urlNotification), без хвостового слэша. */
|
||||
publicBaseUrl?: string;
|
||||
offers?: readonly Offer[];
|
||||
notifier?: Notifier;
|
||||
now?: () => number;
|
||||
sweepIntervalMs?: number;
|
||||
}
|
||||
|
||||
const fail = (reply: FastifyReply, code: number, error: string) => reply.code(code).send({ error });
|
||||
|
||||
function addMonths(d: Date, months: number): Date {
|
||||
const r = new Date(d);
|
||||
r.setUTCMonth(r.getUTCMonth() + months);
|
||||
return r;
|
||||
}
|
||||
|
||||
interface OrderRow {
|
||||
id: string;
|
||||
user_id: string | null;
|
||||
org_id: string | null;
|
||||
offer_id: string;
|
||||
amount_kopecks: string | number;
|
||||
currency: string;
|
||||
status: "pending" | "paid";
|
||||
}
|
||||
|
||||
async function grant(tx: Db, order: OrderRow, offer: Offer, now: Date): Promise<void> {
|
||||
const ownerCol = offer.scope === "org" ? "org_id" : "user_id";
|
||||
const ownerId = offer.scope === "org" ? order.org_id : order.user_id;
|
||||
if (!ownerId) return; // владелец удалён — выдавать некому
|
||||
const cur = await tx.query<{ id: string; valid_until: Date | string | null }>(
|
||||
`SELECT id, valid_until FROM entitlements WHERE ${ownerCol} = $1 AND offer_id = $2 FOR UPDATE`,
|
||||
[ownerId, offer.id],
|
||||
);
|
||||
let validUntil: Date | null = null;
|
||||
if (offer.kind === "subscription") {
|
||||
const existing = cur.rows[0]?.valid_until ? new Date(cur.rows[0].valid_until) : null;
|
||||
const base = existing && existing > now ? existing : now;
|
||||
validUntil = addMonths(base, offer.periodMonths ?? 1);
|
||||
}
|
||||
if (cur.rows[0]) {
|
||||
await tx.query("UPDATE entitlements SET status = 'active', valid_until = $2 WHERE id = $1", [cur.rows[0].id, validUntil]);
|
||||
} else {
|
||||
await tx.query(
|
||||
`INSERT INTO entitlements (id, ${ownerCol}, offer_id, status, valid_until) VALUES ($1, $2, $3, 'active', $4)`,
|
||||
[randomUUID(), ownerId, offer.id, validUntil],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function billingModule(app: FastifyInstance, opts: BillingOptions): Promise<void> {
|
||||
const { db, provider } = opts;
|
||||
const now = opts.now ?? Date.now;
|
||||
const offers = new Map((opts.offers ?? OFFERS).map((o) => [o.id, o]));
|
||||
const notifier: Notifier = opts.notifier ?? {
|
||||
// Email вне scope CLT-4: только лог, без адреса получателя.
|
||||
expiring: (n) => app.log.info({ entitlementId: n.entitlementId, offerId: n.offerId }, "subscription expiring"),
|
||||
};
|
||||
|
||||
const timer = setInterval(
|
||||
() => void runBillingSweep(db, new Date(now()), notifier).catch((err: unknown) => captureError(err)),
|
||||
opts.sweepIntervalMs ?? 60 * 60 * 1000,
|
||||
);
|
||||
timer.unref();
|
||||
app.addHook("onClose", async () => clearInterval(timer));
|
||||
|
||||
app.post("/api/orders", async (req, reply) => {
|
||||
const user = await loadSessionUser(db, req, now);
|
||||
if (!user) return fail(reply, 401, "unauthenticated");
|
||||
if (req.headers["x-csrf-token"] !== user.csrf) return fail(reply, 403, "csrf_failed");
|
||||
const b = req.body && typeof req.body === "object" ? (req.body as Record<string, unknown>) : {};
|
||||
const offer = typeof b.productId === "string" ? offers.get(b.productId) : undefined;
|
||||
if (!offer) return fail(reply, 404, "not_found");
|
||||
if (offer.scope === "org" && (user.role !== "org_admin" || !user.orgId)) return fail(reply, 403, "forbidden");
|
||||
const orderId = randomUUID();
|
||||
await db.query(
|
||||
"INSERT INTO orders (id, user_id, org_id, offer_id, amount_kopecks, currency) VALUES ($1, $2, $3, $4, $5, 'RUB')",
|
||||
[orderId, user.id, user.orgId, offer.id, offer.amountKopecks],
|
||||
);
|
||||
const base = opts.publicBaseUrl ?? `${req.protocol}://${req.headers.host ?? "localhost"}`;
|
||||
const paymentUrl = provider.paymentLink({
|
||||
orderId,
|
||||
offer,
|
||||
email: user.email,
|
||||
notifyUrl: `${base}/api/billing/webhook`,
|
||||
});
|
||||
return reply.code(201).send({ orderId, amountKopecks: offer.amountKopecks, currency: "RUB", status: "pending", paymentUrl });
|
||||
});
|
||||
|
||||
app.get("/api/entitlements", async (req, reply) => {
|
||||
const user = await loadSessionUser(db, req, now);
|
||||
if (!user) return fail(reply, 401, "unauthenticated");
|
||||
const r = await db.query<{ offer_id: string; status: string; valid_until: Date | string | null }>(
|
||||
`SELECT offer_id, status, valid_until FROM entitlements
|
||||
WHERE status = 'active' AND (user_id = $1 OR ($2::uuid IS NOT NULL AND org_id = $2::uuid)) ORDER BY created_at`,
|
||||
[user.id, user.orgId],
|
||||
);
|
||||
return r.rows.map((e) => ({
|
||||
productId: e.offer_id,
|
||||
status: e.status,
|
||||
validUntil: e.valid_until ? new Date(e.valid_until).toISOString() : null,
|
||||
}));
|
||||
});
|
||||
|
||||
// Вебхук: свой парсер тела (сырая строка нужна для подписи), без сессии и CSRF — доверие только подписи.
|
||||
await app.register(async (hook) => {
|
||||
hook.addContentTypeParser("application/x-www-form-urlencoded", { parseAs: "string" }, (_req, body, done) => done(null, body));
|
||||
hook.post("/api/billing/webhook", async (req, reply) => {
|
||||
const raw = typeof req.body === "string" ? req.body : "";
|
||||
const sign = req.headers.sign;
|
||||
let event: PaymentEvent | null;
|
||||
try {
|
||||
event = provider.parseWebhook(raw, typeof sign === "string" ? sign : undefined);
|
||||
} catch {
|
||||
event = null;
|
||||
}
|
||||
if (!event) return fail(reply, 400, "bad_signature");
|
||||
if (!event.success || !event.providerPaymentId) return reply.send({ status: "ignored" });
|
||||
|
||||
const result = await db.tx(async (tx) => {
|
||||
const o = await tx.query<OrderRow>("SELECT * FROM orders WHERE id::text = $1 FOR UPDATE", [event.orderId]);
|
||||
const order = o.rows[0];
|
||||
if (!order) return "unknown_order" as const;
|
||||
const offer = offers.get(order.offer_id);
|
||||
if (!offer) return "unknown_order" as const;
|
||||
const ok = event.amountKopecks === Number(order.amount_kopecks) && event.currency === order.currency;
|
||||
const ins = await tx.query(
|
||||
`INSERT INTO payments (id, provider_payment_id, order_id, amount_kopecks, currency, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (provider_payment_id) DO NOTHING`,
|
||||
[randomUUID(), event.providerPaymentId, order.id, event.amountKopecks ?? 0, event.currency, ok ? "accepted" : "rejected"],
|
||||
);
|
||||
if ((ins.rowCount ?? 0) === 0) return "duplicate" as const;
|
||||
if (!ok) return "rejected" as const;
|
||||
await tx.query("UPDATE orders SET status = 'paid' WHERE id = $1", [order.id]);
|
||||
await grant(tx, order, offer, new Date(now()));
|
||||
return "accepted" as const;
|
||||
});
|
||||
if (result === "rejected") {
|
||||
captureError(new Error("billing: webhook amount/currency mismatch"), { method: "POST", url: "/api/billing/webhook" });
|
||||
}
|
||||
return reply.send({ status: result });
|
||||
});
|
||||
});
|
||||
}
|
||||
13
src/modules/billing/mock-prodamus.ts
Normal file
13
src/modules/billing/mock-prodamus.ts
Normal file
@ -0,0 +1,13 @@
|
||||
import { createProdamus, parseForm, prodamusSign, type PaymentProvider } from "./prodamus.ts";
|
||||
|
||||
export const MOCK_PRODAMUS_KEY = "mock-prodamus-secret";
|
||||
|
||||
export function createMockProdamus(): PaymentProvider {
|
||||
return createProdamus({ secretKey: MOCK_PRODAMUS_KEY, payUrl: "https://mock-shop.payform.ru/" });
|
||||
}
|
||||
|
||||
/** Собирает вебхук в формате Prodamus (form-urlencoded + заголовок Sign), как пришёл бы от сервера провайдера. */
|
||||
export function mockProdamusWebhook(fields: Record<string, string>, key: string = MOCK_PRODAMUS_KEY) {
|
||||
const body = new URLSearchParams(fields).toString();
|
||||
return { body, sign: prodamusSign(parseForm(body), key) };
|
||||
}
|
||||
39
src/modules/billing/offers.ts
Normal file
39
src/modules/billing/offers.ts
Normal file
@ -0,0 +1,39 @@
|
||||
export interface Offer {
|
||||
/** Ключ предложения и доступа (entitlement). */
|
||||
id: string;
|
||||
title: string;
|
||||
kind: "one_time" | "subscription";
|
||||
/** Цена в копейках, рубли. Единственный источник суммы — сервер. */
|
||||
amountKopecks: number;
|
||||
/** Для подписки — длительность периода в календарных месяцах. */
|
||||
periodMonths?: number;
|
||||
/** Доступ получает пользователь или его организация (покупает org_admin). */
|
||||
scope: "user" | "org";
|
||||
/** Id подписки в кабинете Prodamus (для рекуррента). */
|
||||
prodamusSubscriptionId?: string;
|
||||
}
|
||||
|
||||
// Цены — рабочие значения для стенда; финальный прайс утверждает PM.
|
||||
export const OFFERS: readonly Offer[] = [
|
||||
{ id: "kit-basic", title: "Цифровой комплект «Базовый»", kind: "one_time", amountKopecks: 490_000, scope: "user" },
|
||||
{ id: "audit-single", title: "Экспресс-аудит: 1 отчёт", kind: "one_time", amountKopecks: 99_000, scope: "user" },
|
||||
{ id: "audit-pack-10", title: "Экспресс-аудит: пакет 10 отчётов", kind: "one_time", amountKopecks: 790_000, scope: "user" },
|
||||
{ id: "trainer-monthly", title: "AI-тренажёр, месяц", kind: "subscription", amountKopecks: 150_000, periodMonths: 1, scope: "org" },
|
||||
{ id: "hr-pack-monthly", title: "HR-пакет, месяц", kind: "subscription", amountKopecks: 590_000, periodMonths: 1, scope: "org" },
|
||||
];
|
||||
|
||||
export const GRACE_DAYS = 3;
|
||||
export const REMIND_DAYS = 3;
|
||||
|
||||
export function formatRub(kopecks: number): string {
|
||||
const k = Math.abs(kopecks);
|
||||
return `${Math.trunc(k / 100)}.${String(k % 100).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
/** "4900.00" | "4900" → копейки; иначе null. */
|
||||
export function parseRub(raw: unknown): number | null {
|
||||
if (typeof raw !== "string") return null;
|
||||
const m = /^(\d{1,9})(?:\.(\d{1,2}))?$/.exec(raw.trim());
|
||||
if (!m) return null;
|
||||
return Number(m[1]) * 100 + Number((m[2] ?? "").padEnd(2, "0") || 0);
|
||||
}
|
||||
117
src/modules/billing/prodamus.ts
Normal file
117
src/modules/billing/prodamus.ts
Normal file
@ -0,0 +1,117 @@
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
import { formatRub, parseRub, type Offer } from "./offers.ts";
|
||||
|
||||
export interface PaymentEvent {
|
||||
/** Наш id заказа (order_num в Prodamus). */
|
||||
orderId: string;
|
||||
/** Id платежа у провайдера — ключ идемпотентности. */
|
||||
providerPaymentId: string;
|
||||
amountKopecks: number | null;
|
||||
currency: string;
|
||||
success: boolean;
|
||||
}
|
||||
|
||||
export interface PaymentProvider {
|
||||
paymentLink(o: { orderId: string; offer: Offer; email: string; notifyUrl: string }): string;
|
||||
/** Разбирает тело вебхука; null — подпись неверна или тело не разобрать. */
|
||||
parseWebhook(rawBody: string, signature: string | undefined): PaymentEvent | null;
|
||||
}
|
||||
|
||||
type Tree = string | Tree[] | { [k: string]: Tree };
|
||||
|
||||
/** Разбор application/x-www-form-urlencoded с PHP-скобками: a[b][0]=v. */
|
||||
export function parseForm(raw: string): { [k: string]: Tree } {
|
||||
const root: { [k: string]: Tree } = {};
|
||||
for (const pair of raw.split("&")) {
|
||||
if (!pair) continue;
|
||||
const i = pair.indexOf("=");
|
||||
const dec = (s: string) => decodeURIComponent(s.replace(/\+/g, " "));
|
||||
const key = dec(i < 0 ? pair : pair.slice(0, i));
|
||||
const value = i < 0 ? "" : dec(pair.slice(i + 1));
|
||||
const m = /^([^[\]]+)((?:\[[^[\]]*\])*)$/.exec(key);
|
||||
if (!m) continue;
|
||||
const path = [m[1] as string, ...[...(m[2] ?? "").matchAll(/\[([^[\]]*)\]/g)].map((x) => x[1] as string)];
|
||||
if (path.some((p) => p === "__proto__" || p === "constructor" || p === "prototype")) continue;
|
||||
let node = root;
|
||||
path.slice(0, -1).forEach((p) => {
|
||||
const next = node[p];
|
||||
node = typeof next === "object" && !Array.isArray(next) ? next : (node[p] = {});
|
||||
});
|
||||
node[path[path.length - 1] as string] = value;
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
/** Рекурсивная сортировка ключей; объекты с ключами 0..n-1 становятся списками (как в PHP). */
|
||||
function normalize(v: Tree): Tree {
|
||||
if (typeof v === "string" || Array.isArray(v)) return Array.isArray(v) ? v.map(normalize) : v;
|
||||
const keys = Object.keys(v).sort();
|
||||
if (keys.length > 0 && keys.every((k, i) => k === String(i))) return keys.map((k) => normalize(v[k] as Tree));
|
||||
const out: { [k: string]: Tree } = {};
|
||||
for (const k of keys) out[k] = normalize(v[k] as Tree);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Как PHP json_encode по умолчанию: "/" → "\/", не-ASCII → \uXXXX. */
|
||||
function phpJson(v: Tree): string {
|
||||
return JSON.stringify(v).replace(/\//g, "\\/").replace(/[\u0080-]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
||||
}
|
||||
|
||||
export function prodamusSign(data: { [k: string]: Tree }, secretKey: string): string {
|
||||
return createHmac("sha256", secretKey).update(phpJson(normalize(data))).digest("hex");
|
||||
}
|
||||
|
||||
function safeEqualHex(a: string, b: string): boolean {
|
||||
const x = Buffer.from(a.toLowerCase());
|
||||
const y = Buffer.from(b.toLowerCase());
|
||||
return x.length === y.length && timingSafeEqual(x, y);
|
||||
}
|
||||
|
||||
export interface ProdamusOptions {
|
||||
secretKey: string;
|
||||
/** Адрес платёжной страницы магазина, https://<shop>.payform.ru/ */
|
||||
payUrl: string;
|
||||
}
|
||||
|
||||
export function createProdamus(opts: ProdamusOptions): PaymentProvider {
|
||||
return {
|
||||
paymentLink({ orderId, offer, email, notifyUrl }) {
|
||||
const params: { [k: string]: Tree } = {
|
||||
order_id: orderId,
|
||||
customer_email: email,
|
||||
do: "pay",
|
||||
urlNotification: notifyUrl,
|
||||
products: [{ name: offer.title, price: formatRub(offer.amountKopecks), quantity: "1" }] as never,
|
||||
};
|
||||
if (offer.prodamusSubscriptionId) params.subscription = offer.prodamusSubscriptionId;
|
||||
params.signature = prodamusSign(params, opts.secretKey);
|
||||
const url = new URL(opts.payUrl);
|
||||
const add = (k: string, v: Tree): void => {
|
||||
if (typeof v === "string") url.searchParams.append(k, v);
|
||||
else if (Array.isArray(v)) v.forEach((x, i) => add(`${k}[${i}]`, x));
|
||||
else for (const [kk, x] of Object.entries(v)) add(`${k}[${kk}]`, x);
|
||||
};
|
||||
for (const [k, v] of Object.entries(params)) add(k, v);
|
||||
return url.toString();
|
||||
},
|
||||
|
||||
parseWebhook(rawBody, signature) {
|
||||
if (!signature) return null;
|
||||
let data: { [k: string]: Tree };
|
||||
try {
|
||||
data = parseForm(rawBody);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!safeEqualHex(prodamusSign(data, opts.secretKey), signature)) return null;
|
||||
const str = (k: string): string => (typeof data[k] === "string" ? (data[k] as string) : "");
|
||||
return {
|
||||
orderId: str("order_num"),
|
||||
providerPaymentId: str("order_id"),
|
||||
amountKopecks: parseRub(str("sum")),
|
||||
currency: (str("currency") || "rub").toUpperCase(),
|
||||
success: str("payment_status") === "success",
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
36
src/modules/billing/sweep.ts
Normal file
36
src/modules/billing/sweep.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { Db } from "../../db/db.ts";
|
||||
import { GRACE_DAYS, REMIND_DAYS } from "./offers.ts";
|
||||
|
||||
export interface Notifier {
|
||||
expiring(n: { entitlementId: string; offerId: string; validUntil: Date }): void | Promise<void>;
|
||||
}
|
||||
|
||||
/** Напоминает о скором окончании (один раз на срок) и отключает неоплаченные после льготного периода. */
|
||||
export async function runBillingSweep(db: Db, now: Date, notifier: Notifier): Promise<{ reminded: number; suspended: number }> {
|
||||
const suspended = await db.query(
|
||||
`UPDATE entitlements SET status = 'suspended'
|
||||
WHERE status = 'active' AND valid_until IS NOT NULL AND valid_until + make_interval(days => $2) <= $1::timestamptz`,
|
||||
[now, GRACE_DAYS],
|
||||
);
|
||||
const due = await db.query<{ id: string; offer_id: string; valid_until: Date | string }>(
|
||||
`SELECT id, offer_id, valid_until FROM entitlements
|
||||
WHERE status = 'active' AND valid_until IS NOT NULL
|
||||
AND valid_until - make_interval(days => $2) <= $1::timestamptz AND valid_until > $1::timestamptz`,
|
||||
[now, REMIND_DAYS],
|
||||
);
|
||||
let reminded = 0;
|
||||
for (const e of due.rows) {
|
||||
const validUntil = new Date(e.valid_until);
|
||||
const ins = await db.query(
|
||||
`INSERT INTO billing_notifications (id, entitlement_id, kind, valid_until) VALUES ($1, $2, 'expiring', $3)
|
||||
ON CONFLICT DO NOTHING`,
|
||||
[randomUUID(), e.id, validUntil],
|
||||
);
|
||||
if ((ins.rowCount ?? 0) > 0) {
|
||||
reminded++;
|
||||
await notifier.expiring({ entitlementId: e.id, offerId: e.offer_id, validUntil });
|
||||
}
|
||||
}
|
||||
return { reminded, suspended: suspended.rowCount ?? 0 };
|
||||
}
|
||||
200
test/billing.test.ts
Normal file
200
test/billing.test.ts
Normal file
@ -0,0 +1,200 @@
|
||||
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<ReturnType<typeof createTestDb>>;
|
||||
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<Auth> {
|
||||
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<string, string>, 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);
|
||||
});
|
||||
});
|
||||
@ -1,4 +1,4 @@
|
||||
import { mkdtemp, writeFile, cp } from "node:fs/promises";
|
||||
import { mkdtemp, writeFile, cp, readdir } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
@ -30,6 +30,9 @@ describe("Requirement: Подключение к Postgres из окружени
|
||||
});
|
||||
});
|
||||
|
||||
const allMigrations = async (): Promise<string[]> =>
|
||||
(await readdir(MIGRATIONS_DIR)).filter((f) => f.endsWith(".sql")).map((f) => f.replace(/\.sql$/, "")).sort();
|
||||
|
||||
describe("Requirement: Миграции", () => {
|
||||
it("Scenario: Первое применение", async () => {
|
||||
const db = await createTestDb();
|
||||
@ -45,7 +48,7 @@ describe("Requirement: Миграции", () => {
|
||||
it("Scenario: Повторный запуск", async () => {
|
||||
const db = await createTestDb();
|
||||
expect(await runMigrations(db)).toEqual([]);
|
||||
expect(await names(db)).toEqual(["0001_accounts"]);
|
||||
expect(await names(db)).toEqual(await allMigrations());
|
||||
});
|
||||
|
||||
it("Scenario: Ошибка в миграции", async () => {
|
||||
@ -54,7 +57,7 @@ describe("Requirement: Миграции", () => {
|
||||
await cp(MIGRATIONS_DIR, dir, { recursive: true });
|
||||
await writeFile(join(dir, "0002_broken.sql"), "CREATE TABLE ok_table (id int); SELECT * FROM no_such_table;");
|
||||
await expect(runMigrations(db, dir + "/")).rejects.toThrow();
|
||||
expect(await names(db)).toEqual(["0001_accounts"]);
|
||||
expect(await names(db)).toEqual(await allMigrations());
|
||||
const r = await db.query("SELECT 1 FROM information_schema.tables WHERE table_name = 'ok_table'");
|
||||
expect(r.rows).toHaveLength(0);
|
||||
});
|
||||
|
||||
Loading…
Reference in New Issue
Block a user