Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

♻️ Reuse a single seat-update billing portal configuration (#2483)

Luke Vellaa45da41286b5
diff --git a/apps/web/src/features/billing/portal.ts b/apps/web/src/features/billing/portal.ts
new file mode 100644
index 000000000..0d06e948a
--- /dev/null
+++ b/apps/web/src/features/billing/portal.ts
@@ -0,0 +1,139 @@
+import { getProPricing, stripe } from "@rallly/billing";
+import {
+ SEAT_UPDATE_PORTAL_HEADLINE,
+ SEAT_UPDATE_PORTAL_PURPOSE,
+ SEAT_UPDATE_PORTAL_VERSION,
+} from "@rallly/billing/lib/portal";
+import { absoluteUrl } from "@rallly/utils/absolute-url";
+
+async function createSeatUpdateBillingConfig() {
+ const pricing = await getProPricing();
+
+ // Both monthly and yearly prices share the same product.
+ const monthlyPrice = await stripe.prices.retrieve(pricing.monthly.id);
+ const productId = monthlyPrice.product as string;
+
+ return stripe.billingPortal.configurations.create(
+ {
+ business_profile: {
+ headline: SEAT_UPDATE_PORTAL_HEADLINE,
+ },
+ 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.
+ proration_behavior: "always_invoice",
+ products: [
+ {
+ product: productId,
+ prices: [pricing.monthly.id, pricing.yearly.id],
+ },
+ ],
+ },
+ subscription_cancel: {
+ enabled: false,
+ },
+ payment_method_update: {
+ enabled: true,
+ },
+ invoice_history: {
+ enabled: true,
+ },
+ },
+ metadata: {
+ purpose: SEAT_UPDATE_PORTAL_PURPOSE,
+ version: SEAT_UPDATE_PORTAL_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}`,
+ },
+ );
+}
+
+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 = stripe.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. 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;
+ throw error;
+ });
+ }
+ return configurationIdPromise;
+}
+
+/**
+ * Creates a billing portal session deep-linked to the seat-update confirmation
+ * screen for a specific quantity change, reusing the shared configuration.
+ */
+export async function createStripeSubscriptionUpdateConfirmation({
+ customerId,
+ subscriptionId,
+ subscriptionItemId,
+ newSeatCount,
+}: {
+ customerId: string;
+ subscriptionId: string;
+ subscriptionItemId: string;
+ newSeatCount: number;
+}) {
+ const configurationId = await getSeatUpdatePortalConfigurationId();
+
+ const portalSession = await stripe.billingPortal.sessions.create({
+ customer: customerId,
+ configuration: configurationId,
+ return_url: absoluteUrl("/settings/billing"),
+ flow_data: {
+ type: "subscription_update_confirm",
+ subscription_update_confirm: {
+ subscription: subscriptionId,
+ items: [
+ {
+ id: subscriptionItemId,
+ quantity: newSeatCount,
+ },
+ ],
+ },
+ after_completion: {
+ type: "redirect",
+ redirect: {
+ return_url: absoluteUrl("/settings/billing", {
+ seats_updated: "true",
+ }),
+ },
+ },
+ },
+ });
+
+ return portalSession.url;
+}
diff --git a/apps/web/src/features/billing/utils.ts b/apps/web/src/features/billing/utils.ts
deleted file mode 100644
index d618ba752..000000000
--- a/apps/web/src/features/billing/utils.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-import { getProPricing, stripe } from "@rallly/billing";
-import { absoluteUrl } from "@rallly/utils/absolute-url";
-import { AppError } from "@/lib/errors";
-
-async function createQuantityUpdatePortalConfiguration(): Promise<string> {
- try {
- // Get pricing data to configure allowed products and prices
- const pricingData = await getProPricing();
-
- // Get the product ID from one of the prices (both monthly and yearly should have the same product)
- const monthlyPrice = await stripe.prices.retrieve(pricingData.monthly.id);
- const productId = monthlyPrice.product as string;
-
- // Create a billing portal configuration that allows both price and quantity changes
- const configuration = await stripe.billingPortal.configurations.create({
- business_profile: {
- headline: "Update your seat allocation",
- },
- features: {
- subscription_update: {
- enabled: true,
- default_allowed_updates: ["price", "quantity"], // Allow both price and quantity changes
- // 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: [pricingData.monthly.id, pricingData.yearly.id], // Allow switching between monthly and yearly
- },
- ],
- },
- subscription_cancel: {
- enabled: false, // Disable cancellation in seat management flow
- },
- payment_method_update: {
- enabled: true,
- },
- invoice_history: {
- enabled: true,
- },
- },
- });
-
- return configuration.id;
- } catch (error) {
- throw new AppError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Failed to create billing portal configuration",
- cause: error,
- });
- }
-}
-
-export const createStripeSubscriptionUpdateConfirmation = async ({
- customerId,
- subscriptionId,
- subscriptionItemId,
- newSeatCount,
-}: {
- customerId: string;
- subscriptionId: string;
- subscriptionItemId: string;
- newSeatCount: number;
-}) => {
- // Create a billing portal configuration that allows quantity updates
- const configurationId = await createQuantityUpdatePortalConfiguration();
-
- // Create Stripe billing portal session with subscription_update_confirm flow
- // This deep links directly to the confirmation screen for the specific quantity change
- const portalSession = await stripe.billingPortal.sessions.create({
- customer: customerId,
- configuration: configurationId,
- return_url: absoluteUrl("/settings/billing"),
- flow_data: {
- type: "subscription_update_confirm",
- subscription_update_confirm: {
- subscription: subscriptionId,
- items: [
- {
- id: subscriptionItemId,
- quantity: newSeatCount,
- },
- ],
- },
- after_completion: {
- type: "redirect",
- redirect: {
- return_url: absoluteUrl("/settings/billing?seats_updated=true"),
- },
- },
- },
- });
-
- return portalSession.url;
-};
diff --git a/apps/web/src/trpc/routers/billing.ts b/apps/web/src/trpc/routers/billing.ts
index d429fe7d0..a45513f75 100644
--- a/apps/web/src/trpc/routers/billing.ts
+++ b/apps/web/src/trpc/routers/billing.ts
@@ -2,7 +2,7 @@ import { TRPCError } from "@trpc/server";
import * as z from "zod";
import { getSpaceSubscription } from "@/features/billing/data";
-import { createStripeSubscriptionUpdateConfirmation } from "@/features/billing/utils";
+import { createStripeSubscriptionUpdateConfirmation } from "@/features/billing/portal";
import {
getActiveSpaceForUser,
getSpaceSeatCount,
diff --git a/packages/billing/package.json b/packages/billing/package.json
index 6e1a6e98f..98e6a52d5 100644
--- a/packages/billing/package.json
+++ b/packages/billing/package.json
@@ -8,6 +8,7 @@
},
"scripts": {
"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",
"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",
diff --git a/packages/billing/src/lib/portal.ts b/packages/billing/src/lib/portal.ts
new file mode 100644
index 000000000..7e11f6b20
--- /dev/null
+++ b/packages/billing/src/lib/portal.ts
@@ -0,0 +1,13 @@
+/**
+ * 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.
+ *
+ * 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.
+ */
+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";
diff --git a/packages/billing/src/scripts/cleanup-portal-configurations.ts b/packages/billing/src/scripts/cleanup-portal-configurations.ts
new file mode 100644
index 000000000..6bb1bf32b
--- /dev/null
+++ b/packages/billing/src/scripts/cleanup-portal-configurations.ts
@@ -0,0 +1,108 @@
+import {
+ SEAT_UPDATE_PORTAL_HEADLINE,
+ SEAT_UPDATE_PORTAL_VERSION,
+} from "../lib/portal";
+import { stripe } from "../lib/stripe";
+
+/**
+ * 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`).
+ *
+ * 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.
+ *
+ * A 24h age guard additionally skips very recently created configs, eliminating
+ * any race with an in-flight portal session.
+ *
+ * DRY RUN by default — lists what would be deactivated and changes nothing.
+ * Pass --apply to deactivate.
+ *
+ * Usage:
+ * pnpm --filter @rallly/billing cleanup-portal-configurations
+ * pnpm --filter @rallly/billing cleanup-portal-configurations -- --apply
+ */
+
+const MIN_AGE_MS = 24 * 60 * 60 * 1000;
+
+(async function cleanupPortalConfigurations() {
+ const apply = process.argv.slice(2).includes("--apply");
+ const cutoff = Date.now() - MIN_AGE_MS;
+
+ console.info(
+ apply
+ ? "⚠️ APPLY mode — matching configurations will be deactivated."
+ : "🔍 DRY RUN — nothing will change. Pass --apply to deactivate.",
+ );
+
+ const stale: { id: string; created: Date }[] = [];
+ let scanned = 0;
+ let skippedRecent = 0;
+
+ for await (const config of stripe.billingPortal.configurations.list({
+ active: true,
+ limit: 100,
+ })) {
+ scanned++;
+
+ if (config.business_profile?.headline !== SEAT_UPDATE_PORTAL_HEADLINE) {
+ continue; // not one of ours
+ }
+ if (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 (config.created * 1000 > cutoff) {
+ skippedRecent++;
+ continue; // created within the age guard window
+ }
+
+ stale.push({ id: config.id, created: new Date(config.created * 1000) });
+ }
+
+ console.info(
+ `\nScanned ${scanned} active configuration(s); ${stale.length} stale seat-update config(s) to deactivate` +
+ (skippedRecent ? ` (${skippedRecent} skipped by 24h age guard).` : "."),
+ );
+
+ if (stale.length === 0) {
+ console.info("✅ Nothing to clean up.");
+ return;
+ }
+
+ for (const config of stale) {
+ console.info(
+ `• ${config.id} (created ${config.created.toISOString().slice(0, 10)})`,
+ );
+ }
+
+ if (!apply) {
+ console.info(
+ "\n🔍 Dry run complete. Re-run with --apply to deactivate these configurations.",
+ );
+ return;
+ }
+
+ console.info("\n⚠️ Deactivating...\n");
+ let deactivated = 0;
+ let failed = 0;
+
+ for (const config of stale) {
+ try {
+ await stripe.billingPortal.configurations.update(config.id, {
+ active: false,
+ });
+ deactivated++;
+ } catch (error) {
+ console.error(
+ `❌ ${config.id}: ${error instanceof Error ? error.message : error}`,
+ );
+ failed++;
+ }
+ }
+
+ console.info(`\n📊 Done: ${deactivated} deactivated, ${failed} failed.`);
+})();