Files
supabase/apps/studio/components/interfaces/Organization/Usage/Usage.utils.ts
T
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

171 lines
5.2 KiB
TypeScript

import dayjs from 'dayjs'
import { groupBy } from 'lodash'
import { DataPoint } from '@/data/analytics/constants'
import type { OrgDailyUsageResponse, PricingMetric } from '@/data/analytics/org-daily-stats-query'
import type { Branch } from '@/data/branches/branches-query'
import type { OrgSubscription } from '@/data/subscriptions/types'
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
// [Joshen] This is just for development to generate some test data for chart rendering
export const generateUsageData = (attribute: string, days: number): DataPoint[] => {
const tempArray = new Array(days).fill(0)
return tempArray.map((_x, idx) => {
return {
loopId: (idx + 1).toString(),
period_start: `${idx + 1}`,
[attribute]: Math.floor(Math.random() * 100).toString(),
}
})
}
export function getUsageBranchOptions(branches: Branch[] | undefined) {
const previewBranches = (branches ?? [])
.filter((branch) => !branch.is_default)
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
if (previewBranches.length === 0) return []
const mainBranch = branches?.find((branch) => branch.is_default)
return mainBranch ? [mainBranch, ...previewBranches] : previewBranches
}
export function resolveUsageProjectRef(
selectedProjectRef: string | null,
branchOptions: Branch[],
selectedBranchRef: string | null
) {
if (!selectedProjectRef) return null
const selectedBranch = branchOptions.find(
(branch) =>
branch.project_ref === selectedBranchRef && branch.parent_project_ref === selectedProjectRef
)
return selectedBranch?.project_ref ?? selectedProjectRef
}
export function useGetUpgradeUrl(slug: string, subscription?: OrgSubscription, source?: string) {
const { billingAll } = useIsFeatureEnabled(['billing:all'])
if (!billingAll) {
const subject = `Enquiry to upgrade plan for organization`
const message = `Organization Slug: ${slug}\nRequested plan: <Specify which plan to upgrade to: Pro | Team | Enterprise | Platform>`
return `/support/new?orgSlug=${slug}&projectRef=no-project&category=Plan_upgrade&subject=${subject}&message=${encodeURIComponent(message)}`
}
if (!subscription) {
return `/org/${slug}/billing`
}
return subscription?.plan?.id === 'pro' && subscription?.usage_billing_enabled === false
? `/org/${slug}/billing#cost-control`
: `/org/${slug}/billing?panel=subscriptionPlan&source=usage${source}`
}
const compactNumberFormatter = new Intl.NumberFormat('en-US', {
notation: 'compact',
compactDisplay: 'short',
})
/**
* For the y-axis, we don't need to be as precise, to avoid showing 58.597MB.
*/
export const ChartYFormatterCompactNumber = (number: number | string, unit: string) => {
if (typeof number === 'string') return number
if (unit === 'bytes') {
const formattedBytes = formatBytesCompact(number).replace(/\s/g, '')
return formattedBytes === '0bytes' ? '0' : formattedBytes
} else if (unit === 'gigabytes') {
return compactNumberFormatter.format(number) + 'GB'
} else {
return compactNumberFormatter.format(number)
}
}
/**
* For the chart tooltip, we want to be more precise and show more decimals.
*/
export const ChartTooltipValueFormatter = (number: number | string, unit: string) => {
if (typeof number === 'string') return number
if (unit === 'bytes') {
const formattedBytes = formatBytesPrecision(number).replace(/\s/g, '')
return formattedBytes === '0bytes' ? '0' : formattedBytes
} else if (unit === 'gigabytes') {
return compactNumberFormatter.format(number) + 'GB'
} else {
return compactNumberFormatter.format(number)
}
}
const sizes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
const formatBytesCompact = (bytes: number) => {
if (bytes === 0 || bytes === undefined) return '0 bytes'
const k = 1024
const i = Math.floor(Math.log(bytes) / Math.log(k))
const unit = sizes[i]
let dm = 2
if (['bytes', 'KB', 'MB'].includes(unit)) {
dm = 0
} else if (['GB'].includes(unit)) {
dm = 1
}
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + unit
}
const formatBytesPrecision = (bytes: any) => {
if (bytes === 0 || bytes === undefined) return '0 bytes'
const k = 1024
const i = Math.floor(Math.log(bytes) / Math.log(k))
const unit = sizes[i]
return parseFloat((bytes / Math.pow(k, i)).toFixed(3)) + ' ' + unit
}
export function dailyUsageToDataPoints(
dailyUsage: OrgDailyUsageResponse | undefined,
includeMetric: (metric: PricingMetric) => boolean
): DataPoint[] {
if (!dailyUsage || !dailyUsage.usages.length) return []
const groupedByDate = groupBy(
dailyUsage.usages.filter((it) => includeMetric(it.metric as PricingMetric)),
'date'
)
const dataPoints: DataPoint[] = []
Object.entries(groupedByDate).forEach(([date, usages]) => {
const dataPoint: DataPoint = {
period_start: date,
periodStartFormatted: dayjs(date).format('DD MMM'),
}
for (const usage of usages) {
dataPoint[usage.metric.toLowerCase()] = usage.usage_original
if (usage.breakdown) {
for (const [key, value] of Object.entries(usage.breakdown)) {
dataPoint[key.toLowerCase()] = value
}
}
}
dataPoints.push(dataPoint)
})
return dataPoints
}