Skip to content

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

Integrate Service Usage Chart and Tabs in Organizations component

Bill Yang53159dc8de0d
diff --git a/client/src/api/admin/useGetAdminServiceEventCount.ts b/client/src/api/admin/useGetAdminServiceEventCount.ts
new file mode 100644
index 000000000..649ef7f85
--- /dev/null
+++ b/client/src/api/admin/useGetAdminServiceEventCount.ts
@@ -0,0 +1,55 @@
+import { useQuery } from "@tanstack/react-query";
+import { authedFetch } from "../utils";
+
+export type ServiceEventCountResponse = {
+ event_date: string;
+ pageview_count: number;
+ custom_event_count: number;
+ performance_count: number;
+ event_count: number;
+}[];
+
+export type GetServiceEventCountResponse = {
+ data: ServiceEventCountResponse;
+};
+
+async function getAdminServiceEventCount({
+ startDate,
+ endDate,
+ timeZone = "UTC",
+}: {
+ startDate?: string;
+ endDate?: string;
+ timeZone?: string;
+}): Promise<GetServiceEventCountResponse> {
+ const params = new URLSearchParams();
+ if (startDate) params.append("startDate", startDate);
+ if (endDate) params.append("endDate", endDate);
+ if (timeZone) params.append("timeZone", timeZone);
+
+ return authedFetch("/admin/service-event-count", Object.fromEntries(params));
+}
+
+export function useGetAdminServiceEventCount({
+ startDate,
+ endDate,
+ timeZone = "UTC",
+ enabled = true,
+}: {
+ startDate?: string;
+ endDate?: string;
+ timeZone?: string;
+ enabled?: boolean;
+}) {
+ return useQuery({
+ queryKey: ["admin-service-event-count", startDate, endDate, timeZone],
+ queryFn: () =>
+ getAdminServiceEventCount({
+ startDate,
+ endDate,
+ timeZone,
+ }),
+ enabled,
+ staleTime: 1000 * 60 * 5, // 5 minutes
+ });
+}
diff --git a/client/src/app/admin/components/organizations/Organizations.tsx b/client/src/app/admin/components/organizations/Organizations.tsx
index 212ff815c..c26623cb5 100644
--- a/client/src/app/admin/components/organizations/Organizations.tsx
+++ b/client/src/app/admin/components/organizations/Organizations.tsx
@@ -39,6 +39,8 @@ import { ErrorAlert } from "../shared/ErrorAlert";
import { AdminLayout } from "../shared/AdminLayout";
import { GrowthChart } from "../shared/GrowthChart";
import { OverviewCards } from "../shared/OverviewCards";
+import { ServiceUsageChart } from "../shared/ServiceUsageChart";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
export function Organizations() {
const router = useRouter();
@@ -77,8 +79,6 @@ export function Organizations() {
0
);
- console.log(totalEventsLast30Days);
-
return {
totalOrganizations,
activeOrganizations,
@@ -315,7 +315,18 @@ export function Organizations() {
]}
/>
- <GrowthChart data={organizations} color="#8b5cf6" title="Organizations" />
+ <Tabs defaultValue="growth" className="mb-6">
+ <TabsList>
+ <TabsTrigger value="growth">Organization Growth</TabsTrigger>
+ <TabsTrigger value="usage">Service Usage</TabsTrigger>
+ </TabsList>
+ <TabsContent value="growth">
+ <GrowthChart data={organizations} color="#8b5cf6" title="Organizations" />
+ </TabsContent>
+ <TabsContent value="usage">
+ <ServiceUsageChart />
+ </TabsContent>
+ </Tabs>
<div className="mb-4">
<SearchInput
@@ -391,7 +402,7 @@ export function Organizations() {
<CreditCard className="h-4 w-4" />
Subscription Details
</div>
- <div className="grid grid-cols-1 md:grid-cols-3 gap-4 p-4 border border-neutral-700 rounded">
+ <div className="grid grid-cols-1 md:grid-cols-4 gap-4 p-4 border border-neutral-700 rounded">
<div>
<div className="text-xs text-neutral-400 uppercase tracking-wide">Plan</div>
<div className="font-medium">{row.original.subscription.planName}</div>
diff --git a/client/src/app/admin/components/shared/ServiceUsageChart.tsx b/client/src/app/admin/components/shared/ServiceUsageChart.tsx
new file mode 100644
index 000000000..acb13f77a
--- /dev/null
+++ b/client/src/app/admin/components/shared/ServiceUsageChart.tsx
@@ -0,0 +1,191 @@
+"use client";
+
+import { nivoTheme } from "@/lib/nivo";
+import { ResponsiveLine } from "@nivo/line";
+import { useWindowSize } from "@uidotdev/usehooks";
+import { DateTime } from "luxon";
+import { useGetAdminServiceEventCount } from "@/api/admin/useGetAdminServiceEventCount";
+import { userLocale } from "@/lib/dateTimeUtils";
+import { formatter } from "@/lib/utils";
+import { Badge } from "@/components/ui/badge";
+
+interface ServiceUsageChartProps {
+ startDate?: string;
+ endDate?: string;
+ timeZone?: string;
+}
+
+export function ServiceUsageChart({ startDate, endDate, timeZone = "UTC" }: ServiceUsageChartProps) {
+ const { width } = useWindowSize();
+
+ // Fetch the data inside the component
+ const { data, isLoading, error } = useGetAdminServiceEventCount({
+ startDate,
+ endDate,
+ timeZone,
+ });
+
+ const maxTicks = Math.round((width ?? Infinity) / 200);
+
+ const pageviewData =
+ 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.pageview_count,
+ currentTime: timestamp,
+ };
+ })
+ .filter(e => e !== 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.performance_count,
+ currentTime: timestamp,
+ };
+ })
+ .filter(e => e !== null) || [];
+
+ const chartData = [
+ {
+ id: "pageviews",
+ data: pageviewData,
+ },
+ {
+ id: "custom events",
+ data: customEventData,
+ },
+ {
+ id: "performance",
+ data: performanceData,
+ },
+ ];
+
+ const maxValue = Math.max(
+ ...pageviewData.map(d => d.y),
+ ...customEventData.map(d => d.y),
+ ...performanceData.map(d => d.y),
+ 1
+ );
+
+ if (isLoading) {
+ return (
+ <div className="h-64 flex items-center justify-center">
+ <div className="text-sm text-muted-foreground">Loading usage data...</div>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="h-64 flex items-center justify-center">
+ <div className="text-sm text-muted-foreground">Failed to load usage data</div>
+ </div>
+ );
+ }
+
+ const totalEvents = chartData.reduce((acc, curr) => acc + curr.data.reduce((acc, curr) => acc + curr.y, 0), 0);
+
+ return (
+ <div className="h-64">
+ <ResponsiveLine
+ data={chartData}
+ theme={nivoTheme}
+ margin={{ top: 10, right: 10, bottom: 25, left: 50 }}
+ 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(--blue-400))", "hsl(var(--indigo-400))", "hsl(var(--violet-400))"]}
+ enableArea={false}
+ sliceTooltip={({ slice }: any) => {
+ const currentTime = slice.points[0].data.currentTime as DateTime;
+
+ 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
+ .sort((a: any, b: any) => a.seriesId.localeCompare(b.seriesId))
+ .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>{formatter(Number(point.data.yFormatted))}</div>
+ </div>
+ );
+ })}
+ <div className="text-sm mt-2 flex justify-between">
+ <div className="text-neutral-300">Total</div>
+ <div className="font-semibold">{formatter(total)}</div>
+ </div>
+ </div>
+ );
+ }}
+ />
+ </div>
+ );
+}
diff --git a/server/src/api/admin/getAdminServiceEventCount.ts b/server/src/api/admin/getAdminServiceEventCount.ts
new file mode 100644
index 000000000..d2d3b93dc
--- /dev/null
+++ b/server/src/api/admin/getAdminServiceEventCount.ts
@@ -0,0 +1,100 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import SqlString from "sqlstring";
+import { clickhouse } from "../../db/clickhouse/clickhouse.js";
+import { getIsUserAdmin } from "../../lib/auth-utils.js";
+import { processResults } from "../analytics/utils.js";
+
+type ServiceEventCountResponse = {
+ event_date: string;
+ pageview_count: number;
+ custom_event_count: number;
+ performance_count: number;
+ event_count: number;
+}[];
+
+export async function getAdminServiceEventCount(
+ req: FastifyRequest<{
+ Querystring: {
+ startDate?: string;
+ endDate?: string;
+ timeZone?: string;
+ };
+ }>,
+ res: FastifyReply
+) {
+ const isAdmin = await getIsUserAdmin(req);
+
+ if (!isAdmin) {
+ return res.status(401).send({ error: "Unauthorized" });
+ }
+
+ const { startDate, endDate, timeZone = "UTC" } = req.query;
+
+ try {
+ // Build time filter for the query
+ let timeFilter = "";
+ let fillFromDate = "";
+ let fillToDate = "";
+
+ if (startDate && endDate) {
+ timeFilter = `AND event_hour >= toTimeZone(
+ toStartOfDay(toDateTime(${SqlString.escape(startDate)}, ${SqlString.escape(timeZone)})),
+ 'UTC'
+ )
+ AND event_hour < if(
+ toDate(${SqlString.escape(endDate)}) = toDate(now(), ${SqlString.escape(timeZone)}),
+ now(),
+ toTimeZone(
+ toStartOfDay(toDateTime(${SqlString.escape(endDate)}, ${SqlString.escape(timeZone)})) + INTERVAL 1 DAY,
+ 'UTC'
+ )
+ )`;
+
+ // Set up WITH FILL parameters
+ fillFromDate = `FROM toTimeZone(
+ toStartOfDay(toDateTime(${SqlString.escape(startDate)}, ${SqlString.escape(timeZone)})),
+ 'UTC'
+ )`;
+
+ fillToDate = `TO if(
+ toDate(${SqlString.escape(endDate)}) = toDate(now(), ${SqlString.escape(timeZone)}),
+ toStartOfDay(now()) + INTERVAL 1 DAY,
+ toTimeZone(
+ toStartOfDay(toDateTime(${SqlString.escape(endDate)}, ${SqlString.escape(timeZone)})) + INTERVAL 1 DAY,
+ 'UTC'
+ )
+ )`;
+ } else {
+ // Default to last 30 days if no date range provided
+ timeFilter = "AND event_hour >= toStartOfDay(now()) - INTERVAL 30 DAY";
+ fillFromDate = "FROM toStartOfDay(now()) - INTERVAL 30 DAY";
+ fillToDate = "TO toStartOfDay(now()) + INTERVAL 1 DAY";
+ }
+
+ const query = `
+ 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 events
+ WHERE type IN ('pageview', 'custom_event', 'performance')
+ ${timeFilter.replace(/event_hour/g, "timestamp")}
+ GROUP BY event_date
+ ORDER BY event_date
+ WITH FILL ${fillFromDate} ${fillToDate} STEP INTERVAL 1 DAY
+ `;
+
+ const result = await clickhouse.query({
+ query,
+ format: "JSONEachRow",
+ });
+
+ const data = await processResults<ServiceEventCountResponse[number]>(result);
+ return res.send({ data });
+ } catch (error) {
+ console.error("Error fetching service event count:", error);
+ return res.status(500).send({ error: "Failed to fetch service event count" });
+ }
+}
diff --git a/server/src/index.ts b/server/src/index.ts
index 922aa5a5d..03d5b9e01 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -6,6 +6,7 @@ import { dirname, join } from "path";
import { fileURLToPath } from "url";
import { collectTelemetry } from "./api/admin/collectTelemetry.js";
import { getAdminOrganizations } from "./api/admin/getAdminOrganizations.js";
+import { getAdminServiceEventCount } from "./api/admin/getAdminServiceEventCount.js";
import { getAdminSites } from "./api/admin/getAdminSites.js";
import { getEventNames } from "./api/analytics/events/getEventNames.js";
import { getEventProperties } from "./api/analytics/events/getEventProperties.js";
@@ -409,6 +410,7 @@ if (IS_CLOUD) {
// Admin Routes
server.get("/api/admin/sites", getAdminSites);
server.get("/api/admin/organizations", getAdminOrganizations);
+ server.get("/api/admin/service-event-count", getAdminServiceEventCount);
server.post("/api/admin/telemetry", collectTelemetry);
// AppSumo Routes