From 215857a744e463475a2d7f394bc488e93f15812a Mon Sep 17 00:00:00 2001 From: Hydra Date: Sat, 14 Nov 2026 20:12:49 +0200 Subject: [PATCH 1/2] fix(billing): recover checkout without blank tabs or duplicate spaces --- CHANGELOG.md | 6 + .../src/app/(dashboard)/providers.tsx | 3 +- .../components/actions/ActionBudget.test.tsx | 18 +-- .../src/components/actions/ActionBudget.tsx | 7 +- .../components/billing/CheckoutRecovery.tsx | 16 +-- .../components/billing/CloudPlanPicker.tsx | 25 ++-- .../billing/PendingCheckoutsContext.tsx | 37 ++++- .../billing/checkout-recovery.test.tsx | 28 ++-- .../billing/cloud-deploy-pricing.test.tsx | 14 +- .../billing/server-plan-picker.test.tsx | 126 ++++++++++++++---- .../src/components/billing/useCloudBilling.ts | 40 +++--- .../servers/managed/ManagedServerPurchase.tsx | 53 ++++++-- .../dashboard/src/components/sidebar.test.tsx | 49 ++++++- apps/dashboard/src/components/sidebar.tsx | 29 ++-- .../src/i18n/locales/en/billing.json | 2 +- apps/dashboard/src/lib/api/management.ts | 7 +- apps/dashboard/src/lib/billing-events.ts | 6 + .../src/lib/checkout-navigation.test.ts | 35 +++++ apps/dashboard/src/lib/checkout-navigation.ts | 28 ++-- docs/dashboard-design.md | 8 ++ 20 files changed, 388 insertions(+), 149 deletions(-) create mode 100644 apps/dashboard/src/lib/billing-events.ts create mode 100644 apps/dashboard/src/lib/checkout-navigation.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index dcd6b4bab..32daec4a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ Runtime security notices use the signed feed published from `security-advisories ## Unreleased +### Cloud billing + +- Open checkout only when its payment URL is ready, with a visible fallback button. + Recover unfinished Cloud purchases when reopening setup instead of creating duplicate + unpaid spaces. Show pending-plan warnings in the Plans & billing sidebar entry. + ### Backups - Back up verified existing empty Docker volumes and bind directories without blocking diff --git a/apps/dashboard/src/app/(dashboard)/providers.tsx b/apps/dashboard/src/app/(dashboard)/providers.tsx index e1407a0f6..c6c3d0e49 100644 --- a/apps/dashboard/src/app/(dashboard)/providers.tsx +++ b/apps/dashboard/src/app/(dashboard)/providers.tsx @@ -7,6 +7,7 @@ import { PlatformProvider } from "@/context/PlatformContext"; import { MailScopeProvider } from "@/context/MailScopeContext"; import { AuthProvider, type AuthUser } from "@/context/AuthContext"; import { ModalProvider } from "@/context/ModalContext"; +import { DashboardPaymentsProvider } from "@/components/billing/PendingCheckoutsContext"; import type { ProductView } from "@/lib/product-view"; interface DashboardProvidersProps { @@ -50,7 +51,7 @@ export function DashboardProviders({ // Modal content renders where its provider lives, even when opened by a // descendant. Keep dashboard dialogs inside their platform/auth/mail context; // the root layout's provider serves public screens outside this shell. - const content = {children}; + const content = {children}; return ( ({ checkout: vi.fn(), resume: vi.fn(), navigate: vi.fn(), - begin: vi.fn(), - closeTab: vi.fn(), closeDialog: vi.fn(), })); vi.mock("@/lib/api/billing", () => ({ @@ -28,10 +26,7 @@ vi.mock("@/lib/api/billing", () => ({ }, })); vi.mock("@/lib/checkout-navigation", () => ({ - beginCheckoutNavigation: (preserve: boolean) => { - h.begin(preserve); - return { navigate: h.navigate, close: h.closeTab }; - }, + navigateToCheckout: (url: string, preserve: boolean) => h.navigate(url, preserve), })); vi.mock("next/navigation", () => ({ useSearchParams: () => new URLSearchParams(h.query) })); vi.mock("@/lib/auth-client", () => ({ @@ -105,25 +100,24 @@ describe("Actions funding UI", () => { h.navigate.mockImplementation((url: string) => url); await render(true); await act(async () => button("Add $5").click()); - expect(h.begin).toHaveBeenCalledWith(true); - expect(h.begin.mock.invocationCallOrder[0]).toBeLessThan(h.checkout.mock.invocationCallOrder[0]!); + expect(h.navigate).toHaveBeenCalledWith(expect.any(String), true); expect(document.querySelector('a[href="https://checkout.stripe.com/saved"]')?.getAttribute("target")).toBe("_blank"); expect(h.closeDialog).not.toHaveBeenCalled(); await act(async () => button("Back to workflow").click()); expect(h.closeDialog).toHaveBeenCalledOnce(); }); - it("closes an unused payment tab on failure and does not expose an invalid payment link", async () => { + it("does not navigate on failure or expose an invalid payment link", async () => { h.budget.mockResolvedValue({ ...initial(), purchasesAvailable: true }); h.checkout.mockRejectedValueOnce(new Error("Provider unavailable")); await render(true); await act(async () => button("Add $5").click()); - expect(h.closeTab).toHaveBeenCalledOnce(); + expect(h.navigate).not.toHaveBeenCalled(); h.checkout.mockResolvedValue({ checkoutUrl: "javascript:invalid" }); h.navigate.mockImplementationOnce(() => { throw new Error("Invalid checkout URL"); }); await act(async () => button("Add $5").click()); expect(document.querySelector('a[href="javascript:invalid"]')).toBeNull(); - expect(h.closeTab).toHaveBeenCalledTimes(2); + expect(h.navigate).toHaveBeenCalledExactlyOnceWith("javascript:invalid", true); }); it("shows live VM estimates and one usage balance without a separate transfer allowance", async () => { @@ -223,7 +217,7 @@ describe("Actions funding UI", () => { await act(async () => button("Add $5").click()); await act(async () => button("Add $5").click()); expect(h.checkout.mock.calls[0]).toEqual(h.checkout.mock.calls[1]); - expect(h.navigate).toHaveBeenCalledWith("https://checkout.stripe.com/saved"); + expect(h.navigate).toHaveBeenCalledWith("https://checkout.stripe.com/saved", false); }); it("distinguishes a funded but paused budget from a balance that needs topping up", async () => { diff --git a/apps/dashboard/src/components/actions/ActionBudget.tsx b/apps/dashboard/src/components/actions/ActionBudget.tsx index 5fe5f8876..fb5659368 100644 --- a/apps/dashboard/src/components/actions/ActionBudget.tsx +++ b/apps/dashboard/src/components/actions/ActionBudget.tsx @@ -6,7 +6,7 @@ import { useSearchParams } from "next/navigation"; import { Icon } from "@repo/ui/icons"; import type { ActionBudget as BudgetData, ActionCreditPurchase } from "@repo/contracts"; import { billingApi } from "@/lib/api/billing"; -import { beginCheckoutNavigation } from "@/lib/checkout-navigation"; +import { navigateToCheckout } from "@/lib/checkout-navigation"; import { randomUUID } from "@/lib/random-uuid"; import { PageContainer } from "@/components/ui/PageContainer"; import { Button } from "@/components/ui/button"; @@ -72,7 +72,6 @@ function Budget({ onClose }: { onClose?: () => void }) { async function checkout(id?: string) { if (!data?.purchasesAvailable || mutation.busy) return; - const navigation = beginCheckoutNavigation(!!onClose); setCheckoutUrl(null); if (!attempts.current.has(deposit)) attempts.current.set(deposit, randomUUID()); const result = await mutation.execute(() => @@ -85,15 +84,13 @@ function Budget({ onClose }: { onClose?: () => void }) { ); if (result?.checkoutUrl) { const url = result.checkoutUrl; - const destination = await mutation.execute(async () => navigation.navigate(url)); + const destination = await mutation.execute(async () => navigateToCheckout(url, !!onClose)); if (destination) setCheckoutUrl(destination); - else navigation.close(); } else if (result && !id) { // A completed/expired intent is no longer a new deposit. A subsequent // explicit purchase gets its own key; uncertain responses keep this one. attempts.current.delete(deposit); } - if (!result?.checkoutUrl) navigation.close(); budget.refresh(); } diff --git a/apps/dashboard/src/components/billing/CheckoutRecovery.tsx b/apps/dashboard/src/components/billing/CheckoutRecovery.tsx index 5851f8c66..30467cccc 100644 --- a/apps/dashboard/src/components/billing/CheckoutRecovery.tsx +++ b/apps/dashboard/src/components/billing/CheckoutRecovery.tsx @@ -15,7 +15,8 @@ import { getApiErrorCode, getApiErrorMessage } from "@/lib/api/client"; import { useSession } from "@/lib/auth-client"; import { useCloudResourceKey } from "@/context/CloudResourceContext"; import { newServerBillingHref, scopedBillingHref } from "@/lib/billing-links"; -import { beginCheckoutNavigation } from "@/lib/checkout-navigation"; +import { navigateToCheckout } from "@/lib/checkout-navigation"; +import { invalidatePayments } from "@/lib/billing-events"; import { ManagedServerActionFeedback } from "@/components/servers/managed/ManagedServerActionFeedback"; import { useManagedServerActions } from "@/components/servers/managed/useManagedServerActions"; import { useBillingScope } from "./BillingWorkspaceContext"; @@ -244,33 +245,27 @@ function CheckoutRow({ setBusy(operation); setError(null); setConfirmCancel(false); - const navigation = operation === "resume" ? beginCheckoutNavigation(preserveProject) : null; if (operation === "cancel") setCancelAttempted(true); try { const response = await billingApi[ operation === "resume" ? "resumeCheckout" : "cancelCheckout" ]({ workspaceId: item.server.id, id: item.id }); - if (!mounted.current) { - navigation?.close(); - return; - } + if (!mounted.current) return; setResult(response); if (response.status === "ready") { - if (!response.checkoutUrl || !navigation) throw new Error(copy.actionError); - const url = navigation.navigate(response.checkoutUrl); + if (!response.checkoutUrl || operation !== "resume") throw new Error(copy.actionError); + const url = navigateToCheckout(response.checkoutUrl, preserveProject); if (preserveProject) { setCheckoutUrl(url); onCheckoutStarted?.(url); } void onRefresh(); } else { - navigation?.close(); setCheckoutUrl(null); if (response.status === "expired") onCleared?.(); router.refresh(); } } catch (err) { - navigation?.close(); if (!mounted.current) return; setError(getApiErrorMessage(err, copy.actionError)); if (getApiErrorCode(err) === "BILLING_CHECKOUT_CANCEL_UNAVAILABLE") setCancelAttempted(false); @@ -278,6 +273,7 @@ function CheckoutRow({ // Refresh reads persisted recovery state; it never starts another checkout. void onRefresh(); } finally { + if (mounted.current) invalidatePayments(); busyRef.current = false; if (mounted.current) setBusy(null); } diff --git a/apps/dashboard/src/components/billing/CloudPlanPicker.tsx b/apps/dashboard/src/components/billing/CloudPlanPicker.tsx index 1ba60de9e..d2f236ad1 100644 --- a/apps/dashboard/src/components/billing/CloudPlanPicker.tsx +++ b/apps/dashboard/src/components/billing/CloudPlanPicker.tsx @@ -13,7 +13,7 @@ import { useI18n } from "@/components/i18n-provider"; import type { BillingSubscription } from "@repo/contracts"; import type { BillingState } from "@/lib/api/billing"; import { needsCloudPlan } from "@/lib/billing-presentation"; -import { useCloudCheckout, useCloudPlans } from "./useCloudBilling"; +import { useCloudCheckout, useCloudPlans, type PreparedCheckoutWorkspace } from "./useCloudBilling"; import { useBillingWorkspace } from "./BillingWorkspaceContext"; import { CustomPlanConfigurator } from "./CustomPlanConfigurator"; import type { ApiPlan } from "./PricingCards"; @@ -86,7 +86,7 @@ function PlanPicker({ preserveProject?: boolean; onCheckoutStarted?: (checkoutUrl?: string) => void; /** New server acquisition resolves its identity only after choosing a plan. */ - prepareWorkspace?: () => Promise; + prepareWorkspace?: () => Promise; onWorkspaceRemoved?: (workspaceId: string) => void; purchaseDetails?: ReactNode; purchaseDisabled?: boolean; @@ -435,7 +435,7 @@ function PlanPicker({ currentOffer={currentOffer} subscription={subscription} allocatedDiskGb={allocatedDiskGb} - disabled={!selectable || purchaseDisabled || managing || (canPurchase && !referral.ready)} + disabled={!selectable || purchaseDisabled || managing || Boolean(checkoutUrl) || (canPurchase && !referral.ready)} busy={busy} actionLabel={canModify ? t.billing.planChange.review : undefined} quoteRevision={quoteRevision} @@ -454,7 +454,7 @@ function PlanPicker({ currentPlan={selectedCurrentPlan} onSelectPlan={handleSelectPlan} subscribingPlan={subscribing} - purchasesDisabled={!selectable || changes.busy || purchaseDisabled || managing || (canPurchase && !referral.ready)} + purchasesDisabled={!selectable || changes.busy || purchaseDisabled || managing || Boolean(checkoutUrl) || (canPurchase && !referral.ready)} selectionLabel={canModify ? t.billing.planChange.review : undefined} interval={interval} annualSavings={annualSavings} @@ -488,16 +488,13 @@ function PlanPicker({ export function CloudCheckoutNotice({ checkoutUrl }: { checkoutUrl: string }) { const { t } = useI18n(); return ( -
-

{t.billing.deployGate.checkoutOpened}

- - {t.billing.deployGate.continueCheckout} - +
+

{t.billing.deployGate.checkoutOpened}

+
); } diff --git a/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx b/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx index 25446098e..c591eac03 100644 --- a/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx +++ b/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx @@ -14,13 +14,19 @@ import { useResourceScope } from "@/hooks/use-scoped-resource"; import { useSession } from "@/lib/auth-client"; import { billingApi } from "@/lib/api/billing"; import { getApiErrorMessage } from "@/lib/api/client"; +import { managementApi } from "@/lib/api/management"; +import { subscriptionNeedsPayment } from "@/lib/billing-presentation"; +import { usePlatform } from "@/context/PlatformContext"; +import { useCloud } from "@/context/CloudContext"; import { useI18n } from "@/components/i18n-provider"; import { useBillingScope } from "./BillingWorkspaceContext"; +import { PAYMENTS_CHANGED } from "@/lib/billing-events"; type PendingCheckouts = { workspaceId?: string; items: BillingPendingCheckout[]; count: number; + attentionCount: number; loading: boolean; error: string | null; refresh: () => Promise; @@ -30,29 +36,43 @@ type PendingCheckouts = { const PendingCheckoutsContext = createContext(null); export const usePendingCheckouts = () => useContext(PendingCheckoutsContext); +/** One organization-wide payment read supplies the rail and billing hub. */ +export function DashboardPaymentsProvider({ children }: { children: ReactNode }) { + const { selfHosted, deployMode } = usePlatform(); + const { connected } = useCloud(); + return + {children} + ; +} + /** Share one read between billing navigation and recovery; never share customer data across scopes. */ export function PendingCheckoutsProvider({ children, workspaceId, enabled = true, + includeManagement = false, }: { children: ReactNode; workspaceId?: string; enabled?: boolean; + includeManagement?: boolean; }) { const scope = useResourceScope(); const { data: session, isPending } = useSession(); const { organizationId } = useBillingScope(); + const parent = usePendingCheckouts(); const allowed = enabled && !isPending && (!organizationId || organizationId === session?.session.activeOrganizationId); + if (parent && parent.workspaceId === workspaceId && allowed && !includeManagement) return children; return ( {children} @@ -64,11 +84,13 @@ function PendingCheckoutsState({ workspaceId, enabled, waiting, + includeManagement, }: { children: ReactNode; workspaceId?: string; enabled: boolean; waiting?: boolean; + includeManagement: boolean; }) { const { t } = useI18n(); const parent = usePendingCheckouts(); @@ -77,6 +99,7 @@ function PendingCheckoutsState({ const [closed, setClosed] = useState>(() => new Set()); const [loading, setLoading] = useState(enabled); const [error, setError] = useState(null); + const [managementPending, setManagementPending] = useState(false); const mounted = useRef(false); const revision = useRef(0); const refreshing = useRef(false); @@ -86,6 +109,14 @@ function PendingCheckoutsState({ refreshing.current = true; setLoading(true); setError(null); + if (includeManagement) { + // Keep compute recovery usable if this account cannot read Manage billing. + void managementApi.get().then(state => { + if (mounted.current && revision.current === request) setManagementPending(Boolean( + state.pendingCheckout || state.change?.paymentUrl || subscriptionNeedsPayment(state.subscription?.status), + )); + }).catch(() => {}); + } try { const result = await billingApi.listCheckouts(workspaceId); if (!mounted.current || revision.current !== request) return; @@ -102,7 +133,7 @@ function PendingCheckoutsState({ setLoading(false); } } - }, [enabled, workspaceId, t.billing.pendingPayments.loadError]); + }, [enabled, workspaceId, includeManagement, t.billing.pendingPayments.loadError]); useEffect(() => { mounted.current = true; void refresh(); @@ -111,10 +142,13 @@ function PendingCheckoutsState({ if (document.visibilityState === "visible" && !refreshing.current) void refresh(); }; window.addEventListener("focus", onFocus); + const onChanged = () => { void refresh(); }; + window.addEventListener(PAYMENTS_CHANGED, onChanged); return () => { mounted.current = false; revision.current++; window.removeEventListener("focus", onFocus); + window.removeEventListener(PAYMENTS_CHANGED, onChanged); }; }, [refresh]); const markCleared = useCallback( @@ -135,6 +169,7 @@ function PendingCheckoutsState({ refresh, markCleared, count: enabled ? items.filter((item) => !closed.has(item.id)).length : 0, + attentionCount: enabled ? new Set(items.filter(item => !closed.has(item.id)).map(item => item.server.id)).size + Number(managementPending) : 0, }} > {children} diff --git a/apps/dashboard/src/components/billing/checkout-recovery.test.tsx b/apps/dashboard/src/components/billing/checkout-recovery.test.tsx index 0d2daa8fc..19a048b40 100644 --- a/apps/dashboard/src/components/billing/checkout-recovery.test.tsx +++ b/apps/dashboard/src/components/billing/checkout-recovery.test.tsx @@ -69,12 +69,6 @@ const ready = { const expired = { status: "expired", checkoutId: "cs_pending", checkoutUrl: null }; let root: Root; let host: HTMLDivElement; -let popup: { - opener: object | null; - closed: boolean; - location: { href: string }; - close: ReturnType; -}; const recovery = () => ( { h.get.mockImplementation(async () => ({ data: { items: [structuredClone(item)] } })); h.post.mockResolvedValue({ data: ready }); h.remove.mockResolvedValue({ ...server, state: "deleting" }); - popup = { opener: {}, closed: false, location: { href: "about:blank" }, close: vi.fn() }; - vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window); + vi.spyOn(window, "open").mockReturnValue(null); host = document.createElement("div"); document.body.append(host); root = createRoot(host); @@ -157,8 +150,7 @@ describe("unfinished checkout recovery", () => { workspaceId: server.id, id: item.id, }); - expect(popup.location.href).toBe(ready.checkoutUrl); - expect(popup.opener).toBeNull(); + expect(window.open).toHaveBeenCalledExactlyOnceWith(ready.checkoutUrl, "_blank", "noopener,noreferrer"); expect(h.started).toHaveBeenCalledExactlyOnceWith(ready.checkoutUrl); expect(dialog()?.querySelector('a[target="_blank"]')?.getAttribute("href")).toBe( ready.checkoutUrl, @@ -374,7 +366,7 @@ describe("unfinished checkout recovery", () => { expect(h.get).toHaveBeenCalledTimes(2); }); - it.each(["local", "cloud"])("ignores earlier payment results after switching the %s account and closes its reserved tab", async (account) => { + it.each(["local", "cloud"])("ignores earlier payment results after switching the %s account without opening checkout", async (account) => { let finish!: (value: unknown) => void; h.post.mockReturnValueOnce( new Promise((resolve) => { @@ -392,8 +384,7 @@ describe("unfinished checkout recovery", () => { h.get.mockResolvedValueOnce({ data: { items: [] } }); await render(); await act(async () => finish({ data: ready })); - expect(popup.location.href).toBe("about:blank"); - expect(popup.close).toHaveBeenCalled(); + expect(window.open).not.toHaveBeenCalled(); expect(h.started).not.toHaveBeenCalled(); expect(dialog()?.textContent).not.toContain(item.name); }); @@ -421,4 +412,15 @@ describe("unfinished checkout recovery", () => { expect(host.querySelector("output")?.textContent).toBe("0"); expect(dialog()?.textContent).toContain(copy.canceled); }); + + it("does not reuse the organization's payment data in a foreign billing scope", async () => { + function Count({ id }: { id: string }) { return {usePendingCheckouts()?.count}; } + await render( + + + ); + expect(host.querySelector("#current")?.textContent).toBe("1"); + expect(host.querySelector("#foreign")?.textContent).toBe("0"); + expect(h.get).toHaveBeenCalledOnce(); + }); }); diff --git a/apps/dashboard/src/components/billing/cloud-deploy-pricing.test.tsx b/apps/dashboard/src/components/billing/cloud-deploy-pricing.test.tsx index 22b68b439..aa1eb806d 100644 --- a/apps/dashboard/src/components/billing/cloud-deploy-pricing.test.tsx +++ b/apps/dashboard/src/components/billing/cloud-deploy-pricing.test.tsx @@ -65,7 +65,6 @@ function Harness() { let root: Root; let container: HTMLDivElement; -let checkoutTab: { opener: unknown; closed: boolean; location: { href: string }; close: ReturnType }; let open: ReturnType; const restriction = () => new ApiError(402, "Payment Required", { code: "CLOUD_BILLING_BLOCKED" }); function button(label: string) { @@ -89,8 +88,7 @@ beforeEach(() => { mocks.get.mockResolvedValue({ data: { locale: "en", annual: { enabled: true, monthsFree: 0 }, ui: pricingUi("en"), plans } }); mocks.deploy.mockRejectedValue(restriction()); mocks.post.mockResolvedValue({ data: { checkoutUrl: "https://checkout.example.test/session" } }); - checkoutTab = { opener: window, closed: false, location: { href: "about:blank" }, close: vi.fn() }; - open = vi.spyOn(window, "open").mockReturnValue(checkoutTab as unknown as Window); + open = vi.spyOn(window, "open").mockReturnValue(null); container = document.createElement("div"); document.body.append(container); root = createRoot(container); @@ -142,13 +140,13 @@ describe("deployment plan selection", () => { let resolveCheckout!: (value: unknown) => void; mocks.post.mockReturnValueOnce(new Promise((resolve) => { resolveCheckout = resolve; })); await act(async () => { button("Choose Hobby").click(); button("Choose Hobby").click(); }); - expect(open).toHaveBeenCalledOnce(); - expect(checkoutTab.opener).toBeNull(); - expect(checkoutTab.location.href).toBe("about:blank"); + expect(open).not.toHaveBeenCalled(); expect(mocks.post).toHaveBeenCalledTimes(1); expect(mocks.post).toHaveBeenCalledWith("billing/subscription", expect.objectContaining({ planTierId: "starter", interval: "monthly", idempotencyKey: expect.any(String) })); await act(async () => resolveCheckout({ data: { checkoutUrl: "https://checkout.example.test/session" } })); - expect(checkoutTab.location.href).toBe("https://checkout.example.test/session"); + expect(open).toHaveBeenCalledExactlyOnceWith("https://checkout.example.test/session", "_blank", "noopener,noreferrer"); + await click("Choose Hobby"); + expect(mocks.post).toHaveBeenCalledTimes(1); expect(container.querySelector("input")?.value).toBe("My configured project"); expect(mocks.deploy).toHaveBeenCalledTimes(1); await click(copy.deployGate.checkPlan); @@ -211,7 +209,7 @@ describe("deployment plan selection", () => { await click("Deploy"); await click("Choose Hobby"); expect(document.querySelector('[role="alert"]')?.textContent).toBe("Checkout temporarily unavailable"); - expect(checkoutTab.close).toHaveBeenCalledOnce(); + expect(open).not.toHaveBeenCalled(); await click("Choose Hobby"); expect(mocks.post.mock.calls[1]![1].idempotencyKey).toBe(mocks.post.mock.calls[0]![1].idempotencyKey); }); diff --git a/apps/dashboard/src/components/billing/server-plan-picker.test.tsx b/apps/dashboard/src/components/billing/server-plan-picker.test.tsx index 4cfd4208f..03937e70b 100644 --- a/apps/dashboard/src/components/billing/server-plan-picker.test.tsx +++ b/apps/dashboard/src/components/billing/server-plan-picker.test.tsx @@ -59,7 +59,6 @@ function customQuote(resources: CustomServerResources): BillingCustomQuote { let management: ManagementState; let root: Root; let host: HTMLDivElement; -let popup: { opener: object | null; closed: boolean; location: { href: string }; close: ReturnType }; function SidebarState() { const { autoCollapse } = useSidebarLayout(); const { collapsed } = useSidebarCollapse("plans", autoCollapse); @@ -101,16 +100,16 @@ beforeEach(() => { vi.resetAllMocks(); vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); h.user = "user-a"; h.org = "org-a"; h.connected = true; h.sessionPending = false; window.location.href = "http://localhost:3000/"; + sessionStorage.clear(); management = { pricing: PRICING.management, purchasesAvailable: true, cloudIncluded: false, active: false, serverLimit: 0, connectedServers: 0, pendingCheckout: false, subscription: null, change: null }; - h.get.mockImplementation(async (path, options) => path === "/billing/manage" ? { data: management } : path.endsWith("/quote") + h.get.mockImplementation(async (path, options) => path === "billing/checkouts" ? { data: { items: [] } } : path === "/billing/manage" ? { data: management } : path.endsWith("/quote") ? { data: customQuote(options.params) } : catalog); h.create.mockResolvedValue(server); h.readServer.mockResolvedValue({ id: server.serverId, name: server.name, managed: server }); h.available.mockResolvedValue({ servers: [] }); h.post.mockResolvedValue({ data: { checkoutUrl: "https://checkout.example.test/new-server" } }); - popup = { opener: {}, closed: false, location: { href: "about:blank" }, close: vi.fn() }; - vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window); + vi.spyOn(window, "open").mockReturnValue(null); host = document.createElement("div"); document.body.append(host); root = createRoot(host); }); afterEach(async () => { @@ -259,6 +258,7 @@ describe("referral checkout handoff", () => { describe("annual Cloud purchases", () => { beforeEach(() => { h.get.mockImplementation(async (path, options) => { + if (path === "billing/checkouts") return { data: { items: [] } }; if (path.endsWith("/quote")) { const annual = options.params.interval === "annual"; return { data: { ...customQuote(options.params), reference: annual ? "quote-annual" : "quote-monthly", @@ -546,7 +546,83 @@ describe("buying another managed server", () => { expect(h.create).not.toHaveBeenCalled(); expect(h.post).not.toHaveBeenCalled(); await click("Choose Starter"); - expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName }); + expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName, idempotencyKey: expect.any(String) }); + }); + + it("reuses the manual server identity after a lost response and reopening the modal", async () => { + h.create.mockRejectedValueOnce(new Error("Creation response lost")); + await render(); + await click("Choose Hobby"); + expect(h.post).not.toHaveBeenCalled(); + const first = h.create.mock.calls[0]; + await act(async () => root.unmount()); root = createRoot(host); + await render(); + await click("Choose Hobby"); + expect(h.create.mock.calls[1]).toEqual(first); + expect(h.post).toHaveBeenCalledOnce(); + await click("Choose Hobby"); + expect(h.post).toHaveBeenCalledOnce(); + }); + + it("reopens an existing unpaid purchase without creating another Cloud space", async () => { + await render(); + await click("Add a destination"); await click("Choose Hobby"); + expect(h.create).toHaveBeenCalledOnce(); + await click(copy.workspaces.returnToSetup); + const ordinary = h.get.getMockImplementation()!; + h.get.mockImplementation((path, options) => path === "billing/checkouts" ? Promise.resolve({ data: { items: [{ + id: "a".repeat(64), checkoutId: "cs_pending", server, kind: "subscription", name: "Saved Hobby", + amountCents: 1200, currency: "usd", interval: "monthly", state: "open", canResume: true, canCancel: true, + }] } }) : ordinary(path, options)); + await click("Add a destination"); await click("Choose Hobby"); + expect(h.create).toHaveBeenCalledOnce(); + expect(document.body.textContent).toContain("Saved Hobby"); + expect(h.post).toHaveBeenCalledOnce(); + h.post.mockResolvedValueOnce({ data: { status: "ready", checkoutId: "cs_pending", checkoutUrl: "https://checkout.example.test/original" } }); + await click(copy.pendingPayments.resume); + expect(h.post).toHaveBeenLastCalledWith("billing/checkout/resume", { workspaceId: server.id, id: "a".repeat(64) }); + expect(window.open).toHaveBeenLastCalledWith("https://checkout.example.test/original", "_blank", "noopener,noreferrer"); + }); + + it("never creates resources when pending payments cannot be checked", async () => { + const ordinary = h.get.getMockImplementation()!; + h.get.mockImplementation((path, options) => path === "billing/checkouts" ? Promise.reject(new Error("Payment status unavailable")) : ordinary(path, options)); + await render(); await click("Choose Hobby"); + expect(h.create).not.toHaveBeenCalled(); expect(h.post).not.toHaveBeenCalled(); + expect(window.open).not.toHaveBeenCalled(); + expect(host.textContent).toContain("Payment status unavailable"); + }); + + it("opens recovery for a submitted payment without attempting another subscription", async () => { + const ordinary = h.get.getMockImplementation()!; + h.get.mockImplementation((path, options) => path === "billing/checkouts" ? Promise.resolve({ data: { items: [{ + id: "a".repeat(64), checkoutId: "cs_processing", server: { ...server, planTierId: "hobby" }, + kind: "subscription", name: "Submitted Hobby payment", amountCents: 1200, currency: "usd", + interval: "monthly", state: "processing", canResume: false, canCancel: false, + }] } }) : ordinary(path, options)); + await render(); await click("Choose Hobby"); + expect(h.create).not.toHaveBeenCalled(); expect(h.post).not.toHaveBeenCalled(); + expect(document.body.textContent).toContain("Submitted Hobby payment"); + expect(document.body.textContent).toContain(copy.pendingPayments.states.processing); + }); + + it("starts a new manual space after the previous purchase completed", async () => { + h.create.mockResolvedValueOnce({ ...server, planTierId: "hobby", state: "running" }); + await render(); await click("Choose Hobby"); + expect(h.create).toHaveBeenCalledTimes(2); + expect(h.create.mock.calls[1][0].idempotencyKey).not.toBe(h.create.mock.calls[0][0].idempotencyKey); + expect(h.post).toHaveBeenCalledOnce(); + }); + + it("does not create a space after the pending-payment read resolves for a different account", async () => { + let finish!: (value: unknown) => void; + const ordinary = h.get.getMockImplementation()!; + h.get.mockImplementation((path, options) => path === "billing/checkouts" ? new Promise(resolve => { finish = resolve; }) : ordinary(path, options)); + await render(); await click("Choose Hobby"); + h.org = "org-b"; await render(); + await act(async () => finish({ data: { items: [] } })); + expect(h.create).not.toHaveBeenCalled(); expect(h.post).not.toHaveBeenCalled(); + expect(window.open).not.toHaveBeenCalled(); }); it("keeps the landing-page plan using the live offer without creating anything on arrival", async () => { @@ -645,9 +721,8 @@ describe("buying another managed server", () => { id: "a".repeat(64), checkoutId: "cs_pending", server, kind: "subscription", name: "Starter", amountCents: 2000, currency: "usd", interval: "monthly", state: "open", canResume: true, canCancel: true, }] } } : catalog); - h.post.mockRejectedValueOnce(new ApiError(409, "Already pending", { code: "CLOUD_WORKSPACE_CHECKOUT_PENDING" })); await render(); - const first = h.post.mock.calls[0][1].idempotencyKey; + expect(h.post).not.toHaveBeenCalled(); await click(copy.pendingPayments.cancel); h.post.mockResolvedValueOnce({ data: { status: "expired", checkoutId: "cs_pending", checkoutUrl: null } }); await click(copy.pendingPayments.confirmCancel); @@ -655,14 +730,15 @@ describe("buying another managed server", () => { expect(url.searchParams.has("startCheckout")).toBe(false); expect(url.searchParams.get("checkoutIntent")).toBe(key); expect(url.searchParams.get("checkoutAttempt")).not.toBe(key); - expect(h.post).toHaveBeenCalledTimes(2); + expect(h.post).toHaveBeenCalledOnce(); + h.get.mockImplementation(async path => path === "billing/checkouts" ? { data: { items: [] } } : catalog); await act(async () => root.unmount()); root = createRoot(host); await render(); - expect(h.post).toHaveBeenCalledTimes(2); + expect(h.post).toHaveBeenCalledOnce(); await click("Choose Starter"); - expect(h.create.mock.calls[1]).toEqual(h.create.mock.calls[0]); - expect(h.post.mock.calls[2][1].idempotencyKey).not.toBe(first); - expect(h.post.mock.calls[2][1].workspaceId).toBe(server.id); + expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName, idempotencyKey: key }); + expect(h.post.mock.calls[1][1].idempotencyKey).toBe(`${url.searchParams.get("checkoutAttempt")}-starter-monthly`); + expect(h.post.mock.calls[1][1].workspaceId).toBe(server.id); }); it("starts a fresh explicit purchase after removing the cancelled draft", async () => { @@ -672,7 +748,6 @@ describe("buying another managed server", () => { id: "a".repeat(64), checkoutId: "cs_pending", server, kind: "subscription", name: "Starter", amountCents: 2000, currency: "usd", interval: "monthly", state: "open", canResume: true, canCancel: true, }] } } : catalog); - h.post.mockRejectedValueOnce(new ApiError(409, "Already pending", { code: "CLOUD_WORKSPACE_CHECKOUT_PENDING" })); await render(); await click(copy.pendingPayments.cancel); h.post.mockResolvedValueOnce({ data: { status: "expired", checkoutId: "cs_pending", checkoutUrl: null } }); @@ -680,11 +755,12 @@ describe("buying another managed server", () => { h.remove.mockResolvedValueOnce({ data: { accepted: true } }); await click(copy.pendingPayments.deleteServer); await click(copy.workspaces.confirmDelete); - expect(h.create).toHaveBeenCalledOnce(); + expect(h.create).not.toHaveBeenCalled(); + h.get.mockImplementation(async path => path === "billing/checkouts" ? { data: { items: [] } } : catalog); expect(new URL(window.location.href).searchParams.get("checkoutIntent")).not.toBe(key); expect(new URL(window.location.href).searchParams.has("startCheckout")).toBe(false); await click("Choose Starter"); - expect(h.create.mock.calls[1][0].idempotencyKey).not.toBe(key); + expect(h.create.mock.calls[0][0].idempotencyKey).not.toBe(key); }); it("does not continue a pending pricing purchase in another account or organization", async () => { @@ -706,7 +782,7 @@ describe("buying another managed server", () => { currentPeriod: { start: null, end: null }, monthlyCreditLimit: 0, buildTimeMinutes: 0, balance: { total: 0, quotaLimit: 0, quotaUsed: 0, quotaRemaining: 0 }, workspace: server, billing: { enabled: true } }; - h.get.mockImplementation(async path => path === "billing/state" ? { data: billing } : catalog); + h.get.mockImplementation(async path => path === "billing/checkouts" ? { data: { items: [] } } : path === "billing/state" ? { data: billing } : catalog); const location = window.location.href; await render(); await click("Add a destination"); @@ -741,7 +817,7 @@ describe("buying another managed server", () => { const started = vi.fn(); await render(); await act(async () => { buttons("Choose Starter")[0]!.click(); buttons("Choose Starter")[0]!.click(); }); - expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName }); + expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName, idempotencyKey: expect.any(String) }); expect(h.post).not.toHaveBeenCalled(); await act(async () => created(server)); expect(h.post).toHaveBeenCalledWith("billing/subscription", expect.objectContaining({ workspaceId: server.id, planTierId: "starter" })); @@ -750,8 +826,7 @@ describe("buying another managed server", () => { expect(h.create).toHaveBeenCalledOnce(); expect(h.post.mock.calls[1]).toEqual(h.post.mock.calls[0]); expect(started).toHaveBeenCalledWith(server, "https://checkout.example.test/new-server"); - expect(popup.location.href).toBe("https://checkout.example.test/new-server"); - expect(popup.opener).toBeNull(); + expect(window.open).toHaveBeenCalledExactlyOnceWith("https://checkout.example.test/new-server", "_blank", "noopener,noreferrer"); }); it("keeps the new server and exact purchase when retrying from unavailable-capacity feedback", async () => { @@ -762,7 +837,7 @@ describe("buying another managed server", () => { await click("Choose Pro"); expect(document.querySelector('[role="dialog"]')?.textContent).toContain(copy.checkoutUnavailable.capacityTitle); expect(document.body.textContent).not.toContain("Raw provider failure"); - expect(popup.close).toHaveBeenCalledOnce(); + expect(window.open).not.toHaveBeenCalled(); expect(h.post.mock.calls[0]![1]).toMatchObject({ workspaceId: server.id, planTierId: "pro" }); await click(copy.checkoutUnavailable.retry); expect(h.create).toHaveBeenCalledOnce(); @@ -775,7 +850,6 @@ describe("buying another managed server", () => { id: "a".repeat(64), checkoutId: "cs_pending", server, kind: "subscription", name: "Saved Starter", amountCents: 2000, currency: "usd", interval: "monthly", state: "open", canResume: true, canCancel: true, }] } } : catalog); - h.post.mockRejectedValueOnce(new ApiError(409, "Blocked", { code: "CLOUD_WORKSPACE_CHECKOUT_PENDING", error: "Raw pending error" })); h.post.mockImplementation(async path => path === "billing/checkout/cancel" ? { data: { status: "expired", checkoutId: "cs_pending", checkoutUrl: null } } : { data: { checkoutUrl: "https://checkout.example.test/new-server" } }); @@ -785,6 +859,7 @@ describe("buying another managed server", () => { expect(document.querySelector('[role="dialog"]')?.textContent).toContain(copy.pendingPayments.title); expect(document.body.textContent).not.toContain("Raw pending error"); await click(copy.pendingPayments.cancel); await click(copy.pendingPayments.confirmCancel); + h.get.mockImplementation(async path => path === "billing/checkouts" ? { data: { items: [] } } : catalog); if (remove) { await click(copy.pendingPayments.deleteServer); await click(copy.workspaces.confirmDelete); h.create.mockResolvedValueOnce({ ...server, id: "cws-replacement", serverId: "server-replacement" }); @@ -792,10 +867,9 @@ describe("buying another managed server", () => { await act(async () => document.querySelector(`button[aria-label="${copy.checkoutUnavailable.close}"]`)!.click()); await click("Choose Starter"); const attempts = h.post.mock.calls.filter(([path]) => path === "billing/subscription").map(([, input]) => input); - expect(attempts).toHaveLength(2); - expect(attempts[1].idempotencyKey).not.toBe(attempts[0].idempotencyKey); - expect(attempts[1].workspaceId).toBe(remove ? "cws-replacement" : server.id); - expect(h.create).toHaveBeenCalledTimes(remove ? 2 : 1); + expect(attempts).toHaveLength(1); + expect(attempts[0].workspaceId).toBe(remove ? "cws-replacement" : server.id); + expect(h.create).toHaveBeenCalledTimes(remove ? 1 : 0); }); it("discards an unavailable checkout when the customer changes organization", async () => { @@ -818,7 +892,7 @@ describe("buying another managed server", () => { await render(); await act(async () => created(server)); expect(h.post).not.toHaveBeenCalled(); - expect(popup.close).toHaveBeenCalled(); + expect(window.open).not.toHaveBeenCalled(); h.create.mockResolvedValueOnce({ ...server, id: "cws-org-b" }); await click("Choose Starter"); expect(h.post).toHaveBeenCalledWith("billing/subscription", expect.objectContaining({ workspaceId: "cws-org-b" })); diff --git a/apps/dashboard/src/components/billing/useCloudBilling.ts b/apps/dashboard/src/components/billing/useCloudBilling.ts index 97fc55b83..8abbeea39 100644 --- a/apps/dashboard/src/components/billing/useCloudBilling.ts +++ b/apps/dashboard/src/components/billing/useCloudBilling.ts @@ -7,12 +7,12 @@ import type { PlanTierId } from "@repo/core"; import type { BillingPlans, CustomSubscriptionSelection } from "@repo/contracts"; import { useI18n } from "@/components/i18n-provider"; import { api, ApiError, getApiErrorCode, getApiErrorMessage } from "@/lib/api/client"; -import { beginCheckoutNavigation } from "@/lib/checkout-navigation"; +import { navigateToCheckout } from "@/lib/checkout-navigation"; +import { invalidatePayments } from "@/lib/billing-events"; import { endpoints } from "@/lib/api/endpoints"; import { randomUUID } from "@/lib/random-uuid"; import { checkoutFailureKind, type CheckoutFailure } from "@/lib/checkout-failure"; -import { useSession } from "@/lib/auth-client"; -import { useCloudResourceKey } from "@/context/CloudResourceContext"; +import { useResourceScope } from "@/hooks/use-scoped-resource"; import type { ApiPlan, ApiPricingUi } from "./PricingCards"; interface PlansPayload extends Omit { @@ -20,6 +20,8 @@ interface PlansPayload extends Omit { plans: ApiPlan[]; } +export type PreparedCheckoutWorkspace = string | { workspaceId: string; checkoutPending: true }; + /** Both the recommendation and comparison use the same live checkout catalog. */ export function useCloudPlans() { const { t, locale } = useI18n(); @@ -47,7 +49,7 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS workspaceId?: string; preserveProject?: boolean; onCheckoutStarted?: (checkoutUrl: string) => void; - prepareWorkspace?: () => Promise; + prepareWorkspace?: () => Promise; onWorkspaceRemoved?: (workspaceId: string) => void; idempotencyKey?: string; referralCode?: string; @@ -55,9 +57,8 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS }) { const { t } = useI18n(); const { workspaceId: billingWorkspaceId, organizationId } = useBillingScope(); - const { data: session } = useSession(); - const cloudKey = useCloudResourceKey(); - const ownerKey = `${cloudKey}:${session?.user.id}:${organizationId ?? session?.session?.activeOrganizationId}`; + const scope = useResourceScope(); + const ownerKey = `${scope}:${organizationId ?? ""}`; const workspaceId = selectedWorkspaceId ?? billingWorkspaceId ?? undefined; const [subscribing, setSubscribing] = useState(null); const [error, setError] = useState(null); @@ -78,11 +79,10 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS useEffect(() => { attempts.current.clear(); }, [idempotencyKey]); async function startCheckout(planTierId: PlanTierId, interval: "monthly" | "annual", custom?: CustomSubscriptionSelection) { - if (!enabled || busy.current || planTierId === "free" || planTierId === "enterprise") return; + if (!enabled || busy.current || checkoutUrl || planTierId === "free" || planTierId === "enterprise") return; busy.current = true; const version = generation.current; - // Open within the user's click, preserving unfinished project configuration. - const navigation = beginCheckoutNavigation(preserveProject); + let checkoutStarted = false; setSubscribing(custom ? "custom" : planTierId); setError(null); setCheckoutUrl(null); @@ -91,8 +91,13 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS let targetWorkspaceId = workspaceId; let requestId: string | undefined; try { - targetWorkspaceId = prepareWorkspace ? await prepareWorkspace() : workspaceId; - if (version !== generation.current) { navigation.close(); return; } + const prepared = prepareWorkspace ? await prepareWorkspace() : workspaceId; + targetWorkspaceId = typeof prepared === "object" ? prepared.workspaceId : prepared; + if (version !== generation.current) return; + if (typeof prepared === "object" && prepared.checkoutPending) { + setPending({ workspaceId: prepared.workspaceId }); + return; + } if (prepareWorkspace && !targetWorkspaceId) throw new Error(t.billing.plansRoute.checkoutError); const attempt = `${targetWorkspaceId ?? "initial"}:${custom?.quoteReference ?? planTierId}:${interval}:${referralCode ?? ""}`; if (!attempts.current.has(attempt)) attempts.current.set(attempt, @@ -102,14 +107,14 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS planTierId, interval, workspaceId: targetWorkspaceId, custom, idempotencyKey: requestId, ...(referralCode ? { referralCode } : {}), }); - if (version !== generation.current) { navigation.close(); return; } - const url = navigation.navigate(res.data.checkoutUrl); + if (version !== generation.current) return; + const url = navigateToCheckout(res.data.checkoutUrl, preserveProject); if (preserveProject) { + checkoutStarted = true; setCheckoutUrl(url); onCheckoutStarted?.(url); } } catch (err) { - navigation.close(); if (version !== generation.current) return; const kind = checkoutFailureKind(err); if (getApiErrorCode(err) === "CLOUD_WORKSPACE_CHECKOUT_PENDING") setPending({ workspaceId: targetWorkspaceId }); @@ -120,8 +125,9 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS } } finally { if (version === generation.current) { - busy.current = false; + busy.current = checkoutStarted; setSubscribing(null); + invalidatePayments(); } } } @@ -129,7 +135,7 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS recovery: { isOpen: pending !== null, workspaceId: pending?.workspaceId, preserveProject, onClose: () => setPending(null), - onCleared: () => { attempts.current.clear(); setError(null); onCheckoutSettled?.(); }, + onCleared: () => { busy.current = false; attempts.current.clear(); setCheckoutUrl(null); setError(null); onCheckoutSettled?.(); }, onCheckoutStarted: (url: string) => { setCheckoutUrl(url); onCheckoutStarted?.(url); }, onServerRemoved: (id: string) => { attempts.current.clear(); setCheckoutUrl(null); onWorkspaceRemoved?.(id); diff --git a/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx b/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx index c475b1b53..41b6bdad9 100644 --- a/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx +++ b/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx @@ -8,8 +8,9 @@ import { BillingWorkspaceProvider } from "@/components/billing/BillingWorkspaceC import { Button } from "@/components/ui/button"; import { useSession } from "@/lib/auth-client"; import { systemApi } from "@/lib/api/system"; -import { getApiErrorMessage } from "@/lib/api/client"; -import { useCloudResourceKey } from "@/context/CloudResourceContext"; +import { getApiErrorCode, getApiErrorMessage } from "@/lib/api/client"; +import { billingApi } from "@/lib/api/billing"; +import { useResourceScope } from "@/hooks/use-scoped-resource"; import { randomUUID } from "@/lib/random-uuid"; import { isCloudPurchaseIntent } from "@/lib/cloud-purchase-intent"; @@ -31,8 +32,7 @@ interface PurchaseProps { * Browsing does not create a server; retries reuse the identity just created. */ export function ManagedServerPurchase(props: PurchaseProps) { const { data: session, isPending } = useSession(); - const cloudKey = useCloudResourceKey(); - const contextKey = `${cloudKey}:${session?.user.id ?? "local"}:${session?.session.activeOrganizationId ?? ""}`; + const contextKey = useResourceScope(); const [intent, setIntent] = useState<{ owner: string; key: string; paymentKey: string; automatic: boolean } | null>(null); useEffect(() => { if (intent || isPending || !session?.user.id || !session.session.activeOrganizationId) return; @@ -84,14 +84,51 @@ function Purchase({ onIntentRemoved, }: PurchaseProps & { sessionPending?: boolean; onCheckoutSettled?: () => void; onIntentRemoved?: () => void }) { const { t } = useI18n(); + const scope = useResourceScope(); + const owner = useRef(scope); + owner.current = scope; + const mounted = useRef(false); + useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []); const created = useRef(null); const [error, setError] = useState(null); async function prepareWorkspace() { - created.current ??= await systemApi.createManagedServer({ - name: t.billing.workspaces.defaultName, - ...(checkoutIntent ? { idempotencyKey: checkoutIntent } : {}), - }); + if (created.current) return created.current.id; + // Reopening a modal must recover its unpaid space, not buy another one. + // Recover its saved payment directly, including processing payments. + const pending = await billingApi.listCheckouts(); + if (!mounted.current || owner.current !== scope) throw new Error("Purchase scope changed"); + const unfinished = pending.items.find(item => item.kind === "subscription"); + if (unfinished) { + created.current = unfinished.server; + return { workspaceId: unfinished.server.id, checkoutPending: true as const }; + } + const storageKey = `openship:cloud-purchase:${scope}`; + let key = checkoutIntent; + if (!key) { + try { key = sessionStorage.getItem(storageKey) ?? undefined; } catch {} + if (!isCloudPurchaseIntent(key)) key = randomUUID(); + try { sessionStorage.setItem(storageKey, key); } catch {} + } + const create = (idempotencyKey: string) => { + if (!mounted.current || owner.current !== scope) throw new Error("Purchase scope changed"); + return systemApi.createManagedServer({ name: t.billing.workspaces.defaultName, idempotencyKey }); + }; + let server: CloudWorkspaceSummary; + try { server = await create(key); } + catch (error) { + if (checkoutIntent || getApiErrorCode(error) !== "CLOUD_WORKSPACE_PURCHASE_REMOVED") throw error; + key = randomUUID(); + try { sessionStorage.setItem(storageKey, key); } catch {} + server = await create(key); + } + if (!checkoutIntent && (server.planTierId !== "free" || server.resources)) { + // The last purchase completed. This explicit Add space is a new purchase. + key = randomUUID(); + try { sessionStorage.setItem(storageKey, key); } catch {} + server = await create(key); + } + created.current = server; return created.current.id; } diff --git a/apps/dashboard/src/components/sidebar.test.tsx b/apps/dashboard/src/components/sidebar.test.tsx index 406f34065..164291992 100644 --- a/apps/dashboard/src/components/sidebar.test.tsx +++ b/apps/dashboard/src/components/sidebar.test.tsx @@ -9,6 +9,8 @@ import { getActiveOrganizationId, setActiveOrganizationId } from "@/lib/api/clie import { useIssueCounts } from "@/hooks/useIssueCounts"; import { Sidebar } from "./sidebar"; import { SidebarLayoutProvider, useSidebarCollapseRequest } from "@/context/SidebarLayoutContext"; +import { DashboardPaymentsProvider, PendingCheckoutsProvider } from "./billing/PendingCheckoutsContext"; +import { invalidatePayments } from "@/lib/billing-events"; const mocks = vi.hoisted(() => ({ pathname: "/monitoring", @@ -18,6 +20,8 @@ const mocks = vi.hoisted(() => ({ feed: vi.fn(), organization: vi.fn(), projects: vi.fn(), + payments: vi.fn(), + management: vi.fn(), })); vi.mock("next/navigation", () => ({ usePathname: () => mocks.pathname, @@ -25,6 +29,7 @@ vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }), })); vi.mock("@/lib/auth-client", () => ({ + useSession: () => ({ data: { user: { id: "user-a" }, session: { activeOrganizationId: "org-a" } } }), authClient: { organization: { list: async () => ({ data: [] }), @@ -55,6 +60,8 @@ vi.mock("@/lib/api/client", async (original) => { if (path === "issues/summary") return mocks.summary(); if (path === "issues" || path === "issues?status=resolved") return mocks.feed(path); if (path === "projects/home") return mocks.projects(); + if (path === "billing/checkouts") return mocks.payments(); + if (path === "/billing/manage") return mocks.management(); throw new Error(`Unexpected GET ${path}`); }, }, @@ -74,6 +81,8 @@ beforeEach(() => { mocks.organization.mockResolvedValue({ data: { id: "org-a" } }); mocks.summary.mockResolvedValue({ data: counts }); mocks.projects.mockResolvedValue({ success: true, projects: [] }); + mocks.payments.mockResolvedValue({ data: { items: [] } }); + mocks.management.mockResolvedValue({ data: { pendingCheckout: false, subscription: null, change: null } }); host = document.createElement("div"); document.body.append(host); root = createRoot(host); @@ -115,18 +124,48 @@ it.each([ expect(mocks.projects).toHaveBeenCalledOnce(); }); -async function render(props: ComponentProps = {}) { +async function render(props: ComponentProps = {}, payments = false) { + const content = ; await act(async () => root.render( - - - - + {payments ? {content} : content} , ), ); } + +it("counts unpaid Cloud plans and Manage once in the sidebar and refreshes after payment changes", async () => { + mocks.cloudConnected = true; + mocks.payments.mockResolvedValue({ data: { items: [ + { id: "one", server: { id: "space-a" } }, + { id: "two", server: { id: "space-a" } }, + { id: "three", server: { id: "space-b" } }, + ] } }); + mocks.management.mockResolvedValue({ data: { pendingCheckout: true, subscription: null, change: null } }); + await render({}, true); + const link = () => host.querySelector('a[href="/billing"]')!; + expect(link().querySelector(".tabular-nums")?.textContent).toBe("3"); + expect(link().querySelector(".tabular-nums")?.className).toContain("text-danger"); + expect(link().getAttribute("aria-label")).toContain("Pending: 3"); + // The hub's nested provider reuses the organization-wide read. + expect(mocks.payments).toHaveBeenCalledOnce(); + await act(async () => sidebarToggle().click()); + expect(link().title).toContain("Pending: 3"); + expect(link().querySelector(".tabular-nums")?.textContent).toBe("3"); + mocks.payments.mockResolvedValue({ data: { items: [] } }); + mocks.management.mockResolvedValue({ data: { pendingCheckout: false, subscription: null, change: null } }); + await act(async () => invalidatePayments()); + expect(link().getAttribute("aria-label")).toBeNull(); + await act(async () => sidebarToggle().click()); + expect(link().querySelector(".tabular-nums")).toBeNull(); +}); + +it("does not request payment data on an installation disconnected from Cloud", async () => { + await render({}, true); + expect(mocks.payments).not.toHaveBeenCalled(); + expect(mocks.management).not.toHaveBeenCalled(); +}); const monitoring = () => host.querySelector('a[href="/monitoring"]')!; const badge = () => monitoring().querySelector(".tabular-nums"); const sidebarToggle = () => host.querySelector( diff --git a/apps/dashboard/src/components/sidebar.tsx b/apps/dashboard/src/components/sidebar.tsx index 3f3f315b4..b772b2914 100644 --- a/apps/dashboard/src/components/sidebar.tsx +++ b/apps/dashboard/src/components/sidebar.tsx @@ -22,6 +22,7 @@ import { projectsApi } from "@/lib/api"; import { useSidebarCollapse } from "@/hooks/useSidebarCollapse"; import { useSidebarLayout } from "@/context/SidebarLayoutContext"; import { useIssueCounts } from "@/hooks/useIssueCounts"; +import { usePendingCheckouts } from "@/components/billing/PendingCheckoutsContext"; import { countProjectCollections, getSidebarNavCountsRevision, subscribeSidebarNavCounts } from "@/lib/sidebar-nav-counts"; import { getMailNavSections, @@ -153,11 +154,13 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo const [switchingOrgId, setSwitchingOrgId] = useState(null); const hasMonitoring = navSections.some(({ items }) => items.some(({ key }) => key === "issues")); const issueCounts = useIssueCounts(orgsLoaded && hasMonitoring ? activeOrgId : undefined); + const payments = usePendingCheckouts(); const countFor = (key: string): number | null => { // Match Home's Needs attention card; available updates are advisories. if (key === "issues") return issueCounts ? issueCounts.outage + issueCounts.actionRequired : null; if (key === "projects" || key === "apps") return navCounts?.[key] ?? null; + if (key === "billing") return payments?.attentionCount ?? null; return null; }; @@ -373,18 +376,20 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo const { key, href, icon: Icon, labelSource } = item; const active = isNavItemActive(item, navPathname, currentTab); const count = countFor(key); - const issueLabel = + const attentionLabel = key === "issues" && count != null && count > 0 ? `${label(key, labelSource)}: ${count === 1 ? t.dashboard.home.oneIssue : interpolate(t.dashboard.home.manyIssues, { n: String(count) })}` - : undefined; + : key === "billing" && count != null && count > 0 + ? `${label(key, labelSource)}: ${interpolate(t.billing.pendingPayments.count, { count: String(count) })}` + : undefined; return ( @@ -392,10 +397,18 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo {!collapsed && ( {label(key, labelSource)} )} - {/* Hide zero/loading counts; keep issue counts in the collapsed label. */} - {!collapsed && count != null && count > 0 && ( + {/* Keep attention counts accessible when the rail is collapsed. */} + {(!collapsed || key === "billing") && count != null && count > 0 && ( {count} diff --git a/apps/dashboard/src/i18n/locales/en/billing.json b/apps/dashboard/src/i18n/locales/en/billing.json index 922850fa5..e1eb92f67 100644 --- a/apps/dashboard/src/i18n/locales/en/billing.json +++ b/apps/dashboard/src/i18n/locales/en/billing.json @@ -334,7 +334,7 @@ "upgradeDescription": "Choose a plan with enough capacity, or adjust your project and try again.", "manageBilling": "Manage billing", "topups": "Add usage", - "checkoutOpened": "Checkout is ready in a separate tab. If it did not open, use the link below.", + "checkoutOpened": "Complete your payment in secure checkout. If it did not open, use the button below.", "continueCheckout": "Continue to checkout", "reasons": { "static-only": "Your plan does not include this type of app. Choose a plan that supports it to deploy.", diff --git a/apps/dashboard/src/lib/api/management.ts b/apps/dashboard/src/lib/api/management.ts index 09e72d1c6..96897fa95 100644 --- a/apps/dashboard/src/lib/api/management.ts +++ b/apps/dashboard/src/lib/api/management.ts @@ -1,8 +1,11 @@ import type { BillingOperations } from "@repo/contracts"; import { api } from "./client"; +import { invalidatePayments } from "@/lib/billing-events"; type Result = Awaited>; -const post = async (path: string, body?: unknown) => - (await api.post<{ data: Result }>(`/billing/manage/${path}`, body)).data; +const post = async (path: string, body?: unknown) => { + try { return (await api.post<{ data: Result }>(`/billing/manage/${path}`, body)).data; } + finally { invalidatePayments(); } +}; export const managementApi = { get: async () => (await api.get<{ data: Result<"getManagement"> }>("/billing/manage")).data, purchase: (input: Parameters[0]) => diff --git a/apps/dashboard/src/lib/billing-events.ts b/apps/dashboard/src/lib/billing-events.ts new file mode 100644 index 000000000..6b75dfafb --- /dev/null +++ b/apps/dashboard/src/lib/billing-events.ts @@ -0,0 +1,6 @@ +export const PAYMENTS_CHANGED = "openship:payments-changed"; + +/** Refresh payment warnings after mutations, including uncertain responses. */ +export function invalidatePayments() { + window.dispatchEvent(new Event(PAYMENTS_CHANGED)); +} diff --git a/apps/dashboard/src/lib/checkout-navigation.test.ts b/apps/dashboard/src/lib/checkout-navigation.test.ts new file mode 100644 index 000000000..f815161a0 --- /dev/null +++ b/apps/dashboard/src/lib/checkout-navigation.test.ts @@ -0,0 +1,35 @@ +// @vitest-environment happy-dom +import { afterEach, expect, it, vi } from "vitest"; +import { navigateToCheckout } from "./checkout-navigation"; + +afterEach(() => vi.restoreAllMocks()); + +it.each(["javascript:alert(1)", "data:text/html,checkout", "http://checkout.example.test", ""])( + "refuses an invalid payment destination before opening a tab: %s", value => { + const open = vi.spyOn(window, "open"); + const before = window.location.href; + expect(() => navigateToCheckout(value, true)).toThrow(); + expect(open).not.toHaveBeenCalled(); + expect(window.location.href).toBe(before); + }, +); + +it("opens only the final URL without an opener or referrer, preserving the project", () => { + const open = vi.spyOn(window, "open").mockReturnValue(null); + const before = window.location.href; + expect(navigateToCheckout("https://checkout.example.test/session", true)).toBe("https://checkout.example.test/session"); + expect(open).toHaveBeenCalledExactlyOnceWith("https://checkout.example.test/session", "_blank", "noopener,noreferrer"); + expect(window.location.href).toBe(before); +}); + +it("retains the validated fallback URL if the browser throws when refusing a popup", () => { + vi.spyOn(window, "open").mockImplementation(() => { throw new Error("Popups refused"); }); + expect(navigateToCheckout("https://checkout.example.test/session", true)).toBe("https://checkout.example.test/session"); +}); + +it("uses the existing tab when there is no project draft to preserve", () => { + const open = vi.spyOn(window, "open"); + navigateToCheckout("https://checkout.example.test/session", false); + expect(window.location.href).toBe("https://checkout.example.test/session"); + expect(open).not.toHaveBeenCalled(); +}); diff --git a/apps/dashboard/src/lib/checkout-navigation.ts b/apps/dashboard/src/lib/checkout-navigation.ts index 2d73fd312..b3a1f5aee 100644 --- a/apps/dashboard/src/lib/checkout-navigation.ts +++ b/apps/dashboard/src/lib/checkout-navigation.ts @@ -1,19 +1,11 @@ -/** Reserve a tab inside the user's click so payment never discards a draft. - * The API validates hosted-payment URLs; blocked popups retain a manual link. */ -export function beginCheckoutNavigation(preserveProject: boolean) { - const tab = preserveProject ? window.open("about:blank", "_blank") : null; - if (tab) tab.opener = null; - return { - close: () => tab?.close(), - navigate(value: string) { - const url = new URL(value); - if (url.protocol !== "https:") throw new Error("Invalid checkout URL"); - if (preserveProject) { - if (tab && !tab.closed) tab.location.href = url.href; - } else { - window.location.href = url.href; - } - return url.href; - }, - }; +/** Open only a real payment URL. Blocked popups retain the visible checkout + * action; failed requests never leave blank tabs or discard project drafts. */ +export function navigateToCheckout(value: string, preserveProject: boolean) { + const url = new URL(value); + if (url.protocol !== "https:") throw new Error("Invalid checkout URL"); + if (preserveProject) { + try { window.open(url.href, "_blank", "noopener,noreferrer"); } + catch { /* Keep the validated manual checkout link when popups are refused. */ } + } else window.location.href = url.href; + return url.href; } diff --git a/docs/dashboard-design.md b/docs/dashboard-design.md index c71a2d330..10fa9354a 100644 --- a/docs/dashboard-design.md +++ b/docs/dashboard-design.md @@ -876,6 +876,14 @@ check retryable before starting the move. cancellation actions in the selected server's billing card, preserve retry identity after uncertain responses, and never replace the page with a loader. - Checkout returns verify payment, paid coverage and managed-server readiness separately. + Open the hosted URL only after checkout is ready; never reserve an empty browser tab. + Keep a full-width primary checkout action visible if the browser refuses the popup, + and preserve the project draft. Lock repeat submissions after a successful handoff. + Reopening Add Cloud space recovers an unfinished subscription before creating another + space; manual retries retain a customer-scoped creation key across modal dismissal. + Plans & billing shows a warning count for pending Cloud plans and Manage payment. + Reuse the organization-wide payment read in the hub and refresh warnings after mutations + and on return from checkout. Hide zero counts and reset private state on scope changes. Show the subscription welcome only when setup is complete. Keep preparation and failure notices compact and above the billing columns, with a recheck action and a link to the existing server Activity tab for logs and retry. A paid setup failure must never direct the customer to pay again. From 7c1b93365a5cd31e42ca5eb67a34c2ab64f0b248 Mon Sep 17 00:00:00 2001 From: Hydra Date: Sat, 14 Nov 2026 21:30:40 +0200 Subject: [PATCH 2/2] fix(billing): observe checkout fallbacks and update disconnect regression --- .../components/billing/PendingCheckoutsContext.tsx | 5 ++++- .../servers/managed/ManagedServerPurchase.tsx | 13 +++++++++---- .../src/hooks/cloud-resource-refresh.test.tsx | 6 ++---- apps/dashboard/src/lib/checkout-navigation.test.ts | 11 +++++++++-- apps/dashboard/src/lib/checkout-navigation.ts | 11 +++++++++-- 5 files changed, 33 insertions(+), 13 deletions(-) diff --git a/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx b/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx index c591eac03..d0fbed04f 100644 --- a/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx +++ b/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx @@ -1,5 +1,6 @@ "use client"; +import { reportCaughtError } from "@repo/core/diagnostics"; import { createContext, useCallback, @@ -115,7 +116,9 @@ function PendingCheckoutsState({ if (mounted.current && revision.current === request) setManagementPending(Boolean( state.pendingCheckout || state.change?.paymentUrl || subscriptionNeedsPayment(state.subscription?.status), )); - }).catch(() => {}); + }).catch(error => { + reportCaughtError(error, "dashboard/components/billing/PendingCheckoutsContext"); + }); } try { const result = await billingApi.listCheckouts(workspaceId); diff --git a/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx b/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx index 41b6bdad9..51eaa78de 100644 --- a/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx +++ b/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx @@ -1,5 +1,6 @@ "use client"; +import { reportCaughtError } from "@repo/core/diagnostics"; import { useEffect, useRef, useState } from "react"; import type { CloudWorkspaceSummary } from "@repo/contracts"; import { useI18n } from "@/components/i18n-provider"; @@ -106,9 +107,11 @@ function Purchase({ const storageKey = `openship:cloud-purchase:${scope}`; let key = checkoutIntent; if (!key) { - try { key = sessionStorage.getItem(storageKey) ?? undefined; } catch {} + try { key = sessionStorage.getItem(storageKey) ?? undefined; } + catch (error) { reportCaughtError(error, "dashboard/components/servers/managed/ManagedServerPurchase"); } if (!isCloudPurchaseIntent(key)) key = randomUUID(); - try { sessionStorage.setItem(storageKey, key); } catch {} + try { sessionStorage.setItem(storageKey, key); } + catch (error) { reportCaughtError(error, "dashboard/components/servers/managed/ManagedServerPurchase"); } } const create = (idempotencyKey: string) => { if (!mounted.current || owner.current !== scope) throw new Error("Purchase scope changed"); @@ -119,13 +122,15 @@ function Purchase({ catch (error) { if (checkoutIntent || getApiErrorCode(error) !== "CLOUD_WORKSPACE_PURCHASE_REMOVED") throw error; key = randomUUID(); - try { sessionStorage.setItem(storageKey, key); } catch {} + try { sessionStorage.setItem(storageKey, key); } + catch (error) { reportCaughtError(error, "dashboard/components/servers/managed/ManagedServerPurchase"); } server = await create(key); } if (!checkoutIntent && (server.planTierId !== "free" || server.resources)) { // The last purchase completed. This explicit Add space is a new purchase. key = randomUUID(); - try { sessionStorage.setItem(storageKey, key); } catch {} + try { sessionStorage.setItem(storageKey, key); } + catch (error) { reportCaughtError(error, "dashboard/components/servers/managed/ManagedServerPurchase"); } server = await create(key); } created.current = server; diff --git a/apps/dashboard/src/hooks/cloud-resource-refresh.test.tsx b/apps/dashboard/src/hooks/cloud-resource-refresh.test.tsx index a5ea2f0be..46973e557 100644 --- a/apps/dashboard/src/hooks/cloud-resource-refresh.test.tsx +++ b/apps/dashboard/src/hooks/cloud-resource-refresh.test.tsx @@ -107,8 +107,7 @@ it("discards server-rendered project settings and late services when the Cloud i it("does not open a checkout returned for a disconnected Cloud account", async () => { const old = deferred(); h.checkout.mockReturnValue(old.promise); - const popup = { close: vi.fn(), opener: null, location: { href: "about:blank" } }; - const open = vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window); + const open = vi.spyOn(window, "open").mockReturnValue(null); const started = vi.fn(); function Checkout() { const checkout = useCloudCheckout({ enabled: true, preserveProject: true, onCheckoutStarted: started }); @@ -121,8 +120,7 @@ it("does not open a checkout returned for a disconnected Cloud account", async ( await render("account-b", page); await act(async () => old.resolve({ data: { checkoutUrl: "https://checkout.stripe.com/old-account" } })); expect(host.textContent).toBe("Choose plan"); - expect(popup.location.href).toBe("about:blank"); - expect(popup.close).toHaveBeenCalledOnce(); + expect(open).not.toHaveBeenCalled(); expect(started).not.toHaveBeenCalled(); } finally { open.mockRestore(); } }); diff --git a/apps/dashboard/src/lib/checkout-navigation.test.ts b/apps/dashboard/src/lib/checkout-navigation.test.ts index f815161a0..d9dcf1cd1 100644 --- a/apps/dashboard/src/lib/checkout-navigation.test.ts +++ b/apps/dashboard/src/lib/checkout-navigation.test.ts @@ -2,7 +2,10 @@ import { afterEach, expect, it, vi } from "vitest"; import { navigateToCheckout } from "./checkout-navigation"; -afterEach(() => vi.restoreAllMocks()); +const diagnostics = vi.hoisted(() => ({ report: vi.fn() })); +vi.mock("@repo/core/diagnostics", () => ({ reportCaughtError: diagnostics.report })); + +afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks(); }); it.each(["javascript:alert(1)", "data:text/html,checkout", "http://checkout.example.test", ""])( "refuses an invalid payment destination before opening a tab: %s", value => { @@ -23,8 +26,12 @@ it("opens only the final URL without an opener or referrer, preserving the proje }); it("retains the validated fallback URL if the browser throws when refusing a popup", () => { - vi.spyOn(window, "open").mockImplementation(() => { throw new Error("Popups refused"); }); + vi.spyOn(window, "open").mockImplementation(() => { throw new Error("Popups refused: https://checkout.example.test/private-session"); }); expect(navigateToCheckout("https://checkout.example.test/session", true)).toBe("https://checkout.example.test/session"); + expect(diagnostics.report).toHaveBeenCalledExactlyOnceWith(expect.any(Error), "dashboard/lib/checkout-navigation"); + const reported = diagnostics.report.mock.calls[0][0] as Error; + expect(reported.message).toBe("Browser refused to open hosted checkout"); + expect(reported.message).not.toContain("private-session"); }); it("uses the existing tab when there is no project draft to preserve", () => { diff --git a/apps/dashboard/src/lib/checkout-navigation.ts b/apps/dashboard/src/lib/checkout-navigation.ts index b3a1f5aee..7c13e84bf 100644 --- a/apps/dashboard/src/lib/checkout-navigation.ts +++ b/apps/dashboard/src/lib/checkout-navigation.ts @@ -1,11 +1,18 @@ -/** Open only a real payment URL. Blocked popups retain the visible checkout +import { reportCaughtError } from "@repo/core/diagnostics"; + +/** The API validates payment hosts. Open only its final HTTPS URL. + * Blocked popups retain the visible checkout * action; failed requests never leave blank tabs or discard project drafts. */ export function navigateToCheckout(value: string, preserveProject: boolean) { const url = new URL(value); if (url.protocol !== "https:") throw new Error("Invalid checkout URL"); if (preserveProject) { try { window.open(url.href, "_blank", "noopener,noreferrer"); } - catch { /* Keep the validated manual checkout link when popups are refused. */ } + catch { + // Browser errors can embed the payment URL. Report no hosted-session data. + reportCaughtError(new Error("Browser refused to open hosted checkout"), "dashboard/lib/checkout-navigation"); + // Keep the validated manual action available when popups are refused. + } } else window.location.href = url.href; return url.href; }