Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add advanced mode to team
Marc Seitz344e7e6e2aaf
diff --git a/components/ui/form.tsx b/components/ui/form.tsxindex 09b9d46f..bf2df534 100644--- a/components/ui/form.tsx+++ b/components/ui/form.tsx@@ -11,6 +11,7 @@ import { toast } from "sonner";import { cn } from "@/lib/utils";import { validateEmail } from "@/lib/utils/validate-email";+import PlanBadge from "../billing/plan-badge";import { Button } from "./button";import {Card,@@ -34,6 +35,7 @@ export function Form({handleSubmit,validate,defaultValue,+ plan,}: {title: string;description: string;@@ -44,6 +46,7 @@ export function Form({handleSubmit: (data: any) => Promise<any>;validate?: (data: string) => boolean;defaultValue?: string;+ plan?: string;}) {const [saving, setSaving] = useState(false);const [value, setValue] = useState(defaultValue);@@ -123,7 +126,9 @@ export function Form({><Card className="bg-transparent"><CardHeader>- <CardTitle>{title}</CardTitle>+ <CardTitle className="flex items-center gap-2">+ {title} {plan && <PlanBadge plan={plan} />}+ </CardTitle><CardDescription>{description}</CardDescription></CardHeader><CardContent>diff --git a/context/team-context.tsx b/context/team-context.tsxindex e90bb5c9..39eff17f 100644--- a/context/team-context.tsx+++ b/context/team-context.tsx@@ -16,6 +16,7 @@ interface TeamContextProps {export type TeamContextType = {teams: Team[];currentTeam: Team | null;+ currentTeamId: string | null;isLoading: boolean;setCurrentTeam: (team: Team) => void;};@@ -23,6 +24,7 @@ export type TeamContextType = {export const initialState = {teams: [],currentTeam: null,+ currentTeamId: null,isLoading: false,setCurrentTeam: (team: Team) => {},};@@ -49,6 +51,7 @@ export const TeamProvider = ({ children }: TeamContextProps): JSX.Element => {currentTeam:(teams || []).find((team) => team.id === currentTeamId) ||(teams || [])[0],+ currentTeamId,isLoading: loading,setCurrentTeam,}),diff --git a/lib/api/documents/process-document.ts b/lib/api/documents/process-document.tsindex fd4f139b..7cb25dbb 100644--- a/lib/api/documents/process-document.ts+++ b/lib/api/documents/process-document.ts@@ -1,6 +1,7 @@import { parsePageId } from "notion-utils";import { DocumentData } from "@/lib/documents/create-document";+import { copyFileToBucketServer } from "@/lib/files/copy-file-to-bucket-server";import notion from "@/lib/notion";import prisma from "@/lib/prisma";import { convertCadToPdfTask } from "@/lib/trigger/convert-files";@@ -11,7 +12,6 @@ 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;@@ -208,20 +208,19 @@ export const processDocument = async ({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 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}`,- );+ try {+ await fetch(+ `${process.env.NEXTAUTH_URL}/api/revalidate?secret=${process.env.REVALIDATE_TOKEN}&documentId=${document.id}`,+ );+ } catch (error) {+ console.error("Failed to revalidate document:", error);+ // The document is still updated, so we can continue without throwing+ }}// Send webhooksdiff --git a/pages/api/teams/[teamId]/enable-advanced-mode.ts b/pages/api/teams/[teamId]/enable-advanced-mode.tsindex 0c251e56..468ca1c6 100644--- a/pages/api/teams/[teamId]/enable-advanced-mode.ts+++ b/pages/api/teams/[teamId]/enable-advanced-mode.ts@@ -1,128 +1,135 @@import { NextApiRequest, NextApiResponse } from "next";-import { getServerSession } from "next-auth/next";-import prisma from "@/lib/prisma";+import { Session } from "next-auth";+import { getServerSession } from "next-auth/next";++import { errorhandler } from "@/lib/errorHandler";import { copyFileToBucketServer } from "@/lib/files/copy-file-to-bucket-server";+import prisma from "@/lib/prisma";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;- };+ user: {+ id: string;+ name?: string | null;+ email?: string | null;+ image?: string | null;+ };}export default async function handle(- req: NextApiRequest,- res: NextApiResponse+ req: NextApiRequest,+ res: NextApiResponse,) {- if (req.method !== "PATCH") {- return res.status(405).json({ error: "Method not allowed" });+ 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" });}- 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 { 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,+ },+ },+ },+ });- const team = await prisma.team.findFirst({+ 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: {- id: teamId as string,- users: {- some: {- userId: session.user.id,- },- },+ isPrimary: true,+ type: "sheet",},- });-- 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;+ // 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,- });+ 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 },- });- }+ // 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}`,- );- });+ // 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 file+ await Promise.all(updatePromises);+ const updatedTeam = await tx.team.update({+ where: {+ id: teamId as string,+ },+ data: {+ enableExcelAdvancedMode,+ },+ });+ return {+ team: updatedTeam,+ updatedDocumentsCount: documents.length,+ };+ });+ return res.status(200).json({+ ...result,+ message: `Successfully ${enableExcelAdvancedMode ? "enabled" : "disabled"} advanced Excel mode for ${result.updatedDocumentsCount} documents`,+ });+ } catch (error) {+ errorhandler(error, res);+ }+}diff --git a/pages/api/teams/[teamId]/update-advanced-mode.ts b/pages/api/teams/[teamId]/update-advanced-mode.tsnew file mode 100644index 00000000..cf6fa436--- /dev/null+++ b/pages/api/teams/[teamId]/update-advanced-mode.ts@@ -0,0 +1,68 @@+import { NextApiRequest, NextApiResponse } from "next";++import { Session } from "next-auth";+import { getServerSession } from "next-auth/next";++import { errorhandler } from "@/lib/errorHandler";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";++import { authOptions } from "../../auth/[...nextauth]";++interface CustomSession extends Session {+ user: {+ id: string;+ name?: string | null;+ };+}++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "PATCH") {+ // PATCH /api/teams/:teamId/update-advanced-mode+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const { teamId } = req.query as { teamId: string };+ const { enableExcelAdvancedMode } = req.body;++ try {+ // Verify user is part of the team+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId: (session.user as CustomUser).id,+ },+ },+ },+ });+ if (!team || team.plan.includes("free")) {+ return res.status(401).json({ error: "Unauthorized" });+ }++ // Update team limits+ await prisma.team.update({+ where: {+ id: teamId,+ },+ data: {+ enableExcelAdvancedMode,+ },+ });++ return res.status(200).json("Excel mode updated!");+ } catch (error) {+ errorhandler(error, res);+ }+ } else {+ // We only allow PATCH requests+ res.setHeader("Allow", "[PATCH]");+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/api/teams/[teamId]/update-limits.ts b/pages/api/teams/[teamId]/update-limits.tsdeleted file mode 100644index afeaf542..00000000--- a/pages/api/teams/[teamId]/update-limits.ts+++ /dev/null@@ -1,63 +0,0 @@-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/[teamId]/update-name.ts b/pages/api/teams/[teamId]/update-name.tsindex 03fe7eda..966148f4 100644--- a/pages/api/teams/[teamId]/update-name.ts+++ b/pages/api/teams/[teamId]/update-name.ts@@ -12,7 +12,7 @@ export default async function handle(res: NextApiResponse,) {if (req.method === "PATCH") {- // POST /api/teams/:teamId/update-name+ // PATCH /api/teams/:teamId/update-nameconst session = await getServerSession(req, res, authOptions);if (!session) {return res.status(401).end("Unauthorized");@@ -61,8 +61,8 @@ export default async function handle(return res.status(500).json((error as Error).message);}} else {- // We only allow POST requests- res.setHeader("Allow", "[POST]");+ // We only allow PATCH requests+ res.setHeader("Allow", "[PATCH]");return res.status(405).end(`Method ${req.method} Not Allowed`);}}diff --git a/pages/settings/general.tsx b/pages/settings/general.tsxindex d6449824..df62691a 100644--- a/pages/settings/general.tsx+++ b/pages/settings/general.tsx@@ -5,6 +5,7 @@ import { PlanEnum } from "@/ee/stripe/constants";import { toast } from "sonner";import { mutate } from "swr";+import { useAnalytics } from "@/lib/analytics";import { usePlan } from "@/lib/swr/use-billing";import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";@@ -14,8 +15,10 @@ import { SettingsHeader } from "@/components/settings/settings-header";import { Form } from "@/components/ui/form";export default function General() {+ const analytics = useAnalytics();const teamInfo = useTeam();- const { plan } = usePlan();+ const teamId = teamInfo?.currentTeam?.id;+ const { isFree, isPro, isTrial } = usePlan();const [selectedPlan, setSelectedPlan] = useState<PlanEnum>(PlanEnum.Pro);const [planModalTrigger, setPlanModalTrigger] = useState<string>("");const [planModalOpen, setPlanModalOpen] = useState<boolean>(false);@@ -29,31 +32,30 @@ export default function General() {const handleExcelAdvancedModeChange = async (data: {enableExcelAdvancedMode: string;}) => {- if (plan === "free" && data.enableExcelAdvancedMode === "true") {+ if (isFree && 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",- }),+ analytics.capture("Toggle Excel Advanced Mode", {+ teamId,+ enableExcelAdvancedMode: data.enableExcelAdvancedMode === "true",+ });++ const promise = fetch(`/api/teams/${teamId}/update-advanced-mode`, {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",},- ).then(async (res) => {+ 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`),- ]);+ await Promise.all([mutate(`/api/teams/${teamId}`), mutate(`/api/teams`)]);return res.json();});@@ -68,24 +70,23 @@ export default function General() {};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),+ analytics.capture("Update Team Name", {+ teamId,+ name: updateData.name,+ });++ const promise = fetch(`/api/teams/${teamId}/update-name`, {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",},- ).then(async (res) => {+ 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`),- ]);+ await Promise.all([mutate(`/api/teams/${teamId}`), mutate(`/api/teams`)]);return res.json();});@@ -127,7 +128,7 @@ export default function General() {<Formtitle="Excel Advanced Mode"- description="Enable advanced mode for all Excel files in your team. This will use Microsoft Office viewer for better formatting."+ description="Enable advanced mode for all new Excel files in your team. Existing files will not be affected."inputAttrs={{name: "enableExcelAdvancedMode",type: "checkbox",@@ -136,8 +137,9 @@ export default function General() {defaultValue={String(teamInfo?.currentTeam?.enableExcelAdvancedMode ?? false,)}- helpText="When enabled, Excel files will be viewed using the Microsoft Office viewer for better formatting and compatibility."+ helpText="When enabled, newly uploaded Excel files will be viewed using the Microsoft Office viewer for better formatting and compatibility."handleSubmit={handleExcelAdvancedModeChange}+ plan={(isFree && !isTrial) || isPro ? "Business" : undefined}/><DeleteTeam />diff --git a/prisma/migrations/20240320000000_add_excel_advanced_mode/migration.sql b/prisma/migrations/20240320000000_add_excel_advanced_mode/migration.sqldeleted file mode 100644index ae8b3a6a..00000000--- a/prisma/migrations/20240320000000_add_excel_advanced_mode/migration.sql+++ /dev/null@@ -1,2 +0,0 @@--- AlterTable-ALTER TABLE "Team" ADD COLUMN "enableExcelAdvancedMode" BOOLEAN NOT NULL DEFAULT false;\ No newline at end of filediff --git a/prisma/migrations/20250516000000_add_advanced_mode_to_team/migration.sql b/prisma/migrations/20250516000000_add_advanced_mode_to_team/migration.sqlnew file mode 100644index 00000000..6d5414bd--- /dev/null+++ b/prisma/migrations/20250516000000_add_advanced_mode_to_team/migration.sql@@ -0,0 +1,3 @@+-- AlterTable+ALTER TABLE "Team" ADD COLUMN "enableExcelAdvancedMode" BOOLEAN NOT NULL DEFAULT false;+