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!

Add more analytics to track new features usage

Blue Mouse4d10fb087578
diff --git a/backend/.env.example b/backend/.env.example
index 4251955b3..f8a9bd298 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -100,3 +100,5 @@ SWETRIX_LICENSE_KEY=
# OpenRouter API key for AI features
OPENROUTER_API_KEY=
+
+SWETRIX_PID=STEzHcB1rALV
diff --git a/backend/apps/cloud/src/ai/ai.controller.ts b/backend/apps/cloud/src/ai/ai.controller.ts
index b7ae988a1..c82f9a377 100644
--- a/backend/apps/cloud/src/ai/ai.controller.ts
+++ b/backend/apps/cloud/src/ai/ai.controller.ts
@@ -36,14 +36,15 @@ import {
GetRecentChatsQueryDto,
GetAllChatsQueryDto,
} from './dto/chat.dto'
+import { trackCustom } from '../common/analytics'
// Rate limit constants for AI endpoints
-const AI_CHAT_RATE_LIMIT = 30 // requests per hour for authenticated users
-const AI_CHAT_RATE_LIMIT_UNAUTH = 10 // requests per hour for unauthenticated users
+const AI_CHAT_RATE_LIMIT = 50 // requests per hour for authenticated users
+const AI_CHAT_RATE_LIMIT_UNAUTH = 20 // requests per hour for unauthenticated users
const AI_CHAT_RATE_LIMIT_TIMEOUT = 3600 // 1 hour
-const AI_READ_RATE_LIMIT = 100 // requests per hour for read operations
-const AI_READ_RATE_LIMIT_UNAUTH = 30 // requests per hour for unauthenticated users
+const AI_READ_RATE_LIMIT = 200 // requests per hour for read operations
+const AI_READ_RATE_LIMIT_UNAUTH = 50 // requests per hour for unauthenticated users
@ApiTags('AI')
@Controller(['ai', 'v1/ai'])
@@ -231,6 +232,15 @@ export class AiController {
},
'AI stream finish event',
)
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'AI_CHAT_STREAM_FINISHED',
+ meta: {
+ finishReason: part.finishReason,
+ promptTokens: part.usage.promptTokens,
+ completionTokens: part.usage.completionTokens,
+ totalTokens: part.usage.totalTokens,
+ },
+ })
} else if (part.type === 'step-finish') {
this.logger.log(
{
@@ -518,6 +528,10 @@ export class AiController {
name: createChatDto.name,
})
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'AI_CHAT_CREATED',
+ })
+
return {
id: chat.id,
name: chat.name,
@@ -638,6 +652,10 @@ export class AiController {
await this.aiChatService.delete(chatId)
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'AI_CHAT_DELETED',
+ })
+
return { success: true }
}
}
diff --git a/backend/apps/cloud/src/alert/alert.controller.ts b/backend/apps/cloud/src/alert/alert.controller.ts
index a1590d58f..4c7782c95 100644
--- a/backend/apps/cloud/src/alert/alert.controller.ts
+++ b/backend/apps/cloud/src/alert/alert.controller.ts
@@ -13,6 +13,8 @@ import {
HttpException,
HttpStatus,
ParseIntPipe,
+ Ip,
+ Headers,
} from '@nestjs/common'
import { In } from 'typeorm'
import { ApiTags, ApiResponse, ApiBearerAuth } from '@nestjs/swagger'
@@ -36,6 +38,8 @@ import {
QueryTime,
} from './dto/alert.dto'
import { AlertService } from './alert.service'
+import { getIPFromHeaders } from '../common/utils'
+import { trackCustom } from '../common/analytics'
const ALERTS_MAXIMUM = ACCOUNT_PLANS[PlanCode.free].maxAlerts
@@ -117,9 +121,13 @@ export class AlertController {
async createAlert(
@Body() alertDTO: CreateAlertDTO,
@CurrentUserId() uid: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
) {
this.logger.log({ uid }, 'POST /alert')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
const user = await this.userService.findOne({
where: { id: uid },
relations: ['projects'],
@@ -212,6 +220,16 @@ export class AlertController {
await this.projectService.create(project)
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'ALERT_CREATED',
+ meta: {
+ metric: alertDTO.queryMetric,
+ condition: alertDTO.queryCondition,
+ value: alertDTO.queryValue,
+ time: alertDTO.queryTime,
+ },
+ })
+
return {
...newAlert,
pid: alertDTO.pid,
@@ -303,9 +321,16 @@ export class AlertController {
@Delete('/:id')
@Auth()
@ApiResponse({ status: 204, description: 'Empty body' })
- async deleteAlert(@Param('id') id: string, @CurrentUserId() uid: string) {
+ async deleteAlert(
+ @Param('id') id: string,
+ @CurrentUserId() uid: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
+ ) {
this.logger.log({ id, uid }, 'DELETE /alert/:id')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
const alert = await this.alertService.findOneWithRelations(id)
if (_isEmpty(alert)) {
@@ -319,5 +344,9 @@ export class AlertController {
)
await this.alertService.delete(id)
+
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'ALERT_DELETED',
+ })
}
}
diff --git a/backend/apps/cloud/src/auth/auth.controller.ts b/backend/apps/cloud/src/auth/auth.controller.ts
index 1f0441359..f4487bc78 100644
--- a/backend/apps/cloud/src/auth/auth.controller.ts
+++ b/backend/apps/cloud/src/auth/auth.controller.ts
@@ -56,6 +56,7 @@ import {
AuthenticationGuard,
} from './guards'
import { ProjectService } from '../project/project.service'
+import { trackCustom } from '../common/analytics'
const OAUTH_RATE_LIMIT = 15
@@ -123,6 +124,14 @@ export class AuthController {
referrerID,
)
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'SIGNUP',
+ meta: {
+ method: 'email',
+ isReferred: !!referrerID,
+ },
+ })
+
const jwtTokens = await this.authService.generateJwtTokens(newUser.id, true)
return {
diff --git a/backend/apps/cloud/src/auth/auth.service.ts b/backend/apps/cloud/src/auth/auth.service.ts
index 5305f6e07..c8ff6d377 100644
--- a/backend/apps/cloud/src/auth/auth.service.ts
+++ b/backend/apps/cloud/src/auth/auth.service.ts
@@ -47,6 +47,7 @@ import { TelegramService } from '../integrations/telegram/telegram.service'
import { SSOProviders } from './dtos'
import { UserGoogleDTO } from '../user/dto/user-google.dto'
import { UserGithubDTO } from '../user/dto/user-github.dto'
+import { trackCustom } from '../common/analytics'
const REDIS_SSO_SESSION_TIMEOUT = 60 * 5 // 5 minutes
const getSSORedisKey = (uuid: string) => `${REDIS_SSO_UUID}:${uuid}`
@@ -658,7 +659,17 @@ export class AuthService {
if (!user) {
const referrerId = await this.getReferrerId(refCode)
- return await this.registerUserGoogle(sub, email, referrerId)
+ const data = await this.registerUserGoogle(sub, email, referrerId)
+
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'SIGNUP',
+ meta: {
+ method: 'google',
+ isReferred: !!referrerId,
+ },
+ })
+
+ return data
}
return await this.handleExistingUserGoogle(user, headers, ip)
@@ -1054,7 +1065,17 @@ export class AuthService {
if (!user) {
const referrerId = await this.getReferrerId(refCode)
- return await this.registerUserGithub(id, email, referrerId)
+ const data = await this.registerUserGithub(id, email, referrerId)
+
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'SIGNUP',
+ meta: {
+ method: 'github',
+ isReferred: !!referrerId,
+ },
+ })
+
+ return data
}
return await this.handleExistingUserGithub(user, headers, ip)
diff --git a/backend/apps/cloud/src/common/analytics.ts b/backend/apps/cloud/src/common/analytics.ts
new file mode 100644
index 000000000..1bd7a574f
--- /dev/null
+++ b/backend/apps/cloud/src/common/analytics.ts
@@ -0,0 +1,23 @@
+import { Swetrix, type TrackEventOptions } from '@swetrix/node'
+import { isDevelopment } from './constants'
+
+const swetrix = new Swetrix(process.env.SWETRIX_PID, {
+ // Same port as in main.ts
+ apiURL: 'http://localhost:5005',
+ devMode: isDevelopment,
+})
+
+export const trackCustom = (
+ ip: string,
+ userAgent: string,
+ options: Omit<TrackEventOptions, 'meta'> & {
+ meta?: Record<string, string | number | boolean>
+ },
+) => {
+ try {
+ // @ts-expect-error - Will be fixed in the next version of the library
+ swetrix.track(ip, userAgent, options)
+ } catch (reason) {
+ console.error('[ERROR] Failed to track custom event:', reason)
+ }
+}
diff --git a/backend/apps/cloud/src/experiment/experiment.controller.ts b/backend/apps/cloud/src/experiment/experiment.controller.ts
index fc601d9c2..7af1690ec 100644
--- a/backend/apps/cloud/src/experiment/experiment.controller.ts
+++ b/backend/apps/cloud/src/experiment/experiment.controller.ts
@@ -64,6 +64,7 @@ import {
} from '../feature-flag/entity/feature-flag.entity'
import { clickhouse } from '../common/integrations/clickhouse'
import { calculateBayesianProbabilities } from './bayesian'
+import { trackCustom } from '../common/analytics'
const EXPERIMENTS_MAXIMUM = 20 // Maximum experiments per project
@@ -317,6 +318,10 @@ export class ExperimentController {
const newExperiment = await this.experimentService.create(experiment)
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'EXPERIMENT_CREATED',
+ })
+
if (existingFeatureFlag) {
await this.featureFlagService.update(existingFeatureFlag.id, {
experimentId: newExperiment.id,
@@ -557,6 +562,10 @@ export class ExperimentController {
}
await this.experimentService.delete(id)
+
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'EXPERIMENT_DELETED',
+ })
}
@ApiBearerAuth()
diff --git a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts b/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts
index 19092b29c..6af421310 100644
--- a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts
+++ b/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts
@@ -58,6 +58,7 @@ import {
checkRateLimit,
} from '../common/utils'
import { getExperimentVariant } from './evaluation'
+import { trackCustom } from '../common/analytics'
const FEATURE_FLAGS_MAXIMUM = 50 // Maximum feature flags per project
@@ -151,8 +152,11 @@ export class FeatureFlagController {
async createFeatureFlag(
@Body() flagDto: CreateFeatureFlagDto,
@CurrentUserId() uid: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
) {
this.logger.log({ uid, pid: flagDto.pid }, 'POST /feature-flag')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
const user = await this.userService.findOne({
where: { id: uid },
@@ -228,6 +232,10 @@ export class FeatureFlagController {
const newFlag = await this.featureFlagService.create(flag)
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'FEATURE_FLAG_CREATED',
+ })
+
return {
..._omit(newFlag, ['project']),
pid: flagDto.pid,
@@ -503,8 +511,11 @@ export class FeatureFlagController {
async deleteFeatureFlag(
@Param('id') id: string,
@CurrentUserId() uid: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
) {
this.logger.log({ id, uid }, 'DELETE /feature-flag/:id')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
const flag = await this.featureFlagService.findOneWithRelations(id)
@@ -519,6 +530,10 @@ export class FeatureFlagController {
)
await this.featureFlagService.delete(id)
+
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'FEATURE_FLAG_DELETED',
+ })
}
@ApiBearerAuth()
diff --git a/backend/apps/cloud/src/goal/goal.controller.ts b/backend/apps/cloud/src/goal/goal.controller.ts
index 070cd8a7a..f592e36a8 100644
--- a/backend/apps/cloud/src/goal/goal.controller.ts
+++ b/backend/apps/cloud/src/goal/goal.controller.ts
@@ -13,6 +13,8 @@ import {
HttpException,
HttpStatus,
ParseIntPipe,
+ Ip,
+ Headers,
} from '@nestjs/common'
import { ApiTags, ApiResponse, ApiBearerAuth } from '@nestjs/swagger'
import _isEmpty from 'lodash/isEmpty'
@@ -41,6 +43,8 @@ import {
} from './dto/goal.dto'
import { GoalService } from './goal.service'
import { clickhouse } from '../common/integrations/clickhouse'
+import { getIPFromHeaders } from '../common/utils'
+import { trackCustom } from '../common/analytics'
const GOALS_MAXIMUM = 50 // Maximum goals per project
@@ -139,9 +143,13 @@ export class GoalController {
async createGoal(
@Body() goalDto: CreateGoalDto,
@CurrentUserId() uid: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
) {
this.logger.log({ uid, pid: goalDto.pid }, 'POST /goal')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
const user = await this.userService.findOne({
where: { id: uid },
relations: ['projects'],
@@ -204,6 +212,10 @@ export class GoalController {
const newGoal = await this.goalService.create(goal)
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'GOAL_CREATED',
+ })
+
return {
..._omit(newGoal, ['project']),
pid: goalDto.pid,
@@ -265,9 +277,16 @@ export class GoalController {
@Delete('/:id')
@Auth()
@ApiResponse({ status: 204, description: 'Empty body' })
- async deleteGoal(@Param('id') id: string, @CurrentUserId() uid: string) {
+ async deleteGoal(
+ @Param('id') id: string,
+ @CurrentUserId() uid: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
+ ) {
this.logger.log({ id, uid }, 'DELETE /goal/:id')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
const goal = await this.goalService.findOneWithRelations(id)
if (_isEmpty(goal)) {
@@ -281,6 +300,10 @@ export class GoalController {
)
await this.goalService.delete(id)
+
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'GOAL_DELETED',
+ })
}
private buildGoalMatchCondition(
diff --git a/backend/apps/cloud/src/organisation/organisation.controller.ts b/backend/apps/cloud/src/organisation/organisation.controller.ts
index 315ef9975..fa514e47c 100644
--- a/backend/apps/cloud/src/organisation/organisation.controller.ts
+++ b/backend/apps/cloud/src/organisation/organisation.controller.ts
@@ -40,6 +40,7 @@ import { ProjectService } from '../project/project.service'
import { Project } from '../project/entity'
import { isDevelopment, PRODUCTION_ORIGIN } from '../common/constants'
import { checkRateLimit, getIPFromHeaders } from '../common/utils'
+import { trackCustom } from '../common/analytics'
const ORGANISATION_INVITE_EXPIRE = 7 * 24 // 7 days in hours
@@ -127,9 +128,13 @@ export class OrganisationController {
async create(
@Body() createOrgDTO: CreateOrganisationDTO,
@CurrentUserId() uid: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
): Promise<Organisation> {
this.logger.log({ uid, createOrgDTO }, 'POST /organisation')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
const user = await this.userService.findOne({ where: { id: uid } })
const organisation = await this.organisationService.create({
@@ -143,6 +148,10 @@ export class OrganisationController {
confirmed: true,
})
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'ORGANISATION_CREATED',
+ })
+
return organisation
}
@@ -342,9 +351,16 @@ export class OrganisationController {
@Delete('/:orgId')
@ApiResponse({ status: 200, type: Organisation })
@Auth(true)
- async delete(@Param('orgId') orgId: string, @CurrentUserId() userId: string) {
+ async delete(
+ @Param('orgId') orgId: string,
+ @CurrentUserId() userId: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
+ ) {
this.logger.log({ orgId, userId }, 'DELETE /organisation/:orgId')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
const isOwner = await this.organisationService.isOrganisationOwner(
orgId,
userId,
@@ -364,6 +380,10 @@ export class OrganisationController {
organisation: { id: orgId },
})
await this.organisationService.delete(orgId)
+
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'ORGANISATION_DELETED',
+ })
} catch (reason) {
console.error('[ERROR] Failed to delete organisation:', reason)
throw new BadRequestException('Failed to delete organisation')
diff --git a/backend/apps/cloud/src/project/gsc.controller.ts b/backend/apps/cloud/src/project/gsc.controller.ts
index 7279755d3..d137e6293 100644
--- a/backend/apps/cloud/src/project/gsc.controller.ts
+++ b/backend/apps/cloud/src/project/gsc.controller.ts
@@ -8,6 +8,8 @@ import {
UseGuards,
BadRequestException,
HttpCode,
+ Ip,
+ Headers,
} from '@nestjs/common'
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'
@@ -16,6 +18,8 @@ import { Auth } from '../auth/decorators'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
import { GSCService } from './gsc.service'
import { ProjectService } from './project.service'
+import { trackCustom } from '../common/analytics'
+import { getIPFromHeaders } from '../common/utils'
@ApiTags('Project - Google Search Console')
@UseGuards(AuthenticationGuard)
@@ -31,12 +35,22 @@ export class GSCController {
async processGSCToken(
@Body() body: { code: string; state: string },
@CurrentUserId() uid: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
) {
+ const ip = getIPFromHeaders(headers) || requestIp || ''
const { code, state } = body
+
if (!code || !state) {
throw new BadRequestException('Invalid GSC token parameters')
}
+
const { pid } = await this.gscService.handleOAuthCallback(uid, code, state)
+
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'GSC_CONNECTED',
+ })
+
return { pid }
}
@@ -85,9 +99,20 @@ export class GSCController {
@Delete(':pid/disconnect')
@Auth()
@HttpCode(204)
- async disconnect(@Param('pid') pid: string, @CurrentUserId() uid: string) {
+ async disconnect(
+ @Param('pid') pid: string,
+ @CurrentUserId() uid: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
+ ) {
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
const project = await this.projectService.getRedisProject(pid)
this.projectService.allowedToManage(project, uid)
await this.gscService.disconnect(pid)
+
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'GSC_DISCONNECTED',
+ })
}
}
diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.ts
index 153b13042..475e23188 100644
--- a/backend/apps/cloud/src/project/project.controller.ts
+++ b/backend/apps/cloud/src/project/project.controller.ts
@@ -114,6 +114,7 @@ import { ProjectViewIdsDto } from './dto/project-view-ids.dto'
import { OrganisationService } from '../organisation/organisation.service'
import { Organisation } from '../organisation/entity/organisation.entity'
import { ProjectOrganisationDto } from './dto/project-organisation.dto'
+import { trackCustom } from '../common/analytics'
const PROJECTS_MAXIMUM = 50
@@ -232,9 +233,13 @@ export class ProjectController {
async pinProject(
@Param('id') projectId: string,
@CurrentUserId() userId: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
): Promise<void> {
this.logger.log({ projectId, userId }, 'POST /project/:id/pin')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
if (!isValidPID(projectId)) {
throw new BadRequestException('The provided project ID is incorrect')
}
@@ -248,6 +253,10 @@ export class ProjectController {
this.projectService.allowedToView(project, userId)
await this.projectService.pinProject(userId, projectId)
+
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'PROJECT_PINNED',
+ })
}
@ApiBearerAuth()
@@ -258,14 +267,22 @@ export class ProjectController {
async unpinProject(
@Param('id') projectId: string,
@CurrentUserId() userId: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
): Promise<void> {
this.logger.log({ projectId, userId }, 'DELETE /project/:id/pin')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
if (!isValidPID(projectId)) {
throw new BadRequestException('The provided project ID is incorrect')
}
await this.projectService.unpinProject(userId, projectId)
+
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'PROJECT_UNPINNED',
+ })
}
@ApiBearerAuth()
@@ -274,9 +291,12 @@ export class ProjectController {
@Auth(true)
async create(
@Body() projectDTO: CreateProjectDTO,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
@CurrentUserId() userId: string,
): Promise<Omit<Project, 'passwordHash'>> {
this.logger.log({ projectDTO, userId }, 'POST /project')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
if (!userId) {
throw new UnauthorizedException('Please auth first')
@@ -364,6 +384,10 @@ export class ProjectController {
const newProject = await this.projectService.create(project)
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'PROJECT_CREATED',
+ })
+
return _omit(newProject, ['passwordHash'])
} catch (reason) {
console.error('[ERROR] Failed to create a new project:')
@@ -378,9 +402,13 @@ export class ProjectController {
async createFunnel(
@Body() funnelDTO: FunnelCreateDTO,
@CurrentUserId() userId: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
): Promise<any> {
this.logger.log({ funnelDTO, userId }, 'POST /project/funnel')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
if (!userId) {
throw new UnauthorizedException('Please auth first')
}
@@ -419,6 +447,13 @@ export class ProjectController {
this.projectService.allowedToManage(project, userId)
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'FUNNEL_CREATED',
+ meta: {
+ steps_quantity: funnelDTO.steps.length,
+ },
+ })
+
return this.projectService.createFunnel(project.id, funnelDTO)
}
@@ -499,9 +534,13 @@ export class ProjectController {
@Param('id') id: string,
@Param('pid') pid: string,
@CurrentUserId() userId: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
): Promise<void> {
this.logger.log({ id, userId }, 'PATCH /project/funnel')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
if (!userId) {
throw new UnauthorizedException('Please auth first')
}
@@ -521,6 +560,13 @@ export class ProjectController {
}
await this.projectService.deleteFunnel(id)
+
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'FUNNEL_DELETED',
+ meta: {
+ steps_quantity: oldFunnel.steps.length,
+ },
+ })
}
@Get('/funnels/:pid')
@@ -554,9 +600,13 @@ export class ProjectController {
async createAnnotation(
@Body() annotationDTO: AnnotationCreateDTO,
@CurrentUserId() userId: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
): Promise<any> {
this.logger.log({ annotationDTO, userId }, 'POST /project/annotation')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
if (!userId) {
throw new UnauthorizedException('Please auth first')
}
@@ -581,6 +631,13 @@ export class ProjectController {
this.projectService.allowedToManage(project, userId)
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'ANNOTATION_CREATED',
+ meta: {
+ length: annotationDTO.text.length,
+ },
+ })
+
return this.projectService.createAnnotation(project.id, annotationDTO)
}
@@ -1482,9 +1539,13 @@ export class ProjectController {
async delete(
@Param('id') id: string,
@CurrentUserId() uid: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
): Promise<any> {
this.logger.log({ uid, id }, 'DELETE /project/:id')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
if (!uid) {
throw new UnauthorizedException('Please auth first')
}
@@ -1536,6 +1597,10 @@ export class ProjectController {
return 'Error while deleting your project'
}
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'PROJECT_DELETED',
+ })
+
return 'Project deleted successfully'
}
@@ -1927,7 +1992,11 @@ export class ProjectController {
@Param() params: ProjectIdDto,
@Body() body: CreateProjectViewDto,
@CurrentUserId() userId: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
) {
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
const project = await this.projectService.getFullProject(params.projectId)
if (!project) {
@@ -1954,6 +2023,15 @@ export class ProjectController {
),
})
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'SEGMENT_CREATED',
+ meta: {
+ type: body.type,
+ filters: !_isEmpty(body.filters),
+ customEvents: !_isEmpty(body.customEvents),
+ },
+ })
+
return _omit(createdProjectView, ['project'])
}
@@ -2033,7 +2111,11 @@ export class ProjectController {
async deleteProjectView(
@Param() params: ProjectViewIdsDto,
@CurrentUserId() userId: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
) {
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
const project = await this.projectService.getFullProject(params.projectId)
if (!project) {
@@ -2058,5 +2140,9 @@ export class ProjectController {
}
await this.projectsViewsRepository.deleteProjectView(params.viewId)
+
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'SEGMENT_DELETED',
+ })
}
}
diff --git a/backend/apps/cloud/src/revenue/revenue.controller.ts b/backend/apps/cloud/src/revenue/revenue.controller.ts
index 306f8cea8..d77385faf 100644
--- a/backend/apps/cloud/src/revenue/revenue.controller.ts
+++ b/backend/apps/cloud/src/revenue/revenue.controller.ts
@@ -8,6 +8,8 @@ import {
Body,
NotFoundException,
BadRequestException,
+ Ip,
+ Headers,
} from '@nestjs/common'
import { ApiTags, ApiResponse, ApiBearerAuth } from '@nestjs/swagger'
import _isEmpty from 'lodash/isEmpty'
@@ -34,6 +36,8 @@ import {
RevenueStatusDto,
} from './dto/revenue-stats.dto'
import { STRIPE_REQUIRED_PERMISSIONS } from './interfaces/revenue.interface'
+import { trackCustom } from '../common/analytics'
+import { getIPFromHeaders } from '../common/utils'
@ApiTags('Revenue')
@Controller('project')
@@ -76,7 +80,11 @@ export class RevenueController {
@CurrentUserId() userId: string,
@Param('pid') pid: string,
@Body() dto: ConnectRevenueDto,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
) {
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
this.logger.log({ userId, pid }, 'POST /project/:pid/revenue/connect')
const project = await this.projectService.getFullProject(pid)
@@ -134,6 +142,13 @@ export class RevenueController {
throw new BadRequestException(result.message)
}
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'REVENUE_SETUP',
+ meta: {
+ provider: dto.provider,
+ },
+ })
+
return { success: true }
}
@@ -144,9 +159,13 @@ export class RevenueController {
async disconnectRevenue(
@CurrentUserId() userId: string,
@Param('pid') pid: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
) {
this.logger.log({ userId, pid }, 'DELETE /project/:pid/revenue/disconnect')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
const project = await this.projectService.getFullProject(pid)
if (_isEmpty(project)) {
@@ -160,6 +179,10 @@ export class RevenueController {
)
await this.revenueService.disconnectRevenue(pid)
+
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'REVENUE_DISCONNECTED',
+ })
}
@ApiBearerAuth()
@@ -224,70 +247,6 @@ export class RevenueController {
return { success: true }
}
-
- @ApiBearerAuth()
- @Post('/:pid/revenue/sync')
- @Auth()
- async syncRevenue(
- @CurrentUserId() userId: string,
- @Param('pid') pid: string,
- ) {
- this.logger.log({ userId, pid }, 'POST /project/:pid/revenue/sync')
-
- const project = await this.projectService.getFullProject(pid)
-
- if (_isEmpty(project)) {
- throw new NotFoundException('Project not found')
- }
-
- this.projectService.allowedToManage(
- project,
- userId,
- 'You are not allowed to manage revenue settings for this project',
- )
-
- const currency = project.revenueCurrency || 'USD'
-
- if (!project.paddleApiKeyEnc && !project.stripeApiKeyEnc) {
- throw new BadRequestException(
- 'Revenue tracking is not connected to this project',
- )
- }
-
- if (project.paddleApiKeyEnc) {
- const apiKey = this.revenueService.getPaddleApiKey(project)
- if (!apiKey) {
- throw new BadRequestException('Failed to decrypt Paddle API key')
- }
-
- const count = await this.paddleAdapter.syncTransactions(
- pid,
- apiKey,
- currency,
- project.revenueLastSyncAt || undefined,
- )
-
- await this.revenueService.updateLastSyncAt(pid)
- return { success: true, transactionsSynced: count }
- }
-
- // Stripe
- const apiKey = this.revenueService.getStripeApiKey(project)
- if (!apiKey) {
- throw new BadRequestException('Failed to decrypt Stripe API key')
- }
-
- const count = await this.stripeAdapter.syncTransactions(
- pid,
- apiKey,
- currency,
- project.revenueLastSyncAt || undefined,
- )
-
- await this.revenueService.updateLastSyncAt(pid)
-
- return { success: true, transactionsSynced: count }
- }
}
@ApiTags('Revenue Analytics')
diff --git a/backend/apps/cloud/src/user/user.controller.ts b/backend/apps/cloud/src/user/user.controller.ts
index 74c3b2ae0..26203aad8 100644
--- a/backend/apps/cloud/src/user/user.controller.ts
+++ b/backend/apps/cloud/src/user/user.controller.ts
@@ -66,6 +66,7 @@ import {
import { IUsageInfo, IMetaInfo } from './interfaces'
import { ReportFrequency } from '../project/enums'
import { OrganisationService } from '../organisation/organisation.service'
+import { trackCustom } from '../common/analytics'
dayjs.extend(utc)
@@ -200,20 +201,34 @@ export class UserController {
await this.userService.update(userId, { apiKey })
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'API_KEY_GENERATED',
+ })
+
return { apiKey }
}
@ApiBearerAuth()
@Delete('/api-key')
- async deleteApiKey(@CurrentUserId() userId: string): Promise<void> {
+ async deleteApiKey(
+ @CurrentUserId() userId: string,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
+ ): Promise<void> {
this.logger.log({ userId }, 'DELETE /user/api-key')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
const user = await this.userService.findOne({ where: { id: userId } })
if (_isNull(user.apiKey)) {
throw new ConflictException("You don't have an API key")
}
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'API_KEY_DELETED',
+ })
+
await this.userService.update(userId, { apiKey: null })
}
@@ -223,9 +238,13 @@ export class UserController {
async deleteSelf(
@CurrentUserId() id: string,
@Body() deleteSelfDTO: DeleteSelfDTO,
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
): Promise<any> {
this.logger.log({ id }, 'DELETE /user')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
const user = await this.userService.findOne({
where: { id },
relations: ['projects'],
@@ -286,6 +305,13 @@ export class UserController {
this.logger.error('DeleteSelfDTO: ', deleteSelfDTO)
}
+ trackCustom(ip, headers['user-agent'], {
+ ev: 'ACCOUNT_DELETED',
+ meta: {
+ reason_stated: !!deleteSelfDTO.feedback,
+ },
+ })
+
return 'accountDeleted'
}
diff --git a/backend/package-lock.json b/backend/package-lock.json
index 5c7b9a650..cdbc03ac4 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -29,6 +29,7 @@
"@sentry/cli": "^2.58.2",
"@sentry/nestjs": "^10.27.0",
"@sentry/profiling-node": "^10.27.0",
+ "@swetrix/node": "^2.1.0",
"@ua-parser-js/pro-business": "^2.0.6",
"ai": "^4.3.16",
"axios": "^1.13.2",
@@ -4740,6 +4741,62 @@
"integrity": "sha512-Uy0+khmZqUrUGm5dmMqVlnvufZRSK0FbYzVgp0UMstm+F5+W2/jnEEQyc9vo1ZR/E5ZI/B1WjjoTqBqwJL6Krw==",
"license": "MIT"
},
+ "node_modules/@swetrix/node": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/@swetrix/node/-/node-2.1.0.tgz",
+ "integrity": "sha512-oqtAefT/O7lXhRPYEBRlhwCVAoQai2Xewk1u1uLpSl11ATTKQVQDMz8wcvaXBoMIwdTf4Mi8/c0qXdnh5bkf1g==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "^20.6.0",
+ "node-fetch": "^3.3.2",
+ "tslib": "^2.6.2"
+ },
+ "funding": {
+ "url": "https://ko-fi.com/andriir"
+ }
+ },
+ "node_modules/@swetrix/node/node_modules/@types/node": {
+ "version": "20.19.27",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.27.tgz",
+ "integrity": "sha512-N2clP5pJhB2YnZJ3PIHFk5RkygRX5WO/5f0WC08tp0wd+sv0rsJk3MqWn3CbNmT2J505a5336jaQj4ph1AdMug==",
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~6.21.0"
+ }
+ },
+ "node_modules/@swetrix/node/node_modules/data-uri-to-buffer": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
+ "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
+ "node_modules/@swetrix/node/node_modules/node-fetch": {
+ "version": "3.3.2",
+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",
+ "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",
+ "license": "MIT",
+ "dependencies": {
+ "data-uri-to-buffer": "^4.0.0",
+ "fetch-blob": "^3.1.4",
+ "formdata-polyfill": "^4.0.10"
+ },
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/node-fetch"
+ }
+ },
+ "node_modules/@swetrix/node/node_modules/undici-types": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
+ "license": "MIT"
+ },
"node_modules/@telegraf/types": {
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/@telegraf/types/-/types-7.1.0.tgz",
diff --git a/backend/package.json b/backend/package.json
index f95504bf6..5f7024542 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -49,6 +49,7 @@
"@sentry/cli": "^2.58.2",
"@sentry/nestjs": "^10.27.0",
"@sentry/profiling-node": "^10.27.0",
+ "@swetrix/node": "^2.1.0",
"@ua-parser-js/pro-business": "^2.0.6",
"ai": "^4.3.16",
"axios": "^1.13.2",
diff --git a/web/app/components/Header/index.tsx b/web/app/components/Header/index.tsx
index a6d134e56..320341c5e 100644
--- a/web/app/components/Header/index.tsx
+++ b/web/app/components/Header/index.tsx
@@ -234,7 +234,7 @@ const ProfileMenu = ({ logoutHandler }: { logoutHandler: () => void }) => {
<Disclosure>
{({ open }) => (
<>
- <DisclosureButton className='flex w-full justify-between rounded-md p-2 text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-700'>
+ <DisclosureButton className='flex w-full justify-between rounded-md p-2 text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-800/60'>
<div className='flex'>
<Flag
className='mr-1.5 rounded-xs'
@@ -300,7 +300,7 @@ const ProfileMenu = ({ logoutHandler }: { logoutHandler: () => void }) => {
href={CONTACT_US_URL}
target='_blank'
rel='noopener noreferrer'
- className='block rounded-md p-2 text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-700'
+ className='block rounded-md p-2 text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-800/60'
>
{t('footer.support')}
</a>
@@ -309,7 +309,7 @@ const ProfileMenu = ({ logoutHandler }: { logoutHandler: () => void }) => {
<MenuItem>
<Link
to={routes.contact}
- className='block rounded-md p-2 text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-700'
+ className='block rounded-md p-2 text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-800/60'
>
{t('footer.support')}
</Link>
@@ -319,7 +319,7 @@ const ProfileMenu = ({ logoutHandler }: { logoutHandler: () => void }) => {
<MenuItem>
<Link
to={routes.billing}
- className='block rounded-md p-2 text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-700'
+ className='block rounded-md p-2 text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-800/60'
>
{t('common.billing')}
</Link>
@@ -331,7 +331,7 @@ const ProfileMenu = ({ logoutHandler }: { logoutHandler: () => void }) => {
<MenuItem>
<Link
to={routes.user_settings}
- className='block rounded-md p-2 text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-700'
+ className='block rounded-md p-2 text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-800/60'
>
{t('common.accountSettings')}
</Link>
@@ -340,7 +340,7 @@ const ProfileMenu = ({ logoutHandler }: { logoutHandler: () => void }) => {
<MenuItem>
<Link
to={routes.organisations}
- className='block rounded-md p-2 text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-700'
+ className='block rounded-md p-2 text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-800/60'
>
{t('organisations.organisations')}
</Link>
@@ -349,7 +349,7 @@ const ProfileMenu = ({ logoutHandler }: { logoutHandler: () => void }) => {
<MenuItem>
<button
type='button'
- className='w-full rounded-md p-2 text-left text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-700'
+ className='w-full rounded-md p-2 text-left text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-800/60'
onClick={logoutHandler}
>
{t('common.logout')}
diff --git a/web/app/pages/Auth/Signup/Signup.tsx b/web/app/pages/Auth/Signup/Signup.tsx
index 72d2383d7..f31a14661 100644
--- a/web/app/pages/Auth/Signup/Signup.tsx
+++ b/web/app/pages/Auth/Signup/Signup.tsx
@@ -21,7 +21,6 @@ import Input from '~/ui/Input'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
import { setAccessToken } from '~/utils/accessToken'
-import { trackCustom } from '~/utils/analytics'
import { deleteCookie, getCookie } from '~/utils/cookie'
import { cn, delay, openBrowserWindow } from '~/utils/generic'
import { setRefreshToken } from '~/utils/refreshToken'
@@ -140,9 +139,6 @@ const Signup = () => {
setRefreshToken(refreshToken)
setIsLoading(false)
- trackCustom('SIGNUP', {
- from: 'Signup page',
- })
navigate(routes.onboarding)
} catch (reason) {
toast.error((reason as { message?: string })?.message || t('apiNotifications.somethingWentWrong'))
diff --git a/web/app/pages/Dashboard/Dashboard.tsx b/web/app/pages/Dashboard/Dashboard.tsx
index e971078ba..6ee941a65 100644
--- a/web/app/pages/Dashboard/Dashboard.tsx
+++ b/web/app/pages/Dashboard/Dashboard.tsx
@@ -24,7 +24,6 @@ import Modal from '~/ui/Modal'
import Pagination from '~/ui/Pagination'
import Select from '~/ui/Select'
import { Text } from '~/ui/Text'
-import { trackCustom } from '~/utils/analytics'
import { setCookie } from '~/utils/cookie'
import routes from '~/utils/routes'
@@ -211,9 +210,6 @@ const Dashboard = () => {
name: newProjectName || DEFAULT_PROJECT_NAME,
organisationId: newProjectOrganisationId,
})
- trackCustom('PROJECT_CREATED', {
- from: 'dashboard-modal',
- })
await refetchProjects()
diff --git a/web/app/pages/Onboarding/Onboarding.tsx b/web/app/pages/Onboarding/Onboarding.tsx
index 1951992ea..7f931a462 100644
--- a/web/app/pages/Onboarding/Onboarding.tsx
+++ b/web/app/pages/Onboarding/Onboarding.tsx
@@ -173,10 +173,6 @@ const Onboarding = () => {
setProject(newProject)
await updateUserStep('setup_tracking')
setCurrentStep(2)
-
- trackCustom('PROJECT_CREATED', {
- from: 'onboarding',
- })
} catch (reason) {
toast.error(typeof reason === 'string' ? reason : 'Failed to create project')
} finally {
@@ -184,7 +180,7 @@ const Onboarding = () => {
}
}
- const handleCompleteOnboarding = async (skipped = false) => {
+ const handleCompleteOnboarding = async (skipped: boolean) => {
try {
await completeOnboarding()
await loadUser()
@@ -599,7 +595,7 @@ const Onboarding = () => {
>
{t('common.goBack')}
</Button>
- <Button onClick={handleCompleteOnboarding} primary large>
+ <Button onClick={() => handleCompleteOnboarding(false)} primary large>
{t('onboarding.finishOnboarding')}
</Button>
</div>
diff --git a/web/app/pages/Project/Settings/tabs/DangerZone.tsx b/web/app/pages/Project/Settings/tabs/DangerZone.tsx
index 5892e7ab1..36360f881 100644
--- a/web/app/pages/Project/Settings/tabs/DangerZone.tsx
+++ b/web/app/pages/Project/Settings/tabs/DangerZone.tsx
@@ -22,7 +22,7 @@ const DangerZone = ({ setShowTransfer, setShowReset, setShowDelete, isDeleting,
<div className='mt-4 space-y-3'>
<div className='rounded-md border border-gray-200 p-3 dark:border-gray-800'>
<div className='flex items-start'>
- <ArrowLeftRight className='mt-0.5 h-5 w-5 text-red-600 dark:text-red-400' />
+ <ArrowLeftRight className='mt-0.5 h-5 w-5 text-red-700 dark:text-red-500' />
<div className='ml-3 flex-1'>
<div className='text-sm font-medium text-gray-900 dark:text-gray-50'>
{t('project.settings.transfer')}
@@ -39,7 +39,7 @@ const DangerZone = ({ setShowTransfer, setShowReset, setShowDelete, isDeleting,
<div className='rounded-md border border-gray-200 p-3 dark:border-gray-800'>
<div className='flex items-start'>
- <RotateCcw className='mt-0.5 h-5 w-5 text-orange-600 dark:text-orange-400' />
+ <RotateCcw className='mt-0.5 h-5 w-5 text-red-700 dark:text-red-500' />
<div className='ml-3 flex-1'>
<div className='text-sm font-medium text-gray-900 dark:text-gray-50'>{t('project.settings.reset')}</div>
<p className='mt-0.5 text-sm text-gray-500 dark:text-gray-400'>{t('project.settings.resetShort')}</p>
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index b48eaa25c..ac63b28b8 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -62,6 +62,7 @@ import { useTheme } from '~/providers/ThemeProvider'
import Dropdown from '~/ui/Dropdown'
import Flag from '~/ui/Flag'
import Loader from '~/ui/Loader'
+import { trackCustom } from '~/utils/analytics'
import { getItem, setItem } from '~/utils/localstorage'
import routes from '~/utils/routes'
@@ -650,6 +651,7 @@ const ViewProjectContent = () => {
const newSearchParams = new URLSearchParams(searchParams.toString())
newSearchParams.set('tab', key)
setSearchParams(newSearchParams)
+ trackCustom('DASHBOARD_TAB_CHANGED', { tab: key })
}
const refreshStats = useCallback(
@@ -1049,7 +1051,6 @@ const ViewProjectContent = () => {
{!isEmbedded ? <Header /> : null}
<div className='flex min-h-screen flex-col bg-gray-50 dark:bg-slate-900'>
<div className='relative flex flex-1'>
- {/* Real Sidebar */}
<ProjectSidebar
tabs={tabs}
activeTab={activeTab}
@@ -1062,7 +1063,6 @@ const ViewProjectContent = () => {
className='hidden md:flex'
/>
- {/* Skeleton Main Content */}
<div className='flex flex-1 flex-col px-4 py-2 sm:px-6 lg:px-8'>
{/* Skeleton header */}
<div className='mb-6 flex items-center justify-between'>
diff --git a/web/app/pages/Project/View/components/CurrentTime.tsx b/web/app/pages/Project/View/components/CurrentTime.tsx
index 0cf593c09..83acec744 100644
--- a/web/app/pages/Project/View/components/CurrentTime.tsx
+++ b/web/app/pages/Project/View/components/CurrentTime.tsx
@@ -28,9 +28,11 @@ const CurrentTime = () => {
<Tooltip
text={
<div className='flex flex-col'>
- <Text weight='semibold'>{t('project.timezoneX', { timezone })}</Text>
+ <Text className='text-gray-50' weight='semibold' size='xs'>
+ {t('project.timezoneX', { timezone })}
+ </Text>
{isEmbedded ? null : (
- <Text size='xs' colour='muted'>
+ <Text size='xs' colour='secondary' className='mt-1 text-gray-200'>
{isAuthenticated ? t('project.changeInSettings') : t('project.signInToChange')}
</Text>
)}
diff --git a/web/app/pages/Project/View/components/ProjectSidebar.tsx b/web/app/pages/Project/View/components/ProjectSidebar.tsx
index 44438bc6e..b15550e5f 100644
--- a/web/app/pages/Project/View/components/ProjectSidebar.tsx
+++ b/web/app/pages/Project/View/components/ProjectSidebar.tsx
@@ -15,6 +15,7 @@ import { Link, LinkProps } from 'react-router'
import { PROJECT_TABS } from '~/lib/constants'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
+import { trackCustom } from '~/utils/analytics'
import { cn } from '~/utils/generic'
import routes from '~/utils/routes'
@@ -273,6 +274,7 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
setIsCollapsed((prev) => {
const newValue = !prev
localStorage.setItem(SIDEBAR_COLLAPSED_KEY, String(newValue))
+ trackCustom('SIDEBAR_COLLAPSED', { collapsed: newValue })
return newValue
})
}, [])
@@ -400,7 +402,7 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
<div className='flex-1 overflow-y-auto px-2 py-3'>
{/* Ask AI - standalone tab above groups */}
{askAiTab ? (
- <div className='mb-3'>
+ <div className='mb-1'>
{(() => {
const isCurrent = askAiTab.id === activeTab
const TabIcon = askAiTab.icon
diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsx
index d5be3f0cc..c8994967e 100644
--- a/web/app/pages/UserSettings/UserSettings.tsx
+++ b/web/app/pages/UserSettings/UserSettings.tsx
@@ -39,7 +39,6 @@ import Select from '~/ui/Select'
import { Text } from '~/ui/Text'
import Textarea from '~/ui/Textarea'
import TimezonePicker from '~/ui/TimezonePicker'
-import { trackCustom } from '~/utils/analytics'
import { getCookie, setCookie } from '~/utils/cookie'
import routes from '~/utils/routes'
import { isValidEmail, isValidPassword, MIN_PASSWORD_CHARS } from '~/utils/validator'
@@ -313,9 +312,6 @@ const UserSettings = () => {
await deleteUser(deletionFeedback)
logout()
toast.success(t('apiNotifications.accountDeleted'))
- trackCustom('ACCOUNT_DELETED', {
- reason_stated: deletionFeedback ? 'true' : 'false',
- })
navigate(routes.main)
} catch (reason: any) {
toast.error(t(`apiNotifications.${reason}`, 'apiNotifications.somethingWentWrong'))
diff --git a/web/app/pages/UserSettings/components/Integrations.tsx b/web/app/pages/UserSettings/components/Integrations.tsx
index 4d80c0d7f..a5e173e76 100644
--- a/web/app/pages/UserSettings/components/Integrations.tsx
+++ b/web/app/pages/UserSettings/components/Integrations.tsx
@@ -14,6 +14,7 @@ import Discord from '~/ui/icons/Discord'
import Slack from '~/ui/icons/Slack'
import Telegram from '~/ui/icons/Telegram'
import Input from '~/ui/Input'
+import { trackCustom } from '~/utils/analytics'
const getAvailableIntegrations = (
t: typeof i18next.t,
@@ -126,6 +127,10 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
},
)
}
+
+ trackCustom('INTEGRATION_ADDED', {
+ integration: key,
+ })
}
const getIntegrationStatus = (key: string) => {
@@ -225,6 +230,10 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
},
)
}
+
+ trackCustom('INTEGRATION_REMOVED', {
+ integration: key,
+ })
}
if (integrationConfigurating) {
diff --git a/web/app/utils/analytics.ts b/web/app/utils/analytics.ts
index 80100cc5e..fd3fda683 100644
--- a/web/app/utils/analytics.ts
+++ b/web/app/utils/analytics.ts
@@ -178,5 +178,7 @@ export const trackCustom = (ev: string, meta?: Swetrix.TrackEventOptions['meta']
Swetrix.track({
ev,
meta,
+ }).catch((reason) => {
+ console.error('Failed to track custom event:', reason)
})
}