Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add ability to archive views
Marc Seitza42b343d4210
diff --git a/components/visitors/visitor-avatar.tsx b/components/visitors/visitor-avatar.tsxindex 7c7ce76e..ffa40abf 100644--- a/components/visitors/visitor-avatar.tsx+++ b/components/visitors/visitor-avatar.tsx@@ -1,13 +1,19 @@+import { ArchiveIcon } from "lucide-react";+import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";import { generateGravatarHash } from "@/lib/utils";import { cn } from "@/lib/utils";+import { BadgeTooltip } from "../ui/tooltip";+export const VisitorAvatar = ({viewerEmail,+ isArchived,className,}: {viewerEmail: string | null;+ isArchived?: boolean;className?: string;}) => {// Convert email string to a simple hash@@ -38,6 +44,22 @@ export const VisitorAvatar = ({return colors[index];};+ if (isArchived) {+ return (+ <BadgeTooltip+ key="archived"+ content="Visit is archived and excluded from the document statistics"+ >+ <Avatar+ className={cn("hidden flex-shrink-0 sm:inline-flex", className)}+ >+ <AvatarFallback className="bg-gray-200/50 dark:bg-gray-200/50">+ <ArchiveIcon className="h-4 w-4" />+ </AvatarFallback>+ </Avatar>+ </BadgeTooltip>+ );+ }if (!viewerEmail) {return (<Avatar className={cn("hidden flex-shrink-0 sm:inline-flex", className)}>diff --git a/components/visitors/visitors-table.tsx b/components/visitors/visitors-table.tsxindex 062a9c53..b2e2d2b1 100644--- a/components/visitors/visitors-table.tsx+++ b/components/visitors/visitors-table.tsx@@ -1,16 +1,24 @@import { useState } from "react";+import { useTeam } from "@/context/team-context";import {AlertTriangleIcon,+ ArchiveIcon,+ ArchiveRestoreIcon,BadgeCheckIcon,BadgeInfoIcon,+ ChevronRightIcon,DownloadCloudIcon,FileBadgeIcon,FileDigitIcon,+ MoreHorizontalIcon,+ RefreshCw,ServerIcon,ThumbsDownIcon,ThumbsUpIcon,} from "lucide-react";+import { toast } from "sonner";+import { mutate } from "swr";import ChevronDown from "@/components/shared/icons/chevron-down";import {@@ -32,10 +40,18 @@ import { BadgeTooltip } from "@/components/ui/tooltip";import { usePlan } from "@/lib/swr/use-billing";import { useDocumentVisits } from "@/lib/swr/use-document";-import { durationFormat, timeAgo } from "@/lib/utils";+import { cn, durationFormat, timeAgo } from "@/lib/utils";import { UpgradePlanModal } from "../billing/upgrade-plan-modal";import { Button } from "../ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "../ui/dropdown-menu";import {Pagination,PaginationContent,@@ -49,14 +65,59 @@ import { VisitorAvatar } from "./visitor-avatar";import VisitorChart from "./visitor-chart";import VisitorUserAgent from "./visitor-useragent";-export default function VisitorsTable({ numPages }: { numPages: number }) {+export default function VisitorsTable() {+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;const [currentPage, setCurrentPage] = useState<number>(1);const limit = 10; // Set the number of items per page- const { views, loading, error } = useDocumentVisits(currentPage, limit);+ const { views, mutate: mutateViews } = useDocumentVisits(currentPage, limit);const { plan } = usePlan();const isFreePlan = plan === "free";+ const [isLoading, setIsLoading] = useState(false);+ const [isRefreshing, setIsRefreshing] = useState(false);++ const handleArchiveView = async (+ viewId: string,+ targetId: string,+ isArchived: boolean,+ ) => {+ setIsLoading(true);++ const response = await fetch(+ `/api/teams/${teamId}/views/${viewId}/archive`,+ {+ method: "PUT",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ isArchived: !isArchived,+ }),+ },+ );++ if (!response.ok) {+ toast.error("Failed to archive view");+ return;+ }++ // mutate the views on the current page+ mutateViews();+ // mutate the stats+ mutate(+ `/api/teams/${teamId}/documents/${encodeURIComponent(targetId)}/stats`,+ );++ toast.success(+ !isArchived+ ? "View successfully archived"+ : "View successfully unarchived",+ );+ setIsLoading(false);+ };+return (<div className="w-full"><div className="mb-2 md:mb-4">@@ -85,74 +146,25 @@ export default function VisitorsTable({ numPages }: { numPages: number }) {</TableRow>)}{views?.viewsWithDuration ? (- views.viewsWithDuration.map((view) => (- <Collapsible key={view.id} asChild>- <>- <TableRow key={view.id} className="group/row">+ views.viewsWithDuration.map((view) => {+ if (view.isArchived) {+ return (+ <TableRow+ key={view.id}+ className="group/row opacity-50 grayscale"+ >{/* Name */}- <TableCell className="">+ <TableCell><div className="flex items-center overflow-visible sm:space-x-3">- <VisitorAvatar viewerEmail={view.viewerEmail} />+ <VisitorAvatar+ viewerEmail={view.viewerEmail}+ isArchived+ /><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.viewerEmail ? (- <>- {view.viewerEmail}{" "}- {view.verified && (- <BadgeTooltip- content="Verified visitor"- key="verified"- >- <BadgeCheckIcon className="h-4 w-4 text-emerald-500 hover:text-emerald-600" />- </BadgeTooltip>- )}- {view.internal && (- <BadgeTooltip- content="Internal visitor"- key="internal"- >- <BadgeInfoIcon className="h-4 w-4 text-blue-500 hover:text-blue-600" />- </BadgeTooltip>- )}- {view.agreementResponse && (- <BadgeTooltip- content={`Agreed to ${view.agreementResponse.agreement.name}`}- key="nda-agreement"- >- <FileBadgeIcon className="h-4 w-4 text-emerald-500 hover:text-emerald-600" />- </BadgeTooltip>- )}- {view.downloadedAt && (- <BadgeTooltip- content={`Downloaded ${timeAgo(view.downloadedAt)}`}- key="download"- >- <DownloadCloudIcon className="h-4 w-4 text-cyan-500 hover:text-cyan-600" />- </BadgeTooltip>- )}- {view.dataroomId && (- <BadgeTooltip- content={`Dataroom Visitor`}- key="download"- >- <ServerIcon className="h-4 w-4 text-[#fb7a00] hover:text-[#fb7a00]/90" />- </BadgeTooltip>- )}- {view.feedbackResponse && (- <BadgeTooltip- content={`${view.feedbackResponse.data.question}: ${view.feedbackResponse.data.answer}`}- key="feedback"- >- {view.feedbackResponse.data.answer ===- "yes" ? (- <ThumbsUpIcon className="h-4 w-4 text-gray-500 hover:text-gray-600" />- ) : (- <ThumbsDownIcon className="h-4 w-4 text-gray-500 hover:text-gray-600" />- )}- </BadgeTooltip>- )}- </>+ <>{view.viewerEmail}</>) : ("Anonymous")}@@ -186,42 +198,225 @@ export default function VisitorsTable({ numPages }: { numPages: number }) {{timeAgo(view.viewedAt)}</time></TableCell>+{/* Actions */}- <TableCell className="cursor-pointer p-0 text-center sm:text-right">- <CollapsibleTrigger asChild>- <div className="flex justify-end space-x-1 p-5 [&[data-state=open]>svg.chevron]:rotate-180">- <ChevronDown className="chevron h-4 w-4 shrink-0 transition-transform duration-200" />- </div>- </CollapsibleTrigger>+ <TableCell className="text-center sm:text-right">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ className="h-8 w-8 p-0 group-hover/row:ring-1 group-hover/row:ring-gray-200 group-hover/row:dark:ring-gray-700"+ onClick={(e) => {+ e.stopPropagation();+ e.preventDefault();+ }}+ >+ <span className="sr-only">Open menu</span>+ <MoreHorizontalIcon className="h-4 w-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuLabel>Actions</DropdownMenuLabel>++ <DropdownMenuSeparator />+ <DropdownMenuItem+ className="text-destructive focus:bg-destructive focus:text-destructive-foreground"+ onClick={(e) => {+ e.stopPropagation();+ e.preventDefault();+ handleArchiveView(+ view.id,+ view.documentId ?? "",+ view.isArchived,+ );+ }}+ disabled={isLoading}+ >+ <ArchiveRestoreIcon className="mr-2 h-4 w-4" />+ Restore+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu></TableCell></TableRow>-- <CollapsibleContent asChild>- <>- <TableRow className="hover:bg-transparent">- <TableCell colSpan={5}>- {!isFreePlan ? (- <VisitorUserAgent viewId={view.id} />- ) : null}- <div className="pb-0.5 pl-0.5 md:pb-1 md:pl-1">- <div className="flex items-center gap-x-1 px-1">- <FileDigitIcon className="size-4" /> Document- Version {view.versionNumber}+ );+ }+ return (+ <Collapsible key={view.id} asChild>+ <>+ <CollapsibleTrigger asChild>+ <TableRow key={view.id} className="group/row">+ {/* Name */}+ <TableCell>+ <div className="flex items-center overflow-visible sm:space-x-3">+ <VisitorAvatar viewerEmail={view.viewerEmail} />+ <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.viewerEmail ? (+ <>+ {view.viewerEmail}{" "}+ {view.verified && (+ <BadgeTooltip+ content="Verified visitor"+ key="verified"+ >+ <BadgeCheckIcon className="h-4 w-4 text-emerald-500 hover:text-emerald-600" />+ </BadgeTooltip>+ )}+ {view.internal && (+ <BadgeTooltip+ content="Internal visitor"+ key="internal"+ >+ <BadgeInfoIcon className="h-4 w-4 text-blue-500 hover:text-blue-600" />+ </BadgeTooltip>+ )}+ {view.agreementResponse && (+ <BadgeTooltip+ content={`Agreed to ${view.agreementResponse.agreement.name}`}+ key="nda-agreement"+ >+ <FileBadgeIcon className="h-4 w-4 text-emerald-500 hover:text-emerald-600" />+ </BadgeTooltip>+ )}+ {view.downloadedAt && (+ <BadgeTooltip+ content={`Downloaded ${timeAgo(view.downloadedAt)}`}+ key="download"+ >+ <DownloadCloudIcon className="h-4 w-4 text-cyan-500 hover:text-cyan-600" />+ </BadgeTooltip>+ )}+ {view.dataroomId && (+ <BadgeTooltip+ content={`Dataroom Visitor`}+ key="download"+ >+ <ServerIcon className="h-4 w-4 text-[#fb7a00] hover:text-[#fb7a00]/90" />+ </BadgeTooltip>+ )}+ {view.feedbackResponse && (+ <BadgeTooltip+ content={`${view.feedbackResponse.data.question}: ${view.feedbackResponse.data.answer}`}+ key="feedback"+ >+ {view.feedbackResponse.data+ .answer === "yes" ? (+ <ThumbsUpIcon className="h-4 w-4 text-gray-500 hover:text-gray-600" />+ ) : (+ <ThumbsDownIcon className="h-4 w-4 text-gray-500 hover:text-gray-600" />+ )}+ </BadgeTooltip>+ )}+ </>+ ) : (+ "Anonymous"+ )}+ </p>+ <p className="text-xs text-muted-foreground/60 sm:text-sm">+ {view.link.name+ ? view.link.name+ : view.linkId}+ </p>+ </div></div></div>- <VisitorChart- documentId={view.documentId!}- viewId={view.id}- totalPages={view.versionNumPages}- versionNumber={view.versionNumber}- />+ </TableCell>+ {/* Duration */}+ <TableCell className="">+ <div className="text-sm text-muted-foreground">+ {durationFormat(view.totalDuration)}+ </div>+ </TableCell>+ {/* Completion */}+ <TableCell className="flex justify-start">+ <div className="text-sm text-muted-foreground">+ <Gauge+ value={view.completionRate}+ size={"small"}+ showValue={true}+ />+ </div>+ </TableCell>+ {/* Last Viewed */}+ <TableCell className="text-sm text-muted-foreground">+ <time+ dateTime={new Date(view.viewedAt).toISOString()}+ >+ {timeAgo(view.viewedAt)}+ </time>+ </TableCell>++ {/* Actions */}+ <TableCell className="text-center sm:text-right">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ className="h-8 w-8 p-0 group-hover/row:ring-1 group-hover/row:ring-gray-200 group-hover/row:dark:ring-gray-700"+ onClick={(e) => {+ e.stopPropagation();+ e.preventDefault();+ }}+ >+ <span className="sr-only">Open menu</span>+ <MoreHorizontalIcon className="h-4 w-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuLabel>Actions</DropdownMenuLabel>++ <DropdownMenuSeparator />+ <DropdownMenuItem+ className="text-destructive focus:bg-destructive focus:text-destructive-foreground"+ onClick={(e) => {+ e.stopPropagation();+ e.preventDefault();+ handleArchiveView(+ view.id,+ view.documentId ?? "",+ view.isArchived,+ );+ }}+ disabled={isLoading}+ >+ <ArchiveIcon className="mr-2 h-4 w-4" />+ Archive+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu></TableCell></TableRow>- </>- </CollapsibleContent>- </>- </Collapsible>- ))+ </CollapsibleTrigger>++ <CollapsibleContent asChild>+ <>+ <TableRow className="hover:bg-transparent">+ <TableCell colSpan={5}>+ {!isFreePlan ? (+ <VisitorUserAgent viewId={view.id} />+ ) : null}+ <div className="pb-0.5 pl-0.5 md:pb-1 md:pl-1">+ <div className="flex items-center gap-x-1 px-1">+ <FileDigitIcon className="size-4" /> Document+ Version {view.versionNumber}+ </div>+ </div>+ <VisitorChart+ documentId={view.documentId!}+ viewId={view.id}+ totalPages={view.versionNumPages}+ versionNumber={view.versionNumber}+ />+ </TableCell>+ </TableRow>+ </>+ </CollapsibleContent>+ </>+ </Collapsible>+ );+ })) : (<TableRow><TableCell className="min-w-[100px]">diff --git a/lib/swr/use-document.ts b/lib/swr/use-document.tsindex 49ff7b4f..676100e2 100644--- a/lib/swr/use-document.ts+++ b/lib/swr/use-document.ts@@ -112,15 +112,19 @@ export function useDocumentVisits(page: number, limit: number) {? `/api/teams/${teamId}/documents/${id}/views?page=${page}&limit=${limit}`: null;- const { data: views, error } = useSWR<TStatsData>(cacheKey, fetcher, {+ const {+ data: views,+ error,+ mutate,+ } = useSWR<TStatsData>(cacheKey, fetcher, {dedupingInterval: 20000,- revalidateOnFocus: false,});return {views,loading: !error && !views,error,+ mutate,};}diff --git a/lib/swr/use-stats.ts b/lib/swr/use-stats.tsindex abb6c673..79402c41 100644--- a/lib/swr/use-stats.ts+++ b/lib/swr/use-stats.ts@@ -23,6 +23,7 @@ export function useStats({// this gets the data for a document's graph of all viewsconst router = useRouter();const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;const { id } = router.query as {id: string;@@ -30,10 +31,8 @@ export function useStats({const { data: stats, error } = useSWR<TStatsData>(id &&- teamInfo?.currentTeam &&- `/api/teams/${teamInfo.currentTeam.id}/documents/${encodeURIComponent(- id,- )}/stats${excludeTeamMembers ? "?excludeTeamMembers=true" : ""}`,+ teamId &&+ `/api/teams/${teamId}/documents/${encodeURIComponent(id)}/stats${excludeTeamMembers ? "?excludeTeamMembers=true" : ""}`,fetcher,{dedupingInterval: 10000,diff --git a/lib/tinybird/endpoints/get_total_average_page_duration.pipe b/lib/tinybird/endpoints/get_total_average_page_duration.pipeindex 04244728..42122bab 100644--- a/lib/tinybird/endpoints/get_total_average_page_duration.pipe+++ b/lib/tinybird/endpoints/get_total_average_page_duration.pipe@@ -1,4 +1,4 @@-VERSION 4+VERSION 5NODE endpointSQL >@@ -10,8 +10,8 @@ SQL >WHEREdocumentId = {{ String(documentId, required=true) }}AND time >= {{ Int64(since, required=true) }}- AND linkId NOT IN {{ Array(excludedLinkIds, String) }}- AND viewId NOT IN {{ Array(excludedViewIds, String) }}+ AND linkId NOT IN splitByChar(',', {{ String(excludedLinkIds, required=True) }})+ AND viewId NOT IN splitByChar(',', {{ String(excludedViewIds, required=True) }})GROUP BY versionNumber, pageNumber, viewId)SELECT versionNumber, pageNumber, AVG(distinct_duration) AS avg_durationdiff --git a/lib/tinybird/pipes.ts b/lib/tinybird/pipes.tsindex f2c46053..992bdc76 100644--- a/lib/tinybird/pipes.ts+++ b/lib/tinybird/pipes.ts@@ -7,8 +7,8 @@ export const getTotalAvgPageDuration = tb.buildPipe({pipe: "get_total_average_page_duration__v5",parameters: z.object({documentId: z.string(),- excludedLinkIds: z.array(z.string()),- excludedViewIds: z.array(z.string()),+ excludedLinkIds: z.string().describe("Comma separated linkIds"),+ excludedViewIds: z.string().describe("Comma separated viewIds"),since: z.number(),}),data: z.object({diff --git a/pages/api/teams/[teamId]/documents/[id]/stats.ts b/pages/api/teams/[teamId]/documents/[id]/stats.tsindex 6368228e..09bac411 100644--- a/pages/api/teams/[teamId]/documents/[id]/stats.ts+++ b/pages/api/teams/[teamId]/documents/[id]/stats.ts@@ -6,7 +6,6 @@ import { getServerSession } from "next-auth/next";import { LIMITS } from "@/lib/constants";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";-import { getTeamWithUsersAndDocument } from "@/lib/team/helper";import { getTotalAvgPageDuration } from "@/lib/tinybird";import { CustomUser } from "@/lib/types";@@ -51,19 +50,6 @@ export default async function handle(},});- // const { document } = await getTeamWithUsersAndDocument({- // teamId,- // userId,- // docId,- // checkOwner: true,- // options: {- // include: {- // views: true,- // team: true,- // },- // },- // });-const users = await prisma.user.findMany({where: {teams: {@@ -89,22 +75,26 @@ export default async function handle(});}- const totalViews = views.length;+ const activeViews = views.filter((view) => !view.isArchived);+ const archivedViews = views.filter((view) => view.isArchived);// limit the number of views to 20 on free planconst limitedViews =document?.team?.plan === "free" ? views.slice(0, LIMITS.views) : views;// exclude views from the team's members- let excludedViews: View[] = [];+ let internalViews: View[] = [];if (excludeTeamMembers) {- excludedViews = limitedViews.filter((view) => {+ internalViews = limitedViews.filter((view) => {return users.some((user) => user.email === view.viewerEmail);});}+ // combined archived and internal views+ const allExcludedViews = [...internalViews, ...archivedViews];+const filteredViews = limitedViews.filter(- (view) => !excludedViews.map((view) => view.id).includes(view.id),+ (view) => !allExcludedViews.map((view) => view.id).includes(view.id),);const groupedReactions = await prisma.reaction.groupBy({@@ -112,7 +102,7 @@ export default async function handle(where: {view: {documentId: docId,- id: { notIn: excludedViews.map((view) => view.id) },+ id: { notIn: allExcludedViews.map((view) => view.id) },},},_count: { type: true },@@ -120,8 +110,8 @@ export default async function handle(const duration = await getTotalAvgPageDuration({documentId: docId,- excludedLinkIds: [],- excludedViewIds: excludedViews.map((view) => view.id),+ excludedLinkIds: "",+ excludedViewIds: allExcludedViews.map((view) => view.id).join(","),since: 0,});@@ -135,7 +125,7 @@ export default async function handle(duration,total_duration,groupedReactions,- totalViews,+ totalViews: activeViews.length,};return res.status(200).json(stats);diff --git a/pages/api/teams/[teamId]/views/[id]/archive.ts b/pages/api/teams/[teamId]/views/[id]/archive.tsnew file mode 100644index 00000000..2871074b--- /dev/null+++ b/pages/api/teams/[teamId]/views/[id]/archive.ts@@ -0,0 +1,58 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth/next";++import { errorhandler } from "@/lib/errorHandler";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "PUT") {+ // PUT /api/teams/:teamId/views/:id/archive+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const userId = (session.user as CustomUser).id;+ const { teamId, id } = req.query as { teamId: string; id: string };+ const { isArchived } = req.body;++ try {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: { some: { userId } },+ },+ });++ if (!team) {+ return res.status(403).json({ error: "Unauthorized" });+ }++ // Update the link in the database+ const updatedView = await prisma.view.update({+ where: { id, teamId },+ data: {+ isArchived: isArchived,+ },+ });++ if (!updatedView) {+ return res.status(404).json({ error: "View not found" });+ }++ return res.status(200).json(updatedView);+ } catch (error) {+ errorhandler(error, res);+ }+ }++ // We only allow PUT requests+ res.setHeader("Allow", ["PUT"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+}diff --git a/pages/documents/[id]/index.tsx b/pages/documents/[id]/index.tsxindex 8524235a..7732b6bd 100644--- a/pages/documents/[id]/index.tsx+++ b/pages/documents/[id]/index.tsx@@ -98,7 +98,7 @@ export default function DocumentPage() {/>{/* Visitors */}- <VisitorsTable numPages={primaryVersion.numPages!} />+ <VisitorsTable /><LinkSheetisOpen={isLinkSheetOpen}diff --git a/prisma/migrations/20241029000000_add_archived_view/migration.sql b/prisma/migrations/20241029000000_add_archived_view/migration.sqlnew file mode 100644index 00000000..b7fa7af1--- /dev/null+++ b/prisma/migrations/20241029000000_add_archived_view/migration.sql@@ -0,0 +1,3 @@+-- AlterTable+ALTER TABLE "View" ADD COLUMN "isArchived" BOOLEAN NOT NULL DEFAULT false;+diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 16070654..b7f08c4c 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -331,6 +331,8 @@ model View {feedbackResponse FeedbackResponse?agreementResponse AgreementResponse?+ isArchived Boolean @default(false) // Indicates if the view is archived and not counted in the analytics+teamId String?team Team? @relation(fields: [teamId], references: [id], onDelete: Cascade)