Skip to content

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

Refactor date handling and enhance Sidebar functionality

Bill Yangd3d611401170
diff --git a/client/src/api/analytics/useGetFunnel.ts b/client/src/api/analytics/useGetFunnel.ts
new file mode 100644
index 000000000..66ce26fad
--- /dev/null
+++ b/client/src/api/analytics/useGetFunnel.ts
@@ -0,0 +1,51 @@
+import { useMutation } from "@tanstack/react-query";
+import { BACKEND_URL } from "../../lib/const";
+import { authedFetch } from "../utils";
+import { useStore } from "../../lib/store";
+
+export type FunnelStep = {
+ value: string;
+ name?: string;
+ type: "page" | "event";
+};
+
+export type FunnelRequest = {
+ steps: FunnelStep[];
+ startDate: string;
+ endDate: string;
+ timezone: string;
+};
+
+export type FunnelResponse = {
+ step_number: number;
+ step_name: string;
+ visitors: number;
+ conversion_rate: number;
+ dropoff_rate: number;
+};
+
+/**
+ * Hook for analyzing conversion funnels through a series of steps
+ */
+export function useGetFunnel() {
+ const { site } = useStore();
+
+ return useMutation<{ data: FunnelResponse[] }, Error, FunnelRequest>({
+ mutationFn: async (funnelConfig) => {
+ const response = await authedFetch(`${BACKEND_URL}/funnel/${site}`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(funnelConfig),
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || "Failed to analyze funnel");
+ }
+
+ return response.json();
+ },
+ });
+}
diff --git a/client/src/api/utils.ts b/client/src/api/utils.ts
index 582745451..822ab9ab5 100644
--- a/client/src/api/utils.ts
+++ b/client/src/api/utils.ts
@@ -1,8 +1,8 @@
-import { Time } from "@/lib/store";
import { DateTime } from "luxon";
import { APIResponse } from "./types";
import { useQuery, UseQueryResult } from "@tanstack/react-query";
import { BACKEND_URL } from "../lib/const";
+import { Time } from "../components/DateSelector/types";
export function getStartAndEndDate(time: Time) {
if (time.mode === "range") {
diff --git a/client/src/app/[site]/components/Sidebar/Sidebar.tsx b/client/src/app/[site]/components/Sidebar/Sidebar.tsx
index 58f59d6bc..b150b09c7 100644
--- a/client/src/app/[site]/components/Sidebar/Sidebar.tsx
+++ b/client/src/app/[site]/components/Sidebar/Sidebar.tsx
@@ -15,6 +15,7 @@ import LiveUserCount from "./LiveUserCount";
import { SiteSettings } from "../../../../components/SiteSettings/SiteSettings";
import { Button } from "../../../../components/ui/button";
import { SiteSelector } from "./SiteSelector";
+import { Funnel } from "@phosphor-icons/react/dist/ssr";
export function Sidebar() {
const { data: sites } = useGetSites();
@@ -69,6 +70,12 @@ export function Sidebar() {
href={getTabPath("retention")}
icon={<LayoutGrid className="w-4 h-4" />}
/>
+ <SidebarLink
+ label="Funnels"
+ active={isActiveTab("funnels")}
+ href={getTabPath("funnels")}
+ icon={<Funnel weight="bold" />}
+ />
<SidebarLink
label="Reports"
active={isActiveTab("reports")}
diff --git a/client/src/app/[site]/components/SubHeader/SubHeader.tsx b/client/src/app/[site]/components/SubHeader/SubHeader.tsx
index 72d8f034f..e4cbf5506 100644
--- a/client/src/app/[site]/components/SubHeader/SubHeader.tsx
+++ b/client/src/app/[site]/components/SubHeader/SubHeader.tsx
@@ -2,13 +2,14 @@
import { Filters } from "./Filters/Filters";
import { Button } from "@/components/ui/button";
-import { goBack, goForward, Time, useStore } from "@/lib/store";
+import { goBack, goForward, useStore } from "@/lib/store";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { DateTime } from "luxon";
import { usePathname } from "next/navigation";
import { useGetSites } from "../../../../api/admin/sites";
-import { DateSelector } from "./DateSelector";
+import { DateSelector } from "../../../../components/DateSelector/DateSelector";
+import { Time } from "../../../../components/DateSelector/types";
const canGoForward = (time: Time) => {
const currentDay = DateTime.now().startOf("day");
@@ -36,7 +37,7 @@ const canGoForward = (time: Time) => {
};
export function SubHeader() {
- const { time } = useStore();
+ const { time, setTime } = useStore();
const { data: sites } = useGetSites();
const pathname = usePathname();
@@ -46,7 +47,7 @@ export function SubHeader() {
<div className="flex gap-2 mb-3 mt-1 justify-between">
<Filters />
<div className="flex items-center gap-2">
- <DateSelector />
+ <DateSelector time={time} setTime={setTime} />
<div className="flex items-center">
<Button variant="default" size="icon" onClick={goBack}>
<ChevronLeft />
diff --git a/client/src/app/[site]/funnels/components/CreateFunnel.tsx b/client/src/app/[site]/funnels/components/CreateFunnel.tsx
new file mode 100644
index 000000000..54db8c7fd
--- /dev/null
+++ b/client/src/app/[site]/funnels/components/CreateFunnel.tsx
@@ -0,0 +1,3 @@
+export function CreateFunnel() {
+ return <div>CreateFunnel</div>;
+}
diff --git a/client/src/app/[site]/funnels/page.tsx b/client/src/app/[site]/funnels/page.tsx
new file mode 100644
index 000000000..cf20e2d2d
--- /dev/null
+++ b/client/src/app/[site]/funnels/page.tsx
@@ -0,0 +1,3 @@
+export default function FunnelsPage() {
+ return <div>Funnels</div>;
+}
diff --git a/client/src/app/[site]/main/components/MainSection/BucketSelection.tsx b/client/src/app/[site]/main/components/MainSection/BucketSelection.tsx
index 19f5983c4..80d58f7a6 100644
--- a/client/src/app/[site]/main/components/MainSection/BucketSelection.tsx
+++ b/client/src/app/[site]/main/components/MainSection/BucketSelection.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Time, useStore } from "@/lib/store";
+import { useStore } from "@/lib/store";
import {
SelectItem,
Select,
@@ -9,6 +9,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import { DateTime } from "luxon";
+import { Time } from "../../../../../components/DateSelector/types";
const getOptions = (time: Time) => {
if (time.mode === "day") {
diff --git a/client/src/app/[site]/main/components/MainSection/Chart.tsx b/client/src/app/[site]/main/components/MainSection/Chart.tsx
index e85bce9dc..af0a8483b 100644
--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx
@@ -1,11 +1,12 @@
"use client";
import { nivoTheme } from "@/lib/nivo";
-import { StatType, Time, TimeBucket, useStore } from "@/lib/store";
+import { StatType, TimeBucket, useStore } from "@/lib/store";
import { ResponsiveLine } from "@nivo/line";
import { DateTime } from "luxon";
import { formatSecondsAsMinutesAndSeconds } from "../../../../../lib/utils";
import { APIResponse } from "../../../../../api/types";
import { GetOverviewBucketedResponse } from "../../../../../api/analytics/useGetOverviewBucketed";
+import { Time } from "../../../../../components/DateSelector/types";
export const formatter = Intl.NumberFormat("en", { notation: "compact" });
diff --git a/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx b/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
index 7c4ee5981..911f0a26a 100644
--- a/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
@@ -1,11 +1,12 @@
"use client";
import { nivoTheme } from "@/lib/nivo";
-import { Time, useStore } from "@/lib/store";
+import { useStore } from "@/lib/store";
import { ResponsiveLine } from "@nivo/line";
import { DateTime } from "luxon";
import { useMemo } from "react";
import { APIResponse } from "../../../../../api/types";
import { GetOverviewBucketedResponse } from "../../../../../api/analytics/useGetOverviewBucketed";
+import { Time } from "../../../../../components/DateSelector/types";
const getMin = (time: Time) => {
if (time.mode === "day") {
diff --git a/client/src/app/[site]/components/SubHeader/CustomDateRangePicker.tsx b/client/src/components/DateSelector/CustomDateRangePicker.tsx
similarity index 92%
rename from client/src/app/[site]/components/SubHeader/CustomDateRangePicker.tsx
rename to client/src/components/DateSelector/CustomDateRangePicker.tsx
index 9606986dc..16674d9c9 100644
--- a/client/src/app/[site]/components/SubHeader/CustomDateRangePicker.tsx
+++ b/client/src/components/DateSelector/CustomDateRangePicker.tsx
@@ -11,13 +11,16 @@ import {
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
-import { useStore } from "../../../../lib/store";
+import { Time } from "./types";
export function CustomDateRangePicker({
className,
-}: React.HTMLAttributes<HTMLDivElement>) {
+ setTime,
+}: {
+ className?: string;
+ setTime: (time: Time) => void;
+}) {
const [date, setDate] = React.useState<DateRange | undefined>();
- const { setTime } = useStore();
return (
<div className={cn("grid gap-2", className)}>
diff --git a/client/src/app/[site]/components/SubHeader/DateSelector.tsx b/client/src/components/DateSelector/DateSelector.tsx
similarity index 96%
rename from client/src/app/[site]/components/SubHeader/DateSelector.tsx
rename to client/src/components/DateSelector/DateSelector.tsx
index 605e581f9..0e71bbd43 100644
--- a/client/src/app/[site]/components/SubHeader/DateSelector.tsx
+++ b/client/src/components/DateSelector/DateSelector.tsx
@@ -7,10 +7,10 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import { Time, useStore } from "@/lib/store";
import { DateTime } from "luxon";
import { CustomDateRangePicker } from "./CustomDateRangePicker";
import { Calendar, Calendar1 } from "lucide-react";
+import { Time } from "./types";
const getLabel = (time: Time) => {
if (time.mode === "range") {
@@ -66,9 +66,13 @@ const getLabel = (time: Time) => {
}
};
-export function DateSelector() {
- const { time, setTime } = useStore();
-
+export function DateSelector({
+ time,
+ setTime,
+}: {
+ time: Time;
+ setTime: (time: Time) => void;
+}) {
return (
<DropdownMenu>
<DropdownMenuTrigger>
@@ -187,7 +191,7 @@ export function DateSelector() {
All Time
</DropdownMenuItem>
<DropdownMenuSeparator />
- <CustomDateRangePicker />
+ <CustomDateRangePicker setTime={setTime} />
</DropdownMenuContent>
</DropdownMenu>
);
diff --git a/client/src/components/DateSelector/types.ts b/client/src/components/DateSelector/types.ts
new file mode 100644
index 000000000..d898fb50c
--- /dev/null
+++ b/client/src/components/DateSelector/types.ts
@@ -0,0 +1,43 @@
+export type DateMode = {
+ mode: "day";
+ day: string;
+};
+
+export type DateRangeMode = {
+ mode: "range";
+ startDate: string;
+ endDate: string;
+ wellKnown?:
+ | "Last 3 days"
+ | "Last 7 days"
+ | "Last 14 days"
+ | "Last 30 days"
+ | "Last 60 days";
+};
+
+export type WeekMode = {
+ mode: "week";
+ week: string;
+};
+
+export type MonthMode = {
+ mode: "month";
+ month: string;
+};
+
+export type YearMode = {
+ mode: "year";
+ year: string;
+};
+
+export type AllTimeMode = {
+ mode: "all-time";
+};
+
+export type Time =
+ | DateMode
+ | DateRangeMode
+ | WeekMode
+ | MonthMode
+ | YearMode
+ | AllTimeMode;
diff --git a/client/src/lib/store.ts b/client/src/lib/store.ts
index 40157a8bb..8d38fa78a 100644
--- a/client/src/lib/store.ts
+++ b/client/src/lib/store.ts
@@ -1,49 +1,6 @@
import { DateTime } from "luxon";
import { create } from "zustand";
-
-type DateMode = {
- mode: "day";
- day: string;
-};
-
-type DateRangeMode = {
- mode: "range";
- startDate: string;
- endDate: string;
- wellKnown?:
- | "Last 3 days"
- | "Last 7 days"
- | "Last 14 days"
- | "Last 30 days"
- | "Last 60 days";
-};
-
-type WeekMode = {
- mode: "week";
- week: string;
-};
-
-type MonthMode = {
- mode: "month";
- month: string;
-};
-
-type YearMode = {
- mode: "year";
- year: string;
-};
-
-type AllTimeMode = {
- mode: "all-time";
-};
-
-export type Time =
- | DateMode
- | DateRangeMode
- | WeekMode
- | MonthMode
- | YearMode
- | AllTimeMode;
+import { Time } from "../components/DateSelector/types";
export type TimeBucket =
| "minute"
diff --git a/client/src/lib/urlParams.ts b/client/src/lib/urlParams.ts
index 85ba678ab..6d258f85e 100644
--- a/client/src/lib/urlParams.ts
+++ b/client/src/lib/urlParams.ts
@@ -1,8 +1,7 @@
-import { useSearchParams, usePathname, useRouter } from "next/navigation";
-import { useEffect } from "react";
-import { DateTime } from "luxon";
-import { Filter, Time, TimeBucket, StatType, useStore } from "./store";
-import React from "react";
+import { usePathname, useRouter, useSearchParams } from "next/navigation";
+import React, { useEffect } from "react";
+import { Time } from "../components/DateSelector/types";
+import { Filter, StatType, TimeBucket, useStore } from "./store";
// Serialize store state to URL parameters
export const serializeStateToUrl = (
diff --git a/server/src/api/getFunnel.ts b/server/src/api/getFunnel.ts
new file mode 100644
index 000000000..5521426a0
--- /dev/null
+++ b/server/src/api/getFunnel.ts
@@ -0,0 +1,160 @@
+import { FastifyRequest } from "fastify";
+import { FastifyReply } from "fastify";
+import clickhouse from "../db/clickhouse/clickhouse.js";
+import { getTimeStatement, processResults } from "./utils.js";
+import { getUserHasAccessToSite } from "../lib/auth-utils.js";
+
+type FunnelStep = {
+ value: string;
+ name?: string;
+ type: "page" | "event";
+};
+
+type Funnel = {
+ steps: FunnelStep[];
+ startDate: string;
+ endDate: string;
+ timezone: string;
+};
+
+type FunnelResponse = {
+ step_number: number;
+ step_name: string;
+ visitors: number;
+ conversion_rate: number;
+ dropoff_rate: number;
+};
+
+export async function getFunnel(
+ request: FastifyRequest<{
+ Body: Funnel;
+ Params: {
+ site: string;
+ };
+ }>,
+ reply: FastifyReply
+) {
+ const { steps, startDate, endDate, timezone } = request.body;
+ const { site } = request.params;
+
+ // Validate request
+ if (!steps || steps.length < 2) {
+ return reply
+ .status(400)
+ .send({ error: "At least 2 steps are required for a funnel" });
+ }
+
+ // Check user access to site
+ const userHasAccessToSite = await getUserHasAccessToSite(request, site);
+ if (!userHasAccessToSite) {
+ return reply.status(403).send({ error: "Forbidden" });
+ }
+
+ // Build funnel query
+ try {
+ // Create the time statement for the date range
+ const timeStatement = getTimeStatement({
+ date: { startDate, endDate, timezone },
+ });
+
+ // Build conditional statements for each step
+ const stepConditions = steps.map((step) => {
+ if (step.type === "page") {
+ return `pathname = '${step.value}'`;
+ } else {
+ return `type = 'custom_event' AND event_name = '${step.value}'`;
+ }
+ });
+
+ // Build the funnel query
+ const query = `
+ WITH
+ -- Get all user actions in the time period
+ UserActions AS (
+ SELECT
+ user_id,
+ timestamp,
+ pathname,
+ event_name,
+ type
+ FROM pageviews
+ WHERE
+ site_id = ${site}
+ ${timeStatement}
+ AND user_id != ''
+ ),
+ -- Initial step (all users who completed step 1)
+ Step1 AS (
+ SELECT DISTINCT
+ user_id,
+ min(timestamp) as step_time
+ FROM UserActions
+ WHERE ${stepConditions[0]}
+ GROUP BY user_id
+ )
+
+ -- Calculate each funnel step
+ ${steps
+ .slice(1)
+ .map(
+ (step, index) => `
+ , Step${index + 2} AS (
+ SELECT DISTINCT
+ s${index + 1}.user_id,
+ min(ua.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
+ AND ${stepConditions[index + 1]}
+ GROUP BY s${index + 1}.user_id
+ )
+ `
+ )
+ .join("")}
+
+ -- Final results
+ SELECT
+ step_number,
+ step_name,
+ visitors,
+ round(visitors * 100.0 / first_step, 2) as conversion_rate,
+ round((1 - (visitors / prev_step)) * 100.0, 2) as dropoff_rate
+ FROM (
+ ${steps
+ .map(
+ (step, index) => `
+ SELECT
+ ${index + 1} as step_number,
+ '${step.name || step.value}' as step_name,
+ count(DISTINCT user_id) as visitors,
+ FIRST_VALUE(count(DISTINCT user_id)) OVER (ORDER BY ${
+ index + 1
+ }) as first_step,
+ LAG(count(DISTINCT user_id), 1, count(DISTINCT user_id)) OVER (ORDER BY ${
+ index + 1
+ }) as prev_step
+ FROM Step${index + 1}
+ `
+ )
+ .join("\nUNION ALL\n")}
+ )
+ ORDER BY step_number
+ `;
+
+ // Execute the query
+ const result = await clickhouse.query({
+ query,
+ format: "JSONEachRow",
+ });
+
+ // Process the results
+ const data = await processResults<FunnelResponse>(result);
+ return reply.send({ data });
+ } catch (error) {
+ console.error("Error executing funnel query:", error);
+ return reply
+ .status(500)
+ .send({ error: "Failed to execute funnel analysis" });
+ }
+}
diff --git a/server/src/api/sites/addFunnel.ts b/server/src/api/sites/addFunnel.ts
new file mode 100644
index 000000000..b695898ca
--- /dev/null
+++ b/server/src/api/sites/addFunnel.ts
@@ -0,0 +1,12 @@
+import { FastifyReply } from "fastify";
+
+import { FastifyRequest } from "fastify";
+
+export function addFunnel(
+ request: FastifyRequest<{
+ Body: { domain: string; name: string; organizationId: string };
+ }>,
+ reply: FastifyReply
+) {
+ const { domain, name, organizationId } = request.body;
+}
diff --git a/server/src/index.ts b/server/src/index.ts
index 54d04fb82..ffeb2130a 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -34,6 +34,7 @@ import { getUserSubscription } from "./api/user/getUserSubscription.js";
import { getUserInfo } from "./api/getUserInfo.js";
import { getLiveSessionLocations } from "./api/getLiveSessionLocations.js";
import { getRetention } from "./api/getRetention.js";
+import { getFunnel } from "./api/getFunnel.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -135,6 +136,7 @@ server.get("/session/:sessionId", getSession);
server.get("/user/:userId/sessions", getUserSessions);
server.get("/user/info/:siteId/:userId", getUserInfo);
server.get("/live-session-locations/:siteId", getLiveSessionLocations);
+server.get("/funnel/:site", getFunnel);
// Administrative
server.post("/add-site", addSite);