Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: Add timezone setting for team analytics
Cursor Agent1fc5f2af6282
diff --git a/components/settings/timezone-selector.tsx b/components/settings/timezone-selector.tsxnew file mode 100644index 00000000..4b9a8a82--- /dev/null+++ b/components/settings/timezone-selector.tsx@@ -0,0 +1,156 @@+import { useEffect, useState } from "react";++import { useTeam } from "@/context/team-context";+import { toast } from "sonner";+import { mutate } from "swr";++import { useTeamSettings } from "@/lib/swr/use-team-settings";++import { Button } from "@/components/ui/button";+import {+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";++// Common timezone options with IANA identifiers+const TIMEZONE_OPTIONS = [+ { value: "Etc/UTC", label: "UTC (Coordinated Universal Time)" },+ { value: "America/New_York", label: "America/New York (EST/EDT)" },+ { value: "America/Chicago", label: "America/Chicago (CST/CDT)" },+ { value: "America/Denver", label: "America/Denver (MST/MDT)" },+ { value: "America/Los_Angeles", label: "America/Los Angeles (PST/PDT)" },+ { value: "America/Toronto", label: "America/Toronto (EST/EDT)" },+ { value: "America/Vancouver", label: "America/Vancouver (PST/PDT)" },+ { value: "America/Mexico_City", label: "America/Mexico City (CST/CDT)" },+ { value: "America/Sao_Paulo", label: "America/São Paulo (BRT)" },+ {+ value: "America/Argentina/Buenos_Aires",+ label: "America/Buenos Aires (ART)",+ },+ { value: "America/Santiago", label: "America/Santiago (CLT/CLST)" },+ { value: "America/Bogota", label: "America/Bogotá (COT)" },+ { value: "America/Lima", label: "America/Lima (PET)" },+ { value: "Europe/London", label: "Europe/London (GMT/BST)" },+ { value: "Europe/Paris", label: "Europe/Paris (CET/CEST)" },+ { value: "Europe/Berlin", label: "Europe/Berlin (CET/CEST)" },+ { value: "Europe/Madrid", label: "Europe/Madrid (CET/CEST)" },+ { value: "Europe/Rome", label: "Europe/Rome (CET/CEST)" },+ { value: "Europe/Amsterdam", label: "Europe/Amsterdam (CET/CEST)" },+ { value: "Europe/Zurich", label: "Europe/Zurich (CET/CEST)" },+ { value: "Europe/Stockholm", label: "Europe/Stockholm (CET/CEST)" },+ { value: "Europe/Warsaw", label: "Europe/Warsaw (CET/CEST)" },+ { value: "Europe/Moscow", label: "Europe/Moscow (MSK)" },+ { value: "Europe/Istanbul", label: "Europe/Istanbul (TRT)" },+ { value: "Asia/Dubai", label: "Asia/Dubai (GST)" },+ { value: "Asia/Kolkata", label: "Asia/Kolkata (IST)" },+ { value: "Asia/Bangkok", label: "Asia/Bangkok (ICT)" },+ { value: "Asia/Singapore", label: "Asia/Singapore (SGT)" },+ { value: "Asia/Hong_Kong", label: "Asia/Hong Kong (HKT)" },+ { value: "Asia/Shanghai", label: "Asia/Shanghai (CST)" },+ { value: "Asia/Tokyo", label: "Asia/Tokyo (JST)" },+ { value: "Asia/Seoul", label: "Asia/Seoul (KST)" },+ { value: "Australia/Sydney", label: "Australia/Sydney (AEST/AEDT)" },+ { value: "Australia/Melbourne", label: "Australia/Melbourne (AEST/AEDT)" },+ { value: "Australia/Perth", label: "Australia/Perth (AWST)" },+ { value: "Pacific/Auckland", label: "Pacific/Auckland (NZST/NZDT)" },+ { value: "Pacific/Honolulu", label: "Pacific/Honolulu (HST)" },+ { value: "Africa/Johannesburg", label: "Africa/Johannesburg (SAST)" },+ { value: "Africa/Cairo", label: "Africa/Cairo (EET)" },+ { value: "Africa/Lagos", label: "Africa/Lagos (WAT)" },+];++export function TimezoneSelector() {+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;+ const { settings: teamSettings } = useTeamSettings(teamId);++ const [selectedTimezone, setSelectedTimezone] = useState<string>("Etc/UTC");+ const [saving, setSaving] = useState(false);++ useEffect(() => {+ if (teamSettings?.timezone) {+ setSelectedTimezone(teamSettings.timezone);+ }+ }, [teamSettings?.timezone]);++ const handleSave = async () => {+ if (!teamId) return;++ setSaving(true);+ try {+ const response = await fetch(`/api/teams/${teamId}/settings`, {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ timezone: selectedTimezone }),+ });++ if (!response.ok) {+ const { error } = await response.json();+ throw new Error(error || "Failed to update timezone");+ }++ await Promise.all([+ mutate(`/api/teams/${teamId}/settings`),+ mutate(`/api/teams/${teamId}`),+ ]);++ toast.success("Timezone updated successfully");+ } catch (error) {+ toast.error((error as Error).message || "Failed to update timezone");+ } finally {+ setSaving(false);+ }+ };++ const hasChanged = teamSettings?.timezone !== selectedTimezone;++ return (+ <Card className="bg-transparent">+ <CardHeader>+ <CardTitle>Analytics Timezone</CardTitle>+ <CardDescription>+ Set the timezone for your team's analytics. This affects how+ visit data is grouped by day in charts and reports.+ </CardDescription>+ </CardHeader>+ <CardContent>+ <Select value={selectedTimezone} onValueChange={setSelectedTimezone}>+ <SelectTrigger className="w-full max-w-md">+ <SelectValue placeholder="Select a timezone" />+ </SelectTrigger>+ <SelectContent className="max-h-[300px]">+ {TIMEZONE_OPTIONS.map((tz) => (+ <SelectItem key={tz.value} value={tz.value}>+ {tz.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </CardContent>+ <CardFooter className="flex items-center justify-between rounded-b-lg border-t bg-muted px-6 py-3">+ <p className="text-sm text-muted-foreground">+ Uses IANA timezone identifiers. Analytics charts will display data+ based on this timezone.+ </p>+ <div className="shrink-0">+ <Button loading={saving} disabled={!hasChanged || saving} onClick={handleSave}>+ Save Changes+ </Button>+ </div>+ </CardFooter>+ </Card>+ );+}diff --git a/lib/swr/use-team-settings.ts b/lib/swr/use-team-settings.tsindex 4124d04c..999fac11 100644--- a/lib/swr/use-team-settings.ts+++ b/lib/swr/use-team-settings.ts@@ -1,10 +1,11 @@-import useSWR from "swr";+import useSWR, { mutate } from "swr";import { fetcher } from "@/lib/utils";interface TeamSettings {replicateDataroomFolders: boolean;enableExcelAdvancedMode: boolean;+ timezone: string;}/**@@ -22,10 +23,32 @@ export function useTeamSettings(teamId: string | undefined | null) {},);+ const updateTimezone = async (timezone: string) => {+ if (!teamId) return;++ const response = await fetch(`/api/teams/${teamId}/settings`, {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ timezone }),+ });++ if (!response.ok) {+ throw new Error("Failed to update timezone");+ }++ // Revalidate the settings+ mutate(`/api/teams/${teamId}/settings`);++ return response.json();+ };+return {settings: data,isLoading: !data && !error,isError: error,isValidating,+ updateTimezone,};}diff --git a/pages/api/analytics/index.ts b/pages/api/analytics/index.tsindex c7915275..2b6e8940 100644--- a/pages/api/analytics/index.ts+++ b/pages/api/analytics/index.ts@@ -73,6 +73,7 @@ export default async function handler(id: true,plan: true,pauseStartsAt: true,+ timezone: true,},});@@ -82,6 +83,8 @@ export default async function handler(// Get pause date filter if team is pausedconst pauseStartsAt = team.pauseStartsAt;+ // Get team timezone for analytics display (defaults to UTC)+ const timezone = team.timezone || "Etc/UTC";// Check if free plan user is trying to access data beyond 30 daysif (interval === "custom" && team.plan.includes("free")) {@@ -174,10 +177,12 @@ export default async function handler(},}),// Get views data for graph grouped by day+ // Note: We use timezone-aware date truncation to ensure dates are grouped+ // correctly based on the team's timezone setting, avoiding one-day offset issuesinterval === "24h"? prisma.$queryRaw`SELECT- DATE_TRUNC('hour', "viewedAt") as date,+ DATE_TRUNC('hour', "viewedAt" AT TIME ZONE 'UTC' AT TIME ZONE ${timezone}) as date,COUNT(*) as viewsFROM "View"WHERE@@ -185,13 +190,13 @@ export default async function handler(AND "viewedAt" >= ${startDate}AND "isArchived" = falseAND "viewType" = 'DOCUMENT_VIEW'- GROUP BY DATE_TRUNC('hour', "viewedAt")+ GROUP BY DATE_TRUNC('hour', "viewedAt" AT TIME ZONE 'UTC' AT TIME ZONE ${timezone})ORDER BY date ASC`: interval === "custom"? prisma.$queryRaw`SELECT- DATE_TRUNC('day', "viewedAt") as date,+ DATE_TRUNC('day', "viewedAt" AT TIME ZONE 'UTC' AT TIME ZONE ${timezone}) as date,COUNT(*) as viewsFROM "View"WHERE@@ -200,12 +205,12 @@ export default async function handler(AND "viewedAt" <= ${endDate}AND "isArchived" = falseAND "viewType" = 'DOCUMENT_VIEW'- GROUP BY DATE_TRUNC('day', "viewedAt")+ GROUP BY DATE_TRUNC('day', "viewedAt" AT TIME ZONE 'UTC' AT TIME ZONE ${timezone})ORDER BY date ASC`: prisma.$queryRaw`SELECT- DATE_TRUNC('day', "viewedAt") as date,+ DATE_TRUNC('day', "viewedAt" AT TIME ZONE 'UTC' AT TIME ZONE ${timezone}) as date,COUNT(*) as viewsFROM "View"WHERE@@ -213,7 +218,7 @@ export default async function handler(AND "viewedAt" >= ${startDate}AND "isArchived" = falseAND "viewType" = 'DOCUMENT_VIEW'- GROUP BY DATE_TRUNC('day', "viewedAt")+ GROUP BY DATE_TRUNC('day', "viewedAt" AT TIME ZONE 'UTC' AT TIME ZONE ${timezone})ORDER BY date ASC`,]);@@ -238,6 +243,7 @@ export default async function handler(views: Number(point.views),}),),+ timezone, // Include timezone for frontend reference});}diff --git a/pages/api/teams/[teamId]/settings.ts b/pages/api/teams/[teamId]/settings.tsindex 3f534b7f..2df2b77c 100644--- a/pages/api/teams/[teamId]/settings.ts+++ b/pages/api/teams/[teamId]/settings.ts@@ -1,6 +1,7 @@import { NextApiRequest, NextApiResponse } from "next";import { getServerSession } from "next-auth/next";+import { z } from "zod";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";@@ -8,36 +9,42 @@ import { CustomUser } from "@/lib/types";import { authOptions } from "../../auth/[...nextauth]";+const updateSettingsSchema = z.object({+ timezone: z.string().optional(),+ replicateDataroomFolders: z.boolean().optional(),+ enableExcelAdvancedMode: z.boolean().optional(),+});+export default async function handle(req: NextApiRequest,res: NextApiResponse,) {- if (req.method === "GET") {- // GET /api/teams/:teamId/settings- const session = await getServerSession(req, res, authOptions);- if (!session) {- return res.status(401).end("Unauthorized");- }+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }- const { teamId } = req.query as { teamId: string };- const userId = (session.user as CustomUser).id;+ const { teamId } = req.query as { teamId: string };+ const userId = (session.user as CustomUser).id;- try {- // Verify user has access to the team- const teamAccess = await prisma.userTeam.findUnique({- where: {- userId_teamId: {- userId: userId,- teamId: teamId,- },- },- select: { teamId: true },- });+ // Verify user has access to the team+ const teamAccess = await prisma.userTeam.findUnique({+ where: {+ userId_teamId: {+ userId: userId,+ teamId: teamId,+ },+ },+ select: { teamId: true, role: true },+ });- if (!teamAccess) {- return res.status(401).end("Unauthorized");- }+ if (!teamAccess) {+ return res.status(401).end("Unauthorized");+ }+ if (req.method === "GET") {+ // GET /api/teams/:teamId/settings+ try {// Fetch only the settings fieldsconst teamSettings = await prisma.team.findUnique({where: {@@ -46,6 +53,7 @@ export default async function handle(select: {replicateDataroomFolders: true,enableExcelAdvancedMode: true,+ timezone: true,},});@@ -57,8 +65,59 @@ export default async function handle(} catch (error) {errorhandler(error, res);}+ } else if (req.method === "PATCH") {+ // PATCH /api/teams/:teamId/settings+ // Only admins and managers can update settings+ if (teamAccess.role !== "ADMIN" && teamAccess.role !== "MANAGER") {+ return res.status(403).json({ error: "Insufficient permissions" });+ }++ try {+ const result = updateSettingsSchema.safeParse(req.body);+ if (!result.success) {+ return res+ .status(400)+ .json({ error: `Invalid body: ${result.error.message}` });+ }++ const { timezone, replicateDataroomFolders, enableExcelAdvancedMode } =+ result.data;++ // Build update object with only provided fields+ const updateData: {+ timezone?: string;+ replicateDataroomFolders?: boolean;+ enableExcelAdvancedMode?: boolean;+ } = {};++ if (timezone !== undefined) {+ updateData.timezone = timezone;+ }+ if (replicateDataroomFolders !== undefined) {+ updateData.replicateDataroomFolders = replicateDataroomFolders;+ }+ if (enableExcelAdvancedMode !== undefined) {+ updateData.enableExcelAdvancedMode = enableExcelAdvancedMode;+ }++ const updatedTeam = await prisma.team.update({+ where: {+ id: teamId,+ },+ data: updateData,+ select: {+ replicateDataroomFolders: true,+ enableExcelAdvancedMode: true,+ timezone: true,+ },+ });++ return res.status(200).json(updatedTeam);+ } catch (error) {+ errorhandler(error, res);+ }} else {- res.setHeader("Allow", ["GET"]);+ res.setHeader("Allow", ["GET", "PATCH"]);return res.status(405).end(`Method ${req.method} Not Allowed`);}}diff --git a/pages/settings/general.tsx b/pages/settings/general.tsxindex e900402b..bedc8a24 100644--- a/pages/settings/general.tsx+++ b/pages/settings/general.tsx@@ -16,6 +16,7 @@ import DeleteTeam from "@/components/settings/delete-team";import GlobalBlockListForm from "@/components/settings/global-block-list-form";import IgnoredDomainsForm from "@/components/settings/ignored-domains-form";import { SettingsHeader } from "@/components/settings/settings-header";+import { TimezoneSelector } from "@/components/settings/timezone-selector";import { Form } from "@/components/ui/form";export default function General() {@@ -221,6 +222,7 @@ export default function General() {helpText="When enabled, folders uploaded to datarooms will be created in 'All Documents' with the same structure. When disabled, all documents will be placed in a single folder named after the dataroom in 'All Documents'."handleSubmit={handleReplicateFoldersChange}/>+ <TimezoneSelector /><IgnoredDomainsForm /><GlobalBlockListForm />diff --git a/prisma/migrations/20251230000000_add_timezone_to_team/migration.sql b/prisma/migrations/20251230000000_add_timezone_to_team/migration.sqlnew file mode 100644index 00000000..0bb8bc35--- /dev/null+++ b/prisma/migrations/20251230000000_add_timezone_to_team/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "Team" ADD COLUMN "timezone" TEXT NOT NULL DEFAULT 'Etc/UTC';diff --git a/prisma/schema/team.prisma b/prisma/schema/team.prismaindex 34e0d78f..1f59f670 100644--- a/prisma/schema/team.prisma+++ b/prisma/schema/team.prisma@@ -45,6 +45,7 @@ model Team {// team settingsenableExcelAdvancedMode Boolean @default(false) // Enable Excel advanced mode for all documents in the teamreplicateDataroomFolders Boolean @default(true) // Replicate dataroom folder structure in "All Documents"+ timezone String @default("Etc/UTC") // Team-wide timezone for analytics display (IANA timezone identifier)// AI agentsagentsEnabled Boolean @default(false) // Enable AI agents for the team