Skip to content

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

feat: preview costs for Pro/Team plan change

Kevin Grüneberg794d26c8c912
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx
index 9ec255913b8..fd13a6dc6e2 100644
--- a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/PlanUpdateSidePanel.tsx
@@ -7,7 +7,10 @@ import { useEffect, useState } from 'react'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useOrgPlansQuery } from 'data/subscriptions/org-plans-query'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
-import { SubscriptionTier, useOrgSubscriptionUpdateMutation } from 'data/subscriptions/org-subscription-update-mutation'
+import {
+ SubscriptionTier,
+ useOrgSubscriptionUpdateMutation,
+} from 'data/subscriptions/org-subscription-update-mutation'
import { useCheckPermissions, useSelectedOrganization, useStore } from 'hooks'
import { PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
import Telemetry from 'lib/telemetry'
@@ -21,6 +24,9 @@ import ExitSurveyModal from './ExitSurveyModal'
import MembersExceedLimitModal from './MembersExceedLimitModal'
import PaymentMethodSelection from './PaymentMethodSelection'
import { useFreeProjectLimitCheckQuery } from 'data/organizations/free-project-limit-check-query'
+import { useOrganizationBillingSubscriptionPreview } from 'data/organizations/organization-billing-subscription-preview'
+import InformationBox from 'components/ui/InformationBox'
+import AlertError from 'components/ui/AlertError'
// [Joshen TODO] Need to remove all contexts of "projects"
@@ -68,12 +74,16 @@ const PlanUpdateSidePanel = () => {
}
)
+ const {
+ data: subscriptionPreview,
+ error: subscriptionPreviewError,
+ isLoading: subscriptionPreviewIsLoading,
+ isSuccess: subscriptionPreviewInitialized,
+ } = useOrganizationBillingSubscriptionPreview({ tier: selectedTier, organizationSlug: slug })
+
const availablePlans = plans ?? []
const hasMembersExceedingFreeTierLimit = (membersExceededLimit || []).length > 0
const subscriptionPlanMeta = subscriptionsPlans.find((tier) => tier.id === selectedTier)
- const selectedPlanMeta = availablePlans.find(
- (plan) => plan.id === selectedTier?.split('tier_')[1]
- )
useEffect(() => {
if (visible) {
@@ -110,13 +120,18 @@ const PlanUpdateSidePanel = () => {
return ui.setNotification({ category: 'error', message: 'Please select a payment method' })
}
- // If the user is downgrading from team, should have spend cap disabled by default
- const tier = subscription?.plan?.id === 'team' && selectedTier === PRICING_TIER_PRODUCT_IDS.PRO ? PRICING_TIER_PRODUCT_IDS.PAYG as SubscriptionTier : selectedTier
+ // If the user is downgrading from team, should have spend cap disabled by default
+ const tier =
+ subscription?.plan?.id === 'team' && selectedTier === PRICING_TIER_PRODUCT_IDS.PRO
+ ? (PRICING_TIER_PRODUCT_IDS.PAYG as SubscriptionTier)
+ : selectedTier
updateOrgSubscription({ slug, tier, paymentMethod: selectedPaymentMethod })
}
- const planMeta = selectedTier ? availablePlans.find((p) => p.id === selectedTier.split('tier_')[1]) : null
+ const planMeta = selectedTier
+ ? availablePlans.find((p) => p.id === selectedTier.split('tier_')[1])
+ : null
return (
<>
@@ -289,25 +304,101 @@ const PlanUpdateSidePanel = () => {
<Modal
loading={isUpdating}
alignFooter="right"
- className="!w-[450px]"
+ className="!w-[550px]"
visible={selectedTier !== undefined && selectedTier !== 'tier_free'}
onCancel={() => setSelectedTier(undefined)}
onConfirm={onUpdateSubscription}
overlayClassName="pointer-events-none"
- header={`Confirm ${planMeta?.change_type === 'downgrade' ? 'downgrade' : 'upgrade'} to ${subscriptionPlanMeta?.name}`}
+ header={`Confirm ${planMeta?.change_type === 'downgrade' ? 'downgrade' : 'upgrade'} to ${
+ subscriptionPlanMeta?.name
+ }`}
>
+ <Modal.Content className="mt-4">
+ {subscriptionPreviewError && (
+ <AlertError
+ error={subscriptionPreviewError}
+ subject="Failed to preview subscription."
+ />
+ )}
+ {subscriptionPreviewIsLoading && (
+ <span className="text-sm">Estimating monthly costs...</span>
+ )}
+ {subscriptionPreviewInitialized && (
+ <InformationBox
+ defaultVisibility={false}
+ title={
+ <span>
+ Estimated monthly price is $
+ {Math.round(
+ subscriptionPreview.breakdown.reduce((prev, cur) => prev + cur.total_price, 0)
+ )}{' '}
+ + usage
+ </span>
+ }
+ hideCollapse={false}
+ description={
+ <div>
+ <table className="w-full">
+ <thead>
+ <tr className="border-b">
+ <th className="py-2 font-normal text-left text-sm text-scale-1000 w-1/2">
+ Item
+ </th>
+ <th className="py-2 font-normal text-left text-sm text-scale-1000">
+ Count
+ </th>
+ <th className="py-2 font-normal text-left text-sm text-scale-1000">
+ Unit Price
+ </th>
+ <th className="py-2 font-normal text-right text-sm text-scale-1000">
+ Price
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {subscriptionPreview.breakdown.map((item) => (
+ <tr key={item.description} className="border-b">
+ <td className="py-2 text-sm">{item.description ?? 'Unknown'}</td>
+ <td className="py-2 text-sm">{item.quantity}</td>
+ <td className="py-2 text-sm">
+ {item.unit_price === 0 ? 'FREE' : `$${item.unit_price}`}
+ </td>
+ <td className="py-2 text-sm text-right">${item.total_price}</td>
+ </tr>
+ ))}
+ </tbody>
+
+ <tbody>
+ <tr>
+ <td className="py-2 text-sm">Total</td>
+ <td className="py-2 text-sm" />
+ <td className="py-2 text-sm" />
+ <td className="py-2 text-sm text-right">
+ $
+ {Math.round(
+ subscriptionPreview.breakdown.reduce(
+ (prev, cur) => prev + cur.total_price,
+ 0
+ )
+ ) ?? 0}
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ }
+ />
+ )}
+ </Modal.Content>
+
<Modal.Content>
- <div className="py-6 space-y-2">
+ <div className="py-4 space-y-2">
<p className="text-sm">
- Upon clicking confirm, the amount of ${selectedPlanMeta?.price ?? 'Unknown'} will be
- added to your monthly invoice and your credit card will be charged immediately.
- Changing the plan resets your billing cycle and may result in a prorated charge for
- previous usage.
- </p>
- <p className="text-sm text-scale-1000">
- You will also be able to change your project's add-ons after upgrading your plan.
+ Upon clicking confirm, your monthly invoice will be adjusted and your credit card will
+ be charged immediately. Changing the plan resets your billing cycle and may result in
+ a prorated charge for previous usage.
</p>
- <div className="!mt-6">
+ <div className="!mt-4">
<PaymentMethodSelection
selectedPaymentMethod={selectedPaymentMethod}
onSelectPaymentMethod={setSelectedPaymentMethod}
diff --git a/studio/data/api.d.ts b/studio/data/api.d.ts
index 30c7c2551c9..eaeca12f7e9 100644
--- a/studio/data/api.d.ts
+++ b/studio/data/api.d.ts
@@ -214,9 +214,13 @@ export interface paths {
"/platform/organizations/{slug}/billing/subscription": {
/** Gets the current subscription */
get: operations["SubscriptionController_getSubscription"];
- /** Updates subscription */
+ /** Previews subscription change */
put: operations["SubscriptionController_updateSubscription"];
};
+ "/platform/organizations/{slug}/billing/subscription/preview": {
+ /** Updates subscription */
+ post: operations["SubscriptionController_previewSubscriptionChange"];
+ };
"/platform/organizations/{slug}/billing/plans": {
/** Gets subscription plans */
get: operations["OrgPlansController_getAvailablePlans"];
@@ -1818,6 +1822,8 @@ export interface components {
SMS_PROVIDER?: string;
SMS_MESSAGEBIRD_ACCESS_KEY?: string;
SMS_MESSAGEBIRD_ORIGINATOR?: string;
+ SMS_TEST_OTP?: string;
+ SMS_TEST_OTP_VALID_UNTIL?: string;
SMS_TEXTLOCAL_API_KEY?: string;
SMS_TEXTLOCAL_SENDER?: string;
SMS_TWILIO_ACCOUNT_SID?: string;
@@ -5463,6 +5469,26 @@ export interface operations {
500: never;
};
};
+ /** Updates subscription */
+ SubscriptionController_previewSubscriptionChange: {
+ parameters: {
+ path: {
+ /** @description Organization slug */
+ slug: string;
+ };
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["UpdateSubscriptionBody"];
+ };
+ };
+ responses: {
+ 201: never;
+ 403: never;
+ /** @description Failed to update subscription */
+ 500: never;
+ };
+ };
/** Gets subscription plans */
OrgPlansController_getAvailablePlans: {
parameters: {
diff --git a/studio/data/organizations/keys.ts b/studio/data/organizations/keys.ts
index f4ef5c59c67..49adb032d49 100644
--- a/studio/data/organizations/keys.ts
+++ b/studio/data/organizations/keys.ts
@@ -14,6 +14,8 @@ export const organizationKeys = {
migrateBilling: (slug: string | undefined) => ['organizations', slug, 'migrate-billing'] as const,
migrateBillingPreview: (slug: string | undefined) =>
['organizations', slug, 'migrate-billing', 'preview'] as const,
+ subscriptionPreview: (slug: string | undefined, tier: string | undefined) =>
+ ['organizations', slug, 'subscription', 'preview', tier] as const,
taxIds: (slug: string | undefined) => ['organizations', slug, 'tax-ids'] as const,
tokenValidation: (slug: string | undefined, token: string | undefined) =>
['organizations', slug, 'validate-token', token] as const,
diff --git a/studio/data/organizations/organization-billing-subscription-preview.ts b/studio/data/organizations/organization-billing-subscription-preview.ts
new file mode 100644
index 00000000000..8c9068d9322
--- /dev/null
+++ b/studio/data/organizations/organization-billing-subscription-preview.ts
@@ -0,0 +1,80 @@
+import { useQuery, UseQueryOptions } from '@tanstack/react-query'
+import { post } from 'data/fetchers'
+import { organizationKeys } from './keys'
+import { ResponseError } from 'types'
+
+export type OrganizationBillingSubscriptionPreviewVariables = {
+ organizationSlug?: string
+ tier?: 'tier_payg' | 'tier_pro' | 'tier_free' | 'tier_team' | 'tier_enterprise'
+}
+
+export type OrganizationBillingSubscriptionPreviewResponse = {
+ breakdown: {
+ description: string
+ unit_price: number
+ quantity: number
+ total_price: number
+ }[]
+}
+
+export async function previewOrganizationBillingSubscription({
+ organizationSlug,
+ tier,
+}: OrganizationBillingSubscriptionPreviewVariables) {
+ if (!organizationSlug) throw new Error('organizationSlug is required')
+ if (!tier) throw new Error('tier is required')
+
+ const { data, error } = await post(
+ `/platform/organizations/{slug}/billing/subscription/preview`,
+ {
+ params: { path: { slug: organizationSlug } },
+ body: {
+ tier,
+ },
+ }
+ )
+
+ if (error) throw error
+
+ return data as OrganizationBillingSubscriptionPreviewResponse
+}
+
+export type OrganizationBillingSubscriptionPreviewData = Awaited<
+ ReturnType<typeof previewOrganizationBillingSubscription>
+>
+
+export const useOrganizationBillingSubscriptionPreview = <
+ TData = OrganizationBillingSubscriptionPreviewData
+>(
+ { organizationSlug, tier }: OrganizationBillingSubscriptionPreviewVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseQueryOptions<OrganizationBillingSubscriptionPreviewData, ResponseError, TData> = {}
+) =>
+ useQuery<OrganizationBillingSubscriptionPreviewData, ResponseError, TData>(
+ organizationKeys.subscriptionPreview(organizationSlug, tier),
+ () => previewOrganizationBillingSubscription({ organizationSlug, tier }),
+ {
+ enabled: enabled && typeof organizationSlug !== 'undefined' && typeof tier !== 'undefined',
+ ...options,
+
+ retry: (failureCount, error) => {
+ // Don't retry on 400s
+ if (
+ typeof error === 'object' &&
+ error !== null &&
+ 'code' in error &&
+ (error as any).code === 400
+ ) {
+ return false
+ }
+
+ if (failureCount < 3) {
+ return true
+ }
+
+ return false
+ },
+ }
+ )