Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Fix legacy SaaS subscription visibility and billing access (#8107)

ConnorYohd4712cae02bf
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 33d3ac5edd..b7f57b6aaf 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -5644,6 +5644,26 @@ uploadFromComputer = "Browse files"
[language]
direction = "ltr"
+[legacyBilling]
+currentTeamAllowance = "Current allowance for your legacy team"
+loadError = "We couldn't check your existing subscription. Try again before purchasing another plan."
+loading = "Checking your subscription..."
+portalError = "We couldn't open Stripe billing. Please try again."
+pro = "Pro (legacy)"
+retry = "Try again"
+team = "Team (legacy)"
+teamUsers = "Your team: {{used}} of {{limit}} users"
+unlimitedUsers = "Your team: unlimited users ({{used}} in use)"
+usersUnavailable = "We couldn't confirm your team's user allowance. Contact support to check your legacy plan."
+
+[legacyBilling.status]
+active = "Active"
+incomplete = "Payment pending"
+past_due = "Payment overdue"
+paused = "Paused"
+trialing = "Trial"
+unpaid = "Unpaid"
+
[legal]
accessibility = "Accessibility"
cookie = "Cookie Policy"
diff --git a/frontend/editor/src/cloud/components/shared/config/configSections/Plan.tsx b/frontend/editor/src/cloud/components/shared/config/configSections/Plan.tsx
index ff34d9579e..0cbe8b1019 100644
--- a/frontend/editor/src/cloud/components/shared/config/configSections/Plan.tsx
+++ b/frontend/editor/src/cloud/components/shared/config/configSections/Plan.tsx
@@ -1,23 +1,11 @@
-/**
- * SaaS "Plan" page — the single entry point for billing, plan state, and
- * usage. Branches on the team's wallet state and the viewer's role:
- *
- * - free + leader → {@link PaygFreeLeader} (upgrade CTA + manual-tools
- * framing)
- * - free + member → {@link PaygFreeMember} (ask-the-owner note)
- * - subscribed + leader → {@link PaygLeader} (full dashboard, editable cap)
- * - subscribed + member → {@link PaygMember} (member dashboard)
- *
- * <p>The hook handles loading + error states locally so the four view
- * components stay focused on rendering the data they own. {@code Plan} is
- * intentionally tiny (under 60 lines) so future "Plan-level" affordances —
- * a top-level error toast, a subscription confirmation card, etc — have
- * obvious places to land.
- */
+/** Account-owned legacy billing can coexist with the current team's wallet. */
import React, { useCallback } from "react";
-import { Alert, Center, Loader } from "@mantine/core";
+import { Center, Group, Loader, Stack } from "@mantine/core";
+import { Banner, Button } from "@app/ui";
import { useTranslation } from "react-i18next";
import { useWallet } from "@app/hooks/useWallet";
+import { useLegacySubscriptions } from "@app/hooks/useLegacySubscriptions";
+import { LegacySubscriptionPlan } from "@app/components/shared/config/LegacySubscriptionPlan";
import { useRenderCount } from "@app/hooks/useRenderCount";
import {
PaygLeader,
@@ -31,6 +19,11 @@ import {
const Plan: React.FC = () => {
useRenderCount("Plan");
const { t } = useTranslation();
+ const legacyBilling = useLegacySubscriptions();
+ const hasLegacyBilling =
+ legacyBilling.loading ||
+ legacyBilling.loadError ||
+ legacyBilling.subscriptions.length > 0;
const { wallet, loading, error, markSubscribed, updateCap, openPortal } =
useWallet();
@@ -49,46 +42,76 @@ const Plan: React.FC = () => {
[markSubscribed],
);
- if (loading && !wallet) {
- return (
- <Center mih={200}>
- <Loader />
- </Center>
- );
- }
+ const renderWallet = () => {
+ if (loading && !wallet) {
+ return (
+ <Center mih={200}>
+ <Loader />
+ </Center>
+ );
+ }
- if (error || !wallet) {
- return (
- <Alert
- color="red"
- title={t("payg.error.title", "Couldn't load your plan")}
- >
- {error ??
- t(
- "payg.error.body",
- "We couldn't reach the billing service. Refresh the page to try again.",
- )}
- </Alert>
- );
- }
+ if (error || !wallet) {
+ return (
+ <Banner
+ tone="danger"
+ title={t("payg.error.title", "Couldn't load your plan")}
+ >
+ {error ??
+ t(
+ "payg.error.body",
+ "We couldn't reach the billing service. Refresh the page to try again.",
+ )}
+ </Banner>
+ );
+ }
+
+ if (wallet.status === "subscribed") {
+ return wallet.role === "leader" ? (
+ <PaygLeader
+ wallet={wallet}
+ onSaveCap={updateCap}
+ onOpenPortal={openPortal}
+ />
+ ) : (
+ <PaygMember wallet={wallet} />
+ );
+ }
+
+ if (hasLegacyBilling) return null;
- if (wallet.status === "subscribed") {
- return wallet.role === "leader" ? (
- <PaygLeader
- wallet={wallet}
- onSaveCap={updateCap}
- onOpenPortal={openPortal}
- />
- ) : (
- <PaygMember wallet={wallet} />
- );
- }
+ // Free tier — only the leader sees the upgrade CTA.
+ if (wallet.role === "leader") {
+ return <PaygFreeLeader onUpgraded={onUpgraded} />;
+ }
+ return <PaygFreeMember />;
+ };
- // Free tier — only the leader sees the upgrade CTA.
- if (wallet.role === "leader") {
- return <PaygFreeLeader onUpgraded={onUpgraded} />;
- }
- return <PaygFreeMember />;
+ return (
+ <Stack>
+ {legacyBilling.subscriptions.length > 0 && (
+ <Group justify="flex-end">
+ <Button
+ variant="secondary"
+ onClick={legacyBilling.openPortal}
+ disabled={legacyBilling.opening}
+ >
+ {t("payment.manageSubscription", "Manage subscription")}
+ </Button>
+ </Group>
+ )}
+ {legacyBilling.portalError && (
+ <Banner tone="danger">
+ {t(
+ "legacyBilling.portalError",
+ "We couldn't open Stripe billing. Please try again.",
+ )}
+ </Banner>
+ )}
+ <LegacySubscriptionPlan billing={legacyBilling} />
+ {renderWallet()}
+ </Stack>
+ );
};
export default Plan;
diff --git a/frontend/editor/src/core/components/shared/config/LegacySubscriptionPlan.tsx b/frontend/editor/src/core/components/shared/config/LegacySubscriptionPlan.tsx
new file mode 100644
index 0000000000..c1fcf65185
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/config/LegacySubscriptionPlan.tsx
@@ -0,0 +1,91 @@
+import { Stack, Text } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { Banner, Button } from "@app/ui";
+import type { LegacyBillingState } from "@app/types/legacyBilling";
+
+/** Displays owner billing without claiming that a legacy plan grants current product allowances. */
+export function LegacySubscriptionPlan({
+ billing,
+ walletTeamId,
+}: {
+ billing: LegacyBillingState;
+ /** The main billing screen renders this team's allowance in its Users row. */
+ walletTeamId?: number;
+}) {
+ const { t } = useTranslation();
+ if (billing.loading)
+ return (
+ <Text role="status">
+ {t("legacyBilling.loading", "Checking your subscription...")}
+ </Text>
+ );
+ if (billing.loadError) {
+ return (
+ <Banner
+ tone="warning"
+ action={
+ <Button onClick={billing.refresh}>
+ {t("legacyBilling.retry", "Try again")}
+ </Button>
+ }
+ >
+ {t(
+ "legacyBilling.loadError",
+ "We couldn't check your existing subscription. Try again before purchasing another plan.",
+ )}
+ </Banner>
+ );
+ }
+ if (!billing.subscriptions.length) return null;
+ const statusLabels = {
+ active: t("legacyBilling.status.active", "Active"),
+ trialing: t("legacyBilling.status.trialing", "Trial"),
+ past_due: t("legacyBilling.status.past_due", "Payment overdue"),
+ unpaid: t("legacyBilling.status.unpaid", "Unpaid"),
+ paused: t("legacyBilling.status.paused", "Paused"),
+ incomplete: t("legacyBilling.status.incomplete", "Payment pending"),
+ };
+ return (
+ <Stack gap="sm">
+ {billing.subscriptions.map((subscription) => (
+ <div key={subscription.id}>
+ <div className="billing-id">
+ <span className="billing-id__name">
+ {subscription.plan === "pro"
+ ? t("legacyBilling.pro", "Pro (legacy)")
+ : t("legacyBilling.team", "Team (legacy)")}
+ </span>
+ <span className="billing-id__sub">
+ {statusLabels[subscription.status]}
+ </span>
+ </div>
+ {subscription.plan === "team" &&
+ (!subscription.teamAllowance ||
+ subscription.teamId !== walletTeamId) && (
+ <Text size="sm">
+ {subscription.teamAllowance
+ ? subscription.teamAllowance.maxUsers == null
+ ? t(
+ "legacyBilling.unlimitedUsers",
+ "Your team: unlimited users ({{used}} in use)",
+ { used: subscription.teamAllowance.usersInUse },
+ )
+ : t(
+ "legacyBilling.teamUsers",
+ "Your team: {{used}} of {{limit}} users",
+ {
+ used: subscription.teamAllowance.usersInUse,
+ limit: subscription.teamAllowance.maxUsers,
+ },
+ )
+ : t(
+ "legacyBilling.usersUnavailable",
+ "We couldn't confirm your team's user allowance. Contact support to check your legacy plan.",
+ )}
+ </Text>
+ )}
+ </div>
+ ))}
+ </Stack>
+ );
+}
diff --git a/frontend/editor/src/core/hooks/useLegacySubscriptions.ts b/frontend/editor/src/core/hooks/useLegacySubscriptions.ts
new file mode 100644
index 0000000000..ab19041b78
--- /dev/null
+++ b/frontend/editor/src/core/hooks/useLegacySubscriptions.ts
@@ -0,0 +1,16 @@
+import type { LegacyBillingState } from "@app/types/legacyBilling";
+
+const empty: LegacyBillingState = {
+ subscriptions: [],
+ loading: false,
+ loadError: false,
+ opening: false,
+ portalError: false,
+ refresh: () => {},
+ openPortal: async () => {},
+};
+
+/** SaaS shadows this hook to expose the signed-in owner's historical billing. */
+export function useLegacySubscriptions(): LegacyBillingState {
+ return empty;
+}
diff --git a/frontend/editor/src/core/query/keys.ts b/frontend/editor/src/core/query/keys.ts
index a66540b285..b6b0f549ec 100644
--- a/frontend/editor/src/core/query/keys.ts
+++ b/frontend/editor/src/core/query/keys.ts
@@ -35,4 +35,7 @@ export const qk = {
toolRecommendations: (context: string, limit: number, completions: number) =>
["editor", "toolRecommendations", context, limit, completions] as const,
users: () => ["editor", "users"] as const,
+ /** Historical billing belongs to the account, independently of its current team. */
+ legacySubscriptions: (userId: string | null) =>
+ ["editor", "legacySubscriptions", userId] as const,
} as const;
diff --git a/frontend/editor/src/core/types/legacyBilling.ts b/frontend/editor/src/core/types/legacyBilling.ts
new file mode 100644
index 0000000000..bf6891eca0
--- /dev/null
+++ b/frontend/editor/src/core/types/legacyBilling.ts
@@ -0,0 +1,33 @@
+/** Historical subscriptions are billing records, not current wallet entitlements. */
+export interface LegacySubscription {
+ id: string;
+ plan: "pro" | "team";
+ status:
+ | "active"
+ | "trialing"
+ | "past_due"
+ | "unpaid"
+ | "paused"
+ | "incomplete";
+ currentPeriodEnd: string | null;
+ teamId: number | null;
+ teamAllowance: LegacyTeamAllowance | null;
+}
+
+/** The subscription's linked team as enforced by the backend; null maxUsers means unlimited. */
+export interface LegacyTeamAllowance {
+ teamId: number;
+ usersInUse: number;
+ maxUsers: number | null;
+}
+
+/** Account-owned billing; independent of the viewer's role in their current team. */
+export interface LegacyBillingState {
+ subscriptions: LegacySubscription[];
+ loading: boolean;
+ loadError: boolean;
+ opening: boolean;
+ portalError: boolean;
+ refresh: () => void;
+ openPortal: () => Promise<void>;
+}
diff --git a/frontend/editor/src/portal/views/Usage.test.tsx b/frontend/editor/src/portal/views/Usage.test.tsx
index 5aa6763675..dea337a1cc 100644
--- a/frontend/editor/src/portal/views/Usage.test.tsx
+++ b/frontend/editor/src/portal/views/Usage.test.tsx
@@ -21,6 +21,21 @@ import {
setTabHidden,
} from "@app/tests/utils/tabVisibility";
import type { ProcurementSnapshot } from "@app/portal/api/procurement";
+import type { LegacyBillingState } from "@app/types/legacyBilling";
+import { formatPeriodDate } from "@app/billing";
+
+const legacyBilling: LegacyBillingState = {
+ subscriptions: [],
+ loading: false,
+ loadError: false,
+ opening: false,
+ portalError: false,
+ refresh: vi.fn(),
+ openPortal: vi.fn(),
+};
+vi.mock("@app/hooks/useLegacySubscriptions", () => ({
+ useLegacySubscriptions: () => legacyBilling,
+}));
// Usage renders Mantine-backed @app/ui components (e.g. the "Manage Payment"
// Button in the subscribed header), which need a MantineProvider in the tree.
@@ -56,7 +71,14 @@ const renderUsage = (ui: ReactElement, entry = "/settings/billing") =>
</StrictMode>,
);
-const translate = (key: string, def?: string) => def ?? key;
+const translate = (
+ key: string,
+ def?: string,
+ values?: Record<string, unknown>,
+) =>
+ (def ?? key).replace(/\{\{(\w+)\}\}/g, (match, name) =>
+ values?.[name] == null ? match : String(values[name]),
+ );
vi.mock("react-i18next", () => ({
useTranslation: () => ({
@@ -180,6 +202,11 @@ describe("Usage — link-free wallet renderer", () => {
});
beforeEach(() => {
+ legacyBilling.subscriptions = [];
+ legacyBilling.loading = false;
+ legacyBilling.loadError = false;
+ legacyBilling.portalError = false;
+ vi.mocked(legacyBilling.openPortal).mockClear();
checkoutEnabled = false;
checkout.openCheckout.mockReset();
resetPortalSaasSessionState();
@@ -283,6 +310,214 @@ describe("Usage — link-free wallet renderer", () => {
);
});
+ it.each(["pro", "team"] as const)(
+ "shows the legacy %s owner's plan and billing even when their current team role is member",
+ async (plan) => {
+ legacyBilling.subscriptions = [
+ {
+ id: "sub_old",
+ plan,
+ status: "active",
+ currentPeriodEnd: "2026-10-12T00:00:00Z",
+ teamId: null,
+ teamAllowance: null,
+ },
+ ];
+ fetchWallet.mockResolvedValue(walletOf("free"));
+ renderUsage(<Usage />);
+ await screen.findByText(
+ plan === "pro" ? "Pro (legacy)" : "Team (legacy)",
+ );
+ await screen.findByText(formatPeriodDate("2026-10-12", { year: true }));
+ expect(
+ screen.getByText("Next invoice").closest("section"),
+ ).toHaveAttribute("id", "ub-pay");
+ expect(
+ screen.queryByText("Free", { exact: true }),
+ ).not.toBeInTheDocument();
+ fireEvent.click(
+ screen.getByRole("button", { name: "Manage subscription" }),
+ );
+ expect(
+ screen.getAllByRole("button", { name: "Manage subscription" }),
+ ).toHaveLength(1);
+ expect(
+ screen
+ .getByRole("button", { name: "Manage subscription" })
+ .closest(".billing-page__head"),
+ ).not.toBeNull();
+ expect(legacyBilling.openPortal).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it("keeps legacy billing available when the wallet cannot load", async () => {
+ legacyBilling.subscriptions = [
+ {
+ id: "sub_old",
+ plan: "pro",
+ status: "past_due",
+ currentPeriodEnd: null,
+ teamId: null,
+ teamAllowance: null,
+ },
+ ];
+ fetchWallet.mockRejectedValue(new Error("Wallet unavailable"));
+ renderUsage(<Usage />);
+ await screen.findByText("Wallet unavailable");
+ expect(screen.getByText("Payment overdue")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Manage subscription" }),
+ ).toBeEnabled();
+ });
+
+ it.each(["loading", "loadError"] as const)(
+ "does not label the owner Free when the legacy lookup is %s",
+ async (state) => {
+ legacyBilling[state] = true;
+ fetchWallet.mockResolvedValue(walletOf("free"));
+ const loaded = vi.fn();
+ renderUsage(<Usage onWalletLoaded={loaded} />);
+ await waitFor(() => expect(loaded).toHaveBeenCalled());
+ expect(
+ screen.queryByText("Free", { exact: true }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", {
+ name: "Manage subscription",
+ }),
+ ).not.toBeInTheDocument();
+ },
+ );
+
+ it("shows a current Processor holding alongside the legacy subscription", async () => {
+ legacyBilling.subscriptions = [
+ {
+ id: "sub_old",
+ plan: "team",
+ status: "active",
+ currentPeriodEnd: null,
+ teamId: null,
+ teamAllowance: null,
+ },
+ ];
+ fetchWallet.mockResolvedValue({
+ ...walletOf("subscribed"),
+ processor: { active: true },
+ });
+ renderUsage(<Usage />);
+ await screen.findByText("Processor", { selector: ".billing-id__name" });
+ expect(
+ screen.getByText("Team (legacy)", { selector: ".billing-id__name" }),
+ ).toBeInTheDocument();
+ });
+
+ it.each([
+ [1, 5, "1 of 5 users"],
+ [1, 8, "1 of 8 users"],
+ [12, 5, "1 of 12 users"],
+ [null, 5, "1 · Unlimited"],
+ ] as const)(
+ "preserves the included allowance or greater legacy Pro capacity (%s seats, %s included)",
+ async (maxUsers, freeUserAllowance, expectedFact) => {
+ legacyBilling.subscriptions = [
+ {
+ id: "sub_pro",
+ plan: "pro",
+ status: "active",
+ currentPeriodEnd: null,
+ teamId: 42,
+ teamAllowance: { teamId: 42, maxUsers, usersInUse: 1 },
+ },
+ ];
+ fetchWallet.mockResolvedValue({
+ ...walletOf("free"),
+ teamId: 42,
+ freeUserAllowance,
+ });
+ renderUsage(<Usage />);
+ await screen.findByText(expectedFact);
+ expect(screen.queryByText("1 of 1 users")).not.toBeInTheDocument();
+ expect(screen.getByText("Pro (legacy)")).toBeInTheDocument();
+ },
+ );
+
+ it.each([12, null])(
+ "uses the legacy team's recorded capacity (%s) instead of the free or new Team offer",
+ async (maxUsers) => {
+ legacyBilling.subscriptions = [
+ {
+ id: "sub_old",
+ plan: "team",
+ status: "active",
+ currentPeriodEnd: null,
+ teamId: 42,
+ teamAllowance: { teamId: 42, maxUsers, usersInUse: 3 },
+ },
+ ];
+ fetchWallet.mockResolvedValue({
+ ...walletOf("free"),
+ teamId: 42,
+ freeUserAllowance: 5,
+ });
+ renderUsage(<Usage />);
+ await screen.findByText("Current allowance for your legacy team");
+ expect(
+ screen.queryByText("The Team plan covers 100 users"),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText("1 of 5 users")).not.toBeInTheDocument();
+ expect(screen.queryByText("Add capacity")).not.toBeInTheDocument();
+ expect(
+ screen.getAllByText(
+ maxUsers == null ? "3 · Unlimited" : "3 of 12 users",
+ ).length,
+ ).toBeGreaterThan(0);
+ },
+ );
+
+ it("does not apply the legacy team's capacity to an unrelated wallet", async () => {
+ legacyBilling.subscriptions = [
+ {
+ id: "sub_old",
+ plan: "team",
+ status: "active",
+ currentPeriodEnd: null,
+ teamId: 99,
+ teamAllowance: { teamId: 99, maxUsers: null, usersInUse: 3 },
+ },
+ ];
+ fetchWallet.mockResolvedValue({
+ ...walletOf("free"),
+ teamId: 42,
+ freeUserAllowance: 5,
+ });
+ renderUsage(<Usage />);
+ await screen.findByText("1 of 5 users");
+ expect(
+ screen.queryByText("Current allowance for your legacy team"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("flags missing legacy team capacity without inventing an entitlement", async () => {
+ legacyBilling.subscriptions = [
+ {
+ id: "sub_old",
+ plan: "team",
+ status: "active",
+ currentPeriodEnd: null,
+ teamId: null,
+ teamAllowance: null,
+ },
+ ];
+ fetchWallet.mockResolvedValue(walletOf("free"));
+ renderUsage(<Usage />);
+ await screen.findByText(
+ "We couldn't confirm your team's user allowance. Contact support to check your legacy plan.",
+ );
+ expect(
+ screen.getByRole("button", { name: "Manage subscription" }),
+ ).toBeEnabled();
+ });
+
it("works with no callbacks (SaaS passes none)", async () => {
fetchWallet.mockResolvedValue(walletOf("subscribed"));
diff --git a/frontend/editor/src/portal/views/Usage.tsx b/frontend/editor/src/portal/views/Usage.tsx
index 38f0b8f895..cc1adc29b9 100644
--- a/frontend/editor/src/portal/views/Usage.tsx
+++ b/frontend/editor/src/portal/views/Usage.tsx
@@ -13,7 +13,9 @@ import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { useSearchParams } from "react-router-dom";
import { Banner, Button } from "@app/ui";
-import { BillingScreen } from "@app/billing";
+import { BillingScreen, KvRow, formatPeriodDate } from "@app/billing";
+import { useLegacySubscriptions } from "@app/hooks/useLegacySubscriptions";
+import { LegacySubscriptionPlan } from "@app/components/shared/config/LegacySubscriptionPlan";
import { useUI } from "@app/portal/contexts/UIContext";
import { useProcurement } from "@app/portal/components/procurement/useProcurement";
import { ControlledDealStatusHero } from "@app/portal/components/procurement/ProcurementBanner";
@@ -81,10 +83,10 @@ export function Usage({
renderLicenseSection,
}: UsageProps = {}) {
const { t } = useTranslation();
+ const legacyBilling = useLegacySubscriptions();
const queryClient = useQueryClient();
// The gate renders this page only for a linked instance.
const walletOptions = walletQuery(true);
- const walletKey = walletOptions.queryKey!;
const {
data: loadedWallet = null,
isPending: walletPending,
@@ -181,7 +183,7 @@ export function Usage({
return () => {
cancelled = true;
};
- }, [procurement.data]);
+ }, [procurement.data, refresh]);
// From fleet-stats, not the wallet. Null when the backend cannot compute it, which omits the row.
const { data: fleetStats } = useFleetStats();
const editorsDeployed = fleetStats?.editorsDeployed ?? null;
@@ -337,7 +339,7 @@ export function Usage({
const w = await fetchWallet();
if (!mounted.current) return false;
if (w.status === "subscribed") {
- queryClient.setQueryData(walletKey, w);
+ queryClient.setQueryData(qk.wallet(true), w);
// Nudge the local instance to refresh its gate now so billable work
// unblocks immediately rather than on its next poll. Fire-and-forget;
// a no-op on SaaS (no local instance to sync).
@@ -354,23 +356,57 @@ export function Usage({
// shows its "almost there" notice rather than the page silently self-healing.
refresh();
return false;
- }, [onWalletLoaded, hasLocalInstance]);
+ }, [queryClient, hasLocalInstance, refresh]);
const enterpriseProcessor = serverPlan?.licenseType === "ENTERPRISE";
const paying = Boolean(wallet?.processor?.active || wallet?.team?.held);
+ const ownsLegacySubscription = legacyBilling.subscriptions.length > 0;
+ const legacyTeamSubscription = legacyBilling.subscriptions.find(
+ (subscription) => subscription.teamId === wallet?.teamId,
+ );
+ const recordedLegacyAllowance = legacyTeamSubscription?.teamAllowance;
+ // A historical Pro personal team can record one seat; its first invitation grants the free allowance.
+ const legacyTeamAllowance =
+ recordedLegacyAllowance &&
+ legacyTeamSubscription?.plan === "pro" &&
+ recordedLegacyAllowance.maxUsers != null
+ ? {
+ ...recordedLegacyAllowance,
+ maxUsers: Math.max(
+ recordedLegacyAllowance.maxUsers,
+ wallet?.freeUserAllowance ?? 0,
+ ),
+ }
+ : recordedLegacyAllowance;
return (
<BillingScreen
+ legacyTeamAllowance={legacyTeamAllowance ?? undefined}
+ legacyPlan={
+ legacyBilling.loading ||
+ legacyBilling.loadError ||
+ legacyBilling.subscriptions.length ? (
+ <LegacySubscriptionPlan
+ billing={legacyBilling}
+ walletTeamId={wallet?.teamId ?? undefined}
+ />
+ ) : undefined
+ }
usersInUse={localUsersInUse}
userLimit={localUserLimit}
deviceId={accountLink?.status?.deviceId}
headerAction={
- !needsRenewal && paying && wallet?.role === "leader" ? (
+ !needsRenewal &&
+ (ownsLegacySubscription || (paying && wallet?.role === "leader")) ? (
<Button
fat
variant="secondary"
- onClick={portal.open}
- disabled={portal.opening}
+ onClick={
+ ownsLegacySubscription ? legacyBilling.openPortal : portal.open
+ }
+ disabled={
+ ownsLegacySubscription ? legacyBilling.opening : portal.opening
+ }
>
{t("payment.manageSubscription", "Manage subscription")}
</Button>
@@ -438,6 +474,20 @@ export function Usage({
{portal.error}
</Banner>
)}
+ {legacyBilling.portalError && (
+ <Banner
+ tone="danger"
+ title={t(
+ "portal.usage.error.openStripePortal",
+ "Couldn't open Stripe portal",
+ )}
+ >
+ {t(
+ "legacyBilling.portalError",
+ "We couldn't open Stripe billing. Please try again.",
+ )}
+ </Banner>
+ )}
</>
}
editorsDeployed={editorsDeployed}
@@ -488,13 +538,41 @@ export function Usage({
: undefined
}
paymentSection={
- paying && wallet ? (
- <PaymentSection
- pendingUnits={localUsage?.totalUnsyncedUnits ?? 0}
- wallet={wallet}
- onManage={wallet.role === "leader" ? portal.open : undefined}
- managing={portal.opening}
- />
+ paying || ownsLegacySubscription ? (
+ <>
+ {paying && wallet && (
+ <PaymentSection
+ pendingUnits={localUsage?.totalUnsyncedUnits ?? 0}
+ wallet={wallet}
+ onManage={wallet.role === "leader" ? portal.open : undefined}
+ managing={portal.opening}
+ />
+ )}
+ {legacyBilling.subscriptions.map((subscription) => (
+ <KvRow
+ key={subscription.id}
+ label={t("portal.billing.payment.nextInvoice", "Next invoice")}
+ note={
+ paying || legacyBilling.subscriptions.length > 1
+ ? subscription.plan === "pro"
+ ? t("legacyBilling.pro", "Pro (legacy)")
+ : t("legacyBilling.team", "Team (legacy)")
+ : undefined
+ }
+ value={
+ subscription.currentPeriodEnd &&
+ !Number.isNaN(Date.parse(subscription.currentPeriodEnd))
+ ? formatPeriodDate(subscription.currentPeriodEnd, {
+ year: true,
+ })
+ : t(
+ "portal.billing.payment.dateUnavailable",
+ "Billing date not available yet",
+ )
+ }
+ />
+ ))}
+ </>
) : undefined
}
invoicesSection={
diff --git a/frontend/editor/src/proprietary/billing/BillingScreen.tsx b/frontend/editor/src/proprietary/billing/BillingScreen.tsx
index ad240e6dd3..93d39f5513 100644
--- a/frontend/editor/src/proprietary/billing/BillingScreen.tsx
+++ b/frontend/editor/src/proprietary/billing/BillingScreen.tsx
@@ -10,6 +10,7 @@ import { estimatedBillWithPending } from "@app/billing/pendingUsage";
import { fleetUsersInUse } from "@app/billing/fleetSeats";
import type { ServerPlan } from "@app/billing/serverPlan";
import type { Wallet } from "@app/billing/types";
+import type { LegacyTeamAllowance } from "@app/types/legacyBilling";
import "@app/billing/billing-screen.css";
export interface BillingScreenProps {
@@ -21,6 +22,10 @@ export interface BillingScreenProps {
deviceId?: string | null;
/** Host-authorized account actions beside the page title. */
headerAction?: ReactNode;
+ /** Account-owned historical subscriptions, independent of current wallet products. */
+ legacyPlan?: ReactNode;
+ /** Raw legacy capacity retains historical unlimited limits that wallet products omit. */
+ legacyTeamAllowance?: LegacyTeamAllowance;
/**
* Null while loading, or when the host could not read one. A non-null wallet must be complete:
* the sections dereference its fields without guards, so a hand-built partial object throws
@@ -97,6 +102,8 @@ export function BillingScreen({
userLimit,
deviceId,
headerAction,
+ legacyPlan,
+ legacyTeamAllowance,
wallet,
loading = false,
unavailable,
@@ -142,7 +149,7 @@ export function BillingScreen({
"ub-procurement",
t("portal.billing.chip.procurement", "Procurement"),
]);
- if (wallet || serverPlan || unavailable)
+ if (wallet || serverPlan || legacyPlan || unavailable)
out.push(["ub-plan", t("portal.billing.chip.plan", "Plan")]);
if (wallet || unavailable)
out.push(["ub-usage", t("portal.billing.chip.usage", "Usage")]);
@@ -159,6 +166,7 @@ export function BillingScreen({
}, [
wallet,
serverPlan,
+ legacyPlan,
unavailable,
procurementSection,
licenseSection,
@@ -210,7 +218,10 @@ export function BillingScreen({
],
};
}
- if (teamHeld) {
+ if (
+ teamHeld &&
+ (!legacyTeamAllowance || legacyTeamAllowance.teamId !== wallet.teamId)
+ ) {
return {
name: t("portal.billing.identity.team.name", "Team"),
sub:
@@ -232,6 +243,7 @@ export function BillingScreen({
],
};
}
+ if (legacyPlan) return null;
return {
name: t("portal.billing.identity.free.name", "Free"),
sub: t("portal.billing.identity.free.sub", "The full PDF Editor."),
@@ -250,7 +262,15 @@ export function BillingScreen({
),
],
};
- }, [wallet, paying, teamHeld, serverPlan, t]);
+ }, [
+ wallet,
+ paying,
+ teamHeld,
+ serverPlan,
+ legacyPlan,
+ legacyTeamAllowance,
+ t,
+ ]);
const creditUnits = (wallet?.spendUnitsThisPeriod ?? 0) + pendingUnits;
const occupiedSeats = serverPlan
@@ -300,7 +320,11 @@ export function BillingScreen({
</div>
)}
- {(procurementSection || licenseSection || identity || unavailable) && (
+ {(procurementSection ||
+ licenseSection ||
+ identity ||
+ legacyPlan ||
+ unavailable) && (
<div className="billing-card">
<nav
className="billing-card__chips"
@@ -328,31 +352,37 @@ export function BillingScreen({
</section>
)}
- {identity && (
+ {(identity || legacyPlan) && (
<>
<section id="ub-plan" className="billing-sec">
<span className="billing-eyebrow">
{t("portal.billing.section.plan", "Your plan")}
</span>
- <div className="billing-id">
- <span className="billing-id__name">{identity.name}</span>
- <span className="billing-id__sub">{identity.sub}</span>
- {serverPlanAction && (
- <div className="billing-id__action">
- {serverPlanAction}
- </div>
- )}
- </div>
- <div className="billing-id__chips">
- {identity.chips.map((c) => (
- <span key={c} className="billing-id__chip">
- {c}
- </span>
- ))}
- </div>
+ {legacyPlan}
+ {identity && (
+ <div className="billing-id">
+ <span className="billing-id__name">{identity.name}</span>
+ <span className="billing-id__sub">{identity.sub}</span>
+ {serverPlanAction && (
+ <div className="billing-id__action">
+ {serverPlanAction}
+ </div>
+ )}
+ </div>
+ )}
+ {identity && (
+ <div className="billing-id__chips">
+ {identity.chips.map((c) => (
+ <span key={c} className="billing-id__chip">
+ {c}
+ </span>
+ ))}
+ </div>
+ )}
<div className="billing-meters">
{(showTeam || serverPlan) && (
<TeamPlanRow
+ legacyAllowance={legacyTeamAllowance}
usersInUse={usersInUse}
userLimit={userLimit}
deviceId={deviceId}
diff --git a/frontend/editor/src/proprietary/billing/TeamPlanRow.tsx b/frontend/editor/src/proprietary/billing/TeamPlanRow.tsx
index a2f926b8a1..d0d51a38b9 100644
--- a/frontend/editor/src/proprietary/billing/TeamPlanRow.tsx
+++ b/frontend/editor/src/proprietary/billing/TeamPlanRow.tsx
@@ -4,6 +4,7 @@ import type { ServerPlan } from "@app/billing/serverPlan";
import type { Wallet } from "@app/billing/types";
import { SeatBreakdown } from "@app/billing/SeatBreakdown";
import { fleetUsersInUse } from "@app/billing/fleetSeats";
+import type { LegacyTeamAllowance } from "@app/types/legacyBilling";
/**
* The Team product, as a row: users against the capacity the plan covers.
@@ -22,6 +23,7 @@ export function TeamPlanRow({
usersInUse: occupiedSeats,
userLimit,
deviceId,
+ legacyAllowance,
}: {
wallet: Wallet | null;
serverPlan?: ServerPlan;
@@ -34,6 +36,8 @@ export function TeamPlanRow({
/** Used only for standalone servers; linked fleets show the full plan capacity. */
userLimit?: number | null;
deviceId?: string | null;
+ /** Applied only when the historical subscription belongs to the displayed wallet's team. */
+ legacyAllowance?: LegacyTeamAllowance;
}) {
const { t } = useTranslation();
if (serverPlan) {
@@ -77,6 +81,31 @@ export function TeamPlanRow({
);
}
if (!wallet) return null;
+ if (legacyAllowance && legacyAllowance.teamId === wallet.teamId) {
+ const { usersInUse, maxUsers } = legacyAllowance;
+ return (
+ <MeterRow
+ name={t("portal.billing.team.rowName", "Users")}
+ mid={t(
+ "legacyBilling.currentTeamAllowance",
+ "Current allowance for your legacy team",
+ )}
+ showTrack={maxUsers != null && maxUsers > 0}
+ pct={maxUsers ? (usersInUse / maxUsers) * 100 : 0}
+ tone="paid"
+ fact={
+ maxUsers == null
+ ? t("portal.users.seats.unlimited", "{{used}} · Unlimited", {
+ used: usersInUse,
+ })
+ : t("portal.billing.team.fact", "{{users}} of {{licensed}} users", {
+ users: usersInUse,
+ licensed: maxUsers,
+ })
+ }
+ />
+ );
+ }
const { held, licensedUsers } = wallet.team;
const usersInUse = wallet.team.fleet
? fleetUsersInUse(wallet.team, deviceId, occupiedSeats)
diff --git a/frontend/editor/src/saas/hooks/useLegacySubscriptions.test.tsx b/frontend/editor/src/saas/hooks/useLegacySubscriptions.test.tsx
new file mode 100644
index 0000000000..15f5ebf2d0
--- /dev/null
+++ b/frontend/editor/src/saas/hooks/useLegacySubscriptions.test.tsx
@@ -0,0 +1,279 @@
+import {
+ act,
+ cleanup,
+ renderHook as baseRenderHook,
+ waitFor,
+} from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { QueryClientProvider, type QueryClient } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { useLegacySubscriptions } from "@app/hooks/useLegacySubscriptions";
+import type { LegacySubscription } from "@app/types/legacyBilling";
+import { createAppQueryClient } from "@app/query/queryClient";
+import { qk } from "@app/query/keys";
+import {
+ resetTabVisibility,
+ setTabHidden,
+} from "@app/tests/utils/tabVisibility";
+
+let client: QueryClient;
+
+function renderHook<T>(callback: () => T) {
+ return baseRenderHook(callback, {
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ ),
+ });
+}
+
+let user: { id: string; is_anonymous?: boolean } | null;
+let authLoading = false;
+const fetchSubscriptions = vi.fn();
+const portal = vi.fn();
+const navigate = vi.fn();
+vi.mock("@app/auth/UseSession", () => ({
+ useAuth: () => ({ user, loading: authLoading }),
+}));
+vi.mock("@app/services/legacyBilling", () => ({
+ fetchLegacySubscriptions: (...args: unknown[]) => fetchSubscriptions(...args),
+ createLegacyPortalSession: () => portal(),
+}));
+vi.mock("@app/platform/openExternal", () => ({
+ openExternal: (...args: unknown[]) => navigate(...args),
+}));
+const subscription: LegacySubscription = {
+ id: "sub_1",
+ plan: "pro",
+ status: "active",
+ currentPeriodEnd: null,
+ teamId: null,
+ teamAllowance: null,
+};
+
+describe("legacy billing ownership", () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ client = createAppQueryClient();
+ user = { id: "owner" };
+ authLoading = false;
+ fetchSubscriptions.mockResolvedValue([subscription]);
+ portal.mockResolvedValue("https://billing.stripe.com/p/session/test");
+ });
+
+ afterEach(() => {
+ cleanup();
+ client.clear();
+ resetTabVisibility();
+ vi.useRealTimers();
+ });
+
+ it("waits for authentication before deciding that the account has no subscription", () => {
+ user = null;
+ authLoading = true;
+ const { result } = renderHook(() => useLegacySubscriptions());
+ expect(result.current.loading).toBe(true);
+ expect(fetchSubscriptions).not.toHaveBeenCalled();
+ });
+
+ it("does not query billing or mint a portal for anonymous users", async () => {
+ user = { id: "guest", is_anonymous: true };
+ const { result } = renderHook(() => useLegacySubscriptions());
+ await act(() => result.current.openPortal());
+ expect(fetchSubscriptions).not.toHaveBeenCalled();
+ expect(portal).not.toHaveBeenCalled();
+ });
+
+ it("discards the previous owner's records when accounts change during a request", async () => {
+ let resolveOwner!: (value: LegacySubscription[]) => void;
+ fetchSubscriptions.mockImplementationOnce(
+ () =>
+ new Promise<LegacySubscription[]>((resolve) => {
+ resolveOwner = resolve;
+ }),
+ );
+ const { result, rerender } = renderHook(() => useLegacySubscriptions());
+ user = { id: "other" };
+ fetchSubscriptions.mockResolvedValue([]);
+ rerender();
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ await act(async () => resolveOwner([subscription]));
+ expect(result.current.subscriptions).toEqual([]);
+ await act(() => result.current.openPortal());
+ expect(portal).not.toHaveBeenCalled();
+ });
+
+ it("refreshes after returning from Stripe and removes ended subscriptions", async () => {
+ const { result } = renderHook(() => useLegacySubscriptions());
+ await waitFor(() =>
+ expect(result.current.subscriptions).toEqual([subscription]),
+ );
+ await act(() => result.current.openPortal());
+ expect(navigate).toHaveBeenCalledWith(
+ "https://billing.stripe.com/p/session/test",
+ );
+ fetchSubscriptions.mockResolvedValue([]);
+ act(() => {
+ setTabHidden(true);
+ setTabHidden(false);
+ });
+ await waitFor(() => expect(result.current.subscriptions).toEqual([]));
+ });
+
+ it("exposes a retryable lookup failure without claiming the owner has a free plan", async () => {
+ fetchSubscriptions.mockRejectedValueOnce(new Error("Offline"));
+ const { result } = renderHook(() => useLegacySubscriptions());
+ await waitFor(() => expect(result.current.loadError).toBe(true));
+ fetchSubscriptions.mockResolvedValue([subscription]);
+ act(() => result.current.refresh());
+ await waitFor(() =>
+ expect(result.current.subscriptions).toEqual([subscription]),
+ );
+ expect(result.current.loadError).toBe(false);
+ portal.mockRejectedValueOnce(new Error("Stripe unavailable"));
+ await act(() => result.current.openPortal());
+ expect(result.current.portalError).toBe(true);
+ expect(navigate).not.toHaveBeenCalled();
+ });
+
+ it("shares the in-flight lookup and fresh cache across consumers and remounts", async () => {
+ const first = renderHook(() => useLegacySubscriptions());
+ const second = renderHook(() => useLegacySubscriptions());
+ await waitFor(() =>
+ expect(second.result.current.subscriptions).toEqual([subscription]),
+ );
+ expect(first.result.current.subscriptions).toEqual([subscription]);
+ expect(fetchSubscriptions).toHaveBeenCalledTimes(1);
+ first.unmount();
+ second.unmount();
+ const remounted = renderHook(() => useLegacySubscriptions());
+ expect(remounted.result.current.subscriptions).toEqual([subscription]);
+ expect(remounted.result.current.loading).toBe(false);
+ await act(async () => {});
+ expect(fetchSubscriptions).toHaveBeenCalledTimes(1);
+ });
+
+ it("hides cached records when authentication is pending or the owner signs out", async () => {
+ const { result, rerender } = renderHook(() => useLegacySubscriptions());
+ await waitFor(() =>
+ expect(result.current.subscriptions).toEqual([subscription]),
+ );
+ authLoading = true;
+ rerender();
+ expect(result.current.subscriptions).toEqual([]);
+ expect(result.current.loading).toBe(true);
+ act(() => result.current.refresh());
+ await act(() => result.current.openPortal());
+ expect(fetchSubscriptions).toHaveBeenCalledTimes(1);
+ expect(portal).not.toHaveBeenCalled();
+ user = null;
+ authLoading = false;
+ rerender();
+ expect(result.current.subscriptions).toEqual([]);
+ expect(result.current.loading).toBe(false);
+ });
+
+ it("does not show one owner's cached plan to another owner", async () => {
+ const { result, rerender } = renderHook(() => useLegacySubscriptions());
+ await waitFor(() =>
+ expect(result.current.subscriptions).toEqual([subscription]),
+ );
+ fetchSubscriptions.mockResolvedValue([]);
+ user = { id: "other" };
+ rerender();
+ expect(result.current.subscriptions).toEqual([]);
+ expect(result.current.loading).toBe(true);
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.subscriptions).toEqual([]);
+ expect(fetchSubscriptions).toHaveBeenLastCalledWith("other");
+ });
+
+ it("ignores a portal response after the account changes", async () => {
+ let resolvePortal!: (url: string) => void;
+ portal.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolvePortal = resolve;
+ }),
+ );
+ const { result, rerender } = renderHook(() => useLegacySubscriptions());
+ await waitFor(() =>
+ expect(result.current.subscriptions).toEqual([subscription]),
+ );
+ let opening!: Promise<void>;
+ act(() => {
+ opening = result.current.openPortal();
+ });
+ user = { id: "other" };
+ fetchSubscriptions.mockResolvedValue([]);
+ rerender();
+ await act(async () => {
+ resolvePortal("https://billing.stripe.com/p/session/test");
+ await opening;
+ });
+ expect(navigate).not.toHaveBeenCalled();
+ expect(
+ client.getQueryState(qk.legacySubscriptions("owner"))?.isInvalidated,
+ ).toBe(false);
+ });
+
+ describe("query freshness", () => {
+ beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ });
+
+ it("does not refetch for window focus or a tab return while fresh", async () => {
+ const { result } = renderHook(() => useLegacySubscriptions());
+ await waitFor(() =>
+ expect(result.current.subscriptions).toEqual([subscription]),
+ );
+ await act(async () => {
+ for (let i = 0; i < 5; i++) window.dispatchEvent(new Event("focus"));
+ setTabHidden(true);
+ setTabHidden(false);
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(fetchSubscriptions).toHaveBeenCalledTimes(1);
+ });
+
+ it("pauses polling while hidden and refreshes a stale plan on return", async () => {
+ const { result } = renderHook(() => useLegacySubscriptions());
+ await waitFor(() =>
+ expect(result.current.subscriptions).toEqual([subscription]),
+ );
+ act(() => setTabHidden(true));
+ await act(() => vi.advanceTimersByTimeAsync(90_000));
+ expect(fetchSubscriptions).toHaveBeenCalledTimes(1);
+ fetchSubscriptions.mockResolvedValue([]);
+ act(() => setTabHidden(false));
+ await waitFor(() => expect(result.current.subscriptions).toEqual([]));
+ expect(fetchSubscriptions).toHaveBeenCalledTimes(2);
+ });
+
+ it("keeps the plan visible during a background refresh and a failed poll", async () => {
+ const { result } = renderHook(() => useLegacySubscriptions());
+ await waitFor(() =>
+ expect(result.current.subscriptions).toEqual([subscription]),
+ );
+ let rejectPoll!: (reason: Error) => void;
+ fetchSubscriptions.mockImplementationOnce(
+ () =>
+ new Promise((_, reject) => {
+ rejectPoll = reject;
+ }),
+ );
+ await act(() => vi.advanceTimersByTimeAsync(30_000));
+ expect(fetchSubscriptions).toHaveBeenCalledTimes(2);
+ expect(result.current.subscriptions).toEqual([subscription]);
+ expect(result.current.loading).toBe(false);
+ await act(async () => {
+ rejectPoll(new Error("Offline"));
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(result.current.subscriptions).toEqual([subscription]);
+ expect(result.current.loadError).toBe(false);
+ fetchSubscriptions.mockResolvedValue([]);
+ await act(() => vi.advanceTimersByTimeAsync(30_000));
+ await waitFor(() => expect(result.current.subscriptions).toEqual([]));
+ });
+ });
+});
diff --git a/frontend/editor/src/saas/hooks/useLegacySubscriptions.ts b/frontend/editor/src/saas/hooks/useLegacySubscriptions.ts
new file mode 100644
index 0000000000..2e64f8d042
--- /dev/null
+++ b/frontend/editor/src/saas/hooks/useLegacySubscriptions.ts
@@ -0,0 +1,70 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { skipToken, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useAuth } from "@app/auth/UseSession";
+import { openExternal } from "@app/platform/openExternal";
+import { qk } from "@app/query/keys";
+import {
+ createLegacyPortalSession,
+ fetchLegacySubscriptions,
+} from "@app/services/legacyBilling";
+import type { LegacyBillingState } from "@app/types/legacyBilling";
+
+const REFRESH_INTERVAL_MS = 30_000;
+
+/** Keeps historical billing separate from wallet allowances and current team membership. */
+export function useLegacySubscriptions(): LegacyBillingState {
+ const { user, loading: authLoading } = useAuth();
+ const userId = !authLoading && user && !user.is_anonymous ? user.id : null;
+ const queryClient = useQueryClient();
+ const { data, isPending, isError, refetch } = useQuery({
+ queryKey: qk.legacySubscriptions(userId),
+ queryFn: userId ? () => fetchLegacySubscriptions(userId) : skipToken,
+ staleTime: REFRESH_INTERVAL_MS,
+ refetchInterval: REFRESH_INTERVAL_MS,
+ refetchOnWindowFocus: true,
+ retry: false,
+ });
+ const [opening, setOpening] = useState(false);
+ const [portalError, setPortalError] = useState(false);
+ const currentUser = useRef(userId);
+ currentUser.current = userId;
+ const refresh = useCallback(() => {
+ if (userId) void refetch();
+ }, [userId, refetch]);
+
+ useEffect(() => {
+ setPortalError(false);
+ }, [userId]);
+
+ const subscriptions = userId ? (data ?? []) : [];
+ const openPortal = async () => {
+ if (!userId || !subscriptions.length || opening) return;
+ setOpening(true);
+ setPortalError(false);
+ try {
+ const url = await createLegacyPortalSession();
+ if (currentUser.current === userId) {
+ // A return from Stripe must revalidate even inside the normal freshness window.
+ await queryClient.invalidateQueries({
+ queryKey: qk.legacySubscriptions(userId),
+ refetchType: "none",
+ });
+ if (currentUser.current === userId) await openExternal(url);
+ }
+ } catch {
+ if (currentUser.current === userId) setPortalError(true);
+ } finally {
+ setOpening(false);
+ }
+ };
+
+ return {
+ subscriptions,
+ loading: authLoading || Boolean(userId && isPending),
+ loadError: Boolean(userId && isError && data === undefined),
+ opening,
+ portalError,
+ refresh,
+ openPortal,
+ };
+}
diff --git a/frontend/editor/src/saas/services/legacyBilling.test.ts b/frontend/editor/src/saas/services/legacyBilling.test.ts
new file mode 100644
index 0000000000..b49c715781
--- /dev/null
+++ b/frontend/editor/src/saas/services/legacyBilling.test.ts
@@ -0,0 +1,163 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ createLegacyPortalSession,
+ fetchLegacySubscriptions,
+} from "@app/services/legacyBilling";
+
+const query = {
+ select: vi.fn(),
+ eq: vi.fn(),
+ in: vi.fn(),
+ order: vi.fn(),
+ returns: vi.fn(),
+};
+const from = vi.fn();
+const invoke = vi.fn();
+const getTeam = vi.fn();
+vi.mock("@app/services/apiClient", () => ({
+ default: { get: (...args: unknown[]) => getTeam(...args) },
+}));
+vi.mock("@app/auth/supabase", () => ({
+ supabase: {
+ from: (...args: unknown[]) => from(...args),
+ functions: { invoke: (...args: unknown[]) => invoke(...args) },
+ },
+}));
+
+describe("legacy billing", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ from.mockReturnValue(query);
+ for (const method of [query.select, query.eq, query.in, query.order])
+ method.mockReturnValue(query);
+ });
+
+ it("scopes the query to the owner and both exact historical prices, excluding ended and unrelated subscriptions", async () => {
+ const row = {
+ id: "sub_1",
+ price_id: "price_1SBckcP9mY5IAnSneeH0TJHs",
+ status: "active",
+ current_period_end: "2026-10-01T00:00:00Z",
+ team_id: null,
+ };
+ query.returns.mockResolvedValue({
+ data: [
+ row,
+ {
+ ...row,
+ id: "sub_2",
+ price_id: "price_1SzFCEP9mY5IAnSno62u0Tti",
+ status: "past_due",
+ },
+ { ...row, id: "sub_cancelled", status: "canceled" },
+ { ...row, id: "sub_other", price_id: "price_current_team" },
+ ],
+ error: null,
+ });
+ const subscriptions = await fetchLegacySubscriptions("owner-id");
+ expect(from).toHaveBeenCalledWith("billing_subscriptions");
+ expect(query.eq).toHaveBeenCalledWith("user_id", "owner-id");
+ expect(query.in).toHaveBeenCalledWith("price_id", [
+ "price_1SBckcP9mY5IAnSneeH0TJHs",
+ "price_1SzFCEP9mY5IAnSno62u0Tti",
+ ]);
+ expect(query.in).toHaveBeenCalledWith("status", [
+ "active",
+ "trialing",
+ "past_due",
+ "unpaid",
+ "paused",
+ "incomplete",
+ ]);
+ expect(subscriptions.map((s) => [s.id, s.plan, s.status])).toEqual([
+ ["sub_1", "pro", "active"],
+ ["sub_2", "team", "past_due"],
+ ]);
+ expect(subscriptions[0].currentPeriodEnd).toBe(row.current_period_end);
+ expect(getTeam).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [12, 12],
+ [2147483647, null],
+ ])(
+ "reads the linked team's %s-user allowance without falling back to five",
+ async (maxSeats, expectedLimit) => {
+ query.returns.mockResolvedValue({
+ data: [
+ {
+ id: "sub_team",
+ price_id: "price_1SzFCEP9mY5IAnSno62u0Tti",
+ status: "active",
+ current_period_end: null,
+ team_id: 42,
+ },
+ ],
+ error: null,
+ });
+ getTeam.mockResolvedValue({
+ data: { teamId: 42, maxSeats, seatsUsed: 3 },
+ });
+ const [subscription] = await fetchLegacySubscriptions("owner-id");
+ expect(getTeam).toHaveBeenCalledWith("/api/v1/team/42", {
+ suppressErrorToast: true,
+ });
+ expect(subscription.teamAllowance).toEqual({
+ teamId: 42,
+ maxUsers: expectedLimit,
+ usersInUse: 3,
+ });
+ },
+ );
+
+ it("keeps billing available when linked team capacity cannot be read", async () => {
+ query.returns.mockResolvedValue({
+ data: [
+ {
+ id: "sub_team",
+ price_id: "price_1SzFCEP9mY5IAnSno62u0Tti",
+ status: "active",
+ current_period_end: null,
+ team_id: 42,
+ },
+ ],
+ error: null,
+ });
+ getTeam.mockRejectedValue(new Error("Forbidden"));
+ const [subscription] = await fetchLegacySubscriptions("owner-id");
+ expect(subscription.id).toBe("sub_team");
+ expect(subscription.teamAllowance).toBeNull();
+ });
+
+ it("surfaces a failed lookup instead of returning an empty subscription list", async () => {
+ query.returns.mockResolvedValue({
+ data: null,
+ error: new Error("RLS unavailable"),
+ });
+ await expect(fetchLegacySubscriptions("owner-id")).rejects.toThrow(
+ "RLS unavailable",
+ );
+ });
+
+ it("lets the authenticated edge function choose the customer, without sending a team or customer id", async () => {
+ invoke.mockResolvedValue({
+ data: { url: "https://billing.stripe.com/p/session/test" },
+ error: null,
+ });
+ await expect(createLegacyPortalSession()).resolves.toBe(
+ "https://billing.stripe.com/p/session/test",
+ );
+ expect(invoke).toHaveBeenCalledWith("manage-billing", {
+ body: { return_url: window.location.href },
+ });
+ });
+
+ it.each([
+ null,
+ { url: "https://example.com" },
+ { url: "javascript:alert(1)" },
+ ])("rejects a missing or invalid portal URL (%j)", async (data) => {
+ invoke.mockResolvedValue({ data, error: null });
+ await expect(createLegacyPortalSession()).rejects.toThrow();
+ });
+});
diff --git a/frontend/editor/src/saas/services/legacyBilling.ts b/frontend/editor/src/saas/services/legacyBilling.ts
new file mode 100644
index 0000000000..16442e8b6d
--- /dev/null
+++ b/frontend/editor/src/saas/services/legacyBilling.ts
@@ -0,0 +1,125 @@
+import { supabase } from "@app/auth/supabase";
+import apiClient from "@app/services/apiClient";
+import type {
+ LegacySubscription,
+ LegacyTeamAllowance,
+} from "@app/types/legacyBilling";
+
+const plans: Record<string, LegacySubscription["plan"]> = {
+ price_1SBckcP9mY5IAnSneeH0TJHs: "pro",
+ price_1SzFCEP9mY5IAnSno62u0Tti: "team",
+};
+const statuses: LegacySubscription["status"][] = [
+ "active",
+ "trialing",
+ "past_due",
+ "unpaid",
+ "paused",
+ "incomplete",
+];
+
+interface SubscriptionRow {
+ id: string;
+ price_id: string;
+ status: LegacySubscription["status"];
+ current_period_end: string | null;
+ team_id: number | null;
+}
+
+async function fetchTeamAllowance(
+ teamId: number,
+): Promise<LegacyTeamAllowance | null> {
+ try {
+ const { data } = await apiClient.get<{
+ teamId: number;
+ maxSeats: number;
+ seatsUsed: number;
+ }>(`/api/v1/team/${teamId}`, { suppressErrorToast: true });
+ if (
+ data.teamId !== teamId ||
+ !Number.isSafeInteger(data.maxSeats) ||
+ data.maxSeats < 1 ||
+ !Number.isSafeInteger(data.seatsUsed) ||
+ data.seatsUsed < 0
+ )
+ return null;
+ return {
+ teamId,
+ usersInUse: data.seatsUsed,
+ maxUsers: data.maxSeats >= 2147483647 ? null : data.maxSeats,
+ };
+ } catch {
+ return null;
+ }
+}
+
+/** Reads only this owner's known legacy prices; Supabase RLS also enforces ownership. */
+export async function fetchLegacySubscriptions(
+ userId: string,
+): Promise<LegacySubscription[]> {
+ const { data, error } = await supabase
+ .from("billing_subscriptions")
+ .select("id, price_id, status, current_period_end, team_id")
+ .eq("user_id", userId)
+ .in("price_id", Object.keys(plans))
+ .in("status", statuses)
+ .order("created_at", { ascending: true })
+ .returns<SubscriptionRow[]>();
+ if (error) throw error;
+ const subscriptions: LegacySubscription[] = (data ?? []).flatMap((row) => {
+ const plan = plans[row.price_id];
+ return plan && statuses.includes(row.status)
+ ? [
+ {
+ id: row.id,
+ plan,
+ status: row.status,
+ currentPeriodEnd: row.current_period_end,
+ teamId:
+ typeof row.team_id === "number" &&
+ Number.isSafeInteger(row.team_id) &&
+ row.team_id > 0
+ ? row.team_id
+ : null,
+ teamAllowance: null,
+ },
+ ]
+ : [];
+ });
+ const teamIds = [
+ ...new Set(
+ subscriptions.flatMap((subscription) =>
+ subscription.teamId == null ? [] : [subscription.teamId],
+ ),
+ ),
+ ];
+ const allowances = new Map(
+ await Promise.all(
+ teamIds.map(
+ async (teamId) => [teamId, await fetchTeamAllowance(teamId)] as const,
+ ),
+ ),
+ );
+ return subscriptions.map((subscription) => ({
+ ...subscription,
+ teamAllowance:
+ subscription.teamId == null
+ ? null
+ : (allowances.get(subscription.teamId) ?? null),
+ }));
+}
+
+/** The edge function resolves the legacy Stripe customer from the session JWT. */
+export async function createLegacyPortalSession(): Promise<string> {
+ const { data, error } = await supabase.functions.invoke<{ url?: string }>(
+ "manage-billing",
+ { body: { return_url: window.location.href } },
+ );
+ if (error) throw error;
+ if (!data?.url) throw new Error("Missing Stripe billing portal URL");
+ const url = new URL(data.url);
+ if (url.protocol !== "https:" || url.hostname !== "billing.stripe.com") {
+ throw new Error("Invalid Stripe billing portal URL");
+ }
+ return url.href;
+}