Skip to content

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

add spend cap side panel

Joshen Lim3ab0e895c013
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/CostControl/CostControl.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/CostControl/CostControl.tsx
index 90ea7c45e5f..82bc7c6571b 100644
--- a/studio/components/interfaces/Organization/BillingSettingsV2/CostControl/CostControl.tsx
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/CostControl/CostControl.tsx
@@ -2,22 +2,22 @@ import Link from 'next/link'
import { useParams, useTheme } from 'common'
import { BASE_PATH } from 'lib/constants'
-import { useSubscriptionPageStateSnapshot } from 'state/subscription-page'
import { Alert, Button, IconExternalLink } from 'ui'
-// import SpendCapSidePanel from './SpendCapSidePanel'
+import SpendCapSidePanel from './SpendCapSidePanel'
import { FormSection, FormSectionContent, FormSectionLabel } from 'components/ui/Forms'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
import { useFlag } from 'hooks'
+import { useOrgSettingsPageStateSnapshot } from 'state/organization-settings'
import ProjectUpdateDisabledTooltip from '../../BillingSettings/ProjectUpdateDisabledTooltip'
export interface CostControlProps {}
const CostControl = ({}: CostControlProps) => {
const { slug } = useParams()
- const snap = useSubscriptionPageStateSnapshot()
- const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')
const { isDarkMode } = useTheme()
+ const snap = useOrgSettingsPageStateSnapshot()
+ const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')
const { data: subscription, isLoading } = useOrgSubscriptionQuery({ orgSlug: slug })
const currentPlan = subscription?.plan
@@ -27,113 +27,118 @@ const CostControl = ({}: CostControlProps) => {
!projectUpdateDisabled && !['team', 'enterprise'].includes(currentPlan?.id || '')
return (
- <FormSection
- header={
- <FormSectionLabel>
- <div className="sticky space-y-6 top-16">
- <div>
- <p className="text-base">Cost Control</p>
- <p className="text-sm text-scale-1000">
- Control whether to use beyond your plans included quota
- </p>
- </div>
- <div className="space-y-2">
- <p className="text-sm text-scale-1100">More information</p>
+ <>
+ <FormSection
+ header={
+ <FormSectionLabel>
+ <div className="sticky space-y-6 top-16">
<div>
- <Link href="https://supabase.com/docs/guides/platform/spend-cap">
- <a target="_blank" rel="noreferrer">
- <div className="flex items-center space-x-2 opacity-50 hover:opacity-100 transition">
- <p className="text-sm">Spend cap</p>
- <IconExternalLink size={16} strokeWidth={1.5} />
- </div>
- </a>
- </Link>
+ <p className="text-base">Cost Control</p>
+ <p className="text-sm text-scale-1000">
+ Control whether to use beyond your plans included quota
+ </p>
</div>
- </div>
- </div>
- </FormSectionLabel>
- }
- >
- <FormSectionContent loading={isLoading}>
- <div className="space-y-6">
- {['team', 'enterprise'].includes(currentPlan?.id || '') ? (
- <Alert
- withIcon
- variant="info"
- title={`You will be charged for any additional usage on the ${
- currentPlan?.name || ''
- } plan`}
- >
- {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">
- <a className="text-sm text-green-900 transition hover:text-green-1000">
- included usage
- </a>
- </Link>{' '}
- is exceeded will you be charged for any additional usage.
- </Alert>
- ) : (
- <p className="text-sm text-scale-1000">
- You can control whether your organization is charged for additional usage beyond the{' '}
- <Link href="#breakdown">
- <a className="text-sm text-green-900 transition hover:text-green-1000">
- included quota
- </a>
- </Link>{' '}
- of your subscription plan. If you need to go beyond the included quota, simply switch
- off your spend cap to pay for additional usage.
- </p>
- )}
-
- <div className="flex space-x-6">
- <div>
- <div className="rounded-md bg-scale-100 dark:bg-scale-400 w-[160px] h-[96px] shadow">
- <img
- alt="Spend Cap"
- width={160}
- height={96}
- src={
- isUsageBillingEnabled
- ? `${BASE_PATH}/img/spend-cap-off${isDarkMode ? '' : '--light'}.png?v=3`
- : `${BASE_PATH}/img/spend-cap-on${isDarkMode ? '' : '--light'}.png?v=3`
- }
- />
+ <div className="space-y-2">
+ <p className="text-sm text-scale-1100">More information</p>
+ <div>
+ <Link href="https://supabase.com/docs/guides/platform/spend-cap">
+ <a target="_blank" rel="noreferrer">
+ <div className="flex items-center space-x-2 opacity-50 hover:opacity-100 transition">
+ <p className="text-sm">Spend cap</p>
+ <IconExternalLink size={16} strokeWidth={1.5} />
+ </div>
+ </a>
+ </Link>
+ </div>
</div>
</div>
- <div>
- <p className="mb-1">Spend cap is {isUsageBillingEnabled ? 'disabled' : 'enabled'}</p>
+ </FormSectionLabel>
+ }
+ >
+ <FormSectionContent loading={isLoading}>
+ <div className="space-y-6">
+ {['team', 'enterprise'].includes(currentPlan?.id || '') ? (
+ <Alert
+ withIcon
+ variant="info"
+ title={`You will be charged for any additional usage on the ${
+ currentPlan?.name || ''
+ } plan`}
+ >
+ {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">
+ <a className="text-sm text-green-900 transition hover:text-green-1000">
+ included usage
+ </a>
+ </Link>{' '}
+ is exceeded will you be charged for any additional usage.
+ </Alert>
+ ) : (
<p className="text-sm text-scale-1000">
- {isUsageBillingEnabled ? (
- <span>You will be charged for any usage above the included quota.</span>
- ) : (
- <span>
- You won't be charged any extra for usage. However, your projects could become
- unresponsive or enter read only mode if you exceed the included quota.
- </span>
- )}
+ You can control whether your organization is charged for additional usage beyond the{' '}
+ <Link href="#breakdown">
+ <a className="text-sm text-green-900 transition hover:text-green-1000">
+ included quota
+ </a>
+ </Link>{' '}
+ of your subscription plan. If you need to go beyond the included quota, simply
+ switch off your spend cap to pay for additional usage.
</p>
- {isUsageBillingEnabled && (
- <p className="text-sm text-scale-1000 mt-1">
- Your projects will never become unresponsive. Only when your usage reaches the
- quota limit will you be charged for any excess usage.
+ )}
+
+ <div className="flex space-x-6">
+ <div>
+ <div className="rounded-md bg-scale-100 dark:bg-scale-400 w-[160px] h-[96px] shadow">
+ <img
+ alt="Spend Cap"
+ width={160}
+ height={96}
+ src={
+ isUsageBillingEnabled
+ ? `${BASE_PATH}/img/spend-cap-off${isDarkMode ? '' : '--light'}.png?v=3`
+ : `${BASE_PATH}/img/spend-cap-on${isDarkMode ? '' : '--light'}.png?v=3`
+ }
+ />
+ </div>
+ </div>
+ <div>
+ <p className="mb-1">
+ Spend cap is {isUsageBillingEnabled ? 'disabled' : 'enabled'}
+ </p>
+ <p className="text-sm text-scale-1000">
+ {isUsageBillingEnabled ? (
+ <span>You will be charged for any usage above the included quota.</span>
+ ) : (
+ <span>
+ You won't be charged any extra for usage. However, your projects could become
+ unresponsive or enter read only mode if you exceed the included quota.
+ </span>
+ )}
</p>
- )}
- <ProjectUpdateDisabledTooltip projectUpdateDisabled={projectUpdateDisabled}>
- <Button
- type="default"
- className="mt-4"
- disabled={!canChangeTier}
- onClick={() => snap.setPanelKey('costControl')}
- >
- Change spend cap
- </Button>
- </ProjectUpdateDisabledTooltip>
+ {isUsageBillingEnabled && (
+ <p className="text-sm text-scale-1000 mt-1">
+ Your projects will never become unresponsive. Only when your usage reaches the
+ quota limit will you be charged for any excess usage.
+ </p>
+ )}
+ <ProjectUpdateDisabledTooltip projectUpdateDisabled={projectUpdateDisabled}>
+ <Button
+ type="default"
+ className="mt-4"
+ disabled={!canChangeTier}
+ onClick={() => snap.setPanelKey('costControl')}
+ >
+ Change spend cap
+ </Button>
+ </ProjectUpdateDisabledTooltip>
+ </div>
</div>
</div>
- </div>
- </FormSectionContent>
- </FormSection>
+ </FormSectionContent>
+ </FormSection>
+ <SpendCapSidePanel />
+ </>
)
}
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/CostControl/SpendCapSidePanel.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/CostControl/SpendCapSidePanel.tsx
new file mode 100644
index 00000000000..3013c81b829
--- /dev/null
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/CostControl/SpendCapSidePanel.tsx
@@ -0,0 +1,308 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import clsx from 'clsx'
+import { useParams, useTheme } from 'common'
+import Table from 'components/to-be-cleaned/Table'
+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
+import { useOrgSubscriptionUpdateMutation } from 'data/subscriptions/org-subscription-update-mutation'
+import { useCheckPermissions, useStore } from 'hooks'
+import { BASE_PATH, PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
+import Telemetry from 'lib/telemetry'
+import Link from 'next/link'
+import { useRouter } from 'next/router'
+import { useEffect, useState } from 'react'
+import { pricing } from 'shared-data/pricing'
+import { useOrgSettingsPageStateSnapshot } from 'state/organization-settings'
+import { Alert, Button, Collapsible, IconChevronRight, IconExternalLink, SidePanel } from 'ui'
+
+const SPEND_CAP_OPTIONS: {
+ name: string
+ value: 'on' | 'off'
+ imageUrl: string
+ imageUrlLight: string
+}[] = [
+ {
+ name: 'Spend cap enabled',
+ value: 'on',
+ imageUrl: `${BASE_PATH}/img/spend-cap-on.png`,
+ imageUrlLight: `${BASE_PATH}/img/spend-cap-on--light.png`,
+ },
+ {
+ name: 'Spend cap disabled',
+ value: 'off',
+ imageUrl: `${BASE_PATH}/img/spend-cap-off.png`,
+ imageUrlLight: `${BASE_PATH}/img/spend-cap-off--light.png`,
+ },
+]
+
+const SpendCapSidePanel = () => {
+ const { ui } = useStore()
+ const router = useRouter()
+ const { slug } = useParams()
+ const { isDarkMode } = useTheme()
+
+ const [showUsageCosts, setShowUsageCosts] = useState(false)
+ const [isSubmitting, setIsSubmitting] = useState<boolean>(false)
+ const [selectedOption, setSelectedOption] = useState<'on' | 'off'>()
+
+ const canUpdateSpendCap = useCheckPermissions(
+ PermissionAction.BILLING_WRITE,
+ 'stripe.subscriptions'
+ )
+
+ const snap = useOrgSettingsPageStateSnapshot()
+ const visible = snap.panelKey === 'costControl'
+ const onClose = () => snap.setPanelKey(undefined)
+
+ const { data: subscription, isLoading } = useOrgSubscriptionQuery({ orgSlug: slug })
+ const { mutateAsync: updateOrgSubscription } = useOrgSubscriptionUpdateMutation()
+
+ const isFreePlan = subscription?.plan?.id === 'free'
+ const isSpendCapOn = !subscription?.usage_billing_enabled
+ const isTurningOnCap = !isSpendCapOn && selectedOption === 'on'
+ const hasChanges = selectedOption !== (isSpendCapOn ? 'on' : 'off')
+
+ useEffect(() => {
+ if (visible && subscription !== undefined) {
+ setSelectedOption(isSpendCapOn ? 'on' : 'off')
+ Telemetry.sendActivity(
+ {
+ activity: 'Side Panel Viewed',
+ source: 'Dashboard',
+ data: {
+ title: 'Spend cap',
+ section: 'Cost Control',
+ },
+ },
+ router
+ )
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [visible, isLoading, subscription, isSpendCapOn])
+
+ const onConfirm = async () => {
+ if (!slug) return console.error('Org slug is required')
+
+ try {
+ const tier = (
+ selectedOption === 'on' ? PRICING_TIER_PRODUCT_IDS.PRO : PRICING_TIER_PRODUCT_IDS.PAYG
+ ) as 'tier_pro' | 'tier_payg'
+ setIsSubmitting(true)
+ await updateOrgSubscription({ slug, tier })
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully ${isTurningOnCap ? 'enabled' : 'disabled'} spend cap`,
+ })
+ onClose()
+ } catch (error: any) {
+ ui.setNotification({
+ error,
+ category: 'error',
+ message: `Unable to toggle spend cap: ${error.message}`,
+ })
+ } finally {
+ setIsSubmitting(false)
+ }
+ }
+
+ const billingMetricCategories: (keyof typeof pricing)[] = [
+ 'database',
+ 'auth',
+ 'storage',
+ 'realtime',
+ 'edge_functions',
+ ]
+
+ return (
+ <SidePanel
+ size="large"
+ loading={isLoading || isSubmitting}
+ disabled={isFreePlan || isLoading || !hasChanges || isSubmitting || !canUpdateSpendCap}
+ visible={visible}
+ onCancel={onClose}
+ onConfirm={onConfirm}
+ header={
+ <div className="flex items-center justify-between">
+ <h4>Spend cap</h4>
+ <Link href="https://supabase.com/docs/guides/platform/spend-cap">
+ <a target="_blank" rel="noreferrer">
+ <Button type="default" icon={<IconExternalLink strokeWidth={1.5} />}>
+ About spend cap
+ </Button>
+ </a>
+ </Link>
+ </div>
+ }
+ tooltip={!canUpdateSpendCap ? 'You do not have permission to update spend cap' : undefined}
+ >
+ <SidePanel.Content>
+ <div className="py-6 space-y-4">
+ <p className="text-sm">
+ Use the spend cap to manage project usage and costs, and control whether the project can
+ exceed the included quota allowance of any billed line item in a billing cycle
+ </p>
+
+ <Collapsible open={showUsageCosts} onOpenChange={setShowUsageCosts}>
+ <Collapsible.Trigger asChild>
+ <div className="flex items-center space-x-2 cursor-pointer">
+ <IconChevronRight
+ strokeWidth={1.5}
+ size={16}
+ className={showUsageCosts ? 'rotate-90' : ''}
+ />
+ <p className="text-sm text-scale-1100">
+ How are each resource charged after exceeding the included quota?
+ </p>
+ </div>
+ </Collapsible.Trigger>
+ <Collapsible.Content asChild>
+ <Table
+ className="mt-4"
+ head={
+ <>
+ <Table.th>
+ <p className="text-xs">Item</p>
+ </Table.th>
+ <Table.th>
+ <p className="text-xs">Rate</p>
+ </Table.th>
+ </>
+ }
+ body={billingMetricCategories.map((categoryId) => {
+ const category = pricing[categoryId]
+ const usageItems = category.features.filter((it: any) => it.usage_based)
+
+ return (
+ <>
+ <Table.tr key={categoryId}>
+ <Table.td>
+ <p className="text-xs text-scale-1200">{category.title}</p>
+ </Table.td>
+ <Table.td>{null}</Table.td>
+ </Table.tr>
+ {usageItems.map((item: any) => {
+ return (
+ <Table.tr key={item.title}>
+ <Table.td>
+ <p className="text-xs pl-4">{item.title}</p>
+ </Table.td>
+ <Table.td>
+ <p className="text-xs pl-4">
+ {item.plans[subscription?.plan?.id || 'pro']}
+ </p>
+ </Table.td>
+ </Table.tr>
+ )
+ })}
+ </>
+ )
+ })}
+ />
+ </Collapsible.Content>
+ </Collapsible>
+
+ {isFreePlan && (
+ <Alert
+ withIcon
+ variant="info"
+ title="Toggling of the spend cap is only available on the Pro plan"
+ actions={
+ <Button type="default" onClick={() => snap.setPanelKey('subscriptionPlan')}>
+ View available plans
+ </Button>
+ }
+ >
+ Upgrade your plan to disable the spend cap
+ </Alert>
+ )}
+
+ <div className="!mt-8 pb-4">
+ <div className="flex gap-3">
+ {SPEND_CAP_OPTIONS.map((option) => {
+ const isSelected = selectedOption === option.value
+
+ return (
+ <div
+ key={option.value}
+ className={clsx('col-span-4 group space-y-1', isFreePlan && 'opacity-75')}
+ onClick={() => {
+ !isFreePlan && setSelectedOption(option.value)
+ Telemetry.sendActivity(
+ {
+ activity: 'Option Selected',
+ source: 'Dashboard',
+ data: {
+ title: 'Spend cap',
+ section: 'Cost Control',
+ option: option.name,
+ },
+ },
+ router
+ )
+ }}
+ >
+ <img
+ alt="Spend Cap"
+ className={clsx(
+ 'relative rounded-xl transition border bg-no-repeat bg-center bg-cover w-[160px] h-[96px]',
+ isSelected
+ ? 'border-scale-1200'
+ : 'border-scale-900 opacity-50 group-hover:border-scale-1000 group-hover:opacity-100',
+ !isFreePlan && 'cursor-pointer',
+ !isFreePlan && !isSelected && 'group-hover:border-scale-1100'
+ )}
+ width={160}
+ height={96}
+ src={isDarkMode ? option.imageUrl : option.imageUrlLight}
+ />
+
+ <p
+ className={clsx(
+ 'text-sm transition',
+ !isFreePlan && 'group-hover:text-scale-1200',
+ isSelected ? 'text-scale-1200' : 'text-scale-1000'
+ )}
+ >
+ {option.name}
+ </p>
+ </div>
+ )
+ })}
+ </div>
+ </div>
+
+ {selectedOption === 'on' ? (
+ <Alert
+ withIcon
+ variant="warning"
+ title="Your projects could become unresponsive or enter read only mode"
+ >
+ Exceeding the included quota allowance with spend cap enabled can cause your projects
+ to become unresponsive or enter read only mode.
+ </Alert>
+ ) : (
+ <Alert
+ withIcon
+ variant="info"
+ title="Charges apply for usage beyond included quota allowance"
+ >
+ Your projects will always remain responsive and active, and charges only apply when
+ exceeding the included quota limit.
+ </Alert>
+ )}
+
+ {hasChanges && (
+ <>
+ <p className="text-sm">
+ {selectedOption === 'on'
+ ? 'Upon clicking confirm, spend cap will be enabled for your organization and you will no longer be charged any extra for usage.'
+ : 'Upon clicking confirm, spend cap will be disabled for your organization and you will be charged for any usage beyong the included quota.'}
+ </p>
+ </>
+ )}
+ </div>
+ </SidePanel.Content>
+ </SidePanel>
+ )
+}
+
+export default SpendCapSidePanel
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx
index 54c8044cb7e..0d9ffda0a02 100644
--- a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx
@@ -73,6 +73,7 @@ const PlanUpdateSidePanel = () => {
router
)
}
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [visible])
const onConfirmDowngrade = () => {