π 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
(feature) Alerts for custom events (#181)
Maksim Mrug745f1c345bd0
diff --git a/apps/production/src/alert/alert.controller.ts b/apps/production/src/alert/alert.controller.tsindex ec7db5c8f..925514286 100644--- a/apps/production/src/alert/alert.controller.ts+++ b/apps/production/src/alert/alert.controller.ts@@ -189,6 +189,7 @@ export class AlertController {'queryTime','active','name',+ 'queryCustomEvent',]),}diff --git a/apps/production/src/alert/alert.service.ts b/apps/production/src/alert/alert.service.tsindex a215b6627..2763e8131 100644--- a/apps/production/src/alert/alert.service.ts+++ b/apps/production/src/alert/alert.service.ts@@ -1,7 +1,7 @@import { Injectable } from '@nestjs/common'import { InjectRepository } from '@nestjs/typeorm'import { Repository } from 'typeorm'-import { Pagination, PaginationOptionsInterface } from 'src/common/pagination'+import { Pagination, PaginationOptionsInterface } from '../common/pagination'import { Alert } from './entity/alert.entity'import { AlertDTO } from './dto/alert.dto'@@ -65,8 +65,8 @@ export class AlertService {return this.alertsReporsitory.findOne({ where, ...params })}- async create(project: AlertDTO | Alert): Promise<Alert> {- return this.alertsReporsitory.save(project)+ async create(alert: AlertDTO | Alert): Promise<Alert> {+ return this.alertsReporsitory.save(alert)}async update(id: string, alertDTO: AlertDTO | Alert): Promise<any> {diff --git a/apps/production/src/alert/dto/alert.dto.ts b/apps/production/src/alert/dto/alert.dto.tsindex 1fa2084d8..00ca76e06 100644--- a/apps/production/src/alert/dto/alert.dto.ts+++ b/apps/production/src/alert/dto/alert.dto.ts@@ -5,6 +5,7 @@ export enum QueryMetric {PAGE_VIEWS = 'page_views',UNIQUE_PAGE_VIEWS = 'unique_page_views',ONLINE_USERS = 'online_users',+ CUSTOM_EVENTS = 'custom_events',}export enum QueryCondition {@@ -49,6 +50,10 @@ export class AlertDTO {@ApiProperty()@IsOptional()active?: boolean++ @ApiProperty()+ @IsOptional()+ queryCustomEvent?: string}export class CreateAlertDTO {@@ -81,4 +86,8 @@ export class CreateAlertDTO {@ApiProperty()@IsNotEmpty()active: boolean++ @ApiProperty()+ @IsOptional()+ queryCustomEvent?: string}diff --git a/apps/production/src/alert/entity/alert.entity.ts b/apps/production/src/alert/entity/alert.entity.tsindex 4cede0045..44cac497f 100644--- a/apps/production/src/alert/entity/alert.entity.ts+++ b/apps/production/src/alert/entity/alert.entity.ts@@ -1,8 +1,8 @@import { Entity, Column, ManyToOne, PrimaryGeneratedColumn } from 'typeorm'import { ApiProperty } from '@nestjs/swagger'-import { Project } from 'src/project/entity/project.entity'-import { QueryCondition, QueryMetric, QueryTime } from 'src/alert/dto/alert.dto'+import { Project } from '../../project/entity/project.entity'+import { QueryCondition, QueryMetric, QueryTime } from '../dto/alert.dto'@Entity()export class Alert {@@ -67,4 +67,12 @@ export class Alert {default: null,})queryTime: QueryTime++ @ApiProperty()+ @Column({+ type: 'varchar',+ nullable: true,+ default: null,+ })+ queryCustomEvent: string}diff --git a/apps/production/src/task-manager/task-manager.service.ts b/apps/production/src/task-manager/task-manager.service.tsindex 3c960825f..5024465aa 100644--- a/apps/production/src/task-manager/task-manager.service.ts+++ b/apps/production/src/task-manager/task-manager.service.ts@@ -781,8 +781,8 @@ export class TaskManagerService {})}- @Cron(CronExpression.EVERY_5_MINUTES)- // @Cron(CronExpression.EVERY_5_SECONDS)+ // @Cron(CronExpression.EVERY_5_MINUTES)+ @Cron(CronExpression.EVERY_5_SECONDS)async checkMetricAlerts(): Promise<void> {const projects = await this.projectService.findWhere({@@ -820,8 +820,15 @@ export class TaskManagerService {)const time = getQueryTime(alert.queryTime)const createdCondition = getQueryCondition(alert.queryCondition)- const query = `SELECT count() FROM analytics WHERE pid = '${project.id}' AND unique = '${isUnique}' AND created ${createdCondition} now() - ${time}`- const queryResult = await clickhouse.query(query).toPromise()+ const query =+ alert.queryMetric === QueryMetric.CUSTOM_EVENTS+ ? `SELECT count() FROM customEV WHERE pid='${project.id}' AND ev={ev:String} AND created ${createdCondition} now() - ${time}`+ : `SELECT count() FROM analytics WHERE pid='${project.id}' AND unique = '${isUnique}' AND created ${createdCondition} now() - ${time}`++ const params = {+ ev: alert.queryCustomEvent,+ }+ const queryResult = await clickhouse.query(query, { params }).toPromise()const count = Number(queryResult[0]['count()'])@@ -832,14 +839,18 @@ export class TaskManagerService {})const queryMetric =- alert.queryMetric === QueryMetric.UNIQUE_PAGE_VIEWS+ alert.queryMetric === QueryMetric.CUSTOM_EVENTS+ ? 'custom events'+ : alert.queryMetric === QueryMetric.UNIQUE_PAGE_VIEWS? 'unique page views': 'page views'const text = `π Alert *${alert.name}* got triggered!\nYour project *${project.name- }* has had *${count}* ${queryMetric} in the last ${getQueryTimeString(- alert.queryTime,- )}!`+ }* has had *${count}*${+ alert.queryMetric === QueryMetric.CUSTOM_EVENTS+ ? ` "${alert.queryCustomEvent}"`+ : ''+ } ${queryMetric} in the last ${getQueryTimeString(alert.queryTime)}!`if (project.admin && project.admin.isTelegramChatIdConfirmed) {this.telegramService.addMessage(project.admin.telegramChatId, text, {diff --git a/migrations/mysql/2023_08_09.sql b/migrations/mysql/2023_08_09.sqlnew file mode 100644index 000000000..cf0afe1c6--- /dev/null+++ b/migrations/mysql/2023_08_09.sql@@ -0,0 +1,2 @@+alter table alert modify column `queryMetric` enum('page_views','unique_page_views','online_users','custom_events') DEFAULT NULL after lastTriggered;+alter table alert add column `queryCustomEvent` varchar(255) DEFAULT NULL after queryTime;