Open source CapCut alternative.
TypeScript
feat(site): signup credits and their lifetime read from a su setting
David Led81f397f4dd3
diff --git a/site/scripts/backfill-signup-credit.ts b/site/scripts/backfill-signup-credit.tsindex a5082720..a0791089 100644--- a/site/scripts/backfill-signup-credit.ts+++ b/site/scripts/backfill-signup-credit.ts@@ -3,15 +3,15 @@* One-off: re-grant the signup app credit to accounts whose provisioning lost* the write-conflict race at signup (P2034) before grantCredits retried on* conflict. Idempotent — grantCredits dedupes on (source, sourceId, userId) —- * so re-running or listing an already-granted user is a no-op.+ * so re-running or listing an already-granted user is a no-op. The amount and+ * lifetime come from the signupCredits setting, as at signup.** Run from site/ with production credentials in the environment:* bun run scripts/backfill-signup-credit.ts <userId> [<userId> ...]*/-import { creditStringToMicros } from "../src/lib/credits/amounts";-import { grantCredits } from "../src/lib/credits/inference";-import { signupAppCredits } from "../src/lib/onboarding/sequence";+import { getGlobalSetting } from "../src/lib/config/effective";+import { grantSignupAppCredits } from "../src/lib/onboarding/signup-grants";import { prisma } from "../src/lib/prisma";const userIds = process.argv.slice(2);@@ -20,14 +20,14 @@ if (userIds.length === 0) {process.exit(1);}+const setting = await getGlobalSetting("signupCredits");+if (setting.dollars <= 0) {+ console.error("signupCredits grants nothing; set the amount on su first");+ process.exit(1);+}+for (const userId of userIds) {- const grant = await grantCredits({- amountMicros: creditStringToMicros(signupAppCredits),- description: "Signup bonus credits",- source: "signup",- sourceId: `signup-app-credit:${userId}`,- userId,- });+ const grant = await grantSignupAppCredits(userId, String(setting.dollars), setting.expiresAfterDays);console.log(`${userId}: grant ${grant.id} (${grant.originalAmountMicros} micros)`);}diff --git a/site/src/app/api/account/onboarding/route.ts b/site/src/app/api/account/onboarding/route.tsindex 855d19f0..a235286d 100644--- a/site/src/app/api/account/onboarding/route.ts+++ b/site/src/app/api/account/onboarding/route.ts@@ -1,6 +1,7 @@import { NextResponse } from "next/server";import { z } from "zod";+import { creditMicrosToString } from "@/lib/credits/amounts";import {withDonkeyAuth,type DonkeyAuthenticatedRequest,@@ -27,10 +28,10 @@ type OnboardingState = {skipped: boolean;referralSources: string[];referralOther: string | null;- // Whether the signup credit grant landed on this account. An address that- // deleted an earlier account starts without it, and the credits slide says- // so.- signupCreditsGranted: boolean;+ // USD the signup grant landed on this account, or null when none did: the+ // address deleted an earlier account, or the setting grants nothing. The+ // credits slide names this amount.+ signupCredits: string | null;};// An account that has never opened the sequence has no row; it reads as an@@ -96,7 +97,7 @@ export const PUT = withDonkeyAuth(async (request: DonkeyAuthenticatedRequest) =>async function toState(userId: string, row: OnboardingRow): Promise<OnboardingState> {const grant = await prisma.userCreditGrant.findFirst({where: { userId, source: "signup" },- select: { id: true },+ select: { originalAmountMicros: true },});return {version: row.version,@@ -104,6 +105,6 @@ async function toState(userId: string, row: OnboardingRow): Promise<OnboardingStskipped: row.skipped,referralSources: row.referralSources,referralOther: row.referralOther,- signupCreditsGranted: grant !== null,+ signupCredits: grant ? creditMicrosToString(grant.originalAmountMicros) : null,};}diff --git a/site/src/cut/components/onboarding/CutOnboarding.tsx b/site/src/cut/components/onboarding/CutOnboarding.tsxindex 19dfc4cf..76cde2a7 100644--- a/site/src/cut/components/onboarding/CutOnboarding.tsx+++ b/site/src/cut/components/onboarding/CutOnboarding.tsx@@ -338,7 +338,7 @@ export function CutOnboarding() {)}{step === 2 && <ModesSlide />}{step === 3 && (- <CreditsSlide granted={state?.signupCreditsGranted ?? true} />+ <CreditsSlide credits={state?.signupCredits ?? null} />)}{step === 4 && <AiChatSlide />}{step === 5 && !isPro && <PlansSlide onSkipPro={() => finish(false)} />}diff --git a/site/src/cut/components/onboarding/slides/Credits.tsx b/site/src/cut/components/onboarding/slides/Credits.tsxindex 027a093a..e8933ab0 100644--- a/site/src/cut/components/onboarding/slides/Credits.tsx+++ b/site/src/cut/components/onboarding/slides/Credits.tsx@@ -3,33 +3,33 @@import { useEffect, useRef } from "react";import { burstConfetti } from "@/cut/components/onboarding/confetti";-import { signupAppCredits } from "@/lib/onboarding/sequence";// The signup grant already landed when the account was created, so this slide-// never grants anything — it says what's there. That's as true on a replay as-// on a first run, so the words don't change between them; the burst fires every-// time the slide is reached. An account whose address already received the-// grant on an earlier, deleted account has none, and the slide says that.-export function CreditsSlide({ granted }: { granted: boolean }) {+// never grants anything — it says what's there: the USD the grant carried, read+// from the account. That's as true on a replay as on a first run, so the words+// don't change between them; the burst fires every time the slide is reached.+// An account with no grant — its address already had one on an earlier,+// deleted account, or the signup-credits setting grants nothing — gets the+// slide without an amount.+export function CreditsSlide({ credits }: { credits: string | null }) {const canvasRef = useRef<HTMLCanvasElement>(null);useEffect(() => {const canvas = canvasRef.current;if (!canvas) return;- if (!granted) return;+ if (credits === null) return;return burstConfetti(canvas);- }, [granted]);+ }, [credits]);- if (!granted) {+ if (credits === null) {return (<div className="relative flex flex-col items-center text-center"><div className="relative max-w-[900px]"><h2 className="text-[clamp(26px,4.4vw,52px)] font-light leading-[1.02] tracking-[-0.03em]">- Welcome back+ Welcome</h2><p className="mx-auto mt-4 max-w-[460px] text-left text-[16px] leading-[1.55] text-[#454545]">- Signup credits came with your first account. Top up or go Pro to- generate video, audio and images.+ Top up or go Pro to generate video, audio and images.</p></div></div>@@ -53,7 +53,7 @@ export function CreditsSlide({ granted }: { granted: boolean }) {balance, not on the offer. */}<h2 className="flex flex-wrap items-baseline justify-center gap-x-4 leading-[1.02] tracking-[-0.03em]"><span className="text-[clamp(40px,7.4vw,84px)] font-semibold text-coral tabular-nums">- ${signupAppCredits}+ ${credits}</span><span className="text-[clamp(26px,4.4vw,52px)] font-light">in AI credits is on usdiff --git a/site/src/emails/welcome.tsx b/site/src/emails/welcome.tsxindex 2e95f575..99a76337 100644--- a/site/src/emails/welcome.tsx+++ b/site/src/emails/welcome.tsx@@ -16,8 +16,8 @@ import { DonkeyMark } from "./_components/DonkeyMark";// The one email a new account gets: a personal note from David. Sent by// src/lib/email/send-welcome.ts; preview with `npm run email:dev`. The credit-// amount arrives as a prop so src/lib/onboarding/sequence.ts stays its single-// source. This module stays pure — the react-email preview server bundles it+// amount arrives as a prop: it is whatever the signup grant landed, sized by+// the signupCredits setting. This module stays pure — the react-email preview server bundles it// on its own, so everything it needs comes in as props and asset/link URLs are// absolute.diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.tsindex 6c3aafd4..6a6ce1f7 100644--- a/site/src/lib/config/registry.ts+++ b/site/src/lib/config/registry.ts@@ -10,6 +10,8 @@ import {} from "@donkeycut/abexp";import { z } from "zod";+import { maxCreditGrantDollars, maxCreditGrantExpiryDays } from "@/lib/credits/top-up";+// The settings registry: every runtime tunable the product has, declared once// with a schema and a default. A value resolves default < override < variant// (src/lib/config/resolve.ts); su edits the override, an experiment supplies@@ -51,8 +53,26 @@ export const SETTINGS = defineSettings({description:"The bars a verdict is called against, and how long an ended experiment keeps being recomputed.",},+ signupCredits: {+ schema: z+ .object({+ // USD the signup hook grants a new account; 0 grants nothing.+ dollars: z.number().int().min(0).max(maxCreditGrantDollars),+ // Days the grant stays spendable; null keeps it forever.+ expiresAfterDays: z.number().int().min(1).max(maxCreditGrantExpiryDays).nullable(),+ })+ .strict(),+ default: { dollars: 0, expiresAfterDays: 7 },+ public: false,+ title: "Signup credits",+ description: "USD a new account is granted at signup, and how many days the grant lives.",+ },});+// The settings su shows on its Product tab: what an account gets. The+// settings tab under Experiments still lists every key.+export const PRODUCT_SETTING_KEYS = ["signupCredits"] as const satisfies readonly SettingKey[];+export type SettingKey = keyof typeof SETTINGS;export type Settings = SettingsOf<typeof SETTINGS>;export type PublicSettingKey = PublicKeyOf<typeof SETTINGS>;diff --git a/site/src/lib/credits/top-up.ts b/site/src/lib/credits/top-up.tsindex 85ab2403..8571088a 100644--- a/site/src/lib/credits/top-up.ts+++ b/site/src/lib/credits/top-up.ts@@ -27,3 +27,20 @@ export const maxCreditGrantDollars = 100;export function dollarsToStripeCents(amountDollars: number): number {return Math.round(amountDollars * 100);}++// How long a grant lives. The su grant form offers these picks beside a custom+// day count; the grant API and the signup-credits setting cap the count at the+// same ceiling. null stands for a grant that never expires.+export const creditGrantExpiryPresets = [+ { label: "1 day", days: 1 },+ { label: "1 week", days: 7 },+ { label: "1 month", days: 30 },+ { label: "1 year", days: 365 },+] as const;+export const maxCreditGrantExpiryDays = 3650;++/** The moment a grant made now stops being spendable, or undefined for never. */+export function creditGrantExpiry(expiresAfterDays: number | null, now = new Date()): Date | undefined {+ if (expiresAfterDays === null) return undefined;+ return new Date(now.getTime() + expiresAfterDays * 24 * 60 * 60 * 1000);+}diff --git a/site/src/lib/onboarding/sequence.ts b/site/src/lib/onboarding/sequence.tsindex ac547ddd..5d2a5617 100644--- a/site/src/lib/onboarding/sequence.ts+++ b/site/src/lib/onboarding/sequence.ts@@ -30,13 +30,3 @@ export const isKnownReferralSource = (id: string): id is ReferralSource =>// 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).- *- * Sized against the priciest first thing an account can do: a generated video- * clip bills a little over a dollar, so this covers a couple of them and the- * chat around them. A grant that can't buy one leaves every new account- * bouncing off an empty balance on its first real try. */-export const signupAppCredits = "3";diff --git a/site/src/lib/onboarding/signup-grants.ts b/site/src/lib/onboarding/signup-grants.tsindex 5b53c45e..0a2c66f0 100644--- a/site/src/lib/onboarding/signup-grants.ts+++ b/site/src/lib/onboarding/signup-grants.ts@@ -1,19 +1,21 @@import { seedFontsFolder } from "@/cut/server/cloud/library";import { seedStarterProject } from "@/cut/server/cloud/starter";+import { getGlobalSetting } from "@/lib/config/effective";import { creditStringToMicros } from "@/lib/credits/amounts";import { grantCredits } from "@/lib/credits/inference";+import { creditGrantExpiry } from "@/lib/credits/top-up";import { type EmailUser } from "@/lib/email/resend";import { sendWelcomeEmail } from "@/lib/email/send-welcome";import { syncResendContact } from "@/lib/email/sync-contact";import { isDeletedAddress } from "@/lib/onboarding/deleted-account";-import { signupAppCredits } from "@/lib/onboarding/sequence";// Single source of truth for what a new account starts with. All steps are// idempotent and keyed to the user, so provisioning can run more than once// (e.g. a retried signup) without double-granting, double-seeding, or-// double-sending. The grant amounts are in sequence.ts, which the welcome-// slides and the welcome email import too.+// double-sending. The grant amount and its lifetime are the signupCredits+// setting, edited on su; the welcome email names the amount that landed.export async function provisionSignupGrants(user: EmailUser): Promise<void> {+ const setting = await getGlobalSetting("signupCredits");// An address that was deleted already had its signup credits once. The// starter project, fonts and welcome still land; the credits do not, and// the welcome email leaves them out.@@ -23,11 +25,13 @@ export async function provisionSignupGrants(user: EmailUser): Promise<void> {userId: user.id,});}- const credits = returning ? null : signupAppCredits;+ const credits = returning || setting.dollars <= 0 ? null : String(setting.dollars);// Settle the steps independently: one failing must not block the others,// and signup itself must never fail because a bonus grant hiccupped.const results = await Promise.allSettled([- credits === null ? Promise.resolve() : grantSignupAppCredits(user.id, credits),+ credits === null+ ? Promise.resolve()+ : grantSignupAppCredits(user.id, credits, setting.expiresAfterDays),seedStarterProject(user.id),seedFontsFolder(user.id),sendWelcomeEmail(user, credits),@@ -44,12 +48,17 @@ export async function provisionSignupGrants(user: EmailUser): Promise<void> {}}-async function grantSignupAppCredits(userId: string, credits: string): Promise<void> {+export async function grantSignupAppCredits(+ userId: string,+ credits: string,+ expiresAfterDays: number | null,+) {// grantCredits dedupes on (source, sourceId, userId), so this is a no-op on// re-run.- await grantCredits({+ return grantCredits({amountMicros: creditStringToMicros(credits),description: "Signup bonus credits",+ expiresAt: creditGrantExpiry(expiresAfterDays),source: "signup",sourceId: `signup-app-credit:${userId}`,userId,diff --git a/site/src/queries/onboarding.ts b/site/src/queries/onboarding.tsindex deea5f0b..534f1d02 100644--- a/site/src/queries/onboarding.ts+++ b/site/src/queries/onboarding.ts@@ -13,7 +13,7 @@ export type OnboardingState = {skipped: boolean;referralSources: string[];referralOther: string | null;- signupCreditsGranted: boolean;+ signupCredits: string | null;};type OnboardingUpdate =