📈 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 maxProjects validation when creating new project & counting events from ALL projects (analytics)
Blue Mouse987bd5ccf658
diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.tsindex ee84ade72..3810b9d22 100644--- a/src/analytics/analytics.service.ts+++ b/src/analytics/analytics.service.ts@@ -4,6 +4,7 @@ import * as _size from 'lodash/size'import * as _isNull from 'lodash/isNull'import * as _includes from 'lodash/includes'import * as _map from 'lodash/map'+import * as _join from 'lodash/join'import * as _keys from 'lodash/keys'import * as dayjs from 'dayjs'import * as utc from 'dayjs/plugin/utc'@@ -16,7 +17,7 @@ import { Repository } from 'typeorm'import { ACCOUNT_PLANS } from '../user/entities/user.entity'import {redis, isValidPID, getRedisProjectKey, redisProjectCacheTimeout,- UNIQUE_SESSION_LIFE_TIME, clickhouse, getPercentageChange, getRedisProjectCountKey,+ UNIQUE_SESSION_LIFE_TIME, clickhouse, getPercentageChange, getRedisUserCountKey,redisProjectCountCacheTimeout,} from '../common/constants'import { Analytics } from './entities/analytics.entity'@@ -83,13 +84,21 @@ export class AnalyticsService {}// Returns amount of existing events starting from month- async getRedisCount(pid: string): Promise<number | null> {- const countKey = getRedisProjectCountKey(pid)+ async getRedisCount(uid: string): Promise<number | null> {+ const countKey = getRedisUserCountKey(uid)let count = await redis.get(countKey)+if (_isEmpty(count)) {const now = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')const monthStart = dayjs.utc().startOf('month').format('YYYY-MM-DD HH:mm:ss')- const count_query = `SELECT COUNT() FROM analytics WHERE pid='${pid}' AND created BETWEEN '${monthStart}' AND '${now}'`+ const pids = await this.projectService.find({+ where: {+ admin: uid,+ },+ select: ['id'],+ })++ const count_query = `SELECT COUNT() FROM analytics WHERE pid IN (${_join(_map(pids, el => `'${el.id}'`), ',')}) AND created BETWEEN '${monthStart}' AND '${now}'`const result = await clickhouse.query(count_query).toPromise()const pageviews = result[0]['count()']@@ -139,7 +148,7 @@ export class AnalyticsService {if (!project.active) throw new BadRequestException('Incoming analytics is disabled for this project')- const count = await this.getRedisCount(pid)+ const count = await this.getRedisCount(project.admin.id)const maxCount = ACCOUNT_PLANS[project.admin.planCode].monthlyUsageLimit || 0if (count >= maxCount) {diff --git a/src/common/constants.ts b/src/common/constants.tsindex 3e188daa0..dc4cb769e 100644--- a/src/common/constants.ts+++ b/src/common/constants.ts@@ -58,7 +58,7 @@ const isValidPID = (pid: string) => _size(pid) === 12// redis keysconst getRedisProjectKey = (pid: string) => `pid_${pid}`-const getRedisProjectCountKey = (pid: string) => `pid_c_${pid}`+const getRedisUserCountKey = (uid: string) => `user_c_${uid}`const REDIS_LOG_DATA_CACHE_KEY = 'log_cache'@@ -79,5 +79,5 @@ const GDPR_EXPORT_TIMEFRAME = 14export {clickhouse, JWT_LIFE_TIME, HISTORY_LIFE_TIME_DAYS, redis, isValidPID, getRedisProjectKey,redisProjectCacheTimeout, getPercentageChange, UNIQUE_SESSION_LIFE_TIME, REDIS_LOG_DATA_CACHE_KEY,- GDPR_EXPORT_TIMEFRAME, getRedisProjectCountKey, redisProjectCountCacheTimeout, REDIS_LOG_CUSTOM_CACHE_KEY,+ GDPR_EXPORT_TIMEFRAME, getRedisUserCountKey, redisProjectCountCacheTimeout, REDIS_LOG_CUSTOM_CACHE_KEY,}diff --git a/src/project/project.controller.ts b/src/project/project.controller.tsindex 279969d84..42cf6b37b 100644--- a/src/project/project.controller.ts+++ b/src/project/project.controller.ts@@ -6,9 +6,10 @@ import { ApiTags, ApiQuery, ApiResponse } from '@nestjs/swagger'import * as _isEmpty from 'lodash/isEmpty'import * as _map from 'lodash/map'import * as _trim from 'lodash/trim'+import * as _size from 'lodash/size'import { ProjectService } from './project.service'-import { UserType } from '../user/entities/user.entity'+import { UserType, ACCOUNT_PLANS } from '../user/entities/user.entity'import { Roles } from '../common/decorators/roles.decorator'import { RolesGuard } from '../common/guards/roles.guard'import { Pagination } from '../common/pagination/pagination'@@ -67,11 +68,16 @@ export class ProjectController {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'])+ const maxProjects = ACCOUNT_PLANS[user.planCode].maxProjectsif (!user.isActive) {throw new ForbiddenException('Please, verify your email address first')}+ if (_size(user.projects) >= (maxProjects || 5)) {+ throw new ForbiddenException(`You cannot create more than ${maxProjects} projects on your account plan. Please upgrade to be able to create more projects.`)+ }+this.projectService.validateProject(projectDTO)await this.projectService.checkIfIDUnique(projectDTO.id)diff --git a/src/project/project.service.ts b/src/project/project.service.tsindex a11fd024c..e8c815a1d 100644--- a/src/project/project.service.ts+++ b/src/project/project.service.ts@@ -64,6 +64,10 @@ export class ProjectService {return this.projectsRepository.find({ where })}+ find(params: object): Promise<Project[]> {+ return this.projectsRepository.find(params)+ }+findOneWhere(where: Record<string, unknown>): Promise<Project> {return this.projectsRepository.findOne({ where })}diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.tsindex f3399999e..baa46c538 100644--- a/src/user/entities/user.entity.ts+++ b/src/user/entities/user.entity.ts@@ -6,18 +6,22 @@ export const ACCOUNT_PLANS = {free: {displayName: 'Free plan',monthlyUsageLimit: 3000,+ maxProjects: 5,},freelancer: {displayName: 'Freelancer plan',monthlyUsageLimit: 100000,+ maxProjects: 10,},startup: {displayName: 'Startup plan',monthlyUsageLimit: 500000,+ maxProjects: 10,},enterprise: {displayName: 'Enterprise plan',monthlyUsageLimit: 1000000,+ maxProjects: 10,},}