Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat: rework usage overview (#19434)

Kevin Grünebergfc5d389a9f81
diff --git a/apps/studio/components/interfaces/Billing/Subscription/Subscription.constants.ts b/apps/studio/components/interfaces/Billing/Subscription/Subscription.constants.ts
index 6c7ecd3b12a..426cb969fb2 100644
--- a/apps/studio/components/interfaces/Billing/Subscription/Subscription.constants.ts
+++ b/apps/studio/components/interfaces/Billing/Subscription/Subscription.constants.ts
@@ -16,7 +16,7 @@ export const BILLING_BREAKDOWN_METRICS = [
key: 'db_egress',
name: 'Database egress',
units: 'bytes',
- anchor: 'dbEgress',
+ anchor: 'egress',
metric: 'DATABASE_EGRESS',
category: 'Database',
unitName: 'GB',
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.constants.ts b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.constants.ts
index 4080e2dee5d..1152fb503de 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.constants.ts
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.constants.ts
@@ -15,7 +15,7 @@ export interface Metric {
export const BILLING_BREAKDOWN_METRICS: Metric[] = [
{
key: PricingMetric.DATABASE_SIZE,
- name: 'Database space',
+ name: 'Database Size',
units: 'bytes',
anchor: 'dbSize',
category: 'Database',
@@ -31,7 +31,7 @@ export const BILLING_BREAKDOWN_METRICS: Metric[] = [
},
{
key: PricingMetric.MONTHLY_ACTIVE_USERS,
- name: 'Active users',
+ name: 'Monthly Active Users',
units: 'absolute',
anchor: 'mau',
// metric: 'MONTHLY_ACTIVE_USERS',
@@ -40,7 +40,7 @@ export const BILLING_BREAKDOWN_METRICS: Metric[] = [
},
{
key: PricingMetric.MONTHLY_ACTIVE_SSO_USERS,
- name: 'Active SSO users',
+ name: 'Monthly Active SSO Users',
units: 'absolute',
anchor: 'mauSso',
// metric: 'MONTHLY_ACTIVE_SSO_USERS',
@@ -49,7 +49,7 @@ export const BILLING_BREAKDOWN_METRICS: Metric[] = [
},
{
key: PricingMetric.STORAGE_SIZE,
- name: 'Storage space',
+ name: 'Storage Size',
units: 'bytes',
anchor: 'storageSize',
// metric: 'STORAGE_SIZE',
@@ -67,7 +67,7 @@ export const BILLING_BREAKDOWN_METRICS: Metric[] = [
},
{
key: PricingMetric.REALTIME_PEAK_CONNECTIONS,
- name: 'Realtime peak connections',
+ name: 'Realtime Peak Connections',
units: 'absolute',
anchor: 'realtimePeakConnections',
// metric: 'REALTIME_PEAK_CONNECTIONS',
@@ -76,7 +76,7 @@ export const BILLING_BREAKDOWN_METRICS: Metric[] = [
},
{
key: PricingMetric.REALTIME_MESSAGE_COUNT,
- name: 'Realtime messages',
+ name: 'Realtime Messages',
units: 'absolute',
anchor: 'realtimeMessageCount',
// metric: 'REALTIME_MESSAGE_COUNT',
@@ -85,7 +85,7 @@ export const BILLING_BREAKDOWN_METRICS: Metric[] = [
},
{
key: PricingMetric.FUNCTION_INVOCATIONS,
- name: 'Edge Function invocations',
+ name: 'Edge Function Invocations',
units: 'absolute',
anchor: 'funcInvocations',
// metric: 'FUNCTION_INVOCATIONS',
@@ -94,7 +94,7 @@ export const BILLING_BREAKDOWN_METRICS: Metric[] = [
},
{
key: PricingMetric.FUNCTION_COUNT,
- name: 'Edge Functions',
+ name: 'Edge Function Count',
units: 'absolute',
anchor: 'funcCount',
// metric: 'FUNCTION_COUNT',
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx
index 57dcb12650d..adeb36cb37f 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx
@@ -9,49 +9,25 @@ import {
import AlertError from 'components/ui/AlertError'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
-import { useOrgUsageQuery } from 'data/usage/org-usage-query'
-import { useOrgSettingsPageStateSnapshot } from 'state/organization-settings'
-import { Alert, Button } from 'ui'
-import { BILLING_BREAKDOWN_METRICS } from './BillingBreakdown.constants'
-import BillingMetric from './BillingMetric'
import UpcomingInvoice from './UpcomingInvoice'
import { useIsFeatureEnabled } from 'hooks'
import Link from 'next/link'
const BillingBreakdown = () => {
- const snap = useOrgSettingsPageStateSnapshot()
const { slug: orgSlug } = useParams()
- const {
- data: usage,
- error: usageError,
- isLoading: isLoadingUsage,
- isError: isErrorUsage,
- isSuccess: isSuccessUsage,
- } = useOrgUsageQuery({ orgSlug })
+
const {
data: subscription,
error: subscriptionError,
isLoading: isLoadingSubscription,
isError: isErrorSubscription,
- isSuccess: isSuccessSubscription,
} = useOrgSubscriptionQuery({ orgSlug })
const invoiceFeatureEnabled = useIsFeatureEnabled('billing:invoices')
- const currentPlan = subscription?.plan
- const isUsageBillingEnabled = subscription?.usage_billing_enabled
const billingCycleStart = dayjs.unix(subscription?.current_period_start ?? 0).utc()
const billingCycleEnd = dayjs.unix(subscription?.current_period_end ?? 0).utc()
- const hasExceededAnyLimits =
- !isUsageBillingEnabled &&
- Boolean(
- usage?.usages.find(
- (metric) =>
- !metric.unlimited && metric.capped && metric.usage > (metric?.pricing_free_units ?? 0)
- )
- )
-
return (
<ScaffoldSection>
<ScaffoldSectionDetail>
@@ -76,101 +52,26 @@ const BillingBreakdown = () => {
<AlertError subject="Failed to retrieve subscription" error={subscriptionError} />
)}
- {isSuccessSubscription && (
+ {invoiceFeatureEnabled && (
<>
- <p className="text-sm">Included usage summary</p>
- {isUsageBillingEnabled ? (
- <p className="text-sm text-foreground-light">
- Your plan includes a limited amount of usage. If the usage on your organization
- exceeds these quotas, your subscription will be charged for the overages. It may
- take up to 24 hours for usage stats to update.
- </p>
- ) : (
- <p className="text-sm text-foreground-light">
- Your plan includes a limited amount of usage. If the usage on your organization
- exceeds these quotas, you may experience restrictions, as you are currently not
- billed for overages. It may take up to 24 hours for usage stats to update.
- </p>
- )}
-
- {hasExceededAnyLimits && (
- <Alert
- withIcon
- variant="danger"
- title="Your organization's usage has exceeded its included quota"
- actions={[
- <Button
- key="upgrade-button"
- type="default"
- className="ml-8"
- onClick={() =>
- snap.setPanelKey(
- currentPlan?.id === 'free' ? 'subscriptionPlan' : 'costControl'
- )
- }
- >
- {currentPlan?.id === 'free' ? 'Upgrade plan' : 'Change spend cap'}
- </Button>,
- ]}
+ <p className="text-sm">Upcoming cost for next invoice</p>
+ <p className="text-sm text-foreground-light">
+ The following table shows your upcoming costs excluding credits. Depending on your
+ usage, the final amount may vary. Next invoice on{' '}
+ <span className="text-foreground-light whitespace-nowrap">
+ {billingCycleEnd.format('MMM DD, YYYY')}
+ </span>
+ . See{' '}
+ <Link
+ className="text-green-900 transition hover:text-green-1000"
+ href={`/org/${orgSlug}/usage`}
>
- Your projects can become unresponsive or enter read only mode.{' '}
- {currentPlan?.id === 'free'
- ? 'Please upgrade to the Pro plan to ensure that your projects remain available.'
- : 'Please disable spend cap to ensure that your projects remain available.'}
- </Alert>
- )}
-
- {isLoadingUsage && (
- <div className="space-y-2">
- <ShimmeringLoader />
- <ShimmeringLoader className="w-3/4" />
- <ShimmeringLoader className="w-1/2" />
- </div>
- )}
-
- {isErrorUsage && (
- <AlertError subject="Failed to retrieve usage data" error={usageError} />
- )}
-
- {isSuccessUsage && (
- <div className="grid grid-cols-12">
- {BILLING_BREAKDOWN_METRICS.map((metric, i) => {
- return (
- <BillingMetric
- idx={i}
- key={metric.key}
- slug={orgSlug}
- metric={metric}
- usage={usage}
- subscription={subscription}
- />
- )
- })}
- </div>
- )}
-
- {invoiceFeatureEnabled && (
- <>
- <p className="!mt-10 text-sm">Upcoming cost for next invoice</p>
- <p className="text-sm text-foreground-light">
- The following table shows your upcoming costs excluding credits. Depending on your
- usage, the final amount may vary. Next invoice on{' '}
- <span className="text-foreground-light whitespace-nowrap">
- {billingCycleEnd.format('MMM DD, YYYY')}
- </span>
- . See&nbsp;
- <Link
- className="text-green-900 transition hover:text-green-1000"
- href={`/org/${orgSlug}/usage`}
- >
- usage page
- </Link>{' '}
- for a more detailed usage breakdown.
- </p>
+ usage page
+ </Link>{' '}
+ for a more detailed usage breakdown.
+ </p>
- <UpcomingInvoice slug={orgSlug} />
- </>
- )}
+ <UpcomingInvoice slug={orgSlug} />
</>
)}
</ScaffoldSectionContent>
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingMetric.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingMetric.tsx
index 9fca07b1202..61892131b54 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingMetric.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingMetric.tsx
@@ -1,14 +1,13 @@
import * as Tooltip from '@radix-ui/react-tooltip'
-import clsx from 'clsx'
import Link from 'next/link'
-import { BILLING_BREAKDOWN_METRICS } from 'components/interfaces/Billing/Subscription/Subscription.constants'
-import SparkBar from 'components/ui/SparkBar'
import { OrgSubscription } from 'data/subscriptions/org-subscription-query'
import { OrgUsageResponse } from 'data/usage/org-usage-query'
-import { useOrgSettingsPageStateSnapshot } from 'state/organization-settings'
-import { Button, IconAlertTriangle, IconChevronRight, IconInfo } from 'ui'
+import { Button, IconChevronRight, IconPieChart } from 'ui'
import { Metric, USAGE_APPROACHING_THRESHOLD } from './BillingBreakdown.constants'
+import { billingMetricUnit, formatUsage } from '../helpers'
+import { PricingMetric } from 'data/analytics/org-daily-stats-query'
+import { useMemo } from 'react'
export interface BillingMetricProps {
idx: number
@@ -16,173 +15,176 @@ export interface BillingMetricProps {
metric: Metric
usage: OrgUsageResponse
subscription: OrgSubscription
+ relativeToSubscription: boolean
}
-const BillingMetric = ({ idx, slug, metric, usage, subscription }: BillingMetricProps) => {
- const snap = useOrgSettingsPageStateSnapshot()
+const BillingMetric = ({
+ slug,
+ metric,
+ usage,
+ subscription,
+ relativeToSubscription,
+}: BillingMetricProps) => {
const usageMeta = usage.usages.find((x) => x.metric === metric.key)
- const usageRatio =
- typeof usageMeta !== 'number'
- ? (usageMeta?.usage ?? 0) / (usageMeta?.pricing_free_units ?? 0)
- : 0
- const usageFee = subscription?.usage_fees?.find((item) => item.metric === metric.key)
- const isUsageBillingEnabled = subscription?.usage_billing_enabled
- const largeNumberFormatter = new Intl.NumberFormat('en-US', { maximumFractionDigits: 0 })
+ const usageLabel = useMemo(() => {
+ if (!usageMeta) return ''
- const hasLimit = !!usageMeta?.unlimited === false
+ if (relativeToSubscription && usageMeta.available_in_plan === false) {
+ return 'Unavailable in plan'
+ } else if (
+ (usageMeta.cost && usageMeta.cost > 0) ||
+ !relativeToSubscription ||
+ usageMeta.unlimited
+ ) {
+ return metric.units === 'bytes'
+ ? `${usageMeta.usage.toLocaleString() ?? 0} GB`
+ : usageMeta.usage.toLocaleString()
+ } else {
+ return metric.units === 'bytes'
+ ? `${usageMeta.usage.toLocaleString() ?? 0} / ${usageMeta.pricing_free_units ?? 0} GB`
+ : `${usageMeta.usage.toLocaleString()} / ${usageMeta.pricing_free_units?.toLocaleString()}`
+ }
+ }, [usageMeta, relativeToSubscription, metric])
+
+ if (!usageMeta) return null
+
+ const usageRatio = usageMeta.usage / (usageMeta.pricing_free_units ?? 0)
+
+ const isUsageBillingEnabled = subscription?.usage_billing_enabled === true
+
+ const hasLimit = !!usageMeta.unlimited === false
const isApproachingLimit = hasLimit && usageRatio >= USAGE_APPROACHING_THRESHOLD
- const isExceededLimit = hasLimit && usageRatio >= 1
-
- const usageCurrentLabel =
- metric.units === 'bytes'
- ? `${usageMeta?.usage?.toLocaleString() ?? 0} GB`
- : usageMeta?.usage?.toLocaleString()
- const usageLimitLabel =
- metric.units === 'bytes'
- ? `${usageMeta?.pricing_free_units ?? 0} GB`
- : usageMeta?.pricing_free_units?.toLocaleString()
- const percentageLabel = `${(usageRatio * 100).toFixed(2)}%`
- const usageLabel = `${usageCurrentLabel} ${hasLimit ? `of ${usageLimitLabel}` : ''}`
+ const isExceededLimit = relativeToSubscription && hasLimit && usageRatio >= 1
+
+ const unit = billingMetricUnit(usageMeta.metric as PricingMetric)
+
+ const percentageLabel =
+ usageRatio < 0.01 ? '<1%' : `${(+(usageRatio * 100).toFixed(0)).toLocaleString()}%`
return (
- <div
- className={clsx(
- 'col-span-12 md:col-span-6 space-y-4 py-4 border-overlay',
- idx % 2 === 0 ? 'md:border-r md:pr-4' : 'md:pl-4',
- idx < BILLING_BREAKDOWN_METRICS.length - 3 && 'border-b'
- )}
- >
- <div className="flex items-center justify-between">
+ <div className="flex items-center justify-between">
+ <div>
<Link href={`/org/${slug}/usage#${metric.anchor}`}>
<div className="group flex items-center space-x-2">
<p className="text-sm text-foreground-light group-hover:text-foreground transition cursor-pointer">
{metric.name}
</p>
- <IconChevronRight
- strokeWidth={1.5}
- size={16}
- className="transition opacity-0 -translate-x-2 group-hover:opacity-100 group-hover:translate-x-0"
- />
+ <IconChevronRight strokeWidth={1.5} size={16} className="transition" />
</div>
</Link>
+ <span className="text-sm">{usageLabel}</span>&nbsp;
+ {usageMeta.cost && usageMeta.cost > 0 ? (
+ <span className="text-sm">(${usageMeta.cost})</span>
+ ) : usageMeta.available_in_plan && !usageMeta.unlimited && relativeToSubscription ? (
+ <span className="text-sm">({percentageLabel})</span>
+ ) : null}
+ </div>
- {isUsageBillingEnabled && hasLimit && usageFee && (
+ {usageMeta.available_in_plan ? (
+ <div>
<Tooltip.Root delayDuration={0}>
<Tooltip.Trigger>
- <div className="flex items-center">
- <IconInfo size={14} strokeWidth={2} className="hover:text-foreground-light" />
- </div>
+ {relativeToSubscription && !usageMeta.unlimited ? (
+ <svg className="h-8 w-8 -rotate-90 transform">
+ <circle
+ cx={15}
+ cy={15}
+ r={12}
+ fill="transparent"
+ stroke="currentColor"
+ strokeWidth={4}
+ className="text-background-surface-300"
+ />
+ <circle
+ cx={15}
+ cy={15}
+ r={12}
+ fill="transparent"
+ stroke="currentColor"
+ strokeDasharray={75.398}
+ strokeDashoffset={`calc(75.39822 - ${
+ usageRatio < 1 ? usageRatio * 100 : 100
+ } / 100 * 75.39822)`}
+ strokeWidth={4}
+ className={
+ isUsageBillingEnabled
+ ? 'text-gray-dark-800'
+ : isExceededLimit
+ ? 'text-red-900'
+ : isApproachingLimit
+ ? 'text-yellow-1000'
+ : 'text-gray-dark-800'
+ }
+ />
+ </svg>
+ ) : (
+ <IconPieChart className="h-8 w-8 p-1" />
+ )}
</Tooltip.Trigger>
<Tooltip.Portal>
<Tooltip.Content side="bottom">
<Tooltip.Arrow className="radix-tooltip-arrow" />
- <div
- className={[
- 'rounded bg-alternative py-1 px-2 leading-none shadow',
- 'border border-background',
- ].join(' ')}
- >
- <div className="text-xs text-foreground">
- {usageFee.pricingStrategy === 'UNIT' ? (
- <div>
- <p>
- {largeNumberFormatter.format(usageFee.pricingOptions.freeUnits)}{' '}
- {metric.unitName} included
- </p>
- <p>
- then ${usageFee.pricingOptions.perUnitPrice} per {metric.unitName}
- </p>
- </div>
- ) : usageFee.pricingStrategy === 'PACKAGE' ? (
- <div>
- <p>
- {largeNumberFormatter.format(usageFee.pricingOptions.freeUnits)} included
- </p>
-
- <p>
- then ${usageFee.pricingOptions.packagePrice} per{' '}
- {largeNumberFormatter.format(usageFee.pricingOptions.packageSize!)}
- </p>
- </div>
- ) : null}
- </div>
- </div>
- </Tooltip.Content>
- </Tooltip.Portal>
- </Tooltip.Root>
- )}
+ <div className="rounded bg-alternative py-1 px-2 leading-none shadow border border-background min-w-[250px]">
+ <div className="text-xs text-foreground max-w-sm space-y-2">
+ <p className="font-medium">{usageMeta.unit_price_desc}</p>
- {!isUsageBillingEnabled && usageRatio >= USAGE_APPROACHING_THRESHOLD && (
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger asChild>
- {isExceededLimit && !isUsageBillingEnabled ? (
- <div className="flex items-center space-x-2 min-w-[115px] cursor-help">
- <IconAlertTriangle size={14} strokeWidth={2} className="text-red-900" />
- <p className="text-sm text-red-900">Exceeded limit</p>
- </div>
- ) : isApproachingLimit && !isUsageBillingEnabled ? (
- <div className="flex items-center space-x-2 min-w-[115px] cursor-help">
- <IconAlertTriangle size={14} strokeWidth={2} className="text-amber-900" />
- <p className="text-sm text-amber-900">Approaching limit</p>
- </div>
- ) : null}
- </Tooltip.Trigger>
+ {usageMeta.project_allocations && usageMeta.project_allocations.length > 0 && (
+ <table className="list-disc w-full">
+ <thead>
+ <tr>
+ <th className="text-left">Project</th>
+ <th className="text-right">Usage</th>
+ </tr>
+ </thead>
+ <tbody>
+ {usageMeta.project_allocations.map((allocation) => (
+ <tr key={`${usageMeta.metric}_${allocation.ref}`}>
+ <td>{allocation.name}</td>
+ <td className="text-right">
+ {formatUsage(usageMeta.metric as PricingMetric, allocation.usage)}
+ </td>
+ </tr>
+ ))}
+ <tr></tr>
+ </tbody>
+ <tfoot>
+ <tr>
+ <td className="py-2 border-t text-left">
+ Total{unit && <span> ({unit})</span>}
+ </td>
+ <td className="py-2 border-t text-right">
+ {formatUsage(
+ usageMeta.metric as PricingMetric,
+ usageMeta.usage_original
+ )}{' '}
+ </td>
+ </tr>
+ </tfoot>
+ </table>
+ )}
- <Tooltip.Portal>
- <Tooltip.Content side="bottom">
- <Tooltip.Arrow className="radix-tooltip-arrow" />
- <div
- className={[
- 'rounded bg-alternative py-1 px-2 leading-none shadow',
- 'border border-background',
- ].join(' ')}
- >
- <p className="text-xs text-foreground">
- Exceeding your plans included usage will lead to restrictions to your project.
- </p>
- <p className="text-xs text-foreground">
- Upgrade to a usage-based plan or disable the spend cap to avoid restrictions.
- </p>
+ {subscription.usage_billing_enabled === false &&
+ relativeToSubscription &&
+ (isApproachingLimit || isExceededLimit) && (
+ <div className="mt-2">
+ <p className="text-xs">
+ Exceeding your plans included usage will lead to restrictions to your
+ project. Upgrade to a usage-based plan or disable the spend cap to avoid
+ restrictions.
+ </p>
+ </div>
+ )}
+ </div>
</div>
</Tooltip.Content>
</Tooltip.Portal>
</Tooltip.Root>
- )}
- </div>
- {usageMeta?.available_in_plan ? (
- <SparkBar
- type="horizontal"
- max={usageMeta.pricing_free_units || 1}
- value={usageMeta.usage ?? 0}
- barClass={
- !hasLimit && usageMeta.usage > 0
- ? 'bg-foreground-light'
- : isExceededLimit && !isUsageBillingEnabled
- ? 'bg-red-900'
- : isApproachingLimit && !isUsageBillingEnabled
- ? 'bg-amber-900'
- : 'bg-foreground-light'
- }
- bgClass="bg-overlay-hover"
- labelBottom={usageLabel}
- labelBottomClass="!text-foreground-light"
- labelTop={hasLimit ? percentageLabel : undefined}
- labelTopClass={
- !hasLimit
- ? ''
- : isExceededLimit && !isUsageBillingEnabled
- ? '!text-red-900'
- : isApproachingLimit && !isUsageBillingEnabled
- ? '!text-amber-900'
- : ''
- }
- />
+ </div>
) : (
- <div className="flex items-center justify-between flex-grow">
- <p className="text-sm text-foreground-light">Unavailable in your plan</p>
- <Button type="default" onClick={() => snap.setPanelKey('subscriptionPlan')}>
- Upgrade
+ <div>
+ <Button type="default" asChild>
+ <Link href={`/org/${slug}/billing?panel=subscriptionPlan`}>Upgrade</Link>
</Button>
</div>
)}
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/ComputeMetric.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/ComputeMetric.tsx
new file mode 100644
index 00000000000..66dcf5459f1
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/ComputeMetric.tsx
@@ -0,0 +1,109 @@
+import * as Tooltip from '@radix-ui/react-tooltip'
+import Link from 'next/link'
+
+import { OrgUsageResponse } from 'data/usage/org-usage-query'
+import { IconChevronRight, IconPieChart } from 'ui'
+import { Metric } from './BillingBreakdown.constants'
+import { formatUsage } from '../helpers'
+import { PricingMetric } from 'data/analytics/org-daily-stats-query'
+import { useMemo } from 'react'
+
+export interface ComputeMetricProps {
+ slug?: string
+ metric: Metric
+ usage: OrgUsageResponse
+ relativeToSubscription: boolean
+}
+
+const ComputeMetric = ({ slug, metric, usage, relativeToSubscription }: ComputeMetricProps) => {
+ const usageMeta = usage.usages.find((x) => x.metric === metric.key)
+
+ const usageLabel = useMemo(() => {
+ if (usageMeta?.cost && usageMeta.cost > 0) {
+ return `${usageMeta?.usage?.toLocaleString() ?? 0} hours`
+ } else {
+ return `${usageMeta?.usage?.toLocaleString() ?? 0} / ${
+ usageMeta?.pricing_free_units ?? 0
+ } hours`
+ }
+ }, [usageMeta])
+
+ return (
+ <div className="flex items-center justify-between">
+ <div>
+ <Link href={`/org/${slug}/usage#${metric.anchor}`}>
+ <div className="group flex items-center space-x-2">
+ <p className="text-sm text-foreground-light group-hover:text-foreground transition cursor-pointer">
+ {metric.name}
+ </p>
+ <IconChevronRight strokeWidth={1.5} size={16} className="transition" />
+ </div>
+ </Link>
+ <span className="text-sm">{usageLabel}</span>&nbsp;
+ {relativeToSubscription && usageMeta?.cost && usageMeta.cost > 0 ? (
+ <span className="text-sm">(${usageMeta?.cost})</span>
+ ) : null}
+ </div>
+ <div>
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger>
+ <IconPieChart className="h-8 w-8 p-1" />
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div className="rounded bg-alternative py-1 px-2 leading-none shadow border border-background min-w-[250px]">
+ <div className="text-xs text-foreground max-w-sm space-y-2">
+ <p className="font-medium">{usageMeta?.unit_price_desc}</p>
+
+ {usageMeta?.project_allocations && usageMeta.project_allocations.length > 0 && (
+ <table className="list-disc w-full">
+ <thead>
+ <tr>
+ <th className="text-left">Project</th>
+ <th className="text-right">Usage</th>
+ </tr>
+ </thead>
+ <tbody>
+ {usageMeta.project_allocations.map((allocation) => (
+ <tr key={`${usageMeta.metric}_${allocation.ref}`}>
+ <td>{allocation.name}</td>
+ <td className="text-right">
+ {formatUsage(usageMeta.metric as PricingMetric, allocation.usage)}
+ </td>
+ </tr>
+ ))}
+ <tr></tr>
+ </tbody>
+ <tfoot>
+ <tr>
+ <td className="py-2 border-t text-left">Total (Hours)</td>
+ <td className="py-2 border-t text-right">
+ {formatUsage(
+ usageMeta.metric as PricingMetric,
+ usageMeta.usage_original
+ )}
+ </td>
+ </tr>
+ </tfoot>
+ </table>
+ )}
+
+ <div className="mt-2">
+ <p className="text-xs">
+ Every project is a dedicated server and database. For every hour your project
+ is active, it incurs compute costs based on the instance size of your project.
+ Paused projects do not incur compute costs.
+ </p>
+ </div>
+ </div>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ </div>
+ </div>
+ )
+}
+
+export default ComputeMetric
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/CostControl.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/CostControl.tsx
index 3c97f90d9f7..b55eab52ee0 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/CostControl.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/CostControl.tsx
@@ -105,7 +105,7 @@ const CostControl = ({}: CostControlProps) => {
{currentPlan?.name || ''} plan requires you to have spend cap off at all times.
Your projects will never become unresponsive. Only when your{' '}
<Link
- href="#breakdown"
+ href={`/org/${slug}/usage`}
className="text-green-900 transition hover:text-green-1000"
>
included usage
@@ -117,7 +117,7 @@ const CostControl = ({}: CostControlProps) => {
You can control whether your organization is charged for additional usage beyond
the{' '}
<Link
- href="#breakdown"
+ href={`/org/${slug}/usage`}
className="text-green-900 transition hover:text-green-1000"
>
included quota
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
index a9c5390037b..2181e4d030c 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
@@ -35,8 +35,6 @@ import MembersExceedLimitModal from './MembersExceedLimitModal'
import PaymentMethodSelection from './PaymentMethodSelection'
import InformationBox from 'components/ui/InformationBox'
-// [Joshen TODO] Need to remove all contexts of "projects"
-
const PlanUpdateSidePanel = () => {
const { ui } = useStore()
const router = useRouter()
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/Subscription.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/Subscription.tsx
index 349303c71c8..96fa0e938db 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/Subscription.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/Subscription.tsx
@@ -3,6 +3,7 @@ import Link from 'next/link'
import { useParams } from 'common'
import {
+ ScaffoldContainer,
ScaffoldSection,
ScaffoldSectionContent,
ScaffoldSectionDetail,
@@ -25,6 +26,7 @@ import {
import ProjectUpdateDisabledTooltip from '../ProjectUpdateDisabledTooltip'
import PlanUpdateSidePanel from './PlanUpdateSidePanel'
import { useOrganizationBillingSubscriptionCancelSchedule } from 'data/subscriptions/org-subscription-cancel-schedule-mutation'
+import { useOrgUsageQuery } from 'data/usage/org-usage-query'
const Subscription = () => {
const { slug } = useParams()
@@ -39,6 +41,8 @@ const Subscription = () => {
isSuccess,
} = useOrgSubscriptionQuery({ orgSlug: slug })
+ const { data: usage } = useOrgUsageQuery({ orgSlug: slug })
+
const { mutate: cancelSubscriptionSchedule, isLoading: cancelSubscriptionScheduleLoading } =
useOrganizationBillingSubscriptionCancelSchedule()
@@ -51,8 +55,49 @@ const Subscription = () => {
const canChangeTier = !projectUpdateDisabled && !['enterprise'].includes(currentPlan?.id ?? '')
+ const hasExceededAnyLimits = Boolean(
+ usage?.usages.find(
+ (metric) =>
+ !metric.unlimited && metric.capped && metric.usage > (metric?.pricing_free_units ?? 0)
+ )
+ )
+
return (
<>
+ {subscription && hasExceededAnyLimits && (
+ <div className="mt-5">
+ <Alert
+ withIcon
+ variant="danger"
+ title="Your organization's usage has exceeded its included quota"
+ actions={[
+ <div key="upgrade-buttons" className="space-x-3">
+ <Button asChild type="outline">
+ <Link href={`/org/${slug}/usage`}>View usage</Link>
+ </Button>
+
+ <Button asChild type="default">
+ <Link
+ href={`/org/${slug}/billing?panel=${
+ subscription.plan.id === 'free' ? 'subscriptionPlan' : 'costControl'
+ }`}
+ >
+ {subscription.plan.id === 'free' ? 'Upgrade plan' : 'Change spend cap'}
+ </Link>
+ </Button>
+ </div>,
+ ]}
+ >
+ <p>
+ Your projects can become unresponsive or enter read-only mode.{' '}
+ {subscription.plan.id === 'free'
+ ? 'Please upgrade to the Pro plan to ensure that your projects remain available.'
+ : 'Please disable Spend Cap to ensure that your projects remain available.'}
+ </p>
+ </Alert>
+ </div>
+ )}
+
<ScaffoldSection>
<ScaffoldSectionDetail>
<div className="sticky space-y-6 top-12">
@@ -185,7 +230,7 @@ const Subscription = () => {
<div className="text-sm text-foreground-light mr-2">
When this organization exceeds its{' '}
<Link
- href="#breakdown"
+ href={`/org/${slug}/usage`}
className="text-sm text-green-900 transition hover:text-green-1000"
>
included usage quotas
diff --git a/apps/studio/components/interfaces/Organization/Usage/Bandwidth.tsx b/apps/studio/components/interfaces/Organization/Usage/Bandwidth.tsx
index 63a30d5773a..db02c05af0a 100644
--- a/apps/studio/components/interfaces/Organization/Usage/Bandwidth.tsx
+++ b/apps/studio/components/interfaces/Organization/Usage/Bandwidth.tsx
@@ -12,7 +12,6 @@ export interface BandwidthProps {
currentBillingCycleSelected: boolean
}
-// [Joshen TODO] Needs to take in org slug and eventually use daily stats org query
const Bandwidth = ({
orgSlug,
projectRef,
diff --git a/apps/studio/components/interfaces/Organization/Usage/TotalUsage.tsx b/apps/studio/components/interfaces/Organization/Usage/TotalUsage.tsx
new file mode 100644
index 00000000000..bd14899e486
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/Usage/TotalUsage.tsx
@@ -0,0 +1,210 @@
+import { OrgSubscription } from 'data/subscriptions/org-subscription-query'
+import SectionContent from './SectionContent'
+import ShimmeringLoader from 'components/ui/ShimmeringLoader'
+import AlertError from 'components/ui/AlertError'
+import { useMemo } from 'react'
+import { useOrgUsageQuery } from 'data/usage/org-usage-query'
+import BillingMetric from '../BillingSettings/BillingBreakdown/BillingMetric'
+import { BILLING_BREAKDOWN_METRICS } from '../BillingSettings/BillingBreakdown/BillingBreakdown.constants'
+import ComputeMetric from '../BillingSettings/BillingBreakdown/ComputeMetric'
+import clsx from 'clsx'
+import { ComputeUsageMetric, computeUsageMetricLabel } from 'data/analytics/org-daily-stats-query'
+
+export interface ComputeProps {
+ orgSlug: string
+ projectRef?: string
+ startDate: string | undefined
+ endDate: string | undefined
+ subscription: OrgSubscription | undefined
+ currentBillingCycleSelected: boolean
+}
+
+const TotalUsage = ({
+ orgSlug,
+ projectRef,
+ subscription,
+ startDate,
+ endDate,
+ currentBillingCycleSelected,
+}: ComputeProps) => {
+ const isUsageBillingEnabled = subscription?.usage_billing_enabled
+
+ const {
+ data: usage,
+ error: usageError,
+ isLoading: isLoadingUsage,
+ isError: isErrorUsage,
+ isSuccess: isSuccessUsage,
+ } = useOrgUsageQuery({
+ orgSlug,
+ projectRef,
+ start: !currentBillingCycleSelected && startDate ? new Date(startDate) : undefined,
+ end: !currentBillingCycleSelected && endDate ? new Date(endDate) : undefined,
+ })
+
+ // When the user filters by project ref or selects a custom timeframe, we only display usage+project breakdown, but no costs/limits
+ const showRelationToSubscription = currentBillingCycleSelected && !projectRef
+
+ const hasExceededAnyLimits =
+ showRelationToSubscription &&
+ Boolean(
+ usage?.usages.find(
+ (metric) => !metric.unlimited && metric.usage > (metric?.pricing_free_units ?? 0)
+ )
+ )
+
+ const sortedBillingMetrics = useMemo(() => {
+ if (!usage) return BILLING_BREAKDOWN_METRICS
+
+ return BILLING_BREAKDOWN_METRICS.slice().sort((a, b) => {
+ const usageMetaA = usage.usages.find((x) => x.metric === a.key)
+ const usageRatioA =
+ typeof usageMetaA !== 'number'
+ ? (usageMetaA?.usage ?? 0) / (usageMetaA?.pricing_free_units ?? 0)
+ : 0
+
+ const usageMetaB = usage.usages.find((x) => x.metric === b.key)
+ const usageRatioB =
+ typeof usageMetaB !== 'number'
+ ? (usageMetaB?.usage ?? 0) / (usageMetaB?.pricing_free_units ?? 0)
+ : 0
+
+ return (
+ // Sort unavailable features to bottom
+ Number(usageMetaB?.available_in_plan) - Number(usageMetaA?.available_in_plan) ||
+ // Sort high-usage features to top
+ usageRatioB - usageRatioA
+ )
+ })
+ }, [usage])
+
+ const computeMetrics = (usage?.usages || [])
+ .filter((it) => it.metric.startsWith('COMPUTE'))
+ .map((it) => it.metric) as ComputeUsageMetric[]
+
+ return (
+ <div id="summary">
+ <SectionContent
+ section={{
+ name: 'Usage Summary',
+ description: isUsageBillingEnabled
+ ? 'Your plan includes a limited amount of usage. If the usage on your organization exceeds these quotas, your subscription will be charged for the overages. It may take up to 24 hours for usage stats to update.'
+ : 'Your plan includes a limited amount of usage. If the usage on your organization exceeds these quotas, you may experience restrictions, as you are currently not billed for overages. It may take up to 24 hours for usage stats to update.',
+ links: [
+ {
+ name: 'How billing works',
+ url: 'https://supabase.com/docs/guides/platform/org-based-billing',
+ },
+ {
+ name: 'Supabase Plans',
+ url: 'https://supabase.com/pricing',
+ },
+ ],
+ }}
+ >
+ {isLoadingUsage && (
+ <div className="space-y-2">
+ <ShimmeringLoader />
+ <ShimmeringLoader className="w-3/4" />
+ <ShimmeringLoader className="w-1/2" />
+ </div>
+ )}
+
+ {isErrorUsage && <AlertError subject="Failed to retrieve usage data" error={usageError} />}
+
+ {isSuccessUsage && subscription && (
+ <div>
+ {showRelationToSubscription && (
+ <p className="text-sm">
+ {!hasExceededAnyLimits ? (
+ <span>
+ You have not exceeded your{' '}
+ <span className="font-medium">{subscription?.plan.name}</span> plan quota in
+ this billing cycle.
+ </span>
+ ) : hasExceededAnyLimits && subscription?.plan?.id === 'free' ? (
+ <span>
+ You have exceeded your{' '}
+ <span className="font-medium">{subscription?.plan.name}</span> plan quota in
+ this billing cycle. Upgrade your plan to continue using Supabase without
+ restrictions.
+ </span>
+ ) : hasExceededAnyLimits &&
+ subscription?.usage_billing_enabled === false &&
+ subscription?.plan?.id === 'pro' ? (
+ <span>
+ You have exceeded your{' '}
+ <span className="font-medium">{subscription?.plan.name}</span> plan quota in
+ this billing cycle. Disable your spend cap to continue using Supabase without
+ restrictions.
+ </span>
+ ) : hasExceededAnyLimits && subscription?.usage_billing_enabled === true ? (
+ <span>
+ You have exceeded your{' '}
+ <span className="font-medium">{subscription?.plan.name}</span> plan quota in
+ this billing cycle and will be charged for over-usage.
+ </span>
+ ) : (
+ <span>
+ You have not exceeded your{' '}
+ <span className="font-medium">{subscription?.plan.name}</span> plan quota in
+ this billing cycle.
+ </span>
+ )}
+ </p>
+ )}
+ <div className="grid grid-cols-12 mt-3">
+ {sortedBillingMetrics.map((metric, i) => {
+ return (
+ <div
+ className={clsx(
+ 'col-span-12 md:col-span-6 space-y-4 py-4 border-overlay',
+ i % 2 === 0 ? 'md:border-r md:pr-4' : 'md:pl-4',
+ 'border-b'
+ )}
+ key={metric.key}
+ >
+ <BillingMetric
+ idx={i}
+ slug={orgSlug}
+ metric={metric}
+ usage={usage}
+ subscription={subscription!}
+ relativeToSubscription={showRelationToSubscription}
+ />
+ </div>
+ )
+ })}
+
+ {computeMetrics.map((metric, i) => (
+ <div
+ className={clsx(
+ 'col-span-12 md:col-span-6 space-y-4 py-4 border-overlay',
+ i % 2 === 0 ? 'md:border-r md:pr-4' : 'md:pl-4'
+ )}
+ key={metric}
+ >
+ <ComputeMetric
+ slug={orgSlug}
+ metric={{
+ key: metric,
+ name: computeUsageMetricLabel(metric) + ' Compute Hours' || metric,
+ units: 'hours',
+ anchor: 'compute',
+ category: 'Compute',
+ unitName: 'GB',
+ }}
+ relativeToSubscription={showRelationToSubscription}
+ usage={usage}
+ />
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </SectionContent>
+ </div>
+ )
+}
+
+export default TotalUsage
diff --git a/apps/studio/components/interfaces/Organization/Usage/Usage.constants.tsx b/apps/studio/components/interfaces/Organization/Usage/Usage.constants.tsx
index 3dc11511099..52cb9c5f817 100644
--- a/apps/studio/components/interfaces/Organization/Usage/Usage.constants.tsx
+++ b/apps/studio/components/interfaces/Organization/Usage/Usage.constants.tsx
@@ -77,7 +77,7 @@ export const USAGE_CATEGORIES: CategoryMeta[] = [
description: 'Amount of data transmitted over all network connections',
attributes: [
{
- anchor: 'dbEgress',
+ anchor: 'egress',
key: PricingMetric.EGRESS,
attributes: [
{ key: EgressType.AUTH, name: 'Auth Egress', color: 'yellow' },
@@ -250,7 +250,7 @@ export const USAGE_CATEGORIES: CategoryMeta[] = [
],
},
{
- anchor: 'functionInvocations',
+ anchor: 'funcInvocations',
key: PricingMetric.FUNCTION_INVOCATIONS,
attributes: [{ key: PricingMetric.FUNCTION_INVOCATIONS.toLowerCase(), color: 'white' }],
name: 'Edge Function Invocations',
@@ -282,7 +282,7 @@ export const USAGE_CATEGORIES: CategoryMeta[] = [
],
},
{
- anchor: 'realtimePeakConnection',
+ anchor: 'realtimePeakConnections',
key: PricingMetric.REALTIME_PEAK_CONNECTIONS,
attributes: [
{ key: PricingMetric.REALTIME_PEAK_CONNECTIONS.toLowerCase(), color: 'white' },
diff --git a/apps/studio/components/interfaces/Organization/Usage/Usage.tsx b/apps/studio/components/interfaces/Organization/Usage/Usage.tsx
index 8b97c49e296..5ead89fd691 100644
--- a/apps/studio/components/interfaces/Organization/Usage/Usage.tsx
+++ b/apps/studio/components/interfaces/Organization/Usage/Usage.tsx
@@ -19,6 +19,7 @@ import Activity from './Activity'
import Bandwidth from './Bandwidth'
import SizeAndCounts from './SizeAndCounts'
import Compute from './Compute'
+import TotalUsage from './TotalUsage'
const Usage = () => {
const { slug, projectRef } = useParams()
@@ -187,7 +188,7 @@ const Usage = () => {
</Button>,
]}
>
- Your projects can become unresponsive or enter read only mode.{' '}
+ Your projects can become unresponsive or enter read-only mode.{' '}
{subscription.plan.id === 'free'
? 'Please upgrade to the Pro plan to ensure that your projects remain available.'
: 'Please disable spend cap to ensure that your projects remain available.'}
@@ -229,6 +230,15 @@ const Usage = () => {
</ScaffoldContainer>
)}
+ <TotalUsage
+ orgSlug={slug as string}
+ projectRef={selectedProjectRef}
+ subscription={subscription}
+ startDate={startDate}
+ endDate={endDate}
+ currentBillingCycleSelected={currentBillingCycleSelected}
+ />
+
<Compute
orgSlug={slug as string}
projectRef={selectedProjectRef}
diff --git a/apps/studio/components/interfaces/Organization/Usage/UsageSection/AttributeUsage.tsx b/apps/studio/components/interfaces/Organization/Usage/UsageSection/AttributeUsage.tsx
index 88075ee71fa..3fce47adf2b 100644
--- a/apps/studio/components/interfaces/Organization/Usage/UsageSection/AttributeUsage.tsx
+++ b/apps/studio/components/interfaces/Organization/Usage/UsageSection/AttributeUsage.tsx
@@ -7,7 +7,7 @@ import Panel from 'components/ui/Panel'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import SparkBar from 'components/ui/SparkBar'
import { OrgSubscription } from 'data/subscriptions/org-subscription-query'
-import { OrgUsageResponse, UsageMetric } from 'data/usage/org-usage-query'
+import { OrgMetricsUsage, OrgUsageResponse } from 'data/usage/org-usage-query'
import { USAGE_APPROACHING_THRESHOLD } from 'lib/constants'
import { useMemo } from 'react'
import { ResponseError } from 'types'
@@ -27,7 +27,7 @@ export interface AttributeUsageProps {
projectRef?: string
attribute: CategoryAttribute
usage?: OrgUsageResponse
- usageMeta?: UsageMetric
+ usageMeta?: OrgMetricsUsage
chartMeta: ChartMeta
subscription?: OrgSubscription
@@ -79,7 +79,7 @@ const AttributeUsage = ({
}, [attribute.attributes, chartData])
return (
- <div id={attribute.anchor}>
+ <div id={attribute.anchor} className="scroll-my-12">
<SectionContent section={attribute}>
{isLoading && (
<div className="space-y-2">
@@ -148,16 +148,6 @@ const AttributeUsage = ({
</Tooltip.Root>
)}
</div>
-
- {showUsageWarning && (
- <Button type="default" size="tiny" asChild>
- <Link href={upgradeUrl} className="pb-1">
- {subscription?.plan?.id === 'free'
- ? 'Upgrade plan'
- : 'Change spend cap'}
- </Link>
- </Button>
- )}
</div>
{currentBillingCycleSelected && !usageMeta.unlimited && (
diff --git a/apps/studio/components/ui/OveragesBanner/OveragesBanner.utils.ts b/apps/studio/components/ui/OveragesBanner/OveragesBanner.utils.ts
index b5b65aa5f65..9011364f955 100644
--- a/apps/studio/components/ui/OveragesBanner/OveragesBanner.utils.ts
+++ b/apps/studio/components/ui/OveragesBanner/OveragesBanner.utils.ts
@@ -1,6 +1,6 @@
-import { UsageMetric } from 'data/usage/org-usage-query'
+import { OrgMetricsUsage } from 'data/usage/org-usage-query'
-export const getResourcesExceededLimitsOrg = (usageMetrics: UsageMetric[]): string[] => {
+export const getResourcesExceededLimitsOrg = (usageMetrics: OrgMetricsUsage[]): string[] => {
if (!usageMetrics.length) return []
return usageMetrics
diff --git a/apps/studio/data/api.d.ts b/apps/studio/data/api.d.ts
index c1d778541c1..5cf1cba1cf3 100644
--- a/apps/studio/data/api.d.ts
+++ b/apps/studio/data/api.d.ts
@@ -1831,6 +1831,7 @@ export interface components {
PASSWORD_HIBP_ENABLED?: boolean
PASSWORD_MIN_LENGTH?: number
PASSWORD_REQUIRED_CHARACTERS?: string
+ SECURITY_MANUAL_LINKING_ENABLED: boolean
SECURITY_UPDATE_PASSWORD_REQUIRE_REAUTHENTICATION: boolean
SECURITY_REFRESH_TOKEN_REUSE_INTERVAL: number
MAILER_OTP_EXP: number
@@ -1855,6 +1856,8 @@ export interface components {
SMS_TEMPLATE: string
SMS_TEST_OTP: string
SMS_TEST_OTP_VALID_UNTIL: string
+ HOOK_MFA_VERIFICATION_ATTEMPT_ENABLED?: boolean
+ HOOK_MFA_VERIFICATION_ATTEMPT_URI?: string
EXTERNAL_APPLE_ENABLED: boolean
EXTERNAL_APPLE_CLIENT_ID: string
EXTERNAL_APPLE_SECRET: string
@@ -1965,6 +1968,7 @@ export interface components {
RATE_LIMIT_TOKEN_REFRESH?: number
MAILER_SECURE_EMAIL_CHANGE_ENABLED?: boolean
REFRESH_TOKEN_ROTATION_ENABLED?: boolean
+ PASSWORD_HIBP_ENABLED?: boolean
PASSWORD_MIN_LENGTH?: number
/** @enum {string} */
PASSWORD_REQUIRED_CHARACTERS?:
@@ -1972,6 +1976,7 @@ export interface components {
| 'abcdefghijklmnopqrstuvwxyz:ABCDEFGHIJKLMNOPQRSTUVWXYZ:0123456789'
| 'abcdefghijklmnopqrstuvwxyz:ABCDEFGHIJKLMNOPQRSTUVWXYZ:0123456789:!@#$%^&*()_+-=[]{};\'\\:"|<>?,./`~'
| ''
+ SECURITY_MANUAL_LINKING_ENABLED?: boolean
SECURITY_UPDATE_PASSWORD_REQUIRE_REAUTHENTICATION?: boolean
SECURITY_REFRESH_TOKEN_REUSE_INTERVAL?: number
MAILER_OTP_EXP?: number
@@ -1997,6 +2002,8 @@ export interface components {
SMS_VONAGE_API_SECRET?: string
SMS_VONAGE_FROM?: string
SMS_TEMPLATE?: string
+ HOOK_MFA_VERIFICATION_ATTEMPT_ENABLED?: boolean
+ HOOK_MFA_VERIFICATION_ATTEMPT_URI?: string
EXTERNAL_APPLE_ENABLED?: boolean
EXTERNAL_APPLE_CLIENT_ID?: string
EXTERNAL_APPLE_SECRET?: string
@@ -2107,8 +2114,10 @@ export interface components {
RATE_LIMIT_TOKEN_REFRESH?: number
MAILER_SECURE_EMAIL_CHANGE_ENABLED: boolean
REFRESH_TOKEN_ROTATION_ENABLED: boolean
+ PASSWORD_HIBP_ENABLED?: boolean
PASSWORD_MIN_LENGTH?: number
PASSWORD_REQUIRED_CHARACTERS?: string
+ SECURITY_MANUAL_LINKING_ENABLED: boolean
SECURITY_UPDATE_PASSWORD_REQUIRE_REAUTHENTICATION: boolean
SECURITY_REFRESH_TOKEN_REUSE_INTERVAL: number
MAILER_OTP_EXP: number
@@ -2133,6 +2142,8 @@ export interface components {
SMS_TEMPLATE: string
SMS_TEST_OTP: string
SMS_TEST_OTP_VALID_UNTIL: string
+ HOOK_MFA_VERIFICATION_ATTEMPT_ENABLED?: boolean
+ HOOK_MFA_VERIFICATION_ATTEMPT_URI?: string
EXTERNAL_APPLE_ENABLED: boolean
EXTERNAL_APPLE_CLIENT_ID: string
EXTERNAL_APPLE_SECRET: string
@@ -2449,6 +2460,7 @@ export interface components {
ProjectAllocation: {
ref: string
usage: number
+ name: string
}
OrgMetricUsage: {
usage: number
@@ -3586,6 +3598,7 @@ export interface components {
services: (
| 'adminapi'
| 'api-gateway'
+ | 'envoy'
| 'functions'
| 'gotrue'
| 'kong'
diff --git a/apps/studio/data/usage/keys.ts b/apps/studio/data/usage/keys.ts
index 54be56a1858..066dca1bc6f 100644
--- a/apps/studio/data/usage/keys.ts
+++ b/apps/studio/data/usage/keys.ts
@@ -1,5 +1,6 @@
export const usageKeys = {
usage: (projectRef: string | undefined) => ['projects', projectRef, 'usage'] as const,
- orgUsage: (orgSlug: string | undefined) => ['organizations', orgSlug, 'usage'] as const,
+ orgUsage: (orgSlug: string | undefined, projectRef?: string, start?: string, end?: string) =>
+ ['organizations', orgSlug, 'usage', projectRef, start, end] as const,
resourceWarnings: () => ['projects', 'resource-warnings'] as const,
}
diff --git a/apps/studio/data/usage/org-usage-query.ts b/apps/studio/data/usage/org-usage-query.ts
index 126f138cb0c..4bc23315c7a 100644
--- a/apps/studio/data/usage/org-usage-query.ts
+++ b/apps/studio/data/usage/org-usage-query.ts
@@ -1,55 +1,45 @@
-import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'
-import { get } from 'lib/common/fetch'
-import { API_URL } from 'lib/constants'
-import { useCallback } from 'react'
+import { useQuery, UseQueryOptions } from '@tanstack/react-query'
+import { get } from 'data/fetchers'
import { usageKeys } from './keys'
import { ResponseError } from 'types'
-import { PricingMetric } from 'data/analytics/org-daily-stats-query'
+import { components } from 'data/api'
export type OrgUsageVariables = {
orgSlug?: string
+ projectRef?: string
+ start?: Date
+ end?: Date
}
-export interface UsageMetric {
- /** Determines if the metric is available based on the plan */
- available_in_plan: boolean
- cost: number
- metric: PricingMetric
- unlimited: boolean
- /** Determines if over-usage is allowed or not */
- capped: boolean
- /** Refers to the included quota, in GB by default for bytes */
- pricing_free_units?: number
- pricing_package_price?: number
- pricing_package_size?: number
- pricing_per_unit_price?: number
- pricing_strategy: 'UNIT' | 'PACKAGE' | 'NONE'
- usage: number
-}
-
-export type OrgUsageResponse = {
- slugs: string[]
- usage_billing_enabled: boolean
- usages: UsageMetric[]
-}
+export type OrgUsageResponse = components['schemas']['OrgUsageResponse']
+export type OrgMetricsUsage = components['schemas']['OrgMetricUsage']
-export async function getOrgUsage({ orgSlug }: OrgUsageVariables, signal?: AbortSignal) {
+export async function getOrgUsage(
+ { orgSlug, projectRef, start, end }: OrgUsageVariables,
+ signal?: AbortSignal
+): Promise<OrgUsageResponse> {
if (!orgSlug) throw new Error('orgSlug is required')
- const response = await get(`${API_URL}/organizations/${orgSlug}/usage`, { signal })
- if (response.error) throw response.error
- return response as OrgUsageResponse
+ const { data, error } = await get(`/platform/organizations/{slug}/usage`, {
+ params: {
+ path: { slug: orgSlug },
+ query: { project_ref: projectRef, start: start?.toISOString(), end: end?.toISOString() },
+ },
+ signal,
+ })
+ if (error) throw error
+ return data
}
export type OrgUsageData = Awaited<ReturnType<typeof getOrgUsage>>
export type OrgUsageError = ResponseError
export const useOrgUsageQuery = <TData = OrgUsageData>(
- { orgSlug }: OrgUsageVariables,
+ { orgSlug, projectRef, start, end }: OrgUsageVariables,
{ enabled = true, ...options }: UseQueryOptions<OrgUsageData, OrgUsageError, TData> = {}
) =>
useQuery<OrgUsageData, OrgUsageError, TData>(
- usageKeys.orgUsage(orgSlug),
- ({ signal }) => getOrgUsage({ orgSlug }, signal),
+ usageKeys.orgUsage(orgSlug, projectRef, start?.toISOString(), end?.toISOString()),
+ ({ signal }) => getOrgUsage({ orgSlug, projectRef, start, end }, signal),
{
enabled: enabled && typeof orgSlug !== 'undefined',
...options,