From a3733b0424727ebe02b97aecf732e3891d677b76 Mon Sep 17 00:00:00 2001 From: Mike Cao Date: Thu, 5 Feb 2026 21:25:46 -0800 Subject: [PATCH 01/22] Fix TypeScript type errors across multiple files --- .../[websiteId]/(reports)/funnels/Funnel.tsx | 2 +- .../(reports)/funnels/FunnelAddButton.tsx | 2 +- .../websites/[websiteId]/(reports)/goals/Goal.tsx | 2 +- .../(main)/websites/[websiteId]/WebsiteChart.tsx | 6 +++++- .../(main)/websites/[websiteId]/WebsiteMenu.tsx | 4 ++-- src/components/hooks/useMessages.ts | 10 +++++++--- src/components/input/LanguageButton.tsx | 2 +- src/declaration.d.ts | 15 +++++++++++++++ src/lib/db.ts | 2 +- src/lib/react.ts | 2 +- src/lib/request.ts | 2 +- src/queries/sql/reports/getJourney.ts | 4 ++-- 12 files changed, 38 insertions(+), 15 deletions(-) diff --git a/src/app/(main)/websites/[websiteId]/(reports)/funnels/Funnel.tsx b/src/app/(main)/websites/[websiteId]/(reports)/funnels/Funnel.tsx index e336a3db6..54b4cd0f9 100644 --- a/src/app/(main)/websites/[websiteId]/(reports)/funnels/Funnel.tsx +++ b/src/app/(main)/websites/[websiteId]/(reports)/funnels/Funnel.tsx @@ -42,7 +42,7 @@ export function Funnel({ id, name, type, parameters, websiteId }) { return ( diff --git a/src/app/(main)/websites/[websiteId]/(reports)/funnels/FunnelAddButton.tsx b/src/app/(main)/websites/[websiteId]/(reports)/funnels/FunnelAddButton.tsx index 29b548032..725262aac 100644 --- a/src/app/(main)/websites/[websiteId]/(reports)/funnels/FunnelAddButton.tsx +++ b/src/app/(main)/websites/[websiteId]/(reports)/funnels/FunnelAddButton.tsx @@ -16,7 +16,7 @@ export function FunnelAddButton({ websiteId }: { websiteId: string }) { diff --git a/src/app/(main)/websites/[websiteId]/(reports)/goals/Goal.tsx b/src/app/(main)/websites/[websiteId]/(reports)/goals/Goal.tsx index b6c4a11d6..39eb34890 100644 --- a/src/app/(main)/websites/[websiteId]/(reports)/goals/Goal.tsx +++ b/src/app/(main)/websites/[websiteId]/(reports)/goals/Goal.tsx @@ -51,7 +51,7 @@ export function Goal({ id, name, type, parameters, websiteId, startDate, endDate return ( diff --git a/src/app/(main)/websites/[websiteId]/WebsiteChart.tsx b/src/app/(main)/websites/[websiteId]/WebsiteChart.tsx index b2ea2a83e..165d2da21 100644 --- a/src/app/(main)/websites/[websiteId]/WebsiteChart.tsx +++ b/src/app/(main)/websites/[websiteId]/WebsiteChart.tsx @@ -22,7 +22,11 @@ export function WebsiteChart({ const chartData = useMemo(() => { if (data) { - const result = { + const result: { + pageviews: any[]; + sessions: any[]; + compare?: { pageviews: any[]; sessions: any[] }; + } = { pageviews, sessions, }; diff --git a/src/app/(main)/websites/[websiteId]/WebsiteMenu.tsx b/src/app/(main)/websites/[websiteId]/WebsiteMenu.tsx index 301895341..8025635a0 100644 --- a/src/app/(main)/websites/[websiteId]/WebsiteMenu.tsx +++ b/src/app/(main)/websites/[websiteId]/WebsiteMenu.tsx @@ -10,7 +10,7 @@ import { } from '@umami/react-zen'; import { Fragment } from 'react'; import { useMessages, useNavigation } from '@/components/hooks'; -import { Edit, More, Share } from '@/components/icons'; +import { Edit, Ellipsis, Share } from '@/components/icons'; export function WebsiteMenu({ websiteId }: { websiteId: string }) { const { formatMessage, labels } = useMessages(); @@ -33,7 +33,7 @@ export function WebsiteMenu({ websiteId }: { websiteId: string }) { diff --git a/src/components/hooks/useMessages.ts b/src/components/hooks/useMessages.ts index d5bc2423d..c1bffa432 100644 --- a/src/components/hooks/useMessages.ts +++ b/src/components/hooks/useMessages.ts @@ -13,7 +13,7 @@ interface UseMessages { messages: typeof messages; labels: typeof labels; getMessage: (id: string) => string; - getErrorMessage: (error: ApiError) => string | undefined; + getErrorMessage: (error: string | Error | ApiError) => string | undefined; FormattedMessage: typeof FormattedMessage; } @@ -26,12 +26,16 @@ export function useMessages(): UseMessages { return message ? formatMessage(message) : id; }; - const getErrorMessage = (error: ApiError) => { + const getErrorMessage = (error: string | Error | ApiError) => { if (!error) { return undefined; } - const code = error?.code; + if (typeof error === 'string') { + return error; + } + + const code = (error as ApiError)?.code; return code ? getMessage(code) : error?.message || 'Unknown error'; }; diff --git a/src/components/input/LanguageButton.tsx b/src/components/input/LanguageButton.tsx index ac43dcb6b..fe4380d38 100644 --- a/src/components/input/LanguageButton.tsx +++ b/src/components/input/LanguageButton.tsx @@ -19,7 +19,7 @@ export function LanguageButton() { - + {items.map(({ value, label }) => { return ( diff --git a/src/declaration.d.ts b/src/declaration.d.ts index 14bae12ab..17acee2bb 100644 --- a/src/declaration.d.ts +++ b/src/declaration.d.ts @@ -16,3 +16,18 @@ declare module 'semver'; declare module 'tsup'; declare module 'uuid'; declare module '@umami/esbuild-plugin-css-modules'; + +interface UmamiTracker { + track: { + (): Promise; + (eventName: string): Promise; + (eventName: string, obj: Record): Promise; + (properties: Record): Promise; + (eventFunction: (props: Record) => Record): Promise; + }; + identify: (data: Record) => Promise; +} + +interface Window { + umami: UmamiTracker; +} diff --git a/src/lib/db.ts b/src/lib/db.ts index 7b6e8368b..7bee4816b 100644 --- a/src/lib/db.ts +++ b/src/lib/db.ts @@ -5,7 +5,7 @@ export const KAFKA = 'kafka'; export const KAFKA_PRODUCER = 'kafka-producer'; // Fixes issue with converting bigint values -BigInt.prototype.toJSON = function () { +(BigInt.prototype as any).toJSON = function () { return Number(this); }; diff --git a/src/lib/react.ts b/src/lib/react.ts index 668cdf1fb..5a7ce2012 100644 --- a/src/lib/react.ts +++ b/src/lib/react.ts @@ -10,7 +10,7 @@ import { export function getFragmentChildren(children: ReactNode) { return (children as ReactElement)?.type === Fragment - ? (children as ReactElement).props.children + ? (children as ReactElement<{ children: ReactNode }>).props.children : children; } diff --git a/src/lib/request.ts b/src/lib/request.ts index 42c449048..74ee432a3 100644 --- a/src/lib/request.ts +++ b/src/lib/request.ts @@ -16,7 +16,7 @@ export async function parseRequest( const url = new URL(request.url); let query = Object.fromEntries(url.searchParams); let body = await getJsonBody(request); - let error: () => undefined | undefined; + let error: (() => Response) | undefined; let auth = null; if (schema) { diff --git a/src/queries/sql/reports/getJourney.ts b/src/queries/sql/reports/getJourney.ts index 283e0fad4..362f7bdba 100644 --- a/src/queries/sql/reports/getJourney.ts +++ b/src/queries/sql/reports/getJourney.ts @@ -60,7 +60,7 @@ async function relationalQuery( endStepQuery: string; params: Record; } { - const params = {}; + const params: Record = {}; let sequenceQuery = ''; let startStepQuery = ''; let endStepQuery = ''; @@ -172,7 +172,7 @@ async function clickhouseQuery( endStepQuery: string; params: Record; } { - const params = {}; + const params: Record = {}; let sequenceQuery = ''; let startStepQuery = ''; let endStepQuery = ''; From 2260520ae58b7b79327f0f50e4d465931b07f41c Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Mon, 16 Feb 2026 16:20:04 -0800 Subject: [PATCH 02/22] Revert "Fix TypeScript type errors across multiple files" This reverts commit a3733b0424727ebe02b97aecf732e3891d677b76. --- .../[websiteId]/(reports)/funnels/Funnel.tsx | 2 +- .../(reports)/funnels/FunnelAddButton.tsx | 2 +- .../websites/[websiteId]/(reports)/goals/Goal.tsx | 2 +- .../(main)/websites/[websiteId]/WebsiteChart.tsx | 6 +----- .../(main)/websites/[websiteId]/WebsiteMenu.tsx | 4 ++-- src/components/hooks/useMessages.ts | 10 +++------- src/components/input/LanguageButton.tsx | 2 +- src/declaration.d.ts | 15 --------------- src/lib/db.ts | 2 +- src/lib/react.ts | 2 +- src/lib/request.ts | 2 +- src/queries/sql/reports/getJourney.ts | 4 ++-- 12 files changed, 15 insertions(+), 38 deletions(-) diff --git a/src/app/(main)/websites/[websiteId]/(reports)/funnels/Funnel.tsx b/src/app/(main)/websites/[websiteId]/(reports)/funnels/Funnel.tsx index 54b4cd0f9..e336a3db6 100644 --- a/src/app/(main)/websites/[websiteId]/(reports)/funnels/Funnel.tsx +++ b/src/app/(main)/websites/[websiteId]/(reports)/funnels/Funnel.tsx @@ -42,7 +42,7 @@ export function Funnel({ id, name, type, parameters, websiteId }) { return ( diff --git a/src/app/(main)/websites/[websiteId]/(reports)/funnels/FunnelAddButton.tsx b/src/app/(main)/websites/[websiteId]/(reports)/funnels/FunnelAddButton.tsx index 725262aac..29b548032 100644 --- a/src/app/(main)/websites/[websiteId]/(reports)/funnels/FunnelAddButton.tsx +++ b/src/app/(main)/websites/[websiteId]/(reports)/funnels/FunnelAddButton.tsx @@ -16,7 +16,7 @@ export function FunnelAddButton({ websiteId }: { websiteId: string }) { diff --git a/src/app/(main)/websites/[websiteId]/(reports)/goals/Goal.tsx b/src/app/(main)/websites/[websiteId]/(reports)/goals/Goal.tsx index 39eb34890..b6c4a11d6 100644 --- a/src/app/(main)/websites/[websiteId]/(reports)/goals/Goal.tsx +++ b/src/app/(main)/websites/[websiteId]/(reports)/goals/Goal.tsx @@ -51,7 +51,7 @@ export function Goal({ id, name, type, parameters, websiteId, startDate, endDate return ( diff --git a/src/app/(main)/websites/[websiteId]/WebsiteChart.tsx b/src/app/(main)/websites/[websiteId]/WebsiteChart.tsx index 165d2da21..b2ea2a83e 100644 --- a/src/app/(main)/websites/[websiteId]/WebsiteChart.tsx +++ b/src/app/(main)/websites/[websiteId]/WebsiteChart.tsx @@ -22,11 +22,7 @@ export function WebsiteChart({ const chartData = useMemo(() => { if (data) { - const result: { - pageviews: any[]; - sessions: any[]; - compare?: { pageviews: any[]; sessions: any[] }; - } = { + const result = { pageviews, sessions, }; diff --git a/src/app/(main)/websites/[websiteId]/WebsiteMenu.tsx b/src/app/(main)/websites/[websiteId]/WebsiteMenu.tsx index 8025635a0..301895341 100644 --- a/src/app/(main)/websites/[websiteId]/WebsiteMenu.tsx +++ b/src/app/(main)/websites/[websiteId]/WebsiteMenu.tsx @@ -10,7 +10,7 @@ import { } from '@umami/react-zen'; import { Fragment } from 'react'; import { useMessages, useNavigation } from '@/components/hooks'; -import { Edit, Ellipsis, Share } from '@/components/icons'; +import { Edit, More, Share } from '@/components/icons'; export function WebsiteMenu({ websiteId }: { websiteId: string }) { const { formatMessage, labels } = useMessages(); @@ -33,7 +33,7 @@ export function WebsiteMenu({ websiteId }: { websiteId: string }) { diff --git a/src/components/hooks/useMessages.ts b/src/components/hooks/useMessages.ts index c1bffa432..d5bc2423d 100644 --- a/src/components/hooks/useMessages.ts +++ b/src/components/hooks/useMessages.ts @@ -13,7 +13,7 @@ interface UseMessages { messages: typeof messages; labels: typeof labels; getMessage: (id: string) => string; - getErrorMessage: (error: string | Error | ApiError) => string | undefined; + getErrorMessage: (error: ApiError) => string | undefined; FormattedMessage: typeof FormattedMessage; } @@ -26,16 +26,12 @@ export function useMessages(): UseMessages { return message ? formatMessage(message) : id; }; - const getErrorMessage = (error: string | Error | ApiError) => { + const getErrorMessage = (error: ApiError) => { if (!error) { return undefined; } - if (typeof error === 'string') { - return error; - } - - const code = (error as ApiError)?.code; + const code = error?.code; return code ? getMessage(code) : error?.message || 'Unknown error'; }; diff --git a/src/components/input/LanguageButton.tsx b/src/components/input/LanguageButton.tsx index fe4380d38..ac43dcb6b 100644 --- a/src/components/input/LanguageButton.tsx +++ b/src/components/input/LanguageButton.tsx @@ -19,7 +19,7 @@ export function LanguageButton() { - + {items.map(({ value, label }) => { return ( diff --git a/src/declaration.d.ts b/src/declaration.d.ts index 17acee2bb..14bae12ab 100644 --- a/src/declaration.d.ts +++ b/src/declaration.d.ts @@ -16,18 +16,3 @@ declare module 'semver'; declare module 'tsup'; declare module 'uuid'; declare module '@umami/esbuild-plugin-css-modules'; - -interface UmamiTracker { - track: { - (): Promise; - (eventName: string): Promise; - (eventName: string, obj: Record): Promise; - (properties: Record): Promise; - (eventFunction: (props: Record) => Record): Promise; - }; - identify: (data: Record) => Promise; -} - -interface Window { - umami: UmamiTracker; -} diff --git a/src/lib/db.ts b/src/lib/db.ts index 7bee4816b..7b6e8368b 100644 --- a/src/lib/db.ts +++ b/src/lib/db.ts @@ -5,7 +5,7 @@ export const KAFKA = 'kafka'; export const KAFKA_PRODUCER = 'kafka-producer'; // Fixes issue with converting bigint values -(BigInt.prototype as any).toJSON = function () { +BigInt.prototype.toJSON = function () { return Number(this); }; diff --git a/src/lib/react.ts b/src/lib/react.ts index 5a7ce2012..668cdf1fb 100644 --- a/src/lib/react.ts +++ b/src/lib/react.ts @@ -10,7 +10,7 @@ import { export function getFragmentChildren(children: ReactNode) { return (children as ReactElement)?.type === Fragment - ? (children as ReactElement<{ children: ReactNode }>).props.children + ? (children as ReactElement).props.children : children; } diff --git a/src/lib/request.ts b/src/lib/request.ts index 74ee432a3..42c449048 100644 --- a/src/lib/request.ts +++ b/src/lib/request.ts @@ -16,7 +16,7 @@ export async function parseRequest( const url = new URL(request.url); let query = Object.fromEntries(url.searchParams); let body = await getJsonBody(request); - let error: (() => Response) | undefined; + let error: () => undefined | undefined; let auth = null; if (schema) { diff --git a/src/queries/sql/reports/getJourney.ts b/src/queries/sql/reports/getJourney.ts index 362f7bdba..283e0fad4 100644 --- a/src/queries/sql/reports/getJourney.ts +++ b/src/queries/sql/reports/getJourney.ts @@ -60,7 +60,7 @@ async function relationalQuery( endStepQuery: string; params: Record; } { - const params: Record = {}; + const params = {}; let sequenceQuery = ''; let startStepQuery = ''; let endStepQuery = ''; @@ -172,7 +172,7 @@ async function clickhouseQuery( endStepQuery: string; params: Record; } { - const params: Record = {}; + const params = {}; let sequenceQuery = ''; let startStepQuery = ''; let endStepQuery = ''; From 530c21dac088ce76e2b66c7ed8bce3ff9ae69149 Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Tue, 17 Feb 2026 21:55:35 -0800 Subject: [PATCH 03/22] add limit 50 to event chart, metrics table, and UTM report --- .../[websiteId]/events/EventsPage.tsx | 3 +- .../[websiteId]/events/series/route.ts | 4 +- .../queries/useWebsiteEventsSeriesQuery.ts | 20 +++++++-- src/components/metrics/EventsChart.tsx | 5 ++- src/queries/sql/events/getEventStats.ts | 44 ++++++++++++++++++- src/queries/sql/reports/getUTM.ts | 2 + 6 files changed, 69 insertions(+), 9 deletions(-) diff --git a/src/app/(main)/websites/[websiteId]/events/EventsPage.tsx b/src/app/(main)/websites/[websiteId]/events/EventsPage.tsx index f75f735ad..dc46fe41e 100644 --- a/src/app/(main)/websites/[websiteId]/events/EventsPage.tsx +++ b/src/app/(main)/websites/[websiteId]/events/EventsPage.tsx @@ -89,13 +89,14 @@ export function EventsPage({ websiteId }) { - + diff --git a/src/app/api/websites/[websiteId]/events/series/route.ts b/src/app/api/websites/[websiteId]/events/series/route.ts index 977e9c813..6060105c2 100644 --- a/src/app/api/websites/[websiteId]/events/series/route.ts +++ b/src/app/api/websites/[websiteId]/events/series/route.ts @@ -14,6 +14,7 @@ export async function GET( endAt: z.coerce.number().int(), unit: unitParam.optional(), timezone: timezoneParam, + limit: z.coerce.number().optional(), ...filterParams, }); @@ -29,9 +30,10 @@ export async function GET( return unauthorized(); } + const { limit } = query; const filters = await getQueryFilters(query, websiteId); - const data = await getEventStats(websiteId, filters); + const data = await getEventStats(websiteId, { limit }, filters); return json(data); } diff --git a/src/components/hooks/queries/useWebsiteEventsSeriesQuery.ts b/src/components/hooks/queries/useWebsiteEventsSeriesQuery.ts index 6c1d112dd..5318d0d9e 100644 --- a/src/components/hooks/queries/useWebsiteEventsSeriesQuery.ts +++ b/src/components/hooks/queries/useWebsiteEventsSeriesQuery.ts @@ -3,15 +3,29 @@ import { useApi } from '../useApi'; import { useDateParameters } from '../useDateParameters'; import { useFilterParameters } from '../useFilterParameters'; -export function useWebsiteEventsSeriesQuery(websiteId: string, options?: ReactQueryOptions) { +export function useWebsiteEventsSeriesQuery( + websiteId: string, + params?: { limit?: number }, + options?: ReactQueryOptions, +) { const { get, useQuery } = useApi(); const { startAt, endAt, unit, timezone } = useDateParameters(); const filters = useFilterParameters(); return useQuery({ - queryKey: ['websites:events:series', { websiteId, startAt, endAt, unit, timezone, ...filters }], + queryKey: [ + 'websites:events:series', + { websiteId, startAt, endAt, unit, timezone, ...filters, ...params }, + ], queryFn: () => - get(`/websites/${websiteId}/events/series`, { startAt, endAt, unit, timezone, ...filters }), + get(`/websites/${websiteId}/events/series`, { + startAt, + endAt, + unit, + timezone, + ...filters, + ...params, + }), enabled: !!websiteId, ...options, }); diff --git a/src/components/metrics/EventsChart.tsx b/src/components/metrics/EventsChart.tsx index 3a53ba9a6..db23dcc47 100644 --- a/src/components/metrics/EventsChart.tsx +++ b/src/components/metrics/EventsChart.tsx @@ -15,15 +15,16 @@ import { generateTimeSeries } from '@/lib/date'; export interface EventsChartProps extends BarChartProps { websiteId: string; focusLabel?: string; + limit?: number; } -export function EventsChart({ websiteId, focusLabel }: EventsChartProps) { +export function EventsChart({ websiteId, focusLabel, limit }: EventsChartProps) { const { timezone } = useTimezone(); const { dateRange: { startDate, endDate, unit }, } = useDateRange({ timezone: timezone }); const { locale, dateLocale } = useLocale(); - const { data, isLoading, error } = useWebsiteEventsSeriesQuery(websiteId); + const { data, isLoading, error } = useWebsiteEventsSeriesQuery(websiteId, { limit }); const [label, setLabel] = useState(focusLabel); const chartData: any = useMemo(() => { diff --git a/src/queries/sql/events/getEventStats.ts b/src/queries/sql/events/getEventStats.ts index 81d12a0ff..2caba3268 100644 --- a/src/queries/sql/events/getEventStats.ts +++ b/src/queries/sql/events/getEventStats.ts @@ -6,6 +6,10 @@ import type { QueryFilters } from '@/lib/types'; const FUNCTION_NAME = 'getEventStats'; +export interface EventStatsParameters { + limit?: number | string; +} + interface WebsiteEventMetric { x: string; t: string; @@ -13,7 +17,7 @@ interface WebsiteEventMetric { } export async function getEventStats( - ...args: [websiteId: string, filters: QueryFilters] + ...args: [websiteId: string, parameters: EventStatsParameters, filters: QueryFilters] ): Promise { return runQuery({ [PRISMA]: () => relationalQuery(...args), @@ -21,7 +25,12 @@ export async function getEventStats( }); } -async function relationalQuery(websiteId: string, filters: QueryFilters) { +async function relationalQuery( + websiteId: string, + parameters: EventStatsParameters, + filters: QueryFilters, +) { + const { limit } = parameters; const { timezone = 'utc', unit = 'day' } = filters; const { rawQuery, getDateSQL, parseFilters } = prisma; const { filterQuery, cohortQuery, joinSessionQuery, queryParams } = parseFilters({ @@ -30,6 +39,19 @@ async function relationalQuery(websiteId: string, filters: QueryFilters) { eventType: EVENT_TYPE.customEvent, }); + const limitQuery = limit + ? `and event_name in ( + select event_name + from website_event + where website_id = {{websiteId::uuid}} + and created_at between {{startDate}} and {{endDate}} + and event_type = 2 + group by event_name + order by count(*) desc + limit ${limit} + )` + : ''; + return rawQuery( ` select @@ -42,6 +64,7 @@ async function relationalQuery(websiteId: string, filters: QueryFilters) { where website_event.website_id = {{websiteId::uuid}} and website_event.created_at between {{startDate}} and {{endDate}} ${filterQuery} + ${limitQuery} group by 1, 2 order by 2 `, @@ -52,8 +75,10 @@ async function relationalQuery(websiteId: string, filters: QueryFilters) { async function clickhouseQuery( websiteId: string, + parameters: EventStatsParameters, filters: QueryFilters, ): Promise<{ x: string; t: string; y: number }[]> { + const { limit } = parameters; const { timezone = 'UTC', unit = 'day' } = filters; const { rawQuery, getDateSQL, parseFilters } = clickhouse; const { filterQuery, cohortQuery, queryParams } = parseFilters({ @@ -62,6 +87,19 @@ async function clickhouseQuery( eventType: EVENT_TYPE.customEvent, }); + const limitQuery = limit + ? `and event_name in ( + select event_name + from website_event + where website_id = {websiteId:UUID} + and created_at between {startDate:DateTime64} and {endDate:DateTime64} + and event_type = {eventType:UInt32} + group by event_name + order by count(*) desc + limit ${limit} + )` + : ''; + let sql = ''; if (filterQuery || cohortQuery) { @@ -75,6 +113,7 @@ async function clickhouseQuery( where website_id = {websiteId:UUID} and created_at between {startDate:DateTime64} and {endDate:DateTime64} ${filterQuery} + ${limitQuery} group by x, t order by t `; @@ -91,6 +130,7 @@ async function clickhouseQuery( where website_id = {websiteId:UUID} and created_at between {startDate:DateTime64} and {endDate:DateTime64} and event_type = {eventType:UInt32} + ${limitQuery} ) as g group by x, t order by t diff --git a/src/queries/sql/reports/getUTM.ts b/src/queries/sql/reports/getUTM.ts index 4d43eb45b..f470e954c 100644 --- a/src/queries/sql/reports/getUTM.ts +++ b/src/queries/sql/reports/getUTM.ts @@ -47,6 +47,7 @@ async function relationalQuery( ${filterQuery} group by 1 order by 2 desc + limit 50 `, queryParams, ); @@ -78,6 +79,7 @@ async function clickhouseQuery( ${filterQuery} group by 1 order by 2 desc + limit 50 `, queryParams, ); From 99a328359b6c3c600e484ba211bed0ae103272e2 Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Tue, 17 Feb 2026 22:14:10 -0800 Subject: [PATCH 04/22] add comparison to events page metric bar --- .../[websiteId]/events/EventsPage.tsx | 75 +++++++++++-------- .../[websiteId]/events/stats/route.ts | 15 +++- .../hooks/queries/useEventStatsQuery.ts | 6 ++ 3 files changed, 63 insertions(+), 33 deletions(-) diff --git a/src/app/(main)/websites/[websiteId]/events/EventsPage.tsx b/src/app/(main)/websites/[websiteId]/events/EventsPage.tsx index dc46fe41e..5f5ab82a8 100644 --- a/src/app/(main)/websites/[websiteId]/events/EventsPage.tsx +++ b/src/app/(main)/websites/[websiteId]/events/EventsPage.tsx @@ -1,12 +1,11 @@ 'use client'; import { Column, Tab, TabList, TabPanel, Tabs } from '@umami/react-zen'; -import locale from 'date-fns/locale/af'; -import { type Key, useMemo, useState } from 'react'; +import { type Key, useState } from 'react'; import { SessionModal } from '@/app/(main)/websites/[websiteId]/sessions/SessionModal'; import { WebsiteControls } from '@/app/(main)/websites/[websiteId]/WebsiteControls'; import { LoadingPanel } from '@/components/common/LoadingPanel'; import { Panel } from '@/components/common/Panel'; -import { useMessages } from '@/components/hooks'; +import { useDateRange, useMessages } from '@/components/hooks'; import { useEventStatsQuery } from '@/components/hooks/queries/useEventStatsQuery'; import { EventsChart } from '@/components/metrics/EventsChart'; import { MetricCard } from '@/components/metrics/MetricCard'; @@ -21,6 +20,7 @@ const KEY_NAME = 'umami.events.tab'; export function EventsPage({ websiteId }) { const [tab, setTab] = useState(getItem(KEY_NAME) || 'chart'); + const { isAllTime } = useDateRange(); const { t, labels, getErrorMessage } = useMessages(); const { data, isLoading, isFetching, error } = useEventStatsQuery({ websiteId, @@ -31,34 +31,36 @@ export function EventsPage({ websiteId }) { setTab(value); }; - const metrics = useMemo(() => { - if (!data) return []; + const { events, visitors, visits, uniqueEvents, comparison } = data || {}; - const { events, visitors, visits, uniqueEvents } = data || {}; - - return [ - { - value: visitors, - label: t(labels.visitors), - formatValue: formatLongNumber, - }, - { - value: visits, - label: t(labels.visits), - formatValue: formatLongNumber, - }, - { - value: events, - label: t(labels.events), - formatValue: formatLongNumber, - }, - { - value: uniqueEvents, - label: t(labels.uniqueEvents), - formatValue: formatLongNumber, - }, - ] as any; - }, [data, locale]); + const metrics = data + ? [ + { + value: visitors, + label: t(labels.visitors), + change: visitors - comparison.visitors, + formatValue: formatLongNumber, + }, + { + value: visits, + label: t(labels.visits), + change: visits - comparison.visits, + formatValue: formatLongNumber, + }, + { + value: events, + label: t(labels.events), + change: events - comparison.events, + formatValue: formatLongNumber, + }, + { + value: uniqueEvents, + label: t(labels.uniqueEvents), + change: uniqueEvents - comparison.uniqueEvents, + formatValue: formatLongNumber, + }, + ] + : null; return ( @@ -71,8 +73,17 @@ export function EventsPage({ websiteId }) { minHeight="136px" > - {metrics?.map(({ label, value, formatValue }) => { - return ; + {metrics?.map(({ label, value, change, formatValue }) => { + return ( + + ); })} diff --git a/src/app/api/websites/[websiteId]/events/stats/route.ts b/src/app/api/websites/[websiteId]/events/stats/route.ts index 6d0a04602..fceb97cbd 100644 --- a/src/app/api/websites/[websiteId]/events/stats/route.ts +++ b/src/app/api/websites/[websiteId]/events/stats/route.ts @@ -1,3 +1,4 @@ +import { getCompareDate } from '@/lib/date'; import { getQueryFilters, parseRequest } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; import { filterParams, withDateRange } from '@/lib/schema'; @@ -28,5 +29,17 @@ export async function GET( const data = await getWebsiteEventStats(websiteId, filters); - return json({ data }); + const { startDate, endDate } = getCompareDate( + filters.compare ?? 'prev', + filters.startDate, + filters.endDate, + ); + + const comparison = await getWebsiteEventStats(websiteId, { + ...filters, + startDate, + endDate, + }); + + return json({ data: { ...data, comparison } }); } diff --git a/src/components/hooks/queries/useEventStatsQuery.ts b/src/components/hooks/queries/useEventStatsQuery.ts index 44316ca5f..b3ca60eaa 100644 --- a/src/components/hooks/queries/useEventStatsQuery.ts +++ b/src/components/hooks/queries/useEventStatsQuery.ts @@ -8,6 +8,12 @@ export interface EventStatsData { visitors: number; visits: number; uniqueEvents: number; + comparison: { + events: number; + visitors: number; + visits: number; + uniqueEvents: number; + }; } type EventStatsApiResponse = { From 8530329e141f60a71bcbe86a94a46e9644de0473 Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Wed, 18 Feb 2026 09:23:27 -0800 Subject: [PATCH 05/22] deprecate @umami/redis-client, add redis lib --- package.json | 2 +- pnpm-lock.yaml | 18 ++------ src/lib/redis.ts | 108 +++++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 109 insertions(+), 19 deletions(-) diff --git a/package.json b/package.json index 13a818111..89715dd5b 100644 --- a/package.json +++ b/package.json @@ -67,7 +67,6 @@ "@svgr/cli": "^8.1.0", "@tanstack/react-query": "^5.90.21", "@umami/react-zen": "^0.245.0", - "@umami/redis-client": "^0.30.0", "bcryptjs": "^3.0.2", "chalk": "^5.6.2", "chart.js": "^4.5.1", @@ -110,6 +109,7 @@ "react-simple-maps": "^2.3.0", "react-use-measure": "^2.0.4", "react-window": "^1.8.6", + "redis": "^4.5.1", "request-ip": "^3.3.0", "semver": "^7.7.4", "serialize-error": "^12.0.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 77edaf4dd..2968b7535 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -44,9 +44,6 @@ importers: '@umami/react-zen': specifier: ^0.245.0 version: 0.245.0(@types/react@19.2.14)(immer@10.2.0)(react-aria-components@1.14.0(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(tailwindcss@4.1.18)(use-sync-external-store@1.6.0(react@19.2.4)) - '@umami/redis-client': - specifier: ^0.30.0 - version: 0.30.0 bcryptjs: specifier: ^3.0.2 version: 3.0.3 @@ -173,6 +170,9 @@ importers: react-window: specifier: ^1.8.6 version: 1.8.11(react-dom@19.2.4(react@19.2.4))(react@19.2.4) + redis: + specifier: ^4.5.1 + version: 4.7.1 request-ip: specifier: ^3.3.0 version: 3.3.0 @@ -328,8 +328,6 @@ importers: specifier: ^5.9.3 version: 5.9.3 - dist: {} - packages: '@ampproject/remapping@2.3.0': @@ -2965,9 +2963,6 @@ packages: react-aria-components: ^1.0.0 react-dom: ^18.0.0 || ^19.0.0 - '@umami/redis-client@0.30.0': - resolution: {integrity: sha512-pqeMPdEFMH+9GDpiQd5MdRdTppif4vPl/sp8Y9hPY277g/UFlJAbCUJluESmZRBHjFdXtBPtLzQkxjvdjlRzuQ==} - acorn-walk@8.3.4: resolution: {integrity: sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==} engines: {node: '>=0.4.0'} @@ -10062,13 +10057,6 @@ snapshots: - tailwindcss - use-sync-external-store - '@umami/redis-client@0.30.0': - dependencies: - debug: 4.4.3(supports-color@8.1.1) - redis: 4.7.1 - transitivePeerDependencies: - - supports-color - acorn-walk@8.3.4: dependencies: acorn: 8.15.0 diff --git a/src/lib/redis.ts b/src/lib/redis.ts index edde3d653..71a95a5ef 100644 --- a/src/lib/redis.ts +++ b/src/lib/redis.ts @@ -1,10 +1,112 @@ -import { UmamiRedisClient } from '@umami/redis-client'; +import debug from 'debug'; +import { createClient, type RedisClientType } from 'redis'; + +const log = debug('umami:redis-client'); + +export const DELETED = '__DELETED__'; +export const DEFAULT_TTL = 3600; + +const logError = (err: unknown) => log(err); + +class UmamiRedisClient { + url: string; + client: RedisClientType; + isConnected: boolean; + + constructor(url: string) { + const client = createClient({ url }).on('error', logError); + + this.url = url; + this.client = client as RedisClientType; + this.isConnected = false; + } + + async connect() { + if (!this.isConnected) { + this.isConnected = true; + + await this.client.connect(); + + log('Redis connected'); + } + } + + async get(key: string) { + await this.connect(); + + const data = await this.client.get(key); + + try { + return JSON.parse(data as string); + } catch { + return null; + } + } + + async set(key: string, value: any, time?: number) { + await this.connect(); + + const ttl = time && time > 0 ? time : DEFAULT_TTL; + + return this.client.set(key, JSON.stringify(value), { EX: ttl }); + } + + async del(key: string) { + await this.connect(); + + return this.client.del(key); + } + + async incr(key: string) { + await this.connect(); + + return this.client.incr(key); + } + + async expire(key: string, seconds: number) { + await this.connect(); + + return this.client.expire(key, seconds); + } + + async rateLimit(key: string, limit: number, seconds: number): Promise { + await this.connect(); + + const res = await this.client.incr(key); + + if (res === 1) { + await this.client.expire(key, seconds); + } + + return res >= limit; + } + + async fetch(key: string, query: () => Promise, time?: number) { + const result = await this.get(key); + + if (result === DELETED) return null; + + if (!result && query) { + const data = await query(); + if (data) { + await this.set(key, data, time); + } + return data; + } + + return result; + } + + async remove(key: string, soft = false) { + return soft ? this.set(key, DELETED) : this.del(key); + } +} const REDIS = 'redis'; const enabled = !!process.env.REDIS_URL; function getClient() { - const redis = new UmamiRedisClient({ url: process.env.REDIS_URL }); + const redis = new UmamiRedisClient(process.env.REDIS_URL); if (process.env.NODE_ENV !== 'production') { globalThis[REDIS] = redis; @@ -13,6 +115,6 @@ function getClient() { return redis; } -const client = globalThis[REDIS] || getClient(); +const client: UmamiRedisClient = globalThis[REDIS] || getClient(); export default { client, enabled }; From 3d8d5a7293329a3db62bc1774b464ad94c85d955 Mon Sep 17 00:00:00 2001 From: juanisidoro Date: Fri, 13 Feb 2026 08:39:05 +0100 Subject: [PATCH 06/22] fix: handle null referrer in pixel tracking route request.headers.get("referer") returns null when the header is absent (e.g. email clients). The Zod schema uses .optional() which accepts undefined but rejects null, causing silent validation failure and pixel events not being recorded. Fixes #4028 --- src/app/(collect)/p/[slug]/route.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/(collect)/p/[slug]/route.ts b/src/app/(collect)/p/[slug]/route.ts index 79d6faa5c..b1864d017 100644 --- a/src/app/(collect)/p/[slug]/route.ts +++ b/src/app/(collect)/p/[slug]/route.ts @@ -47,7 +47,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ slug payload: { pixel: pixel.id, url: request.url, - referrer: request.headers.get('referer'), + referrer: request.headers.get("referer") || undefined, }, }; From c730442e5c72458c480d26817c76bdadf88a5a85 Mon Sep 17 00:00:00 2001 From: juanisidoro Date: Fri, 13 Feb 2026 09:23:15 +0100 Subject: [PATCH 07/22] fix: apply same null referrer fix to link tracking route The same bug exists in the link route (q/[slug]) where request.headers.get("referer") returns null for requests without a Referer header, causing silent Zod validation failure. --- src/app/(collect)/q/[slug]/route.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/(collect)/q/[slug]/route.ts b/src/app/(collect)/q/[slug]/route.ts index 24089bdb2..aa9c26f3f 100644 --- a/src/app/(collect)/q/[slug]/route.ts +++ b/src/app/(collect)/q/[slug]/route.ts @@ -45,7 +45,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ slug payload: { link: link.id, url: request.url, - referrer: request.headers.get('referer'), + referrer: request.headers.get("referer") || undefined, }, }; From 0505ef137853d7d53499865582de0197de8dac32 Mon Sep 17 00:00:00 2001 From: Yash Date: Thu, 19 Feb 2026 23:44:24 +0530 Subject: [PATCH 08/22] feat: introduce WebsiteDateFilter for date range selection and DataGrid for paginated data display. --- src/components/common/DataGrid.tsx | 2 +- src/components/input/WebsiteDateFilter.tsx | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/components/common/DataGrid.tsx b/src/components/common/DataGrid.tsx index 7e07b8dcd..7169a278f 100644 --- a/src/components/common/DataGrid.tsx +++ b/src/components/common/DataGrid.tsx @@ -56,7 +56,7 @@ export function DataGrid({ (page: number) => { router.push(updateParams({ search, page })); }, - [search], + [search, updateParams], ); const child = data ? (typeof children === 'function' ? children(data) : children) : null; diff --git a/src/components/input/WebsiteDateFilter.tsx b/src/components/input/WebsiteDateFilter.tsx index 18b4f13be..f5da8c8e2 100644 --- a/src/components/input/WebsiteDateFilter.tsx +++ b/src/components/input/WebsiteDateFilter.tsx @@ -38,10 +38,11 @@ export function WebsiteDateFilter({ updateParams({ date: `${getDateRangeValue(websiteDateRange.startDate, websiteDateRange.endDate)}:all`, offset: undefined, + page: 1, }), ); } else { - router.push(updateParams({ date, offset: undefined })); + router.push(updateParams({ date, offset: undefined, page: 1 })); } }; From c84c73b7a71bfd8abd3e6dfba95286a0d879afa9 Mon Sep 17 00:00:00 2001 From: Yash Date: Fri, 20 Feb 2026 00:01:38 +0530 Subject: [PATCH 09/22] feat: Add `useNavigation` hook for managing URL parameters and navigation. --- src/components/hooks/useNavigation.ts | 35 +++++++++++++++++---------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/src/components/hooks/useNavigation.ts b/src/components/hooks/useNavigation.ts index 0a18ac7b2..278cd57f2 100644 --- a/src/components/hooks/useNavigation.ts +++ b/src/components/hooks/useNavigation.ts @@ -1,5 +1,5 @@ import { usePathname, useRouter, useSearchParams } from 'next/navigation'; -import { useEffect, useState } from 'react'; +import { useCallback, useEffect, useState } from 'react'; import { buildPath } from '@/lib/url'; export function useNavigation() { @@ -10,20 +10,29 @@ export function useNavigation() { const [, websiteId] = pathname.match(/\/websites\/([a-f0-9-]+)/) || []; const [queryParams, setQueryParams] = useState(Object.fromEntries(searchParams)); - const updateParams = (params?: Record) => { - return buildPath(pathname, { ...queryParams, ...params }); - }; + const updateParams = useCallback( + (params?: Record) => { + return buildPath(pathname, { ...queryParams, ...params }); + }, + [pathname, queryParams], + ); - const replaceParams = (params?: Record) => { - return buildPath(pathname, params); - }; + const replaceParams = useCallback( + (params?: Record) => { + return buildPath(pathname, params); + }, + [pathname], + ); - const renderUrl = (path: string, params?: Record | false) => { - return buildPath( - teamId ? `/teams/${teamId}${path}` : path, - params === false ? {} : { ...queryParams, ...params }, - ); - }; + const renderUrl = useCallback( + (path: string, params?: Record | false) => { + return buildPath( + teamId ? `/teams/${teamId}${path}` : path, + params === false ? {} : { ...queryParams, ...params }, + ); + }, + [pathname, teamId, queryParams], + ); useEffect(() => { setQueryParams(Object.fromEntries(searchParams)); From cafc24e1d82bdae1d3a4018538ab5f3290f11ebf Mon Sep 17 00:00:00 2001 From: Yash Date: Fri, 20 Feb 2026 00:05:40 +0530 Subject: [PATCH 10/22] Update src/components/hooks/useNavigation.ts Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> --- src/components/hooks/useNavigation.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/hooks/useNavigation.ts b/src/components/hooks/useNavigation.ts index 278cd57f2..bf1f81be2 100644 --- a/src/components/hooks/useNavigation.ts +++ b/src/components/hooks/useNavigation.ts @@ -31,7 +31,7 @@ export function useNavigation() { params === false ? {} : { ...queryParams, ...params }, ); }, - [pathname, teamId, queryParams], + [teamId, queryParams], ); useEffect(() => { From 67626652f96f02af474662098a40988f4370b15b Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Fri, 20 Feb 2026 12:32:02 -0800 Subject: [PATCH 11/22] fix mobile view for admin screens and nav. update equals and not equals filter to be multiselect. --- src/app/(main)/admin/AdminNav.tsx | 38 +++++++--- .../(main)/admin/teams/AdminTeamsTable.tsx | 3 +- src/app/(main)/admin/users/UsersTable.tsx | 3 +- .../admin/websites/AdminWebsitesTable.tsx | 4 +- src/app/login/LoginForm.tsx | 2 +- src/components/common/FilterRecord.tsx | 55 +++++++++----- src/components/common/MultiSelect.tsx | 71 +++++++++++++++++++ src/components/input/FilterBar.tsx | 7 +- src/lib/clickhouse.ts | 16 +++-- src/lib/params.ts | 17 ++++- src/lib/prisma.ts | 18 +++-- src/lib/types.ts | 2 +- 12 files changed, 188 insertions(+), 48 deletions(-) create mode 100644 src/components/common/MultiSelect.tsx diff --git a/src/app/(main)/admin/AdminNav.tsx b/src/app/(main)/admin/AdminNav.tsx index aa1cbe884..edcfb4c62 100644 --- a/src/app/(main)/admin/AdminNav.tsx +++ b/src/app/(main)/admin/AdminNav.tsx @@ -1,10 +1,13 @@ +import { Column, Focusable, Row, Tooltip, TooltipTrigger } from '@umami/react-zen'; +import Link from 'next/link'; +import { IconLabel } from '@/components/common/IconLabel'; import { NavMenu } from '@/components/common/NavMenu'; import { useMessages, useNavigation } from '@/components/hooks'; -import { Globe, User, Users } from '@/components/icons'; +import { ArrowLeft, Globe, User, Users } from '@/components/icons'; export function AdminNav({ onItemClick }: { onItemClick?: () => void }) { const { t, labels } = useMessages(); - const { pathname } = useNavigation(); + const { pathname, renderUrl } = useNavigation(); const items = [ { @@ -37,12 +40,29 @@ export function AdminNav({ onItemClick }: { onItemClick?: () => void }) { ?.find(({ path }) => path && pathname.startsWith(path))?.id; return ( - + + + + + + } label={t(labels.back)} padding /> + + + {t(labels.back)} + + + + ); } diff --git a/src/app/(main)/admin/teams/AdminTeamsTable.tsx b/src/app/(main)/admin/teams/AdminTeamsTable.tsx index 2d5243b99..f948aba96 100644 --- a/src/app/(main)/admin/teams/AdminTeamsTable.tsx +++ b/src/app/(main)/admin/teams/AdminTeamsTable.tsx @@ -10,6 +10,7 @@ import { TeamDeleteForm } from '../../teams/[teamId]/TeamDeleteForm'; export function AdminTeamsTable({ data = [], showActions = true, + ...props }: { data: any[]; showActions?: boolean; @@ -19,7 +20,7 @@ export function AdminTeamsTable({ return ( <> - + {(row: any) => {row.name}} diff --git a/src/app/(main)/admin/users/UsersTable.tsx b/src/app/(main)/admin/users/UsersTable.tsx index 16a5b9084..f337cc85f 100644 --- a/src/app/(main)/admin/users/UsersTable.tsx +++ b/src/app/(main)/admin/users/UsersTable.tsx @@ -11,6 +11,7 @@ import { UserDeleteForm } from './UserDeleteForm'; export function UsersTable({ data = [], showActions = true, + ...props }: { data: any[]; showActions?: boolean; @@ -20,7 +21,7 @@ export function UsersTable({ return ( <> - + {(row: any) => {row.username}} diff --git a/src/app/(main)/admin/websites/AdminWebsitesTable.tsx b/src/app/(main)/admin/websites/AdminWebsitesTable.tsx index def6dd9ff..062fe2774 100644 --- a/src/app/(main)/admin/websites/AdminWebsitesTable.tsx +++ b/src/app/(main)/admin/websites/AdminWebsitesTable.tsx @@ -7,13 +7,13 @@ import { useMessages } from '@/components/hooks'; import { Edit, Trash, Users } from '@/components/icons'; import { MenuButton } from '@/components/input/MenuButton'; -export function AdminWebsitesTable({ data = [] }: { data: any[] }) { +export function AdminWebsitesTable({ data = [], ...props }: { data: any[] }) { const { t, labels } = useMessages(); const [deleteWebsite, setDeleteWebsite] = useState(null); return ( <> - + {(row: any) => ( diff --git a/src/app/login/LoginForm.tsx b/src/app/login/LoginForm.tsx index 936a30e77..23101b947 100644 --- a/src/app/login/LoginForm.tsx +++ b/src/app/login/LoginForm.tsx @@ -36,7 +36,7 @@ export function LoginForm() { umami -
+ void; onRemove?: (name: string) => void; onChange?: (name: string, value: string) => void; @@ -31,7 +42,8 @@ export function FilterRecord({ onChange, }: FilterRecordProps) { const { fields, operators } = useFilters(); - const [selected, setSelected] = useState(value); + const initValues = Array.isArray(value) ? value : value ? value.split(',') : []; + const [selected, setSelected] = useState(initValues); const [search, setSearch] = useState(''); const { formatValue } = useFormat(); const { data, isLoading } = useWebsiteValuesQuery({ @@ -53,10 +65,15 @@ export function FilterRecord({ }; const handleSelectValue = (value: string) => { - setSelected(value); + setSelected([value]); onChange?.(name, value); }; + const handleMultiSelectValue = (values: string[]) => { + setSelected(values); + onChange?.(name, values.join(',')); + }; + return ( @@ -72,26 +89,30 @@ export function FilterRecord({ ))} {isSearch && ( - + )} {!isSearch && ( - + {items.map(({ value }) => ( + + {formatValue(value, type)} + + ))} + )} diff --git a/src/components/common/MultiSelect.tsx b/src/components/common/MultiSelect.tsx new file mode 100644 index 000000000..21782d7ae --- /dev/null +++ b/src/components/common/MultiSelect.tsx @@ -0,0 +1,71 @@ +import { Button, Column, Icon, List, MenuTrigger, Popover, SearchField } from '@umami/react-zen'; +import type { ReactNode } from 'react'; +import { ChevronRight } from '@/components/icons'; + +interface MultiSelectProps { + value?: string[]; + onChange?: (values: string[]) => void; + searchValue?: string; + onSearch?: (value: string) => void; + placeholder?: string; + allowSearch?: boolean; + renderEmptyState?: () => ReactNode; + renderValue?: (values: string[]) => ReactNode; + children: ReactNode; +} + +export function MultiSelect({ + value = [], + onChange, + searchValue, + onSearch, + placeholder = 'Select an item', + allowSearch, + renderEmptyState, + renderValue, + children, +}: MultiSelectProps) { + const displayValue = renderValue + ? renderValue(value) + : value.length > 0 + ? value.join(', ') + : null; + + return ( + + + + + {allowSearch && } + + {children} + + + + + ); +} diff --git a/src/components/input/FilterBar.tsx b/src/components/input/FilterBar.tsx index d53c45676..0dca00b26 100644 --- a/src/components/input/FilterBar.tsx +++ b/src/components/input/FilterBar.tsx @@ -79,7 +79,12 @@ export function FilterBar({ websiteId }: { websiteId: string }) { )} {filters.map(filter => { const { name, label, operator, value } = filter; - const paramValue = isSearchOperator(operator) ? value : formatValue(value, name); + const paramValue = isSearchOperator(operator) + ? value + : String(value) + .split(',') + .map(v => formatValue(v, name)) + .join(', '); return ( 0`; case OPERATORS.doesNotContain: @@ -173,10 +173,14 @@ function getDateQuery(filters: Record) { function getQueryParams(filters: Record) { return { ...filters, - ...filtersObjectToArray(filters).reduce((obj, { name, value }) => { - if (name && value !== undefined) { - obj[name] = value; - } + ...filtersObjectToArray(filters).reduce((obj, { name, column, operator, value }) => { + if (!column || !name || value === undefined) return obj; + + obj[name] = ([OPERATORS.equals, OPERATORS.notEquals] as string[]).includes(operator) + ? Array.isArray(value) + ? value + : [value] + : value; return obj; }, {}), diff --git a/src/lib/params.ts b/src/lib/params.ts index ab2d58663..d7599216a 100644 --- a/src/lib/params.ts +++ b/src/lib/params.ts @@ -9,10 +9,21 @@ export function parseFilterValue(param: any) { const [, operator, value] = param.match(regex) || []; - return { operator: operator || OPERATORS.equals, value: value || param }; + const resolvedOperator = operator || OPERATORS.equals; + const resolvedValue = value ?? param; + + if (resolvedOperator === OPERATORS.equals || resolvedOperator === OPERATORS.notEquals) { + return { operator: resolvedOperator, value: resolvedValue.split(',') }; + } + + return { operator: resolvedOperator, value: resolvedValue }; } - return { operator: OPERATORS.equals, value: param }; + if (Array.isArray(param)) { + return { operator: OPERATORS.equals, value: param }; + } + + return { operator: OPERATORS.equals, value: [param] }; } export function isEqualsOperator(operator: any) { @@ -55,7 +66,7 @@ export function filtersArrayToObject(filters: Filter[]) { return filters.reduce((obj, filter: Filter) => { const { name, operator, value } = filter; - obj[name] = `${operator}.${value}`; + obj[name] = `${operator}.${Array.isArray(value) ? value.join(',') : value}`; return obj; }, {}); diff --git a/src/lib/prisma.ts b/src/lib/prisma.ts index 41e42fbcc..1c9e9c703 100644 --- a/src/lib/prisma.ts +++ b/src/lib/prisma.ts @@ -82,9 +82,9 @@ function mapFilter(column: string, operator: string, name: string, type: string switch (operator) { case OPERATORS.equals: - return `${table}.${column} = ${value}`; + return `${table}.${column} = ANY(${value})`; case OPERATORS.notEquals: - return `${table}.${column} != ${value}`; + return `${table}.${column} != ALL(${value})`; case OPERATORS.contains: return `${table}.${column} ilike ${value}`; case OPERATORS.doesNotContain: @@ -177,10 +177,16 @@ function getDateQuery(filters: Record) { function getQueryParams(filters: Record) { return { ...filters, - ...filtersObjectToArray(filters).reduce((obj, { name, operator, value }) => { - obj[name] = ([OPERATORS.contains, OPERATORS.doesNotContain] as Operator[]).includes(operator) - ? `%${value}%` - : value; + ...filtersObjectToArray(filters).reduce((obj, { name, column, operator, value }) => { + if (!column) return obj; + + if (([OPERATORS.contains, OPERATORS.doesNotContain] as Operator[]).includes(operator)) { + obj[name] = `%${value}%`; + } else if (([OPERATORS.equals, OPERATORS.notEquals] as Operator[]).includes(operator)) { + obj[name] = Array.isArray(value) ? value : [value]; + } else { + obj[name] = value; + } return obj; }, {}), diff --git a/src/lib/types.ts b/src/lib/types.ts index fd8f1e42b..c089e2303 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -27,7 +27,7 @@ export interface Auth { export interface Filter { name: string; operator: Operator; - value: string; + value: string | string[]; type?: string; column?: string; prefix?: string; From f2cf0715235faef6c6d372c7987eee0867cc92ca Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Fri, 20 Feb 2026 13:43:16 -0800 Subject: [PATCH 12/22] add regex operators --- public/intl/messages/ar-SA.json | 2 ++ public/intl/messages/be-BY.json | 2 ++ public/intl/messages/bg-BG.json | 2 ++ public/intl/messages/bn-BD.json | 2 ++ public/intl/messages/bs-BA.json | 2 ++ public/intl/messages/ca-ES.json | 2 ++ public/intl/messages/cs-CZ.json | 2 ++ public/intl/messages/da-DK.json | 2 ++ public/intl/messages/de-CH.json | 2 ++ public/intl/messages/de-DE.json | 2 ++ public/intl/messages/el-GR.json | 2 ++ public/intl/messages/en-GB.json | 2 ++ public/intl/messages/en-US.json | 2 ++ public/intl/messages/es-ES.json | 2 ++ public/intl/messages/fa-IR.json | 2 ++ public/intl/messages/fi-FI.json | 2 ++ public/intl/messages/fo-FO.json | 2 ++ public/intl/messages/fr-FR.json | 2 ++ public/intl/messages/ga-ES.json | 2 ++ public/intl/messages/he-IL.json | 2 ++ public/intl/messages/hi-IN.json | 2 ++ public/intl/messages/hr-HR.json | 2 ++ public/intl/messages/hu-HU.json | 2 ++ public/intl/messages/id-ID.json | 2 ++ public/intl/messages/it-IT.json | 2 ++ public/intl/messages/ja-JP.json | 2 ++ public/intl/messages/km-KH.json | 2 ++ public/intl/messages/ko-KR.json | 2 ++ public/intl/messages/lt-LT.json | 2 ++ public/intl/messages/mn-MN.json | 2 ++ public/intl/messages/ms-MY.json | 2 ++ public/intl/messages/my-MM.json | 2 ++ public/intl/messages/nb-NO.json | 2 ++ public/intl/messages/nl-NL.json | 2 ++ public/intl/messages/pl-PL.json | 2 ++ public/intl/messages/pt-BR.json | 2 ++ public/intl/messages/pt-PT.json | 2 ++ public/intl/messages/ro-RO.json | 2 ++ public/intl/messages/ru-RU.json | 2 ++ public/intl/messages/si-LK.json | 2 ++ public/intl/messages/sk-SK.json | 2 ++ public/intl/messages/sl-SI.json | 2 ++ public/intl/messages/sv-SE.json | 2 ++ public/intl/messages/ta-IN.json | 2 ++ public/intl/messages/th-TH.json | 2 ++ public/intl/messages/tr-TR.json | 2 ++ public/intl/messages/uk-UA.json | 2 ++ public/intl/messages/ur-PK.json | 2 ++ public/intl/messages/uz-UZ.json | 2 ++ public/intl/messages/vi-VN.json | 2 ++ public/intl/messages/zh-CN.json | 2 ++ public/intl/messages/zh-TW.json | 2 ++ src/components/hooks/useFilters.ts | 13 ++++++++++++- src/components/messages.ts | 2 ++ src/lib/clickhouse.ts | 4 ++++ src/lib/constants.ts | 2 ++ src/lib/params.ts | 7 ++++++- src/lib/prisma.ts | 4 ++++ src/lib/schema.ts | 2 ++ 59 files changed, 136 insertions(+), 2 deletions(-) diff --git a/public/intl/messages/ar-SA.json b/public/intl/messages/ar-SA.json index 4f0e7897a..98f937fed 100644 --- a/public/intl/messages/ar-SA.json +++ b/public/intl/messages/ar-SA.json @@ -51,6 +51,8 @@ "confirm": "تأكيد", "confirm-password": "تأكيد كلمة المرور", "contains": "يحتوي على", + "regex-match": "يطابق التعبير النمطي", + "regex-not-match": "لا يطابق التعبير النمطي", "content": "المحتوى", "continue": "تابع", "conversion": "تحويل", diff --git a/public/intl/messages/be-BY.json b/public/intl/messages/be-BY.json index a2ef2a37c..8cbdd1046 100644 --- a/public/intl/messages/be-BY.json +++ b/public/intl/messages/be-BY.json @@ -51,6 +51,8 @@ "confirm": "Падцвердзіць", "confirm-password": "Падцвердзіць пароль", "contains": "Уключае", + "regex-match": "Адпавядае рэгулярнаму выразу", + "regex-not-match": "Не адпавядае рэгулярнаму выразу", "content": "Змест", "continue": "Працягнуць", "conversion": "Канверсія", diff --git a/public/intl/messages/bg-BG.json b/public/intl/messages/bg-BG.json index e3d7cff87..2edf2ae76 100644 --- a/public/intl/messages/bg-BG.json +++ b/public/intl/messages/bg-BG.json @@ -51,6 +51,8 @@ "confirm": "Потвърди", "confirm-password": "Потвърди парола", "contains": "Съдържа", + "regex-match": "Съвпада с регулярен израз", + "regex-not-match": "Не съвпада с регулярен израз", "content": "Съдържание", "continue": "Продължи", "conversion": "Конверсия", diff --git a/public/intl/messages/bn-BD.json b/public/intl/messages/bn-BD.json index 03a79d301..fcc263cb8 100644 --- a/public/intl/messages/bn-BD.json +++ b/public/intl/messages/bn-BD.json @@ -51,6 +51,8 @@ "confirm": "নিশ্চিত করুন", "confirm-password": "পাসওয়ার্ড নিশ্চিত করুন", "contains": "রয়েছে", + "regex-match": "রেজেক্সের সাথে মেলে", + "regex-not-match": "রেজেক্সের সাথে মেলে না", "content": "বিষয়বস্তু", "continue": "পরবর্তিতে", "conversion": "রূপান্তর", diff --git a/public/intl/messages/bs-BA.json b/public/intl/messages/bs-BA.json index 1fc18f431..eb55ff438 100644 --- a/public/intl/messages/bs-BA.json +++ b/public/intl/messages/bs-BA.json @@ -51,6 +51,8 @@ "confirm": "Potvrdi", "confirm-password": "Potvrdi šifru", "contains": "Sadrži", + "regex-match": "Odgovara regularnom izrazu", + "regex-not-match": "Ne odgovara regularnom izrazu", "content": "Sadržaj", "continue": "Nastavi", "conversion": "Konverzija", diff --git a/public/intl/messages/ca-ES.json b/public/intl/messages/ca-ES.json index 0a6984c1a..30b66451c 100644 --- a/public/intl/messages/ca-ES.json +++ b/public/intl/messages/ca-ES.json @@ -51,6 +51,8 @@ "confirm": "Confirmar", "confirm-password": "Confirma la contrasenya", "contains": "Conté", + "regex-match": "Coincideix amb l'expressió regular", + "regex-not-match": "No coincideix amb l'expressió regular", "content": "Contingut", "continue": "Continuar", "conversion": "Conversió", diff --git a/public/intl/messages/cs-CZ.json b/public/intl/messages/cs-CZ.json index 43903a152..eacaee4ac 100644 --- a/public/intl/messages/cs-CZ.json +++ b/public/intl/messages/cs-CZ.json @@ -51,6 +51,8 @@ "confirm": "Potvrdit", "confirm-password": "Potvrdit heslo", "contains": "Obsahuje", + "regex-match": "Odpovídá regulárnímu výrazu", + "regex-not-match": "Neodpovídá regulárnímu výrazu", "content": "Obsah", "continue": "Pokračovat", "conversion": "Konverze", diff --git a/public/intl/messages/da-DK.json b/public/intl/messages/da-DK.json index 0c3d1006c..16e16128d 100644 --- a/public/intl/messages/da-DK.json +++ b/public/intl/messages/da-DK.json @@ -51,6 +51,8 @@ "confirm": "Bekræft", "confirm-password": "Godkendt adgangskode", "contains": "Indeholder", + "regex-match": "Matcher regulært udtryk", + "regex-not-match": "Matcher ikke regulært udtryk", "content": "Indhold", "continue": "Fortsæt", "conversion": "Konvertering", diff --git a/public/intl/messages/de-CH.json b/public/intl/messages/de-CH.json index 6b3b4af59..6125b2386 100644 --- a/public/intl/messages/de-CH.json +++ b/public/intl/messages/de-CH.json @@ -51,6 +51,8 @@ "confirm": "Bestätige", "confirm-password": "Passwort widerhole", "contains": "Enthaltet", + "regex-match": "Entspricht regulärem Ausdruck", + "regex-not-match": "Entspricht nicht regulärem Ausdruck", "content": "Inhalt", "continue": "Wiiter", "conversion": "Umwandlig", diff --git a/public/intl/messages/de-DE.json b/public/intl/messages/de-DE.json index 0b313fdf3..c059a1a5c 100644 --- a/public/intl/messages/de-DE.json +++ b/public/intl/messages/de-DE.json @@ -51,6 +51,8 @@ "confirm": "Bestätigen", "confirm-password": "Passwort wiederholen", "contains": "Enthält", + "regex-match": "Entspricht regulärem Ausdruck", + "regex-not-match": "Entspricht nicht regulärem Ausdruck", "content": "Inhalt", "continue": "Weiter", "conversion": "Konversion", diff --git a/public/intl/messages/el-GR.json b/public/intl/messages/el-GR.json index 597bbdded..4a0b36330 100644 --- a/public/intl/messages/el-GR.json +++ b/public/intl/messages/el-GR.json @@ -51,6 +51,8 @@ "confirm": "Επιβεβαίωση", "confirm-password": "Επιβεβαίωση κωδικού", "contains": "Περιέχει", + "regex-match": "Ταιριάζει με κανονική έκφραση", + "regex-not-match": "Δεν ταιριάζει με κανονική έκφραση", "content": "Περιεχόμενο", "continue": "Συνέχεια", "conversion": "Μετατροπή", diff --git a/public/intl/messages/en-GB.json b/public/intl/messages/en-GB.json index 741b5c8c3..33d676e73 100644 --- a/public/intl/messages/en-GB.json +++ b/public/intl/messages/en-GB.json @@ -51,6 +51,8 @@ "confirm": "Confirm", "confirm-password": "Confirm password", "contains": "Contains", + "regex-match": "Matches regex", + "regex-not-match": "Does not match regex", "content": "Content", "continue": "Continue", "conversion": "Conversion", diff --git a/public/intl/messages/en-US.json b/public/intl/messages/en-US.json index 67721ef04..9ff141bd7 100644 --- a/public/intl/messages/en-US.json +++ b/public/intl/messages/en-US.json @@ -51,6 +51,8 @@ "confirm": "Confirm", "confirm-password": "Confirm password", "contains": "Contains", + "regex-match": "Matches regex", + "regex-not-match": "Does not match regex", "content": "Content", "continue": "Continue", "conversion": "Conversion", diff --git a/public/intl/messages/es-ES.json b/public/intl/messages/es-ES.json index 41a3fecfc..856d6977a 100644 --- a/public/intl/messages/es-ES.json +++ b/public/intl/messages/es-ES.json @@ -51,6 +51,8 @@ "confirm": "Confirmar", "confirm-password": "Confirmar contraseña", "contains": "Contiene", + "regex-match": "Coincide con expresión regular", + "regex-not-match": "No coincide con expresión regular", "content": "Contenido", "continue": "Continuar", "conversion": "Conversión", diff --git a/public/intl/messages/fa-IR.json b/public/intl/messages/fa-IR.json index 17be3d950..49ba05391 100644 --- a/public/intl/messages/fa-IR.json +++ b/public/intl/messages/fa-IR.json @@ -51,6 +51,8 @@ "confirm": "تأیید", "confirm-password": "تأیید رمز", "contains": "شامل", + "regex-match": "با عبارت منظم مطابقت دارد", + "regex-not-match": "با عبارت منظم مطابقت ندارد", "content": "محتوا", "continue": "ادامه", "conversion": "تبدیل", diff --git a/public/intl/messages/fi-FI.json b/public/intl/messages/fi-FI.json index 4d86d3cc7..7b802535c 100644 --- a/public/intl/messages/fi-FI.json +++ b/public/intl/messages/fi-FI.json @@ -51,6 +51,8 @@ "confirm": "Vahvista", "confirm-password": "Vahvista salasana", "contains": "Sisältää", + "regex-match": "Vastaa säännöllistä lauseketta", + "regex-not-match": "Ei vastaa säännöllistä lauseketta", "content": "Sisältö", "continue": "Jatka", "conversion": "Konversio", diff --git a/public/intl/messages/fo-FO.json b/public/intl/messages/fo-FO.json index 45674c294..c16804397 100644 --- a/public/intl/messages/fo-FO.json +++ b/public/intl/messages/fo-FO.json @@ -51,6 +51,8 @@ "confirm": "Staðfest", "confirm-password": "Vátta loyniorð", "contains": "Inniheldur", + "regex-match": "Samsvarar við regluligan úttrykk", + "regex-not-match": "Samsvarar ikki við regluligan úttrykk", "content": "Innihald", "continue": "Halt fram", "conversion": "Umvending", diff --git a/public/intl/messages/fr-FR.json b/public/intl/messages/fr-FR.json index 11ca722ff..0954df1f2 100644 --- a/public/intl/messages/fr-FR.json +++ b/public/intl/messages/fr-FR.json @@ -51,6 +51,8 @@ "confirm": "Confirmer", "confirm-password": "Confirmation du mot de passe", "contains": "Contient", + "regex-match": "Correspond à l'expression régulière", + "regex-not-match": "Ne correspond pas à l'expression régulière", "content": "Contenu", "continue": "Continuer", "conversion": "Conversion", diff --git a/public/intl/messages/ga-ES.json b/public/intl/messages/ga-ES.json index 34a818a1e..89630c714 100644 --- a/public/intl/messages/ga-ES.json +++ b/public/intl/messages/ga-ES.json @@ -51,6 +51,8 @@ "confirm": "Confirmar", "confirm-password": "Confirmar contrasinal", "contains": "Contén", + "regex-match": "Meaitseálann sé le slonn rialta", + "regex-not-match": "Ní mheaitseálann sé le slonn rialta", "content": "Contido", "continue": "Continuar", "conversion": "Conversión", diff --git a/public/intl/messages/he-IL.json b/public/intl/messages/he-IL.json index 200412414..62c83c35b 100644 --- a/public/intl/messages/he-IL.json +++ b/public/intl/messages/he-IL.json @@ -51,6 +51,8 @@ "confirm": "אשר", "confirm-password": "אישור סיסמה", "contains": "מכיל", + "regex-match": "תואם ביטוי רגולרי", + "regex-not-match": "לא תואם ביטוי רגולרי", "content": "תוכן", "continue": "המשך", "conversion": "המרה", diff --git a/public/intl/messages/hi-IN.json b/public/intl/messages/hi-IN.json index 06ecbf636..c8ac7df42 100644 --- a/public/intl/messages/hi-IN.json +++ b/public/intl/messages/hi-IN.json @@ -51,6 +51,8 @@ "confirm": "पुष्टि करें", "confirm-password": "पासवर्ड की पुष्टि कीजिये", "contains": "शामिल है", + "regex-match": "रेगेक्स से मेल खाता है", + "regex-not-match": "रेगेक्स से मेल नहीं खाता", "content": "सामग्री", "continue": "जारी रखें", "conversion": "रूपांतरण", diff --git a/public/intl/messages/hr-HR.json b/public/intl/messages/hr-HR.json index f048dfda0..c49a9dcf3 100644 --- a/public/intl/messages/hr-HR.json +++ b/public/intl/messages/hr-HR.json @@ -51,6 +51,8 @@ "confirm": "Potvrdi", "confirm-password": "Potvrdi lozinku", "contains": "Sadrži", + "regex-match": "Odgovara regularnom izrazu", + "regex-not-match": "Ne odgovara regularnom izrazu", "content": "Sadržaj", "continue": "Nastavi", "conversion": "Konverzija", diff --git a/public/intl/messages/hu-HU.json b/public/intl/messages/hu-HU.json index 6673ec421..ce071cc5f 100644 --- a/public/intl/messages/hu-HU.json +++ b/public/intl/messages/hu-HU.json @@ -51,6 +51,8 @@ "confirm": "Megerősít", "confirm-password": "Jelszó megerősítése", "contains": "Tartalmazza", + "regex-match": "Illeszkedik a reguláris kifejezésre", + "regex-not-match": "Nem illeszkedik a reguláris kifejezésre", "content": "Tartalom", "continue": "Folytatás", "conversion": "Konverzió", diff --git a/public/intl/messages/id-ID.json b/public/intl/messages/id-ID.json index f0cb7e003..422bc114b 100644 --- a/public/intl/messages/id-ID.json +++ b/public/intl/messages/id-ID.json @@ -51,6 +51,8 @@ "confirm": "Konfirmasi", "confirm-password": "Konfirmasi kata sandi", "contains": "Mengandung", + "regex-match": "Cocok dengan ekspresi reguler", + "regex-not-match": "Tidak cocok dengan ekspresi reguler", "content": "Konten", "continue": "Lanjutkan", "conversion": "Konversi", diff --git a/public/intl/messages/it-IT.json b/public/intl/messages/it-IT.json index fc403768e..00f83c304 100644 --- a/public/intl/messages/it-IT.json +++ b/public/intl/messages/it-IT.json @@ -51,6 +51,8 @@ "confirm": "Conferma", "confirm-password": "Conferma password", "contains": "Contiene", + "regex-match": "Corrisponde all'espressione regolare", + "regex-not-match": "Non corrisponde all'espressione regolare", "content": "Contenuto", "continue": "Continua", "conversion": "Conversione", diff --git a/public/intl/messages/ja-JP.json b/public/intl/messages/ja-JP.json index 900bb0f6c..2c2347ffd 100644 --- a/public/intl/messages/ja-JP.json +++ b/public/intl/messages/ja-JP.json @@ -51,6 +51,8 @@ "confirm": "確認", "confirm-password": "パスワード(確認)", "contains": "コンテンツ", + "regex-match": "正規表現に一致", + "regex-not-match": "正規表現に一致しない", "content": "コンテンツ", "continue": "続ける", "conversion": "コンバージョン", diff --git a/public/intl/messages/km-KH.json b/public/intl/messages/km-KH.json index defab4f86..a8bcb040d 100644 --- a/public/intl/messages/km-KH.json +++ b/public/intl/messages/km-KH.json @@ -51,6 +51,8 @@ "confirm": "បញ្ជាក់", "confirm-password": "បញ្ជាក់ពាក្យសម្ងាត់", "contains": "មាន", + "regex-match": "ត្រូវនឹងកន្សោមធម្មតា", + "regex-not-match": "មិនត្រូវនឹងកន្សោមធម្មតា", "content": "មាតិកា", "continue": "បន្ត", "conversion": "ការបម្លែង", diff --git a/public/intl/messages/ko-KR.json b/public/intl/messages/ko-KR.json index 28348f161..45ce769a8 100644 --- a/public/intl/messages/ko-KR.json +++ b/public/intl/messages/ko-KR.json @@ -51,6 +51,8 @@ "confirm": "확인", "confirm-password": "비밀번호 확인", "contains": "포함", + "regex-match": "정규식과 일치", + "regex-not-match": "정규식과 일치하지 않음", "content": "콘텐츠", "continue": "계속", "conversion": "전환", diff --git a/public/intl/messages/lt-LT.json b/public/intl/messages/lt-LT.json index 0dd0eb24a..9ff1d6a33 100644 --- a/public/intl/messages/lt-LT.json +++ b/public/intl/messages/lt-LT.json @@ -51,6 +51,8 @@ "confirm": "Patvirtinti", "confirm-password": "Patvirtinti slaptažodį", "contains": "Turi", + "regex-match": "Atitinka reguliariąją išraišką", + "regex-not-match": "Neatitinka reguliariosios išraiškos", "content": "Turinys", "continue": "Tęsti", "conversion": "Konversija", diff --git a/public/intl/messages/mn-MN.json b/public/intl/messages/mn-MN.json index 5ebc08c2e..a8e270509 100644 --- a/public/intl/messages/mn-MN.json +++ b/public/intl/messages/mn-MN.json @@ -51,6 +51,8 @@ "confirm": "Батлах", "confirm-password": "Шинэ нууц үгээ давтах", "contains": "Агуулах", + "regex-match": "Регекс-тэй таарна", + "regex-not-match": "Регекс-тэй таарахгүй", "content": "Агуулга", "continue": "Үргэлжлүүлэх", "conversion": "Хөрвүүлэлт", diff --git a/public/intl/messages/ms-MY.json b/public/intl/messages/ms-MY.json index e04a39f2d..760224217 100644 --- a/public/intl/messages/ms-MY.json +++ b/public/intl/messages/ms-MY.json @@ -51,6 +51,8 @@ "confirm": "Sahkan", "confirm-password": "Sahkan kata laluan", "contains": "Mengandungi", + "regex-match": "Sepadan dengan ungkapan biasa", + "regex-not-match": "Tidak sepadan dengan ungkapan biasa", "content": "Kandungan", "continue": "Teruskan", "conversion": "Penukaran", diff --git a/public/intl/messages/my-MM.json b/public/intl/messages/my-MM.json index 5e7a149ef..d31ebdb25 100644 --- a/public/intl/messages/my-MM.json +++ b/public/intl/messages/my-MM.json @@ -51,6 +51,8 @@ "confirm": "အတည်ပြုသည်", "confirm-password": "စကားဝှက်အတည်ပြုသည်", "contains": "ပါဝင်သည်", + "regex-match": "Regex နှင့် ကိုက်ညီသည်", + "regex-not-match": "Regex နှင့် မကိုက်ညီပါ", "content": "အကြောင်းအရာ", "continue": "ဆက်သွားမည်", "conversion": "ပြောင်းလဲမှု", diff --git a/public/intl/messages/nb-NO.json b/public/intl/messages/nb-NO.json index 6a70d7acd..c0007cd3d 100644 --- a/public/intl/messages/nb-NO.json +++ b/public/intl/messages/nb-NO.json @@ -51,6 +51,8 @@ "confirm": "Bekreft", "confirm-password": "Godkjenn passord", "contains": "Inneholder", + "regex-match": "Samsvarer med regulært uttrykk", + "regex-not-match": "Samsvarer ikke med regulært uttrykk", "content": "Innhold", "continue": "Fortsett", "conversion": "Konvertering", diff --git a/public/intl/messages/nl-NL.json b/public/intl/messages/nl-NL.json index 8e77a8818..cf56e8b8d 100644 --- a/public/intl/messages/nl-NL.json +++ b/public/intl/messages/nl-NL.json @@ -51,6 +51,8 @@ "confirm": "Bevestigen", "confirm-password": "Wachtwoord bevestigen", "contains": "Bevat", + "regex-match": "Komt overeen met reguliere expressie", + "regex-not-match": "Komt niet overeen met reguliere expressie", "content": "Inhoud", "continue": "Doorgaan", "conversion": "Conversie", diff --git a/public/intl/messages/pl-PL.json b/public/intl/messages/pl-PL.json index 84d6cce9a..1f486cb55 100644 --- a/public/intl/messages/pl-PL.json +++ b/public/intl/messages/pl-PL.json @@ -51,6 +51,8 @@ "confirm": "Potwierdź", "confirm-password": "Potwierdź hasło", "contains": "Zawiera", + "regex-match": "Pasuje do wyrażenia regularnego", + "regex-not-match": "Nie pasuje do wyrażenia regularnego", "content": "Treść", "continue": "Kontynuuj", "conversion": "Konwersja", diff --git a/public/intl/messages/pt-BR.json b/public/intl/messages/pt-BR.json index 338148f66..282981df4 100644 --- a/public/intl/messages/pt-BR.json +++ b/public/intl/messages/pt-BR.json @@ -51,6 +51,8 @@ "confirm": "Confirmar", "confirm-password": "Confirmar senha", "contains": "Contém", + "regex-match": "Corresponde à expressão regular", + "regex-not-match": "Não corresponde à expressão regular", "content": "Conteúdo", "continue": "Continuar", "conversion": "Conversão", diff --git a/public/intl/messages/pt-PT.json b/public/intl/messages/pt-PT.json index eeb02d2fc..907d8e4f2 100644 --- a/public/intl/messages/pt-PT.json +++ b/public/intl/messages/pt-PT.json @@ -51,6 +51,8 @@ "confirm": "Confirmar", "confirm-password": "Confirmar senha", "contains": "Contém", + "regex-match": "Corresponde à expressão regular", + "regex-not-match": "Não corresponde à expressão regular", "content": "Conteúdo", "continue": "Continuar", "conversion": "Conversão", diff --git a/public/intl/messages/ro-RO.json b/public/intl/messages/ro-RO.json index f8a1457a6..b81556524 100644 --- a/public/intl/messages/ro-RO.json +++ b/public/intl/messages/ro-RO.json @@ -51,6 +51,8 @@ "confirm": "Confirmă", "confirm-password": "Confirmare parolă", "contains": "Conține", + "regex-match": "Se potrivește cu expresia regulată", + "regex-not-match": "Nu se potrivește cu expresia regulată", "content": "Conținut", "continue": "Continuă", "conversion": "Conversie", diff --git a/public/intl/messages/ru-RU.json b/public/intl/messages/ru-RU.json index 5c05decc2..10096a5dc 100644 --- a/public/intl/messages/ru-RU.json +++ b/public/intl/messages/ru-RU.json @@ -51,6 +51,8 @@ "confirm": "Подтвердить", "confirm-password": "Подтвердить пароль", "contains": "Содержит", + "regex-match": "Соответствует регулярному выражению", + "regex-not-match": "Не соответствует регулярному выражению", "content": "Контент", "continue": "Продолжить", "conversion": "Конверсия", diff --git a/public/intl/messages/si-LK.json b/public/intl/messages/si-LK.json index 6d38e9d3a..cb2b6163e 100644 --- a/public/intl/messages/si-LK.json +++ b/public/intl/messages/si-LK.json @@ -51,6 +51,8 @@ "confirm": "තහවුරු කරන්න", "confirm-password": "මුරපදය සත්‍යාපනය කරන්න", "contains": "අඩංගු වේ", + "regex-match": "Regex සමඟ ගැලපේ", + "regex-not-match": "Regex සමඟ නොගැලපේ", "content": "අන්තර්ගතය", "continue": "ඉදිරියට", "conversion": "පරිවර්තනය", diff --git a/public/intl/messages/sk-SK.json b/public/intl/messages/sk-SK.json index 517f5b953..f3424a3ee 100644 --- a/public/intl/messages/sk-SK.json +++ b/public/intl/messages/sk-SK.json @@ -51,6 +51,8 @@ "confirm": "Potvrdiť", "confirm-password": "Potvrdiť heslo", "contains": "Obsahuje", + "regex-match": "Zodpovedá regulárnemu výrazu", + "regex-not-match": "Nezodpovedá regulárnemu výrazu", "content": "Obsah", "continue": "Pokračovať", "conversion": "Konverzia", diff --git a/public/intl/messages/sl-SI.json b/public/intl/messages/sl-SI.json index 85e7ee772..34d9d731f 100644 --- a/public/intl/messages/sl-SI.json +++ b/public/intl/messages/sl-SI.json @@ -51,6 +51,8 @@ "confirm": "Potrdi", "confirm-password": "Potrdi geslo", "contains": "Vsebuje", + "regex-match": "Ustreza regularnemu izrazu", + "regex-not-match": "Ne ustreza regularnemu izrazu", "content": "Vsebina", "continue": "Nadaljuj", "conversion": "Konverzija", diff --git a/public/intl/messages/sv-SE.json b/public/intl/messages/sv-SE.json index edcfb8966..a39bbeb0e 100644 --- a/public/intl/messages/sv-SE.json +++ b/public/intl/messages/sv-SE.json @@ -51,6 +51,8 @@ "confirm": "Bekräfta", "confirm-password": "Bekräfta lösenord", "contains": "Innehåller", + "regex-match": "Matchar reguljärt uttryck", + "regex-not-match": "Matchar inte reguljärt uttryck", "content": "Innehåll", "continue": "Fortsätt", "conversion": "Konvertering", diff --git a/public/intl/messages/ta-IN.json b/public/intl/messages/ta-IN.json index 88c062216..9d7fe5b16 100644 --- a/public/intl/messages/ta-IN.json +++ b/public/intl/messages/ta-IN.json @@ -51,6 +51,8 @@ "confirm": "உறுதிப்படுத்து", "confirm-password": "கடவுச்சொல்லை உறுதிப்படுத்தவும்", "contains": "உள்ளடக்கியது", + "regex-match": "Regex உடன் பொருந்துகிறது", + "regex-not-match": "Regex உடன் பொருந்தாது", "content": "உள்ளடக்கம்", "continue": "தொடர்", "conversion": "மாற்றம்", diff --git a/public/intl/messages/th-TH.json b/public/intl/messages/th-TH.json index 901512031..5af2e6713 100644 --- a/public/intl/messages/th-TH.json +++ b/public/intl/messages/th-TH.json @@ -51,6 +51,8 @@ "confirm": "ยืนยัน", "confirm-password": "ยืนยันรหัสผ่าน", "contains": "มี", + "regex-match": "ตรงกับนิพจน์ทั่วไป", + "regex-not-match": "ไม่ตรงกับนิพจน์ทั่วไป", "content": "เนื้อหา", "continue": "ดำเนินต่อ", "conversion": "การแปลง", diff --git a/public/intl/messages/tr-TR.json b/public/intl/messages/tr-TR.json index e176e0208..667da45bf 100644 --- a/public/intl/messages/tr-TR.json +++ b/public/intl/messages/tr-TR.json @@ -51,6 +51,8 @@ "confirm": "Onayla", "confirm-password": "Parolayı onayla", "contains": "İçeriği", + "regex-match": "Düzenli ifadeyle eşleşir", + "regex-not-match": "Düzenli ifadeyle eşleşmez", "content": "İçerik", "continue": "Devam et", "conversion": "Dönüşüm", diff --git a/public/intl/messages/uk-UA.json b/public/intl/messages/uk-UA.json index 88711253d..5d83a9aa2 100644 --- a/public/intl/messages/uk-UA.json +++ b/public/intl/messages/uk-UA.json @@ -51,6 +51,8 @@ "confirm": "Підтвердити", "confirm-password": "Підтвердити пароль", "contains": "Містить", + "regex-match": "Відповідає регулярному виразу", + "regex-not-match": "Не відповідає регулярному виразу", "content": "Вміст", "continue": "Продовжити", "conversion": "Конверсія", diff --git a/public/intl/messages/ur-PK.json b/public/intl/messages/ur-PK.json index 9bb0b13f9..0e03241fc 100644 --- a/public/intl/messages/ur-PK.json +++ b/public/intl/messages/ur-PK.json @@ -51,6 +51,8 @@ "confirm": "تصدیق کریں", "confirm-password": "پاس ورڈ کی تصدیق کریں", "contains": "شامل ہے", + "regex-match": "ریجیکس سے مطابقت رکھتا ہے", + "regex-not-match": "ریجیکس سے مطابقت نہیں رکھتا", "content": "مواد", "continue": "جاری رکھیں", "conversion": "تبدیلی", diff --git a/public/intl/messages/uz-UZ.json b/public/intl/messages/uz-UZ.json index cecaff713..b2b60d5b7 100644 --- a/public/intl/messages/uz-UZ.json +++ b/public/intl/messages/uz-UZ.json @@ -51,6 +51,8 @@ "confirm": "Tasdiqlash", "confirm-password": "Parolni tasdiqlash", "contains": "Oʻz ichiga oladi", + "regex-match": "Muntazam ifodaga mos keladi", + "regex-not-match": "Muntazam ifodaga mos kelmaydi", "content": "Kontent", "continue": "Davom etish", "conversion": "Konversiya", diff --git a/public/intl/messages/vi-VN.json b/public/intl/messages/vi-VN.json index f97601a41..eed6aa8dc 100644 --- a/public/intl/messages/vi-VN.json +++ b/public/intl/messages/vi-VN.json @@ -51,6 +51,8 @@ "confirm": "Xác nhận", "confirm-password": "Xác nhận mật khẩu", "contains": "Chứa", + "regex-match": "Khớp với biểu thức chính quy", + "regex-not-match": "Không khớp với biểu thức chính quy", "content": "Nội dung", "continue": "Tiếp tục", "conversion": "Chuyển đổi", diff --git a/public/intl/messages/zh-CN.json b/public/intl/messages/zh-CN.json index d16f5b858..8f1469a3a 100644 --- a/public/intl/messages/zh-CN.json +++ b/public/intl/messages/zh-CN.json @@ -51,6 +51,8 @@ "confirm": "确认", "confirm-password": "确认密码", "contains": "包含", + "regex-match": "匹配正则表达式", + "regex-not-match": "不匹配正则表达式", "content": "内容", "continue": "继续", "conversion": "转化", diff --git a/public/intl/messages/zh-TW.json b/public/intl/messages/zh-TW.json index 2e555a6d0..57cd293c1 100644 --- a/public/intl/messages/zh-TW.json +++ b/public/intl/messages/zh-TW.json @@ -51,6 +51,8 @@ "confirm": "確認", "confirm-password": "確認密碼", "contains": "包含", + "regex-match": "符合正則表達式", + "regex-not-match": "不符合正則表達式", "content": "內容", "continue": "繼續", "conversion": "轉換", diff --git a/src/components/hooks/useFilters.ts b/src/components/hooks/useFilters.ts index 0dd9a00bb..96397ea4d 100644 --- a/src/components/hooks/useFilters.ts +++ b/src/components/hooks/useFilters.ts @@ -14,6 +14,8 @@ export function useFilters() { { name: 'neq', type: 'string', label: t(labels.isNot) }, { name: 'c', type: 'string', label: t(labels.contains) }, { name: 'dnc', type: 'string', label: t(labels.doesNotContain) }, + { name: 're', type: 'string', label: t(labels.regexMatch) }, + { name: 'nre', type: 'string', label: t(labels.regexNotMatch) }, { name: 'i', type: 'array', label: t(labels.includes) }, { name: 'dni', type: 'array', label: t(labels.doesNotInclude) }, { name: 't', type: 'boolean', label: t(labels.isTrue) }, @@ -36,6 +38,8 @@ export function useFilters() { [OPERATORS.notSet]: t(labels.isNotSet), [OPERATORS.contains]: t(labels.contains), [OPERATORS.doesNotContain]: t(labels.doesNotContain), + [OPERATORS.regex]: t(labels.regexMatch), + [OPERATORS.notRegex]: t(labels.regexNotMatch), [OPERATORS.true]: t(labels.true), [OPERATORS.false]: t(labels.false), [OPERATORS.greaterThan]: t(labels.greaterThan), @@ -47,7 +51,14 @@ export function useFilters() { }; const typeFilters = { - string: [OPERATORS.equals, OPERATORS.notEquals, OPERATORS.contains, OPERATORS.doesNotContain], + string: [ + OPERATORS.equals, + OPERATORS.notEquals, + OPERATORS.contains, + OPERATORS.doesNotContain, + OPERATORS.regex, + OPERATORS.notRegex, + ], array: [OPERATORS.contains, OPERATORS.doesNotContain], boolean: [OPERATORS.true, OPERATORS.false], number: [ diff --git a/src/components/messages.ts b/src/components/messages.ts index b8b4c0161..a0c6f9172 100644 --- a/src/components/messages.ts +++ b/src/components/messages.ts @@ -198,6 +198,8 @@ export const labels: Record = { lessThanEquals: 'label.less-than-equals', contains: 'label.contains', doesNotContain: 'label.does-not-contain', + regexMatch: 'label.regex-match', + regexNotMatch: 'label.regex-not-match', includes: 'label.includes', doesNotInclude: 'label.does-not-include', before: 'label.before', diff --git a/src/lib/clickhouse.ts b/src/lib/clickhouse.ts index 29118a6ba..3620a04ce 100644 --- a/src/lib/clickhouse.ts +++ b/src/lib/clickhouse.ts @@ -82,6 +82,10 @@ function mapFilter(column: string, operator: string, name: string, type: string return `positionCaseInsensitive(${column}, ${value}) > 0`; case OPERATORS.doesNotContain: return `positionCaseInsensitive(${column}, ${value}) = 0`; + case OPERATORS.regex: + return `match(${column}, ${value})`; + case OPERATORS.notRegex: + return `not match(${column}, ${value})`; default: return ''; } diff --git a/src/lib/constants.ts b/src/lib/constants.ts index fb492e03b..8079a2cc8 100644 --- a/src/lib/constants.ts +++ b/src/lib/constants.ts @@ -129,6 +129,8 @@ export const OPERATORS = { notSet: 'ns', contains: 'c', doesNotContain: 'dnc', + regex: 're', + notRegex: 'nre', true: 't', false: 'f', greaterThan: 'gt', diff --git a/src/lib/params.ts b/src/lib/params.ts index d7599216a..bbb52eb3b 100644 --- a/src/lib/params.ts +++ b/src/lib/params.ts @@ -31,7 +31,12 @@ export function isEqualsOperator(operator: any) { } export function isSearchOperator(operator: any) { - return [OPERATORS.contains, OPERATORS.doesNotContain].includes(operator); + return [ + OPERATORS.contains, + OPERATORS.doesNotContain, + OPERATORS.regex, + OPERATORS.notRegex, + ].includes(operator); } export function filtersObjectToArray(filters: QueryFilters, options: QueryOptions = {}): Filter[] { diff --git a/src/lib/prisma.ts b/src/lib/prisma.ts index 1c9e9c703..b8cb82c4d 100644 --- a/src/lib/prisma.ts +++ b/src/lib/prisma.ts @@ -89,6 +89,10 @@ function mapFilter(column: string, operator: string, name: string, type: string return `${table}.${column} ilike ${value}`; case OPERATORS.doesNotContain: return `${table}.${column} not ilike ${value}`; + case OPERATORS.regex: + return `${table}.${column} ~ ${value}`; + case OPERATORS.notRegex: + return `${table}.${column} !~ ${value}`; default: return ''; } diff --git a/src/lib/schema.ts b/src/lib/schema.ts index ef0ce67bb..8693d30bc 100644 --- a/src/lib/schema.ts +++ b/src/lib/schema.ts @@ -143,6 +143,8 @@ export const operatorParam = z.enum([ 'ns', 'c', 'dnc', + 're', + 'nre', 't', 'f', 'gt', From bbf569e8bccec93d819dea622a9c38dc665e7647 Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Fri, 20 Feb 2026 15:03:24 -0800 Subject: [PATCH 13/22] fix cohort queries with new multiselect --- src/lib/clickhouse.ts | 5 ++++- src/lib/prisma.ts | 5 ++++- src/lib/request.ts | 4 ++-- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/lib/clickhouse.ts b/src/lib/clickhouse.ts index 3620a04ce..bb3976c71 100644 --- a/src/lib/clickhouse.ts +++ b/src/lib/clickhouse.ts @@ -178,7 +178,10 @@ function getQueryParams(filters: Record) { return { ...filters, ...filtersObjectToArray(filters).reduce((obj, { name, column, operator, value }) => { - if (!column || !name || value === undefined) return obj; + const resolvedColumn = + column || (name?.startsWith('cohort_') && FILTER_COLUMNS[name.slice('cohort_'.length)]); + + if (!resolvedColumn || !name || value === undefined) return obj; obj[name] = ([OPERATORS.equals, OPERATORS.notEquals] as string[]).includes(operator) ? Array.isArray(value) diff --git a/src/lib/prisma.ts b/src/lib/prisma.ts index b8cb82c4d..3d31fcf9b 100644 --- a/src/lib/prisma.ts +++ b/src/lib/prisma.ts @@ -182,7 +182,10 @@ function getQueryParams(filters: Record) { return { ...filters, ...filtersObjectToArray(filters).reduce((obj, { name, column, operator, value }) => { - if (!column) return obj; + const resolvedColumn = + column || (name?.startsWith('cohort_') && FILTER_COLUMNS[name.slice('cohort_'.length)]); + + if (!resolvedColumn) return obj; if (([OPERATORS.contains, OPERATORS.doesNotContain] as Operator[]).includes(operator)) { obj[name] = `%${value}%`; diff --git a/src/lib/request.ts b/src/lib/request.ts index 0b7c1a424..e89f5722f 100644 --- a/src/lib/request.ts +++ b/src/lib/request.ts @@ -1,7 +1,7 @@ import { startOfMonth, subMonths } from 'date-fns'; import { z } from 'zod'; import { checkAuth } from '@/lib/auth'; -import { DEFAULT_PAGE_SIZE, FILTER_COLUMNS } from '@/lib/constants'; +import { DEFAULT_PAGE_SIZE, FILTER_COLUMNS, OPERATORS } from '@/lib/constants'; import { getAllowedUnits, getMinimumUnit, maxDate, parseDateRange } from '@/lib/date'; import { fetchAccount, fetchWebsite } from '@/lib/load'; import { filtersArrayToObject } from '@/lib/params'; @@ -130,7 +130,7 @@ export async function getQueryFilters( cohortFilters.push({ name: `cohort_${cohortParams.action.type}`, - operator: 'eq', + operator: OPERATORS.equals, value: cohortParams.action.value, }); From 5144aff9cd90810bdb4a41087a801c1227133a50 Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Sat, 21 Feb 2026 10:57:52 -0800 Subject: [PATCH 14/22] revenue report enhancements. --- .../admin/users/[userId]/UserEditForm.tsx | 4 +- .../[websiteId]/(reports)/revenue/Revenue.tsx | 199 +++++--- src/app/api/reports/revenue/route.ts | 19 +- src/components/metrics/RevenueChart.tsx | 60 +++ src/lib/schema.ts | 1 + src/queries/sql/getChannelExpandedMetrics.ts | 35 +- src/queries/sql/getChannelMetrics.ts | 35 +- src/queries/sql/reports/getRevenue.ts | 125 +---- src/queries/sql/reports/getRevenueMetrics.ts | 451 ++++++++++++++++++ src/queries/sql/reports/getRevenueStats.ts | 120 +++++ 10 files changed, 822 insertions(+), 227 deletions(-) create mode 100644 src/components/metrics/RevenueChart.tsx create mode 100644 src/queries/sql/reports/getRevenueMetrics.ts create mode 100644 src/queries/sql/reports/getRevenueStats.ts diff --git a/src/app/(main)/admin/users/[userId]/UserEditForm.tsx b/src/app/(main)/admin/users/[userId]/UserEditForm.tsx index d8110ca90..481a215b7 100644 --- a/src/app/(main)/admin/users/[userId]/UserEditForm.tsx +++ b/src/app/(main)/admin/users/[userId]/UserEditForm.tsx @@ -12,7 +12,7 @@ import { useLoginQuery, useMessages, useUpdateQuery, useUser } from '@/component import { ROLES } from '@/lib/constants'; export function UserEditForm({ userId, onSave }: { userId: string; onSave?: () => void }) { - const { t, labels, messages, getMessage } = useMessages(); + const { t, labels, messages, getErrorMessage } = useMessages(); const user = useUser(); const { user: login } = useLoginQuery(); @@ -30,7 +30,7 @@ export function UserEditForm({ userId, onSave }: { userId: string; onSave?: () = }; return ( - + diff --git a/src/app/(main)/websites/[websiteId]/(reports)/revenue/Revenue.tsx b/src/app/(main)/websites/[websiteId]/(reports)/revenue/Revenue.tsx index 3a7b2058b..abf06aead 100644 --- a/src/app/(main)/websites/[websiteId]/(reports)/revenue/Revenue.tsx +++ b/src/app/(main)/websites/[websiteId]/(reports)/revenue/Revenue.tsx @@ -1,19 +1,16 @@ -import { Column, Grid, Row, Text } from '@umami/react-zen'; -import classNames from 'classnames'; -import { colord } from 'colord'; -import { useCallback, useMemo, useState } from 'react'; -import { BarChart } from '@/components/charts/BarChart'; +import { Column, Grid, Heading, Tab, TabList, TabPanel, Tabs } from '@umami/react-zen'; +import { useMemo, useState } from 'react'; +import { GridRow } from '@/components/common/GridRow'; import { LoadingPanel } from '@/components/common/LoadingPanel'; import { Panel } from '@/components/common/Panel'; -import { TypeIcon } from '@/components/common/TypeIcon'; -import { useCountryNames, useLocale, useMessages, useResultQuery } from '@/components/hooks'; +import { useDateRange, useMessages, useResultQuery } from '@/components/hooks'; import { CurrencySelect } from '@/components/input/CurrencySelect'; import { ListTable } from '@/components/metrics/ListTable'; import { MetricCard } from '@/components/metrics/MetricCard'; +import { MetricLabel } from '@/components/metrics/MetricLabel'; import { MetricsBar } from '@/components/metrics/MetricsBar'; -import { renderDateLabels } from '@/lib/charts'; -import { CHART_COLORS, CURRENCY_CONFIG, DEFAULT_CURRENCY } from '@/lib/constants'; -import { generateTimeSeries } from '@/lib/date'; +import { RevenueChart } from '@/components/metrics/RevenueChart'; +import { CURRENCY_CONFIG, DEFAULT_CURRENCY } from '@/lib/constants'; import { formatLongCurrency, formatLongNumber } from '@/lib/format'; import { getItem, setItem } from '@/lib/storage'; @@ -35,83 +32,49 @@ export function Revenue({ websiteId, startDate, endDate, unit }: RevenueProps) { }; const { t, labels } = useMessages(); - const { locale, dateLocale } = useLocale(); - const { countryNames } = useCountryNames(locale); + const { compare, isAllTime } = useDateRange(); const { data, error, isLoading } = useResultQuery('revenue', { websiteId, startDate, endDate, currency, + compare, }); - const renderCountryName = useCallback( - ({ label: code }) => ( - - - {countryNames[code] || t(labels.unknown)} - - ), - [countryNames, locale], - ); - - const chartData: any = useMemo(() => { - if (!data) return []; - - const map = (data.chart as any[]).reduce((obj, { x, t, y }) => { - if (!obj[x]) { - obj[x] = []; - } - - obj[x].push({ x: t, y }); - - return obj; - }, {}); - - return { - datasets: Object.keys(map).map((key, index) => { - const color = colord(CHART_COLORS[index % CHART_COLORS.length]); - return { - label: key, - data: generateTimeSeries(map[key], startDate, endDate, unit, dateLocale), - lineTension: 0, - backgroundColor: color.alpha(0.6).toRgbString(), - borderColor: color.alpha(0.7).toRgbString(), - borderWidth: 1, - }; - }), - }; - }, [data, startDate, endDate, unit]); - const metrics = useMemo(() => { if (!data) return []; - const { sum, count, unique_count } = data.total; + const { sum, count, average, unique_count, comparison } = data.total; return [ { value: sum, label: t(labels.total), - formatValue: n => formatLongCurrency(n, currency), + change: comparison ? sum - comparison.sum : 0, + formatValue: (n: number) => formatLongCurrency(n, currency), }, { - value: count ? sum / count : 0, + value: average, label: t(labels.average), - formatValue: n => formatLongCurrency(n, currency), + change: comparison ? average - comparison.average : 0, + formatValue: (n: number) => formatLongCurrency(n, currency), }, { value: count, label: t(labels.transactions), + change: comparison ? count - comparison.count : 0, formatValue: formatLongNumber, }, { value: unique_count, label: t(labels.uniqueCustomers), + change: comparison ? unique_count - comparison.unique_count : 0, formatValue: formatLongNumber, }, ] as any; - }, [data, locale]); + }, [data]); - const renderXLabel = useCallback(renderDateLabels(unit, locale), [unit, locale]); + const renderLabel = (type: string) => (data: any) => ; return ( @@ -122,37 +85,119 @@ export function Revenue({ websiteId, startDate, endDate, unit }: RevenueProps) { {data && ( - {metrics?.map(({ label, value, formatValue }) => { + {metrics?.map(({ label, value, change, formatValue }) => { return ( - + ); })} - - - - ({ - label: name, - count: Number(value), - percent: (value / data?.total.sum) * 100, - }))} - currency={currency} - renderLabel={renderCountryName} /> + + + + {t(labels.sources)} + + + {t(labels.referrers)} + {t(labels.channels)} + + + ({ + label: name, + count: Number(value), + percent: (value / data?.total.sum) * 100, + }), + )} + currency={currency} + renderLabel={renderLabel('referrer')} + /> + + + ({ + label: name, + count: Number(value), + percent: (value / data?.total.sum) * 100, + }), + )} + currency={currency} + renderLabel={renderLabel('channel')} + /> + + + + + {t(labels.location)} + + + {t(labels.countries)} + {t(labels.regions)} + + + ({ + label: name, + count: Number(value), + percent: (value / data?.total.sum) * 100, + }), + )} + currency={currency} + renderLabel={renderLabel('country')} + /> + + + ({ + label: name, + country, + count: Number(value), + percent: (value / data?.total.sum) * 100, + }), + )} + currency={currency} + renderLabel={renderLabel('region')} + /> + + + + + )} diff --git a/src/app/api/reports/revenue/route.ts b/src/app/api/reports/revenue/route.ts index 6a556612b..2f87f80e0 100644 --- a/src/app/api/reports/revenue/route.ts +++ b/src/app/api/reports/revenue/route.ts @@ -1,8 +1,11 @@ +import { getCompareDate } from '@/lib/date'; import { getQueryFilters, parseRequest, setWebsiteDate } from '@/lib/request'; import { json, unauthorized } from '@/lib/response'; import { reportResultSchema } from '@/lib/schema'; import { canViewWebsite } from '@/permissions'; import { getRevenue, type RevenuParameters } from '@/queries/sql/reports/getRevenue'; +import { getRevenueMetrics } from '@/queries/sql/reports/getRevenueMetrics'; +import { getRevenueStats } from '@/queries/sql/reports/getRevenueStats'; export async function POST(request: Request) { const { auth, body, error } = await parseRequest(request, reportResultSchema); @@ -20,7 +23,19 @@ export async function POST(request: Request) { const parameters = await setWebsiteDate(websiteId, body.parameters); const filters = await getQueryFilters(body.filters, websiteId); - const data = await getRevenue(websiteId, parameters as RevenuParameters, filters); + const [{ chart }, total, metrics] = await Promise.all([ + getRevenue(websiteId, parameters as RevenuParameters, filters), + getRevenueStats(websiteId, parameters as RevenuParameters, filters), + getRevenueMetrics(websiteId, parameters as RevenuParameters, filters), + ]); - return json(data); + const { compare = 'prev' } = parameters as RevenuParameters; + const { startDate, endDate } = getCompareDate(compare, parameters.startDate, parameters.endDate); + const comparison = await getRevenueStats( + websiteId, + { ...(parameters as RevenuParameters), startDate, endDate }, + filters, + ); + + return json({ chart, total: { ...total, comparison }, ...metrics }); } diff --git a/src/components/metrics/RevenueChart.tsx b/src/components/metrics/RevenueChart.tsx new file mode 100644 index 000000000..bed54706b --- /dev/null +++ b/src/components/metrics/RevenueChart.tsx @@ -0,0 +1,60 @@ +import { colord } from 'colord'; +import { useCallback, useMemo } from 'react'; +import { BarChart } from '@/components/charts/BarChart'; +import { useLocale } from '@/components/hooks'; +import { renderDateLabels } from '@/lib/charts'; +import { CHART_COLORS } from '@/lib/constants'; +import { generateTimeSeries } from '@/lib/date'; + +export interface RevenueChartProps { + data: { x: string; t: string; y: number; count: number }[]; + unit: string; + minDate: Date; + maxDate: Date; + currency: string; +} + +export function RevenueChart({ data, unit, minDate, maxDate, currency }: RevenueChartProps) { + const { locale, dateLocale } = useLocale(); + + const chartData: any = useMemo(() => { + if (!data?.length) return { datasets: [] }; + + const map = data.reduce( + (obj, { x, t, y }) => { + if (!obj[x]) obj[x] = []; + obj[x].push({ x: t, y }); + return obj; + }, + {} as Record, + ); + + return { + datasets: Object.keys(map).map((key, index) => { + const color = colord(CHART_COLORS[index % CHART_COLORS.length]); + return { + label: key, + data: generateTimeSeries(map[key], minDate, maxDate, unit, dateLocale), + backgroundColor: color.alpha(0.6).toRgbString(), + borderColor: color.alpha(0.7).toRgbString(), + borderWidth: 1, + }; + }), + }; + }, [data, minDate, maxDate, unit, dateLocale]); + + const renderXLabel = useCallback(renderDateLabels(unit, locale), [unit, locale]); + + return ( + + ); +} diff --git a/src/lib/schema.ts b/src/lib/schema.ts index 8693d30bc..41cfc70f9 100644 --- a/src/lib/schema.ts +++ b/src/lib/schema.ts @@ -229,6 +229,7 @@ export const revenueReportSchema = z.object({ unit: unitParam.optional(), timezone: timezoneParam.optional(), currency: z.string(), + compare: z.enum(['prev', 'yoy']).optional(), }), }); diff --git a/src/queries/sql/getChannelExpandedMetrics.ts b/src/queries/sql/getChannelExpandedMetrics.ts index 2a055ff36..1c6197064 100644 --- a/src/queries/sql/getChannelExpandedMetrics.ts +++ b/src/queries/sql/getChannelExpandedMetrics.ts @@ -91,6 +91,7 @@ async function relationalQuery( when ${toPostgresPositionClause('referrer_domain', EMAIL_DOMAINS)} or utm_medium ilike '%mail%' then 'email' when ${toPostgresPositionClause('referrer_domain', SHOPPING_DOMAINS)} or utm_medium ilike '%shop%' then concat(prefix, 'Shopping') when ${toPostgresPositionClause('referrer_domain', VIDEO_DOMAINS)} or utm_medium ilike '%video%' then concat(prefix, 'Video') + when referrer_domain != regexp_replace(hostname, '^www.', '') and referrer_domain != '' then 'referral' else '' end as "name", session_id, visit_id, @@ -136,31 +137,33 @@ async function clickhouseQuery( sum(if(t.c = 1, 1, 0)) as "bounces", sum(max_time-min_time) as "totaltime" from ( - select case when multiSearchAny(utm_medium, ['cp', 'ppc', 'retargeting', 'paid']) != 0 then 'paid' else 'organic' end prefix, - case + select + case when multiSearchAny(lower(utm_medium), ['cp', 'ppc', 'retargeting', 'paid']) != 0 then 'paid' else 'organic' end prefix, + case when referrer_domain = '' and url_query = '' then 'direct' - when multiSearchAny(url_query, [${toClickHouseStringArray( + when multiSearchAny(lower(url_query), [${toClickHouseStringArray( PAID_AD_PARAMS, )}]) != 0 then 'paidAds' - when multiSearchAny(utm_medium, ['referral', 'app','link']) != 0 then 'referral' - when position(utm_medium, 'affiliate') > 0 then 'affiliate' - when position(utm_medium, 'sms') > 0 or position(utm_source, 'sms') > 0 then 'sms' - when multiSearchAny(referrer_domain, [${toClickHouseStringArray( + when multiSearchAny(lower(utm_medium), ['referral', 'app','link']) != 0 then 'referral' + when position(lower(utm_medium), 'affiliate') > 0 then 'affiliate' + when position(lower(utm_medium), 'sms') > 0 or position(lower(utm_source), 'sms') > 0 then 'sms' + when multiSearchAny(lower(referrer_domain), [${toClickHouseStringArray( SEARCH_DOMAINS, - )}]) != 0 or position(utm_medium, 'organic') > 0 then concat(prefix, 'Search') - when multiSearchAny(referrer_domain, [${toClickHouseStringArray( + )}]) != 0 or position(lower(utm_medium), 'organic') > 0 then concat(prefix, 'Search') + when multiSearchAny(lower(referrer_domain), [${toClickHouseStringArray( SOCIAL_DOMAINS, )}]) != 0 then concat(prefix, 'Social') - when multiSearchAny(referrer_domain, [${toClickHouseStringArray( + when multiSearchAny(lower(referrer_domain), [${toClickHouseStringArray( EMAIL_DOMAINS, - )}]) != 0 or position(utm_medium, 'mail') > 0 then 'email' - when multiSearchAny(referrer_domain, [${toClickHouseStringArray( + )}]) != 0 or position(lower(utm_medium), 'mail') > 0 then 'email' + when multiSearchAny(lower(referrer_domain), [${toClickHouseStringArray( SHOPPING_DOMAINS, - )}]) != 0 or position(utm_medium, 'shop') > 0 then concat(prefix, 'Shopping') - when multiSearchAny(referrer_domain, [${toClickHouseStringArray( + )}]) != 0 or position(lower(utm_medium), 'shop') > 0 then concat(prefix, 'Shopping') + when multiSearchAny(lower(referrer_domain), [${toClickHouseStringArray( VIDEO_DOMAINS, - )}]) != 0 or position(utm_medium, 'video') > 0 then concat(prefix, 'Video') - else '' end AS name, + )}]) != 0 or position(lower(utm_medium), 'video') > 0 then concat(prefix, 'Video') + when referrer_domain != hostname and referrer_domain != '' then 'referral' + else '' end AS name, session_id, visit_id, count(*) c, diff --git a/src/queries/sql/getChannelMetrics.ts b/src/queries/sql/getChannelMetrics.ts index 9d14af058..524d42ac4 100644 --- a/src/queries/sql/getChannelMetrics.ts +++ b/src/queries/sql/getChannelMetrics.ts @@ -61,6 +61,7 @@ async function relationalQuery(websiteId: string, filters: QueryFilters) { when ${toPostgresLikeClause('referrer_domain', EMAIL_DOMAINS)} or utm_medium ilike '%mail%' then 'email' when ${toPostgresLikeClause('referrer_domain', SHOPPING_DOMAINS)} or utm_medium ilike '%shop%' then concat(prefix, 'Shopping') when ${toPostgresLikeClause('referrer_domain', VIDEO_DOMAINS)} or utm_medium ilike '%video%' then concat(prefix, 'Video') + wwhen referrer_domain != regexp_replace(hostname, '^www.', '') and referrer_domain != '' then 'referral' else '' end AS x, count(distinct session_id) y from prefix @@ -90,31 +91,33 @@ async function clickhouseQuery( const sql = ` WITH channels as ( - select case when multiSearchAny(utm_medium, ['cp', 'ppc', 'retargeting', 'paid']) != 0 then 'paid' else 'organic' end prefix, - case + select + case when multiSearchAny(lower(utm_medium), ['cp', 'ppc', 'retargeting', 'paid']) != 0 then 'paid' else 'organic' end prefix, + case when referrer_domain = '' and url_query = '' then 'direct' - when multiSearchAny(url_query, [${toClickHouseStringArray( + when multiSearchAny(lower(url_query), [${toClickHouseStringArray( PAID_AD_PARAMS, )}]) != 0 then 'paidAds' - when multiSearchAny(utm_medium, ['referral', 'app','link']) != 0 then 'referral' - when position(utm_medium, 'affiliate') > 0 then 'affiliate' - when position(utm_medium, 'sms') > 0 or position(utm_source, 'sms') > 0 then 'sms' - when multiSearchAny(referrer_domain, [${toClickHouseStringArray( + when multiSearchAny(lower(utm_medium), ['referral', 'app','link']) != 0 then 'referral' + when position(lower(utm_medium), 'affiliate') > 0 then 'affiliate' + when position(lower(utm_medium), 'sms') > 0 or position(lower(utm_source), 'sms') > 0 then 'sms' + when multiSearchAny(lower(referrer_domain), [${toClickHouseStringArray( SEARCH_DOMAINS, - )}]) != 0 or position(utm_medium, 'organic') > 0 then concat(prefix, 'Search') - when multiSearchAny(referrer_domain, [${toClickHouseStringArray( + )}]) != 0 or position(lower(utm_medium), 'organic') > 0 then concat(prefix, 'Search') + when multiSearchAny(lower(referrer_domain), [${toClickHouseStringArray( SOCIAL_DOMAINS, )}]) != 0 then concat(prefix, 'Social') - when multiSearchAny(referrer_domain, [${toClickHouseStringArray( + when multiSearchAny(lower(referrer_domain), [${toClickHouseStringArray( EMAIL_DOMAINS, - )}]) != 0 or position(utm_medium, 'mail') > 0 then 'email' - when multiSearchAny(referrer_domain, [${toClickHouseStringArray( + )}]) != 0 or position(lower(utm_medium), 'mail') > 0 then 'email' + when multiSearchAny(lower(referrer_domain), [${toClickHouseStringArray( SHOPPING_DOMAINS, - )}]) != 0 or position(utm_medium, 'shop') > 0 then concat(prefix, 'Shopping') - when multiSearchAny(referrer_domain, [${toClickHouseStringArray( + )}]) != 0 or position(lower(utm_medium), 'shop') > 0 then concat(prefix, 'Shopping') + when multiSearchAny(lower(referrer_domain), [${toClickHouseStringArray( VIDEO_DOMAINS, - )}]) != 0 or position(utm_medium, 'video') > 0 then concat(prefix, 'Video') - else '' end AS x, + )}]) != 0 or position(lower(utm_medium), 'video') > 0 then concat(prefix, 'Video') + when referrer_domain != hostname and referrer_domain != '' then 'referral' + else '' end AS x, count(distinct session_id) y from website_event ${cohortQuery} diff --git a/src/queries/sql/reports/getRevenue.ts b/src/queries/sql/reports/getRevenue.ts index 30d7d7f1f..183861e12 100644 --- a/src/queries/sql/reports/getRevenue.ts +++ b/src/queries/sql/reports/getRevenue.ts @@ -9,12 +9,7 @@ export interface RevenuParameters { unit: string; timezone: string; currency: string; -} - -export interface RevenueResult { - chart: { x: string; t: string; y: number }[]; - country: { name: string; value: number }[]; - total: { sum: number; count: number; average: number; unique_count: number }; + compare?: string; } export async function getRevenue( @@ -30,7 +25,7 @@ async function relationalQuery( websiteId: string, parameters: RevenuParameters, filters: QueryFilters, -): Promise { +) { const { startDate, endDate, unit = 'day', timezone = 'utc', currency } = parameters; const { getDateSQL, rawQuery, parseFilters } = prisma; const { queryParams, filterQuery, cohortQuery, joinSessionQuery } = parseFilters({ @@ -58,7 +53,8 @@ async function relationalQuery( select revenue.event_name x, ${getDateSQL('revenue.created_at', unit, timezone)} t, - sum(revenue.revenue) y + sum(revenue.revenue) y, + count(revenue.event_id) count from revenue ${joinQuery} ${cohortQuery} @@ -73,54 +69,14 @@ async function relationalQuery( queryParams, ); - const country = await rawQuery( - ` - select - session.country as "name", - sum(revenue) as "value" - from revenue - ${joinQuery} - join session - on session.website_id = revenue.website_id - and session.session_id = revenue.session_id - ${cohortQuery} - where revenue.website_id = {{websiteId::uuid}} - and revenue.created_at between {{startDate}} and {{endDate}} - and upper(revenue.currency) = {{currency}} - ${filterQuery} - group by session.country - `, - queryParams, - ); - - const total = await rawQuery( - ` - select - sum(revenue.revenue) as sum, - count(distinct revenue.event_id) as count, - count(distinct revenue.session_id) as unique_count - from revenue - ${joinQuery} - ${cohortQuery} - ${joinSessionQuery} - where revenue.website_id = {{websiteId::uuid}} - and revenue.created_at between {{startDate}} and {{endDate}} - and upper(revenue.currency) = {{currency}} - ${filterQuery} - `, - queryParams, - ).then(result => result?.[0]); - - total.average = total.count > 0 ? Number(total.sum) / Number(total.count) : 0; - - return { chart, country, total }; + return { chart }; } async function clickhouseQuery( websiteId: string, parameters: RevenuParameters, filters: QueryFilters, -): Promise { +) { const { startDate, endDate, unit = 'day', timezone = 'utc', currency } = parameters; const { getDateSQL, rawQuery, parseFilters } = clickhouse; const { filterQuery, cohortQuery, queryParams } = parseFilters({ @@ -133,7 +89,7 @@ async function clickhouseQuery( const joinQuery = filterQuery ? `any left join ( - select * + select * from website_event where website_id = {websiteId:UUID} and created_at between {startDate:DateTime64} and {endDate:DateTime64} @@ -143,18 +99,13 @@ async function clickhouseQuery( and website_event.event_id = website_revenue.event_id` : ''; - const chart = await rawQuery< - { - x: string; - t: string; - y: number; - }[] - >( + const chart = await rawQuery<{ x: string; t: string; y: number; count: number }[]>( ` select website_revenue.event_name x, ${getDateSQL('website_revenue.created_at', unit, timezone)} t, - sum(website_revenue.revenue) y + sum(website_revenue.revenue) y, + count(website_revenue.event_id) count from website_revenue ${joinQuery} ${cohortQuery} @@ -168,59 +119,5 @@ async function clickhouseQuery( queryParams, ); - const country = await rawQuery< - { - name: string; - value: number; - }[] - >( - ` - select - website_event.country as "name", - sum(website_revenue.revenue) as "value" - from website_revenue - any left join ( - select * - from website_event - where website_id = {websiteId:UUID} - and created_at between {startDate:DateTime64} and {endDate:DateTime64} - and event_type = 2) website_event - on website_event.website_id = website_revenue.website_id - and website_event.session_id = website_revenue.session_id - and website_event.event_id = website_revenue.event_id - ${cohortQuery} - where website_revenue.website_id = {websiteId:UUID} - and website_revenue.created_at between {startDate:DateTime64} and {endDate:DateTime64} - and upper(website_revenue.currency) = {currency:String} - ${filterQuery} - group by website_event.country - order by value desc - `, - queryParams, - ); - - const total = await rawQuery<{ - sum: number; - count: number; - unique_count: number; - }>( - ` - select - sum(website_revenue.revenue) as sum, - uniqExact(website_revenue.event_id) as count, - uniqExact(website_revenue.session_id) as unique_count - from website_revenue - ${joinQuery} - ${cohortQuery} - where website_revenue.website_id = {websiteId:UUID} - and website_revenue.created_at between {startDate:DateTime64} and {endDate:DateTime64} - and upper(website_revenue.currency) = {currency:String} - ${filterQuery} - `, - queryParams, - ).then(result => result?.[0]); - - total.average = total.count > 0 ? total.sum / total.count : 0; - - return { chart, country, total }; + return { chart }; } diff --git a/src/queries/sql/reports/getRevenueMetrics.ts b/src/queries/sql/reports/getRevenueMetrics.ts new file mode 100644 index 000000000..6553d2e09 --- /dev/null +++ b/src/queries/sql/reports/getRevenueMetrics.ts @@ -0,0 +1,451 @@ +import clickhouse from '@/lib/clickhouse'; +import { + EMAIL_DOMAINS, + PAID_AD_PARAMS, + SEARCH_DOMAINS, + SHOPPING_DOMAINS, + SOCIAL_DOMAINS, + VIDEO_DOMAINS, +} from '@/lib/constants'; +import { CLICKHOUSE, PRISMA, runQuery } from '@/lib/db'; +import prisma from '@/lib/prisma'; +import type { QueryFilters } from '@/lib/types'; +import type { RevenuParameters } from './getRevenue'; + +export interface RevenueMetricsResult { + country: { name: string; value: number }[]; + region: { name: string; value: number; country: string }[]; + referrer: { name: string; value: number }[]; + channel: { name: string; value: number }[]; +} + +export async function getRevenueMetrics( + ...args: [websiteId: string, parameters: RevenuParameters, filters: QueryFilters] +) { + return runQuery({ + [PRISMA]: () => relationalQuery(...args), + [CLICKHOUSE]: () => clickhouseQuery(...args), + }); +} + +async function relationalQuery( + websiteId: string, + parameters: RevenuParameters, + filters: QueryFilters, +): Promise { + const { startDate, endDate, currency } = parameters; + const { rawQuery, parseFilters } = prisma; + const { queryParams, filterQuery, cohortQuery, joinSessionQuery } = parseFilters({ + ...filters, + websiteId, + startDate, + endDate, + currency, + }); + + const joinQuery = + filterQuery || cohortQuery + ? `join (select * + from website_event + where website_id = {{websiteId::uuid}} + and created_at between {{startDate}} and {{endDate}} + and event_type = 2) website_event + on website_event.website_id = revenue.website_id + and website_event.session_id = revenue.session_id + and website_event.event_id = revenue.event_id` + : ''; + + const country = await rawQuery( + ` + select + session.country as "name", + sum(revenue) as "value" + from revenue + ${joinQuery} + join session + on session.website_id = revenue.website_id + and session.session_id = revenue.session_id + ${cohortQuery} + where revenue.website_id = {{websiteId::uuid}} + and revenue.created_at between {{startDate}} and {{endDate}} + and upper(revenue.currency) = {{currency}} + ${filterQuery} + group by session.country + order by value desc + `, + queryParams, + ); + + const region = await rawQuery( + ` + select + session.country, + session.region as "name", + sum(revenue.revenue) as "value" + from revenue + ${joinQuery} + join session + on session.website_id = revenue.website_id + and session.session_id = revenue.session_id + ${cohortQuery} + where revenue.website_id = {{websiteId::uuid}} + and revenue.created_at between {{startDate}} and {{endDate}} + and upper(revenue.currency) = {{currency}} + ${filterQuery} + group by session.country, session.region + order by value desc + `, + queryParams, + ); + + const referrer = await rawQuery( + ` + WITH events AS ( + select + revenue.website_id, + revenue.session_id, + sum(revenue.revenue) as "value" + from revenue + ${joinQuery} + ${cohortQuery} + ${joinSessionQuery} + where revenue.website_id = {{websiteId::uuid}} + and revenue.created_at between {{startDate}} and {{endDate}} + and upper(revenue.currency) = {{currency}} + ${filterQuery} + group by revenue.website_id, revenue.session_id), + + revenue_data AS ( + select + e.website_id, + e.session_id, + e.value, + we.min_date as created_at + from events e + join ( + select session_id, min(created_at) as min_date + from website_event + where website_id = {{websiteId::uuid}} + and created_at between {{startDate}} and {{endDate}} + group by session_id + ) we on we.session_id = e.session_id) + + select + we.referrer_domain as "name", + sum(revenue_data.value) as "value" + from revenue_data + join ( + select website_id, session_id, referrer_domain, created_at + from website_event + where website_id = {{websiteId::uuid}} + and created_at between {{startDate}} and {{endDate}}) we + on we.website_id = revenue_data.website_id + and we.session_id = revenue_data.session_id + and we.created_at = revenue_data.created_at + group by we.referrer_domain + order by value desc + `, + queryParams, + ); + + const channel = await rawQuery( + ` + WITH events AS ( + select + revenue.website_id, + revenue.session_id, + sum(revenue.revenue) as "value" + from revenue + ${joinQuery} + ${cohortQuery} + ${joinSessionQuery} + where revenue.website_id = {{websiteId::uuid}} + and revenue.created_at between {{startDate}} and {{endDate}} + and upper(revenue.currency) = {{currency}} + ${filterQuery} + group by revenue.website_id, revenue.session_id), + + revenue_data AS ( + select + e.website_id, + e.session_id, + e.value, + we.min_date as created_at + from events e + join ( + select session_id, min(created_at) as min_date + from website_event + where website_id = {{websiteId::uuid}} + and created_at between {{startDate}} and {{endDate}} + group by session_id + ) we on we.session_id = e.session_id), + + revenue_prefix AS ( + select + case when we.utm_medium ilike '%cp%' OR + we.utm_medium ilike '%ppc%' OR + we.utm_medium ilike '%retargeting%' OR + we.utm_medium ilike '%paid%' then 'paid' else 'organic' end AS prefix, + we.referrer_domain, + we.url_query, + we.utm_medium, + we.utm_source, + we.hostname, + r.value + from revenue_data r + join ( + select website_id, session_id, referrer_domain, url_query, utm_medium, utm_source, hostname, created_at + from website_event + where website_id = {{websiteId::uuid}} + and created_at between {{startDate}} and {{endDate}}) we + on we.website_id = r.website_id + and we.session_id = r.session_id + and we.created_at = r.created_at), + + channels AS ( + select + case + when referrer_domain = '' and url_query = '' then 'direct' + when ${toPostgresLikeClause('url_query', PAID_AD_PARAMS)} then 'paidAds' + when ${toPostgresLikeClause('utm_medium', ['referral', 'app', 'link'])} then 'referral' + when utm_medium ilike '%affiliate%' then 'affiliate' + when utm_medium ilike '%sms%' or utm_source ilike '%sms%' then 'sms' + when ${toPostgresLikeClause('referrer_domain', SEARCH_DOMAINS)} or utm_medium ilike '%organic%' then concat(prefix, 'Search') + when ${toPostgresLikeClause('referrer_domain', SOCIAL_DOMAINS)} then concat(prefix, 'Social') + when ${toPostgresLikeClause('referrer_domain', EMAIL_DOMAINS)} or utm_medium ilike '%mail%' then 'email' + when ${toPostgresLikeClause('referrer_domain', SHOPPING_DOMAINS)} or utm_medium ilike '%shop%' then concat(prefix, 'Shopping') + when ${toPostgresLikeClause('referrer_domain', VIDEO_DOMAINS)} or utm_medium ilike '%video%' then concat(prefix, 'Video') + when referrer_domain != regexp_replace(hostname, '^www.', '') and referrer_domain != '' then 'referral' + else 'Unknown' end AS "name", + value + from revenue_prefix) + + select name, sum(value) as value + from channels + group by name + order by value desc + `, + queryParams, + ); + + return { country, region, referrer, channel }; +} + +async function clickhouseQuery( + websiteId: string, + parameters: RevenuParameters, + filters: QueryFilters, +): Promise { + const { startDate, endDate, currency } = parameters; + const { rawQuery, parseFilters } = clickhouse; + const { filterQuery, cohortQuery, queryParams } = parseFilters({ + ...filters, + websiteId, + startDate, + endDate, + currency, + }); + + const joinQuery = filterQuery + ? `any left join ( + select * + from website_event + where website_id = {websiteId:UUID} + and created_at between {startDate:DateTime64} and {endDate:DateTime64} + and event_type = 2) website_event + on website_event.website_id = website_revenue.website_id + and website_event.session_id = website_revenue.session_id + and website_event.event_id = website_revenue.event_id` + : ''; + + const country = await rawQuery<{ name: string; value: number }[]>( + ` + select + website_event.country as "name", + sum(website_revenue.revenue) as "value" + from website_revenue + any left join ( + select * + from website_event + where website_id = {websiteId:UUID} + and created_at between {startDate:DateTime64} and {endDate:DateTime64} + and event_type = 2) website_event + on website_event.website_id = website_revenue.website_id + and website_event.session_id = website_revenue.session_id + and website_event.event_id = website_revenue.event_id + ${cohortQuery} + where website_revenue.website_id = {websiteId:UUID} + and website_revenue.created_at between {startDate:DateTime64} and {endDate:DateTime64} + and upper(website_revenue.currency) = {currency:String} + ${filterQuery} + group by website_event.country + order by value desc + `, + queryParams, + ); + + const region = await rawQuery<{ name: string; value: number; country: string }[]>( + ` + select + website_event.country, + website_event.region as "name", + sum(website_revenue.revenue) as "value" + from website_revenue + any left join ( + select * + from website_event + where website_id = {websiteId:UUID} + and created_at between {startDate:DateTime64} and {endDate:DateTime64} + and event_type = 2) website_event + on website_event.website_id = website_revenue.website_id + and website_event.session_id = website_revenue.session_id + and website_event.event_id = website_revenue.event_id + ${cohortQuery} + where website_revenue.website_id = {websiteId:UUID} + and website_revenue.created_at between {startDate:DateTime64} and {endDate:DateTime64} + and upper(website_revenue.currency) = {currency:String} + ${filterQuery} + group by 1,2 + order by value desc + `, + queryParams, + ); + + const referrer = await rawQuery<{ name: string; value: number }[]>( + ` + WITH events AS ( + select distinct + website_id, + session_id, + sum(revenue) as "value" + from website_revenue + ${joinQuery} + ${cohortQuery} + where website_id = {websiteId:UUID} + and created_at between {startDate:DateTime64} and {endDate:DateTime64} + and upper(currency) = {currency:String} + ${filterQuery} + group by 1,2), + + revenue AS ( + select + e.website_id, + e.session_id, + e.value, + we.min_date as created_at + from events e + join (select session_id, min(created_at) min_date + from website_event + where website_id = {websiteId:UUID} + and created_at between {startDate:DateTime64} and {endDate:DateTime64} + group by 1 + ) we + on we.session_id = e.session_id) + + select + website_event.referrer_domain as "name", + sum(revenue.value) as "value" + from revenue + any left join ( + select website_id, session_id, referrer_domain, created_at + from website_event + where website_id = {websiteId:UUID} + and created_at between {startDate:DateTime64} and {endDate:DateTime64}) website_event + on website_event.website_id = revenue.website_id + and website_event.session_id = revenue.session_id + and website_event.created_at = revenue.created_at + group by 1 + order by value desc + `, + queryParams, + ); + + const channel = await rawQuery<{ name: string; value: number }[]>( + ` + WITH events AS ( + select distinct + website_id, + session_id, + sum(revenue) as "value" + from website_revenue + ${joinQuery} + ${cohortQuery} + where website_id = {websiteId:UUID} + and created_at between {startDate:DateTime64} and {endDate:DateTime64} + and upper(currency) = {currency:String} + ${filterQuery} + group by 1,2), + + revenue AS ( + select + e.website_id, + e.session_id, + e.value, + we.min_date as created_at + from events e + join (select session_id, min(created_at) min_date + from website_event + where website_id = {websiteId:UUID} + and created_at between {startDate:DateTime64} and {endDate:DateTime64} + group by 1 + ) we + on we.session_id = e.session_id), + + channels AS ( + select + case when multiSearchAny(lower(utm_medium), ['cp', 'ppc', 'retargeting', 'paid']) != 0 then 'paid' else 'organic' end prefix, + case + when referrer_domain = '' and url_query = '' then 'direct' + when multiSearchAny(lower(url_query), [${toClickHouseStringArray( + PAID_AD_PARAMS, + )}]) != 0 then 'paidAds' + when multiSearchAny(lower(utm_medium), ['referral', 'app','link']) != 0 then 'referral' + when position(lower(utm_medium), 'affiliate') > 0 then 'affiliate' + when position(lower(utm_medium), 'sms') > 0 or position(lower(utm_source), 'sms') > 0 then 'sms' + when multiSearchAny(lower(referrer_domain), [${toClickHouseStringArray( + SEARCH_DOMAINS, + )}]) != 0 or position(lower(utm_medium), 'organic') > 0 then concat(prefix, 'Search') + when multiSearchAny(lower(referrer_domain), [${toClickHouseStringArray( + SOCIAL_DOMAINS, + )}]) != 0 then concat(prefix, 'Social') + when multiSearchAny(lower(referrer_domain), [${toClickHouseStringArray( + EMAIL_DOMAINS, + )}]) != 0 or position(lower(utm_medium), 'mail') > 0 then 'email' + when multiSearchAny(lower(referrer_domain), [${toClickHouseStringArray( + SHOPPING_DOMAINS, + )}]) != 0 or position(lower(utm_medium), 'shop') > 0 then concat(prefix, 'Shopping') + when multiSearchAny(lower(referrer_domain), [${toClickHouseStringArray( + VIDEO_DOMAINS, + )}]) != 0 or position(lower(utm_medium), 'video') > 0 then concat(prefix, 'Video') + when referrer_domain != hostname and referrer_domain != '' then 'referral' + else 'Unknown' end AS "name", + sum(revenue.value) as "value" + from revenue + any left join ( + select * + from website_event + where website_id = {websiteId:UUID} + and created_at between {startDate:DateTime64} and {endDate:DateTime64}) website_event + on website_event.website_id = revenue.website_id + and website_event.session_id = revenue.session_id + and website_event.created_at = revenue.created_at + group by 1, 2) + + select name, sum(value) value + from channels + group by 1 + order by value desc; + `, + queryParams, + ); + + return { country, region, referrer, channel }; +} + +function toClickHouseStringArray(arr: string[]): string { + return arr.map(p => `'${p.replace(/'/g, "\\'")}'`).join(', '); +} + +function toPostgresLikeClause(column: string, arr: string[]) { + return arr.map(val => `${column} ilike '%${val.replace(/'/g, "''")}%'`).join(' OR\n '); +} diff --git a/src/queries/sql/reports/getRevenueStats.ts b/src/queries/sql/reports/getRevenueStats.ts new file mode 100644 index 000000000..c0eac90fe --- /dev/null +++ b/src/queries/sql/reports/getRevenueStats.ts @@ -0,0 +1,120 @@ +import clickhouse from '@/lib/clickhouse'; +import { CLICKHOUSE, PRISMA, runQuery } from '@/lib/db'; +import prisma from '@/lib/prisma'; +import type { QueryFilters } from '@/lib/types'; +import type { RevenuParameters } from './getRevenue'; + +export interface RevenueStatsResult { + sum: number; + count: number; + average: number; + unique_count: number; +} + +export async function getRevenueStats( + ...args: [websiteId: string, parameters: RevenuParameters, filters: QueryFilters] +) { + return runQuery({ + [PRISMA]: () => relationalQuery(...args), + [CLICKHOUSE]: () => clickhouseQuery(...args), + }); +} + +async function relationalQuery( + websiteId: string, + parameters: RevenuParameters, + filters: QueryFilters, +): Promise { + const { startDate, endDate, currency } = parameters; + const { rawQuery, parseFilters } = prisma; + const { queryParams, filterQuery, cohortQuery, joinSessionQuery } = parseFilters({ + ...filters, + websiteId, + startDate, + endDate, + currency, + }); + + const joinQuery = + filterQuery || cohortQuery + ? `join (select * + from website_event + where website_id = {{websiteId::uuid}} + and created_at between {{startDate}} and {{endDate}} + and event_type = 2) website_event + on website_event.website_id = revenue.website_id + and website_event.session_id = revenue.session_id + and website_event.event_id = revenue.event_id` + : ''; + + const total = await rawQuery( + ` + select + sum(revenue.revenue) as sum, + count(distinct revenue.event_id) as count, + count(distinct revenue.session_id) as unique_count + from revenue + ${joinQuery} + ${cohortQuery} + ${joinSessionQuery} + where revenue.website_id = {{websiteId::uuid}} + and revenue.created_at between {{startDate}} and {{endDate}} + and upper(revenue.currency) = {{currency}} + ${filterQuery} + `, + queryParams, + ).then(result => result?.[0]); + + total.average = total.count > 0 ? Number(total.sum) / Number(total.count) : 0; + + return total; +} + +async function clickhouseQuery( + websiteId: string, + parameters: RevenuParameters, + filters: QueryFilters, +): Promise { + const { startDate, endDate, currency } = parameters; + const { rawQuery, parseFilters } = clickhouse; + const { filterQuery, cohortQuery, queryParams } = parseFilters({ + ...filters, + websiteId, + startDate, + endDate, + currency, + }); + + const joinQuery = filterQuery + ? `any left join ( + select * + from website_event + where website_id = {websiteId:UUID} + and created_at between {startDate:DateTime64} and {endDate:DateTime64} + and event_type = 2) website_event + on website_event.website_id = website_revenue.website_id + and website_event.session_id = website_revenue.session_id + and website_event.event_id = website_revenue.event_id` + : ''; + + const total = await rawQuery<{ sum: number; count: number; unique_count: number }>( + ` + select + sum(website_revenue.revenue) as sum, + uniqExact(website_revenue.event_id) as count, + uniqExact(website_revenue.session_id) as unique_count + from website_revenue + ${joinQuery} + ${cohortQuery} + where website_revenue.website_id = {websiteId:UUID} + and website_revenue.created_at between {startDate:DateTime64} and {endDate:DateTime64} + and upper(website_revenue.currency) = {currency:String} + ${filterQuery} + `, + queryParams, + ).then(result => result?.[0]); + + total.average = total.count > 0 ? total.sum / total.count : 0; + + return total; +} From 4605f5cb06fd3e3fe934ed137a3ad314a568869e Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Sat, 21 Feb 2026 13:19:34 -0800 Subject: [PATCH 15/22] Fix mobile UI/UX issues --- src/app/(main)/MobileNav.tsx | 12 +++++++++--- .../websites/[websiteId]/settings/SharesTable.tsx | 12 +++++------- src/components/input/UserButton.tsx | 5 +++-- 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/src/app/(main)/MobileNav.tsx b/src/app/(main)/MobileNav.tsx index ff7fe73a5..f731cb08a 100644 --- a/src/app/(main)/MobileNav.tsx +++ b/src/app/(main)/MobileNav.tsx @@ -49,7 +49,13 @@ export function MobileNav() { {({ close }) => { return ( - + {isMain && links.map(link => { return ( @@ -63,8 +69,8 @@ export function MobileNav() { {websiteId && } {isAdmin && } {isSettings && } - - + + ); diff --git a/src/app/(main)/websites/[websiteId]/settings/SharesTable.tsx b/src/app/(main)/websites/[websiteId]/settings/SharesTable.tsx index 933fb65ff..2d1c87f15 100644 --- a/src/app/(main)/websites/[websiteId]/settings/SharesTable.tsx +++ b/src/app/(main)/websites/[websiteId]/settings/SharesTable.tsx @@ -18,7 +18,7 @@ export function SharesTable(props: DataTableProps) { }; return ( - + {({ name }: any) => name} @@ -27,16 +27,14 @@ export function SharesTable(props: DataTableProps) { const url = getUrl(slug); return ( - {url} + {isMobile ? slug : url} ); }} - {!isMobile && ( - - {(row: any) => } - - )} + + {(row: any) => } + {({ id, slug }: any) => { return ( diff --git a/src/components/input/UserButton.tsx b/src/components/input/UserButton.tsx index 8804f8e5d..91080f344 100644 --- a/src/components/input/UserButton.tsx +++ b/src/components/input/UserButton.tsx @@ -33,9 +33,10 @@ import { languages } from '@/lib/lang'; export interface UserButtonProps { showText?: boolean; + onClose?: () => void; } -export function UserButton({ showText = true }: UserButtonProps) { +export function UserButton({ showText = true, onClose }: UserButtonProps) { const { user } = useLoginQuery(); const { cloudMode } = useConfig(); const { t, labels } = useMessages(); @@ -111,7 +112,7 @@ export function UserButton({ showText = true }: UserButtonProps) { - + From 98d1d85ed106c5e2c6f18f09715f82a199a7268f Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Sat, 21 Feb 2026 13:34:15 -0800 Subject: [PATCH 16/22] Fix teams button overflow in mobile --- src/components/input/TeamsButton.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/components/input/TeamsButton.tsx b/src/components/input/TeamsButton.tsx index 527ab1fa9..f44ba83a5 100644 --- a/src/components/input/TeamsButton.tsx +++ b/src/components/input/TeamsButton.tsx @@ -23,6 +23,7 @@ export function TeamsButton() { const { user } = useLoginQuery(); const { t, labels } = useMessages(); const { teamId, router } = useNavigation(); + const { isPhone } = useMobile(); const team = user?.teams?.find(({ id }) => id === teamId); const selectedKeys = new Set([teamId || 'user']); const label = teamId ? team?.name : user.username; @@ -52,7 +53,7 @@ export function TeamsButton() { position="relative" gap maxHeight="40px" - minWidth="200px" + minWidth={isPhone ? '100px' : '200px'} maxWidth="200px" > {teamId ? : } From 79c06787cd83d66e8c02661e15e4e8f5fb6b2e74 Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Sat, 21 Feb 2026 14:56:29 -0800 Subject: [PATCH 17/22] enable using same filters --- src/components/hooks/useFilterParameters.ts | 101 ++++---------------- src/components/hooks/useFilters.ts | 6 +- src/components/input/FieldFilters.tsx | 32 +++---- src/components/input/FilterBar.tsx | 4 +- src/lib/clickhouse.ts | 58 ++++++----- src/lib/params.ts | 20 +++- src/lib/prisma.ts | 32 ++++--- src/lib/request.ts | 16 +++- src/lib/types.ts | 1 + 9 files changed, 125 insertions(+), 145 deletions(-) diff --git a/src/components/hooks/useFilterParameters.ts b/src/components/hooks/useFilterParameters.ts index ca2fd1b86..b4b9391b9 100644 --- a/src/components/hooks/useFilterParameters.ts +++ b/src/components/hooks/useFilterParameters.ts @@ -1,91 +1,28 @@ import { useMemo } from 'react'; +import { FILTER_COLUMNS } from '@/lib/constants'; import { useNavigation } from './useNavigation'; export function useFilterParameters() { - const { - query: { - path, - referrer, - title, - query, - host, - os, - browser, - device, - country, - region, - city, - event, - tag, - hostname, - distinctId, - utmSource, - utmMedium, - utmCampaign, - utmContent, - utmTerm, - page, - pageSize, - search, - segment, - cohort, - excludeBounce, - }, - } = useNavigation(); + const { query } = useNavigation(); return useMemo(() => { + const filterParams: Record = {}; + + for (const key of Object.keys(query)) { + const baseName = key.replace(/\d+$/, ''); + if (FILTER_COLUMNS[baseName]) { + filterParams[key] = query[key]; + } + } + return { - path, - referrer, - title, - query, - host, - os, - browser, - device, - country, - region, - city, - event, - tag, - hostname, - distinctId, - utmSource, - utmMedium, - utmCampaign, - utmContent, - utmTerm, - search, - segment, - cohort, - excludeBounce, + ...filterParams, + search: query.search, + segment: query.segment, + cohort: query.cohort, + excludeBounce: query.excludeBounce, + page: query.page, + pageSize: query.pageSize, }; - }, [ - path, - referrer, - title, - query, - host, - os, - browser, - device, - country, - region, - city, - event, - tag, - hostname, - distinctId, - utmSource, - utmMedium, - utmCampaign, - utmContent, - utmTerm, - page, - pageSize, - search, - segment, - cohort, - excludeBounce, - ]); + }, [query]); } diff --git a/src/components/hooks/useFilters.ts b/src/components/hooks/useFilters.ts index 96397ea4d..57d9177cd 100644 --- a/src/components/hooks/useFilters.ts +++ b/src/components/hooks/useFilters.ts @@ -74,10 +74,11 @@ export function useFilters() { }; const filters = Object.keys(query).reduce((arr, key) => { - if (FILTER_COLUMNS[key]) { + const baseName = key.replace(/\d+$/, ''); + if (FILTER_COLUMNS[baseName]) { let operator = 'eq'; let value = safeDecodeURIComponent(query[key]); - const label = fields.find(({ name }) => name === key)?.label; + const label = fields.find(({ name }) => name === baseName)?.label; const match = value.match(/^([a-z]+)\.(.*)/); @@ -88,6 +89,7 @@ export function useFilters() { return arr.concat({ name: key, + type: baseName, operator, value, label, diff --git a/src/components/input/FieldFilters.tsx b/src/components/input/FieldFilters.tsx index df2b4cd3f..0d4aaf035 100644 --- a/src/components/input/FieldFilters.tsx +++ b/src/components/input/FieldFilters.tsx @@ -48,24 +48,24 @@ export function FieldFilters({ websiteId, value, exclude = [], onChange }: Field {} as Record, ); - const updateFilter = (name: string, props: Record) => { - onChange(value.map(filter => (filter.name === name ? { ...filter, ...props } : filter))); + const updateFilter = (index: number, props: Record) => { + onChange(value.map((filter, i) => (i === index ? { ...filter, ...props } : filter))); }; const handleAdd = (name: Key) => { onChange(value.concat({ name: name.toString(), operator: 'eq', value: '' })); }; - const handleChange = (name: string, value: Key) => { - updateFilter(name, { value }); + const handleChange = (index: number, val: Key) => { + updateFilter(index, { value: val }); }; - const handleSelect = (name: string, operator: Key) => { - updateFilter(name, { operator }); + const handleSelect = (index: number, operator: Key) => { + updateFilter(index, { operator }); }; - const handleRemove = (name: string) => { - onChange(value.filter(filter => filter.name !== name)); + const handleRemove = (index: number) => { + onChange(value.filter((_, i) => i !== index)); }; return ( @@ -87,9 +87,8 @@ export function FieldFilters({ websiteId, value, exclude = [], onChange }: Field return ( {groupFields.map(field => { - const isDisabled = !!value.find(({ name }) => name === field.name); return ( - + {field.filterLabel} ); @@ -115,9 +114,8 @@ export function FieldFilters({ websiteId, value, exclude = [], onChange }: Field return ( {groupFields.map(field => { - const isDisabled = !!value.find(({ name }) => name === field.name); return ( - + {field.filterLabel} ); @@ -128,18 +126,18 @@ export function FieldFilters({ websiteId, value, exclude = [], onChange }: Field - {value.map(filter => { + {value.map((filter, index) => { return ( handleSelect(index, operator)} + onRemove={() => handleRemove(index)} + onChange={(_name, val) => handleChange(index, val)} /> ); })} diff --git a/src/components/input/FilterBar.tsx b/src/components/input/FilterBar.tsx index 0dca00b26..bc5537af2 100644 --- a/src/components/input/FilterBar.tsx +++ b/src/components/input/FilterBar.tsx @@ -78,12 +78,12 @@ export function FilterBar({ websiteId }: { websiteId: string }) { /> )} {filters.map(filter => { - const { name, label, operator, value } = filter; + const { name, type, label, operator, value } = filter; const paramValue = isSearchOperator(operator) ? value : String(value) .split(',') - .map(v => formatValue(v, name)) + .map(v => formatValue(v, type || name)) .join(', '); return ( diff --git a/src/lib/clickhouse.ts b/src/lib/clickhouse.ts index bb3976c71..cbe5022d1 100644 --- a/src/lib/clickhouse.ts +++ b/src/lib/clickhouse.ts @@ -70,14 +70,21 @@ function getSearchSQL(column: string, param: string = 'search'): string { return `and positionCaseInsensitive(${column}, {${param}:String}) > 0`; } -function mapFilter(column: string, operator: string, name: string, type: string = 'String') { - const value = `{${name}:${type}}`; +function mapFilter( + column: string, + operator: string, + name: string, + type: string = 'String', + paramName?: string, +) { + const param = paramName ?? name; + const value = `{${param}:${type}}`; switch (operator) { case OPERATORS.equals: - return `${column} IN {${name}:Array(${type})}`; + return `${column} IN {${param}:Array(${type})}`; case OPERATORS.notEquals: - return `${column} NOT IN {${name}:Array(${type})}`; + return `${column} NOT IN {${param}:Array(${type})}`; case OPERATORS.contains: return `positionCaseInsensitive(${column}, ${value}) > 0`; case OPERATORS.doesNotContain: @@ -92,27 +99,30 @@ function mapFilter(column: string, operator: string, name: string, type: string } function getFilterQuery(filters: Record, options: QueryOptions = {}) { - const query = filtersObjectToArray(filters, options).reduce((arr, { name, column, operator }) => { - const isCohort = options?.isCohort; + const query = filtersObjectToArray(filters, options).reduce( + (arr, { name, column, operator, paramName }) => { + const isCohort = options?.isCohort; - if (isCohort) { - column = FILTER_COLUMNS[name.slice('cohort_'.length)]; - } - - if (column) { - if (name === 'eventType') { - arr.push(`and ${mapFilter(column, operator, name, 'UInt32')}`); - } else { - arr.push(`and ${mapFilter(column, operator, name)}`); + if (isCohort) { + column = FILTER_COLUMNS[name.slice('cohort_'.length)]; } - if (name === 'referrer') { - arr.push(`and referrer_domain != hostname`); - } - } + if (column) { + if (name === 'eventType') { + arr.push(`and ${mapFilter(column, operator, name, 'UInt32', paramName)}`); + } else { + arr.push(`and ${mapFilter(column, operator, name, 'String', paramName)}`); + } - return arr; - }, []); + if (name === 'referrer') { + arr.push(`and referrer_domain != hostname`); + } + } + + return arr; + }, + [], + ); return query.join('\n'); } @@ -177,13 +187,15 @@ function getDateQuery(filters: Record) { function getQueryParams(filters: Record) { return { ...filters, - ...filtersObjectToArray(filters).reduce((obj, { name, column, operator, value }) => { + ...filtersObjectToArray(filters).reduce((obj, { name, column, operator, value, paramName }) => { const resolvedColumn = column || (name?.startsWith('cohort_') && FILTER_COLUMNS[name.slice('cohort_'.length)]); if (!resolvedColumn || !name || value === undefined) return obj; - obj[name] = ([OPERATORS.equals, OPERATORS.notEquals] as string[]).includes(operator) + const key = paramName ?? name; + + obj[key] = ([OPERATORS.equals, OPERATORS.notEquals] as string[]).includes(operator) ? Array.isArray(value) ? value : [value] diff --git a/src/lib/params.ts b/src/lib/params.ts index bbb52eb3b..f1452254d 100644 --- a/src/lib/params.ts +++ b/src/lib/params.ts @@ -51,15 +51,23 @@ export function filtersObjectToArray(filters: QueryFilters, options: QueryOption return arr; } + const baseName = key.replace(/\d+$/, ''); + const paramName = key !== baseName ? key : undefined; + if (filter?.name && filter?.value !== undefined) { - return arr.concat({ ...filter, column: options?.columns?.[key] ?? FILTER_COLUMNS[key] }); + return arr.concat({ + ...filter, + column: options?.columns?.[baseName] ?? FILTER_COLUMNS[baseName], + paramName: paramName ?? filter.paramName, + }); } const { operator, value } = parseFilterValue(filter); return arr.concat({ - name: key, - column: options?.columns?.[key] ?? FILTER_COLUMNS[key], + name: baseName, + paramName, + column: options?.columns?.[baseName] ?? FILTER_COLUMNS[baseName], operator, value, prefix: options?.prefix, @@ -68,10 +76,14 @@ export function filtersObjectToArray(filters: QueryFilters, options: QueryOption } export function filtersArrayToObject(filters: Filter[]) { + const nameCounts: Record = {}; return filters.reduce((obj, filter: Filter) => { const { name, operator, value } = filter; + const count = nameCounts[name] ?? 0; + const key = count === 0 ? name : `${name}${count}`; + nameCounts[name] = count + 1; - obj[name] = `${operator}.${Array.isArray(value) ? value.join(',') : value}`; + obj[key] = `${operator}.${Array.isArray(value) ? value.join(',') : value}`; return obj; }, {}); diff --git a/src/lib/prisma.ts b/src/lib/prisma.ts index 3d31fcf9b..f10cc041f 100644 --- a/src/lib/prisma.ts +++ b/src/lib/prisma.ts @@ -71,8 +71,15 @@ function getSearchSQL(column: string, param: string = 'search'): string { return `and ${column} ilike {{${param}}}`; } -function mapFilter(column: string, operator: string, name: string, type: string = '') { - const value = `{{${name}${type ? `::${type}` : ''}}}`; +function mapFilter( + column: string, + operator: string, + name: string, + type: string = '', + paramName?: string, +) { + const param = paramName ?? name; + const value = `{{${param}${type ? `::${type}` : ''}}}`; if (name.startsWith('cohort_')) { name = name.slice('cohort_'.length); @@ -100,7 +107,7 @@ function mapFilter(column: string, operator: string, name: string, type: string function getFilterQuery(filters: Record, options: QueryOptions = {}): string { const query = filtersObjectToArray(filters, options).reduce( - (arr, { name, column, operator, prefix = '' }) => { + (arr, { name, column, operator, prefix = '', paramName }) => { const isCohort = options?.isCohort; if (isCohort) { @@ -108,7 +115,7 @@ function getFilterQuery(filters: Record, options: QueryOptions = {} } if (column) { - arr.push(`and ${mapFilter(`${prefix}${column}`, operator, name)}`); + arr.push(`and ${mapFilter(`${prefix}${column}`, operator, name, '', paramName)}`); if (name === 'referrer') { arr.push( @@ -181,18 +188,20 @@ function getDateQuery(filters: Record) { function getQueryParams(filters: Record) { return { ...filters, - ...filtersObjectToArray(filters).reduce((obj, { name, column, operator, value }) => { + ...filtersObjectToArray(filters).reduce((obj, { name, column, operator, value, paramName }) => { const resolvedColumn = column || (name?.startsWith('cohort_') && FILTER_COLUMNS[name.slice('cohort_'.length)]); if (!resolvedColumn) return obj; + const key = paramName ?? name; + if (([OPERATORS.contains, OPERATORS.doesNotContain] as Operator[]).includes(operator)) { - obj[name] = `%${value}%`; + obj[key] = `%${value}%`; } else if (([OPERATORS.equals, OPERATORS.notEquals] as Operator[]).includes(operator)) { - obj[name] = Array.isArray(value) ? value : [value]; + obj[key] = Array.isArray(value) ? value : [value]; } else { - obj[name] = value; + obj[key] = value; } return obj; @@ -201,9 +210,10 @@ function getQueryParams(filters: Record) { } function parseFilters(filters: Record, options?: QueryOptions) { - const joinSession = Object.keys(filters).find(key => - ['referrer', ...SESSION_COLUMNS].includes(key), - ); + const joinSession = Object.keys(filters).find(key => { + const baseName = key.replace(/\d+$/, ''); + return ['referrer', ...SESSION_COLUMNS].includes(baseName); + }); const cohortFilters = Object.fromEntries( Object.entries(filters).filter(([key]) => key.startsWith('cohort_')), diff --git a/src/lib/request.ts b/src/lib/request.ts index e89f5722f..767288feb 100644 --- a/src/lib/request.ts +++ b/src/lib/request.ts @@ -22,12 +22,20 @@ export async function parseRequest( if (schema) { const isGet = request.method === 'GET'; + const rawQuery = query; const result = schema.safeParse(isGet ? query : body); if (!result.success) { error = () => badRequest(z.treeifyError(result.error)); } else if (isGet) { query = result.data; + + // Re-add suffixed filter params (e.g., browser1, os2) stripped by Zod schema + for (const key of Object.keys(rawQuery)) { + if (/\d+$/.test(key) && !(key in query)) { + query[key] = rawQuery[key]; + } + } } else { body = result.data; } @@ -71,10 +79,10 @@ export function getRequestDateRange(query: Record) { export function getRequestFilters(query: Record) { const result: Record = {}; - for (const key of Object.keys(FILTER_COLUMNS)) { - const value = query[key]; - if (value !== undefined) { - result[key] = value; + for (const key of Object.keys(query)) { + const baseName = key.replace(/\d+$/, ''); + if (baseName in FILTER_COLUMNS) { + result[key] = query[key]; } } diff --git a/src/lib/types.ts b/src/lib/types.ts index c089e2303..e722195aa 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -31,6 +31,7 @@ export interface Filter { type?: string; column?: string; prefix?: string; + paramName?: string; } export interface DateRange { From cc1e4438d01eaba4fcb8218610392716ecff0b5d Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Sat, 21 Feb 2026 20:00:43 -0800 Subject: [PATCH 18/22] implement OR logic to filters, segments, cohorts --- public/intl/messages/ar-SA.json | 3 + public/intl/messages/be-BY.json | 3 + public/intl/messages/bg-BG.json | 3 + public/intl/messages/bn-BD.json | 3 + public/intl/messages/bs-BA.json | 3 + public/intl/messages/ca-ES.json | 3 + public/intl/messages/cs-CZ.json | 3 + public/intl/messages/da-DK.json | 3 + public/intl/messages/de-CH.json | 3 + public/intl/messages/de-DE.json | 3 + public/intl/messages/el-GR.json | 3 + public/intl/messages/en-GB.json | 3 + public/intl/messages/en-US.json | 3 + public/intl/messages/es-ES.json | 3 + public/intl/messages/fa-IR.json | 3 + public/intl/messages/fi-FI.json | 3 + public/intl/messages/fo-FO.json | 3 + public/intl/messages/fr-FR.json | 3 + public/intl/messages/ga-ES.json | 3 + public/intl/messages/he-IL.json | 3 + public/intl/messages/hi-IN.json | 3 + public/intl/messages/hr-HR.json | 3 + public/intl/messages/hu-HU.json | 3 + public/intl/messages/id-ID.json | 3 + public/intl/messages/it-IT.json | 3 + public/intl/messages/ja-JP.json | 3 + public/intl/messages/km-KH.json | 3 + public/intl/messages/ko-KR.json | 3 + public/intl/messages/lt-LT.json | 3 + public/intl/messages/mn-MN.json | 3 + public/intl/messages/ms-MY.json | 3 + public/intl/messages/my-MM.json | 3 + public/intl/messages/nb-NO.json | 3 + public/intl/messages/nl-NL.json | 3 + public/intl/messages/pl-PL.json | 3 + public/intl/messages/pt-BR.json | 3 + public/intl/messages/pt-PT.json | 3 + public/intl/messages/ro-RO.json | 3 + public/intl/messages/ru-RU.json | 3 + public/intl/messages/si-LK.json | 3 + public/intl/messages/sk-SK.json | 3 + public/intl/messages/sl-SI.json | 3 + public/intl/messages/sv-SE.json | 3 + public/intl/messages/ta-IN.json | 3 + public/intl/messages/th-TH.json | 3 + public/intl/messages/tr-TR.json | 3 + public/intl/messages/uk-UA.json | 3 + public/intl/messages/ur-PK.json | 3 + public/intl/messages/uz-UZ.json | 3 + public/intl/messages/vi-VN.json | 3 + public/intl/messages/zh-CN.json | 3 + public/intl/messages/zh-TW.json | 3 + .../[websiteId]/cohorts/CohortEditForm.tsx | 36 ++++++++--- .../[websiteId]/segments/SegmentEditForm.tsx | 35 ++++++++--- src/components/hooks/useFilterParameters.ts | 1 + src/components/input/FieldFilters.tsx | 26 +++++++- src/components/input/FilterEditForm.tsx | 22 ++++++- src/components/input/WebsiteFilterButton.tsx | 3 +- src/components/messages.ts | 3 + src/lib/clickhouse.ts | 59 ++++++++++++------- src/lib/prisma.ts | 40 +++++++++---- src/lib/request.ts | 11 ++++ src/lib/schema.ts | 2 + src/lib/types.ts | 3 + 64 files changed, 343 insertions(+), 54 deletions(-) diff --git a/public/intl/messages/ar-SA.json b/public/intl/messages/ar-SA.json index 98f937fed..85ae17623 100644 --- a/public/intl/messages/ar-SA.json +++ b/public/intl/messages/ar-SA.json @@ -171,6 +171,9 @@ "manager": "مدير", "max": "الحد الأقصى", "maximize": "توسيع", + "match": "تطابق", + "match-all": "الكل (AND)", + "match-any": "أي (OR)", "medium": "وسيط", "member": "عضو", "members": "الأعضاء", diff --git a/public/intl/messages/be-BY.json b/public/intl/messages/be-BY.json index 8cbdd1046..ef13ffecf 100644 --- a/public/intl/messages/be-BY.json +++ b/public/intl/messages/be-BY.json @@ -171,6 +171,9 @@ "manager": "Кіраўнік", "max": "Максімум", "maximize": "Разгарнуць", + "match": "Адпаведнасць", + "match-all": "Усе (AND)", + "match-any": "Любы (OR)", "medium": "Сярэдні", "member": "Удзельнік", "members": "Удзельнікі", diff --git a/public/intl/messages/bg-BG.json b/public/intl/messages/bg-BG.json index 2edf2ae76..b7ab4d1b3 100644 --- a/public/intl/messages/bg-BG.json +++ b/public/intl/messages/bg-BG.json @@ -171,6 +171,9 @@ "manager": "Мениджър", "max": "Максимум", "maximize": "Разшири", + "match": "Съвпадение", + "match-all": "Всички (AND)", + "match-any": "Някои (OR)", "medium": "Среден", "member": "Член", "members": "Членове", diff --git a/public/intl/messages/bn-BD.json b/public/intl/messages/bn-BD.json index fcc263cb8..85dd82f2e 100644 --- a/public/intl/messages/bn-BD.json +++ b/public/intl/messages/bn-BD.json @@ -171,6 +171,9 @@ "manager": "পরিচালক", "max": "সর্বাধিক", "maximize": "বিস্তৃত করুন", + "match": "মিলান", + "match-all": "সব (AND)", + "match-any": "যেকোনো (OR)", "medium": "মাঝারি", "member": "সদস্য", "members": "সদস্যগণ", diff --git a/public/intl/messages/bs-BA.json b/public/intl/messages/bs-BA.json index eb55ff438..547ae7836 100644 --- a/public/intl/messages/bs-BA.json +++ b/public/intl/messages/bs-BA.json @@ -171,6 +171,9 @@ "manager": "Menadžer", "max": "Maks", "maximize": "Proširi", + "match": "Podudaranje", + "match-all": "Sve (AND)", + "match-any": "Bilo koje (OR)", "medium": "Srednje", "member": "Član", "members": "Članovi", diff --git a/public/intl/messages/ca-ES.json b/public/intl/messages/ca-ES.json index 30b66451c..e73ba612f 100644 --- a/public/intl/messages/ca-ES.json +++ b/public/intl/messages/ca-ES.json @@ -171,6 +171,9 @@ "manager": "Responsable", "max": "Màx", "maximize": "Expandeix", + "match": "Coincidència", + "match-all": "Tots (AND)", + "match-any": "Qualsevol (OR)", "medium": "Mitjà", "member": "Membre", "members": "Membres", diff --git a/public/intl/messages/cs-CZ.json b/public/intl/messages/cs-CZ.json index eacaee4ac..ac15c67a1 100644 --- a/public/intl/messages/cs-CZ.json +++ b/public/intl/messages/cs-CZ.json @@ -171,6 +171,9 @@ "manager": "Správce", "max": "Max", "maximize": "Rozbalit", + "match": "Shoda", + "match-all": "Vše (AND)", + "match-any": "Jakýkoli (OR)", "medium": "Střední", "member": "Člen", "members": "Členové", diff --git a/public/intl/messages/da-DK.json b/public/intl/messages/da-DK.json index 16e16128d..57fd08376 100644 --- a/public/intl/messages/da-DK.json +++ b/public/intl/messages/da-DK.json @@ -171,6 +171,9 @@ "manager": "Leder", "max": "Maks", "maximize": "Udvid", + "match": "Match", + "match-all": "Alle (AND)", + "match-any": "Enhver (OR)", "medium": "Medie", "member": "Medlem", "members": "Medlemmer", diff --git a/public/intl/messages/de-CH.json b/public/intl/messages/de-CH.json index 6125b2386..f309f9e54 100644 --- a/public/intl/messages/de-CH.json +++ b/public/intl/messages/de-CH.json @@ -171,6 +171,9 @@ "manager": "Verwalter", "max": "Max", "maximize": "Uusklappe", + "match": "Übereinstimmung", + "match-all": "Alle (AND)", + "match-any": "Beliebige (OR)", "medium": "Medium", "member": "Mitglied", "members": "Mitglieder", diff --git a/public/intl/messages/de-DE.json b/public/intl/messages/de-DE.json index c059a1a5c..bf17b131e 100644 --- a/public/intl/messages/de-DE.json +++ b/public/intl/messages/de-DE.json @@ -171,6 +171,9 @@ "manager": "Verwaltung", "max": "Max", "maximize": "Erweitern", + "match": "Übereinstimmung", + "match-all": "Alle (AND)", + "match-any": "Beliebige (OR)", "medium": "Medium", "member": "Mitglied", "members": "Mitglieder", diff --git a/public/intl/messages/el-GR.json b/public/intl/messages/el-GR.json index 4a0b36330..8450f3a6f 100644 --- a/public/intl/messages/el-GR.json +++ b/public/intl/messages/el-GR.json @@ -171,6 +171,9 @@ "manager": "Διαχειριστής", "max": "Μέγ", "maximize": "Expand", + "match": "Αντιστοίχιση", + "match-all": "Όλα (AND)", + "match-any": "Οποιοδήποτε (OR)", "medium": "Μέσο", "member": "Μέλος", "members": "Μέλη", diff --git a/public/intl/messages/en-GB.json b/public/intl/messages/en-GB.json index 33d676e73..57b8ea619 100644 --- a/public/intl/messages/en-GB.json +++ b/public/intl/messages/en-GB.json @@ -171,6 +171,9 @@ "manager": "Manager", "max": "Max", "maximize": "Expand", + "match": "Match", + "match-all": "All (AND)", + "match-any": "Any (OR)", "medium": "Medium", "member": "Member", "members": "Members", diff --git a/public/intl/messages/en-US.json b/public/intl/messages/en-US.json index 9ff141bd7..33704d17d 100644 --- a/public/intl/messages/en-US.json +++ b/public/intl/messages/en-US.json @@ -170,6 +170,9 @@ "manage": "Manage", "manager": "Manager", "max": "Max", + "match": "Match", + "match-all": "All (AND)", + "match-any": "Any (OR)", "maximize": "Maximize", "medium": "Medium", "member": "Member", diff --git a/public/intl/messages/es-ES.json b/public/intl/messages/es-ES.json index 856d6977a..11031f818 100644 --- a/public/intl/messages/es-ES.json +++ b/public/intl/messages/es-ES.json @@ -171,6 +171,9 @@ "manager": "Gerente", "max": "Máximo", "maximize": "Expandir", + "match": "Coincidencia", + "match-all": "Todo (AND)", + "match-any": "Cualquiera (OR)", "medium": "Medio", "member": "Miembro", "members": "Miembros", diff --git a/public/intl/messages/fa-IR.json b/public/intl/messages/fa-IR.json index 49ba05391..ee072c74c 100644 --- a/public/intl/messages/fa-IR.json +++ b/public/intl/messages/fa-IR.json @@ -171,6 +171,9 @@ "manager": "مدیر", "max": "حداکثر", "maximize": "گسترش", + "match": "تطابق", + "match-all": "همه (AND)", + "match-any": "هر (OR)", "medium": "متوسط", "member": "عضو", "members": "اعضا", diff --git a/public/intl/messages/fi-FI.json b/public/intl/messages/fi-FI.json index 7b802535c..63da45902 100644 --- a/public/intl/messages/fi-FI.json +++ b/public/intl/messages/fi-FI.json @@ -171,6 +171,9 @@ "manager": "Päällikkö", "max": "Maksimi", "maximize": "Laajenna", + "match": "Vastaavuus", + "match-all": "Kaikki (AND)", + "match-any": "Mikä tahansa (OR)", "medium": "Keskitaso", "member": "Jäsen", "members": "Jäsenet", diff --git a/public/intl/messages/fo-FO.json b/public/intl/messages/fo-FO.json index c16804397..cc7e17830 100644 --- a/public/intl/messages/fo-FO.json +++ b/public/intl/messages/fo-FO.json @@ -171,6 +171,9 @@ "manager": "Stjóri", "max": "Mest", "maximize": "Víðka", + "match": "Samsvørun", + "match-all": "Allt (AND)", + "match-any": "Nakað (OR)", "medium": "Miðal", "member": "Limur", "members": "Limir", diff --git a/public/intl/messages/fr-FR.json b/public/intl/messages/fr-FR.json index 0954df1f2..79d912d09 100644 --- a/public/intl/messages/fr-FR.json +++ b/public/intl/messages/fr-FR.json @@ -171,6 +171,9 @@ "manager": "Gestionnaire", "max": "Max", "maximize": "Développer", + "match": "Correspondance", + "match-all": "Tous (AND)", + "match-any": "N'importe lequel (OR)", "medium": "Moyen", "member": "Membre", "members": "Membres", diff --git a/public/intl/messages/ga-ES.json b/public/intl/messages/ga-ES.json index 89630c714..80ad90e21 100644 --- a/public/intl/messages/ga-ES.json +++ b/public/intl/messages/ga-ES.json @@ -171,6 +171,9 @@ "manager": "Xestor", "max": "Máx", "maximize": "Expandir", + "match": "Coincidencia", + "match-all": "Todo (AND)", + "match-any": "Calquera (OR)", "medium": "Medio", "member": "Membro", "members": "Membros", diff --git a/public/intl/messages/he-IL.json b/public/intl/messages/he-IL.json index 62c83c35b..63a5f1d4e 100644 --- a/public/intl/messages/he-IL.json +++ b/public/intl/messages/he-IL.json @@ -171,6 +171,9 @@ "manager": "מנהל", "max": "מקסימום", "maximize": "הרחב", + "match": "התאמה", + "match-all": "הכל (AND)", + "match-any": "כלשהו (OR)", "medium": "בינוני", "member": "חבר", "members": "חברים", diff --git a/public/intl/messages/hi-IN.json b/public/intl/messages/hi-IN.json index c8ac7df42..a148cff2c 100644 --- a/public/intl/messages/hi-IN.json +++ b/public/intl/messages/hi-IN.json @@ -171,6 +171,9 @@ "manager": "प्रबंधक", "max": "अधिकतम", "maximize": "विस्तार करें", + "match": "मेल", + "match-all": "सभी (AND)", + "match-any": "कोई भी (OR)", "medium": "मध्यम", "member": "सदस्य", "members": "सदस्यगण", diff --git a/public/intl/messages/hr-HR.json b/public/intl/messages/hr-HR.json index c49a9dcf3..50b5a745d 100644 --- a/public/intl/messages/hr-HR.json +++ b/public/intl/messages/hr-HR.json @@ -171,6 +171,9 @@ "manager": "Upravitelj", "max": "Maksimum", "maximize": "Proširi", + "match": "Podudaranje", + "match-all": "Sve (AND)", + "match-any": "Bilo koje (OR)", "medium": "Srednje", "member": "Član", "members": "Članovi", diff --git a/public/intl/messages/hu-HU.json b/public/intl/messages/hu-HU.json index ce071cc5f..5a72da344 100644 --- a/public/intl/messages/hu-HU.json +++ b/public/intl/messages/hu-HU.json @@ -171,6 +171,9 @@ "manager": "Menedzser", "max": "Maximum", "maximize": "Kibontás", + "match": "Egyezés", + "match-all": "Összes (AND)", + "match-any": "Bármelyik (OR)", "medium": "Közepes", "member": "Tag", "members": "Tagok", diff --git a/public/intl/messages/id-ID.json b/public/intl/messages/id-ID.json index 422bc114b..c3e14b46f 100644 --- a/public/intl/messages/id-ID.json +++ b/public/intl/messages/id-ID.json @@ -171,6 +171,9 @@ "manager": "Manajer", "max": "Maksimum", "maximize": "Perluas", + "match": "Cocok", + "match-all": "Semua (AND)", + "match-any": "Salah satu (OR)", "medium": "Sedang", "member": "Anggota", "members": "Anggota", diff --git a/public/intl/messages/it-IT.json b/public/intl/messages/it-IT.json index 00f83c304..5f1ee153e 100644 --- a/public/intl/messages/it-IT.json +++ b/public/intl/messages/it-IT.json @@ -171,6 +171,9 @@ "manager": "Gestore", "max": "Massimo", "maximize": "Espandi", + "match": "Corrispondenza", + "match-all": "Tutti (AND)", + "match-any": "Qualsiasi (OR)", "medium": "Medio", "member": "Membro", "members": "Membri", diff --git a/public/intl/messages/ja-JP.json b/public/intl/messages/ja-JP.json index 2c2347ffd..d8d9dbc49 100644 --- a/public/intl/messages/ja-JP.json +++ b/public/intl/messages/ja-JP.json @@ -171,6 +171,9 @@ "manager": "管理者", "max": "最大", "maximize": "展開", + "match": "一致", + "match-all": "すべて (AND)", + "match-any": "いずれか (OR)", "medium": "メディア", "member": "メンバー", "members": "メンバー", diff --git a/public/intl/messages/km-KH.json b/public/intl/messages/km-KH.json index a8bcb040d..0a13399d7 100644 --- a/public/intl/messages/km-KH.json +++ b/public/intl/messages/km-KH.json @@ -171,6 +171,9 @@ "manager": "អ្នកគ្រប់គ្រង", "max": "អតិបរមា", "maximize": "ពង្រីក", + "match": "ត្រូវគ្នា", + "match-all": "ទាំងអស់ (AND)", + "match-any": "ណាមួយ (OR)", "medium": "មធ្យម", "member": "សមាជិក", "members": "សមាជិក", diff --git a/public/intl/messages/ko-KR.json b/public/intl/messages/ko-KR.json index 45ce769a8..d88da6ad1 100644 --- a/public/intl/messages/ko-KR.json +++ b/public/intl/messages/ko-KR.json @@ -171,6 +171,9 @@ "manager": "관리자", "max": "최대", "maximize": "확장", + "match": "일치", + "match-all": "전체 (AND)", + "match-any": "일부 (OR)", "medium": "미디엄", "member": "멤버", "members": "멤버", diff --git a/public/intl/messages/lt-LT.json b/public/intl/messages/lt-LT.json index 9ff1d6a33..34ee0d025 100644 --- a/public/intl/messages/lt-LT.json +++ b/public/intl/messages/lt-LT.json @@ -171,6 +171,9 @@ "manager": "Vadovas", "max": "Maksimumas", "maximize": "Išplėsti", + "match": "Atitikimas", + "match-all": "Visi (AND)", + "match-any": "Bet kuris (OR)", "medium": "Vidutinis", "member": "Narys", "members": "Nariai", diff --git a/public/intl/messages/mn-MN.json b/public/intl/messages/mn-MN.json index a8e270509..100c385f5 100644 --- a/public/intl/messages/mn-MN.json +++ b/public/intl/messages/mn-MN.json @@ -171,6 +171,9 @@ "manager": "Удирдагч", "max": "Дээд", "maximize": "Өргөтгөх", + "match": "Тохирох", + "match-all": "Бүгд (AND)", + "match-any": "Ямар ч (OR)", "medium": "Дунд", "member": "Гишүүн", "members": "Гишүүд", diff --git a/public/intl/messages/ms-MY.json b/public/intl/messages/ms-MY.json index 760224217..ecc282cab 100644 --- a/public/intl/messages/ms-MY.json +++ b/public/intl/messages/ms-MY.json @@ -171,6 +171,9 @@ "manager": "Pengurus", "max": "Maks", "maximize": "Expand", + "match": "Padanan", + "match-all": "Semua (AND)", + "match-any": "Mana-mana (OR)", "medium": "Medium", "member": "Ahli", "members": "Ahli", diff --git a/public/intl/messages/my-MM.json b/public/intl/messages/my-MM.json index d31ebdb25..88e966ac4 100644 --- a/public/intl/messages/my-MM.json +++ b/public/intl/messages/my-MM.json @@ -171,6 +171,9 @@ "manager": "မန်နေဂျာ", "max": "အများဆုံး", "maximize": "Expand", + "match": "ကိုက်ညီ", + "match-all": "အားလုံး (AND)", + "match-any": "တစ်ခုခု (OR)", "medium": "မီဒီယမ်", "member": "အဖွဲ့ဝင်", "members": "အဖွဲ့ဝင်များ", diff --git a/public/intl/messages/nb-NO.json b/public/intl/messages/nb-NO.json index c0007cd3d..1296ee814 100644 --- a/public/intl/messages/nb-NO.json +++ b/public/intl/messages/nb-NO.json @@ -171,6 +171,9 @@ "manager": "Administrator", "max": "Maks", "maximize": "Utvid", + "match": "Samsvar", + "match-all": "Alle (AND)", + "match-any": "Enhver (OR)", "medium": "Medium", "member": "Bruker", "members": "Brukere", diff --git a/public/intl/messages/nl-NL.json b/public/intl/messages/nl-NL.json index cf56e8b8d..69818e3a8 100644 --- a/public/intl/messages/nl-NL.json +++ b/public/intl/messages/nl-NL.json @@ -171,6 +171,9 @@ "manager": "Beheerder", "max": "Max", "maximize": "Uitvouwen", + "match": "Overeenkomst", + "match-all": "Alle (AND)", + "match-any": "Elk (OR)", "medium": "Medium", "member": "Gebruiker", "members": "Gebruikers", diff --git a/public/intl/messages/pl-PL.json b/public/intl/messages/pl-PL.json index 1f486cb55..dad1f2327 100644 --- a/public/intl/messages/pl-PL.json +++ b/public/intl/messages/pl-PL.json @@ -171,6 +171,9 @@ "manager": "Menedżer", "max": "Maks", "maximize": "Rozwiń", + "match": "Dopasowanie", + "match-all": "Wszystkie (AND)", + "match-any": "Dowolny (OR)", "medium": "Medium", "member": "Członek", "members": "Członkowie", diff --git a/public/intl/messages/pt-BR.json b/public/intl/messages/pt-BR.json index 282981df4..8ccfa3991 100644 --- a/public/intl/messages/pt-BR.json +++ b/public/intl/messages/pt-BR.json @@ -171,6 +171,9 @@ "manager": "Gerente", "max": "Máximo", "maximize": "Expandir", + "match": "Correspondência", + "match-all": "Todos (AND)", + "match-any": "Qualquer (OR)", "medium": "Médio", "member": "Membro", "members": "Membros", diff --git a/public/intl/messages/pt-PT.json b/public/intl/messages/pt-PT.json index 907d8e4f2..4b52892c3 100644 --- a/public/intl/messages/pt-PT.json +++ b/public/intl/messages/pt-PT.json @@ -171,6 +171,9 @@ "manager": "Gestor", "max": "Máximo", "maximize": "Expandir", + "match": "Correspondência", + "match-all": "Todos (AND)", + "match-any": "Qualquer (OR)", "medium": "Médio", "member": "Membro", "members": "Membros", diff --git a/public/intl/messages/ro-RO.json b/public/intl/messages/ro-RO.json index b81556524..86c804777 100644 --- a/public/intl/messages/ro-RO.json +++ b/public/intl/messages/ro-RO.json @@ -171,6 +171,9 @@ "manager": "Manager", "max": "Max", "maximize": "Extinde", + "match": "Potrivire", + "match-all": "Toate (AND)", + "match-any": "Oricare (OR)", "medium": "Mediu", "member": "Membru", "members": "Membri", diff --git a/public/intl/messages/ru-RU.json b/public/intl/messages/ru-RU.json index 10096a5dc..8296e160f 100644 --- a/public/intl/messages/ru-RU.json +++ b/public/intl/messages/ru-RU.json @@ -171,6 +171,9 @@ "manager": "Менеджер", "max": "Максимум", "maximize": "Развернуть", + "match": "Соответствие", + "match-all": "Все (AND)", + "match-any": "Любой (OR)", "medium": "Средний", "member": "Участник", "members": "Участники", diff --git a/public/intl/messages/si-LK.json b/public/intl/messages/si-LK.json index cb2b6163e..5aa2bd89a 100644 --- a/public/intl/messages/si-LK.json +++ b/public/intl/messages/si-LK.json @@ -171,6 +171,9 @@ "manager": "කළමනාකරු", "max": "උපරිම", "maximize": "Expand", + "match": "ගැළපීම", + "match-all": "සියල්ල (AND)", + "match-any": "ඕනෑම (OR)", "medium": "මාධ්‍යය", "member": "සාමාජිකයා", "members": "සාමාජිකයින්", diff --git a/public/intl/messages/sk-SK.json b/public/intl/messages/sk-SK.json index f3424a3ee..f51951f93 100644 --- a/public/intl/messages/sk-SK.json +++ b/public/intl/messages/sk-SK.json @@ -171,6 +171,9 @@ "manager": "Manažér", "max": "Maximum", "maximize": "Rozbaliť", + "match": "Zhoda", + "match-all": "Všetky (AND)", + "match-any": "Akýkoľvek (OR)", "medium": "Stredný", "member": "Člen", "members": "Členovia", diff --git a/public/intl/messages/sl-SI.json b/public/intl/messages/sl-SI.json index 34d9d731f..cea57d48e 100644 --- a/public/intl/messages/sl-SI.json +++ b/public/intl/messages/sl-SI.json @@ -171,6 +171,9 @@ "manager": "Upravitelj", "max": "Največ", "maximize": "Povečaj", + "match": "Ujemanje", + "match-all": "Vse (AND)", + "match-any": "Katero koli (OR)", "medium": "Medij", "member": "Član", "members": "Člani", diff --git a/public/intl/messages/sv-SE.json b/public/intl/messages/sv-SE.json index a39bbeb0e..e8f842e3e 100644 --- a/public/intl/messages/sv-SE.json +++ b/public/intl/messages/sv-SE.json @@ -171,6 +171,9 @@ "manager": "Ansvarig", "max": "Max", "maximize": "Expandera", + "match": "Matchning", + "match-all": "Alla (AND)", + "match-any": "Vilken som helst (OR)", "medium": "Medium", "member": "Medlem", "members": "Medlemmar", diff --git a/public/intl/messages/ta-IN.json b/public/intl/messages/ta-IN.json index 9d7fe5b16..6cf4388fa 100644 --- a/public/intl/messages/ta-IN.json +++ b/public/intl/messages/ta-IN.json @@ -171,6 +171,9 @@ "manager": "மேலாளர்", "max": "அதிகபட்சம்", "maximize": "Expand", + "match": "பொருத்தம்", + "match-all": "அனைத்தும் (AND)", + "match-any": "எதுவும் (OR)", "medium": "ஊடகம்", "member": "உறுப்பினர்", "members": "உறுப்பினர்கள்", diff --git a/public/intl/messages/th-TH.json b/public/intl/messages/th-TH.json index 5af2e6713..168cc057a 100644 --- a/public/intl/messages/th-TH.json +++ b/public/intl/messages/th-TH.json @@ -171,6 +171,9 @@ "manager": "ผู้จัดการ", "max": "สูงสุด", "maximize": "Expand", + "match": "จับคู่", + "match-all": "ทั้งหมด (AND)", + "match-any": "ใดๆ (OR)", "medium": "สื่อ", "member": "สมาชิก", "members": "สมาชิก", diff --git a/public/intl/messages/tr-TR.json b/public/intl/messages/tr-TR.json index 667da45bf..139aee6af 100644 --- a/public/intl/messages/tr-TR.json +++ b/public/intl/messages/tr-TR.json @@ -171,6 +171,9 @@ "manager": "Yönetici", "max": "Maks", "maximize": "Genişlet", + "match": "Eşleşme", + "match-all": "Tümü (AND)", + "match-any": "Herhangi (OR)", "medium": "Orta", "member": "Üye", "members": "Üyeler", diff --git a/public/intl/messages/uk-UA.json b/public/intl/messages/uk-UA.json index 5d83a9aa2..5f78c2bfe 100644 --- a/public/intl/messages/uk-UA.json +++ b/public/intl/messages/uk-UA.json @@ -171,6 +171,9 @@ "manager": "Менеджер", "max": "Макс.", "maximize": "Розгорнути", + "match": "Відповідність", + "match-all": "Усі (AND)", + "match-any": "Будь-який (OR)", "medium": "Середній", "member": "Учасник", "members": "Учасники", diff --git a/public/intl/messages/ur-PK.json b/public/intl/messages/ur-PK.json index 0e03241fc..a1d07dbe2 100644 --- a/public/intl/messages/ur-PK.json +++ b/public/intl/messages/ur-PK.json @@ -171,6 +171,9 @@ "manager": "منتظم", "max": "زیادہ سے زیادہ", "maximize": "Expand", + "match": "مطابقت", + "match-all": "سب (AND)", + "match-any": "کوئی بھی (OR)", "medium": "میڈیم", "member": "رکن", "members": "اراکین", diff --git a/public/intl/messages/uz-UZ.json b/public/intl/messages/uz-UZ.json index b2b60d5b7..de0ad0085 100644 --- a/public/intl/messages/uz-UZ.json +++ b/public/intl/messages/uz-UZ.json @@ -171,6 +171,9 @@ "manager": "Menejer", "max": "Maksimal", "maximize": "Kattalashtirish", + "match": "Moslik", + "match-all": "Barchasi (AND)", + "match-any": "Istalgan (OR)", "medium": "Vosita", "member": "A'zo", "members": "A'zolar", diff --git a/public/intl/messages/vi-VN.json b/public/intl/messages/vi-VN.json index eed6aa8dc..2b9514fc4 100644 --- a/public/intl/messages/vi-VN.json +++ b/public/intl/messages/vi-VN.json @@ -171,6 +171,9 @@ "manager": "Quản lý", "max": "Tối đa", "maximize": "Phóng to", + "match": "Khớp", + "match-all": "Tất cả (AND)", + "match-any": "Bất kỳ (OR)", "medium": "Phương tiện", "member": "Thành viên", "members": "Các thành viên", diff --git a/public/intl/messages/zh-CN.json b/public/intl/messages/zh-CN.json index 8f1469a3a..4d65d885f 100644 --- a/public/intl/messages/zh-CN.json +++ b/public/intl/messages/zh-CN.json @@ -171,6 +171,9 @@ "manager": "管理者", "max": "最大", "maximize": "展开", + "match": "匹配", + "match-all": "全部 (AND)", + "match-any": "任意 (OR)", "medium": "中等", "member": "成员", "members": "成员", diff --git a/public/intl/messages/zh-TW.json b/public/intl/messages/zh-TW.json index 57cd293c1..05d304f4b 100644 --- a/public/intl/messages/zh-TW.json +++ b/public/intl/messages/zh-TW.json @@ -171,6 +171,9 @@ "manager": "管理者", "max": "最大值", "maximize": "Expand", + "match": "符合", + "match-all": "全部 (AND)", + "match-any": "任意 (OR)", "medium": "媒介", "member": "成員", "members": "成員", diff --git a/src/app/(main)/websites/[websiteId]/cohorts/CohortEditForm.tsx b/src/app/(main)/websites/[websiteId]/cohorts/CohortEditForm.tsx index dbce37df8..8ad13549d 100644 --- a/src/app/(main)/websites/[websiteId]/cohorts/CohortEditForm.tsx +++ b/src/app/(main)/websites/[websiteId]/cohorts/CohortEditForm.tsx @@ -10,6 +10,7 @@ import { Loading, TextField, } from '@umami/react-zen'; +import { useEffect, useState } from 'react'; import { useMessages, useUpdateQuery, useWebsiteCohortQuery } from '@/components/hooks'; import { ActionSelect } from '@/components/input/ActionSelect'; import { DateFilter } from '@/components/input/DateFilter'; @@ -32,6 +33,11 @@ export function CohortEditForm({ }) { const { data } = useWebsiteCohortQuery(websiteId, cohortId); const { t, labels, messages, getErrorMessage } = useMessages(); + const [currentMatch, setCurrentMatch] = useState('all'); + + useEffect(() => { + setCurrentMatch((data?.parameters as any)?.match || 'all'); + }, [data]); const { mutateAsync, error, isPending, touch, toast } = useUpdateQuery( `/websites/${websiteId}/segments${cohortId ? `/${cohortId}` : ''}`, @@ -41,14 +47,23 @@ export function CohortEditForm({ ); const handleSubmit = async (formData: any) => { - await mutateAsync(formData, { - onSuccess: async () => { - toast(t(messages.saved)); - touch('cohorts'); - onSave?.(); - onClose?.(); + await mutateAsync( + { + ...formData, + parameters: { + ...formData.parameters, + match: currentMatch !== 'all' ? currentMatch : undefined, + }, }, - }); + { + onSuccess: async () => { + toast(t(messages.saved)); + touch('cohorts'); + onSave?.(); + onClose?.(); + }, + }, + ); }; if (cohortId && !data) { @@ -105,7 +120,12 @@ export function CohortEditForm({ - + diff --git a/src/app/(main)/websites/[websiteId]/segments/SegmentEditForm.tsx b/src/app/(main)/websites/[websiteId]/segments/SegmentEditForm.tsx index 5798351ac..553c0c9b6 100644 --- a/src/app/(main)/websites/[websiteId]/segments/SegmentEditForm.tsx +++ b/src/app/(main)/websites/[websiteId]/segments/SegmentEditForm.tsx @@ -8,6 +8,7 @@ import { Loading, TextField, } from '@umami/react-zen'; +import { useEffect, useState } from 'react'; import { useMessages, useUpdateQuery, useWebsiteSegmentQuery } from '@/components/hooks'; import { FieldFilters } from '@/components/input/FieldFilters'; @@ -28,6 +29,11 @@ export function SegmentEditForm({ }) { const { data } = useWebsiteSegmentQuery(websiteId, segmentId); const { t, labels, messages, getErrorMessage } = useMessages(); + const [currentMatch, setCurrentMatch] = useState('all'); + + useEffect(() => { + setCurrentMatch((data?.parameters as any)?.match || 'all'); + }, [data]); const { mutateAsync, error, isPending, touch, toast } = useUpdateQuery( `/websites/${websiteId}/segments${segmentId ? `/${segmentId}` : ''}`, @@ -37,14 +43,23 @@ export function SegmentEditForm({ ); const handleSubmit = async (formData: any) => { - await mutateAsync(formData, { - onSuccess: async () => { - toast(t(messages.saved)); - touch('segments'); - onSave?.(); - onClose?.(); + await mutateAsync( + { + ...formData, + parameters: { + ...formData.parameters, + match: currentMatch !== 'all' ? currentMatch : undefined, + }, }, - }); + { + onSuccess: async () => { + toast(t(messages.saved)); + touch('segments'); + onSave?.(); + onClose?.(); + }, + }, + ); }; if (segmentId && !data) { @@ -64,7 +79,11 @@ export function SegmentEditForm({ <> - + )} diff --git a/src/components/hooks/useFilterParameters.ts b/src/components/hooks/useFilterParameters.ts index b4b9391b9..3579bef95 100644 --- a/src/components/hooks/useFilterParameters.ts +++ b/src/components/hooks/useFilterParameters.ts @@ -21,6 +21,7 @@ export function useFilterParameters() { segment: query.segment, cohort: query.cohort, excludeBounce: query.excludeBounce, + match: query.match, page: query.page, pageSize: query.pageSize, }; diff --git a/src/components/input/FieldFilters.tsx b/src/components/input/FieldFilters.tsx index 0d4aaf035..ec8d63241 100644 --- a/src/components/input/FieldFilters.tsx +++ b/src/components/input/FieldFilters.tsx @@ -3,6 +3,7 @@ import { Column, Grid, Icon, + Label, List, ListItem, ListSection, @@ -12,6 +13,7 @@ import { MenuTrigger, Popover, Row, + Select, } from '@umami/react-zen'; import { endOfDay, subMonths } from 'date-fns'; import type { Key } from 'react'; @@ -24,11 +26,20 @@ export interface FieldFiltersProps { websiteId: string; value?: { name: string; operator: string; value: string }[]; exclude?: string[]; + match?: string; onChange?: (data: any) => void; + onMatchChange?: (match: string) => void; } -export function FieldFilters({ websiteId, value, exclude = [], onChange }: FieldFiltersProps) { - const { t, messages } = useMessages(); +export function FieldFilters({ + websiteId, + value, + exclude = [], + match = 'all', + onChange, + onMatchChange, +}: FieldFiltersProps) { + const { t, labels, messages } = useMessages(); const { fields, groupLabels } = useFields(); const startDate = subMonths(endOfDay(new Date()), 6); const endDate = endOfDay(new Date()); @@ -126,6 +137,17 @@ export function FieldFilters({ websiteId, value, exclude = [], onChange }: Field + {onMatchChange && ( + + + + + + + )} {value.map((filter, index) => { return ( void; + onChange?: (params: { + filters: any[]; + segment?: string; + cohort?: string; + match?: string; + }) => void; onClose?: () => void; } export function FilterEditForm({ websiteId, onChange, onClose }: FilterEditFormProps) { const { - query: { segment, cohort }, + query: { segment, cohort, match }, pathname, } = useNavigation(); const { filters } = useFilters(); @@ -20,6 +25,7 @@ export function FilterEditForm({ websiteId, onChange, onClose }: FilterEditFormP const [currentFilters, setCurrentFilters] = useState(filters); const [currentSegment, setCurrentSegment] = useState(segment); const [currentCohort, setCurrentCohort] = useState(cohort); + const [currentMatch, setCurrentMatch] = useState(match || 'all'); const { isMobile } = useMobile(); const excludeFilters = pathname.includes('/pixels') || pathname.includes('/links'); const excludeEvent = !pathname.endsWith('/events'); @@ -28,6 +34,7 @@ export function FilterEditForm({ websiteId, onChange, onClose }: FilterEditFormP setCurrentFilters([]); setCurrentSegment(undefined); setCurrentCohort(undefined); + setCurrentMatch('all'); }; const handleSave = () => { @@ -35,6 +42,7 @@ export function FilterEditForm({ websiteId, onChange, onClose }: FilterEditFormP filters: currentFilters.filter(f => f.value), segment: currentSegment, cohort: currentCohort, + match: currentMatch !== 'all' ? currentMatch : undefined, }); onClose?.(); }; @@ -61,7 +69,9 @@ export function FilterEditForm({ websiteId, onChange, onClose }: FilterEditFormP {t(labels.reset)} - diff --git a/src/components/input/WebsiteFilterButton.tsx b/src/components/input/WebsiteFilterButton.tsx index c558374ec..e2484727a 100644 --- a/src/components/input/WebsiteFilterButton.tsx +++ b/src/components/input/WebsiteFilterButton.tsx @@ -19,13 +19,14 @@ export function WebsiteFilterButton({ const isOverview = /^\/teams\/[^/]+\/websites\/[^/]+$/.test(pathname) || /^\/share\/[^/]+$/.test(pathname); - const handleChange = ({ filters, segment, cohort }: any) => { + const handleChange = ({ filters, segment, cohort, match }: any) => { const params = filtersArrayToObject(filters); const url = updateParams({ ...params, segment, cohort, + match, excludeBounce: excludeBounce ? 'true' : undefined, }); diff --git a/src/components/messages.ts b/src/components/messages.ts index a0c6f9172..f3ee22834 100644 --- a/src/components/messages.ts +++ b/src/components/messages.ts @@ -305,6 +305,9 @@ export const labels: Record = { other: 'label.other', boards: 'label.boards', apply: 'label.apply', + match: 'label.match', + matchAll: 'label.match-all', + matchAny: 'label.match-any', link: 'label.link', links: 'label.links', pixel: 'label.pixel', diff --git a/src/lib/clickhouse.ts b/src/lib/clickhouse.ts index cbe5022d1..b6a655d47 100644 --- a/src/lib/clickhouse.ts +++ b/src/lib/clickhouse.ts @@ -99,32 +99,44 @@ function mapFilter( } function getFilterQuery(filters: Record, options: QueryOptions = {}) { - const query = filtersObjectToArray(filters, options).reduce( - (arr, { name, column, operator, paramName }) => { - const isCohort = options?.isCohort; + const { isCohort, cohortMatch, cohortActionName } = options; + const isOr = isCohort ? cohortMatch === 'any' : filters.match === 'any'; + const orClauses: string[] = []; + const andClauses: string[] = []; - if (isCohort) { - column = FILTER_COLUMNS[name.slice('cohort_'.length)]; + filtersObjectToArray(filters, options).forEach(({ name, column, operator, paramName }) => { + if (isCohort) { + column = FILTER_COLUMNS[name.slice('cohort_'.length)]; + } + + if (column) { + const isAlwaysAnd = name === 'eventType' || (isCohort && name === cohortActionName); + + if (isAlwaysAnd) { + andClauses.push( + `and ${mapFilter(column, operator, name, name === 'eventType' ? 'UInt32' : 'String', paramName)}`, + ); + } else if (isOr) { + orClauses.push(mapFilter(column, operator, name, 'String', paramName)); + } else { + andClauses.push(`and ${mapFilter(column, operator, name, 'String', paramName)}`); } - if (column) { - if (name === 'eventType') { - arr.push(`and ${mapFilter(column, operator, name, 'UInt32', paramName)}`); - } else { - arr.push(`and ${mapFilter(column, operator, name, 'String', paramName)}`); - } - - if (name === 'referrer') { - arr.push(`and referrer_domain != hostname`); - } + if (name === 'referrer') { + andClauses.push(`and referrer_domain != hostname`); } + } + }); - return arr; - }, - [], - ); + const parts: string[] = []; - return query.join('\n'); + if (orClauses.length > 0) { + parts.push(`and (\n ${orClauses.join('\n or ')}\n)`); + } + + parts.push(...andClauses); + + return parts.join('\n'); } function getCohortQuery(filters: Record) { @@ -132,7 +144,10 @@ function getCohortQuery(filters: Record) { return ''; } - const filterQuery = getFilterQuery(filters, { isCohort: true }); + const cohortMatch = filters.cohort_match; + const cohortActionName = filters.cohort_actionName; + + const filterQuery = getFilterQuery(filters, { isCohort: true, cohortMatch, cohortActionName }); return `join ( select distinct session_id @@ -267,7 +282,7 @@ async function rawQuery( output_format_json_quote_64bit_integers: 0, }, }); - + console.log(query, params); return (await resultSet.json()) as T; } diff --git a/src/lib/prisma.ts b/src/lib/prisma.ts index f10cc041f..19fd421ec 100644 --- a/src/lib/prisma.ts +++ b/src/lib/prisma.ts @@ -106,30 +106,47 @@ function mapFilter( } function getFilterQuery(filters: Record, options: QueryOptions = {}): string { - const query = filtersObjectToArray(filters, options).reduce( - (arr, { name, column, operator, prefix = '', paramName }) => { - const isCohort = options?.isCohort; + const { isCohort, cohortMatch, cohortActionName } = options; + const isOr = isCohort ? cohortMatch === 'any' : filters.match === 'any'; + const orClauses: string[] = []; + const andClauses: string[] = []; + filtersObjectToArray(filters, options).forEach( + ({ name, column, operator, prefix = '', paramName }) => { if (isCohort) { column = FILTER_COLUMNS[name.slice('cohort_'.length)]; } if (column) { - arr.push(`and ${mapFilter(`${prefix}${column}`, operator, name, '', paramName)}`); + const clause = mapFilter(`${prefix}${column}`, operator, name, '', paramName); + const isAlwaysAnd = name === 'eventType' || (isCohort && name === cohortActionName); + + if (isAlwaysAnd) { + andClauses.push(`and ${clause}`); + } else if (isOr) { + orClauses.push(clause); + } else { + andClauses.push(`and ${clause}`); + } if (name === 'referrer') { - arr.push( + andClauses.push( `and (website_event.referrer_domain != regexp_replace(website_event.hostname, '^www.', '') or website_event.referrer_domain is null)`, ); } } - - return arr; }, - [], ); - return query.join('\n'); + const parts: string[] = []; + + if (orClauses.length > 0) { + parts.push(`and (\n ${orClauses.join('\n or ')}\n)`); + } + + parts.push(...andClauses); + + return parts.join('\n'); } function getCohortQuery(filters: QueryFilters = {}) { @@ -137,7 +154,10 @@ function getCohortQuery(filters: QueryFilters = {}) { return ''; } - const filterQuery = getFilterQuery(filters, { isCohort: true }); + const cohortMatch = (filters as any).cohort_match; + const cohortActionName = (filters as any).cohort_actionName; + + const filterQuery = getFilterQuery(filters, { isCohort: true, cohortMatch, cohortActionName }); return `join (select distinct website_event.session_id diff --git a/src/lib/request.ts b/src/lib/request.ts index 767288feb..69f6eb1d7 100644 --- a/src/lib/request.ts +++ b/src/lib/request.ts @@ -115,6 +115,8 @@ export async function getQueryFilters( const dateRange = getRequestDateRange(params); const filters = getRequestFilters(params); + let match = params?.match; + if (websiteId) { await setWebsiteDate(websiteId, dateRange); @@ -123,6 +125,10 @@ export async function getQueryFilters( ?.parameters as Record; Object.assign(filters, filtersArrayToObject(segmentParams.filters)); + + if (segmentParams.match) { + match = segmentParams.match; + } } if (params.cohort) { @@ -146,6 +152,10 @@ export async function getQueryFilters( ...filtersArrayToObject(cohortFilters), cohort_startDate: startDate, cohort_endDate: endDate, + ...(cohortParams.match && { + cohort_match: cohortParams.match, + cohort_actionName: `cohort_${cohortParams.action.type}`, + }), }); } @@ -157,6 +167,7 @@ export async function getQueryFilters( return { ...dateRange, ...filters, + match, page: params?.page, pageSize: params?.pageSize ? params?.pageSize || DEFAULT_PAGE_SIZE : undefined, orderBy: params?.orderBy, diff --git a/src/lib/schema.ts b/src/lib/schema.ts index 41cfc70f9..1755d4fa1 100644 --- a/src/lib/schema.ts +++ b/src/lib/schema.ts @@ -67,6 +67,7 @@ export const filterParams = { cohort: z.uuid().optional(), eventType: z.coerce.number().int().positive().optional(), excludeBounce: z.string().optional(), + match: z.enum(['all', 'any']).optional(), }; export const searchParams = { @@ -295,6 +296,7 @@ export const segmentParamSchema = z.object({ }), ) .optional(), + match: z.enum(['all', 'any']).optional(), dateRange: z.string().optional(), action: z .object({ diff --git a/src/lib/types.ts b/src/lib/types.ts index e722195aa..caa3e1e73 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -53,6 +53,8 @@ export interface QueryOptions { limit?: number; prefix?: string; isCohort?: boolean; + cohortMatch?: string; + cohortActionName?: string; } export interface QueryFilters @@ -93,6 +95,7 @@ export interface FilterParams { cohort?: string; compare?: string; excludeBounce?: boolean; + match?: 'all' | 'any'; } export interface SortParams { From 68fdc1c147b12c09e7d2d20a1a097b1de16f6153 Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Sat, 21 Feb 2026 21:37:29 -0800 Subject: [PATCH 19/22] update translations remove AND/OR. not needed --- public/intl/messages/ar-SA.json | 4 ++-- public/intl/messages/be-BY.json | 4 ++-- public/intl/messages/bg-BG.json | 4 ++-- public/intl/messages/bn-BD.json | 4 ++-- public/intl/messages/bs-BA.json | 4 ++-- public/intl/messages/ca-ES.json | 4 ++-- public/intl/messages/cs-CZ.json | 4 ++-- public/intl/messages/da-DK.json | 4 ++-- public/intl/messages/de-CH.json | 4 ++-- public/intl/messages/de-DE.json | 4 ++-- public/intl/messages/el-GR.json | 4 ++-- public/intl/messages/en-GB.json | 4 ++-- public/intl/messages/en-US.json | 4 ++-- public/intl/messages/es-ES.json | 4 ++-- public/intl/messages/fa-IR.json | 4 ++-- public/intl/messages/fi-FI.json | 4 ++-- public/intl/messages/fo-FO.json | 4 ++-- public/intl/messages/fr-FR.json | 4 ++-- public/intl/messages/ga-ES.json | 4 ++-- public/intl/messages/he-IL.json | 4 ++-- public/intl/messages/hi-IN.json | 4 ++-- public/intl/messages/hr-HR.json | 4 ++-- public/intl/messages/hu-HU.json | 4 ++-- public/intl/messages/id-ID.json | 4 ++-- public/intl/messages/it-IT.json | 4 ++-- public/intl/messages/ja-JP.json | 4 ++-- public/intl/messages/km-KH.json | 4 ++-- public/intl/messages/ko-KR.json | 4 ++-- public/intl/messages/lt-LT.json | 4 ++-- public/intl/messages/mn-MN.json | 4 ++-- public/intl/messages/ms-MY.json | 4 ++-- public/intl/messages/my-MM.json | 4 ++-- public/intl/messages/nb-NO.json | 4 ++-- public/intl/messages/nl-NL.json | 4 ++-- public/intl/messages/pl-PL.json | 4 ++-- public/intl/messages/pt-BR.json | 4 ++-- public/intl/messages/pt-PT.json | 4 ++-- public/intl/messages/ro-RO.json | 4 ++-- public/intl/messages/ru-RU.json | 4 ++-- public/intl/messages/si-LK.json | 4 ++-- public/intl/messages/sk-SK.json | 4 ++-- public/intl/messages/sl-SI.json | 4 ++-- public/intl/messages/sv-SE.json | 4 ++-- public/intl/messages/ta-IN.json | 4 ++-- public/intl/messages/th-TH.json | 4 ++-- public/intl/messages/tr-TR.json | 4 ++-- public/intl/messages/uk-UA.json | 4 ++-- public/intl/messages/ur-PK.json | 4 ++-- public/intl/messages/uz-UZ.json | 4 ++-- public/intl/messages/vi-VN.json | 4 ++-- public/intl/messages/zh-CN.json | 4 ++-- public/intl/messages/zh-TW.json | 4 ++-- 52 files changed, 104 insertions(+), 104 deletions(-) diff --git a/public/intl/messages/ar-SA.json b/public/intl/messages/ar-SA.json index 85ae17623..f659c1ff5 100644 --- a/public/intl/messages/ar-SA.json +++ b/public/intl/messages/ar-SA.json @@ -172,8 +172,8 @@ "max": "الحد الأقصى", "maximize": "توسيع", "match": "تطابق", - "match-all": "الكل (AND)", - "match-any": "أي (OR)", + "match-all": "الكل", + "match-any": "أي", "medium": "وسيط", "member": "عضو", "members": "الأعضاء", diff --git a/public/intl/messages/be-BY.json b/public/intl/messages/be-BY.json index ef13ffecf..0ee8f02be 100644 --- a/public/intl/messages/be-BY.json +++ b/public/intl/messages/be-BY.json @@ -172,8 +172,8 @@ "max": "Максімум", "maximize": "Разгарнуць", "match": "Адпаведнасць", - "match-all": "Усе (AND)", - "match-any": "Любы (OR)", + "match-all": "Усе", + "match-any": "Любы", "medium": "Сярэдні", "member": "Удзельнік", "members": "Удзельнікі", diff --git a/public/intl/messages/bg-BG.json b/public/intl/messages/bg-BG.json index b7ab4d1b3..a25a30ed6 100644 --- a/public/intl/messages/bg-BG.json +++ b/public/intl/messages/bg-BG.json @@ -172,8 +172,8 @@ "max": "Максимум", "maximize": "Разшири", "match": "Съвпадение", - "match-all": "Всички (AND)", - "match-any": "Някои (OR)", + "match-all": "Всички", + "match-any": "Някои", "medium": "Среден", "member": "Член", "members": "Членове", diff --git a/public/intl/messages/bn-BD.json b/public/intl/messages/bn-BD.json index 85dd82f2e..77e82322e 100644 --- a/public/intl/messages/bn-BD.json +++ b/public/intl/messages/bn-BD.json @@ -172,8 +172,8 @@ "max": "সর্বাধিক", "maximize": "বিস্তৃত করুন", "match": "মিলান", - "match-all": "সব (AND)", - "match-any": "যেকোনো (OR)", + "match-all": "সব", + "match-any": "যেকোনো", "medium": "মাঝারি", "member": "সদস্য", "members": "সদস্যগণ", diff --git a/public/intl/messages/bs-BA.json b/public/intl/messages/bs-BA.json index 547ae7836..36a04feba 100644 --- a/public/intl/messages/bs-BA.json +++ b/public/intl/messages/bs-BA.json @@ -172,8 +172,8 @@ "max": "Maks", "maximize": "Proširi", "match": "Podudaranje", - "match-all": "Sve (AND)", - "match-any": "Bilo koje (OR)", + "match-all": "Sve", + "match-any": "Bilo koje", "medium": "Srednje", "member": "Član", "members": "Članovi", diff --git a/public/intl/messages/ca-ES.json b/public/intl/messages/ca-ES.json index e73ba612f..2334290cf 100644 --- a/public/intl/messages/ca-ES.json +++ b/public/intl/messages/ca-ES.json @@ -172,8 +172,8 @@ "max": "Màx", "maximize": "Expandeix", "match": "Coincidència", - "match-all": "Tots (AND)", - "match-any": "Qualsevol (OR)", + "match-all": "Tots", + "match-any": "Qualsevol", "medium": "Mitjà", "member": "Membre", "members": "Membres", diff --git a/public/intl/messages/cs-CZ.json b/public/intl/messages/cs-CZ.json index ac15c67a1..824f92844 100644 --- a/public/intl/messages/cs-CZ.json +++ b/public/intl/messages/cs-CZ.json @@ -172,8 +172,8 @@ "max": "Max", "maximize": "Rozbalit", "match": "Shoda", - "match-all": "Vše (AND)", - "match-any": "Jakýkoli (OR)", + "match-all": "Vše", + "match-any": "Jakýkoli", "medium": "Střední", "member": "Člen", "members": "Členové", diff --git a/public/intl/messages/da-DK.json b/public/intl/messages/da-DK.json index 57fd08376..555c314e2 100644 --- a/public/intl/messages/da-DK.json +++ b/public/intl/messages/da-DK.json @@ -172,8 +172,8 @@ "max": "Maks", "maximize": "Udvid", "match": "Match", - "match-all": "Alle (AND)", - "match-any": "Enhver (OR)", + "match-all": "Alle", + "match-any": "Enhver", "medium": "Medie", "member": "Medlem", "members": "Medlemmer", diff --git a/public/intl/messages/de-CH.json b/public/intl/messages/de-CH.json index f309f9e54..c7869139c 100644 --- a/public/intl/messages/de-CH.json +++ b/public/intl/messages/de-CH.json @@ -172,8 +172,8 @@ "max": "Max", "maximize": "Uusklappe", "match": "Übereinstimmung", - "match-all": "Alle (AND)", - "match-any": "Beliebige (OR)", + "match-all": "Alle", + "match-any": "Beliebige", "medium": "Medium", "member": "Mitglied", "members": "Mitglieder", diff --git a/public/intl/messages/de-DE.json b/public/intl/messages/de-DE.json index bf17b131e..12f8b193b 100644 --- a/public/intl/messages/de-DE.json +++ b/public/intl/messages/de-DE.json @@ -172,8 +172,8 @@ "max": "Max", "maximize": "Erweitern", "match": "Übereinstimmung", - "match-all": "Alle (AND)", - "match-any": "Beliebige (OR)", + "match-all": "Alle", + "match-any": "Beliebige", "medium": "Medium", "member": "Mitglied", "members": "Mitglieder", diff --git a/public/intl/messages/el-GR.json b/public/intl/messages/el-GR.json index 8450f3a6f..8b7ecae23 100644 --- a/public/intl/messages/el-GR.json +++ b/public/intl/messages/el-GR.json @@ -172,8 +172,8 @@ "max": "Μέγ", "maximize": "Expand", "match": "Αντιστοίχιση", - "match-all": "Όλα (AND)", - "match-any": "Οποιοδήποτε (OR)", + "match-all": "Όλα", + "match-any": "Οποιοδήποτε", "medium": "Μέσο", "member": "Μέλος", "members": "Μέλη", diff --git a/public/intl/messages/en-GB.json b/public/intl/messages/en-GB.json index 57b8ea619..86f810c2d 100644 --- a/public/intl/messages/en-GB.json +++ b/public/intl/messages/en-GB.json @@ -172,8 +172,8 @@ "max": "Max", "maximize": "Expand", "match": "Match", - "match-all": "All (AND)", - "match-any": "Any (OR)", + "match-all": "All", + "match-any": "Any", "medium": "Medium", "member": "Member", "members": "Members", diff --git a/public/intl/messages/en-US.json b/public/intl/messages/en-US.json index 33704d17d..fb7c50202 100644 --- a/public/intl/messages/en-US.json +++ b/public/intl/messages/en-US.json @@ -171,8 +171,8 @@ "manager": "Manager", "max": "Max", "match": "Match", - "match-all": "All (AND)", - "match-any": "Any (OR)", + "match-all": "All", + "match-any": "Any", "maximize": "Maximize", "medium": "Medium", "member": "Member", diff --git a/public/intl/messages/es-ES.json b/public/intl/messages/es-ES.json index 11031f818..533d65c4e 100644 --- a/public/intl/messages/es-ES.json +++ b/public/intl/messages/es-ES.json @@ -172,8 +172,8 @@ "max": "Máximo", "maximize": "Expandir", "match": "Coincidencia", - "match-all": "Todo (AND)", - "match-any": "Cualquiera (OR)", + "match-all": "Todo", + "match-any": "Cualquiera", "medium": "Medio", "member": "Miembro", "members": "Miembros", diff --git a/public/intl/messages/fa-IR.json b/public/intl/messages/fa-IR.json index ee072c74c..db54c425d 100644 --- a/public/intl/messages/fa-IR.json +++ b/public/intl/messages/fa-IR.json @@ -172,8 +172,8 @@ "max": "حداکثر", "maximize": "گسترش", "match": "تطابق", - "match-all": "همه (AND)", - "match-any": "هر (OR)", + "match-all": "همه", + "match-any": "هر", "medium": "متوسط", "member": "عضو", "members": "اعضا", diff --git a/public/intl/messages/fi-FI.json b/public/intl/messages/fi-FI.json index 63da45902..f9f6dcb14 100644 --- a/public/intl/messages/fi-FI.json +++ b/public/intl/messages/fi-FI.json @@ -172,8 +172,8 @@ "max": "Maksimi", "maximize": "Laajenna", "match": "Vastaavuus", - "match-all": "Kaikki (AND)", - "match-any": "Mikä tahansa (OR)", + "match-all": "Kaikki", + "match-any": "Mikä tahansa", "medium": "Keskitaso", "member": "Jäsen", "members": "Jäsenet", diff --git a/public/intl/messages/fo-FO.json b/public/intl/messages/fo-FO.json index cc7e17830..b77dacde6 100644 --- a/public/intl/messages/fo-FO.json +++ b/public/intl/messages/fo-FO.json @@ -172,8 +172,8 @@ "max": "Mest", "maximize": "Víðka", "match": "Samsvørun", - "match-all": "Allt (AND)", - "match-any": "Nakað (OR)", + "match-all": "Allt", + "match-any": "Nakað", "medium": "Miðal", "member": "Limur", "members": "Limir", diff --git a/public/intl/messages/fr-FR.json b/public/intl/messages/fr-FR.json index 79d912d09..8a75511b9 100644 --- a/public/intl/messages/fr-FR.json +++ b/public/intl/messages/fr-FR.json @@ -172,8 +172,8 @@ "max": "Max", "maximize": "Développer", "match": "Correspondance", - "match-all": "Tous (AND)", - "match-any": "N'importe lequel (OR)", + "match-all": "Tous", + "match-any": "N'importe lequel", "medium": "Moyen", "member": "Membre", "members": "Membres", diff --git a/public/intl/messages/ga-ES.json b/public/intl/messages/ga-ES.json index 80ad90e21..d2dbf10d5 100644 --- a/public/intl/messages/ga-ES.json +++ b/public/intl/messages/ga-ES.json @@ -172,8 +172,8 @@ "max": "Máx", "maximize": "Expandir", "match": "Coincidencia", - "match-all": "Todo (AND)", - "match-any": "Calquera (OR)", + "match-all": "Todo", + "match-any": "Calquera", "medium": "Medio", "member": "Membro", "members": "Membros", diff --git a/public/intl/messages/he-IL.json b/public/intl/messages/he-IL.json index 63a5f1d4e..55dbe3d59 100644 --- a/public/intl/messages/he-IL.json +++ b/public/intl/messages/he-IL.json @@ -172,8 +172,8 @@ "max": "מקסימום", "maximize": "הרחב", "match": "התאמה", - "match-all": "הכל (AND)", - "match-any": "כלשהו (OR)", + "match-all": "הכל", + "match-any": "כלשהו", "medium": "בינוני", "member": "חבר", "members": "חברים", diff --git a/public/intl/messages/hi-IN.json b/public/intl/messages/hi-IN.json index a148cff2c..03b123823 100644 --- a/public/intl/messages/hi-IN.json +++ b/public/intl/messages/hi-IN.json @@ -172,8 +172,8 @@ "max": "अधिकतम", "maximize": "विस्तार करें", "match": "मेल", - "match-all": "सभी (AND)", - "match-any": "कोई भी (OR)", + "match-all": "सभी", + "match-any": "कोई भी", "medium": "मध्यम", "member": "सदस्य", "members": "सदस्यगण", diff --git a/public/intl/messages/hr-HR.json b/public/intl/messages/hr-HR.json index 50b5a745d..bc9079420 100644 --- a/public/intl/messages/hr-HR.json +++ b/public/intl/messages/hr-HR.json @@ -172,8 +172,8 @@ "max": "Maksimum", "maximize": "Proširi", "match": "Podudaranje", - "match-all": "Sve (AND)", - "match-any": "Bilo koje (OR)", + "match-all": "Sve", + "match-any": "Bilo koje", "medium": "Srednje", "member": "Član", "members": "Članovi", diff --git a/public/intl/messages/hu-HU.json b/public/intl/messages/hu-HU.json index 5a72da344..fd794b161 100644 --- a/public/intl/messages/hu-HU.json +++ b/public/intl/messages/hu-HU.json @@ -172,8 +172,8 @@ "max": "Maximum", "maximize": "Kibontás", "match": "Egyezés", - "match-all": "Összes (AND)", - "match-any": "Bármelyik (OR)", + "match-all": "Összes", + "match-any": "Bármelyik", "medium": "Közepes", "member": "Tag", "members": "Tagok", diff --git a/public/intl/messages/id-ID.json b/public/intl/messages/id-ID.json index c3e14b46f..bde276564 100644 --- a/public/intl/messages/id-ID.json +++ b/public/intl/messages/id-ID.json @@ -172,8 +172,8 @@ "max": "Maksimum", "maximize": "Perluas", "match": "Cocok", - "match-all": "Semua (AND)", - "match-any": "Salah satu (OR)", + "match-all": "Semua", + "match-any": "Salah satu", "medium": "Sedang", "member": "Anggota", "members": "Anggota", diff --git a/public/intl/messages/it-IT.json b/public/intl/messages/it-IT.json index 5f1ee153e..9d0f30e25 100644 --- a/public/intl/messages/it-IT.json +++ b/public/intl/messages/it-IT.json @@ -172,8 +172,8 @@ "max": "Massimo", "maximize": "Espandi", "match": "Corrispondenza", - "match-all": "Tutti (AND)", - "match-any": "Qualsiasi (OR)", + "match-all": "Tutti", + "match-any": "Qualsiasi", "medium": "Medio", "member": "Membro", "members": "Membri", diff --git a/public/intl/messages/ja-JP.json b/public/intl/messages/ja-JP.json index d8d9dbc49..c0b017faf 100644 --- a/public/intl/messages/ja-JP.json +++ b/public/intl/messages/ja-JP.json @@ -172,8 +172,8 @@ "max": "最大", "maximize": "展開", "match": "一致", - "match-all": "すべて (AND)", - "match-any": "いずれか (OR)", + "match-all": "すべて", + "match-any": "いずれか", "medium": "メディア", "member": "メンバー", "members": "メンバー", diff --git a/public/intl/messages/km-KH.json b/public/intl/messages/km-KH.json index 0a13399d7..5d8f234de 100644 --- a/public/intl/messages/km-KH.json +++ b/public/intl/messages/km-KH.json @@ -172,8 +172,8 @@ "max": "អតិបរមា", "maximize": "ពង្រីក", "match": "ត្រូវគ្នា", - "match-all": "ទាំងអស់ (AND)", - "match-any": "ណាមួយ (OR)", + "match-all": "ទាំងអស់", + "match-any": "ណាមួយ", "medium": "មធ្យម", "member": "សមាជិក", "members": "សមាជិក", diff --git a/public/intl/messages/ko-KR.json b/public/intl/messages/ko-KR.json index d88da6ad1..9e0ec6167 100644 --- a/public/intl/messages/ko-KR.json +++ b/public/intl/messages/ko-KR.json @@ -172,8 +172,8 @@ "max": "최대", "maximize": "확장", "match": "일치", - "match-all": "전체 (AND)", - "match-any": "일부 (OR)", + "match-all": "전체", + "match-any": "일부", "medium": "미디엄", "member": "멤버", "members": "멤버", diff --git a/public/intl/messages/lt-LT.json b/public/intl/messages/lt-LT.json index 34ee0d025..83df2e2ee 100644 --- a/public/intl/messages/lt-LT.json +++ b/public/intl/messages/lt-LT.json @@ -172,8 +172,8 @@ "max": "Maksimumas", "maximize": "Išplėsti", "match": "Atitikimas", - "match-all": "Visi (AND)", - "match-any": "Bet kuris (OR)", + "match-all": "Visi", + "match-any": "Bet kuris", "medium": "Vidutinis", "member": "Narys", "members": "Nariai", diff --git a/public/intl/messages/mn-MN.json b/public/intl/messages/mn-MN.json index 100c385f5..4be8f7a40 100644 --- a/public/intl/messages/mn-MN.json +++ b/public/intl/messages/mn-MN.json @@ -172,8 +172,8 @@ "max": "Дээд", "maximize": "Өргөтгөх", "match": "Тохирох", - "match-all": "Бүгд (AND)", - "match-any": "Ямар ч (OR)", + "match-all": "Бүгд", + "match-any": "Ямар ч", "medium": "Дунд", "member": "Гишүүн", "members": "Гишүүд", diff --git a/public/intl/messages/ms-MY.json b/public/intl/messages/ms-MY.json index ecc282cab..450bcc265 100644 --- a/public/intl/messages/ms-MY.json +++ b/public/intl/messages/ms-MY.json @@ -172,8 +172,8 @@ "max": "Maks", "maximize": "Expand", "match": "Padanan", - "match-all": "Semua (AND)", - "match-any": "Mana-mana (OR)", + "match-all": "Semua", + "match-any": "Mana-mana", "medium": "Medium", "member": "Ahli", "members": "Ahli", diff --git a/public/intl/messages/my-MM.json b/public/intl/messages/my-MM.json index 88e966ac4..1299a1a9a 100644 --- a/public/intl/messages/my-MM.json +++ b/public/intl/messages/my-MM.json @@ -172,8 +172,8 @@ "max": "အများဆုံး", "maximize": "Expand", "match": "ကိုက်ညီ", - "match-all": "အားလုံး (AND)", - "match-any": "တစ်ခုခု (OR)", + "match-all": "အားလုံး", + "match-any": "တစ်ခုခု", "medium": "မီဒီယမ်", "member": "အဖွဲ့ဝင်", "members": "အဖွဲ့ဝင်များ", diff --git a/public/intl/messages/nb-NO.json b/public/intl/messages/nb-NO.json index 1296ee814..2113d28f6 100644 --- a/public/intl/messages/nb-NO.json +++ b/public/intl/messages/nb-NO.json @@ -172,8 +172,8 @@ "max": "Maks", "maximize": "Utvid", "match": "Samsvar", - "match-all": "Alle (AND)", - "match-any": "Enhver (OR)", + "match-all": "Alle", + "match-any": "Enhver", "medium": "Medium", "member": "Bruker", "members": "Brukere", diff --git a/public/intl/messages/nl-NL.json b/public/intl/messages/nl-NL.json index 69818e3a8..64b36cc2b 100644 --- a/public/intl/messages/nl-NL.json +++ b/public/intl/messages/nl-NL.json @@ -172,8 +172,8 @@ "max": "Max", "maximize": "Uitvouwen", "match": "Overeenkomst", - "match-all": "Alle (AND)", - "match-any": "Elk (OR)", + "match-all": "Alle", + "match-any": "Elk", "medium": "Medium", "member": "Gebruiker", "members": "Gebruikers", diff --git a/public/intl/messages/pl-PL.json b/public/intl/messages/pl-PL.json index dad1f2327..f6e944956 100644 --- a/public/intl/messages/pl-PL.json +++ b/public/intl/messages/pl-PL.json @@ -172,8 +172,8 @@ "max": "Maks", "maximize": "Rozwiń", "match": "Dopasowanie", - "match-all": "Wszystkie (AND)", - "match-any": "Dowolny (OR)", + "match-all": "Wszystkie", + "match-any": "Dowolny", "medium": "Medium", "member": "Członek", "members": "Członkowie", diff --git a/public/intl/messages/pt-BR.json b/public/intl/messages/pt-BR.json index 8ccfa3991..d6fc531aa 100644 --- a/public/intl/messages/pt-BR.json +++ b/public/intl/messages/pt-BR.json @@ -172,8 +172,8 @@ "max": "Máximo", "maximize": "Expandir", "match": "Correspondência", - "match-all": "Todos (AND)", - "match-any": "Qualquer (OR)", + "match-all": "Todos", + "match-any": "Qualquer", "medium": "Médio", "member": "Membro", "members": "Membros", diff --git a/public/intl/messages/pt-PT.json b/public/intl/messages/pt-PT.json index 4b52892c3..236dc53c1 100644 --- a/public/intl/messages/pt-PT.json +++ b/public/intl/messages/pt-PT.json @@ -172,8 +172,8 @@ "max": "Máximo", "maximize": "Expandir", "match": "Correspondência", - "match-all": "Todos (AND)", - "match-any": "Qualquer (OR)", + "match-all": "Todos", + "match-any": "Qualquer", "medium": "Médio", "member": "Membro", "members": "Membros", diff --git a/public/intl/messages/ro-RO.json b/public/intl/messages/ro-RO.json index 86c804777..b89390a05 100644 --- a/public/intl/messages/ro-RO.json +++ b/public/intl/messages/ro-RO.json @@ -172,8 +172,8 @@ "max": "Max", "maximize": "Extinde", "match": "Potrivire", - "match-all": "Toate (AND)", - "match-any": "Oricare (OR)", + "match-all": "Toate", + "match-any": "Oricare", "medium": "Mediu", "member": "Membru", "members": "Membri", diff --git a/public/intl/messages/ru-RU.json b/public/intl/messages/ru-RU.json index 8296e160f..a76bd0430 100644 --- a/public/intl/messages/ru-RU.json +++ b/public/intl/messages/ru-RU.json @@ -172,8 +172,8 @@ "max": "Максимум", "maximize": "Развернуть", "match": "Соответствие", - "match-all": "Все (AND)", - "match-any": "Любой (OR)", + "match-all": "Все", + "match-any": "Любой", "medium": "Средний", "member": "Участник", "members": "Участники", diff --git a/public/intl/messages/si-LK.json b/public/intl/messages/si-LK.json index 5aa2bd89a..bc8e9804e 100644 --- a/public/intl/messages/si-LK.json +++ b/public/intl/messages/si-LK.json @@ -172,8 +172,8 @@ "max": "උපරිම", "maximize": "Expand", "match": "ගැළපීම", - "match-all": "සියල්ල (AND)", - "match-any": "ඕනෑම (OR)", + "match-all": "සියල්ල", + "match-any": "ඕනෑම", "medium": "මාධ්‍යය", "member": "සාමාජිකයා", "members": "සාමාජිකයින්", diff --git a/public/intl/messages/sk-SK.json b/public/intl/messages/sk-SK.json index f51951f93..ae13758bd 100644 --- a/public/intl/messages/sk-SK.json +++ b/public/intl/messages/sk-SK.json @@ -172,8 +172,8 @@ "max": "Maximum", "maximize": "Rozbaliť", "match": "Zhoda", - "match-all": "Všetky (AND)", - "match-any": "Akýkoľvek (OR)", + "match-all": "Všetky", + "match-any": "Akýkoľvek", "medium": "Stredný", "member": "Člen", "members": "Členovia", diff --git a/public/intl/messages/sl-SI.json b/public/intl/messages/sl-SI.json index cea57d48e..2d92da29e 100644 --- a/public/intl/messages/sl-SI.json +++ b/public/intl/messages/sl-SI.json @@ -172,8 +172,8 @@ "max": "Največ", "maximize": "Povečaj", "match": "Ujemanje", - "match-all": "Vse (AND)", - "match-any": "Katero koli (OR)", + "match-all": "Vse", + "match-any": "Katero koli", "medium": "Medij", "member": "Član", "members": "Člani", diff --git a/public/intl/messages/sv-SE.json b/public/intl/messages/sv-SE.json index e8f842e3e..e505e8810 100644 --- a/public/intl/messages/sv-SE.json +++ b/public/intl/messages/sv-SE.json @@ -172,8 +172,8 @@ "max": "Max", "maximize": "Expandera", "match": "Matchning", - "match-all": "Alla (AND)", - "match-any": "Vilken som helst (OR)", + "match-all": "Alla", + "match-any": "Vilken som helst", "medium": "Medium", "member": "Medlem", "members": "Medlemmar", diff --git a/public/intl/messages/ta-IN.json b/public/intl/messages/ta-IN.json index 6cf4388fa..f4e1c0f0d 100644 --- a/public/intl/messages/ta-IN.json +++ b/public/intl/messages/ta-IN.json @@ -172,8 +172,8 @@ "max": "அதிகபட்சம்", "maximize": "Expand", "match": "பொருத்தம்", - "match-all": "அனைத்தும் (AND)", - "match-any": "எதுவும் (OR)", + "match-all": "அனைத்தும்", + "match-any": "எதுவும்", "medium": "ஊடகம்", "member": "உறுப்பினர்", "members": "உறுப்பினர்கள்", diff --git a/public/intl/messages/th-TH.json b/public/intl/messages/th-TH.json index 168cc057a..2003c8f06 100644 --- a/public/intl/messages/th-TH.json +++ b/public/intl/messages/th-TH.json @@ -172,8 +172,8 @@ "max": "สูงสุด", "maximize": "Expand", "match": "จับคู่", - "match-all": "ทั้งหมด (AND)", - "match-any": "ใดๆ (OR)", + "match-all": "ทั้งหมด", + "match-any": "ใดๆ", "medium": "สื่อ", "member": "สมาชิก", "members": "สมาชิก", diff --git a/public/intl/messages/tr-TR.json b/public/intl/messages/tr-TR.json index 139aee6af..4dd7eddd5 100644 --- a/public/intl/messages/tr-TR.json +++ b/public/intl/messages/tr-TR.json @@ -172,8 +172,8 @@ "max": "Maks", "maximize": "Genişlet", "match": "Eşleşme", - "match-all": "Tümü (AND)", - "match-any": "Herhangi (OR)", + "match-all": "Tümü", + "match-any": "Herhangi", "medium": "Orta", "member": "Üye", "members": "Üyeler", diff --git a/public/intl/messages/uk-UA.json b/public/intl/messages/uk-UA.json index 5f78c2bfe..772373252 100644 --- a/public/intl/messages/uk-UA.json +++ b/public/intl/messages/uk-UA.json @@ -172,8 +172,8 @@ "max": "Макс.", "maximize": "Розгорнути", "match": "Відповідність", - "match-all": "Усі (AND)", - "match-any": "Будь-який (OR)", + "match-all": "Усі", + "match-any": "Будь-який", "medium": "Середній", "member": "Учасник", "members": "Учасники", diff --git a/public/intl/messages/ur-PK.json b/public/intl/messages/ur-PK.json index a1d07dbe2..faba3ee75 100644 --- a/public/intl/messages/ur-PK.json +++ b/public/intl/messages/ur-PK.json @@ -172,8 +172,8 @@ "max": "زیادہ سے زیادہ", "maximize": "Expand", "match": "مطابقت", - "match-all": "سب (AND)", - "match-any": "کوئی بھی (OR)", + "match-all": "سب", + "match-any": "کوئی بھی", "medium": "میڈیم", "member": "رکن", "members": "اراکین", diff --git a/public/intl/messages/uz-UZ.json b/public/intl/messages/uz-UZ.json index de0ad0085..b0ddbb710 100644 --- a/public/intl/messages/uz-UZ.json +++ b/public/intl/messages/uz-UZ.json @@ -172,8 +172,8 @@ "max": "Maksimal", "maximize": "Kattalashtirish", "match": "Moslik", - "match-all": "Barchasi (AND)", - "match-any": "Istalgan (OR)", + "match-all": "Barchasi", + "match-any": "Istalgan", "medium": "Vosita", "member": "A'zo", "members": "A'zolar", diff --git a/public/intl/messages/vi-VN.json b/public/intl/messages/vi-VN.json index 2b9514fc4..cb8360542 100644 --- a/public/intl/messages/vi-VN.json +++ b/public/intl/messages/vi-VN.json @@ -172,8 +172,8 @@ "max": "Tối đa", "maximize": "Phóng to", "match": "Khớp", - "match-all": "Tất cả (AND)", - "match-any": "Bất kỳ (OR)", + "match-all": "Tất cả", + "match-any": "Bất kỳ", "medium": "Phương tiện", "member": "Thành viên", "members": "Các thành viên", diff --git a/public/intl/messages/zh-CN.json b/public/intl/messages/zh-CN.json index 4d65d885f..6d723f83b 100644 --- a/public/intl/messages/zh-CN.json +++ b/public/intl/messages/zh-CN.json @@ -172,8 +172,8 @@ "max": "最大", "maximize": "展开", "match": "匹配", - "match-all": "全部 (AND)", - "match-any": "任意 (OR)", + "match-all": "全部", + "match-any": "任意", "medium": "中等", "member": "成员", "members": "成员", diff --git a/public/intl/messages/zh-TW.json b/public/intl/messages/zh-TW.json index 05d304f4b..d74b803fa 100644 --- a/public/intl/messages/zh-TW.json +++ b/public/intl/messages/zh-TW.json @@ -172,8 +172,8 @@ "max": "最大值", "maximize": "Expand", "match": "符合", - "match-all": "全部 (AND)", - "match-any": "任意 (OR)", + "match-all": "全部", + "match-any": "任意", "medium": "媒介", "member": "成員", "members": "成員", From 0651168823bffb07ea50963aff269b23f52cd70f Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Sat, 21 Feb 2026 23:05:16 -0800 Subject: [PATCH 20/22] fix bug when removed filter do not update --- src/components/input/FilterEditForm.tsx | 8 +------- src/components/input/WebsiteFilterButton.tsx | 5 ++++- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/src/components/input/FilterEditForm.tsx b/src/components/input/FilterEditForm.tsx index fd0f8d48d..f9458f99e 100644 --- a/src/components/input/FilterEditForm.tsx +++ b/src/components/input/FilterEditForm.tsx @@ -102,13 +102,7 @@ export function FilterEditForm({ websiteId, onChange, onClose }: FilterEditFormP - diff --git a/src/components/input/WebsiteFilterButton.tsx b/src/components/input/WebsiteFilterButton.tsx index e2484727a..1f04e2929 100644 --- a/src/components/input/WebsiteFilterButton.tsx +++ b/src/components/input/WebsiteFilterButton.tsx @@ -1,6 +1,6 @@ import { Checkbox, Row } from '@umami/react-zen'; import { useState } from 'react'; -import { useMessages, useNavigation } from '@/components/hooks'; +import { useFilters, useMessages, useNavigation } from '@/components/hooks'; import { ListFilter } from '@/components/icons'; import { DialogButton } from '@/components/input/DialogButton'; import { FilterEditForm } from '@/components/input/FilterEditForm'; @@ -15,14 +15,17 @@ export function WebsiteFilterButton({ }) { const { t, labels } = useMessages(); const { updateParams, pathname, router, query } = useNavigation(); + const { filters: currentFilters } = useFilters(); const [excludeBounce, setExcludeBounce] = useState(!!query.excludeBounce); const isOverview = /^\/teams\/[^/]+\/websites\/[^/]+$/.test(pathname) || /^\/share\/[^/]+$/.test(pathname); const handleChange = ({ filters, segment, cohort, match }: any) => { const params = filtersArrayToObject(filters); + const cleared = Object.fromEntries(currentFilters.map(f => [f.name, undefined])); const url = updateParams({ + ...cleared, ...params, segment, cohort, From 99b5d9dde8ee99ad2b231de5bc75064d658b1fd1 Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Sat, 21 Feb 2026 23:23:56 -0800 Subject: [PATCH 21/22] remove currency from params and references. optimize CH queries with subquery --- src/queries/sql/reports/getAttribution.ts | 199 +++++++++------------- 1 file changed, 79 insertions(+), 120 deletions(-) diff --git a/src/queries/sql/reports/getAttribution.ts b/src/queries/sql/reports/getAttribution.ts index 088b5b24b..a25c92896 100644 --- a/src/queries/sql/reports/getAttribution.ts +++ b/src/queries/sql/reports/getAttribution.ts @@ -10,7 +10,6 @@ export interface AttributionParameters { model: string; type: string; step: string; - currency?: string; } export interface AttributionResult { @@ -38,7 +37,7 @@ async function relationalQuery( parameters: AttributionParameters, filters: QueryFilters, ): Promise { - const { model, type, currency } = parameters; + const { model, type } = parameters; const { rawQuery, parseFilters } = prisma; const eventType = type === 'path' ? EVENT_TYPE.pageView : EVENT_TYPE.customEvent; const column = type === 'path' ? 'url_path' : 'event_name'; @@ -51,17 +50,16 @@ async function relationalQuery( function getUTMQuery(utmColumn: string) { return ` - select + select coalesce(we.${utmColumn}, '') as "name", - ${currency ? 'sum(e.value)' : 'count(distinct we.session_id)'} as "value" + count(distinct we.session_id) as "value" from model m join website_event we on we.created_at = m.created_at and we.session_id = m.session_id - ${currency ? 'join events e on e.session_id = m.session_id' : ''} where we.website_id = {{websiteId::uuid}} and we.created_at between {{startDate}} and {{endDate}} - ${currency ? '' : `and we.${utmColumn} != ''`} + and we.${utmColumn} != '' group by 1 order by 2 desc limit 20`; @@ -80,30 +78,9 @@ async function relationalQuery( ${filterQuery} group by 1),`; - const revenueEventQuery = `WITH events AS ( - select - revenue.session_id, - max(revenue.created_at) max_dt, - sum(revenue.revenue) value - from revenue - join website_event - on website_event.website_id = revenue.website_id - and website_event.session_id = revenue.session_id - and website_event.event_id = revenue.event_id - and website_event.website_id = {{websiteId::uuid}} - and website_event.created_at between {{startDate}} and {{endDate}} - ${cohortQuery} - ${joinSessionQuery} - where revenue.website_id = {{websiteId::uuid}} - and revenue.created_at between {{startDate}} and {{endDate}} - and revenue.${column} = {{step}} - and revenue.currency = {{currency}} - ${filterQuery} - group by 1),`; - function getModelQuery(model: string) { return model === 'first-click' - ? `\n + ? `\n model AS (select e.session_id, min(we.created_at) created_at from events e @@ -112,39 +89,34 @@ async function relationalQuery( where we.website_id = {{websiteId::uuid}} and we.created_at between {{startDate}} and {{endDate}} group by e.session_id)` - : `\n + : `\n model AS (select e.session_id, max(we.created_at) created_at from events e join website_event we on we.session_id = e.session_id where we.website_id = {{websiteId::uuid}} - and we.created_at between {{startDate}} and {{endDate}} + and we.created_at between {{startDate}} and {{endDate}} and we.created_at < e.max_dt group by e.session_id)`; } const referrerRes = await rawQuery( ` - ${currency ? revenueEventQuery : eventQuery} + ${eventQuery} ${getModelQuery(model)} select coalesce(we.referrer_domain, '') as "name", - ${currency ? 'sum(e.value)' : 'count(distinct we.session_id)'} value + count(distinct we.session_id) value from model m join website_event we on we.created_at = m.created_at and we.session_id = m.session_id join session s on s.session_id = m.session_id - ${currency ? 'join events e on e.session_id = m.session_id' : ''} where we.website_id = {{websiteId::uuid}} and we.created_at between {{startDate}} and {{endDate}} - ${ - currency - ? '' - : `and we.referrer_domain != regexp_replace(we.hostname, '^www.', '') - and we.referrer_domain != ''` - } + and we.referrer_domain != regexp_replace(we.hostname, '^www.', '') + and we.referrer_domain != '' group by 1 order by 2 desc limit 20 @@ -154,40 +126,39 @@ async function relationalQuery( const paidAdsres = await rawQuery( ` - ${currency ? revenueEventQuery : eventQuery} + ${eventQuery} ${getModelQuery(model)}, results AS ( select case - when coalesce(gclid, '') != '' then 'Google Ads' - when coalesce(fbclid, '') != '' then 'Facebook / Meta' - when coalesce(msclkid, '') != '' then 'Microsoft Ads' - when coalesce(ttclid, '') != '' then 'TikTok Ads' - when coalesce(li_fat_id, '') != '' then 'LinkedIn Ads' + when coalesce(gclid, '') != '' then 'Google Ads' + when coalesce(fbclid, '') != '' then 'Facebook / Meta' + when coalesce(msclkid, '') != '' then 'Microsoft Ads' + when coalesce(ttclid, '') != '' then 'TikTok Ads' + when coalesce(li_fat_id, '') != '' then 'LinkedIn Ads' when coalesce(twclid, '') != '' then 'Twitter Ads (X)' else '' end as "name", - ${currency ? 'sum(e.value)' : 'count(distinct we.session_id)'} as "value" + count(distinct we.session_id) as "value" from model m join website_event we on we.created_at = m.created_at and we.session_id = m.session_id - ${currency ? 'join events e on e.session_id = m.session_id' : ''} where we.website_id = {{websiteId::uuid}} and we.created_at between {{startDate}} and {{endDate}} group by 1 order by 2 desc limit 20) - SELECT * + SELECT * FROM results - ${currency ? '' : `WHERE name != ''`} + WHERE name != '' `, queryParams, ); const sourceRes = await rawQuery( ` - ${currency ? revenueEventQuery : eventQuery} + ${eventQuery} ${getModelQuery(model)} ${getUTMQuery('utm_source')} `, @@ -196,7 +167,7 @@ async function relationalQuery( const mediumRes = await rawQuery( ` - ${currency ? revenueEventQuery : eventQuery} + ${eventQuery} ${getModelQuery(model)} ${getUTMQuery('utm_medium')} `, @@ -205,7 +176,7 @@ async function relationalQuery( const campaignRes = await rawQuery( ` - ${currency ? revenueEventQuery : eventQuery} + ${eventQuery} ${getModelQuery(model)} ${getUTMQuery('utm_campaign')} `, @@ -214,7 +185,7 @@ async function relationalQuery( const contentRes = await rawQuery( ` - ${currency ? revenueEventQuery : eventQuery} + ${eventQuery} ${getModelQuery(model)} ${getUTMQuery('utm_content')} `, @@ -223,7 +194,7 @@ async function relationalQuery( const termRes = await rawQuery( ` - ${currency ? revenueEventQuery : eventQuery} + ${eventQuery} ${getModelQuery(model)} ${getUTMQuery('utm_term')} `, @@ -232,7 +203,7 @@ async function relationalQuery( const totalRes = await rawQuery( ` - select + select count(*) as "pageviews", count(distinct website_event.session_id) as "visitors", count(distinct website_event.visit_id) as "visits" @@ -264,7 +235,7 @@ async function clickhouseQuery( parameters: AttributionParameters, filters: QueryFilters, ): Promise { - const { model, type, currency } = parameters; + const { model, type } = parameters; const { rawQuery, parseFilters } = clickhouse; const eventType = type === 'path' ? EVENT_TYPE.pageView : EVENT_TYPE.customEvent; const column = type === 'path' ? 'url_path' : 'event_name'; @@ -277,17 +248,19 @@ async function clickhouseQuery( function getUTMQuery(utmColumn: string) { return ` - select + select we.${utmColumn} name, - ${currency ? 'sum(e.value)' : 'uniqExact(we.session_id)'} value + uniqExact(we.session_id) value from model m - join website_event we + join ( + select * + from website_event + where website_id = {websiteId:UUID} + and created_at between {startDate:DateTime64} and {endDate:DateTime64} + ) we on we.created_at = m.created_at and we.session_id = m.session_id - ${currency ? 'join events e on e.session_id = m.session_id' : ''} - where we.website_id = {websiteId:UUID} - and we.created_at between {startDate:DateTime64} and {endDate:DateTime64} - ${currency ? '' : `and we.${utmColumn} != ''`} + where we.${utmColumn} != '' group by 1 order by 2 desc limit 20 @@ -296,14 +269,17 @@ async function clickhouseQuery( function getModelQuery(model: string) { if (model === 'first-click') { - return ` + return ` model AS (select e.session_id, min(we.created_at) created_at from events e - join website_event we + join ( + select * + from website_event + where website_id = {websiteId:UUID} + and created_at between {startDate:DateTime64} and {endDate:DateTime64} + ) we on we.session_id = e.session_id - where we.website_id = {websiteId:UUID} - and we.created_at between {startDate:DateTime64} and {endDate:DateTime64} group by e.session_id) `; } @@ -312,11 +288,14 @@ async function clickhouseQuery( model AS (select e.session_id, max(we.created_at) created_at from events e - join website_event we + join ( + select * + from website_event + where website_id = {websiteId:UUID} + and created_at between {startDate:DateTime64} and {endDate:DateTime64} + ) we on we.session_id = e.session_id - where we.website_id = {websiteId:UUID} - and we.created_at between {startDate:DateTime64} and {endDate:DateTime64} - and we.created_at < e.max_dt + where we.created_at < e.max_dt group by e.session_id) `; } @@ -333,26 +312,6 @@ async function clickhouseQuery( ${filterQuery} group by 1),`; - const revenueEventQuery = `WITH events AS ( - select - website_revenue.session_id, - max(website_revenue.created_at) max_dt, - sum(website_revenue.revenue) as value - from website_revenue - join website_event - on website_event.website_id = website_revenue.website_id - and website_event.session_id = website_revenue.session_id - and website_event.event_id = website_revenue.event_id - and website_event.website_id = {websiteId:UUID} - and website_event.created_at between {startDate:DateTime64} and {endDate:DateTime64} - ${cohortQuery} - where website_revenue.website_id = {websiteId:UUID} - and website_revenue.created_at between {startDate:DateTime64} and {endDate:DateTime64} - and website_revenue.${column} = {step:String} - and website_revenue.currency = {currency:String} - ${filterQuery} - group by 1),`; - const referrerRes = await rawQuery< { name: string; @@ -360,23 +319,21 @@ async function clickhouseQuery( }[] >( ` - ${currency ? revenueEventQuery : eventQuery} + ${eventQuery} ${getModelQuery(model)} select we.referrer_domain name, - ${currency ? 'sum(e.value)' : 'uniqExact(we.session_id)'} value + uniqExact(we.session_id) value from model m - join website_event we + join ( + select * + from website_event + where website_id = {websiteId:UUID} + and created_at between {startDate:DateTime64} and {endDate:DateTime64} + ) we on we.created_at = m.created_at and we.session_id = m.session_id - ${currency ? 'join events e on e.session_id = m.session_id' : ''} - where we.website_id = {websiteId:UUID} - and we.created_at between {startDate:DateTime64} and {endDate:DateTime64} - ${ - currency - ? '' - : `and we.referrer_domain != hostname - and we.referrer_domain != ''` - } + where we.referrer_domain != hostname + and we.referrer_domain != '' group by 1 order by 2 desc limit 20 @@ -391,23 +348,25 @@ async function clickhouseQuery( }[] >( ` - ${currency ? revenueEventQuery : eventQuery} + ${eventQuery} ${getModelQuery(model)} - select multiIf(gclid != '', 'Google Ads', - fbclid != '', 'Facebook / Meta', - msclkid != '', 'Microsoft Ads', - ttclid != '', 'TikTok Ads', - li_fat_id != '', 'LinkedIn Ads', + select multiIf(gclid != '', 'Google Ads', + fbclid != '', 'Facebook / Meta', + msclkid != '', 'Microsoft Ads', + ttclid != '', 'TikTok Ads', + li_fat_id != '', 'LinkedIn Ads', twclid != '', 'Twitter Ads (X)','') name, - ${currency ? 'sum(e.value)' : 'uniqExact(we.session_id)'} value + uniqExact(we.session_id) value from model m - join website_event we + join ( + select * + from website_event + where website_id = {websiteId:UUID} + and created_at between {startDate:DateTime64} and {endDate:DateTime64} + ) we on we.created_at = m.created_at and we.session_id = m.session_id - ${currency ? 'join events e on e.session_id = m.session_id' : ''} - where we.website_id = {websiteId:UUID} - and we.created_at between {startDate:DateTime64} and {endDate:DateTime64} - ${currency ? '' : `and name != ''`} + where name != '' group by 1 order by 2 desc limit 20 @@ -422,7 +381,7 @@ async function clickhouseQuery( }[] >( ` - ${currency ? revenueEventQuery : eventQuery} + ${eventQuery} ${getModelQuery(model)} ${getUTMQuery('utm_source')} `, @@ -436,7 +395,7 @@ async function clickhouseQuery( }[] >( ` - ${currency ? revenueEventQuery : eventQuery} + ${eventQuery} ${getModelQuery(model)} ${getUTMQuery('utm_medium')} `, @@ -450,7 +409,7 @@ async function clickhouseQuery( }[] >( ` - ${currency ? revenueEventQuery : eventQuery} + ${eventQuery} ${getModelQuery(model)} ${getUTMQuery('utm_campaign')} `, @@ -464,7 +423,7 @@ async function clickhouseQuery( }[] >( ` - ${currency ? revenueEventQuery : eventQuery} + ${eventQuery} ${getModelQuery(model)} ${getUTMQuery('utm_content')} `, @@ -478,7 +437,7 @@ async function clickhouseQuery( }[] >( ` - ${currency ? revenueEventQuery : eventQuery} + ${eventQuery} ${getModelQuery(model)} ${getUTMQuery('utm_term')} `, From f4f67dd3caf8fc9f8409e3a66233d8c5963a637e Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Sat, 21 Feb 2026 23:24:51 -0800 Subject: [PATCH 22/22] remove console.log --- src/lib/clickhouse.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/clickhouse.ts b/src/lib/clickhouse.ts index b6a655d47..ef134a0cb 100644 --- a/src/lib/clickhouse.ts +++ b/src/lib/clickhouse.ts @@ -282,7 +282,7 @@ async function rawQuery( output_format_json_quote_64bit_integers: 0, }, }); - console.log(query, params); + return (await resultSet.json()) as T; }