Skip to content

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

Enhance UserPage with user information display and CountryFlag component updates

Bill Yang14f16dad20ec
diff --git a/client/src/api/analytics/userInfo.ts b/client/src/api/analytics/userInfo.ts
new file mode 100644
index 000000000..e91e5ec4e
--- /dev/null
+++ b/client/src/api/analytics/userInfo.ts
@@ -0,0 +1,35 @@
+import { useQuery } from "@tanstack/react-query";
+import { BACKEND_URL } from "../../lib/const";
+import { authedFetch } from "../utils";
+
+export type UserInfo = {
+ duration: number;
+ sessions: number;
+ country: string;
+ iso_3166_2: string;
+ language: string;
+ device_type: string;
+ browser: string;
+ browser_version: string;
+ operating_system: string;
+ operating_system_version: string;
+ screen_height: number;
+ screen_width: number;
+ last_seen: string;
+ first_seen: string;
+ pageviews: number;
+ events: number;
+};
+
+export function useUserInfo(siteId: number, userId: string) {
+ return useQuery<UserInfo>({
+ queryKey: ["user-info", userId, siteId],
+ queryFn: () => {
+ console.info("Fetching user info");
+
+ return authedFetch(`${BACKEND_URL}/user/info/${siteId}/${userId}`)
+ .then((res) => res.json())
+ .then((res) => res.data);
+ },
+ });
+}
diff --git a/client/src/app/[site]/components/shared/icons/CountryFlag.tsx b/client/src/app/[site]/components/shared/icons/CountryFlag.tsx
index f9e66ee5c..662da62ed 100644
--- a/client/src/app/[site]/components/shared/icons/CountryFlag.tsx
+++ b/client/src/app/[site]/components/shared/icons/CountryFlag.tsx
@@ -1,8 +1,15 @@
import * as CountryFlags from "country-flag-icons/react/3x2";
import React from "react";
import { getCountryName } from "../../../../../lib/utils";
+import { cn } from "@/lib/utils";
-export function CountryFlag({ country }: { country: string }) {
+export function CountryFlag({
+ country,
+ className,
+}: {
+ country: string;
+ className?: string;
+}) {
return (
<>
{CountryFlags[country as keyof typeof CountryFlags]
@@ -10,7 +17,7 @@ export function CountryFlag({ country }: { country: string }) {
CountryFlags[country as keyof typeof CountryFlags],
{
title: getCountryName(country),
- className: "w-5",
+ className: cn("w-5", className),
}
)
: null}
diff --git a/client/src/app/[site]/user/[userId]/page.tsx b/client/src/app/[site]/user/[userId]/page.tsx
index 8392fdf9a..a23879c1e 100644
--- a/client/src/app/[site]/user/[userId]/page.tsx
+++ b/client/src/app/[site]/user/[userId]/page.tsx
@@ -1,16 +1,70 @@
"use client";
-import { useParams } from "next/navigation";
import SessionsList from "@/components/Sessions/SessionsList";
+import Avatar from "boring-avatars";
+import { DateTime } from "luxon";
+import { useParams } from "next/navigation";
+import { useUserInfo } from "../../../../api/analytics/userInfo";
+import { formatDuration } from "../../../../lib/utils";
export default function UserPage() {
const { userId } = useParams();
+ const { site } = useParams();
+
+ const { data } = useUserInfo(Number(site), userId as string);
return (
<div className="mx-auto py-8">
<div className="mb-8">
- <h1 className="text-2xl font-bold mb-2">User Profile: {userId}</h1>
- <div className="text-sm text-gray-400 mb-6">User activity sessions</div>
+ <h1 className="text-2xl font-bold mb-2 flex items-center gap-2">
+ <Avatar
+ size={48}
+ name={userId as string}
+ variant="marble"
+ colors={["#92A1C6", "#146A7C", "#F0AB3D", "#C271B4", "#C20D90"]}
+ />{" "}
+ {userId?.slice(0, 10)}
+ </h1>
+ <div className="flex gap-2">
+ <div className="flex items-center gap-2">
+ <div className="bg-neutral-850 p-3 rounded-lg flex flex-col gap-1 border border-neutral-750">
+ <div className="text-xs text-neutral-400">
+ Avg. Session Duration
+ </div>
+ <div className="font-semibold">
+ {data?.duration ? formatDuration(data.duration) : "N/A"}
+ </div>
+ </div>
+ <div className="bg-neutral-850 p-3 rounded-lg flex flex-col gap-1 border border-neutral-750">
+ <div className="text-xs text-neutral-400">First Seen</div>
+ <div className="font-semibold">
+ {DateTime.fromSQL(data?.first_seen ?? "").toLocaleString(
+ DateTime.DATETIME_SHORT
+ )}
+ </div>
+ </div>
+ <div className="bg-neutral-850 p-3 rounded-lg flex flex-col gap-1 border border-neutral-750">
+ <div className="text-xs text-neutral-400">Last Seen</div>
+ <div className="font-semibold">
+ {DateTime.fromSQL(data?.last_seen ?? "").toLocaleString(
+ DateTime.DATETIME_SHORT
+ )}
+ </div>
+ </div>
+ <div className="bg-neutral-850 p-3 rounded-lg flex flex-col gap-1 border border-neutral-750">
+ <div className="text-xs text-neutral-400">Pageviews</div>
+ <div className="font-semibold">{data?.pageviews}</div>
+ </div>
+ <div className="bg-neutral-850 p-3 rounded-lg flex flex-col gap-1 border border-neutral-750">
+ <div className="text-xs text-neutral-400">Events</div>
+ <div className="font-semibold">{data?.events}</div>
+ </div>
+ <div className="bg-neutral-850 p-3 rounded-lg flex flex-col gap-1 border border-neutral-750">
+ <div className="text-xs text-neutral-400">Sessions</div>
+ <div className="font-semibold">{data?.sessions}</div>
+ </div>
+ </div>
+ </div>
</div>
<SessionsList userId={userId as string} />
diff --git a/client/src/lib/utils.ts b/client/src/lib/utils.ts
index 30921891f..7945c8118 100644
--- a/client/src/lib/utils.ts
+++ b/client/src/lib/utils.ts
@@ -32,3 +32,17 @@ export const sleep = (ms: number) =>
export const getCountryName = (countryCode: string) => {
return countries[countryCode as keyof typeof countries]?.name;
};
+
+export function formatDuration(seconds: number): string {
+ if (!seconds) return "0s";
+
+ const duration = Duration.fromObject({ seconds });
+
+ if (seconds < 60) {
+ return duration.toFormat("s'S'");
+ } else if (seconds < 3600) {
+ return duration.toFormat("m'm' s's'");
+ } else {
+ return duration.toFormat("h'h' m'm'");
+ }
+}
diff --git a/server/src/api/getUserInfo.ts b/server/src/api/getUserInfo.ts
new file mode 100644
index 000000000..590d4a3ee
--- /dev/null
+++ b/server/src/api/getUserInfo.ts
@@ -0,0 +1,114 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import { clickhouse } from "../db/clickhouse/clickhouse.js";
+import { processResults } from "./utils.js";
+
+interface UserPageviewData {
+ sessions: number;
+ duration: number;
+ country: string;
+ iso_3166_2: string;
+ language: string;
+ device_type: string;
+ browser: string;
+ browser_version: string;
+ operating_system: string;
+ operating_system_version: string;
+ screen_height: number;
+ screen_width: number;
+ last_seen: string;
+ first_seen: string;
+ pageviews: number;
+ events: number;
+}
+
+export async function getUserInfo(
+ req: FastifyRequest<{
+ Params: {
+ siteId: number;
+ userId: string;
+ };
+ }>,
+ res: FastifyReply
+) {
+ const { userId, siteId } = req.params;
+
+ try {
+ const queryResult = await clickhouse.query({
+ query: `
+ WITH sessions AS (
+ SELECT
+ session_id,
+ user_id,
+ argMax(country, timestamp) AS country,
+ argMax(iso_3166_2, timestamp) AS iso_3166_2,
+ argMax(language, timestamp) AS language,
+ argMax(device_type, timestamp) AS device_type,
+ argMax(browser, timestamp) AS browser,
+ argMax(browser_version, timestamp) AS browser_version,
+ argMax(operating_system, timestamp) AS operating_system,
+ argMax(operating_system_version, timestamp) AS operating_system_version,
+ argMax(screen_width, timestamp) AS screen_width,
+ argMax(screen_height, timestamp) AS screen_height,
+ argMin(referrer, timestamp) AS referrer,
+ MAX(timestamp) AS session_end,
+ MIN(timestamp) AS session_start,
+ dateDiff('second', MIN(timestamp), MAX(timestamp)) AS session_duration,
+ argMinIf(pathname, timestamp, type = 'pageview') AS entry_page,
+ argMaxIf(pathname, timestamp, type = 'pageview') AS exit_page,
+ countIf(type = 'pageview') AS pageviews,
+ countIf(type = 'custom_event') AS events
+ FROM
+ pageviews
+ WHERE
+ user_id = {userId:String}
+ AND site_id = {siteId:Int32}
+ GROUP BY
+ session_id,
+ user_id
+ ORDER BY
+ session_end DESC
+ )
+ SELECT
+ COUNT(DISTINCT session_id) AS sessions,
+ ROUND(avg(session_duration)) AS duration,
+ any(country) as country,
+ any(iso_3166_2) AS iso_3166_2,
+ any(language) AS language,
+ any(device_type) AS device_type,
+ any(browser) AS browser,
+ any(browser_version) AS browser_version,
+ any(operating_system) AS operating_system,
+ any(operating_system_version) AS operating_system_version,
+ any(screen_height) AS screen_height,
+ any(screen_width) AS screen_width,
+ MAX(session_end) AS last_seen,
+ MIN(session_start) AS first_seen,
+ SUM(pageviews) AS pageviews,
+ SUM(events) AS events
+ FROM
+ sessions
+ `,
+ query_params: {
+ userId,
+ siteId: Number(siteId),
+ },
+ format: "JSONEachRow",
+ });
+
+ const data = await processResults<UserPageviewData>(queryResult);
+
+ // If no data found for user
+ if (data.length === 0) {
+ return res.status(404).send({
+ error: "User not found",
+ });
+ }
+
+ return res.send({ data: data[0] });
+ } catch (error) {
+ console.error("Error fetching user info:", error);
+ return res.status(500).send({
+ error: "Internal server error",
+ });
+ }
+}
diff --git a/server/src/index.ts b/server/src/index.ts
index c5e8d1fcc..1943c58ea 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -31,6 +31,7 @@ import { listOrganizationMembers } from "./api/listOrganizationMembers.js";
import { getUserOrganizations } from "./api/user/getUserOrganizations.js";
import { initializeCronJobs } from "./cron/index.js";
import { getUserSubscription } from "./api/user/getUserSubscription.js";
+import { getUserInfo } from "./api/getUserInfo.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -129,6 +130,7 @@ server.get("/site-has-data/:site", getSiteHasData);
server.get("/sessions", getSessions);
server.get("/session/:sessionId", getSession);
server.get("/user/:userId/sessions", getUserSessions);
+server.get("/user/info/:siteId/:userId", getUserInfo);
// Administrative
server.post("/add-site", addSite);