π 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Rework journeys
Blue Mouse78e5a872899c
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.tsindex c107994c5..639aab9ad 100644--- a/backend/apps/cloud/src/analytics/analytics.controller.ts+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts@@ -53,6 +53,8 @@ import { GetDataDto, ChartRenderMode, TimeBucketType } from './dto/getData.dto'import { GetCustomEventMetadata } from './dto/get-custom-event-meta.dto'import { GetPagePropertyMetaDto } from './dto/get-page-property-meta.dto'import { GetUserFlowDto } from './dto/getUserFlow.dto'+import { GetJourneysDto } from './dto/get-journeys.dto'+import { GetJourneySessionsDto } from './dto/get-journey-sessions.dto'import { GetFunnelsDto } from './dto/getFunnels.dto'import { GetFunnelSessionsDto } from './dto/get-funnel-sessions.dto'import { AppLoggerService } from '../logger/logger.service'@@ -1069,6 +1071,147 @@ export class AnalyticsController {return { ...flow, appliedFilters }}+ @Get('journeys')+ @Auth(true, true)+ async getJourneys(+ @Query() data: GetJourneysDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ const { pid, period, from, to, timezone = DEFAULT_TIMEZONE, filters } = data++ await this.analyticsService.checkProjectAccess(+ pid,+ uid,+ headers['x-password'],+ )++ await this.analyticsService.checkBillingAccess(pid)++ const steps = this.analyticsService.getSafeNumber(data.steps, 3)+ const journeys = this.analyticsService.getSafeNumber(data.journeys, 20)++ this.logger.log(+ `pid: ${pid}, period: ${period}, steps: ${steps}, journeys: ${journeys}`,+ 'GET /analytics/journeys',+ )++ let diff++ if (period === 'all') {+ const res = await this.analyticsService.calculateTimeBucketForAllTime(+ pid,+ 'pageview',+ )++ diff = res.diff+ }++ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)+ const { groupFrom, groupTo } = this.analyticsService.getGroupFromTo(+ from,+ to,+ null,+ period,+ safeTimezone,+ diff,+ )++ const [filtersQuery, filtersParams, appliedFilters] =+ this.analyticsService.getFiltersQuery(filters, DataType.ANALYTICS, true)++ const params = { pid, groupFrom, groupTo, ...filtersParams }++ const flow = await this.analyticsService.getJourneys(+ params,+ filtersQuery,+ steps,+ journeys,+ )++ return { ...flow, appliedFilters }+ }++ @Get('journey-sessions')+ @Auth(true, true)+ async getJourneySessions(+ @Query() data: GetJourneySessionsDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ const {+ pid,+ period,+ from,+ to,+ timezone = DEFAULT_TIMEZONE,+ step,+ page,+ filters,+ } = data++ await this.analyticsService.checkProjectAccess(+ pid,+ uid,+ headers['x-password'],+ )++ await this.analyticsService.checkBillingAccess(pid)++ const take = this.analyticsService.getSafeNumber(data.take, 30)+ const skip = this.analyticsService.getSafeNumber(data.skip, 0)++ if (take > 150) {+ throw new BadRequestException(+ 'The maximum number of sessions to return is 150',+ )+ }++ this.logger.log(+ `pid: ${pid}, period: ${period}, step: ${step}, take: ${take}, skip: ${skip}`,+ 'GET /analytics/journey-sessions',+ )++ let diff++ if (period === 'all') {+ const res = await this.analyticsService.calculateTimeBucketForAllTime(+ pid,+ 'pageview',+ )++ diff = res.diff+ }++ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)+ const { groupFrom, groupTo } = this.analyticsService.getGroupFromTo(+ from,+ to,+ null,+ period,+ safeTimezone,+ diff,+ )++ const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(+ filters || '[]',+ DataType.ANALYTICS,+ )+ const params = { pid, groupFrom, groupTo, ...filtersParams }++ const sessions = await this.analyticsService.getJourneySessionsList(+ params,+ safeTimezone,+ step,+ page,+ take,+ skip,+ filtersQuery,+ )++ return { sessions, take, skip }+ }+@Get('keywords')@Auth(true, true)async getKeywords(diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.tsindex 64d386e00..23843250b 100644--- a/backend/apps/cloud/src/analytics/analytics.service.ts+++ b/backend/apps/cloud/src/analytics/analytics.service.ts@@ -97,6 +97,8 @@ import {IUserFlowNode,IUserFlowLink,IUserFlow,+ IJourney,+ IJourneys,IBuildUserFlow,IExtractChartData,IGenerateXAxis,@@ -1230,6 +1232,77 @@ export class AnalyticsService {}}+ async getJourneys(+ params: Record<string, unknown>,+ filtersQuery: string,+ steps: number,+ journeys: number,+ ): Promise<IJourneys> {+ 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 = `+ WITH session_paths AS (+ SELECT+ psid,+ arraySlice(+ arrayCompact(arrayMap(x -> x.2, arraySort(groupArray((created, pg))))),+ 1,+ {steps:UInt32}+ ) AS path+ FROM events+ WHERE+ pid = {pid:FixedString(12)}+ AND type = 'pageview'+ AND psid != 0+ AND pg IS NOT NULL+ ${sessionFiltersQuery}+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ GROUP BY psid+ )+ SELECT+ path,+ count() AS value,+ sum(count()) OVER () AS totalSessions+ FROM session_paths+ GROUP BY path+ ORDER BY value DESC+ LIMIT {journeys:UInt32}+ `++ const { data } = await clickhouse+ .query({+ query,+ query_params: { ...params, steps, journeys },+ })+ .then((res) =>+ res.json<{ path: string[]; value: string; totalSessions: string }>(),+ )++ if (_isEmpty(data)) {+ return { journeys: [], totalSessions: 0 }+ }++ const journeyList: IJourney[] = _map(data, (row) => ({+ path: row.path,+ value: Number(row.value),+ }))++ return {+ journeys: journeyList,+ totalSessions: Number(data[0].totalSessions),+ }+ }+async getPagesArray(rawPages?: string,funnelId?: string,@@ -3495,6 +3568,160 @@ export class AnalyticsService {return data}+ async getJourneySessionsList(+ params: any,+ safeTimezone: string,+ step: number,+ page: string,+ take = 30,+ skip = 0,+ filtersQuery = '',+ ): Promise<object | void> {+ 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 = `+ WITH journey_qualified AS (+ SELECT psid+ FROM (+ SELECT+ psid,+ arrayCompact(arrayMap(x -> x.2, arraySort(groupArray((created, pg))))) AS path+ FROM events+ WHERE pid = {pid:FixedString(12)}+ AND type = 'pageview'+ AND psid != 0+ AND pg IS NOT NULL+ ${sessionFiltersQuery}+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ GROUP BY psid+ )+ WHERE arrayElement(path, {step:UInt32}) = {page:String}+ ),+ distinct_sessions AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ any(cc) AS cc,+ any(os) AS os,+ any(br) AS br,+ min(toTimeZone(created, {timezone:String})) AS sessionStart,+ max(toTimeZone(created, {timezone:String})) AS lastActivity+ FROM events+ WHERE pid = {pid:FixedString(12)}+ AND type IN ('pageview', 'custom_event')+ AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM journey_qualified)+ GROUP BY psidCasted, pid+ ),+ pageview_counts AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ count() as count+ FROM events+ WHERE pid = {pid:FixedString(12)} AND type = 'pageview' AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM journey_qualified)+ GROUP BY psidCasted, pid+ ),+ event_counts AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ count() as count+ FROM events+ WHERE pid = {pid:FixedString(12)} AND type = 'custom_event' AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM journey_qualified)+ GROUP BY psidCasted, pid+ ),+ error_counts AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ count() as count+ FROM events+ WHERE pid = {pid:FixedString(12)} AND type = 'error' AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM journey_qualified)+ GROUP BY psidCasted, pid+ ),+ session_duration_agg AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ dateDiff('second', min(firstSeen), max(lastSeen)) as avg_duration,+ argMax(profileId, lastSeen) as profileId+ FROM sessions+ WHERE pid = {pid:FixedString(12)}+ AND psid IN (SELECT psid FROM journey_qualified)+ GROUP BY psidCasted, pid+ ),+ first_session_per_profile AS (+ SELECT+ profileId,+ argMin(CAST(psid, 'String'), firstSeen) AS firstPsid+ FROM sessions FINAL+ WHERE pid = {pid:FixedString(12)}+ AND profileId IS NOT NULL+ AND profileId != ''+ GROUP BY profileId+ )+ SELECT+ dsf.psidCasted AS psid,+ dsf.cc,+ dsf.os,+ dsf.br,+ COALESCE(pc.count, 0) AS pageviews,+ COALESCE(ec.count, 0) AS customEvents,+ COALESCE(errc.count, 0) AS errors,+ dsf.sessionStart,+ dsf.lastActivity,+ if(dateDiff('second', dsf.lastActivity, now()) < ${LIVE_SESSION_THRESHOLD_SECONDS}, 1, 0) AS isLive,+ sda.avg_duration AS sdur,+ sda.profileId AS profileId,+ if(startsWith(sda.profileId, '${AnalyticsService.PROFILE_PREFIX_USER}'), 1, 0) AS isIdentified,+ if(fsp.firstPsid = dsf.psidCasted, 1, 0) AS isFirstSession+ FROM distinct_sessions dsf+ LEFT JOIN pageview_counts pc ON dsf.psidCasted = pc.psidCasted AND dsf.pid = pc.pid+ LEFT JOIN event_counts ec ON dsf.psidCasted = ec.psidCasted AND dsf.pid = ec.pid+ LEFT JOIN error_counts errc ON dsf.psidCasted = errc.psidCasted AND dsf.pid = errc.pid+ LEFT JOIN session_duration_agg sda ON dsf.psidCasted = sda.psidCasted AND dsf.pid = sda.pid+ LEFT JOIN first_session_per_profile fsp ON sda.profileId = fsp.profileId+ WHERE dsf.psidCasted IS NOT NULL+ ORDER BY dsf.sessionStart DESC+ LIMIT {take:UInt32}+ OFFSET {skip:UInt32}+ `++ const { data } = await clickhouse+ .query({+ query,+ query_params: {+ ...params,+ timezone: safeTimezone,+ step,+ page,+ take,+ skip,+ },+ })+ .then((resultSet) => resultSet.json())++ return data+ }+async getFunnelTimeToConvert(pages: string[],params: any,diff --git a/backend/apps/cloud/src/analytics/dto/get-journey-sessions.dto.ts b/backend/apps/cloud/src/analytics/dto/get-journey-sessions.dto.tsnew file mode 100644index 000000000..cea110557--- /dev/null+++ b/backend/apps/cloud/src/analytics/dto/get-journey-sessions.dto.ts@@ -0,0 +1,79 @@+import { ApiProperty } from '@nestjs/swagger'+import { Type } from 'class-transformer'+import {+ IsInt,+ IsNotEmpty,+ IsOptional,+ IsString,+ Matches,+ Max,+ Min,+} from 'class-validator'++import { PID_REGEX } from '../../common/constants'+import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'+import { ValidatePeriod } from '../decorators/validate-period.decorator'++export class GetJourneySessionsDto {+ @ApiProperty({+ example: 'aUn1quEid-3',+ required: true,+ description: 'The project ID',+ })+ @IsNotEmpty()+ @Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })+ pid: string++ @ApiProperty({ required: false })+ @IsOptional()+ @ValidatePeriod()+ period?: string++ @ApiProperty({ required: false })+ from: string++ @ApiProperty({ required: false })+ to: string++ @ApiProperty({+ description: 'Timezone to display data in',+ default: DEFAULT_TIMEZONE,+ })+ timezone: string++ @ApiProperty({+ description: 'A stringified filters array',+ required: false,+ })+ @IsOptional()+ filters?: string++ @ApiProperty({+ description: 'Journey step the page was visited at (1-indexed)',+ })+ @Type(() => Number)+ @IsInt()+ @Min(1)+ @Max(10)+ step: number++ @ApiProperty({+ description: 'The page visited at the given journey step',+ })+ @IsNotEmpty()+ @IsString()+ page: string++ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(0)+ @Max(150)+ take?: number++ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(0)+ skip?: number+}diff --git a/backend/apps/cloud/src/analytics/dto/get-journeys.dto.ts b/backend/apps/cloud/src/analytics/dto/get-journeys.dto.tsnew file mode 100644index 000000000..176e2620d--- /dev/null+++ b/backend/apps/cloud/src/analytics/dto/get-journeys.dto.ts@@ -0,0 +1,74 @@+import { ApiProperty } from '@nestjs/swagger'+import { Type } from 'class-transformer'+import {+ IsInt,+ IsNotEmpty,+ IsOptional,+ Matches,+ Max,+ Min,+} from 'class-validator'++import { PID_REGEX } from '../../common/constants'+import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'+import { ValidatePeriod } from '../decorators/validate-period.decorator'++export class GetJourneysDto {+ @ApiProperty({+ example: 'aUn1quEid-3',+ required: true,+ description: 'The project ID',+ })+ @IsNotEmpty()+ @Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })+ pid: string++ @ApiProperty({ required: false })+ @IsOptional()+ @ValidatePeriod()+ period?: string++ @ApiProperty({ required: false })+ from: string++ @ApiProperty({ required: false })+ to: string++ @ApiProperty({+ description: 'Timezone to display data in',+ default: DEFAULT_TIMEZONE,+ })+ timezone: string++ @ApiProperty({+ description:+ 'A stringified array of properties to filter [{ column, filter, isExclusive, isContains }]',+ required: false,+ })+ @IsOptional()+ filters?: string++ @ApiProperty({+ description: 'How many pages deep each journey goes (2 - 10)',+ default: 3,+ required: false,+ })+ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(2)+ @Max(10)+ steps?: number++ @ApiProperty({+ description: 'How many of the most popular journeys to return (5 - 100)',+ default: 20,+ required: false,+ })+ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(5)+ @Max(100)+ journeys?: number+}diff --git a/backend/apps/cloud/src/analytics/interfaces/index.ts b/backend/apps/cloud/src/analytics/interfaces/index.tsindex 89dc8a18a..3d810e2f3 100644--- a/backend/apps/cloud/src/analytics/interfaces/index.ts+++ b/backend/apps/cloud/src/analytics/interfaces/index.ts@@ -103,6 +103,16 @@ export interface IUserFlow {descending: IBuildUserFlow}+export interface IJourney {+ path: string[]+ value: number+}++export interface IJourneys {+ journeys: IJourney[]+ totalSessions: number+}+export interface IExtractChartData {visits: number[]uniques: number[]diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.tsindex ca82cbaa2..5ccb88607 100644--- a/backend/apps/community/src/analytics/analytics.controller.ts+++ b/backend/apps/community/src/analytics/analytics.controller.ts@@ -48,6 +48,8 @@ import { GetVersionFiltersDto } from './dto/get-version-filters.dto'import { GetCustomEventMetadata } from './dto/get-custom-event-meta.dto'import { GetPagePropertyMetaDto } from './dto/get-page-property-meta.dto'import { GetUserFlowDto } from './dto/getUserFlow.dto'+import { GetJourneysDto } from './dto/get-journeys.dto'+import { GetJourneySessionsDto } from './dto/get-journey-sessions.dto'import { GetFunnelsDto } from './dto/getFunnels.dto'import { GetFunnelSessionsDto } from './dto/get-funnel-sessions.dto'import { AppLoggerService } from '../logger/logger.service'@@ -933,6 +935,143 @@ export class AnalyticsController {return { ...flow, appliedFilters: parsedFilters }}+ @Get('journeys')+ @Auth(true, true)+ async getJourneys(+ @Query() data: GetJourneysDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ const { pid, period, from, to, timezone = DEFAULT_TIMEZONE, filters } = data++ await this.analyticsService.checkProjectAccess(+ pid,+ uid,+ headers['x-password'],+ )++ const steps = this.analyticsService.getSafeNumber(data.steps, 3)+ const journeys = this.analyticsService.getSafeNumber(data.journeys, 20)++ this.logger.log(+ `pid: ${pid}, period: ${period}, steps: ${steps}, journeys: ${journeys}`,+ 'GET /analytics/journeys',+ )++ let diff++ if (period === 'all') {+ const res = await this.analyticsService.calculateTimeBucketForAllTime(+ pid,+ 'pageview',+ )++ diff = res.diff+ }++ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)+ const { groupFrom, groupTo } = this.analyticsService.getGroupFromTo(+ from,+ to,+ null,+ period,+ safeTimezone,+ diff,+ )++ const [filtersQuery, filtersParams, parsedFilters] =+ this.analyticsService.getFiltersQuery(filters, DataType.ANALYTICS, true)++ const params = { pid, groupFrom, groupTo, ...filtersParams }++ const flow = await this.analyticsService.getJourneys(+ params,+ filtersQuery,+ steps,+ journeys,+ )++ return { ...flow, appliedFilters: parsedFilters }+ }++ @Get('journey-sessions')+ @Auth(true, true)+ async getJourneySessions(+ @Query() data: GetJourneySessionsDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ const {+ pid,+ period,+ from,+ to,+ timezone = DEFAULT_TIMEZONE,+ step,+ page,+ filters,+ } = data++ await this.analyticsService.checkProjectAccess(+ pid,+ uid,+ headers['x-password'],+ )++ const take = this.analyticsService.getSafeNumber(data.take, 30)+ const skip = this.analyticsService.getSafeNumber(data.skip, 0)++ if (take > 150) {+ throw new BadRequestException(+ 'The maximum number of sessions to return is 150',+ )+ }++ this.logger.log(+ `pid: ${pid}, period: ${period}, step: ${step}, take: ${take}, skip: ${skip}`,+ 'GET /analytics/journey-sessions',+ )++ let diff++ if (period === 'all') {+ const res = await this.analyticsService.calculateTimeBucketForAllTime(+ pid,+ 'pageview',+ )++ diff = res.diff+ }++ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)+ const { groupFrom, groupTo } = this.analyticsService.getGroupFromTo(+ from,+ to,+ null,+ period,+ safeTimezone,+ diff,+ )++ const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(+ filters || '[]',+ DataType.ANALYTICS,+ )+ const params = { pid, groupFrom, groupTo, ...filtersParams }++ const sessions = await this.analyticsService.getJourneySessionsList(+ params,+ safeTimezone,+ step,+ page,+ take,+ skip,+ filtersQuery,+ )++ return { sessions, take, skip }+ }+@Get('birdseye')@Auth(true, true)// returns overall short statistics per projectdiff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.tsindex 6d4b2ddaa..ddec3d0eb 100644--- a/backend/apps/community/src/analytics/analytics.service.ts+++ b/backend/apps/community/src/analytics/analytics.service.ts@@ -83,6 +83,8 @@ import {IUserFlowNode,IUserFlowLink,IUserFlow,+ IJourney,+ IJourneys,IBuildUserFlow,IExtractChartData,IGenerateXAxis,@@ -1033,6 +1035,77 @@ export class AnalyticsService {}}+ async getJourneys(+ params: Record<string, unknown>,+ filtersQuery: string,+ steps: number,+ journeys: number,+ ): Promise<IJourneys> {+ 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 = `+ WITH session_paths AS (+ SELECT+ psid,+ arraySlice(+ arrayCompact(arrayMap(x -> x.2, arraySort(groupArray((created, pg))))),+ 1,+ {steps:UInt32}+ ) AS path+ FROM events+ WHERE+ pid = {pid:FixedString(12)}+ AND type = 'pageview'+ AND psid != 0+ AND pg IS NOT NULL+ ${sessionFiltersQuery}+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ GROUP BY psid+ )+ SELECT+ path,+ count() AS value,+ sum(count()) OVER () AS totalSessions+ FROM session_paths+ GROUP BY path+ ORDER BY value DESC+ LIMIT {journeys:UInt32}+ `++ const { data } = await clickhouse+ .query({+ query,+ query_params: { ...params, steps, journeys },+ })+ .then((res) =>+ res.json<{ path: string[]; value: string; totalSessions: string }>(),+ )++ if (_isEmpty(data)) {+ return { journeys: [], totalSessions: 0 }+ }++ const journeyList: IJourney[] = _map(data, (row) => ({+ path: row.path,+ value: Number(row.value),+ }))++ return {+ journeys: journeyList,+ totalSessions: Number(data[0].totalSessions),+ }+ }+async getPagesArray(rawPages?: string,funnelId?: string,@@ -2316,6 +2389,160 @@ export class AnalyticsService {return data}+ async getJourneySessionsList(+ params: any,+ safeTimezone: string,+ step: number,+ page: string,+ take = 30,+ skip = 0,+ filtersQuery = '',+ ): Promise<object | void> {+ 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 = `+ WITH journey_qualified AS (+ SELECT psid+ FROM (+ SELECT+ psid,+ arrayCompact(arrayMap(x -> x.2, arraySort(groupArray((created, pg))))) AS path+ FROM events+ WHERE pid = {pid:FixedString(12)}+ AND type = 'pageview'+ AND psid != 0+ AND pg IS NOT NULL+ ${sessionFiltersQuery}+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ GROUP BY psid+ )+ WHERE arrayElement(path, {step:UInt32}) = {page:String}+ ),+ distinct_sessions AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ any(cc) AS cc,+ any(os) AS os,+ any(br) AS br,+ min(toTimeZone(created, {timezone:String})) AS sessionStart,+ max(toTimeZone(created, {timezone:String})) AS lastActivity+ FROM events+ WHERE pid = {pid:FixedString(12)}+ AND type IN ('pageview', 'custom_event')+ AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM journey_qualified)+ GROUP BY psidCasted, pid+ ),+ pageview_counts AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ count() as count+ FROM events+ WHERE pid = {pid:FixedString(12)} AND type = 'pageview' AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM journey_qualified)+ GROUP BY psidCasted, pid+ ),+ event_counts AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ count() as count+ FROM events+ WHERE pid = {pid:FixedString(12)} AND type = 'custom_event' AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM journey_qualified)+ GROUP BY psidCasted, pid+ ),+ error_counts AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ count() as count+ FROM events+ WHERE pid = {pid:FixedString(12)} AND type = 'error' AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM journey_qualified)+ GROUP BY psidCasted, pid+ ),+ session_duration_agg AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ dateDiff('second', min(firstSeen), max(lastSeen)) as avg_duration,+ argMax(profileId, lastSeen) as profileId+ FROM sessions+ WHERE pid = {pid:FixedString(12)}+ AND psid IN (SELECT psid FROM journey_qualified)+ GROUP BY psidCasted, pid+ ),+ first_session_per_profile AS (+ SELECT+ profileId,+ argMin(CAST(psid, 'String'), firstSeen) AS firstPsid+ FROM sessions FINAL+ WHERE pid = {pid:FixedString(12)}+ AND profileId IS NOT NULL+ AND profileId != ''+ GROUP BY profileId+ )+ SELECT+ dsf.psidCasted AS psid,+ dsf.cc,+ dsf.os,+ dsf.br,+ COALESCE(pc.count, 0) AS pageviews,+ COALESCE(ec.count, 0) AS customEvents,+ COALESCE(errc.count, 0) AS errors,+ dsf.sessionStart,+ dsf.lastActivity,+ if(dateDiff('second', toTimeZone(dsf.lastActivity, 'UTC'), toTimeZone(now(), 'UTC')) < ${LIVE_SESSION_THRESHOLD_SECONDS}, 1, 0) AS isLive,+ sda.avg_duration AS sdur,+ sda.profileId AS profileId,+ if(startsWith(sda.profileId, '${AnalyticsService.PROFILE_PREFIX_USER}'), 1, 0) AS isIdentified,+ if(fsp.firstPsid = dsf.psidCasted, 1, 0) AS isFirstSession+ FROM distinct_sessions dsf+ LEFT JOIN pageview_counts pc ON dsf.psidCasted = pc.psidCasted AND dsf.pid = pc.pid+ LEFT JOIN event_counts ec ON dsf.psidCasted = ec.psidCasted AND dsf.pid = ec.pid+ LEFT JOIN error_counts errc ON dsf.psidCasted = errc.psidCasted AND dsf.pid = errc.pid+ LEFT JOIN session_duration_agg sda ON dsf.psidCasted = sda.psidCasted AND dsf.pid = sda.pid+ LEFT JOIN first_session_per_profile fsp ON sda.profileId = fsp.profileId+ WHERE dsf.psidCasted IS NOT NULL+ ORDER BY dsf.sessionStart DESC+ LIMIT {take:UInt32}+ OFFSET {skip:UInt32}+ `++ const { data } = await clickhouse+ .query({+ query,+ query_params: {+ ...params,+ timezone: safeTimezone,+ step,+ page,+ take,+ skip,+ },+ })+ .then((resultSet) => resultSet.json())++ return data+ }+async getFunnelTimeToConvert(pages: string[],params: any,diff --git a/backend/apps/community/src/analytics/dto/get-journey-sessions.dto.ts b/backend/apps/community/src/analytics/dto/get-journey-sessions.dto.tsnew file mode 100644index 000000000..cea110557--- /dev/null+++ b/backend/apps/community/src/analytics/dto/get-journey-sessions.dto.ts@@ -0,0 +1,79 @@+import { ApiProperty } from '@nestjs/swagger'+import { Type } from 'class-transformer'+import {+ IsInt,+ IsNotEmpty,+ IsOptional,+ IsString,+ Matches,+ Max,+ Min,+} from 'class-validator'++import { PID_REGEX } from '../../common/constants'+import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'+import { ValidatePeriod } from '../decorators/validate-period.decorator'++export class GetJourneySessionsDto {+ @ApiProperty({+ example: 'aUn1quEid-3',+ required: true,+ description: 'The project ID',+ })+ @IsNotEmpty()+ @Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })+ pid: string++ @ApiProperty({ required: false })+ @IsOptional()+ @ValidatePeriod()+ period?: string++ @ApiProperty({ required: false })+ from: string++ @ApiProperty({ required: false })+ to: string++ @ApiProperty({+ description: 'Timezone to display data in',+ default: DEFAULT_TIMEZONE,+ })+ timezone: string++ @ApiProperty({+ description: 'A stringified filters array',+ required: false,+ })+ @IsOptional()+ filters?: string++ @ApiProperty({+ description: 'Journey step the page was visited at (1-indexed)',+ })+ @Type(() => Number)+ @IsInt()+ @Min(1)+ @Max(10)+ step: number++ @ApiProperty({+ description: 'The page visited at the given journey step',+ })+ @IsNotEmpty()+ @IsString()+ page: string++ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(0)+ @Max(150)+ take?: number++ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(0)+ skip?: number+}diff --git a/backend/apps/community/src/analytics/dto/get-journeys.dto.ts b/backend/apps/community/src/analytics/dto/get-journeys.dto.tsnew file mode 100644index 000000000..176e2620d--- /dev/null+++ b/backend/apps/community/src/analytics/dto/get-journeys.dto.ts@@ -0,0 +1,74 @@+import { ApiProperty } from '@nestjs/swagger'+import { Type } from 'class-transformer'+import {+ IsInt,+ IsNotEmpty,+ IsOptional,+ Matches,+ Max,+ Min,+} from 'class-validator'++import { PID_REGEX } from '../../common/constants'+import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'+import { ValidatePeriod } from '../decorators/validate-period.decorator'++export class GetJourneysDto {+ @ApiProperty({+ example: 'aUn1quEid-3',+ required: true,+ description: 'The project ID',+ })+ @IsNotEmpty()+ @Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })+ pid: string++ @ApiProperty({ required: false })+ @IsOptional()+ @ValidatePeriod()+ period?: string++ @ApiProperty({ required: false })+ from: string++ @ApiProperty({ required: false })+ to: string++ @ApiProperty({+ description: 'Timezone to display data in',+ default: DEFAULT_TIMEZONE,+ })+ timezone: string++ @ApiProperty({+ description:+ 'A stringified array of properties to filter [{ column, filter, isExclusive, isContains }]',+ required: false,+ })+ @IsOptional()+ filters?: string++ @ApiProperty({+ description: 'How many pages deep each journey goes (2 - 10)',+ default: 3,+ required: false,+ })+ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(2)+ @Max(10)+ steps?: number++ @ApiProperty({+ description: 'How many of the most popular journeys to return (5 - 100)',+ default: 20,+ required: false,+ })+ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(5)+ @Max(100)+ journeys?: number+}diff --git a/backend/apps/community/src/analytics/interfaces/index.ts b/backend/apps/community/src/analytics/interfaces/index.tsindex dca60debf..b874c07d6 100644--- a/backend/apps/community/src/analytics/interfaces/index.ts+++ b/backend/apps/community/src/analytics/interfaces/index.ts@@ -95,6 +95,16 @@ export interface IUserFlow {descending: IBuildUserFlow}+export interface IJourney {+ path: string[]+ value: number+}++export interface IJourneys {+ journeys: IJourney[]+ totalSessions: number+}+export interface IExtractChartData {visits: number[]uniques: number[]diff --git a/docs/content/docs/analytics-dashboard/journeys.mdx b/docs/content/docs/analytics-dashboard/journeys.mdxnew file mode 100644index 000000000..b8c1f4370--- /dev/null+++ b/docs/content/docs/analytics-dashboard/journeys.mdx@@ -0,0 +1,47 @@+---+id: journeys+title: Journeys+sidebar_label: Journeys+---++Journeys (also known as user flow) visualise the paths visitors take through your website: which page they land on, where they go next, and where they drop off. Each journey is the ordered sequence of pages a visitor viewed within a single session.++<img alt="Journeys view" src="/docs/img/analytics-dashboard/journeys-view.png" />++## Overview++The Journeys tab shows a Sankey diagram of the most popular navigation paths for the selected time period. Each column is a step in the visitor's session: the first column shows the pages visitors landed on, the second column shows the pages they viewed next, and so on. The thickness of a band is proportional to how many sessions travelled that way.++Two sliders let you control how much detail is shown:++- **Steps**: how many pages deep each journey goes (2 to 10). More steps show longer navigation chains; fewer steps keep the diagram compact.+- **Journeys**: how many of the most popular journeys are included (5 to 100). Increasing it reveals rarer paths; decreasing it focuses the diagram on the dominant flows.++Consecutive views of the same page (e.g. reloads) are collapsed, so a journey shows the sequence of distinct pages. Journeys also respect any filters you have applied to the dashboard, so you can look at the paths of, say, visitors from a specific country or referrer.++## Reading the diagram++Hover over a node (page) to see the details for it:++- The page path and which step of the journey it represents.+- How many sessions viewed this page at this step.+- What share of all sessions in the period that is.++Hovering a band between two pages shows how many sessions navigated from one page to the other, and what share of the source page's sessions continued that way.++<img alt="Journey node details" src="/docs/img/analytics-dashboard/journeys-tooltip.png" />++## Inspecting sessions++Click any node to open a sessions drawer listing the individual sessions that viewed that page at that step of their journey. From there you can open any session to see its full pageflow, custom events and details β the same session view used across the rest of the dashboard.++<img+ alt="Journey sessions drawer"+ src="/docs/img/analytics-dashboard/journeys-sessions-drawer.png"+/>++<Callout type="info" title="Journeys vs Funnels">++Journeys are exploratory: they show you every path visitors actually take, with no setup. If you already know the sequence you care about (e.g. `/pricing` β `/signup` β `/dashboard`), create a [funnel](/analytics-dashboard/funnels) to measure conversion and drop-off for that exact flow.++</Callout>diff --git a/docs/content/docs/analytics-dashboard/meta.json b/docs/content/docs/analytics-dashboard/meta.jsonindex 771d45e25..33a9ef014 100644--- a/docs/content/docs/analytics-dashboard/meta.json+++ b/docs/content/docs/analytics-dashboard/meta.json@@ -5,6 +5,7 @@"traffic","seo","performance",+ "journeys","funnels","alerts","profiles-and-sessions",diff --git a/docs/content/docs/analytics-dashboard/traffic.mdx b/docs/content/docs/analytics-dashboard/traffic.mdxindex 7768eec3d..e51138493 100644--- a/docs/content/docs/analytics-dashboard/traffic.mdx+++ b/docs/content/docs/analytics-dashboard/traffic.mdx@@ -60,9 +60,12 @@ See which parts of your website are most popular:- **Page Paths**: The specific URLs visited.- **Entry Pages**: The first page visitors land on.- **Exit Pages**: The last page visitors view before leaving.-- **User Flow**: Visualize the path users take through your site.- **Host**: Useful for cross-domain tracking, showing which specific domain or subdomain the traffic originated from.+:::info+Looking for the paths visitors take through your site? Check out the dedicated **[Journeys](/analytics-dashboard/journeys)** tab.+:::+### Traffic SourcesIdentify how visitors find your website:diff --git a/docs/content/docs/api/stats.mdx b/docs/content/docs/api/stats.mdxindex a5153952e..0f6cae908 100644--- a/docs/content/docs/api/stats.mdx+++ b/docs/content/docs/api/stats.mdx@@ -1257,6 +1257,70 @@ curl 'https://api.swetrix.com/v1/log/user-flow?pid=YOUR_PROJECT_ID&period=7d'\The parameters are similar to the [`/log` endpoint](#get-v1log).+### GET /v1/log/journeys++Returns the most popular journeys β the ordered sequences of pages visitors viewed within a session. This is the data behind the Journeys tab of the dashboard.++```bash+curl 'https://api.swetrix.com/v1/log/journeys?pid=YOUR_PROJECT_ID&period=7d&steps=3&journeys=20'\+ -H "X-Api-Key: ${SWETRIX_API_KEY}"+```++Each journey in the response is a `path` (an array of page paths) together with `value` β the number of sessions that followed it. The response also includes `totalSessions`, the total number of sessions in the period.++#### Parameters++In addition to the parameters of the [`/log` endpoint](#get-v1log):++<hr />++**steps** (optional, default: `3`)++How many pages deep each journey goes (2 - 10).++<hr />++**journeys** (optional, default: `20`)++How many of the most popular journeys to return (5 - 100).++### GET /v1/log/journey-sessions++Returns the sessions that viewed a given page at a given journey step.++```bash+curl 'https://api.swetrix.com/v1/log/journey-sessions?pid=YOUR_PROJECT_ID&period=7d&step=2&page=%2Fpricing'\+ -H "X-Api-Key: ${SWETRIX_API_KEY}"+```++#### Parameters++In addition to the parameters of the [`/log` endpoint](#get-v1log):++<hr />++**step** (required)++The journey step the page was visited at (1-indexed).++<hr />++**page** (required)++The page path visited at the given step.++<hr />++**take** (optional, default: `30`, max: `150`)++The number of sessions to return per page.++<hr />++**skip** (optional, default: `0`)++The number of sessions to skip (for pagination).+### GET /v1/log/chartReturns data for the main chart (visits, uniques, sessions duration, etc.) grouped by time bucket. This is useful when you only need the chart data without other aggregations.diff --git a/docs/public/img/analytics-dashboard/journeys-sessions-drawer.png b/docs/public/img/analytics-dashboard/journeys-sessions-drawer.pngnew file mode 100644index 000000000..bcb4e7a5aBinary files /dev/null and b/docs/public/img/analytics-dashboard/journeys-sessions-drawer.png differdiff --git a/docs/public/img/analytics-dashboard/journeys-tooltip.png b/docs/public/img/analytics-dashboard/journeys-tooltip.pngnew file mode 100644index 000000000..faecb304bBinary files /dev/null and b/docs/public/img/analytics-dashboard/journeys-tooltip.png differdiff --git a/docs/public/img/analytics-dashboard/journeys-view.png b/docs/public/img/analytics-dashboard/journeys-view.pngnew file mode 100644index 000000000..f54d94122Binary files /dev/null and b/docs/public/img/analytics-dashboard/journeys-view.png differdiff --git a/web/app/api/api.server.ts b/web/app/api/api.server.tsindex 32c0bab14..cfa0bdc27 100644--- a/web/app/api/api.server.ts+++ b/web/app/api/api.server.ts@@ -1144,6 +1144,56 @@ export async function getFunnelSessionsServer()}+export interface JourneySessionsResponse {+ sessions: Session[]+ take: number+ skip: number+}++export async function getJourneySessionsServer(+ request: Request,+ pid: string,+ params: {+ period: string+ from?: string+ to?: string+ timezone?: string+ step: number+ page: string+ take?: number+ skip?: number+ password?: string+ filters?: AnalyticsFilter[]+ },+): Promise<ServerFetchResult<JourneySessionsResponse>> {+ const step = Math.min(10, Math.max(1, Math.floor(Number(params.step) || 1)))+ const take = Math.min(150, Math.max(1, Math.floor(Number(params.take) || 30)))+ const skip = Math.max(0, Math.floor(Number(params.skip) || 0))++ const queryParams = new URLSearchParams()+ queryParams.append('pid', pid)+ queryParams.append('period', params.period)+ queryParams.append('step', String(step))+ queryParams.append('page', params.page)+ queryParams.append('take', String(take))+ queryParams.append('skip', String(skip))+ queryParams.append('filters', JSON.stringify(params.filters || []))+ if (params.from) queryParams.append('from', params.from)+ if (params.to) queryParams.append('to', params.to)+ if (params.timezone) queryParams.append('timezone', params.timezone)++ const headers: Record<string, string> = {}+ if (params.password) {+ headers['x-password'] = params.password+ }++ return serverFetch<JourneySessionsResponse>(+ request,+ `log/journey-sessions?${queryParams.toString()}`,+ { headers },+ )+}+export async function getGoalSessionsServer(request: Request,goalId: string,@@ -2662,49 +2712,46 @@ export async function processSSOTokenServer(}// ============================================================================-// MARK: User Flow API+// MARK: Journeys API// ============================================================================-interface UserFlowNode {- id: string- name: string- count: number-}--interface UserFlowLink {- source: string- target: string+export interface Journey {+ path: string[]value: number}-interface UserFlowData {- nodes: UserFlowNode[]- links: UserFlowLink[]-}--export interface UserFlowResponse {- ascending: UserFlowData- descending: UserFlowData+export interface JourneysResponse {+ journeys: Journey[]+ totalSessions: number+ appliedFilters?: AnalyticsFilter[]}-export async function getUserFlowServer(+export async function getJourneysServer(request: Request,pid: string,params: {- timeBucket?: stringperiod?: stringfilters?: AnalyticsFilter[]from?: stringto?: stringtimezone?: string+ steps?: number+ journeys?: numberpassword?: string} = {},-): Promise<ServerFetchResult<UserFlowResponse>> {+): Promise<ServerFetchResult<JourneysResponse>> {+ const steps = Math.min(10, Math.max(2, Math.floor(Number(params.steps) || 3)))+ const journeys = Math.min(+ 100,+ Math.max(5, Math.floor(Number(params.journeys) || 20)),+ )+const queryParams = new URLSearchParams()queryParams.append('pid', pid)- queryParams.append('timeBucket', params.timeBucket || 'hour')queryParams.append('period', params.period || '3d')queryParams.append('filters', JSON.stringify(params.filters || []))+ queryParams.append('steps', String(steps))+ queryParams.append('journeys', String(journeys))if (params.from) queryParams.append('from', params.from)if (params.to) queryParams.append('to', params.to)if (params.timezone) queryParams.append('timezone', params.timezone)@@ -2714,9 +2761,9 @@ export async function getUserFlowServer(headers['x-password'] = params.password}- return serverFetch<UserFlowResponse>(+ return serverFetch<JourneysResponse>(request,- `log/user-flow?${queryParams.toString()}`,+ `log/journeys?${queryParams.toString()}`,{headers,},diff --git a/web/app/hooks/useAnalyticsProxy.ts b/web/app/hooks/useAnalyticsProxy.tsindex 72580d098..65ad2c0e7 100644--- a/web/app/hooks/useAnalyticsProxy.ts+++ b/web/app/hooks/useAnalyticsProxy.ts@@ -29,7 +29,7 @@ import type {BotProtectionStats,BotProtectionPeriod,ProjectDataCustomEventsResponse,- UserFlowResponse,+ JourneysResponse,GSCDashboardResponse,RevenueStatus,RevenueDataResponse,@@ -1008,19 +1008,25 @@ export function useProjectDataCustomEventsProxy() {return { fetchCustomEvents }}-export function useUserFlowProxy() {- const [data, setData] = useState<UserFlowResponse | null>(null)+export function useJourneysProxy() {+ const [data, setData] = useState<JourneysResponse | null>(null)const [error, setError] = useState<string | null>(null)const [isLoading, setIsLoading] = useState(false)- const fetchUserFlow = useCallback(- async (projectId: string, params: ClientAnalyticsParams = {}) => {+ const fetchJourneys = useCallback(+ async (+ projectId: string,+ params: ClientAnalyticsParams & {+ steps?: number+ journeys?: number+ } = {},+ ) => {setIsLoading(true)setError(null)try {- const result = await postAnalytics<UserFlowResponse>({- action: 'getUserFlow',+ const result = await postAnalytics<JourneysResponse>({+ action: 'getJourneys',projectId,params,})@@ -1037,7 +1043,7 @@ export function useUserFlowProxy() {[],)- return { fetchUserFlow, data, error, isLoading }+ return { fetchJourneys, data, error, isLoading }}export function useGSCDashboardProxy() {diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.tsindex d91b3c024..eb0564a60 100644--- a/web/app/lib/constants/index.ts+++ b/web/app/lib/constants/index.ts@@ -561,6 +561,7 @@ const SELFHOSTED_PROJECT_TABS = {traffic: 'traffic',performance: 'performance',seo: 'seo',+ journeys: 'journeys',funnels: 'funnels',profiles: 'profiles',sessions: 'sessions',@@ -577,6 +578,7 @@ const PRODUCTION_PROJECT_TABS = {performance: 'performance',seo: 'seo',profiles: 'profiles',+ journeys: 'journeys',funnels: 'funnels',sessions: 'sessions',replays: 'replays',diff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsxindex bd2dea069..0e7f3952a 100644--- a/web/app/pages/Project/View/ViewProject.helpers.tsx+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx@@ -2342,7 +2342,6 @@ const typeNameMapping = (t: typeof i18next.t) => ({ut: t('project.mapping.ut'),ctp: t('project.mapping.ctp'),ev: t('project.event'),- userFlow: t('project.mapping.userFlow'),'tag:key': t('project.metamapping.tag.key'),'tag:value': t('project.metamapping.tag.value'),'ev:key': t('project.metamapping.ev.key'),diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsxindex 6e02f59c9..01a03d3a6 100644--- a/web/app/pages/Project/View/ViewProject.tsx+++ b/web/app/pages/Project/View/ViewProject.tsx@@ -19,6 +19,7 @@ import {SparkleIcon,FlaskIcon,IdentificationCardIcon,+ PathIcon,UserListIcon,MonitorPlayIcon,ToggleRightIcon,@@ -125,6 +126,7 @@ const FeatureFlagsView = lazy()const FunnelsView = lazy(() => import('../tabs/Funnels/FunnelsView'))const GoalsView = lazy(() => import('../tabs/Goals/GoalsView'))+const JourneysView = lazy(() => import('../tabs/Journeys/JourneysView'))const PerformanceView = lazy(() => import('../tabs/Performance/PerformanceView'),)@@ -202,6 +204,7 @@ interface RefreshTriggersContextType {performanceRefreshTrigger: numbertrafficRefreshTrigger: numberfunnelsRefreshTrigger: number+ journeysRefreshTrigger: numberprofilesRefreshTrigger: numberreplaysRefreshTrigger: numberseoRefreshTrigger: number@@ -271,6 +274,7 @@ const defaultRefreshTriggersContext: RefreshTriggersContextType = {performanceRefreshTrigger: 0,trafficRefreshTrigger: 0,funnelsRefreshTrigger: 0,+ journeysRefreshTrigger: 0,profilesRefreshTrigger: 0,replaysRefreshTrigger: 0,seoRefreshTrigger: 0,@@ -362,6 +366,7 @@ const ViewProjectContent = () => {const [performanceRefreshTrigger, setPerformanceRefreshTrigger] = useState(0)const [trafficRefreshTrigger, setTrafficRefreshTrigger] = useState(0)const [funnelsRefreshTrigger, setFunnelsRefreshTrigger] = useState(0)+ const [journeysRefreshTrigger, setJourneysRefreshTrigger] = useState(0)const [profilesRefreshTrigger, setProfilesRefreshTrigger] = useState(0)const [replaysRefreshTrigger, setReplaysRefreshTrigger] = useState(0)const [seoRefreshTrigger, setSeoRefreshTrigger] = useState(0)@@ -787,6 +792,11 @@ const ViewProjectContent = () => {label: t('dashboard.errors'),icon: WarningIcon,},+ {+ id: PROJECT_TABS.journeys,+ label: t('dashboard.journeys'),+ icon: PathIcon,+ },{id: PROJECT_TABS.funnels,label: t('dashboard.funnels'),@@ -924,6 +934,11 @@ const ViewProjectContent = () => {return}+ if (activeTab === PROJECT_TABS.journeys) {+ setJourneysRefreshTrigger((prev) => prev + 1)+ return+ }+if (activeTab === PROJECT_TABS.profiles) {setProfilesRefreshTrigger((prev) => prev + 1)return@@ -1319,6 +1334,7 @@ const ViewProjectContent = () => {performanceRefreshTrigger,trafficRefreshTrigger,funnelsRefreshTrigger,+ journeysRefreshTrigger,profilesRefreshTrigger,replaysRefreshTrigger,seoRefreshTrigger,@@ -1333,6 +1349,7 @@ const ViewProjectContent = () => {performanceRefreshTrigger,trafficRefreshTrigger,funnelsRefreshTrigger,+ journeysRefreshTrigger,profilesRefreshTrigger,replaysRefreshTrigger,seoRefreshTrigger,@@ -1616,6 +1633,9 @@ const ViewProjectContent = () => {{activeTab === PROJECT_TABS.funnels ? (<FunnelsView tnMapping={tnMapping} />) : null}+ {activeTab === PROJECT_TABS.journeys ? (+ <JourneysView tnMapping={tnMapping} />+ ) : null}{activeTab === PROJECT_TABS.profiles ? (<ProfilesView tnMapping={tnMapping} />) : null}diff --git a/web/app/pages/Project/View/components/ProjectSidebar.tsx b/web/app/pages/Project/View/components/ProjectSidebar.tsxindex 3f48ae512..fb726ed1c 100644--- a/web/app/pages/Project/View/components/ProjectSidebar.tsx+++ b/web/app/pages/Project/View/components/ProjectSidebar.tsx@@ -65,6 +65,7 @@ const ICON_COLORS: Record<string, string> = {traffic: 'text-blue-500',performance: 'text-amber-500',seo: 'text-green-500',+ journeys: 'text-cyan-500',funnels: 'text-teal-500',// Product Analyticsprofiles: 'text-fuchsia-500',@@ -423,6 +424,7 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({PROJECT_TABS.traffic,PROJECT_TABS.seo,PROJECT_TABS.performance,+ PROJECT_TABS.journeys,PROJECT_TABS.funnels,].filter(Boolean)diff --git a/web/app/pages/Project/tabs/Journeys/JourneysView.tsx b/web/app/pages/Project/tabs/Journeys/JourneysView.tsxnew file mode 100644index 000000000..2202e581f--- /dev/null+++ b/web/app/pages/Project/tabs/Journeys/JourneysView.tsx@@ -0,0 +1,497 @@+import { ResponsiveSankey } from '@nivo/sankey'+import { PathIcon } from '@phosphor-icons/react'+import _isEmpty from 'lodash/isEmpty'+import { useEffect, useMemo, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'++import type { JourneysResponse } from '~/api/api.server'+import { useJourneysProxy } from '~/hooks/useAnalyticsProxy'+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 TabErrorBoundary from '~/pages/Project/View/components/TabErrorBoundary'+import {+ useViewProjectContext,+ useRefreshTriggers,+} from '~/pages/Project/View/ViewProject'+import { useCurrentProject } from '~/providers/CurrentProjectProvider'+import { useTheme } from '~/providers/ThemeProvider'+import Loader from '~/ui/Loader'+import LoadingBar from '~/ui/LoadingBar'+import { Text } from '~/ui/Text'++import { SessionsDrawer } from '../Traffic/SessionsDrawer'+import { getFormatDate } from '../../View/ViewProject.helpers'++const MIN_STEPS = 2+const MAX_STEPS = 10+const MIN_JOURNEYS = 5+const MAX_JOURNEYS = 100+const DEFAULT_STEPS = 3+const DEFAULT_JOURNEYS = 20++const NODE_COLOURS = [+ '#2563eb',+ '#0d9488',+ '#7c3aed',+ '#db2777',+ '#ea580c',+ '#65a30d',+ '#0891b2',+ '#c026d3',+ '#4f46e5',+ '#b45309',+]++interface SankeyNodeMeta {+ page: string+ step: number+ sessions: number+}++interface JourneysViewProps {+ tnMapping: Record<string, string>+}++const truncatePath = (path: string, maxLength = 24) => {+ if (path.length <= maxLength) {+ return path+ }++ return `${path.slice(0, maxLength - 1)}β¦`+}++const JourneysView = ({ tnMapping }: JourneysViewProps) => {+ const { dateRange, period, timezone, timeFormat, filters } =+ useViewProjectContext()+ const { journeysRefreshTrigger } = useRefreshTriggers()+ const { id } = useCurrentProject()+ const { theme } = useTheme()+ const { t } = useTranslation('common')++ const [steps, setSteps] = useState(DEFAULT_STEPS)+ const [journeysCount, setJourneysCount] = useState(DEFAULT_JOURNEYS)+ const [debouncedParams, setDebouncedParams] = useState({+ steps: DEFAULT_STEPS,+ journeys: DEFAULT_JOURNEYS,+ })+ const [isLoading, setIsLoading] = useState<boolean | null>(null)+ const [journeysData, setJourneysData] = useState<JourneysResponse | null>(+ null,+ )+ const [sessionsDrawer, setSessionsDrawer] = useState<{+ step: number+ page: string+ sessions: number+ } | null>(null)+ const loadingRef = useRef(false)++ const { fetchJourneys } = useJourneysProxy()++ const [from, to] = useMemo(() => {+ if (!dateRange) {+ return [undefined, undefined]+ }++ return [getFormatDate(dateRange[0]), getFormatDate(dateRange[1])]+ }, [dateRange])++ useEffect(() => {+ const timer = setTimeout(() => {+ setDebouncedParams({ steps, journeys: journeysCount })+ }, 300)++ return () => clearTimeout(timer)+ }, [steps, journeysCount])++ useEffect(() => {+ let cancelled = false++ const load = async () => {+ if (loadingRef.current) {+ return+ }++ loadingRef.current = true+ setIsLoading(true)++ try {+ const result = await fetchJourneys(id, {+ period,+ filters,+ from,+ to,+ timezone,+ steps: debouncedParams.steps,+ journeys: debouncedParams.journeys,+ })++ if (!cancelled && result) {+ setJourneysData(result)+ }+ } catch (error: any) {+ if (!cancelled) {+ toast.error(+ typeof error === 'string'+ ? error+ : t('apiNotifications.somethingWentWrong'),+ )+ }+ } finally {+ loadingRef.current = false++ if (!cancelled) {+ setIsLoading(false)+ }+ }+ }++ load()++ return () => {+ cancelled = true+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [+ id,+ period,+ from,+ to,+ timezone,+ filters,+ debouncedParams,+ journeysRefreshTrigger,+ ])++ const { sankeyData, nodeMeta, maxColumnNodes } = useMemo(() => {+ const meta = new Map<string, SankeyNodeMeta>()++ if (_isEmpty(journeysData?.journeys)) {+ return { sankeyData: null, nodeMeta: meta, maxColumnNodes: 0 }+ }++ const nodeSessions = new Map<string, SankeyNodeMeta>()+ const links = new Map<+ string,+ { source: string; target: string; value: number }+ >()++ for (const { path, value } of journeysData!.journeys) {+ path.forEach((page, index) => {+ const nodeId = `${index}:${page}`+ const node = nodeSessions.get(nodeId)++ if (node) {+ node.sessions += value+ } else {+ nodeSessions.set(nodeId, { page, step: index, sessions: value })+ }++ if (index < path.length - 1) {+ const target = `${index + 1}:${path[index + 1]}`+ const linkId = `${nodeId}β${target}`+ const link = links.get(linkId)++ if (link) {+ link.value += value+ } else {+ links.set(linkId, { source: nodeId, target, value })+ }+ }+ })+ }++ if (links.size === 0) {+ return { sankeyData: null, nodeMeta: meta, maxColumnNodes: 0 }+ }++ // Nivo requires every node to participate in at least one link,+ // so nodes are derived from links (journeys that end early simply taper off)+ const linkedNodeIds = new Set<string>()++ for (const link of links.values()) {+ linkedNodeIds.add(link.source)+ linkedNodeIds.add(link.target)+ }++ const columnCounts = new Map<number, number>()+ const nodes: { id: string }[] = []++ for (const nodeId of linkedNodeIds) {+ const node = nodeSessions.get(nodeId)!+ meta.set(nodeId, node)+ nodes.push({ id: nodeId })+ columnCounts.set(node.step, (columnCounts.get(node.step) || 0) + 1)+ }++ return {+ sankeyData: { nodes, links: Array.from(links.values()) },+ nodeMeta: meta,+ maxColumnNodes: Math.max(...columnCounts.values()),+ }+ }, [journeysData])++ const chartHeight = useMemo(+ () => Math.min(1000, Math.max(440, maxColumnNodes * 56)),+ [maxColumnNodes],+ )++ const totalSessions = journeysData?.totalSessions || 0++ const nodeColour = (nodeId: string) => {+ const node = nodeMeta.get(nodeId)+ return NODE_COLOURS[(node?.step ?? 0) % NODE_COLOURS.length]+ }++ const renderNodeTooltip = (nodeId: string) => {+ const node = nodeMeta.get(nodeId)++ if (!node) {+ return null+ }++ const percentage =+ totalSessions > 0+ ? Math.round((node.sessions / totalSessions) * 10000) / 100+ : 0++ return (+ <div className='w-max max-w-xs rounded-lg bg-gray-50 px-3 py-2.5 text-xs shadow-lg ring-1 ring-black/10 md:max-w-md md:text-sm dark:bg-slate-900 dark:ring-white/10'>+ <p className='font-semibold break-all text-gray-900 dark:text-gray-50'>+ {node.page}+ </p>+ <p className='mt-1 text-gray-700 dark:text-gray-300'>+ {t('project.journeys.stepX', { x: node.step + 1 })} Β·{' '}+ {t('project.journeys.xSessions', {+ x: node.sessions.toLocaleString(),+ })}+ </p>+ <p className='text-gray-700 dark:text-gray-300'>+ {t('project.journeys.percentOfSessions', { x: percentage })}+ </p>+ <p className='mt-1.5 text-gray-500 dark:text-gray-400'>+ {t('project.journeys.clickToInspect')}+ </p>+ </div>+ )+ }++ const renderLinkTooltip = (+ sourceId: string,+ targetId: string,+ value: number,+ ) => {+ const source = nodeMeta.get(sourceId)+ const target = nodeMeta.get(targetId)++ if (!source || !target) {+ return null+ }++ const percentage =+ source.sessions > 0+ ? Math.round((value / source.sessions) * 10000) / 100+ : 0++ return (+ <div className='w-max max-w-xs rounded-lg bg-gray-50 px-3 py-2.5 text-xs shadow-lg ring-1 ring-black/10 md:max-w-md md:text-sm dark:bg-slate-900 dark:ring-white/10'>+ <p className='font-semibold break-all text-gray-900 dark:text-gray-50'>+ {source.page} β {target.page}+ </p>+ <p className='mt-1 text-gray-700 dark:text-gray-300'>+ {t('project.journeys.xSessions', { x: value.toLocaleString() })}+ </p>+ <p className='text-gray-700 dark:text-gray-300'>+ {t('project.journeys.percentContinued', { x: percentage })}+ </p>+ </div>+ )+ }++ const sliders = (+ <div className='mb-3 flex flex-wrap items-center gap-x-8 gap-y-3'>+ <div className='flex items-center gap-3'>+ <Text+ as='span'+ size='sm'+ weight='medium'+ className='whitespace-nowrap tabular-nums'+ >+ {t('project.journeys.xSteps', { x: steps })}+ </Text>+ <input+ type='range'+ aria-label={t('project.journeys.stepsSliderLabel')}+ min={MIN_STEPS}+ max={MAX_STEPS}+ value={steps}+ onChange={(e) => setSteps(Number(e.target.value))}+ className='w-36 sm:w-44'+ />+ </div>+ <div className='flex items-center gap-3'>+ <Text+ as='span'+ size='sm'+ weight='medium'+ className='whitespace-nowrap tabular-nums'+ >+ {t('project.journeys.xJourneys', { x: journeysCount })}+ </Text>+ <input+ type='range'+ aria-label={t('project.journeys.journeysSliderLabel')}+ min={MIN_JOURNEYS}+ max={MAX_JOURNEYS}+ step={5}+ value={journeysCount}+ onChange={(e) => setJourneysCount(Number(e.target.value))}+ className='w-36 sm:w-44'+ />+ </div>+ </div>+ )++ return (+ <TabErrorBoundary+ titleKey='dashboard.failedToLoadJourneys'+ resetKey={`journeys:${journeysRefreshTrigger}`}+ >+ <DashboardHeader+ showLiveVisitors+ hideTimeBucket+ rightContent={<ProjectViewHeaderActions tnMapping={tnMapping} />}+ />+ <Filters className='mb-3' tnMapping={tnMapping} />+ {isLoading && journeysData ? <LoadingBar /> : null}++ {isLoading === null || (isLoading && !journeysData) ? (+ <Loader />+ ) : (+ <>+ {sliders}+ {sankeyData ? (+ <div style={{ height: chartHeight }}>+ <ResponsiveSankey+ data={sankeyData}+ margin={{ top: 8, right: 8, bottom: 8, left: 8 }}+ align='start'+ colors={(node: any) => nodeColour(node.id)}+ nodeOpacity={1}+ nodeHoverOthersOpacity={0.35}+ nodeThickness={14}+ nodeSpacing={22}+ nodeBorderWidth={0}+ nodeBorderRadius={3}+ linkOpacity={theme === 'dark' ? 0.35 : 0.25}+ linkHoverOpacity={0.6}+ linkHoverOthersOpacity={0.1}+ linkContract={2}+ enableLinkGradient+ label={(node: any) => {+ const meta = nodeMeta.get(node.id)++ if (!meta) {+ return node.id+ }++ // hide labels of tiny nodes to reduce clutter, they are still hoverable+ if (+ totalSessions > 0 &&+ meta.sessions / totalSessions < 0.015+ ) {+ return ''+ }++ return truncatePath(meta.page)+ }}+ labelPosition='inside'+ labelOrientation='horizontal'+ labelPadding={10}+ labelTextColor={theme === 'dark' ? '#e2e8f0' : '#334155'}+ theme={{+ labels: {+ text: {+ fontSize: 13,+ fontWeight: 500,+ fontFamily: 'inherit',+ },+ },+ }}+ nodeTooltip={({ node }: any) => renderNodeTooltip(node.id)}+ linkTooltip={({ link }: any) =>+ renderLinkTooltip(link.source.id, link.target.id, link.value)+ }+ onClick={(data: any) => {+ // links (source/target present) are not clickable, only nodes are+ if (data?.source || !data?.id) {+ return+ }++ const node = nodeMeta.get(data.id)++ if (!node) {+ return+ }++ setSessionsDrawer({+ step: node.step + 1,+ page: node.page,+ sessions: node.sessions,+ })+ }}+ />+ </div>+ ) : (+ <div className='mx-auto w-full max-w-2xl py-16 text-center'>+ <div className='mx-auto mb-6 flex size-14 items-center justify-center rounded-xl bg-gray-100 dark:bg-slate-900'>+ <PathIcon className='size-7 text-gray-700 dark:text-gray-200' />+ </div>+ <Text+ as='h3'+ size='xl'+ weight='medium'+ className='tracking-tight'+ >+ {t('dashboard.journeys')}+ </Text>+ <Text+ as='p'+ size='sm'+ colour='secondary'+ className='mx-auto mt-2 max-w-md whitespace-pre-wrap'+ >+ {t('project.journeys.noData')}+ </Text>+ </div>+ )}+ </>+ )}++ <SessionsDrawer+ isOpen={!!sessionsDrawer}+ onClose={() => setSessionsDrawer(null)}+ label={+ sessionsDrawer+ ? `${sessionsDrawer.page} Β· ${t('project.journeys.stepX', {+ x: sessionsDrawer.step,+ })}`+ : ''+ }+ projectId={id}+ timezone={timezone}+ timeFormat={timeFormat}+ period={period}+ from={from}+ to={to}+ filters={filters}+ journeyStep={sessionsDrawer?.step}+ journeyPage={sessionsDrawer?.page}+ totalCount={sessionsDrawer?.sessions}+ />+ </TabErrorBoundary>+ )+}++export default JourneysViewdiff --git a/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx b/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsxindex 2cfe5ff61..c35ed3181 100644--- a/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx+++ b/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx@@ -12,6 +12,7 @@ import { useLocation } from 'react-router'import type {SessionsResponse,FunnelSessionsResponse,+ JourneySessionsResponse,GoalSessionsResponse,ErrorSessionsResponse,ErrorAffectedSession,@@ -43,6 +44,7 @@ const SESSIONS_TAKE = 30type SessionsPageResult =| SessionsResponse| FunnelSessionsResponse+ | JourneySessionsResponse| GoalSessionsResponse| ErrorSessionsResponse@@ -199,6 +201,8 @@ interface SessionsDrawerProps {dropoff?: booleanshowDropoffToggle?: booleanonDropoffChange?: (checked: boolean) => void+ journeyStep?: number+ journeyPage?: stringgoalId?: stringerrorId?: stringsessionEvent?: SessionEventType@@ -222,6 +226,8 @@ export const SessionsDrawer = ({dropoff,showDropoffToggle,onDropoffChange,+ journeyStep,+ journeyPage,goalId,errorId,sessionEvent,@@ -231,6 +237,7 @@ export const SessionsDrawer = ({const { t } = useTranslation('common')const stableFilters = useMemo(() => filters ?? [], [filters])const isFunnelMode = !!(funnelId && funnelStep)+ const isJourneyMode = !!(journeyStep && journeyPage)const isGoalMode = !!goalIdconst isErrorMode = !!errorIdconst [sessions, setSessions] = useState<DrawerSession[]>([])@@ -272,6 +279,23 @@ export const SessionsDrawer = ({},signal,)+ } else if (isJourneyMode) {+ result = await fetchSessionsPage(+ 'getJourneySessions',+ projectId,+ {+ period,+ from,+ to,+ timezone,+ step: journeyStep,+ page: journeyPage,+ filters: stableFilters,+ take: SESSIONS_TAKE,+ skip: currentSkip,+ },+ signal,+ )} else if (isGoalMode) {result = await fetchSessionsPage('getGoalSessions',@@ -361,11 +385,14 @@ export const SessionsDrawer = ({to,timezone,isFunnelMode,+ isJourneyMode,isGoalMode,isErrorMode,funnelId,funnelStep,dropoff,+ journeyStep,+ journeyPage,goalId,errorId,sessionEvent,diff --git a/web/app/pages/Project/tabs/Traffic/TrafficView.tsx b/web/app/pages/Project/tabs/Traffic/TrafficView.tsxindex 656886671..ad26a2c11 100644--- a/web/app/pages/Project/tabs/Traffic/TrafficView.tsx+++ b/web/app/pages/Project/tabs/Traffic/TrafficView.tsx@@ -56,7 +56,6 @@ import PageLinkRow from '~/pages/Project/tabs/Traffic/PageLinkRow'import RefRow from '~/pages/Project/tabs/Traffic/RefRow'import { SessionsDrawer } from '~/pages/Project/tabs/Traffic/SessionsDrawer'import { TrafficChart } from '~/pages/Project/tabs/Traffic/TrafficChart'-import UserFlow from '~/pages/Project/tabs/Traffic/UserFlow'import { getChartPointWindow } from '~/pages/Project/View/utils/chartPoint'import CCRow from '~/pages/Project/View/components/CCRow'import { ChartContextMenu } from '~/pages/Project/View/components/ChartContextMenu'@@ -431,7 +430,7 @@ const TrafficViewInner = ({// Panel active tabsconst [panelsActiveTabs, setPanelsActiveTabs] = useState<{location: 'cc' | 'rg' | 'ct' | 'lc' | 'map'- page: 'pg' | 'host' | 'userFlow' | 'entryPage' | 'exitPage'+ page: 'pg' | 'host' | 'entryPage' | 'exitPage'device: 'br' | 'os' | 'dv'network: 'isp' | 'og' | 'ut' | 'ctp'source: 'ref' | 'so' | 'me' | 'ca' | 'te' | 'co'@@ -1259,7 +1258,6 @@ const TrafficViewInner = ({{ id: 'pg', label: t('project.mapping.pg') },{ id: 'entryPage', label: t('project.entryPages') },{ id: 'exitPage', label: t('project.exitPages') },- { id: 'userFlow', label: t('project.mapping.userFlow') },{id: 'host',label: t('project.mapping.host'),@@ -1311,16 +1309,6 @@ const TrafficViewInner = ({onTabChange={(tab) => setPanelTab('page', tab)}activeTabId={panelsActiveTabs.page}data={panelsData.data[panelsActiveTabs.page]}- customRenderer={- panelsActiveTabs.page === 'userFlow'- ? () => (- <UserFlow- isReversed={false}- setReversed={() => {}}- />- )- : undefined- }/>)}diff --git a/web/app/pages/Project/tabs/Traffic/UserFlow.tsx b/web/app/pages/Project/tabs/Traffic/UserFlow.tsxdeleted file mode 100644index 25f4617f9..000000000--- a/web/app/pages/Project/tabs/Traffic/UserFlow.tsx+++ /dev/null@@ -1,151 +0,0 @@-import { ResponsiveSankey } from '@nivo/sankey'-import { ArrowClockwiseIcon, TreeStructureIcon } from '@phosphor-icons/react'-import _isEmpty from 'lodash/isEmpty'-import { useEffect, useState, memo, useMemo } from 'react'-import { useTranslation } from 'react-i18next'-import { toast } from 'sonner'--import { useUserFlowProxy } from '~/hooks/useAnalyticsProxy'-import type { UserFlowResponse } from '~/api/api.server'-import { PanelEmptyState } from '~/pages/Project/View/Panels'-import Button from '~/ui/Button'-import Loader from '~/ui/Loader'-import { Text } from '~/ui/Text'--import { useCurrentProject } from '../../../../providers/CurrentProjectProvider'-import { useViewProjectContext } from '../../View/ViewProject'-import { getFormatDate } from '../../View/ViewProject.helpers'--interface UserFlowProps {- isReversed?: boolean- setReversed: () => void-}--const UserFlow = ({ setReversed, isReversed }: UserFlowProps) => {- const { dateRange, period, timeBucket, timezone, filters } =- useViewProjectContext()- const { id } = useCurrentProject()- const { t } = useTranslation('common')- const [isLoading, setIsLoading] = useState<boolean | null>(null)- const [userFlow, setUserFlow] = useState<UserFlowResponse | null>(null)- const { fetchUserFlow: fetchUserFlowProxy } = useUserFlowProxy()-- const [from, to] = useMemo(() => {- if (!dateRange) {- return [undefined, undefined]- }-- return [getFormatDate(dateRange[0]), getFormatDate(dateRange[1])]- }, [dateRange])-- const fetchUserFlow = async () => {- if (isLoading) {- return- }-- setIsLoading(true)-- try {- const result = await fetchUserFlowProxy(id, {- timeBucket,- period,- filters,- from,- to,- timezone,- })- if (result) {- setUserFlow(result as UserFlowResponse)- }- } catch (error: any) {- toast.error(- typeof error === 'string'- ? error- : t('apiNotifications.somethingWentWrong'),- )- } finally {- setIsLoading(false)- }- }-- useEffect(() => {- fetchUserFlow()- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [filters, period, timeBucket, from, to, timezone, id])-- if (isLoading || isLoading === null) {- return <Loader />- }-- if (- !isReversed- ? _isEmpty(userFlow?.ascending) ||- _isEmpty(userFlow?.ascending?.nodes) ||- _isEmpty(userFlow?.ascending?.links)- : _isEmpty(userFlow?.descending) ||- _isEmpty(userFlow?.descending?.links) ||- _isEmpty(userFlow?.descending?.nodes)- ) {- return (- <PanelEmptyState- icon={- <TreeStructureIcon className='size-5 text-gray-400 dark:text-slate-500' />- }- >- <Text as='p' size='sm' colour='secondary'>- {t('project.userFlow.noData')}- </Text>- <Button- variant='icon'- type='button'- onClick={() => {- setReversed()- }}- className='mt-3 gap-1.5 px-3 py-2'- aria-label={t('project.reverse')}- >- <ArrowClockwiseIcon className='size-4' />- {t('project.reverse')}- </Button>- </PanelEmptyState>- )- }-- return (- <ResponsiveSankey- // @ts-expect-error- data={isReversed ? userFlow?.descending : userFlow?.ascending}- margin={{- top: 0,- right: 0,- bottom: 0,- left: 20,- }}- align='justify'- colors={{ scheme: 'nivo' }}- nodeOpacity={1}- nodeHoverOthersOpacity={0.35}- nodeThickness={18}- nodeSpacing={24}- nodeBorderWidth={0}- nodeBorderColor={{- from: 'color',- modifiers: [['darker', 0.8]],- }}- nodeBorderRadius={3}- linkOpacity={0.5}- linkHoverOthersOpacity={0.1}- linkContract={3}- enableLinkGradient- labelPosition='outside'- labelOrientation='vertical'- labelPadding={16}- labelTextColor={{- from: 'color',- modifiers: [['darker', 1]],- }}- />- )-}--export default memo(UserFlow)diff --git a/web/app/routes/api.analytics.ts b/web/app/routes/api.analytics.tsindex d24bd1b62..3ba7585d7 100644--- a/web/app/routes/api.analytics.ts+++ b/web/app/routes/api.analytics.ts@@ -37,7 +37,8 @@ import {getLiveVisitorsInfoServer,getBotProtectionStatsServer,getProjectDataCustomEventsServer,- getUserFlowServer,+ getJourneysServer,+ getJourneySessionsServer,getGSCKeywordsServer,getGSCDashboardServer,getGSCDetailsServer,@@ -76,7 +77,8 @@ import {type BotProtectionStats,type BotProtectionPeriod,type ProjectDataCustomEventsResponse,- type UserFlowResponse,+ type JourneysResponse,+ type JourneySessionsResponse,type GSCKeywordsResponse,type GSCDashboardResponse,type GSCDetailsResponse,@@ -134,7 +136,8 @@ interface ProxyRequest {| 'getLiveVisitorsInfo'| 'getBotProtectionStats'| 'getProjectDataCustomEvents'- | 'getUserFlow'+ | 'getJourneys'+ | 'getJourneySessions'| 'getGSCKeywords'| 'getGSCDashboard'| 'getGSCDetails'@@ -175,6 +178,8 @@ interface ProxyRequest {query?: stringfunnelId?: stringstep?: number+ steps?: number+ journeys?: numberdropoff?: booleangoalId?: stringsessionEvent?: 'traffic' | 'performance' | 'error'@@ -946,17 +951,41 @@ export async function action({ request }: ActionFunctionArgs) {})}- case 'getUserFlow': {- const result = await getUserFlowServer(request, projectId, {- timeBucket: params.timeBucket,+ case 'getJourneys': {+ const result = await getJourneysServer(request, projectId, {period: params.period,filters: params.filters,from: formatDateForBackend(params.from),to: formatDateForBackend(params.to),timezone: params.timezone,+ steps: params.steps,+ journeys: params.journeys,password: password || undefined,})- return data<ProxyResponse<UserFlowResponse>>({+ return data<ProxyResponse<JourneysResponse>>({+ data: result.data,+ error: result.error+ ? Array.isArray(result.error)+ ? result.error.join(', ')+ : result.error+ : null,+ })+ }++ case 'getJourneySessions': {+ const result = await getJourneySessionsServer(request, projectId, {+ period: analyticsParams.period,+ from: analyticsParams.from,+ to: analyticsParams.to,+ timezone: analyticsParams.timezone,+ step: params.step ?? 1,+ page: params.page ?? '',+ take: params.take,+ skip: params.skip,+ password: analyticsParams.password,+ filters: params.filters || [],+ })+ return data<ProxyResponse<JourneySessionsResponse>>({data: result.data,error: result.error? Array.isArray(result.error)diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex a1c556c4e..6b3b70d74 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -1077,6 +1077,7 @@"failedToLoadPerformance": "Couldn't load performance data","failedToLoadSeo": "Couldn't load SEO data","failedToLoadFunnels": "Couldn't load funnels",+ "failedToLoadJourneys": "Couldn't load journeys","failedToLoadErrors": "Couldn't load errors","verifyEmailTitle": "Please, verify the email address first","verifyEmailDesc": "To start using our service and creating your projects, you first need to confirm your email address.\n\nA link to confirm your account was sent to the email address you provided during registration, if it was not delivered - you can request the link again in your account settings.",@@ -1115,6 +1116,7 @@"performance": "Performance","profiles": "Profiles","funnels": "Funnels",+ "journeys": "Journeys","sessions": "Sessions","replays": "Replays","xOccurrences": "{{x}} occurrences",@@ -2084,7 +2086,6 @@"ca": "UTM Campaign","te": "UTM Term","co": "UTM Content",- "userFlow": "User flow","entryPage": "Entry page","exitPage": "Exit page","keywords": "Keywords",@@ -2674,10 +2675,17 @@"reportFrequency": "Report frequency"},"page": "Page",- "reverse": "Reverse",- "userFlow": {- "title": "User flow",- "noData": "User flow is not available yet due to lack of data, or you disabled this feature in the tracking script parameters"+ "journeys": {+ "noData": "Journeys are not available yet due to lack of data, or you disabled this feature in the tracking script parameters.",+ "stepX": "Step {{x}}",+ "xSteps": "{{x}} steps",+ "xJourneys": "{{x}} journeys",+ "xSessions": "{{x}} sessions",+ "percentOfSessions": "{{x}}% of all sessions",+ "percentContinued": "{{x}}% continued this way",+ "clickToInspect": "Click to inspect sessions",+ "stepsSliderLabel": "How many pages deep each journey goes",+ "journeysSliderLabel": "How many of the most popular journeys to show"},"compareDateRangeError": "This date range cannot be compared, please select a other date range","previousPeriod": "Previous period",