mirror of
https://github.com/supabase/supabase.git
synced 2026-12-03 23:18:57 +00:00
## Problem On the organization usage page, the per-project breakdowns list project names, but there's no way to jump to that project's usage. You have to find it in the project dropdown instead. Resolves FE-5153. ## Solution Project names in the usage breakdowns are now buttons that set the `projectRef` filter and clear `branchRef`, so the page shows that project's usage. The other query params, such as the date range, are left alone. - New `UsageProjectName` component. It renders plain text when that project is already selected, and a button otherwise. It underlines on hover only. - Applied in the metric breakdown tooltip (`BillingMetric`), the compute hover card (`ComputeMetric`) and the database size table (`DatabaseSizeUsage`). - `TotalUsage` passes the selected `projectRef` down to the metric components. - The `projectRef`/`branchRef` nuqs parsers are now shared as `usageFilterParsers` in `Usage.utils.ts`, so `Usage` and `UsageProjectName` use the same definition. Tests cover the click updating the URL (and clearing `branchRef`), the selected project rendering as text, and the `BillingMetric` breakdown in both states. <img width="410" height="296" alt="Screenshot 2026-11-19 at 13 36 17" src="https://github.com/user-attachments/assets/1f032cc3-d0e2-4185-80f7-4ab3303fc6b6" /> ## Review instructions 1. Open an organization's usage page (`/org/<slug>/usage`) for an org with several projects. 2. Hover a metric that has a per-project breakdown, such as Egress, and click a project name. 3. The project dropdown should switch to that project and the usage should update. Any date range you had selected should survive the click. 4. Hover the same metric again. The selected project is now plain text and the others are still clickable. 5. Do the same from the compute hover card and the database size table. ## Checklist Check all before review: - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)
177 lines
5.4 KiB
TypeScript
177 lines
5.4 KiB
TypeScript
import dayjs from 'dayjs'
|
|
import { groupBy } from 'lodash'
|
|
import { parseAsString } from 'nuqs'
|
|
|
|
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'
|
|
|
|
export const usageFilterParsers = {
|
|
projectRef: parseAsString,
|
|
branchRef: parseAsString,
|
|
}
|
|
|
|
// [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
|
|
}
|