Skip to content

Open source CapCut alternative.

TypeScript

feat(site): open the intro offer on first view

David Le366659f4a585
diff --git a/site/prisma/Auth.prisma b/site/prisma/Auth.prisma
index e53af141..ee0e3a8c 100644
--- a/site/prisma/Auth.prisma
+++ b/site/prisma/Auth.prisma
@@ -28,6 +28,7 @@ model User {
apiKeys Apikey[]
chatgptGrants ChatgptGrant[]
proSubscription ProSubscription?
+ introOfferView IntroOfferView?
avatar UserAvatar?
onboarding UserOnboarding?
emailSettings UserEmailSettings?
diff --git a/site/prisma/Billing.prisma b/site/prisma/Billing.prisma
index cb8ca0a5..bbbdad5d 100644
--- a/site/prisma/Billing.prisma
+++ b/site/prisma/Billing.prisma
@@ -25,3 +25,13 @@ model ProSubscription {
@@map("pro_subscription")
}
+
+// When an account first saw the intro offer. Its window runs once, from here;
+// a row exists only for an account a surface has shown the offer to.
+model IntroOfferView {
+ userId String @id
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ seenAt DateTime @default(now())
+
+ @@map("intro_offer_view")
+}
diff --git a/site/prisma/migrations/20261028180000_intro_offer_view/migration.sql b/site/prisma/migrations/20261028180000_intro_offer_view/migration.sql
new file mode 100644
index 00000000..bb41fea3
--- /dev/null
+++ b/site/prisma/migrations/20261028180000_intro_offer_view/migration.sql
@@ -0,0 +1,10 @@
+-- CreateTable
+CREATE TABLE "intro_offer_view" (
+ "userId" TEXT NOT NULL,
+ "seenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "intro_offer_view_pkey" PRIMARY KEY ("userId")
+);
+
+-- AddForeignKey
+ALTER TABLE "intro_offer_view" ADD CONSTRAINT "intro_offer_view_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/site/src/app/api/billing/intro-offer/route.ts b/site/src/app/api/billing/intro-offer/route.ts
index 375a3571..4f6ae472 100644
--- a/site/src/app/api/billing/intro-offer/route.ts
+++ b/site/src/app/api/billing/intro-offer/route.ts
@@ -1,14 +1,15 @@
import { NextResponse } from "next/server";
import { introPriceCents } from "@/lib/billing/intro-offer";
-import { readIntroOffer, readProPriceCents } from "@/lib/billing/intro-offer-server";
+import { openIntroOffer, 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));
+// 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 });
}
diff --git a/site/src/lib/billing/intro-offer-server.ts b/site/src/lib/billing/intro-offer-server.ts
index 16b069c7..4441cbf8 100644
--- a/site/src/lib/billing/intro-offer-server.ts
+++ b/site/src/lib/billing/intro-offer-server.ts
@@ -1,23 +1,52 @@
import Stripe from "stripe";
-import { proPriceId } from "@/lib/billing/pro-subscription";
+import { planPriceId } 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";
+import { heldPro, introCouponId, introOfferAt, offersIntro, type IntroOffer } from "./intro-offer";
-/** The intro offer open to this account right now, or null. */
+/** The intro offer open to this account right now, or null. Reading never
+ * starts the window; checkout reads it this way. */
export async function readIntroOffer(ctx: ConfigContext, now = new Date()): Promise<IntroOffer | null> {
if (!ctx.hasAccount) {
return null;
}
+ 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 for a surface about to show it. The first time an account the
+ * offer is for gets here, its window starts; every later view reads the same
+ * window, so it runs once and is gone. */
+export async function openIntroOffer(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 facts = { heldPro: heldPro(subscription?.status ?? null) };
+ if (!offersIntro(setting, facts)) {
+ return null;
+ }
+
+ // Two surfaces opening at once both land on the first view's time.
+ await prisma.introOfferView.createMany({ data: [{ userId: ctx.userId, seenAt: now }], skipDuplicates: true });
+ const view = await prisma.introOfferView.findUniqueOrThrow({ where: { userId: ctx.userId }, select: { seenAt: true } });
+ return introOfferAt(setting, { ...facts, seenAt: view.seenAt }, now);
}
const stripeCode = (e: unknown) => (e instanceof Stripe.errors.StripeError ? e.code : undefined);
@@ -53,28 +82,32 @@ export async function introCoupon(offer: IntroOffer): Promise<string> {
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;
+// A price's amount never changes under its id, so one read per process
+// serves every offer; moving Pro to a new price reads that one fresh.
+const priceCents = new Map<string, Promise<number>>();
/** The Pro price in cents, as Stripe holds it. */
-export function readProPriceCents(): Promise<number> {
- const priceId = proPriceId();
+export async function readProPriceCents(): Promise<number> {
+ const priceId = await planPriceId("pro");
if (!priceId) {
- throw new Error("STRIPE_PRO_PRICE_ID is not set");
+ throw new Error("The Pro plan has no price in the planPrices setting");
}
- 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;
+ let cents = priceCents.get(priceId);
+ if (!cents) {
+ cents = 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) => {
+ priceCents.delete(priceId);
+ throw e;
+ });
+ priceCents.set(priceId, cents);
+ }
+ return cents;
}
diff --git a/site/src/lib/billing/intro-offer.test.ts b/site/src/lib/billing/intro-offer.test.ts
index 31fb1dd3..6bbbdb90 100644
--- a/site/src/lib/billing/intro-offer.test.ts
+++ b/site/src/lib/billing/intro-offer.test.ts
@@ -1,25 +1,37 @@
import { describe, expect, test } from "bun:test";
-import { heldPro, introCouponId, introOfferAt, introPriceCents } from "./intro-offer";
+import { heldPro, introCouponId, introOfferAt, introPriceCents, offersIntro } from "./intro-offer";
const HOUR_MS = 3_600_000;
-const signup = new Date("2026-10-16T12:00:00Z");
+const seen = new Date("2026-10-16T12:00:00Z");
const setting = { percentOff: 50, months: 1, windowHours: 24 };
-const fresh = { createdAt: signup, heldPro: false };
+const fresh = { seenAt: seen, 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();
+ const offer = introOfferAt(setting, fresh, new Date(seen.getTime() + HOUR_MS));
+ expect(offer).toEqual({ percentOff: 50, months: 1, endsAt: new Date(seen.getTime() + 24 * HOUR_MS) });
+ expect(introOfferAt(setting, fresh, new Date(seen.getTime() + 24 * HOUR_MS))).toBeNull();
});
test("makes no offer at 0 percent, the default", () => {
- expect(introOfferAt({ ...setting, percentOff: 0 }, fresh, signup)).toBeNull();
+ expect(introOfferAt({ ...setting, percentOff: 0 }, fresh, seen)).toBeNull();
});
test("makes no offer to an account that held Pro", () => {
- expect(introOfferAt(setting, { ...fresh, heldPro: true }, signup)).toBeNull();
+ expect(introOfferAt(setting, { ...fresh, heldPro: true }, seen)).toBeNull();
+ });
+
+ test("has nothing open before the account first sees it", () => {
+ expect(introOfferAt(setting, { ...fresh, seenAt: null }, seen)).toBeNull();
+ });
+});
+
+describe("offersIntro", () => {
+ test("is for an account that never held a plan, while the offer is on", () => {
+ expect(offersIntro(setting, { heldPro: false })).toBe(true);
+ expect(offersIntro(setting, { heldPro: true })).toBe(false);
+ expect(offersIntro({ ...setting, percentOff: 0 }, { heldPro: false })).toBe(false);
});
});
diff --git a/site/src/lib/billing/intro-offer.ts b/site/src/lib/billing/intro-offer.ts
index ccb99eda..f1e9e663 100644
--- a/site/src/lib/billing/intro-offer.ts
+++ b/site/src/lib/billing/intro-offer.ts
@@ -1,7 +1,7 @@
// 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.
+// first months of Pro for an account that has never held a plan, open for a
+// window that starts the first time the account sees it. Pure, so the
+// checkout, the offer read and the tests share one rule.
export type IntroOfferSetting = {
percentOff: number;
@@ -26,17 +26,23 @@ 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. */
+/** Whether the account is one the offer is for, seen or not. */
+export function offersIntro(setting: IntroOfferSetting, facts: { heldPro: boolean }): boolean {
+ return setting.percentOff > 0 && !facts.heldPro;
+}
+
+/** The offer open to an account right now, or null. An account that has not
+ * seen the offer yet has none open; its window starts at `seenAt`. */
export function introOfferAt(
setting: IntroOfferSetting,
- facts: { createdAt: Date; heldPro: boolean },
+ facts: { seenAt: Date | null; heldPro: boolean },
now: Date,
): IntroOffer | null {
- if (setting.percentOff <= 0 || facts.heldPro) {
+ if (!offersIntro(setting, facts) || !facts.seenAt) {
return null;
}
- const endsAt = new Date(facts.createdAt.getTime() + setting.windowHours * HOUR_MS);
+ const endsAt = new Date(facts.seenAt.getTime() + setting.windowHours * HOUR_MS);
if (now.getTime() >= endsAt.getTime()) {
return null;
}