Skip to content

Open source CapCut alternative.

TypeScript

feat(site): record what a new account's welcome sequence answers

David Leb3f2267cc4f6
diff --git a/site/prisma/Auth.prisma b/site/prisma/Auth.prisma
index e28d30c0..201a25ab 100644
--- a/site/prisma/Auth.prisma
+++ b/site/prisma/Auth.prisma
@@ -25,6 +25,7 @@ model User {
visionApiSubscription VisionApiSubscription?
proSubscription ProSubscription?
avatar UserAvatar?
+ onboarding UserOnboarding?
@@map("user")
}
diff --git a/site/prisma/Onboarding.prisma b/site/prisma/Onboarding.prisma
new file mode 100644
index 00000000..5ccfca5c
--- /dev/null
+++ b/site/prisma/Onboarding.prisma
@@ -0,0 +1,21 @@
+// What an account has been through on the way in: the welcome sequence, and
+// the answers it collected. One row per user, written the first time the
+// sequence opens. Referral source ids live in code
+// (src/lib/onboarding/referral-sources.ts); the route accepts only those.
+
+model UserOnboarding {
+ userId String @id
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ // The sequence this account saw. Raising ONBOARDING_VERSION in code shows a
+ // rewritten sequence again to accounts that only finished an older one.
+ version Int @default(1)
+ // Null until the sequence ends; `skipped` says how it ended.
+ completedAt DateTime?
+ skipped Boolean @default(false)
+ referralSource String?
+ // Free text alongside the choice, for answers worth qualifying.
+ referralDetail String?
+ referralAnsweredAt DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+}
diff --git a/site/prisma/migrations/20260729014813/migration.sql b/site/prisma/migrations/20260729014813/migration.sql
new file mode 100644
index 00000000..934ffba1
--- /dev/null
+++ b/site/prisma/migrations/20260729014813/migration.sql
@@ -0,0 +1,17 @@
+-- CreateTable
+CREATE TABLE "UserOnboarding" (
+ "userId" TEXT NOT NULL,
+ "version" INTEGER NOT NULL DEFAULT 1,
+ "completedAt" TIMESTAMP(3),
+ "skipped" BOOLEAN NOT NULL DEFAULT false,
+ "referralSource" TEXT,
+ "referralDetail" TEXT,
+ "referralAnsweredAt" TIMESTAMP(3),
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "UserOnboarding_pkey" PRIMARY KEY ("userId")
+);
+
+-- AddForeignKey
+ALTER TABLE "UserOnboarding" ADD CONSTRAINT "UserOnboarding_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/site/src/app/api/account/onboarding/route.ts b/site/src/app/api/account/onboarding/route.ts
new file mode 100644
index 00000000..f2ae1b07
--- /dev/null
+++ b/site/src/app/api/account/onboarding/route.ts
@@ -0,0 +1,88 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import {
+ withDonkeyAuth,
+ type DonkeyAuthenticatedRequest,
+} from "@/lib/donkey-api-auth";
+import {
+ ONBOARDING_VERSION,
+ isKnownReferralSource,
+} from "@/lib/onboarding/sequence";
+import { prisma } from "@/lib/prisma";
+
+export const dynamic = "force-dynamic";
+
+type OnboardingState = {
+ version: number;
+ completedAt: string | null;
+ skipped: boolean;
+ referralSource: string | null;
+};
+
+// An account that has never opened the sequence has no row; it reads as an
+// unfinished run of the current sequence rather than as an error.
+const UNSTARTED: OnboardingState = {
+ version: ONBOARDING_VERSION,
+ completedAt: null,
+ skipped: false,
+ referralSource: null,
+};
+
+export const GET = withDonkeyAuth(async (request: DonkeyAuthenticatedRequest) => {
+ const row = await prisma.userOnboarding.findUnique({
+ where: { userId: request.donkey.userId },
+ });
+ return NextResponse.json(row ? toState(row) : UNSTARTED);
+});
+
+const updateSchema = z
+ .object({
+ referralSource: z.string().refine(isKnownReferralSource),
+ referralDetail: z.string().max(200).optional(),
+ })
+ .or(z.object({ completed: z.literal(true), skipped: z.boolean() }));
+
+// One write for both things the sequence records: the referral answer when it's
+// picked, and the run's end. Either is the account's first row, so both upsert.
+export const PUT = withDonkeyAuth(async (request: DonkeyAuthenticatedRequest) => {
+ const parsed = updateSchema.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) {
+ return NextResponse.json({ error: "Invalid request." }, { status: 400 });
+ }
+
+ const userId = request.donkey.userId;
+ const data =
+ "referralSource" in parsed.data
+ ? {
+ referralSource: parsed.data.referralSource,
+ referralDetail: parsed.data.referralDetail ?? null,
+ referralAnsweredAt: new Date(),
+ }
+ : {
+ completedAt: new Date(),
+ skipped: parsed.data.skipped,
+ version: ONBOARDING_VERSION,
+ };
+
+ const row = await prisma.userOnboarding.upsert({
+ where: { userId },
+ create: { userId, version: ONBOARDING_VERSION, ...data },
+ update: data,
+ });
+ return NextResponse.json(toState(row));
+});
+
+function toState(row: {
+ version: number;
+ completedAt: Date | null;
+ skipped: boolean;
+ referralSource: string | null;
+}): OnboardingState {
+ return {
+ version: row.version,
+ completedAt: row.completedAt?.toISOString() ?? null,
+ skipped: row.skipped,
+ referralSource: row.referralSource,
+ };
+}
diff --git a/site/src/lib/onboarding/sequence.ts b/site/src/lib/onboarding/sequence.ts
new file mode 100644
index 00000000..9c125f57
--- /dev/null
+++ b/site/src/lib/onboarding/sequence.ts
@@ -0,0 +1,31 @@
+// What the welcome sequence is made of: the sources a new account can pick
+// from when we ask where they found us, and the version of the sequence
+// itself. The slides render this list and the account route accepts only these
+// ids, so the question and the stored answers can't drift apart.
+
+/** A run of the sequence: the first one an account gets, or a replay it asked
+ * for from settings. Slides that congratulate read differently on a replay. */
+export type OnboardingRun = "first_run" | "replay";
+
+export const REFERRAL_SOURCES = [
+ { id: "discord", label: "Discord" },
+ { id: "tiktok", label: "TikTok" },
+ { id: "instagram", label: "Instagram" },
+ { id: "youtube", label: "YouTube" },
+ { id: "search", label: "Search" },
+ { id: "friend", label: "A friend" },
+] as const;
+
+export type ReferralSource = (typeof REFERRAL_SOURCES)[number]["id"];
+
+export const isKnownReferralSource = (id: string): id is ReferralSource =>
+ REFERRAL_SOURCES.some((s) => s.id === id);
+
+// The sequence an account is measured against. Raise it when the slides change
+// enough that people who finished the old one should see the new one.
+export const ONBOARDING_VERSION = 1;
+
+/** USD the signup hook grants a new account. Lives here, free of server
+ * imports, because the sequence's credits slide names the same number the
+ * grant uses (src/lib/onboarding/signup-grants.ts). */
+export const signupAppCredits = "1";
diff --git a/site/src/lib/onboarding/signup-grants.ts b/site/src/lib/onboarding/signup-grants.ts
index 91a0f369..653b3f77 100644
--- a/site/src/lib/onboarding/signup-grants.ts
+++ b/site/src/lib/onboarding/signup-grants.ts
@@ -1,11 +1,12 @@
import { creditStringToMicros } from "@/lib/credits/amounts";
import { grantCredits } from "@/lib/credits/inference";
import { grantVisionCalls } from "@/lib/credits/vision-grants";
+import { signupAppCredits } from "@/lib/onboarding/sequence";
// Single source of truth for what a new account starts with. Both grants are
// idempotent and keyed to the user, so provisioning can run more than once (e.g.
-// a retried signup) without ever double-granting.
-export const signupAppCredits = "1"; // USD added to the app inference balance
+// a retried signup) without ever double-granting. The credit amount itself is
+// in sequence.ts, which the welcome slides can import too.
export const signupVisionFreeCalls = 100; // lifetime free Vision API calls
export async function provisionSignupGrants(userId: string): Promise<void> {
diff --git a/site/src/queries/onboarding.ts b/site/src/queries/onboarding.ts
new file mode 100644
index 00000000..dd1fbe6d
--- /dev/null
+++ b/site/src/queries/onboarding.ts
@@ -0,0 +1,50 @@
+"use client";
+
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+
+import { ONBOARDING_VERSION, type ReferralSource } from "@/lib/onboarding/sequence";
+import { apiFetch } from "@/queries/apiClient";
+
+export const onboardingQueryKey = ["account-onboarding"] as const;
+
+export type OnboardingState = {
+ version: number;
+ completedAt: string | null;
+ skipped: boolean;
+ referralSource: string | null;
+};
+
+type OnboardingUpdate =
+ | { referralSource: ReferralSource; referralDetail?: string }
+ | { completed: true; skipped: boolean };
+
+/** Whether this account still owes us a run of the current sequence. */
+export function needsOnboarding(state: OnboardingState | undefined): boolean {
+ if (!state) return false;
+ return state.completedAt === null || state.version < ONBOARDING_VERSION;
+}
+
+export function useOnboardingState() {
+ return useQuery({
+ queryFn: () => apiFetch<OnboardingState>("/api/account/onboarding"),
+ queryKey: onboardingQueryKey,
+ // The sequence decides once per load whether to open; refetching behind an
+ // open overlay could only close it mid-run.
+ refetchOnWindowFocus: false,
+ retry: false,
+ });
+}
+
+export function useSaveOnboarding() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (update: OnboardingUpdate) =>
+ apiFetch<OnboardingState>("/api/account/onboarding", {
+ body: JSON.stringify(update),
+ method: "PUT",
+ }),
+ onSuccess: (state) => {
+ queryClient.setQueryData(onboardingQueryKey, state);
+ },
+ });
+}