🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Enhance funnel creation and analysis functionality (#76)
Bill Yang93b13d48e2e0
diff --git a/client/package-lock.json b/client/package-lock.jsonindex 3aac62270..b85fcdacb 100644--- a/client/package-lock.json+++ b/client/package-lock.json@@ -47,7 +47,7 @@"ldrs": "^1.0.2","leaflet": "^1.9.4","lodash": "^4.17.21",- "lucide-react": "^0.474.0",+ "lucide-react": "^0.487.0","luxon": "^3.5.0","next": "15.1.6","next-themes": "^0.4.4",@@ -5616,9 +5616,9 @@"dev": true},"node_modules/lucide-react": {- "version": "0.474.0",- "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.474.0.tgz",- "integrity": "sha512-CmghgHkh0OJNmxGKWc0qfPJCYHASPMVSyGY8fj3xgk4v84ItqDg64JNKFZn5hC6E0vHi6gxnbCgwhyVB09wQtA==",+ "version": "0.487.0",+ "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.487.0.tgz",+ "integrity": "sha512-aKqhOQ+YmFnwq8dWgGjOuLc8V1R9/c/yOd+zDY4+ohsR2Jo05lSGc3WsstYPIzcTpeosN7LoCkLReUUITvaIvw==","peerDependencies": {"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"}diff --git a/client/package.json b/client/package.jsonindex fa969767c..7bca5f62e 100644--- a/client/package.json+++ b/client/package.json@@ -48,7 +48,7 @@"ldrs": "^1.0.2","leaflet": "^1.9.4","lodash": "^4.17.21",- "lucide-react": "^0.474.0",+ "lucide-react": "^0.487.0","luxon": "^3.5.0","next": "15.1.6","next-themes": "^0.4.4",diff --git a/client/src/api/analytics/useDeleteFunnel.ts b/client/src/api/analytics/useDeleteFunnel.tsnew file mode 100644index 000000000..5412c5360--- /dev/null+++ b/client/src/api/analytics/useDeleteFunnel.ts@@ -0,0 +1,29 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { BACKEND_URL } from "../../lib/const";+import { authedFetch } from "../utils";++/**+ * Hook for deleting a saved funnel report+ */+export function useDeleteFunnel() {+ const queryClient = useQueryClient();++ return useMutation<{ success: boolean }, Error, number>({+ mutationFn: async (reportId) => {+ const response = await authedFetch(`${BACKEND_URL}/report/${reportId}`, {+ method: "DELETE",+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.error || "Failed to delete funnel");+ }++ return response.json();+ },+ onSuccess: () => {+ // Invalidate the funnels query to refresh the list+ queryClient.invalidateQueries({ queryKey: ["funnels"] });+ },+ });+}diff --git a/client/src/api/analytics/useGetFunnel.ts b/client/src/api/analytics/useGetFunnel.tsindex 66ce26fad..24dc87bd6 100644--- a/client/src/api/analytics/useGetFunnel.ts+++ b/client/src/api/analytics/useGetFunnel.ts@@ -1,4 +1,4 @@-import { useMutation } from "@tanstack/react-query";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { BACKEND_URL } from "../../lib/const";import { authedFetch } from "../utils";import { useStore } from "../../lib/store";@@ -10,10 +10,18 @@ export type FunnelStep = {};export type FunnelRequest = {+ steps: FunnelStep[];+ startDate: string | null;+ endDate: string | null;+ name?: string;+};++export type SaveFunnelRequest = {steps: FunnelStep[];startDate: string;endDate: string;- timezone: string;+ name: string;+ reportId?: number;};export type FunnelResponse = {@@ -27,17 +35,30 @@ export type FunnelResponse = {/*** Hook for analyzing conversion funnels through a series of steps*/-export function useGetFunnel() {+export function useGetFunnel(config?: FunnelRequest) {const { site } = useStore();- return useMutation<{ data: FunnelResponse[] }, Error, FunnelRequest>({- mutationFn: async (funnelConfig) => {+ return useQuery<{ data: FunnelResponse[] }, Error>({+ queryKey: ["funnel", site, config],+ queryFn: async () => {+ console.info(config);+ if (!config) {+ throw new Error("Funnel configuration is required");+ }++ // Add timezone to the request+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ const fullConfig = {+ ...config,+ timezone,+ };+const response = await authedFetch(`${BACKEND_URL}/funnel/${site}`, {method: "POST",headers: {"Content-Type": "application/json",},- body: JSON.stringify(funnelConfig),+ body: JSON.stringify(fullConfig),});if (!response.ok) {@@ -47,5 +68,51 @@ export function useGetFunnel() {return response.json();},+ enabled: !!site && !!config,+ });+}++/**+ * Hook for saving funnel configurations without analyzing them+ */+export function useSaveFunnel() {+ const { site } = useStore();+ const queryClient = useQueryClient();++ return useMutation<+ { success: boolean; funnelId: number },+ Error,+ SaveFunnelRequest+ >({+ mutationFn: async (funnelConfig) => {+ // Add timezone to the request+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ const fullConfig = {+ ...funnelConfig,+ timezone,+ };++ // Save the funnel configuration+ const saveResponse = await authedFetch(+ `${BACKEND_URL}/funnel/create/${site}`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(fullConfig),+ }+ );++ if (!saveResponse.ok) {+ const errorData = await saveResponse.json();+ throw new Error(errorData.error || "Failed to save funnel");+ }++ // Invalidate the funnels query to refresh the list+ queryClient.invalidateQueries({ queryKey: ["funnels", site] });++ return saveResponse.json();+ },});}diff --git a/client/src/api/analytics/useGetFunnels.ts b/client/src/api/analytics/useGetFunnels.tsnew file mode 100644index 000000000..91627dd22--- /dev/null+++ b/client/src/api/analytics/useGetFunnels.ts@@ -0,0 +1,36 @@+import { useQuery } from "@tanstack/react-query";+import { BACKEND_URL } from "../../lib/const";+import { authedFetch } from "../utils";+import { FunnelStep } from "./useGetFunnel";++export interface SavedFunnel {+ id: number;+ name: string;+ steps: FunnelStep[];+ createdAt: string;+ updatedAt: string;+ conversionRate: number | null;+ totalVisitors: number | null;+}++export function useGetFunnels(siteId?: string | number) {+ return useQuery<SavedFunnel[]>({+ queryKey: ["funnels", siteId],+ queryFn: async () => {+ if (!siteId) {+ return [];+ }++ const response = await authedFetch(`${BACKEND_URL}/funnels/${siteId}`);++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.error || "Failed to fetch funnels");+ }++ const result = await response.json();+ return result.data;+ },+ enabled: !!siteId,+ });+}diff --git a/client/src/app/[site]/funnels/components/CreateFunnel.tsx b/client/src/app/[site]/funnels/components/CreateFunnel.tsxindex b3c913986..9e7ea4007 100644--- a/client/src/app/[site]/funnels/components/CreateFunnel.tsx+++ b/client/src/app/[site]/funnels/components/CreateFunnel.tsx@@ -11,19 +11,37 @@ import {SelectTrigger,SelectValue,} from "@/components/ui/select";-import { Plus, Trash2 } from "lucide-react";+import { Plus, Trash2, Search, Save } from "lucide-react";import { Time } from "@/components/DateSelector/types";import { DateTime } from "luxon";-import { useGetFunnel, FunnelStep } from "@/api/analytics/useGetFunnel";+import {+ useGetFunnel,+ FunnelStep,+ useSaveFunnel,+} from "@/api/analytics/useGetFunnel";import { Funnel } from "./Funnel";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+ DialogFooter,+} from "@/components/ui/dialog";+import { useStore } from "@/lib/store";+import { toast } from "sonner";+import { getStartAndEndDate } from "../../../../api/utils";+import { useDebounce } from "@uidotdev/usehooks";++export function CreateFunnelDialog() {+ const [open, setOpen] = useState(false);-export function CreateFunnel() {- // Initial date state - last 30 days+ // Initial date state - last 7 daysconst [time, setTime] = useState<Time>({mode: "range",- startDate: DateTime.now().minus({ days: 30 }).toISODate(),+ startDate: DateTime.now().minus({ days: 7 }).toISODate(),endDate: DateTime.now().toISODate(),- wellKnown: "Last 30 days",+ wellKnown: "Last 7 days",});// Funnel steps state@@ -32,14 +50,37 @@ export function CreateFunnel() {{ type: "page", value: "", name: "" },]);- // Funnel analysis mutation+ // Debounce steps and time changes+ const debouncedSteps = useDebounce(steps, 300);+ const debouncedTime = useDebounce(time, 300);++ // Funnel name+ const [name, setName] = useState("New Funnel");++ const { startDate, endDate } = getStartAndEndDate(debouncedTime);++ // Funnel analysis queryconst {- mutate: analyzeFunnel,data,isError,error,- isPending,- } = useGetFunnel();+ isLoading: isPending,+ } = useGetFunnel(+ debouncedSteps.some((step) => !step.value)+ ? undefined+ : {+ steps: debouncedSteps,+ startDate,+ endDate,+ }+ );++ // Funnel save mutation+ const {+ mutate: saveFunnel,+ isPending: isSaving,+ error: saveError,+ } = useSaveFunnel();// Handle adding a new stepconst addStep = () => {@@ -72,8 +113,24 @@ export function CreateFunnel() {setSteps(newSteps);};- // Handle form submission- const handleSubmit = () => {+ // Query funnel without saving+ const handleQueryFunnel = () => {+ // Validate steps have values+ const hasEmptySteps = steps.some((step) => !step.value);+ if (hasEmptySteps) {+ alert("All steps must have values");+ return;+ }+ };++ // Save funnel configuration+ const handleSaveFunnel = () => {+ // Validate name+ if (!name.trim()) {+ alert("Please enter a funnel name");+ return;+ }+// Validate steps have valuesconst hasEmptySteps = steps.some((step) => !step.value);if (hasEmptySteps) {@@ -81,8 +138,7 @@ export function CreateFunnel() {return;}- // Get timezone and dates- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ // Get dates based on time selectionlet startDate = "",endDate = "";@@ -111,107 +167,191 @@ export function CreateFunnel() {.toISODate();endDate = endDateValue || DateTime.now().toISODate();} else {- // Fall back to last 30 days for all-time- startDate = DateTime.now().minus({ days: 30 }).toISODate();+ // Fall back to last 7 days for all-time+ startDate = DateTime.now().minus({ days: 7 }).toISODate();endDate = DateTime.now().toISODate();}- // Create funnel analysis- analyzeFunnel({- steps,- startDate,- endDate,- timezone,- });+ // Save funnel directly without analyzing+ saveFunnel(+ {+ steps,+ startDate,+ endDate,+ name,+ },+ {+ onSuccess: () => {+ // Close dialog on successful save+ setOpen(false);+ // Optional: Show success message+ toast?.success("Funnel saved successfully");+ },+ onError: (error) => {+ // Show error but don't close dialog+ toast?.error(`Failed to save funnel: ${error.message}`);+ },+ }+ );+ };++ // Reset form when dialog closes+ const handleOpenChange = (open: boolean) => {+ setOpen(open);+ if (!open) {+ // Reset analysis+ }};return (- <div className="grid grid-cols-1 md:grid-cols-2 gap-6">- {/* Left side: Funnel configuration form */}- <Card>- <CardHeader>- <CardTitle>Create Funnel</CardTitle>- </CardHeader>- <CardContent>+ <Dialog open={open} onOpenChange={handleOpenChange}>+ <DialogTrigger asChild>+ <Button className="flex gap-2">+ <Plus className="w-4 h-4" /> Create Funnel+ </Button>+ </DialogTrigger>+ <DialogContent className="max-w-[80vw]">+ <DialogHeader>+ <DialogTitle>Create Funnel</DialogTitle>+ </DialogHeader>++ <div className="grid grid-cols-[600px_3fr] gap-6 my-4">+ {/* Left side: Funnel configuration form */}<div className="space-y-4">- {steps.map((step, index) => (- <div key={index} className="flex flex-col space-y-2">- <div className="flex items-center gap-2">- <div className="flex-shrink-0 w-6 h-6 rounded-full bg-neutral-800 flex items-center justify-center text-xs">- {index + 1}- </div>- <Select- value={step.type}- onValueChange={(value) =>- updateStepType(index, value as "page" | "event")- }- >- <SelectTrigger className="w-[120px]">- <SelectValue placeholder="Type" />- </SelectTrigger>- <SelectContent>- <SelectItem value="page">Page Path</SelectItem>- <SelectItem value="event">Event</SelectItem>- </SelectContent>- </Select>-- <div className="flex-grow flex gap-2">- <Input- placeholder={- step.type === "page"- ? "Path (e.g. /pricing)"- : "Event name"- }- value={step.value}- onChange={(e) =>- updateStep(index, "value", e.target.value)- }- />- <Input- placeholder="Label (optional)"- value={step.name || ""}- onChange={(e) =>- updateStep(index, "name", e.target.value)- }- />+ <div>+ <label className="text-sm font-medium mb-1 block">+ Funnel Name+ </label>+ <Input+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="Enter funnel name"+ />+ </div>++ {/* Funnel Steps in a boxed container */}+ <Card className="border border-neutral-200 dark:border-neutral-800">+ <CardHeader className="px-4 py-3">+ <CardTitle className="text-base">Funnel Steps</CardTitle>+ </CardHeader>+ <CardContent className="px-4 py-3 space-y-4">+ {steps.map((step, index) => (+ <div key={index} className="flex flex-col space-y-2">+ <div className="flex items-center gap-2">+ <div className="flex-shrink-0 w-6 h-6 rounded-full bg-neutral-800 flex items-center justify-center text-xs">+ {index + 1}+ </div>+ <Select+ value={step.type}+ onValueChange={(value) =>+ updateStepType(index, value as "page" | "event")+ }+ >+ <SelectTrigger className="w-[120px]">+ <SelectValue placeholder="Type" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="page">Page Path</SelectItem>+ <SelectItem value="event">Event</SelectItem>+ </SelectContent>+ </Select>++ <div className="flex-grow flex gap-2">+ <Input+ placeholder={+ step.type === "page"+ ? "Path (e.g. /pricing)"+ : "Event name"+ }+ value={step.value}+ onChange={(e) =>+ updateStep(index, "value", e.target.value)+ }+ />+ <Input+ placeholder="Label (optional)"+ value={step.name || ""}+ onChange={(e) =>+ updateStep(index, "name", e.target.value)+ }+ />+ </div>++ <Button+ variant="ghost"+ size="sm"+ onClick={() => removeStep(index)}+ disabled={steps.length <= 2}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ </div></div>+ ))}- <Button- variant="ghost"- size="sm"- onClick={() => removeStep(index)}- disabled={steps.length <= 2}- >- <Trash2 className="h-4 w-4" />- </Button>- </div>- </div>- ))}+ <Button variant="outline" onClick={addStep} className="w-full">+ <Plus className="mr-2 h-4 w-4" /> Add Step+ </Button>+ </CardContent>+ </Card>- <Button variant="outline" onClick={addStep} className="w-full mt-2">- <Plus className="mr-2 h-4 w-4" /> Add Step+ {/* Query Funnel button on the left side */}+ <Button+ onClick={handleQueryFunnel}+ disabled={isPending}+ className="w-full"+ variant="accent"+ >+ <Search className="mr-2 h-4 w-4" />+ {isPending ? "Querying..." : "Query Funnel"}</Button>+ </div>+ {/* Right side: Funnel visualization (if data exists) */}+ {data?.data && data.data.length > 0 ? (+ <Funnel+ data={data}+ isError={isError}+ error={error}+ isPending={isPending}+ time={time}+ setTime={setTime}+ />+ ) : (+ <div className="flex items-center justify-center bg-neutral-50 dark:bg-neutral-900 rounded-lg h-full">+ <div className="text-center p-6">+ <div className="text-lg font-medium mb-2">Funnel Preview</div>+ <p className="text-sm text-neutral-500">+ Configure your funnel steps and click "Query Funnel" to+ preview results+ </p>+ </div>+ </div>+ )}+ </div>++ <DialogFooter className="flex justify-between items-center">+ <div className="text-sm text-red-500">+ {(isError || saveError) &&+ (error instanceof Error || saveError instanceof Error+ ? (error || saveError)?.message+ : "An error occurred")}+ </div>+ <div className="flex gap-2">+ <Button variant="outline" onClick={() => setOpen(false)}>+ Cancel+ </Button><Button- onClick={handleSubmit}- className="w-full mt-4"- disabled={isPending}+ onClick={handleSaveFunnel}+ disabled={isSaving}+ variant="success">- {isPending ? "Analyzing..." : "Analyze Funnel"}+ <Save className="mr-2 h-4 w-4" />+ {isSaving ? "Saving..." : "Save Funnel"}</Button></div>- </CardContent>- </Card>-- {/* Right side: Funnel visualization */}- <Funnel- data={data}- isError={isError}- error={error}- isPending={isPending}- time={time}- setTime={setTime}- />- </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>);}diff --git a/client/src/app/[site]/funnels/components/EditFunnel.tsx b/client/src/app/[site]/funnels/components/EditFunnel.tsxnew file mode 100644index 000000000..75d1ad149--- /dev/null+++ b/client/src/app/[site]/funnels/components/EditFunnel.tsx@@ -0,0 +1,352 @@+"use client";++import { useState, useEffect } from "react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Plus, Trash2, Search, Save } from "lucide-react";+import { Time } from "@/components/DateSelector/types";+import { DateTime } from "luxon";+import {+ useGetFunnel,+ FunnelStep,+ useSaveFunnel,+} from "@/api/analytics/useGetFunnel";+import { SavedFunnel } from "@/api/analytics/useGetFunnels";+import { Funnel } from "./Funnel";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogFooter,+} from "@/components/ui/dialog";+import { useStore } from "@/lib/store";+import { toast } from "sonner";+import { getStartAndEndDate } from "../../../../api/utils";+import { useDebounce } from "@uidotdev/usehooks";++interface EditFunnelDialogProps {+ funnel: SavedFunnel;+ isOpen: boolean;+ onClose: () => void;+}++export function EditFunnelDialog({+ funnel,+ isOpen,+ onClose,+}: EditFunnelDialogProps) {+ // Time state - initialized from funnel configuration+ const [time, setTime] = useState<Time>({+ mode: "range",+ startDate: DateTime.now().minus({ days: 7 }).toISODate(),+ endDate: DateTime.now().toISODate(),+ wellKnown: "Last 7 days",+ });++ // Funnel steps state - initialized from funnel+ const [steps, setSteps] = useState<FunnelStep[]>(funnel.steps);++ // Debounce steps and time changes+ const debouncedSteps = useDebounce(steps, 300);+ const debouncedTime = useDebounce(time, 300);++ // Funnel name - initialized from funnel+ const [name, setName] = useState(funnel.name);++ const { startDate, endDate } = getStartAndEndDate(debouncedTime);++ // Funnel analysis query+ const {+ data,+ isError,+ error,+ isLoading: isPending,+ } = useGetFunnel({+ steps: debouncedSteps,+ startDate,+ endDate,+ });++ // Funnel save mutation+ const {+ mutate: saveFunnel,+ isPending: isSaving,+ error: saveError,+ } = useSaveFunnel();++ // Handle adding a new step+ const addStep = () => {+ setSteps([...steps, { type: "page", value: "", name: "" }]);+ };++ // Handle removing a step+ const removeStep = (index: number) => {+ if (steps.length <= 2) return; // Maintain at least 2 steps+ const newSteps = [...steps];+ newSteps.splice(index, 1);+ setSteps(newSteps);+ };++ // Handle step input changes+ const updateStep = (+ index: number,+ field: keyof FunnelStep,+ value: string+ ) => {+ const newSteps = [...steps];+ newSteps[index] = { ...newSteps[index], [field]: value };+ setSteps(newSteps);+ };++ // Handle step type changes+ const updateStepType = (index: number, type: "page" | "event") => {+ const newSteps = [...steps];+ newSteps[index] = { ...newSteps[index], type };+ setSteps(newSteps);+ };++ // Query funnel without saving+ const handleQueryFunnel = () => {+ // Validate steps have values+ const hasEmptySteps = steps.some((step) => !step.value);+ if (hasEmptySteps) {+ alert("All steps must have values");+ return;+ }+ };++ // Update funnel+ const handleUpdateFunnel = () => {+ // Validate name+ if (!name.trim()) {+ alert("Please enter a funnel name");+ return;+ }++ // Validate steps have values+ const hasEmptySteps = steps.some((step) => !step.value);+ if (hasEmptySteps) {+ alert("All steps must have values");+ return;+ }++ // Get dates based on time selection+ let startDate = "",+ endDate = "";++ if (time.mode === "range") {+ startDate = time.startDate;+ endDate = time.endDate;+ } else if (time.mode === "day") {+ startDate = time.day;+ endDate = time.day;+ } else if (time.mode === "week") {+ startDate = time.week;+ const endDateValue = DateTime.fromISO(time.week)+ .plus({ days: 6 })+ .toISODate();+ endDate = endDateValue || DateTime.now().toISODate();+ } else if (time.mode === "month") {+ startDate = time.month;+ const endDateValue = DateTime.fromISO(time.month)+ .endOf("month")+ .toISODate();+ endDate = endDateValue || DateTime.now().toISODate();+ } else if (time.mode === "year") {+ startDate = time.year;+ const endDateValue = DateTime.fromISO(time.year)+ .endOf("year")+ .toISODate();+ endDate = endDateValue || DateTime.now().toISODate();+ } else {+ // Fall back to last 7 days for all-time+ startDate = DateTime.now().minus({ days: 7 }).toISODate();+ endDate = DateTime.now().toISODate();+ }++ // Update funnel with the report ID+ saveFunnel(+ {+ steps,+ startDate,+ endDate,+ name,+ reportId: funnel.id,+ },+ {+ onSuccess: () => {+ // Close dialog on successful save+ onClose();+ // Show success message+ toast?.success("Funnel updated successfully");+ },+ onError: (error) => {+ // Show error but don't close dialog+ toast?.error(`Failed to update funnel: ${error.message}`);+ },+ }+ );+ };++ // Load existing funnel data on first render+ useEffect(() => {+ // Pre-load the funnel visualization+ handleQueryFunnel();+ }, []);++ return (+ <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>+ <DialogContent className="max-w-[80vw]">+ <DialogHeader>+ <DialogTitle>Edit Funnel</DialogTitle>+ </DialogHeader>++ <div className="grid grid-cols-[600px_3fr] gap-6 my-4">+ {/* Left side: Funnel configuration form */}+ <div className="space-y-4">+ <div>+ <label className="text-sm font-medium mb-1 block">+ Funnel Name+ </label>+ <Input+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="Enter funnel name"+ />+ </div>++ {/* Funnel Steps in a boxed container */}+ <Card className="border border-neutral-200 dark:border-neutral-800">+ <CardHeader className="px-4 py-3">+ <CardTitle className="text-base">Funnel Steps</CardTitle>+ </CardHeader>+ <CardContent className="px-4 py-3 space-y-4">+ {steps.map((step, index) => (+ <div key={index} className="flex flex-col space-y-2">+ <div className="flex items-center gap-2">+ <div className="flex-shrink-0 w-6 h-6 rounded-full bg-neutral-800 flex items-center justify-center text-xs">+ {index + 1}+ </div>+ <Select+ value={step.type}+ onValueChange={(value) =>+ updateStepType(index, value as "page" | "event")+ }+ >+ <SelectTrigger className="w-[120px]">+ <SelectValue placeholder="Type" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="page">Page Path</SelectItem>+ <SelectItem value="event">Event</SelectItem>+ </SelectContent>+ </Select>++ <div className="flex-grow flex gap-2">+ <Input+ placeholder={+ step.type === "page"+ ? "Path (e.g. /pricing)"+ : "Event name"+ }+ value={step.value}+ onChange={(e) =>+ updateStep(index, "value", e.target.value)+ }+ />+ <Input+ placeholder="Label (optional)"+ value={step.name || ""}+ onChange={(e) =>+ updateStep(index, "name", e.target.value)+ }+ />+ </div>++ <Button+ variant="ghost"+ size="sm"+ onClick={() => removeStep(index)}+ disabled={steps.length <= 2}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ </div>+ </div>+ ))}++ <Button variant="outline" onClick={addStep} className="w-full">+ <Plus className="mr-2 h-4 w-4" /> Add Step+ </Button>+ </CardContent>+ </Card>++ {/* Query Funnel button on the left side */}+ <Button+ onClick={handleQueryFunnel}+ disabled={isPending}+ className="w-full"+ variant="accent"+ >+ <Search className="mr-2 h-4 w-4" />+ {isPending ? "Querying..." : "Query Funnel"}+ </Button>+ </div>++ {/* Right side: Funnel visualization (if data exists) */}+ {data?.data && data.data.length > 0 ? (+ <Funnel+ data={data}+ isError={isError}+ error={error}+ isPending={isPending}+ time={time}+ setTime={setTime}+ />+ ) : (+ <div className="flex items-center justify-center bg-neutral-50 dark:bg-neutral-900 rounded-lg h-full">+ <div className="text-center p-6">+ <div className="text-lg font-medium mb-2">Funnel Preview</div>+ <p className="text-sm text-neutral-500">+ Configure your funnel steps and click "Query Funnel" to+ preview results+ </p>+ </div>+ </div>+ )}+ </div>++ <DialogFooter className="flex justify-between items-center">+ <div className="text-sm text-red-500">+ {(isError || saveError) &&+ (error instanceof Error || saveError instanceof Error+ ? (error || saveError)?.message+ : "An error occurred")}+ </div>+ <div className="flex gap-2">+ <Button variant="outline" onClick={onClose}>+ Cancel+ </Button>+ <Button+ onClick={handleUpdateFunnel}+ disabled={isSaving}+ variant="success"+ >+ <Save className="mr-2 h-4 w-4" />+ {isSaving ? "Saving..." : "Update Funnel"}+ </Button>+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/client/src/app/[site]/funnels/components/Funnel.tsx b/client/src/app/[site]/funnels/components/Funnel.tsxindex 2c30e86bf..d36c0571f 100644--- a/client/src/app/[site]/funnels/components/Funnel.tsx+++ b/client/src/app/[site]/funnels/components/Funnel.tsx@@ -1,10 +1,9 @@"use client";+import { FunnelResponse } from "@/api/analytics/useGetFunnel";import { DateSelector } from "@/components/DateSelector/DateSelector";import { Time } from "@/components/DateSelector/types";-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";-import { FunnelResponse } from "@/api/analytics/useGetFunnel";-import { ArrowRight, Clock } from "lucide-react";+import { ArrowRight } from "lucide-react";export type FunnelChartData = {stepName: string;@@ -49,134 +48,135 @@ export function Funnel({const maxBarHeight = 333;return (- <Card>- <CardHeader className="flex flex-row items-center justify-between">- <CardTitle>Funnel Analysis</CardTitle>- <div className="flex items-center gap-2">- <DateSelector time={time} setTime={setTime} />- </div>- </CardHeader>- <CardContent>- {isError ? (- <div className="h-[400px] flex items-center justify-center">- <div className="text-red-500">- Error:{" "}- {error instanceof Error- ? error.message- : "Failed to analyze funnel"}- </div>- </div>- ) : data?.data && chartData.length > 0 ? (- <div className="space-y-4">- {/* Chart grid and background */}- <div className="relative h-[350px]">- {/* Grid lines */}- <div className="absolute inset-0 flex flex-col justify-between pointer-events-none">- {[100, 80, 60, 40, 20, 0].map((value) => (- <div- key={value}- className="w-full border-b border-neutral-200 dark:border-neutral-800 flex items-center"- >- <span className="text-xs text-neutral-500 pr-2">- {value}%- </span>- </div>- ))}- </div>-- {/* Bars container */}- <div className="absolute inset-0 pt-6 flex items-end ml-8">- {chartData.map((step, index) => {- // Calculate pixel height of the bar based on proportion of visitors- const ratio = firstStep?.visitors- ? step.visitors / firstStep.visitors- : 0;- const barHeight = Math.max(ratio * maxBarHeight, 0);+ <div>+ <div className="flex justify-end items-center gap-2 mb-2">+ <DateSelector time={time} setTime={setTime} />+ </div>- return (- <div- key={step.stepNumber}- className="flex-1 flex flex-col items-center px-2"- >- <div- className="w-full bg-accent-400/70 rounded-lg"- style={{ height: `${barHeight}px` }}- ></div>- </div>- );- })}- </div>+ {isError ? (+ <div className="h-[400px] flex items-center justify-center">+ <div className="text-red-500">+ Error:{" "}+ {error instanceof Error+ ? error.message+ : "Failed to analyze funnel"}+ </div>+ </div>+ ) : data?.data && chartData.length > 0 ? (+ <div className="space-y-4">+ {/* Chart grid and background */}+ <div className="relative h-[350px]">+ {/* Grid lines */}+ <div className="absolute inset-0 flex flex-col justify-between pointer-events-none">+ {[100, 80, 60, 40, 20, 0].map((value) => (+ <div+ key={value}+ className="w-full border-b border-neutral-200 dark:border-neutral-800 flex items-center"+ >+ <span className="text-xs text-neutral-500 pr-2">+ {value}%+ </span>+ </div>+ ))}</div>- {/* Step details */}- <div className="grid grid-cols-3 gap-0 ml-8">+ {/* Bars container */}+ <div className="absolute inset-0 pt-6 flex items-end ml-8">{chartData.map((step, index) => {- // 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+ // Calculate pixel height of the bar based on proportion of visitors+ const ratio = firstStep?.visitors+ ? step.visitors / firstStep.visitors: 0;+ const barHeight = Math.max(ratio * maxBarHeight, 0);return (<divkey={step.stepNumber}- className="bg-neutral-50 dark:bg-neutral-900 rounded-md p-1 relative pl-3 border-l border-l-neutral-800 first:border-l-0"+ className="flex-1 flex flex-col items-center px-2">- <div className="font-medium flex items-center gap-2">- {step.stepName}+ <div+ className="w-full bg-accent-400/70 rounded-lg"+ style={{ height: `${barHeight}px` }}+ ></div>+ </div>+ );+ })}+ </div>+ </div>++ {/* Step details */}+ <div+ style={{+ gridTemplateColumns: `repeat(${chartData.length}, 1fr)`,+ }}+ className={`grid gap-0 ml-8`}+ >+ {chartData.map((step, index) => {+ // 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="bg-neutral-50 dark:bg-neutral-900 rounded-md p-1 relative pl-3 border-l border-l-neutral-800 first:border-l-0"+ >+ <div className="font-medium flex items-center gap-2">+ {step.stepName}+ </div>++ {/* Entering users */}+ <div className="mt-3">+ <div className="flex items-center text-green-600 dark:text-green-500">+ <ArrowRight className="w-4 h-4 mr-2" />+ <div>+ <span className="font-medium">+ {step.visitors.toLocaleString()}+ </span>{" "}+ <span className="text-neutral-500 text-sm">+ {index === 0+ ? ` (100%)`+ : ` (${step.conversionRate.toFixed(2)}%)`}+ </span>+ </div></div>- {/* Entering users */}- <div className="mt-3">- <div className="flex items-center text-green-600 dark:text-green-500">- <ArrowRight className="w-4 h-4 mr-2" />+ {/* Dropped off users - only for steps after the first */}+ {index > 0 && (+ <div className="flex items-center text-orange-500 mt-1">+ <div className="w-4 h-4 mr-2 flex items-center justify-center">+ ↘+ </div><div><span className="font-medium">- {step.visitors.toLocaleString()}+ {droppedUsers.toLocaleString()}</span>{" "}<span className="text-neutral-500 text-sm">- {index === 0- ? ` (100%)`- : ` (${step.conversionRate.toFixed(2)}%)`}+ ({dropoffPercent.toFixed(2)}%)</span></div></div>-- {/* Dropped off users - only for steps after the first */}- {index > 0 && (- <div className="flex items-center text-orange-500 mt-1">- <div className="w-4 h-4 mr-2 flex items-center justify-center">- ↘- </div>- <div>- <span className="font-medium">- {droppedUsers.toLocaleString()}- </span>{" "}- <span className="text-neutral-500 text-sm">- ({dropoffPercent.toFixed(2)}%)- </span>- </div>- </div>- )}- </div>+ )}</div>- );- })}- </div>+ </div>+ );+ })}</div>- ) : (- <div className="h-[400px] flex items-center justify-center">- <div className="text-neutral-400 text-sm">- {isPending- ? "Analyzing funnel..."- : "Configure your funnel steps and click 'Analyze Funnel'"}- </div>+ </div>+ ) : (+ <div className="h-[400px] flex items-center justify-center">+ <div className="text-neutral-400 text-sm">+ {isPending+ ? "Analyzing funnel..."+ : "Configure your funnel steps and click 'Analyze Funnel'"}</div>- )}- </CardContent>- </Card>+ </div>+ )}+ </div>);}diff --git a/client/src/app/[site]/funnels/components/FunnelRow.tsx b/client/src/app/[site]/funnels/components/FunnelRow.tsxnew file mode 100644index 000000000..bbe10750c--- /dev/null+++ b/client/src/app/[site]/funnels/components/FunnelRow.tsx@@ -0,0 +1,219 @@+"use client";++import { useDeleteFunnel } from "@/api/analytics/useDeleteFunnel";+import { useGetFunnel } from "@/api/analytics/useGetFunnel";+import { SavedFunnel } from "@/api/analytics/useGetFunnels";+import { ConfirmationModal } from "@/components/ConfirmationModal";+import { DateRangeMode, Time } from "@/components/DateSelector/types";+import { Button } from "@/components/ui/button";+import { Card } from "@/components/ui/card";+import {+ BarChart2,+ Calendar,+ ChevronDown,+ ChevronUp,+ Edit,+ FunnelIcon,+ Trash2,+} from "lucide-react";+import { DateTime } from "luxon";+import { useState } from "react";+import { toast } from "sonner";+import { getStartAndEndDate } from "../../../../api/utils";+import { EditFunnelDialog } from "./EditFunnel";+import { Funnel } from "./Funnel";+import { useDebounce } from "@uidotdev/usehooks";++interface FunnelRowProps {+ funnel: SavedFunnel;+}++export function FunnelRow({ funnel }: FunnelRowProps) {+ const [expanded, setExpanded] = useState(false);+ const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);+ const [isEditModalOpen, setIsEditModalOpen] = useState(false);++ // Time state for funnel visualization - default to last 7 days+ const [time, setTime] = useState<Time>({+ mode: "range",+ startDate: DateTime.now().minus({ days: 7 }).toISODate(),+ endDate: DateTime.now().toISODate(),+ wellKnown: "Last 7 days",+ } as DateRangeMode);++ // Debounce time changes+ const debouncedTime = useDebounce(time, 300);+ const { startDate, endDate } = getStartAndEndDate(debouncedTime);++ // Funnel data fetching+ const {+ data,+ isError,+ error,+ isLoading: isPending,+ isSuccess,+ } = useGetFunnel(+ expanded+ ? {+ steps: funnel.steps,+ startDate,+ endDate,+ }+ : undefined+ );++ // Delete funnel mutation+ const { mutate: deleteFunnel, isPending: isDeleting } = useDeleteFunnel();++ // Handle expansion+ const handleExpand = () => {+ setExpanded(!expanded);+ };++ // Format date string+ const formatDate = (dateString: string) => {+ try {+ return new Date(dateString).toLocaleDateString(undefined, {+ year: "numeric",+ month: "short",+ day: "numeric",+ });+ } catch (e) {+ return "Unknown date";+ }+ };++ // Handle funnel deletion+ const handleDeleteFunnel = async () => {+ try {+ await deleteFunnel(funnel.id);+ toast.success("Funnel deleted successfully");+ } catch (error) {+ console.error("Error deleting funnel:", error);+ throw error; // Let the ConfirmationModal handle the error display+ }+ };++ return (+ <Card className="mb-4 overflow-hidden">+ {/* Header row (always visible) */}+ <div className="flex items-center justify-between p-4">+ <div+ className="flex items-center space-x-4 flex-grow cursor-pointer hover:bg-neutral-50 dark:hover:bg-neutral-900 transition-colors"+ onClick={handleExpand}+ >+ <div className="bg-neutral-100 dark:bg-neutral-800 p-2 rounded-md">+ <FunnelIcon className="h-5 w-5 text-neutral-500" />+ </div>+ <div>+ <h3 className="font-medium">{funnel.name}</h3>+ <div className="text-sm text-neutral-500 flex items-center gap-2">+ <span>{funnel.steps.length} steps</span>+ <span>•</span>+ <div className="flex items-center">+ <Calendar className="h-3 w-3 mr-1" />+ {formatDate(funnel.createdAt)}+ </div>+ </div>+ </div>+ </div>++ <div className="flex items-center gap-4">+ {/* <div className="text-right">+ <div className="text-sm text-neutral-500">Conversion</div>+ <div className="font-semibold">+ {(funnel.conversionRate || 0).toFixed(1)}%+ </div>+ </div> */}++ <div className="flex">+ {/* Edit button */}+ <Button+ variant="ghost"+ size="icon"+ onClick={(e) => {+ e.stopPropagation();+ setIsEditModalOpen(true);+ }}+ >+ <Edit className="h-4 w-4" />+ </Button>++ {/* Delete button */}+ <Button+ variant="ghost"+ size="icon"+ onClick={(e) => {+ e.stopPropagation();+ setIsDeleteModalOpen(true);+ }}+ >+ <Trash2 className="h-4 w-4" />+ </Button>++ <Button variant="ghost" size="icon" onClick={handleExpand}>+ {expanded ? <ChevronUp /> : <ChevronDown />}+ </Button>+ </div>+ </div>+ </div>++ {/* Expandable content */}+ {expanded && (+ <div className="border-t border-neutral-200 dark:border-neutral-800">+ <div className="p-4">+ {isPending ? (+ <div className="flex justify-center items-center h-[400px]">+ <div className="animate-pulse flex items-center">+ <div className="h-2 w-2 bg-neutral-500 rounded-full mr-1 animate-bounce"></div>+ <div className="h-2 w-2 bg-neutral-500 rounded-full mr-1 animate-bounce [animation-delay:0.2s]"></div>+ <div className="h-2 w-2 bg-neutral-500 rounded-full animate-bounce [animation-delay:0.4s]"></div>+ </div>+ </div>+ ) : isError ? (+ <div className="text-red-500 p-4 text-center">+ Error loading funnel:{" "}+ {error instanceof Error ? error.message : "Unknown error"}+ </div>+ ) : data?.data && data.data.length > 0 ? (+ <Funnel+ data={data}+ isError={isError}+ error={error}+ isPending={isPending}+ time={time}+ setTime={setTime}+ />+ ) : (+ <div className="text-center p-6 text-neutral-500">+ No funnel data available+ </div>+ )}+ </div>+ </div>+ )}++ {/* Delete Confirmation Modal */}+ <ConfirmationModal+ title="Delete Funnel"+ description={`Are you sure you want to delete "${funnel.name}"? This action cannot be undone.`}+ isOpen={isDeleteModalOpen}+ setIsOpen={setIsDeleteModalOpen}+ onConfirm={handleDeleteFunnel}+ primaryAction={{+ children: isDeleting ? "Deleting..." : "Delete",+ variant: "destructive",+ }}+ />++ {/* Edit Funnel Modal */}+ {isEditModalOpen && (+ <EditFunnelDialog+ funnel={funnel}+ isOpen={isEditModalOpen}+ onClose={() => setIsEditModalOpen(false)}+ />+ )}+ </Card>+ );+}diff --git a/client/src/app/[site]/funnels/page.tsx b/client/src/app/[site]/funnels/page.tsxindex 6920fd0c4..721d82990 100644--- a/client/src/app/[site]/funnels/page.tsx+++ b/client/src/app/[site]/funnels/page.tsx@@ -1,9 +1,63 @@-import { CreateFunnel } from "./components/CreateFunnel";+"use client";++import { CreateFunnelDialog } from "./components/CreateFunnel";+import { useState, useEffect } from "react";+import { Button } from "@/components/ui/button";+import { useGetFunnels, SavedFunnel } from "@/api/analytics/useGetFunnels";+import { PlusCircle } from "lucide-react";+import { Skeleton } from "@/components/ui/skeleton";+import { useStore } from "@/lib/store";+import { FunnelRow } from "./components/FunnelRow";export default function FunnelsPage() {+ const { site } = useStore();+ const { data: funnels, isLoading, error } = useGetFunnels(site);++ if (isLoading) {+ return (+ <div className="space-y-4">+ <div className="flex justify-between items-center mb-6">+ <h1 className="text-2xl font-bold">Funnels</h1>+ <Skeleton className="h-10 w-32" />+ </div>+ {[1, 2, 3].map((i) => (+ <Skeleton key={i} className="h-20 w-full mb-4" />+ ))}+ </div>+ );+ }+return (<div>- <CreateFunnel />+ <div className="flex justify-between items-center mb-6">+ <h1 className="text-2xl font-bold">Funnels</h1>+ <CreateFunnelDialog />+ </div>++ {error ? (+ <div className="p-4 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-lg">+ Failed to load funnels:{" "}+ {error instanceof Error ? error.message : "Unknown error"}+ </div>+ ) : funnels?.length ? (+ <div className="space-y-4">+ {funnels.map((funnel: SavedFunnel) => (+ <FunnelRow key={funnel.id} funnel={funnel} />+ ))}+ </div>+ ) : (+ <div className="flex flex-col items-center justify-center py-10 text-center">+ <div className="bg-neutral-100 dark:bg-neutral-800 rounded-full p-3 mb-4">+ <PlusCircle className="h-6 w-6" />+ </div>+ <h3 className="text-lg font-medium mb-2">No funnels yet</h3>+ <p className="text-neutral-500 max-w-md mb-6">+ Create your first funnel to track conversions through your site's+ user journey+ </p>+ <CreateFunnelDialog />+ </div>+ )}</div>);}diff --git a/client/src/components/ConfirmationModal.tsx b/client/src/components/ConfirmationModal.tsxindex c36efb90d..5ab512e23 100644--- a/client/src/components/ConfirmationModal.tsx+++ b/client/src/components/ConfirmationModal.tsx@@ -15,7 +15,7 @@ import { AlertCircle } from "lucide-react";export const ConfirmationModal: React.FC<{title: React.ReactNode;description: React.ReactNode;- children: React.ReactNode;+ children?: React.ReactNode;isOpen: boolean;setIsOpen: (b: boolean) => void;onConfirm: () => void;diff --git a/server/src/api/createFunnel.ts b/server/src/api/createFunnel.tsnew file mode 100644index 000000000..b7ce75dca--- /dev/null+++ b/server/src/api/createFunnel.ts@@ -0,0 +1,108 @@+import { FastifyRequest, FastifyReply } from "fastify";+import { db } from "../db/postgres/postgres.js";+import { reports } from "../db/postgres/schema.js";+import { getUserHasAccessToSite } from "../lib/auth-utils.js";+import { eq } from "drizzle-orm";++type FunnelStep = {+ value: string;+ name?: string;+ type: "page" | "event";+};++type Funnel = {+ steps: FunnelStep[];+ name: string;+ reportId?: number; // Optional report ID for updates+};++export async function createFunnel(+ request: FastifyRequest<{+ Body: Funnel;+ Params: {+ site: string;+ };+ }>,+ reply: FastifyReply+) {+ const { steps, name, reportId } = request.body;+ const { site } = request.params;+ const userId = request.user?.id;++ // Validate request+ if (!steps || steps.length < 2) {+ return reply+ .status(400)+ .send({ error: "At least 2 steps are required for a funnel" });+ }++ if (!name) {+ return reply.status(400).send({ error: "Funnel name is required" });+ }++ // Check user access to site+ const userHasAccessToSite = await getUserHasAccessToSite(request, site);+ if (!userHasAccessToSite) {+ return reply.status(403).send({ error: "Forbidden" });+ }++ try {+ let result;++ if (reportId) {+ // Check if the report exists and user has access to it+ const existingReport = await db.query.reports.findFirst({+ where: eq(reports.reportId, reportId),+ });++ if (!existingReport) {+ return reply.status(404).send({ error: "Report not found" });+ }++ if (existingReport.siteId !== Number(site)) {+ return reply+ .status(403)+ .send({ error: "Report does not belong to this site" });+ }++ // Update existing funnel+ result = await db+ .update(reports)+ .set({+ data: {+ name,+ steps,+ },+ updatedAt: new Date().toISOString(),+ })+ .where(eq(reports.reportId, reportId))+ .returning({ reportId: reports.reportId });++ if (!result || result.length === 0) {+ return reply.status(500).send({ error: "Failed to update funnel" });+ }+ } else {+ // Create new funnel+ result = await db+ .insert(reports)+ .values({+ siteId: Number(site),+ userId,+ reportType: "funnel",+ data: {+ name,+ steps,+ },+ })+ .returning({ reportId: reports.reportId });+ }++ return reply.status(201).send({+ success: true,+ funnelId: result[0].reportId,+ });+ } catch (error) {+ console.error("Error creating funnel:", error);+ return reply.status(500).send({ error: "Failed to create funnel" });+ }+}diff --git a/server/src/api/deleteReport.ts b/server/src/api/deleteReport.tsnew file mode 100644index 000000000..5f3d7583c--- /dev/null+++ b/server/src/api/deleteReport.ts@@ -0,0 +1,51 @@+import { FastifyRequest, FastifyReply } from "fastify";+import { db } from "../db/postgres/postgres.js";+import { reports } from "../db/postgres/schema.js";+import { eq } from "drizzle-orm";+import { getUserHasAccessToSite } from "../lib/auth-utils.js";++export async function deleteReport(+ request: FastifyRequest<{+ Params: {+ reportId: string;+ };+ }>,+ reply: FastifyReply+) {+ const { reportId } = request.params;+ const userId = request.user?.id;++ try {+ // First get the report to check ownership+ const report = await db.query.reports.findFirst({+ where: eq(reports.reportId, parseInt(reportId)),+ });++ if (!report) {+ return reply.status(404).send({ error: "Report not found" });+ }++ if (!report.siteId) {+ return reply+ .status(400)+ .send({ error: "Invalid report: missing site ID" });+ }++ // Check user access to site+ const userHasAccessToSite = await getUserHasAccessToSite(+ request,+ report.siteId.toString()+ );+ if (!userHasAccessToSite) {+ return reply.status(403).send({ error: "Forbidden" });+ }++ // Delete the report+ await db.delete(reports).where(eq(reports.reportId, parseInt(reportId)));++ return reply.status(200).send({ success: true });+ } catch (error) {+ console.error("Error deleting report:", error);+ return reply.status(500).send({ error: "Failed to delete report" });+ }+}diff --git a/server/src/api/getFunnels.ts b/server/src/api/getFunnels.tsnew file mode 100644index 000000000..3583bcd93--- /dev/null+++ b/server/src/api/getFunnels.ts@@ -0,0 +1,54 @@+import { FastifyRequest, FastifyReply } from "fastify";+import { db } from "../db/postgres/postgres.js";+import { reports } from "../db/postgres/schema.js";+import { getUserHasAccessToSite } from "../lib/auth-utils.js";+import { eq, and } from "drizzle-orm";++export async function getFunnels(+ request: FastifyRequest<{+ Params: {+ site: string;+ };+ }>,+ reply: FastifyReply+) {+ const { site } = request.params;++ // Check user access to site+ const userHasAccessToSite = await getUserHasAccessToSite(request, site);+ if (!userHasAccessToSite) {+ return reply.status(403).send({ error: "Forbidden" });+ }++ try {+ // Fetch all funnel reports for the site+ const funnelReports = await db+ .select()+ .from(reports)+ .where(+ and(eq(reports.siteId, Number(site)), eq(reports.reportType, "funnel"))+ )+ .orderBy(reports.createdAt);++ // Transform the reports to a more frontend-friendly structure+ const funnels = funnelReports.map((report) => {+ const data = report.data as any;+ return {+ id: report.reportId,+ name: data.name || "Unnamed Funnel",+ steps: data.steps || [],+ configuration: data.configuration || {},+ createdAt: report.createdAt,+ updatedAt: report.updatedAt,+ // Include any additional analytics data that might be stored+ conversionRate: data.lastResult?.conversionRate || null,+ totalVisitors: data.lastResult?.totalVisitors || null,+ };+ });++ return reply.send({ data: funnels });+ } catch (error) {+ console.error("Error fetching funnels:", error);+ return reply.status(500).send({ error: "Failed to fetch funnels" });+ }+}diff --git a/server/src/index.ts b/server/src/index.tsindex 12706eec4..ffba807f2 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -35,6 +35,9 @@ import { getUserInfo } from "./api/getUserInfo.js";import { getLiveSessionLocations } from "./api/getLiveSessionLocations.js";import { getRetention } from "./api/getRetention.js";import { getFunnel } from "./api/getFunnel.js";+import { createFunnel } from "./api/createFunnel.js";+import { getFunnels } from "./api/getFunnels.js";+import { deleteReport } from "./api/deleteReport.js";const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -137,6 +140,9 @@ server.get("/user/:userId/sessions", getUserSessions);server.get("/user/info/:siteId/:userId", getUserInfo);server.get("/live-session-locations/:siteId", getLiveSessionLocations);server.post("/funnel/:site", getFunnel);+server.post("/funnel/create/:site", createFunnel);+server.get("/funnels/:site", getFunnels);+server.delete("/report/:reportId", deleteReport);// Administrativeserver.post("/add-site", addSite);