163 lines
7.4 KiB
TypeScript
163 lines
7.4 KiB
TypeScript
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; // владелец удалён — выдавать некому
|
|
if (offer.auditCredits && order.user_id) {
|
|
await tx.query(
|
|
"INSERT INTO audit_balances (user_id, credits) VALUES ($1, $2) ON CONFLICT (user_id) DO UPDATE SET credits = audit_balances.credits + $2",
|
|
[order.user_id, offer.auditCredits],
|
|
);
|
|
}
|
|
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 });
|
|
});
|
|
});
|
|
}
|