Skip to content

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

Enhance analytics API and RealtimePage with city data and real-time querying

Bill Yang6991800ac8fc
diff --git a/client/src/api/analytics/useGetLiveSessionLocations.ts b/client/src/api/analytics/useGetLiveSessionLocations.ts
index 6c8dd8d7b..fd8bf6aac 100644
--- a/client/src/api/analytics/useGetLiveSessionLocations.ts
+++ b/client/src/api/analytics/useGetLiveSessionLocations.ts
@@ -7,6 +7,7 @@ export type LiveSessionLocation = {
lat: number;
lon: number;
count: number;
+ city: string;
};
export function useGetLiveSessionLocations() {
diff --git a/client/src/api/analytics/useSingleCol.ts b/client/src/api/analytics/useSingleCol.ts
index 3875c45c8..494c3ed20 100644
--- a/client/src/api/analytics/useSingleCol.ts
+++ b/client/src/api/analytics/useSingleCol.ts
@@ -56,3 +56,40 @@ export function useSingleCol({
},
});
}
+
+export function useSingleColRealtime({
+ parameter,
+ limit = 1000,
+ minutes = 30,
+}: {
+ parameter: FilterParameter;
+ limit?: number;
+ minutes?: number;
+}): UseQueryResult<APIResponse<SingleColResponse[]>> {
+ const { time, previousTime, site, filters } = useStore();
+
+ return useQuery({
+ queryKey: [parameter, site, limit, minutes],
+ queryFn: () => {
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+ return authedFetch(`${BACKEND_URL}/single-col`, {
+ timezone,
+ site,
+ parameter,
+ limit,
+ minutes,
+ }).then((res) => res.json());
+ },
+ staleTime: Infinity,
+ placeholderData: (_, query: any) => {
+ if (!query?.queryKey) return undefined;
+ const prevQueryKey = query.queryKey as [string, string, string];
+ const [, , prevSite] = prevQueryKey;
+
+ if (prevSite === site) {
+ return query.state.data;
+ }
+ return undefined;
+ },
+ });
+}
diff --git a/client/src/app/[site]/components/shared/StandardSection/StandardSectionRealtime.tsx b/client/src/app/[site]/components/shared/StandardSection/StandardSectionRealtime.tsx
new file mode 100644
index 000000000..3489d503f
--- /dev/null
+++ b/client/src/app/[site]/components/shared/StandardSection/StandardSectionRealtime.tsx
@@ -0,0 +1,229 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { round } from "lodash";
+import { AlertCircle, RefreshCcw, SquareArrowOutUpRight } from "lucide-react";
+import { ReactNode, useMemo } from "react";
+import {
+ SingleColResponse,
+ useSingleCol,
+ useSingleColRealtime,
+} from "../../../../../api/analytics/useSingleCol";
+import { addFilter, FilterParameter } from "../../../../../lib/store";
+import { formatter } from "../../../../../lib/utils";
+import { Skeleton } from "./Skeleton";
+
+const Row = ({
+ e,
+ ratio,
+ getKey,
+ getLabel,
+ getValue,
+ getLink,
+ filterParameter,
+}: {
+ e: SingleColResponse;
+ ratio: number;
+ getKey: (item: SingleColResponse) => string;
+ getLabel: (item: SingleColResponse) => ReactNode;
+ getValue: (item: SingleColResponse) => string;
+ getLink?: (item: SingleColResponse) => string;
+ filterParameter: FilterParameter;
+}) => {
+ return (
+ <div
+ key={getKey(e)}
+ className="relative h-7 flex items-center cursor-pointer hover:bg-neutral-850 group"
+ onClick={() =>
+ addFilter({
+ parameter: filterParameter,
+ value: [getValue(e)],
+ type: "equals",
+ })
+ }
+ >
+ <div
+ className="absolute inset-0 bg-accent-400 py-2 opacity-30 rounded-md"
+ style={{ width: `${e.percentage * ratio}%` }}
+ ></div>
+ <div className="z-10 mx-2 flex justify-between items-center text-sm w-full">
+ <div className="flex items-center gap-1">
+ {getLabel(e)}
+ {getLink && (
+ <a
+ href={getLink(e)}
+ target="_blank"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <SquareArrowOutUpRight
+ className="w-3 h-3 text-neutral-300 hover:text-neutral-100"
+ strokeWidth={3}
+ />
+ </a>
+ )}
+ </div>
+ <div className="text-sm flex gap-2">
+ <div className="hidden group-hover:block text-neutral-400">
+ {round(e.percentage, 1)}%
+ </div>
+ <div>{formatter(e.count)}</div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+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,
+ });
+
+ // Determine if we're in a loading state
+ const isLoading = isFetching;
+
+ const ratio = data?.data?.[0]?.percentage
+ ? 100 / data?.data?.[0]?.percentage
+ : 1;
+
+ const hasError = error;
+ const errorMessage =
+ error?.message || "An error occurred while fetching data";
+
+ return (
+ <div className="flex flex-col gap-2">
+ {isLoading ? (
+ <Skeleton />
+ ) : hasError ? (
+ <div className="py-6 flex-1 flex flex-col items-center justify-center gap-3 transition-all">
+ <AlertCircle className="text-amber-400 w-8 h-8" />
+ <div className="text-center">
+ <div className="text-neutral-100 font-medium mb-1">
+ Failed to load data
+ </div>
+ <div className="text-sm text-neutral-400 max-w-md mx-auto mb-3">
+ {errorMessage}
+ </div>
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ className="bg-transparent hover:bg-neutral-800 border-neutral-700 text-neutral-300 hover:text-neutral-100"
+ onClick={() => refetch()}
+ >
+ <RefreshCcw className="w-3 h-3" /> Try Again
+ </Button>
+ </div>
+ ) : (
+ <>
+ <div className="flex flex-row gap-2 justify-between pr-1 text-xs text-neutral-400">
+ <div>{title}</div>
+ <div>{countLabel || "Sessions"}</div>
+ </div>
+ {data?.data?.slice(0, 10).map((e) => (
+ <Row
+ key={getKey(e)}
+ e={e}
+ ratio={ratio}
+ getKey={getKey}
+ getLabel={getLabel}
+ getValue={getValue}
+ getLink={getLink}
+ filterParameter={filterParameter}
+ />
+ ))}
+ </>
+ )}
+ {isLoading ? (
+ // Skeleton for "View All" button when loading
+ <Button variant="outline" disabled className="opacity-50">
+ View All
+ </Button>
+ ) : !hasError && data?.data?.length && data?.data?.length > 10 ? (
+ <Dialog>
+ <DialogTrigger asChild>
+ <Button variant="outline">View All</Button>
+ </DialogTrigger>
+ <DialogContent className="max-w-[90vw] w-[1000px]">
+ <DialogHeader>
+ <DialogTitle>{title}</DialogTitle>
+ </DialogHeader>
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-row gap-2 justify-between pr-20 text-sm text-neutral-400">
+ <div>{title}</div>
+ <div>{countLabel || "Sessions"}</div>
+ </div>
+ <div className="flex flex-col gap-2 max-h-[85vh] overflow-x-hidden">
+ {data?.data?.map((e) => (
+ <div
+ key={getKey(e)}
+ className="relative flex items-center mr-3 cursor-pointer hover:bg-neutral-850"
+ onClick={() =>
+ addFilter({
+ parameter: filterParameter,
+ value: [getValue(e)],
+ type: "equals",
+ })
+ }
+ >
+ <div
+ className="absolute inset-0 bg-accent-400 py-2 opacity-30 rounded-md"
+ style={{ width: `${e.percentage * ratio}%` }}
+ ></div>
+ <div className="z-10 ml-2 mr-4 flex justify-between items-center text-sm w-full h-7">
+ <div className="flex items-center gap-1">
+ {getLabel(e)}
+ {getLink && (
+ <a
+ href={getLink(e)}
+ target="_blank"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <SquareArrowOutUpRight
+ className="w-3 h-3 text-neutral-300 hover:text-neutral-100"
+ strokeWidth={3}
+ />
+ </a>
+ )}
+ </div>
+ <div className="text-sm flex">
+ <div>{e.count.toLocaleString()}</div>
+ <div className="mx-2 bg-neutral-400 w-[1px] rounded-full h-5"></div>
+ <div className="w-10 text-neutral-400">
+ {round(e.percentage, 2)}%
+ </div>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ ) : null}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/main/components/sections/Countries.tsx b/client/src/app/[site]/main/components/sections/Countries.tsx
index b06b6abad..25a0f29c4 100644
--- a/client/src/app/[site]/main/components/sections/Countries.tsx
+++ b/client/src/app/[site]/main/components/sections/Countries.tsx
@@ -12,6 +12,7 @@ import { getCountryName } 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";
type Tab = "countries" | "regions" | "languages";
@@ -45,11 +46,13 @@ const getCountryFromLanguage = (languageCode: string): string | null => {
return null;
};
-export function Countries() {
+export function Countries({ isRealtime = false }: { isRealtime?: boolean }) {
const [tab, setTab] = useState<Tab>("countries");
const { data: subdivisions } = useSubdivisions();
+ const ComponentToUse = isRealtime ? StandardSectionRealtime : StandardSection;
+
return (
<Card className="">
<CardContent className="mt-2">
@@ -64,7 +67,7 @@ export function Countries() {
<TabsTrigger value="languages">Languages</TabsTrigger>
</TabsList>
<TabsContent value="countries">
- <StandardSection
+ <ComponentToUse
filterParameter="country"
title="Countries"
getValue={(e) => e.value}
@@ -80,7 +83,7 @@ export function Countries() {
/>
</TabsContent>
<TabsContent value="regions">
- <StandardSection
+ <ComponentToUse
filterParameter="iso_3166_2"
title="Regions"
getValue={(e) => e.value}
@@ -108,7 +111,7 @@ export function Countries() {
/>
</TabsContent>
<TabsContent value="languages">
- <StandardSection
+ <ComponentToUse
filterParameter="language"
title="Languages"
getValue={(e) => e.value}
diff --git a/client/src/app/[site]/main/components/sections/Pages.tsx b/client/src/app/[site]/main/components/sections/Pages.tsx
index f20f984b0..aa98f0de3 100644
--- a/client/src/app/[site]/main/components/sections/Pages.tsx
+++ b/client/src/app/[site]/main/components/sections/Pages.tsx
@@ -10,15 +10,21 @@ 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 = "pages" | "entry_pages" | "exit_pages";
export function Pages({
siteMetadata,
+ isRealtime = false,
}: {
siteMetadata: GetSitesResponse[number];
+ isRealtime?: boolean;
}) {
const [tab, setTab] = useState<Tab>("pages");
+
+ const ComponentToUse = isRealtime ? StandardSectionRealtime : StandardSection;
+
return (
<Card className="h-[493px]">
<CardContent className="mt-2">
@@ -33,7 +39,7 @@ export function Pages({
<TabsTrigger value="exit_pages">Exit Pages</TabsTrigger>
</TabsList>
<TabsContent value="pages">
- <StandardSection
+ <ComponentToUse
filterParameter="pathname"
title="Pages"
getValue={(e) => e.value}
@@ -43,7 +49,7 @@ export function Pages({
/>
</TabsContent>
<TabsContent value="entry_pages">
- <StandardSection
+ <ComponentToUse
filterParameter="entry_page"
title="Entry Pages"
getValue={(e) => e.value}
@@ -53,7 +59,7 @@ export function Pages({
/>
</TabsContent>
<TabsContent value="exit_pages">
- <StandardSection
+ <ComponentToUse
filterParameter="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.tsx
index 42d6935fa..b1b9bcd3c 100644
--- a/client/src/app/[site]/main/components/sections/Referrers.tsx
+++ b/client/src/app/[site]/main/components/sections/Referrers.tsx
@@ -8,11 +8,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";
type Tab = "referrers";
-export function Referrers() {
+export function Referrers({ isRealtime = false }: { isRealtime?: boolean }) {
const [tab, setTab] = useState<Tab>("referrers");
+
+ const ComponentToUse = isRealtime ? StandardSectionRealtime : StandardSection;
+
return (
<Card className="h-[493px]">
<CardContent className="mt-2">
@@ -25,7 +28,7 @@ export function Referrers() {
<TabsTrigger value="referrers">Referrers</TabsTrigger>
</TabsList>
<TabsContent value="referrers">
- <StandardSection
+ <ComponentToUse
filterParameter="referrer"
title="Referrers"
getValue={(e) => e.value}
diff --git a/client/src/app/[site]/realtime/RealtimeMap/RealtimeMap.tsx b/client/src/app/[site]/realtime/RealtimeMap/RealtimeMap.tsx
new file mode 100644
index 000000000..4db078cbf
--- /dev/null
+++ b/client/src/app/[site]/realtime/RealtimeMap/RealtimeMap.tsx
@@ -0,0 +1,180 @@
+"use client";
+
+import { useGetLiveSessionLocations } from "@/api/analytics/useGetLiveSessionLocations";
+import { scaleSqrt } from "d3-scale";
+import { Feature, GeoJsonObject } from "geojson";
+import { Layer } from "leaflet";
+import "leaflet/dist/leaflet.css";
+import { useMemo, useState } from "react";
+import { Circle, GeoJSON, MapContainer, useMapEvent } from "react-leaflet";
+import { useCountries } from "../../../../lib/geo";
+
+// Component to handle zoom events and update circle sizes
+function ZoomHandler({ setZoom }: { setZoom: (zoom: number) => void }) {
+ const map = useMapEvent("zoom", () => {
+ setZoom(map.getZoom());
+ });
+ return null;
+}
+
+interface TooltipContent {
+ count: number;
+ city: string;
+}
+
+interface TooltipPosition {
+ x: number;
+ y: number;
+}
+
+export function RealtimeMap() {
+ const {
+ data: liveSessionLocations,
+ isLoading: isLiveSessionLocationsLoading,
+ } = useGetLiveSessionLocations();
+ const { data: countriesGeoData } = useCountries();
+ const [currentZoom, setCurrentZoom] = useState(1.5); // Initial zoom level
+ const [tooltipContent, setTooltipContent] = useState<TooltipContent | null>(
+ null
+ );
+ const [tooltipPosition, setTooltipPosition] = useState<TooltipPosition>({
+ x: 0,
+ y: 0,
+ });
+
+ // Create a scale for circle radius based on count
+ const radiusScale = useMemo(() => {
+ if (!liveSessionLocations?.length) return () => 0;
+
+ const maxCount = Math.max(...liveSessionLocations.map((loc) => loc.count));
+
+ // Use sqrt scale to make small values more visible
+ // This directly scales radius (not area) which makes small circles more noticeable
+ const baseScale = scaleSqrt().domain([1, maxCount]).range([50000, 500000]); // Min/max radius in meters
+
+ return (count: number) => {
+ const baseRadius = baseScale(count);
+ // Reduce radius gradually as zoom increases
+ const zoomFactor = Math.pow(0.75, currentZoom - 1.5);
+ return baseRadius * zoomFactor;
+ };
+ }, [liveSessionLocations, currentZoom]);
+
+ const handleStyle = (feature: Feature | undefined) => {
+ const count = feature?.properties?.["count"] || 0;
+ return {
+ color: "rgba(140, 140, 140, 0.5)",
+ weight: 0.5,
+ fill: true,
+ fillColor: "rgba(140, 140, 140, 0.5)",
+ fillOpacity: 0.2,
+ };
+ };
+
+ const handleEachFeature = (feature: Feature, layer: Layer) => {
+ layer.on({
+ mouseover: () => {
+ // @ts-ignore
+ layer.setStyle({
+ fillOpacity: 0.5,
+ });
+ },
+ mouseout: () => {
+ // @ts-ignore
+ layer.setStyle({
+ fillOpacity: 0.2,
+ });
+ },
+ });
+ };
+
+ return (
+ <div>
+ <div
+ className="w-full h-[600px] rounded-lg overflow-hidden border border-neutral-800"
+ onMouseMove={(e) => {
+ if (tooltipContent) {
+ setTooltipPosition({
+ x: e.clientX,
+ y: e.clientY,
+ });
+ }
+ }}
+ >
+ <MapContainer
+ center={[30, 0]}
+ zoom={1.5}
+ minZoom={1}
+ style={{ height: "100%", width: "100%", background: "none" }}
+ attributionControl={false}
+ zoomControl={false}
+ >
+ <ZoomHandler setZoom={setCurrentZoom} />
+ {countriesGeoData && (
+ <GeoJSON
+ data={countriesGeoData as GeoJsonObject}
+ style={handleStyle}
+ // onEachFeature={handleEachFeature}
+ />
+ )}
+ {liveSessionLocations?.map((location, index) => (
+ <Circle
+ key={`${location.lat}-${location.lon}-${index}`}
+ center={[location.lat, location.lon]}
+ radius={radiusScale(location.count)}
+ pathOptions={{
+ fillColor: "hsl(var(--accent-500))",
+ fillOpacity: 0.4,
+ color: "hsl(var(--accent-400))",
+ weight: 0,
+ }}
+ eventHandlers={{
+ mouseover: (e) => {
+ setTooltipContent({
+ count: location.count,
+ city: location.city,
+ });
+ setTooltipPosition({
+ x: e.originalEvent.clientX,
+ y: e.originalEvent.clientY,
+ });
+ },
+ mouseout: () => {
+ setTooltipContent(null);
+ },
+ mousemove: (e) => {
+ setTooltipPosition({
+ x: e.originalEvent.clientX,
+ y: e.originalEvent.clientY,
+ });
+ },
+ }}
+ />
+ ))}
+ </MapContainer>
+
+ {tooltipContent && (
+ <div
+ className="fixed bg-neutral-1000 text-white rounded-md p-2 shadow-lg text-sm pointer-events-none"
+ style={{
+ left: tooltipPosition.x,
+ top: tooltipPosition.y - 10,
+ transform: "translate(-50%, -100%)",
+ zIndex: 500,
+ }}
+ >
+ <div className="font-sm">
+ <span className="font-bold text-accent-400">
+ {tooltipContent.count.toLocaleString()}
+ </span>{" "}
+ <span className="text-neutral-300">
+ active {tooltipContent.count === 1 ? "user" : "users"}
+ {tooltipContent.city ? ` from ${tooltipContent.city}` : ""}
+ </span>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/realtime/page.tsx b/client/src/app/[site]/realtime/page.tsx
index 3da984e0b..c0088b2da 100644
--- a/client/src/app/[site]/realtime/page.tsx
+++ b/client/src/app/[site]/realtime/page.tsx
@@ -1,174 +1,19 @@
"use client";
-import { useGetLiveSessionLocations } from "@/api/analytics/useGetLiveSessionLocations";
-import { scaleSqrt } from "d3-scale";
-import { Feature, GeoJsonObject } from "geojson";
-import { Layer } from "leaflet";
-import "leaflet/dist/leaflet.css";
-import { useMemo, useState } from "react";
-import { Circle, GeoJSON, MapContainer, useMapEvent } from "react-leaflet";
-import { useCountries } from "../../../lib/geo";
-
-// Component to handle zoom events and update circle sizes
-function ZoomHandler({ setZoom }: { setZoom: (zoom: number) => void }) {
- const map = useMapEvent("zoom", () => {
- setZoom(map.getZoom());
- });
- return null;
-}
-
-interface TooltipContent {
- count: number;
-}
-
-interface TooltipPosition {
- x: number;
- y: number;
-}
+import { getCountryName } from "../../../lib/utils";
+import { CountryFlag } from "../components/shared/icons/CountryFlag";
+import { StandardSectionRealtime } from "../components/shared/StandardSection/StandardSectionRealtime";
+import { Countries } from "../main/components/sections/Countries";
+import { Referrers } from "../main/components/sections/Referrers";
+import { RealtimeMap } from "./RealtimeMap/RealtimeMap";
export default function RealtimePage() {
- const {
- data: liveSessionLocations,
- isLoading: isLiveSessionLocationsLoading,
- } = useGetLiveSessionLocations();
- const { data: countriesGeoData } = useCountries();
- const [currentZoom, setCurrentZoom] = useState(1.5); // Initial zoom level
- const [tooltipContent, setTooltipContent] = useState<TooltipContent | null>(
- null
- );
- const [tooltipPosition, setTooltipPosition] = useState<TooltipPosition>({
- x: 0,
- y: 0,
- });
-
- // Create a scale for circle radius based on count
- const radiusScale = useMemo(() => {
- if (!liveSessionLocations?.length) return () => 0;
-
- const maxCount = Math.max(...liveSessionLocations.map((loc) => loc.count));
-
- // Use sqrt scale to make small values more visible
- // This directly scales radius (not area) which makes small circles more noticeable
- const baseScale = scaleSqrt().domain([1, maxCount]).range([50000, 500000]); // Min/max radius in meters
-
- return (count: number) => {
- const baseRadius = baseScale(count);
- // Reduce radius gradually as zoom increases
- const zoomFactor = Math.pow(0.75, currentZoom - 1.5);
- return baseRadius * zoomFactor;
- };
- }, [liveSessionLocations, currentZoom]);
-
- const handleStyle = (feature: Feature | undefined) => {
- const count = feature?.properties?.["count"] || 0;
- return {
- color: "rgba(140, 140, 140, 0.5)",
- weight: 0.5,
- fill: true,
- fillColor: "rgba(140, 140, 140, 0.5)",
- fillOpacity: 0.2,
- };
- };
-
- const handleEachFeature = (feature: Feature, layer: Layer) => {
- layer.on({
- mouseover: () => {
- // @ts-ignore
- layer.setStyle({
- fillOpacity: 0.5,
- });
- },
- mouseout: () => {
- // @ts-ignore
- layer.setStyle({
- fillOpacity: 0.2,
- });
- },
- });
- };
-
return (
- <div className="py-6">
- <div
- className="w-full h-[600px] rounded-lg overflow-hidden border border-neutral-800"
- onMouseMove={(e) => {
- if (tooltipContent) {
- setTooltipPosition({
- x: e.clientX,
- y: e.clientY,
- });
- }
- }}
- >
- <MapContainer
- center={[30, 0]}
- zoom={1.5}
- minZoom={1}
- style={{ height: "100%", width: "100%", background: "none" }}
- attributionControl={false}
- zoomControl={false}
- >
- <ZoomHandler setZoom={setCurrentZoom} />
- {countriesGeoData && (
- <GeoJSON
- data={countriesGeoData as GeoJsonObject}
- style={handleStyle}
- // onEachFeature={handleEachFeature}
- />
- )}
- {liveSessionLocations?.map((location, index) => (
- <Circle
- key={`${location.lat}-${location.lon}-${index}`}
- center={[location.lat, location.lon]}
- radius={radiusScale(location.count)}
- pathOptions={{
- fillColor: "hsl(var(--accent-500))",
- fillOpacity: 0.4,
- color: "hsl(var(--accent-400))",
- weight: 0,
- }}
- eventHandlers={{
- mouseover: (e) => {
- setTooltipContent({ count: location.count });
- setTooltipPosition({
- x: e.originalEvent.clientX,
- y: e.originalEvent.clientY,
- });
- },
- mouseout: () => {
- setTooltipContent(null);
- },
- mousemove: (e) => {
- setTooltipPosition({
- x: e.originalEvent.clientX,
- y: e.originalEvent.clientY,
- });
- },
- }}
- />
- ))}
- </MapContainer>
-
- {tooltipContent && (
- <div
- className="fixed bg-neutral-1000 text-white rounded-md p-2 shadow-lg text-sm pointer-events-none"
- style={{
- left: tooltipPosition.x,
- top: tooltipPosition.y - 10,
- transform: "translate(-50%, -100%)",
- zIndex: 500,
- }}
- >
- <div className="font-sm">
- <span className="font-bold text-accent-400">
- {tooltipContent.count.toLocaleString()}
- </span>{" "}
- <span className="text-neutral-300">
- active {tooltipContent.count === 1 ? "session" : "sessions"}
- </span>
- </div>
- </div>
- )}
+ <div className="flex flex-col gap-4">
+ <RealtimeMap />
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <Countries isRealtime />
+ <Referrers isRealtime />
</div>
</div>
);
diff --git a/server/src/api/getLiveSessionLocations.ts b/server/src/api/getLiveSessionLocations.ts
index 902dd1273..0c6333d2f 100644
--- a/server/src/api/getLiveSessionLocations.ts
+++ b/server/src/api/getLiveSessionLocations.ts
@@ -18,7 +18,8 @@ WITH stuff AS (
SELECT
session_id,
any(lat) AS lat,
- any(lon) AS lon
+ any(lon) AS lon,
+ any(city) AS city
FROM
pageviews
WHERE
@@ -30,12 +31,14 @@ WITH stuff AS (
SELECT
lat,
lon,
+ city,
count() as count
from
stuff
GROUP BY
lat,
- lon`,
+ lon,
+ city`,
query_params: {
siteId: Number(siteId),
},
@@ -46,6 +49,7 @@ GROUP BY
lat: number;
lon: number;
count: number;
+ city: string;
}>(result);
return res.status(200).send({ data });
diff --git a/server/src/api/getSingleCol.ts b/server/src/api/getSingleCol.ts
index a522ace54..8ed90036e 100644
--- a/server/src/api/getSingleCol.ts
+++ b/server/src/api/getSingleCol.ts
@@ -4,6 +4,7 @@ import {
geSqlParam,
getFilterStatement,
getTimeStatement,
+ getTimeStatementRealtime,
processResults,
} from "./utils.js";
import { getUserHasAccessToSite } from "../lib/auth-utils.js";
@@ -13,6 +14,7 @@ interface GenericRequest {
Querystring: {
startDate: string;
endDate: string;
+ minutes: number;
timezone: string;
site: string;
filters: string;
@@ -30,8 +32,16 @@ type GetSingleColResponse = {
}[];
const getQuery = (request: GenericRequest["Querystring"]) => {
- const { startDate, endDate, timezone, site, filters, parameter, limit } =
- request;
+ const {
+ startDate,
+ endDate,
+ timezone,
+ site,
+ filters,
+ parameter,
+ limit,
+ minutes,
+ } = request;
const filterStatement = getFilterStatement(filters);
@@ -50,7 +60,11 @@ const getQuery = (request: GenericRequest["Querystring"]) => {
WHERE
site_id = ${site}
${filterStatement}
- ${getTimeStatement(startDate, endDate, timezone)}
+ ${
+ minutes
+ ? getTimeStatementRealtime(minutes)
+ : getTimeStatement(startDate, endDate, timezone)
+ }
AND type = 'custom_event'
GROUP BY event_name ORDER BY count desc
${limit ? `LIMIT ${limit}` : ""};
@@ -74,7 +88,11 @@ const getQuery = (request: GenericRequest["Querystring"]) => {
WHERE
site_id = ${site}
${filterStatement}
- ${getTimeStatement(startDate, endDate, timezone)}
+ ${
+ minutes
+ ? getTimeStatementRealtime(minutes)
+ : getTimeStatement(startDate, endDate, timezone)
+ }
// AND type = 'pageview'
GROUP BY session_id
) AS query
@@ -91,7 +109,11 @@ const getQuery = (request: GenericRequest["Querystring"]) => {
WHERE
site_id = ${site}
${filterStatement}
- ${getTimeStatement(startDate, endDate, timezone)}
+ ${
+ minutes
+ ? getTimeStatementRealtime(minutes)
+ : getTimeStatement(startDate, endDate, timezone)
+ }
// AND type = 'pageview'
GROUP BY value ORDER BY count desc
${limit ? `LIMIT ${limit}` : ""};
diff --git a/server/src/api/utils.ts b/server/src/api/utils.ts
index c175966b8..99499357f 100644
--- a/server/src/api/utils.ts
+++ b/server/src/api/utils.ts
@@ -27,13 +27,17 @@ export function getTimeStatement(
)`;
}
+export function getTimeStatementRealtime(minutes: number) {
+ return `AND timestamp > now() - interval '${minutes} minute'`;
+}
+
export async function processResults<T>(
results: ResultSet<"JSONEachRow">
): Promise<T[]> {
const data: T[] = await results.json();
for (const row of data) {
for (const key in row) {
- if (!isNaN(Number(row[key]))) {
+ if (!isNaN(Number(row[key])) && row[key] !== "") {
row[key] = Number(row[key]) as any;
}
}