Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: small fixes
Marc Seitzdb332c210b8c
diff --git a/components/analytics/views-table.tsx b/components/analytics/views-table.tsxindex 04a97f2c..f4cb9797 100644--- a/components/analytics/views-table.tsx+++ b/components/analytics/views-table.tsx@@ -48,6 +48,7 @@ import {import { BadgeTooltip } from "@/components/ui/tooltip";import { DataTablePagination } from "@/components/visitors/data-table-pagination";import { VisitorAvatar } from "@/components/visitors/visitor-avatar";+import { UpgradeButton } from "../ui/upgrade-button";interface View {@@ -73,7 +74,7 @@ interface View {const columns: ColumnDef<View>[] = [{accessorKey: "viewerEmail",- header: "Recent Visits",+ header: "Recent Views",cell: ({ row }) => (<div className="flex items-center overflow-visible sm:space-x-3"><VisitorAvatar viewerEmail={row.original.viewerEmail} />@@ -246,7 +247,7 @@ const columns: ColumnDef<View>[] = ["px-0",)}>- Last Visited+ Last Viewed{column.getIsSorted() === "asc" ? (<ChevronUpIcon className="ml-2 h-4 w-4" />) : column.getIsSorted() === "desc" ? (@@ -420,7 +421,7 @@ export default function ViewsTable({colSpan={columns.length}className="h-24 text-center">- <p>No visits in the last {interval}</p>+ <p>No views in the last {interval}</p></TableCell></TableRow>)}diff --git a/components/datarooms/add-dataroom-modal.tsx b/components/datarooms/add-dataroom-modal.tsxindex bdc6ee3f..831f129a 100644--- a/components/datarooms/add-dataroom-modal.tsx+++ b/components/datarooms/add-dataroom-modal.tsx@@ -70,9 +70,7 @@ export function AddDataroomModal({});const dataroomSchemaWithType = z.object({- name: z.string().trim().min(3, {- message: "Please provide a dataroom name with at least 3 characters.",- }),+ name: z.string().trim().optional(),type: z.enum(["startup-fundraising",@@ -115,7 +113,10 @@ export function AddDataroomModal({: `/api/teams/${teamInfo?.currentTeam?.id}/datarooms`;const body = useTemplate- ? { name: dataroomName.trim(), type: dataroomType }+ ? {+ name: dataroomName.trim() || undefined,+ type: dataroomType,+ }: { name: dataroomName.trim() };const response = await fetch(endpoint, {@@ -223,7 +224,10 @@ export function AddDataroomModal({className="flex flex-col space-y-4"><div className="space-y-1">- <Label htmlFor="dataroom-name-create">Dataroom Name</Label>+ <Label htmlFor="dataroom-name-create">+ Dataroom Name{" "}+ <span className="text-black dark:text-white">*</span>+ </Label><Inputid="dataroom-name-create"placeholder="ACME Acquisition"@@ -265,13 +269,16 @@ export function AddDataroomModal({</Label><Inputid="dataroom-name-generate"- placeholder="ACME Acquisition"+ 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</Label>+ <Label htmlFor="dataroom-type">+ Dataroom Type{" "}+ <span className="text-black dark:text-white">*</span>+ </Label><Selectvalue={dataroomType}onValueChange={setDataroomType}diff --git a/components/datarooms/dataroom-trial-modal.tsx b/components/datarooms/dataroom-trial-modal.tsxindex 40f5455b..3b394e07 100644--- a/components/datarooms/dataroom-trial-modal.tsx+++ b/components/datarooms/dataroom-trial-modal.tsx@@ -8,6 +8,8 @@ import { E164Number } from "libphonenumber-js";import { toast } from "sonner";import { mutate } from "swr";+import { useAnalytics } from "@/lib/analytics";+import { Button } from "@/components/ui/button";import {Dialog,@@ -21,8 +23,6 @@ import {import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";-import { useAnalytics } from "@/lib/analytics";-import { UpgradePlanModal } from "../billing/upgrade-plan-modal";import { PhoneInput } from "../ui/phone-input";import {@@ -55,6 +55,26 @@ export function DataroomTrialModal({const teamInfo = useTeam();const analytics = useAnalytics();+ // Helper function to convert industry to proper dataroom name+ const getDataroomName = (industryValue: string) => {+ const industryNames: Record<string, string> = {+ "finance-banking": "Finance and Banking Data Room",+ legal: "Legal Data Room",+ "real-estate": "Real Estate Data Room",+ technology: "Technology Data Room",+ pharmaceuticals: "Pharmaceuticals Data Room",+ energy: "Energy Data Room",+ manufacturing: "Manufacturing Data Room",+ healthcare: "Healthcare Data Room",+ consulting: "Consulting and Professional Services Data Room",+ government: "Government and Public Sector Data Room",+ entertainment: "Entertainment and Media Data Room",+ other: "Data Room",+ };++ return industryNames[industryValue] || "Data Room";+ };+const handleSubmit = async (event: any) => {event.preventDefault();event.stopPropagation();@@ -66,6 +86,8 @@ export function DataroomTrialModal({setLoading(true);+ const dataroomName = getDataroomName(industry);+try {const response = await fetch(`/api/teams/${teamInfo?.currentTeam?.id}/datarooms/trial`,@@ -75,7 +97,7 @@ export function DataroomTrialModal({"Content-Type": "application/json",},body: JSON.stringify({- name: "Dataroom #1",+ name: dataroomName,fullName: name,companyName,industry,@@ -93,7 +115,7 @@ export function DataroomTrialModal({}analytics.capture("Dataroom Trial Created", {- dataroomName: "Dataroom #1",+ dataroomName: dataroomName,industry,companySize,});diff --git a/components/datarooms/export-visits-modal.tsx b/components/datarooms/export-visits-modal.tsxindex 1b202f16..6e822a30 100644--- a/components/datarooms/export-visits-modal.tsx+++ b/components/datarooms/export-visits-modal.tsx@@ -326,7 +326,7 @@ export function ExportVisitsModal({<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"><div className="mx-4 w-full max-w-md rounded-lg bg-white p-6 dark:bg-gray-800"><div className="mb-4 flex items-center justify-between">- <h3 className="text-lg font-semibold">Export Visits</h3>+ <h3 className="text-lg font-semibold">Export Views</h3><buttononClick={handleClose}className="text-gray-400 hover:text-gray-600"@@ -362,7 +362,7 @@ export function ExportVisitsModal({</div><div className="text-sm text-gray-600">- Exporting visits for: {displayName}+ Exporting views for: {displayName}</div>{viewCount !== null && (@@ -374,7 +374,7 @@ export function ExportVisitsModal({{viewCount !== null && viewCount > 10 && session?.user?.email && (<div className="rounded-md bg-gray-50 p-3 text-sm dark:bg-gray-900"><p className="mb-2 font-medium text-muted-foreground">- Large export detected ({viewCount} visits)+ Large export detected ({viewCount} views)</p><p className="mb-3 text-muted-foreground">This export may take several minutes. We recommend getting itdiff --git a/components/datarooms/groups/group-member-table.tsx b/components/datarooms/groups/group-member-table.tsxindex aa9ebe60..daafb10d 100644--- a/components/datarooms/groups/group-member-table.tsx+++ b/components/datarooms/groups/group-member-table.tsx@@ -194,7 +194,7 @@ export default function GroupMemberTable({<TableRow><TableCell colSpan={2}><div className="flex h-40 w-full items-center justify-center">- <p>No visits yet. Try sharing a link.</p>+ <p>No views yet. Try sharing a link.</p></div></TableCell></TableRow>diff --git a/components/datarooms/stats-card.tsx b/components/datarooms/stats-card.tsxindex 3a19973f..c2014b3d 100644--- a/components/datarooms/stats-card.tsx+++ b/components/datarooms/stats-card.tsx@@ -1,10 +1,10 @@import ErrorPage from "next/error";+import { useDataroomStats } from "@/lib/swr/use-dataroom-stats";+import StatsElement from "@/components/documents/stats-element";import { Skeleton } from "@/components/ui/skeleton";-import { useDataroomStats } from "@/lib/swr/use-dataroom-stats";-export default function StatsCard() {const { stats, loading, error } = useDataroomStats();@@ -30,12 +30,12 @@ export default function StatsCard() {const statistics = [{- name: "Number of visits",+ name: "Number of views",value: stats?.dataroomViews.length.toString() ?? "0",active: true,},{- name: "Number of documents visits",+ name: "Number of documents views",value: stats?.documentViews.length.toString() ?? "0",active: true,},diff --git a/components/documents/document-header.tsx b/components/documents/document-header.tsxindex d4cc7f4b..984e6860 100644--- a/components/documents/document-header.tsx+++ b/components/documents/document-header.tsx@@ -787,7 +787,7 @@ export default function DocumentHeader({}><FileDownIcon className="mr-2 h-4 w-4" />- Export visits{" "}+ Export views{" "}{isFree && <PlanBadge className="ml-2" plan="pro" />}</DropdownMenuItem>diff --git a/components/documents/document-stats-placeholder.tsx b/components/documents/document-stats-placeholder.tsxindex 675272ce..defa77dd 100644--- a/components/documents/document-stats-placeholder.tsx+++ b/components/documents/document-stats-placeholder.tsx@@ -29,7 +29,7 @@ export default function DocumentStatsPlaceholder({htmlFor="toggle-stats-placeholder"className="text-muted-foreground">- Exclude internal visits+ Exclude internal views</Label></div>@@ -39,8 +39,8 @@ export default function DocumentStatsPlaceholder({{/* Stats Card Placeholder */}<div className="grid grid-cols-1 space-y-2 border-foreground/5 sm:grid-cols-3 sm:space-x-2 sm:space-y-0 lg:grid-cols-3 lg:space-x-3">{[- { name: "Number of visits", value: "0", active: false },- { name: "Number of reactions", value: "0", active: false },+ { name: "Number of views", value: "0", active: false },+ { name: "Average view completion", value: "%", active: false },{name: "Total average view duration",value: "0",diff --git a/components/documents/export-visits-modal.tsx b/components/documents/export-visits-modal.tsxindex b0d8a807..3bb54180 100644--- a/components/documents/export-visits-modal.tsx+++ b/components/documents/export-visits-modal.tsx@@ -315,7 +315,7 @@ export function ExportVisitsModal({<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"><div className="mx-4 w-full max-w-md rounded-lg bg-white p-6 dark:bg-gray-800"><div className="mb-4 flex items-center justify-between">- <h3 className="text-lg font-semibold">Export Visits</h3>+ <h3 className="text-lg font-semibold">Export Views</h3><buttononClick={handleClose}className="text-gray-400 hover:text-gray-600"diff --git a/components/documents/stats-card.tsx b/components/documents/stats-card.tsxindex 5f13226c..5f46cd5d 100644--- a/components/documents/stats-card.tsx+++ b/components/documents/stats-card.tsx@@ -1,9 +1,9 @@import ErrorPage from "next/error";-import { Skeleton } from "@/components/ui/skeleton";-import { TStatsData } from "@/lib/swr/use-stats";+import { Skeleton } from "@/components/ui/skeleton";+import StatsElement from "./stats-element";export default function StatsCard({@@ -33,22 +33,15 @@ export default function StatsCard({);}- const groupedReactionsTotal =- stats?.groupedReactions- .reduce((accumulator, item) => {- return accumulator + item._count.type;- }, 0)- .toString() ?? "0";-const statistics = [{- name: "Number of visits",+ name: "Number of views",value: stats?.totalViews.toString() ?? "0",active: true,},{- name: "Number of reactions",- value: groupedReactionsTotal,+ name: "Average view completion",+ value: `${stats?.avgCompletionRate ?? 0}%`,active: true,},{diff --git a/components/documents/stats.tsx b/components/documents/stats.tsxindex 7d194b3f..6c779342 100644--- a/components/documents/stats.tsx+++ b/components/documents/stats.tsx@@ -2,11 +2,11 @@ import { useRouter, useSearchParams } from "next/navigation";import { useState } from "react";+import { useStats } from "@/lib/swr/use-stats";+import { Label } from "@/components/ui/label";import { Switch } from "@/components/ui/switch";-import { useStats } from "@/lib/swr/use-stats";-import StatsCard from "./stats-card";import StatsChart from "./stats-chart";@@ -46,7 +46,7 @@ export const StatsComponent = ({htmlFor="toggle-stats"className={excludeTeamMembers ? "" : "text-muted-foreground"}>- Exclude internal visits+ Exclude internal views</Label></div>diff --git a/components/documents/video-analytics.tsx b/components/documents/video-analytics.tsxindex 4cd46ac6..41b8dd3e 100644--- a/components/documents/video-analytics.tsx+++ b/components/documents/video-analytics.tsx@@ -10,13 +10,13 @@ import {} from "recharts";import useSWR from "swr";+import { fetcher } from "@/lib/utils";+import StatsElement from "@/components/documents/stats-element";import VideoChartPlaceholder from "@/components/documents/video-chart-placeholder";import { Card, CardContent } from "@/components/ui/card";import LoadingSpinner from "@/components/ui/loading-spinner";-import { fetcher } from "@/lib/utils";-interface VideoAnalyticsProps {teamId: string;documentId: string;@@ -62,7 +62,7 @@ export default function VideoAnalytics({if (!data?.overall) {const emptyStats = [{- name: "Total visits",+ name: "Total views",value: "0",active: false,},@@ -132,12 +132,12 @@ export default function VideoAnalytics({const stats = [{- name: "Total visits",+ name: "Total views",value: data.overall.unique_views.toString(),active: true,},{- name: "Watch time",+ name: "View time",value: formatTime(data.overall.total_watch_time),unit: "minutes",active: true,diff --git a/components/documents/video-stats-placeholder.tsx b/components/documents/video-stats-placeholder.tsxindex 62a51d2f..f081010d 100644--- a/components/documents/video-stats-placeholder.tsx+++ b/components/documents/video-stats-placeholder.tsx@@ -19,7 +19,7 @@ export default function VideoStatsPlaceholder({const mockStats = [{- name: "Total visits",+ name: "Total views",value: "0",active: false,},diff --git a/components/layouts/breadcrumb.tsx b/components/layouts/breadcrumb.tsxindex ba9df654..3b8b058f 100644--- a/components/layouts/breadcrumb.tsx+++ b/components/layouts/breadcrumb.tsx@@ -414,7 +414,7 @@ const AnalyticsBreadcrumb = () => {case "visitors":return "Visitors";case "views":- return "Recent Visits";+ return "Recent Views";default:return "Analytics";}diff --git a/components/visitors/contacts-document-table.tsx b/components/visitors/contacts-document-table.tsxindex a22340d8..7dbb7d17 100644--- a/components/visitors/contacts-document-table.tsx+++ b/components/visitors/contacts-document-table.tsx@@ -267,7 +267,7 @@ export function ContactsDocumentsTable({<TableHead>Document Name</TableHead><TableHead>Last Viewed</TableHead><TableHead>Time Spent</TableHead>- <TableHead>Visits</TableHead>+ <TableHead>Views</TableHead></TableRow></TableHeader><TableBody>diff --git a/components/visitors/contacts-table.tsx b/components/visitors/contacts-table.tsxindex b87fa8e6..f02a060b 100644--- a/components/visitors/contacts-table.tsx+++ b/components/visitors/contacts-table.tsx@@ -192,7 +192,7 @@ export function ContactsTable({onClick={() => handleSort("totalVisits")}className={getSortClass("totalVisits")}>- Total Visits+ Total Views{getSortIcon("totalVisits")}</Button>);@@ -222,7 +222,7 @@ export function ContactsTable({<TableRow><TableHead>Name</TableHead><TableHead>Last Viewed</TableHead>- <TableHead>Total Visits</TableHead>+ <TableHead>Total Views</TableHead></TableRow></TableHeader><TableBody>diff --git a/components/visitors/dataroom-visitors-table.tsx b/components/visitors/dataroom-visitors-table.tsxindex 4b1fbca3..9e33e27f 100644--- a/components/visitors/dataroom-visitors-table.tsx+++ b/components/visitors/dataroom-visitors-table.tsx@@ -83,7 +83,7 @@ export default function DataroomVisitorsTable({<TableRow><TableCell colSpan={5}><div className="flex h-40 w-full items-center justify-center">- <p>No visits yet. Try sharing a link.</p>+ <p>No views yet. Try sharing a link.</p></div></TableCell></TableRow>diff --git a/components/visitors/visitors-table.tsx b/components/visitors/visitors-table.tsxindex b71cbec7..a49b2d23 100644--- a/components/visitors/visitors-table.tsx+++ b/components/visitors/visitors-table.tsx@@ -138,8 +138,8 @@ export default function VisitorsTable({<TableHeader><TableRow className="*:whitespace-nowrap *:font-medium hover:bg-transparent"><TableHead>Name</TableHead>- <TableHead>Visit Duration</TableHead>- <TableHead>Visit Completion</TableHead>+ <TableHead>View Duration</TableHead>+ <TableHead>View Completion</TableHead><TableHead>Last Viewed</TableHead><TableHead className="text-center sm:text-right"></TableHead></TableRow>@@ -150,7 +150,7 @@ export default function VisitorsTable({<TableRow><TableCell colSpan={5}><div className="flex h-40 w-full items-center justify-center">- <p>No visits yet. Try sharing a link.</p>+ <p>No views yet. Try sharing a link.</p></div></TableCell></TableRow>@@ -478,7 +478,7 @@ export default function VisitorsTable({<div className="flex flex-col items-start justify-center gap-1 sm:flex-row sm:items-center"><span className="flex items-center gap-x-1"><AlertTriangleIcon className="inline-block h-4 w-4 text-yellow-500" />- Some older visits may not be shown because your document+ Some older views may not be shown because your documenthas more than 20 views.{" "}</span><UpgradePlanModaldiff --git a/components/welcome/dataroom-choice.tsx b/components/welcome/dataroom-choice.tsxindex 25c49df1..60410ac9 100644--- a/components/welcome/dataroom-choice.tsx+++ b/components/welcome/dataroom-choice.tsx@@ -38,7 +38,7 @@ export default function DataroomChoice({ dataroomId }: { dataroomId: string }) {</motion.div><motion.divvariants={STAGGER_CHILD_VARIANTS}- className="grid w-full 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-2xl grid-cols-1 divide-y divide-border rounded-md border border-border text-foreground md:grid-cols-2 md:divide-x"><buttononClick={() =>diff --git a/components/welcome/dataroom-trial.tsx b/components/welcome/dataroom-trial.tsxindex 4d8fca28..1472961e 100644--- a/components/welcome/dataroom-trial.tsx+++ b/components/welcome/dataroom-trial.tsx@@ -40,6 +40,24 @@ export default function DataroomTrial() {const [loading, setLoading] = useState<boolean>(false);+ // Helper function to convert use case to proper dataroom name+ const getDataroomName = (useCaseValue: string, customValue: string = "") => {+ if (useCaseValue === "other" && customValue) {+ return `${customValue} Data Room`;+ }++ const useCaseNames: Record<string, string> = {+ "mergers-and-acquisitions": "Mergers and Acquisitions Data Room",+ "startup-fundraising": "Startup Fundraising Data Room",+ "fund-management": "Fund Management & Fundraising Data Room",+ sales: "Sales Data Room",+ "project-management": "Project Management Data Room",+ operations: "Operations Data Room",+ };++ return useCaseNames[useCaseValue] || "Data Room";+ };+const handleSubmit = async (event: any) => {event.preventDefault();event.stopPropagation();@@ -51,6 +69,8 @@ export default function DataroomTrial() {setLoading(true);+ const dataroomName = getDataroomName(useCase, customUseCase.trim());+try {const response = await fetch(`/api/teams/${teamInfo?.currentTeam?.id}/datarooms/trial`,@@ -60,7 +80,7 @@ export default function DataroomTrial() {"Content-Type": "application/json",},body: JSON.stringify({- name: "Dataroom #1",+ name: dataroomName,fullName: name,companyName,useCase: useCase === "other" ? customUseCase.trim() : useCase,@@ -84,7 +104,7 @@ export default function DataroomTrial() {}analytics.capture("Dataroom Trial Created", {- dataroomName: "Dataroom #1",+ dataroomName: dataroomName,useCase: useCase === "other" ? customUseCase.trim() : useCase,companySize,dataroomId,diff --git a/components/welcome/next.tsx b/components/welcome/next.tsxindex 5bacb18b..04095cad 100644--- a/components/welcome/next.tsx+++ b/components/welcome/next.tsx@@ -38,7 +38,7 @@ export default function Next() {</motion.div><motion.divvariants={STAGGER_CHILD_VARIANTS}- className="grid w-full 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-2xl grid-cols-1 divide-y divide-border rounded-md border border-border text-foreground md:grid-cols-2 md:divide-x"><buttononClick={() =>@@ -52,7 +52,10 @@ export default function Next() {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"><FileIcon className="pointer-events-none h-auto w-12 sm:w-12" />- <p>Document</p>+ <p className="text-lg font-medium">Document</p>+ <p className="text-sm text-muted-foreground">+ Share a single document with page-by-page analytics+ </p></button><buttononClick={() =>@@ -66,7 +69,10 @@ export default function Next() {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"><ServerIcon className="pointer-events-none h-auto w-12 sm:w-12" />- <p>Data Room</p>+ <p className="text-lg font-medium">Data Room</p>+ <p className="text-sm text-muted-foreground">+ Share multiple documents with folders and page-by-page analytics+ </p></button></motion.div>diff --git a/ee/features/templates/api/datarooms/apply-template.ts b/ee/features/templates/api/datarooms/apply-template.tsindex 0a5f4376..632b579c 100644--- a/ee/features/templates/api/datarooms/apply-template.ts+++ b/ee/features/templates/api/datarooms/apply-template.ts@@ -64,8 +64,16 @@ export default async function handle(const template = DATAROOM_TEMPLATES[type];- // Create folders in a transaction to prevent hanging results+ // Update dataroom name and create folders in a transactionawait prisma.$transaction(async (tx) => {+ // Update dataroom name to match template+ await tx.dataroom.update({+ where: { id: dataroom.id },+ data: {+ name: `${template.name} Data Room`,+ },+ });+// Helper function to create folders recursivelyconst createFolders = async (folders: FolderTemplate[],diff --git a/ee/features/templates/api/datarooms/generate.ts b/ee/features/templates/api/datarooms/generate.tsindex 70dbfa45..f33a2198 100644--- a/ee/features/templates/api/datarooms/generate.ts+++ b/ee/features/templates/api/datarooms/generate.ts@@ -93,12 +93,15 @@ export default async function handle(// Create folders based on the selected templateconst template = DATAROOM_TEMPLATES[type];+ // Use template name + "Data Room" if no name is provided+ const dataroomName = name?.trim() || `${template.name} Data Room`;+// Create the dataroom and folders in a transaction to prevent hanging resultsconst dataroom = await prisma.$transaction(async (tx) => {// Create the dataroomconst createdDataroom = await tx.dataroom.create({data: {- name: name,+ name: dataroomName,teamId: teamId,pId: pId,},diff --git a/ee/features/templates/schemas/dataroom-templates.ts b/ee/features/templates/schemas/dataroom-templates.tsindex 424697d0..4b134ac1 100644--- a/ee/features/templates/schemas/dataroom-templates.ts+++ b/ee/features/templates/schemas/dataroom-templates.ts@@ -28,15 +28,17 @@ export const applyTemplateSchema = z.object({/*** Schema for validating dataroom generation request* Includes both name validation and template type validation+ * Name is optional - if not provided, template name will be used*/export const generateDataroomSchema = z.object({name: z.string()- .min(1, "Dataroom name is required").max(255, "Dataroom name is too long")+ .optional().refine((name) => {- // Ensure no malicious characters in the name+ // If name is provided, ensure no malicious characters+ if (!name) return true;return (!name.includes("\0") &&!name.includes("..") &&diff --git a/lib/swr/use-stats.ts b/lib/swr/use-stats.tsindex 79402c41..2aacb205 100644--- a/lib/swr/use-stats.ts+++ b/lib/swr/use-stats.ts@@ -9,7 +9,7 @@ import { fetcher } from "@/lib/utils";export type TStatsData = {views: View[];- groupedReactions: { type: string; _count: { type: number } }[];+ avgCompletionRate: number;duration: {data: { versionNumber: number; pageNumber: string; avg_duration: number }[];};diff --git a/lib/trigger/export-visits.ts b/lib/trigger/export-visits.tsindex 640e46ee..91be017b 100644--- a/lib/trigger/export-visits.ts+++ b/lib/trigger/export-visits.ts@@ -257,7 +257,7 @@ async function exportDocumentVisits("Name","Email","Link Name",- "Total Visit Duration (s)",+ "Total View Duration (s)","Total Document Completion (%)","Document version","Downloaded at",diff --git a/lib/utils.ts b/lib/utils.tsindex 520021d0..2c1ac162 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -327,8 +327,8 @@ export const daysLeft = (const diffInMilliseconds = endPeriodDate.getTime() - now.getTime();- // Convert milliseconds to days and return- return Math.ceil(diffInMilliseconds / (1000 * 60 * 60 * 24));+ // Convert milliseconds to days and round down to show complete days remaining+ return Math.floor(diffInMilliseconds / (1000 * 60 * 60 * 24));};const cutoffDate = new Date("2023-10-17T00:00:00.000Z");diff --git a/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/stats.ts b/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/stats.tsindex e189324b..b1af3d58 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/stats.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/stats.ts@@ -103,7 +103,7 @@ export default async function handle(views: [],duration: { data: [] },total_duration: 0,- groupedReactions: [],+ avgCompletionRate: 0,totalViews: 0,totalPagesMax: 0,});@@ -145,7 +145,7 @@ export default async function handle(views: filteredViews,duration,total_duration: 0, // INFO: hiding this for now- groupedReactions: [], // INFO: hiding this as not relevant+ avgCompletionRate: 0, // INFO: hiding this for nowtotalViews: filteredViews.length,completionRate: 0,totalPagesMax: dataroomDocument.document.versions[0].numPages,diff --git a/pages/api/teams/[teamId]/datarooms/[id]/stats.ts b/pages/api/teams/[teamId]/datarooms/[id]/stats.tsindex 257116c7..eb404b37 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/stats.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/stats.ts@@ -80,7 +80,7 @@ export default async function handle(views: [],duration: { data: [] },total_duration: 0,- groupedReactions: [],+ avgCompletionRate: 0,});}diff --git a/pages/api/teams/[teamId]/documents/[id]/stats.ts b/pages/api/teams/[teamId]/documents/[id]/stats.tsindex 69ab3068..1e0bce38 100644--- a/pages/api/teams/[teamId]/documents/[id]/stats.ts+++ b/pages/api/teams/[teamId]/documents/[id]/stats.ts@@ -9,7 +9,9 @@ import prisma from "@/lib/prisma";import {getTotalAvgPageDuration,getTotalDocumentDuration,+ getViewPageDuration,} from "@/lib/tinybird";+import { getVideoEventsByDocument } from "@/lib/tinybird/pipes";import { CustomUser } from "@/lib/types";export default async function handle(@@ -53,6 +55,18 @@ export default async function handle(select: {id: true,teamId: true,+ numPages: true,+ type: true,+ versions: {+ orderBy: { createdAt: "desc" },+ select: {+ versionNumber: true,+ createdAt: true,+ numPages: true,+ type: true,+ length: true,+ },+ },_count: {select: {views: { where: { isArchived: false } },@@ -71,7 +85,7 @@ export default async function handle(views: [],duration: { data: [] },total_duration: 0,- groupedReactions: [],+ avgCompletionRate: 0,totalViews: 0,});}@@ -118,31 +132,85 @@ export default async function handle((view) => !allExcludedViews.map((view) => view.id).includes(view.id),);- // get the reactions for the filtered views- const groupedReactions = await prisma.reaction.groupBy({- by: ["type"],- where: {- view: {- documentId: docId,- id: { notIn: allExcludedViews.map((view) => view.id) },- },- },- _count: { type: true },- });-- const duration = await getTotalAvgPageDuration({- documentId: docId,- excludedLinkIds: "",- excludedViewIds: allExcludedViews.map((view) => view.id).join(","),- since: 0,- });+ const [duration, totalDocumentDuration] = await Promise.all([+ getTotalAvgPageDuration({+ documentId: docId,+ excludedLinkIds: "",+ excludedViewIds: allExcludedViews.map((view) => view.id).join(","),+ since: 0,+ }),+ getTotalDocumentDuration({+ documentId: docId,+ excludedLinkIds: "",+ excludedViewIds: allExcludedViews.map((view) => view.id).join(","),+ since: 0,+ }),+ ]);- const totalDocumentDuration = await getTotalDocumentDuration({- documentId: docId,- excludedLinkIds: "",- excludedViewIds: allExcludedViews.map((view) => view.id).join(","),- since: 0,- });+ // Calculate average completion rate for all filtered views+ let avgCompletionRate = 0;+ if (filteredViews.length > 0) {+ if (document.type === "video") {+ // For video documents, calculate based on unique watch time+ const videoEvents = await getVideoEventsByDocument({+ document_id: docId,+ });++ const completionRates = await Promise.all(+ filteredViews.map(async (view) => {+ const viewEvents =+ videoEvents?.data.filter(+ (event: any) =>+ event.view_id === view.id &&+ ["played", "muted", "unmuted", "rate_changed"].includes(+ event.event_type,+ ) &&+ event.end_time > event.start_time &&+ event.end_time - event.start_time >= 1,+ ) || [];++ const uniqueTimestamps = new Set<number>();+ viewEvents.forEach((event: any) => {+ for (let t = event.start_time; t < event.end_time; t++) {+ uniqueTimestamps.add(Math.floor(t));+ }+ });++ const videoLength = document.versions[0]?.length || 0;+ return videoLength > 0+ ? Math.min(100, (uniqueTimestamps.size / videoLength) * 100)+ : 0;+ }),+ );++ avgCompletionRate =+ completionRates.reduce((sum, rate) => sum + rate, 0) /+ completionRates.length;+ } else {+ // For document (PDF) type, calculate based on pages viewed+ const completionRates = await Promise.all(+ filteredViews.map(async (view) => {+ const pageData = await getViewPageDuration({+ documentId: docId,+ viewId: view.id,+ since: 0,+ });++ const relevantVersion = document.versions.find(+ (version) => version.createdAt <= view.viewedAt,+ );+ const numPages =+ relevantVersion?.numPages || document.numPages || 0;++ return numPages > 0 ? (pageData.data.length / numPages) * 100 : 0;+ }),+ );++ avgCompletionRate =+ completionRates.reduce((sum, rate) => sum + rate, 0) /+ completionRates.length;+ }+ }const stats = {views: filteredViews,@@ -150,7 +218,7 @@ export default async function handle(total_duration:(totalDocumentDuration.data[0].sum_duration * 1.0) /filteredViews.length,- groupedReactions,+ avgCompletionRate: Math.round(avgCompletionRate),totalViews: filteredViews.length,};diff --git a/pages/dashboard.tsx b/pages/dashboard.tsxindex 138c93e0..cd3a533c 100644--- a/pages/dashboard.tsx+++ b/pages/dashboard.tsx@@ -8,6 +8,9 @@ import { BarChart3 } from "lucide-react";import { toast } from "sonner";import useSWR from "swr";+import { usePlan } from "@/lib/swr/use-billing";+import { fetcher } from "@/lib/utils";+import { AnalyticsCard } from "@/components/analytics/analytics-card";import DashboardViewsChart from "@/components/analytics/dashboard-views-chart";import DocumentsTable from "@/components/analytics/documents-table";@@ -21,9 +24,6 @@ import VisitorsTable from "@/components/analytics/visitors-table";import AppLayout from "@/components/layouts/app";import { TabMenu } from "@/components/tab-menu";-import { usePlan } from "@/lib/swr/use-billing";-import { fetcher } from "@/lib/utils";-interface OverviewData {counts: {links: number;@@ -174,7 +174,7 @@ export default function DashboardPage() {count: overview?.counts.visitors,},{- label: "Recent Visits",+ label: "Recent Views",href: `/dashboard?interval=${interval}&type=views`,value: "views",currentValue: type,