📈 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
added timezones support
Blue Mouseb345ca30755c
diff --git a/src/analytics/analytics.controller.ts b/src/analytics/analytics.controller.tsindex bc04d8b73..4940d10c8 100644--- a/src/analytics/analytics.controller.ts+++ b/src/analytics/analytics.controller.ts@@ -20,6 +20,7 @@ import * as isbot from 'isbot'import { AnalyticsService, getSessionKey } from './analytics.service'import { TaskManagerService } from '../task-manager/task-manager.service'import { CurrentUserId } from '../common/decorators/current-user-id.decorator'+import { DEFAULT_TIMEZONE } from '../user/entities/user.entity'import { RolesGuard } from 'src/common/guards/roles.guard'import { PageviewsDTO } from './dto/pageviews.dto'import { EventsDTO } from './dto/events.dto'@@ -92,7 +93,7 @@ export class AnalyticsController {@Get('/')async getData(@Query() data: AnalyticsGET_DTO, @CurrentUserId() uid: string): Promise<any> {- const { pid, period, timeBucket, from, to, filters } = data+ const { pid, period, timeBucket, from, to, filters, timezone = DEFAULT_TIMEZONE } = datathis.analyticsService.validatePID(pid)this.analyticsService.validatePeriod(period)this.analyticsService.validateTimebucket(timeBucket)@@ -140,7 +141,7 @@ export class AnalyticsController {throw new BadRequestException('The timeframe (either from/to pair or period) to be provided')}- const result = await this.analyticsService.groupByTimeBucket(timeBucket, groupFrom, groupTo, subQuery, filtersQuery, paramsData)+ const result = await this.analyticsService.groupByTimeBucket(timeBucket, groupFrom, groupTo, subQuery, filtersQuery, paramsData, timezone)const customs = await this.analyticsService.processCustomEV(queryCustoms, paramsData)diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.tsindex 99a87ddc1..7d1728626 100644--- a/src/analytics/analytics.service.ts+++ b/src/analytics/analytics.service.ts@@ -14,13 +14,14 @@ import * as _find from 'lodash/find'import * as _values from 'lodash/values'import * as dayjs from 'dayjs'import * as utc from 'dayjs/plugin/utc'+import * as timezone from 'dayjs/plugin/timezone'import { isLocale } from 'validator'import { hash } from 'blake3'import {Injectable, BadRequestException, InternalServerErrorException, ForbiddenException, UnprocessableEntityException,} from '@nestjs/common'-import { ACCOUNT_PLANS } from '../user/entities/user.entity'+import { ACCOUNT_PLANS, DEFAULT_TIMEZONE } from '../user/entities/user.entity'import {redis, isValidPID, getRedisProjectKey, redisProjectCacheTimeout, UNIQUE_SESSION_LIFE_TIME, clickhouse,getPercentageChange, isSelfhosted, REDIS_SESSION_SALT_KEY,@@ -33,6 +34,7 @@ import { Project } from '../project/entity/project.entity'import { TimeBucketType } from './dto/getData.dto'dayjs.extend(utc)+dayjs.extend(timezone)export const getSessionKey = (ip: string, ua: string, pid: string, salt: string = '') => `ses_${hash(`${ua}${ip}${pid}${salt}`).toString('hex')}`@@ -59,6 +61,15 @@ const customEVvalidate = /^[a-zA-Z](?:[\w\.]){0,62}$/interface GetFiltersQuery extends Array<string | object>{0:string; 1:object}+const isValidTimezone = (timezone) => {+ try {+ dayjs.tz('2013-11-18 11:55', timezone)+ return true+ } catch {+ return false+ }+}+@Injectable()export class AnalyticsService {constructor(@@ -301,7 +312,7 @@ export class AnalyticsService {return result}- async groupByTimeBucket(timeBucket: TimeBucketType, from: string, to: string, subQuery: string, filtersQuery: string, paramsData: object): Promise<object | void> {+ async groupByTimeBucket(timeBucket: TimeBucketType, from: string, to: string, subQuery: string, filtersQuery: string, paramsData: object, timezone: string): Promise<object | void> {const params = {}for (let i of cols) {@@ -347,7 +358,7 @@ export class AnalyticsService {return Promise.reject()}- const x = []+ let x = []while (groupDateIterator < iterateTo) {const nextIteration = groupDateIterator.add(1, timeBucket)@@ -405,6 +416,11 @@ export class AnalyticsService {}}+ // todo: winter / summer time does not seem to work here..+ 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({params,chart: {diff --git a/src/analytics/dto/getData.dto.ts b/src/analytics/dto/getData.dto.tsindex f1c10704a..36b6b049d 100644--- a/src/analytics/dto/getData.dto.ts+++ b/src/analytics/dto/getData.dto.ts@@ -1,5 +1,6 @@import { ApiProperty } from '@nestjs/swagger'import { IsNotEmpty } from 'class-validator'+import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'export enum TimeBucketType {MINUTE = 'minute',@@ -32,4 +33,10 @@ export class AnalyticsGET_DTO {description: 'A stringified array of properties to filter [{ column, filter, isExclusive }]',})filters: string++ @ApiProperty({+ description: 'Timezone to display data in',+ default: DEFAULT_TIMEZONE,+ })+ timezone: string}diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.tsindex 27253368c..8bc62fb32 100644--- a/src/user/entities/user.entity.ts+++ b/src/user/entities/user.entity.ts@@ -52,6 +52,8 @@ export enum ReportFrequency {export const MAX_EMAIL_REQUESTS = 4 // 1 confirmation email on sign up + 3 additional ones+export const DEFAULT_TIMEZONE = 'Etc/GMT'+@Entity()export class User {@PrimaryGeneratedColumn('uuid')@@ -108,14 +110,14 @@ export class User {@Column('varchar', { length: 200, nullable: true })subCancelURL: string+ @Column('varchar', { length: 50, default: DEFAULT_TIMEZONE })+ timezone: string+@BeforeUpdate()updateTimestamp() {this.updated = new Date}- // @Column('datetime', { nullable: true, default: null })- // consent: Date-@OneToMany(() => Project, project => project.admin)projects: Project[]