Open source CapCut alternative.
TypeScript
fix(site): a claimed credit offer stays claimed wherever its dialog reopens
David Le4c52e716a7e9
diff --git a/site/src/app/api/credits/offers/claim/route.ts b/site/src/app/api/credits/offers/claim/route.tsindex 4c91ddeb..dc813b2f 100644--- a/site/src/app/api/credits/offers/claim/route.ts+++ b/site/src/app/api/credits/offers/claim/route.ts@@ -28,7 +28,15 @@ export const GET = withDonkeyAuth(async (request) => {const offerId = token ? verifyCreditOfferToken(token) : null;if (!offerId) return notFoundResponse();const offer = await prisma.creditOffer.findUnique({- select: { amountMicros: true, claimedAt: true, closesAt: true, expiresAfterDays: true, kind: true, userId: true },+ select: {+ amountMicros: true,+ claimedAt: true,+ closesAt: true,+ expiresAfterDays: true,+ grant: { select: { expiresAt: true } },+ kind: true,+ userId: true,+ },where: { id: offerId },});if (!offer || offer.kind !== MANUAL_OFFER_KIND) return notFoundResponse();@@ -38,6 +46,7 @@ export const GET = withDonkeyAuth(async (request) => {claimed: offer.claimedAt !== null,closesAt: offer.closesAt?.toISOString() ?? null,credits: formatUsdPlain(creditMicrosToString(offer.amountMicros)),+ expiresAt: offer.grant?.expiresAt?.toISOString() ?? null,lifetime: describeCreditLifetime(offer.expiresAfterDays),});});diff --git a/site/src/cut/components/ClaimCreditsDialog.tsx b/site/src/cut/components/ClaimCreditsDialog.tsxindex 59371912..661ccfe9 100644--- a/site/src/cut/components/ClaimCreditsDialog.tsx+++ b/site/src/cut/components/ClaimCreditsDialog.tsx@@ -1,14 +1,16 @@"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.+// offer token in the address (?claim=…); this takes the token out of the+// address the moment it is read, holds it for the dialog's life, 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. The address is clean+// from the first paint, so a reload, a back step or a forward step opens+// nothing; the link itself opens a claimed offer as the credit it landed.import { useSearchParams } from "next/navigation";import { Loader2, Sparkle } from "lucide-react";-import { useState } from "react";+import { useEffect, useState } from "react";import { Button } from "@/components/ui/button";import {Dialog,@@ -33,33 +35,36 @@ export function ClaimCreditsDialog() {return user ? <AddressedDialog /> : null;}-function AddressedDialog() {- const token = useSearchParams().get(PARAM);- if (!token) return null;- return <OpenDialog key={token} token={token} />;-}-// Only the token leaves the address; an open folder stays open. The native// history call syncs into the router without a server round trip, so the-// close holds whatever the connection is doing.+// drop holds whatever the connection is doing.function dropTokenFromAddress() {const url = new URL(window.location.href);url.searchParams.delete(PARAM);window.history.replaceState(null, "", url);}-function OpenDialog({ token }: { token: string }) {+function AddressedDialog() {+ const inAddress = useSearchParams().get(PARAM);+ // The token is held from the render that reads it; a new one in the address+ // replaces it.+ const [held, setHeld] = useState(inAddress);+ if (inAddress && inAddress !== held) setHeld(inAddress);+ useEffect(() => {+ if (inAddress) dropTokenFromAddress();+ }, [inAddress]);+ const token = inAddress ?? held;+ if (!token) return null;+ return <OpenDialog key={token} token={token} onClose={() => setHeld(null)} />;+}++function OpenDialog({ token, onClose }: { token: string; onClose: () => void }) {const offer = useCreditOffer(token);const claim = useClaimCreditOffer();- const [open, setOpen] = useState(true);- const done = claim.data ?? (offer.data?.claimed ? { expiresAt: null } : null);+ const done = claim.data ?? (offer.data?.claimed ? { expiresAt: offer.data.expiresAt } : null);// The dialog opens once the offer is known, at the size it keeps: the body// reserves two lines and every state ends in one row of buttons.if (offer.isPending) return null;- const onClose = () => {- setOpen(false);- dropTokenFromAddress();- };let title = "Claim your credits";let body: string;@@ -80,8 +85,8 @@ function OpenDialog({ token }: { token: string }) {}`;footer = <Button onClick={onClose}>Start editing</Button>;} else {- body = `You have ${offer.data.credits} in AI credits. They\u2019re waiting for you.${- offer.data.lifetime ? ` Once claimed, it\u2019s good for ${offer.data.lifetime}.` : ""+ body = `You have ${offer.data.credits} in AI credits. They’re waiting for you.${+ offer.data.lifetime ? ` Once claimed, it’s good for ${offer.data.lifetime}.` : ""}${offer.data.closesAt ? ` Claim by ${formatCreditExpiry(new Date(offer.data.closesAt))}.` : ""}`;footer = (<>@@ -97,7 +102,7 @@ function OpenDialog({ token }: { token: string }) {}return (- <Dialog open={open} onOpenChange={(next) => !next && onClose()}>+ <Dialog open onOpenChange={(next) => !next && onClose()}><DialogContent className="top-[18%] translate-y-0 sm:max-w-md"><DialogHeader><DialogTitle className="flex items-center gap-2 text-lg">@@ -113,7 +118,7 @@ function OpenDialog({ token }: { token: string }) {? "This offer belongs to a different account. Sign in with the address the email was sent to.": claim.error instanceof ApiError && claim.error.status === 410? "The claim window for this offer has closed."- : "That didn\u2019t go through. Try again."}+ : "That didn’t go through. Try again."}</p>)}{footer}diff --git a/site/src/queries/credits.ts b/site/src/queries/credits.tsindex 416397c4..72e689ed 100644--- a/site/src/queries/credits.ts+++ b/site/src/queries/credits.ts@@ -142,6 +142,9 @@ export type CreditOffer = {closesAt: string | null;// Formatted USD, "$5".credits: string;+ // When the claimed credit expires; null before the claim and for a credit+ // that keeps forever.+ expiresAt: string | null;// "a week", or null when the credit keeps forever.lifetime: string | null;};@@ -157,8 +160,9 @@ export function useCreditOffer(token: string, options: { enabled?: boolean } = {});}-// Lands the offer on the signed-in account; the balance re-reads so the top-// bar shows the credit at once.+// Lands the offer on the signed-in account. The balance re-reads so the top+// bar shows the credit at once, and the offer's own entry records the claim,+// so a dialog that opens on the same token again presents the landed credit.export function useClaimCreditOffer() {const queryClient = useQueryClient();return useMutation({@@ -167,6 +171,11 @@ export function useClaimCreditOffer() {"/api/credits/offers/claim",{ body: JSON.stringify({ token }), method: "POST" },),- onSuccess: () => queryClient.invalidateQueries({ queryKey: creditBalanceQueryKey }),+ onSuccess: (landed, token) => {+ queryClient.setQueryData<CreditOffer>(creditOfferQueryKey(token), (offer) =>+ offer ? { ...offer, claimed: true, expiresAt: landed.expiresAt } : offer,+ );+ void queryClient.invalidateQueries({ queryKey: creditBalanceQueryKey });+ },});}