From 1f2745acc56efd3f21d03d6a219ecaa5b1216ed1 Mon Sep 17 00:00:00 2001 From: Josh Zhang <39790535+jiashuoz@users.noreply.github.com> Date: Sun, 22 Nov 2026 10:17:05 -0800 Subject: [PATCH] fix(web): preserve billing behavior until sidecar changes ship --- web/src/app/(app)/billing/page.addon.test.tsx | 2 +- .../app/(app)/billing/page.catalog.test.tsx | 48 +------- web/src/app/(app)/billing/page.tsx | 115 +++--------------- 3 files changed, 23 insertions(+), 142 deletions(-) diff --git a/web/src/app/(app)/billing/page.addon.test.tsx b/web/src/app/(app)/billing/page.addon.test.tsx index 8270c4bde..f3b895b2a 100644 --- a/web/src/app/(app)/billing/page.addon.test.tsx +++ b/web/src/app/(app)/billing/page.addon.test.tsx @@ -488,7 +488,7 @@ describe("BillingPage — total-vs-delta clarity", () => { expect( screen.getByRole("button", { name: "Update to 2 add-ons" }), ).toBeInTheDocument(); - expect(screen.getByText(/At next renewal:/)).toHaveTextContent( + expect(screen.getByText(/New monthly total:/)).toHaveTextContent( "$4/mo (\u22121 add-on, \u2212$2/mo)", ); }); diff --git a/web/src/app/(app)/billing/page.catalog.test.tsx b/web/src/app/(app)/billing/page.catalog.test.tsx index 949be3e08..6f66ef423 100644 --- a/web/src/app/(app)/billing/page.catalog.test.tsx +++ b/web/src/app/(app)/billing/page.catalog.test.tsx @@ -106,7 +106,6 @@ beforeEach(() => { // unexpected error path doesn't surface a jsdom dialog. beforeAll(() => { window.alert = jest.fn(); - window.confirm = jest.fn(() => true); }); type StageOpts = { @@ -216,14 +215,14 @@ describe("BillingPage — tier comparison", () => { expect(screen.getByRole("button", { name: "Downgrade" })).toBeInTheDocument(); expect(screen.queryByRole("button", { name: /Switch to Pro|Upgrade/ })).not.toBeInTheDocument(); - // Existing plan changes use the controlled subscription-change endpoint. + // A switch routes to the Stripe portal (upgrade_url), not checkout. await userEvent.click(switchBtn); await waitFor(() => expect( - mockFetch.mock.calls.some(([u, i]) => u === CHECKOUT_URL && i?.method === "POST"), + mockFetch.mock.calls.some(([u, i]) => u === PORTAL_URL && i?.method === "POST"), ).toBe(true), ); - expect(mockFetch.mock.calls.some(([u]) => u === PORTAL_URL)).toBe(false); + expect(mockFetch.mock.calls.some(([u]) => u === CHECKOUT_URL)).toBe(false); }); it("offers no plan-change actions when the current plan can't be determined", async () => { @@ -255,44 +254,3 @@ describe("BillingPage — tier comparison", () => { expect(screen.queryByText("Scale")).not.toBeInTheDocument(); }); }); - - -describe("Stripe-owned pending changes", () => { - it("keeps the effective plan and billing management available while payment is pending", async () => { - stage({ limits: PRO_LIMITS, plan: { catalog: CATALOG, current: { - code: "pro", status: "active", has_stripe_customer: true, - change: { status: "payment_required", plan_code: "scale", addon_quantity: 0, url: "https://invoice.stripe.com/i/synthetic" }, - } } }); - renderPage(); - await screen.findByRole("button", {name: "Manage billing"}); - expect(screen.queryByText(/Payment is required to complete/)).not.toBeInTheDocument(); - expect(screen.queryByRole("link", {name: "Complete payment"})).not.toBeInTheDocument(); - expect(screen.getByRole("button", {name: "Manage billing"})).toBeEnabled(); - expect(screen.getByRole("button", {name: "Switch to Scale"})).toBeEnabled(); - await userEvent.click(screen.getByRole("button", {name: "Switch to Scale"})); - expect(mockFetch.mock.calls.some(([url, init]) => url === CHECKOUT_URL && JSON.parse(init.body).plan === "scale")).toBe(true); - expect(screen.getAllByText("Pro").length).toBeGreaterThan(0); - }); - it("explains a conflicting change only when selected and leaves it untouched if declined", async () => { - stage({ limits: PRO_LIMITS, plan: { catalog: CATALOG, current: { - code: "pro", status: "active", has_stripe_customer: true, - change: { status: "payment_required", plan_code: "scale", addon_quantity: 0 }, - } } }); - const confirm = jest.spyOn(window, "confirm").mockReturnValueOnce(false); - renderPage(); - await userEvent.click(await screen.findByRole("button", {name: "Downgrade"})); - expect(confirm).toHaveBeenCalledWith(expect.stringContaining("unfinished subscription change")); - expect(mockFetch.mock.calls.some(([, init]) => init?.method === "POST")).toBe(false); - confirm.mockReturnValue(true); - }); - it("shows a renewal change separately from current capacity and offers cancellation", async () => { - stage({ limits: PRO_LIMITS, plan: { catalog: CATALOG, current: { - code: "pro", status: "active", has_stripe_customer: true, - change: { status: "scheduled", plan_code: "free", addon_quantity: 0, effective_at: "2030-01-01T00:00:00Z" }, - } } }); - renderPage(); - expect(await screen.findByText(/Your subscription change is scheduled/)).toHaveTextContent("Your current plan and limits remain active"); - expect(screen.getByRole("button", {name: "Cancel pending change"})).toBeEnabled(); - expect(screen.queryByRole("link", {name: "Complete payment"})).not.toBeInTheDocument(); - }); -}); diff --git a/web/src/app/(app)/billing/page.tsx b/web/src/app/(app)/billing/page.tsx index 2f5011e5c..fb1870476 100644 --- a/web/src/app/(app)/billing/page.tsx +++ b/web/src/app/(app)/billing/page.tsx @@ -46,17 +46,7 @@ type PlanEntry = { max_storage_bytes: number; }; -type BillingChange = { - status: "payment_required" | "scheduled"; - url?: string; - effective_at?: string; - expires_at?: string; - plan_code?: string; - addon_quantity?: number; -}; - type CurrentState = { - change?: BillingChange; code: string; status: string; current_period_end?: string; @@ -325,30 +315,6 @@ export default function BillingPage() { // while the others disable. Tier CTAs are keyed `tier-`; the // banner's Manage-billing button is "manage". const [actionPending, setActionPending] = useState(null); - const [submittedChange, setSubmittedChange] = useState(null); - const planTargetRef = useRef(null); - const upcomingChange = planData?.current.change ?? submittedChange; - useEffect(() => { setSubmittedChange(null); }, [planData]); - - // Keep unfinished payments out of the normal page presentation. The same - // action resumes Stripe's existing invoice; a different action explains the - // conflict and lets the customer discard it before making a new request. - async function prepareChange(plan: string, quantity: number): Promise { - if (upcomingChange?.status !== "payment_required" || - (upcomingChange.plan_code === plan && upcomingChange.addon_quantity === quantity)) return true; - if (!window.confirm("You have an unfinished subscription change. Cancel it and continue with this change? Your current plan stays active.")) return false; - setActionPending("cancel-change"); - try { - const response = await fetch(`${BILLING_API}/api/billing/change/cancel`, { method: "POST", credentials: "include" }); - if (!response.ok) throw new Error("Could not cancel the unfinished change. Please retry."); - setSubmittedChange(null); - await mutatePlan(); - return true; - } catch (error) { - alert(error instanceof Error ? error.message : "Could not cancel the unfinished change."); - return false; - } finally { setActionPending(null); } - } // Both Upgrade and Manage Billing POST to the sidecar and follow the // returned `url`. POST (not GET) because the OSS session cookie is @@ -373,23 +339,11 @@ export default function BillingPage() { const text = await res.text().catch(() => ""); throw new Error(`HTTP ${res.status}${text ? `: ${text}` : ""}`); } - const json = (await res.json()) as { url?: string; updated?: boolean; status?: string } & Omit, "status">; - if (json.url) { - window.location.href = json.url; - return; + const json = (await res.json()) as { url?: string }; + if (!json.url) { + throw new Error("billing endpoint returned no url"); } - if (json.status === "scheduled") { - setSubmittedChange(json as BillingChange); - } else if (json.status === "applied" || json.updated) { - setSubmittedChange(null); - planTargetRef.current = (body as { plan?: string } | undefined)?.plan ?? null; - if (planTargetRef.current) setReconcile("pending"); - } else { - throw new Error("billing endpoint returned no change outcome"); - } - setActionPending(null); - void mutate(); - void mutatePlan(); + window.location.href = json.url; } catch (err) { // Best-effort recovery: surface the error to the user, clear // the pending state, and let them retry. We don't reset SWR @@ -485,7 +439,7 @@ export default function BillingPage() { // Webhook landed — stop polling and let the page render normally. useEffect(() => { - if (reconcile === "pending" && planData?.current.status === "active" && (!planTargetRef.current || planData.current.code === planTargetRef.current)) { + if (reconcile === "pending" && planData?.current.status === "active") { setReconcile("idle"); } }, [reconcile, planData]); @@ -562,7 +516,6 @@ export default function BillingPage() { async function applyAddon(target: number) { const addon = planData?.addon; if (!addon) return; - if (!(await prepareChange(planData?.current.code ?? "free", target))) return; // In-place increases charge the subscription immediately (prorated // by Stripe) with no hosted page in between — the one money action // on this page without a Stripe-owned review step. Make the total @@ -593,20 +546,13 @@ export default function BillingPage() { const text = await res.text().catch(() => ""); throw new Error(`HTTP ${res.status}${text ? `: ${text}` : ""}`); } - const json = (await res.json()) as { url?: string; updated?: boolean; status?: string } & Omit, "status">; + const json = (await res.json()) as { url?: string; updated?: boolean }; if (json.url) { // Keep the pending state through navigation, like postBilling. window.location.href = json.url; return; } - if (json.status === "scheduled") { - setSubmittedChange(json as BillingChange); - setAddonDesired(null); - setActionPending(null); - void mutatePlan(); - return; - } - if (json.updated || json.status === "applied") { + if (json.updated) { addonTargetRef.current = target; // Stamp a FRESH deadline here rather than relying on the sync // effect's `??=`: a second update issued while the first is @@ -659,27 +605,16 @@ export default function BillingPage() { return null; } if (hasSub) { - // Paid plan changes use Stripe pending updates/schedules through the - // sidecar. Cancellation to Free remains in the billing portal. + // Existing subscribers change or cancel their plan through the + // Stripe Billing Portal (it owns proration). Both "switch up/down" + // and "downgrade to Free" route there. const label = tier.monthly_price_cents <= 0 ? "Downgrade" : `Switch to ${tier.display_name}`; const key = `tier-${tier.code}`; return { label: actionPending === key ? "Opening…" : label, - onClick: async () => { - if (!(await prepareChange(tier.code, planData?.current.addon_quantity ?? 0))) return; - if (tier.monthly_price_cents <= 0) { - void postBilling(data!.upgrade_url, key); - return; - } - const current = planData?.catalog.find((p) => p.code === currentCode); - const increase = tier.monthly_price_cents > (current?.monthly_price_cents ?? 0); - const message = increase - ? `Switch to ${tier.display_name} (${formatPrice(tier.monthly_price_cents)})? The prorated difference is charged now. Your plan changes after payment succeeds.` - : `Switch to ${tier.display_name} at your next renewal? Your current plan remains available until then.`; - if (window.confirm(message)) void postBilling(`${BILLING_API}/api/billing/checkout`, key, { plan: tier.code }); - }, - disabled: actionPending !== null || (upcomingChange?.status === "scheduled"), + onClick: () => postBilling(data!.upgrade_url, key), + disabled: actionPending !== null, }; } // No subscription yet. The Free tier is already their plan (handled @@ -692,7 +627,7 @@ export default function BillingPage() { label: actionPending === key ? "Opening…" : `Upgrade to ${tier.display_name}`, onClick: () => postBilling(`${BILLING_API}/api/billing/checkout`, key, { plan: tier.code }), - disabled: actionPending !== null || (upcomingChange?.status === "scheduled"), + disabled: actionPending !== null, }; } @@ -752,18 +687,6 @@ export default function BillingPage() { )} - {upcomingChange?.status === "scheduled" && ( -
-

- {`Your subscription change is scheduled for ${upcomingChange.effective_at ? new Date(upcomingChange.effective_at).toLocaleDateString() : "your next renewal"}. Your current plan and limits remain active until then.`} -

- {upcomingChange.plan_code &&

Requested plan: {planData?.catalog.find((p) => p.code === upcomingChange.plan_code)?.display_name ?? upcomingChange.plan_code}{typeof upcomingChange.addon_quantity === "number" ? ` · ${upcomingChange.addon_quantity} inbox add-ons` : ""}

} - -
- )} - {/* Post-checkout reconciliation. Rendered outside the `data` gate so it shows even if the usage read is slow or failing — the user just paid, and silence is the worst response. A late webhook @@ -840,7 +763,7 @@ export default function BillingPage() { // upgrade_url present → user has an active Stripe // subscription. Clicking POSTs to the sidecar, which // returns a fresh Stripe Billing Portal URL. From the - // Portal, users manage cards, invoices and cancellation. + // Portal, users switch plans (Pro ↔ Scale) and cancel.