Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/composables/billing/__mocks__/useBillingContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ function createBillingContextMock(): BillingContext {
fetchPlans: vi.fn(async () => {}),
requireActiveSubscription: vi.fn(async () => {}),
showSubscriptionDialog: vi.fn(),
reconcileSubscriptionSuccess: vi.fn(async () => {})
reconcileSubscriptionSuccess: vi.fn(async () => {}),
readCheckoutOperation: vi.fn(async () => false)
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/composables/billing/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,8 @@ export interface BillingState {
export interface BillingContext extends BillingState, BillingActions {
type: ComputedRef<BillingType>
reconcileSubscriptionSuccess: () => Promise<void>
/** Reads the checkout rail's status; true once its pending operation is adopted. */
readCheckoutOperation: () => Promise<boolean>
/**
* True when the active team workspace is still on a pre-credit-slider
* (legacy) per-member tier plan, which keeps the old team pricing table.
Expand Down
23 changes: 23 additions & 0 deletions src/composables/billing/useBillingContext.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -519,6 +519,29 @@ describe('useBillingContext', () => {
expect(vi.mocked(useAuthStore().fetchBalance)).not.toHaveBeenCalled()
})

it.for([
{ pending: 'op-1', found: true },
{ pending: undefined, found: false }
])(
'finds an operation the server reports after the first read (pending: $pending)',
async ({ pending, found }) => {
const context = useBillingContext()
await vi.waitFor(() =>
expect(workspaceApi.getBillingStatus).toHaveBeenCalled()
)
vi.clearAllMocks()
mockBillingStatus.value = {
...DEFAULT_BILLING_STATUS,
pending_billing_op_id: pending
}

await expect(context.readCheckoutOperation()).resolves.toBe(found)

expect(workspaceApi.getBillingStatus).toHaveBeenCalledOnce()
expect(workspaceApi.getBillingBalance).not.toHaveBeenCalled()
}
)

it('rejects topup amounts that are not positive whole-dollar cents', async () => {
const { topup } = useBillingContext()
await expect(topup(550)).rejects.toThrow()
Expand Down
21 changes: 18 additions & 3 deletions src/composables/billing/useBillingContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import type {
} from './types'
import { useBillingRouting } from './useBillingRouting'
import { useLegacyBilling } from './useLegacyBilling'
import type { WorkspaceBilling } from '@/platform/workspace/composables/useWorkspaceBilling'
import { useWorkspaceBilling } from '@/platform/workspace/composables/useWorkspaceBilling'

// Legacy per-member team plans use a hyphenated `team-{tier}-{cycle}` slug; the
Expand Down Expand Up @@ -88,9 +89,7 @@ function useBillingContextInternal(): BillingContext {
const legacyBillingRef = shallowRef<(BillingState & BillingActions) | null>(
null
)
const workspaceBillingRef = shallowRef<
(BillingState & BillingActions) | null
>(null)
const workspaceBillingRef = shallowRef<WorkspaceBilling | null>(null)

const getLegacyBilling = () => {
if (!legacyBillingRef.value) {
Expand Down Expand Up @@ -293,6 +292,21 @@ function useBillingContextInternal(): BillingContext {
await account.fetchBalance()
}

/**
* Reads the checkout rail's status, which resumes any operation the server
* reports pending. True once that operation was adopted, so a caller
* watching for a payment taken elsewhere can hand off to its own polling.
*/
async function readCheckoutOperation(): Promise<boolean> {
const checkout = checkoutContext.value
const workspace = workspaceBillingRef.value
if (workspace === null || checkout !== workspace) {
await checkout.fetchStatus()
return false
}
return workspace.readAndAdoptPendingOperation()
}

async function subscribe(planSlug: string, options?: SubscribeOptions) {
return checkoutContext.value.subscribe(planSlug, options)
}
Expand Down Expand Up @@ -372,6 +386,7 @@ function useBillingContextInternal(): BillingContext {
fetchStatus,
fetchBalance,
reconcileSubscriptionSuccess,
readCheckoutOperation,
subscribe,
previewSubscribe,
manageSubscription,
Expand Down
116 changes: 113 additions & 3 deletions src/platform/workspace/billing/openHostedBillingTab.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

const mockHostedBillingRoute = vi.hoisted(() => vi.fn())
vi.mock<unknown>(
Expand All @@ -17,10 +17,12 @@ vi.mock<unknown>(import('@/composables/useFeatureFlags'), () => ({

const mockFetchStatus = vi.hoisted(() => vi.fn(async () => {}))
const mockFetchBalance = vi.hoisted(() => vi.fn(async () => {}))
const mockReadOperation = vi.hoisted(() => vi.fn(async () => false))
vi.mock<unknown>(import('@/composables/billing/useBillingContext'), () => ({
useBillingContext: () => ({
fetchStatus: mockFetchStatus,
fetchBalance: mockFetchBalance
fetchBalance: mockFetchBalance,
readCheckoutOperation: mockReadOperation
})
}))

Expand All @@ -43,7 +45,10 @@ vi.mock<unknown>(

import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore'

import { openHostedBillingTab } from './openHostedBillingTab'
import {
disarmHostedBillingReturnRefresh,
openHostedBillingTab
} from './openHostedBillingTab'

const BILLING_WEB_ROUTE = {
kind: 'billing_web' as const,
Expand Down Expand Up @@ -165,4 +170,109 @@ describe('openHostedBillingTab', () => {
expect(mockStop.mock.calls.length).toBe(stopCallsAfterFirstOpen + 1)
expect(mockRegisterRefreshOnReturn).toHaveBeenCalledTimes(2)
})

describe('while a hosted payment tab is open', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.spyOn(window, 'open').mockReturnValue(fakeTab())
mockReadOperation.mockReset().mockResolvedValue(false)
})

afterEach(() => {
disarmHostedBillingReturnRefresh()
})

it.for(['checkout', 'subscription'] as const)(
're-reads the checkout status so the app picks up the payment %s starts',
async (intent) => {
openHostedBillingTab(intent)

await vi.advanceTimersByTimeAsync(4_000)
expect(mockReadOperation).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(4_000)
expect(mockReadOperation).toHaveBeenCalledTimes(2)
}
)

it('hands off once a read finds the pending operation', async () => {
mockReadOperation.mockResolvedValueOnce(false).mockResolvedValueOnce(true)
openHostedBillingTab('checkout')

await vi.advanceTimersByTimeAsync(60_000)

expect(mockReadOperation).toHaveBeenCalledTimes(2)
})

it('stops watching once the workspace the tab was opened for is left', async () => {
openHostedBillingTab('checkout')
await vi.advanceTimersByTimeAsync(4_000)
expect(mockReadOperation).toHaveBeenCalledOnce()

Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'ws-other' })
await vi.advanceTimersByTimeAsync(60_000)

expect(mockReadOperation).toHaveBeenCalledOnce()
})

it('does not watch for an intent that starts no payment', async () => {
openHostedBillingTab('payment-methods')

await vi.advanceTimersByTimeAsync(60_000)

expect(mockReadOperation).not.toHaveBeenCalled()
})

it('reads until fifteen minutes pass, then stops', async () => {
openHostedBillingTab('checkout')

await vi.advanceTimersByTimeAsync(15 * 60_000 - 1)
const readsBeforeExpiry = mockReadOperation.mock.calls.length
expect(readsBeforeExpiry).toBeGreaterThan(200)

await vi.advanceTimersByTimeAsync(60_000)
expect(mockReadOperation).toHaveBeenCalledTimes(readsBeforeExpiry)
})

it('stops watching when disarmed', async () => {
openHostedBillingTab('checkout')
disarmHostedBillingReturnRefresh()

await vi.advanceTimersByTimeAsync(60_000)

expect(mockReadOperation).not.toHaveBeenCalled()
})

it('skips a tick while the previous read is still in flight', async () => {
let settle: (found: boolean) => void = () => {}
mockReadOperation.mockImplementationOnce(
() => new Promise<boolean>((resolve) => (settle = resolve))
)
openHostedBillingTab('checkout')

await vi.advanceTimersByTimeAsync(8_000)
expect(mockReadOperation).toHaveBeenCalledOnce()

settle(false)
await vi.advanceTimersByTimeAsync(4_000)
expect(mockReadOperation).toHaveBeenCalledTimes(2)
})

it('keeps watching after a read fails', async () => {
mockReadOperation.mockRejectedValueOnce(new Error('status read failed'))
openHostedBillingTab('checkout')

await vi.advanceTimersByTimeAsync(8_000)

expect(mockReadOperation).toHaveBeenCalledTimes(2)
})

it('stops watching when a tab that starts no payment opens next', async () => {
openHostedBillingTab('checkout')
openHostedBillingTab('payment-methods')

await vi.advanceTimersByTimeAsync(60_000)

expect(mockReadOperation).not.toHaveBeenCalled()
})
})
})
63 changes: 60 additions & 3 deletions src/platform/workspace/billing/openHostedBillingTab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,82 @@ function openDisownedTab(url: URL): boolean {
}

let stopReturnRefresh: (() => void) | null = null
let stopOperationWatch: (() => void) | null = null

export function disarmHostedBillingReturnRefresh(): void {
stopReturnRefresh?.()
stopReturnRefresh = null
stopOperationWatch?.()
stopOperationWatch = null
}

function armReturnRefresh(): void {
const OPERATION_INTENTS: ReadonlySet<BillingIntent> = new Set([
'checkout',
'subscription'
])
const OPERATION_POLL_MS = 4_000
const OPERATION_WATCH_MS = 15 * 60_000

/**
* A payment billing-web takes never pushes back to this tab, but a status read
* resumes the operation the server reports pending, and that operation then
* polls itself and shows the same progress and outcome toasts the embedded
* checkout shows. This reads until one is found, for the workspace the tab
* was opened for only. A read still in flight skips the tick, and a failed
* read waits for the next one.
*/
function watchForHostedOperation(
readOperation: () => Promise<boolean>,
workspaceId: string | undefined
) {
const workspaceStore = useTeamWorkspaceStore()
const startedAt = Date.now()
let reading = false
const timer = setInterval(() => {
if (
Date.now() - startedAt >= OPERATION_WATCH_MS ||
(workspaceStore.activeWorkspaceId ?? undefined) !== workspaceId
) {
clearInterval(timer)
return
}
if (reading) return
reading = true
void readOperation()
.then((found) => {
if (found) clearInterval(timer)
})
.catch(() => undefined)
.finally(() => {
reading = false
})
}, OPERATION_POLL_MS)
return () => clearInterval(timer)
}

function armReturnRefresh(
intent: BillingIntent,
workspaceId: string | undefined
): void {
disarmHostedBillingReturnRefresh()
// Resolved inside the call, not at module scope: useBillingContext ->
// useWorkspaceBilling -> this module would otherwise dereference the
// shared context before its state is constructed.
const { fetchStatus, fetchBalance } = useBillingContext()
const { fetchStatus, fetchBalance, readCheckoutOperation } =
useBillingContext()
stopReturnRefresh = registerRefreshOnReturn(() =>
Promise.allSettled([
fetchStatus(),
fetchBalance(),
useBillingCapabilities().refresh()
])
)
if (OPERATION_INTENTS.has(intent)) {
stopOperationWatch = watchForHostedOperation(
readCheckoutOperation,
workspaceId
)
}
}

export type HostedBillingTabOutcome = 'opened' | 'unavailable' | 'blocked'
Expand All @@ -77,7 +134,7 @@ export function openHostedBillingTabOutcome(
})
if (route.kind !== 'billing_web') return 'unavailable'
if (!openDisownedTab(route.url)) return 'blocked'
armReturnRefresh()
armReturnRefresh(intent, workspaceId)
return 'opened'
}

Expand Down
14 changes: 7 additions & 7 deletions src/platform/workspace/billing/refreshOnReturn.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it, onTestFinished, vi } from 'vitest'

import { registerRefreshOnReturn } from './refreshOnReturn'

describe('registerRefreshOnReturn', () => {
it('fires on window focus', () => {
const refresh = vi.fn(async () => {})
registerRefreshOnReturn(refresh)
onTestFinished(registerRefreshOnReturn(refresh))

window.dispatchEvent(new Event('focus'))

Expand All @@ -14,7 +14,7 @@ describe('registerRefreshOnReturn', () => {

it('fires on a visible visibilitychange', () => {
const refresh = vi.fn(async () => {})
registerRefreshOnReturn(refresh)
onTestFinished(registerRefreshOnReturn(refresh))

document.dispatchEvent(new Event('visibilitychange'))

Expand All @@ -25,7 +25,7 @@ describe('registerRefreshOnReturn', () => {
const refresh = vi.fn(async () => {})
const visibilitySpy = vi.spyOn(document, 'visibilityState', 'get')
visibilitySpy.mockReturnValue('hidden')
registerRefreshOnReturn(refresh)
onTestFinished(registerRefreshOnReturn(refresh))

document.dispatchEvent(new Event('visibilitychange'))
expect(refresh).not.toHaveBeenCalled()
Expand Down Expand Up @@ -56,7 +56,7 @@ describe('registerRefreshOnReturn', () => {

it('refreshes again on a later return, so a return before the hosted tab finishes does not spend it', async () => {
const { refresh, settle } = held()
registerRefreshOnReturn(refresh)
onTestFinished(registerRefreshOnReturn(refresh))

come()
await settle(0)
Expand All @@ -68,7 +68,7 @@ describe('registerRefreshOnReturn', () => {

it('coalesces the focus and visibilitychange of one return into one refresh', async () => {
const { refresh, settle } = held()
registerRefreshOnReturn(refresh)
onTestFinished(registerRefreshOnReturn(refresh))

come()
document.dispatchEvent(new Event('visibilitychange'))
Expand All @@ -80,7 +80,7 @@ describe('registerRefreshOnReturn', () => {

it('runs one trailing refresh for a return that arrives while a refresh is in flight', async () => {
const { refresh, settle } = held()
registerRefreshOnReturn(refresh)
onTestFinished(registerRefreshOnReturn(refresh))

come()
leave()
Expand Down
Loading
Loading