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!

Annotations feature for Swetrix CE

Blue Mouse15e9b27831e2
diff --git a/backend/apps/community/src/common/types.ts b/backend/apps/community/src/common/types.ts
index a077f8f93..fc13566c0 100644
--- a/backend/apps/community/src/common/types.ts
+++ b/backend/apps/community/src/common/types.ts
@@ -31,3 +31,11 @@ export interface ClickhouseFunnel {
projectId: string
created: string
}
+
+export interface ClickhouseAnnotation {
+ id: string
+ date: string
+ text: string
+ projectId: string
+ created: string
+}
diff --git a/backend/apps/community/src/common/utils.ts b/backend/apps/community/src/common/utils.ts
index 0229851c4..f8f684bd3 100644
--- a/backend/apps/community/src/common/utils.ts
+++ b/backend/apps/community/src/common/utils.ts
@@ -30,7 +30,7 @@ import { clickhouse } from './integrations/clickhouse'
import { BotsProtectionLevel, Project } from '../project/entity/project.entity'
import { ProjectViewEntity } from '../project/entity/project-view.entity'
-import { ClickhouseFunnel } from './types'
+import { ClickhouseFunnel, ClickhouseAnnotation } from './types'
dayjs.extend(utc)
@@ -224,14 +224,23 @@ const updateFunnelClickhouse = async (funnel: any) => {
{},
)
const columns = _keys(filtered)
- const values = _values(filtered)
- const query = `ALTER table funnel UPDATE ${_join(
- _map(columns, (col, id) => `${col}='${values[id]}'`),
- ', ',
- )} WHERE id='${funnel.id}'`
+
+ if (_isEmpty(columns)) {
+ return
+ }
+
+ const params: Record<string, string> = { id: funnel.id }
+
+ const assignments = _map(columns, col => {
+ params[col] = filtered[col]
+ return `${col}={${col}:String}`
+ }).join(', ')
+
+ const query = `ALTER TABLE funnel UPDATE ${assignments} WHERE id={id:String}`
await clickhouse.command({
query,
+ query_params: params,
})
}
@@ -360,14 +369,20 @@ const updateProjectClickhouse = async (
return
}
- const values = _values(filtered)
- const query = `ALTER table project UPDATE ${_join(
- _map(columns, (col, id) => `${col}='${values[id]}'`),
- ', ',
- )} WHERE id='${project.id}'`
+ const INT8_COLUMNS = ['active', 'public', 'isPasswordProtected']
+ const params: Record<string, any> = { id: project.id }
+
+ const assignments = _map(columns, col => {
+ params[col] = filtered[col]
+ const type = INT8_COLUMNS.includes(col) ? 'Int8' : 'String'
+ return `${col}={${col}:${type}}`
+ }).join(', ')
+
+ const query = `ALTER TABLE project UPDATE ${assignments} WHERE id={id:FixedString(12)}`
await clickhouse.command({
query,
+ query_params: params,
})
}
@@ -899,6 +914,126 @@ const updateProjectViewClickhouse = async (viewId: string, view: any) => {
const millisecondsToSeconds = (milliseconds: number) => milliseconds / 1000
+// Annotation functions
+const ALLOWED_ANNOTATION_KEYS = ['date', 'text']
+
+const getAnnotationsClickhouse = async (
+ projectId: string,
+): Promise<ClickhouseAnnotation[]> => {
+ const queryParams = {
+ projectId,
+ }
+
+ const query =
+ 'SELECT * FROM annotation WHERE projectId = {projectId:FixedString(12)} ORDER BY date ASC'
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: queryParams,
+ })
+ .then(resultSet => resultSet.json<ClickhouseAnnotation>())
+
+ return data
+}
+
+const getAnnotationClickhouse = async (
+ projectId: string,
+ annotationId: string,
+): Promise<ClickhouseAnnotation | null> => {
+ const queryParams = {
+ projectId,
+ annotationId,
+ }
+
+ const query = `
+ SELECT
+ *
+ FROM annotation
+ WHERE
+ projectId = {projectId:FixedString(12)}
+ AND id = {annotationId:String}`
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: queryParams,
+ })
+ .then(resultSet => resultSet.json<ClickhouseAnnotation>())
+
+ if (_isEmpty(data)) {
+ return null
+ }
+
+ return _head(data)
+}
+
+const createAnnotationClickhouse = async (
+ annotation: Partial<ClickhouseAnnotation>,
+) => {
+ const { id, date, text, projectId } = annotation
+
+ await clickhouse.insert({
+ table: 'annotation',
+ format: 'JSONEachRow',
+ values: [
+ {
+ id,
+ date,
+ text,
+ projectId,
+ created: dayjs.utc().format('YYYY-MM-DD HH:mm:ss'),
+ },
+ ],
+ })
+}
+
+const updateAnnotationClickhouse = async (annotation: {
+ id: string
+ date?: string
+ text?: string
+}) => {
+ const filtered = _reduce(
+ _filter(_keys(annotation), key => ALLOWED_ANNOTATION_KEYS.includes(key)),
+ (obj, key) => {
+ obj[key] = annotation[key]
+ return obj
+ },
+ {},
+ )
+ const columns = _keys(filtered)
+
+ if (_isEmpty(columns)) {
+ return
+ }
+
+ const params: Record<string, string> = { id: annotation.id }
+
+ const assignments = _map(columns, col => {
+ params[col] = filtered[col]
+ const type = col === 'date' ? 'Date' : 'String'
+ return `${col}={${col}:${type}}`
+ }).join(', ')
+
+ const query = `ALTER TABLE annotation UPDATE ${assignments} WHERE id={id:FixedString(36)}`
+
+ await clickhouse.command({
+ query,
+ query_params: params,
+ })
+}
+
+const deleteAnnotationClickhouse = async (id: string) => {
+ const query = `ALTER TABLE annotation DELETE WHERE id = {id:String}`
+
+ await clickhouse.command({
+ query,
+ query_params: {
+ id,
+ },
+ })
+}
+
export const isPrimaryNode = () => {
return process.env.IS_PRIMARY_NODE === 'true'
}
@@ -1057,4 +1192,10 @@ export {
deleteProjectSharesByProjectClickhouse,
deleteProjectSharesByUserIdClickhouse,
deleteProjectsByUserIdClickhouse,
+ // annotations
+ getAnnotationsClickhouse,
+ getAnnotationClickhouse,
+ createAnnotationClickhouse,
+ updateAnnotationClickhouse,
+ deleteAnnotationClickhouse,
}
diff --git a/backend/apps/community/src/project/dto/annotation-create.dto.ts b/backend/apps/community/src/project/dto/annotation-create.dto.ts
new file mode 100644
index 000000000..5f680a396
--- /dev/null
+++ b/backend/apps/community/src/project/dto/annotation-create.dto.ts
@@ -0,0 +1,30 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { IsNotEmpty, IsDateString, Length } from 'class-validator'
+
+export class AnnotationCreateDTO {
+ @ApiProperty({
+ example: 'aUn1quEid-3',
+ required: true,
+ description: 'Project ID',
+ })
+ @IsNotEmpty()
+ pid: string
+
+ @ApiProperty({
+ example: '2025-01-15',
+ required: true,
+ description: 'Date of the annotation (YYYY-MM-DD)',
+ })
+ @IsNotEmpty()
+ @IsDateString()
+ date: string
+
+ @ApiProperty({
+ example: 'Started Facebook ad campaign',
+ required: true,
+ description: 'Annotation text (max 120 characters)',
+ })
+ @IsNotEmpty()
+ @Length(1, 120)
+ text: string
+}
diff --git a/backend/apps/community/src/project/dto/annotation-update.dto.ts b/backend/apps/community/src/project/dto/annotation-update.dto.ts
new file mode 100644
index 000000000..e68aa0050
--- /dev/null
+++ b/backend/apps/community/src/project/dto/annotation-update.dto.ts
@@ -0,0 +1,38 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { IsNotEmpty, IsDateString, Length, IsOptional } from 'class-validator'
+
+export class AnnotationUpdateDTO {
+ @ApiProperty({
+ example: 'uuid-annotation-id',
+ required: true,
+ description: 'Annotation ID',
+ })
+ @IsNotEmpty()
+ id: string
+
+ @ApiProperty({
+ example: 'aUn1quEid-3',
+ required: true,
+ description: 'Project ID',
+ })
+ @IsNotEmpty()
+ pid: string
+
+ @ApiProperty({
+ example: '2025-01-15',
+ required: false,
+ description: 'Date of the annotation (YYYY-MM-DD)',
+ })
+ @IsOptional()
+ @IsDateString()
+ date?: string
+
+ @ApiProperty({
+ example: 'Updated annotation text',
+ required: false,
+ description: 'Annotation text (max 120 characters)',
+ })
+ @IsOptional()
+ @Length(1, 120)
+ text?: string
+}
diff --git a/backend/apps/community/src/project/dto/index.ts b/backend/apps/community/src/project/dto/index.ts
index 3ad6d3615..67d4f59aa 100644
--- a/backend/apps/community/src/project/dto/index.ts
+++ b/backend/apps/community/src/project/dto/index.ts
@@ -5,3 +5,5 @@ export * from './project-password.dto'
export * from './funnel-create.dto'
export * from './funnel-update.dto'
export * from './transfer-project.dto'
+export * from './annotation-create.dto'
+export * from './annotation-update.dto'
diff --git a/backend/apps/community/src/project/project.controller.ts b/backend/apps/community/src/project/project.controller.ts
index dfd181c23..67953fef1 100644
--- a/backend/apps/community/src/project/project.controller.ts
+++ b/backend/apps/community/src/project/project.controller.ts
@@ -60,6 +60,8 @@ import {
FunnelCreateDTO,
FunnelUpdateDTO,
TransferProjectBodyDto,
+ AnnotationCreateDTO,
+ AnnotationUpdateDTO,
} from './dto'
import { AppLoggerService } from '../logger/logger.service'
import { isValidPID } from '../common/constants'
@@ -90,6 +92,11 @@ import {
deleteProjectShareClickhouse,
deleteProjectSharesByProjectClickhouse,
ClickhouseProjectShare,
+ getAnnotationsClickhouse,
+ getAnnotationClickhouse,
+ createAnnotationClickhouse,
+ updateAnnotationClickhouse,
+ deleteAnnotationClickhouse,
} from '../common/utils'
import { Funnel } from './entity/funnel.entity'
import { ProjectViewEntity } from './entity/project-view.entity'
@@ -646,6 +653,132 @@ export class ProjectController {
)
}
+ @Post('/annotation')
+ @ApiResponse({ status: 201 })
+ @Auth(true)
+ async createAnnotation(
+ @Body() annotationDTO: AnnotationCreateDTO,
+ @CurrentUserId() userId: string,
+ ): Promise<any> {
+ this.logger.log({ annotationDTO, userId }, 'POST /project/annotation')
+
+ if (!userId) {
+ throw new UnauthorizedException('Please auth first')
+ }
+
+ const project = await this.projectService.getFullProject(annotationDTO.pid)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project was not found in the database')
+ }
+
+ this.projectService.allowedToManage(project, userId)
+
+ const annotation = {
+ id: randomUUID(),
+ date: annotationDTO.date,
+ text: annotationDTO.text,
+ projectId: annotationDTO.pid,
+ }
+
+ await createAnnotationClickhouse(annotation)
+
+ return annotation
+ }
+
+ @Patch('/annotation')
+ @ApiResponse({ status: 200 })
+ @Auth(true)
+ async updateAnnotation(
+ @Body() annotationDTO: AnnotationUpdateDTO,
+ @CurrentUserId() userId: string,
+ ): Promise<void> {
+ this.logger.log({ annotationDTO, userId }, 'PATCH /project/annotation')
+
+ if (!userId) {
+ throw new UnauthorizedException('Please auth first')
+ }
+
+ const project = await this.projectService.getFullProject(annotationDTO.pid)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project was not found in the database')
+ }
+
+ this.projectService.allowedToManage(project, userId)
+
+ const oldAnnotation = await getAnnotationClickhouse(
+ annotationDTO.pid,
+ annotationDTO.id,
+ )
+
+ if (!oldAnnotation) {
+ throw new NotFoundException('Annotation not found.')
+ }
+
+ await updateAnnotationClickhouse({
+ id: annotationDTO.id,
+ date: annotationDTO.date,
+ text: annotationDTO.text,
+ })
+ }
+
+ @Delete('/annotation/:id/:pid')
+ @ApiResponse({ status: 200 })
+ @Auth(true)
+ async deleteAnnotation(
+ @Param('id') id: string,
+ @Param('pid') pid: string,
+ @CurrentUserId() userId: string,
+ ): Promise<void> {
+ this.logger.log({ id, userId }, 'DELETE /project/annotation')
+
+ if (!userId) {
+ throw new UnauthorizedException('Please auth first')
+ }
+
+ const project = await this.projectService.getFullProject(pid)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project was not found in the database')
+ }
+
+ this.projectService.allowedToManage(project, userId)
+
+ const oldAnnotation = await getAnnotationClickhouse(pid, id)
+
+ if (!oldAnnotation) {
+ throw new NotFoundException('Annotation not found.')
+ }
+
+ await deleteAnnotationClickhouse(id)
+ }
+
+ @Get('/annotations/:pid')
+ @ApiResponse({ status: 200 })
+ @Auth(true)
+ async getAnnotations(
+ @Param('pid') pid: string,
+ @CurrentUserId() userId: string,
+ @Headers() headers: { 'x-password'?: string },
+ ): Promise<any> {
+ this.logger.log({ pid, userId }, 'GET /project/annotations')
+
+ if (!userId) {
+ throw new UnauthorizedException('Please auth first')
+ }
+
+ const project = await this.projectService.getFullProject(pid)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project was not found in the database')
+ }
+
+ this.projectService.allowedToView(project, userId, headers['x-password'])
+
+ return getAnnotationsClickhouse(pid)
+ }
+
@Get('password/:projectId')
@Auth(true, true)
@ApiResponse({ status: 200, type: Project })
diff --git a/backend/migrations/clickhouse/initialise_selfhosted.js b/backend/migrations/clickhouse/initialise_selfhosted.js
index bb75ae154..62aa7c8fa 100644
--- a/backend/migrations/clickhouse/initialise_selfhosted.js
+++ b/backend/migrations/clickhouse/initialise_selfhosted.js
@@ -93,6 +93,17 @@ const CLICKHOUSE_INIT_QUERIES = [
)
ENGINE = MergeTree()
PRIMARY KEY id;`,
+
+ `CREATE TABLE IF NOT EXISTS ${dbName}.annotation
+ (
+ id FixedString(36),
+ projectId FixedString(12),
+ date Date,
+ text String,
+ created DateTime
+ )
+ ENGINE = MergeTree()
+ PRIMARY KEY id;`,
]
const initialiseSelfhosted = async () => {
diff --git a/backend/migrations/clickhouse/selfhosted_2025_11_29.js b/backend/migrations/clickhouse/selfhosted_2025_11_29.js
new file mode 100644
index 000000000..ca37d7ed7
--- /dev/null
+++ b/backend/migrations/clickhouse/selfhosted_2025_11_29.js
@@ -0,0 +1,17 @@
+// This migration adds the annotation table for self-hosted instances
+const { queriesRunner, dbName } = require('./setup')
+
+const queries = [
+ `CREATE TABLE IF NOT EXISTS ${dbName}.annotation
+ (
+ id FixedString(36),
+ projectId FixedString(12),
+ date Date,
+ text String,
+ created DateTime
+ )
+ ENGINE = MergeTree()
+ PRIMARY KEY id;`,
+]
+
+queriesRunner(queries)