Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add upload agreement
Marc Seitzfa8b6ca622d8
diff --git a/components/document-upload.tsx b/components/document-upload.tsxindex 321bb8a5..1306bd51 100644--- a/components/document-upload.tsx+++ b/components/document-upload.tsx@@ -1,4 +1,4 @@-import { useMemo, useState } from "react";+import { useMemo } from "react";import {Upload as ArrowUpTrayIcon,diff --git a/components/links/link-sheet/agreement-panel/index.tsx b/components/links/link-sheet/agreement-panel/index.tsxindex 0e37609a..8dbd5eec 100644--- a/components/links/link-sheet/agreement-panel/index.tsx+++ b/components/links/link-sheet/agreement-panel/index.tsx@@ -1,5 +1,3 @@-import { useRouter } from "next/router";-import {Dispatch,FormEvent,@@ -11,13 +9,11 @@ import {import { useTeam } from "@/context/team-context";import { toast } from "sonner";import { mutate } from "swr";-import { set } from "ts-pattern/dist/patterns";+import DocumentUpload from "@/components/document-upload";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";-import { ScrollArea } from "@/components/ui/scroll-area";-import { Separator } from "@/components/ui/separator";import {Sheet,SheetContent,@@ -27,12 +23,12 @@ import {SheetTitle,} from "@/components/ui/sheet";-import { useAnalytics } from "@/lib/analytics";-import { usePlan } from "@/lib/swr/use-billing";-import { useDocumentLinks } from "@/lib/swr/use-document";-import { useDomains } from "@/lib/swr/use-domains";-import { LinkWithViews } from "@/lib/types";-import { convertDataUrlToFile, uploadImage } from "@/lib/utils";+import {+ DocumentData,+ createAgreementDocument,+} from "@/lib/documents/create-document";+import { putFile } from "@/lib/files/put-file";+import { getSupportedContentType } from "@/lib/utils/get-content-type";export default function AgreementSheet({isOpen,@@ -45,6 +41,62 @@ export default function AgreementSheet({const teamId = teamInfo?.currentTeam?.id;const [data, setData] = useState({ name: "", link: "" });const [isLoading, setIsLoading] = useState<boolean>(false);+ const [currentFile, setCurrentFile] = useState<File | null>(null);+ const [currentLink, setCurrentLink] = useState<string | null>(null);++ const handleBrowserUpload = async () => {+ // event.preventDefault();+ // event.stopPropagation();++ // Check if the file is chosen+ if (!currentFile) {+ toast.error("Please select a file to upload.");+ return; // prevent form from submitting+ }++ try {+ setIsLoading(true);++ const contentType = getSupportedContentType(currentFile.type);++ if (!contentType || currentFile.type !== "application/pdf") {+ toast.error("Unsupported file format. Please upload a PDF file.");+ return;+ }++ const { type, data, numPages } = await putFile({+ file: currentFile,+ teamId: teamId!,+ });++ const documentData: DocumentData = {+ name: currentFile.name,+ key: data!,+ storageType: type!,+ contentType: contentType,+ };+ // create a document in the database+ const response = await createAgreementDocument({+ documentData,+ teamId: teamId!,+ numPages,+ });++ if (response) {+ const document = await response.json();+ const linkId = document.links[0].id;+ setData((prevData) => ({+ ...prevData,+ link: "https://www.papermark.io/view/" + linkId,+ }));+ }+ } catch (error) {+ console.error("An error occurred while uploading the file: ", error);+ } finally {+ setCurrentFile(null);+ setIsLoading(false);+ }+ };const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {e.preventDefault();@@ -77,9 +129,16 @@ export default function AgreementSheet({} finally {setIsLoading(false);setIsOpen(false);+ setData({ name: "", link: "" });}};+ useEffect(() => {+ if (currentFile) {+ handleBrowserUpload();+ }+ }, [currentFile]);+return (<Sheet open={isOpen} onOpenChange={setIsOpen}><SheetContent className="flex w-[85%] flex-col justify-between bg-background px-4 text-foreground sm:w-[500px] md:px-5">@@ -114,31 +173,45 @@ export default function AgreementSheet({/></div>- <div className="w-full space-y-2">- <Label htmlFor="link">Link</Label>- <Input- className="flex w-full rounded-md border-0 bg-background py-1.5 text-foreground shadow-sm ring-1 ring-inset ring-input placeholder:text-muted-foreground focus:ring-2 focus:ring-inset focus:ring-gray-400 sm:text-sm sm:leading-6"- id="link"- type="url"- pattern="https://.*"- name="link"- required- autoComplete="off"- data-1p-ignore- placeholder="https://www.papermark.io/nda"- value={data.link || ""}- onChange={(e) =>- setData({- ...data,- link: e.target.value,- })- }- onInvalid={(e) =>- e.currentTarget.setCustomValidity(- "Please enter a valid URL starting with https://",- )- }- />+ <div className="space-y-4">+ <div className="w-full space-y-2">+ <Label htmlFor="link">Link to an agreement</Label>+ <Input+ className="flex w-full rounded-md border-0 bg-background py-1.5 text-foreground shadow-sm ring-1 ring-inset ring-input placeholder:text-muted-foreground focus:ring-2 focus:ring-inset focus:ring-gray-400 sm:text-sm sm:leading-6"+ id="link"+ type="url"+ pattern="https://.*"+ name="link"+ required+ autoComplete="off"+ data-1p-ignore+ placeholder="https://www.papermark.io/nda"+ value={data.link || ""}+ onChange={(e) =>+ setData({+ ...data,+ link: e.target.value,+ })+ }+ onInvalid={(e) =>+ e.currentTarget.setCustomValidity(+ "Please enter a valid URL starting with https://",+ )+ }+ />+ </div>++ <div className="space-y-12">+ <div className="space-y-2 pb-6">+ <Label>Or upload an agreement</Label>+ <div className="grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">+ <DocumentUpload+ currentFile={currentFile}+ setCurrentFile={setCurrentFile}+ />+ </div>+ </div>+ </div></div></div>diff --git a/components/links/link-sheet/agreement-section.tsx b/components/links/link-sheet/agreement-section.tsxindex eecec442..cd7c81d3 100644--- a/components/links/link-sheet/agreement-section.tsx+++ b/components/links/link-sheet/agreement-section.tsx@@ -1,15 +1,7 @@-import {- Dispatch,- SetStateAction,- useCallback,- useEffect,- useState,-} from "react";+import { Dispatch, SetStateAction, useEffect, useState } from "react";-import { Button } from "@react-email/components";import { motion } from "framer-motion";-import { Label } from "@/components/ui/label";import {Select,SelectContent,diff --git a/lib/documents/create-document.ts b/lib/documents/create-document.tsindex 66c6039a..022e45df 100644--- a/lib/documents/create-document.ts+++ b/lib/documents/create-document.ts@@ -41,6 +41,40 @@ export const createDocument = async ({return response;};+export const createAgreementDocument = async ({+ documentData,+ teamId,+ numPages,+ folderPathName,+}: {+ documentData: DocumentData;+ teamId: string;+ numPages?: number;+ folderPathName?: string;+}) => {+ // create a document in the database with the blob url+ const response = await fetch(`/api/teams/${teamId}/documents/agreement`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ name: documentData.name,+ url: documentData.key,+ storageType: documentData.storageType,+ numPages: numPages,+ folderPathName: folderPathName,+ type: documentData.contentType,+ }),+ });++ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }++ return response;+};+// create a new version in the databaseexport const createNewDocumentVersion = async ({documentData,diff --git a/pages/api/teams/[teamId]/agreements/index.ts b/pages/api/teams/[teamId]/agreements/index.tsindex 40d8a9ca..92b0c627 100644--- a/pages/api/teams/[teamId]/agreements/index.ts+++ b/pages/api/teams/[teamId]/agreements/index.ts@@ -82,7 +82,7 @@ export default async function handle(const { name, link } = req.body as { name: string; link: string };- const response = await prisma.agreement.create({+ const agreement = await prisma.agreement.create({data: {teamId,name,@@ -90,7 +90,7 @@ export default async function handle(},});- return res.status(201).json(response);+ return res.status(201).json(agreement);} catch (error) {log({message: `Failed to add agreement. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``,diff --git a/pages/api/teams/[teamId]/documents/agreement.ts b/pages/api/teams/[teamId]/documents/agreement.tsnew file mode 100644index 00000000..e4ebe136--- /dev/null+++ b/pages/api/teams/[teamId]/documents/agreement.ts@@ -0,0 +1,135 @@+import { NextApiRequest, NextApiResponse } from "next";++import { client } from "@/trigger";+import { DocumentStorageType } from "@prisma/client";+import { getServerSession } from "next-auth/next";+import { parsePageId } from "notion-utils";++import { errorhandler } from "@/lib/errorHandler";+import notion from "@/lib/notion";+import prisma from "@/lib/prisma";+import { getTeamWithUsersAndDocument } from "@/lib/team/helper";+import { CustomUser } from "@/lib/types";+import { getExtension, log } from "@/lib/utils";++import { authOptions } from "../../../auth/[...nextauth]";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "POST") {+ // POST /api/teams/:teamId/documents/agreement+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ res.status(401).end("Unauthorized");+ return;+ }++ const { teamId } = req.query as { teamId: string };++ const userId = (session.user as CustomUser).id;++ // Assuming data is an object with `name` and `description` properties+ const {+ name,+ url: fileUrl,+ storageType,+ numPages,+ type: fileType,+ folderPathName,+ } = req.body as {+ name: string;+ url: string;+ storageType: DocumentStorageType;+ numPages?: number;+ type?: string;+ folderPathName?: string;+ };++ try {+ await getTeamWithUsersAndDocument({+ teamId,+ userId,+ });++ // Get passed type property or alternatively, the file extension and save it as the type+ const type = fileType || getExtension(name);++ const folder = await prisma.folder.findUnique({+ where: {+ teamId_path: {+ teamId,+ path: "/" + folderPathName,+ },+ },+ select: {+ id: true,+ },+ });++ // Save data to the database+ const document = await prisma.document.create({+ data: {+ name: name,+ numPages: numPages,+ file: fileUrl,+ type: type,+ storageType,+ ownerId: (session.user as CustomUser).id,+ teamId: teamId,+ links: {+ // create link for agreement without any protection+ create: {+ name: "Generated Agreement Link",+ emailProtected: false,+ enableFeedback: false,+ enableNotification: false,+ },+ },+ versions: {+ create: {+ file: fileUrl,+ type: type,+ storageType,+ numPages: numPages,+ isPrimary: true,+ versionNumber: 1,+ },+ },+ folderId: folder?.id ? folder.id : null,+ },+ include: {+ links: true,+ versions: true,+ },+ });++ // skip triggering convert-pdf-to-image job for "notion" / "excel" documents+ if (type === "pdf") {+ // trigger document uploaded event to trigger convert-pdf-to-image job+ await client.sendEvent({+ id: document.versions[0].id, // unique eventId for the run+ name: "document.uploaded",+ payload: {+ documentVersionId: document.versions[0].id,+ teamId: teamId,+ documentId: document.id,+ },+ });+ }++ return res.status(201).json(document);+ } catch (error) {+ log({+ message: `Failed to create document. \n\n*teamId*: _${teamId}_, \n\n*file*: ${fileUrl} \n\n ${error}`,+ type: "error",+ });+ errorhandler(error, res);+ }+ } else {+ // We only allow GET and POST requests+ res.setHeader("Allow", ["GET", "POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}