📈 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
Improved Analytics & Project validation; added /log/birdseye endpoint
Blue Mousee15875f74e00
diff --git a/src/analytics/analytics.controller.ts b/src/analytics/analytics.controller.tsindex 2354fb918..6b4cdc457 100644--- a/src/analytics/analytics.controller.ts+++ b/src/analytics/analytics.controller.ts@@ -1,12 +1,14 @@import * as _isEmpty from 'lodash/isEmpty'import * as _isNumber from 'lodash/isNumber'+import * as _isArray from 'lodash/isArray'+import * as _size from 'lodash/size'import * as _last from 'lodash/last'import * as dayjs from 'dayjs'import * as utc from 'dayjs/plugin/utc'import { v4 as uuidv4 } from 'uuid'import {Controller, Body, Query, Param, UseGuards, Get, Post, Put, Delete, BadRequestException,- HttpCode, NotFoundException, InternalServerErrorException, NotAcceptableException, NotImplementedException,+ HttpCode, NotFoundException, InternalServerErrorException, NotAcceptableException, NotImplementedException, UnprocessableEntityException,} from '@nestjs/common'import { ApiTags, ApiQuery, ApiResponse } from '@nestjs/swagger'import { Between } from 'typeorm'@@ -22,7 +24,9 @@ import { RolesGuard } from 'src/common/guards/roles.guard'import { PageviewsDTO } from './dto/pageviews.dto'import { AnalyticsGET_DTO } from './dto/getData.dto'import { AppLoggerService } from '../logger/logger.service'-import { clickhouse } from '../common/constants'+import {+ clickhouse, isValidPID, getPercentageChange,+} from '../common/constants'import ct from '../common/countriesTimezones'dayjs.extend(utc)@@ -47,6 +51,8 @@ export class AnalyticsController {this.logger.log({ ...data }, 'GET /log')const { pid, period, timeBucket, from, to } = data+ if (!isValidPID(pid)) throw new BadRequestException('The provided Project ID (pid) is incorrect')+let groupFrom = from, groupTo = to// TODO: data validation// TODO: automatic timeBucket detection based on period provided@@ -56,20 +62,20 @@ export class AnalyticsController {let query = `SELECT * FROM analytics WHERE pid='${pid}' `if (!_isEmpty(from) && !_isEmpty(to)) {- throw new BadRequestException('Filter by from/to params is currently not available')- if (dayjs(from).isAfter(dayjs(to), 'second')) {+ throw new NotImplementedException('Filter by from/to params is currently not available')+ if (dayjs.utc(from).isAfter(dayjs.utc(to), 'second')) {throw new BadRequestException('The timeframe \'from\' parameter cannot be greater than \'to\'')}- if (dayjs(to).isAfter(dayjs(), 'second')) {- groupTo = dayjs().format('YYYY-MM-DD HH:mm:ss')+ if (dayjs.utc(to).isAfter(dayjs.utc(), 'second')) {+ groupTo = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')query += `AND created BETWEEN ${from} AND ${groupTo}`} else {query += `AND created BETWEEN ${from} AND ${to}`}} else if (!_isEmpty(period)) {- groupFrom = dayjs().subtract(parseInt(period), _last(period)).format('YYYY-MM-DD HH:mm:ss')- groupTo = dayjs().format('YYYY-MM-DD HH:mm:ss')+ groupFrom = dayjs.utc().subtract(parseInt(period), _last(period)).format('YYYY-MM-DD HH:mm:ss')+ groupTo = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')query += `AND created BETWEEN '${groupFrom}' AND '${groupTo}'`} else {throw new BadRequestException('The timeframe (either from/to pair or period) to be provided')@@ -80,6 +86,66 @@ export class AnalyticsController {return result}+ @Get('/birdseye')+ @UseGuards(RolesGuard)+ // @Roles(UserType.CUSTOMER, UserType.ADMIN)+ // returns overall short statistics per project+ async getOverallStats(@Query() data): Promise<any> {+ this.logger.log({ ...data }, 'GET /birdseye')++ let { pids, pid } = data+ const pidsEmpty = _isEmpty(pids)+ const pidEmpty = _isEmpty(pid)+ if (pidsEmpty && pidEmpty) throw new BadRequestException('An array of Project ID\'s (pids) or a Project ID (pid) has to be provided')+ else if (!pidsEmpty && !pidEmpty) throw new BadRequestException('Please provide either an array of Project ID\'s (pids) or a Project ID (pid), but not both')+ else if (!pidEmpty) {+ pids = JSON.stringify([pid])+ }++ const result = { }++ try {+ pids = JSON.parse(pids)+ } catch (e) {+ throw new UnprocessableEntityException('Cannot process the provided array of Project ID\'s')+ }++ if (!_isArray(pids)) {+ throw new UnprocessableEntityException('An array of Project ID\'s has to be provided as a \'pids\' param')+ }++ for (let i = 0; i < _size(pids); ++i) {+ const pid = pids[i]+ if (!isValidPID(pid)) throw new BadRequestException(`The provided Project ID (${pid}) is incorrect`)++ const now = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')+ const oneWRaw = dayjs.utc().subtract(1, 'w')+ const oneWeek = oneWRaw.format('YYYY-MM-DD HH:mm:ss')+ const twoWeeks = oneWRaw.subtract(1, 'w').format('YYYY-MM-DD HH:mm:ss')++ let query1 = `SELECT COUNT() FROM analytics WHERE pid='${pid}' AND created BETWEEN '${oneWeek}' AND '${now}'`+ let query2 = `SELECT COUNT() FROM analytics WHERE pid='${pid}' AND created BETWEEN '${twoWeeks}' AND '${oneWeek}'`++ // todo: save to redis+ try {+ const res1 = await clickhouse.query(query1).toPromise()+ const res2 = await clickhouse.query(query2).toPromise()+ const thisWeek = res1[0]['count()']+ const lastWeek = res2[0]['count()']++ result[pid] = {+ thisWeek,+ lastWeek,+ percChange: getPercentageChange(thisWeek, lastWeek),+ }+ } catch {+ throw new InternalServerErrorException('Can\'t process the provided PID. Please, try again later.')+ }+ }++ return result+ }+@Post('/')async log(@Body() logDTO: PageviewsDTO): Promise<any> {this.logger.log({ logDTO }, 'POST /log')diff --git a/src/common/constants.ts b/src/common/constants.tsindex 317e4f1fe..092462729 100644--- a/src/common/constants.ts+++ b/src/common/constants.ts@@ -2,6 +2,7 @@ import { ClickHouse } from 'clickhouse'import Redis from 'ioredis'import * as _toNumber from 'lodash/toNumber'import * as _size from 'lodash/size'+import * as _round from 'lodash/round'require('dotenv').config()const redis = new Redis({@@ -29,6 +30,22 @@ const clickhouse = new ClickHouse({},})+/**+ * Calculates in percent, the change between 2 numbers.+ * e.g from 1000 to 500 = 50%+ *+ * @param oldVal The initial value+ * @param newVal The value that changed+ */+function getPercentageChange(oldVal: number, newVal: number, round: number = 2) {+ if (oldVal === 0) {+ return _round(-100 * newVal, round)+ }++ const decrease = oldVal - newVal+ return _round((decrease / oldVal) * 100, round)+}+const JWT_LIFE_TIME = 7 * 24 * 60 * 60const HISTORY_LIFE_TIME_DAYS = 30@@ -43,5 +60,5 @@ const redisProjectCacheTimeout = 3600export {clickhouse, JWT_LIFE_TIME, HISTORY_LIFE_TIME_DAYS, redis, isValidPID, getRedisProjectKey,- redisProjectCacheTimeout,+ redisProjectCacheTimeout, getPercentageChange,}diff --git a/src/project/entity/project.entity.ts b/src/project/entity/project.entity.tsindex 14d134a03..9f4eb7b6e 100644--- a/src/project/entity/project.entity.ts+++ b/src/project/entity/project.entity.ts@@ -13,7 +13,7 @@ export class Project {id: string@ApiProperty()- @Column('varchar', { length: 80 })+ @Column('varchar', { length: 50 })name: string@ApiProperty()diff --git a/src/project/project.controller.ts b/src/project/project.controller.tsindex 2e27c09ea..e4c18ddcc 100644--- a/src/project/project.controller.ts+++ b/src/project/project.controller.ts@@ -1,7 +1,10 @@-import { Controller, Body, Query, Param, UseGuards, Get, Post, Put, Delete, BadRequestException,- HttpCode, NotFoundException } from '@nestjs/common'+import {+ Controller, Body, Query, Param, UseGuards, Get, Post, Put, Delete,+ BadRequestException, HttpCode, NotFoundException, UnprocessableEntityException,+} from '@nestjs/common'import { ApiTags, ApiQuery, ApiResponse } from '@nestjs/swagger'import * as _isEmpty from 'lodash/isEmpty'+import * as _size from 'lodash/size'import { ProjectService } from './project.service'import { UserType } from '../user/entities/user.entity'@@ -62,7 +65,8 @@ export class ProjectController {@Roles(UserType.CUSTOMER, UserType.ADMIN)async create(@Body() projectDTO: ProjectDTO, @CurrentUserId() userId: string): Promise<Project> {this.logger.log({ projectDTO, userId }, 'POST /project')- if (!isValidPID(projectDTO.id)) throw new BadRequestException('The provided Project ID (pid) is incorrect')+ if (!isValidPID(projectDTO.id)) throw new UnprocessableEntityException('The provided Project ID (pid) is incorrect')+ if (_size(projectDTO.name) > 50) throw new UnprocessableEntityException('The project name is too long')await this.projectService.checkIfIDUnique(projectDTO.id)@@ -96,6 +100,7 @@ export class ProjectController {async update(@Param('id') id: string, @Body() projectDTO: ProjectDTO, @CurrentUserId() userId: string): Promise<any> {this.logger.log({ projectDTO, userId, id }, 'PUT /project/:id')if (!isValidPID(id)) throw new BadRequestException('The provided Project ID (pid) is incorrect')+ if (_size(projectDTO.name) > 50) throw new UnprocessableEntityException('The project name is too long')let project = await this.projectService.findOneWithRelations(id)@@ -103,8 +108,12 @@ export class ProjectController {throw new NotFoundException()}+ project.active = projectDTO.active+ project.origins = projectDTO.origins+ project.name = projectDTO.name+await this.projectService.allowedToManage(project, userId)- await this.projectService.update(id, projectDTO)+ await this.projectService.update(id, project)project = await this.projectService.findOne(id)