Open source CapCut alternative.
TypeScript
feat(site): a Pro subscribe bonus is offered once half the signup credits are spent
David Le2674f43f5ce0
diff --git a/site/src/app/api/billing/checkout/route.ts b/site/src/app/api/billing/checkout/route.tsindex 459a7672..b2bc64d5 100644--- a/site/src/app/api/billing/checkout/route.ts+++ b/site/src/app/api/billing/checkout/route.ts@@ -3,6 +3,7 @@ import { NextResponse } from "next/server";import { auth } from "@/lib/auth";import { proPriceId } from "@/lib/billing/pro-subscription";import { ensureStripeCustomer, getStripe } from "@/lib/billing/stripe";+import { openSubscribeBonusOffer, SUBSCRIBE_BONUS_METADATA_KEY } from "@/lib/credits/subscribe-bonus-claim";import {notFoundResponse,unauthorizedResponse,@@ -29,6 +30,9 @@ export const POST = withDonkeyAuth(async (request) => {name: session.user.name,userId: session.user.id,});+ // A checkout started while the subscribe bonus offer is open carries the+ // offer, so the webhook lands the bonus on the subscription it creates.+ const offer = await openSubscribeBonusOffer(session.user.id);const stripe = getStripe();const origin = request.nextUrl.origin;const checkout = await stripe.checkout.sessions.create({@@ -38,7 +42,12 @@ export const POST = withDonkeyAuth(async (request) => {customer: customerId,line_items: [{ price: priceId, quantity: 1 }],mode: "subscription",- subscription_data: { metadata: { userId: session.user.id } },+ subscription_data: {+ metadata: {+ userId: session.user.id,+ ...(offer ? { [SUBSCRIBE_BONUS_METADATA_KEY]: offer.id } : {}),+ },+ },success_url: `${origin}/app/settings?checkout=success`,});diff --git a/site/src/app/api/credits/subscribe-bonus/route.ts b/site/src/app/api/credits/subscribe-bonus/route.tsnew file mode 100644index 00000000..f714b8b1--- /dev/null+++ b/site/src/app/api/credits/subscribe-bonus/route.ts@@ -0,0 +1,13 @@+import { NextResponse } from "next/server";++import { contextFromRequest } from "@/lib/config/effective";+import { readSubscribeBonusOffer } from "@/lib/credits/subscribe-bonus";+import { withDonkeyAuth } from "@/lib/donkey-api-auth";++// The caller's subscribe bonus offer, opened on this read when the account+// has just crossed the share of its signup grant the offer waits for.+export const GET = withDonkeyAuth(async (request) => {+ const ctx = await contextFromRequest(request);+ const offer = await readSubscribeBonusOffer(ctx);+ return NextResponse.json({ offer });+});diff --git a/site/src/cut/components/SubscribeBonusPill.tsx b/site/src/cut/components/SubscribeBonusPill.tsxnew file mode 100644index 00000000..a44d1aad--- /dev/null+++ b/site/src/cut/components/SubscribeBonusPill.tsx@@ -0,0 +1,158 @@+"use client";++// The subscribe bonus in the top bar: while the account's offer is open, a+// pill names the credit and how long is left, and opens the offer itself. The+// offer opens once on its own the first time this tab sees it.+import { useEffect, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { Gift } from "lucide-react";+import { CUT_PRO } from "@/app/cut/_components/landing/cutPricingPlans";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { useEngineUser } from "@/cut/lib/backend/hooks";+import { useInvalidateOnSettle } from "@/cut/lib/hosted";+import { track } from "@/lib/analytics";+import { formatUsd } from "@/lib/credits/format-usd";+import { formatCreditExpiry } from "@/lib/credits/top-up";+import { useStartCheckout } from "@/queries/billing";+import { subscribeBonusQueryKey, useSubscribeBonus, type SubscribeBonus } from "@/queries/credits";++const PILL =+ "flex cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-full border border-primary/30 bg-primary/10 px-3 py-1.5 text-xs font-medium tabular-nums text-foreground transition-colors hover:border-primary/60 hover:bg-primary/15";++const SEEN_KEY = "cut-subscribe-bonus-seen";++/** The minutes left on an offer, never below zero. */+export function minutesLeft(closesAt: string, now: number): number {+ return Math.max(0, Math.ceil((Date.parse(closesAt) - now) / 60_000));+}++/** "5h left" past the hour, "40m left" inside it. */+export function timeLeftLabel(minutes: number): string {+ if (minutes >= 60) return `${Math.floor(minutes / 60)}h left`;+ return `${minutes}m left`;+}++/** The deadline as people read it in their own clock: "Sep 8, 3:14 PM". */+export function formatDeadline(closesAt: string): string {+ return new Date(closesAt).toLocaleString("en-US", {+ day: "numeric",+ hour: "numeric",+ minute: "2-digit",+ month: "short",+ });+}++function seenBefore(offer: SubscribeBonus): boolean {+ try {+ return localStorage.getItem(SEEN_KEY) === offer.openedAt;+ } catch {+ return false;+ }+}++function markSeen(offer: SubscribeBonus): void {+ try {+ localStorage.setItem(SEEN_KEY, offer.openedAt);+ } catch {+ // A browser that keeps nothing shows the offer again next load.+ }+}++export function SubscribeBonusPill() {+ const user = useEngineUser();+ const offer = useSubscribeBonus({ enabled: Boolean(user) });+ // A charge from this tab may have been the one that opened the offer; the+ // re-read brings the pill up without waiting on the poll.+ useInvalidateOnSettle(subscribeBonusQueryKey);++ if (!user || offer.data?.status !== "open") return null;+ return <OpenOffer key={offer.data.openedAt} offer={offer.data} />;+}++function OpenOffer({ offer }: { offer: SubscribeBonus }) {+ const queryClient = useQueryClient();+ const checkout = useStartCheckout();+ // The offer presents itself once: the first time a tab sees it open.+ const [open, setOpen] = useState(() => !seenBefore(offer));+ const [now, setNow] = useState(() => Date.now());++ // The clock the label reads; a minute is as fine as the label gets.+ useEffect(() => {+ const id = setInterval(() => setNow(Date.now()), 60_000);+ return () => clearInterval(id);+ }, []);+ // The first showing is recorded, so the next load leaves the pill alone.+ useEffect(() => {+ if (seenBefore(offer)) return;+ markSeen(offer);+ track("subscribe_bonus_offered", { dollars: Number(offer.dollars) });+ }, [offer]);++ const minutes = minutesLeft(offer.closesAt, now);+ // Past the deadline the server says closed; ask it.+ useEffect(() => {+ if (minutes > 0) return;+ void queryClient.invalidateQueries({ queryKey: subscribeBonusQueryKey });+ }, [minutes, queryClient]);+ if (minutes === 0) return null;++ const dollars = formatUsd(offer.dollars);+ const subscribe = () => {+ track("subscribe_bonus_checkout_started", {+ dollars: Number(offer.dollars),+ minutesLeft: minutes,+ source: "editor",+ });+ checkout.mutate(undefined, {+ onSuccess: (result) => window.location.assign(result.url),+ });+ };++ return (+ <>+ <button+ type="button"+ className={PILL}+ aria-label={`${dollars} in credits with Pro, ${timeLeftLabel(minutes)}`}+ onClick={() => setOpen(true)}+ >+ <Gift className="size-3.5" />+ {dollars} with Pro · {timeLeftLabel(minutes)}+ </button>+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Get {dollars} in credits with Pro</DialogTitle>+ <DialogDescription>+ You have used half of your signup credits. Subscribe to Pro for {CUT_PRO.price} by{" "}+ {formatDeadline(offer.closesAt)} and a one-time {dollars} in credits lands in your account+ {offer.creditsExpireAt+ ? `, spendable through ${formatCreditExpiry(new Date(offer.creditsExpireAt))}`+ : ""}+ .+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button variant="ghost" onClick={() => setOpen(false)}>+ Not now+ </Button>+ <Button disabled={checkout.isPending} onClick={subscribe}>+ {checkout.isPending ? "Starting…" : "Subscribe to Pro"}+ </Button>+ </DialogFooter>+ {checkout.isError ? (+ <p className="text-sm text-destructive">Billing is unavailable right now.</p>+ ) : null}+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/site/src/cut/components/TopBar.tsx b/site/src/cut/components/TopBar.tsxindex 670a8539..b4fb3ca3 100644--- a/site/src/cut/components/TopBar.tsx+++ b/site/src/cut/components/TopBar.tsx@@ -40,6 +40,7 @@ import { CreditsPill } from "./CreditsPill";import { RecordDialog, type RecordMode } from "./RecordDialog";import { ShareDialog } from "./ShareDialog";import { StoragePill } from "./StoragePill";+import { SubscribeBonusPill } from "./SubscribeBonusPill";function AspectIcon({ aspect, className }: { aspect: Aspect; className?: string }) {const o = aspectOrientation(aspect);@@ -628,6 +629,7 @@ export function TopBar({button. */}<div className="flex shrink-0 items-center gap-2 pr-3"><div ref={pillRef} className="flex items-center gap-2">+ <SubscribeBonusPill /><CreditsPill /><StoragePill /></div>diff --git a/site/src/lib/analytics.ts b/site/src/lib/analytics.tsindex 8ca85168..903e03d0 100644--- a/site/src/lib/analytics.ts+++ b/site/src/lib/analytics.ts@@ -56,6 +56,9 @@ export type AnalyticsEvents = {tag: string;slot: string;};+ // The subscribe bonus: shown once when the offer opens, and taken up.+ subscribe_bonus_offered: { dollars: number };+ subscribe_bonus_checkout_started: { dollars: number; minutesLeft: number; source: "editor" | "settings" };// Billing (settings).pro_checkout_started: void;billing_portal_opened: void;diff --git a/site/src/lib/credits/subscribe-bonus-claim.ts b/site/src/lib/credits/subscribe-bonus-claim.tsnew file mode 100644index 00000000..2ef9cc76--- /dev/null+++ b/site/src/lib/credits/subscribe-bonus-claim.ts@@ -0,0 +1,34 @@+import { creditOfferOpen, landCreditOffer } from "@/lib/credits/offers";+import { prisma } from "@/lib/prisma";++// The subscribe bonus lands here, from the subscription webhook. A Pro+// checkout started while the account's offer was open carries the offer's+// id on the subscription it creates, so the claim is the checkout the person+// took up from the offer, however long Stripe took. The grant keys on the+// account, so the bonus lands once however many webhooks there are.++// The offer's kind, and the source of the grant it lands as.+export const SUBSCRIBE_BONUS_KIND = "subscribe_bonus";+export const SUBSCRIBE_BONUS_SOURCE = "subscribe_bonus";++// The subscription metadata key the checkout writes and the webhook reads.+export const SUBSCRIBE_BONUS_METADATA_KEY = "creditOfferId";++/** The account's offer if it can be taken up right now. */+export async function openSubscribeBonusOffer(userId: string, now = new Date()) {+ const offer = await prisma.creditOffer.findFirst({+ where: { userId, kind: SUBSCRIBE_BONUS_KIND },+ orderBy: { createdAt: "asc" },+ });+ return offer && creditOfferOpen(offer, now) ? offer : null;+}++export async function claimSubscribeBonus(userId: string, offerId: string) {+ const offer = await prisma.creditOffer.findUnique({ where: { id: offerId } });+ if (!offer || offer.userId !== userId || offer.kind !== SUBSCRIBE_BONUS_KIND) return null;+ return landCreditOffer(offer, {+ description: "Pro subscribe bonus",+ source: SUBSCRIBE_BONUS_SOURCE,+ sourceId: `subscribe-bonus:${userId}`,+ });+}diff --git a/site/src/lib/credits/subscribe-bonus.test.ts b/site/src/lib/credits/subscribe-bonus.test.tsnew file mode 100644index 00000000..5714a908--- /dev/null+++ b/site/src/lib/credits/subscribe-bonus.test.ts@@ -0,0 +1,49 @@+import { describe, expect, test } from "bun:test";++import { creditStringToMicros } from "./amounts";+import { creditOutlivesWindow, crossedSpentShare, endOfUtcDay, subscribeBonusStatus } from "./subscribe-bonus";++const usd = (s: string) => creditStringToMicros(s);++describe("the subscribe bonus", () => {+ test("opens once half of the signup grant is spent", () => {+ const grant = { originalAmountMicros: usd("25"), remainingAmountMicros: usd("12.5") };+ expect(crossedSpentShare(grant, usd("0"), 50)).toBe(true);+ expect(crossedSpentShare({ ...grant, remainingAmountMicros: usd("12.51") }, usd("0"), 50)).toBe(false);+ });++ test("credit that lapsed at expiry was never spent", () => {+ const expired = { originalAmountMicros: usd("25"), remainingAmountMicros: usd("0") };+ expect(crossedSpentShare(expired, usd("20"), 50)).toBe(false);+ expect(crossedSpentShare(expired, usd("10"), 50)).toBe(true);+ });++ test("an empty grant never crosses", () => {+ expect(crossedSpentShare({ originalAmountMicros: usd("0"), remainingAmountMicros: usd("0") }, usd("0"), 50)).toBe(false);+ });++ test("the credit stays spendable through the last day", () => {+ expect(endOfUtcDay("2026-10-29").toISOString()).toBe("2026-10-29T23:59:59.999Z");+ });++ test("the offer is open until it closes, and claimed once the grant lands", () => {+ const closesAt = new Date("2026-09-08T12:00:00Z");+ const free = (at: string) => ({ now: new Date(at), pro: false });+ expect(subscribeBonusStatus({ closesAt, claimedAt: null }, free("2026-09-08T11:59:00Z"))).toBe("open");+ expect(subscribeBonusStatus({ closesAt, claimedAt: null }, free("2026-09-08T12:00:01Z"))).toBe("closed");+ expect(subscribeBonusStatus({ closesAt: null, claimedAt: null }, free("2030-01-01T00:00:00Z"))).toBe("open");+ expect(subscribeBonusStatus({ closesAt, claimedAt: new Date() }, free("2026-09-09T00:00:00Z"))).toBe("claimed");+ });++ test("an account that already holds Pro reads the offer as closed", () => {+ const closesAt = new Date("2026-09-08T12:00:00Z");+ expect(subscribeBonusStatus({ closesAt, claimedAt: null }, { now: new Date("2026-09-08T11:00:00Z"), pro: true })).toBe("closed");+ });++ test("no offer promises credit that dies inside its window", () => {+ const closesAt = new Date("2026-10-30T01:00:00Z");+ expect(creditOutlivesWindow(endOfUtcDay("2026-10-29"), closesAt)).toBe(false);+ expect(creditOutlivesWindow(endOfUtcDay("2026-10-30"), closesAt)).toBe(true);+ expect(creditOutlivesWindow(null, closesAt)).toBe(true);+ });+});diff --git a/site/src/lib/credits/subscribe-bonus.ts b/site/src/lib/credits/subscribe-bonus.tsnew file mode 100644index 00000000..4bba9f45--- /dev/null+++ b/site/src/lib/credits/subscribe-bonus.ts@@ -0,0 +1,128 @@+import type { CreditOffer } from "@/generated/prisma/client";+import { getActiveProSubscription } from "@/lib/billing/pro-subscription";+import { getSetting, type ConfigContext } from "@/lib/config/effective";+import { creditMicrosToString, creditStringToMicros, zeroCreditMicros } from "@/lib/credits/amounts";+import { creditOfferOpen } from "@/lib/credits/offers";+import { SUBSCRIBE_BONUS_KIND } from "@/lib/credits/subscribe-bonus-claim";+import { prisma } from "@/lib/prisma";++// The subscribe bonus: an account that has spent enough of its signup grant+// is offered credit for subscribing to Pro within a window. The offer is a+// credit offer of this kind, opened on the first read that finds the account+// past the share; it lands from the subscription webhook+// (src/lib/credits/subscribe-bonus-claim.ts).++export const SIGNUP_GRANT_SOURCE = "signup";++export type SubscribeBonusStatus = "open" | "closed" | "claimed";++export type SubscribeBonusView = {+ // USD, as a credit string.+ dollars: string;+ openedAt: string;+ closesAt: string;+ creditsExpireAt: string | null;+ status: SubscribeBonusStatus;+};++/** The last moment of a UTC day named as YYYY-MM-DD. */+export function endOfUtcDay(day: string): Date {+ return new Date(`${day}T23:59:59.999Z`);+}++/** Whether a grant is spent past the share the offer waits for. Credit that+ * lapsed at expiry was never spent, so it comes off the spent side. */+export function crossedSpentShare(+ grant: { originalAmountMicros: bigint; remainingAmountMicros: bigint },+ lapsedMicros: bigint,+ spentPercent: number,+): boolean {+ if (grant.originalAmountMicros <= zeroCreditMicros) return false;+ const spent = grant.originalAmountMicros - grant.remainingAmountMicros - lapsedMicros;+ return spent * BigInt(100) >= grant.originalAmountMicros * BigInt(spentPercent);+}++/** An offer is open while it can still be taken up: unclaimed, inside its+ * window, and by an account that does not already hold Pro. */+export function subscribeBonusStatus(+ offer: { closesAt: Date | null; claimedAt: Date | null },+ facts: { now: Date; pro: boolean },+): SubscribeBonusStatus {+ if (offer.claimedAt) return "claimed";+ return !facts.pro && creditOfferOpen(offer, facts.now) ? "open" : "closed";+}++export function subscribeBonusView(offer: CreditOffer, facts: { now: Date; pro: boolean }): SubscribeBonusView {+ return {+ dollars: creditMicrosToString(offer.amountMicros),+ openedAt: offer.createdAt.toISOString(),+ closesAt: (offer.closesAt ?? offer.createdAt).toISOString(),+ creditsExpireAt: offer.expiresAt?.toISOString() ?? null,+ status: subscribeBonusStatus(offer, facts),+ };+}++/** Whether credit expiring at the day's end outlives the whole window, so a+ * subscription at the last minute of the window still lands live credit. */+export function creditOutlivesWindow(expiresAt: Date | null, closesAt: Date): boolean {+ return expiresAt === null || expiresAt.getTime() > closesAt.getTime();+}++/** The account's offer of this kind: the earliest, so two first reads that+ * raced agree on which one stands. */+export function findSubscribeBonusOffer(userId: string) {+ return prisma.creditOffer.findFirst({+ where: { userId, kind: SUBSCRIBE_BONUS_KIND },+ orderBy: { createdAt: "asc" },+ });+}++/** The account's offer as it stands, opening it when the account has just+ * crossed the share. Null while there is nothing to offer: the setting makes+ * no offer for this account, the account holds Pro, or the signup grant is+ * not yet spent far enough. */+export async function readSubscribeBonusOffer(ctx: ConfigContext, now = new Date()): Promise<SubscribeBonusView | null> {+ if (!ctx.hasAccount) return null;+ // The indexed reads come first: the offer row, then the two facts that rule+ // most accounts out before the configuration is resolved.+ const [existing, pro, grant] = await Promise.all([+ findSubscribeBonusOffer(ctx.userId),+ getActiveProSubscription(ctx.userId),+ prisma.userCreditGrant.findFirst({+ where: { userId: ctx.userId, source: SIGNUP_GRANT_SOURCE },+ select: { id: true, originalAmountMicros: true, remainingAmountMicros: true },+ }),+ ]);+ const facts = { now, pro: pro !== null };+ if (existing) return subscribeBonusView(existing, facts);+ if (pro || !grant || grant.remainingAmountMicros >= grant.originalAmountMicros) return null;++ const setting = await getSetting("subscribeBonus", ctx);+ if (setting.dollars <= 0) return null;+ const lapsed = await prisma.userCreditLedgerEntry.aggregate({+ _sum: { amountMicros: true },+ where: { grantId: grant.id, type: "expiration" },+ });+ const lapsedMicros = -(lapsed._sum.amountMicros ?? zeroCreditMicros);+ if (!crossedSpentShare(grant, lapsedMicros, setting.spentPercent)) return null;++ // A promise of credit that would be dead by the time it lands is no offer:+ // the setting's last day has to lie past the whole window.+ const closesAt = new Date(now.getTime() + setting.windowHours * 60 * 60 * 1000);+ const expiresAt = setting.creditsExpireOn ? endOfUtcDay(setting.creditsExpireOn) : null;+ if (!creditOutlivesWindow(expiresAt, closesAt)) return null;++ await prisma.creditOffer.create({+ data: {+ amountMicros: creditStringToMicros(String(setting.dollars)),+ closesAt,+ createdAt: now,+ description: "Pro subscribe bonus",+ expiresAt,+ kind: SUBSCRIBE_BONUS_KIND,+ userId: ctx.userId,+ },+ });+ const row = await findSubscribeBonusOffer(ctx.userId);+ return row ? subscribeBonusView(row, facts) : null;+}diff --git a/site/src/lib/email/credit-expiry-notices.ts b/site/src/lib/email/credit-expiry-notices.tsindex cbbc03bb..11c7a344 100644--- a/site/src/lib/email/credit-expiry-notices.ts+++ b/site/src/lib/email/credit-expiry-notices.ts@@ -6,7 +6,7 @@ import { prisma } from "@/lib/prisma";// The grants an account is warned about: credit it was given. Purchased// credit never expires, and the Pro allowance turns over every month.-export const NOTICED_GRANT_SOURCES = ["signup", "manual_dollar"] as const;+export const NOTICED_GRANT_SOURCES = ["signup", "manual_dollar", "subscribe_bonus"] as const;const DAY_MS = 24 * 60 * 60 * 1000;diff --git a/site/src/queries/credits.ts b/site/src/queries/credits.tsindex 09671191..82193ac3 100644--- a/site/src/queries/credits.ts+++ b/site/src/queries/credits.ts@@ -7,6 +7,7 @@ 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;export type CreditBalance = {balance: string;@@ -45,6 +46,29 @@ export function useCreditBalance() {});}+export type SubscribeBonus = {+ // USD, as a credit string.+ dollars: string;+ openedAt: string;+ closesAt: string;+ creditsExpireAt: string | null;+ status: "open" | "closed" | "claimed";+};++// The account's subscribe bonus offer. The read is what opens it, so the+// query keeps asking while the app is up: a poll between charges, and a+// refetch when the tab comes back.+export function useSubscribeBonus(options: { enabled?: boolean } = {}) {+ return useQuery({+ enabled: options.enabled ?? true,+ queryFn: () => apiFetch<{ offer: SubscribeBonus | null }>("/api/credits/subscribe-bonus"),+ queryKey: subscribeBonusQueryKey,+ refetchInterval: 60_000,+ refetchOnWindowFocus: true,+ select: (data) => data.offer,+ });+}+export function useAccount() {return useQuery({queryFn: () => apiFetch<Account>("/api/account/me"),