Skip to content

armgit / umami

Public Imported from GitHub
0

Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.

Support session property filters on segments. Closes #4507

Francis Caoe69496933a52
diff --git a/src/app/(main)/TopNav.tsx b/src/app/(main)/TopNav.tsx
index 2b41e144a..0d3e79bed 100644
--- a/src/app/(main)/TopNav.tsx
+++ b/src/app/(main)/TopNav.tsx
@@ -71,6 +71,8 @@ export function TopNav() {
teamId={teamId}
onChange={handleLinkChange}
buttonProps={{
+ className:
+ 'border-transparent bg-transparent shadow-none hover:border-transparent hover:bg-interactive active:bg-interactive-hover',
style: { minHeight: 40, minWidth: 200, maxWidth: 200 },
}}
/>
@@ -81,6 +83,8 @@ export function TopNav() {
teamId={teamId}
onChange={handlePixelChange}
buttonProps={{
+ className:
+ 'border-transparent bg-transparent shadow-none hover:border-transparent hover:bg-interactive active:bg-interactive-hover',
style: { minHeight: 40, minWidth: 200, maxWidth: 200 },
}}
/>
@@ -91,6 +95,8 @@ export function TopNav() {
teamId={teamId}
onChange={handleBoardChange}
buttonProps={{
+ className:
+ 'border-transparent bg-transparent shadow-none hover:border-transparent hover:bg-interactive active:bg-interactive-hover',
style: { minHeight: 40, minWidth: 200, maxWidth: 200 },
}}
/>
diff --git a/src/app/(main)/links/LinkEditForm.tsx b/src/app/(main)/links/LinkEditForm.tsx
index 8b8f476be..05235ee21 100644
--- a/src/app/(main)/links/LinkEditForm.tsx
+++ b/src/app/(main)/links/LinkEditForm.tsx
@@ -125,7 +125,7 @@ export function LinkEditForm({
</Grid>
)}
- <Column>
+ <Column gap="1">
<Label>{t(labels.link)}</Label>
<Row alignItems="center" gap>
<TextField
diff --git a/src/app/(main)/pixels/PixelEditForm.tsx b/src/app/(main)/pixels/PixelEditForm.tsx
index aa3061d55..56b2a8e7f 100644
--- a/src/app/(main)/pixels/PixelEditForm.tsx
+++ b/src/app/(main)/pixels/PixelEditForm.tsx
@@ -93,7 +93,7 @@ export function PixelEditForm({
<input type="hidden" />
</FormField>
- <Column>
+ <Column gap="1">
<Label>{t(labels.link)}</Label>
<Row alignItems="center" gap>
<TextField
diff --git a/src/app/(main)/settings/preferences/PreferenceSettings.tsx b/src/app/(main)/settings/preferences/PreferenceSettings.tsx
index 55695946b..138f35574 100644
--- a/src/app/(main)/settings/preferences/PreferenceSettings.tsx
+++ b/src/app/(main)/settings/preferences/PreferenceSettings.tsx
@@ -16,23 +16,23 @@ export function PreferenceSettings() {
return (
<Column gap="6">
- <Column>
+ <Column gap="1">
<Label>{t(labels.defaultDateRange)}</Label>
<DateRangeSetting />
</Column>
- <Column>
+ <Column gap="1">
<Label>{t(labels.timezone)}</Label>
<TimezoneSetting />
</Column>
- <Column>
+ <Column gap="1">
<Label>{t(labels.language)}</Label>
<LanguageSetting />
</Column>
- <Column>
+ <Column gap="1">
<Label>{t(labels.theme)}</Label>
<ThemeSetting />
</Column>
- <Column>
+ <Column gap="1">
<Label>{t(labels.version)}</Label>
<VersionSetting />
</Column>
diff --git a/src/app/(main)/websites/[websiteId]/(reports)/goals/GoalEditForm.tsx b/src/app/(main)/websites/[websiteId]/(reports)/goals/GoalEditForm.tsx
index 808057411..9f3ccd92c 100644
--- a/src/app/(main)/websites/[websiteId]/(reports)/goals/GoalEditForm.tsx
+++ b/src/app/(main)/websites/[websiteId]/(reports)/goals/GoalEditForm.tsx
@@ -64,7 +64,7 @@ export function GoalEditForm({
<FormField name="name" label={t(labels.name)} rules={{ required: t(labels.required) }}>
<TextField autoFocus />
</FormField>
- <Column>
+ <Column gap="1">
<Label>{t(labels.action)}</Label>
{isMobile ? (
<Column gap style={{ minWidth: 0 }}>
diff --git a/src/app/(main)/websites/[websiteId]/cohorts/CohortEditForm.tsx b/src/app/(main)/websites/[websiteId]/cohorts/CohortEditForm.tsx
index 8ad13549d..9b77f0067 100644
--- a/src/app/(main)/websites/[websiteId]/cohorts/CohortEditForm.tsx
+++ b/src/app/(main)/websites/[websiteId]/cohorts/CohortEditForm.tsx
@@ -8,6 +8,7 @@ import {
Grid,
Label,
Loading,
+ Text,
TextField,
} from '@umami/react-zen';
import { useEffect, useState } from 'react';
@@ -71,6 +72,7 @@ export function CohortEditForm({
}
const defaultValues = {
+ name: '',
parameters: { filters, dateRange: '30day', action: { type: 'path', value: '' } },
};
@@ -84,12 +86,12 @@ export function CohortEditForm({
const type = watch('parameters.action.type');
return (
- <>
+ <Column gap="4">
<FormField name="name" label={t(labels.name)} rules={{ required: t(labels.required) }}>
<TextField autoFocus />
</FormField>
- <Column>
+ <Column gap="1">
<Label>{t(labels.action)}</Label>
<Grid columns={{ base: '1fr', md: '1fr 1fr' }} gap>
<Column>
@@ -110,15 +112,15 @@ export function CohortEditForm({
</Grid>
</Column>
- <Column width="260px">
+ <Column width="260px" gap="1">
<Label>{t(labels.dateRange)}</Label>
<FormField name="parameters.dateRange" rules={{ required: t(labels.required) }}>
<DateFilter placement="bottom start" />
</FormField>
</Column>
- <Column>
- <Label>{t(labels.filters)}</Label>
+ <Column gap="1">
+ <Text weight="bold">{t(labels.filters)}</Text>
<FormField name="parameters.filters">
<FieldFilters
websiteId={websiteId}
@@ -137,7 +139,7 @@ export function CohortEditForm({
{t(labels.save)}
</FormSubmitButton>
</FormButtons>
- </>
+ </Column>
);
}}
</Form>
diff --git a/src/app/(main)/websites/[websiteId]/segments/SegmentEditForm.tsx b/src/app/(main)/websites/[websiteId]/segments/SegmentEditForm.tsx
index 553c0c9b6..62078cf81 100644
--- a/src/app/(main)/websites/[websiteId]/segments/SegmentEditForm.tsx
+++ b/src/app/(main)/websites/[websiteId]/segments/SegmentEditForm.tsx
@@ -1,21 +1,25 @@
import {
Button,
+ Column,
Form,
FormButtons,
FormField,
FormSubmitButton,
- Label,
Loading,
+ Text,
TextField,
} from '@umami/react-zen';
import { useEffect, useState } from 'react';
import { useMessages, useUpdateQuery, useWebsiteSegmentQuery } from '@/components/hooks';
import { FieldFilters } from '@/components/input/FieldFilters';
+import { PropertyFilters } from '@/components/property-data/PropertyFilters';
+import type { SessionPropertyFilter } from '@/lib/types';
export function SegmentEditForm({
segmentId,
websiteId,
filters = [],
+ sessionPropertyFilters = [],
showFilters = true,
onSave,
onClose,
@@ -23,6 +27,7 @@ export function SegmentEditForm({
segmentId?: string;
websiteId: string;
filters?: any[];
+ sessionPropertyFilters?: SessionPropertyFilter[];
showFilters?: boolean;
onSave?: () => void;
onClose?: () => void;
@@ -69,32 +74,50 @@ export function SegmentEditForm({
return (
<Form
onSubmit={handleSubmit}
- defaultValues={data || { parameters: { filters } }}
+ defaultValues={data || { name: '', parameters: { filters, sessionPropertyFilters } }}
error={getErrorMessage(error)}
>
- <FormField name="name" label={t(labels.name)} rules={{ required: t(labels.required) }}>
- <TextField autoFocus={!segmentId} />
- </FormField>
- {showFilters && (
- <>
- <Label>{t(labels.filters)}</Label>
- <FormField name="parameters.filters" rules={{ required: t(labels.required) }}>
- <FieldFilters
- websiteId={websiteId}
- match={currentMatch}
- onMatchChange={setCurrentMatch}
- />
- </FormField>
- </>
- )}
- <FormButtons>
- <Button isDisabled={isPending} onPress={onClose}>
- {t(labels.cancel)}
- </Button>
- <FormSubmitButton variant="primary" data-test="button-submit" isDisabled={isPending}>
- {t(labels.save)}
- </FormSubmitButton>
- </FormButtons>
+ <Column gap="4">
+ <FormField name="name" label={t(labels.name)} rules={{ required: t(labels.required) }}>
+ <TextField autoFocus={!segmentId} />
+ </FormField>
+ {showFilters && (
+ <Column gap="4">
+ <Column gap="1">
+ <Text weight="bold">{t(labels.filters)}</Text>
+ <FormField name="parameters.filters">
+ <FieldFilters
+ websiteId={websiteId}
+ match={currentMatch}
+ onMatchChange={setCurrentMatch}
+ />
+ </FormField>
+ </Column>
+
+ <Column gap="1">
+ <Text weight="bold">{t(labels.sessionData)}</Text>
+ <FormField name="parameters.sessionPropertyFilters">
+ {({ field }) => (
+ <PropertyFilters
+ source="session"
+ websiteId={websiteId}
+ value={field.value ?? []}
+ onChange={field.onChange}
+ />
+ )}
+ </FormField>
+ </Column>
+ </Column>
+ )}
+ <FormButtons>
+ <Button isDisabled={isPending} onPress={onClose}>
+ {t(labels.cancel)}
+ </Button>
+ <FormSubmitButton variant="primary" data-test="button-submit" isDisabled={isPending}>
+ {t(labels.save)}
+ </FormSubmitButton>
+ </FormButtons>
+ </Column>
</Form>
);
}
diff --git a/src/app/(main)/websites/[websiteId]/settings/ShareEditForm.tsx b/src/app/(main)/websites/[websiteId]/settings/ShareEditForm.tsx
index b89e4e222..161e271ed 100644
--- a/src/app/(main)/websites/[websiteId]/settings/ShareEditForm.tsx
+++ b/src/app/(main)/websites/[websiteId]/settings/ShareEditForm.tsx
@@ -128,7 +128,7 @@ export function ShareEditForm({
return (
<Column gap="6">
{url && (
- <Column>
+ <Column gap="1">
<Label>{t(labels.shareUrl)}</Label>
<TextField value={url} isReadOnly allowCopy />
</Column>
diff --git a/src/app/api/websites/[websiteId]/segments/[segmentId]/route.ts b/src/app/api/websites/[websiteId]/segments/[segmentId]/route.ts
index 1ed6d7955..c3f6bc619 100644
--- a/src/app/api/websites/[websiteId]/segments/[segmentId]/route.ts
+++ b/src/app/api/websites/[websiteId]/segments/[segmentId]/route.ts
@@ -1,7 +1,7 @@
import { z } from 'zod';
import { parseRequest } from '@/lib/request';
-import { json, notFound, ok, unauthorized } from '@/lib/response';
-import { anyObjectParam, segmentTypeParam } from '@/lib/schema';
+import { badRequest, json, notFound, ok, unauthorized } from '@/lib/response';
+import { segmentParamSchema, segmentTypeParam } from '@/lib/schema';
import { canDeleteWebsite, canUpdateWebsite, canViewSharedWebsiteFilters } from '@/permissions';
import { deleteSegment, getWebsiteSegment, updateSegment } from '@/queries/prisma';
@@ -37,7 +37,7 @@ export async function POST(
const schema = z.object({
type: segmentTypeParam,
name: z.string().max(200),
- parameters: anyObjectParam,
+ parameters: segmentParamSchema,
});
const { auth, body, error } = await parseRequest(request, schema);
@@ -49,6 +49,10 @@ export async function POST(
const { websiteId, segmentId } = await params;
const { type, name, parameters } = body;
+ if (type === 'cohort' && parameters.sessionPropertyFilters?.length) {
+ return badRequest({ message: 'Session property filters are only supported for segments.' });
+ }
+
if (!(await canUpdateWebsite(auth, websiteId))) {
return unauthorized();
}
diff --git a/src/app/api/websites/[websiteId]/segments/route.ts b/src/app/api/websites/[websiteId]/segments/route.ts
index 39f326582..015dc8b6c 100644
--- a/src/app/api/websites/[websiteId]/segments/route.ts
+++ b/src/app/api/websites/[websiteId]/segments/route.ts
@@ -1,7 +1,7 @@
import { z } from 'zod';
import { uuid } from '@/lib/crypto';
import { getQueryFilters, parseRequest } from '@/lib/request';
-import { json, unauthorized } from '@/lib/response';
+import { badRequest, json, unauthorized } from '@/lib/response';
import { searchParams, segmentParamSchema, segmentTypeParam } from '@/lib/schema';
import { canUpdateWebsite, canViewSharedWebsiteFilters } from '@/permissions';
import { createSegment, getWebsiteSegments } from '@/queries/prisma';
@@ -54,6 +54,10 @@ export async function POST(
const { websiteId } = await params;
const { type, name, parameters } = body;
+ if (type === 'cohort' && parameters.sessionPropertyFilters?.length) {
+ return badRequest({ message: 'Session property filters are only supported for segments.' });
+ }
+
if (!(await canUpdateWebsite(auth, websiteId))) {
return unauthorized();
}
diff --git a/src/components/common/FilterRecord.tsx b/src/components/common/FilterRecord.tsx
index cb2a1462d..0f8d311ff 100644
--- a/src/components/common/FilterRecord.tsx
+++ b/src/components/common/FilterRecord.tsx
@@ -84,7 +84,7 @@ export function FilterRecord({
};
return (
- <Column>
+ <Column gap="1">
<Label>{fields.find(f => f.name === name)?.label}</Label>
<Grid columns="1fr auto" gap>
<Grid columns={{ base: '1fr', md: '200px 1fr' }} gap>
diff --git a/src/components/input/FilterBar.tsx b/src/components/input/FilterBar.tsx
index 61b7d8387..5429dd1f6 100644
--- a/src/components/input/FilterBar.tsx
+++ b/src/components/input/FilterBar.tsx
@@ -35,9 +35,8 @@ export function FilterBar({ websiteId }: { websiteId?: string }) {
const { data, isLoading } = useWebsiteSegmentQuery(websiteId, segment || cohort);
const canSaveSegment =
!!websiteId &&
- filters.length > 0 &&
+ (filters.length > 0 || sessionPropertyFilters.length > 0) &&
eventPropertyFilters.length === 0 &&
- sessionPropertyFilters.length === 0 &&
!segment &&
!cohort &&
!pathname.includes('/share');
@@ -192,7 +191,14 @@ export function FilterBar({ websiteId }: { websiteId?: string }) {
}}
>
{({ close }) => {
- return <SegmentEditForm websiteId={websiteId} onClose={close} filters={filters} />;
+ return (
+ <SegmentEditForm
+ websiteId={websiteId}
+ onClose={close}
+ filters={filters}
+ sessionPropertyFilters={sessionPropertyFilters}
+ />
+ );
}}
</Dialog>
</Modal>
diff --git a/src/components/input/PreferencesButton.tsx b/src/components/input/PreferencesButton.tsx
index 87149bba3..439ac7b32 100644
--- a/src/components/input/PreferencesButton.tsx
+++ b/src/components/input/PreferencesButton.tsx
@@ -17,11 +17,11 @@ export function PreferencesButton() {
</Button>
<Popover side="bottom" align="end">
<Panel gap="3">
- <Column>
+ <Column gap="1">
<Label>{t(labels.timezone)}</Label>
<TimezoneSetting />
</Column>
- <Column>
+ <Column gap="1">
<Label>{t(labels.defaultDateRange)}</Label>
<DateRangeSetting />
</Column>
diff --git a/src/components/property-data/PropertyFilterRecord.tsx b/src/components/property-data/PropertyFilterRecord.tsx
index 710cb40e3..3131a3cce 100644
--- a/src/components/property-data/PropertyFilterRecord.tsx
+++ b/src/components/property-data/PropertyFilterRecord.tsx
@@ -148,7 +148,7 @@ export function PropertyFilterRecord({
};
return (
- <Column minWidth="0">
+ <Column minWidth="0" gap="1">
<Label
title={filter.propertyName}
style={{
diff --git a/src/components/share/SimpleShareEditForm.tsx b/src/components/share/SimpleShareEditForm.tsx
index ddfbda9f8..abfbd2a3b 100644
--- a/src/components/share/SimpleShareEditForm.tsx
+++ b/src/components/share/SimpleShareEditForm.tsx
@@ -92,7 +92,7 @@ export function SimpleShareEditForm({
>
{({ watch, setValue }) => (
<Column gap="6">
- <Column>
+ <Column gap="1">
<Label>{t(labels.shareUrl)}</Label>
<TextField value={getUrl(share?.slug || '')} isReadOnly allowCopy />
</Column>
diff --git a/src/lib/request.test.ts b/src/lib/request.test.ts
new file mode 100644
index 000000000..a23550dec
--- /dev/null
+++ b/src/lib/request.test.ts
@@ -0,0 +1,48 @@
+import { beforeEach, expect, test, vi } from 'vitest';
+import { fetchWebsite } from '@/lib/load';
+import { getWebsiteSegment } from '@/queries/prisma';
+import { getQueryFilters } from './request';
+
+vi.mock('@/lib/load', () => ({
+ fetchAccount: vi.fn(),
+ fetchWebsite: vi.fn(),
+}));
+
+vi.mock('@/queries/prisma', () => ({
+ getWebsiteSegment: vi.fn(),
+}));
+
+const fetchWebsiteMock = vi.mocked(fetchWebsite);
+const getWebsiteSegmentMock = vi.mocked(getWebsiteSegment);
+
+beforeEach(() => {
+ fetchWebsiteMock.mockReset();
+ getWebsiteSegmentMock.mockReset();
+ fetchWebsiteMock.mockResolvedValue({ id: 'website-1' } as any);
+});
+
+test('combines a saved segment\'s session property filters with active filters', async () => {
+ getWebsiteSegmentMock.mockResolvedValue({
+ parameters: {
+ filters: [],
+ sessionPropertyFilters: [
+ { propertyName: 'plan', dataType: 1, operator: 'eq', value: 'pro' },
+ ],
+ },
+ } as any);
+
+ const filters = await getQueryFilters(
+ {
+ startAt: String(+new Date('2026-09-01T00:00:00.000Z')),
+ endAt: String(+new Date('2026-09-02T00:00:00.000Z')),
+ segment: 'segment-1',
+ spf0: '1.eq.country.US',
+ },
+ 'website-1',
+ );
+
+ expect(filters.sessionPropertyFilters).toEqual([
+ { propertyName: 'country', dataType: 1, operator: 'eq', value: 'US' },
+ { propertyName: 'plan', dataType: 1, operator: 'eq', value: 'pro' },
+ ]);
+});
diff --git a/src/lib/request.ts b/src/lib/request.ts
index e21a243d0..8c5396bc7 100644
--- a/src/lib/request.ts
+++ b/src/lib/request.ts
@@ -134,6 +134,7 @@ export async function getQueryFilters(
?.parameters as Record<string, any>;
Object.assign(filters, filtersArrayToObject(segmentParams.filters));
+ sessionPropertyFilters.push(...(segmentParams.sessionPropertyFilters ?? []));
if (segmentParams.match) {
match = segmentParams.match;
diff --git a/src/lib/schema.ts b/src/lib/schema.ts
index 3a4e98de6..011d46a27 100644
--- a/src/lib/schema.ts
+++ b/src/lib/schema.ts
@@ -1,6 +1,6 @@
import { z } from 'zod';
import { isValidTimezone, normalizeTimezone } from '@/lib/date';
-import { UNIT_TYPES } from './constants';
+import { DATA_TYPE, FIELD_LENGTH, UNIT_TYPES } from './constants';
export const timezoneParam = z
.string()
@@ -332,6 +332,19 @@ export const reportResultSchema = z.intersection(
export const segmentTypeParam = z.enum(['segment', 'cohort']);
+const propertyFilterParamSchema = z.object({
+ propertyName: z.string().min(1).max(FIELD_LENGTH.dataKey),
+ dataType: z.union([
+ z.literal(DATA_TYPE.string),
+ z.literal(DATA_TYPE.number),
+ z.literal(DATA_TYPE.boolean),
+ z.literal(DATA_TYPE.date),
+ z.literal(DATA_TYPE.array),
+ ]),
+ operator: operatorParam,
+ value: z.string(),
+});
+
export const segmentParamSchema = z.object({
filters: z
.array(
@@ -342,6 +355,7 @@ export const segmentParamSchema = z.object({
}),
)
.optional(),
+ sessionPropertyFilters: z.array(propertyFilterParamSchema).optional(),
match: z.enum(['all', 'any']).optional(),
dateRange: z.string().optional(),
action: z