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!

Added user mailing preferences, added weekly & monthly project summary reports

Blue Moused4207fe09c3e
diff --git a/src/analytics/analytics.controller.ts b/src/analytics/analytics.controller.ts
index 774064f88..5b6f3f024 100644
--- a/src/analytics/analytics.controller.ts
+++ b/src/analytics/analytics.controller.ts
@@ -12,6 +12,7 @@ import {
InternalServerErrorException, NotImplementedException, UnprocessableEntityException,
} from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
+import * as UAParser from 'ua-parser-js'
import { AnalyticsService } from './analytics.service'
import { ProjectService } from '../project/project.service'
@@ -22,7 +23,7 @@ import { PageviewsDTO } from './dto/pageviews.dto'
import { AnalyticsGET_DTO } from './dto/getData.dto'
import { AppLoggerService } from '../logger/logger.service'
import {
- clickhouse, isValidPID, getPercentageChange, REDIS_LOG_DATA_CACHE_KEY, redis,
+ clickhouse, isValidPID, REDIS_LOG_DATA_CACHE_KEY, redis,
} from '../common/constants'
import ct from '../common/countriesTimezones'
@@ -32,9 +33,9 @@ dayjs.extend(utc)
// store them in redis storage and reset every 24 hours
const getSessionKey = (ip: string, ua: string, pid: string, salt: string = '') => hash(`${ua}${ip}${pid}${salt}`).toString('hex')
-const analyticsDTO = (pid: string, ev: string, pg: string, lc: string, ref: string, sw: number | string, so: string, me: string, ca: string, lt: number | string, tz: string, unique: number): Array<string | number> => {
+const analyticsDTO = (pid: string, ev: string, pg: string, dv: string, br: string, os: string, lc: string, ref: string, so: string, me: string, ca: string, lt: number | string, tz: string, unique: number): Array<string | number> => {
const cc = tz === 'NULL' ? 'NULL' : ct.getCountryForTimezone(tz)?.id
- return [uuidv4(), pid, ev, pg, lc, ref, sw, so, me, ca, lt, cc, unique, dayjs.utc().format('YYYY-MM-DD HH:mm:ss')]
+ return [uuidv4(), pid, ev, pg, dv, br, os, lc, ref, so, me, ca, lt, cc, unique, dayjs.utc().format('YYYY-MM-DD HH:mm:ss')]
}
const getElValue = (el) => {
@@ -108,8 +109,6 @@ export class AnalyticsController {
pids = JSON.stringify([pid])
}
- const result = { }
-
try {
pids = JSON.parse(pids)
} catch (e) {
@@ -120,36 +119,7 @@ export class AnalyticsController {
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
+ return this.analyticsService.getSummary(pids)
}
@Post('/')
@@ -163,9 +133,13 @@ export class AnalyticsController {
let dto: Array<string | number>
if (unique) {
- dto = analyticsDTO(logDTO.pid, logDTO.ev, logDTO.pg, logDTO.lc, logDTO.ref, logDTO.sw, logDTO.so, logDTO.me, logDTO.ca, logDTO.lt, logDTO.tz, 1)
+ const ua = UAParser(userAgent)
+ const dv = ua.device.type || 'desktop'
+ const br = ua.browser.name
+ const os = ua.os.name
+ dto = analyticsDTO(logDTO.pid, logDTO.ev, logDTO.pg, dv, br, os, logDTO.lc, logDTO.ref, logDTO.so, logDTO.me, logDTO.ca, logDTO.lt, logDTO.tz, 1)
} else {
- dto = analyticsDTO(logDTO.pid, logDTO.ev, logDTO.pg, 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 0)
+ dto = analyticsDTO(logDTO.pid, logDTO.ev, logDTO.pg, 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 0)
}
// todo: fix: may be vulnerable to sql injection attack
diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.ts
index bf3b84ba9..e82966fba 100644
--- a/src/analytics/analytics.service.ts
+++ b/src/analytics/analytics.service.ts
@@ -7,6 +7,7 @@ import * as _map from 'lodash/map'
import * as _keys from 'lodash/keys'
import * as dayjs from 'dayjs'
import * as utc from 'dayjs/plugin/utc'
+// import { OpUnitType } from 'dayjs/index'
import { ForbiddenException, Injectable, BadRequestException, InternalServerErrorException } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
@@ -14,7 +15,7 @@ import { Repository } from 'typeorm'
import { Pagination, PaginationOptionsInterface } from '../common/pagination'
import {
redis, isValidPID, getRedisProjectKey, redisProjectCacheTimeout,
- UNIQUE_SESSION_LIFE_TIME,
+ UNIQUE_SESSION_LIFE_TIME, clickhouse, getPercentageChange,
} from '../common/constants'
import { Analytics } from './entities/analytics.entity'
import { PageviewsDTO } from './dto/pageviews.dto'
@@ -123,13 +124,15 @@ export class AnalyticsService {
processData(data: object): object {
const res = {
cc: {},
- pg: {},
+ pg: {},
lc: {},
+ br: {},
+ os: {},
+ dv: {},
ref: {},
- sw: {},
- so: {},
+ so: {},
me: {},
- ca: {},
+ ca: {},
lt: {},
}
const whitelist = _keys(res)
@@ -150,6 +153,58 @@ export class AnalyticsService {
return res
}
+ async getSummary(pids: string[], period: 'w' | 'M' = 'w', advanced: boolean = false): Promise<Object> {
+ const result = {}
+ 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, period)
+ const oneWeek = oneWRaw.format('YYYY-MM-DD HH:mm:ss')
+ const twoWeeks = oneWRaw.subtract(1, period).format('YYYY-MM-DD HH:mm:ss')
+
+ const query1_pageviews = `SELECT COUNT() FROM analytics WHERE pid='${pid}' AND created BETWEEN '${oneWeek}' AND '${now}'`
+ const query2_pageviews = `SELECT COUNT() FROM analytics WHERE pid='${pid}' AND created BETWEEN '${twoWeeks}' AND '${oneWeek}'`
+ const query1_unique = `SELECT COUNT() FROM analytics WHERE pid='${pid}' AND unique=1 AND created BETWEEN '${oneWeek}' AND '${now}'`
+ const query2_unique = `SELECT COUNT() FROM analytics WHERE pid='${pid}' AND unique=1 AND created BETWEEN '${twoWeeks}' AND '${oneWeek}'`
+
+ // todo: save to redis
+ try {
+ const res1_pageviews = await clickhouse.query(query1_pageviews).toPromise()
+ const res2_pageviews = await clickhouse.query(query2_pageviews).toPromise()
+ const thisWeekPV = res1_pageviews[0]['count()']
+ const lastWeekPV = res2_pageviews[0]['count()']
+
+ if (advanced) {
+ const res1_unique = await clickhouse.query(query1_unique).toPromise()
+ const res2_unique = await clickhouse.query(query2_unique).toPromise()
+ const thisWeekUnique = res1_unique[0]['count()']
+ const lastWeekUnique = res2_unique[0]['count()']
+
+ result[pid] = {
+ thisWeek: thisWeekPV,
+ lastWeek: lastWeekPV,
+ thisWeekUnique,
+ lastWeekUnique,
+ percChange: getPercentageChange(thisWeekPV, lastWeekPV),
+ percChangeUnique: getPercentageChange(thisWeekUnique, lastWeekUnique),
+ }
+ } else {
+ result[pid] = {
+ thisWeek: thisWeekPV,
+ lastWeek: lastWeekPV,
+ percChange: getPercentageChange(thisWeekPV, lastWeekPV),
+ }
+ }
+ } catch {
+ throw new InternalServerErrorException('Can\'t process the provided PID. Please, try again later.')
+ }
+ }
+
+ return result
+ }
+
// TODO: Refactor; check if there's no date/time shifts
async groupByTimeBucket(data: Object[], timeBucket: TimeBucketType, from: string, to: string): Promise<object | void> {
if (_isEmpty(data)) return Promise.resolve()
diff --git a/src/analytics/dto/pageviews.dto.ts b/src/analytics/dto/pageviews.dto.ts
index 7a4af4b95..23f10c2a3 100644
--- a/src/analytics/dto/pageviews.dto.ts
+++ b/src/analytics/dto/pageviews.dto.ts
@@ -41,12 +41,6 @@ export class PageviewsDTO {
})
ref: string
- @ApiProperty({
- example: 1920,
- description: 'Screen width'
- })
- sw: number
-
@ApiProperty({
example: 'duckduckgo',
description: 'utm_source URL parameter'
diff --git a/src/analytics/entities/analytics.entity.ts b/src/analytics/entities/analytics.entity.ts
index 64f0cd814..45882a0a5 100644
--- a/src/analytics/entities/analytics.entity.ts
+++ b/src/analytics/entities/analytics.entity.ts
@@ -50,10 +50,23 @@ export class Analytics {
}) // same question as pg
ref: string
- @Column({
+ @Column('varchar', {
+ length: 32,
+ nullable: true,
+ })
+ br: string // browser name
+
+ @Column('varchar', {
+ length: 32,
+ nullable: true,
+ })
+ os: string // OS name
+
+ @Column('varchar', {
+ length: 32,
nullable: true,
})
- sw: number
+ dv: string // device type [desktop, console, mobile, tablet, smarttv, wearable, embedded]
@Column('varchar', {
length: 100,
@@ -74,15 +87,7 @@ export class Analytics {
ca: string
@Column({ nullable: true })
- lt: number
-
- // the record itself is a unique view
- // every additional pageview request coming from the user will be set as
- // nupw -> non-unique page views
- // @Column({
- // default: 0,
- // })
- // nupw: number
+ lt: number // load time
@CreateDateColumn()
created: Date;
diff --git a/src/common/constants.ts b/src/common/constants.ts
index 62ce32602..7261d1d35 100644
--- a/src/common/constants.ts
+++ b/src/common/constants.ts
@@ -39,7 +39,11 @@ const clickhouse = new ClickHouse({
*/
function getPercentageChange(oldVal: number, newVal: number, round: number = 2) {
if (oldVal === 0) {
- return _round(-100 * newVal, round)
+ if (newVal === 0) {
+ return 0
+ } else {
+ return _round(-100 * newVal, round)
+ }
}
const decrease = oldVal - newVal
diff --git a/src/mailer/letter.ts b/src/mailer/letter.ts
index 4bd89b25a..682c1feb7 100644
--- a/src/mailer/letter.ts
+++ b/src/mailer/letter.ts
@@ -6,4 +6,5 @@ export enum LetterTemplate {
MailAddressHadChanged = 'mailaddress-change_information',
PasswordChangeRequest = 'password-change_request',
GDPRDataExport = 'gdpr_data_export',
+ ProjectReport = 'project-report',
}
diff --git a/src/mailer/mailer.service.ts b/src/mailer/mailer.service.ts
index 95bd99630..64ceb4f3d 100644
--- a/src/mailer/mailer.service.ts
+++ b/src/mailer/mailer.service.ts
@@ -10,37 +10,42 @@ const TEMPLATES_PATH = path.join(__dirname, '..', 'common', 'templates')
const metaInfoJson = {
[LetterTemplate.SignUp]: {
subject: {
- en: 'Please verify your account registration',
+ en: () => 'Please verify your account registration',
},
},
[LetterTemplate.ConfirmPasswordChange]: {
subject: {
- en: 'Please confirm the password change',
+ en: () => 'Please confirm the password change',
},
},
[LetterTemplate.MailAddressChangeConfirmation]: {
subject: {
- en: 'Please confirm the new e-mail address',
+ en: () => 'Please confirm the new e-mail address',
},
},
[LetterTemplate.MailAddressHadChanged]: {
subject: {
- en: 'A new e-mail-address has been saved',
+ en: () => 'A new e-mail-address has been saved',
},
},
[LetterTemplate.PasswordChangeRequest]: {
subject: {
- en: 'Changing your password',
+ en: () => 'Changing your password',
},
},
[LetterTemplate.PasswordChanged]: {
subject: {
- en: 'Your password was successfully changed',
+ en: () => 'Your password was successfully changed',
},
},
[LetterTemplate.GDPRDataExport]: {
subject: {
- en: 'Swetrix Account data export',
+ en: () => 'Swetrix Account data export',
+ },
+ },
+ [LetterTemplate.ProjectReport]: {
+ subject: {
+ en: (p: Params) => `${p.type === 'w' ? 'Weekly' : 'Monthly'} Report: ${p.date}`,
},
},
}
@@ -49,17 +54,28 @@ interface Params {
[name: string]: any
}
+handlebars.registerHelper('ifEquals', function (arg1, arg2, options) {
+ return (arg1 == arg2) ? options.fn(this) : options.inverse(this)
+})
+
+handlebars.registerHelper('greater', function (v1, v2, options) {
+ if (v1 > v2) {
+ return options.fn(this)
+ }
+ return options.inverse(this)
+})
+
@Injectable()
export class MailerService {
constructor(
private readonly logger: AppLoggerService,
- ) {}
+ ) { }
async sendEmail(email: string, templateName: LetterTemplate, params: Params = null): Promise<void> {
try {
const templatePath = `${TEMPLATES_PATH}/en/${templateName}.html`
const letter = fs.readFileSync(templatePath, { encoding: 'utf-8' })
- const subject = metaInfoJson[templateName].subject.en
+ const subject = metaInfoJson[templateName].subject.en(params)
const template = handlebars.compile(letter)
const htmlToSend = template(params)
@@ -85,7 +101,7 @@ export class MailerService {
html: htmlToSend,
attachments: [],
}
-
+
if (process.env.SMTP_MOCK) {
this.logger.log(message, 'sendEmail')
} else {
diff --git a/src/project/project.controller.ts b/src/project/project.controller.ts
index 83aeb34a8..279969d84 100644
--- a/src/project/project.controller.ts
+++ b/src/project/project.controller.ts
@@ -1,6 +1,6 @@
import {
Controller, Body, Query, Param, UseGuards, Get, Post, Put, Delete,
- BadRequestException, HttpCode, NotFoundException,
+ BadRequestException, HttpCode, NotFoundException, ForbiddenException,
} from '@nestjs/common'
import { ApiTags, ApiQuery, ApiResponse } from '@nestjs/swagger'
import * as _isEmpty from 'lodash/isEmpty'
@@ -66,6 +66,12 @@ 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')
+ const user = await this.userService.findOneWithRelations(userId, ['projects'])
+
+ if (!user.isActive) {
+ throw new ForbiddenException('Please, verify your email address first')
+ }
+
this.projectService.validateProject(projectDTO)
await this.projectService.checkIfIDUnique(projectDTO.id)
@@ -76,7 +82,6 @@ export class ProjectController {
project.origins = _map(projectDTO.origins, _trim)
const newProject = await this.projectService.create(project)
- const user = await this.userService.findOneWithRelations(userId, ['projects'])
user.projects.push(project)
await this.userService.create(user)
diff --git a/src/task-manager/task-manager.module.ts b/src/task-manager/task-manager.module.ts
index b59d45b9f..4724271c7 100644
--- a/src/task-manager/task-manager.module.ts
+++ b/src/task-manager/task-manager.module.ts
@@ -1,9 +1,11 @@
import { Module, HttpModule } from '@nestjs/common'
import { TaskManagerService } from './task-manager.service'
import { MailerModule } from '../mailer/mailer.module'
+import { UserModule } from '../user/user.module'
+import { AnalyticsModule } from '../analytics/analytics.module'
@Module({
- imports: [MailerModule, HttpModule],
+ imports: [MailerModule, HttpModule, UserModule, AnalyticsModule],
providers: [TaskManagerService]
})
export class TaskManagerModule {}
diff --git a/src/task-manager/task-manager.service.ts b/src/task-manager/task-manager.service.ts
index 4b1170c0d..0fd8d67e3 100644
--- a/src/task-manager/task-manager.service.ts
+++ b/src/task-manager/task-manager.service.ts
@@ -1,16 +1,30 @@
import { Injectable, HttpService } from '@nestjs/common'
import { Cron, CronExpression } from '@nestjs/schedule'
+import * as dayjs from 'dayjs'
+import * as utc from 'dayjs/plugin/utc'
import * as _isEmpty from 'lodash/isEmpty'
+import * as _isNull from 'lodash/isNull'
import * as _join from 'lodash/join'
+import * as _size from 'lodash/size'
+import * as _map from 'lodash/map'
+import * as _keys from 'lodash/keys'
import { MailerService } from '../mailer/mailer.service'
+import { UserService } from '../user/user.service'
+import { LetterTemplate } from '../mailer/letter'
+import { AnalyticsService } from '../analytics/analytics.service'
+import { ReportFrequency } from '../user/entities/user.entity'
import { clickhouse, REDIS_LOG_DATA_CACHE_KEY, redis } from '../common/constants'
+dayjs.extend(utc)
+
@Injectable()
export class TaskManagerService {
constructor(
private readonly mailerService: MailerService,
- private readonly httpService: HttpService
+ private readonly httpService: HttpService,
+ private readonly userService: UserService,
+ private readonly analyticsService: AnalyticsService,
) {}
@Cron(CronExpression.EVERY_MINUTE)
@@ -23,4 +37,68 @@ export class TaskManagerService {
await clickhouse.query(query).toPromise()
}
}
+
+ // EVERY SUNDAY AT 2:30 AM
+ @Cron('30 02 * * 0')
+ async weeklyReportsHandler(): Promise<void> {
+ const users = await this.userService.findWhereWithRelations({
+ reportFrequency: ReportFrequency.Weekly,
+ }, ['projects'])
+ const now = dayjs.utc().format('DD.MM.YYYY')
+ const weekAgo = dayjs.utc().subtract(1, 'w').format('DD.MM.YYYY')
+ const date = `${weekAgo} - ${now}`
+
+ for (let i = 0; i < _size(users); ++i) {
+ if (_isEmpty(users[i]?.projects) || _isNull(users[i]?.projects)) {
+ continue
+ }
+
+ const ids = _map(users[i].projects, (p) => p.id)
+ const data = await this.analyticsService.getSummary(ids, 'w', true)
+
+ const result = {
+ type: 'w', // week
+ date,
+ projects: _map(ids, (pid, index) => ({
+ data: data[pid],
+ name: users[i].projects[index].name,
+ })),
+ }
+
+ // todo: maybe this should be sent as a broadcast stream
+ await this.mailerService.sendEmail(users[i].email, LetterTemplate.ProjectReport, result)
+ }
+ }
+
+ // ON THE FIRST DAY OF EVERY MONTH AT 2 AM
+ @Cron('0 02 1 * *')
+ async monthlyReportsHandler(): Promise<void> {
+ const users = await this.userService.findWhereWithRelations({
+ reportFrequency: ReportFrequency.Weekly,
+ }, ['projects'])
+ const now = dayjs.utc().format('DD.MM.YYYY')
+ const weekAgo = dayjs.utc().subtract(1, 'M').format('DD.MM.YYYY')
+ const date = `${weekAgo} - ${now}`
+
+ for (let i = 0; i < _size(users); ++i) {
+ if (_isEmpty(users[i]?.projects) || _isNull(users[i]?.projects)) {
+ continue
+ }
+
+ const ids = _map(users[i].projects, (p) => p.id)
+ const data = await this.analyticsService.getSummary(ids, 'M', true)
+
+ const result = {
+ type: 'M', // month
+ date,
+ projects: _map(ids, (pid, index) => ({
+ data: data[pid],
+ name: users[i].projects[index].name,
+ })),
+ }
+
+ // todo: maybe this should be sent as a broadcast stream
+ await this.mailerService.sendEmail(users[i].email, LetterTemplate.ProjectReport, result)
+ }
+ }
}
diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.ts
index 3c408bdea..9d86d3237 100644
--- a/src/user/entities/user.entity.ts
+++ b/src/user/entities/user.entity.ts
@@ -28,6 +28,12 @@ export enum UserType {
ADMIN = 'admin',
}
+export enum ReportFrequency {
+ Never = 'never',
+ Weekly = 'weekly',
+ Monthly = 'monthly'
+}
+
export const MAX_EMAIL_REQUESTS = 4 // 1 confirmation email on sign up + 3 additional ones
@Entity()
@@ -51,6 +57,13 @@ export class User {
@Column({ default: false })
isActive: boolean
+ @Column({
+ type: 'enum',
+ enum: ReportFrequency,
+ default: ReportFrequency.Monthly,
+ })
+ reportFrequency: ReportFrequency
+
@Column('int', { default: 1 })
emailRequests: number
diff --git a/src/user/user.service.ts b/src/user/user.service.ts
index e4c288285..7516a70b9 100644
--- a/src/user/user.service.ts
+++ b/src/user/user.service.ts
@@ -50,6 +50,12 @@ export class UserService {
return this.usersRepository.findOne(id, { relations })
}
+ findWhereWithRelations(where: Record<string, unknown>, relations: string[]): Promise<User[]> {
+ return this.usersRepository.find({
+ where, relations,
+ })
+ }
+
findWhere(where: Record<string, unknown>): Promise<User[]> {
return this.usersRepository.find({ where })
}