import { first, run } from "../db"; import { badRequest, forbidden } from "../errors"; import { publicUrl } from "../events/emit"; import type { BillingAccount } from "../metering/access"; import type { Viewer } from "~/lib/types"; import { billingNotConfigured, proPriceVerified, stripe, stripeEnabled, verifiedPacks } from "./config"; import type { TopupPack } from "./config"; import { env } from "cloudflare:workers"; export type CustomerRow = { account_id: string; stripe_customer_id: string; subscription_id: string | null; subscription_status: string | null; price_id: string | null; current_period_end: number | null; cancel_at_period_end: number; subscription_event_at: number; }; /** Subscription states that keep the Pro plan. past_due keeps it while Stripe retries the card. */ export const ACTIVE_STATUSES = new Set(["active", "trialing", "past_due"]); export async function customerFor(accountId: string): Promise { return first("SELECT * FROM billing_customers WHERE account_id = ?", accountId); } export async function accountForCustomer(customerId: string): Promise { const row = await first<{ account_id: string }>( "SELECT account_id FROM billing_customers WHERE stripe_customer_id = ?", customerId, ); return row?.account_id ?? null; } export async function linkCustomer(accountId: string, customerId: string): Promise { await run( `INSERT INTO billing_customers (account_id, stripe_customer_id, updated_at) VALUES (?, ?, ?) ON CONFLICT DO NOTHING`, accountId, customerId, Date.now(), ); } /** The account's Stripe customer, created on first use. The idempotency key makes concurrent first uses converge. */ async function ensureCustomer(account: BillingAccount, viewer: Viewer): Promise { const existing = await customerFor(account.accountId); if (existing) return existing.stripe_customer_id; const customer = await stripe().customers.create( { name: account.name, email: account.kind === "user" ? viewer.email : undefined, metadata: { account_id: account.accountId, account_kind: account.kind }, }, { idempotencyKey: `customer:${account.accountId}` }, ); await linkCustomer(account.accountId, customer.id); return (await customerFor(account.accountId))?.stripe_customer_id ?? customer.id; } function billingPath(account: BillingAccount): string { return account.kind === "org" ? `/orgs/${encodeURIComponent(account.name)}/billing` : "/settings/billing"; } function requireEditor(account: BillingAccount): void { if (!account.canEdit) throw forbidden("Only account owners can manage billing"); } /** Checkout for the Pro subscription; the webhook, not the redirect, changes the plan. */ export async function createSubscriptionCheckout(account: BillingAccount, viewer: Viewer): Promise<{ url: string }> { requireEditor(account); if (!stripeEnabled() || !env.STRIPE_PRICE_PRO) throw billingNotConfigured(); if (!(await proPriceVerified())) throw badRequest("The Pro price is being updated; try again later"); const current = await customerFor(account.accountId); if (current?.subscription_status && ACTIVE_STATUSES.has(current.subscription_status)) { throw badRequest("This account already has a subscription; manage it from the billing portal"); } const customer = await ensureCustomer(account, viewer); const back = billingPath(account); const metadata = { account_id: account.accountId, kind: "pro" }; const session = await stripe().checkout.sessions.create({ mode: "subscription", customer, client_reference_id: account.accountId, line_items: [{ price: env.STRIPE_PRICE_PRO, quantity: 1 }], success_url: publicUrl(`${back}?checkout=success`), cancel_url: publicUrl(`${back}?checkout=cancelled`), metadata, subscription_data: { metadata }, }); if (!session.url) throw badRequest("Stripe did not return a checkout URL"); return { url: session.url }; } /** Checkout for a one-time prepaid pack; credits land when checkout.session.completed arrives paid. */ export async function createTopupCheckout( account: BillingAccount, viewer: Viewer, packId: string, ): Promise<{ url: string }> { requireEditor(account); if (!stripeEnabled()) throw billingNotConfigured(); const pack = (await verifiedPacks()).find((item) => item.id === packId); if (!pack) throw badRequest("That pack is not available right now"); const customer = await ensureCustomer(account, viewer); const back = billingPath(account); const metadata = { account_id: account.accountId, kind: "topup", pack: pack.id, meter: pack.pool, quantity: String(pack.quantity), }; const session = await stripe().checkout.sessions.create({ mode: "payment", customer, client_reference_id: account.accountId, line_items: [{ price: pack.price, quantity: 1 }], success_url: publicUrl(`${back}?checkout=success`), cancel_url: publicUrl(`${back}?checkout=cancelled`), metadata, payment_intent_data: { metadata }, }); if (!session.url) throw badRequest("Stripe did not return a checkout URL"); return { url: session.url }; } /** Stripe's Customer Portal: manage or cancel the subscription and update the card. */ export async function createPortalSession(account: BillingAccount): Promise<{ url: string }> { requireEditor(account); if (!stripeEnabled()) throw billingNotConfigured(); const current = await customerFor(account.accountId); if (!current) throw badRequest("This account has no billing history yet"); const session = await stripe().billingPortal.sessions.create({ customer: current.stripe_customer_id, return_url: publicUrl(billingPath(account)), }); return { url: session.url }; } export type StripeBillingView = { enabled: boolean; publishableKey: string | null; proAvailable: boolean; subscription: { status: string | null; currentPeriodEnd: number | null; cancelAtPeriodEnd: boolean; } | null; hasCustomer: boolean; packs: Pick[]; }; /** What the billing page needs about Stripe; `enabled: false` hides every Stripe control. */ export async function stripeBillingView(accountId: string): Promise { if (!stripeEnabled()) { return { enabled: false, publishableKey: null, proAvailable: false, subscription: null, hasCustomer: false, packs: [], }; } const row = await customerFor(accountId); return { enabled: true, publishableKey: env.STRIPE_PUBLISHABLE_KEY ?? null, proAvailable: await proPriceVerified(), subscription: row?.subscription_id ? { status: row.subscription_status, currentPeriodEnd: row.current_period_end, cancelAtPeriodEnd: row.cancel_at_period_end === 1, } : null, hasCustomer: row !== null, packs: (await verifiedPacks()).map(({ id, pool, quantity, label, cents }) => ({ id, pool, quantity, label, cents, })), }; }