Skip to content

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

Add GoalCard expansion feature and session display (#685)

Bill Yange2bc4e9397d5
diff --git a/client/src/api/analytics/funnels/useGetFunnel.ts b/client/src/api/analytics/funnels/useGetFunnel.ts
index f45a8fda1..6370cb972 100644
--- a/client/src/api/analytics/funnels/useGetFunnel.ts
+++ b/client/src/api/analytics/funnels/useGetFunnel.ts
@@ -1,8 +1,8 @@
-import { Filter } from "@rybbit/shared";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useDebounce } from "@uidotdev/usehooks";
import { timeZone } from "../../../lib/dateTimeUtils";
-import { useStore } from "../../../lib/store";
+import { FUNNEL_PAGE_FILTERS } from "../../../lib/filterGroups";
+import { getFilteredFilters, useStore } from "../../../lib/store";
import { authedFetch, getQueryParams } from "../../utils";
export type FunnelStep = {
@@ -37,11 +37,11 @@ export type FunnelResponse = {
* Hook for analyzing conversion funnels through a series of steps
*/
export function useGetFunnel(config?: FunnelRequest, debounce?: boolean) {
- const { site, time, filters } = useStore();
+ const { site, time } = useStore();
const debouncedConfig = useDebounce(config, 500);
- const queryParams = getQueryParams(time, { filters });
+ const queryParams = getQueryParams(time, { filters: getFilteredFilters(FUNNEL_PAGE_FILTERS) });
const configToUse = debounce ? debouncedConfig : config;
diff --git a/client/src/api/analytics/funnels/useGetFunnelStepSessions.ts b/client/src/api/analytics/funnels/useGetFunnelStepSessions.ts
new file mode 100644
index 000000000..9a1188688
--- /dev/null
+++ b/client/src/api/analytics/funnels/useGetFunnelStepSessions.ts
@@ -0,0 +1,55 @@
+import { useQuery } from "@tanstack/react-query";
+import { Time } from "../../../components/DateSelector/types";
+import { FUNNEL_PAGE_FILTERS } from "../../../lib/filterGroups";
+import { getFilteredFilters } from "../../../lib/store";
+import { authedFetch, getQueryParams } from "../../utils";
+import { GetSessionsResponse } from "../useGetUserSessions";
+import { FunnelStep } from "./useGetFunnel";
+
+interface FunnelStepSessionsResponse {
+ data: GetSessionsResponse;
+}
+
+export function useGetFunnelStepSessions({
+ steps,
+ stepNumber,
+ siteId,
+ time,
+ mode,
+ page = 1,
+ limit = 25,
+ enabled = false,
+}: {
+ steps: FunnelStep[];
+ stepNumber: number;
+ siteId: number;
+ time: Time;
+ mode: "reached" | "dropped";
+ page?: number;
+ limit?: number;
+ enabled?: boolean;
+}) {
+ const timeParams = getQueryParams(time);
+ const filteredFilters = getFilteredFilters(FUNNEL_PAGE_FILTERS);
+
+ return useQuery({
+ queryKey: ["funnel-step-sessions", steps, stepNumber, siteId, timeParams, mode, page, limit, filteredFilters],
+ queryFn: async () => {
+ return authedFetch<FunnelStepSessionsResponse>(
+ `/funnel/${stepNumber}/sessions/${siteId}`,
+ {
+ ...timeParams,
+ mode,
+ page,
+ limit,
+ filters: filteredFilters,
+ },
+ {
+ method: "POST",
+ data: { steps },
+ }
+ );
+ },
+ enabled: !!siteId && !!steps && steps.length >= 2 && enabled,
+ });
+}
diff --git a/client/src/api/analytics/goals/useGetGoalSessions.ts b/client/src/api/analytics/goals/useGetGoalSessions.ts
new file mode 100644
index 000000000..2093d9029
--- /dev/null
+++ b/client/src/api/analytics/goals/useGetGoalSessions.ts
@@ -0,0 +1,38 @@
+import { useQuery } from "@tanstack/react-query";
+import { authedFetch, getQueryParams } from "../../utils";
+import { GetSessionsResponse } from "../useGetUserSessions";
+import { Time } from "../../../components/DateSelector/types";
+
+interface GoalSessionsResponse {
+ data: GetSessionsResponse;
+}
+
+export function useGetGoalSessions({
+ goalId,
+ siteId,
+ time,
+ page = 1,
+ limit = 25,
+ enabled = false,
+}: {
+ goalId: number;
+ siteId: number;
+ time: Time;
+ page?: number;
+ limit?: number;
+ enabled?: boolean;
+}) {
+ const timeParams = getQueryParams(time);
+
+ return useQuery({
+ queryKey: ["goal-sessions", goalId, siteId, timeParams, page, limit],
+ queryFn: async () => {
+ return authedFetch<GoalSessionsResponse>(`/goals/${goalId}/sessions/${siteId}`, {
+ ...timeParams,
+ page,
+ limit,
+ });
+ },
+ enabled: !!siteId && !!goalId && enabled,
+ });
+}
diff --git a/client/src/api/analytics/useGetUserSessions.ts b/client/src/api/analytics/useGetUserSessions.ts
index e7241d09f..abe63be6c 100644
--- a/client/src/api/analytics/useGetUserSessions.ts
+++ b/client/src/api/analytics/useGetUserSessions.ts
@@ -43,6 +43,45 @@ export type GetSessionsResponse = {
lon: number;
}[];
+export function useGetSessions(userId?: string, page: number = 1, limit: number = 100) {
+ const { time, site } = useStore();
+
+ // Get the appropriate time parameters using getQueryParams
+ const timeParams = getQueryParams(time);
+
+ const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);
+
+ return useQuery<APIResponse<GetSessionsResponse>>({
+ queryKey: ["sessions", time, site, filteredFilters, userId, page, limit],
+ queryFn: () => {
+ // Use an object for request parameters so we can conditionally add fields
+ const requestParams: Record<string, any> = {
+ time_zone: timeZone,
+ filters: filteredFilters,
+ page,
+ limit,
+ };
+
+ // Add userId if provided
+ if (userId) {
+ requestParams.user_id = userId;
+ }
+
+ // Add time parameters
+ if (time.mode === "past-minutes") {
+ Object.assign(requestParams, timeParams);
+ } else if (!userId) {
+ // Only add date parameters if not filtering by userId
+ requestParams.start_date = timeParams.start_date;
+ requestParams.end_date = timeParams.end_date;
+ }
+
+ return authedFetch<APIResponse<GetSessionsResponse>>(`/sessions/${site}`, requestParams);
+ },
+ staleTime: Infinity,
+ });
+}
+
export function useGetSessionsInfinite(userId?: string) {
const { time, site } = useStore();
diff --git a/client/src/app/[site]/funnels/components/Funnel.tsx b/client/src/app/[site]/funnels/components/Funnel.tsx
index a753aa8fb..4d255fc5e 100644
--- a/client/src/app/[site]/funnels/components/Funnel.tsx
+++ b/client/src/app/[site]/funnels/components/Funnel.tsx
@@ -1,8 +1,14 @@
"use client";
import { round } from "lodash";
+import { ChevronDown, ChevronUp } from "lucide-react";
+import { useState } from "react";
import { FunnelResponse, FunnelStep } from "../../../../api/analytics/funnels/useGetFunnel";
+import { useGetFunnelStepSessions } from "../../../../api/analytics/funnels/useGetFunnelStepSessions";
import { EventIcon, PageviewIcon } from "../../../../components/EventIcons";
+import { SessionsList } from "../../../../components/Sessions/SessionsList";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../components/ui/tabs";
+import { useStore } from "../../../../lib/store";
export type FunnelChartData = {
stepName: string;
@@ -20,7 +26,183 @@ interface FunnelProps {
steps: FunnelStep[];
}
+const LIMIT = 25;
+
+interface FunnelStepComponentProps {
+ step: FunnelChartData;
+ index: number;
+ steps: FunnelStep[];
+ chartData: FunnelChartData[];
+ firstStep: FunnelChartData | undefined;
+ siteId: number;
+}
+
+function FunnelStepComponent({ step, index, steps, chartData, firstStep, siteId }: FunnelStepComponentProps) {
+ const [isExpanded, setIsExpanded] = useState(false);
+ const [currentTab, setCurrentTab] = useState<"reached" | "dropped">("reached");
+ const [reachedPage, setReachedPage] = useState(1);
+ const [droppedPage, setDroppedPage] = useState(1);
+ const { time } = useStore();
+
+ const maxBarWidth = 100;
+ const ratio = firstStep?.visitors ? step.visitors / firstStep.visitors : 0;
+ const barWidth = Math.max(ratio * maxBarWidth, 0);
+
+ const prevStep = index > 0 ? chartData[index - 1] : null;
+ const droppedFromPrevious = prevStep ? prevStep.visitors - step.visitors : 0;
+ const dropoffPercent = prevStep ? (droppedFromPrevious / prevStep.visitors) * 100 : 0;
+ const isFirstStep = index === 0;
+
+ // Fetch sessions for "reached" mode
+ const { data: reachedData, isLoading: isLoadingReached } = useGetFunnelStepSessions({
+ steps,
+ stepNumber: step.stepNumber,
+ siteId,
+ time,
+ mode: "reached",
+ page: reachedPage,
+ limit: LIMIT + 1,
+ enabled: isExpanded && currentTab === "reached",
+ });
+
+ // Fetch sessions for "dropped" mode (only if not first step)
+ // For step N, we want sessions that reached step N-1 but NOT step N
+ const { data: droppedData, isLoading: isLoadingDropped } = useGetFunnelStepSessions({
+ steps,
+ stepNumber: step.stepNumber - 1, // Previous step
+ siteId,
+ time,
+ mode: "dropped",
+ page: droppedPage,
+ limit: LIMIT + 1,
+ enabled: isExpanded && currentTab === "dropped" && !isFirstStep,
+ });
+
+ const allReachedSessions = reachedData?.data || [];
+ const hasNextReached = allReachedSessions.length > LIMIT;
+ const reachedSessions = allReachedSessions.slice(0, LIMIT);
+ const hasPrevReached = reachedPage > 1;
+
+ const allDroppedSessions = droppedData?.data || [];
+ const hasNextDropped = allDroppedSessions.length > LIMIT;
+ const droppedSessions = allDroppedSessions.slice(0, LIMIT);
+ const hasPrevDropped = droppedPage > 1;
+
+ const toggleExpansion = () => {
+ setIsExpanded(!isExpanded);
+ if (!isExpanded) {
+ setCurrentTab("reached");
+ setReachedPage(1);
+ setDroppedPage(1);
+ }
+ };
+
+ return (
+ <div key={step.stepNumber} className="relative pb-4">
+ {/* Step Header - Clickable */}
+ <div
+ className="flex items-center cursor-pointer hover:bg-neutral-800/30 rounded-md p-2 -ml-2 transition-colors"
+ onClick={toggleExpansion}
+ >
+ <div className="flex-shrink-0 w-6 h-6 rounded-full bg-neutral-800 flex items-center justify-center text-xs mr-2">
+ {step.stepNumber}
+ </div>
+ <div className="font-medium text-sm flex items-center gap-2 flex-1">
+ {steps[index]?.type === "page" ? <PageviewIcon /> : <EventIcon />}
+ {step.stepName}
+ </div>
+ <div className="flex-shrink-0">
+ {isExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
+ </div>
+ </div>
+
+ {/* Bar and metrics */}
+ <div className="flex items-center pl-8">
+ {/* Metrics */}
+ <div className="flex-shrink-0 min-w-[130px] mr-4 space-y-1">
+ <div className="flex items-baseline">
+ <span className="text-base font-semibold">{step.visitors.toLocaleString()}</span>
+ <span className="text-sm text-neutral-400 ml-1">sessions</span>
+ </div>
+ {index !== 0 && (
+ <div className="flex items-baseline text-orange-500 text-xs font-medium">
+ {droppedFromPrevious.toLocaleString()} dropped
+ </div>
+ )}
+ </div>
+
+ {/* Bar */}
+ <div className="flex-grow h-10 bg-neutral-800 rounded-md overflow-hidden relative mt-2">
+ {/* Relative conversion bar (from previous step) */}
+ {index > 0 && prevStep && (
+ <div
+ className="absolute h-full rounded-md"
+ style={{
+ width: `${(step.visitors / prevStep.visitors) * 100}%`,
+ background: `repeating-linear-gradient(
+ 45deg,
+ rgba(16, 185, 129, 0.25),
+ rgba(16, 185, 129, 0.25) 6px,
+ rgba(16, 185, 129, 0.15) 6px,
+ rgba(16, 185, 129, 0.15) 12px
+ )`,
+ }}
+ ></div>
+ )}
+ {/* Absolute conversion bar (from first step) */}
+ <div className="h-full bg-emerald-500/70 rounded-md relative z-10" style={{ width: `${barWidth}%` }}></div>
+ <div className="absolute top-2 right-2 z-20">
+ <div className="text-base font-semibold">{round(step.conversionRate, 2)}%</div>
+ </div>
+ </div>
+ </div>
+
+ {/* Expanded Sessions Section */}
+ {isExpanded && (
+ <div className=" ml-4 p-4">
+ <Tabs value={currentTab} onValueChange={val => setCurrentTab(val as "reached" | "dropped")}>
+ <TabsList className="mb-1">
+ <TabsTrigger value="reached">Reached ({step.visitors.toLocaleString()})</TabsTrigger>
+ {!isFirstStep && (
+ <TabsTrigger value="dropped">Dropped Off ({droppedFromPrevious.toLocaleString()})</TabsTrigger>
+ )}
+ </TabsList>
+
+ <TabsContent value="reached">
+ <SessionsList
+ sessions={reachedSessions}
+ isLoading={isLoadingReached}
+ page={reachedPage}
+ onPageChange={setReachedPage}
+ hasNextPage={hasNextReached}
+ hasPrevPage={hasPrevReached}
+ emptyMessage="No sessions reached this step in the selected time period."
+ />
+ </TabsContent>
+
+ {!isFirstStep && (
+ <TabsContent value="dropped">
+ <SessionsList
+ sessions={droppedSessions}
+ isLoading={isLoadingDropped}
+ page={droppedPage}
+ onPageChange={setDroppedPage}
+ hasNextPage={hasNextDropped}
+ hasPrevPage={hasPrevDropped}
+ emptyMessage="No sessions dropped off before reaching this step in the selected time period."
+ />
+ </TabsContent>
+ )}
+ </Tabs>
+ </div>
+ )}
+ </div>
+ );
+}
+
export function Funnel({ data, steps, isError, error, isPending }: FunnelProps) {
+ const { site } = useStore();
+
// Prepare chart data
const chartData =
data?.map(step => ({
@@ -36,8 +218,6 @@ export function Funnel({ data, steps, isError, error, isPending }: FunnelProps)
const lastStep = chartData[chartData.length - 1];
const totalConversionRate = lastStep?.conversionRate || 0;
- const maxBarWidth = 100; // as percentage
-
return (
<div className="mt-2">
{isError ? (
@@ -48,75 +228,17 @@ export function Funnel({ data, steps, isError, error, isPending }: FunnelProps)
</div>
) : data && chartData.length > 0 ? (
<div className="space-y-0">
- {chartData.map((step, index) => {
- // Calculate the percentage width for the bar
- const ratio = firstStep?.visitors ? step.visitors / firstStep.visitors : 0;
- const barWidth = Math.max(ratio * maxBarWidth, 0);
-
- // For step 2+, calculate the number of users who dropped off
- const prevStep = index > 0 ? chartData[index - 1] : null;
- const droppedUsers = prevStep ? prevStep.visitors - step.visitors : 0;
- const dropoffPercent = prevStep ? (droppedUsers / prevStep.visitors) * 100 : 0;
-
- return (
- <div key={step.stepNumber} className="relative pb-4">
- {/* Step number indicator */}
- <div className="flex items-center">
- <div className="flex-shrink-0 w-6 h-6 rounded-full bg-neutral-800 flex items-center justify-center text-xs mr-2">
- {step.stepNumber}
- </div>
- <div className="font-medium text-sm flex items-center gap-2">
- {steps[index]?.type === "page" ? <PageviewIcon /> : <EventIcon />}
- {step.stepName}
- </div>
- </div>
-
- {/* Bar and metrics */}
- <div className="flex items-center pl-8">
- {/* Metrics */}
- <div className="flex-shrink-0 min-w-[130px] mr-4 space-y-1">
- <div className="flex items-baseline">
- <span className="text-base font-semibold">{step.visitors.toLocaleString()}</span>
- <span className="text-sm text-neutral-400 ml-1">users</span>
- </div>
- {index !== 0 && (
- <div className="flex items-baseline text-orange-500 text-xs font-medium">
- {droppedUsers.toLocaleString()} dropped
- </div>
- )}
- </div>
-
- {/* Bar */}
- <div className="flex-grow h-10 bg-neutral-800 rounded-md overflow-hidden relative mt-2">
- {/* Relative conversion bar (from previous step) */}
- {index > 0 && prevStep && (
- <div
- className="absolute h-full rounded-md"
- style={{
- width: `${(step.visitors / prevStep.visitors) * 100}%`,
- background: `repeating-linear-gradient(
- 45deg,
- rgba(16, 185, 129, 0.25),
- rgba(16, 185, 129, 0.25) 6px,
- rgba(16, 185, 129, 0.15) 6px,
- rgba(16, 185, 129, 0.15) 12px
- )`,
- }}
- ></div>
- )}
- {/* Absolute conversion bar (from first step) */}
- <div
- className="h-full bg-emerald-500/70 rounded-md relative z-10"
- style={{ width: `${barWidth}%` }}
- ></div>
- <div className="absolute top-2 right-2 z-20">
- <div className="text-base font-semibold">{round(step.conversionRate, 2)}%</div>
- </div>
- </div>
- </div>
- </div>
- );
- })}
+ {chartData.map((step, index) => (
+ <FunnelStepComponent
+ key={step.stepNumber}
+ step={step}
+ index={index}
+ steps={steps}
+ chartData={chartData}
+ firstStep={firstStep}
+ siteId={Number(site)}
+ />
+ ))}
</div>
) : (
<div className="h-[400px] flex items-center justify-center">
diff --git a/client/src/app/[site]/funnels/page.tsx b/client/src/app/[site]/funnels/page.tsx
index 9b6912aef..f8e541d51 100644
--- a/client/src/app/[site]/funnels/page.tsx
+++ b/client/src/app/[site]/funnels/page.tsx
@@ -1,20 +1,18 @@
"use client";
-import { SavedFunnel, useGetFunnels } from "../../../api/analytics/funnels/useGetFunnels";
-import { Skeleton } from "@/components/ui/skeleton";
-import { useStore } from "@/lib/store";
+import { Input } from "@/components/ui/input";
import { GOALS_PAGE_FILTERS } from "@/lib/filterGroups";
-import { ArrowRight, FilterIcon, Funnel } from "lucide-react";
+import { useStore } from "@/lib/store";
+import { ArrowRight, Funnel } from "lucide-react";
+import { useMemo, useState } from "react";
+import { SavedFunnel, useGetFunnels } from "../../../api/analytics/funnels/useGetFunnels";
+import { DisabledOverlay } from "../../../components/DisabledOverlay";
+import { ErrorState } from "../../../components/ErrorState";
import { NothingFound } from "../../../components/NothingFound";
-import { CreateFunnelDialog } from "./components/CreateFunnel";
-import { FunnelRow } from "./components/FunnelRow";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
-import { DisabledOverlay } from "../../../components/DisabledOverlay";
-import { MobileSidebar } from "../components/Sidebar/MobileSidebar";
import { SubHeader } from "../components/SubHeader/SubHeader";
-import { Input } from "@/components/ui/input";
-import { useMemo, useState } from "react";
-import { ErrorState } from "../../../components/ErrorState";
+import { CreateFunnelDialog } from "./components/CreateFunnel";
+import { FunnelRow } from "./components/FunnelRow";
// Skeleton for the funnel row component
const FunnelRowSkeleton = () => (
@@ -42,15 +40,6 @@ const FunnelRowSkeleton = () => (
</div>
</div>
</div>
-
- {/* Filters skeleton */}
- <div className="flex items-center gap-1">
- <FilterIcon className="h-3 w-3 text-neutral-600" />
- <div className="flex flex-wrap gap-1">
- <div className="rounded bg-neutral-800 px-1.5 py-0.5 w-24 h-5"></div>
- <div className="rounded bg-neutral-800 px-1.5 py-0.5 w-20 h-5"></div>
- </div>
- </div>
</div>
</div>
diff --git a/client/src/app/[site]/globe/components/GlobeSessions.tsx b/client/src/app/[site]/globe/components/GlobeSessions.tsx
index cf33e87dd..2e3f55c9c 100644
--- a/client/src/app/[site]/globe/components/GlobeSessions.tsx
+++ b/client/src/app/[site]/globe/components/GlobeSessions.tsx
@@ -162,7 +162,7 @@ function SessionCard({ session, onClick }: { session: GetSessionsResponse[number
}
export function GlobeSessions() {
- const { data, isLoading, error, fetchNextPage, hasNextPage, isFetchingNextPage } = useGetSessionsInfinite();
+ const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } = useGetSessionsInfinite();
const [expanded, setExpanded] = useState(false);
const [selectedSession, setSelectedSession] = useState<GetSessionsResponse[number] | null>(null);
@@ -194,7 +194,14 @@ export function GlobeSessions() {
<SessionCard key={session.session_id} session={session} onClick={() => setSelectedSession(session)} />
))
)}
+ {isFetchingNextPage && <SessionCardSkeleton />}
</div>
+ {/* Load more button */}
+ {hasNextPage && !isLoading && (
+ <Button onClick={() => fetchNextPage()} className="w-full" variant="ghost" size="sm">
+ Load more
+ </Button>
+ )}
</div>
<Dialog open={!!selectedSession} onOpenChange={open => !open && setSelectedSession(null)}>
diff --git a/client/src/app/[site]/goals/components/GoalCard.tsx b/client/src/app/[site]/goals/components/GoalCard.tsx
index f73ba1d0f..85f9d44e0 100644
--- a/client/src/app/[site]/goals/components/GoalCard.tsx
+++ b/client/src/app/[site]/goals/components/GoalCard.tsx
@@ -1,10 +1,12 @@
"use client";
-import { Copy, Edit, Trash2 } from "lucide-react";
+import { ChevronDown, ChevronUp, Copy, Edit, Trash2 } from "lucide-react";
import { useState } from "react";
import { useDeleteGoal } from "../../../../api/analytics/goals/useDeleteGoal";
import { Goal } from "../../../../api/analytics/goals/useGetGoals";
+import { useGetGoalSessions } from "../../../../api/analytics/goals/useGetGoalSessions";
import { EventIcon, PageviewIcon } from "../../../../components/EventIcons";
+import { SessionsList } from "../../../../components/Sessions/SessionsList";
import {
AlertDialog,
AlertDialogAction,
@@ -17,6 +19,7 @@ import {
} from "../../../../components/ui/alert-dialog";
import { Button } from "../../../../components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../components/ui/tooltip";
+import { useStore } from "../../../../lib/store";
import GoalFormModal from "./GoalFormModal";
interface GoalCardProps {
@@ -24,9 +27,24 @@ interface GoalCardProps {
siteId: number;
}
+const LIMIT = 25;
+
export default function GoalCard({ goal, siteId }: GoalCardProps) {
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
+ const [isExpanded, setIsExpanded] = useState(false);
+ const [page, setPage] = useState(1);
const deleteGoalMutation = useDeleteGoal();
+ const { time } = useStore();
+
+ // Fetch sessions when expanded
+ const { data: sessionsData, isLoading: isLoadingSessions } = useGetGoalSessions({
+ goalId: goal.goalId,
+ siteId,
+ time,
+ page,
+ limit: LIMIT + 1,
+ enabled: isExpanded,
+ });
const handleDelete = async () => {
try {
@@ -37,10 +55,25 @@ export default function GoalCard({ goal, siteId }: GoalCardProps) {
}
};
+ const allSessions = sessionsData?.data || [];
+ const hasNextPage = allSessions.length > LIMIT;
+ const sessions = allSessions.slice(0, LIMIT);
+ const hasPrevPage = page > 1;
+
+ const toggleExpansion = () => {
+ setIsExpanded(!isExpanded);
+ if (!isExpanded) {
+ setPage(1); // Reset to first page when expanding
+ }
+ };
+
return (
<>
<div className="rounded-lg bg-neutral-900 border border-neutral-800 overflow-hidden relative">
- <div className="px-4 py-3 flex items-center mb-1">
+ <div
+ className="px-4 py-3 flex items-center mb-1 cursor-pointer hover:bg-neutral-800/50 transition-colors"
+ onClick={toggleExpansion}
+ >
{/* Left section - Title and type */}
<div className="flex-1 pr-4">
<h3 className="font-medium text-base flex items-center gap-2">
@@ -105,7 +138,13 @@ export default function GoalCard({ goal, siteId }: GoalCardProps) {
trigger={
<Tooltip>
<TooltipTrigger asChild>
- <Button variant="ghost" size="smIcon">
+ <Button
+ variant="ghost"
+ size="smIcon"
+ onClick={e => {
+ e.stopPropagation(); // Prevent expanding when clicking edit
+ }}
+ >
<Edit className="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -120,7 +159,13 @@ export default function GoalCard({ goal, siteId }: GoalCardProps) {
trigger={
<Tooltip>
<TooltipTrigger asChild>
- <Button variant="ghost" size="smIcon">
+ <Button
+ variant="ghost"
+ size="smIcon"
+ onClick={e => {
+ e.stopPropagation(); // Prevent expanding when clicking clone
+ }}
+ >
<Copy className="h-4 w-4" />
</Button>
</TooltipTrigger>
@@ -130,21 +175,54 @@ export default function GoalCard({ goal, siteId }: GoalCardProps) {
/>
<Tooltip>
<TooltipTrigger asChild>
- <Button onClick={() => setIsDeleteDialogOpen(true)} variant="ghost" size="smIcon">
+ <Button
+ onClick={e => {
+ e.stopPropagation(); // Prevent expanding when clicking delete
+ setIsDeleteDialogOpen(true);
+ }}
+ variant="ghost"
+ size="smIcon"
+ >
<Trash2 className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Delete Goal</TooltipContent>
</Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="ghost" size="smIcon">
+ {isExpanded ? <ChevronUp className="h-5 w-5" /> : <ChevronDown className="h-5 w-5" />}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{isExpanded ? "Collapse" : "Expand to view conversions"}</TooltipContent>
+ </Tooltip>
</div>
</div>
- <div className="bg-neutral-700 h-1.5 w-full absolute bottom-0 left-0"></div>
- <div
- style={{
- width: goal.conversion_rate * 100 + "%",
- }}
- className="bg-accent-400/75 h-1.5 absolute bottom-0 left-0"
- ></div>
+ <div className="relative">
+ <div className="bg-neutral-700 h-1.5 w-full absolute bottom-0 left-0"></div>
+ <div
+ style={{
+ width: goal.conversion_rate * 100 + "%",
+ }}
+ className="bg-accent-400/75 h-1.5 absolute bottom-0 left-0"
+ ></div>
+ </div>
+
+ {/* Expanded Sessions Section */}
+ {isExpanded && (
+ <div className="border-t border-neutral-800 bg-neutral-900/50 p-4">
+ <h4 className="text-sm font-medium text-neutral-200 mb-3">Converted Sessions</h4>
+ <SessionsList
+ sessions={sessions}
+ isLoading={isLoadingSessions}
+ page={page}
+ onPageChange={setPage}
+ hasNextPage={hasNextPage}
+ hasPrevPage={hasPrevPage}
+ emptyMessage="No sessions converted to this goal in the selected time period."
+ />
+ </div>
+ )}
</div>
{/* Delete Confirmation Dialog */}
diff --git a/client/src/app/[site]/goals/page.tsx b/client/src/app/[site]/goals/page.tsx
index ab4f4eb45..c66a68733 100644
--- a/client/src/app/[site]/goals/page.tsx
+++ b/client/src/app/[site]/goals/page.tsx
@@ -14,6 +14,48 @@ import GoalsList from "./components/GoalsList";
import { Target } from "lucide-react";
import { Input } from "@/components/ui/input";
+// Goal card skeleton component
+const GoalCardSkeleton = () => (
+ <div className="rounded-lg bg-neutral-900 border border-neutral-800 overflow-hidden relative animate-pulse">
+ <div className="px-4 py-3 flex items-center mb-1">
+ {/* Left section skeleton */}
+ <div className="flex-1 pr-4">
+ <div className="flex items-center gap-2">
+ <div className="w-4 h-4 bg-neutral-800 rounded-full"></div>
+ <div className="h-5 bg-neutral-800 rounded w-36"></div>
+ </div>
+ <div className="mt-2">
+ <div className="h-4 bg-neutral-800 rounded w-48 mt-1"></div>
+ </div>
+ </div>
+
+ {/* Center section skeleton */}
+ <div className="flex-1 flex justify-center">
+ <div className="grid grid-cols-2 gap-4 w-full">
+ <div className="text-center">
+ <div className="h-5 bg-neutral-800 rounded w-12 mx-auto"></div>
+ <div className="h-3 bg-neutral-800 rounded w-16 mx-auto mt-1"></div>
+ </div>
+ <div className="text-center">
+ <div className="h-5 bg-neutral-800 rounded w-12 mx-auto"></div>
+ <div className="h-3 bg-neutral-800 rounded w-16 mx-auto mt-1"></div>
+ </div>
+ </div>
+ </div>
+
+ {/* Right section skeleton */}
+ <div className="flex flex-shrink-0 gap-1 pl-4">
+ <div className="w-7 h-7 bg-neutral-800 rounded"></div>
+ <div className="w-7 h-7 bg-neutral-800 rounded"></div>
+ <div className="w-7 h-7 bg-neutral-800 rounded"></div>
+ <div className="w-7 h-7 bg-neutral-800 rounded"></div>
+ </div>
+ </div>
+ <div className="bg-neutral-700 h-1.5 w-full absolute bottom-0 left-0"></div>
+ <div className="bg-neutral-800 h-1.5 w-1/3 absolute bottom-0 left-0"></div>
+ </div>
+);
+
export default function GoalsPage() {
useSetPageTitle("Rybbit · Goals");
@@ -94,46 +136,6 @@ export default function GoalsPage() {
}
: undefined;
- // Goal card skeleton component
- const GoalCardSkeleton = () => (
- <div className="rounded-lg bg-neutral-900 border border-neutral-800 overflow-hidden relative animate-pulse">
- <div className="px-4 py-3 flex items-center mb-1">
- {/* Left section skeleton */}
- <div className="flex-1 pr-4">
- <div className="flex items-center gap-2">
- <div className="w-4 h-4 bg-neutral-800 rounded-full"></div>
- <div className="h-5 bg-neutral-800 rounded w-36"></div>
- </div>
- <div className="mt-2">
- <div className="h-4 bg-neutral-800 rounded w-48 mt-1"></div>
- </div>
- </div>
-
- {/* Center section skeleton */}
- <div className="flex-1 flex justify-center">
- <div className="grid grid-cols-2 gap-4 w-full">
- <div className="text-center">
- <div className="h-5 bg-neutral-800 rounded w-12 mx-auto"></div>
- <div className="h-3 bg-neutral-800 rounded w-16 mx-auto mt-1"></div>
- </div>
- <div className="text-center">
- <div className="h-5 bg-neutral-800 rounded w-12 mx-auto"></div>
- <div className="h-3 bg-neutral-800 rounded w-16 mx-auto mt-1"></div>
- </div>
- </div>
- </div>
-
- {/* Right section skeleton */}
- <div className="flex flex-shrink-0 gap-1 pl-4">
- <div className="w-7 h-7 bg-neutral-800 rounded"></div>
- <div className="w-7 h-7 bg-neutral-800 rounded"></div>
- </div>
- </div>
- <div className="bg-neutral-700 h-1.5 w-full absolute bottom-0 left-0"></div>
- <div className="bg-neutral-800 h-1.5 w-1/3 absolute bottom-0 left-0"></div>
- </div>
- );
-
return (
<DisabledOverlay message="Goals" featurePath="goals">
<div className="p-2 md:p-4 max-w-[1400px] mx-auto space-y-3">
@@ -148,8 +150,8 @@ export default function GoalsPage() {
/>
<CreateGoalButton siteId={Number(site)} />
</div>
-
- {isLoading ? (
+ {/* if site is not loaded, show skeleton */}
+ {isLoading || !site ? (
<div className="space-y-3">
{Array(3)
.fill(0)
diff --git a/client/src/app/[site]/sessions/page.tsx b/client/src/app/[site]/sessions/page.tsx
index 8a745e49f..b31f25a9b 100644
--- a/client/src/app/[site]/sessions/page.tsx
+++ b/client/src/app/[site]/sessions/page.tsx
@@ -1,19 +1,37 @@
"use client";
+import { useState } from "react";
+import { useGetSessions } from "../../../api/analytics/useGetUserSessions";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { SESSION_PAGE_FILTERS } from "../../../lib/filterGroups";
import { SubHeader } from "../components/SubHeader/SubHeader";
-import SessionsList from "@/components/Sessions/SessionsList";
+import { SessionsList } from "@/components/Sessions/SessionsList";
+
+const LIMIT = 100;
export default function SessionsPage() {
useSetPageTitle("Rybbit · Sessions");
+ const [page, setPage] = useState(1);
+
+ const { data, isLoading } = useGetSessions(undefined, page, LIMIT + 1);
+ const allSessions = data?.data || [];
+ const hasNextPage = allSessions.length > LIMIT;
+ const sessions = allSessions.slice(0, LIMIT);
+ const hasPrevPage = page > 1;
return (
<DisabledOverlay message="Sessions" featurePath="sessions">
<div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3">
<SubHeader availableFilters={SESSION_PAGE_FILTERS} />
- <SessionsList />
+ <SessionsList
+ sessions={sessions}
+ isLoading={isLoading}
+ page={page}
+ onPageChange={setPage}
+ hasNextPage={hasNextPage}
+ hasPrevPage={hasPrevPage}
+ />
</div>
</DisabledOverlay>
);
diff --git a/client/src/app/[site]/user/[userId]/page.tsx b/client/src/app/[site]/user/[userId]/page.tsx
index 609aa55c8..22b272017 100644
--- a/client/src/app/[site]/user/[userId]/page.tsx
+++ b/client/src/app/[site]/user/[userId]/page.tsx
@@ -1,6 +1,6 @@
"use client";
-import SessionsList from "@/components/Sessions/SessionsList";
+import { SessionsList } from "@/components/Sessions/SessionsList";
import {
ArrowLeft,
Calendar,
@@ -15,8 +15,9 @@ import {
} from "lucide-react";
import { DateTime } from "luxon";
import { useParams, useRouter } from "next/navigation";
+import { useState } from "react";
import { useUserInfo } from "../../../../api/analytics/userGetInfo";
-import { useGetUserSessionCount } from "../../../../api/analytics/useGetUserSessions";
+import { useGetSessions, useGetUserSessionCount } from "../../../../api/analytics/useGetUserSessions";
import { Avatar, generateName } from "../../../../components/Avatar";
import { Badge } from "../../../../components/ui/badge";
import { Button } from "../../../../components/ui/button";
@@ -32,17 +33,26 @@ import { MobileSidebar } from "../../components/Sidebar/MobileSidebar";
import { VisitCalendar } from "./components/Calendar";
import { EventIcon, PageviewIcon } from "../../../../components/EventIcons";
+const LIMIT = 25;
+
export default function UserPage() {
useSetPageTitle("Rybbit · User");
const router = useRouter();
const { userId } = useParams();
const { site } = useParams();
+ const [page, setPage] = useState(1);
const { data, isLoading } = useUserInfo(Number(site), userId as string);
const { data: sessionCount } = useGetUserSessionCount(userId as string);
+ const { data: sessionsData, isLoading: isLoadingSessions } = useGetSessions(userId as string, page, LIMIT + 1);
+ const allSessions = sessionsData?.data || [];
+ const hasNextPage = allSessions.length > LIMIT;
+ const sessions = allSessions.slice(0, LIMIT);
+ const hasPrevPage = page > 1;
+
const { getRegionName } = useGetRegionName();
const handleBackClick = () => {
@@ -223,7 +233,15 @@ export default function UserPage() {
</div>
<h2 className="text-lg font-bold mb-4">Sessions</h2>
- <SessionsList userId={userId as string} />
+ <SessionsList
+ sessions={sessions}
+ isLoading={isLoadingSessions}
+ page={page}
+ onPageChange={setPage}
+ hasNextPage={hasNextPage}
+ hasPrevPage={hasPrevPage}
+ userId={userId as string}
+ />
</div>
);
}
diff --git a/client/src/components/Sessions/SessionCard.tsx b/client/src/components/Sessions/SessionCard.tsx
index 9c31a33a1..e23bb82f0 100644
--- a/client/src/components/Sessions/SessionCard.tsx
+++ b/client/src/components/Sessions/SessionCard.tsx
@@ -176,7 +176,7 @@ export const SessionCardSkeleton = memo(() => {
};
// Create multiple skeletons for a realistic loading state
- const skeletons = Array.from({ length: 10 }).map((_, index) => (
+ const skeletons = Array.from({ length: 25 }).map((_, index) => (
<div className="rounded-lg bg-neutral-900 border border-neutral-800 overflow-hidden" key={index}>
<div className="p-3">
<div className="flex items-center gap-2">
diff --git a/client/src/components/Sessions/SessionsList.tsx b/client/src/components/Sessions/SessionsList.tsx
index aaaf164c0..1fa078db5 100644
--- a/client/src/components/Sessions/SessionsList.tsx
+++ b/client/src/components/Sessions/SessionsList.tsx
@@ -1,52 +1,59 @@
-import { useEffect, useMemo, useRef } from "react";
-import { useGetSessionsInfinite } from "../../api/analytics/useGetUserSessions";
-import { SessionCard, SessionCardSkeleton } from "./SessionCard";
-import { Button } from "../ui/button";
+import { ChevronLeft, ChevronRight, Rewind } from "lucide-react";
+import { GetSessionsResponse } from "../../api/analytics/useGetUserSessions";
import { NothingFound } from "../NothingFound";
-import { Rewind } from "lucide-react";
-
-export default function SessionsList({ userId }: { userId?: string }) {
- // Get sessions data with infinite loading
- const { data, isLoading, error, fetchNextPage, hasNextPage, isFetchingNextPage } = useGetSessionsInfinite(userId);
-
- // Combine all pages of data
- const flattenedData = useMemo(() => {
- if (!data) return [];
- return data.pages.flatMap(page => page.data || []);
- }, [data]);
+import { Button } from "../ui/button";
+import { SessionCard, SessionCardSkeleton } from "./SessionCard";
- // Reference for the scroll container
- const containerRef = useRef<HTMLDivElement>(null);
+interface SessionsListProps {
+ sessions: GetSessionsResponse;
+ isLoading: boolean;
+ page: number;
+ onPageChange: (page: number) => void;
+ hasNextPage: boolean;
+ hasPrevPage: boolean;
+ emptyMessage?: string;
+ userId?: string;
+}
- if (error) return <div className="text-red-500 p-4">Error: {(error as Error).message}</div>;
+export function SessionsList({
+ sessions,
+ isLoading,
+ page,
+ onPageChange,
+ hasNextPage,
+ hasPrevPage,
+ emptyMessage = "Try a different date range or filter",
+ userId,
+}: SessionsListProps) {
+ if (sessions.length === 0 && !isLoading) {
+ return (
+ <div className="overflow-auto space-y-3">
+ <NothingFound icon={<Rewind className="w-10 h-10" />} title={"No sessions found"} description={emptyMessage} />
+ </div>
+ );
+ }
return (
- <div ref={containerRef} className="overflow-auto space-y-3">
+ <div className="overflow-auto space-y-3">
+ {/* Pagination controls */}
+ <div className="flex items-center justify-end gap-2">
+ <Button variant="ghost" size="smIcon" onClick={() => onPageChange(page - 1)} disabled={!hasPrevPage}>
+ <ChevronLeft className="h-4 w-4" />
+ </Button>
+ <span className="text-sm text-neutral-400">Page {page}</span>
+ <Button variant="ghost" size="smIcon" onClick={() => onPageChange(page + 1)} disabled={!hasNextPage}>
+ <ChevronRight className="h-4 w-4" />
+ </Button>
+ </div>
+
+ {/* Session cards */}
{isLoading ? (
- // Show skeleton cards while loading
<SessionCardSkeleton />
- ) : flattenedData.length === 0 ? (
- <NothingFound
- icon={<Rewind className="w-10 h-10" />}
- title={"No sessions found"}
- description={"Try a different date range or filter"}
- />
) : (
- // Render session cards with more robust key generation
- flattenedData.map((session, index) => (
+ sessions.map((session, index) => (
<SessionCard key={`${session.session_id}-${index}`} session={session} userId={userId} />
))
)}
-
- {isFetchingNextPage && <SessionCardSkeleton key="loading-more" />}
-
- {hasNextPage && (
- <div className="flex justify-center py-2">
- <Button onClick={() => fetchNextPage()} className="w-full" variant="success">
- Load more
- </Button>
- </div>
- )}
</div>
);
}
diff --git a/client/src/lib/filterGroups.ts b/client/src/lib/filterGroups.ts
index abe7ec37d..4f77f3794 100644
--- a/client/src/lib/filterGroups.ts
+++ b/client/src/lib/filterGroups.ts
@@ -39,6 +39,8 @@ export const EVENT_FILTERS: FilterParameter[] = [
export const GOALS_PAGE_FILTERS: FilterParameter[] = [...BASE_FILTERS];
+export const FUNNEL_PAGE_FILTERS: FilterParameter[] = [...BASE_FILTERS];
+
export const USER_PAGE_FILTERS: FilterParameter[] = [
"hostname",
"browser",
diff --git a/server/src/api/analytics/funnels/getFunnel.ts b/server/src/api/analytics/funnels/getFunnel.ts
index 8cb5c68d2..2dcbf1b74 100644
--- a/server/src/api/analytics/funnels/getFunnel.ts
+++ b/server/src/api/analytics/funnels/getFunnel.ts
@@ -53,7 +53,11 @@ export async function getFunnel(
if (step.type === "page") {
// Use pattern matching for page paths to support wildcards
- condition = `type = 'pageview' AND match(pathname, ${SqlString.escape(patternToRegex(step.value))})`;
+ const regex = patternToRegex(step.value);
+ // Manually escape single quotes in the regex and wrap in quotes
+ // Don't use SqlString.escape() as it doesn't preserve the regex correctly
+ const safeRegex = regex.replace(/'/g, "\\'");
+ condition = `type = 'pageview' AND match(pathname, '${safeRegex}')`;
} else {
// Start with the base event match condition
condition = `type = 'custom_event' AND event_name = ${SqlString.escape(step.value)}`;
@@ -86,13 +90,13 @@ export async function getFunnel(
return condition;
});
- // Build the funnel query - first part to calculate visitors at each step
+ // Build the funnel query - session-based tracking
const query = `
WITH
- -- Get all user actions in the time period
- UserActions AS (
+ -- Get all session actions in the time period
+ SessionActions AS (
SELECT
- user_id,
+ session_id,
timestamp,
pathname,
event_name,
@@ -104,18 +108,17 @@ export async function getFunnel(
site_id = {siteId:Int32}
${timeStatement}
${filterStatement}
- AND user_id != ''
),
- -- Initial step (all users who completed step 1)
+ -- Initial step (all sessions who completed step 1)
Step1 AS (
SELECT DISTINCT
- user_id,
+ session_id,
min(timestamp) as step_time
- FROM UserActions
+ FROM SessionActions
WHERE ${stepConditions[0]}
- GROUP BY user_id
+ GROUP BY session_id
)
-
+
-- Calculate each funnel step
${steps
.slice(1)
@@ -123,19 +126,19 @@ export async function getFunnel(
(step, index) => `
, Step${index + 2} AS (
SELECT DISTINCT
- s${index + 1}.user_id,
- min(ua.timestamp) as step_time
+ s${index + 1}.session_id,
+ min(sa.timestamp) as step_time
FROM Step${index + 1} s${index + 1}
- JOIN UserActions ua ON s${index + 1}.user_id = ua.user_id
- WHERE
- ua.timestamp > s${index + 1}.step_time
+ JOIN SessionActions sa ON s${index + 1}.session_id = sa.session_id
+ WHERE
+ sa.timestamp > s${index + 1}.step_time
AND ${stepConditions[index + 1]}
- GROUP BY s${index + 1}.user_id
+ GROUP BY s${index + 1}.session_id
)
`
)
.join("")}
-
+
-- Calculate visitor count for each step
, StepCounts AS (
${steps
@@ -144,7 +147,7 @@ export async function getFunnel(
SELECT
${index + 1} as step_number,
${SqlString.escape(step.name || step.value)} as step_name,
- count(DISTINCT user_id) as visitors
+ count(DISTINCT session_id) as visitors
FROM Step${index + 1}
`
)
diff --git a/server/src/api/analytics/funnels/getFunnelStepSessions.ts b/server/src/api/analytics/funnels/getFunnelStepSessions.ts
new file mode 100644
index 000000000..14205de62
--- /dev/null
+++ b/server/src/api/analytics/funnels/getFunnelStepSessions.ts
@@ -0,0 +1,245 @@
+import { FilterParams } from "@rybbit/shared";
+import { FastifyReply, FastifyRequest } from "fastify";
+import SqlString from "sqlstring";
+import { clickhouse } from "../../../db/clickhouse/clickhouse.js";
+import { getTimeStatement, patternToRegex, processResults, getFilterStatement } from "../utils.js";
+import { GetSessionsResponse } from "../getSessions.js";
+
+type FunnelStep = {
+ value: string;
+ name?: string;
+ type: "page" | "event";
+ hostname?: string;
+ eventPropertyKey?: string;
+ eventPropertyValue?: string | number | boolean;
+};
+
+type Funnel = {
+ steps: FunnelStep[];
+};
+
+export interface GetFunnelStepSessionsRequest {
+ Body: Funnel;
+ Params: {
+ site: string;
+ stepNumber: string;
+ };
+ Querystring: FilterParams<{
+ mode: "reached" | "dropped";
+ limit?: number;
+ page: number;
+ }>;
+}
+
+export async function getFunnelStepSessions(req: FastifyRequest<GetFunnelStepSessionsRequest>, res: FastifyReply) {
+ const { steps } = req.body;
+ const { stepNumber: stepNumberStr, site } = req.params;
+ const { mode, page, limit } = req.query;
+
+ const stepNumber = parseInt(stepNumberStr, 10);
+
+ // Validate request
+ if (!steps || steps.length < 2) {
+ return res.status(400).send({ error: "At least 2 steps are required for a funnel" });
+ }
+
+ if (isNaN(stepNumber) || stepNumber < 1 || stepNumber > steps.length) {
+ return res.status(400).send({ error: "Invalid step number" });
+ }
+
+ if (mode !== "reached" && mode !== "dropped") {
+ return res.status(400).send({ error: "Mode must be 'reached' or 'dropped'" });
+ }
+
+ // For final step in "dropped" mode, return empty results (no drop-off possible)
+ if (mode === "dropped" && stepNumber === steps.length) {
+ return res.send({ data: [] });
+ }
+
+ try {
+ const timeStatement = getTimeStatement(req.query);
+ let filterStatement = getFilterStatement(req.query.filters, Number(site), timeStatement);
+
+ // Transform filter statement to use extracted UTM columns instead of map access
+ // since the CTE already extracts utm_source, utm_medium, etc. as separate columns
+ filterStatement = filterStatement
+ .replace(/url_parameters\['utm_source'\]/g, "utm_source")
+ .replace(/url_parameters\['utm_medium'\]/g, "utm_medium")
+ .replace(/url_parameters\['utm_campaign'\]/g, "utm_campaign")
+ .replace(/url_parameters\['utm_term'\]/g, "utm_term")
+ .replace(/url_parameters\['utm_content'\]/g, "utm_content");
+
+ // Build conditional statements for each step we need
+ const stepsToCheck = mode === "reached" ? stepNumber : stepNumber + 1;
+ const stepConditions = steps.slice(0, stepsToCheck).map((step, idx) => {
+ let condition = "";
+
+ if (step.type === "page") {
+ const regex = patternToRegex(step.value);
+ condition = `type = 'pageview' AND match(pathname, ${SqlString.escape(regex)})`;
+ } else {
+ condition = `type = 'custom_event' AND event_name = ${SqlString.escape(step.value)}`;
+
+ if (step.eventPropertyKey && step.eventPropertyValue !== undefined) {
+ const propValueAccessor = `props.${SqlString.escapeId(step.eventPropertyKey)}`;
+
+ if (typeof step.eventPropertyValue === "string") {
+ condition += ` AND toString(${propValueAccessor}) = ${SqlString.escape(step.eventPropertyValue)}`;
+ } else if (typeof step.eventPropertyValue === "number") {
+ condition += ` AND toFloat64OrNull(${propValueAccessor}) = ${SqlString.escape(step.eventPropertyValue)}`;
+ } else if (typeof step.eventPropertyValue === "boolean") {
+ condition += ` AND toUInt8OrNull(${propValueAccessor}) = ${step.eventPropertyValue ? 1 : 0}`;
+ }
+ }
+ }
+
+ if (step.hostname) {
+ condition += ` AND hostname = ${SqlString.escape(step.hostname)}`;
+ }
+
+ return condition;
+ });
+
+ // Build CTEs for each funnel step to identify qualifying sessions
+ const stepCTEs = [
+ `
+ SessionActions AS (
+ SELECT
+ session_id,
+ timestamp,
+ pathname,
+ event_name,
+ type,
+ props,
+ hostname
+ FROM events
+ WHERE
+ site_id = {siteId:Int32}
+ ${timeStatement}
+ ${filterStatement}
+ ),
+ Step1 AS (
+ SELECT DISTINCT
+ session_id,
+ min(timestamp) as step_time
+ FROM SessionActions
+ WHERE ${stepConditions[0]}
+ GROUP BY session_id
+ )`,
+ ];
+
+ // Add CTEs for steps 2 through stepNumber (and +1 for dropped mode)
+ for (let i = 1; i < stepsToCheck; i++) {
+ stepCTEs.push(`
+ Step${i + 1} AS (
+ SELECT DISTINCT
+ s${i}.session_id,
+ min(sa.timestamp) as step_time
+ FROM Step${i} s${i}
+ JOIN SessionActions sa ON s${i}.session_id = sa.session_id
+ WHERE
+ sa.timestamp > s${i}.step_time
+ AND ${stepConditions[i]}
+ GROUP BY s${i}.session_id
+ )`);
+ }
+
+ // Determine which sessions to retrieve
+ let targetSessionsCTE = "";
+ if (mode === "reached") {
+ // Sessions that completed step N
+ targetSessionsCTE = `
+ TargetSessions AS (
+ SELECT session_id
+ FROM Step${stepNumber}
+ )`;
+ } else {
+ // Sessions that completed step N but NOT step N+1
+ targetSessionsCTE = `
+ TargetSessions AS (
+ SELECT session_id
+ FROM Step${stepNumber}
+ WHERE session_id NOT IN (
+ SELECT session_id
+ FROM Step${stepNumber + 1}
+ )
+ )`;
+ }
+
+ // Build main query to aggregate session data
+ const query = `
+ WITH
+ ${stepCTEs.join(",\n")}
+ ,
+ ${targetSessionsCTE}
+ ,
+ AggregatedSessions AS (
+ SELECT
+ e.session_id,
+ e.user_id,
+ argMax(e.country, e.timestamp) AS country,
+ argMax(e.region, e.timestamp) AS region,
+ argMax(e.city, e.timestamp) AS city,
+ argMax(e.language, e.timestamp) AS language,
+ argMax(e.device_type, e.timestamp) AS device_type,
+ argMax(e.browser, e.timestamp) AS browser,
+ argMax(e.browser_version, e.timestamp) AS browser_version,
+ argMax(e.operating_system, e.timestamp) AS operating_system,
+ argMax(e.operating_system_version, e.timestamp) AS operating_system_version,
+ argMax(e.screen_width, e.timestamp) AS screen_width,
+ argMax(e.screen_height, e.timestamp) AS screen_height,
+ argMin(e.referrer, e.timestamp) AS referrer,
+ argMin(e.channel, e.timestamp) AS channel,
+ argMin(e.hostname, e.timestamp) AS hostname,
+ argMin(e.page_title, e.timestamp) AS page_title,
+ argMin(e.querystring, e.timestamp) AS querystring,
+ argMin(e.url_parameters, e.timestamp)['utm_source'] AS utm_source,
+ argMin(e.url_parameters, e.timestamp)['utm_medium'] AS utm_medium,
+ argMin(e.url_parameters, e.timestamp)['utm_campaign'] AS utm_campaign,
+ argMin(e.url_parameters, e.timestamp)['utm_term'] AS utm_term,
+ argMin(e.url_parameters, e.timestamp)['utm_content'] AS utm_content,
+ MAX(e.timestamp) AS session_end,
+ MIN(e.timestamp) AS session_start,
+ dateDiff('second', MIN(e.timestamp), MAX(e.timestamp)) AS session_duration,
+ argMinIf(e.pathname, e.timestamp, e.type = 'pageview') AS entry_page,
+ argMaxIf(e.pathname, e.timestamp, e.type = 'pageview') AS exit_page,
+ countIf(e.type = 'pageview') AS pageviews,
+ countIf(e.type = 'custom_event') AS events,
+ countIf(e.type = 'error') AS errors,
+ countIf(e.type = 'outbound') AS outbound,
+ argMax(e.ip, e.timestamp) AS ip,
+ argMax(e.lat, e.timestamp) AS lat,
+ argMax(e.lon, e.timestamp) AS lon
+ FROM events e
+ INNER JOIN TargetSessions ts ON e.session_id = ts.session_id
+ WHERE
+ e.site_id = {siteId:Int32}
+ ${timeStatement}
+ GROUP BY
+ e.session_id,
+ e.user_id
+ ORDER BY session_end DESC
+ )
+ SELECT *
+ FROM AggregatedSessions
+ WHERE 1 = 1 ${filterStatement}
+ LIMIT {limit:Int32} OFFSET {offset:Int32}
+ `;
+
+ const result = await clickhouse.query({
+ query,
+ format: "JSONEachRow",
+ query_params: {
+ siteId: Number(site),
+ limit: limit || 25,
+ offset: (page - 1) * (limit || 25),
+ },
+ });
+
+ const data = await processResults<GetSessionsResponse[number]>(result);
+ return res.send({ data });
+ } catch (error) {
+ console.error("Error fetching funnel step sessions:", error);
+ return res.status(500).send({ error: "Failed to fetch funnel step sessions" });
+ }
+}
diff --git a/server/src/api/analytics/goals/getGoalSessions.ts b/server/src/api/analytics/goals/getGoalSessions.ts
new file mode 100644
index 000000000..59ea554fc
--- /dev/null
+++ b/server/src/api/analytics/goals/getGoalSessions.ts
@@ -0,0 +1,164 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import { clickhouse } from "../../../db/clickhouse/clickhouse.js";
+import { db } from "../../../db/postgres/postgres.js";
+import { goals } from "../../../db/postgres/schema.js";
+import { eq } from "drizzle-orm";
+import { getTimeStatement, processResults, patternToRegex } from "../utils.js";
+import { FilterParams } from "@rybbit/shared";
+import { GetSessionsResponse } from "../getSessions.js";
+import SqlString from "sqlstring";
+
+export interface GetGoalSessionsRequest {
+ Params: {
+ site: string;
+ goalId: string;
+ };
+ Querystring: FilterParams<{
+ limit?: number;
+ page: number;
+ }>;
+}
+
+export async function getGoalSessions(req: FastifyRequest<GetGoalSessionsRequest>, res: FastifyReply) {
+ const { goalId, site } = req.params;
+ const { page, limit } = req.query;
+
+ try {
+ // Fetch the goal from PostgreSQL
+ const goal = await db
+ .select()
+ .from(goals)
+ .where(eq(goals.goalId, Number(goalId)))
+ .limit(1);
+
+ if (!goal || goal.length === 0) {
+ return res.status(404).send({ error: "Goal not found" });
+ }
+
+ const goalData = goal[0];
+
+ // Verify the goal belongs to the site
+ if (goalData.siteId !== Number(site)) {
+ return res.status(403).send({ error: "Goal does not belong to this site" });
+ }
+
+ const timeStatement = getTimeStatement(req.query);
+
+ // Build the goal matching condition
+ let goalCondition = "";
+
+ if (goalData.goalType === "path") {
+ const pathPattern = goalData.config.pathPattern;
+ if (!pathPattern) {
+ return res.status(400).send({ error: "Invalid path goal configuration" });
+ }
+
+ const regex = patternToRegex(pathPattern);
+ goalCondition = `type = 'pageview' AND match(pathname, ${SqlString.escape(regex)})`;
+ } else if (goalData.goalType === "event") {
+ const eventName = goalData.config.eventName;
+ if (!eventName) {
+ return res.status(400).send({ error: "Invalid event goal configuration" });
+ }
+
+ goalCondition = `type = 'custom_event' AND event_name = ${SqlString.escape(eventName)}`;
+
+ // Add property matching if needed
+ const eventPropertyKey = goalData.config.eventPropertyKey;
+ const eventPropertyValue = goalData.config.eventPropertyValue;
+
+ if (eventPropertyKey && eventPropertyValue !== undefined) {
+ const propValueAccessor = `props.${SqlString.escapeId(eventPropertyKey)}`;
+
+ if (typeof eventPropertyValue === "string") {
+ goalCondition += ` AND toString(${propValueAccessor}) = ${SqlString.escape(eventPropertyValue)}`;
+ } else if (typeof eventPropertyValue === "number") {
+ goalCondition += ` AND toFloat64OrNull(${propValueAccessor}) = ${SqlString.escape(eventPropertyValue)}`;
+ } else if (typeof eventPropertyValue === "boolean") {
+ goalCondition += ` AND toUInt8OrNull(${propValueAccessor}) = ${eventPropertyValue ? 1 : 0}`;
+ }
+ }
+ } else {
+ return res.status(400).send({ error: "Invalid goal type" });
+ }
+
+ // Build query to find sessions that match the goal
+ // First, find all session_ids that have at least one event matching the goal
+ const query = `
+ WITH GoalSessions AS (
+ SELECT DISTINCT session_id
+ FROM events
+ WHERE
+ site_id = {siteId:Int32}
+ AND (${goalCondition})
+ ${timeStatement}
+ ),
+ AggregatedSessions AS (
+ SELECT
+ e.session_id,
+ e.user_id,
+ argMax(e.country, e.timestamp) AS country,
+ argMax(e.region, e.timestamp) AS region,
+ argMax(e.city, e.timestamp) AS city,
+ argMax(e.language, e.timestamp) AS language,
+ argMax(e.device_type, e.timestamp) AS device_type,
+ argMax(e.browser, e.timestamp) AS browser,
+ argMax(e.browser_version, e.timestamp) AS browser_version,
+ argMax(e.operating_system, e.timestamp) AS operating_system,
+ argMax(e.operating_system_version, e.timestamp) AS operating_system_version,
+ argMax(e.screen_width, e.timestamp) AS screen_width,
+ argMax(e.screen_height, e.timestamp) AS screen_height,
+ argMin(e.referrer, e.timestamp) AS referrer,
+ argMin(e.channel, e.timestamp) AS channel,
+ argMin(e.hostname, e.timestamp) AS hostname,
+ argMin(e.page_title, e.timestamp) AS page_title,
+ argMin(e.querystring, e.timestamp) AS querystring,
+ argMin(e.url_parameters, e.timestamp)['utm_source'] AS utm_source,
+ argMin(e.url_parameters, e.timestamp)['utm_medium'] AS utm_medium,
+ argMin(e.url_parameters, e.timestamp)['utm_campaign'] AS utm_campaign,
+ argMin(e.url_parameters, e.timestamp)['utm_term'] AS utm_term,
+ argMin(e.url_parameters, e.timestamp)['utm_content'] AS utm_content,
+ MAX(e.timestamp) AS session_end,
+ MIN(e.timestamp) AS session_start,
+ dateDiff('second', MIN(e.timestamp), MAX(e.timestamp)) AS session_duration,
+ argMinIf(e.pathname, e.timestamp, e.type = 'pageview') AS entry_page,
+ argMaxIf(e.pathname, e.timestamp, e.type = 'pageview') AS exit_page,
+ countIf(e.type = 'pageview') AS pageviews,
+ countIf(e.type = 'custom_event') AS events,
+ countIf(e.type = 'error') AS errors,
+ countIf(e.type = 'outbound') AS outbound,
+ argMax(e.ip, e.timestamp) AS ip,
+ argMax(e.lat, e.timestamp) AS lat,
+ argMax(e.lon, e.timestamp) AS lon
+ FROM events e
+ INNER JOIN GoalSessions gs ON e.session_id = gs.session_id
+ WHERE
+ e.site_id = {siteId:Int32}
+ ${timeStatement}
+ GROUP BY
+ e.session_id,
+ e.user_id
+ ORDER BY session_end DESC
+ )
+ SELECT *
+ FROM AggregatedSessions
+ LIMIT {limit:Int32} OFFSET {offset:Int32}
+ `;
+
+ const result = await clickhouse.query({
+ query,
+ format: "JSONEachRow",
+ query_params: {
+ siteId: Number(site),
+ limit: limit || 25,
+ offset: (page - 1) * (limit || 25),
+ },
+ });
+
+ const data = await processResults<GetSessionsResponse[number]>(result);
+ return res.send({ data });
+ } catch (error) {
+ console.error("Error fetching goal sessions:", error);
+ return res.status(500).send({ error: "Failed to fetch goal sessions" });
+ }
+}
diff --git a/server/src/index.ts b/server/src/index.ts
index 6ec87129a..eaaa85763 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -15,6 +15,7 @@ import { getOutboundLinks } from "./api/analytics/events/getOutboundLinks.js";
import { createFunnel } from "./api/analytics/funnels/createFunnel.js";
import { deleteFunnel } from "./api/analytics/funnels/deleteFunnel.js";
import { getFunnel } from "./api/analytics/funnels/getFunnel.js";
+import { getFunnelStepSessions } from "./api/analytics/funnels/getFunnelStepSessions.js";
import { getFunnels } from "./api/analytics/funnels/getFunnels.js";
import { getErrorBucketed } from "./api/analytics/getErrorBucketed.js";
import { getErrorEvents } from "./api/analytics/getErrorEvents.js";
@@ -37,6 +38,7 @@ import { getUsers } from "./api/analytics/getUsers.js";
import { createGoal } from "./api/analytics/goals/createGoal.js";
import { deleteGoal } from "./api/analytics/goals/deleteGoal.js";
import { getGoals } from "./api/analytics/goals/getGoals.js";
+import { getGoalSessions } from "./api/analytics/goals/getGoalSessions.js";
import { updateGoal } from "./api/analytics/goals/updateGoal.js";
import { getPerformanceByDimension } from "./api/analytics/performance/getPerformanceByDimension.js";
import { getPerformanceOverview } from "./api/analytics/performance/getPerformanceOverview.js";
@@ -235,9 +237,11 @@ const ANALYTICS_ROUTES = [
"/api/session-locations/",
"/api/funnels/",
"/api/funnel/",
+ "/api/funnel/:stepNumber/sessions/",
"/api/journeys/",
"/api/goals/",
"/api/goal/",
+ "/api/goals/:goalId/sessions/",
"/api/analytics/events/names/",
"/api/analytics/events/properties/",
"/api/events/",
@@ -327,9 +331,11 @@ server.get("/api/session-locations/:site", getSessionLocations);
server.get("/api/funnels/:site", getFunnels);
server.get("/api/journeys/:site", getJourneys);
server.post("/api/funnel/:site", getFunnel);
+server.post("/api/funnel/:stepNumber/sessions/:site", getFunnelStepSessions);
server.post("/api/funnel/create/:site", createFunnel);
server.delete("/api/funnel/:funnelId", deleteFunnel);
server.get("/api/goals/:site", getGoals);
+server.get("/api/goals/:goalId/sessions/:site", getGoalSessions);
server.post("/api/goal/create", createGoal);
server.delete("/api/goal/:goalId", deleteGoal);
server.put("/api/goal/update", updateGoal);