DeleteProjectModal.tsx 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import { LOCAL_STORAGE_KEYS } from 'common'
  2. import { useRouter } from 'next/router'
  3. import { useEffect, useState } from 'react'
  4. import { toast } from 'sonner'
  5. import { TextArea } from 'ui'
  6. import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
  7. import { CANCELLATION_REASONS } from '@/components/interfaces/Billing/Billing.constants'
  8. import { LogicalBackupCliInstructions } from '@/components/layouts/ProjectLayout/LogicalBackupCliInstructions'
  9. import { TextConfirmModal } from '@/components/ui/TextConfirmModalWrapper'
  10. import { useSendDowngradeFeedbackMutation } from '@/data/feedback/exit-survey-send'
  11. import type { OrgProject } from '@/data/projects/org-projects-infinite-query'
  12. import { useProjectDeleteMutation } from '@/data/projects/project-delete-mutation'
  13. import { useOrgSubscriptionQuery } from '@/data/subscriptions/org-subscription-query'
  14. import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
  15. import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
  16. import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
  17. import type { Organization } from '@/types'
  18. export const DeleteProjectModal = ({
  19. visible,
  20. onClose,
  21. project: projectProp,
  22. organization: organizationProp,
  23. }: {
  24. visible: boolean
  25. onClose: () => void
  26. project?: OrgProject
  27. organization?: Organization
  28. }) => {
  29. const router = useRouter()
  30. const { data: projectFromQuery } = useSelectedProjectQuery()
  31. const { data: organizationFromQuery } = useSelectedOrganizationQuery()
  32. // Use props if provided, otherwise fall back to hooks
  33. const project = projectProp || projectFromQuery
  34. const organization = organizationProp || organizationFromQuery
  35. const [lastVisitedOrganization] = useLocalStorageQuery(
  36. LOCAL_STORAGE_KEYS.LAST_VISITED_ORGANIZATION,
  37. ''
  38. )
  39. const projectRef = project?.ref
  40. const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: organization?.slug })
  41. const projectPlan = subscription?.plan?.id ?? 'free'
  42. const isFree = projectPlan === 'free'
  43. const [message, setMessage] = useState<string>('')
  44. const [selectedReason, setSelectedReason] = useState<string[]>([])
  45. // Single select for cancellation reason
  46. const onSelectCancellationReason = (reason: string) => {
  47. setSelectedReason([reason])
  48. }
  49. // Helper to get label for selected reason
  50. const getReasonLabel = (reason: string | undefined) => {
  51. const found = CANCELLATION_REASONS.find((r) => r.value === reason)
  52. return found?.label || 'What can we improve on?'
  53. }
  54. const textareaLabel = getReasonLabel(selectedReason[0])
  55. const [shuffledReasons] = useState(() => [
  56. ...CANCELLATION_REASONS.sort(() => Math.random() - 0.5),
  57. { value: 'None of the above' },
  58. ])
  59. const { mutate: deleteProject, isPending: isDeleting } = useProjectDeleteMutation({
  60. onSuccess: async () => {
  61. if (!isFree) {
  62. try {
  63. await sendExitSurvey({
  64. orgSlug: organization?.slug,
  65. projectRef,
  66. message,
  67. reasons: selectedReason.reduce((a, b) => `${a}- ${b}\n`, ''),
  68. exitAction: 'delete',
  69. })
  70. } catch (error) {
  71. // [Joshen] In this case we don't raise any errors if the exit survey fails to send since it shouldn't block the user
  72. }
  73. }
  74. toast.success(`Successfully deleted ${project?.name}`)
  75. // Only redirect if still viewing the deleted project
  76. if (router.asPath.startsWith(`/project/${projectRef}`)) {
  77. if (lastVisitedOrganization) {
  78. router.push(`/org/${lastVisitedOrganization}`)
  79. } else {
  80. router.push('/organizations')
  81. }
  82. }
  83. },
  84. })
  85. const { mutateAsync: sendExitSurvey, isPending: isSending } = useSendDowngradeFeedbackMutation()
  86. const isSubmitting = isDeleting || isSending
  87. async function handleDeleteProject() {
  88. if (project === undefined) return
  89. if (!isFree && selectedReason.length === 0) {
  90. return toast.error('Please select a reason for deleting your project')
  91. }
  92. deleteProject({ projectRef: project.ref, organizationSlug: organization?.slug })
  93. }
  94. useEffect(() => {
  95. if (visible) {
  96. setSelectedReason([])
  97. setMessage('')
  98. }
  99. }, [visible])
  100. return (
  101. <TextConfirmModal
  102. visible={visible}
  103. loading={isSubmitting}
  104. size={isFree ? 'medium' : 'xlarge'}
  105. title={`Confirm deletion of ${project?.name}`}
  106. variant="destructive"
  107. alert={{
  108. title: isFree
  109. ? 'This action cannot be undone.'
  110. : `This will permanently delete the ${project?.name}`,
  111. description: !isFree ? `All project data will be lost, and cannot be undone` : '',
  112. }}
  113. text={
  114. isFree
  115. ? `This will permanently delete the ${project?.name} project and all of its data.`
  116. : undefined
  117. }
  118. confirmPlaceholder="Type the project name in here"
  119. confirmString={project?.name || ''}
  120. confirmLabel="I understand, delete this project"
  121. onConfirm={handleDeleteProject}
  122. onCancel={() => {
  123. if (!isSubmitting) onClose()
  124. }}
  125. >
  126. <div className="space-y-6">
  127. <LogicalBackupCliInstructions enabled={visible} showResetPassword={false} />
  128. {/*
  129. [Joshen] This is basically ExitSurvey.tsx, ideally we have one shared component but the one
  130. in ExitSurvey has a Form wrapped around it already. Will probably need some effort to refactor
  131. but leaving that for the future.
  132. */}
  133. {!isFree && (
  134. <div className="flex flex-col gap-y-6">
  135. <FormItemLayout
  136. isReactForm={false}
  137. label="What made you decide to delete your project?"
  138. >
  139. <div className="flex flex-wrap gap-2" data-toggle="buttons">
  140. {shuffledReasons.map((option) => {
  141. const active = selectedReason[0] === option.value
  142. return (
  143. <label
  144. key={option.value}
  145. className={[
  146. 'flex cursor-pointer items-center space-x-2 rounded-md py-1',
  147. 'pl-2 pr-3 text-center text-sm shadow-xs transition-all duration-100',
  148. `${
  149. active
  150. ? ` bg-foreground text-background opacity-100 hover:bg-foreground/75`
  151. : ` bg-border-strong text-foreground opacity-50 hover:opacity-75`
  152. }`,
  153. ].join(' ')}
  154. >
  155. <input
  156. type="radio"
  157. name="options"
  158. value={option.value}
  159. className="hidden"
  160. checked={active}
  161. onChange={() => onSelectCancellationReason(option.value)}
  162. />
  163. <div>{option.value}</div>
  164. </label>
  165. )
  166. })}
  167. </div>
  168. </FormItemLayout>
  169. <FormItemLayout isReactForm={false} label={textareaLabel}>
  170. <TextArea
  171. name="message"
  172. rows={3}
  173. value={message}
  174. onChange={(event) => setMessage(event.target.value)}
  175. />
  176. </FormItemLayout>
  177. </div>
  178. )}
  179. </div>
  180. </TextConfirmModal>
  181. )
  182. }