Skip to content

Open source CapCut alternative.

TypeScript

feat(site): sell plans in local currencies

David Lee5f6a3f17791
diff --git a/site/src/app/[locale]/cut/[currency]/page.tsx b/site/src/app/[locale]/cut/[currency]/page.tsx
index 73dc4938..56e824e1 100644
--- a/site/src/app/[locale]/cut/[currency]/page.tsx
+++ b/site/src/app/[locale]/cut/[currency]/page.tsx
@@ -1,8 +1,19 @@
import type { Metadata } from "next";
+import { notFound } from "next/navigation";
import { getTranslations } from "next-intl/server";
import { CutLanding } from "@/app/[locale]/cut/_components/landing/CutLanding";
import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";
+import { CURRENCIES, isCurrency } from "@/lib/billing/currencies";
+
+type Params = { params: Promise<{ currency: string }> };
+
+// The landing prices its plans in its visitor's currency, so it is
+// prerendered once per currency; the proxy picks the one for the visitor's
+// country (src/proxy.ts), and the segment never shows in a URL.
+export function generateStaticParams() {
+ return CURRENCIES.map((currency) => ({ currency }));
+}
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations("landing.meta");
@@ -50,11 +61,15 @@ const WEBSITE_LD = {
// The Cut marketing landing, served at "/" on every host by the proxy's
// "/…" → "/cut/…" rewrite.
-export default function CutLandingPage() {
+export default async function CutLandingPage({ params }: Params) {
+ const { currency } = await params;
+ if (!isCurrency(currency)) {
+ notFound();
+ }
return (
<>
<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(WEBSITE_LD) }} />
- <CutLanding />
+ <CutLanding currency={currency} />
</>
);
}
diff --git a/site/src/app/[locale]/cut/_components/landing/CutLanding.tsx b/site/src/app/[locale]/cut/_components/landing/CutLanding.tsx
index 00814a67..c967d83f 100644
--- a/site/src/app/[locale]/cut/_components/landing/CutLanding.tsx
+++ b/site/src/app/[locale]/cut/_components/landing/CutLanding.tsx
@@ -6,18 +6,20 @@ import { CutOpenSource } from "@/app/[locale]/cut/_components/landing/CutOpenSou
import { CutPricing } from "@/app/[locale]/cut/_components/landing/CutPricing";
import { CutTopNav } from "@/app/[locale]/cut/_components/landing/CutTopNav";
import { CutWorksWith } from "@/app/[locale]/cut/_components/landing/CutWorksWith";
+import type { Currency } from "@/lib/billing/currencies";
// The donkeycut.com marketing page, on the cream visual system. Every CTA into
// the app is gated on session (useAppEntryHref): signed-out clicks route to
// sign-in first. The nav mirrors this — a "Log in" link with a "Sign up" pill
-// when signed out, "Go to App" when signed in.
-export function CutLanding() {
+// when signed out, "Go to App" when signed in. The plans price in the
+// visitor's currency, which the page has from its address.
+export function CutLanding({ currency }: { currency: Currency }) {
return (
<main className="min-h-screen bg-background font-system text-foreground antialiased">
<CutTopNav />
<CutHero />
<CutWorksWith />
- <CutPricing />
+ <CutPricing currency={currency} />
<CutLocal />
<CutOpenSource />
<CutFinalCTA />
diff --git a/site/src/app/[locale]/cut/_components/landing/CutPricing.tsx b/site/src/app/[locale]/cut/_components/landing/CutPricing.tsx
index 66a68f44..087b7545 100644
--- a/site/src/app/[locale]/cut/_components/landing/CutPricing.tsx
+++ b/site/src/app/[locale]/cut/_components/landing/CutPricing.tsx
@@ -2,6 +2,7 @@
import { useTranslations } from "next-intl";
+import { ChargeCurrencyProvider } from "@/app/_components/ChargeCurrencyProvider";
import { Headline } from "@/app/_components/landing/LandingPrimitives";
import { PricingPlanCard } from "@/app/_components/landing/PricingPlanCard";
import { useAppEntryHref } from "@/app/_components/landing/useAppEntryHref";
@@ -11,8 +12,18 @@ import {
useCutPlan,
useCutPricingPlans,
} from "@/app/[locale]/cut/_components/landing/cutPricingPlans";
+import type { Currency } from "@/lib/billing/currencies";
-export function CutPricing() {
+// The plans price in the currency the landing was rendered for.
+export function CutPricing({ currency }: { currency: Currency }) {
+ return (
+ <ChargeCurrencyProvider currency={currency}>
+ <Plans />
+ </ChargeCurrencyProvider>
+ );
+}
+
+function Plans() {
const isDesktop = useMediaQuery("(min-width: 768px)");
const appHref = useAppEntryHref();
const t = useTranslations("landing.pricing");
diff --git a/site/src/app/[locale]/cut/_components/landing/cutPricingPlans.test.tsx b/site/src/app/[locale]/cut/_components/landing/cutPricingPlans.test.tsx
new file mode 100644
index 00000000..f9402dec
--- /dev/null
+++ b/site/src/app/[locale]/cut/_components/landing/cutPricingPlans.test.tsx
@@ -0,0 +1,34 @@
+import { expect, test } from "bun:test";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { NextIntlClientProvider } from "next-intl";
+import { renderToStaticMarkup } from "react-dom/server";
+
+import { ChargeCurrencyProvider } from "@/app/_components/ChargeCurrencyProvider";
+import { PlanTermsProvider } from "@/app/_components/PlanTermsProvider";
+import { useCutPlans } from "@/app/[locale]/cut/_components/landing/cutPricingPlans";
+import type { Currency } from "@/lib/billing/currencies";
+import { SETTINGS } from "@/lib/config/registry";
+import common from "@/i18n/messages/en/common.json";
+
+function Prices() {
+ return <>{useCutPlans().map((plan) => plan.price).join(" | ")}</>;
+}
+
+const render = (currency: Currency) =>
+ renderToStaticMarkup(
+ <QueryClientProvider client={new QueryClient()}>
+ <NextIntlClientProvider locale="en" messages={{ common }} timeZone="UTC">
+ <PlanTermsProvider terms={SETTINGS.planTerms.default}>
+ <ChargeCurrencyProvider currency={currency}>
+ <Prices />
+ </ChargeCurrencyProvider>
+ </PlanTermsProvider>
+ </NextIntlClientProvider>
+ </QueryClientProvider>,
+ );
+
+test("the plan cards price in the currency they were given", () => {
+ expect(render("usd")).toBe("$5/month | $20/month | $49/month");
+ expect(render("jpy")).toBe("¥700/month | ¥2,800/month | ¥6,800/month");
+ expect(render("brl")).toBe("R$15/month | R$59/month | R$149/month");
+});
diff --git a/site/src/app/[locale]/cut/_components/landing/cutPricingPlans.ts b/site/src/app/[locale]/cut/_components/landing/cutPricingPlans.ts
index 45d78264..bc24e45e 100644
--- a/site/src/app/[locale]/cut/_components/landing/cutPricingPlans.ts
+++ b/site/src/app/[locale]/cut/_components/landing/cutPricingPlans.ts
@@ -1,12 +1,13 @@
import { useLocale, useTranslations } from "next-intl";
import type { PricingPlan } from "@/app/_components/landing/pricingPlans";
+import { useChargeCurrency } from "@/app/_components/ChargeCurrencyProvider";
import { usePlanTerms } from "@/app/_components/PlanTermsProvider";
import type { CardColor } from "@/app/_components/landing/theme";
import { promotionCovers, type AllowancePromotion } from "@/lib/billing/allowance-promotion";
-import { PAID_PLANS, PLAN_NAMES, RECOMMENDED_PLAN, type PaidPlan, type PlanTerms } from "@/lib/billing/plans";
+import { formatPrice } from "@/lib/billing/format-price";
+import { PAID_PLANS, PLAN_NAMES, planPrice, RECOMMENDED_PLAN, type PaidPlan, type PlanTerms } from "@/lib/billing/plans";
import { formatCreditCount } from "@/lib/credits/format-credits";
-import { formatUsdPlain } from "@/lib/credits/format-usd";
// The Free plan's cloud storage, as its card states it.
const FREE_STORAGE_MB = 250;
@@ -19,7 +20,8 @@ export type PlanCopy = {
plan: PaidPlan;
name: string;
body: string;
- // "$20/month"; `amount` and `cadence` split it for a large figure.
+ // "$20/month", in the currency the reader checks out in; `amount` and
+ // `cadence` split it for a large figure.
price: string;
amount: string;
cadence: string;
@@ -28,16 +30,18 @@ export type PlanCopy = {
/** Every paid plan in the reader's language, cheapest first: the landing
* cards, the welcome sequence and the upgrade modal all read it, so a plan
- * can't say two different things in two parts of the product. */
+ * can't say two different things in two parts of the product. A surface
+ * holds the cards while useChargeCurrency is pending. */
export function useCutPlans(): PlanCopy[] {
const t = useTranslations("common.plans");
const locale = useLocale();
const table = usePlanTerms();
+ const { currency } = useChargeCurrency();
return PAID_PLANS.map((plan, i) => {
const terms = table[plan];
const below = i > 0 ? PAID_PLANS[i - 1] : null;
const belowTerms = below ? table[below] : null;
- const amount = formatUsdPlain(String(terms.monthlyDollars), locale);
+ const amount = formatPrice(planPrice(terms, currency), currency, locale);
const features: PlanFeature[] = [
{ kind: "credits", text: t("credits", { credits: formatCreditCount(terms.monthlyCredits, locale) }) },
...(below ? [{ kind: "inherits" as const, text: t("everythingIn", { plan: PLAN_NAMES[below] }) }] : []),
@@ -96,6 +100,7 @@ export const NOTE_PLAN: PaidPlan = "max";
export function useCutPricingPlans(): PricingPlan[] {
const t = useTranslations("landing.plans");
const locale = useLocale();
+ const { currency } = useChargeCurrency();
const plans = useCutPlans();
return [
{
@@ -114,7 +119,7 @@ export function useCutPricingPlans(): PricingPlan[] {
t("free.subscriptions"),
],
name: t("free.name"),
- price: formatUsdPlain("0", locale),
+ price: formatPrice(0, currency, locale),
tapeColor: "coral",
},
...plans.map((copy, i): PricingPlan => ({
diff --git a/site/src/app/[locale]/cut/app/(home)/settings/_components/ProCard.tsx b/site/src/app/[locale]/cut/app/(home)/settings/_components/ProCard.tsx
index 6815608d..315826a8 100644
--- a/site/src/app/[locale]/cut/app/(home)/settings/_components/ProCard.tsx
+++ b/site/src/app/[locale]/cut/app/(home)/settings/_components/ProCard.tsx
@@ -18,6 +18,7 @@ import {
CardTitle,
} from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
+import { useChargeCurrency } from "@/app/_components/ChargeCurrencyProvider";
import { usePlanTerms } from "@/app/_components/PlanTermsProvider";
import { activeProPromotion, useCutPlan } from "@/app/[locale]/cut/_components/landing/cutPricingPlans";
import { useApiErrorText } from "@/app/[locale]/cut/app/(home)/settings/_components/useApiErrorText";
@@ -56,8 +57,9 @@ export function ProCard() {
const terms = usePlanTerms();
const promotion = config.data ? activeProPromotion(config.data.settings.proAllowancePromotion, terms.pro) : null;
const intro = useIntroOffer({ enabled: pro.data?.isActive === false });
+ const charge = useChargeCurrency();
- if (pro.isLoading) {
+ if (pro.isLoading || charge.isPending) {
return (
<Card>
<CardHeader>
diff --git a/site/src/app/_components/ChargeCurrencyProvider.tsx b/site/src/app/_components/ChargeCurrencyProvider.tsx
new file mode 100644
index 00000000..dbe17271
--- /dev/null
+++ b/site/src/app/_components/ChargeCurrencyProvider.tsx
@@ -0,0 +1,29 @@
+"use client";
+
+import { createContext, useContext, type ReactNode } from "react";
+
+import type { Currency } from "@/lib/billing/currencies";
+import { useAccountCurrency } from "@/queries/billing";
+
+// The currency every card that sells a plan prices in. The landing has it
+// from its address, which the proxy picks from the visitor's country, and
+// provides it below. Everywhere else a card prices for the signed-in account:
+// the currency Stripe already bills it in, or its country's, from the pricing
+// read the app loads as it starts. isPending holds a card until that read
+// lands, so a figure never repaints in another currency.
+export type ChargeCurrency = { currency: Currency; isPending: boolean };
+
+const ChargeCurrencyContext = createContext<ChargeCurrency | null>(null);
+
+export function ChargeCurrencyProvider({ currency, children }: { currency: Currency; children: ReactNode }) {
+ return (
+ <ChargeCurrencyContext.Provider value={{ currency, isPending: false }}>{children}</ChargeCurrencyContext.Provider>
+ );
+}
+
+/** The currency plan prices read in. */
+export function useChargeCurrency(): ChargeCurrency {
+ const page = useContext(ChargeCurrencyContext);
+ const account = useAccountCurrency({ enabled: page === null });
+ return page ?? account;
+}
diff --git a/site/src/app/api/billing/checkout/route.ts b/site/src/app/api/billing/checkout/route.ts
index d089348f..b81e5bbc 100644
--- a/site/src/app/api/billing/checkout/route.ts
+++ b/site/src/app/api/billing/checkout/route.ts
@@ -5,6 +5,8 @@ import { z } from "zod";
import { requestLocale } from "@/i18n/requestLocale";
import { auth } from "@/lib/auth";
import { introCouponId } from "@/lib/billing/intro-offer";
+import { chargeCurrency } from "@/lib/billing/charge-currency";
+import { CURRENCIES, DEFAULT_CURRENCY } from "@/lib/billing/currencies";
import { introCoupon, readIntroOffer } from "@/lib/billing/intro-offer-server";
import { metaCheckoutMetadata, trackCheckoutStarted } from "@/lib/billing/meta-checkout";
import { PAID_PLANS, PLAN_NAMES, planRank, type PaidPlan } from "@/lib/billing/plans";
@@ -19,6 +21,7 @@ import {
} from "@/lib/billing/pro-subscription";
import { STRIPE_LOCALE } from "@/lib/billing/stripe-locale";
import { drainStripe, ensureStripeCustomer, getStripe } from "@/lib/billing/stripe";
+import { countryFromHeaders } from "@/lib/config/country";
import { contextFromRequest } from "@/lib/config/effective";
import { verifyCreditOfferToken } from "@/lib/credits/offers";
import { openOfferForSubscribing, SUBSCRIBE_BONUS_METADATA_KEY } from "@/lib/credits/subscribe-bonus-claim";
@@ -30,9 +33,13 @@ import {
// The plan to buy, Pro when unnamed. A checkout opened from an offer's claim
// link names the offer by its token, so the credit that lands is the one the
-// dialog described.
+// dialog described. The currency is the one the surface priced the plan in.
const bodySchema = z
- .object({ offerToken: z.string().min(1).optional(), plan: z.enum(PAID_PLANS).optional() })
+ .object({
+ currency: z.enum(CURRENCIES).default(DEFAULT_CURRENCY),
+ offerToken: z.string().min(1).optional(),
+ plan: z.enum(PAID_PLANS).optional(),
+ })
.strict();
const HTTP_CONFLICT = 409;
@@ -54,6 +61,18 @@ export const POST = withDonkeyAuth(async (request) => {
const namedOfferId = parsed.data.offerToken ? verifyCreditOfferToken(parsed.data.offerToken) : null;
const plan = parsed.data.plan ?? "pro";
+ // The account checks out in one currency: the one Stripe already bills it
+ // in, or its country's. A card priced in another, such as one drawn before
+ // the account's pricing read landed, is refused, so the charge always
+ // matches what the person saw and no account buys another country's price.
+ const currency = await chargeCurrency(session.user.id, countryFromHeaders(request.headers));
+ if (parsed.data.currency !== currency) {
+ return NextResponse.json(
+ { error: "currency_changed", message: "Prices for your account changed. Check the new price and try again." },
+ { status: HTTP_CONFLICT },
+ );
+ }
+
// A not-yet-configured price stays a 404 (not 401) so the landing card does
// not treat it as a sign-in prompt.
const prices = await readPlanPrices();
@@ -98,6 +117,7 @@ export const POST = withDonkeyAuth(async (request) => {
...pricing,
cancel_url: `${origin}/app/settings?checkout=cancelled`,
client_reference_id: session.user.id,
+ currency,
customer: customerId,
line_items: [{ price: priceId, quantity: 1 }],
locale: STRIPE_LOCALE[requestLocale(request)],
diff --git a/site/src/app/api/billing/intro-offer/route.ts b/site/src/app/api/billing/intro-offer/route.ts
index 2ce7362e..1438fb34 100644
--- a/site/src/app/api/billing/intro-offer/route.ts
+++ b/site/src/app/api/billing/intro-offer/route.ts
@@ -1,36 +1,13 @@
import { NextResponse } from "next/server";
-import { introPriceCents } from "@/lib/billing/intro-offer";
-import { openIntroOffer, previewIntroOffer, readProPriceCents } from "@/lib/billing/intro-offer-server";
+import { openIntroOffer } from "@/lib/billing/intro-offer-server";
import { contextFromRequest } from "@/lib/config/effective";
import { withDonkeyAuth } from "@/lib/donkey-api-auth";
-// The intro offer, priced. The app loads it with GET as it starts, which
-// never starts the offer's window, so a card that sells Pro paints with the
-// offer on its first frame. The surface showing it then POSTs, and the first
-// POST starts the window. The checkout reads the same offer and applies it.
-
-// The offer on the wire. endsAt is null for a window that starts the moment
-// a surface first shows it, and runs windowHours from there.
-async function priced(offer: { percentOff: number; months: number; endsAt: Date | null; windowHours: number }) {
- const priceCents = await readProPriceCents();
- return {
- endsAt: offer.endsAt?.toISOString() ?? null,
- introCents: introPriceCents(priceCents, offer.percentOff),
- months: offer.months,
- percentOff: offer.percentOff,
- priceCents,
- windowHours: offer.windowHours,
- };
-}
-
-export const GET = withDonkeyAuth(async (request) => {
- const offer = await previewIntroOffer(await contextFromRequest(request));
- return NextResponse.json({ offer: offer ? await priced(offer) : null });
-});
-
-// Starts the window, the first time, and answers when it ends; null when no
-// offer is open.
+// The surface showing the intro offer POSTs here; the first POST starts the
+// offer's window. It answers when the window ends, null when no offer is
+// open. The app reads the offer itself from the pricing route, and checkout
+// reads the same offer and applies it.
export const POST = withDonkeyAuth(async (request) => {
const offer = await openIntroOffer(await contextFromRequest(request));
return NextResponse.json({ endsAt: offer?.endsAt.toISOString() ?? null });
diff --git a/site/src/app/api/billing/pricing/route.ts b/site/src/app/api/billing/pricing/route.ts
new file mode 100644
index 00000000..73922f80
--- /dev/null
+++ b/site/src/app/api/billing/pricing/route.ts
@@ -0,0 +1,42 @@
+import { NextResponse } from "next/server";
+
+import { chargeCurrency } from "@/lib/billing/charge-currency";
+import { toMinor } from "@/lib/billing/currencies";
+import { introPriceMinor } from "@/lib/billing/intro-offer";
+import { previewIntroOffer } from "@/lib/billing/intro-offer-server";
+import { planPrice } from "@/lib/billing/plans";
+import { contextFromRequest, getGlobalSetting } from "@/lib/config/effective";
+import { withDonkeyAuth } from "@/lib/donkey-api-auth";
+
+// What the account pays in and the intro offer open to it, priced in that
+// currency. The app loads it as it starts, so every card that sells a plan
+// paints in the right currency, with the offer, on its first frame. Reading
+// never starts the offer's window; the intro offer route's POST does.
+//
+// endsAt is null for a window that starts the moment a surface first shows
+// it, and runs windowHours from there.
+export const GET = withDonkeyAuth(async (request) => {
+ const ctx = await contextFromRequest(request);
+ const [currency, offer, terms] = await Promise.all([
+ chargeCurrency(ctx.userId, ctx.country),
+ previewIntroOffer(ctx),
+ getGlobalSetting("planTerms"),
+ ]);
+ if (!offer) {
+ return NextResponse.json({ currency, intro: null });
+ }
+
+ const priceMinor = toMinor(planPrice(terms.pro, currency), currency);
+ return NextResponse.json({
+ currency,
+ intro: {
+ currency,
+ endsAt: offer.endsAt?.toISOString() ?? null,
+ introMinor: introPriceMinor(priceMinor, offer.percentOff),
+ months: offer.months,
+ percentOff: offer.percentOff,
+ priceMinor,
+ windowHours: offer.windowHours,
+ },
+ });
+});
diff --git a/site/src/cut/components/IntroOffer.tsx b/site/src/cut/components/IntroOffer.tsx
index 1bc68e4f..a8206ce2 100644
--- a/site/src/cut/components/IntroOffer.tsx
+++ b/site/src/cut/components/IntroOffer.tsx
@@ -3,15 +3,9 @@
// The intro discount as every Pro surface states it: the terms in one line.
import { useLocale, useTranslations } from "next-intl";
-import type { Locale } from "@/i18n/locales";
-import { formatUsdPlain } from "@/lib/credits/format-usd";
+import { formatMinorPrice } from "@/lib/billing/format-price";
import type { IntroOffer } from "@/queries/billing";
-/** Cents as a price reads: 1000 → "$10", 999 → "$9.99". */
-export function priceLabel(cents: number, locale: Locale): string {
- return formatUsdPlain((cents / 100).toFixed(2), locale);
-}
-
/** The intro terms in the page's language: "50% off: $10 for your first
* month, then $20/month." */
export function useIntroTerms(): (offer: IntroOffer) => string {
@@ -19,9 +13,9 @@ export function useIntroTerms(): (offer: IntroOffer) => string {
const locale = useLocale();
return (offer) =>
t("terms", {
- full: priceLabel(offer.priceCents, locale),
+ full: formatMinorPrice(offer.priceMinor, offer.currency, locale),
months: offer.months,
percent: offer.percentOff,
- price: priceLabel(offer.introCents, locale),
+ price: formatMinorPrice(offer.introMinor, offer.currency, locale),
});
}
diff --git a/site/src/cut/components/OfferDialog.tsx b/site/src/cut/components/OfferDialog.tsx
index 31122169..4c6ea3d0 100644
--- a/site/src/cut/components/OfferDialog.tsx
+++ b/site/src/cut/components/OfferDialog.tsx
@@ -8,6 +8,7 @@
import Image from "next/image";
import { useFormatter, useTranslations } from "next-intl";
import { useEffect, useState } from "react";
+import { useChargeCurrency } from "@/app/_components/ChargeCurrencyProvider";
import { useCutPlan } from "@/app/[locale]/cut/_components/landing/cutPricingPlans";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
@@ -179,7 +180,11 @@ export function OfferDialog({
secondary?: React.ReactNode;
error?: React.ReactNode;
}) {
- const ready = useBannerReady(isOfferBanner(banner) ? banner : null);
+ // Held until the picture has loaded and the account's currency is known,
+ // so the card never repaints a price.
+ const bannerReady = useBannerReady(isOfferBanner(banner) ? banner : null);
+ const charge = useChargeCurrency();
+ const ready = bannerReady && !charge.isPending;
return (
<Dialog open={open && ready} onOpenChange={onOpenChange}>
<DialogContent
diff --git a/site/src/cut/components/PlansDialog.tsx b/site/src/cut/components/PlansDialog.tsx
index 0c7ce931..96c0b45c 100644
--- a/site/src/cut/components/PlansDialog.tsx
+++ b/site/src/cut/components/PlansDialog.tsx
@@ -8,15 +8,16 @@ import { useEffect, useRef } from "react";
import { ArrowLeft, Check, Loader2, Sparkles } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
+import { useChargeCurrency } from "@/app/_components/ChargeCurrencyProvider";
import { useApiErrorText } from "@/app/[locale]/cut/app/(home)/settings/_components/useApiErrorText";
import { useCutPlans, type PlanCopy, type PlanFeature } from "@/app/[locale]/cut/_components/landing/cutPricingPlans";
import { Button } from "@/components/ui/button";
import { Dialog, DialogBody, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
-import { priceLabel } from "@/cut/components/IntroOffer";
import { OfferSticker } from "@/cut/components/OfferSticker";
import { usePlanCheckout } from "@/cut/lib/proUpgrade";
import type { UpgradeEntry } from "@/cut/lib/upgrade";
import { track } from "@/lib/analytics";
+import { formatMinorPrice } from "@/lib/billing/format-price";
import { planRank, RECOMMENDED_PLAN, type PaidPlan } from "@/lib/billing/plans";
import { cn } from "@/lib/utils";
import { useIntroOffer, useProSubscription, type IntroOffer } from "@/queries/billing";
@@ -51,14 +52,18 @@ export function PlansDialog({
const tBilling = useTranslations("billing");
const apiErrorText = useApiErrorText();
const plans = useCutPlans();
+ const charge = useChargeCurrency();
const subscription = useProSubscription();
const current = subscription.data?.plan ?? null;
const intro = useIntroOffer({ enabled: subscription.data?.isActive === false });
const checkout = usePlanCheckout({ surface: "plans_dialog", reason: source, entry });
- // Held until the plan is known, so no column opens buyable and then locks.
- // A billing read that fails still opens it, with the failure said, so a
- // refusal is never followed by nothing.
- const ready = subscription.isError || (subscription.isSuccess && (current !== null || !intro.isPending));
+ // Held until the plan and the currency are known, so no column opens
+ // buyable and then locks, or repaints in another currency. A billing read
+ // that fails still opens it, with the failure said, so a refusal is never
+ // followed by nothing.
+ const ready =
+ subscription.isError ||
+ (subscription.isSuccess && !charge.isPending && (current !== null || !intro.isPending));
const error = checkout.error ?? subscription.error;
// Opening focuses the card itself, so no plan's button starts out looking
@@ -127,7 +132,7 @@ export function PlansDialog({
{apiErrorText(error, tBilling("billingUnavailable"))}
</p>
) : null}
- {t("footer")}
+ {t("footer", { currency: charge.currency.toUpperCase() })}
</div>
</DialogContent>
</Dialog>
@@ -199,7 +204,7 @@ function Price({ copy, offer }: { copy: PlanCopy; offer: IntroOffer | null }) {
<div className="mt-4">
<div className="flex items-baseline gap-1.5">
<span className="text-4xl font-semibold tracking-tight tabular-nums">
- {offer ? priceLabel(offer.introCents, locale) : copy.amount}
+ {offer ? formatMinorPrice(offer.introMinor, offer.currency, locale) : copy.amount}
</span>
{offer ? (
<span className="text-lg font-medium text-muted-foreground line-through tabular-nums">{copy.amount}</span>
@@ -208,7 +213,7 @@ function Price({ copy, offer }: { copy: PlanCopy; offer: IntroOffer | null }) {
</div>
<div className={cn("mt-1 text-xs font-medium", offer ? BLUE_TEXT : "text-muted-foreground")}>
{offer
- ? t("introThen", { months: offer.months, price: priceLabel(offer.priceCents, locale) })
+ ? t("introThen", { months: offer.months, price: formatMinorPrice(offer.priceMinor, offer.currency, locale) })
: t("billedMonthly")}
</div>
</div>
diff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsx
index 4297dce6..8832a29e 100644
--- a/site/src/cut/components/RequireSession.tsx
+++ b/site/src/cut/components/RequireSession.tsx
@@ -16,7 +16,7 @@ import {
import { reportExposures, useAppLoaded } from "@/lib/analytics";
import { useSession } from "@/lib/auth-client";
import { useAccountConfig } from "@/queries/accountConfig";
-import { prefetchIntroOffer } from "@/queries/billing";
+import { prefetchPricing } from "@/queries/billing";
import { useNoteOutboxSync } from "@/cut/hooks/useNoteOutboxSync";
// Session gate for the whole Cut app surface. The landing CTAs already route
@@ -63,12 +63,13 @@ export function RequireSession({ children }: { children: ReactNode }) {
reportExposures(config.data);
}, [userId, config.data]);
- // The intro offer, loaded with the account so every card that sells Pro
- // has it on its first frame. Loading it starts no window.
+ // The account's currency and intro offer, loaded with the account so every
+ // card that sells a plan has them on its first frame. Loading it starts no
+ // offer window.
const queryClient = useQueryClient();
useEffect(() => {
if (!userId) return;
- void prefetchIntroOffer(queryClient);
+ void prefetchPricing(queryClient);
}, [userId, queryClient]);
// Paint first, verify behind: the account remembered from the last visit
diff --git a/site/src/cut/components/onboarding/slides/Plans.tsx b/site/src/cut/components/onboarding/slides/Plans.tsx
index 2c51826d..7b41e357 100644
--- a/site/src/cut/components/onboarding/slides/Plans.tsx
+++ b/site/src/cut/components/onboarding/slides/Plans.tsx
@@ -8,10 +8,10 @@ import { TapedCard } from "@/app/_components/landing/LandingPrimitives";
import type { CardColor } from "@/app/_components/landing/theme";
import { useCutPlans, type PlanCopy, type PlanFeature } from "@/app/[locale]/cut/_components/landing/cutPricingPlans";
import { Button } from "@/components/ui/button";
-import { priceLabel } from "@/cut/components/IntroOffer";
import { OfferSticker } from "@/cut/components/OfferSticker";
import { usePlanCheckout } from "@/cut/lib/proUpgrade";
import { track } from "@/lib/analytics";
+import { formatMinorPrice } from "@/lib/billing/format-price";
import { RECOMMENDED_PLAN, type PaidPlan } from "@/lib/billing/plans";
import type { OnboardingRun } from "@/lib/onboarding/sequence";
import { cn } from "@/lib/utils";
@@ -65,9 +65,9 @@ export function PlansSlide({ run, exit, onSkipPro }: { run: OnboardingRun; exit:
slide's gutter to the screen edge so the next card peeks in on the
right, and the top padding keeps the tape and offer sticker. The
recommended plan comes first so it is the one on screen when the
- slide opens. The row holds until the offer read settles, which the
- app has normally done long before this slide, so the Pro card never
- paints a price the offer then replaces. */}
+ slide opens. The row holds until the pricing read settles, which the
+ app has normally done long before this slide, so no card paints a
+ price its currency or the offer then replaces. */}
<div aria-busy={intro.isPending} className={cn(intro.isPending && "invisible", "-mx-6 mt-3 flex scroll-px-6 snap-x snap-mandatory gap-4 overflow-x-auto px-6 pt-5 pb-3 [scrollbar-width:none] md:mx-0 md:mt-8 md:grid md:grid-cols-3 md:items-stretch md:gap-5 md:overflow-visible md:p-0 [&::-webkit-scrollbar]:hidden")}>
{plans.map((copy) => (
<div
@@ -197,14 +197,14 @@ function IntroPrice({ offer }: { offer: IntroOffer }) {
<>
<div className="mt-4 flex items-baseline gap-3">
<span className="text-[clamp(34px,4vw,44px)] leading-[0.95] font-semibold">
- {priceLabel(offer.introCents, locale)}
+ {formatMinorPrice(offer.introMinor, offer.currency, locale)}
</span>
<span className="text-[20px] font-semibold text-[#201715]/40 line-through decoration-2">
- {priceLabel(offer.priceCents, locale)}
+ {formatMinorPrice(offer.priceMinor, offer.currency, locale)}
</span>
</div>
<div className="mt-2.5 text-[13px] font-semibold text-[#201715]">
- {t("covers", { months: offer.months, price: priceLabel(offer.priceCents, locale) })}
+ {t("covers", { months: offer.months, price: formatMinorPrice(offer.priceMinor, offer.currency, locale) })}
</div>
</>
);
diff --git a/site/src/i18n/messages/.source-lock.json b/site/src/i18n/messages/.source-lock.json
index d0d19657..d4742883 100644
--- a/site/src/i18n/messages/.source-lock.json
+++ b/site/src/i18n/messages/.source-lock.json
@@ -105,7 +105,7 @@
"plans.get": "36572be917c8",
"plans.upgrade": "413370c98be7",
"plans.current": "ec5cfba8f01b",
- "plans.footer": "38d6bda2e5b1"
+ "plans.footer": "9f7466d09417"
},
"de/chat": {
"panel.signInToChat": "8b2dd174b118",
@@ -334,6 +334,7 @@
"apiErrors.image_too_large": "3fdb4028f18f",
"apiErrors.plan_not_an_upgrade": "d968260313e6",
"apiErrors.upgrade_in_progress": "105dee90239b",
+ "apiErrors.currency_changed": "691fd3c84c07",
"apiErrors.upgrade_payment_failed": "9f81fe318848",
"languageSaveFailed": "8d8a247bafe6",
"languageBlocked": "6cdf84383309"
@@ -3131,7 +3132,7 @@
"plans.get": "36572be917c8",
"plans.upgrade": "413370c98be7",
"plans.current": "ec5cfba8f01b",
- "plans.footer": "38d6bda2e5b1"
+ "plans.footer": "9f7466d09417"
},
"es/chat": {
"panel.signInToChat": "8b2dd174b118",
@@ -3360,6 +3361,7 @@
"apiErrors.image_too_large": "3fdb4028f18f",
"apiErrors.plan_not_an_upgrade": "d968260313e6",
"apiErrors.upgrade_in_progress": "105dee90239b",
+ "apiErrors.currency_changed": "691fd3c84c07",
"apiErrors.upgrade_payment_failed": "9f81fe318848",
"languageSaveFailed": "8d8a247bafe6",
"languageBlocked": "6cdf84383309"
@@ -6157,7 +6159,7 @@
"plans.get": "36572be917c8",
"plans.upgrade": "413370c98be7",
"plans.current": "ec5cfba8f01b",
- "plans.footer": "38d6bda2e5b1"
+ "plans.footer": "9f7466d09417"
},
"fr/chat": {
"panel.signInToChat": "8b2dd174b118",
@@ -6386,6 +6388,7 @@
"apiErrors.image_too_large": "3fdb4028f18f",
"apiErrors.plan_not_an_upgrade": "d968260313e6",
"apiErrors.upgrade_in_progress": "105dee90239b",
+ "apiErrors.currency_changed": "691fd3c84c07",
"apiErrors.upgrade_payment_failed": "9f81fe318848",
"languageSaveFailed": "8d8a247bafe6",
"languageBlocked": "6cdf84383309"
@@ -9183,7 +9186,7 @@
"plans.get": "36572be917c8",
"plans.upgrade": "413370c98be7",
"plans.current": "ec5cfba8f01b",
- "plans.footer": "38d6bda2e5b1"
+ "plans.footer": "9f7466d09417"
},
"ja/chat": {
"panel.signInToChat": "8b2dd174b118",
@@ -9412,6 +9415,7 @@
"apiErrors.image_too_large": "3fdb4028f18f",
"apiErrors.plan_not_an_upgrade": "d968260313e6",
"apiErrors.upgrade_in_progress": "105dee90239b",
+ "apiErrors.currency_changed": "691fd3c84c07",
"apiErrors.upgrade_payment_failed": "9f81fe318848",
"languageSaveFailed": "8d8a247bafe6",
"languageBlocked": "6cdf84383309"
@@ -12209,7 +12213,7 @@
"plans.get": "36572be917c8",
"plans.upgrade": "413370c98be7",
"plans.current": "ec5cfba8f01b",
- "plans.footer": "38d6bda2e5b1"
+ "plans.footer": "9f7466d09417"
},
"ko/chat": {
"panel.signInToChat": "8b2dd174b118",
@@ -12438,6 +12442,7 @@
"apiErrors.image_too_large": "3fdb4028f18f",
"apiErrors.plan_not_an_upgrade": "d968260313e6",
"apiErrors.upgrade_in_progress": "105dee90239b",
+ "apiErrors.currency_changed": "691fd3c84c07",
"apiErrors.upgrade_payment_failed": "9f81fe318848",
"languageSaveFailed": "8d8a247bafe6",
"languageBlocked": "6cdf84383309"
@@ -15235,7 +15240,7 @@
"plans.get": "36572be917c8",
"plans.upgrade": "413370c98be7",
"plans.current": "ec5cfba8f01b",
- "plans.footer": "38d6bda2e5b1"
+ "plans.footer": "9f7466d09417"
},
"pt-BR/chat": {
"panel.signInToChat": "8b2dd174b118",
@@ -15464,6 +15469,7 @@
"apiErrors.image_too_large": "3fdb4028f18f",
"apiErrors.plan_not_an_upgrade": "d968260313e6",
"apiErrors.upgrade_in_progress": "105dee90239b",
+ "apiErrors.currency_changed": "691fd3c84c07",
"apiErrors.upgrade_payment_failed": "9f81fe318848",
"languageSaveFailed": "8d8a247bafe6",
"languageBlocked": "6cdf84383309"
@@ -18261,7 +18267,7 @@
"plans.get": "36572be917c8",
"plans.upgrade": "413370c98be7",
"plans.current": "ec5cfba8f01b",
- "plans.footer": "38d6bda2e5b1"
+ "plans.footer": "9f7466d09417"
},
"zh-CN/chat": {
"panel.signInToChat": "8b2dd174b118",
@@ -18490,6 +18496,7 @@
"apiErrors.image_too_large": "3fdb4028f18f",
"apiErrors.plan_not_an_upgrade": "d968260313e6",
"apiErrors.upgrade_in_progress": "105dee90239b",
+ "apiErrors.currency_changed": "691fd3c84c07",
"apiErrors.upgrade_payment_failed": "9f81fe318848",
"languageSaveFailed": "8d8a247bafe6",
"languageBlocked": "6cdf84383309"
diff --git a/site/src/i18n/messages/de/billing.json b/site/src/i18n/messages/de/billing.json
index f6ab7d70..56af6378 100644
--- a/site/src/i18n/messages/de/billing.json
+++ b/site/src/i18n/messages/de/billing.json
@@ -81,6 +81,6 @@
"get": "{plan} holen",
"upgrade": "Upgrade auf {plan}",
"current": "Aktueller Plan",
- "footer": "Preise in USD. Pläne verlängern sich monatlich, bis du kündigst. Bei einem Upgrade wird die Differenz heute berechnet."
+ "footer": "Preise in {currency}. Abos verlängern sich monatlich, bis du kündigst. Beim Upgrade zahlst du heute die Differenz."
}
}
diff --git a/site/src/i18n/messages/de/common.json b/site/src/i18n/messages/de/common.json
index e547a203..e48d0c58 100644
--- a/site/src/i18n/messages/de/common.json
+++ b/site/src/i18n/messages/de/common.json
@@ -44,6 +44,7 @@
"image_too_large": "Bild zu groß.",
"plan_not_an_upgrade": "Dieses Konto nutzt bereits diesen oder einen höheren Plan.",
"upgrade_in_progress": "Dieses Upgrade läuft bereits.",
+ "currency_changed": "Die Preise für dein Konto haben sich geändert. Prüfe den neuen Preis und versuche es erneut.",
"upgrade_payment_failed": "Deine Karte wurde abgelehnt, daher wurde dein Plan nicht geändert. Aktualisiere deine Karte unter Abrechnung und versuche es erneut."
},
"languageSaveFailed": "Deine Sprache konnte nicht gespeichert werden. Versuch es noch einmal.",
diff --git a/site/src/i18n/messages/en/billing.json b/site/src/i18n/messages/en/billing.json
index 5270eba6..e6d94889 100644
--- a/site/src/i18n/messages/en/billing.json
+++ b/site/src/i18n/messages/en/billing.json
@@ -81,6 +81,6 @@
"get": "Get {plan}",
"upgrade": "Upgrade to {plan}",
"current": "Current plan",
- "footer": "Prices in USD. Plans renew monthly until you cancel. Moving up a plan charges the difference today."
+ "footer": "Prices in {currency}. Plans renew monthly until you cancel. Moving up a plan charges the difference today."
}
}
diff --git a/site/src/i18n/messages/en/common.json b/site/src/i18n/messages/en/common.json
index c759c2c5..483705ed 100644
--- a/site/src/i18n/messages/en/common.json
+++ b/site/src/i18n/messages/en/common.json
@@ -44,6 +44,7 @@
"image_too_large": "Image too large.",
"plan_not_an_upgrade": "This account is already on this plan or a higher one.",
"upgrade_in_progress": "This upgrade is already in progress.",
+ "currency_changed": "Prices for your account changed. Check the new price and try again.",
"upgrade_payment_failed": "Your card was declined, so your plan didn't change. Update your card in billing and try again."
},
"languageSaveFailed": "Couldn't save your language. Try again.",
diff --git a/site/src/i18n/messages/es/billing.json b/site/src/i18n/messages/es/billing.json
index 970a32ba..768c098d 100644
--- a/site/src/i18n/messages/es/billing.json
+++ b/site/src/i18n/messages/es/billing.json
@@ -81,6 +81,6 @@
"get": "Obtener {plan}",
"upgrade": "Mejorar a {plan}",
"current": "Plan actual",
- "footer": "Precios en USD. Los planes se renuevan cada mes hasta que canceles. Al mejorar de plan se cobra la diferencia hoy."
+ "footer": "Precios en {currency}. Los planes se renuevan mensualmente hasta que canceles. Si pasas a un plan superior, se cobra la diferencia hoy."
}
}
diff --git a/site/src/i18n/messages/es/common.json b/site/src/i18n/messages/es/common.json
index 834455c7..b21cfd42 100644
--- a/site/src/i18n/messages/es/common.json
+++ b/site/src/i18n/messages/es/common.json
@@ -44,6 +44,7 @@
"image_too_large": "Imagen demasiado grande.",
"plan_not_an_upgrade": "Esta cuenta ya tiene este plan o uno superior.",
"upgrade_in_progress": "Esta actualización ya está en curso.",
+ "currency_changed": "Los precios de tu cuenta cambiaron. Revisa el nuevo precio y vuelve a intentarlo.",
"upgrade_payment_failed": "Tu tarjeta fue rechazada, así que tu plan no cambió. Actualiza tu tarjeta en facturación e inténtalo de nuevo."
},
"languageSaveFailed": "No se pudo guardar tu idioma. Inténtalo de nuevo.",
diff --git a/site/src/i18n/messages/fr/billing.json b/site/src/i18n/messages/fr/billing.json
index b1a21902..0720a092 100644
--- a/site/src/i18n/messages/fr/billing.json
+++ b/site/src/i18n/messages/fr/billing.json
@@ -81,6 +81,6 @@
"get": "Obtenir {plan}",
"upgrade": "Passer à {plan}",
"current": "Forfait actuel",
- "footer": "Prix en USD. Renouvellement mensuel automatique jusqu'à résiliation. Passer à un forfait supérieur facture la différence aujourd'hui."
+ "footer": "Prix en {currency}. Les forfaits se renouvellent chaque mois jusqu’à votre résiliation. Passer à un forfait supérieur facture la différence aujourd’hui."
}
}
diff --git a/site/src/i18n/messages/fr/common.json b/site/src/i18n/messages/fr/common.json
index 3576ca84..4d1ac682 100644
--- a/site/src/i18n/messages/fr/common.json
+++ b/site/src/i18n/messages/fr/common.json
@@ -44,6 +44,7 @@
"image_too_large": "Image trop volumineuse.",
"plan_not_an_upgrade": "Ce compte bénéficie déjà de ce forfait ou d'un forfait supérieur.",
"upgrade_in_progress": "Cette mise à niveau est déjà en cours.",
+ "currency_changed": "Les tarifs de votre compte ont changé. Vérifiez le nouveau prix et réessayez.",
"upgrade_payment_failed": "Votre carte a été refusée, votre forfait n'a donc pas changé. Mettez à jour votre carte dans la facturation et réessayez."
},
"languageSaveFailed": "Impossible d'enregistrer votre langue. Réessayez.",
diff --git a/site/src/i18n/messages/ja/billing.json b/site/src/i18n/messages/ja/billing.json
index fc1eb676..56978400 100644
--- a/site/src/i18n/messages/ja/billing.json
+++ b/site/src/i18n/messages/ja/billing.json
@@ -81,6 +81,6 @@
"get": "{plan}を入手",
"upgrade": "{plan}にアップグレード",
"current": "現在のプラン",
- "footer": "価格は米ドル表記です。プランは解約するまで毎月更新されます。上位プランに変更する場合、本日差額が請求されます。"
+ "footer": "表示価格は{currency}です。プランは解約するまで毎月自動更新されます。上位プランへの変更時は、本日差額が請求されます。"
}
}
diff --git a/site/src/i18n/messages/ja/common.json b/site/src/i18n/messages/ja/common.json
index 9cd8e4e7..1ec9146c 100644
--- a/site/src/i18n/messages/ja/common.json
+++ b/site/src/i18n/messages/ja/common.json
@@ -44,6 +44,7 @@
"image_too_large": "画像が大きすぎます。",
"plan_not_an_upgrade": "このアカウントはすでにこのプラン、または上位プランをご利用中です。",
"upgrade_in_progress": "このアップグレードはすでに進行中です。",
+ "currency_changed": "アカウントの価格が変更されました。新しい価格を確認して、もう一度お試しください。",
"upgrade_payment_failed": "カードの支払いが拒否されたため、プランは変更されませんでした。請求設定でカード情報を更新し、もう一度お試しください。"
},
"languageSaveFailed": "言語を保存できませんでした。もう一度お試しください。",
diff --git a/site/src/i18n/messages/ko/billing.json b/site/src/i18n/messages/ko/billing.json
index eeef39c9..05346098 100644
--- a/site/src/i18n/messages/ko/billing.json
+++ b/site/src/i18n/messages/ko/billing.json
@@ -81,6 +81,6 @@
"get": "{plan} 선택",
"upgrade": "{plan}(으)로 업그레이드",
"current": "현재 요금제",
- "footer": "가격은 USD 기준이에요. 직접 취소하기 전까지 요금제가 매달 자동 갱신돼요. 더 높은 요금제로 변경하면 오늘 차액이 결제돼요."
+ "footer": "가격은 {currency} 기준이에요. 취소할 때까지 매월 갱신돼요. 상위 플랜으로 변경하면 오늘 차액이 청구돼요."
}
}
diff --git a/site/src/i18n/messages/ko/common.json b/site/src/i18n/messages/ko/common.json
index b5d882ce..dddad73d 100644
--- a/site/src/i18n/messages/ko/common.json
+++ b/site/src/i18n/messages/ko/common.json
@@ -44,6 +44,7 @@
"image_too_large": "이미지가 너무 커요.",
"plan_not_an_upgrade": "이 계정은 이미 이 플랜 또는 더 높은 플랜을 이용 중이에요.",
"upgrade_in_progress": "이 업그레이드는 이미 진행 중이에요.",
+ "currency_changed": "계정의 가격이 변경되었어요. 새 가격을 확인하고 다시 시도해 보세요.",
"upgrade_payment_failed": "카드가 승인 거부되어 플랜이 변경되지 않았어요. 결제 정보에서 카드를 업데이트하고 다시 시도해 주세요."
},
"languageSaveFailed": "언어를 저장하지 못했어요. 다시 시도해 주세요.",
diff --git a/site/src/i18n/messages/pt-BR/billing.json b/site/src/i18n/messages/pt-BR/billing.json
index 24e0c768..aebedf55 100644
--- a/site/src/i18n/messages/pt-BR/billing.json
+++ b/site/src/i18n/messages/pt-BR/billing.json
@@ -81,6 +81,6 @@
"get": "Obter {plan}",
"upgrade": "Fazer upgrade para o {plan}",
"current": "Plano atual",
- "footer": "Preços em USD. Os planos se renovam mensalmente até você cancelar. Mudar para um plano superior cobra a diferença hoje."
+ "footer": "Preços em {currency}. Os planos renovam mensalmente até você cancelar. Ao mudar para um plano superior, a diferença é cobrada hoje."
}
}
diff --git a/site/src/i18n/messages/pt-BR/common.json b/site/src/i18n/messages/pt-BR/common.json
index 6d8140af..7f15fb73 100644
--- a/site/src/i18n/messages/pt-BR/common.json
+++ b/site/src/i18n/messages/pt-BR/common.json
@@ -44,6 +44,7 @@
"image_too_large": "Imagem grande demais.",
"plan_not_an_upgrade": "Esta conta já está neste plano ou em um superior.",
"upgrade_in_progress": "Este upgrade já está em andamento.",
+ "currency_changed": "Os preços da sua conta mudaram. Verifique o novo preço e tente novamente.",
"upgrade_payment_failed": "Seu cartão foi recusado, portanto seu plano não mudou. Atualize o cartão no faturamento e tente novamente."
},
"languageSaveFailed": "Não foi possível salvar seu idioma. Tente novamente.",
diff --git a/site/src/i18n/messages/zh-CN/billing.json b/site/src/i18n/messages/zh-CN/billing.json
index aaf0bfc7..19e15279 100644
--- a/site/src/i18n/messages/zh-CN/billing.json
+++ b/site/src/i18n/messages/zh-CN/billing.json
@@ -81,6 +81,6 @@
"get": "获取 {plan}",
"upgrade": "升级到 {plan}",
"current": "当前方案",
- "footer": "价格以美元计。方案按月自动续费,直至取消。升级方案今日将收取差价。"
+ "footer": "价格以 {currency} 结算。方案按月自动续订,直至取消。升级方案今日收取差价。"
}
}
diff --git a/site/src/i18n/messages/zh-CN/common.json b/site/src/i18n/messages/zh-CN/common.json
index 9e719f1e..1f954f37 100644
--- a/site/src/i18n/messages/zh-CN/common.json
+++ b/site/src/i18n/messages/zh-CN/common.json
@@ -44,6 +44,7 @@
"image_too_large": "图片过大。",
"plan_not_an_upgrade": "该账号已在使用此方案或更高级方案。",
"upgrade_in_progress": "此升级已在进行中。",
+ "currency_changed": "你账户的价格已变动。请查看新价格后重试。",
"upgrade_payment_failed": "你的银行卡被拒,方案未作更改。请在账单中更新银行卡并重试。"
},
"languageSaveFailed": "无法保存语言设置。请重试。",
diff --git a/site/src/lib/billing/charge-currency.test.ts b/site/src/lib/billing/charge-currency.test.ts
new file mode 100644
index 00000000..e56abf58
--- /dev/null
+++ b/site/src/lib/billing/charge-currency.test.ts
@@ -0,0 +1,17 @@
+import { expect, test } from "bun:test";
+
+import { currencyFor } from "./charge-currency";
+
+test("an account Stripe already bills keeps its currency anywhere", () => {
+ expect(currencyFor("usd", "BR")).toBe("usd");
+ expect(currencyFor("eur", "US")).toBe("eur");
+});
+
+test("an account never billed pays in its country's currency", () => {
+ expect(currencyFor(null, "BR")).toBe("brl");
+ expect(currencyFor(null, "PL")).toBe("usd");
+});
+
+test("a customer billed in a currency no plan sells in is refused", () => {
+ expect(() => currencyFor("inr", "IN")).toThrow();
+});
diff --git a/site/src/lib/billing/charge-currency.ts b/site/src/lib/billing/charge-currency.ts
new file mode 100644
index 00000000..0da5a650
--- /dev/null
+++ b/site/src/lib/billing/charge-currency.ts
@@ -0,0 +1,29 @@
+import { isCurrency, marketCurrency, type Currency } from "@/lib/billing/currencies";
+import { getStripe } from "@/lib/billing/stripe";
+import { prisma } from "@/lib/prisma";
+
+// The currency an account's plans price and check out in. Stripe bills a
+// customer in one currency for good once it has subscribed, so an account
+// Stripe already bills keeps that currency wherever it signs in from; any
+// other account pays in its country's.
+
+/** The currency for a customer Stripe bills in `billed` (null when it never
+ * has), reached from `country`. */
+export function currencyFor(billed: string | null, country: string | null): Currency {
+ if (!billed) {
+ return marketCurrency(country);
+ }
+ if (!isCurrency(billed)) {
+ throw new Error(`Stripe bills this customer in ${billed.toUpperCase()}, which no plan sells in`);
+ }
+ return billed;
+}
+
+export async function chargeCurrency(userId: string, country: string | null): Promise<Currency> {
+ const user = await prisma.user.findUnique({ where: { id: userId }, select: { stripeCustomerId: true } });
+ if (!user?.stripeCustomerId) {
+ return marketCurrency(country);
+ }
+ const customer = await getStripe().customers.retrieve(user.stripeCustomerId);
+ return currencyFor(customer.deleted ? null : customer.currency ?? null, country);
+}
diff --git a/site/src/lib/billing/currencies.test.ts b/site/src/lib/billing/currencies.test.ts
new file mode 100644
index 00000000..0a49dec5
--- /dev/null
+++ b/site/src/lib/billing/currencies.test.ts
@@ -0,0 +1,18 @@
+import { expect, test } from "bun:test";
+
+import { fromMinor, marketCurrency, toMinor } from "./currencies";
+
+test("a country pays in its own currency, and one with none in USD", () => {
+ expect(marketCurrency("DE")).toBe("eur");
+ expect(marketCurrency("BR")).toBe("brl");
+ expect(marketCurrency("JP")).toBe("jpy");
+ expect(marketCurrency("PL")).toBe("usd");
+ expect(marketCurrency(null)).toBe("usd");
+});
+
+test("minor units follow the currency", () => {
+ expect(toMinor(59, "brl")).toBe(5900);
+ expect(toMinor(2800, "jpy")).toBe(2800);
+ expect(fromMinor(2950, "brl")).toBe(29.5);
+ expect(fromMinor(26000, "krw")).toBe(26000);
+});
diff --git a/site/src/lib/billing/currencies.ts b/site/src/lib/billing/currencies.ts
new file mode 100644
index 00000000..2ddf273a
--- /dev/null
+++ b/site/src/lib/billing/currencies.ts
@@ -0,0 +1,58 @@
+// The currencies the plans sell in. USD is every plan's Stripe default; each
+// other currency is a hand-set amount on the same Stripe price (its
+// currency_options), so a subscription keeps its currency through every move
+// between plans. A visitor's country picks the currency, and a country with
+// none of its own pays in USD. Client-safe: no server imports.
+
+export const CURRENCIES = ["usd", "eur", "gbp", "cad", "aud", "jpy", "krw", "brl", "mxn"] as const;
+export type Currency = (typeof CURRENCIES)[number];
+
+// The currencies a plan's terms set by hand; USD is its monthlyDollars.
+export type LocalCurrency = Exclude<Currency, "usd">;
+export const LOCAL_CURRENCIES = CURRENCIES.filter((c): c is LocalCurrency => c !== "usd");
+
+export const DEFAULT_CURRENCY: Currency = "usd";
+
+// Digits after the decimal point in Stripe's minor unit: ¥2,800 is 2800.
+const ZERO_DECIMAL: ReadonlySet<Currency> = new Set(["jpy", "krw"]);
+const CENT_DIGITS = 2;
+
+// Countries that pay in a currency of their own. The euro covers the
+// eurozone, the territories and microstates that use it.
+const EURO_COUNTRIES = [
+ "AT", "BE", "BG", "CY", "DE", "EE", "ES", "FI", "FR", "GR", "HR", "IE", "IT", "LT", "LU", "LV", "MT", "NL", "PT",
+ "SI", "SK", "AD", "AX", "BL", "GF", "GP", "ME", "MC", "MF", "MQ", "PM", "RE", "SM", "VA", "XK", "YT",
+];
+const MARKET_BY_COUNTRY: ReadonlyMap<string, Currency> = new Map([
+ ...EURO_COUNTRIES.map((country) => [country, "eur"] as const),
+ ["GB", "gbp"],
+ ["CA", "cad"],
+ ["AU", "aud"],
+ ["JP", "jpy"],
+ ["KR", "krw"],
+ ["BR", "brl"],
+ ["MX", "mxn"],
+]);
+
+export function isCurrency(value: unknown): value is Currency {
+ return typeof value === "string" && (CURRENCIES as readonly string[]).includes(value);
+}
+
+/** The currency a country's visitors see and pay in. */
+export function marketCurrency(country: string | null): Currency {
+ return (country && MARKET_BY_COUNTRY.get(country)) || DEFAULT_CURRENCY;
+}
+
+function minorDigits(currency: Currency): number {
+ return ZERO_DECIMAL.has(currency) ? 0 : CENT_DIGITS;
+}
+
+/** An amount in Stripe's minor unit: 59 BRL → 5900, 2800 JPY → 2800. */
+export function toMinor(amount: number, currency: Currency): number {
+ return Math.round(amount * 10 ** minorDigits(currency));
+}
+
+/** A Stripe minor-unit amount as the currency reads it: 5900 BRL → 59. */
+export function fromMinor(minor: number, currency: Currency): number {
+ return minor / 10 ** minorDigits(currency);
+}
diff --git a/site/src/lib/billing/format-price.test.ts b/site/src/lib/billing/format-price.test.ts
new file mode 100644
index 00000000..08e5d8e6
--- /dev/null
+++ b/site/src/lib/billing/format-price.test.ts
@@ -0,0 +1,16 @@
+import { expect, test } from "bun:test";
+
+import { formatMinorPrice, formatPrice } from "./format-price";
+
+test("whole prices carry no decimals in any currency", () => {
+ expect(formatPrice(20, "usd", "en")).toBe("$20");
+ expect(formatPrice(59, "brl", "pt-BR")).toBe("R$\u00a059");
+ expect(formatPrice(2800, "jpy", "en")).toBe("¥2,800");
+ expect(formatPrice(19, "eur", "de")).toBe("19\u00a0€");
+});
+
+test("a minor-unit price reads in its currency", () => {
+ expect(formatMinorPrice(2950, "brl", "en")).toBe("R$29.50");
+ expect(formatMinorPrice(1400, "jpy", "en")).toBe("¥1,400");
+ expect(formatMinorPrice(1000, "usd", "en")).toBe("$10");
+});
diff --git a/site/src/lib/billing/format-price.ts b/site/src/lib/billing/format-price.ts
new file mode 100644
index 00000000..6cff9fb1
--- /dev/null
+++ b/site/src/lib/billing/format-price.ts
@@ -0,0 +1,19 @@
+import type { Locale } from "@/i18n/locales";
+import { fromMinor, type Currency } from "@/lib/billing/currencies";
+
+// A plan price in a sentence, in its own currency and the reader's way of
+// writing it: whole amounts carry no decimals ("R$59", "¥2,800", "19 €"),
+// anything else the currency's own ("R$29.50").
+export function formatPrice(amount: number, currency: Currency, locale: Locale): string {
+ const whole = Number.isInteger(amount);
+ return amount.toLocaleString(locale, {
+ currency: currency.toUpperCase(),
+ style: "currency",
+ ...(whole ? { maximumFractionDigits: 0, minimumFractionDigits: 0 } : {}),
+ });
+}
+
+/** A Stripe minor-unit amount as a price reads: 2950 BRL → "R$29.50". */
+export function formatMinorPrice(minor: number, currency: Currency, locale: Locale): string {
+ return formatPrice(fromMinor(minor, currency), currency, locale);
+}
diff --git a/site/src/lib/billing/intro-offer-server.ts b/site/src/lib/billing/intro-offer-server.ts
index 6a0bf6b8..cd87c598 100644
--- a/site/src/lib/billing/intro-offer-server.ts
+++ b/site/src/lib/billing/intro-offer-server.ts
@@ -1,6 +1,5 @@
import Stripe from "stripe";
-import { planPriceId } from "@/lib/billing/pro-subscription";
import { getStripe } from "@/lib/billing/stripe";
import { getSetting, type ConfigContext } from "@/lib/config/effective";
import { prisma } from "@/lib/prisma";
@@ -92,33 +91,3 @@ export async function introCoupon(offer: IntroOffer): Promise<string> {
}
return id;
}
-
-// A price's amount never changes under its id, so one read per process
-// serves every offer; moving Pro to a new price reads that one fresh.
-const priceCents = new Map<string, Promise<number>>();
-
-/** The Pro price in cents, as Stripe holds it. */
-export async function readProPriceCents(): Promise<number> {
- const priceId = await planPriceId("pro");
- if (!priceId) {
- throw new Error("The Pro plan has no price in the planPrices setting");
- }
-
- let cents = priceCents.get(priceId);
- if (!cents) {
- cents = getStripe()
- .prices.retrieve(priceId)
- .then((price) => {
- if (typeof price.unit_amount !== "number") {
- throw new Error(`Pro price ${priceId} has no unit amount`);
- }
- return price.unit_amount;
- })
- .catch((e: unknown) => {
- priceCents.delete(priceId);
- throw e;
- });
- priceCents.set(priceId, cents);
- }
- return cents;
-}
diff --git a/site/src/lib/billing/intro-offer.test.ts b/site/src/lib/billing/intro-offer.test.ts
index cd71e8aa..c32dc6f5 100644
--- a/site/src/lib/billing/intro-offer.test.ts
+++ b/site/src/lib/billing/intro-offer.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test";
-import { heldPro, introCouponId, introOfferAt, introOfferPreview, introPriceCents, offersIntro } from "./intro-offer";
+import { heldPro, introCouponId, introOfferAt, introOfferPreview, introPriceMinor, offersIntro } from "./intro-offer";
const HOUR_MS = 3_600_000;
const seen = new Date("2026-10-16T12:00:00Z");
@@ -51,8 +51,8 @@ test("one coupon per pair of terms", () => {
});
test("the intro price rounds to the cent", () => {
- expect(introPriceCents(2000, 50)).toBe(1000);
- expect(introPriceCents(1999, 33)).toBe(1339);
+ expect(introPriceMinor(2000, 50)).toBe(1000);
+ expect(introPriceMinor(1999, 33)).toBe(1339);
});
describe("introOfferPreview", () => {
diff --git a/site/src/lib/billing/intro-offer.ts b/site/src/lib/billing/intro-offer.ts
index 562beb7a..af5aac55 100644
--- a/site/src/lib/billing/intro-offer.ts
+++ b/site/src/lib/billing/intro-offer.ts
@@ -75,7 +75,8 @@ export function introCouponId(offer: Pick<IntroOffer, "percentOff" | "months">):
return `donkey-intro-${offer.percentOff}-${offer.months}m`;
}
-/** The discounted price, in cents, rounded the way Stripe rounds it. */
-export function introPriceCents(priceCents: number, percentOff: number): number {
- return Math.round((priceCents * (100 - percentOff)) / 100);
+/** The discounted price in the currency's minor unit, rounded the way
+ * Stripe rounds it: 2000 cents → 1000, ¥2,800 → ¥1,400. */
+export function introPriceMinor(priceMinor: number, percentOff: number): number {
+ return Math.round((priceMinor * (100 - percentOff)) / 100);
}
diff --git a/site/src/lib/billing/plans.ts b/site/src/lib/billing/plans.ts
index 5fad65cc..e2edd56d 100644
--- a/site/src/lib/billing/plans.ts
+++ b/site/src/lib/billing/plans.ts
@@ -4,6 +4,8 @@
// can't say two things in two parts of the product. Client-safe: no server
// imports.
+import type { Currency, LocalCurrency } from "@/lib/billing/currencies";
+
// Cheapest first; a plan's place in this list is its rank.
export const PAID_PLANS = ["plus", "pro", "max"] as const;
export type PaidPlan = (typeof PAID_PLANS)[number];
@@ -17,6 +19,9 @@ export const PLAN_NAMES: Record<PaidPlan, string> = { plus: "Plus", pro: "Pro",
export type PlanTerms = {
// The monthly price in USD; su checks it against the plan's Stripe price.
monthlyDollars: number;
+ // The monthly price in each other currency, in whole units (59 is R$59).
+ // su adds them to the plan's Stripe price.
+ localPrices: Record<LocalCurrency, number>;
// The AI credits each billing period starts with.
monthlyCredits: number;
storageGb: number;
@@ -39,3 +44,8 @@ export function isPaidPlan(value: unknown): value is PaidPlan {
export function planRank(plan: PaidPlan | null): number {
return plan === null ? 0 : PAID_PLANS.indexOf(plan) + 1;
}
+
+/** What a plan costs a month in a currency, in whole units of it. */
+export function planPrice(terms: PlanTerms, currency: Currency): number {
+ return currency === "usd" ? terms.monthlyDollars : terms.localPrices[currency];
+}
diff --git a/site/src/lib/config/registry.test.ts b/site/src/lib/config/registry.test.ts
index 80b45157..aa9fd175 100644
--- a/site/src/lib/config/registry.test.ts
+++ b/site/src/lib/config/registry.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, test } from "bun:test";
+import type { PlanTerms } from "@/lib/billing/plans";
+
import { PUBLIC_SETTING_KEYS, SETTINGS, SETTING_KEYS, defaultSettings } from "./registry";
import { publicSubset, resolveSettings } from "./resolve";
@@ -20,6 +22,14 @@ describe("the product's settings registry", () => {
expect(resolved.invalid).toEqual([{ key: "databasePool", layer: "override" }]);
});
+ test("plan terms saved before local prices read the default ones", () => {
+ const { plus, pro, max } = SETTINGS.planTerms.default;
+ const strip = ({ localPrices: _, ...rest }: PlanTerms) => rest;
+ const resolved = resolveSettings({ planTerms: { plus: strip(plus), pro: strip(pro), max: strip(max) } }, []);
+ expect(resolved.invalid).toEqual([]);
+ expect(resolved.settings.planTerms.pro.localPrices).toEqual(pro.localPrices);
+ });
+
test("the signup grant is set to the cent", () => {
// Cents are the smallest step su can set: 0.5 is 500 credits, and a stored
// whole-dollar override keeps parsing.
diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.ts
index 1c7834e6..feaed1ef 100644
--- a/site/src/lib/config/registry.ts
+++ b/site/src/lib/config/registry.ts
@@ -9,12 +9,39 @@ import {
} from "@donkeycut/abexp";
import { z } from "zod";
+import type { LocalCurrency } from "@/lib/billing/currencies";
+import type { PaidPlan } from "@/lib/billing/plans";
import { maxCreditGrantDollars, maxCreditGrantExpiryDays } from "@/lib/credits/top-up";
+// A plan's monthly price in each currency besides USD, in whole units.
+const localAmount = z.number().int().min(1).max(10_000_000);
+const localPricesSchema = z
+ .object({
+ eur: localAmount,
+ gbp: localAmount,
+ cad: localAmount,
+ aud: localAmount,
+ jpy: localAmount,
+ krw: localAmount,
+ brl: localAmount,
+ mxn: localAmount,
+ } satisfies Record<LocalCurrency, typeof localAmount>)
+ .strict();
+
+// Each plan's local prices, set for what the plan is worth where it sells:
+// rounded, and lower where money buys more.
+const LOCAL_PRICES: Record<PaidPlan, z.infer<typeof localPricesSchema>> = {
+ plus: { eur: 5, gbp: 4, cad: 7, aud: 8, jpy: 700, krw: 6_900, brl: 15, mxn: 59 },
+ pro: { eur: 19, gbp: 16, cad: 27, aud: 30, jpy: 2_800, krw: 26_000, brl: 59, mxn: 229 },
+ max: { eur: 45, gbp: 39, cad: 65, aud: 75, jpy: 6_800, krw: 63_000, brl: 149, mxn: 549 },
+};
+
// One paid plan's terms in the planTerms setting (src/lib/billing/plans.ts).
-const planTermsSchema = z
+// Terms saved before a plan had local prices read them from the table above.
+const planTermsSchema = (plan: PaidPlan) => z
.object({
monthlyDollars: z.number().multipleOf(0.01).min(0.5).max(10_000),
+ localPrices: localPricesSchema.default(LOCAL_PRICES[plan]),
monthlyCredits: z.number().int().min(0).max(10_000_000),
storageGb: z.number().int().min(1).max(100_000),
rendersPerDay: z.number().int().min(1).max(100_000),
@@ -231,16 +258,16 @@ export const SETTINGS = defineSettings({
"How many projects a free account may hold besides its starter project. Creating one more opens the upgrade dialog.",
},
planTerms: {
- schema: z.object({ plus: planTermsSchema, pro: planTermsSchema, max: planTermsSchema }).strict(),
+ schema: z.object({ plus: planTermsSchema("plus"), pro: planTermsSchema("pro"), max: planTermsSchema("max") }).strict(),
default: {
- plus: { monthlyDollars: 5, monthlyCredits: 5_000, storageGb: 10, rendersPerDay: 10, unlimitedProjects: false },
- pro: { monthlyDollars: 20, monthlyCredits: 20_000, storageGb: 100, rendersPerDay: 200, unlimitedProjects: true },
- max: { monthlyDollars: 49, monthlyCredits: 60_000, storageGb: 500, rendersPerDay: 500, unlimitedProjects: true },
+ plus: { monthlyDollars: 5, localPrices: LOCAL_PRICES.plus, monthlyCredits: 5_000, storageGb: 10, rendersPerDay: 10, unlimitedProjects: false },
+ pro: { monthlyDollars: 20, localPrices: LOCAL_PRICES.pro, monthlyCredits: 20_000, storageGb: 100, rendersPerDay: 200, unlimitedProjects: true },
+ max: { monthlyDollars: 49, localPrices: LOCAL_PRICES.max, monthlyCredits: 60_000, storageGb: 500, rendersPerDay: 500, unlimitedProjects: true },
},
public: true,
title: "Plan terms",
description:
- "What each paid plan sells: its monthly USD price, which has to match its Stripe price, the AI credits each period starts with, cloud storage, renders a day, and whether the free project limit is lifted. Credits cost about 0.77 of their face value when spent in full.",
+ "What each paid plan sells: its monthly USD price, which has to match its Stripe price, its price in each other currency, which a save adds to the Stripe price and which Stripe never changes once set (a new amount takes a new Stripe price), the AI credits each period starts with, cloud storage, renders a day, and whether the free project limit is lifted. Credits cost about 0.77 of their face value when spent in full.",
},
planPrices: {
schema: z
diff --git a/site/src/proxy.test.ts b/site/src/proxy.test.ts
index 86b2bc69..c6b73274 100644
--- a/site/src/proxy.test.ts
+++ b/site/src/proxy.test.ts
@@ -56,11 +56,26 @@ test("a picked language wins over the browser's", async () => {
test("a regional or unsupported language resolves to a shipped one", async () => {
const portuguese = await proxy(request("https://donkeycut.com/", "", "pt-PT,pt;q=0.9"));
- expect(portuguese.headers.get("x-middleware-rewrite")).toBe("https://donkeycut.com/pt-BR/cut");
+ expect(portuguese.headers.get("x-middleware-rewrite")).toBe("https://donkeycut.com/pt-BR/cut/usd");
const chinese = await proxy(request("https://donkeycut.com/", "", "zh"));
- expect(chinese.headers.get("x-middleware-rewrite")).toBe("https://donkeycut.com/zh-CN/cut");
+ expect(chinese.headers.get("x-middleware-rewrite")).toBe("https://donkeycut.com/zh-CN/cut/usd");
const dutch = await proxy(request("https://donkeycut.com/", "", "nl-NL"));
- expect(dutch.headers.get("x-middleware-rewrite")).toBe("https://donkeycut.com/en/cut");
+ expect(dutch.headers.get("x-middleware-rewrite")).toBe("https://donkeycut.com/en/cut/usd");
+});
+
+test("the landing prices in the visitor's country's currency", async () => {
+ const brazil = request("https://donkeycut.com/", "", "pt-BR");
+ brazil.headers.set("x-vercel-ip-country", "BR");
+ expect((await proxy(brazil)).headers.get("x-middleware-rewrite")).toBe("https://donkeycut.com/pt-BR/cut/brl");
+ const poland = request("https://donkeycut.com/");
+ poland.headers.set("x-vercel-ip-country", "PL");
+ expect((await proxy(poland)).headers.get("x-middleware-rewrite")).toBe("https://donkeycut.com/en/cut/usd");
+});
+
+test("a currency segment typed into the address goes back to the landing", async () => {
+ const res = await proxy(request("https://donkeycut.com/eur"));
+ expect(res.status).toBe(308);
+ expect(res.headers.get("location")).toBe("https://donkeycut.com/");
});
test("a crawler with no language gets English", async () => {
diff --git a/site/src/proxy.ts b/site/src/proxy.ts
index aef1f40c..69301e6e 100644
--- a/site/src/proxy.ts
+++ b/site/src/proxy.ts
@@ -3,6 +3,8 @@ import { NextResponse, type NextRequest } from "next/server";
import { allowedOrigin, corsHeaders, preflightHeaders } from "@/cut/server/cors";
import { DONKEYCUT_CANONICAL, isDonkeycutHost } from "@/cut/lib/hosts";
import { requestLocale } from "@/i18n/requestLocale";
+import { isCurrency, marketCurrency } from "@/lib/billing/currencies";
+import { countryFromHeaders } from "@/lib/config/country";
import { BEACON_PATH, META_COOKIE_MAX_AGE_S, metaCookies } from "@/lib/meta/identity";
// Cut (the video editor, publicly "Donkey Cut") lives under /cut in this single
@@ -128,7 +130,17 @@ export function proxy(req: NextRequest) {
return withMetaCookies(req, NextResponse.next());
}
if (passesThrough(pathname)) return localized(req, pathname);
- return localized(req, `/cut${pathname === "/" ? "" : pathname}`);
+
+ // The landing is prerendered once per currency, and "/" serves the one for
+ // the visitor's country. The currency segment never shows in a URL, so a
+ // visit to one ("/eur") goes back to "/".
+ if (pathname === "/") {
+ return localized(req, `/cut/${marketCurrency(countryFromHeaders(req.headers))}`);
+ }
+ if (isCurrency(pathname.slice(1))) {
+ return NextResponse.redirect(new URL("/", req.url), 308);
+ }
+ return localized(req, `/cut${pathname}`);
}
export const config = {
diff --git a/site/src/queries/billing.ts b/site/src/queries/billing.ts
index ba999874..c2bd1d69 100644
--- a/site/src/queries/billing.ts
+++ b/site/src/queries/billing.ts
@@ -3,11 +3,11 @@
import { useMutation, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
+import { DEFAULT_CURRENCY, type Currency } from "@/lib/billing/currencies";
import type { PaidPlan } from "@/lib/billing/plans";
import { apiFetch } from "@/queries/apiClient";
export const proSubscriptionQueryKey = ["billing", "pro"] as const;
-export const introOfferQueryKey = ["billing", "intro-offer"] as const;
export type ProSubscription = {
isActive: boolean;
@@ -41,45 +41,64 @@ export type IntroOffer = {
months: number;
// When the offer closes.
endsAt: string;
- // The Pro price and what the discounted months cost.
- priceCents: number;
- introCents: number;
+ // The Pro price and what the discounted months cost, in the currency's
+ // minor unit.
+ currency: Currency;
+ priceMinor: number;
+ introMinor: number;
};
// The offer as the app loads it: endsAt is null while the window has not
// started, and it runs windowHours from the moment a surface first shows it.
type IntroOfferRead = Omit<IntroOffer, "endsAt"> & { endsAt: string | null; windowHours: number };
+// What the account pays in and the intro offer open to it, read together as
+// the app starts.
+type PricingRead = { currency: Currency; intro: IntroOfferRead | null };
+
+const pricingQueryKey = ["billing", "pricing"] as const;
+const PRICING_URL = "/api/billing/pricing";
const INTRO_OFFER_URL = "/api/billing/intro-offer";
-const INTRO_STALE_MS = 5 * 60_000;
+const PRICING_STALE_MS = 5 * 60_000;
const HOUR_MS = 3_600_000;
-const fetchIntroOffer = async () => (await apiFetch<{ offer: IntroOfferRead | null }>(INTRO_OFFER_URL)).offer;
+const fetchPricing = () => apiFetch<PricingRead>(PRICING_URL);
+
+/** Load the account's pricing as the app starts, ahead of every surface
+ * that sells a plan, so each paints in its currency and with the offer on
+ * its first frame. Reading starts nothing. */
+export function prefetchPricing(client: QueryClient): Promise<void> {
+ return client.prefetchQuery({ queryFn: fetchPricing, queryKey: pricingQueryKey, staleTime: PRICING_STALE_MS });
+}
-/** Load the offer as the app starts, ahead of every surface that shows it,
- * so a card selling Pro paints with it on its first frame. Reading starts
- * nothing. */
-export function prefetchIntroOffer(client: QueryClient): Promise<void> {
- return client.prefetchQuery({ queryFn: fetchIntroOffer, queryKey: introOfferQueryKey, staleTime: INTRO_STALE_MS });
+function usePricing({ enabled = true }: { enabled?: boolean } = {}) {
+ return useQuery({ enabled, queryFn: fetchPricing, queryKey: pricingQueryKey, staleTime: PRICING_STALE_MS });
+}
+
+/** The currency the account's plans price and check out in. */
+export function useAccountCurrency({ enabled }: { enabled: boolean }): { currency: Currency; isPending: boolean } {
+ const read = usePricing({ enabled });
+ return { currency: read.data?.currency ?? DEFAULT_CURRENCY, isPending: read.isPending };
}
// The discount an account inside its intro window gets on Pro. Checkout
// applies it on its own; this read is for the surfaces that show it, and the
-// first one to show it starts the window.
+// first one to show it starts the window. A surface that shows no offer, such
+// as one for an account already on a plan, passes enabled: false.
export function useIntroOffer({ enabled = true }: { enabled?: boolean } = {}): {
data: IntroOffer | null | undefined;
isPending: boolean;
} {
const queryClient = useQueryClient();
- const read = useQuery({ enabled, queryFn: fetchIntroOffer, queryKey: introOfferQueryKey, staleTime: INTRO_STALE_MS });
- const offer = read.data;
+ const read = usePricing();
+ const offer = enabled ? read.data?.intro : undefined;
// A window this surface is the first to show runs from its mount, the
// moment the start below lands on the server too; the countdown keeps that
// anchor, so it never jumps when the server's answer arrives.
const [mountedAt] = useState(() => Date.now());
const [startedHere, setStartedHere] = useState(false);
- const unstarted = enabled && offer !== undefined && offer !== null && offer.endsAt === null;
+ const unstarted = offer !== undefined && offer !== null && offer.endsAt === null;
if (unstarted && !startedHere) {
setStartedHere(true);
}
@@ -88,12 +107,15 @@ export function useIntroOffer({ enabled = true }: { enabled?: boolean } = {}): {
return;
}
void apiFetch<{ endsAt: string | null }>(INTRO_OFFER_URL, { method: "POST" }).then(({ endsAt }) => {
- queryClient.setQueryData<IntroOfferRead | null>(introOfferQueryKey, (prev) =>
- prev && endsAt ? { ...prev, endsAt } : null,
+ queryClient.setQueryData<PricingRead>(pricingQueryKey, (prev) =>
+ prev?.intro ? { ...prev, intro: endsAt ? { ...prev.intro, endsAt } : null } : prev,
);
});
}, [unstarted, queryClient]);
+ if (!enabled) {
+ return { data: undefined, isPending: true };
+ }
if (!offer) {
return { data: offer, isPending: read.isPending };
}
@@ -110,13 +132,19 @@ export function useIntroOffer({ enabled = true }: { enabled?: boolean } = {}): {
// claim link passes the offer's token, so the credit that lands is the one the
// dialog described. An account already on a plan moves up in place and comes
// back with the settings URL.
+// Every checkout names the currency its surface showed. The route refuses
+// one the account no longer checks out in, so a charge never differs from
+// the card.
export function useStartCheckout() {
+ const queryClient = useQueryClient();
+ const { currency } = useAccountCurrency({ enabled: true });
return useMutation({
mutationFn: (input?: { plan?: PaidPlan; offerToken?: string } | void) =>
apiFetch<{ url: string }>("/api/billing/checkout", {
method: "POST",
- ...(input ? { body: JSON.stringify(input) } : {}),
+ body: JSON.stringify({ ...input, currency }),
}),
+ onError: () => queryClient.invalidateQueries({ queryKey: pricingQueryKey }),
});
}