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
11 changes: 10 additions & 1 deletion apps/billing-web/e2e/invoices.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,14 @@ test('opens the provider portal for invoices, returning to this page', async ({
const portal = cloud.requests.find(
(request) => request.path === '/billing/payment-portal'
)
expect(portal?.body).toStrictEqual({ return_url: `${E2E_ORIGIN}${invoices}` })
const portalReturn = entryPath('invoices', { portal: 'return' })
expect(portal?.body).toStrictEqual({
return_url: `${E2E_ORIGIN}${portalReturn}`
})

await page.goto(portalReturn)
await page.waitForURL(`${E2E_ORIGIN}${invoices}`)
await expect(
page.getByRole('button', { name: 'Open invoices' })
).toBeVisible()
})
59 changes: 13 additions & 46 deletions apps/billing-web/src/components/PaymentMethodsPanel.vue
Original file line number Diff line number Diff line change
@@ -1,34 +1,26 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'

import type { SavedPaymentMethod } from '@comfyorg/account-core/billing'
import {
usePaymentMethods,
useBillingClient
} from '@comfyorg/account-ui/billing'
import { usePaymentMethods } from '@comfyorg/account-ui/billing'

import { useHostedCopy } from '@/composables/useHostedCopy'

/** Marks the customer's trip back from the provider's hosted portal. */
const PORTAL_PARAM = 'portal'
const PORTAL_RETURN = 'return'
import { usePaymentPortal } from '@/composables/usePaymentPortal'

const { t } = useI18n()
const { coded, refusal } = useHostedCopy()
const route = useRoute()
const router = useRouter()
const { commands } = useBillingClient<'commands'>(undefined)

const returningFromPortal = route.query[PORTAL_PARAM] === PORTAL_RETURN
const {
returningFromPortal,
opening: openingPortal,
refusal: portalRefusal,
openPortal,
dropReturnMarker
} = usePaymentPortal('payment_methods')

const { methods, defaultMethod, loading, failure, invalidateAndRefresh } =
usePaymentMethods({ immediate: !returningFromPortal })

const portalFailure = ref<string | undefined>()
const openingPortal = ref(false)

const rows = computed(() =>
(methods.value ?? []).map((method) => ({
id: method.id,
Expand All @@ -46,34 +38,9 @@ function describe(method: SavedPaymentMethod): string {
})
}

function portalReturnUrl(): string {
const url = new URL(window.location.href)
url.searchParams.set(PORTAL_PARAM, PORTAL_RETURN)
return url.href
}

async function openPortal() {
openingPortal.value = true
portalFailure.value = undefined
const result = await commands.openPaymentPortal({
returnUrl: portalReturnUrl()
})
openingPortal.value = false
if (result.status === 'error') {
portalFailure.value = refusal(result)
return
}
window.location.assign(result.value.url)
}

async function resumeFromPortal() {
await invalidateAndRefresh()
await router.replace({
path: route.path,
query: Object.fromEntries(
Object.entries(route.query).filter(([key]) => key !== PORTAL_PARAM)
)
})
await dropReturnMarker()
}

if (returningFromPortal) void resumeFromPortal()
Expand Down Expand Up @@ -107,8 +74,8 @@ if (returningFromPortal) void resumeFromPortal()
</li>
</ul>

<p v-if="portalFailure" class="m-0 text-sm text-destructive-background">
{{ portalFailure }}
<p v-if="portalRefusal" class="m-0 text-sm text-destructive-background">
{{ refusal(portalRefusal) }}
</p>
<button
type="button"
Expand Down
60 changes: 60 additions & 0 deletions apps/billing-web/src/composables/usePaymentPortal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import type {
BillingFailure,
BillingPortalTarget
} from '@comfyorg/account-core/billing'
import { useBillingClient } from '@comfyorg/account-ui/billing'

import { reportPortal } from '@/telemetry/portalTelemetry'

/** Marks the customer's trip back from the provider's hosted portal. */
const PORTAL_PARAM = 'portal'
const PORTAL_RETURN = 'return'

/** Sends the customer to the provider's portal and back to this page. */
export function usePaymentPortal(target: BillingPortalTarget) {
const route = useRoute()
const router = useRouter()
const { commands } = useBillingClient<'commands'>(undefined)

const returningFromPortal = route.query[PORTAL_PARAM] === PORTAL_RETURN
const opening = ref(false)
const refusal = ref<BillingFailure | undefined>()

if (returningFromPortal) reportPortal(target, { stage: 'returned' })

function portalReturnUrl(): string {
const url = new URL(window.location.href)
url.searchParams.set(PORTAL_PARAM, PORTAL_RETURN)
return url.href
}

async function openPortal() {
opening.value = true
refusal.value = undefined
const result = await commands.openPaymentPortal({
returnUrl: portalReturnUrl()
})
opening.value = false
if (result.status === 'error') {
refusal.value = result
reportPortal(target, { stage: 'failed', refusal: result })
return
}
reportPortal(target, { stage: 'opened' })
window.location.assign(result.value.url)
}

async function dropReturnMarker() {
await router.replace({
path: route.path,
query: Object.fromEntries(
Object.entries(route.query).filter(([key]) => key !== PORTAL_PARAM)
)
})
}

return { returningFromPortal, opening, refusal, openPortal, dropReturnMarker }
}
39 changes: 39 additions & 0 deletions apps/billing-web/src/telemetry/portalTelemetry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import type {
BillingFailure,
BillingPortalTarget,
BillingTelemetryFailure
} from '@comfyorg/account-core/billing'

import { billingWebTelemetry } from '@/telemetry/billingWebTelemetry'

function failureOfPortalRefusal({
code,
httpStatus
}: BillingFailure): BillingTelemetryFailure {
if (code === 'MALFORMED_RESPONSE') return { failure_category: 'unknown' }
return {
failure_category: httpStatus === undefined ? 'network' : 'api_rejected'
}
}

type PortalStage =
| { readonly stage: 'opened' }
| { readonly stage: 'returned' }
| { readonly stage: 'failed'; readonly refusal: BillingFailure }

export function reportPortal(
target: BillingPortalTarget,
event: PortalStage
): void {
const base = { operation: 'portal', target, billing_client: 'sdk' } as const
billingWebTelemetry.trackBillingEvent(
event.stage === 'failed'
? {
...base,
stage: 'failed',
outcome: 'failure',
...failureOfPortalRefusal(event.refusal)
}
: { ...base, stage: event.stage, outcome: 'pending' }
)
}
109 changes: 102 additions & 7 deletions apps/billing-web/src/views/InvoicesView.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import userEvent from '@testing-library/user-event'
import { render, screen } from '@testing-library/vue'
import { createMemoryHistory, createRouter } from 'vue-router'

import { BILLING_CLIENT_KEY } from '@comfyorg/account-ui/billing'
import { parseBillingEntry } from '@comfyorg/billing-contract'
Expand All @@ -8,38 +9,132 @@ import { recordBillingEntry } from '@/entry/billingEntry'
import { createBillingI18n } from '@/i18n'
import type { FakeBillingClientOptions } from '@/test/fakeBillingClient'
import { createFakeBillingClient } from '@/test/fakeBillingClient'
import { trackedBillingEvents } from '@/test/trackedBillingEvents'
import InvoicesView from '@/views/InvoicesView.vue'

const INVOICES_PATH = '/v1/invoices?product=comfyui&return_to=comfyui_workspace'
const SURFACE_PATH = '/v1/invoices'
const INVOICES_PATH = `${SURFACE_PATH}?product=comfyui&return_to=comfyui_workspace`

function renderInvoices(options: FakeBillingClientOptions = {}) {
async function renderInvoices(
options: FakeBillingClientOptions = {},
path = INVOICES_PATH
) {
recordBillingEntry(parseBillingEntry(INVOICES_PATH))
const router = createRouter({
history: createMemoryHistory(),
routes: [{ path: SURFACE_PATH, component: InvoicesView }]
})
await router.push(path)
await router.isReady()
const fake = createFakeBillingClient(options)
render(InvoicesView, {
global: {
plugins: [createBillingI18n()],
plugins: [createBillingI18n(), router],
provide: { [BILLING_CLIENT_KEY]: fake.client }
}
})
return fake
return { ...fake, router }
}

describe('InvoicesView', () => {
it('sends the visitor to the portal with this page as the way back', async () => {
const assign = vi.fn()
vi.spyOn(window.location, 'assign').mockImplementation(assign)
const fake = renderInvoices({ portalUrl: 'https://billing.stripe.test/p' })
const fake = await renderInvoices({
portalUrl: 'https://billing.stripe.test/p'
})

await userEvent.click(screen.getByRole('button', { name: 'Open invoices' }))

expect(fake.openPaymentPortal).toHaveBeenCalledWith({
returnUrl: window.location.href
returnUrl: expect.stringContaining('portal=return')
})
expect(assign).toHaveBeenCalledWith('https://billing.stripe.test/p')
})

it('reports the portal opening on the invoices', async () => {
vi.spyOn(window.location, 'assign').mockImplementation(() => undefined)
const sent = trackedBillingEvents()
await renderInvoices({ portalUrl: 'https://billing.stripe.test/p' })

await userEvent.click(screen.getByRole('button', { name: 'Open invoices' }))

expect(sent()).toEqual([
{
operation: 'portal',
stage: 'opened',
outcome: 'pending',
target: 'invoices',
billing_client: 'sdk'
}
])
})

it('reports the return from the portal once and drops the marker', async () => {
const sent = trackedBillingEvents()
const { router } = await renderInvoices(
{},
`${INVOICES_PATH}&portal=return`
)

await vi.waitFor(() => {
expect(router.currentRoute.value.fullPath).toBe(INVOICES_PATH)
})
expect(sent()).toEqual([
{
operation: 'portal',
stage: 'returned',
outcome: 'pending',
target: 'invoices',
billing_client: 'sdk'
}
])
})

it.for<{
name: string
portal: FakeBillingClientOptions['portal']
failure: Record<string, string>
}>([
{
name: 'a request that never reached the server',
portal: { status: 'error', code: 'REQUEST_FAILED' },
failure: { failure_category: 'network' }
},
{
name: 'a refusal from the server',
portal: { status: 'error', code: 'ACCESS_DENIED', httpStatus: 403 },
failure: { failure_category: 'api_rejected' }
},
{
name: 'a portal address that fails validation',
portal: { status: 'error', code: 'MALFORMED_RESPONSE', httpStatus: 200 },
failure: { failure_category: 'unknown' }
}
])('reports $name as a failed portal open', async ({ portal, failure }) => {
const sent = trackedBillingEvents()
await renderInvoices({ portal })

await userEvent.click(screen.getByRole('button', { name: 'Open invoices' }))

await vi.waitFor(() => {
expect(sent()).toEqual([
{
operation: 'portal',
stage: 'failed',
outcome: 'failure',
target: 'invoices',
billing_client: 'sdk',
...failure
}
])
})
})

it('explains a portal it could not open in our own words', async () => {
renderInvoices({ portal: { status: 'error', code: 'REQUEST_FAILED' } })
await renderInvoices({
portal: { status: 'error', code: 'REQUEST_FAILED' }
})

await userEvent.click(screen.getByRole('button', { name: 'Open invoices' }))

Expand Down
Loading
Loading