Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

feat: Add filters support for Goals & Funnels, goal conditions, and conversion insights

Blue Mouse35a50e93b968
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index 2818c83c2..7dc9c9177 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -404,6 +404,7 @@ export class AnalyticsController {
timezone = DEFAULT_TIMEZONE,
pages,
funnelId,
+ filters,
} = data
await this.analyticsService.checkProjectAccess(
@@ -446,24 +447,40 @@ export class AnalyticsController {
diff,
)
- const params = { pid, groupFrom, groupTo }
+ const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(
+ filters || '[]',
+ DataType.ANALYTICS,
+ )
+ const params = { pid, groupFrom, groupTo, ...filtersParams }
let funnel: IFunnel[] = []
let totalPageviews: number = 0
- let stepDetails: {
- countries: Record<number, Record<string, number>>
- sources: Record<number, Record<string, number>>
- } = { countries: {}, sources: {} }
+ let timeToConvert: IGetFunnel['timeToConvert']
+ let stepDetails = {
+ countries: {},
+ devices: {},
+ browsers: {},
+ sources: {},
+ campaigns: {},
+ pages: {},
+ profileTypes: {},
+ } as Record<string, Record<number, Record<string, number>>>
const promises = [
(async () => {
- funnel = await this.analyticsService.getFunnel(pagesArr, params)
+ funnel = await this.analyticsService.getFunnel(
+ pagesArr,
+ params,
+ filtersQuery,
+ )
})(),
(async () => {
totalPageviews = await this.analyticsService.getTotalPageviews(
pid,
groupFrom,
groupTo,
+ filtersQuery,
+ filtersParams,
)
})(),
(async () => {
@@ -471,11 +488,19 @@ export class AnalyticsController {
stepDetails = await this.analyticsService.getFunnelStepDetails(
pagesArr,
params,
+ filtersQuery,
)
} catch (e) {
this.logger.error(e, 'GET /analytics/funnel - getFunnelStepDetails')
}
})(),
+ (async () => {
+ timeToConvert = await this.analyticsService.getFunnelTimeToConvert(
+ pagesArr,
+ params,
+ filtersQuery,
+ )
+ })(),
]
await Promise.all(promises)
@@ -483,9 +508,18 @@ export class AnalyticsController {
for (let i = 0; i < funnel.length; i++) {
funnel[i].topCountries = stepDetails.countries[i + 1] || {}
funnel[i].topSources = stepDetails.sources[i + 1] || {}
+ funnel[i].breakdowns = {
+ countries: stepDetails.countries[i + 1] || {},
+ devices: stepDetails.devices[i + 1] || {},
+ browsers: stepDetails.browsers[i + 1] || {},
+ sources: stepDetails.sources[i + 1] || {},
+ campaigns: stepDetails.campaigns[i + 1] || {},
+ pages: stepDetails.pages[i + 1] || {},
+ profileTypes: stepDetails.profileTypes[i + 1] || {},
+ }
}
- return { funnel, totalPageviews }
+ return { funnel, totalPageviews, timeToConvert }
}
@Get('funnel-sessions')
@@ -504,6 +538,8 @@ export class AnalyticsController {
pages,
funnelId,
step,
+ filters,
+ dropoff,
} = data
await this.analyticsService.checkProjectAccess(
@@ -564,7 +600,12 @@ export class AnalyticsController {
diff,
)
- const params = { pid, groupFrom, groupTo }
+ const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(
+ filters || '[]',
+ DataType.ANALYTICS,
+ )
+ const params = { pid, groupFrom, groupTo, ...filtersParams }
+ const isDropoff = dropoff === true || dropoff === 'true'
const sessions = await this.analyticsService.getFunnelSessionsList(
pagesArr,
@@ -573,6 +614,8 @@ export class AnalyticsController {
step,
take,
skip,
+ filtersQuery,
+ isDropoff,
)
return { sessions, take, skip }
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index 2757ace60..8f27d2b34 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -96,6 +96,8 @@ import {
IAggregatedMetadata,
IFunnelCHResponse,
IFunnel,
+ IFunnelBreakdowns,
+ IConversionTimeMetric,
IOverall,
IOverallPerformance,
IPageflow,
@@ -132,6 +134,11 @@ const MAX_FILTER_VALUES = 100
const SOFTWARE_WITH_PATCH_VERSION = ['GameVault']
+type FunnelStepDetails = Record<
+ keyof Required<IFunnelBreakdowns>,
+ Record<number, Record<string, number>>
+>
+
const GMT_0_TIMEZONES = [
'Atlantic/Azores',
'Etc/GMT',
@@ -1673,11 +1680,27 @@ export class AnalyticsService {
dropoffPercStep: 0,
topCountries: {},
topSources: {},
+ breakdowns: {},
}))
}
- async getFunnel(pages: string[], params: any): Promise<IFunnel[]> {
+ async getFunnel(
+ pages: string[],
+ params: any,
+ filtersQuery = '',
+ ): Promise<IFunnel[]> {
const pageParams: Record<string, string> = {}
+ const sessionFiltersQuery = filtersQuery
+ ? `AND psid IN (
+ SELECT DISTINCT psid
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type IN ('pageview', 'custom_event')
+ AND psid != 0
+ ${filtersQuery}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ )`
+ : ''
const pagesStr = _join(
_map(pages, (value, index) => {
@@ -1705,6 +1728,7 @@ export class AnalyticsService {
WHERE pid = {pid:FixedString(12)}
AND type IN ('pageview', 'custom_event')
AND psid != 0
+ ${sessionFiltersQuery}
AND created BETWEEN {groupFrom:String} AND {groupTo:String}
)
GROUP BY psid
@@ -1731,11 +1755,20 @@ export class AnalyticsService {
async getFunnelStepDetails(
pages: string[],
params: any,
- ): Promise<{
- countries: Record<number, Record<string, number>>
- sources: Record<number, Record<string, number>>
- }> {
+ filtersQuery = '',
+ ): Promise<FunnelStepDetails> {
const pageParams: Record<string, string> = {}
+ const sessionFiltersQuery = filtersQuery
+ ? `AND psid IN (
+ SELECT DISTINCT psid
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type IN ('pageview', 'custom_event')
+ AND psid != 0
+ ${filtersQuery}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ )`
+ : ''
const pagesStr = _join(
_map(pages, (value, index) => {
@@ -1759,6 +1792,7 @@ export class AnalyticsService {
WHERE pid = {pid:FixedString(12)}
AND type IN ('pageview', 'custom_event')
AND psid != 0
+ ${sessionFiltersQuery}
AND created BETWEEN {groupFrom:String} AND {groupTo:String}
)
GROUP BY psid
@@ -1772,7 +1806,12 @@ export class AnalyticsService {
SELECT
psid,
argMin(cc, created) AS cc,
- argMin(if(domain(ref) != '', domain(ref), 'Direct / None'), created) AS source
+ argMin(dv, created) AS dv,
+ argMin(br, created) AS br,
+ argMin(if(so IS NOT NULL AND so != '', so, if(domain(ref) != '', domain(ref), 'Direct / None')), created) AS source,
+ argMin(ca, created) AS campaign,
+ argMin(pg, created) AS page,
+ argMax(profileId, created) AS profileId
FROM events
WHERE pid = {pid:FixedString(12)}
AND type IN ('pageview', 'custom_event')
@@ -1781,7 +1820,7 @@ export class AnalyticsService {
GROUP BY psid
)
SELECT step, type, val, cnt FROM (
- SELECT e.step AS step, 'cc' AS type, si.cc AS val, count() AS cnt
+ SELECT e.step AS step, 'countries' AS type, si.cc AS val, count() AS cnt
FROM expanded e
INNER JOIN session_info si ON e.psid = si.psid
WHERE si.cc != ''
@@ -1789,13 +1828,53 @@ export class AnalyticsService {
UNION ALL
- SELECT e.step AS step, 'so' AS type, si.source AS val, count() AS cnt
+ SELECT e.step AS step, 'devices' AS type, si.dv AS val, count() AS cnt
+ FROM expanded e
+ INNER JOIN session_info si ON e.psid = si.psid
+ WHERE si.dv != ''
+ GROUP BY e.step, si.dv
+
+ UNION ALL
+
+ SELECT e.step AS step, 'browsers' AS type, si.br AS val, count() AS cnt
+ FROM expanded e
+ INNER JOIN session_info si ON e.psid = si.psid
+ WHERE si.br != ''
+ GROUP BY e.step, si.br
+
+ UNION ALL
+
+ SELECT e.step AS step, 'sources' AS type, si.source AS val, count() AS cnt
FROM expanded e
INNER JOIN session_info si ON e.psid = si.psid
GROUP BY e.step, si.source
+
+ UNION ALL
+
+ SELECT e.step AS step, 'campaigns' AS type, si.campaign AS val, count() AS cnt
+ FROM expanded e
+ INNER JOIN session_info si ON e.psid = si.psid
+ WHERE si.campaign != ''
+ GROUP BY e.step, si.campaign
+
+ UNION ALL
+
+ SELECT e.step AS step, 'pages' AS type, si.page AS val, count() AS cnt
+ FROM expanded e
+ INNER JOIN session_info si ON e.psid = si.psid
+ WHERE si.page != ''
+ GROUP BY e.step, si.page
+
+ UNION ALL
+
+ SELECT e.step AS step, 'profileTypes' AS type, if(startsWith(si.profileId, '${AnalyticsService.PROFILE_PREFIX_USER}'), 'identified', 'anonymous') AS val, count() AS cnt
+ FROM expanded e
+ INNER JOIN session_info si ON e.psid = si.psid
+ WHERE si.profileId != ''
+ GROUP BY e.step, val
)
ORDER BY step, type, cnt DESC, val ASC
- LIMIT 3 BY step, type
+ LIMIT 5 BY step, type
`
const { data } = await clickhouse
@@ -1812,21 +1891,27 @@ export class AnalyticsService {
}>(),
)
- const countries: Record<number, Record<string, number>> = {}
- const sources: Record<number, Record<string, number>> = {}
+ const details: FunnelStepDetails = {
+ countries: {},
+ devices: {},
+ browsers: {},
+ sources: {},
+ campaigns: {},
+ pages: {},
+ profileTypes: {},
+ }
for (const row of data) {
const { step } = row
- if (row.type === 'cc') {
- if (!countries[step]) countries[step] = {}
- countries[step][row.val] = row.cnt
- } else if (row.type === 'so') {
- if (!sources[step]) sources[step] = {}
- sources[step][row.val] = row.cnt
+ const type = row.type as keyof FunnelStepDetails
+
+ if (details[type]) {
+ if (!details[type][step]) details[type][step] = {}
+ details[type][step][row.val] = row.cnt
}
}
- return { countries, sources }
+ return details
}
async getFunnelSessionsList(
@@ -1836,8 +1921,24 @@ export class AnalyticsService {
step: number,
take = 30,
skip = 0,
+ filtersQuery = '',
+ dropoff = false,
): Promise<object | void> {
const pageParams: Record<string, string> = {}
+ const levelCondition = dropoff
+ ? 'level = {step:UInt32}'
+ : 'level >= {step:UInt32}'
+ const sessionFiltersQuery = filtersQuery
+ ? `AND psid IN (
+ SELECT DISTINCT psid
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type IN ('pageview', 'custom_event')
+ AND psid != 0
+ ${filtersQuery}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ )`
+ : ''
const pagesStr = _join(
_map(pages, (value, index) => {
@@ -1863,11 +1964,12 @@ export class AnalyticsService {
WHERE pid = {pid:FixedString(12)}
AND type IN ('pageview', 'custom_event')
AND psid != 0
+ ${sessionFiltersQuery}
AND created BETWEEN {groupFrom:String} AND {groupTo:String}
)
GROUP BY psid
)
- WHERE level >= {step:UInt32}
+ WHERE ${levelCondition}
),
distinct_sessions AS (
SELECT
@@ -1984,24 +2086,175 @@ export class AnalyticsService {
return data
}
+ async getFunnelTimeToConvert(
+ pages: string[],
+ params: any,
+ filtersQuery = '',
+ ): Promise<{
+ fromSessionStart: IConversionTimeMetric
+ fromFirstPage: IConversionTimeMetric
+ fromFirstFunnelStep: IConversionTimeMetric
+ }> {
+ const emptyMetric: IConversionTimeMetric = {
+ average: null,
+ median: null,
+ p75: null,
+ }
+ const pageParams: Record<string, string | number> = {
+ steps: pages.length,
+ }
+ const sessionFiltersQuery = filtersQuery
+ ? `AND psid IN (
+ SELECT DISTINCT psid
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type IN ('pageview', 'custom_event')
+ AND psid != 0
+ ${filtersQuery}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ )`
+ : ''
+
+ const pagesStr = _join(
+ _map(pages, (value, index) => {
+ pageParams[`v${index}`] = value
+ return `value={v${index}:String}`
+ }),
+ ',',
+ )
+
+ const query = `
+ WITH funnel_sessions AS (
+ SELECT
+ psid,
+ minIf(created, value = {v0:String}) AS firstStepAt,
+ maxIf(created, value = {v${pages.length - 1}:String}) AS conversionAt,
+ CAST(windowFunnel(86400)(created, ${pagesStr}) AS UInt64) AS level
+ FROM (
+ SELECT
+ psid,
+ if(type = 'pageview', pg, event_name) AS value,
+ created
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type IN ('pageview', 'custom_event')
+ AND psid != 0
+ ${sessionFiltersQuery}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ )
+ GROUP BY psid
+ HAVING level = {steps:UInt32}
+ ),
+ session_starts AS (
+ SELECT psid, min(firstSeen) AS sessionStart
+ FROM sessions FINAL
+ WHERE pid = {pid:FixedString(12)}
+ GROUP BY psid
+ ),
+ first_pages AS (
+ SELECT psid, min(created) AS firstPageAt
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type = 'pageview'
+ AND psid != 0
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY psid
+ )
+ SELECT
+ round(avgOrNull(if(sessionStart > toDateTime(0) AND sessionStart <= conversionAt, dateDiff('second', sessionStart, conversionAt), NULL)), 2) AS averageSession,
+ quantileExactOrNull(0.5)(if(sessionStart > toDateTime(0) AND sessionStart <= conversionAt, dateDiff('second', sessionStart, conversionAt), NULL)) AS medianSession,
+ quantileExactOrNull(0.75)(if(sessionStart > toDateTime(0) AND sessionStart <= conversionAt, dateDiff('second', sessionStart, conversionAt), NULL)) AS p75Session,
+ round(avgOrNull(if(firstPageAt > toDateTime(0) AND firstPageAt <= conversionAt, dateDiff('second', firstPageAt, conversionAt), NULL)), 2) AS averageFirstPage,
+ quantileExactOrNull(0.5)(if(firstPageAt > toDateTime(0) AND firstPageAt <= conversionAt, dateDiff('second', firstPageAt, conversionAt), NULL)) AS medianFirstPage,
+ quantileExactOrNull(0.75)(if(firstPageAt > toDateTime(0) AND firstPageAt <= conversionAt, dateDiff('second', firstPageAt, conversionAt), NULL)) AS p75FirstPage,
+ round(avgOrNull(if(firstStepAt > toDateTime(0) AND firstStepAt <= conversionAt, dateDiff('second', firstStepAt, conversionAt), NULL)), 2) AS averageFirstStep,
+ quantileExactOrNull(0.5)(if(firstStepAt > toDateTime(0) AND firstStepAt <= conversionAt, dateDiff('second', firstStepAt, conversionAt), NULL)) AS medianFirstStep,
+ quantileExactOrNull(0.75)(if(firstStepAt > toDateTime(0) AND firstStepAt <= conversionAt, dateDiff('second', firstStepAt, conversionAt), NULL)) AS p75FirstStep
+ FROM funnel_sessions fs
+ LEFT JOIN session_starts ss ON fs.psid = ss.psid
+ LEFT JOIN first_pages fp ON fs.psid = fp.psid
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { ...params, ...pageParams },
+ })
+ .then((resultSet) =>
+ resultSet.json<{
+ averageSession: number | null
+ medianSession: number | null
+ p75Session: number | null
+ averageFirstPage: number | null
+ medianFirstPage: number | null
+ p75FirstPage: number | null
+ averageFirstStep: number | null
+ medianFirstStep: number | null
+ p75FirstStep: number | null
+ }>(),
+ )
+
+ const row = data[0]
+
+ if (!row) {
+ return {
+ fromSessionStart: emptyMetric,
+ fromFirstPage: emptyMetric,
+ fromFirstFunnelStep: emptyMetric,
+ }
+ }
+
+ return {
+ fromSessionStart: {
+ average: row.averageSession,
+ median: row.medianSession,
+ p75: row.p75Session,
+ },
+ fromFirstPage: {
+ average: row.averageFirstPage,
+ median: row.medianFirstPage,
+ p75: row.p75FirstPage,
+ },
+ fromFirstFunnelStep: {
+ average: row.averageFirstStep,
+ median: row.medianFirstStep,
+ p75: row.p75FirstStep,
+ },
+ }
+ }
+
async getTotalPageviews(
pid: string,
groupFrom: string,
groupTo: string,
+ filtersQuery = '',
+ filtersParams: Record<string, unknown> = {},
): Promise<number> {
+ const sessionFiltersQuery = filtersQuery
+ ? `AND psid IN (
+ SELECT DISTINCT psid
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type IN ('pageview', 'custom_event')
+ AND psid != 0
+ ${filtersQuery}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ )`
+ : ''
const query = `
SELECT
count() as c
FROM events
WHERE pid = {pid:FixedString(12)}
AND type = 'pageview'
+ ${sessionFiltersQuery}
AND created BETWEEN {groupFrom:String} AND {groupTo:String}
`
const { data } = await clickhouse
.query({
query,
- query_params: { pid, groupFrom, groupTo },
+ query_params: { pid, groupFrom, groupTo, ...filtersParams },
})
.then((resultSet) => resultSet.json<{ c: number }>())
diff --git a/backend/apps/cloud/src/analytics/dto/get-funnel-sessions.dto.ts b/backend/apps/cloud/src/analytics/dto/get-funnel-sessions.dto.ts
index 962d48568..1a033e094 100644
--- a/backend/apps/cloud/src/analytics/dto/get-funnel-sessions.dto.ts
+++ b/backend/apps/cloud/src/analytics/dto/get-funnel-sessions.dto.ts
@@ -52,6 +52,20 @@ export class GetFunnelSessionsDto {
})
funnelId?: string
+ @ApiProperty({
+ description: 'A stringified filters array',
+ required: false,
+ })
+ @IsOptional()
+ filters?: string
+
+ @ApiProperty({
+ description: 'Return sessions that dropped off after this step',
+ required: false,
+ })
+ @IsOptional()
+ dropoff?: boolean | string
+
@ApiProperty({
description: 'Funnel step to get sessions for (1-indexed)',
})
diff --git a/backend/apps/cloud/src/analytics/dto/getFunnels.dto.ts b/backend/apps/cloud/src/analytics/dto/getFunnels.dto.ts
index 6e8229d36..73f52b94e 100644
--- a/backend/apps/cloud/src/analytics/dto/getFunnels.dto.ts
+++ b/backend/apps/cloud/src/analytics/dto/getFunnels.dto.ts
@@ -40,4 +40,11 @@ export class GetFunnelsDto {
description: 'Funnel ID',
})
funnelId?: string
+
+ @ApiProperty({
+ description: 'A stringified filters array',
+ required: false,
+ })
+ @IsOptional()
+ filters?: string
}
diff --git a/backend/apps/cloud/src/analytics/interfaces/index.ts b/backend/apps/cloud/src/analytics/interfaces/index.ts
index f0e6203ad..b16a31f95 100644
--- a/backend/apps/cloud/src/analytics/interfaces/index.ts
+++ b/backend/apps/cloud/src/analytics/interfaces/index.ts
@@ -118,6 +118,22 @@ export interface IFunnelCHResponse {
c: number
}
+export interface IConversionTimeMetric {
+ average: number | null
+ median: number | null
+ p75: number | null
+}
+
+export interface IFunnelBreakdowns {
+ countries?: Record<string, number>
+ devices?: Record<string, number>
+ browsers?: Record<string, number>
+ sources?: Record<string, number>
+ campaigns?: Record<string, number>
+ pages?: Record<string, number>
+ profileTypes?: Record<string, number>
+}
+
export interface IFunnel {
value: string
events: number
@@ -127,11 +143,17 @@ export interface IFunnel {
dropoffPercStep: number
topCountries: Record<string, number>
topSources: Record<string, number>
+ breakdowns?: IFunnelBreakdowns
}
export interface IGetFunnel {
funnel: IFunnel[]
totalPageviews: number
+ timeToConvert?: {
+ fromSessionStart: IConversionTimeMetric
+ fromFirstPage: IConversionTimeMetric
+ fromFirstFunnelStep: IConversionTimeMetric
+ }
}
interface IOverallPeriodStats {
diff --git a/backend/apps/cloud/src/goal/dto/goal.dto.ts b/backend/apps/cloud/src/goal/dto/goal.dto.ts
index a7ac60fba..a48eff9f8 100644
--- a/backend/apps/cloud/src/goal/dto/goal.dto.ts
+++ b/backend/apps/cloud/src/goal/dto/goal.dto.ts
@@ -12,7 +12,16 @@ import {
ArrayMaxSize,
} from 'class-validator'
import { Type } from 'class-transformer'
-import { GoalType, GoalMatchType, MetadataFilter } from '../entity/goal.entity'
+import {
+ GoalType,
+ GoalMatchType,
+ MetadataFilter,
+ GoalCondition,
+ GoalConditions,
+ GoalConditionEventType,
+ GoalConditionOperator,
+ GoalConditionRelation,
+} from '../entity/goal.entity'
// Allowed match types for API (regex is disabled for now)
const ALLOWED_MATCH_TYPES = [GoalMatchType.EXACT, GoalMatchType.CONTAINS]
@@ -31,6 +40,67 @@ class MetadataFilterDto implements MetadataFilter {
value: string
}
+const ALLOWED_CONDITION_RELATIONS: GoalConditionRelation[] = ['AND', 'OR']
+const ALLOWED_CONDITION_EVENT_TYPES: GoalConditionEventType[] = [
+ 'any',
+ GoalType.PAGEVIEW,
+ GoalType.CUSTOM_EVENT,
+]
+const ALLOWED_CONDITION_OPERATORS: GoalConditionOperator[] = [
+ 'equals',
+ 'not_equals',
+ 'contains',
+ 'not_contains',
+ 'exists',
+ 'not_exists',
+]
+
+class GoalConditionDto implements GoalCondition {
+ @ApiPropertyOptional()
+ @IsString()
+ @IsOptional()
+ id?: string
+
+ @ApiProperty({ enum: ALLOWED_CONDITION_EVENT_TYPES })
+ @IsIn(ALLOWED_CONDITION_EVENT_TYPES)
+ eventType: GoalConditionEventType
+
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ @MaxLength(100)
+ field: string
+
+ @ApiProperty({ enum: ALLOWED_CONDITION_OPERATORS })
+ @IsIn(ALLOWED_CONDITION_OPERATORS)
+ operator: GoalConditionOperator
+
+ @ApiPropertyOptional()
+ @IsString()
+ @MaxLength(500)
+ @IsOptional()
+ value?: string
+
+ @ApiPropertyOptional()
+ @IsString()
+ @MaxLength(100)
+ @IsOptional()
+ metadataKey?: string
+}
+
+class GoalConditionsDto implements GoalConditions {
+ @ApiProperty({ enum: ALLOWED_CONDITION_RELATIONS })
+ @IsIn(ALLOWED_CONDITION_RELATIONS)
+ relation: GoalConditionRelation
+
+ @ApiProperty({ type: [GoalConditionDto] })
+ @IsArray()
+ @ArrayMaxSize(20)
+ @ValidateNested({ each: true })
+ @Type(() => GoalConditionDto)
+ conditions: GoalConditionDto[]
+}
+
export class CreateGoalDto {
@ApiProperty({ description: 'Project ID' })
@IsString()
@@ -72,6 +142,12 @@ export class CreateGoalDto {
@Type(() => MetadataFilterDto)
@IsOptional()
metadataFilters?: MetadataFilterDto[]
+
+ @ApiPropertyOptional({ type: GoalConditionsDto })
+ @ValidateNested()
+ @Type(() => GoalConditionsDto)
+ @IsOptional()
+ conditions?: GoalConditionsDto | null
}
export class UpdateGoalDto {
@@ -113,6 +189,12 @@ export class UpdateGoalDto {
@IsOptional()
metadataFilters?: MetadataFilterDto[]
+ @ApiPropertyOptional({ type: GoalConditionsDto })
+ @ValidateNested()
+ @Type(() => GoalConditionsDto)
+ @IsOptional()
+ conditions?: GoalConditionsDto | null
+
@ApiPropertyOptional({ description: 'Whether the goal is active' })
@IsBoolean()
@IsOptional()
@@ -138,6 +220,9 @@ export class GoalDto {
@ApiPropertyOptional({ type: [MetadataFilterDto] })
metadataFilters: MetadataFilterDto[] | null
+ @ApiPropertyOptional({ type: GoalConditionsDto })
+ conditions: GoalConditionsDto | null
+
@ApiProperty()
active: boolean
@@ -163,4 +248,10 @@ export class GoalStatsDto {
@ApiProperty({ description: 'Trend percentage change' })
trend: number
+
+ @ApiPropertyOptional({ description: 'Conversion segment breakdowns' })
+ breakdowns?: Record<string, Record<string, number>>
+
+ @ApiPropertyOptional({ description: 'Conversion timing metrics' })
+ timeToConvert?: Record<string, Record<string, number | null>>
}
diff --git a/backend/apps/cloud/src/goal/entity/goal.entity.ts b/backend/apps/cloud/src/goal/entity/goal.entity.ts
index 628178639..683e6c0c8 100644
--- a/backend/apps/cloud/src/goal/entity/goal.entity.ts
+++ b/backend/apps/cloud/src/goal/entity/goal.entity.ts
@@ -24,6 +24,30 @@ export interface MetadataFilter {
value: string
}
+export type GoalConditionRelation = 'AND' | 'OR'
+export type GoalConditionEventType = 'any' | GoalType
+export type GoalConditionOperator =
+ | 'equals'
+ | 'not_equals'
+ | 'contains'
+ | 'not_contains'
+ | 'exists'
+ | 'not_exists'
+
+export interface GoalCondition {
+ id?: string
+ eventType: GoalConditionEventType
+ field: string
+ operator: GoalConditionOperator
+ value?: string
+ metadataKey?: string
+}
+
+export interface GoalConditions {
+ relation: GoalConditionRelation
+ conditions: GoalCondition[]
+}
+
@Entity()
export class Goal {
@ApiProperty()
@@ -57,6 +81,10 @@ export class Goal {
@Column('json', { nullable: true })
metadataFilters: MetadataFilter[] | null
+ @ApiProperty()
+ @Column('json', { nullable: true })
+ conditions: GoalConditions | null
+
@ApiProperty()
@Column({
type: 'boolean',
diff --git a/backend/apps/cloud/src/goal/goal.controller.ts b/backend/apps/cloud/src/goal/goal.controller.ts
index ac4cde6de..98aad063e 100644
--- a/backend/apps/cloud/src/goal/goal.controller.ts
+++ b/backend/apps/cloud/src/goal/goal.controller.ts
@@ -30,11 +30,17 @@ import { AppLoggerService } from '../logger/logger.service'
import { PlanCode } from '../user/entities/user.entity'
import {
AnalyticsService,
+ DataType,
getLowestPossibleTimeBucket,
} from '../analytics/analytics.service'
import { Auth } from '../auth/decorators'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
-import { Goal, GoalType, GoalMatchType } from './entity/goal.entity'
+import {
+ Goal,
+ GoalType,
+ GoalMatchType,
+ GoalCondition,
+} from './entity/goal.entity'
import {
CreateGoalDto,
UpdateGoalDto,
@@ -76,6 +82,41 @@ const clampPagination = (take?: number, skip?: number) => {
return { take: safeTake, skip: safeSkip }
}
+const GOAL_CONDITION_COLUMNS: Record<string, string> = {
+ page: 'pg',
+ pg: 'pg',
+ event: 'event_name',
+ event_name: 'event_name',
+ host: 'host',
+ ref: 'ref',
+ so: 'so',
+ me: 'me',
+ ca: 'ca',
+ te: 'te',
+ co: 'co',
+ cc: 'cc',
+ dv: 'dv',
+ br: 'br',
+ os: 'os',
+}
+
+type GoalBreakdownKey =
+ | 'countries'
+ | 'devices'
+ | 'browsers'
+ | 'sources'
+ | 'campaigns'
+ | 'pages'
+ | 'profileTypes'
+
+type GoalBreakdowns = Record<GoalBreakdownKey, Record<string, number>>
+
+type TimeToConvertMetric = {
+ average: number | null
+ median: number | null
+ p75: number | null
+}
+
@ApiTags('Goal')
@Controller('goal')
export class GoalController {
@@ -229,6 +270,7 @@ export class GoalController {
goal.matchType = goalDto.matchType
goal.value = goalDto.value || null
goal.metadataFilters = goalDto.metadataFilters || null
+ goal.conditions = goalDto.conditions || null
goal.project = project
const newGoal = await this.goalService.create(goal)
@@ -282,6 +324,7 @@ export class GoalController {
'matchType',
'value',
'metadataFilters',
+ 'conditions',
'active',
]),
}
@@ -395,6 +438,401 @@ export class GoalController {
}
}
+ private buildConditionExpression(
+ condition: GoalCondition,
+ index: number,
+ ): { condition: string; params: Record<string, string> } {
+ const params: Record<string, string> = {}
+ const eventType = condition.eventType || 'any'
+ const parts: string[] = []
+
+ if (
+ eventType === GoalType.PAGEVIEW ||
+ eventType === GoalType.CUSTOM_EVENT
+ ) {
+ params[`conditionType${index}`] = eventType
+ parts.push(`type = {conditionType${index}:String}`)
+ } else if (condition.field === 'pg' || condition.field === 'page') {
+ parts.push(`type = 'pageview'`)
+ } else if (
+ condition.field === 'event' ||
+ condition.field === 'event_name'
+ ) {
+ parts.push(`type = 'custom_event'`)
+ } else {
+ parts.push(`type IN ('pageview', 'custom_event')`)
+ }
+
+ if (condition.field === 'metadata') {
+ const keyParam = `conditionMetaKey${index}`
+ params[keyParam] = condition.metadataKey || ''
+
+ if (!params[keyParam]) {
+ return { condition: '1=0', params: {} }
+ }
+
+ if (condition.operator === 'exists') {
+ parts.push(`indexOf(meta.key, {${keyParam}:String}) > 0`)
+ } else if (condition.operator === 'not_exists') {
+ parts.push(`indexOf(meta.key, {${keyParam}:String}) = 0`)
+ } else {
+ const valueParam = `conditionValue${index}`
+ params[valueParam] = condition.value || ''
+ const valueExpression = `meta.value[indexOf(meta.key, {${keyParam}:String})]`
+ parts.push(`indexOf(meta.key, {${keyParam}:String}) > 0`)
+
+ if (condition.operator === 'contains') {
+ parts.push(
+ `${valueExpression} ILIKE concat('%', {${valueParam}:String}, '%')`,
+ )
+ } else if (condition.operator === 'not_contains') {
+ parts.push(
+ `NOT (${valueExpression} ILIKE concat('%', {${valueParam}:String}, '%'))`,
+ )
+ } else {
+ parts.push(
+ `${valueExpression} ${condition.operator === 'not_equals' ? '!=' : '='} {${valueParam}:String}`,
+ )
+ }
+ }
+
+ return { condition: `(${parts.join(' AND ')})`, params }
+ }
+
+ const column = GOAL_CONDITION_COLUMNS[condition.field]
+ if (!column) {
+ return { condition: '1=0', params: {} }
+ }
+
+ if (condition.operator === 'exists') {
+ parts.push(`${column} IS NOT NULL AND ${column} != ''`)
+ } else if (condition.operator === 'not_exists') {
+ parts.push(`(${column} IS NULL OR ${column} = '')`)
+ } else {
+ const valueParam = `conditionValue${index}`
+ params[valueParam] = condition.value || ''
+
+ if (!params[valueParam]) {
+ return { condition: '1=0', params: {} }
+ }
+
+ if (condition.operator === 'contains') {
+ parts.push(`${column} ILIKE concat('%', {${valueParam}:String}, '%')`)
+ } else if (condition.operator === 'not_contains') {
+ parts.push(
+ `NOT (${column} ILIKE concat('%', {${valueParam}:String}, '%'))`,
+ )
+ } else {
+ parts.push(
+ `${column} ${condition.operator === 'not_equals' ? '!=' : '='} {${valueParam}:String}`,
+ )
+ }
+ }
+
+ return { condition: `(${parts.join(' AND ')})`, params }
+ }
+
+ private buildGoalEventCondition(goal: Goal): {
+ condition: string
+ params: Record<string, string>
+ } {
+ if (goal.conditions?.conditions?.length) {
+ const relation = goal.conditions.relation === 'OR' ? ' OR ' : ' AND '
+ const builtConditions = goal.conditions.conditions.map(
+ (condition, index) => this.buildConditionExpression(condition, index),
+ )
+
+ return {
+ condition: `(${builtConditions
+ .map((condition) => condition.condition)
+ .join(relation)})`,
+ params: Object.assign(
+ {},
+ ...builtConditions.map((condition) => condition.params),
+ ),
+ }
+ }
+
+ const goalType =
+ goal.type === GoalType.CUSTOM_EVENT ? 'custom_event' : 'pageview'
+ const { condition: matchCondition, params: matchParams } =
+ this.buildGoalMatchCondition(goal)
+ const { condition: metaCondition, params: metaParams } =
+ this.buildMetadataCondition(goal)
+
+ return {
+ condition: `(type = '${goalType}' AND ${matchCondition} ${metaCondition})`,
+ params: { ...matchParams, ...metaParams },
+ }
+ }
+
+ private buildGoalConversionsSubquery(
+ goal: Goal,
+ filtersQuery: string,
+ ): {
+ query: string
+ params: Record<string, string | number>
+ } {
+ const conditions = goal.conditions?.conditions || []
+
+ if (conditions.length > 1 && goal.conditions?.relation === 'AND') {
+ const builtConditions = conditions.map((condition, index) =>
+ this.buildConditionExpression(condition, index),
+ )
+
+ return {
+ query: `
+ SELECT psid, max(matchedAt) AS conversionAt, 1 AS conversions
+ FROM (
+ SELECT psid, conditionIndex, min(created) AS matchedAt
+ FROM (
+ ${builtConditions
+ .map(
+ (condition, index) => `
+ SELECT psid, created, ${index} AS conditionIndex
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND (${condition.condition})
+ ${filtersQuery}
+ AND psid != 0
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ `,
+ )
+ .join(' UNION ALL ')}
+ )
+ GROUP BY psid, conditionIndex
+ )
+ GROUP BY psid
+ HAVING countDistinct(conditionIndex) = {conditionsCount:UInt32}
+ `,
+ params: {
+ ...Object.assign(
+ {},
+ ...builtConditions.map((condition) => condition.params),
+ ),
+ conditionsCount: conditions.length,
+ },
+ }
+ }
+
+ const { condition: goalCondition, params: goalParams } =
+ this.buildGoalEventCondition(goal)
+
+ return {
+ query: `
+ SELECT psid, min(created) AS conversionAt, count() AS conversions
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND (${goalCondition})
+ ${filtersQuery}
+ AND psid != 0
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY psid
+ `,
+ params: goalParams,
+ }
+ }
+
+ private async getGoalBreakdowns(
+ projectId: string,
+ groupFrom: string,
+ groupTo: string,
+ conversionsSubquery: string,
+ queryParams: Record<string, unknown>,
+ ): Promise<GoalBreakdowns> {
+ const emptyBreakdowns: GoalBreakdowns = {
+ countries: {},
+ devices: {},
+ browsers: {},
+ sources: {},
+ campaigns: {},
+ pages: {},
+ profileTypes: {},
+ }
+
+ const query = `
+ WITH conversions AS (
+ ${conversionsSubquery}
+ ),
+ session_info AS (
+ SELECT
+ c.psid AS psid,
+ argMin(e.cc, e.created) AS cc,
+ argMin(e.dv, e.created) AS dv,
+ argMin(e.br, e.created) AS br,
+ argMin(if(e.so IS NOT NULL AND e.so != '', e.so, if(domain(e.ref) != '', domain(e.ref), 'Direct / None')), e.created) AS source,
+ argMin(e.ca, e.created) AS campaign,
+ argMin(e.pg, e.created) AS page,
+ argMax(e.profileId, e.created) AS profileId
+ FROM conversions c
+ INNER JOIN events e ON c.psid = e.psid
+ WHERE e.pid = {pid:FixedString(12)}
+ AND e.type IN ('pageview', 'custom_event')
+ AND e.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ AND e.created <= c.conversionAt
+ GROUP BY c.psid
+ )
+ SELECT kind, val, cnt FROM (
+ SELECT 'countries' AS kind, cc AS val, count() AS cnt
+ FROM session_info
+ WHERE cc IS NOT NULL AND cc != ''
+ GROUP BY cc
+
+ UNION ALL
+
+ SELECT 'devices' AS kind, dv AS val, count() AS cnt
+ FROM session_info
+ WHERE dv IS NOT NULL AND dv != ''
+ GROUP BY dv
+
+ UNION ALL
+
+ SELECT 'browsers' AS kind, br AS val, count() AS cnt
+ FROM session_info
+ WHERE br IS NOT NULL AND br != ''
+ GROUP BY br
+
+ UNION ALL
+
+ SELECT 'sources' AS kind, source AS val, count() AS cnt
+ FROM session_info
+ GROUP BY val
+
+ UNION ALL
+
+ SELECT 'campaigns' AS kind, campaign AS val, count() AS cnt
+ FROM session_info
+ WHERE campaign IS NOT NULL AND campaign != ''
+ GROUP BY campaign
+
+ UNION ALL
+
+ SELECT 'pages' AS kind, page AS val, count() AS cnt
+ FROM session_info
+ WHERE page IS NOT NULL AND page != ''
+ GROUP BY page
+
+ UNION ALL
+
+ SELECT 'profileTypes' AS kind, if(startsWith(profileId, '${AnalyticsService.PROFILE_PREFIX_USER}'), 'identified', 'anonymous') AS val, count() AS cnt
+ FROM session_info
+ WHERE profileId IS NOT NULL AND profileId != ''
+ GROUP BY val
+ )
+ ORDER BY kind, cnt DESC, val ASC
+ LIMIT 5 BY kind
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { ...queryParams, pid: projectId, groupFrom, groupTo },
+ })
+ .then((resultSet) =>
+ resultSet.json<{
+ kind: GoalBreakdownKey
+ val: string
+ cnt: number
+ }>(),
+ )
+
+ for (const row of data) {
+ if (!emptyBreakdowns[row.kind] || !row.val) {
+ continue
+ }
+
+ emptyBreakdowns[row.kind][row.val] = row.cnt
+ }
+
+ return emptyBreakdowns
+ }
+
+ private async getGoalTimeToConvert(
+ projectId: string,
+ groupFrom: string,
+ groupTo: string,
+ conversionsSubquery: string,
+ queryParams: Record<string, unknown>,
+ ): Promise<{
+ fromSessionStart: TimeToConvertMetric
+ fromFirstPage: TimeToConvertMetric
+ }> {
+ const emptyMetric: TimeToConvertMetric = {
+ average: null,
+ median: null,
+ p75: null,
+ }
+
+ const query = `
+ WITH conversions AS (
+ ${conversionsSubquery}
+ ),
+ session_starts AS (
+ SELECT psid, min(firstSeen) AS sessionStart
+ FROM sessions FINAL
+ WHERE pid = {pid:FixedString(12)}
+ GROUP BY psid
+ ),
+ first_pages AS (
+ SELECT psid, min(created) AS firstPageAt
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type = 'pageview'
+ AND psid != 0
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY psid
+ )
+ SELECT
+ round(avgOrNull(if(sessionStart > toDateTime(0) AND sessionStart <= conversionAt, dateDiff('second', sessionStart, conversionAt), NULL)), 2) AS averageSession,
+ quantileExactOrNull(0.5)(if(sessionStart > toDateTime(0) AND sessionStart <= conversionAt, dateDiff('second', sessionStart, conversionAt), NULL)) AS medianSession,
+ quantileExactOrNull(0.75)(if(sessionStart > toDateTime(0) AND sessionStart <= conversionAt, dateDiff('second', sessionStart, conversionAt), NULL)) AS p75Session,
+ round(avgOrNull(if(firstPageAt > toDateTime(0) AND firstPageAt <= conversionAt, dateDiff('second', firstPageAt, conversionAt), NULL)), 2) AS averageFirstPage,
+ quantileExactOrNull(0.5)(if(firstPageAt > toDateTime(0) AND firstPageAt <= conversionAt, dateDiff('second', firstPageAt, conversionAt), NULL)) AS medianFirstPage,
+ quantileExactOrNull(0.75)(if(firstPageAt > toDateTime(0) AND firstPageAt <= conversionAt, dateDiff('second', firstPageAt, conversionAt), NULL)) AS p75FirstPage
+ FROM conversions c
+ LEFT JOIN session_starts ss ON c.psid = ss.psid
+ LEFT JOIN first_pages fp ON c.psid = fp.psid
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { ...queryParams, pid: projectId, groupFrom, groupTo },
+ })
+ .then((resultSet) =>
+ resultSet.json<{
+ averageSession: number | null
+ medianSession: number | null
+ p75Session: number | null
+ averageFirstPage: number | null
+ medianFirstPage: number | null
+ p75FirstPage: number | null
+ }>(),
+ )
+
+ const row = data[0]
+
+ if (!row) {
+ return {
+ fromSessionStart: emptyMetric,
+ fromFirstPage: emptyMetric,
+ }
+ }
+
+ return {
+ fromSessionStart: {
+ average: row.averageSession,
+ median: row.medianSession,
+ p75: row.p75Session,
+ },
+ fromFirstPage: {
+ average: row.averageFirstPage,
+ median: row.medianFirstPage,
+ p75: row.p75FirstPage,
+ },
+ }
+ }
+
@ApiBearerAuth()
@Get('/:id/stats')
@Auth(true, true)
@@ -406,6 +844,7 @@ export class GoalController {
@Query('from') from?: string,
@Query('to') to?: string,
@Query('timezone') timezone?: string,
+ @Query('filters') filters?: string,
) {
this.logger.log({ userId, id, period, from, to }, 'GET /goal/:id/stats')
@@ -429,33 +868,29 @@ export class GoalController {
safeTimezone,
)
- const goalType =
- goal.type === GoalType.CUSTOM_EVENT ? 'custom_event' : 'pageview'
- const { condition: matchCondition, params: matchParams } =
- this.buildGoalMatchCondition(goal)
- const { condition: metaCondition, params: metaParams } =
- this.buildMetadataCondition(goal)
+ const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(
+ filters || '[]',
+ DataType.ANALYTICS,
+ )
+ const { query: conversionsSubquery, params: goalParams } =
+ this.buildGoalConversionsSubquery(goal, filtersQuery)
- // Get conversions for current period
const conversionsQuery = `
+ WITH conversions AS (
+ ${conversionsSubquery}
+ )
SELECT
- count(*) as conversions,
- uniqExact(psid) as uniqueSessions
- FROM events
- WHERE
- pid = {pid:FixedString(12)}
- AND type = '${goalType}'
- AND ${matchCondition}
- ${metaCondition}
- AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ sum(conversions) as conversions,
+ count() as uniqueSessions
+ FROM conversions
`
const queryParams = {
pid: goal.project.id,
groupFrom: groupFromUTC,
groupTo: groupToUTC,
- ...matchParams,
- ...metaParams,
+ ...goalParams,
+ ...filtersParams,
}
const { data: conversionsData } = await clickhouse
@@ -467,13 +902,13 @@ export class GoalController {
const conversions = conversionsData[0]?.conversions || 0
const uniqueSessions = conversionsData[0]?.uniqueSessions || 0
- // Get total unique sessions for conversion rate
const totalSessionsQuery = `
SELECT uniqExact(psid) as totalSessions
FROM events
WHERE
pid = {pid:FixedString(12)}
- AND type = 'pageview'
+ AND type IN ('pageview', 'custom_event')
+ ${filtersQuery}
AND created BETWEEN {groupFrom:String} AND {groupTo:String}
`
@@ -484,6 +919,7 @@ export class GoalController {
pid: goal.project.id,
groupFrom: groupFromUTC,
groupTo: groupToUTC,
+ ...filtersParams,
},
})
.then((resultSet) => resultSet.json<{ totalSessions: number }>())
@@ -491,7 +927,6 @@ export class GoalController {
const totalSessions = totalData[0]?.totalSessions || 1
const conversionRate = _round((uniqueSessions / totalSessions) * 100, 2)
- // Get previous period conversions for trend
const periodDays = dayjs(groupToUTC).diff(dayjs(groupFromUTC), 'day') || 1
const previousFrom = dayjs(groupFromUTC)
.subtract(periodDays, 'day')
@@ -502,8 +937,8 @@ export class GoalController {
pid: goal.project.id,
groupFrom: previousFrom,
groupTo: previousTo,
- ...matchParams,
- ...metaParams,
+ ...goalParams,
+ ...filtersParams,
}
const { data: previousData } = await clickhouse
@@ -523,12 +958,31 @@ export class GoalController {
? 100
: 0
+ const [breakdowns, timeToConvert] = await Promise.all([
+ this.getGoalBreakdowns(
+ goal.project.id,
+ groupFromUTC,
+ groupToUTC,
+ conversionsSubquery,
+ { ...goalParams, ...filtersParams },
+ ),
+ this.getGoalTimeToConvert(
+ goal.project.id,
+ groupFromUTC,
+ groupToUTC,
+ conversionsSubquery,
+ { ...goalParams, ...filtersParams },
+ ),
+ ])
+
return {
conversions,
uniqueSessions,
conversionRate,
previousConversions,
trend,
+ breakdowns,
+ timeToConvert,
}
}
@@ -617,6 +1071,7 @@ export class GoalController {
@Query('to') to?: string,
@Query('timeBucket') timeBucket?: string,
@Query('timezone') timezone?: string,
+ @Query('filters') filters?: string,
) {
this.logger.log(
{ userId, id, period, from, to, timeBucket },
@@ -644,7 +1099,6 @@ export class GoalController {
safeTimezone,
)
- // Generate complete X axis with all time buckets
const { xShifted } = this.analyticsService.generateXAxis(
resolvedTimeBucket as any,
groupFromUTC,
@@ -652,8 +1106,6 @@ export class GoalController {
safeTimezone,
)
- const goalType =
- goal.type === GoalType.CUSTOM_EVENT ? 'custom_event' : 'pageview'
const timeBucketFunc = Object.prototype.hasOwnProperty.call(
timeBucketConversion,
resolvedTimeBucket,
@@ -662,26 +1114,26 @@ export class GoalController {
: 'toStartOfDay'
const [selector, groupBy] = this.getGroupSubquery(resolvedTimeBucket)
- const { condition: matchCondition, params: matchParams } =
- this.buildGoalMatchCondition(goal)
- const { condition: metaCondition, params: metaParams } =
- this.buildMetadataCondition(goal)
+ const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(
+ filters || '[]',
+ DataType.ANALYTICS,
+ )
+ const { query: conversionsSubquery, params: goalParams } =
+ this.buildGoalConversionsSubquery(goal, filtersQuery)
const chartQuery = `
SELECT
${selector},
- count(*) as conversions,
- uniqExact(psid) as uniqueSessions
+ sum(conversions) as conversions,
+ count() as uniqueSessions
FROM (
- SELECT *,
- ${timeBucketFunc}(toTimeZone(created, {timezone:String})) as tz_created
- FROM events
- WHERE
- pid = {pid:FixedString(12)}
- AND type = '${goalType}'
- AND ${matchCondition}
- ${metaCondition}
- AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ SELECT
+ psid,
+ conversions,
+ ${timeBucketFunc}(toTimeZone(conversionAt, {timezone:String})) as tz_created
+ FROM (
+ ${conversionsSubquery}
+ )
) as subquery
GROUP BY ${groupBy}
ORDER BY ${groupBy}
@@ -692,8 +1144,8 @@ export class GoalController {
groupFrom: groupFromUTC,
groupTo: groupToUTC,
timezone: safeTimezone,
- ...matchParams,
- ...metaParams,
+ ...goalParams,
+ ...filtersParams,
}
const { data } = await clickhouse
diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.ts
index 278038d98..17cc8f3d6 100644
--- a/backend/apps/community/src/analytics/analytics.controller.ts
+++ b/backend/apps/community/src/analytics/analytics.controller.ts
@@ -390,6 +390,7 @@ export class AnalyticsController {
timezone = DEFAULT_TIMEZONE,
pages,
funnelId,
+ filters,
} = data
const pagesArr = await this.analyticsService.getPagesArray(
@@ -430,24 +431,40 @@ export class AnalyticsController {
diff,
)
- const params = { pid, groupFrom, groupTo }
+ const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(
+ filters || '[]',
+ DataType.ANALYTICS,
+ )
+ const params = { pid, groupFrom, groupTo, ...filtersParams }
let funnel: IFunnel[] = []
let totalPageviews: number = 0
- let stepDetails: {
- countries: Record<number, Record<string, number>>
- sources: Record<number, Record<string, number>>
- } = { countries: {}, sources: {} }
+ let timeToConvert: IGetFunnel['timeToConvert']
+ let stepDetails = {
+ countries: {},
+ devices: {},
+ browsers: {},
+ sources: {},
+ campaigns: {},
+ pages: {},
+ profileTypes: {},
+ } as Record<string, Record<number, Record<string, number>>>
const promises = [
(async () => {
- funnel = await this.analyticsService.getFunnel(pagesArr, params)
+ funnel = await this.analyticsService.getFunnel(
+ pagesArr,
+ params,
+ filtersQuery,
+ )
})(),
(async () => {
totalPageviews = await this.analyticsService.getTotalPageviews(
pid,
groupFrom,
groupTo,
+ filtersQuery,
+ filtersParams,
)
})(),
(async () => {
@@ -455,11 +472,19 @@ export class AnalyticsController {
stepDetails = await this.analyticsService.getFunnelStepDetails(
pagesArr,
params,
+ filtersQuery,
)
} catch (e) {
this.logger.error(e, 'GET /analytics/funnel - getFunnelStepDetails')
}
})(),
+ (async () => {
+ timeToConvert = await this.analyticsService.getFunnelTimeToConvert(
+ pagesArr,
+ params,
+ filtersQuery,
+ )
+ })(),
]
await Promise.all(promises)
@@ -467,9 +492,18 @@ export class AnalyticsController {
for (let i = 0; i < funnel.length; i++) {
funnel[i].topCountries = stepDetails.countries[i + 1] || {}
funnel[i].topSources = stepDetails.sources[i + 1] || {}
+ funnel[i].breakdowns = {
+ countries: stepDetails.countries[i + 1] || {},
+ devices: stepDetails.devices[i + 1] || {},
+ browsers: stepDetails.browsers[i + 1] || {},
+ sources: stepDetails.sources[i + 1] || {},
+ campaigns: stepDetails.campaigns[i + 1] || {},
+ pages: stepDetails.pages[i + 1] || {},
+ profileTypes: stepDetails.profileTypes[i + 1] || {},
+ }
}
- return { funnel, totalPageviews }
+ return { funnel, totalPageviews, timeToConvert }
}
@Get('funnel-sessions')
@@ -488,6 +522,8 @@ export class AnalyticsController {
pages,
funnelId,
step,
+ filters,
+ dropoff,
} = data
await this.analyticsService.checkProjectAccess(
@@ -546,7 +582,12 @@ export class AnalyticsController {
diff,
)
- const params = { pid, groupFrom, groupTo }
+ const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(
+ filters || '[]',
+ DataType.ANALYTICS,
+ )
+ const params = { pid, groupFrom, groupTo, ...filtersParams }
+ const isDropoff = dropoff === true || dropoff === 'true'
const sessions = await this.analyticsService.getFunnelSessionsList(
pagesArr,
@@ -555,6 +596,8 @@ export class AnalyticsController {
step,
take,
skip,
+ filtersQuery,
+ isDropoff,
)
return { sessions, take, skip }
diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.ts
index 982f8d294..1541627da 100644
--- a/backend/apps/community/src/analytics/analytics.service.ts
+++ b/backend/apps/community/src/analytics/analytics.service.ts
@@ -89,6 +89,8 @@ import {
IAggregatedMetadata,
IFunnelCHResponse,
IFunnel,
+ IFunnelBreakdowns,
+ IConversionTimeMetric,
IOverall,
IOverallPerformance,
IPageflow,
@@ -124,6 +126,11 @@ const MAX_FILTER_VALUES = 100
const SOFTWARE_WITH_PATCH_VERSION = ['GameVault']
+type FunnelStepDetails = Record<
+ keyof Required<IFunnelBreakdowns>,
+ Record<number, Record<string, number>>
+>
+
const GMT_0_TIMEZONES = [
'Atlantic/Azores',
'Etc/GMT',
@@ -1629,11 +1636,27 @@ export class AnalyticsService {
dropoffPercStep: 0,
topCountries: {},
topSources: {},
+ breakdowns: {},
}))
}
- async getFunnel(pages: string[], params: any): Promise<IFunnel[]> {
+ async getFunnel(
+ pages: string[],
+ params: any,
+ filtersQuery = '',
+ ): Promise<IFunnel[]> {
const pageParams: Record<string, string> = {}
+ const sessionFiltersQuery = filtersQuery
+ ? `AND psid IN (
+ SELECT DISTINCT psid
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type IN ('pageview', 'custom_event')
+ AND psid != 0
+ ${filtersQuery}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ )`
+ : ''
const pagesStr = _join(
_map(pages, (value, index) => {
@@ -1661,6 +1684,7 @@ export class AnalyticsService {
WHERE pid = {pid:FixedString(12)}
AND type IN ('pageview', 'custom_event')
AND psid != 0
+ ${sessionFiltersQuery}
AND created BETWEEN {groupFrom:String} AND {groupTo:String}
)
GROUP BY psid
@@ -1687,11 +1711,20 @@ export class AnalyticsService {
async getFunnelStepDetails(
pages: string[],
params: any,
- ): Promise<{
- countries: Record<number, Record<string, number>>
- sources: Record<number, Record<string, number>>
- }> {
+ filtersQuery = '',
+ ): Promise<FunnelStepDetails> {
const pageParams: Record<string, string> = {}
+ const sessionFiltersQuery = filtersQuery
+ ? `AND psid IN (
+ SELECT DISTINCT psid
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type IN ('pageview', 'custom_event')
+ AND psid != 0
+ ${filtersQuery}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ )`
+ : ''
const pagesStr = _join(
_map(pages, (value, index) => {
@@ -1715,6 +1748,7 @@ export class AnalyticsService {
WHERE pid = {pid:FixedString(12)}
AND type IN ('pageview', 'custom_event')
AND psid != 0
+ ${sessionFiltersQuery}
AND created BETWEEN {groupFrom:String} AND {groupTo:String}
)
GROUP BY psid
@@ -1728,7 +1762,12 @@ export class AnalyticsService {
SELECT
psid,
argMin(cc, created) AS cc,
- argMin(if(domain(ref) != '', domain(ref), 'Direct / None'), created) AS source
+ argMin(dv, created) AS dv,
+ argMin(br, created) AS br,
+ argMin(if(so IS NOT NULL AND so != '', so, if(domain(ref) != '', domain(ref), 'Direct / None')), created) AS source,
+ argMin(ca, created) AS campaign,
+ argMin(pg, created) AS page,
+ argMax(profileId, created) AS profileId
FROM events
WHERE pid = {pid:FixedString(12)}
AND type IN ('pageview', 'custom_event')
@@ -1737,7 +1776,7 @@ export class AnalyticsService {
GROUP BY psid
)
SELECT step, type, val, cnt FROM (
- SELECT e.step AS step, 'cc' AS type, si.cc AS val, count() AS cnt
+ SELECT e.step AS step, 'countries' AS type, si.cc AS val, count() AS cnt
FROM expanded e
INNER JOIN session_info si ON e.psid = si.psid
WHERE si.cc != ''
@@ -1745,13 +1784,53 @@ export class AnalyticsService {
UNION ALL
- SELECT e.step AS step, 'so' AS type, si.source AS val, count() AS cnt
+ SELECT e.step AS step, 'devices' AS type, si.dv AS val, count() AS cnt
+ FROM expanded e
+ INNER JOIN session_info si ON e.psid = si.psid
+ WHERE si.dv != ''
+ GROUP BY e.step, si.dv
+
+ UNION ALL
+
+ SELECT e.step AS step, 'browsers' AS type, si.br AS val, count() AS cnt
+ FROM expanded e
+ INNER JOIN session_info si ON e.psid = si.psid
+ WHERE si.br != ''
+ GROUP BY e.step, si.br
+
+ UNION ALL
+
+ SELECT e.step AS step, 'sources' AS type, si.source AS val, count() AS cnt
FROM expanded e
INNER JOIN session_info si ON e.psid = si.psid
GROUP BY e.step, si.source
+
+ UNION ALL
+
+ SELECT e.step AS step, 'campaigns' AS type, si.campaign AS val, count() AS cnt
+ FROM expanded e
+ INNER JOIN session_info si ON e.psid = si.psid
+ WHERE si.campaign != ''
+ GROUP BY e.step, si.campaign
+
+ UNION ALL
+
+ SELECT e.step AS step, 'pages' AS type, si.page AS val, count() AS cnt
+ FROM expanded e
+ INNER JOIN session_info si ON e.psid = si.psid
+ WHERE si.page != ''
+ GROUP BY e.step, si.page
+
+ UNION ALL
+
+ SELECT e.step AS step, 'profileTypes' AS type, if(startsWith(si.profileId, '${AnalyticsService.PROFILE_PREFIX_USER}'), 'identified', 'anonymous') AS val, count() AS cnt
+ FROM expanded e
+ INNER JOIN session_info si ON e.psid = si.psid
+ WHERE si.profileId != ''
+ GROUP BY e.step, val
)
ORDER BY step, type, cnt DESC, val ASC
- LIMIT 3 BY step, type
+ LIMIT 5 BY step, type
`
const { data } = await clickhouse
@@ -1768,21 +1847,27 @@ export class AnalyticsService {
}>(),
)
- const countries: Record<number, Record<string, number>> = {}
- const sources: Record<number, Record<string, number>> = {}
+ const details: FunnelStepDetails = {
+ countries: {},
+ devices: {},
+ browsers: {},
+ sources: {},
+ campaigns: {},
+ pages: {},
+ profileTypes: {},
+ }
for (const row of data) {
const { step } = row
- if (row.type === 'cc') {
- if (!countries[step]) countries[step] = {}
- countries[step][row.val] = row.cnt
- } else if (row.type === 'so') {
- if (!sources[step]) sources[step] = {}
- sources[step][row.val] = row.cnt
+ const type = row.type as keyof FunnelStepDetails
+
+ if (details[type]) {
+ if (!details[type][step]) details[type][step] = {}
+ details[type][step][row.val] = row.cnt
}
}
- return { countries, sources }
+ return details
}
async getFunnelSessionsList(
@@ -1792,8 +1877,24 @@ export class AnalyticsService {
step: number,
take = 30,
skip = 0,
+ filtersQuery = '',
+ dropoff = false,
): Promise<object | void> {
const pageParams: Record<string, string> = {}
+ const levelCondition = dropoff
+ ? 'level = {step:UInt32}'
+ : 'level >= {step:UInt32}'
+ const sessionFiltersQuery = filtersQuery
+ ? `AND psid IN (
+ SELECT DISTINCT psid
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type IN ('pageview', 'custom_event')
+ AND psid != 0
+ ${filtersQuery}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ )`
+ : ''
const pagesStr = _join(
_map(pages, (value, index) => {
@@ -1819,11 +1920,12 @@ export class AnalyticsService {
WHERE pid = {pid:FixedString(12)}
AND type IN ('pageview', 'custom_event')
AND psid != 0
+ ${sessionFiltersQuery}
AND created BETWEEN {groupFrom:String} AND {groupTo:String}
)
GROUP BY psid
)
- WHERE level >= {step:UInt32}
+ WHERE ${levelCondition}
),
distinct_sessions AS (
SELECT
@@ -1940,23 +2042,174 @@ export class AnalyticsService {
return data
}
+ async getFunnelTimeToConvert(
+ pages: string[],
+ params: any,
+ filtersQuery = '',
+ ): Promise<{
+ fromSessionStart: IConversionTimeMetric
+ fromFirstPage: IConversionTimeMetric
+ fromFirstFunnelStep: IConversionTimeMetric
+ }> {
+ const emptyMetric: IConversionTimeMetric = {
+ average: null,
+ median: null,
+ p75: null,
+ }
+ const pageParams: Record<string, string | number> = {
+ steps: pages.length,
+ }
+ const sessionFiltersQuery = filtersQuery
+ ? `AND psid IN (
+ SELECT DISTINCT psid
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type IN ('pageview', 'custom_event')
+ AND psid != 0
+ ${filtersQuery}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ )`
+ : ''
+
+ const pagesStr = _join(
+ _map(pages, (value, index) => {
+ pageParams[`v${index}`] = value
+ return `value={v${index}:String}`
+ }),
+ ',',
+ )
+
+ const query = `
+ WITH funnel_sessions AS (
+ SELECT
+ psid,
+ minIf(created, value = {v0:String}) AS firstStepAt,
+ maxIf(created, value = {v${pages.length - 1}:String}) AS conversionAt,
+ CAST(windowFunnel(86400)(created, ${pagesStr}) AS UInt64) AS level
+ FROM (
+ SELECT
+ psid,
+ if(type = 'pageview', pg, event_name) AS value,
+ created
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type IN ('pageview', 'custom_event')
+ AND psid != 0
+ ${sessionFiltersQuery}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ )
+ GROUP BY psid
+ HAVING level = {steps:UInt32}
+ ),
+ session_starts AS (
+ SELECT psid, min(firstSeen) AS sessionStart
+ FROM sessions FINAL
+ WHERE pid = {pid:FixedString(12)}
+ GROUP BY psid
+ ),
+ first_pages AS (
+ SELECT psid, min(created) AS firstPageAt
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type = 'pageview'
+ AND psid != 0
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY psid
+ )
+ SELECT
+ round(avgOrNull(if(sessionStart > toDateTime(0) AND sessionStart <= conversionAt, dateDiff('second', sessionStart, conversionAt), NULL)), 2) AS averageSession,
+ quantileExactOrNull(0.5)(if(sessionStart > toDateTime(0) AND sessionStart <= conversionAt, dateDiff('second', sessionStart, conversionAt), NULL)) AS medianSession,
+ quantileExactOrNull(0.75)(if(sessionStart > toDateTime(0) AND sessionStart <= conversionAt, dateDiff('second', sessionStart, conversionAt), NULL)) AS p75Session,
+ round(avgOrNull(if(firstPageAt > toDateTime(0) AND firstPageAt <= conversionAt, dateDiff('second', firstPageAt, conversionAt), NULL)), 2) AS averageFirstPage,
+ quantileExactOrNull(0.5)(if(firstPageAt > toDateTime(0) AND firstPageAt <= conversionAt, dateDiff('second', firstPageAt, conversionAt), NULL)) AS medianFirstPage,
+ quantileExactOrNull(0.75)(if(firstPageAt > toDateTime(0) AND firstPageAt <= conversionAt, dateDiff('second', firstPageAt, conversionAt), NULL)) AS p75FirstPage,
+ round(avgOrNull(if(firstStepAt > toDateTime(0) AND firstStepAt <= conversionAt, dateDiff('second', firstStepAt, conversionAt), NULL)), 2) AS averageFirstStep,
+ quantileExactOrNull(0.5)(if(firstStepAt > toDateTime(0) AND firstStepAt <= conversionAt, dateDiff('second', firstStepAt, conversionAt), NULL)) AS medianFirstStep,
+ quantileExactOrNull(0.75)(if(firstStepAt > toDateTime(0) AND firstStepAt <= conversionAt, dateDiff('second', firstStepAt, conversionAt), NULL)) AS p75FirstStep
+ FROM funnel_sessions fs
+ LEFT JOIN session_starts ss ON fs.psid = ss.psid
+ LEFT JOIN first_pages fp ON fs.psid = fp.psid
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { ...params, ...pageParams },
+ })
+ .then((resultSet) =>
+ resultSet.json<{
+ averageSession: number | null
+ medianSession: number | null
+ p75Session: number | null
+ averageFirstPage: number | null
+ medianFirstPage: number | null
+ p75FirstPage: number | null
+ averageFirstStep: number | null
+ medianFirstStep: number | null
+ p75FirstStep: number | null
+ }>(),
+ )
+
+ const row = data[0]
+
+ if (!row) {
+ return {
+ fromSessionStart: emptyMetric,
+ fromFirstPage: emptyMetric,
+ fromFirstFunnelStep: emptyMetric,
+ }
+ }
+
+ return {
+ fromSessionStart: {
+ average: row.averageSession,
+ median: row.medianSession,
+ p75: row.p75Session,
+ },
+ fromFirstPage: {
+ average: row.averageFirstPage,
+ median: row.medianFirstPage,
+ p75: row.p75FirstPage,
+ },
+ fromFirstFunnelStep: {
+ average: row.averageFirstStep,
+ median: row.medianFirstStep,
+ p75: row.p75FirstStep,
+ },
+ }
+ }
+
async getTotalPageviews(
pid: string,
groupFrom: string,
groupTo: string,
+ filtersQuery = '',
+ filtersParams: Record<string, unknown> = {},
): Promise<number> {
+ const sessionFiltersQuery = filtersQuery
+ ? `AND psid IN (
+ SELECT DISTINCT psid
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type IN ('pageview', 'custom_event')
+ AND psid != 0
+ ${filtersQuery}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ )`
+ : ''
const query = `
SELECT
count() as c
FROM events
WHERE pid = {pid:FixedString(12)}
AND type = 'pageview'
+ ${sessionFiltersQuery}
AND created BETWEEN {groupFrom:String} AND {groupTo:String}
`
const { data } = await clickhouse
.query({
query,
- query_params: { pid, groupFrom, groupTo },
+ query_params: { pid, groupFrom, groupTo, ...filtersParams },
})
.then((resultSet) => resultSet.json<{ c: number }>())
diff --git a/backend/apps/community/src/analytics/dto/get-funnel-sessions.dto.ts b/backend/apps/community/src/analytics/dto/get-funnel-sessions.dto.ts
index 962d48568..1a033e094 100644
--- a/backend/apps/community/src/analytics/dto/get-funnel-sessions.dto.ts
+++ b/backend/apps/community/src/analytics/dto/get-funnel-sessions.dto.ts
@@ -52,6 +52,20 @@ export class GetFunnelSessionsDto {
})
funnelId?: string
+ @ApiProperty({
+ description: 'A stringified filters array',
+ required: false,
+ })
+ @IsOptional()
+ filters?: string
+
+ @ApiProperty({
+ description: 'Return sessions that dropped off after this step',
+ required: false,
+ })
+ @IsOptional()
+ dropoff?: boolean | string
+
@ApiProperty({
description: 'Funnel step to get sessions for (1-indexed)',
})
diff --git a/backend/apps/community/src/analytics/dto/getFunnels.dto.ts b/backend/apps/community/src/analytics/dto/getFunnels.dto.ts
index 6e8229d36..73f52b94e 100644
--- a/backend/apps/community/src/analytics/dto/getFunnels.dto.ts
+++ b/backend/apps/community/src/analytics/dto/getFunnels.dto.ts
@@ -40,4 +40,11 @@ export class GetFunnelsDto {
description: 'Funnel ID',
})
funnelId?: string
+
+ @ApiProperty({
+ description: 'A stringified filters array',
+ required: false,
+ })
+ @IsOptional()
+ filters?: string
}
diff --git a/backend/apps/community/src/analytics/interfaces/index.ts b/backend/apps/community/src/analytics/interfaces/index.ts
index 2dace48be..a57eb8f2a 100644
--- a/backend/apps/community/src/analytics/interfaces/index.ts
+++ b/backend/apps/community/src/analytics/interfaces/index.ts
@@ -111,6 +111,22 @@ export interface IFunnelCHResponse {
c: number
}
+export interface IConversionTimeMetric {
+ average: number | null
+ median: number | null
+ p75: number | null
+}
+
+export interface IFunnelBreakdowns {
+ countries?: Record<string, number>
+ devices?: Record<string, number>
+ browsers?: Record<string, number>
+ sources?: Record<string, number>
+ campaigns?: Record<string, number>
+ pages?: Record<string, number>
+ profileTypes?: Record<string, number>
+}
+
export interface IFunnel {
value: string
events: number
@@ -120,11 +136,17 @@ export interface IFunnel {
dropoffPercStep: number
topCountries: Record<string, number>
topSources: Record<string, number>
+ breakdowns?: IFunnelBreakdowns
}
export interface IGetFunnel {
funnel: IFunnel[]
totalPageviews: number
+ timeToConvert?: {
+ fromSessionStart: IConversionTimeMetric
+ fromFirstPage: IConversionTimeMetric
+ fromFirstFunnelStep: IConversionTimeMetric
+ }
}
export interface BirdseyeCHResponse {
diff --git a/backend/apps/community/src/goal/dto/goal.dto.ts b/backend/apps/community/src/goal/dto/goal.dto.ts
index 0e0519c97..0410e113c 100644
--- a/backend/apps/community/src/goal/dto/goal.dto.ts
+++ b/backend/apps/community/src/goal/dto/goal.dto.ts
@@ -11,7 +11,16 @@ import {
ArrayMaxSize,
} from 'class-validator'
import { Type } from 'class-transformer'
-import { GoalType, GoalMatchType, MetadataFilter } from '../entity/goal.entity'
+import {
+ GoalType,
+ GoalMatchType,
+ MetadataFilter,
+ GoalCondition,
+ GoalConditions,
+ GoalConditionEventType,
+ GoalConditionOperator,
+ GoalConditionRelation,
+} from '../entity/goal.entity'
// Allowed match types for API (regex is disabled for now)
const ALLOWED_MATCH_TYPES = [GoalMatchType.EXACT, GoalMatchType.CONTAINS]
@@ -28,6 +37,59 @@ class MetadataFilterDto implements MetadataFilter {
value: string
}
+const ALLOWED_CONDITION_RELATIONS: GoalConditionRelation[] = ['AND', 'OR']
+const ALLOWED_CONDITION_EVENT_TYPES: GoalConditionEventType[] = [
+ 'any',
+ GoalType.PAGEVIEW,
+ GoalType.CUSTOM_EVENT,
+]
+const ALLOWED_CONDITION_OPERATORS: GoalConditionOperator[] = [
+ 'equals',
+ 'not_equals',
+ 'contains',
+ 'not_contains',
+ 'exists',
+ 'not_exists',
+]
+
+class GoalConditionDto implements GoalCondition {
+ @IsString()
+ @IsOptional()
+ id?: string
+
+ @IsIn(ALLOWED_CONDITION_EVENT_TYPES)
+ eventType: GoalConditionEventType
+
+ @IsString()
+ @IsNotEmpty()
+ @MaxLength(100)
+ field: string
+
+ @IsIn(ALLOWED_CONDITION_OPERATORS)
+ operator: GoalConditionOperator
+
+ @IsString()
+ @MaxLength(500)
+ @IsOptional()
+ value?: string
+
+ @IsString()
+ @MaxLength(100)
+ @IsOptional()
+ metadataKey?: string
+}
+
+class GoalConditionsDto implements GoalConditions {
+ @IsIn(ALLOWED_CONDITION_RELATIONS)
+ relation: GoalConditionRelation
+
+ @IsArray()
+ @ArrayMaxSize(20)
+ @ValidateNested({ each: true })
+ @Type(() => GoalConditionDto)
+ conditions: GoalConditionDto[]
+}
+
export class CreateGoalDto {
@IsString()
@IsNotEmpty()
@@ -57,6 +119,11 @@ export class CreateGoalDto {
@Type(() => MetadataFilterDto)
@IsOptional()
metadataFilters?: MetadataFilterDto[]
+
+ @ValidateNested()
+ @Type(() => GoalConditionsDto)
+ @IsOptional()
+ conditions?: GoalConditionsDto | null
}
export class UpdateGoalDto {
@@ -87,6 +154,11 @@ export class UpdateGoalDto {
@IsOptional()
metadataFilters?: MetadataFilterDto[]
+ @ValidateNested()
+ @Type(() => GoalConditionsDto)
+ @IsOptional()
+ conditions?: GoalConditionsDto | null
+
@IsBoolean()
@IsOptional()
active?: boolean
diff --git a/backend/apps/community/src/goal/entity/goal.entity.ts b/backend/apps/community/src/goal/entity/goal.entity.ts
index 90de27315..96df5c446 100644
--- a/backend/apps/community/src/goal/entity/goal.entity.ts
+++ b/backend/apps/community/src/goal/entity/goal.entity.ts
@@ -13,6 +13,30 @@ export interface MetadataFilter {
value: string
}
+export type GoalConditionRelation = 'AND' | 'OR'
+export type GoalConditionEventType = 'any' | GoalType
+export type GoalConditionOperator =
+ | 'equals'
+ | 'not_equals'
+ | 'contains'
+ | 'not_contains'
+ | 'exists'
+ | 'not_exists'
+
+export interface GoalCondition {
+ id?: string
+ eventType: GoalConditionEventType
+ field: string
+ operator: GoalConditionOperator
+ value?: string
+ metadataKey?: string
+}
+
+export interface GoalConditions {
+ relation: GoalConditionRelation
+ conditions: GoalCondition[]
+}
+
export interface Goal {
id: string
name: string
@@ -20,6 +44,7 @@ export interface Goal {
matchType: GoalMatchType
value: string | null
metadataFilters: MetadataFilter[] | null
+ conditions: GoalConditions | null
active: boolean
projectId: string
created: string
@@ -31,8 +56,9 @@ export interface ClickhouseGoal {
type: string
matchType: string
value: string | null
- metadataFilters: string | null // JSON string in ClickHouse
- active: number // Int8 in ClickHouse
+ metadataFilters: string | null
+ conditions: string | null
+ active: number
projectId: string
created: string
}
diff --git a/backend/apps/community/src/goal/goal.controller.ts b/backend/apps/community/src/goal/goal.controller.ts
index 4a022b2e8..336e55e37 100644
--- a/backend/apps/community/src/goal/goal.controller.ts
+++ b/backend/apps/community/src/goal/goal.controller.ts
@@ -24,11 +24,17 @@ import { ProjectService } from '../project/project.service'
import { AppLoggerService } from '../logger/logger.service'
import {
AnalyticsService,
+ DataType,
getLowestPossibleTimeBucket,
} from '../analytics/analytics.service'
import { Auth } from '../auth/decorators'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
-import { Goal, GoalType, GoalMatchType } from './entity/goal.entity'
+import {
+ Goal,
+ GoalType,
+ GoalMatchType,
+ GoalCondition,
+} from './entity/goal.entity'
import { CreateGoalDto, UpdateGoalDto } from './dto/goal.dto'
import { GoalService } from './goal.service'
import { clickhouse } from '../common/integrations/clickhouse'
@@ -63,6 +69,41 @@ const clampPagination = (take?: number, skip?: number) => {
return { take: safeTake, skip: safeSkip }
}
+const GOAL_CONDITION_COLUMNS: Record<string, string> = {
+ page: 'pg',
+ pg: 'pg',
+ event: 'event_name',
+ event_name: 'event_name',
+ host: 'host',
+ ref: 'ref',
+ so: 'so',
+ me: 'me',
+ ca: 'ca',
+ te: 'te',
+ co: 'co',
+ cc: 'cc',
+ dv: 'dv',
+ br: 'br',
+ os: 'os',
+}
+
+type GoalBreakdownKey =
+ | 'countries'
+ | 'devices'
+ | 'browsers'
+ | 'sources'
+ | 'campaigns'
+ | 'pages'
+ | 'profileTypes'
+
+type GoalBreakdowns = Record<GoalBreakdownKey, Record<string, number>>
+
+type TimeToConvertMetric = {
+ average: number | null
+ median: number | null
+ p75: number | null
+}
+
@Controller('goal')
export class GoalController {
constructor(
@@ -170,6 +211,7 @@ export class GoalController {
matchType: goalDto.matchType,
value: goalDto.value || null,
metadataFilters: goalDto.metadataFilters || null,
+ conditions: goalDto.conditions || null,
projectId: goalDto.pid,
})
@@ -213,6 +255,7 @@ export class GoalController {
'matchType',
'value',
'metadataFilters',
+ 'conditions',
'active',
]),
}
@@ -315,6 +358,401 @@ export class GoalController {
}
}
+ private buildConditionExpression(
+ condition: GoalCondition,
+ index: number,
+ ): { condition: string; params: Record<string, string> } {
+ const params: Record<string, string> = {}
+ const eventType = condition.eventType || 'any'
+ const parts: string[] = []
+
+ if (
+ eventType === GoalType.PAGEVIEW ||
+ eventType === GoalType.CUSTOM_EVENT
+ ) {
+ params[`conditionType${index}`] = eventType
+ parts.push(`type = {conditionType${index}:String}`)
+ } else if (condition.field === 'pg' || condition.field === 'page') {
+ parts.push(`type = 'pageview'`)
+ } else if (
+ condition.field === 'event' ||
+ condition.field === 'event_name'
+ ) {
+ parts.push(`type = 'custom_event'`)
+ } else {
+ parts.push(`type IN ('pageview', 'custom_event')`)
+ }
+
+ if (condition.field === 'metadata') {
+ const keyParam = `conditionMetaKey${index}`
+ params[keyParam] = condition.metadataKey || ''
+
+ if (!params[keyParam]) {
+ return { condition: '1=0', params: {} }
+ }
+
+ if (condition.operator === 'exists') {
+ parts.push(`indexOf(meta.key, {${keyParam}:String}) > 0`)
+ } else if (condition.operator === 'not_exists') {
+ parts.push(`indexOf(meta.key, {${keyParam}:String}) = 0`)
+ } else {
+ const valueParam = `conditionValue${index}`
+ params[valueParam] = condition.value || ''
+ const valueExpression = `meta.value[indexOf(meta.key, {${keyParam}:String})]`
+ parts.push(`indexOf(meta.key, {${keyParam}:String}) > 0`)
+
+ if (condition.operator === 'contains') {
+ parts.push(
+ `${valueExpression} ILIKE concat('%', {${valueParam}:String}, '%')`,
+ )
+ } else if (condition.operator === 'not_contains') {
+ parts.push(
+ `NOT (${valueExpression} ILIKE concat('%', {${valueParam}:String}, '%'))`,
+ )
+ } else {
+ parts.push(
+ `${valueExpression} ${condition.operator === 'not_equals' ? '!=' : '='} {${valueParam}:String}`,
+ )
+ }
+ }
+
+ return { condition: `(${parts.join(' AND ')})`, params }
+ }
+
+ const column = GOAL_CONDITION_COLUMNS[condition.field]
+ if (!column) {
+ return { condition: '1=0', params: {} }
+ }
+
+ if (condition.operator === 'exists') {
+ parts.push(`${column} IS NOT NULL AND ${column} != ''`)
+ } else if (condition.operator === 'not_exists') {
+ parts.push(`(${column} IS NULL OR ${column} = '')`)
+ } else {
+ const valueParam = `conditionValue${index}`
+ params[valueParam] = condition.value || ''
+
+ if (!params[valueParam]) {
+ return { condition: '1=0', params: {} }
+ }
+
+ if (condition.operator === 'contains') {
+ parts.push(`${column} ILIKE concat('%', {${valueParam}:String}, '%')`)
+ } else if (condition.operator === 'not_contains') {
+ parts.push(
+ `NOT (${column} ILIKE concat('%', {${valueParam}:String}, '%'))`,
+ )
+ } else {
+ parts.push(
+ `${column} ${condition.operator === 'not_equals' ? '!=' : '='} {${valueParam}:String}`,
+ )
+ }
+ }
+
+ return { condition: `(${parts.join(' AND ')})`, params }
+ }
+
+ private buildGoalEventCondition(goal: Goal): {
+ condition: string
+ params: Record<string, string>
+ } {
+ if (goal.conditions?.conditions?.length) {
+ const relation = goal.conditions.relation === 'OR' ? ' OR ' : ' AND '
+ const builtConditions = goal.conditions.conditions.map(
+ (condition, index) => this.buildConditionExpression(condition, index),
+ )
+
+ return {
+ condition: `(${builtConditions
+ .map((condition) => condition.condition)
+ .join(relation)})`,
+ params: Object.assign(
+ {},
+ ...builtConditions.map((condition) => condition.params),
+ ),
+ }
+ }
+
+ const goalType =
+ goal.type === GoalType.CUSTOM_EVENT ? 'custom_event' : 'pageview'
+ const { condition: matchCondition, params: matchParams } =
+ this.buildGoalMatchCondition(goal)
+ const { condition: metaCondition, params: metaParams } =
+ this.buildMetadataCondition(goal)
+
+ return {
+ condition: `(type = '${goalType}' AND ${matchCondition} ${metaCondition})`,
+ params: { ...matchParams, ...metaParams },
+ }
+ }
+
+ private buildGoalConversionsSubquery(
+ goal: Goal,
+ filtersQuery: string,
+ ): {
+ query: string
+ params: Record<string, string | number>
+ } {
+ const conditions = goal.conditions?.conditions || []
+
+ if (conditions.length > 1 && goal.conditions?.relation === 'AND') {
+ const builtConditions = conditions.map((condition, index) =>
+ this.buildConditionExpression(condition, index),
+ )
+
+ return {
+ query: `
+ SELECT psid, max(matchedAt) AS conversionAt, 1 AS conversions
+ FROM (
+ SELECT psid, conditionIndex, min(created) AS matchedAt
+ FROM (
+ ${builtConditions
+ .map(
+ (condition, index) => `
+ SELECT psid, created, ${index} AS conditionIndex
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND (${condition.condition})
+ ${filtersQuery}
+ AND psid != 0
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ `,
+ )
+ .join(' UNION ALL ')}
+ )
+ GROUP BY psid, conditionIndex
+ )
+ GROUP BY psid
+ HAVING countDistinct(conditionIndex) = {conditionsCount:UInt32}
+ `,
+ params: {
+ ...Object.assign(
+ {},
+ ...builtConditions.map((condition) => condition.params),
+ ),
+ conditionsCount: conditions.length,
+ },
+ }
+ }
+
+ const { condition: goalCondition, params: goalParams } =
+ this.buildGoalEventCondition(goal)
+
+ return {
+ query: `
+ SELECT psid, min(created) AS conversionAt, count() AS conversions
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND (${goalCondition})
+ ${filtersQuery}
+ AND psid != 0
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY psid
+ `,
+ params: goalParams,
+ }
+ }
+
+ private async getGoalBreakdowns(
+ projectId: string,
+ groupFrom: string,
+ groupTo: string,
+ conversionsSubquery: string,
+ queryParams: Record<string, unknown>,
+ ): Promise<GoalBreakdowns> {
+ const emptyBreakdowns: GoalBreakdowns = {
+ countries: {},
+ devices: {},
+ browsers: {},
+ sources: {},
+ campaigns: {},
+ pages: {},
+ profileTypes: {},
+ }
+
+ const query = `
+ WITH conversions AS (
+ ${conversionsSubquery}
+ ),
+ session_info AS (
+ SELECT
+ c.psid AS psid,
+ argMin(e.cc, e.created) AS cc,
+ argMin(e.dv, e.created) AS dv,
+ argMin(e.br, e.created) AS br,
+ argMin(if(e.so IS NOT NULL AND e.so != '', e.so, if(domain(e.ref) != '', domain(e.ref), 'Direct / None')), e.created) AS source,
+ argMin(e.ca, e.created) AS campaign,
+ argMin(e.pg, e.created) AS page,
+ argMax(e.profileId, e.created) AS profileId
+ FROM conversions c
+ INNER JOIN events e ON c.psid = e.psid
+ WHERE e.pid = {pid:FixedString(12)}
+ AND e.type IN ('pageview', 'custom_event')
+ AND e.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ AND e.created <= c.conversionAt
+ GROUP BY c.psid
+ )
+ SELECT kind, val, cnt FROM (
+ SELECT 'countries' AS kind, cc AS val, count() AS cnt
+ FROM session_info
+ WHERE cc IS NOT NULL AND cc != ''
+ GROUP BY cc
+
+ UNION ALL
+
+ SELECT 'devices' AS kind, dv AS val, count() AS cnt
+ FROM session_info
+ WHERE dv IS NOT NULL AND dv != ''
+ GROUP BY dv
+
+ UNION ALL
+
+ SELECT 'browsers' AS kind, br AS val, count() AS cnt
+ FROM session_info
+ WHERE br IS NOT NULL AND br != ''
+ GROUP BY br
+
+ UNION ALL
+
+ SELECT 'sources' AS kind, source AS val, count() AS cnt
+ FROM session_info
+ GROUP BY val
+
+ UNION ALL
+
+ SELECT 'campaigns' AS kind, campaign AS val, count() AS cnt
+ FROM session_info
+ WHERE campaign IS NOT NULL AND campaign != ''
+ GROUP BY campaign
+
+ UNION ALL
+
+ SELECT 'pages' AS kind, page AS val, count() AS cnt
+ FROM session_info
+ WHERE page IS NOT NULL AND page != ''
+ GROUP BY page
+
+ UNION ALL
+
+ SELECT 'profileTypes' AS kind, if(startsWith(profileId, '${AnalyticsService.PROFILE_PREFIX_USER}'), 'identified', 'anonymous') AS val, count() AS cnt
+ FROM session_info
+ WHERE profileId IS NOT NULL AND profileId != ''
+ GROUP BY val
+ )
+ ORDER BY kind, cnt DESC, val ASC
+ LIMIT 5 BY kind
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { ...queryParams, pid: projectId, groupFrom, groupTo },
+ })
+ .then((resultSet) =>
+ resultSet.json<{
+ kind: GoalBreakdownKey
+ val: string
+ cnt: number
+ }>(),
+ )
+
+ for (const row of data) {
+ if (!emptyBreakdowns[row.kind] || !row.val) {
+ continue
+ }
+
+ emptyBreakdowns[row.kind][row.val] = row.cnt
+ }
+
+ return emptyBreakdowns
+ }
+
+ private async getGoalTimeToConvert(
+ projectId: string,
+ groupFrom: string,
+ groupTo: string,
+ conversionsSubquery: string,
+ queryParams: Record<string, unknown>,
+ ): Promise<{
+ fromSessionStart: TimeToConvertMetric
+ fromFirstPage: TimeToConvertMetric
+ }> {
+ const emptyMetric: TimeToConvertMetric = {
+ average: null,
+ median: null,
+ p75: null,
+ }
+
+ const query = `
+ WITH conversions AS (
+ ${conversionsSubquery}
+ ),
+ session_starts AS (
+ SELECT psid, min(firstSeen) AS sessionStart
+ FROM sessions FINAL
+ WHERE pid = {pid:FixedString(12)}
+ GROUP BY psid
+ ),
+ first_pages AS (
+ SELECT psid, min(created) AS firstPageAt
+ FROM events
+ WHERE pid = {pid:FixedString(12)}
+ AND type = 'pageview'
+ AND psid != 0
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY psid
+ )
+ SELECT
+ round(avgOrNull(if(sessionStart > toDateTime(0) AND sessionStart <= conversionAt, dateDiff('second', sessionStart, conversionAt), NULL)), 2) AS averageSession,
+ quantileExactOrNull(0.5)(if(sessionStart > toDateTime(0) AND sessionStart <= conversionAt, dateDiff('second', sessionStart, conversionAt), NULL)) AS medianSession,
+ quantileExactOrNull(0.75)(if(sessionStart > toDateTime(0) AND sessionStart <= conversionAt, dateDiff('second', sessionStart, conversionAt), NULL)) AS p75Session,
+ round(avgOrNull(if(firstPageAt > toDateTime(0) AND firstPageAt <= conversionAt, dateDiff('second', firstPageAt, conversionAt), NULL)), 2) AS averageFirstPage,
+ quantileExactOrNull(0.5)(if(firstPageAt > toDateTime(0) AND firstPageAt <= conversionAt, dateDiff('second', firstPageAt, conversionAt), NULL)) AS medianFirstPage,
+ quantileExactOrNull(0.75)(if(firstPageAt > toDateTime(0) AND firstPageAt <= conversionAt, dateDiff('second', firstPageAt, conversionAt), NULL)) AS p75FirstPage
+ FROM conversions c
+ LEFT JOIN session_starts ss ON c.psid = ss.psid
+ LEFT JOIN first_pages fp ON c.psid = fp.psid
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { ...queryParams, pid: projectId, groupFrom, groupTo },
+ })
+ .then((resultSet) =>
+ resultSet.json<{
+ averageSession: number | null
+ medianSession: number | null
+ p75Session: number | null
+ averageFirstPage: number | null
+ medianFirstPage: number | null
+ p75FirstPage: number | null
+ }>(),
+ )
+
+ const row = data[0]
+
+ if (!row) {
+ return {
+ fromSessionStart: emptyMetric,
+ fromFirstPage: emptyMetric,
+ }
+ }
+
+ return {
+ fromSessionStart: {
+ average: row.averageSession,
+ median: row.medianSession,
+ p75: row.p75Session,
+ },
+ fromFirstPage: {
+ average: row.averageFirstPage,
+ median: row.medianFirstPage,
+ p75: row.p75FirstPage,
+ },
+ }
+ }
+
@Get('/:id/stats')
@Auth()
async getGoalStats(
@@ -324,6 +762,7 @@ export class GoalController {
@Query('from') from?: string,
@Query('to') to?: string,
@Query('timezone') timezone?: string,
+ @Query('filters') filters?: string,
) {
this.logger.log({ userId, id, period, from, to }, 'GET /goal/:id/stats')
@@ -347,33 +786,29 @@ export class GoalController {
safeTimezone,
)
- const goalType =
- goal.type === GoalType.CUSTOM_EVENT ? 'custom_event' : 'pageview'
- const { condition: matchCondition, params: matchParams } =
- this.buildGoalMatchCondition(goal)
- const { condition: metaCondition, params: metaParams } =
- this.buildMetadataCondition(goal)
+ const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(
+ filters || '[]',
+ DataType.ANALYTICS,
+ )
+ const { query: conversionsSubquery, params: goalParams } =
+ this.buildGoalConversionsSubquery(goal, filtersQuery)
- // Get conversions for current period
const conversionsQuery = `
+ WITH conversions AS (
+ ${conversionsSubquery}
+ )
SELECT
- count(*) as conversions,
- uniqExact(psid) as uniqueSessions
- FROM events
- WHERE
- pid = {pid:FixedString(12)}
- AND type = '${goalType}'
- AND ${matchCondition}
- ${metaCondition}
- AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ sum(conversions) as conversions,
+ count() as uniqueSessions
+ FROM conversions
`
const queryParams = {
pid: goal.projectId,
groupFrom: groupFromUTC,
groupTo: groupToUTC,
- ...matchParams,
- ...metaParams,
+ ...goalParams,
+ ...filtersParams,
}
const { data: conversionsData } = await clickhouse
@@ -385,13 +820,13 @@ export class GoalController {
const conversions = conversionsData[0]?.conversions || 0
const uniqueSessions = conversionsData[0]?.uniqueSessions || 0
- // Get total unique sessions for conversion rate
const totalSessionsQuery = `
SELECT uniqExact(psid) as totalSessions
FROM events
WHERE
pid = {pid:FixedString(12)}
- AND type = 'pageview'
+ AND type IN ('pageview', 'custom_event')
+ ${filtersQuery}
AND created BETWEEN {groupFrom:String} AND {groupTo:String}
`
@@ -402,6 +837,7 @@ export class GoalController {
pid: goal.projectId,
groupFrom: groupFromUTC,
groupTo: groupToUTC,
+ ...filtersParams,
},
})
.then((resultSet) => resultSet.json<{ totalSessions: number }>())
@@ -409,7 +845,6 @@ export class GoalController {
const totalSessions = totalData[0]?.totalSessions || 1
const conversionRate = _round((uniqueSessions / totalSessions) * 100, 2)
- // Get previous period conversions for trend
const periodDays = dayjs(groupToUTC).diff(dayjs(groupFromUTC), 'day') || 1
const previousFrom = dayjs(groupFromUTC)
.subtract(periodDays, 'day')
@@ -420,8 +855,8 @@ export class GoalController {
pid: goal.projectId,
groupFrom: previousFrom,
groupTo: previousTo,
- ...matchParams,
- ...metaParams,
+ ...goalParams,
+ ...filtersParams,
}
const { data: previousData } = await clickhouse
@@ -441,12 +876,31 @@ export class GoalController {
? 100
: 0
+ const [breakdowns, timeToConvert] = await Promise.all([
+ this.getGoalBreakdowns(
+ goal.projectId,
+ groupFromUTC,
+ groupToUTC,
+ conversionsSubquery,
+ { ...goalParams, ...filtersParams },
+ ),
+ this.getGoalTimeToConvert(
+ goal.projectId,
+ groupFromUTC,
+ groupToUTC,
+ conversionsSubquery,
+ { ...goalParams, ...filtersParams },
+ ),
+ ])
+
return {
conversions,
uniqueSessions,
conversionRate,
previousConversions,
trend,
+ breakdowns,
+ timeToConvert,
}
}
@@ -534,6 +988,7 @@ export class GoalController {
@Query('to') to?: string,
@Query('timeBucket') timeBucket?: string,
@Query('timezone') timezone?: string,
+ @Query('filters') filters?: string,
) {
this.logger.log(
{ userId, id, period, from, to, timeBucket },
@@ -561,7 +1016,6 @@ export class GoalController {
safeTimezone,
)
- // Generate complete X axis with all time buckets
const { xShifted } = this.analyticsService.generateXAxis(
resolvedTimeBucket as any,
groupFromUTC,
@@ -569,8 +1023,6 @@ export class GoalController {
safeTimezone,
)
- const goalType =
- goal.type === GoalType.CUSTOM_EVENT ? 'custom_event' : 'pageview'
const timeBucketFunc = Object.prototype.hasOwnProperty.call(
timeBucketConversion,
resolvedTimeBucket,
@@ -579,26 +1031,26 @@ export class GoalController {
: 'toStartOfDay'
const [selector, groupBy] = this.getGroupSubquery(resolvedTimeBucket)
- const { condition: matchCondition, params: matchParams } =
- this.buildGoalMatchCondition(goal)
- const { condition: metaCondition, params: metaParams } =
- this.buildMetadataCondition(goal)
+ const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(
+ filters || '[]',
+ DataType.ANALYTICS,
+ )
+ const { query: conversionsSubquery, params: goalParams } =
+ this.buildGoalConversionsSubquery(goal, filtersQuery)
const chartQuery = `
SELECT
${selector},
- count(*) as conversions,
- uniqExact(psid) as uniqueSessions
+ sum(conversions) as conversions,
+ count() as uniqueSessions
FROM (
- SELECT *,
- ${timeBucketFunc}(toTimeZone(created, {timezone:String})) as tz_created
- FROM events
- WHERE
- pid = {pid:FixedString(12)}
- AND type = '${goalType}'
- AND ${matchCondition}
- ${metaCondition}
- AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ SELECT
+ psid,
+ conversions,
+ ${timeBucketFunc}(toTimeZone(conversionAt, {timezone:String})) as tz_created
+ FROM (
+ ${conversionsSubquery}
+ )
) as subquery
GROUP BY ${groupBy}
ORDER BY ${groupBy}
@@ -609,8 +1061,8 @@ export class GoalController {
groupFrom: groupFromUTC,
groupTo: groupToUTC,
timezone: safeTimezone,
- ...matchParams,
- ...metaParams,
+ ...goalParams,
+ ...filtersParams,
}
const { data } = await clickhouse
diff --git a/backend/apps/community/src/goal/goal.service.ts b/backend/apps/community/src/goal/goal.service.ts
index 7c36aa063..a409dd69b 100644
--- a/backend/apps/community/src/goal/goal.service.ts
+++ b/backend/apps/community/src/goal/goal.service.ts
@@ -15,6 +15,7 @@ import {
ClickhouseGoal,
GoalMatchType,
MetadataFilter,
+ GoalConditions,
} from './entity/goal.entity'
import { Pagination } from '../common/pagination/pagination'
import { PaginationOptionsInterface } from '../common/pagination/pagination.results.interface'
@@ -27,6 +28,7 @@ const ALLOWED_GOAL_KEYS = [
'matchType',
'value',
'metadataFilters',
+ 'conditions',
'active',
]
@@ -38,6 +40,7 @@ export class GoalService {
}
let metadataFilters: MetadataFilter[] | null = null
+ let conditions: GoalConditions | null = null
if (goal.metadataFilters) {
try {
metadataFilters = JSON.parse(goal.metadataFilters)
@@ -45,6 +48,13 @@ export class GoalService {
metadataFilters = null
}
}
+ if (goal.conditions) {
+ try {
+ conditions = JSON.parse(goal.conditions)
+ } catch {
+ conditions = null
+ }
+ }
return {
id: goal.id,
@@ -53,6 +63,7 @@ export class GoalService {
matchType: (goal.matchType as GoalMatchType) || GoalMatchType.EXACT,
value: goal.value,
metadataFilters,
+ conditions,
active: Boolean(goal.active),
projectId: goal.projectId,
created: goal.created,
@@ -68,6 +79,12 @@ export class GoalService {
: null
}
+ if (goal.conditions !== undefined) {
+ result.conditions = goal.conditions
+ ? JSON.stringify(goal.conditions)
+ : null
+ }
+
if (goal.active !== undefined) {
result.active = goal.active ? 1 : 0
}
@@ -214,6 +231,7 @@ export class GoalService {
matchType: formattedGoal.matchType || GoalMatchType.EXACT,
value: formattedGoal.value || null,
metadataFilters: formattedGoal.metadataFilters || null,
+ conditions: formattedGoal.conditions || null,
active: formattedGoal.active ?? 1,
projectId: goalData.projectId,
created,
@@ -257,8 +275,10 @@ export class GoalService {
return `${col}={${col}:Int8}`
}
- // Handle nullable string columns
- if (value === null && (col === 'value' || col === 'metadataFilters')) {
+ if (
+ value === null &&
+ (col === 'value' || col === 'metadataFilters' || col === 'conditions')
+ ) {
return `${col}=NULL`
}
diff --git a/backend/migrations/clickhouse/initialise_selfhosted.js b/backend/migrations/clickhouse/initialise_selfhosted.js
index 2cbc4a48b..502c62830 100644
--- a/backend/migrations/clickhouse/initialise_selfhosted.js
+++ b/backend/migrations/clickhouse/initialise_selfhosted.js
@@ -70,6 +70,7 @@ const CLICKHOUSE_INIT_QUERIES = [
matchType Enum8('exact' = 1, 'contains' = 2, 'regex' = 3) DEFAULT 'exact',
value Nullable(String),
metadataFilters Nullable(String),
+ conditions Nullable(String),
active Int8 DEFAULT 1,
projectId FixedString(12),
created DateTime
diff --git a/backend/migrations/clickhouse/selfhosted_2025_12_07_goals.js b/backend/migrations/clickhouse/selfhosted_2025_12_07_goals.js
index 765960c2e..074dde3c8 100644
--- a/backend/migrations/clickhouse/selfhosted_2025_12_07_goals.js
+++ b/backend/migrations/clickhouse/selfhosted_2025_12_07_goals.js
@@ -10,6 +10,7 @@ const queries = [
matchType Enum8('exact' = 1, 'contains' = 2, 'regex' = 3) DEFAULT 'exact',
value Nullable(String),
metadataFilters Nullable(String),
+ conditions Nullable(String),
active Int8 DEFAULT 1,
projectId FixedString(12),
created DateTime
diff --git a/backend/migrations/clickhouse/selfhosted_2026_05_20_goal_conditions.js b/backend/migrations/clickhouse/selfhosted_2026_05_20_goal_conditions.js
new file mode 100644
index 000000000..aaed4d91c
--- /dev/null
+++ b/backend/migrations/clickhouse/selfhosted_2026_05_20_goal_conditions.js
@@ -0,0 +1,7 @@
+const { queriesRunner, dbName } = require('./setup')
+
+const queries = [
+ `ALTER TABLE ${dbName}.goal ADD COLUMN IF NOT EXISTS conditions Nullable(String) AFTER metadataFilters;`,
+]
+
+queriesRunner(queries)
diff --git a/backend/migrations/mysql/2026_05_20_goal_conditions.sql b/backend/migrations/mysql/2026_05_20_goal_conditions.sql
new file mode 100644
index 000000000..18cbd77a8
--- /dev/null
+++ b/backend/migrations/mysql/2026_05_20_goal_conditions.sql
@@ -0,0 +1,2 @@
+ALTER TABLE `goal`
+ ADD COLUMN `conditions` json DEFAULT NULL AFTER `metadataFilters`;
diff --git a/docs/content/docs/analytics-dashboard/funnels.mdx b/docs/content/docs/analytics-dashboard/funnels.mdx
index 1ec49162e..c7581dad2 100644
--- a/docs/content/docs/analytics-dashboard/funnels.mdx
+++ b/docs/content/docs/analytics-dashboard/funnels.mdx
@@ -71,6 +71,8 @@ Hover over a step to see more detail, including:
You can click on any bar in the funnel chart to open a sessions drawer showing the individual sessions that reached that step. These are not just sessions that visited the page — they are sessions that completed every prior funnel step in order, matching the same sequential logic the funnel itself uses.
+For every step except the final one, the sessions drawer can be switched to show only drop-offs: sessions that reached the selected step but did not continue to the next step.
+
For example, in a three-step funnel (`/pricing` → `/signup` → `/dashboard`), clicking the `/dashboard` bar will only show sessions where the visitor first viewed `/pricing`, then `/signup`, and then `/dashboard` — in that order.
## Managing Funnels
diff --git a/docs/content/docs/analytics-dashboard/goals.mdx b/docs/content/docs/analytics-dashboard/goals.mdx
index e8e07e279..e455cb920 100644
--- a/docs/content/docs/analytics-dashboard/goals.mdx
+++ b/docs/content/docs/analytics-dashboard/goals.mdx
@@ -12,10 +12,11 @@ Goals allow you to track specific actions that visitors perform on your website.
A Goal in Swetrix represents a desired outcome, such as a visitor signing up for a newsletter, downloading a file, or reaching a "Thank You" page after a purchase. By defining goals, you can see conversion rates and trends for these critical actions directly in your dashboard.
-Swetrix supports two types of goals:
+Swetrix supports simple goals and multi-condition goals:
-1. **Pageview**: Triggered when a visitor visits a specific page URL.
-2. **Custom Event**: Triggered when a specific custom event is sent from your website.
+1. **Simple Pageview**: Triggered when a visitor visits a specific page URL.
+2. **Simple Custom Event**: Triggered when a specific custom event is sent from your website.
+3. **Multi-condition**: Triggered when a session matches several pageview, custom event, campaign, referrer, device, browser, country, or metadata conditions.
## Creating a Goal
@@ -37,6 +38,12 @@ To create a new goal:
| **Value** | For **Pageview**: The path of the page (e.g., `/pricing` or `/thank-you`).<br/>For **Custom Event**: The name of the event (e.g., `signup_completed`). |
| **Metadata Filters** | (Optional) Add specific conditions based on event metadata. For example, track only signups where `plan` equals `pro`. You can add multiple key-value pairs. |
+### Multi-condition Goals
+
+Use a multi-condition goal when one URL or event name is not enough to define the conversion. Conditions can be matched with **AND** or **OR** logic. For example, you can count sessions where a visitor viewed `/pricing`, arrived from a specific campaign, and then fired a `signup_completed` event.
+
+The condition editor uses the same selectors as dashboard filters, so common values such as pages, browsers, devices, countries, sources, campaigns, and UTM fields can be selected from existing analytics values or typed manually.
+
## Managing Goals
Once created, your goals will appear in a list on the Goals tab.
@@ -58,6 +65,8 @@ Each goal in the list displays a quick summary of its performance for the select
Click on any goal in the list to expand it and view a detailed performance chart.
+The expanded view also shows time-to-convert metrics where enough data exists, including median conversion time from the session start and from the first page.
+
The chart visualises two metrics over time:
1. **Conversions** (Green): The volume of goal completions.
diff --git a/docs/content/docs/api/stats.mdx b/docs/content/docs/api/stats.mdx
index 92a7e70b3..28a42bd9d 100644
--- a/docs/content/docs/api/stats.mdx
+++ b/docs/content/docs/api/stats.mdx
@@ -993,10 +993,10 @@ The timezone to use for the time range. The default is `Etc/GMT`. You can use an
### GET /v1/log/funnel
-Returns a funnel analysis for a specific set of pages.
+Returns a funnel analysis for a specific set of pages or a saved funnel.
```bash
-curl 'https://api.swetrix.com/v1/log/funnel?pid=YOUR_PROJECT_ID&pages=["/","/pricing","/signup"]&period=30d'\
+curl 'https://api.swetrix.com/v1/log/funnel?pid=YOUR_PROJECT_ID&pages=["/","/pricing","/signup"]&period=7d'\
-H "X-Api-Key: ${SWETRIX_API_KEY}"
```
@@ -1004,25 +1004,156 @@ curl 'https://api.swetrix.com/v1/log/funnel?pid=YOUR_PROJECT_ID&pages=["/","/pri
{
"funnel": [
{
- "page": "/",
- "count": 100,
+ "value": "/",
+ "events": 100,
+ "eventsPerc": 100,
+ "eventsPercStep": 100,
"dropoff": 0,
- "dropoffPercentage": 0
+ "dropoffPercStep": 0,
+ "topCountries": {
+ "US": 42,
+ "GB": 18
+ },
+ "topSources": {
+ "google": 31,
+ "Direct / None": 20
+ },
+ "breakdowns": {
+ "countries": {
+ "US": 42,
+ "GB": 18
+ },
+ "devices": {
+ "desktop": 67,
+ "mobile": 33
+ },
+ "browsers": {
+ "Chrome": 61,
+ "Safari": 22
+ },
+ "sources": {
+ "google": 31,
+ "Direct / None": 20
+ },
+ "campaigns": {
+ "spring_launch": 12
+ },
+ "pages": {
+ "/": 100
+ },
+ "profileTypes": {
+ "anonymous": 76,
+ "identified": 24
+ }
+ }
},
{
- "page": "/pricing",
- "count": 50,
+ "value": "/pricing",
+ "events": 50,
+ "eventsPerc": 50,
+ "eventsPercStep": 50,
"dropoff": 50,
- "dropoffPercentage": 50
+ "dropoffPercStep": 50,
+ "topCountries": {
+ "US": 22,
+ "GB": 8
+ },
+ "topSources": {
+ "google": 16,
+ "Direct / None": 10
+ },
+ "breakdowns": {
+ "countries": {
+ "US": 22,
+ "GB": 8
+ },
+ "devices": {
+ "desktop": 32,
+ "mobile": 18
+ },
+ "browsers": {
+ "Chrome": 30,
+ "Safari": 11
+ },
+ "sources": {
+ "google": 16,
+ "Direct / None": 10
+ },
+ "campaigns": {
+ "spring_launch": 8
+ },
+ "pages": {
+ "/pricing": 50
+ },
+ "profileTypes": {
+ "anonymous": 33,
+ "identified": 17
+ }
+ }
},
{
- "page": "/signup",
- "count": 10,
+ "value": "/signup",
+ "events": 10,
+ "eventsPerc": 10,
+ "eventsPercStep": 20,
"dropoff": 40,
- "dropoffPercentage": 80
+ "dropoffPercStep": 80,
+ "topCountries": {
+ "US": 5,
+ "GB": 2
+ },
+ "topSources": {
+ "google": 4,
+ "Direct / None": 2
+ },
+ "breakdowns": {
+ "countries": {
+ "US": 5,
+ "GB": 2
+ },
+ "devices": {
+ "desktop": 7,
+ "mobile": 3
+ },
+ "browsers": {
+ "Chrome": 6,
+ "Safari": 3
+ },
+ "sources": {
+ "google": 4,
+ "Direct / None": 2
+ },
+ "campaigns": {
+ "spring_launch": 3
+ },
+ "pages": {
+ "/signup": 10
+ },
+ "profileTypes": {
+ "anonymous": 6,
+ "identified": 4
+ }
+ }
}
],
- "totalPageviews": 160
+ "totalPageviews": 160,
+ "timeToConvert": {
+ "fromSessionStart": {
+ "average": 120.4,
+ "median": 90,
+ "p75": 180
+ },
+ "fromFirstPage": {
+ "average": 102.1,
+ "median": 80,
+ "p75": 160
+ },
+ "fromFirstFunnelStep": {
+ "average": 76.8,
+ "median": 60,
+ "p75": 120
+ }
+ }
}
```
@@ -1038,14 +1169,18 @@ A stringified JSON array of page paths to define the funnel steps.
The ID of a saved funnel to retrieve.
+**filters** (optional)
+
+A stringified JSON array of [filter objects](#filters). Filters select the session cohort for the funnel analysis.
+
<hr />
### GET /v1/log/funnel-sessions
-Returns paginated sessions that reached a specific step in a funnel. Sessions are filtered using the same `windowFunnel` logic as the funnel analysis — only sessions that completed every prior step in order are included.
+Returns paginated sessions that reached a specific step in a funnel. Sessions are filtered using the same `windowFunnel` logic as the funnel analysis - only sessions that completed every prior step in order are included.
```bash
-curl 'https://api.swetrix.com/v1/log/funnel-sessions?pid=YOUR_PROJECT_ID&funnelId=FUNNEL_ID&step=2&period=30d&take=30&skip=0'\
+curl 'https://api.swetrix.com/v1/log/funnel-sessions?pid=YOUR_PROJECT_ID&funnelId=FUNNEL_ID&step=2&period=7d&take=30&skip=0'\
-H "X-Api-Key: ${SWETRIX_API_KEY}"
```
@@ -1082,6 +1217,10 @@ The parameters are similar to the [`/log/funnel` endpoint](#get-v1logfunnel), wi
The funnel step number to get sessions for (1-indexed). For example, `step=2` returns sessions that completed at least the first two funnel steps in order.
+**dropoff** (optional)
+
+Set to `true` to return sessions that reached the requested step but did not continue to the next step.
+
**take** (optional, default: `30`, max: `150`)
The number of sessions to return per page.
@@ -1390,19 +1529,74 @@ Column: `br` or `os`.
### GET /goal/:id/stats
-Returns statistics for a specific goal (conversions, conversion rate, trend).
+Returns statistics for a specific goal, including conversions, conversion rate, trend, segment breakdowns, and time-to-convert metrics. Simple goals and multi-condition goals are both supported; for multi-condition goals using `AND`, the conversion timestamp is the point where the required conditions have all been satisfied in the session.
```bash
curl 'https://api.swetrix.com/goal/GOAL_ID/stats?period=7d'\
-H "X-Api-Key: ${SWETRIX_API_KEY}"
```
+```json title="Response"
+{
+ "conversions": 42,
+ "uniqueSessions": 38,
+ "conversionRate": 12.34,
+ "previousConversions": 31,
+ "trend": 35.48,
+ "breakdowns": {
+ "countries": {
+ "US": 18,
+ "GB": 7
+ },
+ "devices": {
+ "desktop": 25,
+ "mobile": 13
+ },
+ "browsers": {
+ "Chrome": 22,
+ "Safari": 9
+ },
+ "sources": {
+ "google": 14,
+ "Direct / None": 8
+ },
+ "campaigns": {
+ "spring_launch": 6
+ },
+ "pages": {
+ "/signup": 20,
+ "/pricing": 12
+ },
+ "profileTypes": {
+ "anonymous": 27,
+ "identified": 11
+ }
+ },
+ "timeToConvert": {
+ "fromSessionStart": {
+ "average": 156.7,
+ "median": 120,
+ "p75": 240
+ },
+ "fromFirstPage": {
+ "average": 132.4,
+ "median": 95,
+ "p75": 210
+ }
+ }
+}
+```
+
#### Parameters
**period**, **from**, **to**, **timezone**
Time range parameters.
+**filters** (optional)
+
+A stringified JSON array of [filter objects](#filters).
+
### GET /goal/:id/chart
Returns chart data for a specific goal.
@@ -1418,6 +1612,10 @@ curl 'https://api.swetrix.com/goal/GOAL_ID/chart?period=7d'\
Time range parameters.
+**filters** (optional)
+
+A stringified JSON array of [filter objects](#filters).
+
### GET /v1/feature-flag/:id/stats
Returns statistics for a specific feature flag (evaluations, true/false counts).
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
index 780469c0a..28f6003dc 100644
--- a/web/app/api/api.server.ts
+++ b/web/app/api/api.server.ts
@@ -1009,6 +1009,8 @@ export async function getFunnelSessionsServer(
take?: number
skip?: number
password?: string
+ filters?: AnalyticsFilter[]
+ dropoff?: boolean
},
): Promise<ServerFetchResult<FunnelSessionsResponse>> {
const step = Math.max(1, Math.floor(Number(params.step) || 1))
@@ -1021,10 +1023,12 @@ export async function getFunnelSessionsServer(
queryParams.append('step', String(step))
queryParams.append('take', String(take))
queryParams.append('skip', String(skip))
+ queryParams.append('filters', JSON.stringify(params.filters || []))
if (params.funnelId) queryParams.append('funnelId', params.funnelId)
if (params.from) queryParams.append('from', params.from)
if (params.to) queryParams.append('to', params.to)
if (params.timezone) queryParams.append('timezone', params.timezone)
+ if (params.dropoff) queryParams.append('dropoff', 'true')
const headers: Record<string, string> = {}
if (params.password) {
@@ -1381,6 +1385,32 @@ export async function getFeatureFlagProfilesServer(
// MARK: Goals API (Deferred Loading)
// ============================================================================
+export type GoalConditionRelation = 'AND' | 'OR'
+
+export type GoalConditionOperator =
+ | 'equals'
+ | 'not_equals'
+ | 'contains'
+ | 'not_contains'
+ | 'exists'
+ | 'not_exists'
+
+export type GoalConditionEventType = 'any' | 'pageview' | 'custom_event'
+
+export interface GoalCondition {
+ id?: string
+ eventType: GoalConditionEventType
+ field: string
+ operator: GoalConditionOperator
+ value?: string
+ metadataKey?: string
+}
+
+export interface GoalConditions {
+ relation: GoalConditionRelation
+ conditions: GoalCondition[]
+}
+
export interface Goal {
id: string
name: string
@@ -1388,6 +1418,7 @@ export interface Goal {
matchType: 'exact' | 'contains'
value: string | null
metadataFilters: { key: string; value: string }[] | null
+ conditions?: GoalConditions | null
active: boolean
pid: string
created: string
@@ -1398,6 +1429,28 @@ export interface GoalsResponse {
total: number
}
+export interface ConversionTimeBucket {
+ average: number | null
+ median: number | null
+ p75: number | null
+}
+
+export interface ConversionTimeToConvert {
+ fromSessionStart?: ConversionTimeBucket
+ fromFirstPage?: ConversionTimeBucket
+ fromFirstFunnelStep?: ConversionTimeBucket
+}
+
+export interface ConversionBreakdowns {
+ countries?: Record<string, number>
+ devices?: Record<string, number>
+ browsers?: Record<string, number>
+ sources?: Record<string, number>
+ campaigns?: Record<string, number>
+ pages?: Record<string, number>
+ profileTypes?: Record<string, number>
+}
+
export async function getProjectGoalsServer(
request: Request,
projectId: string,
@@ -1426,6 +1479,8 @@ export interface GoalStats {
conversionRate: number
previousConversions: number
trend: number
+ breakdowns?: ConversionBreakdowns
+ timeToConvert?: ConversionTimeToConvert
}
export async function getGoalStatsServer(
@@ -1435,11 +1490,13 @@ export async function getGoalStatsServer(
from = '',
to = '',
timezone?: string,
+ filters: AnalyticsFilter[] = [],
): Promise<ServerFetchResult<GoalStats>> {
const params = new URLSearchParams({ period })
if (from) params.append('from', from)
if (to) params.append('to', to)
if (timezone) params.append('timezone', timezone)
+ params.append('filters', JSON.stringify(filters))
return serverFetch<GoalStats>(
request,
@@ -1461,11 +1518,13 @@ export async function getGoalChartServer(
to = '',
timeBucket = 'day',
timezone?: string,
+ filters: AnalyticsFilter[] = [],
): Promise<ServerFetchResult<{ chart: GoalChartData }>> {
const params = new URLSearchParams({ period, timeBucket })
if (from) params.append('from', from)
if (to) params.append('to', to)
if (timezone) params.append('timezone', timezone)
+ params.append('filters', JSON.stringify(filters))
return serverFetch<{ chart: GoalChartData }>(
request,
@@ -1488,8 +1547,10 @@ export interface FunnelDataResponse {
dropoffPercStep: number
topCountries: Record<string, number>
topSources: Record<string, number>
+ breakdowns?: ConversionBreakdowns
}[]
totalPageviews: number
+ timeToConvert?: ConversionTimeToConvert
}
export async function getFunnelDataServer(
@@ -1501,11 +1562,13 @@ export async function getFunnelDataServer(
to: string,
timezone: string,
password?: string,
+ filters: AnalyticsFilter[] = [],
): Promise<ServerFetchResult<FunnelDataResponse>> {
const queryParams = new URLSearchParams()
queryParams.append('pid', pid)
queryParams.append('period', period)
queryParams.append('funnelId', funnelId)
+ queryParams.append('filters', JSON.stringify(filters))
if (from) queryParams.append('from', from)
if (to) queryParams.append('to', to)
if (timezone) queryParams.append('timezone', timezone)
diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.ts
index 184ddcc4e..507ba13d7 100644
--- a/web/app/lib/models/Project.ts
+++ b/web/app/lib/models/Project.ts
@@ -172,6 +172,15 @@ export interface AnalyticsFunnel {
dropoffPercStep: number
topCountries: Record<string, number>
topSources: Record<string, number>
+ breakdowns?: {
+ countries?: Record<string, number>
+ devices?: Record<string, number>
+ browsers?: Record<string, number>
+ sources?: Record<string, number>
+ campaigns?: Record<string, number>
+ pages?: Record<string, number>
+ profileTypes?: Record<string, number>
+ }
}
export type Provider =
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 039d0188f..7d8bbd6d9 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -1581,7 +1581,7 @@ const ViewProjectContent = () => {
<SEOView projectId={id} tnMapping={tnMapping} />
) : null}
{activeTab === PROJECT_TABS.funnels ? (
- <FunnelsView />
+ <FunnelsView tnMapping={tnMapping} />
) : null}
{activeTab === PROJECT_TABS.profiles ? (
<ProfilesView tnMapping={tnMapping} />
@@ -1597,6 +1597,7 @@ const ViewProjectContent = () => {
) : null}
{activeTab === PROJECT_TABS.goals ? (
<GoalsView
+ tnMapping={tnMapping}
period={period}
from={
dateRange ? getFormatDate(dateRange[0]) : ''
diff --git a/web/app/pages/Project/View/components/FilterRowsEditor.tsx b/web/app/pages/Project/View/components/FilterRowsEditor.tsx
index 1aca6d3c3..4c675e3b9 100644
--- a/web/app/pages/Project/View/components/FilterRowsEditor.tsx
+++ b/web/app/pages/Project/View/components/FilterRowsEditor.tsx
@@ -149,6 +149,24 @@ const filtersToRows = (filters: FilterType[] = []): FilterRow[] => {
})
}
+const getMetadataColumnBase = (column: string) => {
+ if (column === 'ev:key' || column.startsWith('ev:key:')) return 'ev:key'
+ if (column === 'tag:key' || column.startsWith('tag:key:')) return 'tag:key'
+ if (column === 'ev:value') return 'ev:value'
+ if (column === 'tag:value') return 'tag:value'
+ return column
+}
+
+const getOperatorsForColumn = (column: string) => {
+ if (column === 'ev:key' || column === 'tag:key') {
+ return OPERATORS.filter(
+ (operator) => operator.value === 'is' || operator.value === 'isNot',
+ )
+ }
+
+ return OPERATORS
+}
+
const InlineButton = ({
text,
onClick,
@@ -287,6 +305,30 @@ const FilterRowsEditor = ({
[filterRows, language],
)
+ const getColumnLabel = useCallback(
+ (column: string) => {
+ if (column.startsWith('ev:key:')) {
+ return t('project.metamapping.ev.dynamicKey', {
+ key: column.replace(/^ev:key:/, ''),
+ })
+ }
+
+ if (column.startsWith('tag:key:')) {
+ return t('project.metamapping.tag.dynamicKey', {
+ key: column.replace(/^tag:key:/, ''),
+ })
+ }
+
+ return tnMapping[column] || t(`project.mapping.${column}`)
+ },
+ [t, tnMapping],
+ )
+
+ const getColumnIcon = useCallback((column: string) => {
+ const baseColumn = getMetadataColumnBase(column)
+ return filterCategoryIcons[column] || filterCategoryIcons[baseColumn]
+ }, [])
+
useEffect(() => {
if (!active) {
return
@@ -297,6 +339,13 @@ const FilterRowsEditor = ({
const fetchFilterValues = useCallback(
async (column: string) => {
+ if (getMetadataColumnBase(column) !== column || column.includes(':')) {
+ setFilterValuesCache((prev) =>
+ prev[column] ? prev : { ...prev, [column]: [] },
+ )
+ return
+ }
+
if (
filterValuesCache[column] ||
loadingColumns.has(column) ||
@@ -414,7 +463,14 @@ const FilterRowsEditor = ({
) {
fetchFilterValues(fieldValue)
}
- return { ...row, column: fieldValue, value: '' }
+ const operatorOptions = getOperatorsForColumn(fieldValue)
+ const operator = operatorOptions.some(
+ (option) => option.value === row.operator,
+ )
+ ? row.operator
+ : 'is'
+
+ return { ...row, column: fieldValue, operator, value: '' }
}
return { ...row, [field]: fieldValue }
@@ -431,180 +487,182 @@ const FilterRowsEditor = ({
return (
<div className='space-y-4'>
<div className='space-y-3'>
- {filterRows.map((row) => (
- <div
- key={row.id}
- className='grid gap-2 sm:grid-cols-[minmax(0,11rem)_minmax(0,8rem)_minmax(0,1fr)_auto]'
- >
- <Listbox
- value={row.column}
- onChange={(value) => updateFilterRow(row.id, 'column', value)}
- >
- {({ open }) => (
- <div className='relative min-w-0'>
- <ListboxButton className='relative w-full rounded-md border border-gray-300 bg-white py-2 pr-8 pl-3 text-left text-sm transition-colors hover:bg-gray-50 focus:ring-2 focus:ring-slate-900 focus:ring-offset-1 focus:outline-hidden dark:border-gray-700 dark:bg-slate-900 dark:text-gray-50 dark:hover:bg-slate-800 dark:focus:ring-slate-300'>
- <span
- className={cx('flex items-center gap-2 truncate', {
- 'text-gray-400': !row.column,
- })}
- >
- {row.column ? filterCategoryIcons[row.column] : null}
- {row.column
- ? tnMapping[row.column] ||
- t(`project.mapping.${row.column}`)
- : t('project.selectColumn')}
- </span>
- <span className='pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2'>
- <CaretUpDownIcon className='h-4 w-4 text-gray-400' />
- </span>
- </ListboxButton>
- <Transition
- show={open}
- as={Fragment}
- enter='transition ease-in duration-100'
- enterFrom='opacity-0'
- enterTo='opacity-100'
- leave='transition ease-in duration-100'
- leaveFrom='opacity-100'
- leaveTo='opacity-0'
- >
- <ListboxOptions
- static
- className='absolute z-50 mt-1 max-h-60 w-full min-w-[180px] overflow-auto rounded-md bg-white py-1 text-sm ring-1 ring-black/10 focus:outline-hidden dark:bg-slate-900'
- >
- {panelOptions.map((option) => (
- <ListboxOption
- key={option}
- value={option}
- className={({ focus }) =>
- cx(
- 'relative cursor-pointer py-2 pr-4 pl-3 select-none',
- {
- 'bg-gray-100 dark:bg-slate-700': focus,
- 'text-gray-700 dark:text-gray-50': !focus,
- },
- )
- }
- >
- {({ selected }) => (
- <span
- className={cx('flex items-center gap-2', {
- 'font-medium': selected,
- })}
- >
- <span className='shrink-0 text-gray-500 dark:text-gray-400'>
- {filterCategoryIcons[option]}
- </span>
- <span className='truncate'>
- {tnMapping[option] ||
- t(`project.mapping.${option}`)}
- </span>
- {selected ? (
- <CheckIcon className='ml-auto h-4 w-4 shrink-0 text-indigo-600 dark:text-indigo-400' />
- ) : null}
- </span>
- )}
- </ListboxOption>
- ))}
- </ListboxOptions>
- </Transition>
- </div>
- )}
- </Listbox>
-
- <Listbox
- value={row.operator}
- onChange={(value) => updateFilterRow(row.id, 'operator', value)}
+ {filterRows.map((row) => {
+ const operatorOptions = getOperatorsForColumn(row.column)
+
+ return (
+ <div
+ key={row.id}
+ className='grid gap-2 sm:grid-cols-[minmax(0,11rem)_minmax(0,8rem)_minmax(0,1fr)_auto]'
>
- {({ open }) => (
- <div className='relative min-w-0'>
- <ListboxButton className='relative w-full rounded-md border border-gray-300 bg-white py-2 pr-8 pl-3 text-left text-sm transition-colors hover:bg-gray-50 focus:ring-2 focus:ring-slate-900 focus:ring-offset-1 focus:outline-hidden dark:border-gray-700 dark:bg-slate-900 dark:text-gray-50 dark:hover:bg-slate-800 dark:focus:ring-slate-300'>
- <span className='block truncate'>
- {t(
- OPERATORS.find(
- (operator) => operator.value === row.operator,
- )?.labelKey || '',
- )}
- </span>
- <span className='pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2'>
- <CaretUpDownIcon className='h-4 w-4 text-gray-400' />
- </span>
- </ListboxButton>
- <Transition
- show={open}
- as={Fragment}
- enter='transition ease-in duration-100'
- enterFrom='opacity-0'
- enterTo='opacity-100'
- leave='transition ease-in duration-100'
- leaveFrom='opacity-100'
- leaveTo='opacity-0'
- >
- <ListboxOptions
- static
- className='absolute z-50 mt-1 w-full overflow-auto rounded-md bg-white py-1 text-sm ring-1 ring-black/10 focus:outline-hidden dark:bg-slate-900'
+ <Listbox
+ value={row.column}
+ onChange={(value) => updateFilterRow(row.id, 'column', value)}
+ >
+ {({ open }) => (
+ <div className='relative min-w-0'>
+ <ListboxButton className='relative w-full rounded-md border border-gray-300 bg-white py-2 pr-8 pl-3 text-left text-sm transition-colors hover:bg-gray-50 focus:ring-2 focus:ring-slate-900 focus:ring-offset-1 focus:outline-hidden dark:border-gray-700 dark:bg-slate-900 dark:text-gray-50 dark:hover:bg-slate-800 dark:focus:ring-slate-300'>
+ <span
+ className={cx('flex items-center gap-2 truncate', {
+ 'text-gray-400': !row.column,
+ })}
+ >
+ {row.column ? getColumnIcon(row.column) : null}
+ {row.column
+ ? getColumnLabel(row.column)
+ : t('project.selectColumn')}
+ </span>
+ <span className='pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2'>
+ <CaretUpDownIcon className='h-4 w-4 text-gray-400' />
+ </span>
+ </ListboxButton>
+ <Transition
+ show={open}
+ as={Fragment}
+ enter='transition ease-in duration-100'
+ enterFrom='opacity-0'
+ enterTo='opacity-100'
+ leave='transition ease-in duration-100'
+ leaveFrom='opacity-100'
+ leaveTo='opacity-0'
>
- {OPERATORS.map((operator) => (
- <ListboxOption
- key={operator.value}
- value={operator.value}
- className={({ focus }) =>
- cx(
- 'relative cursor-pointer py-2 pr-4 pl-8 select-none',
- {
- 'bg-gray-100 dark:bg-slate-700': focus,
- 'text-gray-700 dark:text-gray-50': !focus,
- },
- )
- }
- >
- {({ selected }) => (
- <>
+ <ListboxOptions
+ static
+ className='absolute z-50 mt-1 max-h-60 w-full min-w-[180px] overflow-auto rounded-md bg-white py-1 text-sm ring-1 ring-black/10 focus:outline-hidden dark:bg-slate-900'
+ >
+ {panelOptions.map((option) => (
+ <ListboxOption
+ key={option}
+ value={option}
+ className={({ focus }) =>
+ cx(
+ 'relative cursor-pointer py-2 pr-4 pl-3 select-none',
+ {
+ 'bg-gray-100 dark:bg-slate-700': focus,
+ 'text-gray-700 dark:text-gray-50': !focus,
+ },
+ )
+ }
+ >
+ {({ selected }) => (
<span
- className={cx('block truncate', {
+ className={cx('flex items-center gap-2', {
'font-medium': selected,
})}
>
- {t(operator.labelKey)}
+ <span className='shrink-0 text-gray-500 dark:text-gray-400'>
+ {getColumnIcon(option)}
+ </span>
+ <span className='truncate'>
+ {getColumnLabel(option)}
+ </span>
+ {selected ? (
+ <CheckIcon className='ml-auto h-4 w-4 shrink-0 text-indigo-600 dark:text-indigo-400' />
+ ) : null}
</span>
- {selected ? (
- <span className='absolute inset-y-0 left-0 flex items-center pl-2 text-indigo-600 dark:text-indigo-400'>
- <CheckIcon className='h-4 w-4' />
+ )}
+ </ListboxOption>
+ ))}
+ </ListboxOptions>
+ </Transition>
+ </div>
+ )}
+ </Listbox>
+
+ <Listbox
+ value={row.operator}
+ onChange={(value) => updateFilterRow(row.id, 'operator', value)}
+ >
+ {({ open }) => (
+ <div className='relative min-w-0'>
+ <ListboxButton className='relative w-full rounded-md border border-gray-300 bg-white py-2 pr-8 pl-3 text-left text-sm transition-colors hover:bg-gray-50 focus:ring-2 focus:ring-slate-900 focus:ring-offset-1 focus:outline-hidden dark:border-gray-700 dark:bg-slate-900 dark:text-gray-50 dark:hover:bg-slate-800 dark:focus:ring-slate-300'>
+ <span className='block truncate'>
+ {t(
+ operatorOptions.find(
+ (operator) => operator.value === row.operator,
+ )?.labelKey || '',
+ )}
+ </span>
+ <span className='pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2'>
+ <CaretUpDownIcon className='h-4 w-4 text-gray-400' />
+ </span>
+ </ListboxButton>
+ <Transition
+ show={open}
+ as={Fragment}
+ enter='transition ease-in duration-100'
+ enterFrom='opacity-0'
+ enterTo='opacity-100'
+ leave='transition ease-in duration-100'
+ leaveFrom='opacity-100'
+ leaveTo='opacity-0'
+ >
+ <ListboxOptions
+ static
+ className='absolute z-50 mt-1 w-full overflow-auto rounded-md bg-white py-1 text-sm ring-1 ring-black/10 focus:outline-hidden dark:bg-slate-900'
+ >
+ {operatorOptions.map((operator) => (
+ <ListboxOption
+ key={operator.value}
+ value={operator.value}
+ className={({ focus }) =>
+ cx(
+ 'relative cursor-pointer py-2 pr-4 pl-8 select-none',
+ {
+ 'bg-gray-100 dark:bg-slate-700': focus,
+ 'text-gray-700 dark:text-gray-50': !focus,
+ },
+ )
+ }
+ >
+ {({ selected }) => (
+ <>
+ <span
+ className={cx('block truncate', {
+ 'font-medium': selected,
+ })}
+ >
+ {t(operator.labelKey)}
</span>
- ) : null}
- </>
- )}
- </ListboxOption>
- ))}
- </ListboxOptions>
- </Transition>
- </div>
- )}
- </Listbox>
-
- <FilterValueInput
- items={filterValuesCache[row.column] || []}
- value={row.value}
- onChange={(value) => updateFilterRow(row.id, 'value', value)}
- placeholder={t('project.filterSearchOrType')}
- column={row.column}
- language={language}
- disabled={!row.column}
- isLoading={loadingColumns.has(row.column)}
- theme={theme}
- className='min-w-0'
- />
-
- <button
- type='button'
- onClick={() => removeFilterRow(row.id)}
- className='rounded-md p-2 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-slate-800 dark:hover:text-gray-300'
- title={t('project.removeFilter')}
- >
- <TrashIcon className='h-5 w-5' />
- </button>
- </div>
- ))}
+ {selected ? (
+ <span className='absolute inset-y-0 left-0 flex items-center pl-2 text-indigo-600 dark:text-indigo-400'>
+ <CheckIcon className='h-4 w-4' />
+ </span>
+ ) : null}
+ </>
+ )}
+ </ListboxOption>
+ ))}
+ </ListboxOptions>
+ </Transition>
+ </div>
+ )}
+ </Listbox>
+
+ <FilterValueInput
+ items={filterValuesCache[row.column] || []}
+ value={row.value}
+ onChange={(value) => updateFilterRow(row.id, 'value', value)}
+ placeholder={t('project.filterSearchOrType')}
+ column={row.column}
+ language={language}
+ disabled={!row.column}
+ isLoading={loadingColumns.has(row.column)}
+ theme={theme}
+ className='min-w-0'
+ />
+
+ <button
+ type='button'
+ onClick={() => removeFilterRow(row.id)}
+ className='rounded-md p-2 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-slate-800 dark:hover:text-gray-300'
+ title={t('project.removeFilter')}
+ >
+ <TrashIcon className='h-5 w-5' />
+ </button>
+ </div>
+ )
+ })}
</div>
<div className='flex items-center justify-between'>
@@ -651,7 +709,7 @@ const FilterRowsEditor = ({
className='inline-flex items-center gap-1 rounded-full bg-gray-100 px-2.5 py-1 text-xs font-medium text-gray-700 dark:bg-slate-700 dark:text-gray-300'
>
<span className='text-gray-500 dark:text-gray-400'>
- {tnMapping[column] || t(`project.mapping.${column}`)}
+ {getColumnLabel(column)}
</span>
<span
className={cx({
diff --git a/web/app/pages/Project/View/utils/projectViewSegments.ts b/web/app/pages/Project/View/utils/projectViewSegments.ts
index 19fbb0b27..d1e771266 100644
--- a/web/app/pages/Project/View/utils/projectViewSegments.ts
+++ b/web/app/pages/Project/View/utils/projectViewSegments.ts
@@ -49,6 +49,8 @@ const ANALYTICS_TABS = new Set<ProjectTab>([
PROJECT_TABS.traffic,
PROJECT_TABS.sessions,
PROJECT_TABS.profiles,
+ PROJECT_TABS.funnels,
+ PROJECT_TABS.goals,
])
const FILTER_OPTIONS_BY_TAB: Partial<Record<ProjectTab, string[]>> = {
@@ -57,6 +59,8 @@ const FILTER_OPTIONS_BY_TAB: Partial<Record<ProjectTab, string[]>> = {
[PROJECT_TABS.seo]: ['pg', 'cc', 'dv'],
[PROJECT_TABS.sessions]: FILTERS_PANELS_ORDER,
[PROJECT_TABS.profiles]: FILTERS_PANELS_ORDER,
+ [PROJECT_TABS.funnels]: FILTERS_PANELS_ORDER,
+ [PROJECT_TABS.goals]: FILTERS_PANELS_ORDER,
[PROJECT_TABS.errors]: ['host', ...ERRORS_FILTERS_PANELS_ORDER],
[PROJECT_TABS.captcha]: CAPTCHA_FILTER_COLUMNS,
}
diff --git a/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx b/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx
index 5a77c93f0..fed34d4b9 100644
--- a/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx
+++ b/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx
@@ -30,6 +30,8 @@ import NewFunnel from '~/modals/NewFunnel'
import { FunnelChart } from '~/pages/Project/tabs/Funnels/FunnelChart'
import FunnelsList from '~/pages/Project/tabs/Funnels/FunnelsList'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
+import Filters from '~/pages/Project/View/components/Filters'
+import ProjectViewHeaderActions from '~/pages/Project/View/components/ProjectViewHeaderActions'
import {
useViewProjectContext,
useRefreshTriggers,
@@ -66,27 +68,37 @@ function FunnelDataResolver({
return <>{children({ funnelData })}</>
}
-function FunnelsViewWrapper() {
+interface FunnelsViewProps {
+ tnMapping: Record<string, string>
+}
+
+function FunnelsViewWrapper({ tnMapping }: FunnelsViewProps) {
return (
<Suspense fallback={<LoaderView />}>
<FunnelDataResolver>
- {(deferredData) => <FunnelsViewInner deferredData={deferredData} />}
+ {(deferredData) => (
+ <FunnelsViewInner deferredData={deferredData} tnMapping={tnMapping} />
+ )}
</FunnelDataResolver>
</Suspense>
)
}
-interface FunnelsViewInnerProps {
+interface FunnelsViewInnerProps extends FunnelsViewProps {
deferredData: DeferredFunnelData
}
-const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {
+const FunnelsViewInner = ({
+ deferredData,
+ tnMapping,
+}: FunnelsViewInnerProps) => {
const { id, project, mergeProject, allowedToManage } = useCurrentProject()
const projectPassword = useProjectPassword(id)
const revalidator = useRevalidator()
const { isAuthenticated } = useAuth()
const { funnelsRefreshTrigger } = useRefreshTriggers()
- const { periodPairs, period, timezone, timeFormat } = useViewProjectContext()
+ const { periodPairs, period, timezone, timeFormat, filters } =
+ useViewProjectContext()
// Filter periods to only include those valid for funnels
const timeBucketSelectorItems = useMemo(() => {
@@ -111,6 +123,7 @@ const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {
const [sessionsDrawer, setSessionsDrawer] = useState<{
stepIndex: number
label: string
+ dropoff?: boolean
} | null>(null)
// Initialize funnelAnalytics from loader data
@@ -339,9 +352,9 @@ const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {
backLink={`?${pureSearchParams}`}
backButtonLabel={t('project.backToFunnels')}
showLiveVisitors={false}
- showSearchButton={false}
hideTimeBucket
timeBucketSelectorItems={timeBucketSelectorItems}
+ rightContent={<ProjectViewHeaderActions tnMapping={tnMapping} />}
leftContent={
<Text
as='h2'
@@ -353,6 +366,7 @@ const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {
</Text>
}
/>
+ <Filters className='mb-3' tnMapping={tnMapping} />
{dataLoading && funnelAnalytics ? <LoadingBar /> : null}
{/* Funnel Chart */}
@@ -417,11 +431,26 @@ const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {
period={period}
from={searchParams.get('from') || undefined}
to={searchParams.get('to') || undefined}
+ filters={filters}
funnelId={activeFunnel?.id}
funnelStep={sessionsDrawer ? sessionsDrawer.stepIndex + 1 : undefined}
+ dropoff={Boolean(sessionsDrawer?.dropoff)}
+ showDropoffToggle={
+ !!sessionsDrawer &&
+ sessionsDrawer.stepIndex <
+ (funnelAnalytics?.funnel?.length || 0) - 1
+ }
+ onDropoffChange={(dropoff) =>
+ setSessionsDrawer((current) =>
+ current ? { ...current, dropoff } : current,
+ )
+ }
totalCount={
sessionsDrawer
- ? funnelAnalytics?.funnel?.[sessionsDrawer.stepIndex]?.events
+ ? sessionsDrawer.dropoff
+ ? funnelAnalytics?.funnel?.[sessionsDrawer.stepIndex + 1]
+ ?.dropoff
+ : funnelAnalytics?.funnel?.[sessionsDrawer.stepIndex]?.events
: undefined
}
/>
diff --git a/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx b/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx
index 8189d8768..4f516cf48 100644
--- a/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx
+++ b/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx
@@ -6,18 +6,25 @@ import {
} from '@headlessui/react'
import _map from 'lodash/map'
import { TrashIcon, PlusIcon, XIcon } from '@phosphor-icons/react'
-import { useState, useEffect, useRef } from 'react'
+import { useState, useEffect, useRef, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { useFetcher } from 'react-router'
import { toast } from 'sonner'
import { useGoalProxy } from '~/hooks/useAnalyticsProxy'
+import type {
+ GoalCondition,
+ GoalConditionRelation,
+ GoalConditions,
+} from '~/api/api.server'
import type { ProjectViewActionData } from '~/routes/projects.$id'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
import Loader from '~/ui/Loader'
import Select from '~/ui/Select'
import { Text } from '~/ui/Text'
+import type { Filter as FilterType } from '../../View/interfaces/traffic'
+import FilterRowsEditor from '../../View/components/FilterRowsEditor'
const GOAL_TYPES = [
{ value: 'pageview', label: 'Pageview' },
@@ -29,12 +36,155 @@ const GOAL_MATCH_TYPES = [
{ value: 'contains', label: 'Contains' },
]
+const DEFINITION_MODES = [
+ { value: 'simple', labelKey: 'goals.simpleGoal' },
+ { value: 'conditions', labelKey: 'goals.multiConditionGoal' },
+] as const
+
+const CONDITION_RELATIONS: { value: GoalConditionRelation; label: string }[] = [
+ { value: 'AND', label: 'AND' },
+ { value: 'OR', label: 'OR' },
+]
+
+const GOAL_CONDITION_FILTER_OPTIONS = [
+ 'pg',
+ 'ev',
+ 'host',
+ 'cc',
+ 'dv',
+ 'br',
+ 'os',
+ 'ref',
+ 'so',
+ 'me',
+ 'ca',
+ 'te',
+ 'co',
+ 'tag:key',
+ 'ev:key',
+]
+
+const createConditionId = () =>
+ globalThis.crypto?.randomUUID?.() || Math.random().toString(36).slice(2)
+
+const filterToConditionOperator = ({
+ isExclusive,
+ isContains,
+}: FilterType): GoalCondition['operator'] => {
+ if (isContains && isExclusive) return 'not_contains'
+ if (isContains) return 'contains'
+ if (isExclusive) return 'not_equals'
+ return 'equals'
+}
+
+const conditionOperatorToFilterFlags = (
+ operator: GoalCondition['operator'],
+) => ({
+ isExclusive: operator === 'not_equals' || operator === 'not_contains',
+ isContains: operator === 'contains' || operator === 'not_contains',
+})
+
+const getMetadataConditionPrefix = (eventType: GoalCondition['eventType']) =>
+ eventType === 'custom_event' ? 'ev:key' : 'tag:key'
+
+const filterToCondition = (filter: FilterType): GoalCondition | null => {
+ if (!filter.column || !filter.filter) return null
+
+ if (filter.column === 'ev') {
+ return {
+ id: createConditionId(),
+ eventType: 'custom_event',
+ field: 'event_name',
+ operator: filterToConditionOperator(filter),
+ value: filter.filter,
+ }
+ }
+
+ if (filter.column === 'ev:key' || filter.column === 'tag:key') {
+ return {
+ id: createConditionId(),
+ eventType: filter.column === 'ev:key' ? 'custom_event' : 'pageview',
+ field: 'metadata',
+ operator: filter.isExclusive ? 'not_exists' : 'exists',
+ metadataKey: filter.filter,
+ }
+ }
+
+ if (
+ filter.column.startsWith('ev:key:') ||
+ filter.column.startsWith('tag:key:')
+ ) {
+ return {
+ id: createConditionId(),
+ eventType: filter.column.startsWith('ev:key:')
+ ? 'custom_event'
+ : 'pageview',
+ field: 'metadata',
+ operator: filterToConditionOperator(filter),
+ metadataKey: filter.column
+ .replace(/^ev:key:/, '')
+ .replace(/^tag:key:/, ''),
+ value: filter.filter,
+ }
+ }
+
+ return {
+ id: createConditionId(),
+ eventType: filter.column === 'pg' ? 'pageview' : 'any',
+ field: filter.column,
+ operator: filterToConditionOperator(filter),
+ value: filter.filter,
+ }
+}
+
+const conditionToFilter = (condition: GoalCondition): FilterType | null => {
+ if (condition.field === 'metadata') {
+ if (!condition.metadataKey) return null
+
+ const prefix = getMetadataConditionPrefix(condition.eventType)
+
+ if (
+ condition.operator === 'exists' ||
+ condition.operator === 'not_exists'
+ ) {
+ return {
+ column: prefix,
+ filter: condition.metadataKey,
+ isExclusive: condition.operator === 'not_exists',
+ isContains: false,
+ }
+ }
+
+ if (!condition.value) return null
+ const flags = conditionOperatorToFilterFlags(condition.operator)
+
+ return {
+ column: `${prefix}:${condition.metadataKey}`,
+ filter: condition.value,
+ ...flags,
+ }
+ }
+
+ if (!condition.value) return null
+ const flags = conditionOperatorToFilterFlags(condition.operator)
+
+ return {
+ column:
+ condition.field === 'event' || condition.field === 'event_name'
+ ? 'ev'
+ : condition.field,
+ filter: condition.value,
+ ...flags,
+ }
+}
+
interface GoalSettingsModalProps {
isOpen: boolean
onClose: () => void
onSuccess: () => void
projectId: string
goalId?: string | null
+ tnMapping: Record<string, string>
}
const GoalSettingsModal = ({
@@ -43,6 +193,7 @@ const GoalSettingsModal = ({
onSuccess,
projectId: _projectId,
goalId,
+ tnMapping,
}: GoalSettingsModalProps) => {
const { t } = useTranslation()
const fetcher = useFetcher<ProjectViewActionData>()
@@ -52,7 +203,6 @@ const GoalSettingsModal = ({
const [isLoading, setIsLoading] = useState(false)
- // Form state
const [name, setName] = useState('')
const [type, setType] = useState<'pageview' | 'custom_event'>('pageview')
const [matchType, setMatchType] = useState<'exact' | 'contains'>('exact')
@@ -60,16 +210,38 @@ const GoalSettingsModal = ({
const [metadataFilters, setMetadataFilters] = useState<
{ key: string; value: string }[]
>([])
+ const [definitionMode, setDefinitionMode] =
+ useState<(typeof DEFINITION_MODES)[number]['value']>('simple')
+ const [conditionsRelation, setConditionsRelation] =
+ useState<GoalConditionRelation>('AND')
+ const [conditionInitialFilters, setConditionInitialFilters] = useState<
+ FilterType[]
+ >([])
+ const [conditionFilters, setConditionFilters] = useState<FilterType[]>([])
+ const [unmappedConditions, setUnmappedConditions] = useState<GoalCondition[]>(
+ [],
+ )
+ const [conditionResetKey, setConditionResetKey] = useState('new')
const isSaving = fetcher.state === 'submitting'
- const resetForm = () => {
+ const resetConditionFilters = useCallback((filters: FilterType[] = []) => {
+ setConditionInitialFilters(filters)
+ setConditionFilters(filters)
+ setUnmappedConditions([])
+ setConditionResetKey(createConditionId())
+ }, [])
+
+ const resetForm = useCallback(() => {
setName('')
setType('pageview')
setMatchType('exact')
setValue('')
setMetadataFilters([])
- }
+ setDefinitionMode('simple')
+ setConditionsRelation('AND')
+ resetConditionFilters()
+ }, [resetConditionFilters])
const loadGoal = async () => {
if (!goalId) return
@@ -84,6 +256,31 @@ const GoalSettingsModal = ({
setMatchType(goal.matchType)
setValue(goal.value || '')
setMetadataFilters(goal.metadataFilters || [])
+ setDefinitionMode(
+ goal.conditions?.conditions?.length ? 'conditions' : 'simple',
+ )
+ setConditionsRelation(goal.conditions?.relation || 'AND')
+ const mappedFilters: FilterType[] = []
+ const nextUnmappedConditions: GoalCondition[] = []
+ const loadedConditions = goal.conditions?.conditions || []
+
+ loadedConditions.forEach((condition) => {
+ const filter = conditionToFilter(condition)
+ if (filter) {
+ mappedFilters.push(filter)
+ return
+ }
+
+ nextUnmappedConditions.push({
+ ...condition,
+ id: condition.id || createConditionId(),
+ })
+ })
+
+ setConditionInitialFilters(mappedFilters)
+ setConditionFilters(mappedFilters)
+ setUnmappedConditions(nextUnmappedConditions)
+ setConditionResetKey(createConditionId())
} catch (err: any) {
toast.error(err?.message || 'Failed to load goal')
onClose()
@@ -103,7 +300,6 @@ const GoalSettingsModal = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isOpen, goalId])
- // Handle fetcher responses
useEffect(() => {
if (!fetcher.data || fetcher.state !== 'idle') return
@@ -125,7 +321,6 @@ const GoalSettingsModal = ({
}
}, [fetcher.data, fetcher.state, t, onSuccess, onClose])
- // Reset processed ref when modal opens
useEffect(() => {
if (isOpen) {
processedRef.current = null
@@ -142,7 +337,26 @@ const GoalSettingsModal = ({
formData.set('type', type)
formData.set('matchType', matchType)
formData.set('value', value)
- formData.set('metadataFilters', JSON.stringify(metadataFilters))
+ formData.set(
+ 'metadataFilters',
+ JSON.stringify(
+ metadataFilters.filter((filter) => filter.key && filter.value),
+ ),
+ )
+
+ const mappedConditions = conditionFilters
+ .map(filterToCondition)
+ .filter((condition): condition is GoalCondition => Boolean(condition))
+ const goalConditions: GoalConditions | null =
+ definitionMode === 'conditions' &&
+ (mappedConditions.length > 0 || unmappedConditions.length > 0)
+ ? {
+ relation: conditionsRelation,
+ conditions: [...mappedConditions, ...unmappedConditions],
+ }
+ : null
+
+ formData.set('conditions', JSON.stringify(goalConditions))
if (!isNew && goalId) {
formData.set('goalId', goalId)
@@ -180,7 +394,7 @@ const GoalSettingsModal = ({
<div className='flex min-h-full items-center justify-center p-4'>
<DialogPanel
transition
- className='w-full max-w-lg transform rounded-xl bg-white transition-all data-closed:translate-y-4 data-closed:opacity-0 data-enter:ease-out data-leave:duration-200 data-leave:ease-in dark:bg-slate-950'
+ className='w-full max-w-3xl transform rounded-xl bg-white transition-all data-closed:translate-y-4 data-closed:opacity-0 data-enter:ease-out data-leave:duration-200 data-leave:ease-in dark:bg-slate-950'
>
{isLoading ? (
<div className='flex min-h-[300px] items-center justify-center'>
@@ -211,136 +425,202 @@ const GoalSettingsModal = ({
required
/>
- <div>
- <label className='mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300'>
- {t('goals.type')}
- </label>
- <Select
- items={GOAL_TYPES}
- onSelect={(item) =>
- setType(item.value as 'pageview' | 'custom_event')
- }
- title={
- GOAL_TYPES.find((t) => t.value === type)?.label || ''
- }
- labelExtractor={(item) => item.label}
- keyExtractor={(item) => item.value}
- selectedItem={GOAL_TYPES.find((t) => t.value === type)}
- capitalise
- />
- <Text as='p' size='xs' colour='muted' className='mt-1'>
- {type === 'pageview'
- ? t('goals.typePageviewDesc')
- : t('goals.typeCustomEventDesc')}
- </Text>
- </div>
-
- <div>
- <label className='mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300'>
- {t('goals.matchType')}
- </label>
- <Select
- items={GOAL_MATCH_TYPES}
- onSelect={(item) =>
- setMatchType(item.value as 'exact' | 'contains')
- }
- title={
- GOAL_MATCH_TYPES.find((t) => t.value === matchType)
- ?.label || ''
- }
- labelExtractor={(item) => item.label}
- keyExtractor={(item) => item.value}
- selectedItem={GOAL_MATCH_TYPES.find(
- (t) => t.value === matchType,
- )}
- capitalise
- />
- </div>
-
- <Input
- label={
- type === 'pageview'
- ? t('goals.pagePath')
- : t('goals.eventName')
- }
- value={value}
- onChange={(e) => setValue(e.target.value)}
- placeholder={
- type === 'pageview'
- ? matchType === 'exact'
- ? '/pricing'
- : 'pricing'
- : matchType === 'exact'
- ? 'signup_completed'
- : 'signup'
- }
+ <Select
+ items={DEFINITION_MODES}
+ onSelect={(item) => setDefinitionMode(item.value)}
+ title={t(
+ DEFINITION_MODES.find(
+ (item) => item.value === definitionMode,
+ )?.labelKey || 'goals.simpleGoal',
+ )}
+ label={t('goals.definitionMode')}
+ labelExtractor={(item) => t(item.labelKey)}
+ keyExtractor={(item) => item.value}
+ selectedItem={DEFINITION_MODES.find(
+ (item) => item.value === definitionMode,
+ )}
/>
- {/* Metadata filters */}
- <div>
- <div className='mb-2 flex items-center justify-between'>
- <label className='block text-sm font-medium text-gray-700 dark:text-gray-300'>
- {t('goals.metadataFilters')}
- </label>
- <button
- type='button'
- onClick={addMetadataFilter}
- className='flex items-center gap-1 text-sm text-gray-700 underline decoration-dashed hover:decoration-solid dark:text-gray-200'
- >
- <PlusIcon className='size-3' />
- {t('goals.addFilter')}
- </button>
- </div>
- {metadataFilters.length > 0 ? (
- <div className='space-y-2'>
- {_map(metadataFilters, (filter, index) => (
- <div
- key={index}
- className='flex items-center gap-2'
+ {definitionMode === 'simple' ? (
+ <>
+ <div>
+ <label className='mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300'>
+ {t('goals.type')}
+ </label>
+ <Select
+ items={GOAL_TYPES}
+ onSelect={(item) =>
+ setType(item.value as 'pageview' | 'custom_event')
+ }
+ title={
+ GOAL_TYPES.find((t) => t.value === type)?.label ||
+ ''
+ }
+ labelExtractor={(item) => item.label}
+ keyExtractor={(item) => item.value}
+ selectedItem={GOAL_TYPES.find(
+ (t) => t.value === type,
+ )}
+ capitalise
+ />
+ <Text
+ as='p'
+ size='xs'
+ colour='muted'
+ className='mt-1'
+ >
+ {type === 'pageview'
+ ? t('goals.typePageviewDesc')
+ : t('goals.typeCustomEventDesc')}
+ </Text>
+ </div>
+
+ <div>
+ <label className='mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300'>
+ {t('goals.matchType')}
+ </label>
+ <Select
+ items={GOAL_MATCH_TYPES}
+ onSelect={(item) =>
+ setMatchType(item.value as 'exact' | 'contains')
+ }
+ title={
+ GOAL_MATCH_TYPES.find(
+ (t) => t.value === matchType,
+ )?.label || ''
+ }
+ labelExtractor={(item) => item.label}
+ keyExtractor={(item) => item.value}
+ selectedItem={GOAL_MATCH_TYPES.find(
+ (t) => t.value === matchType,
+ )}
+ capitalise
+ />
+ </div>
+
+ <Input
+ label={
+ type === 'pageview'
+ ? t('goals.pagePath')
+ : t('goals.eventName')
+ }
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ placeholder={
+ type === 'pageview'
+ ? matchType === 'exact'
+ ? '/pricing'
+ : 'pricing'
+ : matchType === 'exact'
+ ? 'signup_completed'
+ : 'signup'
+ }
+ />
+
+ <div>
+ <div className='mb-2 flex items-center justify-between'>
+ <label className='block text-sm font-medium text-gray-700 dark:text-gray-300'>
+ {t('goals.metadataFilters')}
+ </label>
+ <button
+ type='button'
+ onClick={addMetadataFilter}
+ className='flex items-center gap-1 text-sm text-gray-700 underline decoration-dashed hover:decoration-solid dark:text-gray-200'
>
- <Input
- value={filter.key}
- onChange={(e) =>
- updateMetadataFilter(
- index,
- 'key',
- e.target.value,
- )
- }
- placeholder={t('goals.filterKey')}
- className='flex-1'
- />
- <span className='text-gray-500'>=</span>
- <Input
- value={filter.value}
- onChange={(e) =>
- updateMetadataFilter(
- index,
- 'value',
- e.target.value,
- )
- }
- placeholder={t('goals.filterValue')}
- className='flex-1'
- />
- <Button
- variant='icon'
- type='button'
- onClick={() => removeMetadataFilter(index)}
- aria-label={t('common.delete')}
- className='p-1.5 text-gray-800 dark:text-slate-400 dark:hover:text-slate-300'
- >
- <TrashIcon className='h-4 w-4' />
- </Button>
+ <PlusIcon className='size-3' />
+ {t('goals.addFilter')}
+ </button>
+ </div>
+ {metadataFilters.length > 0 ? (
+ <div className='space-y-2'>
+ {_map(metadataFilters, (filter, index) => (
+ <div
+ key={index}
+ className='flex items-center gap-2'
+ >
+ <Input
+ value={filter.key}
+ onChange={(e) =>
+ updateMetadataFilter(
+ index,
+ 'key',
+ e.target.value,
+ )
+ }
+ placeholder={t('goals.filterKey')}
+ className='flex-1'
+ />
+ <span className='text-gray-500'>=</span>
+ <Input
+ value={filter.value}
+ onChange={(e) =>
+ updateMetadataFilter(
+ index,
+ 'value',
+ e.target.value,
+ )
+ }
+ placeholder={t('goals.filterValue')}
+ className='flex-1'
+ />
+ <Button
+ variant='icon'
+ type='button'
+ onClick={() => removeMetadataFilter(index)}
+ aria-label={t('common.delete')}
+ className='p-1.5 text-gray-800 dark:text-slate-400 dark:hover:text-slate-300'
+ >
+ <TrashIcon className='h-4 w-4' />
+ </Button>
+ </div>
+ ))}
</div>
- ))}
+ ) : (
+ <Text as='p' size='sm' colour='muted'>
+ {t('goals.noMetadataFilters')}
+ </Text>
+ )}
</div>
- ) : (
- <Text as='p' size='sm' colour='muted'>
- {t('goals.noMetadataFilters')}
- </Text>
- )}
- </div>
+ </>
+ ) : (
+ <div className='space-y-3'>
+ <div className='max-w-44'>
+ <Select
+ items={CONDITION_RELATIONS}
+ onSelect={(item) =>
+ setConditionsRelation(item.value)
+ }
+ title={conditionsRelation}
+ label={t('goals.matchConditionsWith')}
+ labelExtractor={(item) => item.label}
+ keyExtractor={(item) => item.value}
+ selectedItem={CONDITION_RELATIONS.find(
+ (item) => item.value === conditionsRelation,
+ )}
+ />
+ </div>
+
+ <div>
+ <Text
+ as='p'
+ size='sm'
+ weight='medium'
+ className='mb-3 text-gray-700 dark:text-gray-100'
+ >
+ {t('project.filters')}
+ </Text>
+ <FilterRowsEditor
+ active={isOpen && definitionMode === 'conditions'}
+ tnMapping={tnMapping}
+ initialFilters={conditionInitialFilters}
+ type='traffic'
+ filterOptions={GOAL_CONDITION_FILTER_OPTIONS}
+ onChange={setConditionFilters}
+ resetKey={conditionResetKey}
+ />
+ </div>
+ </div>
+ )}
</div>
</div>
diff --git a/web/app/pages/Project/tabs/Goals/GoalsView.tsx b/web/app/pages/Project/tabs/Goals/GoalsView.tsx
index 504766176..39eda8d38 100644
--- a/web/app/pages/Project/tabs/Goals/GoalsView.tsx
+++ b/web/app/pages/Project/tabs/Goals/GoalsView.tsx
@@ -3,6 +3,7 @@ import { area, bar } from 'billboard.js'
import cx from 'clsx'
import * as d3 from 'd3'
import dayjs from 'dayjs'
+import type { TFunction } from 'i18next'
import _debounce from 'lodash/debounce'
import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
@@ -16,6 +17,7 @@ import {
FileTextIcon,
CursorClickIcon,
CaretDownIcon,
+ QuestionIcon,
} from '@phosphor-icons/react'
import {
useState,
@@ -36,6 +38,7 @@ import type {
Goal,
GoalStats,
GoalChartData,
+ ConversionBreakdowns,
} from '~/api/api.server'
import { useGoalStatsProxy, useGoalChartProxy } from '~/hooks/useAnalyticsProxy'
import {
@@ -47,6 +50,8 @@ import {
chartTypes,
} from '~/lib/constants'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
+import Filters from '~/pages/Project/View/components/Filters'
+import ProjectViewHeaderActions from '~/pages/Project/View/components/ProjectViewHeaderActions'
import {
useViewProjectContext,
useRefreshTriggers,
@@ -66,13 +71,142 @@ import Pagination from '~/ui/Pagination'
import ProgressRing from '~/ui/ProgressRing'
import StatusPage from '~/ui/StatusPage'
import { Text } from '~/ui/Text'
-import { nFormatter } from '~/utils/generic'
+import Tooltip from '~/ui/Tooltip'
+import { escapeHtml, nFormatter } from '~/utils/generic'
+import countries from '~/utils/isoCountries'
import routes from '~/utils/routes'
import GoalSettingsModal from './GoalSettingsModal'
import { LoaderView } from '../../View/components/LoaderView'
const DEFAULT_GOALS_TAKE = 20
+const GOAL_TOOLTIP_BREAKDOWN_LIMIT = 3
+
+const isDurationValue = (seconds?: number | null): seconds is number =>
+ seconds != null && Number.isFinite(seconds)
+
+const formatDuration = (seconds?: number | null) => {
+ if (!isDurationValue(seconds)) {
+ return 'N/A'
+ }
+
+ if (seconds < 60) {
+ return `${Math.round(seconds)}s`
+ }
+
+ if (seconds < 3600) {
+ return `${Math.round(seconds / 60)}m`
+ }
+
+ return `${Math.round(seconds / 3600)}h`
+}
+
+const TIME_TO_CONVERT_METRICS = [
+ {
+ labelKey: 'goals.fromSessionStart',
+ tooltipKey: 'goals.fromSessionStartTooltip',
+ getValue: (stats: GoalStats) => stats.timeToConvert?.fromSessionStart,
+ },
+ {
+ labelKey: 'goals.fromFirstPage',
+ tooltipKey: 'goals.fromFirstPageTooltip',
+ getValue: (stats: GoalStats) => stats.timeToConvert?.fromFirstPage,
+ },
+]
+
+const getTopBreakdownEntries = (items?: Record<string, number>) => {
+ return Object.entries(items || {})
+ .filter(([, count]) => Number.isFinite(count) && count > 0)
+ .sort(([, a], [, b]) => b - a)
+ .slice(0, GOAL_TOOLTIP_BREAKDOWN_LIMIT)
+}
+
+const renderGoalTooltipBreakdowns = (
+ breakdowns: ConversionBreakdowns | undefined,
+ conversions: number,
+ t: TFunction,
+ language: string,
+) => {
+ const topSourcesEntries = getTopBreakdownEntries(breakdowns?.sources)
+ const topCountriesEntries = getTopBreakdownEntries(breakdowns?.countries)
+
+ if (topSourcesEntries.length === 0 && topCountriesEntries.length === 0) {
+ return ''
+ }
+
+ const primary = 'text-gray-900 dark:text-gray-50'
+ const secondary = 'text-gray-700 dark:text-gray-200'
+ const denominator = Math.max(conversions, 1)
+
+ const sourcesHtml =
+ topSourcesEntries.length > 0
+ ? `
+ <div class='flex-1 min-w-0'>
+ <p class='text-[10px] font-semibold uppercase tracking-wider ${secondary} mb-1.5'>
+ ${t('project.topSources')}
+ </p>
+ ${topSourcesEntries
+ .map(([domain, count]) => {
+ const perc = Math.round((count / denominator) * 100)
+ const isDirect = domain === 'Direct / None'
+ const safeDomain = escapeHtml(domain)
+ const iconHtml = isDirect
+ ? `
+ <img src='/assets/icons/chain.svg' class='size-3.5 shrink-0 dark:hidden' alt='' />
+ <img src='/assets/icons/chain-light.svg' class='size-3.5 shrink-0 hidden dark:inline' alt='' />
+ `
+ : `<img src='/api/favicon?domain=${encodeURIComponent(domain)}' class='size-3.5 rounded-sm shrink-0' loading='lazy' alt='' />`
+
+ return `
+ <div class='flex items-center justify-between gap-2 mt-1'>
+ <div class='flex items-center gap-1.5 min-w-0'>
+ ${iconHtml}
+ <span class='truncate ${primary}'>${safeDomain}</span>
+ </div>
+ <span class='font-mono tabular-nums shrink-0 ${primary}'>${perc}%</span>
+ </div>
+ `
+ })
+ .join('')}
+ </div>
+ `
+ : ''
+
+ const countriesHtml =
+ topCountriesEntries.length > 0
+ ? `
+ <div class='flex-1 min-w-0'>
+ <p class='text-[10px] font-semibold uppercase tracking-wider ${secondary} mb-1.5'>
+ ${t('project.topCountries')}
+ </p>
+ ${topCountriesEntries
+ .map(([cc, count]) => {
+ const perc = Math.round((count / denominator) * 100)
+ const safeName = escapeHtml(countries.getName(cc, language) || cc)
+ const safeCC = encodeURIComponent(cc.toLowerCase())
+
+ return `
+ <div class='flex items-center justify-between gap-2 mt-1'>
+ <div class='flex items-center gap-1.5 min-w-0'>
+ <img src='/assets/flags/${safeCC}.svg' width='16' height='12' class='shrink-0 rounded-[2px]' loading='lazy' alt='' />
+ <span class='truncate ${primary}'>${safeName}</span>
+ </div>
+ <span class='font-mono tabular-nums shrink-0 ${primary}'>${perc}%</span>
+ </div>
+ `
+ })
+ .join('')}
+ </div>
+ `
+ : ''
+
+ return `
+ <div class='border-t border-gray-200 dark:border-slate-700/80 mt-2 pt-2 flex gap-5'>
+ ${sourcesHtml}
+ ${countriesHtml}
+ </div>
+ `
+}
// Calculate optimal Y axis ticks
const calculateOptimalTicks = (
@@ -132,6 +266,9 @@ const getGoalChartSettings = (
timeFormat: string,
chartType: string,
dataNames: Record<string, string>,
+ t: TFunction,
+ language: string,
+ stats: GoalStats | null,
): ChartOptions => {
const xAxisSize = _size(chartData.x)
@@ -211,23 +348,32 @@ const getGoalChartSettings = (
if (!item || _isEmpty(item) || !item[0]) {
return ''
}
- return `<ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-900 rounded-md ring-1 ring-black/10 px-2 py-1 text-xs md:text-sm max-h-[250px] md:max-h-[350px] overflow-y-auto shadow-md z-50'>
- <li class='font-semibold pb-1 mb-1 border-b border-gray-200 dark:border-slate-800 sticky top-0 bg-gray-50 dark:bg-slate-900'>${
+ const breakdownsHtml = renderGoalTooltipBreakdowns(
+ stats?.breakdowns,
+ stats?.conversions || 0,
+ t,
+ language,
+ )
+
+ return `<div class='bg-gray-50 dark:bg-slate-900 rounded-lg ring-1 ring-black/10 dark:ring-white/10 px-3 py-2.5 text-xs md:text-sm max-w-sm md:max-w-md shadow-lg z-50'>
+ <div class='font-semibold pb-1 mb-1 border-b border-gray-200 dark:border-slate-800 text-gray-900 dark:text-gray-50'>${
timeFormat === TimeFormat['24-hour']
? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x)
: d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)
- }</li>
+ }</div>
${_map(item, (el: { id: string; name: string; value: string }) => {
return `
- <li class='flex justify-between items-center py-px leading-snug'>
+ <div class='flex justify-between items-center py-px leading-snug'>
<div class='flex items-center min-w-0 mr-4'>
<div class='w-2.5 h-2.5 rounded-xs mr-1.5 shrink-0' style=background-color:${color(el.id)}></div>
- <span class="truncate">${el.name}</span>
+ <span class='truncate text-gray-900 dark:text-gray-50'>${escapeHtml(el.name)}</span>
</div>
- <span class='font-mono whitespace-nowrap'>${el.value}</span>
- </li>
+ <span class='font-mono whitespace-nowrap text-gray-900 dark:text-gray-50'>${el.value}</span>
+ </div>
`
- }).join('')}</ul>`
+ }).join('')}
+ ${breakdownsHtml}
+ </div>`
},
},
point:
@@ -285,10 +431,17 @@ const GoalRow = ({
onEdit,
onToggleExpand,
}: GoalRowProps) => {
- const { t } = useTranslation()
+ const { t, i18n } = useTranslation()
const [showDeleteModal, setShowDeleteModal] = useState(false)
const patternDisplay = useMemo(() => {
+ if (goal.conditions?.conditions?.length) {
+ return t('goals.conditionsSummary', {
+ count: goal.conditions.conditions.length,
+ relation: goal.conditions.relation,
+ })
+ }
+
if (!goal.value) return null
const matchPrefix =
goal.matchType === 'exact'
@@ -297,7 +450,7 @@ const GoalRow = ({
? '~ '
: ''
return `${matchPrefix}${goal.value}`
- }, [goal.value, goal.matchType])
+ }, [goal.conditions, goal.value, goal.matchType, t])
const chartOptions = useMemo(() => {
if (!chartData || !chartData.x || chartData.x.length === 0) return null
@@ -310,8 +463,11 @@ const GoalRow = ({
conversions: t('goals.conversions'),
sessions: t('project.sessions'),
},
+ t,
+ i18n.language,
+ stats,
)
- }, [chartData, timeBucket, timeFormat, t])
+ }, [chartData, timeBucket, timeFormat, t, i18n.language, stats])
return (
<>
@@ -457,7 +613,60 @@ const GoalRow = ({
{/* Expanded chart section */}
{isExpanded ? (
- <div className='border-t border-gray-200 px-4 py-4 sm:px-6 dark:border-slate-700'>
+ <div className='space-y-4 border-t border-gray-200 px-4 py-4 sm:px-6 dark:border-slate-700'>
+ {stats?.timeToConvert ? (
+ <div className='flex flex-wrap gap-x-10 gap-y-4 border-b border-gray-200 pb-4 dark:border-slate-800'>
+ {TIME_TO_CONVERT_METRICS.map(
+ ({ labelKey, tooltipKey, getValue }) => {
+ const metric = getValue(stats)
+ const hasTiming = isDurationValue(metric?.median)
+
+ return (
+ <div key={labelKey} className='min-w-44'>
+ <Text
+ as='p'
+ size='4xl'
+ weight='bold'
+ className='leading-none whitespace-nowrap'
+ >
+ {formatDuration(metric?.median)}
+ </Text>
+ <div className='mt-1 flex items-center gap-1.5'>
+ <Text as='p' size='sm' weight='semibold'>
+ {t(labelKey)}
+ </Text>
+ <Tooltip
+ ariaLabel={t(labelKey)}
+ text={t(tooltipKey)}
+ tooltipNode={
+ <span className='inline-flex size-4 items-center justify-center rounded-full text-gray-400 transition-colors hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300'>
+ <QuestionIcon className='size-3.5' />
+ </span>
+ }
+ contentClassName='max-w-72'
+ />
+ </div>
+ <Text
+ as='p'
+ size='xs'
+ colour='secondary'
+ className='mt-0.5'
+ >
+ {hasTiming
+ ? t('goals.avgP75', {
+ avg: formatDuration(metric?.average),
+ p75: formatDuration(metric?.p75),
+ })
+ : stats.conversions > 0
+ ? t('goals.timeToConvertInsufficient')
+ : t('goals.timeToConvertNoConversions')}
+ </Text>
+ </div>
+ )
+ },
+ )}
+ </div>
+ ) : null}
{chartLoading ? (
<div className='flex h-[200px] items-center justify-center'>
<Spin className='size-8' />
@@ -496,6 +705,7 @@ const GoalRow = ({
}
interface GoalsViewProps {
+ tnMapping: Record<string, string>
period: string
from?: string
to?: string
@@ -533,6 +743,7 @@ interface GoalsViewInnerProps extends GoalsViewProps {
}
const GoalsViewInner = ({
+ tnMapping,
period,
from = '',
to = '',
@@ -542,7 +753,7 @@ const GoalsViewInner = ({
const { id } = useCurrentProject()
const revalidator = useRevalidator()
const { goalsRefreshTrigger } = useRefreshTriggers()
- const { timeBucket, timeFormat } = useViewProjectContext()
+ const { timeBucket, timeFormat, filters } = useViewProjectContext()
const { t } = useTranslation()
const fetcher = useFetcher<ProjectViewActionData>()
@@ -561,6 +772,7 @@ const GoalsViewInner = ({
const [error, setError] = useState<string | null>(null)
const [filterQuery, setFilterQuery] = useState('')
const [debouncedSearch, setDebouncedSearch] = useState('')
+ const filtersKey = useMemo(() => JSON.stringify(filters), [filters])
// Expanded goal state
const [expandedGoalId, setExpandedGoalId] = useState<string | null>(null)
@@ -642,7 +854,10 @@ const GoalsViewInner = ({
) {
if (isMountedRef.current) {
if (fetcher.data.success && fetcher.data.data) {
- const result = fetcher.data.data as { results: Goal[]; total: number }
+ const result = fetcher.data.data as {
+ results: Goal[]
+ total: number
+ }
setGoals(result.results)
setTotal(result.total)
setError(null)
@@ -665,6 +880,7 @@ const GoalsViewInner = ({
from,
to,
timezone,
+ filters,
})
if (isMountedRef.current) {
setGoalStats((prev) => ({ ...prev, [goalId]: stats }))
@@ -693,6 +909,7 @@ const GoalsViewInner = ({
to,
timeBucket,
timezone,
+ filters,
})
if (isMountedRef.current && result) {
setGoalChartData((prev) => ({ ...prev, [goalId]: result.chart }))
@@ -740,7 +957,7 @@ const GoalsViewInner = ({
loadGoalStats(goal.id)
})
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [goals, period, from, to, timezone])
+ }, [goals, period, from, to, timezone, filtersKey])
// Reload chart data when period changes for expanded goal
useEffect(() => {
@@ -750,7 +967,7 @@ const GoalsViewInner = ({
loadGoalChartData(expandedGoalId, !hasExistingData)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [period, from, to, timezone, timeBucket])
+ }, [period, from, to, timezone, timeBucket, filtersKey])
// Refresh goals data when refresh button is clicked
useEffect(() => {
@@ -767,7 +984,9 @@ const GoalsViewInner = ({
}
// Clear cached chart data for non-expanded goals, silently refresh expanded goal
if (expandedGoalId) {
- setGoalChartData((prev) => ({ [expandedGoalId]: prev[expandedGoalId] }))
+ setGoalChartData((prev) => ({
+ [expandedGoalId]: prev[expandedGoalId],
+ }))
loadGoalChartData(expandedGoalId, false)
} else {
setGoalChartData({})
@@ -850,8 +1069,12 @@ const GoalsViewInner = ({
return (
<>
- <DashboardHeader showLiveVisitors />
+ <DashboardHeader
+ showLiveVisitors
+ rightContent={<ProjectViewHeaderActions tnMapping={tnMapping} />}
+ />
<div>
+ <Filters className='mb-3' tnMapping={tnMapping} />
{isLoading && !_isEmpty(goals) ? <LoadingBar /> : null}
{_isEmpty(goals) && !filterQuery ? (
<div className='mx-auto w-full max-w-2xl py-16 text-center'>
@@ -944,6 +1167,7 @@ const GoalsViewInner = ({
onSuccess={handleModalSuccess}
projectId={id}
goalId={editingGoalId}
+ tnMapping={tnMapping}
/>
</div>
</>
diff --git a/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx b/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx
index 98c345dc6..7ff05dcf3 100644
--- a/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx
+++ b/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx
@@ -15,6 +15,7 @@ import {
} from '~/ui/Drawer'
import Loader from '~/ui/Loader'
import Spin from '~/ui/icons/Spin'
+import { Switch } from '~/ui/Switch'
import { Session } from '../Sessions/Sessions'
@@ -68,6 +69,9 @@ interface SessionsDrawerProps {
period?: string
funnelId?: string
funnelStep?: number
+ dropoff?: boolean
+ showDropoffToggle?: boolean
+ onDropoffChange?: (checked: boolean) => void
totalCount?: number
}
@@ -84,6 +88,9 @@ export const SessionsDrawer = ({
period = 'custom',
funnelId,
funnelStep,
+ dropoff,
+ showDropoffToggle,
+ onDropoffChange,
totalCount,
}: SessionsDrawerProps) => {
const { t } = useTranslation('common')
@@ -120,6 +127,8 @@ export const SessionsDrawer = ({
timezone,
funnelId,
step: funnelStep,
+ filters: stableFilters,
+ dropoff,
take: SESSIONS_TAKE,
skip: currentSkip,
},
@@ -176,6 +185,7 @@ export const SessionsDrawer = ({
isFunnelMode,
funnelId,
funnelStep,
+ dropoff,
stableFilters,
t,
],
@@ -266,6 +276,14 @@ export const SessionsDrawer = ({
<div className='min-w-0'>
<DrawerTitle>{t('project.sessions')}</DrawerTitle>
<DrawerDescription>{label}</DrawerDescription>
+ {isFunnelMode && showDropoffToggle ? (
+ <Switch
+ checked={Boolean(dropoff)}
+ onChange={onDropoffChange}
+ label={t('project.dropoffSessionsOnly')}
+ className='mt-3'
+ />
+ ) : null}
</div>
<div className='ml-3 flex shrink-0 items-center gap-2'>
{!initialLoading &&
diff --git a/web/app/routes/api.analytics.ts b/web/app/routes/api.analytics.ts
index c47b17605..7d16ee1b3 100644
--- a/web/app/routes/api.analytics.ts
+++ b/web/app/routes/api.analytics.ts
@@ -158,6 +158,7 @@ interface ProxyRequest {
query?: string
funnelId?: string
step?: number
+ dropoff?: boolean
}
}
@@ -218,6 +219,8 @@ export async function action({ request }: ActionFunctionArgs) {
take: params.take,
skip: params.skip,
password: analyticsParams.password,
+ filters: params.filters || [],
+ dropoff: params.dropoff,
})
return data<ProxyResponse<FunnelSessionsResponse>>({
data: result.data,
@@ -309,6 +312,7 @@ export async function action({ request }: ActionFunctionArgs) {
formatDateForBackend(params.from) || '',
formatDateForBackend(params.to) || '',
params.timezone,
+ params.filters || [],
)
return data<ProxyResponse<GoalStats>>({
data: result.data,
@@ -335,6 +339,7 @@ export async function action({ request }: ActionFunctionArgs) {
formatDateForBackend(params.to) || '',
params.timeBucket || 'day',
params.timezone,
+ params.filters || [],
)
return data<ProxyResponse<{ chart: GoalChartData }>>({
data: result.data,
diff --git a/web/app/routes/projects.$id.tsx b/web/app/routes/projects.$id.tsx
index c3a1348aa..0a80bde55 100644
--- a/web/app/routes/projects.$id.tsx
+++ b/web/app/routes/projects.$id.tsx
@@ -587,6 +587,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
funnelTo,
timezone,
password || undefined,
+ filters,
).then((res) => res.data)
}
}
@@ -696,10 +697,24 @@ export async function action({ request, params }: ActionFunctionArgs) {
const type = formData.get('type')?.toString() || 'pageview'
const matchType = formData.get('matchType')?.toString() || 'exact'
const value = formData.get('value')?.toString() || ''
+ const metadataFilters = JSON.parse(
+ formData.get('metadataFilters')?.toString() || '[]',
+ )
+ const conditions = JSON.parse(
+ formData.get('conditions')?.toString() || 'null',
+ )
const result = await serverFetch(request, 'goal', {
method: 'POST',
- body: { pid: projectId, name, type, matchType, value },
+ body: {
+ pid: projectId,
+ name,
+ type,
+ matchType,
+ value,
+ metadataFilters,
+ conditions,
+ },
})
if (result.error) {
@@ -721,10 +736,16 @@ export async function action({ request, params }: ActionFunctionArgs) {
const type = formData.get('type')?.toString()
const matchType = formData.get('matchType')?.toString()
const value = formData.get('value')?.toString()
+ const metadataFilters = JSON.parse(
+ formData.get('metadataFilters')?.toString() || '[]',
+ )
+ const conditions = JSON.parse(
+ formData.get('conditions')?.toString() || 'null',
+ )
const result = await serverFetch(request, `goal/${goalId}`, {
method: 'PUT',
- body: { name, type, matchType, value },
+ body: { name, type, matchType, value, metadataFilters, conditions },
})
if (result.error) {
@@ -1620,11 +1641,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
const fromDate = formData.get('from')?.toString() || ''
const toDate = formData.get('to')?.toString() || ''
const tz = formData.get('timezone')?.toString() || ''
+ const filters = formData.get('filters')?.toString() || '[]'
const params = new URLSearchParams({ period })
if (fromDate) params.append('from', fromDate)
if (toDate) params.append('to', toDate)
if (tz) params.append('timezone', tz)
+ params.append('filters', filters)
const result = await serverFetch(
request,
@@ -2050,11 +2073,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
const fromDate = formData.get('from')?.toString() || ''
const toDate = formData.get('to')?.toString() || ''
const tz = formData.get('timezone')?.toString() || ''
+ const filters = formData.get('filters')?.toString() || '[]'
const params = new URLSearchParams({ period })
if (fromDate) params.append('from', fromDate)
if (toDate) params.append('to', toDate)
if (tz) params.append('timezone', tz)
+ params.append('filters', filters)
const result = await serverFetch(
request,
@@ -2084,11 +2109,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
const toDate = formData.get('to')?.toString() || ''
const timeBucket = formData.get('timeBucket')?.toString() || 'day'
const tz = formData.get('timezone')?.toString() || ''
+ const filters = formData.get('filters')?.toString() || '[]'
const params = new URLSearchParams({ period, timeBucket })
if (fromDate) params.append('from', fromDate)
if (toDate) params.append('to', toDate)
if (tz) params.append('timezone', tz)
+ params.append('filters', filters)
const result = await serverFetch(
request,
@@ -2143,6 +2170,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const toDate = formData.get('to')?.toString() || ''
const tz = formData.get('timezone')?.toString() || ''
const funnelId = formData.get('funnelId')?.toString() || ''
+ const filters = formData.get('filters')?.toString() || '[]'
const password = getPassword()
const params = new URLSearchParams({ pid: projectId || '' })
@@ -2151,6 +2179,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (toDate) params.append('to', toDate)
if (tz) params.append('timezone', tz)
if (funnelId) params.append('funnelId', funnelId)
+ params.append('filters', filters)
const result = await serverFetch(
request,
diff --git a/web/app/ui/FilterValueInput.tsx b/web/app/ui/FilterValueInput.tsx
index 19aecaae3..567f11398 100644
--- a/web/app/ui/FilterValueInput.tsx
+++ b/web/app/ui/FilterValueInput.tsx
@@ -80,6 +80,11 @@ export const filterCategoryIcons: Record<string, ReactNode> = {
og: <BuildingIcon className='size-4' />,
ut: <CpuIcon className='size-4' />,
ctp: <LinkIcon className='size-4' />,
+ ev: <RadioIcon className='size-4' />,
+ 'ev:key': <TagIcon className='size-4' />,
+ 'ev:value': <TagIcon className='size-4' />,
+ 'tag:key': <TagIcon className='size-4' />,
+ 'tag:value': <TagIcon className='size-4' />,
}
const deviceIconMapping: Record<string, ReactNode> = {
@@ -274,10 +279,18 @@ const FilterValueInput = ({
}
}
- if (filterCategoryIcons[column]) {
+ const baseColumn = column.startsWith('ev:key:')
+ ? 'ev:key'
+ : column.startsWith('tag:key:')
+ ? 'tag:key'
+ : column
+ const categoryIcon =
+ filterCategoryIcons[column] || filterCategoryIcons[baseColumn]
+
+ if (categoryIcon) {
return (
<span className='shrink-0 text-gray-500 dark:text-gray-400'>
- {filterCategoryIcons[column]}
+ {categoryIcon}
</span>
)
}
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index ddcf7fb0c..926d5a68a 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -1328,6 +1328,18 @@
"typePageviewDesc": "Track visits to specific pages or sections of your website.",
"typeCustomEventDesc": "Track specific custom events triggered on your website.",
"matchType": "Match type",
+ "definitionMode": "Definition mode",
+ "simpleGoal": "Simple goal",
+ "multiConditionGoal": "Multi-condition goal",
+ "matchConditionsWith": "Match conditions with",
+ "conditionsSummary": "{{count}} conditions ({{relation}})",
+ "fromSessionStart": "From session start",
+ "fromFirstPage": "From first page",
+ "fromSessionStartTooltip": "Median time from the start of the visitor's session to the goal conversion. Avg and p75 use the same conversion timings.",
+ "fromFirstPageTooltip": "Median time from the first pageview in the session to the goal conversion. Avg and p75 use the same conversion timings.",
+ "timeToConvertNoConversions": "Available after the first conversion",
+ "timeToConvertInsufficient": "Not enough timing data",
+ "avgP75": "Avg {{avg}} · p75 {{p75}}",
"pagePath": "Page path",
"eventName": "Event name",
"metadataFilters": "Metadata filters",
@@ -1786,6 +1798,7 @@
"showAll": "Show all views",
"trendlineUnique": "Sessions trendline",
"backToFunnels": "Back to funnels list",
+ "dropoffSessionsOnly": "Drop-offs only",
"backToSessions": "Back to sessions list",
"backToUsers": "Back to users list",
"allUsers": "All",