🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Enhance Sidebar component with new Users tab and icon integration
Bill Yang0178744f7f6b
diff --git a/client/src/api/analytics/users.ts b/client/src/api/analytics/users.tsnew file mode 100644index 000000000..f6113a89d--- /dev/null+++ b/client/src/api/analytics/users.ts@@ -0,0 +1,67 @@+import { useQuery } from "@tanstack/react-query";+import { BACKEND_URL } from "../../lib/const";+import { useStore, Filter } from "../../lib/store";+import { getStartAndEndDate, authedFetch } from "../utils";+import { APIResponse } from "../types";++export type UsersResponse = {+ user_id: string;+ country: string;+ browser: string;+ operating_system: string;+ device_type: string;+ pageviews: number;+ events: number;+ sessions: number;+ last_seen: string;+ first_seen: string;+};++export interface GetUsersOptions {+ page: number;+ pageSize: number;+ sortBy: string;+ sortOrder: string;+ filters?: Filter[];+}++export function useGetUsers(options: GetUsersOptions) {+ const { time, site, filters: storeFilters } = useStore();+ const { startDate, endDate } = getStartAndEndDate(time);++ const { page, pageSize, sortBy, sortOrder } = options;++ return useQuery<+ APIResponse<UsersResponse[]> & {+ totalCount: number;+ page: number;+ pageSize: number;+ }+ >({+ queryKey: [+ "users",+ site,+ time,+ page,+ pageSize,+ sortBy,+ sortOrder,+ storeFilters,+ ],+ queryFn: async () => {+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;++ return authedFetch(`${BACKEND_URL}/users`, {+ startDate,+ endDate,+ timezone,+ site,+ filters: storeFilters,+ page,+ pageSize,+ sortBy,+ sortOrder,+ }).then((res) => res.json());+ },+ });+}diff --git a/client/src/app/[site]/components/Sidebar/Sidebar.tsx b/client/src/app/[site]/components/Sidebar/Sidebar.tsxindex b150b09c7..440c23165 100644--- a/client/src/app/[site]/components/Sidebar/Sidebar.tsx+++ b/client/src/app/[site]/components/Sidebar/Sidebar.tsx@@ -1,21 +1,20 @@"use client";+import { Funnel } from "@phosphor-icons/react/dist/ssr";import {ChartBarDecreasing,- ChartLine,LayoutDashboard,LayoutGrid,Radio,+ Rewind,Settings,User,} from "lucide-react";import Link from "next/link";import { usePathname } from "next/navigation";import { useGetSites } from "../../../../api/admin/sites";-import LiveUserCount from "./LiveUserCount";import { SiteSettings } from "../../../../components/SiteSettings/SiteSettings";-import { Button } from "../../../../components/ui/button";+import LiveUserCount from "./LiveUserCount";import { SiteSelector } from "./SiteSelector";-import { Funnel } from "@phosphor-icons/react/dist/ssr";export function Sidebar() {const { data: sites } = useGetSites();@@ -56,6 +55,12 @@ export function Sidebar() {label="Sessions"active={isActiveTab("sessions")}href={getTabPath("sessions")}+ icon={<Rewind className="w-4 h-4" />}+ />+ <SidebarLink+ label="Users"+ active={isActiveTab("users")}+ href={getTabPath("users")}icon={<User className="w-4 h-4" />}/><SidebarLinkdiff --git a/client/src/app/[site]/users/page.tsx b/client/src/app/[site]/users/page.tsxnew file mode 100644index 000000000..01ed44c41--- /dev/null+++ b/client/src/app/[site]/users/page.tsx@@ -0,0 +1,344 @@+"use client";++import { useState } from "react";+import { useParams, useRouter } from "next/navigation";+import {+ createColumnHelper,+ flexRender,+ getCoreRowModel,+ getPaginationRowModel,+ getSortedRowModel,+ SortingState,+ useReactTable,+} from "@tanstack/react-table";+import { DateTime } from "luxon";+import {+ ArrowUpDown,+ ChevronLeft,+ ChevronRight,+ ChevronsLeft,+ ChevronsRight,+ Users,+} from "lucide-react";+import { UsersResponse, useGetUsers } from "../../../api/analytics/users";+import { Button } from "../../../components/ui/button";+import { CountryFlag } from "../components/shared/icons/CountryFlag";+import { Browser } from "../components/shared/icons/Browser";+import { OperatingSystem } from "../components/shared/icons/OperatingSystem";+import { getCountryName } from "../../../lib/utils";+import { Smartphone, Tablet, Monitor } from "lucide-react";++// Set up column helper+const columnHelper = createColumnHelper<UsersResponse>();++export default function UsersPage() {+ const router = useRouter();+ const { site } = useParams();++ // State for server-side operations+ const [pagination, setPagination] = useState({+ pageIndex: 0,+ pageSize: 20,+ });+ const [sorting, setSorting] = useState<SortingState>([+ { id: "last_seen", desc: true },+ ]);++ // Convert page index to 1-based for the API+ const page = pagination.pageIndex + 1;++ // Get the first sorting column+ const sortBy = sorting.length > 0 ? sorting[0].id : "last_seen";+ const sortOrder = sorting.length > 0 && !sorting[0].desc ? "asc" : "desc";++ // Fetch data+ const { data, isLoading, isError } = useGetUsers({+ page,+ pageSize: pagination.pageSize,+ sortBy,+ sortOrder,+ });++ // Define table columns+ const columns = [+ columnHelper.accessor("user_id", {+ header: "User ID",+ cell: (info) => (+ <div className="max-w-[100px] truncate">+ {info.getValue().slice(0, 10)}...+ </div>+ ),+ }),+ columnHelper.accessor("country", {+ header: "Country",+ cell: (info) => (+ <div className="flex items-center gap-1">+ <CountryFlag country={info.getValue() || ""} />+ {info.getValue() ? getCountryName(info.getValue()) : "Unknown"}+ </div>+ ),+ }),+ columnHelper.accessor("browser", {+ header: "Browser",+ cell: (info) => (+ <div className="flex items-center gap-1">+ <Browser browser={info.getValue() || "Unknown"} />+ {info.getValue() || "Unknown"}+ </div>+ ),+ }),+ columnHelper.accessor("operating_system", {+ header: "OS",+ cell: (info) => (+ <div className="flex items-center gap-1">+ <OperatingSystem os={info.getValue() || ""} />+ {info.getValue() || "Unknown"}+ </div>+ ),+ }),+ columnHelper.accessor("device_type", {+ header: "Device",+ cell: (info) => {+ const deviceType = info.getValue();+ return (+ <div className="flex items-center gap-1">+ {deviceType === "Desktop" && <Monitor className="w-4 h-4" />}+ {deviceType === "Mobile" && <Smartphone className="w-4 h-4" />}+ {deviceType === "Tablet" && <Tablet className="w-4 h-4" />}+ {deviceType || "Unknown"}+ </div>+ );+ },+ }),+ columnHelper.accessor("pageviews", {+ header: "Pageviews",+ cell: (info) => info.getValue().toLocaleString(),+ }),+ columnHelper.accessor("events", {+ header: "Events",+ cell: (info) => info.getValue().toLocaleString(),+ }),+ columnHelper.accessor("sessions", {+ header: "Sessions",+ cell: (info) => info.getValue().toLocaleString(),+ }),+ columnHelper.accessor("last_seen", {+ header: ({ column }) => (+ <Button+ variant="ghost"+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}+ className="p-0 hover:bg-transparent"+ >+ Last Seen+ <ArrowUpDown className="ml-2 h-4 w-4" />+ </Button>+ ),+ cell: (info) => (+ <div>+ {DateTime.fromSQL(info.getValue(), {+ zone: "utc",+ })+ .toLocal()+ .toLocaleString(DateTime.DATETIME_SHORT)}+ </div>+ ),+ }),+ columnHelper.accessor("first_seen", {+ header: ({ column }) => (+ <Button+ variant="ghost"+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}+ className="p-0 hover:bg-transparent"+ >+ First Seen+ <ArrowUpDown className="ml-2 h-4 w-4" />+ </Button>+ ),+ cell: (info) => (+ <div>+ {DateTime.fromSQL(info.getValue(), {+ zone: "utc",+ })+ .toLocal()+ .toLocaleString(DateTime.DATETIME_SHORT)}+ </div>+ ),+ }),+ ];++ // Set up table instance+ const table = useReactTable({+ data: data?.data || [],+ columns,+ pageCount: data?.totalCount+ ? Math.ceil(data.totalCount / pagination.pageSize)+ : -1,+ state: {+ pagination,+ sorting,+ },+ onPaginationChange: setPagination,+ onSortingChange: setSorting,+ getCoreRowModel: getCoreRowModel(),+ getSortedRowModel: getSortedRowModel(),+ getPaginationRowModel: getPaginationRowModel(),+ manualPagination: true,+ manualSorting: true,+ });++ const handleRowClick = (userId: string) => {+ router.push(`/${site}/user/${userId}`);+ };++ if (isError) {+ return (+ <div className="p-8 text-center text-red-500">+ An error occurred while fetching users data.+ </div>+ );+ }++ return (+ <div className="space-y-4">+ <div className="flex items-center justify-between">+ <h1 className="text-2xl font-bold flex items-center gap-2">+ <Users className="w-6 h-6" />+ Users+ </h1>+ </div>++ <div className="rounded-md border border-neutral-700 bg-neutral-850">+ <div className="relative overflow-x-auto">+ <table className="w-full text-sm text-left">+ <thead className="bg-neutral-900 text-neutral-400 text-xs uppercase">+ {table.getHeaderGroups().map((headerGroup) => (+ <tr key={headerGroup.id}>+ {headerGroup.headers.map((header) => (+ <th+ key={header.id}+ scope="col"+ className="px-4 py-3 font-medium"+ >+ {header.isPlaceholder+ ? null+ : flexRender(+ header.column.columnDef.header,+ header.getContext()+ )}+ </th>+ ))}+ </tr>+ ))}+ </thead>+ <tbody>+ {isLoading ? (+ Array.from({ length: 10 }).map((_, index) => (+ <tr+ key={index}+ className="border-b border-neutral-800 animate-pulse"+ >+ {Array.from({ length: columns.length }).map(+ (_, cellIndex) => (+ <td key={cellIndex} className="px-4 py-3">+ <div className="h-4 bg-neutral-800 rounded"></div>+ </td>+ )+ )}+ </tr>+ ))+ ) : table.getRowModel().rows.length === 0 ? (+ <tr>+ <td+ colSpan={columns.length}+ className="px-4 py-8 text-center text-neutral-400"+ >+ No users found+ </td>+ </tr>+ ) : (+ table.getRowModel().rows.map((row) => (+ <tr+ key={row.id}+ className="border-b border-neutral-800 hover:bg-neutral-800 cursor-pointer"+ onClick={() => handleRowClick(row.original.user_id)}+ >+ {row.getVisibleCells().map((cell) => (+ <td key={cell.id} className="px-4 py-3">+ {flexRender(+ cell.column.columnDef.cell,+ cell.getContext()+ )}+ </td>+ ))}+ </tr>+ ))+ )}+ </tbody>+ </table>+ </div>++ {/* Pagination */}+ <div className="flex items-center justify-between px-4 py-3 border-t border-neutral-800">+ <div className="text-sm text-neutral-400">+ Showing{" "}+ <span className="font-semibold">+ {table.getState().pagination.pageIndex * pagination.pageSize + 1}+ </span>{" "}+ to{" "}+ <span className="font-semibold">+ {Math.min(+ (table.getState().pagination.pageIndex + 1) *+ pagination.pageSize,+ data?.totalCount || 0+ )}+ </span>{" "}+ of <span className="font-semibold">{data?.totalCount || 0}</span>{" "}+ users+ </div>+ <div className="flex items-center space-x-2">+ <Button+ variant="outline"+ size="sm"+ onClick={() => table.setPageIndex(0)}+ disabled={!table.getCanPreviousPage()}+ >+ <ChevronsLeft className="h-4 w-4" />+ </Button>+ <Button+ variant="outline"+ size="sm"+ onClick={() => table.previousPage()}+ disabled={!table.getCanPreviousPage()}+ >+ <ChevronLeft className="h-4 w-4" />+ </Button>+ <div className="text-sm text-neutral-400">+ Page{" "}+ <span className="font-semibold">+ {table.getState().pagination.pageIndex + 1}+ </span>{" "}+ of{" "}+ <span className="font-semibold">{table.getPageCount() || 1}</span>+ </div>+ <Button+ variant="outline"+ size="sm"+ onClick={() => table.nextPage()}+ disabled={!table.getCanNextPage()}+ >+ <ChevronRight className="h-4 w-4" />+ </Button>+ <Button+ variant="outline"+ size="sm"+ onClick={() => table.setPageIndex(table.getPageCount() - 1)}+ disabled={!table.getCanNextPage()}+ >+ <ChevronsRight className="h-4 w-4" />+ </Button>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/server/src/api/analytics/getUsers.ts b/server/src/api/analytics/getUsers.tsnew file mode 100644index 000000000..3b5367891--- /dev/null+++ b/server/src/api/analytics/getUsers.ts@@ -0,0 +1,143 @@+import { FastifyReply, FastifyRequest } from "fastify";+import clickhouse from "../../db/clickhouse/clickhouse.js";+import {+ getFilterStatement,+ getTimeStatement,+ processResults,+} from "./utils.js";+import { getUserHasAccessToSite } from "../../lib/auth-utils.js";++export type GetUsersResponse = {+ user_id: string;+ country: string;+ browser: string;+ operating_system: string;+ device_type: string;+ pageviews: number;+ events: number;+ sessions: number;+ last_seen: string;+ first_seen: string;+}[];++export interface GetUsersRequest {+ Querystring: {+ startDate: string;+ endDate: string;+ timezone: string;+ site: string;+ filters: string;+ page?: string;+ pageSize?: string;+ sortBy?: string;+ sortOrder?: string;+ };+}++export async function getUsers(+ req: FastifyRequest<GetUsersRequest>,+ res: FastifyReply+) {+ const {+ startDate,+ endDate,+ timezone,+ site,+ filters,+ page = "1",+ pageSize = "20",+ sortBy = "last_seen",+ sortOrder = "desc",+ } = req.query;++ const userHasAccessToSite = await getUserHasAccessToSite(req, site);+ if (!userHasAccessToSite) {+ return res.status(403).send({ error: "Forbidden" });+ }++ const pageNum = parseInt(page, 10);+ const pageSizeNum = parseInt(pageSize, 10);+ const offset = (pageNum - 1) * pageSizeNum;++ // Validate sort parameters+ const validSortFields = [+ "first_seen",+ "last_seen",+ "pageviews",+ "sessions",+ "events",+ ];+ const actualSortBy = validSortFields.includes(sortBy) ? sortBy : "last_seen";+ const actualSortOrder = sortOrder === "asc" ? "ASC" : "DESC";++ const filterStatement = getFilterStatement(filters);++ // Query to get user data with pagination+ const query = `+SELECT+ user_id,+ argMax(country, timestamp) AS country,+ argMax(browser, timestamp) AS browser,+ argMax(operating_system, timestamp) AS operating_system,+ argMax(device_type, timestamp) AS device_type,+ count() AS pageviews,+ countIf(type = 'custom_event') AS events,+ count(distinct session_id) AS sessions,+ max(timestamp) AS last_seen,+ min(timestamp) AS first_seen+FROM pageviews+WHERE+ site_id = ${site}+ ${filterStatement}+ ${getTimeStatement({+ date: { startDate, endDate, timezone },+ })}+GROUP BY+ user_id+ORDER BY ${actualSortBy} ${actualSortOrder}+LIMIT ${pageSizeNum} OFFSET ${offset}+ `;++ // Query to get total count+ const countQuery = `+SELECT+ count(DISTINCT user_id) AS total_count+FROM pageviews+WHERE+ site_id = ${site}+ ${filterStatement}+ ${getTimeStatement({+ date: { startDate, endDate, timezone },+ })}+ `;++ try {+ // Execute both queries in parallel+ const [result, countResult] = await Promise.all([+ clickhouse.query({+ query,+ format: "JSONEachRow",+ }),+ clickhouse.query({+ query: countQuery,+ format: "JSONEachRow",+ }),+ ]);++ const data = await processResults<GetUsersResponse[number]>(result);+ const countData = await processResults<{ total_count: number }>(+ countResult+ );+ const totalCount = countData[0]?.total_count || 0;++ return res.send({+ data,+ totalCount,+ page: pageNum,+ pageSize: pageSizeNum,+ });+ } catch (error) {+ console.error("Error fetching users:", error);+ return res.status(500).send({ error: "Failed to fetch users" });+ }+}