Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add upload new document version
Marc Seitzed64bc1009ae
diff --git a/components/documents/add-document-modal.tsx b/components/documents/add-document-modal.tsxindex 7b6f52b0..fe121bed 100644--- a/components/documents/add-document-modal.tsx+++ b/components/documents/add-document-modal.tsx@@ -15,10 +15,11 @@ import { pdfjs } from "react-pdf";import { copyToClipboard, getExtension } from "@/lib/utils";import { Button } from "../ui/button";import { usePlausible } from "next-plausible";+import { toast } from "sonner";pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;-export function AddDocumentModal({children}: {children: React.ReactNode}) {+export function AddDocumentModal({newVersion, children}: {newVersion?: boolean, children: React.ReactNode}) {const router = useRouter();const plausible = usePlausible();const [uploading, setUploading] = useState<boolean>(false);@@ -43,27 +44,56 @@ export function AddDocumentModal({children}: {children: React.ReactNode}) {let response: Response | undefined;let numPages: number | undefined;- // create a document in the database if the document is a pdf+ // create a document or new version in the database if the document is a pdfif (getExtension(newBlob.pathname).includes("pdf")) {numPages = await getTotalPages(newBlob.url);- response = await saveDocumentToDatabase(newBlob, numPages);- } else {- response = await saveDocumentToDatabase(newBlob);+ if (!newVersion) {+ // create a document in the database+ response = await saveDocumentToDatabase(newBlob, numPages);+ } else {+ // create a new version for existing document in the database+ const documentId = router.query.id;+ response = await saveNewVersionToDatabase(+ newBlob,+ documentId as string,+ numPages+ );+ }}if (response) {const document = await response.json();- // copy the link to the clipboard- copyToClipboard(`${process.env.NEXT_PUBLIC_BASE_URL}/view/${document.links[0].id}`, "Document uploaded and link copied to clipboard. Redirecting to document page...")-- // track the event- plausible("documentUploaded");-- setTimeout(() => {- router.push("/documents/" + document.id);- setUploading(false);- }, 2000);+ console.log("document: ", document)++ if (!newVersion) {+ // copy the link to the clipboard+ copyToClipboard(+ `${process.env.NEXT_PUBLIC_BASE_URL}/view/${document.links[0].id}`,+ "Document uploaded and link copied to clipboard. Redirecting to document page..."+ );++ // track the event+ plausible("documentUploaded");++ // redirect to the document page+ setTimeout(() => {+ router.push("/documents/" + document.id);+ setUploading(false);+ }, 2000);+ } else {+ // track the event+ plausible("documentVersionUploaded");+ toast.success("New document version uploaded.");++ // reload to the document page+ setTimeout(() => {+ router.reload();+ setUploading(false);+ }, 2000);+ }++}} catch (error) {console.error("An error occurred while uploading the file: ", error);@@ -91,6 +121,27 @@ export function AddDocumentModal({children}: {children: React.ReactNode}) {return response;}+ // create a new version in the database+ async function saveNewVersionToDatabase(blob: PutBlobResult, documentId: string, numPages?: number) {+ const response = await fetch(`/api/documents/${documentId}/versions`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ url: blob.url,+ numPages: numPages,+ type: "pdf",+ }),+ });++ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }++ return response;+ }+// get the number of pages in the pdfasync function getTotalPages(url: string): Promise<number> {const pdf = await pdfjs.getDocument(url).promise;@@ -102,12 +153,12 @@ export function AddDocumentModal({children}: {children: React.ReactNode}) {<DialogTrigger asChild>{children}</DialogTrigger><DialogContent className="text-foreground bg-background"><DialogHeader>- <DialogTitle>Share a document</DialogTitle>+ <DialogTitle>{newVersion ? `Upload a new version` : `Share a document`}</DialogTitle><DialogDescription><div className="border-b border-border py-2"><p className="mb-1 text-sm text-muted-foreground">- After you upload the document, a shareable link will be- generated and copied to your clipboard.+ {newVersion ? `After you upload a new version, the existing links will remain the unchanged but ` : `After you upload the document, a shareable link will be+ generated and copied to your clipboard.`}</p></div><formdiff --git a/components/shared/icons/file-up.tsx b/components/shared/icons/file-up.tsxnew file mode 100644index 00000000..a40501aa--- /dev/null+++ b/components/shared/icons/file-up.tsx@@ -0,0 +1,21 @@+export default function FileUp({ className }: { className?: string }) {+ return (+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ className={className}+ shapeRendering="geometricPrecision"+ >+ <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z" />+ <polyline points="14 2 14 8 20 8" />+ <path d="M12 12v6" />+ <path d="m15 15-3-3-3 3" />+ </svg>+ );+}\ No newline at end of filediff --git a/pages/api/documents/[id]/versions/index.ts b/pages/api/documents/[id]/versions/index.tsnew file mode 100644index 00000000..80e4db31--- /dev/null+++ b/pages/api/documents/[id]/versions/index.ts@@ -0,0 +1,88 @@+import { NextApiRequest, NextApiResponse } from "next";+import { getServerSession } from "next-auth/next";+import prisma from "@/lib/prisma";+import { log } from "@/lib/utils";+import { authOptions } from "@/pages/api/auth/[...nextauth]";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse+) {+ if (req.method === "POST") {+ // GET /api/documents/:id/versions+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ // get document id from query params+ const { id: documentId } = req.query as { id: string };+ const { url, type, numPages } = req.body as { url: string, type: string, numPages: number };++ console.log("documentId", documentId)+ console.log("file", url)+++ try {+ // 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 },+ },+ },+ });++ console.log("result", result)++ // create a new document version+ const currentVersionNumber = result?.versions[0]?.versionNumber!;+ console.log("currentVersionNumber", currentVersionNumber)+ const version = await prisma.documentVersion.create({+ data: {+ documentId: documentId,+ file: url,+ type: type,+ numPages: numPages,+ isPrimary: true,+ versionNumber: currentVersionNumber + 1,+ },+ });++ console.log("version", version)++ // update all other versions to be not primary+ await prisma.documentVersion.updateMany({+ where: {+ documentId: documentId,+ versionNumber: {+ not: version.versionNumber,+ },+ },+ data: {+ isPrimary: false,+ },+ });+++ res.status(200).json({ id: documentId });+ } catch (error) {+ log(+ `Failed to create new version for document ${documentId}. Error: \n\n ${error}`+ );+ return res.status(500).json({+ message: "Internal Server Error",+ error: (error as Error).message,+ });+ }+ } else {+ // We only allow GET requests+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/documents/[id].tsx b/pages/documents/[id].tsxindex 36b907b2..6a27dc95 100644--- a/pages/documents/[id].tsx+++ b/pages/documents/[id].tsx@@ -11,6 +11,8 @@ import VisitorsTable from "@/components/visitors/visitors-table";import { useState } from "react";import { Button } from "@/components/ui/button";import LoadingSpinner from "@/components/ui/loading-spinner";+import { AddDocumentModal } from "@/components/documents/add-document-modal";+import FileUp from "@/components/shared/icons/file-up";export default function DocumentPage() {const { document, primaryVersion, error } = useDocument();@@ -44,9 +46,16 @@ export default function DocumentPage() {</h2></div></div>- <Button onClick={() => setIsLinkSheetOpen(true)}>- Create Link- </Button>+ <div className="flex items-center space-x-4">+ <AddDocumentModal newVersion>+ <button title="Upload a new version">+ <FileUp className="w-6 h-6" />+ </button>+ </AddDocumentModal>+ <Button onClick={() => setIsLinkSheetOpen(true)}>+ Create Link+ </Button>+ </div></div>{/* Stats */}{document.numPages !== null && (