Skip to content

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

refactor: update AdminPage layout and remove unused components (#294)

Bill Yang7a950520313a
diff --git a/client/src/api/admin/getAdminSites.ts b/client/src/api/admin/getAdminSites.ts
new file mode 100644
index 000000000..83c752b89
--- /dev/null
+++ b/client/src/api/admin/getAdminSites.ts
@@ -0,0 +1,24 @@
+import { useQuery } from "@tanstack/react-query";
+import { BACKEND_URL } from "../../lib/const";
+import { authedFetchWithError } from "../utils";
+
+export interface AdminSiteData {
+ siteId: number;
+ domain: string;
+ createdAt: string;
+ public: boolean;
+ eventsLast24Hours: number;
+ organizationOwnerEmail: string | null;
+}
+
+export async function getAdminSites() {
+ return authedFetchWithError<AdminSiteData[]>(`${BACKEND_URL}/admin/sites`);
+}
+
+export function useAdminSites() {
+ return useQuery<AdminSiteData[]>({
+ queryKey: ["admin-sites"],
+ queryFn: getAdminSites,
+ staleTime: 60000, // 1 minute
+ });
+}
diff --git a/client/src/api/admin/getAdminUsers.ts b/client/src/api/admin/getAdminUsers.ts
new file mode 100644
index 000000000..bb07e76ae
--- /dev/null
+++ b/client/src/api/admin/getAdminUsers.ts
@@ -0,0 +1,30 @@
+import { useQuery } from "@tanstack/react-query";
+import { BACKEND_URL } from "../../lib/const";
+import { authedFetchWithError } from "../utils";
+
+export interface AdminUserData {
+ id: string;
+ name: string;
+ email: string;
+ role: string;
+ createdAt: string;
+ monthlyEventCount: number;
+ sites: {
+ siteId: number;
+ name: string;
+ domain: string;
+ createdAt: string;
+ }[];
+}
+
+export async function getAdminUsers() {
+ return authedFetchWithError<AdminUserData[]>(`${BACKEND_URL}/admin/users`);
+}
+
+export function useAdminUsers() {
+ return useQuery<AdminUserData[]>({
+ queryKey: ["admin-users"],
+ queryFn: getAdminUsers,
+ staleTime: 60000, // 1 minute
+ });
+}
diff --git a/client/src/app/admin/components/sites/SiteTablePagination.tsx b/client/src/app/admin/components/sites/SiteTablePagination.tsx
new file mode 100644
index 000000000..222daa650
--- /dev/null
+++ b/client/src/app/admin/components/sites/SiteTablePagination.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+import { Table } from "@tanstack/react-table";
+import { AdminSiteData } from "@/api/admin/getAdminSites";
+import { TablePagination } from "@/components/pagination";
+
+interface SitePaginationProps {
+ table: Table<AdminSiteData>;
+ data: AdminSiteData[] | undefined;
+ pagination: { pageIndex: number; pageSize: number };
+ setPagination: (value: { pageIndex: number; pageSize: number }) => void;
+ isLoading: boolean;
+}
+
+export function SiteTablePagination({
+ table,
+ data,
+ pagination,
+ setPagination,
+ isLoading,
+}: SitePaginationProps) {
+ return (
+ <TablePagination
+ table={table}
+ data={data ? { items: data, total: data.length } : undefined}
+ pagination={pagination}
+ setPagination={setPagination}
+ isLoading={isLoading}
+ itemName="sites"
+ />
+ );
+}
diff --git a/client/src/app/admin/components/sites/Sites.tsx b/client/src/app/admin/components/sites/Sites.tsx
new file mode 100644
index 000000000..860a36619
--- /dev/null
+++ b/client/src/app/admin/components/sites/Sites.tsx
@@ -0,0 +1,345 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useAdminSites, AdminSiteData } from "@/api/admin/getAdminSites";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { Badge } from "@/components/ui/badge";
+import { Skeleton } from "@/components/ui/skeleton";
+import { formatDistanceToNow } from "date-fns";
+import { AlertCircle, ArrowDown, ArrowUp, ArrowUpDown } from "lucide-react";
+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
+import { Input } from "@/components/ui/input";
+import { Button } from "@/components/ui/button";
+import {
+ ColumnDef,
+ flexRender,
+ getCoreRowModel,
+ useReactTable,
+ getSortedRowModel,
+ SortingState,
+ getPaginationRowModel,
+} from "@tanstack/react-table";
+import { SiteTablePagination } from "./SiteTablePagination";
+import Link from "next/link";
+
+export function Sites() {
+ const { data: sites, isLoading, isError } = useAdminSites();
+ const [searchQuery, setSearchQuery] = useState("");
+ const [sorting, setSorting] = useState<SortingState>([
+ { id: "eventsLast24Hours", desc: true },
+ ]);
+ const [pagination, setPagination] = useState({
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ // Filter sites based on search query
+ const filteredSites = useMemo(() => {
+ if (!sites) return [];
+
+ return sites.filter((site) => {
+ const lowerSearchQuery = searchQuery.toLowerCase();
+ return (
+ site.domain.toLowerCase().includes(lowerSearchQuery) ||
+ (site.organizationOwnerEmail &&
+ site.organizationOwnerEmail.toLowerCase().includes(lowerSearchQuery))
+ );
+ });
+ }, [sites, searchQuery]);
+
+ // Define columns for the table
+ const columns = useMemo<ColumnDef<AdminSiteData>[]>(
+ () => [
+ {
+ accessorKey: "siteId",
+ header: ({ column }) => (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className="p-0 hover:bg-transparent"
+ >
+ Site ID
+ {{
+ asc: <ArrowUp className="ml-2 h-4 w-4" />,
+ desc: <ArrowDown className="ml-2 h-4 w-4" />,
+ }[column.getIsSorted() as string] ?? (
+ <ArrowUpDown className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ ),
+ cell: ({ row }) => (
+ <div>
+ <Link
+ href={`/${row.getValue("siteId")}`}
+ target="_blank"
+ className="hover:underline"
+ >
+ {row.getValue("siteId")}
+ </Link>
+ </div>
+ ),
+ },
+ {
+ accessorKey: "domain",
+ header: ({ column }) => (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className="p-0 hover:bg-transparent"
+ >
+ Domain
+ {{
+ asc: <ArrowUp className="ml-2 h-4 w-4" />,
+ desc: <ArrowDown className="ml-2 h-4 w-4" />,
+ }[column.getIsSorted() as string] ?? (
+ <ArrowUpDown className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ ),
+ cell: ({ row }) => (
+ <div className="font-medium">
+ <Link
+ href={`https://${row.original.domain}`}
+ target="_blank"
+ className="hover:underline"
+ >
+ {row.getValue("domain")}
+ </Link>
+ </div>
+ ),
+ },
+ {
+ accessorKey: "createdAt",
+ header: ({ column }) => (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className="p-0 hover:bg-transparent"
+ >
+ Created
+ {{
+ asc: <ArrowUp className="ml-2 h-4 w-4" />,
+ desc: <ArrowDown className="ml-2 h-4 w-4" />,
+ }[column.getIsSorted() as string] ?? (
+ <ArrowUpDown className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ ),
+ cell: ({ row }) => (
+ <div>
+ {formatDistanceToNow(new Date(row.getValue("createdAt")), {
+ addSuffix: true,
+ })}
+ </div>
+ ),
+ },
+ {
+ accessorKey: "public",
+ header: ({ column }) => (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className="p-0 hover:bg-transparent"
+ >
+ Public
+ {{
+ asc: <ArrowUp className="ml-2 h-4 w-4" />,
+ desc: <ArrowDown className="ml-2 h-4 w-4" />,
+ }[column.getIsSorted() as string] ?? (
+ <ArrowUpDown className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ ),
+ cell: ({ row }) => (
+ <div>
+ {row.getValue("public") ? (
+ <Badge>Public</Badge>
+ ) : (
+ <Badge variant="outline">Private</Badge>
+ )}
+ </div>
+ ),
+ },
+ {
+ accessorKey: "eventsLast24Hours",
+ header: ({ column }) => (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className="p-0 hover:bg-transparent"
+ >
+ Events (24h)
+ {{
+ asc: <ArrowUp className="ml-2 h-4 w-4" />,
+ desc: <ArrowDown className="ml-2 h-4 w-4" />,
+ }[column.getIsSorted() as string] ?? (
+ <ArrowUpDown className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ ),
+ cell: ({ row }) => (
+ <div>
+ {Number(row.getValue("eventsLast24Hours")).toLocaleString()}
+ </div>
+ ),
+ },
+ {
+ accessorKey: "organizationOwnerEmail",
+ header: ({ column }) => (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className="p-0 hover:bg-transparent"
+ >
+ Owner Email
+ {{
+ asc: <ArrowUp className="ml-2 h-4 w-4" />,
+ desc: <ArrowDown className="ml-2 h-4 w-4" />,
+ }[column.getIsSorted() as string] ?? (
+ <ArrowUpDown className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ ),
+ cell: ({ row }) => (
+ <div>{row.getValue("organizationOwnerEmail") || "-"}</div>
+ ),
+ },
+ ],
+ []
+ );
+
+ // Initialize the table
+ const table = useReactTable({
+ data: filteredSites,
+ columns,
+ state: {
+ sorting,
+ pagination,
+ },
+ onSortingChange: setSorting,
+ onPaginationChange: setPagination,
+ getCoreRowModel: getCoreRowModel(),
+ getSortedRowModel: getSortedRowModel(),
+ getPaginationRowModel: getPaginationRowModel(),
+ manualPagination: false,
+ });
+
+ if (isError) {
+ return (
+ <Alert variant="destructive" className="mb-4">
+ <AlertCircle className="h-4 w-4" />
+ <AlertTitle>Error</AlertTitle>
+ <AlertDescription>
+ Failed to load sites data. Please try again later.
+ </AlertDescription>
+ </Alert>
+ );
+ }
+
+ return (
+ <div>
+ <div className="flex items-center justify-between mb-6">
+ <h2 className="text-xl font-bold">Sites</h2>
+ </div>
+
+ <div className="mb-4">
+ <Input
+ placeholder="Search by domain or owner email..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="max-w-sm"
+ />
+ </div>
+
+ <div className="rounded-md border border-neutral-700">
+ <Table>
+ <TableHeader>
+ {table.getHeaderGroups().map((headerGroup) => (
+ <TableRow key={headerGroup.id}>
+ {headerGroup.headers.map((header) => (
+ <TableHead key={header.id}>
+ {header.isPlaceholder
+ ? null
+ : flexRender(
+ header.column.columnDef.header,
+ header.getContext()
+ )}
+ </TableHead>
+ ))}
+ </TableRow>
+ ))}
+ </TableHeader>
+ <TableBody>
+ {isLoading ? (
+ Array(pagination.pageSize)
+ .fill(0)
+ .map((_, index) => (
+ <TableRow key={index}>
+ <TableCell>
+ <Skeleton className="h-5 w-10" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-40" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-24" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-16" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-16" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-40" />
+ </TableCell>
+ </TableRow>
+ ))
+ ) : table.getRowModel().rows.length === 0 ? (
+ <TableRow>
+ <TableCell
+ colSpan={columns.length}
+ className="text-center py-6 text-muted-foreground"
+ >
+ {searchQuery
+ ? "No sites match your search"
+ : "No sites found"}
+ </TableCell>
+ </TableRow>
+ ) : (
+ table.getRowModel().rows.map((row) => (
+ <TableRow key={row.id}>
+ {row.getVisibleCells().map((cell) => (
+ <TableCell key={cell.id}>
+ {flexRender(
+ cell.column.columnDef.cell,
+ cell.getContext()
+ )}
+ </TableCell>
+ ))}
+ </TableRow>
+ ))
+ )}
+ </TableBody>
+ </Table>
+ </div>
+
+ <div className="mt-4">
+ <SiteTablePagination
+ table={table}
+ data={filteredSites}
+ pagination={pagination}
+ setPagination={setPagination}
+ isLoading={isLoading}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/app/admin/components/users/OrgUsersList.tsx b/client/src/app/admin/components/users/OrgUsersList.tsx
new file mode 100644
index 000000000..d970b72ca
--- /dev/null
+++ b/client/src/app/admin/components/users/OrgUsersList.tsx
@@ -0,0 +1,313 @@
+"use client";
+
+import { useState } from "react";
+import { useRouter } from "next/navigation";
+import { useAdminUsers, AdminUserData } from "@/api/admin/getAdminUsers";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { Badge } from "@/components/ui/badge";
+import { Skeleton } from "@/components/ui/skeleton";
+import { formatDistanceToNow } from "date-fns";
+import { AlertCircle, ChevronDown, ChevronRight, User } from "lucide-react";
+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
+import { Input } from "@/components/ui/input";
+import Link from "next/link";
+import { Button } from "@/components/ui/button";
+import { TablePagination } from "@/components/pagination";
+import { authClient } from "@/lib/auth";
+import { userStore } from "@/lib/userStore";
+
+export function OrgUsersList() {
+ const router = useRouter();
+ const { data: users, isLoading, isError } = useAdminUsers();
+ const [searchQuery, setSearchQuery] = useState("");
+ const [expandedUsers, setExpandedUsers] = useState<Set<string>>(new Set());
+ const [pagination, setPagination] = useState({
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ const toggleExpand = (userId: string) => {
+ const newExpanded = new Set(expandedUsers);
+ if (newExpanded.has(userId)) {
+ newExpanded.delete(userId);
+ } else {
+ newExpanded.add(userId);
+ }
+ setExpandedUsers(newExpanded);
+ };
+
+ // Filter users based on search query
+ const filteredUsers = users?.filter((user) => {
+ const lowerSearchQuery = searchQuery.toLowerCase();
+ return (
+ user.name?.toLowerCase().includes(lowerSearchQuery) ||
+ user.email.toLowerCase().includes(lowerSearchQuery) ||
+ user.sites.some((site) =>
+ site.domain.toLowerCase().includes(lowerSearchQuery)
+ )
+ );
+ });
+
+ // Paginate the filtered users
+ const paginatedUsers = filteredUsers?.slice(
+ pagination.pageIndex * pagination.pageSize,
+ (pagination.pageIndex + 1) * pagination.pageSize
+ );
+
+ // Pagination controller for TablePagination
+ const paginationController = {
+ getState: () => ({ pagination }),
+ getCanPreviousPage: () => pagination.pageIndex > 0,
+ getCanNextPage: () =>
+ filteredUsers
+ ? pagination.pageIndex <
+ Math.ceil(filteredUsers.length / pagination.pageSize) - 1
+ : false,
+ getPageCount: () =>
+ filteredUsers ? Math.ceil(filteredUsers.length / pagination.pageSize) : 0,
+ setPageIndex: (index: number) =>
+ setPagination({ ...pagination, pageIndex: index }),
+ previousPage: () =>
+ setPagination({
+ ...pagination,
+ pageIndex: Math.max(0, pagination.pageIndex - 1),
+ }),
+ nextPage: () =>
+ setPagination({
+ ...pagination,
+ pageIndex: Math.min(
+ filteredUsers
+ ? Math.ceil(filteredUsers.length / pagination.pageSize) - 1
+ : 0,
+ pagination.pageIndex + 1
+ ),
+ }),
+ };
+
+ // Impersonation handler
+ const handleImpersonate = async (userId: string) => {
+ try {
+ await authClient.admin.impersonateUser({
+ userId,
+ });
+ router.push("/");
+ window.location.reload();
+ return true;
+ } catch (err) {
+ const errorMessage =
+ err instanceof Error ? err.message : "Unknown error occurred";
+ console.error(`Failed to impersonate user: ${errorMessage}`);
+ return false;
+ }
+ };
+
+ if (isError) {
+ return (
+ <Alert variant="destructive" className="mb-4">
+ <AlertCircle className="h-4 w-4" />
+ <AlertTitle>Error</AlertTitle>
+ <AlertDescription>
+ Failed to load organization users data. Please try again later.
+ </AlertDescription>
+ </Alert>
+ );
+ }
+
+ return (
+ <div>
+ <div className="flex items-center justify-between mb-6">
+ <h2 className="text-xl font-bold">Organization Owners</h2>
+ </div>
+
+ <div className="mb-4">
+ <Input
+ placeholder="Search by name, email or domain..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="max-w-sm"
+ />
+ </div>
+
+ <div className="rounded-md border border-neutral-700">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-8"></TableHead>
+ <TableHead>User</TableHead>
+ <TableHead>Email</TableHead>
+ <TableHead>Role</TableHead>
+ <TableHead>Created</TableHead>
+ <TableHead>Monthly Events</TableHead>
+ <TableHead>Sites</TableHead>
+ <TableHead>Actions</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {isLoading ? (
+ Array(pagination.pageSize)
+ .fill(0)
+ .map((_, index) => (
+ <TableRow key={index}>
+ <TableCell>
+ <Skeleton className="h-5 w-5" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-32" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-40" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-20" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-24" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-20" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-16" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-8 w-24" />
+ </TableCell>
+ </TableRow>
+ ))
+ ) : paginatedUsers && paginatedUsers.length > 0 ? (
+ paginatedUsers.map((user) => (
+ <>
+ <TableRow key={user.id} className="group">
+ <TableCell>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-5 w-5 p-0"
+ onClick={() => toggleExpand(user.id)}
+ >
+ {expandedUsers.has(user.id) ? (
+ <ChevronDown className="h-4 w-4" />
+ ) : (
+ <ChevronRight className="h-4 w-4" />
+ )}
+ </Button>
+ </TableCell>
+ <TableCell className="font-medium">
+ {user.name || "Unnamed"}
+ </TableCell>
+ <TableCell>{user.email}</TableCell>
+ <TableCell>{user.role}</TableCell>
+ <TableCell>
+ {formatDistanceToNow(new Date(user.createdAt), {
+ addSuffix: true,
+ })}
+ </TableCell>
+ <TableCell>
+ {user.monthlyEventCount?.toLocaleString() || 0}
+ </TableCell>
+ <TableCell>
+ <Badge>{user.sites.length}</Badge>
+ </TableCell>
+ <TableCell>
+ <Button
+ onClick={() => handleImpersonate(user.id)}
+ size="sm"
+ variant="outline"
+ className="flex items-center gap-1"
+ disabled={user.id === userStore.getState().user?.id}
+ >
+ <User className="h-4 w-4" />
+ Impersonate
+ </Button>
+ </TableCell>
+ </TableRow>
+ {expandedUsers.has(user.id) && (
+ <TableRow>
+ <TableCell
+ colSpan={8}
+ className="bg-neutral-900 py-2 px-8"
+ >
+ <div className="text-sm font-semibold mb-2">Sites:</div>
+ {user.sites.length > 0 ? (
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
+ {user.sites.map((site) => (
+ <div
+ key={site.siteId}
+ className="p-3 border border-neutral-700 rounded"
+ >
+ <div className="font-medium">
+ <Link
+ href={`/${site.siteId}`}
+ target="_blank"
+ className="hover:underline"
+ >
+ {site.name || site.domain}
+ </Link>
+ </div>
+ <div className="text-sm text-neutral-400 mt-1">
+ <Link
+ href={`https://${site.domain}`}
+ target="_blank"
+ className="hover:underline"
+ >
+ {site.domain}
+ </Link>
+ </div>
+ <div className="text-xs text-neutral-500 mt-1">
+ Created:{" "}
+ {formatDistanceToNow(
+ new Date(site.createdAt),
+ { addSuffix: true }
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div className="text-neutral-400">No sites</div>
+ )}
+ </TableCell>
+ </TableRow>
+ )}
+ </>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell
+ colSpan={8}
+ className="text-center py-6 text-muted-foreground"
+ >
+ {searchQuery
+ ? "No users match your search"
+ : "No organization owners found"}
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </div>
+
+ <div className="mt-4">
+ <TablePagination
+ table={paginationController}
+ data={
+ filteredUsers
+ ? { items: filteredUsers, total: filteredUsers.length }
+ : undefined
+ }
+ pagination={pagination}
+ setPagination={setPagination}
+ isLoading={isLoading}
+ itemName="users"
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/app/admin/components/UserFilters.tsx b/client/src/app/admin/components/users/UserFilters.tsx
similarity index 100%
rename from client/src/app/admin/components/UserFilters.tsx
rename to client/src/app/admin/components/users/UserFilters.tsx
diff --git a/client/src/app/admin/components/UserTablePagination.tsx b/client/src/app/admin/components/users/UserTablePagination.tsx
similarity index 100%
rename from client/src/app/admin/components/UserTablePagination.tsx
rename to client/src/app/admin/components/users/UserTablePagination.tsx
diff --git a/client/src/app/admin/components/UserTableSkeleton.tsx b/client/src/app/admin/components/users/UserTableSkeleton.tsx
similarity index 100%
rename from client/src/app/admin/components/UserTableSkeleton.tsx
rename to client/src/app/admin/components/users/UserTableSkeleton.tsx
diff --git a/client/src/app/admin/components/users/Users.tsx b/client/src/app/admin/components/users/Users.tsx
new file mode 100644
index 000000000..4c313445a
--- /dev/null
+++ b/client/src/app/admin/components/users/Users.tsx
@@ -0,0 +1,213 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { useRouter } from "next/navigation";
+import { Button } from "@/components/ui/button";
+import { AlertCircle } from "lucide-react";
+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
+import { StandardPage } from "@/components/StandardPage";
+import { useAdminUsers } from "@/hooks/useAdminUsers";
+import { UsersTable } from "@/app/admin/components/users/UsersTable";
+import { UserFilters } from "@/app/admin/components/users/UserFilters";
+import { UserTablePagination } from "@/app/admin/components/users/UserTablePagination";
+import { authClient } from "@/lib/auth";
+
+export function Users() {
+ const router = useRouter();
+ const [isAdmin, setIsAdmin] = useState(false);
+ const [isImpersonating, setIsImpersonating] = useState(false);
+ const [isCheckingAdmin, setIsCheckingAdmin] = useState(true);
+
+ const {
+ // Data
+ users,
+ total,
+
+ // Loading state
+ isLoading,
+ isError,
+
+ // Table state
+ sorting,
+ setSorting,
+ columnFilters,
+ setColumnFilters,
+ pagination,
+ setPagination,
+ globalFilter,
+ setGlobalFilter,
+
+ // Actions
+ handleImpersonate,
+ } = useAdminUsers();
+
+ useEffect(() => {
+ async function checkAdminPermission() {
+ try {
+ // Check if the user has impersonate permission (admin feature)
+ const result = await authClient.admin.hasPermission({
+ permissions: {
+ user: ["impersonate"],
+ },
+ });
+ setIsAdmin(result.data?.success ?? false);
+
+ // Check if the user is currently impersonating
+ const session = await authClient.getSession();
+ // Check if impersonatedBy exists in the session data
+ setIsImpersonating(Boolean(session.data?.session?.impersonatedBy));
+
+ setIsCheckingAdmin(false);
+ } catch (err) {
+ setIsAdmin(false);
+ setIsCheckingAdmin(false);
+ console.error("Error checking admin status:", err);
+ }
+ }
+
+ checkAdminPermission();
+ }, []);
+
+ // Function to stop impersonating
+ const stopImpersonating = async () => {
+ try {
+ await authClient.admin.stopImpersonating();
+ setIsImpersonating(false);
+ window.location.reload();
+ return true;
+ } catch (err) {
+ const errorMessage =
+ err instanceof Error ? err.message : "Unknown error occurred";
+ console.error(`Failed to stop impersonation: ${errorMessage}`);
+ return false;
+ }
+ };
+
+ const data = { users, total };
+
+ // Handle impersonation with navigation
+ const onImpersonate = async (userId: string) => {
+ const success = await handleImpersonate(userId);
+ if (success) {
+ router.push("/");
+ window.location.reload();
+ }
+ };
+
+ // If not admin, show access denied
+ if (!isAdmin && !isCheckingAdmin) {
+ return (
+ <div className="container mt-8">
+ <Alert variant="destructive">
+ <AlertCircle className="h-4 w-4" />
+ <AlertTitle>Access Denied</AlertTitle>
+ <AlertDescription>
+ You don't have permission to access this page. Please contact an
+ administrator if you believe this is an error.
+ </AlertDescription>
+ </Alert>
+ </div>
+ );
+ }
+
+ return (
+ <div>
+ <div className="flex items-center justify-between mb-6">
+ <h2 className="text-xl font-bold">Users</h2>
+ {isImpersonating && (
+ <Button onClick={stopImpersonating} variant="destructive">
+ Stop Impersonating
+ </Button>
+ )}
+ </div>
+
+ {isError && (
+ <Alert variant="destructive" className="mb-4">
+ <AlertCircle className="h-4 w-4" />
+ <AlertTitle>Error</AlertTitle>
+ <AlertDescription>
+ Failed to load users. Please try again later.
+ </AlertDescription>
+ </Alert>
+ )}
+
+ <div className="space-y-4">
+ {/* Filters */}
+ <UserFilters
+ table={
+ {
+ getColumn: (columnId: string) => {
+ const getFilterValue = () =>
+ columnFilters.find((filter) => filter.id === columnId)
+ ?.value ?? "";
+
+ const setFilterValue = (value: string) => {
+ const newFilters = columnFilters.filter(
+ (filter) => filter.id !== columnId
+ );
+ if (value) {
+ newFilters.push({ id: columnId, value });
+ }
+ setColumnFilters(newFilters);
+ };
+
+ return {
+ getFilterValue,
+ setFilterValue,
+ };
+ },
+ } as any
+ }
+ />
+
+ {/* Users Table */}
+ <UsersTable
+ data={data}
+ isLoading={isLoading}
+ pagination={pagination}
+ setPagination={setPagination}
+ sorting={sorting}
+ setSorting={setSorting}
+ columnFilters={columnFilters}
+ setColumnFilters={setColumnFilters}
+ globalFilter={globalFilter}
+ setGlobalFilter={setGlobalFilter}
+ onImpersonate={onImpersonate}
+ />
+
+ {/* Pagination */}
+ <UserTablePagination
+ table={
+ {
+ getCanPreviousPage: () => pagination.pageIndex > 0,
+ getCanNextPage: () =>
+ pagination.pageIndex <
+ Math.ceil(total / pagination.pageSize) - 1,
+ getPageCount: () => Math.ceil(total / pagination.pageSize),
+ getState: () => ({ pagination }),
+ setPageIndex: (index: number) =>
+ setPagination({ ...pagination, pageIndex: index }),
+ previousPage: () =>
+ setPagination({
+ ...pagination,
+ pageIndex: Math.max(0, pagination.pageIndex - 1),
+ }),
+ nextPage: () =>
+ setPagination({
+ ...pagination,
+ pageIndex: Math.min(
+ Math.ceil(total / pagination.pageSize) - 1,
+ pagination.pageIndex + 1
+ ),
+ }),
+ } as any
+ }
+ data={data}
+ pagination={pagination}
+ setPagination={setPagination}
+ isLoading={isLoading}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/app/admin/components/UsersTable.tsx b/client/src/app/admin/components/users/UsersTable.tsx
similarity index 100%
rename from client/src/app/admin/components/UsersTable.tsx
rename to client/src/app/admin/components/users/UsersTable.tsx
diff --git a/client/src/app/admin/page.tsx b/client/src/app/admin/page.tsx
index daeab1782..9717309c8 100644
--- a/client/src/app/admin/page.tsx
+++ b/client/src/app/admin/page.tsx
@@ -1,62 +1,30 @@
"use client";
-import { useEffect, useState } from "react";
-import { useRouter } from "next/navigation";
-import { Button } from "@/components/ui/button";
-import { AlertCircle } from "lucide-react";
-import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
+import { useState, useEffect } from "react";
import { StandardPage } from "@/components/StandardPage";
-import { useAdminUsers } from "@/hooks/useAdminUsers";
-import { UsersTable } from "@/app/admin/components/UsersTable";
-import { UserFilters } from "@/app/admin/components/UserFilters";
-import { UserTablePagination } from "@/app/admin/components/UserTablePagination";
+import { Users } from "./components/users/Users";
+import { Sites } from "./components/sites/Sites";
+import { OrgUsersList } from "./components/users/OrgUsersList";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
+import { AlertCircle } from "lucide-react";
import { authClient } from "@/lib/auth";
export default function AdminPage() {
- const router = useRouter();
const [isAdmin, setIsAdmin] = useState(false);
- const [isImpersonating, setIsImpersonating] = useState(false);
const [isCheckingAdmin, setIsCheckingAdmin] = useState(true);
-
- const {
- // Data
- users,
- total,
-
- // Loading state
- isLoading,
- isError,
-
- // Table state
- sorting,
- setSorting,
- columnFilters,
- setColumnFilters,
- pagination,
- setPagination,
- globalFilter,
- setGlobalFilter,
-
- // Actions
- handleImpersonate,
- } = useAdminUsers();
+ const [activeTab, setActiveTab] = useState("users");
useEffect(() => {
async function checkAdminPermission() {
try {
- // Check if the user has impersonate permission (admin feature)
+ // Check if the user has admin access
const result = await authClient.admin.hasPermission({
permissions: {
user: ["impersonate"],
},
});
setIsAdmin(result.data?.success ?? false);
-
- // Check if the user is currently impersonating
- const session = await authClient.getSession();
- // Check if impersonatedBy exists in the session data
- setIsImpersonating(Boolean(session.data?.session?.impersonatedBy));
-
setIsCheckingAdmin(false);
} catch (err) {
setIsAdmin(false);
@@ -68,32 +36,6 @@ export default function AdminPage() {
checkAdminPermission();
}, []);
- // Function to stop impersonating
- const stopImpersonating = async () => {
- try {
- await authClient.admin.stopImpersonating();
- setIsImpersonating(false);
- window.location.reload();
- return true;
- } catch (err) {
- const errorMessage =
- err instanceof Error ? err.message : "Unknown error occurred";
- console.error(`Failed to stop impersonation: ${errorMessage}`);
- return false;
- }
- };
-
- const data = { users, total };
-
- // Handle impersonation with navigation
- const onImpersonate = async (userId: string) => {
- const success = await handleImpersonate(userId);
- if (success) {
- router.push("/");
- window.location.reload();
- }
- };
-
// If not admin, show access denied
if (!isAdmin && !isCheckingAdmin) {
return (
@@ -112,102 +54,39 @@ export default function AdminPage() {
return (
<StandardPage>
- <div className="flex items-center justify-between mb-6">
+ <div className="mb-6">
<h1 className="text-2xl font-bold">Admin Dashboard</h1>
- {isImpersonating && (
- <Button onClick={stopImpersonating} variant="destructive">
- Stop Impersonating
- </Button>
- )}
</div>
- {isError && (
- <Alert variant="destructive" className="mb-4">
- <AlertCircle className="h-4 w-4" />
- <AlertTitle>Error</AlertTitle>
- <AlertDescription>
- Failed to load users. Please try again later.
- </AlertDescription>
- </Alert>
- )}
-
- <div className="space-y-4">
- {/* Filters */}
- <UserFilters
- table={
- {
- getColumn: (columnId: string) => {
- const getFilterValue = () =>
- columnFilters.find((filter) => filter.id === columnId)
- ?.value ?? "";
-
- const setFilterValue = (value: string) => {
- const newFilters = columnFilters.filter(
- (filter) => filter.id !== columnId
- );
- if (value) {
- newFilters.push({ id: columnId, value });
- }
- setColumnFilters(newFilters);
- };
-
- return {
- getFilterValue,
- setFilterValue,
- };
- },
- } as any
- }
- />
-
- {/* Users Table */}
- <UsersTable
- data={data}
- isLoading={isLoading}
- pagination={pagination}
- setPagination={setPagination}
- sorting={sorting}
- setSorting={setSorting}
- columnFilters={columnFilters}
- setColumnFilters={setColumnFilters}
- globalFilter={globalFilter}
- setGlobalFilter={setGlobalFilter}
- onImpersonate={onImpersonate}
- />
-
- {/* Pagination */}
- <UserTablePagination
- table={
- {
- getCanPreviousPage: () => pagination.pageIndex > 0,
- getCanNextPage: () =>
- pagination.pageIndex <
- Math.ceil(total / pagination.pageSize) - 1,
- getPageCount: () => Math.ceil(total / pagination.pageSize),
- getState: () => ({ pagination }),
- setPageIndex: (index: number) =>
- setPagination({ ...pagination, pageIndex: index }),
- previousPage: () =>
- setPagination({
- ...pagination,
- pageIndex: Math.max(0, pagination.pageIndex - 1),
- }),
- nextPage: () =>
- setPagination({
- ...pagination,
- pageIndex: Math.min(
- Math.ceil(total / pagination.pageSize) - 1,
- pagination.pageIndex + 1
- ),
- }),
- } as any
- }
- data={data}
- pagination={pagination}
- setPagination={setPagination}
- isLoading={isLoading}
- />
- </div>
+ <Tabs defaultValue="users" value={activeTab} onValueChange={setActiveTab}>
+ <TabsList className="mb-4">
+ <TabsTrigger value="users">Users</TabsTrigger>
+ <TabsTrigger value="org-users">Organization Owners</TabsTrigger>
+ <TabsTrigger value="sites">Sites</TabsTrigger>
+ <TabsTrigger value="settings">Settings</TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="users">
+ <Users />
+ </TabsContent>
+
+ <TabsContent value="org-users">
+ <OrgUsersList />
+ </TabsContent>
+
+ <TabsContent value="sites">
+ <Sites />
+ </TabsContent>
+
+ <TabsContent value="settings">
+ <div className="p-4 border rounded-md">
+ <h2 className="text-xl font-bold mb-4">Admin Settings</h2>
+ <p className="text-muted-foreground">
+ Settings panel coming soon...
+ </p>
+ </div>
+ </TabsContent>
+ </Tabs>
</StandardPage>
);
}
diff --git a/docker-compose.yml b/docker-compose.yml
index d1d4029da..3d90a740d 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -80,7 +80,6 @@ services:
- BETTER_AUTH_SECRET=${BETTER_AUTH_SECRET}
- BASE_URL=${BASE_URL}
- DISABLE_SIGNUP=${DISABLE_SIGNUP}
- - RESEND_API_KEY=${RESEND_API_KEY}
depends_on:
clickhouse:
condition: service_healthy
diff --git a/server/src/api/admin/getAdminSites.ts b/server/src/api/admin/getAdminSites.ts
new file mode 100644
index 000000000..e5d9ff83a
--- /dev/null
+++ b/server/src/api/admin/getAdminSites.ts
@@ -0,0 +1,100 @@
+import { eq } from "drizzle-orm";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { DateTime } from "luxon";
+import clickhouse from "../../db/clickhouse/clickhouse.js";
+import { db } from "../../db/postgres/postgres.js";
+import { member, user, sites } from "../../db/postgres/schema.js";
+import { getSessionFromReq } from "../../lib/auth-utils.js";
+
+// Define event count result type
+interface EventCountResult {
+ site_id: string;
+ total_events: number;
+}
+
+export async function getAdminSites(
+ request: FastifyRequest,
+ reply: FastifyReply
+) {
+ const session = await getSessionFromReq(request);
+
+ const userRecord = await db
+ .select({ godMode: user.godMode })
+ .from(user)
+ .where(eq(user.id, session?.user.id ?? ""))
+ .limit(1);
+
+ if (!userRecord || !userRecord[0].godMode) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ // Get all sites (including organizationId for owner lookup)
+ const sitesData = await db.query.sites.findMany();
+
+ // Get organization owners and their emails
+ const orgOwners = await db
+ .select({
+ organizationId: member.organizationId,
+ userId: member.userId,
+ email: user.email,
+ })
+ .from(member)
+ .innerJoin(user, eq(member.userId, user.id))
+ .where(eq(member.role, "owner"));
+
+ // Create map of organization IDs to owner emails
+ const orgOwnerMap = new Map();
+ for (const owner of orgOwners) {
+ orgOwnerMap.set(owner.organizationId, owner.email);
+ }
+
+ // Get event counts for the past 24 hours from Clickhouse
+ const now = DateTime.now();
+ const yesterday = now.minus({ hours: 24 });
+
+ const eventCountsResult = await clickhouse.query({
+ query: `
+ SELECT
+ site_id,
+ sum(event_count) as total_events
+ FROM
+ hourly_events_by_site_mv_target
+ WHERE
+ event_hour >= toDateTime('${yesterday.toFormat("yyyy-MM-dd HH:mm:ss")}') AND
+ event_hour <= toDateTime('${now.toFormat("yyyy-MM-dd HH:mm:ss")}')
+ GROUP BY
+ site_id
+ `,
+ format: "JSONEachRow",
+ });
+
+ const rawEventCounts = await eventCountsResult.json();
+
+ // Create map of site IDs to event counts
+ const siteEventMap = new Map<number, number>();
+
+ // Type assertion for the events data
+ const eventCounts = rawEventCounts as EventCountResult[];
+ for (const event of eventCounts) {
+ siteEventMap.set(Number(event.site_id), event.total_events);
+ }
+
+ // Combine all data
+ const enrichedSites = sitesData.map((site) => {
+ return {
+ siteId: site.siteId,
+ domain: site.domain,
+ createdAt: site.createdAt,
+ public: site.public,
+ eventsLast24Hours: siteEventMap.get(site.siteId) || 0,
+ organizationOwnerEmail: site.organizationId
+ ? orgOwnerMap.get(site.organizationId)
+ : null,
+ };
+ });
+
+ // Sort by events count in descending order
+ enrichedSites.sort((a, b) => b.eventsLast24Hours - a.eventsLast24Hours);
+
+ return reply.status(200).send(enrichedSites);
+}
diff --git a/server/src/api/admin/getAdminUsers.ts b/server/src/api/admin/getAdminUsers.ts
new file mode 100644
index 000000000..ccf35f9fb
--- /dev/null
+++ b/server/src/api/admin/getAdminUsers.ts
@@ -0,0 +1,111 @@
+import { eq, inArray } from "drizzle-orm";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { db } from "../../db/postgres/postgres.js";
+import { member, sites, user } from "../../db/postgres/schema.js";
+import { getSessionFromReq } from "../../lib/auth-utils.js";
+
+export async function getAdminUsers(
+ request: FastifyRequest,
+ reply: FastifyReply
+) {
+ const session = await getSessionFromReq(request);
+
+ const userRecord = await db
+ .select({ godMode: user.godMode })
+ .from(user)
+ .where(eq(user.id, session?.user.id ?? ""))
+ .limit(1);
+
+ if (!userRecord || !userRecord[0].godMode) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ // Get all organization owners
+ const orgOwners = await db
+ .select({
+ userId: member.userId,
+ organizationId: member.organizationId,
+ })
+ .from(member)
+ .where(eq(member.role, "owner"));
+
+ // Create a map of user IDs to their owned organization IDs
+ const userOrgMap = new Map<string, string[]>();
+ for (const owner of orgOwners) {
+ if (!userOrgMap.has(owner.userId)) {
+ userOrgMap.set(owner.userId, []);
+ }
+ userOrgMap.get(owner.userId)?.push(owner.organizationId);
+ }
+
+ // Get all user details for organization owners
+ const allOrgOwnerIds = [...userOrgMap.keys()];
+ const ownerUsers = await db
+ .select({
+ id: user.id,
+ name: user.name,
+ email: user.email,
+ role: user.role,
+ createdAt: user.createdAt,
+ monthlyEventCount: user.monthlyEventCount,
+ })
+ .from(user)
+ .where(
+ allOrgOwnerIds.length > 0 ? inArray(user.id, allOrgOwnerIds) : undefined
+ );
+
+ // Get all sites belonging to the organizations
+ const allOrgIds = [
+ ...new Set(orgOwners.map((owner) => owner.organizationId)),
+ ];
+ const orgSites = await db
+ .select({
+ siteId: sites.siteId,
+ name: sites.name,
+ domain: sites.domain,
+ createdAt: sites.createdAt,
+ organizationId: sites.organizationId,
+ })
+ .from(sites)
+ .where(
+ allOrgIds.length > 0
+ ? inArray(sites.organizationId, allOrgIds)
+ : undefined
+ );
+
+ // Create a map of organization IDs to their sites
+ const orgSitesMap = new Map<string, any[]>();
+ for (const site of orgSites) {
+ if (site.organizationId) {
+ if (!orgSitesMap.has(site.organizationId)) {
+ orgSitesMap.set(site.organizationId, []);
+ }
+ orgSitesMap.get(site.organizationId)?.push({
+ siteId: site.siteId,
+ name: site.name,
+ domain: site.domain,
+ createdAt: site.createdAt,
+ });
+ }
+ }
+
+ // Combine user data with their organizations' sites
+ const enrichedUsers = ownerUsers.map((user) => {
+ const userOrgIds = userOrgMap.get(user.id) || [];
+ const userSites = userOrgIds.flatMap(
+ (orgId) => orgSitesMap.get(orgId) || []
+ );
+
+ return {
+ ...user,
+ sites: userSites,
+ };
+ });
+
+ // Sort by monthlyEventCount in descending order
+ enrichedUsers.sort(
+ (a, b) => (b.monthlyEventCount || 0) - (a.monthlyEventCount || 0)
+ );
+
+ return reply.status(200).send(enrichedUsers);
+}
diff --git a/server/src/index.ts b/server/src/index.ts
index 59e588fdf..d3701880e 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -59,6 +59,8 @@ import { IS_CLOUD } from "./lib/const.js";
import { addUserToOrganization } from "./api/user/addUserToOrganization.js";
import { getConfig } from "./api/getConfig.js";
import { getPageTitles } from "./api/analytics/getPageTitles.js";
+import { getAdminSites } from "./api/admin/getAdminSites.js";
+import { getAdminUsers } from "./api/admin/getAdminUsers.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -153,7 +155,6 @@ const ANALYTICS_ROUTES = [
"/api/analytics/events/names/",
"/api/analytics/events/properties/",
"/events/",
-
"/get-site",
];
@@ -256,6 +257,10 @@ if (IS_CLOUD) {
{ config: { rawBody: true } },
handleWebhook
); // Use rawBody parser config for webhook
+
+ // Admin Routes
+ server.get("/admin/sites", getAdminSites);
+ server.get("/admin/users", getAdminUsers);
}
server.post("/track", trackEvent);