Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add pagination to visitor data
Marc Seitz04f272bc0a49
diff --git a/components/ui/pagination.tsx b/components/ui/pagination.tsxnew file mode 100644index 00000000..d13638bf--- /dev/null+++ b/components/ui/pagination.tsx@@ -0,0 +1,128 @@+import * as React from "react";+import { ChevronLeft, ChevronRight, MoreHorizontal } from "lucide-react";++import { cn } from "@/lib/utils";+import { ButtonProps, buttonVariants } from "@/components/ui/button";++const Pagination = ({ className, ...props }: React.ComponentProps<"nav">) => (+ <nav+ role="navigation"+ aria-label="pagination"+ className={cn("mx-auto flex w-full justify-center", className)}+ {...props}+ />+);+Pagination.displayName = "Pagination";++const PaginationContent = React.forwardRef<+ HTMLUListElement,+ React.ComponentProps<"ul">+>(({ className, ...props }, ref) => (+ <ul+ ref={ref}+ className={cn("flex flex-row items-center gap-1", className)}+ {...props}+ />+));+PaginationContent.displayName = "PaginationContent";++const PaginationItem = React.forwardRef<+ HTMLLIElement,+ React.ComponentProps<"li">+>(({ className, ...props }, ref) => (+ <li ref={ref} className={cn("", className)} {...props} />+));+PaginationItem.displayName = "PaginationItem";++type PaginationLinkProps = {+ isActive?: boolean;+ disabled?: boolean;+} & Pick<ButtonProps, "size"> &+ React.ComponentProps<"a">;++const PaginationLink = ({+ className,+ isActive,+ size = "icon",+ ...props+}: PaginationLinkProps) => (+ <a+ aria-current={isActive ? "page" : undefined}+ className={cn(+ buttonVariants({+ variant: isActive ? "outline" : "ghost",+ size,+ }),+ className,+ )}+ {...props}+ />+);+PaginationLink.displayName = "PaginationLink";++const PaginationPrevious = ({+ className,+ disabled,+ ...props+}: React.ComponentProps<typeof PaginationLink>) => (+ <PaginationLink+ aria-label="Go to previous page"+ size="default"+ className={cn(+ "gap-1 pl-2.5",+ disabled ? "pointer-events-none opacity-50" : "",+ className,+ )}+ {...props}+ >+ <ChevronLeft className="h-4 w-4" />+ <span>Previous</span>+ </PaginationLink>+);+PaginationPrevious.displayName = "PaginationPrevious";++const PaginationNext = ({+ className,+ disabled,+ ...props+}: React.ComponentProps<typeof PaginationLink>) => (+ <PaginationLink+ aria-label="Go to next page"+ size="default"+ className={cn(+ "gap-1 pr-2.5",+ disabled ? "pointer-events-none opacity-50" : "",+ className,+ )}+ {...props}+ >+ <span>Next</span>+ <ChevronRight className="h-4 w-4" />+ </PaginationLink>+);+PaginationNext.displayName = "PaginationNext";++const PaginationEllipsis = ({+ className,+ ...props+}: React.ComponentProps<"span">) => (+ <span+ aria-hidden+ className={cn("flex h-9 w-9 items-center justify-center", className)}+ {...props}+ >+ <MoreHorizontal className="h-4 w-4" />+ <span className="sr-only">More pages</span>+ </span>+);+PaginationEllipsis.displayName = "PaginationEllipsis";++export {+ Pagination,+ PaginationContent,+ PaginationEllipsis,+ PaginationItem,+ PaginationLink,+ PaginationNext,+ PaginationPrevious,+};diff --git a/components/visitors/visitors-table.tsx b/components/visitors/visitors-table.tsxindex cabb73aa..e479da20 100644--- a/components/visitors/visitors-table.tsx+++ b/components/visitors/visitors-table.tsx@@ -32,10 +32,22 @@ import { BadgeTooltip } from "@/components/ui/tooltip";import { usePlan } from "@/lib/swr/use-billing";import { UpgradePlanModal } from "../billing/upgrade-plan-modal";import { Button } from "../ui/button";+import { useState } from "react";+import {+ Pagination,+ PaginationContent,+ PaginationEllipsis,+ PaginationItem,+ PaginationLink,+ PaginationNext,+ PaginationPrevious,+} from "../ui/pagination";export default function VisitorsTable({ numPages }: { numPages: number }) {- const { views } = useDocumentVisits();+ const [currentPage, setCurrentPage] = useState<number>(1);+ const limit = 10; // Set the number of items per page+ const { views, loading, error } = useDocumentVisits(currentPage, limit);const { plan } = usePlan();const isFreePlan = plan?.plan === "free";@@ -228,6 +240,57 @@ export default function VisitorsTable({ numPages }: { numPages: number }) {</TableBody></Table></div>+ {/* Pagination Controls */}+ <div className="mt-2 w-full flex items-center">+ <div className="text-sm w-full">+ Showing <span className="font-semibold">10</span> of{" "}+ {views?.totalViews} visits+ </div>+ <Pagination className="justify-end">+ <PaginationContent>+ <PaginationItem>+ <PaginationPrevious+ onClick={() => setCurrentPage(currentPage - 1)}+ disabled={currentPage === 1}+ />+ </PaginationItem>+ {currentPage !== 1 ? (+ <PaginationItem>+ <PaginationLink onClick={() => setCurrentPage(1)}>+ {1}+ </PaginationLink>+ </PaginationItem>+ ) : null}++ <PaginationItem>+ <PaginationLink isActive>{currentPage}</PaginationLink>+ </PaginationItem>++ {views?.totalViews &&+ currentPage !== Math.ceil(views?.totalViews / 10) ? (+ <PaginationItem>+ <PaginationLink+ onClick={() =>+ setCurrentPage(Math.ceil(views?.totalViews / 10))+ }+ >+ {Math.ceil(views?.totalViews / 10)}+ </PaginationLink>+ </PaginationItem>+ ) : null}+ <PaginationItem>+ <PaginationNext+ onClick={() => setCurrentPage(currentPage + 1)}+ disabled={+ views?.totalViews+ ? currentPage === Math.ceil(views?.totalViews / 10)+ : true+ }+ />+ </PaginationItem>+ </PaginationContent>+ </Pagination>+ </div></div>);}diff --git a/lib/swr/use-document.ts b/lib/swr/use-document.tsindex d2fc362a..48b2e6e0 100644--- a/lib/swr/use-document.ts+++ b/lib/swr/use-document.ts@@ -1,5 +1,6 @@import { useRouter } from "next/router";import useSWR from "swr";+import useSWRImmutable from "swr/immutable";import { fetcher } from "@/lib/utils";import { DocumentWithVersion, LinkWithViews } from "@/lib/types";import { View } from "@prisma/client";@@ -82,27 +83,29 @@ interface ViewWithDuration extends View {type TStatsData = {hiddenViewCount: number;viewsWithDuration: ViewWithDuration[];+ totalViews: number;};-export function useDocumentVisits() {+export function useDocumentVisits(page: number, limit: number) {const router = useRouter();const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;const { id } = router.query as {id: string;};- const { data: views, error } = useSWR<TStatsData>(- teamInfo?.currentTeam?.id &&- id &&- `/api/teams/${teamInfo?.currentTeam?.id}/documents/${encodeURIComponent(- id,- )}/views`,- fetcher,- {- dedupingInterval: 10000,- },- );+ const cacheKey =+ teamId && id+ ? `/api/teams/${teamInfo?.currentTeam?.id}/documents/${encodeURIComponent(+ id,+ )}/views?page=${page}&limit=${limit}`+ : null;++ const { data: views, error } = useSWR<TStatsData>(cacheKey, fetcher, {+ dedupingInterval: 20000,+ revalidateOnFocus: false,+ });return {views,diff --git a/pages/api/teams/[teamId]/documents/[id]/views/index.ts b/pages/api/teams/[teamId]/documents/[id]/views/index.tsindex 0efd6595..20b03fb2 100644--- a/pages/api/teams/[teamId]/documents/[id]/views/index.ts+++ b/pages/api/teams/[teamId]/documents/[id]/views/index.ts@@ -23,48 +23,81 @@ export default async function handle(// get document id and teamId from query paramsconst { teamId, id: docId } = req.query as { teamId: string; id: string };+ const page = parseInt((req.query.page as string) || "1", 10);+ const limit = parseInt((req.query.limit as string) || "10", 10);+ const offset = (page - 1) * limit;const userId = (session.user as CustomUser).id;try {- const { document } = await getTeamWithUsersAndDocument({- teamId,- userId,- docId,- checkOwner: true,- options: {- select: {- id: true,- ownerId: true,- numPages: true,- versions: {- where: { isPrimary: true },- orderBy: { createdAt: "desc" },- take: 1,- select: { numPages: true },+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId: userId,},- views: {- orderBy: {- viewedAt: "desc",- },- include: {- link: {- select: {- name: true,- },- },- feedbackResponse: {- select: {- id: true,- data: true,- },- },- },+ },+ },+ select: { plan: true },+ });++ if (!team) {+ return res.status(404).end("Team not found");+ }++ const document = await prisma.document.findUnique({+ where: { id: docId, teamId: teamId },+ select: {+ id: true,+ ownerId: true,+ numPages: true,+ versions: {+ where: { isPrimary: true },+ orderBy: { createdAt: "desc" },+ take: 1,+ select: { numPages: true },+ },+ _count: {+ select: {+ views: true,},},},});+ if (!document) {+ return res.status(404).end("Document not found");+ }++ const views = await prisma.view.findMany({+ skip: offset, // Implementing pagination+ take: limit, // Limit the number of views fetched+ where: {+ documentId: docId,+ },+ orderBy: {+ viewedAt: "desc",+ },+ include: {+ link: {+ select: {+ name: true,+ },+ },+ feedbackResponse: {+ select: {+ id: true,+ data: true,+ },+ },+ },+ });++ if (!views) {+ return res.status(404).end("Document has no views");+ }+const users = await prisma.user.findMany({where: {teams: {@@ -78,20 +111,13 @@ export default async function handle(},});- const team = await prisma.team.findUnique({- where: { id: teamId },- select: { plan: true },- });-// get the numPages from documentconst numPages =- document?.versions?.[0]?.numPages || document?.numPages || 0;-- const views = document?.views || [];+ document.versions?.[0]?.numPages || document.numPages || 0;// filter the last 20 viewsconst limitedViews =- team?.plan === "free" ? views.slice(0, LIMITS.views) : views;+ team.plan === "free" ? views.slice(0, LIMITS.views) : views;const durationsPromises = limitedViews?.map((view: { id: string }) => {return getViewPageDuration({@@ -133,6 +159,7 @@ export default async function handle(return res.status(200).json({viewsWithDuration,hiddenViewCount: views.length - limitedViews.length,+ totalViews: document._count.views || 0,});} catch (error) {log({