Skip to content

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

feat(admin): add organizations tab and related API endpoint

Bill Yangae025e20af37
diff --git a/client/src/api/admin/getAdminOrganizations.ts b/client/src/api/admin/getAdminOrganizations.ts
new file mode 100644
index 000000000..2e2700d94
--- /dev/null
+++ b/client/src/api/admin/getAdminOrganizations.ts
@@ -0,0 +1,47 @@
+import { useQuery } from "@tanstack/react-query";
+import { BACKEND_URL } from "../../lib/const";
+import { authedFetchWithError } from "../utils";
+
+export interface AdminOrganizationData {
+ id: string;
+ name: string;
+ createdAt: string;
+ monthlyEventCount: number;
+ overMonthlyLimit: boolean;
+ subscription: {
+ id: string | null;
+ planName: string;
+ status: string;
+ eventLimit: number;
+ currentPeriodEnd: Date;
+ cancelAtPeriodEnd?: boolean;
+ interval?: string;
+ };
+ sites: {
+ siteId: number;
+ name: string;
+ domain: string;
+ createdAt: string;
+ eventsLast24Hours: number;
+ }[];
+ members: {
+ userId: string;
+ name: string;
+ email: string;
+ role: string;
+ createdAt: string;
+ }[];
+}
+
+export async function getAdminOrganizations() {
+ return authedFetchWithError<AdminOrganizationData[]>(
+ `${BACKEND_URL}/admin/organizations`
+ );
+}
+
+export function useAdminOrganizations() {
+ return useQuery<AdminOrganizationData[]>({
+ queryKey: ["admin-organizations"],
+ queryFn: getAdminOrganizations,
+ });
+}
diff --git a/client/src/app/admin/components/organizations/Organizations.tsx b/client/src/app/admin/components/organizations/Organizations.tsx
new file mode 100644
index 000000000..e6e984451
--- /dev/null
+++ b/client/src/app/admin/components/organizations/Organizations.tsx
@@ -0,0 +1,575 @@
+"use client";
+
+import { useState, useMemo, useCallback } from "react";
+import { useRouter } from "next/navigation";
+import {
+ useAdminOrganizations,
+ AdminOrganizationData,
+} from "@/api/admin/getAdminOrganizations";
+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 {
+ ChevronDown,
+ ChevronRight,
+ User,
+ Building2,
+ CreditCard,
+ UserCheck,
+ ExternalLink,
+} from "lucide-react";
+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";
+import {
+ ColumnDef,
+ flexRender,
+ getCoreRowModel,
+ useReactTable,
+ getSortedRowModel,
+ SortingState,
+} from "@tanstack/react-table";
+import { SortableHeader } from "../shared/SortableHeader";
+import { SearchInput } from "../shared/SearchInput";
+import { ErrorAlert } from "../shared/ErrorAlert";
+import { AdminLayout } from "../shared/AdminLayout";
+
+export function Organizations() {
+ const router = useRouter();
+ const { data: organizations, isLoading, isError } = useAdminOrganizations();
+
+ const [searchQuery, setSearchQuery] = useState("");
+ const [expandedOrgs, setExpandedOrgs] = useState<Set<string>>(new Set());
+ const [sorting, setSorting] = useState<SortingState>([]);
+ const [pagination, setPagination] = useState({
+ pageIndex: 0,
+ pageSize: 50,
+ });
+
+ const toggleExpand = useCallback(
+ (orgId: string) => {
+ const newExpanded = new Set(expandedOrgs);
+ if (newExpanded.has(orgId)) {
+ newExpanded.delete(orgId);
+ } else {
+ newExpanded.add(orgId);
+ }
+ setExpandedOrgs(newExpanded);
+ },
+ [expandedOrgs]
+ );
+
+ // Filter organizations based on search query
+ const filteredOrganizations = useMemo(() => {
+ if (!organizations) return [];
+
+ if (!searchQuery.trim()) return organizations;
+
+ const lowerSearchQuery = searchQuery.toLowerCase();
+ return organizations.filter((org) => {
+ return (
+ org.name.toLowerCase().includes(lowerSearchQuery) ||
+ org.sites.some((site) =>
+ site.domain.toLowerCase().includes(lowerSearchQuery)
+ ) ||
+ org.members.some(
+ (member) =>
+ member.email.toLowerCase().includes(lowerSearchQuery) ||
+ member.name.toLowerCase().includes(lowerSearchQuery)
+ )
+ );
+ });
+ }, [organizations, searchQuery]);
+
+ // Impersonation handler
+ const handleImpersonate = useCallback(
+ async (userId: string) => {
+ try {
+ await authClient.admin.impersonateUser({
+ userId,
+ });
+ window.location.reload();
+ router.push("/");
+ return true;
+ } catch (err) {
+ const errorMessage =
+ err instanceof Error ? err.message : "Unknown error occurred";
+ console.error(`Failed to impersonate user: ${errorMessage}`);
+ return false;
+ }
+ },
+ [router]
+ );
+
+ // Format subscription status
+ const formatSubscriptionStatus = (
+ subscription: AdminOrganizationData["subscription"]
+ ) => {
+ if (!subscription.id) {
+ return <Badge variant="secondary">Free</Badge>;
+ }
+
+ const statusColor =
+ subscription.status === "active"
+ ? "default"
+ : subscription.status === "canceled"
+ ? "destructive"
+ : "secondary";
+
+ return <Badge variant={statusColor}>{subscription.planName}</Badge>;
+ };
+
+ // Define columns for the table
+ const columns = useMemo<ColumnDef<AdminOrganizationData>[]>(
+ () => [
+ {
+ id: "expand",
+ header: "",
+ cell: ({ row }) => (
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-5 w-5 p-0"
+ onClick={() => toggleExpand(row.original.id)}
+ >
+ {expandedOrgs.has(row.original.id) ? (
+ <ChevronDown className="h-4 w-4" />
+ ) : (
+ <ChevronRight className="h-4 w-4" />
+ )}
+ </Button>
+ ),
+ enableSorting: false,
+ },
+ {
+ accessorKey: "name",
+ header: ({ column }) => (
+ <SortableHeader column={column}>Organization</SortableHeader>
+ ),
+ cell: ({ row }) => (
+ <div className="font-medium">{row.getValue("name")}</div>
+ ),
+ },
+ {
+ accessorKey: "createdAt",
+ header: ({ column }) => (
+ <SortableHeader column={column}>Created</SortableHeader>
+ ),
+ cell: ({ row }) =>
+ formatDistanceToNow(new Date(row.getValue("createdAt")), {
+ addSuffix: true,
+ }),
+ },
+ {
+ accessorKey: "monthlyEventCount",
+ header: ({ column }) => (
+ <SortableHeader column={column}>Monthly Events</SortableHeader>
+ ),
+ cell: ({ row }) => {
+ const count = row.getValue("monthlyEventCount") as number;
+ const isOverLimit = row.original.overMonthlyLimit;
+ return (
+ <div className={`font-medium ${isOverLimit ? "text-red-400" : ""}`}>
+ {count?.toLocaleString() || 0}
+ {isOverLimit && <span className="text-red-400 ml-1">⚠️</span>}
+ </div>
+ );
+ },
+ },
+ {
+ id: "eventsLast24Hours",
+ header: ({ column }) => (
+ <SortableHeader column={column}>24h Events</SortableHeader>
+ ),
+ accessorFn: (row) =>
+ row.sites.reduce(
+ (total, site) => total + Number(site.eventsLast24Hours || 0),
+ 0
+ ),
+ cell: ({ row }) => {
+ const total = row.original.sites.reduce(
+ (sum, site) => sum + Number(site.eventsLast24Hours || 0),
+ 0
+ );
+ return total.toLocaleString();
+ },
+ },
+ {
+ id: "subscription",
+ header: ({ column }) => (
+ <SortableHeader column={column}>Subscription</SortableHeader>
+ ),
+ accessorFn: (row) => row.subscription.planName,
+ cell: ({ row }) => formatSubscriptionStatus(row.original.subscription),
+ },
+ {
+ id: "sites",
+ header: ({ column }) => (
+ <SortableHeader column={column}>Sites</SortableHeader>
+ ),
+ accessorFn: (row) => row.sites.length,
+ cell: ({ row }) => (
+ <Badge variant="outline">{row.original.sites.length}</Badge>
+ ),
+ },
+ {
+ id: "members",
+ header: ({ column }) => (
+ <SortableHeader column={column}>Members</SortableHeader>
+ ),
+ accessorFn: (row) => row.members.length,
+ cell: ({ row }) => (
+ <Badge variant="outline">{row.original.members.length}</Badge>
+ ),
+ },
+ ],
+ [toggleExpand]
+ );
+
+ // Initialize the table
+ const table = useReactTable({
+ data: filteredOrganizations || [],
+ columns,
+ state: {
+ sorting,
+ },
+ onSortingChange: setSorting,
+ getCoreRowModel: getCoreRowModel(),
+ getSortedRowModel: getSortedRowModel(),
+ manualSorting: false,
+ });
+
+ // Paginate the sorted and filtered organizations
+ const paginatedOrganizations = table
+ .getRowModel()
+ .rows.slice(
+ pagination.pageIndex * pagination.pageSize,
+ (pagination.pageIndex + 1) * pagination.pageSize
+ );
+
+ // Pagination controller for TablePagination
+ const paginationController = {
+ getState: () => ({ pagination }),
+ getCanPreviousPage: () => pagination.pageIndex > 0,
+ getCanNextPage: () =>
+ table.getRowModel().rows.length > 0
+ ? pagination.pageIndex <
+ Math.ceil(table.getRowModel().rows.length / pagination.pageSize) - 1
+ : false,
+ getPageCount: () =>
+ table.getRowModel().rows.length > 0
+ ? Math.ceil(table.getRowModel().rows.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(
+ table.getRowModel().rows.length > 0
+ ? Math.ceil(table.getRowModel().rows.length / pagination.pageSize) -
+ 1
+ : 0,
+ pagination.pageIndex + 1
+ ),
+ }),
+ };
+
+ if (isError) {
+ return (
+ <AdminLayout title="Organizations">
+ <ErrorAlert message="Failed to load organizations data. Please try again later." />
+ </AdminLayout>
+ );
+ }
+
+ return (
+ <AdminLayout title="Organizations">
+ <div className="mb-4">
+ <SearchInput
+ placeholder="Search by name, slug, domain, or member email..."
+ value={searchQuery}
+ onChange={setSearchQuery}
+ />
+ </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}
+ className={header.id === "expand" ? "w-8" : ""}
+ >
+ {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-5" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-32" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-24" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-24" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-20" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-20" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-16" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-16" />
+ </TableCell>
+ </TableRow>
+ ))
+ ) : paginatedOrganizations && paginatedOrganizations.length > 0 ? (
+ paginatedOrganizations.map((row) => (
+ <>
+ <TableRow key={row.id} className="group">
+ {row.getVisibleCells().map((cell) => (
+ <TableCell key={cell.id}>
+ {flexRender(
+ cell.column.columnDef.cell,
+ cell.getContext()
+ )}
+ </TableCell>
+ ))}
+ </TableRow>
+ {expandedOrgs.has(row.original.id) && (
+ <TableRow>
+ <TableCell
+ colSpan={columns.length}
+ className="bg-neutral-900 py-4 px-8"
+ >
+ <div className="space-y-6">
+ {/* Subscription Details */}
+ <div>
+ <div className="flex items-center gap-2 text-sm font-semibold mb-3">
+ <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>
+ <div className="text-xs text-neutral-400 uppercase tracking-wide">
+ Plan
+ </div>
+ <div className="font-medium">
+ {row.original.subscription.planName}
+ </div>
+ </div>
+ <div>
+ <div className="text-xs text-neutral-400 uppercase tracking-wide">
+ Status
+ </div>
+ <div className="font-medium">
+ {row.original.subscription.status}
+ </div>
+ </div>
+ <div>
+ <div className="text-xs text-neutral-400 uppercase tracking-wide">
+ Event Limit
+ </div>
+ <div className="font-medium">
+ {row.original.subscription.eventLimit?.toLocaleString() ||
+ "Unlimited"}
+ </div>
+ </div>
+ {row.original.subscription.currentPeriodEnd && (
+ <div>
+ <div className="text-xs text-neutral-400 uppercase tracking-wide">
+ Period End
+ </div>
+ <div className="font-medium">
+ {formatDistanceToNow(
+ new Date(
+ row.original.subscription.currentPeriodEnd
+ ),
+ {
+ addSuffix: true,
+ }
+ )}
+ </div>
+ </div>
+ )}
+ {row.original.subscription.cancelAtPeriodEnd && (
+ <div>
+ <div className="text-xs text-neutral-400 uppercase tracking-wide">
+ Cancellation
+ </div>
+ <div className="font-medium text-orange-400">
+ Cancels at period end
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Sites */}
+ <div>
+ <div className="flex items-center gap-2 text-sm font-semibold mb-3">
+ <Building2 className="h-4 w-4" />
+ Sites ({row.original.sites.length})
+ </div>
+ {row.original.sites.length > 0 ? (
+ <div className="flex flex-wrap gap-2">
+ {row.original.sites.map((site) => (
+ <Link
+ key={site.siteId}
+ href={`/${site.siteId}`}
+ target="_blank"
+ className="inline-flex items-center gap-2 px-3 py-2 bg-neutral-800 hover:bg-neutral-700 border border-neutral-600 rounded-md text-sm transition-colors"
+ >
+ <div className="flex flex-col">
+ <span className="font-medium">
+ {site.domain}
+ </span>
+ <span className="text-xs text-neutral-400">
+ {site.eventsLast24Hours.toLocaleString()}{" "}
+ events (24h)
+ </span>
+ </div>
+ <ExternalLink className="h-3 w-3" />
+ </Link>
+ ))}
+ </div>
+ ) : (
+ <div className="text-neutral-400 p-4 border border-neutral-700 rounded">
+ No sites
+ </div>
+ )}
+ </div>
+
+ {/* Members */}
+ <div>
+ <div className="flex items-center gap-2 text-sm font-semibold mb-3">
+ <User className="h-4 w-4" />
+ Members ({row.original.members.length})
+ </div>
+ {row.original.members.length > 0 ? (
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
+ {row.original.members.map((member) => (
+ <div
+ key={member.userId}
+ className="p-3 border border-neutral-700 rounded flex items-center justify-between"
+ >
+ <div>
+ <div className="font-medium">
+ {member.name}
+ </div>
+ <div className="text-sm text-neutral-400">
+ {member.email}
+ </div>
+ <div className="text-xs text-neutral-500 mt-1">
+ <Badge
+ variant="outline"
+ className="text-xs"
+ >
+ {member.role}
+ </Badge>
+ </div>
+ </div>
+ <Button
+ onClick={() =>
+ handleImpersonate(member.userId)
+ }
+ size="sm"
+ variant="outline"
+ className="flex items-center gap-1"
+ disabled={
+ member.userId ===
+ userStore.getState().user?.id
+ }
+ >
+ <UserCheck className="h-3 w-3" />
+ Impersonate
+ </Button>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div className="text-neutral-400 p-4 border border-neutral-700 rounded">
+ No members
+ </div>
+ )}
+ </div>
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+ </>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell
+ colSpan={columns.length}
+ className="text-center py-6 text-muted-foreground"
+ >
+ {searchQuery
+ ? "No organizations match your search"
+ : "No organizations found"}
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </div>
+
+ <div className="mt-4">
+ <TablePagination
+ table={paginationController}
+ data={
+ table.getRowModel().rows.length > 0
+ ? {
+ items: table.getRowModel().rows,
+ total: table.getRowModel().rows.length,
+ }
+ : undefined
+ }
+ pagination={pagination}
+ setPagination={setPagination}
+ isLoading={isLoading}
+ itemName="organizations"
+ />
+ </div>
+ </AdminLayout>
+ );
+}
diff --git a/client/src/app/admin/page.tsx b/client/src/app/admin/page.tsx
index 29c494492..12df7b880 100644
--- a/client/src/app/admin/page.tsx
+++ b/client/src/app/admin/page.tsx
@@ -6,6 +6,7 @@ import { useState } from "react";
import { Sites } from "./components/sites/Sites";
import { OrgUsersList } from "./components/users/OrgUsersList";
import { Users } from "./components/users/Users";
+import { Organizations } from "./components/organizations/Organizations";
import { AdminLayout } from "./components/shared/AdminLayout";
export default function AdminPage() {
@@ -22,6 +23,7 @@ export default function AdminPage() {
<TabsList className="mb-4">
<TabsTrigger value="users">Users</TabsTrigger>
<TabsTrigger value="org-users">Organization Owners</TabsTrigger>
+ <TabsTrigger value="organizations">Organizations</TabsTrigger>
<TabsTrigger value="sites">Sites</TabsTrigger>
<TabsTrigger value="settings">Settings</TabsTrigger>
</TabsList>
@@ -34,6 +36,10 @@ export default function AdminPage() {
<OrgUsersList />
</TabsContent>
+ <TabsContent value="organizations">
+ <Organizations />
+ </TabsContent>
+
<TabsContent value="sites">
<Sites />
</TabsContent>
diff --git a/server/src/api/admin/getAdminOrganizations.ts b/server/src/api/admin/getAdminOrganizations.ts
new file mode 100644
index 000000000..f5c3a067f
--- /dev/null
+++ b/server/src/api/admin/getAdminOrganizations.ts
@@ -0,0 +1,285 @@
+import { eq, inArray } 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, sites, user } from "../../db/postgres/schema.js";
+import { getIsUserAdmin } from "../../lib/auth-utils.js";
+import {
+ DEFAULT_EVENT_LIMIT,
+ getStripePrices,
+ StripePlan,
+} from "../../lib/const.js";
+import { stripe } from "../../lib/stripe.js";
+
+// Define event count result type
+interface EventCountResult {
+ site_id: string;
+ total_events: number;
+}
+
+// Function to find plan details by price ID
+function findPlanDetails(priceId: string): StripePlan | undefined {
+ return getStripePrices().find(
+ (plan: StripePlan) =>
+ plan.priceId === priceId ||
+ (plan.annualDiscountPriceId && plan.annualDiscountPriceId === priceId)
+ );
+}
+
+function getStartOfNextMonth() {
+ return DateTime.now().startOf("month").plus({ months: 1 }).toJSDate();
+}
+
+export interface AdminOrganizationData {
+ id: string;
+ name: string;
+ createdAt: string;
+ monthlyEventCount: number;
+ overMonthlyLimit: boolean;
+ subscription: {
+ id: string | null;
+ planName: string;
+ status: string;
+ eventLimit: number;
+ currentPeriodEnd: Date;
+ cancelAtPeriodEnd?: boolean;
+ interval?: string;
+ };
+ sites: {
+ siteId: number;
+ name: string;
+ domain: string;
+ createdAt: string;
+ eventsLast24Hours: number;
+ }[];
+ members: {
+ userId: string;
+ name: string;
+ email: string;
+ role: string;
+ createdAt: string;
+ }[];
+}
+
+export async function getAdminOrganizations(
+ request: FastifyRequest,
+ reply: FastifyReply
+) {
+ const isAdmin = await getIsUserAdmin(request);
+
+ if (!isAdmin) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ try {
+ // Get all organizations with their basic data
+ const organizationsData = await db.query.organization.findMany({
+ orderBy: (organization, { desc }) => [
+ desc(organization.monthlyEventCount),
+ ],
+ });
+
+ // Get all members for all organizations
+ const allMembers = await db
+ .select({
+ organizationId: member.organizationId,
+ userId: member.userId,
+ role: member.role,
+ createdAt: member.createdAt,
+ userName: user.name,
+ userEmail: user.email,
+ })
+ .from(member)
+ .innerJoin(user, eq(member.userId, user.id));
+
+ // Create map of organization IDs to their members
+ const orgMembersMap = new Map<string, any[]>();
+ for (const memberData of allMembers) {
+ if (!orgMembersMap.has(memberData.organizationId)) {
+ orgMembersMap.set(memberData.organizationId, []);
+ }
+ orgMembersMap.get(memberData.organizationId)?.push({
+ userId: memberData.userId,
+ name: memberData.userName,
+ email: memberData.userEmail,
+ role: memberData.role,
+ createdAt: memberData.createdAt,
+ });
+ }
+
+ // Get all sites for all organizations
+ const allOrgIds = organizationsData.map((org) => org.id);
+ 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
+ );
+
+ // Get event counts for the past 24 hours from ClickHouse
+ const now = DateTime.now();
+ const yesterday = now.minus({ hours: 24 });
+
+ let siteEventMap = new Map<number, number>();
+
+ try {
+ 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();
+ const eventCounts = rawEventCounts as EventCountResult[];
+
+ for (const event of eventCounts) {
+ siteEventMap.set(Number(event.site_id), event.total_events);
+ }
+ } catch (clickhouseError) {
+ console.warn(
+ "ClickHouse query failed, continuing without event counts:",
+ clickhouseError
+ );
+ }
+
+ // Create map of organization IDs to their sites with event counts
+ 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,
+ eventsLast24Hours: siteEventMap.get(site.siteId) || 0,
+ });
+ }
+ }
+
+ // Get subscription data for organizations with Stripe customer IDs
+ const orgsWithStripe = organizationsData.filter(
+ (org) => org.stripeCustomerId
+ );
+ const stripeCustomerIds = new Set(
+ orgsWithStripe.map((org) => org.stripeCustomerId!)
+ );
+
+ // Use bulk fetch approach: get all active subscriptions and filter by customer IDs
+ const subscriptionMap = new Map<string, any>();
+
+ if (stripe && stripeCustomerIds.size > 0) {
+ try {
+ // Fetch all active subscriptions in batches using pagination
+ let hasMore = true;
+ let startingAfter: string | undefined;
+
+ while (hasMore) {
+ const subscriptions = await stripe.subscriptions.list({
+ status: "active",
+ limit: 100, // Maximum allowed by Stripe
+ expand: ["data.plan.product"],
+ ...(startingAfter && { starting_after: startingAfter }),
+ });
+
+ // Process subscriptions for our customers
+ for (const subscription of subscriptions.data) {
+ const customerId = subscription.customer as string;
+
+ if (stripeCustomerIds.has(customerId)) {
+ const subscriptionItem = subscription.items.data[0];
+ const priceId = subscriptionItem.price.id;
+
+ if (priceId) {
+ const planDetails = findPlanDetails(priceId);
+
+ subscriptionMap.set(customerId, {
+ id: subscription.id,
+ planName: planDetails?.name || "Unknown Plan",
+ status: subscription.status,
+ currentPeriodStart: new Date(
+ subscriptionItem.current_period_start * 1000
+ ),
+ currentPeriodEnd: new Date(
+ subscriptionItem.current_period_end * 1000
+ ),
+ cancelAtPeriodEnd: subscription.cancel_at_period_end,
+ eventLimit: planDetails?.limits.events || 0,
+ interval:
+ subscriptionItem.price.recurring?.interval ?? "unknown",
+ });
+ }
+ }
+ }
+
+ hasMore = subscriptions.has_more;
+ if (hasMore && subscriptions.data.length > 0) {
+ startingAfter =
+ subscriptions.data[subscriptions.data.length - 1].id;
+ }
+
+ // Rate limiting: wait 50ms between requests (20 req/s)
+ if (hasMore) {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ }
+ } catch (error) {
+ console.error("Error fetching subscriptions from Stripe:", error);
+ }
+ }
+
+ // Build the final response with subscription data
+ const enrichedOrganizations: AdminOrganizationData[] =
+ organizationsData.map((org) => {
+ const subscriptionData = org.stripeCustomerId
+ ? subscriptionMap.get(org.stripeCustomerId)
+ : null;
+
+ return {
+ id: org.id,
+ name: org.name,
+ createdAt: org.createdAt,
+ monthlyEventCount: org.monthlyEventCount || 0,
+ overMonthlyLimit: org.overMonthlyLimit || false,
+ subscription: subscriptionData || {
+ id: null,
+ planName: "free",
+ status: "free",
+ eventLimit: DEFAULT_EVENT_LIMIT,
+ currentPeriodEnd: getStartOfNextMonth(),
+ },
+ sites: orgSitesMap.get(org.id) || [],
+ members: orgMembersMap.get(org.id) || [],
+ };
+ });
+
+ return reply.status(200).send(enrichedOrganizations);
+ } catch (error) {
+ console.error("Get Admin Organizations Error:", error);
+ return reply.status(500).send({
+ error: "Failed to fetch organizations data",
+ details: error instanceof Error ? error.message : "Unknown error",
+ });
+ }
+}
diff --git a/server/src/index.ts b/server/src/index.ts
index e797b7ffe..e21da7302 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 { getAdminSites } from "./api/admin/getAdminSites.js";
import { getAdminUsers } from "./api/admin/getAdminUsers.js";
+import { getAdminOrganizations } from "./api/admin/getAdminOrganizations.js";
import { createFunnel } from "./api/analytics/createFunnel.js";
import { createGoal } from "./api/analytics/createGoal.js";
import { deleteFunnel } from "./api/analytics/deleteFunnel.js";
@@ -260,6 +261,7 @@ if (IS_CLOUD) {
// Admin Routes
server.get("/admin/sites", getAdminSites);
server.get("/admin/users", getAdminUsers);
+ server.get("/admin/organizations", getAdminOrganizations);
}
server.post("/track", trackEvent);