import { createRootRoute, createRoute } from '@tanstack/react-router' import { act, screen, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' import type { platformComponents as components } from 'api-types' import { HttpResponse } from 'msw' import type { UrlUpdateEvent } from 'nuqs/adapters/testing' import { beforeEach, describe, expect, it, vi } from 'vitest' import { Usage } from './Usage' import type { Branch } from '@/data/branches/branches-query' import { createMockOrganizationResponse, createMockProject } from '@/tests/helpers' import { createTestBranch } from '@/tests/lib/branch-test-utils' import { createTestRouter, customRender } from '@/tests/lib/custom-render' import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw' import { mockPermissions } from '@/tests/lib/msw-permissions' import { ALL_FGA_PERMISSIONS, allPermissionsFor } from '@/tests/lib/permissions-fixtures' import { createMockProfileContext } from '@/tests/lib/profile-helpers' vi.mock('common', async (importOriginal) => ({ ...(await importOriginal()), useIsLoggedIn: () => true, })) vi.mock('@/lib/constants', async (importOriginal) => ({ ...(await importOriginal()), IS_PLATFORM: true, })) const parent = createMockProject({ ref: 'parent-ref', name: 'Parent project' }) const branch = createTestBranch({ name: 'Preview branch' }) const main = createTestBranch({ id: 'main-id', project_ref: parent.ref, is_default: true }) const parentDetail: components['schemas']['ProjectDetailResponse_Output'] = { ...parent, connectionString: null, db_host: 'db.parent-ref.supabase.co', high_availability: false, integration_source: null, inserted_at: '2026-01-01T00:00:00Z', is_physical_backups_enabled: false, restUrl: 'https://parent-ref.supabase.co', status: 'ACTIVE_HEALTHY', subscription_id: 'subscription-1', updated_at: '2026-01-01T00:00:00Z', } const branchDetail = { ...parentDetail, ref: branch.project_ref, name: branch.name, parent_project_ref: parent.ref, } function renderUsage(branchRef: string | null = branch.project_ref, projectRef = parent.ref) { const onUrlUpdate = vi.fn<(event: UrlUpdateEvent) => void>() const searchParams: Record = { projectRef } if (branchRef !== null) searchParams.branchRef = branchRef const rootRoute = createRootRoute() const usageRoute = createRoute({ getParentRoute: () => rootRoute, path: '/org/$slug/usage', }) const query = new URLSearchParams(searchParams).toString() const router = createTestRouter( `/org/test-org/usage${query ? `?${query}` : ''}`, rootRoute.addChildren([usageRoute]) ) customRender(, { router, profileContext: createMockProfileContext(), nuqs: { searchParams, hasMemory: true, onUrlUpdate }, }) return { onUrlUpdate } } function captureUsageRequests() { const requests: { usage: (string | null)[]; daily: (string | null)[] } = { usage: [], daily: [], } addAPIMock({ method: 'get', path: '/platform/organizations/:slug/usage', response: ({ request }) => { const ref = new URL(request.url).searchParams.get('project_ref') requests.usage.push(ref) let usage = 23 if (ref === branch.project_ref) usage = 7 if (ref === parent.ref) usage = 13 return HttpResponse.json({ usages: [ { metric: 'EGRESS', usage, usage_original: usage * 1e9, available_in_plan: true, capped: true, cost: 0, pricing_free_units: 5, pricing_strategy: 'UNIT', project_allocations: [], unit_price_desc: 'Egress per GB', unlimited: false, }, ], usage_billing_enabled: false, }) }, }) addAPIMock({ method: 'get', path: '/platform/organizations/:slug/usage/daily', response: ({ request }) => { requests.daily.push(new URL(request.url).searchParams.get('project_ref')) return HttpResponse.json({ usages: [], }) }, }) return requests } function expectUsageRefs( requests: ReturnType, refs: (string | null)[] ) { expect(new Set(requests.usage)).toEqual(new Set(refs)) expect(new Set(requests.daily)).toEqual(new Set(refs)) } describe('Usage branch URLs', () => { beforeEach(() => { addAPIMock({ method: 'get', path: '/platform/projects/:ref', response: ({ params }) => HttpResponse.json( params.ref === branch.project_ref ? branchDetail : parentDetail ), }) addAPIMock({ method: 'get', path: '/platform/organizations', response: () => HttpResponse.json([ createMockOrganizationResponse({ slug: 'test-org' }), ]), }) mockPermissions(allPermissionsFor(['test-org'])) addAPIMock({ method: 'get', path: '/platform/organizations/:slug/billing/subscription', response: () => HttpResponse.json({ addons: [], billing_via_partner: false, current_period_start: 1767225600, current_period_end: 1769904000, next_invoice_at: 1769904000, payment_method_type: 'card', plan: { id: 'free', name: 'Free' }, project_addons: [], usage_billing_enabled: false, }), }) addAPIMock({ method: 'get', path: '/v1/projects/:ref/branches', response: () => HttpResponse.json([main, branch]), }) }) it('shows the permission notice when subscription access is denied', async () => { captureUsageRequests() addAPIMock({ method: 'get', path: '/platform/organizations/:slug/projects', response: () => HttpResponse.json({ projects: [], pagination: { count: 0, limit: 96, offset: 0 }, }), }) mockPermissions({ organizations: [{ slug: 'test-org', role: 'readonly', permissions: [], projects: [] }], }) const subscriptionRequested = vi.fn() addAPIMock({ method: 'get', path: '/platform/organizations/:slug/billing/subscription', response: () => { subscriptionRequested() return HttpResponse.json({ message: 'Forbidden' }, { status: 403 }) }, }) renderUsage() expect( await screen.findByText(/additional permissions to view organization usage/) ).toBeVisible() expect(screen.queryByRole('button', { name: 'Current billing cycle' })).not.toBeInTheDocument() expect(subscriptionRequested).not.toHaveBeenCalled() }) it('requests both usage endpoints with the branch project ref from the URL', async () => { const requests = captureUsageRequests() renderUsage() expect(await screen.findByText(`${branch.name} branch only.`)).toBeInTheDocument() await waitFor(() => { expectUsageRefs(requests, [branch.project_ref]) }) expect(screen.getByLabelText('Filter by branch')).toHaveTextContent(branch.name) expect(screen.queryByText('Branch unavailable')).not.toBeInTheDocument() }) it('resolves a direct branch URL and switches to main and organization totals', async () => { const user = userEvent.setup() const requests = captureUsageRequests() const branchListRefs: string[] = [] const projectRefs: string[] = [] addAPIMock({ method: 'get', path: '/platform/projects/:ref', response: ({ params }) => { projectRefs.push(String(params.ref)) return HttpResponse.json( params.ref === branch.project_ref ? branchDetail : parentDetail ) }, }) addAPIMock({ method: 'get', path: '/v1/projects/:ref/branches', response: ({ params }) => { branchListRefs.push(String(params.ref)) return HttpResponse.json([main, branch]) }, }) const { onUrlUpdate } = renderUsage(null, branch.project_ref) expect(await screen.findByText(`${branch.name} branch only.`)).toBeInTheDocument() await waitFor(() => { expectUsageRefs(requests, [branch.project_ref]) }) expect(await screen.findByText('7 GB')).toBeVisible() expect(new Set(projectRefs)).toEqual(new Set([branch.project_ref, parent.ref])) expect(new Set(branchListRefs)).toEqual(new Set([parent.ref])) expect(screen.getByLabelText('Filter by branch')).toHaveTextContent(branch.name) expect(screen.getByRole('combobox', { name: '' })).toHaveTextContent(parent.name) await user.click(screen.getByLabelText('Filter by branch')) await user.click(await screen.findByRole('option', { name: main.name })) expect(await screen.findByText(/Main branch only/)).toBeInTheDocument() await waitFor(() => { expectUsageRefs(requests, [branch.project_ref, parent.ref]) }) expect(await screen.findByText('13 GB')).toBeVisible() expect(screen.getByLabelText('Filter by branch')).toHaveTextContent(main.name) expect(new Set(branchListRefs)).toEqual(new Set([parent.ref])) await user.click(screen.getByLabelText('Filter by branch')) await user.click(await screen.findByRole('option', { name: branch.name })) expect(await screen.findByText(`${branch.name} branch only.`)).toBeInTheDocument() await user.click(screen.getByRole('button', { name: 'View organization total' })) await waitFor(() => { expectUsageRefs(requests, [branch.project_ref, parent.ref, null]) const searchParams = onUrlUpdate.mock.lastCall?.[0].searchParams expect(searchParams).toBeDefined() expect(searchParams?.has('projectRef')).toBe(false) expect(searchParams?.has('branchRef')).toBe(false) }) expect(await screen.findByText('23 / 5 GB')).toBeVisible() expect(screen.queryByLabelText('Filter by branch')).not.toBeInTheDocument() expect( screen.queryByRole('button', { name: 'View organization total' }) ).not.toBeInTheDocument() }) it('waits for direct branch project details before requesting branches or usage', async () => { const requests = captureUsageRequests() const response = Promise.withResolvers() const projectRequested = vi.fn() const branchListRefs: string[] = [] addAPIMock({ method: 'get', path: '/platform/projects/:ref', response: async ({ params }) => { if (params.ref === branch.project_ref) { projectRequested() await response.promise return HttpResponse.json( branchDetail ) } return HttpResponse.json( parentDetail ) }, }) addAPIMock({ method: 'get', path: '/v1/projects/:ref/branches', response: ({ params }) => { branchListRefs.push(String(params.ref)) return HttpResponse.json([main, branch]) }, }) renderUsage(null, branch.project_ref) try { await waitFor(() => expect(projectRequested).toHaveBeenCalled()) expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument() expect(branchListRefs).toEqual([]) expect(requests).toEqual({ usage: [], daily: [] }) } finally { await act(async () => response.resolve()) } expect(await screen.findByText(`${branch.name} branch only.`)).toBeInTheDocument() await waitFor(() => { expectUsageRefs(requests, [branch.project_ref]) }) expect(new Set(branchListRefs)).toEqual(new Set([parent.ref])) }) it('blocks a direct branch link when its parent project lookup fails', async () => { const requests = captureUsageRequests() const branchRequested = vi.fn() addAPIMock({ method: 'get', path: '/platform/projects/:ref', response: ({ params }) => params.ref === branch.project_ref ? HttpResponse.json(branchDetail) : HttpResponse.json({ message: 'Parent lookup failed' }, { status: 500 }), }) addAPIMock({ method: 'get', path: '/v1/projects/:ref/branches', response: () => { branchRequested() return HttpResponse.json([main, branch]) }, }) renderUsage(null, branch.project_ref) expect(await screen.findByText('Failed to retrieve project')).toBeInTheDocument() expect(screen.queryByRole('status', { name: 'Loading branch usage' })).not.toBeInTheDocument() expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument() expect(branchRequested).not.toHaveBeenCalled() expect(requests).toEqual({ usage: [], daily: [] }) }) it('does not request parent usage while the branch list is pending', async () => { const requests = captureUsageRequests() const response = Promise.withResolvers() const branchRequested = vi.fn() addAPIMock({ method: 'get', path: '/v1/projects/:ref/branches', response: async () => { branchRequested() return HttpResponse.json(await response.promise) }, }) renderUsage() try { await waitFor(() => expect(branchRequested).toHaveBeenCalled()) expect(await screen.findByText('Free Plan')).toBeInTheDocument() expect(screen.getByRole('status', { name: 'Loading branch usage' })).toBeInTheDocument() expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument() expect(requests).toEqual({ usage: [], daily: [] }) } finally { await act(async () => response.resolve([main, branch])) } await waitFor(() => { expectUsageRefs(requests, [branch.project_ref]) }) }) it('shows a branch error without requesting parent usage when the branch list fails', async () => { const requests = captureUsageRequests() addAPIMock({ method: 'get', path: '/v1/projects/:ref/branches', response: () => HttpResponse.json({ message: 'Branch lookup failed' }, { status: 500 }), }) renderUsage() expect(await screen.findByText('Failed to retrieve branches')).toBeInTheDocument() expect(await screen.findByText('Free Plan')).toBeInTheDocument() expect(screen.queryByRole('status', { name: 'Loading branch usage' })).not.toBeInTheDocument() expect(screen.queryByText('Branch unavailable')).not.toBeInTheDocument() expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument() expect(requests).toEqual({ usage: [], daily: [] }) }) it('blocks branch usage without falling back to the parent when branch access is denied', async () => { const requests = captureUsageRequests() mockPermissions({ organizations: [ { slug: 'test-org', role: 'owner', permissions: ALL_FGA_PERMISSIONS.filter( (permission) => !permission.startsWith('branching_') ), projects: [], }, ], }) renderUsage() expect( await screen.findByText(/additional permissions to view this branch's usage/) ).toBeVisible() expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument() expect(requests).toEqual({ usage: [], daily: [] }) }) it('shows Branch unavailable and requests parent usage for a deleted branch ref', async () => { const requests = captureUsageRequests() renderUsage('deleted-branch-ref') expect(await screen.findByText('Branch unavailable')).toBeInTheDocument() expect(screen.getByText(/Main branch only/)).toBeInTheDocument() await waitFor(() => { expectUsageRefs(requests, [parent.ref]) }) }) it('keeps filters usable after a project lookup failure and recovers through All projects', async () => { const user = userEvent.setup() const requests = captureUsageRequests() addAPIMock({ method: 'get', path: '/platform/projects/:ref', response: ({ params }) => params.ref === parent.ref ? HttpResponse.json({ message: 'Project lookup failed' }, { status: 404 }) : HttpResponse.json(branchDetail), }) addAPIMock({ method: 'get', path: '/platform/organizations/:slug/projects', response: () => HttpResponse.json({ projects: [], pagination: { count: 0, limit: 96, offset: 0 }, }), }) const { onUrlUpdate } = renderUsage() expect(await screen.findByText('Failed to retrieve project')).toBeInTheDocument() expect(screen.queryByRole('status', { name: 'Loading branch usage' })).not.toBeInTheDocument() expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument() expect(requests).toEqual({ usage: [], daily: [] }) await user.click(await screen.findByRole('button', { name: 'Current billing cycle' })) expect( await screen.findByRole('menuitemradio', { name: 'Current billing cycle' }) ).toBeInTheDocument() await user.keyboard('{Escape}') const projectPicker = screen.getByRole('combobox', { name: '' }) expect(projectPicker).toHaveTextContent(parent.ref) await user.click(projectPicker) const allProjects = await screen.findByRole('option', { name: 'All projects' }) expect(screen.getByText('Failed to retrieve project')).toBeInTheDocument() expect(requests).toEqual({ usage: [], daily: [] }) await user.click(allProjects) await waitFor(() => { expectUsageRefs(requests, [null]) const searchParams = onUrlUpdate.mock.lastCall?.[0].searchParams expect(searchParams).toBeDefined() expect(searchParams?.has('projectRef')).toBe(false) expect(searchParams?.has('branchRef')).toBe(false) }) expect(screen.queryByText('Failed to retrieve project')).not.toBeInTheDocument() expect(screen.getByText('Usage Summary')).toBeInTheDocument() expect(screen.getByRole('combobox', { name: '' })).toHaveTextContent('All projects') }) })