Open source CapCut alternative.
TypeScript
feat(site): drop one-off credit purchases
David Lea19ef6c94797
diff --git a/site/src/app/[locale]/cut/app/(home)/settings/_components/CreditsCard.tsx b/site/src/app/[locale]/cut/app/(home)/settings/_components/CreditsCard.tsxindex 21cea140..47300c30 100644--- a/site/src/app/[locale]/cut/app/(home)/settings/_components/CreditsCard.tsx+++ b/site/src/app/[locale]/cut/app/(home)/settings/_components/CreditsCard.tsx@@ -1,11 +1,7 @@"use client";import { useLocale, useTranslations } from "next-intl";-import { useState } from "react";-import { useApiErrorText } from "@/app/[locale]/cut/app/(home)/settings/_components/useApiErrorText";--import { Button } from "@/components/ui/button";import {Card,CardContent,@@ -13,68 +9,14 @@ import {CardHeader,CardTitle,} from "@/components/ui/card";-import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";import { Skeleton } from "@/components/ui/skeleton";-import { track } from "@/lib/analytics";-import {- creditCountLabel,- creditsPerDollar,- dollarsForCredits,- formatCredits,-} from "@/lib/credits/format-credits";-import { formatUsdPlain } from "@/lib/credits/format-usd";-import {- creditTopUpDefaultDollars,- creditTopUpMaxDollars,- creditTopUpMinDollars,- creditTopUpPresetsDollars,-} from "@/lib/credits/top-up";-import { ApiError } from "@/queries/apiClient";-import {- useCreditAutoReload,- useCreditBalance,- useStartCreditCheckout,- useUpdateCreditAutoReload,-} from "@/queries/credits";--// Credits are sold in whole thousands, so every pack is a whole-dollar Stripe-// charge: 5,000 credits is $5.-const creditPackStep = creditsPerDollar;-const minPackCredits = creditTopUpMinDollars * creditsPerDollar;-const maxPackCredits = creditTopUpMaxDollars * creditsPerDollar;--/** Whole dollars a credit amount typed in a field costs, or null when it is not a whole pack. */-function packDollars(value: string): number | null {- // The whole field must be a count: "5000.9" or "5e3" is no pack.- const credits = value.trim() === "" ? Number.NaN : Number(value);- if (!Number.isInteger(credits) || credits % creditPackStep !== 0) {- return null;- }- return dollarsForCredits(credits);-}+import { formatCredits } from "@/lib/credits/format-credits";+import { useCreditBalance } from "@/queries/credits";export function CreditsCard() {const t = useTranslations("settings.credits");const locale = useLocale();- const apiErrorText = useApiErrorText();const balance = useCreditBalance();- const checkout = useStartCreditCheckout();- const [customAmount, setCustomAmount] = useState("");-- const startCheckout = (amountDollars: number) => {- track("credits_checkout_started", { amountDollars });- checkout.mutate(amountDollars, {- onSuccess: (result) => window.location.assign(result.url),- });- };-- // The field holds credits; checkout takes the dollars they cost.- const customDollars = packDollars(customAmount);- const customValid =- customDollars !== null &&- customDollars >= creditTopUpMinDollars &&- customDollars <= creditTopUpMaxDollars;return (<Card>@@ -82,190 +24,16 @@ export function CreditsCard() {<CardTitle>{t("title")}</CardTitle><CardDescription>{t("description")}</CardDescription></CardHeader>- <CardContent className="space-y-6">- <div>- {balance.isLoading ? (- <Skeleton className="h-9 w-32" />- ) : (- <div className="text-3xl font-semibold tabular-nums">- {formatCredits(balance.data?.balance ?? "0", locale)}- </div>- )}- <p className="mt-1 text-sm text-muted-foreground">{t("available")}</p>- </div>-- <div className="space-y-3">- <Label>{t("buy")}</Label>- <div className="flex flex-wrap gap-2">- {creditTopUpPresetsDollars.map((amount) => {- const credits = String(amount * creditsPerDollar);- return (- <Button- disabled={checkout.isPending}- key={amount}- onClick={() => setCustomAmount(credits)}- variant={customAmount === credits ? "default" : "outline"}- >- {t("preset", {- credits: creditCountLabel(amount * creditsPerDollar, locale),- price: formatUsdPlain(String(amount), locale),- })}- </Button>- );- })}- </div>- <div className="flex items-end gap-2">- <div className="space-y-1">- <Label className="text-xs text-muted-foreground" htmlFor="custom-amount">- {t("customLabel")}- </Label>- <Input- className="w-32"- id="custom-amount"- inputMode="numeric"- max={maxPackCredits}- min={minPackCredits}- onChange={(event) => setCustomAmount(event.target.value)}- placeholder="50000"- step={creditPackStep}- type="number"- value={customAmount}- />- </div>- <Button- disabled={!customValid || checkout.isPending}- onClick={() => customDollars !== null && startCheckout(customDollars)}- >- {checkout.isPending- ? t("starting")- : customValid- ? t("buyFor", { price: formatUsdPlain(String(customDollars), locale) })- : t("buyPlain")}- </Button>+ <CardContent>+ {balance.isLoading ? (+ <Skeleton className="h-9 w-32" />+ ) : (+ <div className="text-3xl font-semibold tabular-nums">+ {formatCredits(balance.data?.balance ?? "0", locale)}</div>- {checkout.isError ? (- <p className="text-sm text-destructive">- {apiErrorText(checkout.error, t("checkoutFailed"), {- max: creditCountLabel(maxPackCredits, locale),- min: creditCountLabel(minPackCredits, locale),- })}- </p>- ) : null}- </div>-- <AutoReloadSection- onNeedsCard={() => startCheckout(creditTopUpDefaultDollars)}- />+ )}+ <p className="mt-1 text-sm text-muted-foreground">{t("available")}</p></CardContent></Card>);}--function AutoReloadSection({ onNeedsCard }: { onNeedsCard: () => void }) {- const t = useTranslations("settings.credits");- const apiErrorText = useApiErrorText();- const autoReload = useCreditAutoReload();- const update = useUpdateCreditAutoReload();- const [needsCard, setNeedsCard] = useState(false);-- if (autoReload.isLoading) {- return <Skeleton className="h-24 w-full" />;- }-- const data = autoReload.data;- const enabled = data?.enabled ?? false;-- const save = (next: {- enabled: boolean;- thresholdDollars: number;- amountDollars: number;- }) => {- setNeedsCard(false);- track("credit_auto_reload_saved", next);- update.mutate(next, {- onError: (error) => {- if (error instanceof ApiError && error.code === "no_payment_method") {- setNeedsCard(true);- }- },- });- };-- return (- <form- className="space-y-3 border-t pt-5"- onSubmit={(event) => {- event.preventDefault();- const form = new FormData(event.currentTarget);- // The fields hold credits; the saved config is in whole dollars.- save({- amountDollars: Math.round(dollarsForCredits(Number(form.get("amount")))),- enabled: form.get("enabled") === "on",- thresholdDollars: Math.round(dollarsForCredits(Number(form.get("threshold")))),- });- }}- >- <label className="flex items-center gap-2 text-sm font-medium">- <input- className="size-4 accent-primary"- defaultChecked={enabled}- name="enabled"- type="checkbox"- />- {t("autoReload")}- </label>- <div className="flex flex-wrap items-end gap-3 text-sm text-muted-foreground">- <span>{t("fallsBelow")}</span>- <div className="flex items-center gap-1">- <Input- className="w-28"- defaultValue={(data?.thresholdDollars ?? 10) * creditsPerDollar}- min={0}- name="threshold"- step={creditPackStep}- type="number"- />- <span>{t("unit")}</span>- </div>- <span>{t("thenBuy")}</span>- <div className="flex items-center gap-1">- <Input- className="w-28"- defaultValue={(data?.amountDollars ?? creditTopUpDefaultDollars) * creditsPerDollar}- max={maxPackCredits}- min={minPackCredits}- name="amount"- step={creditPackStep}- type="number"- />- <span>{t("unit")}</span>- </div>- <Button disabled={update.isPending} size="sm" type="submit">- {update.isPending ? t("saving") : t("save")}- </Button>- </div>- {data?.status === "failed" && data.lastError ? (- <p className="text-sm text-destructive">- {t("lastFailed", { error: data.lastError })}- </p>- ) : null}- {needsCard ? (- <p className="text-sm text-muted-foreground">- {t.rich("needsCard", {- buy: (chunks) => (- <button- className="text-primary underline-offset-4 hover:underline"- onClick={onNeedsCard}- type="button"- >- {chunks}- </button>- ),- })}- </p>- ) : update.isError ? (- <p className="text-sm text-destructive">{apiErrorText(update.error, t("saveFailed"))}</p>- ) : null}- </form>- );-}diff --git a/site/src/app/api/billing/credits/auto-reload/route.ts b/site/src/app/api/billing/credits/auto-reload/route.tsdeleted file mode 100644index 27fc4346..00000000--- a/site/src/app/api/billing/credits/auto-reload/route.ts+++ /dev/null@@ -1,123 +0,0 @@-import { NextResponse } from "next/server";-import { z } from "zod";--import { creditMicrosPerDollar } from "@/lib/credits/amounts";-import {- creditTopUpMaxDollars,- creditTopUpMinDollars,-} from "@/lib/credits/top-up";-import { withDonkeyAuth } from "@/lib/donkey-api-auth";-import { prisma } from "@/lib/prisma";--// Defaults shown before the user has saved any config.-const defaultThresholdDollars = 10;-const defaultAmountDollars = 25;--type AutoReloadRow = {- enabled: boolean;- thresholdMicros: bigint;- amountMicros: bigint;- stripePaymentMethodId: string | null;- status: string;- lastError: string | null;-};--function dollarsFromMicros(micros: bigint): number {- return Number(micros / creditMicrosPerDollar);-}--function serialize(config: AutoReloadRow | null) {- return {- amountDollars: config ? dollarsFromMicros(config.amountMicros) : defaultAmountDollars,- enabled: config?.enabled ?? false,- hasPaymentMethod: Boolean(config?.stripePaymentMethodId),- lastError: config?.lastError ?? null,- status: config?.status ?? "idle",- thresholdDollars: config- ? dollarsFromMicros(config.thresholdMicros)- : defaultThresholdDollars,- };-}--export const GET = withDonkeyAuth(async (request) => {- const config = await prisma.creditAutoReload.findUnique({- where: { userId: request.donkey.userId },- });- return NextResponse.json(serialize(config));-});--const updateSchema = z- .object({- amountDollars: z.coerce- .number()- .int()- .min(creditTopUpMinDollars)- .max(creditTopUpMaxDollars),- enabled: z.boolean(),- thresholdDollars: z.coerce.number().int().min(0).max(creditTopUpMaxDollars),- })- .strict();--export const PUT = withDonkeyAuth(async (request) => {- const parsed = updateSchema.safeParse(await request.json().catch(() => ({})));- if (!parsed.success) {- return NextResponse.json(- {- error: "auto_reload_invalid",- message: "Provide enabled, thresholdDollars, and amountDollars.",- },- { status: 400 },- );- }-- const existing = await prisma.creditAutoReload.findUnique({- where: { userId: request.donkey.userId },- });-- // Enabling needs a saved card, which is captured the first time the user buys- // credits. Surface a distinct code so the UI can prompt a one-time top-up.- if (parsed.data.enabled && !existing?.stripePaymentMethodId) {- return NextResponse.json(- {- error: "no_payment_method",- message:- "Buy credits once to save a card, then turn on auto-reload.",- },- { status: 409 },- );- }-- const amountMicros = BigInt(parsed.data.amountDollars) * creditMicrosPerDollar;- const thresholdMicros =- BigInt(parsed.data.thresholdDollars) * creditMicrosPerDollar;-- await prisma.creditAutoReload.upsert({- create: {- amountMicros,- enabled: parsed.data.enabled,- thresholdMicros,- userId: request.donkey.userId,- },- update: {- amountMicros,- enabled: parsed.data.enabled,- thresholdMicros,- },- where: { userId: request.donkey.userId },- });-- // Re-enabling clears a prior failure so the saved card is retried promptly.- // Scoped to status "failed" so it never resets an in-flight "charging" lock —- // clobbering that would let the next inference fire a second off-session charge.- if (parsed.data.enabled) {- await prisma.creditAutoReload.updateMany({- data: { chargingPaymentIntentId: null, lastError: null, status: "idle" },- where: { status: "failed", userId: request.donkey.userId },- });- }-- const config = await prisma.creditAutoReload.findUnique({- where: { userId: request.donkey.userId },- });- return NextResponse.json(serialize(config));-});diff --git a/site/src/app/api/billing/credits/checkout/route.ts b/site/src/app/api/billing/credits/checkout/route.tsdeleted file mode 100644index 768e734f..00000000--- a/site/src/app/api/billing/credits/checkout/route.ts+++ /dev/null@@ -1,99 +0,0 @@-import { NextResponse } from "next/server";-import { z } from "zod";--import { requestLocale } from "@/i18n/requestLocale";-import { translatorFor } from "@/i18n/translator";-import { auth } from "@/lib/auth";-import { metaCheckoutMetadata, trackCheckoutStarted } from "@/lib/billing/meta-checkout";-import { ensureStripeCustomer, getStripe } from "@/lib/billing/stripe";-import { STRIPE_LOCALE } from "@/lib/billing/stripe-locale";-import { creditCountLabel, creditsPerDollar } from "@/lib/credits/format-credits";-import {- creditTopUpKind,- creditTopUpMaxDollars,- creditTopUpMinDollars,- dollarsToStripeCents,-} from "@/lib/credits/top-up";-import { unauthorizedResponse, withDonkeyAuth } from "@/lib/donkey-api-auth";--const checkoutRequestSchema = z- .object({- amountDollars: z.coerce- .number()- .int()- .min(creditTopUpMinDollars)- .max(creditTopUpMaxDollars),- })- .strict();--// Start a one-time Stripe Checkout to buy credits. Session-only (no API keys).-// The card is saved (setup_future_usage) so auto-reload can charge it later.-export const POST = withDonkeyAuth(async (request) => {- const session = await auth.api.getSession({ headers: request.headers });- if (!session) {- return unauthorizedResponse();- }-- const locale = requestLocale(request);- const parsed = checkoutRequestSchema.safeParse(- await request.json().catch(() => ({})),- );- if (!parsed.success) {- return NextResponse.json(- {- error: "credit_amount_out_of_range",- message: `Choose between ${creditCountLabel(creditTopUpMinDollars * creditsPerDollar, locale)} and ${creditCountLabel(creditTopUpMaxDollars * creditsPerDollar, locale)}, in whole thousands.`,- },- { status: 400 },- );- }- const amountDollars = parsed.data.amountDollars;-- const customerId = await ensureStripeCustomer({- email: session.user.email,- name: session.user.name,- userId: session.user.id,- });- const stripe = getStripe();- const t = await translatorFor(locale, "settings");- const origin = request.nextUrl.origin;- const metadata = {- amountDollars: String(amountDollars),- kind: creditTopUpKind,- userId: session.user.id,- };-- const checkout = await stripe.checkout.sessions.create({- cancel_url: `${origin}/app/settings?topup=cancelled`,- client_reference_id: session.user.id,- customer: customerId,- locale: STRIPE_LOCALE[locale],- line_items: [- {- price_data: {- currency: "usd",- product_data: {- description: creditCountLabel(amountDollars * creditsPerDollar, locale),- name: t("checkout.creditsProduct"),- },- unit_amount: dollarsToStripeCents(amountDollars),- },- quantity: 1,- },- ],- metadata: { ...metadata, ...metaCheckoutMetadata(request.headers) },- mode: "payment",- payment_intent_data: { metadata, setup_future_usage: "off_session" },- success_url: `${origin}/app/settings?topup=success`,- });-- if (!checkout.url) {- return NextResponse.json(- { error: "checkout_no_url", message: "Stripe did not return a URL." },- { status: 502 },- );- }-- trackCheckoutStarted(checkout.id, "Credits", request.headers, session.user);- return NextResponse.json({ url: checkout.url });-});diff --git a/site/src/cut/components/hostedError.tsx b/site/src/cut/components/hostedError.tsxindex 81a4326e..fe8b4f81 100644--- a/site/src/cut/components/hostedError.tsx+++ b/site/src/cut/components/hostedError.tsx@@ -8,7 +8,7 @@ import { openUpgrade } from "@/cut/lib/upgrade";import { useDescribeError } from "@/i18n/describeError";/** Opens the upgrade dialog on its credits wall. A surface without the dialog- * (the ChatGPT card) opens the credits page. */+ * (the ChatGPT card) opens the settings page, where plans are sold. */export function openCreditsWall(): void {if (openUpgrade("credits")) {return;@@ -18,7 +18,7 @@ export function openCreditsWall(): void {/** A hosted-inference failure (chat reply or generation tile): an Error, a* string, or a record carrying `error` and `errorCode` (a job). A balance- * failure reads "Insufficient credits, reload here" with the link to the+ * failure reads "Insufficient credits, see plans" with the link to the* credits wall inline; any other failure reads through the shared describer, and* a missing one reads `fallback`.* Surfaces inside the chat panel pass `link={false}` and lean on the composer'sdiff --git a/site/src/cut/lib/genScene.ts b/site/src/cut/lib/genScene.tsindex f7221786..fd51241b 100644--- a/site/src/cut/lib/genScene.ts+++ b/site/src/cut/lib/genScene.ts@@ -673,7 +673,7 @@ interface GenSceneState {* render only the new ones. The rest of the scene stays as it is. */recutShots: (fromN: number, toN: number, instruction: string) => { ok: boolean; message: string };/** Redo every shot holding a still in one go — the card's single retry- * button after a credits top-up or a bad batch. */+ * button after credits land or a bad batch. */retryFailedShots: () => { ok: boolean; message: string };/** Restyle the whole scene and redo every shot. */restyle: (style: string) => { ok: boolean; message: string };diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.tsindex 7a545132..d0d6edb4 100644--- a/site/src/cut/lib/generate.ts+++ b/site/src/cut/lib/generate.ts@@ -153,7 +153,7 @@ interface GenerateState {) => { jobId: string; settled: Promise<GenerateJob>; submitted: Promise<VideoSubmitOutcome> };/** Resubmit a failed video job as itself: same job id (so its chat card and* doc mirror follow along), same ladder. A render that failed on an empty- * balance retries after a top-up without retyping the prompt or losing its+ * balance retries once credits land without retyping the prompt or losing its* references. */retry: (id: string) => void;dismiss: (id: string) => void;@@ -239,8 +239,8 @@ export function signInUrl(): string {return `/sign-in?callbackURL=${encodeURIComponent(window.location.href)}`;}-/** Cut's billing page, where credits are bought. Linked from any generation- * error caused by an empty balance. */+/** Cut's settings page, where the plans are sold. Linked from any+ * generation error caused by an empty balance. */export function creditsUrl(): string {return `${CUT_APP_BASE}/settings`;}diff --git a/site/src/cut/lib/hosted.ts b/site/src/cut/lib/hosted.tsindex bad3cf74..350c228e 100644--- a/site/src/cut/lib/hosted.ts+++ b/site/src/cut/lib/hosted.ts@@ -108,9 +108,9 @@ async function noteBalance(res: Response) {// One re-check in flight at a time; focus/visibility events can fire together.let rechecking: Promise<void> | null = null;-/** While flagged out, ask the balance route directly: a top-up happens on the- * settings page, so waiting for the next hosted call would leave the credits- * tab up after the user already paid. Any failure leaves the flag as is. */+/** While flagged out, ask the balance route directly: a subscription starts on+ * the settings page, so waiting for the next hosted call would leave the+ * credits tab up after the user already paid. Any failure leaves the flag as is. */export function recheckCredits(): Promise<void> {if (!useOutOfCredits.getState().out) return Promise.resolve();rechecking ??= hostedFetch("/api/credits/balance", { cache: "no-store" })diff --git a/site/src/cut/lib/hostedError.ts b/site/src/cut/lib/hostedError.tsindex 25600e58..0a836a33 100644--- a/site/src/cut/lib/hostedError.ts+++ b/site/src/cut/lib/hostedError.ts@@ -19,7 +19,7 @@ interface ErrorBody {const text = (v: unknown): string | undefined => (typeof v === "string" && v.trim() ? v.trim() : undefined);/** The account balance can't cover the generation — callers surface a link to- * buy credits alongside the message. */+ * the plans alongside the message. */export class NoCreditsError extends UserError {constructor() {super("credits_insufficient", NO_CREDITS_MESSAGE);diff --git a/site/src/cut/lib/removal/bakeJobs.ts b/site/src/cut/lib/removal/bakeJobs.tsindex 6d991c8d..cb52da03 100644--- a/site/src/cut/lib/removal/bakeJobs.ts+++ b/site/src/cut/lib/removal/bakeJobs.ts@@ -248,7 +248,7 @@ export function cancelMatteBake(key: string): void {}/** Clear a failed bake and run the ladder again — the panel's Retry, and the- * upgrade affordance after a credit top-up. */+ * upgrade affordance once credits land. */export function retryMatteBake(clipId: string): void {failed.delete(clipId);setJob(clipId, null);diff --git a/site/src/lib/billing/credit-auto-reload.ts b/site/src/lib/billing/credit-auto-reload.tsdeleted file mode 100644index f951a81c..00000000--- a/site/src/lib/billing/credit-auto-reload.ts+++ /dev/null@@ -1,94 +0,0 @@-import { getStripe } from "@/lib/billing/stripe";-import { creditMicrosPerCent, zeroCreditMicros } from "@/lib/credits/amounts";-import { creditAutoReloadKind } from "@/lib/credits/top-up";-import { prisma } from "@/lib/prisma";--// A "charging" lock older than this is treated as stale and may be re-claimed.-// This self-heals a lock left dangling by a dropped success/failure webhook (or a-// PaymentIntent that ended in requires_action), so auto-reload never wedges.-const chargingStaleMs = 10 * 60 * 1000;-// After a failed charge, wait this long before retrying the saved card, so a-// declined card doesn't fire a fresh charge on every subsequent inference.-const failedRetryMs = 60 * 60 * 1000;--// Fired (best-effort, off the response path) after an inference charge commits.-// If the balance fell below the user's threshold, kick off an off-session Stripe-// charge against the saved card. The credit grant itself lands in the-// payment_intent.succeeded webhook — this only starts the charge. balanceMicros-// is the post-charge balance the caller already computed, so we don't re-read it.-export async function maybeTriggerCreditAutoReload(- userId: string,- balanceMicros: bigint,-): Promise<void> {- const config = await prisma.creditAutoReload.findUnique({ where: { userId } });- if (- !config ||- !config.enabled ||- !config.stripeCustomerId ||- !config.stripePaymentMethodId ||- config.amountMicros <= zeroCreditMicros ||- balanceMicros > config.thresholdMicros- ) {- return;- }-- const now = Date.now();- const chargingCutoff = new Date(now - chargingStaleMs);- const failedCutoff = new Date(now - failedRetryMs);-- // Claim the lock atomically. A fresh "charging" lock blocks (one charge at a- // time); a stale one is reclaimable (dropped webhook); a "failed" one only- // after the backoff window. updatedAt is set to now by this write, so it- // doubles as the lock-claim timestamp the cutoffs above compare against.- const claimed = await prisma.creditAutoReload.updateMany({- data: { status: "charging" },- where: {- enabled: true,- stripePaymentMethodId: { not: null },- userId,- OR: [- { status: "idle" },- { status: "charging", updatedAt: { lt: chargingCutoff } },- { status: "failed", updatedAt: { lt: failedCutoff } },- ],- },- });- if (claimed.count === 0) {- return;- }-- // amountMicros is whole dollars; charge the exact cents it represents.- const amountCents = Number(config.amountMicros / creditMicrosPerCent);- try {- const stripe = getStripe();- const paymentIntent = await stripe.paymentIntents.create({- amount: amountCents,- confirm: true,- currency: "usd",- customer: config.stripeCustomerId,- metadata: {- amountDollars: String(amountCents / 100),- kind: creditAutoReloadKind,- userId,- },- off_session: true,- payment_method: config.stripePaymentMethodId,- });- // Record which PaymentIntent owns the lock so its webhook only releases- // its own charge (a later charge's lock is never clobbered by a stale one).- await prisma.creditAutoReload.updateMany({- data: { chargingPaymentIntentId: paymentIntent.id },- where: { userId, status: "charging" },- });- } catch (error) {- await prisma.creditAutoReload.updateMany({- data: {- chargingPaymentIntentId: null,- lastError:- error instanceof Error ? error.message : "Auto-reload charge failed.",- status: "failed",- },- where: { userId },- });- }-}diff --git a/site/src/lib/billing/credit-purchases.ts b/site/src/lib/billing/credit-purchases.tsindex 7703bc00..78ec30c4 100644--- a/site/src/lib/billing/credit-purchases.ts+++ b/site/src/lib/billing/credit-purchases.ts@@ -1,10 +1,8 @@import type Stripe from "stripe";-import { stripeId } from "@/lib/billing/stripe";import { creditStringToMicros } from "@/lib/credits/amounts";import { creditAutoReloadKind, creditTopUpKind } from "@/lib/credits/top-up";import { grantCredits } from "@/lib/credits/inference";-import { prisma } from "@/lib/prisma";function parseAmountDollars(value: string | undefined): number | null {if (!value) {@@ -14,183 +12,48 @@ function parseAmountDollars(value: string | undefined): number | null {return Number.isFinite(parsed) && parsed > 0 ? parsed : null;}-// Grant purchased credits. Idempotent on (source, sourceId): Stripe can deliver-// the same event more than once, and grantCredits dedupes by sourceId, so the-// Stripe payment_intent id is used as the sourceId.+// The ledger source each purchase kind granted under, so a redelivered event+// dedupes against the grant it already made.+const PURCHASE_SOURCES = new Map<string, { source: string; label: string }>([+ [creditTopUpKind, { source: "stripe_topup", label: "credit top-up" }],+ [creditAutoReloadKind, { source: "stripe_autoreload", label: "auto-reload" }],+]);++// Credit purchases are retired, but a top-up or auto-reload charged before+// the change can still settle. Its PaymentIntent lands the credits it paid+// for. Idempotent on (source, sourceId): grantCredits dedupes by the+// PaymentIntent id, so a repeated delivery grants once.//-// Purchased credits NEVER expire: no expiresAt / periodEnd is set. That is also-// what places them last in the debit queue (see compareGrantConsumptionOrder in-// credits/inference.ts) — a subscription's periodic allotment is drawn down-// first, and prepaid purchased credit is only spent once that runs out.-async function grantPurchasedCredits(input: {- userId: string;- amountDollars: number;- source: string;- sourceId: string;- description: string;-}) {- await grantCredits({- amountMicros: creditStringToMicros(String(input.amountDollars)),- description: input.description,- // No expiresAt / periodEnd — purchased credits are permanent.- metadata: {- amountDollars: String(input.amountDollars),- purchaseSource: input.source,- },- source: input.source,- sourceId: input.sourceId,- userId: input.userId,- });-}--// A one-time top-up Checkout completed. Grant the credits and remember the saved-// payment method so auto-reload can charge it off-session later. The card is-// saved via setup_future_usage on the Checkout session.-export async function handleCreditTopUpCheckout(- stripe: Stripe,- session: Stripe.Checkout.Session,-): Promise<void> {- if (session.mode !== "payment" || session.metadata?.kind !== creditTopUpKind) {- return;- }-- const userId = session.metadata?.userId;- const amountDollars = parseAmountDollars(session.metadata?.amountDollars);- const paymentIntentId = stripeId(session.payment_intent);- if (!userId || !amountDollars || !paymentIntentId) {- console.error("[billing] incomplete credit top-up checkout", {- amountDollars,- paymentIntentId,- session: session.id,- userId,- });- return;- }-- await grantPurchasedCredits({- amountDollars,- description: `$${amountDollars} credit top-up`,- source: "stripe_topup",- sourceId: paymentIntentId,- userId,- });-- // Saving the card for auto-reload is best-effort: it must never fail the- // webhook (and thus the already-granted top-up) if it errors.- try {- await rememberSavedPaymentMethod(stripe, {- customerId: stripeId(session.customer),- paymentIntentId,- userId,- });- } catch (error) {- console.error("[billing] failed to save auto-reload payment method", error);- }-}--// A one-time top-up PaymentIntent succeeded. A fallback to the-// checkout.session.completed grant: the two share a (source, sourceId) so-// grantCredits dedupes, but this guarantees the credits land even if the-// Checkout event is dropped or the endpoint isn't subscribed to it.-export async function handleCreditTopUpPaymentSucceeded(+// Purchased credits never expire: no expiresAt / periodEnd is set, which also+// places them last in the debit queue (see compareGrantConsumptionOrder in+// credits/inference.ts).+export async function handleCreditPaymentSucceeded(paymentIntent: Stripe.PaymentIntent,): Promise<void> {- if (paymentIntent.metadata?.kind !== creditTopUpKind) {- return;- }- const userId = paymentIntent.metadata?.userId;- const amountDollars = parseAmountDollars(paymentIntent.metadata?.amountDollars);- if (!userId || !amountDollars) {- return;- }-- await grantPurchasedCredits({- amountDollars,- description: `$${amountDollars} credit top-up`,- source: "stripe_topup",- sourceId: paymentIntent.id,- userId,- });-}--// An off-session auto-reload charge succeeded. Grant the credits and release the-// lock — but only if this PaymentIntent still owns it, so a stale webhook can't-// clear a newer charge's lock.-export async function handleAutoReloadPaymentSucceeded(- paymentIntent: Stripe.PaymentIntent,-): Promise<void> {- if (paymentIntent.metadata?.kind !== creditAutoReloadKind) {+ const purchase = PURCHASE_SOURCES.get(paymentIntent.metadata?.kind ?? "");+ if (!purchase) {return;}const userId = paymentIntent.metadata?.userId;const amountDollars = parseAmountDollars(paymentIntent.metadata?.amountDollars);if (!userId || !amountDollars) {+ console.error("[billing] incomplete credit purchase payment", {+ amountDollars,+ paymentIntent: paymentIntent.id,+ userId,+ });return;}- await grantPurchasedCredits({- amountDollars,- description: `$${amountDollars} auto-reload`,- source: "stripe_autoreload",+ await grantCredits({+ amountMicros: creditStringToMicros(String(amountDollars)),+ description: `$${amountDollars} ${purchase.label}`,+ metadata: {+ amountDollars: String(amountDollars),+ purchaseSource: purchase.source,+ },+ source: purchase.source,sourceId: paymentIntent.id,userId,});-- await prisma.creditAutoReload.updateMany({- data: {- chargingPaymentIntentId: null,- lastChargeAt: new Date(),- lastError: null,- status: "idle",- },- where: { chargingPaymentIntentId: paymentIntent.id, userId },- });-}--// An off-session auto-reload charge failed (e.g. card declined). Record it and-// release the lock it owns; the UI surfaces lastError so the user can fix the card.-export async function handleAutoReloadPaymentFailed(- paymentIntent: Stripe.PaymentIntent,-): Promise<void> {- if (paymentIntent.metadata?.kind !== creditAutoReloadKind) {- return;- }- const userId = paymentIntent.metadata?.userId;- if (!userId) {- return;- }-- await prisma.creditAutoReload.updateMany({- data: {- chargingPaymentIntentId: null,- lastError:- paymentIntent.last_payment_error?.message ?? "The auto-reload charge failed.",- status: "failed",- },- where: { chargingPaymentIntentId: paymentIntent.id, userId },- });-}--async function rememberSavedPaymentMethod(- stripe: Stripe,- input: { userId: string; paymentIntentId: string; customerId: string | null },-): Promise<void> {- const paymentIntent = await stripe.paymentIntents.retrieve(input.paymentIntentId);- const paymentMethodId = stripeId(paymentIntent.payment_method);- if (!paymentMethodId) {- return;- }-- await prisma.creditAutoReload.upsert({- create: {- stripeCustomerId: input.customerId,- stripePaymentMethodId: paymentMethodId,- userId: input.userId,- },- update: {- ...(input.customerId ? { stripeCustomerId: input.customerId } : {}),- stripePaymentMethodId: paymentMethodId,- },- where: { userId: input.userId },- });}diff --git a/site/src/lib/billing/stripe.ts b/site/src/lib/billing/stripe.tsindex 9acab9a1..8fcb435b 100644--- a/site/src/lib/billing/stripe.ts+++ b/site/src/lib/billing/stripe.ts@@ -51,7 +51,7 @@ export function portalConfigurationId(): string | undefined {}// Reuse one Stripe customer per user, stored on User.stripeCustomerId so every-// billing product (Pro, top-ups) shares it and a customer is never duplicated.+// billing product shares it and a customer is never duplicated.export async function ensureStripeCustomer(input: {userId: string;email: string;diff --git a/site/src/lib/credits/inference.ts b/site/src/lib/credits/inference.tsindex 99267e3e..c8fe6e26 100644--- a/site/src/lib/credits/inference.ts+++ b/site/src/lib/credits/inference.ts@@ -1,4 +1,4 @@-import { NextResponse, after } from "next/server";+import { NextResponse } from "next/server";import { Prisma, type PrismaClient } from "@/generated/prisma/client";import { prisma } from "@/lib/prisma";@@ -482,32 +482,6 @@ export async function recordInferenceUsage(input: InferenceUsageInput) {},));- // After a real charge commits, top up the balance via auto-reload if it fell- // below the user's threshold. Scheduled with next/server `after` so it runs- // off the response path AND the serverless runtime keeps the function alive- // until it finishes (an un-awaited promise can be dropped after the response).- // The dynamic import breaks the module cycle (billing -> credits -> billing);- // the post-charge balance is passed in so the trigger needn't re-read it.- if (input.billingMode !== "included" && recorded.creditCostMicros > zeroCreditMicros) {- const balanceMicros = recorded.remainingBalanceMicros;- try {- after(async () => {- try {- const { maybeTriggerCreditAutoReload } = await import(- "@/lib/billing/credit-auto-reload"- );- await maybeTriggerCreditAutoReload(input.userId, balanceMicros);- } catch (error) {- console.error("[credit-auto-reload] trigger failed", error);- }- });- } catch (error) {- // `after` throws outside a request scope (e.g. a script/test). Don't let- // that break usage recording — auto-reload is best-effort.- console.error("[credit-auto-reload] could not schedule trigger", error);- }- }-return recorded;}diff --git a/site/src/lib/credits/top-up.ts b/site/src/lib/credits/top-up.tsindex 8f4a3b9d..646862dc 100644--- a/site/src/lib/credits/top-up.ts+++ b/site/src/lib/credits/top-up.ts@@ -1,23 +1,11 @@-// Client-safe credit top-up constants and pure helpers (no server-only imports),-// shared by the purchase logic, the auto-reload validation, and the settings UI-// so the presets and bounds can never drift between the buttons and the server-// checks. Keep this file free of prisma / Stripe imports.+// Client-safe credit constants and pure helpers (no server-only imports),+// shared by the server and the settings UI. Keep this file free of prisma /+// Stripe imports.import type { Locale } from "@/i18n/locales";-// Presets drive the quick-buy buttons; the custom field accepts any whole-dollar-// amount in [min, max]. Amounts are whole dollars so they map cleanly to Stripe-// unit_amount cents and the grant ledger.-export const creditTopUpPresetsDollars = [5, 25, 50, 100] as const;-export const creditTopUpMinDollars = 5;-export const creditTopUpMaxDollars = 2_000;--// The default pay-as-you-go amount: the value we pre-fill / fall back to when no-// other amount is chosen (the auto-reload default and the "buy once to save a-// card" nudge both key off this so they stay in sync).-export const creditTopUpDefaultDollars = 25;--// Stripe metadata "kind" tags that route a completed payment to a credit grant.+// Stripe metadata "kind" tags the retired credit purchases charged under; a+// payment that settles late is routed to its grant by them.export const creditTopUpKind = "credit_topup";export const creditAutoReloadKind = "credit_topup_autoreload";@@ -26,10 +14,6 @@ export const creditAutoReloadKind = "credit_topup_autoreload";// rejected.export const maxCreditGrantDollars = 100;-export function dollarsToStripeCents(amountDollars: number): number {- return Math.round(amountDollars * 100);-}-// How long a grant lives, capped at the same ceiling everywhere. null stands// for a grant that never expires.export const maxCreditGrantExpiryDays = 3650;diff --git a/site/src/queries/credits.ts b/site/src/queries/credits.tsindex bb8ce8b7..b17c5c9e 100644--- a/site/src/queries/credits.ts+++ b/site/src/queries/credits.ts@@ -6,7 +6,6 @@ import type { CreditPriceSheet } from "@/lib/credits/price-sheet";import { apiFetch } from "@/queries/apiClient";export const creditBalanceQueryKey = ["credits", "balance"] as const;-export const creditAutoReloadQueryKey = ["credits", "auto-reload"] as const;export const accountQueryKey = ["account", "me"] as const;export const subscribeBonusQueryKey = ["credits", "subscribe-bonus"] as const;@@ -25,15 +24,6 @@ export type CreditBalance = {}[];};-export type CreditAutoReload = {- enabled: boolean;- thresholdDollars: number;- amountDollars: number;- hasPaymentMethod: boolean;- status: string;- lastError: string | null;-};-export type Account = {userId: string;email: string | null;@@ -101,43 +91,6 @@ export function useAccount() {});}-// Returns the Stripe Checkout URL; the caller redirects the browser. No-// invalidation here because the user leaves the page for Stripe and returns to-// /app/settings, which refetches on mount.-export function useStartCreditCheckout() {- return useMutation({- mutationFn: (amountDollars: number) =>- apiFetch<{ url: string }>("/api/billing/credits/checkout", {- body: JSON.stringify({ amountDollars }),- method: "POST",- }),- });-}--export function useCreditAutoReload() {- return useQuery({- queryFn: () => apiFetch<CreditAutoReload>("/api/billing/credits/auto-reload"),- queryKey: creditAutoReloadQueryKey,- });-}--export function useUpdateCreditAutoReload() {- const queryClient = useQueryClient();- return useMutation({- mutationFn: (input: {- enabled: boolean;- thresholdDollars: number;- amountDollars: number;- }) =>- apiFetch<CreditAutoReload>("/api/billing/credits/auto-reload", {- body: JSON.stringify(input),- method: "PUT",- }),- onSuccess: () =>- queryClient.invalidateQueries({ queryKey: creditAutoReloadQueryKey }),- });-}-export const creditOfferQueryKey = (token: string) => ["credits", "offer", token] as const;export type CreditOffer = {