Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add toggle for advanced excel mode
Marc Seitze3b728dee87f
diff --git a/components/documents/document-header.tsx b/components/documents/document-header.tsxindex f8c0ac3e..95869d96 100644--- a/components/documents/document-header.tsx+++ b/components/documents/document-header.tsx@@ -5,7 +5,12 @@ import { useEffect, useRef, useState } from "react";import { useTeam } from "@/context/team-context";import { Document, DocumentVersion } from "@prisma/client";-import { BetweenHorizontalStartIcon, Sparkles, TrashIcon } from "lucide-react";+import {+ BetweenHorizontalStartIcon,+ SheetIcon,+ Sparkles,+ TrashIcon,+} from "lucide-react";import { usePlausible } from "next-plausible";import { useTheme } from "next-themes";import { toast } from "sonner";@@ -29,6 +34,7 @@ import {import { DocumentWithLinksAndLinkCountAndViewCount } from "@/lib/types";import { cn, getExtension } from "@/lib/utils";+import AdvancedSheet from "../shared/icons/advanced-sheet";import PortraitLandscape from "../shared/icons/portrait-landscape";import LoadingSpinner from "../ui/loading-spinner";import { ButtonTooltip } from "../ui/tooltip";@@ -222,6 +228,25 @@ export default function DocumentHeader({}};+ const enableAdvancedExcel = async (document: Document) => {+ try {+ const response = await fetch(+ `/api/teams/${teamId}/documents/${document.id}/advanced-mode`,+ { method: "POST", headers: { "Content-Type": "application/json" } },+ );+ if (!response.ok) {+ const { message } = await response.json();+ toast.error(message);+ } else {+ const { message } = await response.json();+ toast.success(message);+ }+ } catch (error) {+ console.error("Error:", error);+ toast.error("An error occurred. Please try again.");+ }+ };+useEffect(() => {function handleClickOutside(event: { target: any }) {if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {@@ -329,6 +354,15 @@ export default function DocumentHeader({</span>)}</div>++ {prismaDocument.type === "sheet" &&+ prismaDocument.advancedExcelEnabled && (+ <ButtonTooltip content="Advanced Excel mode">+ <span className="mt-1 text-xs">+ <AdvancedSheet className="h-6 w-6" />+ </span>+ </ButtonTooltip>+ )}</div><div className="flex items-center gap-x-4 md:gap-x-2 lg:gap-x-4">@@ -362,6 +396,7 @@ export default function DocumentHeader({)}{prismaDocument.type !== "notion" &&+ prismaDocument.type !== "sheet" &&prismaDocument.assistantEnabled && (<ButtonclassName="group hidden h-8 space-x-1 whitespace-nowrap bg-gradient-to-r from-[#16222A] via-emerald-500 to-[#16222A] text-xs duration-200 ease-linear hover:bg-right md:flex lg:h-9 lg:text-sm"@@ -400,7 +435,7 @@ export default function DocumentHeader({</DropdownMenuTrigger><DropdownMenuContentalign="end"- className="w-[180px]"+ className="w-[240px]"ref={dropdownRef}><DropdownMenuLabel>Actions</DropdownMenuLabel>@@ -433,19 +468,21 @@ export default function DocumentHeader({{" Change orientation"}</DropdownMenuItem>- {prismaDocument.type !== "notion" && (- <DropdownMenuItem- onClick={() => activateOrRedirectAssistant(prismaDocument)}- >- <PapermarkSparkle className="mr-2 h-4 w-4" />- Open AI Assistant- </DropdownMenuItem>- )}+ {prismaDocument.type !== "notion" &&+ prismaDocument.type !== "sheet" && (+ <DropdownMenuItem+ onClick={() => activateOrRedirectAssistant(prismaDocument)}+ >+ <PapermarkSparkle className="mr-2 h-4 w-4" />+ Open AI Assistant+ </DropdownMenuItem>+ )}<DropdownMenuSeparator /></DropdownMenuGroup>{primaryVersion.type !== "notion" &&+ primaryVersion.type !== "sheet" &&(!prismaDocument.assistantEnabled ? (<DropdownMenuItemonClick={() =>@@ -464,6 +501,16 @@ export default function DocumentHeader({</DropdownMenuItem>))}+ {prismaDocument.type === "sheet" &&+ !prismaDocument.advancedExcelEnabled && (+ <DropdownMenuItem+ onClick={() => enableAdvancedExcel(prismaDocument)}+ >+ <SheetIcon className="mr-2 h-4 w-4" />+ Enable Advanced Mode+ </DropdownMenuItem>+ )}+<DropdownMenuItem onClick={() => setAddDataroomOpen(true)}><BetweenHorizontalStartIcon className="mr-2 h-4 w-4" />Add to dataroomdiff --git a/components/shared/icons/advanced-sheet.tsx b/components/shared/icons/advanced-sheet.tsxnew file mode 100644index 00000000..62343121--- /dev/null+++ b/components/shared/icons/advanced-sheet.tsx@@ -0,0 +1,23 @@+export default function AdvancedSheet({ className }: { className?: string }) {+ return (+ <svg+ width="52"+ height="52"+ viewBox="0 0 52 52"+ fill="none"+ stroke="currentColor"+ strokeWidth="3"+ strokeLinecap="round"+ strokeLinejoin="round"+ className={className}+ xmlns="http://www.w3.org/2000/svg"+ >+ <path d="M45.5 30V10.8333C45.5 8.4401 43.5599 6.5 41.1667 6.5H10.8333C8.4401 6.5 6.5 8.4401 6.5 10.8333V41.1667C6.5 43.5599 8.4401 45.5 10.8333 45.5H32.3187" />+ <path d="M6.5 19.5H45.5" />+ <path d="M6.5 32.5H32.5" />+ <path d="M19.5 19.5V45.5" />+ <path d="M32.5 19.5V32.5" />+ <path d="M31.0034 40.0026C30.8142 40.0032 30.6286 39.9502 30.4684 39.8496C30.3081 39.749 30.1796 39.605 30.098 39.4343C30.0163 39.2636 29.9847 39.0732 30.0069 38.8853C30.0291 38.6973 30.1042 38.5196 30.2234 38.3726L40.1234 28.1726C40.1977 28.0869 40.2989 28.029 40.4104 28.0083C40.5219 27.9877 40.6371 28.0056 40.7371 28.0591C40.8371 28.1126 40.916 28.1985 40.9607 28.3027C41.0055 28.4069 41.0135 28.5233 40.9834 28.6326L39.0634 34.6526C39.0068 34.8041 38.9878 34.9671 39.008 35.1276C39.0282 35.2881 39.0871 35.4413 39.1795 35.574C39.2719 35.7068 39.3952 35.8151 39.5387 35.8898C39.6822 35.9644 39.8417 36.0031 40.0034 36.0026H47.0034C47.1926 36.002 47.3782 36.055 47.5385 36.1556C47.6987 36.2562 47.8272 36.4002 47.9089 36.5709C47.9905 36.7416 48.0221 36.932 47.9999 37.1199C47.9777 37.3079 47.9026 37.4856 47.7834 37.6326L37.8834 47.8326C37.8091 47.9183 37.708 47.9762 37.5964 47.9969C37.4849 48.0175 37.3697 47.9996 37.2697 47.9461C37.1697 47.8926 37.0908 47.8067 37.0461 47.7025C37.0013 47.5983 36.9933 47.482 37.0234 47.3726L38.9434 41.3526C39 41.2011 39.019 41.0381 38.9988 40.8776C38.9786 40.7171 38.9198 40.5639 38.8273 40.4312C38.7349 40.2984 38.6116 40.1901 38.4681 40.1154C38.3246 40.0408 38.1652 40.0021 38.0034 40.0026H31.0034Z" />+ </svg>+ );+}diff --git a/components/view/dataroom/dataroom-view.tsx b/components/view/dataroom/dataroom-view.tsxindex 85b7dcd8..beaf377c 100644--- a/components/view/dataroom/dataroom-view.tsx+++ b/components/view/dataroom/dataroom-view.tsx@@ -63,6 +63,7 @@ export type DEFAULT_DOCUMENT_VIEW_TYPE = {notionData?: { recordMap: ExtendedRecordMap | null };fileType?: string;ipAddress?: string;+ useAdvancedExcelViewer?: boolean;};export default function DataroomView({@@ -162,6 +163,7 @@ export default function DataroomView({fileType,isPreview,ipAddress,+ useAdvancedExcelViewer,} = fetchData as DEFAULT_DOCUMENT_VIEW_TYPE;plausible("dataroomViewed"); // track the eventanalytics.identify(@@ -186,6 +188,7 @@ export default function DataroomView({fileType,isPreview,ipAddress,+ useAdvancedExcelViewer,}));setSubmitted(true);setVerificationRequested(false);@@ -321,7 +324,7 @@ export default function DataroomView({allowDownload={link.allowDownload!}/></div>- ) : viewData.fileType === "sheet" && useAdvancedExcelViewer ? (+ ) : viewData.fileType === "sheet" && viewData.useAdvancedExcelViewer ? (<div className="bg-gray-950"><AdvancedExcelViewerlinkId={link.id}diff --git a/lib/api/links/link-data.ts b/lib/api/links/link-data.tsindex 402d8fa9..af3a8392 100644--- a/lib/api/links/link-data.ts+++ b/lib/api/links/link-data.ts@@ -54,6 +54,7 @@ export async function fetchDataroomLinkData({select: {id: true,name: true,+ advancedExcelEnabled: true,versions: {where: { isPrimary: true },select: {@@ -120,6 +121,7 @@ export async function fetchDocumentLinkData({ linkId }: { linkId: string }) {id: true,name: true,assistantEnabled: true,+ advancedExcelEnabled: true,teamId: true,ownerId: true,team: {diff --git a/lib/files/copy-file-to-bucket-server.ts b/lib/files/copy-file-to-bucket-server.tsnew file mode 100644index 00000000..08068e91--- /dev/null+++ b/lib/files/copy-file-to-bucket-server.ts@@ -0,0 +1,55 @@+import { CopyObjectCommand, ListObjectsV2Command } from "@aws-sdk/client-s3";+import { DocumentStorageType } from "@prisma/client";+import { match } from "ts-pattern";++import { getS3Client } from "./aws-client";++export const copyFileToBucketServer = async ({+ filePath,+ storageType,+}: {+ filePath: string;+ storageType: DocumentStorageType;+}) => {+ const { type, data } = await match(storageType)+ .with("S3_PATH", async () => copyFileToBucketInS3Server({ filePath }))+ .otherwise(() => {+ return {+ type: null,+ data: null,+ };+ });++ return { type, data };+};++const copyFileToBucketInS3Server = async ({+ filePath,+}: {+ filePath: string;+}) => {+ const client = getS3Client();+ const fromBucket = process.env.NEXT_PRIVATE_UPLOAD_BUCKET as string;+ const toBucket = process.env.NEXT_PRIVATE_ADVANCED_UPLOAD_BUCKET as string;++ try {+ const copyCommand = new CopyObjectCommand({+ CopySource: `${fromBucket}/${filePath}`,+ Bucket: toBucket,+ Key: filePath,+ });++ await client.send(copyCommand);++ return {+ type: DocumentStorageType.S3_PATH,+ data: filePath,+ };+ } catch (error) {+ console.error(error);+ return {+ type: null,+ data: null,+ };+ }+};diff --git a/next.config.mjs b/next.config.mjsindex 3db77dca..669540ec 100644--- a/next.config.mjs+++ b/next.config.mjs@@ -58,6 +58,13 @@ function prepareRemotePatterns() {});}+ if (process.env.NEXT_PRIVATE_ADVANCED_UPLOAD_DISTRIBUTION_HOST) {+ patterns.push({+ protocol: "https",+ hostname: process.env.NEXT_PRIVATE_ADVANCED_UPLOAD_DISTRIBUTION_HOST,+ });+ }+if (process.env.VERCEL_ENV === "production") {patterns.push({// production vercel blobdiff --git a/pages/api/teams/[teamId]/documents/[id]/advanced-mode.ts b/pages/api/teams/[teamId]/documents/[id]/advanced-mode.tsnew file mode 100644index 00000000..9c62d517--- /dev/null+++ b/pages/api/teams/[teamId]/documents/[id]/advanced-mode.ts@@ -0,0 +1,86 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { DocumentStorageType } from "@prisma/client";+import { waitUntil } from "@vercel/functions";+import { getServerSession } from "next-auth/next";+import { version } from "os";++import { errorhandler } from "@/lib/errorHandler";+import { copyFileToBucketServer } from "@/lib/files/copy-file-to-bucket-server";+import prisma from "@/lib/prisma";+import { getTeamWithUsersAndDocument } from "@/lib/team/helper";+import { CustomUser } from "@/lib/types";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "POST") {+ // GET /api/teams/:teamId/documents/:id/advanced-mode+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const { teamId, id: docId } = req.query as { teamId: string; id: string };++ const userId = (session.user as CustomUser).id;++ try {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId,+ },+ },+ },+ select: {+ id: true,+ },+ });++ if (!team) {+ return res.status(401).end("Unauthorized");+ }++ const documentVersion = await prisma.documentVersion.findFirst({+ where: {+ documentId: docId,+ isPrimary: true,+ type: "sheet",+ },+ });++ if (!documentVersion) {+ return res.status(404).end("Document not found");+ }++ await copyFileToBucketServer({+ filePath: documentVersion.file,+ storageType: documentVersion.storageType,+ });++ await prisma.document.update({+ where: { id: docId },+ data: { advancedExcelEnabled: true },+ });++ await fetch(+ `${process.env.NEXTAUTH_URL}/api/revalidate?secret=${process.env.REVALIDATE_TOKEN}&documentId=${docId}`,+ );++ return res.status(200).json({+ message: `Document updated to advanced Excel mode!`,+ });+ } catch (error) {+ errorhandler(error, res);+ }+ } else {+ // We only allow POST requests+ res.setHeader("Allow", ["POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/api/teams/[teamId]/documents/[id]/versions/index.ts b/pages/api/teams/[teamId]/documents/[id]/versions/index.tsindex 9d872059..35309f16 100644--- a/pages/api/teams/[teamId]/documents/[id]/versions/index.ts+++ b/pages/api/teams/[teamId]/documents/[id]/versions/index.ts@@ -5,6 +5,7 @@ import { client } from "@/trigger";import { DocumentStorageType } from "@prisma/client";import { getServerSession } from "next-auth/next";+import { copyFileToBucketServer } from "@/lib/files/copy-file-to-bucket-server";import prisma from "@/lib/prisma";import { getTeamWithUsersAndDocument } from "@/lib/team/helper";import { CustomUser } from "@/lib/types";@@ -15,7 +16,7 @@ export default async function handle(res: NextApiResponse,) {if (req.method === "POST") {- // GET /api/teams/:teamId/documents/:id/versions+ // POST /api/teams/:teamId/documents/:id/versionsconst session = await getServerSession(req, res, authOptions);if (!session) {return res.status(401).end("Unauthorized");@@ -44,6 +45,7 @@ export default async function handle(options: {select: {id: true,+ advancedExcelEnabled: true,versions: {orderBy: { createdAt: "desc" },take: 1,@@ -53,20 +55,6 @@ export default async function handle(},});- // get the latest version number for this document- // const result = await prisma.document.findUnique({- // where: {- // id: documentId,- // },- // select: {- // versions: {- // orderBy: { createdAt: "desc" },- // take: 1,- // select: { versionNumber: true },- // },- // },- // });-// create a new document versionconst currentVersionNumber = document?.versions? document.versions[0].versionNumber@@ -83,18 +71,41 @@ export default async function handle(},});- // trigger document uploaded event to trigger convert-pdf-to-image job- await client.sendEvent({- id: version.id,- name: "document.uploaded",- payload: {- documentVersionId: version.id,- versionNumber: version.versionNumber,+ // turn off isPrimary flag for all other versions+ await prisma.documentVersion.updateMany({+ where: {documentId: documentId,- teamId: teamId,+ id: {+ not: version.id,+ },+ },+ data: {+ isPrimary: false,},});+ // trigger document uploaded event to trigger convert-pdf-to-image job+ if (type === "pdf") {+ await client.sendEvent({+ id: version.id,+ name: "document.uploaded",+ payload: {+ documentVersionId: version.id,+ versionNumber: version.versionNumber,+ documentId: documentId,+ teamId: teamId,+ },+ });+ }++ if (type === "sheet" && document?.advancedExcelEnabled) {+ console.log("copying file to bucket server");+ await copyFileToBucketServer({+ filePath: version.file,+ storageType: version.storageType,+ });+ }+res.status(200).json({ id: documentId });} catch (error) {log({diff --git a/pages/api/views-dataroom.ts b/pages/api/views-dataroom.tsindex 73db0867..98ff6d03 100644--- a/pages/api/views-dataroom.ts+++ b/pages/api/views-dataroom.ts@@ -76,7 +76,7 @@ export default async function handle(};// INFO: for using the advanced excel viewer- const { useAdvancedExcelViewer } = data as {+ let { useAdvancedExcelViewer } = data as {useAdvancedExcelViewer: boolean;};@@ -518,14 +518,26 @@ export default async function handle(recordMap = await notion.getPage(pageId);}- if (documentVersion.type === "sheet" && !useAdvancedExcelViewer) {- const fileUrl = await getFile({- data: documentVersion.file,- type: documentVersion.storageType,+ if (documentVersion.type === "sheet") {+ const document = await prisma.document.findUnique({+ where: { id: documentId },+ select: { advancedExcelEnabled: true },});-- const data = await parseSheet({ fileUrl });- sheetData = data;+ useAdvancedExcelViewer = document?.advancedExcelEnabled ?? false;++ if (useAdvancedExcelViewer) {+ documentVersion.file = documentVersion.file.includes("https://")+ ? documentVersion.file+ : `https://${process.env.NEXT_PRIVATE_ADVANCED_UPLOAD_DISTRIBUTION_HOST}/${documentVersion.file}`;+ } else {+ const fileUrl = await getFile({+ data: documentVersion.file,+ type: documentVersion.storageType,+ });++ const data = await parseSheet({ fileUrl });+ sheetData = data;+ }}console.timeEnd("get-file");}@@ -563,6 +575,12 @@ export default async function handle()? getIpAddress(req.headers): undefined,+ useAdvancedExcelViewer:+ documentVersion &&+ documentVersion.type === "sheet" &&+ useAdvancedExcelViewer+ ? useAdvancedExcelViewer+ : undefined,};return res.status(200).json(returnObject);diff --git a/pages/api/views.ts b/pages/api/views.tsindex f29d15a8..efad9234 100644--- a/pages/api/views.ts+++ b/pages/api/views.ts@@ -364,14 +364,20 @@ export default async function handle(});}- if (documentVersion.type === "sheet" && !useAdvancedExcelViewer) {- const fileUrl = await getFile({- data: documentVersion.file,- type: documentVersion.storageType,- });-- const data = await parseSheet({ fileUrl });- sheetData = data;+ if (documentVersion.type === "sheet") {+ if (useAdvancedExcelViewer) {+ documentVersion.file = documentVersion.file.includes("https://")+ ? documentVersion.file+ : `https://${process.env.NEXT_PRIVATE_ADVANCED_UPLOAD_DISTRIBUTION_HOST}/${documentVersion.file}`;+ } else {+ const fileUrl = await getFile({+ data: documentVersion.file,+ type: documentVersion.storageType,+ });++ const data = await parseSheet({ fileUrl });+ sheetData = data;+ }}console.timeEnd("get-file");}diff --git a/pages/view/[linkId]/index.tsx b/pages/view/[linkId]/index.tsxindex dd261252..17bdfd50 100644--- a/pages/view/[linkId]/index.tsx+++ b/pages/view/[linkId]/index.tsx@@ -65,7 +65,8 @@ export const getStaticProps = async (context: GetStaticPropsContext) => {recordMap = await notion.getPage(pageId);}- const { team, teamId, ...linkDocument } = link.document;+ const { team, teamId, advancedExcelEnabled, ...linkDocument } =+ link.document;const teamPlan = team?.plan || "free";return {@@ -94,9 +95,7 @@ export const getStaticProps = async (context: GetStaticPropsContext) => {},showPoweredByBanner: link.showBanner || teamPlan === "free",showAccountCreationSlide: link.showBanner || teamPlan === "free",- useAdvancedExcelViewer:- teamId === "clwt1qwt00000qz39aqra71w6" ||- teamId === "clup33by90000oewh4rfvp2eg",+ useAdvancedExcelViewer: advancedExcelEnabled,},revalidate: brand ? 10 : false,};@@ -146,9 +145,7 @@ export const getStaticProps = async (context: GetStaticPropsContext) => {},showPoweredByBanner: false,showAccountCreationSlide: false,- useAdvancedExcelViewer:- teamId === "clwt1qwt00000qz39aqra71w6" ||- teamId === "clup33by90000oewh4rfvp2eg",+ useAdvancedExcelViewer: false, // INFO: this is managed in the API route},revalidate: 10,};diff --git a/pages/view/domains/[domain]/[slug]/index.tsx b/pages/view/domains/[domain]/[slug]/index.tsxindex 2b8857e1..7ac79978 100644--- a/pages/view/domains/[domain]/[slug]/index.tsx+++ b/pages/view/domains/[domain]/[slug]/index.tsx@@ -70,7 +70,8 @@ export const getStaticProps = async (context: GetStaticPropsContext) => {recordMap = await notion.getPage(pageId);}- const { team, teamId, ...linkDocument } = link.document;+ const { team, teamId, advancedExcelEnabled, ...linkDocument } =+ link.document;const teamPlan = team?.plan || "free";return {@@ -98,9 +99,7 @@ export const getStaticProps = async (context: GetStaticPropsContext) => {metaUrl: `https://${domain}/${slug}` || null,},showAccountCreationSlide: link.showBanner || teamPlan === "free",- useAdvancedExcelViewer:- teamId === "clwt1qwt00000qz39aqra71w6" ||- teamId === "clup33by90000oewh4rfvp2eg",+ useAdvancedExcelViewer: advancedExcelEnabled,},revalidate: 10,};@@ -150,9 +149,7 @@ export const getStaticProps = async (context: GetStaticPropsContext) => {},showPoweredByBanner: false,showAccountCreationSlide: false,- useAdvancedExcelViewer:- teamId === "clwt1qwt00000qz39aqra71w6" ||- teamId === "clup33by90000oewh4rfvp2eg",+ useAdvancedExcelViewer: false, // INFO: this is managed in the API route},revalidate: 10,};diff --git a/prisma/migrations/20240915000000_add_advanced_mode/migration.sql b/prisma/migrations/20240915000000_add_advanced_mode/migration.sqlnew file mode 100644index 00000000..2c466a2b--- /dev/null+++ b/prisma/migrations/20240915000000_add_advanced_mode/migration.sql@@ -0,0 +1,3 @@+-- AlterTable+ALTER TABLE "Document" ADD COLUMN "advancedExcelEnabled" BOOLEAN NOT NULL DEFAULT false;+diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex a86b5e94..a0c08b71 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -137,6 +137,7 @@ model Document {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+ advancedExcelEnabled Boolean @default(false) // This indicates if advanced Excel is enabled for this documentcreatedAt DateTime @default(now())updatedAt DateTime @updatedAtlinks Link[]