Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
♻️ Key billing portal configurations by the price set they allow (#3306)
Luke Vellaf713fc686d24
diff --git a/apps/web/src/features/billing/data.ts b/apps/web/src/features/billing/data.tsindex 728a830b2..902e58ebd 100644--- a/apps/web/src/features/billing/data.ts+++ b/apps/web/src/features/billing/data.ts@@ -27,6 +27,8 @@ export async function getSpaceSubscription(spaceId: string) {return {id: subscription.id,+ priceId: subscription.priceId,+ userId: subscription.userId,tier: (subscription.active ? "pro" : "hobby") as SpaceTier,quantity: subscription.quantity,subscriptionItemId: subscription.subscriptionItemId,diff --git a/apps/web/src/features/billing/mutations.ts b/apps/web/src/features/billing/mutations.tsindex d0114f491..007525db0 100644--- a/apps/web/src/features/billing/mutations.ts+++ b/apps/web/src/features/billing/mutations.ts@@ -1,10 +1,9 @@import "server-only";-import { getProPricing } from "@rallly/billing";import {- SEAT_UPDATE_PORTAL_HEADLINE,- SEAT_UPDATE_PORTAL_PURPOSE,- SEAT_UPDATE_PORTAL_VERSION,+ ACCOUNT_PORTAL_CONFIG_VERSION,+ PORTAL_CONFIG_PURPOSE,+ portalConfigPriceKey,} from "@rallly/billing/lib/portal";import { prisma } from "@rallly/database";import { absoluteUrl } from "@rallly/utils/absolute-url";@@ -27,91 +26,160 @@ export async function createStripePortalSession({return portalSession.url;}-async function createSeatUpdateBillingConfig() {+async function findConfigurationByMetadata(+ match: Record<string, string>,+): Promise<string | undefined> {+ // Auto-paginate so a match isn't missed when many stale configs still exist+ // (pre-cleanup). The live configs are the newest, so this returns on the+ // first page in practice.+ const configs = getStripe().billingPortal.configurations.list({+ active: true,+ limit: 100,+ });+ for await (const config of configs) {+ const metadata = config.metadata ?? {};+ if (+ Object.entries(match).every(([key, value]) => metadata[key] === value)+ ) {+ return config.id;+ }+ }+ return undefined;+}++async function createFlowsConfiguration({ priceIds }: { priceIds: string[] }) {const stripe = getStripe();- const pricing = await getProPricing({ stripe });+ const priceKey = portalConfigPriceKey(priceIds);- // Both monthly and yearly prices share the same product.- const monthlyPrice = await stripe.prices.retrieve(pricing.monthly.id);- const productId = monthlyPrice.product as string;+ // Stripe validates that every price listed under a product belongs to it,+ // so group by product rather than assume the set shares one.+ const pricesByProduct = new Map<string, string[]>();+ for (const priceId of new Set(priceIds)) {+ const price = await stripe.prices.retrieve(priceId);+ const productId = price.product as string;+ pricesByProduct.set(productId, [+ ...(pricesByProduct.get(productId) ?? []),+ priceId,+ ]);+ }return stripe.billingPortal.configurations.create({business_profile: {- headline: SEAT_UPDATE_PORTAL_HEADLINE,+ headline: "Update your subscription",},features: {subscription_update: {enabled: true,default_allowed_updates: ["price", "quantity"],- // Invoice prorations immediately so seat additions are charged right away- // rather than deferred onto the next renewal invoice.+ // Invoice prorations immediately so seat additions are charged right+ // away rather than deferred onto the next renewal invoice.proration_behavior: "always_invoice",- products: [- {- product: productId,- prices: [pricing.monthly.id, pricing.yearly.id],- },- ],- },- subscription_cancel: {- enabled: false,+ products: [...pricesByProduct.entries()].map(([product, prices]) => ({+ product,+ prices,+ })),},- payment_method_update: {+ // Cancellation is in-app so the retention moment is ours.+ subscription_cancel: { enabled: false },+ payment_method_update: { enabled: true },+ invoice_history: { enabled: true },+ },+ metadata: {+ purpose: PORTAL_CONFIG_PURPOSE.flows,+ prices: priceKey,+ },+ },+ {+ // Collapse concurrent first-time creation across processes into a+ // single config; the cleanup script would otherwise leave duplicates+ // active forever.+ idempotencyKey: `portal-config-flows-${priceKey}`,+ },+ );+}++async function createAccountConfiguration() {+ return getStripe().billingPortal.configurations.create(+ {+ business_profile: {+ headline: "Manage your billing details",+ },+ features: {+ customer_update: {enabled: true,+ allowed_updates: ["name", "address", "tax_id"],},- invoice_history: {- enabled: true,+ payment_method_update: { enabled: true },+ invoice_history: { enabled: true },+ // Stripe's create type requires these even when disabled.+ subscription_update: {+ enabled: false,+ default_allowed_updates: null,+ products: null,},+ subscription_cancel: { enabled: false },},metadata: {- purpose: SEAT_UPDATE_PORTAL_PURPOSE,- version: SEAT_UPDATE_PORTAL_VERSION,+ purpose: PORTAL_CONFIG_PURPOSE.account,+ version: ACCOUNT_PORTAL_CONFIG_VERSION,},},{- // Collapse concurrent first-time creation across processes (e.g. right- // after a deploy) into a single config. Without this, two cold instances- // can each create a same-version config — and the cleanup script skips the- // current version, so the duplicates would linger active forever.- idempotencyKey: `seat-update-portal-config-v${SEAT_UPDATE_PORTAL_VERSION}`,+ idempotencyKey: `portal-config-account-v${ACCOUNT_PORTAL_CONFIG_VERSION}`,},);}-async function resolveConfigurationId(): Promise<string> {- // Auto-paginate so a match isn't missed when many stale configs still exist- // (pre-cleanup). The current-version config is the newest, so this returns on- // the first page in practice.- const configs = getStripe().billingPortal.configurations.list({- active: true,- limit: 100,- });- for await (const config of configs) {- if (- config.metadata?.purpose === SEAT_UPDATE_PORTAL_PURPOSE &&- config.metadata?.version === SEAT_UPDATE_PORTAL_VERSION- ) {- return config.id;- }- }-- const created = await createSeatUpdateBillingConfig();- return created.id;-}+// Memoised per server process and per identity. Dedupes concurrent callers+// and survives across warm invocations; resets on failure so the next call+// retries.+const configurationIdPromises = new Map<string, Promise<string>>();-// Memoised per server process. Dedupes concurrent callers and survives across-// warm invocations; resets on failure so the next call retries.-let configurationIdPromise: Promise<string> | undefined;--function getSeatUpdatePortalConfigurationId(): Promise<string> {- if (!configurationIdPromise) {- configurationIdPromise = resolveConfigurationId().catch((error) => {- configurationIdPromise = undefined;+function memoiseConfigurationId(key: string, resolve: () => Promise<string>) {+ let promise = configurationIdPromises.get(key);+ if (!promise) {+ promise = resolve().catch((error) => {+ configurationIdPromises.delete(key);throw error;});+ configurationIdPromises.set(key, promise);}- return configurationIdPromise;+ return promise;+}++export function getFlowsPortalConfigurationId({+ priceIds,+}: {+ priceIds: string[];+}) {+ const priceKey = portalConfigPriceKey(priceIds);+ return memoiseConfigurationId(`flows:${priceKey}`, async () => {+ const existing = await findConfigurationByMetadata({+ purpose: PORTAL_CONFIG_PURPOSE.flows,+ prices: priceKey,+ });+ if (existing) {+ return existing;+ }+ return (await createFlowsConfiguration({ priceIds })).id;+ });+}++export function getAccountPortalConfigurationId() {+ return memoiseConfigurationId(+ `account:${ACCOUNT_PORTAL_CONFIG_VERSION}`,+ async () => {+ const existing = await findConfigurationByMetadata({+ purpose: PORTAL_CONFIG_PURPOSE.account,+ version: ACCOUNT_PORTAL_CONFIG_VERSION,+ });+ if (existing) {+ return existing;+ }+ return (await createAccountConfiguration()).id;+ },+ );}export function billingReturnUrl(flow: BillingReturnFlow) {@@ -119,21 +187,31 @@ export function billingReturnUrl(flow: BillingReturnFlow) {}/**- * Creates a billing portal session deep-linked to the seat-update confirmation- * screen for a specific quantity change, reusing the shared configuration.+ * Creates a billing portal session deep-linked to the confirmation screen for+ * a specific change to the subscription's single item: a new quantity, a new+ * price, or both. The configuration only lists the subscriber's own price+ * set, so an early supporter can never be moved onto a current price here.+ * The subscriber's own current price is always included even when it's+ * neither the current nor early supporter price (a legacy tail price):+ * Stripe's subscription_update_confirm requires the item's current price to+ * be in the configuration's product price list, or the flow fails outright.*/export async function createStripeSubscriptionUpdateConfirmation({customerId,subscriptionId,subscriptionItemId,- newSeatCount,+ priceIds,+ item,+ returnFlow,}: {customerId: string;subscriptionId: string;subscriptionItemId: string;- newSeatCount: number;+ priceIds: string[];+ item: { quantity?: number; price?: string };+ returnFlow: BillingReturnFlow;}) {- const configurationId = await getSeatUpdatePortalConfigurationId();+ const configurationId = await getFlowsPortalConfigurationId({ priceIds });const portalSession = await getStripe().billingPortal.sessions.create({customer: customerId,@@ -143,16 +221,11 @@ export async function createStripeSubscriptionUpdateConfirmation({type: "subscription_update_confirm",subscription_update_confirm: {subscription: subscriptionId,- items: [- {- id: subscriptionItemId,- quantity: newSeatCount,- },- ],+ items: [{ id: subscriptionItemId, ...item }],},after_completion: {type: "redirect",- redirect: { return_url: billingReturnUrl("seats") },+ redirect: { return_url: billingReturnUrl(returnFlow) },},},});diff --git a/apps/web/src/features/billing/utils.test.ts b/apps/web/src/features/billing/utils.test.tsindex be65c02f3..675961eba 100644--- a/apps/web/src/features/billing/utils.test.ts+++ b/apps/web/src/features/billing/utils.test.ts@@ -1,4 +1,5 @@import { afterEach, describe, expect, it, vi } from "vitest";+import { isEarlySupporter, resolvePriceSet } from "./utils";// isBillingEnabled is a module constant read from the environment, so each// branch needs a fresh module registry to observe the stubbed value.@@ -28,3 +29,71 @@ describe("resolveSpaceTier", () => {expect(resolveSpaceTier("pro")).toBe("pro");});});++const price = (id: string, amount: number) => ({+ id,+ amount,+ currency: "usd",+ amounts: { usd: amount },+});++const pricing = {+ monthly: price("price_new_m", 1000),+ yearly: price("price_new_y", 8400),+ currencies: { usd: { monthly: 1000, yearly: 8400 } },+ earlySupporter: {+ monthly: price("price_old_m", 700),+ yearly: price("price_old_y", 5600),+ },+};++describe("isEarlySupporter", () => {+ it("is false for a subscription on a current price", () => {+ expect(isEarlySupporter({ priceId: "price_new_m", pricing })).toBe(false);+ expect(isEarlySupporter({ priceId: "price_new_y", pricing })).toBe(false);+ });++ it("is true for a subscription on an early supporter price", () => {+ expect(isEarlySupporter({ priceId: "price_old_y", pricing })).toBe(true);+ });++ it("is true for a subscription on an older price with no lookup key", () => {+ expect(isEarlySupporter({ priceId: "price_2022_y", pricing })).toBe(true);+ });++ it("is false before the rollout when there are no early supporter prices", () => {+ expect(+ isEarlySupporter({+ priceId: "price_2022_y",+ pricing: { ...pricing, earlySupporter: undefined },+ }),+ ).toBe(false);+ });++ it("is false when pricing could not be loaded", () => {+ expect(isEarlySupporter({ priceId: "price_old_y", pricing: null })).toBe(+ false,+ );+ });+});++describe("resolvePriceSet", () => {+ it("returns the early supporter pair for early supporters", () => {+ expect(resolvePriceSet({ earlySupporter: true, pricing })).toEqual(+ pricing.earlySupporter,+ );+ });++ it("returns the current pair otherwise, and when early supporter prices are missing", () => {+ expect(resolvePriceSet({ earlySupporter: false, pricing })).toEqual({+ monthly: pricing.monthly,+ yearly: pricing.yearly,+ });+ expect(+ resolvePriceSet({+ earlySupporter: true,+ pricing: { ...pricing, earlySupporter: undefined },+ }),+ ).toEqual({ monthly: pricing.monthly, yearly: pricing.yearly });+ });+});diff --git a/apps/web/src/features/billing/utils.ts b/apps/web/src/features/billing/utils.tsindex 560f33f78..65900de73 100644--- a/apps/web/src/features/billing/utils.ts+++ b/apps/web/src/features/billing/utils.ts@@ -1,3 +1,4 @@+import type { PricingData, ProPrice } from "@rallly/billing";import { isBillingEnabled } from "@/features/billing/constants";import type { SpaceTier } from "@/features/space/schema";@@ -22,3 +23,37 @@ export function isStripeErrorCode(error: unknown, code: string) {export function isStripeResourceMissingError(error: unknown) {return isStripeErrorCode(error, "resource_missing");}++type PricingLike = Pick<PricingData, "monthly" | "yearly" | "earlySupporter">;++/**+ * A subscriber whose price is not one of the two current list prices keeps+ * that price for life. Only meaningful once the early supporter prices exist+ * in Stripe; before the rollout everyone is on a current price by definition.+ */+export function isEarlySupporter({+ priceId,+ pricing,+}: {+ priceId: string;+ pricing: PricingLike | null;+}) {+ if (!pricing?.earlySupporter) {+ return false;+ }+ return priceId !== pricing.monthly.id && priceId !== pricing.yearly.id;+}++/** The monthly/yearly pair a subscriber may move between without repricing. */+export function resolvePriceSet({+ earlySupporter,+ pricing,+}: {+ earlySupporter: boolean;+ pricing: PricingLike;+}): { monthly: ProPrice; yearly: ProPrice } {+ if (earlySupporter && pricing.earlySupporter) {+ return pricing.earlySupporter;+ }+ return { monthly: pricing.monthly, yearly: pricing.yearly };+}diff --git a/apps/web/src/trpc/routers/billing.ts b/apps/web/src/trpc/routers/billing.tsindex fc06a1635..8c5fd1774 100644--- a/apps/web/src/trpc/routers/billing.ts+++ b/apps/web/src/trpc/routers/billing.ts@@ -1,8 +1,9 @@import { TRPCError } from "@trpc/server";import * as z from "zod";-import { getSpaceSubscription } from "@/features/billing/data";+import { getProPrices, getSpaceSubscription } from "@/features/billing/data";import { createStripeSubscriptionUpdateConfirmation } from "@/features/billing/mutations";+import { isEarlySupporter, resolvePriceSet } from "@/features/billing/utils";import { getSpaceSeatCount } from "@/features/space/data";import { router, spaceOwnerProcedure } from "../trpc";@@ -46,12 +47,27 @@ export const billing = router({});}+ const pricing = await getProPrices();+ const priceSet = resolvePriceSet({+ earlySupporter: isEarlySupporter({+ priceId: subscription.priceId,+ pricing,+ }),+ pricing,+ });+const portalSessionUrl = await createStripeSubscriptionUpdateConfirmation({customerId: ctx.user.customerId,- newSeatCount,subscriptionId: subscription.id,subscriptionItemId: subscription.subscriptionItemId,+ priceIds: [+ priceSet.monthly.id,+ priceSet.yearly.id,+ subscription.priceId,+ ],+ item: { quantity: newSeatCount },+ returnFlow: "seats",},);diff --git a/packages/billing/src/lib/portal.test.ts b/packages/billing/src/lib/portal.test.tsnew file mode 100644index 000000000..c30345ba4--- /dev/null+++ b/packages/billing/src/lib/portal.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from "vitest";+import { portalConfigCoversPair, portalConfigPriceKey } from "./portal";++describe("portalConfigPriceKey", () => {+ it("is order independent so the same price set always resolves the same configuration", () => {+ expect(portalConfigPriceKey(["price_b", "price_a"])).toBe(+ portalConfigPriceKey(["price_a", "price_b"]),+ );+ });++ it("distinguishes different price sets", () => {+ expect(portalConfigPriceKey(["price_a", "price_b"])).not.toBe(+ portalConfigPriceKey(["price_a", "price_c"]),+ );+ });++ it("deduplicates repeated ids", () => {+ expect(portalConfigPriceKey(["price_a", "price_a", "price_b"])).toBe(+ portalConfigPriceKey(["price_a", "price_b"]),+ );+ });+});++describe("portalConfigCoversPair", () => {+ it("is true when the key contains every id of the pair", () => {+ expect(+ portalConfigCoversPair({+ key: "price_a,price_b",+ pairIds: ["price_a", "price_b"],+ }),+ ).toBe(true);+ });++ it("is true when the key has extra ids beyond the pair", () => {+ expect(+ portalConfigCoversPair({+ key: "price_a,price_b,price_legacy",+ pairIds: ["price_a", "price_b"],+ }),+ ).toBe(true);+ });++ it("is false when the key is missing one of the pair's ids", () => {+ expect(+ portalConfigCoversPair({+ key: "price_a",+ pairIds: ["price_a", "price_b"],+ }),+ ).toBe(false);+ });+});diff --git a/packages/billing/src/lib/portal.ts b/packages/billing/src/lib/portal.tsindex 7e11f6b20..70ba253da 100644--- a/packages/billing/src/lib/portal.ts+++ b/packages/billing/src/lib/portal.ts@@ -1,13 +1,37 @@/**- * Identity markers for the seat-update billing portal configuration. Shared- * between the seat-update flow (apps/web/src/features/billing/portal.ts), which- * creates and reuses the configuration, and the cleanup script- * (scripts/cleanup-portal-configurations.ts), which deactivates stale ones.+ * Identity markers for the code defined billing portal configurations. Shared+ * between the app (which creates and reuses them) and the cleanup script+ * (which deactivates stale ones; Stripe has no DELETE for configurations).*- * Bump SEAT_UPDATE_PORTAL_VERSION whenever the configuration shape changes: a new- * configuration is created on next use and the cleanup script retires the- * previous-version ones.+ * "flows" configurations are keyed by the pair of prices they allow, so a+ * price change creates a fresh configuration on next use instead of relying+ * on someone bumping a version. "account" is static; bump its version when+ * its feature set changes.*/-export const SEAT_UPDATE_PORTAL_HEADLINE = "Update your seat allocation";-export const SEAT_UPDATE_PORTAL_PURPOSE = "seat_update";-export const SEAT_UPDATE_PORTAL_VERSION = "1";+export const PORTAL_CONFIG_PURPOSE = {+ flows: "flows",+ account: "account",+} as const;++export const ACCOUNT_PORTAL_CONFIG_VERSION = "1";++export function portalConfigPriceKey(priceIds: string[]) {+ return [...new Set(priceIds)].sort().join(",");+}++/**+ * A flows config is still live if it covers every id of at least one live+ * price pair (the current pair, or the early supporter pair) — it may also+ * carry extra ids (legacy tail-price subscribers folded in), which must not+ * make it look stale.+ */+export function portalConfigCoversPair({+ key,+ pairIds,+}: {+ key: string;+ pairIds: string[];+}) {+ const keyIds = new Set(key.split(",").filter(Boolean));+ return pairIds.every((id) => keyIds.has(id));+}diff --git a/packages/billing/src/scripts/cleanup-portal-configurations.ts b/packages/billing/src/scripts/cleanup-portal-configurations.tsindex e60839370..4755f2051 100644--- a/packages/billing/src/scripts/cleanup-portal-configurations.ts+++ b/packages/billing/src/scripts/cleanup-portal-configurations.ts@@ -1,8 +1,9 @@import {- SEAT_UPDATE_PORTAL_HEADLINE,- SEAT_UPDATE_PORTAL_VERSION,+ ACCOUNT_PORTAL_CONFIG_VERSION,+ PORTAL_CONFIG_PURPOSE,+ portalConfigCoversPair,} from "../lib/portal";-import { createStripeClient } from "../lib/stripe";+import { createStripeClient, getProPricing } from "../lib/stripe";const secretKey = process.env.STRIPE_SECRET_KEY;@@ -13,15 +14,17 @@ if (!secretKey) {const stripe = createStripeClient({ secretKey });/**- * Before the seat-update flow reused a single billing portal configuration, it- * created a new one on every session, so the Stripe account accumulated throwaway- * config objects. Stripe has no API to DELETE a portal configuration — the only- * cleanup available is to deactivate it (`active: false`).+ * Portal configurations are created on demand and identified by metadata:+ * "flows" configurations carry the sorted pair of price ids they allow,+ * "account" carries a version. Stripe has no API to DELETE a portal+ * configuration — the only cleanup available is to deactivate it+ * (`active: false`).*- * This deactivates the stale seat-update configurations: those carrying our- * headline but NOT the current version (i.e. old unversioned ones, or any- * previous version after a version bump). The current-version configuration the- * app is actively using is left untouched, as is the default configuration.+ * This deactivates our stale configurations: "flows" configs whose price+ * pair is no longer a live price set (current or early supporter), "account"+ * configs whose version isn't current, and any leftover pre-2026-09+ * "seat_update" configs. The live configurations the app is actively using+ * are left untouched, as is the default configuration.** A 24h age guard additionally skips very recently created configs, eliminating* any race with an in-flight portal session.@@ -46,6 +49,36 @@ const MIN_AGE_MS = 24 * 60 * 60 * 1000;: "🔍 DRY RUN — nothing will change. Pass --apply to deactivate.",);+ const pricing = await getProPricing({ stripe });+ const livePairs = [[pricing.monthly.id, pricing.yearly.id]];+ if (pricing.earlySupporter) {+ livePairs.push([+ pricing.earlySupporter.monthly.id,+ pricing.earlySupporter.yearly.id,+ ]);+ }++ const isLive = (metadata: Record<string, string>) => {+ if (metadata.purpose === PORTAL_CONFIG_PURPOSE.flows) {+ const key = metadata.prices ?? "";+ // A flows config may also carry a subscriber's own legacy tail price+ // alongside a live pair, so "live" means it covers at least one pair.+ return livePairs.some((pairIds) =>+ portalConfigCoversPair({ key, pairIds }),+ );+ }+ if (metadata.purpose === PORTAL_CONFIG_PURPOSE.account) {+ return metadata.version === ACCOUNT_PORTAL_CONFIG_VERSION;+ }+ return false;+ };++ // "seat_update" is the pre-2026-09 purpose; every config carrying it is stale.+ const ours = (metadata: Record<string, string>) =>+ metadata.purpose === PORTAL_CONFIG_PURPOSE.flows ||+ metadata.purpose === PORTAL_CONFIG_PURPOSE.account ||+ metadata.purpose === "seat_update";+const stale: { id: string; created: Date }[] = [];let scanned = 0;let skippedRecent = 0;@@ -55,14 +88,10 @@ const MIN_AGE_MS = 24 * 60 * 60 * 1000;limit: 100,})) {scanned++;-- if (config.business_profile?.headline !== SEAT_UPDATE_PORTAL_HEADLINE) {- continue; // not one of ours- }+ const metadata = config.metadata ?? {};+ if (!ours(metadata)) continue; // not one of oursif (config.is_default) continue; // never touch the default- if (config.metadata?.version === SEAT_UPDATE_PORTAL_VERSION) {- continue; // current version — the live config, leave it- }+ if (isLive(metadata)) continue;if (config.created * 1000 > cutoff) {skippedRecent++;continue; // created within the age guard window@@ -72,7 +101,7 @@ const MIN_AGE_MS = 24 * 60 * 60 * 1000;}console.info(- `\nScanned ${scanned} active configuration(s); ${stale.length} stale seat-update config(s) to deactivate` ++ `\nScanned ${scanned} active configuration(s); ${stale.length} stale config(s) to deactivate` +(skippedRecent ? ` (${skippedRecent} skipped by 24h age guard).` : "."),);