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!

Hell's torment is over.

Yevhenii Kulisidid6e5955133d3
diff --git a/src/analytics/analytics.controller.ts b/src/analytics/analytics.controller.ts
index 78d901054..6cadd838f 100644
--- a/src/analytics/analytics.controller.ts
+++ b/src/analytics/analytics.controller.ts
@@ -707,7 +707,9 @@ export class AnalyticsController {
await Promise.all(keyCountPromises).catch(reason => {
this.logger.error(`[@Get('/hb')] ${reason}`)
- throw new InternalServerErrorException('An error occured while calculating heartbeat statistics')
+ throw new InternalServerErrorException(
+ 'An error occured while calculating heartbeat statistics',
+ )
})
return result
@@ -1058,4 +1060,166 @@ export class AnalyticsController {
res.writeHead(200, { 'Content-Type': 'image/gif' })
return res.end(TRANSPARENT_GIF_BUFFER, 'binary')
}
+
+ @Get('custom-events')
+ @Auth([], true, true)
+ async getCustomEvents(
+ @Query() data: AnalyticsGET_DTO,
+ @CurrentUserId() uid: string,
+ ): Promise<any> {
+ const {
+ pid,
+ period,
+ timeBucket,
+ from,
+ to,
+ filters,
+ timezone = DEFAULT_TIMEZONE,
+ } = data
+ this.analyticsService.validatePID(pid)
+
+ if (!_isEmpty(period)) {
+ this.analyticsService.validatePeriod(period)
+ }
+
+ this.analyticsService.validateTimebucket(timeBucket)
+ const [filtersQuery, filtersParams] =
+ this.analyticsService.getFiltersQuery(filters)
+ await this.analyticsService.checkProjectAccess(pid, uid)
+
+ let groupFrom = from
+ let groupTo = to
+
+ const queryCustoms = `SELECT ev, count() FROM customEV WHERE pid = {pid:FixedString(12)} ${filtersQuery} AND created BETWEEN {groupFrom:String} AND {groupTo:String} GROUP BY ev`
+ const subQuery = `FROM customEV WHERE pid = {pid:FixedString(12)} ${filtersQuery} AND created BETWEEN {groupFrom:String} AND {groupTo:String}`
+
+ const paramsData = {
+ params: {
+ pid,
+ groupFrom: null,
+ groupTo: null,
+ ...filtersParams,
+ },
+ }
+
+ if (!_isEmpty(from) && !_isEmpty(to)) {
+ if (!isValidDate(from)) {
+ throw new PreconditionFailedException(
+ "The timeframe 'from' parameter is invalid",
+ )
+ }
+
+ if (!isValidDate(to)) {
+ throw new PreconditionFailedException(
+ "The timeframe 'to' parameter is invalid",
+ )
+ }
+
+ if (dayjs.utc(from).isAfter(dayjs.utc(to), 'second')) {
+ throw new PreconditionFailedException(
+ "The timeframe 'from' parameter cannot be greater than 'to'",
+ )
+ }
+
+ checkIfTBAllowed(timeBucket, from, to)
+
+ groupFrom = dayjs.tz(from, timezone).utc().format('YYYY-MM-DD HH:mm:ss')
+
+ if (from === to) {
+ groupTo = dayjs
+ .tz(to, timezone)
+ .add(1, 'day')
+ .format('YYYY-MM-DD HH:mm:ss')
+ } else {
+ groupTo = dayjs.tz(to, timezone).format('YYYY-MM-DD HH:mm:ss')
+ }
+ } else if (!_isEmpty(period)) {
+ if (period === 'today') {
+ if (timezone !== DEFAULT_TIMEZONE && isValidTimezone(timezone)) {
+ groupFrom = dayjs()
+ .tz(timezone)
+ .startOf('d')
+ .utc()
+ .format('YYYY-MM-DD HH:mm:ss')
+ groupTo = dayjs().tz(timezone).utc().format('YYYY-MM-DD HH:mm:ss')
+ } else {
+ groupFrom = dayjs.utc().startOf('d').format('YYYY-MM-DD')
+ groupTo = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')
+ }
+ } else if (period === 'yesterday') {
+ if (timezone !== DEFAULT_TIMEZONE && isValidTimezone(timezone)) {
+ groupFrom = dayjs()
+ .tz(timezone)
+ .startOf('d')
+ .subtract(1, 'day')
+ .utc()
+ .format('YYYY-MM-DD HH:mm:ss')
+ groupTo = dayjs()
+ .tz(timezone)
+ .startOf('d')
+ .utc()
+ .format('YYYY-MM-DD HH:mm:ss')
+ } else {
+ groupFrom = dayjs
+ .utc()
+ .startOf('d')
+ .subtract(1, 'day')
+ .format('YYYY-MM-DD')
+ groupTo = dayjs.utc().startOf('d').format('YYYY-MM-DD HH:mm:ss')
+ }
+ } else {
+ groupFrom = dayjs
+ .utc()
+ .subtract(parseInt(period, 10), _last(period))
+ .format('YYYY-MM-DD')
+ groupTo = dayjs.utc().format('YYYY-MM-DD 23:59:59')
+
+ checkIfTBAllowed(timeBucket, groupFrom, groupTo)
+ }
+ } else {
+ throw new BadRequestException(
+ 'The timeframe (either from/to pair or period) has to be provided',
+ )
+ }
+
+ paramsData.params = {
+ ...paramsData.params,
+ groupFrom,
+ groupTo,
+ }
+
+ // let result: object | void
+
+ let appliedFilters = filters
+
+ if (filters) {
+ try {
+ appliedFilters = JSON.parse(filters)
+ // eslint-disable-next-line no-empty
+ } catch {}
+ }
+
+ const customs = await this.analyticsService.processCustomEV(
+ queryCustoms,
+ paramsData,
+ )
+
+ const customEventsName = Object.keys(customs)
+
+ const result = await this.analyticsService.groupCustomEVByTimeBucket(
+ timeBucket,
+ groupFrom,
+ groupTo,
+ subQuery,
+ filtersQuery,
+ paramsData,
+ timezone,
+ customEventsName,
+ )
+
+ return {
+ ...result,
+ appliedFilters,
+ }
+ }
}
diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.ts
index 1ab1ba800..4da227645 100644
--- a/src/analytics/analytics.service.ts
+++ b/src/analytics/analytics.service.ts
@@ -1017,4 +1017,103 @@ export class AnalyticsService {
// @ts-ignore
return redis.countKeysByPattern(`hb:${pid}:*`)
}
+
+ async groupCustomEVByTimeBucket(
+ timeBucket: TimeBucketType,
+ from: string,
+ to: string,
+ subQuery: string,
+ filtersQuery: string,
+ paramsData: object,
+ timezone: string,
+ customEventsName: string[],
+ ): Promise<object | void> {
+ let groupDateIterator
+ const now = dayjs.utc().endOf(timeBucket)
+ const djsTo = dayjs.utc(to).endOf(timeBucket)
+ const iterateTo = djsTo > now ? now : djsTo
+
+ switch (timeBucket) {
+ case TimeBucketType.HOUR:
+ groupDateIterator = dayjs.utc(from).startOf('hour')
+ break
+
+ case TimeBucketType.DAY:
+ case TimeBucketType.WEEK:
+ case TimeBucketType.MONTH:
+ groupDateIterator = dayjs.utc(from).startOf('day')
+ break
+
+ default:
+ return Promise.reject()
+ }
+
+ let x = []
+
+ while (groupDateIterator < iterateTo) {
+ const nextIteration = groupDateIterator.add(1, timeBucket)
+ x.push(groupDateIterator.format('YYYY-MM-DD HH:mm:ss'))
+ groupDateIterator = nextIteration
+ }
+
+ const xM = [...x, groupDateIterator.format('YYYY-MM-DD HH:mm:ss')]
+ let query = ''
+
+ for (let i = 0; i < _size(x); ++i) {
+ if (i > 0) {
+ query += ' UNION ALL '
+ }
+
+ query += `select ${i} index, ev, count() from customEV where pid = {pid:FixedString(12)} and created between '${
+ xM[i]
+ }' and '${xM[1 + i]}' ${filtersQuery} group by pid, ev`
+ }
+
+ // @ts-ignore
+ const result: Array<CustomsCHResponse> = (
+ await clickhouse.query(query, paramsData).toPromise()
+ )
+ // @ts-ignore
+ .sort((a, b) => a.index - b.index)
+
+ const customEvents = {}
+
+ let idx = 0
+ const resSize = _size(result)
+
+ while (idx < resSize) {
+ const res = result[idx]
+ // get index from res by js destructuring
+ const { ev } = res
+
+ if (!customEvents[ev]) {
+ customEvents[ev] = []
+ }
+
+ customEvents[ev][idx] = _round(res['count()'], 2)
+
+ idx++
+ }
+
+ for (let i = 0; i < _size(x); ++i) {
+ for (let j = 0; j < _size(customEventsName); ++j) {
+ if (!customEvents[customEventsName[j]][i]) {
+ customEvents[customEventsName[j]][i] = 0
+ }
+ }
+ }
+
+ if (timezone !== DEFAULT_TIMEZONE && isValidTimezone(timezone)) {
+ x = _map(x, el =>
+ dayjs.utc(el).tz(timezone).format('YYYY-MM-DD HH:mm:ss'),
+ )
+ }
+
+ return Promise.resolve({
+ chart: {
+ x,
+ events: customEvents,
+ },
+ })
+ }
}
diff --git a/src/project/project.controller.ts b/src/project/project.controller.ts
index e2b72dad5..4a936efa1 100644
--- a/src/project/project.controller.ts
+++ b/src/project/project.controller.ts
@@ -799,8 +799,20 @@ export class ProjectController {
}
@Delete('/partially/:pid')
- @ApiQuery({ name: 'from', required: true, description: 'Date in ISO format', example: '2020-01-01T00:00:00.000Z', type: 'string' })
- @ApiQuery({ name: 'to', required: true, description: 'Date in ISO format', example: '2020-01-01T00:00:00.000Z', type: 'string' })
+ @ApiQuery({
+ name: 'from',
+ required: true,
+ description: 'Date in ISO format',
+ example: '2020-01-01T00:00:00.000Z',
+ type: 'string',
+ })
+ @ApiQuery({
+ name: 'to',
+ required: true,
+ description: 'Date in ISO format',
+ example: '2020-01-01T00:00:00.000Z',
+ type: 'string',
+ })
@ApiResponse({ status: 200 })
@UseGuards(JwtAccessTokenGuard, RolesGuard)
@Auth([UserType.ADMIN, UserType.CUSTOMER])
@@ -813,18 +825,20 @@ export class ProjectController {
this.logger.log({ from, to, pid }, 'DELETE /partially/:id')
if (!isValidPID(pid)) {
- throw new BadRequestException('The provided Project ID (pid) is incorrect')
+ throw new BadRequestException(
+ 'The provided Project ID (pid) is incorrect',
+ )
}
from = _head(_split(from, 'T'))
to = _head(_split(to, 'T'))
if (!isValidDate(from)) {
- throw new BadRequestException('The provided \'from\' date is incorrect',)
+ throw new BadRequestException("The provided 'from' date is incorrect")
}
if (!isValidDate(to)) {
- throw new BadRequestException('The provided \'to\' date is incorrect',)
+ throw new BadRequestException("The provided 'to' date is incorrect")
}
const project = await this.projectService.findOne(pid, {
diff --git a/src/project/project.service.ts b/src/project/project.service.ts
index e70bd5fd8..005e28f2b 100644
--- a/src/project/project.service.ts
+++ b/src/project/project.service.ts
@@ -347,13 +347,22 @@ export class ProjectService {
}
}
- async removeDataFromClickhouse(pid: string, from: string, to: string): Promise<void> {
- const queryAnalytics = 'ALTER TABLE analytics DELETE WHERE pid = {pid:FixedString(12)} AND created BETWEEN {from:String} AND {to:String}'
- const queryCustomEvents = 'ALTER TABLE customEV DELETE WHERE pid = {pid:FixedString(12)} AND created BETWEEN {from:String} AND {to:String}'
- const queryPerformance = 'ALTER TABLE performance DELETE WHERE pid = {pid:FixedString(12)} AND created BETWEEN {from:String} AND {to:String}'
+ async removeDataFromClickhouse(
+ pid: string,
+ from: string,
+ to: string,
+ ): Promise<void> {
+ const queryAnalytics =
+ 'ALTER TABLE analytics DELETE WHERE pid = {pid:FixedString(12)} AND created BETWEEN {from:String} AND {to:String}'
+ const queryCustomEvents =
+ 'ALTER TABLE customEV DELETE WHERE pid = {pid:FixedString(12)} AND created BETWEEN {from:String} AND {to:String}'
+ const queryPerformance =
+ 'ALTER TABLE performance DELETE WHERE pid = {pid:FixedString(12)} AND created BETWEEN {from:String} AND {to:String}'
const params = {
params: {
- pid, from, to,
+ pid,
+ from,
+ to,
},
}