Skip to content

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

feat(api): implement organization-specific site retrieval and subscri… (#333)

Bill Yangc97a49dc163c
diff --git a/client/src/api/admin/sites.ts b/client/src/api/admin/sites.ts
index 9cf651dd1..b26edd240 100644
--- a/client/src/api/admin/sites.ts
+++ b/client/src/api/admin/sites.ts
@@ -3,6 +3,7 @@ import { BACKEND_URL } from "../../lib/const";
import { useStore } from "../../lib/store";
import { authedFetchWithError } from "../utils";
import { usePathname } from "next/navigation";
+import { authClient } from "../../lib/auth";
export type SiteResponse = {
siteId: number;
@@ -11,6 +12,7 @@ export type SiteResponse = {
createdAt: string;
updatedAt: string;
createdBy: string;
+ organizationId: string | null;
public: boolean;
saltUserIds: boolean;
blockBots: boolean;
@@ -33,6 +35,41 @@ export type GetSitesResponse = {
isOwner?: boolean;
}[];
+export type GetSitesFromOrgResponse = {
+ organization: {
+ id: string;
+ name: string;
+ slug: string;
+ logo: string | null;
+ createdAt: string;
+ metadata: string | null;
+ stripeCustomerId: string | null;
+ monthlyEventCount: number | null;
+ overMonthlyLimit: boolean | null;
+ } | null;
+ sites: Array<{
+ siteId: number;
+ name: string;
+ domain: string;
+ createdAt: string;
+ updatedAt: string;
+ createdBy: string;
+ organizationId: string | null;
+ public: boolean | null;
+ saltUserIds: boolean | null;
+ blockBots: boolean;
+ sessionsLast24Hours: number;
+ isOwner: boolean;
+ }>;
+ subscription: {
+ monthlyEventCount: number;
+ eventLimit: number;
+ overMonthlyLimit: boolean;
+ planName: string;
+ status: string;
+ };
+};
+
export function useGetSites() {
return useQuery<GetSitesResponse>({
queryKey: ["get-sites"],
@@ -43,6 +80,19 @@ export function useGetSites() {
});
}
+export function useGetSitesFromOrg(organizationId?: string) {
+ return useQuery<GetSitesFromOrgResponse>({
+ queryKey: ["get-sites-from-org", organizationId],
+ queryFn: () => {
+ return authedFetchWithError(
+ `${BACKEND_URL}/get-sites-from-org/${organizationId}`
+ );
+ },
+ staleTime: 60000, // 1 minute
+ enabled: !!organizationId,
+ });
+}
+
export async function getSites() {
return authedFetchWithError<GetSitesResponse>(`${BACKEND_URL}/get-sites`);
}
@@ -171,8 +221,14 @@ export function changeSiteBlockBots(siteId: number, blockBots: boolean) {
}
export const useCurrentSite = () => {
- const { data: sites } = useGetSites();
+ const { data: activeOrganization } = authClient.useActiveOrganization();
+ const { data: sites } = useGetSitesFromOrg(activeOrganization?.id);
const pathname = usePathname();
- return sites?.find((site) => site.siteId === Number(pathname.split("/")[1]));
+ return {
+ site: sites?.sites.find(
+ (site) => site.siteId === Number(pathname.split("/")[1])
+ ),
+ subscription: sites?.subscription,
+ };
};
diff --git a/client/src/app/[site]/components/Header/UsageBanners.tsx b/client/src/app/[site]/components/Header/UsageBanners.tsx
index 4980e45f4..b8e881fe2 100644
--- a/client/src/app/[site]/components/Header/UsageBanners.tsx
+++ b/client/src/app/[site]/components/Header/UsageBanners.tsx
@@ -9,7 +9,7 @@ import {
import { Button } from "../../../../components/ui/button";
export function UsageBanners() {
- const site = useCurrentSite();
+ const { site, subscription } = useCurrentSite();
if (!site) return null;
@@ -20,17 +20,17 @@ export function UsageBanners() {
// Calculate usage percentage
const getUsagePercentage = () => {
- if (!site.eventLimit || !site.monthlyEventCount) return 0;
- return (site.monthlyEventCount / site.eventLimit) * 100;
+ if (!subscription?.eventLimit || !subscription.monthlyEventCount) return 0;
+ return (subscription.monthlyEventCount / subscription.eventLimit) * 100;
};
const usagePercentage = getUsagePercentage();
- const isNearLimit = usagePercentage >= 90 && !site.overMonthlyLimit;
+ const isNearLimit = usagePercentage >= 90 && !subscription?.overMonthlyLimit;
if (
- site.monthlyEventCount &&
- site.eventLimit &&
- site.monthlyEventCount > site.eventLimit
+ subscription?.monthlyEventCount &&
+ subscription?.eventLimit &&
+ subscription.monthlyEventCount > subscription.eventLimit
) {
return (
<Alert variant="destructive" className="p-4 mt-4">
@@ -41,8 +41,11 @@ export function UsageBanners() {
Event Limit Exceeded
</AlertTitle>
<div className="mb-2 text-sm">
- <strong>{formatNumber(site.monthlyEventCount || 0)}</strong>{" "}
- events used of <strong>{formatNumber(site.eventLimit)}</strong>
+ <strong>
+ {formatNumber(subscription.monthlyEventCount || 0)}
+ </strong>{" "}
+ events used of{" "}
+ <strong>{formatNumber(subscription.eventLimit)}</strong>
</div>
{site.isOwner ? (
@@ -79,8 +82,11 @@ export function UsageBanners() {
Approaching Event Limit
</AlertTitle>
<div className="mb-2 text-sm text-amber-700 dark:text-amber-400">
- <strong>{formatNumber(site.monthlyEventCount || 0)}</strong>{" "}
- events used of <strong>{formatNumber(site.eventLimit)}</strong>
+ <strong>
+ {formatNumber(subscription?.monthlyEventCount || 0)}
+ </strong>{" "}
+ events used of{" "}
+ <strong>{formatNumber(subscription?.eventLimit || 0)}</strong>
</div>
{site.isOwner ? (
diff --git a/client/src/app/[site]/components/Sidebar/SiteSelector.tsx b/client/src/app/[site]/components/Sidebar/SiteSelector.tsx
index a4f6050c3..1af0c5bf8 100644
--- a/client/src/app/[site]/components/Sidebar/SiteSelector.tsx
+++ b/client/src/app/[site]/components/Sidebar/SiteSelector.tsx
@@ -1,6 +1,6 @@
import { Check } from "lucide-react";
import { usePathname, useRouter } from "next/navigation";
-import { useGetSite, useGetSites } from "../../../../api/admin/sites";
+import { useGetSite, useGetSitesFromOrg } from "../../../../api/admin/sites";
import { Favicon } from "../../../../components/Favicon";
import {
DropdownMenu,
@@ -8,20 +8,22 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "../../../../components/ui/dropdown-menu";
-import { resetStore, useStore } from "../../../../lib/store";
+import { authClient } from "../../../../lib/auth";
+import { resetStore } from "../../../../lib/store";
import { userStore } from "../../../../lib/userStore";
import { cn } from "../../../../lib/utils";
function SiteSelectorContent() {
- const { data: sites } = useGetSites();
- const stuff = useStore();
+ const { data: activeOrganization } = authClient.useActiveOrganization();
+ const { data: sites } = useGetSitesFromOrg(activeOrganization?.id);
+
const pathname = usePathname();
const router = useRouter();
const currentSiteId = Number(pathname.split("/")[1]);
return (
<DropdownMenuContent align="start">
- {sites?.map((site) => {
+ {sites?.sites?.map((site) => {
const isSelected = site.siteId === currentSiteId;
return (
<DropdownMenuItem
diff --git a/client/src/app/settings/account/components/AccountInner.tsx b/client/src/app/account/components/AccountInner.tsx
similarity index 96%
rename from client/src/app/settings/account/components/AccountInner.tsx
rename to client/src/app/account/components/AccountInner.tsx
index 9d1e2e32b..dc6f269d5 100644
--- a/client/src/app/settings/account/components/AccountInner.tsx
+++ b/client/src/app/account/components/AccountInner.tsx
@@ -3,14 +3,14 @@
import { authClient } from "@/lib/auth";
import { useState } from "react";
import { toast } from "sonner";
-import { Button } from "../../../../components/ui/button";
+import { Button } from "../../../components/ui/button";
import {
Card,
CardContent,
CardHeader,
CardTitle,
-} from "../../../../components/ui/card";
-import { Input } from "../../../../components/ui/input";
+} from "../../../components/ui/card";
+import { Input } from "../../../components/ui/input";
import { ChangePassword } from "./ChangePassword";
import { DeleteAccount } from "./DeleteAccount";
diff --git a/client/src/app/settings/account/components/ChangePassword.tsx b/client/src/app/account/components/ChangePassword.tsx
similarity index 87%
rename from client/src/app/settings/account/components/ChangePassword.tsx
rename to client/src/app/account/components/ChangePassword.tsx
index e158457db..2136a1c52 100644
--- a/client/src/app/settings/account/components/ChangePassword.tsx
+++ b/client/src/app/account/components/ChangePassword.tsx
@@ -10,7 +10,7 @@ import {
} from "lucide-react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
-import { Button } from "../../../../components/ui/button";
+import { Button } from "../../../components/ui/button";
import {
Dialog,
DialogClose,
@@ -20,10 +20,10 @@ import {
DialogHeader,
DialogTitle,
DialogTrigger,
-} from "../../../../components/ui/dialog";
-import { Input } from "../../../../components/ui/input";
-import { Label } from "../../../../components/ui/label";
-import { authClient } from "../../../../lib/auth";
+} from "../../../components/ui/dialog";
+import { Input } from "../../../components/ui/input";
+import { Label } from "../../../components/ui/label";
+import { authClient } from "../../../lib/auth";
export function ChangePassword() {
const [open, setOpen] = useState(false);
@@ -186,7 +186,14 @@ export function ChangePassword() {
<span>New Password</span>
{passwordStrength > 0 && (
<span
- className={cn("text-xs", passwordStrength <= 2 ? "text-red-500" : passwordStrength === 3 ? "text-yellow-500" : "text-green-500")}
+ className={cn(
+ "text-xs",
+ passwordStrength <= 2
+ ? "text-red-500"
+ : passwordStrength === 3
+ ? "text-yellow-500"
+ : "text-green-500"
+ )}
>
{passwordStrength <= 2
? "Weak"
@@ -223,13 +230,25 @@ export function ChangePassword() {
{[1, 2, 3, 4].map((index) => (
<div
key={index}
- className={cn("h-1.5 w-1/4 rounded-full transition-colors duration-300", index <= passwordStrength ? getStrengthColor() : "bg-neutral-200 dark:bg-neutral-700")}
+ className={cn(
+ "h-1.5 w-1/4 rounded-full transition-colors duration-300",
+ index <= passwordStrength
+ ? getStrengthColor()
+ : "bg-neutral-200 dark:bg-neutral-700"
+ )}
/>
))}
</div>
{passwordFeedback && (
<p
- className={cn("text-xs mt-1", passwordStrength <= 2 ? "text-red-500" : passwordStrength === 3 ? "text-yellow-500" : "text-green-500")}
+ className={cn(
+ "text-xs mt-1",
+ passwordStrength <= 2
+ ? "text-red-500"
+ : passwordStrength === 3
+ ? "text-yellow-500"
+ : "text-green-500"
+ )}
>
{passwordFeedback}
</p>
diff --git a/client/src/app/settings/account/components/DeleteAccount.tsx b/client/src/app/account/components/DeleteAccount.tsx
similarity index 92%
rename from client/src/app/settings/account/components/DeleteAccount.tsx
rename to client/src/app/account/components/DeleteAccount.tsx
index 18401ef65..e8ff75811 100644
--- a/client/src/app/settings/account/components/DeleteAccount.tsx
+++ b/client/src/app/account/components/DeleteAccount.tsx
@@ -15,12 +15,12 @@ import {
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
-} from "../../../../components/ui/alert-dialog";
-import { Button } from "../../../../components/ui/button";
-import { Input } from "../../../../components/ui/input";
-import { Label } from "../../../../components/ui/label";
-import { authClient } from "../../../../lib/auth";
-import { cn } from "../../../../lib/utils";
+} from "../../../components/ui/alert-dialog";
+import { Button } from "../../../components/ui/button";
+import { Input } from "../../../components/ui/input";
+import { Label } from "../../../components/ui/label";
+import { authClient } from "../../../lib/auth";
+import { cn } from "../../../lib/utils";
export function DeleteAccount() {
const [isDeleting, setIsDeleting] = useState(false);
diff --git a/client/src/app/account/page.tsx b/client/src/app/account/page.tsx
new file mode 100644
index 000000000..72b67d83c
--- /dev/null
+++ b/client/src/app/account/page.tsx
@@ -0,0 +1,27 @@
+"use client";
+
+import { useSetPageTitle } from "../../hooks/useSetPageTitle";
+import { StandardPage } from "../../components/StandardPage";
+import { AccountInner } from "./components/AccountInner";
+import { authClient } from "../../lib/auth";
+
+export default function AccountPage() {
+ useSetPageTitle("Rybbit Β· Account");
+ const session = authClient.useSession();
+
+ return (
+ <StandardPage>
+ <div className="space-y-6">
+ <div>
+ <h1 className="text-3xl font-bold tracking-tight">
+ Account Settings
+ </h1>
+ <p className="text-gray-500 dark:text-gray-400">
+ Manage your personal account settings
+ </p>
+ </div>
+ <AccountInner session={session} />
+ </div>
+ </StandardPage>
+ );
+}
diff --git a/client/src/app/auth/subscription/success/page.tsx b/client/src/app/auth/subscription/success/page.tsx
index c1e3f51a5..ce6f07990 100644
--- a/client/src/app/auth/subscription/success/page.tsx
+++ b/client/src/app/auth/subscription/success/page.tsx
@@ -14,7 +14,7 @@ export default function StripeSuccessPage() {
// Add a small delay to ensure the page has fully loaded before redirecting
const redirectTimer = setTimeout(() => {
// Redirect to the subscription settings page
- router.push("/settings/subscription");
+ router.push("/organization/subscription");
}, 1000);
// Clean up the timer if the component unmounts
diff --git a/client/src/app/components/AddSite.tsx b/client/src/app/components/AddSite.tsx
index 8fb405c5c..be65dcaea 100644
--- a/client/src/app/components/AddSite.tsx
+++ b/client/src/app/components/AddSite.tsx
@@ -1,9 +1,8 @@
"use client";
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 { AlertCircle, AppWindow, Plus } from "lucide-react";
+import { useState } from "react";
+import { addSite, useGetSitesFromOrg } from "../../api/admin/sites";
import { Alert, AlertDescription, AlertTitle } from "../../components/ui/alert";
import {
Dialog,
@@ -16,21 +15,15 @@ import {
} from "../../components/ui/dialog";
import { Input } from "../../components/ui/input";
import { Label } from "../../components/ui/label";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "../../components/ui/select";
import { Switch } from "../../components/ui/switch";
-import { authClient } from "../../lib/auth";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "../../components/ui/tooltip";
+import { authClient } from "../../lib/auth";
import { IS_CLOUD } from "../../lib/const";
+import { useStripeSubscription } from "../../lib/subscription/useStripeSubscription";
/**
* A simple domain validation function:
@@ -51,38 +44,27 @@ export function AddSite({
trigger?: React.ReactNode;
disabled?: boolean;
}) {
- const { data: sites, refetch } = useGetSites();
- const { data: organizations } = authClient.useListOrganizations();
+ const { data: activeOrganization } = authClient.useActiveOrganization();
+ const { data: sites, refetch } = useGetSitesFromOrg(activeOrganization?.id);
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;
+ subscription?.status !== "active" &&
+ (sites?.sites?.length || 0) >= 3 &&
+ IS_CLOUD;
const finalDisabled = disabled || isDisabledDueToLimit;
const [open, setOpen] = useState(false);
const [domain, setDomain] = useState("");
- const [selectedOrganizationId, setSelectedOrganizationId] =
- useState<string>("");
const [isPublic, setIsPublic] = useState(false);
const [saltUserIds, setSaltUserIds] = useState(false);
const [error, setError] = useState("");
- // Set the first organization as the default selection when organizations are loaded
- useEffect(() => {
- if (organizations && organizations.length > 0 && !selectedOrganizationId) {
- setSelectedOrganizationId(organizations[0].id);
- }
- }, [organizations, selectedOrganizationId]);
-
- const domainMatchesExistingSites = existingSites?.includes(domain);
-
const handleSubmit = async () => {
setError("");
- if (!selectedOrganizationId) {
+ if (!activeOrganization?.id) {
setError("Please select an organization");
return;
}
@@ -96,7 +78,7 @@ export function AddSite({
}
try {
- await addSite(domain, domain, selectedOrganizationId, {
+ await addSite(domain, domain, activeOrganization.id, {
isPublic,
saltUserIds,
});
@@ -114,10 +96,6 @@ export function AddSite({
setError("");
setIsPublic(false);
setSaltUserIds(false);
- // Reset organization to first one when opening dialog
- if (organizations && organizations.length > 0) {
- setSelectedOrganizationId(organizations[0].id);
- }
};
// Show upgrade message if disabled due to limit
@@ -182,39 +160,6 @@ export function AddSite({
placeholder="example.com or sub.example.com"
/>
</div>
- <div className="grid w-full items-center gap-1.5">
- <Label
- htmlFor="organization"
- className="text-sm font-medium text-white"
- >
- Organization
- </Label>
- <Select
- value={selectedOrganizationId}
- onValueChange={setSelectedOrganizationId}
- disabled={!organizations || organizations.length === 0}
- >
- <SelectTrigger className="w-full">
- <SelectValue placeholder="Select an organization" />
- </SelectTrigger>
- <SelectContent>
- {organizations?.map((org) => (
- <SelectItem key={org.id} value={org.id}>
- <div className="flex items-center">
- <Building2 className="h-4 w-4 mr-2 text-muted-foreground" />
- {org.name}
- </div>
- </SelectItem>
- ))}
- {(!organizations || organizations.length === 0) && (
- <SelectItem value="no-org" disabled>
- No organizations available
- </SelectItem>
- )}
- </SelectContent>
- </Select>
- </div>
-
{/* Public Analytics Setting */}
<div className="flex items-center justify-between">
<div>
@@ -275,9 +220,7 @@ export function AddSite({
type="submit"
variant={"success"}
onClick={handleSubmit}
- disabled={
- !domain || domainMatchesExistingSites || !selectedOrganizationId
- }
+ disabled={!domain}
>
Add
</Button>
diff --git a/client/src/app/layout.tsx b/client/src/app/layout.tsx
index fb4232af2..f92557d07 100644
--- a/client/src/app/layout.tsx
+++ b/client/src/app/layout.tsx
@@ -13,6 +13,7 @@ import "./globals.css";
import Script from "next/script";
import { useStopImpersonation } from "@/hooks/useStopImpersonation";
import { ReactScan } from "./ReactScan";
+import { OrganizationInitializer } from "../components/OrganizationInitializer";
const inter = Inter({ subsets: ["latin"] });
@@ -91,7 +92,10 @@ export default function RootLayout({
inter.className
)}
>
- <QueryProvider>{children}</QueryProvider>
+ <QueryProvider>
+ <OrganizationInitializer />
+ {children}
+ </QueryProvider>
<Toaster />
</body>
</TooltipProvider>
diff --git a/client/src/app/organization/layout.tsx b/client/src/app/organization/layout.tsx
new file mode 100644
index 000000000..a3b139c93
--- /dev/null
+++ b/client/src/app/organization/layout.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+import { StandardPage } from "../../components/StandardPage";
+import { OrganizationSelector } from "../../components/OrganizationSelector";
+import { Tabs, TabsList, TabsTrigger } from "../../components/ui/tabs";
+import { useRouter, usePathname } from "next/navigation";
+import { Users, CreditCard } from "lucide-react";
+import { IS_CLOUD } from "../../lib/const";
+
+export default function OrganizationLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ const router = useRouter();
+ const pathname = usePathname();
+
+ // Determine active tab from pathname
+ const activeTab = pathname.includes("/subscription")
+ ? "subscription"
+ : "members";
+
+ const handleTabChange = (value: string) => {
+ if (value === "members") {
+ router.push("/organization/members");
+ } else if (value === "subscription") {
+ router.push("/organization/subscription");
+ }
+ };
+
+ return (
+ <StandardPage>
+ <div className="space-y-6">
+ <div>
+ <h1 className="text-3xl font-bold tracking-tight">
+ Organization Settings
+ </h1>
+ <p className="text-gray-500 dark:text-gray-400">
+ Manage your organization settings and members
+ </p>
+ </div>
+
+ <OrganizationSelector />
+
+ <Tabs value={activeTab} onValueChange={handleTabChange}>
+ <TabsList>
+ <TabsTrigger value="members" className="flex items-center gap-2">
+ <Users size={16} />
+ Members
+ </TabsTrigger>
+ {IS_CLOUD && (
+ <TabsTrigger
+ value="subscription"
+ className="flex items-center gap-2"
+ >
+ <CreditCard size={16} />
+ Subscription
+ </TabsTrigger>
+ )}
+ </TabsList>
+ </Tabs>
+
+ <div className="mt-6">{children}</div>
+ </div>
+ </StandardPage>
+ );
+}
diff --git a/client/src/app/settings/organizations/components/DeleteOrganizationDialog.tsx b/client/src/app/organization/members/components/DeleteOrganizationDialog.tsx
similarity index 100%
rename from client/src/app/settings/organizations/components/DeleteOrganizationDialog.tsx
rename to client/src/app/organization/members/components/DeleteOrganizationDialog.tsx
diff --git a/client/src/app/settings/organizations/components/EditOrganizationDialog.tsx b/client/src/app/organization/members/components/EditOrganizationDialog.tsx
similarity index 100%
rename from client/src/app/settings/organizations/components/EditOrganizationDialog.tsx
rename to client/src/app/organization/members/components/EditOrganizationDialog.tsx
diff --git a/client/src/app/settings/organizations/components/Invitations.tsx b/client/src/app/organization/members/components/Invitations.tsx
similarity index 100%
rename from client/src/app/settings/organizations/components/Invitations.tsx
rename to client/src/app/organization/members/components/Invitations.tsx
diff --git a/client/src/app/settings/organizations/components/InviteMemberDialog.tsx b/client/src/app/organization/members/components/InviteMemberDialog.tsx
similarity index 89%
rename from client/src/app/settings/organizations/components/InviteMemberDialog.tsx
rename to client/src/app/organization/members/components/InviteMemberDialog.tsx
index 7dc1a9068..47c5ec67d 100644
--- a/client/src/app/settings/organizations/components/InviteMemberDialog.tsx
+++ b/client/src/app/organization/members/components/InviteMemberDialog.tsx
@@ -49,19 +49,6 @@ export function InviteMemberDialog({
setIsLoading(true);
try {
- // await fetch(`${BACKEND_URL}/add-user-to-organization`, {
- // method: "POST",
- // body: JSON.stringify({
- // email: email,
- // role: role,
- // organizationId: organizationId,
- // }),
- // headers: {
- // "Content-Type": "application/json",
- // },
- // credentials: "include",
- // });
-
await authClient.organization.inviteMember({
email,
role,
@@ -119,7 +106,7 @@ export function InviteMemberDialog({
<SelectValue placeholder="Select a role" />
</SelectTrigger>
<SelectContent>
- {/* <SelectItem value="owner">Owner</SelectItem> */}
+ <SelectItem value="owner">Owner</SelectItem>
<SelectItem value="admin">Admin</SelectItem>
<SelectItem value="member">Member</SelectItem>
</SelectContent>
diff --git a/client/src/app/settings/organizations/components/RemoveMemberDialog.tsx b/client/src/app/organization/members/components/RemoveMemberDialog.tsx
similarity index 100%
rename from client/src/app/settings/organizations/components/RemoveMemberDialog.tsx
rename to client/src/app/organization/members/components/RemoveMemberDialog.tsx
diff --git a/client/src/app/settings/organizations/page.tsx b/client/src/app/organization/members/page.tsx
similarity index 87%
rename from client/src/app/settings/organizations/page.tsx
rename to client/src/app/organization/members/page.tsx
index e979ae8f7..2f6aff4de 100644
--- a/client/src/app/settings/organizations/page.tsx
+++ b/client/src/app/organization/members/page.tsx
@@ -16,26 +16,21 @@ import {
} from "../../../components/ui/table";
import { authClient } from "../../../lib/auth";
-// Import the separated dialog components
import { useOrganizationMembers } from "../../../api/admin/auth";
-import {
- useOrganizationInvitations,
- UserOrganization,
- useUserOrganizations,
-} from "../../../api/admin/organizations";
+import { useOrganizationInvitations } from "../../../api/admin/organizations";
import { NoOrganization } from "../../../components/NoOrganization";
import { InviteMemberDialog } from "./components/InviteMemberDialog";
-import { DeleteOrganizationDialog } from "./components/DeleteOrganizationDialog";
+import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { EditOrganizationDialog } from "./components/EditOrganizationDialog";
+import { DeleteOrganizationDialog } from "./components/DeleteOrganizationDialog";
import { RemoveMemberDialog } from "./components/RemoveMemberDialog";
-import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { Invitations } from "./components/Invitations";
// Types for our component
export type Organization = {
id: string;
name: string;
- createdAt: string;
+ createdAt: Date;
slug: string;
};
@@ -54,7 +49,16 @@ export type Member = {
};
// Organization Component with Members Table
-function Organization({ org }: { org: UserOrganization }) {
+function Organization({
+ org,
+}: {
+ org: {
+ id: string;
+ name: string;
+ slug: string;
+ createdAt: Date;
+ };
+}) {
const { data: members, refetch } = useOrganizationMembers(org.id);
const { refetch: refetchInvitations } = useOrganizationInvitations(org.id);
const { data } = authClient.useSession();
@@ -156,29 +160,28 @@ function Organization({ org }: { org: UserOrganization }) {
}
// Main Organizations component
-export default function Organizations() {
- useSetPageTitle("Rybbit Β· Organizations");
- const { data, isLoading } = useUserOrganizations();
+export default function MembersPage() {
+ useSetPageTitle("Rybbit Β· Organization Members");
+ const { data: activeOrganization, isPending } =
+ authClient.useActiveOrganization();
- if (isLoading) {
+ if (isPending) {
return (
<div className="flex justify-center py-8">
- <div className="animate-pulse">Loading organizations...</div>
+ <div className="animate-pulse">Loading organization...</div>
</div>
);
}
- if (!data?.length) {
+ if (!activeOrganization) {
return (
- <NoOrganization message="You need to create or be added to an organization before you can manage your organizations." />
+ <NoOrganization message="You need to create or be added to an organization before you can manage members." />
);
}
return (
<div className="flex flex-col gap-6">
- {data?.map((organization) => (
- <Organization key={organization.id} org={organization} />
- ))}
+ <Organization key={activeOrganization.id} org={activeOrganization} />
</div>
);
}
diff --git a/client/src/app/organization/page.tsx b/client/src/app/organization/page.tsx
new file mode 100644
index 000000000..7ad46be0b
--- /dev/null
+++ b/client/src/app/organization/page.tsx
@@ -0,0 +1,15 @@
+"use client";
+
+import { useEffect } from "react";
+import { useRouter } from "next/navigation";
+
+export default function OrganizationPage() {
+ const router = useRouter();
+
+ useEffect(() => {
+ // Redirect to members page by default
+ router.replace("/organization/members");
+ }, [router]);
+
+ return null;
+}
diff --git a/client/src/app/settings/subscription/page.tsx b/client/src/app/organization/subscription/page.tsx
similarity index 62%
rename from client/src/app/settings/subscription/page.tsx
rename to client/src/app/organization/subscription/page.tsx
index c557a50f6..53b627ffd 100644
--- a/client/src/app/settings/subscription/page.tsx
+++ b/client/src/app/organization/subscription/page.tsx
@@ -7,37 +7,41 @@ import {
CardTitle,
} from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
-import { ProPlan } from "./components/ProPlan";
-import { useStripeSubscription } from "./utils/useStripeSubscription";
-import { useUserOrganizations } from "../../../api/admin/organizations";
+import { ProPlan } from "../../../components/subscription/ProPlan";
+import { useStripeSubscription } from "../../../lib/subscription/useStripeSubscription";
import { NoOrganization } from "../../../components/NoOrganization";
-import { TrialPlan } from "./components/TrialPlan";
-import { ExpiredTrialPlan } from "./components/ExpiredTrialPlan";
+import { TrialPlan } from "../../../components/subscription/TrialPlan";
+import { ExpiredTrialPlan } from "../../../components/subscription/ExpiredTrialPlan";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
-import { FreePlan } from "./components/FreePlan";
+import { FreePlan } from "../../../components/subscription/FreePlan";
import { Building } from "lucide-react";
+import { authClient } from "@/lib/auth";
-export default function SubscriptionPage() {
- useSetPageTitle("Rybbit Β· Subscription");
+export default function OrganizationSubscriptionPage() {
+ useSetPageTitle("Rybbit Β· Organization Subscription");
const { data: activeSubscription, isLoading: isLoadingSubscription } =
useStripeSubscription();
- const { data: organizations, isLoading: isLoadingOrganizations } =
- useUserOrganizations();
+ const { data: activeOrg } = authClient.useActiveOrganization();
+ const { data: session } = authClient.useSession();
- const hasOrganization = !!organizations?.length;
+ // Check if the current user is an owner by looking at the members in the active organization
+ const currentUserMember = activeOrg?.members?.find(
+ (member) => member.userId === session?.user?.id
+ );
+ const isOwner = currentUserMember?.role === "owner";
- const isLoading = isLoadingSubscription || isLoadingOrganizations;
+ const isLoading = isLoadingSubscription;
// Determine which plan to display
const renderPlanComponent = () => {
- if (!hasOrganization) {
+ if (!activeOrg) {
return (
- <NoOrganization message="You need to be part of an organization to manage your subscription." />
+ <NoOrganization message="You need to select an organization to manage your subscription." />
);
}
- if (organizations[0].role !== "owner") {
+ if (!isOwner) {
return (
<Card className="p-6 flex flex-col items-center text-center w-full">
<div className="mx-auto w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center mb-4">
@@ -73,16 +77,7 @@ export default function SubscriptionPage() {
};
return (
- <div className="py-2">
- <div className="flex justify-between items-center mb-4">
- <div>
- <h1 className="text-3xl font-bold tracking-tight">Subscription</h1>
- <p className="text-gray-500 dark:text-gray-400">
- Manage your subscription and billing information
- </p>
- </div>
- </div>
-
+ <div className="space-y-6">
{isLoading ? (
<Card>
<CardContent className="pt-6">
diff --git a/client/src/app/page.tsx b/client/src/app/page.tsx
index 6aecbe58b..43a827836 100644
--- a/client/src/app/page.tsx
+++ b/client/src/app/page.tsx
@@ -3,24 +3,30 @@
import { Plus } from "lucide-react";
import { useState } from "react";
import { useUserOrganizations } from "../api/admin/organizations";
-import { useGetSites } from "../api/admin/sites";
+import { useGetSitesFromOrg } from "../api/admin/sites";
import { CreateOrganizationDialog } from "../components/CreateOrganizationDialog";
import { NoOrganization } from "../components/NoOrganization";
+import { OrganizationSelector } from "../components/OrganizationSelector";
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 { useSetPageTitle } from "../hooks/useSetPageTitle";
+import { authClient } from "../lib/auth";
import { AddSite } from "./components/AddSite";
export default function Home() {
useSetPageTitle("Rybbit Β· Home");
+ const { data: activeOrganization, isPending } =
+ authClient.useActiveOrganization();
+
const {
data: sites,
refetch: refetchSites,
isLoading: isLoadingSites,
- } = useGetSites();
+ } = useGetSitesFromOrg(activeOrganization?.id);
+
const {
data: userOrganizationsData,
isLoading: isLoadingOrganizations,
@@ -47,7 +53,10 @@ export default function Home() {
return (
<StandardPage>
<div className="flex justify-between items-center my-4">
- <div className="text-2xl font-bold">{sites?.length} Websites</div>
+ <div>
+ <OrganizationSelector />
+ </div>
+ {/* <div className="text-2xl font-bold">{sites?.length} Websites</div> */}
<AddSite disabled={hasNoOrganizations || disabled} />
</div>
{/* Organization required message */}
@@ -56,7 +65,7 @@ export default function Home() {
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{/* Sites list */}
- {sites?.map((site) => {
+ {sites?.sites?.map((site) => {
return (
<SiteCard
key={site.siteId}
@@ -68,7 +77,7 @@ export default function Home() {
{/* No websites message */}
{!hasNoOrganizations &&
- (!sites || sites.length === 0) &&
+ (!sites?.sites || sites?.sites?.length === 0) &&
!isLoadingOrganizations &&
!isLoadingSites && (
<Card className="col-span-full p-6 flex flex-col items-center text-center">
diff --git a/client/src/app/settings/account/page.tsx b/client/src/app/settings/account/page.tsx
deleted file mode 100644
index b949adb03..000000000
--- a/client/src/app/settings/account/page.tsx
+++ /dev/null
@@ -1,16 +0,0 @@
-"use client";
-
-import { authClient } from "@/lib/auth";
-import { AccountInner } from "./components/AccountInner";
-import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
-
-export default function AccountPage() {
- useSetPageTitle("Rybbit Β· Account");
- const session = authClient.useSession();
-
- if (!session.data) {
- return null;
- }
-
- return <AccountInner session={session} />;
-}
diff --git a/client/src/app/settings/layout.tsx b/client/src/app/settings/layout.tsx
deleted file mode 100644
index 32b9e0811..000000000
--- a/client/src/app/settings/layout.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-"use client";
-
-import { useEffect, useState } from "react";
-import { Button } from "../../components/ui/button";
-import { CreditCard, User, Users } from "lucide-react";
-import { usePathname, useRouter } from "next/navigation";
-import { StandardPage } from "../../components/StandardPage";
-import { IS_CLOUD } from "../../lib/const";
-
-export default function SettingsLayout({
- children,
-}: {
- children: React.ReactNode;
-}) {
- const router = useRouter();
- const [selectedTab, setSelectedTab] = useState<
- "account" | "settings" | "organizations" | "subscription"
- >("account");
-
- const pathname = usePathname();
-
- useEffect(() => {
- setSelectedTab(
- pathname.split("/").pop() as "account" | "organizations" | "subscription"
- );
- }, [pathname]);
-
- return (
- <StandardPage>
- <div className="grid grid-cols-1 sm:grid-cols-[200px_1fr] gap-6">
- <div className="flex flex-col gap-2">
- <Button
- variant={selectedTab === "account" ? "default" : "ghost"}
- onClick={() => {
- setSelectedTab("account");
- router.push("/settings/account");
- }}
- className="justify-start"
- >
- <User size={16} />
- Account
- </Button>
- <Button
- variant={selectedTab === "organizations" ? "default" : "ghost"}
- onClick={() => {
- setSelectedTab("organizations");
- router.push("/settings/organizations");
- }}
- className="justify-start"
- >
- <Users size={16} />
- Organizations
- </Button>
- {IS_CLOUD && (
- <Button
- variant={selectedTab === "subscription" ? "default" : "ghost"}
- onClick={() => {
- setSelectedTab("subscription");
- router.push("/settings/subscription");
- }}
- className="justify-start"
- >
- <CreditCard size={16} />
- Subscription
- </Button>
- )}
- </div>
- {children}
- </div>
- </StandardPage>
- );
-}
diff --git a/client/src/app/settings/organizations/components/AddUser.tsx b/client/src/app/settings/organizations/components/AddUser.tsx
deleted file mode 100644
index 26a8fd7e1..000000000
--- a/client/src/app/settings/organizations/components/AddUser.tsx
+++ /dev/null
@@ -1,144 +0,0 @@
-import { authedFetchWithError } from "@/api/utils";
-import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
-import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogFooter,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
-} from "@/components/ui/dialog";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { Switch } from "@/components/ui/switch";
-import { BACKEND_URL } from "@/lib/const";
-import { AlertCircle } from "lucide-react";
-import { useState } from "react";
-
-export function AddUser({ refetch }: { refetch: () => void }) {
- const [open, setOpen] = useState(false);
- const [email, setEmail] = useState("");
- const [password, setPassword] = useState("");
- const [confirmPassword, setConfirmPassword] = useState("");
- const [isAdmin, setIsAdmin] = useState(false);
-
- const [error, setError] = useState("");
-
- const passwordsMatch = password === confirmPassword;
-
- const handleSubmit = async () => {
- setError("");
-
- if (password !== confirmPassword) {
- setError("password and confirm password do not match");
- return;
- }
- try {
- await authedFetchWithError<{ success: boolean }>(
- `${BACKEND_URL}/create-account`,
- {
- method: "POST",
- body: JSON.stringify({
- email,
- name: "",
- password,
- isAdmin,
- }),
- headers: {
- "Content-Type": "application/json",
- },
- }
- );
- setOpen(false);
- refetch();
- } catch (error) {
- setError(String(error));
- }
- };
-
- return (
- <div>
- <Dialog
- open={open}
- onOpenChange={(isOpen) => {
- setOpen(isOpen);
- setPassword("");
- setConfirmPassword("");
- setEmail("");
- setError("");
- setIsAdmin(false);
- }}
- >
- <DialogTrigger asChild>
- <Button>Add User</Button>
- </DialogTrigger>
- <DialogContent className="max-w-lg">
- <DialogHeader>
- <DialogTitle>Add User</DialogTitle>
- </DialogHeader>
- <div className="grid w-full items-center gap-1.5">
- <Label htmlFor="email">Email</Label>
- <Input
- id="email"
- value={email}
- onChange={(e) => setEmail(e.target.value)}
- placeholder="Email"
- />
- </div>
- <div className="flex items-center space-x-2">
- <Switch
- id="is-admin"
- checked={isAdmin}
- onCheckedChange={() => setIsAdmin(!isAdmin)}
- />
- <Label htmlFor="is-admin">Admin</Label>
- </div>
- <div className="grid w-full items-center gap-1.5">
- <Label htmlFor="password"> Password</Label>
- <Input
- id="password"
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- placeholder="β€’β€’β€’β€’β€’β€’β€’β€’"
- type="password"
- />
- </div>
- <div className="grid w-full items-center gap-1.5">
- <Label htmlFor="confirmPassword">Confirm Password</Label>
- <Input
- id="confirmPassword"
- value={confirmPassword}
- onChange={(e) => setConfirmPassword(e.target.value)}
- placeholder="β€’β€’β€’β€’β€’β€’β€’β€’"
- type="password"
- />
- </div>
- {error && (
- <Alert variant="destructive">
- <AlertCircle className="h-4 w-4" />
- <AlertTitle>Error Creating User</AlertTitle>
- <AlertDescription>{error}</AlertDescription>
- </Alert>
- )}
- <DialogFooter>
- <Button
- type="submit"
- onClick={() => setOpen(false)}
- variant={"ghost"}
- >
- Cancel
- </Button>
- <Button
- type="submit"
- onClick={handleSubmit}
- disabled={!password || !confirmPassword || !passwordsMatch}
- >
- Create
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </div>
- );
-}
diff --git a/client/src/app/settings/organizations/components/DeleteUser.tsx b/client/src/app/settings/organizations/components/DeleteUser.tsx
deleted file mode 100644
index eae36a4e9..000000000
--- a/client/src/app/settings/organizations/components/DeleteUser.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { useState } from "react";
-import { ConfirmationModal } from "@/components/ConfirmationModal";
-import { Button } from "@/components/ui/button";
-import { UserWithRole } from "better-auth/plugins/admin";
-import { authClient } from "@/lib/auth";
-
-export function DeleteUser({
- user,
- refetch,
-}: {
- user: UserWithRole;
- refetch: () => void;
-}) {
- const [isOpen, setIsOpen] = useState(false);
-
- return (
- <ConfirmationModal
- title="Delete User"
- description="Are you sure you want to delete this user?"
- isOpen={isOpen}
- setIsOpen={setIsOpen}
- onConfirm={async () => {
- await authClient.admin.removeUser({ userId: user.id });
- refetch();
- }}
- primaryAction={{
- variant: "destructive",
- children: "Delete",
- }}
- >
- <Button variant={"destructive"} size={"sm"}>
- Delete
- </Button>
- </ConfirmationModal>
- );
-}
diff --git a/client/src/app/subscribe/components/PricingCard.tsx b/client/src/app/subscribe/components/PricingCard.tsx
index 75cd984c1..8d2193a7b 100644
--- a/client/src/app/subscribe/components/PricingCard.tsx
+++ b/client/src/app/subscribe/components/PricingCard.tsx
@@ -4,6 +4,7 @@ import { Slider } from "@/components/ui/slider";
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import { BACKEND_URL } from "@/lib/const";
+import { authClient } from "@/lib/auth";
import {
EVENT_TIERS,
PRO_FEATURES,
@@ -21,6 +22,7 @@ export function PricingCard({ stripePrices, isLoggedIn }: PricingCardProps) {
const [eventLimitIndex, setEventLimitIndex] = useState<number>(0); // Default to 100k (index 0)
const [isAnnual, setIsAnnual] = useState<boolean>(true);
const [isLoading, setIsLoading] = useState<boolean>(false);
+ const { data: activeOrg } = authClient.useActiveOrganization();
const eventLimit = EVENT_TIERS[eventLimitIndex];
@@ -38,6 +40,12 @@ export function PricingCard({ stripePrices, isLoggedIn }: PricingCardProps) {
return;
}
+ // Check if user has an active organization
+ if (!activeOrg) {
+ toast.error("Please select an organization to subscribe.");
+ return;
+ }
+
const selectedTierPrice = findPriceForTier(
eventLimit,
isAnnual ? "year" : "month",
@@ -53,7 +61,7 @@ export function PricingCard({ stripePrices, isLoggedIn }: PricingCardProps) {
try {
// Use NEXT_PUBLIC_BACKEND_URL if available, otherwise use relative path for same-origin requests
const baseUrl = window.location.origin;
- const successUrl = `${baseUrl}/settings/subscription?session_id={CHECKOUT_SESSION_ID}`;
+ const successUrl = `${baseUrl}/organization/subscription?session_id={CHECKOUT_SESSION_ID}`;
const cancelUrl = `${baseUrl}/subscribe`;
const response = await fetch(
@@ -68,6 +76,7 @@ export function PricingCard({ stripePrices, isLoggedIn }: PricingCardProps) {
priceId: selectedTierPrice.priceId,
successUrl: successUrl,
cancelUrl: cancelUrl,
+ organizationId: activeOrg.id,
}),
}
);
diff --git a/client/src/app/subscribe/page.tsx b/client/src/app/subscribe/page.tsx
index d4497ad96..084fa4b14 100644
--- a/client/src/app/subscribe/page.tsx
+++ b/client/src/app/subscribe/page.tsx
@@ -6,8 +6,7 @@ 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 { useStripeSubscription } from "../../lib/subscription/useStripeSubscription";
import { useGetOrgEventCount } from "../../api/analytics/useGetOrgEventCount";
import { UsageChart } from "../../components/UsageChart";
import { PricingHeader } from "./components/PricingHeader";
@@ -17,16 +16,16 @@ import { FAQSection } from "./components/FAQSection";
export default function Subscribe() {
const { data: sessionData } = authClient.useSession();
const { data: subscription } = useStripeSubscription();
- const { data: organizations } = useUserOrganizations();
+ const { data: activeOrg } = authClient.useActiveOrganization();
const router = useRouter();
// Redirect if already subscribed
if (subscription?.status === "active") {
- router.push("/settings/subscription");
+ router.push("/organization/subscription");
}
- // Get the first organization
- const organizationId = organizations?.[0]?.id;
+ // Get the active organization ID
+ const organizationId = activeOrg?.id;
// Get last 30 days of data
const endDate = DateTime.now().toISODate();
diff --git a/client/src/components/DisabledOverlay.tsx b/client/src/components/DisabledOverlay.tsx
index 8b5d9e9d5..e1006656b 100644
--- a/client/src/components/DisabledOverlay.tsx
+++ b/client/src/components/DisabledOverlay.tsx
@@ -1,10 +1,9 @@
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";
import { useCurrentSite } from "../api/admin/sites";
-import { DEFAULT_EVENT_LIMIT } from "../app/settings/subscription/utils/constants";
+import { DEFAULT_EVENT_LIMIT } from "../lib/subscription/constants";
+import { Button } from "./ui/button";
interface DisabledOverlayProps {
children: ReactNode;
@@ -57,9 +56,9 @@ export const DisabledOverlay: React.FC<DisabledOverlayProps> = ({
showMessage = true,
style,
}) => {
- const site = useCurrentSite();
+ const { subscription, site } = useCurrentSite();
- const disabled = site?.eventLimit === DEFAULT_EVENT_LIMIT;
+ const disabled = subscription?.eventLimit === DEFAULT_EVENT_LIMIT;
if (!disabled) {
return <>{children}</>;
@@ -82,7 +81,7 @@ export const DisabledOverlay: React.FC<DisabledOverlayProps> = ({
>
{showMessage && (
<div className="flex items-center justify-center">
- {site.isOwner ? ownerMessage(message) : userMessage(message)}
+ {site?.isOwner ? ownerMessage(message) : userMessage(message)}
</div>
)}
</div>
diff --git a/client/src/components/FreePlanBanner.tsx b/client/src/components/FreePlanBanner.tsx
index b56638440..717fb7087 100644
--- a/client/src/components/FreePlanBanner.tsx
+++ b/client/src/components/FreePlanBanner.tsx
@@ -1,11 +1,11 @@
import { ArrowRight } from "lucide-react";
import Link from "next/link";
import { useCurrentSite } from "../api/admin/sites";
-import { DEFAULT_EVENT_LIMIT } from "../app/settings/subscription/utils/constants";
+import { DEFAULT_EVENT_LIMIT } from "../lib/subscription/constants";
import { Button } from "./ui/button";
export function FreePlanBanner() {
- const site = useCurrentSite();
+ const { site, subscription } = useCurrentSite();
if (!site) return null;
@@ -14,14 +14,17 @@ export function FreePlanBanner() {
return num.toLocaleString();
};
- if (site.eventLimit === DEFAULT_EVENT_LIMIT) {
+ if (subscription?.eventLimit === DEFAULT_EVENT_LIMIT) {
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(site.monthlyEventCount)}</strong> of{" "}
- {formatNumber(site.eventLimit)} events
+ <strong>
+ {formatNumber(subscription?.monthlyEventCount || 0)}
+ </strong>{" "}
+ of <strong>{formatNumber(subscription?.eventLimit || 0)}</strong>{" "}
+ events
</span>
</div>
{site.isOwner && (
diff --git a/client/src/components/FreeTrialBanner.tsx b/client/src/components/FreeTrialBanner.tsx
index c86f96cc4..a952d24cc 100644
--- a/client/src/components/FreeTrialBanner.tsx
+++ b/client/src/components/FreeTrialBanner.tsx
@@ -1,9 +1,9 @@
import { AlertTriangle, ArrowRight, Clock } from "lucide-react";
import { Alert, AlertDescription, AlertTitle } from "./ui/alert";
-import { useStripeSubscription } from "../app/settings/subscription/utils/useStripeSubscription";
+import { useStripeSubscription } from "../lib/subscription/useStripeSubscription";
import Link from "next/link";
import { Button } from "./ui/button";
-import { DEFAULT_EVENT_LIMIT } from "../app/settings/subscription/utils/constants";
+import { DEFAULT_EVENT_LIMIT } from "../lib/subscription/constants";
export function FreeTrialBanner() {
const { data: subscription } = useStripeSubscription();
diff --git a/client/src/components/NoOrganization.tsx b/client/src/components/NoOrganization.tsx
index 152e8e952..ca328f579 100644
--- a/client/src/components/NoOrganization.tsx
+++ b/client/src/components/NoOrganization.tsx
@@ -1,7 +1,6 @@
import { Building, Plus } from "lucide-react";
import { useState } from "react";
import { useUserOrganizations } from "../api/admin/organizations";
-import { useGetSites } from "../api/admin/sites";
import { CreateOrganizationDialog } from "./CreateOrganizationDialog";
import { Button } from "./ui/button";
import { Card, CardDescription, CardTitle } from "./ui/card";
@@ -12,12 +11,10 @@ export function NoOrganization({
message?: string;
}) {
const [createOrgDialogOpen, setCreateOrgDialogOpen] = useState(false);
- const { refetch: refetchSites } = useGetSites();
const { refetch: refetchOrganizations } = useUserOrganizations();
const handleOrganizationCreated = () => {
refetchOrganizations();
- refetchSites();
};
return (
<div className="w-full ">
diff --git a/client/src/components/OrganizationInitializer.tsx b/client/src/components/OrganizationInitializer.tsx
new file mode 100644
index 000000000..e37c20efd
--- /dev/null
+++ b/client/src/components/OrganizationInitializer.tsx
@@ -0,0 +1,25 @@
+"use client";
+
+import { useEffect } from "react";
+import { authClient } from "../lib/auth";
+import { useUserOrganizations } from "../api/admin/organizations";
+
+export function OrganizationInitializer() {
+ const { data: organizations } = useUserOrganizations();
+ const { data: activeOrganization, isPending: isPendingActiveOrganization } =
+ authClient.useActiveOrganization();
+
+ useEffect(() => {
+ if (
+ !isPendingActiveOrganization &&
+ !activeOrganization &&
+ organizations?.length
+ ) {
+ authClient.organization.setActive({
+ organizationId: organizations?.[0]?.id,
+ });
+ }
+ }, [isPendingActiveOrganization, activeOrganization, organizations]);
+
+ return null; // This component doesn't render anything
+}
diff --git a/client/src/components/OrganizationSelector.tsx b/client/src/components/OrganizationSelector.tsx
new file mode 100644
index 000000000..0d18b1485
--- /dev/null
+++ b/client/src/components/OrganizationSelector.tsx
@@ -0,0 +1,79 @@
+import { Building2 } from "lucide-react";
+import { useState, useEffect } from "react";
+import { authClient } from "../lib/auth";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "./ui/select";
+import { useUserOrganizations } from "../api/admin/organizations";
+
+export function OrganizationSelector() {
+ const { data: organizations } = useUserOrganizations();
+ const { data: activeOrganization, isPending } =
+ authClient.useActiveOrganization();
+
+ // Local state to handle the delay when switching organizations
+ const [selectedOrgId, setSelectedOrgId] = useState<string | null>(null);
+
+ // Update local state when activeOrganization changes
+ useEffect(() => {
+ if (activeOrganization?.id) {
+ setSelectedOrgId(activeOrganization.id);
+ }
+ }, [activeOrganization?.id]);
+
+ const handleValueChange = (organizationId: string) => {
+ // Update local state immediately for responsive UI
+ setSelectedOrgId(organizationId);
+ // Then update the actual active organization
+ authClient.organization.setActive({
+ organizationId,
+ });
+ };
+
+ // Show placeholder when loading or no active organization
+ if (isPending || !activeOrganization) {
+ return (
+ <Select disabled>
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder={"Loading..."} />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="placeholder" disabled>
+ {"Loading organizations..."}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ );
+ }
+
+ return (
+ <Select
+ value={selectedOrgId || activeOrganization?.id}
+ onValueChange={handleValueChange}
+ disabled={!organizations || organizations.length === 0}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select an organization" />
+ </SelectTrigger>
+ <SelectContent>
+ {organizations?.map((org) => (
+ <SelectItem key={org.id} value={org.id}>
+ <div className="flex items-center">
+ <Building2 className="h-4 w-4 mr-2 text-muted-foreground" />
+ {org.name}
+ </div>
+ </SelectItem>
+ ))}
+ {(!organizations || organizations.length === 0) && (
+ <SelectItem value="no-org" disabled>
+ No organizations available
+ </SelectItem>
+ )}
+ </SelectContent>
+ </Select>
+ );
+}
diff --git a/client/src/components/SiteSettings/SiteSettings.tsx b/client/src/components/SiteSettings/SiteSettings.tsx
index 94f311af1..801df924c 100644
--- a/client/src/components/SiteSettings/SiteSettings.tsx
+++ b/client/src/components/SiteSettings/SiteSettings.tsx
@@ -33,18 +33,17 @@ import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
+ changeSiteBlockBots,
changeSiteDomain,
changeSitePublic,
changeSiteSalt,
- changeSiteBlockBots,
deleteSite,
- GetSitesResponse,
SiteResponse,
useGetSite,
- useGetSites,
+ useGetSitesFromOrg,
} from "@/api/admin/sites";
-import { ScriptBuilder } from "./ScriptBuilder";
import { useUserOrganizations } from "../../api/admin/organizations";
+import { ScriptBuilder } from "./ScriptBuilder";
export function SiteSettings({
siteId,
@@ -66,10 +65,10 @@ export function SiteSettingsInner({
siteMetadata,
trigger,
}: {
- siteMetadata: SiteResponse | GetSitesResponse[number];
+ siteMetadata: SiteResponse;
trigger?: React.ReactNode;
}) {
- const { refetch } = useGetSites();
+ const { refetch } = useGetSitesFromOrg(siteMetadata?.organizationId ?? "");
const { data: userOrganizationsData } = useUserOrganizations();
const disabled =
!userOrganizationsData?.[0]?.role ||
@@ -83,7 +82,7 @@ export function SiteSettingsInner({
const [isSalting, setIsSalting] = useState(siteMetadata.saltUserIds || false);
const [isChangingSalt, setIsChangingSalt] = useState(false);
const [isBlockingBots, setIsBlockingBots] = useState(
- siteMetadata.blockBots === undefined ? true : siteMetadata.blockBots
+ siteMetadata.blockBots || false
);
const [isChangingBlockBots, setIsChangingBlockBots] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
diff --git a/client/src/components/TopBar.tsx b/client/src/components/TopBar.tsx
index 71be378e2..119eb8e8d 100644
--- a/client/src/components/TopBar.tsx
+++ b/client/src/components/TopBar.tsx
@@ -40,8 +40,11 @@ export function TopBar() {
{session?.user.name}
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
- <Link href="/settings/account" passHref>
- <DropdownMenuItem>Settings</DropdownMenuItem>
+ <Link href="/account" passHref>
+ <DropdownMenuItem>Account</DropdownMenuItem>
+ </Link>
+ <Link href="/organization/members" passHref>
+ <DropdownMenuItem>Organization</DropdownMenuItem>
</Link>
<DropdownMenuItem
onClick={async () => {
diff --git a/client/src/app/settings/subscription/components/ExpiredTrialPlan.tsx b/client/src/components/subscription/ExpiredTrialPlan.tsx
similarity index 88%
rename from client/src/app/settings/subscription/components/ExpiredTrialPlan.tsx
rename to client/src/components/subscription/ExpiredTrialPlan.tsx
index 88ed76ac0..f47c84f4b 100644
--- a/client/src/app/settings/subscription/components/ExpiredTrialPlan.tsx
+++ b/client/src/components/subscription/ExpiredTrialPlan.tsx
@@ -1,11 +1,7 @@
import { AlertTriangle, ArrowRight } from "lucide-react";
import { useRouter } from "next/navigation";
-import {
- Alert,
- AlertDescription,
- AlertTitle,
-} from "../../../../components/ui/alert";
-import { Button } from "../../../../components/ui/button";
+import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
+import { Button } from "../ui/button";
import {
Card,
CardContent,
@@ -13,7 +9,7 @@ import {
CardFooter,
CardHeader,
CardTitle,
-} from "../../../../components/ui/card";
+} from "../ui/card";
interface ExpiredTrialPlanProps {
message?: string;
diff --git a/client/src/app/settings/subscription/components/FreePlan.tsx b/client/src/components/subscription/FreePlan.tsx
similarity index 84%
rename from client/src/app/settings/subscription/components/FreePlan.tsx
rename to client/src/components/subscription/FreePlan.tsx
index 9eea91f20..671a6711a 100644
--- a/client/src/app/settings/subscription/components/FreePlan.tsx
+++ b/client/src/components/subscription/FreePlan.tsx
@@ -1,12 +1,8 @@
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 { Alert, AlertDescription, AlertTitle } from "../ui/alert";
+import { Button } from "../ui/button";
import {
Card,
CardContent,
@@ -14,20 +10,20 @@ import {
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";
+} from "../ui/card";
+import { Progress } from "../ui/progress";
+import { DEFAULT_EVENT_LIMIT } from "../../lib/subscription/constants";
+import { useStripeSubscription } from "../../lib/subscription/useStripeSubscription";
+import { UsageChart } from "../UsageChart";
+import { authClient } from "@/lib/auth";
export function FreePlan() {
const { data: subscription } = useStripeSubscription();
- const { data: organizations } = useUserOrganizations();
+ const { data: activeOrg } = authClient.useActiveOrganization();
const router = useRouter();
- // Get the first organization (assuming user is part of one organization for now)
- const organizationId = organizations?.[0]?.id;
+ // Get the active organization ID
+ const organizationId = activeOrg?.id;
// Get last 30 days of data for the chart
const endDate = DateTime.now().toISODate();
diff --git a/client/src/app/settings/subscription/components/HelpSection.tsx b/client/src/components/subscription/HelpSection.tsx
similarity index 91%
rename from client/src/app/settings/subscription/components/HelpSection.tsx
rename to client/src/components/subscription/HelpSection.tsx
index 9b40e0a8a..104a81d15 100644
--- a/client/src/app/settings/subscription/components/HelpSection.tsx
+++ b/client/src/components/subscription/HelpSection.tsx
@@ -1,4 +1,4 @@
-import { Button } from "@/components/ui/button";
+import { Button } from "../ui/button";
interface HelpSectionProps {
router: {
diff --git a/client/src/app/settings/subscription/components/ProPlan.tsx b/client/src/components/subscription/ProPlan.tsx
similarity index 90%
rename from client/src/app/settings/subscription/components/ProPlan.tsx
rename to client/src/components/subscription/ProPlan.tsx
index df5415696..23437b64b 100644
--- a/client/src/app/settings/subscription/components/ProPlan.tsx
+++ b/client/src/components/subscription/ProPlan.tsx
@@ -2,16 +2,16 @@ 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";
+import { Alert } from "../ui/alert";
+import { Button } from "../ui/button";
+import { Card, CardContent } from "../ui/card";
+import { Progress } from "../ui/progress";
+import { BACKEND_URL } from "../../lib/const";
+import { getStripePrices } from "../../lib/stripe";
+import { formatDate } from "../../lib/subscription/planUtils";
+import { useStripeSubscription } from "../../lib/subscription/useStripeSubscription";
+import { UsageChart } from "../UsageChart";
+import { authClient } from "@/lib/auth";
export function ProPlan() {
const {
@@ -21,10 +21,10 @@ export function ProPlan() {
refetch,
} = useStripeSubscription();
- const { data: organizations } = useUserOrganizations();
+ const { data: activeOrg } = authClient.useActiveOrganization();
- // Get the first organization (assuming user is part of one organization for now)
- const organizationId = organizations?.[0]?.id;
+ // Get the active organization ID
+ const organizationId = activeOrg?.id;
// Get last 30 days of data for the chart
const endDate = DateTime.now().toISODate();
@@ -58,6 +58,11 @@ export function ProPlan() {
: null;
const createPortalSession = async (flowType?: string) => {
+ if (!organizationId) {
+ toast.error("No organization selected");
+ return;
+ }
+
setActionError(null);
setIsProcessing(true);
try {
@@ -71,6 +76,7 @@ export function ProPlan() {
credentials: "include",
body: JSON.stringify({
returnUrl: window.location.href,
+ organizationId,
flowType,
}),
}
diff --git a/client/src/app/settings/subscription/components/TrialPlan.tsx b/client/src/components/subscription/TrialPlan.tsx
similarity index 87%
rename from client/src/app/settings/subscription/components/TrialPlan.tsx
rename to client/src/components/subscription/TrialPlan.tsx
index e325528d6..dc384df9e 100644
--- a/client/src/app/settings/subscription/components/TrialPlan.tsx
+++ b/client/src/components/subscription/TrialPlan.tsx
@@ -1,11 +1,7 @@
import { ArrowRight, Clock } from "lucide-react";
import { useRouter } from "next/navigation";
-import {
- Alert,
- AlertDescription,
- AlertTitle,
-} from "../../../../components/ui/alert";
-import { Button } from "../../../../components/ui/button";
+import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
+import { Button } from "../ui/button";
import {
Card,
CardContent,
@@ -13,11 +9,11 @@ import {
CardFooter,
CardHeader,
CardTitle,
-} from "../../../../components/ui/card";
-import { Progress } from "../../../../components/ui/progress";
-import { TRIAL_EVENT_LIMIT } from "../utils/constants";
-import { formatDate } from "../utils/planUtils";
-import { useStripeSubscription } from "../utils/useStripeSubscription";
+} from "../ui/card";
+import { Progress } from "../ui/progress";
+import { TRIAL_EVENT_LIMIT } from "../../lib/subscription/constants";
+import { formatDate } from "../../lib/subscription/planUtils";
+import { useStripeSubscription } from "../../lib/subscription/useStripeSubscription";
export function TrialPlan() {
const {
diff --git a/client/src/app/settings/subscription/utils/constants.ts b/client/src/lib/subscription/constants.ts
similarity index 100%
rename from client/src/app/settings/subscription/utils/constants.ts
rename to client/src/lib/subscription/constants.ts
diff --git a/client/src/app/settings/subscription/utils/planUtils.tsx b/client/src/lib/subscription/planUtils.tsx
similarity index 100%
rename from client/src/app/settings/subscription/utils/planUtils.tsx
rename to client/src/lib/subscription/planUtils.tsx
diff --git a/client/src/app/settings/subscription/utils/useStripeSubscription.ts b/client/src/lib/subscription/useStripeSubscription.ts
similarity index 65%
rename from client/src/app/settings/subscription/utils/useStripeSubscription.ts
rename to client/src/lib/subscription/useStripeSubscription.ts
index 2daee5894..bd7b319ee 100644
--- a/client/src/app/settings/subscription/utils/useStripeSubscription.ts
+++ b/client/src/lib/subscription/useStripeSubscription.ts
@@ -1,5 +1,6 @@
import { useQuery } from "@tanstack/react-query";
-import { BACKEND_URL } from "../../../../lib/const";
+import { authClient } from "@/lib/auth";
+import { BACKEND_URL } from "../const";
interface SubscriptionData {
id: string;
@@ -17,14 +18,23 @@ interface SubscriptionData {
}
export function useStripeSubscription() {
+ const { data: activeOrg } = authClient.useActiveOrganization();
+
const fetchSubscription = async () => {
- const response = await fetch(`${BACKEND_URL}/stripe/subscription`, {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- },
- credentials: "include",
- });
+ if (!activeOrg) {
+ return null;
+ }
+
+ const response = await fetch(
+ `${BACKEND_URL}/stripe/subscription?organizationId=${activeOrg.id}`,
+ {
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ credentials: "include",
+ }
+ );
if (!response.ok) {
if (response.status === 401) {
@@ -39,10 +49,11 @@ export function useStripeSubscription() {
};
const { data, isLoading, error, refetch } = useQuery<SubscriptionData>({
- queryKey: ["stripe-subscription"],
+ queryKey: ["stripe-subscription", activeOrg?.id],
queryFn: fetchSubscription,
staleTime: 5 * 60 * 1000, // 5 minutes
retry: false,
+ enabled: !!activeOrg,
});
return { data, isLoading, error, refetch };
diff --git a/client/src/middleware.ts b/client/src/middleware.ts
index 3545d5a92..1e5778f1a 100644
--- a/client/src/middleware.ts
+++ b/client/src/middleware.ts
@@ -38,6 +38,8 @@ export async function middleware(request: NextRequest) {
"reset-password",
"auth",
"admin",
+ "organization",
+ "account",
"_next",
"api",
];
diff --git a/server/src/api/sites/getSite.ts b/server/src/api/sites/getSite.ts
index b79cc6190..9ce9c0603 100644
--- a/server/src/api/sites/getSite.ts
+++ b/server/src/api/sites/getSite.ts
@@ -46,8 +46,10 @@ export async function getSite(
createdAt: site.createdAt,
updatedAt: site.updatedAt,
createdBy: site.createdBy,
+ organizationId: site.organizationId,
saltUserIds: site.saltUserIds,
public: site.public,
+ blockBots: site.blockBots,
isOwner: isOwner,
});
} catch (error) {
diff --git a/server/src/api/sites/getSites.ts b/server/src/api/sites/getSites.ts
index fa5d7dcbb..c1bc82beb 100644
--- a/server/src/api/sites/getSites.ts
+++ b/server/src/api/sites/getSites.ts
@@ -88,7 +88,7 @@ export async function getSites(req: FastifyRequest, reply: FastifyReply) {
}
}
- const subscription = await getSubscriptionInner(ownerId);
+ const subscription = await getSubscriptionInner(site.organizationId);
const monthlyEventCount = subscription?.monthlyEventCount || 0;
const eventLimit = subscription?.eventLimit || DEFAULT_EVENT_LIMIT;
diff --git a/server/src/api/sites/getSitesFromOrg.ts b/server/src/api/sites/getSitesFromOrg.ts
new file mode 100644
index 000000000..2afbe09ac
--- /dev/null
+++ b/server/src/api/sites/getSitesFromOrg.ts
@@ -0,0 +1,153 @@
+import { eq, and } from "drizzle-orm";
+import { FastifyRequest, FastifyReply } from "fastify";
+import clickhouse from "../../db/clickhouse/clickhouse.js";
+import { db } from "../../db/postgres/postgres.js";
+import { sites, member, organization } from "../../db/postgres/schema.js";
+import { getSessionFromReq, getUserGodMode } from "../../lib/auth-utils.js";
+import { IS_CLOUD, DEFAULT_EVENT_LIMIT } from "../../lib/const.js";
+import { processResults } from "../analytics/utils.js";
+import { getSubscriptionInner } from "../stripe/getSubscription.js";
+
+export async function getSitesFromOrg(
+ req: FastifyRequest<{
+ Params: {
+ organizationId: string;
+ };
+ }>,
+ res: FastifyReply
+) {
+ try {
+ const { organizationId } = req.params;
+ const session = await getSessionFromReq(req);
+ const userId = session?.user.id;
+
+ if (!userId) {
+ return res.status(401).send({ error: "Unauthorized" });
+ }
+
+ // Check if user has god mode
+ const godMode = await getUserGodMode(req);
+
+ // If not god mode, verify user is a member of the organization
+ if (!godMode) {
+ const memberCheck = await db
+ .select()
+ .from(member)
+ .where(
+ and(
+ eq(member.organizationId, organizationId),
+ eq(member.userId, userId)
+ )
+ )
+ .limit(1);
+
+ if (memberCheck.length === 0) {
+ return res
+ .status(403)
+ .send({ error: "Access denied to this organization" });
+ }
+ }
+
+ // Get sites for the organization
+ const sitesData = await db
+ .select()
+ .from(sites)
+ .where(eq(sites.organizationId, organizationId));
+
+ // Query session counts for the sites
+ const sessionCountMap = new Map<number, number>();
+
+ if (sitesData.length > 0) {
+ const siteIds = sitesData.map((site) => site.siteId);
+
+ const sessionCountsResult = await clickhouse.query({
+ query: `
+ SELECT
+ site_id,
+ uniqExact(session_id) AS total_sessions
+ FROM events
+ WHERE timestamp >= now() - INTERVAL 1 DAY
+ AND site_id IN (${siteIds.join(",")})
+ GROUP BY site_id
+ `,
+ format: "JSONEachRow",
+ });
+
+ const sessionCounts = await processResults(sessionCountsResult);
+
+ if (Array.isArray(sessionCounts)) {
+ sessionCounts.forEach((row: any) => {
+ if (
+ row &&
+ typeof row.site_id === "number" &&
+ typeof row.total_sessions === "number"
+ ) {
+ sessionCountMap.set(Number(row.site_id), row.total_sessions);
+ }
+ });
+ }
+ }
+
+ // Get organization owner for subscription info
+ let ownerId = "";
+ const orgOwnerResult = await db
+ .select({ userId: member.userId })
+ .from(member)
+ .where(
+ and(eq(member.organizationId, organizationId), eq(member.role, "owner"))
+ )
+ .limit(1);
+
+ if (orgOwnerResult.length > 0) {
+ ownerId = orgOwnerResult[0].userId;
+ }
+
+ // Get subscription info
+ let subscription = null;
+ let monthlyEventCount = 0;
+ let eventLimit = DEFAULT_EVENT_LIMIT;
+
+ if (!IS_CLOUD) {
+ // Self-hosted version has unlimited events
+ eventLimit = Infinity;
+ } else if (ownerId) {
+ subscription = await getSubscriptionInner(organizationId);
+ monthlyEventCount = subscription?.monthlyEventCount || 0;
+ eventLimit = subscription?.eventLimit || DEFAULT_EVENT_LIMIT;
+ }
+
+ // Get organization info
+ const orgInfo = await db
+ .select()
+ .from(organization)
+ .where(eq(organization.id, organizationId))
+ .limit(1);
+
+ // Enhance sites data with session counts and subscription info
+ const enhancedSitesData = sitesData.map((site) => ({
+ ...site,
+ sessionsLast24Hours: sessionCountMap.get(site.siteId) || 0,
+ isOwner: userId === ownerId,
+ }));
+
+ // Sort by sessions descending
+ enhancedSitesData.sort(
+ (a, b) => b.sessionsLast24Hours - a.sessionsLast24Hours
+ );
+
+ return res.status(200).send({
+ organization: orgInfo[0] || null,
+ sites: enhancedSitesData,
+ subscription: {
+ monthlyEventCount,
+ eventLimit,
+ overMonthlyLimit: monthlyEventCount > eventLimit,
+ planName: subscription?.planName || "free",
+ status: subscription?.status || "free",
+ },
+ });
+ } catch (err) {
+ console.error("Error in getSitesFromOrg:", err);
+ return res.status(500).send({ error: String(err) });
+ }
+}
diff --git a/server/src/api/stripe/createCheckoutSession.ts b/server/src/api/stripe/createCheckoutSession.ts
index 03d7a113c..3374ece9a 100644
--- a/server/src/api/stripe/createCheckoutSession.ts
+++ b/server/src/api/stripe/createCheckoutSession.ts
@@ -1,71 +1,112 @@
-import { eq } from "drizzle-orm";
+import { eq, and } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import Stripe from "stripe";
import { db } from "../../db/postgres/postgres.js";
-import { user as userSchema } from "../../db/postgres/schema.js";
+import {
+ organization,
+ user as userSchema,
+ member,
+} from "../../db/postgres/schema.js";
import { stripe } from "../../lib/stripe.js";
interface CheckoutRequestBody {
priceId: string;
successUrl: string;
cancelUrl: string;
+ organizationId: string;
}
export async function createCheckoutSession(
request: FastifyRequest<{ Body: CheckoutRequestBody }>,
reply: FastifyReply
) {
- const { priceId, successUrl, cancelUrl } = request.body;
+ const { priceId, successUrl, cancelUrl, organizationId } = request.body;
const userId = request.user?.id;
if (!userId) {
return reply.status(401).send({ error: "Unauthorized" });
}
- if (!priceId || !successUrl || !cancelUrl) {
+ if (!priceId || !successUrl || !cancelUrl || !organizationId) {
return reply.status(400).send({
- error: "Missing required parameters: priceId, successUrl, cancelUrl",
+ error:
+ "Missing required parameters: priceId, successUrl, cancelUrl, organizationId",
});
}
try {
- // 1. Find the user in your database
- const userResult = await db
+ // 1. Verify user has permission to manage billing for this organization
+ const memberResult = await db
.select({
- id: userSchema.id,
- email: userSchema.email,
- stripeCustomerId: userSchema.stripeCustomerId,
+ role: member.role,
})
- .from(userSchema)
- .where(eq(userSchema.id, userId))
+ .from(member)
+ .where(
+ and(
+ eq(member.userId, userId),
+ eq(member.organizationId, organizationId)
+ )
+ )
.limit(1);
+ if (!memberResult.length || memberResult[0].role !== "owner") {
+ return reply.status(403).send({
+ error: "Only organization owners can manage billing",
+ });
+ }
+
+ // 2. Get user and organization details
+ const [userResult, orgResult] = await Promise.all([
+ db
+ .select({
+ id: userSchema.id,
+ email: userSchema.email,
+ })
+ .from(userSchema)
+ .where(eq(userSchema.id, userId))
+ .limit(1),
+ db
+ .select({
+ id: organization.id,
+ name: organization.name,
+ stripeCustomerId: organization.stripeCustomerId,
+ })
+ .from(organization)
+ .where(eq(organization.id, organizationId))
+ .limit(1),
+ ]);
+
const user = userResult[0];
+ const org = orgResult[0];
- if (!user) {
- return reply.status(404).send({ error: "User not found" });
+ if (!user || !org) {
+ return reply
+ .status(404)
+ .send({ error: "User or organization not found" });
}
- let stripeCustomerId = user.stripeCustomerId;
+ let stripeCustomerId = org.stripeCustomerId;
- // 2. If the user doesn't have a Stripe Customer ID, create one
+ // 3. If the organization doesn't have a Stripe Customer ID, create one
if (!stripeCustomerId) {
const customer = await (stripe as Stripe).customers.create({
email: user.email,
+ name: org.name,
metadata: {
- userId: user.id, // Link Stripe customer to your internal user ID
+ organizationId: org.id,
+ createdByUserId: userId, // For audit trail
},
});
stripeCustomerId = customer.id;
- // 3. Update the user record in your database with the new Stripe Customer ID
+ // 4. Update the organization with the new Stripe Customer ID
await db
- .update(userSchema)
- .set({ stripeCustomerId: stripeCustomerId })
- .where(eq(userSchema.id, userId));
+ .update(organization)
+ .set({ stripeCustomerId })
+ .where(eq(organization.id, organizationId));
}
- // 4. Create a Stripe Checkout Session
+ // 5. Create a Stripe Checkout Session
const session = await (stripe as Stripe).checkout.sessions.create({
payment_method_types: ["card"],
mode: "subscription",
@@ -76,8 +117,12 @@ export async function createCheckoutSession(
quantity: 1,
},
],
- success_url: successUrl, // The user will be redirected here on success
- cancel_url: cancelUrl, // The user will be redirected here if they cancel
+ success_url: successUrl,
+ cancel_url: cancelUrl,
+ // Store organization ID in metadata for webhook processing
+ metadata: {
+ organizationId: organizationId,
+ },
// Allow promotion codes
allow_promotion_codes: true,
// Enable automatic tax calculation if configured in Stripe Tax settings
@@ -88,7 +133,7 @@ export async function createCheckoutSession(
},
});
- // 5. Return the Checkout Session URL
+ // 6. Return the Checkout Session URL
return reply.send({ checkoutUrl: session.url });
} catch (error: any) {
console.error("Stripe Checkout Session Error:", error);
diff --git a/server/src/api/stripe/createPortalSession.ts b/server/src/api/stripe/createPortalSession.ts
index e3a40cd36..5576e4324 100644
--- a/server/src/api/stripe/createPortalSession.ts
+++ b/server/src/api/stripe/createPortalSession.ts
@@ -1,12 +1,13 @@
import { FastifyReply, FastifyRequest } from "fastify";
import { stripe } from "../../lib/stripe.js";
import { db } from "../../db/postgres/postgres.js";
-import { user as userSchema } from "../../db/postgres/schema.js";
-import { eq } from "drizzle-orm";
+import { organization, member } from "../../db/postgres/schema.js";
+import { eq, and } from "drizzle-orm";
import Stripe from "stripe";
interface PortalRequestBody {
returnUrl: string;
+ organizationId: string;
flowType?:
| "subscription_update"
| "subscription_cancel"
@@ -17,40 +18,60 @@ export async function createPortalSession(
request: FastifyRequest<{ Body: PortalRequestBody }>,
reply: FastifyReply
) {
- const { returnUrl, flowType } = request.body;
+ const { returnUrl, organizationId, flowType } = request.body;
const userId = request.user?.id;
if (!userId) {
return reply.status(401).send({ error: "Unauthorized" });
}
- if (!returnUrl) {
- return reply
- .status(400)
- .send({ error: "Missing required parameter: returnUrl" });
+ if (!returnUrl || !organizationId) {
+ return reply.status(400).send({
+ error: "Missing required parameters: returnUrl, organizationId",
+ });
}
try {
- // 1. Find the user in your database
- const userResult = await db
+ // 1. Verify user has permission to manage billing for this organization
+ const memberResult = await db
+ .select({
+ role: member.role,
+ })
+ .from(member)
+ .where(
+ and(
+ eq(member.userId, userId),
+ eq(member.organizationId, organizationId)
+ )
+ )
+ .limit(1);
+
+ if (!memberResult.length || memberResult[0].role !== "owner") {
+ return reply.status(403).send({
+ error: "Only organization owners can manage billing",
+ });
+ }
+
+ // 2. Find the organization and its Stripe customer ID
+ const orgResult = await db
.select({
- stripeCustomerId: userSchema.stripeCustomerId,
+ stripeCustomerId: organization.stripeCustomerId,
})
- .from(userSchema)
- .where(eq(userSchema.id, userId))
+ .from(organization)
+ .where(eq(organization.id, organizationId))
.limit(1);
- const user = userResult[0];
+ const org = orgResult[0];
- if (!user || !user.stripeCustomerId) {
+ if (!org || !org.stripeCustomerId) {
return reply
.status(404)
- .send({ error: "User or Stripe customer ID not found" });
+ .send({ error: "Organization or Stripe customer ID not found" });
}
- // 2. Create a Stripe Billing Portal Session, with optional direct flow
+ // 3. Create a Stripe Billing Portal Session, with optional direct flow
const sessionConfig: Stripe.BillingPortal.SessionCreateParams = {
- customer: user.stripeCustomerId,
+ customer: org.stripeCustomerId,
return_url: returnUrl, // The user will be redirected here after managing their billing
};
@@ -59,7 +80,7 @@ export async function createPortalSession(
if (flowType === "subscription_update") {
// For subscription_update flow, we need to fetch the subscription ID first
const subscriptions = await (stripe as Stripe).subscriptions.list({
- customer: user.stripeCustomerId,
+ customer: org.stripeCustomerId,
status: "active",
limit: 1,
});
@@ -81,7 +102,7 @@ export async function createPortalSession(
} else if (flowType === "subscription_cancel") {
// For subscription_cancel flow, we need to fetch the subscription ID first
const subscriptions = await (stripe as Stripe).subscriptions.list({
- customer: user.stripeCustomerId,
+ customer: org.stripeCustomerId,
status: "active",
limit: 1,
});
@@ -111,7 +132,7 @@ export async function createPortalSession(
stripe as Stripe
).billingPortal.sessions.create(sessionConfig);
- // 3. Return the Billing Portal Session URL
+ // 4. Return the Billing Portal Session URL
return reply.send({ portalUrl: portalSession.url });
} catch (error: any) {
console.error("Stripe Portal Session Error:", error);
diff --git a/server/src/api/stripe/getSubscription.ts b/server/src/api/stripe/getSubscription.ts
index 19898c919..660432773 100644
--- a/server/src/api/stripe/getSubscription.ts
+++ b/server/src/api/stripe/getSubscription.ts
@@ -2,7 +2,7 @@ import { eq } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import Stripe from "stripe";
import { db } from "../../db/postgres/postgres.js";
-import { user as userSchema } from "../../db/postgres/schema.js";
+import { organization } from "../../db/postgres/schema.js";
import {
DEFAULT_EVENT_LIMIT,
getStripePrices,
@@ -28,31 +28,31 @@ 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
+export async function getSubscriptionInner(organizationId: string) {
+ // 1. Find the organization and their Stripe Customer ID
+ const orgResult = await db
.select({
- stripeCustomerId: userSchema.stripeCustomerId,
- monthlyEventCount: userSchema.monthlyEventCount,
- createdAt: userSchema.createdAt,
+ stripeCustomerId: organization.stripeCustomerId,
+ monthlyEventCount: organization.monthlyEventCount,
+ createdAt: organization.createdAt,
})
- .from(userSchema)
- .where(eq(userSchema.id, userId))
+ .from(organization)
+ .where(eq(organization.id, organizationId))
.limit(1);
- const user = userResult[0];
+ const org = orgResult[0];
- if (!user) {
+ if (!org) {
return null;
}
- // Check if user has an active Stripe subscription
- if (user.stripeCustomerId) {
+ // Check if organization has an active Stripe subscription
+ if (org.stripeCustomerId) {
// 2. List active subscriptions for the customer from Stripe
const subscriptions = await (stripe as Stripe).subscriptions.list({
- customer: user.stripeCustomerId,
+ customer: org.stripeCustomerId,
status: "active", // Only fetch active subscriptions
- limit: 1, // Users should only have one active subscription in this model
+ limit: 1, // Organizations should only have one active subscription
expand: ["data.plan.product"], // Expand to get product details if needed
});
@@ -84,7 +84,7 @@ export async function getSubscriptionInner(userId: string) {
),
cancelAtPeriodEnd: subscription.cancel_at_period_end,
eventLimit: 0, // Unknown limit
- monthlyEventCount: user.monthlyEventCount,
+ monthlyEventCount: org.monthlyEventCount || 0,
interval: subscriptionItem.price.recurring?.interval ?? "unknown",
};
}
@@ -100,7 +100,7 @@ export async function getSubscriptionInner(userId: string) {
currentPeriodEnd: new Date(subscriptionItem.current_period_end * 1000),
cancelAtPeriodEnd: subscription.cancel_at_period_end,
eventLimit: planDetails.limits.events,
- monthlyEventCount: user.monthlyEventCount,
+ monthlyEventCount: org.monthlyEventCount || 0,
interval: subscriptionItem.price.recurring?.interval ?? "unknown",
};
@@ -108,33 +108,7 @@ 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)
- // ),
- // };
- // }
-
+ // If we get here, the organization has no active paid subscription
return {
id: null,
planName: "free",
@@ -142,23 +116,32 @@ export async function getSubscriptionInner(userId: string) {
currentPeriodEnd: getStartOfNextMonth(),
currentPeriodStart: getStartOfMonth(),
eventLimit: DEFAULT_EVENT_LIMIT,
- monthlyEventCount: user.monthlyEventCount,
+ monthlyEventCount: org.monthlyEventCount || 0,
trialDaysRemaining: 0,
};
}
export async function getSubscription(
- request: FastifyRequest,
+ request: FastifyRequest<{
+ Querystring: {
+ organizationId: string;
+ };
+ }>,
reply: FastifyReply
) {
const userId = request.user?.id;
+ const { organizationId } = request.query;
if (!userId) {
return reply.status(401).send({ error: "Unauthorized" });
}
+ if (!organizationId) {
+ return reply.status(400).send({ error: "Organization ID is required" });
+ }
+
try {
- const responseData = await getSubscriptionInner(userId);
+ const responseData = await getSubscriptionInner(organizationId);
return reply.send(responseData);
} catch (error: any) {
console.error("Get Subscription Error:", error);
diff --git a/server/src/api/stripe/webhook.ts b/server/src/api/stripe/webhook.ts
index eaef351e7..8f65b2448 100644
--- a/server/src/api/stripe/webhook.ts
+++ b/server/src/api/stripe/webhook.ts
@@ -1,7 +1,7 @@
import { FastifyReply, FastifyRequest } from "fastify";
import { stripe } from "../../lib/stripe.js";
import { db } from "../../db/postgres/postgres.js";
-import { user as userSchema } from "../../db/postgres/schema.js";
+import { organization } from "../../db/postgres/schema.js";
import { eq } from "drizzle-orm";
import Stripe from "stripe";
import dotenv from "dotenv";
@@ -48,60 +48,41 @@ export async function handleWebhook(
// If the checkout session was for a subscription
if (session.mode === "subscription" && session.customer) {
const stripeCustomerId = session.customer as string;
- const userId = session.metadata?.userId; // Retrieve userId from metadata if you set it
+ const organizationId = session.metadata?.organizationId; // Retrieve organizationId from metadata
- if (stripeCustomerId) {
+ if (stripeCustomerId && organizationId) {
try {
- // Check if user already has this customer ID
- const existingUser = await db
- .select({ id: userSchema.id })
- .from(userSchema)
- .where(eq(userSchema.stripeCustomerId, stripeCustomerId))
+ // Check if organization already has this customer ID
+ const existingOrg = await db
+ .select({ id: organization.id })
+ .from(organization)
+ .where(eq(organization.stripeCustomerId, stripeCustomerId))
.limit(1);
- // If no user has this ID, update the user linked via metadata (if available)
- // Or update based on email if metadata is not reliable
- if (existingUser.length === 0) {
- let userToUpdateId: string | null = null;
-
- if (userId) {
- userToUpdateId = userId;
- } else if (session.customer_details?.email) {
- // Fallback: Find user by email (ensure email is unique in your DB)
- const userByEmail = await db
- .select({ id: userSchema.id })
- .from(userSchema)
- .where(eq(userSchema.email, session.customer_details.email))
- .limit(1);
- if (userByEmail.length > 0) {
- userToUpdateId = userByEmail[0].id;
- }
- }
-
- if (userToUpdateId) {
- console.log(
- `Updating user ${userToUpdateId} with Stripe customer ID ${stripeCustomerId}`
- );
- await db
- .update(userSchema)
- .set({ stripeCustomerId: stripeCustomerId })
- .where(eq(userSchema.id, userToUpdateId));
- } else {
- console.error(
- `Could not find user to associate with Stripe customer ID ${stripeCustomerId} from checkout session ${session.id}`
- );
- }
+ // If the organization doesn't have the customer ID yet, update it
+ if (existingOrg.length === 0) {
+ console.log(
+ `Updating organization ${organizationId} with Stripe customer ID ${stripeCustomerId}`
+ );
+ await db
+ .update(organization)
+ .set({ stripeCustomerId: stripeCustomerId })
+ .where(eq(organization.id, organizationId));
} else {
console.log(
- `User ${existingUser[0].id} already has Stripe customer ID ${stripeCustomerId}`
+ `Organization ${existingOrg[0].id} already has Stripe customer ID ${stripeCustomerId}`
);
}
} catch (dbError: any) {
console.error(
- `Database error updating user with Stripe customer ID: ${dbError.message}`
+ `Database error updating organization with Stripe customer ID: ${dbError.message}`
);
// Decide if you should still return 200 to Stripe or signal an error
}
+ } else {
+ console.error(
+ `Missing required metadata in checkout session ${session.id}. Customer ID: ${stripeCustomerId}, Organization ID: ${organizationId}`
+ );
}
}
break;
diff --git a/server/src/cron/monthly-usage-checker.ts b/server/src/cron/monthly-usage-checker.ts
index c09745333..4a60ddc08 100644
--- a/server/src/cron/monthly-usage-checker.ts
+++ b/server/src/cron/monthly-usage-checker.ts
@@ -1,10 +1,10 @@
-import { and, eq, inArray } from "drizzle-orm";
+import { eq, inArray, isNotNull } from "drizzle-orm";
import { DateTime } from "luxon";
import Stripe from "stripe";
import { processResults } from "../api/analytics/utils.js";
import { clickhouse } from "../db/clickhouse/clickhouse.js";
import { db } from "../db/postgres/postgres.js";
-import { member, sites, user } from "../db/postgres/schema.js";
+import { organization, sites } from "../db/postgres/schema.js";
import {
getStripePrices,
StripePlan,
@@ -23,47 +23,39 @@ function getStartOfMonth(): string {
}
/**
- * Gets all site IDs for organizations owned by a user
+ * Gets all site IDs for an organization
*/
-async function getSiteIdsForUser(userId: string): Promise<number[]> {
+async function getSiteIdsForOrganization(
+ organizationId: string
+): Promise<number[]> {
try {
- // Find the organizations this user is an owner of
- const userOrgs = await db
- .select({ organizationId: member.organizationId })
- .from(member)
- .where(and(eq(member.userId, userId), eq(member.role, "owner")));
-
- if (!userOrgs.length) {
- return [];
- }
-
- const orgIds = userOrgs.map((org) => org.organizationId);
-
- // Get all sites for these organizations
const siteRecords = await db
.select({ siteId: sites.siteId })
.from(sites)
- .where(inArray(sites.organizationId, orgIds));
+ .where(eq(sites.organizationId, organizationId));
return siteRecords.map((record) => record.siteId);
} catch (error) {
- console.error(`Error getting sites for user ${userId}:`, error);
+ console.error(
+ `Error getting sites for organization ${organizationId}:`,
+ error
+ );
return [];
}
}
/**
- * Gets event limit and billing period start date for a user based on their Stripe subscription.
- * Fetches directly from Stripe if the user has a stripeCustomerId.
+ * Gets event limit and billing period start date for an organization based on their Stripe subscription.
+ * Fetches directly from Stripe if the organization has a stripeCustomerId.
* @returns [eventLimit, periodStartDate]
*/
-async function getUserSubscriptionInfo(userData: {
+async function getOrganizationSubscriptionInfo(orgData: {
id: string;
stripeCustomerId: string | null;
createdAt: string;
- email: string;
+ name: string;
}): Promise<[number, string | null]> {
- if (!userData.stripeCustomerId) {
+ if (!orgData.stripeCustomerId) {
// No Stripe customer ID, use default limit and start of current month
return [DEFAULT_EVENT_LIMIT, getStartOfMonth()];
}
@@ -71,7 +63,7 @@ async function getUserSubscriptionInfo(userData: {
try {
// Fetch active subscriptions for the customer from Stripe
const subscriptions = await (stripe as Stripe).subscriptions.list({
- customer: userData.stripeCustomerId,
+ customer: orgData.stripeCustomerId,
status: "active",
limit: 1,
});
@@ -87,7 +79,7 @@ async function getUserSubscriptionInfo(userData: {
if (!priceId) {
console.error(
- `Subscription item price ID not found for user ${userData.id}, sub ${subscription.id}`
+ `Subscription item price ID not found for organization ${orgData.id}, sub ${subscription.id}`
);
return [DEFAULT_EVENT_LIMIT, getStartOfMonth()];
}
@@ -120,11 +112,11 @@ async function getUserSubscriptionInfo(userData: {
if (subscriptionStartDate >= currentMonth) {
periodStart = subscriptionStartDate.toISODate() as string;
console.log(
- `[Monthly Usage Checker] User ${userData.email} subscribed during current month on ${periodStart}. Using subscription start date for counting.`
+ `[Monthly Usage Checker] Organization ${orgData.name} subscribed during current month on ${periodStart}. Using subscription start date for counting.`
);
} else {
console.log(
- `[Monthly Usage Checker] User ${userData.email} subscription started before current month. Using month start for counting.`
+ `[Monthly Usage Checker] Organization ${orgData.name} subscription started before current month. Using month start for counting.`
);
}
}
@@ -132,13 +124,13 @@ async function getUserSubscriptionInfo(userData: {
// Include subscription info for logging purposes
const interval = subscriptionItem.price.recurring?.interval || "unknown";
console.log(
- `[Monthly Usage Checker] User ${userData.email} has a ${interval} subscription.`
+ `[Monthly Usage Checker] Organization ${orgData.name} has a ${interval} subscription.`
);
return [eventLimit, periodStart];
} catch (error: any) {
console.error(
- `Error fetching Stripe subscription info for user ${userData.email}:`,
+ `Error fetching Stripe subscription info for organization ${orgData.name}:`,
error
);
// Fallback to default limit and current month start on Stripe API error
@@ -182,37 +174,37 @@ async function getMonthlyPageviews(
}
/**
- * Updates monthly event usage for all users
+ * Updates monthly event usage for all organizations
*/
export async function updateUsersMonthlyUsage() {
console.log(
- "[Monthly Usage Checker] Starting check of monthly event usage..."
+ "[Monthly Usage Checker] Starting check of monthly event usage for organizations..."
);
try {
- // Get all users with their Stripe customer ID
- const users = await db
+ // Get all organizations (both with and without Stripe customer IDs)
+ const organizations = await db
.select({
- id: user.id,
- email: user.email,
- stripeCustomerId: user.stripeCustomerId,
- createdAt: user.createdAt,
+ id: organization.id,
+ name: organization.name,
+ stripeCustomerId: organization.stripeCustomerId,
+ createdAt: organization.createdAt,
})
- .from(user);
+ .from(organization);
- for (const userData of users) {
+ for (const orgData of organizations) {
try {
- // Get site IDs for organizations owned by this user
- const siteIds = await getSiteIdsForUser(userData.id);
+ // Get site IDs for this organization
+ const siteIds = await getSiteIdsForOrganization(orgData.id);
- // If user has no sites, continue to next user
+ // If organization has no sites, continue to next organization
if (!siteIds.length) {
continue;
}
- // Get user's subscription information (limit and period start)
+ // Get organization's subscription information (limit and period start)
const [eventLimit, periodStart] =
- await getUserSubscriptionInfo(userData);
+ await getOrganizationSubscriptionInfo(orgData);
// Get monthly pageview count from ClickHouse using the billing period start date
const pageviewCount = await getMonthlyPageviews(siteIds, periodStart);
@@ -220,22 +212,22 @@ export async function updateUsersMonthlyUsage() {
// Check if over limit and update global set
const isOverLimit = pageviewCount > eventLimit;
- // Update user's monthlyEventCount and overMonthlyLimit fields
+ // Update organization's monthlyEventCount and overMonthlyLimit fields
await db
- .update(user)
+ .update(organization)
.set({
monthlyEventCount: pageviewCount,
overMonthlyLimit: isOverLimit,
})
- .where(eq(user.id, userData.id));
+ .where(eq(organization.id, orgData.id));
- // If over the limit, add all this user's sites to the global set
+ // If over the limit, add all this organization's sites to the global set
if (isOverLimit) {
for (const siteId of siteIds) {
sitesOverLimit.add(siteId);
}
console.log(
- `[Monthly Usage Checker] User ${userData.email} is over limit. Added ${siteIds.length} sites to blocked list.`
+ `[Monthly Usage Checker] Organization ${orgData.name} is over limit. Added ${siteIds.length} sites to blocked list.`
);
} else {
for (const siteId of siteIds) {
@@ -249,13 +241,13 @@ export async function updateUsersMonthlyUsage() {
: "this month";
console.log(
- `[Monthly Usage Checker] Updated user ${
- userData.email
+ `[Monthly Usage Checker] Updated organization ${
+ orgData.name
}: ${pageviewCount.toLocaleString()} events, limit ${eventLimit.toLocaleString()}, ${periodInfo}`
);
} catch (error) {
console.error(
- `[Monthly Usage Checker] Error processing user ${userData.id}:`,
+ `[Monthly Usage Checker] Error processing organization ${orgData.id}:`,
error
);
}
diff --git a/server/src/db/postgres/migration.ts b/server/src/db/postgres/migration.ts
new file mode 100644
index 000000000..4a236ef64
--- /dev/null
+++ b/server/src/db/postgres/migration.ts
@@ -0,0 +1,217 @@
+import { db } from "./postgres.js";
+import { user, organization, member } from "./schema.js";
+import { eq, and, isNotNull } from "drizzle-orm";
+
+export async function migrateUserSubscriptionsToOrganizations() {
+ console.log(
+ "πŸš€ Starting migration: User subscriptions β†’ Organization subscriptions"
+ );
+
+ try {
+ // Step 1: Find all users with Stripe customer IDs
+ const subscribedUsers = await db
+ .select({
+ userId: user.id,
+ email: user.email,
+ stripeCustomerId: user.stripeCustomerId,
+ monthlyEventCount: user.monthlyEventCount,
+ overMonthlyLimit: user.overMonthlyLimit,
+ })
+ .from(user)
+ .where(isNotNull(user.stripeCustomerId));
+
+ console.log(
+ `πŸ“Š Found ${subscribedUsers.length} users with Stripe subscriptions`
+ );
+
+ if (subscribedUsers.length === 0) {
+ console.log("βœ… No subscriptions to migrate");
+ return;
+ }
+
+ // Step 2: For each subscribed user, find their owned organizations
+ let migratedCount = 0;
+ let skippedCount = 0;
+
+ for (const subscribedUser of subscribedUsers) {
+ console.log(
+ `\nπŸ‘€ Processing user: ${subscribedUser.email} (${subscribedUser.stripeCustomerId})`
+ );
+
+ // Find organizations where this user is an owner
+ const ownedOrganizations = await db
+ .select({
+ organizationId: member.organizationId,
+ organizationName: organization.name,
+ organizationSlug: organization.slug,
+ currentStripeCustomerId: organization.stripeCustomerId,
+ })
+ .from(member)
+ .innerJoin(organization, eq(organization.id, member.organizationId))
+ .where(
+ and(
+ eq(member.userId, subscribedUser.userId),
+ eq(member.role, "owner")
+ )
+ );
+
+ if (ownedOrganizations.length === 0) {
+ console.log(
+ ` ⚠️ User has subscription but owns no organizations - skipping`
+ );
+ skippedCount++;
+ continue;
+ }
+
+ if (ownedOrganizations.length > 1) {
+ console.log(
+ ` ⚠️ User owns ${ownedOrganizations.length} organizations - migrating to first one only`
+ );
+ }
+
+ const targetOrg = ownedOrganizations[0];
+
+ // Check if organization already has a Stripe customer ID
+ if (targetOrg.currentStripeCustomerId) {
+ console.log(
+ ` ⚠️ Organization "${targetOrg.organizationName}" already has Stripe customer ID: ${targetOrg.currentStripeCustomerId} - skipping`
+ );
+ skippedCount++;
+ continue;
+ }
+
+ // Step 3: Migrate billing data to organization
+ await db
+ .update(organization)
+ .set({
+ stripeCustomerId: subscribedUser.stripeCustomerId,
+ monthlyEventCount: subscribedUser.monthlyEventCount || 0,
+ overMonthlyLimit: subscribedUser.overMonthlyLimit || false,
+ })
+ .where(eq(organization.id, targetOrg.organizationId));
+
+ console.log(
+ ` βœ… Migrated subscription to organization: "${targetOrg.organizationName}" (${targetOrg.organizationSlug})`
+ );
+ console.log(
+ ` - Stripe Customer ID: ${subscribedUser.stripeCustomerId}`
+ );
+ console.log(
+ ` - Monthly Event Count: ${subscribedUser.monthlyEventCount || 0}`
+ );
+ console.log(
+ ` - Over Monthly Limit: ${subscribedUser.overMonthlyLimit || false}`
+ );
+
+ migratedCount++;
+ }
+
+ // Step 4: Clear user billing data (optional - uncomment if you want to clean up immediately)
+ /*
+ console.log("\n🧹 Clearing user billing data...");
+ await db
+ .update(user)
+ .set({
+ stripeCustomerId: null,
+ monthlyEventCount: 0,
+ overMonthlyLimit: false,
+ })
+ .where(isNotNull(user.stripeCustomerId));
+ */
+
+ console.log(`\nπŸ“ˆ Migration Summary:`);
+ console.log(` βœ… Successfully migrated: ${migratedCount} subscriptions`);
+ console.log(` ⚠️ Skipped: ${skippedCount} subscriptions`);
+ console.log(`\nπŸŽ‰ Migration completed successfully!`);
+
+ // Step 5: Verification query
+ console.log("\nπŸ” Verification - Organizations with billing:");
+ const orgBilling = await db
+ .select({
+ organizationId: organization.id,
+ organizationName: organization.name,
+ stripeCustomerId: organization.stripeCustomerId,
+ monthlyEventCount: organization.monthlyEventCount,
+ overMonthlyLimit: organization.overMonthlyLimit,
+ })
+ .from(organization)
+ .where(isNotNull(organization.stripeCustomerId));
+
+ orgBilling.forEach((org) => {
+ console.log(
+ ` πŸ“‹ ${org.organizationName}: ${org.stripeCustomerId} (${org.monthlyEventCount} events)`
+ );
+ });
+ } catch (error) {
+ console.error("❌ Migration failed:", error);
+ throw error;
+ }
+}
+
+// Optional: Add a rollback function in case you need to undo the migration
+export async function rollbackOrganizationSubscriptions() {
+ console.log("πŸ”„ Rolling back organization subscriptions to users...");
+
+ try {
+ // Find organizations with billing data
+ const orgsWithBilling = await db
+ .select({
+ organizationId: organization.id,
+ organizationName: organization.name,
+ stripeCustomerId: organization.stripeCustomerId,
+ monthlyEventCount: organization.monthlyEventCount,
+ overMonthlyLimit: organization.overMonthlyLimit,
+ })
+ .from(organization)
+ .where(isNotNull(organization.stripeCustomerId));
+
+ for (const org of orgsWithBilling) {
+ // Find the owner of this organization
+ const owner = await db
+ .select({
+ userId: member.userId,
+ userEmail: user.email,
+ })
+ .from(member)
+ .innerJoin(user, eq(user.id, member.userId))
+ .where(
+ and(
+ eq(member.organizationId, org.organizationId),
+ eq(member.role, "owner")
+ )
+ )
+ .limit(1);
+
+ if (owner.length > 0) {
+ // Move billing back to user
+ await db
+ .update(user)
+ .set({
+ stripeCustomerId: org.stripeCustomerId,
+ monthlyEventCount: org.monthlyEventCount || 0,
+ overMonthlyLimit: org.overMonthlyLimit || false,
+ })
+ .where(eq(user.id, owner[0].userId));
+
+ // Clear organization billing
+ await db
+ .update(organization)
+ .set({
+ stripeCustomerId: null,
+ monthlyEventCount: 0,
+ overMonthlyLimit: false,
+ })
+ .where(eq(organization.id, org.organizationId));
+
+ console.log(
+ `βœ… Rolled back ${org.organizationName} billing to user ${owner[0].userEmail}`
+ );
+ }
+ }
+
+ console.log("πŸŽ‰ Rollback completed successfully!");
+ } catch (error) {
+ console.error("❌ Rollback failed:", error);
+ throw error;
+ }
+}
diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.ts
index e052eb6f0..4c13d4ddb 100644
--- a/server/src/db/postgres/schema.ts
+++ b/server/src/db/postgres/schema.ts
@@ -158,6 +158,9 @@ export const organization = pgTable(
logo: text(),
createdAt: timestamp({ mode: "string" }).notNull(),
metadata: text(),
+ stripeCustomerId: text(),
+ monthlyEventCount: integer().default(0),
+ overMonthlyLimit: boolean().default(false),
},
(table) => [unique("organization_slug_unique").on(table.slug)]
);
diff --git a/server/src/index.ts b/server/src/index.ts
index 01c83e40e..2358c8adf 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -3,12 +3,13 @@ import fastifyStatic from "@fastify/static";
import { toNodeHandler } from "better-auth/node";
import Fastify from "fastify";
import { dirname, join } from "path";
-import { Headers, HeadersInit } from "undici";
import { fileURLToPath } from "url";
+import { getAdminSites } from "./api/admin/getAdminSites.js";
+import { getAdminUsers } from "./api/admin/getAdminUsers.js";
import { createFunnel } from "./api/analytics/createFunnel.js";
import { createGoal } from "./api/analytics/createGoal.js";
-import { deleteGoal } from "./api/analytics/deleteGoal.js";
import { deleteFunnel } from "./api/analytics/deleteFunnel.js";
+import { deleteGoal } from "./api/analytics/deleteGoal.js";
import { getEventNames } from "./api/analytics/getEventNames.js";
import { getEventProperties } from "./api/analytics/getEventProperties.js";
import { getEvents } from "./api/analytics/getEvents.js";
@@ -19,8 +20,10 @@ import { getGoals } from "./api/analytics/getGoals.js";
import { getJourneys } from "./api/analytics/getJourneys.js";
import { getLiveSessionLocations } from "./api/analytics/getLiveSessionLocations.js";
import { getLiveUsercount } from "./api/analytics/getLiveUsercount.js";
+import { getOrgEventCount } from "./api/analytics/getOrgEventCount.js";
import { getOverview } from "./api/analytics/getOverview.js";
import { getOverviewBucketed } from "./api/analytics/getOverviewBucketed.js";
+import { getPageTitles } from "./api/analytics/getPageTitles.js";
import { getRetention } from "./api/analytics/getRetention.js";
import { getSession } from "./api/analytics/getSession.js";
import { getSessions } from "./api/analytics/getSessions.js";
@@ -30,16 +33,23 @@ import { getUserSessionCount } from "./api/analytics/getUserSessionCount.js";
import { getUserSessions } from "./api/analytics/getUserSessions.js";
import { getUsers } from "./api/analytics/getUsers.js";
import { updateGoal } from "./api/analytics/updateGoal.js";
+import { getConfig } from "./api/getConfig.js";
import { addSite } from "./api/sites/addSite.js";
+import { changeSiteBlockBots } from "./api/sites/changeSiteBlockBots.js";
import { changeSiteDomain } from "./api/sites/changeSiteDomain.js";
import { changeSitePublic } from "./api/sites/changeSitePublic.js";
import { changeSiteSalt } from "./api/sites/changeSiteSalt.js";
-import { changeSiteBlockBots } from "./api/sites/changeSiteBlockBots.js";
import { deleteSite } from "./api/sites/deleteSite.js";
import { getSite } from "./api/sites/getSite.js";
import { getSiteHasData } from "./api/sites/getSiteHasData.js";
import { getSiteIsPublic } from "./api/sites/getSiteIsPublic.js";
import { getSites } from "./api/sites/getSites.js";
+import { getSitesFromOrg } from "./api/sites/getSitesFromOrg.js";
+import { createCheckoutSession } from "./api/stripe/createCheckoutSession.js";
+import { createPortalSession } from "./api/stripe/createPortalSession.js";
+import { getSubscription } from "./api/stripe/getSubscription.js";
+import { handleWebhook } from "./api/stripe/webhook.js";
+import { addUserToOrganization } from "./api/user/addUserToOrganization.js";
import { createAccount } from "./api/user/createAccount.js";
import { getUserOrganizations } from "./api/user/getUserOrganizations.js";
import { listOrganizationMembers } from "./api/user/listOrganizationMembers.js";
@@ -48,20 +58,10 @@ import { initializeClickhouse } from "./db/clickhouse/clickhouse.js";
import { allowList, loadAllowedDomains } from "./lib/allowedDomains.js";
import { getSessionFromReq, mapHeaders } from "./lib/auth-utils.js";
import { auth } from "./lib/auth.js";
+import { IS_CLOUD } from "./lib/const.js";
import { siteConfig } from "./lib/siteConfig.js";
import { trackEvent } from "./tracker/trackEvent.js";
import { extractSiteId, isSitePublic, normalizeOrigin } from "./utils.js";
-import { createCheckoutSession } from "./api/stripe/createCheckoutSession.js";
-import { createPortalSession } from "./api/stripe/createPortalSession.js";
-import { getSubscription } from "./api/stripe/getSubscription.js";
-import { handleWebhook } from "./api/stripe/webhook.js";
-import { IS_CLOUD } from "./lib/const.js";
-import { addUserToOrganization } from "./api/user/addUserToOrganization.js";
-import { getConfig } from "./api/getConfig.js";
-import { getPageTitles } from "./api/analytics/getPageTitles.js";
-import { getAdminSites } from "./api/admin/getAdminSites.js";
-import { getAdminUsers } from "./api/admin/getAdminUsers.js";
-import { getOrgEventCount } from "./api/analytics/getOrgEventCount.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -240,6 +240,7 @@ server.post("/change-site-salt", changeSiteSalt);
server.post("/change-site-block-bots", changeSiteBlockBots);
server.post("/delete-site/:id", deleteSite);
server.get("/get-sites", getSites);
+server.get("/get-sites-from-org/:organizationId", getSitesFromOrg);
server.get("/get-site/:id", getSite);
server.post("/create-account", createAccount);
server.get(
@@ -266,7 +267,7 @@ if (IS_CLOUD) {
}
server.post("/track", trackEvent);
-server.get("/health", { logLevel: 'silent' }, (_, reply) => reply.send("OK"));
+server.get("/health", { logLevel: "silent" }, (_, reply) => reply.send("OK"));
const start = async () => {
try {