Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: make components compatible with datarooms
Marc Seitz6a6cab151879
diff --git a/components/documents/add-document-modal.tsx b/components/documents/add-document-modal.tsxindex c27b5cf1..0022f6b2 100644--- a/components/documents/add-document-modal.tsx+++ b/components/documents/add-document-modal.tsx@@ -24,13 +24,18 @@ import {createNewDocumentVersion,} from "@/lib/documents/create-document";import { useAnalytics } from "@/lib/analytics";+import { mutate } from "swr";export function AddDocumentModal({newVersion,children,+ isDataroom,+ dataroomId,}: {newVersion?: boolean;children: React.ReactNode;+ isDataroom?: boolean;+ dataroomId?: string;}) {const router = useRouter();const plausible = usePlausible();@@ -94,6 +99,26 @@ export function AddDocumentModal({if (response) {const document = await response.json();+ if (isDataroom && dataroomId) {+ await addDocumentToDataroom({+ documentId: document.id,+ folderPathName: currentFolderPath?.join("/"),+ });++ plausible("documentUploaded");+ analytics.capture("Document Added", {+ documentId: document.id,+ name: document.name,+ numPages: document.numPages,+ path: router.asPath,+ type: "pdf",+ teamId: teamId,+ dataroomId: dataroomId,+ });++ return;+ }+if (!newVersion) {// copy the link to the clipboardcopyToClipboard(@@ -148,6 +173,51 @@ export function AddDocumentModal({}};+ const addDocumentToDataroom = async ({+ documentId,+ folderPathName,+ }: {+ documentId: string;+ folderPathName?: string;+ }) => {+ try {+ const response = await fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ documentId: documentId,+ folderPathName: folderPathName,+ }),+ },+ );++ if (!response.ok) {+ const { message } = await response.json();+ toast.error(message);+ return;+ }++ mutate(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents`,+ );+ mutate(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/folders/documents/${folderPathName}`,+ );++ toast.success("Document added to dataroom successfully! 🎉");+ } catch (error) {+ toast.error("Error adding document to dataroom.");+ console.error(+ "An error occurred while adding document to the dataroom: ",+ error,+ );+ }+ };+const createNotionFileName = () => {// Extract Notion file name from the URLconst urlSegments = (notionLink as string).split("/")[3];@@ -199,6 +269,27 @@ export function AddDocumentModal({if (response) {const document = await response.json();+ if (isDataroom && dataroomId) {+ await addDocumentToDataroom({+ documentId: document.id,+ folderPathName: currentFolderPath?.join("/"),+ });++ plausible("documentUploaded");+ plausible("notionDocumentUploaded");+ analytics.capture("Document Added", {+ documentId: document.id,+ name: document.name,+ numPages: document.numPages,+ path: router.asPath,+ type: "notion",+ teamId: teamId,+ dataroomId: dataroomId,+ });++ return;+ }+if (!newVersion) {// copy the link to the clipboardcopyToClipboard(diff --git a/components/documents/folder-card.tsx b/components/documents/folder-card.tsxindex 351c551b..cb735beb 100644--- a/components/documents/folder-card.tsx+++ b/components/documents/folder-card.tsx@@ -13,14 +13,27 @@ import {import { MoreVertical, FolderIcon } from "lucide-react";import { useRef } from "react";import { FolderWithCount } from "@/lib/swr/use-documents";+import { DataroomFolderWithCount } from "@/lib/swr/use-dataroom";type FolderCardProps = {- folder: FolderWithCount;+ folder: FolderWithCount | DataroomFolderWithCount;teamInfo: TeamContextType | null;+ isDataroom?: boolean;+ dataroomId?: string;};-export default function FolderCard({ folder, teamInfo }: FolderCardProps) {+export default function FolderCard({+ folder,+ teamInfo,+ isDataroom,+ dataroomId,+}: FolderCardProps) {const dropdownRef = useRef<HTMLDivElement | null>(null);+ const folderPath =+ isDataroom && dataroomId+ ? `/datarooms/${dataroomId}/documents${folder.path}`+ : `/documents/tree${folder.path}`;+return (<li className="group/row relative rounded-lg p-3 border-0 dark:bg-secondary ring-1 ring-gray-400 dark:ring-gray-500 transition-all hover:ring-gray-500 hover:dark:ring-gray-400 hover:bg-secondary sm:p-4 flex justify-between items-center"><div className="min-w-0 flex shrink items-center space-x-2 sm:space-x-4">@@ -31,10 +44,7 @@ export default function FolderCard({ folder, teamInfo }: FolderCardProps) {<div className="flex-col"><div className="flex items-center"><h2 className="min-w-0 text-sm font-semibold leading-6 text-foreground truncate max-w-[150px] sm:max-w-md">- <Link- href={`/documents/tree${folder.path}`}- className="truncate w-full"- >+ <Link href={`${folderPath}`} className="truncate w-full"><span>{folder.name}</span><span className="absolute inset-0" /></Link>diff --git a/components/documents/process-status-bar.tsx b/components/documents/process-status-bar.tsxindex faa091b6..84038f6a 100644--- a/components/documents/process-status-bar.tsx+++ b/components/documents/process-status-bar.tsx@@ -42,14 +42,14 @@ export default function ProcessStatusBar({return null;}- const progress = Number(statuses[0].data?.progress) * 100 || 0;- const text = String(statuses[0].data?.text) || "";+ const progress = Number(statuses[0]?.data?.progress) * 100 || 0;+ const text = String(statuses[0]?.data?.text) || "";if (run.status === "FAILURE") {return (<Progressvalue={progress}- text={`Error processing document page ${Number(statuses[0].data?.currentPage)}`}+ text={`Error processing document page ${Number(statuses[0]?.data?.currentPage)}`}error={true}className={cn("w-full text-[8px] font-semibold rounded-none",diff --git a/components/links/link-sheet/index.tsx b/components/links/link-sheet/index.tsxindex 8b9b6a7e..77c35718 100644--- a/components/links/link-sheet/index.tsx+++ b/components/links/link-sheet/index.tsx@@ -21,6 +21,7 @@ import { useTeam } from "@/context/team-context";import { ScrollArea } from "@/components/ui/scroll-area";import { LinkOptions } from "./link-options";import { useAnalytics } from "@/lib/analytics";+import { LinkWithViews } from "@/lib/types";export const DEFAULT_LINK_PROPS = {id: null,@@ -65,13 +66,16 @@ export type DEFAULT_LINK_TYPE = {export default function LinkSheet({isOpen,setIsOpen,+ linkType,currentLink,+ existingLinks,}: {isOpen: boolean;setIsOpen: Dispatch<SetStateAction<boolean>>;+ linkType: "DOCUMENT_LINK" | "DATAROOM_LINK";currentLink?: DEFAULT_LINK_TYPE;+ existingLinks?: LinkWithViews[];}) {- const { links } = useDocumentLinks();const { domains } = useDomains();const teamInfo = useTeam();const analytics = useAnalytics();@@ -79,7 +83,7 @@ export default function LinkSheet({const [isLoading, setIsLoading] = useState<boolean>(false);const router = useRouter();- const documentId = router.query.id as string;+ const targetId = router.query.id as string;useEffect(() => {setData(currentLink || DEFAULT_LINK_PROPS);@@ -120,7 +124,9 @@ export default function LinkSheet({body: JSON.stringify({...data,metaImage: blobUrl,- documentId: documentId,+ targetId: targetId,+ linkType: linkType,+ teamId: teamInfo?.currentTeam?.id,}),});@@ -133,15 +139,16 @@ export default function LinkSheet({}const returnedLink = await response.json();+ const endpointTargetType = `${linkType.replace("_LINK", "").toLowerCase()}s`; // "documents" or "datarooms"if (currentLink) {setIsOpen(false);// Update the link in the list of linksmutate(- `/api/teams/${teamInfo?.currentTeam?.id}/documents/${encodeURIComponent(- documentId,+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}/${encodeURIComponent(+ targetId,)}/links`,- (links || []).map((link) =>+ (existingLinks || []).map((link) =>link.id === currentLink.id ? returnedLink : link,),false,@@ -151,16 +158,17 @@ export default function LinkSheet({setIsOpen(false);// Add the new link to the list of linksmutate(- `/api/teams/${teamInfo?.currentTeam?.id}/documents/${encodeURIComponent(- documentId,+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}/${encodeURIComponent(+ targetId,)}/links`,- [...(links || []), returnedLink],+ [...(existingLinks || []), returnedLink],false,);analytics.capture("Link Added", {linkId: returnedLink.id,- documentId,+ targetId,+ linkType,customDomain: returnedLink.domainSlug,});diff --git a/components/links/links-table.tsx b/components/links/links-table.tsxindex a2ceb6ec..3939e152 100644--- a/components/links/links-table.tsx+++ b/components/links/links-table.tsx@@ -41,13 +41,17 @@ import { usePlan } from "@/lib/swr/use-billing";import { useTeam } from "@/context/team-context";import ProcessStatusBar from "../documents/process-status-bar";import { Settings2Icon } from "lucide-react";+import { DocumentVersion } from "@prisma/client";export default function LinksTable({+ targetType,+ links,primaryVersion,}: {- primaryVersion: any;+ targetType: "DOCUMENT" | "DATAROOM";+ links?: LinkWithViews[];+ primaryVersion?: DocumentVersion;}) {- const { links } = useDocumentLinks();const router = useRouter();const { plan } = usePlan();const teamInfo = useTeam();@@ -93,7 +97,7 @@ export default function LinksTable({const handleArchiveLink = async (linkId: string,- documentId: string,+ targetId: string,isArchived: boolean,) => {setIsLoading(true);@@ -113,11 +117,12 @@ export default function LinksTable({}const archivedLink = await response.json();+ const endpointTargetType = `${targetType.toLowerCase()}s`; // "documents" or "datarooms"// Update the archived link in the list of linksmutate(- `/api/teams/${teamInfo?.currentTeam?.id}/documents/${encodeURIComponent(- documentId,+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}/${encodeURIComponent(+ targetId,)}/links`,(links || []).map((link) => (link.id === linkId ? archivedLink : link)),false,@@ -137,6 +142,8 @@ export default function LinksTable({const hasFreePlan = plan && plan.plan === "free";+ console.log("links", links);+return (<><div className="w-full">@@ -182,7 +189,8 @@ export default function LinksTable({)}>{/* Progress bar */}- {primaryVersion.type !== "notion" &&+ {primaryVersion &&+ primaryVersion.type !== "notion" &&!primaryVersion.hasPages ? (<ProcessStatusBardocumentVersionId={primaryVersion.id}@@ -287,7 +295,7 @@ export default function LinksTable({onClick={() =>handleArchiveLink(link.id,- link.documentId,+ link.documentId ?? link.dataroomId ?? "",link.isArchived,)}@@ -330,7 +338,9 @@ export default function LinksTable({<LinkSheetisOpen={isLinkSheetVisible}setIsOpen={setIsLinkSheetVisible}+ linkType={`${targetType}_LINK`}currentLink={selectedLink}+ existingLinks={links}/>{archivedLinksCount > 0 && (@@ -428,7 +438,9 @@ export default function LinksTable({onClick={() =>handleArchiveLink(link.id,- link.documentId,+ link.documentId ??+ link.dataroomId ??+ "",link.isArchived,)}diff --git a/pages/api/links/[id]/index.ts b/pages/api/links/[id]/index.tsindex cd62bac4..e6c4d615 100644--- a/pages/api/links/[id]/index.ts+++ b/pages/api/links/[id]/index.ts@@ -94,7 +94,11 @@ export default async function handle(}const { id } = req.query as { id: string };- const { documentId, password, expiresAt, ...linkDomainData } = req.body;+ const { targetId, linkType, password, expiresAt, ...linkDomainData } =+ req.body;++ const dataroomLink = linkType === "DATAROOM_LINK";+ const documentLink = linkType === "DOCUMENT_LINK";const hashedPassword =password && password.length > 0 ? await hashPassword(password) : null;@@ -153,7 +157,8 @@ export default async function handle(const updatedLink = await prisma.link.update({where: { id: id },data: {- documentId: documentId,+ documentId: documentLink ? targetId : null,+ dataroomId: dataroomLink ? targetId : null,password: hashedPassword,name: linkData.name || null,emailProtected: linkData.emailProtected,diff --git a/pages/api/links/index.ts b/pages/api/links/index.tsindex b53a9a6d..09f8c9af 100644--- a/pages/api/links/index.ts+++ b/pages/api/links/index.ts@@ -21,27 +21,53 @@ export default async function handler(return res.status(401).end("Unauthorized");}- const { documentId, password, expiresAt, ...linkDomainData } = req.body;+ const { targetId, linkType, password, expiresAt, ...linkDomainData } =+ req.body;const userId = (session.user as CustomUser).id;+ const dataroomLink = linkType === "DATAROOM_LINK";+ const documentLink = linkType === "DOCUMENT_LINK";+try {- // check if the the team that own the document has the current user- await getDocumentWithTeamAndUser({- docId: documentId,- userId,- options: {- team: {- select: {+ if (documentLink) {+ // check if the the team that own the document has the current user+ await getDocumentWithTeamAndUser({+ docId: targetId,+ userId,+ options: {+ team: {+ select: {+ users: {+ select: {+ userId: true,+ },+ },+ },+ },+ },+ });+ }++ if (dataroomLink) {+ const dataroom = await prisma.dataroom.findUnique({+ where: {+ id: targetId,+ team: {users: {- select: {- userId: true,+ some: {+ userId: userId,},},},},- },- });+ select: { id: true },+ });++ if (!dataroom) {+ return res.status(400).json({ error: "Dataroom not found." });+ }+ }const hashedPassword =password && password.length > 0 ? await hashPassword(password) : null;@@ -87,7 +113,9 @@ export default async function handler(// Fetch the link and its related document from the databaseconst link = await prisma.link.create({data: {- documentId: documentId,+ documentId: documentLink ? targetId : null,+ dataroomId: dataroomLink ? targetId : null,+ linkType,password: hashedPassword,name: linkData.name || null,emailProtected: linkData.emailProtected,diff --git a/pages/documents/[id]/index.tsx b/pages/documents/[id]/index.tsxindex 1b2d380c..b1cf76e6 100644--- a/pages/documents/[id]/index.tsx+++ b/pages/documents/[id]/index.tsx@@ -1,5 +1,5 @@import { getExtension } from "@/lib/utils";-import { useDocument } from "@/lib/swr/use-document";+import { useDocument, useDocumentLinks } from "@/lib/swr/use-document";import ErrorPage from "next/error";import AppLayout from "@/components/layouts/app";import LinkSheet from "@/components/links/link-sheet";@@ -31,12 +31,11 @@ import { usePlausible } from "next-plausible";import { mutate } from "swr";import { TrashIcon, Sparkles } from "lucide-react";import { StatsComponent } from "@/components/documents/stats";-import { Switch } from "@/components/ui/switch";-import { Label } from "@/components/ui/label";import { useTheme } from "next-themes";export default function DocumentPage() {const { document: prismaDocument, primaryVersion, error } = useDocument();+ const { links } = useDocumentLinks();const { theme, systemTheme } = useTheme();const isLight =theme === "light" || (theme === "system" && systemTheme === "light");@@ -406,14 +405,20 @@ export default function DocumentPage() {/>{/* Links */}- <LinksTable primaryVersion={primaryVersion} />+ <LinksTable+ links={links}+ targetType={"DOCUMENT"}+ primaryVersion={primaryVersion}+ />{/* Visitors */}<VisitorsTable numPages={primaryVersion.numPages!} /><LinkSheetisOpen={isLinkSheetOpen}+ linkType="DOCUMENT_LINK"setIsOpen={setIsLinkSheetOpen}+ existingLinks={links}/></>) : (