diff --git a/apps/code/src/renderer/features/settings/components/sections/PlanUsageSettings.tsx b/apps/code/src/renderer/features/settings/components/sections/PlanUsageSettings.tsx index 9046e271b..e36c1460f 100644 --- a/apps/code/src/renderer/features/settings/components/sections/PlanUsageSettings.tsx +++ b/apps/code/src/renderer/features/settings/components/sections/PlanUsageSettings.tsx @@ -1,4 +1,4 @@ -import { getAuthenticatedClient } from "@features/auth/hooks/authClient"; +import { useSwitchOrgMutation } from "@features/auth/hooks/authMutations"; import { useAuthStateValue } from "@features/auth/hooks/authQueries"; import { TokenSpendAnalysisBanner } from "@features/billing/components/TokenSpendAnalysisBanner"; import { useUsage } from "@features/billing/hooks/useUsage"; @@ -34,21 +34,6 @@ const log = logger.scope("plan-usage"); const SPEND_ANALYSIS_FLAG = "posthog-code-spend-analysis"; -async function openBillingPage(orgId: string | null): Promise { - if (orgId) { - try { - const client = await getAuthenticatedClient(); - if (client) { - await client.switchOrganization(orgId); - } - } catch (err) { - log.warn("Failed to switch org before opening billing", err); - } - } - const url = getBillingUrl(); - if (url) window.open(url, "_blank"); -} - export function PlanUsageSettings() { const { seat, @@ -65,7 +50,34 @@ export function PlanUsageSettings() { const { fetchSeat, upgradeToPro, cancelSeat, reactivateSeat, clearError } = useSeatStore(); const cloudRegion = useAuthStateValue((state) => state.cloudRegion); + const currentOrgId = useAuthStateValue((state) => state.currentOrgId); + const switchOrgMutation = useSwitchOrgMutation(); const billingUrl = getBillingUrl(cloudRegion); + + async function switchOrgAndRefreshSeat(orgId: string): Promise { + await switchOrgMutation.mutateAsync(orgId); + await fetchSeat({ autoProvision: true }); + } + + async function openBillingPage(orgId: string | null): Promise { + if (orgId && orgId !== currentOrgId) { + try { + await switchOrgAndRefreshSeat(orgId); + } catch (err) { + log.warn("Failed to switch org before opening billing", err); + return; + } + } + if (billingUrl) window.open(billingUrl, "_blank"); + } + + async function switchToBillingOrg(orgId: string): Promise { + try { + await switchOrgAndRefreshSeat(orgId); + } catch (err) { + log.warn("Failed to switch to billing org", err); + } + } const redirectFullUrl = redirectUrl ? (getPostHogUrl(redirectUrl, cloudRegion) ?? billingUrl) : null; @@ -177,10 +189,37 @@ export function PlanUsageSettings() { - - You have a Pro plan on{" "} - {seat.organization_name}. Usage on this - page reflects your current organization. + + + + You have a Pro plan on{" "} + {seat.organization_name}. Usage on + this page reflects your current organization. + + {billingOrgId && ( + + + {switchOrgMutation.isError && ( + + Switching failed. Try again or switch from the sidebar. + + )} + + )} + )}