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
5 changes: 0 additions & 5 deletions eslint-suppressions.json
Original file line number Diff line number Diff line change
Expand Up @@ -209,11 +209,6 @@
"count": 1
}
},
"src/platform/cloud/subscription/composables/useSubscription.ts": {
"comfy/no-new-error-throw": {
"count": 1
}
},
"src/platform/cloud/subscription/launchCancellationFlow.ts": {
"comfy/no-new-error-throw": {
"count": 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,23 @@ import { assert, beforeEach, describe, expect, it, vi } from 'vitest'
import { computed } from 'vue'
import { createI18n } from 'vue-i18n'

import { useAuthActions } from '@/composables/auth/useAuthActions'
import { useBillingContext } from '@/composables/billing/useBillingContext'
import { useBillingRouting } from '@/composables/billing/useBillingRouting'
import { useSubscription } from '@/platform/cloud/subscription/composables/useSubscription'
import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog'
import { useTelemetry } from '@/platform/telemetry'
import { AuthStoreError } from '@/stores/authStore'
import { AuthStoreError, useAuthStore } from '@/stores/authStore'
import { useDialogStore } from '@/stores/dialogStore'

import TopUpCreditsDialogContentLegacy from './TopUpCreditsDialogContentLegacy.vue'

const PENDING_TOPUP_KEY = 'pending_topup_timestamp'

const mockToastAdd = vi.fn()

const mockShouldUseWorkspaceBilling = vi.hoisted(() => ({ value: false }))

vi.mock(import('@/composables/auth/useAuthActions'))
vi.mock(import('@/composables/billing/useBillingContext'))

vi.mock(import('@/composables/billing/useBillingRouting'))

Expand All @@ -28,11 +30,6 @@ vi.mock(import('@/platform/settings/composables/useSettingsDialog'))

vi.mock(import('@/platform/telemetry'))

const mockClearPendingTopup = vi.hoisted(() => vi.fn())
vi.mock<unknown>(import('@/composables/billing/usePendingTopup'), () => ({
usePendingTopup: () => ({ clearPendingTopup: mockClearPendingTopup })
}))

vi.mock<unknown>(
import('primevue/usetoast'), // oxlint-disable-line comfy/no-primevue-imports

Expand Down Expand Up @@ -98,41 +95,47 @@ async function clickBuyCredits() {

describe('TopUpCreditsDialogContentLegacy', () => {
beforeEach(() => {
localStorage.clear()
useBillingRouting().shouldUseWorkspaceBilling = computed(
() => mockShouldUseWorkspaceBilling.value
)
vi.mocked(useSubscription().isSubscriptionEnabled).mockReturnValue(true)
mockShouldUseWorkspaceBilling.value = false
const billingContext = useBillingContext()
vi.mocked(useBillingContext).mockReturnValue(billingContext)
billingContext.canAccessSubscriptionFeatures = computed(() => true)
vi.mocked(useAuthStore().initiateCreditPurchase).mockResolvedValue({
checkout_url: 'https://checkout.stripe.test'
})
vi.spyOn(window, 'open').mockImplementation(() => window)
})

it('shows Plan & Credits after a successful Cloud purchase', async () => {
vi.mocked(useAuthActions().purchaseCreditsDirect).mockResolvedValue(
undefined
)

renderDialog()
await clickBuyCredits()

expect(useAuthActions().purchaseCreditsDirect).toHaveBeenCalledWith(50)
expect(useAuthStore().initiateCreditPurchase).toHaveBeenCalledWith({
amount_micros: 50_000_000,
currency: 'usd'
})
expect(useDialogStore().closeDialog).toHaveBeenCalled()
expect(useSettingsDialog().show).toHaveBeenCalledWith('workspace')
expect(mockClearPendingTopup).not.toHaveBeenCalled()
expect(localStorage.getItem(PENDING_TOPUP_KEY)).not.toBeNull()
})

it('clears the pending top-up marker when the user closes the dialog', async () => {
localStorage.setItem(PENDING_TOPUP_KEY, Date.now().toString())

renderDialog()
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Close' }))

expect(mockClearPendingTopup).toHaveBeenCalled()
expect(localStorage.getItem(PENDING_TOPUP_KEY)).toBeNull()
expect(useDialogStore().closeDialog).toHaveBeenCalled()
})

it('shows Plan & Credits when no billing rail is active', async () => {
vi.mocked(useSubscription().isSubscriptionEnabled).mockReturnValue(false)
vi.mocked(useAuthActions().purchaseCreditsDirect).mockResolvedValue(
undefined
)

renderDialog()
await clickBuyCredits()
Expand All @@ -142,9 +145,6 @@ describe('TopUpCreditsDialogContentLegacy', () => {

it('shows the workspace settings panel when workspace billing is active', async () => {
mockShouldUseWorkspaceBilling.value = true
vi.mocked(useAuthActions().purchaseCreditsDirect).mockResolvedValue(
undefined
)

renderDialog()
await clickBuyCredits()
Expand All @@ -153,7 +153,7 @@ describe('TopUpCreditsDialogContentLegacy', () => {
})

it('tracks the failure and surfaces a toast when the purchase rejects', async () => {
vi.mocked(useAuthActions().purchaseCreditsDirect).mockRejectedValue(
vi.mocked(useAuthStore().initiateCreditPurchase).mockRejectedValue(
new Error('declined for person@example.com')
)

Expand All @@ -176,12 +176,8 @@ describe('TopUpCreditsDialogContentLegacy', () => {
})

it('categorizes an auth-store rejection with an HTTP status via the shared classifier', async () => {
const authStoreError = new AuthStoreError(
'backend rejected the purchase',
400
)
vi.mocked(useAuthActions().purchaseCreditsDirect).mockRejectedValue(
authStoreError
vi.mocked(useAuthStore().initiateCreditPurchase).mockRejectedValue(
new AuthStoreError('backend rejected the purchase', 400)
)

renderDialog()
Expand All @@ -196,9 +192,8 @@ describe('TopUpCreditsDialogContentLegacy', () => {
})

it('categorizes an auth-store rejection with no HTTP status as a network failure', async () => {
const authStoreError = new AuthStoreError('offline')
vi.mocked(useAuthActions().purchaseCreditsDirect).mockRejectedValue(
authStoreError
vi.mocked(useAuthStore().initiateCreditPurchase).mockRejectedValue(
new AuthStoreError('offline')
)

renderDialog()
Expand All @@ -215,14 +210,19 @@ describe('TopUpCreditsDialogContentLegacy', () => {
it.for([
{
name: 'a checkout that opens stays pending',
purchase: () => Promise.resolve(),
purchase: () =>
Promise.resolve({ checkout_url: 'https://checkout.stripe.test' }),
openedWindow: window,
expectedEvents: [
[{ operation: 'topup', stage: 'started', outcome: 'pending' }]
]
],
markerKept: true,
settingsCalls: [['workspace']]
},
{
name: 'a rejected purchase closes as failed',
purchase: () => Promise.reject(new Error('declined')),
openedWindow: window,
expectedEvents: [
[{ operation: 'topup', stage: 'started', outcome: 'pending' }],
[
Expand All @@ -233,14 +233,43 @@ describe('TopUpCreditsDialogContentLegacy', () => {
failure_category: 'unknown'
}
]
]
],
markerKept: false,
settingsCalls: []
},
{
name: 'a checkout tab the browser blocks closes as a popup-blocked failure',
purchase: () =>
Promise.resolve({ checkout_url: 'https://checkout.stripe.test' }),
openedWindow: null,
expectedEvents: [
[{ operation: 'topup', stage: 'started', outcome: 'pending' }],
[
{
operation: 'topup',
stage: 'failed',
outcome: 'failure',
failure_category: 'redirect',
error_code: 'payment_popup_blocked'
}
]
],
markerKept: false,
settingsCalls: []
}
])(
'opens every purchase attempt with one started event: $name',
async ({ purchase, expectedEvents }) => {
vi.mocked(useAuthActions().purchaseCreditsDirect).mockImplementation(
async ({
purchase,
openedWindow,
expectedEvents,
markerKept,
settingsCalls
}) => {
vi.mocked(useAuthStore().initiateCreditPurchase).mockImplementation(
purchase
)
vi.spyOn(window, 'open').mockImplementation(() => openedWindow)

renderDialog()
await clickBuyCredits()
Expand All @@ -250,11 +279,29 @@ describe('TopUpCreditsDialogContentLegacy', () => {
expect(vi.mocked(telemetry.trackBillingEvent).mock.calls).toEqual(
expectedEvents
)
expect(localStorage.getItem(PENDING_TOPUP_KEY) !== null).toBe(markerKept)
expect(vi.mocked(useSettingsDialog().show).mock.calls).toEqual(
settingsCalls
)
}
)

it('sends no started event when the customer cannot buy credits', async () => {
useBillingContext().canAccessSubscriptionFeatures = computed(() => false)

renderDialog()
await clickBuyCredits()

const telemetry = useTelemetry()
assert.exists(telemetry)
expect(vi.mocked(telemetry.trackBillingEvent).mock.calls).toEqual([])
expect(useAuthStore().initiateCreditPurchase).not.toHaveBeenCalled()
expect(localStorage.getItem(PENDING_TOPUP_KEY)).toBeNull()
expect(useSettingsDialog().show).toHaveBeenCalledWith('workspace')
})

it('uses the same bounded category when the rejection is not an Error', async () => {
vi.mocked(useAuthActions().purchaseCreditsDirect).mockRejectedValue('boom')
vi.mocked(useAuthStore().initiateCreditPurchase).mockRejectedValue('boom')

renderDialog()
await clickBuyCredits()
Expand All @@ -267,3 +314,4 @@ describe('TopUpCreditsDialogContentLegacy', () => {
})
})
})
vi.mock(import('firebase/auth'))
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ import { useAuthActions } from '@/composables/auth/useAuthActions'
import { useExternalLink } from '@/composables/useExternalLink'
import { useTelemetry } from '@/platform/telemetry'
import { usePendingTopup } from '@/composables/billing/usePendingTopup'
import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFailureCategory'
import { describeBillingFailure } from '@/platform/telemetry/utils/billingFailureCategory'
import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog'
import { useDialogStore } from '@/stores/dialogStore'
import { cn } from '@comfyorg/tailwind-utils'
Expand Down Expand Up @@ -252,11 +252,13 @@ async function handleBuy() {
loading.value = true
try {
telemetry?.trackApiCreditTopupButtonPurchaseClicked(payAmount.value)
telemetry?.trackBillingEvent({
operation: 'topup',
stage: 'started',
outcome: 'pending'
})
if (authActions.canPurchaseCredits()) {
telemetry?.trackBillingEvent({
operation: 'topup',
stage: 'started',
outcome: 'pending'
})
}
await authActions.purchaseCreditsDirect(payAmount.value)

// Close top-up dialog (keep tracking) and open Plan & Credits to show the
Expand All @@ -276,7 +278,7 @@ async function handleBuy() {
operation: 'topup',
stage: 'failed',
outcome: 'failure',
failure_category: categorizeBillingApiError(error)
...describeBillingFailure(error)
})
toast.add({
severity: 'error',
Expand Down
40 changes: 27 additions & 13 deletions src/components/dialog/content/setting/UsageLogsTable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ vi.mock(import('@/services/customerEventsService'))

vi.mock(import('@/platform/telemetry'))

const CONFIRMED_AT_MS = Date.parse('2024-06-15T12:30:00Z')

const mockPendingTopup = vi.hoisted(() => ({
isPendingTopupCompleted: vi.fn().mockReturnValue(true)
consumeCompletedTopup: vi.fn().mockReturnValue({ startedAtMs: Date.now() })
}))
vi.mock<unknown>(import('@/composables/billing/usePendingTopup'), () => ({
usePendingTopup: () => mockPendingTopup
Expand Down Expand Up @@ -392,7 +394,9 @@ describe('UsageLogsTable', () => {
useBillingRouting().shouldUseWorkspaceBilling = computed(
() => workspaceBilling.value
)
mockPendingTopup.isPendingTopupCompleted.mockReturnValue(true)
mockPendingTopup.consumeCompletedTopup.mockReturnValue({
startedAtMs: Date.now()
})
let resolveLegacy!: (value: ReturnType<typeof makeEventsResponse>) => void
vi.mocked(useCustomerEventsService().getMyEvents).mockReturnValue(
new Promise((resolve) => {
Expand Down Expand Up @@ -428,7 +432,7 @@ describe('UsageLogsTable', () => {
resolveLegacy(legacyResponse)

await waitFor(() => {
expect(mockPendingTopup.isPendingTopupCompleted).toHaveBeenCalledWith(
expect(mockPendingTopup.consumeCompletedTopup).toHaveBeenCalledWith(
legacyResponse.events
)
expect(useTelemetry()?.trackApiCreditTopupSucceeded).toHaveBeenCalled()
Expand All @@ -437,21 +441,29 @@ describe('UsageLogsTable', () => {

it.for([
{
name: 'a completed legacy top-up closes as succeeded',
completed: true,
name: 'a completed legacy top-up closes as succeeded, measured from its start',
completedTopup: { startedAtMs: CONFIRMED_AT_MS - 90_000 },
expectedEvents: [
[{ operation: 'topup', stage: 'succeeded', outcome: 'success' }]
[
{
operation: 'topup',
stage: 'succeeded',
outcome: 'success',
duration_ms: 90_000
}
]
]
},
{
name: 'no completed top-up reports nothing',
completed: false,
completedTopup: null,
expectedEvents: []
}
])(
'reports top-up completion to the billing funnel: $name',
async ({ completed, expectedEvents }) => {
mockPendingTopup.isPendingTopupCompleted.mockReturnValue(completed)
async ({ completedTopup, expectedEvents }) => {
vi.spyOn(Date, 'now').mockReturnValue(CONFIRMED_AT_MS)
mockPendingTopup.consumeCompletedTopup.mockReturnValue(completedTopup)

await renderLoaded()

Expand All @@ -464,11 +476,11 @@ describe('UsageLogsTable', () => {
)

it('skips top-up telemetry when no completion is pending', async () => {
mockPendingTopup.isPendingTopupCompleted.mockReturnValue(false)
mockPendingTopup.consumeCompletedTopup.mockReturnValue(null)

await renderLoaded()

expect(mockPendingTopup.isPendingTopupCompleted).toHaveBeenCalledWith(
expect(mockPendingTopup.consumeCompletedTopup).toHaveBeenCalledWith(
mockEventsResponse.events
)
expect(
Expand Down Expand Up @@ -628,11 +640,13 @@ describe('UsageLogsTable', () => {

it('runs top-up completion telemetry off the reader page', async () => {
onTheRail()
mockPendingTopup.isPendingTopupCompleted.mockReturnValue(true)
mockPendingTopup.consumeCompletedTopup.mockReturnValue({
startedAtMs: Date.now()
})

await renderLoaded()

expect(mockPendingTopup.isPendingTopupCompleted).toHaveBeenCalledWith(
expect(mockPendingTopup.consumeCompletedTopup).toHaveBeenCalledWith(
railResponse.events
)
expect(useTelemetry()?.trackApiCreditTopupSucceeded).toHaveBeenCalled()
Expand Down
Loading
Loading