Skip to content

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

fix(studio): send exit survey before deleting a project (#51844)

Drew McLellanb859ca065966
diff --git a/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.test.tsx b/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.test.tsx
new file mode 100644
index 00000000000..04af40ef5cd
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.test.tsx
@@ -0,0 +1,127 @@
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { mockAnimationsApi } from 'jsdom-testing-mocks'
+import { HttpResponse } from 'msw'
+import { toast } from 'sonner'
+import { beforeEach, describe, expect, test, vi } from 'vitest'
+
+import { DeleteProjectModal } from './DeleteProjectModal'
+import type { OrgProject } from '@/data/projects/org-projects-infinite-query'
+import { createMockOrganization } from '@/tests/helpers'
+import { customRender } from '@/tests/lib/custom-render'
+import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
+
+mockAnimationsApi()
+
+// Heavy child with its own queries and permission checks, unrelated to this flow
+vi.mock('@/components/layouts/ProjectLayout/LogicalBackupCliInstructions', () => ({
+ LogicalBackupCliInstructions: () => null,
+}))
+
+const PROJECT: OrgProject = {
+ ref: 'abcdefghijklmnopqrst',
+ name: 'Project 1',
+ status: 'ACTIVE_HEALTHY',
+ cloud_provider: 'AWS',
+ region: 'us-east-1',
+ inserted_at: '2024-01-01T00:00:00Z',
+ integration_source: null,
+ is_branch: false,
+ databases: [],
+}
+const ORGANIZATION = createMockOrganization({ slug: 'org-slug', plan: { id: 'pro', name: 'Pro' } })
+
+const mockSubscription = (planId: 'free' | 'pro') => {
+ addAPIMock({
+ method: 'get',
+ path: '/platform/organizations/:slug/billing/subscription',
+ response: {
+ addons: [],
+ billing_via_partner: false,
+ current_period_end: 1700000000,
+ current_period_start: 1700000000,
+ next_invoice_at: 1700000000,
+ payment_method_type: 'card',
+ plan: { id: planId, name: planId },
+ project_addons: [],
+ usage_billing_enabled: false,
+ },
+ })
+}
+
+// Records the order requests hit the API, since the ordering is the contract under test
+const mockSurveyAndDelete = ({ surveyStatus }: { surveyStatus: 201 | 403 }) => {
+ const calls: string[] = []
+
+ // The selected-project hook fires alongside the props; the component prefers the props
+ addAPIMock({
+ method: 'get',
+ path: '/platform/projects/:ref',
+ response: () => HttpResponse.json<APIErrorBody>({ message: 'Not found' }, { status: 404 }),
+ })
+ addAPIMock({
+ method: 'post',
+ path: '/platform/feedback/downgrade',
+ response: () => {
+ calls.push('survey')
+ if (surveyStatus === 403) {
+ return HttpResponse.json<APIErrorBody>({ message: 'Forbidden' }, { status: 403 })
+ }
+ return HttpResponse.json<{ result: string }>({ result: 'success' }, { status: 201 })
+ },
+ })
+ addAPIMock({
+ method: 'delete',
+ path: '/platform/projects/:ref',
+ response: () => {
+ calls.push('delete')
+ return HttpResponse.json<{ id: number; name: string; ref: string }>({
+ id: 1,
+ name: PROJECT.name,
+ ref: PROJECT.ref,
+ })
+ },
+ })
+
+ return calls
+}
+
+const deleteProject = async () => {
+ const [reason] = await screen.findAllByRole('radio', { hidden: true })
+ fireEvent.click(reason)
+ await userEvent.type(screen.getByPlaceholderText('Type the project name in here'), PROJECT.name)
+ fireEvent.click(screen.getByRole('button', { name: 'I understand, delete this project' }))
+ await new Promise((r) => setTimeout(r, 300))
+ await new Promise((r) => setTimeout(r, 500))
+}
+
+describe('DeleteProjectModal', () => {
+ beforeEach(() => {
+ vi.spyOn(toast, 'error')
+ })
+
+ test('sends the exit survey before deleting a paid project', async () => {
+ mockSubscription('pro')
+ const calls = mockSurveyAndDelete({ surveyStatus: 201 })
+
+ customRender(
+ <DeleteProjectModal visible onClose={vi.fn()} project={PROJECT} organization={ORGANIZATION} />
+ )
+ await deleteProject()
+
+ await waitFor(() => expect(calls).toEqual(['survey', 'delete']))
+ })
+
+ test('still deletes the project, without an error toast, when the survey fails', async () => {
+ mockSubscription('pro')
+ const calls = mockSurveyAndDelete({ surveyStatus: 403 })
+
+ customRender(
+ <DeleteProjectModal visible onClose={vi.fn()} project={PROJECT} organization={ORGANIZATION} />
+ )
+ await deleteProject()
+
+ await waitFor(() => expect(calls).toEqual(['survey', 'delete']))
+ expect(toast.error).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.tsx b/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.tsx
index 1876bc1035e..18d723a1fc3 100644
--- a/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.tsx
+++ b/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.tsx
@@ -68,20 +68,6 @@ export const DeleteProjectModal = ({
const { mutate: deleteProject, isPending: isDeleting } = useProjectDeleteMutation({
onSuccess: async () => {
- if (!isFree) {
- try {
- await sendExitSurvey({
- orgSlug: organization?.slug,
- projectRef,
- message,
- reasons: selectedReason.reduce((a, b) => `${a}- ${b}\n`, ''),
- exitAction: 'delete',
- })
- } catch (error) {
- // [Joshen] In this case we don't raise any errors if the exit survey fails to send since it shouldn't block the user
- }
- }
-
toast.success(`Successfully deleted ${project?.name}`)
// Only redirect if still viewing the deleted project
@@ -94,7 +80,10 @@ export const DeleteProjectModal = ({
}
},
})
- const { mutateAsync: sendExitSurvey, isPending: isSending } = useSendDowngradeFeedbackMutation()
+ const { mutateAsync: sendExitSurvey, isPending: isSending } = useSendDowngradeFeedbackMutation({
+ // The user should not get a toast saying "submitting survey failed"
+ onError: () => {},
+ })
const isSubmitting = isDeleting || isSending
async function handleDeleteProject() {
@@ -103,6 +92,22 @@ export const DeleteProjectModal = ({
return toast.error('Please select a reason for deleting your project')
}
+ if (!isFree) {
+ // The survey must be sent before the delete: deleting the project removes its permissions,
+ // so the survey endpoint would reject the request afterwards.
+ try {
+ await sendExitSurvey({
+ orgSlug: organization?.slug,
+ projectRef: project.ref,
+ message,
+ reasons: selectedReason.reduce((a, b) => `${a}- ${b}\n`, ''),
+ exitAction: 'delete',
+ })
+ } catch {
+ // A failed survey should never block the user from deleting their project
+ }
+ }
+
deleteProject({ projectRef: project.ref, organizationSlug: organization?.slug })
}