Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

feat: timeline annotations on the overview chart (#1164)

Goldflag8a6ea3c40371
diff --git a/client/src/api/analytics/endpoints/annotations.ts b/client/src/api/analytics/endpoints/annotations.ts
new file mode 100644
index 000000000..885701209
--- /dev/null
+++ b/client/src/api/analytics/endpoints/annotations.ts
@@ -0,0 +1,39 @@
+import type { Annotation, AnnotationColor, AnnotationScope } from "@rybbit/shared";
+import { authedFetch } from "../../utils";
+
+export type AnnotationWriteBody = {
+ title: string;
+ description?: string | null;
+ /** ISO 8601 timestamp. */
+ date: string;
+ /** ISO 8601 timestamp, or null to clear a range. */
+ endDate?: string | null;
+ color?: AnnotationColor | null;
+ icon?: string | null;
+ isPublic?: boolean;
+ scope?: AnnotationScope;
+};
+
+export function fetchAnnotations(site: string | number) {
+ return authedFetch<Annotation[]>(`/sites/${site}/annotations`);
+}
+
+export function createAnnotation(site: string | number, body: AnnotationWriteBody) {
+ return authedFetch<{ success: true; annotationId: number }>(`/sites/${site}/annotations`, undefined, {
+ method: "POST",
+ data: body,
+ });
+}
+
+export function updateAnnotation(site: string | number, annotationId: number, body: Partial<AnnotationWriteBody>) {
+ return authedFetch<{ success: true }>(`/sites/${site}/annotations/${annotationId}`, undefined, {
+ method: "PUT",
+ data: body,
+ });
+}
+
+export function deleteAnnotation(site: string | number, annotationId: number) {
+ return authedFetch<{ success: true }>(`/sites/${site}/annotations/${annotationId}`, undefined, {
+ method: "DELETE",
+ });
+}
diff --git a/client/src/api/analytics/hooks/useAnnotations.ts b/client/src/api/analytics/hooks/useAnnotations.ts
new file mode 100644
index 000000000..8615922e8
--- /dev/null
+++ b/client/src/api/analytics/hooks/useAnnotations.ts
@@ -0,0 +1,73 @@
+import type { Annotation } from "@rybbit/shared";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { authClient } from "../../../lib/auth";
+import { useStore } from "../../../lib/store";
+import {
+ AnnotationWriteBody,
+ createAnnotation,
+ deleteAnnotation,
+ fetchAnnotations,
+ updateAnnotation,
+} from "../endpoints/annotations";
+
+export const ANNOTATIONS_QUERY_KEY = "get-annotations";
+
+/**
+ * The endpoint returns different rows per viewer (members see everything,
+ * public and private-link viewers only public rows), so the cache is keyed by
+ * who is asking and waits for the session to resolve before fetching.
+ */
+export function useGetAnnotations(siteId?: string | number) {
+ const { privateKey } = useStore();
+ const session = authClient.useSession();
+ const viewer = privateKey ? `link:${privateKey}` : session.data?.user.id ? `user:${session.data.user.id}` : "anon";
+ return useQuery<Annotation[]>({
+ queryKey: [ANNOTATIONS_QUERY_KEY, siteId, viewer],
+ queryFn: () => fetchAnnotations(siteId!),
+ enabled: !!siteId && !session.isPending,
+ staleTime: 60_000,
+ });
+}
+
+export function useCreateAnnotation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: ({ siteId, body }: { siteId: string | number; body: AnnotationWriteBody }) =>
+ createAnnotation(siteId, body),
+ // Organization-wide annotations show on every site, so drop every cached list.
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: [ANNOTATIONS_QUERY_KEY] });
+ },
+ });
+}
+
+export function useUpdateAnnotation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: ({
+ siteId,
+ annotationId,
+ body,
+ }: {
+ siteId: string | number;
+ annotationId: number;
+ body: Partial<AnnotationWriteBody>;
+ }) => updateAnnotation(siteId, annotationId, body),
+ // Organization-wide annotations show on every site, so drop every cached list.
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: [ANNOTATIONS_QUERY_KEY] });
+ },
+ });
+}
+
+export function useDeleteAnnotation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: ({ siteId, annotationId }: { siteId: string | number; annotationId: number }) =>
+ deleteAnnotation(siteId, annotationId),
+ // Organization-wide annotations show on every site, so drop every cached list.
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: [ANNOTATIONS_QUERY_KEY] });
+ },
+ });
+}
diff --git a/client/src/app/[site]/main/components/MainSection/Chart.tsx b/client/src/app/[site]/main/components/MainSection/Chart.tsx
index 8d57db255..32c7b15a4 100644
--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx
@@ -1,7 +1,10 @@
"use client";
+import type { Annotation } from "@rybbit/shared";
import { DateTime } from "luxon";
-import { useMemo } from "react";
+import { useExtracted } from "next-intl";
+import { useEffect, useMemo, useState } from "react";
+import { createPortal } from "react-dom";
import type { GetOverviewBucketedResponse } from "../../../../../api/analytics/endpoints";
import { ChartTooltip } from "../../../../../components/charts/ChartTooltip";
@@ -12,6 +15,14 @@ import { formatChartDateTime } from "../../../../../lib/dateTimeUtils";
import { getTimezone, useStore } from "../../../../../lib/store";
import type { StatType } from "../../../../../lib/store";
import { formatSecondsAsMinutesAndSeconds } from "../../../../../lib/utils";
+import { useDeleteAnnotation } from "@/api/analytics/hooks/useAnnotations";
+import { ConfirmationModal } from "@/components/ConfirmationModal";
+import { toast } from "@/components/ui/sonner";
+import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";
+import { AnnotationHoverCard, AnnotationPopoverContent } from "./annotations/AnnotationDetails";
+import { AnnotationPins } from "./annotations/AnnotationPins";
+import type { AnnotationCluster } from "./annotations/annotationUtils";
+import { useAnnotationPermissions } from "./annotations/useAnnotationPermissions";
type Point = TimeSeriesChartPoint & {
currentTime: DateTime;
@@ -27,18 +38,52 @@ const formatTooltipValue = (value: number, selectedStat: StatType): string => {
return value.toLocaleString();
};
+type PinTarget = { cluster: AnnotationCluster; rect: DOMRect };
+
export function Chart({
data,
previousData,
max,
chartXMax,
+ annotations = [],
+ onCreateAnnotation,
+ onEditAnnotation,
}: {
data: GetOverviewBucketedResponse | undefined;
previousData: GetOverviewBucketedResponse | undefined;
max: number;
chartXMax: Date | undefined;
+ annotations?: Annotation[];
+ /** Set when the viewer may create; a click on the plot opens the form at that bucket. */
+ onCreateAnnotation?: (date: Date) => void;
+ onEditAnnotation?: (annotation: Annotation) => void;
}) {
- const { time, bucket, selectedStat, previousTime } = useStore();
+ const t = useExtracted();
+ const { time, bucket, selectedStat, previousTime, site } = useStore();
+ const { canManage } = useAnnotationPermissions();
+ const deleteAnnotation = useDeleteAnnotation();
+ const [hoveredPin, setHoveredPin] = useState<PinTarget | null>(null);
+ const [selectedPin, setSelectedPin] = useState<PinTarget | null>(null);
+ const [pendingDelete, setPendingDelete] = useState<Annotation | null>(null);
+
+ // The popover anchors to a snapshot of the pin's screen rect; once the
+ // window, bucket, site, or data changes the pin has moved or gone.
+ useEffect(() => {
+ setSelectedPin(null);
+ setHoveredPin(null);
+ }, [time, bucket, site, annotations]);
+
+ const confirmDelete = async () => {
+ if (!pendingDelete) return;
+ try {
+ await deleteAnnotation.mutateAsync({ siteId: site, annotationId: pendingDelete.annotationId });
+ toast.success(t("Annotation deleted"));
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : t("Could not delete the annotation"));
+ }
+ setPendingDelete(null);
+ setSelectedPin(null);
+ };
const timezone = getTimezone();
const isExactRange = time.mode === "range" && Boolean(time.startTime && time.endTime);
@@ -119,7 +164,11 @@ export function Chart({
};
}, [data, previousData, selectedStat, time, previousTime, bucket, timezone, chartXMax, isExactRange]);
+ const hoverLeft =
+ hoveredPin && typeof window !== "undefined" ? Math.min(hoveredPin.rect.right + 8, window.innerWidth - 272) : 0;
+
return (
+ <>
<TimeSeriesChart
current={current}
previous={previous}
@@ -127,6 +176,21 @@ export function Chart({
chartMin={chartMin}
chartMax={chartMax}
displayDashed={displayDashed}
+ onPlotClick={onCreateAnnotation}
+ renderOverlay={context =>
+ annotations.length ? (
+ <AnnotationPins
+ context={context}
+ annotations={annotations}
+ selectedKey={selectedPin?.cluster.key ?? null}
+ onSelect={(cluster, rect) => {
+ setHoveredPin(null);
+ setSelectedPin({ cluster, rect });
+ }}
+ onHover={(cluster, rect) => setHoveredPin(cluster && rect ? { cluster, rect } : null)}
+ />
+ ) : null
+ }
renderTooltip={({ point, previousPoint, bucket }) => {
const hoverCurrentY = point.y;
const hoverPreviousY = previousPoint?.y ?? 0;
@@ -169,5 +233,54 @@ export function Chart({
);
}}
/>
+
+ {hoveredPin &&
+ !selectedPin &&
+ typeof document !== "undefined" &&
+ createPortal(
+ <div
+ style={{
+ position: "fixed",
+ left: hoverLeft,
+ top: Math.max(8, hoveredPin.rect.top - 6),
+ pointerEvents: "none",
+ zIndex: 9999,
+ }}
+ >
+ <AnnotationHoverCard cluster={hoveredPin.cluster} />
+ </div>,
+ document.body
+ )}
+
+ {selectedPin && (
+ <Popover open onOpenChange={open => !open && setSelectedPin(null)}>
+ <PopoverAnchor virtualRef={{ current: { getBoundingClientRect: () => selectedPin.rect } }} />
+ <PopoverContent side="top" align="start" className="w-80 p-0">
+ <AnnotationPopoverContent
+ cluster={selectedPin.cluster}
+ canManage={canManage}
+ onEdit={annotation => {
+ setSelectedPin(null);
+ onEditAnnotation?.(annotation);
+ }}
+ onDelete={annotation => setPendingDelete(annotation)}
+ />
+ </PopoverContent>
+ </Popover>
+ )}
+
+ <ConfirmationModal
+ title={t("Delete annotation")}
+ description={
+ pendingDelete
+ ? t("Delete “{title}”? This cannot be undone.", { title: pendingDelete.title })
+ : ""
+ }
+ isOpen={!!pendingDelete}
+ setIsOpen={open => !open && setPendingDelete(null)}
+ onConfirm={confirmDelete}
+ primaryAction={{ variant: "destructive", children: t("Delete") }}
+ />
+ </>
);
}
diff --git a/client/src/app/[site]/main/components/MainSection/MainSection.tsx b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
index 31cfd2ab8..57f77d395 100644
--- a/client/src/app/[site]/main/components/MainSection/MainSection.tsx
+++ b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
@@ -2,8 +2,12 @@
import { Card, CardContent, CardLoader } from "@/components/ui/card";
import { DateTime } from "luxon";
import { Tilt_Warp } from "next/font/google";
+import { MessageSquarePlus } from "lucide-react";
import { useExtracted } from "next-intl";
import Link from "next/link";
+import { useState } from "react";
+import { useGetAnnotations } from "@/api/analytics/hooks/useAnnotations";
+import { Button } from "@/components/ui/button";
import { useGetOverview } from "../../../../../api/analytics/hooks/useGetOverview";
import { useGetOverviewBucketed } from "../../../../../api/analytics/hooks/useGetOverviewBucketed";
import { BucketSelection } from "../../../../../components/BucketSelection";
@@ -11,6 +15,8 @@ import { RybbitTextLogo } from "../../../../../components/RybbitLogo";
import { useWhiteLabel } from "../../../../../hooks/useIsWhiteLabel";
import { authClient } from "../../../../../lib/auth";
import { getTimezone, useStore } from "../../../../../lib/store";
+import { AnnotationFormDialog, type AnnotationEditorState } from "./annotations/AnnotationFormDialog";
+import { useAnnotationPermissions } from "./annotations/useAnnotationPermissions";
import { Chart } from "./Chart";
import { Overview } from "./Overview";
@@ -28,6 +34,10 @@ export function MainSection() {
const { selectedStat, time, site, bucket } = useStore();
+ const { data: annotations } = useGetAnnotations(site);
+ const { canCreate: canAnnotate } = useAnnotationPermissions();
+ const [annotationEditor, setAnnotationEditor] = useState<AnnotationEditorState | null>(null);
+
const getSelectedStatLabel = () => {
switch (selectedStat) {
case "pageviews": return t("Pageviews");
@@ -110,7 +120,15 @@ export function MainSection() {
)}
</div>
<span className="text-sm text-neutral-700 dark:text-neutral-200">{getSelectedStatLabel()}</span>
- <BucketSelection />
+ <div className="flex items-center gap-2">
+ {canAnnotate && (
+ <Button variant="outline" size="sm" onClick={() => setAnnotationEditor({ mode: "create" })}>
+ <MessageSquarePlus />
+ <span className="hidden sm:inline">{t("Annotate")}</span>
+ </Button>
+ )}
+ <BucketSelection />
+ </div>
</div>
<div className="h-[200px] md:h-[290px]">
<Chart
@@ -118,10 +136,14 @@ export function MainSection() {
max={maxOfDataAndPreviousData}
previousData={time.mode === "all-time" ? undefined : previousData}
chartXMax={chartXMax}
+ annotations={annotations}
+ onCreateAnnotation={canAnnotate ? date => setAnnotationEditor({ mode: "create", date }) : undefined}
+ onEditAnnotation={annotation => setAnnotationEditor({ mode: "edit", annotation })}
/>
</div>
</CardContent>
</Card>
+ <AnnotationFormDialog state={annotationEditor} onClose={() => setAnnotationEditor(null)} />
</>
);
}
diff --git a/client/src/app/[site]/main/components/MainSection/annotations/AnnotationDetails.tsx b/client/src/app/[site]/main/components/MainSection/annotations/AnnotationDetails.tsx
new file mode 100644
index 000000000..0001da554
--- /dev/null
+++ b/client/src/app/[site]/main/components/MainSection/annotations/AnnotationDetails.tsx
@@ -0,0 +1,107 @@
+"use client";
+
+import type { Annotation } from "@rybbit/shared";
+import { Pencil, Trash2 } from "lucide-react";
+import { useTheme } from "next-themes";
+import { useExtracted } from "next-intl";
+import { ChartTooltip } from "@/components/charts/ChartTooltip";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { getTimezone } from "@/lib/store";
+import { annotationColor, formatAnnotationDate, type AnnotationCluster } from "./annotationUtils";
+
+function ColorDot({ annotation }: { annotation: Annotation }) {
+ const { resolvedTheme } = useTheme();
+ return (
+ <span
+ className="w-2 h-2 rounded-[2px] shrink-0"
+ style={{ background: annotationColor(annotation.color, resolvedTheme === "dark") }}
+ />
+ );
+}
+
+/** Compact hover card: titles and the date, nothing interactive. */
+export function AnnotationHoverCard({ cluster }: { cluster: AnnotationCluster }) {
+ const timezone = getTimezone();
+ const first = cluster.items[0].annotation;
+ const last = cluster.items[cluster.items.length - 1].annotation;
+ const dateText =
+ cluster.items.length === 1 || first.date === last.date
+ ? formatAnnotationDate(first, timezone)
+ : `${formatAnnotationDate({ ...first, endDate: null }, timezone)} – ${formatAnnotationDate({ ...last, endDate: null }, timezone)}`;
+ return (
+ <ChartTooltip className="px-3 py-2 max-w-[260px]">
+ <div className="flex flex-col gap-1">
+ {cluster.items.map(({ annotation }) => (
+ <div key={annotation.annotationId} className="flex items-center gap-2 text-sm min-w-0">
+ <ColorDot annotation={annotation} />
+ <span className="truncate font-medium">
+ {annotation.icon ? `${annotation.icon} ` : ""}
+ {annotation.title}
+ </span>
+ </div>
+ ))}
+ </div>
+ <div className="text-xs text-muted-foreground mt-1 tabular-nums">{dateText}</div>
+ </ChartTooltip>
+ );
+}
+
+/** Full details for a pin, with edit and delete for those allowed to manage. */
+export function AnnotationPopoverContent({
+ cluster,
+ canManage,
+ onEdit,
+ onDelete,
+}: {
+ cluster: AnnotationCluster;
+ canManage: (annotation: Annotation) => boolean;
+ onEdit: (annotation: Annotation) => void;
+ onDelete: (annotation: Annotation) => void;
+}) {
+ const t = useExtracted();
+ const timezone = getTimezone();
+ return (
+ <div className="flex flex-col divide-y divide-neutral-100 dark:divide-neutral-800 max-h-[320px] overflow-y-auto">
+ {cluster.items.map(({ annotation }) => (
+ <div key={annotation.annotationId} className="px-3 py-2.5 flex flex-col gap-1">
+ <div className="flex items-start gap-2">
+ <div className="flex items-center gap-2 min-w-0 flex-1 pt-0.5">
+ <ColorDot annotation={annotation} />
+ <span className="font-medium text-sm leading-tight break-words">
+ {annotation.icon ? `${annotation.icon} ` : ""}
+ {annotation.title}
+ </span>
+ </div>
+ {canManage(annotation) && (
+ <div className="flex items-center -mr-1.5 -mt-1 shrink-0">
+ <Button variant="ghost" size="smIcon" aria-label={t("Edit annotation")} onClick={() => onEdit(annotation)}>
+ <Pencil className="w-3.5 h-3.5" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="smIcon"
+ aria-label={t("Delete annotation")}
+ onClick={() => onDelete(annotation)}
+ >
+ <Trash2 className="w-3.5 h-3.5" />
+ </Button>
+ </div>
+ )}
+ </div>
+ <div className="flex items-center gap-1.5 flex-wrap text-xs text-muted-foreground tabular-nums">
+ <span>{formatAnnotationDate(annotation, timezone)}</span>
+ {annotation.siteId === null && <Badge variant="outline">{t("All sites")}</Badge>}
+ {annotation.isPublic && <Badge variant="success">{t("Public")}</Badge>}
+ </div>
+ {annotation.description && (
+ <p className="text-sm text-neutral-700 dark:text-neutral-300 whitespace-pre-wrap break-words">
+ {annotation.description}
+ </p>
+ )}
+ {annotation.userName && <div className="text-xs text-muted-foreground">{annotation.userName}</div>}
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/main/components/MainSection/annotations/AnnotationFormDialog.tsx b/client/src/app/[site]/main/components/MainSection/annotations/AnnotationFormDialog.tsx
new file mode 100644
index 000000000..6fe6a89f6
--- /dev/null
+++ b/client/src/app/[site]/main/components/MainSection/annotations/AnnotationFormDialog.tsx
@@ -0,0 +1,386 @@
+"use client";
+
+import type { Annotation, AnnotationColor, AnnotationScope } from "@rybbit/shared";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+import { useEffect, useMemo } from "react";
+import { useForm } from "react-hook-form";
+import * as z from "zod";
+import { useCreateAnnotation, useUpdateAnnotation } from "@/api/analytics/hooks/useAnnotations";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { toast } from "@/components/ui/sonner";
+import { Switch } from "@/components/ui/switch";
+import { Textarea } from "@/components/ui/textarea";
+import { getTimezone, useStore } from "@/lib/store";
+import { cn } from "@/lib/utils";
+import {
+ ANNOTATION_COLOR_OPTIONS,
+ ANNOTATION_ICON_OPTIONS,
+ annotationSwatch,
+ toDateInput,
+} from "./annotationUtils";
+import { useAnnotationPermissions } from "./useAnnotationPermissions";
+
+export type AnnotationEditorState =
+ | { mode: "create"; date?: Date }
+ | { mode: "edit"; annotation: Annotation };
+
+type FormValues = {
+ title: string;
+ date: string;
+ isRange: boolean;
+ endDate: string;
+ description: string;
+ color: AnnotationColor | null;
+ icon: string | null;
+ scope: AnnotationScope;
+ isPublic: boolean;
+};
+
+export function AnnotationFormDialog({
+ state,
+ onClose,
+}: {
+ state: AnnotationEditorState | null;
+ onClose: () => void;
+}) {
+ const t = useExtracted();
+ const { site } = useStore();
+ const timezone = getTimezone();
+ const { isAdmin } = useAnnotationPermissions();
+ const createAnnotation = useCreateAnnotation();
+ const updateAnnotation = useUpdateAnnotation();
+
+ const schema = useMemo(
+ () =>
+ z
+ .object({
+ title: z.string().trim().min(1, t("Title is required")).max(120, t("Keep the title under 120 characters")),
+ date: z.string().min(1, t("Pick a date")),
+ isRange: z.boolean(),
+ endDate: z.string(),
+ description: z.string().max(2000, t("Keep the note under 2000 characters")),
+ color: z.enum(ANNOTATION_COLOR_OPTIONS as [AnnotationColor, ...AnnotationColor[]]).nullable(),
+ icon: z.string().nullable(),
+ scope: z.enum(["site", "organization"]),
+ isPublic: z.boolean(),
+ })
+ .refine(values => !values.isRange || (values.endDate !== "" && values.endDate >= values.date), {
+ message: t("End date must not be before the start date"),
+ path: ["endDate"],
+ }),
+ [t]
+ );
+
+ const defaults = useMemo<FormValues>(() => {
+ if (state?.mode === "edit") {
+ const a = state.annotation;
+ return {
+ title: a.title,
+ date: toDateInput(a.date, timezone),
+ isRange: !!a.endDate,
+ endDate: a.endDate ? toDateInput(a.endDate, timezone) : "",
+ description: a.description ?? "",
+ color: a.color,
+ icon: a.icon,
+ scope: a.siteId === null ? "organization" : "site",
+ isPublic: a.isPublic,
+ };
+ }
+ const clicked = state?.mode === "create" ? state.date : undefined;
+ return {
+ title: "",
+ date: (clicked ? DateTime.fromJSDate(clicked).setZone(timezone) : DateTime.now().setZone(timezone)).toISODate() ?? "",
+ isRange: false,
+ endDate: "",
+ description: "",
+ color: null,
+ icon: null,
+ scope: "site",
+ isPublic: false,
+ };
+ }, [state, timezone]);
+
+ const form = useForm<FormValues>({ resolver: zodResolver(schema), defaultValues: defaults });
+
+ // Each open gets fresh values for the annotation (or click) it was opened for.
+ useEffect(() => {
+ if (state) form.reset(defaults);
+ }, [state, defaults, form]);
+
+ const isRange = form.watch("isRange");
+ const isPending = createAnnotation.isPending || updateAnnotation.isPending;
+
+ const onSubmit = async (values: FormValues) => {
+ if (!state) return;
+ const existing = state.mode === "edit" ? state.annotation : undefined;
+ const clicked = state.mode === "create" ? state.date : undefined;
+ const clickedDay = clicked ? DateTime.fromJSDate(clicked).setZone(timezone).toISODate() : null;
+ const dayStart = (day: string) => DateTime.fromISO(day, { zone: timezone }).startOf("day").toUTC().toISO() ?? day;
+ const dayEnd = (day: string) => DateTime.fromISO(day, { zone: timezone }).endOf("day").toUTC().toISO() ?? day;
+
+ // Untouched dates keep their stored instant: an hourly or API-created
+ // annotation must not snap to midnight because the title was edited.
+ // A click on an hour bucket likewise keeps its hour unless the day changed.
+ const startIso =
+ existing && values.date === defaults.date
+ ? existing.date
+ : clicked && clickedDay === values.date
+ ? clicked.toISOString()
+ : dayStart(values.date);
+ const endIso = !values.isRange
+ ? null
+ : existing?.endDate && values.endDate === defaults.endDate
+ ? existing.endDate
+ : dayEnd(values.endDate);
+
+ const body = {
+ title: values.title.trim(),
+ description: values.description.trim() || null,
+ date: startIso,
+ endDate: endIso,
+ color: values.color,
+ icon: values.icon,
+ isPublic: values.isPublic,
+ scope: values.scope,
+ };
+
+ try {
+ if (state.mode === "edit") {
+ await updateAnnotation.mutateAsync({ siteId: site, annotationId: state.annotation.annotationId, body });
+ toast.success(t("Annotation updated"));
+ } else {
+ await createAnnotation.mutateAsync({ siteId: site, body });
+ toast.success(t("Annotation added"));
+ }
+ onClose();
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : t("Could not save the annotation"));
+ }
+ };
+
+ return (
+ <Dialog open={!!state} onOpenChange={open => !open && onClose()}>
+ <DialogContent className="sm:max-w-[440px]">
+ <DialogHeader>
+ <DialogTitle>{state?.mode === "edit" ? t("Edit annotation") : t("New annotation")}</DialogTitle>
+ <DialogDescription>{t("A note pinned to the chart, so this moment stays explainable later.")}</DialogDescription>
+ </DialogHeader>
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-4">
+ <FormField
+ control={form.control}
+ name="title"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>{t("Title")}</FormLabel>
+ <FormControl>
+ <Input placeholder={t("What happened?")} autoFocus maxLength={120} {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <div className="grid grid-cols-2 gap-3">
+ <FormField
+ control={form.control}
+ name="date"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>{isRange ? t("Start date") : t("Date")}</FormLabel>
+ <FormControl>
+ <Input type="date" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ {isRange ? (
+ <FormField
+ control={form.control}
+ name="endDate"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>{t("End date")}</FormLabel>
+ <FormControl>
+ <Input type="date" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ ) : (
+ <div className="flex items-end pb-2">
+ <FormField
+ control={form.control}
+ name="isRange"
+ render={({ field }) => (
+ <div className="flex items-center gap-2">
+ <Switch id="annotation-range" checked={field.value} onCheckedChange={field.onChange} />
+ <Label htmlFor="annotation-range" className="text-sm font-normal">
+ {t("Date range")}
+ </Label>
+ </div>
+ )}
+ />
+ </div>
+ )}
+ </div>
+ {isRange && (
+ <FormField
+ control={form.control}
+ name="isRange"
+ render={({ field }) => (
+ <div className="flex items-center gap-2 -mt-2">
+ <Switch id="annotation-range" checked={field.value} onCheckedChange={field.onChange} />
+ <Label htmlFor="annotation-range" className="text-sm font-normal">
+ {t("Date range")}
+ </Label>
+ </div>
+ )}
+ />
+ )}
+
+ <FormField
+ control={form.control}
+ name="description"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ {t("Note")} <span className="text-muted-foreground font-normal">({t("optional")})</span>
+ </FormLabel>
+ <FormControl>
+ <Textarea rows={2} placeholder={t("What changed and why it matters")} maxLength={2000} {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <div className="grid grid-cols-2 gap-3">
+ <FormField
+ control={form.control}
+ name="color"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>{t("Color")}</FormLabel>
+ <div className="flex items-center gap-2 h-9">
+ {[null, ...ANNOTATION_COLOR_OPTIONS].map(color => (
+ <button
+ key={color ?? "neutral"}
+ type="button"
+ aria-label={color ?? t("Neutral")}
+ aria-pressed={field.value === color}
+ onClick={() => field.onChange(color)}
+ className={cn(
+ "w-5 h-5 rounded-full border-2 border-transparent transition-shadow",
+ field.value === color && "ring-1 ring-offset-2 ring-neutral-900 dark:ring-neutral-100 ring-offset-white dark:ring-offset-neutral-900"
+ )}
+ style={{ background: annotationSwatch(color) }}
+ />
+ ))}
+ </div>
+ </FormItem>
+ )}
+ />
+ {isAdmin && (
+ <FormField
+ control={form.control}
+ name="scope"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>{t("Applies to")}</FormLabel>
+ <div className="inline-flex h-9 items-center rounded-lg border border-neutral-150 dark:border-neutral-750 p-0.5 text-xs">
+ {(["site", "organization"] as const).map(scope => (
+ <button
+ key={scope}
+ type="button"
+ aria-pressed={field.value === scope}
+ onClick={() => field.onChange(scope)}
+ className={cn(
+ "px-2.5 h-full rounded-md transition-colors",
+ field.value === scope
+ ? "bg-neutral-100 dark:bg-neutral-800 text-neutral-900 dark:text-neutral-50"
+ : "text-muted-foreground hover:text-neutral-900 dark:hover:text-neutral-50"
+ )}
+ >
+ {scope === "site" ? t("This site") : t("All sites")}
+ </button>
+ ))}
+ </div>
+ </FormItem>
+ )}
+ />
+ )}
+ </div>
+
+ <FormField
+ control={form.control}
+ name="icon"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ {t("Icon")} <span className="text-muted-foreground font-normal">({t("optional")})</span>
+ </FormLabel>
+ <div className="flex flex-wrap gap-1">
+ {ANNOTATION_ICON_OPTIONS.map(icon => (
+ <button
+ key={icon}
+ type="button"
+ aria-pressed={field.value === icon}
+ onClick={() => field.onChange(field.value === icon ? null : icon)}
+ className={cn(
+ "w-8 h-8 rounded-md border text-base leading-none transition-colors",
+ field.value === icon
+ ? "border-neutral-900 dark:border-neutral-100 bg-neutral-100 dark:bg-neutral-800"
+ : "border-neutral-150 dark:border-neutral-750 hover:bg-neutral-50 dark:hover:bg-neutral-800"
+ )}
+ >
+ {icon}
+ </button>
+ ))}
+ </div>
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="isPublic"
+ render={({ field }) => (
+ <div className="flex items-center gap-2">
+ <Switch id="annotation-public" checked={field.value} onCheckedChange={field.onChange} />
+ <Label htmlFor="annotation-public" className="text-sm font-normal">
+ {t("Show on public dashboard and shared links")}
+ </Label>
+ </div>
+ )}
+ />
+
+ <DialogFooter className="mt-1">
+ <Button type="button" variant="outline" onClick={onClose} disabled={isPending}>
+ {t("Cancel")}
+ </Button>
+ <Button type="submit" variant="success" disabled={isPending}>
+ {state?.mode === "edit" ? t("Save changes") : t("Add annotation")}
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/client/src/app/[site]/main/components/MainSection/annotations/AnnotationPins.tsx b/client/src/app/[site]/main/components/MainSection/annotations/AnnotationPins.tsx
new file mode 100644
index 000000000..34325544e
--- /dev/null
+++ b/client/src/app/[site]/main/components/MainSection/annotations/AnnotationPins.tsx
@@ -0,0 +1,125 @@
+"use client";
+
+import type { Annotation } from "@rybbit/shared";
+import { StickyNote } from "lucide-react";
+import { useMemo } from "react";
+import type { TimeSeriesOverlayContext } from "@/components/charts/TimeSeriesChart";
+import { annotationColor, clusterAnnotations, type AnnotationCluster, type PositionedAnnotation } from "./annotationUtils";
+
+const PIN_RADIUS = 11;
+// Pins closer than this merge into one counted pin.
+const CLUSTER_GAP = 26;
+
+export function AnnotationPins({
+ context,
+ annotations,
+ selectedKey,
+ onSelect,
+ onHover,
+}: {
+ context: TimeSeriesOverlayContext;
+ annotations: Annotation[];
+ selectedKey: string | null;
+ onSelect: (cluster: AnnotationCluster, anchor: DOMRect) => void;
+ onHover: (cluster: AnnotationCluster | null, anchor?: DOMRect) => void;
+}) {
+ const { xScale, yScale, plotLeft, plotRight, plotTop, plotBottom, pointAt, isDark } = context;
+
+ const clusters = useMemo(() => {
+ const [min, max] = xScale.domain();
+ const positioned: PositionedAnnotation[] = [];
+ for (const annotation of annotations) {
+ const start = new Date(annotation.date);
+ const end = annotation.endDate ? new Date(annotation.endDate) : null;
+ if (start > max || (end ?? start) < min) continue;
+ // A range that began before the visible window pins at the left edge.
+ const anchor = start < min ? min : start;
+ const point = pointAt(anchor);
+ positioned.push({
+ annotation,
+ x: Math.max(plotLeft, Math.min(plotRight, xScale(anchor))),
+ x2: end ? Math.max(plotLeft, Math.min(plotRight, xScale(end))) : null,
+ y: point ? yScale(point.y) : plotBottom,
+ });
+ }
+ return clusterAnnotations(positioned, CLUSTER_GAP);
+ }, [annotations, xScale, yScale, pointAt, plotLeft, plotRight, plotBottom]);
+
+ if (!clusters.length) return null;
+
+ const pinFill = isDark ? "hsl(var(--neutral-900))" : "white";
+ const badgeFill = isDark ? "hsl(var(--neutral-50))" : "hsl(var(--neutral-900))";
+ const badgeText = isDark ? "hsl(var(--neutral-900))" : "white";
+
+ return (
+ <g>
+ {clusters.map(cluster => {
+ const first = cluster.items[0].annotation;
+ const single = cluster.items.length === 1;
+ const color = annotationColor(single ? first.color : null, isDark);
+ const selected = cluster.key === selectedKey;
+ const r = selected ? PIN_RADIUS + 1 : PIN_RADIUS;
+ // Sit above the data point; clamp so a pin on the peak stays inside the plot.
+ const pinY = Math.max(plotTop + r + 1, cluster.y - r - 9);
+ const label = single ? first.title : `${cluster.items.length} annotations`;
+ // The count badge hangs off the top-right of the pin; near the right
+ // edge it would leave the SVG, so it flips to the top-left.
+ const badgeX = cluster.x + r + 6 > plotRight ? cluster.x - r + 2 : cluster.x + r - 2;
+ return (
+ <g key={cluster.key}>
+ {cluster.items
+ .filter(item => item.x2 !== null)
+ .map(item => {
+ const bandColor = annotationColor(item.annotation.color, isDark);
+ const width = Math.max(0, (item.x2 ?? item.x) - item.x);
+ return (
+ <g key={item.annotation.annotationId} pointerEvents="none">
+ <rect x={item.x} y={plotTop} width={width} height={plotBottom - plotTop} fill={bandColor} opacity={0.08} />
+ <rect x={item.x} y={plotTop} width={width} height={2} fill={bandColor} />
+ </g>
+ );
+ })}
+ <g
+ role="button"
+ aria-label={label}
+ style={{ cursor: "pointer" }}
+ onClick={e => {
+ e.stopPropagation();
+ onSelect(cluster, e.currentTarget.getBoundingClientRect());
+ }}
+ onMouseEnter={e => onHover(cluster, e.currentTarget.getBoundingClientRect())}
+ onMouseLeave={() => onHover(null)}
+ >
+ <line x1={cluster.x} x2={cluster.x} y1={pinY + r} y2={cluster.y - 2} stroke={color} strokeWidth={1.5} />
+ <circle cx={cluster.x} cy={cluster.y} r={2.5} fill={color} />
+ <circle cx={cluster.x} cy={pinY} r={r} fill={pinFill} stroke={color} strokeWidth={selected ? 2 : 1.5} />
+ {first.icon ? (
+ <text x={cluster.x} y={pinY} dy="0.36em" textAnchor="middle" fontSize={11.5} pointerEvents="none">
+ {first.icon}
+ </text>
+ ) : (
+ <StickyNote x={cluster.x - 6} y={pinY - 6} width={12} height={12} color={color} strokeWidth={2} pointerEvents="none" />
+ )}
+ {!single && (
+ <g pointerEvents="none">
+ <circle cx={badgeX} cy={pinY - r + 2} r={7} fill={badgeFill} />
+ <text
+ x={badgeX}
+ y={pinY - r + 2}
+ dy="0.35em"
+ textAnchor="middle"
+ fontSize={9}
+ fontWeight={600}
+ fill={badgeText}
+ >
+ {cluster.items.length}
+ </text>
+ </g>
+ )}
+ </g>
+ </g>
+ );
+ })}
+ </g>
+ );
+}
diff --git a/client/src/app/[site]/main/components/MainSection/annotations/annotationUtils.test.ts b/client/src/app/[site]/main/components/MainSection/annotations/annotationUtils.test.ts
new file mode 100644
index 000000000..c1cc67ab1
--- /dev/null
+++ b/client/src/app/[site]/main/components/MainSection/annotations/annotationUtils.test.ts
@@ -0,0 +1,68 @@
+import type { Annotation } from "@rybbit/shared";
+import { describe, expect, it } from "vitest";
+import { clusterAnnotations, formatAnnotationDate, toDateInput, type PositionedAnnotation } from "./annotationUtils";
+
+const base: Annotation = {
+ annotationId: 1,
+ siteId: 1,
+ organizationId: "org",
+ userId: "u",
+ userName: "Bill",
+ title: "Launch",
+ description: null,
+ date: "2026-08-18T07:00:00.000Z",
+ endDate: null,
+ color: null,
+ icon: null,
+ isPublic: false,
+ createdAt: "",
+ updatedAt: "",
+};
+
+const at = (annotationId: number, x: number, y: number, x2: number | null = null): PositionedAnnotation => ({
+ annotation: { ...base, annotationId },
+ x,
+ x2,
+ y,
+});
+
+describe("clusterAnnotations", () => {
+ it("merges pins closer than the gap and keeps the highest point", () => {
+ const clusters = clusterAnnotations([at(1, 100, 80), at(2, 110, 40), at(3, 200, 60)], 26);
+ expect(clusters.map(c => c.items.length)).toEqual([2, 1]);
+ expect(clusters[0].y).toBe(40);
+ expect(clusters[0].x).toBe(105);
+ expect(clusters[0].key).toBe("1-2");
+ });
+
+ it("measures the gap from the first pin of the group, not the last", () => {
+ // Three pins 20px apart: the third is 40px from the first, so it starts a new group.
+ const clusters = clusterAnnotations([at(1, 0, 0), at(2, 20, 0), at(3, 40, 0)], 26);
+ expect(clusters.map(c => c.items.length)).toEqual([2, 1]);
+ });
+
+ it("sorts by x before grouping", () => {
+ const clusters = clusterAnnotations([at(2, 300, 0), at(1, 10, 0), at(3, 20, 0)], 26);
+ expect(clusters.map(c => c.key)).toEqual(["1-3", "2"]);
+ });
+});
+
+describe("formatAnnotationDate", () => {
+ it("prints a whole day as a date and an instant with its time", () => {
+ // 2026-08-18T07:00Z is midnight in Los Angeles.
+ expect(formatAnnotationDate(base, "America/Los_Angeles")).toBe("Aug 18, 2026");
+ expect(formatAnnotationDate(base, "UTC")).toMatch(/Aug 18, 2026, 7:00/);
+ });
+
+ it("prints whole-day ranges as two dates", () => {
+ const range = { ...base, date: "2026-08-11T00:00:00.000Z", endDate: "2026-08-14T23:59:59.999Z" };
+ expect(formatAnnotationDate(range, "UTC")).toBe("Aug 11, 2026 – Aug 14, 2026");
+ });
+});
+
+describe("toDateInput", () => {
+ it("gives the calendar date in the user's timezone", () => {
+ expect(toDateInput("2026-08-18T07:00:00.000Z", "America/Los_Angeles")).toBe("2026-08-18");
+ expect(toDateInput("2026-08-18T03:00:00.000Z", "America/Los_Angeles")).toBe("2026-08-17");
+ });
+});
diff --git a/client/src/app/[site]/main/components/MainSection/annotations/annotationUtils.ts b/client/src/app/[site]/main/components/MainSection/annotations/annotationUtils.ts
new file mode 100644
index 000000000..efd92bbfe
--- /dev/null
+++ b/client/src/app/[site]/main/components/MainSection/annotations/annotationUtils.ts
@@ -0,0 +1,85 @@
+import type { Annotation, AnnotationColor } from "@rybbit/shared";
+import { DateTime } from "luxon";
+
+// Mirrors ANNOTATION_COLORS in @rybbit/shared, which the client imports for
+// types only (its runtime values would force Turbopack to bundle the
+// workspace package). Keep the two in sync.
+export const ANNOTATION_COLOR_OPTIONS: AnnotationColor[] = ["amber", "rose", "sky", "violet", "lime"];
+export const ANNOTATION_ICON_OPTIONS = ["🚀", "🏷️", "📣", "🧪", "🐛", "✉️", "📰", "🔥", "✨", "🛠️"];
+
+/** Marker color for the chart, tuned per theme. Neutral when unset. */
+export function annotationColor(color: AnnotationColor | null | undefined, isDark: boolean): string {
+ if (!color) return isDark ? "hsl(var(--neutral-400))" : "hsl(var(--neutral-500))";
+ return `hsl(var(--${color}-${isDark ? 400 : 600}))`;
+}
+
+/** Swatch color for the form; the 500 step reads the same on both themes. */
+export function annotationSwatch(color: AnnotationColor | null): string {
+ return color ? `hsl(var(--${color}-500))` : "hsl(var(--neutral-400))";
+}
+
+function toZoned(iso: string, timezone: string): DateTime {
+ return DateTime.fromISO(iso, { zone: "utc" }).setZone(timezone);
+}
+
+function isStartOfDay(dt: DateTime): boolean {
+ return dt.equals(dt.startOf("day"));
+}
+
+// Ranges are stored as [start of day, end of day], so an end that sits on the
+// last millisecond of its day is a whole-day end and prints as a date.
+function isEndOfDay(dt: DateTime): boolean {
+ return dt.equals(dt.endOf("day"));
+}
+
+export function formatAnnotationDate(annotation: Annotation, timezone: string): string {
+ const start = toZoned(annotation.date, timezone);
+ const startText = start.toLocaleString(isStartOfDay(start) ? DateTime.DATE_MED : DateTime.DATETIME_MED);
+ if (!annotation.endDate) return startText;
+ const end = toZoned(annotation.endDate, timezone);
+ const endText = end.toLocaleString(isEndOfDay(end) ? DateTime.DATE_MED : DateTime.DATETIME_MED);
+ return `${startText} – ${endText}`;
+}
+
+/** Calendar date (YYYY-MM-DD) of an instant in the user's timezone, for date inputs. */
+export function toDateInput(iso: string, timezone: string): string {
+ return toZoned(iso, timezone).toISODate() ?? "";
+}
+
+export type PositionedAnnotation = {
+ annotation: Annotation;
+ x: number;
+ /** Right edge of a range annotation, in plot px. */
+ x2: number | null;
+ y: number;
+};
+
+export type AnnotationCluster = {
+ key: string;
+ x: number;
+ /** Highest data point among the members, so the pin sits above the line. */
+ y: number;
+ items: PositionedAnnotation[];
+};
+
+/** Merge pins that would overlap (closer than `gap` px) into one counted pin. */
+export function clusterAnnotations(items: PositionedAnnotation[], gap: number): AnnotationCluster[] {
+ const sorted = [...items].sort((a, b) => a.x - b.x);
+ const groups: { x0: number; x: number; y: number; items: PositionedAnnotation[] }[] = [];
+ for (const item of sorted) {
+ const last = groups[groups.length - 1];
+ if (last && item.x - last.x0 < gap) {
+ last.items.push(item);
+ last.x = (last.x0 + item.x) / 2;
+ last.y = Math.min(last.y, item.y);
+ } else {
+ groups.push({ x0: item.x, x: item.x, y: item.y, items: [item] });
+ }
+ }
+ return groups.map(group => ({
+ key: group.items.map(item => item.annotation.annotationId).join("-"),
+ x: group.x,
+ y: group.y,
+ items: group.items,
+ }));
+}
diff --git a/client/src/app/[site]/main/components/MainSection/annotations/useAnnotationPermissions.ts b/client/src/app/[site]/main/components/MainSection/annotations/useAnnotationPermissions.ts
new file mode 100644
index 000000000..0e8c75c83
--- /dev/null
+++ b/client/src/app/[site]/main/components/MainSection/annotations/useAnnotationPermissions.ts
@@ -0,0 +1,41 @@
+"use client";
+
+import type { Annotation } from "@rybbit/shared";
+import { useQuery } from "@tanstack/react-query";
+import { getUserOrganizations, USER_ORGANIZATIONS_QUERY_KEY } from "@/api/admin/endpoints";
+import { useGetSite } from "@/api/admin/hooks/useSites";
+import { authClient } from "@/lib/auth";
+import { useStore } from "@/lib/store";
+
+/**
+ * Who may do what with annotations on the current site. Mirrors the server
+ * rules: members create and manage their own, admins and owners manage all,
+ * and public or private-link viewers only read.
+ */
+export function useAnnotationPermissions() {
+ const { site, privateKey } = useStore();
+ const session = authClient.useSession();
+ const userId = session.data?.user.id;
+ const signedIn = !!userId && !privateKey;
+
+ const { data: siteData } = useGetSite(site, { enabled: signedIn });
+ // A signed-in visitor on someone else's public dashboard has a session but
+ // no membership; the organization list tells the two apart.
+ const { data: organizations } = useQuery({
+ queryKey: [USER_ORGANIZATIONS_QUERY_KEY],
+ queryFn: getUserOrganizations,
+ enabled: signedIn,
+ });
+
+ const isAdmin = signedIn && !!siteData?.isOwner;
+ const isMember =
+ isAdmin ||
+ (!!siteData?.organizationId && !!organizations?.some(org => org.id === siteData.organizationId));
+
+ return {
+ canCreate: signedIn && isMember,
+ isAdmin,
+ canManage: (annotation: Annotation) =>
+ isAdmin || (annotation.siteId !== null && signedIn && annotation.userId === userId),
+ };
+}
diff --git a/client/src/app/settings/account/components/ApiKeyScopePicker.tsx b/client/src/app/settings/account/components/ApiKeyScopePicker.tsx
index 783c912ae..e1c24c06b 100644
--- a/client/src/app/settings/account/components/ApiKeyScopePicker.tsx
+++ b/client/src/app/settings/account/components/ApiKeyScopePicker.tsx
@@ -18,6 +18,7 @@ const SCOPE_MATRIX = {
goals: ["read", "write"],
funnels: ["read", "write"],
dashboards: ["read", "write"],
+ annotations: ["read", "write"],
segments: ["read", "write"],
flags: ["read", "write"],
experiments: ["read", "write"],
@@ -40,6 +41,7 @@ const SCOPE_DESCRIPTORS: { resource: ScopeResource; label: string; description:
{ resource: "goals", label: "Goals", description: "Conversion goals" },
{ resource: "funnels", label: "Funnels", description: "Saved and ad-hoc conversion funnels" },
{ resource: "dashboards", label: "Dashboards", description: "Saved dashboards" },
+ { resource: "annotations", label: "Annotations", description: "Timeline notes on the traffic chart" },
{ resource: "segments", label: "Segments", description: "Saved filter segments" },
{ resource: "flags", label: "Feature flags", description: "Feature flag definitions and evaluation" },
{ resource: "experiments", label: "Experiments", description: "A/B experiments and their results" },
diff --git a/client/src/components/charts/TimeSeriesChart.tsx b/client/src/components/charts/TimeSeriesChart.tsx
index 2fef9cd54..bbbf35ddf 100644
--- a/client/src/components/charts/TimeSeriesChart.tsx
+++ b/client/src/components/charts/TimeSeriesChart.tsx
@@ -44,6 +44,19 @@ export type TimeSeriesChartMarker = {
strokeDasharray?: string;
};
+/** Geometry handed to `renderOverlay` so callers can draw on top of the plot. */
+export type TimeSeriesOverlayContext = {
+ xScale: d3.ScaleTime<number, number>;
+ yScale: d3.ScaleLinear<number, number>;
+ plotLeft: number;
+ plotRight: number;
+ plotTop: number;
+ plotBottom: number;
+ /** Nearest primary data point to an instant, if the chart has data. */
+ pointAt: (x: Date) => TimeSeriesChartPoint | undefined;
+ isDark: boolean;
+};
+
type TimeSeriesTooltipContext<CurrentPoint extends TimeSeriesChartPoint, PreviousPoint extends TimeSeriesChartPoint> = {
point: CurrentPoint;
previousPoint?: PreviousPoint;
@@ -76,6 +89,10 @@ type TimeSeriesChartProps<
/** Disable click-drag range zoom (e.g. for embedded dashboard cards). */
disableDragZoom?: boolean;
renderTooltip: (context: TimeSeriesTooltipContext<CurrentPoint, PreviousPoint>) => ReactNode;
+ /** SVG drawn above the plot's hit area, so its own elements receive pointer events. */
+ renderOverlay?: (context: TimeSeriesOverlayContext) => ReactNode;
+ /** A click (not a drag) on the plot; receives the start of the bucket under the cursor. */
+ onPlotClick?: (date: Date) => void;
};
const hasDuplicateTickLabels = (ticks: Date[], formatLabel: (tick: Date) => string): boolean => {
@@ -193,6 +210,8 @@ export function TimeSeriesChart<
yTickFormat = formatter,
disableDragZoom = false,
renderTooltip,
+ renderOverlay,
+ onPlotClick,
}: TimeSeriesChartProps<CurrentPoint, PreviousPoint>) {
const { time, bucket, setTime, setBucket } = useStore();
const { resolvedTheme } = useTheme();
@@ -556,6 +575,14 @@ export function TimeSeriesChart<
window.removeEventListener("mouseup", onUp);
setDragRaw(null);
if (!moved) return;
+ // The click event that follows mouseup must not create an annotation.
+ // It fires in the same task, so a macrotask later the flag is stale and
+ // must not swallow an unrelated later click (a drag ending off-plot
+ // produces no click at all).
+ suppressClickRef.current = true;
+ setTimeout(() => {
+ suppressClickRef.current = false;
+ }, 0);
const leftPx = Math.min(startX, currentX);
const rightPx = Math.max(startX, currentX);
const startBucket = pxToBucketStart(leftPx);
@@ -591,7 +618,41 @@ export function TimeSeriesChart<
window.addEventListener("mouseup", onUp);
};
+ const suppressClickRef = useRef(false);
+ const hasDomain = Boolean(W && chartMin && chartMax);
+ // A single click is deferred past the double-click window so dblclick
+ // (zoom restore) can cancel it; otherwise the first click's action would
+ // swallow the second click.
+ const pendingClickRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ useEffect(() => () => {
+ if (pendingClickRef.current) clearTimeout(pendingClickRef.current);
+ }, []);
+ const handleClick = (e: React.MouseEvent<SVGRectElement>) => {
+ if (suppressClickRef.current) {
+ suppressClickRef.current = false;
+ return;
+ }
+ if (!onPlotClick || !hasDomain) return;
+ const rect = e.currentTarget.getBoundingClientRect();
+ const px = Math.max(plotLeft, Math.min(plotRight, e.clientX - rect.left + plotLeft));
+ const date = pxToBucketStart(px).toUTC().toJSDate();
+ if (pendingClickRef.current) clearTimeout(pendingClickRef.current);
+ pendingClickRef.current = setTimeout(() => {
+ pendingClickRef.current = null;
+ onPlotClick(date);
+ }, 250);
+ };
+
+ const pointAt = useCallback(
+ (x: Date) => (primaryData.length ? primaryData[bisectCurrent(primaryData, x)] : undefined),
+ [bisectCurrent, primaryData]
+ );
+
const handleDoubleClick = (e: React.MouseEvent<SVGRectElement>) => {
+ if (pendingClickRef.current) {
+ clearTimeout(pendingClickRef.current);
+ pendingClickRef.current = null;
+ }
const dragZoom = dragZoomRestoreRef.current;
if (!dragZoom) return;
if (!isSameTime(time, dragZoom.after) || bucket !== dragZoom.afterBucket) {
@@ -801,11 +862,15 @@ export function TimeSeriesChart<
fill="transparent"
style={{ cursor: dragEnabled ? "crosshair" : "default" }}
onMouseDown={handleMouseDown}
+ onClick={handleClick}
onDoubleClick={handleDoubleClick}
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
/>
)}
+
+ {hasDomain &&
+ renderOverlay?.({ xScale, yScale, plotLeft, plotRight, plotTop, plotBottom, pointAt, isDark })}
</svg>
)}
diff --git a/docs/content/docs/api/annotations/create.mdx b/docs/content/docs/api/annotations/create.mdx
new file mode 100644
index 000000000..afe74fde9
--- /dev/null
+++ b/docs/content/docs/api/annotations/create.mdx
@@ -0,0 +1,87 @@
+---
+title: Create Annotation
+description: Pins a note to a date or date range on the site's traffic chart.
+full: true
+method: POST
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+POST /api/sites/:site/annotations
+```
+
+Creates an annotation. Any member with access to the site can create site annotations; organization-wide annotations (`scope: "organization"`) require an admin or owner role.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: 'Site ID or site identifier',
+ type: 'string | number',
+ required: true,
+ },
+ }}
+/>
+
+### Request Body
+
+<TypeTable
+ type={{
+ title: { description: 'Short title (max 120 characters)', type: 'string', required: true },
+ date: { description: 'ISO 8601 timestamp with Z or offset, or YYYY-MM-DD (read as midnight UTC)', type: 'string', required: true },
+ endDate: { description: 'End of a range; must be after date', type: 'string', required: false },
+ description: { description: 'Longer note (max 2000 characters)', type: 'string', required: false },
+ color: { description: 'Marker color', type: 'string', typeDescription: '"amber" | "rose" | "sky" | "violet" | "lime"', required: false },
+ icon: { description: 'Emoji shown in the marker (max 16 characters)', type: 'string', required: false },
+ isPublic: { description: 'Show on public dashboards and private links', type: 'boolean', default: 'false', required: false },
+ scope: { description: 'Attach to this site or to every site in the organization', type: 'string', typeDescription: '"site" | "organization"', default: '"site"', required: false },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ success: { description: 'Always true', type: 'boolean' },
+ annotationId: { description: 'ID of the new annotation', type: 'number' },
+ }}
+/>
+
+</div>
+<div>
+
+### Example
+
+<Tabs items={['cURL', 'Response']}>
+<Tab value="cURL">
+
+```bash
+curl -X POST "https://app.rybbit.io/api/sites/123/annotations" \
+ -H "Authorization: Bearer YOUR_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "title": "Deployed v2.3.0",
+ "date": "2026-08-24T14:10:00Z",
+ "color": "sky",
+ "scope": "organization"
+ }'
+```
+
+</Tab>
+<Tab value="Response">
+
+```json
+{ "success": true, "annotationId": 43 }
+```
+
+</Tab>
+</Tabs>
+
+</div>
+</div>
diff --git a/docs/content/docs/api/annotations/delete.mdx b/docs/content/docs/api/annotations/delete.mdx
new file mode 100644
index 000000000..27300a452
--- /dev/null
+++ b/docs/content/docs/api/annotations/delete.mdx
@@ -0,0 +1,53 @@
+---
+title: Delete Annotation
+description: Permanently deletes an annotation.
+full: true
+method: DELETE
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+DELETE /api/sites/:site/annotations/:annotationId
+```
+
+Deletes an annotation. Admins and owners can delete any annotation on their sites; members can delete only the annotations they created.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: { description: 'Site ID or site identifier', type: 'string | number', required: true },
+ annotationId: { description: 'Annotation ID', type: 'number', required: true },
+ }}
+/>
+
+</div>
+<div>
+
+### Example
+
+<Tabs items={['cURL', 'Response']}>
+<Tab value="cURL">
+
+```bash
+curl -X DELETE "https://app.rybbit.io/api/sites/123/annotations/43" \
+ -H "Authorization: Bearer YOUR_API_KEY"
+```
+
+</Tab>
+<Tab value="Response">
+
+```json
+{ "success": true }
+```
+
+</Tab>
+</Tabs>
+
+</div>
+</div>
diff --git a/docs/content/docs/api/annotations/list.mdx b/docs/content/docs/api/annotations/list.mdx
new file mode 100644
index 000000000..0cafd38f1
--- /dev/null
+++ b/docs/content/docs/api/annotations/list.mdx
@@ -0,0 +1,121 @@
+---
+title: Get Annotations
+description: Returns the timeline annotations that apply to a site, including organization-wide ones.
+full: true
+method: GET
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+GET /api/sites/:site/annotations
+```
+
+Returns the annotations pinned to the site's traffic chart, ordered by date. Organization-wide annotations (those with a `null` `siteId`) are included for every site in the organization.
+
+Anonymous viewers of a public dashboard or a private link only receive annotations with `isPublic: true`.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: 'Site ID or site identifier',
+ type: 'string | number',
+ required: true,
+ },
+ }}
+/>
+
+### Query Parameters
+
+<TypeTable
+ type={{
+ start_date: {
+ description: 'Only annotations that end on or after the start of this day (YYYY-MM-DD). May be sent without end_date.',
+ type: 'string',
+ required: false,
+ },
+ end_date: {
+ description: 'Only annotations that start before the end of this day (YYYY-MM-DD). May be sent without start_date; must not precede start_date.',
+ type: 'string',
+ required: false,
+ },
+ time_zone: {
+ description: 'IANA timezone the day bounds are read in',
+ type: 'string',
+ default: 'UTC',
+ required: false,
+ },
+ }}
+/>
+
+### Response
+
+An array of annotation objects.
+
+<TypeTable
+ type={{
+ annotationId: { description: 'Unique annotation ID', type: 'number' },
+ siteId: { description: 'Site the annotation belongs to, or null for organization-wide annotations', type: 'number | null' },
+ organizationId: { description: 'Owning organization', type: 'string' },
+ userId: { description: 'Creator user ID', type: 'string | null' },
+ userName: { description: 'Creator display name', type: 'string | null' },
+ title: { description: 'Short title shown on the chart', type: 'string' },
+ description: { description: 'Longer note', type: 'string | null' },
+ date: { description: 'ISO 8601 timestamp the annotation is pinned to', type: 'string' },
+ endDate: { description: 'ISO 8601 end timestamp for range annotations', type: 'string | null' },
+ color: { description: 'Marker color', type: 'string | null', typeDescription: '"amber" | "rose" | "sky" | "violet" | "lime" | null' },
+ icon: { description: 'Emoji shown in the marker', type: 'string | null' },
+ isPublic: { description: 'Whether public dashboards and private links show it', type: 'boolean' },
+ createdAt: { description: 'Creation timestamp', type: 'string' },
+ updatedAt: { description: 'Last update timestamp', type: 'string' },
+ }}
+/>
+
+</div>
+<div>
+
+### Example
+
+<Tabs items={['cURL', 'Response']}>
+<Tab value="cURL">
+
+```bash
+curl "https://app.rybbit.io/api/sites/123/annotations?start_date=2026-08-01&end_date=2026-08-31" \
+ -H "Authorization: Bearer YOUR_API_KEY"
+```
+
+</Tab>
+<Tab value="Response">
+
+```json
+[
+ {
+ "annotationId": 42,
+ "siteId": 123,
+ "organizationId": "org_abc",
+ "userId": "user_xyz",
+ "userName": "Bill",
+ "title": "Product Hunt launch",
+ "description": "Finished #2 Product of the Day.",
+ "date": "2026-08-18T07:00:00.000Z",
+ "endDate": null,
+ "color": "amber",
+ "icon": "🚀",
+ "isPublic": true,
+ "createdAt": "2026-08-18 07:05:12.1",
+ "updatedAt": "2026-08-18 07:05:12.1"
+ }
+]
+```
+
+</Tab>
+</Tabs>
+
+</div>
+</div>
diff --git a/docs/content/docs/api/annotations/meta.json b/docs/content/docs/api/annotations/meta.json
new file mode 100644
index 000000000..1dadbb06d
--- /dev/null
+++ b/docs/content/docs/api/annotations/meta.json
@@ -0,0 +1,4 @@
+{
+ "title": "Annotations",
+ "pages": ["list", "create", "update", "delete"]
+}
diff --git a/docs/content/docs/api/annotations/update.mdx b/docs/content/docs/api/annotations/update.mdx
new file mode 100644
index 000000000..e2747dd94
--- /dev/null
+++ b/docs/content/docs/api/annotations/update.mdx
@@ -0,0 +1,70 @@
+---
+title: Update Annotation
+description: Updates an annotation's fields.
+full: true
+method: PUT
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+PUT /api/sites/:site/annotations/:annotationId
+```
+
+Partial update: only the fields you send change. Admins and owners can edit any annotation on their sites; members can edit only the annotations they created. Changing `scope` requires an admin or owner role.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: { description: 'Site ID or site identifier', type: 'string | number', required: true },
+ annotationId: { description: 'Annotation ID', type: 'number', required: true },
+ }}
+/>
+
+### Request Body
+
+<TypeTable
+ type={{
+ title: { description: 'Short title (max 120 characters)', type: 'string', required: false },
+ date: { description: 'ISO 8601 timestamp with Z or offset, or YYYY-MM-DD', type: 'string', required: false },
+ endDate: { description: 'End of a range, or null to turn a range back into a point', type: 'string | null', required: false },
+ description: { description: 'Longer note, or null to clear', type: 'string | null', required: false },
+ color: { description: 'Marker color, or null for the neutral default', type: 'string | null', required: false },
+ icon: { description: 'Emoji, or null to clear', type: 'string | null', required: false },
+ isPublic: { description: 'Show on public dashboards and private links', type: 'boolean', required: false },
+ scope: { description: 'Move between site and organization-wide', type: 'string', typeDescription: '"site" | "organization"', required: false },
+ }}
+/>
+
+</div>
+<div>
+
+### Example
+
+<Tabs items={['cURL', 'Response']}>
+<Tab value="cURL">
+
+```bash
+curl -X PUT "https://app.rybbit.io/api/sites/123/annotations/43" \
+ -H "Authorization: Bearer YOUR_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "title": "Deployed v2.3.0 (rolled back)", "color": "rose" }'
+```
+
+</Tab>
+<Tab value="Response">
+
+```json
+{ "success": true }
+```
+
+</Tab>
+</Tabs>
+
+</div>
+</div>
diff --git a/docs/content/docs/api/meta.json b/docs/content/docs/api/meta.json
index 13c0f9e59..fa5b9534d 100644
--- a/docs/content/docs/api/meta.json
+++ b/docs/content/docs/api/meta.json
@@ -19,6 +19,7 @@
"user-traits",
"events",
"goals",
+ "annotations",
"funnels",
"segments",
"performance",
diff --git a/server/drizzle/0017_burly_nick_fury.sql b/server/drizzle/0017_burly_nick_fury.sql
new file mode 100644
index 000000000..6c2ca4376
--- /dev/null
+++ b/server/drizzle/0017_burly_nick_fury.sql
@@ -0,0 +1,33 @@
+CREATE TABLE IF NOT EXISTS "annotations" (
+ "annotation_id" serial PRIMARY KEY NOT NULL,
+ "site_id" integer,
+ "organization_id" text NOT NULL,
+ "user_id" text,
+ "title" text NOT NULL,
+ "description" text,
+ "date" timestamp with time zone NOT NULL,
+ "end_date" timestamp with time zone,
+ "color" text,
+ "icon" text,
+ "is_public" boolean DEFAULT false NOT NULL,
+ "created_at" timestamp DEFAULT now(),
+ "updated_at" timestamp DEFAULT now()
+);
+--> statement-breakpoint
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'annotations_site_id_sites_site_id_fk') THEN
+ ALTER TABLE "annotations" ADD CONSTRAINT "annotations_site_id_sites_site_id_fk" FOREIGN KEY ("site_id") REFERENCES "public"."sites"("site_id") ON DELETE cascade ON UPDATE no action;
+ END IF;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'annotations_organization_id_organization_id_fk') THEN
+ ALTER TABLE "annotations" ADD CONSTRAINT "annotations_organization_id_organization_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organization"("id") ON DELETE cascade ON UPDATE no action;
+ END IF;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'annotations_user_id_user_id_fk') THEN
+ ALTER TABLE "annotations" ADD CONSTRAINT "annotations_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;
+ END IF;
+END $$;--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "annotations_site_date_idx" ON "annotations" USING btree ("site_id","date");--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "annotations_org_date_idx" ON "annotations" USING btree ("organization_id","date");
diff --git a/server/drizzle/meta/0017_snapshot.json b/server/drizzle/meta/0017_snapshot.json
new file mode 100644
index 000000000..bf5e6751c
--- /dev/null
+++ b/server/drizzle/meta/0017_snapshot.json
@@ -0,0 +1,3341 @@
+{
+ "id": "951578fe-c04f-4fa0-8ce7-b1246fd746fc",
+ "prevId": "f2ba75dc-5cab-41b7-9221-bffb0f9ea629",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.account": {
+ "name": "account",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "accountId": {
+ "name": "accountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "providerId": {
+ "name": "providerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessToken": {
+ "name": "accessToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshToken": {
+ "name": "refreshToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "idToken": {
+ "name": "idToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessTokenExpiresAt": {
+ "name": "accessTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshTokenExpiresAt": {
+ "name": "refreshTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_userId_user_id_fk": {
+ "name": "account_userId_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.active_sessions": {
+ "name": "active_sessions",
+ "schema": "",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "last_activity": {
+ "name": "last_activity",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.annotations": {
+ "name": "annotations",
+ "schema": "",
+ "columns": {
+ "annotation_id": {
+ "name": "annotation_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "date": {
+ "name": "date",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "end_date": {
+ "name": "end_date",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_public": {
+ "name": "is_public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "annotations_site_date_idx": {
+ "name": "annotations_site_date_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "date",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "annotations_org_date_idx": {
+ "name": "annotations_org_date_idx",
+ "columns": [
+ {
+ "expression": "organization_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "date",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "annotations_site_id_sites_site_id_fk": {
+ "name": "annotations_site_id_sites_site_id_fk",
+ "tableFrom": "annotations",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "annotations_organization_id_organization_id_fk": {
+ "name": "annotations_organization_id_organization_id_fk",
+ "tableFrom": "annotations",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "annotations_user_id_user_id_fk": {
+ "name": "annotations_user_id_user_id_fk",
+ "tableFrom": "annotations",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.apikey": {
+ "name": "apikey",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start": {
+ "name": "start",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "prefix": {
+ "name": "prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refillInterval": {
+ "name": "refillInterval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refillAmount": {
+ "name": "refillAmount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastRefillAt": {
+ "name": "lastRefillAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "rateLimitEnabled": {
+ "name": "rateLimitEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "rateLimitTimeWindow": {
+ "name": "rateLimitTimeWindow",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rateLimitMax": {
+ "name": "rateLimitMax",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestCount": {
+ "name": "requestCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "remaining": {
+ "name": "remaining",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastRequest": {
+ "name": "lastRequest",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "configId": {
+ "name": "configId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.cancellation_feedback": {
+ "name": "cancellation_feedback",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reason_details": {
+ "name": "reason_details",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "retention_offer_shown": {
+ "name": "retention_offer_shown",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "retention_offer_accepted": {
+ "name": "retention_offer_accepted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "outcome": {
+ "name": "outcome",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "plan_name_at_cancellation": {
+ "name": "plan_name_at_cancellation",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "monthly_event_count_at_cancellation": {
+ "name": "monthly_event_count_at_cancellation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.dashboards": {
+ "name": "dashboards",
+ "schema": "",
+ "columns": {
+ "dashboard_id": {
+ "name": "dashboard_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{\"cards\":[]}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "dashboards_site_id_sites_site_id_fk": {
+ "name": "dashboards_site_id_sites_site_id_fk",
+ "tableFrom": "dashboards",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "dashboards_user_id_user_id_fk": {
+ "name": "dashboards_user_id_user_id_fk",
+ "tableFrom": "dashboards",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.experiments": {
+ "name": "experiments",
+ "schema": "",
+ "columns": {
+ "experiment_id": {
+ "name": "experiment_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "feature_flag_id": {
+ "name": "feature_flag_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "primary_goal_id": {
+ "name": "primary_goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "hypothesis": {
+ "name": "hypothesis",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'draft'"
+ },
+ "winning_variant": {
+ "name": "winning_variant",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "experiments_site_idx": {
+ "name": "experiments_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "experiments_feature_flag_idx": {
+ "name": "experiments_feature_flag_idx",
+ "columns": [
+ {
+ "expression": "feature_flag_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "experiments_primary_goal_idx": {
+ "name": "experiments_primary_goal_idx",
+ "columns": [
+ {
+ "expression": "primary_goal_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "experiments_site_id_sites_site_id_fk": {
+ "name": "experiments_site_id_sites_site_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "experiments_feature_flag_id_feature_flags_flag_id_fk": {
+ "name": "experiments_feature_flag_id_feature_flags_flag_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "feature_flags",
+ "columnsFrom": [
+ "feature_flag_id"
+ ],
+ "columnsTo": [
+ "flag_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "experiments_primary_goal_id_goals_goal_id_fk": {
+ "name": "experiments_primary_goal_id_goals_goal_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "primary_goal_id"
+ ],
+ "columnsTo": [
+ "goal_id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "experiments_site_flag_unique": {
+ "name": "experiments_site_flag_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "feature_flag_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "experiments_status_check": {
+ "name": "experiments_status_check",
+ "value": "status IN ('draft', 'running', 'paused', 'completed')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.feature_flags": {
+ "name": "feature_flags",
+ "schema": "",
+ "columns": {
+ "flag_id": {
+ "name": "flag_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "runtime": {
+ "name": "runtime",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'client'"
+ },
+ "flag_type": {
+ "name": "flag_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'boolean'"
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "variants": {
+ "name": "variants",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "rollout_percentage": {
+ "name": "rollout_percentage",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 100
+ },
+ "rules": {
+ "name": "rules",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "condition_sets": {
+ "name": "condition_sets",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "salt": {
+ "name": "salt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "md5(random()::text || clock_timestamp()::text)"
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "feature_flags_site_idx": {
+ "name": "feature_flags_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "feature_flags_site_id_sites_site_id_fk": {
+ "name": "feature_flags_site_id_sites_site_id_fk",
+ "tableFrom": "feature_flags",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "feature_flags_site_key_unique": {
+ "name": "feature_flags_site_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "feature_flags_rollout_check": {
+ "name": "feature_flags_rollout_check",
+ "value": "rollout_percentage >= 0 AND rollout_percentage <= 100"
+ },
+ "feature_flags_runtime_check": {
+ "name": "feature_flags_runtime_check",
+ "value": "runtime IN ('client', 'server', 'both')"
+ },
+ "feature_flags_type_check": {
+ "name": "feature_flags_type_check",
+ "value": "flag_type IN ('boolean', 'multivariate', 'remote_config')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.funnels": {
+ "name": "funnels",
+ "schema": "",
+ "columns": {
+ "report_id": {
+ "name": "report_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data": {
+ "name": "data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "funnels_site_id_sites_site_id_fk": {
+ "name": "funnels_site_id_sites_site_id_fk",
+ "tableFrom": "funnels",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "funnels_user_id_user_id_fk": {
+ "name": "funnels_user_id_user_id_fk",
+ "tableFrom": "funnels",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.goals": {
+ "name": "goals",
+ "schema": "",
+ "columns": {
+ "goal_id": {
+ "name": "goal_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "goal_type": {
+ "name": "goal_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "goals_site_id_sites_site_id_fk": {
+ "name": "goals_site_id_sites_site_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.gsc_connections": {
+ "name": "gsc_connections",
+ "schema": "",
+ "columns": {
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "gsc_property_url": {
+ "name": "gsc_property_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "gsc_connections_site_id_sites_site_id_fk": {
+ "name": "gsc_connections_site_id_sites_site_id_fk",
+ "tableFrom": "gsc_connections",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.import_status": {
+ "name": "import_status",
+ "schema": "",
+ "columns": {
+ "import_id": {
+ "name": "import_id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "platform": {
+ "name": "platform",
+ "type": "import_platform_enum",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "imported_events": {
+ "name": "imported_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "skipped_events": {
+ "name": "skipped_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "invalid_events": {
+ "name": "invalid_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "import_status_site_id_sites_site_id_fk": {
+ "name": "import_status_site_id_sites_site_id_fk",
+ "tableFrom": "import_status",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "import_status_organization_id_organization_id_fk": {
+ "name": "import_status_organization_id_organization_id_fk",
+ "tableFrom": "import_status",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.invitation": {
+ "name": "invitation",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "inviterId": {
+ "name": "inviterId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "has_restricted_site_access": {
+ "name": "has_restricted_site_access",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "site_ids": {
+ "name": "site_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "teamId": {
+ "name": "teamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "invitation_inviterId_user_id_fk": {
+ "name": "invitation_inviterId_user_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "user",
+ "columnsFrom": [
+ "inviterId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "invitation_organizationId_organization_id_fk": {
+ "name": "invitation_organizationId_organization_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "invitation_teamId_team_id_fk": {
+ "name": "invitation_teamId_team_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "team",
+ "columnsFrom": [
+ "teamId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.lifecycle_email_log": {
+ "name": "lifecycle_email_log",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email_key": {
+ "name": "email_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "lifecycle_email_log_user_id_user_id_fk": {
+ "name": "lifecycle_email_log_user_id_user_id_fk",
+ "tableFrom": "lifecycle_email_log",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "lifecycle_email_log_user_email_key_unique": {
+ "name": "lifecycle_email_log_user_email_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "user_id",
+ "email_key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.member": {
+ "name": "member",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "has_restricted_site_access": {
+ "name": "has_restricted_site_access",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "member_organizationId_organization_id_fk": {
+ "name": "member_organizationId_organization_id_fk",
+ "tableFrom": "member",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "member_userId_user_id_fk": {
+ "name": "member_userId_user_id_fk",
+ "tableFrom": "member",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.member_site_access": {
+ "name": "member_site_access",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "member_id": {
+ "name": "member_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "member_site_access_member_idx": {
+ "name": "member_site_access_member_idx",
+ "columns": [
+ {
+ "expression": "member_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "member_site_access_site_idx": {
+ "name": "member_site_access_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "member_site_access_member_id_member_id_fk": {
+ "name": "member_site_access_member_id_member_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "member",
+ "columnsFrom": [
+ "member_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "member_site_access_site_id_sites_site_id_fk": {
+ "name": "member_site_access_site_id_sites_site_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "member_site_access_created_by_user_id_fk": {
+ "name": "member_site_access_created_by_user_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "member_site_access_unique": {
+ "name": "member_site_access_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "member_id",
+ "site_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthAccessToken": {
+ "name": "oauthAccessToken",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "accessToken": {
+ "name": "accessToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refreshToken": {
+ "name": "refreshToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessTokenExpiresAt": {
+ "name": "accessTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refreshTokenExpiresAt": {
+ "name": "refreshTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthAccessToken_clientId_oauthApplication_clientId_fk": {
+ "name": "oauthAccessToken_clientId_oauthApplication_clientId_fk",
+ "tableFrom": "oauthAccessToken",
+ "tableTo": "oauthApplication",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthAccessToken_userId_user_id_fk": {
+ "name": "oauthAccessToken_userId_user_id_fk",
+ "tableFrom": "oauthAccessToken",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthAccessToken_accessToken_unique": {
+ "name": "oauthAccessToken_accessToken_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "accessToken"
+ ]
+ },
+ "oauthAccessToken_refreshToken_unique": {
+ "name": "oauthAccessToken_refreshToken_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "refreshToken"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthApplication": {
+ "name": "oauthApplication",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientSecret": {
+ "name": "clientSecret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "redirectUrls": {
+ "name": "redirectUrls",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "disabled": {
+ "name": "disabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthApplication_userId_user_id_fk": {
+ "name": "oauthApplication_userId_user_id_fk",
+ "tableFrom": "oauthApplication",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthApplication_clientId_unique": {
+ "name": "oauthApplication_clientId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "clientId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthConsent": {
+ "name": "oauthConsent",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consentGiven": {
+ "name": "consentGiven",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthConsent_clientId_oauthApplication_clientId_fk": {
+ "name": "oauthConsent_clientId_oauthApplication_clientId_fk",
+ "tableFrom": "oauthConsent",
+ "tableTo": "oauthApplication",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthConsent_userId_user_id_fk": {
+ "name": "oauthConsent_userId_user_id_fk",
+ "tableFrom": "oauthConsent",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.organization": {
+ "name": "organization",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "logo": {
+ "name": "logo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "monthlyEventCount": {
+ "name": "monthlyEventCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "overMonthlyLimit": {
+ "name": "overMonthlyLimit",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "approachingLimitNotifiedPeriodStart": {
+ "name": "approachingLimitNotifiedPeriodStart",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "planOverride": {
+ "name": "planOverride",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "custom_plan": {
+ "name": "custom_plan",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "organization_slug_unique": {
+ "name": "organization_slug_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "slug"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.segments": {
+ "name": "segments",
+ "schema": "",
+ "columns": {
+ "segment_id": {
+ "name": "segment_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "filters": {
+ "name": "filters",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "is_public": {
+ "name": "is_public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'segment'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "segments_organization_idx": {
+ "name": "segments_organization_idx",
+ "columns": [
+ {
+ "expression": "organization_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "segments_site_idx": {
+ "name": "segments_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "segments_organization_id_organization_id_fk": {
+ "name": "segments_organization_id_organization_id_fk",
+ "tableFrom": "segments",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "segments_site_id_sites_site_id_fk": {
+ "name": "segments_site_id_sites_site_id_fk",
+ "tableFrom": "segments",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "segments_user_id_user_id_fk": {
+ "name": "segments_user_id_user_id_fk",
+ "tableFrom": "segments",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.session": {
+ "name": "session",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ipAddress": {
+ "name": "ipAddress",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userAgent": {
+ "name": "userAgent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "impersonatedBy": {
+ "name": "impersonatedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "activeOrganizationId": {
+ "name": "activeOrganizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "activeTeamId": {
+ "name": "activeTeamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_userId_user_id_fk": {
+ "name": "session_userId_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sites": {
+ "name": "sites",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "domain": {
+ "name": "domain",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "public": {
+ "name": "public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "embed_enabled": {
+ "name": "embed_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "saltUserIds": {
+ "name": "saltUserIds",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "blockBots": {
+ "name": "blockBots",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "first_party_proxy": {
+ "name": "first_party_proxy",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "excluded_ips": {
+ "name": "excluded_ips",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_countries": {
+ "name": "excluded_countries",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_paths": {
+ "name": "excluded_paths",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_hostnames": {
+ "name": "excluded_hostnames",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_user_agents": {
+ "name": "excluded_user_agents",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_asns": {
+ "name": "excluded_asns",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_query_params": {
+ "name": "excluded_query_params",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "sessionReplay": {
+ "name": "sessionReplay",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "webVitals": {
+ "name": "webVitals",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackErrors": {
+ "name": "trackErrors",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackOutbound": {
+ "name": "trackOutbound",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackUrlParams": {
+ "name": "trackUrlParams",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackInitialPageView": {
+ "name": "trackInitialPageView",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackSpaNavigation": {
+ "name": "trackSpaNavigation",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackIp": {
+ "name": "trackIp",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackButtonClicks": {
+ "name": "trackButtonClicks",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackCopy": {
+ "name": "trackCopy",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackFormInteractions": {
+ "name": "trackFormInteractions",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "api_key": {
+ "name": "api_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "private_link_key": {
+ "name": "private_link_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "detected_platform": {
+ "name": "detected_platform",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "sites_created_by_user_id_fk": {
+ "name": "sites_created_by_user_id_fk",
+ "tableFrom": "sites",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sites_organization_id_organization_id_fk": {
+ "name": "sites_organization_id_organization_id_fk",
+ "tableFrom": "sites",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "sites_type_check": {
+ "name": "sites_type_check",
+ "value": "\"sites\".\"type\" IS NULL OR \"sites\".\"type\" IN ('web', 'mobile')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.team": {
+ "name": "team",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "team_organizationId_organization_id_fk": {
+ "name": "team_organizationId_organization_id_fk",
+ "tableFrom": "team",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.teamMember": {
+ "name": "teamMember",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "teamId": {
+ "name": "teamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "teamMember_teamId_team_id_fk": {
+ "name": "teamMember_teamId_team_id_fk",
+ "tableFrom": "teamMember",
+ "tableTo": "team",
+ "columnsFrom": [
+ "teamId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "teamMember_userId_user_id_fk": {
+ "name": "teamMember_userId_user_id_fk",
+ "tableFrom": "teamMember",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.team_site_access": {
+ "name": "team_site_access",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "team_site_access_team_idx": {
+ "name": "team_site_access_team_idx",
+ "columns": [
+ {
+ "expression": "team_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "team_site_access_site_idx": {
+ "name": "team_site_access_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "team_site_access_team_id_team_id_fk": {
+ "name": "team_site_access_team_id_team_id_fk",
+ "tableFrom": "team_site_access",
+ "tableTo": "team",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "team_site_access_site_id_sites_site_id_fk": {
+ "name": "team_site_access_site_id_sites_site_id_fk",
+ "tableFrom": "team_site_access",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "team_site_access_unique": {
+ "name": "team_site_access_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "team_id",
+ "site_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.telemetry": {
+ "name": "telemetry",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "instance_id": {
+ "name": "instance_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "version": {
+ "name": "version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "table_counts": {
+ "name": "table_counts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clickhouse_size_gb": {
+ "name": "clickhouse_size_gb",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user": {
+ "name": "user",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "username": {
+ "name": "username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'user'"
+ },
+ "displayUsername": {
+ "name": "displayUsername",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banned": {
+ "name": "banned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banReason": {
+ "name": "banReason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banExpires": {
+ "name": "banExpires",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "overMonthlyLimit": {
+ "name": "overMonthlyLimit",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "monthlyEventCount": {
+ "name": "monthlyEventCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "sendAutoEmailReports": {
+ "name": "sendAutoEmailReports",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "scheduled_tip_email_ids": {
+ "name": "scheduled_tip_email_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_username_unique": {
+ "name": "user_username_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "username"
+ ]
+ },
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "email"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_aliases": {
+ "name": "user_aliases",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "anonymous_id": {
+ "name": "anonymous_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_aliases_user_idx": {
+ "name": "user_aliases_user_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_aliases_anon_idx": {
+ "name": "user_aliases_anon_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "anonymous_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_aliases_site_id_sites_site_id_fk": {
+ "name": "user_aliases_site_id_sites_site_id_fk",
+ "tableFrom": "user_aliases",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_aliases_site_anon_unique": {
+ "name": "user_aliases_site_anon_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "anonymous_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_profiles": {
+ "name": "user_profiles",
+ "schema": "",
+ "columns": {
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "traits": {
+ "name": "traits",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_profiles_site_idx": {
+ "name": "user_profiles_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_profiles_site_id_sites_site_id_fk": {
+ "name": "user_profiles_site_id_sites_site_id_fk",
+ "tableFrom": "user_profiles",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "user_profiles_site_id_user_id_pk": {
+ "name": "user_profiles_site_id_user_id_pk",
+ "columns": [
+ "site_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verification": {
+ "name": "verification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {
+ "public.import_platform_enum": {
+ "name": "import_platform_enum",
+ "schema": "public",
+ "values": [
+ "umami",
+ "simple_analytics",
+ "plausible"
+ ]
+ }
+ },
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.json
index 105dde9f9..bafd99575 100644
--- a/server/drizzle/meta/_journal.json
+++ b/server/drizzle/meta/_journal.json
@@ -120,6 +120,13 @@
"when": 1788386038776,
"tag": "0016_shocking_vance_astro",
"breakpoints": true
+ },
+ {
+ "idx": 17,
+ "version": "7",
+ "when": 1788393490335,
+ "tag": "0017_burly_nick_fury",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/server/src/api/analytics/annotations/annotationAccess.ts b/server/src/api/analytics/annotations/annotationAccess.ts
new file mode 100644
index 000000000..eae87d18f
--- /dev/null
+++ b/server/src/api/analytics/annotations/annotationAccess.ts
@@ -0,0 +1,52 @@
+import { and, eq, isNull, or, SQL } from "drizzle-orm";
+import { FastifyRequest } from "fastify";
+import { db } from "../../../db/postgres/postgres.js";
+import { annotations, sites } from "../../../db/postgres/schema.js";
+import { getUserHasAdminAccessToSite } from "../../../lib/auth-utils.js";
+
+export type AnnotationRow = typeof annotations.$inferSelect;
+
+export function parseSiteId(raw: string): number | null {
+ const siteId = parseInt(raw, 10);
+ return isNaN(siteId) || siteId <= 0 ? null : siteId;
+}
+
+export function parseAnnotationId(raw: string): number | null {
+ const id = parseInt(raw, 10);
+ return isNaN(id) || id <= 0 ? null : id;
+}
+
+export async function getSiteOrganizationId(siteId: number): Promise<string | null> {
+ const site = await db.query.sites.findFirst({
+ where: eq(sites.siteId, siteId),
+ columns: { organizationId: true },
+ });
+ return site?.organizationId ?? null;
+}
+
+/** Annotations that apply to a site: its own plus its organization's site-less ones. */
+export function annotationsForSite(siteId: number, organizationId: string): SQL {
+ return or(
+ eq(annotations.siteId, siteId),
+ and(isNull(annotations.siteId), eq(annotations.organizationId, organizationId))
+ )!;
+}
+
+export function annotationBelongsToSite(row: AnnotationRow, siteId: number, organizationId: string): boolean {
+ return row.siteId === siteId || (row.siteId === null && row.organizationId === organizationId);
+}
+
+/**
+ * Admins and owners manage every annotation on their sites. Members may only
+ * change what they created, and never organization-wide annotations.
+ */
+export async function canManageAnnotation(
+ request: FastifyRequest,
+ siteId: number,
+ row: AnnotationRow
+): Promise<boolean> {
+ if (await getUserHasAdminAccessToSite(request, siteId)) return true;
+ if (row.siteId === null) return false;
+ const userId = request.user?.id;
+ return Boolean(userId) && row.userId === userId;
+}
diff --git a/server/src/api/analytics/annotations/annotationSchema.test.ts b/server/src/api/analytics/annotations/annotationSchema.test.ts
new file mode 100644
index 000000000..a35b57320
--- /dev/null
+++ b/server/src/api/analytics/annotations/annotationSchema.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from "vitest";
+import { createAnnotationSchema, listAnnotationsQuerySchema, updateAnnotationSchema } from "./annotationSchema.js";
+
+describe("createAnnotationSchema", () => {
+ it("normalizes a bare date to midnight UTC and applies defaults", () => {
+ const parsed = createAnnotationSchema.parse({ title: " Launch ", date: "2026-08-18" });
+ expect(parsed.date).toBe("2026-08-18T00:00:00.000Z");
+ expect(parsed.title).toBe("Launch");
+ expect(parsed.scope).toBe("site");
+ expect(parsed.isPublic).toBe(false);
+ });
+
+ it("keeps the instant of a full timestamp with an offset", () => {
+ const parsed = createAnnotationSchema.parse({ title: "Deploy", date: "2026-08-24T16:10:00+02:00" });
+ expect(parsed.date).toBe("2026-08-24T14:10:00.000Z");
+ });
+
+ it("rejects a range that ends before it starts", () => {
+ const result = createAnnotationSchema.safeParse({ title: "Test", date: "2026-08-14", endDate: "2026-08-11" });
+ expect(result.success).toBe(false);
+ });
+
+ it("rejects unknown colors, empty titles, and garbage dates", () => {
+ expect(createAnnotationSchema.safeParse({ title: "x", date: "2026-08-18", color: "emerald" }).success).toBe(false);
+ expect(createAnnotationSchema.safeParse({ title: " ", date: "2026-08-18" }).success).toBe(false);
+ expect(createAnnotationSchema.safeParse({ title: "x", date: "yesterday" }).success).toBe(false);
+ });
+});
+
+describe("updateAnnotationSchema", () => {
+ it("rejects an empty update and allows clearing nullable fields", () => {
+ expect(updateAnnotationSchema.safeParse({}).success).toBe(false);
+ const parsed = updateAnnotationSchema.parse({ endDate: null, description: null, color: null });
+ expect(parsed).toEqual({ endDate: null, description: null, color: null });
+ });
+});
+
+describe("date strictness", () => {
+ it("rejects impossible calendar dates and offset-less timestamps", () => {
+ expect(createAnnotationSchema.safeParse({ title: "x", date: "2026-02-30" }).success).toBe(false);
+ expect(createAnnotationSchema.safeParse({ title: "x", date: "2026-08-18T14:10:00" }).success).toBe(false);
+ expect(createAnnotationSchema.safeParse({ title: "x", date: "08/18/2026" }).success).toBe(false);
+ expect(createAnnotationSchema.safeParse({ title: "x", date: "2026-08-18T14:10:00Z" }).success).toBe(true);
+ expect(createAnnotationSchema.safeParse({ title: "x", date: "2026-08-18T14:10:00.5+0200" }).success).toBe(true);
+ });
+});
+
+describe("listAnnotationsQuerySchema", () => {
+ it("allows either bound alone and rejects reversed or invalid bounds", () => {
+ expect(listAnnotationsQuerySchema.safeParse({ start_date: "2026-08-01" }).success).toBe(true);
+ expect(listAnnotationsQuerySchema.safeParse({ end_date: "2026-08-31" }).success).toBe(true);
+ expect(listAnnotationsQuerySchema.safeParse({ start_date: "2026-08-31", end_date: "2026-08-01" }).success).toBe(false);
+ expect(listAnnotationsQuerySchema.safeParse({ start_date: "2026-13-01" }).success).toBe(false);
+ });
+});
diff --git a/server/src/api/analytics/annotations/annotationSchema.ts b/server/src/api/analytics/annotations/annotationSchema.ts
new file mode 100644
index 000000000..04ea79382
--- /dev/null
+++ b/server/src/api/analytics/annotations/annotationSchema.ts
@@ -0,0 +1,76 @@
+import { z } from "zod";
+
+// Mirrors ANNOTATION_COLORS in @rybbit/shared. That package is types-only on
+// the server (its imports are erased at compile time), so the runtime list
+// lives here — keep the two in sync.
+export const ANNOTATION_COLORS = ["amber", "rose", "sky", "violet", "lime"] as const;
+
+const DATE_ONLY = /^(\d{4})-(\d{2})-(\d{2})$/;
+// Full ISO 8601 timestamps must carry Z or an explicit offset; an offset-less
+// value would be read in the server's timezone.
+const ISO_WITH_OFFSET = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?(?:Z|[+-]\d{2}:?\d{2})$/;
+
+/** True for a real calendar date (rejects 2026-02-30). */
+export function isCalendarDate(value: string): boolean {
+ const match = DATE_ONLY.exec(value);
+ if (!match) return false;
+ const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
+ const date = new Date(Date.UTC(year, month - 1, day));
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
+}
+
+// Accepts a full ISO 8601 timestamp with offset, or a bare YYYY-MM-DD read as
+// midnight UTC. Normalized to an ISO string for the timestamptz column.
+const dateInput = z
+ .string()
+ .trim()
+ .refine(value => isCalendarDate(value) || (ISO_WITH_OFFSET.test(value) && !Number.isNaN(Date.parse(value))), {
+ message: "Expected an ISO 8601 timestamp with offset (e.g. 2026-08-18T14:10:00Z) or a YYYY-MM-DD date",
+ })
+ .transform(value => new Date(DATE_ONLY.test(value) ? `${value}T00:00:00.000Z` : value).toISOString());
+
+const endAfterStart = (data: { date?: string; endDate?: string | null }) =>
+ !data.date || !data.endDate || Date.parse(data.endDate) > Date.parse(data.date);
+
+export const annotationScopeSchema = z.enum(["site", "organization"]);
+
+export const createAnnotationSchema = z
+ .object({
+ title: z.string().trim().min(1, "Title is required").max(120),
+ description: z.string().trim().max(2000).nullable().optional(),
+ date: dateInput,
+ endDate: dateInput.nullable().optional(),
+ color: z.enum(ANNOTATION_COLORS).nullable().optional(),
+ icon: z.string().trim().max(16).nullable().optional(),
+ isPublic: z.boolean().optional().default(false),
+ scope: annotationScopeSchema.optional().default("site"),
+ })
+ .refine(endAfterStart, { message: "endDate must be after date", path: ["endDate"] });
+
+export const updateAnnotationSchema = z
+ .object({
+ title: z.string().trim().min(1, "Title is required").max(120).optional(),
+ description: z.string().trim().max(2000).nullable().optional(),
+ date: dateInput.optional(),
+ endDate: dateInput.nullable().optional(),
+ color: z.enum(ANNOTATION_COLORS).nullable().optional(),
+ icon: z.string().trim().max(16).nullable().optional(),
+ isPublic: z.boolean().optional(),
+ scope: annotationScopeSchema.optional(),
+ })
+ .refine(data => Object.keys(data).length > 0, { message: "No fields to update" });
+
+export type CreateAnnotationInput = z.infer<typeof createAnnotationSchema>;
+export type UpdateAnnotationInput = z.infer<typeof updateAnnotationSchema>;
+
+/** Query filters for GET /annotations: either bound is optional, both are calendar dates. */
+export const listAnnotationsQuerySchema = z
+ .object({
+ start_date: z.string().refine(isCalendarDate, { message: "start_date must be a valid YYYY-MM-DD date" }).optional(),
+ end_date: z.string().refine(isCalendarDate, { message: "end_date must be a valid YYYY-MM-DD date" }).optional(),
+ time_zone: z.string().optional(),
+ })
+ .refine(q => !q.start_date || !q.end_date || q.start_date <= q.end_date, {
+ message: "start_date must be on or before end_date",
+ path: ["start_date"],
+ });
diff --git a/server/src/api/analytics/annotations/createAnnotation.ts b/server/src/api/analytics/annotations/createAnnotation.ts
new file mode 100644
index 000000000..5124c12ee
--- /dev/null
+++ b/server/src/api/analytics/annotations/createAnnotation.ts
@@ -0,0 +1,63 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import { z } from "zod";
+import { db } from "../../../db/postgres/postgres.js";
+import { annotations } from "../../../db/postgres/schema.js";
+import { getUserHasAdminAccessToSite } from "../../../lib/auth-utils.js";
+import { getSiteOrganizationId, parseSiteId } from "./annotationAccess.js";
+import { createAnnotationSchema } from "./annotationSchema.js";
+
+export async function createAnnotation(
+ request: FastifyRequest<{
+ Params: { siteId: string };
+ Body: unknown;
+ }>,
+ reply: FastifyReply
+) {
+ const siteId = parseSiteId(request.params.siteId);
+ if (!siteId) {
+ return reply.status(400).send({ error: "Invalid site ID" });
+ }
+
+ try {
+ const input = createAnnotationSchema.parse(request.body);
+
+ const organizationId = await getSiteOrganizationId(siteId);
+ if (!organizationId) {
+ return reply.status(404).send({ error: "Site not found" });
+ }
+
+ // Site access is enforced by the requireSiteAccess preHandler; any member
+ // may create for the site, but organization-wide annotations are admin-only.
+ if (input.scope === "organization" && !(await getUserHasAdminAccessToSite(request, siteId))) {
+ return reply.status(403).send({ error: "Only organization admins can create organization-wide annotations" });
+ }
+
+ const result = await db
+ .insert(annotations)
+ .values({
+ siteId: input.scope === "organization" ? null : siteId,
+ organizationId,
+ userId: request.user?.id ?? null,
+ title: input.title,
+ description: input.description ?? null,
+ date: input.date,
+ endDate: input.endDate ?? null,
+ color: input.color ?? null,
+ icon: input.icon || null,
+ isPublic: input.isPublic,
+ })
+ .returning({ annotationId: annotations.annotationId });
+
+ if (!result.length) {
+ return reply.status(500).send({ error: "Failed to create annotation" });
+ }
+
+ return reply.status(201).send({ success: true, annotationId: result[0].annotationId });
+ } catch (error) {
+ if (error instanceof z.ZodError) {
+ return reply.status(400).send({ error: "Validation error", details: error.errors });
+ }
+ request.log.error({ err: error }, "Error creating annotation");
+ return reply.status(500).send({ error: "Failed to create annotation" });
+ }
+}
diff --git a/server/src/api/analytics/annotations/deleteAnnotation.ts b/server/src/api/analytics/annotations/deleteAnnotation.ts
new file mode 100644
index 000000000..ec92e429c
--- /dev/null
+++ b/server/src/api/analytics/annotations/deleteAnnotation.ts
@@ -0,0 +1,59 @@
+import { eq } from "drizzle-orm";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { db } from "../../../db/postgres/postgres.js";
+import { annotations } from "../../../db/postgres/schema.js";
+import {
+ annotationBelongsToSite,
+ canManageAnnotation,
+ getSiteOrganizationId,
+ parseAnnotationId,
+ parseSiteId,
+} from "./annotationAccess.js";
+
+export async function deleteAnnotation(
+ request: FastifyRequest<{
+ Params: { siteId: string; annotationId: string };
+ }>,
+ reply: FastifyReply
+) {
+ const siteId = parseSiteId(request.params.siteId);
+ const annotationId = parseAnnotationId(request.params.annotationId);
+ if (!siteId) {
+ return reply.status(400).send({ error: "Invalid site ID" });
+ }
+ if (!annotationId) {
+ return reply.status(400).send({ error: "Invalid annotation ID" });
+ }
+
+ try {
+ const organizationId = await getSiteOrganizationId(siteId);
+ if (!organizationId) {
+ return reply.status(404).send({ error: "Site not found" });
+ }
+
+ const existing = await db.query.annotations.findFirst({
+ where: eq(annotations.annotationId, annotationId),
+ });
+ if (!existing || !annotationBelongsToSite(existing, siteId, organizationId)) {
+ return reply.status(404).send({ error: "Annotation not found" });
+ }
+
+ if (!(await canManageAnnotation(request, siteId, existing))) {
+ return reply.status(403).send({ error: "You can only delete annotations you created" });
+ }
+
+ const result = await db
+ .delete(annotations)
+ .where(eq(annotations.annotationId, annotationId))
+ .returning({ deleted: annotations.annotationId });
+
+ if (!result.length) {
+ return reply.status(500).send({ error: "Failed to delete annotation" });
+ }
+
+ return reply.send({ success: true });
+ } catch (error) {
+ request.log.error({ err: error }, "Error deleting annotation");
+ return reply.status(500).send({ error: "Failed to delete annotation" });
+ }
+}
diff --git a/server/src/api/analytics/annotations/getAnnotations.ts b/server/src/api/analytics/annotations/getAnnotations.ts
new file mode 100644
index 000000000..196706ede
--- /dev/null
+++ b/server/src/api/analytics/annotations/getAnnotations.ts
@@ -0,0 +1,92 @@
+import { and, asc, eq, gte, lt, sql } from "drizzle-orm";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { DateTime } from "luxon";
+import { z } from "zod";
+import { db } from "../../../db/postgres/postgres.js";
+import { annotations, user } from "../../../db/postgres/schema.js";
+import { getUserHasAccessToSite } from "../../../lib/auth-utils.js";
+import { isValidTimeZone } from "../utils/timeWindow.js";
+import { annotationsForSite, getSiteOrganizationId, parseSiteId } from "./annotationAccess.js";
+import { listAnnotationsQuerySchema } from "./annotationSchema.js";
+
+export async function getAnnotations(
+ request: FastifyRequest<{
+ Params: { siteId: string };
+ Querystring: { start_date?: string; end_date?: string; time_zone?: string };
+ }>,
+ reply: FastifyReply
+) {
+ const siteId = parseSiteId(request.params.siteId);
+ if (!siteId) {
+ return reply.status(400).send({ error: "Invalid site ID" });
+ }
+
+ try {
+ // This route deliberately skips the shared time validator, which requires
+ // both bounds together; here either bound may stand alone.
+ const query = listAnnotationsQuerySchema.parse(request.query ?? {});
+ const timeZone = query.time_zone ?? "UTC";
+ if (!isValidTimeZone(timeZone)) {
+ return reply.status(400).send({ error: "Invalid time_zone" });
+ }
+
+ const organizationId = await getSiteOrganizationId(siteId);
+ if (!organizationId) {
+ return reply.status(404).send({ error: "Site not found" });
+ }
+
+ // The route is public-guarded: anonymous viewers of a public site or a
+ // private link only see annotations marked public.
+ const fullAccess = await getUserHasAccessToSite(request, siteId);
+
+ const conditions = [annotationsForSite(siteId, organizationId)];
+ if (!fullAccess) conditions.push(eq(annotations.isPublic, true));
+
+ // Day bounds are resolved in the caller's timezone (the dashboard sends
+ // its own), as a half-open interval [start of start_date, start of the
+ // day after end_date). A range annotation overlaps if it ends after the
+ // window starts and starts before the window ends.
+ if (query.start_date) {
+ const start = DateTime.fromISO(query.start_date, { zone: timeZone }).startOf("day").toUTC().toISO()!;
+ conditions.push(gte(sql`coalesce(${annotations.endDate}, ${annotations.date})`, start));
+ }
+ if (query.end_date) {
+ const endExclusive = DateTime.fromISO(query.end_date, { zone: timeZone })
+ .plus({ days: 1 })
+ .startOf("day")
+ .toUTC()
+ .toISO()!;
+ conditions.push(lt(annotations.date, endExclusive));
+ }
+
+ const rows = await db
+ .select({
+ annotationId: annotations.annotationId,
+ siteId: annotations.siteId,
+ organizationId: annotations.organizationId,
+ userId: annotations.userId,
+ userName: user.name,
+ title: annotations.title,
+ description: annotations.description,
+ date: annotations.date,
+ endDate: annotations.endDate,
+ color: annotations.color,
+ icon: annotations.icon,
+ isPublic: annotations.isPublic,
+ createdAt: annotations.createdAt,
+ updatedAt: annotations.updatedAt,
+ })
+ .from(annotations)
+ .leftJoin(user, eq(user.id, annotations.userId))
+ .where(and(...conditions))
+ .orderBy(asc(annotations.date), asc(annotations.annotationId));
+
+ return reply.send(rows);
+ } catch (error) {
+ if (error instanceof z.ZodError) {
+ return reply.status(400).send({ error: "Validation error", details: error.errors });
+ }
+ request.log.error({ err: error }, "Error fetching annotations");
+ return reply.status(500).send({ error: "Failed to fetch annotations" });
+ }
+}
diff --git a/server/src/api/analytics/annotations/updateAnnotation.ts b/server/src/api/analytics/annotations/updateAnnotation.ts
new file mode 100644
index 000000000..92c965c03
--- /dev/null
+++ b/server/src/api/analytics/annotations/updateAnnotation.ts
@@ -0,0 +1,97 @@
+import { eq } from "drizzle-orm";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { z } from "zod";
+import { db } from "../../../db/postgres/postgres.js";
+import { annotations } from "../../../db/postgres/schema.js";
+import { getUserHasAdminAccessToSite } from "../../../lib/auth-utils.js";
+import {
+ annotationBelongsToSite,
+ canManageAnnotation,
+ getSiteOrganizationId,
+ parseAnnotationId,
+ parseSiteId,
+} from "./annotationAccess.js";
+import { updateAnnotationSchema } from "./annotationSchema.js";
+
+export async function updateAnnotation(
+ request: FastifyRequest<{
+ Params: { siteId: string; annotationId: string };
+ Body: unknown;
+ }>,
+ reply: FastifyReply
+) {
+ const siteId = parseSiteId(request.params.siteId);
+ const annotationId = parseAnnotationId(request.params.annotationId);
+ if (!siteId) {
+ return reply.status(400).send({ error: "Invalid site ID" });
+ }
+ if (!annotationId) {
+ return reply.status(400).send({ error: "Invalid annotation ID" });
+ }
+
+ try {
+ const input = updateAnnotationSchema.parse(request.body);
+
+ const organizationId = await getSiteOrganizationId(siteId);
+ if (!organizationId) {
+ return reply.status(404).send({ error: "Site not found" });
+ }
+
+ const existing = await db.query.annotations.findFirst({
+ where: eq(annotations.annotationId, annotationId),
+ });
+ if (!existing || !annotationBelongsToSite(existing, siteId, organizationId)) {
+ return reply.status(404).send({ error: "Annotation not found" });
+ }
+
+ if (!(await canManageAnnotation(request, siteId, existing))) {
+ return reply.status(403).send({ error: "You can only edit annotations you created" });
+ }
+
+ // The merged row must still be a valid range.
+ const nextDate = input.date ?? existing.date;
+ const nextEndDate = input.endDate === undefined ? existing.endDate : input.endDate;
+ if (nextEndDate && Date.parse(nextEndDate) <= Date.parse(nextDate)) {
+ return reply.status(400).send({ error: "endDate must be after date" });
+ }
+
+ let nextSiteId: number | null | undefined;
+ if (input.scope !== undefined) {
+ const wantsOrgWide = input.scope === "organization";
+ if (wantsOrgWide !== (existing.siteId === null)) {
+ if (!(await getUserHasAdminAccessToSite(request, siteId))) {
+ return reply.status(403).send({ error: "Only organization admins can change an annotation's scope" });
+ }
+ nextSiteId = wantsOrgWide ? null : siteId;
+ }
+ }
+
+ const result = await db
+ .update(annotations)
+ .set({
+ ...(input.title !== undefined ? { title: input.title } : {}),
+ ...(input.description !== undefined ? { description: input.description } : {}),
+ ...(input.date !== undefined ? { date: input.date } : {}),
+ ...(input.endDate !== undefined ? { endDate: input.endDate } : {}),
+ ...(input.color !== undefined ? { color: input.color } : {}),
+ ...(input.icon !== undefined ? { icon: input.icon || null } : {}),
+ ...(input.isPublic !== undefined ? { isPublic: input.isPublic } : {}),
+ ...(nextSiteId !== undefined ? { siteId: nextSiteId } : {}),
+ updatedAt: new Date().toISOString(),
+ })
+ .where(eq(annotations.annotationId, annotationId))
+ .returning({ annotationId: annotations.annotationId });
+
+ if (!result.length) {
+ return reply.status(500).send({ error: "Failed to update annotation" });
+ }
+
+ return reply.send({ success: true });
+ } catch (error) {
+ if (error instanceof z.ZodError) {
+ return reply.status(400).send({ error: "Validation error", details: error.errors });
+ }
+ request.log.error({ err: error }, "Error updating annotation");
+ return reply.status(500).send({ error: "Failed to update annotation" });
+ }
+}
diff --git a/server/src/api/analytics/index.ts b/server/src/api/analytics/index.ts
index 8ef8cd391..8e44749f8 100644
--- a/server/src/api/analytics/index.ts
+++ b/server/src/api/analytics/index.ts
@@ -80,3 +80,8 @@ export { getUsers } from "./users/getUsers.js";
export { getUserTraitKeys, getUserTraitValues, getUserTraitValueUsers } from "./users/getUserTraits.js";
export { identifyUser } from "./users/identifyUser.js";
export { updateUserTraits } from "./users/updateUserTraits.js";
+
+export { getAnnotations } from "./annotations/getAnnotations.js";
+export { createAnnotation } from "./annotations/createAnnotation.js";
+export { updateAnnotation } from "./annotations/updateAnnotation.js";
+export { deleteAnnotation } from "./annotations/deleteAnnotation.js";
diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.ts
index a81678a20..cedf36928 100644
--- a/server/src/db/postgres/schema.ts
+++ b/server/src/db/postgres/schema.ts
@@ -1,5 +1,5 @@
import { sql } from "drizzle-orm";
-import type { DashboardConfig, Filter, SegmentType } from "@rybbit/shared";
+import type { AnnotationColor, DashboardConfig, Filter, SegmentType } from "@rybbit/shared";
import {
boolean,
check,
@@ -142,6 +142,34 @@ export const dashboards = pgTable("dashboards", {
updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
});
+// Timeline annotations: a note pinned to a date (or range) on the traffic chart.
+// site_id is null for organization-wide annotations, which show on every site
+// in organization_id.
+export const annotations = pgTable(
+ "annotations",
+ {
+ annotationId: serial("annotation_id").primaryKey().notNull(),
+ siteId: integer("site_id").references(() => sites.siteId, { onDelete: "cascade" }),
+ organizationId: text("organization_id")
+ .notNull()
+ .references(() => organization.id, { onDelete: "cascade" }),
+ userId: text("user_id").references(() => user.id, { onDelete: "set null" }),
+ title: text("title").notNull(),
+ description: text("description"),
+ date: timestamp("date", { mode: "string", withTimezone: true }).notNull(),
+ endDate: timestamp("end_date", { mode: "string", withTimezone: true }),
+ color: text("color").$type<AnnotationColor>(),
+ icon: text("icon"),
+ isPublic: boolean("is_public").notNull().default(false),
+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
+ },
+ table => [
+ index("annotations_site_date_idx").on(table.siteId, table.date),
+ index("annotations_org_date_idx").on(table.organizationId, table.date),
+ ]
+);
+
// Saved segments: a named, reusable set of analytics filters. A segment is
// scoped to one site or, with a null site_id, to every site in its
// organization. `type` is reserved so cohorts can share the table later.
diff --git a/server/src/index.ts b/server/src/index.ts
index ae15f67f6..f88bd01eb 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -22,16 +22,19 @@ import {
updateAdminSubscriptionOverride,
} from "./api/admin/index.js";
import {
+ createAnnotation,
createDashboard,
createSegment,
createFunnel,
createGoal,
+ deleteAnnotation,
deleteDashboard,
deleteSegment,
deleteFunnel,
deleteGoal,
deleteUser,
generatePdfReport,
+ getAnnotations,
getDashboard,
getDashboards,
getSegment,
@@ -84,6 +87,7 @@ import {
identifyUser,
runCustomQuery,
runDashboardCardQuery,
+ updateAnnotation,
updateDashboard,
updateSegment,
expandSegmentParam,
@@ -272,6 +276,12 @@ const authAnalyticsRead = authSiteScoped("analytics", "read");
const authReplayWrite = authSiteScoped("replay", "write");
const authOrgRead = authOnlyScoped("org", "read");
const adminSitesRead = adminSiteScoped("sites", "read");
+// Annotations validate their own optional start/end bounds (either may stand
+// alone), so the shared time validator is left off this chain.
+const publicAnnotationsRead = {
+ preHandler: [resolveSiteId, allowPublicSiteAccess({ resource: "annotations", action: "read" })] as any,
+};
+const authAnnotationsWrite = authSiteScoped("annotations", "write");
const authDashboardsRead = authSiteScoped("dashboards", "read");
const authDashboardsWrite = authSiteScoped("dashboards", "write");
const publicSegmentsRead = publicSiteScoped("segments", "read");
@@ -450,6 +460,12 @@ async function analyticsRoutes(fastify: FastifyInstance) {
fastify.post("/sites/:siteId/goals", authGoalsWrite, createGoal);
fastify.delete("/sites/:siteId/goals/:goalId", authGoalsWrite, deleteGoal);
fastify.put("/sites/:siteId/goals/:goalId", authGoalsWrite, updateGoal);
+ // Timeline annotations. Read is public-guarded so public dashboards and
+ // private links get the annotations marked public; writes need site access.
+ fastify.get("/sites/:siteId/annotations", publicAnnotationsRead, getAnnotations);
+ fastify.post("/sites/:siteId/annotations", authAnnotationsWrite, createAnnotation);
+ fastify.put("/sites/:siteId/annotations/:annotationId", authAnnotationsWrite, updateAnnotation);
+ fastify.delete("/sites/:siteId/annotations/:annotationId", authAnnotationsWrite, deleteAnnotation);
fastify.get("/sites/:siteId/dashboards", authDashboardsRead, getDashboards);
fastify.get("/sites/:siteId/dashboards/:dashboardId", authDashboardsRead, getDashboard);
fastify.post("/sites/:siteId/dashboards", authDashboardsWrite, createDashboard);
diff --git a/server/src/mcp/mcp.test.ts b/server/src/mcp/mcp.test.ts
index 77c2cc3aa..7a8819710 100644
--- a/server/src/mcp/mcp.test.ts
+++ b/server/src/mcp/mcp.test.ts
@@ -163,6 +163,12 @@ describe("mcp endpoint", () => {
return reply.status(403).send({ error: "You don't have access to this site" });
});
+ fastify.get("/sites/:siteId/annotations", async request => {
+ captured.url = request.url;
+ captured.query = request.query as Record<string, unknown>;
+ return [{ annotationId: 1, siteId: 5, title: "Launch", date: "2026-08-18T00:00:00.000Z", isPublic: true }];
+ });
+
fastify.post("/sites/:siteId/goals", async request => {
captured.url = request.url;
captured.method = request.method;
@@ -321,11 +327,11 @@ describe("mcp endpoint", () => {
expect(result.instructions).toContain("run_query");
});
- it("lists all 39 tools with output schemas", async () => {
+ it("lists all 42 tools with output schemas", async () => {
const tools = await listTools(app);
const names = tools.map(tool => tool.name);
- expect(tools).toHaveLength(41);
+ expect(tools).toHaveLength(42);
expect(names).toContain("list_sites");
expect(names).toContain("get_overview");
expect(names).toContain("get_breakdown");
@@ -336,9 +342,13 @@ describe("mcp endpoint", () => {
expect(names).toContain("create_goal");
expect(names).toContain("get_users");
expect(names).toContain("list_members");
+ expect(names).toContain("get_annotations");
const overview = tools.find(tool => tool.name === "get_overview");
expect(overview?.outputSchema).toBeTruthy();
+ const annotationsTool = tools.find(tool => tool.name === "get_annotations");
+ expect(annotationsTool?.outputSchema).toBeTruthy();
+ expect(annotationsTool?.annotations?.readOnlyHint).toBe(true);
});
it("filters tools/list to the API key's scopes, keeping list_sites", async () => {
@@ -363,7 +373,7 @@ describe("mcp endpoint", () => {
it("legacy OAuth grants with only standard scopes stay unrestricted", async () => {
const tools = await listTools(app, "Bearer oauth_valid_token");
- expect(tools).toHaveLength(41);
+ expect(tools).toHaveLength(42);
});
it("partitions tools into reads, writes, and destructive deletes", async () => {
@@ -473,6 +483,17 @@ describe("mcp endpoint", () => {
expect(captured.url).toBeUndefined();
});
+ it("get_annotations forwards optional date bounds and wraps the array", async () => {
+ const result = await callTool(app, "get_annotations", { site_id: 5, start_date: "2026-08-01", time_zone: "UTC" });
+
+ expect(result.isError).toBeFalsy();
+ expect(captured.url).toContain("/api/sites/5/annotations");
+ expect(captured.query).toEqual({ start_date: "2026-08-01", time_zone: "UTC" });
+ expect(result.structuredContent).toEqual({
+ data: [{ annotationId: 1, siteId: 5, title: "Launch", date: "2026-08-18T00:00:00.000Z", isPublic: true }],
+ });
+ });
+
it("get_sessions passes rows through but strips bidi control characters", async () => {
const result = await callTool(app, "get_sessions", { site_id: 5 });
diff --git a/server/src/mcp/tools/annotations.ts b/server/src/mcp/tools/annotations.ts
new file mode 100644
index 000000000..4da37e519
--- /dev/null
+++ b/server/src/mcp/tools/annotations.ts
@@ -0,0 +1,48 @@
+import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { z } from "zod";
+import { RybbitApiClient } from "../apiClient.js";
+import { siteIdInput } from "../inputs.js";
+import { looseRows, ok, readOnly, type ScopeCheck, type ToolGuard } from "./shared.js";
+
+const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
+
+const annotationsOutput = z.object({ data: looseRows.optional() }).passthrough();
+
+export function registerAnnotationTools(
+ server: McpServer,
+ api: RybbitApiClient,
+ guard: ToolGuard,
+ allowed: ScopeCheck
+): void {
+ if (allowed("annotations", "read"))
+ server.registerTool(
+ "get_annotations",
+ {
+ title: "Timeline annotations",
+ description:
+ "Notes pinned to dates on the site's traffic chart (launches, deploys, campaigns, outages), including organization-wide ones. Each has a title, optional description, date, optional endDate for ranges, and isPublic. Use these to explain spikes or dips before speculating about causes.",
+ inputSchema: {
+ site_id: siteIdInput,
+ start_date: z
+ .string()
+ .regex(dateRegex, "Use YYYY-MM-DD")
+ .optional()
+ .describe("Only annotations on or after this date (YYYY-MM-DD, in time_zone). Omit for all."),
+ end_date: z
+ .string()
+ .regex(dateRegex, "Use YYYY-MM-DD")
+ .optional()
+ .describe("Only annotations on or before this date (YYYY-MM-DD, in time_zone). Omit for all."),
+ time_zone: z
+ .string()
+ .optional()
+ .describe("IANA timezone the date bounds are read in (default UTC), e.g. America/Los_Angeles."),
+ },
+ outputSchema: annotationsOutput,
+ annotations: readOnly,
+ },
+ guard(async ({ site_id, start_date, end_date, time_zone }) =>
+ ok(await api.call("GET", `/sites/${site_id}/annotations`, { query: { start_date, end_date, time_zone } }))
+ )
+ );
+}
diff --git a/server/src/mcp/tools/index.ts b/server/src/mcp/tools/index.ts
index 81998c956..38b09a935 100644
--- a/server/src/mcp/tools/index.ts
+++ b/server/src/mcp/tools/index.ts
@@ -1,6 +1,7 @@
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { RybbitApiClient } from "../apiClient.js";
import { registerAnalyticsTools } from "./analytics.js";
+import { registerAnnotationTools } from "./annotations.js";
import { registerFunnelTools } from "./funnels.js";
import { registerGoalTools } from "./goals.js";
import { registerOrganizationTools } from "./organizations.js";
@@ -23,4 +24,5 @@ export function registerTools(server: McpServer, api: RybbitApiClient, config: T
registerUserTools(server, api, guard, allowed);
registerOrganizationTools(server, api, guard, allowed);
registerRawDataTools(server, api, guard, allowed);
+ registerAnnotationTools(server, api, guard, allowed);
}
diff --git a/shared/src/annotations.ts b/shared/src/annotations.ts
new file mode 100644
index 000000000..9f61c3255
--- /dev/null
+++ b/shared/src/annotations.ts
@@ -0,0 +1,27 @@
+/** Marker colors an annotation may use. `null` renders the neutral default. */
+export const ANNOTATION_COLORS = ["amber", "rose", "sky", "violet", "lime"] as const;
+export type AnnotationColor = (typeof ANNOTATION_COLORS)[number];
+
+export interface Annotation {
+ annotationId: number;
+ /** Null for organization-wide annotations, which appear on every site in the organization. */
+ siteId: number | null;
+ organizationId: string;
+ userId: string | null;
+ userName: string | null;
+ title: string;
+ description: string | null;
+ /** ISO 8601 timestamp. */
+ date: string;
+ /** ISO 8601 timestamp; set when the annotation spans a range. */
+ endDate: string | null;
+ color: AnnotationColor | null;
+ /** Short emoji or symbol shown in the pin. */
+ icon: string | null;
+ /** Public annotations are visible on public dashboards and private-link views. */
+ isPublic: boolean;
+ createdAt: string;
+ updatedAt: string;
+}
+
+export type AnnotationScope = "site" | "organization";
diff --git a/shared/src/index.ts b/shared/src/index.ts
index 698b5ec59..399b8ffd0 100644
--- a/shared/src/index.ts
+++ b/shared/src/index.ts
@@ -7,3 +7,4 @@ export * from "./segments";
export * from "./time";
export * from "./performance";
export * from "./aiOperators";
+export * from "./annotations";
diff --git a/shared/src/scopes.ts b/shared/src/scopes.ts
index e53f88cbf..2f459e767 100644
--- a/shared/src/scopes.ts
+++ b/shared/src/scopes.ts
@@ -16,6 +16,7 @@ export const SCOPE_MATRIX = {
goals: ["read", "write"],
funnels: ["read", "write"],
dashboards: ["read", "write"],
+ annotations: ["read", "write"],
segments: ["read", "write"],
flags: ["read", "write"],
experiments: ["read", "write"],