Files
Jordi Enric 090e5bceff feat(studio): filter organization usage by branch FE-4153 (#49257)
## Summary

Customers could see a branch-driven egress overage in their organization
total but could not select the branch on the Usage page. This adds a
branch filter next to the parent project selector and uses the selected
branch's project ref for usage requests.

- Validate bookmarked branch refs before displaying usage. Show loading
and API errors explicitly, and disclose when an unavailable branch falls
back to its parent.
- Keep the filter, notice, and usage requests on the same project ref.
Allow returning to the parent even when the branches response omits its
main row.
- Find the selected branch's disk usage beyond the first page of
organization projects and explain that deleted branches still contribute
to organization totals.
- Correct the branching and egress documentation to explain separate
branch usage.

## Scope

This is the branch-selector improvement proposed in FE-4153's
discussion. It does not provide the original ticket's reconciled
per-project egress table or historical rows for deleted branches. The
current daily-usage API contract supports a single project filter, but
does not return project-grouped usage. Keep the full reconciliation work
open.

## Validation

All 47 focused Vitest tests pass across six files, including nine MSW
page tests covering usage request refs, direct branch links,
pending/failed lookups, deleted-branch fallback, invalid-project
recovery, and denied subscription permissions. Disk tests cover
selection beyond the first 96 projects and pagination failures.
Deterministic shuffled runs with seeds `4153` and `49257` pass with
retries disabled (`--retry=0`). Four focused production mutants were
killed by behavioral assertions; original source bytes were restored and
verified after every probe.

Studio TypeScript, Prettier on all PR paths, and focused lint checks
pass; inherited `any` warnings remain.

Browser QA on the matching `be17d77` Vercel preview passed parent usage
(0.213 GB), searching for `dev-test`, branch selection, return to main,
invalid-project recovery, stale-branch fallback, and returning to
organization totals. The selected branch showed 0 GB, so nonzero branch
overage was not verified. Browser network traffic was not captured;
request-ref coverage comes from MSW.

Three existing auth/router/platform module-mock scaffolds remain as a
test-harness limitation; strict no-module-mock compliance is not
claimed.

All Studio unit-test and E2E shards passed on be17d77801; CI report jobs
are finishing.

Related: FE-4153


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Filter organization usage by project branch with searchable branch
selection. Usage details reflect the selected branch where available,
including branches found on later project-list pages.
* See whether usage is scoped to a branch, the main branch, or a
project, and switch to organization-wide totals. Billing and quota
totals include all branches, including deleted branches that are no
longer selectable.
* **Documentation**
* Clarified how non-compute usage is recorded per branch, included in
organization totals, and viewed; it isn’t itemized by branch on
invoices.
* Clarified that Preview branch Egress counts toward organization
totals, not the parent project’s usage, and how to view it.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-10-19 11:30:37 +00:00

141 lines
4.3 KiB
TypeScript

import { screen } from '@testing-library/react'
import { HttpResponse } from 'msw'
import { describe, expect, it } from 'vitest'
import type { CategoryAttribute } from '../Usage.constants'
import { DiskUsage } from './DiskUsage'
import type { OrgProject, OrgProjectsResponse } from '@/data/projects/org-projects-infinite-query'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
import { createMockProfileContext } from '@/tests/lib/profile-helpers'
const attribute: CategoryAttribute = {
anchor: 'diskSize',
key: 'diskSize',
attributes: [],
name: 'Disk size',
unit: 'bytes',
description: 'Provisioned disk size',
chartDescription: '',
}
const branch: OrgProject = {
cloud_provider: 'AWS',
databases: [
{
cloud_provider: 'AWS',
disk_volume_size_gb: 8,
identifier: 'branch-ref',
region: 'us-east-1',
status: 'ACTIVE_HEALTHY',
type: 'PRIMARY',
},
],
inserted_at: '2026-01-01T00:00:00Z',
integration_source: null,
is_branch: true,
name: 'Preview branch',
ref: 'branch-ref',
region: 'us-east-1',
status: 'ACTIVE_HEALTHY',
}
const firstPage = Array.from({ length: 96 }, (_, index) => ({
...branch,
ref: `project-${index}`,
name: `Project ${index}`,
is_branch: false,
}))
const renderDiskUsage = (projectRef?: string) =>
customRender(
<DiskUsage
slug="test-org"
projectRef={projectRef}
attribute={attribute}
currentBillingCycleSelected
/>,
{ profileContext: createMockProfileContext() }
)
describe('DiskUsage', () => {
it('finds a selected branch beyond the first page and stops once found', async () => {
const offsets: number[] = []
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/projects',
response: ({ request }) => {
const offset = Number(new URL(request.url).searchParams.get('offset'))
offsets.push(offset)
return HttpResponse.json<OrgProjectsResponse>({
pagination: { count: 250, limit: 96, offset },
projects: offset === 0 ? firstPage : [branch],
})
},
})
renderDiskUsage('branch-ref')
expect(await screen.findByText('Preview branch')).toBeInTheDocument()
expect(screen.getByText('8 GB Disk provisioned')).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'Manage Disk' })).toHaveAttribute(
'href',
'/project/branch-ref/settings/infrastructure'
)
expect(screen.queryByText('No active projects')).not.toBeInTheDocument()
expect(offsets).toEqual([0, 96])
})
it.each([undefined, 'project-0'])(
'does not paginate when the filter is %s',
async (projectRef) => {
const offsets: number[] = []
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/projects',
response: ({ request }) => {
const offset = Number(new URL(request.url).searchParams.get('offset'))
offsets.push(offset)
return HttpResponse.json<OrgProjectsResponse>({
pagination: { count: 250, limit: 96, offset },
projects: firstPage,
})
},
})
renderDiskUsage(projectRef)
expect(await screen.findByText('Project 0')).toBeInTheDocument()
expect(offsets).toEqual([0])
}
)
it('shows an error when the next page fails instead of claiming there are no projects', async () => {
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
response: () =>
HttpResponse.json<APIErrorBody>({ message: 'Project not found' }, { status: 404 }),
})
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/projects',
response: ({ request }) => {
const offset = Number(new URL(request.url).searchParams.get('offset'))
if (offset > 0) {
return HttpResponse.json<APIErrorBody>({ message: 'Page unavailable' }, { status: 500 })
}
return HttpResponse.json<OrgProjectsResponse>({
pagination: { count: 97, limit: 96, offset },
projects: firstPage,
})
},
})
renderDiskUsage('branch-ref')
expect(await screen.findByText('Failed to retrieve usage data')).toBeInTheDocument()
expect(screen.queryByText('No active projects')).not.toBeInTheDocument()
})
})