Skip to content

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

Update AdminPage and Organizations components for improved tab manage… (#486)

Bill Yangbee7a073d264
diff --git a/client/src/api/admin/getAdminSites.ts b/client/src/api/admin/getAdminSites.ts
index d63ac3903..db2af945b 100644
--- a/client/src/api/admin/getAdminSites.ts
+++ b/client/src/api/admin/getAdminSites.ts
@@ -7,7 +7,12 @@ export interface AdminSiteData {
createdAt: string;
public: boolean;
eventsLast24Hours: number;
+ eventsLast30Days: number;
organizationOwnerEmail: string | null;
+ subscription: {
+ planName: string;
+ status: string;
+ };
}
async function getAdminSites() {
diff --git a/client/src/app/admin/components/organizations/Organizations.tsx b/client/src/app/admin/components/organizations/Organizations.tsx
index 02e913a7e..2133711cb 100644
--- a/client/src/app/admin/components/organizations/Organizations.tsx
+++ b/client/src/app/admin/components/organizations/Organizations.tsx
@@ -2,30 +2,13 @@
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 { 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 { parseUtcTimestamp } from "@/lib/dateTimeUtils";
+import { ChevronDown, ChevronRight, User, Building2, CreditCard, UserCheck, ExternalLink } from "lucide-react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Pagination } from "@/components/pagination";
@@ -43,6 +26,7 @@ import { SortableHeader } from "../shared/SortableHeader";
import { SearchInput } from "../shared/SearchInput";
import { ErrorAlert } from "../shared/ErrorAlert";
import { AdminLayout } from "../shared/AdminLayout";
+import { GrowthChart } from "../shared/GrowthChart";
export function Organizations() {
const router = useRouter();
@@ -79,9 +63,7 @@ export function Organizations() {
return organizations.filter((org) => {
return (
org.name.toLowerCase().includes(lowerSearchQuery) ||
- org.sites.some((site) =>
- site.domain.toLowerCase().includes(lowerSearchQuery)
- ) ||
+ org.sites.some((site) => site.domain.toLowerCase().includes(lowerSearchQuery)) ||
org.members.some(
(member) =>
member.email.toLowerCase().includes(lowerSearchQuery) ||
@@ -102,8 +84,7 @@ export function Organizations() {
router.push("/");
return true;
} catch (err) {
- const errorMessage =
- err instanceof Error ? err.message : "Unknown error occurred";
+ const errorMessage = err instanceof Error ? err.message : "Unknown error occurred";
console.error(`Failed to impersonate user: ${errorMessage}`);
return false;
}
@@ -112,19 +93,13 @@ export function Organizations() {
);
// Format subscription status
- const formatSubscriptionStatus = (
- subscription: AdminOrganizationData["subscription"]
- ) => {
+ 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";
+ subscription.status === "active" ? "default" : subscription.status === "canceled" ? "destructive" : "secondary";
return <Badge variant={statusColor}>{subscription.planName}</Badge>;
};
@@ -136,12 +111,7 @@ export function Organizations() {
id: "expand",
header: "",
cell: ({ row }) => (
- <Button
- variant="ghost"
- size="icon"
- className="h-5 w-5 p-0"
- onClick={() => toggleExpand(row.original.id)}
- >
+ <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" />
) : (
@@ -153,28 +123,20 @@ export function Organizations() {
},
{
accessorKey: "name",
- header: ({ column }) => (
- <SortableHeader column={column}>Organization</SortableHeader>
- ),
- cell: ({ row }) => (
- <div className="font-medium">{row.getValue("name")}</div>
- ),
+ 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>
- ),
+ header: ({ column }) => <SortableHeader column={column}>Created</SortableHeader>,
cell: ({ row }) =>
- formatDistanceToNow(new Date(row.getValue("createdAt")), {
+ formatDistanceToNow(parseUtcTimestamp(row.getValue("createdAt")).toJSDate(), {
addSuffix: true,
}),
},
{
accessorKey: "monthlyEventCount",
- header: ({ column }) => (
- <SortableHeader column={column}>Monthly Events</SortableHeader>
- ),
+ header: ({ column }) => <SortableHeader column={column}>Monthly Events</SortableHeader>,
cell: ({ row }) => {
const count = row.getValue("monthlyEventCount") as number;
const isOverLimit = row.original.overMonthlyLimit;
@@ -188,49 +150,30 @@ export function Organizations() {
},
{
id: "eventsLast24Hours",
- header: ({ column }) => (
- <SortableHeader column={column}>24h Events</SortableHeader>
- ),
- accessorFn: (row) =>
- row.sites.reduce(
- (total, site) => total + Number(site.eventsLast24Hours || 0),
- 0
- ),
+ 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
- );
+ 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>
- ),
+ 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>
- ),
+ header: ({ column }) => <SortableHeader column={column}>Sites</SortableHeader>,
accessorFn: (row) => row.sites.length,
- cell: ({ row }) => (
- <Badge variant="outline">{row.original.sites.length}</Badge>
- ),
+ cell: ({ row }) => <Badge variant="outline">{row.original.sites.length}</Badge>,
},
{
id: "members",
- header: ({ column }) => (
- <SortableHeader column={column}>Members</SortableHeader>
- ),
+ header: ({ column }) => <SortableHeader column={column}>Members</SortableHeader>,
accessorFn: (row) => row.members.length,
- cell: ({ row }) => (
- <Badge variant="outline">{row.original.members.length}</Badge>
- ),
+ cell: ({ row }) => <Badge variant="outline">{row.original.members.length}</Badge>,
},
],
[toggleExpand]
@@ -252,10 +195,7 @@ export function Organizations() {
// Paginate the sorted and filtered organizations
const paginatedOrganizations = table
.getRowModel()
- .rows.slice(
- pagination.pageIndex * pagination.pageSize,
- (pagination.pageIndex + 1) * pagination.pageSize
- );
+ .rows.slice(pagination.pageIndex * pagination.pageSize, (pagination.pageIndex + 1) * pagination.pageSize);
// Pagination controller for TablePagination
const paginationController = {
@@ -263,15 +203,11 @@ export function Organizations() {
getCanPreviousPage: () => pagination.pageIndex > 0,
getCanNextPage: () =>
table.getRowModel().rows.length > 0
- ? pagination.pageIndex <
- Math.ceil(table.getRowModel().rows.length / pagination.pageSize) - 1
+ ? 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 }),
+ table.getRowModel().rows.length > 0 ? Math.ceil(table.getRowModel().rows.length / pagination.pageSize) : 0,
+ setPageIndex: (index: number) => setPagination({ ...pagination, pageIndex: index }),
previousPage: () =>
setPagination({
...pagination,
@@ -282,8 +218,7 @@ export function Organizations() {
...pagination,
pageIndex: Math.min(
table.getRowModel().rows.length > 0
- ? Math.ceil(table.getRowModel().rows.length / pagination.pageSize) -
- 1
+ ? Math.ceil(table.getRowModel().rows.length / pagination.pageSize) - 1
: 0,
pagination.pageIndex + 1
),
@@ -300,6 +235,8 @@ export function Organizations() {
return (
<AdminLayout title="Organizations">
+ <GrowthChart data={organizations || []} title="Organizations" color="#8b5cf6" />
+
<div className="mb-4">
<SearchInput
placeholder="Search by name, slug, domain, or member email..."
@@ -314,16 +251,8 @@ export function Organizations() {
{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 key={header.id} className={header.id === "expand" ? "w-8" : ""}>
+ {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
</TableHead>
))}
</TableRow>
@@ -366,20 +295,12 @@ export function Organizations() {
<>
<TableRow key={row.id} className="group">
{row.getVisibleCells().map((cell) => (
- <TableCell key={cell.id}>
- {flexRender(
- cell.column.columnDef.cell,
- cell.getContext()
- )}
- </TableCell>
+ <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"
- >
+ <TableCell colSpan={columns.length} className="bg-neutral-900 py-4 px-8">
<div className="space-y-6">
{/* Subscription Details */}
<div>
@@ -389,55 +310,33 @@ export function Organizations() {
</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 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 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="text-xs text-neutral-400 uppercase tracking-wide">Event Limit</div>
<div className="font-medium">
- {row.original.subscription.eventLimit?.toLocaleString() ||
- "Unlimited"}
+ {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="text-xs text-neutral-400 uppercase tracking-wide">Period End</div>
<div className="font-medium">
- {formatDistanceToNow(
- new Date(
- row.original.subscription.currentPeriodEnd
- ),
- {
- addSuffix: true,
- }
- )}
+ {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 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>
@@ -459,12 +358,9 @@ export function Organizations() {
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="font-medium">{site.domain}</span>
<span className="text-xs text-neutral-400">
- {site.eventsLast24Hours.toLocaleString()}{" "}
- events (24h)
+ {site.eventsLast24Hours.toLocaleString()} events (24h)
</span>
</div>
<ExternalLink className="h-3 w-3" />
@@ -472,9 +368,7 @@ export function Organizations() {
))}
</div>
) : (
- <div className="text-neutral-400 p-4 border border-neutral-700 rounded">
- No sites
- </div>
+ <div className="text-neutral-400 p-4 border border-neutral-700 rounded">No sites</div>
)}
</div>
@@ -492,32 +386,20 @@ export function Organizations() {
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="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"
- >
+ <Badge variant="outline" className="text-xs">
{member.role}
</Badge>
</div>
</div>
<Button
- onClick={() =>
- handleImpersonate(member.userId)
- }
+ onClick={() => handleImpersonate(member.userId)}
size="sm"
variant="outline"
className="flex items-center gap-1"
- disabled={
- member.userId ===
- userStore.getState().user?.id
- }
+ disabled={member.userId === userStore.getState().user?.id}
>
<UserCheck className="h-3 w-3" />
Impersonate
@@ -526,9 +408,7 @@ export function Organizations() {
))}
</div>
) : (
- <div className="text-neutral-400 p-4 border border-neutral-700 rounded">
- No members
- </div>
+ <div className="text-neutral-400 p-4 border border-neutral-700 rounded">No members</div>
)}
</div>
</div>
@@ -539,13 +419,8 @@ export function Organizations() {
))
) : (
<TableRow>
- <TableCell
- colSpan={columns.length}
- className="text-center py-6 text-muted-foreground"
- >
- {searchQuery
- ? "No organizations match your search"
- : "No organizations found"}
+ <TableCell colSpan={columns.length} className="text-center py-6 text-muted-foreground">
+ {searchQuery ? "No organizations match your search" : "No organizations found"}
</TableCell>
</TableRow>
)}
diff --git a/client/src/app/admin/components/shared/GrowthChart.tsx b/client/src/app/admin/components/shared/GrowthChart.tsx
new file mode 100644
index 000000000..d4dca008c
--- /dev/null
+++ b/client/src/app/admin/components/shared/GrowthChart.tsx
@@ -0,0 +1,171 @@
+"use client";
+
+import { useMemo } from "react";
+import { ResponsiveLine } from "@nivo/line";
+import { parseUtcTimestamp } from "@/lib/dateTimeUtils";
+
+interface GrowthChartProps {
+ data: Array<{ createdAt: string }>;
+ title: string;
+ color?: string;
+}
+
+export function GrowthChart({ data, title, color = "#3b82f6" }: GrowthChartProps) {
+ const chartData = useMemo(() => {
+ if (!data || data.length === 0) return [];
+
+ // Group data by date
+ const dailyCounts = new Map<string, number>();
+
+ data.forEach((item) => {
+ const date = parseUtcTimestamp(item.createdAt).toFormat("yyyy-MM-dd");
+ dailyCounts.set(date, (dailyCounts.get(date) || 0) + 1);
+ });
+
+ // Convert to chart format and sort by date
+ const chartPoints = Array.from(dailyCounts.entries())
+ .map(([date, count]) => ({
+ x: date,
+ y: count,
+ }))
+ .sort((a, b) => a.x.localeCompare(b.x));
+
+ return [
+ {
+ id: title.toLowerCase(),
+ data: chartPoints,
+ },
+ ];
+ }, [data, title]);
+
+ if (!data || data.length === 0) {
+ return (
+ <div className="bg-neutral-900 border border-neutral-700 rounded-lg p-3 sm:p-6 mb-6">
+ <h3 className="text-base sm:text-lg font-semibold mb-3 sm:mb-4">{title} Growth</h3>
+ <div className="h-48 sm:h-64 flex items-center justify-center text-neutral-400 text-sm">
+ No data available
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="bg-neutral-900 border border-neutral-700 rounded-lg p-3 sm:p-6 mb-6">
+ <h3 className="text-base sm:text-lg font-semibold mb-3 sm:mb-4">{title} Growth</h3>
+ <div className="h-48 sm:h-64">
+ <ResponsiveLine
+ data={chartData}
+ margin={{
+ top: 20,
+ right: 10,
+ bottom: 50,
+ left: 45
+ }}
+ xScale={{
+ type: "time",
+ format: "%Y-%m-%d",
+ precision: "day",
+ }}
+ xFormat="time:%Y-%m-%d"
+ yScale={{
+ type: "linear",
+ min: 0,
+ max: "auto",
+ stacked: false,
+ }}
+ curve="monotoneX"
+ axisTop={null}
+ axisRight={null}
+ axisBottom={{
+ format: "%m/%d",
+ tickValues: "every 14 days",
+ tickRotation: -45,
+ tickSize: 5,
+ tickPadding: 5,
+ }}
+ axisLeft={{
+ tickSize: 5,
+ tickPadding: 5,
+ tickRotation: 0,
+ legend: `New ${title}`,
+ legendOffset: -35,
+ legendPosition: "middle",
+ }}
+ colors={[color]}
+ pointSize={4}
+ pointColor={{ theme: "background" }}
+ pointBorderWidth={2}
+ pointBorderColor={{ from: "serieColor" }}
+ pointLabelYOffset={-12}
+ useMesh={true}
+ enableGridX={false}
+ enableGridY={true}
+ gridYValues={5}
+ theme={{
+ background: "transparent",
+ text: {
+ fontSize: 11,
+ fill: "#a3a3a3",
+ },
+ axis: {
+ domain: {
+ line: {
+ stroke: "#525252",
+ strokeWidth: 1,
+ },
+ },
+ legend: {
+ text: {
+ fontSize: 11,
+ fill: "#a3a3a3",
+ },
+ },
+ ticks: {
+ line: {
+ stroke: "#525252",
+ strokeWidth: 1,
+ },
+ text: {
+ fontSize: 10,
+ fill: "#a3a3a3",
+ },
+ },
+ },
+ grid: {
+ line: {
+ stroke: "#404040",
+ strokeWidth: 1,
+ },
+ },
+ crosshair: {
+ line: {
+ stroke: "#ffffff",
+ strokeWidth: 1,
+ strokeOpacity: 0.35,
+ },
+ },
+ tooltip: {
+ container: {
+ background: "#262626",
+ color: "#ffffff",
+ fontSize: "11px",
+ borderRadius: "4px",
+ boxShadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1)",
+ border: "1px solid #404040",
+ padding: "6px 8px",
+ },
+ },
+ }}
+ tooltip={({ point }) => (
+ <div className="bg-neutral-800 border border-neutral-600 rounded px-2 py-1 text-xs sm:text-sm">
+ <div className="font-medium text-white">{point.data.xFormatted}</div>
+ <div className="text-neutral-300">
+ {point.data.y} new {title.toLowerCase()}
+ </div>
+ </div>
+ )}
+ />
+ </div>
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/client/src/app/admin/components/sites/Sites.tsx b/client/src/app/admin/components/sites/Sites.tsx
index d769eb06b..0cce52707 100644
--- a/client/src/app/admin/components/sites/Sites.tsx
+++ b/client/src/app/admin/components/sites/Sites.tsx
@@ -2,14 +2,7 @@
import { useMemo, useState } from "react";
import { useAdminSites, AdminSiteData } from "@/api/admin/getAdminSites";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@/components/ui/table";
+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";
@@ -27,15 +20,14 @@ import { SortableHeader } from "../shared/SortableHeader";
import { SearchInput } from "../shared/SearchInput";
import { ErrorAlert } from "../shared/ErrorAlert";
import { AdminLayout } from "../shared/AdminLayout";
+import { GrowthChart } from "../shared/GrowthChart";
import Link from "next/link";
import { Favicon } from "../../../../components/Favicon";
export function Sites() {
const { data: sites, isLoading, isError } = useAdminSites();
const [searchQuery, setSearchQuery] = useState("");
- const [sorting, setSorting] = useState<SortingState>([
- { id: "eventsLast24Hours", desc: true },
- ]);
+ const [sorting, setSorting] = useState<SortingState>([{ id: "eventsLast24Hours", desc: true }]);
const [pagination, setPagination] = useState({
pageIndex: 0,
pageSize: 50,
@@ -49,8 +41,8 @@ export function Sites() {
const lowerSearchQuery = searchQuery.toLowerCase();
return (
site.domain.toLowerCase().includes(lowerSearchQuery) ||
- (site.organizationOwnerEmail &&
- site.organizationOwnerEmail.toLowerCase().includes(lowerSearchQuery))
+- (site.organizationOwnerEmail && site.organizationOwnerEmail.toLowerCase().includes(lowerSearchQuery))
++ site.organizationOwnerEmail?.toLowerCase().includes(lowerSearchQuery)
);
});
}, [sites, searchQuery]);
@@ -60,16 +52,10 @@ export function Sites() {
() => [
{
accessorKey: "siteId",
- header: ({ column }) => (
- <SortableHeader column={column}>Site ID</SortableHeader>
- ),
+ header: ({ column }) => <SortableHeader column={column}>Site ID</SortableHeader>,
cell: ({ row }) => (
<div>
- <Link
- href={`/${row.getValue("siteId")}`}
- target="_blank"
- className="hover:underline"
- >
+ <Link href={`/${row.getValue("siteId")}`} target="_blank" className="hover:underline">
{row.getValue("siteId")}
</Link>
</div>
@@ -77,20 +63,11 @@ export function Sites() {
},
{
accessorKey: "domain",
- header: ({ column }) => (
- <SortableHeader column={column}>Domain</SortableHeader>
- ),
+ header: ({ column }) => <SortableHeader column={column}>Domain</SortableHeader>,
cell: ({ row }) => (
<div className="font-medium flex items-center gap-2">
- <Favicon
- domain={row.original.domain}
- className="w-5 h-5 flex-shrink-0"
- />
- <Link
- href={`https://${row.original.domain}`}
- target="_blank"
- className="hover:underline"
- >
+ <Favicon domain={row.original.domain} className="w-5 h-5 flex-shrink-0" />
+ <Link href={`https://${row.original.domain}`} target="_blank" className="hover:underline">
{row.getValue("domain")}
</Link>
</div>
@@ -98,12 +75,10 @@ export function Sites() {
},
{
accessorKey: "createdAt",
- header: ({ column }) => (
- <SortableHeader column={column}>Created</SortableHeader>
- ),
+ header: ({ column }) => <SortableHeader column={column}>Created</SortableHeader>,
cell: ({ row }) => (
<div>
- {formatDistanceToNow(new Date(row.getValue("createdAt")), {
+ {formatDistanceToNow(row.getValue("createdAt"), {
addSuffix: true,
})}
</div>
@@ -111,38 +86,40 @@ export function Sites() {
},
{
accessorKey: "public",
- header: ({ column }) => (
- <SortableHeader column={column}>Public</SortableHeader>
- ),
+ header: ({ column }) => <SortableHeader column={column}>Public</SortableHeader>,
cell: ({ row }) => (
- <div>
- {row.getValue("public") ? (
- <Badge>Public</Badge>
- ) : (
- <Badge variant="outline">Private</Badge>
- )}
- </div>
+ <div>{row.getValue("public") ? <Badge>Public</Badge> : <Badge variant="outline">Private</Badge>}</div>
),
},
{
accessorKey: "eventsLast24Hours",
- header: ({ column }) => (
- <SortableHeader column={column}>Events (24h)</SortableHeader>
- ),
- cell: ({ row }) => (
- <div>
- {Number(row.getValue("eventsLast24Hours")).toLocaleString()}
- </div>
- ),
+ header: ({ column }) => <SortableHeader column={column}>Events (24h)</SortableHeader>,
+ cell: ({ row }) => <div>{Number(row.getValue("eventsLast24Hours")).toLocaleString()}</div>,
+ },
+ {
+ accessorKey: "eventsLast30Days",
+ header: ({ column }) => <SortableHeader column={column}>Events (30d)</SortableHeader>,
+ cell: ({ row }) => <div>{Number(row.getValue("eventsLast30Days")).toLocaleString()}</div>,
+ },
+ {
+ id: "subscription",
+ header: ({ column }) => <SortableHeader column={column}>Subscription</SortableHeader>,
+ accessorFn: (row) => row.subscription.planName,
+ cell: ({ row }) => {
+ const subscription = row.original.subscription;
+ const statusColor =
+ subscription.status === "active"
+ ? "default"
+ : subscription.status === "canceled"
+ ? "destructive"
+ : "secondary";
+ return <Badge variant={statusColor}>{subscription.planName}</Badge>;
+ },
},
{
accessorKey: "organizationOwnerEmail",
- header: ({ column }) => (
- <SortableHeader column={column}>Owner Email</SortableHeader>
- ),
- cell: ({ row }) => (
- <div>{row.getValue("organizationOwnerEmail") || "-"}</div>
- ),
+ header: ({ column }) => <SortableHeader column={column}>Owner Email</SortableHeader>,
+ cell: ({ row }) => <div>{row.getValue("organizationOwnerEmail") || "-"}</div>,
},
],
[]
@@ -174,12 +151,10 @@ export function Sites() {
return (
<AdminLayout title="Sites">
+ <GrowthChart data={sites || []} title="Sites" color="#10b981" />
+
<div className="mb-4">
- <SearchInput
- placeholder="Search by domain or owner email..."
- value={searchQuery}
- onChange={setSearchQuery}
- />
+ <SearchInput placeholder="Search by domain or owner email..." value={searchQuery} onChange={setSearchQuery} />
</div>
<div className="rounded-md border border-neutral-700">
@@ -189,12 +164,7 @@ export function Sites() {
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead key={header.id}>
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext()
- )}
+ {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
</TableHead>
))}
</TableRow>
@@ -221,6 +191,12 @@ export function Sites() {
<TableCell>
<Skeleton className="h-5 w-16" />
</TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-16" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-20" />
+ </TableCell>
<TableCell>
<Skeleton className="h-5 w-40" />
</TableCell>
@@ -228,25 +204,15 @@ export function Sites() {
))
) : 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 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>
+ <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
))}
</TableRow>
))
@@ -258,11 +224,7 @@ export function Sites() {
<div className="mt-4">
<AdminTablePagination
table={table}
- data={
- filteredSites
- ? { items: filteredSites, total: filteredSites.length }
- : undefined
- }
+ data={filteredSites ? { items: filteredSites, total: filteredSites.length } : undefined}
pagination={pagination}
setPagination={setPagination}
isLoading={isLoading}
diff --git a/client/src/app/admin/page.tsx b/client/src/app/admin/page.tsx
index becfba402..31bc06219 100644
--- a/client/src/app/admin/page.tsx
+++ b/client/src/app/admin/page.tsx
@@ -9,20 +9,16 @@ import { Organizations } from "./components/organizations/Organizations";
import { AdminLayout } from "./components/shared/AdminLayout";
export default function AdminPage() {
- const [activeTab, setActiveTab] = useState("users");
+ const [activeTab, setActiveTab] = useState("organizations");
return (
<StandardPage>
<AdminLayout title="Admin Dashboard">
- <Tabs
- defaultValue="users"
- value={activeTab}
- onValueChange={setActiveTab}
- >
+ <Tabs defaultValue="organizations" value={activeTab} onValueChange={setActiveTab}>
<TabsList className="mb-4">
- <TabsTrigger value="users">Users</TabsTrigger>
<TabsTrigger value="organizations">Organizations</TabsTrigger>
<TabsTrigger value="sites">Sites</TabsTrigger>
+ <TabsTrigger value="users">Users</TabsTrigger>
<TabsTrigger value="settings">Settings</TabsTrigger>
</TabsList>
@@ -41,9 +37,7 @@ export default function AdminPage() {
<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>
+ <p className="text-muted-foreground">Settings panel coming soon...</p>
</div>
</TabsContent>
</Tabs>
diff --git a/client/src/lib/dateTimeUtils.ts b/client/src/lib/dateTimeUtils.ts
index 68722ce47..3e3c3a7b1 100644
--- a/client/src/lib/dateTimeUtils.ts
+++ b/client/src/lib/dateTimeUtils.ts
@@ -209,3 +209,12 @@ export const formatChartDateTime = (dt: DateTime, bucket: TimeBucket) => {
}
return new Intl.DateTimeFormat(userLocale, options).format(dt.toJSDate());
};
+
+/**
+ * Converts a UTC timestamp string to local time for display
+ * @param timestamp - UTC timestamp string from the server
+ * @returns DateTime object in local timezone
+ */
+export const parseUtcTimestamp = (timestamp: string): DateTime => {
+ return DateTime.fromSQL(timestamp, { zone: "utc" }).toLocal();
+};
diff --git a/server/src/api/admin/getAdminOrganizations.ts b/server/src/api/admin/getAdminOrganizations.ts
index 8252a9f7b..a7980d1ea 100644
--- a/server/src/api/admin/getAdminOrganizations.ts
+++ b/server/src/api/admin/getAdminOrganizations.ts
@@ -5,12 +5,8 @@ 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";
+import { DEFAULT_EVENT_LIMIT } from "../../lib/const.js";
+import { getOrganizationSubscriptions } from "../../services/admin/subscriptionService.js";
// Define event count result type
interface EventCountResult {
@@ -18,14 +14,6 @@ interface EventCountResult {
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();
@@ -62,10 +50,7 @@ export interface AdminOrganizationData {
}[];
}
-export async function getAdminOrganizations(
- request: FastifyRequest,
- reply: FastifyReply
-) {
+export async function getAdminOrganizations(request: FastifyRequest, reply: FastifyReply) {
const isAdmin = await getIsUserAdmin(request);
if (!isAdmin) {
@@ -75,9 +60,7 @@ export async function getAdminOrganizations(
try {
// Get all organizations with their basic data
const organizationsData = await db.query.organization.findMany({
- orderBy: (organization, { desc }) => [
- desc(organization.monthlyEventCount),
- ],
+ orderBy: (organization, { desc }) => [desc(organization.createdAt)],
});
// Get all members for all organizations
@@ -119,11 +102,7 @@ export async function getAdminOrganizations(
organizationId: sites.organizationId,
})
.from(sites)
- .where(
- allOrgIds.length > 0
- ? inArray(sites.organizationId, allOrgIds)
- : undefined
- );
+ .where(allOrgIds.length > 0 ? inArray(sites.organizationId, allOrgIds) : undefined);
// Get event counts for the past 24 hours from ClickHouse
const now = DateTime.now();
@@ -155,10 +134,7 @@ export async function getAdminOrganizations(
siteEventMap.set(Number(event.site_id), event.total_events);
}
} catch (clickhouseError) {
- console.warn(
- "ClickHouse query failed, continuing without event counts:",
- clickhouseError
- );
+ console.warn("ClickHouse query failed, continuing without event counts:", clickhouseError);
}
// Create map of organization IDs to their sites with event counts
@@ -178,101 +154,24 @@ export async function getAdminOrganizations(
}
}
- // 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);
- }
- }
+ // Get subscription data for organizations
+ const orgSubscriptionMap = await getOrganizationSubscriptions(organizationsData, true);
// 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) || [],
- };
- });
+ const enrichedOrganizations: AdminOrganizationData[] = organizationsData.map((org) => {
+ const subscriptionData = orgSubscriptionMap.get(org.id)!; // Non-null assertion since service always returns data
+
+ return {
+ id: org.id,
+ name: org.name,
+ createdAt: org.createdAt,
+ monthlyEventCount: org.monthlyEventCount || 0,
+ overMonthlyLimit: org.overMonthlyLimit || false,
+ subscription: subscriptionData,
+ sites: orgSitesMap.get(org.id) || [],
+ members: orgMembersMap.get(org.id) || [],
+ };
+ });
return reply.status(200).send(enrichedOrganizations);
} catch (error) {
diff --git a/server/src/api/admin/getAdminSites.ts b/server/src/api/admin/getAdminSites.ts
index ccea12939..7f58e3dd4 100644
--- a/server/src/api/admin/getAdminSites.ts
+++ b/server/src/api/admin/getAdminSites.ts
@@ -5,6 +5,7 @@ import { clickhouse } from "../../db/clickhouse/clickhouse.js";
import { db } from "../../db/postgres/postgres.js";
import { member, user } from "../../db/postgres/schema.js";
import { getIsUserAdmin } from "../../lib/auth-utils.js";
+import { getOrganizationSubscriptions } from "../../services/admin/subscriptionService.js";
// Define event count result type
interface EventCountResult {
@@ -12,10 +13,8 @@ interface EventCountResult {
total_events: number;
}
-export async function getAdminSites(
- request: FastifyRequest,
- reply: FastifyReply
-) {
+
+export async function getAdminSites(request: FastifyRequest, reply: FastifyReply) {
const isAdmin = await getIsUserAdmin(request);
if (!isAdmin) {
@@ -23,7 +22,9 @@ export async function getAdminSites(
}
// Get all sites (including organizationId for owner lookup)
- const sitesData = await db.query.sites.findMany();
+ const sitesData = await db.query.sites.findMany({
+ orderBy: (sites, { desc }) => [desc(sites.createdAt)],
+ });
// Get organization owners and their emails
const orgOwners = await db
@@ -42,11 +43,17 @@ export async function getAdminSites(
orgOwnerMap.set(owner.organizationId, owner.email);
}
- // Get event counts for the past 24 hours from Clickhouse
+ // Get organizations and their subscription data
+ const organizationsData = await db.query.organization.findMany();
+ const orgSubscriptionMap = await getOrganizationSubscriptions(organizationsData, false);
+
+ // Get event counts for the past 24 hours and 30 days from Clickhouse
const now = DateTime.now();
const yesterday = now.minus({ hours: 24 });
+ const thirtyDaysAgo = now.minus({ days: 30 });
- const eventCountsResult = await clickhouse.query({
+ // Get 24h event counts
+ const eventCounts24hResult = await clickhouse.query({
query: `
SELECT
site_id,
@@ -62,33 +69,62 @@ export async function getAdminSites(
format: "JSONEachRow",
});
- const rawEventCounts = await eventCountsResult.json();
+ // Get 30d event counts
+ const eventCounts30dResult = await clickhouse.query({
+ query: `
+ SELECT
+ site_id,
+ sum(event_count) as total_events
+ FROM
+ hourly_events_by_site_mv_target
+ WHERE
+ event_hour >= toDateTime('${thirtyDaysAgo.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 rawEventCounts24h = await eventCounts24hResult.json();
+ const rawEventCounts30d = await eventCounts30dResult.json();
- // Create map of site IDs to event counts
- const siteEventMap = new Map<number, number>();
+ // Create maps of site IDs to event counts
+ const siteEventMap24h = new Map<number, number>();
+ const siteEventMap30d = 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);
+ const eventCounts24h = rawEventCounts24h as EventCountResult[];
+ const eventCounts30d = rawEventCounts30d as EventCountResult[];
+
+ for (const event of eventCounts24h) {
+ siteEventMap24h.set(Number(event.site_id), event.total_events);
+ }
+
+ for (const event of eventCounts30d) {
+ siteEventMap30d.set(Number(event.site_id), event.total_events);
}
// Combine all data
const enrichedSites = sitesData.map((site) => {
+ const subscription = site.organizationId
+ ? orgSubscriptionMap.get(site.organizationId)
+ : { planName: "free", status: "free" };
+
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,
+ eventsLast24Hours: siteEventMap24h.get(site.siteId) || 0,
+ eventsLast30Days: siteEventMap30d.get(site.siteId) || 0,
+ organizationOwnerEmail: site.organizationId ? orgOwnerMap.get(site.organizationId) : null,
+ subscription: {
+ planName: subscription?.planName || "free",
+ status: subscription?.status || "free",
+ },
};
});
- // 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/services/admin/subscriptionService.ts b/server/src/services/admin/subscriptionService.ts
new file mode 100644
index 000000000..0d3f59444
--- /dev/null
+++ b/server/src/services/admin/subscriptionService.ts
@@ -0,0 +1,146 @@
+import { getStripePrices, StripePlan, DEFAULT_EVENT_LIMIT } from "../../lib/const.js";
+import { stripe } from "../../lib/stripe.js";
+import { DateTime } from "luxon";
+
+export interface SubscriptionData {
+ id: string;
+ planName: string;
+ status: string;
+ currentPeriodStart?: Date;
+ currentPeriodEnd?: Date;
+ cancelAtPeriodEnd?: boolean;
+ eventLimit?: number;
+ interval?: string;
+}
+
+// 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),
+ );
+}
+
+/**
+ * Fetches subscription data for multiple Stripe customer IDs
+ * @param stripeCustomerIds Set of Stripe customer IDs to fetch subscriptions for
+ * @param includeFullDetails Whether to include full subscription details (periods, limits, etc.)
+ * @returns Map of customer ID to subscription data
+ */
+export async function fetchSubscriptionsForCustomers(
+ stripeCustomerIds: Set<string>,
+ includeFullDetails = false,
+): Promise<Map<string, SubscriptionData>> {
+ const subscriptionMap = new Map<string, SubscriptionData>();
+
+ if (!stripe || stripeCustomerIds.size === 0) {
+ return subscriptionMap;
+ }
+
+ try {
+ let hasMore = true;
+ let startingAfter: string | undefined;
+
+ while (hasMore) {
+ const subscriptions = await stripe.subscriptions.list({
+ status: "active",
+ limit: 100,
+ expand: ["data.plan.product"],
+ ...(startingAfter && { starting_after: startingAfter }),
+ });
+
+ 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);
+
+ const subscriptionData: SubscriptionData = {
+ id: subscription.id,
+ planName: planDetails?.name || "Unknown Plan",
+ status: subscription.status,
+ };
+
+ if (includeFullDetails) {
+ subscriptionData.currentPeriodStart = new Date(subscriptionItem.current_period_start * 1000);
+ subscriptionData.currentPeriodEnd = new Date(subscriptionItem.current_period_end * 1000);
+ subscriptionData.cancelAtPeriodEnd = subscription.cancel_at_period_end;
+ subscriptionData.eventLimit = planDetails?.limits.events || 0;
+ subscriptionData.interval = subscriptionItem.price.recurring?.interval ?? "unknown";
+ }
+
+ subscriptionMap.set(customerId, subscriptionData);
+ }
+ }
+ }
+
+ 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);
+ }
+
+ return subscriptionMap;
+}
+
+/**
+ * Creates a map of organization IDs to their subscription data
+ * @param organizations Array of organization objects with id and stripeCustomerId
+ * @param includeFullDetails Whether to include full subscription details
+ * @returns Map of organization ID to subscription data with fallback to free plan
+ */
+export async function getOrganizationSubscriptions(
+ organizations: Array<{ id: string; stripeCustomerId?: string | null }>,
+ includeFullDetails = false,
+): Promise<
+ Map<string, SubscriptionData & { planName: string; status: string; eventLimit: number; currentPeriodEnd: Date }>
+> {
+ const orgsWithStripe = organizations.filter((org) => org.stripeCustomerId);
+ const stripeCustomerIds = new Set(orgsWithStripe.map((org) => org.stripeCustomerId!));
+
+ const subscriptionMap = await fetchSubscriptionsForCustomers(stripeCustomerIds, includeFullDetails);
+
+ // Create organization map with subscription data
+ const orgSubscriptionMap = new Map<
+ string,
+ SubscriptionData & { planName: string; status: string; eventLimit: number; currentPeriodEnd: Date }
+ >();
+
+ for (const org of organizations) {
+ const subscriptionData = org.stripeCustomerId ? subscriptionMap.get(org.stripeCustomerId) : null;
+
+ if (subscriptionData) {
+ // Ensure all required fields are present for paid subscriptions
+ orgSubscriptionMap.set(org.id, {
+ ...subscriptionData,
+ planName: subscriptionData.planName || "free",
+ status: subscriptionData.status || "free",
+ eventLimit: subscriptionData.eventLimit ?? 0,
+ currentPeriodEnd: subscriptionData.currentPeriodEnd ?? new Date(),
+ });
+ } else {
+ // Free plan with all required fields
+ orgSubscriptionMap.set(org.id, {
+ id: "",
+ planName: "free",
+ status: "free",
+ eventLimit: DEFAULT_EVENT_LIMIT,
+ currentPeriodEnd: DateTime.now().startOf("month").plus({ months: 1 }).toJSDate(),
+ });
+ }
+ }
+
+ return orgSubscriptionMap;
+}