The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Address comments from part 1
Joshen Lim53182aef4a36
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/PaymentMethods/ChangePaymentMethodModal.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/PaymentMethods/ChangePaymentMethodModal.tsxindex 8abb06b9d87..9036b975955 100644--- a/studio/components/interfaces/Organization/BillingSettingsV2/PaymentMethods/ChangePaymentMethodModal.tsx+++ b/studio/components/interfaces/Organization/BillingSettingsV2/PaymentMethods/ChangePaymentMethodModal.tsx@@ -41,7 +41,7 @@ const ChangePaymentMethodModal = ({})ui.setNotification({category: 'success',- message: `Successfully removed payment method ending with ${selectedPaymentMethod.card.last4}`,+ message: `Successfully changed payment method to the card ending with ${selectedPaymentMethod.card.last4}`,})onClose()} catch (error: any) {diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/DowngradeModal.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/DowngradeModal.tsxnew file mode 100644index 00000000000..360512305a0--- /dev/null+++ b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/DowngradeModal.tsx@@ -0,0 +1,75 @@+import { PricingInformation } from 'shared-data'+import { Alert, IconAlertOctagon, IconMinusCircle, IconPauseCircle, Modal } from 'ui'++export interface DowngradeModalProps {+ visible: boolean+ selectedTier?: PricingInformation+ onClose: () => void+ onConfirm: () => void+}++const DowngradeModal = ({ visible, selectedTier, onClose, onConfirm }: DowngradeModalProps) => {+ return (+ <Modal+ size="medium"+ alignFooter="right"+ visible={visible}+ onCancel={onClose}+ onConfirm={onConfirm}+ header={`Confirm to downgrade to ${selectedTier?.name} plan`}+ >+ <Modal.Content>+ <div className="py-6">+ <Alert+ withIcon+ variant="warning"+ title="Downgrading to the free plan will lead to reductions in your project's capacity"+ >+ <p>+ If you're already past the limits of the free plan, your project could become+ unresponsive or enter read only mode.+ </p>+ </Alert>++ {/* [Joshen] Improvement area: Show which projects might be most affected by the downgrade? */}+ {/* [Joshen] Improvement area: Show which projects addons will be removed */}++ <ul className="mt-4 space-y-5 text-sm">+ <li className="flex gap-3">+ <IconMinusCircle />+ <span>Add ons from all projects under this organization will be removed.</span>+ </li>++ <li className="flex gap-3">+ <div>+ <IconPauseCircle />+ </div>+ <span>+ Your projects will be paused if it exceeds the free plan quotas, or after a week of+ inactivity+ </span>+ </li>++ <li className="flex gap-3">+ <IconAlertOctagon w={14} className="flex-shrink-0" />+ <div>+ <strong>Before you downgrading to the {selectedTier?.name} plan, consider:</strong>+ <ul className="space-y-2 mt-2">+ <li className="list-disc ml-4">+ Your projects no longer require their respective add ons.+ </li>+ <li className="list-disc ml-4">+ Your projects are currently consuming resources that are well within the{' '}+ {selectedTier?.name} plan's quota.+ </li>+ </ul>+ </div>+ </li>+ </ul>+ </div>+ </Modal.Content>+ </Modal>+ )+}++export default DowngradeModaldiff --git a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/ExitSurveyModal.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/ExitSurveyModal.tsxindex ff7dd6b1552..9f906dbc5d3 100644--- a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/ExitSurveyModal.tsx+++ b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/ExitSurveyModal.tsx@@ -14,6 +14,7 @@ import { API_URL, PROJECT_STATUS } from 'lib/constants'import { Button, Input, Modal } from 'ui'import { CANCELLATION_REASONS } from '../BillingSettings.constants'import ProjectUpdateDisabledTooltip from '../../BillingSettings/ProjectUpdateDisabledTooltip'+import { useOrgSubscriptionUpdateMutation } from 'data/subscriptions/org-subscription-update-mutation'export interface ExitSurveyModalProps {visible: boolean@@ -24,23 +25,25 @@ export interface ExitSurveyModalProps {// [Joshen TODO] Remove all contexts of projects - i'm presuming we still want the exit surveyconst ExitSurveyModal = ({ visible, onClose }: ExitSurveyModalProps) => {- const queryClient = useQueryClient()const { ui } = useStore()- const { ref: projectRef } = useParams()- const captchaRef = useRef<HCaptcha>(null)const router = useRouter()+ const { slug } = useParams()+ const queryClient = useQueryClient()+ const captchaRef = useRef<HCaptcha>(null)const [isSubmitting, setIsSubmitting] = useState(false)const [message, setMessage] = useState('')const [captchaToken, setCaptchaToken] = useState<string | null>(null)const [selectedReasons, dispatchSelectedReasons] = useReducer(reducer, [])- const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')- const { data: addons } = useProjectAddonsQuery({ projectRef })- const { mutateAsync: updateSubscriptionTier } = useProjectSubscriptionUpdateMutation()+ const subscriptionUpdateDisabled = useFlag('disableProjectCreationAndUpdate')+ const { mutateAsync: updateOrgSubscription } = useOrgSubscriptionUpdateMutation()- const subscriptionAddons = addons?.selected_addons ?? []- const hasComputeInstance = subscriptionAddons.find((addon) => addon.type === 'compute_instance')+ // [Joshen] We'll need to fix this - but need a way to check which projects will be affected+ // const { data: addons } = useProjectAddonsQuery({ projectRef })+ // const subscriptionAddons = addons?.selected_addons ?? []+ // const hasComputeInstance = subscriptionAddons.find((addon) => addon.type === 'compute_instance')+ const hasComputeInstance = falsefunction reducer(state: any, action: any) {if (includes(state, action.target.value)) {@@ -70,7 +73,7 @@ const ExitSurveyModal = ({ visible, onClose }: ExitSurveyModalProps) => {if (!token) {const captchaResponse = await captchaRef.current?.execute({ async: true })token = captchaResponse?.response ?? null- await downgradeProject()+ await downgradeOrganization()}} catch (error: any) {ui.setNotification({@@ -82,25 +85,26 @@ const ExitSurveyModal = ({ visible, onClose }: ExitSurveyModalProps) => {}}- const downgradeProject = async (values?: any) => {+ const downgradeOrganization = async (values?: any) => {// Update the subscription first, followed by posting the exit survey if successful// If compute instance is present within the existing subscription, then a restart will be triggered- if (!projectRef) return console.error('Project ref is required')+ if (!slug) return console.error('Slug is required')try {- await updateSubscriptionTier({ projectRef, tier: 'tier_free' })+ await updateOrgSubscription({ slug, tier: 'tier_free' })resetCaptcha()} catch (error: any) {return ui.setNotification({error,category: 'error',- message: `Failed to cancel subscription: ${error.message}`,+ message: `Failed to downgrade subscription: ${error.message}`,})}try {+ // [Joshen TODO] Update to accept org slug once endpoint is updatedconst feedbackRes = await post(`${API_URL}/feedback/downgrade`, {- projectRef,+ projectRef: '',reasons: selectedReasons.reduce((a, b) => `${a}- ${b}\n`, ''),additionalFeedback: message,exitAction: 'downgrade',@@ -117,13 +121,14 @@ const ExitSurveyModal = ({ visible, onClose }: ExitSurveyModalProps) => {category: 'success',duration: hasComputeInstance ? 8000 : 4000,message: hasComputeInstance- ? 'Your project has been downgraded and is currently restarting to update its instance size'- : 'Successfully downgraded project to the free plan',+ ? 'Your organization has been downgraded and your projects are currently restarting to update their compute instances'+ : 'Successfully downgraded organization to the free plan',})- if (hasComputeInstance) {- setProjectStatus(queryClient, projectRef, PROJECT_STATUS.RESTORING)- router.push(`/project/${projectRef}`)- }+ // [Joshen TODO] Think about how to handle this+ // if (hasComputeInstance) {+ // setProjectStatus(queryClient, projectRef, PROJECT_STATUS.RESTORING)+ // router.push(`/project/${projectRef}`)+ // }onClose(true)window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })}@@ -215,11 +220,11 @@ const ExitSurveyModal = ({ visible, onClose }: ExitSurveyModalProps) => {<Button type="default" onClick={() => onClose()}>Cancel</Button>- <ProjectUpdateDisabledTooltip projectUpdateDisabled={projectUpdateDisabled}>+ <ProjectUpdateDisabledTooltip projectUpdateDisabled={subscriptionUpdateDisabled}><Buttontype="danger"loading={isSubmitting}- disabled={projectUpdateDisabled || isSubmitting}+ disabled={subscriptionUpdateDisabled || isSubmitting}onClick={onSubmit}>Confirm downgradediff --git a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsxindex f80f4f14b65..beedca987b5 100644--- a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx+++ b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx@@ -14,11 +14,13 @@ import Telemetry from 'lib/telemetry'import { useRouter } from 'next/router'import { plans as subscriptionsPlans } from 'shared-data/plans'import { useOrgSettingsPageStateSnapshot } from 'state/organization-settings'-import { Alert, Button, IconCheck, IconExternalLink, Modal, SidePanel } from 'ui'+import { Button, IconCheck, IconExternalLink, Modal, SidePanel } from 'ui'+import DowngradeModal from './DowngradeModal'import EnterpriseCard from './EnterpriseCard'import ExitSurveyModal from './ExitSurveyModal'import MembersExceedLimitModal from './MembersExceedLimitModal'import PaymentMethodSelection from './PaymentMethodSelection'+import { useFreeProjectLimitCheckQuery } from 'data/organizations/free-project-limit-check-query'// [Joshen TODO] Need to remove all contexts of "projects"@@ -45,14 +47,11 @@ const PlanUpdateSidePanel = () => {const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: slug })const { data: plans, isLoading: isLoadingPlans } = useOrgPlansQuery({ orgSlug: slug })+ const { data: membersExceededLimit } = useFreeProjectLimitCheckQuery({ slug })const { mutateAsync: updateOrgSubscription } = useOrgSubscriptionUpdateMutation()- // const { data: membersExceededLimit } = useFreeProjectLimitCheckQuery({ slug }) // [Joshen] Still need?const availablePlans = plans ?? []- const subscriptionAddons: any[] = [] // [Joshen] Still need?-- // const hasMembersExceedingFreeTierLimit = (membersExceededLimit || []).length > 0- const hasMembersExceedingFreeTierLimit = false // [Joshen] Still need?+ const hasMembersExceedingFreeTierLimit = (membersExceededLimit || []).length > 0const selectedTierMeta = subscriptionsPlans.find((tier) => tier.id === selectedTier)const selectedPlanMeta = availablePlans.find((plan) => plan.id === selectedTier?.split('tier_')[1]@@ -278,49 +277,12 @@ const PlanUpdateSidePanel = () => {</SidePanel.Content></SidePanel>- <Modal- size="medium"- alignFooter="right"+ <DowngradeModalvisible={selectedTier === 'tier_free'}- onCancel={() => setSelectedTier(undefined)}+ selectedTier={selectedTierMeta}+ onClose={() => setSelectedTier(undefined)}onConfirm={onConfirmDowngrade}- header={`Confirm to downgrade to ${selectedTierMeta?.name}`}- >- {/* [JOSHEN] We could make this better by only showing a danger warning if the project is already above the free plan limits */}- <Modal.Content>- <div className="py-6">- <Alert- withIcon- variant="warning"- title="Downgrading to the free plan will lead to reductions in your project's capacity"- >- <p>- If you're already past the limits of the free plan, your project could become- unresponsive or enter read only mode.- </p>- {subscriptionAddons.length > 0 && (- <>- <p className="mt-2">- Your project's add ons will also be removed, which includes:- </p>- <ul className="list-disc pl-6">- {subscriptionAddons.map((addon) => (- <li key={addon.type} className="mt-0.5">- {addon.variant.name}{' '}- {addon.type === 'compute_instance'- ? 'compute instance'- : addon.type === 'pitr'- ? 'PITR'- : ''}- </li>- ))}- </ul>- </>- )}- </Alert>- </div>- </Modal.Content>- </Modal>+ /><Modalloading={isSubmitting}@@ -341,8 +303,7 @@ const PlanUpdateSidePanel = () => {previous usage.</p><p className="text-sm text-scale-1000">- You will also be able to change your project's add-ons after upgrading your project's- plan.+ You will also be able to change your project's add-ons after upgrading your plan.</p><div className="!mt-6"><PaymentMethodSelectiondiff --git a/studio/components/interfaces/Organization/Usage/Activity.tsx b/studio/components/interfaces/Organization/Usage/Activity.tsxindex f801ef519c6..c859ccfbec4 100644--- a/studio/components/interfaces/Organization/Usage/Activity.tsx+++ b/studio/components/interfaces/Organization/Usage/Activity.tsx@@ -1,6 +1,6 @@import { DataPoint } from 'data/analytics/constants'import { ProjectSubscriptionResponse } from 'data/subscriptions/project-subscription-v2-query'-import UsageSection from './UsageSection'+import UsageSection from './UsageSection/UsageSection'import { PricingMetric, useOrgDailyStatsQuery } from 'data/analytics/org-daily-stats-query'export interface ActivityProps {diff --git a/studio/components/interfaces/Organization/Usage/Bandwidth.tsx b/studio/components/interfaces/Organization/Usage/Bandwidth.tsxindex 066df624791..633fddf58cf 100644--- a/studio/components/interfaces/Organization/Usage/Bandwidth.tsx+++ b/studio/components/interfaces/Organization/Usage/Bandwidth.tsx@@ -1,7 +1,7 @@import { DataPoint } from 'data/analytics/constants'import { PricingMetric, useOrgDailyStatsQuery } from 'data/analytics/org-daily-stats-query'import { ProjectSubscriptionResponse } from 'data/subscriptions/project-subscription-v2-query'-import UsageSection from './UsageSection'+import UsageSection from './UsageSection/UsageSection'const GB = 1073741824diff --git a/studio/components/interfaces/Organization/Usage/SizeAndCounts.tsx b/studio/components/interfaces/Organization/Usage/SizeAndCounts.tsxindex 10aaa9c60b9..728a8c34079 100644--- a/studio/components/interfaces/Organization/Usage/SizeAndCounts.tsx+++ b/studio/components/interfaces/Organization/Usage/SizeAndCounts.tsx@@ -1,7 +1,7 @@import { DataPoint } from 'data/analytics/constants'import { PricingMetric, useOrgDailyStatsQuery } from 'data/analytics/org-daily-stats-query'import { OrgSubscription } from 'data/subscriptions/org-subscription-query'-import UsageSection from './UsageSection'+import UsageSection from './UsageSection/UsageSection'export interface SizeAndCountsProps {orgSlug: stringdiff --git a/studio/components/interfaces/Organization/Usage/UsageChartTooltips.tsx b/studio/components/interfaces/Organization/Usage/UsageChartTooltips.tsxindex 0c69d6a91ba..aa2b3697f80 100644--- a/studio/components/interfaces/Organization/Usage/UsageChartTooltips.tsx+++ b/studio/components/interfaces/Organization/Usage/UsageChartTooltips.tsx@@ -39,40 +39,57 @@ export interface MultiAttributeTooltipContentProps {tooltipFormatter?: (value: any) => any}+const AttributeContent = ({+ attribute,+ attributeMeta,+ sumValue,+ tooltipFormatter,+}: {+ attribute: Attribute+ attributeMeta?: Payload<ValueType, string | number>+ sumValue: number+ tooltipFormatter?: (value: any) => any+}) => {+ const attrValue = Number(attributeMeta?.value ?? 0)+ const percentageContribution = ((attrValue / sumValue) * 100).toFixed(1)++ return (+ <div key={attribute.name} className="flex items-center justify-between">+ <div className="flex items-center space-x-2 w-[200px]">+ <div className={clsx('w-3 h-3 rounded-full border', COLOR_MAP[attribute.color].marker)} />+ <p className="text-xs prose">+ {attribute.name} ({percentageContribution}%):{' '}+ </p>+ </div>+ <p className="text-xs tabular-nums">+ {tooltipFormatter !== undefined ? tooltipFormatter(attrValue) : attrValue}+ </p>+ </div>+ )+}+export const MultiAttributeTooltipContent = ({attributes,values,isAfterToday,tooltipFormatter,}: MultiAttributeTooltipContentProps) => {+ const sumValue = values.reduce((a, b) => a + Number(b.value), 0)return (<>{isAfterToday ? (<p className="text-scale-1000 text-lg">No data yet</p>) : (<div className="space-y-1 pb-1">- {attributes.map((attr) => {- const attrMeta = values.find((x) => x.dataKey === attr.key)- const attrValue = Number(attrMeta?.value ?? 0)- const sumValue = values.reduce((a, b) => a + Number(b.value), 0)- const percentageContribution = ((attrValue / sumValue) * 100).toFixed(1)-- return (- <div key={attr.name} className="flex items-center justify-between">- <div className="flex items-center space-x-2 w-[200px]">- <div- className={clsx('w-3 h-3 rounded-full border', COLOR_MAP[attr.color].marker)}- />- <p className="text-xs prose">- {attr.name} ({percentageContribution}%):{' '}- </p>- </div>- <p className="text-xs tabular-nums">- {tooltipFormatter !== undefined ? tooltipFormatter(attrValue) : attrValue}- </p>- </div>- )- })}+ {attributes.map((attr) => (+ <AttributeContent+ key={attr.name}+ attribute={attr}+ attributeMeta={values.find((x) => x.dataKey === attr.key)}+ sumValue={sumValue}+ tooltipFormatter={tooltipFormatter}+ />+ ))}</div>)}</>diff --git a/studio/components/interfaces/Organization/Usage/UsageSection.tsx b/studio/components/interfaces/Organization/Usage/UsageSection.tsxdeleted file mode 100644index 817ca264286..00000000000--- a/studio/components/interfaces/Organization/Usage/UsageSection.tsx+++ /dev/null@@ -1,306 +0,0 @@-import * as Tooltip from '@radix-ui/react-tooltip'-import clsx from 'clsx'-import Link from 'next/link'--import { USAGE_APPROACHING_THRESHOLD } from 'components/interfaces/BillingV2/Billing.constants'-import { ScaffoldContainer, ScaffoldDivider } from 'components/layouts/Scaffold'-import Panel from 'components/ui/Panel'-import ShimmeringLoader from 'components/ui/ShimmeringLoader'-import SparkBar from 'components/ui/SparkBar'-import { DataPoint } from 'data/analytics/constants'-import { OrgSubscription } from 'data/subscriptions/org-subscription-query'-import { useOrgUsageQuery } from 'data/usage/org-usage-query'-import { Button, IconAlertTriangle, IconBarChart2 } from 'ui'-import SectionContent from './SectionContent'-import SectionHeader from './SectionHeader'-import { CategoryMetaKey, USAGE_CATEGORIES } from './Usage.constants'-import {- ChartTooltipValueFormatter,- ChartYFormatterCompactNumber,- getUpgradeUrl,-} from './Usage.utils'-import UsageBarChart from './UsageBarChart'-import AlertError from 'components/ui/AlertError'--interface UsageSectionProps {- orgSlug: string- categoryKey: CategoryMetaKey- subscription: OrgSubscription | undefined- chartMeta: {- [key: string]: { data: DataPoint[]; margin: number; isLoading: boolean; hasNoData: boolean }- }- currentBillingCycleSelected: boolean-}--const UsageSection = ({- orgSlug,- categoryKey,- chartMeta,- subscription,- currentBillingCycleSelected,-}: UsageSectionProps) => {- const {- data: usage,- error: usageError,- isLoading: isLoadingUsage,- isError: isErrorUsage,- isSuccess: isSuccessUsage,- } = useOrgUsageQuery({ orgSlug })-- const categoryMeta = USAGE_CATEGORIES.find((category) => category.key === categoryKey)- if (!categoryMeta) return null-- const usageBasedBilling = subscription?.usage_billing_enabled- const exceededLimitStyle = !usageBasedBilling ? 'text-red-900' : 'text-amber-900'- const upgradeUrl = getUpgradeUrl(orgSlug ?? '', subscription)-- return (- <>- <ScaffoldContainer>- <SectionHeader title={categoryMeta.name} description={categoryMeta.description} />- </ScaffoldContainer>-- <ScaffoldDivider />-- {categoryMeta.attributes.map((attribute) => {- const usageMeta = usage?.usages.find((x) => x.metric === attribute.key)- const usageRatio = (usageMeta?.usage ?? 0) / (usageMeta?.pricing_free_units ?? 0)- const usageExcess = (usageMeta?.usage ?? 0) - (usageMeta?.pricing_free_units ?? 0)-- const chartData = chartMeta[attribute.key]?.data ?? []- const notAllValuesZero =- attribute.attributes- ?.map((attr) => {- return chartData.some((dataPoint) => Number(dataPoint[attr.key]) !== 0)- })- .some((x) => !!x) ?? false- const showUsageWarning =- currentBillingCycleSelected &&- usageBasedBilling === false &&- usageRatio >= USAGE_APPROACHING_THRESHOLD-- return (- <div id={attribute.anchor} key={attribute.key}>- <SectionContent section={attribute}>- {isLoadingUsage && (- <div className="space-y-2">- <ShimmeringLoader />- <ShimmeringLoader className="w-3/4" />- <ShimmeringLoader className="w-1/2" />- </div>- )}-- {isErrorUsage && <AlertError subject="Unable to retrieve usage" error={usageError} />}-- {isSuccessUsage && (- <>- {usageMeta?.available_in_plan ? (- <>- <div className="space-y-2">- <div className="flex items-center justify-between">- <div className="flex items-center space-x-4">- <p className="text-sm">{attribute.name} usage</p>- {showUsageWarning && (- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- {usageRatio >= 1 ? (- <div className="flex items-center space-x-2 min-w-[115px] cursor-help">- <IconAlertTriangle- size={14}- strokeWidth={2}- className={exceededLimitStyle}- />- <p className={`text-sm ${exceededLimitStyle}`}>- Exceeded limit- </p>- </div>- ) : (- usageRatio >= USAGE_APPROACHING_THRESHOLD && (- <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>- )- )}- </Tooltip.Trigger>- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-scale-100 py-1 px-2 leading-none shadow',- 'border border-scale-200',- ].join(' ')}- >- <p className="text-xs text-scale-1200">- Exceeding your plans included usage will lead to- restrictions to your project.- </p>- <p className="text-xs text-scale-1200">- Upgrade to a usage-based plan or disable the spend cap to- avoid restrictions.- </p>- </div>- </Tooltip.Content>- </Tooltip.Portal>- </Tooltip.Root>- )}- </div>-- {showUsageWarning && (- <Link href={upgradeUrl}>- <a className="pb-1">- <Button type="default" size="tiny">- {subscription?.plan?.id === 'free'- ? 'Upgrade plan'- : 'Change spend cap'}- </Button>- </a>- </Link>- )}- </div>-- {currentBillingCycleSelected && !usageMeta.unlimited && (- <SparkBar- type="horizontal"- barClass={clsx(- usageRatio >= 1- ? usageBasedBilling- ? 'bg-scale-1100'- : 'bg-red-900'- : usageBasedBilling === false &&- usageRatio >= USAGE_APPROACHING_THRESHOLD- ? 'bg-amber-900'- : 'bg-scale-1100'- )}- bgClass="bg-gray-300 dark:bg-gray-600"- value={usageMeta?.usage ?? 0}- max={usageMeta?.pricing_free_units || 1}- />- )}-- <div>- <div className="flex items-center justify-between border-b py-1">- <p className="text-xs text-scale-1000">- Included in {subscription?.plan?.name.toLowerCase()} plan- </p>- {usageMeta.unlimited ? (- <p className="text-xs">Unlimited</p>- ) : (- <p className="text-xs">- {attribute.unit === 'bytes'- ? `${usageMeta.pricing_free_units ?? 0} GB`- : (usageMeta.pricing_free_units ?? 0).toLocaleString()}- </p>- )}- </div>- {currentBillingCycleSelected && (- <div className="flex items-center justify-between py-1">- <p className="text-xs text-scale-1000">- {attribute.chartPrefix || 'Used '} in period- </p>- <p className="text-xs">- {attribute.unit === 'bytes'- ? `${usageMeta?.usage ?? 0} GB`- : (usageMeta?.usage ?? 0).toLocaleString()}- </p>- </div>- )}- {currentBillingCycleSelected &&- (usageMeta?.pricing_free_units ?? 0) > 0 && (- <div className="flex items-center justify-between border-t py-1">- <p className="text-xs text-scale-1000">Overage in period</p>- <p className="text-xs">- {(usageMeta?.pricing_free_units ?? 0) === -1 || usageExcess < 0- ? `0${attribute.unit === 'bytes' ? ' GB' : ''}`- : attribute.unit === 'bytes'- ? `${usageExcess} GB`- : usageExcess.toLocaleString()}- </p>- </div>- )}- </div>- </div>-- {attribute.additionalInfo?.(usage)}-- <div className="space-y-1">- <p className="text-sm">- {attribute.chartPrefix || ''} {attribute.name} per day- </p>- {attribute.chartDescription.split('\n').map((paragraph, idx) => (- <p key={`para-${idx}`} className="text-sm text-scale-1000">- {paragraph}- </p>- ))}- </div>- {chartMeta[attribute.key].isLoading ? (- <div className="space-y-2">- <ShimmeringLoader />- <ShimmeringLoader className="w-3/4" />- <ShimmeringLoader className="w-1/2" />- </div>- ) : chartData.length > 0 && notAllValuesZero ? (- <UsageBarChart- name={`${attribute.chartPrefix || ''}${attribute.name}`}- unit={attribute.unit}- attributes={attribute.attributes}- data={chartData}- yLeftMargin={chartMeta[attribute.key].margin}- yFormatter={(value) =>- ChartYFormatterCompactNumber(value, attribute.unit)- }- tooltipFormatter={(value) =>- ChartTooltipValueFormatter(value, attribute.unit)- }- />- ) : (- <Panel>- <Panel.Content>- <div className="flex flex-col items-center justify-center">- <IconBarChart2 className="text-scale-1100 mb-2" />- <p className="text-sm">No data in period</p>- <p className="text-sm text-scale-1000">- May take up to 24 hours to show- </p>- </div>- </Panel.Content>- </Panel>- )}- </>- ) : (- <Panel>- <Panel.Content>- <div className="flex w-full items-center flex-col justify-center space-y-2 md:flex-row md:justify-between">- <div className="space-y-1">- <p className="text-sm">Not included in plan</p>- <div>- <p className="text-sm text-scale-1100">- You need to be on a higher plan in order to use this feature.- </p>- </div>- </div>- <Link href={`/org/${orgSlug}/billing?panel=subscriptionPlan`}>- <a>- <Button type="primary">Upgrade plan</Button>- </a>- </Link>- </div>- </Panel.Content>- </Panel>- )}- </>- )}- </SectionContent>- </div>- )- })}- </>- )-}--export default UsageSectiondiff --git a/studio/components/interfaces/Organization/Usage/UsageSection/AttributeUsage.tsx b/studio/components/interfaces/Organization/Usage/UsageSection/AttributeUsage.tsxnew file mode 100644index 00000000000..e7ed1a006e3--- /dev/null+++ b/studio/components/interfaces/Organization/Usage/UsageSection/AttributeUsage.tsx@@ -0,0 +1,289 @@+import * as Tooltip from '@radix-ui/react-tooltip'+import clsx from 'clsx'+import Link from 'next/link'++import AlertError from 'components/ui/AlertError'+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 { USAGE_APPROACHING_THRESHOLD } from 'lib/constants'+import { ResponseError } from 'types'+import { Button, IconAlertTriangle, IconBarChart2 } from 'ui'+import SectionContent from '../SectionContent'+import { CategoryAttribute } from '../Usage.constants'+import {+ ChartTooltipValueFormatter,+ ChartYFormatterCompactNumber,+ getUpgradeUrl,+} from '../Usage.utils'+import UsageBarChart from '../UsageBarChart'+import { ChartMeta } from './UsageSection'+import { useMemo } from 'react'++export interface AttributeUsageProps {+ slug: string+ attribute: CategoryAttribute+ usage?: OrgUsageResponse+ usageMeta?: UsageMetric+ chartMeta: ChartMeta+ subscription?: OrgSubscription++ error: ResponseError | null+ isLoading: boolean+ isError: boolean+ isSuccess: boolean++ currentBillingCycleSelected: boolean+}++const AttributeUsage = ({+ slug,+ attribute,+ usage,+ usageMeta,+ chartMeta,+ subscription,++ error,+ isLoading,+ isError,+ isSuccess,+ currentBillingCycleSelected,+}: AttributeUsageProps) => {+ const upgradeUrl = getUpgradeUrl(slug ?? '', subscription)+ const usageRatio = (usageMeta?.usage ?? 0) / (usageMeta?.pricing_free_units ?? 0)+ const usageExcess = (usageMeta?.usage ?? 0) - (usageMeta?.pricing_free_units ?? 0)+ const usageBasedBilling = subscription?.usage_billing_enabled+ const exceededLimitStyle = !usageBasedBilling ? 'text-red-900' : 'text-amber-900'++ const chartData = useMemo(() => chartMeta[attribute.key]?.data ?? [], [attribute.key, chartMeta])++ const showUsageWarning =+ currentBillingCycleSelected &&+ usageBasedBilling === false &&+ usageRatio >= USAGE_APPROACHING_THRESHOLD++ const notAllValuesZero = useMemo(() => {+ return (+ attribute.attributes+ ?.map((attr) => {+ return chartData.some((dataPoint) => Number(dataPoint[attr.key]) !== 0)+ })+ .some((x) => !!x) ?? false+ )+ }, [attribute.attributes, chartData])++ return (+ <div id={attribute.anchor}>+ <SectionContent section={attribute}>+ {isLoading && (+ <div className="space-y-2">+ <ShimmeringLoader />+ <ShimmeringLoader className="w-3/4" />+ <ShimmeringLoader className="w-1/2" />+ </div>+ )}++ {isError && <AlertError subject="Unable to retrieve usage" error={error} />}++ {isSuccess && (+ <>+ {usageMeta?.available_in_plan ? (+ <>+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <div className="flex items-center space-x-4">+ <p className="text-sm">{attribute.name} usage</p>+ {showUsageWarning && (+ <Tooltip.Root delayDuration={0}>+ <Tooltip.Trigger asChild>+ {usageRatio >= 1 ? (+ <div className="flex items-center space-x-2 min-w-[115px] cursor-help">+ <IconAlertTriangle+ size={14}+ strokeWidth={2}+ className={exceededLimitStyle}+ />+ <p className={`text-sm ${exceededLimitStyle}`}>Exceeded limit</p>+ </div>+ ) : (+ usageRatio >= USAGE_APPROACHING_THRESHOLD && (+ <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>+ )+ )}+ </Tooltip.Trigger>+ <Tooltip.Portal>+ <Tooltip.Content side="bottom">+ <Tooltip.Arrow className="radix-tooltip-arrow" />+ <div+ className={[+ 'rounded bg-scale-100 py-1 px-2 leading-none shadow',+ 'border border-scale-200',+ ].join(' ')}+ >+ <p className="text-xs text-scale-1200">+ Exceeding your plans included usage will lead to restrictions to+ your project.+ </p>+ <p className="text-xs text-scale-1200">+ Upgrade to a usage-based plan or disable the spend cap to avoid+ restrictions.+ </p>+ </div>+ </Tooltip.Content>+ </Tooltip.Portal>+ </Tooltip.Root>+ )}+ </div>++ {showUsageWarning && (+ <Link href={upgradeUrl}>+ <a className="pb-1">+ <Button type="default" size="tiny">+ {subscription?.plan?.id === 'free'+ ? 'Upgrade plan'+ : 'Change spend cap'}+ </Button>+ </a>+ </Link>+ )}+ </div>++ {currentBillingCycleSelected && !usageMeta.unlimited && (+ <SparkBar+ type="horizontal"+ barClass={clsx(+ usageRatio >= 1+ ? usageBasedBilling+ ? 'bg-scale-1100'+ : 'bg-red-900'+ : usageBasedBilling === false && usageRatio >= USAGE_APPROACHING_THRESHOLD+ ? 'bg-amber-900'+ : 'bg-scale-1100'+ )}+ bgClass="bg-gray-300 dark:bg-gray-600"+ value={usageMeta?.usage ?? 0}+ max={usageMeta?.pricing_free_units || 1}+ />+ )}++ <div>+ <div className="flex items-center justify-between border-b py-1">+ <p className="text-xs text-scale-1000">+ Included in {subscription?.plan?.name.toLowerCase()} plan+ </p>+ {usageMeta.unlimited ? (+ <p className="text-xs">Unlimited</p>+ ) : (+ <p className="text-xs">+ {attribute.unit === 'bytes'+ ? `${usageMeta.pricing_free_units ?? 0} GB`+ : (usageMeta.pricing_free_units ?? 0).toLocaleString()}+ </p>+ )}+ </div>+ {currentBillingCycleSelected && (+ <div className="flex items-center justify-between py-1">+ <p className="text-xs text-scale-1000">+ {attribute.chartPrefix || 'Used '} in period+ </p>+ <p className="text-xs">+ {attribute.unit === 'bytes'+ ? `${usageMeta?.usage ?? 0} GB`+ : (usageMeta?.usage ?? 0).toLocaleString()}+ </p>+ </div>+ )}+ {currentBillingCycleSelected && (usageMeta?.pricing_free_units ?? 0) > 0 && (+ <div className="flex items-center justify-between border-t py-1">+ <p className="text-xs text-scale-1000">Overage in period</p>+ <p className="text-xs">+ {(usageMeta?.pricing_free_units ?? 0) === -1 || usageExcess < 0+ ? `0${attribute.unit === 'bytes' ? ' GB' : ''}`+ : attribute.unit === 'bytes'+ ? `${usageExcess} GB`+ : usageExcess.toLocaleString()}+ </p>+ </div>+ )}+ </div>+ </div>++ {attribute.additionalInfo?.(usage)}++ <div className="space-y-1">+ <p className="text-sm">+ {attribute.chartPrefix || ''} {attribute.name} per day+ </p>+ {attribute.chartDescription.split('\n').map((paragraph, idx) => (+ <p key={`para-${idx}`} className="text-sm text-scale-1000">+ {paragraph}+ </p>+ ))}+ </div>+ {chartMeta[attribute.key].isLoading ? (+ <div className="space-y-2">+ <ShimmeringLoader />+ <ShimmeringLoader className="w-3/4" />+ <ShimmeringLoader className="w-1/2" />+ </div>+ ) : chartData.length > 0 && notAllValuesZero ? (+ <UsageBarChart+ name={`${attribute.chartPrefix || ''}${attribute.name}`}+ unit={attribute.unit}+ attributes={attribute.attributes}+ data={chartData}+ yLeftMargin={chartMeta[attribute.key].margin}+ yFormatter={(value) => ChartYFormatterCompactNumber(value, attribute.unit)}+ tooltipFormatter={(value) => ChartTooltipValueFormatter(value, attribute.unit)}+ />+ ) : (+ <Panel>+ <Panel.Content>+ <div className="flex flex-col items-center justify-center">+ <IconBarChart2 className="text-scale-1100 mb-2" />+ <p className="text-sm">No data in period</p>+ <p className="text-sm text-scale-1000">May take up to 24 hours to show</p>+ </div>+ </Panel.Content>+ </Panel>+ )}+ </>+ ) : (+ <Panel>+ <Panel.Content>+ <div className="flex w-full items-center flex-col justify-center space-y-2 md:flex-row md:justify-between">+ <div className="space-y-1">+ <p className="text-sm">Not included in plan</p>+ <div>+ <p className="text-sm text-scale-1100">+ You need to be on a higher plan in order to use this feature.+ </p>+ </div>+ </div>+ <Link href={upgradeUrl}>+ <a>+ <Button type="primary">Upgrade plan</Button>+ </a>+ </Link>+ </div>+ </Panel.Content>+ </Panel>+ )}+ </>+ )}+ </SectionContent>+ </div>+ )+}++export default AttributeUsagediff --git a/studio/components/interfaces/Organization/Usage/UsageSection/UsageSection.tsx b/studio/components/interfaces/Organization/Usage/UsageSection/UsageSection.tsxnew file mode 100644index 00000000000..6542fd17292--- /dev/null+++ b/studio/components/interfaces/Organization/Usage/UsageSection/UsageSection.tsx@@ -0,0 +1,67 @@+import { ScaffoldContainer, ScaffoldDivider } from 'components/layouts/Scaffold'+import { DataPoint } from 'data/analytics/constants'+import { OrgSubscription } from 'data/subscriptions/org-subscription-query'+import { useOrgUsageQuery } from 'data/usage/org-usage-query'+import SectionHeader from '../SectionHeader'+import { CategoryMetaKey, USAGE_CATEGORIES } from '../Usage.constants'+import AttributeUsage from './AttributeUsage'++export interface ChartMeta {+ [key: string]: { data: DataPoint[]; margin: number; isLoading: boolean; hasNoData: boolean }+}++export interface UsageSectionProps {+ orgSlug: string+ categoryKey: CategoryMetaKey+ subscription?: OrgSubscription+ chartMeta: ChartMeta+ currentBillingCycleSelected: boolean+}++const UsageSection = ({+ orgSlug,+ categoryKey,+ chartMeta,+ subscription,+ currentBillingCycleSelected,+}: UsageSectionProps) => {+ const {+ data: usage,+ error: usageError,+ isLoading: isLoadingUsage,+ isError: isErrorUsage,+ isSuccess: isSuccessUsage,+ } = useOrgUsageQuery({ orgSlug })++ const categoryMeta = USAGE_CATEGORIES.find((category) => category.key === categoryKey)+ if (!categoryMeta) return null++ return (+ <>+ <ScaffoldContainer>+ <SectionHeader title={categoryMeta.name} description={categoryMeta.description} />+ </ScaffoldContainer>++ <ScaffoldDivider />++ {categoryMeta.attributes.map((attribute) => (+ <AttributeUsage+ key={attribute.name}+ slug={orgSlug}+ attribute={attribute}+ usage={usage}+ usageMeta={usage?.usages.find((x) => x.metric === attribute.key)}+ chartMeta={chartMeta}+ subscription={subscription}+ error={usageError}+ isLoading={isLoadingUsage}+ isError={isErrorUsage}+ isSuccess={isSuccessUsage}+ currentBillingCycleSelected={currentBillingCycleSelected}+ />+ ))}+ </>+ )+}++export default UsageSectiondiff --git a/studio/data/subscriptions/org-subscription-update-mutation.ts b/studio/data/subscriptions/org-subscription-update-mutation.tsindex 83c5e1bd74d..d2592bbcc8f 100644--- a/studio/data/subscriptions/org-subscription-update-mutation.ts+++ b/studio/data/subscriptions/org-subscription-update-mutation.ts@@ -51,7 +51,7 @@ export const useOrgSubscriptionUpdateMutation = ({(vars) => updateOrgSubscription(vars),{async onSuccess(data, variables, context) {- const { slug, paymentMethod } = variables+ const { slug } = variablesawait queryClient.invalidateQueries(subscriptionKeys.orgSubscription(slug))await onSuccess?.(data, variables, context)},