Skip to content

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

Convert direct requests to RQ in ExitSurveyModals and DeleteProjectButton

Joshen Limb72eb5262238
diff --git a/studio/components/interfaces/BillingV2/Subscription/Tier/ExitSurveyModal.tsx b/studio/components/interfaces/BillingV2/Subscription/Tier/ExitSurveyModal.tsx
index b0445dd0c28..1c4c1a16294 100644
--- a/studio/components/interfaces/BillingV2/Subscription/Tier/ExitSurveyModal.tsx
+++ b/studio/components/interfaces/BillingV2/Subscription/Tier/ExitSurveyModal.tsx
@@ -5,12 +5,12 @@ import { useRouter } from 'next/router'
import { useReducer, useRef, useState } from 'react'
import { useParams } from 'common'
+import { useSendDowngradeFeedbackMutation } from 'data/feedback/feedback-downgrade-send'
import { setProjectStatus } from 'data/projects/projects-query'
import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'
import { useProjectSubscriptionUpdateMutation } from 'data/subscriptions/project-subscription-update-mutation'
import { useFlag, useStore } from 'hooks'
-import { post } from 'lib/common/fetch'
-import { API_URL, PROJECT_STATUS } from 'lib/constants'
+import { PROJECT_STATUS } from 'lib/constants'
import { Button, Input, Modal } from 'ui'
import { CANCELLATION_REASONS } from '../../Billing.constants'
import ProjectUpdateDisabledTooltip from '../../ProjectUpdateDisabledTooltip'
@@ -35,7 +35,9 @@ const ExitSurveyModal = ({ visible, onClose }: ExitSurveyModalProps) => {
const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')
const { data: addons } = useProjectAddonsQuery({ projectRef })
- const { mutateAsync: updateSubscriptionTier, isLoading: isUpdating } =
+ const { mutateAsync: sendExitSurvey, isLoading: isSubmittingFeedback } =
+ useSendDowngradeFeedbackMutation()
+ const { mutateAsync: updateSubscriptionTier, isLoading: isUpdatingSubscription } =
useProjectSubscriptionUpdateMutation({
onError: (error) => {
return ui.setNotification({
@@ -45,7 +47,7 @@ const ExitSurveyModal = ({ visible, onClose }: ExitSurveyModalProps) => {
})
},
})
-
+ const isSubmitting = isUpdatingSubscription || isSubmittingFeedback
const subscriptionAddons = addons?.selected_addons ?? []
const hasComputeInstance = subscriptionAddons.find((addon) => addon.type === 'compute_instance')
@@ -87,35 +89,25 @@ const ExitSurveyModal = ({ visible, onClose }: ExitSurveyModalProps) => {
await updateSubscriptionTier({ projectRef, tier: 'tier_free' })
resetCaptcha()
- try {
- const feedbackRes = await post(`${API_URL}/feedback/downgrade`, {
- projectRef,
- reasons: selectedReasons.reduce((a, b) => `${a}- ${b}\n`, ''),
- additionalFeedback: message,
- exitAction: 'downgrade',
- })
- if (feedbackRes.error) throw feedbackRes.error
- } catch (error: any) {
- return ui.setNotification({
- error,
- category: 'info',
- message: `Failed to submit exit survey: ${error.message}`,
- })
- } finally {
- ui.setNotification({
- category: 'success',
- duration: hasComputeInstance ? 8000 : 4000,
- message: hasComputeInstance
- ? 'Your project has been downgraded and is currently restarting to update its instance size'
- : 'Successfully downgraded project to the free plan',
- })
- if (hasComputeInstance) {
- setProjectStatus(queryClient, projectRef, PROJECT_STATUS.RESTORING)
- router.push(`/project/${projectRef}`)
- }
- onClose(true)
- window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
+ await sendExitSurvey({
+ projectRef,
+ reasons: selectedReasons.reduce((a, b) => `${a}- ${b}\n`, ''),
+ message,
+ })
+
+ ui.setNotification({
+ category: 'success',
+ duration: hasComputeInstance ? 8000 : 4000,
+ message: hasComputeInstance
+ ? 'Your project has been downgraded and is currently restarting to update its instance size'
+ : 'Successfully downgraded project to the free plan',
+ })
+ if (hasComputeInstance) {
+ setProjectStatus(queryClient, projectRef, PROJECT_STATUS.RESTORING)
+ router.push(`/project/${projectRef}`)
}
+ onClose(true)
+ window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
}
return (
@@ -207,8 +199,8 @@ const ExitSurveyModal = ({ visible, onClose }: ExitSurveyModalProps) => {
<ProjectUpdateDisabledTooltip projectUpdateDisabled={projectUpdateDisabled}>
<Button
type="danger"
- loading={isUpdating}
- disabled={projectUpdateDisabled || isUpdating}
+ loading={isSubmitting}
+ disabled={projectUpdateDisabled || isSubmitting}
onClick={onSubmit}
>
Confirm downgrade
diff --git a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/ExitSurveyModal.tsx b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/ExitSurveyModal.tsx
index 957267da09d..8147d928445 100644
--- a/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/ExitSurveyModal.tsx
+++ b/studio/components/interfaces/Organization/BillingSettingsV2/Subscription/ExitSurveyModal.tsx
@@ -3,11 +3,10 @@ import { includes, without } from 'lodash'
import { useReducer, useRef, useState } from 'react'
import { useParams } from 'common'
+import { useSendDowngradeFeedbackMutation } from 'data/feedback/feedback-downgrade-send'
import { OrgSubscription } from 'data/subscriptions/org-subscription-query'
import { useOrgSubscriptionUpdateMutation } from 'data/subscriptions/org-subscription-update-mutation'
import { useFlag, useStore } from 'hooks'
-import { post } from 'lib/common/fetch'
-import { API_URL } from 'lib/constants'
import { Alert, Button, Input, Modal } from 'ui'
import ProjectUpdateDisabledTooltip from '../../BillingSettings/ProjectUpdateDisabledTooltip'
import { CANCELLATION_REASONS } from '../BillingSettings.constants'
@@ -25,20 +24,22 @@ const ExitSurveyModal = ({ visible, subscription, onClose }: ExitSurveyModalProp
const captchaRef = useRef<HCaptcha>(null)
const [message, setMessage] = useState('')
- // [Joshen] Separate submitting state as there are additional async logic involved in the submit
- const [isSubmitting, setIsSubmitting] = useState(false)
const [captchaToken, setCaptchaToken] = useState<string | null>(null)
const [selectedReasons, dispatchSelectedReasons] = useReducer(reducer, [])
const subscriptionUpdateDisabled = useFlag('disableProjectCreationAndUpdate')
- const { mutateAsync: updateOrgSubscription } = useOrgSubscriptionUpdateMutation({
- onError: (error) => {
- ui.setNotification({
- category: 'error',
- message: `Failed to downgrade project: ${error.message}`,
- })
- },
- })
+ const { mutateAsync: sendExitSurvey, isLoading: isSubmittingFeedback } =
+ useSendDowngradeFeedbackMutation()
+ const { mutateAsync: updateOrgSubscription, isLoading: isUpdating } =
+ useOrgSubscriptionUpdateMutation({
+ onError: (error) => {
+ ui.setNotification({
+ category: 'error',
+ message: `Failed to downgrade project: ${error.message}`,
+ })
+ },
+ })
+ const isSubmitting = isUpdating || isSubmittingFeedback
const projectsWithComputeInstances =
subscription?.project_addons.filter((project) =>
@@ -81,40 +82,24 @@ const ExitSurveyModal = ({ visible, subscription, onClose }: ExitSurveyModalProp
// If compute instance is present within the existing subscription, then a restart will be triggered
if (!slug) return console.error('Slug is required')
- setIsSubmitting(true)
- try {
- await updateOrgSubscription({ slug, tier: 'tier_free' })
- resetCaptcha()
- } catch (error: any) {
- setIsSubmitting(false)
- }
-
- try {
- const feedbackRes = await post(`${API_URL}/feedback/downgrade`, {
- orgSlug: slug,
- reasons: selectedReasons.reduce((a, b) => `${a}- ${b}\n`, ''),
- additionalFeedback: message,
- exitAction: 'downgrade',
- })
- if (feedbackRes.error) throw feedbackRes.error
- } catch (error: any) {
- return ui.setNotification({
- error,
- category: 'info',
- message: `Failed to submit exit survey: ${error.message}`,
- })
- } finally {
- ui.setNotification({
- category: 'success',
- duration: hasComputeInstance ? 8000 : 4000,
- message: hasComputeInstance
- ? 'Your organization has been downgraded and your projects are currently restarting to update their compute instances'
- : 'Successfully downgraded organization to the free plan',
- })
- onClose(true)
- setIsSubmitting(false)
- window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
- }
+ await updateOrgSubscription({ slug, tier: 'tier_free' })
+ resetCaptcha()
+
+ await sendExitSurvey({
+ orgSlug: slug,
+ reasons: selectedReasons.reduce((a, b) => `${a}- ${b}\n`, ''),
+ message,
+ })
+
+ ui.setNotification({
+ category: 'success',
+ duration: hasComputeInstance ? 8000 : 4000,
+ message: hasComputeInstance
+ ? 'Your organization has been downgraded and your projects are currently restarting to update their compute instances'
+ : 'Successfully downgraded organization to the free plan',
+ })
+ onClose(true)
+ window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
}
return (
diff --git a/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectButton.tsx b/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectButton.tsx
index 915c12b0dc5..993331d8e40 100644
--- a/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectButton.tsx
+++ b/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectButton.tsx
@@ -1,6 +1,5 @@
import * as Tooltip from '@radix-ui/react-tooltip'
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useQueryClient } from '@tanstack/react-query'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import { Button, Input } from 'ui'
@@ -8,41 +7,43 @@ import { Button, Input } from 'ui'
import { CANCELLATION_REASONS } from 'components/interfaces/BillingV2/Billing.constants'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import TextConfirmModal from 'components/ui/Modals/TextConfirmModal'
-import { invalidateProjectsQuery } from 'data/projects/projects-query'
+import { useSendDowngradeFeedbackMutation } from 'data/feedback/feedback-downgrade-send'
+import { useProjectDeleteMutation } from 'data/projects/project-delete-mutation'
import { useCheckPermissions, useStore } from 'hooks'
-import { delete_, post } from 'lib/common/fetch'
-import { API_URL, PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
+import { PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
export interface DeleteProjectButtonProps {
type?: 'danger' | 'default'
}
const DeleteProjectButton = ({ type = 'danger' }: DeleteProjectButtonProps) => {
- const queryClient = useQueryClient()
const router = useRouter()
const { ui } = useStore()
-
const { project } = useProjectContext()
+
const projectRef = project?.ref
const projectTier = project?.subscription_tier ?? PRICING_TIER_PRODUCT_IDS.FREE
const isFree = projectTier === PRICING_TIER_PRODUCT_IDS.FREE
const [isOpen, setIsOpen] = useState(false)
- const [loading, setLoading] = useState(false)
+ const [message, setMessage] = useState<string>('')
const [selectedReasons, setSelectedReasons] = useState<string[]>([])
- const [cancellationMessage, setCancellationMessage] = useState<string>('')
+
+ const { mutateAsync: deleteProject, isLoading: isDeleting } = useProjectDeleteMutation()
+ const { mutateAsync: sendExitSurvey, isLoading: isSending } = useSendDowngradeFeedbackMutation()
+ const isSubmitting = isDeleting || isSending
useEffect(() => {
if (isOpen) {
setSelectedReasons([])
- setCancellationMessage('')
+ setMessage('')
}
}, [isOpen])
const canDeleteProject = useCheckPermissions(PermissionAction.UPDATE, 'projects')
const toggle = () => {
- if (loading) return
+ if (isSubmitting) return
setIsOpen(!isOpen)
}
@@ -66,31 +67,15 @@ const DeleteProjectButton = ({ type = 'danger' }: DeleteProjectButtonProps) => {
})
}
- setLoading(true)
- try {
- const response = await delete_(`${API_URL}/projects/${projectRef}`)
- if (response.error) throw response.error
- await invalidateProjectsQuery(queryClient)
- ui.setNotification({ category: 'success', message: `Successfully deleted ${project.name}` })
- router.push(`/projects`)
- } catch (error: any) {
- setLoading(false)
- ui.setNotification({
- category: 'error',
- message: `Failed to delete project ${project.name}: ${error.message}`,
- })
- }
+ await deleteProject({ projectRef: project.ref })
+ await sendExitSurvey({
+ projectRef,
+ message,
+ reasons: selectedReasons.reduce((a, b) => `${a}- ${b}\n`, ''),
+ })
- // Submit exit survey to Hubspot for paid projects
- if (!isFree) {
- const feedbackRes = await post(`${API_URL}/feedback/downgrade`, {
- projectRef,
- reasons: selectedReasons.reduce((a, b) => `${a}- ${b}\n`, ''),
- additionalFeedback: cancellationMessage,
- exitAction: 'delete',
- })
- if (feedbackRes.error) throw feedbackRes.error
- }
+ ui.setNotification({ category: 'success', message: `Successfully deleted ${project.name}` })
+ router.push(`/projects`)
}
return (
@@ -121,7 +106,7 @@ const DeleteProjectButton = ({ type = 'danger' }: DeleteProjectButtonProps) => {
</Tooltip.Root>
<TextConfirmModal
visible={isOpen}
- loading={loading}
+ loading={isSubmitting}
size={isFree ? 'small' : 'xlarge'}
title={`Confirm deletion of ${project?.name}`}
alert={
@@ -188,8 +173,8 @@ const DeleteProjectButton = ({ type = 'danger' }: DeleteProjectButtonProps) => {
name="message"
label="Anything else that we can improve on?"
rows={3}
- value={cancellationMessage}
- onChange={(event) => setCancellationMessage(event.target.value)}
+ value={message}
+ onChange={(event) => setMessage(event.target.value)}
/>
</div>
</div>
diff --git a/studio/data/feedback/feedback-downgrade-send.ts b/studio/data/feedback/feedback-downgrade-send.ts
new file mode 100644
index 00000000000..1faecb67fc0
--- /dev/null
+++ b/studio/data/feedback/feedback-downgrade-send.ts
@@ -0,0 +1,54 @@
+import { useMutation, UseMutationOptions } from '@tanstack/react-query'
+import toast from 'react-hot-toast'
+
+import { post } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { ResponseError } from 'types'
+
+export type SendDowngradeFeedbackVariables = {
+ projectRef?: string
+ orgSlug?: string
+ reasons: string
+ message: string
+}
+
+export async function sendDowngradeFeedback({
+ projectRef,
+ orgSlug,
+ reasons,
+ message,
+}: SendDowngradeFeedbackVariables) {
+ const response = await post(`${API_URL}/feedback/downgrade`, {
+ ...(projectRef !== undefined && { projectRef }),
+ ...(orgSlug !== undefined && { orgSlug }),
+ reasons,
+ additionalFeedback: message,
+ exitAction: 'downgrade',
+ })
+ if (response.error) throw response.error
+ return response
+}
+
+type SendDowngradeFeedbackData = Awaited<ReturnType<typeof sendDowngradeFeedback>>
+
+export const useSendDowngradeFeedbackMutation = ({
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<SendDowngradeFeedbackData, ResponseError, SendDowngradeFeedbackVariables>,
+ 'mutationFn'
+> = {}) => {
+ return useMutation<SendDowngradeFeedbackData, ResponseError, SendDowngradeFeedbackVariables>(
+ (vars) => sendDowngradeFeedback(vars),
+ {
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to submit exit survey: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/studio/data/projects/project-delete-mutation.ts b/studio/data/projects/project-delete-mutation.ts
new file mode 100644
index 00000000000..feab99f1c68
--- /dev/null
+++ b/studio/data/projects/project-delete-mutation.ts
@@ -0,0 +1,48 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'react-hot-toast'
+
+import { delete_ } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { ResponseError } from 'types'
+import { projectKeys } from './keys'
+
+export type ProjectDeleteVariables = {
+ projectRef: string
+}
+
+export async function deleteProject({ projectRef }: ProjectDeleteVariables) {
+ const response = await delete_(`${API_URL}/projects/${projectRef}`)
+ if (response.error) throw response.error
+ return response
+}
+
+type ProjectDeleteData = Awaited<ReturnType<typeof deleteProject>>
+
+export const useProjectDeleteMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<ProjectDeleteData, ResponseError, ProjectDeleteVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<ProjectDeleteData, ResponseError, ProjectDeleteVariables>(
+ (vars) => deleteProject(vars),
+ {
+ async onSuccess(data, variables, context) {
+ await queryClient.invalidateQueries(projectKeys.list()),
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to delete project: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}