Open source CapCut alternative.
TypeScript
feat(site): a credit offer is claimed from a dialog inside the app
David Le0fcb27ccd55d
diff --git a/site/src/app/api/credits/offers/claim/route.ts b/site/src/app/api/credits/offers/claim/route.tsindex 9eac7634..aacd7d83 100644--- a/site/src/app/api/credits/offers/claim/route.ts+++ b/site/src/app/api/credits/offers/claim/route.ts@@ -2,16 +2,40 @@ import { NextResponse } from "next/server";import { z } from "zod";import { creditMicrosToString } from "@/lib/credits/amounts";+import { formatUsdPlain } from "@/lib/credits/format-usd";import { getCreditBalance } from "@/lib/credits/inference";import {claimCreditOffer,CreditOfferNotYoursError,+ MANUAL_OFFER_KIND,verifyCreditOfferToken,} from "@/lib/credits/offers";+import { describeCreditLifetime } from "@/lib/email/send-credits-offered";import { forbiddenResponse, notFoundResponse, withDonkeyAuth } from "@/lib/donkey-api-auth";+import { prisma } from "@/lib/prisma";const claimRequestSchema = z.object({ token: z.string().min(1) }).strict();+// Describes the offer a claim link names, for the dialog that presents it.+// The token proves the link came from the offer's email; the session has to be+// the offered account's, and a different account is told so before it tries.+export const GET = withDonkeyAuth(async (request) => {+ const token = request.nextUrl.searchParams.get("token");+ const offerId = token ? verifyCreditOfferToken(token) : null;+ if (!offerId) return notFoundResponse();+ const offer = await prisma.creditOffer.findUnique({+ select: { amountMicros: true, claimedAt: true, expiresAfterDays: true, kind: true, userId: true },+ where: { id: offerId },+ });+ if (!offer || offer.kind !== MANUAL_OFFER_KIND) return notFoundResponse();+ if (offer.userId !== request.donkey.userId) return forbiddenResponse();+ return NextResponse.json({+ claimed: offer.claimedAt !== null,+ credits: formatUsdPlain(creditMicrosToString(offer.amountMicros)),+ lifetime: describeCreditLifetime(offer.expiresAfterDays),+ });+});+// Claims a credit offer for the signed-in account. The token names the offer// and proves the link came from its email; the session has to be the offered// account's.diff --git a/site/src/app/cut/app/(home)/layout.tsx b/site/src/app/cut/app/(home)/layout.tsxindex 8b9cbd7e..570eea4e 100644--- a/site/src/app/cut/app/(home)/layout.tsx+++ b/site/src/app/cut/app/(home)/layout.tsx@@ -1,4 +1,7 @@+import { Suspense } from "react";+import { AppSidebar } from "@/cut/components/AppSidebar";+import { ClaimCreditsDialog } from "@/cut/components/ClaimCreditsDialog";import { StorageUpgradeDialog } from "@/cut/components/StorageUpgradeDialog";export default function HomeLayout({ children }: { children: React.ReactNode }) {@@ -9,6 +12,12 @@ export default function HomeLayout({ children }: { children: React.ReactNode }){/* Every home surface uploads — projects, library — so the quota wallanswers from the layout rather than from each page. */}<StorageUpgradeDialog />+ {/* A credit offer's email link lands on the home with ?claim=…; the+ dialog reads the address, so it needs a boundary in the prerendered+ shell. */}+ <Suspense>+ <ClaimCreditsDialog />+ </Suspense></div>);}diff --git a/site/src/cut/components/ClaimCreditsDialog.tsx b/site/src/cut/components/ClaimCreditsDialog.tsxnew file mode 100644index 00000000..b749d536--- /dev/null+++ b/site/src/cut/components/ClaimCreditsDialog.tsx@@ -0,0 +1,102 @@+"use client";++// A credit offer's face. The email's claim link opens the app home with the+// offer token in the address (?claim=…); this reads it, presents the offer,+// and lands the credit on a press. The credit waits for that press:+// link-prefetching mail scanners open URLs on the recipient's behalf, and a+// claim on load would start the credit's lifetime before the person saw it.+// Closing drops the token from the address, so a reload opens nothing.+import { usePathname, useRouter, useSearchParams } from "next/navigation";+import { Loader2 } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { useEngineUser } from "@/cut/lib/backend/hooks";+import { formatCreditExpiry } from "@/lib/credits/top-up";+import { ApiError } from "@/queries/apiClient";+import { useClaimCreditOffer, useCreditOffer } from "@/queries/credits";++const PARAM = "claim";++export function ClaimCreditsDialog() {+ const user = useEngineUser();+ const params = useSearchParams();+ const token = params.get(PARAM);+ const router = useRouter();+ const pathname = usePathname();+ if (!user || !token) return null;+ // Only the token leaves the address; an open folder stays open.+ const close = () => {+ const rest = new URLSearchParams(params);+ rest.delete(PARAM);+ const search = rest.toString();+ router.replace(search ? `${pathname}?${search}` : pathname);+ };+ return <OpenDialog key={token} token={token} onClose={close} />;+}++function OpenDialog({ token, onClose }: { token: string; onClose: () => void }) {+ const offer = useCreditOffer(token);+ const claim = useClaimCreditOffer();+ const done = claim.data ?? (offer.data?.claimed ? { expiresAt: null } : null);++ let title = "Your credits";+ let body: React.ReactNode;+ let footer: React.ReactNode;+ if (offer.isPending) {+ body = "Checking this link…";+ footer = null;+ } else if (offer.isError) {+ title = "This link is no longer valid";+ body =+ offer.error instanceof ApiError && offer.error.status === 403+ ? "This offer belongs to a different account. Sign in with the address the email was sent to."+ : "The offer it pointed to is gone.";+ footer = <Button onClick={onClose}>OK</Button>;+ } else if (done) {+ body = `${offer.data.credits} in AI credits is on your account.${+ done.expiresAt ? ` It expires ${formatCreditExpiry(new Date(done.expiresAt))}.` : ""+ }`;+ footer = <Button onClick={onClose}>Start editing</Button>;+ } else {+ body = `${offer.data.credits} in AI credits is waiting for you.${+ offer.data.lifetime ? ` Once claimed, it is good for ${offer.data.lifetime}.` : ""+ }`;+ footer = (+ <>+ <Button variant="ghost" onClick={onClose}>+ Not now+ </Button>+ <Button disabled={claim.isPending} onClick={() => claim.mutate(token)}>+ {claim.isPending && <Loader2 className="animate-spin" data-icon="inline-start" />}+ Claim {offer.data.credits}+ </Button>+ </>+ );+ }++ return (+ <Dialog open onOpenChange={(open) => !open && onClose()}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{title}</DialogTitle>+ <DialogDescription>{body}</DialogDescription>+ </DialogHeader>+ {footer && <DialogFooter>{footer}</DialogFooter>}+ {claim.isError && (+ <p className="text-sm text-destructive">+ {claim.error instanceof ApiError && claim.error.status === 403+ ? "This offer belongs to a different account. Sign in with the address the email was sent to."+ : "That didn't go through. Try again."}+ </p>+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/site/src/emails/credits-offered.tsx b/site/src/emails/credits-offered.tsxindex d2b9e6ac..9e214dbb 100644--- a/site/src/emails/credits-offered.tsx+++ b/site/src/emails/credits-offered.tsx@@ -92,6 +92,6 @@ CreditsOfferedEmail.PreviewProps = {name: "Ada",credits: "$25.00",lifetime: "7 days",- claimUrl: "https://donkeycut.com/claim?token=preview",+ claimUrl: "https://donkeycut.com/app?claim=preview",unsubscribeUrl: "https://donkeycut.com/unsubscribe?token=preview",} satisfies CreditsOfferedEmailProps;diff --git a/site/src/lib/credits/offers.ts b/site/src/lib/credits/offers.tsindex 3d68de66..ce94220f 100644--- a/site/src/lib/credits/offers.ts+++ b/site/src/lib/credits/offers.ts@@ -1,6 +1,7 @@import { createHmac, timingSafeEqual } from "node:crypto";import type { CreditOffer } from "@/generated/prisma/client";+import { CUT_APP_BASE } from "@/cut/lib/appBase";import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";import { grantCredits } from "@/lib/credits/inference";import { creditGrantExpiry } from "@/lib/credits/top-up";@@ -36,8 +37,10 @@ export function verifyCreditOfferToken(token: string): string | null {return offerId;}+// The claim link opens the app with the token in the address; the app's home+// reads it and presents the offer in a dialog (ClaimCreditsDialog).export function creditOfferClaimUrl(offerId: string): string {- return `${DONKEYCUT_CANONICAL}/claim?token=${encodeURIComponent(creditOfferToken(offerId))}`;+ return `${DONKEYCUT_CANONICAL}${CUT_APP_BASE}?claim=${encodeURIComponent(creditOfferToken(offerId))}`;}// Records the offer and emails the claim link. The row comes first so thediff --git a/site/src/proxy.ts b/site/src/proxy.tsindex 7ed82401..7198e4c4 100644--- a/site/src/proxy.ts+++ b/site/src/proxy.ts@@ -69,9 +69,8 @@ const PASSTHROUGH = ["/terms","/sign-in","/sign-up",- // Email-footer unsubscribe page, and the credit-offer claim page.+ // Email-footer unsubscribe page."/unsubscribe",- "/claim",];// Whole-segment prefix match, so "/cut" covers "/cut/…" but not "/cut-app".diff --git a/site/src/queries/credits.ts b/site/src/queries/credits.tsindex 82193ac3..d337f314 100644--- a/site/src/queries/credits.ts+++ b/site/src/queries/credits.ts@@ -133,3 +133,38 @@ export function useOfferCredits() {),});}++export const creditOfferQueryKey = (token: string) => ["credits", "offer", token] as const;++export type CreditOffer = {+ claimed: boolean;+ // Formatted USD, "$5".+ credits: string;+ // "a week", or null when the credit keeps forever.+ lifetime: string | null;+};++// The offer a claim link names. 404 is a link that no longer opens anything;+// 403 is an offer made to another account.+export function useCreditOffer(token: string, options: { enabled?: boolean } = {}) {+ return useQuery({+ enabled: options.enabled ?? true,+ queryFn: () => apiFetch<CreditOffer>(`/api/credits/offers/claim?token=${encodeURIComponent(token)}`),+ queryKey: creditOfferQueryKey(token),+ retry: false,+ });+}++// Lands the offer on the signed-in account; the balance re-reads so the top+// bar shows the credit at once.+export function useClaimCreditOffer() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (token: string) =>+ apiFetch<{ balance: string; credits: string; expiresAt: string | null }>(+ "/api/credits/offers/claim",+ { body: JSON.stringify({ token }), method: "POST" },+ ),+ onSuccess: () => queryClient.invalidateQueries({ queryKey: creditBalanceQueryKey }),+ });+}