Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Add a currency switcher to the pricing page fed by Stripe prices (#3202)
Luke Vella8200e5b39a9d
diff --git a/apps/landing/.env.sample b/apps/landing/.env.sampleindex 2c7f58504..a45a761a1 100644--- a/apps/landing/.env.sample+++ b/apps/landing/.env.sample@@ -6,3 +6,6 @@ NEXT_PUBLIC_BASE_URL=https://landing.rallly.test# A connection string to your Postgres databaseDATABASE_URL=postgres://postgres:postgres@localhost:5450/rallly++# Optional. Lets the pricing page read live prices from Stripe; without it the page shows the built-in USD prices.+STRIPE_SECRET_KEY=diff --git a/apps/landing/public/locales/en/pricing.json b/apps/landing/public/locales/en/pricing.jsonindex d6b3942df..2b83f1bf4 100644--- a/apps/landing/public/locales/en/pricing.json+++ b/apps/landing/public/locales/en/pricing.json@@ -18,6 +18,7 @@"compareSchedulingPolls": "Scheduling polls","compareSchedulingPollsDescription": "Create polls to find the best time to meet","compareUnlimited": "Unlimited",+ "currency": "Currency","customBranding": "Custom branding","customBrandingDescription": "Show your logo and brand colors to your participants","duplicatePolls": "Duplicate polls",@@ -58,5 +59,5 @@"whenPollInactiveAnswer": "Polls become inactive when all date options are in the past AND there has been no activity for over 30 days. Activity includes new votes, comments, or changes to the poll. Inactive polls are automatically deleted if you do not have a paid subscription.","whyUpgrade": "Why should I upgrade?","whyUpgradeAnswer2": "Upgrading to a paid plan makes sense if you use Rallly often or use it for work. The current subscription rate is a special early adopter rate and will increase in the future. By upgrading now, you will get early access to new, high-quality scheduling tools as they are released and lock in your subscription rate so you won't be affected by future price increases.",- "yearlyFreeMonths": "{count, plural, one {# month free} other {# months free}}"+ "yearlySavePercent": "Save {percent}%"}diff --git a/apps/landing/src/app/[locale]/(main)/pricing/billing-interval.tsx b/apps/landing/src/app/[locale]/(main)/pricing/billing-interval.tsxdeleted file mode 100644index c07d0e69a..000000000--- a/apps/landing/src/app/[locale]/(main)/pricing/billing-interval.tsx+++ /dev/null@@ -1,145 +0,0 @@-"use client";--import NumberFlow from "@number-flow/react";-import { cn } from "@rallly/ui";-import { Switch } from "@rallly/ui/switch";-import React from "react";--type BillingInterval = "monthly" | "yearly";--const BillingIntervalContext = React.createContext<{- interval: BillingInterval;- setInterval: (interval: BillingInterval) => void;-} | null>(null);--function useBillingInterval() {- const context = React.useContext(BillingIntervalContext);- if (!context) {- throw new Error(- "useBillingInterval must be used within BillingIntervalProvider",- );- }- return context;-}--export function BillingIntervalProvider({- children,-}: {- children: React.ReactNode;-}) {- const [interval, setInterval] = React.useState<BillingInterval>("yearly");- const value = React.useMemo(() => ({ interval, setInterval }), [interval]);- return (- <BillingIntervalContext.Provider value={value}>- {children}- </BillingIntervalContext.Provider>- );-}--export function BillingIntervalSwitch({- monthlyLabel,- yearlyLabel,- badge,- switchLabel,-}: {- monthlyLabel: React.ReactNode;- yearlyLabel: React.ReactNode;- badge?: React.ReactNode;- switchLabel: string;-}) {- const { interval, setInterval } = useBillingInterval();- const isYearly = interval === "yearly";- return (- <div className="flex flex-col items-center gap-y-4">- {badge ? (- <div className="relative">- {badge}- <svg- aria-hidden="true"- viewBox="0 0 48 32"- className="pointer-events-none absolute top-0 -right-16 h-9 w-16 text-gray-400"- fill="none"- >- <path- d="M2 7c17-6 31 1 30 15"- stroke="currentColor"- strokeWidth="1.5"- strokeLinecap="round"- />- <path- d="M26 18l6 5 4-5"- stroke="currentColor"- strokeWidth="1.5"- strokeLinecap="round"- strokeLinejoin="round"- />- </svg>- </div>- ) : null}- <div className="flex items-center gap-x-3">- <button- type="button"- aria-pressed={!isYearly}- onClick={() => setInterval("monthly")}- className={cn(- "cursor-pointer rounded-sm font-medium text-sm transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2",- isYearly ? "text-gray-500" : "text-gray-800",- )}- >- {monthlyLabel}- </button>- <Switch- aria-label={switchLabel}- checked={isYearly}- onCheckedChange={(checked) =>- setInterval(checked ? "yearly" : "monthly")- }- />- <button- type="button"- aria-pressed={isYearly}- onClick={() => setInterval("yearly")}- className={cn(- "cursor-pointer rounded-sm font-medium text-sm transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2",- isYearly ? "text-gray-800" : "text-gray-500",- )}- >- {yearlyLabel}- </button>- </div>- </div>- );-}--export function BillingIntervalPrice({- monthly,- yearly,-}: {- monthly: number;- yearly: number;-}) {- const { interval } = useBillingInterval();- return (- <NumberFlow- value={interval === "yearly" ? yearly : monthly}- locales="en-US"- format={{- style: "currency",- currency: "USD",- minimumFractionDigits: 2,- maximumFractionDigits: 2,- }}- />- );-}--export function BillingIntervalValue({- monthly,- yearly,-}: {- monthly: React.ReactNode;- yearly: React.ReactNode;-}) {- const { interval } = useBillingInterval();- return interval === "yearly" ? yearly : monthly;-}diff --git a/apps/landing/src/app/[locale]/(main)/pricing/page.tsx b/apps/landing/src/app/[locale]/(main)/pricing/page.tsxindex c8a980e00..ddecb5ca1 100644--- a/apps/landing/src/app/[locale]/(main)/pricing/page.tsx+++ b/apps/landing/src/app/[locale]/(main)/pricing/page.tsx@@ -1,7 +1,8 @@"use cache";-import { PLAN_NAMES, pricingData } from "@rallly/billing";-import { buttonVariants, cn } from "@rallly/ui";+import type { PriceAmounts } from "@rallly/billing";+import { PLAN_NAMES, yearlySavingsPercent } from "@rallly/billing";+import { buttonVariants } from "@rallly/ui";import { Badge } from "@rallly/ui/badge";import {CalendarCheckIcon,@@ -31,7 +32,6 @@ import {import { PeopleBadge, PollsBadge } from "@/components/home/animated-number";import { Cta } from "@/components/home/cta";import { Faq, FaqItem } from "@/components/home/faq";-import { Hero } from "@/components/home/hero";import { Stats } from "@/components/home/stats";import {Section,@@ -40,17 +40,14 @@ import {SectionHeading,SectionTitle,} from "@/components/section";-import { handwritten } from "@/fonts/handwritten";import { getTranslation } from "@/i18n/server";import { getAlternates } from "@/lib/alternates";-import { getMonthlyPollCount, getMonthlyVoterCount } from "@/lib/data";-import { linkToApp } from "@/lib/linkToApp";import {- BillingIntervalPrice,- BillingIntervalProvider,- BillingIntervalSwitch,- BillingIntervalValue,-} from "./billing-interval";+ getMonthlyPollCount,+ getMonthlyVoterCount,+ getPricing,+} from "@/lib/data";+import { linkToApp } from "@/lib/linkToApp";import {PlanBenefit,PlanBenefitName,@@ -64,6 +61,16 @@ import {PlanCardPriceLabel,PlanCards,} from "./plan-card";+import {+ BillingIntervalSwitch,+ BillingIntervalValue,+ CurrencySelect,+ PlanPrice,+ PricingControls,+ PricingControlsDivider,+ PricingProvider,+ YearlySavingsBadge,+} from "./pricing-controls";const faqLinkClassName ="text-gray-800 underline underline-offset-2 hover:text-gray-600";@@ -74,12 +81,25 @@ export default async function Page(props: {cacheLife("hours");const { locale } = await props.params;const { t } = await getTranslation(locale, ["common", "pricing", "home"]);- const [pollCount, voterCount] = await Promise.all([+ const [pollCount, voterCount, prices] = await Promise.all([getMonthlyPollCount(),getMonthlyVoterCount(),+ getPricing(),]);- const freeMonths = Math.round(- 12 - pricingData.yearly.amount / pricingData.monthly.amount,+ const savingsLabels = Object.fromEntries(+ Object.entries(prices).map(+ ([currency, amounts]: [string, PriceAmounts]) => [+ currency,+ <Trans+ key={currency}+ t={t}+ ns="pricing"+ i18nKey="yearlySavePercent"+ defaults="Save {percent}%"+ values={{ percent: yearlySavingsPercent(amounts) }}+ />,+ ],+ ),);const included = t("included", {ns: "pricing",@@ -92,60 +112,65 @@ export default async function Page(props: {return (<div className="divide-y"><Section>- <Hero- centered- title={t("pricingTitle", {- ns: "pricing",- defaultValue: "Pricing",- })}- description={t("pricingSubtitle", {- ns: "pricing",- defaultValue:- "Upgrade to a paid plan to get access to premium features",- })}- />- <BillingIntervalProvider>- <div className="mt-8 flex justify-center sm:mt-12">- <BillingIntervalSwitch- switchLabel={t("payYearly", {- ns: "pricing",- defaultValue: "Pay yearly",- })}- monthlyLabel={- <Trans- t={t}- ns="pricing"- i18nKey="payMonthly"- defaults="Pay monthly"- />- }- yearlyLabel={- <Trans- t={t}- ns="pricing"- i18nKey="payYearly"- defaults="Pay yearly"- />- }- badge={- <span- className={cn(- "whitespace-nowrap text-gray-600 text-sm",- handwritten.className,- )}- >+ <PricingProvider+ prices={prices}+ defaultCurrency={prices.usd ? "usd" : Object.keys(prices)[0]}+ locale={locale}+ >+ <div className="flex flex-col items-center gap-y-8 text-center">+ <div>+ <h1 className="mx-auto max-w-[700px] text-balance font-medium text-3xl text-gray-800 tracking-tight sm:text-[2.75rem]/none">+ {t("pricingTitle", {+ ns: "pricing",+ defaultValue: "Pricing",+ })}+ </h1>+ <p className="mx-auto mt-4 max-w-[620px] text-pretty font-normal text-base/6 text-gray-500 sm:text-lg sm:leading-relaxed">+ {t("pricingSubtitle", {+ ns: "pricing",+ defaultValue:+ "Upgrade to a paid plan to get access to premium features",+ })}+ </p>+ </div>+ <PricingControls>+ <CurrencySelect+ label={t("currency", {+ ns: "pricing",+ defaultValue: "Currency",+ })}+ />+ <PricingControlsDivider />+ <BillingIntervalSwitch+ switchLabel={t("payYearly", {+ ns: "pricing",+ defaultValue: "Pay yearly",+ })}+ monthlyLabel={<Transt={t}ns="pricing"- i18nKey="yearlyFreeMonths"- defaults="{count, plural, one {# month free} other {# months free}}"- values={{ count: freeMonths }}+ i18nKey="payMonthly"+ defaults="Pay monthly"/>- </span>- }- />+ }+ yearlyLabel={+ <Trans+ t={t}+ ns="pricing"+ i18nKey="payYearly"+ defaults="Pay yearly"+ />+ }+ badge={+ <Badge variant="pill">+ <YearlySavingsBadge labels={savingsLabels} />+ </Badge>+ }+ />+ </PricingControls></div>- <PlanCards className="mx-auto mt-4 max-w-6xl sm:mt-6">+ <PlanCards className="mx-auto mt-8 sm:mt-10"><PlanCard><PlanCardHeader><PlanCardName>{PLAN_NAMES.HOBBY}</PlanCardName>@@ -233,10 +258,7 @@ export default async function Page(props: {</PlanCardHeader><PlanCardPrice><PlanCardPriceAmount>- <BillingIntervalPrice- monthly={pricingData.monthly.amount / 100}- yearly={pricingData.yearly.amount / 100 / 12}- />+ <PlanPrice /></PlanCardPriceAmount><PlanCardPriceLabel><BillingIntervalValue@@ -362,8 +384,8 @@ export default async function Page(props: {</PlanBenefits></PlanCard></PlanCards>- </BillingIntervalProvider>- <Stats className="mt-8 sm:mt-24">+ </PricingProvider>+ <Stats className="mt-8 sm:mt-12"><Transt={t}ns="home"diff --git a/apps/landing/src/app/[locale]/(main)/pricing/pricing-controls.tsx b/apps/landing/src/app/[locale]/(main)/pricing/pricing-controls.tsxnew file mode 100644index 000000000..ecf1e77be--- /dev/null+++ b/apps/landing/src/app/[locale]/(main)/pricing/pricing-controls.tsx@@ -0,0 +1,213 @@+"use client";++import NumberFlow from "@number-flow/react";+import type { PricesByCurrency } from "@rallly/billing";+import { cn } from "@rallly/ui";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@rallly/ui/select";+import { Switch } from "@rallly/ui/switch";+import React from "react";++type BillingInterval = "monthly" | "yearly";++const PricingContext = React.createContext<{+ interval: BillingInterval;+ setInterval: (interval: BillingInterval) => void;+ currency: string;+ setCurrency: (currency: string) => void;+ prices: PricesByCurrency;+ locale: string;+} | null>(null);++function usePricing() {+ const context = React.useContext(PricingContext);+ if (!context) {+ throw new Error("usePricing must be used within PricingProvider");+ }+ return context;+}++export function PricingProvider({+ prices,+ defaultCurrency,+ locale,+ children,+}: {+ prices: PricesByCurrency;+ defaultCurrency: string;+ locale: string;+ children: React.ReactNode;+}) {+ const [interval, setInterval] = React.useState<BillingInterval>("yearly");+ const [selectedCurrency, setCurrency] = React.useState(defaultCurrency);+ const currency = prices[selectedCurrency]+ ? selectedCurrency+ : defaultCurrency;+ const value = React.useMemo(+ () => ({ interval, setInterval, currency, setCurrency, prices, locale }),+ [interval, currency, prices, locale],+ );+ return (+ <PricingContext.Provider value={value}>{children}</PricingContext.Provider>+ );+}++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 CurrencySelect({ label }: { label: string }) {+ const { currency, setCurrency, prices, locale } = usePricing();+ const currencies = Object.keys(prices);+ if (currencies.length < 2) {+ return null;+ }+ return (+ <Select+ value={currency}+ onValueChange={(value) => {+ if (value) {+ setCurrency(value);+ }+ }}+ >+ <SelectTrigger+ aria-label={label}+ className="-ml-2 bg-transparent px-2 shadow-none ring-0 hover:bg-gray-200/60"+ >+ <SelectValue>{currencyLabel(currency, locale)}</SelectValue>+ </SelectTrigger>+ <SelectContent>+ {currencies.map((code) => (+ <SelectItem key={code} value={code}>+ {currencyLabel(code, locale)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}++export function BillingIntervalSwitch({+ monthlyLabel,+ yearlyLabel,+ switchLabel,+ badge,+}: {+ monthlyLabel: React.ReactNode;+ yearlyLabel: React.ReactNode;+ switchLabel: string;+ badge?: React.ReactNode;+}) {+ const { interval, setInterval } = usePricing();+ const isYearly = interval === "yearly";+ return (+ <div className="flex items-center gap-x-3">+ <button+ type="button"+ aria-pressed={!isYearly}+ onClick={() => setInterval("monthly")}+ className={cn(+ "cursor-pointer whitespace-nowrap rounded-sm font-medium text-sm transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2",+ isYearly ? "text-gray-500" : "text-gray-800",+ )}+ >+ {monthlyLabel}+ </button>+ <Switch+ aria-label={switchLabel}+ checked={isYearly}+ onCheckedChange={(checked) =>+ setInterval(checked ? "yearly" : "monthly")+ }+ />+ <div className="flex items-center gap-x-2">+ <button+ type="button"+ aria-pressed={isYearly}+ onClick={() => setInterval("yearly")}+ className={cn(+ "cursor-pointer whitespace-nowrap rounded-sm font-medium text-sm transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2",+ isYearly ? "text-gray-800" : "text-gray-500",+ )}+ >+ {yearlyLabel}+ </button>+ {badge}+ </div>+ </div>+ );+}++export function PricingControls({ children }: { children: React.ReactNode }) {+ return (+ <div className="flex flex-wrap items-center justify-center gap-x-4 gap-y-3">+ {children}+ </div>+ );+}++export function PricingControlsDivider() {+ // Hidden when the currency select renders nothing and the divider becomes the first child.+ return (+ <div+ aria-hidden="true"+ className="hidden h-5 w-px bg-gray-200 first:hidden sm:block"+ />+ );+}++export function YearlySavingsBadge({+ labels,+}: {+ labels: Record<string, React.ReactNode>;+}) {+ const { currency } = usePricing();+ return labels[currency] ?? null;+}++export function PlanPrice() {+ const { interval, currency, prices, locale } = usePricing();+ const amounts = prices[currency];+ if (!amounts) {+ return null;+ }+ const value =+ interval === "yearly" ? amounts.yearly / 12 / 100 : amounts.monthly / 100;+ return (+ <NumberFlow+ value={value}+ locales={locale}+ format={{+ style: "currency",+ currency: currency.toUpperCase(),+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ }}+ />+ );+}++export function BillingIntervalValue({+ monthly,+ yearly,+}: {+ monthly: React.ReactNode;+ yearly: React.ReactNode;+}) {+ const { interval } = usePricing();+ return interval === "yearly" ? yearly : monthly;+}diff --git a/apps/landing/src/lib/data.ts b/apps/landing/src/lib/data.tsindex 9f79b8225..0ccbfd503 100644--- a/apps/landing/src/lib/data.ts+++ b/apps/landing/src/lib/data.ts@@ -1,5 +1,10 @@import "server-only";-+import type { PricesByCurrency } from "@rallly/billing";+import {+ createStripeClient,+ getProPricing,+ pricingData,+} from "@rallly/billing";import { prisma } from "@rallly/database";import { cacheLife } from "next/cache";@@ -29,3 +34,36 @@ export const getMonthlyVoterCount = async () => {},});};++const fallbackPricing: PricesByCurrency = {+ [pricingData.monthly.currency]: {+ monthly: pricingData.monthly.amount,+ yearly: pricingData.yearly.amount,+ },+};++const getStripePricing = async (secretKey: string) => {+ "use cache";+ cacheLife("hours");+ const { currencies } = await getProPricing({+ stripe: createStripeClient({ secretKey }),+ });+ if (Object.keys(currencies).length === 0) {+ throw new Error("Stripe prices carry none of the displayed currencies");+ }+ return currencies;+};++// A failed Stripe call is not cached, so the fallback only lasts for that request.+export const getPricing = async (): Promise<PricesByCurrency> => {+ const secretKey = process.env.STRIPE_SECRET_KEY;+ if (!secretKey) {+ return fallbackPricing;+ }+ try {+ return await getStripePricing(secretKey);+ } catch (error) {+ console.error("Failed to load prices from Stripe", error);+ return fallbackPricing;+ }+};diff --git a/packages/billing/package.json b/packages/billing/package.jsonindex c938e73c2..50932e3d4 100644--- a/packages/billing/package.json+++ b/packages/billing/package.json@@ -13,6 +13,7 @@"subscription-data-sync": "dotenv -e .env -- pnpx tsx ./src/scripts/subscription-data-sync.ts","sync-payment-methods": "dotenv -e .env -- pnpx tsx ./src/scripts/sync-payment-methods.ts","sync-space-subscription": "dotenv -e .env -- pnpx tsx ./src/scripts/sync-space-subscription.ts",+ "test:unit": "vitest run","type-check": "tsc --pretty --noEmit"},"dependencies": {@@ -21,6 +22,7 @@"stripe": "^13.2.0"},"devDependencies": {- "@rallly/tsconfig": "workspace:*"+ "@rallly/tsconfig": "workspace:*",+ "vitest": "^4.0.16"}}diff --git a/packages/billing/src/lib/stripe.test.ts b/packages/billing/src/lib/stripe.test.tsnew file mode 100644index 000000000..d676e86f7--- /dev/null+++ b/packages/billing/src/lib/stripe.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from "vitest";+import type { Stripe } from "./stripe";+import { mapProPrices } from "./stripe";++function price(+ lookupKey: string,+ unitAmount: number,+ currencyOptions: Record<string, number> = {},+) {+ return {+ id: `price_${lookupKey}`,+ lookup_key: lookupKey,+ unit_amount: unitAmount,+ currency: "usd",+ currency_options: Object.fromEntries(+ Object.entries(currencyOptions).map(([currency, amount]) => [+ currency,+ { unit_amount: amount },+ ]),+ ),+ } as unknown as Stripe.Price;+}++describe("mapProPrices", () => {+ it("matches prices by lookup key regardless of list order", () => {+ const result = mapProPrices([+ price("pro-yearly", 5600),+ price("pro-monthly", 700),+ ]);+ expect(result.monthly.id).toBe("price_pro-monthly");+ expect(result.yearly.id).toBe("price_pro-yearly");+ });++ it("keeps the base currency amounts on the top level", () => {+ const result = mapProPrices([+ price("pro-monthly", 700),+ price("pro-yearly", 5600),+ ]);+ expect(result.monthly).toEqual({+ id: "price_pro-monthly",+ amount: 700,+ currency: "usd",+ });+ expect(result.yearly.amount).toBe(5600);+ });++ it("builds a per currency map limited to the displayed currencies both prices carry", () => {+ const result = mapProPrices([+ price("pro-monthly", 700, { eur: 650, gbp: 560, chf: 650, inr: 58000 }),+ price("pro-yearly", 5600, {+ eur: 5200,+ gbp: 4500,+ chf: 5600,+ inr: 580000,+ }),+ ]);+ expect(result.currencies).toEqual({+ usd: { monthly: 700, yearly: 5600 },+ eur: { monthly: 650, yearly: 5200 },+ gbp: { monthly: 560, yearly: 4500 },+ });+ });++ it("throws when a price is missing", () => {+ expect(() => mapProPrices([price("pro-monthly", 700)])).toThrow(+ "Price not found",+ );+ });+});diff --git a/packages/billing/src/lib/stripe.ts b/packages/billing/src/lib/stripe.tsindex 34658d1b0..5e17d9c5a 100644--- a/packages/billing/src/lib/stripe.ts+++ b/packages/billing/src/lib/stripe.ts@@ -1,4 +1,5 @@import Stripe from "stripe";+import { displayedCurrencies } from "../pricing";export type { Stripe } from "stripe";@@ -9,17 +10,52 @@ export function createStripeClient({ secretKey }: { secretKey: string }) {});}-export async function getProPricing({ stripe }: { stripe: Stripe }) {- const prices = await stripe.prices.list({- lookup_keys: ["pro-monthly", "pro-yearly"],- });+export type PriceAmounts = {+ monthly: number;+ yearly: number;+};++export type PricesByCurrency = Record<string, PriceAmounts>;++function unitAmountsByCurrency(price: Stripe.Price) {+ const amounts: Record<string, number> = {};+ if (price.unit_amount !== null) {+ amounts[price.currency] = price.unit_amount;+ }+ for (const [currency, option] of Object.entries(+ price.currency_options ?? {},+ )) {+ if (option.unit_amount !== null && option.unit_amount !== undefined) {+ amounts[currency] = option.unit_amount;+ }+ }+ return amounts;+}- const [monthly, yearly] = prices.data;+export function mapProPrices(prices: Stripe.Price[]) {+ const monthly = prices.find((price) => price.lookup_key === "pro-monthly");+ const yearly = prices.find((price) => price.lookup_key === "pro-yearly");- if (monthly.unit_amount === null || yearly.unit_amount === null) {+ if (+ !monthly ||+ !yearly ||+ monthly.unit_amount === null ||+ yearly.unit_amount === null+ ) {throw new Error("Price not found");}+ const monthlyAmounts = unitAmountsByCurrency(monthly);+ const yearlyAmounts = unitAmountsByCurrency(yearly);+ const currencies: PricesByCurrency = {};+ for (const currency of displayedCurrencies) {+ const monthlyAmount = monthlyAmounts[currency];+ const yearlyAmount = yearlyAmounts[currency];+ if (monthlyAmount !== undefined && yearlyAmount !== undefined) {+ currencies[currency] = { monthly: monthlyAmount, yearly: yearlyAmount };+ }+ }+return {monthly: {id: monthly.id,@@ -31,7 +67,17 @@ export async function getProPricing({ stripe }: { stripe: Stripe }) {amount: yearly.unit_amount,currency: yearly.currency,},+ currencies,};}+export async function getProPricing({ stripe }: { stripe: Stripe }) {+ const prices = await stripe.prices.list({+ lookup_keys: ["pro-monthly", "pro-yearly"],+ expand: ["data.currency_options"],+ });++ return mapProPrices(prices.data);+}+export type PricingData = Awaited<ReturnType<typeof getProPricing>>;diff --git a/packages/billing/src/pricing.test.ts b/packages/billing/src/pricing.test.tsnew file mode 100644index 000000000..f862e2abc--- /dev/null+++ b/packages/billing/src/pricing.test.ts@@ -0,0 +1,14 @@+import { describe, expect, it } from "vitest";+import { yearlySavingsPercent } from "./pricing";++describe("yearlySavingsPercent", () => {+ it("rounds the saving of yearly against twelve months to a whole percent", () => {+ expect(yearlySavingsPercent({ monthly: 700, yearly: 5600 })).toBe(33);+ expect(yearlySavingsPercent({ monthly: 560, yearly: 4500 })).toBe(33);+ expect(yearlySavingsPercent({ monthly: 1000, yearly: 8400 })).toBe(30);+ });++ it("is zero when yearly costs the same as twelve months", () => {+ expect(yearlySavingsPercent({ monthly: 100, yearly: 1200 })).toBe(0);+ });+});diff --git a/packages/billing/src/pricing.ts b/packages/billing/src/pricing.tsindex 234230cab..8e2dab6a5 100644--- a/packages/billing/src/pricing.ts+++ b/packages/billing/src/pricing.ts@@ -8,3 +8,15 @@ export const pricingData = {currency: "usd",},};++export function yearlySavingsPercent({+ monthly,+ yearly,+}: {+ monthly: number;+ yearly: number;+}) {+ return Math.round((1 - yearly / (monthly * 12)) * 100);+}++export const displayedCurrencies = ["usd", "eur", "gbp"] as const;diff --git a/packages/billing/vitest.config.mts b/packages/billing/vitest.config.mtsnew file mode 100644index 000000000..83bef549f--- /dev/null+++ b/packages/billing/vitest.config.mts@@ -0,0 +1,9 @@+import { defineConfig } from "vitest/config";++export default defineConfig({+ test: {+ globals: true,+ include: ["**/*.test.ts"],+ exclude: ["**/node_modules/**"],+ },+});diff --git a/packages/ui/src/badge.tsx b/packages/ui/src/badge.tsxindex d2061ab82..c91870eda 100644--- a/packages/ui/src/badge.tsx+++ b/packages/ui/src/badge.tsx@@ -17,6 +17,7 @@ const badgeVariants = cva(green:"bg-green-400/10 text-green-600 dark:bg-green-500/10 dark:text-green-500",secondary: "bg-primary/10 text-primary",+ pill: "rounded-full bg-gray-200 text-gray-700 dark:bg-gray-700 dark:text-gray-200",},size: {sm: "h-5 min-w-5 px-1.5 text-xs",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 268a9d593..2489dc00e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -533,6 +533,9 @@ importers:'@rallly/tsconfig':specifier: workspace:*version: link:../tsconfig+ vitest:+ specifier: ^4.0.16+ version: 4.0.18(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/database:dependencies: