Skip to content

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

feat: update improved custom date range picker

Marc Seitz8e95d62c878d
diff --git a/components/analytics/time-range-select.tsx b/components/analytics/time-range-select.tsx
index 7f122b32..1238cb5d 100644
--- a/components/analytics/time-range-select.tsx
+++ b/components/analytics/time-range-select.tsx
@@ -1,20 +1,19 @@
-import { useRouter } from "next/navigation";
+import { useEffect, useState } from "react";
-import { Ref, useState } from "react";
-
-import { addDays, format } from "date-fns";
+import { differenceInDays, format, startOfDay, subDays } from "date-fns";
import { CalendarIcon, ChevronDown } from "lucide-react";
-import { start } from "repl";
+import { DateRange } from "react-day-picker";
+import { toast } from "sonner";
import { Button } from "@/components/ui/button";
+import { Calendar } from "@/components/ui/calendar";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
-import { DatePickerWithPresets } from "../ui/datePicker";
-import { Separator } from "../ui/separator";
+import { cn } from "@/lib/utils";
const TIME_RANGES = [
{ value: "24h", label: "Last 24 hours", shortcut: "D" },
@@ -32,8 +31,10 @@ interface TimeRangeSelectProps {
value: TimeRange;
onChange: (value: TimeRange) => void;
customRange: CustomRange;
- setCustomRange: React.Dispatch<React.SetStateAction<CustomRange>>;
+ setCustomRange: (range: CustomRange) => void;
+ onCustomRangeComplete?: (range: CustomRange) => void;
slug: React.MutableRefObject<boolean>;
+ isPremium?: boolean;
}
export function TimeRangeSelect({
@@ -41,81 +42,153 @@ export function TimeRangeSelect({
onChange,
customRange,
setCustomRange,
+ onCustomRangeComplete,
slug,
+ isPremium = false,
}: TimeRangeSelectProps) {
- const [isDatePickerShow, setIsDatePickerShow] = useState(false);
- const selectedRange =
- value !== "custom"
- ? TIME_RANGES.find((range) => range.value === value)
- : null;
+ const selectedRange = TIME_RANGES.find((range) => range.value === value);
+ const [date, setDate] = useState<DateRange | undefined>({
+ from: customRange.start,
+ to: customRange.end,
+ });
+ const [open, setOpen] = useState(false);
+
+ // Calculate the minimum allowed date (30 days ago for non-premium)
+ const minDate = isPremium ? undefined : subDays(new Date(), 30);
+
+ useEffect(() => {
+ setDate({ from: customRange.start, to: customRange.end });
+ }, [customRange]);
const handleSelectOption = (value: TimeRange) => {
- const isCustom = value === "custom";
+ // Prevent selecting custom range for non-premium users
+ if (value === "custom" && !isPremium) {
+ toast.error("Upgrade to view data beyond 30 days");
+ return;
+ }
+
onChange(value);
- setIsDatePickerShow(isCustom);
- };
- const handleDateChange = (key: "start" | "end", date: Date) => {
- setCustomRange((prev: CustomRange) => ({ ...prev, [key]: date }));
+ // Update date range based on selected preset
+ const now = new Date();
+ const end = startOfDay(now);
+ let start = startOfDay(now);
+
+ switch (value) {
+ case "24h":
+ start = subDays(end, 1);
+ break;
+ case "7d":
+ start = subDays(end, 7);
+ break;
+ case "30d":
+ start = subDays(end, 30);
+ break;
+ case "custom":
+ // Reset the date range when switching to custom
+ setDate(undefined);
+ return;
+ default:
+ return;
+ }
+
+ setCustomRange({ start, end });
+ setDate({ from: start, to: end });
slug.current = false;
+ setOpen(false);
+ };
+
+ const handleRangeChange = (range: DateRange | undefined) => {
+ setDate(range);
+ if (range?.from && range?.to) {
+ // Check if the selected range is within limits for non-premium users
+ if (
+ !isPremium &&
+ (differenceInDays(new Date(), range.from) > 30 ||
+ differenceInDays(new Date(), range.to) > 30)
+ ) {
+ toast.error("Upgrade to view data beyond 30 days");
+ return;
+ }
+
+ const newRange = { start: range.from, end: range.to };
+ setCustomRange(newRange);
+ onChange("custom");
+ slug.current = false;
+ setOpen(false);
+ onCustomRangeComplete?.(newRange);
+ } else if (range?.from) {
+ setCustomRange({ start: range.from, end: range.from });
+ onChange("custom");
+ slug.current = false;
+ }
};
return (
- <Popover>
+ <Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
- className="w-full justify-between text-left font-normal sm:inline-flex sm:min-w-[200px] md:w-fit"
+ className={cn(
+ "w-[300px] justify-between text-left font-normal",
+ !date && "text-muted-foreground",
+ )}
>
<div className="flex items-center gap-2">
- <CalendarIcon className="!size-4" />
+ <CalendarIcon className="h-4 w-4" />
<span>
- {selectedRange
- ? selectedRange.label
- : customRange.start && customRange.end
- ? `${format(customRange.start, "PP")} - ${format(customRange.end, "PP")}`
- : "Select Date Range"}
+ {value === "custom" && date?.from ? (
+ <>
+ {format(date.from, "MMM d")} -{" "}
+ {format(date.to || date.from, "MMM d, yyyy")}
+ </>
+ ) : (
+ selectedRange?.label
+ )}
</span>
</div>
- <ChevronDown className="!size-4 opacity-50" />
+ <ChevronDown className="h-4 w-4 opacity-50" />
</Button>
</PopoverTrigger>
- <PopoverContent className="w-[250px] p-1" align="end">
- <div className="grid gap-0.5">
- {TIME_RANGES.map((range) => (
- <Button
- key={range.value}
- variant={range.value === value ? "secondary" : "ghost"}
- className="justify-between"
- onClick={() => handleSelectOption(range.value)}
- >
- <span>{range.label}</span>
- <kbd className="pointer-events-none inline-flex h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground opacity-100">
- {range.shortcut}
- </kbd>
- </Button>
- ))}
- </div>
- {isDatePickerShow && (
- <>
- <Separator className="mt-2" />
- <div className="mt-2 grid gap-0.5">
- <DatePickerWithPresets
- value={customRange.start}
- defaultDate={customRange.start}
- onChange={(date) => handleDateChange("start", date)}
- title="Start Date"
- />
- <DatePickerWithPresets
- startDate={customRange.start}
- value={customRange.end}
- defaultDate={customRange.end}
- onChange={(date) => handleDateChange("end", date)}
- title="End Date"
- />
+ <PopoverContent className="w-auto p-2" align="end">
+ <div className="flex gap-2">
+ <div className="rounded-md border">
+ <Calendar
+ mode="range"
+ defaultMonth={date?.from}
+ selected={date}
+ onSelect={handleRangeChange}
+ numberOfMonths={2}
+ disabled={
+ !isPremium
+ ? (date) => {
+ if (!date) return false;
+ return differenceInDays(new Date(), date) > 30;
+ }
+ : undefined
+ }
+ fromDate={minDate}
+ />
+ </div>
+ <div className="flex flex-col gap-2">
+ <div className="grid gap-1">
+ {TIME_RANGES.map((range) => (
+ <Button
+ key={range.value}
+ variant={range.value === value ? "secondary" : "ghost"}
+ className="justify-between"
+ onClick={() => handleSelectOption(range.value)}
+ disabled={!isPremium && range.value === "custom"}
+ >
+ <span>{range.label}</span>
+ {/* <kbd className="pointer-events-none inline-flex h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground opacity-100">
+ {range.shortcut}
+ </kbd> */}
+ </Button>
+ ))}
</div>
- </>
- )}
+ </div>
+ </div>
</PopoverContent>
</Popover>
);
diff --git a/components/ui/datePicker.tsx b/components/ui/datePicker.tsx
deleted file mode 100644
index 02735cd0..00000000
--- a/components/ui/datePicker.tsx
+++ /dev/null
@@ -1,147 +0,0 @@
-"use client";
-
-import * as React from "react";
-
-import { addDays, format } from "date-fns";
-import { Calendar as CalendarIcon } from "lucide-react";
-
-import { Button } from "@/components/ui/button";
-import { Calendar } from "@/components/ui/calendar";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-
-import { cn } from "@/lib/utils";
-
-import { Label } from "./label";
-
-interface DatePickerWithPresetsProps {
- title?: string;
- value?: Date;
- startDate?: Date;
- defaultDate?: Date;
- onChange: (date: Date) => void;
- presets?: { label: string; value: number }[];
-}
-
-export const DatePickerWithPresets: React.FC<DatePickerWithPresetsProps> = ({
- title,
- value,
- onChange,
- startDate,
- defaultDate,
- presets = [
- { label: "Today", value: 0 },
- { label: "Tomorrow", value: 1 },
- { label: "In 3 days", value: 3 },
- { label: "In a week", value: 7 },
- { label: "In 2 weeks", value: 14 },
- { label: "30 days", value: 30 },
- { label: "90 days", value: 90 },
- {
- label: "End of this month",
- value:
- new Date(
- new Date().getFullYear(),
- new Date().getMonth() + 1,
- 0,
- ).getDate() - new Date().getDate(),
- },
- {
- label: "End of next month",
- value:
- new Date(
- new Date().getFullYear(),
- new Date().getMonth() + 1,
- 0,
- ).getDate() -
- new Date().getDate() +
- new Date(new Date().getFullYear(), new Date().getMonth(), 0).getDate(),
- },
- { label: "In 6 months", value: 180 },
- { label: "In a year", value: 365 },
- ],
-}) => {
- const [month, setMonth] = React.useState<Date | undefined>(
- value || new Date(),
- );
-
- React.useEffect(() => {
- if (value) {
- setMonth(value);
- }
- }, [value]);
-
- return (
- <Popover>
- <PopoverTrigger asChild>
- <Button
- variant="outline"
- className={cn(
- "w-full justify-start text-left font-normal",
- !value && "text-muted-foreground",
- )}
- >
- <CalendarIcon />
- <Label>
- {value
- ? startDate
- ? `To ${format(value, "PP")}`
- : `From ${format(value, "PP")}`
- : title || "Select Date"}
- </Label>
- </Button>
- </PopoverTrigger>
- <PopoverContent className="flex w-auto flex-col space-y-2 p-2">
- {/* Dropdown for selecting preset dates */}
- <Select
- onValueChange={(val) => {
- const newDate = addDays(
- startDate ? startDate : new Date(),
- parseInt(val),
- );
- onChange(newDate);
- setMonth(newDate); // Update calendar month
- }}
- >
- <SelectTrigger>
- <SelectValue placeholder="Select a preset" />
- </SelectTrigger>
- <SelectContent position="popper">
- {presets.map((preset) => (
- <SelectItem key={preset.value} value={preset.value.toString()}>
- {preset.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
-
- {/* Calendar for selecting a custom date */}
- <div className="rounded-md border">
- <Calendar
- mode="single"
- selected={value ?? defaultDate}
- month={month ?? defaultDate}
- onMonthChange={setMonth}
- fromDate={startDate}
- onSelect={(date) => {
- if (date) {
- onChange(date);
- setMonth(date);
- }
- }}
- />
- </div>
- </PopoverContent>
- </Popover>
- );
-};
diff --git a/pages/api/analytics/index.ts b/pages/api/analytics/index.ts
index 9d58752b..61fddc11 100644
--- a/pages/api/analytics/index.ts
+++ b/pages/api/analytics/index.ts
@@ -11,6 +11,7 @@ import {
getTotalViewerDuration,
getViewPageDuration,
} from "@/lib/tinybird/pipes";
+import { CustomUser } from "@/lib/types";
import { durationFormat } from "@/lib/utils";
import { authOptions } from "../auth/[...nextauth]";
@@ -59,6 +60,35 @@ export default async function handler(
endDate: endStr,
} = result.data;
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: (session.user as CustomUser).id,
+ },
+ },
+ },
+ });
+
+ if (!team) {
+ return res.status(401).json({ error: "Unauthorized" });
+ }
+
+ // Check if free plan user is trying to access data beyond 30 days
+ if (interval === "custom" && team.plan.includes("free")) {
+ const thirtyDaysAgo = new Date();
+ thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
+ thirtyDaysAgo.setHours(0, 0, 0, 0);
+
+ // For custom range, check the provided start date
+ if (startStr && new Date(startStr) < thirtyDaysAgo) {
+ return res.status(401).json({
+ error: "Free plan users can only access data from the last 30 days",
+ });
+ }
+ }
+
// get the start date for the interval
const now = new Date();
let startDate: Date;
@@ -84,14 +114,9 @@ export default async function handler(
startDate.setHours(0, 0, 0, 0);
break;
case "custom":
- startDate = new Date(startStr || addDays(new Date(), -7));
- endDate = new Date(endStr || addDays(new Date(), 0));
-
- if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
- return res
- .status(400)
- .json({ error: "Invalid startDate or endDate format." });
- }
+ startDate = new Date(startStr || addDays(new Date(), -6));
+ startDate.setHours(0, 0, 0, 0);
+ endDate = new Date(endStr || now);
if (startDate > endDate) {
return res
@@ -101,6 +126,7 @@ export default async function handler(
break;
default:
startDate = new Date(now);
+ startDate.setDate(startDate.getDate() - 6);
}
// Create the interval filter for the query
@@ -157,19 +183,16 @@ export default async function handler(
: interval === "custom"
? prisma.$queryRaw`
SELECT
- CASE
- WHEN ${endDate} - ${startDate} > INTERVAL '1 years' THEN DATE_TRUNC('year', "viewedAt")
- WHEN ${endDate} - ${startDate} > INTERVAL '1 months' THEN DATE_TRUNC('month', "viewedAt")
- ELSE DATE_TRUNC('day', "viewedAt")
- END AS date,
+ DATE_TRUNC('day', "viewedAt") as date,
COUNT(*) as views
FROM "View"
WHERE
"teamId" = ${teamId}
- AND "viewedAt" BETWEEN ${startDate} AND ${endDate}
+ AND "viewedAt" >= ${startDate}
+ AND "viewedAt" <= ${endDate}
AND "isArchived" = false
AND "viewType" = 'DOCUMENT_VIEW'
- GROUP BY date
+ GROUP BY DATE_TRUNC('day', "viewedAt")
ORDER BY date ASC
`
: prisma.$queryRaw`
diff --git a/pages/dashboard.tsx b/pages/dashboard.tsx
index 7e698dcc..af03b485 100644
--- a/pages/dashboard.tsx
+++ b/pages/dashboard.tsx
@@ -4,7 +4,7 @@ import { useRef, useState } from "react";
import { useTeam } from "@/context/team-context";
import { addDays, format } from "date-fns";
-import { BarChart3, Eye, FileText, Link, Users } from "lucide-react";
+import { BarChart3 } from "lucide-react";
import { toast } from "sonner";
import useSWR from "swr";
@@ -21,6 +21,7 @@ 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 {
@@ -43,15 +44,26 @@ export const defaultRange = {
export default function DashboardPage() {
const router = useRouter();
const teamInfo = useTeam();
+ const { plan, trial } = usePlan();
const slug = useRef<boolean>(false);
const [customRange, setCustomRange] = useState<{
start: Date;
end: Date;
}>(defaultRange);
- const { interval = "7d", type = "links" } = router.query as {
+ // Check if user has access to data beyond 30 days
+ const isPremium = plan !== "free" || !!trial;
+
+ const {
+ interval = "7d",
+ type = "links",
+ start,
+ end,
+ } = router.query as {
interval: TimeRange;
type: string;
+ start: string;
+ end: string;
};
const {
@@ -79,7 +91,31 @@ export default function DashboardPage() {
const handleTimeRangeChange = (newTimeRange: TimeRange) => {
const params = new URLSearchParams(window.location.search);
params.set("interval", newTimeRange);
- router.push(`/dashboard?${params.toString()}`);
+ if (type) {
+ params.set("type", type);
+ }
+ // Only remove date params when switching to preset ranges
+ if (newTimeRange !== "custom") {
+ params.delete("start");
+ params.delete("end");
+ }
+ router.push(`/dashboard?${params.toString()}`, undefined, {
+ shallow: true,
+ });
+ };
+
+ // Handle custom range URL updates
+ const handleCustomRangeComplete = (range: { start: Date; end: Date }) => {
+ const params = new URLSearchParams(window.location.search);
+ params.set("interval", "custom");
+ params.set("start", range.start.toISOString());
+ params.set("end", range.end.toISOString());
+ if (type) {
+ params.set("type", type);
+ }
+ router.push(`/dashboard?${params.toString()}`, undefined, {
+ shallow: true,
+ });
};
return (
@@ -92,7 +128,9 @@ export default function DashboardPage() {
onChange={handleTimeRangeChange}
customRange={customRange}
setCustomRange={setCustomRange}
+ onCustomRangeComplete={handleCustomRangeComplete}
slug={slug}
+ isPremium={isPremium}
/>
</div>