Skip to content

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

Add plan upgrade side panel

Joshen Limdf188a118977
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/BillingSettings.constants.ts b/studio/components/interfaces/Organization/BillingSettingsV2/BillingSettings.constants.ts
new file mode 100644
index 00000000000..3e16e7b2138
--- /dev/null
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/BillingSettings.constants.ts
@@ -0,0 +1,16 @@
+export const CANCELLATION_REASONS = [
+ 'Pricing',
+ "My project isn't getting traction",
+ 'Poor customer service',
+ 'Missing feature',
+ "I didn't see the value",
+ "Supabase didn't meet my needs",
+ 'Dashboard is too complicated',
+ 'Postgres is too complicated',
+ 'Problem not solved',
+ 'Bug issues',
+ 'I decided to use something else',
+ 'My work has finished/discontinued',
+ 'I’m migrating to/starting a new project',
+ 'None of the above',
+]
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/PaymentMethods/PaymentMethods.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/PaymentMethods/PaymentMethods.tsx
index c49c416c316..18ef727fa21 100644
--- a/studio/components/interfaces/Organization/BillingSettingsV2/PaymentMethods/PaymentMethods.tsx
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/PaymentMethods/PaymentMethods.tsx
@@ -35,7 +35,6 @@ const PaymentMethods = () => {
} = useOrganizationPaymentMethodsQuery({ slug })
const sortedPaymentMethods =
paymentMethods?.sort((a, b) => (a.id === subscription?.payment_method_id ? -1 : 0)) ?? []
- console.log({ sortedPaymentMethods })
const canReadPaymentMethods = useCheckPermissions(
PermissionAction.BILLING_READ,
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/EnterpriseCard.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/EnterpriseCard.tsx
new file mode 100644
index 00000000000..af9608f0dd0
--- /dev/null
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/EnterpriseCard.tsx
@@ -0,0 +1,62 @@
+import clsx from 'clsx'
+import { Button, IconCheck } from 'ui'
+import { PricingInformation } from 'shared-data'
+
+export interface EnterpriseCardProps {
+ plan: PricingInformation
+ isCurrentPlan: boolean
+}
+
+const EnterpriseCard = ({ plan, isCurrentPlan }: EnterpriseCardProps) => {
+ return (
+ <div
+ key={plan.id}
+ className={clsx(
+ 'grid grid-cols-1 md:grid-cols-3 border rounded-md bg-scale-200',
+ 'py-4 col-span-12 justify-between gap-x-8'
+ )}
+ >
+ <div className="flex flex-col justify-center px-4">
+ <div className="flex items-center space-x-2">
+ <p className={clsx('text-brand-900 text-sm uppercase')}>{plan.name}</p>
+ {isCurrentPlan ? (
+ <div className="text-xs bg-scale-500 text-scale-1000 rounded px-2 py-0.5">
+ Current plan
+ </div>
+ ) : plan.nameBadge ? (
+ <div className="text-xs bg-brand-400 text-brand-900 rounded px-2 py-0.5">
+ {plan.nameBadge}
+ </div>
+ ) : null}
+ </div>
+
+ <p className="text-sm mt-2 mb-4">{plan.description}</p>
+
+ <a href={plan.href} className="hidden md:block" target="_blank">
+ <Button block type="default" size="tiny">
+ {plan.cta}
+ </Button>
+ </a>
+ </div>
+
+ <div className="flex flex-col justify-center col-span-2 px-4 md:px-0">
+ <ul role="list" className="text-xs text-scale-1000 md:grid md:grid-cols-2 md:gap-x-10">
+ {plan.features.map((feature) => (
+ <li key={feature} className="flex items-center py-2 first:mt-0">
+ <IconCheck className="text-brand-900 h-4 w-4" aria-hidden="true" strokeWidth={3} />
+ <span className="dark:text-scale-1200 mb-0 ml-3 ">{feature}</span>
+ </li>
+ ))}
+ </ul>
+
+ <a href={plan.href} className="visible md:hidden mt-8" target="_blank">
+ <Button block type="default" size="tiny">
+ {plan.cta}
+ </Button>
+ </a>
+ </div>
+ </div>
+ )
+}
+
+export default EnterpriseCard
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/ExitSurveyModal.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/ExitSurveyModal.tsx
new file mode 100644
index 00000000000..ff7dd6b1552
--- /dev/null
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/ExitSurveyModal.tsx
@@ -0,0 +1,235 @@
+import HCaptcha from '@hcaptcha/react-hcaptcha'
+import { useQueryClient } from '@tanstack/react-query'
+import { includes, without } from 'lodash'
+import { useRouter } from 'next/router'
+import { useReducer, useRef, useState } from 'react'
+
+import { useParams } from 'common'
+import { setProjectStatus } from 'data/projects/projects-query'
+import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'
+import { useProjectSubscriptionUpdateMutation } from 'data/subscriptions/project-subscription-update-mutation'
+import { useFlag, useStore } from 'hooks'
+import { post } from 'lib/common/fetch'
+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'
+
+export interface ExitSurveyModalProps {
+ visible: boolean
+ onClose: (success?: boolean) => void
+}
+
+// [Joshen] For context - Exit survey is only when going to free plan from a paid plan
+// [Joshen TODO] Remove all contexts of projects - i'm presuming we still want the exit survey
+
+const ExitSurveyModal = ({ visible, onClose }: ExitSurveyModalProps) => {
+ const queryClient = useQueryClient()
+ const { ui } = useStore()
+ const { ref: projectRef } = useParams()
+ const captchaRef = useRef<HCaptcha>(null)
+ const router = useRouter()
+
+ 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 subscriptionAddons = addons?.selected_addons ?? []
+ const hasComputeInstance = subscriptionAddons.find((addon) => addon.type === 'compute_instance')
+
+ function reducer(state: any, action: any) {
+ if (includes(state, action.target.value)) {
+ return without(state, action.target.value)
+ } else {
+ return [...state, action.target.value]
+ }
+ }
+
+ const resetCaptcha = () => {
+ setCaptchaToken(null)
+ captchaRef.current?.resetCaptcha()
+ }
+
+ const onSubmit = async () => {
+ if (selectedReasons.length === 0) {
+ return ui.setNotification({
+ category: 'error',
+ message: 'Please select at least one reason for canceling your subscription',
+ })
+ }
+
+ setIsSubmitting(true)
+ let token = captchaToken
+
+ try {
+ if (!token) {
+ const captchaResponse = await captchaRef.current?.execute({ async: true })
+ token = captchaResponse?.response ?? null
+ await downgradeProject()
+ }
+ } catch (error: any) {
+ ui.setNotification({
+ category: 'error',
+ message: `Failed to downgrade project: ${error.message}`,
+ })
+ } finally {
+ setIsSubmitting(false)
+ }
+ }
+
+ const downgradeProject = 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')
+
+ try {
+ await updateSubscriptionTier({ projectRef, tier: 'tier_free' })
+ resetCaptcha()
+ } catch (error: any) {
+ return ui.setNotification({
+ error,
+ category: 'error',
+ message: `Failed to cancel subscription: ${error.message}`,
+ })
+ }
+
+ try {
+ const feedbackRes = await post(`${API_URL}/feedback/downgrade`, {
+ projectRef,
+ reasons: selectedReasons.reduce((a, b) => `${a}- ${b}\n`, ''),
+ additionalFeedback: message,
+ exitAction: 'downgrade',
+ })
+ if (feedbackRes.error) throw feedbackRes.error
+ } catch (error: any) {
+ return ui.setNotification({
+ error,
+ category: 'info',
+ message: `Failed to submit exit survey: ${error.message}`,
+ })
+ } finally {
+ ui.setNotification({
+ 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',
+ })
+ if (hasComputeInstance) {
+ setProjectStatus(queryClient, projectRef, PROJECT_STATUS.RESTORING)
+ router.push(`/project/${projectRef}`)
+ }
+ onClose(true)
+ window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
+ }
+ }
+
+ return (
+ <>
+ <div className="self-center">
+ <HCaptcha
+ ref={captchaRef}
+ sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY!}
+ size="invisible"
+ onVerify={(token) => {
+ setCaptchaToken(token)
+ if (document !== undefined) document.body.classList.remove('!pointer-events-auto')
+ }}
+ onExpire={() => setCaptchaToken(null)}
+ onOpen={() => {
+ // [Joshen] This is to ensure that hCaptcha popup remains clickable
+ if (document !== undefined) document.body.classList.add('!pointer-events-auto')
+ }}
+ onClose={() => {
+ if (document !== undefined) document.body.classList.remove('!pointer-events-auto')
+ }}
+ />
+ </div>
+
+ <Modal
+ hideFooter
+ size="xlarge"
+ visible={visible}
+ onCancel={onClose}
+ header="We're sad that you're leaving"
+ >
+ <Modal.Content>
+ <div className="py-6">
+ <p className="text-sm text-scale-1100">
+ We always strive to improve Supabase as much as we can. Please let us know the reasons
+ you are canceling your subscription so that we can improve in the future.
+ </p>
+ <div className="space-y-8 mt-6">
+ <div className="flex flex-wrap gap-2" data-toggle="buttons">
+ {CANCELLATION_REASONS.map((option) => {
+ const active = selectedReasons.find((x) => x === option)
+ return (
+ <label
+ key={option}
+ className={`
+ flex cursor-pointer items-center space-x-2 rounded-md py-1
+ pl-2 pr-3 text-center text-sm
+ shadow-sm transition-all duration-100
+ ${
+ active
+ ? ` bg-scale-1200 text-scale-100 opacity-100 hover:bg-opacity-75`
+ : ` bg-scale-700 text-scale-1200 opacity-25 hover:opacity-50`
+ }
+ `}
+ >
+ <input
+ type="checkbox"
+ name="options"
+ value={option}
+ className="hidden"
+ onClick={dispatchSelectedReasons}
+ />
+ <div>{option}</div>
+ </label>
+ )
+ })}
+ </div>
+ <div className="text-area-text-sm">
+ <Input.TextArea
+ id="message"
+ name="message"
+ value={message}
+ onChange={(event: any) => setMessage(event.target.value)}
+ label="Anything else that we can improve on?"
+ />
+ </div>
+ </div>
+ </div>
+ </Modal.Content>
+
+ <div className="flex items-center justify-between border-t px-4 py-4">
+ <p className="text-xs text-scale-900">
+ The unused amount for the remaining of your billing cycle will be refunded as credits
+ </p>
+ <div className="flex items-center space-x-2">
+ <Button type="default" onClick={() => onClose()}>
+ Cancel
+ </Button>
+ <ProjectUpdateDisabledTooltip projectUpdateDisabled={projectUpdateDisabled}>
+ <Button
+ type="danger"
+ loading={isSubmitting}
+ disabled={projectUpdateDisabled || isSubmitting}
+ onClick={onSubmit}
+ >
+ Confirm downgrade
+ </Button>
+ </ProjectUpdateDisabledTooltip>
+ </div>
+ </div>
+ </Modal>
+ </>
+ )
+}
+
+export default ExitSurveyModal
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/MembersExceedLimitModal.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/MembersExceedLimitModal.tsx
new file mode 100644
index 00000000000..7f64080e394
--- /dev/null
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/MembersExceedLimitModal.tsx
@@ -0,0 +1,59 @@
+import { useFreeProjectLimitCheckQuery } from 'data/organizations/free-project-limit-check-query'
+import { useSelectedOrganization } from 'hooks'
+import { Button, Modal } from 'ui'
+
+// [Joshen TODO] Check if we still need this?
+
+export interface MembersExceedLimitModalProps {
+ visible: boolean
+ onClose: () => void
+}
+
+const MembersExceedLimitModal = ({ visible, onClose }: MembersExceedLimitModalProps) => {
+ const selectedOrganization = useSelectedOrganization()
+ const slug = selectedOrganization?.slug
+ const { data: membersExceededLimit } = useFreeProjectLimitCheckQuery({ slug })
+
+ return (
+ <Modal
+ hideFooter
+ visible={visible}
+ size="medium"
+ header="Your organization has members who have exceeded their free project limits"
+ onCancel={onClose}
+ >
+ <div className="py-4 space-y-4">
+ <Modal.Content>
+ <div className="space-y-2">
+ <p className="text-sm text-scale-1100">
+ The following members have reached their maximum limits for the number of active free
+ plan projects within organizations where they are an administrator or owner:
+ </p>
+ <ul className="pl-5 text-sm list-disc text-scale-1100">
+ {(membersExceededLimit || []).map((member, idx: number) => (
+ <li key={`member-${idx}`}>
+ {member.username || member.primary_email} (Limit: {member.free_project_limit} free
+ projects)
+ </li>
+ ))}
+ </ul>
+ <p className="text-sm text-scale-1100">
+ These members will need to either delete, pause, or upgrade one or more of these
+ projects before you're able to downgrade this project.
+ </p>
+ </div>
+ </Modal.Content>
+ <Modal.Separator />
+ <Modal.Content>
+ <div className="flex items-center gap-2">
+ <Button htmlType="button" type="default" onClick={onClose} block>
+ Understood
+ </Button>
+ </div>
+ </Modal.Content>
+ </div>
+ </Modal>
+ )
+}
+
+export default MembersExceedLimitModal
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx
new file mode 100644
index 00000000000..54c8044cb7e
--- /dev/null
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx
@@ -0,0 +1,380 @@
+import * as Tooltip from '@radix-ui/react-tooltip'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import clsx from 'clsx'
+import Link from 'next/link'
+import { useEffect, useState } from 'react'
+
+import ShimmeringLoader from 'components/ui/ShimmeringLoader'
+import { useOrgPlansQuery } from 'data/subscriptions/org-plans-query'
+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
+import { useOrgSubscriptionUpdateMutation } from 'data/subscriptions/org-subscription-update-mutation'
+import { useCheckPermissions, useSelectedOrganization, useStore } from 'hooks'
+import { PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
+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 EnterpriseCard from './EnterpriseCard'
+import ExitSurveyModal from './ExitSurveyModal'
+import MembersExceedLimitModal from './MembersExceedLimitModal'
+import PaymentMethodSelection from './PaymentMethodSelection'
+
+// [Joshen TODO] Need to remove all contexts of "projects"
+
+const PlanUpdateSidePanel = () => {
+ const { ui } = useStore()
+ const router = useRouter()
+ const selectedOrganization = useSelectedOrganization()
+ const slug = selectedOrganization?.slug
+
+ const [isSubmitting, setIsSubmitting] = useState(false)
+ const [showExitSurvey, setShowExitSurvey] = useState(false)
+ const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string>()
+ const [showDowngradeError, setShowDowngradeError] = useState(false)
+ const [selectedTier, setSelectedTier] = useState<'tier_free' | 'tier_pro' | 'tier_team'>()
+
+ const canUpdateSubscription = useCheckPermissions(
+ PermissionAction.BILLING_WRITE,
+ 'stripe.subscriptions'
+ )
+
+ const snap = useOrgSettingsPageStateSnapshot()
+ const visible = snap.panelKey === 'subscriptionPlan'
+ const onClose = () => snap.setPanelKey(undefined)
+
+ const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: slug })
+ const { data: plans, isLoading: isLoadingPlans } = useOrgPlansQuery({ orgSlug: 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 selectedTierMeta = subscriptionsPlans.find((tier) => tier.id === selectedTier)
+ const selectedPlanMeta = availablePlans.find(
+ (plan) => plan.id === selectedTier?.split('tier_')[1]
+ )
+
+ useEffect(() => {
+ if (visible) {
+ setSelectedTier(undefined)
+ Telemetry.sendActivity(
+ {
+ activity: 'Side Panel Viewed',
+ source: 'Dashboard',
+ data: {
+ title: 'Change Subscription Plan',
+ section: 'Subscription plan',
+ },
+ },
+ router
+ )
+ }
+ }, [visible])
+
+ const onConfirmDowngrade = () => {
+ setSelectedTier(undefined)
+ if (hasMembersExceedingFreeTierLimit) {
+ setShowDowngradeError(true)
+ } else {
+ setShowExitSurvey(true)
+ }
+ }
+
+ const onUpdateSubscription = async () => {
+ if (!slug) return console.error('org slug is required')
+ if (!selectedTier) return console.error('Selected plan is required')
+ if (!selectedPaymentMethod) {
+ return ui.setNotification({ category: 'error', message: 'Please select a payment method' })
+ }
+
+ try {
+ setIsSubmitting(true)
+ await updateOrgSubscription({
+ slug,
+ tier: selectedTier,
+ paymentMethod: selectedPaymentMethod,
+ })
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully updated subscription to ${selectedTierMeta?.name}!`,
+ })
+ setSelectedTier(undefined)
+ onClose()
+ window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
+ } catch (error: any) {
+ ui.setNotification({
+ error,
+ category: 'error',
+ message: `Unable to update subscription: ${error.message}`,
+ })
+ } finally {
+ setIsSubmitting(false)
+ }
+ }
+
+ return (
+ <>
+ <SidePanel
+ hideFooter
+ size="xxlarge"
+ visible={visible}
+ onCancel={() => onClose()}
+ header={
+ <div className="flex items-center justify-between">
+ <h4>Change subscription plan</h4>
+ <Link href="https://supabase.com/pricing">
+ <a target="_blank" rel="noreferrer">
+ <Button type="default" icon={<IconExternalLink strokeWidth={1.5} />}>
+ Pricing
+ </Button>
+ </a>
+ </Link>
+ </div>
+ }
+ >
+ <SidePanel.Content>
+ <div className="py-6 grid grid-cols-12 gap-3">
+ {subscriptionsPlans.map((plan) => {
+ const planMeta = availablePlans.find((p) => p.id === plan.id.split('tier_')[1])
+ const tierMeta = subscriptionsPlans.find((it) => it.id === plan.id)
+ const price = planMeta?.price ?? 0
+ const isDowngradeOption = planMeta?.change_type === 'downgrade'
+ const isCurrentPlan = planMeta?.id === subscription?.plan?.id
+
+ if (plan.id === 'tier_enterprise') {
+ return <EnterpriseCard key={plan.id} plan={plan} isCurrentPlan={isCurrentPlan} />
+ }
+
+ return (
+ <div
+ key={plan.id}
+ className={clsx(
+ 'border rounded-md px-4 py-4 flex flex-col items-start justify-between',
+ plan.id === 'tier_enterprise' ? 'col-span-12' : 'col-span-12 md:col-span-4',
+ plan.id === 'tier_enterprise' ? 'bg-scale-200' : 'bg-scale-300'
+ )}
+ >
+ <div className="w-full">
+ <div className="flex items-center space-x-2">
+ <p className={clsx('text-brand-900 text-sm uppercase')}>{plan.name}</p>
+ {isCurrentPlan ? (
+ <div className="text-xs bg-scale-500 text-scale-1000 rounded px-2 py-0.5">
+ Current plan
+ </div>
+ ) : plan.nameBadge ? (
+ <div className="text-xs bg-brand-400 text-brand-900 rounded px-2 py-0.5">
+ {plan.nameBadge}
+ </div>
+ ) : (
+ <></>
+ )}
+ </div>
+ <div className="mt-4 flex items-center space-x-1">
+ {(price ?? 0) > 0 && <p className="text-scale-1000 text-sm">From</p>}
+ {isLoadingPlans ? (
+ <div className="h-[28px] flex items-center justify-center">
+ <ShimmeringLoader className="w-[30px] h-[24px]" />
+ </div>
+ ) : (
+ <p className="text-scale-1200 text-lg">${price}</p>
+ )}
+ <p className="text-scale-1000 text-sm">{tierMeta?.costUnit}</p>
+ </div>
+ <div className={clsx('flex mt-1 mb-4', !tierMeta?.warning && 'opacity-0')}>
+ <div className="bg-scale-200 text-brand-1100 border shadow-sm rounded-md bg-opacity-30 py-0.5 px-2 text-xs">
+ {tierMeta?.warning}
+ </div>
+ </div>
+ {isCurrentPlan ? (
+ <Button block disabled type="default">
+ Current plan
+ </Button>
+ ) : plan.id !== PRICING_TIER_PRODUCT_IDS.TEAM ? (
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger asChild>
+ <div>
+ <Button
+ block
+ disabled={
+ // no self-serve downgrades from team plan right now
+ (plan.id !== PRICING_TIER_PRODUCT_IDS.TEAM &&
+ ['team', 'enterprise'].includes(subscription?.plan?.id || '')) ||
+ !canUpdateSubscription
+ }
+ type={isDowngradeOption ? 'default' : 'primary'}
+ onClick={() => {
+ setSelectedTier(plan.id as any)
+ Telemetry.sendActivity(
+ {
+ activity: 'Popup Viewed',
+ source: 'Dashboard',
+ data: {
+ title: isDowngradeOption
+ ? 'Downgrade'
+ : 'Upgrade' + ' to ' + plan.name,
+ section: 'Subscription plan',
+ },
+ },
+ router
+ )
+ }}
+ >
+ {isDowngradeOption ? 'Downgrade' : 'Upgrade'} to {plan.name}
+ </Button>
+ </div>
+ </Tooltip.Trigger>
+ {!canUpdateSubscription ? (
+ <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(' ')}
+ >
+ <span className="text-xs text-scale-1200">
+ You do not have permission to change the subscription plan.
+ </span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ ) : null}
+ </Tooltip.Root>
+ ) : (
+ <Link href={plan.href} passHref className="hidden md:block">
+ <a target="_blank">
+ <Button block type="primary">
+ Contact Us
+ </Button>
+ </a>
+ </Link>
+ )}
+
+ <div className="border-t my-6" />
+
+ <ul role="list">
+ {plan.features.map((feature) => (
+ <li key={feature} className="flex py-2">
+ <div className="w-[12px]">
+ <IconCheck
+ className="h-3 w-3 text-brand-900 translate-y-[2.5px]"
+ aria-hidden="true"
+ strokeWidth={3}
+ />
+ </div>
+ <p className="ml-3 text-xs text-scale-1100">{feature}</p>
+ </li>
+ ))}
+ </ul>
+ </div>
+
+ {plan.footer && (
+ <div className="border-t pt-4 mt-4">
+ <p className="text-scale-1000 text-xs">{plan.footer}</p>
+ </div>
+ )}
+ </div>
+ )
+ })}
+ </div>
+ </SidePanel.Content>
+ </SidePanel>
+
+ <Modal
+ size="medium"
+ alignFooter="right"
+ visible={selectedTier === 'tier_free'}
+ onCancel={() => 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>
+
+ <Modal
+ loading={isSubmitting}
+ alignFooter="right"
+ className="!w-[450px]"
+ visible={selectedTier !== undefined && selectedTier !== 'tier_free'}
+ onCancel={() => setSelectedTier(undefined)}
+ onConfirm={onUpdateSubscription}
+ overlayClassName="pointer-events-none"
+ header={`Confirm to upgrade to ${selectedTierMeta?.name}`}
+ >
+ <Modal.Content>
+ <div className="py-6 space-y-2">
+ <p className="text-sm">
+ Upon clicking confirm, the amount of ${selectedPlanMeta?.price ?? 'Unknown'} will be
+ added to your monthly invoice and your credit card will be charged immediately.
+ Changing the plan resets your billing cycle and may result in a prorated charge for
+ 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.
+ </p>
+ <div className="!mt-6">
+ <PaymentMethodSelection
+ selectedPaymentMethod={selectedPaymentMethod}
+ onSelectPaymentMethod={setSelectedPaymentMethod}
+ />
+ </div>
+ </div>
+ </Modal.Content>
+ </Modal>
+
+ <MembersExceedLimitModal
+ visible={showDowngradeError}
+ onClose={() => setShowDowngradeError(false)}
+ />
+
+ <ExitSurveyModal
+ visible={showExitSurvey}
+ onClose={(success?: boolean) => {
+ setShowExitSurvey(false)
+ if (success) onClose()
+ }}
+ />
+ </>
+ )
+}
+
+export default PlanUpdateSidePanel
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/README.md b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/README.md
deleted file mode 100644
index 0ed42b4e4bc..00000000000
--- a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/README.md
+++ /dev/null
@@ -1,7 +0,0 @@
-### Disclaimer
-
-[Joshen] Just FYI a lot of these are lifted from `components/interfaces/BillingV2/Subscription` since they are
-more or less the same, in fact after migrating to Org billing completely, we will probably deprecate the BillingV2 folder
-at the project scope.
-
-- Probably also need to update support form to allow selecting an organization, not just project
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/Subscription.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/Subscription.tsx
index 032612c1f29..dc5eed476fd 100644
--- a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/Subscription.tsx
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/Subscription.tsx
@@ -10,9 +10,12 @@ import { useFlag } from 'hooks'
import { Alert, Button, IconExternalLink } from 'ui'
import ProjectUpdateDisabledTooltip from '../../BillingSettings/ProjectUpdateDisabledTooltip'
import SubscriptionPaymentMethod from './SubscriptionPaymentMethod'
+import { useOrgSettingsPageStateSnapshot } from 'state/organization-settings'
+import PlanUpdateSidePanel from './PlanUpdateSidePanel'
const Subscription = () => {
const { slug } = useParams()
+ const snap = useOrgSettingsPageStateSnapshot()
const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')
const {
@@ -34,139 +37,142 @@ const Subscription = () => {
!projectUpdateDisabled && !['team', 'enterprise'].includes(currentPlan?.id ?? '')
return (
- <FormSection
- id="plan"
- header={
- <FormSectionLabel>
- <div className="sticky space-y-6 top-16">
- <p className="text-base">Subscription Plan</p>
- <div className="space-y-2">
- <p className="text-sm text-scale-1100">More information</p>
- <div>
- <Link href="https://supabase.com/pricing">
- <a target="_blank" rel="noreferrer">
- <div className="flex items-center space-x-2 opacity-50 hover:opacity-100 transition">
- <p className="text-sm">Pricing</p>
- <IconExternalLink size={16} strokeWidth={1.5} />
- </div>
- </a>
- </Link>
+ <>
+ <FormSection
+ id="plan"
+ header={
+ <FormSectionLabel>
+ <div className="sticky space-y-6 top-16">
+ <p className="text-base">Subscription Plan</p>
+ <div className="space-y-2">
+ <p className="text-sm text-scale-1100">More information</p>
+ <div>
+ <Link href="https://supabase.com/pricing">
+ <a target="_blank" rel="noreferrer">
+ <div className="flex items-center space-x-2 opacity-50 hover:opacity-100 transition">
+ <p className="text-sm">Pricing</p>
+ <IconExternalLink size={16} strokeWidth={1.5} />
+ </div>
+ </a>
+ </Link>
+ </div>
</div>
</div>
- </div>
- </FormSectionLabel>
- }
- >
- <FormSectionContent loading={isLoading}>
- {isError && <AlertError subject="Failed to retrieve subscription" error={error} />}
+ </FormSectionLabel>
+ }
+ >
+ <FormSectionContent loading={isLoading}>
+ {isError && <AlertError subject="Failed to retrieve subscription" error={error} />}
- {isSuccess && (
- <div className="space-y-6">
- <div>
- <p className="text-sm">This organization is currently on the plan:</p>
- <p className="text-2xl text-brand-900 uppercase">{currentPlan?.name ?? 'Unknown'}</p>
- </div>
+ {isSuccess && (
+ <div className="space-y-6">
+ <div>
+ <p className="text-sm">This organization is currently on the plan:</p>
+ <p className="text-2xl text-brand-900 uppercase">
+ {currentPlan?.name ?? 'Unknown'}
+ </p>
+ </div>
- <div>
- <ProjectUpdateDisabledTooltip projectUpdateDisabled={projectUpdateDisabled}>
- <Button
- type="default"
- disabled={!canChangeTier}
- onClick={() => {}} // [JOSHEN TODO: Implement]
- >
- Change subscription plan
- </Button>
- </ProjectUpdateDisabledTooltip>
- {!canChangeTier &&
- (projectUpdateDisabled ? (
- <Alert withIcon variant="info" title={`Unable to update plan from ${planName}`}>
- We have temporarily disabled project and subscription changes - our engineers
- are working on a fix.
- </Alert>
- ) : (
- <Alert
- withIcon
- variant="info"
- title={`Unable to update plan from ${planName}`}
- actions={[
- <div key="contact-support">
- <Link
- href={`/support/new?category=sales&subject=Change%20plan%20away%20from%20${planName}`}
- >
- <a>
- <Button type="default">Contact support</Button>
- </a>
- </Link>
- </div>,
- ]}
+ <div>
+ <ProjectUpdateDisabledTooltip projectUpdateDisabled={projectUpdateDisabled}>
+ <Button
+ type="default"
+ disabled={!canChangeTier}
+ onClick={() => snap.setPanelKey('subscriptionPlan')}
>
- Please contact us if you'd like to change your plan.
- </Alert>
- ))}
- </div>
-
- {!subscription?.usage_billing_enabled && (
- <Alert
- withIcon
- variant="info"
- title="This organization is limited by the included usage"
- actions={
- currentPlan?.id === 'free' ? (
- // [Joshen TODO]: Implement
- <Button type="default" onClick={() => {}}>
- Upgrade Plan
- </Button>
+ Change subscription plan
+ </Button>
+ </ProjectUpdateDisabledTooltip>
+ {!canChangeTier &&
+ (projectUpdateDisabled ? (
+ <Alert withIcon variant="info" title={`Unable to update plan from ${planName}`}>
+ We have temporarily disabled project and subscription changes - our engineers
+ are working on a fix.
+ </Alert>
) : (
- // [Joshen TODO]: Implement
- <Button type="default" onClick={() => {}}>
- Adjust Spend Cap
- </Button>
- )
- }
- >
- <p className="text-sm text-scale-1000">
- When this organization exceeds its{' '}
- <Link href="#breakdown">
- <a className="text-sm text-green-900 transition hover:text-green-1000">
- included usage quotas
- </a>
- </Link>
- , its projects may become unresponsive.{' '}
- {currentPlan?.id === 'free' ? (
- <p className="pr-4">
- If you wish to exceed the included usage, you should upgrade to a paid plan.
- </p>
- ) : (
- <p className="pr-4">
- You currently have Spend Cap enabled - when you exceed your plan's limit, you
- will experience restrictions. To scale seamlessly and pay for over-usage, you
- can adjust your Cost Control settings.
- </p>
- )}
- </p>
- </Alert>
- )}
+ <Alert
+ withIcon
+ variant="info"
+ title={`Unable to update plan from ${planName}`}
+ actions={[
+ <div key="contact-support">
+ <Link
+ href={`/support/new?category=sales&subject=Change%20plan%20away%20from%20${planName}`}
+ >
+ <a>
+ <Button type="default">Contact support</Button>
+ </a>
+ </Link>
+ </div>,
+ ]}
+ >
+ Please contact us if you'd like to change your plan.
+ </Alert>
+ ))}
+ </div>
+
+ {!subscription?.usage_billing_enabled && (
+ <Alert
+ withIcon
+ variant="info"
+ title="This organization is limited by the included usage"
+ actions={
+ currentPlan?.id === 'free' ? (
+ <Button type="default" onClick={() => snap.setPanelKey('subscriptionPlan')}>
+ Upgrade Plan
+ </Button>
+ ) : (
+ <Button type="default" onClick={() => snap.setPanelKey('costControl')}>
+ Adjust Spend Cap
+ </Button>
+ )
+ }
+ >
+ <p className="text-sm text-scale-1000 mr-2">
+ When this organization exceeds its{' '}
+ <Link href="#breakdown">
+ <a className="text-sm text-green-900 transition hover:text-green-1000">
+ included usage quotas
+ </a>
+ </Link>
+ , its projects may become unresponsive.{' '}
+ {currentPlan?.id === 'free' ? (
+ <p className="pr-4 mt-1">
+ If you wish to exceed the included usage, you should upgrade to a paid plan.
+ </p>
+ ) : (
+ <p className="pr-4 mt-1">
+ You currently have Spend Cap enabled - when you exceed your plan's limit,
+ you will experience restrictions. To scale seamlessly and pay for
+ over-usage, you can adjust your Cost Control settings.
+ </p>
+ )}
+ </p>
+ </Alert>
+ )}
- <SparkBar
- type="horizontal"
- value={daysWithinCycle - daysToCycleEnd}
- max={daysWithinCycle}
- barClass="bg-scale-1200"
- labelBottom={`Current billing cycle (${billingCycleStart.format(
- 'MMM DD'
- )} - ${billingCycleEnd.format('MMM DD')})`}
- bgClass="bg-gray-300 dark:bg-gray-600"
- labelBottomClass="!text-scale-1000 pb-1"
- labelTop={`${daysToCycleEnd} Days left`}
- />
+ <SparkBar
+ type="horizontal"
+ value={daysWithinCycle - daysToCycleEnd}
+ max={daysWithinCycle}
+ barClass="bg-scale-1200"
+ labelBottom={`Current billing cycle (${billingCycleStart.format(
+ 'MMM DD'
+ )} - ${billingCycleEnd.format('MMM DD')})`}
+ bgClass="bg-gray-300 dark:bg-gray-600"
+ labelBottomClass="!text-scale-1000 pb-1"
+ labelTop={`${daysToCycleEnd} Days left`}
+ />
- {subscription !== undefined && (
- <SubscriptionPaymentMethod subscription={subscription} />
- )}
- </div>
- )}
- </FormSectionContent>
- </FormSection>
+ {subscription !== undefined && (
+ <SubscriptionPaymentMethod subscription={subscription} />
+ )}
+ </div>
+ )}
+ </FormSectionContent>
+ </FormSection>
+ <PlanUpdateSidePanel />
+ </>
)
}
diff --git a/studio/data/subscriptions/keys.ts b/studio/data/subscriptions/keys.ts
index 16b4998d66d..94be5ab2794 100644
--- a/studio/data/subscriptions/keys.ts
+++ b/studio/data/subscriptions/keys.ts
@@ -1,10 +1,12 @@
// [Joshen TODO] To remove subscription V2 after v2 is launched and stable to deprecate old billing ui + endpoints
export const subscriptionKeys = {
- subscriptionV2: (projectRef: string | undefined) =>
- ['projects', projectRef, 'subscriptionV2'] as const,
orgSubscription: (orgSlug: string | undefined) =>
['organizations', orgSlug, 'subscription'] as const,
+ orgPlans: (orgSlug: string | undefined) => ['organizations', orgSlug, 'plans'] as const,
+
+ subscriptionV2: (projectRef: string | undefined) =>
+ ['projects', projectRef, 'subscriptionV2'] as const,
addons: (projectRef: string | undefined) => ['projects', projectRef, 'addons'] as const,
plans: (projectRef: string | undefined) => ['projects', projectRef, 'plans'] as const,
preview: (projectRef: string | undefined) =>
diff --git a/studio/data/subscriptions/org-plans-query.ts b/studio/data/subscriptions/org-plans-query.ts
new file mode 100644
index 00000000000..acfcae395f2
--- /dev/null
+++ b/studio/data/subscriptions/org-plans-query.ts
@@ -0,0 +1,55 @@
+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 { subscriptionKeys } from './keys'
+
+export type OrgPlansVariables = {
+ orgSlug?: string
+}
+
+export type OrgPlansResponse = {
+ id: 'free' | 'pro' | 'team' | 'enterprise'
+ name: string
+ price: number
+ is_current: boolean
+ change_type: 'downgrade' | 'upgrade' | 'none'
+ effective_at: string
+}[]
+
+export async function getOrgPlans({ orgSlug }: OrgPlansVariables, signal?: AbortSignal) {
+ if (!orgSlug) throw new Error('orgSlug is required')
+
+ const response = await get(`${API_URL}/organizations/${orgSlug}/billing/plans`, { signal })
+ if (response.error) throw response.error
+
+ return response.plans as OrgPlansResponse
+}
+
+export type OrgPlansData = Awaited<ReturnType<typeof getOrgPlans>>
+export type OrgPlansError = unknown
+
+export const useOrgPlansQuery = <TData = OrgPlansData>(
+ { orgSlug }: OrgPlansVariables,
+ { enabled = true, ...options }: UseQueryOptions<OrgPlansData, OrgPlansError, TData> = {}
+) =>
+ useQuery<OrgPlansData, OrgPlansError, TData>(
+ subscriptionKeys.orgPlans(orgSlug),
+ ({ signal }) => getOrgPlans({ orgSlug }, signal),
+ {
+ enabled: enabled && typeof orgSlug !== 'undefined',
+ ...options,
+ }
+ )
+
+export const useOrgPlansPrefetch = ({ orgSlug }: OrgPlansVariables) => {
+ const client = useQueryClient()
+
+ return useCallback(() => {
+ if (orgSlug) {
+ client.prefetchQuery(subscriptionKeys.orgPlans(orgSlug), ({ signal }) =>
+ getOrgPlans({ orgSlug }, signal)
+ )
+ }
+ }, [orgSlug])
+}
diff --git a/studio/state/organization-settings.ts b/studio/state/organization-settings.ts
new file mode 100644
index 00000000000..a6f67c58f78
--- /dev/null
+++ b/studio/state/organization-settings.ts
@@ -0,0 +1,15 @@
+import { proxy, snapshot, useSnapshot } from 'valtio'
+
+export type ORG_SETTINGS_PANEL_KEYS = undefined | 'subscriptionPlan' | 'costControl'
+
+export const orgSettingsPageState = proxy({
+ panelKey: undefined as ORG_SETTINGS_PANEL_KEYS,
+ setPanelKey: (key: ORG_SETTINGS_PANEL_KEYS) => {
+ orgSettingsPageState.panelKey = key
+ },
+})
+
+export const getOrgSettingsPageStateSnapshot = () => snapshot(orgSettingsPageState)
+
+export const useOrgSettingsPageStateSnapshot = (options?: Parameters<typeof useSnapshot>[1]) =>
+ useSnapshot(orgSettingsPageState, options)