Skip to content

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

feat: limit views on free plan

Marc Seitz0e4052e59750
diff --git a/components/visitors/visitors-table.tsx b/components/visitors/visitors-table.tsx
index d7d19986..cabb73aa 100644
--- a/components/visitors/visitors-table.tsx
+++ b/components/visitors/visitors-table.tsx
@@ -20,6 +20,7 @@ import ChevronDown from "@/components/shared/icons/chevron-down";
import VisitorChart from "./visitor-chart";
import { VisitorAvatar } from "./visitor-avatar";
import {
+ AlertTriangleIcon,
BadgeCheckIcon,
BadgeInfoIcon,
DownloadCloudIcon,
@@ -28,14 +29,20 @@ import {
ThumbsUpIcon,
} from "lucide-react";
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";
export default function VisitorsTable({ numPages }: { numPages: number }) {
const { views } = useDocumentVisits();
+ const { plan } = usePlan();
+ const isFreePlan = plan?.plan === "free";
+
return (
<div className="w-full">
- <div>
- <h2 className="mb-2 md:mb-4">All visitors</h2>
+ <div className="mb-2 md:mb-4">
+ <h2>All visitors</h2>
</div>
<div className="rounded-md border">
<Table>
@@ -49,17 +56,18 @@ export default function VisitorsTable({ numPages }: { numPages: number }) {
</TableRow>
</TableHeader>
<TableBody>
- {views?.length === 0 && (
- <TableRow>
- <TableCell colSpan={5}>
- <div className="w-full h-40 flex items-center justify-center">
- <p>No Data Available</p>
- </div>
- </TableCell>
- </TableRow>
- )}
- {views ? (
- views.map((view) => (
+ {views?.viewsWithDuration.length === 0 &&
+ views?.hiddenViewCount === 0 && (
+ <TableRow>
+ <TableCell colSpan={5}>
+ <div className="w-full h-40 flex items-center justify-center">
+ <p>No Data Available</p>
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+ {views?.viewsWithDuration ? (
+ views.viewsWithDuration.map((view) => (
<Collapsible key={view.id} asChild>
<>
<TableRow key={view.id} className="group/row">
@@ -194,9 +202,83 @@ export default function VisitorsTable({ numPages }: { numPages: number }) {
</TableCell>
</TableRow>
)}
+ {views?.hiddenViewCount! > 0 && (
+ <>
+ <TableRow className="">
+ <TableCell colSpan={5} className="text-left sm:text-center">
+ <div className="flex flex-col sm:flex-row items-start sm:items-center justify-center gap-1">
+ <span className="flex items-center gap-x-1">
+ <AlertTriangleIcon className="h-4 w-4 inline-block text-yellow-500" />
+ Some older visits may not be shown because your document
+ has more than 20 views.{" "}
+ </span>
+ <UpgradePlanModal clickedPlan="Pro" trigger="">
+ <button className="underline hover:text-gray-800">
+ Upgrade to see full history
+ </button>
+ </UpgradePlanModal>
+ </div>
+ </TableCell>
+ </TableRow>
+ {Array.from({ length: views?.hiddenViewCount! }).map((_, i) => (
+ <VisitorBlurred key={i} />
+ ))}
+ </>
+ )}
</TableBody>
</Table>
</div>
</div>
);
}
+
+// create a component for a blurred view of the visitor
+const VisitorBlurred = () => {
+ return (
+ <TableRow className="blur-sm">
+ <TableCell className="">
+ <div className="flex items-center sm:space-x-3 overflow-visible">
+ <VisitorAvatar viewerEmail={"[email protected]"} />
+ <div className="min-w-0 flex-1">
+ <div className="focus:outline-none">
+ <p className="text-sm font-medium text-gray-800 dark:text-gray-200 overflow-visible flex items-center gap-x-2">
+ Anonymous
+ </p>
+ <p className="text-xs sm:text-sm text-muted-foreground/60">
+ Demo link
+ </p>
+ </div>
+ </div>
+ </div>
+ </TableCell>
+ {/* Duration */}
+ <TableCell className="">
+ <div className="text-sm text-muted-foreground">
+ {durationFormat(10000)}
+ </div>
+ </TableCell>
+ {/* Completion */}
+ <TableCell className="flex justify-start">
+ <div className="text-sm text-muted-foreground">
+ <Gauge value={90} size={"small"} showValue={true} />
+ </div>
+ </TableCell>
+ {/* Last Viewed */}
+ <TableCell className="text-sm text-muted-foreground">
+ <time
+ dateTime={new Date(
+ new Date().getTime() - 30 * 24 * 60 * 60 * 1000,
+ ).toISOString()}
+ >
+ {timeAgo(new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000))}
+ </time>
+ </TableCell>
+ {/* Actions */}
+ <TableCell className="text-center sm:text-right cursor-pointer p-0">
+ <div className="flex justify-end p-5 space-x-1 [&[data-state=open]>svg.chevron]:rotate-180">
+ <ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200 chevron" />
+ </div>
+ </TableCell>
+ </TableRow>
+ );
+};
diff --git a/lib/constants.ts b/lib/constants.ts
index 147d2c26..b93b85aa 100644
--- a/lib/constants.ts
+++ b/lib/constants.ts
@@ -70,3 +70,8 @@ export const EXCLUDED_PATHS = [
"/blog",
"/view",
];
+
+// free limits
+export const LIMITS = {
+ views: 5,
+};
diff --git a/lib/swr/use-document.ts b/lib/swr/use-document.ts
index 95f2ee00..d2fc362a 100644
--- a/lib/swr/use-document.ts
+++ b/lib/swr/use-document.ts
@@ -79,6 +79,11 @@ interface ViewWithDuration extends View {
} | null;
}
+type TStatsData = {
+ hiddenViewCount: number;
+ viewsWithDuration: ViewWithDuration[];
+};
+
export function useDocumentVisits() {
const router = useRouter();
const teamInfo = useTeam();
@@ -87,7 +92,7 @@ export function useDocumentVisits() {
id: string;
};
- const { data: views, error } = useSWR<ViewWithDuration[]>(
+ const { data: views, error } = useSWR<TStatsData>(
teamInfo?.currentTeam?.id &&
id &&
`/api/teams/${teamInfo?.currentTeam?.id}/documents/${encodeURIComponent(
diff --git a/pages/api/links/[id]/visits.ts b/pages/api/links/[id]/visits.ts
index 99861c0b..b9d8bf40 100644
--- a/pages/api/links/[id]/visits.ts
+++ b/pages/api/links/[id]/visits.ts
@@ -7,6 +7,7 @@ import { getViewPageDuration } from "@/lib/tinybird";
import { getDocumentWithTeamAndUser } from "@/lib/team/helper";
import { CustomUser } from "@/lib/types";
import { errorhandler } from "@/lib/errorHandler";
+import { LIMITS } from "@/lib/constants";
export default async function handle(
req: NextApiRequest,
@@ -41,6 +42,12 @@ export default async function handle(
take: 1,
select: { numPages: true },
},
+ team: {
+ select: {
+ id: true,
+ plan: true,
+ },
+ },
},
},
},
@@ -79,7 +86,13 @@ export default async function handle(
},
});
- const durationsPromises = views.map((view) => {
+ // limit the number of views to 20 on free plan
+ const limitedViews =
+ result?.document?.team?.plan === "free"
+ ? views.slice(0, LIMITS.views)
+ : views;
+
+ const durationsPromises = limitedViews.map((view) => {
return getViewPageDuration({
documentId: view.documentId!,
viewId: view.id,
@@ -98,7 +111,7 @@ export default async function handle(
});
// Construct the response combining views and their respective durations
- const viewsWithDuration = views.map((view, index) => {
+ const viewsWithDuration = limitedViews.map((view, index) => {
// calculate the completion rate
const completionRate = numPages
? (durations[index].data.length / numPages) * 100
diff --git a/pages/api/teams/[teamId]/documents/[id]/stats.ts b/pages/api/teams/[teamId]/documents/[id]/stats.ts
index 9ab14a25..b7184b82 100644
--- a/pages/api/teams/[teamId]/documents/[id]/stats.ts
+++ b/pages/api/teams/[teamId]/documents/[id]/stats.ts
@@ -7,6 +7,7 @@ import { CustomUser } from "@/lib/types";
import { getTeamWithUsersAndDocument } from "@/lib/team/helper";
import { errorhandler } from "@/lib/errorHandler";
import { View } from "@prisma/client";
+import { LIMITS } from "@/lib/constants";
export default async function handle(
req: NextApiRequest,
@@ -32,18 +33,34 @@ export default async function handle(
const userId = (session.user as CustomUser).id;
try {
- const { document } = await getTeamWithUsersAndDocument({
- teamId,
- userId,
- docId,
- checkOwner: true,
- options: {
- include: {
- views: true,
+ const document = await prisma.document.findUnique({
+ where: {
+ id: docId,
+ teamId,
+ },
+ include: {
+ views: true,
+ team: {
+ select: {
+ plan: true,
+ },
},
},
});
+ // const { document } = await getTeamWithUsersAndDocument({
+ // teamId,
+ // userId,
+ // docId,
+ // checkOwner: true,
+ // options: {
+ // include: {
+ // views: true,
+ // team: true,
+ // },
+ // },
+ // });
+
const users = await prisma.user.findMany({
where: {
teams: {
@@ -69,15 +86,19 @@ export default async function handle(
});
}
+ // limit the number of views to 20 on free plan
+ const limitedViews =
+ document?.team?.plan === "free" ? views.slice(0, LIMITS.views) : views;
+
// exclude views from the team's members
let excludedViews: View[] = [];
if (excludeTeamMembers) {
- excludedViews = views.filter((view) => {
+ excludedViews = limitedViews.filter((view) => {
return users.some((user) => user.email === view.viewerEmail);
});
}
- const filteredViews = views.filter(
+ const filteredViews = limitedViews.filter(
(view) => !excludedViews.map((view) => view.id).includes(view.id),
);
diff --git a/pages/api/teams/[teamId]/documents/[id]/views/index.ts b/pages/api/teams/[teamId]/documents/[id]/views/index.ts
index 915dfda9..0efd6595 100644
--- a/pages/api/teams/[teamId]/documents/[id]/views/index.ts
+++ b/pages/api/teams/[teamId]/documents/[id]/views/index.ts
@@ -7,6 +7,7 @@ import { CustomUser } from "@/lib/types";
import { getTeamWithUsersAndDocument } from "@/lib/team/helper";
import { errorhandler } from "@/lib/errorHandler";
import prisma from "@/lib/prisma";
+import { LIMITS } from "@/lib/constants";
export default async function handle(
req: NextApiRequest,
@@ -77,13 +78,22 @@ export default async function handle(
},
});
+ const team = await prisma.team.findUnique({
+ where: { id: teamId },
+ select: { plan: true },
+ });
+
// get the numPages from document
const numPages =
document?.versions?.[0]?.numPages || document?.numPages || 0;
const views = document?.views || [];
- const durationsPromises = views?.map((view: { id: string }) => {
+ // filter the last 20 views
+ const limitedViews =
+ team?.plan === "free" ? views.slice(0, LIMITS.views) : views;
+
+ const durationsPromises = limitedViews?.map((view: { id: string }) => {
return getViewPageDuration({
documentId: docId,
viewId: view.id,
@@ -103,22 +113,27 @@ export default async function handle(
});
// Construct the response combining views and their respective durations
- const viewsWithDuration = views?.map((view: any, index: number) => {
- // calculate the completion rate
- const completionRate = numPages
- ? (durations[index].data.length / numPages) * 100
- : 0;
-
- return {
- ...view,
- internal: users.some((user) => user.email === view.viewerEmail), // set internal to true if view.viewerEmail is in the users list
- duration: durations[index],
- totalDuration: summedDurations[index],
- completionRate: completionRate.toFixed(),
- };
- });
+ const viewsWithDuration = limitedViews?.map(
+ (view: any, index: number) => {
+ // calculate the completion rate
+ const completionRate = numPages
+ ? (durations[index].data.length / numPages) * 100
+ : 0;
- return res.status(200).json(viewsWithDuration);
+ return {
+ ...view,
+ internal: users.some((user) => user.email === view.viewerEmail), // set internal to true if view.viewerEmail is in the users list
+ duration: durations[index],
+ totalDuration: summedDurations[index],
+ completionRate: completionRate.toFixed(),
+ };
+ },
+ );
+
+ return res.status(200).json({
+ viewsWithDuration,
+ hiddenViewCount: views.length - limitedViews.length,
+ });
} catch (error) {
log({
message: `Failed to get views for document: _${docId}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``,