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
117 changes: 117 additions & 0 deletions src/components/dialog/content/setting/CreditsPanel.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { render, screen } from '@testing-library/vue'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { defineComponent, h, nextTick } from 'vue'
import { createI18n } from 'vue-i18n'

import type { BalanceInfo } from '@/composables/billing/types'

import CreditsPanel from './CreditsPanel.vue'

const billingMocks = vi.hoisted(() => ({
balance: { value: null as BalanceInfo | null },
manageSubscription: vi.fn()
}))
vi.mock('@/composables/billing/useBillingContext', async () => {
const { ref } = await import('vue')
const balance = ref<BalanceInfo | null>(null)
Object.defineProperty(billingMocks, 'balance', { get: () => balance })
return {
useBillingContext: () => ({
balance,
manageSubscription: billingMocks.manageSubscription
})
}
})

const refreshActivity = vi.hoisted(() => vi.fn())
vi.mock('./UsageLogsTable.vue', async () => {
const { defineComponent, h } = await import('vue')
return {
default: defineComponent({
setup(_props, { expose }) {
expose({ refresh: refreshActivity })
return () => h('div', { 'data-testid': 'usage-logs-table' })
}
})
}
})

vi.mock('@/platform/cloud/subscription/components/CreditsTile.vue', () => ({
default: defineComponent({ setup: () => () => h('div') })
}))

vi.mock('@/platform/telemetry', () => ({
useTelemetry: () => ({ trackHelpResourceClicked: vi.fn() })
}))

vi.mock('@/stores/commandStore', () => ({
useCommandStore: () => ({ execute: vi.fn() })
}))

vi.mock('@/composables/useExternalLink', () => ({
useExternalLink: () => ({
buildDocsUrl: () => 'https://docs.comfy.org',
docsPaths: { partnerNodesPricing: '/partner-nodes' }
})
}))

const i18n = createI18n({
legacy: false,
locale: 'en',
messages: {
en: {
credits: {
credits: 'Credits',
activity: 'Activity',
invoiceHistory: 'Invoice History',
faqs: 'FAQs',
messageSupport: 'Message Support'
},
subscription: { partnerNodesCredits: 'Partner Nodes Credits' }
}
}
})

function makeBalance(amountMicros: number): BalanceInfo {
return {
amountMicros,
currency: 'usd',
effectiveBalanceMicros: amountMicros,
prepaidBalanceMicros: 0,
cloudCreditBalanceMicros: 0
}
}

describe('CreditsPanel', () => {
beforeEach(() => {
billingMocks.balance.value = null
})

function renderComponent() {
return render(CreditsPanel, {
global: { plugins: [i18n], stubs: { Divider: true } }
})
}

it('opens the billing portal for the active billing rail', async () => {
const user = userEvent.setup()
renderComponent()

await user.click(screen.getByRole('button', { name: /Invoice History/ }))

expect(billingMocks.manageSubscription).toHaveBeenCalledOnce()
})

it('refreshes activity on a balance change but not on first hydration', async () => {
renderComponent()

billingMocks.balance.value = makeBalance(5000)
await nextTick()
expect(refreshActivity).not.toHaveBeenCalled()

billingMocks.balance.value = makeBalance(9000)
await nextTick()
expect(refreshActivity).toHaveBeenCalledOnce()
})
})
20 changes: 7 additions & 13 deletions src/components/dialog/content/setting/CreditsPanel.vue
Original file line number Diff line number Diff line change
Expand Up @@ -65,36 +65,30 @@ import { ref, watch } from 'vue'

import UsageLogsTable from '@/components/dialog/content/setting/UsageLogsTable.vue'
import Button from '@/components/ui/button/Button.vue'
import { useAuthActions } from '@/composables/auth/useAuthActions'
import { useBillingContext } from '@/composables/billing/useBillingContext'
import { useExternalLink } from '@/composables/useExternalLink'
import CreditsTile from '@/platform/cloud/subscription/components/CreditsTile.vue'
import { useTelemetry } from '@/platform/telemetry'
import { useAuthStore } from '@/stores/authStore'
import { useCommandStore } from '@/stores/commandStore'

const { embedded = false } = defineProps<{
embedded?: boolean
}>()

const { buildDocsUrl, docsPaths } = useExternalLink()
const authStore = useAuthStore()
const authActions = useAuthActions()
const { balance, manageSubscription } = useBillingContext()
const commandStore = useCommandStore()
const telemetry = useTelemetry()

const usageLogsTableRef = ref<InstanceType<typeof UsageLogsTable> | null>(null)

watch(
() => authStore.lastBalanceUpdateTime,
(newTime, oldTime) => {
if (newTime && newTime !== oldTime && usageLogsTableRef.value) {
void usageLogsTableRef.value.refresh()
}
}
)
watch(balance, (next, previous) => {
if (!next || !previous) return
void usageLogsTableRef.value?.refresh()
})

const handleCreditsHistoryClick = async () => {
await authActions.accessBillingPortal()
await manageSubscription()
}

const handleMessageSupport = async () => {
Expand Down
56 changes: 27 additions & 29 deletions src/components/dialog/content/setting/UsageLogsTable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { createTestingPinia } from '@pinia/testing'
import PrimeVue from 'primevue/config'
import Tooltip from 'primevue/tooltip'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { nextTick } from 'vue'
import { createI18n } from 'vue-i18n'

import { render, screen, waitFor } from '@testing-library/vue'
Expand Down Expand Up @@ -91,22 +91,6 @@ const globalConfig = {
directives: { tooltip: Tooltip }
}

/**
* The component starts with loading=true and only loads data when refresh()
* is called via template ref. This wrapper auto-calls refresh on mount.
*/
const AutoRefreshWrapper = defineComponent({
components: { UsageLogsTable },
setup() {
const tableRef = ref<InstanceType<typeof UsageLogsTable> | null>(null)
onMounted(async () => {
await tableRef.value?.refresh()
})
return { tableRef }
},
template: '<UsageLogsTable ref="tableRef" />'
})

async function flushMicrotasks() {
await new Promise((resolve) => setTimeout(resolve, 0))
await nextTick()
Expand Down Expand Up @@ -208,20 +192,34 @@ describe('UsageLogsTable', () => {
return render(UsageLogsTable, { global: globalConfig })
}

function renderWithAutoRefresh() {
return render(AutoRefreshWrapper, { global: globalConfig })
}

async function renderLoaded() {
const result = renderWithAutoRefresh()
const result = renderComponent()
await waitFor(() => {
expect(screen.getByRole('table')).toBeInTheDocument()
})
return result
}

describe('loading states', () => {
it('shows loading spinner before refresh is called', () => {
it('loads activity on mount without an external refresh', async () => {
await renderLoaded()

expect(mockCustomerEventsService.getMyEvents).toHaveBeenCalledTimes(1)
})

it('loads activity on mount on the workspace billing rail', async () => {
mockBillingRouting.shouldUseWorkspaceBilling = true

await renderLoaded()

expect(mockWorkspaceApi.getBillingEvents).toHaveBeenCalledTimes(1)
})

it('shows a loading spinner while the initial load is in flight', () => {
mockCustomerEventsService.getMyEvents.mockReturnValue(
new Promise(() => {})
)

renderComponent()

expect(screen.getByRole('progressbar')).toBeInTheDocument()
Expand All @@ -232,7 +230,7 @@ describe('UsageLogsTable', () => {
mockCustomerEventsService.getMyEvents.mockResolvedValue(null)
mockCustomerEventsService.error.value = 'Failed to load events'

renderWithAutoRefresh()
renderComponent()

await waitFor(() => {
expect(screen.getByText('Failed to load events')).toBeInTheDocument()
Expand All @@ -244,7 +242,7 @@ describe('UsageLogsTable', () => {
new Error('Network error')
)

renderWithAutoRefresh()
renderComponent()

await waitFor(() => {
expect(
Expand All @@ -260,7 +258,7 @@ describe('UsageLogsTable', () => {
mockCustomerEventsService.getMyEvents.mockResolvedValue(null)
mockCustomerEventsService.error.value = null

renderWithAutoRefresh()
renderComponent()

await waitFor(() => {
expect(
Expand Down Expand Up @@ -312,7 +310,7 @@ describe('UsageLogsTable', () => {
])
)

renderWithAutoRefresh()
renderComponent()

await waitFor(() => {
expect(screen.getByText('Account initialized')).toBeInTheDocument()
Expand Down Expand Up @@ -400,7 +398,7 @@ describe('UsageLogsTable', () => {
])
)

renderWithAutoRefresh()
renderComponent()

mockBillingRouting.shouldUseWorkspaceBilling = true
await waitFor(() => {
Expand Down Expand Up @@ -442,7 +440,7 @@ describe('UsageLogsTable', () => {
])
)

renderWithAutoRefresh()
renderComponent()

mockBillingRouting.shouldUseWorkspaceBilling = true
await waitFor(() => {
Expand Down
14 changes: 9 additions & 5 deletions src/components/dialog/content/setting/UsageLogsTable.vue
Original file line number Diff line number Diff line change
Expand Up @@ -212,11 +212,15 @@ const refresh = async () => {
await loadEvents()
}

watch(shouldUseWorkspaceBilling, () => {
refresh().catch((error) => {
console.error('Error loading events:', error)
})
})
watch(
shouldUseWorkspaceBilling,
() => {
refresh().catch((error) => {
console.error('Error loading events:', error)
})
},
{ immediate: true }
)

defineExpose({
refresh
Expand Down
Loading