Skip to content

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

Enable filtering on pageview properties (#800)

Stijn46139f980fcb
diff --git a/client/src/api/analytics/endpoints/funnels.ts b/client/src/api/analytics/endpoints/funnels.ts
index 606075034..ddc450c8f 100644
--- a/client/src/api/analytics/endpoints/funnels.ts
+++ b/client/src/api/analytics/endpoints/funnels.ts
@@ -8,8 +8,14 @@ export type FunnelStep = {
name?: string;
type: "page" | "event";
hostname?: string;
+ // Deprecated fields - kept for backwards compatibility
eventPropertyKey?: string;
eventPropertyValue?: string | number | boolean;
+ // New field for multiple property filters
+ propertyFilters?: Array<{
+ key: string;
+ value: string | number | boolean;
+ }>;
};
// Funnel request type
diff --git a/client/src/api/analytics/endpoints/goals.ts b/client/src/api/analytics/endpoints/goals.ts
index a99404806..8da7fb973 100644
--- a/client/src/api/analytics/endpoints/goals.ts
+++ b/client/src/api/analytics/endpoints/goals.ts
@@ -10,8 +10,14 @@ export interface Goal {
config: {
pathPattern?: string;
eventName?: string;
+ // Deprecated fields - kept for backwards compatibility
eventPropertyKey?: string;
eventPropertyValue?: string | number | boolean;
+ // New field for multiple property filters
+ propertyFilters?: Array<{
+ key: string;
+ value: string | number | boolean;
+ }>;
};
createdAt: string;
total_conversions: number;
@@ -51,11 +57,16 @@ export interface CreateGoalParams {
eventName?: string;
eventPropertyKey?: string;
eventPropertyValue?: string | number | boolean;
+ propertyFilters?: Array<{
+ key: string;
+ value: string | number | boolean;
+ }>;
};
}
export interface UpdateGoalParams extends CreateGoalParams {
goalId: number;
+ siteId: number;
}
/**
diff --git a/client/src/api/analytics/hooks/goals/useUpdateGoal.ts b/client/src/api/analytics/hooks/goals/useUpdateGoal.ts
index 639abfba9..b73307cf8 100644
--- a/client/src/api/analytics/hooks/goals/useUpdateGoal.ts
+++ b/client/src/api/analytics/hooks/goals/useUpdateGoal.ts
@@ -12,6 +12,10 @@ export interface UpdateGoalRequest {
eventName?: string;
eventPropertyKey?: string;
eventPropertyValue?: string | number | boolean;
+ propertyFilters?: Array<{
+ key: string;
+ value: string | number | boolean;
+ }>;
};
}
@@ -28,6 +32,7 @@ export function useUpdateGoal() {
mutationFn: async goalData => {
return updateGoal(goalData.siteId, {
goalId: goalData.goalId,
+ siteId: goalData.siteId,
name: goalData.name,
goalType: goalData.goalType,
config: goalData.config,
diff --git a/client/src/app/[site]/funnels/components/FunnelForm.tsx b/client/src/app/[site]/funnels/components/FunnelForm.tsx
index b677614a4..3bde16586 100644
--- a/client/src/app/[site]/funnels/components/FunnelForm.tsx
+++ b/client/src/app/[site]/funnels/components/FunnelForm.tsx
@@ -3,7 +3,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { InputWithSuggestions, SuggestionOption } from "@/components/ui/input-with-suggestions";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
-import { Plus, Save, Trash2 } from "lucide-react";
+import { Plus, Save, Trash2, X } from "lucide-react";
import { useState } from "react";
import { FunnelResponse, FunnelStep } from "../../../../api/analytics/endpoints";
import { useMetric } from "../../../../api/analytics/hooks/useGetMetric";
@@ -47,7 +47,17 @@ export function FunnelForm({
}: FunnelFormProps) {
// State to track which event steps have property filtering enabled
const [useProperties, setUseProperties] = useState<boolean[]>(() =>
- steps.map(step => !!step.eventPropertyKey && step.eventPropertyValue !== undefined)
+ steps.map(step => !!(step.propertyFilters?.length || (step.eventPropertyKey && step.eventPropertyValue !== undefined)))
+ );
+
+ // State for managing multiple property filters per step (store as strings in UI)
+ const [stepPropertyFilters, setStepPropertyFilters] = useState<Array<Array<{ key: string; value: string }>>>(() =>
+ steps.map(step =>
+ step.propertyFilters?.map(f => ({ key: f.key, value: String(f.value) })) ||
+ (step.eventPropertyKey && step.eventPropertyValue !== undefined
+ ? [{ key: step.eventPropertyKey, value: String(step.eventPropertyValue) }]
+ : [{ key: "", value: "" }])
+ )
);
// Fetch suggestions for paths, events, and hostnames
@@ -92,6 +102,7 @@ export function FunnelForm({
const addStep = () => {
setSteps([...steps, { type: "page", value: "", name: "" }]);
setUseProperties([...useProperties, false]);
+ setStepPropertyFilters([...stepPropertyFilters, [{ key: "", value: "" }]]);
};
// Handle removing a step
@@ -104,6 +115,10 @@ export function FunnelForm({
const newUseProperties = [...useProperties];
newUseProperties.splice(index, 1);
setUseProperties(newUseProperties);
+
+ const newStepPropertyFilters = [...stepPropertyFilters];
+ newStepPropertyFilters.splice(index, 1);
+ setStepPropertyFilters(newStepPropertyFilters);
};
// Handle step input changes
@@ -119,17 +134,8 @@ export function FunnelForm({
newSteps[index] = {
...newSteps[index],
type,
- // Clear property fields if switching from event to page
- ...(type === "page" ? { eventPropertyKey: undefined, eventPropertyValue: undefined } : {}),
};
setSteps(newSteps);
-
- // Disable property filtering if switching to page type
- if (type === "page" && useProperties[index]) {
- const newUseProperties = [...useProperties];
- newUseProperties[index] = false;
- setUseProperties(newUseProperties);
- }
};
// Handle property filtering toggle
@@ -145,6 +151,7 @@ export function FunnelForm({
...newSteps[index],
eventPropertyKey: undefined,
eventPropertyValue: undefined,
+ propertyFilters: undefined,
};
setSteps(newSteps);
}
@@ -247,36 +254,105 @@ export function FunnelForm({
<Trash2 className="h-4 w-4" />
</Button>
</div>
- {/* Property filtering for event steps */}
- {step.type === "event" && (
- <div className="mt-2 space-y-2">
- <div className="flex items-center space-x-2">
- <Switch
- checked={useProperties[index]}
- onCheckedChange={checked => togglePropertyFiltering(index, checked)}
- id={`use-properties-${index}`}
- />
- <Label htmlFor={`use-properties-${index}`}>Filter by event property</Label>
- </div>
-
- {useProperties[index] && (
- <div className="grid grid-cols-2 gap-2 mt-2">
- <Input
- placeholder="Property key"
- className="border-neutral-300 dark:border-neutral-700"
- value={step.eventPropertyKey || ""}
- onChange={e => updateStep(index, "eventPropertyKey", e.target.value)}
- />
- <Input
- placeholder="Property value"
- className="border-neutral-300 dark:border-neutral-700"
- value={step.eventPropertyValue !== undefined ? String(step.eventPropertyValue) : ""}
- onChange={e => updateStep(index, "eventPropertyValue", e.target.value)}
- />
- </div>
- )}
+ {/* Property filtering for both page and event steps */}
+ <div className="mt-2 space-y-2">
+ <div className="flex items-center space-x-2">
+ <Switch
+ checked={useProperties[index]}
+ onCheckedChange={checked => togglePropertyFiltering(index, checked)}
+ id={`use-properties-${index}`}
+ />
+ <Label htmlFor={`use-properties-${index}`}>
+ {step.type === "page" ? "Filter by URL parameter" : "Filter by event property"}
+ </Label>
</div>
- )}
+
+ {useProperties[index] && (
+ <div className="space-y-3">
+ {stepPropertyFilters[index]?.map((filter, filterIndex) => (
+ <div key={filterIndex} className="flex gap-2 items-start">
+ <div className="flex-1 grid grid-cols-2 gap-2">
+ <Input
+ placeholder={step.type === "page" ? "e.g., utm_source" : "e.g., plan_type"}
+ className="border-neutral-300 dark:border-neutral-700"
+ value={filter.key}
+ onChange={e => {
+ // Create immutable copies for nested state
+ const newStepPropertyFilters = [...stepPropertyFilters];
+ const stepFilters = [...newStepPropertyFilters[index]];
+ const updatedFilter = { ...stepFilters[filterIndex], key: e.target.value };
+ stepFilters[filterIndex] = updatedFilter;
+ newStepPropertyFilters[index] = stepFilters;
+ setStepPropertyFilters(newStepPropertyFilters);
+
+ // Update the step with propertyFilters immutably
+ const newSteps = [...steps];
+ newSteps[index] = { ...newSteps[index], propertyFilters: stepFilters };
+ setSteps(newSteps);
+ }}
+ />
+ <Input
+ placeholder={step.type === "page" ? "e.g., adwords" : "e.g., premium"}
+ className="border-neutral-300 dark:border-neutral-700"
+ value={filter.value}
+ onChange={e => {
+ // Create immutable copies for nested state
+ const newStepPropertyFilters = [...stepPropertyFilters];
+ const stepFilters = [...newStepPropertyFilters[index]];
+ const updatedFilter = { ...stepFilters[filterIndex], value: e.target.value };
+ stepFilters[filterIndex] = updatedFilter;
+ newStepPropertyFilters[index] = stepFilters;
+ setStepPropertyFilters(newStepPropertyFilters);
+
+ // Update the step with propertyFilters immutably
+ const newSteps = [...steps];
+ newSteps[index] = { ...newSteps[index], propertyFilters: stepFilters };
+ setSteps(newSteps);
+ }}
+ />
+ </div>
+ {stepPropertyFilters[index].length > 1 && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={() => {
+ // Create immutable copies for nested state
+ const newStepPropertyFilters = [...stepPropertyFilters];
+ const stepFilters = newStepPropertyFilters[index].filter(
+ (_, i) => i !== filterIndex
+ );
+ newStepPropertyFilters[index] = stepFilters;
+ setStepPropertyFilters(newStepPropertyFilters);
+
+ // Update the step with propertyFilters immutably
+ const newSteps = [...steps];
+ newSteps[index] = { ...newSteps[index], propertyFilters: stepFilters };
+ setSteps(newSteps);
+ }}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ ))}
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ const newStepPropertyFilters = [...stepPropertyFilters];
+ newStepPropertyFilters[index] = [...newStepPropertyFilters[index], { key: "", value: "" }];
+ setStepPropertyFilters(newStepPropertyFilters);
+ }}
+ className="w-full"
+ >
+ <Plus className="mr-2 h-4 w-4" />
+ Add Another {step.type === "page" ? "Parameter" : "Property"}
+ </Button>
+ </div>
+ )}
+ </div>
</div>
</div>
</div>
diff --git a/client/src/app/[site]/goals/components/GoalFormModal.tsx b/client/src/app/[site]/goals/components/GoalFormModal.tsx
index 47d364d63..b5cc6695b 100644
--- a/client/src/app/[site]/goals/components/GoalFormModal.tsx
+++ b/client/src/app/[site]/goals/components/GoalFormModal.tsx
@@ -24,6 +24,7 @@ import { InputWithSuggestions, SuggestionOption } from "../../../../components/u
import { Label } from "../../../../components/ui/label";
import { Switch } from "../../../../components/ui/switch";
import { cn } from "../../../../lib/utils";
+import { Plus, X } from "lucide-react";
// Define form schema
const formSchema = z
@@ -35,6 +36,10 @@ const formSchema = z
eventName: z.string().optional(),
eventPropertyKey: z.string().optional(),
eventPropertyValue: z.string().optional(),
+ propertyFilters: z.array(z.object({
+ key: z.string(),
+ value: z.union([z.string(), z.number(), z.boolean()]),
+ })).optional(),
}),
})
.refine(
@@ -63,8 +68,18 @@ interface GoalFormModalProps {
export default function GoalFormModal({ siteId, goal, trigger, isCloneMode = false }: GoalFormModalProps) {
const [isOpen, setIsOpen] = useState(false);
- const [useProperties, setUseProperties] = useState(
- !!goal?.config.eventPropertyKey && !!goal?.config.eventPropertyValue
+
+ // Initialize useProperties based on either new propertyFilters or legacy properties
+ const hasProperties = !!(goal?.config.propertyFilters?.length ||
+ (goal?.config.eventPropertyKey && goal?.config.eventPropertyValue !== undefined));
+ const [useProperties, setUseProperties] = useState(hasProperties);
+
+ // State for managing multiple property filters (store as strings in UI)
+ const [propertyFilters, setPropertyFilters] = useState<Array<{ key: string; value: string }>>(
+ goal?.config.propertyFilters?.map(f => ({ key: f.key, value: String(f.value) })) ||
+ (goal?.config.eventPropertyKey && goal?.config.eventPropertyValue !== undefined
+ ? [{ key: goal.config.eventPropertyKey, value: String(goal.config.eventPropertyValue) }]
+ : [{ key: "", value: "" }])
);
// Fetch suggestions for paths and events
@@ -95,10 +110,20 @@ export default function GoalFormModal({ siteId, goal, trigger, isCloneMode = fal
// Reinitialize useProperties when goal changes or modal opens
useEffect(() => {
- if (isOpen) {
- setUseProperties(!!goal?.config.eventPropertyKey && !!goal?.config.eventPropertyValue);
+ if (isOpen && goal) {
+ // Update useProperties based on either new propertyFilters or legacy properties
+ const hasFilters = !!(goal.config.propertyFilters?.length ||
+ (goal.config.eventPropertyKey && goal.config.eventPropertyValue !== undefined));
+ setUseProperties(hasFilters);
+
+ // Update propertyFilters state
+ const filters = goal.config.propertyFilters?.map(f => ({ key: f.key, value: String(f.value) })) ||
+ (goal.config.eventPropertyKey && goal.config.eventPropertyValue !== undefined
+ ? [{ key: goal.config.eventPropertyKey, value: String(goal.config.eventPropertyValue) }]
+ : [{ key: "", value: "" }]);
+ setPropertyFilters(filters);
}
- }, [isOpen, goal?.config.eventPropertyKey, goal?.config.eventPropertyValue]);
+ }, [isOpen, goal]);
const onClose = () => {
setIsOpen(false);
@@ -144,16 +169,30 @@ export default function GoalFormModal({ siteId, goal, trigger, isCloneMode = fal
// Clean up the config based on goal type
if (values.goalType === "path") {
values.config.eventName = undefined;
+
+ // Set propertyFilters if using properties
+ if (useProperties) {
+ const validFilters = propertyFilters.filter(f => f.key && f.value);
+ values.config.propertyFilters = validFilters.length > 0 ? validFilters : undefined;
+ } else {
+ values.config.propertyFilters = undefined;
+ }
+ // Clear legacy fields
values.config.eventPropertyKey = undefined;
values.config.eventPropertyValue = undefined;
} else if (values.goalType === "event") {
values.config.pathPattern = undefined;
- // If not using properties, clear them
- if (!useProperties) {
- values.config.eventPropertyKey = undefined;
- values.config.eventPropertyValue = undefined;
+ // Set propertyFilters if using properties
+ if (useProperties) {
+ const validFilters = propertyFilters.filter(f => f.key && f.value);
+ values.config.propertyFilters = validFilters.length > 0 ? validFilters : undefined;
+ } else {
+ values.config.propertyFilters = undefined;
}
+ // Clear legacy fields
+ values.config.eventPropertyKey = undefined;
+ values.config.eventPropertyValue = undefined;
}
if (isEditMode) {
@@ -191,6 +230,7 @@ export default function GoalFormModal({ siteId, goal, trigger, isCloneMode = fal
if (!open) {
form.reset();
setUseProperties(false);
+ setPropertyFilters([{ key: "", value: "" }]);
}
}}
>
@@ -281,26 +321,87 @@ export default function GoalFormModal({ siteId, goal, trigger, isCloneMode = fal
/>
{goalType === "path" && (
- <FormField
- control={form.control}
- name="config.pathPattern"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Path Pattern</FormLabel>
- <FormControl>
- <InputWithSuggestions
- suggestions={pathSuggestions}
- placeholder="/checkout/complete or /product/*/view"
- {...field}
- />
- </FormControl>
- <FormMessage />
- <div className="text-xs text-neutral-500 mt-1">
- Use * to match a single path segment. Use ** to match across segments.
+ <>
+ <FormField
+ control={form.control}
+ name="config.pathPattern"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Path Pattern</FormLabel>
+ <FormControl>
+ <InputWithSuggestions
+ suggestions={pathSuggestions}
+ placeholder="/checkout/complete or /product/*/view"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ <div className="text-xs text-neutral-500 mt-1">
+ Use * to match a single path segment. Use ** to match across segments.
+ </div>
+ </FormItem>
+ )}
+ />
+
+ <div className="mt-4">
+ <div className="flex items-center space-x-2 mb-4">
+ <Switch id="use-properties" checked={useProperties} onCheckedChange={setUseProperties} />
+ <Label htmlFor="use-properties">Match specific URL parameters</Label>
+ </div>
+
+ {useProperties && (
+ <div className="space-y-3">
+ {propertyFilters.map((filter, index) => (
+ <div key={index} className="flex gap-2 items-start">
+ <div className="flex-1 grid grid-cols-2 gap-2">
+ <Input
+ placeholder="e.g., utm_source"
+ value={filter.key}
+ onChange={e => {
+ const newFilters = [...propertyFilters];
+ newFilters[index].key = e.target.value;
+ setPropertyFilters(newFilters);
+ }}
+ />
+ <Input
+ placeholder="e.g., adwords"
+ value={filter.value}
+ onChange={e => {
+ const newFilters = [...propertyFilters];
+ newFilters[index].value = e.target.value;
+ setPropertyFilters(newFilters);
+ }}
+ />
+ </div>
+ {propertyFilters.length > 1 && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={() => {
+ const newFilters = propertyFilters.filter((_, i) => i !== index);
+ setPropertyFilters(newFilters);
+ }}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ ))}
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setPropertyFilters([...propertyFilters, { key: "", value: "" }])}
+ className="w-full"
+ >
+ <Plus className="mr-2 h-4 w-4" />
+ Add Another Parameter
+ </Button>
</div>
- </FormItem>
- )}
- />
+ )}
+ </div>
+ </>
)}
{goalType === "event" && (
@@ -325,39 +426,59 @@ export default function GoalFormModal({ siteId, goal, trigger, isCloneMode = fal
<div className="mt-4">
<div className="flex items-center space-x-2 mb-4">
- <Switch id="use-properties" checked={useProperties} onCheckedChange={setUseProperties} />
- <Label htmlFor="use-properties">Match specific event property</Label>
+ <Switch id="use-properties-event" checked={useProperties} onCheckedChange={setUseProperties} />
+ <Label htmlFor="use-properties-event">Match specific event properties</Label>
</div>
{useProperties && (
- <div className="grid grid-cols-2 gap-4">
- <FormField
- control={form.control}
- name="config.eventPropertyKey"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Property Key</FormLabel>
- <FormControl>
- <Input placeholder="e.g., plan_type" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="config.eventPropertyValue"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Property Value</FormLabel>
- <FormControl>
- <Input placeholder="e.g., premium" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
+ <div className="space-y-3">
+ {propertyFilters.map((filter, index) => (
+ <div key={index} className="flex gap-2 items-start">
+ <div className="flex-1 grid grid-cols-2 gap-2">
+ <Input
+ placeholder="e.g., plan_type"
+ value={filter.key}
+ onChange={e => {
+ const newFilters = [...propertyFilters];
+ newFilters[index].key = e.target.value;
+ setPropertyFilters(newFilters);
+ }}
+ />
+ <Input
+ placeholder="e.g., premium"
+ value={filter.value}
+ onChange={e => {
+ const newFilters = [...propertyFilters];
+ newFilters[index].value = e.target.value;
+ setPropertyFilters(newFilters);
+ }}
+ />
+ </div>
+ {propertyFilters.length > 1 && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={() => {
+ const newFilters = propertyFilters.filter((_, i) => i !== index);
+ setPropertyFilters(newFilters);
+ }}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ ))}
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setPropertyFilters([...propertyFilters, { key: "", value: "" }])}
+ className="w-full"
+ >
+ <Plus className="mr-2 h-4 w-4" />
+ Add Another Property
+ </Button>
</div>
)}
</div>
diff --git a/server/src/api/analytics/funnels/createFunnel.ts b/server/src/api/analytics/funnels/createFunnel.ts
index 0d9342c3b..ad05fb741 100644
--- a/server/src/api/analytics/funnels/createFunnel.ts
+++ b/server/src/api/analytics/funnels/createFunnel.ts
@@ -9,6 +9,13 @@ type FunnelStep = {
value: string;
name?: string;
type: "page" | "event";
+ hostname?: string;
+ eventPropertyKey?: string;
+ eventPropertyValue?: string | number | boolean;
+ propertyFilters?: Array<{
+ key: string;
+ value: string | number | boolean;
+ }>;
};
type Funnel = {
diff --git a/server/src/api/analytics/funnels/getFunnel.ts b/server/src/api/analytics/funnels/getFunnel.ts
index 66bcde1ce..b03281246 100644
--- a/server/src/api/analytics/funnels/getFunnel.ts
+++ b/server/src/api/analytics/funnels/getFunnel.ts
@@ -10,8 +10,14 @@ type FunnelStep = {
name?: string;
type: "page" | "event";
hostname?: string;
+ // Deprecated fields - kept for backwards compatibility
eventPropertyKey?: string;
eventPropertyValue?: string | number | boolean;
+ // New field for multiple property filters
+ propertyFilters?: Array<{
+ key: string;
+ value: string | number | boolean;
+ }>;
};
type Funnel = {
@@ -59,26 +65,41 @@ export async function getFunnel(
// 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}')`;
+
+ // Support both new propertyFilters array and legacy single property
+ const filters = step.propertyFilters || (
+ step.eventPropertyKey && step.eventPropertyValue !== undefined
+ ? [{ key: step.eventPropertyKey, value: step.eventPropertyValue }]
+ : []
+ );
+
+ // Add property matching for page steps (URL parameters)
+ for (const filter of filters) {
+ // Access URL parameters from the url_parameters map
+ const propValueAccessor = `url_parameters[${SqlString.escape(filter.key)}]`;
+
+ // URL parameters are stored as strings in the Map
+ condition += ` AND ${propValueAccessor} = ${SqlString.escape(String(filter.value))}`;
+ }
} else {
// Start with the base event match condition
condition = `type = 'custom_event' AND event_name = ${SqlString.escape(step.value)}`;
+ // Support both new propertyFilters array and legacy single property
+ const filters = step.propertyFilters || (
+ step.eventPropertyKey && step.eventPropertyValue !== undefined
+ ? [{ key: step.eventPropertyKey, value: step.eventPropertyValue }]
+ : []
+ );
+
// Add property matching if both key and value are provided
- if (step.eventPropertyKey && step.eventPropertyValue !== undefined) {
- // Access the sub-column directly for native JSON type
- const propValueAccessor = `props.${SqlString.escapeId(step.eventPropertyKey)}`;
-
- // Comparison needs to handle the dynamic type returned
- // Let ClickHouse handle the comparison based on the provided value type
- if (typeof step.eventPropertyValue === "string") {
- condition += ` AND toString(${propValueAccessor}) = ${SqlString.escape(step.eventPropertyValue)}`;
- } else if (typeof step.eventPropertyValue === "number") {
- // Use toFloat64 or toInt* depending on expected number type
- condition += ` AND toFloat64OrNull(${propValueAccessor}) = ${SqlString.escape(step.eventPropertyValue)}`;
- } else if (typeof step.eventPropertyValue === "boolean") {
- // Booleans might be stored as 0/1 or true/false in JSON
- // Comparing toUInt8 seems robust
- condition += ` AND toUInt8OrNull(${propValueAccessor}) = ${step.eventPropertyValue ? 1 : 0}`;
+ for (const filter of filters) {
+ if (typeof filter.value === "string") {
+ condition += ` AND JSONExtractString(toString(props), ${SqlString.escape(filter.key)}) = ${SqlString.escape(filter.value)}`;
+ } else if (typeof filter.value === "number") {
+ condition += ` AND toFloat64(JSONExtractString(toString(props), ${SqlString.escape(filter.key)})) = ${SqlString.escape(filter.value)}`;
+ } else if (typeof filter.value === "boolean") {
+ condition += ` AND JSONExtractString(toString(props), ${SqlString.escape(filter.key)}) = ${SqlString.escape(filter.value ? 'true' : 'false')}`;
}
}
}
@@ -103,7 +124,8 @@ export async function getFunnel(
event_name,
type,
props,
- hostname
+ hostname,
+ url_parameters
FROM events
WHERE
site_id = {siteId:Int32}
diff --git a/server/src/api/analytics/funnels/getFunnelStepSessions.ts b/server/src/api/analytics/funnels/getFunnelStepSessions.ts
index bbc3e8da4..8f5a98865 100644
--- a/server/src/api/analytics/funnels/getFunnelStepSessions.ts
+++ b/server/src/api/analytics/funnels/getFunnelStepSessions.ts
@@ -13,6 +13,10 @@ type FunnelStep = {
hostname?: string;
eventPropertyKey?: string;
eventPropertyValue?: string | number | boolean;
+ propertyFilters?: Array<{
+ key: string;
+ value: string | number | boolean;
+ }>;
};
type Funnel = {
@@ -72,24 +76,43 @@ export async function getFunnelStepSessions(req: FastifyRequest<GetFunnelStepSes
// Build conditional statements for each step we need
const stepsToCheck = mode === "reached" ? stepNumber : stepNumber + 1;
- const stepConditions = steps.slice(0, stepsToCheck).map((step, idx) => {
+ const stepConditions = steps.slice(0, stepsToCheck).map((step) => {
let condition = "";
if (step.type === "page") {
const regex = patternToRegex(step.value);
condition = `type = 'pageview' AND match(pathname, ${SqlString.escape(regex)})`;
+
+ // Support both new propertyFilters array and legacy single property
+ const filters = step.propertyFilters || (
+ step.eventPropertyKey && step.eventPropertyValue !== undefined
+ ? [{ key: step.eventPropertyKey, value: step.eventPropertyValue }]
+ : []
+ );
+
+ // Add property matching for page steps (URL parameters)
+ for (const filter of filters) {
+ const propValueAccessor = `url_parameters[${SqlString.escape(filter.key)}]`;
+ condition += ` AND ${propValueAccessor} = ${SqlString.escape(String(filter.value))}`;
+ }
} 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)}`;
+ // Support both new propertyFilters array and legacy single property
+ const filters = step.propertyFilters || (
+ step.eventPropertyKey && step.eventPropertyValue !== undefined
+ ? [{ key: step.eventPropertyKey, value: step.eventPropertyValue }]
+ : []
+ );
- 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}`;
+ // Add property matching for event steps
+ for (const filter of filters) {
+ if (typeof filter.value === "string") {
+ condition += ` AND JSONExtractString(toString(props), ${SqlString.escape(filter.key)}) = ${SqlString.escape(filter.value)}`;
+ } else if (typeof filter.value === "number") {
+ condition += ` AND toFloat64(JSONExtractString(toString(props), ${SqlString.escape(filter.key)})) = ${SqlString.escape(filter.value)}`;
+ } else if (typeof filter.value === "boolean") {
+ condition += ` AND JSONExtractString(toString(props), ${SqlString.escape(filter.key)}) = ${SqlString.escape(filter.value ? 'true' : 'false')}`;
}
}
}
@@ -112,7 +135,8 @@ export async function getFunnelStepSessions(req: FastifyRequest<GetFunnelStepSes
event_name,
type,
props,
- hostname
+ hostname,
+ url_parameters
FROM events
WHERE
site_id = {siteId:Int32}
diff --git a/server/src/api/analytics/goals/createGoal.ts b/server/src/api/analytics/goals/createGoal.ts
index a3dedcc27..aac36e664 100644
--- a/server/src/api/analytics/goals/createGoal.ts
+++ b/server/src/api/analytics/goals/createGoal.ts
@@ -40,6 +40,10 @@ const goalBodySchema = z
eventName: z.string().optional(),
eventPropertyKey: z.string().optional(),
eventPropertyValue: z.union([z.string(), z.number(), z.boolean()]).optional(),
+ propertyFilters: z.array(z.object({
+ key: z.string(),
+ value: z.union([z.string(), z.number(), z.boolean()]),
+ })).optional(),
}),
})
.refine(
diff --git a/server/src/api/analytics/goals/getGoalSessions.ts b/server/src/api/analytics/goals/getGoalSessions.ts
index c5783609c..535e5a98c 100644
--- a/server/src/api/analytics/goals/getGoalSessions.ts
+++ b/server/src/api/analytics/goals/getGoalSessions.ts
@@ -55,6 +55,19 @@ export async function getGoalSessions(req: FastifyRequest<GetGoalSessionsRequest
const regex = patternToRegex(pathPattern);
goalCondition = `type = 'pageview' AND match(pathname, ${SqlString.escape(regex)})`;
+
+ // Support both new propertyFilters array and legacy single property
+ const filters = goalData.config.propertyFilters || (
+ goalData.config.eventPropertyKey && goalData.config.eventPropertyValue !== undefined
+ ? [{ key: goalData.config.eventPropertyKey, value: goalData.config.eventPropertyValue }]
+ : []
+ );
+
+ // Add property matching for page goals (URL parameters)
+ for (const filter of filters) {
+ const propValueAccessor = `url_parameters[${SqlString.escape(filter.key)}]`;
+ goalCondition += ` AND ${propValueAccessor} = ${SqlString.escape(String(filter.value))}`;
+ }
} else if (goalData.goalType === "event") {
const eventName = goalData.config.eventName;
if (!eventName) {
@@ -63,19 +76,21 @@ export async function getGoalSessions(req: FastifyRequest<GetGoalSessionsRequest
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}`;
+ // Support both new propertyFilters array and legacy single property
+ const filters = goalData.config.propertyFilters || (
+ goalData.config.eventPropertyKey && goalData.config.eventPropertyValue !== undefined
+ ? [{ key: goalData.config.eventPropertyKey, value: goalData.config.eventPropertyValue }]
+ : []
+ );
+
+ // Add property matching for event goals
+ for (const filter of filters) {
+ if (typeof filter.value === "string") {
+ goalCondition += ` AND JSONExtractString(toString(props), ${SqlString.escape(filter.key)}) = ${SqlString.escape(filter.value)}`;
+ } else if (typeof filter.value === "number") {
+ goalCondition += ` AND toFloat64(JSONExtractString(toString(props), ${SqlString.escape(filter.key)})) = ${SqlString.escape(filter.value)}`;
+ } else if (typeof filter.value === "boolean") {
+ goalCondition += ` AND JSONExtractString(toString(props), ${SqlString.escape(filter.key)}) = ${SqlString.escape(filter.value ? 'true' : 'false')}`;
}
}
} else {
diff --git a/server/src/api/analytics/goals/getGoals.ts b/server/src/api/analytics/goals/getGoals.ts
index c5a003280..2aa7e7c00 100644
--- a/server/src/api/analytics/goals/getGoals.ts
+++ b/server/src/api/analytics/goals/getGoals.ts
@@ -153,38 +153,53 @@ export async function getGoals(
if (!pathPattern) continue;
const regex = patternToRegex(pathPattern);
+ let pathClause = `type = 'pageview' AND match(pathname, ${SqlString.escape(regex)})`;
+
+ // Support both new propertyFilters array and legacy single property
+ const filters = goal.config.propertyFilters || (
+ goal.config.eventPropertyKey && goal.config.eventPropertyValue !== undefined
+ ? [{ key: goal.config.eventPropertyKey, value: goal.config.eventPropertyValue }]
+ : []
+ );
+
+ // Add property matching for page goals (URL parameters)
+ for (const filter of filters) {
+ // Access URL parameters from the url_parameters map
+ const propValueAccessor = `url_parameters[${SqlString.escape(filter.key)}]`;
+
+ // URL parameters are stored as strings in the Map
+ pathClause += ` AND ${propValueAccessor} = ${SqlString.escape(String(filter.value))}`;
+ }
+
conditionalClauses.push(`
COUNT(DISTINCT IF(
- type = 'pageview' AND match(pathname, ${SqlString.escape(regex)}),
+ ${pathClause},
session_id,
NULL
)) AS goal_${goal.goalId}_conversions
`);
} else if (goal.goalType === "event") {
const eventName = goal.config.eventName;
- const eventPropertyKey = goal.config.eventPropertyKey;
- const eventPropertyValue = goal.config.eventPropertyValue;
if (!eventName) continue;
let eventClause = `type = 'custom_event' AND event_name = ${SqlString.escape(eventName)}`;
+ // Support both new propertyFilters array and legacy single property
+ const filters = goal.config.propertyFilters || (
+ goal.config.eventPropertyKey && goal.config.eventPropertyValue !== undefined
+ ? [{ key: goal.config.eventPropertyKey, value: goal.config.eventPropertyValue }]
+ : []
+ );
+
// Add property matching if needed
- if (eventPropertyKey && eventPropertyValue !== undefined) {
- // Access the sub-column directly for native JSON type
- const propValueAccessor = `props.${SqlString.escapeId(eventPropertyKey)}`;
-
- // Comparison needs to handle the Dynamic type returned
- // Let ClickHouse handle the comparison based on the provided value type
- if (typeof eventPropertyValue === "string") {
- eventClause += ` AND toString(${propValueAccessor}) = ${SqlString.escape(eventPropertyValue)}`;
- } else if (typeof eventPropertyValue === "number") {
- // Use toFloat64 or toInt* depending on expected number type
- eventClause += ` AND toFloat64OrNull(${propValueAccessor}) = ${SqlString.escape(eventPropertyValue)}`;
- } else if (typeof eventPropertyValue === "boolean") {
- // Booleans might be stored as 0/1 or true/false in JSON
- // Comparing toUInt8 seems robust
- eventClause += ` AND toUInt8OrNull(${propValueAccessor}) = ${eventPropertyValue ? 1 : 0}`;
+ for (const filter of filters) {
+ if (typeof filter.value === "string") {
+ eventClause += ` AND JSONExtractString(toString(props), ${SqlString.escape(filter.key)}) = ${SqlString.escape(filter.value)}`;
+ } else if (typeof filter.value === "number") {
+ eventClause += ` AND toFloat64(JSONExtractString(toString(props), ${SqlString.escape(filter.key)})) = ${SqlString.escape(filter.value)}`;
+ } else if (typeof filter.value === "boolean") {
+ eventClause += ` AND JSONExtractString(toString(props), ${SqlString.escape(filter.key)}) = ${SqlString.escape(filter.value ? 'true' : 'false')}`;
}
}
diff --git a/server/src/api/analytics/goals/updateGoal.ts b/server/src/api/analytics/goals/updateGoal.ts
index b00c29a98..b18829262 100644
--- a/server/src/api/analytics/goals/updateGoal.ts
+++ b/server/src/api/analytics/goals/updateGoal.ts
@@ -43,6 +43,10 @@ const updateGoalSchema = z
eventName: z.string().optional(),
eventPropertyKey: z.string().optional(),
eventPropertyValue: z.union([z.string(), z.number(), z.boolean()]).optional(),
+ propertyFilters: z.array(z.object({
+ key: z.string(),
+ value: z.union([z.string(), z.number(), z.boolean()]),
+ })).optional(),
}),
})
.refine(
diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.ts
index e29e73bcf..ff3f0a64b 100644
--- a/server/src/db/postgres/schema.ts
+++ b/server/src/db/postgres/schema.ts
@@ -253,8 +253,13 @@ export const goals = pgTable(
pathPattern?: string; // e.g., "/pricing", "/product/*/view", "/docs/**"
// For 'event' type
eventName?: string; // e.g., "signup_completed", "file_downloaded"
- eventPropertyKey?: string; // Optional property key to match
- eventPropertyValue?: string | number | boolean; // Optional property value to match (exact match)
+ // Property filters (for both path and event types)
+ eventPropertyKey?: string; // Deprecated - use propertyFilters instead
+ eventPropertyValue?: string | number | boolean; // Deprecated - use propertyFilters instead
+ propertyFilters?: Array<{
+ key: string;
+ value: string | number | boolean;
+ }>; // Array of property filters to match (all must match)
}>(),
createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
},