From ebfa25d1e87991100ce8583a79896a765fa03332 Mon Sep 17 00:00:00 2001 From: anonymousratwastaken Date: Sat, 24 Oct 2026 16:40:08 +0100 Subject: [PATCH] Rework donate flow into guided steps with gift options - Split the donate page into step components and reorder the flow: intent, rank or amount, recipient, gift, upgrade target, then confirm - Let a gift go to a player on the other edition, and allow anonymous gifts (donor is left blank in metadata) - Look up the recipient's current rank for upgrades and disable ranks they already hold - Validate custom amounts on the server as integers between CUSTOM_MIN and CUSTOM_MAX - Show friendly messages for checkout errors and send users back to the step that needs fixing - Build the Stripe appearance from the page's glow accent colour, and tint the glow to match a custom amount's unlocked tier --- src/app/api/donations/checkout/route.ts | 16 +- src/app/donate/page.tsx | 787 +++++++++++++----------- src/components/donate-amount.tsx | 104 ++++ src/components/donate-confirm.tsx | 54 ++ src/components/donate-gift.tsx | 158 +++++ src/components/donate-hand.tsx | 203 ++++++ src/components/donate-player.tsx | 272 ++++++++ src/components/donate-podium.tsx | 164 +++++ src/components/segmented.tsx | 68 ++ src/lib/donate-errors.ts | 36 ++ src/lib/donations.ts | 4 + src/lib/player-lookup.ts | 44 ++ src/lib/stripe-appearance.ts | 74 +++ src/lib/use-fine-pointer.ts | 16 + 14 files changed, 1642 insertions(+), 358 deletions(-) create mode 100644 src/components/donate-amount.tsx create mode 100644 src/components/donate-confirm.tsx create mode 100644 src/components/donate-gift.tsx create mode 100644 src/components/donate-hand.tsx create mode 100644 src/components/donate-player.tsx create mode 100644 src/components/donate-podium.tsx create mode 100644 src/components/segmented.tsx create mode 100644 src/lib/donate-errors.ts create mode 100644 src/lib/player-lookup.ts create mode 100644 src/lib/stripe-appearance.ts create mode 100644 src/lib/use-fine-pointer.ts diff --git a/src/app/api/donations/checkout/route.ts b/src/app/api/donations/checkout/route.ts index f7ba1e9..ecb0de2 100644 --- a/src/app/api/donations/checkout/route.ts +++ b/src/app/api/donations/checkout/route.ts @@ -1,22 +1,23 @@ import { NextRequest, NextResponse } from "next/server"; import { getStripe } from "@/lib/stripe"; import { cfg } from "@/lib/cfg"; -import { TIERS, tierForAmount } from "@/lib/donations"; +import { TIERS, tierForAmount, CUSTOM_MIN, CUSTOM_MAX } from "@/lib/donations"; import { minecraftApi } from "@/lib/minecraft-api"; import { minecraft } from "@/lib/servertap"; export async function POST(req: NextRequest) { try { const body = await req.json(); - const { platform, username, tier, customAmount, customRecurring, giftTo, upgrade } = body as { - platform: "java" | "bedrock"; username: string; tier: string; customAmount?: number; customRecurring?: boolean; giftTo?: string; upgrade?: boolean; + const { platform, giftPlatform, username, tier, customAmount, customRecurring, giftTo, upgrade, anonymous } = body as { + platform: "java" | "bedrock"; giftPlatform?: "java" | "bedrock"; username: string; tier: string; customAmount?: number; customRecurring?: boolean; giftTo?: string; upgrade?: boolean; anonymous?: boolean; }; if (!username || !platform || !tier) return NextResponse.json({ error: "Missing fields" }, { status: 400 }); // resolve recipient first — validates the account exists and gives us // uuid/xuid so the webhook can grant by UUID instead of name const recipientName = (giftTo?.trim() || username).trim(); - const recipientPlatform = platform; + // A gift can go to a player on the other edition from the donor. + const recipientPlatform = giftTo?.trim() && (giftPlatform === "java" || giftPlatform === "bedrock") ? giftPlatform : platform; const resolved = await minecraftApi.resolvePlayerIdentifier({ type: recipientPlatform, username: recipientName }).catch((e: any) => { return { error: e?.message || "Could not resolve that player" } as const; }); @@ -25,8 +26,8 @@ export async function POST(req: NextRequest) { let price = 0; let tierId = tier; let isSub = false; let label = ""; let verifiedFrom: string | null = null; if (tier === "custom") { - if (!customAmount || customAmount < 100) return NextResponse.json({ error: "Custom amount min £1" }, { status: 400 }); - price = customAmount; isSub = !!customRecurring; + if (!Number.isInteger(customAmount) || customAmount! < CUSTOM_MIN || customAmount! > CUSTOM_MAX) return NextResponse.json({ error: "Custom amount must be between £1 and £1,000" }, { status: 400 }); + price = customAmount!; isSub = !!customRecurring; // >=£5/mo recurring custom grants Patron const unlocked = isSub && price >= TIERS.patron.price ? "patron" : tierForAmount(price); label = unlocked ? `Custom — unlocks ${unlocked}` : "Custom donation"; @@ -54,7 +55,8 @@ export async function POST(req: NextRequest) { const metadata: Record = { tier: tierId, platform: recipientPlatform, username: recipient.username, uuid: recipient.uuid ?? "", xuid: recipient.xuid ?? "", - donor: username, gift: giftTo ? "1" : "0", + // An anonymous gift leaves the donor blank; the webhook then says "someone". + donor: giftTo && anonymous ? "" : username, gift: giftTo ? "1" : "0", custom: tier === "custom" ? "1" : "0", customAmount: String(price), isSub: isSub ? "1" : "0", upgradeFrom: verifiedFrom || "", upgrade: verifiedFrom ? "1" : "0", }; diff --git a/src/app/donate/page.tsx b/src/app/donate/page.tsx index 8c60e01..2ae250c 100644 --- a/src/app/donate/page.tsx +++ b/src/app/donate/page.tsx @@ -1,6 +1,5 @@ "use client"; -import { Suspense, useEffect, useMemo, useState } from "react"; -import Link from "next/link"; +import { Suspense, useEffect, useMemo, useRef, useState } from "react"; import { useSearchParams } from "next/navigation"; import { loadStripe, type Appearance } from "@stripe/stripe-js"; import { @@ -11,12 +10,21 @@ import { } from "@stripe/react-stripe-js/checkout"; import { toast } from "sonner"; import { ArrowLeft, Loader2, Leaf } from "lucide-react"; -import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; -import { TIERS, tierForAmount, upgradePrice } from "@/lib/donations"; +import { CUSTOM_MAX, CUSTOM_MIN, TIERS, tierForCustom, upgradePrice, type TierId } from "@/lib/donations"; +import { explainCheckoutError } from "@/lib/donate-errors"; +import { usePlayerLookup } from "@/lib/player-lookup"; +import { useFinePointer } from "@/lib/use-fine-pointer"; +import { buildStripeAppearance } from "@/lib/stripe-appearance"; import { TopBar } from "@/components/top-bar"; import { DonateGlow, glowAccentStyle, type GlowTheme } from "@/components/donate-glow"; +import { DonateHand, type Intent } from "@/components/donate-hand"; +import { DonatePodium, type Rank } from "@/components/donate-podium"; +import { GiftStage } from "@/components/donate-gift"; +import { AmountStage } from "@/components/donate-amount"; +import { ConfirmStage } from "@/components/donate-confirm"; +import { PlayerStage } from "@/components/donate-player"; const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ?? ""); @@ -31,6 +39,8 @@ type Answers = { platform: "java" | "bedrock"; player: string; giftTo: string; + giftPlatform: "" | "java" | "bedrock"; + anonymous: boolean; customPounds: string; customRecurring: boolean; }; @@ -39,158 +49,164 @@ const EMPTY_ANSWERS: Answers = { intent: "", rank: "", upgradeTo: "", - gift: "", + // Most donations are for the donor, so that is the starting answer. + gift: "no", platform: "java", player: "", giftTo: "", + giftPlatform: "", + anonymous: false, customPounds: "", customRecurring: false, }; -function Choice({ title, description, checked, disabled, onClick }: { - title: React.ReactNode; - description?: React.ReactNode; - checked: boolean; - disabled?: boolean; - onClick: () => void; +const money = (pence: number) => `£${(pence / 100).toFixed(2)}`; + +// The rank the recipient already holds, which decides what an upgrade costs. +type RankLookup = { status: "idle" | "checking" | "found" | "none" | "error"; current: TierId | null; label?: string }; +const IDLE_RANK: RankLookup = { status: "idle", current: null }; + +function useCurrentRank(raw: string, platform: "java" | "bedrock", enabled: boolean): RankLookup { + const name = raw.trim(); + const key = `${platform}:${name.toLowerCase()}`; + const [result, setResult] = useState<{ key: string; value: RankLookup } | null>(null); + const active = enabled && name.length >= 3; + + useEffect(() => { + if (!active) return; + let stale = false; + const t = setTimeout(async () => { + let value: RankLookup = { status: "error", current: null }; + try { + const r = await fetch(`/api/donations/verify?username=${encodeURIComponent(name)}&platform=${platform}`); + const j = await r.json(); + if (r.ok && !j.error) value = j.current ? { status: "found", current: j.current, label: j.label } : { status: "none", current: null }; + } catch {} + if (!stale) setResult({ key, value }); + }, 400); + return () => { stale = true; clearTimeout(t); }; + }, [active, key, platform, name]); + + if (!active) return IDLE_RANK; + if (result?.key !== key) return { status: "checking", current: null }; + return result.value; +} + +// The upgrade step's podium. The recipient's current rank is looked up from +// their name: ranks at or below it stay on the podium but cannot be picked, +// and the rest show the price of the difference. +function UpgradeStage({ value, onChange, onPreview, rank, name }: { + value: string; + onChange: (v: Rank) => void; + onPreview: (id: Rank | null) => void; + rank: RankLookup; + name: string; }) { - return ( - - ); -} + const current = rank.current; + const known = rank.status === "found"; + // Iron is the floor: it is never an upgrade target. Until the current rank + // is known nothing is priced, and if it cannot be found nothing can be picked. + const canPick = (id: Rank) => + id !== "iron" && rank.status !== "none" && rank.status !== "error" && !(current && !upgradePrice(current, id)); + const disabled = (["iron", "gold", "diamond"] as const).filter((id) => !canPick(id)); -function Field({ className, ...props }: React.InputHTMLAttributes) { return ( - - ); -} - -function UpgradeTargetPicker({ value, onChange, player }: { value: string; onChange: (v: string)=>void; player: string }) { - const [verified, setVerified] = useState<{current:string|null;label?:string}|null>(null); - useEffect(()=>{ - const name=(player||"").trim(); - if(name.length<3){setVerified(null);return;} - let cancelled=false; - const t=setTimeout(async()=>{ - try{ - const r=await fetch(`/api/donations/verify?username=${encodeURIComponent(name)}`); - const j=await r.json(); - if(!cancelled) setVerified(j.error?null:j); - }catch{ if(!cancelled) setVerified(null); } - },500); - return()=>{cancelled=true;clearTimeout(t);}; - },[player]); - return (<> - {verified?.current ?

Verified current: {verified.label} — price will be difference

: player.trim().length>=3 ?

No rank found for "{player.trim()}" — upgrade requires an existing rank.

:

Enter your Minecraft name in the next step to verify.

} -
- {(["gold","diamond"] as const).map(id=>{ - const t=(TIERS as any)[id]; - const disabled = !!verified?.current && !upgradePrice(verified.current as any, id as any); - const price = verified?.current ? upgradePrice(verified.current as any, id as any) : null; - return onChange(id)} title={`${t.label}${price ? ` — £${(price/100).toFixed(2)} upgrade` : ` — £${(t.price/100).toFixed(2)}`}`} description={disabled ? `Already have ${verified?.label} or higher` : t.perks.join(" · ")} />; - })} +
+

+ {rank.status === "checking" ? "Checking their current rank…" + : known ? <>{name} is {rank.label} now + : rank.status === "none" ? <>No rank found for "{name}". Upgrades need an existing rank, so go back to check the name or buy a rank instead. + : rank.status === "error" ? "We couldn't check their rank just now. Go back and try again in a moment." + : null} +

+ { + if (!canPick(id)) return null; + const diff = current ? upgradePrice(current, id) : null; + return diff != null ? money(diff) : null; + }} + note={(id) => (canPick(id) ? (known ? "upgrade price" : undefined) : id === "iron" ? "Starting rank" : current === id ? "Their rank" : undefined)} + />
- ); + ); } -type Pending = { +// What the confirm and payment steps list, worked out from the answers. +type Summary = { rows: { label: string; value: React.ReactNode }[]; total: string; perks?: string[] }; + +function confirmSummary(ans: Answers, rank: RankLookup): Summary { + const edition = ans.gift === "yes" ? ans.giftPlatform || ans.platform : ans.platform; + const rows: Summary["rows"] = [ + { label: "Edition", value: {edition} }, + ]; + let total = "—"; + let perks: string[] | undefined; + if (ans.intent === "rank" && ans.rank) { + const t = TIERS[ans.rank as "iron" | "gold" | "diamond"]; + rows.push({ label: "Getting", value: {t.label} }); + total = money(t.price); + perks = [...t.perks]; + } else if (ans.intent === "patron") { + rows.push({ label: "Getting", value: {TIERS.patron.label} }); + total = `${money(TIERS.patron.price)} / month`; + perks = [...TIERS.patron.perks]; + } else if (ans.intent === "upgrade" && ans.upgradeTo) { + const t = TIERS[ans.upgradeTo as "gold" | "diamond"]; + const diff = rank.current ? upgradePrice(rank.current, ans.upgradeTo as TierId) : null; + if (rank.label) rows.push({ label: "Current rank", value: rank.label }); + rows.push({ label: "Getting", value: {t.label} }); + total = diff != null ? money(diff) : "Worked out at checkout"; + perks = [...t.perks]; + } else if (ans.intent === "custom") { + const pounds = parseFloat(ans.customPounds); + const pence = Math.round((isNaN(pounds) ? 0 : pounds) * 100); + const unlocked = tierForCustom(pence, ans.customRecurring); + rows.push({ label: "Getting", value: unlocked ? {TIERS[unlocked as keyof typeof TIERS].label} : "Donation" }); + rows.push({ label: "Frequency", value: ans.customRecurring ? "Monthly" : "One-time" }); + total = `${money(pence)}${ans.customRecurring ? " / month" : ""}`; + if (unlocked) perks = [...TIERS[unlocked as keyof typeof TIERS].perks]; + } + return { rows, total, perks }; +} + +type Pending = Summary & { clientSecret: string; - label: string; - perks: string[]; isSub: boolean; - forUser: string; - gift: boolean; + recipient: string; + platform: "java" | "bedrock"; + // Who a gift is from; absent when it is not a gift. + from?: string; }; -function useStripeAppearance() { - return useMemo(() => { - const cs = getComputedStyle(document.documentElement); - const v = (n: string) => cs.getPropertyValue(n).trim(); - const primary = v("--primary"); - const fg = v("--foreground"); - const bg = v("--background"); - const border = v("--border"); - const input = v("--input"); - const mutedFg = v("--muted-foreground"); - const destructive = v("--destructive"); - const accent = v("--accent"); - const radius = v("--radius") || "0.75rem"; - const appearance: Appearance = { - theme: "night", - labels: "above", - variables: { - fontFamily: - "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Ubuntu, sans-serif", - colorPrimary: primary, - colorPrimaryText: v("--primary-foreground"), - colorBackground: bg, - colorText: fg, - colorTextSecondary: mutedFg, - colorTextPlaceholder: mutedFg, - colorIcon: mutedFg, - colorDanger: destructive, - colorSuccess: primary, - borderRadius: radius, - }, - rules: { - ".Input": { border: `1px solid ${input}`, backgroundColor: "transparent", boxShadow: "none" }, - ".Input:focus": { border: `1px solid ${primary}`, boxShadow: "none" }, - ".Input--invalid": { border: `1px solid ${destructive}`, boxShadow: "none" }, - ".Label": { color: mutedFg, fontWeight: "500", marginBottom: "6px" }, - ".Tab": { border: `1px solid ${border}`, backgroundColor: "transparent", boxShadow: "none" }, - ".Tab:hover": { backgroundColor: accent, boxShadow: "none" }, - ".Tab--selected": { borderColor: primary, boxShadow: "none" }, - ".AccordionItem": { border: `1px solid ${border}`, backgroundColor: "transparent", boxShadow: "none" }, - ".AccordionItem--selected": { borderColor: primary, boxShadow: "none" }, - ".Block": { border: `1px solid ${border}`, backgroundColor: "transparent", boxShadow: "none" }, - ".Divider": { backgroundColor: border }, - ".Error": { color: destructive }, - ".TermsText": { color: mutedFg }, - }, - }; - return { appearance }; +function PaymentStage({ pending, glow, onBack }: { pending: Pending; glow: GlowTheme; onBack: () => void }) { + const root = useRef(null); + const [appearance, setAppearance] = useState(null); + // The accent lives on this element, so Stripe's colours are read from here. + useEffect(() => { + if (root.current) setAppearance(buildStripeAppearance(root.current)); }, []); -} -function PaymentStage({ pending, onBack }: { pending: Pending; onBack: () => void }) { - const { appearance } = useStripeAppearance(); return ( - - - +
+ + {appearance ? ( + + + + ) : ( +
+ +
+ )} +
); } @@ -211,7 +227,7 @@ function CheckoutShell({ pending, onBack }: { pending: Pending; onBack: () => vo

Couldn't load checkout

{state.error.message}

- +
); @@ -223,6 +239,7 @@ function CheckoutShell({ pending, onBack }: { pending: Pending; onBack: () => vo const total = checkout.total.total.minorUnitsAmount / divisor; const fmt = (n: number) => new Intl.NumberFormat("en-GB", { style: "currency", currency }).format(n); + const totalText = `${fmt(total)}${pending.isSub ? " / month" : ""}`; async function pay(e: React.FormEvent) { e.preventDefault(); @@ -240,72 +257,75 @@ function CheckoutShell({ pending, onBack }: { pending: Pending; onBack: () => vo } } + const summary = { + recipient: pending.recipient, + platform: pending.platform, + from: pending.from, + rows: pending.rows, + total: totalText, + perks: pending.perks, + }; + return (
-