Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
Feat(dataroom): add download document btn to doc card
Ashish Viradiya0af983b25dd6
diff --git a/components/view/DataroomViewer.tsx b/components/view/DataroomViewer.tsxindex e284a88e..70a209a7 100644--- a/components/view/DataroomViewer.tsx+++ b/components/view/DataroomViewer.tsx@@ -1,7 +1,11 @@import { useMemo } from "react";import React from "react";-import { DataroomBrand, DataroomFolder } from "@prisma/client";+import {+ DataroomBrand,+ DataroomFolder,+ ViewerGroupAccessControls,+} from "@prisma/client";import * as SheetPrimitive from "@radix-ui/react-dialog";import { PanelLeftIcon, XIcon } from "lucide-react";@@ -30,6 +34,14 @@ import DataroomNav from "./dataroom/nav-dataroom";type FolderOrDocument = DataroomFolder | DataroomDocument;+export type DocumentVersion = {+ id: string;+ type: string;+ versionNumber: number;+ hasPages: boolean;+ isVertical: boolean;+};+type DataroomDocument = {dataroomDocumentId: string;folderId: string | null;@@ -37,13 +49,9 @@ type DataroomDocument = {name: string;orderIndex: number | null;downloadOnly: boolean;- versions: {- id: string;- type: string;- versionNumber: number;- hasPages: boolean;- isVertical: boolean;- }[];+ versions: DocumentVersion[];+ canDownload: boolean;+ canView: boolean;};const getParentFolders = (@@ -72,6 +80,7 @@ export default function DataroomViewer({isPreview,folderId,setFolderId,+ accessControls,}: {brand: Partial<DataroomBrand>;viewId?: string;@@ -81,6 +90,7 @@ export default function DataroomViewer({isPreview?: boolean;folderId: string | null;setFolderId: React.Dispatch<React.SetStateAction<string | null>>;+ accessControls: ViewerGroupAccessControls[];}) {const { documents, folders } = dataroom as {documents: DataroomDocument[];@@ -100,15 +110,33 @@ export default function DataroomViewer({.map((folder) => ({ ...folder, itemType: "folder" })),...(documents || []).filter((doc) => doc.folderId === folderId)- .map((doc) => ({ ...doc, itemType: "document" })),- ];+ .map((doc) => {+ const accessControl = accessControls.find(+ (access) => access.itemId === doc.dataroomDocumentId,+ );+ return {+ ...doc,+ itemType: "document",+ canDownload: accessControl?.canDownload ?? true,+ };+ }),+ ];return mixedItems.sort((a, b) => (a.orderIndex || 0) - (b.orderIndex || 0));- }, [folders, documents, folderId]);+ }, [folders, documents, folderId, accessControls]);const renderItem = (item: FolderOrDocument) => {if ("versions" in item) {- return <DocumentCard key={item.id} document={item} linkId={linkId} />;+ return (+ <DocumentCard+ key={item.id}+ document={item}+ linkId={linkId}+ viewId={viewId}+ isPreview={!!isPreview}+ allowDownload={allowDownload}+ />+ );}return (diff --git a/components/view/dataroom/dataroom-view.tsx b/components/view/dataroom/dataroom-view.tsxindex ccb980d9..d7bbbf0b 100644--- a/components/view/dataroom/dataroom-view.tsx+++ b/components/view/dataroom/dataroom-view.tsx@@ -72,6 +72,7 @@ export default function DataroomView({emailProtected,password: linkPassword,enableAgreement,+ group,} = link;const analytics = useAnalytics();@@ -243,6 +244,7 @@ export default function DataroomView({return (<div className="bg-gray-950"><DataroomViewer+ accessControls={group?.accessControls || []}brand={brand!}viewId={viewData.viewId}isPreview={viewData.isPreview}diff --git a/components/view/dataroom/document-card.tsx b/components/view/dataroom/document-card.tsxindex dbb41e5a..a87207e5 100644--- a/components/view/dataroom/document-card.tsx+++ b/components/view/dataroom/document-card.tsx@@ -2,31 +2,43 @@ import { useRouter } from "next/router";import React from "react";+import { ArrowDownToLineIcon } from "lucide-react";import { useTheme } from "next-themes";+import { toast } from "sonner";++import { Button } from "@/components/ui/button";import { fileIcon } from "@/lib/utils/get-file-icon";+import { DocumentVersion } from "../DataroomViewer";+type DRDocument = {dataroomDocumentId: string;id: string;name: string;downloadOnly: boolean;- versions: {- id: string;- type: string;- versionNumber: number;- hasPages: boolean;- isVertical: boolean;- }[];+ versions: DocumentVersion[];+ canDownload: boolean;};type DocumentsCardProps = {document: DRDocument;linkId: string;+ viewId?: string;+ isPreview: boolean;+ allowDownload: boolean;};-export default function DocumentCard({ document, linkId }: DocumentsCardProps) {+export default function DocumentCard({+ document,+ linkId,+ viewId,+ isPreview,+ allowDownload,+}: DocumentsCardProps) {const { theme, systemTheme } = useTheme();+ const canDownload = document.canDownload && allowDownload;+const isLight =theme === "light" || (theme === "system" && systemTheme === "light");const router = useRouter();@@ -51,10 +63,40 @@ export default function DocumentCard({ document, linkId }: DocumentsCardProps) {}};+ const downloadDocument = async () => {+ if (isPreview) {+ toast.error("You cannot download dataroom document in preview mode.");+ return;+ }+ try {+ const response = await fetch(`/api/links/download/dataroomDocumet`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ linkId,+ viewId,+ documentId: document.id,+ }),+ });++ if (!response.ok) {+ toast.error("Error downloading file");+ return;+ }+ const { downloadUrl } = await response.json();++ window.open(downloadUrl, "_blank");+ } catch (error) {+ console.error("Error downloading file:", error);+ }+ };+return (<><li className="group/row relative flex items-center justify-between rounded-lg border-0 p-3 ring-1 ring-gray-200 transition-all hover:bg-secondary hover:ring-gray-300 dark:bg-secondary dark:ring-gray-700 hover:dark:ring-gray-500 sm:p-4">- <div className="flex min-w-0 shrink items-center space-x-2 sm:space-x-4">+ <div className="z-0 flex min-w-0 shrink items-center space-x-2 sm:space-x-4"><div className="mx-0.5 flex w-8 items-center justify-center text-center sm:mx-1">{fileIcon({fileType: document.versions[0].type ?? "",@@ -77,6 +119,22 @@ export default function DocumentCard({ document, linkId }: DocumentsCardProps) {</div></div></div>+ {canDownload && (+ <div className="invisible z-10 group-hover/row:visible">+ <Button+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ downloadDocument();+ }}+ variant="default"+ className="rounded-md p-2"+ aria-label="Download document"+ >+ <ArrowDownToLineIcon className="h-5 w-5" />+ </Button>+ </div>+ )}</li></>);diff --git a/lib/api/links/link-data.ts b/lib/api/links/link-data.tsindex 36486a2d..86f06496 100644--- a/lib/api/links/link-data.ts+++ b/lib/api/links/link-data.ts@@ -89,6 +89,11 @@ export async function fetchDataroomLinkData({},},},+ group: {+ select: {+ accessControls: true,+ },+ },},});diff --git a/lib/types.ts b/lib/types.tsindex dc77590d..ce9c2a62 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -10,6 +10,7 @@ import {Link,User as PrismaUser,View,+ ViewerGroupAccessControls,} from "@prisma/client";import { User as NextAuthUser } from "next-auth";import { z } from "zod";@@ -129,6 +130,9 @@ export interface LinkWithDataroom extends Link {lastUpdatedAt: Date;createdAt: Date;};+ group?: {+ accessControls: ViewerGroupAccessControls[];+ };agreement: Agreement | null;customFields: CustomField[];}diff --git a/pages/api/links/download/dataroomDocumet.ts b/pages/api/links/download/dataroomDocumet.tsnew file mode 100644index 00000000..018cd19f--- /dev/null+++ b/pages/api/links/download/dataroomDocumet.ts@@ -0,0 +1,212 @@+import { NextApiRequest, NextApiResponse } from "next";++import { ItemType, ViewType } from "@prisma/client";++import { getFile } from "@/lib/files/get-file";+import prisma from "@/lib/prisma";+import { getIpAddress } from "@/lib/utils/ip";++export const config = {+ maxDuration: 180,+};++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "POST") {+ // POST /api/links/download/dataroomDocumet+ const { linkId, viewId, documentId } = req.body as {+ linkId: string;+ viewId: string;+ documentId: string;+ };++ try {+ const view = await prisma.view.findUnique({+ where: {+ id: viewId,+ linkId: linkId,+ viewType: { equals: ViewType.DATAROOM_VIEW },+ },+ select: {+ viewerId: true,+ verified: true,+ id: true,+ viewerEmail: true,+ viewedAt: true,+ link: {+ select: {+ enableWatermark: true,+ allowDownload: true,+ expiresAt: true,+ watermarkConfig: true,+ name: true,+ isArchived: true,+ },+ },+ groupId: true,+ dataroom: {+ select: {+ id: true,+ documents: {+ where: {+ documentId: documentId,+ },+ select: {+ id: true,+ document: {+ select: {+ name: true,+ versions: {+ where: { isPrimary: true },+ select: {+ type: true,+ file: true,+ storageType: true,+ originalFile: true,+ numPages: true,+ contentType: true,+ },+ take: 1,+ },+ },+ },+ },+ },+ },+ },+ },+ });++ // if view does not exist, we should not allow the download+ if (!view) {+ return res.status(404).json({ error: "Error downloading" });+ }++ // if link does not allow download, we should not allow the download+ if (!view.link.allowDownload) {+ return res.status(403).json({ error: "Error downloading" });+ }++ // if link is archived, we should not allow the download+ if (view.link.isArchived) {+ return res.status(403).json({ error: "Error downloading" });+ }++ // if link is expired, we should not allow the download+ if (view.link.expiresAt && view.link.expiresAt < new Date()) {+ return res.status(403).json({ error: "Error downloading" });+ }++ // if dataroom does not exist, we should not allow the download+ if (!view.dataroom) {+ return res.status(404).json({ error: "Error downloading" });+ }++ // if viewedAt is longer than 30 mins ago, we should not allow the download+ if (+ view.viewedAt &&+ view.viewedAt < new Date(Date.now() - 30 * 60 * 1000)+ ) {+ return res.status(403).json({ error: "Error downloading" });+ }++ let downloadDocuments = view.dataroom.documents;++ // if groupId is not null,+ // we should find the group permissions+ // and reduce the number of documents and folders to download+ if (view.groupId) {+ const groupPermissions =+ await prisma.viewerGroupAccessControls.findMany({+ where: { groupId: view.groupId, canDownload: true },+ });++ const permittedDocumentIds = groupPermissions+ .filter(+ (permission) => permission.itemType === ItemType.DATAROOM_DOCUMENT,+ )+ .map((permission) => permission.itemId);++ downloadDocuments = downloadDocuments.filter((doc) =>+ permittedDocumentIds.includes(doc.id),+ );+ }++ //creates new view for document+ await prisma.view.create({+ data: {+ viewType: "DOCUMENT_VIEW",+ documentId: documentId,+ linkId: linkId,+ dataroomId: view.dataroom.id,+ groupId: view.groupId,+ dataroomViewId: view.id,+ viewerEmail: view.viewerEmail,+ downloadedAt: new Date(),+ viewerId: view.viewerId,+ verified: view.verified,+ },+ });++ const downloadUrl = await getFile({+ type: downloadDocuments[0].document!.versions[0].storageType,+ data:+ downloadDocuments[0].document!.versions[0].originalFile ??+ downloadDocuments[0].document!.versions[0].file,+ isDownload: true,+ });++ if (+ downloadDocuments[0].document!.versions[0].type === "pdf" &&+ view.link.enableWatermark+ ) {+ const response = await fetch(+ `${process.env.NEXTAUTH_URL}/api/mupdf/annotate-document`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ url: downloadUrl,+ numPages: downloadDocuments[0].document!.versions[0].numPages,+ watermarkConfig: view.link.watermarkConfig,+ viewerData: {+ email: view.viewerEmail,+ date: new Date(view.viewedAt).toLocaleDateString(),+ ipAddress: getIpAddress(req.headers),+ link: view.link.name,+ time: new Date(view.viewedAt).toLocaleTimeString(),+ },+ }),+ },+ );++ if (!response.ok) {+ return res.status(500).json({ error: "Error downloading" });+ }++ const pdfBuffer = await response.arrayBuffer();++ // Set appropriate headers+ res.setHeader("Content-Type", "application/pdf");+ res.setHeader(+ "Content-Disposition",+ 'attachment; filename="watermarked.pdf"',+ );++ // Send the buffer directly+ return res.send(Buffer.from(pdfBuffer));+ }++ return res.status(200).json({ downloadUrl });+ // Add documents in folders+ } catch {}+ } else {+ // We only allow POST requests+ res.setHeader("Allow", ["POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}