Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Resolve early supporter prices and add the Pro reprice script (#3303)
Luke Vellace0fb666ea53
diff --git a/apps/web/src/features/billing/data.ts b/apps/web/src/features/billing/data.tsindex 979ab7d0a..728a830b2 100644--- a/apps/web/src/features/billing/data.ts+++ b/apps/web/src/features/billing/data.ts@@ -44,8 +44,10 @@ export async function getSpaceSubscription(spaceId: string) {// 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.+// Bump the "-vN" suffix whenever the cached shape changes, so a warm cache+// never deserialises a value in the old shape.export const getProPrices = unstable_cache(- async () => (await getProPricing({ stripe: getStripe() })).currencies,- ["pro-prices"],+ async () => getProPricing({ stripe: getStripe() }),+ ["pro-prices-v2"],{ revalidate: 60 * 60 },);diff --git a/apps/web/src/features/billing/loaders.ts b/apps/web/src/features/billing/loaders.tsindex 8368d373e..c5c10c45b 100644--- a/apps/web/src/features/billing/loaders.ts+++ b/apps/web/src/features/billing/loaders.ts@@ -18,11 +18,12 @@ export const loadPayWallPricing = cache(async () => {return null;}try {- const [prices, cookieStore, headersList] = await Promise.all([+ const [pricing, cookieStore, headersList] = await Promise.all([getProPrices(),cookies(),headers(),]);+ const prices = pricing.currencies;const available = Object.keys(prices);if (available.length === 0) {return null;diff --git a/packages/billing/package.json b/packages/billing/package.jsonindex f8328d3b2..ab5a20ebc 100644--- a/packages/billing/package.json+++ b/packages/billing/package.json@@ -10,6 +10,7 @@"checkout-expiry": "dotenv -e .env -- pnpx tsx ./src/scripts/checkout-expiry.ts","cleanup-portal-configurations": "dotenv -e .env -- pnpx tsx ./src/scripts/cleanup-portal-configurations.ts","invoice-pending-prorations": "dotenv -e .env -- pnpx tsx ./src/scripts/invoice-pending-prorations.ts",+ "reprice-pro": "dotenv -e .env -- pnpx tsx ./src/scripts/reprice-pro.ts","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",diff --git a/packages/billing/src/lib/stripe.test.ts b/packages/billing/src/lib/stripe.test.tsindex d676e86f7..0826f972d 100644--- a/packages/billing/src/lib/stripe.test.ts+++ b/packages/billing/src/lib/stripe.test.ts@@ -40,6 +40,7 @@ describe("mapProPrices", () => {id: "price_pro-monthly",amount: 700,currency: "usd",+ amounts: { usd: 700 },});expect(result.yearly.amount).toBe(5600);});@@ -66,4 +67,53 @@ describe("mapProPrices", () => {"Price not found",);});++ it("carries every currency amount on each price", () => {+ const result = mapProPrices([+ price("pro-monthly", 700, { eur: 650 }),+ price("pro-yearly", 5600, { eur: 5200 }),+ ]);+ expect(result.monthly.amounts).toEqual({ usd: 700, eur: 650 });+ expect(result.yearly.amounts).toEqual({ usd: 5600, eur: 5200 });+ });++ it("leaves earlySupporter undefined when the early supporter keys are absent", () => {+ const result = mapProPrices([+ price("pro-monthly", 1000),+ price("pro-yearly", 8400),+ ]);+ expect(result.earlySupporter).toBeUndefined();+ });++ it("maps the early supporter prices when both keys are present", () => {+ const result = mapProPrices([+ price("pro-monthly", 1000),+ price("pro-yearly", 8400),+ price("pro-monthly-early-supporter", 700, { eur: 650 }),+ price("pro-yearly-early-supporter", 5600),+ ]);+ expect(result.earlySupporter).toEqual({+ monthly: {+ id: "price_pro-monthly-early-supporter",+ amount: 700,+ currency: "usd",+ amounts: { usd: 700, eur: 650 },+ },+ yearly: {+ id: "price_pro-yearly-early-supporter",+ amount: 5600,+ currency: "usd",+ amounts: { usd: 5600 },+ },+ });+ });++ it("ignores a lone early supporter key so a half finished rollout never exposes one interval", () => {+ const result = mapProPrices([+ price("pro-monthly", 1000),+ price("pro-yearly", 8400),+ price("pro-monthly-early-supporter", 700),+ ]);+ expect(result.earlySupporter).toBeUndefined();+ });});diff --git a/packages/billing/src/lib/stripe.ts b/packages/billing/src/lib/stripe.tsindex 5e17d9c5a..b033fcec6 100644--- a/packages/billing/src/lib/stripe.ts+++ b/packages/billing/src/lib/stripe.ts@@ -17,6 +17,21 @@ export type PriceAmounts = {export type PricesByCurrency = Record<string, PriceAmounts>;+export const PRO_LOOKUP_KEYS = {+ monthly: "pro-monthly",+ yearly: "pro-yearly",+ earlySupporterMonthly: "pro-monthly-early-supporter",+ earlySupporterYearly: "pro-yearly-early-supporter",+} as const;++export type ProPrice = {+ id: string;+ amount: number;+ currency: string;+ /** Unit amount per currency in minor units: base currency plus currency_options. */+ amounts: Record<string, number>;+};+function unitAmountsByCurrency(price: Stripe.Price) {const amounts: Record<string, number> = {};if (price.unit_amount !== null) {@@ -32,48 +47,61 @@ function unitAmountsByCurrency(price: Stripe.Price) {return amounts;}+function toProPrice(price: Stripe.Price | undefined): ProPrice | undefined {+ if (!price || price.unit_amount === null) {+ return undefined;+ }+ return {+ id: price.id,+ amount: price.unit_amount,+ currency: price.currency,+ amounts: unitAmountsByCurrency(price),+ };+}+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 ||- !yearly ||- monthly.unit_amount === null ||- yearly.unit_amount === null- ) {+ const byKey = (key: string) =>+ prices.find((price) => price.lookup_key === key);++ const monthly = toProPrice(byKey(PRO_LOOKUP_KEYS.monthly));+ const yearly = toProPrice(byKey(PRO_LOOKUP_KEYS.yearly));++ if (!monthly || !yearly) {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];+ const monthlyAmount = monthly.amounts[currency];+ const yearlyAmount = yearly.amounts[currency];if (monthlyAmount !== undefined && yearlyAmount !== undefined) {currencies[currency] = { monthly: monthlyAmount, yearly: yearlyAmount };}}+ // Both or neither: a subscriber must be able to move between the two+ // early supporter intervals, so a half finished rollout exposes nothing.+ const earlySupporterMonthly = toProPrice(+ byKey(PRO_LOOKUP_KEYS.earlySupporterMonthly),+ );+ const earlySupporterYearly = toProPrice(+ byKey(PRO_LOOKUP_KEYS.earlySupporterYearly),+ );+return {- monthly: {- id: monthly.id,- amount: monthly.unit_amount,- currency: monthly.currency,- },- yearly: {- id: yearly.id,- amount: yearly.unit_amount,- currency: yearly.currency,- },+ monthly,+ yearly,currencies,+ earlySupporter:+ earlySupporterMonthly && earlySupporterYearly+ ? { monthly: earlySupporterMonthly, yearly: earlySupporterYearly }+ : undefined,};}export async function getProPricing({ stripe }: { stripe: Stripe }) {const prices = await stripe.prices.list({- lookup_keys: ["pro-monthly", "pro-yearly"],+ lookup_keys: Object.values(PRO_LOOKUP_KEYS),expand: ["data.currency_options"],});diff --git a/packages/billing/src/scripts/reprice-pro.ts b/packages/billing/src/scripts/reprice-pro.tsnew file mode 100644index 000000000..5c1c720cd--- /dev/null+++ b/packages/billing/src/scripts/reprice-pro.ts@@ -0,0 +1,238 @@+import type { Stripe } from "../lib/stripe";+import { createStripeClient, PRO_LOOKUP_KEYS } from "../lib/stripe";++/**+ * Moves the `pro-monthly` / `pro-yearly` lookup keys onto new prices and+ * re-keys the previous prices as early supporter prices. Existing+ * subscriptions keep their price object, so they become early supporters by+ * the app's "not a current price" rule the moment the keys move.+ *+ * Each interval is reconciled independently from whatever state Stripe is in,+ * so a run that stops partway can be repeated until both intervals report+ * done. The new price carries `metadata.replaces = <old price id>` so a+ * half moved interval can still be finished.+ *+ * DRY RUN by default. Pass --apply to write.+ *+ * Usage:+ * pnpm --filter @rallly/billing reprice-pro -- --monthly usd=1000,eur=900,gbp=800 --yearly usd=7200,eur=6500,gbp=5800+ * pnpm --filter @rallly/billing reprice-pro -- --monthly ... --yearly ... --apply+ */++const secretKey = process.env.STRIPE_SECRET_KEY;++if (!secretKey) {+ throw new Error("STRIPE_SECRET_KEY is not set");+}++const stripe = createStripeClient({ secretKey });++const REPLACES_METADATA_KEY = "replaces";++type Interval = "month" | "year";++type IntervalSpec = {+ interval: Interval;+ currentKey: string;+ earlySupporterKey: string;+ amounts: Record<string, number>;+};++function parseAmounts(flag: string) {+ const args = process.argv.slice(2);+ const index = args.indexOf(flag);+ const raw = index === -1 ? undefined : args[index + 1];+ if (!raw) {+ throw new Error(`Missing ${flag} usd=<minor>,eur=<minor>,gbp=<minor>`);+ }+ const amounts: Record<string, number> = {};+ for (const pair of raw.split(",")) {+ const parts = pair.split("=");+ const currency = parts[0]?.trim().toLowerCase();+ const amount = parts[1]?.trim();+ const value = Number(amount);+ if (+ parts.length !== 2 ||+ !currency ||+ !/^[a-z]{3}$/.test(currency) ||+ !amount ||+ !/^\d+$/.test(amount) ||+ !Number.isSafeInteger(value) ||+ value <= 0 ||+ Object.hasOwn(amounts, currency)+ ) {+ throw new Error(`Invalid amount in ${flag}: ${pair}`);+ }+ amounts[currency] = value;+ }+ if (!amounts.usd) {+ throw new Error(`${flag} must include usd`);+ }+ return amounts;+}++async function findByLookupKey(lookupKey: string) {+ const prices = await stripe.prices.list({+ lookup_keys: [lookupKey],+ expand: ["data.currency_options"],+ });+ return prices.data[0];+}++// The replacement price created earlier for `oldPrice`, located by metadata+// rather than lookup key because a crash between "create" and "re-key" leaves+// it without one.+async function findReplacementFor(oldPrice: Stripe.Price, interval: Interval) {+ const prices = stripe.prices.list({+ product: oldPrice.product as string,+ active: true,+ recurring: { interval },+ limit: 100,+ });+ for await (const price of prices) {+ if (price.metadata?.[REPLACES_METADATA_KEY] === oldPrice.id) {+ return price;+ }+ }+ return undefined;+}++function describe(price: Stripe.Price) {+ const options = Object.entries(price.currency_options ?? {})+ .map(([currency, option]) => `${currency}=${option.unit_amount}`)+ .join(",");+ return `${price.id} (${price.currency}=${price.unit_amount}${options ? `, ${options}` : ""})`;+}++function toCreateParams(+ oldPrice: Stripe.Price,+ spec: IntervalSpec,+): Stripe.PriceCreateParams {+ const { usd, ...others } = spec.amounts;+ return {+ product: oldPrice.product as string,+ currency: "usd",+ unit_amount: usd,+ recurring: { interval: spec.interval },+ metadata: { [REPLACES_METADATA_KEY]: oldPrice.id },+ currency_options: Object.fromEntries(+ Object.entries(others).map(([currency, amount]) => [+ currency,+ { unit_amount: amount },+ ]),+ ),+ };+}++/**+ * Brings one interval to the finished state: the new price holds the current+ * key, the old price holds the early supporter key. Steps, each of which can+ * be the point a previous run stopped at:+ *+ * 1. create the new price (no lookup key yet; idempotent on the old price id)+ * 2. move the old price onto the early supporter key+ * 3. move the new price onto the current key+ */+async function reconcileInterval(spec: IntervalSpec, apply: boolean) {+ const label = spec.interval === "month" ? "monthly" : "yearly";+ const [current, earlySupporter] = await Promise.all([+ findByLookupKey(spec.currentKey),+ findByLookupKey(spec.earlySupporterKey),+ ]);++ if (current && earlySupporter) {+ console.info(+ `✅ ${label}: done. ${spec.currentKey}=${current.id} ${spec.earlySupporterKey}=${earlySupporter.id}`,+ );+ return;+ }++ if (!current && !earlySupporter) {+ throw new Error(`${label}: neither lookup key exists; nothing to move`);+ }++ if (earlySupporter && !current) {+ // Stopped between steps 2 and 3.+ const replacement = await findReplacementFor(earlySupporter, spec.interval);+ if (!replacement) {+ throw new Error(+ `${label}: ${spec.earlySupporterKey} is set on ${earlySupporter.id} but no replacement price carries metadata.${REPLACES_METADATA_KEY}=${earlySupporter.id}`,+ );+ }+ console.info(+ `↻ ${label}: resuming. Assign ${spec.currentKey} to ${describe(replacement)}`,+ );+ if (apply) {+ await stripe.prices.update(replacement.id, {+ lookup_key: spec.currentKey,+ });+ console.info(`✅ ${label}: done.`);+ }+ return;+ }++ // current && !earlySupporter: not started, or stopped between steps 1 and 2.+ const oldPrice = current as Stripe.Price;+ if (oldPrice.metadata?.[REPLACES_METADATA_KEY]) {+ throw new Error(+ `${label}: ${spec.currentKey} is already on a replacement price (${oldPrice.id}) but ${spec.earlySupporterKey} is missing; fix the keys in Stripe by hand`,+ );+ }++ console.info(`Current ${label}: ${describe(oldPrice)}`);+ console.info(`New ${label}: ${JSON.stringify(spec.amounts)}`);++ if (!apply) {+ return;+ }++ // Idempotent on the old price id, so a re-run after a crash between steps 1+ // and 2 gets the same price back instead of a second one.+ const replacement = await stripe.prices.create(+ toCreateParams(oldPrice, spec),+ { idempotencyKey: `reprice-pro-${label}-${oldPrice.id}` },+ );+ await stripe.prices.update(oldPrice.id, {+ lookup_key: spec.earlySupporterKey,+ });+ await stripe.prices.update(replacement.id, {+ lookup_key: spec.currentKey,+ });+ console.info(+ `✅ ${label}: done. ${spec.currentKey}=${replacement.id} ${spec.earlySupporterKey}=${oldPrice.id}`,+ );+}++(async function repricePro() {+ const apply = process.argv.slice(2).includes("--apply");+ const specs: IntervalSpec[] = [+ {+ interval: "month",+ currentKey: PRO_LOOKUP_KEYS.monthly,+ earlySupporterKey: PRO_LOOKUP_KEYS.earlySupporterMonthly,+ amounts: parseAmounts("--monthly"),+ },+ {+ interval: "year",+ currentKey: PRO_LOOKUP_KEYS.yearly,+ earlySupporterKey: PRO_LOOKUP_KEYS.earlySupporterYearly,+ amounts: parseAmounts("--yearly"),+ },+ ];++ console.info(+ apply+ ? "⚠️ APPLY mode — prices will be created and lookup keys moved."+ : "🔍 DRY RUN — nothing will change. Pass --apply to write.",+ );++ for (const spec of specs) {+ await reconcileInterval(spec, apply);+ }++ console.info(+ apply+ ? "\nThe app caches prices for one hour. Redeploy or wait before verifying."+ : "\n🔍 Dry run complete. Re-run with --apply to write.",+ );+})();