Skip to content

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

feat: support pending changes for plan upgrades (#36430)

Kevin Grünebergdff6074d3076
diff --git a/apps/studio/components/interfaces/Billing/Subscription/Subscription.utils.ts b/apps/studio/components/interfaces/Billing/Subscription/Subscription.utils.ts
index 2d8af813fde..ece737507d6 100644
--- a/apps/studio/components/interfaces/Billing/Subscription/Subscription.utils.ts
+++ b/apps/studio/components/interfaces/Billing/Subscription/Subscription.utils.ts
@@ -1,4 +1,4 @@
-import type { OrgSubscription, ProjectSelectedAddon } from 'data/subscriptions/types'
+import type { OrgSubscription, PlanId, ProjectSelectedAddon } from 'data/subscriptions/types'
import { IS_PLATFORM } from 'lib/constants'
export const getAddons = (selectedAddons: ProjectSelectedAddon[]) => {
@@ -32,3 +32,43 @@ export const billingPartnerLabel = (billingPartner?: string) => {
return billingPartner
}
}
+
+type PlanChangeType = 'upgrade' | 'downgrade' | 'none'
+
+export const getPlanChangeType = (
+ fromPlan: PlanId | undefined,
+ toPlan: PlanId | undefined
+): PlanChangeType => {
+ const planChangeTypes: Record<PlanId, Record<PlanId, PlanChangeType>> = {
+ free: {
+ free: 'none',
+ pro: 'upgrade',
+ team: 'upgrade',
+ enterprise: 'upgrade',
+ },
+ pro: {
+ free: 'downgrade',
+ pro: 'none',
+ team: 'upgrade',
+ enterprise: 'upgrade',
+ },
+ team: {
+ free: 'downgrade',
+ pro: 'downgrade',
+ team: 'none',
+ enterprise: 'upgrade',
+ },
+ enterprise: {
+ free: 'downgrade',
+ pro: 'downgrade',
+ team: 'downgrade',
+ enterprise: 'none',
+ },
+ }
+
+ if (!fromPlan || !toPlan) {
+ return 'none'
+ }
+
+ return planChangeTypes[fromPlan]?.[toPlan] ?? 'none'
+}
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/CreditTopUp.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/CreditTopUp.tsx
index c3edcba0847..a2e71206e62 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/CreditTopUp.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/CreditTopUp.tsx
@@ -252,8 +252,10 @@ export const CreditTopUp = ({ slug }: { slug: string | undefined }) => {
name="paymentMethod"
render={() => (
<PaymentMethodSelection
+ createPaymentMethodInline={false}
onSelectPaymentMethod={(pm) => form.setValue('paymentMethod', pm)}
selectedPaymentMethod={form.getValues('paymentMethod')}
+ readOnly={executingTopUp || paymentConfirmationLoading}
/>
)}
/>
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/PaymentMethods/NewPaymentMethodElement.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/PaymentMethods/NewPaymentMethodElement.tsx
index 0578878093a..5123b3bca2c 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/PaymentMethods/NewPaymentMethodElement.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/PaymentMethods/NewPaymentMethodElement.tsx
@@ -15,7 +15,8 @@ const NewPaymentMethodElement = forwardRef(
{
pending_subscription_flow_enabled,
email,
- }: { pending_subscription_flow_enabled: boolean; email?: string },
+ readOnly,
+ }: { pending_subscription_flow_enabled: boolean; email?: string; readOnly: boolean },
ref
) => {
const stripe = useStripe()
@@ -58,7 +59,7 @@ const NewPaymentMethodElement = forwardRef(
createPaymentMethod,
}))
- return <PaymentElement options={{ defaultValues: { billingDetails: { email } } }} />
+ return <PaymentElement options={{ defaultValues: { billingDetails: { email } }, readOnly }} />
}
)
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/DowngradeModal.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/DowngradeModal.tsx
index 94e7f2f1bdb..91a3e3ceb7c 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/DowngradeModal.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/DowngradeModal.tsx
@@ -5,10 +5,11 @@ import type { OrgSubscription, ProjectAddon } from 'data/subscriptions/types'
import { PricingInformation } from 'shared-data'
import { Modal } from 'ui'
import { Admonition } from 'ui-patterns'
+import { plans as subscriptionsPlans } from 'shared-data/plans'
+import { useMemo } from 'react'
export interface DowngradeModalProps {
visible: boolean
- selectedPlan?: PricingInformation
subscription?: OrgSubscription
onClose: () => void
onConfirm: () => void
@@ -50,12 +51,13 @@ const ProjectDowngradeListItem = ({ projectAddon }: { projectAddon: ProjectAddon
const DowngradeModal = ({
visible,
- selectedPlan,
subscription,
onClose,
onConfirm,
projects,
}: DowngradeModalProps) => {
+ const selectedPlan = useMemo(() => subscriptionsPlans.find((tier) => tier.id === 'tier_free'), [])
+
// Filter out the micro addon as we're dealing with that separately
const previousProjectAddons =
subscription?.project_addons.flatMap((projectAddons) => {
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PaymentMethodSelection.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PaymentMethodSelection.tsx
index 0555c36687d..85441004f95 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PaymentMethodSelection.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PaymentMethodSelection.tsx
@@ -1,5 +1,13 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useEffect, useState } from 'react'
+import {
+ forwardRef,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState,
+} from 'react'
import { toast } from 'sonner'
import AddNewPaymentMethodModal from 'components/interfaces/Billing/Payment/AddNewPaymentMethodModal'
@@ -7,25 +15,51 @@ import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useOrganizationPaymentMethodsQuery } from 'data/organizations/organization-payment-methods-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
-import { BASE_PATH } from 'lib/constants'
+import { BASE_PATH, STRIPE_PUBLIC_KEY } from 'lib/constants'
import { getURL } from 'lib/helpers'
import { AlertCircle, CreditCard, Loader, Plus } from 'lucide-react'
import { Listbox } from 'ui'
+import HCaptcha from '@hcaptcha/react-hcaptcha'
+import { useIsHCaptchaLoaded } from 'stores/hcaptcha-loaded-store'
+import { useOrganizationPaymentMethodSetupIntent } from 'data/organizations/organization-payment-method-setup-intent-mutation'
+import { SetupIntentResponse } from 'data/stripe/setup-intent-mutation'
+import { loadStripe, PaymentMethod, StripeElementsOptions } from '@stripe/stripe-js'
+import { getStripeElementsAppearanceOptions } from 'components/interfaces/Billing/Payment/Payment.utils'
+import { useTheme } from 'next-themes'
+import { Elements } from '@stripe/react-stripe-js'
+import { NewPaymentMethodElement } from '../PaymentMethods/NewPaymentMethodElement'
+import ShimmeringLoader from 'ui-patterns/ShimmeringLoader'
+
+const stripePromise = loadStripe(STRIPE_PUBLIC_KEY)
export interface PaymentMethodSelectionProps {
selectedPaymentMethod?: string
onSelectPaymentMethod: (id: string) => void
layout?: 'vertical' | 'horizontal'
+ createPaymentMethodInline: boolean
+ readOnly: boolean
}
-const PaymentMethodSelection = ({
- selectedPaymentMethod,
- onSelectPaymentMethod,
- layout = 'vertical',
-}: PaymentMethodSelectionProps) => {
+const PaymentMethodSelection = forwardRef(function PaymentMethodSelection(
+ {
+ selectedPaymentMethod,
+ onSelectPaymentMethod,
+ layout = 'vertical',
+ createPaymentMethodInline = false,
+ readOnly,
+ }: PaymentMethodSelectionProps,
+ ref
+) {
const selectedOrganization = useSelectedOrganization()
const slug = selectedOrganization?.slug
const [showAddNewPaymentMethodModal, setShowAddNewPaymentMethodModal] = useState(false)
+ const captchaLoaded = useIsHCaptchaLoaded()
+ const [captchaToken, setCaptchaToken] = useState<string | null>(null)
+ const [captchaRef, setCaptchaRef] = useState<HCaptcha | null>(null)
+ const [setupIntent, setSetupIntent] = useState<SetupIntentResponse | undefined>(undefined)
+ const { resolvedTheme } = useTheme()
+ const paymentRef = useRef<{ createPaymentMethod: () => Promise<PaymentMethod | undefined> }>(null)
+ const [setupNewPaymentMethod, setSetupNewPaymentMethod] = useState<boolean | null>(null)
const {
data: paymentMethods,
@@ -33,11 +67,77 @@ const PaymentMethodSelection = ({
refetch: refetchPaymentMethods,
} = useOrganizationPaymentMethodsQuery({ slug })
+ const captchaRefCallback = useCallback((node: any) => {
+ setCaptchaRef(node)
+ }, [])
+
+ const { mutate: initSetupIntent, isLoading: setupIntentLoading } =
+ useOrganizationPaymentMethodSetupIntent({
+ onSuccess: (intent) => {
+ setSetupIntent(intent)
+ },
+ onError: (error) => {
+ toast.error(`Failed to setup intent: ${error.message}`)
+ },
+ })
+
+ useEffect(() => {
+ if (paymentMethods?.data && paymentMethods.data.length === 0 && setupNewPaymentMethod == null) {
+ setSetupNewPaymentMethod(true)
+ }
+ }, [paymentMethods])
+
+ useEffect(() => {
+ const loadSetupIntent = async (hcaptchaToken: string | undefined) => {
+ const slug = selectedOrganization?.slug
+ if (!slug) return console.error('Slug is required')
+ if (!hcaptchaToken) return console.error('HCaptcha token required')
+
+ setSetupIntent(undefined)
+ initSetupIntent({ slug: slug!, hcaptchaToken })
+ }
+
+ const loadPaymentForm = async () => {
+ if (setupNewPaymentMethod && createPaymentMethodInline && captchaRef && captchaLoaded) {
+ let token = captchaToken
+
+ try {
+ if (!token) {
+ const captchaResponse = await captchaRef.execute({ async: true })
+ token = captchaResponse?.response ?? null
+ }
+ } catch (error) {
+ return
+ }
+
+ await loadSetupIntent(token ?? undefined)
+ resetCaptcha()
+ }
+ }
+
+ loadPaymentForm()
+ }, [createPaymentMethodInline, captchaRef, captchaLoaded, setupNewPaymentMethod])
+
+ const resetCaptcha = () => {
+ setCaptchaToken(null)
+ captchaRef?.resetCaptcha()
+ }
+
const canUpdatePaymentMethods = useCheckPermissions(
PermissionAction.BILLING_WRITE,
'stripe.payment_methods'
)
+ const stripeOptionsPaymentMethod: StripeElementsOptions = useMemo(
+ () =>
+ ({
+ clientSecret: setupIntent ? setupIntent.client_secret! : '',
+ appearance: getStripeElementsAppearanceOptions(resolvedTheme),
+ paymentMethodCreation: 'manual',
+ }) as const,
+ [setupIntent, resolvedTheme]
+ )
+
useEffect(() => {
if (paymentMethods?.data && paymentMethods.data.length > 0) {
const selectedPaymentMethodExists = paymentMethods.data.some(
@@ -55,15 +155,49 @@ const PaymentMethodSelection = ({
}
}, [selectedPaymentMethod, paymentMethods, onSelectPaymentMethod])
+ // If createPaymentMethod already exists, use it. Otherwise, define it here.
+ const createPaymentMethod = async () => {
+ if (setupNewPaymentMethod || (paymentMethods?.data && paymentMethods.data.length === 0)) {
+ return paymentRef.current?.createPaymentMethod()
+ } else {
+ return { id: selectedPaymentMethod }
+ }
+ }
+
+ useImperativeHandle(ref, () => ({
+ createPaymentMethod,
+ }))
+
return (
<>
+ <HCaptcha
+ ref={captchaRefCallback}
+ sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY!}
+ size="invisible"
+ onOpen={() => {
+ // [Joshen] This is to ensure that hCaptcha popup remains clickable
+ if (document !== undefined) document.body.classList.add('!pointer-events-auto')
+ }}
+ onClose={() => {
+ setSetupIntent(undefined)
+ if (document !== undefined) document.body.classList.remove('!pointer-events-auto')
+ }}
+ onVerify={(token) => {
+ setCaptchaToken(token)
+ if (document !== undefined) document.body.classList.remove('!pointer-events-auto')
+ }}
+ onExpire={() => {
+ setCaptchaToken(null)
+ }}
+ />
+
<div>
{isLoading ? (
<div className="flex items-center px-4 py-2 space-x-4 border rounded-md border-strong bg-surface-200">
<Loader className="animate-spin" size={14} />
<p className="text-sm text-foreground-light">Retrieving payment methods</p>
</div>
- ) : paymentMethods?.data.length === 0 ? (
+ ) : paymentMethods?.data.length === 0 && !createPaymentMethodInline ? (
<div className="flex items-center justify-between px-4 py-2 border border-dashed rounded-md bg-alternative">
<div className="flex items-center space-x-4 text-foreground-light">
<AlertCircle size={16} strokeWidth={1.5} />
@@ -74,7 +208,13 @@ const PaymentMethodSelection = ({
type="default"
disabled={!canUpdatePaymentMethods}
icon={<CreditCard />}
- onClick={() => setShowAddNewPaymentMethodModal(true)}
+ onClick={() => {
+ if (createPaymentMethodInline) {
+ setSetupNewPaymentMethod(true)
+ } else {
+ setShowAddNewPaymentMethodModal(true)
+ }
+ }}
htmlType="button"
tooltip={{
content: {
@@ -93,7 +233,7 @@ const PaymentMethodSelection = ({
Add new
</ButtonTooltip>
</div>
- ) : (
+ ) : paymentMethods?.data && paymentMethods?.data.length > 0 && !setupNewPaymentMethod ? (
<Listbox
layout={layout}
label="Payment method"
@@ -126,7 +266,13 @@ const PaymentMethodSelection = ({
})}
<div
className="flex items-center px-3 py-2 space-x-2 transition cursor-pointer group hover:bg-surface-300"
- onClick={() => setShowAddNewPaymentMethodModal(true)}
+ onClick={() => {
+ if (createPaymentMethodInline) {
+ setSetupNewPaymentMethod(true)
+ } else {
+ setShowAddNewPaymentMethodModal(true)
+ }
+ }}
>
<Plus size={16} />
<p className="transition text-foreground-light group-hover:text-foreground">
@@ -134,6 +280,28 @@ const PaymentMethodSelection = ({
</p>
</div>
</Listbox>
+ ) : null}
+
+ {stripePromise && setupIntent && (
+ <Elements stripe={stripePromise} options={stripeOptionsPaymentMethod}>
+ <NewPaymentMethodElement
+ ref={paymentRef}
+ pending_subscription_flow_enabled={true}
+ email={selectedOrganization?.billing_email}
+ readOnly={readOnly}
+ />
+ </Elements>
+ )}
+
+ {setupIntentLoading && (
+ <div className="space-y-2">
+ <ShimmeringLoader className="h-10" />
+ <div className="grid grid-cols-2 gap-4">
+ <ShimmeringLoader className="h-10" />
+ <ShimmeringLoader className="h-10" />
+ </div>
+ <ShimmeringLoader className="h-10" />
+ </div>
)}
</div>
@@ -158,6 +326,8 @@ const PaymentMethodSelection = ({
/>
</>
)
-}
+})
+
+PaymentMethodSelection.displayName = 'PaymentMethodSelection'
export default PaymentMethodSelection
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
index 40f7fd83c70..4102d6f65bb 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
@@ -28,6 +28,7 @@ import MembersExceedLimitModal from './MembersExceedLimitModal'
import { SubscriptionPlanUpdateDialog } from './SubscriptionPlanUpdateDialog'
import UpgradeSurveyModal from './UpgradeModal'
import PartnerManagedResource from 'components/ui/PartnerManagedResource'
+import { getPlanChangeType } from 'components/interfaces/Billing/Subscription/Subscription.utils'
const PlanUpdateSidePanel = () => {
const router = useRouter()
@@ -70,7 +71,6 @@ const PlanUpdateSidePanel = () => {
const { data: plans, isLoading: isLoadingPlans } = useOrgPlansQuery({ orgSlug: slug })
const { data: membersExceededLimit } = useFreeProjectLimitCheckQuery({ slug })
- const billingViaPartner = subscription?.billing_via_partner === true
const billingPartner = subscription?.billing_partner
const {
@@ -84,7 +84,6 @@ const PlanUpdateSidePanel = () => {
const hasMembersExceedingFreeTierLimit =
(membersExceededLimit || []).length > 0 &&
orgProjects.filter((it) => it.status !== 'INACTIVE' && it.status !== 'GOING_DOWN').length > 0
- const subscriptionPlanMeta = subscriptionsPlans.find((tier) => tier.id === selectedTier)
useEffect(() => {
if (visible) {
@@ -161,7 +160,8 @@ const PlanUpdateSidePanel = () => {
{subscriptionsPlans.map((plan) => {
const planMeta = availablePlans.find((p) => p.id === plan.id.split('tier_')[1])
const price = planMeta?.price ?? 0
- const isDowngradeOption = planMeta?.change_type === 'downgrade'
+ const isDowngradeOption =
+ getPlanChangeType(subscription?.plan.id, plan?.planId) === 'downgrade'
const isCurrentPlan = planMeta?.id === subscription?.plan?.id
const features = pickFeatures(plan, billingPartner)
const footer = pickFooter(plan, billingPartner)
@@ -299,7 +299,6 @@ const PlanUpdateSidePanel = () => {
<DowngradeModal
visible={selectedTier === 'tier_free'}
- selectedPlan={subscriptionPlanMeta}
subscription={subscription}
onClose={() => setSelectedTier(undefined)}
onConfirm={onConfirmDowngrade}
@@ -308,16 +307,12 @@ const PlanUpdateSidePanel = () => {
<SubscriptionPlanUpdateDialog
selectedTier={selectedTier}
- selectedOrganization={selectedOrganization}
onClose={() => setSelectedTier(undefined)}
- subscriptionPlanMeta={subscriptionPlanMeta}
planMeta={planMeta}
subscriptionPreviewError={subscriptionPreviewError}
subscriptionPreviewIsLoading={subscriptionPreviewIsLoading}
subscriptionPreviewInitialized={subscriptionPreviewInitialized}
subscriptionPreview={subscriptionPreview}
- billingViaPartner={billingViaPartner}
- billingPartner={billingPartner}
subscription={subscription}
projects={orgProjects}
currentPlanMeta={{
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/SubscriptionPlanUpdateDialog.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/SubscriptionPlanUpdateDialog.tsx
index 0bee353c27b..9cc8fbc274f 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/SubscriptionPlanUpdateDialog.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/SubscriptionPlanUpdateDialog.tsx
@@ -1,11 +1,14 @@
import { useQueryClient } from '@tanstack/react-query'
import { Check, InfoIcon } from 'lucide-react'
import Link from 'next/link'
-import { useEffect, useState } from 'react'
+import { useMemo, useRef, useState } from 'react'
import tweets from 'shared-data/tweets'
import { toast } from 'sonner'
-import { billingPartnerLabel } from 'components/interfaces/Billing/Subscription/Subscription.utils'
+import {
+ billingPartnerLabel,
+ getPlanChangeType,
+} from 'components/interfaces/Billing/Subscription/Subscription.utils'
import AlertError from 'components/ui/AlertError'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { organizationKeys } from 'data/organizations/keys'
@@ -14,13 +17,23 @@ import { ProjectInfo } from 'data/projects/projects-query'
import { useOrgSubscriptionUpdateMutation } from 'data/subscriptions/org-subscription-update-mutation'
import { SubscriptionTier } from 'data/subscriptions/types'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
-import { PRICING_TIER_PRODUCT_IDS, PROJECT_STATUS } from 'lib/constants'
+import { PRICING_TIER_PRODUCT_IDS, PROJECT_STATUS, STRIPE_PUBLIC_KEY } from 'lib/constants'
import { formatCurrency } from 'lib/helpers'
import { Badge, Button, Dialog, DialogContent, Table, TableBody, TableCell, TableRow } from 'ui'
import { Admonition } from 'ui-patterns'
import { InfoTooltip } from 'ui-patterns/info-tooltip'
import { BillingCustomerDataExistingOrgDialog } from '../BillingCustomerData/BillingCustomerDataExistingOrgDialog'
import PaymentMethodSelection from './PaymentMethodSelection'
+import { useConfirmPendingSubscriptionChangeMutation } from 'data/subscriptions/org-subscription-confirm-pending-change'
+import { PaymentConfirmation } from 'components/interfaces/Billing/Payment/PaymentConfirmation'
+import { Elements } from '@stripe/react-stripe-js'
+import { loadStripe, PaymentMethod, StripeElementsOptions } from '@stripe/stripe-js'
+import { useTheme } from 'next-themes'
+import { PaymentIntentResult } from '@stripe/stripe-js'
+import { getStripeElementsAppearanceOptions } from 'components/interfaces/Billing/Payment/Payment.utils'
+import { plans as subscriptionsPlans } from 'shared-data/plans'
+
+const stripePromise = loadStripe(STRIPE_PUBLIC_KEY)
const getRandomTweet = () => {
const filteredTweets = tweets.filter((it) => it.text.length < 180)
@@ -49,15 +62,11 @@ type DowngradePlanHeadingKey = keyof typeof DOWNGRADE_PLAN_HEADINGS
interface Props {
selectedTier: 'tier_free' | 'tier_pro' | 'tier_team' | undefined
onClose: () => void
- subscriptionPlanMeta: any
planMeta: any
subscriptionPreviewError: any
subscriptionPreviewIsLoading: boolean
subscriptionPreviewInitialized: boolean
subscriptionPreview: OrganizationBillingSubscriptionPreviewResponse | undefined
- billingViaPartner: boolean
- billingPartner?: string
- selectedOrganization: any
subscription: any
currentPlanMeta: any
projects: ProjectInfo[]
@@ -66,38 +75,63 @@ interface Props {
export const SubscriptionPlanUpdateDialog = ({
selectedTier,
onClose,
- subscriptionPlanMeta,
planMeta,
subscriptionPreviewError,
subscriptionPreviewIsLoading,
subscriptionPreviewInitialized,
subscriptionPreview,
- billingViaPartner,
- billingPartner,
- selectedOrganization,
subscription,
currentPlanMeta,
projects,
}: Props) => {
+ const { resolvedTheme } = useTheme()
const queryClient = useQueryClient()
- const { slug } = useSelectedOrganization() ?? {}
+ const selectedOrganization = useSelectedOrganization()
const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string>()
- const [testimonialTweet, setTestimonialTweet] = useState(getRandomTweet())
+ const [paymentIntentSecret, setPaymentIntentSecret] = useState<string | null>(null)
+ const [paymentConfirmationLoading, setPaymentConfirmationLoading] = useState(false)
+ const paymentMethodSelection = useRef<{
+ createPaymentMethod: () => Promise<PaymentMethod | undefined>
+ }>(null)
+
+ const billingViaPartner = subscription?.billing_via_partner === true
+ const billingPartner = subscription?.billing_partner
+
+ const stripeOptionsConfirm = useMemo(() => {
+ return {
+ clientSecret: paymentIntentSecret,
+ appearance: getStripeElementsAppearanceOptions(resolvedTheme),
+ } as StripeElementsOptions
+ }, [paymentIntentSecret, resolvedTheme])
+
+ const testimonialTweet = useMemo(() => getRandomTweet(), [])
+
+ const changeType = useMemo(() => {
+ return getPlanChangeType(subscription?.plan?.id, planMeta?.id)
+ }, [planMeta, subscription])
+
+ const subscriptionPlanMeta = useMemo(
+ () => subscriptionsPlans.find((tier) => tier.id === selectedTier),
+ [selectedTier]
+ )
- useEffect(() => {
- if (selectedTier !== undefined && selectedTier !== 'tier_free') {
- setTestimonialTweet(getRandomTweet())
- }
- }, [selectedTier])
+ const onSuccessfulPlanChange = () => {
+ toast.success(
+ `Successfully ${changeType === 'downgrade' ? 'downgraded' : 'upgraded'} subscription to ${subscriptionPlanMeta?.name}!`
+ )
+ onClose()
+ window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
+ }
const { mutate: updateOrgSubscription, isLoading: isUpdating } = useOrgSubscriptionUpdateMutation(
{
- onSuccess: () => {
- toast.success(
- `Successfully ${planMeta?.change_type === 'downgrade' ? 'downgraded' : 'upgraded'} subscription to ${subscriptionPlanMeta?.name}!`
- )
- onClose()
- window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
+ onSuccess: (data) => {
+ if (data.pending_payment_intent_secret) {
+ setPaymentIntentSecret(data.pending_payment_intent_secret)
+ return
+ }
+
+ onSuccessfulPlanChange()
},
onError: (error) => {
toast.error(`Unable to update subscription: ${error.message}`)
@@ -105,25 +139,64 @@ export const SubscriptionPlanUpdateDialog = ({
}
)
+ const { mutate: confirmPendingSubscriptionChange, isLoading: isConfirming } =
+ useConfirmPendingSubscriptionChangeMutation({
+ onSuccess: () => {
+ onSuccessfulPlanChange()
+ },
+ onError: (error) => {
+ toast.error(`Unable to update subscription: ${error.message}`)
+ },
+ })
+
+ const paymentIntentConfirmed = async (paymentIntentConfirmation: PaymentIntentResult) => {
+ // Reset payment intent secret to ensure another attempt works as expected
+ setPaymentIntentSecret('')
+
+ if (paymentIntentConfirmation.paymentIntent?.status === 'succeeded') {
+ await confirmPendingSubscriptionChange({
+ slug: selectedOrganization?.slug,
+ payment_intent_id: paymentIntentConfirmation.paymentIntent.id,
+ })
+ } else {
+ setPaymentConfirmationLoading(false)
+ // If the payment intent is not successful, we reset the payment method and show an error
+ toast.error(`Could not confirm payment. Please try again or use a different card.`)
+ }
+ }
+
const onUpdateSubscription = async () => {
- if (!slug) return console.error('org slug is required')
+ if (!selectedOrganization?.slug) return console.error('org slug is required')
if (!selectedTier) return console.error('Selected plan is required')
- if (!selectedPaymentMethod && subscription?.payment_method_type !== 'invoice') {
- return toast.error('Please select a payment method')
+
+ const paymentMethod = await paymentMethodSelection.current?.createPaymentMethod()
+ if (paymentMethod) {
+ setSelectedPaymentMethod(paymentMethod.id)
}
- if (selectedPaymentMethod) {
- queryClient.setQueriesData(organizationKeys.paymentMethods(slug), (prev: any) => {
- if (!prev) return prev
- return {
- ...prev,
- defaultPaymentMethodId: selectedPaymentMethod,
- data: prev.data.map((pm: any) => ({
- ...pm,
- is_default: pm.id === selectedPaymentMethod,
- })),
+ if (
+ !paymentMethod &&
+ subscription?.payment_method_type !== 'invoice' &&
+ changeType === 'upgrade'
+ ) {
+ return
+ }
+
+ if (paymentMethod) {
+ queryClient.setQueriesData(
+ organizationKeys.paymentMethods(selectedOrganization.slug),
+ (prev: any) => {
+ if (!prev) return prev
+ return {
+ ...prev,
+ defaultPaymentMethodId: paymentMethod?.id,
+ data: prev.data.map((pm: any) => ({
+ ...pm,
+ is_default: pm.id === paymentMethod?.id,
+ })),
+ }
}
- })
+ )
}
// If the user is downgrading from team, should have spend cap disabled by default
@@ -132,7 +205,11 @@ export const SubscriptionPlanUpdateDialog = ({
? (PRICING_TIER_PRODUCT_IDS.PAYG as SubscriptionTier)
: selectedTier
- updateOrgSubscription({ slug, tier, paymentMethod: selectedPaymentMethod })
+ updateOrgSubscription({
+ slug: selectedOrganization?.slug,
+ tier,
+ paymentMethod: paymentMethod?.id,
+ })
}
const features = subscriptionPlanMeta?.features?.[0]?.features || []
@@ -143,11 +220,11 @@ export const SubscriptionPlanUpdateDialog = ({
// Features that will be lost when downgrading
const featuresToLose =
- planMeta?.change_type === 'downgrade'
+ changeType === 'downgrade'
? currentPlanFeatures.filter((feature: string | [string, ...any[]]) => {
const featureStr = typeof feature === 'string' ? feature : feature[0]
// Check if this feature exists in the new plan
- return !topFeatures.some((newFeature: string | [string, ...any[]]) => {
+ return !topFeatures.some((newFeature: string | string[]) => {
const newFeatureStr = typeof newFeature === 'string' ? newFeature : newFeature[0]
return newFeatureStr === featureStr
})
@@ -165,7 +242,7 @@ export const SubscriptionPlanUpdateDialog = ({
const proratedCredit = currentPlanMonthlyPrice * remainingRatio
// Calculate new plan cost
- const newPlanCost = subscriptionPlanMeta?.priceMonthly ?? 0
+ const newPlanCost = Number(subscriptionPlanMeta?.priceMonthly) ?? 0
const customerBalance = ((subscription?.customer_balance ?? 0) / 100) * -1
@@ -182,16 +259,16 @@ export const SubscriptionPlanUpdateDialog = ({
<DialogContent
onOpenAutoFocus={(event) => event.preventDefault()}
size="xlarge"
- className="p-0"
+ className="p-0 overflow-y-auto max-h-[1000px]"
>
- <div className="grid grid-cols-1 md:grid-cols-2 h-full items-stretch">
+ <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-5 h-full items-stretch">
{/* Left Column */}
- <div className="p-8 pb-8 flex flex-col">
+ <div className="p-8 pb-8 flex flex-col xl:col-span-3">
<div className="flex-1">
<h3 className="text-base mb-4">
- {planMeta?.change_type === 'downgrade' ? 'Downgrade' : 'Upgrade'}{' '}
+ {changeType === 'downgrade' ? 'Downgrade' : 'Upgrade'}{' '}
<span className="font-bold">{selectedOrganization?.name}</span> to{' '}
- {planMeta?.change_type === 'downgrade'
+ {changeType === 'downgrade'
? DOWNGRADE_PLAN_HEADINGS[(selectedTier as DowngradePlanHeadingKey) || 'default']
: PLAN_HEADINGS[(selectedTier as PlanHeadingKey) || 'default']}
</h3>
@@ -256,7 +333,7 @@ export const SubscriptionPlanUpdateDialog = ({
<>
{' '}
<Link
- href={`/org/${slug}/billing#breakdown`}
+ href={`/org/${selectedOrganization?.slug}/billing#breakdown`}
className="text-sm text-brand hover:text-brand-600 transition"
target="_blank"
>
@@ -483,16 +560,24 @@ export const SubscriptionPlanUpdateDialog = ({
)}
</div>
- <div className="pt-6">
- {!billingViaPartner ? (
+ <div className="pt-4">
+ {!billingViaPartner && !subscriptionPreviewIsLoading && changeType === 'upgrade' && (
<div className="space-y-2 mb-4">
<BillingCustomerDataExistingOrgDialog />
+
<PaymentMethodSelection
+ ref={paymentMethodSelection}
selectedPaymentMethod={selectedPaymentMethod}
onSelectPaymentMethod={setSelectedPaymentMethod}
+ createPaymentMethodInline={
+ subscriptionPreview?.pending_subscription_flow === true
+ }
+ readOnly={paymentConfirmationLoading || isConfirming || isUpdating}
/>
</div>
- ) : (
+ )}
+
+ {billingViaPartner && (
<div className="mb-4">
<p className="text-sm">
This organization is billed through our partner{' '}
@@ -518,40 +603,42 @@ export const SubscriptionPlanUpdateDialog = ({
(it) =>
it.status === PROJECT_STATUS.ACTIVE_HEALTHY ||
it.status === PROJECT_STATUS.COMING_UP
- ).length === 0 && (
- <div className="pb-2">
- <Admonition title="Empty organization" type="warning">
- This organization has no active projects. Did you select the correct
- organization?
- </Admonition>
- </div>
- )}
+ ).length === 0 &&
+ subscriptionPreview?.plan_change_type !== 'downgrade' && (
+ <div className="pb-2">
+ <Admonition title="Empty organization" type="warning">
+ This organization has no active projects. Did you select the correct
+ organization?
+ </Admonition>
+ </div>
+ )}
<div className="flex space-x-2">
<Button type="default" size="medium" onClick={onClose} className="flex-1">
Cancel
</Button>
<Button
- loading={isUpdating}
+ loading={isUpdating || paymentConfirmationLoading || isConfirming}
+ disabled={subscriptionPreviewIsLoading}
type="primary"
onClick={onUpdateSubscription}
className="flex-1"
size="medium"
>
- Confirm {planMeta?.change_type === 'downgrade' ? 'downgrade' : 'upgrade'}
+ Confirm {changeType === 'downgrade' ? 'downgrade' : 'upgrade'}
</Button>
</div>
</div>
</div>
{/* Right Column */}
- <div className="bg-surface-100 p-8 flex flex-col border-l">
- {planMeta?.change_type === 'downgrade'
+ <div className="bg-surface-100 p-8 flex flex-col border-l xl:col-span-2">
+ {changeType === 'downgrade'
? featuresToLose.length > 0 && (
<div className="mb-4">
<h3 className="text-sm mb-1">Features you'll lose</h3>
<p className="text-xs text-foreground-light mb-4">
- Please review this carefully before downgrading.
+ Please review carefully before downgrading.
</p>
<div className="space-y-2 mb-4 text-foreground-light">
{featuresToLose.map((feature: string | [string, ...any[]]) => (
@@ -575,7 +662,7 @@ export const SubscriptionPlanUpdateDialog = ({
<h3 className="text-sm mb-4">Upgrade features</h3>
<div className="space-y-2 mb-4 text-foreground-light">
- {topFeatures.map((feature: string | [string, ...any[]]) => (
+ {topFeatures.map((feature: string | string[]) => (
<div
key={typeof feature === 'string' ? feature : feature[0]}
className="flex items-center gap-2"
@@ -594,7 +681,7 @@ export const SubscriptionPlanUpdateDialog = ({
</div>
</div>
)}
- {planMeta?.change_type !== 'downgrade' && (
+ {changeType !== 'downgrade' && (
<div className="border-t pt-6">
<blockquote className="text-sm text-foreground-light italic">
{testimonialTweet.text}
@@ -604,6 +691,19 @@ export const SubscriptionPlanUpdateDialog = ({
)}
</div>
</div>
+
+ {stripePromise && paymentIntentSecret && (
+ <Elements stripe={stripePromise} options={stripeOptionsConfirm}>
+ <PaymentConfirmation
+ paymentIntentSecret={paymentIntentSecret}
+ onPaymentIntentConfirm={(paymentIntentConfirmation) =>
+ paymentIntentConfirmed(paymentIntentConfirmation)
+ }
+ onLoadingChange={(loading) => setPaymentConfirmationLoading(loading)}
+ paymentMethodId={selectedPaymentMethod!}
+ />
+ </Elements>
+ )}
</DialogContent>
</Dialog>
)
diff --git a/apps/studio/components/interfaces/Organization/NewOrg/NewOrgForm.tsx b/apps/studio/components/interfaces/Organization/NewOrg/NewOrgForm.tsx
index 066177fb158..a544b10ef5d 100644
--- a/apps/studio/components/interfaces/Organization/NewOrg/NewOrgForm.tsx
+++ b/apps/studio/components/interfaces/Organization/NewOrg/NewOrgForm.tsx
@@ -1,11 +1,11 @@
-import { Elements, PaymentElement, useElements, useStripe } from '@stripe/react-stripe-js'
+import { Elements } from '@stripe/react-stripe-js'
import type { PaymentIntentResult, PaymentMethod, StripeElementsOptions } from '@stripe/stripe-js'
import _ from 'lodash'
import { ExternalLink, HelpCircle } from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { parseAsString, useQueryStates } from 'nuqs'
-import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
import { toast } from 'sonner'
import { z } from 'zod'
@@ -19,7 +19,6 @@ import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
import { PRICING_TIER_LABELS_ORG, STRIPE_PUBLIC_KEY } from 'lib/constants'
import {
Button,
- Input,
Input_Shadcn_,
Label_Shadcn_,
Select_Shadcn_,
@@ -35,13 +34,12 @@ import {
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { BillingCustomerDataNewOrgDialog } from '../BillingSettings/BillingCustomerData/BillingCustomerDataNewOrgDialog'
import { FormCustomerData } from '../BillingSettings/BillingCustomerData/useBillingCustomerDataForm'
-import { useConfirmPendingSubscriptionChangeMutation } from 'data/subscriptions/org-subscription-confirm-pending-change'
+import { useConfirmPendingSubscriptionCreateMutation } from 'data/subscriptions/org-subscription-confirm-pending-create'
import { loadStripe } from '@stripe/stripe-js'
import { useTheme } from 'next-themes'
import { SetupIntentResponse } from 'data/stripe/setup-intent-mutation'
import { useProfile } from 'lib/profile'
import { PaymentConfirmation } from 'components/interfaces/Billing/Payment/PaymentConfirmation'
-import { getURL } from 'lib/helpers'
import { getStripeElementsAppearanceOptions } from 'components/interfaces/Billing/Payment/Payment.utils'
import { NewPaymentMethodElement } from '../BillingSettings/PaymentMethods/NewPaymentMethodElement'
@@ -190,7 +188,7 @@ const NewOrgForm = ({ onPaymentMethodReset, setupIntent, onPlanSelected }: NewOr
},
})
- const { mutate: confirmPendingSubscriptionChange } = useConfirmPendingSubscriptionChangeMutation({
+ const { mutate: confirmPendingSubscriptionChange } = useConfirmPendingSubscriptionCreateMutation({
onSuccess: (data) => {
if (data && 'slug' in data) {
onOrganizationCreated({ slug: data.slug })
@@ -557,6 +555,7 @@ const NewOrgForm = ({ onPaymentMethodReset, setupIntent, onPlanSelected }: NewOr
setupIntent?.pending_subscription_flow_enabled_for_creation === true
}
email={user.profile?.primary_email}
+ readOnly={newOrgLoading || paymentConfirmationLoading}
/>
</Panel.Content>
</Elements>
diff --git a/apps/studio/data/organizations/organization-billing-subscription-preview.ts b/apps/studio/data/organizations/organization-billing-subscription-preview.ts
index beb079b520e..0f0adef3bb0 100644
--- a/apps/studio/data/organizations/organization-billing-subscription-preview.ts
+++ b/apps/studio/data/organizations/organization-billing-subscription-preview.ts
@@ -43,6 +43,7 @@ export type OrganizationBillingSubscriptionPreviewResponse = {
ref: string
}[]
billed_via_partner?: boolean
+ pending_subscription_flow?: boolean
}
export async function previewOrganizationBillingSubscription({
diff --git a/apps/studio/data/subscriptions/org-subscription-confirm-pending-change.ts b/apps/studio/data/subscriptions/org-subscription-confirm-pending-change.ts
index ed6065771c8..44df6615185 100644
--- a/apps/studio/data/subscriptions/org-subscription-confirm-pending-change.ts
+++ b/apps/studio/data/subscriptions/org-subscription-confirm-pending-change.ts
@@ -4,31 +4,36 @@ import { toast } from 'sonner'
import { handleError, post } from 'data/fetchers'
import type { ResponseError } from 'types'
import { organizationKeys } from 'data/organizations/keys'
-import { permissionKeys } from 'data/permissions/keys'
-import { castOrganizationResponseToOrganization } from 'data/organizations/organizations-query'
-import type { components } from 'api-types'
+import { subscriptionKeys } from './keys'
+import { usageKeys } from 'data/usage/keys'
+import { invoicesKeys } from 'data/invoices/keys'
export type PendingSubscriptionChangeVariables = {
payment_intent_id: string
- name: string
- kind?: string
- size?: string
+ slug?: string
}
export async function confirmPendingSubscriptionChange({
payment_intent_id,
- name,
- kind,
- size,
+ slug,
}: PendingSubscriptionChangeVariables) {
- const { data, error } = await post('/platform/organizations/confirm-subscription', {
- body: {
- payment_intent_id,
- name,
- kind,
- size,
- },
- })
+ if (!slug) {
+ throw new Error('Organization slug is required to confirm pending subscription change')
+ }
+
+ const { data, error } = await post(
+ '/platform/organizations/{slug}/billing/subscription/confirm',
+ {
+ params: {
+ path: {
+ slug,
+ },
+ },
+ body: {
+ payment_intent_id,
+ },
+ }
+ )
if (error) handleError(error)
return data
@@ -56,33 +61,28 @@ export const useConfirmPendingSubscriptionChangeMutation = ({
PendingSubscriptionChangeVariables
>((vars) => confirmPendingSubscriptionChange(vars), {
async onSuccess(data, variables, context) {
- // [Joshen] We're manually updating the query client here as the org's subscription is
- // created async, and the invalidation will happen too quick where the GET organizations
- // endpoint will error out with a 500 since the subscription isn't created yet.
- queryClient.setQueriesData(
- {
- queryKey: organizationKeys.list(),
- exact: true,
- },
- (prev: any) => {
- if (!prev) return prev
- return [
- ...prev,
- castOrganizationResponseToOrganization(
- data as components['schemas']['OrganizationResponse']
- ),
- ]
- }
- )
+ const { slug } = variables
- await queryClient.invalidateQueries(permissionKeys.list())
+ // [Kevin] Backend can return stale data as it's waiting for the Stripe-sync to complete. Until that's solved in the backend
+ // we are going back to monkey here and delay the invalidation
+ await new Promise((resolve) => setTimeout(resolve, 2000))
- // todo replace plan in org
+ await Promise.all([
+ queryClient.invalidateQueries(subscriptionKeys.orgSubscription(slug)),
+ queryClient.invalidateQueries(subscriptionKeys.orgPlans(slug)),
+ queryClient.invalidateQueries(usageKeys.orgUsage(slug)),
+ queryClient.invalidateQueries(invoicesKeys.orgUpcomingPreview(slug)),
+ queryClient.invalidateQueries(organizationKeys.detail(slug)),
+ queryClient.invalidateQueries(organizationKeys.list()),
+ ])
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {
if (onError === undefined) {
- toast.error(`Failed to confirm payment: ${data.message}`)
+ toast.error(data.message, {
+ dismissible: true,
+ duration: 10_000,
+ })
} else {
onError(data, variables, context)
}
diff --git a/apps/studio/data/subscriptions/org-subscription-confirm-pending-create.ts b/apps/studio/data/subscriptions/org-subscription-confirm-pending-create.ts
new file mode 100644
index 00000000000..8d60276bb94
--- /dev/null
+++ b/apps/studio/data/subscriptions/org-subscription-confirm-pending-create.ts
@@ -0,0 +1,95 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { handleError, post } from 'data/fetchers'
+import type { ResponseError } from 'types'
+import { organizationKeys } from 'data/organizations/keys'
+import { permissionKeys } from 'data/permissions/keys'
+import { castOrganizationResponseToOrganization } from 'data/organizations/organizations-query'
+import type { components } from 'api-types'
+
+export type PendingSubscriptionCreateVariables = {
+ payment_intent_id: string
+ name: string
+ kind?: string
+ size?: string
+}
+
+export async function confirmPendingSubscriptionCreate({
+ payment_intent_id,
+ name,
+ kind,
+ size,
+}: PendingSubscriptionCreateVariables) {
+ const { data, error } = await post('/platform/organizations/confirm-subscription', {
+ body: {
+ payment_intent_id,
+ name,
+ kind,
+ size,
+ },
+ })
+
+ if (error) handleError(error)
+ return data
+}
+
+type PendingSubscriptionCreateData = Awaited<ReturnType<typeof confirmPendingSubscriptionCreate>>
+
+export const useConfirmPendingSubscriptionCreateMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<
+ PendingSubscriptionCreateData,
+ ResponseError,
+ PendingSubscriptionCreateVariables
+ >,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<
+ PendingSubscriptionCreateData,
+ ResponseError,
+ PendingSubscriptionCreateVariables
+ >((vars) => confirmPendingSubscriptionCreate(vars), {
+ async onSuccess(data, variables, context) {
+ // [Joshen] We're manually updating the query client here as the org's subscription is
+ // created async, and the invalidation will happen too quick where the GET organizations
+ // endpoint will error out with a 500 since the subscription isn't created yet.
+ queryClient.setQueriesData(
+ {
+ queryKey: organizationKeys.list(),
+ exact: true,
+ },
+ (prev: any) => {
+ if (!prev) return prev
+ return [
+ ...prev,
+ castOrganizationResponseToOrganization(
+ data as components['schemas']['OrganizationResponse']
+ ),
+ ]
+ }
+ )
+
+ await queryClient.invalidateQueries(permissionKeys.list())
+
+ // todo replace plan in org
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(data.message, {
+ dismissible: true,
+ duration: 10_000,
+ })
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ })
+}
diff --git a/apps/studio/data/subscriptions/org-subscription-update-mutation.ts b/apps/studio/data/subscriptions/org-subscription-update-mutation.ts
index 348eb311780..d899039b23c 100644
--- a/apps/studio/data/subscriptions/org-subscription-update-mutation.ts
+++ b/apps/studio/data/subscriptions/org-subscription-update-mutation.ts
@@ -55,24 +55,29 @@ export const useOrgSubscriptionUpdateMutation = ({
async onSuccess(data, variables, context) {
const { slug } = variables
- // [Kevin] Backend can return stale data as it's waiting for the Stripe-sync to complete. Until that's solved in the backend
- // we are going back to monkey here and delay the invalidation
- await new Promise((resolve) => setTimeout(resolve, 2000))
+ if (!data.pending_payment_intent_secret) {
+ // [Kevin] Backend can return stale data as it's waiting for the Stripe-sync to complete. Until that's solved in the backend
+ // we are going back to monkey here and delay the invalidation
+ await new Promise((resolve) => setTimeout(resolve, 2000))
- await Promise.all([
- queryClient.invalidateQueries(subscriptionKeys.orgSubscription(slug)),
- queryClient.invalidateQueries(subscriptionKeys.orgPlans(slug)),
- queryClient.invalidateQueries(usageKeys.orgUsage(slug)),
- queryClient.invalidateQueries(invoicesKeys.orgUpcomingPreview(slug)),
- queryClient.invalidateQueries(organizationKeys.detail(slug)),
- queryClient.invalidateQueries(organizationKeys.list()),
- ])
+ await Promise.all([
+ queryClient.invalidateQueries(subscriptionKeys.orgSubscription(slug)),
+ queryClient.invalidateQueries(subscriptionKeys.orgPlans(slug)),
+ queryClient.invalidateQueries(usageKeys.orgUsage(slug)),
+ queryClient.invalidateQueries(invoicesKeys.orgUpcomingPreview(slug)),
+ queryClient.invalidateQueries(organizationKeys.detail(slug)),
+ queryClient.invalidateQueries(organizationKeys.list()),
+ ])
+ }
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {
if (onError === undefined) {
- toast.error(`Failed to update subscription: ${data.message}`)
+ toast.error(data.message, {
+ dismissible: true,
+ duration: 10_000,
+ })
} else {
onError(data, variables, context)
}
diff --git a/packages/api-types/types/api.d.ts b/packages/api-types/types/api.d.ts
index 8a43fd88679..88d51e24ff2 100644
--- a/packages/api-types/types/api.d.ts
+++ b/packages/api-types/types/api.d.ts
@@ -368,7 +368,7 @@ export interface paths {
/** Get project api keys */
get: operations['v1-get-project-api-keys']
put?: never
- /** [Beta] Creates a new API key for the project */
+ /** Creates a new API key for the project */
post: operations['createApiKey']
delete?: never
options?: never
@@ -383,15 +383,15 @@ export interface paths {
path?: never
cookie?: never
}
- /** [Beta] Get API key */
+ /** Get API key */
get: operations['getApiKey']
put?: never
post?: never
- /** [Beta] Deletes an API key for the project */
+ /** Deletes an API key for the project */
delete: operations['deleteApiKey']
options?: never
head?: never
- /** [Beta] Updates an API key for the project */
+ /** Updates an API key for the project */
patch: operations['updateApiKey']
trace?: never
}
@@ -402,9 +402,9 @@ export interface paths {
path?: never
cookie?: never
}
- /** [Beta] Check whether JWT based legacy (anon, service_role) API keys are enabled. This API endpoint will be removed in the future, check for HTTP 404 Not Found. */
+ /** Check whether JWT based legacy (anon, service_role) API keys are enabled. This API endpoint will be removed in the future, check for HTTP 404 Not Found. */
get: operations['checkLegacyApiKeys']
- /** [Beta] Disable or re-enable JWT based legacy (anon, service_role) API keys. This API endpoint will be removed in the future, check for HTTP 404 Not Found. */
+ /** Disable or re-enable JWT based legacy (anon, service_role) API keys. This API endpoint will be removed in the future, check for HTTP 404 Not Found. */
put: operations['updateLegacyApiKeys']
post?: never
delete?: never
diff --git a/packages/api-types/types/platform.d.ts b/packages/api-types/types/platform.d.ts
index 5b677bd4128..3107d66b7f4 100644
--- a/packages/api-types/types/platform.d.ts
+++ b/packages/api-types/types/platform.d.ts
@@ -1007,6 +1007,23 @@ export interface paths {
patch?: never
trace?: never
}
+ '/platform/organizations/{slug}/billing/subscription/confirm': {
+ parameters: {
+ query?: never
+ header?: never
+ path?: never
+ cookie?: never
+ }
+ get?: never
+ put?: never
+ /** Confirm subscription change */
+ post: operations['SubscriptionController_confirmSubscriptionChange']
+ delete?: never
+ options?: never
+ head?: never
+ patch?: never
+ trace?: never
+ }
'/platform/organizations/{slug}/billing/subscription/preview': {
parameters: {
query?: never
@@ -4257,6 +4274,9 @@ export interface components {
payment_intent_id: string
size?: string
}
+ ConfirmSubscriptionChangeBody: {
+ payment_intent_id: string
+ }
CopyObjectBody: {
from: string
to: string
@@ -8246,6 +8266,9 @@ export interface components {
/** @enum {string} */
tier: 'tier_free' | 'tier_pro' | 'tier_payg' | 'tier_team' | 'tier_enterprise'
}
+ UpdateSubscriptionResponse: {
+ pending_payment_intent_secret: string | null
+ }
UpdateSupavisorConfigBody: {
default_pool_size?: number | null
/**
@@ -10701,7 +10724,9 @@ export interface operations {
headers: {
[name: string]: unknown
}
- content?: never
+ content: {
+ 'application/json': components['schemas']['UpdateSubscriptionResponse']
+ }
}
403: {
headers: {
@@ -10718,6 +10743,43 @@ export interface operations {
}
}
}
+ SubscriptionController_confirmSubscriptionChange: {
+ parameters: {
+ query?: never
+ header?: never
+ path: {
+ /** @description Organization slug */
+ slug: string
+ }
+ cookie?: never
+ }
+ requestBody: {
+ content: {
+ 'application/json': components['schemas']['ConfirmSubscriptionChangeBody']
+ }
+ }
+ responses: {
+ 200: {
+ headers: {
+ [name: string]: unknown
+ }
+ content?: never
+ }
+ 403: {
+ headers: {
+ [name: string]: unknown
+ }
+ content?: never
+ }
+ /** @description Failed to confirm subscription change */
+ 500: {
+ headers: {
+ [name: string]: unknown
+ }
+ content?: never
+ }
+ }
+ }
SubscriptionController_previewSubscriptionChange: {
parameters: {
query?: never