Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: add delete team

Marc Seitz38869ff63c12
diff --git a/components/settings/delete-team-modal.tsx b/components/settings/delete-team-modal.tsx
new file mode 100644
index 00000000..380e3f36
--- /dev/null
+++ b/components/settings/delete-team-modal.tsx
@@ -0,0 +1,163 @@
+import { useRouter } from "next/router";
+
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useMemo,
+ useState,
+} from "react";
+
+import { TeamContextType, useTeam } from "@/context/team-context";
+import { signOut } from "next-auth/react";
+import { toast } from "sonner";
+import { mutate } from "swr";
+
+import { Button } from "@/components/ui/button";
+import { CardDescription, CardTitle } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Modal } from "@/components/ui/modal";
+
+import { useMediaQuery } from "@/lib/utils/use-media-query";
+
+function DeleteTeamModal({
+ showDeleteTeamModal,
+ setShowDeleteTeamModal,
+}: {
+ showDeleteTeamModal: boolean;
+ setShowDeleteTeamModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ const router = useRouter();
+ const teamInfo = useTeam();
+
+ const [deleting, setDeleting] = useState(false);
+
+ async function deleteTeam() {
+ const teamsCount = teamInfo?.teams.length ?? 1;
+
+ return new Promise((resolve, reject) => {
+ setDeleting(true);
+
+ fetch(`/api/teams/${teamInfo?.currentTeam?.id}`, {
+ method: "DELETE",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }).then(async (res) => {
+ if (res.ok) {
+ await mutate("/api/teams");
+ console.log("teamsCount", teamsCount);
+ teamsCount > 1 ? router.push("/documents") : signOut();
+ resolve(null);
+ } else {
+ setDeleting(false);
+ const error = await res.json();
+ reject(error.message);
+ }
+ });
+ });
+ }
+
+ const { isMobile } = useMediaQuery();
+
+ return (
+ <Modal
+ showModal={showDeleteTeamModal}
+ setShowModal={setShowDeleteTeamModal}
+ >
+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-border bg-white px-4 py-4 pt-8 dark:border-gray-900 dark:bg-gray-900 sm:px-8">
+ <CardTitle>Delete Team</CardTitle>
+ <CardDescription>
+ Warning: This will permanently delete your team, custom domains,
+ documents and all associated links and their respective views.
+ </CardDescription>
+ </div>
+
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ toast.promise(deleteTeam(), {
+ loading: "Deleting team...",
+ success: "Team deleted successfully!",
+ error: (err) => err,
+ });
+ }}
+ className="flex flex-col space-y-6 bg-muted px-4 py-8 text-left dark:bg-gray-900 sm:px-8"
+ >
+ <div>
+ <label
+ htmlFor="team-name"
+ className="block text-sm font-medium text-muted-foreground"
+ >
+ Enter the team name{" "}
+ <span className="font-semibold text-foreground">
+ {teamInfo?.currentTeam?.name}
+ </span>{" "}
+ to continue:
+ </label>
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <Input
+ type="text"
+ name="team-name"
+ id="team-name"
+ autoFocus={!isMobile}
+ autoComplete="off"
+ required
+ pattern={teamInfo?.currentTeam?.name}
+ className="bg-white dark:border-gray-500 dark:bg-gray-800 focus:dark:bg-transparent"
+ />
+ </div>
+ </div>
+
+ <div>
+ <label
+ htmlFor="verification"
+ className="block text-sm text-muted-foreground"
+ >
+ To verify, type{" "}
+ <span className="font-semibold text-foreground">
+ confirm delete team
+ </span>{" "}
+ below
+ </label>
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <Input
+ type="text"
+ name="verification"
+ id="verification"
+ pattern="confirm delete team"
+ required
+ autoComplete="off"
+ className="bg-white dark:border-gray-500 dark:bg-gray-800 focus:dark:bg-transparent"
+ />
+ </div>
+ </div>
+
+ <Button variant="destructive" loading={deleting}>
+ Confirm delete team
+ </Button>
+ </form>
+ </Modal>
+ );
+}
+
+export function useDeleteTeamModal() {
+ const [showDeleteTeamModal, setShowDeleteTeamModal] = useState(false);
+
+ const DeleteTeamModalCallback = useCallback(() => {
+ return (
+ <DeleteTeamModal
+ showDeleteTeamModal={showDeleteTeamModal}
+ setShowDeleteTeamModal={setShowDeleteTeamModal}
+ />
+ );
+ }, [showDeleteTeamModal, setShowDeleteTeamModal]);
+
+ return useMemo(
+ () => ({
+ setShowDeleteTeamModal,
+ DeleteTeamModal: DeleteTeamModalCallback,
+ }),
+ [setShowDeleteTeamModal, DeleteTeamModalCallback],
+ );
+}
diff --git a/components/settings/delete-team.tsx b/components/settings/delete-team.tsx
new file mode 100644
index 00000000..9e7cf89d
--- /dev/null
+++ b/components/settings/delete-team.tsx
@@ -0,0 +1,43 @@
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+
+import { useDeleteTeamModal } from "./delete-team-modal";
+
+export default function DeleteTeam() {
+ const { setShowDeleteTeamModal, DeleteTeamModal } = useDeleteTeamModal();
+
+ return (
+ <div className="rounded-lg">
+ <DeleteTeamModal />
+ <Card className="border-destructive bg-transparent">
+ <CardHeader>
+ <CardTitle>Delete Team</CardTitle>
+ <CardDescription>
+ Permanently delete your team, custom domains, and all associated
+ documents, links + their views. <br />
+ <span className="font-medium">This action cannot be undone</span> -
+ please proceed with caution.
+ </CardDescription>
+ </CardHeader>
+ <CardContent></CardContent>
+ <CardFooter className="flex items-center justify-end rounded-b-lg border-t px-6 py-3">
+ <div className="shrink-0">
+ <Button
+ onClick={() => setShowDeleteTeamModal(true)}
+ variant="destructive"
+ >
+ Delete Team
+ </Button>
+ </div>
+ </CardFooter>
+ </Card>
+ </div>
+ );
+}
diff --git a/components/ui/modal.tsx b/components/ui/modal.tsx
new file mode 100644
index 00000000..ddc4debb
--- /dev/null
+++ b/components/ui/modal.tsx
@@ -0,0 +1,106 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+
+import { Dispatch, SetStateAction } from "react";
+
+import * as Dialog from "@radix-ui/react-dialog";
+import { Drawer } from "vaul";
+
+import { cn } from "@/lib/utils";
+import { useMediaQuery } from "@/lib/utils/use-media-query";
+
+export function Modal({
+ children,
+ className,
+ showModal,
+ setShowModal,
+ onClose,
+ desktopOnly,
+ preventDefaultClose,
+}: {
+ children: React.ReactNode;
+ className?: string;
+ showModal?: boolean;
+ setShowModal?: Dispatch<SetStateAction<boolean>>;
+ onClose?: () => void;
+ desktopOnly?: boolean;
+ preventDefaultClose?: boolean;
+}) {
+ const router = useRouter();
+
+ const closeModal = ({ dragged }: { dragged?: boolean } = {}) => {
+ if (preventDefaultClose && !dragged) {
+ return;
+ }
+ // fire onClose event if provided
+ onClose && onClose();
+
+ // if setShowModal is defined, use it to close modal
+ if (setShowModal) {
+ setShowModal(false);
+ // else, this is intercepting route @modal
+ } else {
+ router.back();
+ }
+ };
+ const { isMobile } = useMediaQuery();
+
+ if (isMobile && !desktopOnly) {
+ return (
+ <Drawer.Root
+ open={setShowModal ? showModal : true}
+ onOpenChange={(open) => {
+ if (!open) {
+ closeModal({ dragged: true });
+ }
+ }}
+ >
+ <Drawer.Overlay className="fixed inset-0 z-50 bg-background/80 backdrop-blur" />
+ <Drawer.Portal>
+ <Drawer.Content
+ className={cn(
+ "fixed bottom-0 left-0 right-0 z-50 mt-24 rounded-t-[10px] border-t border-gray-200 bg-background dark:border-gray-800 dark:bg-gray-900",
+ className,
+ )}
+ >
+ <div className="sticky top-0 z-20 flex w-full items-center justify-center rounded-t-[10px] bg-inherit">
+ <div className="my-3 h-1 w-12 rounded-full bg-gray-300" />
+ </div>
+ {children}
+ </Drawer.Content>
+ <Drawer.Overlay />
+ </Drawer.Portal>
+ </Drawer.Root>
+ );
+ }
+
+ return (
+ <Dialog.Root
+ open={setShowModal ? showModal : true}
+ onOpenChange={(open) => {
+ if (!open) {
+ closeModal();
+ }
+ }}
+ >
+ <Dialog.Portal>
+ <Dialog.Overlay
+ // for detecting when there's an active opened modal
+ id="modal-backdrop"
+ className="animate-fade-in fixed inset-0 z-50 bg-background/80 backdrop-blur-md"
+ />
+ <Dialog.Content
+ onOpenAutoFocus={(e) => e.preventDefault()}
+ onCloseAutoFocus={(e) => e.preventDefault()}
+ className={cn(
+ "animate-scale-in fixed inset-0 z-50 m-auto max-h-fit w-full max-w-md overflow-hidden border border-gray-200 bg-background p-0 shadow-xl dark:border-gray-800 dark:bg-gray-900 sm:rounded-lg",
+ className,
+ )}
+ >
+ {children}
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
diff --git a/lib/files/delete-team-files-server.ts b/lib/files/delete-team-files-server.ts
new file mode 100644
index 00000000..7119a273
--- /dev/null
+++ b/lib/files/delete-team-files-server.ts
@@ -0,0 +1,61 @@
+import { DeleteObjectsCommand, ListObjectsV2Command } from "@aws-sdk/client-s3";
+import { del } from "@vercel/blob";
+
+import { getS3Client } from "./aws-client";
+
+export type DeleteFilesOptions = {
+ teamId: string;
+ data?: string[]; // urls for vercel, not needed for s3
+};
+
+export const deleteFiles = async ({ teamId, data }: DeleteFilesOptions) => {
+ // run both delete functions in parallel
+ await Promise.allSettled([
+ deleteAllFilesFromS3Server(teamId),
+ data && deleteFileFromVercelServer(data),
+ ]);
+};
+
+const deleteFileFromVercelServer = async (urls: string[]) => {
+ const deleteUrlsPromises = urls.map((url) => del(url));
+ await Promise.allSettled(deleteUrlsPromises);
+};
+
+const deleteAllFilesFromS3Server = async (teamId: string) => {
+ // the teamId is the first prefix in the folder path
+ const folderPath = teamId;
+
+ const client = getS3Client();
+
+ try {
+ // List all objects in the folder
+ const listParams = {
+ Bucket: process.env.NEXT_PRIVATE_UPLOAD_BUCKET,
+ Prefix: `${folderPath}/`, // Ensure this ends with a slash if it's a folder
+ };
+ const listedObjects = await client.send(
+ new ListObjectsV2Command(listParams),
+ );
+
+ if (!listedObjects.Contents) return;
+ if (listedObjects.Contents.length === 0) return;
+
+ // Prepare delete parameters
+ const deleteParams = {
+ Bucket: process.env.NEXT_PRIVATE_UPLOAD_BUCKET,
+ Delete: {
+ Objects: listedObjects.Contents.map((file) => ({ Key: file.Key })),
+ },
+ };
+
+ // Delete the objects
+ await client.send(new DeleteObjectsCommand(deleteParams));
+
+ if (listedObjects.IsTruncated) {
+ // If there are more files than returned in a single request, recurse
+ await deleteAllFilesFromS3Server(folderPath);
+ }
+ } catch (error) {
+ console.error("Error deleting files:", error);
+ }
+};
diff --git a/pages/api/teams/[teamId]/index.ts b/pages/api/teams/[teamId]/index.ts
index 38646617..20f88032 100644
--- a/pages/api/teams/[teamId]/index.ts
+++ b/pages/api/teams/[teamId]/index.ts
@@ -1,9 +1,13 @@
import { NextApiRequest, NextApiResponse } from "next";
+import { DocumentStorageType } from "@prisma/client";
import { getServerSession } from "next-auth";
+import { removeDomainFromVercelProject } from "@/lib/domains";
import { errorhandler } from "@/lib/errorHandler";
+import { deleteFiles } from "@/lib/files/delete-team-files-server";
import prisma from "@/lib/prisma";
+import { cancelSubscription } from "@/lib/stripe";
import { CustomUser } from "@/lib/types";
import { authOptions } from "../../auth/[...nextauth]";
@@ -86,6 +90,7 @@ export default async function handle(
},
include: {
users: true,
+ domains: true,
},
});
if (!team) {
@@ -101,16 +106,128 @@ export default async function handle(
if (!isUserAdmin) {
return res
.status(403)
- .json("You are not permitted to perform this action");
+ .json({ message: "You are not permitted to perform this action" });
}
- // delete team
- await prisma.team.delete({
+ // get all documents using Vercel Blob storage
+ const documentsUsingBlob = await prisma.document.findMany({
where: {
- id: teamId,
+ teamId: teamId,
+ storageType: DocumentStorageType.VERCEL_BLOB,
+ },
+ select: {
+ file: true,
+ versions: {
+ select: {
+ file: true,
+ pages: {
+ select: {
+ file: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ // get all branding files
+ const brandingFiles = await prisma.brand.findMany({
+ where: {
+ teamId,
+ },
+ select: {
+ logo: true,
+ },
+ });
+
+ // get all dataroom branding files
+ const dataroomBrandingFiles = await prisma.dataroomBrand.findMany({
+ where: {
+ dataroom: {
+ teamId: teamId,
+ },
+ },
+ select: {
+ logo: true,
+ banner: true,
},
});
+ let files: string[] = [];
+ let hasBlobDocuments = false;
+
+ if (documentsUsingBlob) {
+ hasBlobDocuments = true;
+ // flatten documents and extract file fields
+ files = documentsUsingBlob.flatMap((doc) => [
+ doc.file,
+ ...doc.versions.flatMap((version) => [
+ version.file,
+ ...version.pages.map((page) => page.file),
+ ]),
+ ]);
+ }
+
+ if (brandingFiles) {
+ files = [
+ ...files,
+ ...brandingFiles
+ .map((brand) => brand.logo)
+ .filter((logo): logo is string => logo !== null),
+ ];
+ }
+
+ if (dataroomBrandingFiles) {
+ files = [
+ ...files,
+ ...dataroomBrandingFiles
+ .flatMap((brand) => [brand.logo, brand.banner])
+ .filter((item): item is string => item !== null),
+ ];
+ }
+
+ // delete all files from storage
+ await deleteFiles({ teamId, data: hasBlobDocuments ? files : undefined });
+
+ // if user doesn't have other teams, delete the user
+ const userTeams = await prisma.team.findMany({
+ where: {
+ users: {
+ some: {
+ userId: (session.user as CustomUser).id,
+ },
+ },
+ },
+ });
+
+ // prepare a list of promises to delete domains
+ let domainPromises: void[] = [];
+ if (team.domains) {
+ domainPromises = team.domains.map((domain) => {
+ removeDomainFromVercelProject(domain.slug);
+ });
+ }
+
+ await Promise.all([
+ // delete domains, if exists on team
+ team.domains && domainPromises,
+ // delete subscription, if exists on team
+ team.stripeId && cancelSubscription(team.stripeId),
+ // delete user, if no other teams
+ userTeams.length === 1 &&
+ prisma.user.delete({
+ where: {
+ id: (session.user as CustomUser).id,
+ },
+ }),
+ // delete team
+ prisma.team.delete({
+ where: {
+ id: teamId,
+ },
+ }),
+ ]);
+
return res.status(204).end();
} catch (error) {
return res.status(500).json((error as Error).message);
diff --git a/pages/settings/general.tsx b/pages/settings/general.tsx
index 02bbd461..78057b90 100644
--- a/pages/settings/general.tsx
+++ b/pages/settings/general.tsx
@@ -7,6 +7,7 @@ import { toast } from "sonner";
import { mutate } from "swr";
import AppLayout from "@/components/layouts/app";
+import DeleteTeam from "@/components/settings/delete-team";
import { SettingsHeader } from "@/components/settings/settings-header";
import Passkey from "@/components/shared/icons/passkey";
import { Button } from "@/components/ui/button";
@@ -106,6 +107,8 @@ export default function General() {
</Button>
</div>
</div>
+
+ <DeleteTeam />
</div>
</main>
</AppLayout>
diff --git a/prisma/migrations/20240720000000_change_owner_dependecy/migration.sql b/prisma/migrations/20240720000000_change_owner_dependecy/migration.sql
new file mode 100644
index 00000000..87dbab55
--- /dev/null
+++ b/prisma/migrations/20240720000000_change_owner_dependecy/migration.sql
@@ -0,0 +1,32 @@
+-- DropForeignKey
+ALTER TABLE "Document" DROP CONSTRAINT "Document_ownerId_fkey";
+
+-- DropForeignKey
+ALTER TABLE "Document" DROP CONSTRAINT "Document_teamId_fkey";
+
+-- DropForeignKey
+ALTER TABLE "Domain" DROP CONSTRAINT "Domain_teamId_fkey";
+
+-- DropForeignKey
+ALTER TABLE "Domain" DROP CONSTRAINT "Domain_userId_fkey";
+
+-- AlterTable
+ALTER TABLE "Document" ALTER COLUMN "ownerId" DROP NOT NULL,
+ALTER COLUMN "teamId" SET NOT NULL;
+
+-- AlterTable
+ALTER TABLE "Domain" ALTER COLUMN "userId" DROP NOT NULL,
+ALTER COLUMN "teamId" SET NOT NULL;
+
+-- AddForeignKey
+ALTER TABLE "Document" ADD CONSTRAINT "Document_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "Document" ADD CONSTRAINT "Document_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "Domain" ADD CONSTRAINT "Domain_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "Domain" ADD CONSTRAINT "Domain_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 8a266bfa..70cf3bd3 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -128,10 +128,10 @@ model Document {
type String? // This should be a reference to the file type (pdf, sheet, etc.)
storageType DocumentStorageType @default(VERCEL_BLOB)
numPages Int? // This should be a reference to the number of pages in the document
- owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
- teamId String?
- team Team? @relation(fields: [teamId], references: [id], onDelete: SetNull)
- ownerId String // This field holds the foreign key.
+ owner User? @relation(fields: [ownerId], references: [id], onDelete: SetNull)
+ teamId String
+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
+ ownerId String? // This field holds the foreign key.
assistantEnabled Boolean @default(false) // This indicates if assistant is enabled for this document
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -244,10 +244,10 @@ model Link {
model Domain {
id String @id @default(cuid())
slug String @unique
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
- userId String
- teamId String?
- Team Team? @relation(fields: [teamId], references: [id], onDelete: SetNull)
+ user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
+ userId String?
+ teamId String
+ Team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
verified Boolean @default(false) // Whether the domain has been verified
lastChecked DateTime @default(now())
createdAt DateTime @default(now())
diff --git a/tailwind.config.js b/tailwind.config.js
index b11eed46..0100e238 100644
--- a/tailwind.config.js
+++ b/tailwind.config.js
@@ -151,6 +151,16 @@ module.exports = {
//** END: TREMOR fontSize **//
},
keyframes: {
+ // Modal
+ "scale-in": {
+ "0%": { transform: "scale(0.95)" },
+ "100%": { transform: "scale(1)" },
+ },
+ "fade-in": {
+ "0%": { opacity: "0" },
+ "100%": { opacity: "1" },
+ },
+ // Others
gauge_fadeIn: {
from: { opacity: "0" },
to: { opacity: "1" },
@@ -182,6 +192,10 @@ module.exports = {
16: "repeat(16, minmax(0, 1fr))",
},
animation: {
+ // Modal
+ "scale-in": "scale-in 0.2s cubic-bezier(0.16, 1, 0.3, 1)",
+ "fade-in": "fade-in 0.2s ease-out forwards",
+ // Others
gauge_fadeIn: "gauge_fadeIn 1s ease forwards",
gauge_fill: "gauge_fill 1s ease forwards",
flyEmoji: "flyEmoji 1s forwards",