Skip to content

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

Add banner

Bill Yangf2f7129a8788
diff --git a/client/src/api/admin/sites.ts b/client/src/api/admin/sites.ts
index 4edeb383c..102ad2b72 100644
--- a/client/src/api/admin/sites.ts
+++ b/client/src/api/admin/sites.ts
@@ -9,6 +9,8 @@ export type GetSitesResponse = {
createdAt: string;
updatedAt: string;
createdBy: string;
+ overMonthlyLimit?: boolean;
+ monthlyEventCount?: number;
}[];
export function useGetSites() {
diff --git a/client/src/app/[site]/Header/Header.tsx b/client/src/app/[site]/Header/Header.tsx
index 86b356cb1..d37957a2f 100644
--- a/client/src/app/[site]/Header/Header.tsx
+++ b/client/src/app/[site]/Header/Header.tsx
@@ -1,16 +1,26 @@
"use client";
import { useStore } from "@/lib/store";
import { Circle } from "@phosphor-icons/react";
-import { ChartBarDecreasing, ChartLine, Radio, User } from "lucide-react";
+import {
+ ChartBarDecreasing,
+ ChartLine,
+ Radio,
+ User,
+ AlertTriangle,
+} from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { SiteSettings } from "../../../components/SiteSettings/SiteSettings";
import { useGetSites } from "../../../api/admin/sites";
import { useGetLiveUsercount } from "../../../api/analytics/useLiveUserCount";
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+} from "../../../components/ui/alert";
export function Header() {
const { data } = useGetLiveUsercount();
- const { time } = useStore();
const { data: sites } = useGetSites();
const pathname = usePathname();
@@ -31,47 +41,68 @@ export function Header() {
};
return (
- <div className="flex items-center justify-between py-2">
- <div className="flex gap-3">
- <div className="flex items-center gap-2 text-xl font-bold">
- <img
- className="w-7 mr-1"
- src={`https://www.google.com/s2/favicons?domain=${site?.domain}&sz=64`}
- />
- <div>{site?.domain}</div>
+ <div className="flex flex-col">
+ {/* Usage Limit Banner */}
+ {site?.overMonthlyLimit && (
+ <Alert variant="destructive" className="mb-3">
+ <AlertTriangle className="h-4 w-4" />
+ <AlertTitle>Monthly Event Limit Exceeded</AlertTitle>
+ <AlertDescription>
+ This site's organization has exceeded its monthly event limit (
+ {site.monthlyEventCount?.toLocaleString()} events recorded). Please
+ upgrade your plan to continue collecting analytics.
+ </AlertDescription>
+ <Link
+ href="/settings/subscription"
+ className="underline ml-1 font-medium"
+ >
+ Upgrade Plan
+ </Link>
+ </Alert>
+ )}
+
+ <div className="flex items-center justify-between py-2">
+ <div className="flex gap-3">
+ <div className="flex items-center gap-2 text-xl font-bold">
+ <img
+ className="w-7 mr-1"
+ src={`https://www.google.com/s2/favicons?domain=${site?.domain}&sz=64`}
+ />
+ <div>{site?.domain}</div>
+ </div>
+ <div className="flex items-center gap-1 text-base text-neutral-600 dark:text-neutral-400">
+ <Circle size={12} weight="fill" color="hsl(var(--green-500))" />
+ {data?.count} users online
+ <SiteSettings siteId={site?.siteId ?? 0} />
+ </div>
</div>
- <div className="flex items-center gap-1 text-base text-neutral-600 dark:text-neutral-400">
- <Circle size={12} weight="fill" color="hsl(var(--green-500))" />
- {data?.count} users online
- <SiteSettings siteId={site?.siteId ?? 0} />
+ <div className="flex space-x-2">
+ <TabButton
+ label="Main"
+ active={isActiveTab("main")}
+ href={getTabPath("main")}
+ icon={<ChartLine size={20} />}
+ />
+ <TabButton
+ label="Sessions"
+ active={isActiveTab("sessions")}
+ href={getTabPath("sessions")}
+ icon={<User size={20} />}
+ />
+ <TabButton
+ label="Realtime"
+ active={isActiveTab("realtime")}
+ href={getTabPath("realtime")}
+ icon={<Radio size={20} />}
+ />
+ <TabButton
+ label="Reports"
+ active={isActiveTab("reports")}
+ href={getTabPath("reports")}
+ icon={<ChartBarDecreasing size={20} />}
+ />
</div>
</div>
- <div className="flex space-x-2">
- <TabButton
- label="Main"
- active={isActiveTab("main")}
- href={getTabPath("main")}
- icon={<ChartLine size={20} />}
- />
- <TabButton
- label="Sessions"
- active={isActiveTab("sessions")}
- href={getTabPath("sessions")}
- icon={<User size={20} />}
- />
- <TabButton
- label="Realtime"
- active={isActiveTab("realtime")}
- href={getTabPath("realtime")}
- icon={<Radio size={20} />}
- />
- <TabButton
- label="Reports"
- active={isActiveTab("reports")}
- href={getTabPath("reports")}
- icon={<ChartBarDecreasing size={20} />}
- />
- </div>
</div>
);
}
diff --git a/server/src/api/sites/getSites.ts b/server/src/api/sites/getSites.ts
index 70af68668..d35752709 100644
--- a/server/src/api/sites/getSites.ts
+++ b/server/src/api/sites/getSites.ts
@@ -1,11 +1,64 @@
+import { and, eq } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
+import { db } from "../../db/postgres/postgres.js";
+import { member, user } from "../../db/postgres/schema.js";
import { getSitesUserHasAccessTo } from "../../lib/auth-utils.js";
export async function getSites(req: FastifyRequest, reply: FastifyReply) {
try {
+ // Get sites the user has access to
const sitesData = await getSitesUserHasAccessTo(req);
- return reply.status(200).send({ data: sitesData });
+
+ // Enhance sites data with usage limit information
+ const enhancedSitesData = await Promise.all(
+ sitesData.map(async (site) => {
+ // Skip if no organization ID
+ if (!site.organizationId) {
+ return { ...site, overMonthlyLimit: false };
+ }
+
+ // Get the organization owner
+ const orgOwner = await db
+ .select({ userId: member.userId })
+ .from(member)
+ .where(
+ and(
+ eq(member.organizationId, site.organizationId),
+ eq(member.role, "owner")
+ )
+ )
+ .limit(1);
+
+ if (!orgOwner.length) {
+ return { ...site, overMonthlyLimit: false };
+ }
+
+ // Get the user data to check if they're over limit
+ const userData = await db
+ .select({
+ overMonthlyLimit: user.overMonthlyLimit,
+ monthlyEventCount: user.monthlyEventCount,
+ })
+ .from(user)
+ .where(eq(user.id, orgOwner[0].userId))
+ .limit(1);
+
+ if (!userData.length) {
+ return { ...site, overMonthlyLimit: false };
+ }
+
+ // Return site with usage limit info
+ return {
+ ...site,
+ overMonthlyLimit: userData[0].overMonthlyLimit || false,
+ monthlyEventCount: userData[0].monthlyEventCount || 0,
+ };
+ })
+ );
+
+ return reply.status(200).send({ data: enhancedSitesData });
} catch (err) {
+ console.error("Error in getSites:", err);
return reply.status(500).send({ error: String(err) });
}
}
diff --git a/server/src/db/postgres/migrate.ts b/server/src/db/postgres/migrate.ts
deleted file mode 100644
index e1e4aec7a..000000000
--- a/server/src/db/postgres/migrate.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import { drizzle } from "drizzle-orm/postgres-js";
-import { migrate } from "drizzle-orm/postgres-js/migrator";
-import postgres from "postgres";
-import dotenv from "dotenv";
-import * as schema from "./schema.js";
-
-dotenv.config();
-
-/**
- * Run database migrations
- * @param migrationsPath Path to migrations folder
- * @returns Promise that resolves when migrations are complete
- */
-export async function runMigrations(migrationsPath: string = "./drizzle") {
- console.log("Running database migrations...");
-
- const migrationClient = postgres({
- host: process.env.POSTGRES_HOST || "postgres",
- port: parseInt(process.env.POSTGRES_PORT || "5432", 10),
- database: process.env.POSTGRES_DB,
- username: process.env.POSTGRES_USER,
- password: process.env.POSTGRES_PASSWORD,
- max: 1,
- onnotice: () => {}, // Silence notices
- });
-
- const db = drizzle(migrationClient, { schema });
-
- try {
- // Create drizzle schema if it doesn't exist
- await migrationClient`CREATE SCHEMA IF NOT EXISTS drizzle;`;
-
- // Create migration table if it doesn't exist
- await migrationClient`
- CREATE TABLE IF NOT EXISTS drizzle."__drizzle_migrations" (
- id SERIAL PRIMARY KEY,
- hash text NOT NULL,
- created_at timestamp with time zone DEFAULT now()
- );
- `;
-
- // Always run migrations, Drizzle will skip already applied ones
- console.log(
- "Running all migrations - Drizzle will skip already applied ones"
- );
-
- // This will run migrations on the database, skipping the ones already applied
- try {
- await migrate(db, { migrationsFolder: migrationsPath });
- console.log("Migrations completed!");
- return true; // Return success
- } catch (err: any) {
- // If error contains relation already exists, tables likely exist but not in drizzle metadata
- if (err.message && err.message.includes("already exists")) {
- console.log(
- "Some tables already exist but not tracked by drizzle. This is expected for existing databases."
- );
- console.log(
- "You can safely ignore these errors if your database is already set up."
- );
- return true; // Consider this a success case
- } else {
- // Other errors should be reported
- throw err;
- }
- }
- } catch (e) {
- console.error("Migration failed!");
- console.error(e);
- return false; // Return failure
- } finally {
- // Don't forget to close the connection
- await migrationClient.end();
- }
-}
-
-// Only run migrations directly if this module is executed directly
-if (import.meta.url === `file://${process.argv[1]}`) {
- runMigrations()
- .then((success) => {
- if (!success) {
- process.exit(1);
- }
- })
- .catch((err) => {
- console.error("Unhandled error in migrations:", err);
- process.exit(1);
- });
-}
diff --git a/server/src/db/postgres/session-cleanup.ts b/server/src/db/postgres/session-cleanup.ts
index a553ed8a8..550b35e6c 100644
--- a/server/src/db/postgres/session-cleanup.ts
+++ b/server/src/db/postgres/session-cleanup.ts
@@ -1,7 +1,5 @@
-import { insertSessions } from "../clickhouse/clickhouse.js";
import { sql } from "./postgres.js";
import { Session } from "./types.js";
-import { DateTime } from "luxon";
// function convertPostgresToClickhouse(postgresTimestamp: string): string {
// console.log("Parsing timestamp:", postgresTimestamp);
@@ -45,13 +43,14 @@ export async function cleanupOldSessions() {
// console.log(`Cleaned up ${deletedSessions.length} sessions`);
- if (deletedSessions.length > 0) {
- await insertSessions(
- deletedSessions.map((e) => ({
- ...e,
- start_time: convertPostgresToClickhouse(e.start_time),
- last_activity: convertPostgresToClickhouse(e.last_activity),
- }))
- );
- }
+ // disabled for now dubvious if we need sessions in clikchouse
+ // if (deletedSessions.length > 0) {
+ // await insertSessions(
+ // deletedSessions.map((e) => ({
+ // ...e,
+ // start_time: convertPostgresToClickhouse(e.start_time),
+ // last_activity: convertPostgresToClickhouse(e.last_activity),
+ // }))
+ // );
+ // }
}