Skip to content

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

custome time input on dashboard

Ashish Viradiya6e5a234c9cf8
diff --git a/components/analytics/dashboard-views-chart.tsx b/components/analytics/dashboard-views-chart.tsx
index 5cd002a4..1521f64e 100644
--- a/components/analytics/dashboard-views-chart.tsx
+++ b/components/analytics/dashboard-views-chart.tsx
@@ -1,6 +1,6 @@
import { useMemo } from "react";
-import { format, subDays, subHours } from "date-fns";
+import { format } from "date-fns";
import {
Bar,
BarChart,
@@ -15,23 +15,59 @@ import { TimeRange } from "./time-range-select";
interface DashboardViewsChartProps {
timeRange: TimeRange;
- data?: {
- date: string;
- views: number;
- }[];
+ data?: { date: string; views: number }[];
+ startDate?: Date;
+ endDate?: Date;
}
export default function DashboardViewsChart({
timeRange,
data = [],
+ startDate,
+ endDate,
}: DashboardViewsChartProps) {
+ const totalDays =
+ startDate && endDate
+ ? Math.ceil(
+ (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24),
+ )
+ : 0;
// Format the data for display
const formattedData = useMemo(() => {
// Generate all possible time slots
const now = new Date();
const slots: { date: Date; views: number }[] = [];
+ if (timeRange === "custom" && startDate && endDate) {
+ if (totalDays > 365) {
+ // More than a year: Group by months
+ let current = new Date(
+ startDate.getFullYear(),
+ startDate.getMonth(),
+ 1,
+ );
- if (timeRange === "24h") {
+ while (current <= endDate) {
+ slots.push({ date: new Date(current), views: 0 });
+ current.setMonth(current.getMonth() + 1);
+ }
+ } else if (totalDays > 30) {
+ // More than a month but less than a year: Group by weeks
+ for (let i = 0; i <= totalDays; i += 7) {
+ const date = new Date(startDate);
+ date.setDate(date.getDate() + i);
+ date.setHours(0, 0, 0, 0);
+ slots.push({ date, views: 0 });
+ }
+ } else {
+ // Less than a month: Show daily data
+ for (let i = 0; i <= totalDays; i++) {
+ const date = new Date(startDate);
+ date.setDate(date.getDate() + i);
+ date.setHours(0, 0, 0, 0);
+ slots.push({ date, views: 0 });
+ }
+ }
+ } else if (timeRange === "24h") {
// Generate 24 hourly slots
for (let i = 23; i >= 0; i--) {
const date = new Date(now);
@@ -54,15 +90,44 @@ export default function DashboardViewsChart({
if (data) {
data.forEach((point) => {
const pointDate = new Date(point.date);
- const slotIndex = slots.findIndex((slot) => {
- if (timeRange === "24h") {
- return slot.date.getHours() === pointDate.getHours();
+
+ let slotIndex = -1;
+
+ if (timeRange === "24h") {
+ slotIndex = slots.findIndex(
+ (slot) => slot.date.getHours() === pointDate.getHours(),
+ );
+ } else if (timeRange === "custom") {
+ if (totalDays > 365) {
+ // If range is more than a year, match by month
+ slotIndex = slots.findIndex(
+ (slot) =>
+ slot.date.getFullYear() === pointDate.getFullYear() &&
+ slot.date.getMonth() === pointDate.getMonth(),
+ );
+ } else if (totalDays > 30) {
+ // If range is more than a month but less than a year, match by week
+ slotIndex = slots.findIndex(
+ (slot) =>
+ pointDate >= slot.date &&
+ pointDate <
+ new Date(slot.date.getTime() + 7 * 24 * 60 * 60 * 1000), // Within the week
+ );
} else {
- return slot.date.toDateString() === pointDate.toDateString();
+ // If range is less than a month, match by exact day
+ slotIndex = slots.findIndex(
+ (slot) => slot.date.toDateString() === pointDate.toDateString(),
+ );
}
- });
+ } else {
+ // Default case: match by exact day for '7d' and '30d'
+ slotIndex = slots.findIndex(
+ (slot) => slot.date.toDateString() === pointDate.toDateString(),
+ );
+ }
+
if (slotIndex !== -1) {
- slots[slotIndex].views = point.views;
+ slots[slotIndex].views += point.views;
}
});
}
@@ -70,10 +135,19 @@ export default function DashboardViewsChart({
// Format for display
return slots.map((slot) => ({
date: slot.date,
- name: format(slot.date, timeRange === "24h" ? "h:mm aa" : "EEE, MMM d"),
+ name: format(
+ slot.date,
+ timeRange === "24h"
+ ? "h:mm aa"
+ : totalDays > 365
+ ? "MMM yyyy"
+ : totalDays > 30
+ ? "MMM d"
+ : "EEE, MMM d",
+ ),
views: slot.views,
}));
- }, [data, timeRange]);
+ }, [data, timeRange, startDate, endDate, totalDays]);
// Calculate tick values based on time range
const ticks = useMemo(() => {
@@ -96,9 +170,33 @@ export default function DashboardViewsChart({
tickIndices.unshift(i);
}
return tickIndices.map((i) => formattedData[i].name);
+ } else if (timeRange === "custom") {
+ if (totalDays > 365) {
+ // Show every 2rd month
+ return formattedData.filter((_, i) => i % 2 === 0).map((d) => d.name);
+ }
+
+ if (totalDays > 30) {
+ // Show every 2nd week
+ return formattedData.filter((_, i) => i % 2 === 0).map((d) => d.name);
+ }
+ return formattedData.map((d) => d.name);
}
return formattedData.map((d) => d.name);
- }, [timeRange, formattedData]);
+ }, [timeRange, formattedData, totalDays]);
+
+ const barSize = useMemo(() => {
+ if (timeRange === "24h") return 8;
+ if (timeRange === "7d") return 24;
+ if (timeRange === "30d") return 12;
+
+ if (startDate && endDate) {
+ if (totalDays > 365) return 24;
+ if (totalDays > 30) return 16;
+ }
+
+ return 12;
+ }, [timeRange, startDate, endDate, totalDays]);
return (
<div className="h-[300px] w-full">
@@ -106,7 +204,7 @@ export default function DashboardViewsChart({
<BarChart
data={formattedData}
margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
- barSize={timeRange === "24h" ? 8 : timeRange === "7d" ? 24 : 12}
+ barSize={barSize}
>
<XAxis
dataKey="name"
@@ -137,9 +235,16 @@ export default function DashboardViewsChart({
Time
</span>
<span className="font-bold text-muted-foreground">
- {timeRange === "24h"
- ? format(data.date, "h:mm a")
- : format(data.date, "MMM d, yyyy")}
+ {format(
+ data.date,
+ timeRange === "24h"
+ ? "h:mm aa"
+ : totalDays > 365
+ ? "MMM yyyy"
+ : totalDays > 30
+ ? "'Week of' MMM d"
+ : "MMM d, yyyy",
+ )}
</span>
</div>
<div className="flex flex-col">
diff --git a/components/analytics/documents-table.tsx b/components/analytics/documents-table.tsx
index c8add5a1..1f3bc579 100644
--- a/components/analytics/documents-table.tsx
+++ b/components/analytics/documents-table.tsx
@@ -13,6 +13,7 @@ import {
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
+import { format } from "date-fns";
import {
ChevronDownIcon,
ChevronUpIcon,
@@ -154,7 +155,13 @@ const columns: ColumnDef<Document>[] = [
},
];
-export default function DocumentsTable() {
+export default function DocumentsTable({
+ startDate,
+ endDate,
+}: {
+ startDate: Date;
+ endDate: Date;
+}) {
const router = useRouter();
const teamInfo = useTeam();
const [sorting, setSorting] = useState<SortingState>([
@@ -163,7 +170,7 @@ export default function DocumentsTable() {
const interval = router.query.interval || "24h";
const { data: documents, isLoading } = useSWR<Document[]>(
- `/api/analytics?type=documents&interval=${interval}&teamId=${teamInfo?.currentTeam?.id}`,
+ `/api/analytics?type=documents&interval=${interval}&teamId=${teamInfo?.currentTeam?.id}${interval === "custom" ? `&startDate=${format(startDate, "MM-dd-yyyy")}&endDate=${format(endDate, "MM-dd-yyyy")}` : ""}`,
fetcher,
{
keepPreviousData: true,
diff --git a/components/analytics/links-table.tsx b/components/analytics/links-table.tsx
index f17d3a12..c61b9e08 100644
--- a/components/analytics/links-table.tsx
+++ b/components/analytics/links-table.tsx
@@ -13,6 +13,7 @@ import {
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
+import { format } from "date-fns";
import {
Check,
ChevronDownIcon,
@@ -216,7 +217,13 @@ const columns: ColumnDef<Link>[] = [
},
];
-export default function LinksTable() {
+export default function LinksTable({
+ startDate,
+ endDate,
+}: {
+ startDate: Date;
+ endDate: Date;
+}) {
const router = useRouter();
const teamInfo = useTeam();
@@ -226,7 +233,7 @@ export default function LinksTable() {
const interval = router.query.interval || "7d";
const { data: links, isLoading } = useSWR<Link[]>(
- `/api/analytics?type=links&interval=${interval}&teamId=${teamInfo?.currentTeam?.id}`,
+ `/api/analytics?type=links&interval=${interval}&teamId=${teamInfo?.currentTeam?.id}${interval === "custom" ? `&startDate=${format(startDate, "MM-dd-yyyy")}&endDate=${format(endDate, "MM-dd-yyyy")}` : ""}`,
fetcher,
{
keepPreviousData: true,
diff --git a/components/analytics/time-range-select.tsx b/components/analytics/time-range-select.tsx
index 979a2b9f..7f122b32 100644
--- a/components/analytics/time-range-select.tsx
+++ b/components/analytics/time-range-select.tsx
@@ -1,4 +1,10 @@
-import { CalendarDays, CalendarIcon, ChevronDown } from "lucide-react";
+import { useRouter } from "next/navigation";
+
+import { Ref, useState } from "react";
+
+import { addDays, format } from "date-fns";
+import { CalendarIcon, ChevronDown } from "lucide-react";
+import { start } from "repl";
import { Button } from "@/components/ui/button";
import {
@@ -7,23 +13,52 @@ import {
PopoverTrigger,
} from "@/components/ui/popover";
+import { DatePickerWithPresets } from "../ui/datePicker";
+import { Separator } from "../ui/separator";
+
const TIME_RANGES = [
{ value: "24h", label: "Last 24 hours", shortcut: "D" },
{ value: "7d", label: "Last 7 days", shortcut: "W" },
{ value: "30d", label: "Last 30 days", shortcut: "M" },
- // { value: "90d", label: "Last 3 months", shortcut: "Q" },
- // { value: "1y", label: "Last 12 months", shortcut: "Y" },
+ { value: "custom", label: "Custom Date", shortcut: "C" },
] as const;
export type TimeRange = (typeof TIME_RANGES)[number]["value"];
-
+interface CustomRange {
+ start: Date;
+ end: Date;
+}
interface TimeRangeSelectProps {
value: TimeRange;
onChange: (value: TimeRange) => void;
+ customRange: CustomRange;
+ setCustomRange: React.Dispatch<React.SetStateAction<CustomRange>>;
+ slug: React.MutableRefObject<boolean>;
}
-export function TimeRangeSelect({ value, onChange }: TimeRangeSelectProps) {
- const selectedRange = TIME_RANGES.find((range) => range.value === value);
+export function TimeRangeSelect({
+ value,
+ onChange,
+ customRange,
+ setCustomRange,
+ slug,
+}: TimeRangeSelectProps) {
+ const [isDatePickerShow, setIsDatePickerShow] = useState(false);
+ const selectedRange =
+ value !== "custom"
+ ? TIME_RANGES.find((range) => range.value === value)
+ : null;
+
+ const handleSelectOption = (value: TimeRange) => {
+ const isCustom = value === "custom";
+ onChange(value);
+ setIsDatePickerShow(isCustom);
+ };
+
+ const handleDateChange = (key: "start" | "end", date: Date) => {
+ setCustomRange((prev: CustomRange) => ({ ...prev, [key]: date }));
+ slug.current = false;
+ };
return (
<Popover>
@@ -34,19 +69,25 @@ export function TimeRangeSelect({ value, onChange }: TimeRangeSelectProps) {
>
<div className="flex items-center gap-2">
<CalendarIcon className="!size-4" />
- <span>{selectedRange?.label}</span>
+ <span>
+ {selectedRange
+ ? selectedRange.label
+ : customRange.start && customRange.end
+ ? `${format(customRange.start, "PP")} - ${format(customRange.end, "PP")}`
+ : "Select Date Range"}
+ </span>
</div>
<ChevronDown className="!size-4 opacity-50" />
</Button>
</PopoverTrigger>
- <PopoverContent className="w-[200px] p-1" align="end">
- <div className="grid">
+ <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={() => onChange(range.value)}
+ 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">
@@ -55,6 +96,26 @@ export function TimeRangeSelect({ value, onChange }: TimeRangeSelectProps) {
</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"
+ />
+ </div>
+ </>
+ )}
</PopoverContent>
</Popover>
);
diff --git a/components/analytics/views-table.tsx b/components/analytics/views-table.tsx
index aa0626f3..f4a38864 100644
--- a/components/analytics/views-table.tsx
+++ b/components/analytics/views-table.tsx
@@ -13,6 +13,7 @@ import {
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
+import { format } from "date-fns";
import {
BadgeCheckIcon,
BadgeInfoIcon,
@@ -273,7 +274,13 @@ const columns: ColumnDef<View>[] = [
},
];
-export default function ViewsTable() {
+export default function ViewsTable({
+ startDate,
+ endDate,
+}: {
+ startDate: Date;
+ endDate: Date;
+}) {
const router = useRouter();
const teamInfo = useTeam();
const { interval = "7d" } = router.query;
@@ -283,7 +290,7 @@ export default function ViewsTable() {
const { data: views } = useSWR<View[]>(
teamInfo?.currentTeam?.id
- ? `/api/analytics?type=views&interval=${interval}&teamId=${teamInfo.currentTeam.id}`
+ ? `/api/analytics?type=views&interval=${interval}&teamId=${teamInfo.currentTeam.id}${interval === "custom" ? `&startDate=${format(startDate, "MM-dd-yyyy")}&endDate=${format(endDate, "MM-dd-yyyy")}` : ""}`
: null,
fetcher,
{
diff --git a/components/analytics/visitors-table.tsx b/components/analytics/visitors-table.tsx
index 061382a7..9d0d01dc 100644
--- a/components/analytics/visitors-table.tsx
+++ b/components/analytics/visitors-table.tsx
@@ -12,6 +12,7 @@ import {
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
+import { format } from "date-fns";
import {
BadgeCheckIcon,
ChevronDownIcon,
@@ -202,7 +203,13 @@ const columns: ColumnDef<Visitor>[] = [
},
];
-export default function VisitorsTable() {
+export default function VisitorsTable({
+ startDate,
+ endDate,
+}: {
+ startDate: Date;
+ endDate: Date;
+}) {
const router = useRouter();
const teamInfo = useTeam();
const { interval = "7d" } = router.query;
@@ -212,7 +219,7 @@ export default function VisitorsTable() {
const { data: visitors } = useSWR<Visitor[]>(
teamInfo?.currentTeam?.id
- ? `/api/analytics?type=visitors&interval=${interval}&teamId=${teamInfo.currentTeam.id}`
+ ? `/api/analytics?type=visitors&interval=${interval}&teamId=${teamInfo.currentTeam.id}${interval === "custom" ? `&startDate=${format(startDate, "MM-dd-yyyy")}&endDate=${format(endDate, "MM-dd-yyyy")}` : ""}`
: null,
fetcher,
{
diff --git a/components/ui/calendar.tsx b/components/ui/calendar.tsx
new file mode 100644
index 00000000..67ee0f38
--- /dev/null
+++ b/components/ui/calendar.tsx
@@ -0,0 +1,70 @@
+import * as React from "react";
+
+import { ChevronLeft, ChevronRight } from "lucide-react";
+import { DayPicker } from "react-day-picker";
+
+import { buttonVariants } from "@/components/ui/button";
+
+import { cn } from "@/lib/utils";
+
+export type CalendarProps = React.ComponentProps<typeof DayPicker>;
+
+function Calendar({
+ className,
+ classNames,
+ showOutsideDays = true,
+ ...props
+}: CalendarProps) {
+ return (
+ <DayPicker
+ showOutsideDays={showOutsideDays}
+ className={cn("p-3", className)}
+ classNames={{
+ months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
+ month: "space-y-4",
+ caption: "flex justify-center pt-1 relative items-center",
+ caption_label: "text-sm font-medium",
+ nav: "space-x-1 flex items-center",
+ nav_button: cn(
+ buttonVariants({ variant: "outline" }),
+ "h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100",
+ ),
+ nav_button_previous: "absolute left-1",
+ nav_button_next: "absolute right-1",
+ table: "w-full border-collapse space-y-1",
+ head_row: "flex",
+ head_cell:
+ "text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",
+ row: "flex w-full mt-2",
+ cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",
+ day: cn(
+ buttonVariants({ variant: "ghost" }),
+ "h-9 w-9 p-0 font-normal aria-selected:opacity-100",
+ ),
+ day_range_end: "day-range-end",
+ day_selected:
+ "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
+ day_today: "bg-accent text-accent-foreground",
+ day_outside:
+ "day-outside text-muted-foreground aria-selected:bg-accent/50 aria-selected:text-muted-foreground",
+ day_disabled: "text-muted-foreground opacity-50",
+ day_range_middle:
+ "aria-selected:bg-accent aria-selected:text-accent-foreground",
+ day_hidden: "invisible",
+ ...classNames,
+ }}
+ components={{
+ IconLeft: ({ className, ...props }) => (
+ <ChevronLeft className={cn("h-4 w-4", className)} {...props} />
+ ),
+ IconRight: ({ className, ...props }) => (
+ <ChevronRight className={cn("h-4 w-4", className)} {...props} />
+ ),
+ }}
+ {...props}
+ />
+ );
+}
+Calendar.displayName = "Calendar";
+
+export { Calendar };
diff --git a/components/ui/datePicker.tsx b/components/ui/datePicker.tsx
new file mode 100644
index 00000000..02735cd0
--- /dev/null
+++ b/components/ui/datePicker.tsx
@@ -0,0 +1,147 @@
+"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/lib/tinybird/pipes.ts b/lib/tinybird/pipes.ts
index d459054d..b70025b1 100644
--- a/lib/tinybird/pipes.ts
+++ b/lib/tinybird/pipes.ts
@@ -27,6 +27,7 @@ export const getViewPageDuration = tb.buildPipe({
documentId: z.string(),
viewId: z.string(),
since: z.number(),
+ until: z.number().optional(),
}),
data: z.object({
pageNumber: z.string(),
@@ -41,6 +42,7 @@ export const getTotalDocumentDuration = tb.buildPipe({
excludedLinkIds: z.string().describe("Comma separated linkIds"),
excludedViewIds: z.string().describe("Comma separated viewIds"),
since: z.number(),
+ until: z.number().optional(),
}),
data: z.object({
sum_duration: z.number(),
@@ -54,6 +56,7 @@ export const getTotalLinkDuration = tb.buildPipe({
documentId: z.string(),
excludedViewIds: z.string().describe("Comma separated viewIds"),
since: z.number(),
+ until: z.number(),
}),
data: z.object({
sum_duration: z.number(),
@@ -66,6 +69,7 @@ export const getTotalViewerDuration = tb.buildPipe({
parameters: z.object({
viewIds: z.string().describe("Comma separated viewIds"),
since: z.number(),
+ until: z.number(),
}),
data: z.object({
sum_duration: z.number(),
diff --git a/package.json b/package.json
index d6d8e2fc..60ae4ac0 100644
--- a/package.json
+++ b/package.json
@@ -81,6 +81,7 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.4",
+ "date-fns": "^3.6.0",
"eslint": "8.57.0",
"eslint-config-next": "^14.2.24",
"fluent-ffmpeg": "^2.1.3",
@@ -108,6 +109,7 @@
"posthog-js": "^1.217.2",
"react": "^18.3.1",
"react-colorful": "^5.6.1",
+ "react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-draggable": "^4.4.6",
"react-dropzone": "^14.3.5",
diff --git a/pages/api/analytics/index.ts b/pages/api/analytics/index.ts
index 012c6af6..9d58752b 100644
--- a/pages/api/analytics/index.ts
+++ b/pages/api/analytics/index.ts
@@ -1,5 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
+import { addDays } from "date-fns";
import { getServerSession } from "next-auth";
import { z } from "zod";
@@ -15,9 +16,11 @@ import { durationFormat } from "@/lib/utils";
import { authOptions } from "../auth/[...nextauth]";
const analyticsQuerySchema = z.object({
- interval: z.enum(["24h", "7d", "30d"]),
+ interval: z.enum(["24h", "7d", "30d", "custom"]),
type: z.enum(["overview", "links", "documents", "visitors", "views"]),
teamId: z.string(),
+ startDate: z.string().optional(),
+ endDate: z.string().optional(),
});
const INTERVALS = {
@@ -48,11 +51,18 @@ export default async function handler(
.json({ error: `Invalid body: ${result.error.message}` });
}
- const { interval, type, teamId } = result.data;
+ const {
+ interval,
+ type,
+ teamId,
+ startDate: startStr,
+ endDate: endStr,
+ } = result.data;
// get the start date for the interval
const now = new Date();
let startDate: Date;
+ let endDate: Date = now;
switch (interval) {
case "24h":
@@ -73,15 +83,42 @@ export default async function handler(
startDate.setDate(startDate.getDate() - 29);
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." });
+ }
+
+ if (startDate > endDate) {
+ return res
+ .status(400)
+ .json({ error: "The 'From' date must be before the 'To' date." });
+ }
+ break;
+ default:
+ startDate = new Date(now);
}
- // create the interval filter for the query
- const intervalFilter = {
- gte: startDate,
- };
+ // Create the interval filter for the query
+ const intervalFilter: any = { gte: startDate, lte: endDate };
+
+ let since: number;
- console.log("startDate", startDate);
- console.log("intervalFilter", intervalFilter);
+ if (interval === "custom") {
+ const startTimestamp = startStr ? new Date(startStr).getTime() : NaN;
+
+ if (isNaN(startTimestamp)) {
+ since = Date.now();
+ } else {
+ since = startTimestamp;
+ }
+ } else {
+ since = Date.now() - INTERVALS[interval];
+ }
switch (type) {
case "overview": {
@@ -117,7 +154,25 @@ export default async function handler(
GROUP BY DATE_TRUNC('hour', "viewedAt")
ORDER BY date ASC
`
- : prisma.$queryRaw`
+ : 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,
+ COUNT(*) as views
+ FROM "View"
+ WHERE
+ "teamId" = ${teamId}
+ AND "viewedAt" BETWEEN ${startDate} AND ${endDate}
+ AND "isArchived" = false
+ AND "viewType" = 'DOCUMENT_VIEW'
+ GROUP BY date
+ ORDER BY date ASC
+ `
+ : prisma.$queryRaw`
SELECT
DATE_TRUNC('day', "viewedAt") as date,
COUNT(*) as views
@@ -227,12 +282,14 @@ export default async function handler(
if (link.documentId) {
try {
- const since = Date.now() - INTERVALS[interval];
const durationData = await getTotalLinkDuration({
linkId: link.id,
documentId: link.documentId,
excludedViewIds: "", // Include all views
since,
+ until: endStr
+ ? new Date(endStr).getTime()
+ : new Date().getTime(),
});
if (durationData.data && durationData.data[0]) {
@@ -314,14 +371,15 @@ export default async function handler(
const transformedDocuments = await Promise.all(
documents.map(async (doc) => {
let avgDuration = "0s";
-
try {
- const since = Date.now() - INTERVALS[interval];
const durationData = await getTotalDocumentDuration({
documentId: doc.id,
excludedLinkIds: "", // Include all links
excludedViewIds: "", // Include all views
since,
+ until: endStr
+ ? new Date(endStr).getTime()
+ : new Date().getTime(),
});
if (durationData.data && durationData.data[0]) {
@@ -381,13 +439,14 @@ export default async function handler(
);
let totalDuration = 0;
-
try {
- const since = Date.now() - INTERVALS[interval];
const viewIds = viewer.views.map((view) => view.id).join(",");
const durationData = await getTotalViewerDuration({
viewIds,
since,
+ until: endStr
+ ? new Date(endStr).getTime()
+ : new Date().getTime(),
});
if (durationData.data && durationData.data[0]) {
@@ -457,11 +516,13 @@ export default async function handler(
if (view.document?.id) {
try {
- const since = Date.now() - INTERVALS[interval];
const pageData = await getViewPageDuration({
documentId: view.document.id,
viewId: view.id,
since,
+ until: endStr
+ ? new Date(endStr).getTime()
+ : new Date().getTime(),
});
if (pageData.data && pageData.data.length > 0) {
diff --git a/pages/dashboard.tsx b/pages/dashboard.tsx
index d2205465..7e698dcc 100644
--- a/pages/dashboard.tsx
+++ b/pages/dashboard.tsx
@@ -1,9 +1,11 @@
import { useRouter } from "next/router";
-import { useEffect } from "react";
+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 { toast } from "sonner";
import useSWR from "swr";
import { AnalyticsCard } from "@/components/analytics/analytics-card";
@@ -33,20 +35,31 @@ interface OverviewData {
views: number;
}[];
}
+export const defaultRange = {
+ start: addDays(new Date(), -7),
+ end: addDays(new Date(), 0),
+};
export default function DashboardPage() {
const router = useRouter();
const teamInfo = useTeam();
+ const slug = useRef<boolean>(false);
+ const [customRange, setCustomRange] = useState<{
+ start: Date;
+ end: Date;
+ }>(defaultRange);
+
const { interval = "7d", type = "links" } = router.query as {
interval: TimeRange;
type: string;
};
- // Fetch overview data
- const { data: overview, isLoading } = useSWR<OverviewData>(
- teamInfo?.currentTeam?.id
- ? `/api/analytics?type=overview&interval=${interval}&teamId=${teamInfo.currentTeam.id}`
- : null,
+ const {
+ data: overview,
+ isLoading,
+ error,
+ } = useSWR<OverviewData>(
+ `/api/analytics?type=overview&interval=${interval}&teamId=${teamInfo?.currentTeam?.id}${interval === "custom" ? `&startDate=${format(customRange.start, "MM-dd-yyyy")}&endDate=${format(customRange.end, "MM-dd-yyyy")}` : ""}`,
fetcher,
{
keepPreviousData: true,
@@ -54,6 +67,14 @@ export default function DashboardPage() {
},
);
+ if (error && !slug.current) {
+ const errorObj = JSON.parse(error.message);
+ const errorMessage = errorObj?.error;
+ toast.info(errorMessage);
+ setCustomRange(defaultRange);
+ slug.current = true;
+ }
+
// Update the URL when time range changes
const handleTimeRangeChange = (newTimeRange: TimeRange) => {
const params = new URLSearchParams(window.location.search);
@@ -66,7 +87,13 @@ export default function DashboardPage() {
<div className="flex-1 space-y-4 p-4 pt-6 md:p-8">
<div className="flex items-center justify-between">
<h2 className="text-3xl font-bold tracking-tight">Dashboard</h2>
- <TimeRangeSelect value={interval} onChange={handleTimeRangeChange} />
+ <TimeRangeSelect
+ value={interval}
+ onChange={handleTimeRangeChange}
+ customRange={customRange}
+ setCustomRange={setCustomRange}
+ slug={slug}
+ />
</div>
<div className="space-y-4">
@@ -75,7 +102,12 @@ export default function DashboardPage() {
icon={<BarChart3 className="h-4 w-4" />}
contentClassName="space-y-4"
>
- <DashboardViewsChart timeRange={interval} data={overview?.graph} />
+ <DashboardViewsChart
+ timeRange={interval}
+ data={overview?.graph}
+ startDate={customRange.start}
+ endDate={customRange.end}
+ />
</AnalyticsCard>
<TabMenu
@@ -112,10 +144,30 @@ export default function DashboardPage() {
/>
<div className="grid grid-cols-1">
- {type === "links" && <LinksTable />}
- {type === "documents" && <DocumentsTable />}
- {type === "visitors" && <VisitorsTable />}
- {type === "views" && <ViewsTable />}
+ {type === "links" && (
+ <LinksTable
+ startDate={customRange.start}
+ endDate={customRange.end}
+ />
+ )}
+ {type === "documents" && (
+ <DocumentsTable
+ startDate={customRange.start}
+ endDate={customRange.end}
+ />
+ )}
+ {type === "visitors" && (
+ <VisitorsTable
+ startDate={customRange.start}
+ endDate={customRange.end}
+ />
+ )}
+ {type === "views" && (
+ <ViewsTable
+ startDate={customRange.start}
+ endDate={customRange.end}
+ />
+ )}
</div>
</div>
</div>