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!

CE profiles support

Blue Mouse9d7cbb564559
diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.ts
index 048a42526..d7a0d8425 100644
--- a/backend/apps/community/src/analytics/analytics.controller.ts
+++ b/backend/apps/community/src/analytics/analytics.controller.ts
@@ -64,6 +64,9 @@ import {
} from './interfaces'
import { GetSessionsDto } from './dto/get-sessions.dto'
import { GetSessionDto } from './dto/get-session.dto'
+import { GetProfilesDto } from './dto/get-profiles.dto'
+import { GetProfileDto, GetProfileSessionsDto } from './dto/get-profile.dto'
+import { GetProfileIdDto, GetSessionIdDto } from './dto/get-id.dto'
import { ErrorDto } from './dto/error.dto'
import { GetErrorsDto } from './dto/get-errors.dto'
import { GetErrorDto } from './dto/get-error.dto'
@@ -1871,4 +1874,290 @@ export class AnalyticsController {
skip,
)
}
+
+ @Get('profiles')
+ @Auth(true, true)
+ async getProfiles(
+ @Query() data: GetProfilesDto,
+ @CurrentUserId() uid: string,
+ @Headers() headers: { 'x-password'?: string },
+ ) {
+ const {
+ pid,
+ period,
+ from,
+ to,
+ filters,
+ timezone = DEFAULT_TIMEZONE,
+ profileType = 'all',
+ } = 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 profiles to return is 150',
+ )
+ }
+
+ let timeBucket
+ let diff
+
+ if (period === 'all') {
+ const res = await this.analyticsService.calculateTimeBucketForAllTime(
+ pid,
+ 'analytics',
+ )
+
+ timeBucket = res.timeBucket[0]
+ diff = res.diff
+ } else {
+ timeBucket = getLowestPossibleTimeBucket(period, from, to)
+ }
+
+ const [filtersQuery, filtersParams, appliedFilters] =
+ this.analyticsService.getFiltersQuery(filters, DataType.ANALYTICS)
+
+ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
+ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(
+ from,
+ to,
+ timeBucket,
+ period,
+ safeTimezone,
+ diff,
+ )
+
+ const paramsData = {
+ params: {
+ pid,
+ groupFrom: groupFromUTC,
+ groupTo: groupToUTC,
+ ...filtersParams,
+ },
+ }
+
+ const profiles = await this.analyticsService.getProfilesList(
+ pid,
+ filtersQuery,
+ paramsData,
+ safeTimezone,
+ take,
+ skip,
+ profileType,
+ )
+
+ return { profiles, appliedFilters, take, skip }
+ }
+
+ @Get('profile')
+ @Auth(true, true)
+ async getProfile(
+ @Query() data: GetProfileDto,
+ @CurrentUserId() uid: string,
+ @Headers() headers: { 'x-password'?: string },
+ ) {
+ const {
+ pid,
+ profileId,
+ timezone = DEFAULT_TIMEZONE,
+ period,
+ from,
+ to,
+ } = data
+
+ await this.analyticsService.checkProjectAccess(
+ pid,
+ uid,
+ headers['x-password'],
+ )
+
+ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
+
+ let timeBucket
+ let diff
+
+ if (period === 'all') {
+ const res = await this.analyticsService.calculateTimeBucketForAllTime(
+ pid,
+ 'analytics',
+ )
+ timeBucket = res.timeBucket[0]
+ diff = res.diff
+ } else {
+ timeBucket = getLowestPossibleTimeBucket(period, from, to)
+ }
+
+ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(
+ from,
+ to,
+ timeBucket,
+ period,
+ safeTimezone,
+ diff,
+ )
+
+ const [details, topPages, activityCalendar, chart] = await Promise.all([
+ this.analyticsService.getProfileDetails(pid, profileId, safeTimezone),
+ this.analyticsService.getProfileTopPages(pid, profileId),
+ this.analyticsService.getProfileActivityCalendar(pid, profileId),
+ this.analyticsService.getProfileChartData(
+ pid,
+ profileId,
+ timeBucket,
+ groupFromUTC,
+ groupToUTC,
+ safeTimezone,
+ ),
+ ])
+
+ return {
+ ...details,
+ topPages,
+ activityCalendar,
+ chart,
+ timeBucket,
+ }
+ }
+
+ @Get('profile/sessions')
+ @Auth(true, true)
+ async getProfileSessions(
+ @Query() data: GetProfileSessionsDto,
+ @CurrentUserId() uid: string,
+ @Headers() headers: { 'x-password'?: string },
+ ) {
+ const {
+ pid,
+ profileId,
+ period,
+ from,
+ to,
+ filters,
+ timezone = DEFAULT_TIMEZONE,
+ } = 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',
+ )
+ }
+
+ let timeBucket
+ let diff
+
+ if (period === 'all') {
+ const res = await this.analyticsService.calculateTimeBucketForAllTime(
+ pid,
+ 'analytics',
+ )
+
+ timeBucket = res.timeBucket[0]
+ diff = res.diff
+ } else {
+ timeBucket = getLowestPossibleTimeBucket(period, from, to)
+ }
+
+ const [filtersQuery, filtersParams, appliedFilters] =
+ this.analyticsService.getFiltersQuery(filters, DataType.ANALYTICS)
+
+ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
+ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(
+ from,
+ to,
+ timeBucket,
+ period,
+ safeTimezone,
+ diff,
+ )
+
+ const paramsData = {
+ params: {
+ pid,
+ groupFrom: groupFromUTC,
+ groupTo: groupToUTC,
+ ...filtersParams,
+ },
+ }
+
+ const sessions = await this.analyticsService.getProfileSessionsList(
+ pid,
+ profileId,
+ filtersQuery,
+ paramsData,
+ safeTimezone,
+ take,
+ skip,
+ )
+
+ return { sessions, appliedFilters, take, skip }
+ }
+
+ @Post('profile-id')
+ @Public()
+ async getOrCreateProfileId(
+ @Body() dto: GetProfileIdDto,
+ @Headers() headers,
+ @Ip() reqIP,
+ ): Promise<{ profileId: string | null }> {
+ const { 'user-agent': userAgent } = headers
+ const { pid } = dto
+
+ try {
+ const ip = getIPFromHeaders(headers) || reqIP || ''
+
+ const profileId = await this.analyticsService.generateProfileId(
+ pid,
+ userAgent,
+ ip,
+ )
+
+ return { profileId }
+ } catch (error) {
+ this.logger.error({ error, pid }, 'Error generating profile ID')
+ return { profileId: null }
+ }
+ }
+
+ @Post('session-id')
+ @Public()
+ async getOrCreateSessionId(
+ @Body() dto: GetSessionIdDto,
+ @Headers() headers,
+ @Ip() reqIP,
+ ): Promise<{ sessionId: string | null }> {
+ const { 'user-agent': userAgent } = headers
+ const { pid } = dto
+
+ try {
+ const ip = getIPFromHeaders(headers) || reqIP || ''
+
+ const { psid } = await this.analyticsService.getSessionId(
+ pid,
+ userAgent,
+ ip,
+ )
+
+ return { sessionId: psid }
+ } catch (error) {
+ this.logger.error({ error, pid }, 'Error generating session ID')
+ return { sessionId: null }
+ }
+ }
}
diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.ts
index f409c69c6..ae26c78a1 100644
--- a/backend/apps/community/src/analytics/analytics.service.ts
+++ b/backend/apps/community/src/analytics/analytics.service.ts
@@ -4991,4 +4991,491 @@ export class AnalyticsService {
)
}
}
+
+ async getProfilesList(
+ pid: string,
+ filtersQuery: string,
+ paramsData: any,
+ safeTimezone: string,
+ take = 30,
+ skip = 0,
+ profileType: 'all' | 'anonymous' | 'identified' = 'all',
+ ): Promise<object[]> {
+ let profileTypeFilter = ''
+ if (profileType === 'anonymous') {
+ profileTypeFilter = `AND profileId LIKE '${AnalyticsService.PROFILE_PREFIX_ANON}%'`
+ } else if (profileType === 'identified') {
+ profileTypeFilter = `AND profileId LIKE '${AnalyticsService.PROFILE_PREFIX_USER}%'`
+ }
+
+ const query = `
+ WITH profile_analytics AS (
+ SELECT
+ profileId,
+ count() AS pageviewsCount,
+ countDistinct(psid) AS sessionsCount,
+ min(created) AS firstSeen,
+ max(created) AS lastSeen,
+ any(cc) AS cc_agg,
+ any(os) AS os_agg,
+ any(br) AS br_agg,
+ any(dv) AS dv_agg
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId IS NOT NULL
+ AND profileId != ''
+ ${profileTypeFilter}
+ ${filtersQuery}
+ GROUP BY profileId
+ ),
+ profile_events AS (
+ SELECT
+ profileId,
+ count() AS eventsCount
+ FROM customEV
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId IS NOT NULL
+ AND profileId != ''
+ ${profileTypeFilter}
+ GROUP BY profileId
+ ),
+ profile_errors AS (
+ SELECT
+ profileId,
+ count() AS errorsCount
+ FROM errors
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId IS NOT NULL
+ AND profileId != ''
+ ${profileTypeFilter}
+ GROUP BY profileId
+ )
+ SELECT
+ pa.profileId AS profileId,
+ pa.sessionsCount AS sessionsCount,
+ pa.pageviewsCount AS pageviewsCount,
+ COALESCE(pe.eventsCount, 0) AS eventsCount,
+ COALESCE(perr.errorsCount, 0) AS errorsCount,
+ pa.firstSeen AS firstSeen,
+ pa.lastSeen AS lastSeen,
+ pa.cc_agg AS cc,
+ pa.os_agg AS os,
+ pa.br_agg AS br,
+ pa.dv_agg AS dv
+ FROM profile_analytics AS pa
+ LEFT JOIN profile_events AS pe ON pa.profileId = pe.profileId
+ LEFT JOIN profile_errors AS perr ON pa.profileId = perr.profileId
+ ORDER BY pa.lastSeen DESC
+ LIMIT {take:UInt32}
+ OFFSET {skip:UInt32}
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { pid, ...paramsData.params, take, skip },
+ })
+ .then(resultSet => resultSet.json())
+
+ return data
+ .filter((profile: any) => profile.profileId)
+ .map((profile: any) => ({
+ ...profile,
+ isIdentified: this.isUserSuppliedProfile(profile.profileId),
+ }))
+ }
+
+ async getProfileDetails(
+ pid: string,
+ profileId: string,
+ _safeTimezone: string,
+ ): Promise<any> {
+ // Query session count from sessions table
+ const querySessionCount = `
+ SELECT
+ count() AS sessionsCount,
+ min(sessions.firstSeen) AS firstSeen,
+ max(sessions.lastSeen) AS lastSeen
+ FROM sessions FINAL
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId = {profileId:String}
+ `
+
+ // Query avg duration from analytics table (more accurate than sessions table)
+ const queryAvgDuration = `
+ SELECT
+ avg(session_duration) AS avgDuration
+ FROM (
+ SELECT
+ psid,
+ dateDiff('second', min(created), max(created)) AS session_duration
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId = {profileId:String}
+ AND psid IS NOT NULL
+ GROUP BY psid
+ HAVING session_duration > 0
+ )
+ `
+
+ // Query analytics for accurate pageview count
+ const queryPageviews = `
+ SELECT count() AS pageviewsCount
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId = {profileId:String}
+ `
+
+ // Query customEV for accurate events count
+ const queryEvents = `
+ SELECT count() AS eventsCount
+ FROM customEV
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId = {profileId:String}
+ `
+
+ // Query for device/location details
+ const queryDetails = `
+ SELECT
+ any(cc) AS cc,
+ any(rg) AS rg,
+ any(ct) AS ct,
+ any(os) AS os,
+ any(osv) AS osv,
+ any(br) AS br,
+ any(brv) AS brv,
+ any(dv) AS dv,
+ any(lc) AS lc
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId = {profileId:String}
+ `
+
+ const params = { pid, profileId }
+
+ const [
+ sessionCountResult,
+ avgDurationResult,
+ pageviewsResult,
+ eventsResult,
+ detailsResult,
+ ] = await Promise.all([
+ clickhouse
+ .query({ query: querySessionCount, query_params: params })
+ .then(resultSet => resultSet.json()),
+ clickhouse
+ .query({ query: queryAvgDuration, query_params: params })
+ .then(resultSet => resultSet.json()),
+ clickhouse
+ .query({ query: queryPageviews, query_params: params })
+ .then(resultSet => resultSet.json()),
+ clickhouse
+ .query({ query: queryEvents, query_params: params })
+ .then(resultSet => resultSet.json()),
+ clickhouse
+ .query({ query: queryDetails, query_params: params })
+ .then(resultSet => resultSet.json()),
+ ])
+
+ const sessionCount = (sessionCountResult.data[0] || {}) as Record<
+ string,
+ any
+ >
+ const avgDuration = (avgDurationResult.data[0] || {}) as Record<string, any>
+ const pageviews = (pageviewsResult.data[0] || {}) as Record<string, any>
+ const events = (eventsResult.data[0] || {}) as Record<string, any>
+ const details = (detailsResult.data[0] || {}) as Record<string, any>
+
+ return {
+ profileId,
+ isIdentified: this.isUserSuppliedProfile(profileId),
+ sessionsCount: sessionCount.sessionsCount || 0,
+ pageviewsCount: pageviews.pageviewsCount || 0,
+ eventsCount: events.eventsCount || 0,
+ firstSeen: sessionCount.firstSeen,
+ lastSeen: sessionCount.lastSeen,
+ avgDuration: avgDuration.avgDuration || 0,
+ ...details,
+ }
+ }
+
+ async getProfileTopPages(
+ pid: string,
+ profileId: string,
+ limit = 10,
+ ): Promise<{ page: string; count: number }[]> {
+ const query = `
+ SELECT
+ pg AS page,
+ count() AS count
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId = {profileId:String}
+ GROUP BY pg
+ ORDER BY count DESC
+ LIMIT {limit:UInt32}
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { pid, profileId, limit: Number(limit) },
+ })
+ .then(resultSet => resultSet.json())
+
+ return data as { page: string; count: number }[]
+ }
+
+ async getProfileActivityCalendar(
+ pid: string,
+ profileId: string,
+ months = 4,
+ ): Promise<{ date: string; count: number }[]> {
+ const startDate = dayjs
+ .utc()
+ .subtract(months, 'month')
+ .startOf('day')
+ .format('YYYY-MM-DD')
+
+ const query = `
+ SELECT
+ toDate(created) AS date,
+ count() AS count
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId = {profileId:String}
+ AND created >= {startDate:Date}
+ GROUP BY date
+ ORDER BY date ASC
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { pid, profileId, startDate },
+ })
+ .then(resultSet => resultSet.json())
+
+ return data as { date: string; count: number }[]
+ }
+
+ async getProfileChartData(
+ pid: string,
+ profileId: string,
+ timeBucket: string,
+ from: string,
+ to: string,
+ safeTimezone: string,
+ ): Promise<{
+ x: string[]
+ pageviews: number[]
+ customEvents: number[]
+ errors: number[]
+ }> {
+ const timeBucketFunc =
+ timeBucketConversion[timeBucket] || timeBucketConversion.day
+
+ const queryPageviews = `
+ SELECT
+ ${timeBucketFunc}(toTimeZone(created, {timezone:String})) AS time,
+ count() AS count
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId = {profileId:String}
+ AND created BETWEEN {from:String} AND {to:String}
+ GROUP BY time
+ ORDER BY time ASC
+ `
+
+ const queryEvents = `
+ SELECT
+ ${timeBucketFunc}(toTimeZone(created, {timezone:String})) AS time,
+ count() AS count
+ FROM customEV
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId = {profileId:String}
+ AND created BETWEEN {from:String} AND {to:String}
+ GROUP BY time
+ ORDER BY time ASC
+ `
+
+ const queryErrors = `
+ SELECT
+ ${timeBucketFunc}(toTimeZone(created, {timezone:String})) AS time,
+ count() AS count
+ FROM errors
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId = {profileId:String}
+ AND created BETWEEN {from:String} AND {to:String}
+ GROUP BY time
+ ORDER BY time ASC
+ `
+
+ const params = { pid, profileId, from, to, timezone: safeTimezone }
+
+ const [pageviewsResult, eventsResult, errorsResult] = await Promise.all([
+ clickhouse
+ .query({ query: queryPageviews, query_params: params })
+ .then(resultSet => resultSet.json()),
+ clickhouse
+ .query({ query: queryEvents, query_params: params })
+ .then(resultSet => resultSet.json()),
+ clickhouse
+ .query({ query: queryErrors, query_params: params })
+ .then(resultSet => resultSet.json()),
+ ])
+
+ // Merge all timestamps and create aligned data
+ const allTimes = new Set<string>()
+ const pageviewsMap = new Map<string, number>()
+ const eventsMap = new Map<string, number>()
+ const errorsMap = new Map<string, number>()
+
+ for (const row of pageviewsResult.data as {
+ time: string
+ count: number
+ }[]) {
+ allTimes.add(row.time)
+ pageviewsMap.set(row.time, Number(row.count))
+ }
+
+ for (const row of eventsResult.data as {
+ time: string
+ count: number
+ }[]) {
+ allTimes.add(row.time)
+ eventsMap.set(row.time, Number(row.count))
+ }
+
+ for (const row of errorsResult.data as {
+ time: string
+ count: number
+ }[]) {
+ allTimes.add(row.time)
+ errorsMap.set(row.time, Number(row.count))
+ }
+
+ const sortedTimes = Array.from(allTimes).sort()
+
+ return {
+ x: sortedTimes,
+ pageviews: sortedTimes.map(t => pageviewsMap.get(t) || 0),
+ customEvents: sortedTimes.map(t => eventsMap.get(t) || 0),
+ errors: sortedTimes.map(t => errorsMap.get(t) || 0),
+ }
+ }
+
+ async getProfileSessionsList(
+ pid: string,
+ profileId: string,
+ filtersQuery: string,
+ paramsData: any,
+ safeTimezone: string,
+ take = 30,
+ skip = 0,
+ ): Promise<object[]> {
+ const query = `
+ WITH profile_sessions AS (
+ SELECT
+ CAST(psid, 'String') AS psidCasted,
+ pid,
+ profileId,
+ any(cc) AS cc_agg,
+ any(os) AS os_agg,
+ any(br) AS br_agg,
+ min(toTimeZone(created, {timezone:String})) AS sessionStart,
+ max(toTimeZone(created, {timezone:String})) AS lastActivity
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId = {profileId:String}
+ AND psid IS NOT NULL
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filtersQuery}
+ GROUP BY psidCasted, pid, profileId
+ ),
+ pageview_counts AS (
+ SELECT
+ CAST(psid, 'String') AS psidCasted,
+ pid,
+ count() as count
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId = {profileId:String}
+ AND psid IS NOT NULL
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY psidCasted, pid
+ ),
+ event_counts AS (
+ SELECT
+ CAST(psid, 'String') AS psidCasted,
+ pid,
+ count() as count
+ FROM customEV
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId = {profileId:String}
+ AND psid IS NOT NULL
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY psidCasted, pid
+ ),
+ error_counts AS (
+ SELECT
+ CAST(psid, 'String') AS psidCasted,
+ pid,
+ count() as count
+ FROM errors
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId = {profileId:String}
+ AND psid IS NOT NULL
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY psidCasted, pid
+ ),
+ session_duration_agg AS (
+ SELECT
+ CAST(psid, 'String') AS psidCasted,
+ pid,
+ dateDiff('second', min(firstSeen), max(lastSeen)) as avg_duration
+ FROM sessions
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId = {profileId:String}
+ GROUP BY psidCasted, pid
+ )
+ SELECT
+ ps.psidCasted AS psid,
+ ps.cc_agg AS cc,
+ ps.os_agg AS os,
+ ps.br_agg AS br,
+ COALESCE(pc.count, 0) AS pageviews,
+ COALESCE(ec.count, 0) AS customEvents,
+ COALESCE(errc.count, 0) AS errors,
+ ps.sessionStart,
+ ps.lastActivity,
+ if(dateDiff('second', ps.lastActivity, now()) < ${LIVE_SESSION_THRESHOLD_SECONDS}, 1, 0) AS isLive,
+ sda.avg_duration AS sdur
+ FROM profile_sessions ps
+ LEFT JOIN pageview_counts pc ON ps.psidCasted = pc.psidCasted AND ps.pid = pc.pid
+ LEFT JOIN event_counts ec ON ps.psidCasted = ec.psidCasted AND ps.pid = ec.pid
+ LEFT JOIN error_counts errc ON ps.psidCasted = errc.psidCasted AND ps.pid = errc.pid
+ LEFT JOIN session_duration_agg sda ON ps.psidCasted = sda.psidCasted AND ps.pid = sda.pid
+ WHERE ps.psidCasted IS NOT NULL
+ ORDER BY ps.sessionStart DESC
+ LIMIT {take:UInt32}
+ OFFSET {skip:UInt32}
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: {
+ pid,
+ profileId,
+ ...paramsData.params,
+ timezone: safeTimezone,
+ take,
+ skip,
+ },
+ })
+ .then(resultSet => resultSet.json())
+
+ return data as object[]
+ }
}
diff --git a/backend/apps/community/src/analytics/dto/get-id.dto.ts b/backend/apps/community/src/analytics/dto/get-id.dto.ts
new file mode 100644
index 000000000..539c70999
--- /dev/null
+++ b/backend/apps/community/src/analytics/dto/get-id.dto.ts
@@ -0,0 +1,25 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { IsNotEmpty, Matches } from 'class-validator'
+import { PID_REGEX } from '../../common/constants'
+
+export class GetProfileIdDto {
+ @ApiProperty({
+ example: 'aUn1quEid-3',
+ required: true,
+ description: 'The project ID',
+ })
+ @IsNotEmpty()
+ @Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })
+ pid: string
+}
+
+export class GetSessionIdDto {
+ @ApiProperty({
+ example: 'aUn1quEid-3',
+ required: true,
+ description: 'The project ID',
+ })
+ @IsNotEmpty()
+ @Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })
+ pid: string
+}
diff --git a/backend/apps/community/src/analytics/dto/get-profile.dto.ts b/backend/apps/community/src/analytics/dto/get-profile.dto.ts
new file mode 100644
index 000000000..064a897f6
--- /dev/null
+++ b/backend/apps/community/src/analytics/dto/get-profile.dto.ts
@@ -0,0 +1,91 @@
+import { ApiProperty, PickType } from '@nestjs/swagger'
+import { Type } from 'class-transformer'
+import {
+ IsNotEmpty,
+ IsOptional,
+ IsString,
+ Matches,
+ MaxLength,
+ IsInt,
+ Min,
+ Max,
+} from 'class-validator'
+import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'
+import { PID_REGEX } from '../../common/constants'
+import { ValidatePeriod } from '../decorators/validate-period.decorator'
+import { GetDataDto } from './getData.dto'
+
+export class GetProfileDto {
+ @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: true,
+ description: 'The profile ID',
+ maxLength: 256,
+ })
+ @IsNotEmpty()
+ @IsString()
+ @MaxLength(256)
+ profileId: string
+
+ @ApiProperty({
+ description: 'Timezone to display data in',
+ default: DEFAULT_TIMEZONE,
+ })
+ @IsOptional()
+ timezone?: string
+
+ @ApiProperty({ required: false })
+ @IsOptional()
+ @ValidatePeriod()
+ period?: string
+
+ @ApiProperty({ required: false })
+ @IsOptional()
+ from?: string
+
+ @ApiProperty({ required: false })
+ @IsOptional()
+ to?: string
+}
+
+export class GetProfileSessionsDto extends PickType(GetDataDto, [
+ 'pid',
+ 'period',
+ 'from',
+ 'to',
+ 'filters',
+ 'timezone',
+] as const) {
+ @ApiProperty({
+ required: true,
+ description: 'The profile ID',
+ maxLength: 256,
+ })
+ @IsNotEmpty()
+ @IsString()
+ @MaxLength(256)
+ profileId: string
+
+ @ApiProperty({ required: false, default: 30 })
+ @IsOptional()
+ @Type(() => Number)
+ @IsInt()
+ @Min(0)
+ @Max(150)
+ take?: number
+
+ @ApiProperty({ required: false, default: 0 })
+ @IsOptional()
+ @Type(() => Number)
+ @IsInt()
+ @Min(0)
+ skip?: number
+}
diff --git a/backend/apps/community/src/analytics/dto/get-profiles.dto.ts b/backend/apps/community/src/analytics/dto/get-profiles.dto.ts
new file mode 100644
index 000000000..3591ff196
--- /dev/null
+++ b/backend/apps/community/src/analytics/dto/get-profiles.dto.ts
@@ -0,0 +1,38 @@
+import { ApiProperty, PickType } from '@nestjs/swagger'
+import { Type } from 'class-transformer'
+import { IsOptional, IsIn, IsInt, Min, Max } from 'class-validator'
+import { GetDataDto } from './getData.dto'
+
+export class GetProfilesDto extends PickType(GetDataDto, [
+ 'pid',
+ 'period',
+ 'from',
+ 'to',
+ 'filters',
+ 'timezone',
+] as const) {
+ @ApiProperty({ required: false, default: 30 })
+ @IsOptional()
+ @Type(() => Number)
+ @IsInt()
+ @Min(0)
+ @Max(150)
+ take?: number
+
+ @ApiProperty({ required: false, default: 0 })
+ @IsOptional()
+ @Type(() => Number)
+ @IsInt()
+ @Min(0)
+ skip?: number
+
+ @ApiProperty({
+ required: false,
+ description: 'Filter by profile type',
+ enum: ['all', 'anonymous', 'identified'],
+ default: 'all',
+ })
+ @IsOptional()
+ @IsIn(['all', 'anonymous', 'identified'])
+ profileType?: 'all' | 'anonymous' | 'identified'
+}