Skip to content

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

improvement: Improve loading speed of visitors tab

Ashish Viradiya6ed43ccb318b
diff --git a/components/visitors/contacts-document-table.tsx b/components/visitors/contacts-document-table.tsx
index eaeb111e..a22340d8 100644
--- a/components/visitors/contacts-document-table.tsx
+++ b/components/visitors/contacts-document-table.tsx
@@ -1,19 +1,14 @@
-"use client";
-
import { useRouter } from "next/router";
-import { useMemo, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
import React from "react";
import {
ColumnDef,
ExpandedState,
- SortingState,
flexRender,
getCoreRowModel,
getExpandedRowModel,
- getPaginationRowModel,
- getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
import {
@@ -22,6 +17,10 @@ import {
ChevronsUpDownIcon,
} from "lucide-react";
+import { durationFormat, timeAgo } from "@/lib/utils";
+import { fileIcon } from "@/lib/utils/get-file-icon";
+
+import { Pagination } from "@/components/documents/pagination";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import {
@@ -33,215 +32,230 @@ import {
TableRow,
} from "@/components/ui/table";
-import { durationFormat, timeAgo } from "@/lib/utils";
-import { fileIcon } from "@/lib/utils/get-file-icon";
-
-import { DataTablePagination } from "./data-table-pagination";
-
-type DocumentView = {
+type ViewerView = {
documentId: string;
document: {
- name: string;
- type: string;
+ name: string | null;
+ type: string | null;
};
lastViewed: Date;
totalDuration: number;
viewCount: number;
};
-const columns: ColumnDef<DocumentView>[] = [
- {
- accessorKey: "document",
- header: "Document Name",
- cell: ({ row }) => {
- const view = row.original;
- return (
- <div className="flex items-center overflow-visible sm:space-x-3">
- {fileIcon({
- fileType: view.document.type ?? "",
- className: "h-7 w-7",
- isLight: true,
- })}
- <div className="min-w-0 flex-1">
- <div className="focus:outline-none">
- <p className="flex items-center gap-x-2 overflow-visible text-sm font-medium text-gray-800 dark:text-gray-200">
- {view.document.name}
- </p>
- </div>
- </div>
- </div>
- );
- },
- },
- {
- accessorKey: "lastViewed",
- header: ({ column }) => {
- return (
- <Button
- variant="ghost"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
- className={
- column.getIsSorted()
- ? "text-nowrap font-medium"
- : "text-nowrap font-normal"
- }
- >
- Last Viewed
- {column.getIsSorted() === "asc" ? (
- <ChevronUpIcon className="ml-2 h-4 w-4" />
- ) : column.getIsSorted() === "desc" ? (
- <ChevronDownIcon className="ml-2 h-4 w-4" />
- ) : (
- <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
- )}
- </Button>
- );
- },
- cell: ({ row }) => {
- const view = row.original;
- return (
- <time dateTime={new Date(view.lastViewed).toISOString()}>
- {timeAgo(view.lastViewed)}
- </time>
- );
- },
- sortingFn: (rowA, rowB) => {
- return (
- new Date(rowB.original.lastViewed).getTime() -
- new Date(rowA.original.lastViewed).getTime()
- );
- },
- },
- {
- accessorKey: "totalDuration",
- header: ({ column }) => {
- return (
- <Button
- variant="ghost"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
- className={
- column.getIsSorted()
- ? "text-nowrap font-medium"
- : "text-nowrap font-normal"
- }
- >
- Time Spent
- {column.getIsSorted() === "asc" ? (
- <ChevronUpIcon className="ml-2 h-4 w-4" />
- ) : column.getIsSorted() === "desc" ? (
- <ChevronDownIcon className="ml-2 h-4 w-4" />
- ) : (
- <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
- )}
- </Button>
- );
- },
- cell: ({ row }) => {
- const view = row.original;
- return (
- <div className="text-sm text-muted-foreground">
- {durationFormat(view.totalDuration)}
- </div>
- );
- },
- },
- {
- accessorKey: "viewCount",
- header: ({ column }) => {
- return (
- <Button
- variant="ghost"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
- className={
- column.getIsSorted()
- ? "text-nowrap font-medium"
- : "text-nowrap font-normal"
- }
- >
- Visits
- {column.getIsSorted() === "asc" ? (
- <ChevronUpIcon className="ml-2 h-4 w-4" />
- ) : column.getIsSorted() === "desc" ? (
- <ChevronDownIcon className="ml-2 h-4 w-4" />
- ) : (
- <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
- )}
- </Button>
- );
- },
- cell: ({ row }) => {
- const view = row.original;
- return (
- <div className="text-sm text-muted-foreground">{view.viewCount}</div>
- );
- },
- },
- // INFO: disable for now until we have more details
- // {
- // id: "expander",
- // header: () => null,
- // cell: ({ row }) => {
- // return (
- // <Button
- // variant="ghost"
- // onClick={() => {
- // row.toggleExpanded();
- // }}
- // className="p-0"
- // >
- // {row.getIsExpanded() ? (
- // <ChevronUpIcon className="h-4 w-4" />
- // ) : (
- // <ChevronDownIcon className="h-4 w-4" />
- // )}
- // </Button>
- // );
- // },
- // },
-];
-
export function ContactsDocumentsTable({
views,
+ durations = {},
+ loadingDurations = false,
+ pagination,
+ sorting,
+ onPageChange,
+ onPageSizeChange,
+ onSortChange,
}: {
- views: DocumentView[] | null | undefined;
+ views: ViewerView[] | null | undefined;
+ durations?: Record<string, number>;
+ loadingDurations?: boolean;
+ pagination?: {
+ currentPage: number;
+ pageSize: number;
+ totalItems: number;
+ totalPages: number;
+ hasNext: boolean;
+ hasPrev: boolean;
+ };
+ sorting?: {
+ sortBy: string;
+ sortOrder: string;
+ };
+ onPageChange?: (page: number) => void;
+ onPageSizeChange?: (size: number) => void;
+ onSortChange?: (sortBy: string, sortOrder: string) => void;
}) {
const router = useRouter();
- const [sorting, setSorting] = useState<SortingState>([
- { id: "lastViewed", desc: false },
- ]);
const [expanded, setExpanded] = useState<ExpandedState>({});
const data = useMemo(() => views || [], [views]);
+ const handlePageChange = (page: number) => {
+ if (onPageChange) {
+ onPageChange(page);
+ }
+ };
+
+ const handlePageSizeChange = (size: number) => {
+ if (onPageSizeChange) {
+ onPageSizeChange(size);
+ }
+ };
+
+ const handleSort = useCallback(
+ (columnId: string) => {
+ if (!onSortChange) return;
+
+ const currentSortBy = sorting?.sortBy;
+ const currentSortOrder = sorting?.sortOrder;
+
+ let newSortOrder = "desc";
+ if (currentSortBy === columnId) {
+ if (currentSortOrder === "desc") {
+ newSortOrder = "asc";
+ } else if (currentSortOrder === "asc") {
+ onSortChange("lastViewed", "desc");
+ return;
+ }
+ }
+
+ onSortChange(columnId, newSortOrder);
+ },
+ [onSortChange, sorting?.sortBy, sorting?.sortOrder],
+ );
+
+ const getSortIcon = useCallback(
+ (columnId: string) => {
+ const currentSortBy = sorting?.sortBy;
+ const currentSortOrder = sorting?.sortOrder;
+
+ if (currentSortBy !== columnId) {
+ return <ChevronsUpDownIcon className="ml-2 h-4 w-4" />;
+ }
+
+ return currentSortOrder === "asc" ? (
+ <ChevronUpIcon className="ml-2 h-4 w-4" />
+ ) : (
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
+ );
+ },
+ [sorting?.sortBy, sorting?.sortOrder],
+ );
+
+ const getSortClass = useCallback(
+ (columnId: string) => {
+ const currentSortBy = sorting?.sortBy;
+ return currentSortBy === columnId
+ ? "text-nowrap font-medium"
+ : "text-nowrap font-normal";
+ },
+ [sorting?.sortBy],
+ );
+
+ const columns: ColumnDef<ViewerView>[] = useMemo(
+ () => [
+ {
+ accessorKey: "document",
+ header: "Document Name",
+ cell: ({ row }) => {
+ const view = row.original;
+ return (
+ <div className="flex items-center overflow-visible sm:space-x-3">
+ {fileIcon({
+ fileType: view.document.type ?? "",
+ className: "h-7 w-7",
+ isLight: true,
+ })}
+ <div className="min-w-0 flex-1">
+ <div className="focus:outline-none">
+ <p className="flex items-center gap-x-2 overflow-visible text-sm font-medium text-gray-800 dark:text-gray-200">
+ {view.document.name}
+ </p>
+ </div>
+ </div>
+ </div>
+ );
+ },
+ },
+ {
+ accessorKey: "lastViewed",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => handleSort("lastViewed")}
+ className={getSortClass("lastViewed")}
+ >
+ Last Viewed
+ {getSortIcon("lastViewed")}
+ </Button>
+ );
+ },
+ cell: ({ row }) => {
+ const view = row.original;
+ return (
+ <time dateTime={new Date(view.lastViewed).toISOString()}>
+ {timeAgo(view.lastViewed)}
+ </time>
+ );
+ },
+ sortingFn: (rowA, rowB) => {
+ return (
+ new Date(rowB.original.lastViewed).getTime() -
+ new Date(rowA.original.lastViewed).getTime()
+ );
+ },
+ },
+ {
+ accessorKey: "totalDuration",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => handleSort("totalDuration")}
+ className={getSortClass("totalDuration")}
+ >
+ Time Spent
+ {getSortIcon("totalDuration")}
+ </Button>
+ );
+ },
+ cell: ({ row }) => {
+ const view = row.original;
+ const duration = durations[view.documentId] ?? view.totalDuration;
+ const isLoading = loadingDurations && !(view.documentId in durations);
+
+ if (isLoading) {
+ return <Skeleton className="h-4 w-16" />;
+ }
+
+ return (
+ <div className="text-sm text-muted-foreground">
+ {durationFormat(duration)}
+ </div>
+ );
+ },
+ },
+ {
+ accessorKey: "viewCount",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => handleSort("viewCount")}
+ className={getSortClass("viewCount")}
+ >
+ Visits
+ {getSortIcon("viewCount")}
+ </Button>
+ );
+ },
+ cell: ({ row }) => {
+ const view = row.original;
+ return <span>{view.viewCount}</span>;
+ },
+ },
+ ],
+ [durations, loadingDurations, handleSort, getSortIcon, getSortClass],
+ );
+
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
- getSortedRowModel: getSortedRowModel(),
- getPaginationRowModel: getPaginationRowModel(),
getExpandedRowModel: getExpandedRowModel(),
- onSortingChange: (updater) => {
- setSorting((old) => {
- const newSorting =
- typeof updater === "function" ? updater(old) : updater;
- if (newSorting.length > 0) {
- const [{ id, desc }] = newSorting;
- const prevSorting = old.find((s) => s.id === id);
- if (prevSorting) {
- if (prevSorting.desc && !desc) {
- // If it was descending and now ascending, reset
- return [];
- }
- }
- }
- return newSorting;
- });
- },
onExpandedChange: setExpanded,
state: {
- sorting,
expanded,
},
+ manualPagination: true,
});
if (!views) {
@@ -254,7 +268,6 @@ export function ContactsDocumentsTable({
<TableHead>Last Viewed</TableHead>
<TableHead>Time Spent</TableHead>
<TableHead>Visits</TableHead>
- <TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -275,9 +288,6 @@ export function ContactsDocumentsTable({
<TableCell>
<Skeleton className="h-4 w-[50px]" />
</TableCell>
- <TableCell>
- <Skeleton className="h-4 w-4" />
- </TableCell>
</TableRow>
))}
</TableBody>
@@ -313,36 +323,22 @@ export function ContactsDocumentsTable({
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
- <React.Fragment key={row.id}>
- <TableRow
- key={row.id}
- onClick={() => handleRowClick(row.original.documentId)}
- className="cursor-pointer"
- >
- {row.getVisibleCells().map((cell) => (
+ <TableRow
+ key={row.id}
+ onClick={() => handleRowClick(row.original.documentId)}
+ className="cursor-pointer"
+ >
+ {row.getVisibleCells().map((cell) => {
+ return (
<TableCell key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext(),
)}
</TableCell>
- ))}
- </TableRow>
- {row.getIsExpanded() && (
- <TableRow>
- <TableCell colSpan={columns.length}>
- {/* Placeholder for expanded content */}
- <div className="p-4">
- <h4 className="mb-2 font-semibold">
- Additional Details
- </h4>
- <p>Chart placeholder</p>
- <p>Rows of all visits placeholder</p>
- </div>
- </TableCell>
- </TableRow>
- )}
- </React.Fragment>
+ );
+ })}
+ </TableRow>
))
) : (
<TableRow>
@@ -350,14 +346,26 @@ export function ContactsDocumentsTable({
colSpan={columns.length}
className="h-24 text-center"
>
- No visits yet.
+ No documents viewed yet.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
- <DataTablePagination table={table} name="document" />
+
+ {pagination && pagination.totalItems > 0 && (
+ <Pagination
+ currentPage={pagination.currentPage}
+ pageSize={pagination.pageSize}
+ totalItems={pagination.totalItems}
+ totalPages={pagination.totalPages}
+ onPageChange={handlePageChange}
+ onPageSizeChange={handlePageSizeChange}
+ totalShownItems={data.length}
+ itemName="documents"
+ />
+ )}
</div>
);
}
diff --git a/components/visitors/contacts-table.tsx b/components/visitors/contacts-table.tsx
index 0eea5f15..b87fa8e6 100644
--- a/components/visitors/contacts-table.tsx
+++ b/components/visitors/contacts-table.tsx
@@ -1,26 +1,23 @@
-"use client";
-
import { useRouter } from "next/router";
-import { useMemo, useState } from "react";
+import { useCallback, useMemo } from "react";
import React from "react";
import {
ColumnDef,
- SortingState,
flexRender,
getCoreRowModel,
- getPaginationRowModel,
- getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
import {
- ArrowUpDown,
ChevronDownIcon,
ChevronUpIcon,
ChevronsUpDownIcon,
} from "lucide-react";
+import { timeAgo } from "@/lib/utils";
+
+import { Pagination } from "@/components/documents/pagination";
import { Button } from "@/components/ui/button";
import {
Table,
@@ -32,159 +29,189 @@ import {
} from "@/components/ui/table";
import { VisitorAvatar } from "@/components/visitors/visitor-avatar";
-import { timeAgo } from "@/lib/utils";
-
import { Skeleton } from "../ui/skeleton";
-import { DataTablePagination } from "./data-table-pagination";
type Viewer = {
id: string;
email: string;
- views: { viewedAt: Date }[];
+ createdAt: Date;
+ updatedAt: Date;
+ totalVisits: number;
+ lastViewed: Date | null;
};
-const columns: ColumnDef<Viewer>[] = [
- {
- accessorKey: "email",
- header: "Contact",
- cell: ({ row }) => (
- <div className="flex items-center overflow-visible sm:space-x-3">
- <VisitorAvatar viewerEmail={row.original.email} />
- <div className="min-w-0 flex-1">
- <div className="focus:outline-none">
- <p className="flex items-center gap-x-2 overflow-visible text-sm font-medium text-gray-800 dark:text-gray-200">
- {row.original.email}
- </p>
- </div>
- </div>
- </div>
- ),
- },
- {
- accessorKey: "lastViewed",
- header: ({ column }) => {
- return (
- <Button
- variant="ghost"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
- className={
- column.getIsSorted()
- ? "text-nowrap font-medium"
- : "text-nowrap font-normal"
+export function ContactsTable({
+ viewers,
+ pagination,
+ sorting,
+ onPageChange,
+ onPageSizeChange,
+ onSortChange,
+}: {
+ viewers: Viewer[] | null | undefined;
+ pagination?: {
+ currentPage: number;
+ pageSize: number;
+ totalItems: number;
+ totalPages: number;
+ hasNext: boolean;
+ hasPrev: boolean;
+ };
+ sorting?: {
+ sortBy: string;
+ sortOrder: string;
+ };
+ onPageChange?: (page: number) => void;
+ onPageSizeChange?: (size: number) => void;
+ onSortChange?: (sortBy: string, sortOrder: string) => void;
+}) {
+ const router = useRouter();
+
+ const data = useMemo(() => viewers || [], [viewers]);
+
+ const handlePageChange = (page: number) => {
+ if (onPageChange) {
+ onPageChange(page);
+ }
+ };
+
+ const handlePageSizeChange = (size: number) => {
+ if (onPageSizeChange) {
+ onPageSizeChange(size);
+ }
+ };
+
+ const handleSort = useCallback(
+ (columnId: string) => {
+ if (!onSortChange) return;
+
+ const currentSortBy = sorting?.sortBy;
+ const currentSortOrder = sorting?.sortOrder;
+
+ if (currentSortBy === columnId) {
+ if (columnId === "lastViewed") {
+ if (currentSortOrder === "asc") {
+ onSortChange("lastViewed", "desc");
+ } else {
+ onSortChange("lastViewed", "asc");
}
- >
- Last Viewed
- {column.getIsSorted() === "asc" ? (
- <ChevronUpIcon className="ml-2 h-4 w-4" />
- ) : column.getIsSorted() === "desc" ? (
- <ChevronDownIcon className="ml-2 h-4 w-4" />
- ) : (
- <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
- )}
- </Button>
- );
- },
- cell: ({ row }) => {
- const lastView = row.original.views[0];
- return lastView ? (
- <time
- dateTime={new Date(lastView.viewedAt).toISOString()}
- className="text-sm text-muted-foreground"
- >
- {timeAgo(lastView.viewedAt)}
- </time>
- ) : (
- <div className="text-sm text-muted-foreground">-</div>
- );
+ } else {
+ if (currentSortOrder === "asc") {
+ onSortChange(columnId, "desc");
+ } else if (currentSortOrder === "desc") {
+ onSortChange("lastViewed", "desc");
+ }
+ }
+ } else {
+ onSortChange(columnId, "asc");
+ }
},
- sortingFn: (rowA, rowB) => {
- const dateA = rowA.original.views[0]?.viewedAt;
- const dateB = rowB.original.views[0]?.viewedAt;
+ [onSortChange, sorting?.sortBy, sorting?.sortOrder],
+ );
- if (!dateA && !dateB) return 0;
- if (!dateA) return 1;
- if (!dateB) return -1;
+ const getSortIcon = useCallback(
+ (columnId: string) => {
+ const currentSortBy = sorting?.sortBy;
+ const currentSortOrder = sorting?.sortOrder;
- const timeA =
- dateA instanceof Date ? dateA.getTime() : new Date(dateA).getTime();
- const timeB =
- dateB instanceof Date ? dateB.getTime() : new Date(dateB).getTime();
+ if (currentSortBy !== columnId) {
+ return <ChevronsUpDownIcon className="ml-2 h-4 w-4" />;
+ }
- return timeB - timeA; // Sort in descending order (most recent first)
- },
- },
- {
- accessorKey: "totalVisits",
- header: ({ column }) => {
- return (
- <Button
- variant="ghost"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
- className={
- column.getIsSorted()
- ? "text-nowrap font-medium"
- : "text-nowrap font-normal"
- }
- >
- Total Visits
- {column.getIsSorted() === "asc" ? (
- <ChevronDownIcon className="ml-2 h-4 w-4" />
- ) : column.getIsSorted() === "desc" ? (
- <ChevronUpIcon className="ml-2 h-4 w-4" />
- ) : (
- <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
- )}
- </Button>
+ return currentSortOrder === "asc" ? (
+ <ChevronUpIcon className="ml-2 h-4 w-4" />
+ ) : (
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
);
},
- cell: ({ row }) => (
- <div className="text-sm text-muted-foreground">
- {row.original.views.length}
- </div>
- ),
- sortingFn: (rowA, rowB) =>
- rowA.original.views.length - rowB.original.views.length,
- },
-];
+ [sorting?.sortBy, sorting?.sortOrder],
+ );
-export function ContactsTable({
- viewers,
-}: {
- viewers: Viewer[] | null | undefined;
-}) {
- const router = useRouter();
- const [sorting, setSorting] = useState<SortingState>([
- { id: "lastViewed", desc: false },
- ]);
+ const getSortClass = useCallback(
+ (columnId: string) => {
+ const currentSortBy = sorting?.sortBy;
+ return currentSortBy === columnId
+ ? "text-nowrap font-medium"
+ : "text-nowrap font-normal";
+ },
+ [sorting?.sortBy],
+ );
- const data = useMemo(() => viewers || [], [viewers]);
+ const columns: ColumnDef<Viewer>[] = useMemo(
+ () => [
+ {
+ accessorKey: "email",
+ header: "Contact",
+ cell: ({ row }) => (
+ <div className="flex items-center overflow-visible sm:space-x-3">
+ <VisitorAvatar viewerEmail={row.original.email} />
+ <div className="min-w-0 flex-1">
+ <div className="focus:outline-none">
+ <p className="flex items-center gap-x-2 overflow-visible text-sm font-medium text-gray-800 dark:text-gray-200">
+ {row.original.email}
+ </p>
+ </div>
+ </div>
+ </div>
+ ),
+ },
+ {
+ accessorKey: "lastViewed",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => handleSort("lastViewed")}
+ className={getSortClass("lastViewed")}
+ >
+ Last Viewed
+ {getSortIcon("lastViewed")}
+ </Button>
+ );
+ },
+ cell: ({ row }) => {
+ const lastView = row.original.lastViewed;
+ return lastView ? (
+ <time
+ dateTime={new Date(lastView).toISOString()}
+ className="text-sm text-muted-foreground"
+ >
+ {timeAgo(lastView)}
+ </time>
+ ) : (
+ <div className="text-sm text-muted-foreground">-</div>
+ );
+ },
+ },
+ {
+ accessorKey: "totalVisits",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => handleSort("totalVisits")}
+ className={getSortClass("totalVisits")}
+ >
+ Total Visits
+ {getSortIcon("totalVisits")}
+ </Button>
+ );
+ },
+ cell: ({ row }) => (
+ <div className="text-sm text-muted-foreground">
+ {row.original.totalVisits}
+ </div>
+ ),
+ },
+ ],
+ [handleSort, getSortIcon, getSortClass],
+ );
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
- getSortedRowModel: getSortedRowModel(),
- getPaginationRowModel: getPaginationRowModel(),
- onSortingChange: (updater) => {
- setSorting((old) => {
- const newSorting =
- typeof updater === "function" ? updater(old) : updater;
- if (newSorting.length > 0) {
- const [{ id, desc }] = newSorting;
- const prevSorting = old.find((s) => s.id === id);
- if (prevSorting) {
- if (prevSorting.desc && !desc) {
- // If it was descending and now ascending, reset
- return [];
- }
- }
- }
- return newSorting;
- });
- },
- state: {
- sorting,
- },
+ manualPagination: true,
});
if (!viewers) {
@@ -278,7 +305,19 @@ export function ContactsTable({
</TableBody>
</Table>
</div>
- <DataTablePagination table={table} name="visitor" />
+
+ {pagination && pagination.totalItems > 0 && (
+ <Pagination
+ currentPage={pagination.currentPage}
+ pageSize={pagination.pageSize}
+ totalItems={pagination.totalItems}
+ totalPages={pagination.totalPages}
+ onPageChange={handlePageChange}
+ onPageSizeChange={handlePageSizeChange}
+ totalShownItems={data.length}
+ itemName="visitors"
+ />
+ )}
</div>
);
}
diff --git a/lib/swr/use-viewer.ts b/lib/swr/use-viewer.ts
index 008e2744..f8524e20 100644
--- a/lib/swr/use-viewer.ts
+++ b/lib/swr/use-viewer.ts
@@ -1,35 +1,96 @@
import { useRouter } from "next/router";
import { useTeam } from "@/context/team-context";
-import { View, Viewer } from "@prisma/client";
import useSWR from "swr";
+import { useMemo } from "react";
import { fetcher } from "@/lib/utils";
-type ViewerWithViews = Viewer & {
+type ViewerWithViews = {
+ id: string;
+ email: string;
+ createdAt: Date;
+ updatedAt: Date;
views: {
documentId: string;
viewCount: number;
- viewIds: string[];
lastViewed: Date;
+ document: {
+ id: string;
+ name: string | null;
+ type: string | null;
+ contentType: string | null;
+ };
+ totalDuration: number;
}[];
+ pagination?: {
+ currentPage: number;
+ pageSize: number;
+ totalItems: number;
+ totalPages: number;
+ hasNext: boolean;
+ hasPrev: boolean;
+ };
+ sorting?: {
+ sortBy: string;
+ sortOrder: string;
+ };
};
-export default function useViewer() {
+export default function useViewer(
+ page: number = 1,
+ pageSize: number = 10,
+ sortBy: string = "lastViewed",
+ sortOrder: string = "desc"
+) {
const router = useRouter();
const teamInfo = useTeam();
const teamId = teamInfo?.currentTeam?.id;
const { id } = router.query;
+ const paginationParam = `page=${page}&pageSize=${pageSize}`;
+ const sortingParam = `&sortBy=${sortBy}&sortOrder=${sortOrder}`;
+
const { data: viewer, error } = useSWR<ViewerWithViews>(
- teamId && id && `/api/teams/${teamId}/viewers/${id}`,
+ teamId && id ? `/api/teams/${teamId}/viewers/${id}?${paginationParam}${sortingParam}` : null,
fetcher,
+ {
+ revalidateOnFocus: false,
+ dedupingInterval: 30000,
+ revalidateIfStale: false,
+ }
);
+ const shouldFetchDurations = viewer && viewer.views && viewer.views.length > 0;
+
+ const { data: durationsResponse, isLoading: loadingDurations, error: durationsError } = useSWR<{ durations: Record<string, number> }>(
+ shouldFetchDurations
+ ? `/api/teams/${teamId}/viewers/${id}?${paginationParam}${sortingParam}&withDuration=true`
+ : null,
+ fetcher,
+ {
+ revalidateOnFocus: false,
+ dedupingInterval: 60000,
+ errorRetryCount: 1,
+ errorRetryInterval: 5000,
+ revalidateIfStale: false,
+ }
+ );
+
+ const durations = useMemo(() => {
+ return durationsResponse?.durations || {};
+ }, [durationsResponse]);
+
+ const isMainLoading = !viewer && !error;
+ const isDurationsLoading = shouldFetchDurations && loadingDurations && !durationsError;
+
return {
- viewer,
- loading: !viewer && !error,
- error,
+ viewer, // Always use the main viewer data
+ durations,
+ loadingDurations: isDurationsLoading,
+ loading: isMainLoading,
+ error: error || durationsError,
+ hasData: Boolean(viewer),
};
}
diff --git a/lib/swr/use-viewers.ts b/lib/swr/use-viewers.ts
index f6f5693d..8d99e980 100644
--- a/lib/swr/use-viewers.ts
+++ b/lib/swr/use-viewers.ts
@@ -6,7 +6,37 @@ import useSWR from "swr";
import { fetcher } from "@/lib/utils";
-export default function useViewers() {
+type ViewerWithStats = {
+ id: string;
+ email: string;
+ createdAt: Date;
+ updatedAt: Date;
+ totalVisits: number;
+ lastViewed: Date | null;
+};
+
+type ViewersResponse = {
+ viewers: ViewerWithStats[];
+ pagination: {
+ currentPage: number;
+ pageSize: number;
+ totalItems: number;
+ totalPages: number;
+ hasNext: boolean;
+ hasPrev: boolean;
+ };
+ sorting: {
+ sortBy: string;
+ sortOrder: string;
+ };
+};
+
+export default function useViewers(
+ page: number = 1,
+ pageSize: number = 10,
+ sortBy: string = "lastViewed",
+ sortOrder: string = "desc"
+) {
const router = useRouter();
const teamInfo = useTeam();
const teamId = teamInfo?.currentTeam?.id;
@@ -14,13 +44,18 @@ export default function useViewers() {
const queryParams = router.query;
const searchQuery = queryParams["search"];
+ const searchParam = searchQuery ? `&query=${searchQuery}` : "";
+ const paginationParam = `page=${page}&pageSize=${pageSize}`;
+ const sortingParam = `&sortBy=${sortBy}&sortOrder=${sortOrder}`;
+
const {
- data: viewers,
+ data: response,
isValidating,
error,
- } = useSWR<Viewer[]>(
- teamId &&
- `/api/teams/${teamId}/viewers${searchQuery ? `?query=${searchQuery}` : ""}`,
+ } = useSWR<ViewersResponse>(
+ teamId
+ ? `/api/teams/${teamId}/viewers?${paginationParam}${searchParam}${sortingParam}`
+ : null,
fetcher,
{
revalidateOnFocus: false,
@@ -30,9 +65,11 @@ export default function useViewers() {
);
return {
- viewers,
+ viewers: response?.viewers,
+ pagination: response?.pagination,
+ sorting: response?.sorting,
isValidating,
- loading: !viewers && !error,
+ loading: !response && !error,
isFiltered: !!searchQuery,
error,
};
diff --git a/pages/api/teams/[teamId]/viewers/[id]/index.ts b/pages/api/teams/[teamId]/viewers/[id]/index.ts
index 8a46f5ae..5f20b26e 100644
--- a/pages/api/teams/[teamId]/viewers/[id]/index.ts
+++ b/pages/api/teams/[teamId]/viewers/[id]/index.ts
@@ -5,8 +5,10 @@ import { getServerSession } from "next-auth/next";
import { errorhandler } from "@/lib/errorHandler";
import prisma from "@/lib/prisma";
+import { redis } from "@/lib/redis";
import { getDocumentDurationPerViewer } from "@/lib/tinybird";
import { CustomUser } from "@/lib/types";
+import { Prisma } from "@prisma/client";
export default async function handle(
req: NextApiRequest,
@@ -19,7 +21,26 @@ export default async function handle(
return res.status(401).end("Unauthorized");
}
- const { teamId, id } = req.query as { teamId: string; id: string };
+ const { teamId, id, page, pageSize, sortBy, sortOrder, withDuration } = req.query as {
+ teamId: string;
+ id: string;
+ page?: string;
+ pageSize?: string;
+ sortBy?: string;
+ sortOrder?: string;
+ withDuration?: string;
+ };
+
+ // Parse pagination parameters
+ const currentPage = parseInt(page || "1", 10);
+ const limit = parseInt(pageSize || "10", 10);
+ const offset = (currentPage - 1) * limit;
+
+ // Parse sorting parameters
+ const validSortFields = ["lastViewed", "totalDuration", "viewCount"];
+ const validSortOrders = ["asc", "desc"];
+ const sort = validSortFields.includes(sortBy || "") ? sortBy : "lastViewed";
+ const order = validSortOrders.includes(sortOrder || "") ? sortOrder : "desc";
const userId = (session.user as CustomUser).id;
@@ -41,112 +62,311 @@ export default async function handle(
const viewer = await prisma.viewer.findUnique({
where: { id, teamId },
- include: {
- views: {
- where: {
- documentId: {
- not: null,
- },
- },
- },
+ select: {
+ id: true,
+ email: true,
+ createdAt: true,
+ updatedAt: true,
},
});
- // same but for documentId
- const groupedViewsByDocumentId = viewer?.views.reduce(
- (
- acc: Record<
- string,
- {
- documentId: string;
- viewCount: number;
- viewIds: string[];
- lastViewed: Date;
+ if (!viewer) {
+ return res.status(404).json({ message: "Viewer not found" });
+ }
+
+ // Create cache key for this specific query
+ const cacheKey = `viewer-data:${teamId}:${id}:${currentPage}:${limit}:${sort}:${order}`;
+
+ // If withDuration=true, try to get cached data from Redis first
+ if (withDuration === "true") {
+ const cachedData = await redis.get(cacheKey);
+
+ if (cachedData) {
+ try {
+ const groupedViews = typeof cachedData === 'string' ? JSON.parse(cachedData) : cachedData;
+
+ if (!groupedViews || groupedViews.length === 0) {
+ return res.status(200).json({ durations: {} });
}
- >,
- view,
- ) => {
- const key = view.documentId!;
- if (!acc[key]) {
- acc[key] = {
- documentId: view.documentId ?? "",
- viewCount: 0,
- viewIds: [],
- lastViewed: new Date(0),
- };
- }
- acc[key].viewCount++;
- acc[key].viewIds.push(view.id);
- if (view.viewedAt > acc[key].lastViewed) {
- acc[key].lastViewed = view.viewedAt;
+
+ // Try to get cached durations from Redis
+ const durationCacheKey = `durations:${teamId}:${id}:${currentPage}:${limit}:${sort}:${order}`;
+ let durationsMap: Record<string, number> = {};
+ const cachedDurations = await redis.get(durationCacheKey);
+
+ if (cachedDurations) {
+ const parsedDurations = typeof cachedDurations === 'string' ? JSON.parse(cachedDurations) : cachedDurations;
+ durationsMap = parsedDurations;
+ } else {
+ // Process durations in smaller batches
+ const batchSize = 5;
+
+ for (let i = 0; i < groupedViews.length; i += batchSize) {
+ const batch = groupedViews.slice(i, i + batchSize);
+
+ const batchPromises = batch.map(async (view: any) => {
+ try {
+ const durationResult = await getDocumentDurationPerViewer({
+ documentId: view.documentId,
+ viewIds: view.viewIds.join(","),
+ });
+ return {
+ documentId: view.documentId,
+ totalDuration: durationResult.data[0]?.sum_duration || 0,
+ };
+ } catch (error) {
+ console.error(`Error fetching duration for document ${view.documentId}:`, error);
+ return {
+ documentId: view.documentId,
+ totalDuration: 0,
+ };
+ }
+ });
+
+ const batchResults = await Promise.all(batchPromises);
+ batchResults.forEach(result => {
+ durationsMap[result.documentId] = result.totalDuration;
+ });
+ }
+
+ await redis.set(durationCacheKey, JSON.stringify(durationsMap), { ex: 600 });
+ }
+
+ return res.status(200).json({ durations: durationsMap });
+
+ } catch (error) {
+ console.error("Error processing cached data:", error);
}
- return acc;
- },
- {},
- );
-
- // get the document details for each documentId
- let documentDetails: {
- id: string;
- name: string | null;
- type: string | null;
- contentType: string | null;
- }[] = [];
- if (groupedViewsByDocumentId) {
- documentDetails = await prisma.document.findMany({
- where: {
- id: {
- in: Object.keys(groupedViewsByDocumentId),
- },
- },
- select: {
- id: true,
- name: true,
- type: true,
- contentType: true,
- },
+ }
+ }
+
+ // Optimize: Use different approaches based on sort type
+ let groupedViews: Array<{
+ documentId: string;
+ viewCount: number;
+ lastViewed: Date;
+ documentName: string | null;
+ documentType: string | null;
+ documentContentType: string | null;
+ viewIds: string[];
+ totalDuration?: number;
+ }>;
+
+ const orderDirection = order?.toUpperCase() || "DESC";
+
+ if (sort === "totalDuration") {
+ const allDocuments = await prisma.$queryRaw`
+ SELECT
+ v."documentId",
+ COUNT(v.id)::int as "viewCount",
+ MAX(v."viewedAt") as "lastViewed",
+ d.name as "documentName",
+ d.type as "documentType",
+ d."contentType" as "documentContentType",
+ ARRAY_AGG(v.id) as "viewIds"
+ FROM "View" v
+ INNER JOIN "Document" d ON v."documentId" = d.id
+ WHERE v."viewerId" = ${id}
+ AND v."documentId" IS NOT NULL
+ GROUP BY v."documentId", d.name, d.type, d."contentType"
+ ` as Array<{
+ documentId: string;
+ viewCount: number;
+ lastViewed: Date;
+ documentName: string | null;
+ documentType: string | null;
+ documentContentType: string | null;
+ viewIds: string[];
+ }>;
+
+ // Check for cached durations in Redis for totalDuration sorting
+ const durationCacheKey = `durations:${teamId}:${id}:all:${sort}:${order}`;
+ let documentsWithDurations;
+ const cachedDurations = await redis.get(durationCacheKey);
+
+ if (cachedDurations) {
+ const parsedDurations = typeof cachedDurations === 'string' ? JSON.parse(cachedDurations) : cachedDurations;
+ documentsWithDurations = allDocuments.map(doc => ({
+ ...doc,
+ totalDuration: parsedDurations[doc.documentId] || 0
+ }));
+ } else {
+ documentsWithDurations = await Promise.all(
+ allDocuments.map(async (doc) => {
+ try {
+ const durationResult = await getDocumentDurationPerViewer({
+ documentId: doc.documentId,
+ viewIds: doc.viewIds.join(","),
+ });
+ const totalDuration = durationResult.data[0]?.sum_duration || 0;
+ return { ...doc, totalDuration };
+ } catch (error) {
+ console.error(`Error fetching duration for document ${doc.documentId}:`, error);
+ return { ...doc, totalDuration: 0 };
+ }
+ })
+ );
+
+ // Cache durations to Redis for 10 minutes
+ const durationsMap = Object.fromEntries(
+ documentsWithDurations.map(doc => [doc.documentId, doc.totalDuration])
+ );
+ await redis.set(durationCacheKey, JSON.stringify(durationsMap), { ex: 600 });
+ }
+
+ // Sort by duration
+ documentsWithDurations.sort((a, b) => {
+ return order === "asc"
+ ? a.totalDuration - b.totalDuration
+ : b.totalDuration - a.totalDuration;
});
+
+ // Apply pagination after sorting
+ groupedViews = documentsWithDurations.slice(offset, offset + limit);
+
+ } else {
+ let orderClause;
+ switch (sort) {
+ case "lastViewed":
+ orderClause = `MAX(v."viewedAt") ${orderDirection === "ASC" ? "ASC" : "DESC"}`;
+ break;
+ case "viewCount":
+ orderClause = `COUNT(v.id) ${orderDirection === "ASC" ? "ASC" : "DESC"}`;
+ break;
+ default:
+ orderClause = `MAX(v."viewedAt") ${orderDirection === "ASC" ? "ASC" : "DESC"}`;
+ }
+
+ groupedViews = await prisma.$queryRaw`
+ SELECT
+ v."documentId",
+ COUNT(v.id)::int as "viewCount",
+ MAX(v."viewedAt") as "lastViewed",
+ d.name as "documentName",
+ d.type as "documentType",
+ d."contentType" as "documentContentType",
+ ARRAY_AGG(v.id) as "viewIds"
+ FROM "View" v
+ INNER JOIN "Document" d ON v."documentId" = d.id
+ WHERE v."viewerId" = ${id}
+ AND v."documentId" IS NOT NULL
+ GROUP BY v."documentId", d.name, d.type, d."contentType"
+ ORDER BY ${Prisma.raw(orderClause)}
+ LIMIT ${limit}
+ OFFSET ${offset}
+ ` as Array<{
+ documentId: string;
+ viewCount: number;
+ lastViewed: Date;
+ documentName: string | null;
+ documentType: string | null;
+ documentContentType: string | null;
+ viewIds: string[];
+ }>;
}
- // Calculate sum_duration for each document
- const documentDurations = await Promise.all(
- Object.entries(groupedViewsByDocumentId ?? {}).map(
- async ([documentId, view]) => {
- const durationResult = await getDocumentDurationPerViewer({
- documentId,
- viewIds: view.viewIds.join(","),
- });
- return {
- documentId,
- sum_duration: durationResult.data[0].sum_duration,
- };
- },
- ),
- );
-
- // Create a map for quick lookup
- const durationMap = new Map(
- documentDurations.map((d) => [d.documentId, d.sum_duration]),
- );
-
- // create a new array with the grouped views and merge with document details
- const groupedViews = groupedViewsByDocumentId
- ? Object.values(groupedViewsByDocumentId).map((view) => {
- const document = documentDetails?.find(
- (doc) => doc.id === view.documentId,
- );
-
- return {
- ...view,
- document,
- totalDuration: durationMap.get(view.documentId) || 0,
- };
- })
- : [];
+ // Get total count for pagination
+ const totalCountResult = await prisma.$queryRaw`
+ SELECT COUNT(DISTINCT v."documentId")::int as count
+ FROM "View" v
+ WHERE v."viewerId" = ${id}
+ AND v."documentId" IS NOT NULL
+ ` as Array<{ count: number }>;
+
+ const totalItems = totalCountResult[0]?.count || 0;
+ const totalPages = Math.ceil(totalItems / limit);
+
+ // Cache the grouped views to Redis (only if not withDuration call)
+ if (withDuration !== "true") {
+ await redis.set(cacheKey, JSON.stringify(groupedViews), { ex: 300 });
+ }
+
+ // If withDuration=true, return only duration data for faster response
+ if (withDuration === "true") {
+ try {
+ const durationCacheKey = `durations:${teamId}:${id}:${currentPage}:${limit}:${sort}:${order}`;
+ let durationsMap: Record<string, number> = {};
+ const cachedDurations = await redis.get(durationCacheKey);
+
+ if (cachedDurations) {
+ const parsedDurations = typeof cachedDurations === 'string' ? JSON.parse(cachedDurations) : cachedDurations;
+ durationsMap = parsedDurations;
+ } else {
+ const batchSize = 5;
+
+ for (let i = 0; i < groupedViews.length; i += batchSize) {
+ const batch = groupedViews.slice(i, i + batchSize);
+
+ const batchPromises = batch.map(async (view) => {
+ try {
+ const durationResult = await getDocumentDurationPerViewer({
+ documentId: view.documentId,
+ viewIds: view.viewIds.join(","),
+ });
+ return {
+ documentId: view.documentId,
+ totalDuration: durationResult.data[0]?.sum_duration || 0,
+ };
+ } catch (error) {
+ console.error(`Error fetching duration for document ${view.documentId}:`, error);
+ return {
+ documentId: view.documentId,
+ totalDuration: 0,
+ };
+ }
+ });
+
+ const batchResults = await Promise.all(batchPromises);
+ batchResults.forEach(result => {
+ durationsMap[result.documentId] = result.totalDuration;
+ });
+ }
+
+ // Cache durations to Redis
+ await redis.set(durationCacheKey, JSON.stringify(durationsMap), { ex: 600 });
+ }
+
+ return res.status(200).json({ durations: durationsMap });
+
+ } catch (error) {
+ console.error("Error processing duration batches:", error);
+ // Return empty durations on error
+ const emptyDurationsMap = Object.fromEntries(
+ groupedViews.map(view => [view.documentId, 0])
+ );
+ return res.status(200).json({ durations: emptyDurationsMap });
+ }
+ }
+
+ // Standard response without durations
+ const formattedViews = groupedViews.map((view) => ({
+ documentId: view.documentId,
+ viewCount: view.viewCount,
+ lastViewed: view.lastViewed,
+ document: {
+ id: view.documentId,
+ name: view.documentName,
+ type: view.documentType,
+ contentType: view.documentContentType,
+ },
+ totalDuration: view.totalDuration || 0,
+ }));
const newViewer = {
...viewer,
- views: groupedViews,
+ views: formattedViews,
+ pagination: {
+ currentPage,
+ pageSize: limit,
+ totalItems,
+ totalPages,
+ hasNext: currentPage < totalPages,
+ hasPrev: currentPage > 1,
+ },
+ sorting: {
+ sortBy: sort,
+ sortOrder: order,
+ },
};
return res.status(200).json(newViewer);
diff --git a/pages/api/teams/[teamId]/viewers/index.ts b/pages/api/teams/[teamId]/viewers/index.ts
index 910848b8..7b3d92a6 100644
--- a/pages/api/teams/[teamId]/viewers/index.ts
+++ b/pages/api/teams/[teamId]/viewers/index.ts
@@ -6,6 +6,7 @@ import { getServerSession } from "next-auth/next";
import { errorhandler } from "@/lib/errorHandler";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
+import { Prisma } from "@prisma/client";
export default async function handle(
req: NextApiRequest,
@@ -18,10 +19,25 @@ export default async function handle(
return res.status(401).end("Unauthorized");
}
- const { query } = req.query as { query?: string };
+ const { query, page, pageSize, sortBy, sortOrder } = req.query as {
+ query?: string;
+ page?: string;
+ pageSize?: string;
+ sortBy?: string;
+ sortOrder?: string;
+ };
const { teamId } = req.query as { teamId: string };
+ const currentPage = parseInt(page || "1", 10);
+ const limit = parseInt(pageSize || "10", 10);
+ const offset = (currentPage - 1) * limit;
+
+ const validSortFields = ["lastViewed", "totalVisits"];
+ const validSortOrders = ["asc", "desc"];
+ const sort = validSortFields.includes(sortBy || "") ? sortBy : "lastViewed";
+ const order = validSortOrders.includes(sortOrder || "") ? sortOrder : "desc";
+
const userId = (session.user as CustomUser).id;
try {
@@ -40,31 +56,89 @@ export default async function handle(
return res.status(404).json({ error: "Team not found" });
}
- const viewers = await prisma.viewer.findMany({
- where: {
- teamId,
- ...(query && {
- email: {
- contains: query,
- mode: "insensitive",
- },
- }),
+ const orderDirection = order?.toUpperCase() || "DESC";
+
+ const searchCondition = query
+ ? Prisma.sql`AND LOWER(v.email) LIKE LOWER(${`%${query}%`})`
+ : Prisma.empty;
+
+ let viewers: Array<{
+ id: string;
+ email: string;
+ createdAt: Date;
+ updatedAt: Date;
+ totalVisits: number;
+ lastViewed: Date | null;
+ }>;
+
+ // Optimized query - only get essential data
+ const orderClause = sort === "lastViewed"
+ ? `view_stats."lastViewed" ${orderDirection} NULLS LAST`
+ : `COALESCE(view_stats."totalVisits", 0) ${orderDirection}, v."createdAt" DESC`;
+
+ viewers = await prisma.$queryRaw`
+ SELECT
+ v.id,
+ v.email,
+ v."createdAt",
+ v."updatedAt",
+ COALESCE(view_stats."totalVisits", 0)::int as "totalVisits",
+ view_stats."lastViewed"
+ FROM "Viewer" v
+ LEFT JOIN (
+ SELECT
+ "viewerId",
+ COUNT(*)::int as "totalVisits",
+ MAX("viewedAt") as "lastViewed"
+ FROM "View"
+ WHERE "documentId" IS NOT NULL
+ GROUP BY "viewerId"
+ ) view_stats ON v.id = view_stats."viewerId"
+ WHERE v."teamId" = ${teamId}
+ ${searchCondition}
+ ORDER BY ${Prisma.raw(orderClause)}
+ LIMIT ${limit}
+ OFFSET ${offset}
+ `;
+
+ // Get total count for pagination
+ const totalCountResult = await prisma.$queryRaw`
+ SELECT COUNT(*)::int as count
+ FROM "Viewer" v
+ WHERE v."teamId" = ${teamId}
+ ${searchCondition}
+ ` as Array<{ count: number }>;
+
+ const totalCount = totalCountResult[0]?.count || 0;
+ const totalPages = Math.ceil(totalCount / limit);
+
+ // Return clean, essential data only
+ const formattedViewers = viewers.map((viewer) => ({
+ id: viewer.id,
+ email: viewer.email,
+ createdAt: viewer.createdAt,
+ updatedAt: viewer.updatedAt,
+ totalVisits: viewer.totalVisits,
+ lastViewed: viewer.lastViewed,
+ }));
+
+ const response = {
+ viewers: formattedViewers,
+ pagination: {
+ currentPage,
+ pageSize: limit,
+ totalItems: totalCount,
+ totalPages,
+ hasNext: currentPage < totalPages,
+ hasPrev: currentPage > 1,
},
- include: {
- views: {
- orderBy: {
- viewedAt: "desc",
- },
- where: {
- documentId: {
- not: null,
- },
- },
- },
+ sorting: {
+ sortBy: sort,
+ sortOrder: order,
},
- });
+ };
- return res.status(200).json(viewers);
+ return res.status(200).json(response);
} catch (error) {
errorhandler(error, res);
}
diff --git a/pages/visitors/[id]/index.tsx b/pages/visitors/[id]/index.tsx
index 07f70495..48cda6a3 100644
--- a/pages/visitors/[id]/index.tsx
+++ b/pages/visitors/[id]/index.tsx
@@ -2,7 +2,10 @@ import ErrorPage from "next/error";
import Link from "next/link";
import { useRouter } from "next/router";
-import { useEffect } from "react";
+import { useEffect, useState } from "react";
+
+import { usePlan } from "@/lib/swr/use-billing";
+import useViewer from "@/lib/swr/use-viewer";
import AppLayout from "@/components/layouts/app";
import {
@@ -18,14 +21,38 @@ import { Skeleton } from "@/components/ui/skeleton";
import { ContactsDocumentsTable } from "@/components/visitors/contacts-document-table";
import { VisitorAvatar } from "@/components/visitors/visitor-avatar";
-import { usePlan } from "@/lib/swr/use-billing";
-import useViewer from "@/lib/swr/use-viewer";
-
export default function VisitorDetailPage() {
const router = useRouter();
const { isFree, isTrial } = usePlan();
- const { viewer, error } = useViewer();
+ const [currentPage, setCurrentPage] = useState(1);
+ const [pageSize, setPageSize] = useState(10);
+ const [sortBy, setSortBy] = useState("lastViewed");
+ const [sortOrder, setSortOrder] = useState("desc");
+
+ const { viewer, durations, loadingDurations, error } = useViewer(
+ currentPage,
+ pageSize,
+ sortBy,
+ sortOrder,
+ );
const views = viewer?.views;
+ const pagination = viewer?.pagination;
+ const sorting = viewer?.sorting;
+
+ const handlePageChange = (page: number) => {
+ setCurrentPage(page);
+ };
+
+ const handlePageSizeChange = (size: number) => {
+ setPageSize(size);
+ setCurrentPage(1);
+ };
+
+ const handleSortChange = (newSortBy: string, newSortOrder: string) => {
+ setSortBy(newSortBy);
+ setSortOrder(newSortOrder);
+ setCurrentPage(1);
+ };
useEffect(() => {
if (isFree && !isTrial) router.push("/documents");
@@ -56,8 +83,16 @@ export default function VisitorDetailPage() {
</div>
<div className="relative p-4 pt-0 sm:mx-4 sm:mt-4">
- {/* @ts-ignore */}
- <ContactsDocumentsTable views={views} />
+ <ContactsDocumentsTable
+ views={views}
+ durations={durations}
+ loadingDurations={loadingDurations}
+ pagination={pagination}
+ sorting={sorting}
+ onPageChange={handlePageChange}
+ onPageSizeChange={handlePageSizeChange}
+ onSortChange={handleSortChange}
+ />
</div>
</AppLayout>
);
diff --git a/pages/visitors/index.tsx b/pages/visitors/index.tsx
index aa8076ff..49e1a6d9 100644
--- a/pages/visitors/index.tsx
+++ b/pages/visitors/index.tsx
@@ -1,19 +1,50 @@
import { useRouter } from "next/router";
-import { useEffect } from "react";
+
+
+import { useEffect, useState } from "react";
+
+import { usePlan } from "@/lib/swr/use-billing";
+import useViewers from "@/lib/swr/use-viewers";
import AppLayout from "@/components/layouts/app";
import { SearchBoxPersisted } from "@/components/search-box";
import { Separator } from "@/components/ui/separator";
import { ContactsTable } from "@/components/visitors/contacts-table";
-import { usePlan } from "@/lib/swr/use-billing";
-import useViewers from "@/lib/swr/use-viewers";
-
export default function Visitors() {
const router = useRouter();
const { isFree, isTrial } = usePlan();
- const { viewers, isValidating, isFiltered } = useViewers();
+ const [currentPage, setCurrentPage] = useState(1);
+ const [pageSize, setPageSize] = useState(10);
+ const [sortBy, setSortBy] = useState("lastViewed");
+ const [sortOrder, setSortOrder] = useState("desc");
+
+ const { viewers, pagination, isValidating } = useViewers(
+ currentPage,
+ pageSize,
+ sortBy,
+ sortOrder,
+ );
+
+ const handlePageChange = (page: number) => {
+ setCurrentPage(page);
+ };
+
+ const handlePageSizeChange = (size: number) => {
+ setPageSize(size);
+ setCurrentPage(1);
+ };
+
+ const handleSortChange = (newSortBy: string, newSortOrder: string) => {
+ setSortBy(newSortBy);
+ setSortOrder(newSortOrder);
+ setCurrentPage(1);
+ };
+
+ useEffect(() => {
+ setCurrentPage(1);
+ }, [router.query.search]);
useEffect(() => {
if (isFree && !isTrial) router.push("/documents");
@@ -47,9 +78,15 @@ export default function Visitors() {
</div>
<div className="relative p-4 pt-0 sm:mx-4 sm:mt-4">
- {/* @ts-ignore */}
- <ContactsTable viewers={viewers} />
+ <ContactsTable
+ viewers={viewers}
+ pagination={pagination}
+ sorting={{ sortBy, sortOrder }}
+ onPageChange={handlePageChange}
+ onPageSizeChange={handlePageSizeChange}
+ onSortChange={handleSortChange}
+ />
</div>
</AppLayout>
);
-}
+}
\ No newline at end of file
diff --git a/prisma/migrations/20250624020507_indexed_view_modal/migration.sql b/prisma/migrations/20250624020507_indexed_view_modal/migration.sql
new file mode 100644
index 00000000..ab204897
--- /dev/null
+++ b/prisma/migrations/20250624020507_indexed_view_modal/migration.sql
@@ -0,0 +1,2 @@
+-- CreateIndex
+CREATE INDEX "View_viewerId_idx" ON "View"("viewerId");
diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prisma
index cdeac904..d319a3a2 100644
--- a/prisma/schema/schema.prisma
+++ b/prisma/schema/schema.prisma
@@ -296,6 +296,7 @@ model View {
@@index([documentId])
@@index([dataroomId])
@@index([dataroomViewId])
+ @@index([viewerId])
@@index([teamId])
}