📈 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
Goals analytics
Blue Mouse454b485aa027
diff --git a/backend/apps/cloud/src/app.module.ts b/backend/apps/cloud/src/app.module.tsindex 10d7c6dc2..890cb697f 100644--- a/backend/apps/cloud/src/app.module.ts+++ b/backend/apps/cloud/src/app.module.ts@@ -20,6 +20,7 @@ import { WebhookModule } from './webhook/webhook.module'import { PingModule } from './ping/ping.module'import { MarketplaceModule } from './marketplace/marketplace.module'import { AlertModule } from './alert/alert.module'+import { GoalModule } from './goal/goal.module'import { getI18nConfig } from './configs'import { AuthModule } from './auth/auth.module'import { CaptchaModule } from './captcha/captcha.module'@@ -77,6 +78,7 @@ const modules = [PingModule,MarketplaceModule,AlertModule,+ GoalModule,AuthModule,CaptchaModule,OgImageModule,diff --git a/backend/apps/cloud/src/goal/dto/goal.dto.ts b/backend/apps/cloud/src/goal/dto/goal.dto.tsnew file mode 100644index 000000000..11b22efab--- /dev/null+++ b/backend/apps/cloud/src/goal/dto/goal.dto.ts@@ -0,0 +1,150 @@+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'+import {+ IsString,+ IsEnum,+ IsOptional,+ IsArray,+ ValidateNested,+ MaxLength,+ IsBoolean,+ IsNotEmpty,+} from 'class-validator'+import { Type } from 'class-transformer'+import { GoalType, GoalMatchType, MetadataFilter } from '../entity/goal.entity'++export class MetadataFilterDto implements MetadataFilter {+ @ApiProperty()+ @IsString()+ @IsNotEmpty()+ key: string++ @ApiProperty()+ @IsString()+ @IsNotEmpty()+ value: string+}++export class CreateGoalDto {+ @ApiProperty({ description: 'Project ID' })+ @IsString()+ @IsNotEmpty()+ pid: string++ @ApiProperty({ description: 'Goal name' })+ @IsString()+ @MaxLength(100)+ @IsNotEmpty()+ name: string++ @ApiProperty({ enum: GoalType, description: 'Type of goal' })+ @IsEnum(GoalType)+ type: GoalType++ @ApiProperty({ enum: GoalMatchType, description: 'How to match the value' })+ @IsEnum(GoalMatchType)+ matchType: GoalMatchType++ @ApiPropertyOptional({ description: 'Page path or event name to match' })+ @IsString()+ @MaxLength(500)+ @IsOptional()+ value?: string++ @ApiPropertyOptional({+ type: [MetadataFilterDto],+ description: 'Optional metadata filters',+ })+ @IsArray()+ @ValidateNested({ each: true })+ @Type(() => MetadataFilterDto)+ @IsOptional()+ metadataFilters?: MetadataFilterDto[]+}++export class UpdateGoalDto {+ @ApiPropertyOptional({ description: 'Goal name' })+ @IsString()+ @MaxLength(100)+ @IsOptional()+ name?: string++ @ApiPropertyOptional({ enum: GoalType, description: 'Type of goal' })+ @IsEnum(GoalType)+ @IsOptional()+ type?: GoalType++ @ApiPropertyOptional({+ enum: GoalMatchType,+ description: 'How to match the value',+ })+ @IsEnum(GoalMatchType)+ @IsOptional()+ matchType?: GoalMatchType++ @ApiPropertyOptional({ description: 'Page path or event name to match' })+ @IsString()+ @MaxLength(500)+ @IsOptional()+ value?: string++ @ApiPropertyOptional({+ type: [MetadataFilterDto],+ description: 'Optional metadata filters',+ })+ @IsArray()+ @ValidateNested({ each: true })+ @Type(() => MetadataFilterDto)+ @IsOptional()+ metadataFilters?: MetadataFilterDto[]++ @ApiPropertyOptional({ description: 'Whether the goal is active' })+ @IsBoolean()+ @IsOptional()+ active?: boolean+}++export class GoalDto {+ @ApiProperty()+ id: string++ @ApiProperty()+ name: string++ @ApiProperty({ enum: GoalType })+ type: GoalType++ @ApiProperty({ enum: GoalMatchType })+ matchType: GoalMatchType++ @ApiPropertyOptional()+ value: string | null++ @ApiPropertyOptional({ type: [MetadataFilterDto] })+ metadataFilters: MetadataFilterDto[] | null++ @ApiProperty()+ active: boolean++ @ApiProperty()+ pid: string++ @ApiProperty()+ created: Date+}++export class GoalStatsDto {+ @ApiProperty({ description: 'Total number of conversions' })+ conversions: number++ @ApiProperty({ description: 'Number of unique sessions that converted' })+ uniqueSessions: number++ @ApiProperty({ description: 'Conversion rate as percentage' })+ conversionRate: number++ @ApiProperty({ description: 'Previous period conversions for trend' })+ previousConversions: number++ @ApiProperty({ description: 'Trend percentage change' })+ trend: number+}diff --git a/backend/apps/cloud/src/goal/entity/goal.entity.ts b/backend/apps/cloud/src/goal/entity/goal.entity.tsnew file mode 100644index 000000000..4778ba033--- /dev/null+++ b/backend/apps/cloud/src/goal/entity/goal.entity.ts@@ -0,0 +1,76 @@+import {+ Column,+ CreateDateColumn,+ Entity,+ JoinColumn,+ ManyToOne,+ PrimaryGeneratedColumn,+} from 'typeorm'+import { ApiProperty } from '@nestjs/swagger'+import { Project } from '../../project/entity/project.entity'++export enum GoalType {+ PAGEVIEW = 'pageview',+ CUSTOM_EVENT = 'custom_event',+}++export enum GoalMatchType {+ EXACT = 'exact',+ CONTAINS = 'contains',+ REGEX = 'regex',+}++export interface MetadataFilter {+ key: string+ value: string+}++@Entity()+export class Goal {+ @ApiProperty()+ @PrimaryGeneratedColumn('uuid')+ id: string++ @ApiProperty()+ @Column('varchar', { length: 100 })+ name: string++ @ApiProperty()+ @Column({+ type: 'enum',+ enum: GoalType,+ })+ type: GoalType++ @ApiProperty()+ @Column({+ type: 'enum',+ enum: GoalMatchType,+ default: GoalMatchType.EXACT,+ })+ matchType: GoalMatchType++ @ApiProperty()+ @Column('varchar', { length: 500, nullable: true })+ value: string | null++ @ApiProperty()+ @Column('json', { nullable: true })+ metadataFilters: MetadataFilter[] | null++ @ApiProperty()+ @Column({+ type: 'boolean',+ default: true,+ })+ active: boolean++ @ApiProperty({ type: () => Project })+ @ManyToOne(() => Project, project => project.goals)+ @JoinColumn()+ project: Project++ @ApiProperty()+ @CreateDateColumn()+ created: Date+}diff --git a/backend/apps/cloud/src/goal/goal.controller.ts b/backend/apps/cloud/src/goal/goal.controller.tsnew file mode 100644index 000000000..cf42fa9a0--- /dev/null+++ b/backend/apps/cloud/src/goal/goal.controller.ts@@ -0,0 +1,670 @@+import {+ Controller,+ Get,+ Put,+ Delete,+ Query,+ Param,+ Body,+ NotFoundException,+ Post,+ ForbiddenException,+ BadRequestException,+ HttpException,+ HttpStatus,+ ParseIntPipe,+} from '@nestjs/common'+import { ApiTags, ApiResponse, ApiBearerAuth } from '@nestjs/swagger'+import _isEmpty from 'lodash/isEmpty'+import _map from 'lodash/map'+import _omit from 'lodash/omit'+import _pick from 'lodash/pick'+import _round from 'lodash/round'+import dayjs from 'dayjs'++import { UserService } from '../user/user.service'+import { ProjectService } from '../project/project.service'+import { AppLoggerService } from '../logger/logger.service'+import { PlanCode } from '../user/entities/user.entity'+import {+ AnalyticsService,+ getLowestPossibleTimeBucket,+} from '../analytics/analytics.service'+import { Auth } from '../auth/decorators'+import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'+import { Goal, GoalType, GoalMatchType } from './entity/goal.entity'+import {+ CreateGoalDto,+ UpdateGoalDto,+ GoalDto,+ GoalStatsDto,+} from './dto/goal.dto'+import { GoalService } from './goal.service'+import { clickhouse } from '../common/integrations/clickhouse'++const GOALS_MAXIMUM = 50 // Maximum goals per project++const timeBucketConversion: Record<string, string> = {+ minute: 'toStartOfMinute',+ hour: 'toStartOfHour',+ day: 'toStartOfDay',+ month: 'toStartOfMonth',+ year: 'toStartOfYear',+}++@ApiTags('Goal')+@Controller('goal')+export class GoalController {+ constructor(+ private readonly goalService: GoalService,+ private readonly projectService: ProjectService,+ private readonly logger: AppLoggerService,+ private readonly userService: UserService,+ private readonly analyticsService: AnalyticsService,+ ) {}++ @ApiBearerAuth()+ @Get('/:goalId')+ @Auth()+ @ApiResponse({ status: 200, type: Goal })+ async getGoal(+ @CurrentUserId() userId: string,+ @Param('goalId') goalId: string,+ ) {+ this.logger.log({ userId, goalId }, 'GET /goal/:goalId')++ const goal = await this.goalService.findOne({+ where: { id: goalId },+ relations: ['project'],+ })++ if (_isEmpty(goal)) {+ throw new NotFoundException('Goal not found')+ }++ const project = await this.projectService.getFullProject(goal.project.id)++ this.projectService.allowedToView(project, userId)++ return {+ ..._omit(goal, ['project']),+ pid: goal.project.id,+ }+ }++ @ApiBearerAuth()+ @Get('/project/:projectId')+ @Auth()+ @ApiResponse({ status: 200, type: [GoalDto] })+ async getProjectGoals(+ @CurrentUserId() userId: string,+ @Param('projectId') projectId: string,+ @Query('take', new ParseIntPipe({ optional: true })) take?: number,+ @Query('skip', new ParseIntPipe({ optional: true })) skip?: number,+ ) {+ this.logger.log(+ { userId, projectId, take, skip },+ 'GET /goal/project/:projectId',+ )++ const project = await this.projectService.getFullProject(projectId)++ if (_isEmpty(project)) {+ throw new NotFoundException('Project not found')+ }++ this.projectService.allowedToView(project, userId)++ const result = await this.goalService.paginate(+ { take, skip },+ { project: { id: projectId } },+ ['project'],+ )++ // @ts-expect-error+ result.results = _map(result.results, goal => ({+ ..._omit(goal, ['project']),+ pid: goal.project.id,+ }))++ return result+ }++ @ApiBearerAuth()+ @Post('/')+ @Auth()+ @ApiResponse({ status: 201, type: GoalDto })+ async createGoal(+ @Body() goalDto: CreateGoalDto,+ @CurrentUserId() uid: string,+ ) {+ this.logger.log({ uid, pid: goalDto.pid }, 'POST /goal')++ const user = await this.userService.findOne({+ where: { id: uid },+ relations: ['projects'],+ })++ if (!user.isActive) {+ throw new ForbiddenException('Please, verify your email address first')+ }++ const project = await this.projectService.findOne({+ where: {+ id: goalDto.pid,+ },+ relations: ['goals', 'admin'],+ })++ if (_isEmpty(project)) {+ throw new NotFoundException('Project not found')+ }++ this.projectService.allowedToManage(+ project,+ uid,+ 'You are not allowed to add goals to this project',+ )++ const goalsCount = await this.goalService.count({+ where: { project: { id: goalDto.pid } },+ })++ if (user.planCode === PlanCode.none) {+ throw new HttpException(+ 'You cannot create new goals due to no active subscription. Please upgrade your account plan to continue.',+ HttpStatus.PAYMENT_REQUIRED,+ )+ }++ if (user.isAccountBillingSuspended) {+ throw new HttpException(+ 'The account that owns this site is currently suspended, this is because of a billing issue. Please resolve the issue to continue.',+ HttpStatus.PAYMENT_REQUIRED,+ )+ }++ if (goalsCount >= GOALS_MAXIMUM) {+ throw new HttpException(+ `You cannot create more than ${GOALS_MAXIMUM} goals per project.`,+ HttpStatus.PAYMENT_REQUIRED,+ )+ }++ try {+ const goal = new Goal()+ goal.name = goalDto.name+ goal.type = goalDto.type+ goal.matchType = goalDto.matchType+ goal.value = goalDto.value || null+ goal.metadataFilters = goalDto.metadataFilters || null+ goal.project = project++ const newGoal = await this.goalService.create(goal)++ return {+ ..._omit(newGoal, ['project']),+ pid: goalDto.pid,+ }+ } catch (reason) {+ console.error('Error while creating goal', reason)+ throw new BadRequestException('Error occurred while creating goal')+ }+ }++ @ApiBearerAuth()+ @Put('/:id')+ @Auth()+ @ApiResponse({ status: 200, type: GoalDto })+ async updateGoal(+ @Param('id') id: string,+ @Body() goalDto: UpdateGoalDto,+ @CurrentUserId() uid: string,+ ) {+ this.logger.log({ id, uid }, 'PUT /goal/:id')++ const goal = await this.goalService.findOneWithRelations(id)++ if (_isEmpty(goal)) {+ throw new NotFoundException()+ }++ this.projectService.allowedToManage(+ goal.project,+ uid,+ 'You are not allowed to manage this goal',+ )++ const updatePayload: Partial<Goal> = {+ ..._pick(goalDto, [+ 'name',+ 'type',+ 'matchType',+ 'value',+ 'metadataFilters',+ 'active',+ ]),+ }++ await this.goalService.update(id, updatePayload)++ const updatedGoal = await this.goalService.findOne({ where: { id } })+ if (!updatedGoal) {+ throw new NotFoundException('Goal not found after update')+ }++ return {+ ..._omit(updatedGoal, ['project']),+ pid: goal.project.id,+ }+ }++ @ApiBearerAuth()+ @Delete('/:id')+ @Auth()+ @ApiResponse({ status: 204, description: 'Empty body' })+ async deleteGoal(@Param('id') id: string, @CurrentUserId() uid: string) {+ this.logger.log({ id, uid }, 'DELETE /goal/:id')++ const goal = await this.goalService.findOneWithRelations(id)++ if (_isEmpty(goal)) {+ throw new NotFoundException()+ }++ this.projectService.allowedToManage(+ goal.project,+ uid,+ 'You are not allowed to manage this goal',+ )++ await this.goalService.delete(id)+ }++ private buildGoalMatchCondition(+ goal: Goal,+ _table: 'analytics' | 'customEV',+ ): { condition: string; params: Record<string, string> } {+ const params: Record<string, string> = {}++ if (goal.type === GoalType.CUSTOM_EVENT) {+ // For custom events, match the event name+ if (goal.matchType === GoalMatchType.EXACT) {+ params.goalValue = goal.value || ''+ return { condition: `ev = {goalValue:String}`, params }+ } else if (goal.matchType === GoalMatchType.CONTAINS) {+ params.goalValue = goal.value || ''+ return {+ condition: `ev ILIKE concat('%', {goalValue:String}, '%')`,+ params,+ }+ } else {+ // Regex match+ params.goalValue = goal.value || ''+ return { condition: `match(ev, {goalValue:String})`, params }+ }+ } else {+ // For pageview goals, match the page path+ if (goal.matchType === GoalMatchType.EXACT) {+ params.goalValue = goal.value || ''+ return { condition: `pg = {goalValue:String}`, params }+ } else if (goal.matchType === GoalMatchType.CONTAINS) {+ params.goalValue = goal.value || ''+ return {+ condition: `pg ILIKE concat('%', {goalValue:String}, '%')`,+ params,+ }+ } else {+ // Regex match+ params.goalValue = goal.value || ''+ return { condition: `match(pg, {goalValue:String})`, params }+ }+ }+ }++ private buildMetadataCondition(goal: Goal): {+ condition: string+ params: Record<string, string>+ } {+ if (!goal.metadataFilters || goal.metadataFilters.length === 0) {+ return { condition: '', params: {} }+ }++ const conditions: string[] = []+ const params: Record<string, string> = {}++ goal.metadataFilters.forEach((filter, index) => {+ const keyParam = `metaKey${index}`+ const valueParam = `metaValue${index}`+ params[keyParam] = filter.key+ params[valueParam] = filter.value+ conditions.push(+ `has(meta.key, {${keyParam}:String}) AND meta.value[indexOf(meta.key, {${keyParam}:String})] = {${valueParam}:String}`,+ )+ })++ return {+ condition:+ conditions.length > 0 ? `AND (${conditions.join(' AND ')})` : '',+ params,+ }+ }++ @ApiBearerAuth()+ @Get('/:id/stats')+ @Auth()+ @ApiResponse({ status: 200, type: GoalStatsDto })+ async getGoalStats(+ @CurrentUserId() userId: string,+ @Param('id') id: string,+ @Query('period') period: string,+ @Query('from') from?: string,+ @Query('to') to?: string,+ @Query('timezone') timezone?: string,+ ) {+ this.logger.log({ userId, id, period, from, to }, 'GET /goal/:id/stats')++ const goal = await this.goalService.findOneWithRelations(id)++ if (_isEmpty(goal)) {+ throw new NotFoundException('Goal not found')+ }++ const project = await this.projectService.getFullProject(goal.project.id)+ this.projectService.allowedToView(project, userId)++ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)+ const timeBucket = getLowestPossibleTimeBucket(period, from, to)++ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(+ from,+ to,+ timeBucket,+ period,+ safeTimezone,+ )++ const table = goal.type === GoalType.CUSTOM_EVENT ? 'customEV' : 'analytics'+ const { condition: matchCondition, params: matchParams } =+ this.buildGoalMatchCondition(goal, table)+ const { condition: metaCondition, params: metaParams } =+ this.buildMetadataCondition(goal)++ // Get conversions for current period+ const conversionsQuery = `+ SELECT+ count(*) as conversions,+ uniqExact(psid) as uniqueSessions+ FROM ${table}+ WHERE+ pid = {pid:FixedString(12)}+ AND ${matchCondition}+ ${metaCondition}+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ `++ const queryParams = {+ pid: goal.project.id,+ groupFrom: groupFromUTC,+ groupTo: groupToUTC,+ ...matchParams,+ ...metaParams,+ }++ const { data: conversionsData } = await clickhouse+ .query({ query: conversionsQuery, query_params: queryParams })+ .then(resultSet =>+ resultSet.json<{ conversions: number; uniqueSessions: number }>(),+ )++ const conversions = conversionsData[0]?.conversions || 0+ const uniqueSessions = conversionsData[0]?.uniqueSessions || 0++ // Get total unique sessions for conversion rate+ const totalSessionsQuery = `+ SELECT uniqExact(psid) as totalSessions+ FROM analytics+ WHERE+ pid = {pid:FixedString(12)}+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ `++ const { data: totalData } = await clickhouse+ .query({+ query: totalSessionsQuery,+ query_params: {+ pid: goal.project.id,+ groupFrom: groupFromUTC,+ groupTo: groupToUTC,+ },+ })+ .then(resultSet => resultSet.json<{ totalSessions: number }>())++ const totalSessions = totalData[0]?.totalSessions || 1+ const conversionRate = _round((uniqueSessions / totalSessions) * 100, 2)++ // Get previous period conversions for trend+ const periodDays = dayjs(groupToUTC).diff(dayjs(groupFromUTC), 'day') || 1+ const previousFrom = dayjs(groupFromUTC)+ .subtract(periodDays, 'day')+ .format('YYYY-MM-DD HH:mm:ss')+ const previousTo = groupFromUTC++ const previousQueryParams = {+ pid: goal.project.id,+ groupFrom: previousFrom,+ groupTo: previousTo,+ ...matchParams,+ ...metaParams,+ }++ const { data: previousData } = await clickhouse+ .query({ query: conversionsQuery, query_params: previousQueryParams })+ .then(resultSet =>+ resultSet.json<{ conversions: number; uniqueSessions: number }>(),+ )++ const previousConversions = previousData[0]?.conversions || 0+ const trend =+ previousConversions > 0+ ? _round(+ ((conversions - previousConversions) / previousConversions) * 100,+ 2,+ )+ : conversions > 0+ ? 100+ : 0++ return {+ conversions,+ uniqueSessions,+ conversionRate,+ previousConversions,+ trend,+ }+ }++ @ApiBearerAuth()+ @Get('/:id/chart')+ @Auth()+ async getGoalChart(+ @CurrentUserId() userId: string,+ @Param('id') id: string,+ @Query('period') period: string,+ @Query('from') from?: string,+ @Query('to') to?: string,+ @Query('timeBucket') timeBucket: string = 'day',+ @Query('timezone') timezone?: string,+ ) {+ this.logger.log(+ { userId, id, period, from, to, timeBucket },+ 'GET /goal/:id/chart',+ )++ const goal = await this.goalService.findOneWithRelations(id)++ if (_isEmpty(goal)) {+ throw new NotFoundException('Goal not found')+ }++ const project = await this.projectService.getFullProject(goal.project.id)+ this.projectService.allowedToView(project, userId)++ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)+ const resolvedTimeBucket =+ timeBucket || getLowestPossibleTimeBucket(period, from, to)++ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(+ from,+ to,+ resolvedTimeBucket as any,+ period,+ safeTimezone,+ )++ const table = goal.type === GoalType.CUSTOM_EVENT ? 'customEV' : 'analytics'+ const timeBucketFunc = timeBucketConversion[timeBucket] || 'toStartOfDay'++ const { condition: matchCondition, params: matchParams } =+ this.buildGoalMatchCondition(goal, table)+ const { condition: metaCondition, params: metaParams } =+ this.buildMetadataCondition(goal)++ const chartQuery = `+ SELECT+ ${timeBucketFunc}(toTimeZone(created, '${safeTimezone}')) as time,+ count(*) as conversions,+ uniqExact(psid) as uniqueSessions+ FROM ${table}+ WHERE+ pid = {pid:FixedString(12)}+ AND ${matchCondition}+ ${metaCondition}+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ GROUP BY time+ ORDER BY time+ `++ const queryParams = {+ pid: goal.project.id,+ groupFrom: groupFromUTC,+ groupTo: groupToUTC,+ ...matchParams,+ ...metaParams,+ }++ const { data } = await clickhouse+ .query({ query: chartQuery, query_params: queryParams })+ .then(resultSet =>+ resultSet.json<{+ time: string+ conversions: number+ uniqueSessions: number+ }>(),+ )++ return { chart: data }+ }++ @ApiBearerAuth()+ @Get('/:id/sessions')+ @Auth()+ async getGoalSessions(+ @CurrentUserId() userId: string,+ @Param('id') id: string,+ @Query('period') period: string,+ @Query('from') from?: string,+ @Query('to') to?: string,+ @Query('take', new ParseIntPipe({ optional: true })) take: number = 30,+ @Query('skip', new ParseIntPipe({ optional: true })) skip: number = 0,+ @Query('timezone') timezone?: string,+ ) {+ this.logger.log(+ { userId, id, period, from, to, take, skip },+ 'GET /goal/:id/sessions',+ )++ const goal = await this.goalService.findOneWithRelations(id)++ if (_isEmpty(goal)) {+ throw new NotFoundException('Goal not found')+ }++ const project = await this.projectService.getFullProject(goal.project.id)+ this.projectService.allowedToView(project, userId)++ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)+ const timeBucket = getLowestPossibleTimeBucket(period, from, to)++ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(+ from,+ to,+ timeBucket,+ period,+ safeTimezone,+ )++ const table = goal.type === GoalType.CUSTOM_EVENT ? 'customEV' : 'analytics'++ const { condition: matchCondition, params: matchParams } =+ this.buildGoalMatchCondition(goal, table)+ const { condition: metaCondition, params: metaParams } =+ this.buildMetadataCondition(goal)++ const sessionsQuery = `+ SELECT+ DISTINCT psid,+ any(cc) as country,+ any(br) as browser,+ any(os) as os,+ any(dv) as device,+ min(created) as firstConversion,+ count(*) as conversionCount+ FROM ${table}+ WHERE+ pid = {pid:FixedString(12)}+ AND ${matchCondition}+ ${metaCondition}+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IS NOT NULL+ GROUP BY psid+ ORDER BY firstConversion DESC+ LIMIT {take:UInt32} OFFSET {skip:UInt32}+ `++ const countQuery = `+ SELECT count(DISTINCT psid) as total+ FROM ${table}+ WHERE+ pid = {pid:FixedString(12)}+ AND ${matchCondition}+ ${metaCondition}+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IS NOT NULL+ `++ const queryParams = {+ pid: goal.project.id,+ groupFrom: groupFromUTC,+ groupTo: groupToUTC,+ take,+ skip,+ ...matchParams,+ ...metaParams,+ }++ const [sessionsResult, countResult] = await Promise.all([+ clickhouse+ .query({ query: sessionsQuery, query_params: queryParams })+ .then(resultSet => resultSet.json<any>()),+ clickhouse+ .query({ query: countQuery, query_params: queryParams })+ .then(resultSet => resultSet.json<{ total: number }>()),+ ])++ return {+ sessions: sessionsResult.data,+ total: countResult.data[0]?.total || 0,+ }+ }+}diff --git a/backend/apps/cloud/src/goal/goal.module.ts b/backend/apps/cloud/src/goal/goal.module.tsnew file mode 100644index 000000000..dfa7db545--- /dev/null+++ b/backend/apps/cloud/src/goal/goal.module.ts@@ -0,0 +1,24 @@+import { Module } from '@nestjs/common'+import { TypeOrmModule } from '@nestjs/typeorm'++import { ProjectModule } from '../project/project.module'+import { AppLoggerModule } from '../logger/logger.module'+import { UserModule } from '../user/user.module'+import { AnalyticsModule } from '../analytics/analytics.module'+import { GoalService } from './goal.service'+import { Goal } from './entity/goal.entity'+import { GoalController } from './goal.controller'++@Module({+ imports: [+ TypeOrmModule.forFeature([Goal]),+ ProjectModule,+ AppLoggerModule,+ UserModule,+ AnalyticsModule,+ ],+ providers: [GoalService],+ exports: [GoalService],+ controllers: [GoalController],+})+export class GoalModule {}diff --git a/backend/apps/cloud/src/goal/goal.service.ts b/backend/apps/cloud/src/goal/goal.service.tsnew file mode 100644index 000000000..7490c562b--- /dev/null+++ b/backend/apps/cloud/src/goal/goal.service.ts@@ -0,0 +1,73 @@+import { Injectable } from '@nestjs/common'+import { InjectRepository } from '@nestjs/typeorm'+import { FindManyOptions, FindOneOptions, Repository } from 'typeorm'+import { Pagination, PaginationOptionsInterface } from '../common/pagination'+import { Goal } from './entity/goal.entity'+import { CreateGoalDto, UpdateGoalDto } from './dto/goal.dto'++@Injectable()+export class GoalService {+ constructor(+ @InjectRepository(Goal)+ private goalsRepository: Repository<Goal>,+ ) {}++ async paginate(+ options: PaginationOptionsInterface,+ where: FindManyOptions<Goal>['where'],+ relations?: Array<string>,+ ): Promise<Pagination<Goal>> {+ const [results, total] = await this.goalsRepository.findAndCount({+ take: options.take || 100,+ skip: options.skip || 0,+ where,+ order: {+ name: 'ASC',+ },+ relations,+ })++ return new Pagination<Goal>({+ results,+ total,+ })+ }++ findOneWithRelations(id: string): Promise<Goal | null> {+ return this.goalsRepository.findOne({+ where: { id },+ relations: ['project', 'project.admin'],+ })+ }++ async count(options: FindManyOptions<Goal> = {}): Promise<number> {+ return this.goalsRepository.count(options)+ }++ findOne(options: FindOneOptions<Goal>): Promise<Goal | null> {+ return this.goalsRepository.findOne(options)+ }++ find(options: FindManyOptions<Goal>): Promise<Goal[]> {+ return this.goalsRepository.find(options)+ }++ findByProject(projectId: string): Promise<Goal[]> {+ return this.goalsRepository.find({+ where: { project: { id: projectId }, active: true },+ order: { name: 'ASC' },+ })+ }++ async create(goalData: Partial<Goal>): Promise<Goal> {+ return this.goalsRepository.save(goalData)+ }++ async update(id: string, goalData: Partial<Goal>): Promise<any> {+ return this.goalsRepository.update(id, goalData)+ }++ async delete(id: string): Promise<any> {+ return this.goalsRepository.delete(id)+ }+}diff --git a/backend/apps/cloud/src/project/entity/project.entity.ts b/backend/apps/cloud/src/project/entity/project.entity.tsindex 04fc41902..24d3c2751 100644--- a/backend/apps/cloud/src/project/entity/project.entity.ts+++ b/backend/apps/cloud/src/project/entity/project.entity.ts@@ -9,6 +9,7 @@ import {import { ApiProperty } from '@nestjs/swagger'import { Alert } from '../../alert/entity/alert.entity'+import { Goal } from '../../goal/entity/goal.entity'import { User } from '../../user/entities/user.entity'import { ProjectShare } from './project-share.entity'import { ExtensionToProject } from '../../marketplace/extensions/entities/extension-to-project.entity'@@ -123,6 +124,10 @@ export class Project {@OneToMany(() => Annotation, annotation => annotation.project)annotations: Annotation[]+ @ApiProperty({ type: () => Goal })+ @OneToMany(() => Goal, goal => goal.project)+ goals: Goal[]+@Column('varchar', {default: null,length: 60,diff --git a/backend/migrations/mysql/2025_12_07_goals.sql b/backend/migrations/mysql/2025_12_07_goals.sqlnew file mode 100644index 000000000..439a1fbbd--- /dev/null+++ b/backend/migrations/mysql/2025_12_07_goals.sql@@ -0,0 +1,14 @@+-- Goals table migration+CREATE TABLE IF NOT EXISTS `goal` (+ `id` varchar(36) NOT NULL,+ `name` varchar(100) NOT NULL,+ `type` enum('pageview', 'custom_event') NOT NULL,+ `matchType` enum('exact', 'contains', 'regex') NOT NULL DEFAULT 'exact',+ `value` varchar(500) DEFAULT NULL,+ `metadataFilters` json DEFAULT NULL,+ `active` tinyint(1) NOT NULL DEFAULT 1,+ `created` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),+ `projectId` varchar(12) DEFAULT NULL,+ PRIMARY KEY (`id`),+ FOREIGN KEY (`projectId`) REFERENCES `project` (`id`) ON DELETE CASCADE+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;diff --git a/web/app/api/index.ts b/web/app/api/index.tsindex 0a5b783c0..e51a8b471 100644--- a/web/app/api/index.ts+++ b/web/app/api/index.ts@@ -1134,6 +1134,153 @@ export const deleteAlert = (id: string) =>throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})+// Goals API+export interface Goal {+ id: string+ name: string+ type: 'pageview' | 'custom_event'+ matchType: 'exact' | 'contains' | 'regex'+ value: string | null+ metadataFilters: { key: string; value: string }[] | null+ active: boolean+ pid: string+ created: string+}++export interface GoalStats {+ conversions: number+ uniqueSessions: number+ conversionRate: number+ previousConversions: number+ trend: number+}++export interface GoalChartData {+ time: string+ conversions: number+ uniqueSessions: number+}++export interface GoalSession {+ psid: string+ country: string | null+ browser: string | null+ os: string | null+ device: string | null+ firstConversion: string+ conversionCount: number+}++export const DEFAULT_GOALS_TAKE = 20++export const getProjectGoals = (projectId: string, take: number = DEFAULT_GOALS_TAKE, skip = 0) =>+ api+ .get(`/goal/project/${projectId}?take=${take}&skip=${skip}`)+ .then(+ (+ response,+ ): {+ results: Goal[]+ total: number+ } => response.data,+ )+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })++export const getGoal = (goalId: string) =>+ api+ .get(`/goal/${goalId}`)+ .then((response): Goal => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })++export type CreateGoal = {+ pid: string+ name: string+ type: 'pageview' | 'custom_event'+ matchType: 'exact' | 'contains' | 'regex'+ value?: string+ metadataFilters?: { key: string; value: string }[]+}++export const createGoal = (data: CreateGoal) =>+ api+ .post('goal', data)+ .then((response): Goal => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })++export const updateGoal = (id: string, data: Partial<Goal>) =>+ api+ .put(`goal/${id}`, data)+ .then((response): Goal => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })++export const deleteGoal = (id: string) =>+ api+ .delete(`goal/${id}`)+ .then((response) => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })++export const getGoalStats = (goalId: string, period: string, from: string = '', to: string = '', timezone?: string) =>+ api+ .get(`/goal/${goalId}/stats`, {+ params: { period, from, to, timezone },+ })+ .then((response): GoalStats => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })++export const getGoalChart = (+ goalId: string,+ period: string,+ from: string = '',+ to: string = '',+ timeBucket: string = 'day',+ timezone?: string,+) =>+ api+ .get(`/goal/${goalId}/chart`, {+ params: { period, from, to, timeBucket, timezone },+ })+ .then((response): { chart: GoalChartData[] } => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })++export const getGoalSessions = (+ goalId: string,+ period: string,+ from: string = '',+ to: string = '',+ take: number = 30,+ skip: number = 0,+ timezone?: string,+) =>+ api+ .get(`/goal/${goalId}/sessions`, {+ params: { period, from, to, take, skip, timezone },+ })+ .then(+ (+ response,+ ): {+ sessions: GoalSession[]+ total: number+ } => response.data,+ )+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })+export const reGenerateCaptchaSecretKey = (pid: string) =>api.post(`project/secret-gen/${pid}`)diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.tsindex f1e78deb3..e7f896112 100644--- a/web/app/lib/constants/index.ts+++ b/web/app/lib/constants/index.ts@@ -404,6 +404,7 @@ const SELFHOSTED_PROJECT_TABS = {funnels: 'funnels',sessions: 'sessions',errors: 'errors',+ goals: 'goals',} as constconst PRODUCTION_PROJECT_TABS = {@@ -413,6 +414,7 @@ const PRODUCTION_PROJECT_TABS = {funnels: 'funnels',sessions: 'sessions',errors: 'errors',+ goals: 'goals',alerts: 'alerts',captcha: 'captcha',} as constdiff --git a/web/app/lib/models/Goal.ts b/web/app/lib/models/Goal.tsnew file mode 100644index 000000000..f1c5ee966--- /dev/null+++ b/web/app/lib/models/Goal.ts@@ -0,0 +1,54 @@+export type GoalType = 'pageview' | 'custom_event'+export type GoalMatchType = 'exact' | 'contains' | 'regex'++export interface MetadataFilter {+ key: string+ value: string+}++export interface Goal {+ id: string+ name: string+ type: GoalType+ matchType: GoalMatchType+ value: string | null+ metadataFilters: MetadataFilter[] | null+ active: boolean+ pid: string+ created: string+}++export interface GoalStats {+ conversions: number+ uniqueSessions: number+ conversionRate: number+ previousConversions: number+ trend: number+}++export interface GoalChartData {+ time: string+ conversions: number+ uniqueSessions: number+}++export interface GoalSession {+ psid: string+ country: string | null+ browser: string | null+ os: string | null+ device: string | null+ firstConversion: string+ conversionCount: number+}++export const GOAL_TYPE_LABELS: Record<GoalType, string> = {+ pageview: 'Pageview',+ custom_event: 'Custom Event',+}++export const GOAL_MATCH_TYPE_LABELS: Record<GoalMatchType, string> = {+ exact: 'Exact match',+ contains: 'Contains',+ regex: 'Regex',+}diff --git a/web/app/pages/Project/Goals/View/GoalSettingsModal.tsx b/web/app/pages/Project/Goals/View/GoalSettingsModal.tsxnew file mode 100644index 000000000..10860adf4--- /dev/null+++ b/web/app/pages/Project/Goals/View/GoalSettingsModal.tsx@@ -0,0 +1,278 @@+import { Dialog, DialogBackdrop, DialogPanel, DialogTitle } from '@headlessui/react'+import { XMarkIcon } from '@heroicons/react/24/outline'+import _map from 'lodash/map'+import { Trash2Icon, PlusIcon } from 'lucide-react'+import { useState, useEffect } from 'react'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'++import { getGoal, createGoal, updateGoal, type CreateGoal, type Goal } from '~/api'+import Button from '~/ui/Button'+import Input from '~/ui/Input'+import Loader from '~/ui/Loader'+import Select from '~/ui/Select'++const GOAL_TYPES = [+ { value: 'pageview', label: 'Pageview' },+ { value: 'custom_event', label: 'Custom Event' },+]++const GOAL_MATCH_TYPES = [+ { value: 'exact', label: 'Exact match' },+ { value: 'contains', label: 'Contains' },+ { value: 'regex', label: 'Regular expression' },+]++interface GoalSettingsModalProps {+ isOpen: boolean+ onClose: () => void+ onSuccess: () => void+ projectId: string+ goalId?: string | null+}++const GoalSettingsModal = ({ isOpen, onClose, onSuccess, projectId, goalId }: GoalSettingsModalProps) => {+ const { t } = useTranslation()+ const isNew = !goalId++ const [isLoading, setIsLoading] = useState(false)+ const [isSaving, setIsSaving] = useState(false)++ // Form state+ const [name, setName] = useState('')+ const [type, setType] = useState<'pageview' | 'custom_event'>('pageview')+ const [matchType, setMatchType] = useState<'exact' | 'contains' | 'regex'>('exact')+ const [value, setValue] = useState('')+ const [metadataFilters, setMetadataFilters] = useState<{ key: string; value: string }[]>([])++ const resetForm = () => {+ setName('')+ setType('pageview')+ setMatchType('exact')+ setValue('')+ setMetadataFilters([])+ }++ const loadGoal = async () => {+ if (!goalId) return+ setIsLoading(true)+ try {+ const goal = await getGoal(goalId)+ setName(goal.name)+ setType(goal.type)+ setMatchType(goal.matchType)+ setValue(goal.value || '')+ setMetadataFilters(goal.metadataFilters || [])+ } catch (err: any) {+ toast.error(err?.message || 'Failed to load goal')+ onClose()+ } finally {+ setIsLoading(false)+ }+ }++ useEffect(() => {+ if (isOpen) {+ if (goalId) {+ loadGoal()+ } else {+ resetForm()+ }+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [isOpen, goalId])++ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault()+ setIsSaving(true)++ try {+ if (isNew) {+ const data: CreateGoal = {+ pid: projectId,+ name,+ type,+ matchType,+ value: value || undefined,+ metadataFilters: metadataFilters.length > 0 ? metadataFilters : undefined,+ }+ await createGoal(data)+ toast.success(t('goals.created'))+ } else if (goalId) {+ await updateGoal(goalId, {+ name,+ type,+ matchType,+ value: value || null,+ metadataFilters: metadataFilters.length > 0 ? metadataFilters : null,+ })+ toast.success(t('goals.updated'))+ }+ onSuccess()+ onClose()+ } catch (err: any) {+ toast.error(err?.message || t('apiNotifications.somethingWentWrong'))+ } finally {+ setIsSaving(false)+ }+ }++ const addMetadataFilter = () => {+ setMetadataFilters([...metadataFilters, { key: '', value: '' }])+ }++ const updateMetadataFilter = (index: number, field: 'key' | 'value', val: string) => {+ const updated = [...metadataFilters]+ updated[index][field] = val+ setMetadataFilters(updated)+ }++ const removeMetadataFilter = (index: number) => {+ setMetadataFilters(metadataFilters.filter((_, i) => i !== index))+ }++ return (+ <Dialog className='relative z-40' open={isOpen} onClose={onClose}>+ <DialogBackdrop+ transition+ className='fixed inset-0 bg-gray-500/75 transition-opacity data-closed:opacity-0 data-enter:ease-out data-leave:duration-200 data-leave:ease-in'+ />++ <div className='fixed inset-0 z-10 w-screen overflow-y-auto'>+ <div className='flex min-h-full items-center justify-center p-4'>+ <DialogPanel+ transition+ className='w-full max-w-lg transform rounded-xl bg-white transition-all data-closed:translate-y-4 data-closed:opacity-0 data-enter:ease-out data-leave:duration-200 data-leave:ease-in dark:bg-slate-900'+ >+ {isLoading ? (+ <div className='flex min-h-[300px] items-center justify-center'>+ <Loader />+ </div>+ ) : (+ <form onSubmit={handleSubmit}>+ <div className='px-6 pt-5 pb-4'>+ <div className='flex items-center justify-between'>+ <DialogTitle className='text-lg font-semibold text-gray-900 dark:text-gray-50'>+ {isNew ? t('goals.createTitle') : t('goals.editTitle')}+ </DialogTitle>+ <button+ type='button'+ onClick={onClose}+ className='rounded-md p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-500 dark:hover:bg-slate-800 dark:hover:text-gray-300'+ >+ <XMarkIcon className='h-5 w-5' />+ </button>+ </div>++ <div className='mt-4 space-y-4'>+ <Input+ label={t('goals.name')}+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder={t('goals.namePlaceholder')}+ required+ />++ <div>+ <label className='mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300'>+ {t('goals.type')}+ </label>+ <Select+ items={GOAL_TYPES}+ onSelect={(item) => setType(item.value as 'pageview' | 'custom_event')}+ title={GOAL_TYPES.find((t) => t.value === type)?.label || ''}+ labelExtractor={(item) => item.label}+ keyExtractor={(item) => item.value}+ selectedItem={GOAL_TYPES.find((t) => t.value === type)}+ capitalise+ />+ <p className='mt-1 text-xs text-gray-500 dark:text-gray-400'>+ {type === 'pageview' ? t('goals.typePageviewDesc') : t('goals.typeCustomEventDesc')}+ </p>+ </div>++ <div>+ <label className='mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300'>+ {t('goals.matchType')}+ </label>+ <Select+ items={GOAL_MATCH_TYPES}+ onSelect={(item) => setMatchType(item.value as 'exact' | 'contains' | 'regex')}+ title={GOAL_MATCH_TYPES.find((t) => t.value === matchType)?.label || ''}+ labelExtractor={(item) => item.label}+ keyExtractor={(item) => item.value}+ selectedItem={GOAL_MATCH_TYPES.find((t) => t.value === matchType)}+ capitalise+ />+ </div>++ <Input+ label={type === 'pageview' ? t('goals.pagePath') : t('goals.eventName')}+ value={value}+ onChange={(e) => setValue(e.target.value)}+ placeholder={type === 'pageview' ? '/pricing' : 'signup_completed'}+ />++ {/* Metadata filters */}+ <div>+ <div className='mb-2 flex items-center justify-between'>+ <label className='block text-sm font-medium text-gray-700 dark:text-gray-300'>+ {t('goals.metadataFilters')}+ </label>+ <button+ type='button'+ onClick={addMetadataFilter}+ className='flex items-center gap-1 text-sm text-indigo-600 hover:text-indigo-500 dark:text-indigo-400'+ >+ <PlusIcon className='h-4 w-4' />+ {t('goals.addFilter')}+ </button>+ </div>+ {metadataFilters.length > 0 ? (+ <div className='space-y-2'>+ {_map(metadataFilters, (filter, index) => (+ <div key={index} className='flex items-center gap-2'>+ <Input+ value={filter.key}+ onChange={(e) => updateMetadataFilter(index, 'key', e.target.value)}+ placeholder={t('goals.filterKey')}+ className='flex-1'+ />+ <span className='text-gray-500'>=</span>+ <Input+ value={filter.value}+ onChange={(e) => updateMetadataFilter(index, 'value', e.target.value)}+ placeholder={t('goals.filterValue')}+ className='flex-1'+ />+ <Button type='button' onClick={() => removeMetadataFilter(index)} noBorder small>+ <Trash2Icon className='h-4 w-4' />+ </Button>+ </div>+ ))}+ </div>+ ) : (+ <p className='text-sm text-gray-500 dark:text-gray-400'>{t('goals.noMetadataFilters')}</p>+ )}+ </div>+ </div>+ </div>++ <div className='flex justify-end gap-3 border-t border-gray-200 px-6 py-4 dark:border-slate-700'>+ <Button type='button' onClick={onClose} secondary regular>+ {t('common.cancel')}+ </Button>+ <Button type='submit' primary regular loading={isSaving}>+ {isNew ? t('goals.create') : t('goals.save')}+ </Button>+ </div>+ </form>+ )}+ </DialogPanel>+ </div>+ </div>+ </Dialog>+ )+}++export default GoalSettingsModaldiff --git a/web/app/pages/Project/Goals/View/GoalsView.tsx b/web/app/pages/Project/Goals/View/GoalsView.tsxnew file mode 100644index 000000000..db1bb34db--- /dev/null+++ b/web/app/pages/Project/Goals/View/GoalsView.tsx@@ -0,0 +1,406 @@+import { XCircleIcon } from '@heroicons/react/24/outline'+import cx from 'clsx'+import _isEmpty from 'lodash/isEmpty'+import _map from 'lodash/map'+import {+ TargetIcon,+ Trash2Icon,+ Settings2Icon,+ PlusIcon,+ TrendingUpIcon,+ TrendingDownIcon,+ FileTextIcon,+ ZapIcon,+} from 'lucide-react'+import { useState, useEffect } from 'react'+import { useTranslation } from 'react-i18next'+import { Link } from 'react-router'+import { toast } from 'sonner'++import {+ deleteGoal as deleteGoalApi,+ getProjectGoals,+ getGoalStats,+ DEFAULT_GOALS_TAKE,+ type Goal,+ type GoalStats,+} from '~/api'+import { useViewProjectContext } from '~/pages/Project/View/ViewProject'+import { useCurrentProject } from '~/providers/CurrentProjectProvider'+import { Badge, type BadgeProps } from '~/ui/Badge'+import Button from '~/ui/Button'+import Loader from '~/ui/Loader'+import Modal from '~/ui/Modal'+import Pagination from '~/ui/Pagination'+import routes from '~/utils/routes'++import GoalSettingsModal from './GoalSettingsModal'++const GOAL_TYPE_BADGE_COLOURS: Record<Goal['type'], BadgeProps['colour']> = {+ pageview: 'indigo',+ custom_event: 'green',+}++interface GoalCardProps {+ goal: Goal+ stats: GoalStats | null+ statsLoading: boolean+ onDelete: (id: string) => void+ onEdit: (id: string) => void+ onClick: (id: string) => void+}++const GoalCard = ({ goal, stats, statsLoading, onDelete, onEdit, onClick }: GoalCardProps) => {+ const { t } = useTranslation()+ const [showDeleteModal, setShowDeleteModal] = useState(false)++ const typeLabel = goal.type === 'pageview' ? t('goals.typePageview') : t('goals.typeCustomEvent')++ return (+ <>+ <li+ onClick={() => onClick(goal.id)}+ className='min-h-[140px] cursor-pointer overflow-hidden rounded-xl border border-gray-200 bg-gray-50 transition-colors hover:bg-gray-200/70 dark:border-slate-800/25 dark:bg-slate-800/70 dark:hover:bg-slate-700/60'+ >+ <div className='px-4 py-4'>+ <div className='flex items-start justify-between'>+ <div className='min-w-0 flex-1'>+ <div className='mb-2 flex items-center gap-2'>+ {goal.type === 'pageview' ? (+ <FileTextIcon className='h-5 w-5 text-indigo-500' strokeWidth={1.5} />+ ) : (+ <ZapIcon className='h-5 w-5 text-green-500' strokeWidth={1.5} />+ )}+ <p className='truncate text-lg font-semibold text-slate-900 dark:text-gray-50'>{goal.name}</p>+ </div>+ <Badge colour={GOAL_TYPE_BADGE_COLOURS[goal.type]} label={typeLabel} />+ {goal.value && (+ <p className='mt-2 truncate text-sm text-gray-600 dark:text-gray-400'>+ {goal.matchType === 'exact' && '= '}+ {goal.matchType === 'contains' && '~ '}+ {goal.matchType === 'regex' && '⁓ '}+ {goal.value}+ </p>+ )}+ </div>+ <div className='ml-2 flex items-center gap-1'>+ <button+ onClick={(e) => {+ e.stopPropagation()+ onEdit(goal.id)+ }}+ aria-label={t('common.settings')}+ className='rounded-md border border-transparent p-1.5 text-gray-800 transition-colors hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:text-slate-400 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 dark:hover:text-slate-300'+ >+ <Settings2Icon className='size-5' strokeWidth={1.5} />+ </button>++ <button+ onClick={(e) => {+ e.stopPropagation()+ setShowDeleteModal(true)+ }}+ aria-label={t('common.delete')}+ className='rounded-md border border-transparent p-1.5 text-gray-800 transition-colors hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:text-slate-400 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 dark:hover:text-slate-300'+ >+ <Trash2Icon className='size-5' strokeWidth={1.5} />+ </button>+ </div>+ </div>++ {/* Stats section */}+ <div className='mt-4 grid grid-cols-2 gap-4'>+ {statsLoading ? (+ <div className='col-span-2 flex justify-center py-2'>+ <Loader size='sm' />+ </div>+ ) : stats ? (+ <>+ <div>+ <p className='text-xs text-gray-500 dark:text-gray-400'>{t('goals.conversions')}</p>+ <p className='text-xl font-bold text-slate-900 dark:text-gray-50'>+ {stats.conversions.toLocaleString()}+ </p>+ </div>+ <div>+ <p className='text-xs text-gray-500 dark:text-gray-400'>{t('goals.conversionRate')}</p>+ <div className='flex items-center gap-2'>+ <p className='text-xl font-bold text-slate-900 dark:text-gray-50'>{stats.conversionRate}%</p>+ {stats.trend !== 0 && (+ <span+ className={cx('flex items-center text-sm', {+ 'text-green-500': stats.trend > 0,+ 'text-red-500': stats.trend < 0,+ })}+ >+ {stats.trend > 0 ? (+ <TrendingUpIcon className='mr-0.5 h-4 w-4' />+ ) : (+ <TrendingDownIcon className='mr-0.5 h-4 w-4' />+ )}+ {Math.abs(stats.trend)}%+ </span>+ )}+ </div>+ </div>+ </>+ ) : (+ <p className='col-span-2 text-sm text-gray-500 dark:text-gray-400'>{t('goals.noData')}</p>+ )}+ </div>+ </div>+ </li>+ <Modal+ onClose={() => setShowDeleteModal(false)}+ onSubmit={() => {+ onDelete(goal.id)+ setShowDeleteModal(false)+ }}+ submitText={t('goals.delete')}+ closeText={t('common.close')}+ title={t('goals.deleteConfirmTitle')}+ message={t('goals.deleteConfirmMessage')}+ submitType='danger'+ type='error'+ isOpened={showDeleteModal}+ />+ </>+ )+}++interface AddGoalProps {+ onClick: () => void+}++const AddGoal = ({ onClick }: AddGoalProps) => {+ const { t } = useTranslation()++ return (+ <li+ onClick={onClick}+ className='group flex h-auto min-h-[140px] cursor-pointer items-center justify-center rounded-lg border border-dashed border-gray-300 transition-colors hover:border-gray-400 dark:border-gray-500 dark:hover:border-gray-600'+ >+ <div>+ <PlusIcon+ className='mx-auto h-12 w-12 text-gray-400 transition-colors group-hover:text-gray-500 dark:text-gray-200 group-hover:dark:text-gray-400'+ strokeWidth={1}+ />+ <span className='mt-2 block text-sm font-semibold text-gray-900 dark:text-gray-50 group-hover:dark:text-gray-400'>+ {t('goals.add')}+ </span>+ </div>+ </li>+ )+}++interface GoalsViewProps {+ period: string+ from?: string+ to?: string+ timezone?: string+}++const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) => {+ const { id } = useCurrentProject()+ const { goalsRefreshTrigger } = useViewProjectContext()+ const { t } = useTranslation()++ const [isLoading, setIsLoading] = useState<boolean | null>(null)+ const [total, setTotal] = useState(0)+ const [goals, setGoals] = useState<Goal[]>([])+ const [goalStats, setGoalStats] = useState<Record<string, GoalStats | null>>({})+ const [statsLoading, setStatsLoading] = useState<Record<string, boolean>>({})+ const [page, setPage] = useState(1)+ const [error, setError] = useState<string | null>(null)++ // Modal state+ const [isModalOpen, setIsModalOpen] = useState(false)+ const [editingGoalId, setEditingGoalId] = useState<string | null>(null)++ const pageAmount = Math.ceil(total / DEFAULT_GOALS_TAKE)++ const loadGoals = async (take: number, skip: number) => {+ if (isLoading) {+ return+ }+ setIsLoading(true)++ try {+ const result = await getProjectGoals(id, take, skip)+ setGoals(result.results)+ setTotal(result.total)+ } catch (reason: any) {+ setError(reason)+ } finally {+ setIsLoading(false)+ }+ }++ const loadGoalStats = async (goalId: string) => {+ setStatsLoading((prev) => ({ ...prev, [goalId]: true }))+ try {+ const stats = await getGoalStats(goalId, period, from, to, timezone)+ setGoalStats((prev) => ({ ...prev, [goalId]: stats }))+ } catch (err) {+ console.error('Failed to load goal stats:', err)+ setGoalStats((prev) => ({ ...prev, [goalId]: null }))+ } finally {+ setStatsLoading((prev) => ({ ...prev, [goalId]: false }))+ }+ }++ useEffect(() => {+ loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [page])++ useEffect(() => {+ // Load stats for all goals when goals change or date range changes+ goals.forEach((goal) => {+ loadGoalStats(goal.id)+ })+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [goals, period, from, to, timezone])++ // Refresh goals data when refresh button is clicked+ useEffect(() => {+ if (goalsRefreshTrigger > 0) {+ loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE)+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [goalsRefreshTrigger])++ const handleNewGoal = () => {+ setEditingGoalId(null)+ setIsModalOpen(true)+ }++ const handleEditGoal = (goalId: string) => {+ setEditingGoalId(goalId)+ setIsModalOpen(true)+ }++ const handleCloseModal = () => {+ setIsModalOpen(false)+ setEditingGoalId(null)+ }++ const handleModalSuccess = () => {+ loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE)+ }++ const handleDeleteGoal = async (goalId: string) => {+ try {+ await deleteGoalApi(goalId)+ toast.success(t('goals.deleted'))+ // Reload goals+ loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE)+ } catch (reason: any) {+ toast.error(reason?.response?.data?.message || reason?.message || t('apiNotifications.somethingWentWrong'))+ }+ }++ if (error && isLoading === false) {+ return (+ <div className='bg-gray-50 px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8 dark:bg-slate-900'>+ <div className='mx-auto max-w-max'>+ <main className='sm:flex'>+ <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />+ <div className='sm:ml-6'>+ <div className='max-w-prose sm:border-l sm:border-gray-200 sm:pl-6'>+ <h1 className='text-4xl font-extrabold text-gray-900 sm:text-5xl dark:text-gray-50'>+ {t('apiNotifications.somethingWentWrong')}+ </h1>+ <p className='mt-4 text-2xl font-medium text-gray-700 dark:text-gray-200'>+ {t('apiNotifications.errorCode', { error })}+ </p>+ </div>+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>+ <button+ type='button'+ onClick={() => window.location.reload()}+ className='inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden'+ >+ {t('dashboard.reloadPage')}+ </button>+ <Link+ to={routes.contact}+ className='inline-flex items-center rounded-md border border-transparent bg-indigo-100 px-4 py-2 text-sm font-medium text-indigo-700 hover:bg-indigo-200 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700 dark:focus:ring-gray-50'+ >+ {t('notFoundPage.support')}+ </Link>+ </div>+ </div>+ </main>+ </div>+ </div>+ )+ }++ if (isLoading || isLoading === null) {+ return (+ <div className='mt-4'>+ <Loader />+ </div>+ )+ }++ return (+ <div className='mt-4'>+ {_isEmpty(goals) ? (+ <div className='mt-5 rounded-xl bg-gray-700 p-5'>+ <div className='flex items-center text-gray-50'>+ <TargetIcon className='mr-2 h-8 w-8' strokeWidth={1.5} />+ <p className='text-3xl font-bold'>{t('goals.title')}</p>+ </div>+ <p className='mt-2 text-sm whitespace-pre-wrap text-gray-100'>{t('goals.description')}</p>+ <Button+ onClick={handleNewGoal}+ className='mt-6 block max-w-max rounded-md border border-transparent bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-indigo-50 md:px-4'+ secondary+ large+ >+ {t('goals.add')}+ </Button>+ </div>+ ) : (+ <>+ <ul className='mt-4 grid grid-cols-1 gap-3 lg:grid-cols-3'>+ {_map(goals, (goal) => (+ <GoalCard+ key={goal.id}+ goal={goal}+ stats={goalStats[goal.id] || null}+ statsLoading={statsLoading[goal.id] || false}+ onDelete={handleDeleteGoal}+ onEdit={handleEditGoal}+ onClick={handleEditGoal}+ />+ ))}+ <AddGoal onClick={handleNewGoal} />+ </ul>+ </>+ )}+ {pageAmount > 1 ? (+ <Pagination+ className='mt-4'+ page={page}+ pageAmount={pageAmount}+ setPage={setPage}+ total={total}+ pageSize={DEFAULT_GOALS_TAKE}+ />+ ) : null}++ <GoalSettingsModal+ isOpen={isModalOpen}+ onClose={handleCloseModal}+ onSuccess={handleModalSuccess}+ projectId={id}+ goalId={editingGoalId}+ />+ </div>+ )+}++export default GoalsViewdiff --git a/web/app/pages/Project/Goals/View/index.tsx b/web/app/pages/Project/Goals/View/index.tsxnew file mode 100644index 000000000..6a5a362f2--- /dev/null+++ b/web/app/pages/Project/Goals/View/index.tsx@@ -0,0 +1 @@+export { default } from './GoalsView'diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsxindex e7874612e..09d5c41d0 100644--- a/web/app/pages/Project/Settings/ProjectSettings.tsx+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx@@ -1026,6 +1026,7 @@ const ProjectSettings = () => {]}keyExtractor={(item) => String(item.value)}labelExtractor={(item) => item.label}+ selectedItem={{ value: captchaDifficulty, label: '' }}onSelect={(item: { value: number; label: string }) => {setCaptchaDifficulty(item.value)}}diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsxindex f04239442..6234c8aed 100644--- a/web/app/pages/Project/View/ViewProject.tsx+++ b/web/app/pages/Project/View/ViewProject.tsx@@ -39,6 +39,7 @@ import {PercentIcon,KeyboardIcon,ShieldCheckIcon,+ TargetIcon,} from 'lucide-react'import React, {useState,@@ -166,6 +167,7 @@ import routes from '~/utils/routes'import { useCurrentProject, useProjectPassword } from '../../../providers/CurrentProjectProvider'import ProjectAlertsView from '../Alerts/View'+import GoalsView from '../Goals/View'import AddAViewModal from './components/AddAViewModal'import CCRow from './components/CCRow'@@ -403,6 +405,7 @@ interface ViewProjectContextType {filters: Filter[]customPanelTabs: CustomTab[]captchaRefreshTrigger: number+ goalsRefreshTrigger: number// FunctionsupdatePeriod: (newPeriod: { period: Period; label?: string }) => void@@ -427,6 +430,7 @@ const defaultViewProjectContext: ViewProjectContextType = {filters: [],customPanelTabs: [],captchaRefreshTrigger: 0,+ goalsRefreshTrigger: 0,updatePeriod: () => {},updateTimebucket: (_newTimebucket) => {},refCalendar: { current: null } as any,@@ -538,6 +542,7 @@ const ViewProjectContent = () => {const [dataLoading, setDataLoading] = useState(false)const [isAutoRefreshing, setIsAutoRefreshing] = useState(false)const [captchaRefreshTrigger, setCaptchaRefreshTrigger] = useState(0)+ const [goalsRefreshTrigger, setGoalsRefreshTrigger] = useState(0)const [activeChartMetrics, setActiveChartMetrics] = useState<Record<keyof typeof CHART_METRICS_MAPPING, boolean>>({[CHART_METRICS_MAPPING.unique]: true,[CHART_METRICS_MAPPING.views]: false,@@ -1495,6 +1500,11 @@ const ViewProjectContent = () => {label: t('dashboard.funnels'),icon: FilterIcon,},+ {+ id: PROJECT_TABS.goals,+ label: t('dashboard.goals'),+ icon: TargetIcon,+ },]const adminTabs = allowedToManage@@ -2663,6 +2673,11 @@ const ViewProjectContent = () => {return}+ if (activeTab === PROJECT_TABS.goals) {+ setGoalsRefreshTrigger((prev) => prev + 1)+ return+ }+loadAnalytics()}},@@ -3412,6 +3427,7 @@ const ViewProjectContent = () => {filters,customPanelTabs,captchaRefreshTrigger,+ goalsRefreshTrigger,// FunctionsupdatePeriod,@@ -4295,6 +4311,14 @@ const ViewProjectContent = () => {{activeTab === PROJECT_TABS.alerts && project.role === 'owner' && isAuthenticated ? (<ProjectAlertsView />) : null}+ {activeTab === PROJECT_TABS.goals ? (+ <GoalsView+ period={period}+ from={dateRange ? getFormatDate(dateRange[0]) : ''}+ to={dateRange ? getFormatDate(dateRange[1]) : ''}+ timezone={timezone}+ />+ ) : null}{activeTab === PROJECT_TABS.captcha ? <CaptchaView projectId={id} /> : null}{analyticsLoading &&(activeTab === PROJECT_TABS.traffic || activeTab === PROJECT_TABS.performance) ? (diff --git a/web/app/pages/Project/View/components/ProjectSidebar.tsx b/web/app/pages/Project/View/components/ProjectSidebar.tsxindex 6188c0122..b8f92d580 100644--- a/web/app/pages/Project/View/components/ProjectSidebar.tsx+++ b/web/app/pages/Project/View/components/ProjectSidebar.tsx@@ -29,6 +29,7 @@ const ICON_COLORS: Record<string, string> = {sessions: 'text-indigo-500',errors: 'text-red-500',funnels: 'text-teal-500',+ goals: 'text-purple-500',// CAPTCHAcaptcha: 'text-emerald-500',// Settings@@ -203,7 +204,13 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({// Product Analytics groupconst productAnalyticsTabs = tabs.filter((tab) =>- [PROJECT_TABS.profiles, PROJECT_TABS.sessions, PROJECT_TABS.funnels, PROJECT_TABS.errors].includes(tab.id as any),+ [+ PROJECT_TABS.profiles,+ PROJECT_TABS.sessions,+ PROJECT_TABS.funnels,+ PROJECT_TABS.errors,+ PROJECT_TABS.goals,+ ].includes(tab.id as any),)if (productAnalyticsTabs.length > 0) {groups.push({diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex 77678d864..081bfd5e7 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -881,6 +881,8 @@"events": "Events","alerts": "Alerts","alertsDesc": "Automated alerts is a powerful tool that notifies you when some events occur on your website.\nWe can automatically monitor your project for traffic spikes and notify you via Telegram, Slack or Discord.",+ "goals": "Goals",+ "goalsDesc": "Conversion goals help you track important user actions on your website.\nDefine pageview goals or custom event goals to measure how many visitors complete specific actions.","webAnalytics": "Web analytics","productAnalytics": "Product analytics","revenueAnalytics": "Revenue analytics",@@ -947,6 +949,49 @@"errors": "Errors"}},+ "goals": {+ "title": "Goals",+ "description": "Conversion goals help you track important user actions on your website.\nDefine pageview goals or custom event goals to measure how many visitors complete specific actions.",+ "add": "Add goal",+ "create": "Create goal",+ "save": "Save",+ "delete": "Delete goal",+ "deleted": "Goal has been deleted",+ "created": "Goal has been created",+ "updated": "Goal has been updated",+ "createTitle": "Create new goal",+ "editTitle": "Edit goal",+ "deleteConfirmTitle": "Delete this goal?",+ "deleteConfirmMessage": "This action is irreversible. The goal and all its data will be deleted from our servers.",+ "name": "Goal name",+ "namePlaceholder": "e.g., Sign up completed",+ "type": "Goal type",+ "typePageview": "Pageview",+ "typeCustomEvent": "Custom Event",+ "typePageviewDesc": "Track visits to specific pages or sections of your website.",+ "typeCustomEventDesc": "Track specific custom events triggered on your website.",+ "matchType": "Match type",+ "pagePath": "Page path",+ "eventName": "Event name",+ "metadataFilters": "Metadata filters",+ "addFilter": "Add filter",+ "filterKey": "Key",+ "filterValue": "Value",+ "noMetadataFilters": "No metadata filters added. Click 'Add filter' to filter by event metadata.",+ "conversions": "Conversions",+ "uniqueSessions": "Unique sessions",+ "conversionRate": "Conversion rate",+ "trend": "Trend",+ "performance": "Performance",+ "conversionsOverTime": "Conversions over time",+ "recentSessions": "Recent converting sessions",+ "sessionId": "Session ID",+ "country": "Country",+ "browser": "Browser",+ "conversionsCount": "Conversions",+ "configuration": "Configuration",+ "noData": "No conversion data yet"+ },"error": {"status": {"active": "Active",