The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Show confirmation modal when downgrading to free if project is not on micro
Joshen Lim9888c093140e
diff --git a/studio/components/interfaces/Billing/ExitSurvey/ExitSurvey.tsx b/studio/components/interfaces/Billing/ExitSurvey/ExitSurvey.tsxindex 0b82f7b3d63..eae9cdb61a8 100644--- a/studio/components/interfaces/Billing/ExitSurvey/ExitSurvey.tsx+++ b/studio/components/interfaces/Billing/ExitSurvey/ExitSurvey.tsx@@ -1,7 +1,8 @@-import { FC, useReducer, useState, useEffect } from 'react'+import { FC, useReducer, useState, useEffect, useRef } from 'react'+import { useRouter } from 'next/router'import { includes, without } from 'lodash'import { Transition } from '@headlessui/react'-import { Button, Form, Input, IconArrowLeft } from '@supabase/ui'+import { Button, Form, Input, Modal, IconArrowLeft, Alert } from '@supabase/ui'import { useStore } from 'hooks'import { post, patch } from 'lib/common/fetch'@@ -10,22 +11,41 @@ import { CANCELLATION_REASONS } from '../Billing.constants'import { generateFeedbackMessage } from './ExitSurvey.utils'import { UpdateSuccess } from '../'import { SubscriptionPreview } from '../Billing.types'+import { StripeSubscription } from 'components/interfaces/Billing'interface Props {freeTier: any+ subscription?: StripeSubscriptiononSelectBack: () => void}-const ExitSurvey: FC<Props> = ({ freeTier, onSelectBack }) => {- const { ui } = useStore()+const ExitSurvey: FC<Props> = ({ freeTier, subscription, onSelectBack }) => {+ const router = useRouter()+ const { app, ui } = useStore()+ const projectId = ui.selectedProject?.id ?? -1const projectRef = ui.selectedProject?.ref+ 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 [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+ const willChangeComputeSize = (subscription?.addons ?? []).length > 0+ 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()@@ -40,6 +60,17 @@ const ExitSurvey: FC<Props> = ({ freeTier, onSelectBack }) => {}}+ const getDowngradeSuccessMessage = () => {+ 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`, {@@ -50,15 +81,27 @@ const ExitSurvey: FC<Props> = ({ freeTier, onSelectBack }) => {setSubscriptionPreview(preview)}- const onSubmit = async (values: any, { setSubmitting }: any) => {+ 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',+ })+ }++ if (willChangeComputeSize) {+ setMessage(values.message)+ return setShowConfirmModal(true)+ } else {+ downgradeProject(values)+ }+ }++ const downgradeProject = async (values?: any) => {+ const downgradeMessage = values?.message ?? message+try {- setSubmitting(true)- if (selectedReasons.length === 0) {- return ui.setNotification({- category: 'error',- message: 'Please select at least one reason for cancelling your subscription',- })- }+ setIsSubmitting(true)// Submit feedback to Freshdeskawait post(`${API_URL}/feedback/send`, {@@ -66,7 +109,7 @@ const ExitSurvey: FC<Props> = ({ freeTier, onSelectBack }) => {subject: 'Subscription cancellation - Exit survey',tags: ['dashboard-exitsurvey'],category: 'Billing',- message: generateFeedbackMessage(selectedReasons, values.message),+ message: generateFeedbackMessage(selectedReasons, downgradeMessage),})// Trigger subscription downgrade@@ -86,66 +129,72 @@ const ExitSurvey: FC<Props> = ({ freeTier, onSelectBack }) => {error: res.error,})} else {- setIsSuccessful(true)+ if (willChangeComputeSize) {+ app.onProjectPostgrestStatusUpdated(projectId, 'OFFLINE')+ ui.setNotification({+ category: 'info',+ message: getDowngradeSuccessMessage(),+ })+ ui.setNotification({+ category: 'success',+ message:+ 'Your project has been updated and is currently restarting to update its instance size',+ })+ router.push(`/project/${projectRef}`)+ } else {+ setIsSuccessful(true)+ setIsSubmitting(false)+ }}} catch (error: any) {ui.setNotification({ category: 'error', message: `Failed to cancel subscription: ${error}` })- } finally {- setSubmitting(false)+ setIsSubmitting(false)}}if (isSuccessful) {- const returnedAmount = (subscriptionPreview?.returned_credits_for_unused_time ?? 0) / 100- const billingDate = new Date((subscriptionPreview?.bill_on ?? 0) * 1000)return (<UpdateSuccessprojectRef={projectRef || ''}title="Your project has been updated"- message={`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].`}+ message={getDowngradeSuccessMessage()}/>)}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="space-y-8 w-4/5">- <div 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}>- {({ isSubmitting }: { isSubmitting: boolean }) => (- <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={`+ <>+ <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="space-y-8 w-4/5">+ <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={`text-center rounded-md py-1 pl-2 pr-3 shadow-smtransition-all flex items-center space-x-2duration-100 cursor-pointer text-sm@@ -155,42 +204,94 @@ const ExitSurvey: FC<Props> = ({ freeTier, onSelectBack }) => {: ` bg-scale-700 opacity-25 hover:opacity-50 text-scale-1200`}`}- >- <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 space-x-2">- <Button htmlType="button" type="default">- Cancel- </Button>- <Button htmlType="submit" type="danger" loading={isSubmitting}>- Confirm downgrade- </Button>- <p className="text-xs text-scale-900">- The unused amount for the remaining of your billing cycle will be refunded as- credits- </p>+ >+ <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 space-x-2">+ <Button+ htmlType="button"+ type="default"+ onClick={() => router.push(`/project/${projectRef}/settings/billing/update`)}+ >+ Cancel+ </Button>+ <Button+ type="danger"+ htmlType="submit"+ loading={isSubmitting}+ disabled={isSubmitting}+ >+ Confirm downgrade+ </Button>+ <p className="text-xs text-scale-900">+ The unused amount for the remaining of your billing cycle will be refunded as+ credits+ </p>+ </div></div>- </div>- )}- </Form>+ )}+ </Form>+ </div>+ </div>+ </Transition>+ <Modal+ hideFooter+ visible={showConfirmModal}+ size="large"+ header="Downgrading project to free"+ onCancel={() => setShowConfirmModal(false)}+ >+ <div className="py-4 space-y-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.Seperator />+ <Modal.Content>+ <div className="flex items-center gap-2">+ <Button block type="default" onClick={() => setShowConfirmModal(false)}>+ Cancel+ </Button>+ <Button+ block+ htmlType="submit"+ loading={isSubmitting}+ disabled={isSubmitting}+ onClick={() => downgradeProject()}+ >+ Confirm+ </Button>+ </div>+ </Modal.Content></div>- </div>- </Transition>+ </Modal>+ </>)}diff --git a/studio/pages/project/[ref]/settings/billing/update/free.tsx b/studio/pages/project/[ref]/settings/billing/update/free.tsxindex d4d12bc3145..360560af34c 100644--- a/studio/pages/project/[ref]/settings/billing/update/free.tsx+++ b/studio/pages/project/[ref]/settings/billing/update/free.tsx@@ -8,7 +8,7 @@ import { get } from 'lib/common/fetch'import { API_URL, STRIPE_PRODUCT_IDS } from 'lib/constants'import { BillingLayout } from 'components/layouts'-import { ExitSurvey } from 'components/interfaces/Billing'+import { ExitSurvey, StripeSubscription } from 'components/interfaces/Billing'const BillingUpdateFree: NextPage = () => {const { ui } = useStore()@@ -16,11 +16,15 @@ const BillingUpdateFree: NextPage = () => {const projectRef = ui.selectedProject?.refconst [products, setProducts] = useState<{ tiers: any[]; addons: any[] }>()+ const [subscription, setSubscription] = useState<StripeSubscription>()const [isLoadingProducts, setIsLoadingProducts] = useState(false)useEffect(() => {- getStripeProducts()- }, [])+ if (projectRef) {+ getStripeProducts()+ getSubscription()+ }+ }, [projectRef])const getStripeProducts = async () => {try {@@ -37,6 +41,24 @@ const BillingUpdateFree: NextPage = () => {}}+ 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)return (@@ -44,6 +66,7 @@ const BillingUpdateFree: NextPage = () => {<div className="mx-auto max-w-5xl my-10"><ExitSurveyfreeTier={freeTier}+ subscription={subscription}onSelectBack={() => router.push(`/project/${projectRef}/settings/billing/update`)}/></div>