Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add DocumentVersion and migrations
Marc Seitz17730a438235
diff --git a/components/documents/document-card.tsx b/components/documents/document-card.tsxindex cc7a6bfe..c310a97d 100644--- a/components/documents/document-card.tsx+++ b/components/documents/document-card.tsx@@ -22,7 +22,7 @@ export default function DocumentsCard({<div className="min-w-0 flex shrink items-center space-x-4"><div className="w-8 mx-1 text-center flex justify-center items-center"><Image- src={`/_icons/${getExtension(document.file)}.svg`}+ src={`/_icons/${document.type}.svg`}alt="File icon"width={50}height={50}@@ -56,6 +56,12 @@ export default function DocumentsCard({<p className="truncate">{`${document._count.links} ${document._count.links === 1 ? "Link" : "Links"}`}</p>+ { document._count.versions > 1 ? (+ <>+ <p>•</p>+ <p className="truncate">{`${document._count.versions} Versions`}</p>+ </>+ ) : null}</div></div></div>diff --git a/lib/swr/use-document.ts b/lib/swr/use-document.tsindex 0592dc4d..87726a9b 100644--- a/lib/swr/use-document.ts+++ b/lib/swr/use-document.ts@@ -1,7 +1,7 @@import { useRouter } from "next/router";import useSWR from "swr";import { fetcher } from "@/lib/utils";-import { LinkWithViews } from "@/lib/types";+import { DocumentWithVersion, LinkWithViews } from "@/lib/types";import { Document, View } from "@prisma/client";export function useDocument() {@@ -11,7 +11,7 @@ export function useDocument() {id: string;};- const { data: document, error } = useSWR<Document>(+ const { data: document, error } = useSWR<DocumentWithVersion>(id && `/api/documents/${encodeURIComponent(id)}`,fetcher,{@@ -21,6 +21,7 @@ export function useDocument() {return {document,+ primaryVersion: document?.versions[0],loading: !error && !document,error,};diff --git a/lib/types.ts b/lib/types.tsindex 2b9a9af4..6edd4476 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -1,5 +1,5 @@import { User as NextAuthUser } from "next-auth";-import { Document, Link, View, User as PrismaUser } from "@prisma/client";+import { Document, Link, View, User as PrismaUser, DocumentVersion } from "@prisma/client";export type CustomUser = NextAuthUser & PrismaUser;@@ -14,10 +14,15 @@ export interface DocumentWithLinksAndLinkCountAndViewCount extends Document {_count: {links: number;views: number;+ versions: number;};links: Link[];}+export interface DocumentWithVersion extends Document {+ versions: DocumentVersion[];+}+export interface LinkWithViews extends Link {_count: {views: number;diff --git a/pages/api/documents/[id]/index.ts b/pages/api/documents/[id]/index.tsindex e9f0747f..e37f523d 100644--- a/pages/api/documents/[id]/index.ts+++ b/pages/api/documents/[id]/index.ts@@ -23,6 +23,14 @@ export default async function handle(where: {id: id,},+ include: {+ // Get the latest primary version of the document+ versions: {+ where: { isPrimary: true },+ orderBy: { createdAt: "desc" },+ take: 1,+ },+ }});if (!document) {diff --git a/pages/api/documents/[id]/views/index.ts b/pages/api/documents/[id]/views/index.tsindex 4ade3bf3..d5b1364d 100644--- a/pages/api/documents/[id]/views/index.ts+++ b/pages/api/documents/[id]/views/index.ts@@ -27,9 +27,15 @@ export default async function handle(},select: {numPages: true,+ versions: {+ where: { isPrimary: true },+ orderBy: { createdAt: "desc" },+ take: 1,+ select: { numPages: true },+ },},});- const numPages = result?.numPages;+ const numPages = result?.versions[0]?.numPages || result?.numPages || 0;const views = await prisma.view.findMany({where: {diff --git a/pages/api/documents/index.ts b/pages/api/documents/index.tsindex 029209c6..0aadd56e 100644--- a/pages/api/documents/index.ts+++ b/pages/api/documents/index.ts@@ -27,7 +27,7 @@ export default async function handle(},include: {_count: {- select: { links: true, views: true },+ select: { links: true, views: true, versions: true },},links: {take: 1,@@ -75,12 +75,22 @@ export default async function handle(file: url,type: type,ownerId: (session.user as CustomUser).id,- links : {+ links: {create: {}- }+ },+ versions: {+ create: {+ file: url,+ type: type,+ numPages: numPages,+ isPrimary: true,+ versionNumber: 1,+ },+ },},include: {links: true,+ versions: true,},});diff --git a/pages/api/documents/update.ts b/pages/api/documents/update.tsindex 6cf4991d..a0b2d732 100644--- a/pages/api/documents/update.ts+++ b/pages/api/documents/update.ts@@ -24,7 +24,15 @@ export default async function handle(// Save data to the databaseawait prisma.document.update({where: { id: documentId },- data: { numPages: numPages },+ data: {+ numPages: numPages,+ // versions: {+ // update: {+ // where: { id: documentId },+ // data: { numPages: numPages },+ // },+ // },+ },});res.status(201).json({message: "Document updated successfully"});diff --git a/pages/api/links/[id]/visits.ts b/pages/api/links/[id]/visits.tsindex 1d73d529..05e598af 100644--- a/pages/api/links/[id]/visits.ts+++ b/pages/api/links/[id]/visits.ts@@ -29,11 +29,17 @@ export default async function handle(document: {select: {numPages: true,+ versions: {+ where: { isPrimary: true },+ orderBy: { createdAt: "desc" },+ take: 1,+ select: { numPages: true },+ },},},},});- const numPages = result?.document?.numPages;+ const numPages = result?.document?.versions[0]?.numPages || result?.document?.numPages || 0;const views = await prisma.view.findMany({where: {diff --git a/pages/api/views.ts b/pages/api/views.tsindex 0df7ff02..eac6e719 100644--- a/pages/api/views.ts+++ b/pages/api/views.ts@@ -68,10 +68,15 @@ export default async function handle(include: {document: {select: {- file: true- }- }- }+ versions: {+ where: { isPrimary: true },+ orderBy: { createdAt: "desc" },+ take: 1,+ select: { file: true },+ },+ },+ },+ },});// TODO: cannot identify user because session is not available@@ -85,7 +90,7 @@ export default async function handle(viewerEmail: email,});- res.status(200).json({ message: "View recorded", viewId: newView.id, file: newView.document.file });+ res.status(200).json({ message: "View recorded", viewId: newView.id, file: newView.document.versions[0].file });} catch (error) {log(`Failed to record view for ${linkId}. Error: \n\n ${error}`);res.status(500).json({ message: (error as Error).message });diff --git a/pages/documents/[id].tsx b/pages/documents/[id].tsxindex 1d81f83b..36b907b2 100644--- a/pages/documents/[id].tsx+++ b/pages/documents/[id].tsx@@ -13,7 +13,7 @@ import { Button } from "@/components/ui/button";import LoadingSpinner from "@/components/ui/loading-spinner";export default function DocumentPage() {- const { document, error } = useDocument();+ const { document, primaryVersion, error } = useDocument();const [isLinkSheetOpen, setIsLinkSheetOpen] = useState<boolean>(false);@@ -24,7 +24,7 @@ export default function DocumentPage() {return (<AppLayout><div>- {document ? (+ {document && primaryVersion ? (<>{/* Heading */}<div className="flex flex-col items-start justify-between gap-x-8 gap-y-4 p-4 sm:flex-row sm:items-center sm:m-4">@@ -32,7 +32,7 @@ export default function DocumentPage() {<div className="flex space-x-4 items-center"><div className="w-8"><Image- src={`/_icons/${getExtension(document.file)}.svg`}+ src={`/_icons/${getExtension(primaryVersion.file)}.svg`}alt="File icon"width={50}height={50}@@ -52,12 +52,12 @@ export default function DocumentPage() {{document.numPages !== null && (<StatsChartdocumentId={document.id}- totalPages={document.numPages}+ totalPages={primaryVersion.numPages!}/>)}<StatsCard />{/* Visitors */}- <VisitorsTable numPages={document.numPages!} />+ <VisitorsTable numPages={primaryVersion.numPages!} />{/* Links */}<LinksTable /><LinkSheetdiff --git a/prisma/migrations/20231013165123_create_document_version/migration.sql b/prisma/migrations/20231013165123_create_document_version/migration.sqlnew file mode 100644index 00000000..c67ed3ef--- /dev/null+++ b/prisma/migrations/20231013165123_create_document_version/migration.sql@@ -0,0 +1,17 @@+-- CreateTable+CREATE TABLE "DocumentVersion" (+ "id" TEXT NOT NULL,+ "versionNumber" INTEGER NOT NULL,+ "documentId" TEXT NOT NULL,+ "file" TEXT NOT NULL,+ "type" TEXT,+ "numPages" INTEGER,+ "isPrimary" BOOLEAN NOT NULL DEFAULT false,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "DocumentVersion_pkey" PRIMARY KEY ("id")+);++-- AddForeignKey+ALTER TABLE "DocumentVersion" ADD CONSTRAINT "DocumentVersion_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "Document"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex c24d8f54..43eabd27 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -76,6 +76,22 @@ model Document {updatedAt DateTime @updatedAtlinks Link[]views View[]+ versions DocumentVersion[]+}++model DocumentVersion {+ id String @id @default(cuid())+ versionNumber Int // e.g., 1, 2, 3 for version control+ document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)+ documentId String+ file String // This should be a reference to where the file is stored (S3, Google Cloud Storage, etc.)+ type String? // This should be a reference to the file type (pdf, docx, etc.)+ numPages Int? // This should be a reference to the number of pages in the document+ isPrimary Boolean @default(false) // Indicates if this is the primary version+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@unique([versionNumber, documentId])}model Link {