Files
Joshen Lim 85194a05d8 Joshenlim/fe 5190 move off scaffold components in (#53849)
## Context

Housekeeping to deprecate more deprecated UI components, this one's
focusing on the `Scaffold` components.
The main visual differences are just the width within PageSections since
the new components where the right content takes up a bit more width
than the left content. (Ref org billing + usage)

Starting the refactor with the organization pages:
- Billing
- Team
- Usage
- Settings -> SSO
- Settings -> Security
- Settings -> Audit Logs
- Settings -> Documents
2026-11-24 10:39:33 +07:00

504 lines
19 KiB
TypeScript

import { useQuery } from '@tanstack/react-query'
import { useParams } from 'common'
import dayjs from 'dayjs'
import { ChartAreaIcon, CheckIcon, ChevronDownIcon } from 'lucide-react'
import { useQueryStates } from 'nuqs'
import { useMemo, useState } from 'react'
import { Button, cn, CommandGroup, CommandItem } from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import { PageContainer } from 'ui-patterns/PageContainer'
import {
PageHeader,
PageHeaderMeta,
PageHeaderSummary,
PageHeaderTitle,
} from 'ui-patterns/PageHeader'
import { PageSection } from 'ui-patterns/PageSection'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
import { Restriction } from '../BillingSettings/Restriction'
import ActiveCompute from './ActiveCompute'
import Activity from './Activity'
import Compute from './Compute'
import Egress from './Egress'
import OrgLogUsage from './OrgLogUsage'
import { Pipelines } from './Pipelines'
import SizeAndCounts from './SizeAndCounts'
import { TotalUsage } from './TotalUsage'
import { getUsageBranchOptions, resolveUsageProjectRef, usageFilterParsers } from './Usage.utils'
import { UsageBranchFilter } from './UsageBranchFilter'
import { UsageFilterNotice } from './UsageFilterNotice'
import { AlertError } from '@/components/ui/AlertError'
import { DateRangePicker } from '@/components/ui/DateRangePicker'
import { HighAvailabilityDisabledEmptyState } from '@/components/ui/HighAvailability/HighAvailabilityDisabledEmptyState'
import { NoPermission } from '@/components/ui/NoPermission'
import { OrganizationProjectSelector } from '@/components/ui/OrganizationProjectSelector'
import { useOrgDailyStatsQuery } from '@/data/analytics/org-daily-stats-query'
import { branchesQueryOptions } from '@/data/branches/branches-query'
import { useProjectDetailQuery } from '@/data/projects/project-detail-query'
import { useOrgSubscriptionQuery } from '@/data/subscriptions/org-subscription-query'
import { FGA_PERMISSIONS, useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2'
import { resolveHighAvailability } from '@/hooks/misc/useHighAvailability'
import { TIME_PERIODS_BILLING, TIME_PERIODS_REPORTS } from '@/lib/constants/metrics'
import { useGrant } from '@/lib/grants'
export const Usage = () => {
const { slug } = useParams()
const [dateRange, setDateRange] = useState<any>()
const [{ projectRef, branchRef }, setUsageFilter] = useQueryStates(usageFilterParsers)
const [openProjectSelector, setOpenProjectSelector] = useState(false)
const {
data: requestedProject,
isPending: isLoadingRequestedProject,
isError: isErrorRequestedProject,
error: requestedProjectError,
} = useProjectDetailQuery({
ref: projectRef ?? undefined,
})
const parentProjectRef = requestedProject?.parent_project_ref
const {
data: parentProject,
isPending: isLoadingParentProject,
isError: isErrorParentProject,
error: parentProjectError,
} = useProjectDetailQuery({ ref: parentProjectRef ?? undefined })
const selectedProjectRef = parentProjectRef ?? projectRef
const selectedBranchRef = branchRef ?? (parentProjectRef ? projectRef : null)
const selectedProject = parentProjectRef ? parentProject : requestedProject
const isLoadingSelectedProject =
!!projectRef && (isLoadingRequestedProject || (!!parentProjectRef && isLoadingParentProject))
const isErrorSelectedProject =
isErrorRequestedProject || (!!parentProjectRef && isErrorParentProject)
const selectedProjectError = requestedProjectError ?? parentProjectError
const isHighAvailability = resolveHighAvailability(selectedProject)
const canLoadProjectUsage =
!selectedProjectRef ||
(!isLoadingSelectedProject && !isErrorSelectedProject && !isHighAvailability)
const isBranchesQueryEnabled = !!selectedProject && !isHighAvailability
const branchesGrant = useGrant('GET /v1/projects/{ref}/branches', {
projectRef: selectedProjectRef ?? undefined,
})
const {
data: branches,
isPending: isPendingBranchesQuery,
isError: isErrorBranchesQuery,
isSuccess: isSuccessBranches,
error: branchesQueryError,
} = useQuery(
branchesQueryOptions(
{
projectRef: selectedProjectRef ?? undefined,
grant: branchesGrant.grant,
},
{ enabled: isBranchesQueryEnabled }
)
)
const isPendingBranches =
isBranchesQueryEnabled &&
(branchesGrant.status === 'loading' ||
(branchesGrant.status === 'granted' && isPendingBranchesQuery))
const isLoadingBranches = isPendingBranches
const isErrorBranches = isErrorBranchesQuery || branchesGrant.status === 'error'
const branchesError = branchesGrant.status === 'error' ? branchesGrant.error : branchesQueryError
const branchOptions = useMemo(() => getUsageBranchOptions(branches), [branches])
const usageProjectRef = resolveUsageProjectRef(
selectedProjectRef,
branchOptions,
selectedBranchRef
)
const selectedBranch = branchOptions.find(
(branch) => branch.project_ref === usageProjectRef && branch.project_ref !== selectedProjectRef
)
const isProjectLookupBlocked = !!selectedProjectRef && isErrorSelectedProject
const isResolvingBranch =
!!selectedProjectRef && !!selectedBranchRef && isPendingBranches && !isProjectLookupBlocked
const isBranchLookupBlocked = !!selectedBranchRef && isErrorBranches
const isBranchLookupDenied = !!selectedBranchRef && branchesGrant.status === 'denied'
const isBranchUnavailable =
!!selectedBranchRef && isSuccessBranches && usageProjectRef !== selectedBranchRef
const canShowUsage =
!isLoadingSelectedProject &&
!isResolvingBranch &&
!isBranchLookupBlocked &&
!isBranchLookupDenied &&
!isProjectLookupBlocked
const canLoadUsage = canLoadProjectUsage && canShowUsage
const { can: canReadSubscriptions, isLoading: isLoadingPermissions } = useAsyncCheckPermissionsV2(
FGA_PERMISSIONS.ORGANIZATION.BILLING_READ
)
const {
data: subscription,
error: subscriptionError,
isLoading: isLoadingSubscription,
isError: isErrorSubscription,
isSuccess: isSuccessSubscription,
} = useOrgSubscriptionQuery(
{ orgSlug: slug },
{ enabled: canReadSubscriptions && !isHighAvailability }
)
const billingCycleStart = useMemo(() => {
return dayjs.unix(subscription?.current_period_start ?? 0).utc()
}, [subscription])
const billingCycleEnd = useMemo(() => {
return dayjs.unix(subscription?.current_period_end ?? 0).utc()
}, [subscription])
const currentBillingCycleSelected = useMemo(() => {
// Selected by default
if (!dateRange?.period_start || !dateRange?.period_end) return true
return (
dayjs(dateRange.period_start.date).isSame(billingCycleStart) &&
dayjs(dateRange.period_end.date).isSame(billingCycleEnd)
)
}, [dateRange, billingCycleStart, billingCycleEnd])
const startDate = useMemo(() => {
// If end date is in future, set end date to now
if (!dateRange?.period_start?.date) {
return undefined
} else {
// LF seems to have an issue with the milliseconds, causes infinite loading sometimes
return new Date(dateRange?.period_start?.date).toISOString().slice(0, -5) + 'Z'
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dateRange, subscription])
const endDate = useMemo(() => {
// If end date is in future, set end date to end of current day
if (dateRange?.period_end?.date && dayjs(dateRange.period_end.date).isAfter(dayjs())) {
// LF seems to have an issue with the milliseconds, causes infinite loading sometimes
// In order to have full days from Prometheus metrics when using 1d interval,
// the time needs to be greater or equal than the time of the start date
return dayjs().endOf('day').toISOString().slice(0, -5) + 'Z'
} else if (dateRange?.period_end?.date) {
// LF seems to have an issue with the milliseconds, causes infinite loading sometimes
return new Date(dateRange.period_end.date).toISOString().slice(0, -5) + 'Z'
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dateRange, subscription])
const {
data: orgDailyStats,
error: orgDailyStatsError,
isPending: isLoadingOrgDailyStats,
isError: isErrorOrgDailyStats,
} = useOrgDailyStatsQuery(
{
orgSlug: slug,
projectRef: usageProjectRef ?? undefined,
startDate,
endDate,
},
{ enabled: canLoadUsage }
)
if (isHighAvailability) {
return (
<div className="flex flex-1 items-center justify-center p-6">
<HighAvailabilityDisabledEmptyState
icon={ChartAreaIcon}
title="Usage unavailable on High Availability projects"
description="Usage insights for High Availability projects are coming soon."
/>
</div>
)
}
return (
<>
<PageHeader>
<PageHeaderMeta>
<PageHeaderSummary>
<PageHeaderTitle>Usage</PageHeaderTitle>
</PageHeaderSummary>
</PageHeaderMeta>
</PageHeader>
<div className="sticky top-0 border-b bg-sidebar z-1">
<PageContainer>
<div className="py-4 flex items-center space-x-4">
{isLoadingSubscription || isLoadingPermissions ? (
<div className="flex lg:items-center items-start gap-3 flex-col lg:flex-row lg:justify-between w-full">
<div className="flex items-center gap-2">
<ShimmeringLoader className="w-48" />
<ShimmeringLoader className="w-48" />
</div>
<ShimmeringLoader className="w-[280px]" />
</div>
) : !canReadSubscriptions ? (
<NoPermission resourceText="view organization usage" />
) : null}
{isErrorSubscription && (
<AlertError
className="w-full"
subject="Failed to retrieve usage data"
error={subscriptionError}
/>
)}
{isSuccessSubscription && (
<div className="flex lg:items-center items-start gap-3 flex-col lg:flex-row lg:justify-between w-full">
<div className="flex flex-wrap items-center gap-2">
<DateRangePicker
onChange={setDateRange}
value={TIME_PERIODS_BILLING[0].key}
options={[...TIME_PERIODS_BILLING, ...TIME_PERIODS_REPORTS]}
loading={isLoadingSubscription}
currentBillingPeriodStart={subscription?.current_period_start}
currentBillingPeriodEnd={subscription?.current_period_end}
className="w-48!"
/>
<OrganizationProjectSelector
open={openProjectSelector}
setOpen={setOpenProjectSelector}
selectedRef={selectedProjectRef}
onSelect={(project) => {
setUsageFilter({ projectRef: project.ref, branchRef: null })
}}
renderTrigger={({ listboxId, open }) => {
return (
<Button
block
role="combobox"
size="tiny"
aria-expanded={open}
aria-controls={listboxId}
className="justify-between w-[180px]"
iconRight={
<ChevronDownIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
}
>
{selectedProject?.name ?? selectedProjectRef ?? 'All projects'}
</Button>
)
}}
renderRow={(project) => {
const isSelected = selectedProjectRef === project.ref
return (
<div className="w-full flex items-center justify-between">
<span className={cn('truncate', isSelected ? 'max-w-60' : 'max-w-64')}>
{project.name}
</span>
{isSelected && <CheckIcon size={16} />}
</div>
)
}}
renderActions={() => (
<CommandGroup>
<CommandItem
className="cursor-pointer flex items-center justify-between w-full"
onSelect={() => {
setOpenProjectSelector(false)
setUsageFilter({ projectRef: null, branchRef: null })
}}
onClick={() => {
setOpenProjectSelector(false)
setUsageFilter({ projectRef: null, branchRef: null })
}}
>
All projects
{!selectedProjectRef && <CheckIcon size={16} />}
</CommandItem>
</CommandGroup>
)}
/>
{isLoadingBranches && <ShimmeringLoader className="w-[180px] py-3.5" />}
{!isLoadingBranches && !!selectedProjectRef && (
<UsageBranchFilter
branchOptions={branchOptions}
projectRef={selectedProjectRef}
branchRef={selectedBranch?.project_ref ?? null}
onSelectBranch={(branchRef) =>
setUsageFilter({ projectRef: selectedProjectRef, branchRef })
}
/>
)}
</div>
<div className="flex items-center gap-2">
<p className={cn('text-sm transition', isLoadingSubscription && 'opacity-50')}>
Organization is on the{' '}
<span className="font-medium text-primary">{subscription.plan.name} Plan</span>
</p>
<span className="text-border-stronger">
<svg
viewBox="0 0 24 24"
width="16"
height="16"
stroke="currentColor"
strokeWidth="1"
strokeLinecap="round"
strokeLinejoin="round"
fill="none"
shapeRendering="geometricPrecision"
>
<path d="M16 3.549L7.12 20.600" />
</svg>
</span>
<p className="text-sm text-foreground-light">
{billingCycleStart.format('DD MMM YYYY')} -{' '}
{billingCycleEnd.format('DD MMM YYYY')}
</p>
</div>
</div>
)}
</div>
</PageContainer>
</div>
{isErrorOrgDailyStats && (
<PageContainer>
<PageSection className="last:pb-0">
<AlertError
error={orgDailyStatsError}
subject="Failed to retrieve usage statistics for organization"
/>
</PageSection>
</PageContainer>
)}
{isProjectLookupBlocked && (
<PageContainer className="mt-5">
<AlertError subject="Failed to retrieve project" error={selectedProjectError} />
</PageContainer>
)}
{isErrorBranches && (
<PageContainer className="mt-5">
<AlertError subject="Failed to retrieve branches" error={branchesError} />
</PageContainer>
)}
{isBranchLookupDenied && (
<PageContainer className="mt-5">
<NoPermission resourceText="view this branch's usage" />
</PageContainer>
)}
{isResolvingBranch && (
<PageContainer className="mt-5">
<div role="status" aria-label="Loading branch usage">
<ShimmeringLoader />
</div>
</PageContainer>
)}
{isBranchUnavailable && (
<PageContainer className="mt-5">
<Admonition
type="warning"
title="Branch unavailable"
description="The selected branch could not be found for this project. Showing usage for the parent project. Usage from deleted branches still counts toward the organization total."
/>
</PageContainer>
)}
{canShowUsage && (
<>
{selectedProject ? (
<UsageFilterNotice
branchName={selectedBranch?.name}
hasBranches={branchOptions.length > 0}
onViewOrganizationUsage={() => setUsageFilter({ projectRef: null, branchRef: null })}
/>
) : (
<PageContainer id="restriction" className="mt-5">
<Restriction />
</PageContainer>
)}
<TotalUsage
orgSlug={slug as string}
projectRef={usageProjectRef}
subscription={subscription}
startDate={startDate}
endDate={endDate}
currentBillingCycleSelected={currentBillingCycleSelected}
/>
{subscription?.plan.id !== 'free' && (
<Compute
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
/>
)}
{subscription?.plan.id === 'platform' && (
<ActiveCompute
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
/>
)}
<Egress
orgSlug={slug as string}
projectRef={usageProjectRef}
subscription={subscription}
currentBillingCycleSelected={currentBillingCycleSelected}
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
startDate={startDate}
endDate={endDate}
/>
<SizeAndCounts
orgSlug={slug as string}
projectRef={usageProjectRef}
subscription={subscription}
currentBillingCycleSelected={currentBillingCycleSelected}
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
startDate={startDate}
endDate={endDate}
/>
<Activity
orgSlug={slug as string}
projectRef={usageProjectRef}
subscription={subscription}
startDate={startDate}
endDate={endDate}
currentBillingCycleSelected={currentBillingCycleSelected}
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
/>
<OrgLogUsage
orgSlug={slug as string}
projectRef={usageProjectRef}
subscription={subscription}
startDate={startDate}
endDate={endDate}
currentBillingCycleSelected={currentBillingCycleSelected}
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats || isLoadingSubscription}
/>
<Pipelines
orgSlug={slug as string}
projectRef={usageProjectRef}
subscription={subscription}
startDate={startDate}
endDate={endDate}
currentBillingCycleSelected={currentBillingCycleSelected}
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
/>
</>
)}
</>
)
}