Skip to content

Open source CapCut alternative.

TypeScript

fix(site): paint the intro offer with its card

David Le77c70c33bde4
diff --git a/site/src/app/api/billing/intro-offer/route.ts b/site/src/app/api/billing/intro-offer/route.ts
index 4f6ae472..2ce7362e 100644
--- a/site/src/app/api/billing/intro-offer/route.ts
+++ b/site/src/app/api/billing/intro-offer/route.ts
@@ -1,27 +1,37 @@
import { NextResponse } from "next/server";
import { introPriceCents } from "@/lib/billing/intro-offer";
-import { openIntroOffer, readProPriceCents } from "@/lib/billing/intro-offer-server";
+import { openIntroOffer, previewIntroOffer, readProPriceCents } from "@/lib/billing/intro-offer-server";
import { contextFromRequest } from "@/lib/config/effective";
import { withDonkeyAuth } from "@/lib/donkey-api-auth";
-// The intro offer, priced, for a surface that sells Pro and is showing it.
-// The first call starts the offer's window, so it is a POST. The checkout
-// reads the same offer and applies it.
-export const POST = withDonkeyAuth(async (request) => {
- const offer = await openIntroOffer(await contextFromRequest(request));
- if (!offer) {
- return NextResponse.json({ offer: null });
- }
+// The intro offer, priced. The app loads it with GET as it starts, which
+// never starts the offer's window, so a card that sells Pro paints with the
+// offer on its first frame. The surface showing it then POSTs, and the first
+// POST starts the window. The checkout reads the same offer and applies it.
+// The offer on the wire. endsAt is null for a window that starts the moment
+// a surface first shows it, and runs windowHours from there.
+async function priced(offer: { percentOff: number; months: number; endsAt: Date | null; windowHours: number }) {
const priceCents = await readProPriceCents();
- return NextResponse.json({
- offer: {
- endsAt: offer.endsAt.toISOString(),
- introCents: introPriceCents(priceCents, offer.percentOff),
- months: offer.months,
- percentOff: offer.percentOff,
- priceCents,
- },
- });
+ return {
+ endsAt: offer.endsAt?.toISOString() ?? null,
+ introCents: introPriceCents(priceCents, offer.percentOff),
+ months: offer.months,
+ percentOff: offer.percentOff,
+ priceCents,
+ windowHours: offer.windowHours,
+ };
+}
+
+export const GET = withDonkeyAuth(async (request) => {
+ const offer = await previewIntroOffer(await contextFromRequest(request));
+ return NextResponse.json({ offer: offer ? await priced(offer) : null });
+});
+
+// Starts the window, the first time, and answers when it ends; null when no
+// offer is open.
+export const POST = withDonkeyAuth(async (request) => {
+ const offer = await openIntroOffer(await contextFromRequest(request));
+ return NextResponse.json({ endsAt: offer?.endsAt.toISOString() ?? null });
});
diff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsx
index 405e33ba..4297dce6 100644
--- a/site/src/cut/components/RequireSession.tsx
+++ b/site/src/cut/components/RequireSession.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useQueryClient } from "@tanstack/react-query";
import { useEffect, type ReactNode } from "react";
import { useEnvironment } from "@/cut/lib/environment";
import { EmbeddedSignInFallback } from "@/cut/components/EmbeddedSignInFallback";
@@ -15,6 +16,7 @@ import {
import { reportExposures, useAppLoaded } from "@/lib/analytics";
import { useSession } from "@/lib/auth-client";
import { useAccountConfig } from "@/queries/accountConfig";
+import { prefetchIntroOffer } from "@/queries/billing";
import { useNoteOutboxSync } from "@/cut/hooks/useNoteOutboxSync";
// Session gate for the whole Cut app surface. The landing CTAs already route
@@ -61,6 +63,14 @@ export function RequireSession({ children }: { children: ReactNode }) {
reportExposures(config.data);
}, [userId, config.data]);
+ // The intro offer, loaded with the account so every card that sells Pro
+ // has it on its first frame. Loading it starts no window.
+ const queryClient = useQueryClient();
+ useEffect(() => {
+ if (!userId) return;
+ void prefetchIntroOffer(queryClient);
+ }, [userId, queryClient]);
+
// Paint first, verify behind: the account remembered from the last visit
// opens the gate immediately, so a reload shows cached shelves while the
// session request is still in flight. The resolved session overrides it —
diff --git a/site/src/cut/components/onboarding/slides/Plans.tsx b/site/src/cut/components/onboarding/slides/Plans.tsx
index 06698a7d..2c51826d 100644
--- a/site/src/cut/components/onboarding/slides/Plans.tsx
+++ b/site/src/cut/components/onboarding/slides/Plans.tsx
@@ -65,8 +65,10 @@ export function PlansSlide({ run, exit, onSkipPro }: { run: OnboardingRun; exit:
slide's gutter to the screen edge so the next card peeks in on the
right, and the top padding keeps the tape and offer sticker. The
recommended plan comes first so it is the one on screen when the
- slide opens. */}
- <div className="-mx-6 mt-3 flex scroll-px-6 snap-x snap-mandatory gap-4 overflow-x-auto px-6 pt-5 pb-3 [scrollbar-width:none] md:mx-0 md:mt-8 md:grid md:grid-cols-3 md:items-stretch md:gap-5 md:overflow-visible md:p-0 [&::-webkit-scrollbar]:hidden">
+ slide opens. The row holds until the offer read settles, which the
+ app has normally done long before this slide, so the Pro card never
+ paints a price the offer then replaces. */}
+ <div aria-busy={intro.isPending} className={cn(intro.isPending && "invisible", "-mx-6 mt-3 flex scroll-px-6 snap-x snap-mandatory gap-4 overflow-x-auto px-6 pt-5 pb-3 [scrollbar-width:none] md:mx-0 md:mt-8 md:grid md:grid-cols-3 md:items-stretch md:gap-5 md:overflow-visible md:p-0 [&::-webkit-scrollbar]:hidden")}>
{plans.map((copy) => (
<div
key={copy.plan}
diff --git a/site/src/lib/billing/intro-offer-server.ts b/site/src/lib/billing/intro-offer-server.ts
index 4441cbf8..6a0bf6b8 100644
--- a/site/src/lib/billing/intro-offer-server.ts
+++ b/site/src/lib/billing/intro-offer-server.ts
@@ -5,7 +5,17 @@ import { getStripe } from "@/lib/billing/stripe";
import { getSetting, type ConfigContext } from "@/lib/config/effective";
import { prisma } from "@/lib/prisma";
-import { heldPro, introCouponId, introOfferAt, offersIntro, type IntroOffer } from "./intro-offer";
+import { heldPro, introCouponId, introOfferAt, introOfferPreview, offersIntro, type IntroOffer } from "./intro-offer";
+
+// The setting and what the account has done, for the reads below.
+async function introFacts(ctx: ConfigContext) {
+ const [setting, subscription, view] = await Promise.all([
+ getSetting("introOffer", ctx),
+ prisma.proSubscription.findUnique({ where: { userId: ctx.userId }, select: { status: true } }),
+ prisma.introOfferView.findUnique({ where: { userId: ctx.userId }, select: { seenAt: true } }),
+ ]);
+ return { setting, facts: { seenAt: view?.seenAt ?? null, heldPro: heldPro(subscription?.status ?? null) } };
+}
/** The intro offer open to this account right now, or null. Reading never
* starts the window; checkout reads it this way. */
@@ -13,17 +23,18 @@ export async function readIntroOffer(ctx: ConfigContext, now = new Date()): Prom
if (!ctx.hasAccount) {
return null;
}
+ const { setting, facts } = await introFacts(ctx);
+ return introOfferAt(setting, facts, now);
+}
- const [setting, subscription, view] = await Promise.all([
- getSetting("introOffer", ctx),
- prisma.proSubscription.findUnique({ where: { userId: ctx.userId }, select: { status: true } }),
- prisma.introOfferView.findUnique({ where: { userId: ctx.userId }, select: { seenAt: true } }),
- ]);
- return introOfferAt(
- setting,
- { seenAt: view?.seenAt ?? null, heldPro: heldPro(subscription?.status ?? null) },
- now,
- );
+/** The offer as the app loads it ahead of any surface, which never starts
+ * the window; see introOfferPreview. */
+export async function previewIntroOffer(ctx: ConfigContext, now = new Date()) {
+ if (!ctx.hasAccount) {
+ return null;
+ }
+ const { setting, facts } = await introFacts(ctx);
+ return introOfferPreview(setting, facts, now);
}
/** The offer for a surface about to show it. The first time an account the
diff --git a/site/src/lib/billing/intro-offer.test.ts b/site/src/lib/billing/intro-offer.test.ts
index 6bbbdb90..cd71e8aa 100644
--- a/site/src/lib/billing/intro-offer.test.ts
+++ b/site/src/lib/billing/intro-offer.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test";
-import { heldPro, introCouponId, introOfferAt, introPriceCents, offersIntro } from "./intro-offer";
+import { heldPro, introCouponId, introOfferAt, introOfferPreview, introPriceCents, offersIntro } from "./intro-offer";
const HOUR_MS = 3_600_000;
const seen = new Date("2026-10-16T12:00:00Z");
@@ -54,3 +54,30 @@ test("the intro price rounds to the cent", () => {
expect(introPriceCents(2000, 50)).toBe(1000);
expect(introPriceCents(1999, 33)).toBe(1339);
});
+
+describe("introOfferPreview", () => {
+ const setting = { percentOff: 50, months: 1, windowHours: 73 };
+ const now = new Date("2026-10-29T00:00:00Z");
+
+ test("an account that has not seen it gets the terms with the window unstarted", () => {
+ expect(introOfferPreview(setting, { seenAt: null, heldPro: false }, now)).toEqual({
+ percentOff: 50,
+ months: 1,
+ windowHours: 73,
+ endsAt: null,
+ });
+ });
+
+ test("an account inside its window gets the window's end", () => {
+ const seenAt = new Date("2026-10-28T00:00:00Z");
+ expect(introOfferPreview(setting, { seenAt, heldPro: false }, now)?.endsAt).toEqual(
+ new Date("2026-10-31T01:00:00Z"),
+ );
+ });
+
+ test("a closed window, a past subscriber, or no offer is null", () => {
+ expect(introOfferPreview(setting, { seenAt: new Date("2026-10-01T00:00:00Z"), heldPro: false }, now)).toBeNull();
+ expect(introOfferPreview(setting, { seenAt: null, heldPro: true }, now)).toBeNull();
+ expect(introOfferPreview({ ...setting, percentOff: 0 }, { seenAt: null, heldPro: false }, now)).toBeNull();
+ });
+});
diff --git a/site/src/lib/billing/intro-offer.ts b/site/src/lib/billing/intro-offer.ts
index f1e9e663..562beb7a 100644
--- a/site/src/lib/billing/intro-offer.ts
+++ b/site/src/lib/billing/intro-offer.ts
@@ -49,6 +49,26 @@ export function introOfferAt(
return { percentOff: setting.percentOff, months: setting.months, endsAt };
}
+/** The offer as a surface may show it before it is opened: the open window
+ * when the account has seen it, or a window not yet started (endsAt null),
+ * which runs `windowHours` from the moment a surface first shows it. Null
+ * when no offer is or will be open. */
+export function introOfferPreview(
+ setting: IntroOfferSetting,
+ facts: { seenAt: Date | null; heldPro: boolean },
+ now: Date,
+): (Omit<IntroOffer, "endsAt"> & { endsAt: Date | null; windowHours: number }) | null {
+ if (!offersIntro(setting, facts)) {
+ return null;
+ }
+ const terms = { percentOff: setting.percentOff, months: setting.months, windowHours: setting.windowHours };
+ if (!facts.seenAt) {
+ return { ...terms, endsAt: null };
+ }
+ const open = introOfferAt(setting, facts, now);
+ return open ? { ...terms, endsAt: open.endsAt } : null;
+}
+
/** 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 {
diff --git a/site/src/queries/billing.ts b/site/src/queries/billing.ts
index 31455c16..ba999874 100644
--- a/site/src/queries/billing.ts
+++ b/site/src/queries/billing.ts
@@ -1,6 +1,7 @@
"use client";
-import { useMutation, useQuery } from "@tanstack/react-query";
+import { useMutation, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";
+import { useEffect, useState } from "react";
import type { PaidPlan } from "@/lib/billing/plans";
import { apiFetch } from "@/queries/apiClient";
@@ -45,17 +46,62 @@ export type IntroOffer = {
introCents: number;
};
+// The offer as the app loads it: endsAt is null while the window has not
+// started, and it runs windowHours from the moment a surface first shows it.
+type IntroOfferRead = Omit<IntroOffer, "endsAt"> & { endsAt: string | null; windowHours: number };
+
+const INTRO_OFFER_URL = "/api/billing/intro-offer";
+const INTRO_STALE_MS = 5 * 60_000;
+const HOUR_MS = 3_600_000;
+
+const fetchIntroOffer = async () => (await apiFetch<{ offer: IntroOfferRead | null }>(INTRO_OFFER_URL)).offer;
+
+/** Load the offer as the app starts, ahead of every surface that shows it,
+ * so a card selling Pro paints with it on its first frame. Reading starts
+ * nothing. */
+export function prefetchIntroOffer(client: QueryClient): Promise<void> {
+ return client.prefetchQuery({ queryFn: fetchIntroOffer, queryKey: introOfferQueryKey, staleTime: INTRO_STALE_MS });
+}
+
// 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, and the
-// first one starts the window.
-export function useIntroOffer({ enabled = true }: { enabled?: boolean } = {}) {
- return useQuery({
- enabled,
- queryFn: async () =>
- (await apiFetch<{ offer: IntroOffer | null }>("/api/billing/intro-offer", { method: "POST" })).offer,
- queryKey: introOfferQueryKey,
- staleTime: 5 * 60_000,
- });
+// first one to show it starts the window.
+export function useIntroOffer({ enabled = true }: { enabled?: boolean } = {}): {
+ data: IntroOffer | null | undefined;
+ isPending: boolean;
+} {
+ const queryClient = useQueryClient();
+ const read = useQuery({ enabled, queryFn: fetchIntroOffer, queryKey: introOfferQueryKey, staleTime: INTRO_STALE_MS });
+ const offer = read.data;
+
+ // A window this surface is the first to show runs from its mount, the
+ // moment the start below lands on the server too; the countdown keeps that
+ // anchor, so it never jumps when the server's answer arrives.
+ const [mountedAt] = useState(() => Date.now());
+ const [startedHere, setStartedHere] = useState(false);
+ const unstarted = enabled && offer !== undefined && offer !== null && offer.endsAt === null;
+ if (unstarted && !startedHere) {
+ setStartedHere(true);
+ }
+ useEffect(() => {
+ if (!unstarted) {
+ return;
+ }
+ void apiFetch<{ endsAt: string | null }>(INTRO_OFFER_URL, { method: "POST" }).then(({ endsAt }) => {
+ queryClient.setQueryData<IntroOfferRead | null>(introOfferQueryKey, (prev) =>
+ prev && endsAt ? { ...prev, endsAt } : null,
+ );
+ });
+ }, [unstarted, queryClient]);
+
+ if (!offer) {
+ return { data: offer, isPending: read.isPending };
+ }
+ const endsAt =
+ startedHere || offer.endsAt === null
+ ? new Date(mountedAt + offer.windowHours * HOUR_MS).toISOString()
+ : offer.endsAt;
+ return { data: { ...offer, endsAt }, isPending: read.isPending };
}
// Mutations return the Stripe URL; the caller redirects the browser. We don't