🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
events (#103)
Bill Yangb220d01a70c6
diff --git a/client/src/api/analytics/useGetEventNames.ts b/client/src/api/analytics/useGetEventNames.tsnew file mode 100644index 000000000..e628717e7--- /dev/null+++ b/client/src/api/analytics/useGetEventNames.ts@@ -0,0 +1,33 @@+import { useQuery } from "@tanstack/react-query";+import { BACKEND_URL } from "../../lib/const";+import { useStore, getFilteredFilters, EVENT_FILTERS } from "../../lib/store";+import { authedFetchWithError } from "../utils";+import { getQueryTimeParams } from "./utils";+import { buildUrl } from "../utils";++export type EventName = {+ eventName: string;+ count: number;+};++export function useGetEventNames() {+ const { site, time, filters } = useStore();++ const timeParams = getQueryTimeParams(time);+ const filteredFilters = getFilteredFilters(EVENT_FILTERS);++ return useQuery({+ queryKey: ["event-names", site, timeParams, filteredFilters],+ enabled: !!site,+ queryFn: () => {+ const url = buildUrl(`${BACKEND_URL}/events/names/${site}`, {+ ...Object.fromEntries(new URLSearchParams(timeParams)),+ filters: filteredFilters.length > 0 ? filteredFilters : undefined,+ });++ return authedFetchWithError<{ data: EventName[] }>(url).then(+ (res) => res.data+ );+ },+ });+}diff --git a/client/src/api/analytics/useGetEventProperties.ts b/client/src/api/analytics/useGetEventProperties.tsnew file mode 100644index 000000000..efa009a69--- /dev/null+++ b/client/src/api/analytics/useGetEventProperties.ts@@ -0,0 +1,41 @@+import { useQuery } from "@tanstack/react-query";+import { BACKEND_URL } from "../../lib/const";+import { useStore, getFilteredFilters, EVENT_FILTERS } from "../../lib/store";+import { authedFetchWithError } from "../utils";+import { getQueryTimeParams } from "./utils";+import { buildUrl } from "../utils";++export type EventProperty = {+ propertyKey: string;+ propertyValue: string;+ count: number;+};++export function useGetEventProperties(eventName: string | null) {+ const { site, time, filters } = useStore();++ const timeParams = getQueryTimeParams(time);+ const filteredFilters = getFilteredFilters(EVENT_FILTERS);++ return useQuery({+ queryKey: [+ "event-properties",+ site,+ eventName,+ timeParams,+ filteredFilters,+ ],+ enabled: !!site && !!eventName,+ queryFn: () => {+ const url = buildUrl(`${BACKEND_URL}/events/properties/${site}`, {+ ...Object.fromEntries(new URLSearchParams(timeParams)),+ eventName,+ filters: filteredFilters.length > 0 ? filteredFilters : undefined,+ });++ return authedFetchWithError<{ data: EventProperty[] }>(url).then(+ (res) => res.data+ );+ },+ });+}diff --git a/client/src/api/analytics/useGetEvents.ts b/client/src/api/analytics/useGetEvents.tsindex ecc07ad82..04afeaff0 100644--- a/client/src/api/analytics/useGetEvents.ts+++ b/client/src/api/analytics/useGetEvents.ts@@ -1,7 +1,8 @@-import { useQuery } from "@tanstack/react-query";+import { useInfiniteQuery, useQuery } from "@tanstack/react-query";+import { Time } from "../../components/DateSelector/types";import { BACKEND_URL } from "../../lib/const";import { useStore } from "../../lib/store";-import { authedFetchWithError } from "../utils";+import { authedFetchWithError, buildUrl, getStartAndEndDate } from "../utils";export type Event = {timestamp: string;@@ -20,6 +21,24 @@ export type Event = {type: string;};+export interface EventsResponse {+ data: Event[];+ pagination: {+ total: number;+ page: number;+ pageSize: number;+ totalPages: number;+ };+}++export interface GetEventsOptions {+ time?: Time;+ page?: number;+ pageSize?: number;+ count?: number; // For backward compatibility+ isRealtime?: boolean;+}+export function useGetEvents(count = 10) {const { site } = useStore();return useQuery({@@ -31,3 +50,57 @@ export function useGetEvents(count = 10) {).then((res) => res.data),});}++// New hook with pagination and filtering support+export function useGetEventsInfinite(options: GetEventsOptions = {}) {+ const { site, time, filters } = useStore();+ const { startDate, endDate } = options.time+ ? getStartAndEndDate(options.time)+ : getStartAndEndDate(time);+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ const pageSize = options.pageSize || 20;++ return useInfiniteQuery<EventsResponse, Error>({+ queryKey: [+ "events-infinite",+ site,+ startDate,+ endDate,+ timezone,+ filters,+ pageSize,+ options.isRealtime,+ ],+ initialPageParam: 1,+ queryFn: async ({ pageParam }) => {+ const params: Record<string, any> = {+ startDate,+ endDate,+ timezone,+ page: pageParam,+ pageSize,+ };++ // Add filters if provided+ if (filters && filters.length > 0) {+ params.filters = JSON.stringify(filters);+ }++ // Add count if provided (for backward compatibility)+ if (options.count) {+ params.count = options.count;+ }++ const url = buildUrl(`${BACKEND_URL}/events/${site}`, params);+ const response = await authedFetchWithError<EventsResponse>(url);+ return response;+ },+ getNextPageParam: (lastPage: EventsResponse) => {+ if (lastPage.pagination.page < lastPage.pagination.totalPages) {+ return lastPage.pagination.page + 1;+ }+ return undefined;+ },+ refetchInterval: options.isRealtime ? 5000 : undefined,+ });+}diff --git a/client/src/api/analytics/utils.ts b/client/src/api/analytics/utils.tsnew file mode 100644index 000000000..69bf814f5--- /dev/null+++ b/client/src/api/analytics/utils.ts@@ -0,0 +1,20 @@+import { Time } from "../../components/DateSelector/types";+import { getStartAndEndDate } from "../utils";++/**+ * Generates URL query parameters for time filtering+ * @param time Time object from store+ * @returns URL query string with time parameters+ */+export function getQueryTimeParams(time: Time): string {+ const { startDate, endDate } = getStartAndEndDate(time);+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;++ const params = new URLSearchParams();++ if (startDate) params.append("startDate", startDate);+ if (endDate) params.append("endDate", endDate);+ params.append("timezone", timezone);++ return params.toString();+}diff --git a/client/src/app/[site]/components/Sidebar/Sidebar.tsx b/client/src/app/[site]/components/Sidebar/Sidebar.tsxindex 0785eb73e..fac07f630 100644--- a/client/src/app/[site]/components/Sidebar/Sidebar.tsx+++ b/client/src/app/[site]/components/Sidebar/Sidebar.tsx@@ -1,5 +1,5 @@"use client";-import { Funnel, Target } from "@phosphor-icons/react/dist/ssr";+import { CursorClick, Funnel, Target } from "@phosphor-icons/react/dist/ssr";import {ChartBarDecreasing,Earth,@@ -10,6 +10,7 @@ import {User,Map,Split,+ MousePointerClick,} from "lucide-react";import Link from "next/link";import { usePathname } from "next/navigation";@@ -100,6 +101,12 @@ export function Sidebar() {href={getTabPath("retention")}icon={<LayoutGrid className="w-4 h-4" />}/>+ <SidebarLink+ label="Events"+ active={isActiveTab("events")}+ href={getTabPath("events")}+ icon={<MousePointerClick className="w-4 h-4" />}+ />{/* <SidebarLinklabel="Reports"active={isActiveTab("reports")}diff --git a/client/src/app/[site]/components/shared/StandardSection/StandardSectionRealtime.tsx b/client/src/app/[site]/components/shared/StandardSection/StandardSectionRealtime.tsxdeleted file mode 100644index 6c0c6b507..000000000--- a/client/src/app/[site]/components/shared/StandardSection/StandardSectionRealtime.tsx+++ /dev/null@@ -1,47 +0,0 @@-"use client";--import { ReactNode } from "react";-import {- SingleColResponse,- useSingleColRealtime,-} from "../../../../../api/analytics/useSingleCol";-import { FilterParameter } from "../../../../../lib/store";-import { BaseStandardSection } from "./BaseStandardSection";--export function StandardSectionRealtime({- title,- getKey,- getLabel,- getValue,- getLink,- countLabel,- filterParameter,-}: {- title: string;- isFetching?: boolean;- getKey: (item: SingleColResponse) => string;- getLabel: (item: SingleColResponse) => ReactNode;- getValue: (item: SingleColResponse) => string;- getLink?: (item: SingleColResponse) => string;- countLabel?: string;- filterParameter: FilterParameter;-}) {- const { data, isFetching, error, refetch } = useSingleColRealtime({- parameter: filterParameter,- });-- return null;- // <BaseStandardSection- // title={title}- // data={data}- // isFetching={isFetching}- // error={error}- // refetch={refetch}- // getKey={getKey}- // getLabel={getLabel}- // getValue={getValue}- // getLink={getLink}- // countLabel={countLabel}- // filterParameter={filterParameter}- // />-}diff --git a/client/src/app/[site]/events/components/EventList.tsx b/client/src/app/[site]/events/components/EventList.tsxnew file mode 100644index 000000000..74a21638f--- /dev/null+++ b/client/src/app/[site]/events/components/EventList.tsx@@ -0,0 +1,183 @@+"use client";++import NumberFlow from "@number-flow/react";+import { ChevronDown, ChevronRight, Info } from "lucide-react";+import { memo, useState } from "react";+import { EventName } from "../../../../api/analytics/useGetEventNames";+import { useGetEventProperties } from "../../../../api/analytics/useGetEventProperties";+import { EventProperties } from "./EventProperties";++// Skeleton component for EventList+const EventListSkeleton = memo(+ ({ size = "small" }: { size?: "small" | "large" }) => {+ // Generate widths following Pareto principle with top item at 100%+ const widths = Array.from({ length: 10 }, (_, i) => {+ if (i === 0) {+ // First item always has 100% width+ return 100;+ } else if (i === 1) {+ // Second item gets large width (60-80%)+ return 60 + Math.random() * 20;+ } else {+ // Remaining 8 items get progressively smaller widths (10-40%)+ const factor = 1 - (i - 2) / 8; // Creates a declining factor from 1 to 0.125+ return 10 + factor * 30; // Creates widths from ~40% down to ~15%+ }+ });++ // Generate random widths for label and value placeholders+ const labelWidths = Array.from({ length: 10 }, (_, i) => {+ // First few items get wider labels+ return i < 3 ? 75 + Math.random() * 100 : 40 + Math.random() * 60;+ });++ const valueWidths = Array.from(+ { length: 10 },+ () => 20 + Math.random() * 40 // Between 20px and 60px+ );++ return (+ <div className="flex flex-col gap-2 pr-2">+ {Array.from({ length: 10 }).map((_, index) => (+ <div+ key={index}+ className={`relative ${+ size === "small" ? "h-6" : "h-9"+ } flex items-center`}+ >+ <div+ className="absolute inset-0 bg-neutral-800 py-2 rounded-md animate-pulse"+ style={{ width: `${widths[index]}%` }}+ ></div>+ <div+ className={`z-5 mx-2 flex justify-between items-center ${+ size === "small" ? "text-xs" : "text-sm"+ } w-full`}+ >+ <div className="flex items-center gap-1">+ <div className="h-4 w-4 bg-neutral-800 rounded animate-pulse mr-1"></div>+ <div+ className="h-4 bg-neutral-800 rounded animate-pulse"+ style={{ width: `${labelWidths[index]}px` }}+ ></div>+ </div>+ <div+ className={`${+ size === "small" ? "text-xs" : "text-sm"+ } flex gap-2`}+ >+ <div+ className="h-4 bg-neutral-800 rounded animate-pulse"+ style={{ width: `${valueWidths[index]}px` }}+ ></div>+ </div>+ </div>+ </div>+ ))}+ </div>+ );+ }+);++interface EventListProps {+ events: EventName[];+ isLoading: boolean;+ size?: "small" | "large";+}++export function EventList({+ events,+ isLoading,+ size = "small",+}: EventListProps) {+ const [expandedEvent, setExpandedEvent] = useState<string | null>(null);++ const handleEventClick = (eventName: string) => {+ setExpandedEvent(expandedEvent === eventName ? null : eventName);+ };++ const { data: eventPropertiesData, isLoading: isLoadingProperties } =+ useGetEventProperties(expandedEvent);++ if (isLoading) {+ return <EventListSkeleton size={size} />;+ }++ if (!events || events.length === 0) {+ return (+ <div className="text-neutral-300 w-full text-center mt-6 flex flex-row gap-2 items-center justify-center">+ <Info className="w-5 h-5" />+ No custom events found+ </div>+ );+ }++ // Find the highest count to calculate percentages+ const maxCount = Math.max(...events.map((event) => event.count));++ return (+ <div className="flex flex-col gap-2">+ {events.map((event) => {+ const percentage = (event.count / maxCount) * 100;+ const isExpanded = expandedEvent === event.eventName;++ return (+ <div key={event.eventName} className="flex flex-col">+ {/* Event Row */}+ <div+ className={`relative ${+ size === "small" ? "h-6" : "h-9"+ } flex items-center cursor-pointer hover:bg-neutral-850 group px-2 rounded-md`}+ onClick={() => handleEventClick(event.eventName)}+ >+ <div+ className="absolute inset-0 bg-dataviz py-2 opacity-25 rounded-md"+ style={{ width: `${percentage}%` }}+ ></div>+ <div+ className={`z-10 flex justify-between items-center ${+ size === "small" ? "text-xs" : "text-sm"+ } w-full`}+ >+ <div className="font-medium truncate max-w-[70%] flex items-center gap-1">+ {isExpanded ? (+ <ChevronDown className="h-4 w-4 text-neutral-400" />+ ) : (+ <ChevronRight className="h-4 w-4 text-neutral-400" />+ )}+ {event.eventName}+ </div>+ <div+ className={`text-sm flex gap-2 ${+ size === "small" ? "text-xs" : "text-sm"+ }`}+ >+ <div className="hidden group-hover:block text-neutral-400">+ {Math.round(percentage * 10) / 10}%+ </div>+ <NumberFlow+ respectMotionPreference={false}+ value={event.count}+ format={{ notation: "compact" }}+ />+ </div>+ </div>+ </div>++ {/* Properties Section (Expanded) */}+ {isExpanded && (+ <div className="ml-4 mt-2 mb-4 border-l-2 border-neutral-800 pl-4">+ <EventProperties+ properties={eventPropertiesData || []}+ isLoading={isLoadingProperties}+ selectedEvent={expandedEvent}+ size={size}+ />+ </div>+ )}+ </div>+ );+ })}+ </div>+ );+}diff --git a/client/src/app/[site]/events/components/EventLog.tsx b/client/src/app/[site]/events/components/EventLog.tsxnew file mode 100644index 000000000..189a43ae5--- /dev/null+++ b/client/src/app/[site]/events/components/EventLog.tsx@@ -0,0 +1,117 @@+"use client";++import { useCallback, useEffect, useRef } from "react";+import { useGetEventsInfinite } from "../../../../api/analytics/useGetEvents";+import { formatter } from "../../../../lib/utils";+import { EventLogItem, EventLogItemSkeleton } from "./EventLogItem";++export function EventLog() {+ const containerRef = useRef<HTMLDivElement>(null);+ const loadMoreRef = useRef<HTMLDivElement>(null);++ // Fetch events with infinite scrolling+ const {+ data,+ isLoading,+ isError,+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage,+ } = useGetEventsInfinite({+ pageSize: 100,+ });++ // Remove console.log++ // Handle scroll for infinite loading+ const handleScroll = useCallback(() => {+ if (+ !loadMoreRef.current ||+ !containerRef.current ||+ !hasNextPage ||+ isFetchingNextPage+ ) {+ return;+ }++ const container = containerRef.current;+ const loadMoreElement = loadMoreRef.current;+ const containerRect = container.getBoundingClientRect();+ const loadMoreRect = loadMoreElement.getBoundingClientRect();++ // Check if the load more element is visible in the viewport+ if (loadMoreRect.top <= containerRect.bottom + 100) {+ fetchNextPage();+ }+ }, [fetchNextPage, hasNextPage, isFetchingNextPage]);++ // Set up scroll event listener+ useEffect(() => {+ const container = containerRef.current;+ if (!container) return;++ container.addEventListener("scroll", handleScroll);+ return () => {+ container.removeEventListener("scroll", handleScroll);+ };+ }, [handleScroll]);++ // Flatten all pages of data+ const allEvents = data?.pages.flatMap((page) => page.data) || [];++ if (isLoading) {+ return (+ <div className="space-y-2">+ {Array.from({ length: 100 }).map((_, index) => (+ <EventLogItemSkeleton key={index} />+ ))}+ </div>+ );+ }++ if (isError) {+ return (+ <div className="text-center py-8 text-neutral-400">+ Error loading events. Please try again.+ </div>+ );+ }++ if (allEvents.length === 0) {+ return (+ <div className="text-center py-8 text-neutral-400">+ No events found in the selected time period.+ </div>+ );+ }++ return (+ <div className="space-y-1">+ {/* Event list */}+ <div ref={containerRef} className={`max-h-[80vh] overflow-y-auto pr-2`}>+ {allEvents.map((event, index) => (+ <EventLogItem key={`${event.timestamp}-${index}`} event={event} />+ ))}++ {/* Loading state for next page */}+ {hasNextPage && (+ <div className="py-2">+ {Array.from({ length: 3 }).map((_, index) => (+ <EventLogItemSkeleton key={`next-page-${index}`} />+ ))}+ </div>+ )}++ {/* Invisible element for scroll detection */}+ {hasNextPage && <div ref={loadMoreRef} className="h-1" />}+ </div>+ {/* Pagination info */}+ {data?.pages[0]?.pagination && (+ <div className="text-center text-xs text-neutral-400 pt-2">+ Showing {allEvents.length} of{" "}+ {formatter(data.pages[0].pagination.total)} events+ </div>+ )}+ </div>+ );+}diff --git a/client/src/app/[site]/events/components/EventLogItem.tsx b/client/src/app/[site]/events/components/EventLogItem.tsxnew file mode 100644index 000000000..c6b7a79c1--- /dev/null+++ b/client/src/app/[site]/events/components/EventLogItem.tsx@@ -0,0 +1,245 @@+"use client";++import { Event } from "../../../../api/analytics/useGetEvents";+import { DateTime } from "luxon";+import { Browser } from "../../components/shared/icons/Browser";+import { CountryFlag } from "../../components/shared/icons/CountryFlag";+import { OperatingSystem } from "../../components/shared/icons/OperatingSystem";+import { getCountryName } from "../../../../lib/utils";+import { Laptop, Smartphone, FileText, MousePointerClick } from "lucide-react";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import { Badge } from "@/components/ui/badge";+import Link from "next/link";+import { useParams } from "next/navigation";+import { memo } from "react";++// DeviceIcon component for displaying mobile/desktop icons+function DeviceIcon({ deviceType }: { deviceType: string }) {+ const type = deviceType.toLowerCase();++ if (type.includes("mobile") || type.includes("tablet")) {+ return <Smartphone className="w-4 h-4" />;+ }++ return <Laptop className="w-4 h-4" />;+}++// Function to truncate path for display+function truncatePath(path: string, maxLength: number = 64) {+ if (!path) return "-";+ if (path.length <= maxLength) return path;++ // Keep the beginning of the path with ellipsis+ return `${path.substring(0, maxLength)}...`;+}++interface EventLogItemProps {+ event: Event;+}++export function EventLogItem({ event }: EventLogItemProps) {+ const { site } = useParams();++ // Parse event timestamp+ const eventTime = DateTime.fromSQL(event.timestamp, {+ zone: "utc",+ }).toLocal();++ // Determine if it's a pageview or custom event+ const isPageview = event.type === "pageview";++ const fullPath = `https://${event.hostname}${event.pathname}${+ event.querystring ? `${event.querystring}` : ""+ }`;++ // Parse event properties if they exist+ let eventProperties: Record<string, any> = {};+ if (event.properties && event.properties !== "{}") {+ try {+ eventProperties = JSON.parse(event.properties);+ } catch (e) {+ console.error("Failed to parse event properties:", e);+ }+ }++ return (+ <div className="mb-3 rounded-lg bg-neutral-850/50 border border-neutral-800 overflow-hidden p-3 hover:bg-neutral-800/70 transition-all duration-200">+ <div className="flex flex-col space-y-2">+ {/* Single row with event type, name/path, device info, and timestamp */}+ <div className="flex items-center gap-2 text-sm text-neutral-100">+ {/* Left side content */}+ <div className="flex items-center gap-2 flex-grow min-w-0">+ {/* Event type icon */}+ <div className="flex-shrink-0">+ {isPageview ? (+ <FileText className="w-4 h-4 text-blue-500" />+ ) : (+ <MousePointerClick className="w-4 h-4 text-amber-500" />+ )}+ </div>++ {/* Event name or path */}+ <div className="min-w-0 max-w-[40%]">+ {isPageview ? (+ <Link href={fullPath} target="_blank" rel="noopener noreferrer">+ <div+ className="text-sm truncate hover:underline"+ title={event.pathname}+ >+ {truncatePath(+ `${event.pathname}${+ event.querystring ? `${event.querystring}` : ""+ }`+ )}+ </div>+ </Link>+ ) : (+ <div className="text-sm font-medium truncate">+ {event.event_name}+ </div>+ )}+ </div>++ {/* Device info */}+ <div className="flex-shrink-0 flex space-x-1 items-center">+ {event.country && (+ <Tooltip>+ <TooltipTrigger asChild>+ <div className="flex items-center">+ <CountryFlag country={event.country} />+ </div>+ </TooltipTrigger>+ <TooltipContent>+ <p>{getCountryName(event.country)}</p>+ </TooltipContent>+ </Tooltip>+ )}+ <Tooltip>+ <TooltipTrigger asChild>+ <div>+ <Browser browser={event.browser || "Unknown"} />+ </div>+ </TooltipTrigger>+ <TooltipContent>+ <p>{event.browser || "Unknown browser"}</p>+ </TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <div>+ <OperatingSystem os={event.operating_system || ""} />+ </div>+ </TooltipTrigger>+ <TooltipContent>+ <p>{event.operating_system || "Unknown OS"}</p>+ </TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <div>+ <DeviceIcon deviceType={event.device_type || ""} />+ </div>+ </TooltipTrigger>+ <TooltipContent>+ <p>{event.device_type || "Unknown device"}</p>+ </TooltipContent>+ </Tooltip>+ </div>++ {/* User ID */}+ <Link+ href={`/${site}/user/${event.user_id}`}+ className="flex-shrink-0"+ >+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="text-sm font-mono text-neutral-400 hover:text-neutral-300">+ {event.user_id.substring(0, 8)}+ </span>+ </TooltipTrigger>+ <TooltipContent>+ <p>View user profile</p>+ </TooltipContent>+ </Tooltip>+ </Link>+ </div>++ {/* Timestamp (right-aligned) */}+ <div className="text-sm flex-shrink-0 text-neutral-400 ml-auto">+ {eventTime.toRelative()}+ </div>+ </div>++ {/* Bottom row with event properties */}+ {Object.keys(eventProperties).length > 0 && (+ <div className="flex flex-wrap gap-1 mt-1 ml-6">+ {Object.entries(eventProperties).map(([key, value]) => (+ <Badge+ key={key}+ variant="outline"+ className="px-1.5 py-0 h-5 text-xs bg-neutral-800 text-neutral-100 font-medium"+ >+ <span className="text-neutral-300 font-light mr-1">{key}:</span>{" "}+ {String(value)}+ </Badge>+ ))}+ </div>+ )}+ </div>+ </div>+ );+}++export const EventLogItemSkeleton = memo(() => {+ // Function to get a random width class for skeletons+ const getRandomWidth = () => {+ const widths = ["w-16", "w-20", "w-24", "w-28", "w-32", "w-36", "w-40"];+ return widths[Math.floor(Math.random() * widths.length)];+ };++ return (+ <div className="mb-3 rounded-lg bg-neutral-850/50 border border-neutral-800 overflow-hidden p-3">+ <div className="flex flex-col space-y-2">+ {/* Single row skeleton */}+ <div className="flex items-center gap-2">+ {/* Left side content */}+ <div className="flex items-center gap-2 flex-grow">+ <div className="h-4 w-4 bg-neutral-800 rounded-sm animate-pulse flex-shrink-0"></div>+ <div+ className={`h-4 w-40 bg-neutral-800 rounded animate-pulse flex-shrink-0`}+ ></div>+ <div className="flex space-x-1 flex-shrink-0">+ <div className="h-4 w-4 bg-neutral-800 rounded-sm animate-pulse"></div>+ <div className="h-4 w-4 bg-neutral-800 rounded-sm animate-pulse"></div>+ <div className="h-4 w-4 bg-neutral-800 rounded-sm animate-pulse"></div>+ <div className="h-4 w-4 bg-neutral-800 rounded-sm animate-pulse"></div>+ </div>+ <div className="h-4 w-16 bg-neutral-800 rounded animate-pulse flex-shrink-0"></div>+ </div>++ {/* Timestamp (right-aligned) */}+ <div className="h-4 w-24 bg-neutral-800 rounded animate-pulse flex-shrink-0 ml-auto"></div>+ </div>++ {/* Bottom row skeleton (properties) - show randomly */}+ {Math.random() > 0.5 && (+ <div className="flex flex-wrap gap-1 mt-1 ml-6">+ {Array.from({ length: Math.floor(Math.random() * 4) + 1 }).map(+ (_, i) => (+ <div+ key={i}+ className="h-5 bg-neutral-800 rounded animate-pulse"+ style={{ width: `${Math.random() * 60 + 40}px` }}+ ></div>+ )+ )}+ </div>+ )}+ </div>+ </div>+ );+});diff --git a/client/src/app/[site]/events/components/EventProperties.tsx b/client/src/app/[site]/events/components/EventProperties.tsxnew file mode 100644index 000000000..1531edccd--- /dev/null+++ b/client/src/app/[site]/events/components/EventProperties.tsx@@ -0,0 +1,216 @@+"use client";++import { EventProperty } from "../../../../api/analytics/useGetEventProperties";+import NumberFlow from "@number-flow/react";+import { Info } from "lucide-react";+import { memo } from "react";++interface EventPropertiesProps {+ properties: EventProperty[];+ isLoading: boolean;+ selectedEvent: string | null;+ size?: "small" | "large";+}++export function EventProperties({+ properties,+ isLoading,+ selectedEvent,+ size = "small",+}: EventPropertiesProps) {+ if (isLoading) {+ return <EventPropertiesSkeleton size={size} />;+ }++ if (!selectedEvent) {+ return (+ <div className="text-neutral-300 w-full text-center py-8 flex flex-col gap-2 items-center justify-center">+ <Info className="w-6 h-6" />+ <p>Select an event to view its properties</p>+ </div>+ );+ }++ if (!properties || properties.length === 0) {+ return (+ <div className="text-neutral-300 w-full text-center py-8 flex flex-col gap-2 items-center justify-center">+ <Info className="w-6 h-6" />+ <p>No properties found for this event</p>+ </div>+ );+ }++ // Group properties by propertyKey+ const groupedProperties = properties.reduce((acc, property) => {+ if (!acc[property.propertyKey]) {+ acc[property.propertyKey] = [];+ }+ acc[property.propertyKey].push(property);+ return acc;+ }, {} as Record<string, EventProperty[]>);++ // Sort keys by the total count of their values+ const sortedKeys = Object.keys(groupedProperties).sort((a, b) => {+ const sumA = groupedProperties[a].reduce(+ (sum, prop) => sum + prop.count,+ 0+ );+ const sumB = groupedProperties[b].reduce(+ (sum, prop) => sum + prop.count,+ 0+ );+ return sumB - sumA;+ });++ // Find the highest count to calculate percentages for values+ const maxCount = Math.max(...properties.map((prop) => prop.count));++ return (+ <div+ className={`flex flex-col gap-4 ${+ size === "small" ? "max-h-[30vh]" : "max-h-[60vh]"+ } overflow-y-auto pr-2`}+ >+ {sortedKeys.map((key) => {+ // Sort property values by count (descending)+ const values = groupedProperties[key].sort((a, b) => b.count - a.count);++ return (+ <div+ key={key}+ className={`flex flex-col gap-1 ${+ size === "small" ? "text-xs" : "text-sm"+ }`}+ >+ {/* Property Key Header */}+ <div className="font-semibold text-primary py-1 border-b border-neutral-800">+ {key}+ </div>++ {/* Property Values */}+ <div className="pl-4 flex flex-col gap-2">+ {values.map((property) => {+ const percentage = (property.count / maxCount) * 100;++ return (+ <div+ key={`${property.propertyKey}-${property.propertyValue}`}+ className={`relative ${+ size === "small" ? "h-6" : "h-8"+ } flex items-center hover:bg-neutral-850 group px-2 rounded-md`}+ >+ <div+ className="absolute inset-0 bg-dataviz py-2 opacity-25 rounded-md"+ style={{ width: `${percentage}%` }}+ ></div>+ <div className="z-10 flex justify-between items-center w-full">+ <div className="truncate max-w-[70%]">+ {property.propertyValue}+ </div>+ <div className="flex gap-2">+ <div className="hidden group-hover:block text-neutral-400">+ {Math.round(percentage * 10) / 10}%+ </div>+ <NumberFlow+ respectMotionPreference={false}+ value={property.count}+ format={{ notation: "compact" }}+ />+ </div>+ </div>+ </div>+ );+ })}+ </div>+ </div>+ );+ })}+ </div>+ );+}++// Skeleton component for EventProperties+const EventPropertiesSkeleton = memo(+ ({ size = "small" }: { size?: "small" | "large" }) => {+ // Generate random number of property groups (2-4)+ const groupCount = 2 + Math.floor(Math.random() * 3);++ // Generate random number of properties per group (2-5)+ const propertyCounts = Array.from(+ { length: groupCount },+ () => 2 + Math.floor(Math.random() * 4)+ );++ // Generate random widths for property values+ const generateWidths = (count: number) =>+ Array.from({ length: count }, () => 20 + Math.random() * 80);++ // Generate random widths for property bars+ const generateBarWidths = (count: number) =>+ Array.from({ length: count }, () => 20 + Math.random() * 80);++ return (+ <div+ className={`flex flex-col gap-4 ${+ size === "small" ? "max-h-[30vh]" : "max-h-[60vh]"+ } overflow-y-auto pr-2`}+ >+ {Array.from({ length: groupCount }).map((_, groupIndex) => (+ <div+ key={groupIndex}+ className={`flex flex-col gap-1 ${+ size === "small" ? "text-xs" : "text-sm"+ }`}+ >+ {/* Property Key Header Skeleton */}+ <div className="font-semibold py-1 border-b border-neutral-800">+ <div className="h-4 bg-neutral-800 rounded animate-pulse w-24"></div>+ </div>++ {/* Property Values Skeleton */}+ <div className="pl-4 flex flex-col gap-2">+ {Array.from({ length: propertyCounts[groupIndex] }).map(+ (_, propIndex) => {+ const valueWidths = generateWidths(+ propertyCounts[groupIndex]+ );+ const barWidths = generateBarWidths(+ propertyCounts[groupIndex]+ );++ return (+ <div+ key={propIndex}+ className={`relative ${+ size === "small" ? "h-6" : "h-8"+ } flex items-center px-2 rounded-md`}+ >+ <div+ className="absolute inset-0 bg-neutral-800 py-2 opacity-25 rounded-md animate-pulse"+ style={{ width: `${barWidths[propIndex]}%` }}+ ></div>+ <div className="z-10 flex justify-between items-center w-full">+ <div className="truncate max-w-[70%]">+ <div+ className="h-4 bg-neutral-800 rounded animate-pulse"+ style={{ width: `${valueWidths[propIndex]}px` }}+ ></div>+ </div>+ <div className="flex gap-2">+ <div+ className="h-4 bg-neutral-800 rounded animate-pulse"+ style={{ width: "40px" }}+ ></div>+ </div>+ </div>+ </div>+ );+ }+ )}+ </div>+ </div>+ ))}+ </div>+ );+ }+);diff --git a/client/src/app/[site]/events/page.tsx b/client/src/app/[site]/events/page.tsxnew file mode 100644index 000000000..27768234e--- /dev/null+++ b/client/src/app/[site]/events/page.tsx@@ -0,0 +1,41 @@+"use client";++import { EVENT_FILTERS } from "@/lib/store";+import { useGetEventNames } from "../../../api/analytics/useGetEventNames";+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";+import { EventList } from "./components/EventList";+import { EventLog } from "./components/EventLog";+import { SubHeader } from "../components/SubHeader/SubHeader";++export default function EventsPage() {+ const { data: eventNamesData, isLoading: isLoadingEventNames } =+ useGetEventNames();++ return (+ <div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3">+ <SubHeader availableFilters={EVENT_FILTERS} />++ <Card>+ <CardHeader>+ <CardTitle>Custom Events</CardTitle>+ </CardHeader>+ <CardContent>+ <EventList+ events={eventNamesData || []}+ isLoading={isLoadingEventNames}+ size="large"+ />+ </CardContent>+ </Card>++ <Card>+ <CardHeader>+ <CardTitle>Event Log</CardTitle>+ </CardHeader>+ <CardContent>+ <EventLog />+ </CardContent>+ </Card>+ </div>+ );+}diff --git a/client/src/app/[site]/main/components/sections/Countries.tsx b/client/src/app/[site]/main/components/sections/Countries.tsxindex 52d976e9d..bb48193b4 100644--- a/client/src/app/[site]/main/components/sections/Countries.tsx+++ b/client/src/app/[site]/main/components/sections/Countries.tsx@@ -12,7 +12,6 @@ import { getCountryName, getLanguageName } from "../../../../../lib/utils";import { StandardSection } from "../../../components/shared/StandardSection/StandardSection";import { CountryFlag } from "../../../components/shared/icons/CountryFlag";import { useSubdivisions } from "../../../../../lib/geo";-import { StandardSectionRealtime } from "../../../components/shared/StandardSection/StandardSectionRealtime";import { MapComponent } from "../../../components/shared/Map";type Tab = "countries" | "regions" | "languages" | "cities" | "map";@@ -26,13 +25,11 @@ const getCountryFromLanguage = (languageCode: string): string | null => {return null;};-export function Countries({ isRealtime = false }: { isRealtime?: boolean }) {+export function Countries() {const [tab, setTab] = useState<Tab>("countries");const { data: subdivisions } = useSubdivisions();- const ComponentToUse = isRealtime ? StandardSectionRealtime : StandardSection;-return (<Card className=""><CardContent className="mt-2">@@ -49,7 +46,7 @@ export function Countries({ isRealtime = false }: { isRealtime?: boolean }) {<TabsTrigger value="map">Map</TabsTrigger></TabsList><TabsContent value="countries">- <ComponentToUse+ <StandardSectionfilterParameter="country"title="Countries"getValue={(e) => e.value}@@ -66,7 +63,7 @@ export function Countries({ isRealtime = false }: { isRealtime?: boolean }) {/></TabsContent><TabsContent value="regions">- <ComponentToUse+ <StandardSectionfilterParameter="region"title="Regions"getValue={(e) => e.value}@@ -100,7 +97,7 @@ export function Countries({ isRealtime = false }: { isRealtime?: boolean }) {/></TabsContent><TabsContent value="cities">- <ComponentToUse+ <StandardSectionfilterParameter="city"title="Cities"getValue={(e) => e.value}@@ -114,7 +111,7 @@ export function Countries({ isRealtime = false }: { isRealtime?: boolean }) {/></TabsContent><TabsContent value="languages">- <ComponentToUse+ <StandardSectionfilterParameter="language"title="Languages"getValue={(e) => e.value}diff --git a/client/src/app/[site]/main/components/sections/Events.tsx b/client/src/app/[site]/main/components/sections/Events.tsxindex 34708eaaf..f2838aeb0 100644--- a/client/src/app/[site]/main/components/sections/Events.tsx+++ b/client/src/app/[site]/main/components/sections/Events.tsx@@ -5,16 +5,20 @@ import {TabsList,TabsTrigger,} from "../../../../../components/ui/basic-tabs";-import { Card, CardContent } from "../../../../../components/ui/card";-import { StandardSection } from "../../../components/shared/StandardSection/StandardSection";-import { StandardSectionRealtime } from "../../../components/shared/StandardSection/StandardSectionRealtime";+import {+ Card,+ CardContent,+ CardLoader,+} from "../../../../../components/ui/card";+import { useGetEventNames } from "../../../../../api/analytics/useGetEventNames";+import { EventList } from "../../../events/components/EventList";type Tab = "events";-export function Events({ isRealtime = false }: { isRealtime?: boolean }) {+export function Events() {const [tab, setTab] = useState<Tab>("events");-- const ComponentToUse = isRealtime ? StandardSectionRealtime : StandardSection;+ const { data: eventNamesData, isLoading: isLoadingEventNames } =+ useGetEventNames();return (<Card>@@ -28,14 +32,21 @@ export function Events({ isRealtime = false }: { isRealtime?: boolean }) {<TabsTrigger value="events">Custom Events</TabsTrigger></TabsList><TabsContent value="events">- <ComponentToUse- filterParameter="event_name"- title="Events"- countLabel="Count"- getValue={(e) => e.value}- getKey={(e) => e.value}- getLabel={(e) => e.value}- />+ {isLoadingEventNames && (+ <div className="absolute top-[-8px] left-0 w-full h-full">+ <CardLoader />+ </div>+ )}+ <div className="relative">+ <div className="flex flex-row gap-2 justify-between pr-1 text-xs text-neutral-400 mb-2">+ <div>Custom Events</div>+ <div>Count</div>+ </div>+ <EventList+ events={eventNamesData || []}+ isLoading={isLoadingEventNames}+ />+ </div></TabsContent></Tabs></CardContent>diff --git a/client/src/app/[site]/main/components/sections/Pages.tsx b/client/src/app/[site]/main/components/sections/Pages.tsxindex 10aa87fe4..aa5375ded 100644--- a/client/src/app/[site]/main/components/sections/Pages.tsx+++ b/client/src/app/[site]/main/components/sections/Pages.tsx@@ -9,17 +9,14 @@ import {} from "../../../../../components/ui/basic-tabs";import { Card, CardContent } from "../../../../../components/ui/card";import { StandardSection } from "../../../components/shared/StandardSection/StandardSection";-import { StandardSectionRealtime } from "../../../components/shared/StandardSection/StandardSectionRealtime";import { useGetSite } from "../../../../../api/admin/sites";import { truncateString } from "../../../../../lib/utils";type Tab = "pages" | "entry_pages" | "exit_pages";-export function Pages({ isRealtime = false }: { isRealtime?: boolean }) {+export function Pages() {const { data: siteMetadata } = useGetSite();const [tab, setTab] = useState<Tab>("pages");- const ComponentToUse = isRealtime ? StandardSectionRealtime : StandardSection;-return (<Card className="h-[445px]"><CardContent className="mt-2">@@ -34,7 +31,7 @@ export function Pages({ isRealtime = false }: { isRealtime?: boolean }) {<TabsTrigger value="exit_pages">Exit Pages</TabsTrigger></TabsList><TabsContent value="pages">- <ComponentToUse+ <StandardSectionfilterParameter="pathname"title="Pages"getValue={(e) => e.value}@@ -44,7 +41,7 @@ export function Pages({ isRealtime = false }: { isRealtime?: boolean }) {/></TabsContent><TabsContent value="entry_pages">- <ComponentToUse+ <StandardSectionfilterParameter="entry_page"title="Entry Pages"getValue={(e) => e.value}@@ -54,7 +51,7 @@ export function Pages({ isRealtime = false }: { isRealtime?: boolean }) {/></TabsContent><TabsContent value="exit_pages">- <ComponentToUse+ <StandardSectionfilterParameter="exit_page"title="Exit Pages"getValue={(e) => e.value}diff --git a/client/src/app/[site]/main/components/sections/Referrers.tsx b/client/src/app/[site]/main/components/sections/Referrers.tsxindex c2e1fe84c..a63359f19 100644--- a/client/src/app/[site]/main/components/sections/Referrers.tsx+++ b/client/src/app/[site]/main/components/sections/Referrers.tsx@@ -8,7 +8,6 @@ import {} from "../../../../../components/ui/basic-tabs";import { Card, CardContent } from "../../../../../components/ui/card";import { StandardSection } from "../../../components/shared/StandardSection/StandardSection";-import { StandardSectionRealtime } from "../../../components/shared/StandardSection/StandardSectionRealtime";type Tab =| "referrers"@@ -19,11 +18,9 @@ type Tab =| "utm_term"| "utm_content";-export function Referrers({ isRealtime = false }: { isRealtime?: boolean }) {+export function Referrers() {const [tab, setTab] = useState<Tab>("referrers");- const ComponentToUse = isRealtime ? StandardSectionRealtime : StandardSection;-return (<Card className="h-[445px]"><CardContent className="mt-2">@@ -42,7 +39,7 @@ export function Referrers({ isRealtime = false }: { isRealtime?: boolean }) {<TabsTrigger value="utm_content">Content</TabsTrigger></TabsList><TabsContent value="referrers">- <ComponentToUse+ <StandardSectionfilterParameter="referrer"title="Referrers"getValue={(e) => e.value}@@ -60,7 +57,7 @@ export function Referrers({ isRealtime = false }: { isRealtime?: boolean }) {/></TabsContent><TabsContent value="channels">- <ComponentToUse+ <StandardSectionfilterParameter="channel"title="Channels"getValue={(e) => e.value}@@ -72,7 +69,7 @@ export function Referrers({ isRealtime = false }: { isRealtime?: boolean }) {/></TabsContent><TabsContent value="utm_source">- <ComponentToUse+ <StandardSectionfilterParameter="utm_source"title="UTM Source"getKey={(e) => e.value}@@ -81,7 +78,7 @@ export function Referrers({ isRealtime = false }: { isRealtime?: boolean }) {/></TabsContent><TabsContent value="utm_medium">- <ComponentToUse+ <StandardSectionfilterParameter="utm_medium"title="UTM Medium"getKey={(e) => e.value}@@ -90,7 +87,7 @@ export function Referrers({ isRealtime = false }: { isRealtime?: boolean }) {/></TabsContent><TabsContent value="utm_campaign">- <ComponentToUse+ <StandardSectionfilterParameter="utm_campaign"title="UTM Campaign"getKey={(e) => e.value}@@ -99,7 +96,7 @@ export function Referrers({ isRealtime = false }: { isRealtime?: boolean }) {/></TabsContent><TabsContent value="utm_content">- <ComponentToUse+ <StandardSectionfilterParameter="utm_content"title="UTM Content"getKey={(e) => e.value}@@ -108,7 +105,7 @@ export function Referrers({ isRealtime = false }: { isRealtime?: boolean }) {/></TabsContent><TabsContent value="utm_term">- <ComponentToUse+ <StandardSectionfilterParameter="utm_term"title="UTM Term"getKey={(e) => e.value}diff --git a/client/src/lib/store.ts b/client/src/lib/store.tsindex 2d301a722..055314399 100644--- a/client/src/lib/store.ts+++ b/client/src/lib/store.ts@@ -67,6 +67,37 @@ export const SESSION_PAGE_FILTERS: FilterParameter[] = ["utm_content",];+export const EVENT_FILTERS: FilterParameter[] = [+ // "event_name",+ // "browser",+ // "operating_system",+ // "country",+ // "device_type",+ // "referrer",++ "browser",+ "operating_system",+ "language",+ "country",+ "region",+ "city",+ "device_type",+ "referrer",+ "pathname",+ "page_title",+ "querystring",+ "event_name",+ "channel",+ "utm_source",+ "utm_medium",+ "utm_campaign",+ "utm_term",+ "utm_content",+ "entry_page",+ "exit_page",+ "dimensions",+];+export const GOALS_PAGE_FILTERS: FilterParameter[] = ["browser","operating_system",diff --git a/server/src/api/analytics/getEventNames.ts b/server/src/api/analytics/getEventNames.tsnew file mode 100644index 000000000..4572a12d0--- /dev/null+++ b/server/src/api/analytics/getEventNames.ts@@ -0,0 +1,77 @@+import { FastifyReply, FastifyRequest } from "fastify";+import clickhouse from "../../db/clickhouse/clickhouse.js";+import {+ getTimeStatement,+ processResults,+ getFilterStatement,+} from "./utils.js";+import { getUserHasAccessToSitePublic } from "../../lib/auth-utils.js";++export type GetEventNamesResponse = {+ eventName: string;+ count: number;+}[];++export interface GetEventNamesRequest {+ Params: {+ site: string;+ };+ Querystring: {+ startDate: string;+ endDate: string;+ timezone: string;+ filters?: string;+ };+}++export async function getEventNames(+ req: FastifyRequest<GetEventNamesRequest>,+ res: FastifyReply+) {+ const { startDate, endDate, timezone, filters } = req.query;+ const site = req.params.site;+ const userHasAccessToSite = await getUserHasAccessToSitePublic(req, site);+ if (!userHasAccessToSite) {+ return res.status(403).send({ error: "Forbidden" });+ }++ const timeStatement = getTimeStatement({+ date: { startDate, endDate, timezone },+ });++ const filterStatement = filters ? getFilterStatement(filters) : "";++ const query = `+ SELECT+ event_name AS eventName,+ count() AS count+ FROM events+ WHERE+ site_id = {siteId:Int32}+ AND type = 'custom_event'+ AND event_name IS NOT NULL+ AND event_name != ''+ ${timeStatement}+ ${filterStatement}+ GROUP BY event_name+ ORDER BY count DESC+ LIMIT 1000+ `;++ try {+ const result = await clickhouse.query({+ query,+ format: "JSONEachRow",+ query_params: {+ siteId: Number(site),+ },+ });++ const data = await processResults<GetEventNamesResponse[number]>(result);+ return res.send({ data });+ } catch (error) {+ console.error("Generated Query:", query);+ console.error("Error fetching event names:", error);+ return res.status(500).send({ error: "Failed to fetch event names" });+ }+}diff --git a/server/src/api/analytics/getEventProperties.ts b/server/src/api/analytics/getEventProperties.tsnew file mode 100644index 000000000..8e1c2243a--- /dev/null+++ b/server/src/api/analytics/getEventProperties.ts@@ -0,0 +1,88 @@+import { FastifyReply, FastifyRequest } from "fastify";+import clickhouse from "../../db/clickhouse/clickhouse.js";+import {+ getTimeStatement,+ processResults,+ getFilterStatement,+} from "./utils.js";+import { getUserHasAccessToSitePublic } from "../../lib/auth-utils.js";++export type GetEventPropertiesResponse = {+ propertyKey: string;+ propertyValue: string;+ count: number;+}[];++export interface GetEventPropertiesRequest {+ Params: {+ site: string;+ };+ Querystring: {+ startDate: string;+ endDate: string;+ timezone: string;+ eventName: string;+ filters?: string;+ };+}++export async function getEventProperties(+ req: FastifyRequest<GetEventPropertiesRequest>,+ res: FastifyReply+) {+ const { startDate, endDate, timezone, eventName, filters } = req.query;+ const site = req.params.site;+ const userHasAccessToSite = await getUserHasAccessToSitePublic(req, site);+ if (!userHasAccessToSite) {+ return res.status(403).send({ error: "Forbidden" });+ }++ if (!eventName) {+ return res.status(400).send({ error: "Event name is required" });+ }++ const timeStatement = getTimeStatement({+ date: { startDate, endDate, timezone },+ });++ const filterStatement = filters ? getFilterStatement(filters) : "";++ const query = `+ SELECT+ kv.1 AS propertyKey, -- Access tuple elements+ replaceRegexpAll(kv.2, '^"|"$', '') AS propertyValue, -- Remove surrounding quotes if they exist+ count() AS count+ FROM events+ ARRAY JOIN JSONExtractKeysAndValuesRaw(CAST(props AS String)) AS kv -- Alias the tuple elements directly+ WHERE+ site_id = {siteId:Int32}+ AND type = 'custom_event'+ AND event_name = {eventName:String}+ AND props != '{}' -- Check if the JSON object is not empty+ ${timeStatement}+ ${filterStatement}+ GROUP BY propertyKey, propertyValue+ ORDER BY propertyKey ASC, count DESC+ LIMIT 500+ `;++ try {+ const result = await clickhouse.query({+ query,+ format: "JSONEachRow",+ query_params: {+ siteId: Number(site),+ eventName,+ },+ });++ const data = await processResults<GetEventPropertiesResponse[number]>(+ result+ );+ return res.send({ data });+ } catch (error) {+ console.error("Generated Query:", query);+ console.error("Error fetching event properties:", error);+ return res.status(500).send({ error: "Failed to fetch event properties" });+ }+}diff --git a/server/src/api/analytics/getEvents.ts b/server/src/api/analytics/getEvents.tsindex b55665b55..dea4611b0 100644--- a/server/src/api/analytics/getEvents.ts+++ b/server/src/api/analytics/getEvents.ts@@ -1,12 +1,16 @@import { FastifyReply, FastifyRequest } from "fastify";import clickhouse from "../../db/clickhouse/clickhouse.js";-import { processResults } from "./utils.js";+import {+ processResults,+ getTimeStatement,+ getFilterStatement,+} from "./utils.js";import { getUserHasAccessToSitePublic } from "../../lib/auth-utils.js";export type GetEventsResponse = {timestamp: string;event_name: string;- properties: string;+ properties: string; // This will be populated from the props columnuser_id: string;pathname: string;querystring: string;@@ -25,7 +29,13 @@ interface GetEventsRequest {site: string;};Querystring: {- count?: string;+ startDate?: string;+ endDate?: string;+ timezone?: string;+ filters?: string;+ page?: string;+ pageSize?: string;+ count?: string; // Keeping for backward compatibility};}@@ -34,51 +44,107 @@ export async function getEvents(res: FastifyReply) {const { site } = req.params;- const { count = "10" } = req.query;+ const {+ startDate,+ endDate,+ timezone,+ filters,+ page = "1",+ pageSize = "20",+ count,+ } = req.query;const userHasAccessToSite = await getUserHasAccessToSitePublic(req, site);if (!userHasAccessToSite) {return res.status(403).send({ error: "Forbidden" });}- const limitCount = parseInt(count, 10);+ // Use count if provided (for backward compatibility), otherwise use pageSize+ const limit = count ? parseInt(count, 10) : parseInt(pageSize, 10);+ const offset = (parseInt(page, 10) - 1) * limit;++ // Get time and filter statements if parameters are provided+ const timeStatement =+ startDate || endDate+ ? getTimeStatement({ date: { startDate, endDate, timezone } })+ : "AND timestamp > now() - INTERVAL 30 MINUTE"; // Default to last 30 minutes if no time range specified++ const filterStatement = filters ? getFilterStatement(filters) : "";try {- const query = await clickhouse.query({- query: `- SELECT- timestamp,- event_name,- properties,- user_id,- pathname,- querystring,- hostname,- page_title,- referrer,- browser,- operating_system,- country,- device_type,- type- FROM events- WHERE- site_id = {siteId:Int32}- AND (type = 'custom_event' OR type = 'pageview')- AND timestamp > now() - INTERVAL 30 MINUTE- ORDER BY timestamp DESC- LIMIT {limit:Int32}- `,+ // First, get the total count for pagination metadata+ const countQuery = `+ SELECT+ COUNT(*) as total+ FROM events+ WHERE+ site_id = {siteId:Int32}+ AND (type = 'custom_event' OR type = 'pageview')+ ${timeStatement}+ ${filterStatement}+ `;++ const countResult = await clickhouse.query({+ query: countQuery,format: "JSONEachRow",query_params: {siteId: Number(site),- limit: Number(limitCount),},});- const events = await processResults<GetEventsResponse[number]>(query);+ const countData = await processResults<{ total: number }>(countResult);+ const totalCount = countData[0]?.total || 0;++ // Then, get the actual events with pagination+ const eventsQuery = `+ SELECT+ timestamp,+ event_name,+ toString(props) as properties, -- Convert props Map to string+ user_id,+ pathname,+ querystring,+ hostname,+ page_title,+ referrer,+ browser,+ operating_system,+ country,+ device_type,+ type+ FROM events+ WHERE+ site_id = {siteId:Int32}+ AND (type = 'custom_event' OR type = 'pageview')+ ${timeStatement}+ ${filterStatement}+ ORDER BY timestamp DESC+ LIMIT {limit:Int32} OFFSET {offset:Int32}+ `;- return res.send({ data: events });+ const eventsResult = await clickhouse.query({+ query: eventsQuery,+ format: "JSONEachRow",+ query_params: {+ siteId: Number(site),+ limit: Number(limit),+ offset: Number(offset),+ },+ });++ const events = await processResults<GetEventsResponse[number]>(+ eventsResult+ );++ return res.send({+ data: events,+ pagination: {+ total: totalCount,+ page: parseInt(page, 10),+ pageSize: limit,+ totalPages: Math.ceil(totalCount / limit),+ },+ });} catch (error) {console.error("Error fetching events:", error);return res.status(500).send({ error: "Failed to fetch events" });diff --git a/server/src/api/analytics/utils.ts b/server/src/api/analytics/utils.tsindex 064e561f4..cb30a852b 100644--- a/server/src/api/analytics/utils.ts+++ b/server/src/api/analytics/utils.ts@@ -14,7 +14,7 @@ export function getTimeStatement({date?: {startDate?: string;endDate?: string;- timezone: string;+ timezone?: string;table?: "events" | "sessions";};pastMinutes?: number;diff --git a/server/src/index.ts b/server/src/index.tsindex 94964026e..2e43a88f1 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -9,6 +9,8 @@ import { createFunnel } from "./api/analytics/createFunnel.js";import { createGoal } from "./api/analytics/createGoal.js";import { deleteGoal } from "./api/analytics/deleteGoal.js";import { deleteFunnel } from "./api/analytics/deleteFunnel.js";+import { getEventNames } from "./api/analytics/getEventNames.js";+import { getEventProperties } from "./api/analytics/getEventProperties.js";import { getEvents } from "./api/analytics/getEvents.js";import { getFunnel } from "./api/analytics/getFunnel.js";import { getFunnels } from "./api/analytics/getFunnels.js";@@ -143,6 +145,9 @@ const ANALYTICS_ROUTES = ["/journeys/","/goals/","/goal/",+ "/api/analytics/events/names/",+ "/api/analytics/events/properties/",+ "/events/","/get-site",];@@ -201,7 +206,8 @@ server.get("/site-has-data/:site", getSiteHasData);server.get("/site-is-public/:site", getSiteIsPublic);server.get("/sessions/:site", getSessions);server.get("/session/:sessionId/:site", getSession);-server.get("/recent-events/:site", getEvents);+server.get("/recent-events/:site", getEvents); // Legacy endpoint for backward compatibility+server.get("/events/:site", getEvents); // New endpoint with filtering and paginationserver.get("/users/:site", getUsers);server.get("/user/:userId/sessions/:site", getUserSessions);server.get("/user/session-count/:site", getUserSessionCount);@@ -217,6 +223,8 @@ server.get("/goal/:goalId/:site", getGoal);server.post("/goal/create", createGoal);server.delete("/goal/:goalId", deleteGoal);server.put("/goal/update", updateGoal);+server.get("/events/names/:site", getEventNames);+server.get("/events/properties/:site", getEventProperties);// Administrativeserver.post("/add-site", addSite);