Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

feat: improve filters for profiles and sessions

Carl-Gerhard Lindesvärdeab216a09e85
diff --git a/apps/api/src/controllers/export.controller.ts b/apps/api/src/controllers/export.controller.ts
index d1f8de94a..15b045c03 100644
--- a/apps/api/src/controllers/export.controller.ts
+++ b/apps/api/src/controllers/export.controller.ts
@@ -8,7 +8,7 @@ import {
getEventsCount,
getSettingsForProject,
} from '@openpanel/db';
-import { zChartEvent, zReport } from '@openpanel/validation';
+import { zChartEvent, zChartEventFilter, zReport } from '@openpanel/validation';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { z } from 'zod';
import { HttpError } from '@/utils/errors';
@@ -69,6 +69,20 @@ export const eventsScheme = z.object({
end: z.coerce.string().optional(),
page: z.coerce.number().optional().default(1),
limit: z.coerce.number().optional().default(50),
+ filters: z
+ .preprocess((value) => {
+ if (value == null || value === '') return undefined;
+ if (Array.isArray(value)) return value;
+ if (typeof value === 'string') {
+ try {
+ return JSON.parse(value);
+ } catch {
+ return undefined;
+ }
+ }
+ return value;
+ }, z.array(zChartEventFilter))
+ .optional(),
includes: z
.preprocess(
(arg) => {
@@ -96,7 +110,7 @@ export async function events(
reply: FastifyReply
) {
const projectId = await getProjectId(request);
- const { limit, page: rawPage, event, start, end, profileId, includes } = request.query;
+ const { limit, page: rawPage, event, start, end, profileId, includes, filters } = request.query;
const take = Math.max(Math.min(limit, 1000), 1);
const cursor = Math.max(rawPage, 1) - 1;
const options: GetEventListOptions = {
@@ -107,6 +121,7 @@ export async function events(
cursor,
take,
profileId,
+ filters,
select: {
profile: false,
meta: false,
diff --git a/apps/api/src/controllers/insights.controller.ts b/apps/api/src/controllers/insights.controller.ts
index 6ad02a44c..7f7daed16 100644
--- a/apps/api/src/controllers/insights.controller.ts
+++ b/apps/api/src/controllers/insights.controller.ts
@@ -43,6 +43,26 @@ import {
type TrafficColumn,
} from '@openpanel/db';
import { zChartEventFilter, zRange } from '@openpanel/validation';
+
+/**
+ * REST querystrings can't carry arrays of objects natively. Callers pass
+ * `filters` as a URL-encoded JSON string; we decode it here. Empty string and
+ * already-parsed arrays (e.g. from server-side dispatch) are both accepted.
+ */
+const zFiltersParam = z
+ .preprocess((value) => {
+ if (value == null || value === '') return undefined;
+ if (Array.isArray(value)) return value;
+ if (typeof value === 'string') {
+ try {
+ return JSON.parse(value);
+ } catch {
+ return undefined;
+ }
+ }
+ return value;
+ }, z.array(zChartEventFilter))
+ .optional();
import type { FastifyReply, FastifyRequest } from 'fastify';
import { z } from 'zod';
@@ -442,6 +462,7 @@ export const zEventsQuery = zDateRange.extend({
referrerType: z.string().optional(),
profileId: z.string().optional(),
properties: z.record(z.string(), z.string()).optional(),
+ filters: zFiltersParam,
limit: z.number().int().min(1).max(100).default(20),
});
@@ -495,6 +516,7 @@ export const zProfilesQuery = z.object({
inactiveDays: z.number().int().min(1).optional(),
minSessions: z.number().int().min(1).optional(),
performedEvent: z.string().optional(),
+ filters: zFiltersParam,
sortOrder: z.enum(['asc', 'desc']).default('desc'),
limit: z.number().int().min(1).max(100).default(20),
});
@@ -553,6 +575,7 @@ export const zSessionsQuery = zDateRange.extend({
referrerName: z.string().optional(),
referrerType: z.string().optional(),
profileId: z.string().optional(),
+ filters: zFiltersParam,
limit: z.number().int().min(1).max(100).default(20),
});
diff --git a/apps/start/src/components/cohort/cohort-criteria-builder.tsx b/apps/start/src/components/cohort/cohort-criteria-builder.tsx
index e2b7ef214..ed9c199fc 100644
--- a/apps/start/src/components/cohort/cohort-criteria-builder.tsx
+++ b/apps/start/src/components/cohort/cohort-criteria-builder.tsx
@@ -477,7 +477,7 @@ function EventCriteriaItem({
onSelect={(action) => {
addFilter(action.value);
}}
- mode="events"
+ categories={['event']}
>
{(setOpen) => (
<Button
@@ -612,7 +612,7 @@ function PropertyBasedBuilder({
onSelect={(action) => {
addPropertyFilter(action.value);
}}
- mode="profile"
+ categories={['profile']}
>
{(setOpen) => (
<Button
diff --git a/apps/start/src/components/filters/FiltersBuilder.tsx b/apps/start/src/components/filters/FiltersBuilder.tsx
new file mode 100644
index 000000000..64ace316a
--- /dev/null
+++ b/apps/start/src/components/filters/FiltersBuilder.tsx
@@ -0,0 +1,148 @@
+import { FilterIcon } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import {
+ PropertiesCombobox,
+ type PropertiesComboboxCategory,
+} from '@/components/report/sidebar/PropertiesCombobox';
+import { PureCohortFilterItem } from '@/components/report/sidebar/filters/CohortFilterItem';
+import { PureFilterItem } from '@/components/report/sidebar/filters/FilterItem';
+import type {
+ IChartEventFilter,
+ IChartEventFilterOperator,
+ IChartEventFilterValue,
+} from '@openpanel/validation';
+
+interface FiltersBuilderProps {
+ value: IChartEventFilter[];
+ onChange: (next: IChartEventFilter[]) => void;
+ categories?: PropertiesComboboxCategory[];
+ /** Event name to scope value-autocomplete suggestions. Optional. */
+ eventName?: string;
+ /** Label on the "Add filter" trigger button. */
+ addLabel?: string;
+ className?: string;
+}
+
+/**
+ * Prop-driven filter list reusing the report editor's PropertiesCombobox +
+ * Pure filter item components. Use this on any surface (sessions / profiles /
+ * events tables, future dashboards) that needs the same affordance the chart
+ * editor exposes, without coupling to Redux.
+ */
+export function FiltersBuilder({
+ value,
+ onChange,
+ categories = ['event', 'profile', 'group', 'cohort'],
+ eventName = '',
+ addLabel = 'Add filter',
+ className,
+}: FiltersBuilderProps) {
+ const setFilter = (updated: IChartEventFilter) => {
+ onChange(value.map((f) => (f.id === updated.id ? updated : f)));
+ };
+
+ const removeFilter = (target: IChartEventFilter) => {
+ onChange(value.filter((f) => f.id !== target.id));
+ };
+
+ const addFilter = (action: {
+ value: string;
+ cohortId?: string;
+ }) => {
+ // Use the property name as the id so the URL serializer can encode the
+ // filter under a stable, human-readable key. A random id would survive
+ // round-trips through the URL but would replace the human-readable
+ // `name` on reload — see useTableFilters serialize/parse logic.
+ const next: IChartEventFilter = action.cohortId
+ ? {
+ id: action.value,
+ name: action.value,
+ operator: 'inCohort',
+ value: [],
+ cohortId: action.cohortId,
+ }
+ : {
+ id: action.value,
+ name: action.value,
+ operator: 'is',
+ value: [],
+ };
+ onChange([...value, next]);
+ };
+
+ return (
+ <div className={className}>
+ <div className="col gap-2">
+ {value.map((filter) => {
+ const isCohort =
+ filter.operator === 'inCohort' || filter.operator === 'notInCohort';
+ if (isCohort) {
+ return (
+ <PureCohortFilterItem
+ key={filter.id}
+ filter={filter}
+ className="rounded border bg-def-100 p-3"
+ onRemove={removeFilter}
+ onChangeOperator={(operator, original) =>
+ setFilter({ ...original, operator })
+ }
+ onChangeCohort={(cohortIds, original) => {
+ const firstId = cohortIds[0];
+ setFilter({
+ ...original,
+ name: firstId ? `cohort:${firstId}` : original.name,
+ cohortId: firstId,
+ cohortIds,
+ });
+ }}
+ />
+ );
+ }
+ return (
+ <PureFilterItem
+ key={filter.id}
+ filter={filter}
+ eventName={eventName}
+ className="rounded border bg-def-100 p-3"
+ immediateInput
+ onRemove={removeFilter}
+ onChangeValue={(nextValue: IChartEventFilterValue[], original) =>
+ setFilter({ ...original, value: nextValue })
+ }
+ onChangeOperator={(
+ operator: IChartEventFilterOperator,
+ original,
+ ) =>
+ setFilter({
+ ...original,
+ operator,
+ // Reset value when switching to/from cohort-like operators,
+ // mirroring the report editor's behaviour.
+ value: original.value.filter(Boolean).slice(0, 1),
+ })
+ }
+ />
+ );
+ })}
+ </div>
+ <div className="mt-2">
+ <PropertiesCombobox
+ categories={categories}
+ onSelect={addFilter}
+ event={eventName ? ({ name: eventName, id: 'builder' } as never) : undefined}
+ >
+ {(setOpen) => (
+ <Button
+ variant="outline"
+ size="sm"
+ icon={FilterIcon}
+ onClick={() => setOpen((p) => !p)}
+ >
+ {addLabel}
+ </Button>
+ )}
+ </PropertiesCombobox>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/start/src/components/filters/TableFilterPills.tsx b/apps/start/src/components/filters/TableFilterPills.tsx
new file mode 100644
index 000000000..e6b5aac61
--- /dev/null
+++ b/apps/start/src/components/filters/TableFilterPills.tsx
@@ -0,0 +1,164 @@
+import { FilterIcon, X } from 'lucide-react';
+import type { Options as NuqsOptions } from 'nuqs';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import type { PropertiesComboboxCategory } from '@/components/report/sidebar/PropertiesCombobox';
+import { useAppParams } from '@/hooks/use-app-params';
+import { useCohorts } from '@/hooks/use-cohorts';
+import { useTableFilters } from '@/hooks/use-table-filters';
+import { pushModal } from '@/modals';
+import { getPropertyLabel } from '@/translations/properties';
+import { cn } from '@/utils/cn';
+import { operators } from '@openpanel/constants';
+import {
+ getCohortIds,
+ type IChartEventFilter,
+} from '@openpanel/validation';
+
+interface TableFilterPillsProps {
+ /** URL key the filters live under. Sessions tables use `f`. */
+ urlKey: string;
+ /** Categories surfaced when the user opens the sheet to add a filter. */
+ categories: PropertiesComboboxCategory[];
+ /** Header rendered inside the sheet. */
+ title?: string;
+ className?: string;
+ /** Forwarded to `useTableFilters` (e.g. to disable URL push). */
+ nuqsOptions?: NuqsOptions;
+}
+
+/** Friendly labels for the hard-coded session.* filter family. */
+const SESSION_LABELS: Record<string, string> = {
+ 'session.is_bounce': 'Bounced',
+ 'session.screen_view_count': 'Screen views',
+ 'session.event_count': 'Events',
+ 'session.duration': 'Duration',
+ 'session.revenue': 'Revenue',
+ 'session.performed_event': 'Performed event',
+};
+
+function humanizeFilterName(name: string): string {
+ if (name.startsWith('cohort:')) return 'Cohort';
+ if (SESSION_LABELS[name]) return SESSION_LABELS[name]!;
+ if (name.startsWith('profile.')) {
+ const rest = name.replace(/^profile\./, '');
+ return `Profile · ${rest.replace(/^properties\./, '')}`;
+ }
+ if (name.startsWith('group.')) {
+ const rest = name.replace(/^group\./, '');
+ return `Group · ${rest.replace(/^properties\./, '')}`;
+ }
+ return getPropertyLabel(name);
+}
+
+function formatFilterValue(filter: IChartEventFilter): string {
+ if (filter.name === 'session.is_bounce') {
+ const v = filter.value[0];
+ if (v === undefined) return '';
+ const truthy =
+ typeof v === 'boolean' ? v : String(v).toLowerCase() === 'true';
+ return truthy ? 'Yes' : 'No';
+ }
+ return filter.value
+ .filter((v) => v !== null && v !== undefined && v !== '')
+ .map(String)
+ .join(', ');
+}
+
+export function TableFilterPills({
+ urlKey,
+ categories,
+ title,
+ className,
+ nuqsOptions,
+}: TableFilterPillsProps) {
+ const { projectId } = useAppParams();
+ const [filters, setFilters] = useTableFilters(urlKey, nuqsOptions);
+ const cohorts = useCohorts(
+ { projectId, includeCount: false },
+ { enabled: categories.includes('cohort') },
+ );
+ const cohortNames = new Map(cohorts.map((c) => [c.id, c.name]));
+
+ const openSheet = () => {
+ pushModal('TableFilters', {
+ urlKey,
+ categories,
+ title,
+ });
+ };
+
+ const removeAt = (index: number) => {
+ setFilters(filters.filter((_, i) => i !== index));
+ };
+
+ return (
+ <div className={cn('row flex-wrap items-center gap-2', className)}>
+ <Button
+ variant="outline"
+ size="sm"
+ icon={FilterIcon}
+ onClick={openSheet}
+ >
+ Filters
+ {filters.length > 0 && (
+ <Badge className="ml-2 rounded-full px-1.5 py-0 text-xs">
+ {filters.length}
+ </Badge>
+ )}
+ </Button>
+ {filters.map((filter, index) => {
+ const isCohort =
+ filter.operator === 'inCohort' || filter.operator === 'notInCohort';
+ const cohortIds = isCohort ? getCohortIds(filter) : [];
+ const valueText = isCohort
+ ? cohortIds
+ .map(
+ (id) => cohortNames.get(id) ?? cohortNames.get(id.replace(/^cohort:/, '')),
+ )
+ .filter(Boolean)
+ .join(', ') || 'pick cohort'
+ : formatFilterValue(filter);
+
+ return (
+ <div
+ key={`${filter.name}-${index}`}
+ className="flex items-stretch text-sm border rounded-md overflow-hidden h-8 bg-card"
+ >
+ <button
+ type="button"
+ onClick={openSheet}
+ className="px-2 hover:bg-accent transition-colors cursor-pointer"
+ >
+ {humanizeFilterName(filter.name)}
+ </button>
+ <button
+ type="button"
+ onClick={openSheet}
+ className="px-2 opacity-50 lowercase hover:opacity-100 hover:bg-accent transition-colors border-l cursor-pointer"
+ >
+ {operators[filter.operator] ?? filter.operator}
+ </button>
+ {valueText && (
+ <button
+ type="button"
+ onClick={openSheet}
+ className="px-2 font-semibold hover:bg-accent transition-colors border-l cursor-pointer max-w-40 truncate"
+ >
+ {valueText}
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={() => removeAt(index)}
+ className="px-2 hover:bg-destructive hover:text-destructive-foreground transition-colors border-l cursor-pointer"
+ aria-label="Remove filter"
+ >
+ <X className="size-3" />
+ </button>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/apps/start/src/components/profiles/table/index.tsx b/apps/start/src/components/profiles/table/index.tsx
index 9c534b313..38f2d05c3 100644
--- a/apps/start/src/components/profiles/table/index.tsx
+++ b/apps/start/src/components/profiles/table/index.tsx
@@ -5,6 +5,7 @@ import type { PaginationState, Table, Updater } from '@tanstack/react-table';
import { getCoreRowModel, useReactTable } from '@tanstack/react-table';
import { memo, useCallback } from 'react';
import { useColumns } from './columns';
+import { TableFilterPills } from '@/components/filters/TableFilterPills';
import { DataTable } from '@/components/ui/data-table/data-table';
import {
useDataTableColumnVisibility,
@@ -110,13 +111,21 @@ export const ProfilesTable = memo(
function ProfileTableToolbar({ table }: { table: Table<IServiceProfile> }) {
const { search, setSearch } = useSearchQueryState();
+
return (
<DataTableToolbarContainer>
- <AnimatedSearchInput
- onChange={setSearch}
- placeholder="Search profiles"
- value={search}
- />
+ <div className="flex flex-1 flex-wrap items-center gap-2">
+ <AnimatedSearchInput
+ onChange={setSearch}
+ placeholder="Search profiles"
+ value={search}
+ />
+ <TableFilterPills
+ urlKey="f"
+ categories={['profile', 'group', 'cohort']}
+ title="Profile filters"
+ />
+ </div>
<DataTableViewOptions table={table} />
</DataTableToolbarContainer>
);
diff --git a/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx b/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx
index 9cd2e37aa..146c3fe3b 100644
--- a/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx
+++ b/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx
@@ -2,6 +2,7 @@ import type { IChartEvent } from '@openpanel/validation';
import { useQuery } from '@tanstack/react-query';
import { AnimatePresence, motion } from 'framer-motion';
import {
+ ActivityIcon,
ArrowLeftIcon,
Building2Icon,
DatabaseIcon,
@@ -32,17 +33,69 @@ export type PropertiesComboboxAction = {
cohortId?: string;
};
+export type PropertiesComboboxCategory =
+ | 'event'
+ | 'profile'
+ | 'group'
+ | 'cohort'
+ | 'session';
+
+type State = 'index' | PropertiesComboboxCategory;
+
interface PropertiesComboboxProps {
event?: IChartEvent;
children: (setOpen: Dispatch<SetStateAction<boolean>>) => React.ReactNode;
onSelect: (action: PropertiesComboboxAction) => void;
exclude?: string[];
include?: string[];
- mode?: 'events' | 'profile';
- showCohorts?: boolean;
+ categories?: PropertiesComboboxCategory[];
isBreakdown?: boolean;
}
+/**
+ * Hard-coded session-level filters exposed alongside event/profile/group/cohort
+ * dimensions. These map to the `session.*` filter prefix handled by the DB
+ * filter-where utility.
+ */
+const SESSION_ACTIONS: PropertiesComboboxAction[] = [
+ {
+ value: 'session.is_bounce',
+ label: 'Bounced',
+ description: 'Single-pageview session',
+ },
+ {
+ value: 'session.screen_view_count',
+ label: 'Screen views',
+ description: 'Number of screen views in the session',
+ },
+ {
+ value: 'session.event_count',
+ label: 'Events',
+ description: 'Total events in the session',
+ },
+ {
+ value: 'session.duration',
+ label: 'Duration',
+ description: 'Session length in milliseconds',
+ },
+ {
+ value: 'session.revenue',
+ label: 'Revenue',
+ description: 'Revenue attributed to the session',
+ },
+ {
+ value: 'session.performed_event',
+ label: 'Performed event',
+ description: 'Session contains an event named X',
+ },
+];
+
+const DEFAULT_CATEGORIES: PropertiesComboboxCategory[] = [
+ 'event',
+ 'profile',
+ 'group',
+];
+
function SearchHeader({
onBack,
onSearch,
@@ -73,10 +126,9 @@ export function PropertiesCombobox({
event,
children,
onSelect,
- mode,
+ categories = DEFAULT_CATEGORIES,
exclude = [],
include = [],
- showCohorts = false,
isBreakdown = false,
}: PropertiesComboboxProps) {
const { projectId } = useAppParams();
@@ -87,23 +139,29 @@ export function PropertiesCombobox({
projectId,
});
const groupPropertiesQuery = useQuery(
- trpc.group.properties.queryOptions({ projectId })
+ trpc.group.properties.queryOptions(
+ { projectId },
+ { enabled: categories.includes('group') },
+ ),
);
const cohorts = useCohorts(
{ projectId, includeCount: false },
- { enabled: showCohorts },
+ { enabled: categories.includes('cohort') },
);
- const [state, setState] = useState<
- 'index' | 'event' | 'profile' | 'group' | 'cohort'
- >('index');
+
+ /** Skip the index screen when only one category is reachable. */
+ const initialState: State =
+ categories.length === 1 ? categories[0]! : 'index';
+
+ const [state, setState] = useState<State>(initialState);
const [search, setSearch] = useState('');
const [direction, setDirection] = useState<'forward' | 'backward'>('forward');
useEffect(() => {
if (!open) {
- setState(mode ? (mode === 'events' ? 'event' : 'profile') : 'index');
+ setState(initialState);
}
- }, [open, mode]);
+ }, [open, initialState]);
const matchesPropertyPattern = (property: string, pattern: string) => {
if (pattern.endsWith('*')) {
@@ -118,7 +176,6 @@ export function PropertiesCombobox({
const allProperties = Array.from(new Set([...properties, ...include]));
- // Fixed group properties: name, type, plus dynamic property keys
const groupActions = [
{ value: 'group.name', label: 'name', description: 'group' },
{ value: 'group.type', label: 'type', description: 'group' },
@@ -149,10 +206,11 @@ export function PropertiesCombobox({
label: property.split('.').pop() ?? property,
description: property.split('.').slice(0, -1).join('.'),
}));
+ const sessionActions = SESSION_ACTIONS.filter((a) =>
+ shouldShowProperty(a.value),
+ );
- const handleStateChange = (
- newState: 'index' | 'event' | 'profile' | 'group' | 'cohort'
- ) => {
+ const handleStateChange = (newState: State) => {
setDirection(newState === 'index' ? 'backward' : 'forward');
setState(newState);
};
@@ -171,42 +229,48 @@ export function PropertiesCombobox({
cohortId: cohort.id,
}));
+ const showBackButton = categories.length > 1;
+
const renderIndex = () => {
return (
<DropdownMenuGroup>
- {/* <SearchHeader onSearch={() => {}} value={search} /> */}
- {/* <DropdownMenuSeparator /> */}
- <DropdownMenuItem
- className="group justify-between gap-2"
- onClick={(e) => {
- e.preventDefault();
- handleStateChange('event');
- }}
- >
- Event properties
- <DatabaseIcon className="size-4 transition-all group-hover:rotate-12 group-hover:scale-125 group-hover:text-blue-500" />
- </DropdownMenuItem>
- <DropdownMenuItem
- className="group justify-between gap-2"
- onClick={(e) => {
- e.preventDefault();
- handleStateChange('profile');
- }}
- >
- Profile properties
- <UserIcon className="size-4 transition-all group-hover:rotate-12 group-hover:scale-125 group-hover:text-blue-500" />
- </DropdownMenuItem>
- <DropdownMenuItem
- className="group justify-between gap-2"
- onClick={(e) => {
- e.preventDefault();
- handleStateChange('group');
- }}
- >
- Group properties
- <Building2Icon className="size-4 transition-all group-hover:rotate-12 group-hover:scale-125 group-hover:text-blue-500" />
- </DropdownMenuItem>
- {showCohorts && (
+ {categories.includes('event') && (
+ <DropdownMenuItem
+ className="group justify-between gap-2"
+ onClick={(e) => {
+ e.preventDefault();
+ handleStateChange('event');
+ }}
+ >
+ Event properties
+ <DatabaseIcon className="size-4 transition-all group-hover:rotate-12 group-hover:scale-125 group-hover:text-blue-500" />
+ </DropdownMenuItem>
+ )}
+ {categories.includes('profile') && (
+ <DropdownMenuItem
+ className="group justify-between gap-2"
+ onClick={(e) => {
+ e.preventDefault();
+ handleStateChange('profile');
+ }}
+ >
+ Profile properties
+ <UserIcon className="size-4 transition-all group-hover:rotate-12 group-hover:scale-125 group-hover:text-blue-500" />
+ </DropdownMenuItem>
+ )}
+ {categories.includes('group') && (
+ <DropdownMenuItem
+ className="group justify-between gap-2"
+ onClick={(e) => {
+ e.preventDefault();
+ handleStateChange('group');
+ }}
+ >
+ Group properties
+ <Building2Icon className="size-4 transition-all group-hover:rotate-12 group-hover:scale-125 group-hover:text-blue-500" />
+ </DropdownMenuItem>
+ )}
+ {categories.includes('cohort') && (
<DropdownMenuItem
className="group justify-between gap-2"
onClick={(e) => {
@@ -226,149 +290,45 @@ export function PropertiesCombobox({
<TargetIcon className="size-4 transition-all group-hover:rotate-12 group-hover:scale-125 group-hover:text-blue-500" />
</DropdownMenuItem>
)}
+ {categories.includes('session') && (
+ <DropdownMenuItem
+ className="group justify-between gap-2"
+ onClick={(e) => {
+ e.preventDefault();
+ handleStateChange('session');
+ }}
+ >
+ Session metrics
+ <ActivityIcon className="size-4 transition-all group-hover:rotate-12 group-hover:scale-125 group-hover:text-blue-500" />
+ </DropdownMenuItem>
+ )}
</DropdownMenuGroup>
);
};
- const renderCohort = () => {
- const filteredActions = cohortActions.filter(
+ const renderActionList = (
+ actions: PropertiesComboboxAction[],
+ options: { itemKey?: string } = {},
+ ) => {
+ const filtered = actions.filter(
(action) =>
action.label.toLowerCase().includes(search.toLowerCase()) ||
action.description.toLowerCase().includes(search.toLowerCase()),
);
- return (
- <div className="flex flex-col">
- <SearchHeader
- onBack={() => handleStateChange('index')}
- onSearch={setSearch}
- value={search}
- />
- <DropdownMenuSeparator />
- <VirtualList
- data={filteredActions}
- height={Math.min(300, filteredActions.length * 40 + 8)}
- itemHeight={40}
- itemKey="value"
- >
- {(action) => (
- <motion.div
- animate={{ opacity: 1, y: 0 }}
- className="col cursor-pointer gap-px rounded-md p-2 hover:bg-accent"
- initial={{ opacity: 0, y: 10 }}
- onClick={() => handleSelect(action)}
- >
- <div className="font-medium">{action.label}</div>
- <div className="text-muted-foreground text-sm">
- {action.description}
- </div>
- </motion.div>
- )}
- </VirtualList>
- </div>
- );
- };
-
- const renderEvent = () => {
- const filteredActions = eventActions.filter(
- (action) =>
- action.label.toLowerCase().includes(search.toLowerCase()) ||
- action.description.toLowerCase().includes(search.toLowerCase())
- );
-
return (
<div className="col">
<SearchHeader
- onBack={
- mode === undefined ? () => handleStateChange('index') : undefined
- }
+ onBack={showBackButton ? () => handleStateChange('index') : undefined}
onSearch={setSearch}
value={search}
/>
<DropdownMenuSeparator />
<VirtualList
- data={filteredActions}
- height={300}
+ data={filtered}
+ height={Math.min(300, Math.max(40, filtered.length * 40 + 8))}
itemHeight={40}
- itemKey="id"
- >
- {(action) => (
- <motion.div
- animate={{ opacity: 1, y: 0 }}
- className="col cursor-pointer gap-px rounded-md p-2 hover:bg-accent"
- initial={{ opacity: 0, y: 10 }}
- onClick={() => handleSelect(action)}
- >
- <div className="font-medium">{action.label}</div>
- <div className="text-muted-foreground text-sm">
- {action.description}
- </div>
- </motion.div>
- )}
- </VirtualList>
- </div>
- );
- };
-
- const renderProfile = () => {
- const filteredActions = profileActions.filter(
- (action) =>
- action.label.toLowerCase().includes(search.toLowerCase()) ||
- action.description.toLowerCase().includes(search.toLowerCase())
- );
-
- return (
- <div className="flex flex-col">
- <SearchHeader
- onBack={() => handleStateChange('index')}
- onSearch={setSearch}
- value={search}
- />
- <DropdownMenuSeparator />
- <VirtualList
- data={filteredActions}
- height={300}
- itemHeight={40}
- itemKey="id"
- >
- {(action) => (
- <motion.div
- animate={{ opacity: 1, y: 0 }}
- className="col cursor-pointer gap-px rounded-md p-2 hover:bg-accent"
- initial={{ opacity: 0, y: 10 }}
- onClick={() => handleSelect(action)}
- >
- <div className="font-medium">{action.label}</div>
- <div className="text-muted-foreground text-sm">
- {action.description}
- </div>
- </motion.div>
- )}
- </VirtualList>
- </div>
- );
- };
-
- const renderGroup = () => {
- const filteredActions = groupActions.filter(
- (action) =>
- action.label.toLowerCase().includes(search.toLowerCase()) ||
- action.description.toLowerCase().includes(search.toLowerCase())
- );
-
- return (
- <div className="flex flex-col">
- <SearchHeader
- onBack={() => handleStateChange('index')}
- onSearch={setSearch}
- value={search}
- />
- <DropdownMenuSeparator />
- <VirtualList
- data={filteredActions}
- height={Math.min(300, filteredActions.length * 40 + 8)}
- itemHeight={40}
- itemKey="value"
+ itemKey={options.itemKey ?? 'value'}
>
{(action) => (
<motion.div
@@ -417,7 +377,7 @@ export function PropertiesCombobox({
key="event"
transition={{ duration: 0.05 }}
>
- {renderEvent()}
+ {renderActionList(eventActions)}
</motion.div>
)}
{state === 'profile' && (
@@ -428,7 +388,7 @@ export function PropertiesCombobox({
key="profile"
transition={{ duration: 0.05 }}
>
- {renderProfile()}
+ {renderActionList(profileActions)}
</motion.div>
)}
{state === 'group' && (
@@ -439,7 +399,7 @@ export function PropertiesCombobox({
key="group"
transition={{ duration: 0.05 }}
>
- {renderGroup()}
+ {renderActionList(groupActions)}
</motion.div>
)}
{state === 'cohort' && (
@@ -450,7 +410,18 @@ export function PropertiesCombobox({
key="cohort"
transition={{ duration: 0.05 }}
>
- {renderCohort()}
+ {renderActionList(cohortActions)}
+ </motion.div>
+ )}
+ {state === 'session' && (
+ <motion.div
+ animate={{ opacity: 1, x: 0 }}
+ exit={{ opacity: 0, x: direction === 'forward' ? -20 : 20 }}
+ initial={{ opacity: 0, x: direction === 'forward' ? 20 : -20 }}
+ key="session"
+ transition={{ duration: 0.05 }}
+ >
+ {renderActionList(sessionActions)}
</motion.div>
)}
</AnimatePresence>
diff --git a/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx b/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx
index 5ebc1c23f..5b9a8da91 100644
--- a/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx
+++ b/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx
@@ -40,7 +40,7 @@ export function ReportBreakdowns() {
<ColorSquare>{index}</ColorSquare>
<PropertiesCombobox
isBreakdown
- showCohorts
+ categories={['event', 'profile', 'group', 'cohort']}
onSelect={(action) => {
dispatch(
changeBreakdown({
@@ -73,8 +73,8 @@ export function ReportBreakdowns() {
})}
<PropertiesCombobox
- showCohorts
isBreakdown
+ categories={['event', 'profile', 'group', 'cohort']}
onSelect={(action) => {
dispatch(
addBreakdown({
diff --git a/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx b/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx
index c30b5f5f4..87b0d2f3e 100644
--- a/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx
+++ b/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx
@@ -71,7 +71,7 @@ export function ReportSeriesItem({
{showAddFilter && (
<PropertiesCombobox
event={chartEvent}
- showCohorts
+ categories={['event', 'profile', 'group', 'cohort']}
onSelect={(action) => {
dispatch(
changeEvent({
diff --git a/apps/start/src/components/report/sidebar/filters/CohortFilterItem.tsx b/apps/start/src/components/report/sidebar/filters/CohortFilterItem.tsx
index ca9b33e0e..9b1fda0b6 100644
--- a/apps/start/src/components/report/sidebar/filters/CohortFilterItem.tsx
+++ b/apps/start/src/components/report/sidebar/filters/CohortFilterItem.tsx
@@ -6,10 +6,11 @@ import { DropdownMenuComposed } from '@/components/ui/dropdown-menu';
import { useAppParams } from '@/hooks/use-app-params';
import { useCohorts } from '@/hooks/use-cohorts';
import { useDispatch } from '@/redux';
-import type {
- IChartEvent,
- IChartEventFilter,
- IChartEventFilterOperator,
+import {
+ getCohortIds,
+ type IChartEvent,
+ type IChartEventFilter,
+ type IChartEventFilterOperator,
} from '@openpanel/validation';
import { SlidersHorizontal, Trash } from 'lucide-react';
import { changeEvent } from '../../reportSlice';
@@ -26,7 +27,7 @@ interface PureCohortFilterItemProps {
operator: IChartEventFilterOperator,
filter: IChartEventFilter,
) => void;
- onChangeCohort: (cohortId: string, filter: IChartEventFilter) => void;
+ onChangeCohort: (cohortIds: string[], filter: IChartEventFilter) => void;
className?: string;
}
@@ -58,13 +59,23 @@ export function CohortFilterItem({ filter, event }: CohortFilterItemProps) {
);
};
- const onChangeCohort = (cohortId: string, { id }: IChartEventFilter) => {
+ const onChangeCohort = (cohortIds: string[], { id }: IChartEventFilter) => {
+ // Write both `cohortIds` (source of truth) and `cohortId` (legacy, set
+ // to the first id) so saved reports loaded by older code keep working.
+ const firstId = cohortIds[0];
dispatch(
changeEvent({
...event,
type: 'event',
filters: event.filters.map((item) =>
- item.id === id ? { ...item, cohortId } : item,
+ item.id === id
+ ? {
+ ...item,
+ name: firstId ? `cohort:${firstId}` : item.name,
+ cohortId: firstId,
+ cohortIds,
+ }
+ : item,
),
}),
);
@@ -91,12 +102,25 @@ export function PureCohortFilterItem({
const { projectId } = useAppParams();
const cohorts = useCohorts({ projectId, includeCount: false });
+ const selectedIds = getCohortIds(filter);
const cohortsCombobox = cohorts.map((cohort) => ({
value: cohort.id,
label: cohort.name,
}));
+ /**
+ * The filter's `name` is a `cohort:<id>` sentinel — show one or more
+ * cohort names in the header instead of the raw uuid. Falls back to the
+ * sentinel while the cohorts query is still loading or when no cohorts
+ * are selected yet.
+ */
+ const cohortLabel =
+ selectedIds
+ .map((id) => cohorts.find((c) => c.id === id)?.name)
+ .filter(Boolean)
+ .join(', ') || filter.name;
+
const removeFilter = () => {
onRemove(filter);
};
@@ -105,11 +129,11 @@ export function PureCohortFilterItem({
onChangeOperator(operator, filter);
};
- const changeCohort = (cohortIds: Array<string | number>) => {
- const cohortId = cohortIds[0];
- if (cohortId && typeof cohortId === 'string') {
- onChangeCohort(cohortId, filter);
- }
+ const changeCohort = (next: Array<string | number>) => {
+ onChangeCohort(
+ next.filter((id): id is string => typeof id === 'string'),
+ filter,
+ );
};
return (
@@ -119,7 +143,7 @@ export function PureCohortFilterItem({
<SlidersHorizontal size={10} />
</ColorSquare>
<div className="flex flex-1">
- <RenderDots truncate>{filter.name}</RenderDots>
+ <RenderDots truncate>{cohortLabel}</RenderDots>
</div>
<Button variant="ghost" size="sm" onClick={removeFilter}>
<Trash size={16} />
@@ -140,10 +164,10 @@ export function PureCohortFilterItem({
</DropdownMenuComposed>
<ComboboxAdvanced
items={cohortsCombobox}
- value={filter.cohortId ? [filter.cohortId] : []}
+ value={selectedIds}
className="flex-1"
onChange={changeCohort}
- placeholder="Select cohort..."
+ placeholder="Select cohorts..."
/>
</div>
</div>
diff --git a/apps/start/src/components/report/sidebar/filters/FilterItem.tsx b/apps/start/src/components/report/sidebar/filters/FilterItem.tsx
index ef7e09265..03e769f48 100644
--- a/apps/start/src/components/report/sidebar/filters/FilterItem.tsx
+++ b/apps/start/src/components/report/sidebar/filters/FilterItem.tsx
@@ -2,9 +2,12 @@ import { ColorSquare } from '@/components/color-square';
import { FilterOperatorSelect } from '@/components/report/sidebar/filters/FilterOperatorSelect';
import { RenderDots } from '@/components/ui/RenderDots';
import { Button } from '@/components/ui/button';
+import { Combobox } from '@/components/ui/combobox';
import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
+import { ComboboxEvents } from '@/components/ui/combobox-events';
import { InputEnter } from '@/components/ui/input-enter';
import { useAppParams } from '@/hooks/use-app-params';
+import { useEventNames } from '@/hooks/use-event-names';
import { usePropertyValues } from '@/hooks/use-property-values';
import { useDispatch } from '@/redux';
import type {
@@ -107,6 +110,11 @@ export function FilterItem({ filter, event }: FilterProps) {
);
}
+const BOOLEAN_VALUE_ITEMS = [
+ { value: 'true', label: 'Yes' },
+ { value: 'false', label: 'No' },
+];
+
export function PureFilterItem({
filter,
eventName,
@@ -118,10 +126,23 @@ export function PureFilterItem({
}: PureFilterProps) {
const { projectId } = useAppParams();
+ const isBooleanSessionFilter = filter.name === 'session.is_bounce';
+ const isPerformedEventFilter = filter.name === 'session.performed_event';
+
const potentialValues = usePropertyValues({
event: eventName,
property: filter.name,
projectId,
+ // session.* filters live on the sessions row, not on event properties.
+ // The standard property-values endpoint can't enumerate them, so we
+ // bypass the lookup entirely.
+ enabled: !filter.name.startsWith('session.'),
+ });
+
+ const eventNames = useEventNames({
+ projectId,
+ anyEvents: false,
+ enabled: isPerformedEventFilter,
});
const valuesCombobox =
@@ -142,6 +163,55 @@ export function PureFilterItem({
onChangeOperator(operator, filter);
};
+ const renderValueControl = () => {
+ if (isBooleanSessionFilter) {
+ return (
+ <Combobox
+ className="flex-1"
+ items={BOOLEAN_VALUE_ITEMS}
+ value={
+ filter.value[0] === undefined ? null : String(filter.value[0])
+ }
+ onChange={(v) => changeFilterValue([v])}
+ placeholder="Yes / No"
+ />
+ );
+ }
+
+ if (isPerformedEventFilter) {
+ return (
+ <ComboboxEvents
+ className="flex-1"
+ items={eventNames}
+ value={filter.value[0] ? String(filter.value[0]) : null}
+ onChange={(v: string) => changeFilterValue([v])}
+ placeholder="Select event"
+ searchable
+ />
+ );
+ }
+
+ if (filter.operator === 'is' || filter.operator === 'isNot') {
+ return (
+ <ComboboxAdvanced
+ items={valuesCombobox}
+ value={filter.value}
+ className="flex-1"
+ onChange={changeFilterValue}
+ placeholder="Select..."
+ />
+ );
+ }
+
+ return (
+ <InputEnter
+ value={filter.value[0] ? String(filter.value[0]) : ''}
+ onChangeValue={(value) => changeFilterValue([value])}
+ immediate={immediateInput}
+ />
+ );
+ };
+
return (
<div className={className}>
<div className="mb-2 flex items-center gap-2">
@@ -160,21 +230,7 @@ export function PureFilterItem({
value={filter.operator}
onChange={changeFilterOperator}
/>
- {filter.operator === 'is' || filter.operator === 'isNot' ? (
- <ComboboxAdvanced
- items={valuesCombobox}
- value={filter.value}
- className="flex-1"
- onChange={changeFilterValue}
- placeholder="Select..."
- />
- ) : (
- <InputEnter
- value={filter.value[0] ? String(filter.value[0]) : ''}
- onChangeValue={(value) => changeFilterValue([value])}
- immediate={immediateInput}
- />
- )}
+ {renderValueControl()}
</div>
</div>
);
diff --git a/apps/start/src/components/sessions/table/index.tsx b/apps/start/src/components/sessions/table/index.tsx
index 95bd82724..26b7c1619 100644
--- a/apps/start/src/components/sessions/table/index.tsx
+++ b/apps/start/src/components/sessions/table/index.tsx
@@ -36,31 +36,26 @@ const usePersistentColumnVisibility = (columns: any[]) => {
};
import type { IServiceSession } from '@openpanel/db';
-import { useQueryClient } from '@tanstack/react-query';
import { useNavigate } from '@tanstack/react-router';
import type { Table } from '@tanstack/react-table';
import { getCoreRowModel, useReactTable } from '@tanstack/react-table';
import { useWindowVirtualizer } from '@tanstack/react-virtual';
import type { TRPCInfiniteData } from '@trpc/tanstack-react-query';
-import { Loader2Icon, SlidersHorizontalIcon } from 'lucide-react';
+import { Loader2Icon } from 'lucide-react';
import { last } from 'ramda';
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
import { useInViewport } from 'react-in-viewport';
+import { TableFilterPills } from '@/components/filters/TableFilterPills';
import { FullPageEmptyState } from '@/components/full-page-empty-state';
import { Skeleton } from '@/components/skeleton';
-import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
AnimatedSearchInput,
DataTableToolbarContainer,
} from '@/components/ui/data-table/data-table-toolbar';
import { DataTableViewOptions } from '@/components/ui/data-table/data-table-view-options';
-import type { FilterDefinition } from '@/components/ui/filter-dropdown';
-import { FilterDropdown } from '@/components/ui/filter-dropdown';
import { useAppParams } from '@/hooks/use-app-params';
import { useSearchQueryState } from '@/hooks/use-search-query-state';
-import { useSessionFilters } from '@/hooks/use-session-filters';
-import { useTRPC } from '@/integrations/trpc/react';
import { cn } from '@/utils/cn';
type Props = {
@@ -187,6 +182,10 @@ const VirtualizedSessionsTable = ({
estimateSize: () => ROW_HEIGHT, // Estimated row height
overscan: 10,
scrollMargin: parentRef.current?.offsetTop ?? 0,
+ // Key cache entries by row id so when filters refetch and the data
+ // array changes, the virtualizer doesn't reuse stale per-index
+ // measurements (which produces overlapping rows).
+ getItemKey: (index) => data[index]?.id ?? index,
});
const virtualRows = rowVirtualizer.getVirtualItems();
@@ -357,55 +356,8 @@ export const SessionsTable = ({ query }: Props) => {
);
};
-const SESSION_FILTER_KEY_TO_FIELD: Record<string, string> = {
- referrer: 'referrer_name',
- country: 'country',
- os: 'os',
- browser: 'browser',
- device: 'device',
-};
-
-const SESSION_FILTER_DEFINITIONS: FilterDefinition[] = [
- { key: 'referrer', label: 'Referrer', type: 'select' },
- { key: 'country', label: 'Country', type: 'select' },
- { key: 'os', label: 'OS', type: 'select' },
- { key: 'browser', label: 'Browser', type: 'select' },
- { key: 'device', label: 'Device', type: 'select' },
- { key: 'entryPage', label: 'Entry page', type: 'string' },
- { key: 'exitPage', label: 'Exit page', type: 'string' },
- { key: 'minPageViews', label: 'Min page views', type: 'number' },
- { key: 'maxPageViews', label: 'Max page views', type: 'number' },
- { key: 'minEvents', label: 'Min events', type: 'number' },
- { key: 'maxEvents', label: 'Max events', type: 'number' },
-];
-
function SessionTableToolbar({ table }: { table: Table<IServiceSession> }) {
- const { projectId } = useAppParams();
- const trpc = useTRPC();
- const queryClient = useQueryClient();
const { search, setSearch } = useSearchQueryState();
- const { values, setValue, activeCount } = useSessionFilters();
-
- const loadOptions = useCallback(
- (key: string) => {
- const field = SESSION_FILTER_KEY_TO_FIELD[key];
- if (!field) {
- return Promise.resolve([]);
- }
- return queryClient.fetchQuery(
- trpc.session.distinctValues.queryOptions({
- projectId,
- field: field as
- | 'referrer_name'
- | 'country'
- | 'os'
- | 'browser'
- | 'device',
- })
- );
- },
- [trpc, queryClient, projectId]
- );
return (
<DataTableToolbarContainer>
@@ -415,29 +367,11 @@ function SessionTableToolbar({ table }: { table: Table<IServiceSession> }) {
placeholder="Search sessions by path, referrer..."
value={search}
/>
- <FilterDropdown
- definitions={SESSION_FILTER_DEFINITIONS}
- loadOptions={loadOptions}
- onChange={setValue}
- values={values}
- >
- <Button
- className={cn(
- 'border-dashed',
- activeCount > 0 && 'border-primary border-solid'
- )}
- size="sm"
- variant="outline"
- >
- <SlidersHorizontalIcon className="mr-2 size-4" />
- Filters
- {activeCount > 0 && (
- <Badge className="ml-2 rounded-full px-1.5 py-0 text-xs">
- {activeCount}
- </Badge>
- )}
- </Button>
- </FilterDropdown>
+ <TableFilterPills
+ urlKey="f"
+ categories={['profile', 'group', 'cohort', 'session']}
+ title="Session filters"
+ />
</div>
<DataTableViewOptions table={table} />
</DataTableToolbarContainer>
diff --git a/apps/start/src/components/settings/edit-project-filters.tsx b/apps/start/src/components/settings/edit-project-filters.tsx
index 90fa0df11..bacd1b62b 100644
--- a/apps/start/src/components/settings/edit-project-filters.tsx
+++ b/apps/start/src/components/settings/edit-project-filters.tsx
@@ -135,7 +135,7 @@ function EventRuleItem({
</>
)}
<div className="p-4 border-t">
- <PropertiesCombobox onSelect={addFilter} mode="events">
+ <PropertiesCombobox onSelect={addFilter} categories={['event']}>
{(setOpen) => (
<Button
variant="outline"
diff --git a/apps/start/src/components/ui/filter-dropdown.tsx b/apps/start/src/components/ui/filter-dropdown.tsx
deleted file mode 100644
index 8edfbd21e..000000000
--- a/apps/start/src/components/ui/filter-dropdown.tsx
+++ /dev/null
@@ -1,328 +0,0 @@
-import { AnimatePresence, motion } from 'framer-motion';
-import {
- ArrowLeftIcon,
- CheckIcon,
- ChevronRightIcon,
- Loader2Icon,
- XIcon,
-} from 'lucide-react';
-import VirtualList from 'rc-virtual-list';
-import { useEffect, useState } from 'react';
-import { SerieIcon } from '@/components/report-chart/common/serie-icon';
-import { Button } from '@/components/ui/button';
-import { Input } from '@/components/ui/input';
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from '@/components/ui/popover';
-import { Separator } from '@/components/ui/separator';
-import { cn } from '@/utils/cn';
-
-export type FilterType = 'select' | 'string' | 'number';
-
-export interface FilterDefinition {
- key: string;
- label: string;
- type: FilterType;
- /** For 'select' type: show SerieIcon next to options (default true) */
- showIcon?: boolean;
-}
-
-interface FilterDropdownProps {
- definitions: FilterDefinition[];
- values: Record<string, string | number | null | undefined>;
- onChange: (key: string, value: string | number | null) => void;
- loadOptions: (key: string) => Promise<string[]>;
- children: React.ReactNode;
-}
-
-export function FilterDropdown({
- definitions,
- values,
- onChange,
- loadOptions,
- children,
-}: FilterDropdownProps) {
- const [open, setOpen] = useState(false);
- const [activeKey, setActiveKey] = useState<string | null>(null);
- const [direction, setDirection] = useState<'forward' | 'backward'>('forward');
- const [search, setSearch] = useState('');
- const [options, setOptions] = useState<string[]>([]);
- const [isLoading, setIsLoading] = useState(false);
- const [inputValue, setInputValue] = useState('');
-
- useEffect(() => {
- if (!open) {
- setActiveKey(null);
- setSearch('');
- setOptions([]);
- setInputValue('');
- }
- }, [open]);
-
- useEffect(() => {
- if (!activeKey) {
- return;
- }
- const def = definitions.find((d) => d.key === activeKey);
- if (!def || def.type !== 'select') {
- return;
- }
-
- setIsLoading(true);
- loadOptions(activeKey)
- .then((opts) => {
- setOptions(opts);
- setIsLoading(false);
- })
- .catch(() => setIsLoading(false));
- }, [activeKey]);
-
- const currentDef = activeKey
- ? definitions.find((d) => d.key === activeKey)
- : null;
-
- const goToFilter = (key: string) => {
- setDirection('forward');
- setSearch('');
- setOptions([]);
- const current = values[key];
- setInputValue(current != null ? String(current) : '');
- setActiveKey(key);
- };
-
- const goBack = () => {
- setDirection('backward');
- setActiveKey(null);
- setSearch('');
- };
-
- const applyValue = (key: string, value: string | number | null) => {
- onChange(key, value);
- goBack();
- };
-
- const renderIndex = () => (
- <div className="min-w-52">
- {definitions.map((def) => {
- const currentValue = values[def.key];
- const isActive = currentValue != null && currentValue !== '';
- return (
- <button
- className="flex w-full cursor-pointer items-center justify-between gap-2 rounded-md px-3 py-2 hover:bg-accent"
- key={def.key}
- onClick={() => goToFilter(def.key)}
- type="button"
- >
- <span className="font-medium text-sm">{def.label}</span>
- <div className="flex shrink-0 items-center gap-1">
- {isActive && (
- <>
- <span className="max-w-24 truncate text-muted-foreground text-xs">
- {String(currentValue)}
- </span>
- <button
- className="rounded-sm p-0.5 text-muted-foreground hover:text-foreground"
- onClick={(e) => {
- e.stopPropagation();
- onChange(def.key, null);
- }}
- type="button"
- >
- <XIcon className="size-3" />
- </button>
- </>
- )}
- <ChevronRightIcon className="size-4 text-muted-foreground" />
- </div>
- </button>
- );
- })}
- </div>
- );
-
- const renderSelectFilter = () => {
- const showIcon = currentDef?.showIcon !== false;
- const filteredOptions = options.filter((opt) =>
- opt.toLowerCase().includes(search.toLowerCase())
- );
- const currentValue = activeKey ? values[activeKey] : undefined;
-
- return (
- <div className="min-w-52">
- <div className="flex items-center gap-1 p-1">
- <Button
- className="size-7 shrink-0"
- onClick={goBack}
- size="icon"
- variant="ghost"
- >
- <ArrowLeftIcon className="size-4" />
- </Button>
- <Input
- autoFocus
- className="h-7 text-sm"
- onChange={(e) => setSearch(e.target.value)}
- placeholder="Search..."
- value={search}
- />
- </div>
- <Separator />
- {isLoading ? (
- <div className="flex items-center justify-center p-6 text-muted-foreground">
- <Loader2Icon className="size-4 animate-spin" />
- </div>
- ) : filteredOptions.length === 0 ? (
- <div className="p-4 text-center text-muted-foreground text-sm">
- No options found
- </div>
- ) : (
- <VirtualList
- data={filteredOptions}
- height={Math.min(filteredOptions.length * 36, 250)}
- itemHeight={36}
- itemKey={(item) => item}
- >
- {(option) => (
- <button
- className="flex cursor-pointer items-center gap-2 rounded-md px-3 py-2 hover:bg-accent"
- onClick={() => applyValue(activeKey!, option)}
- type="button"
- >
- {showIcon && <SerieIcon name={option} />}
- <span className="truncate text-sm">{option || 'Direct'}</span>
- <CheckIcon
- className={cn(
- 'ml-auto size-4 shrink-0',
- currentValue === option ? 'opacity-100' : 'opacity-0'
- )}
- />
- </button>
- )}
- </VirtualList>
- )}
- </div>
- );
- };
-
- const renderStringFilter = () => (
- <div className="min-w-52">
- <div className="flex items-center gap-1 p-1">
- <Button
- className="size-7 shrink-0"
- onClick={goBack}
- size="icon"
- variant="ghost"
- >
- <ArrowLeftIcon className="size-4" />
- </Button>
- <span className="px-1 font-medium text-sm">{currentDef?.label}</span>
- </div>
- <Separator />
- <div className="flex flex-col gap-2 p-2">
- <Input
- autoFocus
- className="h-8 text-sm"
- onChange={(e) => setInputValue(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- applyValue(activeKey!, inputValue || null);
- }
- }}
- placeholder={`Filter by ${currentDef?.label.toLowerCase()}...`}
- value={inputValue}
- />
- <Button
- className="w-full"
- onClick={() => applyValue(activeKey!, inputValue || null)}
- size="sm"
- >
- Apply
- </Button>
- </div>
- </div>
- );
-
- const renderNumberFilter = () => (
- <div className="min-w-52">
- <div className="flex items-center gap-1 p-1">
- <Button
- className="size-7 shrink-0"
- onClick={goBack}
- size="icon"
- variant="ghost"
- >
- <ArrowLeftIcon className="size-4" />
- </Button>
- <span className="px-1 font-medium text-sm">{currentDef?.label}</span>
- </div>
- <Separator />
- <div className="flex flex-col gap-2 p-2">
- <Input
- autoFocus
- className="h-8 text-sm"
- inputMode="numeric"
- min={0}
- onChange={(e) => setInputValue(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- applyValue(
- activeKey!,
- inputValue === '' ? null : Number(inputValue)
- );
- }
- }}
- placeholder="Enter value..."
- type="number"
- value={inputValue}
- />
- <Button
- className="w-full"
- onClick={() =>
- applyValue(
- activeKey!,
- inputValue === '' ? null : Number(inputValue)
- )
- }
- size="sm"
- >
- Apply
- </Button>
- </div>
- </div>
- );
-
- const renderContent = () => {
- if (!(activeKey && currentDef)) {
- return renderIndex();
- }
- switch (currentDef.type) {
- case 'select':
- return renderSelectFilter();
- case 'string':
- return renderStringFilter();
- case 'number':
- return renderNumberFilter();
- }
- };
-
- return (
- <Popover onOpenChange={setOpen} open={open}>
- <PopoverTrigger asChild>{children}</PopoverTrigger>
- <PopoverContent align="start" className="w-auto p-1">
- <AnimatePresence initial={false} mode="wait">
- <motion.div
- animate={{ opacity: 1, x: 0 }}
- exit={{ opacity: 0, x: direction === 'forward' ? -20 : 20 }}
- initial={{ opacity: 0, x: direction === 'forward' ? 20 : -20 }}
- key={activeKey ?? 'index'}
- transition={{ duration: 0.1 }}
- >
- {renderContent()}
- </motion.div>
- </AnimatePresence>
- </PopoverContent>
- </Popover>
- );
-}
diff --git a/apps/start/src/hooks/use-event-names.ts b/apps/start/src/hooks/use-event-names.ts
index 36ef66075..d0527c866 100644
--- a/apps/start/src/hooks/use-event-names.ts
+++ b/apps/start/src/hooks/use-event-names.ts
@@ -4,11 +4,13 @@ import { useQuery } from '@tanstack/react-query';
export function useEventNames(params: {
projectId: string;
anyEvents?: boolean;
+ enabled?: boolean;
}) {
const trpc = useTRPC();
+ const { enabled = true, ...input } = params;
const query = useQuery(
- trpc.chart.events.queryOptions(params, {
- enabled: !!params.projectId,
+ trpc.chart.events.queryOptions(input, {
+ enabled: enabled !== false && !!params.projectId,
staleTime: 1000 * 60 * 10,
}),
);
diff --git a/apps/start/src/hooks/use-event-query-filters.ts b/apps/start/src/hooks/use-event-query-filters.ts
index bb7afd27a..c824c2ec9 100644
--- a/apps/start/src/hooks/use-event-query-filters.ts
+++ b/apps/start/src/hooks/use-event-query-filters.ts
@@ -16,26 +16,58 @@ export const eventQueryFiltersParser = createParser({
if (query === '') return [];
const filters = query.split(';');
- return (
- filters.map((filter) => {
- const [key, operator, value] = filter.split(',');
- return {
- id: key!,
- name: key!,
- operator: (operator ?? 'is') as IChartEventFilterOperator,
- value: value
- ? value.split('|').map((v) => decodeURIComponent(v))
- : [],
- };
- }) ?? []
- );
+ return filters.map((filter) => {
+ const [key, operator, value, cohortIdSegment] = filter.split(',');
+ const name = key ?? '';
+ // 4th segment is pipe-separated cohort ids. Old single-id URLs split
+ // to a one-element array; new URLs may carry many.
+ const cohortIds = cohortIdSegment
+ ? cohortIdSegment
+ .split('|')
+ .map((v) => decodeURIComponent(v))
+ .filter(Boolean)
+ : name.startsWith('cohort:')
+ ? [name.slice('cohort:'.length)]
+ : [];
+ return {
+ id: name,
+ name,
+ operator: (operator ?? 'is') as IChartEventFilterOperator,
+ value: value
+ ? value.split('|').map((v) => decodeURIComponent(v))
+ : [],
+ // Keep both fields populated for legacy consumers that read
+ // `cohortId` directly. `cohortIds` is the source of truth.
+ ...(cohortIds.length > 0
+ ? { cohortId: cohortIds[0], cohortIds }
+ : {}),
+ };
+ });
},
serialize: (value) => {
return value
- .map(
- (filter) =>
- `${filter.id},${filter.operator},${filter.value.map((v) => encodeURIComponent(v.trim())).join('|')}`,
- )
+ .map((filter) => {
+ const encodedValue = filter.value
+ .map((v) => encodeURIComponent(String(v).trim()))
+ .join('|');
+ // Prefer the multi-value `cohortIds`. Fall back to the legacy
+ // singular `cohortId` so already-rendered filters without the new
+ // field still round-trip.
+ const cohortIds =
+ filter.cohortIds && filter.cohortIds.length > 0
+ ? filter.cohortIds
+ : filter.cohortId
+ ? [filter.cohortId]
+ : [];
+ const cohortSegment =
+ cohortIds.length > 0
+ ? `,${cohortIds.map((c) => encodeURIComponent(c)).join('|')}`
+ : '';
+ // Always serialize by `name` — `id` may be a random shortId used only
+ // for React reconciliation and would otherwise clobber the human
+ // label on the next page load.
+ return `${filter.name},${filter.operator},${encodedValue}${cohortSegment}`;
+ })
.join(';');
},
});
diff --git a/apps/start/src/hooks/use-property-values.ts b/apps/start/src/hooks/use-property-values.ts
index 22f0d542c..4b9b3589f 100644
--- a/apps/start/src/hooks/use-property-values.ts
+++ b/apps/start/src/hooks/use-property-values.ts
@@ -3,9 +3,10 @@ import { useQuery } from '@tanstack/react-query';
export function usePropertyValues(params: any) {
const trpc = useTRPC();
+ const { enabled = true, ...input } = params;
const query = useQuery(
- trpc.chart.values.queryOptions(params, {
- enabled: !!params.projectId,
+ trpc.chart.values.queryOptions(input, {
+ enabled: enabled !== false && !!input.projectId,
}),
);
return query.data?.values ?? [];
diff --git a/apps/start/src/hooks/use-session-filters.ts b/apps/start/src/hooks/use-session-filters.ts
deleted file mode 100644
index 8f105281b..000000000
--- a/apps/start/src/hooks/use-session-filters.ts
+++ /dev/null
@@ -1,229 +0,0 @@
-import type { IChartEventFilter } from '@openpanel/validation';
-import { parseAsInteger, parseAsString, useQueryState } from 'nuqs';
-import { useCallback, useMemo } from 'react';
-
-const DEBOUNCE_MS = 500;
-const debounceOpts = {
- clearOnDefault: true,
- limitUrlUpdates: { method: 'debounce' as const, timeMs: DEBOUNCE_MS },
-};
-
-export function useSessionFilters() {
- const [referrer, setReferrer] = useQueryState(
- 'referrer',
- parseAsString.withDefault('').withOptions(debounceOpts),
- );
- const [country, setCountry] = useQueryState(
- 'country',
- parseAsString.withDefault('').withOptions(debounceOpts),
- );
- const [os, setOs] = useQueryState(
- 'os',
- parseAsString.withDefault('').withOptions(debounceOpts),
- );
- const [browser, setBrowser] = useQueryState(
- 'browser',
- parseAsString.withDefault('').withOptions(debounceOpts),
- );
- const [device, setDevice] = useQueryState(
- 'device',
- parseAsString.withDefault('').withOptions(debounceOpts),
- );
- const [entryPage, setEntryPage] = useQueryState(
- 'entryPage',
- parseAsString.withDefault('').withOptions(debounceOpts),
- );
- const [exitPage, setExitPage] = useQueryState(
- 'exitPage',
- parseAsString.withDefault('').withOptions(debounceOpts),
- );
- const [minPageViews, setMinPageViews] = useQueryState(
- 'minPageViews',
- parseAsInteger,
- );
- const [maxPageViews, setMaxPageViews] = useQueryState(
- 'maxPageViews',
- parseAsInteger,
- );
- const [minEvents, setMinEvents] = useQueryState('minEvents', parseAsInteger);
- const [maxEvents, setMaxEvents] = useQueryState('maxEvents', parseAsInteger);
-
- const filters = useMemo<IChartEventFilter[]>(() => {
- const result: IChartEventFilter[] = [];
- if (referrer) {
- result.push({ name: 'referrer_name', operator: 'is', value: [referrer] });
- }
- if (country) {
- result.push({ name: 'country', operator: 'is', value: [country] });
- }
- if (os) {
- result.push({ name: 'os', operator: 'is', value: [os] });
- }
- if (browser) {
- result.push({ name: 'browser', operator: 'is', value: [browser] });
- }
- if (device) {
- result.push({ name: 'device', operator: 'is', value: [device] });
- }
- if (entryPage) {
- result.push({
- name: 'entry_path',
- operator: 'contains',
- value: [entryPage],
- });
- }
- if (exitPage) {
- result.push({
- name: 'exit_path',
- operator: 'contains',
- value: [exitPage],
- });
- }
- return result;
- }, [referrer, country, os, browser, device, entryPage, exitPage]);
-
- const values = useMemo(
- () => ({
- referrer,
- country,
- os,
- browser,
- device,
- entryPage,
- exitPage,
- minPageViews,
- maxPageViews,
- minEvents,
- maxEvents,
- }),
- [
- referrer,
- country,
- os,
- browser,
- device,
- entryPage,
- exitPage,
- minPageViews,
- maxPageViews,
- minEvents,
- maxEvents,
- ],
- );
-
- const setValue = useCallback(
- (key: string, value: string | number | null) => {
- switch (key) {
- case 'referrer':
- setReferrer(String(value ?? ''));
- break;
- case 'country':
- setCountry(String(value ?? ''));
- break;
- case 'os':
- setOs(String(value ?? ''));
- break;
- case 'browser':
- setBrowser(String(value ?? ''));
- break;
- case 'device':
- setDevice(String(value ?? ''));
- break;
- case 'entryPage':
- setEntryPage(String(value ?? ''));
- break;
- case 'exitPage':
- setExitPage(String(value ?? ''));
- break;
- case 'minPageViews':
- setMinPageViews(value != null ? Number(value) : null);
- break;
- case 'maxPageViews':
- setMaxPageViews(value != null ? Number(value) : null);
- break;
- case 'minEvents':
- setMinEvents(value != null ? Number(value) : null);
- break;
- case 'maxEvents':
- setMaxEvents(value != null ? Number(value) : null);
- break;
- }
- },
- [
- setReferrer,
- setCountry,
- setOs,
- setBrowser,
- setDevice,
- setEntryPage,
- setExitPage,
- setMinPageViews,
- setMaxPageViews,
- setMinEvents,
- setMaxEvents,
- ],
- );
-
- const activeCount =
- filters.length +
- (minPageViews != null ? 1 : 0) +
- (maxPageViews != null ? 1 : 0) +
- (minEvents != null ? 1 : 0) +
- (maxEvents != null ? 1 : 0);
-
- const clearAll = useCallback(() => {
- setReferrer('');
- setCountry('');
- setOs('');
- setBrowser('');
- setDevice('');
- setEntryPage('');
- setExitPage('');
- setMinPageViews(null);
- setMaxPageViews(null);
- setMinEvents(null);
- setMaxEvents(null);
- }, [
- setReferrer,
- setCountry,
- setOs,
- setBrowser,
- setDevice,
- setEntryPage,
- setExitPage,
- setMinPageViews,
- setMaxPageViews,
- setMinEvents,
- setMaxEvents,
- ]);
-
- return {
- referrer,
- setReferrer,
- country,
- setCountry,
- os,
- setOs,
- browser,
- setBrowser,
- device,
- setDevice,
- entryPage,
- setEntryPage,
- exitPage,
- setExitPage,
- minPageViews,
- setMinPageViews,
- maxPageViews,
- setMaxPageViews,
- minEvents,
- setMinEvents,
- maxEvents,
- setMaxEvents,
- filters,
- values,
- setValue,
- activeCount,
- clearAll,
- };
-}
diff --git a/apps/start/src/hooks/use-table-filters.ts b/apps/start/src/hooks/use-table-filters.ts
new file mode 100644
index 000000000..08dd67dcc
--- /dev/null
+++ b/apps/start/src/hooks/use-table-filters.ts
@@ -0,0 +1,58 @@
+import type { Options as NuqsOptions } from 'nuqs';
+import { useQueryState } from 'nuqs';
+import { useCallback, useMemo } from 'react';
+
+import type { IChartEventFilter } from '@openpanel/validation';
+
+import { eventQueryFiltersParser } from './use-event-query-filters';
+
+const nuqsOptions = { history: 'push' } as const;
+
+/**
+ * Generic table-filter state hook. Stores an `IChartEventFilter[]` in the URL
+ * using the same encoding as `useEventQueryFilters`, but parameterised by key
+ * so multiple tables can persist independent filter sets in one URL.
+ */
+export function useTableFilters(
+ key = 'f',
+ options: NuqsOptions = {},
+): [
+ IChartEventFilter[],
+ (next: IChartEventFilter[]) => void,
+] {
+ const [rawFilters, setFilters] = useQueryState(
+ key,
+ eventQueryFiltersParser.withDefault([]).withOptions({
+ ...nuqsOptions,
+ ...options,
+ }),
+ );
+
+ const filters = useMemo<IChartEventFilter[]>(
+ () => rawFilters as unknown as IChartEventFilter[],
+ [rawFilters],
+ );
+
+ const setAll = useCallback(
+ (next: IChartEventFilter[]) => {
+ setFilters(
+ next.map((filter) => ({
+ id: filter.id ?? filter.name,
+ name: filter.name,
+ operator: filter.operator,
+ value: filter.value.map((v) => (v == null ? '' : String(v))),
+ // Preserve both cohort fields so legacy consumers reading
+ // `cohortId` directly stay happy while the parser round-trips
+ // `cohortIds` as the source of truth.
+ ...(filter.cohortIds && filter.cohortIds.length > 0
+ ? { cohortIds: filter.cohortIds }
+ : {}),
+ ...(filter.cohortId ? { cohortId: filter.cohortId } : {}),
+ })),
+ );
+ },
+ [setFilters],
+ );
+
+ return [filters, setAll];
+}
diff --git a/apps/start/src/modals/index.tsx b/apps/start/src/modals/index.tsx
index 865e3ecbc..ee8ec038b 100644
--- a/apps/start/src/modals/index.tsx
+++ b/apps/start/src/modals/index.tsx
@@ -27,6 +27,7 @@ import EventDetails from './event-details';
import Instructions from './Instructions';
import OverviewChartDetails from './overview-chart-details';
import OverviewFilters from './overview-filters';
+import TableFilters from './table-filters';
import PageDetails from './page-details';
import RegenerateRecoveryCodes from './regenerate-recovery-codes';
import RequestPasswordReset from './request-reset-password';
@@ -75,6 +76,7 @@ const modals = {
AddIntegration,
AddNotificationRule,
OverviewFilters,
+ TableFilters,
CreateInvite,
SelectBillingPlan,
BillingSuccess,
diff --git a/apps/start/src/modals/overview-filters.tsx b/apps/start/src/modals/overview-filters.tsx
index 99fcb6a43..48f5b19a2 100644
--- a/apps/start/src/modals/overview-filters.tsx
+++ b/apps/start/src/modals/overview-filters.tsx
@@ -112,7 +112,13 @@ export default function OverviewFilters({
})}
</div>
<PropertiesCombobox
- mode={mode}
+ categories={
+ mode === 'events'
+ ? ['event']
+ : mode === 'profile'
+ ? ['profile']
+ : ['event', 'profile', 'group', 'cohort']
+ }
exclude={
enableEventsFilter
? []
diff --git a/apps/start/src/modals/table-filters.tsx b/apps/start/src/modals/table-filters.tsx
new file mode 100644
index 000000000..ceaee196b
--- /dev/null
+++ b/apps/start/src/modals/table-filters.tsx
@@ -0,0 +1,156 @@
+import { FilterIcon, type LucideIcon, SlidersHorizontal } from 'lucide-react';
+import type { IChartEventFilter } from '@openpanel/validation';
+import {
+ PropertiesCombobox,
+ type PropertiesComboboxCategory,
+} from '@/components/report/sidebar/PropertiesCombobox';
+import { PureCohortFilterItem } from '@/components/report/sidebar/filters/CohortFilterItem';
+import { PureFilterItem } from '@/components/report/sidebar/filters/FilterItem';
+import { Button } from '@/components/ui/button';
+import { SheetContent } from '@/components/ui/sheet';
+import { useTableFilters } from '@/hooks/use-table-filters';
+import { cn } from '@/utils/cn';
+import { ModalHeader } from './Modal/Container';
+
+export interface TableFiltersProps {
+ /** URL query-string key the filters are stored under (matches useTableFilters). */
+ urlKey: string;
+ /** Categories the user can pick from when adding a filter. */
+ categories: PropertiesComboboxCategory[];
+ /** Sheet title — defaults to "Filters". */
+ title?: string;
+}
+
+const Heading = ({
+ title,
+ icon: Icon,
+}: {
+ title: string;
+ icon: LucideIcon;
+}) => (
+ <div className="row items-center gap-2">
+ <Icon className="size-4" />
+ <h2 className="text-sm font-medium">{title}</h2>
+ </div>
+);
+
+/**
+ * Generic sheet modal hosting an `IChartEventFilter[]` editor against a named
+ * URL key. Layout mirrors `overview-filters.tsx` so every filter sheet in the
+ * app feels identical.
+ */
+export default function TableFilters({
+ urlKey,
+ categories,
+ title = 'Filters',
+}: TableFiltersProps) {
+ const [filters, setFilters] = useTableFilters(urlKey);
+
+ const setFilter = (updated: IChartEventFilter) => {
+ setFilters(filters.map((f) => (f.id === updated.id ? updated : f)));
+ };
+
+ const removeFilter = (target: IChartEventFilter) => {
+ setFilters(filters.filter((f) => f.id !== target.id));
+ };
+
+ const addFilter = (action: { value: string; cohortId?: string }) => {
+ // Use the property name as the id so the URL serializer (which encodes
+ // by name) round-trips cleanly on reload.
+ const next: IChartEventFilter = action.cohortId
+ ? {
+ id: action.value,
+ name: action.value,
+ operator: 'inCohort',
+ value: [],
+ cohortId: action.cohortId,
+ }
+ : {
+ id: action.value,
+ name: action.value,
+ operator: 'is',
+ value: [],
+ };
+ setFilters([...filters, next]);
+ };
+
+ return (
+ <SheetContent className="[&>button.absolute]:hidden">
+ <ModalHeader title={title} />
+ <Heading icon={SlidersHorizontal} title="Filters" />
+ <div className="flex flex-col gap-2">
+ <div className={cn('bg-card rounded-lg border')}>
+ {filters.length === 0 && (
+ <div className="p-4 text-center text-sm text-muted-foreground">
+ No filters selected
+ </div>
+ )}
+ {filters.map((filter) => {
+ const isCohort =
+ filter.operator === 'inCohort' ||
+ filter.operator === 'notInCohort';
+ if (isCohort) {
+ return (
+ <PureCohortFilterItem
+ className="border-t p-4 first:border-0"
+ key={filter.id ?? filter.name}
+ filter={filter}
+ onRemove={removeFilter}
+ onChangeOperator={(operator, original) =>
+ setFilter({ ...original, operator })
+ }
+ onChangeCohort={(cohortIds, original) => {
+ // Keep `id` stable so the setFilter helper (which matches
+ // by id) still finds this row. URL serializes by `name`,
+ // which we update — on reload the parser will resync id
+ // from the name. Write both cohort fields so legacy
+ // consumers reading `cohortId` keep working.
+ const firstId = cohortIds[0];
+ setFilter({
+ ...original,
+ name: firstId ? `cohort:${firstId}` : original.name,
+ cohortId: firstId,
+ cohortIds,
+ });
+ }}
+ />
+ );
+ }
+ return (
+ <PureFilterItem
+ className="border-t p-4 first:border-0"
+ eventName="screen_view"
+ key={filter.id ?? filter.name}
+ filter={filter}
+ onRemove={removeFilter}
+ onChangeValue={(value, original) =>
+ setFilter({ ...original, value })
+ }
+ onChangeOperator={(operator, original) =>
+ setFilter({
+ ...original,
+ operator,
+ value: original.value.filter(Boolean).slice(0, 1),
+ })
+ }
+ />
+ );
+ })}
+ </div>
+ <PropertiesCombobox categories={categories} onSelect={addFilter}>
+ {(setOpen) => (
+ <Button
+ onClick={() => setOpen((p) => !p)}
+ variant="outline"
+ size="lg"
+ className="w-full"
+ icon={FilterIcon}
+ >
+ Add filter
+ </Button>
+ )}
+ </PropertiesCombobox>
+ </div>
+ </SheetContent>
+ );
+}
diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.profiles._tabs.anonymous.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.profiles._tabs.anonymous.tsx
index b2af79aad..967de0525 100644
--- a/apps/start/src/routes/_app.$organizationId.$projectId.profiles._tabs.anonymous.tsx
+++ b/apps/start/src/routes/_app.$organizationId.$projectId.profiles._tabs.anonymous.tsx
@@ -1,6 +1,7 @@
import { ProfilesTable } from '@/components/profiles/table';
import { useDataTablePagination } from '@/components/ui/data-table/data-table-hooks';
import { useSearchQueryState } from '@/hooks/use-search-query-state';
+import { useTableFilters } from '@/hooks/use-table-filters';
import { useTRPC } from '@/integrations/trpc/react';
import { PAGE_TITLES, createEntityTitle } from '@/utils/title';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
@@ -26,6 +27,7 @@ function Component() {
const trpc = useTRPC();
const { page } = useDataTablePagination(50);
const { debouncedSearch } = useSearchQueryState();
+ const [filters] = useTableFilters('f');
const query = useQuery(
trpc.profile.list.queryOptions(
{
@@ -34,6 +36,7 @@ function Component() {
take: 50,
search: debouncedSearch,
isExternal: false,
+ filters,
},
{
placeholderData: keepPreviousData,
diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.profiles._tabs.identified.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.profiles._tabs.identified.tsx
index d6265a6b4..77cfa1588 100644
--- a/apps/start/src/routes/_app.$organizationId.$projectId.profiles._tabs.identified.tsx
+++ b/apps/start/src/routes/_app.$organizationId.$projectId.profiles._tabs.identified.tsx
@@ -1,6 +1,7 @@
import { ProfilesTable } from '@/components/profiles/table';
import { useDataTablePagination } from '@/components/ui/data-table/data-table-hooks';
import { useSearchQueryState } from '@/hooks/use-search-query-state';
+import { useTableFilters } from '@/hooks/use-table-filters';
import { useTRPC } from '@/integrations/trpc/react';
import { PAGE_TITLES, createEntityTitle } from '@/utils/title';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
@@ -27,6 +28,7 @@ function Component() {
const { page } = useDataTablePagination(50);
const { debouncedSearch } = useSearchQueryState();
+ const [filters] = useTableFilters('f');
const query = useQuery(
trpc.profile.list.queryOptions(
@@ -36,6 +38,7 @@ function Component() {
take: 50,
search: debouncedSearch,
isExternal: true,
+ filters,
},
{
placeholderData: keepPreviousData,
diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.sessions.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.sessions.tsx
index a2f282035..ee19ca595 100644
--- a/apps/start/src/routes/_app.$organizationId.$projectId.sessions.tsx
+++ b/apps/start/src/routes/_app.$organizationId.$projectId.sessions.tsx
@@ -4,7 +4,7 @@ import { PageContainer } from '@/components/page-container';
import { PageHeader } from '@/components/page-header';
import { SessionsTable } from '@/components/sessions/table';
import { useSearchQueryState } from '@/hooks/use-search-query-state';
-import { useSessionFilters } from '@/hooks/use-session-filters';
+import { useTableFilters } from '@/hooks/use-table-filters';
import { useTRPC } from '@/integrations/trpc/react';
import { createProjectTitle, PAGE_TITLES } from '@/utils/title';
@@ -27,8 +27,7 @@ function Component() {
const { projectId } = Route.useParams();
const trpc = useTRPC();
const { debouncedSearch } = useSearchQueryState();
- const { filters, minPageViews, maxPageViews, minEvents, maxEvents } =
- useSessionFilters();
+ const [filters, setFilters] = useTableFilters('f');
const query = useInfiniteQuery(
trpc.session.list.infiniteQueryOptions(
@@ -37,10 +36,6 @@ function Component() {
take: 50,
search: debouncedSearch,
filters,
- minPageViews,
- maxPageViews,
- minEvents,
- maxEvents,
},
{
getNextPageParam: (lastPage) => lastPage.meta.next,
diff --git a/packages/db/index.ts b/packages/db/index.ts
index 781f959fe..cb8e52831 100644
--- a/packages/db/index.ts
+++ b/packages/db/index.ts
@@ -16,6 +16,7 @@ export * from './src/services/dashboard.service';
export * from './src/services/date.service';
export * from './src/services/delete.service';
export * from './src/services/event.service';
+export * from './src/services/filter-where.service';
export * from './src/services/funnel.service';
export * from './src/services/group.service';
export * from './src/services/gsc.service';
diff --git a/packages/db/src/services/chart.service.ts b/packages/db/src/services/chart.service.ts
index 98a2df9ff..7bd851cdd 100644
--- a/packages/db/src/services/chart.service.ts
+++ b/packages/db/src/services/chart.service.ts
@@ -1,11 +1,12 @@
/** biome-ignore-all lint/style/useDefaultSwitchClause: switch cases are exhaustive by design */
import { stripLeadingAndTrailingSlashes } from '@openpanel/common';
-import type {
- CohortDefinition,
- IChartBreakdown,
- IChartEventFilter,
- IGetChartDataInput,
- IReportInput,
+import {
+ type CohortDefinition,
+ getCohortIds,
+ type IChartBreakdown,
+ type IChartEventFilter,
+ type IGetChartDataInput,
+ type IReportInput,
} from '@openpanel/validation';
import sqlstring from 'sqlstring';
import { formatClickhouseDate, TABLE_NAMES } from '../clickhouse/client';
@@ -112,8 +113,12 @@ export function collectCohortIds(
): string[] {
const ids = new Set<string>();
for (const filter of filters) {
- if (filter.cohortId) {
- ids.add(filter.cohortId);
+ // Collect from both `cohortId` (legacy) and `cohortIds` (multi-value).
+ // Only single-cohort filters use the CTE join path — multi-cohort
+ // filters compile to a direct subselect in getEventFiltersWhereClause.
+ const filterCohortIds = getCohortIds(filter);
+ if (filterCohortIds.length === 1) {
+ ids.add(filterCohortIds[0]!);
}
}
for (const breakdown of breakdowns) {
@@ -1011,15 +1016,34 @@ export function getEventFiltersWhereClause(
const where: Record<string, string> = {};
filters.forEach((filter, index) => {
const id = `f${index}`;
- const { name, value, operator, cohortId } = filter;
+ const { name, value, operator } = filter;
- if (operator === 'inCohort' && cohortId && projectId) {
- where[id] = `notEmpty(${getCohortAlias(cohortId)}.profile_id)`;
- return;
- }
+ if (
+ (operator === 'inCohort' || operator === 'notInCohort') &&
+ projectId
+ ) {
+ const cohortIds = getCohortIds(filter);
+ if (cohortIds.length === 0) return;
+
+ if (cohortIds.length === 1) {
+ // Preserve the original CTE-join path for the single-cohort case
+ // (collectCohortIds wires up the CTE for us). Behaviour for saved
+ // reports with `cohortId: string` is unchanged.
+ const single = cohortIds[0]!;
+ where[id] =
+ operator === 'notInCohort'
+ ? `empty(${getCohortAlias(single)}.profile_id)`
+ : `notEmpty(${getCohortAlias(single)}.profile_id)`;
+ return;
+ }
- if (operator === 'notInCohort' && cohortId && projectId) {
- where[id] = `empty(${getCohortAlias(cohortId)}.profile_id)`;
+ // Multi-cohort: compile to a direct subselect against cohort_members.
+ // No CTE join needed — saves an unnecessary plan for the ad-hoc case.
+ const escapedIds = cohortIds
+ .map((c) => sqlstring.escape(c))
+ .join(', ');
+ const op = operator === 'notInCohort' ? 'NOT IN' : 'IN';
+ where[id] = `e.profile_id ${op} (SELECT profile_id FROM ${TABLE_NAMES.cohort_members} FINAL WHERE cohort_id IN (${escapedIds}) AND project_id = ${sqlstring.escape(projectId)})`;
return;
}
diff --git a/packages/db/src/services/cohort.service.ts b/packages/db/src/services/cohort.service.ts
index 91025db08..5666ce22b 100644
--- a/packages/db/src/services/cohort.service.ts
+++ b/packages/db/src/services/cohort.service.ts
@@ -17,7 +17,12 @@ import {
getReplicatedTableName,
} from '../clickhouse/client';
import { db } from '../prisma-client';
-import { getProfiles, type IServiceProfile } from './profile.service';
+import { buildFilterWhere } from './filter-where.service';
+import {
+ getProfiles,
+ profileSearchSql,
+ type IServiceProfile,
+} from './profile.service';
export const COHORT_MATERIALIZE_LIMIT = 10000;
@@ -618,17 +623,30 @@ export async function listCohortMemberProfiles({
cursor,
take,
search,
+ filters,
}: {
projectId: string;
cohortId: string;
cursor?: number;
take: number;
search?: string;
+ filters?: IChartEventFilter[];
}): Promise<{ data: IServiceProfile[]; count: number }> {
const offset = Math.max(0, (cursor ?? 0) * take);
- const trimmed = search?.trim();
- const searchCondition = trimmed
- ? `AND (email ILIKE ${sqlstring.escape(`%${trimmed}%`)} OR first_name ILIKE ${sqlstring.escape(`%${trimmed}%`)} OR last_name ILIKE ${sqlstring.escape(`%${trimmed}%`)})`
+ const searchClause = profileSearchSql(search);
+ const searchCondition = searchClause ? `AND ${searchClause}` : '';
+
+ const extraConditions = filters?.length
+ ? Object.values(
+ buildFilterWhere(filters, projectId, {
+ selfTable: 'profiles',
+ profileIdExpr: 'id',
+ groupsExpr: 'groups',
+ }),
+ )
+ : [];
+ const extraConditionSql = extraConditions.length
+ ? `AND ${extraConditions.join(' AND ')}`
: '';
const rows = await chQuery<{ id: string; total_count: number }>(`
@@ -641,6 +659,7 @@ export async function listCohortMemberProfiles({
AND project_id = ${sqlstring.escape(projectId)}
)
${searchCondition}
+ ${extraConditionSql}
ORDER BY created_at DESC
LIMIT ${take} OFFSET ${offset}
`);
diff --git a/packages/db/src/services/event.service.ts b/packages/db/src/services/event.service.ts
index bc320dc23..94e433bff 100644
--- a/packages/db/src/services/event.service.ts
+++ b/packages/db/src/services/event.service.ts
@@ -17,6 +17,7 @@ import type { EventMeta, Prisma } from '../prisma-client';
import { db } from '../prisma-client';
import { createSqlBuilder, type SqlBuilderObject } from '../sql-builder';
import { getEventFiltersWhereClause } from './chart.service';
+import { buildFilterWhere } from './filter-where.service';
import type { IServiceProfile, IServiceUpsertProfile } from './profile.service';
import {
getProfileById,
@@ -1284,6 +1285,7 @@ export interface QueryEventsInput {
profileId?: string;
profileIds?: string[];
properties?: Record<string, string>;
+ filters?: IChartEventFilter[];
limit?: number;
}
@@ -1377,5 +1379,16 @@ export async function queryEventsCore(
]);
}
+ if (input.filters?.length) {
+ const filterClauses = buildFilterWhere(input.filters, input.projectId, {
+ selfTable: 'events',
+ profileIdExpr: 'profile_id',
+ groupsExpr: 'groups',
+ });
+ for (const clause of Object.values(filterClauses)) {
+ builder.rawWhere(clause);
+ }
+ }
+
return builder.limit(input.limit ?? 20).execute();
}
diff --git a/packages/db/src/services/filter-where.service.ts b/packages/db/src/services/filter-where.service.ts
new file mode 100644
index 000000000..6c51ea220
--- /dev/null
+++ b/packages/db/src/services/filter-where.service.ts
@@ -0,0 +1,336 @@
+/** biome-ignore-all lint/style/useDefaultSwitchClause: switch cases are exhaustive by design */
+import { getCohortIds, type IChartEventFilter } from '@openpanel/validation';
+import sqlstring from 'sqlstring';
+import { formatClickhouseDate, TABLE_NAMES } from '../clickhouse/client';
+
+export type FilterTableContext = {
+ /** Outer query's primary table. */
+ selfTable: 'sessions' | 'profiles' | 'events';
+ /**
+ * Expression on the outer row that yields the owning profile id. For the
+ * profiles table this is `id`; for events/sessions it's `profile_id`. Used
+ * by cohort + cross-table profile.* filters.
+ */
+ profileIdExpr: string;
+ /**
+ * Expression on the outer row that yields the array of group ids. All three
+ * canonical tables expose a `groups Array(String)` column today.
+ */
+ groupsExpr?: string;
+ /**
+ * Optional date scope passed to subselects that reference the events table
+ * (currently only `session.performed_event`). Without it ClickHouse has to
+ * scan the entire event history for the project.
+ */
+ startDate?: Date;
+ endDate?: Date;
+};
+
+/** Sentinel sessions columns that the UI may filter on directly. */
+const SESSION_NUMERIC_COLUMNS = new Set([
+ 'screen_view_count',
+ 'event_count',
+ 'duration',
+ 'revenue',
+]);
+
+function escape(value: string | number | boolean | null): string {
+ return sqlstring.escape(typeof value === 'string' ? value.trim() : value);
+}
+
+function trimVal(value: string | number | boolean | null): string {
+ return typeof value === 'string' ? value.trim() : String(value);
+}
+
+/**
+ * Build a WHERE-clause fragment for a single non-array column. Mirrors the
+ * operator set used by `getEventFiltersWhereClause` so behaviour stays
+ * consistent across surfaces.
+ */
+function compileScalarClause(
+ column: string,
+ operator: IChartEventFilter['operator'],
+ value: IChartEventFilter['value'],
+ options: { numeric?: boolean } = {},
+): string | null {
+ if (
+ value.length === 0 &&
+ operator !== 'isNull' &&
+ operator !== 'isNotNull'
+ ) {
+ return null;
+ }
+
+ const numeric = options.numeric === true;
+
+ switch (operator) {
+ case 'is': {
+ if (numeric) {
+ return `(${value
+ .map((v) => `toFloat64(${column}) = toFloat64(${escape(v)})`)
+ .join(' OR ')})`;
+ }
+ if (value.length === 1) {
+ return `${column} = ${escape(value[0]!)}`;
+ }
+ return `${column} IN (${value.map(escape).join(', ')})`;
+ }
+ case 'isNot': {
+ if (numeric) {
+ return `(${value
+ .map((v) => `toFloat64(${column}) != toFloat64(${escape(v)})`)
+ .join(' OR ')})`;
+ }
+ if (value.length === 1) {
+ return `${column} != ${escape(value[0]!)}`;
+ }
+ return `${column} NOT IN (${value.map(escape).join(', ')})`;
+ }
+ case 'contains': {
+ return `(${value
+ .map((v) => `${column} ILIKE ${sqlstring.escape(`%${trimVal(v)}%`)}`)
+ .join(' OR ')})`;
+ }
+ case 'doesNotContain': {
+ return `(${value
+ .map((v) => `${column} NOT ILIKE ${sqlstring.escape(`%${trimVal(v)}%`)}`)
+ .join(' AND ')})`;
+ }
+ case 'startsWith': {
+ return `(${value
+ .map((v) => `${column} ILIKE ${sqlstring.escape(`${trimVal(v)}%`)}`)
+ .join(' OR ')})`;
+ }
+ case 'endsWith': {
+ return `(${value
+ .map((v) => `${column} ILIKE ${sqlstring.escape(`%${trimVal(v)}`)}`)
+ .join(' OR ')})`;
+ }
+ case 'regex': {
+ return `(${value
+ .map((v) => `match(${column}, ${escape(v)})`)
+ .join(' OR ')})`;
+ }
+ case 'isNull':
+ return `(${column} = '' OR ${column} IS NULL)`;
+ case 'isNotNull':
+ return `(${column} != '' AND ${column} IS NOT NULL)`;
+ case 'gt': {
+ return `(${value
+ .map(
+ (v) =>
+ `${numeric ? `toFloat64(${column})` : column} > ${numeric ? `toFloat64(${escape(v)})` : escape(v)}`,
+ )
+ .join(' OR ')})`;
+ }
+ case 'lt': {
+ return `(${value
+ .map(
+ (v) =>
+ `${numeric ? `toFloat64(${column})` : column} < ${numeric ? `toFloat64(${escape(v)})` : escape(v)}`,
+ )
+ .join(' OR ')})`;
+ }
+ case 'gte': {
+ return `(${value
+ .map(
+ (v) =>
+ `${numeric ? `toFloat64(${column})` : column} >= ${numeric ? `toFloat64(${escape(v)})` : escape(v)}`,
+ )
+ .join(' OR ')})`;
+ }
+ case 'lte': {
+ return `(${value
+ .map(
+ (v) =>
+ `${numeric ? `toFloat64(${column})` : column} <= ${numeric ? `toFloat64(${escape(v)})` : escape(v)}`,
+ )
+ .join(' OR ')})`;
+ }
+ }
+
+ return null;
+}
+
+/**
+ * Translate `profile.<field>` into the SQL accessor used when querying the
+ * profiles table directly. Bare fields (email, first_name, …) map to columns;
+ * `profile.properties.<key>` maps to the JSON `properties[key]` lookup.
+ */
+function profileColumnSql(name: string): string {
+ const withoutPrefix = name.replace(/^profile\./, '');
+ if (withoutPrefix.startsWith('properties.')) {
+ const key = withoutPrefix.replace(/^properties\./, '');
+ return `properties[${sqlstring.escape(key)}]`;
+ }
+ return withoutPrefix;
+}
+
+/**
+ * Translate `group.<field>` into the SQL accessor used when querying the
+ * groups table directly (no join alias).
+ */
+function groupColumnSql(name: string): string {
+ const withoutPrefix = name.replace(/^group\./, '');
+ if (withoutPrefix === 'name' || withoutPrefix === 'type' || withoutPrefix === 'id') {
+ return withoutPrefix;
+ }
+ if (withoutPrefix.startsWith('properties.')) {
+ const key = withoutPrefix.replace(/^properties\./, '');
+ return `properties[${sqlstring.escape(key)}]`;
+ }
+ return 'id';
+}
+
+/** Translate `session.<field>` to the underlying sessions column. */
+function sessionColumnSql(name: string): string | null {
+ const withoutPrefix = name.replace(/^session\./, '');
+ if (withoutPrefix === 'is_bounce') return 'is_bounce';
+ if (SESSION_NUMERIC_COLUMNS.has(withoutPrefix)) return withoutPrefix;
+ // performed_event is handled as a subselect, not a column
+ return null;
+}
+
+function buildCohortClause(
+ filter: IChartEventFilter,
+ projectId: string,
+ ctx: FilterTableContext,
+): string | null {
+ // `getCohortIds` normalizes the legacy single-value `cohortId` field and
+ // the newer `cohortIds` array into one list. Falls back to extracting the
+ // id from the `cohort:<id>` filter name when neither is set (older URL
+ // formats encoded the id only in the name).
+ let cohortIds = getCohortIds(filter);
+ if (cohortIds.length === 0 && filter.name.startsWith('cohort:')) {
+ cohortIds = [filter.name.slice('cohort:'.length)];
+ }
+ if (cohortIds.length === 0) return null;
+ const negate = filter.operator === 'notInCohort';
+ const op = negate ? 'NOT IN' : 'IN';
+ const escapedIds = cohortIds.map((id) => sqlstring.escape(id)).join(', ');
+ return `${ctx.profileIdExpr} ${op} (SELECT profile_id FROM ${TABLE_NAMES.cohort_members} FINAL WHERE cohort_id IN (${escapedIds}) AND project_id = ${sqlstring.escape(projectId)})`;
+}
+
+function buildGroupClause(
+ filter: IChartEventFilter,
+ projectId: string,
+ ctx: FilterTableContext,
+): string | null {
+ if (!ctx.groupsExpr) return null;
+ const column = groupColumnSql(filter.name);
+ const inner = compileScalarClause(column, filter.operator, filter.value);
+ if (!inner) return null;
+ const projectClause = `project_id = ${sqlstring.escape(projectId)}`;
+ return `arrayExists(g -> g IN (SELECT id FROM ${TABLE_NAMES.groups} FINAL WHERE ${projectClause} AND ${inner}), ${ctx.groupsExpr})`;
+}
+
+function buildProfileClause(
+ filter: IChartEventFilter,
+ projectId: string,
+ ctx: FilterTableContext,
+): string | null {
+ const column = profileColumnSql(filter.name);
+ const numeric = column === 'created_at' || column === 'last_seen_at';
+ const inner = compileScalarClause(column, filter.operator, filter.value, {
+ numeric,
+ });
+ if (!inner) return null;
+ if (ctx.selfTable === 'profiles') {
+ return inner;
+ }
+ return `${ctx.profileIdExpr} IN (SELECT id FROM ${TABLE_NAMES.profiles} FINAL WHERE project_id = ${sqlstring.escape(projectId)} AND ${inner})`;
+}
+
+function buildSessionClause(
+ filter: IChartEventFilter,
+ projectId: string,
+ ctx: FilterTableContext,
+): string | null {
+ if (ctx.selfTable !== 'sessions') return null;
+ const fieldName = filter.name.replace(/^session\./, '');
+
+ if (fieldName === 'performed_event') {
+ if (filter.value.length === 0) return null;
+ const inClause =
+ filter.value.length === 1
+ ? `= ${escape(filter.value[0]!)}`
+ : `IN (${filter.value.map(escape).join(', ')})`;
+ const op = filter.operator === 'isNot' ? 'NOT IN' : 'IN';
+ const dateScope: string[] = [];
+ if (ctx.startDate && ctx.endDate) {
+ dateScope.push(
+ `toDate(created_at) BETWEEN toDate('${formatClickhouseDate(ctx.startDate)}') AND toDate('${formatClickhouseDate(ctx.endDate)}')`,
+ );
+ }
+ const scopeSql = dateScope.length ? `AND ${dateScope.join(' AND ')} ` : '';
+ return `id ${op} (SELECT DISTINCT session_id FROM ${TABLE_NAMES.events} WHERE project_id = ${sqlstring.escape(projectId)} ${scopeSql}AND name ${inClause})`;
+ }
+
+ if (fieldName === 'is_bounce') {
+ if (filter.value.length === 0) return null;
+ const wants = filter.value.some((v) =>
+ typeof v === 'boolean' ? v : String(v).toLowerCase() === 'true',
+ );
+ const truthy = filter.operator === 'isNot' ? !wants : wants;
+ return `is_bounce = ${truthy ? 1 : 0}`;
+ }
+
+ const column = sessionColumnSql(filter.name);
+ if (!column) return null;
+ return compileScalarClause(column, filter.operator, filter.value, {
+ numeric: SESSION_NUMERIC_COLUMNS.has(column),
+ });
+}
+
+/**
+ * Translate `IChartEventFilter[]` into a WHERE-clause record suitable for
+ * merging into `createSqlBuilder().sb.where`. Handles cohort / group / profile
+ * / session prefixes. Event-property (`properties.*`) filters are ignored on
+ * non-events tables — they require a subquery on the events table that is
+ * better expressed as a cohort.
+ */
+export function buildFilterWhere(
+ filters: IChartEventFilter[],
+ projectId: string,
+ ctx: FilterTableContext,
+): Record<string, string> {
+ const where: Record<string, string> = {};
+ filters.forEach((filter, index) => {
+ const id = `f${index}`;
+
+ if (filter.operator === 'inCohort' || filter.operator === 'notInCohort') {
+ const clause = buildCohortClause(filter, projectId, ctx);
+ if (clause) where[id] = clause;
+ return;
+ }
+
+ if (filter.name.startsWith('cohort:')) {
+ const clause = buildCohortClause(filter, projectId, ctx);
+ if (clause) where[id] = clause;
+ return;
+ }
+
+ if (filter.name.startsWith('group.')) {
+ const clause = buildGroupClause(filter, projectId, ctx);
+ if (clause) where[id] = clause;
+ return;
+ }
+
+ if (filter.name.startsWith('profile.')) {
+ const clause = buildProfileClause(filter, projectId, ctx);
+ if (clause) where[id] = clause;
+ return;
+ }
+
+ if (filter.name.startsWith('session.')) {
+ const clause = buildSessionClause(filter, projectId, ctx);
+ if (clause) where[id] = clause;
+ return;
+ }
+
+ // properties.* filters only make sense on the events table; ignore on
+ // sessions/profiles queries. Callers that need them should query the
+ // events table directly (e.g. via getEventList) or use a cohort.
+ });
+ return where;
+}
diff --git a/packages/db/src/services/profile.service.ts b/packages/db/src/services/profile.service.ts
index 1aa660165..e758e8aa8 100644
--- a/packages/db/src/services/profile.service.ts
+++ b/packages/db/src/services/profile.service.ts
@@ -15,6 +15,7 @@ import {
import { clix } from '../clickhouse/query-builder';
import { createSqlBuilder } from '../sql-builder';
import type { IClickhouseEvent } from './event.service';
+import { buildFilterWhere } from './filter-where.service';
import type { IClickhouseSession } from './session.service';
export interface IProfileMetrics {
@@ -141,6 +142,22 @@ interface GetProfileListOptions {
isExternal?: boolean;
}
+/**
+ * Build a profile search predicate that handles multi-token queries like
+ * "John Smith" — splits on whitespace, requires every token to match SOME
+ * profile field (email/first/last/full name), case-insensitively. Returns
+ * `null` when the search string is empty.
+ */
+export function profileSearchSql(search: string | null | undefined): string | null {
+ const tokens = (search ?? '').trim().split(/\s+/).filter(Boolean).slice(0, 5);
+ if (tokens.length === 0) return null;
+ const perToken = tokens.map((token) => {
+ const like = sqlstring.escape(`%${token}%`);
+ return `(email ILIKE ${like} OR first_name ILIKE ${like} OR last_name ILIKE ${like} OR concat(first_name, ' ', last_name) ILIKE ${like})`;
+ });
+ return `(${perToken.join(' AND ')})`;
+}
+
export async function getProfiles(ids: string[], projectId: string) {
const filteredIds = uniq(ids.filter((id) => id !== ''));
@@ -166,6 +183,7 @@ export async function getProfileList({
take,
cursor,
projectId,
+ filters,
search,
isExternal,
}: GetProfileListOptions) {
@@ -176,18 +194,30 @@ export async function getProfileList({
sb.limit = take;
sb.offset = Math.max(0, (cursor ?? 0) * take);
sb.orderBy.created_at = 'created_at DESC';
- if (search) {
- sb.where.search = `(email ILIKE '%${search}%' OR first_name ILIKE '%${search}%' OR last_name ILIKE '%${search}%')`;
+ const searchClause = profileSearchSql(search);
+ if (searchClause) {
+ sb.where.search = searchClause;
}
if (isExternal !== undefined) {
sb.where.external = `is_external = ${isExternal ? 'true' : 'false'}`;
}
+ if (filters?.length) {
+ Object.assign(
+ sb.where,
+ buildFilterWhere(filters, projectId, {
+ selfTable: 'profiles',
+ profileIdExpr: 'id',
+ groupsExpr: 'groups',
+ }),
+ );
+ }
const data = await chQuery<IClickhouseProfile>(getSql());
return data.map(transformProfile);
}
export async function getProfileListCount({
projectId,
+ filters,
isExternal,
search,
}: Omit<GetProfileListOptions, 'cursor' | 'take'>) {
@@ -196,12 +226,23 @@ export async function getProfileListCount({
sb.select.count = 'count(id) as count';
sb.where.project_id = `project_id = ${sqlstring.escape(projectId)}`;
sb.groupBy.project_id = 'project_id';
- if (search) {
- sb.where.search = `(email ILIKE '%${search}%' OR first_name ILIKE '%${search}%' OR last_name ILIKE '%${search}%')`;
+ const searchClause = profileSearchSql(search);
+ if (searchClause) {
+ sb.where.search = searchClause;
}
if (isExternal !== undefined) {
sb.where.external = `is_external = ${isExternal ? 'true' : 'false'}`;
}
+ if (filters?.length) {
+ Object.assign(
+ sb.where,
+ buildFilterWhere(filters, projectId, {
+ selfTable: 'profiles',
+ profileIdExpr: 'id',
+ groupsExpr: 'groups',
+ }),
+ );
+ }
const data = await chQuery<{ count: number }>(getSql());
return data[0]?.count ?? 0;
}
@@ -339,6 +380,7 @@ export interface FindProfilesInput {
inactiveDays?: number;
minSessions?: number;
performedEvent?: string;
+ filters?: IChartEventFilter[];
sortBy?: 'created_at';
sortOrder?: 'asc' | 'desc';
limit?: number;
@@ -351,13 +393,11 @@ export function findProfilesCore(
const conditions: string[] = [`project_id = ${pid}`];
if (input.email) {
- conditions.push(`email LIKE ${sqlstring.escape(`%${input.email}%`)}`);
+ conditions.push(`email ILIKE ${sqlstring.escape(`%${input.email}%`)}`);
}
if (input.name) {
- const escaped = sqlstring.escape(`%${input.name}%`);
- conditions.push(
- `(first_name LIKE ${escaped} OR last_name LIKE ${escaped})`
- );
+ const nameClause = profileSearchSql(input.name);
+ if (nameClause) conditions.push(nameClause);
}
if (input.country) {
conditions.push(
@@ -406,6 +446,15 @@ export function findProfilesCore(
)`);
}
+ if (input.filters?.length) {
+ const filterClauses = buildFilterWhere(input.filters, input.projectId, {
+ selfTable: 'profiles',
+ profileIdExpr: 'id',
+ groupsExpr: 'groups',
+ });
+ conditions.push(...Object.values(filterClauses));
+ }
+
const orderDir = input.sortOrder === 'asc' ? 'ASC' : 'DESC';
const limit = Math.min(input.limit ?? 20, 100);
diff --git a/packages/db/src/services/session.service.ts b/packages/db/src/services/session.service.ts
index 77614bb32..0102999e3 100644
--- a/packages/db/src/services/session.service.ts
+++ b/packages/db/src/services/session.service.ts
@@ -11,7 +11,7 @@ import {
} from '../clickhouse/client';
import { clix } from '../clickhouse/query-builder';
import { createSqlBuilder } from '../sql-builder';
-import { getEventFiltersWhereClause } from './chart.service';
+import { buildFilterWhere } from './filter-where.service';
import { getProfilesCached, type IServiceProfile } from './profile.service';
export interface IClickhouseSession {
@@ -107,10 +107,6 @@ export interface GetSessionListOptions {
endDate?: Date;
search?: string;
cursor?: Date;
- minPageViews?: number | null;
- maxPageViews?: number | null;
- minEvents?: number | null;
- maxEvents?: number | null;
dateIntervalInDays?: number;
}
@@ -167,10 +163,6 @@ export async function getSessionList(options: GetSessionListOptions) {
startDate,
endDate,
search,
- minPageViews,
- maxPageViews,
- minEvents,
- maxEvents,
dateIntervalInDays = 0.5,
} = options;
@@ -210,19 +202,16 @@ export async function getSessionList(options: GetSessionListOptions) {
sb.where.search = `(entry_path ILIKE ${s} OR exit_path ILIKE ${s} OR referrer ILIKE ${s} OR referrer_name ILIKE ${s})`;
}
if (filters?.length) {
- Object.assign(sb.where, getEventFiltersWhereClause(filters));
- }
- if (minPageViews != null) {
- sb.where.minPageViews = `screen_view_count >= ${minPageViews}`;
- }
- if (maxPageViews != null) {
- sb.where.maxPageViews = `screen_view_count <= ${maxPageViews}`;
- }
- if (minEvents != null) {
- sb.where.minEvents = `event_count >= ${minEvents}`;
- }
- if (maxEvents != null) {
- sb.where.maxEvents = `event_count <= ${maxEvents}`;
+ Object.assign(
+ sb.where,
+ buildFilterWhere(filters, projectId, {
+ selfTable: 'sessions',
+ profileIdExpr: 'profile_id',
+ groupsExpr: 'groups',
+ startDate,
+ endDate,
+ }),
+ );
}
const columns = [
@@ -333,15 +322,21 @@ export async function getSessionsCount({
}
if (search) {
- sb.where.search = `(entry_path ILIKE '%${search}%' OR exit_path ILIKE '%${search}%' OR referrer ILIKE '%${search}%' OR referrer_name ILIKE '%${search}%')`;
+ const s = sqlstring.escape(`%${search}%`);
+ sb.where.search = `(entry_path ILIKE ${s} OR exit_path ILIKE ${s} OR referrer ILIKE ${s} OR referrer_name ILIKE ${s})`;
}
if (filters && filters.length > 0) {
- const sessionFilters = getEventFiltersWhereClause(filters);
- sb.where = {
- ...sb.where,
- ...sessionFilters,
- };
+ Object.assign(
+ sb.where,
+ buildFilterWhere(filters, projectId, {
+ selfTable: 'sessions',
+ profileIdExpr: 'profile_id',
+ groupsExpr: 'groups',
+ startDate,
+ endDate,
+ }),
+ );
}
sb.from = TABLE_NAMES.sessions;
@@ -478,6 +473,7 @@ export interface QuerySessionsInput {
referrerName?: string;
referrerType?: string;
profileId?: string;
+ filters?: IChartEventFilter[];
limit?: number;
}
@@ -533,5 +529,18 @@ export async function querySessionsCore(
clix.datetime(end),
]);
+ if (input.filters?.length) {
+ const filterClauses = buildFilterWhere(input.filters, input.projectId, {
+ selfTable: 'sessions',
+ profileIdExpr: 'profile_id',
+ groupsExpr: 'groups',
+ startDate: new Date(start),
+ endDate: new Date(end),
+ });
+ for (const clause of Object.values(filterClauses)) {
+ builder.rawWhere(clause);
+ }
+ }
+
return builder.limit(input.limit ?? 20).execute();
}
diff --git a/packages/mcp/src/tools/analytics/profiles.test.ts b/packages/mcp/src/tools/analytics/profiles.test.ts
index a59336e9e..f4a06200a 100644
--- a/packages/mcp/src/tools/analytics/profiles.test.ts
+++ b/packages/mcp/src/tools/analytics/profiles.test.ts
@@ -61,19 +61,29 @@ describe('findProfilesCore — SQL conditions', () => {
expect(capturedSql()).toContain("project_id = 'proj-1'");
});
- it('adds email LIKE condition when email is provided', async () => {
+ it('adds email ILIKE condition when email is provided', async () => {
await findProfilesCore({ projectId: 'proj-1', email: 'carl@' });
- expect(capturedSql()).toContain("email LIKE '%carl@%'");
+ expect(capturedSql()).toContain("email ILIKE '%carl@%'");
});
- it('searches both first_name and last_name for name filter', async () => {
+ it('searches across first/last/full name for name filter', async () => {
await findProfilesCore({ projectId: 'proj-1', name: 'Carl' });
const sql = capturedSql();
- expect(sql).toContain('first_name LIKE');
- expect(sql).toContain('last_name LIKE');
+ expect(sql).toContain('first_name ILIKE');
+ expect(sql).toContain('last_name ILIKE');
+ expect(sql).toContain("concat(first_name, ' ', last_name) ILIKE");
expect(sql).toContain('%Carl%');
});
+ it('matches multi-token name queries by ANDing each token', async () => {
+ await findProfilesCore({ projectId: 'proj-1', name: 'John Smith' });
+ const sql = capturedSql();
+ expect(sql).toContain('%John%');
+ expect(sql).toContain('%Smith%');
+ // Each token wrapped in its own OR-of-fields group, joined by AND.
+ expect(sql).toContain(') AND (');
+ });
+
it('adds country property condition', async () => {
await findProfilesCore({ projectId: 'proj-1', country: 'SE' });
expect(capturedSql()).toContain("properties['country'] = 'SE'");
diff --git a/packages/trpc/src/routers/cohort.ts b/packages/trpc/src/routers/cohort.ts
index 98210d1a0..48eecfa2f 100644
--- a/packages/trpc/src/routers/cohort.ts
+++ b/packages/trpc/src/routers/cohort.ts
@@ -14,6 +14,7 @@ import {
} from '@openpanel/db';
import {
type CohortDefinition,
+ zChartEventFilter,
zCohortDefinition,
zCohortInput,
zCohortUpdate,
@@ -164,6 +165,7 @@ export const cohortRouter = createTRPCRouter({
cursor: z.number().optional(),
take: z.number().default(50),
search: z.string().optional(),
+ filters: z.array(zChartEventFilter).default([]),
})
)
.query(async ({ input }) => {
diff --git a/packages/trpc/src/routers/profile.ts b/packages/trpc/src/routers/profile.ts
index 64159f493..3c1441b91 100644
--- a/packages/trpc/src/routers/profile.ts
+++ b/packages/trpc/src/routers/profile.ts
@@ -12,6 +12,7 @@ import {
getProfileMetrics,
getProfiles,
} from '@openpanel/db';
+import { zChartEventFilter } from '@openpanel/validation';
import { createTRPCRouter, protectedProcedure } from '../trpc';
@@ -81,6 +82,7 @@ export const profileRouter = createTRPCRouter({
take: z.number().default(50),
search: z.string().optional(),
isExternal: z.boolean().optional(),
+ filters: z.array(zChartEventFilter).default([]),
}),
)
.query(async ({ input }) => {
diff --git a/packages/trpc/src/routers/session.ts b/packages/trpc/src/routers/session.ts
index 9c60a9794..0f94450c7 100644
--- a/packages/trpc/src/routers/session.ts
+++ b/packages/trpc/src/routers/session.ts
@@ -44,10 +44,6 @@ export const sessionRouter = createTRPCRouter({
endDate: z.date().optional(),
search: z.string().optional(),
take: z.number().default(50),
- minPageViews: z.number().nullish(),
- maxPageViews: z.number().nullish(),
- minEvents: z.number().nullish(),
- maxEvents: z.number().nullish(),
})
)
.query(({ input }) => {
diff --git a/packages/validation/src/index.ts b/packages/validation/src/index.ts
index 18fc4b9f8..88745584a 100644
--- a/packages/validation/src/index.ts
+++ b/packages/validation/src/index.ts
@@ -31,9 +31,40 @@ export const zChartEventFilter = z.object({
cohortId: z
.string()
.optional()
- .describe('Cohort ID when using inCohort/notInCohort operators'),
+ .describe(
+ 'DEPRECATED: legacy single-cohort id, kept for saved reports. ' +
+ 'New code reads cohortIds via getCohortIds(filter).',
+ ),
+ cohortIds: z
+ .array(z.string())
+ .optional()
+ .describe(
+ 'Cohort IDs for inCohort/notInCohort. Multiple ids OR-match ' +
+ '(matches profiles in any of the listed cohorts).',
+ ),
});
+/**
+ * Normalize the two cohort id fields on a filter into a single array.
+ *
+ * Both `cohortIds` (new, multi-value) and `cohortId` (legacy, single-value)
+ * coexist on `zChartEventFilter` for backward compatibility with saved
+ * reports. Always read cohort membership through this helper instead of
+ * accessing the raw fields, so legacy data keeps working.
+ */
+export function getCohortIds(filter: {
+ cohortIds?: string[];
+ cohortId?: string;
+}): string[] {
+ if (filter.cohortIds && filter.cohortIds.length > 0) {
+ return filter.cohortIds;
+ }
+ if (filter.cohortId) {
+ return [filter.cohortId];
+ }
+ return [];
+}
+
export const zChartEventSegment = z
.enum(objectToZodEnums(chartSegments))
.default('event')