Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
data-room
Iuliia Shnaie53979dac1a0
diff --git a/components/datarooms/add-dataroom-modal.tsx b/components/datarooms/add-dataroom-modal.tsxindex 831f129a..73bfc0b8 100644--- a/components/datarooms/add-dataroom-modal.tsx+++ b/components/datarooms/add-dataroom-modal.tsx@@ -4,7 +4,22 @@ import { useState } from "react";import { useTeam } from "@/context/team-context";import { PlanEnum } from "@/ee/stripe/constants";-import { XIcon } from "lucide-react";+import {+ Brain,+ BriefcaseIcon,+ BuildingIcon,+ FileTextIcon,+ FolderKanbanIcon,+ FolderIcon,+ HomeIcon,+ LineChartIcon,+ RocketIcon,+ ShoppingCartIcon,+ Sparkles,+ TrendingUpIcon,+ XIcon,+ Zap,+} from "lucide-react";import { toast } from "sonner";import { mutate } from "swr";import { z } from "zod";@@ -37,6 +52,8 @@ import {SelectValue,} from "@/components/ui/select";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { Textarea } from "@/components/ui/textarea";+import { Checkbox } from "@/components/ui/checkbox";import { UpgradePlanModal } from "../billing/upgrade-plan-modal";@@ -55,12 +72,22 @@ export function AddDataroomModal({const [open, setOpen] = useState<boolean>(openModal);const [activeTab, setActiveTab] = useState<string>("create");const [dataroomType, setDataroomType] = useState<string>("");+ const [aiDescription, setAiDescription] = useState<string>("");+ const [aiGenerating, setAiGenerating] = useState<boolean>(false);+ const [generatedFolders, setGeneratedFolders] = useState<any[] | null>(null);+ const [showPreview, setShowPreview] = useState<boolean>(false);+ const [selectedFolderPaths, setSelectedFolderPaths] = useState<Set<string>>(+ new Set(),+ );+ const [editingFolderPath, setEditingFolderPath] = useState<string | null>(null);+ const [editingFolderName, setEditingFolderName] = useState<string>("");const teamInfo = useTeam();const { isFree, isPro } = usePlan();const analytics = useAnalytics();const useTemplate = activeTab === "generate";+ const useAI = activeTab === "ai";const dataroomSchema = z.object({name: z.string().trim().min(3, {@@ -70,7 +97,6 @@ export function AddDataroomModal({});const dataroomSchemaWithType = z.object({- name: z.string().trim().optional(),type: z.enum(["startup-fundraising",@@ -89,14 +115,170 @@ export function AddDataroomModal({),});+ const TEMPLATES = [+ {+ id: "startup-fundraising",+ name: "Startup Fundraising",+ icon: RocketIcon,+ },+ {+ id: "series-a-plus",+ name: "Series A+",+ icon: TrendingUpIcon,+ },+ {+ id: "raising-first-fund",+ name: "Raising a Fund",+ icon: LineChartIcon,+ },+ {+ id: "ma-acquisition",+ name: "M&A / Acquisition",+ icon: BriefcaseIcon,+ },+ {+ id: "sales-dataroom",+ name: "Sales Data Room",+ icon: ShoppingCartIcon,+ },+ {+ id: "real-estate-transaction",+ name: "Real Estate",+ icon: HomeIcon,+ },+ {+ id: "fund-management",+ name: "Fund Management",+ icon: BuildingIcon,+ },+ {+ id: "portfolio-management",+ name: "Portfolio Management",+ icon: FolderKanbanIcon,+ },+ {+ id: "project-management",+ name: "Project Management",+ icon: FileTextIcon,+ },+ ];++ const handleGenerateFolders = async () => {+ if (!aiDescription.trim()) {+ return toast.error("Please describe what kind of dataroom you want to create.");+ }++ setAiGenerating(true);++ try {+ const response = await fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/generate-ai-structure`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ description: aiDescription.trim(),+ }),+ },+ );++ if (!response.ok) {+ const { message } = await response.json();+ setAiGenerating(false);+ toast.error(message || "Failed to generate folder structure");+ return;+ }++ const { name, folders } = await response.json();+ setGeneratedFolders(folders);+ // Set the generated name as default, but allow user to edit it+ if (name) {+ setDataroomName(name);+ }+ // Initialize all folders as selected+ initializeFolderSelection(folders);+ setShowPreview(true);+ setAiGenerating(false);+ } catch (error) {+ setAiGenerating(false);+ toast.error("Error generating folder structure. Please try again.");+ }+ };+const handleSubmit = async (event: any) => {event.preventDefault();event.stopPropagation();+ // For AI generation, if we're in preview mode, create the dataroom+ if (useAI && showPreview && generatedFolders) {+ // Validate dataroom name+ if (!dataroomName.trim()) {+ return toast.error("Please provide a dataroom name.");+ }++ if (dataroomName.trim().length < 3) {+ return toast.error(+ "Please provide a dataroom name with at least 3 characters.",+ );+ }++ // Filter folders based on selection+ const filteredFolders = filterSelectedFolders(generatedFolders);++ if (filteredFolders.length === 0) {+ return toast.error("Please select at least one folder to include.");+ }++ setLoading(true);+ try {+ const response = await fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/generate-ai`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ name: dataroomName.trim(),+ folders: filteredFolders,+ }),+ },+ );++ if (!response.ok) {+ const { message } = await response.json();+ setLoading(false);+ toast.error(message);+ return;+ }++ const { dataroom } = await response.json();++ analytics.capture("Dataroom Generated with AI", {+ dataroomName: dataroomName.trim(),+ });++ mutate(`/api/teams/${teamInfo?.currentTeam?.id}/datarooms`);+ toast.success("Dataroom successfully generated! π");+ router.push(`/datarooms/${dataroom.id}/documents`);+ } catch (error) {+ setLoading(false);+ toast.error("Error creating dataroom. Please try again.");+ return;+ } finally {+ setLoading(false);+ setOpen(false);+ if (openModal && setOpenModal) setOpenModal(false);+ }+ return;+ }+// Validate based on whether template is enabledconst schema = useTemplate ? dataroomSchemaWithType : dataroomSchema;const validation = schema.safeParse({- name: dataroomName,+ name: useTemplate ? undefined : dataroomName,type: useTemplate ? dataroomType : undefined,});@@ -114,8 +296,8 @@ export function AddDataroomModal({const body = useTemplate? {- name: dataroomName.trim() || undefined,type: dataroomType,+ // Name will be taken from template}: { name: dataroomName.trim() };@@ -147,7 +329,7 @@ export function AddDataroomModal({mutate(`/api/teams/${teamInfo?.currentTeam?.id}/datarooms`);toast.success(useTemplate- ? "Dataroom successfully generated! π"+ ? "Dataroom successfully created! π": "Dataroom successfully created! π",);router.push(`/datarooms/${dataroom.id}/documents`);@@ -182,29 +364,269 @@ export function AddDataroomModal({setDataroomName("");setActiveTab("create");setDataroomType("");+ setAiDescription("");+ setGeneratedFolders(null);+ setShowPreview(false);+ setSelectedFolderPaths(new Set());+ setEditingFolderPath(null);+ setEditingFolderName("");} else {setOpen(true);}if (openModal && setOpenModal) setOpenModal(false);};+ // Generate a unique path for each folder+ const generateFolderPath = (folder: any, parentPath: string = ""): string => {+ const currentPath = parentPath ? `${parentPath}/${folder.name}` : folder.name;+ return currentPath;+ };++ // Update folder name in the folder structure+ const updateFolderName = (+ folders: any[],+ targetPath: string,+ newName: string,+ currentPath: string = "",+ ): any[] => {+ return folders.map((folder) => {+ const folderPath = generateFolderPath(folder, currentPath);++ if (folderPath === targetPath) {+ // Update this folder's name+ return { ...folder, name: newName };+ }++ // Recursively update subfolders+ if (folder.subfolders && folder.subfolders.length > 0) {+ return {+ ...folder,+ subfolders: updateFolderName(+ folder.subfolders,+ targetPath,+ newName,+ folderPath,+ ),+ };+ }++ return folder;+ });+ };++ // Handle folder name edit+ const handleFolderNameEdit = (path: string, currentName: string) => {+ setEditingFolderPath(path);+ setEditingFolderName(currentName);+ };++ // Save edited folder name+ const saveFolderName = () => {+ if (!editingFolderPath || !generatedFolders) return;++ if (editingFolderName.trim()) {+ const updatedFolders = updateFolderName(+ generatedFolders,+ editingFolderPath,+ editingFolderName.trim(),+ );+ setGeneratedFolders(updatedFolders);++ // Update selected paths if needed (recalculate paths)+ initializeFolderSelection(updatedFolders);+ }++ setEditingFolderPath(null);+ setEditingFolderName("");+ };++ // Cancel editing+ const cancelFolderNameEdit = () => {+ setEditingFolderPath(null);+ setEditingFolderName("");+ };++ // Toggle folder selection+ const toggleFolderSelection = (path: string, folder: any) => {+ const newSelected = new Set(selectedFolderPaths);++ if (newSelected.has(path)) {+ // If unchecking, remove this folder and all its subfolders+ newSelected.delete(path);+ const removeSubfolders = (f: any, currentPath: string) => {+ if (f.subfolders) {+ f.subfolders.forEach((sub: any) => {+ const subPath = generateFolderPath(sub, currentPath);+ newSelected.delete(subPath);+ removeSubfolders(sub, subPath);+ });+ }+ };+ removeSubfolders(folder, path);+ } else {+ // If checking, add this folder+ newSelected.add(path);+ }++ setSelectedFolderPaths(newSelected);+ };++ // Filter folders based on selection+ const filterSelectedFolders = (folders: any[], parentPath: string = ""): any[] => {+ return folders+ .map((folder) => {+ const currentPath = generateFolderPath(folder, parentPath);+ const isSelected = selectedFolderPaths.has(currentPath);++ if (!isSelected) {+ return null;+ }++ const filteredSubfolders = folder.subfolders+ ? filterSelectedFolders(folder.subfolders, currentPath)+ : undefined;++ return {+ ...folder,+ subfolders: filteredSubfolders && filteredSubfolders.length > 0+ ? filteredSubfolders+ : undefined,+ };+ })+ .filter((folder) => folder !== null);+ };++ // Initialize all folders as selected when preview is shown+ const initializeFolderSelection = (folders: any[], parentPath: string = "") => {+ const paths = new Set<string>();+ const collectPaths = (f: any[], currentPath: string = "") => {+ f.forEach((folder) => {+ const folderPath = generateFolderPath(folder, currentPath);+ paths.add(folderPath);+ if (folder.subfolders) {+ collectPaths(folder.subfolders, folderPath);+ }+ });+ };+ collectPaths(folders);+ setSelectedFolderPaths(paths);+ };++ const renderFolderPreview = (+ folders: any[],+ indent = 0,+ parentPath: string = "",+ ) => {+ return (+ <div className="space-y-1">+ {folders.map((folder, index) => {+ const currentPath = generateFolderPath(folder, parentPath);+ const isSelected = selectedFolderPaths.has(currentPath);++ return (+ <div key={`${parentPath}-${index}`} className="pl-4">+ <div className="flex items-center gap-2 py-1">+ <div+ className="h-4 w-4"+ style={{ marginLeft: `${indent * 16}px` }}+ />+ <Checkbox+ checked={isSelected}+ onCheckedChange={() => toggleFolderSelection(currentPath, folder)}+ id={`folder-${currentPath}`}+ />+ <label+ htmlFor={`folder-${currentPath}`}+ className="flex items-center gap-2 cursor-pointer flex-1"+ >+ <FolderIcon className="h-4 w-4 text-gray-500" />+ {editingFolderPath === currentPath ? (+ <Input+ value={editingFolderName}+ onChange={(e) => setEditingFolderName(e.target.value)}+ onBlur={saveFolderName}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ saveFolderName();+ } else if (e.key === "Escape") {+ e.preventDefault();+ cancelFolderNameEdit();+ }+ }}+ className="h-6 text-sm px-2 py-1"+ autoFocus+ onClick={(e) => e.stopPropagation()}+ />+ ) : (+ <span+ className="text-sm hover:bg-gray-100 dark:hover:bg-gray-800 px-1 py-0.5 rounded cursor-text"+ onClick={(e) => {+ e.stopPropagation();+ handleFolderNameEdit(currentPath, folder.name);+ }}+ title="Click to edit folder name"+ >+ {folder.name}+ </span>+ )}+ </label>+ </div>+ {folder.subfolders && folder.subfolders.length > 0 && (+ <div className="ml-4">+ {renderFolderPreview(folder.subfolders, indent + 1, currentPath)}+ </div>+ )}+ </div>+ );+ })}+ </div>+ );+ };+return (<Dialog open={open} onOpenChange={onOpenChange}><DialogTrigger asChild>{children}</DialogTrigger>- <DialogContent className="border-none bg-transparent text-foreground shadow-none sm:max-w-[500px] [&>button]:hidden">+ <DialogContent className="border-none bg-transparent text-foreground shadow-none sm:max-w-[575px] [&>button]:hidden"><DialogTitle className="sr-only">Create Dataroom</DialogTitle><DialogDescription className="sr-only">Create a new dataroom or generate one with pre-configured folders</DialogDescription>- <Tabs value={activeTab} onValueChange={setActiveTab}>- <TabsList className="grid w-full grid-cols-2">+ <Tabs+ value={activeTab}+ onValueChange={(value) => {+ setActiveTab(value);+ // Reset AI-related state when switching tabs+ if (value !== "ai") {+ setAiDescription("");+ setGeneratedFolders(null);+ setShowPreview(false);+ }+ }}+ >+ <TabsList className="grid w-full grid-cols-3"><TabsTrigger value="create">Create from scratch</TabsTrigger>- <TabsTrigger value="generate">Generate with template</TabsTrigger>+ <TabsTrigger value="generate">Create from template</TabsTrigger>+ <TabsTrigger+ value="ai"+ className={`flex items-center gap-2 ${+ activeTab === "ai"+ ? "text-orange-500 data-[state=active]:text-orange-500"+ : ""+ }`}+ >+ <Sparkles+ className={`h-4 w-4 ${+ activeTab === "ai" ? "text-orange-500" : "text-current"+ }`}+ />+ Generate with AI+ </TabsTrigger></TabsList><TabsContent value="create">- <Card className="relative">+ <Card className="relative outline-none focus:outline-none"><buttononClick={() => onOpenChange(false)}className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"@@ -221,7 +643,7 @@ export function AddDataroomModal({<CardContent className="space-y-2"><formonSubmit={handleSubmit}- className="flex flex-col space-y-4"+ className="flex flex-col space-y-4 outline-none"><div className="space-y-1"><Label htmlFor="dataroom-name-create">@@ -244,7 +666,7 @@ export function AddDataroomModal({</TabsContent><TabsContent value="generate">- <Card className="relative">+ <Card className="relative outline-none focus:outline-none"><buttononClick={() => onOpenChange(false)}className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"@@ -255,75 +677,181 @@ export function AddDataroomModal({<CardHeader className="space-y-3"><CardTitle>Create dataroom</CardTitle><CardDescription>- Generate a dataroom with pre-configured folder structure.+ Create a dataroom with pre-configured folder structure.</CardDescription></CardHeader>- <CardContent className="space-y-2">+ <CardContent className="space-y-4"><formonSubmit={handleSubmit}- className="flex flex-col space-y-4"+ className="flex flex-col space-y-4 outline-none">- <div className="space-y-1">- <Label htmlFor="dataroom-name-generate">- Dataroom Name- </Label>- <Input- id="dataroom-name-generate"- placeholder="Leave empty to use template name"- value={dataroomName}- onChange={(e) => setDataroomName(e.target.value)}- />- </div>- <div className="space-y-1">- <Label htmlFor="dataroom-type">- Dataroom Type{" "}+ <div className="space-y-2">+ <Label>+ Select Template{" "}<span className="text-black dark:text-white">*</span></Label>- <Select- value={dataroomType}- onValueChange={setDataroomType}- >- <SelectTrigger id="dataroom-type">- <SelectValue placeholder="Select a type" />- </SelectTrigger>- <SelectContent>- <SelectItem value="startup-fundraising">- Startup Fundraising (Early stage)- </SelectItem>- <SelectItem value="series-a-plus">- Series A+ Fundraising- </SelectItem>- <SelectItem value="raising-first-fund">- Raising a Fund (GP/LP)- </SelectItem>- <SelectItem value="ma-acquisition">- M&A / Acquisition- </SelectItem>- <SelectItem value="sales-dataroom">- Sales Data Room- </SelectItem>- <SelectItem value="real-estate-transaction">- Real Estate Transaction- </SelectItem>- <SelectItem value="fund-management">- Fund Management (LP reporting)- </SelectItem>- <SelectItem value="portfolio-management">- Portfolio Management- </SelectItem>- <SelectItem value="project-management">- Project Management- </SelectItem>- </SelectContent>- </Select>+ <div className="grid grid-cols-3 divide-x divide-y divide-border overflow-hidden rounded-md border ">+ {TEMPLATES.map((template) => {+ const Icon = template.icon;+ const isSelected = dataroomType === template.id;++ return (+ <button+ key={template.id}+ type="button"+ onClick={() => setDataroomType(template.id)}+ className={`relative flex min-h-[120px] flex-col items-center justify-center space-y-3 overflow-hidden p-4 transition-colors ${+ isSelected+ ? "bg-gray-200 dark:bg-gray-800"+ : "hover:bg-gray-100 hover:dark:bg-gray-800"+ }`}+ >+ <Icon className="pointer-events-none h-auto w-10 text-foreground" />+ <p className="text-sm">{template.name}</p>+ </button>+ );+ })}+ </div></div>- <Button type="submit" className="w-full" loading={loading}>- Generate new dataroom+ <Button+ type="submit"+ className="w-full"+ loading={loading}+ disabled={!dataroomType}+ >+ Create new dataroom</Button></form></CardContent></Card></TabsContent>++ <TabsContent value="ai">+ <Card className="relative outline-none focus:outline-none">+ <button+ onClick={() => onOpenChange(false)}+ className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"+ >+ <XIcon className="h-4 w-4" />+ <span className="sr-only">Close</span>+ </button>+ <CardHeader className="space-y-3">+ <CardTitle>Generate dataroom with AI</CardTitle>+ <CardDescription>+ AI will create a unique and proven data room structure for your use case.+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-4">+ {!showPreview ? (+ <>+ <div className="space-y-1">+ <Label htmlFor="ai-description">+ Describe your dataroom in details{" "}+ <span className="text-black dark:text-white">*</span>+ </Label>+ <Textarea+ id="ai-description"+ placeholder="A data room for a Series B fundraising round for a AI startup called 'Acme AI'. Create advanced data room with IP information and financials."+ value={aiDescription}+ onChange={(e) => setAiDescription(e.target.value)}+ rows={4}+ className="resize-none"+ />+ </div>+ <Button+ type="button"+ className="w-full"+ loading={aiGenerating}+ onClick={handleGenerateFolders}+ disabled={!aiDescription.trim() || aiGenerating}+ >+ Generate data room structure+ </Button>+ </>+ ) : (+ <form+ onSubmit={handleSubmit}+ className="flex flex-col space-y-4 outline-none"+ >+ <div className="space-y-1">+ <Label htmlFor="dataroom-name-ai">+ Dataroom Name{" "}+ <span className="text-black dark:text-white">*</span>+ </Label>+ <Input+ id="dataroom-name-ai"+ placeholder="AI Generated Data Room"+ value={dataroomName}+ onChange={(e) => setDataroomName(e.target.value)}+ required+ />+ </div>+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <Label>+ Generated Folder Structure{" "}+ <span className="text-xs text-muted-foreground font-normal">+ (Select folders to include)+ </span>+ </Label>+ <div className="flex items-center gap-2 text-xs text-muted-foreground">+ <Checkbox+ checked={+ generatedFolders &&+ selectedFolderPaths.size > 0 &&+ generatedFolders.every((folder) => {+ const path = generateFolderPath(folder);+ return selectedFolderPaths.has(path);+ })+ ? true+ : false+ }+ onCheckedChange={(checked) => {+ if (checked && generatedFolders) {+ initializeFolderSelection(generatedFolders);+ } else {+ setSelectedFolderPaths(new Set());+ }+ }}+ id="select-all"+ />+ <label+ htmlFor="select-all"+ className="cursor-pointer"+ >+ Select/Deselect All+ </label>+ </div>+ </div>+ <div className="max-h-96 overflow-y-auto rounded-md border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900">+ {generatedFolders && renderFolderPreview(generatedFolders)}+ </div>+ </div>+ <div className="flex gap-2">+ <Button+ type="button"+ variant="outline"+ className="flex-1"+ onClick={() => {+ setShowPreview(false);+ setGeneratedFolders(null);+ }}+ >+ Back+ </Button>+ <Button+ type="submit"+ className="flex-1"+ loading={loading}+ >+ Create Dataroom+ </Button>+ </div>+ </form>+ )}+ </CardContent>+ </Card>+ </TabsContent></Tabs></DialogContent></Dialog>diff --git a/components/welcome/dataroom-ai-generate.tsx b/components/welcome/dataroom-ai-generate.tsxnew file mode 100644index 00000000..d292cc24--- /dev/null+++ b/components/welcome/dataroom-ai-generate.tsx@@ -0,0 +1,470 @@+import { useRouter } from "next/router";+import { useState } from "react";++import { useTeam } from "@/context/team-context";+import { FolderIcon, Sparkles } from "lucide-react";+import { motion } from "motion/react";+import { toast } from "sonner";+import { mutate } from "swr";++import { useAnalytics } from "@/lib/analytics";+import { STAGGER_CHILD_VARIANTS } from "@/lib/constants";++import { Button } from "../ui/button";+import { Checkbox } from "../ui/checkbox";+import { Input } from "../ui/input";+import { Label } from "../ui/label";+import { Textarea } from "../ui/textarea";++export default function DataroomAIGenerate() {+ const router = useRouter();+ const teamInfo = useTeam();+ const analytics = useAnalytics();++ const [aiDescription, setAiDescription] = useState<string>("");+ const [aiGenerating, setAiGenerating] = useState<boolean>(false);+ const [generatedFolders, setGeneratedFolders] = useState<any[] | null>(null);+ const [showPreview, setShowPreview] = useState<boolean>(false);+ const [dataroomName, setDataroomName] = useState<string>("");+ const [loading, setLoading] = useState<boolean>(false);+ const [selectedFolderPaths, setSelectedFolderPaths] = useState<Set<string>>(+ new Set(),+ );+ const [editingFolderPath, setEditingFolderPath] = useState<string | null>(null);+ const [editingFolderName, setEditingFolderName] = useState<string>("");++ // Generate a unique path for each folder+ const generateFolderPath = (folder: any, parentPath: string = ""): string => {+ const currentPath = parentPath ? `${parentPath}/${folder.name}` : folder.name;+ return currentPath;+ };++ // Initialize all folders as selected when preview is shown+ const initializeFolderSelection = (folders: any[], parentPath: string = "") => {+ const paths = new Set<string>();+ const collectPaths = (f: any[], currentPath: string = "") => {+ f.forEach((folder) => {+ const folderPath = generateFolderPath(folder, currentPath);+ paths.add(folderPath);+ if (folder.subfolders) {+ collectPaths(folder.subfolders, folderPath);+ }+ });+ };+ collectPaths(folders);+ setSelectedFolderPaths(paths);+ };++ // Toggle folder selection+ const toggleFolderSelection = (path: string, folder: any) => {+ const newSelected = new Set(selectedFolderPaths);++ if (newSelected.has(path)) {+ newSelected.delete(path);+ const removeSubfolders = (f: any, currentPath: string) => {+ if (f.subfolders) {+ f.subfolders.forEach((sub: any) => {+ const subPath = generateFolderPath(sub, currentPath);+ newSelected.delete(subPath);+ removeSubfolders(sub, subPath);+ });+ }+ };+ removeSubfolders(folder, path);+ } else {+ newSelected.add(path);+ }++ setSelectedFolderPaths(newSelected);+ };++ // Filter folders based on selection+ const filterSelectedFolders = (folders: any[], parentPath: string = ""): any[] => {+ return folders+ .map((folder) => {+ const currentPath = generateFolderPath(folder, parentPath);+ const isSelected = selectedFolderPaths.has(currentPath);++ if (!isSelected) {+ return null;+ }++ const filteredSubfolders = folder.subfolders+ ? filterSelectedFolders(folder.subfolders, currentPath)+ : undefined;++ return {+ ...folder,+ subfolders: filteredSubfolders && filteredSubfolders.length > 0+ ? filteredSubfolders+ : undefined,+ };+ })+ .filter((folder) => folder !== null);+ };++ // Update folder name in the folder structure+ const updateFolderName = (+ folders: any[],+ targetPath: string,+ newName: string,+ currentPath: string = "",+ ): any[] => {+ return folders.map((folder) => {+ const folderPath = generateFolderPath(folder, currentPath);++ if (folderPath === targetPath) {+ return { ...folder, name: newName };+ }++ if (folder.subfolders && folder.subfolders.length > 0) {+ return {+ ...folder,+ subfolders: updateFolderName(+ folder.subfolders,+ targetPath,+ newName,+ folderPath,+ ),+ };+ }++ return folder;+ });+ };++ // Handle folder name edit+ const handleFolderNameEdit = (path: string, currentName: string) => {+ setEditingFolderPath(path);+ setEditingFolderName(currentName);+ };++ // Save edited folder name+ const saveFolderName = () => {+ if (!editingFolderPath || !generatedFolders) return;++ if (editingFolderName.trim()) {+ const updatedFolders = updateFolderName(+ generatedFolders,+ editingFolderPath,+ editingFolderName.trim(),+ );+ setGeneratedFolders(updatedFolders);+ initializeFolderSelection(updatedFolders);+ }++ setEditingFolderPath(null);+ setEditingFolderName("");+ };++ // Cancel editing+ const cancelFolderNameEdit = () => {+ setEditingFolderPath(null);+ setEditingFolderName("");+ };++ const handleGenerateFolders = async () => {+ if (!aiDescription.trim()) {+ return toast.error("Please describe what kind of dataroom you want to create.");+ }++ setAiGenerating(true);++ try {+ const response = await fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/generate-ai-structure`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ description: aiDescription.trim(),+ }),+ },+ );++ if (!response.ok) {+ const { message } = await response.json();+ setAiGenerating(false);+ toast.error(message || "Failed to generate folder structure");+ return;+ }++ const { name, folders } = await response.json();+ setGeneratedFolders(folders);+ if (name) {+ setDataroomName(name);+ }+ initializeFolderSelection(folders);+ setShowPreview(true);+ setAiGenerating(false);+ } catch (error) {+ setAiGenerating(false);+ toast.error("Error generating folder structure. Please try again.");+ }+ };++ const handleCreateDataroom = async () => {+ if (!dataroomName.trim()) {+ return toast.error("Please provide a dataroom name.");+ }++ if (dataroomName.trim().length < 3) {+ return toast.error(+ "Please provide a dataroom name with at least 3 characters.",+ );+ }++ if (!generatedFolders) return;++ if (!teamInfo?.currentTeam?.id) {+ return toast.error("Team not found. Please refresh the page and try again.");+ }++ const filteredFolders = filterSelectedFolders(generatedFolders);++ if (filteredFolders.length === 0) {+ return toast.error("Please select at least one folder to include.");+ }++ setLoading(true);+ try {+ const response = await fetch(+ `/api/teams/${teamInfo.currentTeam.id}/datarooms/generate-ai`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ name: dataroomName.trim(),+ folders: filteredFolders,+ }),+ },+ );++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ const errorMessage = errorData.message || errorData.error || "Error creating dataroom. Please try again.";+ setLoading(false);+ toast.error(errorMessage);+ return;+ }++ const { dataroom } = await response.json();++ analytics.capture("Dataroom Generated with AI", {+ dataroomName: dataroomName.trim(),+ });++ mutate(`/api/teams/${teamInfo?.currentTeam?.id}/datarooms`);+ toast.success("Dataroom successfully generated! π");+ router.push(`/datarooms/${dataroom.id}/documents`);+ } catch (error) {+ setLoading(false);+ toast.error("Error creating dataroom. Please try again.");+ }+ };++ const renderFolderPreview = (+ folders: any[],+ indent = 0,+ parentPath: string = "",+ ) => {+ return (+ <div className="space-y-1">+ {folders.map((folder, index) => {+ const currentPath = generateFolderPath(folder, parentPath);+ const isSelected = selectedFolderPaths.has(currentPath);++ return (+ <div key={`${parentPath}-${index}`} className="pl-4">+ <div className="flex items-center gap-2 py-1">+ <div+ className="h-4 w-4"+ style={{ marginLeft: `${indent * 16}px` }}+ />+ <Checkbox+ checked={isSelected}+ onCheckedChange={() => toggleFolderSelection(currentPath, folder)}+ id={`folder-${currentPath}`}+ />+ <label+ htmlFor={`folder-${currentPath}`}+ className="flex items-center gap-2 cursor-pointer flex-1"+ >+ <FolderIcon className="h-4 w-4 text-gray-500" />+ {editingFolderPath === currentPath ? (+ <Input+ value={editingFolderName}+ onChange={(e) => setEditingFolderName(e.target.value)}+ onBlur={saveFolderName}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ saveFolderName();+ } else if (e.key === "Escape") {+ e.preventDefault();+ cancelFolderNameEdit();+ }+ }}+ className="h-6 text-sm px-2 py-1"+ autoFocus+ onClick={(e) => e.stopPropagation()}+ />+ ) : (+ <span+ className="text-sm hover:bg-gray-100 dark:hover:bg-gray-800 px-1 py-0.5 rounded cursor-text"+ onClick={(e) => {+ e.stopPropagation();+ handleFolderNameEdit(currentPath, folder.name);+ }}+ title="Click to edit folder name"+ >+ {folder.name}+ </span>+ )}+ </label>+ </div>+ {folder.subfolders && folder.subfolders.length > 0 && (+ <div className="ml-4">+ {renderFolderPreview(folder.subfolders, indent + 1, currentPath)}+ </div>+ )}+ </div>+ );+ })}+ </div>+ );+ };++ return (+ <motion.div+ className="z-10 flex flex-col space-y-10 text-center"+ variants={{+ hidden: { opacity: 0, scale: 0.95 },+ show: {+ opacity: 1,+ scale: 1,+ transition: {+ staggerChildren: 0.2,+ },+ },+ }}+ initial="hidden"+ animate="show"+ exit="hidden"+ transition={{ duration: 0.3, type: "spring" }}+ >+ <motion.div+ variants={STAGGER_CHILD_VARIANTS}+ className="flex flex-col items-center space-y-10 text-center"+ >+ <h1 className="font-display text-balance text-3xl font-semibold text-foreground transition-colors sm:text-4xl">+ Generate dataroom with AI+ </h1>++ </motion.div>++ <motion.div variants={STAGGER_CHILD_VARIANTS}>+ <main className="mx-auto mt-8 max-w-md w-full px-4 sm:px-0">+ <div className="space-y-6">+ {!showPreview ? (+ <>+ <div className="space-y-2 text-left">+ <Label htmlFor="ai-description" className="text-base">+ Describe your dataroom in details{" "}+ <span className="text-black dark:text-white">*</span>+ </Label>+ <Textarea+ id="ai-description"+ placeholder="A data room for a Series B fundraising round for a AI startup called 'Acme AI'. Create advanced data room with IP information and financials."+ value={aiDescription}+ onChange={(e) => setAiDescription(e.target.value)}+ rows={4}+ className="resize-none"+ />+ </div>+ <Button+ onClick={handleGenerateFolders}+ loading={aiGenerating}+ disabled={!aiDescription.trim() || aiGenerating}+ className="w-full"+ size="lg"+ >+ Generate data room structure+ </Button>+ </>+ ) : (+ <>+ <div className="space-y-2 text-left">+ <Label htmlFor="dataroom-name-ai" className="text-base">+ Dataroom Name{" "}+ <span className="text-black dark:text-white">*</span>+ </Label>+ <Input+ id="dataroom-name-ai"+ placeholder="AI Generated Data Room"+ value={dataroomName}+ onChange={(e) => setDataroomName(e.target.value)}+ required+ className="text-base"+ />+ </div>+ <div className="space-y-2 text-left">+ <Label className="text-base">+ Generated Folder Structure{" "}+ <span className="text-xs text-muted-foreground font-normal">+ (Select folders to include)+ </span>+ </Label>+ <div className="flex items-center gap-2 text-xs text-muted-foreground">+ <Checkbox+ checked={+ generatedFolders &&+ selectedFolderPaths.size > 0 &&+ generatedFolders.every((folder) => {+ const path = generateFolderPath(folder);+ return selectedFolderPaths.has(path);+ })+ ? true+ : false+ }+ onCheckedChange={(checked) => {+ if (checked && generatedFolders) {+ initializeFolderSelection(generatedFolders);+ } else {+ setSelectedFolderPaths(new Set());+ }+ }}+ id="select-all"+ />+ <label+ htmlFor="select-all"+ className="cursor-pointer"+ >+ Select/Deselect All+ </label>+ </div>+ <div className="max-h-96 overflow-y-auto rounded-md border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900">+ {generatedFolders && renderFolderPreview(generatedFolders)}+ </div>+ </div>+ <Button+ onClick={handleCreateDataroom}+ loading={loading}+ className="w-full"+ size="lg"+ >+ Create Dataroom+ </Button>+ </>+ )}+ </div>+ </main>+ </motion.div>+ </motion.div>+ );+}+diff --git a/components/welcome/dataroom-choice.tsx b/components/welcome/dataroom-choice.tsxindex 60410ac9..15883837 100644--- a/components/welcome/dataroom-choice.tsx+++ b/components/welcome/dataroom-choice.tsx@@ -1,6 +1,6 @@import { useRouter } from "next/router";-import { FolderIcon, SparklesIcon } from "lucide-react";+import { FileTextIcon, FolderIcon, Sparkles } from "lucide-react";import { motion } from "motion/react";import { STAGGER_CHILD_VARIANTS } from "@/lib/constants";@@ -38,7 +38,7 @@ export default function DataroomChoice({ dataroomId }: { dataroomId: string }) {</motion.div><motion.divvariants={STAGGER_CHILD_VARIANTS}- className="grid w-full max-w-2xl grid-cols-1 divide-y divide-border rounded-md border border-border text-foreground md:grid-cols-2 md:divide-x"+ className="grid w-full max-w-3xl grid-cols-1 divide-y divide-border rounded-md border border-border text-foreground md:grid-cols-3 md:divide-x md:divide-y-0"><buttononClick={() =>@@ -70,12 +70,32 @@ export default function DataroomChoice({ dataroomId }: { dataroomId: string }) {}className="flex min-h-[200px] flex-col items-center justify-center space-y-5 overflow-hidden p-5 transition-colors hover:bg-gray-200 hover:dark:bg-gray-800 md:p-10">- <SparklesIcon className="pointer-events-none h-auto w-12 sm:w-12" />+ <FileTextIcon className="pointer-events-none h-auto w-12 sm:w-12" /><p className="text-lg font-medium">Use a Template</p><p className="text-sm text-muted-foreground">Start with pre-configured folders for your use case</p></button>+ <button+ onClick={() =>+ router.push({+ pathname: "/welcome",+ query: {+ type: "dataroom-ai-generate",+ dataroomId,+ },+ })+ }+ className="flex min-h-[200px] flex-col items-center justify-center space-y-5 overflow-hidden p-5 transition-colors hover:bg-orange-50 hover:dark:bg-orange-900/20 md:p-10"+ >+ <Sparkles className="pointer-events-none h-auto w-12 sm:w-12 text-orange-500" />+ <p className="text-lg font-medium text-orange-600 dark:text-orange-400">+ Generate with AI+ </p>+ <p className="text-sm text-muted-foreground">+ Let AI create a unique data room structure+ </p>+ </button></motion.div></motion.div>);diff --git a/ee/features/templates/components/dataroom-templates.tsx b/ee/features/templates/components/dataroom-templates.tsxindex b5927a5a..407dc36c 100644--- a/ee/features/templates/components/dataroom-templates.tsx+++ b/ee/features/templates/components/dataroom-templates.tsx@@ -173,7 +173,7 @@ export default function DataroomTemplates({Papermark</p><h1 className="font-display max-w-md text-3xl font-semibold transition-colors sm:text-4xl">- Which template do you want to use?+ Select a template to get started</h1></motion.div>diff --git a/pages/api/teams/[teamId]/datarooms/generate-ai-structure.ts b/pages/api/teams/[teamId]/datarooms/generate-ai-structure.tsnew file mode 100644index 00000000..60aaf884--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/generate-ai-structure.ts@@ -0,0 +1,153 @@+import type { NextApiRequest, NextApiResponse } from "next";++import { getServerSession } from "next-auth/next";++import { openai } from "@/lib/openai";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";++import { authOptions } from "../../../auth/[...nextauth]";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "POST") {+ // POST /api/teams/:teamId/datarooms/generate-ai-structure+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ res.status(401).end("Unauthorized");+ return;+ }++ const userId = (session.user as CustomUser).id;+ const { teamId } = req.query as { teamId: string };+ const { description } = req.body as { description: string };++ if (!description || typeof description !== "string" || description.trim().length === 0) {+ return res.status(400).json({+ message: "Description is required",+ });+ }++ // Validate description length and content+ if (description.length > 2000) {+ return res.status(400).json({+ message: "Description is too long. Please keep it under 2000 characters.",+ });+ }++ try {+ // Check if the user is part of the team+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId: userId,+ },+ },+ },+ });++ if (!team) {+ return res.status(401).end("Unauthorized");+ }++ // Use GPT to generate folder structure+ const systemPrompt = `Prompt`;++ const completion = await openai.chat.completions.create({+ model: "gpt-4o-mini",+ messages: [+ { role: "system", content: systemPrompt },+ {+ role: "user",+ content: `Analyze this description carefully and create a highly tailored, specific data room folder structure that perfectly matches this exact use case:++"${description.trim()}"++Generate a folder structure that is:+- Specifically designed for this exact scenario+- Includes all relevant document types for this specific transaction/use case+- Uses industry-appropriate naming conventions+- Organized logically for this particular purpose++Also suggest an appropriate, professional name for this data room.`,+ },+ ],+ temperature: 0.7,+ max_tokens: 3000,+ response_format: { type: "json_object" },+ });++ const responseContent = completion.choices[0]?.message?.content;+ if (!responseContent) {+ return res.status(500).json({+ message: "Failed to generate folder structure",+ });+ }++ // Parse the JSON response+ let parsedResponse;+ try {+ parsedResponse = JSON.parse(responseContent);+ } catch (parseError) {+ return res.status(500).json({+ message: "Invalid response format from AI",+ });+ }++ // Extract name and folders+ const suggestedName = parsedResponse.name;+ const folders = parsedResponse.folders;++ if (!suggestedName || typeof suggestedName !== "string") {+ return res.status(500).json({+ message: "Invalid response: name is missing or invalid",+ });+ }++ if (!Array.isArray(folders)) {+ return res.status(500).json({+ message: "Invalid folder structure format",+ });+ }++ // Validate folder structure+ const validateFolder = (folder: any, depth = 0): boolean => {+ if (depth > 5) return false; // Max depth+ if (!folder.name || typeof folder.name !== "string") return false;+ if (folder.name.length > 255) return false;+ if (folder.subfolders) {+ if (!Array.isArray(folder.subfolders)) return false;+ return folder.subfolders.every((sub: any) => validateFolder(sub, depth + 1));+ }+ return true;+ };++ if (!folders.every((folder) => validateFolder(folder))) {+ return res.status(500).json({+ message: "Generated folder structure is invalid",+ });+ }++ res.status(200).json({+ name: suggestedName.trim(),+ folders: folders,+ message: "Folder structure generated successfully",+ });+ } catch (error) {+ console.error("Error generating AI folder structure:", error);+ return res.status(500).json({+ message: "Error generating folder structure",+ error: error instanceof Error ? error.message : "Unknown error",+ });+ }+ } else {+ // We only allow POST requests+ res.setHeader("Allow", ["POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}+diff --git a/pages/api/teams/[teamId]/datarooms/generate-ai.ts b/pages/api/teams/[teamId]/datarooms/generate-ai.tsnew file mode 100644index 00000000..193e60e7--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/generate-ai.ts@@ -0,0 +1,203 @@+import type { NextApiRequest, NextApiResponse } from "next";++import { FolderTemplate } from "@/ee/features/templates/constants/dataroom-templates";+import { getLimits } from "@/ee/limits/server";+import { authOptions } from "@/pages/api/auth/[...nextauth]";+import slugify from "@sindresorhus/slugify";+import { getServerSession } from "next-auth/next";++import { newId } from "@/lib/id-helper";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "POST") {+ // POST /api/teams/:teamId/datarooms/generate-ai+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ res.status(401).end("Unauthorized");+ return;+ }++ const userId = (session.user as CustomUser).id;+ const { teamId } = req.query as { teamId: string };+ const { name, folders } = req.body as {+ name: string;+ folders: FolderTemplate[];+ };++ // Validate input+ if (!name || typeof name !== "string" || name.trim().length === 0) {+ return res.status(400).json({+ message: "Dataroom name is required",+ });+ }++ if (name.length > 255) {+ return res.status(400).json({+ message: "Dataroom name is too long",+ });+ }++ if (!Array.isArray(folders) || folders.length === 0) {+ return res.status(400).json({+ message: "Folder structure is required",+ });+ }++ // Validate folder structure+ const validateFolder = (folder: any, depth = 0): boolean => {+ if (depth > 5) return false;+ if (!folder.name || typeof folder.name !== "string") return false;+ if (folder.name.length > 255) return false;+ if (folder.subfolders) {+ if (!Array.isArray(folder.subfolders)) return false;+ return folder.subfolders.every((sub: any) => validateFolder(sub, depth + 1));+ }+ return true;+ };++ if (!folders.every((folder) => validateFolder(folder))) {+ return res.status(400).json({+ message: "Invalid folder structure",+ });+ }++ try {+ // Check if the user is part of the team (without plan restriction first)+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId: userId,+ },+ },+ },+ select: {+ id: true,+ plan: true,+ },+ });++ if (!team) {+ return res.status(401).end("Unauthorized");+ }++ // Check if team has access to datarooms (allow trial plans, paid plans, and free plan for onboarding)+ const allowedPlans = [+ "business",+ "datarooms",+ "datarooms-plus",+ "business+old",+ "datarooms+old",+ "datarooms-plus+old",+ "datarooms+drtrial",+ "business+drtrial",+ "datarooms-plus+drtrial",+ "free+drtrial",+ ];++ // Allow free plan (for onboarding) or any plan that includes allowed plans or drtrial+ const hasAccess =+ team.plan === "free" || // Allow free plan during onboarding+ team.plan.includes("drtrial") || // Allow any trial plan+ allowedPlans.some((plan) => team.plan.includes(plan));++ if (!hasAccess) {+ return res.status(403).json({+ message: "This feature requires a datarooms plan. Please upgrade to access AI-generated data rooms.",+ });+ }++ // Limits: Check if the user has reached the limit of datarooms in the team+ const dataroomCount = await prisma.dataroom.count({+ where: {+ teamId: teamId,+ },+ });++ const limits = await getLimits({ teamId, userId });++ // Allow first dataroom creation on free plan during onboarding+ const isFreePlan = team.plan === "free" || team.plan === "free+drtrial";+ const isFirstDataroom = dataroomCount === 0;++ if (limits && !(isFreePlan && isFirstDataroom) && dataroomCount >= limits.datarooms) {+ return res+ .status(403)+ .json({ message: "You have reached the limit of datarooms" });+ }++ const pId = newId("dataroom");+ const dataroomName = name.trim();++ // Create the dataroom and folders in a transaction to prevent hanging results+ const dataroom = await prisma.$transaction(async (tx) => {+ // Create the dataroom+ const createdDataroom = await tx.dataroom.create({+ data: {+ name: dataroomName,+ teamId: teamId,+ pId: pId,+ },+ });++ // Helper function to create folders recursively+ const createFolders = async (+ folders: FolderTemplate[],+ parentPath: string = "",+ parentId: string | null = null,+ ): Promise<void> => {+ for (const folder of folders) {+ const folderPath = parentPath + "/" + slugify(folder.name);++ // Create the folder+ const createdFolder = await tx.dataroomFolder.create({+ data: {+ name: folder.name,+ path: folderPath,+ parentId: parentId,+ dataroomId: createdDataroom.id,+ },+ });++ // If the folder has subfolders, create them recursively+ if (folder.subfolders && folder.subfolders.length > 0) {+ await createFolders(+ folder.subfolders,+ folderPath,+ createdFolder.id,+ );+ }+ }+ };++ await createFolders(folders);++ return createdDataroom;+ });++ const dataroomWithCount = {+ ...dataroom,+ _count: { documents: 0 },+ };++ res.status(201).json({+ dataroom: dataroomWithCount,+ message: "Dataroom generated successfully with AI",+ });+ } catch (error) {+ console.error("Error generating dataroom with AI:", error);+ return res.status(500).json({ error: "Error generating dataroom" });+ }+ } else {+ // We only allow POST requests+ res.setHeader("Allow", ["POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}+diff --git a/pages/api/views/[viewId]/nda-certificate.ts b/pages/api/views/[viewId]/nda-certificate.tsnew file mode 100644index 00000000..a43ce5ae--- /dev/null+++ b/pages/api/views/[viewId]/nda-certificate.ts@@ -0,0 +1,691 @@+import { NextApiRequest, NextApiResponse } from "next";++import { PDFDocument, StandardFonts, rgb } from "pdf-lib";+import { format } from "date-fns";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth/next";++import { errorhandler } from "@/lib/errorHandler";+import { getFile } from "@/lib/files/get-file";+import { getViewUserAgent, getViewUserAgent_v2 } from "@/lib/tinybird/pipes";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";+import { log } from "@/lib/utils";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "GET") {+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }++ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const { viewId } = req.query as {+ viewId: string;+ };+ const userId = (session.user as CustomUser).id;++ try {+ // Fetch the view with agreement response and related data+ // IMPORTANT: We use the agreement from agreementResponse to ensure we get+ // the agreement that was actually agreed to, not the current link's agreement+ // (which may have been changed after the user agreed)+ const view = await prisma.view.findUnique({+ where: { id: viewId },+ include: {+ agreementResponse: {+ include: {+ agreement: {+ select: {+ id: true,+ name: true,+ content: true,+ contentType: true,+ updatedAt: true, // Track when agreement was last updated+ },+ },+ },+ },+ team: {+ select: {+ id: true,+ name: true,+ users: {+ where: {+ userId: userId,+ },+ select: {+ userId: true,+ },+ },+ },+ },+ },+ });++ if (!view) {+ return res.status(404).json({ error: "View not found" });+ }++ // Check if user has access to this team+ if (!view.team || !view.team.users.some((u) => u.userId === userId)) {+ return res.status(403).json({ error: "Unauthorized" });+ }++ // Check if agreement response exists+ if (!view.agreementResponse) {+ return res.status(400).json({ error: "No agreement response found" });+ }++ // IMPORTANT: Verify that the agreement hasn't been modified after the user agreed to it+ // If the agreement was updated after the response was created, we should warn or handle it+ // NOTE: This is a known limitation - if an Agreement is updated after users agree to it,+ // the certificate will show the current agreement content, not the original.+ // A proper fix would require storing a snapshot of agreement data in AgreementResponse.+ const agreementUpdatedAfterResponse =+ view.agreementResponse.agreement.updatedAt > view.agreementResponse.createdAt;++ if (agreementUpdatedAfterResponse) {+ // Log that the agreement was modified after the user agreed+ // The certificate will use the current agreement content, which may differ from what was agreed to+ log({+ message: `Agreement ${view.agreementResponse.agreement.id} was updated after user agreed to it (viewId: ${viewId}). Certificate shows current agreement version, not original.`,+ type: "error",+ });+ }++ // Fetch user agent data for location, device, browser, OS+ // This is optional - if it fails, we'll use defaults+ let userAgentData: {+ browser?: string;+ os?: string;+ device?: string;+ country?: string;+ city?: string;+ } = {+ browser: "Unknown",+ os: "Unknown",+ device: "Unknown",+ country: "Unknown",+ city: "Unknown",+ };++ try {+ const userAgent = await getViewUserAgent({ viewId: viewId });+ if (userAgent && (userAgent.rows ?? 0) > 0 && userAgent.data && userAgent.data[0]) {+ userAgentData = {+ browser: userAgent.data[0].browser || "Unknown",+ os: userAgent.data[0].os || "Unknown",+ device: userAgent.data[0].device || "Unknown",+ country: userAgent.data[0].country || "Unknown",+ city: userAgent.data[0].city || "Unknown",+ };+ } else if (view.documentId) {+ // Try v2 if v3 doesn't have data and we have a documentId+ try {+ const userAgentV2 = await getViewUserAgent_v2({+ documentId: view.documentId,+ viewId: viewId,+ since: 0,+ });+ if (userAgentV2 && (userAgentV2.rows ?? 0) > 0 && userAgentV2.data && userAgentV2.data[0]) {+ userAgentData = {+ browser: userAgentV2.data[0].browser || "Unknown",+ os: userAgentV2.data[0].os || "Unknown",+ device: userAgentV2.data[0].device || "Unknown",+ country: userAgentV2.data[0].country || "Unknown",+ city: userAgentV2.data[0].city || "Unknown",+ };+ }+ } catch (v2Error) {+ // Silently fail v2 attempt+ }+ }+ } catch (error) {+ // If user agent fetch fails, continue with defaults+ // This should not break certificate generation+ }++ // Format location data+ const locationText =+ userAgentData.city && userAgentData.city !== "Unknown" && userAgentData.country && userAgentData.country !== "Unknown"+ ? `${userAgentData.city}, ${userAgentData.country}`+ : userAgentData.country && userAgentData.country !== "Unknown"+ ? userAgentData.country+ : "Not available";++ // Format device details+ const deviceType = userAgentData.device && userAgentData.device !== "Unknown"+ ? userAgentData.device+ : "Desktop";+ const isDesktop = deviceType.toLowerCase() === "desktop" || deviceType.toLowerCase() === "unknown";++ const agreement = view.agreementResponse.agreement;+ let basePdfDoc: PDFDocument;++ // Load or create the agreement PDF+ if (agreement.contentType === "TEXT") {+ // Create PDF from text content+ basePdfDoc = await PDFDocument.create();+ const agreementPage = basePdfDoc.addPage([612, 792]);+ const { width: pageWidth, height: pageHeight } = agreementPage.getSize();++ const helveticaFont = await basePdfDoc.embedFont(StandardFonts.Helvetica);+ const helveticaBoldFont = await basePdfDoc.embedFont(+ StandardFonts.HelveticaBold,+ );++ const darkGray = rgb(0.2, 0.2, 0.2);+ const lightGray = rgb(0.5, 0.5, 0.5);++ // Agreement name as title (left-aligned)+ const titleFontSize = 20;+ const titleText = agreement.name;+ const margin = 72; // 1 inch margin+ agreementPage.drawText(titleText, {+ x: margin,+ y: pageHeight - 80,+ size: titleFontSize,+ font: helveticaBoldFont,+ color: darkGray,+ });++ // Agreement text content - split into lines+ const textContent = agreement.content;+ const fontSize = 12;+ const lineHeight = fontSize * 1.5;+ const maxWidth = pageWidth - 2 * margin;+ const startY = pageHeight - 120;++ // Simple text wrapping+ const words = textContent.split(/\s+/);+ let currentLine = "";+ let y = startY;+ const lines: string[] = [];++ for (const word of words) {+ const testLine = currentLine ? `${currentLine} ${word}` : word;+ const testWidth = helveticaFont.widthOfTextAtSize(testLine, fontSize);++ if (testWidth > maxWidth && currentLine) {+ lines.push(currentLine);+ currentLine = word;+ } else {+ currentLine = testLine;+ }+ }+ if (currentLine) {+ lines.push(currentLine);+ }++ // Draw text lines+ let currentPage = agreementPage;+ for (let i = 0; i < lines.length; i++) {+ if (y < margin) {+ // Add new page if needed+ currentPage = basePdfDoc.addPage([612, 792]);+ y = pageHeight - margin;+ }+ currentPage.drawText(lines[i], {+ x: margin,+ y: y,+ size: fontSize,+ font: helveticaFont,+ color: darkGray,+ });+ y -= lineHeight;+ }+ } else {+ // contentType === "LINK" - fetch the document PDF+ try {+ // Extract linkId from URL+ const isPapermarkUrl =+ agreement.content.includes("papermark.com/view/") ||+ agreement.content.includes("/view/");+ let linkId: string | null = null;++ if (isPapermarkUrl) {+ const urlParts = agreement.content.split("/view/");+ if (urlParts.length >= 2) {+ linkId = urlParts[1].split(/[/?#]/)[0];+ }+ }++ if (!linkId) {+ // If not a Papermark URL, try to fetch directly+ const response = await fetch(agreement.content, {+ headers: { Accept: "application/pdf" },+ });+ if (!response.ok) {+ throw new Error("Failed to fetch agreement document");+ }+ const pdfBuffer = await response.arrayBuffer();+ basePdfDoc = await PDFDocument.load(pdfBuffer);+ } else {+ // Fetch link and document+ const link = await prisma.link.findUnique({+ where: { id: linkId },+ include: {+ document: {+ select: {+ file: true,+ originalFile: true,+ storageType: true,+ versions: {+ where: { isPrimary: true },+ select: {+ file: true,+ originalFile: true,+ storageType: true,+ type: true,+ },+ take: 1,+ },+ },+ },+ },+ });++ if (!link || !link.document) {+ throw new Error("Document not found for agreement");+ }++ const documentVersion = link.document.versions[0];+ const fileKey = documentVersion+ ? documentVersion.originalFile || documentVersion.file+ : link.document.originalFile || link.document.file;+ const storageType = documentVersion+ ? documentVersion.storageType+ : link.document.storageType;++ // Only process if it's a PDF+ if (documentVersion && documentVersion.type !== "pdf") {+ throw new Error("Agreement document is not a PDF");+ }++ const fileUrl = await getFile({+ type: storageType,+ data: fileKey,+ isDownload: true,+ });++ const response = await fetch(fileUrl, {+ headers: { Accept: "application/pdf" },+ });+ if (!response.ok) {+ throw new Error("Failed to fetch agreement PDF");+ }+ const pdfBuffer = await response.arrayBuffer();+ basePdfDoc = await PDFDocument.load(pdfBuffer);+ }+ } catch (error) {+ // If fetching fails, create a simple PDF with agreement name+ basePdfDoc = await PDFDocument.create();+ const agreementPage = basePdfDoc.addPage([612, 792]);+ const { width: pageWidth, height: pageHeight } = agreementPage.getSize();++ const helveticaBoldFont = await basePdfDoc.embedFont(+ StandardFonts.HelveticaBold,+ );+ const darkGray = rgb(0.2, 0.2, 0.2);++ const titleText = agreement.name;+ const titleFontSize = 20;+ const titleWidth = helveticaBoldFont.widthOfTextAtSize(+ titleText,+ titleFontSize,+ );+ agreementPage.drawText(titleText, {+ x: (pageWidth - titleWidth) / 2,+ y: pageHeight - 100,+ size: titleFontSize,+ font: helveticaBoldFont,+ color: darkGray,+ });++ // Add note about agreement+ const helveticaFont = await basePdfDoc.embedFont(StandardFonts.Helvetica);+ const noteText = "Agreement document reference:";+ const noteWidth = helveticaFont.widthOfTextAtSize(noteText, 12);+ agreementPage.drawText(noteText, {+ x: (pageWidth - noteWidth) / 2,+ y: pageHeight - 150,+ size: 12,+ font: helveticaFont,+ color: rgb(0.5, 0.5, 0.5),+ });++ const urlText = agreement.content;+ const urlWidth = helveticaFont.widthOfTextAtSize(urlText, 10);+ agreementPage.drawText(urlText, {+ x: (pageWidth - urlWidth) / 2,+ y: pageHeight - 180,+ size: 10,+ font: helveticaFont,+ color: rgb(0.5, 0.5, 0.5),+ });+ }+ }++ // Now create the certificate page and append it+ const certificatePage = basePdfDoc.addPage([612, 792]);+ const { width, height } = certificatePage.getSize();++ // Embed fonts for certificate (reuse if already embedded, or embed new ones)+ const helveticaFont = await basePdfDoc.embedFont(StandardFonts.Helvetica);+ const helveticaBoldFont = await basePdfDoc.embedFont(+ StandardFonts.HelveticaBold,+ );++ // Colors matching the UI design - slate colors+ const slate900 = rgb(0.15, 0.18, 0.22); // Dark slate for main text+ const slate600 = rgb(0.48, 0.55, 0.64); // Medium slate+ const slate500 = rgb(0.65, 0.71, 0.78); // Light slate for labels+ const slate200 = rgb(0.93, 0.94, 0.96); // Very light slate for borders+ const slate300 = rgb(0.85, 0.88, 0.92); // Light slate for separators++ const marginX = 72; // 1 inch margin++ // Header section - matching second image design (clean top, no gradient line)+ const headerTopY = height - 60;+ const headerBottomY = headerTopY - 100;++ // "COMPLIANCE CERTIFICATE" label (uppercase, small, lighter gray, more spacing)+ const complianceLabel = "COMPLIANCE CERTIFICATE";+ certificatePage.drawText(complianceLabel, {+ x: marginX,+ y: headerTopY - 12,+ size: 8.5,+ font: helveticaBoldFont,+ color: slate500,+ });++ // "NDA Completion" title (large, bold, more spacing from label)+ const titleText = "NDA Signing Certificate";+ certificatePage.drawText(titleText, {+ x: marginX,+ y: headerTopY - 50,+ size: 26,+ font: helveticaBoldFont,+ color: slate900,+ });++ // Certificate ID on the right (matching second image layout)+ const certificateId = `NDA-${view.id.slice(0, 8).toUpperCase()}`;+ const certIdLabel = "Certificate ID";+ const certIdLabelWidth = helveticaBoldFont.widthOfTextAtSize(certIdLabel, 8.5);+ certificatePage.drawText(certIdLabel, {+ x: width - marginX - certIdLabelWidth,+ y: headerTopY - 12,+ size: 8.5,+ font: helveticaBoldFont,+ color: slate500,+ });+ const certIdWidth = helveticaBoldFont.widthOfTextAtSize(certificateId, 12);+ certificatePage.drawText(certificateId, {+ x: width - marginX - certIdWidth,+ y: headerTopY - 50,+ size: 12,+ font: helveticaBoldFont,+ color: slate900,+ });++ // Header bottom border (horizontal line separator)+ certificatePage.drawLine({+ start: { x: marginX, y: headerBottomY },+ end: { x: width - marginX, y: headerBottomY },+ thickness: 1.5,+ color: slate200,+ });++ // Main content area - Recipient section (matching second image)+ const recipientSectionY = headerBottomY - 50;++ // "RECIPIENT" label (uppercase, small, lighter gray)+ const recipientLabel = "RECIPIENT";+ certificatePage.drawText(recipientLabel, {+ x: marginX,+ y: recipientSectionY,+ size: 8.5,+ font: helveticaBoldFont,+ color: slate500,+ });++ // Recipient name (large, bold, more spacing)+ const recipientName =+ view.viewerName || view.viewerEmail?.split("@")[0] || "Anonymous";+ certificatePage.drawText(recipientName, {+ x: marginX,+ y: recipientSectionY - 35,+ size: 20,+ font: helveticaBoldFont,+ color: slate900,+ });++ // Recipient email (regular weight, medium gray)+ const recipientEmail = view.viewerEmail || "Not provided";+ certificatePage.drawText(recipientEmail, {+ x: marginX,+ y: recipientSectionY - 55,+ size: 11,+ font: helveticaFont,+ color: slate600,+ });++ // Recipient section bottom border (horizontal line separator)+ const recipientBorderY = recipientSectionY - 85;+ certificatePage.drawLine({+ start: { x: marginX, y: recipientBorderY },+ end: { x: width - marginX, y: recipientBorderY },+ thickness: 1.5,+ color: slate200,+ });++ // Details Grid - Two columns (matching second image spacing)+ const detailsStartY = recipientBorderY - 50;+ const col1X = marginX;+ const col2X = width / 2 + 40; // Center split with gap+ const colSpacing = 50; // Vertical spacing between items (consistent for all)++ // Left Column - Authentication Level, Location, Device Type+ let currentY = detailsStartY;++ // Authentication Level+ const authLabel = "AUTHENTICATION LEVEL";+ certificatePage.drawText(authLabel, {+ x: col1X,+ y: currentY,+ size: 8.5,+ font: helveticaBoldFont,+ color: slate500,+ });+ certificatePage.drawText("Email", {+ x: col1X,+ y: currentY - 20,+ size: 10.5,+ font: helveticaFont,+ color: slate900,+ });++ currentY -= colSpacing;+ // Location+ const locationLabel = "LOCATION";+ certificatePage.drawText(locationLabel, {+ x: col1X,+ y: currentY,+ size: 8.5,+ font: helveticaBoldFont,+ color: slate500,+ });+ certificatePage.drawText(locationText, {+ x: col1X,+ y: currentY - 20,+ size: 10.5,+ font: helveticaFont,+ color: slate900,+ });++ currentY -= colSpacing;+ // Device Type (no separator line)+ const deviceLabel = "DEVICE TYPE";+ certificatePage.drawText(deviceLabel, {+ x: col1X,+ y: currentY,+ size: 8.5,+ font: helveticaBoldFont,+ color: slate500,+ });+ certificatePage.drawText(deviceType, {+ x: col1X,+ y: currentY - 20,+ size: 10.5,+ font: helveticaFont,+ color: slate900,+ });+++ // Right Column - Viewed, Completed, System+ currentY = detailsStartY;++ // Viewed+ const viewedLabel = "VIEWED";+ const viewedDate = view.viewedAt+ ? format(new Date(view.viewedAt), "yyyy-MM-dd h:mm a '(UTC)'")+ : "Not available";+ certificatePage.drawText(viewedLabel, {+ x: col2X,+ y: currentY,+ size: 8.5,+ font: helveticaBoldFont,+ color: slate500,+ });+ certificatePage.drawText(viewedDate, {+ x: col2X,+ y: currentY - 20,+ size: 10,+ font: helveticaFont,+ color: slate900,+ });++ currentY -= colSpacing;+ // Completed+ const completedLabel = "COMPLETED";+ const completedDate = format(+ new Date(view.agreementResponse.createdAt),+ "yyyy-MM-dd h:mm a '(UTC)'",+ );+ certificatePage.drawText(completedLabel, {+ x: col2X,+ y: currentY,+ size: 8.5,+ font: helveticaBoldFont,+ color: slate500,+ });+ certificatePage.drawText(completedDate, {+ x: col2X,+ y: currentY - 20,+ size: 10,+ font: helveticaFont,+ color: slate900,+ });++ currentY -= colSpacing;+ // System (no separator line)+ const systemLabel = "SYSTEM";+ const systemInfo = `${userAgentData.os || "Unknown"} - ${userAgentData.browser || "Unknown"}`;+ certificatePage.drawText(systemLabel, {+ x: col2X,+ y: currentY,+ size: 8.5,+ font: helveticaBoldFont,+ color: slate500,+ });+ certificatePage.drawText(systemInfo, {+ x: col2X,+ y: currentY - 20,+ size: 10,+ font: helveticaFont,+ color: slate900,+ });++ // Footer section with border top (matching second image)+ const footerY = 70;+ const footerBorderY = footerY + 25;++ // Footer top border+ certificatePage.drawLine({+ start: { x: marginX, y: footerBorderY },+ end: { x: width - marginX, y: footerBorderY },+ thickness: 1.5,+ color: slate200,+ });++ // "Issued by" on left (matching second image style)+ if (view.team.name) {+ const issuedByPrefix = "Issued by: ";+ const prefixWidth = helveticaFont.widthOfTextAtSize(issuedByPrefix, 9);+ certificatePage.drawText(issuedByPrefix, {+ x: marginX,+ y: footerY,+ size: 9,+ font: helveticaFont,+ color: slate600,+ });+ // Team name in bold+ certificatePage.drawText(view.team.name, {+ x: marginX + prefixWidth,+ y: footerY,+ size: 9,+ font: helveticaBoldFont,+ color: slate900,+ });+ }++ // "NDA Certificate β’ Year" on right (matching second image)+ const currentYear = new Date().getFullYear();+ const footerRightText = `NDA Certificate β’ ${currentYear}`;+ const footerRightWidth = helveticaBoldFont.widthOfTextAtSize(footerRightText, 9);+ certificatePage.drawText(footerRightText, {+ x: width - marginX - footerRightWidth,+ y: footerY,+ size: 9,+ font: helveticaBoldFont,+ color: slate600,+ });++ // Generate PDF bytes with agreement + certificate+ const pdfBytes = await basePdfDoc.save({+ useObjectStreams: false, // Better compatibility+ addDefaultPage: false, // Don't add default page+ });++ // Convert to Buffer for proper binary encoding+ const pdfBuffer = Buffer.from(pdfBytes);++ // Set response headers+ const fileName = `NDA-Certificate-${recipientName.replace(/[^a-z0-9]/gi, "-")}-${Date.now()}.pdf`;+ res.setHeader("Content-Type", "application/pdf");+ res.setHeader(+ "Content-Disposition",+ `attachment; filename="${encodeURIComponent(fileName)}"`,+ );+ res.setHeader("Content-Length", pdfBuffer.length);+ res.setHeader("Cache-Control", "no-cache");++ return res.status(200).send(pdfBuffer);+ } catch (error) {+ log({+ message: `Failed to generate NDA certificate for view: ${viewId}. \n\n ${error} \n\n*Metadata*: \`{userId: ${userId}}\``,+ type: "error",+ });+ errorhandler(error, res);+ }+}+diff --git a/pages/welcome.tsx b/pages/welcome.tsxindex fc82fca9..902cdfce 100644--- a/pages/welcome.tsx+++ b/pages/welcome.tsx@@ -15,6 +15,7 @@ import { cn } from "@/lib/utils";import { GTMComponent } from "@/components/gtm-component";import { Button } from "@/components/ui/button";import Dataroom from "@/components/welcome/dataroom";+import DataroomAIGenerate from "@/components/welcome/dataroom-ai-generate";import DataroomChoice from "@/components/welcome/dataroom-choice";import DataroomTrial from "@/components/welcome/dataroom-trial";import DataroomUpload from "@/components/welcome/dataroom-upload";@@ -56,9 +57,10 @@ export default function Welcome() {const isDataroomUpload = router.query.type === "dataroom-upload";const isDataroomChoice = router.query.type === "dataroom-choice";const isDataroomTemplates = router.query.type === "dataroom-templates";+ const isDataroomAIGenerate = router.query.type === "dataroom-ai-generate";const skipButtonText =- isDataroomUpload || isDataroomChoice || isDataroomTemplates+ isDataroomUpload || isDataroomChoice || isDataroomTemplates || isDataroomAIGenerate? "Skip to dataroom": "Skip to dashboard";const skipButtonPath =@@ -128,6 +130,9 @@ export default function Welcome() {dataroomId={router.query.dataroomId as string}/>)}+ {router.query.type === "dataroom-ai-generate" && (+ <DataroomAIGenerate key="dataroom-ai-generate" />+ )}</AnimatePresence></div></>