Skip to content

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

feat(ee): add viewer side conversations faq

Marc Seitz13bc6e3670ae
diff --git a/app/(ee)/api/faqs/route.ts b/app/(ee)/api/faqs/route.ts
new file mode 100644
index 00000000..c019d648
--- /dev/null
+++ b/app/(ee)/api/faqs/route.ts
@@ -0,0 +1,115 @@
+import { NextRequest, NextResponse } from "next/server";
+
+import { verifyDataroomSession } from "@/lib/auth/dataroom-auth";
+import prisma from "@/lib/prisma";
+
+export interface VisitorFAQResponse {
+ id: string;
+ editedQuestion: string;
+ answer: string;
+ documentPageNumber?: number;
+ documentVersionNumber?: number;
+ createdAt: string;
+ document?: {
+ name: string;
+ };
+}
+
+// GET /api/faqs?linkId=xxx&dataroomId=xxx - List published FAQs for visitors
+export async function GET(req: NextRequest) {
+ try {
+ const searchParams = req.nextUrl.searchParams;
+ const linkId = searchParams.get("linkId");
+ const dataroomId = searchParams.get("dataroomId");
+ const documentId = searchParams.get("documentId");
+
+ if (!linkId || !dataroomId) {
+ return NextResponse.json(
+ { error: "linkId and dataroomId are required" },
+ { status: 400 },
+ );
+ }
+
+ // Verify dataroom session
+ const session = await verifyDataroomSession(req, linkId, dataroomId);
+ if (!session) {
+ return NextResponse.json(
+ { error: "Unauthorized - invalid or expired session" },
+ { status: 401 },
+ );
+ }
+
+ // Build where clause based on visibility filters
+ const whereClause: any = {
+ dataroomId,
+ status: "PUBLISHED",
+ };
+
+ // Apply visibility filters
+ const visibilityFilters: any[] = [
+ { visibilityMode: "PUBLIC_DATAROOM" }, // Always include dataroom-wide FAQs
+ ];
+
+ if (linkId) {
+ visibilityFilters.push({
+ visibilityMode: "PUBLIC_LINK",
+ linkId: linkId,
+ });
+ }
+
+ if (documentId) {
+ visibilityFilters.push({
+ visibilityMode: "PUBLIC_DOCUMENT",
+ dataroomDocumentId: documentId,
+ });
+ }
+
+ whereClause.OR = visibilityFilters;
+
+ // Fetch published FAQs
+ const faqs = await prisma.dataroomFaqItem.findMany({
+ where: whereClause,
+ select: {
+ id: true,
+ editedQuestion: true,
+ answer: true,
+ documentPageNumber: true,
+ documentVersionNumber: true,
+ createdAt: true,
+ dataroomDocument: {
+ select: {
+ document: {
+ select: {
+ name: true,
+ },
+ },
+ },
+ },
+ },
+ orderBy: { createdAt: "desc" },
+ });
+
+ // Format response
+ const response: VisitorFAQResponse[] = faqs.map((faq: any) => ({
+ id: faq.id,
+ editedQuestion: faq.editedQuestion,
+ answer: faq.answer,
+ documentPageNumber: faq.documentPageNumber || undefined,
+ documentVersionNumber: faq.documentVersionNumber || undefined,
+ createdAt: faq.createdAt.toISOString(),
+ document: faq.dataroomDocument?.document
+ ? {
+ name: faq.dataroomDocument.document.name,
+ }
+ : undefined,
+ }));
+
+ return NextResponse.json(response);
+ } catch (error) {
+ console.error("Error fetching visitor FAQs:", error);
+ return NextResponse.json(
+ { error: "Internal server error" },
+ { status: 500 },
+ );
+ }
+}
diff --git a/ee/features/conversations/components/shared/conversation-message.tsx b/ee/features/conversations/components/shared/conversation-message.tsx
index 8b0a4de4..bc706f4c 100644
--- a/ee/features/conversations/components/shared/conversation-message.tsx
+++ b/ee/features/conversations/components/shared/conversation-message.tsx
@@ -1,24 +1,81 @@
import { format } from "date-fns";
+import { Check, HelpCircle, MessageSquareReply } from "lucide-react";
export function ConversationMessage({
message,
isAuthor,
senderEmail,
+ isSelectable = false,
+ isSelected = false,
+ selectionType,
+ isPublished = false,
+ onSelect,
}: {
message: any;
isAuthor: boolean;
senderEmail: string;
+ isSelectable?: boolean;
+ isSelected?: boolean;
+ selectionType?: "question" | "answer";
+ isPublished?: boolean;
+ onSelect?: (messageId: string, isVisitor: boolean) => void;
}) {
+ const isVisitor = message.viewerId !== null;
+ const canBeSelected =
+ isSelectable &&
+ ((isVisitor && !isAuthor) || // Visitor questions
+ (!isVisitor && isAuthor)); // Admin answers
+
return (
- <div
- className={`flex w-max max-w-[80%] flex-col rounded-lg px-4 py-2 ${
- isAuthor ? "ml-auto bg-primary text-primary-foreground" : "bg-muted"
- }`}
- >
- <p className="text-sm">{message.content}</p>
- <div className="mt-1 text-xs opacity-70">
- {isAuthor ? "You" : message.userId ? "Admin" : senderEmail} •{" "}
- {format(new Date(message.createdAt), "MMM d, h:mm a")}
+ <div className="group relative">
+ <div
+ className={`flex w-max max-w-[80%] cursor-pointer flex-col rounded-lg px-4 py-2 transition-all ${
+ isAuthor ? "ml-auto bg-primary text-primary-foreground" : "bg-muted"
+ } ${
+ isSelected
+ ? "ring-2 ring-blue-500 ring-offset-2"
+ : canBeSelected
+ ? "hover:ring-1 hover:ring-gray-300"
+ : ""
+ }`}
+ onClick={() => canBeSelected && onSelect?.(message.id, isVisitor)}
+ >
+ <div className="flex items-start justify-between gap-2">
+ <p className="flex-1 text-sm">{message.content}</p>
+ <div className="mt-0.5 flex items-center gap-1">
+ {isPublished && (
+ <div className="flex items-center text-xs opacity-60">
+ <Check className="mr-1 h-3 w-3" />
+ FAQ
+ </div>
+ )}
+ {canBeSelected && (
+ <div
+ className={`flex items-center text-xs opacity-60 ${
+ isSelected
+ ? "opacity-100"
+ : "opacity-0 group-hover:opacity-60"
+ }`}
+ >
+ {isVisitor ? (
+ <>
+ <HelpCircle className="mr-1 h-3 w-3" />
+ {isSelected ? "Question" : "Q"}
+ </>
+ ) : (
+ <>
+ <MessageSquareReply className="mr-1 h-3 w-3" />
+ {isSelected ? "Answer" : "A"}
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ <div className="mt-1 text-xs opacity-70">
+ {isAuthor ? "You" : message.userId ? "Admin" : senderEmail} •{" "}
+ {format(new Date(message.createdAt), "MMM d, h:mm a")}
+ </div>
</div>
</div>
);
diff --git a/ee/features/conversations/components/viewer/conversation-view-sidebar.tsx b/ee/features/conversations/components/viewer/conversation-view-sidebar.tsx
index 656101ab..a997a790 100644
--- a/ee/features/conversations/components/viewer/conversation-view-sidebar.tsx
+++ b/ee/features/conversations/components/viewer/conversation-view-sidebar.tsx
@@ -4,6 +4,7 @@ import { useState } from "react";
import { ConversationDocumentContext } from "@/ee/features/conversations/components/shared/conversation-document-context";
import { ConversationMessage } from "@/ee/features/conversations/components/shared/conversation-message";
+import { FAQSection } from "@/ee/features/conversations/components/viewer/faq-section";
import { format } from "date-fns";
import { ArrowLeftIcon, BellIcon, BellOffIcon, Plus } from "lucide-react";
import { toast } from "sonner";
@@ -207,18 +208,26 @@ export function ConversationViewSidebar({
<SheetContent side="right" className="p-0 sm:max-w-md">
<div className="flex h-full flex-col">
{/* Header */}
- <div className="flex items-center justify-between border-b px-4 py-3">
- <h2 className="text-lg font-medium">Conversations</h2>
- </div>
+ {/* <div className="flex items-center justify-between border-b px-4 py-3">
+ <h2 className="text-lg font-medium">Questions</h2>
+ </div> */}
{/* Content */}
- <div className="flex-1 overflow-auto">
+ <div className="flex flex-1 flex-col overflow-hidden">
{isEnabled ? (
<>
+ {/* FAQ Section */}
+ <FAQSection
+ dataroomId={dataroomId}
+ linkId={linkId}
+ documentId={documentId}
+ viewerId={viewerId}
+ />
+
{activeConversation ? (
- <div className="flex h-full flex-col">
+ <div className="flex flex-1 flex-col overflow-hidden">
{/* Conversation Header */}
- <div className="border-b p-4">
+ <div className="flex-shrink-0 border-b p-4">
<div className="flex items-center justify-between">
<div className="flex min-w-0 flex-1 items-center">
<Button
@@ -231,7 +240,7 @@ export function ConversationViewSidebar({
</Button>
<div className="min-w-0">
<h3 className="truncate font-medium">
- {activeConversation.title || "Conversation"}
+ {activeConversation.title || "Question"}
</h3>
</div>
</div>
@@ -324,7 +333,10 @@ export function ConversationViewSidebar({
</ScrollArea>
{/* Message Input */}
- <form onSubmit={handleSendMessage} className="border-t p-3">
+ <form
+ onSubmit={handleSendMessage}
+ className="flex-shrink-0 border-t p-3"
+ >
<div className="flex gap-2">
<input
type="text"
@@ -340,7 +352,7 @@ export function ConversationViewSidebar({
</form>
</div>
) : isNewConversationFormOpen ? (
- <div className="p-4">
+ <div className="flex-1 p-4">
<div className="mb-4 flex items-center">
<Button
variant="ghost"
@@ -350,7 +362,7 @@ export function ConversationViewSidebar({
>
<ArrowLeftIcon className="h-5 w-5" />
</Button>
- <h3 className="font-medium">New Conversation</h3>
+ <h3 className="font-medium">New Question</h3>
</div>
<form
@@ -366,17 +378,11 @@ export function ConversationViewSidebar({
className="space-y-4"
>
<div>
- <label
- htmlFor="message"
- className="mb-1 block text-sm font-medium text-gray-700"
- >
- Your message
- </label>
<textarea
id="message"
value={newMessage}
onChange={(e) => setNewMessage(e.target.value)}
- placeholder="Type your message..."
+ placeholder="Type your question..."
className="min-h-[100px] w-full rounded-md border border-input px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
required
/>
@@ -391,94 +397,95 @@ export function ConversationViewSidebar({
Cancel
</Button>
<Button type="submit" disabled={!newMessage.trim()}>
- Start Conversation
+ Ask Question
</Button>
</div>
</form>
</div>
) : (
- <>
- <div className="p-4">
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <div className="flex-shrink-0 p-4">
<Button
onClick={() => setIsNewConversationFormOpen(true)}
className="w-full"
>
<Plus className="mr-2 h-4 w-4" />
- New Conversation
+ New Question
</Button>
</div>
<Separator />
- <div className="divide-y">
- {isLoading ? (
- <div className="space-y-3 p-4">
- {Array.from({ length: 3 }).map((_, i) => (
- <div key={i} className="flex flex-col gap-2">
- <div className="h-5 w-3/4 animate-pulse bg-muted"></div>
- <div className="h-4 w-1/2 animate-pulse bg-muted"></div>
- <div className="h-10 w-full animate-pulse bg-muted"></div>
- </div>
- ))}
- </div>
- ) : conversations.length === 0 ? (
- <div className="p-4 text-center text-muted-foreground">
- No conversations yet. Start a new one!
- </div>
- ) : (
- conversations.map((conversation) => {
- const lastMessage =
- conversation.messages?.[
- conversation.messages.length - 1
- ];
- const hasUnread = conversation.messages?.some(
- (msg) =>
- !msg.isRead &&
- (msg.userId ||
- msg.viewerId !== conversation.viewerId),
- );
-
- return (
- <div
- key={conversation.id}
- className="cursor-pointer p-4 hover:bg-muted/50"
- onClick={() =>
- setActiveConversation(conversation)
- }
- >
- <div className="mb-1 flex items-center justify-between">
- <h3 className="truncate font-medium">
- {conversation.title ||
- "Untitled conversation"}
- </h3>
- {/* {hasUnread && (
+ <div className="flex-1 overflow-y-auto">
+ <div className="divide-y">
+ {isLoading ? (
+ <div className="space-y-3 p-4">
+ {Array.from({ length: 3 }).map((_, i) => (
+ <div key={i} className="flex flex-col gap-2">
+ <div className="h-5 w-3/4 animate-pulse bg-muted"></div>
+ <div className="h-4 w-1/2 animate-pulse bg-muted"></div>
+ <div className="h-10 w-full animate-pulse bg-muted"></div>
+ </div>
+ ))}
+ </div>
+ ) : conversations.length === 0 ? (
+ <div className="p-4 text-center text-muted-foreground">
+ No questions yet. Ask a new one!
+ </div>
+ ) : (
+ conversations.map((conversation) => {
+ const lastMessage =
+ conversation.messages?.[
+ conversation.messages.length - 1
+ ];
+ const hasUnread = conversation.messages?.some(
+ (msg) =>
+ !msg.isRead &&
+ (msg.userId ||
+ msg.viewerId !== conversation.viewerId),
+ );
+
+ return (
+ <div
+ key={conversation.id}
+ className="cursor-pointer p-4 hover:bg-muted/50"
+ onClick={() =>
+ setActiveConversation(conversation)
+ }
+ >
+ <div className="mb-1 flex items-center justify-between">
+ <h3 className="truncate font-medium">
+ {conversation.title || "Untitled question"}
+ </h3>
+ {/* {hasUnread && (
<span className="ml-2 inline-flex h-5 items-center rounded-full bg-primary px-2 text-xs font-medium text-primary-foreground">
New
</span>
)} */}
- </div>
-
- <div className="mb-2 text-xs text-muted-foreground">
- {format(
- new Date(conversation.updatedAt),
- "MMM d, h:mm a",
+ </div>
+
+ <div className="mb-2 text-xs text-muted-foreground">
+ {format(
+ new Date(conversation.updatedAt),
+ "MMM d, h:mm a",
+ )}
+ </div>
+
+ {lastMessage && (
+ <p className="line-clamp-2 text-sm">
+ {lastMessage.content}
+ </p>
)}
</div>
-
- {lastMessage && (
- <p className="line-clamp-2 text-sm">
- {lastMessage.content}
- </p>
- )}
- </div>
- );
- })
- )}
+ );
+ })
+ )}
+ </div>
</div>
- </>
+ </div>
)}
</>
) : (
<div className="flex h-full items-center justify-center p-4 text-center text-muted-foreground">
- Conversations are disabled for this document.
+ Questions are disabled for this document.
</div>
)}
</div>
diff --git a/ee/features/conversations/components/viewer/faq-section.tsx b/ee/features/conversations/components/viewer/faq-section.tsx
new file mode 100644
index 00000000..302ce6ff
--- /dev/null
+++ b/ee/features/conversations/components/viewer/faq-section.tsx
@@ -0,0 +1,247 @@
+import { useEffect, useRef, useState } from "react";
+
+import useSWR from "swr";
+
+import { fetcher } from "@/lib/utils";
+
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+} from "@/components/ui/accordion";
+import { Badge } from "@/components/ui/badge";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { Separator } from "@/components/ui/separator";
+
+interface FAQ {
+ id: string;
+ editedQuestion: string;
+ answer: string;
+ title?: string;
+ tags: string[];
+ viewCount: number;
+ description?: string;
+ documentPageNumber?: number;
+ documentVersionNumber?: number;
+ createdAt: string;
+}
+
+interface FAQSectionProps {
+ dataroomId?: string;
+ linkId: string;
+ documentId?: string;
+ viewerId?: string;
+}
+
+export function FAQSection({
+ dataroomId,
+ linkId,
+ documentId,
+ viewerId,
+}: FAQSectionProps) {
+ const [viewedFAQs, setViewedFAQs] = useState<Set<string>>(new Set());
+ const [showTopBlur, setShowTopBlur] = useState(false);
+ const [showBottomBlur, setShowBottomBlur] = useState(false);
+ const scrollAreaRef = useRef<HTMLDivElement>(null);
+
+ // Fetch FAQs for this dataroom/link/document
+ const { data: faqs = [], isLoading } = useSWR<FAQ[]>(
+ `/api/faqs?${new URLSearchParams({
+ ...(dataroomId && { dataroomId }),
+ ...(linkId && { linkId }),
+ ...(documentId && { documentId }),
+ }).toString()}`,
+ fetcher,
+ {
+ revalidateOnFocus: false,
+ dedupingInterval: 30000, // 30 seconds
+ keepPreviousData: true,
+ },
+ );
+
+ const handleAccordionChange = async (openItems: string[]) => {
+ // Track views for newly opened items
+ const newlyOpened = openItems.filter((item) => !viewedFAQs.has(item));
+
+ for (const faqId of newlyOpened) {
+ try {
+ const params = new URLSearchParams({
+ ...(dataroomId && { dataroomId }),
+ ...(linkId && { linkId }),
+ });
+
+ await fetch(`/api/faqs/${faqId}?${params.toString()}`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+
+ // Mark as viewed
+ setViewedFAQs((prev) => new Set(prev).add(faqId));
+ } catch (error) {
+ console.error("Error tracking FAQ view:", error);
+ }
+ }
+ };
+
+ // Check scroll position to show/hide blur effects
+ const checkScrollPosition = () => {
+ const scrollElement = scrollAreaRef.current?.querySelector(
+ "[data-radix-scroll-area-viewport]",
+ );
+ if (!scrollElement) return;
+
+ const { scrollTop, scrollHeight, clientHeight } = scrollElement;
+
+ setShowTopBlur(scrollTop > 10);
+ setShowBottomBlur(scrollTop < scrollHeight - clientHeight - 10);
+ };
+
+ // Set up scroll listeners and initial check
+ useEffect(() => {
+ const scrollElement = scrollAreaRef.current?.querySelector(
+ "[data-radix-scroll-area-viewport]",
+ );
+ if (!scrollElement) return;
+
+ // Initial check and delayed check for content that loads after render
+ checkScrollPosition();
+ const timeoutId = setTimeout(checkScrollPosition, 100);
+
+ scrollElement.addEventListener("scroll", checkScrollPosition);
+ return () => {
+ scrollElement.removeEventListener("scroll", checkScrollPosition);
+ clearTimeout(timeoutId);
+ };
+ }, [faqs]);
+
+ if (isLoading) {
+ return (
+ <>
+ <div className="bg-gray-50 p-4 dark:bg-gray-900">
+ <div className="mb-3 flex items-center gap-2">
+ <h3 className="font-medium text-primary">
+ Frequently Asked Questions
+ </h3>
+ <div className="h-5 w-5 animate-pulse rounded bg-muted"></div>
+ </div>
+
+ <div className="space-y-2">
+ {Array.from({ length: 2 }).map((_, i) => (
+ <div
+ key={i}
+ className="rounded-md border border-gray-200 bg-white"
+ >
+ <div className="px-3 py-2.5">
+ <div className="flex w-full items-center justify-between gap-2">
+ <div className="h-5 w-5 animate-pulse rounded bg-muted"></div>
+ <div className="h-5 w-full animate-pulse rounded bg-muted"></div>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ <Separator />
+ </>
+ );
+ }
+
+ if (faqs.length === 0) {
+ return (
+ <>
+ <div className="bg-gray-50 p-4 dark:bg-gray-900">
+ <div className="mb-3 flex items-center gap-2">
+ <h3 className="font-medium text-primary">
+ Frequently Asked Questions
+ </h3>
+ <Badge
+ variant="notification"
+ className="bg-primary/80 text-xs text-primary-foreground"
+ >
+ 0
+ </Badge>
+ </div>
+ <div className="space-y-2 text-sm">No questions published yet.</div>
+ </div>
+ <Separator />
+ </>
+ );
+ }
+
+ return (
+ <>
+ <div className="flex-shrink-0 bg-gray-50 dark:bg-gray-900">
+ <div className="px-4 pb-2 pt-4">
+ <div className="mb-3 flex items-center gap-2">
+ <h3 className="font-medium text-primary">
+ Frequently Asked Questions
+ </h3>
+ <Badge
+ variant="notification"
+ className="bg-primary/80 text-xs text-primary-foreground"
+ >
+ {faqs.length}
+ </Badge>
+ </div>
+ </div>
+
+ <div className="relative px-4">
+ <ScrollArea className="h-fit" ref={scrollAreaRef}>
+ <div className="max-h-80">
+ <Accordion
+ type="multiple"
+ defaultValue={faqs.length > 0 ? [faqs[0].id] : []}
+ onValueChange={handleAccordionChange}
+ className="space-y-2 last:pb-4"
+ >
+ {faqs.map((faq) => (
+ <AccordionItem
+ key={faq.id}
+ value={faq.id}
+ className="rounded-md border border-gray-200 bg-white"
+ >
+ <AccordionTrigger className="px-3 py-2.5 hover:no-underline">
+ <div className="flex w-full items-start justify-between gap-2">
+ <span className="flex-shrink-0 rounded bg-secondary px-1.5 py-0.5 text-xs font-medium text-secondary-foreground">
+ Q
+ </span>
+ <div className="line-clamp-2 min-w-0 flex-1 text-left text-sm font-medium text-gray-900">
+ {faq.editedQuestion}
+ </div>
+ </div>
+ </AccordionTrigger>
+
+ <AccordionContent className="rounded-b-md bg-muted px-3 pb-3 text-foreground">
+ <div className="space-y-2 pt-3">
+ <div className="flex items-start gap-2">
+ <span className="flex-shrink-0 rounded bg-primary/80 px-1.5 py-0.5 text-xs font-medium text-primary-foreground">
+ A
+ </span>
+ <p className="whitespace-pre-wrap text-sm font-medium text-gray-700">
+ {faq.answer}
+ </p>
+ </div>
+ </div>
+ </AccordionContent>
+ </AccordionItem>
+ ))}
+ </Accordion>
+ </div>
+ </ScrollArea>
+
+ {/* Scroll blur indicators */}
+ {showTopBlur && (
+ <div className="pointer-events-none absolute left-4 right-4 top-0 z-10 h-6 bg-gradient-to-b from-gray-50 via-gray-50/80 to-transparent dark:from-gray-900 dark:via-gray-900/80" />
+ )}
+ {showBottomBlur && (
+ <div className="pointer-events-none absolute bottom-0 left-4 right-4 z-10 h-6 bg-gradient-to-t from-gray-50 via-gray-50/80 to-transparent dark:from-gray-900 dark:via-gray-900/80" />
+ )}
+ </div>
+ </div>
+ <Separator />
+ </>
+ );
+}