Skip to content

Open source CapCut alternative.

TypeScript

feat(site): offer an su-set intro discount on Pro

David Le529868885304
diff --git a/site/src/app/api/billing/checkout/route.ts b/site/src/app/api/billing/checkout/route.ts
index b07b8379..ea85b382 100644
--- a/site/src/app/api/billing/checkout/route.ts
+++ b/site/src/app/api/billing/checkout/route.ts
@@ -2,8 +2,11 @@ import { NextResponse } from "next/server";
import { z } from "zod";
import { auth } from "@/lib/auth";
+import { introCouponId } from "@/lib/billing/intro-offer";
+import { introCoupon, readIntroOffer } from "@/lib/billing/intro-offer-server";
import { proPriceId } from "@/lib/billing/pro-subscription";
import { ensureStripeCustomer, getStripe } from "@/lib/billing/stripe";
+import { contextFromRequest } from "@/lib/config/effective";
import { verifyCreditOfferToken } from "@/lib/credits/offers";
import { openOfferForSubscribing, SUBSCRIBE_BONUS_METADATA_KEY } from "@/lib/credits/subscribe-bonus-claim";
import {
@@ -46,10 +49,16 @@ export const POST = withDonkeyAuth(async (request) => {
// A checkout started while an offer for subscribing is open carries the
// offer, so the webhook lands the credit on the subscription it creates.
const offer = await openOfferForSubscribing(session.user.id, namedOfferId);
+ // An account inside its intro window checks out with the discount already
+ // on. Stripe takes either a discount or a promotion code field, never both.
+ const intro = await readIntroOffer(await contextFromRequest(request));
+ const pricing = intro
+ ? { discounts: [{ coupon: await introCoupon(intro) }] }
+ : { allow_promotion_codes: true };
const stripe = getStripe();
const origin = request.nextUrl.origin;
const checkout = await stripe.checkout.sessions.create({
- allow_promotion_codes: true,
+ ...pricing,
cancel_url: `${origin}/app/settings?checkout=cancelled`,
client_reference_id: session.user.id,
customer: customerId,
@@ -59,6 +68,7 @@ export const POST = withDonkeyAuth(async (request) => {
metadata: {
userId: session.user.id,
...(offer ? { [SUBSCRIBE_BONUS_METADATA_KEY]: offer.id } : {}),
+ ...(intro ? { introOffer: introCouponId(intro) } : {}),
},
},
success_url: `${origin}/app/settings?checkout=success`,
diff --git a/site/src/app/api/billing/intro-offer/route.ts b/site/src/app/api/billing/intro-offer/route.ts
new file mode 100644
index 00000000..375a3571
--- /dev/null
+++ b/site/src/app/api/billing/intro-offer/route.ts
@@ -0,0 +1,26 @@
+import { NextResponse } from "next/server";
+
+import { introPriceCents } from "@/lib/billing/intro-offer";
+import { readIntroOffer, readProPriceCents } from "@/lib/billing/intro-offer-server";
+import { contextFromRequest } from "@/lib/config/effective";
+import { withDonkeyAuth } from "@/lib/donkey-api-auth";
+
+// The intro offer open to the caller, priced, for the surfaces that sell Pro.
+// The checkout reads the same offer and applies it.
+export const GET = withDonkeyAuth(async (request) => {
+ const offer = await readIntroOffer(await contextFromRequest(request));
+ if (!offer) {
+ return NextResponse.json({ offer: null });
+ }
+
+ const priceCents = await readProPriceCents();
+ return NextResponse.json({
+ offer: {
+ endsAt: offer.endsAt.toISOString(),
+ introCents: introPriceCents(priceCents, offer.percentOff),
+ months: offer.months,
+ percentOff: offer.percentOff,
+ priceCents,
+ },
+ });
+});
diff --git a/site/src/app/cut/app/(home)/settings/_components/ProCard.tsx b/site/src/app/cut/app/(home)/settings/_components/ProCard.tsx
index 47dee8f0..a5ef2a31 100644
--- a/site/src/app/cut/app/(home)/settings/_components/ProCard.tsx
+++ b/site/src/app/cut/app/(home)/settings/_components/ProCard.tsx
@@ -1,6 +1,7 @@
"use client";
import {
+ useIntroOffer,
useOpenBillingPortal,
useProSubscription,
useStartCheckout,
@@ -17,6 +18,7 @@ import {
} from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { activeProPromotion, CUT_PRO } from "@/app/cut/_components/landing/cutPricingPlans";
+import { introTerms } from "@/cut/components/IntroOffer";
import { creditLifeClause, formatDeadline, minutesLeft } from "@/cut/components/SubscribeBonusPill";
import { track } from "@/lib/analytics";
import { creditCountLabel, creditsFromDollars, creditsPerDollar, formatCreditCount, formatCredits } from "@/lib/credits/format-credits";
@@ -44,6 +46,7 @@ export function ProCard() {
const bonus = useSubscribeBonus();
const config = useAccountConfig({ enabled: true });
const promotion = config.data ? activeProPromotion(config.data.settings.proAllowancePromotion) : null;
+ const intro = useIntroOffer({ enabled: pro.data?.isActive === false });
if (pro.isLoading) {
return (
@@ -133,6 +136,11 @@ export function ProCard() {
{formatCredits(offer.dollars)}.{creditLifeClause(offer)}
</CardContent>
) : null}
+ {intro.data && !isActive ? (
+ <CardContent className="text-sm text-foreground">
+ {introTerms(intro.data)} Subscribe by {formatDeadline(intro.data.endsAt)}.
+ </CardContent>
+ ) : null}
<CardFooter className="gap-3">
{isActive ? (
<Button
diff --git a/site/src/cut/components/IntroOffer.tsx b/site/src/cut/components/IntroOffer.tsx
new file mode 100644
index 00000000..ddb59bee
--- /dev/null
+++ b/site/src/cut/components/IntroOffer.tsx
@@ -0,0 +1,38 @@
+"use client";
+
+// The intro discount as every Pro surface states it: the terms in one line,
+// and a wall's banner that becomes the offer's picture while it is open.
+import type { LucideIcon } from "lucide-react";
+
+import type { OfferBanner } from "@/cut/components/OfferDialog";
+import type { IntroOffer } from "@/queries/billing";
+
+/** Cents as a price reads: 1000 → "$10", 999 → "$9.99". */
+export function priceLabel(cents: number): string {
+ return cents % 100 === 0 ? `$${cents / 100}` : `$${(cents / 100).toFixed(2)}`;
+}
+
+/** "$10 for your first month" or "$10/month for your first 3 months". */
+export function introPrice(offer: IntroOffer): string {
+ const price = priceLabel(offer.introCents);
+ return offer.months === 1 ? `${price} for your first month` : `${price}/month for your first ${offer.months} months`;
+}
+
+/** "50% off: $10 for your first month, then $20/month." */
+export function introTerms(offer: IntroOffer): string {
+ return `${offer.percentOff}% off: ${introPrice(offer)}, then ${priceLabel(offer.priceCents)}/month.`;
+}
+
+/** A wall's banner: a quiet bar with the wall's icon, half the height of an
+ * offer's picture. With an offer open the wall is a promotion, so it takes
+ * the offer's picture and the countdown over it. */
+export function wallBanner(Icon: LucideIcon, offer: IntroOffer | null | undefined): OfferBanner | React.ReactNode {
+ if (offer) {
+ return "subscribe";
+ }
+ return (
+ <div className="flex aspect-[16/3] w-full items-center bg-neutral-800 px-6 dark:bg-neutral-700">
+ <Icon className="size-7 text-white" strokeWidth={1.5} />
+ </div>
+ );
+}
diff --git a/site/src/cut/components/OfferDialog.tsx b/site/src/cut/components/OfferDialog.tsx
index a2863cd5..a30a86f0 100644
--- a/site/src/cut/components/OfferDialog.tsx
+++ b/site/src/cut/components/OfferDialog.tsx
@@ -73,8 +73,8 @@ export function countdownLabel(closesAt: string, now: number): string {
return `${hours}h ${two(minutes)}m ${two(seconds)}s`;
}
-/** The clock the countdown reads; one tick a second while the card is open. */
-function useNow(): number {
+/** The clock a countdown reads; one tick a second while it is on screen. */
+export function useNow(): number {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const id = setInterval(() => setNow(Date.now()), 1000);
diff --git a/site/src/cut/components/StorageUpgradeDialog.tsx b/site/src/cut/components/StorageUpgradeDialog.tsx
index fa60f390..90559e75 100644
--- a/site/src/cut/components/StorageUpgradeDialog.tsx
+++ b/site/src/cut/components/StorageUpgradeDialog.tsx
@@ -13,6 +13,7 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
+import { introTerms, wallBanner } from "./IntroOffer";
import { OfferButton, OfferDialog, OfferDismiss } from "./OfferDialog";
import { useUpgradeToPro } from "@/cut/lib/proUpgrade";
import {
@@ -23,7 +24,7 @@ import {
} from "@/cut/lib/storageQuota";
import { daysUntil } from "@/cut/lib/time";
import { track } from "@/lib/analytics";
-import { useProSubscription } from "@/queries/billing";
+import { useIntroOffer, useProSubscription } from "@/queries/billing";
import { useCloudUsage } from "@/cut/lib/backend/hooks";
import { onOperationFailure } from "@/cut/lib/operationFailure";
import { formatBytes } from "@/lib/bytes";
@@ -59,6 +60,7 @@ function OpenDialog({ detail, onClose }: { detail: StorageQuotaDetail; onClose:
const pro = useProSubscription();
const upgrade = useUpgradeToPro();
const isPro = pro.data?.isActive === true;
+ const intro = useIntroOffer({ enabled: pro.data?.isActive === false });
// A wall raised by a queued render carries no numbers — it failed in the
// worker, hours from the request. The account's own meter fills them in, so
// every wall says how full the account is.
@@ -107,16 +109,11 @@ function OpenDialog({ detail, onClose }: { detail: StorageQuotaDetail; onClose:
<OfferDialog
open
onOpenChange={(open) => !open && onClose()}
- // Neutral, and half the height of a credit offer's picture: this card is
- // a wall, not a promotion.
- banner={
- <div className="flex aspect-[16/3] w-full items-center bg-neutral-800 px-6 dark:bg-neutral-700">
- <HardDrive className="size-7 text-white" strokeWidth={1.5} />
- </div>
- }
+ banner={wallBanner(HardDrive, intro.data)}
+ closesAt={intro.data?.endsAt}
title={title}
body={`${used ? `${used} ` : ""}Pro includes 100 GB of cloud storage.`}
- terms="Or free up space by deleting projects and media you no longer need."
+ terms={intro.data ? introTerms(intro.data) : "Or free up space by deleting projects and media you no longer need."}
error={grace}
cta={
<OfferButton disabled={upgrade.isPending} onClick={upgrade.start}>
diff --git a/site/src/cut/components/onboarding/slides/Plans.tsx b/site/src/cut/components/onboarding/slides/Plans.tsx
index 944ab5cc..ca0d2a7a 100644
--- a/site/src/cut/components/onboarding/slides/Plans.tsx
+++ b/site/src/cut/components/onboarding/slides/Plans.tsx
@@ -5,7 +5,10 @@ import { Check } from "lucide-react";
import { TapedCard } from "@/app/_components/landing/LandingPrimitives";
import { CUT_PRO } from "@/app/cut/_components/landing/cutPricingPlans";
import { Button } from "@/components/ui/button";
+import { priceLabel } from "@/cut/components/IntroOffer";
+import { countdownLabel, useNow } from "@/cut/components/OfferDialog";
import { useUpgradeToPro } from "@/cut/lib/proUpgrade";
+import { useIntroOffer, type IntroOffer } from "@/queries/billing";
import "../onboarding.css";
@@ -13,9 +16,11 @@ import "../onboarding.css";
// benefits sit in the card so nobody has to take the price on faith. It's the
// landing's own Pro card — same taped coral frame, same ringed check bullets —
// so the offer looks the same wherever it's met. Checkout is the one the
-// storage wall and the billing page start.
+// storage wall and the billing page start. While the intro offer is open the
+// card prices the discount and counts down to its end.
export function PlansSlide({ onSkipPro }: { onSkipPro: () => void }) {
const pro = useUpgradeToPro();
+ const offer = useIntroOffer().data ?? null;
return (
<div className="mx-auto w-full max-w-[520px]">
@@ -35,12 +40,18 @@ export function PlansSlide({ onSkipPro }: { onSkipPro: () => void }) {
>
<div className="p-7 md:p-9">
<div className="text-[22px] font-semibold">Pro</div>
- <div className="mt-4 text-[clamp(34px,4.4vw,48px)] leading-[0.95] font-semibold">
- {CUT_PRO.price}
- </div>
- <div className="mt-2.5 text-[13px] font-semibold text-[#201715]">
- For individuals
- </div>
+ {offer ? (
+ <IntroPrice offer={offer} />
+ ) : (
+ <>
+ <div className="mt-4 text-[clamp(34px,4.4vw,48px)] leading-[0.95] font-semibold">
+ {CUT_PRO.price}
+ </div>
+ <div className="mt-2.5 text-[13px] font-semibold text-[#201715]">
+ For individuals
+ </div>
+ </>
+ )}
<p className="mt-5 text-[15px] leading-[1.55] text-[#1a1a1a]">
{CUT_PRO.body}
</p>
@@ -64,7 +75,7 @@ export function PlansSlide({ onSkipPro }: { onSkipPro: () => void }) {
disabled={pro.isPending}
className="mt-7 h-11 rounded-full bg-ink px-6 text-[15px] text-white hover:bg-ink/90"
>
- Get Pro
+ {offer ? `Get ${offer.percentOff}% off Pro` : "Get Pro"}
</Button>
</div>
</TapedCard>
@@ -82,3 +93,29 @@ export function PlansSlide({ onSkipPro }: { onSkipPro: () => void }) {
</div>
);
}
+
+// The discounted price beside the struck-through one, what it covers, and
+// the time left to take it.
+function IntroPrice({ offer }: { offer: IntroOffer }) {
+ const now = useNow();
+ const covers = offer.months === 1 ? "For your first month" : `Per month for your first ${offer.months} months`;
+
+ return (
+ <>
+ <div className="mt-4 flex items-baseline gap-3">
+ <span className="text-[clamp(34px,4.4vw,48px)] leading-[0.95] font-semibold">
+ {priceLabel(offer.introCents)}
+ </span>
+ <span className="text-[22px] font-semibold text-[#201715]/40 line-through decoration-2">
+ {priceLabel(offer.priceCents)}
+ </span>
+ </div>
+ <div className="mt-2.5 text-[13px] font-semibold text-[#201715]">
+ {covers}, then {priceLabel(offer.priceCents)}/month
+ </div>
+ <div className="mt-4 inline-flex rounded-full bg-ink px-3 py-1 text-[12px] font-semibold text-white tabular-nums">
+ {offer.percentOff}% off ends in {countdownLabel(offer.endsAt, now)}
+ </div>
+ </>
+ );
+}
diff --git a/site/src/lib/billing/intro-offer-server.ts b/site/src/lib/billing/intro-offer-server.ts
new file mode 100644
index 00000000..16b069c7
--- /dev/null
+++ b/site/src/lib/billing/intro-offer-server.ts
@@ -0,0 +1,80 @@
+import Stripe from "stripe";
+
+import { proPriceId } from "@/lib/billing/pro-subscription";
+import { getStripe } from "@/lib/billing/stripe";
+import { getSetting, type ConfigContext } from "@/lib/config/effective";
+import { prisma } from "@/lib/prisma";
+
+import { heldPro, introCouponId, introOfferAt, type IntroOffer } from "./intro-offer";
+
+/** The intro offer open to this account right now, or null. */
+export async function readIntroOffer(ctx: ConfigContext, now = new Date()): Promise<IntroOffer | null> {
+ if (!ctx.hasAccount) {
+ return null;
+ }
+
+ const [setting, subscription] = await Promise.all([
+ getSetting("introOffer", ctx),
+ prisma.proSubscription.findUnique({ where: { userId: ctx.userId }, select: { status: true } }),
+ ]);
+ return introOfferAt(setting, { createdAt: ctx.createdAt, heldPro: heldPro(subscription?.status ?? null) }, now);
+}
+
+const stripeCode = (e: unknown) => (e instanceof Stripe.errors.StripeError ? e.code : undefined);
+
+/** The coupon for an offer's terms, created the first time a checkout needs
+ * it. Two checkouts racing to create it both end on the same coupon. */
+export async function introCoupon(offer: IntroOffer): Promise<string> {
+ const stripe = getStripe();
+ const id = introCouponId(offer);
+
+ try {
+ await stripe.coupons.retrieve(id);
+ return id;
+ } catch (e) {
+ if (stripeCode(e) !== "resource_missing") {
+ throw e;
+ }
+ }
+
+ try {
+ await stripe.coupons.create({
+ duration: "repeating",
+ duration_in_months: offer.months,
+ id,
+ name: `Intro ${offer.percentOff}% off`,
+ percent_off: offer.percentOff,
+ });
+ } catch (e) {
+ if (stripeCode(e) !== "resource_already_exists") {
+ throw e;
+ }
+ }
+ return id;
+}
+
+// The Pro price's amount never changes under a price id, so one read per
+// process serves every offer.
+let proPriceCents: Promise<number> | null = null;
+
+/** The Pro price in cents, as Stripe holds it. */
+export function readProPriceCents(): Promise<number> {
+ const priceId = proPriceId();
+ if (!priceId) {
+ throw new Error("STRIPE_PRO_PRICE_ID is not set");
+ }
+
+ proPriceCents ??= getStripe()
+ .prices.retrieve(priceId)
+ .then((price) => {
+ if (typeof price.unit_amount !== "number") {
+ throw new Error(`Pro price ${priceId} has no unit amount`);
+ }
+ return price.unit_amount;
+ })
+ .catch((e: unknown) => {
+ proPriceCents = null;
+ throw e;
+ });
+ return proPriceCents;
+}
diff --git a/site/src/lib/billing/intro-offer.test.ts b/site/src/lib/billing/intro-offer.test.ts
new file mode 100644
index 00000000..31fb1dd3
--- /dev/null
+++ b/site/src/lib/billing/intro-offer.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, test } from "bun:test";
+
+import { heldPro, introCouponId, introOfferAt, introPriceCents } from "./intro-offer";
+
+const HOUR_MS = 3_600_000;
+const signup = new Date("2026-10-16T12:00:00Z");
+const setting = { percentOff: 50, months: 1, windowHours: 24 };
+const fresh = { createdAt: signup, heldPro: false };
+
+describe("introOfferAt", () => {
+ test("opens inside the window and closes at its end", () => {
+ const offer = introOfferAt(setting, fresh, new Date(signup.getTime() + HOUR_MS));
+ expect(offer).toEqual({ percentOff: 50, months: 1, endsAt: new Date(signup.getTime() + 24 * HOUR_MS) });
+ expect(introOfferAt(setting, fresh, new Date(signup.getTime() + 24 * HOUR_MS))).toBeNull();
+ });
+
+ test("makes no offer at 0 percent, the default", () => {
+ expect(introOfferAt({ ...setting, percentOff: 0 }, fresh, signup)).toBeNull();
+ });
+
+ test("makes no offer to an account that held Pro", () => {
+ expect(introOfferAt(setting, { ...fresh, heldPro: true }, signup)).toBeNull();
+ });
+});
+
+describe("heldPro", () => {
+ test("a checkout that never paid held nothing", () => {
+ expect(heldPro(null)).toBe(false);
+ expect(heldPro("incomplete")).toBe(false);
+ expect(heldPro("incomplete_expired")).toBe(false);
+ expect(heldPro("canceled")).toBe(true);
+ expect(heldPro("active")).toBe(true);
+ });
+});
+
+test("one coupon per pair of terms", () => {
+ expect(introCouponId({ percentOff: 50, months: 1 })).toBe("donkey-intro-50-1m");
+ expect(introCouponId({ percentOff: 25, months: 3 })).toBe("donkey-intro-25-3m");
+});
+
+test("the intro price rounds to the cent", () => {
+ expect(introPriceCents(2000, 50)).toBe(1000);
+ expect(introPriceCents(1999, 33)).toBe(1339);
+});
diff --git a/site/src/lib/billing/intro-offer.ts b/site/src/lib/billing/intro-offer.ts
new file mode 100644
index 00000000..ccb99eda
--- /dev/null
+++ b/site/src/lib/billing/intro-offer.ts
@@ -0,0 +1,55 @@
+// The intro offer, as the introOffer setting states it: a percent off the
+// first months of Pro for an account that subscribes within a window after
+// signup and has never held Pro. Pure, so the checkout, the offer read and
+// the tests share one rule.
+
+export type IntroOfferSetting = {
+ percentOff: number;
+ months: number;
+ windowHours: number;
+};
+
+export type IntroOffer = {
+ percentOff: number;
+ months: number;
+ endsAt: Date;
+};
+
+const HOUR_MS = 3_600_000;
+
+// Subscription rows a checkout leaves behind when payment never went
+// through; they never held Pro.
+const NEVER_PAID_STATUSES = new Set(["incomplete", "incomplete_expired"]);
+
+/** Whether a stored subscription status means the account once held Pro. */
+export function heldPro(status: string | null): boolean {
+ return status !== null && !NEVER_PAID_STATUSES.has(status);
+}
+
+/** The offer open to an account right now, or null. */
+export function introOfferAt(
+ setting: IntroOfferSetting,
+ facts: { createdAt: Date; heldPro: boolean },
+ now: Date,
+): IntroOffer | null {
+ if (setting.percentOff <= 0 || facts.heldPro) {
+ return null;
+ }
+
+ const endsAt = new Date(facts.createdAt.getTime() + setting.windowHours * HOUR_MS);
+ if (now.getTime() >= endsAt.getTime()) {
+ return null;
+ }
+ return { percentOff: setting.percentOff, months: setting.months, endsAt };
+}
+
+/** The Stripe coupon id for an offer's terms. One coupon per pair of terms,
+ * so changing the setting needs no step in the Stripe dashboard. */
+export function introCouponId(offer: Pick<IntroOffer, "percentOff" | "months">): string {
+ return `donkey-intro-${offer.percentOff}-${offer.months}m`;
+}
+
+/** The discounted price, in cents, rounded the way Stripe rounds it. */
+export function introPriceCents(priceCents: number, percentOff: number): number {
+ return Math.round((priceCents * (100 - percentOff)) / 100);
+}
diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.ts
index 2afdf928..11c870dd 100644
--- a/site/src/lib/config/registry.ts
+++ b/site/src/lib/config/registry.ts
@@ -571,6 +571,49 @@ export const SETTINGS = defineSettings({
description:
"How many days before a cancelled Pro plan ends the editor starts showing the days left. Until then a plan set to cancel looks like one that renews.",
},
+ introOffer: {
+ schema: z
+ .object({
+ // Percent off the Pro price; 0 makes no offer.
+ percentOff: z.number().int().min(0).max(90),
+ // Billing months the discount covers.
+ months: z.number().int().min(1).max(12),
+ // Hours after signup the offer stays open.
+ windowHours: z.number().int().min(1).max(24 * 30),
+ })
+ .strict(),
+ default: { percentOff: 0, months: 1, windowHours: 24 },
+ public: true,
+ title: "Intro offer",
+ description:
+ "A discount on the first months of Pro for an account that subscribes within this many hours of signing up and has never held Pro. Checkout applies it on its own.",
+ },
+ freeProjectLimit: {
+ schema: z
+ .object({
+ // Projects a free account may hold besides its starter; null is no limit.
+ projects: z.number().int().min(0).max(1000).nullable(),
+ })
+ .strict(),
+ default: { projects: null },
+ public: true,
+ title: "Free project limit",
+ description:
+ "How many projects a free account may hold besides its starter project. Creating one more opens the upgrade dialog.",
+ },
+ outOfCreditsUpsell: {
+ schema: z
+ .object({
+ // "dialog" opens the upgrade dialog when a request runs out of credits.
+ mode: z.enum(["off", "dialog"]),
+ })
+ .strict(),
+ default: { mode: "off" },
+ public: true,
+ title: "Out of credits upsell",
+ description:
+ "What happens when an AI request runs out of credits. Off leaves the inline notice; dialog also opens the upgrade dialog, which sells Pro to a free account and credits to a Pro one.",
+ },
});
export type SettingKey = keyof typeof SETTINGS;
diff --git a/site/src/queries/billing.ts b/site/src/queries/billing.ts
index 1819cf94..dbe7fe48 100644
--- a/site/src/queries/billing.ts
+++ b/site/src/queries/billing.ts
@@ -6,6 +6,7 @@ import { apiFetch } from "@/queries/apiClient";
export const usageQueryKey = ["billing", "usage"] as const;
export const proSubscriptionQueryKey = ["billing", "pro"] as const;
+export const introOfferQueryKey = ["billing", "intro-offer"] as const;
export type ProSubscription = {
isActive: boolean;
@@ -20,13 +21,36 @@ export type ProSubscription = {
allowanceRemaining: string;
};
+export const fetchProSubscription = () => apiFetch<ProSubscription>("/api/billing/pro");
+
export function useProSubscription() {
return useQuery({
- queryFn: () => apiFetch<ProSubscription>("/api/billing/pro"),
+ queryFn: fetchProSubscription,
queryKey: proSubscriptionQueryKey,
});
}
+export type IntroOffer = {
+ percentOff: number;
+ months: number;
+ // When the offer closes.
+ endsAt: string;
+ // The Pro price and what the discounted months cost.
+ priceCents: number;
+ introCents: number;
+};
+
+// The discount an account inside its intro window gets on Pro. Checkout
+// applies it on its own; this read is for the surfaces that show it.
+export function useIntroOffer({ enabled = true }: { enabled?: boolean } = {}) {
+ return useQuery({
+ enabled,
+ queryFn: async () => (await apiFetch<{ offer: IntroOffer | null }>("/api/billing/intro-offer")).offer,
+ queryKey: introOfferQueryKey,
+ staleTime: 5 * 60_000,
+ });
+}
+
export type UsageHistory = {
// Recent credit-billed inference calls, newest first.
recent: {