Skip to content

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

Free (#313)

Bill Yang2d0aea797e5a
diff --git a/client/package.json b/client/package.json
index 2c07c0f9e..a9e56f6fb 100644
--- a/client/package.json
+++ b/client/package.json
@@ -1,6 +1,6 @@
{
"name": "client",
- "version": "0.4.0",
+ "version": "0.4.2",
"private": true,
"scripts": {
"dev": "next dev -p 3002 --turbopack",
diff --git a/client/src/api/analytics/useGetOrgEventCount.ts b/client/src/api/analytics/useGetOrgEventCount.ts
new file mode 100644
index 000000000..ecc20078c
--- /dev/null
+++ b/client/src/api/analytics/useGetOrgEventCount.ts
@@ -0,0 +1,60 @@
+import { useQuery } from "@tanstack/react-query";
+import { BACKEND_URL } from "../../lib/const";
+import { authedFetchWithError } from "../utils";
+
+export type OrgEventCountResponse = {
+ event_date: string;
+ event_count: number;
+}[];
+
+export type GetOrgEventCountResponse = {
+ data: OrgEventCountResponse;
+};
+
+async function getOrgEventCount({
+ organizationId,
+ startDate,
+ endDate,
+ timeZone = "UTC",
+}: {
+ organizationId: string;
+ startDate?: string;
+ endDate?: string;
+ timeZone?: string;
+}): Promise<GetOrgEventCountResponse> {
+ const params = new URLSearchParams();
+ if (startDate) params.append("startDate", startDate);
+ if (endDate) params.append("endDate", endDate);
+ if (timeZone) params.append("timeZone", timeZone);
+
+ return authedFetchWithError(
+ `${BACKEND_URL}/org-event-count/${organizationId}?${params.toString()}`
+ );
+}
+
+export function useGetOrgEventCount({
+ organizationId,
+ startDate,
+ endDate,
+ timeZone = "UTC",
+ enabled = true,
+}: {
+ organizationId: string;
+ startDate?: string;
+ endDate?: string;
+ timeZone?: string;
+ enabled?: boolean;
+}) {
+ return useQuery({
+ queryKey: ["org-event-count", organizationId, startDate, endDate, timeZone],
+ queryFn: () =>
+ getOrgEventCount({
+ organizationId,
+ startDate,
+ endDate,
+ timeZone,
+ }),
+ enabled: enabled && !!organizationId,
+ staleTime: 1000 * 60 * 5, // 5 minutes
+ });
+}
diff --git a/client/src/app/[site]/components/Header/Header.tsx b/client/src/app/[site]/components/Header/Header.tsx
index 63a0e884a..1fc005f1b 100644
--- a/client/src/app/[site]/components/Header/Header.tsx
+++ b/client/src/app/[site]/components/Header/Header.tsx
@@ -1,6 +1,6 @@
"use client";
-import { FreeTrialBanner } from "../../../../components/FreeTrialBanner";
+import { FreePlanBanner } from "../../../../components/FreePlanBanner";
import { userStore } from "../../../../lib/userStore";
import { NoData } from "./NoData";
import { UsageBanners } from "./UsageBanners";
@@ -12,7 +12,7 @@ export function Header() {
<div className="flex flex-col">
{user && (
<div className="flex flex-col px-4">
- <FreeTrialBanner />
+ <FreePlanBanner />
<UsageBanners />
<NoData />
</div>
diff --git a/client/src/app/[site]/components/Header/UsageBanners.tsx b/client/src/app/[site]/components/Header/UsageBanners.tsx
index 7e4eed1d1..2c6b24279 100644
--- a/client/src/app/[site]/components/Header/UsageBanners.tsx
+++ b/client/src/app/[site]/components/Header/UsageBanners.tsx
@@ -48,8 +48,7 @@ export function UsageBanners() {
</AlertTitle>
<div className="mb-2 text-sm">
<strong>{formatNumber(site.monthlyEventCount || 0)}</strong>{" "}
- events used (limit:{" "}
- <strong>{formatNumber(site.eventLimit || 20000)}</strong>)
+ events used of <strong>{formatNumber(site.eventLimit)}</strong>
</div>
{site.isOwner ? (
@@ -57,8 +56,8 @@ export function UsageBanners() {
<AlertDescription className="text-sm">
Upgrade your plan to continue collecting analytics.
</AlertDescription>
- <Button variant="default" asChild>
- <Link href="/settings/subscription">
+ <Button variant="success" asChild size="sm">
+ <Link href="/subscribe">
Upgrade Plan <ArrowRight className="ml-1 h-3 w-3" />
</Link>
</Button>
@@ -87,8 +86,7 @@ export function UsageBanners() {
</AlertTitle>
<div className="mb-2 text-sm text-amber-700 dark:text-amber-400">
<strong>{formatNumber(site.monthlyEventCount || 0)}</strong>{" "}
- events used ({Math.round(usagePercentage)}% of your{" "}
- <strong>{formatNumber(site.eventLimit || 20000)}</strong> limit)
+ events used of <strong>{formatNumber(site.eventLimit)}</strong>
</div>
{site.isOwner ? (
@@ -96,11 +94,8 @@ export function UsageBanners() {
<AlertDescription className="text-sm text-amber-700 dark:text-amber-400">
Consider upgrading your plan to avoid interruptions.
</AlertDescription>
- <Button
- className="bg-white hover:bg-white/90 text-neutral-100 border-white/20 hover:border-white/30 py-1 h-auto text-sm"
- asChild
- >
- <Link href="/settings/subscription">
+ <Button asChild variant="success" size="sm">
+ <Link href="/subscribe">
Upgrade Plan <ArrowRight className="ml-1 h-3 w-3" />
</Link>
</Button>
diff --git a/client/src/app/[site]/events/page.tsx b/client/src/app/[site]/events/page.tsx
index b37b3bc4b..cfd2c8e77 100644
--- a/client/src/app/[site]/events/page.tsx
+++ b/client/src/app/[site]/events/page.tsx
@@ -1,12 +1,13 @@
"use client";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { EVENT_FILTERS } from "@/lib/store";
import { useGetEventNames } from "../../../api/analytics/useGetEventNames";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { DisabledOverlay } from "../../../components/DisabledOverlay";
+import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
+import { SubHeader } from "../components/SubHeader/SubHeader";
import { EventList } from "./components/EventList";
import { EventLog } from "./components/EventLog";
-import { SubHeader } from "../components/SubHeader/SubHeader";
-import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
export default function EventsPage() {
useSetPageTitle("Rybbit · Events");
@@ -15,30 +16,32 @@ export default function EventsPage() {
useGetEventNames();
return (
- <div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3">
- <SubHeader availableFilters={EVENT_FILTERS} />
+ <DisabledOverlay>
+ <div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3">
+ <SubHeader availableFilters={EVENT_FILTERS} />
- <Card>
- <CardHeader>
- <CardTitle>Custom Events</CardTitle>
- </CardHeader>
- <CardContent>
- <EventList
- events={eventNamesData || []}
- isLoading={isLoadingEventNames}
- size="large"
- />
- </CardContent>
- </Card>
+ <Card>
+ <CardHeader>
+ <CardTitle>Custom Events</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <EventList
+ events={eventNamesData || []}
+ isLoading={isLoadingEventNames}
+ size="large"
+ />
+ </CardContent>
+ </Card>
- <Card>
- <CardHeader>
- <CardTitle>Event Log</CardTitle>
- </CardHeader>
- <CardContent>
- <EventLog />
- </CardContent>
- </Card>
- </div>
+ <Card>
+ <CardHeader>
+ <CardTitle>Event Log</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <EventLog />
+ </CardContent>
+ </Card>
+ </div>
+ </DisabledOverlay>
);
}
diff --git a/client/src/app/[site]/funnels/page.tsx b/client/src/app/[site]/funnels/page.tsx
index 4dd8a12b8..5d5382b82 100644
--- a/client/src/app/[site]/funnels/page.tsx
+++ b/client/src/app/[site]/funnels/page.tsx
@@ -9,6 +9,7 @@ import { NothingFound } from "../../../components/NothingFound";
import { CreateFunnelDialog } from "./components/CreateFunnel";
import { FunnelRow } from "./components/FunnelRow";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
+import { DisabledOverlay } from "../../../components/DisabledOverlay";
// Skeleton for the funnel row component
const FunnelRowSkeleton = () => (
@@ -82,34 +83,36 @@ export default function FunnelsPage() {
}
return (
- <div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3">
- <div className="flex justify-between items-center mb-3">
- <div>
- <MobileSidebar />
+ <DisabledOverlay>
+ <div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3">
+ <div className="flex justify-between items-center mb-3">
+ <div>
+ <MobileSidebar />
+ </div>
+ <CreateFunnelDialog />
</div>
- <CreateFunnelDialog />
- </div>
- {error ? (
- <div className="p-4 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-lg">
- Failed to load funnels:{" "}
- {error instanceof Error ? error.message : "Unknown error"}
- </div>
- ) : funnels?.length ? (
- <div className="space-y-4">
- {funnels.map((funnel: SavedFunnel) => (
- <FunnelRow key={funnel.id} funnel={funnel} />
- ))}
- </div>
- ) : (
- <NothingFound
- title={"No funnels yet"}
- description={
- "Create your first funnel to track conversions through your site's user journey"
- }
- action={<CreateFunnelDialog />}
- />
- )}
- </div>
+ {error ? (
+ <div className="p-4 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-lg">
+ Failed to load funnels:{" "}
+ {error instanceof Error ? error.message : "Unknown error"}
+ </div>
+ ) : funnels?.length ? (
+ <div className="space-y-4">
+ {funnels.map((funnel: SavedFunnel) => (
+ <FunnelRow key={funnel.id} funnel={funnel} />
+ ))}
+ </div>
+ ) : (
+ <NothingFound
+ title={"No funnels yet"}
+ description={
+ "Create your first funnel to track conversions through your site's user journey"
+ }
+ action={<CreateFunnelDialog />}
+ />
+ )}
+ </div>
+ </DisabledOverlay>
);
}
diff --git a/client/src/app/[site]/goals/page.tsx b/client/src/app/[site]/goals/page.tsx
index 477033385..8dc231432 100644
--- a/client/src/app/[site]/goals/page.tsx
+++ b/client/src/app/[site]/goals/page.tsx
@@ -5,13 +5,13 @@ import {
useGetGoals,
useGetGoalsPastMinutes,
} from "../../../api/analytics/useGetGoals";
-import { getStartAndEndDate } from "../../../api/utils";
+import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { NothingFound } from "../../../components/NothingFound";
+import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { GOALS_PAGE_FILTERS, useStore } from "../../../lib/store";
import { SubHeader } from "../components/SubHeader/SubHeader";
import CreateGoalButton from "./components/CreateGoalButton";
import GoalsList from "./components/GoalsList";
-import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
export default function GoalsPage() {
useSetPageTitle("Rybbit · Goals");
@@ -83,37 +83,39 @@ export default function GoalsPage() {
);
return (
- <div className="p-2 md:p-4 max-w-[1400px] mx-auto space-y-3">
- <SubHeader availableFilters={GOALS_PAGE_FILTERS} />
- <div className="flex items-center justify-between">
- <div />
- <CreateGoalButton siteId={Number(site)} />
- </div>
-
- {isLoading ? (
- <div className="space-y-3">
- {Array(3)
- .fill(0)
- .map((_, index) => (
- <GoalCardSkeleton key={`skeleton-${index}`} />
- ))}
+ <DisabledOverlay>
+ <div className="p-2 md:p-4 max-w-[1400px] mx-auto space-y-3">
+ <SubHeader availableFilters={GOALS_PAGE_FILTERS} />
+ <div className="flex items-center justify-between">
+ <div />
+ <CreateGoalButton siteId={Number(site)} />
</div>
- ) : !goalsData || goalsData.data.length === 0 ? (
- <NothingFound
- title={"No goals found"}
- description={
- "Create your first conversion goal to start tracking important user actions."
- }
- action={<CreateGoalButton siteId={Number(site)} />}
- />
- ) : (
- <GoalsList
- goals={goalsData.data}
- siteId={Number(site)}
- paginationMeta={goalsData.meta}
- onPageChange={handlePageChange}
- />
- )}
- </div>
+
+ {isLoading ? (
+ <div className="space-y-3">
+ {Array(3)
+ .fill(0)
+ .map((_, index) => (
+ <GoalCardSkeleton key={`skeleton-${index}`} />
+ ))}
+ </div>
+ ) : !goalsData || goalsData.data.length === 0 ? (
+ <NothingFound
+ title={"No goals found"}
+ description={
+ "Create your first conversion goal to start tracking important user actions."
+ }
+ action={<CreateGoalButton siteId={Number(site)} />}
+ />
+ ) : (
+ <GoalsList
+ goals={goalsData.data}
+ siteId={Number(site)}
+ paginationMeta={goalsData.meta}
+ onPageChange={handlePageChange}
+ />
+ )}
+ </div>
+ </DisabledOverlay>
);
}
diff --git a/client/src/app/[site]/journeys/page.tsx b/client/src/app/[site]/journeys/page.tsx
index 046c6a8e0..96a979602 100644
--- a/client/src/app/[site]/journeys/page.tsx
+++ b/client/src/app/[site]/journeys/page.tsx
@@ -18,6 +18,7 @@ import { useEffect, useRef, useState } from "react";
import { useGetSite } from "../../../api/admin/sites";
import { DateSelector } from "../../../components/DateSelector/DateSelector";
import { DateRangeMode, Time } from "../../../components/DateSelector/types";
+import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { MobileSidebar } from "../../../components/MobileSidebar";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { timeZone } from "../../../lib/dateTimeUtils";
@@ -431,86 +432,88 @@ export default function JourneysPage() {
}, [data, steps, maxJourneys, siteMetadata]);
return (
- <div className="container mx-auto p-2 md:p-4">
- <div className="md:hidden mb-2">
- <MobileSidebar />
+ <DisabledOverlay>
+ <div className="container mx-auto p-2 md:p-4">
+ <div className="md:hidden mb-2">
+ <MobileSidebar />
+ </div>
+ <div className="flex justify-end items-center gap-2 mb-2">
+ <DateSelector
+ time={time}
+ setTime={setTime}
+ past24HoursEnabled={false}
+ />
+ <Select
+ value={steps.toString()}
+ onValueChange={(value) => setSteps(Number(value))}
+ >
+ <SelectTrigger className="w-[120px]">
+ <SelectValue placeholder="Number of steps" />
+ </SelectTrigger>
+ <SelectContent>
+ {[2, 3, 4, 5, 6, 7, 8, 9, 10].map((step) => (
+ <SelectItem key={step} value={step.toString()}>
+ {step} steps
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Select
+ value={maxJourneys.toString()}
+ onValueChange={(value) => setMaxJourneys(Number(value))}
+ >
+ <SelectTrigger className="w-[140px]">
+ <SelectValue placeholder="Max journeys" />
+ </SelectTrigger>
+ <SelectContent>
+ {[10, 25, 50, 100, 150, 200].map((count) => (
+ <SelectItem key={count} value={count.toString()}>
+ {count} journeys
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <Card className="w-full">
+ <CardHeader className="flex flex-row items-center justify-between">
+ <CardTitle>User Journeys</CardTitle>
+ </CardHeader>
+ <CardContent>
+ {isLoading && (
+ <div className="flex flex-col space-y-4">
+ <Skeleton className="h-[1000px] w-full rounded-md" />
+ </div>
+ )}
+
+ {error && (
+ <Alert variant="destructive">
+ <AlertCircle className="h-4 w-4" />
+ <AlertTitle>Error</AlertTitle>
+ <AlertDescription>
+ Failed to load journey data. Please try again.
+ </AlertDescription>
+ </Alert>
+ )}
+
+ {data?.journeys?.length === 0 && !isLoading && !error && (
+ <Alert>
+ <AlertCircle className="h-4 w-4" />
+ <AlertTitle>No Data</AlertTitle>
+ <AlertDescription>
+ No journey data found for the selected criteria.
+ </AlertDescription>
+ </Alert>
+ )}
+
+ {data?.journeys?.length && data?.journeys?.length > 0 ? (
+ <div className="overflow-x-auto w-full">
+ <svg ref={svgRef} className="min-w-full" />
+ {/* <svg ref={svgRef} className="w-full h-[1000px]" /> */}
+ </div>
+ ) : null}
+ </CardContent>
+ </Card>
</div>
- <div className="flex justify-end items-center gap-2 mb-2">
- <DateSelector
- time={time}
- setTime={setTime}
- past24HoursEnabled={false}
- />
- <Select
- value={steps.toString()}
- onValueChange={(value) => setSteps(Number(value))}
- >
- <SelectTrigger className="w-[120px]">
- <SelectValue placeholder="Number of steps" />
- </SelectTrigger>
- <SelectContent>
- {[2, 3, 4, 5, 6, 7, 8, 9, 10].map((step) => (
- <SelectItem key={step} value={step.toString()}>
- {step} steps
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <Select
- value={maxJourneys.toString()}
- onValueChange={(value) => setMaxJourneys(Number(value))}
- >
- <SelectTrigger className="w-[140px]">
- <SelectValue placeholder="Max journeys" />
- </SelectTrigger>
- <SelectContent>
- {[10, 25, 50, 100, 150, 200].map((count) => (
- <SelectItem key={count} value={count.toString()}>
- {count} journeys
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- <Card className="w-full">
- <CardHeader className="flex flex-row items-center justify-between">
- <CardTitle>User Journeys</CardTitle>
- </CardHeader>
- <CardContent>
- {isLoading && (
- <div className="flex flex-col space-y-4">
- <Skeleton className="h-[1000px] w-full rounded-md" />
- </div>
- )}
-
- {error && (
- <Alert variant="destructive">
- <AlertCircle className="h-4 w-4" />
- <AlertTitle>Error</AlertTitle>
- <AlertDescription>
- Failed to load journey data. Please try again.
- </AlertDescription>
- </Alert>
- )}
-
- {data?.journeys?.length === 0 && !isLoading && !error && (
- <Alert>
- <AlertCircle className="h-4 w-4" />
- <AlertTitle>No Data</AlertTitle>
- <AlertDescription>
- No journey data found for the selected criteria.
- </AlertDescription>
- </Alert>
- )}
-
- {data?.journeys?.length && data?.journeys?.length > 0 ? (
- <div className="overflow-x-auto w-full">
- <svg ref={svgRef} className="min-w-full" />
- {/* <svg ref={svgRef} className="w-full h-[1000px]" /> */}
- </div>
- ) : null}
- </CardContent>
- </Card>
- </div>
+ </DisabledOverlay>
);
}
diff --git a/client/src/app/[site]/map/page.tsx b/client/src/app/[site]/map/page.tsx
index 722a8a14f..f2cba9f3e 100644
--- a/client/src/app/[site]/map/page.tsx
+++ b/client/src/app/[site]/map/page.tsx
@@ -6,6 +6,7 @@ import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { cn } from "../../../lib/utils";
import { MapComponent } from "../components/shared/Map";
import { SubHeader } from "../components/SubHeader/SubHeader";
+import { DisabledOverlay } from "../../../components/DisabledOverlay";
export default function MapPage() {
useSetPageTitle("Rybbit · Map");
@@ -13,34 +14,40 @@ export default function MapPage() {
const [mapMode, setMapMode] = useState<"total" | "perCapita">("total");
return (
- <div className="relative w-full h-[calc(100vh-45px)]">
- <div className="p-2 md:p-4 relative z-50">
- <SubHeader />
- </div>
- <div className="absolute bottom-2 md:bottom-4 left-2 md:left-4 z-50">
- <div className="flex items-center gap-3 bg-neutral-900 rounded-md px-3 py-2 text-sm">
- <span
- className={cn(mapMode === "total" ? "text-white" : "text-neutral-400")}
- >
- Total Visits
- </span>
- <Switch
- checked={mapMode === "perCapita"}
- onCheckedChange={(checked) =>
- setMapMode(checked ? "perCapita" : "total")
- }
- className="data-[state=checked]:bg-accent-400"
- />
- <span
- className={cn(mapMode === "perCapita" ? "text-white" : "text-neutral-400")}
- >
- Per Capita
- </span>
+ <DisabledOverlay>
+ <div className="relative w-full h-[calc(100vh-45px)]">
+ <div className="p-2 md:p-4 relative z-50">
+ <SubHeader />
+ </div>
+ <div className="absolute bottom-2 md:bottom-4 left-2 md:left-4 z-50">
+ <div className="flex items-center gap-3 bg-neutral-900 rounded-md px-3 py-2 text-sm">
+ <span
+ className={cn(
+ mapMode === "total" ? "text-white" : "text-neutral-400"
+ )}
+ >
+ Total Visits
+ </span>
+ <Switch
+ checked={mapMode === "perCapita"}
+ onCheckedChange={(checked) =>
+ setMapMode(checked ? "perCapita" : "total")
+ }
+ className="data-[state=checked]:bg-accent-400"
+ />
+ <span
+ className={cn(
+ mapMode === "perCapita" ? "text-white" : "text-neutral-400"
+ )}
+ >
+ Per Capita
+ </span>
+ </div>
+ </div>
+ <div className="absolute top-0 left-0 right-0 bottom-0 z-10">
+ <MapComponent height="calc(100vh - 45px - 40px)" mode={mapMode} />
</div>
</div>
- <div className="absolute top-0 left-0 right-0 bottom-0 z-10">
- <MapComponent height="calc(100vh - 45px - 40px)" mode={mapMode} />
- </div>
- </div>
+ </DisabledOverlay>
);
}
diff --git a/client/src/app/[site]/pages/page.tsx b/client/src/app/[site]/pages/page.tsx
index 7edffab5a..cfd3468c7 100644
--- a/client/src/app/[site]/pages/page.tsx
+++ b/client/src/app/[site]/pages/page.tsx
@@ -4,14 +4,14 @@ import {
PageTitleItem,
useGetPageTitlesPaginated,
} from "@/api/analytics/useGetPageTitles";
+import { TablePagination } from "@/components/pagination";
import { useSetPageTitle } from "@/hooks/useSetPageTitle";
import { useStore } from "@/lib/store";
import { useEffect, useState } from "react";
+import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { SubHeader } from "../components/SubHeader/SubHeader";
import { PageListItem } from "./components/PageListItem";
import { PageListSkeleton } from "./components/PageListSkeleton";
-import { TablePagination } from "@/components/pagination";
-import { createColumnHelper } from "@tanstack/react-table";
// Number of items per page
const PAGE_SIZE = 10;
@@ -111,45 +111,47 @@ export default function Pages() {
]);
return (
- <div className="p-2 md:p-4 max-w-[1100px] mx-auto space-y-3">
- <SubHeader />
+ <DisabledOverlay>
+ <div className="p-2 md:p-4 max-w-[1100px] mx-auto space-y-3">
+ <SubHeader />
- {isLoading ? (
- <PageListSkeleton count={pagination.pageSize} />
- ) : isErrorPages ? (
- <div className="text-center p-8 text-destructive">
- <p>Error loading pages data</p>
- <p className="text-sm">{pagesError?.toString()}</p>
- </div>
- ) : pagesDataArray && pagesDataArray.length > 0 ? (
- <>
- {pagesDataArray.map((pageItem: PageTitleItem, index: number) => (
- <PageListItem
- key={`${pageItem.value}-${index}-${pagination.pageIndex}`}
- pageData={{
- value: pageItem.pathname,
- title: pageItem.value,
- count: pageItem.count,
- percentage: pageItem.percentage,
- }}
- />
- ))}
- {totalPages > 0 && (
- <TablePagination
- table={table}
- data={{ items: pagesDataArray || [], total: totalCount || 0 }}
- pagination={pagination}
- setPagination={setPagination}
- isLoading={isLoading}
- itemName="pages"
- />
- )}
- </>
- ) : !isLoadingPages && !isFetching ? (
- <div className="text-center py-12 text-muted-foreground">
- <p>No pages data found for the selected period.</p>
- </div>
- ) : null}
- </div>
+ {isLoading ? (
+ <PageListSkeleton count={pagination.pageSize} />
+ ) : isErrorPages ? (
+ <div className="text-center p-8 text-destructive">
+ <p>Error loading pages data</p>
+ <p className="text-sm">{pagesError?.toString()}</p>
+ </div>
+ ) : pagesDataArray && pagesDataArray.length > 0 ? (
+ <>
+ {pagesDataArray.map((pageItem: PageTitleItem, index: number) => (
+ <PageListItem
+ key={`${pageItem.value}-${index}-${pagination.pageIndex}`}
+ pageData={{
+ value: pageItem.pathname,
+ title: pageItem.value,
+ count: pageItem.count,
+ percentage: pageItem.percentage,
+ }}
+ />
+ ))}
+ {totalPages > 0 && (
+ <TablePagination
+ table={table}
+ data={{ items: pagesDataArray || [], total: totalCount || 0 }}
+ pagination={pagination}
+ setPagination={setPagination}
+ isLoading={isLoading}
+ itemName="pages"
+ />
+ )}
+ </>
+ ) : !isLoadingPages && !isFetching ? (
+ <div className="text-center py-12 text-muted-foreground">
+ <p>No pages data found for the selected period.</p>
+ </div>
+ ) : null}
+ </div>
+ </DisabledOverlay>
);
}
diff --git a/client/src/app/[site]/realtime/page.tsx b/client/src/app/[site]/realtime/page.tsx
index 396e59169..f60c4d97c 100644
--- a/client/src/app/[site]/realtime/page.tsx
+++ b/client/src/app/[site]/realtime/page.tsx
@@ -17,6 +17,7 @@ import { RealtimeChart } from "./RealtimeChart/RealtimeChart";
import { RealtimeEvents } from "./RealtimeEvents/RealtimeEvents";
import { World } from "./RealtimeGlobe/RealtimeGlobe";
import { minutesAtom, MinutesType } from "./realtimeStore";
+import { DisabledOverlay } from "../../../components/DisabledOverlay";
export default function RealtimePage() {
useSetPageTitle("Rybbit · Realtime");
@@ -27,66 +28,68 @@ export default function RealtimePage() {
const { data } = useGetLiveUsercount(Number(minutes));
return (
- <div className="relative overflow-hidden" ref={ref}>
- <World width={width ?? 0} />
+ <DisabledOverlay>
+ <div className="relative overflow-hidden" ref={ref}>
+ <World width={width ?? 0} />
- <div className="absolute top-2 left-2 md:top-4 md:left-4 flex flex-row gap-2 items-start">
- <MobileSidebar />
- <div className="flex flex-col p-2 md:p-3 bg-neutral-900 rounded-lg shadow-lg border border-neutral-750 w-[300px] md:w-[400px]">
- <div className="p-2">
- <div className="text-sm text-gray-400 flex gap-2 text-nowrap items-center">
- <div className="flex justify-center">
- <span className="relative flex h-3 w-3">
- <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-green-400 opacity-75"></span>
- <span className="relative inline-flex h-3 w-3 rounded-full bg-green-500"></span>
- </span>
+ <div className="absolute top-2 left-2 md:top-4 md:left-4 flex flex-row gap-2 items-start">
+ <MobileSidebar />
+ <div className="flex flex-col p-2 md:p-3 bg-neutral-900 rounded-lg shadow-lg border border-neutral-750 w-[300px] md:w-[400px]">
+ <div className="p-2">
+ <div className="text-sm text-gray-400 flex gap-2 text-nowrap items-center">
+ <div className="flex justify-center">
+ <span className="relative flex h-3 w-3">
+ <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-green-400 opacity-75"></span>
+ <span className="relative inline-flex h-3 w-3 rounded-full bg-green-500"></span>
+ </span>
+ </div>
+ Visitors in the last{" "}
+ <Select
+ value={minutes}
+ onValueChange={(value) => setMinutes(value as MinutesType)}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Select a time period" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="5">5 minutes</SelectItem>
+ <SelectItem value="15">15 minutes</SelectItem>
+ <SelectItem value="30">30 minutes</SelectItem>
+ <SelectItem value="60">1 hour</SelectItem>
+ <SelectItem value="120">2 hours</SelectItem>
+ <SelectItem value="240">4 hours</SelectItem>
+ <SelectItem value="480">8 hours</SelectItem>
+ <SelectItem value="720">12 hours</SelectItem>
+ <SelectItem value="1440">24 hours</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="text-3xl md:text-5xl font-bold flex items-center gap-2">
+ {
+ <NumberFlow
+ respectMotionPreference={false}
+ value={data?.count ?? 0}
+ />
+ }
</div>
- Visitors in the last{" "}
- <Select
- value={minutes}
- onValueChange={(value) => setMinutes(value as MinutesType)}
- >
- <SelectTrigger>
- <SelectValue placeholder="Select a time period" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="5">5 minutes</SelectItem>
- <SelectItem value="15">15 minutes</SelectItem>
- <SelectItem value="30">30 minutes</SelectItem>
- <SelectItem value="60">1 hour</SelectItem>
- <SelectItem value="120">2 hours</SelectItem>
- <SelectItem value="240">4 hours</SelectItem>
- <SelectItem value="480">8 hours</SelectItem>
- <SelectItem value="720">12 hours</SelectItem>
- <SelectItem value="1440">24 hours</SelectItem>
- </SelectContent>
- </Select>
</div>
- <div className="text-3xl md:text-5xl font-bold flex items-center gap-2">
- {
- <NumberFlow
- respectMotionPreference={false}
- value={data?.count ?? 0}
- />
- }
+ <div className="h-[50px] md:h-[70px]">
+ <RealtimeChart />
</div>
</div>
- <div className="h-[50px] md:h-[70px]">
- <RealtimeChart />
- </div>
</div>
- </div>
- <div className="hidden md:block absolute top-4 right-4 w-[320px]">
- <RealtimeEvents />
- </div>
+ <div className="hidden md:block absolute top-4 right-4 w-[320px]">
+ <RealtimeEvents />
+ </div>
- {/* <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ {/* <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Pages isRealtime />
<Events isRealtime />
<Referrers isRealtime />
<Countries isRealtime />
- </div> */}
- </div>
+ </div> */}
+ </div>
+ </DisabledOverlay>
);
}
diff --git a/client/src/app/[site]/retention/page.tsx b/client/src/app/[site]/retention/page.tsx
index ecd51f27e..30ff12545 100644
--- a/client/src/app/[site]/retention/page.tsx
+++ b/client/src/app/[site]/retention/page.tsx
@@ -25,6 +25,7 @@ import { Tabs, TabsList, TabsTrigger } from "../../../components/ui/tabs";
import { RetentionChart } from "./RetentionChart";
import { NothingFound } from "../../../components/NothingFound";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
+import { DisabledOverlay } from "../../../components/DisabledOverlay";
// Available time range options (in days)
const RANGE_OPTIONS = [
@@ -107,13 +108,19 @@ export default function RetentionPage() {
// If same month, don't repeat month name
if (startDate.month === endDate.month) {
- return `${startDate.toFormat("MMM dd")} - ${endDate.toFormat("dd, yyyy")}`;
+ return `${startDate.toFormat("MMM dd")} - ${endDate.toFormat(
+ "dd, yyyy"
+ )}`;
} else if (startDate.year === endDate.year) {
// Different months, same year
- return `${startDate.toFormat("MMM dd")} - ${endDate.toFormat("MMM dd, yyyy")}`;
+ return `${startDate.toFormat("MMM dd")} - ${endDate.toFormat(
+ "MMM dd, yyyy"
+ )}`;
} else {
// Different years
- return `${startDate.toFormat("MMM dd, yyyy")} - ${endDate.toFormat("MMM dd, yyyy")}`;
+ return `${startDate.toFormat("MMM dd, yyyy")} - ${endDate.toFormat(
+ "MMM dd, yyyy"
+ )}`;
}
}
};
@@ -211,91 +218,93 @@ export default function RetentionPage() {
: [];
return (
- <div className="p-2 md:p-4 max-w-[1300px] mx-auto flex flex-col gap-3">
- {/* Single Card containing both chart and grid */}
- <FilterControls />
- <Card>
- <CardHeader className="flex flex-row items-center justify-between pb-2">
- <CardTitle>Retention</CardTitle>
- </CardHeader>
- <CardContent className="space-y-6">
- {isLoading ? (
- <ThreeDotLoader />
- ) : data ? (
- <RetentionChart data={data} isLoading={false} mode={mode} />
- ) : null}
- </CardContent>
- </Card>
- <Card className="pt-3">
- <CardContent className="space-y-6 px-2">
- <div>
+ <DisabledOverlay>
+ <div className="p-2 md:p-4 max-w-[1300px] mx-auto flex flex-col gap-3">
+ {/* Single Card containing both chart and grid */}
+ <FilterControls />
+ <Card>
+ <CardHeader className="flex flex-row items-center justify-between pb-2">
+ <CardTitle>Retention</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-6">
{isLoading ? (
<ThreeDotLoader />
) : data ? (
- <div className="overflow-x-auto">
- <div
- className="inline-grid gap-px bg-neutral-900 rounded-lg shadow-lg"
- style={{
- gridTemplateColumns: `minmax(120px, auto) repeat(${
- data.maxPeriods + 1
- }, minmax(80px, auto))`,
- }}
- >
- {/* Header Row */}
- <div className="p-2 text-sm font-semibold bg-neutral-900 text-neutral-100 text-center sticky left-0 z-10 border-b border-r border-neutral-700">
- Cohort
- </div>
- {periodHeaders.map((header) => (
- <div
- key={header}
- className="p-2 text-sm bg-neutral-900 text-neutral-100 text-center border-b border-neutral-700"
- >
- {header}
+ <RetentionChart data={data} isLoading={false} mode={mode} />
+ ) : null}
+ </CardContent>
+ </Card>
+ <Card className="pt-3">
+ <CardContent className="space-y-6 px-2">
+ <div>
+ {isLoading ? (
+ <ThreeDotLoader />
+ ) : data ? (
+ <div className="overflow-x-auto">
+ <div
+ className="inline-grid gap-px bg-neutral-900 rounded-lg shadow-lg"
+ style={{
+ gridTemplateColumns: `minmax(120px, auto) repeat(${
+ data.maxPeriods + 1
+ }, minmax(80px, auto))`,
+ }}
+ >
+ {/* Header Row */}
+ <div className="p-2 text-sm font-semibold bg-neutral-900 text-neutral-100 text-center sticky left-0 z-10 border-b border-r border-neutral-700">
+ Cohort
</div>
- ))}
+ {periodHeaders.map((header) => (
+ <div
+ key={header}
+ className="p-2 text-sm bg-neutral-900 text-neutral-100 text-center border-b border-neutral-700"
+ >
+ {header}
+ </div>
+ ))}
- {/* Data Rows */}
- {cohortKeys.map((cohortPeriod) => (
- <Fragment key={cohortPeriod}>
- {/* Cohort Info Cell */}
- <div className="py-2 px-2 bg-neutral-900 text-sm sticky left-0 z-10 border-r border-neutral-800">
- <div className="whitespace-nowrap text-neutral-100">
- {formatDate(cohortPeriod)}
+ {/* Data Rows */}
+ {cohortKeys.map((cohortPeriod) => (
+ <Fragment key={cohortPeriod}>
+ {/* Cohort Info Cell */}
+ <div className="py-2 px-2 bg-neutral-900 text-sm sticky left-0 z-10 border-r border-neutral-800">
+ <div className="whitespace-nowrap text-neutral-100">
+ {formatDate(cohortPeriod)}
+ </div>
+ <div className="text-xs text-neutral-300 mt-1 whitespace-nowrap">
+ {data.cohorts[cohortPeriod].size.toLocaleString()}{" "}
+ users
+ </div>
</div>
- <div className="text-xs text-neutral-300 mt-1 whitespace-nowrap">
- {data.cohorts[cohortPeriod].size.toLocaleString()}{" "}
- users
- </div>
- </div>
- {/* Retention Cells */}
- {data.cohorts[cohortPeriod].percentages.map(
- (percentage: number | null, index: number) => {
- const { backgroundColor, textColor } =
- getRetentionColor(percentage);
- return (
- <div
- key={`${cohortPeriod}-period-${index}`}
- className="m-[2px] text-center flex items-center justify-center font-medium transition-colors duration-150 bg-neutral-900 rounded-md"
- style={{
- backgroundColor,
- color: textColor,
- }}
- >
- {percentage !== null
- ? `${percentage.toFixed(1)}%`
- : "-"}
- </div>
- );
- }
- )}
- </Fragment>
- ))}
+ {/* Retention Cells */}
+ {data.cohorts[cohortPeriod].percentages.map(
+ (percentage: number | null, index: number) => {
+ const { backgroundColor, textColor } =
+ getRetentionColor(percentage);
+ return (
+ <div
+ key={`${cohortPeriod}-period-${index}`}
+ className="m-[2px] text-center flex items-center justify-center font-medium transition-colors duration-150 bg-neutral-900 rounded-md"
+ style={{
+ backgroundColor,
+ color: textColor,
+ }}
+ >
+ {percentage !== null
+ ? `${percentage.toFixed(1)}%`
+ : "-"}
+ </div>
+ );
+ }
+ )}
+ </Fragment>
+ ))}
+ </div>
</div>
- </div>
- ) : null}
- </div>
- </CardContent>
- </Card>
- </div>
+ ) : null}
+ </div>
+ </CardContent>
+ </Card>
+ </div>
+ </DisabledOverlay>
);
}
diff --git a/client/src/app/[site]/sessions/page.tsx b/client/src/app/[site]/sessions/page.tsx
index 2481ece12..fdab55e72 100644
--- a/client/src/app/[site]/sessions/page.tsx
+++ b/client/src/app/[site]/sessions/page.tsx
@@ -1,5 +1,6 @@
"use client";
+import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { SESSION_PAGE_FILTERS } from "../../../lib/store";
import { SubHeader } from "../components/SubHeader/SubHeader";
@@ -9,9 +10,11 @@ export default function SessionsPage() {
useSetPageTitle("Rybbit · Sessions");
return (
- <div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3">
- <SubHeader availableFilters={SESSION_PAGE_FILTERS} />
- <SessionsList />
- </div>
+ <DisabledOverlay>
+ <div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3">
+ <SubHeader availableFilters={SESSION_PAGE_FILTERS} />
+ <SessionsList />
+ </div>
+ </DisabledOverlay>
);
}
diff --git a/client/src/app/[site]/users/page.tsx b/client/src/app/[site]/users/page.tsx
index ec4f193ea..af5e0c3cd 100644
--- a/client/src/app/[site]/users/page.tsx
+++ b/client/src/app/[site]/users/page.tsx
@@ -38,6 +38,7 @@ import { Browser } from "../components/shared/icons/Browser";
import { CountryFlag } from "../components/shared/icons/CountryFlag";
import { OperatingSystem } from "../components/shared/icons/OperatingSystem";
import { SubHeader } from "../components/SubHeader/SubHeader";
+import { DisabledOverlay } from "../../../components/DisabledOverlay";
// Set up column helper
const columnHelper = createColumnHelper<UsersResponse>();
@@ -276,108 +277,110 @@ export default function UsersPage() {
}
return (
- <div className="p-2 md:p-4 max-w-[1400px] mx-auto space-y-3">
- <SubHeader availableFilters={USER_PAGE_FILTERS} />
- <div className="rounded-md border border-neutral-800 bg-neutral-900">
- <div className="relative overflow-x-auto">
- <table className="w-full text-sm text-left">
- <thead className="bg-neutral-850 text-neutral-400 ">
- {table.getHeaderGroups().map((headerGroup) => (
- <tr key={headerGroup.id}>
- {headerGroup.headers.map((header) => (
- <th
- key={header.id}
- scope="col"
- className="px-3 py-1 font-medium whitespace-nowrap"
- style={{
- minWidth: header.id === "user_id" ? "100px" : "auto",
- }}
- >
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext()
- )}
- </th>
- ))}
- </tr>
- ))}
- </thead>
- <tbody>
- {isLoading ? (
- Array.from({ length: 15 }).map((_, index) => (
- <tr
- key={index}
- className="border-b border-neutral-800 animate-pulse"
- >
- {Array.from({ length: columns.length }).map(
- (_, cellIndex) => (
- <td key={cellIndex} className="px-3 py-3">
- <div className="h-4 bg-neutral-800 rounded"></div>
- </td>
- )
- )}
+ <DisabledOverlay>
+ <div className="p-2 md:p-4 max-w-[1400px] mx-auto space-y-3">
+ <SubHeader availableFilters={USER_PAGE_FILTERS} />
+ <div className="rounded-md border border-neutral-800 bg-neutral-900">
+ <div className="relative overflow-x-auto">
+ <table className="w-full text-sm text-left">
+ <thead className="bg-neutral-850 text-neutral-400 ">
+ {table.getHeaderGroups().map((headerGroup) => (
+ <tr key={headerGroup.id}>
+ {headerGroup.headers.map((header) => (
+ <th
+ key={header.id}
+ scope="col"
+ className="px-3 py-1 font-medium whitespace-nowrap"
+ style={{
+ minWidth: header.id === "user_id" ? "100px" : "auto",
+ }}
+ >
+ {header.isPlaceholder
+ ? null
+ : flexRender(
+ header.column.columnDef.header,
+ header.getContext()
+ )}
+ </th>
+ ))}
</tr>
- ))
- ) : table.getRowModel().rows.length === 0 ? (
- <tr>
- <td
- colSpan={columns.length}
- className="px-3 py-8 text-center text-neutral-400"
- >
- No users found
- </td>
- </tr>
- ) : (
- table.getRowModel().rows.map((row) => {
- const userId = row.original.user_id;
- const href = `/${site}/user/${userId}`;
-
- return (
+ ))}
+ </thead>
+ <tbody>
+ {isLoading ? (
+ Array.from({ length: 15 }).map((_, index) => (
<tr
- key={row.id}
- className="border-b border-neutral-800 hover:bg-neutral-800 cursor-pointer group"
+ key={index}
+ className="border-b border-neutral-800 animate-pulse"
>
- {row.getVisibleCells().map((cell) => (
- <td key={cell.id} className="px-3 py-3 relative">
- <Link
- href={href}
- className="absolute inset-0 z-10"
- aria-label={`View user ${userId}`}
- >
- <span className="sr-only">View user details</span>
- </Link>
- <span className="relative z-0">
- {flexRender(
- cell.column.columnDef.cell,
- cell.getContext()
- )}
- </span>
- </td>
- ))}
+ {Array.from({ length: columns.length }).map(
+ (_, cellIndex) => (
+ <td key={cellIndex} className="px-3 py-3">
+ <div className="h-4 bg-neutral-800 rounded"></div>
+ </td>
+ )
+ )}
</tr>
- );
- })
- )}
- </tbody>
- </table>
- </div>
+ ))
+ ) : table.getRowModel().rows.length === 0 ? (
+ <tr>
+ <td
+ colSpan={columns.length}
+ className="px-3 py-8 text-center text-neutral-400"
+ >
+ No users found
+ </td>
+ </tr>
+ ) : (
+ table.getRowModel().rows.map((row) => {
+ const userId = row.original.user_id;
+ const href = `/${site}/user/${userId}`;
+
+ return (
+ <tr
+ key={row.id}
+ className="border-b border-neutral-800 hover:bg-neutral-800 cursor-pointer group"
+ >
+ {row.getVisibleCells().map((cell) => (
+ <td key={cell.id} className="px-3 py-3 relative">
+ <Link
+ href={href}
+ className="absolute inset-0 z-10"
+ aria-label={`View user ${userId}`}
+ >
+ <span className="sr-only">View user details</span>
+ </Link>
+ <span className="relative z-0">
+ {flexRender(
+ cell.column.columnDef.cell,
+ cell.getContext()
+ )}
+ </span>
+ </td>
+ ))}
+ </tr>
+ );
+ })
+ )}
+ </tbody>
+ </table>
+ </div>
- {/* Pagination */}
- <div className="border-t border-neutral-800">
- <div className="px-4 py-3">
- <TablePagination
- table={table}
- data={{ items: data?.data || [], total: data?.totalCount || 0 }}
- pagination={pagination}
- setPagination={setPagination}
- isLoading={isLoading}
- itemName="users"
- />
+ {/* Pagination */}
+ <div className="border-t border-neutral-800">
+ <div className="px-4 py-3">
+ <TablePagination
+ table={table}
+ data={{ items: data?.data || [], total: data?.totalCount || 0 }}
+ pagination={pagination}
+ setPagination={setPagination}
+ isLoading={isLoading}
+ itemName="users"
+ />
+ </div>
</div>
</div>
</div>
- </div>
+ </DisabledOverlay>
);
}
diff --git a/client/src/app/components/AddSite.tsx b/client/src/app/components/AddSite.tsx
index d8d9311d6..8fb405c5c 100644
--- a/client/src/app/components/AddSite.tsx
+++ b/client/src/app/components/AddSite.tsx
@@ -3,6 +3,7 @@ import { Button } from "@/components/ui/button";
import { AlertCircle, AppWindow, Building2, Plus } from "lucide-react";
import { useEffect, useState } from "react";
import { addSite, useGetSites } from "../../api/admin/sites";
+import { useStripeSubscription } from "../settings/subscription/utils/useStripeSubscription";
import { Alert, AlertDescription, AlertTitle } from "../../components/ui/alert";
import {
Dialog,
@@ -24,6 +25,12 @@ import {
} from "../../components/ui/select";
import { Switch } from "../../components/ui/switch";
import { authClient } from "../../lib/auth";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "../../components/ui/tooltip";
+import { IS_CLOUD } from "../../lib/const";
/**
* A simple domain validation function:
@@ -46,9 +53,15 @@ export function AddSite({
}) {
const { data: sites, refetch } = useGetSites();
const { data: organizations } = authClient.useListOrganizations();
+ const { data: subscription } = useStripeSubscription();
const existingSites = sites?.map((site) => site.domain);
+ // Disable if user is on free plan and has 3+ sites
+ const isDisabledDueToLimit =
+ subscription?.status !== "active" && (sites?.length || 0) >= 3 && IS_CLOUD;
+ const finalDisabled = disabled || isDisabledDueToLimit;
+
const [open, setOpen] = useState(false);
const [domain, setDomain] = useState("");
const [selectedOrganizationId, setSelectedOrganizationId] =
@@ -107,6 +120,23 @@ export function AddSite({
}
};
+ // Show upgrade message if disabled due to limit
+ if (isDisabledDueToLimit) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button disabled title="Upgrade to Pro to add more websites">
+ <Plus className="h-4 w-4" />
+ Add Website
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>Upgrade to Pro to add more websites</TooltipContent>
+ </Tooltip>
+ );
+ }
+
return (
<div>
<Dialog
@@ -120,7 +150,7 @@ export function AddSite({
>
<DialogTrigger asChild>
{trigger || (
- <Button disabled={disabled}>
+ <Button disabled={finalDisabled}>
<Plus className="h-4 w-4" />
Add Website
</Button>
diff --git a/client/src/app/page.tsx b/client/src/app/page.tsx
index 5da16337c..37ef5aa22 100644
--- a/client/src/app/page.tsx
+++ b/client/src/app/page.tsx
@@ -4,15 +4,15 @@ import { Plus } from "lucide-react";
import { useState } from "react";
import { useUserOrganizations } from "../api/admin/organizations";
import { useGetSites } from "../api/admin/sites";
+import { CreateOrganizationDialog } from "../components/CreateOrganizationDialog";
+import { FreePlanBanner } from "../components/FreePlanBanner";
import { NoOrganization } from "../components/NoOrganization";
import { SiteCard } from "../components/SiteCard";
import { StandardPage } from "../components/StandardPage";
import { Button } from "../components/ui/button";
import { Card, CardDescription, CardTitle } from "../components/ui/card";
-import { AddSite } from "./components/AddSite";
-import { CreateOrganizationDialog } from "../components/CreateOrganizationDialog";
-import { FreeTrialBanner } from "../components/FreeTrialBanner";
import { useSetPageTitle } from "../hooks/useSetPageTitle";
+import { AddSite } from "./components/AddSite";
export default function Home() {
useSetPageTitle("Rybbit · Home");
@@ -47,7 +47,7 @@ export default function Home() {
return (
<StandardPage>
- <FreeTrialBanner />
+ <FreePlanBanner />
<div className="flex justify-between items-center my-4">
<div className="text-2xl font-bold">{sites?.length} Websites</div>
<AddSite disabled={hasNoOrganizations || disabled} />
diff --git a/client/src/app/settings/subscription/components/FreePlan.tsx b/client/src/app/settings/subscription/components/FreePlan.tsx
new file mode 100644
index 000000000..9eea91f20
--- /dev/null
+++ b/client/src/app/settings/subscription/components/FreePlan.tsx
@@ -0,0 +1,121 @@
+import { AlertTriangle, ArrowRight, PackageOpen } from "lucide-react";
+import { useRouter } from "next/navigation";
+import { DateTime } from "luxon";
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+} from "../../../../components/ui/alert";
+import { Button } from "../../../../components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "../../../../components/ui/card";
+import { Progress } from "../../../../components/ui/progress";
+import { useUserOrganizations } from "../../../../api/admin/organizations";
+import { DEFAULT_EVENT_LIMIT } from "../utils/constants";
+import { useStripeSubscription } from "../utils/useStripeSubscription";
+import { UsageChart } from "../../../../components/UsageChart";
+
+export function FreePlan() {
+ const { data: subscription } = useStripeSubscription();
+ const { data: organizations } = useUserOrganizations();
+ const router = useRouter();
+
+ // Get the first organization (assuming user is part of one organization for now)
+ const organizationId = organizations?.[0]?.id;
+
+ // Get last 30 days of data for the chart
+ const endDate = DateTime.now().toISODate();
+ const startDate = DateTime.now().minus({ days: 30 }).toISODate();
+
+ if (!subscription) return null;
+
+ const currentUsage = subscription?.monthlyEventCount || 0;
+ const limit = subscription?.eventLimit || DEFAULT_EVENT_LIMIT;
+
+ // Calculate percentage of limit used
+ const percentageUsed = Math.min((currentUsage / limit) * 100, 100);
+ const isNearLimit = percentageUsed > 80;
+ const isLimitExceeded = currentUsage >= limit;
+
+ return (
+ <div className="space-y-6">
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center">Free Plan</CardTitle>
+ <CardDescription>
+ You are on the Free plan with up to 3,000 events per month.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-6">
+ {isLimitExceeded ? (
+ <Alert className="bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800">
+ <AlertTriangle className="h-4 w-4 text-red-500 dark:text-red-400" />
+ <AlertTitle>Event Limit Exceeded</AlertTitle>
+ <AlertDescription>
+ You have exceeded your monthly event limit. Please upgrade to
+ a Pro plan to continue collecting analytics.
+ </AlertDescription>
+ </Alert>
+ ) : (
+ isNearLimit && (
+ <Alert className="bg-amber-50 dark:bg-amber-900/20 border-amber-200 dark:border-amber-800">
+ <AlertTriangle className="h-4 w-4 text-amber-500 dark:text-amber-400" />
+ <AlertTitle>Approaching Limit</AlertTitle>
+ <AlertDescription>
+ You are approaching your monthly event limit. Consider
+ upgrading to a paid plan for higher limits.
+ </AlertDescription>
+ </Alert>
+ )
+ )}
+
+ <div className="space-y-2">
+ <h3 className="font-medium mb-2">Usage</h3>
+ <div className="space-y-4">
+ <div>
+ <div className="flex justify-between mb-1">
+ <span className="text-sm">Events</span>
+ <span className="text-sm">
+ {currentUsage.toLocaleString()} / {limit.toLocaleString()}
+ </span>
+ </div>
+ <Progress
+ value={percentageUsed}
+ className={
+ isNearLimit ? "bg-amber-100 dark:bg-amber-900" : ""
+ }
+ />
+ </div>
+ </div>
+ </div>
+
+ {organizationId && (
+ <div className="space-y-2">
+ <h3 className="font-medium text-sm text-neutral-400 mb-2">
+ Last 30 Days
+ </h3>
+ <UsageChart
+ organizationId={organizationId}
+ startDate={startDate}
+ endDate={endDate}
+ />
+ </div>
+ )}
+ </div>
+ </CardContent>
+ <CardFooter>
+ <Button onClick={() => router.push("/subscribe")} variant={"success"}>
+ Upgrade To Pro <ArrowRight className="ml-2 h-4 w-4" />
+ </Button>
+ </CardFooter>
+ </Card>
+ </div>
+ );
+}
diff --git a/client/src/app/settings/subscription/components/ProPlan.tsx b/client/src/app/settings/subscription/components/ProPlan.tsx
index 47b6dfa5e..df5415696 100644
--- a/client/src/app/settings/subscription/components/ProPlan.tsx
+++ b/client/src/app/settings/subscription/components/ProPlan.tsx
@@ -1,14 +1,17 @@
import { Shield } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
+import { DateTime } from "luxon";
import { Alert } from "../../../../components/ui/alert";
import { Button } from "../../../../components/ui/button";
import { Card, CardContent } from "../../../../components/ui/card";
import { Progress } from "../../../../components/ui/progress";
+import { useUserOrganizations } from "../../../../api/admin/organizations";
import { BACKEND_URL } from "../../../../lib/const";
import { getStripePrices } from "../../../../lib/stripe";
import { formatDate } from "../utils/planUtils";
import { useStripeSubscription } from "../utils/useStripeSubscription";
+import { UsageChart } from "../../../../components/UsageChart";
export function ProPlan() {
const {
@@ -18,6 +21,15 @@ export function ProPlan() {
refetch,
} = useStripeSubscription();
+ const { data: organizations } = useUserOrganizations();
+
+ // Get the first organization (assuming user is part of one organization for now)
+ const organizationId = organizations?.[0]?.id;
+
+ // Get last 30 days of data for the chart
+ const endDate = DateTime.now().toISODate();
+ const startDate = DateTime.now().minus({ days: 30 }).toISODate();
+
const [isProcessing, setIsProcessing] = useState(false);
const [actionError, setActionError] = useState<string | null>(null);
@@ -189,6 +201,19 @@ export function ProPlan() {
</div>
</div>
+ {organizationId && (
+ <div className="space-y-2">
+ <h3 className="font-medium text-sm text-neutral-400 mb-2">
+ Last 30 Days
+ </h3>
+ <UsageChart
+ organizationId={organizationId}
+ startDate={startDate}
+ endDate={endDate}
+ />
+ </div>
+ )}
+
{isAnnualPlan && (
<div className="pt-2 pb-0 px-3 bg-emerald-50 dark:bg-emerald-900/20 rounded-md border border-emerald-100 dark:border-emerald-800">
<p className="text-sm text-emerald-700 dark:text-emerald-300 py-2">
diff --git a/client/src/app/settings/subscription/page.tsx b/client/src/app/settings/subscription/page.tsx
index dba2b4b84..1403d2a3e 100644
--- a/client/src/app/settings/subscription/page.tsx
+++ b/client/src/app/settings/subscription/page.tsx
@@ -9,6 +9,7 @@ import { NoOrganization } from "../../../components/NoOrganization";
import { TrialPlan } from "./components/TrialPlan";
import { ExpiredTrialPlan } from "./components/ExpiredTrialPlan";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
+import { FreePlan } from "./components/FreePlan";
export default function SubscriptionPage() {
useSetPageTitle("Rybbit · Subscription");
@@ -39,6 +40,11 @@ export default function SubscriptionPage() {
return <ExpiredTrialPlan message={activeSubscription.message} />;
}
+ // Check if user is on free plan
+ if (activeSubscription.status === "free") {
+ return <FreePlan />;
+ }
+
if (activeSubscription.isTrial) {
return <TrialPlan />;
}
diff --git a/client/src/app/settings/subscription/utils/constants.ts b/client/src/app/settings/subscription/utils/constants.ts
index 75a6c50e5..c08fcfd2b 100644
--- a/client/src/app/settings/subscription/utils/constants.ts
+++ b/client/src/app/settings/subscription/utils/constants.ts
@@ -1,2 +1,5 @@
export const TRIAL_EVENT_LIMIT = 1_000_000;
export const TRIAL_DURATION_DAYS = 14;
+
+// Default limit for the free tier
+export const DEFAULT_EVENT_LIMIT = 3_000;
diff --git a/client/src/app/settings/subscription/utils/useStripeSubscription.ts b/client/src/app/settings/subscription/utils/useStripeSubscription.ts
index feee56b11..2daee5894 100644
--- a/client/src/app/settings/subscription/utils/useStripeSubscription.ts
+++ b/client/src/app/settings/subscription/utils/useStripeSubscription.ts
@@ -4,7 +4,7 @@ import { BACKEND_URL } from "../../../../lib/const";
interface SubscriptionData {
id: string;
planName: string;
- status: "expired" | "active" | "trialing";
+ status: "expired" | "active" | "trialing" | "free";
currentPeriodEnd: string;
currentPeriodStart: string;
monthlyEventCount: number;
diff --git a/client/src/app/subscribe/page.tsx b/client/src/app/subscribe/page.tsx
index c0d4dce64..d4497ad96 100644
--- a/client/src/app/subscribe/page.tsx
+++ b/client/src/app/subscribe/page.tsx
@@ -3,20 +3,21 @@
import { authClient } from "@/lib/auth";
import { getStripePrices } from "@/lib/stripe";
import { useRouter } from "next/navigation";
+import { DateTime } from "luxon";
+import { TrendingUp } from "lucide-react";
import { StandardPage } from "../../components/StandardPage";
import { useStripeSubscription } from "../settings/subscription/utils/useStripeSubscription";
+import { useUserOrganizations } from "../../api/admin/organizations";
+import { useGetOrgEventCount } from "../../api/analytics/useGetOrgEventCount";
+import { UsageChart } from "../../components/UsageChart";
import { PricingHeader } from "./components/PricingHeader";
-import {
- TrialUsageStats,
- daysElapsed,
- extrapolateMonthlyUsage,
-} from "./components/TrialUsageStats";
import { PricingCard } from "./components/PricingCard";
import { FAQSection } from "./components/FAQSection";
export default function Subscribe() {
const { data: sessionData } = authClient.useSession();
const { data: subscription } = useStripeSubscription();
+ const { data: organizations } = useUserOrganizations();
const router = useRouter();
// Redirect if already subscribed
@@ -24,14 +25,24 @@ export default function Subscribe() {
router.push("/settings/subscription");
}
- // Calculate trial usage metrics
- const currentUsage = subscription?.monthlyEventCount || 0;
- const trialStartDate = subscription?.currentPeriodStart;
- const daysInTrial = trialStartDate ? daysElapsed(trialStartDate) : 14;
- const projectedMonthlyUsage = extrapolateMonthlyUsage(
- currentUsage,
- daysInTrial
- );
+ // Get the first organization
+ const organizationId = organizations?.[0]?.id;
+
+ // Get last 30 days of data
+ const endDate = DateTime.now().toISODate();
+ const startDate = DateTime.now().minus({ days: 30 }).toISODate();
+
+ // Fetch usage data for the chart and total calculation
+ const { data: eventCountData } = useGetOrgEventCount({
+ organizationId: organizationId || "",
+ startDate,
+ endDate,
+ enabled: !!organizationId,
+ });
+
+ // Calculate total events over the past 30 days
+ const totalEvents =
+ eventCountData?.data?.reduce((sum, day) => sum + day.event_count, 0) || 0;
return (
<StandardPage>
@@ -44,12 +55,35 @@ export default function Subscribe() {
isLoggedIn={!!sessionData?.user}
/>
- {/* Trial Usage Stats */}
- <TrialUsageStats
- currentUsage={currentUsage}
- daysInTrial={daysInTrial}
- projectedMonthlyUsage={projectedMonthlyUsage}
- />
+ {/* Usage Stats and Chart */}
+ {organizationId && (
+ <div className="max-w-lg mx-auto mt-6">
+ <div className="bg-blue-900/20 rounded-xl border border-blue-800 p-6">
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center gap-2">
+ <TrendingUp className="h-5 w-5 text-blue-400" />
+ <h3 className="font-semibold text-lg">
+ Your Usage (Last 30 Days)
+ </h3>
+ </div>
+ <div className="text-right">
+ <p className="text-2xl font-bold text-blue-300">
+ {totalEvents.toLocaleString()}
+ </p>
+ <p className="text-xs text-neutral-400">total events</p>
+ </div>
+ </div>
+
+ <div className="p-1">
+ <UsageChart
+ organizationId={organizationId}
+ startDate={startDate}
+ endDate={endDate}
+ />
+ </div>
+ </div>
+ </div>
+ )}
{/* FAQ Section */}
<div className="max-w-lg mx-auto">
diff --git a/client/src/components/DisabledOverlay.tsx b/client/src/components/DisabledOverlay.tsx
new file mode 100644
index 000000000..9eb280965
--- /dev/null
+++ b/client/src/components/DisabledOverlay.tsx
@@ -0,0 +1,74 @@
+import { ArrowRight, Crown } from "lucide-react";
+import Link from "next/link";
+import React, { ReactNode } from "react";
+import { useStripeSubscription } from "../app/settings/subscription/utils/useStripeSubscription";
+import { Button } from "./ui/button";
+
+interface DisabledOverlayProps {
+ children: ReactNode;
+ message?: string;
+ blur?: number;
+ borderRadius?: number;
+ showMessage?: boolean;
+ style?: React.CSSProperties;
+}
+
+function defaultMessage(message: string) {
+ return (
+ <div className="bg-neutral-900 rounded-lg border border-neutral-700 shadow-xl flex items-center gap-3 p-4">
+ <Crown className="h-5 w-5 text-amber-500 flex-shrink-0" />
+ <div className="flex-1">
+ <p className="text-sm text-muted-foreground">
+ Upgrade to <span className="font-medium text-foreground">Pro</span> to
+ unlock {message}
+ </p>
+ </div>
+ <Button asChild size="sm" variant="success">
+ <Link href="/subscribe">
+ Upgrade <ArrowRight className="ml-1 h-3 w-3" />
+ </Link>
+ </Button>
+ </div>
+ );
+}
+
+export const DisabledOverlay: React.FC<DisabledOverlayProps> = ({
+ children,
+ message = "this feature",
+ blur = 10,
+ borderRadius = 0,
+ showMessage = true,
+ style,
+}) => {
+ const { data: subscription } = useStripeSubscription();
+
+ const disabled = subscription?.planName === "free";
+
+ if (!disabled) {
+ return <>{children}</>;
+ }
+
+ const borderRadiusStyle =
+ borderRadius > 0 ? { borderRadius: `${borderRadius}px` } : {};
+
+ return (
+ <div className="relative" style={style}>
+ <div
+ className={disabled ? "filter" : ""}
+ style={disabled ? { filter: `blur(${blur}px)` } : {}}
+ >
+ {children}
+ </div>
+ <div
+ className="absolute inset-0 flex items-center justify-center z-10"
+ style={borderRadiusStyle}
+ >
+ {showMessage && (
+ <div className="flex items-center justify-center">
+ {defaultMessage(message)}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/client/src/components/FreePlanBanner.tsx b/client/src/components/FreePlanBanner.tsx
new file mode 100644
index 000000000..1b3a69caf
--- /dev/null
+++ b/client/src/components/FreePlanBanner.tsx
@@ -0,0 +1,43 @@
+import { ArrowRight } from "lucide-react";
+import Link from "next/link";
+import { useStripeSubscription } from "../app/settings/subscription/utils/useStripeSubscription";
+import { Button } from "./ui/button";
+import { DEFAULT_EVENT_LIMIT } from "../app/settings/subscription/utils/constants";
+
+export function FreePlanBanner() {
+ const { data: subscription } = useStripeSubscription();
+
+ // Don't show the banner if no subscription data or if there's a paid subscription
+ if (!subscription) {
+ return null;
+ }
+
+ // Format numbers with commas
+ const formatNumber = (num: number = 0) => {
+ return num.toLocaleString();
+ };
+
+ // Active trial banner - slightly more visible but still minimal
+ if (subscription.planName === "free") {
+ const eventLimit = subscription.eventLimit || DEFAULT_EVENT_LIMIT;
+ const eventsUsed = subscription.monthlyEventCount || 0;
+
+ return (
+ <div className="mt-4 px-4 py-3 rounded-lg border border-blue-100 dark:border-blue-400/30 bg-blue-50/80 dark:bg-blue-900/20 text-sm flex gap-4 items-center">
+ <div className="text-blue-700 dark:text-blue-300 flex items-center font-medium">
+ <span>
+ Free plan: Using <strong>{formatNumber(eventsUsed)}</strong> of{" "}
+ {formatNumber(eventLimit)} events
+ </span>
+ </div>
+ <Button variant="success" size="sm" asChild>
+ <Link href="/subscribe">
+ Upgrade <ArrowRight className="ml-1 h-3 w-3" />
+ </Link>
+ </Button>
+ </div>
+ );
+ }
+
+ return null;
+}
diff --git a/client/src/components/FreeTrialBanner.tsx b/client/src/components/FreeTrialBanner.tsx
index f8c9fe9f6..c86f96cc4 100644
--- a/client/src/components/FreeTrialBanner.tsx
+++ b/client/src/components/FreeTrialBanner.tsx
@@ -3,6 +3,7 @@ import { Alert, AlertDescription, AlertTitle } from "./ui/alert";
import { useStripeSubscription } from "../app/settings/subscription/utils/useStripeSubscription";
import Link from "next/link";
import { Button } from "./ui/button";
+import { DEFAULT_EVENT_LIMIT } from "../app/settings/subscription/utils/constants";
export function FreeTrialBanner() {
const { data: subscription } = useStripeSubscription();
@@ -20,7 +21,7 @@ export function FreeTrialBanner() {
// Active trial banner - slightly more visible but still minimal
if (subscription.isTrial) {
const daysRemaining = subscription.trialDaysRemaining || 0;
- const eventLimit = subscription.eventLimit || 100000;
+ const eventLimit = subscription.eventLimit || DEFAULT_EVENT_LIMIT;
const eventsUsed = subscription.monthlyEventCount || 0;
return (
diff --git a/client/src/components/UsageChart.tsx b/client/src/components/UsageChart.tsx
new file mode 100644
index 000000000..3df2eb52a
--- /dev/null
+++ b/client/src/components/UsageChart.tsx
@@ -0,0 +1,180 @@
+"use client";
+import { nivoTheme } from "@/lib/nivo";
+import { ResponsiveLine } from "@nivo/line";
+import { useWindowSize } from "@uidotdev/usehooks";
+import { DateTime } from "luxon";
+import { useGetOrgEventCount } from "../api/analytics/useGetOrgEventCount";
+import { userLocale, hour12 } from "../lib/dateTimeUtils";
+
+export const formatter = Intl.NumberFormat(userLocale, { notation: "compact" });
+
+interface UsageChartProps {
+ organizationId: string;
+ startDate?: string;
+ endDate?: string;
+ timeZone?: string;
+}
+
+export function UsageChart({
+ organizationId,
+ startDate,
+ endDate,
+ timeZone = "UTC",
+}: UsageChartProps) {
+ const { width } = useWindowSize();
+
+ // Fetch the data inside the component
+ const { data, isLoading, error } = useGetOrgEventCount({
+ organizationId,
+ startDate,
+ endDate,
+ timeZone,
+ enabled: !!organizationId,
+ });
+
+ const maxTicks = Math.round((width ?? Infinity) / 200);
+
+ const formattedData =
+ data?.data
+ ?.map((e) => {
+ // Parse timestamp properly - now it's a date instead of datetime
+ const timestamp = DateTime.fromSQL(e.event_date).toUTC();
+
+ // filter out dates from the future
+ if (timestamp > DateTime.now()) {
+ return null;
+ }
+
+ return {
+ x: timestamp.toFormat("yyyy-MM-dd"),
+ y: e.event_count,
+ currentTime: timestamp,
+ };
+ })
+ .filter((e) => e !== null) || [];
+
+ const chartData = [
+ {
+ id: "events",
+ data: formattedData,
+ },
+ ];
+
+ const maxValue = Math.max(...formattedData.map((d) => d.y), 1);
+
+ if (isLoading) {
+ return (
+ <div className="h-48 flex items-center justify-center">
+ <div className="text-sm text-muted-foreground">
+ Loading usage data...
+ </div>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="h-48 flex items-center justify-center">
+ <div className="text-sm text-muted-foreground">
+ Failed to load usage data
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="h-48">
+ <ResponsiveLine
+ data={chartData}
+ theme={nivoTheme}
+ margin={{ top: 10, right: 10, bottom: 25, left: 35 }}
+ xScale={{
+ type: "time",
+ format: "%Y-%m-%d",
+ precision: "day",
+ useUTC: true,
+ }}
+ yScale={{
+ type: "linear",
+ min: 0,
+ stacked: false,
+ reverse: false,
+ max: maxValue,
+ }}
+ enableGridX={false}
+ enableGridY={true}
+ gridYValues={5}
+ yFormat=" >-.0f"
+ axisTop={null}
+ axisRight={null}
+ axisBottom={{
+ tickSize: 0,
+ tickPadding: 10,
+ tickRotation: 0,
+ truncateTickAt: 0,
+ tickValues: Math.min(maxTicks, 10),
+ format: (value) => {
+ const dt = DateTime.fromJSDate(value).setLocale(userLocale);
+ return dt.toFormat("MMM d");
+ },
+ }}
+ axisLeft={{
+ tickSize: 0,
+ tickPadding: 10,
+ tickRotation: 0,
+ truncateTickAt: 0,
+ tickValues: 5,
+ format: formatter.format,
+ }}
+ enableTouchCrosshair={true}
+ enablePoints={false}
+ useMesh={true}
+ animate={false}
+ enableSlices={"x"}
+ colors={["hsl(var(--dataviz))"]}
+ enableArea={true}
+ areaBaselineValue={0}
+ areaOpacity={0.3}
+ defs={[
+ {
+ id: "gradient",
+ type: "linearGradient",
+ colors: [
+ { offset: 0, color: "hsl(var(--dataviz))", opacity: 1 },
+ { offset: 100, color: "hsl(var(--dataviz))", opacity: 0 },
+ ],
+ },
+ ]}
+ fill={[
+ {
+ match: {
+ id: "events",
+ },
+ id: "gradient",
+ },
+ ]}
+ sliceTooltip={({ slice }: any) => {
+ const currentY = Number(slice.points[0].data.yFormatted);
+ const currentTime = slice.points[0].data.currentTime as DateTime;
+
+ return (
+ <div className="text-sm bg-neutral-900 p-2 rounded-md">
+ <div className="flex justify-between text-sm w-36">
+ <div>{formatDateTime(currentTime)}</div>
+ <div>{currentY.toLocaleString()} events</div>
+ </div>
+ </div>
+ );
+ }}
+ />
+ </div>
+ );
+}
+
+const formatDateTime = (dt: DateTime) => {
+ const options: Intl.DateTimeFormatOptions = {
+ month: "short",
+ day: "numeric",
+ };
+ return new Intl.DateTimeFormat(userLocale, options).format(dt.toJSDate());
+};
diff --git a/client/src/components/ui/tooltip.tsx b/client/src/components/ui/tooltip.tsx
index c787d1cfc..c4e67992e 100644
--- a/client/src/components/ui/tooltip.tsx
+++ b/client/src/components/ui/tooltip.tsx
@@ -7,7 +7,12 @@ import { cn } from "@/lib/utils";
const TooltipProvider = TooltipPrimitive.Provider;
-const Tooltip = TooltipPrimitive.Root;
+const Tooltip = ({
+ delayDuration = 300,
+ ...props
+}: React.ComponentProps<typeof TooltipPrimitive.Root>) => (
+ <TooltipPrimitive.Root delayDuration={delayDuration} {...props} />
+);
const TooltipTrigger = TooltipPrimitive.Trigger;
diff --git a/docs/src/app/components/PricingSection.jsx b/docs/src/app/components/PricingSection.jsx
index 87f2f58c0..3cd112ef6 100644
--- a/docs/src/app/components/PricingSection.jsx
+++ b/docs/src/app/components/PricingSection.jsx
@@ -1,7 +1,7 @@
"use client";
import { Slider } from "@/components/ui/slider";
-import { Check } from "lucide-react";
+import { Check, X } from "lucide-react";
import Link from "next/link";
import { useState } from "react";
import { cn } from "../../lib/utils";
@@ -24,10 +24,23 @@ const PRO_FEATURES = [
"Unlimited team members",
"Real-time analytics",
"Custom events",
- "Funnels & user flows",
+ "Sessions",
+ "Funnels",
+ "Goals",
+ "User flows",
"All features",
];
+// Define free plan features
+const FREE_FEATURES = [
+ { feature: "Up to 3 websites", included: true },
+ { feature: "Basic features", included: true },
+ { feature: "Custom events", included: true },
+ // { feature: "Team members", included: false },
+ // { feature: "Real-time analytics", included: false },
+ // { feature: "Funnels & user flows", included: false },
+];
+
export const formatter = Intl.NumberFormat("en", {
notation: "compact",
}).format;
@@ -80,132 +93,202 @@ export function PricingSection() {
</p>
</div>
- {/* Pricing card with background gradients */}
- <div className="relative max-w-lg mx-auto mb-10">
- {/* Background gradients - overlapping circles for organic feel */}
- <div className="absolute top-0 left-0 w-[400px] h-[400px] bg-emerald-500/30 rounded-full blur-[80px] opacity-60"></div>
- <div className="absolute top-20 left-20 w-[300px] h-[300px] bg-emerald-600/20 rounded-full blur-[70px] opacity-40"></div>
+ {/* Two card layout */}
+ <div className="flex flex-col lg:flex-row gap-6 max-w-6xl mx-auto justify-center items-start">
+ {/* Free Plan Card */}
+ <div className="w-full lg:w-70 flex-shrink-0 md:h-[666px] h-full">
+ <div className="bg-neutral-800/30 rounded-xl border border-neutral-700 overflow-hidden backdrop-blur-sm shadow-lg h-full">
+ <div className="p-6">
+ <div className="md:mb-[74px] mb-6">
+ <div className="flex justify-between mb-3 items-center">
+ <div>
+ <h3 className="font-semibold mb-2">Free</h3>
+ <div className="text-3xl font-semibold text-neutral-200">
+ 3,000
+ </div>
+ <p className="text-neutral-400 text-sm">events/month</p>
+ </div>
+ {/* <div className="flex flex-col items-end">
+ <div className="text-right">
+ <span className="text-3xl font-bold">$0</span>
+ <p className="text-neutral-400 text-sm mt-1">Forever</p>
+ </div>
+ </div> */}
+ </div>
+ </div>
+
+ <Link
+ href="https://app.rybbit.io/signup"
+ className="w-full block"
+ >
+ <button className="w-full bg-neutral-700 hover:bg-neutral-600 text-white font-medium px-5 py-3 rounded-lg border border-neutral-600 transform hover:-translate-y-0.5 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-neutral-400 focus:ring-opacity-50 cursor-pointer">
+ Start for free
+ </button>
+ </Link>
+ <div className="space-y-3 mt-6 mb-3">
+ {FREE_FEATURES.map((item, i) => (
+ <div key={i} className="flex items-center">
+ {item.included ? (
+ <Check className="h-4 w-4 text-emerald-400 mr-3 shrink-0" />
+ ) : (
+ <X className="h-4 w-4 text-neutral-500 mr-3 shrink-0" />
+ )}
+ <span
+ className={cn(
+ item.included ? "text-white" : "text-neutral-500"
+ )}
+ >
+ {item.feature}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Pro Plan Card */}
+ <div className="relative w-full lg:w-96 flex-shrink-0">
+ {/* Background gradients - overlapping circles for organic feel */}
+ <div className="absolute top-0 left-0 w-[400px] h-[400px] bg-emerald-500/30 rounded-full blur-[80px] opacity-60"></div>
+ <div className="absolute top-20 left-20 w-[300px] h-[300px] bg-emerald-600/20 rounded-full blur-[70px] opacity-40"></div>
- <div className="absolute bottom-0 right-0 w-[350px] h-[350px] bg-blue-500/30 rounded-full blur-[80px] opacity-50"></div>
- <div className="absolute bottom-40 right-20 w-[250px] h-[250px] bg-indigo-500/20 rounded-full blur-[75px] opacity-40"></div>
+ <div className="absolute bottom-0 right-0 w-[350px] h-[350px] bg-blue-500/30 rounded-full blur-[80px] opacity-50"></div>
+ <div className="absolute bottom-40 right-20 w-[250px] h-[250px] bg-indigo-500/20 rounded-full blur-[75px] opacity-40"></div>
- <div className="absolute top-1/4 right-0 w-[200px] h-[200px] bg-purple-500/30 rounded-full blur-[70px] opacity-40"></div>
+ <div className="absolute top-1/4 right-0 w-[200px] h-[200px] bg-purple-500/30 rounded-full blur-[70px] opacity-40"></div>
- <div className="absolute bottom-1/3 left-0 w-[220px] h-[220px] bg-emerald-400/20 rounded-full blur-[70px] opacity-50"></div>
+ <div className="absolute bottom-1/3 left-0 w-[220px] h-[220px] bg-emerald-400/20 rounded-full blur-[70px] opacity-50"></div>
- <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[350px] h-[350px] bg-indigo-400/20 rounded-full blur-[80px] opacity-40"></div>
+ <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[350px] h-[350px] bg-indigo-400/20 rounded-full blur-[80px] opacity-40"></div>
- {/* Card with relative positioning and higher z-index */}
- <div className="relative z-10 bg-neutral-800/50 rounded-xl border border-neutral-700 overflow-hidden backdrop-blur-sm shadow-xl">
- <div className="p-6">
- {/* Slider section */}
- <div className="mb-6">
- <div className="flex justify-between mb-3 items-center">
- <div>
- <h3 className="font-semibold mb-2">Events per month</h3>
- <div className="text-3xl font-bold text-emerald-400 hidden md:block">
- {eventLimit.toLocaleString()}
+ {/* Card with relative positioning and higher z-index */}
+ <div className="relative z-10 bg-neutral-800/50 rounded-xl border border-neutral-700 overflow-hidden backdrop-blur-sm shadow-xl">
+ <div className="p-6">
+ {/* Slider section */}
+ <div className="mb-6">
+ <div className="flex justify-between mb-3 items-center">
+ <div>
+ <h3 className="font-semibold mb-2">Pro</h3>
+ <div className="text-3xl font-bold text-emerald-400 hidden md:block">
+ {eventLimit.toLocaleString()}
+ </div>
+ <div className="text-3xl font-bold text-emerald-400 md:hidden">
+ {isNaN(eventLimit) ? "10M+" : formatter(eventLimit)}
+ </div>
+ <p className="text-neutral-400 text-sm">events/month</p>
</div>
- <div className="text-3xl font-bold text-emerald-400 md:hidden">
- {isNaN(eventLimit) ? "10M+" : formatter(eventLimit)}
+ <div className="flex flex-col items-end">
+ {/* Billing toggle */}
+ <div className="flex gap-3 mb-1 text-sm -mt-5">
+ <button
+ onClick={() => setIsAnnual(false)}
+ className={cn(
+ "px-3 py-1 rounded-full transition-colors cursor-pointer",
+ !isAnnual
+ ? "bg-emerald-500/20 text-emerald-400 font-medium"
+ : "text-neutral-400 hover:text-neutral-200"
+ )}
+ >
+ Monthly
+ </button>
+ <button
+ onClick={() => setIsAnnual(true)}
+ className={cn(
+ "px-3 py-1 rounded-full transition-colors cursor-pointer",
+ isAnnual
+ ? "bg-emerald-500/20 text-emerald-400 font-medium"
+ : "text-neutral-400 hover:text-neutral-200"
+ )}
+ >
+ Annual
+ <span className="ml-1 text-xs text-emerald-500">
+ -17%
+ </span>
+ </button>
+ </div>
+ <div className="text-right h-10">
+ {prices.custom ? (
+ <></>
+ ) : (
+ <>
+ <span className="text-3xl font-bold">
+ $
+ {isAnnual
+ ? Math.round(prices.annual / 12)
+ : prices.monthly}
+ </span>
+ <span className="ml-1 text-neutral-400">
+ /month
+ </span>
+ </>
+ )}
+ </div>
</div>
</div>
- <div className="flex flex-col items-end">
- {/* Billing toggle */}
- <div className="flex gap-3 mb-2 text-sm">
- <button
- onClick={() => setIsAnnual(false)}
- className={cn("px-3 py-1 rounded-full transition-colors cursor-pointer", !isAnnual ? "bg-emerald-500/20 text-emerald-400 font-medium" : "text-neutral-400 hover:text-neutral-200")}
- >
- Monthly
- </button>
- <button
- onClick={() => setIsAnnual(true)}
- className={cn("px-3 py-1 rounded-full transition-colors cursor-pointer", isAnnual ? "bg-emerald-500/20 text-emerald-400 font-medium" : "text-neutral-400 hover:text-neutral-200")}
+
+ <Slider
+ defaultValue={[0]}
+ max={EVENT_TIERS.length - 1}
+ min={0}
+ step={1}
+ onValueChange={handleSliderChange}
+ className="mb-3"
+ />
+
+ <div className="flex justify-between text-xs text-neutral-400">
+ {EVENT_TIERS.map((tier, index) => (
+ <span
+ key={index}
+ className={cn(
+ eventLimitIndex === index &&
+ "font-bold text-emerald-400"
+ )}
>
- Annual
- <span className="ml-1 text-xs text-emerald-500">
- -17%
- </span>
- </button>
- </div>
- <div className="text-right h-10">
- {prices.custom ? (
- <></>
- ) : (
- <>
- <span className="text-3xl font-bold">
- $
- {isAnnual
- ? Math.round(prices.annual / 12)
- : prices.monthly}
- </span>
- <span className="ml-1 text-neutral-400">/month</span>
- </>
- )}
- </div>
+ {index === EVENT_TIERS.length - 1
+ ? "10M+"
+ : tier >= 1_000_000
+ ? `${tier / 1_000_000}M`
+ : `${tier / 1_000}K`}
+ </span>
+ ))}
</div>
</div>
- <Slider
- defaultValue={[0]}
- max={EVENT_TIERS.length - 1}
- min={0}
- step={1}
- onValueChange={handleSliderChange}
- className="mb-3"
- />
-
- <div className="flex justify-between text-xs text-neutral-400">
- {EVENT_TIERS.map((tier, index) => (
- <span
- key={index}
- className={cn(eventLimitIndex === index && "font-bold text-emerald-400")}
- >
- {index === EVENT_TIERS.length - 1
- ? "10M+"
- : tier >= 1_000_000
- ? `${tier / 1_000_000}M`
- : `${tier / 1_000}K`}
- </span>
+ {prices.custom ? (
+ <Link
+ href="https://www.rybbit.io/contact"
+ className="w-full block"
+ >
+ <button className="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-medium px-5 py-3 rounded-lg shadow-lg shadow-emerald-900/20 transform hover:-translate-y-0.5 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-opacity-50 cursor-pointer">
+ Contact us
+ </button>
+ </Link>
+ ) : (
+ <Link
+ href="https://app.rybbit.io/signup"
+ className="w-full block"
+ >
+ <button className="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-medium px-5 py-3 rounded-lg shadow-lg shadow-emerald-900/20 transform hover:-translate-y-0.5 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-opacity-50 cursor-pointer">
+ Try for free
+ </button>
+ </Link>
+ )}
+ <div className="space-y-4 my-6">
+ {PRO_FEATURES.map((feature, i) => (
+ <div key={i} className="flex items-center">
+ <Check className="h-4 w-4 text-emerald-400 mr-3 shrink-0" />
+ <span>{feature}</span>
+ </div>
))}
</div>
- </div>
- <div className="space-y-4 mb-6">
- {PRO_FEATURES.map((feature, i) => (
- <div key={i} className="flex items-center">
- <Check className="h-4 w-4 text-emerald-400 mr-3 shrink-0" />
- <span>{feature}</span>
- </div>
- ))}
+ <p className="text-center text-sm text-neutral-400 mt-4">
+ {prices.custom
+ ? "Email us at [email protected] for custom pricing"
+ : "We don't ask for your credit card"}
+ </p>
</div>
-
- {prices.custom ? (
- <Link
- href="https://www.rybbit.io/contact"
- className="w-full block"
- >
- <button className="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-medium px-5 py-3 rounded-lg shadow-lg shadow-emerald-900/20 transform hover:-translate-y-0.5 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-opacity-50 cursor-pointer">
- Contact us
- </button>
- </Link>
- ) : (
- <Link
- href="https://app.rybbit.io/signup"
- className="w-full block"
- >
- <button className="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-medium px-5 py-3 rounded-lg shadow-lg shadow-emerald-900/20 transform hover:-translate-y-0.5 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-opacity-50 cursor-pointer">
- Start your 14 day free trial
- </button>
- </Link>
- )}
-
- <p className="text-center text-sm text-neutral-400 mt-4">
- {prices.custom
- ? "Email us at [email protected] for custom pricing"
- : "We don't ask for your credit card"}
- </p>
</div>
</div>
</div>
diff --git a/docs/src/app/pricing/page.jsx b/docs/src/app/pricing/page.jsx
index 37c311fd6..614e78ddf 100644
--- a/docs/src/app/pricing/page.jsx
+++ b/docs/src/app/pricing/page.jsx
@@ -1,6 +1,5 @@
import { PricingSection } from "../components/PricingSection";
-
export const metadata = {
title: "Pricing",
description: "Rybbit pricing plans and features",
@@ -10,34 +9,43 @@ export default function Pricing() {
return (
<div className="flex flex-col items-center justify-center overflow-x-hidden">
<PricingSection />
-
+
{/* FAQ section */}
<div className="max-w-lg mx-auto px-4 pb-16">
<div className="mt-10 space-y-6">
- <h3 className="text-xl font-semibold mb-4">Frequently Asked Questions</h3>
-
+ <h3 className="text-xl font-semibold mb-4">
+ Frequently Asked Questions
+ </h3>
+
<div className="bg-neutral-800/20 p-5 rounded-lg border border-neutral-700">
<h4 className="font-medium mb-2">What counts as an event?</h4>
<p className="text-neutral-300">
- An event is either a pageview or a custom event that you create on your website. Pageviews are tracked automatically, while custom events can be defined to track specific user interactions.
+ An event is either a pageview or a custom event that you create on
+ your website. Pageviews are tracked automatically, while custom
+ events can be defined to track specific user interactions.
</p>
</div>
-
+
<div className="bg-neutral-800/20 p-5 rounded-lg border border-neutral-700">
<h4 className="font-medium mb-2">Can I change my plan later?</h4>
<p className="text-neutral-300">
- Absolutely. You can upgrade, downgrade, or cancel your plan at any time through your account settings.
+ Absolutely. You can upgrade, downgrade, or cancel your plan at any
+ time through your account settings.
</p>
</div>
-
+
<div className="bg-neutral-800/20 p-5 rounded-lg border border-neutral-700">
- <h4 className="font-medium mb-2">What happens if I go over my event limit?</h4>
+ <h4 className="font-medium mb-2">
+ What happens if I go over my event limit?
+ </h4>
<p className="text-neutral-300">
- We'll notify you when you're approaching your limit. You can either upgrade to a higher plan or continue with your current plan (events beyond the limit won't be tracked).
+ We'll notify you when you're approaching your limit. You can
+ either upgrade to a higher plan or continue with your current plan
+ (events beyond the limit won't be tracked).
</p>
</div>
</div>
</div>
</div>
);
-}
\ No newline at end of file
+}
diff --git a/server/src/api/analytics/getOrgEventCount.ts b/server/src/api/analytics/getOrgEventCount.ts
new file mode 100644
index 000000000..2dfa39b6c
--- /dev/null
+++ b/server/src/api/analytics/getOrgEventCount.ts
@@ -0,0 +1,113 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import clickhouse from "../../db/clickhouse/clickhouse.js";
+import { processResults } from "./utils.js";
+import SqlString from "sqlstring";
+import { getSitesUserHasAccessTo } from "../../lib/auth-utils.js";
+import { db } from "../../db/postgres/postgres.js";
+import { sites } from "../../db/postgres/schema.js";
+import { eq } from "drizzle-orm";
+
+type OrgEventCountResponse = {
+ event_date: string;
+ event_count: number;
+}[];
+
+export async function getOrgEventCount(
+ req: FastifyRequest<{
+ Params: {
+ organizationId: string;
+ };
+ Querystring: {
+ startDate?: string;
+ endDate?: string;
+ timeZone?: string;
+ };
+ }>,
+ res: FastifyReply
+) {
+ const { organizationId } = req.params;
+ const { startDate, endDate, timeZone = "UTC" } = req.query;
+
+ try {
+ // Get all sites the user has access to
+ const userSites = await getSitesUserHasAccessTo(req);
+
+ // Filter to only sites in the requested organization
+ const orgSites = userSites.filter(
+ (site) => site.organizationId === organizationId
+ );
+
+ if (orgSites.length === 0) {
+ return res
+ .status(403)
+ .send({ error: "No access to organization or no sites found" });
+ }
+
+ const siteIds = orgSites.map((site: any) => site.siteId);
+
+ // Build time filter for the query
+ let timeFilter = "";
+ let fillFromDate = "";
+ let fillToDate = "";
+
+ if (startDate && endDate) {
+ timeFilter = `AND event_hour >= toTimeZone(
+ toStartOfDay(toDateTime(${SqlString.escape(startDate)}, ${SqlString.escape(timeZone)})),
+ 'UTC'
+ )
+ AND event_hour < if(
+ toDate(${SqlString.escape(endDate)}) = toDate(now(), ${SqlString.escape(timeZone)}),
+ now(),
+ toTimeZone(
+ toStartOfDay(toDateTime(${SqlString.escape(endDate)}, ${SqlString.escape(timeZone)})) + INTERVAL 1 DAY,
+ 'UTC'
+ )
+ )`;
+
+ // Set up WITH FILL parameters
+ fillFromDate = `FROM toTimeZone(
+ toStartOfDay(toDateTime(${SqlString.escape(startDate)}, ${SqlString.escape(timeZone)})),
+ 'UTC'
+ )`;
+
+ fillToDate = `TO if(
+ toDate(${SqlString.escape(endDate)}) = toDate(now(), ${SqlString.escape(timeZone)}),
+ toStartOfDay(now()) + INTERVAL 1 DAY,
+ toTimeZone(
+ toStartOfDay(toDateTime(${SqlString.escape(endDate)}, ${SqlString.escape(timeZone)})) + INTERVAL 1 DAY,
+ 'UTC'
+ )
+ )`;
+ } else {
+ // Default to last 30 days if no date range provided
+ timeFilter = "AND event_hour >= now() - INTERVAL 30 DAY";
+ fillFromDate = "FROM now() - INTERVAL 30 DAY";
+ fillToDate = "TO now() + INTERVAL 1 DAY";
+ }
+
+ const query = `
+ SELECT
+ toStartOfDay(event_hour) as event_date,
+ SUM(event_count) as event_count
+ FROM hourly_events_by_site_mv_target
+ WHERE site_id IN (${siteIds.map((id: number) => SqlString.escape(id)).join(", ")})
+ ${timeFilter}
+ GROUP BY event_date
+ ORDER BY event_date
+ WITH FILL ${fillFromDate} ${fillToDate} STEP INTERVAL 1 DAY
+ `;
+
+ const result = await clickhouse.query({
+ query,
+ format: "JSONEachRow",
+ });
+
+ const data = await processResults<OrgEventCountResponse[number]>(result);
+ return res.send({ data });
+ } catch (error) {
+ console.error("Error fetching organization event count:", error);
+ return res
+ .status(500)
+ .send({ error: "Failed to fetch organization event count" });
+ }
+}
diff --git a/server/src/api/sites/getSites.ts b/server/src/api/sites/getSites.ts
index 65e9d10a5..fa5d7dcbb 100644
--- a/server/src/api/sites/getSites.ts
+++ b/server/src/api/sites/getSites.ts
@@ -7,7 +7,7 @@ import {
getSitesUserHasAccessTo,
getUserGodMode,
} from "../../lib/auth-utils.js";
-import { IS_CLOUD, TRIAL_EVENT_LIMIT } from "../../lib/const.js";
+import { IS_CLOUD, DEFAULT_EVENT_LIMIT } from "../../lib/const.js";
import { processResults } from "../analytics/utils.js";
import { getSubscriptionInner } from "../stripe/getSubscription.js";
@@ -91,7 +91,7 @@ export async function getSites(req: FastifyRequest, reply: FastifyReply) {
const subscription = await getSubscriptionInner(ownerId);
const monthlyEventCount = subscription?.monthlyEventCount || 0;
- const eventLimit = subscription?.eventLimit || TRIAL_EVENT_LIMIT;
+ const eventLimit = subscription?.eventLimit || DEFAULT_EVENT_LIMIT;
return {
...site,
diff --git a/server/src/api/stripe/getSubscription.ts b/server/src/api/stripe/getSubscription.ts
index af120e996..19898c919 100644
--- a/server/src/api/stripe/getSubscription.ts
+++ b/server/src/api/stripe/getSubscription.ts
@@ -4,12 +4,12 @@ import Stripe from "stripe";
import { db } from "../../db/postgres/postgres.js";
import { user as userSchema } from "../../db/postgres/schema.js";
import {
+ DEFAULT_EVENT_LIMIT,
getStripePrices,
StripePlan,
- TRIAL_DURATION_DAYS,
- TRIAL_EVENT_LIMIT,
} from "../../lib/const.js";
import { stripe } from "../../lib/stripe.js";
+import { DateTime } from "luxon";
// Function to find plan details by price ID
function findPlanDetails(priceId: string): StripePlan | undefined {
@@ -20,6 +20,14 @@ function findPlanDetails(priceId: string): StripePlan | undefined {
);
}
+function getStartOfMonth() {
+ return DateTime.now().startOf("month").toJSDate();
+}
+
+function getStartOfNextMonth() {
+ return DateTime.now().startOf("month").plus({ months: 1 }).toJSDate();
+}
+
export async function getSubscriptionInner(userId: string) {
// 1. Find the user and their Stripe Customer ID
const userResult = await db
@@ -102,41 +110,39 @@ export async function getSubscriptionInner(userId: string) {
// If we get here, the user has no active paid subscription
// Check if they're in the trial period
- const createdAt = new Date(user.createdAt);
- const now = new Date();
- const trialEndDate = new Date(createdAt);
- trialEndDate.setDate(trialEndDate.getDate() + TRIAL_DURATION_DAYS);
-
- const isInTrialPeriod = now < trialEndDate;
-
- if (isInTrialPeriod) {
- // User is in trial period
- return {
- id: null,
- planName: "trial",
- status: "trialing",
- currentPeriodEnd: trialEndDate,
- currentPeriodStart: createdAt,
- eventLimit: TRIAL_EVENT_LIMIT,
- monthlyEventCount: user.monthlyEventCount,
- interval: "month",
- isTrial: true,
- trialDaysRemaining: Math.ceil(
- (trialEndDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24)
- ),
- };
- }
+ // const createdAt = new Date(user.createdAt);
+ // const now = new Date();
+ // const trialEndDate = new Date(createdAt);
+ // trialEndDate.setDate(trialEndDate.getDate() + TRIAL_DURATION_DAYS);
+
+ // const isInTrialPeriod = now < trialEndDate;
+
+ // if (isInTrialPeriod) {
+ // // User is in trial period
+ // return {
+ // id: null,
+ // planName: "trial",
+ // status: "trialing",
+ // currentPeriodEnd: trialEndDate,
+ // currentPeriodStart: createdAt,
+ // eventLimit: TRIAL_EVENT_LIMIT,
+ // monthlyEventCount: user.monthlyEventCount,
+ // interval: "month",
+ // isTrial: true,
+ // trialDaysRemaining: Math.ceil(
+ // (trialEndDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24)
+ // ),
+ // };
+ // }
- // User has no subscription and trial has ended - return null
return {
id: null,
planName: "free",
- status: "expired",
- currentPeriodEnd: null,
- currentPeriodStart: null,
- eventLimit: 0,
+ status: "free",
+ currentPeriodEnd: getStartOfNextMonth(),
+ currentPeriodStart: getStartOfMonth(),
+ eventLimit: DEFAULT_EVENT_LIMIT,
monthlyEventCount: user.monthlyEventCount,
- isTrial: false,
trialDaysRemaining: 0,
};
}
diff --git a/server/src/cron/monthly-usage-checker.ts b/server/src/cron/monthly-usage-checker.ts
index f598e6aee..5bc9cc723 100644
--- a/server/src/cron/monthly-usage-checker.ts
+++ b/server/src/cron/monthly-usage-checker.ts
@@ -8,13 +8,10 @@ import { member, sites, user } from "../db/postgres/schema.js";
import {
getStripePrices,
StripePlan,
- TRIAL_EVENT_LIMIT,
+ DEFAULT_EVENT_LIMIT,
} from "../lib/const.js";
import { stripe } from "../lib/stripe.js";
-// Default event limit for users without an active subscription
-const DEFAULT_EVENT_LIMIT = 0;
-
// Global set to track site IDs that have exceeded their monthly limits
export const sitesOverLimit = new Set<number>();
@@ -66,14 +63,7 @@ async function getUserSubscriptionInfo(userData: {
createdAt: string;
email: string;
}): Promise<[number, string | null]> {
- const createdAtDate = DateTime.fromSQL(userData.createdAt);
- const daysSinceCreation = Math.abs(createdAtDate.diffNow("days").days);
-
if (!userData.stripeCustomerId) {
- if (daysSinceCreation < 14) {
- return [TRIAL_EVENT_LIMIT, createdAtDate.toISODate() as string];
- }
-
// No Stripe customer ID, use default limit and start of current month
return [DEFAULT_EVENT_LIMIT, getStartOfMonth()];
}
@@ -87,11 +77,6 @@ async function getUserSubscriptionInfo(userData: {
});
if (subscriptions.data.length === 0) {
- // If the user was created in the last 14 days, use the trial limit
- if (daysSinceCreation < 14) {
- return [TRIAL_EVENT_LIMIT, createdAtDate.toISODate() as string];
- }
- // No active subscription, use default limit and start of current month
return [DEFAULT_EVENT_LIMIT, getStartOfMonth()];
}
@@ -229,9 +214,8 @@ export async function updateUsersMonthlyUsage() {
}
// Get user's subscription information (limit and period start)
- const [eventLimit, periodStart] = await getUserSubscriptionInfo(
- userData
- );
+ const [eventLimit, periodStart] =
+ await getUserSubscriptionInfo(userData);
// Get monthly pageview count from ClickHouse using the billing period start date
const pageviewCount = await getMonthlyPageviews(siteIds, periodStart);
diff --git a/server/src/index.ts b/server/src/index.ts
index b3e4eb395..908906891 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -61,6 +61,7 @@ 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";
+import { getOrgEventCount } from "./api/analytics/getOrgEventCount.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -228,6 +229,7 @@ server.delete("/goal/:goalId", deleteGoal);
server.put("/goal/update", updateGoal);
server.get("/events/names/:site", getEventNames);
server.get("/events/properties/:site", getEventProperties);
+server.get("/org-event-count/:organizationId", getOrgEventCount);
// Administrative
server.get("/config", getConfig);
diff --git a/server/src/lib/const.ts b/server/src/lib/const.ts
index 3389ef770..45d485924 100644
--- a/server/src/lib/const.ts
+++ b/server/src/lib/const.ts
@@ -5,9 +5,11 @@ dotenv.config();
export const IS_CLOUD = process.env.CLOUD === "true";
export const DISABLE_SIGNUP = process.env.DISABLE_SIGNUP === "true";
-// Trial constants
-export const TRIAL_DURATION_DAYS = 14;
-export const TRIAL_EVENT_LIMIT = 1_000_000;
+// Trial constants (commented out as we're replacing with free tier)
+// export const TRIAL_DURATION_DAYS = 14;
+// export const TRIAL_EVENT_LIMIT = 100000;
+
+export const DEFAULT_EVENT_LIMIT = 3_000;
// Define a type for the plan objects
export interface StripePlan {