The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: remove old subscription UI / use v2 endpoint
Kevin Grünebergf0643d05fab1
diff --git a/apps/docs/pages/guides/platform/custom-domains.mdx b/apps/docs/pages/guides/platform/custom-domains.mdxindex e6d9b67f6c3..f968556bde6 100644--- a/apps/docs/pages/guides/platform/custom-domains.mdx+++ b/apps/docs/pages/guides/platform/custom-domains.mdx@@ -7,7 +7,7 @@ export const meta = {video: 'https://www.youtube.com/v/6rcGnW_Mh-0',}-Custom domains allow you to present a branded experience to your users. Custom domains are available as a [add-on for projects on a paid plan](https://app.supabase.com/project/_/settings/billing/update). Setting up a custom domain requires [Owner or Admin permissions](/docs/guides/platform/access-control#manage-team-members) for the project. Currently, you must use a subdomain (e.g., `api.example.com`, rather than `example.com`) for the purposes of this guide.+Custom domains allow you to present a branded experience to your users. Custom domains are available as a [add-on for projects on a paid plan](https://app.supabase.com/project/_/settings/billing/subscription?panel=customDomain). Setting up a custom domain requires [Owner or Admin permissions](/docs/guides/platform/access-control#manage-team-members) for the project. Currently, you must use a subdomain (e.g., `api.example.com`, rather than `example.com`) for the purposes of this guide.<div className="video-container"><iframediff --git a/apps/docs/pages/guides/platform/exhaust-cpu.mdx b/apps/docs/pages/guides/platform/exhaust-cpu.mdxindex 9a5f0484b26..74d10410615 100644--- a/apps/docs/pages/guides/platform/exhaust-cpu.mdx+++ b/apps/docs/pages/guides/platform/exhaust-cpu.mdx@@ -42,7 +42,7 @@ Everything you do with your Supabase project requires compute. Hence, there canThere are two ways to solve high CPU:1. **Optimize performance:** Get more out of your instance's resources by optimizing your usage. Have a look at our [performance tuning guide](https://supabase.com/docs/guides/platform/performance#examining-query-performance) and our [production readiness guide](https://supabase.com/docs/guides/platform/going-into-prod#performance).-2. **Upgrade your compute:** You can get a Compute Add-on for your project. Follow [this link](https://app.supabase.com/project/_/settings/billing/update/pro) and select your project to see your upgrade options.+2. **Upgrade your compute:** You can get a Compute Add-on for your project. Follow [this link](https://app.supabase.com/project/_/settings/billing/subscription?panel=computeInstance) and select your project to see your upgrade options.export const Page = ({ children }) => <Layout meta={meta} children={children} />diff --git a/apps/docs/pages/guides/platform/exhaust-ram.mdx b/apps/docs/pages/guides/platform/exhaust-ram.mdxindex 597e8200157..1c1649351d2 100644--- a/apps/docs/pages/guides/platform/exhaust-ram.mdx+++ b/apps/docs/pages/guides/platform/exhaust-ram.mdx@@ -45,7 +45,7 @@ Everything you do with your Supabase project requires memory in some form. Hence## How to fix your memory issues-1. **Upgrade your compute:** You can get a Compute Add-on for your project. See your [upgrade options](https://app.supabase.com/project/_/settings/billing/update/pro) by selecting your project.+1. **Upgrade your compute:** You can get a Compute Add-on for your project. See your [upgrade options](https://app.supabase.com/project/_/settings/billing/subscription?panel=computeInstance) by selecting your project.2. **Optimize performance:** Get more out of your instance's resources by optimizing your usage. Have a look at our [performance tuning guide](https://supabase.com/docs/guides/platform/performance#examining-query-performance) and our [production readiness guide](https://supabase.com/docs/guides/platform/going-into-prod#performance).export const Page = ({ children }) => <Layout meta={meta} children={children} />diff --git a/apps/docs/pages/guides/platform/going-into-prod.mdx b/apps/docs/pages/guides/platform/going-into-prod.mdxindex 65e6cfc3797..6f8ce75f135 100644--- a/apps/docs/pages/guides/platform/going-into-prod.mdx+++ b/apps/docs/pages/guides/platform/going-into-prod.mdx@@ -35,7 +35,7 @@ After developing your project and deciding it's Production Ready, you should run- Tools like [k6](https://k6.io/) can simulate traffic from many different users.- Upgrade your database if you require more resources. If you need anything beyond what is listed, contact [email protected].- If you are expecting a surge in traffic (for a big launch) [contact support](https://app.supabase.com/support/new) with more details about your launch. We'll keep an eye on your project.-- If you expect your database size to be > 4 GB, [enable](https://app.supabase.com/project/_/settings/billing/update) the Point in Time Recovery (PITR) addon. Daily backups can take up resources from your database when the backup is in progress. PITR is more resource efficient, since only the changes to the database are backed up.+- If you expect your database size to be > 4 GB, [enable](https://app.supabase.com/project/_/settings/billing/subscription?panel=pitr) the Point in Time Recovery (PITR) addon. Daily backups can take up resources from your database when the backup is in progress. PITR is more resource efficient, since only the changes to the database are backed up.## Availabilitydiff --git a/apps/www/_blog/2022-12-16-postgres-point-in-time-recovery.mdx b/apps/www/_blog/2022-12-16-postgres-point-in-time-recovery.mdxindex 51699b7c65a..dbce9c96b54 100644--- a/apps/www/_blog/2022-12-16-postgres-point-in-time-recovery.mdx+++ b/apps/www/_blog/2022-12-16-postgres-point-in-time-recovery.mdx@@ -39,7 +39,7 @@ While all Pro-plan projects and above are backed up on a daily basis, this means## Getting started-Enabling Point in Time Recovery could be done [in the Dashboard](https://app.supabase.com/project/_/settings/billing/update/pro). Retention for backups used by PITR is set to up to 7 days by default but could be increased to up to 28 days via self-serve.+Enabling Point in Time Recovery can be done [in the Dashboard](https://app.supabase.com/project/_/settings/billing/subscription?panel=pitr). Retention for backups used by PITR is set to up to 7 days by default but could be increased to up to 28 days via self-serve.## More Launch Week 6diff --git a/studio/__mocks__/data/subscriptions/project-subscription-query.js b/studio/__mocks__/data/subscriptions/project-subscription-query.jsdeleted file mode 100644index 8f95fdbac4e..00000000000--- a/studio/__mocks__/data/subscriptions/project-subscription-query.js+++ /dev/null@@ -1,7 +0,0 @@-export const useProjectSubscriptionQuery = jest.fn().mockReturnValue({- data: {- tier: {- supabase_prod_id: 'tier_free',- },- },-})diff --git a/studio/__mocks__/data/subscriptions/project-subscription-v2-query.js b/studio/__mocks__/data/subscriptions/project-subscription-v2-query.jsnew file mode 100644index 00000000000..8335f3ea6e9--- /dev/null+++ b/studio/__mocks__/data/subscriptions/project-subscription-v2-query.js@@ -0,0 +1,7 @@+export const useProjectSubscriptionV2Query = jest.fn().mockReturnValue({+ data: {+ plan: {+ id: 'free',+ },+ },+})diff --git a/studio/components/interfaces/Billing/AddOns/AddOns.types.ts b/studio/components/interfaces/Billing/AddOns/AddOns.types.tsdeleted file mode 100644index 58807e61125..00000000000--- a/studio/components/interfaces/Billing/AddOns/AddOns.types.ts+++ /dev/null@@ -1,26 +0,0 @@-export interface SubscriptionAddon {- id?: string- name: string- description?: string | null- prices: AddonPrice[]- metadata: {- features: string- default_price_id?: string- supabase_prod_id: string- }- // UI specific, do not allow changes if add on has a $0 price to it- isLocked?: boolean-}--export interface AddonPrice {- id?: string- currency: string- unit_amount: number- recurring: {- aggregate_usage: number | null- interval: 'month' | 'year'- interval_count: number- trial_period_days: number | null- usage_type: string- }-}diff --git a/studio/components/interfaces/Billing/AddOns/AddOns.utils.ts b/studio/components/interfaces/Billing/AddOns/AddOns.utils.tsdeleted file mode 100644index 11c6b267632..00000000000--- a/studio/components/interfaces/Billing/AddOns/AddOns.utils.ts+++ /dev/null@@ -1,134 +0,0 @@-import { SubscriptionAddon } from './AddOns.types'--export const getSemanticVersion = (version: string) => {- if (!version) return 0-- // e.g supabase-postgres-14.1.0.88- // There's 4 segments instead so we can't use the semver package- const segments = version.split('supabase-postgres-')- const semver = segments[segments.length - 1]-- // e.g supabase-postgres-14.1.0.99-vault-rc1- const formattedSemver = semver.split('-')[0]-- return Number(formattedSemver.split('.').join(''))-}--export const formatComputeSizes = (addons: SubscriptionAddon[]) => {- const addonsOrder = [- 'addon_instance_small',- 'addon_instance_medium',- 'addon_instance_large',- 'addon_instance_xlarge',- 'addon_instance_xxlarge',- 'addon_instance_4xlarge',- 'addon_instance_8xlarge',- 'addon_instance_12xlarge',- 'addon_instance_16xlarge',- ]-- const microOption: SubscriptionAddon = {- id: undefined,- name: 'Micro Add-on',- metadata: {- default_price_id: undefined,- supabase_prod_id: 'addon_instance_micro',- features: '2-core ARM (shared) • 1GB memory • 2,085Mbps Disk Throughput',- },- prices: [- {- id: undefined,- currency: 'usd',- recurring: {- interval: 'month',- usage_type: 'licensed',- interval_count: 1,- aggregate_usage: null,- trial_period_days: null,- },- unit_amount: 0,- },- ],- }-- return [microOption]- .concat(- addonsOrder.map((id: string) => {- return addons.find((option) => option.metadata.supabase_prod_id === id)- }) as SubscriptionAddon[]- )- .filter((option) => option !== undefined)-}--export const formatPITROptions = (addons: SubscriptionAddon[]) => {- const pitrOrder = ['addon_pitr_7days', 'addon_pitr_14days', 'addon_pitr_28days']-- const noPITROption: SubscriptionAddon = {- id: undefined,- name: 'Disable PITR',- metadata: {- default_price_id: undefined,- supabase_prod_id: 'addon_pitr_0days',- features: '',- },- prices: [- {- id: undefined,- currency: 'usd',- recurring: {- interval: 'month',- usage_type: 'licensed',- interval_count: 1,- aggregate_usage: null,- trial_period_days: null,- },- unit_amount: 0,- },- ],- }-- const pitrOptions = pitrOrder- .map((id: string) => {- return addons.find((option) => option.metadata.supabase_prod_id === id)- })- .filter((option) => option !== undefined) as SubscriptionAddon[]-- if (pitrOptions.length === 0) return []- else return [noPITROption].concat(pitrOptions)-}--export const formatCustomDomainOptions = (addons: SubscriptionAddon[]) => {- const customDomainOrder = ['addon_custom_domains']- const noCustomDomainOption: SubscriptionAddon = {- id: undefined,- name: 'Disable Custom Domains',- metadata: {- default_price_id: undefined,- supabase_prod_id: 'addon_custom_domains_disabled',- features: '',- },- prices: [- {- id: undefined,- currency: 'usd',- recurring: {- interval: 'month',- usage_type: 'licensed',- interval_count: 1,- aggregate_usage: null,- trial_period_days: null,- },- unit_amount: 0,- },- ],- }-- const customDomainOptions = customDomainOrder- .map((id: string) => {- return addons.find((option) => option.metadata.supabase_prod_id === id)- })- .filter((option) => option !== undefined) as SubscriptionAddon[]-- if (customDomainOptions.length === 0) return []- else return [noCustomDomainOption].concat(customDomainOptions)-}diff --git a/studio/components/interfaces/Billing/AddOns/ComputeSizeSelection.tsx b/studio/components/interfaces/Billing/AddOns/ComputeSizeSelection.tsxdeleted file mode 100644index 78746a52fbf..00000000000--- a/studio/components/interfaces/Billing/AddOns/ComputeSizeSelection.tsx+++ /dev/null@@ -1,140 +0,0 @@-import Link from 'next/link'-import { FC, useEffect } from 'react'-import { useRouter } from 'next/router'-import { Badge, Button, IconExternalLink, Radio } from 'ui'--import { useFlag } from 'hooks'-import { useParams } from 'common/hooks'-import { getProductPrice } from '../Billing.utils'-import DisabledWarningDueToIncident from 'components/ui/DisabledWarningDueToIncident'-import { SubscriptionAddon } from './AddOns.types'--interface Props {- computeSizes: SubscriptionAddon[]- currentComputeSize?: SubscriptionAddon- selectedComputeSize: SubscriptionAddon- onSelectOption: (option: any) => void-}--const ComputeSizeSelection: FC<Props> = ({- computeSizes,- currentComputeSize,- selectedComputeSize,- onSelectOption,-}) => {- const { ref } = useParams()- const { asPath } = useRouter()- useEffect(() => {- const hash = asPath.split('#')[1]- if (hash !== undefined) {- window.location.hash = ''- window.location.hash = hash- }- }, [asPath])- const addonUpdateDisabled = useFlag('disableProjectCreationAndUpdate')- return (- <div className="space-y-4">- <div className="flex items-center justify-between">- <div>- <div className="flex items-center space-x-2">- <h4 id="compute-addon" className="text-lg">- <Link href="#compute-addon" prefetch={false}>- <a>Compute add-ons</a>- </Link>- </h4>- <Badge color="green">Optional</Badge>- </div>- <p className="text-sm text-scale-1100">- Choose the database instance size that best fits your needs- </p>- </div>- <Link href="https://supabase.com/docs/guides/platform/compute-add-ons">- <a target="_blank" rel="noreferrer">- <Button type="default" icon={<IconExternalLink strokeWidth={1.5} />}>- About compute add-ons- </Button>- </a>- </Link>- </div>- {addonUpdateDisabled ? (- <DisabledWarningDueToIncident title="Updating database add-ons is currently disabled" />- ) : currentComputeSize?.isLocked ? (- <div- className={[- 'flex items-center justify-between block w-full rounded px-4 py-3',- 'border border-scale-600 bg-scale-100 dark:border-scale-500 dark:bg-scale-400',- ].join(' ')}- >- <div className="space-y-3">- <h5 className="text-sm text-scale-1200">- Your project currently has the {currentComputeSize.name} included- </h5>- <p className="text-sm text-scale-1100">- If you would like to change your compute size, do reach out to us- </p>- </div>- <div className="">- <Link- href={`/support/new?ref=${ref}&category=sales&subject=Disable%20custom%20domains`}- >- <a>- <Button>Contact us</Button>- </a>- </Link>- </div>- </div>- ) : (- <Radio.Group type="cards" className="billing-compute-radio">- {computeSizes.map((option: any) => {- const defaultPrice = getProductPrice(option)- return (- <Radio- hidden- key={option.id || 'micro-add-on'}- align="vertical"- // @ts-ignore- label={- <div className="flex items-center space-x-4">- <p>{option.name}</p>- {currentComputeSize?.id === option.id && (- <Badge color="brand">Current selection</Badge>- )}- </div>- }- // @ts-ignore- description={option.metadata.features}- value={option.id}- optionalLabel={- <div className="w-[6rem] flex items-center justify-end">- ${defaultPrice.unit_amount / 100} / month- </div>- }- checked={selectedComputeSize?.id === option.id}- onChange={() => onSelectOption(option)}- />- )- })}- <Radio- hidden- disabled- key="compute-size-cta"- align="vertical"- label="Need a larger add on?"- description="Reach out to us - we've got you covered!"- optionalLabel={- <Link- href={`/support/new?ref=${ref}&category=sales&subject=Enquiry%20for%20larger%20compute%20size`}- >- <a>- <Button>Contact us</Button>- </a>- </Link>- }- />- </Radio.Group>- )}- </div>- )-}--export default ComputeSizeSelectiondiff --git a/studio/components/interfaces/Billing/AddOns/CustomDomainSelection.tsx b/studio/components/interfaces/Billing/AddOns/CustomDomainSelection.tsxdeleted file mode 100644index 31b290805f4..00000000000--- a/studio/components/interfaces/Billing/AddOns/CustomDomainSelection.tsx+++ /dev/null@@ -1,112 +0,0 @@-import Link from 'next/link'-import { FC, useEffect } from 'react'-import { useRouter } from 'next/router'-import { Badge, Button, Radio } from 'ui'--import { useFlag } from 'hooks'-import { useParams } from 'common/hooks'-import { getProductPrice } from '../Billing.utils'-import DisabledWarningDueToIncident from 'components/ui/DisabledWarningDueToIncident'-import { SubscriptionAddon } from './AddOns.types'--interface Props {- options: SubscriptionAddon[]- currentOption?: SubscriptionAddon- selectedOption: SubscriptionAddon- onSelectOption: (option: any) => void-}--const CustomDomainSelection: FC<Props> = ({- options,- currentOption,- selectedOption,- onSelectOption,-}) => {- const { ref } = useParams()- const addonUpdateDisabled = useFlag('disableProjectCreationAndUpdate')- const { asPath } = useRouter()- useEffect(() => {- const hash = asPath.split('#')[1]- if (hash !== undefined) {- window.location.hash = ''- window.location.hash = hash- }- }, [asPath])- return (- <div className="space-y-4">- <div>- <div className="flex items-center space-x-2">- <h4 id="custom-domain-addon" className="text-lg">- <Link href="#custom-domain-addon" prefetch={false}>- <a>Custom Domains</a>- </Link>- </h4>- <Badge color="green">Optional</Badge>- </div>- <p className="text-sm text-scale-1100">Present a branded experience to your users</p>- </div>- {addonUpdateDisabled ? (- <DisabledWarningDueToIncident title="Updating database add-ons is currently disabled" />- ) : currentOption?.isLocked ? (- <div- className={[- 'flex items-center justify-between block w-full rounded px-4 py-3',- 'border border-scale-600 bg-scale-100 dark:border-scale-500 dark:bg-scale-400',- ].join(' ')}- >- <div className="space-y-3">- <h5 className="text-sm text-scale-1200">- Your project currently has custom domains included- </h5>- <p className="text-sm text-scale-1100">- If you would like to disable custom domains, do reach out to us- </p>- </div>- <div className="">- <Link- href={`/support/new?ref=${ref}&category=sales&subject=Disable%20custom%20domains%20`}- >- <a>- <Button>Contact us</Button>- </a>- </Link>- </div>- </div>- ) : (- <Radio.Group type="cards" className="billing-compute-radio">- {options.map((option: any) => {- const defaultPrice = getProductPrice(option)- return (- <Radio- hidden- key={option.id || 'micro-add-on'}- align="vertical"- // @ts-ignore- label={- <div className="flex items-center space-x-4">- <p>{option.name}</p>- {currentOption?.id === option.id && (- <Badge color="brand">Current selection</Badge>- )}- </div>- }- // @ts-ignore- description={- <div>- <p>{option.metadata.features}</p>- </div>- }- value={option.id}- optionalLabel={<div>${defaultPrice.unit_amount / 100} / month</div>}- checked={selectedOption?.id === option.id}- onChange={() => onSelectOption(option)}- />- )- })}- </Radio.Group>- )}- </div>- )-}--export default CustomDomainSelectiondiff --git a/studio/components/interfaces/Billing/AddOns/PITRDurationSelection.tsx b/studio/components/interfaces/Billing/AddOns/PITRDurationSelection.tsxdeleted file mode 100644index e05291b08be..00000000000--- a/studio/components/interfaces/Billing/AddOns/PITRDurationSelection.tsx+++ /dev/null@@ -1,146 +0,0 @@-import Link from 'next/link'-import { FC, useEffect } from 'react'-import { useRouter } from 'next/router'-import { Badge, IconAlertCircle, Radio, Button } from 'ui'--import { useFlag, useStore } from 'hooks'-import { useParams } from 'common/hooks'-import { SubscriptionAddon } from './AddOns.types'-import { getProductPrice } from '../Billing.utils'-import DisabledWarningDueToIncident from 'components/ui/DisabledWarningDueToIncident'-import InformationBox from 'components/ui/InformationBox'-import { getSemanticVersion } from './AddOns.utils'--interface Props {- pitrDurationOptions: SubscriptionAddon[]- currentPitrDuration?: SubscriptionAddon- selectedPitrDuration?: SubscriptionAddon- onSelectOption: (option: any) => void-}--const PITRDurationSelection: FC<Props> = ({- pitrDurationOptions,- currentPitrDuration,- selectedPitrDuration,- onSelectOption,-}) => {- const { ui } = useStore()- const { ref } = useParams()- const addonUpdateDisabled = useFlag('disableProjectCreationAndUpdate')-- // Only projects of version greater than supabase-postgrest-14.1.0.44 can use PITR- const sufficientPgVersion = getSemanticVersion(ui.selectedProject?.dbVersion ?? '') >= 141044- const { asPath } = useRouter()- useEffect(() => {- const hash = asPath.split('#')[1]- if (hash !== undefined) {- window.location.hash = ''- window.location.hash = hash- }- }, [asPath])- return (- <div className="space-y-4">- <div>- <div className="flex items-center space-x-2">- <h4 id="pitr-addon" className="text-lg">- <Link href="#pitr-addon" prefetch={false}>- <a>Point in time recovery (PITR)</a>- </Link>- </h4>- <Badge color="green">Optional</Badge>- </div>- <p className="text-sm text-scale-1100">- Restore your database from a specific point in time- </p>- {sufficientPgVersion && !currentPitrDuration?.isLocked && (- <div className="mt-2">- <InformationBox- icon={<IconAlertCircle strokeWidth={2} />}- title="Your project is required to minimally be on a Small Add-on to enable PITR"- description="This is to ensure that your project has enough resources to execute PITR successfully"- />- </div>- )}- </div>- {addonUpdateDisabled ? (- <DisabledWarningDueToIncident title="Updating database add-ons is currently disabled" />- ) : !sufficientPgVersion ? (- <InformationBox- hideCollapse- defaultVisibility- title="Your project is too old to be able to enable PITR for"- description={- <div className="flex items-center justify-between m-1">- <p className="text-sm leading-normal">Reach out to us if you're interested!</p>- <Link- href={`/support/new?ref=${ref}&category=sales&subject=Project%20too%20old%20old%20for%20PITR`}- >- <a>- <Button type="default">Contact support</Button>- </a>- </Link>- </div>- }- icon={<IconAlertCircle strokeWidth={2} />}- />- ) : currentPitrDuration?.isLocked ? (- <div- className={[- 'flex items-center justify-between block w-full rounded px-4 py-3',- 'border border-scale-600 bg-scale-100 dark:border-scale-500 dark:bg-scale-400',- ].join(' ')}- >- <div className="space-y-3">- <h5 className="text-sm text-scale-1200">- Your project currently has {currentPitrDuration.name} included- </h5>- <p className="text-sm text-scale-1100">- If you would like to change your PITR duration, do reach out to us- </p>- </div>- <div className="">- <Link href={`/support/new?ref=${ref}&category=sales&subject=Change%20PITR%20duration`}>- <a>- <Button>Contact us</Button>- </a>- </Link>- </div>- </div>- ) : (- <Radio.Group type="cards" className="billing-compute-radio">- {pitrDurationOptions.map((option: any) => {- const defaultPrice = getProductPrice(option)- return (- <Radio- hidden- key={option.id || 'pitr-disabled'}- align="vertical"- // @ts-ignore- label={- <div className="flex items-center space-x-4">- <p>{option.name}</p>- {currentPitrDuration?.id === option.id && (- <Badge color="brand">Current selection</Badge>- )}- </div>- }- // @ts-ignore- description={- <div>- <p>{option.metadata.features}</p>- </div>- }- value={option.id}- optionalLabel={<div>${defaultPrice.unit_amount / 100} / month</div>}- checked={selectedPitrDuration?.id === option.id}- onChange={() => onSelectOption(option)}- />- )- })}- </Radio.Group>- )}- </div>- )-}--export default PITRDurationSelectiondiff --git a/studio/components/interfaces/Billing/AddOns/SupportPlan.tsx b/studio/components/interfaces/Billing/AddOns/SupportPlan.tsxdeleted file mode 100644index 3208912bace..00000000000--- a/studio/components/interfaces/Billing/AddOns/SupportPlan.tsx+++ /dev/null@@ -1,59 +0,0 @@-import Link from 'next/link'-import { FC, useEffect } from 'react'-import { useRouter } from 'next/router'-import { Button } from 'ui'-import { useParams } from 'common/hooks'--interface Props {- currentOption?: any-}--const SupportPlan: FC<Props> = ({ currentOption }) => {- const { ref } = useParams()- const { asPath } = useRouter()- useEffect(() => {- const hash = asPath.split('#')[1]- if (hash !== undefined) {- window.location.hash = ''- window.location.hash = hash- }- }, [asPath])- return (- <div className="space-y-4">- <div>- <div className="flex items-center space-x-2">- <h4 id="support-addon" className="text-lg">- <Link href="#support-addon" prefetch={false}>- <a>Support Plan</a>- </Link>- </h4>- </div>- <p className="text-sm text-scale-1100">Designated support with guaranteed response times</p>- </div>- <div- className={[- 'flex items-center justify-between block w-full rounded px-4 py-3',- 'border border-scale-600 bg-scale-100 dark:border-scale-500 dark:bg-scale-400',- ].join(' ')}- >- <div className="space-y-3">- <h5 className="text-sm text-scale-1200">- Your project is currently on {currentOption.name}- </h5>- <p className="text-sm text-scale-1100">- If you would like to change your support plan, do reach out to us- </p>- </div>- <div className="">- <Link href={`/support/new?ref=${ref}&category=sales&subject=Change%20support%20plan`}>- <a>- <Button>Contact us</Button>- </a>- </Link>- </div>- </div>- </div>- )-}--export default SupportPlandiff --git a/studio/components/interfaces/Billing/Billing.constants.tsx b/studio/components/interfaces/Billing/Billing.constants.tsxdeleted file mode 100644index 5b55dbb1ba8..00000000000--- a/studio/components/interfaces/Billing/Billing.constants.tsx+++ /dev/null@@ -1,189 +0,0 @@-import { IconArchive, IconCode, IconDatabase, IconKey, IconZap } from 'ui'--export const USAGE_BASED_PRODUCTS = [- {- title: 'Database',- icon: <IconDatabase className="dark:text-scale-100" size={16} strokeWidth={2} />,- features: [- {- key: 'db_size',- attribute: 'total_db_size_bytes',- title: 'Database size',- units: 'bytes',- costPerUnit: 0.125,- tooltip: (- <span>- Billing is based on the average daily database size in GB throughout the billing period.{' '}- <a- href="https://supabase.com/docs/guides/platform/database-usage"- target="_blank"- rel="noreferrer"- >- Docs- </a>- </span>- ),- },- {- key: 'db_egress',- attribute: 'total_egress_modified',- title: 'Database egress',- units: 'bytes',- costPerUnit: 0.09,- tooltip: (- <span>- Database egress contains any outgoing traffic (egress) from your database. Billing is- based on the total sum of egress in GB throughout your billing period.- </span>- ),- },- ],- },- {- title: 'Auth',- icon: <IconKey className="dark:text-scale-100" size={16} strokeWidth={2} />,- features: [- {- key: 'monthly_active_users',- attribute: 'total_auth_billing_period_mau',- title: 'Monthly Active Users',- units: 'absolute',- costPerUnit: 0.00325,- tooltip: (- <span>- The amount of distinct users requesting your API throughout the billing period. Resets- at the beginning of every billing period.- </span>- ),- },- {- key: 'monthly_active_sso_users',- attribute: 'total_auth_billing_period_sso_mau',- title: 'Monthly Single Sign-On Users',- units: 'absolute',- costPerUnit: 0.015,- tooltip: (- <span>- The amount of distinct Single Sign-On users requesting your API throughout the billing- period. Resets at the beginning of every billing period.- </span>- ),- },- ],- },- {- title: 'Storage',- icon: <IconArchive className="dark:text-scale-100" size={16} strokeWidth={2} />,- features: [- {- key: 'storage_size',- attribute: 'total_storage_size_bytes',- title: 'Storage space',- units: 'bytes',- costPerUnit: 0.021,- tooltip: (- <span>- The storage size is the sum of all objects in your storage buckets. Billing is based on- the average size in GB throughout your billing period.- </span>- ),- },- {- key: 'storage_egress',- attribute: 'total_storage_egress',- title: 'Storage egress',- units: 'bytes',- costPerUnit: 0.09,- tooltip: (- <span>- Storage egress contains any outgoing traffic (egress) from your storage buckets, only- download operations are counted. We currently do not differentiate between no-cache and- cache hits. Billing is based on the total amount of egress in GB throughout your billing- period.- </span>- ),- },- {- key: 'storage_image_render_count',- attribute: 'total_storage_image_render_count',- title: 'Storage Image Transformations',- units: 'absolute',- costPerUnit: 0.005,- tooltip: (- <span>- We distinctly count all images transformed in the billing period, ignoring any- transformations. Transforming one image with different transformations (i.e. once with- height=50 and once with height=150), only counts as one. Resets at the beginning of- every billing period.- </span>- ),- },- ],- },- {- title: 'Functions',- icon: <IconCode className="dark:text-scale-100" size={16} strokeWidth={2} />,- features: [- {- key: 'func_count',- attribute: 'total_func_count',- title: 'Function Count',- units: 'absolute',- costPerUnit: 0.1,- tooltip: (- <span>- We continuously monitor the amount of serverless functions in your project. Billing is- based on the maximum amount of functions at any point in time throughout your billing- period.- </span>- ),- },-- {- key: 'func_invocations',- attribute: 'total_func_invocations',- title: 'Function Invocations',- units: 'absolute',- costPerUnit: 0.000002,- tooltip: (- <span>- Every serverless function invocation independent of response status is counted.- Billing is based on the sum of all invocations throughout your billing period.- </span>- ),- },- ],- },- {- title: 'Realtime',- icon: <IconZap className="dark:text-scale-100" size={16} strokeWidth={2} />,- features: [- {- key: 'realtime_message_count',- attribute: 'total_realtime_message_count',- title: 'Realtime Messages',- units: 'absolute',- costPerUnit: 0.0000025,- tooltip: (- <span>- Billing is based on the total amount of messages throughout your billing period.- </span>- ),- },-- {- key: 'realtime_peak_connection',- attribute: 'total_realtime_peak_connection',- title: 'Realtime Concurrent Peak Connections',- units: 'absolute',- costPerUnit: 0.01,- tooltip: (- <span>- Billing is based on the maximum amount of concurrent peak connections throughout your- billing period.- </span>- ),- },- ],- },-]diff --git a/studio/components/interfaces/Billing/Billing.types.ts b/studio/components/interfaces/Billing/Billing.types.tsindex 8066b18b1df..15758bc7238 100644--- a/studio/components/interfaces/Billing/Billing.types.ts+++ b/studio/components/interfaces/Billing/Billing.types.ts@@ -1,30 +1,3 @@-// I'm guessing this should come from the API?-export interface SubscriptionPreview {- // Amount due total- amount_due: number- // Amount due total - available credit balance- amount_due_immediately: number- // Amount of credit the org has left- available_credit_balance: number- // Remaining credit balance after deducting to amount due immediately- remaining_credit_balance: number- // Amount of credits returned as refund from a downgrade- returned_credits_for_unused_time: number- // Amount due for each subsequent month- base_amount_due_next_billing_cycle: number- // Date for which bill will be enacted- bill_on: number- // Remaining number of days to end of current billing cycle- // This is meant for FE to display the refund specifics- remaining_days_in_current_billing_cycle: number- // Total days in current billing cycle- // This is meant for FE to display the refund specifics- total_days_in_current_billing_cycle: number-- has_changes: boolean- cost_breakdown: any[]-}-export interface PaymentMethod {id: stringbilling_details: objectdiff --git a/studio/components/interfaces/Billing/Billing.utils.ts b/studio/components/interfaces/Billing/Billing.utils.tsdeleted file mode 100644index 4bad6ed40a7..00000000000--- a/studio/components/interfaces/Billing/Billing.utils.ts+++ /dev/null@@ -1,146 +0,0 @@-import { SubscriptionAddon } from './AddOns/AddOns.types'-import {- formatComputeSizes,- formatCustomDomainOptions,- formatPITROptions,-} from './AddOns/AddOns.utils'-import { StripeSubscription } from './Subscription/Subscription.types'--// Retrieve the price based on the default price id of the product-export const getProductPrice = (product: any) => {- const defaultPriceId = product.metadata?.default_price_id- const price =- defaultPriceId !== undefined- ? product.prices.find((price: any) => price.id === defaultPriceId)- : product.prices[0]- return price-}--// Products can have multiple prices, this is to get the correct one based on the subscription-const getProductPriceId = (- currentSubscription: StripeSubscription,- product: any-): string | undefined => {- const existingAddon = currentSubscription.addons.find((addon) => addon.prod_id === product.id)- const existingAddonPriceId = product.prices.find(- (price: any) => price.unit_amount === existingAddon?.unit_amount- )- return existingAddonPriceId?.id || getProductPrice(product)?.id-}--export const validateSubscriptionUpdatePayload = (selectedAddons: {- computeSize: SubscriptionAddon- pitrDuration: SubscriptionAddon- customDomains: SubscriptionAddon-}) => {- if (- selectedAddons.pitrDuration?.id !== undefined &&- selectedAddons.computeSize.id === undefined- ) {- return 'To enable PITR for your project, your project must minimally be on a Small Add-on.'- }- return undefined-}--export const formSubscriptionUpdatePayload = (- currentSubscription: StripeSubscription,- selectedTier: any,- selectedAddons: {- computeSize: SubscriptionAddon- pitrDuration: SubscriptionAddon- customDomains: SubscriptionAddon- },- nonChangeableAddons: SubscriptionAddon[],- selectedPaymentMethod: string,- region: string-) => {- const { computeSize, pitrDuration, customDomains } = selectedAddons-- const computeSizePriceId = getProductPriceId(currentSubscription, computeSize)- const pitrAddonPriceId = getProductPriceId(currentSubscription, pitrDuration)- const customDomainPriceId = getProductPriceId(currentSubscription, customDomains)- const tierPriceId = selectedTier ? getProductPrice(selectedTier) : undefined-- const nonChangeablePriceIds = nonChangeableAddons.map((addon) =>- getProductPriceId(currentSubscription, addon)- )-- const addons =- region === 'af-south-1'- ? []- : [computeSizePriceId, pitrAddonPriceId, customDomainPriceId]- .concat(nonChangeablePriceIds)- .filter((x) => x !== undefined)- const proration_date = Math.floor(Date.now() / 1000)-- return {- ...(tierPriceId && { tier: tierPriceId.id }),- addons,- proration_date,- payment_method: selectedPaymentMethod- }-}--const findAddon = (- subscription: StripeSubscription,- addons: SubscriptionAddon[],- key: string,- defaultKey: string-): SubscriptionAddon => {- const product = addons.find((option) => {- const subscriptionAddon = subscription.addons.find((addon) =>- addon.supabase_prod_id.includes(key)- )- return option.id === subscriptionAddon?.prod_id- })- if (product === undefined) {- return addons.find(- (addon) => addon.metadata.supabase_prod_id === defaultKey- ) as SubscriptionAddon- } else {- const subscriptionAddon = subscription.addons.find((addon) => addon.prod_id === product.id)- return { ...product, isLocked: subscriptionAddon?.unit_amount === 0 }- }-}--export const getCurrentAddons = (- currentSubscription: StripeSubscription,- addons: SubscriptionAddon[]-): {- computeSize: SubscriptionAddon- pitrDuration: SubscriptionAddon- customDomains: SubscriptionAddon- supportPlan?: SubscriptionAddon-} => {- const computeSizes = formatComputeSizes(addons)- const pitrDurationOptions = formatPITROptions(addons)- const customDomainOptions = formatCustomDomainOptions(addons)-- const computeSize = findAddon(- currentSubscription,- computeSizes,- '_instance_',- 'addon_instance_micro'- )- const pitrDuration = findAddon(- currentSubscription,- pitrDurationOptions,- '_pitr_',- 'addon_pitr_0days'- )- const customDomains = findAddon(- currentSubscription,- customDomainOptions,- '_custom_domains',- 'addon_custom_domains_disabled'- )-- const supportPlan = addons.find((option) => {- const subscriptionSupportPlan = currentSubscription?.addons.find((addon) =>- addon.supabase_prod_id.includes('_support_')- )- return option.id === subscriptionSupportPlan?.prod_id- })-- return { computeSize, pitrDuration, customDomains, supportPlan }-}diff --git a/studio/components/interfaces/Billing/EnterpriseUpdate.tsx b/studio/components/interfaces/Billing/EnterpriseUpdate.tsxdeleted file mode 100644index b94d583c065..00000000000--- a/studio/components/interfaces/Billing/EnterpriseUpdate.tsx+++ /dev/null@@ -1,337 +0,0 @@-import { FC, useState, useEffect, useRef } from 'react'-import { useRouter } from 'next/router'-import { Transition } from '@headlessui/react'--import { useStore } from 'hooks'-import { getURL } from 'lib/helpers'-import { post, patch } from 'lib/common/fetch'-import { API_URL, PROJECT_STATUS } from 'lib/constants'-import HCaptcha from '@hcaptcha/react-hcaptcha'--import Divider from 'components/ui/Divider'-import { SubscriptionAddon } from './AddOns/AddOns.types'-import {- formatComputeSizes,- formatCustomDomainOptions,- formatPITROptions,-} from './AddOns/AddOns.utils'-import {- AddNewPaymentMethodModal,- ComputeSizeSelection,- PITRDurationSelection,- StripeSubscription,- PaymentSummaryPanel,- UpdateSuccess,- CustomDomainSelection,-} from './'-import { PaymentMethod, SubscriptionPreview } from './Billing.types'-import { formSubscriptionUpdatePayload, getCurrentAddons } from './Billing.utils'-import SupportPlan from './AddOns/SupportPlan'-import { subscriptionKeys } from 'data/subscriptions/keys'-import { useQueryClient } from '@tanstack/react-query'--interface Props {- products: { tiers: any[]; addons: SubscriptionAddon[] }- paymentMethods?: PaymentMethod[]- currentSubscription: StripeSubscription- isLoadingPaymentMethods: boolean- onPaymentMethodAdded: () => void-}--const EnterpriseUpdate: FC<Props> = ({- products,- paymentMethods,- currentSubscription,- isLoadingPaymentMethods,- onPaymentMethodAdded,-}) => {- const { app, ui } = useStore()- const router = useRouter()- const queryClient = useQueryClient()-- const [captchaToken, setCaptchaToken] = useState<string | null>(null)- const captchaRef = useRef<HCaptcha>(null)-- const projectId = ui.selectedProject?.id ?? -1- const projectRef = ui.selectedProject?.ref ?? 'default'- const projectRegion = ui.selectedProject?.region ?? ''-- const { addons } = products- const computeSizes = formatComputeSizes(addons)- const pitrDurationOptions = formatPITROptions(addons)- const customDomainOptions = formatCustomDomainOptions(addons)- const currentAddons = getCurrentAddons(currentSubscription, addons)-- // [Joshen TODO] Ideally we just have a state to hold all the add ons selection, rather than individual- // Even better if we can just use the <Form> component to handle all of these. Mainly to reduce the amount- // of unnecessary state management on this complex page.- const [selectedComputeSize, setSelectedComputeSize] = useState<SubscriptionAddon>(- currentAddons.computeSize- )- const [selectedPITRDuration, setSelectedPITRDuration] = useState<SubscriptionAddon>(- currentAddons.pitrDuration- )- const [selectedCustomDomainOption, setSelectedCustomDomainOption] = useState<SubscriptionAddon>(- currentAddons.customDomains- )- // [Joshen TODO] Future - We may need to also include any add ons outside of- // compute size, pitr, custom domain and support plan, although we dont have any now- const nonChangeableAddons = [currentAddons.supportPlan].filter(- (x) => x !== undefined- ) as SubscriptionAddon[]-- // [Joshen] Scaffolded here- const selectedAddons = {- computeSize: selectedComputeSize,- pitrDuration: selectedPITRDuration,- customDomains: selectedCustomDomainOption,- }-- const [selectedPaymentMethodId, setSelectedPaymentMethodId] = useState<any>()- const [subscriptionPreview, setSubscriptionPreview] = useState<SubscriptionPreview>()-- const [isRefreshingPreview, setIsRefreshingPreview] = useState(false)- const [isSubmitting, setIsSubmitting] = useState(false)- const [isSuccessful, setIsSuccessful] = useState(false)- const [showAddPaymentMethodModal, setShowAddPaymentMethodModal] = useState(false)-- const isChangingComputeSize = currentAddons.computeSize?.id !== selectedAddons.computeSize.id-- const onLocalPaymentMethodAdded = () => {- setShowAddPaymentMethodModal(false)- return onPaymentMethodAdded()- }-- useEffect(() => {- getSubscriptionPreview()- }, [selectedComputeSize, selectedPITRDuration, selectedCustomDomainOption])-- useEffect(() => {- if (!isLoadingPaymentMethods && paymentMethods && paymentMethods.length > 0) {- setSelectedPaymentMethodId(paymentMethods[0].id)- }- }, [isLoadingPaymentMethods, paymentMethods])-- const getSubscriptionPreview = async () => {- // For enterprise, only tier will be fixed based on current subscription- // Only allow add-ons changing- const payload = {- ...formSubscriptionUpdatePayload(- currentSubscription,- null,- selectedAddons,- nonChangeableAddons,- selectedPaymentMethodId,- projectRegion- ),- tier: currentSubscription.tier.price_id,- }-- setIsRefreshingPreview(true)- const preview = await post(`${API_URL}/projects/${projectRef}/subscription/preview`, payload)- if (preview.error) {- ui.setNotification({- category: 'error',- message: `Failed to fetch subscription preview: ${preview.error.message}`,- })- }- setSubscriptionPreview(preview)- setIsRefreshingPreview(false)- }-- const resetCaptcha = () => {- setCaptchaToken(null)- captchaRef.current?.resetCaptcha()- }-- const beforeConfirmPayment = async (): Promise<boolean> => {- setIsSubmitting(true)- let token = captchaToken-- try {- if (!token) {- const captchaResponse = await captchaRef.current?.execute({ async: true })- token = captchaResponse?.response ?? null- setCaptchaToken(token)- }- } catch (error) {- setIsSubmitting(false)- return false- }-- setIsSubmitting(false)- return true- }-- // Last todo to support enterprise billing on dashboard + E2E test- const onConfirmPayment = async () => {- setIsSubmitting(true)- const payload = {- ...formSubscriptionUpdatePayload(- currentSubscription,- null,- selectedAddons,- nonChangeableAddons,- selectedPaymentMethodId,- projectRegion- ),- tier: currentSubscription.tier.price_id,- }- const res = await patch(`${API_URL}/projects/${projectRef}/subscription`, payload)- resetCaptcha()-- if (res?.error) {- ui.setNotification({- category: 'error',- message: `Failed to update subscription: ${res?.error?.message}`,- })- } else {- if (isChangingComputeSize) {- app.onProjectStatusUpdated(projectId, PROJECT_STATUS.RESTORING)- ui.setNotification({- category: 'success',- message:- 'Your project has been updated and is currently restarting to update its instance size',- duration: 8000,- })- router.push(`/project/${projectRef}`)- } else {- setIsSuccessful(true)- }-- await Promise.all([- queryClient.invalidateQueries(subscriptionKeys.subscriptionV2(projectRef)),- queryClient.invalidateQueries(subscriptionKeys.subscription(projectRef)),- queryClient.invalidateQueries(subscriptionKeys.addons(projectRef)),- ])- }- setIsSubmitting(false)- }-- if (!isSubmitting && isSuccessful) {- return (- <UpdateSuccess- projectRef={projectRef || ''}- title="Your project has been updated!"- message="Let us know if you have any feedback at [email protected]."- />- )- }-- return (- <>- <Transition- show- enter="transition ease-out duration-300"- enterFrom="transform opacity-0 translate-x-10"- enterTo="transform opacity-100 translate-x-0"- className="flex w-full items-start justify-between"- >- <div className="flex-grow mt-10">- <div className="relative space-y-4">- <div className="space-y-8">- <div className="space-y-4 2xl:max-w-5xl mx-auto px-32">- <h4 className="text-lg text-scale-900 !mb-8">Change your project's subscription</h4>- </div>-- <div- className="space-y-8 overflow-y-auto pb-8 2xl:max-w-5xl mx-auto px-32"- style={{ height: 'calc(100vh - 6.4rem - 57px)' }}- >- <h3 className="text-xl">- Managing your <span className="text-brand-900">Enterprise</span> plan- </h3>- <div- className={[- 'bg-panel-body-light dark:bg-panel-body-dark border-panel-border-light border-panel-border-dark',- 'flex max-w-[600px] items-center justify-between gap-16 rounded border px-6 py-4 drop-shadow-sm',- ].join(' ')}- >- <p className="text-sm">- If you'd like to change your subscription away from enterprise, please reach out- to <span className="text-brand-900">[email protected]</span> with your- request.- </p>- </div>- {projectRegion !== 'af-south-1' && (- <>- {currentAddons.supportPlan !== undefined && (- <>- <Divider light />- <SupportPlan currentOption={currentAddons.supportPlan} />- </>- )}- <Divider light />- <CustomDomainSelection- options={customDomainOptions}- currentOption={currentAddons.customDomains}- selectedOption={selectedAddons.customDomains}- onSelectOption={setSelectedCustomDomainOption}- />- <Divider light />- <PITRDurationSelection- pitrDurationOptions={pitrDurationOptions}- currentPitrDuration={currentAddons.pitrDuration}- selectedPitrDuration={selectedAddons.pitrDuration}- onSelectOption={setSelectedPITRDuration}- />- <Divider light />- <ComputeSizeSelection- computeSizes={computeSizes || []}- currentComputeSize={currentAddons.computeSize}- selectedComputeSize={selectedAddons.computeSize}- onSelectOption={setSelectedComputeSize}- />- </>- )}- </div>- </div>- </div>- </div>- <PaymentSummaryPanel- isSpendCapEnabled={true}- isSubmitting={isSubmitting}- isRefreshingPreview={isRefreshingPreview}- currentSubscription={currentSubscription}- subscriptionPreview={subscriptionPreview}- // Current subscription configuration based on DB- currentPlan={currentSubscription.tier}- currentAddons={currentAddons}- // Selected subscription configuration based on UI- selectedAddons={selectedAddons}- paymentMethods={paymentMethods}- isLoadingPaymentMethods={isLoadingPaymentMethods}- selectedPaymentMethod={selectedPaymentMethodId}- onSelectPaymentMethod={setSelectedPaymentMethodId}- onSelectAddNewPaymentMethod={() => {- setShowAddPaymentMethodModal(true)- }}- beforeConfirmPayment={beforeConfirmPayment}- onConfirmPayment={onConfirmPayment}- captcha={- <HCaptcha- ref={captchaRef}- sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY!}- size="invisible"- onVerify={(token) => {- setCaptchaToken(token)- }}- onExpire={() => {- setCaptchaToken(null)- }}- />- }- />- </Transition>-- <AddNewPaymentMethodModal- visible={showAddPaymentMethodModal}- returnUrl={`${getURL()}/project/${projectRef}/settings/billing/update/pro`}- onCancel={() => setShowAddPaymentMethodModal(false)}- onConfirm={() => onLocalPaymentMethodAdded()}- />- </>- )-}--export default EnterpriseUpdatediff --git a/studio/components/interfaces/Billing/ExitSurvey/ExitSurvey.tsx b/studio/components/interfaces/Billing/ExitSurvey/ExitSurvey.tsxdeleted file mode 100644index 365e59dbd64..00000000000--- a/studio/components/interfaces/Billing/ExitSurvey/ExitSurvey.tsx+++ /dev/null@@ -1,389 +0,0 @@-import { useReducer, useState, useEffect, useRef } from 'react'-import { useRouter } from 'next/router'-import { includes, without } from 'lodash'-import { Transition } from '@headlessui/react'-import * as Tooltip from '@radix-ui/react-tooltip'-import { Button, Form, Input, Modal, IconArrowLeft, Alert } from 'ui'--import { useFlag, useStore } from 'hooks'-import { post, patch } from 'lib/common/fetch'-import { API_URL, PROJECT_STATUS } from 'lib/constants'-import { UpdateSuccess } from '../'-import { SubscriptionPreview } from '../Billing.types'-import { StripeSubscription } from 'components/interfaces/Billing'-import HCaptcha from '@hcaptcha/react-hcaptcha'-import { CANCELLATION_REASONS } from 'components/interfaces/BillingV2/Billing.constants'-import { subscriptionKeys } from 'data/subscriptions/keys'-import { useQueryClient } from '@tanstack/react-query'--interface ExitSurveyProps {- freeTier: any- subscription?: StripeSubscription- onSelectBack: () => void-}--const ExitSurvey = ({ freeTier, subscription, onSelectBack }: ExitSurveyProps) => {- const router = useRouter()- const { app, ui } = useStore()- const queryClient = useQueryClient()-- const projectId = ui.selectedProject?.id ?? -1- const projectRef = ui.selectedProject?.ref-- const captchaRef = useRef<HCaptcha>(null)- const [captchaToken, setCaptchaToken] = useState<string | null>(null)- const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')-- const formRef = useRef<any>()-- const initialValues = { message: '' }- const [message, setMessage] = useState('')- const [selectedReasons, dispatchSelectedReasons] = useReducer(reducer, [])-- // Tracking submitting state separately outside of form component cause of- // the additional dynamic confirmation modal that we're doing- const [isSubmitting, setIsSubmitting] = useState(false)- const [isSubmittingDowngradeModal, setIsSubmittingDowngradeModal] = useState(false)-- const [isSuccessful, setIsSuccessful] = useState(false)- const [showConfirmModal, setShowConfirmModal] = useState(false)- const [subscriptionPreview, setSubscriptionPreview] = useState<SubscriptionPreview>()-- // Anything above a micro instance size will involve a change in compute size- // as downgrading back to free will bring the project back to micro- const currentComputeSize = subscription?.addons.find((option) =>- option.supabase_prod_id.includes('addon_instance')- )- const returnedAmount = (subscriptionPreview?.returned_credits_for_unused_time ?? 0) / 100- const billingDate = new Date((subscriptionPreview?.bill_on ?? 0) * 1000)-- useEffect(() => {- if (freeTier) {- getSubscriptionPreview()- }- }, [freeTier])-- 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 getDowngradeRefundMessage = () => {- return `A total of $${returnedAmount} will be refunded as credits on ${billingDate.toLocaleDateString(- 'en-US',- {- day: 'numeric',- month: 'long',- year: 'numeric',- }- )} to your balance for unused time on your resources. Do let us know if you have any other feedback at [email protected].`- }-- const getSubscriptionPreview = async () => {- const proration_date = Math.floor(Date.now() / 1000)- const preview = await post(`${API_URL}/projects/${projectRef}/subscription/preview`, {- tier: freeTier.prices[0].id,- addons: [],- proration_date,- })- setSubscriptionPreview(preview)- }-- const onSubmit = async (values: any) => {- if (selectedReasons.length === 0) {- return ui.setNotification({- category: 'error',- message: 'Please select at least one reason for cancelling your subscription',- })- }-- setIsSubmitting(true)- let token = captchaToken-- try {- if (!token) {- const captchaResponse = await captchaRef.current?.execute({ async: true })- token = captchaResponse?.response ?? null- }- } catch (error) {- setIsSubmitting(false)- return- }-- if (currentComputeSize !== undefined) {- setMessage(values.message)- return setShowConfirmModal(true)- } else {- downgradeProject(values)- }- }-- const resetCaptcha = () => {- setCaptchaToken(null)- captchaRef.current?.resetCaptcha()- }-- const downgradeProject = async (values?: any) => {- const downgradeMessage = values?.message ?? message-- try {- setIsSubmitting(true)- setIsSubmittingDowngradeModal(true)-- // Trigger subscription downgrade- const tier = freeTier.prices[0].id- const addons: string[] = []- const proration_date = Math.floor(Date.now() / 1000)- const res = await patch(`${API_URL}/projects/${projectRef}/subscription`, {- tier,- addons,- proration_date,- })-- resetCaptcha()-- if (res?.error) {- return ui.setNotification({- category: 'error',- message: `Failed to cancel subscription: ${res?.error?.message}`,- error: res.error,- })- } else {- if (currentComputeSize !== undefined) {- app.onProjectStatusUpdated(projectId, PROJECT_STATUS.RESTORING)- ui.setNotification({- category: 'info',- message: getDowngradeRefundMessage(),- duration: 8000,- })- ui.setNotification({- category: 'success',- message:- 'Your project has been updated and is currently restarting to update its instance size',- duration: 8000,- })- router.push(`/project/${projectRef}`)- } else {- setIsSuccessful(true)- }-- await Promise.all([- queryClient.invalidateQueries(subscriptionKeys.subscriptionV2(projectRef)),- queryClient.invalidateQueries(subscriptionKeys.subscription(projectRef)),- queryClient.invalidateQueries(subscriptionKeys.addons(projectRef)),- ])- }- const feedbackRes = await post(`${API_URL}/feedback/downgrade`, {- projectRef,- reasons: selectedReasons.reduce((a, b) => `${a}- ${b}\n`, ''),- additionalFeedback: downgradeMessage,- exitAction: 'downgrade',- })- if (feedbackRes.error) throw feedbackRes.error- } catch (error: any) {- ui.setNotification({- category: 'error',- message: `Failed to cancel subscription: ${error.message}`,- })- } finally {- setIsSubmitting(false)- setIsSubmittingDowngradeModal(false)- }- }-- if (isSuccessful) {- return (- <UpdateSuccess- projectRef={projectRef || ''}- title="Your project has been updated"- message={getDowngradeRefundMessage()}- />- )- }-- return (- <>- <Transition- show- appear- enter="transition ease-out duration-300"- enterFrom="transform opacity-0 translate-x-10"- enterTo="transform opacity-100 translate-x-0"- >- <div className="w-full xl:w-4/5 space-y-8">- <div ref={formRef} className="relative">- <div className="absolute top-[2px] -left-24">- <Button type="text" icon={<IconArrowLeft />} onClick={onSelectBack}>- Back- </Button>- </div>- <div className="space-y-1">- <h4 className="text-lg">We're sad that you're leaving.</h4>- <p className="text-scale-1100">- We always strive to improve Supabase as much as we can. Please let us know the- reasons you are cancelling your subscription so that we can improve in the future.- </p>- </div>- <Form validateOnBlur initialValues={initialValues} onSubmit={onSubmit}>- {() => (- <div className="space-y-8 py-8">- <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>- <Input.TextArea- id="message"- name="message"- label="Anything else that we can improve on?"- />- <div className="flex items-center justify-between">- <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- htmlType="button"- type="default"- onClick={() =>- router.push(`/project/${projectRef}/settings/billing/update`)- }- >- Cancel- </Button>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger className="w-full">- <Button- type="danger"- htmlType="submit"- loading={isSubmitting}- disabled={projectUpdateDisabled || isSubmitting}- >- Confirm downgrade- </Button>- </Tooltip.Trigger>- {projectUpdateDisabled ? (- <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">- Subscription changes are currently disabled. Our engineers are- working on a fix.- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- ) : null}- </Tooltip.Root>- </div>- </div>- <div className="self-center">- <HCaptcha- ref={captchaRef}- sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY!}- size="invisible"- onVerify={(token) => {- setCaptchaToken(token)- }}- onExpire={() => {- setCaptchaToken(null)- }}- />- </div>- </div>- )}- </Form>- </div>- </div>- </Transition>- <Modal- hideFooter- visible={showConfirmModal}- size="large"- header="Downgrading project to free"- onCancel={() => {- setShowConfirmModal(false)- setIsSubmitting(false)- }}- >- <div className="space-y-4 py-4">- <Modal.Content>- <Alert- withIcon- variant="warning"- title="Your project will need to be restarted for changes to take place"- >- Your project is currently using a{' '}- {(currentComputeSize?.name ?? '').toLocaleLowerCase()} and will be downgraded to a- micro add-on. Upon confirmation, your project will be restarted for changes to take- place. This will take up to 2 minutes during which your project will be unavailable.- </Alert>- </Modal.Content>- <Modal.Content>- <p className="text-sm text-scale-1200">Would you like to update your project now?</p>- </Modal.Content>- <Modal.Separator />- <Modal.Content>- <div className="flex items-center gap-2">- <Button- block- type="default"- onClick={() => {- setShowConfirmModal(false)- setIsSubmitting(false)- }}- >- Cancel- </Button>- <Button- block- htmlType="submit"- loading={isSubmittingDowngradeModal}- disabled={isSubmittingDowngradeModal}- onClick={() => downgradeProject()}- >- Confirm- </Button>- </div>- </Modal.Content>- </div>- </Modal>- </>- )-}--export default ExitSurveydiff --git a/studio/components/interfaces/Billing/PaymentSummaryPanel/ConfirmPaymentModal.tsx b/studio/components/interfaces/Billing/PaymentSummaryPanel/ConfirmPaymentModal.tsxdeleted file mode 100644index 978b141a4d4..00000000000--- a/studio/components/interfaces/Billing/PaymentSummaryPanel/ConfirmPaymentModal.tsx+++ /dev/null@@ -1,85 +0,0 @@-import { FC } from 'react'-import { Alert, Button, Modal } from 'ui'--interface Props {- visible: boolean- isSubmitting: boolean- isChangingInstanceSize: boolean- isDisablingPITR: boolean- onCancel: () => void- onConfirm: () => void-}--const warnings = {- changingInstanceSize: {},-}--const ConfirmPaymentModal: FC<Props> = ({- visible,- isSubmitting,- isChangingInstanceSize,- isDisablingPITR,- onCancel,- onConfirm,-}) => {- return (- <Modal- hideFooter- visible={visible}- size="large"- header="Confirm changes to your project's subscription"- onCancel={onCancel}- >- <div className="space-y-4 py-4">- <Modal.Content>- <div className="space-y-2">- {isChangingInstanceSize && (- <Alert- withIcon- variant="warning"- title="Your project will need to be restarted for size changes to take place"- >- Upon confirmation, your project will be restarted to change your instance size. This- will take up to 2 minutes in which your project will be unavailable during the time.- </Alert>- )}- {isDisablingPITR && (- <Alert- withIcon- variant="warning"- title="All available PITR back ups for your project will be removed and are non-recoverable"- >- As such, your project will not have past PITR backups if you were to re-enable PITR- for your project.- </Alert>- )}- </div>- </Modal.Content>- <Modal.Content>- <p className="text-sm text-scale-1200">- Confirm the changes to your project's subscription?- </p>- </Modal.Content>- <Modal.Separator />- <Modal.Content>- <div className="flex items-center gap-2">- <Button block type="default" onClick={onCancel}>- Cancel- </Button>- <Button- block- type="primary"- loading={isSubmitting}- disabled={isSubmitting}- onClick={onConfirm}- >- Confirm- </Button>- </div>- </Modal.Content>- </div>- </Modal>- )-}--export default ConfirmPaymentModaldiff --git a/studio/components/interfaces/Billing/PaymentSummaryPanel/CostBreakdownModal.tsx b/studio/components/interfaces/Billing/PaymentSummaryPanel/CostBreakdownModal.tsxdeleted file mode 100644index 4a965db7126..00000000000--- a/studio/components/interfaces/Billing/PaymentSummaryPanel/CostBreakdownModal.tsx+++ /dev/null@@ -1,108 +0,0 @@-import { FC } from 'react'-import { groupBy } from 'lodash'-import { Modal } from 'ui'--interface Props {- visible: boolean- totalDue: number- billingDate: Date- costBreakdown: any[]- onCancel: () => void-}--const CostBreakdownModal: FC<Props> = ({- visible,- totalDue,- billingDate,- costBreakdown,- onCancel,-}) => {- const groupedBreakdown = groupBy(costBreakdown, 'period.start')-- return (- <Modal- hideFooter- visible={visible}- size="xlarge"- header="Cost breakdown details"- onCancel={onCancel}- >- <div className="space-y-2 py-4">- <Modal.Content>- <p className="text-sm">- The following shows the cost breakdown of the invoice that will be billed on{' '}- {billingDate.toLocaleDateString('en-US', {- day: 'numeric',- month: 'long',- year: 'numeric',- })}- .- </p>- </Modal.Content>- <Modal.Content>- <div className="rounded border border-scale-600 bg-scale-500">- <div className="flex items-center border-b border-scale-600 py-2 px-4">- <div className="w-[75%] text-xs">Description</div>- <div className="w-[10%] text-right text-xs">Qty</div>- <div className="w-[15%] text-right text-xs">Amount</div>- </div>- {Object.keys(groupedBreakdown).map((startPeriod: any, idx: number) => {- const start = new Date(Number(startPeriod) * 1000).toLocaleDateString('en-US', {- day: 'numeric',- month: 'long',- year: 'numeric',- })- const end = new Date(- groupedBreakdown[startPeriod][0].period.end * 1000- ).toLocaleDateString('en-US', {- day: 'numeric',- month: 'long',- year: 'numeric',- })- return (- <div key={`breakdown-${idx}`} className="border-b border-scale-600">- <div className="flex items-center py-2 px-4 ">- <div className="w-full text-xs text-scale-1100">- {start} - {end}- </div>- </div>- {groupedBreakdown[startPeriod].map((item: any, index: number) => {- return (- <div key={`breakdown-row-${index}`} className="flex items-center py-2 px-4">- <div className="w-[75%] text-sm">{item.description}</div>- <div className="w-[10%] text-right text-sm">{item.quantity}</div>- <div className="w-[15%] text-right text-sm">- ${(item.amount / 100).toFixed(2)}- </div>- </div>- )- })}- </div>- )- })}- <div className="flex flex-col space-y-1 py-2 px-4">- <div className="flex items-center">- <div className="w-[75%] text-sm">Total amount</div>- <div className="w-[10%] text-right text-sm"></div>- <div className="w-[15%] text-right text-xl">- ${totalDue < 0 ? 0 : totalDue.toFixed(2)}- </div>- </div>- {totalDue < 0 && (- <div className="flex items-center text-scale-1100">- <div className="w-[75%] text-sm">- Amount returned as credits for unused resources- </div>- <div className="w-[10%] text-right text-sm"></div>- <div className="w-[15%] text-right text-sm">${Math.abs(totalDue).toFixed(2)}</div>- </div>- )}- </div>- </div>- </Modal.Content>- </div>- </Modal>- )-}--export default CostBreakdownModaldiff --git a/studio/components/interfaces/Billing/PaymentSummaryPanel/PaymentSummaryPanel.tsx b/studio/components/interfaces/Billing/PaymentSummaryPanel/PaymentSummaryPanel.tsxdeleted file mode 100644index 3d4e4de4af5..00000000000--- a/studio/components/interfaces/Billing/PaymentSummaryPanel/PaymentSummaryPanel.tsx+++ /dev/null@@ -1,508 +0,0 @@-import { useState } from 'react'-import * as Tooltip from '@radix-ui/react-tooltip'-import { Listbox, IconLoader, Button, IconPlus, IconAlertCircle, IconCreditCard } from 'ui'-import { PermissionAction } from '@supabase/shared-types/out/constants'--import { checkPermissions, useFlag, useStore } from 'hooks'-import { BASE_PATH, PRICING_TIER_PRODUCT_IDS, STRIPE_PRODUCT_IDS } from 'lib/constants'-import { SubscriptionPreview } from '../Billing.types'-import { getProductPrice, validateSubscriptionUpdatePayload } from '../Billing.utils'-import PaymentTotal from './PaymentTotal'-import InformationBox from 'components/ui/InformationBox'-import { AddonPrice, SubscriptionAddon } from '../AddOns/AddOns.types'-import { getPITRDays } from './PaymentSummaryPanel.utils'-import ConfirmPaymentModal from './ConfirmPaymentModal'-import { StripeSubscription } from '../Subscription/Subscription.types'-import { useIsProjectActive } from 'components/layouts/ProjectLayout/ProjectContext'-import clsx from 'clsx'--// [Joshen] PITR stuff can be undefined for now until we officially launch PITR self serve--interface PaymentSummaryPanelProps {- isRefreshingPreview: boolean- currentSubscription?: StripeSubscription- subscriptionPreview?: SubscriptionPreview-- currentPlan: any- currentAddons: {- computeSize: SubscriptionAddon- pitrDuration: SubscriptionAddon- customDomains: SubscriptionAddon- supportPlan?: SubscriptionAddon- }-- selectedPlan?: any- selectedAddons: {- computeSize: SubscriptionAddon- pitrDuration: SubscriptionAddon- customDomains: SubscriptionAddon- }-- isSpendCapEnabled: boolean- paymentMethods?: any- selectedPaymentMethod: any- isLoadingPaymentMethods: boolean- onSelectPaymentMethod: (method: any) => void- onSelectAddNewPaymentMethod: () => void- beforeConfirmPayment: () => Promise<boolean>- onConfirmPayment: () => void- isSubmitting: boolean-- captcha: React.ReactNode-}--// Use case of this panel is actually only for upgrading from Free to Pro-// OR managing Pro configuration. For simplicity, we code this component-// within this boundary--// [Joshen] Eventually if we do support more addons, it'll be better to generalize-// the selectedComputeSize to an addOns array. But for now, we keep it simple, don't over-engineer too early--const PaymentSummaryPanel = ({- isRefreshingPreview,- isSpendCapEnabled,- currentSubscription,- subscriptionPreview,-- currentPlan,- currentAddons,-- selectedPlan,- selectedAddons,-- paymentMethods,- selectedPaymentMethod,- isLoadingPaymentMethods,- onSelectPaymentMethod,- onSelectAddNewPaymentMethod,- beforeConfirmPayment,- onConfirmPayment,- isSubmitting,- captcha,-}: PaymentSummaryPanelProps) => {- const { ui } = useStore()- const isActive = useIsProjectActive()- const projectRegion = ui.selectedProject?.region-- // [Joshen] Point of refactor: Current plan can just be currentSubscription.tier- // Reduce one unnecessary prop-- const canUpdatePaymentMethods = checkPermissions(- PermissionAction.BILLING_WRITE,- 'stripe.payment_methods'- )-- const [showConfirmModal, setShowConfirmModal] = useState(false)- const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')-- const selectedPlanCost =- selectedPlan !== undefined- ? selectedPlan.prices.find(- (price: AddonPrice) => price.id === selectedPlan.metadata.default_price_id- )?.unit_amount ?? 0- : currentSubscription?.tier.unit_amount ?? 0-- const totalSelectedAddonCost = Object.keys(selectedAddons)- .map((productName) => {- const product = (selectedAddons as any)[productName]- const price = product.prices.find(- (price: AddonPrice) => price.id === product.metadata.default_price_id- )- return price- })- .reduce((a, b) => a + b.unit_amount, 0)- const totalMonthlyCost = selectedPlanCost + totalSelectedAddonCost-- const currentPITRDays =- currentAddons.pitrDuration !== undefined ? getPITRDays(currentAddons.pitrDuration) : 0- const selectedPITRDays =- selectedAddons.pitrDuration !== undefined ? getPITRDays(selectedAddons.pitrDuration) : 0-- const isEnterprise = currentPlan.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.ENTERPRISE- const isChangingPlan =- (currentPlan.prod_id !== STRIPE_PRODUCT_IDS.PAYG &&- selectedPlan &&- currentPlan.prod_id !== selectedPlan.id) ||- (currentPlan.prod_id !== STRIPE_PRODUCT_IDS.PAYG && !isSpendCapEnabled) ||- (currentPlan.prod_id === STRIPE_PRODUCT_IDS.PAYG && isSpendCapEnabled)- const isChangingComputeSize = currentAddons.computeSize.id !== selectedAddons.computeSize.id- const isChangingPITRDuration = currentAddons.pitrDuration?.id !== selectedAddons.pitrDuration?.id- const isChangingCustomDomains =- currentAddons.customDomains?.id !== selectedAddons.customDomains?.id-- const togglingOnSpendCap =- currentPlan.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.PAYG &&- selectedPlan &&- selectedPlan.metadata.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.PRO-- // If it's enterprise we only only changing of add-ons- const hasChangesToPlan = isEnterprise- ? isChangingComputeSize || isChangingPITRDuration- : subscriptionPreview?.has_changes ?? false-- const getPlanName = (plan: any) => {- if (plan.prod_id === STRIPE_PRODUCT_IDS.PAYG || plan.id === STRIPE_PRODUCT_IDS.PAYG) {- return 'Pro plan (No spend caps)'- } else return plan.name- }-- const getAddonPriceFromSubscription = (- key: 'computeSize' | 'pitrDuration' | 'customDomains' | 'supportPlan'- ) => {- return (- ((currentSubscription?.addons ?? []).find((addon) => addon.prod_id === currentAddons[key]?.id)- ?.unit_amount ?? 0) / 100- ).toFixed(2)- }-- const validateOrder = async () => {- const error = validateSubscriptionUpdatePayload(selectedAddons)- if (error) {- return ui.setNotification({- duration: 4000,- category: 'error',- message: error,- })- } else {- // [Joshen] We're validating captcha before subsequent actions as there's an issue- // with the hcaptcha overlay and the modal component, such that clicking on the hcaptcha closes- // both the hcaptcha overlay and the modal. Need to figure that out first, then we can validate- // the hcaptcha within onConfirmPayment()- const hasValidCaptcha = await beforeConfirmPayment()- if (hasValidCaptcha) {- isChangingComputeSize || (isChangingPITRDuration && selectedPITRDays === 0)- ? setShowConfirmModal(true)- : onConfirmPayment()- }- }- }-- return (- <>- <div- className={clsx(- 'bg-panel-body-light dark:bg-panel-body-dark overflow-y-auto border-l',- 'px-6 lg:px-12 py-10 space-y-8',- 'min-w-[450px] max-w-[450px] 2xl:min-w-[630px] 2xl:max-w-[630px]'- )}- style={{ height: 'calc(100vh - 57px)' }}- >- <p>Payment Summary</p>-- {/* Subscription details */}- <div className="space-y-1">- <p className="text-sm text-scale-1100">Selected subscription</p>- <div className="flex items-center justify-between">- <p className={`${isChangingPlan ? 'text-scale-1100 line-through' : ''} text-sm`}>- {getPlanName(currentPlan)}- </p>- <p className={`${isChangingPlan ? 'text-scale-1100 line-through' : ''} text-sm`}>- ${(currentPlan.unit_amount / 100).toFixed(2)}- </p>- </div>- {isChangingPlan && (- <div className="flex items-center justify-between">- <p className="text-sm">{getPlanName(selectedPlan)}</p>- <p className="text-sm">- ${(getProductPrice(selectedPlan).unit_amount / 100).toFixed(2)}- </p>- </div>- )}- </div>-- {/* Add on details */}- {projectRegion !== 'af-south-1' && (- <div className="space-y-1">- <p className="text-sm text-scale-1100">Selected add-ons</p>-- {/* Compute size */}- <div className="flex items-center justify-between">- <p- className={`${isChangingComputeSize ? 'text-scale-1100 line-through' : ''} text-sm`}- >- {currentAddons.computeSize.name}- </p>- <p- className={`${isChangingComputeSize ? 'text-scale-1100 line-through' : ''} text-sm`}- >- ${getAddonPriceFromSubscription('computeSize')}- </p>- </div>- {isChangingComputeSize && (- <div className="flex items-center justify-between">- <p className="text-sm">{selectedAddons.computeSize.name}</p>- <p className="text-sm">- ${(getProductPrice(selectedAddons.computeSize).unit_amount / 100).toFixed(2)}- </p>- </div>- )}-- {/* PITR Duration */}- {currentAddons.pitrDuration?.id !== undefined && (- <div className="flex items-center justify-between">- <p- className={`${- isChangingPITRDuration ? 'text-scale-1100 line-through' : ''- } text-sm`}- >- {currentAddons.pitrDuration?.name}- </p>- <p- className={`${- isChangingPITRDuration ? 'text-scale-1100 line-through' : ''- } text-sm`}- >- ${getAddonPriceFromSubscription('pitrDuration')}- </p>- </div>- )}- {isChangingPITRDuration && (- <div className="flex items-center justify-between">- <p className="text-sm">{selectedAddons.pitrDuration?.name}</p>- <p className="text-sm">- ${(getProductPrice(selectedAddons.pitrDuration).unit_amount / 100).toFixed(2)}- </p>- </div>- )}-- {/* Custom Domains */}- {currentAddons.customDomains?.id !== undefined && (- <div className="flex items-center justify-between">- <p- className={`${- isChangingCustomDomains ? 'text-scale-1100 line-through' : ''- } text-sm`}- >- {currentAddons.customDomains?.name}- </p>- <p- className={`${- isChangingCustomDomains ? 'text-scale-1100 line-through' : ''- } text-sm`}- >- ${getAddonPriceFromSubscription('customDomains')}- </p>- </div>- )}- {isChangingCustomDomains && (- <div className="flex items-center justify-between">- <p className="text-sm">{selectedAddons.customDomains?.name}</p>- <p className="text-sm">- ${(getProductPrice(selectedAddons.customDomains).unit_amount / 100).toFixed(2)}- </p>- </div>- )}-- {/* Support Plan */}- {currentAddons.supportPlan !== undefined && (- <div className="flex items-center justify-between">- <p className="text-sm">{currentAddons.supportPlan?.name}</p>- <p className="text-sm">${getAddonPriceFromSubscription('supportPlan')}</p>- </div>- )}-- {/* Show information boxes with regards to change in subscriptions */}- <div className="!mt-4 space-y-4">- {isChangingPITRDuration && (- <InformationBox- hideCollapse- defaultVisibility- icon={<IconAlertCircle strokeWidth={2} />}- title={- currentAddons.pitrDuration?.id === undefined- ? 'Enabling PITR'- : selectedAddons.pitrDuration?.id === undefined- ? 'Disabling PITR'- : 'Updating PITR duration'- }- description={- selectedPITRDays >= currentPITRDays- ? `The days for which PITR is available for will only start at the time of enabling the add-on (e.g You will have access to the full ${selectedPITRDays} days of PITR after ${- selectedPITRDays - currentPITRDays- } days from today)`- : selectedPITRDays === 0- ? 'All available PITR back ups for your project will be removed and are non-recoverable'- : `Only the latest ${selectedPITRDays} days of PITR from today will be retained (all backups that are later than ${selectedPITRDays} days will be removed and are non-recoverable)`- }- />- )}- {isChangingComputeSize && (- <InformationBox- hideCollapse- defaultVisibility- icon={<IconAlertCircle strokeWidth={2} />}- title="Changing your compute size"- description="It will take up to 2 minutes for changes to take place, and your project will be unavailable during that time"- />- )}-- {togglingOnSpendCap && (- <InformationBox- hideCollapse- defaultVisibility- icon={<IconAlertCircle strokeWidth={2} />}- title="Enabling spend cap"- description="Exceeding your plan's quota will result in service restrictions. With the spend cap disabled, you'll be charged for usage beyond the quota."- />- )}- </div>- </div>- )}-- <div className="w-full h-px bg-scale-600" />-- <PaymentTotal- totalMonthlyCost={totalMonthlyCost / 100}- subscriptionPreview={subscriptionPreview}- isRefreshingPreview={isRefreshingPreview}- isSpendCapEnabled={isSpendCapEnabled}- />-- {/* Payment method selection */}- <div className="space-y-2">- <p className="text-sm">Select payment method</p>- {isLoadingPaymentMethods ? (- <div className="flex items-center px-4 py-2 space-x-4 border rounded-md border-scale-700 bg-scale-400">- <IconLoader className="animate-spin" size={14} />- <p className="text-sm text-scale-1100">Retrieving payment methods</p>- </div>- ) : paymentMethods.length === 0 ? (- <div className="flex items-center justify-between px-4 py-2 border border-dashed rounded-md bg-scale-100">- <div className="flex items-center space-x-4 text-scale-1100">- <IconAlertCircle size={16} strokeWidth={1.5} />- <p className="text-sm">No saved payment methods</p>- </div>-- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger>- <Button- type="default"- disabled={!canUpdatePaymentMethods}- icon={<IconCreditCard />}- onClick={onSelectAddNewPaymentMethod}- >- Add new- </Button>- </Tooltip.Trigger>- {!canUpdatePaymentMethods && (- <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', // background- 'w-48 border border-scale-200 text-center', //border- ].join(' ')}- >- <span className="text-xs text-scale-1200">- You need additional permissions to add new payment methods to this- organization- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>- </div>- ) : (- <Listbox value={selectedPaymentMethod?.id} onChange={onSelectPaymentMethod}>- {paymentMethods.map((method: any) => {- const label = `•••• •••• •••• ${method.card.last4}`- return (- <Listbox.Option- key={method.id}- label={label}- value={method.id}- addOnBefore={() => {- return (- <img- src={`${BASE_PATH}/img/payment-methods/${method.card.brand- .replace(' ', '-')- .toLowerCase()}.png`}- width="32"- />- )- }}- >- <div>{label}</div>- </Listbox.Option>- )- })}- <div- className="flex items-center px-3 py-2 space-x-2 transition cursor-pointer group hover:bg-scale-500"- onClick={onSelectAddNewPaymentMethod}- >- <IconPlus size={16} />- <p className="transition text-scale-1000 group-hover:text-scale-1200">- Add new payment method- </p>- </div>- </Listbox>- )}- </div>-- <div className="self-center">{captcha}</div>-- <div className="flex items-center justify-end">- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger className="w-full">- <Button- block- type="primary"- size="medium"- loading={isSubmitting}- disabled={- !isActive ||- projectUpdateDisabled ||- isSubmitting ||- isLoadingPaymentMethods ||- !hasChangesToPlan ||- !selectedPaymentMethod- }- onClick={() => validateOrder()}- >- Confirm payment- </Button>- </Tooltip.Trigger>- {!hasChangesToPlan || !selectedPaymentMethod || !isActive ? (- <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">- {!hasChangesToPlan- ? 'No changes made to your subscription'- : !selectedPaymentMethod- ? 'Please select a payment method'- : !isActive- ? 'Unable to update subscription as project is not active'- : projectUpdateDisabled- ? 'Subscription changes are currently disabled. Our engineers are working on a fix.'- : ''}- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- ) : null}- </Tooltip.Root>- </div>- </div>-- <ConfirmPaymentModal- visible={showConfirmModal}- isChangingInstanceSize={isChangingComputeSize}- isDisablingPITR={isChangingPITRDuration && selectedPITRDays === 0}- isSubmitting={isSubmitting}- onCancel={() => setShowConfirmModal(false)}- onConfirm={() => onConfirmPayment()}- />- </>- )-}--export default PaymentSummaryPaneldiff --git a/studio/components/interfaces/Billing/PaymentSummaryPanel/PaymentSummaryPanel.utils.ts b/studio/components/interfaces/Billing/PaymentSummaryPanel/PaymentSummaryPanel.utils.tsdeleted file mode 100644index dab0fd5c88f..00000000000--- a/studio/components/interfaces/Billing/PaymentSummaryPanel/PaymentSummaryPanel.utils.ts+++ /dev/null@@ -1,7 +0,0 @@-import { SubscriptionAddon } from '../AddOns/AddOns.types'--export const getPITRDays = (pitrAddon: SubscriptionAddon) => {- const prodId = pitrAddon.metadata.supabase_prod_id- const daysString = prodId.split('_')[2]- return Number(daysString.split('days')[0])-}diff --git a/studio/components/interfaces/Billing/PaymentSummaryPanel/PaymentTotal.tsx b/studio/components/interfaces/Billing/PaymentSummaryPanel/PaymentTotal.tsxdeleted file mode 100644index f0b1200e7f4..00000000000--- a/studio/components/interfaces/Billing/PaymentSummaryPanel/PaymentTotal.tsx+++ /dev/null@@ -1,137 +0,0 @@-import { FC, useState } from 'react'-import { Loading, IconHelpCircle, Button } from 'ui'-import * as Tooltip from '@radix-ui/react-tooltip'-import { SubscriptionPreview } from '../Billing.types'-import CostBreakdownModal from './CostBreakdownModal'--interface Props {- totalMonthlyCost: number- subscriptionPreview?: SubscriptionPreview- isRefreshingPreview: boolean- isSpendCapEnabled: boolean-}--const PaymentTotal: FC<Props> = ({- totalMonthlyCost,- subscriptionPreview,- isRefreshingPreview,- isSpendCapEnabled,-}) => {- const hasChanges = subscriptionPreview?.has_changes ?? false- // const totalMonthlyCost = (subscriptionPreview?.base_amount_due_next_billing_cycle ?? 0) / 100- const amountDueImmediately = (subscriptionPreview?.amount_due_immediately ?? 0) / 100- const billingDate = new Date((subscriptionPreview?.bill_on ?? 0) * 1000)- const isBillingToday =- new Date().toLocaleDateString('en-US', {- day: 'numeric',- month: 'long',- year: 'numeric',- }) ===- billingDate.toLocaleDateString('en-US', {- day: 'numeric',- month: 'long',- year: 'numeric',- })-- const [showCostBreakdown, setShowCostBreakdown] = useState(false)-- return (- <>- {/* Payment total */}- <Loading active={isRefreshingPreview}>- <div className="mb-2 space-y-4">- <div className="flex items-start justify-between space-x-12">- <div className="">- <div className="flex items-center space-x-2">- <p>Total amount due</p>- {hasChanges && (- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger>- <IconHelpCircle- size={16}- strokeWidth={1.5}- className="cursor-pointer opacity-50 transition hover:opacity-100"- onClick={() => setShowCostBreakdown(true)}- />- </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', // background- 'border border-scale-200 ', //border- ].join(' ')}- >- <span className="text-xs text-scale-1200">How is this calculated?</span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- </Tooltip.Root>- )}- </div>- {hasChanges ? (- <div className="space-y-2">- {amountDueImmediately < 0 ? (- <p className="text-sm text-scale-1100">- A total of ${Math.abs(amountDueImmediately).toFixed(2)} will be returned as- credits on{' '}- <span className="text-brand-900">- {billingDate.toLocaleDateString('en-US', {- day: 'numeric',- month: 'long',- year: 'numeric',- })}- </span>{' '}- for unused resources.- </p>- ) : (- <p className="text-sm text-scale-1100">- This amount {!isSpendCapEnabled && !isBillingToday && '+ usage fees '}will be- charged on{' '}- <span className="text-brand-900">- {billingDate.toLocaleDateString('en-US', {- day: 'numeric',- month: 'long',- year: 'numeric',- })}- </span>- .- </p>- )}- <p className="text-sm text-scale-1100">- You'll pay a monthly total of{' '}- <span className="text-scale-1200">- ${totalMonthlyCost} {!isSpendCapEnabled && '+ usage fees '}- </span>{' '}- for each subsequent billing cycle.- </p>- </div>- ) : (- <p className="text-sm text-scale-1100">No changes to current subscription</p>- )}- </div>- <div className="relative -top-[8px] flex items-end justify-end">- <p className="relative -top-[1px] text-scale-1100">$</p>- <p className="text-2xl">- {!hasChanges- ? '0.00'- : (amountDueImmediately < 0 ? 0 : amountDueImmediately).toFixed(2)}- </p>- </div>- </div>- </div>- </Loading>-- <CostBreakdownModal- visible={showCostBreakdown}- totalDue={amountDueImmediately}- billingDate={billingDate}- costBreakdown={subscriptionPreview?.cost_breakdown || []}- onCancel={() => setShowCostBreakdown(false)}- />- </>- )-}--export default PaymentTotaldiff --git a/studio/components/interfaces/Billing/PlanSelection/PlanSelection.tsx b/studio/components/interfaces/Billing/PlanSelection/PlanSelection.tsxdeleted file mode 100644index a063a545588..00000000000--- a/studio/components/interfaces/Billing/PlanSelection/PlanSelection.tsx+++ /dev/null@@ -1,70 +0,0 @@-import Link from 'next/link'-import { FC } from 'react'-import { Transition } from '@headlessui/react'--import PlanCard from './Plans/PlanCard'-import { formatTierOptions } from './PlanSelection.utils'-import { Button, IconExternalLink } from 'ui'-import PlanCardEnterprise from './Plans/PlanCardEnterprise'--interface Props {- visible: boolean- tiers: any[]- currentPlan?: any- onSelectPlan: (plan: any) => void-}--const PlanSelection: FC<Props> = ({ visible, tiers, currentPlan, onSelectPlan }) => {- const formattedTiers = formatTierOptions(tiers)-- const enterprisePlan = formattedTiers.find((it) => it.name === 'Enterprise')!-- return (- <Transition- show={visible}- enter="transition ease-out duration-300"- enterFrom="transform opacity-0 -translate-x-10"- enterTo="transform opacity-100 translate-x-0"- >- <div>- <h4 className="text-lg">Change your project's subscription</h4>- <div className={`grid py-8 grid-cols-1 gap-8 md:grid-cols-3`}>- {formattedTiers- .filter((it) => it.name !== 'Enterprise')- .map((plan) => {- return (- <PlanCard- key={plan.id}- plan={plan}- currentPlan={currentPlan}- onSelectPlan={() => onSelectPlan(plan)}- />- )- })}- </div>- <div>- <PlanCardEnterprise- plan={enterprisePlan}- currentPlan={currentPlan}- onSelectPlan={() => onSelectPlan(enterprisePlan)}- />- </div>- <div className="flex justify-center items-center mt-4">- <Link href="https://supabase.com/pricing">- <a target="_blank" rel="noreferrer">- <Button- type="link"- icon={<IconExternalLink size={14} strokeWidth={1.5} />}- className="text-sm text-scale-1000 hover:text-scale-1100 hover:bg-scale-400"- >- See detailed comparisons across plans- </Button>- </a>- </Link>- </div>- </div>- </Transition>- )-}--export default PlanSelectiondiff --git a/studio/components/interfaces/Billing/PlanSelection/PlanSelection.utils.ts b/studio/components/interfaces/Billing/PlanSelection/PlanSelection.utils.tsdeleted file mode 100644index 3f9b842ff7a..00000000000--- a/studio/components/interfaces/Billing/PlanSelection/PlanSelection.utils.ts+++ /dev/null@@ -1,26 +0,0 @@-import { STRIPE_PRODUCT_IDS } from 'lib/constants'--// On the UI, we hide PAYG, and add an Enterprise option-export const formatTierOptions = (tiers: any[]) => {- const enterpriseOption = {- id: 'Enterprise',- name: 'Enterprise',- description: 'For large-scale applications managing serious workloads',- metadata: {- features:- 'Point in time recovery\\nDesignated Support manager & SLAs\\nSSO / SAML + SOC2\\nCustom contracts & invoicing\\n24×7×365 premium enterprise support',- },- prices: [],- }-- // Fix the order of plans here- return (- tiers- .filter((tier: any) => tier.id === STRIPE_PRODUCT_IDS.FREE)- .concat(tiers.filter((tier: any) => tier.id === STRIPE_PRODUCT_IDS.PRO))- .concat(tiers.filter((tier: any) => tier.id === STRIPE_PRODUCT_IDS.TEAM))- .concat([enterpriseOption])- // Team plan might not be enabled yet, make sure to filter out null/undefined- .filter(Boolean)- )-}diff --git a/studio/components/interfaces/Billing/PlanSelection/Plans/PlanCTAButton.tsx b/studio/components/interfaces/Billing/PlanSelection/Plans/PlanCTAButton.tsxdeleted file mode 100644index 444084b9579..00000000000--- a/studio/components/interfaces/Billing/PlanSelection/Plans/PlanCTAButton.tsx+++ /dev/null@@ -1,163 +0,0 @@-import Link from 'next/link'-import { Button, IconLoader } from 'ui'-import * as Tooltip from '@radix-ui/react-tooltip'--import { useFlag } from 'hooks'-import { PRICING_TIER_PRODUCT_IDS, STRIPE_PRODUCT_IDS } from 'lib/constants'-import { StripeProduct } from 'components/interfaces/Billing'-import { useIsProjectActive } from 'components/layouts/ProjectLayout/ProjectContext'--interface PlanCTAButtonProps {- plan: any- currentPlan?: StripeProduct- onSelectPlan: (plan: any) => void-}--const PlanCTAButton = ({ plan, currentPlan, onSelectPlan }: PlanCTAButtonProps) => {- const isProjectActive = useIsProjectActive()- const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')-- const isTeamTier = currentPlan?.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.TEAM-- const getButtonType = (plan: any, currentPlan: any) => {- if (- currentPlan.supabase_prod_id !== PRICING_TIER_PRODUCT_IDS.ENTERPRISE &&- plan.name === 'Enterprise'- ) {- return 'default'- }-- if (['Free tier', 'Free plan'].includes(plan.name)) {- // Free is always default- return 'default'- } else if (currentPlan.prod_id === STRIPE_PRODUCT_IDS.FREE) {- // If the current plan is free, other plans are primary- return 'primary'- } else if (- currentPlan.prod_id === STRIPE_PRODUCT_IDS.TEAM &&- !['Team tier', 'Team plan'].includes(plan.name)- ) {- // Non-free plans are default (pro), when team plan is selected- return 'default'- }-- return 'primary'- }-- const getButtonText = (plan: any, currentPlan: StripeProduct) => {- if (plan.name === 'Enterprise') {- return 'Contact sales'- }- if (plan.id === STRIPE_PRODUCT_IDS.FREE) {- if (currentPlan.prod_id === STRIPE_PRODUCT_IDS.FREE) {- return 'Current plan'- } else {- return 'Downgrade to Free'- }- }- if (plan.id === STRIPE_PRODUCT_IDS.PRO) {- if (currentPlan.prod_id === STRIPE_PRODUCT_IDS.FREE) {- return 'Upgrade to Pro'- } else if (currentPlan.prod_id === STRIPE_PRODUCT_IDS.TEAM) {- return 'Downgrade to Pro'- } else if (- currentPlan.prod_id === STRIPE_PRODUCT_IDS.PRO ||- currentPlan.prod_id === STRIPE_PRODUCT_IDS.PAYG- ) {- return 'Edit plan configuration'- } else {- return 'Contact sales'- }- }-- if (plan.id === STRIPE_PRODUCT_IDS.TEAM && currentPlan.prod_id === STRIPE_PRODUCT_IDS.TEAM) {- return 'Edit plan configuration'- } else {- return 'Contact sales'- }- }-- if (!currentPlan)- return (- <div className="flex items-center justify-center">- <Button type="text">- <IconLoader size={18} className="animate-spin" />- </Button>- </div>- )-- const type = getButtonType(plan, currentPlan)- const ctaText = getButtonText(plan, currentPlan)- const disabled =- (!isProjectActive && plan.name !== 'Enterprise') ||- (isTeamTier && plan.name !== 'Enterprise' && !['Team tier', 'Team plan'].includes(plan.name)) ||- (plan.id === STRIPE_PRODUCT_IDS.FREE && currentPlan.prod_id === STRIPE_PRODUCT_IDS.FREE)-- if (plan.name === 'Enterprise') {- return (- <Link href="https://supabase.com/contact/enterprise">- <a>- <Button disabled={disabled} type={type} block>- {ctaText}- </Button>- </a>- </Link>- )- }-- if (!isTeamTier && plan.name === 'Team plan') {- return (- <Link href="https://forms.supabase.com/team">- <a>- <Button disabled={disabled} type={type} block>- {ctaText}- </Button>- </a>- </Link>- )- }-- return (- <div className="flex flex-col items-center justify-center space-y-2">- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger className="w-full">- <Button- block- type={type}- disabled={disabled || projectUpdateDisabled}- onClick={() => onSelectPlan(plan)}- >- {ctaText}- </Button>- </Tooltip.Trigger>- {((disabled && isTeamTier) || projectUpdateDisabled || !isProjectActive) && (- <Tooltip.Portal>- <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 w-[260px] flex items-center justify-center',- ].join(' ')}- >- <span className="text-xs text-scale-1200 text-center">- {projectUpdateDisabled- ? 'Subscription changes are currently disabled, our engineers are working on a fix'- : !isProjectActive- ? 'Unable to update subscription as project is not active'- : isTeamTier- ? "Unable to update subscription from Team tier. Please reach out to us via support if you'd like to change your plan"- : ''}- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- </Tooltip.Portal>- )}- </Tooltip.Root>- </div>- )-}--export default PlanCTAButtondiff --git a/studio/components/interfaces/Billing/PlanSelection/Plans/PlanCard.tsx b/studio/components/interfaces/Billing/PlanSelection/Plans/PlanCard.tsxdeleted file mode 100644index 74102beab90..00000000000--- a/studio/components/interfaces/Billing/PlanSelection/Plans/PlanCard.tsx+++ /dev/null@@ -1,107 +0,0 @@-import { STRIPE_PRODUCT_IDS } from 'lib/constants'-import { FC } from 'react'-import { IconCheck } from 'ui'--import PlanCTAButton from './PlanCTAButton'-import { PRICING_META } from './Plans.Constants'--interface Props {- plan: any- currentPlan: any- onSelectPlan: () => void-}--const PlanCard: FC<Props> = ({ plan, currentPlan, onSelectPlan }) => {- const planMeta = PRICING_META[plan.id]- const isCurrentPlan =- plan.id === currentPlan?.prod_id ||- (plan.id === STRIPE_PRODUCT_IDS.PRO && currentPlan?.prod_id === STRIPE_PRODUCT_IDS.PRO) ||- (plan.id === STRIPE_PRODUCT_IDS.PRO && currentPlan?.prod_id === STRIPE_PRODUCT_IDS.PAYG)-- return (- <div- className={['px-6 py-6 border rounded flex flex-col justify-between bg-scale-300'].join(' ')}- >- <div className={['space-y-8'].join(' ')}>- <div className={['space-y-4'].join(' ')}>- <div className="flex items-center space-x-2">- <p className={['text-brand-900 text-sm'].join(' ')}>{planMeta.name}</p>- {isCurrentPlan ? (- <div className="text-xs bg-scale-500 text-scale-1000 rounded px-2 py-0.5">- Current plan- </div>- ) : planMeta.new ? (- <div className="text-xs bg-brand-400 text-brand-900 rounded px-2 py-0.5">New</div>- ) : (- <></>- )}- </div>- <p className="text-sm text-scale-1100">{planMeta.description}</p>- <div className={['space-y-2', 'border-b border-t py-8'].join(' ')}>- {planMeta.priceMonthly !== undefined ? (- <>- <p className="text-sm text-scale-1000">Starting from</p>- <div className="space-y-1">- <p className="text-[3.4rem] leading-none">${planMeta.priceMonthly}</p>- <p className="text-sm text-scale-1000">{planMeta.priceUnit}</p>- </div>- <div className="text-xs bg-brand-400 text-brand-900 rounded px-2 py-0.5 w-fit">- {planMeta.warning}- </div>- </>- ) : (- <PlanCTAButton plan={plan} currentPlan={currentPlan} onSelectPlan={onSelectPlan} />- )}- </div>- </div>- <div className="space-y-4">- <p className="text-xs text-scale-1000">{planMeta.preface}</p>- <ul role="list">- {planMeta.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>- </div>-- <div className="space-y-4 !mt-20">- <div className="space-y-2">- <p className="text-xs text-scale-1000">{planMeta.scale}</p>-- {planMeta.name === 'Pro' && currentPlan?.prod_id === STRIPE_PRODUCT_IDS.PRO && (- <div>- <p className="text-sm text-scale-1100">- Need more? Turn off your spend cap to Pay As You Grow- </p>- <p className="text-xs text-scale-1000">- Additional fees apply for spend beyond the limits above- </p>{' '}- </div>- )}-- {planMeta.name === 'Pro' && currentPlan?.prod_id === STRIPE_PRODUCT_IDS.PAYG && (- <div>- <p className="text-sm text-scale-1100">Spend cap is currently disabled</p>- <p className="text-xs text-scale-1000">- You will be charged for usage beyond the plan limits- </p>{' '}- </div>- )}- </div>-- <PlanCTAButton plan={plan} currentPlan={currentPlan} onSelectPlan={onSelectPlan} />- </div>- </div>- )-}--export default PlanCarddiff --git a/studio/components/interfaces/Billing/PlanSelection/Plans/PlanCardEnterprise.tsx b/studio/components/interfaces/Billing/PlanSelection/Plans/PlanCardEnterprise.tsxdeleted file mode 100644index a586e9b6d27..00000000000--- a/studio/components/interfaces/Billing/PlanSelection/Plans/PlanCardEnterprise.tsx+++ /dev/null@@ -1,64 +0,0 @@-import { STRIPE_PRODUCT_IDS } from 'lib/constants'-import { FC } from 'react'-import { IconCheck } from 'ui'--import PlanCTAButton from './PlanCTAButton'-import { PRICING_META } from './Plans.Constants'--interface Props {- plan: any- currentPlan: any- onSelectPlan: () => void-}--const PlanCardEnterprise: FC<Props> = ({ plan, currentPlan, onSelectPlan }) => {- const planMeta = PRICING_META[plan.id]- const isCurrentPlan =- plan.id === currentPlan?.prod_id ||- (plan.id === STRIPE_PRODUCT_IDS.PRO && currentPlan?.prod_id === STRIPE_PRODUCT_IDS.PRO) ||- (plan.id === STRIPE_PRODUCT_IDS.PRO && currentPlan?.prod_id === STRIPE_PRODUCT_IDS.PAYG)-- return (- <div className="px-6 py-6 border rounded flex-col bg-scale-200 flex">- <div className="space-y-8">- <div className=" grid grid-cols-3 space-x-8">- <div className="space-y-4 pr-14">- <div className="flex items-center ">- <p className="text-brand-900 text-sm">{planMeta.name}</p>- {isCurrentPlan ? (- <div className="text-xs bg-scale-500 text-scale-1000 rounded px-2 py-0.5">- Current plan- </div>- ) : planMeta.new ? (- <div className="text-xs bg-brand-400 text-brand-900 rounded px-2 py-0.5">New</div>- ) : (- <></>- )}- </div>- <p className="text-sm text-scale-1100">{planMeta.description}</p>- <div className="space-y-2 border-t pb-6 lg:pt-6 xl:pt-0 xl:pb-6">- <PlanCTAButton plan={plan} currentPlan={currentPlan} onSelectPlan={onSelectPlan} />- </div>- </div>- <div className="space-y-4 lg:col-span-2">- <p className="text-xs text-scale-1000">{planMeta.preface}</p>- <ul role="list" className="text-xs text-scale-1000 md:grid md:grid-cols-2 md:gap-x-10">- {planMeta.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>- </div>- </div>- </div>- </div>- )-}--export default PlanCardEnterprisediff --git a/studio/components/interfaces/Billing/PlanSelection/Plans/Plans.Constants.ts b/studio/components/interfaces/Billing/PlanSelection/Plans/Plans.Constants.tsdeleted file mode 100644index 15f93675fc4..00000000000--- a/studio/components/interfaces/Billing/PlanSelection/Plans/Plans.Constants.ts+++ /dev/null@@ -1,90 +0,0 @@-import { STRIPE_PRODUCT_IDS } from 'lib/constants'--// This file will get deleted soon and superseded by components in BillingV2/*--export const PRICING_META = {- [STRIPE_PRODUCT_IDS.FREE]: {- id: 'tier_free',- new: false,- name: 'Free',- description: 'Perfect for passion projects & simple websites.',- priceMonthly: 0,- priceUnit: '/ month',- warning: 'Limit of 2 free projects',- preface: 'Get started with:',- features: [- 'Unlimited API requests',- 'Social OAuth providers',- 'Up to 500MB database space',- 'Up to 1GB file storage',- 'Up to 2GB bandwidth',- 'Up to 50MB file uploads',- 'Up to 50,000 monthly active users',- 'Up to 500K Edge Function invocations',- 'Up to 200 concurrent Realtime connections',- 'Up to 2 million Realtime messages',- '1-day log retention',- 'Community support',- ],- scale: 'Free projects are paused after 1 week of inactivity.',- },- [STRIPE_PRODUCT_IDS.PRO]: {- id: 'tier_pro',- new: false,- name: 'Pro',- description: 'For production applications with the option to scale.',- priceMonthly: 25,- priceUnit: '/ month',- warning: 'Usage-based plan',- preface: 'Everything in the Free plan, plus:',- features: [- 'No project pausing',- 'Daily backups stored for 7 days',- '8GB database space included',- '100GB file storage included',- '50GB bandwidth included',- '5GB file uploads included',- '100,000 monthly active users included',- '2M Edge Function invocations included',- '500 concurrent Realtime connections included',- '5 million Realtime messages included',- '7-day log retention',- 'Email support',- ],- },- [STRIPE_PRODUCT_IDS.TEAM]: {- id: 'tier_team',- new: true,- name: 'Team',- description: 'Collaborate with different permissions and access patterns.',- priceMonthly: 599,- priceUnit: '/ month',- warning: 'Usage-based plan',- preface: 'Everything in the Pro plan, plus:',- features: [- 'Additional Organization member roles',- 'Daily backups stored for 14 days',- 'Standardised Security Questionnaire',- 'SOC2',- 'SSO for Supabase Dashboard',- 'Priority email support & SLAs',- '28-day log retention',- ],- },- Enterprise: {- id: 'tier_enterprise',- new: false,- name: 'Enterprise',- href: '/contact/enterprise',- description: 'For large-scale applications managing serious workloads.',- priceMonthly: undefined,- features: [- `Designated Support manager & SLAs`,- `Enterprise OAuth providers`,- `SSO/SAML`,- `On-premise support`,- `24×7×365 premium enterprise support`,- `Private Slack channel`,- ],- },-}diff --git a/studio/components/interfaces/Billing/ProUpgrade.tsx b/studio/components/interfaces/Billing/ProUpgrade.tsxdeleted file mode 100644index 044fc420df8..00000000000--- a/studio/components/interfaces/Billing/ProUpgrade.tsx+++ /dev/null@@ -1,394 +0,0 @@-import { FC, useEffect, useRef, useState } from 'react'-import { Transition } from '@headlessui/react'-import { useRouter } from 'next/router'-import { IconHelpCircle, Toggle } from 'ui'--import { useStore } from 'hooks'-import { post, patch } from 'lib/common/fetch'-import { API_URL, PROJECT_STATUS } from 'lib/constants'-import { getURL } from 'lib/helpers'-import Divider from 'components/ui/Divider'-import {- PaymentSummaryPanel,- ComputeSizeSelection,- PITRDurationSelection,- CustomDomainSelection,- StripeSubscription,- AddNewPaymentMethodModal,-} from './'-import { STRIPE_PRODUCT_IDS } from 'lib/constants'-import UpdateSuccess from './UpdateSuccess'-import { PaymentMethod, SubscriptionPreview } from './Billing.types'-import { formSubscriptionUpdatePayload, getCurrentAddons } from './Billing.utils'-import { SubscriptionAddon } from './AddOns/AddOns.types'-import {- formatComputeSizes,- formatCustomDomainOptions,- formatPITROptions,-} from './AddOns/AddOns.utils'-import BackButton from 'components/ui/BackButton'-import SupportPlan from './AddOns/SupportPlan'-import HCaptcha from '@hcaptcha/react-hcaptcha'-import SpendCapModal from './SpendCapModal'-import { useQueryClient } from '@tanstack/react-query'-import { subscriptionKeys } from 'data/subscriptions/keys'--// Do not allow compute size changes for af-south-1--interface Props {- products: { tiers: any[]; addons: SubscriptionAddon[] }- paymentMethods?: PaymentMethod[]- currentSubscription: StripeSubscription- isLoadingPaymentMethods: boolean- onPaymentMethodAdded: () => void- onSelectBack: () => void-}--const ProUpgrade: FC<Props> = ({- products,- paymentMethods,- currentSubscription,- isLoadingPaymentMethods,- onSelectBack,- onPaymentMethodAdded,-}) => {- const { app, ui } = useStore()- const router = useRouter()- const queryClient = useQueryClient()-- const [captchaToken, setCaptchaToken] = useState<string | null>(null)- const captchaRef = useRef<HCaptcha>(null)-- const { addons } = products- const computeSizes = formatComputeSizes(addons)- const pitrDurationOptions = formatPITROptions(addons)- const customDomainOptions = formatCustomDomainOptions(addons)- const currentAddons = getCurrentAddons(currentSubscription, addons)-- const projectId = ui.selectedProject?.id ?? -1- const projectRef = ui.selectedProject?.ref- const projectRegion = ui.selectedProject?.region ?? ''-- const [isSpendCapEnabled, setIsSpendCapEnabled] = useState(- // If project is currently free, default to enabling spend caps- currentSubscription.tier.prod_id === STRIPE_PRODUCT_IDS.FREE ||- // Otherwise, Pro plan implies spend caps enabled- currentSubscription.tier.prod_id === STRIPE_PRODUCT_IDS.PRO- )-- const [isRefreshingPreview, setIsRefreshingPreview] = useState(false)- const [isSubmitting, setIsSubmitting] = useState(false)- const [isSuccessful, setIsSuccessful] = useState(false)- const [showAddPaymentMethodModal, setShowAddPaymentMethodModal] = useState(false)- const [showSpendCapHelperModal, setShowSpendCapHelperModal] = useState(false)-- // [Joshen TODO] Ideally we just have a state to hold all the add ons selection, rather than individual- // Even better if we can just use the <Form> component to handle all of these. Mainly to reduce the amount- // of unnecessary state management on this complex page.- const [selectedComputeSize, setSelectedComputeSize] = useState<SubscriptionAddon>(- currentAddons.computeSize- )- const [selectedPITRDuration, setSelectedPITRDuration] = useState<SubscriptionAddon>(- currentAddons.pitrDuration- )- const [selectedCustomDomainOption, setSelectedCustomDomainOption] = useState<SubscriptionAddon>(- currentAddons.customDomains- )-- // [Joshen TODO] Future - We may need to also include any add ons outside of- // compute size, pitr, custom domain and support plan, although we dont have any now- const nonChangeableAddons = [currentAddons.supportPlan].filter(- (x) => x !== undefined- ) as SubscriptionAddon[]-- // [Joshen] Scaffolded here- const selectedAddons = {- computeSize: selectedComputeSize,- pitrDuration: selectedPITRDuration,- customDomains: selectedCustomDomainOption,- }-- const [selectedPaymentMethodId, setSelectedPaymentMethodId] = useState<string>('')- const [subscriptionPreview, setSubscriptionPreview] = useState<SubscriptionPreview>()-- const selectedTier = isSpendCapEnabled- ? products?.tiers.find((tier: any) => tier.id === STRIPE_PRODUCT_IDS.PRO)- : products?.tiers.find((tier: any) => tier.id === STRIPE_PRODUCT_IDS.PAYG)-- const isManagingProSubscription =- currentSubscription.tier.prod_id === STRIPE_PRODUCT_IDS.PRO ||- currentSubscription.tier.prod_id === STRIPE_PRODUCT_IDS.PAYG-- const isChangingComputeSize = currentAddons.computeSize?.id !== selectedAddons.computeSize.id-- const onLocalPaymentMethodAdded = () => {- setShowAddPaymentMethodModal(false)- return onPaymentMethodAdded()- }-- useEffect(() => {- if (!isLoadingPaymentMethods && paymentMethods && paymentMethods.length > 0) {- setSelectedPaymentMethodId(paymentMethods[0].id)- }- }, [isLoadingPaymentMethods, paymentMethods])-- useEffect(() => {- getSubscriptionPreview()- }, [selectedComputeSize, selectedPITRDuration, selectedCustomDomainOption, isSpendCapEnabled])-- const getSubscriptionPreview = async () => {- if (!selectedTier) return-- const payload = formSubscriptionUpdatePayload(- currentSubscription,- selectedTier,- selectedAddons,- nonChangeableAddons,- selectedPaymentMethodId,- projectRegion- )-- setIsRefreshingPreview(true)- const preview = await post(`${API_URL}/projects/${projectRef}/subscription/preview`, payload)- if (preview.error) {- ui.setNotification({- category: 'error',- message: `Failed to fetch subscription preview: ${preview.error.message}`,- })- }- setSubscriptionPreview(preview)- setIsRefreshingPreview(false)- }-- const resetCaptcha = () => {- setCaptchaToken(null)- captchaRef.current?.resetCaptcha()- }-- const beforeConfirmPayment = async (): Promise<boolean> => {- setIsSubmitting(true)- let token = captchaToken-- try {- if (!token) {- const captchaResponse = await captchaRef.current?.execute({ async: true })- token = captchaResponse?.response ?? null- setCaptchaToken(token)- }- } catch (error) {- setIsSubmitting(false)- return false- }-- setIsSubmitting(false)- return true- }-- const onConfirmPayment = async () => {- setIsSubmitting(true)- const payload = formSubscriptionUpdatePayload(- currentSubscription,- selectedTier,- selectedAddons,- nonChangeableAddons,- selectedPaymentMethodId,- projectRegion- )- const res = await patch(`${API_URL}/projects/${projectRef}/subscription`, payload)- resetCaptcha()-- if (res?.error) {- ui.setNotification({- category: 'error',- message: `Failed to update subscription: ${res?.error?.message}`,- })- } else {- if (isChangingComputeSize) {- app.onProjectStatusUpdated(projectId, PROJECT_STATUS.RESTORING)- ui.setNotification({- category: 'success',- message:- 'Your project has been updated and is currently restarting to update its instance size',- duration: 8000,- })- router.push(`/project/${projectRef}`)- } else {- setIsSuccessful(true)- }-- await Promise.all([- queryClient.invalidateQueries(subscriptionKeys.subscriptionV2(projectRef)),- queryClient.invalidateQueries(subscriptionKeys.subscription(projectRef)),- queryClient.invalidateQueries(subscriptionKeys.addons(projectRef)),- ])- }- setIsSubmitting(false)- }-- if (!isSubmitting && isSuccessful) {- return (- <UpdateSuccess- projectRef={projectRef || ''}- title="Your project has been updated!"- message="Let us know if you have any feedback at [email protected]."- />- )- }-- return (- <>- <Transition- show- enter="transition ease-out duration-300"- enterFrom="transform opacity-0 translate-x-10"- enterTo="transform opacity-100 translate-x-0"- className="flex items-start justify-between w-full"- >- <div className="flex-grow mt-10">- <div className="relative space-y-4">- <div className="relative px-32 mx-auto space-y-4 2xl:max-w-5xl">- <BackButton onClick={() => onSelectBack()} />- <h4 className="text-lg text-scale-900 !mb-8">Change your project's subscription</h4>- </div>-- <div- className="px-32 pb-8 mx-auto space-y-8 overflow-y-auto 2xl:max-w-5xl"- style={{ height: 'calc(100vh - 9rem - 57px)' }}- >- <div className="space-y-2">- {!isManagingProSubscription ? (- <>- <h3 className="text-xl">- Welcome to <span className="text-brand-900">Pro</span>- </h3>- <p className="text-base text-scale-1100">- Your new subscription will begin immediately after payment- </p>- </>- ) : (- <>- <h3 className="text-3xl">- Managing your <span className="text-brand-900">Pro</span> plan- </h3>- {/* <p className="text-base text-scale-1100">- Your billing cycle will reset after payment- </p> */}- </>- )}- </div>- <div className="flex items-center justify-between gap-16 px-6 py-4 border rounded border-panel-border-light dark:border-panel-border-dark bg-panel-body-light drop-shadow-sm dark:bg-panel-body-dark">- <div>- <div className="flex items-center space-x-2">- <p>Spend cap</p>- <IconHelpCircle- size={16}- strokeWidth={1.5}- className="transition opacity-50 cursor-pointer hover:opacity-100"- onClick={() => setShowSpendCapHelperModal(true)}- />- </div>- <p className="text-sm text-scale-1100">- By default, Pro projects have a spend cap enabled to control costs and prevent- exceeding limits. This restricts usage upon exhausting the quota. To scale- without restrictions, disable the spend cap and be charged for overusage beyond- the quota.- </p>- </div>- <Toggle- checked={isSpendCapEnabled}- onChange={() => setIsSpendCapEnabled(!isSpendCapEnabled)}- />- </div>- {projectRegion !== 'af-south-1' && (- <>- {currentAddons.supportPlan !== undefined && (- <>- <Divider light />- <SupportPlan currentOption={currentAddons.supportPlan} />- </>- )}- <Divider light />- <CustomDomainSelection- options={customDomainOptions}- currentOption={- isManagingProSubscription ? currentAddons.customDomains : undefined- }- selectedOption={selectedAddons.customDomains}- onSelectOption={setSelectedCustomDomainOption}- />- <Divider light />- <PITRDurationSelection- pitrDurationOptions={pitrDurationOptions}- currentPitrDuration={- isManagingProSubscription ? currentAddons.pitrDuration : undefined- }- selectedPitrDuration={selectedAddons.pitrDuration}- onSelectOption={setSelectedPITRDuration}- />- <Divider light />- <ComputeSizeSelection- computeSizes={computeSizes || []}- currentComputeSize={currentAddons.computeSize}- selectedComputeSize={selectedAddons.computeSize}- onSelectOption={setSelectedComputeSize}- />- </>- )}- </div>- </div>- </div>- <PaymentSummaryPanel- isRefreshingPreview={isRefreshingPreview}- subscriptionPreview={subscriptionPreview}- isSpendCapEnabled={isSpendCapEnabled}- // Current subscription configuration based on DB- currentPlan={currentSubscription.tier}- currentAddons={currentAddons}- currentSubscription={currentSubscription}- // Selected subscription configuration based on UI- selectedPlan={selectedTier}- selectedAddons={selectedAddons}- paymentMethods={paymentMethods}- isLoadingPaymentMethods={isLoadingPaymentMethods}- selectedPaymentMethod={selectedPaymentMethodId}- onSelectPaymentMethod={setSelectedPaymentMethodId}- onSelectAddNewPaymentMethod={() => {- setShowAddPaymentMethodModal(true)- }}- beforeConfirmPayment={beforeConfirmPayment}- onConfirmPayment={onConfirmPayment}- isSubmitting={isSubmitting}- captcha={- <HCaptcha- ref={captchaRef}- sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY!}- size="invisible"- onVerify={(token) => {- setCaptchaToken(token)- }}- onExpire={() => {- setCaptchaToken(null)- }}- />- }- />- </Transition>-- <AddNewPaymentMethodModal- visible={showAddPaymentMethodModal}- returnUrl={`${getURL()}/project/${projectRef}/settings/billing/update/pro`}- onCancel={() => setShowAddPaymentMethodModal(false)}- onConfirm={() => onLocalPaymentMethodAdded()}- />-- {/* Spend caps helper modal */}-- <SpendCapModal- visible={showSpendCapHelperModal}- onHide={() => setShowSpendCapHelperModal(false)}- />- </>- )-}--export default ProUpgradediff --git a/studio/components/interfaces/Billing/Subscription/CostBreakdownRow.tsx b/studio/components/interfaces/Billing/Subscription/CostBreakdownRow.tsxdeleted file mode 100644index 7e653328ced..00000000000--- a/studio/components/interfaces/Billing/Subscription/CostBreakdownRow.tsx+++ /dev/null@@ -1,36 +0,0 @@-import { FC } from 'react'-import { Badge } from 'ui'--interface Props {- item: string- amount: number | string- unitPrice: number | string- price: number | string- note?: string-}--const CostBreakdownRow: FC<Props> = ({ item, amount, unitPrice, price, note }) => {- return (- <div className="relative flex items-center border-t border-panel-border-light px-6 py-3 dark:border-panel-border-dark">- <div className="flex w-[40%] items-center gap-3">- <span className="text-sm">{item}</span>- {note && (- <Badge color="scale">- <span className="text-xs text-scale-900">{note}</span>- </Badge>- )}- </div>- <div className="flex w-[20%] justify-end">- <span className="text-sm">{amount}</span>- </div>- <div className="flex w-[20%] justify-end">- <span className="text-sm">${unitPrice}</span>- </div>- <div className="flex w-[20%] justify-end">- <span className="text-sm">${price}</span>- </div>- </div>- )-}--export default CostBreakdownRowdiff --git a/studio/components/interfaces/Billing/Subscription/Subscription.tsx b/studio/components/interfaces/Billing/Subscription/Subscription.tsxdeleted file mode 100644index 7b77e6c6661..00000000000--- a/studio/components/interfaces/Billing/Subscription/Subscription.tsx+++ /dev/null@@ -1,264 +0,0 @@-import dayjs from 'dayjs'-import Link from 'next/link'-import { FC, useEffect } from 'react'-import { Button, Loading } from 'ui'-import * as Tooltip from '@radix-ui/react-tooltip'-import { PermissionAction } from '@supabase/shared-types/out/constants'--import { checkPermissions, useFlag, useStore } from 'hooks'-import { useParams } from 'common/hooks'-import { STRIPE_PRODUCT_IDS } from 'lib/constants'-import { formatBytes } from 'lib/helpers'--import { PRICING_TIER_PRODUCT_IDS } from 'lib/constants'-import CostBreakdownRow from './CostBreakdownRow'-import NoPermission from 'components/ui/NoPermission'-import { USAGE_BASED_PRODUCTS } from 'components/interfaces/Billing/Billing.constants'-import { ProjectUsageResponseUsageKeys, useProjectUsageQuery } from 'data/usage/project-usage-query'-import { useProjectSubscriptionQuery } from 'data/subscriptions/project-subscription-query'-import { useIsProjectActive } from 'components/layouts/ProjectLayout/ProjectContext'--interface Props {- showProjectName?: boolean-}--const Subscription: FC<Props> = ({ showProjectName = false }) => {- const { ui } = useStore()- const { ref: projectRef } = useParams()- const isActive = useIsProjectActive()- const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')-- const canReadSubscription = checkPermissions(PermissionAction.READ, 'subscriptions')- const canUpdateSubscription = checkPermissions(- PermissionAction.BILLING_WRITE,- 'stripe.subscriptions'- )-- const project = ui.selectedProject- const {- data: subscription,- isLoading: loading,- error,- } = useProjectSubscriptionQuery({ projectRef: ui.selectedProject?.ref })- const { data: usage } = useProjectUsageQuery({ projectRef })-- const isPayg = subscription?.tier.prod_id === STRIPE_PRODUCT_IDS.PAYG- const isTeam = subscription?.tier.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.TEAM- const isEnterprise = subscription?.tier.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.ENTERPRISE- const canOnlyUpdateAddons = isTeam || isEnterprise-- const addOns = subscription?.addons ?? []- const paid = subscription && subscription.tier.unit_amount > 0- const basePlanCost = (subscription?.tier.unit_amount ?? 0) / 100-- const currentPeriodStart = subscription?.billing.current_period_start ?? 0- const currentPeriodEnd = subscription?.billing.current_period_end ?? 0-- const deriveTotalCost = (): number => {- const totalAddOnCost = addOns- .map((addOn) => addOn.unit_amount / 100)- .reduce((prev, current) => prev + current, 0)- const totalUsageCost =- usage === undefined- ? 0- : Object.keys(usage)- .map((productKey) => {- return usage[productKey as ProjectUsageResponseUsageKeys].cost ?? 0- })- .reduce((prev, current) => prev + current, 0)-- return basePlanCost + totalAddOnCost + totalUsageCost- }-- const subscriptionUpdateURL = isEnterprise- ? `/project/${projectRef}/settings/billing/update/enterprise`- : isTeam- ? `/project/${projectRef}/settings/billing/update/team`- : `/project/${projectRef}/settings/billing/update`-- useEffect(() => {- if (error) {- ui.setNotification({- category: 'error',- message: `Failed to get project subscription: ${(error as any)?.message ?? 'unknown'}`,- })- }- }, [error])-- return (- <Loading active={loading}>- <div className="w-full mb-8 overflow-hidden border rounded border-panel-border-light dark:border-panel-border-dark">- <div className="bg-panel-body-light dark:bg-panel-body-dark">- <div className="flex items-center justify-between px-6 pt-4">- <div className="flex flex-col">- <p className="text-sm text-scale-1100">- {showProjectName ? project?.name ?? '' : 'Current subscription'}- </p>- <h3 className="mb-0 text-xl">{subscription?.tier.name ?? '-'}</h3>- </div>- <div className="flex flex-col items-end space-y-2">- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger>- <Link href={subscriptionUpdateURL}>- <a>- <Button- type="primary"- disabled={!canUpdateSubscription || projectUpdateDisabled || !isActive}- >- {canOnlyUpdateAddons ? 'Change add-ons' : 'Change subscription'}- </Button>- </a>- </Link>- </Tooltip.Trigger>- {!canUpdateSubscription || projectUpdateDisabled || !isActive ? (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'border border-scale-200 text-center', //border- 'rounded bg-scale-100 py-1 px-2 leading-none shadow', // background- ].join(' ')}- >- <span className="text-xs text-scale-1200">- {projectUpdateDisabled ? (- <>- Subscription changes are currently disabled.- <br />- Our engineers are working on a fix.- </>- ) : !canUpdateSubscription ? (- 'You need additional permissions to amend subscriptions'- ) : !isActive ? (- 'Unable to update subscription as project is not active'- ) : (- ''- )}- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- ) : (- <></>- )}- </Tooltip.Root>- </div>- </div>- {paid && (- <div className="px-6 pt-4">- <p>- The next payment for this plan will be occur on{' '}- {dayjs.unix(currentPeriodEnd).utc().format('MMM D, YYYY')}.- </p>- </div>- )}- <div className="px-6 pb-4 mt-2">- <p className="text-sm text-scale-1100">- See our{' '}- <a- href="https://supabase.com/pricing"- target="_blank"- rel="noreferrer"- className="underline"- >- pricing- </a>{' '}- for a more detailed analysis of what Supabase has on offer.- </p>- </div>-- {!canReadSubscription ? (- <div className="px-6 pb-4">- <NoPermission resourceText="view this project's subscription" />- </div>- ) : !loading && subscription ? (- // Cost breakdown- <>- <div className="relative flex items-center px-6 py-3 border-t border-panel-border-light dark:border-panel-border-dark">- <div className="w-[40%]">- <p className="text-xs uppercase text-scale-900">Item</p>- </div>- <div className="flex w-[20%] justify-end">- <p className="text-xs uppercase text-scale-900">Amount</p>- </div>- <div className="flex w-[20%] justify-end">- <p className="text-xs uppercase text-scale-900">Unit Price</p>- </div>- <div className="flex w-[20%] justify-end">- <p className="text-xs uppercase text-scale-900">Price</p>- </div>- </div>- <CostBreakdownRow- item="Base Plan"- amount={1}- unitPrice={basePlanCost.toFixed(2)}- price={basePlanCost.toFixed(2)}- />- {addOns.map((addOn) => (- <CostBreakdownRow- key={addOn.prod_id}- item={addOn.name}- amount={1}- unitPrice={addOn.unit_amount / 100}- price={addOn.unit_amount / 100}- />- ))}- {isPayg &&- USAGE_BASED_PRODUCTS.map((product) => {- return product.features.map((feature) => {- const amount = usage?.[feature.key as ProjectUsageResponseUsageKeys]?.usage ?? 0- const limit = usage?.[feature.key as ProjectUsageResponseUsageKeys]?.limit ?? 0- const cost = (- usage?.[feature.key as ProjectUsageResponseUsageKeys]?.cost ?? 0- ).toFixed(2)-- return (- <CostBreakdownRow- key={feature.key}- item={feature.title}- amount={- feature.units === 'bytes' ? formatBytes(amount) : amount.toLocaleString()- }- unitPrice={- feature.units === 'bytes'- ? `${feature.costPerUnit}/GB`- : feature.costPerUnit- }- price={cost}- note={- feature.units === 'bytes'- ? `${formatBytes(limit)} included`- : `${limit.toLocaleString()} included`- }- />- )- })- })}- <div- className={[- 'relative flex items-center border-t px-6 py-3',- 'border-panel-border-light dark:border-panel-border-dark',- ].join(' ')}- >- <div className="w-[80%]">- <p className="text-sm text-scale-1100">- Estimated cost for {dayjs.unix(currentPeriodStart).utc().format('MMM D, YYYY')}{' '}- - {dayjs.unix(currentPeriodEnd).utc().format('MMM D, YYYY')} so far- </p>- </div>- <div className="flex w-[20%] items-center justify-end space-x-1">- <p className="text-scale-1100">$</p>- <h3 className="m-0 text-xl">{deriveTotalCost().toFixed(2)}</h3>- </div>- </div>- </>- ) : (- <></>- )}- </div>- </div>- </Loading>- )-}--export default Subscriptiondiff --git a/studio/components/interfaces/Billing/Subscription/Subscription.types.ts b/studio/components/interfaces/Billing/Subscription/Subscription.types.tsdeleted file mode 100644index 5142008b039..00000000000--- a/studio/components/interfaces/Billing/Subscription/Subscription.types.ts+++ /dev/null@@ -1,18 +0,0 @@-export interface StripeSubscription {- tier: StripeProduct- billing: {- current_period_end: number- current_period_start: number- billing_cycle_anchor: number- }- addons: StripeProduct[]-}--export interface StripeProduct {- name: string- prod_id: string- price_id?: string- unit_amount: number- supabase_prod_id: string- key: 'FREE' | 'PRO' | 'TEAM' | 'ENTERPRISE'-}diff --git a/studio/components/interfaces/Billing/TeamUpgrade.tsx b/studio/components/interfaces/Billing/TeamUpgrade.tsxdeleted file mode 100644index 48b2dde8dcb..00000000000--- a/studio/components/interfaces/Billing/TeamUpgrade.tsx+++ /dev/null@@ -1,352 +0,0 @@-import { useEffect, useRef, useState } from 'react'-import { Transition } from '@headlessui/react'-import { useRouter } from 'next/router'--import { useStore, useFlag } from 'hooks'-import { post, patch } from 'lib/common/fetch'-import { API_URL, PRICING_TIER_PRODUCT_IDS, PROJECT_STATUS } from 'lib/constants'-import { getURL } from 'lib/helpers'-import Divider from 'components/ui/Divider'-import {- PaymentSummaryPanel,- ComputeSizeSelection,- PITRDurationSelection,- CustomDomainSelection,- StripeSubscription,- AddNewPaymentMethodModal,-} from './'-import { STRIPE_PRODUCT_IDS } from 'lib/constants'-import UpdateSuccess from './UpdateSuccess'-import { PaymentMethod, SubscriptionPreview } from './Billing.types'-import { formSubscriptionUpdatePayload, getCurrentAddons } from './Billing.utils'-import { SubscriptionAddon } from './AddOns/AddOns.types'-import {- formatComputeSizes,- formatCustomDomainOptions,- formatPITROptions,-} from './AddOns/AddOns.utils'-import SupportPlan from './AddOns/SupportPlan'-import HCaptcha from '@hcaptcha/react-hcaptcha'-import { subscriptionKeys } from 'data/subscriptions/keys'-import { useQueryClient } from '@tanstack/react-query'--// Do not allow compute size changes for af-south-1--interface TeamUpgradeProps {- products: { tiers: any[]; addons: SubscriptionAddon[] }- paymentMethods?: PaymentMethod[]- currentSubscription: StripeSubscription- isLoadingPaymentMethods: boolean- onPaymentMethodAdded: () => void-}--const TeamUpgrade = ({- products,- paymentMethods,- currentSubscription,- isLoadingPaymentMethods,- onPaymentMethodAdded,-}: TeamUpgradeProps) => {- const { app, ui } = useStore()- const router = useRouter()-- // Team tier is enabled when the user is already on the team tier (manually assigned by us)- const teamTierEnabled =- currentSubscription?.tier?.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.TEAM-- const [captchaToken, setCaptchaToken] = useState<string | null>(null)- const captchaRef = useRef<HCaptcha>(null)- const queryClient = useQueryClient()-- const { addons } = products- const computeSizes = formatComputeSizes(addons)- const pitrDurationOptions = formatPITROptions(addons)- const customDomainOptions = formatCustomDomainOptions(addons)- const currentAddons = getCurrentAddons(currentSubscription, addons)-- const projectId = ui.selectedProject?.id ?? -1- const projectRef = ui.selectedProject?.ref- const projectRegion = ui.selectedProject?.region ?? ''-- const [isRefreshingPreview, setIsRefreshingPreview] = useState(false)- const [isSubmitting, setIsSubmitting] = useState(false)- const [isSuccessful, setIsSuccessful] = useState(false)- const [showAddPaymentMethodModal, setShowAddPaymentMethodModal] = useState(false)-- // [Joshen TODO] Ideally we just have a state to hold all the add ons selection, rather than individual- // Even better if we can just use the <Form> component to handle all of these. Mainly to reduce the amount- // of unnecessary state management on this complex page.- const [selectedComputeSize, setSelectedComputeSize] = useState<SubscriptionAddon>(- currentAddons.computeSize- )- const [selectedPITRDuration, setSelectedPITRDuration] = useState<SubscriptionAddon>(- currentAddons.pitrDuration- )- const [selectedCustomDomainOption, setSelectedCustomDomainOption] = useState<SubscriptionAddon>(- currentAddons.customDomains- )-- // [Joshen TODO] Future - We may need to also include any add ons outside of- // compute size, pitr, custom domain and support plan, although we dont have any now- const nonChangeableAddons = [currentAddons.supportPlan].filter(- (x) => x !== undefined- ) as SubscriptionAddon[]-- // [Joshen] Scaffolded here- const selectedAddons = {- computeSize: selectedComputeSize,- pitrDuration: selectedPITRDuration,- customDomains: selectedCustomDomainOption,- }-- const [selectedPaymentMethodId, setSelectedPaymentMethodId] = useState<string>('')- const [subscriptionPreview, setSubscriptionPreview] = useState<SubscriptionPreview>()-- const selectedTier = products?.tiers.find((tier: any) => tier.id === STRIPE_PRODUCT_IDS.TEAM)-- const isManagingTeamSubscription = currentSubscription.tier.prod_id === STRIPE_PRODUCT_IDS.TEAM-- const isChangingComputeSize = currentAddons.computeSize?.id !== selectedAddons.computeSize.id-- useEffect(() => {- if (!isLoadingPaymentMethods && paymentMethods && paymentMethods.length > 0) {- setSelectedPaymentMethodId(paymentMethods[0].id)- }- }, [isLoadingPaymentMethods, paymentMethods])-- useEffect(() => {- getSubscriptionPreview()- }, [selectedComputeSize, selectedPITRDuration, selectedCustomDomainOption])-- const getSubscriptionPreview = async () => {- const payload = formSubscriptionUpdatePayload(- currentSubscription,- selectedTier,- selectedAddons,- nonChangeableAddons,- selectedPaymentMethodId,- projectRegion- )-- setIsRefreshingPreview(true)- const preview = await post(`${API_URL}/projects/${projectRef}/subscription/preview`, payload)- if (preview.error) {- ui.setNotification({- category: 'error',- message: `Failed to fetch subscription preview: ${preview.error.message}`,- })- }- setSubscriptionPreview(preview)- setIsRefreshingPreview(false)- }-- const resetCaptcha = () => {- setCaptchaToken(null)- captchaRef.current?.resetCaptcha()- }-- const beforeConfirmPayment = async (): Promise<boolean> => {- setIsSubmitting(true)- let token = captchaToken-- try {- if (!token) {- const captchaResponse = await captchaRef.current?.execute({ async: true })- token = captchaResponse?.response ?? null- setCaptchaToken(token)- }- } catch (error) {- setIsSubmitting(false)- return false- }-- setIsSubmitting(false)- return true- }-- const onLocalPaymentMethodAdded = () => {- setShowAddPaymentMethodModal(false)- return onPaymentMethodAdded()- }-- const onConfirmPayment = async () => {- if (!teamTierEnabled) {- return ui.setNotification({- category: 'error',- message: 'Team Plan is not enabled yet.',- })- }- setIsSubmitting(true)- const payload = formSubscriptionUpdatePayload(- currentSubscription,- selectedTier,- selectedAddons,- nonChangeableAddons,- selectedPaymentMethodId,- projectRegion- )- const res = await patch(`${API_URL}/projects/${projectRef}/subscription`, payload)- resetCaptcha()-- if (res?.error) {- ui.setNotification({- category: 'error',- message: `Failed to update subscription: ${res?.error?.message}`,- })- } else {- if (isChangingComputeSize) {- app.onProjectStatusUpdated(projectId, PROJECT_STATUS.RESTORING)- ui.setNotification({- category: 'success',- message:- 'Your project has been updated and is currently restarting to update its instance size',- duration: 8000,- })- router.push(`/project/${projectRef}`)- } else {- setIsSuccessful(true)- }-- await Promise.all([- queryClient.invalidateQueries(subscriptionKeys.subscriptionV2(projectRef)),- queryClient.invalidateQueries(subscriptionKeys.subscription(projectRef)),- queryClient.invalidateQueries(subscriptionKeys.addons(projectRef)),- ])- }- setIsSubmitting(false)- }-- if (!isSubmitting && isSuccessful) {- return (- <UpdateSuccess- projectRef={projectRef || ''}- title="Your project has been updated!"- message="Let us know if you have any feedback at [email protected]."- />- )- }-- return (- <>- <Transition- show- enter="transition ease-out duration-300"- enterFrom="transform opacity-0 translate-x-10"- enterTo="transform opacity-100 translate-x-0"- className="flex items-start justify-between w-full"- >- <div className="flex-grow mt-10">- <div className="relative space-y-4">- <div className="relative px-32 mx-auto space-y-4 2xl:max-w-5xl">- <h4 className="text-lg text-scale-900 !mb-8">Change your project's subscription</h4>- </div>-- <div- className="px-32 pb-8 mx-auto space-y-8 overflow-y-auto 2xl:max-w-5xl"- style={{ height: 'calc(100vh - 9rem - 57px)' }}- >- <div className="space-y-2">- {!isManagingTeamSubscription ? (- <>- <h3 className="text-xl">- Welcome to <span className="text-brand-900">Team</span>- </h3>- <p className="text-base text-scale-1100">- Your new subscription will begin immediately after payment- </p>- </>- ) : (- <>- <h3 className="text-3xl">- Managing your <span className="text-brand-900">Team</span> plan- </h3>- </>- )}- </div>-- {projectRegion !== 'af-south-1' && (- <>- {currentAddons.supportPlan !== undefined && (- <>- <Divider light />- <SupportPlan currentOption={currentAddons.supportPlan} />- </>- )}- <Divider light />- <CustomDomainSelection- options={customDomainOptions}- currentOption={- isManagingTeamSubscription ? currentAddons.customDomains : undefined- }- selectedOption={selectedAddons.customDomains}- onSelectOption={setSelectedCustomDomainOption}- />- <Divider light />- <PITRDurationSelection- pitrDurationOptions={pitrDurationOptions}- currentPitrDuration={- isManagingTeamSubscription ? currentAddons.pitrDuration : undefined- }- selectedPitrDuration={selectedAddons.pitrDuration}- onSelectOption={setSelectedPITRDuration}- />- <Divider light />- <ComputeSizeSelection- computeSizes={computeSizes || []}- currentComputeSize={currentAddons.computeSize}- selectedComputeSize={selectedAddons.computeSize}- onSelectOption={setSelectedComputeSize}- />- </>- )}- </div>- </div>- </div>- <PaymentSummaryPanel- isRefreshingPreview={isRefreshingPreview}- subscriptionPreview={subscriptionPreview}- isSpendCapEnabled={false}- // Current subscription configuration based on DB- currentPlan={currentSubscription.tier}- currentAddons={currentAddons}- currentSubscription={currentSubscription}- // Selected subscription configuration based on UI- selectedPlan={selectedTier}- selectedAddons={selectedAddons}- paymentMethods={paymentMethods}- isLoadingPaymentMethods={isLoadingPaymentMethods}- selectedPaymentMethod={selectedPaymentMethodId}- onSelectPaymentMethod={setSelectedPaymentMethodId}- onSelectAddNewPaymentMethod={() => {- setShowAddPaymentMethodModal(true)- }}- beforeConfirmPayment={beforeConfirmPayment}- onConfirmPayment={onConfirmPayment}- isSubmitting={isSubmitting}- captcha={- <HCaptcha- ref={captchaRef}- sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY!}- size="invisible"- onVerify={(token) => {- setCaptchaToken(token)- }}- onExpire={() => {- setCaptchaToken(null)- }}- />- }- />- </Transition>-- <AddNewPaymentMethodModal- visible={showAddPaymentMethodModal}- returnUrl={`${getURL()}/project/${projectRef}/settings/billing/update/team`}- onCancel={() => setShowAddPaymentMethodModal(false)}- onConfirm={() => onLocalPaymentMethodAdded()}- />- </>- )-}--export default TeamUpgradediff --git a/studio/components/interfaces/Billing/UpdateSuccess.tsx b/studio/components/interfaces/Billing/UpdateSuccess.tsxdeleted file mode 100644index 6f8d507e08a..00000000000--- a/studio/components/interfaces/Billing/UpdateSuccess.tsx+++ /dev/null@@ -1,38 +0,0 @@-import { FC } from 'react'-import { useRouter } from 'next/router'-import { Button, IconCheckCircle } from 'ui'--interface Props {- title: string- message: string- projectRef: string-}--const UpdateSuccess: FC<Props> = ({ title, message, projectRef }) => {- const router = useRouter()-- return (- <div- style={{ height: 'calc(100vh - 5rem - 49.5px)' }}- className="mx-auto flex max-w-xl flex-col justify-center space-y-4"- >- <div className="flex items-center space-x-4">- <IconCheckCircle strokeWidth={2} />- <h3 className="text-xl">{title}</h3>- </div>- <p className="text-sm text-scale-1100">{message}</p>- <div />- <div className="flex items-center space-x-4">- <Button onClick={() => router.push(`/project/${projectRef}`)}>Back to dashboard</Button>- <Button- onClick={() => router.push(`/project/${projectRef}/settings/billing/update`)}- type="default"- >- Back to billing- </Button>- </div>- </div>- )-}--export default UpdateSuccessdiff --git a/studio/components/interfaces/Billing/index.ts b/studio/components/interfaces/Billing/index.tsindex 6ba88496b0d..aad5a5febb3 100644--- a/studio/components/interfaces/Billing/index.ts+++ b/studio/components/interfaces/Billing/index.ts@@ -1,27 +1,4 @@-import Subscription from './Subscription/Subscription'-import PlanSelection from './PlanSelection/PlanSelection'-import ProUpgrade from './ProUpgrade'-import ExitSurvey from './ExitSurvey/ExitSurvey'-import PaymentSummaryPanel from './PaymentSummaryPanel/PaymentSummaryPanel'-import ComputeSizeSelection from './AddOns/ComputeSizeSelection'-import PITRDurationSelection from './AddOns/PITRDurationSelection'-import CustomDomainSelection from './AddOns/CustomDomainSelection'import AddNewPaymentMethodModal from './AddNewPaymentMethodModal/AddNewPaymentMethodModal'-import UpdateSuccess from './UpdateSuccess'-import Invoices from './Invoices'-export * from './Subscription/Subscription.types'-export {- Subscription,- PlanSelection,- ProUpgrade,- ExitSurvey,- PaymentSummaryPanel,- ComputeSizeSelection,- PITRDurationSelection,- CustomDomainSelection,- AddNewPaymentMethodModal,- UpdateSuccess,- Invoices,-}+export { AddNewPaymentMethodModal, Invoices }diff --git a/studio/components/interfaces/BillingV2/Subscription/Subscription.tsx b/studio/components/interfaces/BillingV2/Subscription/Subscription.tsxindex 206ad8236c5..e3d8877510e 100644--- a/studio/components/interfaces/BillingV2/Subscription/Subscription.tsx+++ b/studio/components/interfaces/BillingV2/Subscription/Subscription.tsx@@ -22,11 +22,6 @@ const Subscription = ({}: SubscriptionProps) => {if (panel && typeof panel === 'string' && allowedValues.includes(panel)) {snap.setPanelKey(panel as SUBSCRIPTION_PANEL_KEYS)-- const url = new URL(window.location.href)- url.searchParams.delete('panel')-- router.push(url.toString())}return (diff --git a/studio/components/interfaces/BillingV2/Subscription/Tier/PaymentMethodSelection.tsx b/studio/components/interfaces/BillingV2/Subscription/Tier/PaymentMethodSelection.tsxindex f0008936b6a..6bb6b298c51 100644--- a/studio/components/interfaces/BillingV2/Subscription/Tier/PaymentMethodSelection.tsx+++ b/studio/components/interfaces/BillingV2/Subscription/Tier/PaymentMethodSelection.tsx@@ -139,7 +139,7 @@ const PaymentMethodSelection = ({<AddNewPaymentMethodModalvisible={showAddNewPaymentMethodModal}- returnUrl={`${getURL()}/project/${projectRef}/settings/billing/update/pro`}+ returnUrl={`${getURL()}/project/${projectRef}/settings/billing/subscription?panel=subscriptionPlan`}onCancel={() => setShowAddNewPaymentMethodModal(false)}onConfirm={async () => {setShowAddNewPaymentMethodModal(false)diff --git a/studio/components/interfaces/BillingV2/Usage/Infrastructure.tsx b/studio/components/interfaces/BillingV2/Usage/Infrastructure.tsxindex f1b2af95baf..70a09db9830 100644--- a/studio/components/interfaces/BillingV2/Usage/Infrastructure.tsx+++ b/studio/components/interfaces/BillingV2/Usage/Infrastructure.tsx@@ -7,11 +7,10 @@ import { Alert, Button, IconBarChart2 } from 'ui'import SectionContent from './SectionContent'import SectionHeader from './SectionHeader'import { COMPUTE_INSTANCE_SPECS, USAGE_CATEGORIES } from './Usage.constants'-import { getUpgradeUrlFromV2Subscription } from './Usage.utils'+import { getUpgradeUrl } from './Usage.utils'import UsageBarChart from './UsageBarChart'import Panel from 'components/ui/Panel'import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'-import { useFlag } from 'hooks'export interface InfrastructureProps {projectRef: string@@ -26,12 +25,11 @@ const Infrastructure = ({endDate,currentBillingCycleSelected,}: InfrastructureProps) => {- const enableSubscriptionV2 = useFlag('subscriptionV2')const { data: subscription } = useProjectSubscriptionV2Query({ projectRef })const categoryMeta = USAGE_CATEGORIES.find((category) => category.key === 'infra')- const upgradeUrl = getUpgradeUrlFromV2Subscription(projectRef, subscription, enableSubscriptionV2)+ const upgradeUrl = getUpgradeUrl(projectRef, subscription)const isFreeTier = subscription?.plan?.id === 'free'const currentComputeInstance = subscription?.addons.find((addon) =>addon.supabase_prod_id.includes('_instance_')diff --git a/studio/components/interfaces/BillingV2/Usage/Usage.utils.ts b/studio/components/interfaces/BillingV2/Usage/Usage.utils.tsindex 2d85f0f4177..8fcec0fa371 100644--- a/studio/components/interfaces/BillingV2/Usage/Usage.utils.ts+++ b/studio/components/interfaces/BillingV2/Usage/Usage.utils.ts@@ -2,8 +2,6 @@ import { DataPoint } from 'data/analytics/constants'import { ProjectUsageResponse } from 'data/usage/project-usage-query'import { USAGE_APPROACHING_THRESHOLD } from '../Billing.constants'import { CategoryAttribute, USAGE_STATUS } from './Usage.constants'-import { StripeSubscription } from 'components/interfaces/Billing'-import { PRICING_TIER_PRODUCT_IDS } from 'lib/constants'import { formatBytes } from 'lib/helpers'import { ProjectSubscriptionResponse } from 'data/subscriptions/project-subscription-v2-query'@@ -37,42 +35,14 @@ export const getUsageStatus = (attributes: CategoryAttribute[], usage?: ProjectUelse return USAGE_STATUS.NORMAL}-export const getUpgradeUrl = (projectRef: string, subscription?: StripeSubscription) => {- if (!subscription) return `/project/${projectRef}/settings/billing/update`-- return subscription?.tier.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.ENTERPRISE- ? `/project/${projectRef}/settings/billing/update/enterprise`- : subscription?.tier.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.TEAM- ? `/project/${projectRef}/settings/billing/update/team`- : subscription?.tier.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.FREE- ? `/project/${projectRef}/settings/billing/update`- : `/project/${projectRef}/settings/billing/update/pro`-}--export const getUpgradeUrlFromV2Subscription = (- projectRef: string,- subscription?: ProjectSubscriptionResponse,- newSubscriptionPage?: boolean-) => {+export const getUpgradeUrl = (projectRef: string, subscription?: ProjectSubscriptionResponse) => {if (!subscription) {- return !newSubscriptionPage- ? `/project/${projectRef}/settings/billing/update`- : `/project/${projectRef}/settings/billing/subscription`+ return `/project/${projectRef}/settings/billing/subscription`}- if (!newSubscriptionPage) {- return subscription?.plan.id === 'enterprise'- ? `/project/${projectRef}/settings/billing/update/enterprise`- : subscription?.plan.id === 'team'- ? `/project/${projectRef}/settings/billing/update/team`- : subscription?.plan.id === 'free'- ? `/project/${projectRef}/settings/billing/update`- : `/project/${projectRef}/settings/billing/update/pro`- } else {- return subscription?.plan?.id === 'pro' && subscription?.usage_billing_enabled === false- ? `/project/${projectRef}/settings/billing/subscription#cost-control`- : `/project/${projectRef}/settings/billing/subscription?panel=subscriptionPlan`- }+ return subscription?.plan?.id === 'pro' && subscription?.usage_billing_enabled === false+ ? `/project/${projectRef}/settings/billing/subscription#cost-control`+ : `/project/${projectRef}/settings/billing/subscription?panel=subscriptionPlan`}const compactNumberFormatter = new Intl.NumberFormat('en-US', {diff --git a/studio/components/interfaces/BillingV2/Usage/UsageSection.tsx b/studio/components/interfaces/BillingV2/Usage/UsageSection.tsxindex 52a9a798e08..c5916b39341 100644--- a/studio/components/interfaces/BillingV2/Usage/UsageSection.tsx+++ b/studio/components/interfaces/BillingV2/Usage/UsageSection.tsx@@ -14,12 +14,11 @@ import Link from 'next/link'import SparkBar from 'components/ui/SparkBar'import clsx from 'clsx'import { ProjectSubscriptionResponse } from 'data/subscriptions/project-subscription-v2-query'-import { ChartYFormatterCompactNumber, getUpgradeUrlFromV2Subscription } from './Usage.utils'+import { ChartYFormatterCompactNumber, getUpgradeUrl } from './Usage.utils'import { formatBytes } from 'lib/helpers'import UsageBarChart from './UsageBarChart'import Panel from 'components/ui/Panel'import * as Tooltip from '@radix-ui/react-tooltip'-import { useFlag } from 'hooks'interface UsageSectionProps {projectRef: string@@ -38,7 +37,6 @@ const UsageSection = ({subscription,currentBillingCycleSelected,}: UsageSectionProps) => {- const enableSubscriptionV2 = useFlag('subscriptionV2')const { data: usage } = useProjectUsageQuery({ projectRef })const categoryMeta = USAGE_CATEGORIES.find((category) => category.key === categoryKey)@@ -47,7 +45,7 @@ const UsageSection = ({const usageBasedBilling = subscription?.usage_billing_enabledconst exceededLimitStyle = !usageBasedBilling ? 'text-red-900' : 'text-amber-900'- const upgradeUrl = getUpgradeUrlFromV2Subscription(projectRef, subscription, enableSubscriptionV2)+ const upgradeUrl = getUpgradeUrl(projectRef, subscription)return (<>@@ -256,7 +254,7 @@ const UsageSection = ({</p></div></div>- <Link href={`/project/${projectRef}/settings/billing/subscription`}>+ <Link href={`/project/${projectRef}/settings/billing/subscription?panel=subscriptionPlan`}><a><Button type="primary">Upgrade plan</Button></a>diff --git a/studio/components/interfaces/Database/Backups/PITR/PITR.utils.ts b/studio/components/interfaces/Database/Backups/PITR/PITR.utils.tsindex 61283648614..c0edb57e96a 100644--- a/studio/components/interfaces/Database/Backups/PITR/PITR.utils.ts+++ b/studio/components/interfaces/Database/Backups/PITR/PITR.utils.ts@@ -1,14 +1,13 @@-import { StripeProduct } from 'components/interfaces/Billing'import dayjs from 'dayjs'import { ALL_TIMEZONES } from './PITR.constants'import { Time, Timezone } from './PITR.types'+import { ProjectSelectedAddon } from 'data/subscriptions/project-addons-query'-export const getPITRRetentionDuration = (addons: StripeProduct[]) => {- const pitrAddon = addons.find((addon) => addon.supabase_prod_id.startsWith('addon_pitr'))+export const getPITRRetentionDuration = (addons: ProjectSelectedAddon[]) => {+ const pitrAddon = addons.find((addon) => addon.type === 'pitr')if (!pitrAddon) return 0- const daysString = pitrAddon.supabase_prod_id.split('_')[2]- return Number(daysString.split('days')[0])+ return pitrAddon.variant.meta?.backup_duration_days ?? 0}export const getDatesBetweenRange = (startDate: dayjs.Dayjs, endDate: dayjs.Dayjs) => {diff --git a/studio/components/interfaces/Database/Backups/PITR/PITRNotice.tsx b/studio/components/interfaces/Database/Backups/PITR/PITRNotice.tsxindex 66278292c19..88e43844ae3 100644--- a/studio/components/interfaces/Database/Backups/PITR/PITRNotice.tsx+++ b/studio/components/interfaces/Database/Backups/PITR/PITRNotice.tsx@@ -4,14 +4,14 @@ import { FormPanel } from 'components/ui/Forms'import * as Tooltip from '@radix-ui/react-tooltip'import { checkPermissions } from 'hooks'import { useParams } from 'common/hooks'-import { useProjectSubscriptionQuery } from 'data/subscriptions/project-subscription-query'import { getPITRRetentionDuration } from './PITR.utils'import { PermissionAction } from '@supabase/shared-types/out/constants'+import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'const PITRNotice = ({}) => {const { ref: projectRef } = useParams()- const { data: subscription } = useProjectSubscriptionQuery({ projectRef })- const retentionPeriod = getPITRRetentionDuration(subscription?.addons ?? [])+ const { data: addonsResponse } = useProjectAddonsQuery({ projectRef })+ const retentionPeriod = getPITRRetentionDuration(addonsResponse?.selected_addons ?? [])const canUpdateSubscription = checkPermissions(PermissionAction.BILLING_WRITE,@@ -28,7 +28,7 @@ const PITRNotice = ({}) => {</span><Tooltip.Root delayDuration={0}><Tooltip.Trigger>- <Link href={`/project/${projectRef}/settings/billing/update/pro`} passHref>+ <Link href={`/project/${projectRef}/settings/billing/subscription?panel=pitr`} passHref><Button disabled={canUpdateSubscription} type="default" asChild><a>Increase retention period</a></Button>diff --git a/studio/components/interfaces/Organization/BillingSettings/ProjectsSummary.tsx b/studio/components/interfaces/Organization/BillingSettings/ProjectsSummary.tsxindex 6590417c026..dd7c89c898f 100644--- a/studio/components/interfaces/Organization/BillingSettings/ProjectsSummary.tsx+++ b/studio/components/interfaces/Organization/BillingSettings/ProjectsSummary.tsx@@ -4,8 +4,8 @@ import { FC, useEffect } from 'react'import { IconChevronRight, IconLoader } from 'ui'import { useStore } from 'hooks'-import { useProjectSubscriptionQuery } from 'data/subscriptions/project-subscription-query'import Panel from 'components/ui/Panel'+import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'interface ProjectSummaryProps {project: any@@ -17,10 +17,10 @@ const ProjectSummary: FC<ProjectSummaryProps> = ({ project }) => {data: subscription,isLoading: loading,error,- } = useProjectSubscriptionQuery({ projectRef: project.ref })+ } = useProjectSubscriptionV2Query({ projectRef: project.ref })- const currentPeriodStart = subscription?.billing?.current_period_start ?? 0- const currentPeriodEnd = subscription?.billing?.current_period_end ?? 0+ const currentPeriodStart = subscription?.current_period_start ?? 0+ const currentPeriodEnd = subscription?.current_period_end ?? 0useEffect(() => {if (error) {@@ -43,7 +43,7 @@ const ProjectSummary: FC<ProjectSummaryProps> = ({ project }) => {) : (<><div className="w-[20%]">- <p className="text-sm">{subscription?.tier.name ?? ''}</p>+ <p className="text-sm">{subscription?.plan.name ?? ''}</p></div><div className="flex w-[40%] items-center space-x-2"><p className="text-sm">{dayjs.unix(currentPeriodStart).utc().format('MMM D, YYYY')}</p>diff --git a/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsx b/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsxindex 9e118b92d1c..a92bb05abc8 100644--- a/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsx+++ b/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsx@@ -3,8 +3,8 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common/hooks'import { FormHeader } from 'components/ui/Forms'import Panel from 'components/ui/Panel'-import { useProjectSubscriptionQuery } from 'data/subscriptions/project-subscription-query'import { useProjectDiskResizeMutation } from 'data/config/project-disk-resize-mutation'+import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'import { useProjectUsageQuery } from 'data/usage/project-usage-query'import { checkPermissions, useStore } from 'hooks'import Link from 'next/link'@@ -26,7 +26,7 @@ const DiskSizeConfiguration = ({ disabled = false }: DiskSizeConfigurationProps)const [isUpdatingDiskSize, setIsUpdatingDiskSize] = useState<boolean>(false)const { data: projectUsage } = useProjectUsageQuery({ projectRef })- const { data: projectSubscriptionData } = useProjectSubscriptionQuery({ projectRef })+ const { data: projectSubscriptionData } = useProjectSubscriptionV2Query({ projectRef })const { mutateAsync: updateProjectUsage } = useProjectDiskResizeMutation()useEffect(() => {@@ -73,7 +73,7 @@ const DiskSizeConfiguration = ({ disabled = false }: DiskSizeConfigurationProps)return (<div id="diskManagement"><FormHeader title="Disk management" />- {projectSubscriptionData?.tier.supabase_prod_id != 'tier_free' ? (+ {projectSubscriptionData?.plan.id != 'free' ? (<div className="flex flex-col gap-3"><Panel className="!m-0"><Panel.Content>diff --git a/studio/components/interfaces/Settings/General/Infrastructure/Infrastructure.tsx b/studio/components/interfaces/Settings/General/Infrastructure/Infrastructure.tsxindex fff06461d27..c354f72cc97 100644--- a/studio/components/interfaces/Settings/General/Infrastructure/Infrastructure.tsx+++ b/studio/components/interfaces/Settings/General/Infrastructure/Infrastructure.tsx@@ -16,17 +16,17 @@ import {import ProjectUpgradeAlert from './ProjectUpgradeAlert'import PauseProjectButton from './PauseProjectButton'import RestartServerButton from './RestartServerButton'-import { useProjectSubscriptionQuery } from 'data/subscriptions/project-subscription-query'import { useProjectUpgradeEligibilityQuery } from 'data/config/project-upgrade-eligibility-query'import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'+import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'interface InfrastructureProps {}const Infrastructure = ({}: InfrastructureProps) => {const { ref } = useParams()const { project } = useProjectContext()- const { data: subscription } = useProjectSubscriptionQuery({ projectRef: ref })- const isFreeProject = subscription?.tier.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.FREE+ const { data: subscription } = useProjectSubscriptionV2Query({ projectRef: ref })+ const isFreeProject = subscription?.plan.id === 'free'const {data,diff --git a/studio/components/interfaces/Settings/Logs/Logs.utils.ts b/studio/components/interfaces/Settings/Logs/Logs.utils.tsindex d9ad8fdef3d..f9ca314548b 100644--- a/studio/components/interfaces/Settings/Logs/Logs.utils.ts+++ b/studio/components/interfaces/Settings/Logs/Logs.utils.ts@@ -1,12 +1,12 @@import { Filters, LogData, LogsEndpointParams, LogsTableName, SQL_FILTER_TEMPLATES } from '.'import dayjs, { Dayjs } from 'dayjs'import { get, isEqual } from 'lodash'-import { StripeSubscription } from 'components/interfaces/Billing'import { useMonaco } from '@monaco-editor/react'import logConstants from 'shared-data/logConstants'import BackwardIterator from 'components/ui/CodeEditor/Providers/BackwardIterator'import uniqBy from 'lodash/uniqBy'import { useEffect } from 'react'+import { PlanId } from 'data/subscriptions/project-subscription-v2-query'/*** Convert a micro timestamp from number/string to iso timestamp@@ -183,17 +183,14 @@ export const genSingleLogQuery = (table: LogsTableName, id: string) =>/*** Determine if we should show the user an upgrade prompt while browsing logs*/-export const maybeShowUpgradePrompt = (- from: string | null | undefined,- tierKey?: StripeSubscription['tier']['key']-) => {+export const maybeShowUpgradePrompt = (from: string | null | undefined, planId?: PlanId) => {const day = Math.abs(dayjs().diff(dayjs(from), 'day'))return (- (day > 1 && tierKey === 'FREE') ||- (day > 7 && tierKey === 'PRO') ||- (day > 28 && tierKey === 'TEAM') ||- (day > 90 && tierKey === 'ENTERPRISE')+ (day > 1 && planId === 'free') ||+ (day > 7 && planId === 'pro') ||+ (day > 28 && planId === 'team') ||+ (day > 90 && planId === 'enterprise'))}diff --git a/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx b/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsxindex 4b01e08c126..31b29ad9f8e 100644--- a/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx+++ b/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx@@ -23,7 +23,7 @@ import LoadingOpacity from 'components/ui/LoadingOpacity'import { useUpgradePrompt } from 'hooks/misc/useUpgradePrompt'import UpgradePrompt from './UpgradePrompt'import { useParams } from 'common/hooks'-import { useProjectSubscriptionQuery } from 'data/subscriptions/project-subscription-query'+import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'/*** Acts as a container component for the entire log display@@ -52,8 +52,7 @@ export const LogsPreviewer: React.FC<Props> = ({const router = useRouter()const { s, ite, its } = useParams()const [showChart, setShowChart] = useState(true)- const { data: subscription } = useProjectSubscriptionQuery({ projectRef })- const tier = subscription?.tier+ const { data: subscription } = useProjectSubscriptionV2Query({ projectRef })const table = !tableName ? LOGS_TABLES[queryType] : tableName@@ -90,12 +89,12 @@ export const LogsPreviewer: React.FC<Props> = ({// Show the prompt on page load based on query paramsuseEffect(() => {if (its) {- const shouldShowUpgradePrompt = maybeShowUpgradePrompt(its as string, tier?.key)+ const shouldShowUpgradePrompt = maybeShowUpgradePrompt(its as string, subscription?.plan?.id)if (shouldShowUpgradePrompt) {setShowUpgradePrompt(!showUpgradePrompt)}}- }, [its, tier])+ }, [its, subscription])const onSelectTemplate = (template: LogTemplate) => {setFilters((prev: any) => ({ ...prev, search_query: template.searchString }))@@ -139,7 +138,7 @@ export const LogsPreviewer: React.FC<Props> = ({},})} else if (event === 'datepicker-change') {- const shouldShowUpgradePrompt = maybeShowUpgradePrompt(from, tier?.key)+ const shouldShowUpgradePrompt = maybeShowUpgradePrompt(from, subscription?.plan?.id)if (shouldShowUpgradePrompt) {setShowUpgradePrompt(!showUpgradePrompt)@@ -244,7 +243,6 @@ export const LogsPreviewer: React.FC<Props> = ({<UpgradePromptshow={showUpgradePrompt}setShowUpgradePrompt={setShowUpgradePrompt}- subscription={subscription}/></div></div>diff --git a/studio/components/interfaces/Settings/Logs/UpgradePrompt.tsx b/studio/components/interfaces/Settings/Logs/UpgradePrompt.tsxindex 25a45b84b75..bd88aa58a6e 100644--- a/studio/components/interfaces/Settings/Logs/UpgradePrompt.tsx+++ b/studio/components/interfaces/Settings/Logs/UpgradePrompt.tsx@@ -3,17 +3,13 @@ import { Button, Modal } from 'ui'import { TIER_QUERY_LIMITS } from '.'import Link from 'next/link'import { useRouter } from 'next/router'-import { useFlag } from 'hooks'-import { StripeSubscription } from 'components/interfaces/Billing'-import { PRICING_TIER_PRODUCT_IDS } from 'lib/constants'interface Props {show: booleansetShowUpgradePrompt: (value: boolean) => void- subscription: StripeSubscription | undefined}-const UpgradePrompt: React.FC<Props> = ({ show, setShowUpgradePrompt, subscription }) => {+const UpgradePrompt: React.FC<Props> = ({ show, setShowUpgradePrompt }) => {const router = useRouter()const { ref } = router.querydiff --git a/studio/components/interfaces/Support/DisabledStateForFreeTier.tsx b/studio/components/interfaces/Support/DisabledStateForFreeTier.tsxindex 3d7628194fb..3d1396ca44c 100644--- a/studio/components/interfaces/Support/DisabledStateForFreeTier.tsx+++ b/studio/components/interfaces/Support/DisabledStateForFreeTier.tsx@@ -20,7 +20,7 @@ const DisabledStateForFreeTier: FC<Props> = ({ projectRef, category }) => {<div className="space-y-4 mb-1"><p>Upgrade your project to the Pro plan for support in this area</p><div className="flex items-center space-x-2">- <Link href={`/project/${projectRef}/settings/billing/update`}>+ <Link href={`/project/${projectRef}/settings/billing/subscription?panel=subscriptionPlan`}><a><Button>Upgrade project</Button></a>diff --git a/studio/components/interfaces/Support/SupportForm.tsx b/studio/components/interfaces/Support/SupportForm.tsxindex 20e5cbdef10..03d73893e89 100644--- a/studio/components/interfaces/Support/SupportForm.tsx+++ b/studio/components/interfaces/Support/SupportForm.tsx@@ -353,7 +353,7 @@ const SupportForm: FC<Props> = ({ setSentCategory }) => {Enhanced SLAs for support are available on our Enterprise Plan.</p><div className="flex items-center space-x-2">- <Link href={`/project/${values.projectRef}/settings/billing/update`}>+ <Link href={`/project/${values.projectRef}/settings/billing/subscription?panel=subscriptionPlan`}><a><Button>Upgrade project</Button></a>diff --git a/studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/NotificationActions.tsx b/studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/NotificationActions.tsxindex ceda11fdbbe..05e048c43b3 100644--- a/studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/NotificationActions.tsx+++ b/studio/components/layouts/ProjectLayout/LayoutHeader/NotificationsPopover/NotificationActions.tsx@@ -33,7 +33,7 @@ const NotificationActions: FC<Props> = ({const router = useRouter()const onSelectUpgradeProject = () => {- return router.push(`/project/${project.ref}/settings/billing/update/pro`)+ return router.push(`/project/${project.ref}/settings/billing/subscription?panel=subscriptionPlan`)}const renderActionButton = (action: Action) => {diff --git a/studio/components/layouts/ProjectLayout/ProjectLayout.tsx b/studio/components/layouts/ProjectLayout/ProjectLayout.tsxindex 9df62f126e9..f00bbca7e2a 100644--- a/studio/components/layouts/ProjectLayout/ProjectLayout.tsx+++ b/studio/components/layouts/ProjectLayout/ProjectLayout.tsx@@ -140,10 +140,7 @@ const ContentWrapper = observer(({ isLoading, children }: ContentWrapperProps) ='/project/[ref]/settings/database','/project/[ref]/settings/billing/subscription','/project/[ref]/settings/billing/usage',- '/project/[ref]/settings/billing/invoices',- '/project/[ref]/settings/billing/update',- '/project/[ref]/settings/billing/update/free',- '/project/[ref]/settings/billing/update/pro',+ '/project/[ref]/settings/billing/invoices']const requiresDbConnection: boolean = router.pathname !== '/project/[ref]/settings/general'diff --git a/studio/components/ui/UpgradeToPro.tsx b/studio/components/ui/UpgradeToPro.tsxindex 47259e9f7b7..fb17a75452a 100644--- a/studio/components/ui/UpgradeToPro.tsx+++ b/studio/components/ui/UpgradeToPro.tsx@@ -48,13 +48,7 @@ const UpgradeToPro: FC<Props> = ({ icon, primaryText, projectRef, secondaryText<Tooltip.Root delayDuration={0}><Tooltip.Trigger><Button type="primary" disabled={!canUpdateSubscription || projectUpdateDisabled}>- <Link- href={- isEnterprise- ? `/project/${ref}/settings/billing/update/enterprise`- : `/project/${ref}/settings/billing/update`- }- >+ <Link href={`/project/${ref}/settings/billing/subscription?panel=subscriptionPlan`}><a>{tier === PRICING_TIER_PRODUCT_IDS.FREE? 'Upgrade to Pro'diff --git a/studio/data/stripe/keys.ts b/studio/data/stripe/keys.tsdeleted file mode 100644index 868c5058a07..00000000000--- a/studio/data/stripe/keys.ts+++ /dev/null@@ -1,3 +0,0 @@-export const stripeKeys = {- products: () => ['products'] as const,-}diff --git a/studio/data/stripe/products-query.ts b/studio/data/stripe/products-query.tsdeleted file mode 100644index 9ed5c8526cc..00000000000--- a/studio/data/stripe/products-query.ts+++ /dev/null@@ -1,31 +0,0 @@-import { useQuery, UseQueryOptions } from '@tanstack/react-query'-import { get } from 'lib/common/fetch'-import { API_URL } from 'lib/constants'-import { stripeKeys } from './keys'-import { SubscriptionAddon } from 'components/interfaces/Billing/AddOns/AddOns.types'--export type StripeProductsResponse = {- tiers: SubscriptionAddon[]- addons: SubscriptionAddon[]-}--export async function getStripeProducts(signal?: AbortSignal) {- const response = await get(`${API_URL}/stripe/products`, {- signal,- })- if (response.error) throw response.error- return response as StripeProductsResponse-}--export type StripeProductsData = Awaited<ReturnType<typeof getStripeProducts>>-export type StripeProductsError = unknown--export const useStripeProductsQuery = <TData = StripeProductsData>({- enabled = true,- ...options-}: UseQueryOptions<StripeProductsData, StripeProductsError, TData> = {}) =>- useQuery<StripeProductsData, StripeProductsError, TData>(- stripeKeys.products(),- ({ signal }) => getStripeProducts(signal),- { enabled, ...options }- )diff --git a/studio/data/subscriptions/keys.ts b/studio/data/subscriptions/keys.tsindex 4a617d1bddd..c8f1fddaead 100644--- a/studio/data/subscriptions/keys.ts+++ b/studio/data/subscriptions/keys.ts@@ -1,8 +1,6 @@// [Joshen TODO] To remove subscription V2 after v2 is launched and stable to deprecate old billing ui + endpointsexport const subscriptionKeys = {- subscription: (projectRef: string | undefined) =>- ['projects', projectRef, 'subscription'] as const,subscriptionV2: (projectRef: string | undefined) =>['projects', projectRef, 'subscriptionV2'] as const,addons: (projectRef: string | undefined) => ['projects', projectRef, 'addons'] as const,diff --git a/studio/data/subscriptions/project-addon-update-mutation.ts b/studio/data/subscriptions/project-addon-update-mutation.tsindex e58f12c79c5..d154d1e8206 100644--- a/studio/data/subscriptions/project-addon-update-mutation.ts+++ b/studio/data/subscriptions/project-addon-update-mutation.ts@@ -49,7 +49,6 @@ export const useProjectAddonUpdateMutation = ({const { projectRef } = variablesawait Promise.all([queryClient.invalidateQueries(subscriptionKeys.subscriptionV2(projectRef)),- queryClient.invalidateQueries(subscriptionKeys.subscription(projectRef)),queryClient.invalidateQueries(subscriptionKeys.addons(projectRef)),])await onSuccess?.(data, variables, context)diff --git a/studio/data/subscriptions/project-addons-query.ts b/studio/data/subscriptions/project-addons-query.tsindex 5717870c988..fd648bed44e 100644--- a/studio/data/subscriptions/project-addons-query.ts+++ b/studio/data/subscriptions/project-addons-query.ts@@ -17,19 +17,18 @@ export type ProjectAddonVariant = {price_description: stringprice_interval: 'monthly' | 'hourly'price_type: 'fixed' | 'usage'+ meta?: ProjectAddonVariantMeta}-export interface ProjectAvailableAddonVariant extends ProjectAddonVariant {- meta?: {- cpu_cores?: number- cpu_dedicated?: boolean- baseline_disk_io_mbs?: number- max_disk_io_mbs?: number- memory_gb?: number- connections_direct?: number- connections_pooler?: number- backup_duration_days?: number- }+export interface ProjectAddonVariantMeta {+ cpu_cores?: number+ cpu_dedicated?: boolean+ baseline_disk_io_mbs?: number+ max_disk_io_mbs?: number+ memory_gb?: number+ connections_direct?: number+ connections_pooler?: number+ backup_duration_days?: number}export type ProjectSelectedAddon = {@@ -43,7 +42,7 @@ export type ProjectAddonsResponse = {available_addons: {name: stringtype: ProjectAddonType- variants: ProjectAvailableAddonVariant[]+ variants: ProjectAddonVariant[]}[]}diff --git a/studio/data/subscriptions/project-subscription-query.ts b/studio/data/subscriptions/project-subscription-query.tsdeleted file mode 100644index 8a3365dc9f9..00000000000--- a/studio/data/subscriptions/project-subscription-query.ts+++ /dev/null@@ -1,61 +0,0 @@-import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'-import { StripeSubscription } from 'components/interfaces/Billing'-import { get } from 'lib/common/fetch'-import { API_URL } from 'lib/constants'-import { useCallback } from 'react'-import { subscriptionKeys } from './keys'--export type ProjectSubscriptionVariables = {- projectRef?: string-}--export type ProjectSubscriptionResponse = StripeSubscription--export async function getProjectSubscription(- { projectRef }: ProjectSubscriptionVariables,- signal?: AbortSignal-) {- if (!projectRef) {- throw new Error('projectRef is required')- }-- const response = await get(`${API_URL}/projects/${projectRef}/subscription`, {- signal,- })- if (response.error) {- throw response.error- }-- return response as ProjectSubscriptionResponse-}--export type ProjectSubscriptionData = Awaited<ReturnType<typeof getProjectSubscription>>-export type ProjectSubscriptionError = unknown--export const useProjectSubscriptionQuery = <TData = ProjectSubscriptionData>(- { projectRef }: ProjectSubscriptionVariables,- {- enabled = true,- ...options- }: UseQueryOptions<ProjectSubscriptionData, ProjectSubscriptionError, TData> = {}-) =>- useQuery<ProjectSubscriptionData, ProjectSubscriptionError, TData>(- subscriptionKeys.subscription(projectRef),- ({ signal }) => getProjectSubscription({ projectRef }, signal),- {- enabled: enabled && typeof projectRef !== 'undefined',- ...options,- }- )--export const useProjectSubscriptionPrefetch = ({ projectRef }: ProjectSubscriptionVariables) => {- const client = useQueryClient()-- return useCallback(() => {- if (projectRef) {- client.prefetchQuery(subscriptionKeys.subscription(projectRef), ({ signal }) =>- getProjectSubscription({ projectRef }, signal)- )- }- }, [projectRef])-}diff --git a/studio/data/subscriptions/project-subscription-update-mutation.ts b/studio/data/subscriptions/project-subscription-update-mutation.tsindex 0f30dae670f..69c5b853522 100644--- a/studio/data/subscriptions/project-subscription-update-mutation.ts+++ b/studio/data/subscriptions/project-subscription-update-mutation.ts@@ -58,7 +58,6 @@ export const useProjectSubscriptionUpdateMutation = ({const { projectRef } = variablesawait Promise.all([queryClient.invalidateQueries(subscriptionKeys.subscriptionV2(projectRef)),- queryClient.invalidateQueries(subscriptionKeys.subscription(projectRef)),queryClient.invalidateQueries(subscriptionKeys.addons(projectRef)),])await onSuccess?.(data, variables, context)diff --git a/studio/data/subscriptions/project-subscription-v2-query.ts b/studio/data/subscriptions/project-subscription-v2-query.tsindex 16e793ded47..881f2118b76 100644--- a/studio/data/subscriptions/project-subscription-v2-query.ts+++ b/studio/data/subscriptions/project-subscription-v2-query.ts@@ -10,6 +10,8 @@ export type ProjectSubscriptionVariables = {projectRef?: string}+export type PlanId = 'free' | 'pro' | 'team' | 'enterprise'+export type ProjectSubscriptionResponse = {billing_cycle_anchor: numbercurrent_period_start: number@@ -17,7 +19,7 @@ export type ProjectSubscriptionResponse = {next_invoice_at: numberusage_billing_enabled: booleanplan: {- id: 'free' | 'pro' | 'team' | 'enterprise'+ id: PlanIdname: stringprice: number}diff --git a/studio/hooks/misc/useUpgradePrompt.tsx b/studio/hooks/misc/useUpgradePrompt.tsxindex f58aca0c45d..f7852ffd06c 100644--- a/studio/hooks/misc/useUpgradePrompt.tsx+++ b/studio/hooks/misc/useUpgradePrompt.tsx@@ -1,15 +1,14 @@import { useEffect, useState } from 'react'import { useParams } from 'common/hooks'import { maybeShowUpgradePrompt } from 'components/interfaces/Settings/Logs'-import { useProjectSubscriptionQuery } from 'data/subscriptions/project-subscription-query'+import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'export const useUpgradePrompt = (from: string) => {const { ref: projectRef } = useParams()- const { data: subscription } = useProjectSubscriptionQuery({ projectRef })- const tier = subscription?.tier+ const { data: subscription } = useProjectSubscriptionV2Query({ projectRef })const [showUpgradePrompt, setShowUpgradePrompt] = useState(false)- const shouldShowUpgradePrompt = maybeShowUpgradePrompt(from, tier?.key)+ const shouldShowUpgradePrompt = maybeShowUpgradePrompt(from, subscription?.plan?.id)useEffect(() => {if (shouldShowUpgradePrompt) {diff --git a/studio/lib/constants/infrastructure.ts b/studio/lib/constants/infrastructure.tsindex 634e68072eb..eed060ab177 100644--- a/studio/lib/constants/infrastructure.ts+++ b/studio/lib/constants/infrastructure.ts@@ -136,13 +136,6 @@ export const PROJECT_STATUS = {UPGRADING: 'UPGRADING',}-export const STRIPE_PRODUCT_IDS: { [x: string]: string } = {- FREE: process?.env?.NEXT_PUBLIC_STRIPE_FREE_TIER_ID || 'prod_Ip4vqwv3EJ7Mi0',- PRO: process?.env?.NEXT_PUBLIC_STRIPE_PRO_TIER_ID || 'prod_IsRLOp58Z7V4XN',- PAYG: process?.env?.NEXT_PUBLIC_STRIPE_PAYG_TIER_ID || 'prod_JlTbw91xcM6NY4',- TEAM: process?.env?.NEXT_PUBLIC_STRIPE_TEAM_TIER_ID || 'prod_MeUrsWN6pj0oXM',-}-export const DEFAULT_MINIMUM_PASSWORD_STRENGTH = 4export const PASSWORD_STRENGTH = {diff --git a/studio/next.config.js b/studio/next.config.jsindex 5305c2d290e..482be47c169 100644--- a/studio/next.config.js+++ b/studio/next.config.js@@ -140,6 +140,31 @@ const nextConfig = {destination: '/org/:slug/general',permanent: true,},+ {+ source: '/project/:ref/settings/billing/update',+ destination: '/project/:ref/settings/billing/subscription',+ permanent: true,+ },+ {+ source: '/project/:ref/settings/billing/update/free',+ destination: '/project/:ref/settings/billing/subscription',+ permanent: true,+ },+ {+ source: '/project/:ref/settings/billing/update/pro',+ destination: '/project/:ref/settings/billing/subscription',+ permanent: true,+ },+ {+ source: '/project/:ref/settings/billing/update/team',+ destination: '/project/:ref/settings/billing/subscription',+ permanent: true,+ },+ {+ source: '/project/:ref/settings/billing/update/enterprise',+ destination: '/project/:ref/settings/billing/subscription',+ permanent: true,+ },]},async headers() {diff --git a/studio/pages/project/[ref]/logs/explorer/index.tsx b/studio/pages/project/[ref]/logs/explorer/index.tsxindex 3b9a7d09f82..32e873816c6 100644--- a/studio/pages/project/[ref]/logs/explorer/index.tsx+++ b/studio/pages/project/[ref]/logs/explorer/index.tsx@@ -7,7 +7,6 @@ import { Input, Modal, Form, Button } from 'ui'import { useStore } from 'hooks'import { useParams } from 'common/hooks'import useLogsQuery from 'hooks/analytics/useLogsQuery'-import { useProjectSubscriptionQuery } from 'data/subscriptions/project-subscription-query'import { NextPageWithLayout, UserContent } from 'types'import { uuidv4 } from 'lib/helpers'import { LogsLayout } from 'components/layouts'@@ -29,6 +28,7 @@ import {import { useUpgradePrompt } from 'hooks/misc/useUpgradePrompt'import UpgradePrompt from 'components/interfaces/Settings/Logs/UpgradePrompt'import LogsExplorerHeader from 'components/ui/Logs/LogsExplorerHeader'+import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'const PLACEHOLDER_QUERY ='select\n cast(timestamp as datetime) as timestamp,\n event_message, metadata \nfrom edge_logs \nlimit 5'@@ -41,13 +41,14 @@ export const LogsExplorerPage: NextPageWithLayout = () => {const [editorValue, setEditorValue] = useState<string>(PLACEHOLDER_QUERY)const [saveModalOpen, setSaveModalOpen] = useState<boolean>(false)const [warnings, setWarnings] = useState<LogsWarning[]>([])- const { data: subscription } = useProjectSubscriptionQuery({ projectRef })- const tier = subscription?.tier- const { params, logData, error, isLoading, changeQuery, runQuery, setParams } =- useLogsQuery(projectRef as string, {+ const { data: subscription } = useProjectSubscriptionV2Query({ projectRef })+ const { params, logData, error, isLoading, changeQuery, runQuery, setParams } = useLogsQuery(+ projectRef as string,+ {iso_timestamp_start: its ? (its as string) : undefined,iso_timestamp_end: ite ? (ite as string) : undefined,- })+ }+ )const { showUpgradePrompt, setShowUpgradePrompt } = useUpgradePrompt(params.iso_timestamp_start as string@@ -81,12 +82,12 @@ export const LogsExplorerPage: NextPageWithLayout = () => {// Show the prompt on page load based on query paramsuseEffect(() => {if (its) {- const shouldShowUpgradePrompt = maybeShowUpgradePrompt(its as string, tier?.key)+ const shouldShowUpgradePrompt = maybeShowUpgradePrompt(its as string, subscription?.plan?.id)if (shouldShowUpgradePrompt) {setShowUpgradePrompt(!showUpgradePrompt)}}- }, [its, tier])+ }, [its, subscription])const onSelectTemplate = (template: LogTemplate) => {setEditorValue(template.searchString)@@ -133,7 +134,7 @@ export const LogsExplorerPage: NextPageWithLayout = () => {}const handleDateChange = ({ to, from }: DatePickerToFrom) => {- const shouldShowUpgradePrompt = maybeShowUpgradePrompt(from, tier?.key)+ const shouldShowUpgradePrompt = maybeShowUpgradePrompt(from, subscription?.plan?.id)if (shouldShowUpgradePrompt) {setShowUpgradePrompt(!showUpgradePrompt)@@ -193,11 +194,7 @@ export const LogsExplorerPage: NextPageWithLayout = () => {</div></LoadingOpacity><div className="flex flex-row justify-end mt-2">- <UpgradePrompt- show={showUpgradePrompt}- setShowUpgradePrompt={setShowUpgradePrompt}- subscription={subscription}- />+ <UpgradePrompt show={showUpgradePrompt} setShowUpgradePrompt={setShowUpgradePrompt} /></div></div></div>diff --git a/studio/pages/project/[ref]/reports/api-overview.tsx b/studio/pages/project/[ref]/reports/api-overview.tsxindex 2bf633a05b1..3f258f447f6 100644--- a/studio/pages/project/[ref]/reports/api-overview.tsx+++ b/studio/pages/project/[ref]/reports/api-overview.tsx@@ -18,18 +18,18 @@ import { useState, useEffect } from 'react'import ReportHeader from 'components/interfaces/Reports/ReportHeader'import { DatePickerToFrom, LogsEndpointParams } from 'components/interfaces/Settings/Logs'import ReportFilterBar from 'components/interfaces/Reports/ReportFilterBar'-import { useProjectSubscriptionQuery } from 'data/subscriptions/project-subscription-query'import { useParams } from 'common'import { isEqual } from 'lodash'import ShimmerLine from 'components/ui/ShimmerLine'import ReportPadding from 'components/interfaces/Reports/ReportPadding'+import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'export const ApiReport: NextPageWithLayout = () => {const { ref: projectRef } = useParams()const report = useApiReport()- const { data: subscription } = useProjectSubscriptionQuery({ projectRef })- const tier = subscription?.tier+ const { data: subscription } = useProjectSubscriptionV2Query({ projectRef })+ const plan = subscription?.planconst handleDatepickerChange = ({ from, to }: DatePickerToFrom) => {report.mergeParams({@@ -51,7 +51,7 @@ export const ApiReport: NextPageWithLayout = () => {filters={report.filters}datepickerHelpers={REPORTS_DATEPICKER_HELPERS.map((helper, index) => ({...helper,- disabled: (index > 0 && tier?.key === 'FREE') || (index > 1 && tier?.key !== 'PRO'),+ disabled: (index > 0 && plan?.id === 'free') || (index > 1 && plan?.id !== 'pro'),}))}/><div className="h-2 w-full">diff --git a/studio/pages/project/[ref]/settings/billing/invoices.tsx b/studio/pages/project/[ref]/settings/billing/invoices.tsxindex a83d188e7a4..eab1762fe97 100644--- a/studio/pages/project/[ref]/settings/billing/invoices.tsx+++ b/studio/pages/project/[ref]/settings/billing/invoices.tsx@@ -1,10 +1,8 @@import { observer } from 'mobx-react-lite'-import { FC, useEffect } from 'react'+import { FC } from 'react'import { SettingsLayout } from 'components/layouts'-import LoadingUI from 'components/ui/Loading'import { useStore } from 'hooks'-import { useProjectSubscriptionQuery } from 'data/subscriptions/project-subscription-query'import { NextPageWithLayout, Project } from 'types'import { Invoices } from 'components/interfaces/Billing'@@ -37,28 +35,8 @@ const Settings: FC<SettingsProps> = ({ project }) => {const { ui } = useStore()const orgSlug = ui.selectedOrganization?.slug ?? ''- const { data: subscription, error } = useProjectSubscriptionQuery({- projectRef: ui.selectedProject?.ref,- })-- useEffect(() => {- if (error) {- ui.setNotification({- category: 'error',- message: `Failed to get project subscription: ${(error as any)?.message ?? 'unknown'}`,- })- }- }, [error])-- if (!subscription) {- return <LoadingUI />- }-return (<div className="container max-w-4xl p-4 space-y-8">- {/* [Joshen TODO] Temporarily hidden until usage endpoint is sorted out */}- {/* {projectTier !== undefined && <OveragesBanner tier={projectTier} />} */}-<div className="space-y-2"><h4 className="text-lg">Invoices</h4>diff --git a/studio/pages/project/[ref]/settings/billing/subscription.tsx b/studio/pages/project/[ref]/settings/billing/subscription.tsxindex 5cb88295fc5..c9c5a352eed 100644--- a/studio/pages/project/[ref]/settings/billing/subscription.tsx+++ b/studio/pages/project/[ref]/settings/billing/subscription.tsx@@ -1,43 +1,12 @@-import { useState } from 'react'import { observer } from 'mobx-react-lite'-import { Loading, Toggle } from 'ui'import { SettingsLayout } from 'components/layouts'-import LoadingUI from 'components/ui/Loading'-import { useStore, useFlag } from 'hooks'-import { useProjectSubscriptionQuery } from 'data/subscriptions/project-subscription-query'import { NextPageWithLayout } from 'types'-import { Subscription } from 'components/interfaces/Billing'import SubscriptionV2 from 'components/interfaces/BillingV2/Subscription/Subscription'const ProjectBilling: NextPageWithLayout = () => {- const enableSubscriptionV2 = useFlag('subscriptionV2')- const [showNewSubscriptionUI, setShowNewSubscriptionUI] = useState(enableSubscriptionV2)-- return (- <div className="relative">- {enableSubscriptionV2 && (- <div className="absolute top-[1.9rem] right-16 xl:right-32 flex items-center space-x-3 z-10">- <Toggle- size="tiny"- checked={showNewSubscriptionUI}- onChange={() => setShowNewSubscriptionUI(!showNewSubscriptionUI)}- />- <p className="text-xs text-scale-1100 -translate-y-[1px]">Preview new interface</p>- </div>- )}- {showNewSubscriptionUI ? (- <SubscriptionV2 />- ) : (- <div className="w-full h-full overflow-y-auto content">- <div className="w-full mx-auto">- <Settings />- </div>- </div>- )}- </div>- )+ return <SubscriptionV2 />}ProjectBilling.getLayout = (page) => (@@ -45,34 +14,3 @@ ProjectBilling.getLayout = (page) => ()export default observer(ProjectBilling)--const Settings = () => {- const { ui } = useStore()-- const { data: subscription, isLoading: loading } = useProjectSubscriptionQuery({- projectRef: ui.selectedProject?.ref,- })-- if (!subscription) {- return <LoadingUI />- }-- return (- <div className="container max-w-4xl p-4 space-y-8">- {/* [Joshen TODO] Temporarily hidden until usage endpoint is sorted out */}- {/* {projectTier !== undefined && <OveragesBanner tier={projectTier} />} */}- <Subscription />- {loading ? (- <Loading active={loading}>- <div className="w-full mb-8 overflow-hidden border rounded border-panel-border-light dark:border-panel-border-dark">- <div className="flex items-center justify-center px-6 py-6 bg-panel-body-light dark:bg-panel-body-dark">- <p>Loading usage breakdown</p>- </div>- </div>- </Loading>- ) : (- <></>- )}- </div>- )-}diff --git a/studio/pages/project/[ref]/settings/billing/update/enterprise.tsx b/studio/pages/project/[ref]/settings/billing/update/enterprise.tsxdeleted file mode 100644index 07ed3f3ba42..00000000000--- a/studio/pages/project/[ref]/settings/billing/update/enterprise.tsx+++ /dev/null@@ -1,131 +0,0 @@-import { useState, useEffect } from 'react'-import { observer } from 'mobx-react-lite'-import { useRouter } from 'next/router'--import { useStore } from 'hooks'-import { NextPageWithLayout } from 'types'-import { API_URL, PRICING_TIER_PRODUCT_IDS } from 'lib/constants'-import { get } from 'lib/common/fetch'--import Connecting from 'components/ui/Loading/Loading'-import { BillingLayout } from 'components/layouts'-import { StripeSubscription } from 'components/interfaces/Billing'-import EnterpriseUpdate from 'components/interfaces/Billing/EnterpriseUpdate'--const BillingUpdateEnterprise: NextPageWithLayout = () => {- const { ui } = useStore()- const router = useRouter()-- const projectRef = ui.selectedProject?.ref- const orgSlug = ui.selectedOrganization?.slug-- const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(false)- const [subscription, setSubscription] = useState<StripeSubscription>()- const [products, setProducts] = useState<{ tiers: any[]; addons: any[] }>()- const [paymentMethods, setPaymentMethods] = useState<any>()-- const isEnterprise =- subscription && subscription.tier.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.ENTERPRISE-- useEffect(() => {- if (projectRef) {- getStripeProducts()- getSubscription()- }- }, [projectRef])-- useEffect(() => {- if (orgSlug) {- getPaymentMethods()- }- }, [orgSlug])-- useEffect(() => {- if (subscription && !isEnterprise) {- if (subscription.tier.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.TEAM) {- router.push(`/project/${projectRef}/settings/billing/update/team`)- } else if (- [PRICING_TIER_PRODUCT_IDS.PAYG, PRICING_TIER_PRODUCT_IDS.PRO].includes(- subscription.tier.supabase_prod_id- )- ) {- router.push(`/project/${projectRef}/settings/billing/update/pro`)- } else {- router.push(`/project/${projectRef}/settings/billing/update`)- }- }- }, [subscription, isEnterprise, projectRef, router])-- const getStripeProducts = async () => {- try {- const products = await get(`${API_URL}/stripe/products`)- setProducts(products)- } catch (error: any) {- ui.setNotification({- error,- category: 'error',- message: `Failed to get products: ${error.message}`,- })- }- }-- const getPaymentMethods = async () => {- const orgSlug = ui.selectedOrganization?.slug ?? ''- try {- setIsLoadingPaymentMethods(true)- const { data: paymentMethods, error } = await get(- `${API_URL}/organizations/${orgSlug}/payments`- )- if (error) throw error- setIsLoadingPaymentMethods(false)- setPaymentMethods(paymentMethods)- } catch (error: any) {- ui.setNotification({- error,- category: 'error',- message: `Failed to get available payment methods: ${error.message}`,- })- }- }-- const getSubscription = async () => {- try {- if (!ui.selectedProject?.subscription_id) {- throw new Error('Unable to get subscription ID of project')- }-- const subscription = await get(`${API_URL}/projects/${projectRef}/subscription`)- if (subscription.error) throw subscription.error-- setSubscription(subscription)- } catch (error: any) {- ui.setNotification({- error,- category: 'error',- message: `Failed to get subscription: ${error.message}`,- })- }- }-- if (!products || !subscription || !isEnterprise) {- return (- <div className="flex h-full w-full items-center justify-center">- <Connecting />- </div>- )- }-- return (- <EnterpriseUpdate- products={products}- currentSubscription={subscription}- isLoadingPaymentMethods={isLoadingPaymentMethods}- paymentMethods={paymentMethods || []}- onPaymentMethodAdded={() => getPaymentMethods()}- />- )-}--BillingUpdateEnterprise.getLayout = (page) => <BillingLayout>{page}</BillingLayout>--export default observer(BillingUpdateEnterprise)diff --git a/studio/pages/project/[ref]/settings/billing/update/free.tsx b/studio/pages/project/[ref]/settings/billing/update/free.tsxdeleted file mode 100644index 4a6f6205aa5..00000000000--- a/studio/pages/project/[ref]/settings/billing/update/free.tsx+++ /dev/null@@ -1,98 +0,0 @@-import { useState, useEffect } from 'react'-import { observer } from 'mobx-react-lite'-import { useRouter } from 'next/router'--import { NextPageWithLayout } from 'types'-import { useStore } from 'hooks'-import { get } from 'lib/common/fetch'-import { API_URL, PRICING_TIER_PRODUCT_IDS, STRIPE_PRODUCT_IDS } from 'lib/constants'--import { BillingLayout } from 'components/layouts'-import { ExitSurvey, StripeSubscription } from 'components/interfaces/Billing'-import Connecting from 'components/ui/Loading/Loading'--const BillingUpdateFree: NextPageWithLayout = () => {- const { ui } = useStore()- const router = useRouter()- const projectRef = ui.selectedProject?.ref-- const [products, setProducts] = useState<{ tiers: any[]; addons: any[] }>()- const [subscription, setSubscription] = useState<StripeSubscription>()-- const isEnterprise =- subscription && subscription.tier.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.ENTERPRISE-- useEffect(() => {- if (projectRef) {- getStripeProducts()- getSubscription()- }- }, [projectRef])-- useEffect(() => {- if (subscription?.tier?.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.ENTERPRISE) {- // no self-serve downgrade from Enterprise- router.push(`/project/${projectRef}/settings/billing/update/enterprise`)- } else if (subscription?.tier?.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.TEAM) {- // no self-serve downgrade from Team- router.push(`/project/${projectRef}/settings/billing/update/team`)- } else if (subscription?.tier?.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.FREE) {- // Downgrade from free to free is not possible, so let's redirect- router.push(`/project/${projectRef}/settings/billing/update`)- }- }, [subscription, projectRef, router])-- const getStripeProducts = async () => {- try {- const products = await get(`${API_URL}/stripe/products`)- setProducts(products)- } catch (error: any) {- ui.setNotification({- error,- category: 'error',- message: `Failed to get products: ${error.message}`,- })- }- }-- const getSubscription = async () => {- try {- if (!ui.selectedProject?.subscription_id) {- throw new Error('Unable to get subscription ID of project')- }-- const subscription = await get(`${API_URL}/projects/${projectRef}/subscription`)- if (subscription.error) throw subscription.error- setSubscription(subscription)- } catch (error: any) {- ui.setNotification({- error,- category: 'error',- message: `Failed to get subscription: ${error.message}`,- })- }- }-- const freeTier = products?.tiers.find((tier: any) => tier.id === STRIPE_PRODUCT_IDS.FREE)-- if (isEnterprise)- return (- <div className="flex h-full w-full items-center justify-center">- <Connecting />- </div>- )-- return (- <div className="mx-auto my-10 max-w-5xl px-32 xl:px-0">- <ExitSurvey- freeTier={freeTier}- subscription={subscription}- onSelectBack={() => router.push(`/project/${projectRef}/settings/billing/update`)}- />- </div>- )-}--BillingUpdateFree.getLayout = (page) => <BillingLayout>{page}</BillingLayout>--export default observer(BillingUpdateFree)diff --git a/studio/pages/project/[ref]/settings/billing/update/index.tsx b/studio/pages/project/[ref]/settings/billing/update/index.tsxdeleted file mode 100644index b1da19e8d66..00000000000--- a/studio/pages/project/[ref]/settings/billing/update/index.tsx+++ /dev/null@@ -1,191 +0,0 @@-import { useEffect, useState } from 'react'-import { useRouter } from 'next/router'-import { observer } from 'mobx-react-lite'-import { Button, Modal } from 'ui'--import { useStore } from 'hooks'-import { useFreeProjectLimitCheckQuery } from 'data/organizations/free-project-limit-check-query'-import { get } from 'lib/common/fetch'-import { API_URL, PRICING_TIER_PRODUCT_IDS, STRIPE_PRODUCT_IDS } from 'lib/constants'--import { BillingLayout } from 'components/layouts'-import ConfirmModal from 'components/ui/Dialogs/ConfirmDialog'-import { PlanSelection, StripeSubscription } from 'components/interfaces/Billing'-import Connecting from 'components/ui/Loading/Loading'-import { NextPageWithLayout } from 'types'--const BillingUpdate: NextPageWithLayout = () => {- const { ui } = useStore()- const router = useRouter()- const orgSlug = ui.selectedOrganization?.slug- const projectRef = ui.selectedProject?.ref-- const { data: membersExceededLimit } = useFreeProjectLimitCheckQuery({ slug: orgSlug })- const hasMembersExceedingFreeTierLimit = (membersExceededLimit || []).length > 0-- const [isLoadingProducts, setIsLoadingProducts] = useState(false)- const [showConfirmDowngrade, setShowConfirmDowngrade] = useState(false)- const [showDowngradeError, setShowDowngradeError] = useState(false)-- const [products, setProducts] = useState<{ tiers: any[]; addons: any[] }>()- const [subscription, setSubscription] = useState<StripeSubscription>()- const [selectedPlan, setSelectedPlan] = useState<any>()-- const isEnterprise = subscription?.tier?.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.ENTERPRISE-- useEffect(() => {- if (projectRef) {- getStripeProducts()- getSubscription()- }- }, [projectRef])-- useEffect(() => {- if (isEnterprise) {- router.push(`/project/${projectRef}/settings/billing/update/enterprise`)- }- }, [subscription])-- // [Joshen] Perhaps we shift this fetch into the global mobx tree- // Since all the pages require this data, makes more sense to load it once at the layout- const getStripeProducts = async () => {- try {- setIsLoadingProducts(true)- const products = await get(`${API_URL}/stripe/products`)- setProducts(products)- setIsLoadingProducts(false)- } catch (error: any) {- ui.setNotification({- error,- category: 'error',- message: `Failed to get products: ${error.message}`,- })- }- }-- const getSubscription = async () => {- try {- if (!ui.selectedProject?.subscription_id) {- throw new Error('Unable to get subscription ID of project')- }-- const subscription = await get(`${API_URL}/projects/${projectRef}/subscription`)- if (subscription.error) throw subscription.error-- setSubscription(subscription)- } catch (error: any) {- ui.setNotification({- error,- category: 'error',- message: `Failed to get subscription: ${error.message}`,- })- }- }-- const onSelectPlan = (plan: any) => {- if (plan.id === STRIPE_PRODUCT_IDS.PRO) {- router.push(`/project/${projectRef}/settings/billing/update/pro`)- } else if (plan.id === STRIPE_PRODUCT_IDS.TEAM) {- router.push(`/project/${projectRef}/settings/billing/update/team`)- } else if (plan.id === STRIPE_PRODUCT_IDS.FREE) {- setSelectedPlan(plan)- setShowConfirmDowngrade(true)- }- }-- const onConfirmDowngrade = () => {- if (hasMembersExceedingFreeTierLimit) {- setShowDowngradeError(true)- setShowConfirmDowngrade(false)- setSelectedPlan(undefined)- } else {- router.push(`/project/${projectRef}/settings/billing/update/free`)- }- }-- if (isLoadingProducts || isEnterprise) {- return (- <div className="flex items-center justify-center w-full h-full">- <Connecting />- </div>- )- }-- const productTiers = (products?.tiers ?? [])-- return (- <>- <div className={`mx-auto my-10 max-w-[90vw] xl:max-w-[80vw]`}>- <PlanSelection- visible={!selectedPlan || (selectedPlan && showConfirmDowngrade)}- tiers={productTiers}- currentPlan={subscription?.tier}- onSelectPlan={onSelectPlan}- />- </div>-- <ConfirmModal- danger- visible={showConfirmDowngrade}- title="Are you sure?"- description="Downgrading to the free plan will lead to reductions in your project’s capacity.- If you're already past the limits of the free plan, your project will be throttled greatly."- buttonLabel="Confirm"- buttonLoadingLabel="Confirm"- onSelectCancel={() => {- setShowConfirmDowngrade(false)- setSelectedPlan(undefined)- }}- onSelectConfirm={onConfirmDowngrade}- />-- <Modal- hideFooter- visible={showDowngradeError}- size="medium"- header="Your organization has members who have exceeded their free project limits"- onCancel={() => setShowDowngradeError(false)}- >- <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={() => setShowDowngradeError(false)}- block- >- Understood- </Button>- </div>- </Modal.Content>- </div>- </Modal>- </>- )-}--BillingUpdate.getLayout = (page) => <BillingLayout>{page}</BillingLayout>--export default observer(BillingUpdate)diff --git a/studio/pages/project/[ref]/settings/billing/update/pro.tsx b/studio/pages/project/[ref]/settings/billing/update/pro.tsxdeleted file mode 100644index 5bcb5c11768..00000000000--- a/studio/pages/project/[ref]/settings/billing/update/pro.tsx+++ /dev/null@@ -1,144 +0,0 @@-import { useState, useEffect } from 'react'-import { observer } from 'mobx-react-lite'-import { useRouter } from 'next/router'--import { useStore } from 'hooks'-import { get } from 'lib/common/fetch'-import { API_URL, PRICING_TIER_PRODUCT_IDS } from 'lib/constants'--import { NextPageWithLayout } from 'types'-import { BillingLayout } from 'components/layouts'-import Connecting from 'components/ui/Loading/Loading'-import { StripeSubscription } from 'components/interfaces/Billing'-import { ProUpgrade } from 'components/interfaces/Billing'-import { PaymentMethod } from 'components/interfaces/Billing/Billing.types'-import { SubscriptionAddon } from 'components/interfaces/Billing/AddOns/AddOns.types'--const BillingUpdatePro: NextPageWithLayout = () => {- const { ui } = useStore()- const router = useRouter()-- const projectRef = ui.selectedProject?.ref- const orgSlug = ui.selectedOrganization?.slug-- const [subscription, setSubscription] = useState<StripeSubscription>()- const [products, setProducts] = useState<{ tiers: any[]; addons: SubscriptionAddon[] }>()- const [paymentMethods, setPaymentMethods] = useState<PaymentMethod[]>()- const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(false)-- const isEnterprise =- subscription && subscription.tier.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.ENTERPRISE-- useEffect(() => {- // User added a new payment method- if (router.query.setup_intent && router.query.redirect_status) {- ui.setNotification({ category: 'success', message: 'Successfully added new payment method' })- }- }, [])-- useEffect(() => {- if (- subscription &&- ![PRICING_TIER_PRODUCT_IDS.PAYG, PRICING_TIER_PRODUCT_IDS.PRO].includes(- subscription.tier.supabase_prod_id- )- ) {- if (subscription.tier.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.ENTERPRISE) {- router.push(`/project/${projectRef}/settings/billing/update/enterprise`)- } else if (subscription.tier.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.TEAM) {- router.push(`/project/${projectRef}/settings/billing/update/team`)- }- }- }, [subscription, projectRef, router])-- useEffect(() => {- if (projectRef) {- getStripeProducts()- getSubscription()- }- }, [projectRef])-- useEffect(() => {- if (orgSlug) {- getPaymentMethods()- }- }, [orgSlug])-- useEffect(() => {- if (isEnterprise) {- router.push(`/project/${projectRef}/settings/billing/update/enterprise`)- }- }, [subscription])-- const getStripeProducts = async () => {- try {- const products = await get(`${API_URL}/stripe/products`)- setProducts(products)- } catch (error: any) {- ui.setNotification({- error,- category: 'error',- message: `Failed to get products: ${error.message}`,- })- }- }-- const getPaymentMethods = async () => {- const orgSlug = ui.selectedOrganization?.slug ?? ''- try {- setIsLoadingPaymentMethods(true)- const { data: paymentMethods, error } = await get(- `${API_URL}/organizations/${orgSlug}/payments`- )- if (error) throw error- setIsLoadingPaymentMethods(false)- setPaymentMethods(paymentMethods)- } catch (error: any) {- ui.setNotification({- error,- category: 'error',- message: `Failed to get available payment methods: ${error.message}`,- })- }- }-- const getSubscription = async () => {- try {- if (!ui.selectedProject?.subscription_id) {- throw new Error('Unable to get subscription ID of project')- }-- const subscription = await get(`${API_URL}/projects/${projectRef}/subscription`)- if (subscription.error) throw subscription.error- setSubscription(subscription)- } catch (error: any) {- ui.setNotification({- error,- category: 'error',- message: `Failed to get subscription: ${error.message}`,- })- }- }-- if (!products || !subscription || isEnterprise)- return (- <div className="flex h-full w-full items-center justify-center">- <Connecting />- </div>- )-- return (- <ProUpgrade- products={products}- currentSubscription={subscription}- isLoadingPaymentMethods={isLoadingPaymentMethods}- paymentMethods={paymentMethods || []}- onSelectBack={() => router.push(`/project/${projectRef}/settings/billing/update`)}- onPaymentMethodAdded={() => getPaymentMethods()}- />- )-}--BillingUpdatePro.getLayout = (page) => <BillingLayout>{page}</BillingLayout>--export default observer(BillingUpdatePro)diff --git a/studio/pages/project/[ref]/settings/billing/update/team.tsx b/studio/pages/project/[ref]/settings/billing/update/team.tsxdeleted file mode 100644index 31d04f8547b..00000000000--- a/studio/pages/project/[ref]/settings/billing/update/team.tsx+++ /dev/null@@ -1,140 +0,0 @@-import { useState, useEffect } from 'react'-import { observer } from 'mobx-react-lite'-import { useRouter } from 'next/router'--import { useStore } from 'hooks'-import { get } from 'lib/common/fetch'-import { API_URL, PRICING_TIER_PRODUCT_IDS } from 'lib/constants'--import { NextPageWithLayout } from 'types'-import { BillingLayout } from 'components/layouts'-import Connecting from 'components/ui/Loading/Loading'-import { StripeSubscription } from 'components/interfaces/Billing'-import { PaymentMethod } from 'components/interfaces/Billing/Billing.types'-import { SubscriptionAddon } from 'components/interfaces/Billing/AddOns/AddOns.types'-import TeamUpgrade from 'components/interfaces/Billing/TeamUpgrade'--const BillingUpdateTeam: NextPageWithLayout = () => {- const { ui } = useStore()- const router = useRouter()-- const projectRef = ui.selectedProject?.ref- const orgSlug = ui.selectedOrganization?.slug-- const [subscription, setSubscription] = useState<StripeSubscription>()- const [products, setProducts] = useState<{ tiers: any[]; addons: SubscriptionAddon[] }>()- const [paymentMethods, setPaymentMethods] = useState<PaymentMethod[]>()- const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(false)-- const isEnterprise =- subscription && subscription.tier.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.ENTERPRISE-- useEffect(() => {- // User added a new payment method- if (router.query.setup_intent && router.query.redirect_status) {- ui.setNotification({ category: 'success', message: 'Successfully added new payment method' })- }- }, [])-- useEffect(() => {- if (projectRef) {- getStripeProducts()- getSubscription()- }- }, [projectRef])-- useEffect(() => {- if (orgSlug) {- getPaymentMethods()- }- }, [orgSlug])-- useEffect(() => {- if (subscription?.tier?.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.ENTERPRISE) {- router.push(`/project/${projectRef}/settings/billing/update/enterprise`)- } else if (- subscription &&- [PRICING_TIER_PRODUCT_IDS.PAYG, PRICING_TIER_PRODUCT_IDS.PRO].includes(- subscription.tier.supabase_prod_id- )- ) {- router.push(`/project/${projectRef}/settings/billing/update/pro`)- } else if (- subscription &&- subscription.tier.supabase_prod_id !== PRICING_TIER_PRODUCT_IDS.TEAM- ) {- router.push(`/project/${projectRef}/settings/billing/update`)- }- }, [subscription, projectRef, router])-- const getStripeProducts = async () => {- try {- const products = await get(`${API_URL}/stripe/products`)- setProducts(products)- } catch (error: any) {- ui.setNotification({- error,- category: 'error',- message: `Failed to get products: ${error.message}`,- })- }- }-- const getPaymentMethods = async () => {- const orgSlug = ui.selectedOrganization?.slug ?? ''- try {- setIsLoadingPaymentMethods(true)- const { data: paymentMethods, error } = await get(- `${API_URL}/organizations/${orgSlug}/payments`- )- if (error) throw error- setIsLoadingPaymentMethods(false)- setPaymentMethods(paymentMethods)- } catch (error: any) {- ui.setNotification({- error,- category: 'error',- message: `Failed to get available payment methods: ${error.message}`,- })- }- }-- const getSubscription = async () => {- try {- if (!ui.selectedProject?.subscription_id) {- throw new Error('Unable to get subscription ID of project')- }-- const subscription = await get(`${API_URL}/projects/${projectRef}/subscription`)- if (subscription.error) throw subscription.error- setSubscription(subscription)- } catch (error: any) {- ui.setNotification({- error,- category: 'error',- message: `Failed to get subscription: ${error.message}`,- })- }- }-- if (!products || !subscription || isEnterprise)- return (- <div className="flex h-full w-full items-center justify-center">- <Connecting />- </div>- )-- return (- <TeamUpgrade- products={products}- currentSubscription={subscription}- isLoadingPaymentMethods={isLoadingPaymentMethods}- paymentMethods={paymentMethods || []}- onPaymentMethodAdded={() => getPaymentMethods()}- />- )-}--BillingUpdateTeam.getLayout = (page) => <BillingLayout>{page}</BillingLayout>--export default observer(BillingUpdateTeam)diff --git a/studio/tests/components/Home/ProjectUsage.test.js b/studio/tests/components/Home/ProjectUsage.test.jsindex 9884fb1feae..d81320bb7dd 100644--- a/studio/tests/components/Home/ProjectUsage.test.js+++ b/studio/tests/components/Home/ProjectUsage.test.js@@ -32,10 +32,10 @@ ProjectUsage.mockImplementation((props) => {)})-jest.mock('data/subscriptions/project-subscription-query')-import { useProjectSubscriptionQuery } from 'data/subscriptions/project-subscription-query'+jest.mock('data/subscriptions/project-subscription-v2-query')+import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'-useProjectSubscriptionQuery.mockReturnValue({+useProjectSubscriptionV2Query.mockReturnValue({data: undefined,})diff --git a/studio/tests/pages/projects/LogsPreviewer.test.js b/studio/tests/pages/projects/LogsPreviewer.test.jsindex ceb210b9e17..eedba9ead18 100644--- a/studio/tests/pages/projects/LogsPreviewer.test.js+++ b/studio/tests/pages/projects/LogsPreviewer.test.js@@ -16,7 +16,7 @@ const defaultRouterMock = () => {useRouter.mockReturnValue(defaultRouterMock())import LogsPreviewer from 'components/interfaces/Settings/Logs/LogsPreviewer'-import { useProjectSubscriptionQuery } from 'data/subscriptions/project-subscription-query'+import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'import { fireEvent, waitFor, screen, act } from '@testing-library/react'import { render } from '../../helpers'import userEvent from '@testing-library/user-event'@@ -87,22 +87,22 @@ test.each([queryType: 'auth',tableName: undefined,tableLog: logDataFixture({- event_message: "some event_message",- level: "info",+ event_message: 'some event_message',+ level: 'info',path: '/auth-path',msg: 'some metadata_msg',level: 'info',status: 300,- metadata: undefined+ metadata: undefined,}),selectionLog: logDataFixture({- event_message: "some event_message",+ event_message: 'some event_message',metadata: {msg: 'some metadata_msg',path: '/auth-path',level: 'info',status: 300,- }+ },}),tableTexts: [/auth\-path/, /some metadata_msg/, /INFO/],selectionTexts: [@@ -451,13 +451,12 @@ test('filters accept filterOverride', async () => {})})-describe.each(['FREE', 'PRO', 'TEAM', 'ENTERPRISE'])('upgrade modal for %s', (key) => {+describe.each(['free', 'pro', 'team', 'enterprise'])('upgrade modal for %s', (key) => {beforeEach(() => {- useProjectSubscriptionQuery.mockReturnValue({+ useProjectSubscriptionV2Query.mockReturnValue({data: {- tier: {- supabase_prod_id: `tier_${key.toLocaleLowerCase()}`,- key,+ plan: {+ id: key,},},})diff --git a/studio/tests/pages/projects/logs-query.test.js b/studio/tests/pages/projects/logs-query.test.jsindex 1a8ddab8720..edb1c28c0f3 100644--- a/studio/tests/pages/projects/logs-query.test.js+++ b/studio/tests/pages/projects/logs-query.test.js@@ -7,7 +7,7 @@ import userEvent from '@testing-library/user-event'import { logDataFixture } from '../../fixtures'import { clickDropdown } from 'tests/helpers'import dayjs from 'dayjs'-import { useProjectSubscriptionQuery } from 'data/subscriptions/project-subscription-query'+import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'jest.mock('common/hooks')import { useParams } from 'common/hooks'@@ -220,13 +220,12 @@ test('field reference', async () => {await screen.findByText('metadata.request.cf.asOrganization')})-describe.each(['FREE', 'PRO', 'TEAM', 'ENTERPRISE'])('upgrade modal for %s', (key) => {+describe.each(['free', 'pro', 'team', 'enterprise'])('upgrade modal for %s', (key) => {beforeEach(() => {- useProjectSubscriptionQuery.mockReturnValue({+ useProjectSubscriptionV2Query.mockReturnValue({data: {- tier: {- supabase_prod_id: `tier_${key.toLocaleLowerCase()}`,- key,+ plan: {+ id: key,},},})@@ -255,7 +254,7 @@ describe.each(['FREE', 'PRO', 'TEAM', 'ENTERPRISE'])('upgrade modal for %s', (ke})// only free plan will show modal- if (key === 'FREE') {+ if (key === 'free') {await screen.findByText('Log retention') // assert modal title is present} else {await expect(screen.findByText('Log retention')).rejects.toThrow()