Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Show the pay wall in the buyer's currency and pass it to checkout (#3204)
Luke Velladd4833d3fd89
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 6434068a7..1925b5dfe 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -195,6 +195,7 @@"createSpace": "Create space","createSpaceDescription": "Create a new space to organize your polls and events.","cropPreview": "Crop preview",+ "currency": "Currency","currentlyUsing": "Currently using {usedSeats} of {currentSeats} seats","currentPassword": "Current password","currentPlan": "Current plan",diff --git a/apps/web/src/app/[locale]/(optional-space)/layout.tsx b/apps/web/src/app/[locale]/(optional-space)/layout.tsxindex 2d6640da4..76152cced 100644--- a/apps/web/src/app/[locale]/(optional-space)/layout.tsx+++ b/apps/web/src/app/[locale]/(optional-space)/layout.tsx@@ -3,6 +3,7 @@ import { RouterLoadingIndicator } from "@/components/router-loading-indicator";import { SessionRefresher } from "@/components/session-refresher";import { TierProvider } from "@/features/billing/client";import { PayWall } from "@/features/billing/components/pay-wall";+import { loadPayWallPricing } from "@/features/billing/loaders";import { resolveSpaceTier } from "@/features/billing/utils";import { isQuickCreateEnabled } from "@/features/quick-create/constants";import { getActiveSpaceForUser } from "@/features/space/data";@@ -21,11 +22,13 @@ async function OptionalSpaceGate({ children }: { children: React.ReactNode }) {await requireUser();}- const [locale, deviceDateTimeConfig, session] = await Promise.all([- getLocale(),- getDeviceDateTimeConfig(),- getSession(),- ]);+ const [locale, deviceDateTimeConfig, session, payWallPricing] =+ await Promise.all([+ getLocale(),+ getDeviceDateTimeConfig(),+ getSession(),+ loadPayWallPricing(),+ ]);const user = session?.user;@@ -50,7 +53,7 @@ async function OptionalSpaceGate({ children }: { children: React.ReactNode }) {><TierProvider tier={tier}>{children}- <PayWall />+ <PayWall pricing={payWallPricing} /></TierProvider></DeviceDateTimeProvider></UserProvider>diff --git a/apps/web/src/app/[locale]/(space)/layout.tsx b/apps/web/src/app/[locale]/(space)/layout.tsxindex 5cfb902dd..4dde25368 100644--- a/apps/web/src/app/[locale]/(space)/layout.tsx+++ b/apps/web/src/app/[locale]/(space)/layout.tsx@@ -3,6 +3,7 @@ import { RouterLoadingIndicator } from "@/components/router-loading-indicator";import { SessionRefresher } from "@/components/session-refresher";import { TierProvider } from "@/features/billing/client";import { PayWall } from "@/features/billing/components/pay-wall";+import { loadPayWallPricing } from "@/features/billing/loaders";import { SpaceProvider } from "@/features/space/client";import { getActiveSpace } from "@/features/space/loaders";import { UserProvider } from "@/features/user/client";@@ -15,10 +16,11 @@ import { DateTimeProvider } from "@/lib/datetime/client";// flush before the session store responds; without it, every hard load of// a space route streams nothing until getActiveSpace resolves.async function SpaceGate({ children }: { children: React.ReactNode }) {- const [locale, session, space] = await Promise.all([+ const [locale, session, space, payWallPricing] = await Promise.all([getLocale(),getSession(),getActiveSpace(),+ loadPayWallPricing(),]);const user = session?.user;@@ -37,7 +39,7 @@ async function SpaceGate({ children }: { children: React.ReactNode }) {<TierProvider tier={space.tier}><SpaceProvider space={space}>{children}- <PayWall />+ <PayWall pricing={payWallPricing} /></SpaceProvider></TierProvider></DateTimeProvider>diff --git a/apps/web/src/features/billing/actions.ts b/apps/web/src/features/billing/actions.tsindex f50e2af85..c8f716a9d 100644--- a/apps/web/src/features/billing/actions.ts+++ b/apps/web/src/features/billing/actions.ts@@ -1,6 +1,6 @@"use server";-import { getProPricing } from "@rallly/billing";+import { displayedCurrencies, getProPricing } from "@rallly/billing";import { absoluteUrl } from "@rallly/utils/absolute-url";import { redirect } from "next/navigation";import * as z from "zod";@@ -29,6 +29,7 @@ export const upgradeToProAction = authActionClient.inputSchema(z.object({period: z.enum(["monthly", "yearly"]).optional(),+ currency: z.enum(displayedCurrencies).optional(),returnPath: returnPathSchema.optional(),}),)@@ -73,7 +74,7 @@ export const upgradeToProAction = authActionClient);}- const { period, returnPath } = parsedInput;+ const { period, currency, returnPath } = parsedInput;const stripe = getStripe();@@ -109,6 +110,14 @@ export const upgradeToProAction = authActionClientaddress: "auto",},mode: "subscription",+ // The currency the user saw on the pay wall; without it Stripe picks+ // one from the IP and the two can disagree. A currency the price no+ // longer carries (stale pay wall cache) is dropped rather than failing+ // the session, so Stripe localizes as it would without the hint.+ currency:+ currency && currency in proPricingData.currencies+ ? currency+ : undefined,allow_promotion_codes: true,billing_address_collection: "auto",tax_id_collection: {@@ -156,6 +165,7 @@ export const upgradeToProAction = authActionClientevent: "billing:checkout_start",properties: {interval: period === "yearly" ? "year" : "month",+ currency,},groups: {space: space.id,diff --git a/apps/web/src/features/billing/client.tsx b/apps/web/src/features/billing/client.tsxindex b2f166bd6..fae58e484 100644--- a/apps/web/src/features/billing/client.tsx+++ b/apps/web/src/features/billing/client.tsx@@ -1,5 +1,6 @@"use client";+import type { PricesByCurrency } from "@rallly/billing";import { posthog } from "@rallly/posthog/client";import React from "react";import { create } from "zustand";@@ -71,3 +72,8 @@ export const usePayWallStore = create<PayWallStore>((set) => ({export const showPayWall = (trigger: PayWallTrigger) =>usePayWallStore.getState().show(trigger);++export type PayWallPricing = {+ prices: PricesByCurrency;+ defaultCurrency: string;+};diff --git a/apps/web/src/features/billing/components/pay-wall-dialog.tsx b/apps/web/src/features/billing/components/pay-wall-dialog.tsxindex 77d481401..912bab14a 100644--- a/apps/web/src/features/billing/components/pay-wall-dialog.tsx+++ b/apps/web/src/features/billing/components/pay-wall-dialog.tsx@@ -1,6 +1,6 @@"use client";-import { pricingData } from "@rallly/billing/pricing";+import { isDisplayedCurrency, pricingData } from "@rallly/billing/pricing";import { posthog } from "@rallly/posthog/client";import { Button } from "@rallly/ui/button";import {@@ -12,10 +12,17 @@ import {} from "@rallly/ui/dialog";import { Label } from "@rallly/ui/label";import { RadioGroup, RadioGroupItem } from "@rallly/ui/radio-group";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@rallly/ui/select";import { Switch } from "@rallly/ui/switch";import { Tabs, TabsContent } from "@rallly/ui/tabs";import {- BadgeDollarSignIcon,+ BadgePercentIcon,CalendarCheckIcon,CalendarSearchIcon,ClockIcon,@@ -31,8 +38,9 @@ import { PageIcon } from "@/components/page-icons";import { UpgradeButton } from "@/features/billing/components/upgrade-button";import type { SpaceTier } from "@/features/space/schema";import { spaceTierSchema } from "@/features/space/schema";-import { Trans } from "@/i18n/client";-import type { PayWallTrigger } from "../client";+import { Trans, useTranslation } from "@/i18n/client";+import { useDateTimeConfig } from "@/lib/datetime/client";+import type { PayWallPricing, PayWallTrigger } from "../client";import { usePayWallStore } from "../client";import { PLAN_NAMES } from "../constants";@@ -185,17 +193,31 @@ function getProBenefits(from: PayWallTrigger["from"] | undefined) {];}-const currencyFormatter = new Intl.NumberFormat("en-US", {- style: "currency",- currency: "USD",- minimumFractionDigits: 2,- maximumFractionDigits: 2,-});+const fallbackPrices = {+ [pricingData.monthly.currency]: {+ monthly: pricingData.monthly.amount,+ yearly: pricingData.yearly.amount,+ },+};++function currencyLabel(currency: string, locale: string) {+ const code = currency.toUpperCase();+ const symbol = new Intl.NumberFormat(locale, {+ style: "currency",+ currency: code,+ currencyDisplay: "narrowSymbol",+ })+ .formatToParts(0)+ .find((part) => part.type === "currency")?.value;+ return symbol && symbol !== code ? `${symbol} ${code}` : code;+}export function PayWallDialog({+ pricing,isOpen,onOpenChange,}: {+ pricing: PayWallPricing | null;isOpen: boolean;onOpenChange: (open: boolean) => void;}) {@@ -203,20 +225,38 @@ export function PayWallDialog({const [isAnnual, setIsAnnual] = React.useState(true);const trigger = usePayWallStore((state) => state.trigger);const proBenefits = getProBenefits(trigger?.from);+ const { t } = useTranslation();+ const { locale } = useDateTimeConfig();+ const prices = pricing?.prices ?? fallbackPrices;+ const currencies = Object.keys(prices);+ const defaultCurrency = pricing?.defaultCurrency ?? currencies[0];+ const [selectedCurrency, setSelectedCurrency] =+ React.useState(defaultCurrency);+ const currency = prices[selectedCurrency]+ ? selectedCurrency+ : defaultCurrency;+ const amounts = prices[currency];const handleChangePlan = (value: string) => {setSelectedPlan(spaceTierSchema.parse(value));};+ const currencyFormatter = React.useMemo(+ () =>+ new Intl.NumberFormat(locale, {+ style: "currency",+ currency: currency.toUpperCase(),+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ }),+ [locale, currency],+ );+const getProPrice = () => {if (isAnnual) {- const yearlyPrice = pricingData.yearly.amount / 100;- const monthlyEquivalent = yearlyPrice / 12;- return currencyFormatter.format(monthlyEquivalent);- } else {- const monthlyPrice = pricingData.monthly.amount / 100;- return currencyFormatter.format(monthlyPrice);+ return currencyFormatter.format(amounts.yearly / 12 / 100);}+ return currencyFormatter.format(amounts.monthly / 100);};return (@@ -227,6 +267,7 @@ export function PayWallDialog({if (!open) {setSelectedPlan("pro");setIsAnnual(true);+ setSelectedCurrency(defaultCurrency);}}}>@@ -241,13 +282,41 @@ export function PayWallDialog({><div className="flex flex-col p-6"><DialogHeader>- <div className="flex items-center gap-3">- <PageIcon size="sm" color="primary">- <SparklesIcon />- </PageIcon>- <DialogTitle>- <Trans i18nKey="upgradePromptTitle" />- </DialogTitle>+ <div className="flex items-center justify-between gap-3">+ <div className="flex items-center gap-3">+ <PageIcon size="sm" color="primary">+ <SparklesIcon />+ </PageIcon>+ <DialogTitle>+ <Trans i18nKey="upgradePromptTitle" />+ </DialogTitle>+ </div>+ {currencies.length > 1 && (+ <Select+ value={currency}+ onValueChange={(value) => {+ if (value) {+ setSelectedCurrency(value);+ }+ }}+ >+ <SelectTrigger+ className="h-8"+ aria-label={t("currency", { defaultValue: "Currency" })}+ >+ <SelectValue>+ {currencyLabel(currency, locale)}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {currencies.map((code) => (+ <SelectItem key={code} value={code}>+ {currencyLabel(code, locale)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}</div></DialogHeader><div className="mt-6 flex flex-1 flex-col gap-4">@@ -290,7 +359,7 @@ export function PayWallDialog({htmlFor="annual-switch"className="relative flex select-none items-start justify-between gap-4 overflow-hidden rounded-lg bg-gray-50 p-4 ring ring-button-outline ring-inset hover:bg-gray-100 dark:bg-gray-700/50 dark:hover:bg-gray-700">- <BadgeDollarSignIcon className="pointer-events-none absolute -top-5 right-16 size-24 opacity-5" />+ <BadgePercentIcon className="pointer-events-none absolute -top-5 right-16 size-24 opacity-5" /><div className="flex-1"><div className="text-sm">@@ -305,12 +374,10 @@ export function PayWallDialog({i18nKey="yearlyBillingDescription"values={{yearlyPrice: currencyFormatter.format(- pricingData.yearly.amount / 100,+ amounts.yearly / 100,),savings: currencyFormatter.format(- (pricingData.monthly.amount * 12 -- pricingData.yearly.amount) /- 100,+ (amounts.monthly * 12 - amounts.yearly) / 100,),}}/>@@ -328,6 +395,9 @@ export function PayWallDialog({<UpgradeButtonclassName="w-full"annual={isAnnual}+ currency={+ isDisplayedCurrency(currency) ? currency : undefined+ }onClick={() => {posthog?.capture("paywall:upgrade_button_click", {from: trigger?.from,@@ -336,6 +406,7 @@ export function PayWallDialog({poll_id: trigger?.pollId,plan: selectedPlan,interval: isAnnual ? "year" : "month",+ currency,});}}>diff --git a/apps/web/src/features/billing/components/pay-wall.tsx b/apps/web/src/features/billing/components/pay-wall.tsxindex bd4067b21..6706bba3b 100644--- a/apps/web/src/features/billing/components/pay-wall.tsx+++ b/apps/web/src/features/billing/components/pay-wall.tsx@@ -1,5 +1,6 @@"use client";+import type { PayWallPricing } from "../client";import { usePayWallStore } from "../client";import { PayWallDialog } from "./pay-wall-dialog";@@ -7,12 +8,13 @@ import { PayWallDialog } from "./pay-wall-dialog";* Single, app-wide paywall instance.* Open it from anywhere with `showPayWall()`.*/-export function PayWall() {+export function PayWall({ pricing }: { pricing: PayWallPricing | null }) {const isOpen = usePayWallStore((state) => state.isOpen);const hide = usePayWallStore((state) => state.hide);return (<PayWallDialog+ pricing={pricing}isOpen={isOpen}onOpenChange={(open) => {if (!open) {diff --git a/apps/web/src/features/billing/components/upgrade-button.tsx b/apps/web/src/features/billing/components/upgrade-button.tsxindex 2f10e94f4..960ea1786 100644--- a/apps/web/src/features/billing/components/upgrade-button.tsx+++ b/apps/web/src/features/billing/components/upgrade-button.tsx@@ -1,4 +1,5 @@"use client";+import type { DisplayedCurrency } from "@rallly/billing";import { Button } from "@rallly/ui/button";import { usePathname, useRouter } from "next/navigation";import type React from "react";@@ -11,10 +12,12 @@ import { useSafeAction } from "@/lib/safe-action/client";export const UpgradeButton = ({children,annual,+ currency,className,onClick,}: React.PropsWithChildren<{annual?: boolean;+ currency?: DisplayedCurrency;className?: string;onClick?: () => void;}>) => {@@ -38,6 +41,7 @@ export const UpgradeButton = ({}upgradeToPro.execute({period: annual ? "yearly" : "monthly",+ currency,returnPath: pathname,});}}diff --git a/apps/web/src/features/billing/data.ts b/apps/web/src/features/billing/data.tsindex d06436a3d..979ab7d0a 100644--- a/apps/web/src/features/billing/data.ts+++ b/apps/web/src/features/billing/data.ts@@ -1,6 +1,9 @@import "server-only";+import { getProPricing } from "@rallly/billing";import { prisma } from "@rallly/database";+import { unstable_cache } from "next/cache";+import { getStripe } from "@/features/billing/service";import type { SpaceTier } from "@/features/space/schema";export async function getSpaceSubscription(spaceId: string) {@@ -38,3 +41,11 @@ export async function getSpaceSubscription(spaceId: string) {active: subscription.active,};}++// Prices change on the order of years; an hour is a compromise between+// picking up a repricing without a deploy and not calling Stripe per render.+export const getProPrices = unstable_cache(+ async () => (await getProPricing({ stripe: getStripe() })).currencies,+ ["pro-prices"],+ { revalidate: 60 * 60 },+);diff --git a/apps/web/src/features/billing/loaders.ts b/apps/web/src/features/billing/loaders.tsnew file mode 100644index 000000000..cb8b5b55b--- /dev/null+++ b/apps/web/src/features/billing/loaders.ts@@ -0,0 +1,39 @@+import "server-only";++import { getCountryCurrency } from "@rallly/billing";+import { headers } from "next/headers";+import { cache } from "react";+import { isBillingEnabled } from "@/features/billing/constants";+import { getProPrices } from "@/features/billing/data";++/**+ * Prices for the pay wall plus the currency to show first, from the request+ * country Vercel stamps on every request. Null when there is nothing to pay+ * for, and when Stripe is unreachable so the pay wall degrades to the built+ * in prices rather than the layout failing.+ */+export const loadPayWallPricing = cache(async () => {+ if (!isBillingEnabled) {+ return null;+ }+ try {+ const [prices, headersList] = await Promise.all([+ getProPrices(),+ headers(),+ ]);+ const available = Object.keys(prices);+ if (available.length === 0) {+ return null;+ }+ return {+ prices,+ defaultCurrency: getCountryCurrency(+ headersList.get("x-vercel-ip-country") ?? undefined,+ available,+ ),+ };+ } catch (error) {+ console.error("Failed to load pay wall pricing", error);+ return null;+ }+});diff --git a/packages/billing/src/pricing.test.ts b/packages/billing/src/pricing.test.tsindex f862e2abc..bd70fd3cb 100644--- a/packages/billing/src/pricing.test.ts+++ b/packages/billing/src/pricing.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { yearlySavingsPercent } from "./pricing";+import { getCountryCurrency, yearlySavingsPercent } from "./pricing";describe("yearlySavingsPercent", () => {it("rounds the saving of yearly against twelve months to a whole percent", () => {@@ -12,3 +12,29 @@ describe("yearlySavingsPercent", () => {expect(yearlySavingsPercent({ monthly: 100, yearly: 1200 })).toBe(0);});});++describe("getCountryCurrency", () => {+ const available = ["usd", "eur", "gbp"];++ it("maps the United Kingdom to GBP", () => {+ expect(getCountryCurrency("GB", available)).toBe("gbp");+ });++ it("maps euro area and EFTA countries to EUR", () => {+ expect(getCountryCurrency("DE", available)).toBe("eur");+ expect(getCountryCurrency("FR", available)).toBe("eur");+ expect(getCountryCurrency("CH", available)).toBe("eur");+ expect(getCountryCurrency("SE", available)).toBe("eur");+ });++ it("falls back to USD for everywhere else and when the country is unknown", () => {+ expect(getCountryCurrency("US", available)).toBe("usd");+ expect(getCountryCurrency("IN", available)).toBe("usd");+ expect(getCountryCurrency(undefined, available)).toBe("usd");+ });++ it("only returns a currency Stripe actually offers", () => {+ expect(getCountryCurrency("GB", ["usd", "eur"])).toBe("usd");+ expect(getCountryCurrency("US", ["eur", "gbp"])).toBe("eur");+ });+});diff --git a/packages/billing/src/pricing.ts b/packages/billing/src/pricing.tsindex 8e2dab6a5..e3c310752 100644--- a/packages/billing/src/pricing.ts+++ b/packages/billing/src/pricing.ts@@ -20,3 +20,71 @@ export function yearlySavingsPercent({}export const displayedCurrencies = ["usd", "eur", "gbp"] as const;++export type DisplayedCurrency = (typeof displayedCurrencies)[number];++export function isDisplayedCurrency(value: string): value is DisplayedCurrency {+ return (displayedCurrencies as readonly string[]).includes(value);+}++// Euro area plus the EFTA and EU countries that price in euros comfortably.+// Nordic and Swiss buyers get EUR rather than USD since we stopped offering+// their own currencies.+const eurCountries = new Set([+ "AT",+ "BE",+ "BG",+ "CH",+ "CY",+ "CZ",+ "DE",+ "DK",+ "EE",+ "ES",+ "FI",+ "FR",+ "GR",+ "HR",+ "HU",+ "IE",+ "IS",+ "IT",+ "LI",+ "LT",+ "LU",+ "LV",+ "MT",+ "NL",+ "NO",+ "PL",+ "PT",+ "RO",+ "SE",+ "SI",+ "SK",+]);++const gbpCountries = new Set(["GB", "GG", "IM", "JE"]);++/**+ * The currency to show a buyer from `country` (ISO 3166-1 alpha-2), limited+ * to what Stripe offers. Anywhere unmapped, unknown, or without its currency+ * on the price falls back to USD, then to whatever is available.+ */+export function getCountryCurrency(+ country: string | undefined,+ available: string[],+) {+ const code = country?.toUpperCase();+ const preferred = code+ ? gbpCountries.has(code)+ ? "gbp"+ : eurCountries.has(code)+ ? "eur"+ : "usd"+ : "usd";+ if (available.includes(preferred)) {+ return preferred;+ }+ return available.includes("usd") ? "usd" : available[0];+}