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!

Add error alerts functionality

Blue Mouse6260a9b60f13
diff --git a/backend/apps/cloud/src/alert/alert.controller.ts b/backend/apps/cloud/src/alert/alert.controller.ts
index dd7ce4b61..30f81cfcf 100644
--- a/backend/apps/cloud/src/alert/alert.controller.ts
+++ b/backend/apps/cloud/src/alert/alert.controller.ts
@@ -29,7 +29,13 @@ import { JwtAccessTokenGuard } from '../auth/guards'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
import { Roles } from '../auth/decorators/roles.decorator'
import { Alert } from './entity/alert.entity'
-import { AlertDTO, CreateAlertDTO } from './dto/alert.dto'
+import {
+ AlertDTO,
+ CreateAlertDTO,
+ QueryMetric,
+ QueryCondition,
+ QueryTime,
+} from './dto/alert.dto'
import { RolesGuard } from '../auth/guards/roles.guard'
import { AlertService } from './alert.service'
@@ -179,6 +185,22 @@ export class AlertController {
Object.assign(alert, alertDTO)
alert = _omit(alert, ['pid'])
+ if (alertDTO.queryMetric === QueryMetric.ERRORS) {
+ alert.queryCondition = null
+ alert.queryValue = null
+ alert.queryTime = null
+ } else {
+ if (alertDTO.queryCondition === undefined)
+ alert.queryCondition = QueryCondition.GREATER_THAN
+ if (alertDTO.queryValue === undefined) alert.queryValue = 0
+ if (alertDTO.queryTime === undefined)
+ alert.queryTime = QueryTime.LAST_1_HOUR
+ }
+
+ if (alertDTO.alertOnNewErrorsOnly === undefined) {
+ alert.alertOnNewErrorsOnly = true
+ }
+
const newAlert = await this.alertService.create(alert)
project.alerts.push(newAlert)
@@ -222,26 +244,44 @@ export class AlertController {
'You are not allowed to manage this alert',
)
- alert = {
- ...alert,
+ const updatePayload: Partial<Alert> = {
..._pick(alertDTO, [
'queryMetric',
- 'queryCondition',
- 'queryValue',
- 'queryTime',
- 'active',
'name',
'queryCustomEvent',
+ 'alertOnNewErrorsOnly',
+ 'active',
]),
}
+ if (alertDTO.queryMetric === QueryMetric.ERRORS) {
+ updatePayload.queryCondition = null
+ updatePayload.queryValue = null
+ updatePayload.queryTime = null
+ } else {
+ if (alertDTO.queryCondition !== undefined)
+ updatePayload.queryCondition = alertDTO.queryCondition
+ if (alertDTO.queryValue !== undefined)
+ updatePayload.queryValue = alertDTO.queryValue
+ if (alertDTO.queryTime !== undefined)
+ updatePayload.queryTime = alertDTO.queryTime
+ }
+
+ if (alertDTO.alertOnNewErrorsOnly !== undefined) {
+ updatePayload.alertOnNewErrorsOnly = alertDTO.alertOnNewErrorsOnly
+ }
+
await this.alertService.update(
id,
- _omit(alert, ['project', 'lastTriggered']),
+ _omit(updatePayload, ['project', 'lastTriggered']),
)
+ const updatedAlert = await this.alertService.findOne({ where: { id } })
+ if (!updatedAlert)
+ throw new NotFoundException('Alert not found after update')
+
return {
- ..._omit(alert, ['project']),
+ ..._omit(updatedAlert, ['project']),
pid: alert.project.id,
}
}
diff --git a/backend/apps/cloud/src/alert/dto/alert.dto.ts b/backend/apps/cloud/src/alert/dto/alert.dto.ts
index 00ca76e06..d4e38ecf4 100644
--- a/backend/apps/cloud/src/alert/dto/alert.dto.ts
+++ b/backend/apps/cloud/src/alert/dto/alert.dto.ts
@@ -1,11 +1,20 @@
-import { ApiProperty } from '@nestjs/swagger'
-import { IsEnum, IsNotEmpty, IsOptional, Length } from 'class-validator'
+import { ApiProperty, PartialType } from '@nestjs/swagger'
+import {
+ IsEnum,
+ IsNotEmpty,
+ IsOptional,
+ Length,
+ IsBoolean,
+ IsString,
+ IsNumber,
+} from 'class-validator'
export enum QueryMetric {
PAGE_VIEWS = 'page_views',
UNIQUE_PAGE_VIEWS = 'unique_page_views',
ONLINE_USERS = 'online_users',
CUSTOM_EVENTS = 'custom_events',
+ ERRORS = 'errors',
}
export enum QueryCondition {
@@ -24,70 +33,53 @@ export enum QueryTime {
LAST_48_HOURS = 'last_48_hours',
}
-export class AlertDTO {
+class AlertBaseDTO {
@ApiProperty()
@IsNotEmpty()
@Length(1, 50)
- name?: string
+ name: string
- @ApiProperty()
- @IsOptional()
+ @ApiProperty({ enum: QueryMetric })
+ @IsNotEmpty()
@IsEnum(QueryMetric)
- queryMetric?: QueryMetric
+ queryMetric: QueryMetric
- @ApiProperty()
+ @ApiProperty({ enum: QueryCondition, nullable: true })
+ @IsEnum(QueryCondition)
@IsOptional()
- queryCondition?: QueryCondition
+ queryCondition: QueryCondition | null
- @ApiProperty()
+ @ApiProperty({ nullable: true })
+ @IsNumber()
@IsOptional()
- queryValue?: number
+ queryValue: number | null
- @ApiProperty()
+ @ApiProperty({ enum: QueryTime, nullable: true })
+ @IsEnum(QueryTime)
@IsOptional()
- queryTime?: QueryTime
+ queryTime: QueryTime | null
@ApiProperty()
+ @IsBoolean()
@IsOptional()
active?: boolean
@ApiProperty()
+ @IsString()
@IsOptional()
queryCustomEvent?: string
-}
-
-export class CreateAlertDTO {
- @ApiProperty()
- @IsNotEmpty()
- pid: string
-
- @ApiProperty()
- @IsNotEmpty()
- @Length(1, 50)
- name: string
-
- @ApiProperty()
- @IsNotEmpty()
- @IsEnum(QueryMetric)
- queryMetric: QueryMetric
-
- @ApiProperty()
- @IsNotEmpty()
- queryCondition: QueryCondition
-
- @ApiProperty()
- @IsNotEmpty()
- queryValue: number
@ApiProperty()
- @IsNotEmpty()
- queryTime: QueryTime
+ @IsBoolean()
+ @IsOptional()
+ alertOnNewErrorsOnly?: boolean
+}
+export class CreateAlertDTO extends AlertBaseDTO {
@ApiProperty()
+ @IsString()
@IsNotEmpty()
- active: boolean
-
- @ApiProperty()
- @IsOptional()
- queryCustomEvent?: string
+ pid: string
}
+
+export class AlertDTO extends PartialType(AlertBaseDTO) {}
diff --git a/backend/apps/cloud/src/alert/entity/alert.entity.ts b/backend/apps/cloud/src/alert/entity/alert.entity.ts
index 44cac497f..a2724ea4e 100644
--- a/backend/apps/cloud/src/alert/entity/alert.entity.ts
+++ b/backend/apps/cloud/src/alert/entity/alert.entity.ts
@@ -18,10 +18,18 @@ export class Alert {
@ApiProperty()
@Column({
+ type: 'boolean',
default: true,
})
active: boolean
+ @Column({
+ type: 'boolean',
+ default: true,
+ name: 'alert_on_new_errors_only',
+ })
+ alertOnNewErrorsOnly: boolean
+
@Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
created: Date
diff --git a/backend/apps/cloud/src/integrations/telegram/telegram.service.ts b/backend/apps/cloud/src/integrations/telegram/telegram.service.ts
index 31a8f14fd..65386bdb6 100644
--- a/backend/apps/cloud/src/integrations/telegram/telegram.service.ts
+++ b/backend/apps/cloud/src/integrations/telegram/telegram.service.ts
@@ -7,6 +7,7 @@ import { Repository } from 'typeorm'
import { Context } from './interface/context.interface'
import { Message } from './entities/message.entity'
import { UserService } from '../../user/user.service'
+import { ExtraReplyMessage } from 'telegraf/typings/telegram-types'
@Injectable()
export class TelegramService {
@@ -24,7 +25,7 @@ export class TelegramService {
)
let text: string
- let extra: unknown = {}
+ let extra: ExtraReplyMessage = {}
if (!user) {
text =
@@ -39,6 +40,7 @@ export class TelegramService {
'\n\n' +
'After that, you can use the bot to manage your projects.'
extra = {
+ // @ts-expect-error ??
disable_web_page_preview: true,
reply_markup: { remove_keyboard: true },
}
@@ -102,11 +104,19 @@ export class TelegramService {
})
}
+ escapeTelegramMarkdownV2(text?: string | null) {
+ if (text === null || text === undefined) return ''
+
+ // Characters to escape for MarkdownV2: _ * [ ] ( ) ~ ` > # + - = | { } . !
+ const charsToEscapeRegex = /[_*[\]()~`>#+\-=|{}.!]/g
+ return text.replace(charsToEscapeRegex, '\\$&')
+ }
+
async sendMessage(
messageId: string,
chatId: string,
text: string,
- extra?: unknown,
+ extra?: ExtraReplyMessage,
) {
if (
this.configService.get<string>('ENABLE_INTEGRATIONS') !== 'true' &&
diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.ts
index d53539793..f291e63fc 100644
--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts
+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts
@@ -1011,8 +1011,11 @@ export class TaskManagerService {
})
}
- @Cron(CronExpression.EVERY_5_MINUTES)
+ // @Cron(CronExpression.EVERY_5_MINUTES)
+ @Cron(CronExpression.EVERY_MINUTE)
async checkMetricAlerts() {
+ const CRON_INTERVAL_SECONDS = 60
+
const projects = await this.projectService.find({
where: {
admin: {
@@ -1035,7 +1038,10 @@ export class TaskManagerService {
const promises = _map(alerts, async alert => {
const project = _find(projects, { id: alert.project.id })
- if (alert.lastTriggered !== null) {
+ if (
+ alert.lastTriggered !== null &&
+ alert.queryMetric !== QueryMetric.ERRORS
+ ) {
const lastTriggered = new Date(alert.lastTriggered)
const now = new Date()
@@ -1044,51 +1050,224 @@ export class TaskManagerService {
}
}
- const isUnique = Number(
- alert.queryMetric === QueryMetric.UNIQUE_PAGE_VIEWS,
- )
- const time = getQueryTime(alert.queryTime)
- const query =
- alert.queryMetric === QueryMetric.CUSTOM_EVENTS
- ? `SELECT count() FROM customEV WHERE pid='${project.id}' AND ev={ev:String} AND created >= now() - ${time}`
- : `SELECT count(${isUnique ? 'DISTINCT psid' : '*'}) FROM analytics WHERE pid='${project.id}' AND created >= now() - ${time}`
-
- const params = {
- ev: alert.queryCustomEvent,
+ let query: string
+ const queryParams: Record<string, any> = { pid: project.id }
+
+ let startTimestampForQuery: string
+ if (alert.lastTriggered) {
+ startTimestampForQuery = dayjs
+ .utc(alert.lastTriggered)
+ .format('YYYY-MM-DD HH:mm:ss')
+ } else {
+ startTimestampForQuery = dayjs
+ .utc()
+ .subtract(CRON_INTERVAL_SECONDS, 'second')
+ .format('YYYY-MM-DD HH:mm:ss')
+ }
+ queryParams.startTimestampVal = startTimestampForQuery
+
+ const timeToUseForOtherMetrics =
+ alert.queryMetric === QueryMetric.ERRORS
+ ? CRON_INTERVAL_SECONDS
+ : getQueryTime(alert.queryTime as QueryTime)
+
+ if (alert.queryMetric === QueryMetric.ERRORS) {
+ if (alert.alertOnNewErrorsOnly) {
+ query = `
+ SELECT count() AS total_new_errors
+ FROM (
+ SELECT eid, min(created) as first_seen
+ FROM errors
+ WHERE pid = {pid:FixedString(12)}
+ GROUP BY eid
+ )
+ WHERE first_seen >= toDateTime({startTimestampVal:String})
+ `
+ } else {
+ query = `SELECT count() FROM errors WHERE pid = {pid:FixedString(12)} AND created >= toDateTime({startTimestampVal:String})`
+ }
+ } else if (alert.queryMetric === QueryMetric.CUSTOM_EVENTS) {
+ query = `SELECT count() FROM customEV WHERE pid = {pid:FixedString(12)} AND ev = {ev:String} AND created >= now() - ${timeToUseForOtherMetrics}`
+ queryParams.ev = alert.queryCustomEvent
+ } else {
+ const isUnique = alert.queryMetric === QueryMetric.UNIQUE_PAGE_VIEWS
+ query = `SELECT count(${isUnique ? 'DISTINCT psid' : '*'}) FROM analytics WHERE pid = {pid:FixedString(12)} AND created >= now() - ${timeToUseForOtherMetrics}`
}
const { data: queryResult } = await clickhouse
.query({
query,
- query_params: params,
+ query_params: queryParams,
})
.then(resultSet => resultSet.json())
- const count = Number(queryResult[0]['count()'])
+ const count = Number(
+ queryResult[0]['count()'] || queryResult[0]['total_new_errors'] || 0,
+ )
+
+ const conditionMet =
+ alert.queryMetric === QueryMetric.ERRORS
+ ? count > 0
+ : checkQueryCondition(
+ count,
+ alert.queryValue as number,
+ alert.queryCondition as QueryCondition,
+ )
+
+ if (conditionMet) {
+ let errorDetails: {
+ eid: string
+ name: string
+ message?: string | null
+ lineno?: number | null
+ colno?: number | null
+ filename?: string | null
+ } | null = null
+
+ if (alert.queryMetric === QueryMetric.ERRORS && count > 0) {
+ let detailQuery: string
+ const detailQueryParams: Record<string, any> = {
+ pid_val: project.id,
+ startTimestampVal: queryParams.startTimestampVal,
+ }
+
+ if (alert.alertOnNewErrorsOnly) {
+ detailQuery = `
+ SELECT eid, name, message, lineno, colno, filename
+ FROM errors
+ WHERE pid = {pid_val:FixedString(12)} AND eid IN (
+ SELECT eid
+ FROM (
+ SELECT eid, min(created) AS first_seen_for_eid
+ FROM errors
+ WHERE pid = {pid_val:FixedString(12)}
+ GROUP BY eid
+ )
+ WHERE first_seen_for_eid >= toDateTime({startTimestampVal:String})
+ )
+ ORDER BY created DESC
+ LIMIT 1
+ `
+ } else {
+ detailQuery = `
+ SELECT eid, name, message, lineno, colno, filename
+ FROM errors
+ WHERE pid = {pid_val:FixedString(12)} AND created >= toDateTime({startTimestampVal:String})
+ ORDER BY created DESC
+ LIMIT 1
+ `
+ }
+ try {
+ const { data: errorDetailResult } = await clickhouse
+ .query({ query: detailQuery, query_params: detailQueryParams })
+ .then(resultSet => resultSet.json())
+ if (errorDetailResult && errorDetailResult.length > 0) {
+ errorDetails = errorDetailResult[0] as typeof errorDetails
+ }
+ } catch (e) {
+ this.logger.error(
+ `[CRON WORKER](checkMetricAlerts) Error fetching error details: ${e}`,
+ )
+ }
+ }
+
+ console.log('errorDetails', errorDetails)
- if (checkQueryCondition(count, alert.queryValue, alert.queryCondition)) {
// @ts-expect-error
await this.alertService.update(alert.id, {
lastTriggered: new Date(),
})
- const queryMetric =
- 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}*${
- alert.queryMetric === QueryMetric.CUSTOM_EVENTS
- ? ` "${alert.queryCustomEvent}"`
- : ''
- } ${queryMetric} in the last ${getQueryTimeString(alert.queryTime)}!`
+ let queryMetricString = ''
+ switch (alert.queryMetric) {
+ case QueryMetric.CUSTOM_EVENTS:
+ queryMetricString = 'custom events'
+ break
+ case QueryMetric.UNIQUE_PAGE_VIEWS:
+ queryMetricString = 'unique page views'
+ break
+ case QueryMetric.PAGE_VIEWS:
+ queryMetricString = 'page views'
+ break
+ case QueryMetric.ERRORS:
+ queryMetricString = alert.alertOnNewErrorsOnly
+ ? 'new errors'
+ : 'errors'
+ break
+ default:
+ queryMetricString = alert.queryMetric
+ }
+
+ const effectiveQueryTimeString =
+ alert.queryMetric === QueryMetric.ERRORS
+ ? `${CRON_INTERVAL_SECONDS / 60} minutes`
+ : getQueryTimeString(alert.queryTime as QueryTime)
+
+ let text = ``
+ if (alert.queryMetric === QueryMetric.ERRORS && errorDetails) {
+ // const clientUrl = this.configService.get('CLIENT_URL')
+ // const escapedErrorLink =
+ // this.telegramService.escapeTelegramMarkdownV2(
+ // `${clientUrl}/projects/${project.id}?tab=errors&eid=${errorDetails.eid}`,
+ // )
+ // const escapedProjectLink =
+ // this.telegramService.escapeTelegramMarkdownV2(
+ // `${clientUrl}/projects/${project.id}`,
+ // )
+
+ // Values are now raw, not pre-escaped
+ const alertName = alert.name
+ const projectName = project.name
+ const errorName = errorDetails.name || 'N/A'
+ const errorMessage = errorDetails.message || 'N/A'
+ const filename = errorDetails.filename || 'N/A'
+
+ let locationInfo = 'Location: Not available'
+ if (
+ errorDetails.filename ||
+ errorDetails.lineno !== null ||
+ errorDetails.colno !== null
+ ) {
+ const ln =
+ errorDetails.lineno !== null
+ ? errorDetails.lineno.toString()
+ : 'N/A'
+ const cn =
+ errorDetails.colno !== null
+ ? errorDetails.colno.toString()
+ : 'N/A'
+ locationInfo = `File: ${filename}, Line: ${ln}, Col: ${cn}`
+ }
+
+ text =
+ `πŸ”” Alert *${this.telegramService.escapeTelegramMarkdownV2(alertName)}* triggered\\!\n\n` +
+ // `Project: [${this.telegramService.escapeTelegramMarkdownV2(projectName)}]\\(${escapedProjectLink}\\)\n` +
+ `Project: ${projectName}\n` +
+ `Error: ${this.telegramService.escapeTelegramMarkdownV2(errorName)}\n` +
+ `Message: ${this.telegramService.escapeTelegramMarkdownV2(errorMessage)}\n\n` +
+ `${this.telegramService.escapeTelegramMarkdownV2(locationInfo)}\n\n` // +
+ // `[View error](${escapedErrorLink})`
+ } else {
+ const alertName = alert.name
+ const projectName = project.name
+
+ let customEventInfo = ''
+ if (
+ alert.queryMetric === QueryMetric.CUSTOM_EVENTS &&
+ alert.queryCustomEvent
+ ) {
+ customEventInfo = ` "${alert.queryCustomEvent}"`
+ }
+
+ text =
+ `πŸ”” Alert *${this.telegramService.escapeTelegramMarkdownV2(alertName)}* triggered\\!\n\n` +
+ `Your project *${this.telegramService.escapeTelegramMarkdownV2(projectName)}* has had *${count}${customEventInfo}* ${queryMetricString} in the last *${effectiveQueryTimeString}*\\!`
+ }
if (project.admin && project.admin.isTelegramChatIdConfirmed) {
this.telegramService.addMessage(project.admin.telegramChatId, text, {
- parse_mode: 'Markdown',
+ parse_mode: 'MarkdownV2',
+ disable_web_page_preview: true,
})
}
@@ -1224,6 +1403,7 @@ export class TaskManagerService {
const messages = await this.telegramService.getMessages()
messages.forEach(async message => {
+ console.log('message', message)
try {
await this.telegramService.sendMessage(
message.id,
@@ -1231,10 +1411,11 @@ export class TaskManagerService {
message.text,
message.extra,
)
- } catch (e) {
+ } catch (reason) {
this.logger.error(
- `[CRON WORKER](sendTelegramMessages) Error occured while sending message: ${e}`,
+ `[CRON WORKER](sendTelegramMessages) Error occured while sending message: ${reason}`,
)
+ } finally {
await this.telegramService.deleteMessage(message.id)
}
})
diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.ts
index 03cd5e78f..55084283e 100644
--- a/web/app/lib/constants/index.ts
+++ b/web/app/lib/constants/index.ts
@@ -459,6 +459,7 @@ export const QUERY_METRIC = {
UNIQUE_PAGE_VIEWS: 'unique_page_views',
ONLINE_USERS: 'online_users',
CUSTOM_EVENTS: 'custom_events',
+ ERRORS: 'errors',
} as const
export const QUERY_CONDITION = {
diff --git a/web/app/lib/models/Alerts.ts b/web/app/lib/models/Alerts.ts
index 88c4558e7..90ecaea17 100644
--- a/web/app/lib/models/Alerts.ts
+++ b/web/app/lib/models/Alerts.ts
@@ -2,14 +2,15 @@ import { QUERY_METRIC, QUERY_CONDITION, QUERY_TIME } from '../constants'
export interface Alerts {
id: string
+ pid: string
+ uid?: string
name: string
- active: boolean
- created: string
- lastTriggered: string | null
queryMetric: (typeof QUERY_METRIC)[keyof typeof QUERY_METRIC]
- queryCondition: (typeof QUERY_CONDITION)[keyof typeof QUERY_CONDITION]
- queryValue: number
- queryTime: (typeof QUERY_TIME)[keyof typeof QUERY_TIME]
- pid: string
+ queryCondition: (typeof QUERY_CONDITION)[keyof typeof QUERY_CONDITION] | null
+ queryValue: number | null
+ queryTime: (typeof QUERY_TIME)[keyof typeof QUERY_TIME] | null
queryCustomEvent?: string
+ active: boolean
+ lastTriggered?: Date
+ alertOnNewErrorsOnly?: boolean
}
diff --git a/web/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx b/web/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx
index 0b047887f..3175ab76e 100644
--- a/web/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx
+++ b/web/app/pages/Project/Alerts/Settings/ProjectAlertsSettings.tsx
@@ -45,8 +45,10 @@ const ProjectAlertsSettings = ({ isSettings }: ProjectAlertsSettingsProps) => {
queryTime: QUERY_TIME.LAST_1_HOUR,
queryCondition: QUERY_CONDITION.GREATER_THAN,
queryMetric: QUERY_METRIC.PAGE_VIEWS,
+ queryValue: 10,
active: true,
queryCustomEvent: '',
+ alertOnNewErrorsOnly: true,
})
const [validated, setValidated] = useState(false)
const [errors, setErrors] = useState<Record<string, string>>({})
@@ -162,6 +164,17 @@ const ProjectAlertsSettings = ({ isSettings }: ProjectAlertsSettingsProps) => {
}
}, [alert])
+ useEffect(() => {
+ if (form.queryMetric === QUERY_METRIC.ERRORS) {
+ setForm((prevForm) => ({
+ ...prevForm,
+ queryCondition: undefined,
+ queryValue: undefined,
+ queryTime: undefined,
+ }))
+ }
+ }, [form.queryMetric])
+
const validate = () => {
const allErrors: Record<string, string> = {}
@@ -173,8 +186,10 @@ const ProjectAlertsSettings = ({ isSettings }: ProjectAlertsSettingsProps) => {
allErrors.queryCustomEvent = t('alert.noCustomEventError')
}
- if (Number.isNaN(_toNumber(form.queryValue))) {
- allErrors.queryValue = t('alert.queryValueError')
+ if (form.queryMetric !== QUERY_METRIC.ERRORS) {
+ if (form.queryValue === undefined || Number.isNaN(_toNumber(form.queryValue))) {
+ allErrors.queryValue = t('alert.queryValueError')
+ }
}
const valid = _isEmpty(_keys(allErrors))
@@ -184,8 +199,18 @@ const ProjectAlertsSettings = ({ isSettings }: ProjectAlertsSettingsProps) => {
}
const onSubmit = (data: Partial<Alerts>) => {
+ let submissionData = { ...data }
+ if (data.queryMetric === QUERY_METRIC.ERRORS) {
+ submissionData = {
+ ...submissionData,
+ queryCondition: null,
+ queryValue: null,
+ queryTime: null,
+ }
+ }
+
if (isSettings) {
- updateAlert(id as string, data)
+ updateAlert(id as string, submissionData)
.then((res) => {
navigate(`/projects/${pid}?tab=${PROJECT_TABS.alerts}`)
setAlert(res)
@@ -195,7 +220,7 @@ const ProjectAlertsSettings = ({ isSettings }: ProjectAlertsSettingsProps) => {
toast.error(reason.message || reason || 'Something went wrong')
})
} else {
- createAlert(data as CreateAlert)
+ createAlert(submissionData as CreateAlert)
.then(() => {
navigate(`/projects/${pid}?tab=${PROJECT_TABS.alerts}`)
toast.success(t('alertsSettings.alertCreated'))
@@ -240,8 +265,18 @@ const ProjectAlertsSettings = ({ isSettings }: ProjectAlertsSettingsProps) => {
e.stopPropagation()
setBeenSubmitted(true)
+ let currentForm = { ...form }
+ if (form.queryMetric === QUERY_METRIC.ERRORS) {
+ currentForm = {
+ ...currentForm,
+ queryCondition: null,
+ queryValue: null,
+ queryTime: null,
+ }
+ }
+
if (validated) {
- onSubmit(form)
+ onSubmit(currentForm)
}
}
@@ -369,51 +404,72 @@ const ProjectAlertsSettings = ({ isSettings }: ProjectAlertsSettingsProps) => {
error={beenSubmitted ? errors.queryCustomEvent : null}
/>
) : null}
- <div className='mt-4'>
- <Select
- id='queryCondition'
- label={t('alert.condition')}
- items={_values(queryConditionTMapping)}
- title={form.queryCondition ? queryConditionTMapping[form.queryCondition] : ''}
- onSelect={(item) => {
- const key = _findKey(queryConditionTMapping, (predicate) => predicate === item)
-
- // @ts-expect-error
- setForm((prevForm) => ({
- ...prevForm,
- queryCondition: key,
+ {form.queryMetric === QUERY_METRIC.ERRORS ? (
+ <Checkbox
+ checked={Boolean(form.alertOnNewErrorsOnly)}
+ onChange={(checked) =>
+ setForm((prev) => ({
+ ...prev,
+ alertOnNewErrorsOnly: checked,
}))
+ }
+ name='alertOnNewErrorsOnly'
+ classes={{
+ label: 'mt-4',
}}
- capitalise
+ label={t('alert.newErrorsOnly')}
+ hint={t('alert.newErrorsOnlyHint')}
/>
- </div>
- <Input
- name='queryValue'
- label={t('alert.threshold')}
- value={form.queryValue || ''}
- placeholder='10'
- className='mt-4'
- onChange={handleInput}
- error={beenSubmitted ? errors.queryValue : null}
- />
- <div className='mt-4'>
- <Select
- id='queryTime'
- label={t('alert.time')}
- items={_values(queryTimeTMapping)}
- title={form.queryTime ? queryTimeTMapping[form.queryTime] : ''}
- onSelect={(item) => {
- const key = _findKey(queryTimeTMapping, (predicate) => predicate === item)
-
- // @ts-expect-error
- setForm((prevForm) => ({
- ...prevForm,
- queryTime: key,
- }))
- }}
- capitalise
- />
- </div>
+ ) : null}
+ {form.queryMetric !== QUERY_METRIC.ERRORS ? (
+ <>
+ <div className='mt-4'>
+ <Select
+ id='queryCondition'
+ label={t('alert.condition')}
+ items={_values(queryConditionTMapping)}
+ title={form.queryCondition ? queryConditionTMapping[form.queryCondition] : ''}
+ onSelect={(item) => {
+ const key = _findKey(queryConditionTMapping, (predicate) => predicate === item)
+
+ // @ts-expect-error
+ setForm((prevForm) => ({
+ ...prevForm,
+ queryCondition: key,
+ }))
+ }}
+ capitalise
+ />
+ </div>
+ <Input
+ name='queryValue'
+ label={t('alert.threshold')}
+ value={form.queryValue || ''}
+ placeholder='10'
+ className='mt-4'
+ onChange={handleInput}
+ error={beenSubmitted ? errors.queryValue : null}
+ />
+ <div className='mt-4'>
+ <Select
+ id='queryTime'
+ label={t('alert.time')}
+ items={_values(queryTimeTMapping)}
+ title={form.queryTime ? queryTimeTMapping[form.queryTime] : ''}
+ onSelect={(item) => {
+ const key = _findKey(queryTimeTMapping, (predicate) => predicate === item)
+
+ // @ts-expect-error
+ setForm((prevForm) => ({
+ ...prevForm,
+ queryTime: key,
+ }))
+ }}
+ capitalise
+ />
+ </div>
+ </>
+ ) : null}
{isSettings ? (
<div className='mt-5 flex items-center justify-between'>
<Button onClick={() => setShowModal(true)} danger semiSmall>
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index da8e95f27..db270458f 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -770,6 +770,8 @@
"alert": {
"create": "Create an alert",
"customEvent": "Custom event name",
+ "newErrorsOnly": "Alert on new errors only",
+ "newErrorsOnlyHint": "If enabled, an alert will be triggered only for the first occurrence of a specific error.",
"add": "Add alert",
"delete": "Delete alert",
"noNameError": "Please enter a name for the alert.",
@@ -803,7 +805,8 @@
"page_views": "Page views",
"unique_page_views": "Unique sessions",
"online_users": "Online users",
- "custom_events": "Custom events"
+ "custom_events": "Custom events",
+ "errors": "Errors"
}
},
"error": {