import { useParams } from 'common' import { ChevronRightIcon, ExternalLinkIcon } from 'lucide-react' import { useTheme } from 'next-themes' import { Fragment, useEffect, useMemo, useState } from 'react' import { pricing } from 'shared-data/pricing' import { toast } from 'sonner' import { Button, Card, CardContent, cn, Collapsible, CollapsibleContent, CollapsibleTrigger, Sheet, SheetContent, SheetFooter, SheetHeader, SheetSection, SheetTitle, Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from 'ui' import { Admonition } from 'ui-patterns/Admonition' import { useOrgSettingsPanel } from '../useOrgSettingsPanel' import { ButtonTooltip } from '@/components/ui/ButtonTooltip' import { useOrgProjectsInfiniteQuery } from '@/data/projects/org-projects-infinite-query' import { useOrgSubscriptionQuery } from '@/data/subscriptions/org-subscription-query' import { useOrgSubscriptionUpdateMutation } from '@/data/subscriptions/org-subscription-update-mutation' import { FGA_PERMISSIONS, useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2' import { BASE_PATH, DOCS_URL, PRICING_TIER_PRODUCT_IDS } from '@/lib/constants' import { PROJECT_STATUS } from '@/lib/constants/infrastructure' const BILLING_METRIC_CATEGORIES: (keyof typeof pricing)[] = [ 'database', 'auth', 'storage', 'realtime', 'edge_functions', ] 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`, }, ] export const SpendCapSidePanel = () => { const { slug } = useParams() const { resolvedTheme } = useTheme() const [showUsageCosts, setShowUsageCosts] = useState(false) const [selectedOption, setSelectedOption] = useState<'on' | 'off'>() const { can: canUpdateSpendCap } = useAsyncCheckPermissionsV2( FGA_PERMISSIONS.ORGANIZATION.BILLING_WRITE ) const { panel, setPanel } = useOrgSettingsPanel() const visible = panel === 'costControl' const onClose = () => setPanel(null) const { data } = useOrgProjectsInfiniteQuery({ slug }) const projects = useMemo(() => data?.pages.flatMap((page) => page.projects) || [], [data?.pages]) const hasReplicas = useMemo( () => projects.some( (it) => it.status !== PROJECT_STATUS.INACTIVE && it.databases.some((db) => db.type === 'READ_REPLICA') ), [projects] ) const { data: subscription, isPending: isLoading } = useOrgSubscriptionQuery({ orgSlug: slug }) const { mutate: updateOrgSubscription, isPending: isUpdating } = useOrgSubscriptionUpdateMutation( { onSuccess: () => { toast.success(`Successfully ${isTurningOnCap ? 'enabled' : 'disabled'} spend cap`) onClose() }, onError: (error) => { toast.error(`Failed to toggle spend cap: ${error.message}`) }, } ) const isFreePlan = subscription?.plan?.id === 'free' const isSpendCapOn = !subscription?.usage_billing_enabled const isTurningOnCap = !isSpendCapOn && selectedOption === 'on' const hasChanges = selectedOption !== (isSpendCapOn ? 'on' : 'off') const isBlockedByReplicas = isTurningOnCap && hasReplicas const disabled = isFreePlan || isLoading || !hasChanges || isUpdating || !canUpdateSpendCap || isBlockedByReplicas const confirmTooltipText = !canUpdateSpendCap ? 'You do not have permission to update spend cap' : isBlockedByReplicas ? 'Remove your read replicas before enabling the spend cap' : undefined const onConfirm = async () => { if (!slug) return console.error('Org slug is required') const tier = ( selectedOption === 'on' ? PRICING_TIER_PRODUCT_IDS.PRO : PRICING_TIER_PRODUCT_IDS.PAYG ) as 'tier_pro' | 'tier_payg' updateOrgSubscription({ slug, tier }) } useEffect(() => { if (visible && subscription !== undefined) { setSelectedOption(isSpendCapOn ? 'on' : 'off') } }, [visible, isLoading, subscription, isSpendCapOn]) return ( onClose()}> Spend cap

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

How is each resource charged after exceeding the included quota?

Item Rate {BILLING_METRIC_CATEGORIES.map((categoryId) => { const category = pricing[categoryId] const usageItems = category.features.filter((it) => it.usage_based) return ( {category.title} {usageItems.map((item) => ( {item.title} {Array.isArray(item.plans['pro']) ? item.plans['pro']?.join(', ') : item.plans['pro']} ))} ) })}
{isFreePlan && ( setPanel('subscriptionPlan')}>View available plans } /> )}
{SPEND_CAP_OPTIONS.map((option) => { const isSelected = selectedOption === option.value return ( ) })}
{isBlockedByReplicas ? ( ) : selectedOption === 'on' ? ( ) : ( )} {hasChanges && !disabled && ( <>

{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 beyond the included quota.'}

Toggling spend cap triggers an invoice and there might be prorated charges for any usage beyond the Pro Plans quota during this billing cycle.

)}
Confirm
) }