🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Enhance analytics event tracking and performance metrics
Bill Yanga54af896f033
diff --git a/client/src/api/analytics/useGetOrgEventCount.ts b/client/src/api/analytics/useGetOrgEventCount.tsindex 053563e95..17ea2efcd 100644--- a/client/src/api/analytics/useGetOrgEventCount.ts+++ b/client/src/api/analytics/useGetOrgEventCount.ts@@ -3,6 +3,9 @@ import { authedFetch } from "../utils";export type OrgEventCountResponse = {event_date: string;+ pageview_count: number;+ custom_event_count: number;+ performance_count: number;event_count: number;}[];diff --git a/client/src/app/[site]/performance/utils/performanceUtils.ts b/client/src/app/[site]/performance/utils/performanceUtils.tsindex c371a2f00..38e670726 100644--- a/client/src/app/[site]/performance/utils/performanceUtils.ts+++ b/client/src/app/[site]/performance/utils/performanceUtils.ts@@ -55,26 +55,6 @@ export const getMetricUnit = (metric: PerformanceMetric, value: number): stringreturn "ms";};-/**- * Get the chart color for a performance metric (used in charts)- */-const getMetricChartColor = (metric: PerformanceMetric): string => {- switch (metric) {- case "lcp":- return "#3b82f6"; // blue- case "cls":- return "#10b981"; // emerald- case "inp":- return "#f59e0b"; // amber- case "fcp":- return "#8b5cf6"; // violet- case "ttfb":- return "#ef4444"; // red- default:- return "#6b7280"; // gray- }-};-/*** Performance metric labels for display*/diff --git a/client/src/app/subscribe/page.tsx b/client/src/app/subscribe/page.tsxindex eba175912..7d69b9c67 100644--- a/client/src/app/subscribe/page.tsx+++ b/client/src/app/subscribe/page.tsx@@ -1,10 +1,8 @@"use client";import { authClient } from "@/lib/auth";-import { TrendingUp } from "lucide-react";import { DateTime } from "luxon";import { useRouter } from "next/navigation";-import { useGetOrgEventCount } from "../../api/analytics/useGetOrgEventCount";import { StandardPage } from "../../components/StandardPage";import { UsageChart } from "../../components/UsageChart";import { useStripeSubscription } from "../../lib/subscription/useStripeSubscription";@@ -30,17 +28,6 @@ export default function Subscribe() {const endDate = DateTime.now().toISODate();const startDate = DateTime.now().minus({ days: 30 }).toISODate();- // Fetch usage data for the chart and total calculation- const { data: eventCountData } = useGetOrgEventCount({- organizationId: organizationId || "",- startDate,- endDate,- enabled: !!organizationId,- });-- // Calculate total events over the past 30 days- const totalEvents = eventCountData?.data?.reduce((sum, day) => sum + day.event_count, 0) || 0;-return (<StandardPage><div className="container mx-auto py-12 px-4">@@ -51,23 +38,8 @@ export default function Subscribe() {{/* Usage Stats and Chart */}{organizationId && (- <div className="max-w-lg mx-auto mt-6">- <div className="bg-blue-900/20 rounded-xl border border-blue-800 p-6">- <div className="flex items-center justify-between mb-4">- <div className="flex items-center gap-2">- <TrendingUp className="h-5 w-5 text-blue-400" />- <h3 className="font-semibold text-lg">Your Usage (Last 30 Days)</h3>- </div>- <div className="text-right">- <p className="text-2xl font-bold text-blue-300">{totalEvents.toLocaleString()}</p>- <p className="text-xs text-neutral-400">total events</p>- </div>- </div>-- <div className="p-1">- <UsageChart organizationId={organizationId} startDate={startDate} endDate={endDate} />- </div>- </div>+ <div className="max-w-lg mx-auto mt-6 bg-blue-900/20 rounded-xl border border-blue-800 p-6">+ <UsageChart organizationId={organizationId} startDate={startDate} endDate={endDate} /></div>)}diff --git a/client/src/components/UsageChart.tsx b/client/src/components/UsageChart.tsxindex 152f4a2aa..0833cb50b 100644--- a/client/src/components/UsageChart.tsx+++ b/client/src/components/UsageChart.tsx@@ -4,8 +4,9 @@ import { ResponsiveLine } from "@nivo/line";import { useWindowSize } from "@uidotdev/usehooks";import { DateTime } from "luxon";import { useGetOrgEventCount } from "../api/analytics/useGetOrgEventCount";-import { userLocale, hour12 } from "../lib/dateTimeUtils";+import { userLocale } from "../lib/dateTimeUtils";import { formatter } from "../lib/utils";+import { Badge } from "./ui/badge";interface UsageChartProps {organizationId: string;@@ -28,20 +29,40 @@ export function UsageChart({ organizationId, startDate, endDate, timeZone = "UTCconst maxTicks = Math.round((width ?? Infinity) / 200);- const formattedData =+ const pageviewData =data?.data?.map(e => {- // Parse timestamp properly - now it's a date instead of datetimeconst timestamp = DateTime.fromSQL(e.event_date).toUTC();+ if (timestamp > DateTime.now()) return null;+ return {+ x: timestamp.toFormat("yyyy-MM-dd"),+ y: e.pageview_count,+ currentTime: timestamp,+ };+ })+ .filter(e => e !== null) || [];- // filter out dates from the future- if (timestamp > DateTime.now()) {- return null;- }+ const customEventData =+ data?.data+ ?.map(e => {+ const timestamp = DateTime.fromSQL(e.event_date).toUTC();+ if (timestamp > DateTime.now()) return null;+ return {+ x: timestamp.toFormat("yyyy-MM-dd"),+ y: e.custom_event_count,+ currentTime: timestamp,+ };+ })+ .filter(e => e !== null) || [];+ const performanceData =+ data?.data+ ?.map(e => {+ const timestamp = DateTime.fromSQL(e.event_date).toUTC();+ if (timestamp > DateTime.now()) return null;return {x: timestamp.toFormat("yyyy-MM-dd"),- y: e.event_count,+ y: e.performance_count,currentTime: timestamp,};})@@ -49,12 +70,25 @@ export function UsageChart({ organizationId, startDate, endDate, timeZone = "UTCconst chartData = [{- id: "events",- data: formattedData,+ id: "pageviews",+ data: pageviewData,+ },+ {+ id: "custom events",+ data: customEventData,+ },+ {+ id: "performance",+ data: performanceData,},];- const maxValue = Math.max(...formattedData.map(d => d.y), 1);+ const maxValue = Math.max(+ ...pageviewData.map(d => d.y),+ ...customEventData.map(d => d.y),+ ...performanceData.map(d => d.y),+ 1+ );if (isLoading) {return (@@ -72,99 +106,94 @@ export function UsageChart({ organizationId, startDate, endDate, timeZone = "UTC);}+ const totalEvents = chartData.reduce((acc, curr) => acc + curr.data.reduce((acc, curr) => acc + curr.y, 0), 0);+return (- <div className="h-48">- <ResponsiveLine- data={chartData}- theme={nivoTheme}- margin={{ top: 10, right: 10, bottom: 25, left: 35 }}- xScale={{- type: "time",- format: "%Y-%m-%d",- precision: "day",- useUTC: true,- }}- yScale={{- type: "linear",- min: 0,- stacked: false,- reverse: false,- max: maxValue,- }}- enableGridX={false}- enableGridY={true}- gridYValues={5}- yFormat=" >-.0f"- axisTop={null}- axisRight={null}- axisBottom={{- tickSize: 0,- tickPadding: 10,- tickRotation: 0,- truncateTickAt: 0,- tickValues: Math.min(maxTicks, 10),- format: value => {- const dt = DateTime.fromJSDate(value).setLocale(userLocale);- return dt.toFormat("MMM d");- },- }}- axisLeft={{- tickSize: 0,- tickPadding: 10,- tickRotation: 0,- truncateTickAt: 0,- tickValues: 5,- format: formatter,- }}- enableTouchCrosshair={true}- enablePoints={false}- useMesh={true}- animate={false}- enableSlices={"x"}- colors={["hsl(var(--dataviz))"]}- enableArea={true}- areaBaselineValue={0}- areaOpacity={0.3}- defs={[- {- id: "gradient",- type: "linearGradient",- colors: [- { offset: 0, color: "hsl(var(--dataviz))", opacity: 1 },- { offset: 100, color: "hsl(var(--dataviz))", opacity: 0 },- ],- },- ]}- fill={[- {- match: {- id: "events",+ <div>+ <h3 className="font-medium text-sm text-neutral-300 mb-2 flex items-center gap-2 mb-4">+ Last 30 Days+ <Badge variant="outline" className="text-neutral-300">+ {totalEvents.toLocaleString()} events+ </Badge>+ </h3>+ <div className="h-48">+ <ResponsiveLine+ data={chartData}+ theme={nivoTheme}+ margin={{ top: 10, right: 10, bottom: 25, left: 35 }}+ xScale={{+ type: "time",+ format: "%Y-%m-%d",+ precision: "day",+ useUTC: true,+ }}+ yScale={{+ type: "linear",+ min: 0,+ stacked: false,+ reverse: false,+ max: maxValue,+ }}+ enableGridX={false}+ enableGridY={true}+ gridYValues={5}+ yFormat=" >-.0f"+ axisTop={null}+ axisRight={null}+ axisBottom={{+ tickSize: 0,+ tickPadding: 10,+ tickRotation: 0,+ truncateTickAt: 0,+ tickValues: Math.min(maxTicks, 10),+ format: value => {+ const dt = DateTime.fromJSDate(value).setLocale(userLocale);+ return dt.toFormat("MMM d");},- id: "gradient",- },- ]}- sliceTooltip={({ slice }: any) => {- const currentY = Number(slice.points[0].data.yFormatted);- const currentTime = slice.points[0].data.currentTime as DateTime;+ }}+ axisLeft={{+ tickSize: 0,+ tickPadding: 10,+ tickRotation: 0,+ truncateTickAt: 0,+ tickValues: 5,+ format: formatter,+ }}+ enableTouchCrosshair={true}+ enablePoints={false}+ useMesh={true}+ animate={false}+ enableSlices={"x"}+ colors={["hsl(var(--blue-400))", "hsl(var(--indigo-400))", "hsl(var(--violet-400))"]}+ enableArea={false}+ sliceTooltip={({ slice }: any) => {+ const currentTime = slice.points[0].data.currentTime as DateTime;- return (- <div className="text-sm bg-neutral-900 p-2 rounded-md">- <div className="flex justify-between text-sm w-36">- <div>{formatDateTime(currentTime)}</div>- <div>{currentY.toLocaleString()} events</div>+ const total = slice.points.reduce((acc: number, point: any) => acc + Number(point.data.yFormatted), 0);++ return (+ <div className="text-sm bg-neutral-850 p-3 rounded-md min-w-[100px] border border-neutral-750">+ <div className="font-medium mb-1">{currentTime.toLocaleString(DateTime.DATE_MED)}</div>+ {slice.points.reverse().map((point: any) => {+ return (+ <div key={point.serieId} className="flex justify-between gap-4 text-sm">+ <div className="flex items-center gap-2 text-neutral-300">+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: point.seriesColor }} />+ <span>{point.seriesId.charAt(0).toUpperCase() + point.seriesId.slice(1)}</span>+ </div>+ <div>{Number(point.data.yFormatted).toLocaleString()}</div>+ </div>+ );+ })}+ <div className="text-sm mt-2 flex justify-between">+ <div className="text-neutral-300">Total</div>+ <div className="font-semibold">{total.toLocaleString()}</div>+ </div></div>- </div>- );- }}- />+ );+ }}+ />+ </div></div>);}--const formatDateTime = (dt: DateTime) => {- const options: Intl.DateTimeFormatOptions = {- month: "short",- day: "numeric",- };- return new Intl.DateTimeFormat(userLocale, options).format(dt.toJSDate());-};diff --git a/client/src/components/subscription/FreePlan.tsx b/client/src/components/subscription/FreePlan.tsxindex 3c4dcecbb..d2ca3e11c 100644--- a/client/src/components/subscription/FreePlan.tsx+++ b/client/src/components/subscription/FreePlan.tsx@@ -1,14 +1,14 @@-import { AlertTriangle, ArrowRight, PackageOpen } from "lucide-react";-import { useRouter } from "next/navigation";+import { authClient } from "@/lib/auth";+import { AlertTriangle, ArrowRight } from "lucide-react";import { DateTime } from "luxon";+import { useRouter } from "next/navigation";+import { DEFAULT_EVENT_LIMIT } from "../../lib/subscription/constants";+import { useStripeSubscription } from "../../lib/subscription/useStripeSubscription";import { Alert, AlertDescription, AlertTitle } from "../ui/alert";import { Button } from "../ui/button";import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "../ui/card";import { Progress } from "../ui/progress";-import { DEFAULT_EVENT_LIMIT } from "../../lib/subscription/constants";-import { useStripeSubscription } from "../../lib/subscription/useStripeSubscription";import { UsageChart } from "../UsageChart";-import { authClient } from "@/lib/auth";export function FreePlan() {const { data: subscription } = useStripeSubscription();@@ -79,12 +79,7 @@ export function FreePlan() {</div></div>- {organizationId && (- <div className="space-y-2">- <h3 className="font-medium text-sm text-neutral-400 mb-2">Last 30 Days</h3>- <UsageChart organizationId={organizationId} startDate={startDate} endDate={endDate} />- </div>- )}+ {organizationId && <UsageChart organizationId={organizationId} startDate={startDate} endDate={endDate} />}</div></CardContent><CardFooter>diff --git a/client/src/components/subscription/PaidPlain/PaidPlan.tsx b/client/src/components/subscription/PaidPlain/PaidPlan.tsxindex ea6fb010f..3d969a5bd 100644--- a/client/src/components/subscription/PaidPlain/PaidPlan.tsx+++ b/client/src/components/subscription/PaidPlain/PaidPlan.tsx@@ -191,12 +191,7 @@ export function PaidPlan() {</div></div>- {organizationId && (- <div className="space-y-2">- <h3 className="font-medium text-sm text-neutral-400 mb-2">Last 30 Days</h3>- <UsageChart organizationId={organizationId} startDate={startDate} endDate={endDate} />- </div>- )}+ {organizationId && <UsageChart organizationId={organizationId} startDate={startDate} endDate={endDate} />}{isAnnualPlan && (<div className="pt-2 pb-0 px-3 bg-emerald-50 dark:bg-emerald-900/20 rounded-md border border-emerald-100 dark:border-emerald-800">diff --git a/docs-v2/src/components/PricingSection.tsx b/docs-v2/src/components/PricingSection.tsxindex 3c682b47c..c1705dae5 100644--- a/docs-v2/src/components/PricingSection.tsx+++ b/docs-v2/src/components/PricingSection.tsx@@ -278,7 +278,7 @@ export function PricingSection() {) : (<><CheckCircle className="w-3 h-3" />- We don't ask for your credit card+ We don't ask for your credit card. 60 day money back guarantee.</>)}</p>@@ -343,7 +343,7 @@ export function PricingSection() {) : (<><CheckCircle className="w-3 h-3" />- We don't ask for your credit card+ We don't ask for your credit card. 60 day money back guarantee.</>)}</p>diff --git a/server/src/api/analytics/getOrgEventCount.ts b/server/src/api/analytics/getOrgEventCount.tsindex adbd281c9..c0f9461a6 100644--- a/server/src/api/analytics/getOrgEventCount.ts+++ b/server/src/api/analytics/getOrgEventCount.ts@@ -1,14 +1,14 @@import { FastifyReply, FastifyRequest } from "fastify";-import { clickhouse } from "../../db/clickhouse/clickhouse.js";-import { processResults } from "./utils.js";import SqlString from "sqlstring";+import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { getSitesUserHasAccessTo } from "../../lib/auth-utils.js";-import { db } from "../../db/postgres/postgres.js";-import { sites } from "../../db/postgres/schema.js";-import { eq } from "drizzle-orm";+import { processResults } from "./utils.js";type OrgEventCountResponse = {event_date: string;+ pageview_count: number;+ custom_event_count: number;+ performance_count: number;event_count: number;}[];@@ -82,12 +82,16 @@ export async function getOrgEventCount(}const query = `- SELECT- toStartOfDay(event_hour) as event_date,- SUM(event_count) as event_count- FROM hourly_events_by_site_mv_target+ SELECT+ toStartOfDay(timestamp) as event_date,+ countIf(type = 'pageview') as pageview_count,+ countIf(type = 'custom_event') as custom_event_count,+ countIf(type = 'performance') as performance_count,+ count() as event_count+ FROM eventsWHERE site_id IN (${siteIds.map((id: number) => SqlString.escape(id)).join(", ")})- ${timeFilter}+ AND type IN ('pageview', 'custom_event', 'performance')+ ${timeFilter.replace(/event_hour/g, "timestamp")}GROUP BY event_dateORDER BY event_dateWITH FILL ${fillFromDate} ${fillToDate} STEP INTERVAL 1 DAY