Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: add end of document feedback question

Marc Seitz73a26cf38a91
diff --git a/components/Sidebar.tsx b/components/Sidebar.tsx
index 58df4c02..cf72dcc6 100644
--- a/components/Sidebar.tsx
+++ b/components/Sidebar.tsx
@@ -127,7 +127,8 @@ export const SidebarComponent = ({ className }: { className?: string }) => {
current:
router.pathname.includes("settings") &&
!router.pathname.includes("branding") &&
- !router.pathname.includes("datarooms"),
+ !router.pathname.includes("datarooms") &&
+ !router.pathname.includes("documents"),
active: false,
disabled: false,
},
diff --git a/pages/api/teams/[teamId]/documents/[id]/feedback/index.ts b/pages/api/teams/[teamId]/documents/[id]/feedback/index.ts
new file mode 100644
index 00000000..99d1493a
--- /dev/null
+++ b/pages/api/teams/[teamId]/documents/[id]/feedback/index.ts
@@ -0,0 +1,141 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { getServerSession } from "next-auth/next";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import { errorhandler } from "@/lib/errorHandler";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "GET") {
+ // GET /api/teams/:teamId/documents/:id/feedback
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const { teamId, id: documentId } = req.query as {
+ teamId: string;
+ id: string;
+ };
+ const userId = (session.user as CustomUser).id;
+
+ try {
+ const document = await prisma.document.findUnique({
+ where: {
+ id: documentId,
+ teamId: teamId,
+ team: {
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ },
+ });
+ if (!document) {
+ return res.status(404).json({ message: "Not found" });
+ }
+ } catch (error) {
+ return errorhandler(error, res);
+ }
+
+ try {
+ const feedback = await prisma.feedback.findUnique({
+ where: { documentId },
+ });
+
+ return res.status(200).json(feedback);
+ } catch (error) {
+ return errorhandler(error, res);
+ }
+ } else if (req.method === "PUT") {
+ // PUT /api/teams/:teamId/document/:id/feedback
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).end("Unauthorized");
+ return;
+ }
+ const userId = (session.user as CustomUser).id;
+ const { teamId, id: documentId } = req.query as {
+ teamId: string;
+ id: string;
+ };
+ const { questionText, enabled } = req.body as {
+ questionText?: string;
+ enabled?: boolean;
+ };
+
+ try {
+ const document = await prisma.document.findUnique({
+ where: {
+ id: documentId,
+ teamId: teamId,
+ team: {
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ },
+ });
+ if (!document) {
+ return res.status(404).json({ message: "Not found" });
+ }
+ } catch (error) {
+ return errorhandler(error, res);
+ }
+
+ // construct the feedback object
+ const feedbackJsonPayload = {
+ question: questionText,
+ type: "YES_NO",
+ };
+
+ try {
+ // get the feedback object
+ let feedback: { id: string } | null = await prisma.feedback.findUnique({
+ where: { documentId },
+ select: { id: true },
+ });
+
+ // if feedback object does not exist, create it
+ if (!feedback) {
+ feedback = await prisma.feedback.create({
+ data: {
+ documentId,
+ data: feedbackJsonPayload,
+ },
+ });
+ } else {
+ feedback = await prisma.feedback.update({
+ where: {
+ id: feedback.id,
+ },
+ data: {
+ ...(questionText && { data: feedbackJsonPayload }),
+ ...(enabled !== undefined && { enabled: enabled }),
+ },
+ });
+ }
+
+ await fetch(
+ `${process.env.NEXTAUTH_URL}/api/revalidate?secret=${process.env.REVALIDATE_TOKEN}&documentId=${documentId}`,
+ );
+
+ return res.status(200).json({
+ message: "Success",
+ });
+ } catch (error) {
+ return errorhandler(error, res);
+ }
+ } else {
+ // We only allow GET, PUT and DELETE requests
+ res.setHeader("Allow", ["GET", "PUT"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/documents/[id]/settings.tsx b/pages/documents/[id]/settings.tsx
new file mode 100644
index 00000000..764a9455
--- /dev/null
+++ b/pages/documents/[id]/settings.tsx
@@ -0,0 +1,296 @@
+import DocumentHeader from "@/components/documents/document-header";
+import AppLayout from "@/components/layouts/app";
+import { NavMenu } from "@/components/navigation-menu";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import LoadingSpinner from "@/components/ui/loading-spinner";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { useTeam } from "@/context/team-context";
+import { useDocument } from "@/lib/swr/use-document";
+import { cn, fetcher } from "@/lib/utils";
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+import useSWR, { mutate } from "swr";
+
+type Feedback = {
+ id: string;
+ documentId: string;
+ enabled: boolean;
+ data: {
+ question: string;
+ type: string;
+ };
+ createdAt: Date;
+ updatedAt: Date;
+};
+
+export default function Settings() {
+ const { document, primaryVersion } = useDocument();
+
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+ const id = document?.id;
+
+ const { data: feedback } = useSWR<Feedback>(
+ teamId && id && `/api/teams/${teamId}/documents/${id}/feedback`,
+ fetcher,
+ {
+ dedupingInterval: 1000 * 60 * 60,
+ },
+ );
+
+ const [loading, setLoading] = useState(false);
+ const [loadingStatus, setLoadingStatus] = useState(false);
+ const [value, setValue] = useState<string>("");
+
+ useEffect(() => {
+ setValue(feedback?.data.question || "");
+ }, [feedback]);
+
+ return (
+ <AppLayout>
+ <main className="relative overflow-hidden mx-2 sm:mx-3 md:mx-5 lg:mx-7 xl:mx-10 mt-4 md:mt-5 lg:mt-8 mb-10 space-y-8 px-1">
+ {document && primaryVersion ? (
+ <>
+ {/* Action Header */}
+ <DocumentHeader
+ primaryVersion={primaryVersion}
+ prismaDocument={document}
+ teamId={teamInfo?.currentTeam?.id!}
+ />
+
+ <NavMenu
+ navigation={[
+ {
+ label: "Overview",
+ href: `/documents/${document.id}`,
+ segment: `${document.id}`,
+ },
+ {
+ label: "Settings",
+ href: `/documents/${document.id}/settings`,
+ segment: "settings",
+ },
+ ]}
+ />
+
+ {/* Settings */}
+ <div className="mx-auto grid w-full gap-2">
+ <h1 className="text-2xl font-semibold">Settings</h1>
+ </div>
+ <div className="mx-auto grid w-full items-start gap-6 md:grid-cols-[180px_1fr] lg:grid-cols-[250px_1fr]">
+ <nav className="grid gap-4 text-sm text-muted-foreground">
+ <Link href="#" className="font-semibold text-primary">
+ Feedback
+ </Link>
+ </nav>
+ <div className="grid gap-6">
+ {/* <Card>
+ <CardHeader>
+ <CardTitle>Document Name</CardTitle>
+ <CardDescription>
+ Used to identify your document.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <form>
+ <Input placeholder="Document Name" />
+ </form>
+ </CardContent>
+ <CardFooter className="border-t px-6 py-3 bg-muted rounded-b-lg justify-end">
+ <Button>Save</Button>
+ </CardFooter>
+ </Card> */}
+ <Card>
+ <CardHeader className="relative">
+ <CardTitle>Feedback Question</CardTitle>
+ <CardDescription>
+ This question will be shown to visitors after the last
+ page of your document.
+ </CardDescription>
+ <div className="absolute right-8 top-6">
+ <span
+ className="relative ml-auto flex h-4 w-4"
+ title={`Feedback is ${feedback?.enabled ? "" : "not"} active`}
+ >
+ <span
+ className={cn(
+ "absolute inline-flex h-full w-full rounded-full opacity-75",
+ feedback?.enabled
+ ? "animate-ping bg-green-400"
+ : "",
+ )}
+ />
+ <span
+ className={cn(
+ "relative inline-flex rounded-full h-4 w-4",
+ feedback?.enabled ? "bg-green-500" : "bg-red-500",
+ )}
+ />
+ </span>
+ <span className="sr-only">
+ {feedback?.enabled ? "Enabled" : "Disabled"}
+ </span>
+ </div>
+ </CardHeader>
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ setLoading(true);
+
+ if (value == "") return null;
+
+ try {
+ const response = await fetch(
+ `/api/teams/${teamId}/documents/${id}/feedback`,
+ {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ questionText: value }),
+ },
+ );
+
+ if (response.status === 200) {
+ await mutate(
+ `/api/teams/${teamId}/documents/${id}/feedback`,
+ );
+ toast.success(
+ "Successfully added a feedback question!",
+ );
+ } else {
+ const { error } = await response.json();
+ toast.error(error.message);
+ }
+ } catch (error) {
+ // Handle any errors that might occur during fetch
+ toast.error(
+ "An error occurred while adding the question.",
+ );
+ console.error("Fetch error:", error);
+ } finally {
+ setLoading(false);
+ }
+ }}
+ >
+ <CardContent>
+ <div className="grid w-full items-start gap-6 overflow-x-visible pb-4 pt-0">
+ <div className="grid gap-3">
+ <Label>Question Type</Label>
+ <Select defaultValue="yes-no">
+ <SelectTrigger>
+ <SelectValue placeholder="Select a question type" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="yes-no">Yes / No</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="grid gap-3">
+ <Label htmlFor="question">Question</Label>
+ <Input
+ id="question"
+ type="text"
+ name="question"
+ required
+ placeholder="Are you interested?"
+ value={value || ""}
+ onChange={(e) => setValue(e.target.value)}
+ />
+ </div>
+ </div>
+ </CardContent>
+ <CardFooter className="border-t py-3 bg-muted rounded-b-lg justify-end gap-x-2">
+ <Button
+ type="button"
+ variant="outline"
+ loading={loadingStatus}
+ onClick={async (e) => {
+ try {
+ e.preventDefault();
+ setLoadingStatus(true);
+
+ const response = await fetch(
+ `/api/teams/${teamId}/documents/${id}/feedback`,
+ {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ enabled: !feedback?.enabled,
+ }),
+ },
+ );
+
+ if (response.status === 200) {
+ await mutate(
+ `/api/teams/${teamId}/documents/${id}/feedback`,
+ );
+ toast.success(
+ `${feedback?.enabled ? "Turned off" : "Turned on"} feedback question`,
+ );
+ } else {
+ const { error } = await response.json();
+ toast.error(error.message);
+ }
+ } catch (error) {
+ // Handle any errors that might occur during fetch
+ toast.error("An error occurred.");
+ console.error("Fetch error:", error);
+ } finally {
+ setLoadingStatus(false);
+ }
+ }}
+ >
+ {feedback?.enabled ? "Turn off" : "Turn on"}
+ </Button>
+ <Button type="submit" loading={loading}>
+ {feedback ? "Update question" : "Create question"}
+ </Button>
+ </CardFooter>
+ </form>
+ </Card>
+ {/* <Card className="border-red-500">
+ <CardHeader>
+ <CardTitle>Delete Document</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <p className="text-sm text-muted-foreground">
+ This actions deletes the document and any associates links
+ and analytics.
+ </p>
+ </CardContent>
+ <CardFooter className="border-t px-6 py-3 border-red-500 rounded-b-lg justify-end">
+ <Button variant="destructive">Delete document</Button>
+ </CardFooter>
+ </Card> */}
+ </div>
+ </div>
+ </>
+ ) : (
+ <div className="h-screen flex items-center justify-center">
+ <LoadingSpinner className="mr-1 h-20 w-20" />
+ </div>
+ )}
+ </main>
+ </AppLayout>
+ );
+}
diff --git a/prisma/migrations/20240415000000_add_feedback/migration.sql b/prisma/migrations/20240415000000_add_feedback/migration.sql
new file mode 100644
index 00000000..1e2a8388
--- /dev/null
+++ b/prisma/migrations/20240415000000_add_feedback/migration.sql
@@ -0,0 +1,48 @@
+-- CreateTable
+CREATE TABLE "Feedback" (
+ "id" TEXT NOT NULL,
+ "documentId" TEXT NOT NULL,
+ "enabled" BOOLEAN NOT NULL DEFAULT false,
+ "data" JSONB NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "Feedback_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "FeedbackResponse" (
+ "id" TEXT NOT NULL,
+ "feedbackId" TEXT NOT NULL,
+ "data" JSONB NOT NULL,
+ "viewId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "FeedbackResponse_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "Feedback_documentId_key" ON "Feedback"("documentId");
+
+-- CreateIndex
+CREATE INDEX "Feedback_documentId_idx" ON "Feedback"("documentId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "FeedbackResponse_viewId_key" ON "FeedbackResponse"("viewId");
+
+-- CreateIndex
+CREATE INDEX "FeedbackResponse_feedbackId_idx" ON "FeedbackResponse"("feedbackId");
+
+-- CreateIndex
+CREATE INDEX "FeedbackResponse_viewId_idx" ON "FeedbackResponse"("viewId");
+
+-- AddForeignKey
+ALTER TABLE "Feedback" ADD CONSTRAINT "Feedback_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "Document"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "FeedbackResponse" ADD CONSTRAINT "FeedbackResponse_feedbackId_fkey" FOREIGN KEY ("feedbackId") REFERENCES "Feedback"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "FeedbackResponse" ADD CONSTRAINT "FeedbackResponse_viewId_fkey" FOREIGN KEY ("viewId") REFERENCES "View"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 678bd025..2cce872f 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -135,6 +135,7 @@ model Document {
views View[]
versions DocumentVersion[]
conversations Conversation[]
+ feedback Feedback?
folderId String? // Optional Folder ID for documents in folders
folder Folder? @relation(fields: [folderId], references: [id], onDelete: SetNull)
@@ -246,22 +247,23 @@ model Domain {
}
model View {
- id String @id @default(cuid())
- link Link @relation(fields: [linkId], references: [id])
- linkId String
- document Document? @relation(fields: [documentId], references: [id], onDelete: Cascade)
- documentId String?
- dataroom Dataroom? @relation(fields: [dataroomId], references: [id], onDelete: Cascade)
- dataroomId String?
- dataroomViewId String? // This is the view ID from the dataroom
- viewerEmail String? // Email of the viewer if known
- verified Boolean @default(false) // Whether the viewer email has been verified
- viewedAt DateTime @default(now())
- downloadedAt DateTime? // This is the time the document was downloaded
- reactions Reaction[]
- viewType ViewType @default(DOCUMENT_VIEW)
- viewerId String? // This is the viewer ID from the dataroom
- viewer Viewer? @relation(fields: [viewerId], references: [id], onDelete: Cascade)
+ id String @id @default(cuid())
+ link Link @relation(fields: [linkId], references: [id])
+ linkId String
+ document Document? @relation(fields: [documentId], references: [id], onDelete: Cascade)
+ documentId String?
+ dataroom Dataroom? @relation(fields: [dataroomId], references: [id], onDelete: Cascade)
+ dataroomId String?
+ dataroomViewId String? // This is the view ID from the dataroom
+ viewerEmail String? // Email of the viewer if known
+ verified Boolean @default(false) // Whether the viewer email has been verified
+ viewedAt DateTime @default(now())
+ downloadedAt DateTime? // This is the time the document was downloaded
+ reactions Reaction[]
+ viewType ViewType @default(DOCUMENT_VIEW)
+ viewerId String? // This is the viewer ID from the dataroom
+ viewer Viewer? @relation(fields: [viewerId], references: [id], onDelete: Cascade)
+ feedbackResponse FeedbackResponse?
@@index([linkId])
@@index([documentId])
@@ -432,3 +434,33 @@ model DataroomBrand {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
+
+model Feedback {
+ id String @id @default(cuid())
+ documentId String @unique
+ document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)
+ enabled Boolean @default(false) // This indicates if feedback is enabled for this document
+ data Json // This will store the feedback question data: {question: "What is the purpose of this document?", type: "yes/no", options: ["Yes", "No"]}
+
+ responses FeedbackResponse[]
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([documentId])
+}
+
+model FeedbackResponse {
+ id String @id @default(cuid())
+ feedbackId String
+ feedback Feedback @relation(fields: [feedbackId], references: [id], onDelete: Cascade)
+ data Json // This will store the feedback question data: {question: "What is the purpose of this document?", type: "yes/no", options: ["Yes", "No"], answer: "Yes"}
+ viewId String @unique
+ view View @relation(fields: [viewId], references: [id], onDelete: Cascade)
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([feedbackId])
+ @@index([viewId])
+}