Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
Feat: enable excel advanced mode on teams by default
Ashish Viradiya4f41efb1c8ab
diff --git a/app/api/links/[id]/upload/route.ts b/app/api/links/[id]/upload/route.tsindex 6f93e60a..a31a0338 100644--- a/app/api/links/[id]/upload/route.ts+++ b/app/api/links/[id]/upload/route.ts@@ -51,6 +51,7 @@ export async function POST(team: {select: {plan: true,+ enableExcelAdvancedMode: true,},},},@@ -87,9 +88,15 @@ export async function POST();}++ const updatedDocumentData = {+ ...documentData,+ enableExcelAdvancedMode: link.team?.enableExcelAdvancedMode ?? false,+ };+// 1. Create the documentconst document = await processDocument({- documentData,+ documentData: updatedDocumentData,teamId: link.teamId,teamPlan: link.team?.plan ?? "free",isExternalUpload: true,diff --git a/components/documents/document-header.tsx b/components/documents/document-header.tsxindex e6da0d65..ec95b027 100644--- a/components/documents/document-header.tsx+++ b/components/documents/document-header.tsx@@ -286,26 +286,30 @@ 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 {+ toast.promise(+ fetch(`/api/teams/${teamId}/documents/${document.id}/advanced-mode`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ }).then(async (response) => {+ if (!response.ok) {+ const { message } = await response.json();+ throw new Error(message);+ }const { message } = await response.json();plausible("advancedExcelEnabled", {props: { documentId: document.id },}); // track the event+ mutate(`/api/teams/${teamId}/documents/${document.id}`);handleCloseAlert("enable-advanced-excel-alert");- toast.success(message);- }- } catch (error) {- console.error("Error:", error);- toast.error("An error occurred. Please try again.");- }+ return message;+ }),+ {+ loading: "Enabling advanced Excel mode...",+ success: (message) => message,+ error: (error) =>+ error.message || "Failed to enable advanced Excel mode",+ },+ );};// export method to fetch the visits data and convert to csv.diff --git a/components/ui/form.tsx b/components/ui/form.tsxindex a4e4a84b..09b9d46f 100644--- a/components/ui/form.tsx+++ b/components/ui/form.tsx@@ -21,6 +21,8 @@ import {CardTitle,} from "./card";import { Input } from "./input";+import { Label } from "./label";+import { Switch } from "./switch";export function Form({title,@@ -51,8 +53,57 @@ export function Form({}, [defaultValue]);const saveDisabled = useMemo(() => {- return saving || !value || value === defaultValue;- }, [saving, value, defaultValue]);+ if (saving) return true;+ if (inputAttrs.type === "checkbox") {+ const currentValue = value === "true";+ const defaultVal = defaultValue === "true";+ return currentValue === defaultVal;+ }+ return !value || value === defaultValue;+ }, [saving, value, defaultValue, inputAttrs.type]);++ const renderInput = () => {+ if (inputAttrs.type === "checkbox") {+ return (+ <div className="flex items-center space-x-2">+ <Switch+ checked={value === "true"}+ onCheckedChange={(checked) => setValue(String(checked))}+ disabled={!!disabledTooltip}+ id={inputAttrs.name}+ />+ <Label+ htmlFor={inputAttrs.name}+ className="text-sm text-muted-foreground"+ >+ {inputAttrs.placeholder}+ </Label>+ </div>+ );+ }++ return (+ <Input+ {...inputAttrs}+ value={value}+ type={inputAttrs.type || "text"}+ required+ disabled={!!disabledTooltip}+ onChange={(e) => setValue(e.target.value)}+ onBlur={(e) => setValue(e.target.value.trim())}+ onKeyDown={(e) =>+ inputAttrs.type === "email" && e.key === " " && e.preventDefault()+ }+ className={cn(+ "w-full max-w-md focus:border-gray-500 focus:outline-none focus:ring-gray-500",+ {+ "cursor-not-allowed bg-gray-100 text-gray-400": disabledTooltip,+ },+ )}+ data-1p-ignore+ />+ );+ };return (<form@@ -77,28 +128,7 @@ export function Form({</CardHeader><CardContent>{typeof defaultValue === "string" ? (- <Input- {...inputAttrs}- value={value}- type={inputAttrs.type || "text"}- required- disabled={!!disabledTooltip}- onChange={(e) => setValue(e.target.value)}- onBlur={(e) => setValue(e.target.value.trim())}- onKeyDown={(e) =>- inputAttrs.type === "email" &&- e.key === " " &&- e.preventDefault()- }- className={cn(- "w-full max-w-md focus:border-gray-500 focus:outline-none focus:ring-gray-500",- {- "cursor-not-allowed bg-gray-100 text-gray-400":- disabledTooltip,- },- )}- data-1p-ignore- />+ renderInput()) : (<div className="h-[2.35rem] w-full max-w-md animate-pulse rounded-md bg-gray-200" />)}diff --git a/lib/api/documents/process-document.ts b/lib/api/documents/process-document.tsindex 2fa5ce09..fd4f139b 100644--- a/lib/api/documents/process-document.ts+++ b/lib/api/documents/process-document.ts@@ -11,6 +11,7 @@ import { getExtension } from "@/lib/utils";import { conversionQueue } from "@/lib/utils/trigger-utils";import { sendDocumentCreatedWebhook } from "@/lib/webhook/triggers/document-created";import { sendLinkCreatedWebhook } from "@/lib/webhook/triggers/link-created";+import { copyFileToBucketServer } from "@/lib/files/copy-file-to-bucket-server";type ProcessDocumentParams = {documentData: DocumentData;@@ -39,6 +40,7 @@ export const processDocument = async ({supportedFileType,fileSize,numPages,+ enableExcelAdvancedMode,} = documentData;// Get passed type property or alternatively, the file extension and save it as the type@@ -85,6 +87,7 @@ export const processDocument = async ({storageType,ownerId: userId,teamId: teamId,+ advancedExcelEnabled: enableExcelAdvancedMode,downloadOnly: isDownloadOnly,...(createLink && {links: {@@ -199,6 +202,28 @@ export const processDocument = async ({);}+ if (type === "sheet" && enableExcelAdvancedMode) {+ await copyFileToBucketServer({+ filePath: document.versions[0].file,+ storageType: document.versions[0].storageType,+ });++ await Promise.all([+ prisma.document.update({+ where: { id: document.id },+ data: { advancedExcelEnabled: true },+ }),+ prisma.documentVersion.update({+ where: { id: document.versions[0].id },+ data: { numPages: 1 },+ }),+ ]);++ await fetch(+ `${process.env.NEXTAUTH_URL}/api/revalidate?secret=${process.env.REVALIDATE_TOKEN}&documentId=${document.id}`,+ );+ }+// Send webhooksawait Promise.all([!isExternalUpload &&diff --git a/lib/documents/create-document.ts b/lib/documents/create-document.tsindex 845c604d..171e7ad0 100644--- a/lib/documents/create-document.ts+++ b/lib/documents/create-document.ts@@ -8,6 +8,7 @@ export type DocumentData = {supportedFileType: string; // papermark types: "pdf", "sheet", "docs", "slides", "map", "zip"fileSize: number | undefined; // file size in bytesnumPages?: number;+ enableExcelAdvancedMode?: boolean;};export const createDocument = async ({diff --git a/lib/types.ts b/lib/types.tsindex a4a3753a..02a0b317 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -298,6 +298,7 @@ export interface Team {logo?: React.ElementType;plan?: string;createdAt?: Date;+ enableExcelAdvancedMode?: boolean;}export interface TeamDetail {diff --git a/pages/api/teams/[teamId]/documents/index.ts b/pages/api/teams/[teamId]/documents/index.tsindex 9d5a8067..231e687a 100644--- a/pages/api/teams/[teamId]/documents/index.ts+++ b/pages/api/teams/[teamId]/documents/index.ts@@ -278,6 +278,8 @@ export default async function handle(supportedFileType: fileType,contentType,fileSize,+ enableExcelAdvancedMode:+ fileType === "sheet" && team.enableExcelAdvancedMode,},teamId,userId,diff --git a/pages/api/teams/[teamId]/enable-advanced-mode.ts b/pages/api/teams/[teamId]/enable-advanced-mode.tsnew file mode 100644index 00000000..0c251e56--- /dev/null+++ b/pages/api/teams/[teamId]/enable-advanced-mode.ts@@ -0,0 +1,128 @@+import { NextApiRequest, NextApiResponse } from "next";+import { getServerSession } from "next-auth/next";+import prisma from "@/lib/prisma";+import { Session } from "next-auth";+import { copyFileToBucketServer } from "@/lib/files/copy-file-to-bucket-server";++import { authOptions } from "../../auth/[...nextauth]";+import { errorhandler } from "@/lib/errorHandler";++interface CustomSession extends Session {+ user: {+ id: string;+ name?: string | null;+ email?: string | null;+ image?: string | null;+ };+}++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse+) {+ if (req.method !== "PATCH") {+ return res.status(405).json({ error: "Method not allowed" });+ }++ try {+ const session = await getServerSession(req, res, authOptions) as CustomSession | null;+ if (!session?.user?.id) {+ return res.status(401).json({ error: "Unauthorized" });+ }++ const { teamId } = req.query;+ const { enableExcelAdvancedMode } = req.body as { enableExcelAdvancedMode: boolean };++ const team = await prisma.team.findFirst({+ where: {+ id: teamId as string,+ users: {+ some: {+ userId: session.user.id,+ },+ },+ },+ });++ if (!team) {+ return res.status(401).json({ error: "Unauthorized" });+ }++ // Start a transaction to ensure all updates succeed or none do+ const result = await prisma.$transaction(async (tx) => {+ // Get all Excel documents in the team that need to be updated+ const documents = await tx.document.findMany({+ where: {+ teamId: teamId as string,+ type: "sheet",+ advancedExcelEnabled: !enableExcelAdvancedMode,+ },+ include: {+ versions: {+ where: {+ isPrimary: true,+ type: "sheet",+ },+ },+ },+ });++ // Update all documents and their versions+ const updatePromises = documents.map(async (doc) => {+ const primaryVersion = doc.versions[0];+ if (!primaryVersion) return;++ if (enableExcelAdvancedMode) {+ // Copy file to bucket if enabling advanced mode+ await copyFileToBucketServer({+ filePath: primaryVersion.file,+ storageType: primaryVersion.storageType,+ });++ // Update document and version when enabling+ await Promise.all([+ tx.document.update({+ where: { id: doc.id },+ data: { advancedExcelEnabled: true },+ }),+ tx.documentVersion.update({+ where: { id: primaryVersion.id },+ data: { numPages: 1 },+ }),+ ]);+ } else {+ await tx.document.update({+ where: { id: doc.id },+ data: { advancedExcelEnabled: false },+ });+ }++ // Revalidate the document+ await fetch(+ `${process.env.NEXTAUTH_URL}/api/revalidate?secret=${process.env.REVALIDATE_TOKEN}&documentId=${doc.id}`,+ );+ });++ await Promise.all(updatePromises);+ const updatedTeam = await tx.team.update({+ where: {+ id: teamId as string,+ },+ data: {+ enableExcelAdvancedMode,+ },+ });+ return {+ team: updatedTeam,+ updatedDocumentsCount: documents.length,+ };+ });+ console.log('result', result);+ return res.status(200).json({+ ...result,+ message: `Successfully ${enableExcelAdvancedMode ? 'enabled' : 'disabled'} advanced Excel mode for ${result.updatedDocumentsCount} documents`,+ });+ } catch (error) {+ errorhandler(error, res);+ }+}\ No newline at end of filediff --git a/pages/api/teams/[teamId]/update-limits.ts b/pages/api/teams/[teamId]/update-limits.tsnew file mode 100644index 00000000..afeaf542--- /dev/null+++ b/pages/api/teams/[teamId]/update-limits.ts@@ -0,0 +1,63 @@+import { NextApiRequest, NextApiResponse } from "next";+import { getServerSession } from "next-auth/next";+import prisma from "@/lib/prisma";+import { Session } from "next-auth";++import { authOptions } from "../../auth/[...nextauth]";+import { errorhandler } from "@/lib/errorHandler";++interface CustomSession extends Session {+ user: {+ id: string;+ name?: string | null;+ };+}++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse+) {+ if (req.method !== "PATCH") {+ return res.status(405).json({ error: "Method not allowed" });+ }++ try {+ const session = await getServerSession(req, res, authOptions) as CustomSession | null;+ if (!session?.user?.id) {+ return res.status(401).json({ error: "Unauthorized" });+ }++ const { teamId } = req.query;+ const { enableExcelAdvancedMode } = req.body;++ // Verify user is part of the team+ const team = await prisma.team.findFirst({+ where: {+ id: teamId as string,+ users: {+ some: {+ userId: session.user.id,+ },+ },+ },+ });++ if (!team) {+ return res.status(401).json({ error: "Unauthorized" });+ }++ // Update team limits+ const updatedTeam = await prisma.team.update({+ where: {+ id: teamId as string,+ },+ data: {+ enableExcelAdvancedMode,+ },+ });++ return res.status(200).json(updatedTeam);+ } catch (error) {+ errorhandler(error, res);+ }+}\ No newline at end of filediff --git a/pages/api/teams/index.ts b/pages/api/teams/index.tsindex 5ed2b96d..8c1d2da3 100644--- a/pages/api/teams/index.ts+++ b/pages/api/teams/index.ts@@ -34,6 +34,7 @@ export default async function handle(name: true,plan: true,createdAt: true,+ enableExcelAdvancedMode: true,},},},@@ -66,6 +67,7 @@ export default async function handle(name: true,plan: true,createdAt: true,+ enableExcelAdvancedMode: true,},});teams.push(defaultTeam);diff --git a/pages/settings/general.tsx b/pages/settings/general.tsxindex 1c57e36e..d6449824 100644--- a/pages/settings/general.tsx+++ b/pages/settings/general.tsx@@ -1,7 +1,13 @@+import { useState } from "react";+import { useTeam } from "@/context/team-context";+import { PlanEnum } from "@/ee/stripe/constants";import { toast } from "sonner";import { mutate } from "swr";+import { usePlan } from "@/lib/swr/use-billing";++import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";import AppLayout from "@/components/layouts/app";import DeleteTeam from "@/components/settings/delete-team";import { SettingsHeader } from "@/components/settings/settings-header";@@ -9,6 +15,88 @@ import { Form } from "@/components/ui/form";export default function General() {const teamInfo = useTeam();+ const { plan } = usePlan();+ const [selectedPlan, setSelectedPlan] = useState<PlanEnum>(PlanEnum.Pro);+ const [planModalTrigger, setPlanModalTrigger] = useState<string>("");+ const [planModalOpen, setPlanModalOpen] = useState<boolean>(false);++ const showUpgradeModal = (plan: PlanEnum, trigger: string) => {+ setSelectedPlan(plan);+ setPlanModalTrigger(trigger);+ setPlanModalOpen(true);+ };++ const handleExcelAdvancedModeChange = async (data: {+ enableExcelAdvancedMode: string;+ }) => {+ if (plan === "free" && data.enableExcelAdvancedMode === "true") {+ showUpgradeModal(PlanEnum.Business, "advanced-excel-mode");+ return;+ }++ const promise = fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/enable-advanced-mode`,+ {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ enableExcelAdvancedMode: data.enableExcelAdvancedMode === "true",+ }),+ },+ ).then(async (res) => {+ if (!res.ok) {+ const { error } = await res.json();+ throw new Error(error.message);+ }+ await Promise.all([+ mutate(`/api/teams/${teamInfo?.currentTeam?.id}`),+ mutate(`/api/teams`),+ ]);+ return res.json();+ });++ toast.promise(promise, {+ loading: "Updating Excel advanced mode setting...",+ success: "Successfully updated Excel advanced mode setting!",+ error: (err) =>+ err.message || "Failed to update Excel advanced mode setting",+ });++ return promise;+ };++ const handleTeamNameChange = async (updateData: any) => {+ const promise = fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/update-name`,+ {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(updateData),+ },+ ).then(async (res) => {+ if (!res.ok) {+ const { error } = await res.json();+ throw new Error(error.message);+ }+ await Promise.all([+ mutate(`/api/teams/${teamInfo?.currentTeam?.id}`),+ mutate(`/api/teams`),+ ]);+ return res.json();+ });++ toast.promise(promise, {+ loading: "Updating team name...",+ success: "Successfully updated team name!",+ error: (err) => err.message || "Failed to update team name",+ });++ return promise;+ };return (<AppLayout>@@ -34,29 +122,35 @@ export default function General() {}}defaultValue={teamInfo?.currentTeam?.name ?? ""}helpText="Max 32 characters."- handleSubmit={(updateData) =>- fetch(`/api/teams/${teamInfo?.currentTeam?.id}/update-name`, {- method: "PATCH",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(updateData),- }).then(async (res) => {- if (res.status === 200) {- await Promise.all([- mutate(`/api/teams/${teamInfo?.currentTeam?.id}`),- mutate(`/api/teams`),- ]);- toast.success("Successfully updated team name!");- } else {- const { error } = await res.json();- toast.error(error.message);- }- })- }+ handleSubmit={handleTeamNameChange}/>++ <Form+ title="Excel Advanced Mode"+ description="Enable advanced mode for all Excel files in your team. This will use Microsoft Office viewer for better formatting."+ inputAttrs={{+ name: "enableExcelAdvancedMode",+ type: "checkbox",+ placeholder: "Enable advanced mode for Excel files",+ }}+ defaultValue={String(+ teamInfo?.currentTeam?.enableExcelAdvancedMode ?? false,+ )}+ helpText="When enabled, Excel files will be viewed using the Microsoft Office viewer for better formatting and compatibility."+ handleSubmit={handleExcelAdvancedModeChange}+ />+<DeleteTeam /></div>++ {planModalOpen ? (+ <UpgradePlanModal+ clickedPlan={selectedPlan}+ trigger={planModalTrigger}+ open={planModalOpen}+ setOpen={setPlanModalOpen}+ />+ ) : null}</main></AppLayout>);diff --git a/prisma/migrations/20240320000000_add_excel_advanced_mode/migration.sql b/prisma/migrations/20240320000000_add_excel_advanced_mode/migration.sqlnew file mode 100644index 00000000..ae8b3a6a--- /dev/null+++ b/prisma/migrations/20240320000000_add_excel_advanced_mode/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "Team" ADD COLUMN "enableExcelAdvancedMode" BOOLEAN NOT NULL DEFAULT false;\ No newline at end of filediff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prismaindex 31f60b22..0f07dcd9 100644--- a/prisma/schema/schema.prisma+++ b/prisma/schema/schema.prisma@@ -100,6 +100,9 @@ model Team {uploadedDocuments DocumentUpload[]+ // team settings+ enableExcelAdvancedMode Boolean @default(false) // Enable Excel advanced mode for all documents in the team+createdAt DateTime @default(now())updatedAt DateTime @updatedAtTag Tag[]