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!

(improvement) Support for project views on selfhosted instances (#251)

Andrii Romasiuna04e5af61f6d
diff --git a/apps/selfhosted/src/analytics/analytics.controller.ts b/apps/selfhosted/src/analytics/analytics.controller.ts
index 595ac6d23..77069b624 100644
--- a/apps/selfhosted/src/analytics/analytics.controller.ts
+++ b/apps/selfhosted/src/analytics/analytics.controller.ts
@@ -4,6 +4,7 @@ import * as _pick from 'lodash/pick'
import * as _map from 'lodash/map'
import * as _uniqBy from 'lodash/uniqBy'
import * as _includes from 'lodash/includes'
+import * as _size from 'lodash/size'
import * as dayjs from 'dayjs'
import * as utc from 'dayjs/plugin/utc'
import * as dayjsTimezone from 'dayjs/plugin/timezone'
@@ -83,6 +84,7 @@ import {
performanceTransformer,
trafficTransformer,
} from './utils/transformers'
+import { MAX_METRICS_IN_VIEW } from '../project/dto/create-project-view.dto'
dayjs.extend(utc)
dayjs.extend(dayjsTimezone)
@@ -204,6 +206,7 @@ export class AnalyticsController {
filters,
timezone = DEFAULT_TIMEZONE,
mode = ChartRenderMode.PERIODICAL,
+ metrics,
} = data
this.analyticsService.validatePID(pid)
@@ -217,6 +220,14 @@ export class AnalyticsController {
headers['x-password'],
)
+ const parsedMetrics = this.analyticsService.parseMetrics(metrics)
+
+ if (_size(parsedMetrics) > MAX_METRICS_IN_VIEW) {
+ throw new BadRequestException(
+ `The maximum number of metrics within one request is ${MAX_METRICS_IN_VIEW}`,
+ )
+ }
+
let newTimebucket = timeBucket
let allowedTumebucketForPeriodAll
@@ -294,12 +305,28 @@ export class AnalyticsController {
)
}
+ let meta: Awaited<ReturnType<typeof this.analyticsService.getMetaResults>>
+
+ if (!_isEmpty(parsedMetrics)) {
+ meta = await this.analyticsService.getMetaResults(
+ pid,
+ parsedMetrics,
+ filtersQuery,
+ paramsData,
+ timezone,
+ period,
+ from,
+ to,
+ )
+ }
+
return {
...result,
customs,
properties,
appliedFilters: parsedFilters,
timeBucket: allowedTumebucketForPeriodAll,
+ meta,
}
}
diff --git a/apps/selfhosted/src/analytics/analytics.service.ts b/apps/selfhosted/src/analytics/analytics.service.ts
index fe8d57121..5272f7e54 100644
--- a/apps/selfhosted/src/analytics/analytics.service.ts
+++ b/apps/selfhosted/src/analytics/analytics.service.ts
@@ -91,6 +91,8 @@ import {
} from './interfaces'
import { ErrorDTO } from './dto/error.dto'
import { GetPagePropertyMetaDTO } from './dto/get-page-property-meta.dto'
+import { ProjectViewCustomEventMetaValueType } from '../project/entity/project-view-custom-event.entity'
+import { ProjectViewCustomEventDto } from '../project/dto/create-project-view.dto'
dayjs.extend(utc)
dayjs.extend(dayjsTimezone)
@@ -857,6 +859,21 @@ export class AnalyticsService {
)
}
+ parseMetrics(metrics: string): ProjectViewCustomEventDto[] {
+ if (metrics === '""' || _isEmpty(metrics)) {
+ return []
+ }
+
+ try {
+ return JSON.parse(metrics)
+ } catch {
+ console.error(
+ `[ERROR] parseMetrics: Cannot parse the metrics array: ${metrics}`,
+ )
+ return []
+ }
+ }
+
// returns SQL filters query in a format like 'AND col=value AND ...'
getFiltersQuery(
filters: string,
@@ -3425,4 +3442,209 @@ export class AnalyticsService {
)
}
}
+
+ async getMetaResults(
+ pid: string,
+ customEvents: ProjectViewCustomEventDto[],
+ filtersQuery: string,
+ paramsData: any,
+ timezone: string,
+ period?: string,
+ from?: string,
+ to?: string,
+ ) {
+ // eslint-disable-next-line
+ let _from = from
+ // eslint-disable-next-line
+ let _to = to
+
+ if (_isEmpty(period) || ['today', 'yesterday', 'custom'].includes(period)) {
+ const safeTimezone = this.getSafeTimezone(timezone)
+
+ const { groupFrom, groupTo } = this.getGroupFromTo(
+ from,
+ to,
+ ['today', 'yesterday'].includes(period) ? TimeBucketType.HOUR : null,
+ period,
+ safeTimezone,
+ )
+
+ _from = groupFrom
+ _to = groupTo
+ }
+
+ const results = []
+
+ await Promise.all(
+ customEvents.map(async event => {
+ const result = await this.getMetaResult(
+ pid,
+ event,
+ filtersQuery,
+ paramsData,
+ period,
+ _from,
+ _to,
+ )
+ results.push(result)
+ }),
+ )
+
+ return results.filter(r => !!r)
+ }
+
+ async getMetaResult(
+ pid: string,
+ metric: ProjectViewCustomEventDto,
+ filtersQuery: string,
+ paramsData: any,
+ period?: string,
+ from?: string,
+ to?: string,
+ ) {
+ if (metric.metaValueType === ProjectViewCustomEventMetaValueType.STRING) {
+ return undefined
+ }
+
+ const paramsKeys = ['customEventName', 'metaKey', 'metaValue', 'metricKey']
+
+ const aggFunction =
+ metric.metaValueType === ProjectViewCustomEventMetaValueType.INTEGER
+ ? 'toInt32OrZero(value)'
+ : 'toFloat32OrZero(value)'
+
+ let kvQuery = ''
+
+ if (metric.metaKey && metric.metaValue) {
+ kvQuery = `AND (
+ indexOf(meta.key, {metaKey:String}) > 0
+ AND meta.value[indexOf(meta.key, {metaKey:String})] = {metaValue:String}
+ )`
+ } else if (metric.metaKey) {
+ kvQuery = `AND indexOf(meta.key, {metaKey:String}) > 0`
+ } else if (metric.metaValue) {
+ kvQuery = `AND indexOf(meta.value, {metaValue:String}) > 0`
+ }
+
+ const queryCurrent = `
+ SELECT
+ 1 AS sortOrder,
+ key,
+ round(sum(${aggFunction}), 2) AS sum,
+ round(avg(${aggFunction}), 2) AS avg
+ FROM customEV
+ ARRAY JOIN meta.key AS key, meta.value AS value
+ WHERE
+ pid = {pid:FixedString(12)}
+ AND key = {metricKey:String}
+ AND ev = {customEventName:String}
+ AND created BETWEEN {periodFormatted:String} AND {now:String}
+ ${kvQuery}
+ ${filtersQuery}
+ GROUP BY key
+ `
+
+ const queryPrevious = `
+ SELECT
+ 2 AS sortOrder,
+ key,
+ round(sum(${aggFunction}), 2) AS sum,
+ round(avg(${aggFunction}), 2) AS avg
+ FROM customEV
+ ARRAY JOIN meta.key AS key, meta.value AS value
+ WHERE
+ pid = {pid:FixedString(12)}
+ AND key = {metricKey:String}
+ AND ev = {customEventName:String}
+ AND created BETWEEN {periodSubtracted:String} AND {periodFormatted:String}
+ ${kvQuery}
+ ${filtersQuery}
+ GROUP BY key
+ `
+
+ let now
+ let periodFormatted
+ let periodSubtracted
+
+ if (period !== 'all') {
+ if (from && to) {
+ // diff may be 0 (when selecting data for 1 day), so let's make it 1 to grab some data for the prev day as well
+ const diff = dayjs(to).diff(dayjs(from), 'days') || 1
+
+ now = to
+ periodFormatted = from
+ periodSubtracted = dayjs(from)
+ .subtract(diff, 'days')
+ .format('YYYY-MM-DD HH:mm:ss')
+ } else {
+ const amountToSubtract = parseInt(period, 10)
+ const unit = _replace(period, /[0-9]/g, '')
+
+ now = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')
+ const periodRaw = dayjs.utc().subtract(amountToSubtract, unit)
+ periodFormatted = periodRaw.format('YYYY-MM-DD HH:mm:ss')
+ periodSubtracted = periodRaw
+ .subtract(amountToSubtract, unit)
+ .format('YYYY-MM-DD HH:mm:ss')
+ }
+ }
+
+ const params = {
+ pid,
+ ...paramsKeys.reduce(
+ (acc, curr) => ({
+ ...acc,
+ [curr]: metric[curr],
+ }),
+ {},
+ ),
+ now,
+ periodFormatted,
+ periodSubtracted,
+ ...paramsData.params,
+ }
+
+ try {
+ let { data } = await clickhouse
+ .query({
+ query: `${queryCurrent} UNION ALL ${queryPrevious}`,
+ query_params: params,
+ })
+ .then(resultSet =>
+ resultSet.json<{
+ sortOrder: 1 | 2
+ key: string
+ sum: number
+ avg: number
+ }>(),
+ )
+
+ data = _sortBy(data, 'sortOrder')
+
+ const currentPeriod = data[0]
+ const previousPeriod = data[1]
+
+ if (!currentPeriod) {
+ return undefined
+ }
+
+ return {
+ key: currentPeriod.key,
+ current: {
+ sum: currentPeriod.sum || 0,
+ avg: currentPeriod.avg || 0,
+ },
+ previous: {
+ sum: previousPeriod?.sum || 0,
+ avg: previousPeriod?.avg || 0,
+ },
+ }
+ } catch (reason) {
+ console.error('[ERROR] (getMetaResult) - Clickhouse query error:')
+ console.error(reason)
+ throw new InternalServerErrorException(
+ 'Error occurred while fetching meta results',
+ )
+ }
+ }
}
diff --git a/apps/selfhosted/src/analytics/dto/getData.dto.ts b/apps/selfhosted/src/analytics/dto/getData.dto.ts
index 870f59c98..c56c226df 100644
--- a/apps/selfhosted/src/analytics/dto/getData.dto.ts
+++ b/apps/selfhosted/src/analytics/dto/getData.dto.ts
@@ -1,5 +1,5 @@
import { ApiProperty } from '@nestjs/swagger'
-import { IsNotEmpty } from 'class-validator'
+import { IsNotEmpty, IsOptional } from 'class-validator'
import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'
export enum TimeBucketType {
@@ -52,4 +52,10 @@ export class AnalyticsGET_DTO {
default: ChartRenderMode.PERIODICAL,
})
mode?: ChartRenderMode
+
+ @ApiProperty({
+ required: false,
+ })
+ @IsOptional()
+ metrics?: string
}
diff --git a/apps/selfhosted/src/common/utils.ts b/apps/selfhosted/src/common/utils.ts
index 28f5a8b6f..7a4c2fbbc 100644
--- a/apps/selfhosted/src/common/utils.ts
+++ b/apps/selfhosted/src/common/utils.ts
@@ -30,6 +30,7 @@ import { clickhouse } from './integrations/clickhouse'
import { DEFAULT_TIMEZONE, TimeFormat } from '../user/entities/user.entity'
import { Project } from '../project/entity/project.entity'
import { Funnel } from '../project/entity/funnel.entity'
+import { ProjectViewEntity } from '../project/entity/project-view.entity'
dayjs.extend(utc)
@@ -131,28 +132,20 @@ const updateFunnelClickhouse = async (funnel: any) => {
', ',
)} WHERE id='${funnel.id}'`
- const { data } = await clickhouse
- .query({
- query,
- })
- .then(resultSet => resultSet.json())
-
- return data
+ await clickhouse.command({
+ query,
+ })
}
const deleteFunnelClickhouse = async (id: string) => {
const query = `ALTER table funnel DELETE WHERE id = {id:String}`
- const { data } = await clickhouse
- .query({
- query,
- query_params: {
- id,
- },
- })
- .then(resultSet => resultSet.json())
-
- return data
+ await clickhouse.command({
+ query,
+ query_params: {
+ id,
+ },
+ })
}
const createFunnelClickhouse = async (funnel: Partial<Funnel>) => {
@@ -243,13 +236,9 @@ const updateProjectClickhouse = async (project: any) => {
', ',
)} WHERE id='${project.id}'`
- const { data } = await clickhouse
- .query({
- query,
- })
- .then(resultSet => resultSet.json())
-
- return data
+ await clickhouse.command({
+ query,
+ })
}
/**
@@ -277,16 +266,12 @@ const calculateRelativePercentage = (
const deleteProjectClickhouse = async (id: string) => {
const query = `ALTER table project DELETE WHERE id = {id:FixedString(12)}`
- const { data } = await clickhouse
- .query({
- query,
- query_params: {
- id,
- },
- })
- .then(resultSet => resultSet.json())
-
- return data
+ await clickhouse.command({
+ query,
+ query_params: {
+ id,
+ },
+ })
}
const createProjectClickhouse = async (project: Partial<Project>) => {
@@ -353,17 +338,13 @@ const deleteRefreshTokenClickhouse = async (
) => {
const query = `ALTER table refresh_token DELETE WHERE userId = {userId:String} AND refreshToken = {refreshToken:String}`
- const { data } = await clickhouse
- .query({
- query,
- query_params: {
- userId,
- refreshToken,
- },
- })
- .then(resultSet => resultSet.json())
-
- return data
+ await clickhouse.command({
+ query,
+ query_params: {
+ userId,
+ refreshToken,
+ },
+ })
}
interface IClickhouseUser {
@@ -458,17 +439,224 @@ const updateUserClickhouse = async (user: IClickhouseUser) => {
query += ` WHERE id={id:String}`
- const { data } = await clickhouse
- .query({
- query,
- query_params: {
- ...user,
- id: CLICKHOUSE_SETTINGS_ID,
+ await clickhouse.command({
+ query,
+ query_params: {
+ ...user,
+ id: CLICKHOUSE_SETTINGS_ID,
+ },
+ })
+}
+
+const findProjectViewCustomEventsClickhouse = async (viewId: string) => {
+ try {
+ const { data } = await clickhouse
+ .query({
+ query:
+ 'SELECT * FROM projects_views_custom_events WHERE viewId = {viewId:FixedString(36)}',
+ query_params: {
+ viewId,
+ },
+ })
+ .then(resultSet => resultSet.json())
+
+ return data
+ } catch {
+ return []
+ }
+}
+
+const doesProjectViewExistClickhouse = async (
+ projectId: string,
+ id: string,
+): Promise<boolean> => {
+ try {
+ const { data } = await clickhouse
+ .query({
+ query: `
+ SELECT
+ count(*) AS count
+ FROM
+ project_views
+ WHERE
+ id = {id:FixedString(36)}
+ AND projectId = {projectId:FixedString(12)}
+ `,
+ query_params: {
+ id,
+ projectId,
+ },
+ })
+ .then(resultSet => resultSet.json<{ count: number }>())
+
+ if (_isEmpty(data)) {
+ return false
+ }
+
+ return data[0]?.count > 0
+ } catch {
+ return false
+ }
+}
+
+const findProjectViewClickhouse = async (id: string, projectId: string) => {
+ try {
+ const { data } = await clickhouse
+ .query({
+ query: `
+ SELECT
+ *
+ FROM
+ project_views
+ WHERE
+ id = {id:FixedString(36)}
+ AND projectId = {projectId:FixedString(12)}
+ `,
+ query_params: {
+ id,
+ projectId,
+ },
+ })
+ .then(resultSet => resultSet.json())
+
+ if (_isEmpty(data)) {
+ return null
+ }
+
+ const view: any = data[0]
+ const customEvents = await findProjectViewCustomEventsClickhouse(id)
+
+ return {
+ ...view,
+ customEvents,
+ }
+ } catch {
+ return null
+ }
+}
+
+const findProjectViewsClickhouse = async (projectId: string) => {
+ try {
+ const { data } = await clickhouse
+ .query({
+ query: `
+ SELECT
+ *
+ FROM
+ project_views
+ WHERE
+ projectId = {projectId:FixedString(12)}
+ `,
+ query_params: {
+ projectId,
+ },
+ })
+ .then(resultSet => resultSet.json())
+
+ if (_isEmpty(data)) {
+ return []
+ }
+
+ const result = []
+
+ for (let i = 0; i < _size(data); ++i) {
+ const view: any = data[i]
+ // eslint-disable-next-line no-await-in-loop
+ const customEvents = await findProjectViewCustomEventsClickhouse(view.id)
+
+ result.push({
+ ...view,
+ customEvents,
+ })
+ }
+
+ return result
+ } catch {
+ return []
+ }
+}
+
+const deleteProjectViewClickhouse = async (id: string) => {
+ const query = `ALTER TABLE project_views DELETE WHERE id = {id:FixedString(36)}`
+
+ await clickhouse.command({
+ query,
+ query_params: {
+ id,
+ },
+ })
+}
+
+const deleteCustomMetricsClickhouse = async (viewId: string) => {
+ const query = `ALTER TABLE projects_views_custom_events DELETE WHERE viewId = {viewId:FixedString(36)}`
+
+ await clickhouse.command({
+ query,
+ query_params: {
+ viewId,
+ },
+ })
+}
+
+const createProjectViewClickhouse = async (
+ view: Partial<ProjectViewEntity>,
+) => {
+ const { id, projectId, name, type, filters, customEvents } = view
+
+ const createdAt = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')
+
+ await clickhouse.insert({
+ table: 'project_views',
+ format: 'JSONEachRow',
+ values: [
+ {
+ id,
+ projectId,
+ name,
+ type,
+ filters,
+ createdAt,
+ updatedAt: createdAt,
},
+ ],
+ })
+
+ if (!_isEmpty(customEvents)) {
+ await clickhouse.insert({
+ table: 'projects_views_custom_events',
+ format: 'JSONEachRow',
+ values: customEvents,
})
- .then(resultSet => resultSet.json())
+ }
+}
- return data
+const updateProjectViewClickhouse = async (viewId: string, view: any) => {
+ await clickhouse.command({
+ query: `
+ ALTER TABLE
+ project_views
+ UPDATE
+ name={name:String},
+ filters={filters:String}
+ WHERE
+ id={viewId:String}
+ `,
+ query_params: {
+ name: view.name,
+ filters: view.filters,
+ viewId,
+ },
+ })
+
+ await deleteCustomMetricsClickhouse(viewId)
+
+ if (!_isEmpty(view.customEvents)) {
+ await clickhouse.insert({
+ table: 'projects_views_custom_events',
+ format: 'JSONEachRow',
+ values: view.customEvents,
+ })
+ }
}
const millisecondsToSeconds = (milliseconds: number) => milliseconds / 1000
@@ -579,4 +767,10 @@ export {
updateFunnelClickhouse,
deleteFunnelClickhouse,
createFunnelClickhouse,
+ findProjectViewClickhouse,
+ deleteProjectViewClickhouse,
+ findProjectViewsClickhouse,
+ createProjectViewClickhouse,
+ doesProjectViewExistClickhouse,
+ updateProjectViewClickhouse,
}
diff --git a/apps/selfhosted/src/project/dto/create-project-view.dto.ts b/apps/selfhosted/src/project/dto/create-project-view.dto.ts
new file mode 100644
index 000000000..e4e221bd7
--- /dev/null
+++ b/apps/selfhosted/src/project/dto/create-project-view.dto.ts
@@ -0,0 +1,89 @@
+import {
+ ArrayMaxSize,
+ IsEnum,
+ IsNotEmpty,
+ IsOptional,
+ IsString,
+ MaxLength,
+ MinLength,
+ ValidateNested,
+} from 'class-validator'
+
+import { ApiProperty } from '@nestjs/swagger'
+import { ProjectViewType } from '../entity/project-view.entity'
+import { ProjectViewCustomEventMetaValueType } from '../entity/project-view-custom-event.entity'
+import { TRAFFIC_COLUMNS } from '../../common/constants'
+
+export class ProjectViewCustomEventDto {
+ @ApiProperty()
+ @MaxLength(100)
+ @MinLength(1)
+ @IsString()
+ @IsNotEmpty()
+ customEventName: string
+
+ @ApiProperty()
+ @MaxLength(100)
+ @IsString()
+ @IsOptional()
+ metaKey: string
+
+ @ApiProperty()
+ @MaxLength(100)
+ @IsString()
+ @IsOptional()
+ metaValue: string
+
+ @ApiProperty()
+ @MaxLength(100)
+ @MinLength(1)
+ @IsString()
+ @IsNotEmpty()
+ metricKey: string
+
+ @ApiProperty({ enum: ProjectViewCustomEventMetaValueType })
+ @IsEnum(ProjectViewCustomEventMetaValueType)
+ @IsNotEmpty()
+ metaValueType: ProjectViewCustomEventMetaValueType
+}
+
+export interface Filter {
+ column: keyof typeof TRAFFIC_COLUMNS
+ filter: string
+ isExclusive: boolean
+}
+
+export const MAX_METRICS_IN_VIEW = 3
+
+export class CreateProjectViewDto {
+ @ApiProperty()
+ @MaxLength(20)
+ @MinLength(1)
+ @IsString()
+ @IsNotEmpty()
+ name: string
+
+ @ApiProperty({ description: 'Type of the view', enum: ProjectViewType })
+ @IsEnum(ProjectViewType)
+ @IsNotEmpty()
+ type: ProjectViewType
+
+ @ApiProperty({
+ description:
+ 'An array of properties to filter [{ column, filter, isExclusive }]',
+ required: false,
+ isArray: true,
+ })
+ @IsOptional()
+ filters?: Filter[]
+
+ @ApiProperty({
+ type: ProjectViewCustomEventDto,
+ required: false,
+ isArray: true,
+ })
+ @ValidateNested()
+ @IsOptional()
+ @ArrayMaxSize(MAX_METRICS_IN_VIEW)
+ customEvents?: ProjectViewCustomEventDto[]
+}
diff --git a/apps/selfhosted/src/project/dto/project-id.dto.ts b/apps/selfhosted/src/project/dto/project-id.dto.ts
new file mode 100644
index 000000000..4c33ab2c7
--- /dev/null
+++ b/apps/selfhosted/src/project/dto/project-id.dto.ts
@@ -0,0 +1,11 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { Matches, IsNotEmpty } from 'class-validator'
+
+const PROJECT_ID_REGEX = /^(?!.*--)[a-zA-Z0-9-]{12}$/
+
+export class ProjectIdDto {
+ @ApiProperty()
+ @Matches(PROJECT_ID_REGEX)
+ @IsNotEmpty()
+ readonly projectId: string
+}
diff --git a/apps/selfhosted/src/project/dto/project-view-id.dto.ts b/apps/selfhosted/src/project/dto/project-view-id.dto.ts
new file mode 100644
index 000000000..6d9085dfb
--- /dev/null
+++ b/apps/selfhosted/src/project/dto/project-view-id.dto.ts
@@ -0,0 +1,9 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { IsNotEmpty, IsUUID } from 'class-validator'
+
+export class ProjectViewIdDto {
+ @ApiProperty()
+ @IsUUID('4')
+ @IsNotEmpty()
+ readonly viewId: string
+}
diff --git a/apps/selfhosted/src/project/dto/project-view-ids.dto.ts b/apps/selfhosted/src/project/dto/project-view-ids.dto.ts
new file mode 100644
index 000000000..c2ddf0c7b
--- /dev/null
+++ b/apps/selfhosted/src/project/dto/project-view-ids.dto.ts
@@ -0,0 +1,8 @@
+import { IntersectionType } from '@nestjs/swagger'
+import { ProjectIdDto } from './project-id.dto'
+import { ProjectViewIdDto } from './project-view-id.dto'
+
+export class ProjectViewIdsDto extends IntersectionType(
+ ProjectIdDto,
+ ProjectViewIdDto,
+) {}
diff --git a/apps/selfhosted/src/project/dto/update-project-view.dto.ts b/apps/selfhosted/src/project/dto/update-project-view.dto.ts
new file mode 100644
index 000000000..b62ab8a63
--- /dev/null
+++ b/apps/selfhosted/src/project/dto/update-project-view.dto.ts
@@ -0,0 +1,6 @@
+import { PartialType, OmitType } from '@nestjs/swagger'
+import { CreateProjectViewDto } from './create-project-view.dto'
+
+export class UpdateProjectViewDto extends PartialType(
+ OmitType(CreateProjectViewDto, ['type'] as const),
+) {}
diff --git a/apps/selfhosted/src/project/entity/project-view-custom-event.entity.ts b/apps/selfhosted/src/project/entity/project-view-custom-event.entity.ts
new file mode 100644
index 000000000..35b4dfcd8
--- /dev/null
+++ b/apps/selfhosted/src/project/entity/project-view-custom-event.entity.ts
@@ -0,0 +1,29 @@
+import { ProjectViewEntity } from './project-view.entity'
+
+export enum ProjectViewCustomEventMetaValueType {
+ STRING = 'string',
+ INTEGER = 'integer',
+ FLOAT = 'float',
+}
+
+export class ProjectViewCustomEventEntity {
+ id: string
+
+ viewId: string
+
+ customEventName: string
+
+ metaKey?: string
+
+ metaValue?: string
+
+ metricKey: string
+
+ metaValueType: ProjectViewCustomEventMetaValueType
+
+ createdAt: Date
+
+ updatedAt: Date
+
+ view: ProjectViewEntity
+}
diff --git a/apps/selfhosted/src/project/entity/project-view.entity.ts b/apps/selfhosted/src/project/entity/project-view.entity.ts
new file mode 100644
index 000000000..6ffb99c94
--- /dev/null
+++ b/apps/selfhosted/src/project/entity/project-view.entity.ts
@@ -0,0 +1,27 @@
+import { Project } from './project.entity'
+import { ProjectViewCustomEventEntity } from './project-view-custom-event.entity'
+
+export enum ProjectViewType {
+ TRAFFIC = 'traffic',
+ PERFORMANCE = 'performance',
+}
+
+export class ProjectViewEntity {
+ id: string
+
+ projectId: string
+
+ name: string
+
+ type: ProjectViewType
+
+ filters: string | null
+
+ createdAt: Date
+
+ updatedAt: Date
+
+ project: Project
+
+ customEvents: ProjectViewCustomEventEntity[]
+}
diff --git a/apps/selfhosted/src/project/project.controller.ts b/apps/selfhosted/src/project/project.controller.ts
index 84ecc2e23..d3e3cee17 100644
--- a/apps/selfhosted/src/project/project.controller.ts
+++ b/apps/selfhosted/src/project/project.controller.ts
@@ -14,9 +14,18 @@ import {
Headers,
UnauthorizedException,
Patch,
+ HttpStatus,
} from '@nestjs/common'
import { v4 as uuidv4 } from 'uuid'
-import { ApiTags, ApiQuery, ApiResponse, ApiBearerAuth } from '@nestjs/swagger'
+import {
+ ApiTags,
+ ApiQuery,
+ ApiResponse,
+ ApiBearerAuth,
+ ApiOperation,
+ ApiOkResponse,
+ ApiNoContentResponse,
+} from '@nestjs/swagger'
import * as _isEmpty from 'lodash/isEmpty'
import * as _map from 'lodash/map'
import * as _trim from 'lodash/trim'
@@ -61,8 +70,19 @@ import {
deleteFunnelClickhouse,
createFunnelClickhouse,
updateFunnelClickhouse,
+ findProjectViewClickhouse,
+ deleteProjectViewClickhouse,
+ createProjectViewClickhouse,
+ findProjectViewsClickhouse,
+ doesProjectViewExistClickhouse,
+ updateProjectViewClickhouse,
} from '../common/utils'
import { Funnel } from './entity/funnel.entity'
+import { ProjectViewEntity } from './entity/project-view.entity'
+import { ProjectViewIdsDto } from './dto/project-view-ids.dto'
+import { ProjectIdDto } from './dto/project-id.dto'
+import { CreateProjectViewDto } from './dto/create-project-view.dto'
+import { UpdateProjectViewDto } from './dto/update-project-view.dto'
@ApiTags('Project')
@Controller(['project', 'v1/project'])
@@ -86,8 +106,6 @@ export class ProjectController {
): Promise<Pagination<Project> | Project[] | object> {
this.logger.log({ userId, take, skip }, 'GET /project')
- console.log('hello !!! GET PROJECT')
-
const chResults = await getProjectsClickhouse(null, search)
const formatted = _map(chResults, this.projectService.formatFromClickhouse)
@@ -555,4 +573,165 @@ export class ProjectController {
isErrorDataExists,
})
}
+
+ @ApiOperation({ summary: 'Get project view' })
+ @ApiOkResponse({ type: ProjectViewEntity })
+ @ApiBearerAuth()
+ @Get(':projectId/views/:viewId')
+ @Auth([], true, true)
+ async getProjectView(
+ @Param() params: ProjectViewIdsDto,
+ @CurrentUserId() userId: string,
+ @Headers() headers: { 'x-password'?: string },
+ ) {
+ const project = await getProjectsClickhouse(params.projectId)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project was not found in the database')
+ }
+
+ this.projectService.allowedToView(project, userId, headers['x-password'])
+
+ return findProjectViewClickhouse(params.projectId, params.viewId)
+ }
+
+ @ApiOperation({ summary: 'Create project view' })
+ @ApiOkResponse({ type: ProjectViewEntity })
+ @ApiBearerAuth()
+ @Post(':projectId/views')
+ @Auth([], true)
+ async createProjectView(
+ @Param() params: ProjectIdDto,
+ @Body() body: CreateProjectViewDto,
+ @CurrentUserId() userId: string,
+ ) {
+ if (!userId) {
+ throw new UnauthorizedException('Please auth first')
+ }
+
+ const project = await getProjectsClickhouse(params.projectId)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project was not found in the database')
+ }
+
+ const viewId = uuidv4()
+
+ const { customEvents } = body
+
+ if (!_isEmpty(customEvents)) {
+ for (let i = 0; i < _size(customEvents); ++i) {
+ const customEvent = customEvents[i]
+
+ customEvents[i] = {
+ ...customEvent,
+ // @ts-expect-error
+ id: uuidv4(),
+ }
+ }
+ }
+
+ await createProjectViewClickhouse(
+ this.projectService.formatViewToClickhouse({
+ ...body,
+ customEvents,
+ id: viewId,
+ projectId: params.projectId,
+ }),
+ )
+
+ const view = await findProjectViewClickhouse(viewId, params.projectId)
+
+ return this.projectService.formatViewFromClickhouse(view)
+ }
+
+ @ApiOperation({ summary: 'Get project views' })
+ @ApiOkResponse({ type: ProjectViewEntity })
+ @ApiBearerAuth()
+ @Get(':projectId/views')
+ @Auth([], true, true)
+ async getProjectViews(
+ @Param() params: ProjectIdDto,
+ @CurrentUserId() userId: string,
+ @Headers() headers: { 'x-password'?: string },
+ ) {
+ const project = await getProjectsClickhouse(params.projectId)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project was not found in the database')
+ }
+
+ this.projectService.allowedToView(project, userId, headers['x-password'])
+
+ const views = await findProjectViewsClickhouse(params.projectId)
+
+ return this.projectService.formatViewsFromClickhouse(views)
+ }
+
+ @ApiOperation({ summary: 'Update project view' })
+ @ApiOkResponse({ type: ProjectViewEntity })
+ @ApiBearerAuth()
+ @Patch(':projectId/views/:viewId')
+ @Auth([], true)
+ async updateProjectView(
+ @Param() params: ProjectViewIdsDto,
+ @Body() body: UpdateProjectViewDto,
+ @CurrentUserId() userId: string,
+ ) {
+ if (!userId) {
+ throw new UnauthorizedException('Please auth first')
+ }
+
+ const viewExists = await doesProjectViewExistClickhouse(
+ params.projectId,
+ params.viewId,
+ )
+
+ if (!viewExists) {
+ throw new NotFoundException('View not found.')
+ }
+
+ await updateProjectViewClickhouse(
+ params.viewId,
+ // @ts-expect-error
+ this.projectService.formatViewToClickhouse({
+ ...body,
+ id: params.viewId,
+ projectId: params.projectId,
+ }),
+ )
+
+ const view = await findProjectViewClickhouse(
+ params.viewId,
+ params.projectId,
+ )
+
+ return this.projectService.formatViewFromClickhouse(view)
+ }
+
+ @ApiOperation({ summary: 'Delete project view' })
+ @ApiNoContentResponse()
+ @ApiBearerAuth()
+ @HttpCode(HttpStatus.NO_CONTENT)
+ @Delete(':projectId/views/:viewId')
+ @Auth([], true)
+ async deleteProjectView(
+ @Param() params: ProjectViewIdsDto,
+ @CurrentUserId() userId: string,
+ ) {
+ if (!userId) {
+ throw new UnauthorizedException('Please auth first')
+ }
+
+ const viewExists = await doesProjectViewExistClickhouse(
+ params.projectId,
+ params.viewId,
+ )
+
+ if (!viewExists) {
+ throw new NotFoundException('View not found.')
+ }
+
+ await deleteProjectViewClickhouse(params.viewId)
+ }
}
diff --git a/apps/selfhosted/src/project/project.service.ts b/apps/selfhosted/src/project/project.service.ts
index cef9f157b..52a608a2a 100644
--- a/apps/selfhosted/src/project/project.service.ts
+++ b/apps/selfhosted/src/project/project.service.ts
@@ -12,6 +12,8 @@ import * as _isEmpty from 'lodash/isEmpty'
import * as _isString from 'lodash/isString'
import * as _size from 'lodash/size'
import * as _join from 'lodash/join'
+import * as _filter from 'lodash/filter'
+import * as _includes from 'lodash/includes'
import * as _find from 'lodash/find'
import * as _map from 'lodash/map'
import * as _isNull from 'lodash/isNull'
@@ -29,11 +31,20 @@ import {
ORIGINS_REGEX,
getRedisProjectKey,
redisProjectCacheTimeout,
+ ALL_COLUMNS,
+ TRAFFIC_METAKEY_COLUMNS,
} from '../common/constants'
import { clickhouse } from '../common/integrations/clickhouse'
import { getProjectsClickhouse } from '../common/utils'
import { MAX_PROJECT_PASSWORD_LENGTH, UpdateProjectDto } from './dto'
import { Funnel } from './entity/funnel.entity'
+import { ProjectViewEntity } from './entity/project-view.entity'
+import {
+ CreateProjectViewDto,
+ Filter,
+ ProjectViewCustomEventDto,
+} from './dto/create-project-view.dto'
+import { ProjectViewCustomEventEntity } from './entity/project-view-custom-event.entity'
// A list of characters that can be used in a Project ID
const LEGAL_PID_CHARACTERS =
@@ -315,6 +326,97 @@ export class ProjectService {
return updProject
}
+ filterUnsupportedColumns(
+ filters: CreateProjectViewDto['filters'],
+ ): CreateProjectViewDto['filters'] {
+ if (!filters) {
+ return []
+ }
+
+ return _filter(
+ filters,
+ ({ column }) =>
+ _includes(ALL_COLUMNS, column) ||
+ _includes(TRAFFIC_METAKEY_COLUMNS, column),
+ )
+ }
+
+ formatCustomEventToClickhose(
+ viewId: string,
+ customEvent: ProjectViewCustomEventEntity | ProjectViewCustomEventDto,
+ ) {
+ if (!customEvent) {
+ return null
+ }
+
+ return {
+ viewId,
+ // @ts-expect-error
+ id: customEvent.id,
+ customEventName: customEvent.customEventName,
+ metaKey: customEvent.metaKey || null,
+ metaValue: customEvent.metaValue || null,
+ metaValueType: customEvent.metaValueType,
+ metricKey: customEvent.metricKey,
+ }
+ }
+
+ formatCustomEventsToClickhouse(
+ viewId: string,
+ customEvents: ProjectViewCustomEventEntity[] | ProjectViewCustomEventDto[],
+ ) {
+ if (_isEmpty(customEvents)) {
+ return []
+ }
+
+ return _map(customEvents, customEvent =>
+ this.formatCustomEventToClickhose(viewId, customEvent),
+ )
+ }
+
+ formatViewToClickhouse(
+ view: (ProjectViewEntity | CreateProjectViewDto) & {
+ id: string
+ projectId: string
+ },
+ ) {
+ const { id, projectId, type, customEvents, name, filters } = view
+
+ return {
+ id,
+ projectId,
+ type,
+ customEvents: this.formatCustomEventsToClickhouse(id, customEvents),
+ name,
+ filters: JSON.stringify(
+ this.filterUnsupportedColumns(filters as Filter[]),
+ null,
+ 2,
+ ),
+ }
+ }
+
+ formatViewsFromClickhouse(views: any[]): ProjectViewEntity[] {
+ if (_isEmpty(views)) {
+ return []
+ }
+
+ return _map(views, this.formatViewFromClickhouse)
+ }
+
+ formatViewFromClickhouse(view: any): ProjectViewEntity {
+ const updView = { ...view }
+ updView.name = _trim(updView.name)
+ updView.filters = JSON.parse(view.filters)
+ updView.customEvents = _map(view.customEvents, customEvent => ({
+ ...customEvent,
+ createdAt: '1970-01-01T00:00:00.000Z',
+ updatedAt: '1970-01-01T00:00:00.000Z',
+ }))
+
+ return updView
+ }
+
formatFunnelToClickhouse(funnel: Funnel): any {
const updFunnel = { ...funnel }
updFunnel.name = _trim(funnel.name)
diff --git a/migrations/clickhouse/initialise_selfhosted.js b/migrations/clickhouse/initialise_selfhosted.js
index 6517518dc..201421164 100644
--- a/migrations/clickhouse/initialise_selfhosted.js
+++ b/migrations/clickhouse/initialise_selfhosted.js
@@ -47,6 +47,32 @@ const CLICKHOUSE_INIT_QUERIES = [
)
ENGINE = MergeTree()
PRIMARY KEY id;`,
+
+ `CREATE TABLE IF NOT EXISTS ${dbName}.project_views
+ (
+ id FixedString(36),
+ projectId FixedString(12),
+ name String,
+ type String,
+ filters Nullable(String),
+ createdAt DateTime,
+ updatedAt DateTime
+ )
+ ENGINE = MergeTree()
+ PRIMARY KEY id;`,
+
+ `CREATE TABLE IF NOT EXISTS ${dbName}.projects_views_custom_events
+ (
+ id FixedString(36),
+ viewId FixedString(36),
+ customEventName String,
+ metaKey Nullable(String),
+ metaValue Nullable(String),
+ metricKey String,
+ metaValueType String
+ )
+ ENGINE = MergeTree()
+ PRIMARY KEY id;`,
]
const initialiseSelfhosted = async () => {
diff --git a/migrations/clickhouse/selfhosted_2024_08_10.js b/migrations/clickhouse/selfhosted_2024_08_10.js
new file mode 100644
index 000000000..bb9e70ed7
--- /dev/null
+++ b/migrations/clickhouse/selfhosted_2024_08_10.js
@@ -0,0 +1,33 @@
+const { queriesRunner, dbName } = require('./setup')
+
+const queries = [
+ // Added 'Project views' table
+ `CREATE TABLE IF NOT EXISTS ${dbName}.project_views
+ (
+ id FixedString(36),
+ projectId FixedString(12),
+ name String,
+ type String,
+ filters Nullable(String),
+ createdAt DateTime,
+ updatedAt DateTime
+ )
+ ENGINE = MergeTree()
+ PRIMARY KEY id;`,
+
+ // Added 'Project views -- custom events' table
+ `CREATE TABLE IF NOT EXISTS ${dbName}.projects_views_custom_events
+ (
+ id FixedString(36),
+ viewId FixedString(36),
+ customEventName String,
+ metaKey Nullable(String),
+ metaValue Nullable(String),
+ metricKey String,
+ metaValueType String
+ )
+ ENGINE = MergeTree()
+ PRIMARY KEY id;`,
+]
+
+queriesRunner(queries)