Open source CapCut alternative.
TypeScript
feat(site): cap super-user grants and align credit top-up presets and defaults
David Le91005eb9ece2
diff --git a/site/src/app/api/credits/grants/route.ts b/site/src/app/api/credits/grants/route.tsindex ad685944..23917824 100644--- a/site/src/app/api/credits/grants/route.ts+++ b/site/src/app/api/credits/grants/route.ts@@ -3,6 +3,7 @@ import { z } from "zod";import { creditMicrosToString, creditStringToMicros } from "@/lib/credits/amounts";import { getCreditBalance, grantCredits } from "@/lib/credits/inference";+import { maxCreditGrantDollars } from "@/lib/credits/top-up";import {isDonkeySuperUser,notFoundResponse,@@ -12,11 +13,12 @@ import { prisma } from "@/lib/prisma";export const dynamic = "force-dynamic";-// The target is identified by userId (e.g. "+$100 to me") or by email (the-// grant-to-user form). At least one is required.+// The target is identified by userId (grant to self) or by email (grant to+// another user). At least one is required. A single grant is capped to guard+// against typos.const creditGrantRequestSchema = z.object({- amountDollars: z.coerce.number().int().positive().max(100),+ amountDollars: z.coerce.number().int().positive().max(maxCreditGrantDollars),description: z.string().trim().min(1).max(500).optional(),email: z.string().trim().email().optional(),sourceId: z.string().trim().min(1).max(160).optional(),diff --git a/site/src/app/app/settings/_components/CreditsCard.tsx b/site/src/app/app/settings/_components/CreditsCard.tsxindex c5c1540d..4219b680 100644--- a/site/src/app/app/settings/_components/CreditsCard.tsx+++ b/site/src/app/app/settings/_components/CreditsCard.tsx@@ -15,6 +15,8 @@ import { Label } from "@/components/ui/label";import { Skeleton } from "@/components/ui/skeleton";import { formatUsd } from "@/lib/credits/format-usd";import {+ creditTopUpDefaultDollars,+ creditTopUpMaxDollars,creditTopUpMinDollars,creditTopUpPresetsDollars,} from "@/lib/credits/top-up";@@ -39,7 +41,9 @@ export function CreditsCard() {const customValue = Number.parseInt(customAmount, 10);const customValid =- Number.isFinite(customValue) && customValue >= creditTopUpMinDollars;+ Number.isFinite(customValue) &&+ customValue >= creditTopUpMinDollars &&+ customValue <= creditTopUpMaxDollars;return (<Card>@@ -66,10 +70,11 @@ export function CreditsCard() {<div className="flex flex-wrap gap-2">{creditTopUpPresetsDollars.map((amount) => (<Button+ className={customAmount === String(amount) ? undefined : "bg-card"}disabled={checkout.isPending}key={amount}- onClick={() => startCheckout(amount)}- variant="outline"+ onClick={() => setCustomAmount(String(amount))}+ variant={customAmount === String(amount) ? "default" : "outline"}>${amount}</Button>@@ -78,13 +83,14 @@ export function CreditsCard() {<div className="flex items-end gap-2"><div className="space-y-1"><Label className="text-xs text-muted-foreground" htmlFor="custom-amount">- Custom amount (USD)+ Amount (USD)</Label><InputclassName="w-32"id="custom-amount"inputMode="numeric"- min={5}+ max={creditTopUpMaxDollars}+ min={creditTopUpMinDollars}onChange={(event) => setCustomAmount(event.target.value)}placeholder="50"type="number"@@ -106,7 +112,7 @@ export function CreditsCard() {</div><AutoReloadSection- onNeedsCard={() => startCheckout(creditTopUpPresetsDollars[1])}+ onNeedsCard={() => startCheckout(creditTopUpDefaultDollars)}/></CardContent></Card>@@ -179,7 +185,7 @@ function AutoReloadSection({ onNeedsCard }: { onNeedsCard: () => void }) {<span>$</span><InputclassName="w-20"- defaultValue={data?.amountDollars ?? 25}+ defaultValue={data?.amountDollars ?? creditTopUpDefaultDollars}min={5}name="amount"type="number"diff --git a/site/src/app/app/settings/_components/ProCard.tsx b/site/src/app/app/settings/_components/ProCard.tsxindex a4915426..4bbcf008 100644--- a/site/src/app/app/settings/_components/ProCard.tsx+++ b/site/src/app/app/settings/_components/ProCard.tsx@@ -49,9 +49,8 @@ export function ProCard() {) : null}</CardTitle><CardDescription>- A monthly usage allowance for the Donkey app. The included- allowance is spent before your purchased credits, and resets each- month.+ A monthly usage allowance for the Donkey app that resets each+ month. You can still buy credits any time.</CardDescription></CardHeader><CardContent className="text-sm text-muted-foreground">@@ -75,8 +74,8 @@ export function ProCard() {</div>) : (<p>- Subscribe to include a monthly usage allowance. You can still buy- credits any time; the included allowance is used first.+ You're not subscribed. Subscribe to get a monthly included+ allowance for the app; you can still buy credits any time.</p>)}</CardContent>diff --git a/site/src/app/app/settings/_components/SuperuserCreditsCard.tsx b/site/src/app/app/settings/_components/SuperuserCreditsCard.tsxindex f327e577..60e0f0bd 100644--- a/site/src/app/app/settings/_components/SuperuserCreditsCard.tsx+++ b/site/src/app/app/settings/_components/SuperuserCreditsCard.tsx@@ -10,18 +10,37 @@ import {CardHeader,CardTitle,} from "@/components/ui/card";+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";+import {+ creditTopUpDefaultDollars,+ creditTopUpPresetsDollars,+ maxCreditGrantDollars,+} from "@/lib/credits/top-up";import { useAccount, useGrantCredits } from "@/queries/credits";-// Super users top up in $100 increments — the manual grant route caps a single-// grant at $100, so larger top-ups are repeated clicks.-const incrementDollars = 100;+// Quick-pick amounts mirror the pay-as-you-go presets; super users can also type+// a custom dollar value. The grant route caps a single grant at+// maxCreditGrantDollars to guard against typos.+const presetDollars = creditTopUpPresetsDollars;export function SuperuserCreditsCard() {const account = useAccount();const grant = useGrantCredits();- const [email, setEmail] = useState("");+ // null means "use the current user's email as the default recipient"; once the+ // super user edits the field we track their override here.+ const [emailOverride, setEmailOverride] = useState<string | null>(null);+ const [amount, setAmount] = useState(String(creditTopUpDefaultDollars));+ const [confirmOpen, setConfirmOpen] = useState(false);const [lastResult, setLastResult] = useState<string | null>(null);// Render nothing for non-super users (and while we don't yet know).@@ -29,32 +48,40 @@ export function SuperuserCreditsCard() {return null;}- const grantToSelf = () => {- setLastResult(null);- grant.mutate(- { amountDollars: incrementDollars, userId: account.data.userId },- {- onSuccess: (result) =>- setLastResult(- `Added $${incrementDollars} to ${result.targetUser.email} — new balance $${result.balance.balance}.`,- ),- },- );- };+ // The field shows the user's own email by default; only treat it as a target+ // when the super user actually overrides it. An unedited (or cleared) field+ // grants to self by the authoritative userId, not by re-resolving the email.+ const email = emailOverride ?? account.data.email ?? "";+ const overrideEmail = emailOverride?.trim() ?? "";+ const grantingToSelf = overrideEmail === "";+ const recipientLabel = grantingToSelf ? "your account" : overrideEmail;- const grantToEmail = () => {- if (!email.trim()) {+ const amountDollars = Number(amount);+ const amountValid =+ Number.isInteger(amountDollars) &&+ amountDollars > 0 &&+ amountDollars <= maxCreditGrantDollars;++ const submit = () => {+ if (!amountValid) {return;}setLastResult(null);grant.mutate(- { amountDollars: incrementDollars, email: email.trim() },+ {+ amountDollars,+ ...(grantingToSelf+ ? { userId: account.data.userId }+ : { email: overrideEmail }),+ },{onSuccess: (result) => {setLastResult(- `Added $${incrementDollars} to ${result.targetUser.email} — new balance $${result.balance.balance}.`,+ `Added $${amountDollars} to ${result.targetUser.email} — new balance $${result.balance.balance}.`,);- setEmail("");+ // Reset back to the default recipient (the current user).+ setEmailOverride(null);+ setConfirmOpen(false);},},);@@ -67,44 +94,84 @@ export function SuperuserCreditsCard() {Super user · Credits</CardTitle><CardDescription>- Grant credits in ${incrementDollars} increments. Visible to super users- only.+ Defaults to your account — change the recipient to grant to another+ user. Visible to super users only.</CardDescription></CardHeader><CardContent className="space-y-5">- <div>- <Button disabled={grant.isPending} onClick={grantToSelf}>- {grant.isPending ? "Adding…" : `+ $${incrementDollars} to my account`}- </Button>+ <div className="space-y-2">+ <Label htmlFor="grant-email">Recipient</Label>+ <Input+ className="max-w-xs"+ id="grant-email"+ onChange={(event) => setEmailOverride(event.target.value)}+ placeholder="[email protected]"+ type="email"+ value={email}+ /></div>- <div className="space-y-2 border-t pt-5">- <Label htmlFor="grant-email">Grant to a user</Label>- <div className="flex items-end gap-2">+ <div className="space-y-2">+ <Label htmlFor="grant-amount">Amount (USD)</Label>+ <div className="flex flex-wrap items-center gap-2">+ {presetDollars.map((preset) => (+ <Button+ key={preset}+ className={amount === String(preset) ? undefined : "bg-card"}+ onClick={() => setAmount(String(preset))}+ type="button"+ variant={amount === String(preset) ? "default" : "outline"}+ >+ ${preset}+ </Button>+ ))}<Input- className="max-w-xs"- id="grant-email"- onChange={(event) => setEmail(event.target.value)}- placeholder="[email protected]"- type="email"- value={email}+ className="max-w-[7rem]"+ id="grant-amount"+ max={maxCreditGrantDollars}+ min={1}+ onChange={(event) => setAmount(event.target.value)}+ placeholder="Custom"+ type="number"+ value={amount}/>- <Button- disabled={grant.isPending || !email.trim()}- onClick={grantToEmail}- variant="secondary"- >- Grant ${incrementDollars}- </Button></div></div>+ <Button+ disabled={grant.isPending || !amountValid}+ onClick={() => setConfirmOpen(true)}+ >+ {grant.isPending ? "Granting…" : `Grant $${amountDollars}`}+ </Button>++ <Dialog onOpenChange={setConfirmOpen} open={confirmOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Confirm credit grant</DialogTitle>+ <DialogDescription>+ Grant <span className="font-medium">${amountDollars}</span> in+ credits to{" "}+ <span className="font-medium">{recipientLabel}</span>?+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <DialogClose render={<Button variant="outline" />}>+ Cancel+ </DialogClose>+ <Button disabled={grant.isPending} onClick={submit}>+ {grant.isPending ? "Granting…" : `Grant $${amountDollars}`}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+{lastResult ? (<p className="text-sm text-muted-foreground">{lastResult}</p>) : null}{grant.isError ? (<p className="text-sm text-destructive">- Grant failed. Check the email and try again.+ Grant failed. Check the email and amount, then try again.</p>) : null}</CardContent>diff --git a/site/src/lib/credits/top-up.ts b/site/src/lib/credits/top-up.tsindex 4ec58201..85ab2403 100644--- a/site/src/lib/credits/top-up.ts+++ b/site/src/lib/credits/top-up.ts@@ -10,10 +10,20 @@ export const creditTopUpPresetsDollars = [5, 25, 50, 100] as const;export const creditTopUpMinDollars = 5;export const creditTopUpMaxDollars = 2_000;+// The default pay-as-you-go amount: the value we pre-fill / fall back to when no+// other amount is chosen (auto-reload default, the "buy once to save a card"+// nudge, and the super user grant default all key off this so they stay in sync).+export const creditTopUpDefaultDollars = 25;+// Stripe metadata "kind" tags that route a completed payment to a credit grant.export const creditTopUpKind = "credit_topup";export const creditAutoReloadKind = "credit_topup_autoreload";+// Ceiling on a single super-user credit grant (whole dollars), enforced both by+// the grant API's schema and the settings form so the two never drift. Kept low+// as a typo guard — grants above this are rejected.+export const maxCreditGrantDollars = 100;+export function dollarsToStripeCents(amountDollars: number): number {return Math.round(amountDollars * 100);}