π 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
Stats API v2 for Swetrix CE
Blue Mouse6407373f31f0
diff --git a/backend/apps/community/src/analytics/analytics.module.ts b/backend/apps/community/src/analytics/analytics.module.tsindex 29fab9058..da9d6ce47 100644--- a/backend/apps/community/src/analytics/analytics.module.ts+++ b/backend/apps/community/src/analytics/analytics.module.ts@@ -3,21 +3,43 @@ import { Module, forwardRef } from '@nestjs/common'import { AnalyticsService } from './analytics.service'import { AnalyticsController } from './analytics.controller'import { BotDetectionService } from './bot-detection.service'+import { AnalyticsReadGuard } from './protection/analytics-read.guard'+import { PublicProjectCacheInterceptor } from './protection/public-project-cache.interceptor'import { HeartbeatGateway } from './heartbeat.gateway'import { SaltService } from './salt.service'import { AppLoggerModule } from '../logger/logger.module'import { ProjectModule } from '../project/project.module'import { ExperimentModule } from '../experiment/experiment.module'+import { AnalyticsV2Service } from './v2/analytics-v2.service'+import { TrafficV2Controller } from './v2/controllers/traffic-v2.controller'+import { PerformanceV2Controller } from './v2/controllers/performance-v2.controller'+import { CaptchaV2Controller } from './v2/controllers/captcha-v2.controller'+import { ErrorsV2Controller } from './v2/controllers/errors-v2.controller'+import { SessionsV2Controller } from './v2/controllers/sessions-v2.controller'+import { ProfilesV2Controller } from './v2/controllers/profiles-v2.controller'+import { ProjectV2Controller } from './v2/controllers/project-v2.controller'@Module({imports: [AppLoggerModule, ProjectModule, forwardRef(() => ExperimentModule)],providers: [AnalyticsService,+ AnalyticsV2Service,BotDetectionService,SaltService,HeartbeatGateway,+ AnalyticsReadGuard,+ PublicProjectCacheInterceptor,],exports: [AnalyticsService, BotDetectionService, SaltService],- controllers: [AnalyticsController],+ controllers: [+ AnalyticsController,+ TrafficV2Controller,+ PerformanceV2Controller,+ CaptchaV2Controller,+ ErrorsV2Controller,+ SessionsV2Controller,+ ProfilesV2Controller,+ ProjectV2Controller,+ ],})export class AnalyticsModule {}diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.tsindex 6d4b2ddaa..59d3ca55c 100644--- a/backend/apps/community/src/analytics/analytics.service.ts+++ b/backend/apps/community/src/analytics/analytics.service.ts@@ -308,10 +308,10 @@ const mapErrorColumn = (type: string): string => ERROR_COLUMN_MAP[type] || typeconst captchaMetaValue = (key: string, fallback: string) =>`if(indexOf(\`meta.key\`, '${key}') = 0, '${fallback}', arrayElement(\`meta.value\`, indexOf(\`meta.key\`, '${key}')))`-const CAPTCHA_EVENT_SQL = captchaMetaValue('captcha_event', 'pass')-const CAPTCHA_DIFFICULTY_SQL = captchaMetaValue('captcha_difficulty', '0')-const CAPTCHA_REASON_SQL = captchaMetaValue('captcha_reason', '')-const CAPTCHA_SOLVE_MS_SQL = `toUInt32OrZero(${captchaMetaValue('solve_ms', '0')})`+export const CAPTCHA_EVENT_SQL = captchaMetaValue('captcha_event', 'pass')+export const CAPTCHA_DIFFICULTY_SQL = captchaMetaValue('captcha_difficulty', '0')+export const CAPTCHA_REASON_SQL = captchaMetaValue('captcha_reason', '')+export const CAPTCHA_SOLVE_MS_SQL = `toUInt32OrZero(${captchaMetaValue('solve_ms', '0')})`const CAPTCHA_SOLVE_TIME_SQL = `multiIf(${CAPTCHA_SOLVE_MS_SQL} = 0, 'unknown', ${CAPTCHA_SOLVE_MS_SQL} < 1000, '<1s', ${CAPTCHA_SOLVE_MS_SQL} < 3000, '1-3s', ${CAPTCHA_SOLVE_MS_SQL} < 10000, '3-10s', ${CAPTCHA_SOLVE_MS_SQL} < 30000, '10-30s', '30s+')`const CAPTCHA_META_COLUMN_MAP: Record<string, string> = {@@ -321,7 +321,7 @@ const CAPTCHA_META_COLUMN_MAP: Record<string, string> = {solve_time: CAPTCHA_SOLVE_TIME_SQL,}-const getCaptchaColumnExpression = (col: string): string =>+export const getCaptchaColumnExpression = (col: string): string =>CAPTCHA_META_COLUMN_MAP[col] || colconst generateParamsQuery = (diff --git a/backend/apps/community/src/analytics/protection/analytics-read.guard.ts b/backend/apps/community/src/analytics/protection/analytics-read.guard.tsnew file mode 100644index 000000000..14b1e1919--- /dev/null+++ b/backend/apps/community/src/analytics/protection/analytics-read.guard.ts@@ -0,0 +1,115 @@+import {+ CanActivate,+ ExecutionContext,+ ForbiddenException,+ Injectable,+} from '@nestjs/common'+import { isbot } from 'isbot'++import { ProjectService } from '../../project/project.service'+import { checkRateLimit, getIPDetails } from '../../common/utils'+import { AppLoggerService } from '../../logger/logger.service'+import { getTrustworthyIp, getSinglePid } from './analytics-read.util'++const READ_RATE_LIMIT = 300 // requests per rate window+const AUTHED_READ_RATE_LIMIT = 3000 // requests per rate window+const READ_RATE_WINDOW = 60 // seconds++const BLOCK_DATACENTER_READS =+ process.env.ANALYTICS_BLOCK_DATACENTER_READS === 'true'++@Injectable()+export class AnalyticsReadGuard implements CanActivate {+ constructor(+ private readonly projectService: ProjectService,+ private readonly logger: AppLoggerService,+ ) {}++ async canActivate(context: ExecutionContext): Promise<boolean> {+ const req = context.switchToHttp().getRequest()++ // Only police read (GET) traffic+ if (req.method !== 'GET') {+ return true+ }++ // API-key requests are metered separately, per plan+ if (req.headers['x-api-key']) {+ return true+ }++ // Logged-in requests - limiting by userId on a more generous limit+ const uid = req.user?.sub || req.user?.id || null+ if (uid) {+ if (AUTHED_READ_RATE_LIMIT > 0) {+ await checkRateLimit(+ String(uid),+ 'analytics-read-user',+ AUTHED_READ_RATE_LIMIT,+ READ_RATE_WINDOW,+ )+ }+ return true+ }++ let isPublicProject = false+ try {+ const pid = getSinglePid(req.query || {}, req.params || {})+ if (pid) {+ const project = await this.projectService.getRedisProject(pid)+ isPublicProject = Boolean(project?.public)+ }+ } catch (reason) {+ this.logger.warn(+ `AnalyticsReadGuard soft-failed: ${reason}`,+ 'AnalyticsReadGuard',+ )+ return true+ }++ if (!isPublicProject) {+ return true+ }++ // --- Public-project protections only below this line ---++ // Bot user-agents never legitimately view a public dashboard+ const userAgent = String(req.headers['user-agent'] || '')+ if (userAgent && isbot(userAgent)) {+ throw new ForbiddenException(+ 'Automated traffic is not permitted for this resource',+ )+ }++ // The real visitor IP, or '' when only a proxy IP is visible (so we never+ // rate-limit or geo-check the shared proxy address)+ const ip = getTrustworthyIp(req)++ if (BLOCK_DATACENTER_READS && ip) {+ try {+ if (getIPDetails(ip).isHosting) {+ throw new ForbiddenException(+ 'Automated traffic is not permitted for this resource',+ )+ }+ } catch (reason) {+ if (reason instanceof ForbiddenException) {+ throw reason+ }+ // GeoIP lookup failed β ignore, fail open.+ }+ }++ // Opt-in per-IP limit, public projects only, real client IP only.+ if (READ_RATE_LIMIT && ip) {+ await checkRateLimit(+ ip,+ 'analytics-read',+ READ_RATE_LIMIT,+ READ_RATE_WINDOW,+ )+ }++ return true+ }+}diff --git a/backend/apps/community/src/analytics/protection/analytics-read.util.ts b/backend/apps/community/src/analytics/protection/analytics-read.util.tsnew file mode 100644index 000000000..19482e35b--- /dev/null+++ b/backend/apps/community/src/analytics/protection/analytics-read.util.ts@@ -0,0 +1,76 @@+import _isString from 'lodash/isString'++import { PID_REGEX } from '../../common/constants'+import { getIPFromHeaders } from '../../common/utils'++const TRUSTED_PROXY_IPS = new Set(+ (process.env.TRUSTED_PROXY_IPS || '')+ .split(',')+ .map((entry) => entry.trim())+ .filter(Boolean),+)++const firstHeaderValue = (value: unknown): string => {+ if (_isString(value) && value) {+ return value.trim()+ }+ if (Array.isArray(value) && _isString(value[0]) && value[0]) {+ return value[0].trim()+ }+ return ''+}++export const getTrustworthyIp = (req: {+ headers: Record<string, unknown>+ ip?: string+}): string => {+ const connectionIp = firstHeaderValue(req.headers['x-real-ip'])++ if (connectionIp && TRUSTED_PROXY_IPS.has(connectionIp)) {+ return firstHeaderValue(req.headers['x-client-ip-address'])+ }++ if (connectionIp) {+ return connectionIp+ }++ return getIPFromHeaders(req.headers) || req.ip || ''+}++export const getSinglePid = (+ query: Record<string, unknown>,+ params?: Record<string, unknown>,+): string | null => {+ // v2 routes carry the pid as a path param (/v2/projects/:pid/...)+ const paramPid = params?.pid++ if (_isString(paramPid) && PID_REGEX.test(paramPid)) {+ return paramPid+ }++ const { pid, pids } = query++ if (_isString(pid) && pid) {+ return pid+ }++ if (_isString(pids) && pids) {+ try {+ const parsed = JSON.parse(pids)+ if (+ Array.isArray(parsed) &&+ parsed.length === 1 &&+ _isString(parsed[0])+ ) {+ return parsed[0]+ }+ } catch {+ return null+ }+ }++ return null+}++export const getAnalyticsRoute = (path: string): string =>+ path.replace(/^\/(v1\/)?log\/?/, '').replace(/\/$/, '')diff --git a/backend/apps/community/src/analytics/protection/cacheable-analytics.decorator.ts b/backend/apps/community/src/analytics/protection/cacheable-analytics.decorator.tsnew file mode 100644index 000000000..3e34cd2ef--- /dev/null+++ b/backend/apps/community/src/analytics/protection/cacheable-analytics.decorator.ts@@ -0,0 +1,11 @@+import { SetMetadata } from '@nestjs/common'++export const CACHEABLE_ANALYTICS_KEY = 'cacheable_analytics'++/**+ * Opt a v2 analytics GET handler into the public-project Redis cache+ * (PublicProjectCacheInterceptor). v1 routes are matched by the+ * CACHEABLE_ROUTES set instead and don't need this decorator.+ */+export const CacheableAnalytics = () =>+ SetMetadata(CACHEABLE_ANALYTICS_KEY, true)diff --git a/backend/apps/community/src/analytics/protection/public-project-cache.interceptor.ts b/backend/apps/community/src/analytics/protection/public-project-cache.interceptor.tsnew file mode 100644index 000000000..e284d8662--- /dev/null+++ b/backend/apps/community/src/analytics/protection/public-project-cache.interceptor.ts@@ -0,0 +1,124 @@+import {+ CallHandler,+ ExecutionContext,+ Injectable,+ NestInterceptor,+} from '@nestjs/common'+import { Reflector } from '@nestjs/core'+import { Observable, of } from 'rxjs'+import { tap } from 'rxjs/operators'++import { ProjectService } from '../../project/project.service'+import { AppLoggerService } from '../../logger/logger.service'+import { redis } from '../../common/constants'+import { getSinglePid, getAnalyticsRoute } from './analytics-read.util'+import { CACHEABLE_ANALYTICS_KEY } from './cacheable-analytics.decorator'++const CACHE_TTL = Number(process.env.PUBLIC_PROJECT_CACHE_TTL) || 10 // seconds++const CACHE_PREFIX = 'arc' // analytics read cache++const CACHEABLE_ROUTES = new Set([+ '', // getData - dashboard overview+ 'chart',+ 'birdseye',+ 'performance',+ 'performance/chart',+ 'performance/birdseye',+ 'sessions',+ 'profiles',+ 'errors',+ 'error-overview',+ 'funnel',+ 'funnel-sessions',+ 'user-flow',+ 'custom-events',+ 'keywords',+ 'gsc-dashboard',+ 'gsc-details',+])++/**+ * Caches read responses for PUBLIC projects in Redis for a short window.+ */+@Injectable()+export class PublicProjectCacheInterceptor implements NestInterceptor {+ constructor(+ private readonly projectService: ProjectService,+ private readonly logger: AppLoggerService,+ private readonly reflector: Reflector,+ ) {}++ async intercept(+ context: ExecutionContext,+ next: CallHandler,+ ): Promise<Observable<unknown>> {+ const req = context.switchToHttp().getRequest()++ if (req.method !== 'GET') {+ return next.handle()+ }++ // v2 handlers opt in via @CacheableAnalytics(); v1 routes are matched+ // against the static route set+ const isCacheableV2 = this.reflector.get<boolean>(+ CACHEABLE_ANALYTICS_KEY,+ context.getHandler(),+ )++ if (!isCacheableV2) {+ const route = getAnalyticsRoute(req.path || '')+ if (!CACHEABLE_ROUTES.has(route)) {+ return next.handle()+ }+ }++ const pid = getSinglePid(req.query || {}, req.params || {})+ if (!pid) {+ return next.handle()+ }++ let isPublic = false+ try {+ const project = await this.projectService.getRedisProject(pid)+ isPublic = Boolean(project?.public)+ } catch {+ return next.handle()+ }++ if (!isPublic) {+ return next.handle()+ }++ const key = `${CACHE_PREFIX}:${req.originalUrl}`++ try {+ const cached = await redis.get(key)+ if (cached !== null) {+ return of(JSON.parse(cached))+ }+ } catch (reason) {+ this.logger.warn(+ `PublicProjectCacheInterceptor read failed: ${reason}`,+ 'PublicProjectCacheInterceptor',+ )+ return next.handle()+ }++ return next.handle().pipe(+ tap((body) => {+ if (body === undefined || body === null) {+ return+ }+ redis+ .set(key, JSON.stringify(body), 'EX', CACHE_TTL)+ .catch((reason) => {+ this.logger.warn(+ `PublicProjectCacheInterceptor write failed: ${reason}`,+ 'PublicProjectCacheInterceptor',+ )+ })+ }),+ )+ }+}diff --git a/backend/apps/community/src/analytics/v2/__tests__/breakdown-query.builder.spec.ts b/backend/apps/community/src/analytics/v2/__tests__/breakdown-query.builder.spec.tsnew file mode 100644index 000000000..75f684dd0--- /dev/null+++ b/backend/apps/community/src/analytics/v2/__tests__/breakdown-query.builder.spec.ts@@ -0,0 +1,160 @@+import { UnprocessableEntityException } from '@nestjs/common'++import {+ buildBreakdownQuery,+ parseSortParam,+} from '../query/breakdown-query.builder'+import {+ getBreakdownDimension,+ getMetric,+ parseMetricsParam,+} from '../registry'++const SUB_QUERY = `FROM events WHERE pid = {pid:FixedString(12)} AND type = 'pageview' AND created BETWEEN {groupFrom:String} AND {groupTo:String}`++const normalize = (sql: string) => sql.replace(/\s+/g, ' ').trim()++describe('parseSortParam', () => {+ const dimension = getBreakdownDimension('country', 'traffic')+ const metrics = parseMetricsParam('visitors,pageviews', 'traffic')++ it('defaults to first metric desc', () => {+ expect(parseSortParam(undefined, dimension, metrics)).toEqual({+ field: 'visitors',+ direction: 'desc',+ })+ })++ it('parses field:direction and validates both', () => {+ expect(parseSortParam('pageviews:asc', dimension, metrics)).toEqual({+ field: 'pageviews',+ direction: 'asc',+ })+ expect(parseSortParam('value:asc', dimension, metrics)).toEqual({+ field: 'value',+ direction: 'asc',+ })+ expect(() => parseSortParam('visitors:up', dimension, metrics)).toThrow(+ UnprocessableEntityException,+ )+ expect(() => parseSortParam('users:desc', dimension, metrics)).toThrow(+ UnprocessableEntityException,+ )+ })+})++describe('buildBreakdownQuery', () => {+ it('builds a multi-metric traffic query with pagination and total', () => {+ const query = normalize(+ buildBreakdownQuery({+ dataType: 'traffic',+ dimension: getBreakdownDimension('country', 'traffic'),+ metrics: parseMetricsParam('visitors,pageviews', 'traffic'),+ subQuery: SUB_QUERY,+ ctx: { customEVFilterApplied: false },+ sort: { field: 'visitors', direction: 'desc' },+ }),+ )++ expect(query).toContain('cc AS value')+ expect(query).toContain('count(DISTINCT psid) AS visitors')+ expect(query).toContain('count(*) AS pageviews')+ expect(query).toContain('count() OVER () AS __total')+ expect(query).toContain('GROUP BY value')+ expect(query).toContain('ORDER BY visitors desc')+ expect(query).toContain('LIMIT {v2_limit:UInt32} OFFSET {v2_offset:UInt32}')+ })++ it('degrades visitors to count(*) under custom-event filters (v1 parity)', () => {+ const query = buildBreakdownQuery({+ dataType: 'traffic',+ dimension: getBreakdownDimension('country', 'traffic'),+ metrics: [getMetric('visitors', 'traffic')],+ subQuery: SUB_QUERY,+ ctx: { customEVFilterApplied: true },+ sort: { field: 'visitors', direction: 'desc' },+ })++ expect(query).toContain('count(*) AS visitors')+ expect(query).not.toContain('count(DISTINCT psid)')+ })++ it('includes extra fields for region and groups by them', () => {+ const query = normalize(+ buildBreakdownQuery({+ dataType: 'traffic',+ dimension: getBreakdownDimension('region', 'traffic'),+ metrics: [getMetric('visitors', 'traffic')],+ subQuery: SUB_QUERY,+ ctx: { customEVFilterApplied: false },+ sort: { field: 'visitors', direction: 'desc' },+ }),+ )++ expect(query).toContain('rg AS value')+ expect(query).toContain('cc AS country')+ expect(query).toContain('rgc AS region_code')+ expect(query).toContain('GROUP BY value, country, region_code')+ // region is in the v1 EXCLUDE_NULL_FOR list+ expect(query).toContain('AND rg IS NOT NULL')+ })++ it('applies the measure to performance metrics', () => {+ const query = buildBreakdownQuery({+ dataType: 'performance',+ dimension: getBreakdownDimension('page', 'performance'),+ metrics: [getMetric('load_time', 'performance')],+ subQuery: SUB_QUERY,+ ctx: { customEVFilterApplied: false, measure: 'p95' },+ sort: { field: 'load_time', direction: 'desc' },+ })++ expect(query).toContain(+ 'round(divide(quantileExact(0.95)(pageLoad), 1000), 2) AS load_time',+ )+ })++ it('uses captcha meta-column expressions and per-dimension guards', () => {+ const query = normalize(+ buildBreakdownQuery({+ dataType: 'captcha',+ dimension: getBreakdownDimension('solve_time', 'captcha'),+ metrics: [getMetric('events', 'captcha')],+ subQuery: SUB_QUERY,+ ctx: { customEVFilterApplied: false },+ sort: { field: 'events', direction: 'desc' },+ }),+ )++ // solve_time resolves to a multiIf bucket expression, not a plain column+ expect(query).toContain('multiIf(')+ expect(query).toContain("= 'pass'")++ const countryQuery = normalize(+ buildBreakdownQuery({+ dataType: 'captcha',+ dimension: getBreakdownDimension('country', 'captcha'),+ metrics: [getMetric('events', 'captcha')],+ subQuery: SUB_QUERY,+ ctx: { customEVFilterApplied: false },+ sort: { field: 'events', direction: 'desc' },+ }),+ )++ // country/browser/os/device only count passed captchas (v1 parity)+ expect(countryQuery).toContain("= 'pass'")+ })++ it('rejects sessions-join metrics with a 422', () => {+ expect(() =>+ buildBreakdownQuery({+ dataType: 'traffic',+ dimension: getBreakdownDimension('country', 'traffic'),+ metrics: [getMetric('bounce_rate', 'traffic')],+ subQuery: SUB_QUERY,+ ctx: { customEVFilterApplied: false },+ sort: { field: 'bounce_rate', direction: 'desc' },+ }),+ ).toThrow(UnprocessableEntityException)+ })+})diff --git a/backend/apps/community/src/analytics/v2/__tests__/filters.translator.spec.ts b/backend/apps/community/src/analytics/v2/__tests__/filters.translator.spec.tsnew file mode 100644index 000000000..adec3deb3--- /dev/null+++ b/backend/apps/community/src/analytics/v2/__tests__/filters.translator.spec.ts@@ -0,0 +1,175 @@+import { UnprocessableEntityException } from '@nestjs/common'++import { parseV2Filters, toV1FiltersJson } from '../query/filters.translator'++describe('parseV2Filters', () => {+ it('returns [] for empty input', () => {+ expect(parseV2Filters(undefined)).toEqual([])+ expect(parseV2Filters('')).toEqual([])+ expect(parseV2Filters('""')).toEqual([])+ })++ it('parses valid filters', () => {+ const filters = parseV2Filters(+ JSON.stringify([+ { dimension: 'country', operator: 'is', value: ['US', 'DE'] },+ { dimension: 'page', operator: 'contains', value: '/blog' },+ ]),+ )++ expect(filters).toHaveLength(2)+ expect(filters[0]).toEqual({+ dimension: 'country',+ operator: 'is',+ value: ['US', 'DE'],+ })+ })++ it('rejects invalid JSON, non-arrays, bad operators and values', () => {+ expect(() => parseV2Filters('not json')).toThrow(+ UnprocessableEntityException,+ )+ expect(() => parseV2Filters('{"dimension":"country"}')).toThrow(+ UnprocessableEntityException,+ )+ expect(() =>+ parseV2Filters(+ JSON.stringify([+ { dimension: 'country', operator: 'equals', value: 'US' },+ ]),+ ),+ ).toThrow(UnprocessableEntityException)+ expect(() =>+ parseV2Filters(+ JSON.stringify([{ dimension: 'country', operator: 'is', value: 42 }]),+ ),+ ).toThrow(UnprocessableEntityException)+ })++ it('accepts null values (filter for unknown)', () => {+ const filters = parseV2Filters(+ JSON.stringify([{ dimension: 'region', operator: 'is', value: null }]),+ )++ expect(filters[0].value).toBeNull()+ })+})++describe('toV1FiltersJson', () => {+ it('translates operators to isExclusive/isContains and columns to v1 codes', () => {+ const filters = parseV2Filters(+ JSON.stringify([+ { dimension: 'country', operator: 'is', value: 'US' },+ { dimension: 'page', operator: 'contains', value: '/blog' },+ { dimension: 'browser', operator: 'is_not', value: 'Chrome' },+ { dimension: 'referrer', operator: 'contains_not', value: 'google' },+ ]),+ )++ const v1 = JSON.parse(toV1FiltersJson(filters, 'traffic'))++ expect(v1).toEqual([+ { column: 'cc', filter: 'US', isExclusive: false, isContains: false },+ { column: 'pg', filter: '/blog', isExclusive: false, isContains: true },+ { column: 'br', filter: 'Chrome', isExclusive: true, isContains: false },+ {+ column: 'ref',+ filter: 'google',+ isExclusive: true,+ isContains: true,+ },+ ])+ })++ it('translates keyed metadata filters to ev:key:<k> / tag:key:<k>', () => {+ const filters = parseV2Filters(+ JSON.stringify([+ {+ dimension: 'event_metadata',+ key: 'plan',+ operator: 'is_not',+ value: 'free',+ },+ {+ dimension: 'page_property',+ key: 'author',+ operator: 'is',+ value: 'Andrii',+ },+ { dimension: 'event_metadata', operator: 'is', value: 'plan' },+ ]),+ )++ const v1 = JSON.parse(toV1FiltersJson(filters, 'traffic'))++ expect(v1[0].column).toBe('ev:key:plan')+ expect(v1[0].isExclusive).toBe(true)+ expect(v1[1].column).toBe('tag:key:author')+ expect(v1[2].column).toBe('ev:key')+ })++ it('maps errors-only dimensions through v1 public names', () => {+ const filters = parseV2Filters(+ JSON.stringify([+ { dimension: 'error_name', operator: 'is', value: 'TypeError' },+ ]),+ )++ const v1 = JSON.parse(toV1FiltersJson(filters, 'errors'))++ expect(v1[0].column).toBe('name')+ })++ it('rejects unknown dimensions strictly, drops them in lenient mode', () => {+ const filters = parseV2Filters(+ JSON.stringify([+ { dimension: 'error_name', operator: 'is', value: 'TypeError' },+ { dimension: 'country', operator: 'is', value: 'US' },+ ]),+ )++ // error_name is not a traffic dimension+ expect(() => toV1FiltersJson(filters, 'traffic')).toThrow(+ UnprocessableEntityException,+ )++ const lenient = JSON.parse(+ toV1FiltersJson(filters, 'traffic', { lenient: true }),+ )++ expect(lenient).toHaveLength(1)+ expect(lenient[0].column).toBe('cc')+ })++ it('keeps array values intact (v1 expands them internally)', () => {+ const filters = parseV2Filters(+ JSON.stringify([+ { dimension: 'country', operator: 'is', value: ['US', null] },+ ]),+ )++ const v1 = JSON.parse(toV1FiltersJson(filters, 'traffic'))++ expect(v1[0].filter).toEqual(['US', null])+ })++ it('translates entry_page / exit_page / referrer_name / event filters', () => {+ const filters = parseV2Filters(+ JSON.stringify([+ { dimension: 'entry_page', operator: 'is', value: '/' },+ { dimension: 'exit_page', operator: 'is', value: '/bye' },+ { dimension: 'referrer_name', operator: 'is', value: 'google.com' },+ { dimension: 'event', operator: 'is', value: 'signup' },+ ]),+ )++ const v1 = JSON.parse(toV1FiltersJson(filters, 'traffic'))++ expect(v1.map((filter: { column: string }) => filter.column)).toEqual([+ 'entryPage',+ 'exitPage',+ 'refn',+ 'ev',+ ])+ })+})diff --git a/backend/apps/community/src/analytics/v2/__tests__/ioredis.stub.ts b/backend/apps/community/src/analytics/v2/__tests__/ioredis.stub.tsnew file mode 100644index 000000000..c1b956f81--- /dev/null+++ b/backend/apps/community/src/analytics/v2/__tests__/ioredis.stub.ts@@ -0,0 +1,18 @@+/**+ * Minimal ioredis stand-in so importing analytics.service.ts (which pulls in+ * common/constants and its module-level Redis client) doesn't open network+ * connections during unit tests.+ */+class RedisStub {+ // eslint-disable-next-line @typescript-eslint/no-useless-constructor+ constructor(..._args: unknown[]) {}++ defineCommand(): void {}++ on(): this {+ return this+ }+}++export default RedisStub+export { RedisStub as Redis }diff --git a/backend/apps/community/src/analytics/v2/__tests__/registry.spec.ts b/backend/apps/community/src/analytics/v2/__tests__/registry.spec.tsnew file mode 100644index 000000000..7194022d3--- /dev/null+++ b/backend/apps/community/src/analytics/v2/__tests__/registry.spec.ts@@ -0,0 +1,126 @@+import { UnprocessableEntityException } from '@nestjs/common'++import {+ getBreakdownDimension,+ getDefaultMetrics,+ getMetric,+ listDimensions,+ parseMetricsParam,+ V2_DIMENSIONS,+} from '../registry'++// Keep the registry in lockstep with the v1 filter column allowlists+// (common/constants.ts). If a column is added there, the registry must learn+// about it too.+const {+ TRAFFIC_COLUMNS,+ PERFORMANCE_COLUMNS,+ ERROR_COLUMNS,+ CAPTCHA_COLUMNS,+ // eslint-disable-next-line @typescript-eslint/no-require-imports+} = require('../../../common/constants')++describe('registry <-> v1 column allowlist lockstep', () => {+ const columnsFor = (type: 'traffic' | 'performance' | 'captcha' | 'errors') =>+ V2_DIMENSIONS.filter(+ (dimension) => dimension.types.includes(type) && !dimension.virtual,+ ).map((dimension) => dimension.column)++ it('covers every v1 traffic column', () => {+ for (const column of TRAFFIC_COLUMNS) {+ expect(columnsFor('traffic')).toContain(column)+ }+ })++ it('covers every v1 performance column', () => {+ for (const column of PERFORMANCE_COLUMNS) {+ expect(columnsFor('performance')).toContain(column)+ }+ })++ it('covers every v1 error column', () => {+ for (const column of ERROR_COLUMNS) {+ expect(columnsFor('errors')).toContain(column)+ }+ })++ it('covers every v1 captcha column', () => {+ for (const column of CAPTCHA_COLUMNS) {+ expect(columnsFor('captcha')).toContain(column)+ }+ })+})++describe('dimension lookups', () => {+ it('resolves valid breakdown dimensions', () => {+ expect(getBreakdownDimension('country', 'traffic').column).toBe('cc')+ expect(getBreakdownDimension('page', 'performance').column).toBe('pg')+ })++ it('rejects unknown and filter-only dimensions with 422', () => {+ expect(() => getBreakdownDimension('nope', 'traffic')).toThrow(+ UnprocessableEntityException,+ )+ expect(() => getBreakdownDimension('referrer_name', 'traffic')).toThrow(+ UnprocessableEntityException,+ )+ expect(() => getBreakdownDimension('event', 'traffic')).toThrow(+ UnprocessableEntityException,+ )+ // valid dimension, wrong data type+ expect(() => getBreakdownDimension('referrer', 'performance')).toThrow(+ UnprocessableEntityException,+ )+ })++ it('has unique api names per data type', () => {+ for (const type of [+ 'traffic',+ 'performance',+ 'captcha',+ 'errors',+ ] as const) {+ const names = listDimensions(type).map((dimension) => dimension.api)+ expect(new Set(names).size).toBe(names.length)+ }+ })+})++describe('metric lookups', () => {+ it('resolves metrics and rejects unknown ones', () => {+ expect(getMetric('visitors', 'traffic').api).toBe('visitors')+ expect(() => getMetric('visitors', 'errors')).toThrow(+ UnprocessableEntityException,+ )+ })++ it('provides sensible defaults per data type', () => {+ expect(getDefaultMetrics('traffic').map((metric) => metric.api)).toEqual([+ 'visitors',+ 'pageviews',+ ])+ expect(+ getDefaultMetrics('performance').map((metric) => metric.api),+ ).toEqual(['load_time'])+ expect(getDefaultMetrics('errors').map((metric) => metric.api)).toEqual([+ 'occurrences',+ ])+ })++ it('parses and dedupes the metrics CSV param', () => {+ expect(+ parseMetricsParam('visitors, pageviews,visitors', 'traffic').map(+ (metric) => metric.api,+ ),+ ).toEqual(['visitors', 'pageviews'])++ expect(parseMetricsParam(undefined, 'traffic').map((m) => m.api)).toEqual([+ 'visitors',+ 'pageviews',+ ])++ expect(() => parseMetricsParam('bogus', 'traffic')).toThrow(+ UnprocessableEntityException,+ )+ })+})diff --git a/backend/apps/community/src/analytics/v2/__tests__/timeseries.mapper.spec.ts b/backend/apps/community/src/analytics/v2/__tests__/timeseries.mapper.spec.tsnew file mode 100644index 000000000..1c97d0db3--- /dev/null+++ b/backend/apps/community/src/analytics/v2/__tests__/timeseries.mapper.spec.ts@@ -0,0 +1,72 @@+import {+ computeBounceRateSeries,+ toIsoTimestamp,+ zipTimeseries,+} from '../mappers/timeseries.mapper'++describe('toIsoTimestamp', () => {+ it('applies the timezone offset for day labels', () => {+ expect(toIsoTimestamp('2026-07-01', 'Europe/Kyiv')).toBe(+ '2026-07-01T00:00:00+03:00',+ )+ })++ it('handles hour labels and UTC', () => {+ expect(toIsoTimestamp('2026-07-01 13:00:00', 'Etc/GMT')).toBe(+ '2026-07-01T13:00:00Z',+ )+ })++ it('handles month and year labels', () => {+ expect(toIsoTimestamp('2026-07', 'Etc/GMT')).toBe('2026-07-01T00:00:00Z')+ expect(toIsoTimestamp('2026', 'Etc/GMT')).toBe('2026-01-01T00:00:00Z')+ })+})++describe('zipTimeseries', () => {+ it('zips columnar series into self-describing rows', () => {+ const rows = zipTimeseries(+ ['2026-07-01', '2026-07-02'],+ {+ visitors: [10, 20],+ pageviews: [30, 40],+ skipped: undefined,+ },+ 'Etc/GMT',+ )++ expect(rows).toEqual([+ {+ timestamp: '2026-07-01T00:00:00Z',+ visitors: 10,+ pageviews: 30,+ },+ {+ timestamp: '2026-07-02T00:00:00Z',+ visitors: 20,+ pageviews: 40,+ },+ ])+ })++ it('fills missing values with null', () => {+ const rows = zipTimeseries(+ ['2026-07-01', '2026-07-02'],+ { visitors: [10] },+ 'Etc/GMT',+ )++ expect(rows[1].visitors).toBeNull()+ })+})++describe('computeBounceRateSeries', () => {+ it('computes per-bucket bounce rate as bounces / uniques * 100', () => {+ expect(computeBounceRateSeries([1, 0, 3], [4, 0, 6])).toEqual([25, 0, 50])+ })++ it('returns undefined when either input is missing', () => {+ expect(computeBounceRateSeries(undefined, [1])).toBeUndefined()+ expect(computeBounceRateSeries([1], undefined)).toBeUndefined()+ })+})diff --git a/backend/apps/community/src/analytics/v2/analytics-v2.service.ts b/backend/apps/community/src/analytics/v2/analytics-v2.service.tsnew file mode 100644index 000000000..2c9720963--- /dev/null+++ b/backend/apps/community/src/analytics/v2/analytics-v2.service.ts@@ -0,0 +1,2022 @@+import {+ BadRequestException,+ Injectable,+ InternalServerErrorException,+ UnprocessableEntityException,+} from '@nestjs/common'+import dayjs from 'dayjs'+import utc from 'dayjs/plugin/utc'++import { clickhouse } from '../../common/integrations/clickhouse'+import { AppLoggerService } from '../../logger/logger.service'+import { MAX_METRICS_IN_VIEW } from '../../project/dto/create-project-view.dto'+import { IFunnel, PerfMeasure } from '../interfaces'+import {+ AnalyticsService,+ getLowestPossibleTimeBucket,+} from '../analytics.service'+import { ChartRenderMode, TimeBucketType } from '../dto/getData.dto'+import { GetCustomEventMetadata } from '../dto/get-custom-event-meta.dto'+import { GetPagePropertyMetaDto } from '../dto/get-page-property-meta.dto'+import {+ findDimension,+ getBreakdownDimension,+ getMetric,+ listDimensions,+ listMetrics,+ parseMetricsParam,+ V2_TO_V1_DATATYPE,+ V2DataType,+ V2MetricDef,+} from './registry'+import {+ parseV2Filters,+ toV1FiltersJson,+ V2Filter,+} from './query/filters.translator'+import {+ buildBreakdownQuery,+ parseSortParam,+} from './query/breakdown-query.builder'+import {+ computeBounceRateSeries,+ toIsoTimestamp,+ zipTimeseries,+ TimeseriesRow,+} from './mappers/timeseries.mapper'+import { renameEntityKeys, renameEntityList } from './mappers/entity.mapper'+import { mapTrafficSummary, V1TrafficSummary } from './mappers/summary.mapper'+import { envelope, V2Envelope } from './mappers/envelope'+import {+ V2_DEFAULT_PERIOD,+ V2BaseQueryDto,+ V2BreakdownDto,+ V2TimeseriesDto,+} from './dto/v2-base.dto'++dayjs.extend(utc)++type EventsAllTimeType =+ | 'pageview'+ | 'custom_event'+ | 'performance'+ | 'error'+ | 'captcha'++const ALL_TIME_EVENT_TYPES: Record<V2DataType, readonly EventsAllTimeType[]> = {+ traffic: ['pageview', 'custom_event', 'error'],+ performance: ['performance'],+ captcha: ['captcha'],+ errors: ['error'],+}++/** Traffic metrics computable per time bucket by the v1 chart query */+const TRAFFIC_TIMESERIES_METRICS = [+ 'visitors',+ 'pageviews',+ 'session_duration',+ 'bounce_rate',+]++/** Performance metrics computable per time bucket (v2 name -> v1 chart key) */+const PERFORMANCE_TIMESERIES_METRICS: Record<string, string> = {+ dns: 'dns',+ tls: 'tls',+ connection: 'conn',+ response: 'response',+ render: 'render',+ dom_load: 'domLoad',+ ttfb: 'ttfb',+}++/** Captcha counters computable per time bucket (v2 name -> v1 chart key) */+const CAPTCHA_TIMESERIES_METRICS: Record<string, string> = {+ generated: 'generated',+ passed: 'passed',+ failed: 'failed',+ validation_failed: 'validationFailed',+ replayed: 'replayed',+}++const ONLINE_VISITORS_WINDOW_MINUTES = 5++export interface ResolvedTimeframe {+ period: string | null+ timeBucket: TimeBucketType | null+ allowedTimeBuckets: TimeBucketType[] | null+ safeTimezone: string+ /** Timezone-shifted bounds (YYYY-MM-DD HH:mm:ss) */+ groupFrom: string+ groupTo: string+ /** UTC bounds used as ClickHouse query params */+ groupFromUTC: string+ groupToUTC: string+}++interface PreparedFilters {+ appliedFilters: V2Filter[]+ v1FiltersJson: string+ filtersQuery: string+ filtersParams: Record<string, unknown>+ customEVFilterApplied: boolean+}++const DEFAULT_BREAKDOWN_LIMIT = 30++@Injectable()+export class AnalyticsV2Service {+ constructor(+ private readonly analyticsService: AnalyticsService,+ private readonly logger: AppLoggerService,+ ) {}++ async assertReadAccess(+ pid: string,+ uid: string | null,+ password?: string,+ ): Promise<void> {+ await this.analyticsService.checkProjectAccess(pid, uid, password)+ }++ /**+ * Resolve period/from/to/timeBucket/timezone into concrete query bounds.+ * Centralizes the v1 `period=all` dance (first-event lookup -> diff ->+ * allowed time buckets) in a single place.+ */+ async resolveTimeframe(opts: {+ pid: string+ dataType: V2DataType+ period?: string+ from?: string+ to?: string+ timeBucket?: TimeBucketType+ timezone?: string+ /** Override the event types used for the period=all first-event lookup */+ allTimeEventTypes?: readonly EventsAllTimeType[]+ }): Promise<ResolvedTimeframe> {+ const { pid, dataType, from, to, timezone } = opts++ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)++ if (Boolean(from) !== Boolean(to)) {+ throw new BadRequestException(+ "The 'from' and 'to' parameters must be provided together",+ )+ }++ const hasCustomRange = Boolean(from && to)+ const period = hasCustomRange+ ? null+ : opts.period && opts.period !== 'custom'+ ? opts.period+ : V2_DEFAULT_PERIOD++ let timeBucket =+ opts.timeBucket ||+ getLowestPossibleTimeBucket(+ period ?? undefined,+ hasCustomRange ? from : undefined,+ hasCustomRange ? to : undefined,+ )++ let diff: number | undefined+ let allowedTimeBuckets: TimeBucketType[] | null = null++ if (period === 'all') {+ const allTime = await this.analyticsService.calculateTimeBucketForAllTime(+ pid,+ opts.allTimeEventTypes ?? ALL_TIME_EVENT_TYPES[dataType],+ )++ diff = allTime.diff+ allowedTimeBuckets = allTime.timeBucket+ timeBucket =+ opts.timeBucket && allTime.timeBucket.includes(opts.timeBucket)+ ? opts.timeBucket+ : allTime.timeBucket[0]+ }++ const { groupFrom, groupTo, groupFromUTC, groupToUTC } =+ this.analyticsService.getGroupFromTo(+ hasCustomRange ? from : undefined,+ hasCustomRange ? to : undefined,+ timeBucket,+ period ?? undefined,+ safeTimezone,+ diff,+ )++ return {+ period,+ timeBucket,+ allowedTimeBuckets,+ safeTimezone,+ groupFrom,+ groupTo,+ groupFromUTC,+ groupToUTC,+ }+ }++ prepareFilters(+ filters: string | undefined,+ dataType: V2DataType,+ ignoreEV?: boolean,+ ): PreparedFilters {+ const appliedFilters = parseV2Filters(filters)+ const v1FiltersJson = toV1FiltersJson(appliedFilters, dataType)++ const [filtersQuery, filtersParams, , customEVFilterApplied] =+ this.analyticsService.getFiltersQuery(+ v1FiltersJson,+ V2_TO_V1_DATATYPE[dataType],+ ignoreEV,+ )++ return {+ appliedFilters,+ v1FiltersJson,+ filtersQuery,+ filtersParams,+ customEVFilterApplied,+ }+ }++ buildSubQuery(+ dataType: V2DataType,+ filtersQuery: string,+ customEVFilterApplied: boolean,+ ): string {+ if (dataType === 'traffic') {+ return this.analyticsService.buildAnalyticsEventsSubQuery(+ filtersQuery,+ customEVFilterApplied,+ )+ }++ if (dataType === 'captcha') {+ return this.analyticsService.buildAnalyticsEventsSubQuery(+ filtersQuery,+ false,+ true,+ )+ }++ const eventType = dataType === 'performance' ? 'performance' : 'error'++ return `FROM events WHERE pid = {pid:FixedString(12)} AND type = '${eventType}' ${filtersQuery} AND created BETWEEN {groupFrom:String} AND {groupTo:String}`+ }++ private baseMeta(+ pid: string,+ timeframe: ResolvedTimeframe,+ appliedFilters: V2Filter[],+ ): Record<string, unknown> {+ return {+ pid,+ period: timeframe.period,+ from: toIsoTimestamp(timeframe.groupFrom, timeframe.safeTimezone),+ to: toIsoTimestamp(timeframe.groupTo, timeframe.safeTimezone),+ timezone: timeframe.safeTimezone,+ appliedFilters,+ }+ }++ async getBreakdown(+ pid: string,+ dto: V2BreakdownDto,+ dataType: V2DataType,+ measure?: PerfMeasure,+ ): Promise<V2Envelope<Record<string, unknown>[]>> {+ const dimension = getBreakdownDimension(dto.dimension, dataType)+ // Session-scoped virtual dimensions (entry/exit page) only support+ // 'visitors', so the per-type defaults don't apply to them+ const metrics =+ dimension.virtual && !dto.metrics+ ? [getMetric('visitors', dataType)]+ : parseMetricsParam(dto.metrics, dataType)+ // v1 parity: performance and error queries ignore custom-event filters+ const filters = this.prepareFilters(+ dto.filters,+ dataType,+ dataType === 'performance' || dataType === 'errors',+ )+ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timezone: dto.timezone,+ })++ const limit = dto.limit ?? DEFAULT_BREAKDOWN_LIMIT+ const offset = dto.offset ?? 0+ const sort = parseSortParam(dto.sort, dimension, metrics)+ const subQuery = this.buildSubQuery(+ dataType,+ filters.filtersQuery,+ filters.customEVFilterApplied,+ )++ const meta: Record<string, unknown> = {+ ...this.baseMeta(pid, timeframe, filters.appliedFilters),+ dimension: dimension.api,+ metrics: metrics.map((metric) => metric.api),+ limit,+ offset,+ sort: `${sort.field}:${sort.direction}`,+ }++ if (dimension.virtual) {+ const rows = await this.getVirtualPageBreakdown(+ dimension.virtual,+ dataType,+ metrics,+ filters,+ subQuery,+ {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ },+ sort,+ )++ meta.total = rows.length++ return envelope(rows.slice(offset, offset + limit), meta)+ }++ const query = buildBreakdownQuery({+ dataType,+ dimension,+ metrics,+ subQuery,+ ctx: {+ customEVFilterApplied: filters.customEVFilterApplied,+ measure,+ },+ sort,+ })++ const { data } = await clickhouse+ .query({+ query,+ query_params: {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ v2_limit: limit,+ v2_offset: offset,+ },+ })+ .then((resultSet) => resultSet.json<Record<string, unknown>>())++ let total = 0++ const rows = (data || []).map((row) => {+ const { __total, value, ...rest } = row++ total = Number(__total) || 0++ const mapped: Record<string, unknown> = { value }++ for (const field of dimension.extraFields ?? []) {+ mapped[field.api] = rest[field.api] ?? null+ }++ for (const metric of metrics) {+ mapped[metric.api] = Number(rest[metric.api]) || 0+ }++ return mapped+ })++ meta.total = total++ return envelope(rows, meta)+ }++ private async getVirtualPageBreakdown(+ kind: 'entry_page' | 'exit_page',+ dataType: V2DataType,+ metrics: V2MetricDef[],+ filters: PreparedFilters,+ subQuery: string,+ params: Record<string, unknown>,+ sort: { field: string; direction: 'asc' | 'desc' },+ ): Promise<Record<string, unknown>[]> {+ if (dataType !== 'traffic') {+ throw new UnprocessableEntityException(+ `The '${kind}' dimension is only available for traffic breakdowns`,+ )+ }++ if (filters.customEVFilterApplied) {+ throw new UnprocessableEntityException(+ `The '${kind}' dimension cannot be combined with custom event filters`,+ )+ }++ const unsupported = metrics.filter((metric) => metric.api !== 'visitors')++ if (unsupported.length > 0) {+ throw new UnprocessableEntityException(+ `The '${kind}' dimension only supports the 'visitors' metric`,+ )+ }++ const paramsData = { params }++ const rows =+ kind === 'entry_page'+ ? await this.analyticsService.getEntryPages(subQuery, paramsData)+ : await this.analyticsService.getExitPages(subQuery, paramsData)++ const mapped = (rows || []).map((row) => ({+ value: row.name,+ visitors: Number(row.count) || 0,+ }))++ const directionFactor = sort.direction === 'asc' ? 1 : -1++ mapped.sort((a, b) => {+ if (sort.field === 'value') {+ return String(a.value).localeCompare(String(b.value)) * directionFactor+ }++ return (a.visitors - b.visitors) * directionFactor+ })++ return mapped+ }++ async getTrafficTimeseries(+ pid: string,+ dto: V2TimeseriesDto,+ ): Promise<V2Envelope<TimeseriesRow[]>> {+ const dataType: V2DataType = 'traffic'+ const metrics = parseMetricsParam(dto.metrics, dataType)++ for (const metric of metrics) {+ if (!TRAFFIC_TIMESERIES_METRICS.includes(metric.api)) {+ throw new UnprocessableEntityException(+ `The '${metric.api}' metric is not supported on the traffic timeseries. Supported metrics: ${TRAFFIC_TIMESERIES_METRICS.join(', ')}`,+ )+ }+ }++ const filters = this.prepareFilters(dto.filters, dataType)+ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timeBucket: dto.timeBucket,+ timezone: dto.timezone,+ })++ const mode = dto.mode || ChartRenderMode.PERIODICAL++ const result = (await this.analyticsService.groupChartByTimeBucket(+ timeframe.timeBucket,+ timeframe.groupFrom,+ timeframe.groupTo,+ filters.filtersQuery,+ {+ params: {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ },+ },+ timeframe.safeTimezone,+ filters.customEVFilterApplied,+ mode,+ )) as {+ chart: {+ x: string[]+ visits: number[]+ uniques: number[]+ sdur: number[]+ bounces?: number[]+ }+ }++ const { chart } = result++ const availableSeries: Record<string, (number | null)[] | undefined> = {+ visitors: chart.uniques,+ pageviews: chart.visits,+ session_duration: chart.sdur,+ bounce_rate: computeBounceRateSeries(chart.bounces, chart.uniques),+ }++ const series: Record<string, (number | null)[] | undefined> = {}++ for (const metric of metrics) {+ series[metric.api] = availableSeries[metric.api]+ }++ return envelope(zipTimeseries(chart.x, series, timeframe.safeTimezone), {+ ...this.baseMeta(pid, timeframe, filters.appliedFilters),+ timeBucket: timeframe.timeBucket,+ allowedTimeBuckets: timeframe.allowedTimeBuckets,+ metrics: metrics.map((metric) => metric.api),+ mode,+ })+ }++ async getTrafficSummary(+ pid: string,+ dto: V2BaseQueryDto,+ ): Promise<V2Envelope<ReturnType<typeof mapTrafficSummary>>> {+ const dataType: V2DataType = 'traffic'+ const appliedFilters = parseV2Filters(dto.filters)+ const v1FiltersJson = toV1FiltersJson(appliedFilters, dataType)++ const hasCustomRange = Boolean(dto.from && dto.to)++ if (Boolean(dto.from) !== Boolean(dto.to)) {+ throw new BadRequestException(+ "The 'from' and 'to' parameters must be provided together",+ )+ }++ const period = hasCustomRange+ ? undefined+ : dto.period && dto.period !== 'custom'+ ? dto.period+ : V2_DEFAULT_PERIOD++ const result = await this.analyticsService.getAnalyticsSummary(+ [pid],+ undefined,+ period,+ hasCustomRange ? dto.from : undefined,+ hasCustomRange ? dto.to : undefined,+ dto.timezone,+ v1FiltersJson,+ false,+ )++ const summary = result?.[pid] as V1TrafficSummary | undefined++ if (!summary) {+ throw new InternalServerErrorException(+ 'Failed to compute the traffic summary for this project',+ )+ }++ return envelope(mapTrafficSummary(summary), {+ pid,+ period: period ?? null,+ from: hasCustomRange ? dto.from : undefined,+ to: hasCustomRange ? dto.to : undefined,+ timezone: this.analyticsService.getSafeTimezone(dto.timezone),+ appliedFilters,+ })+ }++ async getTrafficCustomEvents(+ pid: string,+ dto: V2BaseQueryDto & { limit?: number; offset?: number },+ ): Promise<V2Envelope<{ event: string; count: number }[]>> {+ const dataType: V2DataType = 'traffic'+ const filters = this.prepareFilters(dto.filters, dataType)+ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timezone: dto.timezone,+ })++ const customs = await this.analyticsService.getCustomEvents(+ filters.filtersQuery,+ {+ params: {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ },+ },+ )++ const rows = Object.entries(customs || {})+ .map(([event, count]) => ({ event, count: Number(count) || 0 }))+ .sort((a, b) => b.count - a.count)++ const limit = dto.limit ?? DEFAULT_BREAKDOWN_LIMIT+ const offset = dto.offset ?? 0++ return envelope(rows.slice(offset, offset + limit), {+ ...this.baseMeta(pid, timeframe, filters.appliedFilters),+ total: rows.length,+ limit,+ offset,+ })+ }++ async getTrafficCustomMetrics(+ pid: string,+ dto: V2BaseQueryDto & { metrics: string },+ ): Promise<V2Envelope<unknown[]>> {+ const dataType: V2DataType = 'traffic'+ const filters = this.prepareFilters(dto.filters, dataType)+ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timezone: dto.timezone,+ })++ const parsedMetrics = this.analyticsService.parseMetrics(dto.metrics)++ if (parsedMetrics.length > MAX_METRICS_IN_VIEW) {+ throw new UnprocessableEntityException(+ `The maximum number of metrics within one request is ${MAX_METRICS_IN_VIEW}`,+ )+ }++ if (!parsedMetrics.length) {+ return envelope([], this.baseMeta(pid, timeframe, filters.appliedFilters))+ }++ const meta = await this.analyticsService.getMetaResults(+ pid,+ parsedMetrics,+ filters.filtersQuery,+ {+ params: {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ },+ },+ timeframe.safeTimezone,+ timeframe.period ?? undefined,+ dto.from,+ dto.to,+ )++ return envelope(+ meta ?? [],+ this.baseMeta(pid, timeframe, filters.appliedFilters),+ )+ }++ async getTrafficPageProperties(+ pid: string,+ dto: V2BaseQueryDto & { limit?: number; offset?: number },+ ): Promise<V2Envelope<{ property: string; count: number }[]>> {+ const dataType: V2DataType = 'traffic'+ const filters = this.prepareFilters(dto.filters, dataType)++ if (filters.customEVFilterApplied) {+ throw new UnprocessableEntityException(+ 'Page properties cannot be combined with custom event filters',+ )+ }++ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timezone: dto.timezone,+ })++ const properties = await this.analyticsService.getPageProperties(+ filters.filtersQuery,+ {+ params: {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ },+ },+ )++ const rows = Object.entries(properties || {})+ .map(([property, count]) => ({ property, count: Number(count) || 0 }))+ .sort((a, b) => b.count - a.count)++ const limit = dto.limit ?? DEFAULT_BREAKDOWN_LIMIT+ const offset = dto.offset ?? 0++ return envelope(rows.slice(offset, offset + limit), {+ ...this.baseMeta(pid, timeframe, filters.appliedFilters),+ total: rows.length,+ limit,+ offset,+ })+ }++ async getTrafficUserFlow(+ pid: string,+ dto: V2BaseQueryDto,+ ): Promise<V2Envelope<unknown>> {+ const dataType: V2DataType = 'traffic'+ const filters = this.prepareFilters(dto.filters, dataType, true)+ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timezone: dto.timezone,+ allTimeEventTypes: ['pageview'],+ })++ // v1 parity: the user-flow query compares `created` against the+ // timezone-shifted bounds directly+ const flow = await this.analyticsService.getUserFlow(+ {+ pid,+ groupFrom: timeframe.groupFrom,+ groupTo: timeframe.groupTo,+ ...filters.filtersParams,+ },+ filters.filtersQuery,+ )++ return envelope(flow, this.baseMeta(pid, timeframe, filters.appliedFilters))+ }++ async getPerformanceTimeseries(+ pid: string,+ dto: V2TimeseriesDto & { measure?: string },+ ): Promise<V2Envelope<TimeseriesRow[]>> {+ const dataType: V2DataType = 'performance'+ const measure = (dto.measure || 'median') as PerfMeasure++ this.analyticsService.checkIfPerfMeasureIsValid(measure)++ const filters = this.prepareFilters(dto.filters, dataType, true)+ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timeBucket: dto.timeBucket,+ timezone: dto.timezone,+ })++ const chart = (await this.analyticsService.getPerfChartData(+ timeframe.timeBucket,+ timeframe.groupFrom,+ timeframe.groupTo,+ filters.filtersQuery,+ {+ params: {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ },+ },+ timeframe.safeTimezone,+ measure,+ )) as { x: string[] } & Record<string, (number | null)[]>++ const series: Record<string, (number | null)[] | undefined> = {}+ let metricNames: string[]++ if (measure === 'quantiles') {+ metricNames = ['p50', 'p75', 'p95']++ for (const name of metricNames) {+ series[name] = chart[name]+ }+ } else {+ metricNames = dto.metrics+ ? [+ ...new Set(+ dto.metrics+ .split(',')+ .map((name) => name.trim())+ .filter(Boolean),+ ),+ ]+ : Object.keys(PERFORMANCE_TIMESERIES_METRICS)++ for (const name of metricNames) {+ const v1Key = Object.hasOwn(PERFORMANCE_TIMESERIES_METRICS, name)+ ? PERFORMANCE_TIMESERIES_METRICS[name]+ : undefined++ if (!v1Key) {+ throw new UnprocessableEntityException(+ `The '${name}' metric is not supported on the performance timeseries. Supported metrics: ${Object.keys(PERFORMANCE_TIMESERIES_METRICS).join(', ')}`,+ )+ }++ series[name] = chart[v1Key]+ }+ }++ return envelope(zipTimeseries(chart.x, series, timeframe.safeTimezone), {+ ...this.baseMeta(pid, timeframe, filters.appliedFilters),+ timeBucket: timeframe.timeBucket,+ allowedTimeBuckets: timeframe.allowedTimeBuckets,+ metrics: metricNames,+ measure,+ })+ }++ async getPerformanceSummary(+ pid: string,+ dto: V2BaseQueryDto & { measure?: string },+ ): Promise<V2Envelope<Record<string, unknown>>> {+ const dataType: V2DataType = 'performance'+ let measure = (dto.measure || 'median') as PerfMeasure++ this.analyticsService.checkIfPerfMeasureIsValid(measure)++ // v1 parity: quantiles is a timeseries-only measure; birdseye maps it to median+ if (measure === 'quantiles') {+ measure = 'median'+ }++ const appliedFilters = parseV2Filters(dto.filters)+ const v1FiltersJson = toV1FiltersJson(appliedFilters, dataType)++ if (Boolean(dto.from) !== Boolean(dto.to)) {+ throw new BadRequestException(+ "The 'from' and 'to' parameters must be provided together",+ )+ }++ const hasCustomRange = Boolean(dto.from && dto.to)+ const period = hasCustomRange+ ? undefined+ : dto.period && dto.period !== 'custom'+ ? dto.period+ : V2_DEFAULT_PERIOD++ const result = await this.analyticsService.getPerformanceSummary(+ [pid],+ period,+ hasCustomRange ? dto.from : undefined,+ hasCustomRange ? dto.to : undefined,+ dto.timezone,+ v1FiltersJson,+ measure,+ )++ const summary = result?.[pid] as+ | {+ current: Record<string, number>+ previous: Record<string, number>+ frontendChange: number+ networkChange: number+ backendChange: number+ }+ | undefined++ if (!summary) {+ throw new InternalServerErrorException(+ 'Failed to compute the performance summary for this project',+ )+ }++ return envelope(+ {+ current: summary.current,+ previous: summary.previous,+ change: {+ frontend: summary.frontendChange,+ network: summary.networkChange,+ backend: summary.backendChange,+ },+ },+ {+ pid,+ period: period ?? null,+ from: hasCustomRange ? dto.from : undefined,+ to: hasCustomRange ? dto.to : undefined,+ timezone: this.analyticsService.getSafeTimezone(dto.timezone),+ measure,+ appliedFilters,+ },+ )+ }++ async getCaptchaTimeseries(+ pid: string,+ dto: V2TimeseriesDto,+ ): Promise<V2Envelope<TimeseriesRow[]>> {+ const dataType: V2DataType = 'captcha'+ const filters = this.prepareFilters(dto.filters, dataType)+ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timeBucket: dto.timeBucket,+ timezone: dto.timezone,+ })++ const mode = dto.mode || ChartRenderMode.PERIODICAL++ const { xShifted } = this.analyticsService.generateXAxis(+ timeframe.timeBucket,+ timeframe.groupFrom,+ timeframe.groupTo,+ timeframe.safeTimezone,+ )++ const query = this.analyticsService.generateCaptchaAggregationQuery(+ timeframe.timeBucket,+ filters.filtersQuery,+ mode,+ )++ const { data } = await clickhouse+ .query({+ query,+ query_params: {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ timezone: timeframe.safeTimezone,+ },+ })+ .then((resultSet) => resultSet.json<Record<string, unknown>>())++ const chart = this.analyticsService.extractCaptchaChartData(+ data,+ xShifted,+ ) as Record<string, number[]>++ const metricNames = dto.metrics+ ? [+ ...new Set(+ dto.metrics+ .split(',')+ .map((name) => name.trim())+ .filter(Boolean),+ ),+ ]+ : Object.keys(CAPTCHA_TIMESERIES_METRICS)++ const series: Record<string, (number | null)[] | undefined> = {}++ for (const name of metricNames) {+ const v1Key = Object.hasOwn(CAPTCHA_TIMESERIES_METRICS, name)+ ? CAPTCHA_TIMESERIES_METRICS[name]+ : undefined++ if (!v1Key) {+ throw new UnprocessableEntityException(+ `The '${name}' metric is not supported on the captcha timeseries. Supported metrics: ${Object.keys(CAPTCHA_TIMESERIES_METRICS).join(', ')}`,+ )+ }++ series[name] = chart[v1Key]+ }++ return envelope(zipTimeseries(xShifted, series, timeframe.safeTimezone), {+ ...this.baseMeta(pid, timeframe, filters.appliedFilters),+ timeBucket: timeframe.timeBucket,+ allowedTimeBuckets: timeframe.allowedTimeBuckets,+ metrics: metricNames,+ mode,+ })+ }++ async getCaptchaSummary(+ pid: string,+ dto: V2BaseQueryDto,+ ): Promise<V2Envelope<Record<string, unknown>>> {+ const dataType: V2DataType = 'captcha'+ const filters = this.prepareFilters(dto.filters, dataType)+ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timezone: dto.timezone,+ })++ const baseParams = {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ }++ const currentPromise = this.analyticsService.getCaptchaSummary(+ filters.filtersQuery,+ { params: baseParams },+ )++ // Previous period of the same length (v1 parity; skipped for period=all)+ let previousPromise: Promise<object | null> = Promise.resolve(null)++ if (timeframe.period !== 'all') {+ const periodSubtracted = dayjs+ .utc(timeframe.groupFromUTC)+ .subtract(+ Math.abs(+ dayjs+ .utc(timeframe.groupFromUTC)+ .diff(dayjs.utc(timeframe.groupToUTC), 'minutes'),+ ),+ 'minutes',+ )+ .format('YYYY-MM-DD HH:mm:ss')++ previousPromise = this.analyticsService.getCaptchaSummary(+ filters.filtersQuery,+ {+ params: {+ ...baseParams,+ groupFrom: periodSubtracted,+ groupTo: timeframe.groupFromUTC,+ },+ },+ )+ }++ const [current, previous] = await Promise.all([+ currentPromise,+ previousPromise,+ ])++ return envelope(+ { current, previous },+ this.baseMeta(pid, timeframe, filters.appliedFilters),+ )+ }++ async getErrorsList(+ pid: string,+ dto: V2BaseQueryDto & {+ limit?: number+ offset?: number+ show_resolved?: boolean+ },+ ): Promise<V2Envelope<Record<string, unknown>[]>> {+ const dataType: V2DataType = 'errors'+ const filters = this.prepareFilters(dto.filters, dataType, true)+ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timezone: dto.timezone,+ })++ const limit = dto.limit ?? DEFAULT_BREAKDOWN_LIMIT+ const offset = dto.offset ?? 0++ const errors = await this.analyticsService.getErrorsList(+ JSON.stringify({ showResolved: Boolean(dto.show_resolved) }),+ filters.filtersQuery,+ {+ params: {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ },+ },+ timeframe.safeTimezone,+ limit,+ offset,+ )++ return envelope(renameEntityList(errors), {+ ...this.baseMeta(pid, timeframe, filters.appliedFilters),+ limit,+ offset,+ showResolved: Boolean(dto.show_resolved),+ })+ }++ async getErrorsTimeseries(+ pid: string,+ dto: V2TimeseriesDto,+ ): Promise<V2Envelope<TimeseriesRow[]>> {+ const dataType: V2DataType = 'errors'+ const filters = this.prepareFilters(dto.filters, dataType, true)+ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timeBucket: dto.timeBucket,+ timezone: dto.timezone,+ })++ const mode = dto.mode || ChartRenderMode.PERIODICAL++ // v1 parity: error occurrences are bucketed in UTC, labels are shifted+ // to the requested timezone afterwards+ const { x, format } = this.analyticsService.generateUTCXAxis(+ timeframe.timeBucket,+ timeframe.groupFromUTC,+ timeframe.groupToUTC,+ )++ const query = this.analyticsService.generateErrorsAggregationQuery(+ timeframe.timeBucket,+ filters.filtersQuery,+ mode,+ )++ const { data } = await clickhouse+ .query({+ query,+ query_params: {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ },+ })+ .then((resultSet) => resultSet.json<Record<string, unknown>>())++ const { count, affectedUsers } =+ this.analyticsService.extractErrorsChartData(data as never[], x)++ const labels = this.analyticsService.shiftToTimezone(+ x,+ timeframe.safeTimezone,+ format,+ )++ const availableSeries: Record<string, (number | null)[] | undefined> = {+ occurrences: count,+ affected_users: affectedUsers,+ }++ const metricNames = dto.metrics+ ? [+ ...new Set(+ dto.metrics+ .split(',')+ .map((name) => name.trim())+ .filter(Boolean),+ ),+ ]+ : Object.keys(availableSeries)++ const series: Record<string, (number | null)[] | undefined> = {}++ for (const name of metricNames) {+ if (!Object.hasOwn(availableSeries, name) || !availableSeries[name]) {+ throw new UnprocessableEntityException(+ `The '${name}' metric is not supported on the errors timeseries. Supported metrics: ${Object.keys(availableSeries).join(', ')}`,+ )+ }++ series[name] = availableSeries[name]+ }++ return envelope(zipTimeseries(labels, series, timeframe.safeTimezone), {+ ...this.baseMeta(pid, timeframe, filters.appliedFilters),+ timeBucket: timeframe.timeBucket,+ allowedTimeBuckets: timeframe.allowedTimeBuckets,+ metrics: metricNames,+ mode,+ })+ }++ async getErrorsOverview(+ pid: string,+ dto: V2BaseQueryDto & { show_resolved?: boolean },+ ): Promise<V2Envelope<unknown>> {+ const dataType: V2DataType = 'errors'+ const filters = this.prepareFilters(dto.filters, dataType, true)++ // Session-scoped stats inside the overview run against traffic data;+ // error-specific filters are dropped for that part (v1 parity)+ const sessionV1FiltersJson = toV1FiltersJson(+ filters.appliedFilters,+ 'traffic',+ { lenient: true },+ )+ const [sessionFiltersQuery, sessionFiltersParams] =+ this.analyticsService.getFiltersQuery(+ sessionV1FiltersJson,+ V2_TO_V1_DATATYPE.traffic,+ true,+ )++ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timezone: dto.timezone,+ })++ const overview = await this.analyticsService.getErrorOverview(+ pid,+ filters.filtersQuery,+ {+ params: {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ },+ },+ timeframe.safeTimezone,+ timeframe.groupFromUTC,+ timeframe.groupToUTC,+ timeframe.timeBucket,+ Boolean(dto.show_resolved),+ sessionFiltersQuery,+ sessionFiltersParams,+ )++ return envelope(overview, {+ ...this.baseMeta(pid, timeframe, filters.appliedFilters),+ timeBucket: timeframe.timeBucket,+ showResolved: Boolean(dto.show_resolved),+ })+ }++ async getErrorDetails(+ pid: string,+ eid: string,+ dto: V2BaseQueryDto & { timeBucket?: TimeBucketType },+ ): Promise<V2Envelope<unknown>> {+ const dataType: V2DataType = 'errors'+ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timeBucket: dto.timeBucket,+ timezone: dto.timezone,+ })++ const details = await this.analyticsService.getErrorDetails(+ pid,+ eid,+ timeframe.safeTimezone,+ timeframe.groupFromUTC,+ timeframe.groupToUTC,+ timeframe.timeBucket,+ )++ return envelope(details, {+ ...this.baseMeta(pid, timeframe, []),+ eid,+ timeBucket: timeframe.timeBucket,+ })+ }++ async getErrorSessions(+ pid: string,+ eid: string,+ dto: V2BaseQueryDto & { limit?: number; offset?: number },+ ): Promise<V2Envelope<Record<string, unknown>[]>> {+ const dataType: V2DataType = 'errors'+ const filters = this.prepareFilters(dto.filters, dataType, true)+ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timezone: dto.timezone,+ })++ const limit = dto.limit ?? 10+ const offset = dto.offset ?? 0++ const result = (await this.analyticsService.getErrorAffectedSessions(+ pid,+ eid,+ timeframe.groupFromUTC,+ timeframe.groupToUTC,+ limit,+ offset,+ filters.filtersQuery,+ filters.filtersParams,+ )) as { sessions?: unknown } | Record<string, unknown>[]++ const sessions = Array.isArray(result)+ ? result+ : ((result?.sessions ?? []) as Record<string, unknown>[])++ return envelope(renameEntityList(sessions), {+ ...this.baseMeta(pid, timeframe, filters.appliedFilters),+ eid,+ limit,+ offset,+ })+ }++ async getSessionsList(+ pid: string,+ dto: V2BaseQueryDto & {+ limit?: number+ offset?: number+ event_type?: 'traffic' | 'performance' | 'error'+ },+ ): Promise<V2Envelope<Record<string, unknown>[]>> {+ const eventType = dto.event_type || 'traffic'+ const dataType: V2DataType =+ eventType === 'performance'+ ? 'performance'+ : eventType === 'error'+ ? 'errors'+ : 'traffic'++ const filters = this.prepareFilters(+ dto.filters,+ dataType,+ eventType !== 'traffic',+ )++ const timeframe = await this.resolveTimeframe({+ pid,+ dataType: 'traffic',+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timezone: dto.timezone,+ allTimeEventTypes:+ eventType === 'traffic'+ ? ['pageview', 'custom_event', 'error']+ : [eventType],+ })++ const limit = dto.limit ?? DEFAULT_BREAKDOWN_LIMIT+ const offset = dto.offset ?? 0++ const sessions = await this.analyticsService.getSessionsList(+ filters.filtersQuery,+ {+ params: {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ },+ },+ timeframe.safeTimezone,+ limit,+ offset,+ filters.customEVFilterApplied,+ eventType,+ )++ return envelope(renameEntityList(sessions), {+ ...this.baseMeta(pid, timeframe, filters.appliedFilters),+ eventType,+ limit,+ offset,+ })+ }++ async getSessionDetails(+ pid: string,+ psid: string,+ timezone?: string,+ ): Promise<V2Envelope<Record<string, unknown>>> {+ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)++ const result = (await this.analyticsService.getSessionDetails(+ pid,+ psid,+ safeTimezone,+ )) as Record<string, unknown>++ const details = result?.details as Record<string, unknown> | undefined++ return envelope(+ {+ ...result,+ details: details ? renameEntityKeys(details) : details,+ },+ { pid, psid, timezone: safeTimezone },+ )+ }++ async getProfilesList(+ pid: string,+ dto: V2BaseQueryDto & {+ limit?: number+ offset?: number+ profile_type?: 'all' | 'anonymous' | 'identified'+ },+ ): Promise<V2Envelope<Record<string, unknown>[]>> {+ const dataType: V2DataType = 'traffic'+ const filters = this.prepareFilters(dto.filters, dataType)+ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timezone: dto.timezone,+ })++ const limit = dto.limit ?? DEFAULT_BREAKDOWN_LIMIT+ const offset = dto.offset ?? 0++ const profiles = await this.analyticsService.getProfilesList(+ pid,+ filters.filtersQuery,+ {+ params: {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ },+ },+ timeframe.safeTimezone,+ limit,+ offset,+ dto.profile_type || 'all',+ filters.customEVFilterApplied,+ )++ return envelope(renameEntityList(profiles), {+ ...this.baseMeta(pid, timeframe, filters.appliedFilters),+ profileType: dto.profile_type || 'all',+ limit,+ offset,+ })+ }++ async getProfileDetails(+ pid: string,+ profileId: string,+ timezone?: string,+ ): Promise<V2Envelope<Record<string, unknown>>> {+ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)++ const [details, topPages, activityCalendar] = await Promise.all([+ this.analyticsService.getProfileDetails(pid, profileId, safeTimezone),+ this.analyticsService.getProfileTopPages(pid, profileId),+ this.analyticsService.getProfileActivityCalendar(pid, profileId),+ ])++ return envelope(+ {+ ...renameEntityKeys((details ?? {}) as Record<string, unknown>),+ topPages,+ activityCalendar,+ },+ { pid, profileId, timezone: safeTimezone },+ )+ }++ async getProfileSessions(+ pid: string,+ profileId: string,+ dto: V2BaseQueryDto & { limit?: number; offset?: number },+ ): Promise<V2Envelope<Record<string, unknown>[]>> {+ const dataType: V2DataType = 'traffic'+ const filters = this.prepareFilters(dto.filters, dataType)+ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timezone: dto.timezone,+ })++ const limit = dto.limit ?? DEFAULT_BREAKDOWN_LIMIT+ const offset = dto.offset ?? 0++ const sessions = await this.analyticsService.getProfileSessionsList(+ pid,+ profileId,+ filters.filtersQuery,+ {+ params: {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ },+ },+ timeframe.safeTimezone,+ limit,+ offset,+ filters.customEVFilterApplied,+ )++ return envelope(renameEntityList(sessions), {+ ...this.baseMeta(pid, timeframe, filters.appliedFilters),+ profileId,+ limit,+ offset,+ })+ }++ async getTrafficCustomEventMetadata(+ pid: string,+ dto: V2BaseQueryDto & { event: string; timeBucket?: TimeBucketType },+ ): Promise<V2Envelope<unknown>> {+ const appliedFilters = parseV2Filters(dto.filters)+ const v1FiltersJson = toV1FiltersJson(appliedFilters, 'traffic')++ if (Boolean(dto.from) !== Boolean(dto.to)) {+ throw new BadRequestException(+ "The 'from' and 'to' parameters must be provided together",+ )+ }++ const hasCustomRange = Boolean(dto.from && dto.to)+ const from = hasCustomRange ? dto.from : undefined+ const to = hasCustomRange ? dto.to : undefined+ const period = hasCustomRange+ ? undefined+ : dto.period && dto.period !== 'custom'+ ? dto.period+ : V2_DEFAULT_PERIOD++ const { result } = await this.analyticsService.getCustomEventMetadata({+ pid,+ period,+ timeBucket:+ dto.timeBucket || getLowestPossibleTimeBucket(period, from, to),+ from,+ to,+ filters: v1FiltersJson,+ timezone: dto.timezone,+ event: dto.event,+ } as GetCustomEventMetadata)++ return envelope(result, {+ pid,+ event: dto.event,+ period: period ?? null,+ timezone: this.analyticsService.getSafeTimezone(dto.timezone),+ appliedFilters,+ })+ }++ async getTrafficPagePropertyMetadata(+ pid: string,+ dto: V2BaseQueryDto & { property: string; timeBucket?: TimeBucketType },+ ): Promise<V2Envelope<unknown>> {+ const appliedFilters = parseV2Filters(dto.filters)+ const v1FiltersJson = toV1FiltersJson(appliedFilters, 'traffic')++ if (Boolean(dto.from) !== Boolean(dto.to)) {+ throw new BadRequestException(+ "The 'from' and 'to' parameters must be provided together",+ )+ }++ const hasCustomRange = Boolean(dto.from && dto.to)+ const from = hasCustomRange ? dto.from : undefined+ const to = hasCustomRange ? dto.to : undefined+ const period = hasCustomRange+ ? undefined+ : dto.period && dto.period !== 'custom'+ ? dto.period+ : V2_DEFAULT_PERIOD++ const { result } = await this.analyticsService.getPagePropertyMeta({+ pid,+ period,+ timeBucket:+ dto.timeBucket || getLowestPossibleTimeBucket(period, from, to),+ from,+ to,+ filters: v1FiltersJson,+ timezone: dto.timezone,+ property: dto.property,+ } as GetPagePropertyMetaDto)++ return envelope(result, {+ pid,+ property: dto.property,+ period: period ?? null,+ timezone: this.analyticsService.getSafeTimezone(dto.timezone),+ appliedFilters,+ })+ }++ async getTrafficCustomEventsTimeseries(+ pid: string,+ dto: V2BaseQueryDto & { events: string; timeBucket?: TimeBucketType },+ ): Promise<V2Envelope<TimeseriesRow[]>> {+ const dataType: V2DataType = 'traffic'++ let events: string[]+ try {+ const parsed = JSON.parse(dto.events)+ events = Array.isArray(parsed) ? parsed.map(String) : []+ } catch {+ events = dto.events+ .split(',')+ .map((event) => event.trim())+ .filter(Boolean)+ }++ // A '__proto__' series key would mutate the response object's prototype+ // instead of adding a series+ events = events.filter((event) => event && event !== '__proto__')++ if (events.length === 0) {+ throw new UnprocessableEntityException(+ 'At least one custom event name has to be provided',+ )+ }++ const filters = this.prepareFilters(dto.filters, dataType)+ const timeframe = await this.resolveTimeframe({+ pid,+ dataType,+ period: dto.period,+ from: dto.from,+ to: dto.to,+ timeBucket: dto.timeBucket,+ timezone: dto.timezone,+ allTimeEventTypes: ['custom_event'],+ })++ const result = (await this.analyticsService.groupCustomEVByTimeBucket(+ timeframe.timeBucket,+ timeframe.groupFrom,+ timeframe.groupTo,+ filters.filtersQuery,+ {+ params: {+ pid,+ groupFrom: timeframe.groupFromUTC,+ groupTo: timeframe.groupToUTC,+ ...filters.filtersParams,+ },+ },+ timeframe.safeTimezone,+ events,+ )) as { chart: { x: string[]; events: Record<string, number[]> } }++ const series: Record<string, (number | null)[] | undefined> = {}++ for (const event of events) {+ series[event] = result.chart.events?.[event] ?? []+ }++ return envelope(+ zipTimeseries(result.chart.x, series, timeframe.safeTimezone),+ {+ ...this.baseMeta(pid, timeframe, filters.appliedFilters),+ timeBucket: timeframe.timeBucket,+ allowedTimeBuckets: timeframe.allowedTimeBuckets,+ events,+ },+ )+ }++ async getFunnel(+ pid: string,+ dto: V2BaseQueryDto & { steps?: string; funnelId?: string },+ ): Promise<V2Envelope<unknown>> {+ const steps = await this.resolveFunnelSteps(pid, dto)++ const { params, filters, timeframe } = await this.resolveFunnelContext(+ pid,+ dto,+ )++ let funnel: IFunnel[] = []+ let totalPageviews = 0+ let timeToConvert: unknown+ let stepDetails: Record<string, Record<number, Record<string, number>>> = {+ countries: {},+ devices: {},+ browsers: {},+ sources: {},+ campaigns: {},+ pages: {},+ profileTypes: {},+ }++ await Promise.all([+ (async () => {+ funnel = await this.analyticsService.getFunnel(+ steps,+ params,+ filters.filtersQuery,+ )+ })(),+ (async () => {+ totalPageviews = await this.analyticsService.getTotalPageviews(+ pid,+ params.groupFrom as string,+ params.groupTo as string,+ filters.filtersQuery,+ filters.filtersParams,+ )+ })(),+ (async () => {+ try {+ stepDetails = await this.analyticsService.getFunnelStepDetails(+ steps,+ params,+ filters.filtersQuery,+ )+ } catch (reason) {+ // Step details are best-effort (v1 parity); dev-only logging as+ // the raw error may embed funnel query params+ this.logger.log(reason, 'AnalyticsV2Service -> getFunnelStepDetails')+ }+ })(),+ (async () => {+ timeToConvert = await this.analyticsService.getFunnelTimeToConvert(+ steps,+ params,+ filters.filtersQuery,+ )+ })(),+ ])++ for (let i = 0; i < funnel.length; i++) {+ funnel[i].breakdowns = {+ countries: stepDetails.countries[i + 1] || {},+ devices: stepDetails.devices[i + 1] || {},+ browsers: stepDetails.browsers[i + 1] || {},+ sources: stepDetails.sources[i + 1] || {},+ campaigns: stepDetails.campaigns[i + 1] || {},+ pages: stepDetails.pages[i + 1] || {},+ profileTypes: stepDetails.profileTypes[i + 1] || {},+ }+ }++ return envelope(+ { steps: funnel, totalPageviews, timeToConvert },+ this.baseMeta(pid, timeframe, filters.appliedFilters),+ )+ }++ async getFunnelSessions(+ pid: string,+ dto: V2BaseQueryDto & {+ steps?: string+ funnelId?: string+ step: number+ dropoff?: boolean+ limit?: number+ offset?: number+ },+ ): Promise<V2Envelope<Record<string, unknown>[]>> {+ const steps = await this.resolveFunnelSteps(pid, dto)++ if (dto.step < 1 || dto.step > steps.length) {+ throw new BadRequestException(+ 'Step must be between 1 and the number of funnel steps',+ )+ }++ const { params, filters, timeframe } = await this.resolveFunnelContext(+ pid,+ dto,+ )++ const limit = dto.limit ?? DEFAULT_BREAKDOWN_LIMIT+ const offset = dto.offset ?? 0++ const sessions = await this.analyticsService.getFunnelSessionsList(+ steps,+ params,+ timeframe.safeTimezone,+ dto.step,+ limit,+ offset,+ filters.filtersQuery,+ Boolean(dto.dropoff),+ )++ return envelope(renameEntityList(sessions), {+ ...this.baseMeta(pid, timeframe, filters.appliedFilters),+ step: dto.step,+ dropoff: Boolean(dto.dropoff),+ limit,+ offset,+ })+ }++ private async resolveFunnelSteps(+ pid: string,+ dto: { steps?: string; funnelId?: string },+ ): Promise<string[]> {+ if (dto.steps && dto.funnelId) {+ throw new BadRequestException(+ "The 'steps' and 'funnelId' parameters are mutually exclusive",+ )+ }++ return this.analyticsService.getPagesArray(dto.steps, dto.funnelId, pid)+ }++ /**+ * Funnel time bounds mirror v1 exactly: no time bucket, timezone-shifted+ * bounds as ClickHouse params, and a period=all diff based on the max of+ * pageview / custom_event first-seen.+ */+ private async resolveFunnelContext(+ pid: string,+ dto: V2BaseQueryDto,+ ): Promise<{+ params: Record<string, unknown>+ filters: PreparedFilters+ timeframe: ResolvedTimeframe+ }> {+ const filters = this.prepareFilters(dto.filters, 'traffic')+ const safeTimezone = this.analyticsService.getSafeTimezone(dto.timezone)++ if (Boolean(dto.from) !== Boolean(dto.to)) {+ throw new BadRequestException(+ "The 'from' and 'to' parameters must be provided together",+ )+ }++ const hasCustomRange = Boolean(dto.from && dto.to)+ const period = hasCustomRange+ ? null+ : dto.period && dto.period !== 'custom'+ ? dto.period+ : V2_DEFAULT_PERIOD++ let diff: number | undefined++ if (period === 'all') {+ const [pageviewRes, customEventRes] = await Promise.all([+ this.analyticsService.calculateTimeBucketForAllTime(pid, 'pageview'),+ this.analyticsService.calculateTimeBucketForAllTime(+ pid,+ 'custom_event',+ ),+ ])++ diff = Math.max(pageviewRes.diff, customEventRes.diff)+ }++ const { groupFrom, groupTo, groupFromUTC, groupToUTC } =+ this.analyticsService.getGroupFromTo(+ hasCustomRange ? dto.from : undefined,+ hasCustomRange ? dto.to : undefined,+ null,+ period ?? undefined,+ safeTimezone,+ diff,+ )++ return {+ params: {+ pid,+ groupFrom,+ groupTo,+ ...filters.filtersParams,+ },+ filters,+ timeframe: {+ period,+ timeBucket: null,+ allowedTimeBuckets: null,+ safeTimezone,+ groupFrom,+ groupTo,+ groupFromUTC,+ groupToUTC,+ },+ }+ }++ async getLiveVisitors(+ pid: string,+ ): Promise<V2Envelope<{ count: number; visitors: unknown[] }>> {+ const since = dayjs+ .utc()+ .subtract(ONLINE_VISITORS_WINDOW_MINUTES, 'minute')+ .format('YYYY-MM-DD HH:mm:ss')++ const query = `+ SELECT+ dv,+ br,+ os,+ cc,+ psidCasted AS psid+ FROM (+ SELECT+ any(dv) AS dv,+ any(br) AS br,+ any(os) AS os,+ any(cc) AS cc,+ toString(psid) AS psidCasted+ FROM events+ WHERE+ pid = {pid:FixedString(12)}+ AND type IN ('pageview', 'custom_event')+ AND created >= {since:DateTime}+ AND psid IS NOT NULL+ AND psid != 0+ GROUP BY psid+ )+ `++ const [{ data }, count] = await Promise.all([+ clickhouse+ .query({ query, query_params: { pid, since } })+ .then((resultSet) => resultSet.json<Record<string, unknown>>()),+ this.analyticsService.getOnlineUserCount(pid),+ ])++ return envelope(+ { count, visitors: renameEntityList(data) },+ { pid, windowMinutes: ONLINE_VISITORS_WINDOW_MINUTES },+ )+ }++ getDimensions(type: V2DataType): V2Envelope<{+ dimensions: Record<string, unknown>[]+ metrics: Record<string, unknown>[]+ }> {+ const dimensions = listDimensions(type).map((dimension) => ({+ name: dimension.api,+ description: dimension.description,+ filterOnly: Boolean(dimension.filterOnly),+ extraFields: (dimension.extraFields ?? []).map((field) => field.api),+ }))++ const metrics = listMetrics(type).map((metric) => ({+ name: metric.api,+ description: metric.description,+ format: metric.format ?? 'integer',+ default: Boolean(metric.isDefault),+ }))++ return envelope({ dimensions, metrics }, { type })+ }++ async getDimensionValues(+ pid: string,+ dimensionApi: string,+ type: 'traffic' | 'errors',+ ): Promise<V2Envelope<unknown[]>> {+ const dimension = findDimension(+ dimensionApi,+ type === 'errors' ? 'errors' : 'traffic',+ )++ if (!dimension) {+ throw new UnprocessableEntityException(+ `Unknown ${type} dimension '${dimensionApi}'`,+ )+ }++ // Browser / OS versions return { name, version } pairs+ if (dimension.column === 'brv' || dimension.column === 'osv') {+ const values = await this.analyticsService.getVersionFilters(+ pid,+ type,+ dimension.column === 'brv' ? 'br' : 'os',+ )++ return envelope(values, { pid, dimension: dimensionApi, type })+ }++ // Entry/exit page values come from the session-scoped virtual-column+ // path in getFilters; getErrorsFilters cannot resolve them+ const values =+ type === 'errors' && !dimension.virtual+ ? await this.analyticsService.getErrorsFilters(pid, dimension.column)+ : await this.analyticsService.getFilters(pid, dimension.column)++ return envelope(values, { pid, dimension: dimensionApi, type })+ }++ /** Validate a metric name exists for the data type (helper for controllers) */+ validateMetric(api: string, dataType: V2DataType): V2MetricDef {+ return getMetric(api, dataType)+ }+}diff --git a/backend/apps/community/src/analytics/v2/controllers/captcha-v2.controller.ts b/backend/apps/community/src/analytics/v2/controllers/captcha-v2.controller.tsnew file mode 100644index 000000000..b2e0c313b--- /dev/null+++ b/backend/apps/community/src/analytics/v2/controllers/captcha-v2.controller.ts@@ -0,0 +1,125 @@+import {+ Controller,+ Get,+ Headers,+ Param,+ Query,+ UseGuards,+ UseInterceptors,+ UsePipes,+ ValidationPipe,+} from '@nestjs/common'+import {+ ApiBearerAuth,+ ApiOperation,+ ApiSecurity,+ ApiTags,+} from '@nestjs/swagger'++import { Auth } from '../../../auth/decorators'+import { CurrentUserId } from '../../../auth/decorators/current-user-id.decorator'+import { OptionalJwtAccessTokenGuard } from '../../../auth/guards'+import { AuthenticationGuard } from '../../../auth/guards/authentication.guard'+import { AppLoggerService } from '../../../logger/logger.service'+import { AnalyticsReadGuard } from '../../protection/analytics-read.guard'+import { CacheableAnalytics } from '../../protection/cacheable-analytics.decorator'+import { PublicProjectCacheInterceptor } from '../../protection/public-project-cache.interceptor'+import { AnalyticsV2Service } from '../analytics-v2.service'+import {+ V2BreakdownDto,+ V2ProjectParamsDto,+ V2SummaryDto,+ V2TimeseriesDto,+} from '../dto/v2-base.dto'++@ApiTags('Analytics v2')+@ApiBearerAuth()+@ApiSecurity('apiKey')+@UseGuards(OptionalJwtAccessTokenGuard, AuthenticationGuard, AnalyticsReadGuard)+@UseInterceptors(PublicProjectCacheInterceptor)+@UsePipes(new ValidationPipe({ transform: true }))+@Controller('v2/projects/:pid/captcha')+export class CaptchaV2Controller {+ constructor(+ private readonly analyticsV2Service: AnalyticsV2Service,+ private readonly logger: AppLoggerService,+ ) {}++ @Get('summary')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Captcha summary',+ description:+ 'Captcha counters, pass rate, solve-time quantiles, and difficulty/solve-time distributions for the selected period, plus the previous period for comparison.',+ })+ async getSummary(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2SummaryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(`pid: ${pid}`, 'GET /v2/projects/:pid/captcha/summary')++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getCaptchaSummary(pid, query)+ }++ @Get('timeseries')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Captcha timeseries',+ description:+ 'Captcha counters (generated, passed, failed, validation_failed, replayed) grouped by time bucket.',+ })+ async getTimeseries(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2TimeseriesDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(`pid: ${pid}`, 'GET /v2/projects/:pid/captcha/timeseries')++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getCaptchaTimeseries(pid, query)+ }++ @Get('breakdown')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Captcha breakdown',+ description:+ 'Captcha events grouped by a single dimension (country, browser, os, device, captcha_event, captcha_difficulty, captcha_reason, solve_time).',+ })+ async getBreakdown(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2BreakdownDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}, dimension: ${query.dimension}`,+ 'GET /v2/projects/:pid/captcha/breakdown',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getBreakdown(pid, query, 'captcha')+ }+}diff --git a/backend/apps/community/src/analytics/v2/controllers/errors-v2.controller.ts b/backend/apps/community/src/analytics/v2/controllers/errors-v2.controller.tsnew file mode 100644index 000000000..926c498ec--- /dev/null+++ b/backend/apps/community/src/analytics/v2/controllers/errors-v2.controller.ts@@ -0,0 +1,209 @@+import {+ Controller,+ Get,+ Headers,+ Param,+ Query,+ UseGuards,+ UseInterceptors,+ UsePipes,+ ValidationPipe,+} from '@nestjs/common'+import {+ ApiBearerAuth,+ ApiOperation,+ ApiSecurity,+ ApiTags,+} from '@nestjs/swagger'++import { Auth } from '../../../auth/decorators'+import { CurrentUserId } from '../../../auth/decorators/current-user-id.decorator'+import { OptionalJwtAccessTokenGuard } from '../../../auth/guards'+import { AuthenticationGuard } from '../../../auth/guards/authentication.guard'+import { AppLoggerService } from '../../../logger/logger.service'+import { AnalyticsReadGuard } from '../../protection/analytics-read.guard'+import { CacheableAnalytics } from '../../protection/cacheable-analytics.decorator'+import { PublicProjectCacheInterceptor } from '../../protection/public-project-cache.interceptor'+import { AnalyticsV2Service } from '../analytics-v2.service'+import {+ V2ErrorDetailQueryDto,+ V2ErrorParamsDto,+ V2ErrorSessionsQueryDto,+ V2ErrorsQueryDto,+} from '../dto/entities.dto'+import {+ V2BreakdownDto,+ V2ProjectParamsDto,+ V2TimeseriesDto,+} from '../dto/v2-base.dto'++// NOTE: static routes (overview, timeseries, breakdown) MUST be declared+// before the :eid routes β NestJS matches routes in declaration order.+@ApiTags('Analytics v2')+@ApiBearerAuth()+@ApiSecurity('apiKey')+@UseGuards(OptionalJwtAccessTokenGuard, AuthenticationGuard, AnalyticsReadGuard)+@UseInterceptors(PublicProjectCacheInterceptor)+@UsePipes(new ValidationPipe({ transform: true }))+@Controller('v2/projects/:pid/errors')+export class ErrorsV2Controller {+ constructor(+ private readonly analyticsV2Service: AnalyticsV2Service,+ private readonly logger: AppLoggerService,+ ) {}++ @Get()+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Error groups',+ description:+ 'Paginated list of error groups (grouped by error ID) with occurrence counts, affected users and status.',+ })+ async getErrors(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2ErrorsQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(`pid: ${pid}`, 'GET /v2/projects/:pid/errors')++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getErrorsList(pid, query)+ }++ @Get('overview')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Errors overview',+ description:+ 'Aggregated error statistics: occurrences, affected users and sessions for the selected period.',+ })+ async getOverview(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2ErrorsQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(`pid: ${pid}`, 'GET /v2/projects/:pid/errors/overview')++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getErrorsOverview(pid, query)+ }++ @Get('timeseries')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Errors timeseries',+ description: 'Error occurrences and affected users grouped by time bucket.',+ })+ async getTimeseries(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2TimeseriesDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(`pid: ${pid}`, 'GET /v2/projects/:pid/errors/timeseries')++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getErrorsTimeseries(pid, query)+ }++ @Get('breakdown')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Errors breakdown',+ description:+ 'Error occurrences grouped by a single dimension (page, browser, os, country, ...).',+ })+ async getBreakdown(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2BreakdownDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}, dimension: ${query.dimension}`,+ 'GET /v2/projects/:pid/errors/breakdown',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getBreakdown(pid, query, 'errors')+ }++ @Get(':eid')+ @Auth(true, true)+ @ApiOperation({+ summary: 'Error details',+ description:+ 'Details for a single error group: metadata, occurrence chart and affected user counts.',+ })+ async getErrorDetails(+ @Param() { pid, eid }: V2ErrorParamsDto,+ @Query() query: V2ErrorDetailQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}, eid: ${eid}`,+ 'GET /v2/projects/:pid/errors/:eid',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getErrorDetails(pid, eid, query)+ }++ @Get(':eid/sessions')+ @Auth(true, true)+ @ApiOperation({+ summary: 'Error sessions',+ description: 'Paginated sessions affected by a specific error group.',+ })+ async getErrorSessions(+ @Param() { pid, eid }: V2ErrorParamsDto,+ @Query() query: V2ErrorSessionsQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}, eid: ${eid}`,+ 'GET /v2/projects/:pid/errors/:eid/sessions',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getErrorSessions(pid, eid, query)+ }+}diff --git a/backend/apps/community/src/analytics/v2/controllers/performance-v2.controller.ts b/backend/apps/community/src/analytics/v2/controllers/performance-v2.controller.tsnew file mode 100644index 000000000..664f8d91e--- /dev/null+++ b/backend/apps/community/src/analytics/v2/controllers/performance-v2.controller.ts@@ -0,0 +1,134 @@+import {+ Controller,+ Get,+ Headers,+ Param,+ Query,+ UseGuards,+ UseInterceptors,+ UsePipes,+ ValidationPipe,+} from '@nestjs/common'+import {+ ApiBearerAuth,+ ApiOperation,+ ApiSecurity,+ ApiTags,+} from '@nestjs/swagger'++import { Auth } from '../../../auth/decorators'+import { CurrentUserId } from '../../../auth/decorators/current-user-id.decorator'+import { OptionalJwtAccessTokenGuard } from '../../../auth/guards'+import { AuthenticationGuard } from '../../../auth/guards/authentication.guard'+import { AppLoggerService } from '../../../logger/logger.service'+import { PerfMeasure } from '../../interfaces'+import { AnalyticsReadGuard } from '../../protection/analytics-read.guard'+import { CacheableAnalytics } from '../../protection/cacheable-analytics.decorator'+import { PublicProjectCacheInterceptor } from '../../protection/public-project-cache.interceptor'+import { AnalyticsV2Service } from '../analytics-v2.service'+import {+ V2PerfBreakdownDto,+ V2PerfSummaryDto,+ V2PerfTimeseriesDto,+} from '../dto/performance.dto'+import { V2ProjectParamsDto } from '../dto/v2-base.dto'++@ApiTags('Analytics v2')+@ApiBearerAuth()+@ApiSecurity('apiKey')+@UseGuards(OptionalJwtAccessTokenGuard, AuthenticationGuard, AnalyticsReadGuard)+@UseInterceptors(PublicProjectCacheInterceptor)+@UsePipes(new ValidationPipe({ transform: true }))+@Controller('v2/projects/:pid/performance')+export class PerformanceV2Controller {+ constructor(+ private readonly analyticsV2Service: AnalyticsV2Service,+ private readonly logger: AppLoggerService,+ ) {}++ @Get('summary')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Performance summary',+ description:+ 'Aggregated frontend/network/backend timings for the selected period, the previous period, and the change between them. Values are in seconds.',+ })+ async getSummary(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2PerfSummaryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(`pid: ${pid}`, 'GET /v2/projects/:pid/performance/summary')++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getPerformanceSummary(pid, query)+ }++ @Get('timeseries')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Performance timeseries',+ description:+ 'Performance timings grouped by time bucket. With measure=quantiles, returns p50/p75/p95 of the total load time instead of individual timings. Values are in seconds.',+ })+ async getTimeseries(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2PerfTimeseriesDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}, measure: ${query.measure}`,+ 'GET /v2/projects/:pid/performance/timeseries',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getPerformanceTimeseries(pid, query)+ }++ @Get('breakdown')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Performance breakdown',+ description:+ 'Performance timings grouped by a single dimension (country, page, browser, ...), paginated and sortable. Values are in seconds.',+ })+ async getBreakdown(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2PerfBreakdownDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}, dimension: ${query.dimension}, measure: ${query.measure}`,+ 'GET /v2/projects/:pid/performance/breakdown',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getBreakdown(+ pid,+ query,+ 'performance',+ (query.measure || 'median') as PerfMeasure,+ )+ }+}diff --git a/backend/apps/community/src/analytics/v2/controllers/profiles-v2.controller.ts b/backend/apps/community/src/analytics/v2/controllers/profiles-v2.controller.tsnew file mode 100644index 000000000..7b4e29f96--- /dev/null+++ b/backend/apps/community/src/analytics/v2/controllers/profiles-v2.controller.ts@@ -0,0 +1,129 @@+import {+ Controller,+ Get,+ Headers,+ Param,+ Query,+ UseGuards,+ UseInterceptors,+ UsePipes,+ ValidationPipe,+} from '@nestjs/common'+import {+ ApiBearerAuth,+ ApiOperation,+ ApiSecurity,+ ApiTags,+} from '@nestjs/swagger'++import { Auth } from '../../../auth/decorators'+import { CurrentUserId } from '../../../auth/decorators/current-user-id.decorator'+import { OptionalJwtAccessTokenGuard } from '../../../auth/guards'+import { AuthenticationGuard } from '../../../auth/guards/authentication.guard'+import { AppLoggerService } from '../../../logger/logger.service'+import { AnalyticsReadGuard } from '../../protection/analytics-read.guard'+import { CacheableAnalytics } from '../../protection/cacheable-analytics.decorator'+import { PublicProjectCacheInterceptor } from '../../protection/public-project-cache.interceptor'+import { AnalyticsV2Service } from '../analytics-v2.service'+import {+ V2ProfileParamsDto,+ V2ProfilesQueryDto,+ V2TimezoneQueryDto,+} from '../dto/entities.dto'+import { V2ListQueryDto, V2ProjectParamsDto } from '../dto/v2-base.dto'++@ApiTags('Analytics v2')+@ApiBearerAuth()+@ApiSecurity('apiKey')+@UseGuards(OptionalJwtAccessTokenGuard, AuthenticationGuard, AnalyticsReadGuard)+@UseInterceptors(PublicProjectCacheInterceptor)+@UsePipes(new ValidationPipe({ transform: true }))+@Controller('v2/projects/:pid/profiles')+export class ProfilesV2Controller {+ constructor(+ private readonly analyticsV2Service: AnalyticsV2Service,+ private readonly logger: AppLoggerService,+ ) {}++ @Get()+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Profiles',+ description:+ 'Paginated list of user profiles (anonymous and identified visitors).',+ })+ async getProfiles(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2ProfilesQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(`pid: ${pid}`, 'GET /v2/projects/:pid/profiles')++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getProfilesList(pid, query)+ }++ @Get(':profileId')+ @Auth(true, true)+ @ApiOperation({+ summary: 'Profile details',+ description:+ 'Details for a single profile: attributes, top pages and activity calendar.',+ })+ async getProfile(+ @Param() { pid, profileId }: V2ProfileParamsDto,+ @Query() query: V2TimezoneQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}, profileId: ${profileId}`,+ 'GET /v2/projects/:pid/profiles/:profileId',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getProfileDetails(+ pid,+ profileId,+ query.timezone,+ )+ }++ @Get(':profileId/sessions')+ @Auth(true, true)+ @ApiOperation({+ summary: 'Profile sessions',+ description: 'Paginated sessions recorded for a specific profile.',+ })+ async getProfileSessions(+ @Param() { pid, profileId }: V2ProfileParamsDto,+ @Query() query: V2ListQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}, profileId: ${profileId}`,+ 'GET /v2/projects/:pid/profiles/:profileId/sessions',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getProfileSessions(pid, profileId, query)+ }+}diff --git a/backend/apps/community/src/analytics/v2/controllers/project-v2.controller.ts b/backend/apps/community/src/analytics/v2/controllers/project-v2.controller.tsnew file mode 100644index 000000000..48df6c494--- /dev/null+++ b/backend/apps/community/src/analytics/v2/controllers/project-v2.controller.ts@@ -0,0 +1,180 @@+import {+ Controller,+ Get,+ Headers,+ Param,+ Query,+ UseGuards,+ UseInterceptors,+ UsePipes,+ ValidationPipe,+} from '@nestjs/common'+import {+ ApiBearerAuth,+ ApiOperation,+ ApiSecurity,+ ApiTags,+} from '@nestjs/swagger'++import { Auth } from '../../../auth/decorators'+import { CurrentUserId } from '../../../auth/decorators/current-user-id.decorator'+import { OptionalJwtAccessTokenGuard } from '../../../auth/guards'+import { AuthenticationGuard } from '../../../auth/guards/authentication.guard'+import { AppLoggerService } from '../../../logger/logger.service'+import { AnalyticsReadGuard } from '../../protection/analytics-read.guard'+import { CacheableAnalytics } from '../../protection/cacheable-analytics.decorator'+import { PublicProjectCacheInterceptor } from '../../protection/public-project-cache.interceptor'+import { AnalyticsV2Service } from '../analytics-v2.service'+import {+ V2DimensionsQueryDto,+ V2DimensionValuesParamsDto,+ V2DimensionValuesQueryDto,+ V2FunnelQueryDto,+ V2FunnelSessionsQueryDto,+} from '../dto/project.dto'+import { V2ProjectParamsDto } from '../dto/v2-base.dto'++@ApiTags('Analytics v2')+@ApiBearerAuth()+@ApiSecurity('apiKey')+@UseGuards(OptionalJwtAccessTokenGuard, AuthenticationGuard, AnalyticsReadGuard)+@UseInterceptors(PublicProjectCacheInterceptor)+@UsePipes(new ValidationPipe({ transform: true }))+@Controller('v2/projects/:pid')+export class ProjectV2Controller {+ constructor(+ private readonly analyticsV2Service: AnalyticsV2Service,+ private readonly logger: AppLoggerService,+ ) {}++ @Get('funnel')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Funnel analysis',+ description:+ 'Funnel step conversion for a saved funnel (funnelId) or an ad-hoc list of steps, with per-step breakdowns and time-to-convert stats.',+ })+ async getFunnel(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2FunnelQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(`pid: ${pid}`, 'GET /v2/projects/:pid/funnel')++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getFunnel(pid, query)+ }++ @Get('funnel/sessions')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Funnel sessions',+ description:+ 'Paginated sessions that reached (or dropped off at) a specific funnel step.',+ })+ async getFunnelSessions(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2FunnelSessionsQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}, step: ${query.step}`,+ 'GET /v2/projects/:pid/funnel/sessions',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getFunnelSessions(pid, query)+ }++ @Get('live-visitors')+ @Auth(true, true)+ @ApiOperation({+ summary: 'Live visitors',+ description:+ 'Current online visitor count and the list of active visitors (last 5 minutes).',+ })+ async getLiveVisitors(+ @Param() { pid }: V2ProjectParamsDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(`pid: ${pid}`, 'GET /v2/projects/:pid/live-visitors')++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getLiveVisitors(pid)+ }++ @Get('dimensions')+ @Auth(true, true)+ @ApiOperation({+ summary: 'Dimension & metric discovery',+ description:+ 'Machine-readable list of the dimensions and metrics available for a data type β useful for building custom dashboards.',+ })+ async getDimensions(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2DimensionsQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(`pid: ${pid}`, 'GET /v2/projects/:pid/dimensions')++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getDimensions(query.type || 'traffic')+ }++ @Get('dimensions/:dimension/values')+ @Auth(true, true)+ @ApiOperation({+ summary: 'Dimension values',+ description:+ 'Distinct recorded values for a dimension β useful for filter autocompletion. browser_version and os_version return { name, version } pairs.',+ })+ async getDimensionValues(+ @Param() { pid, dimension }: V2DimensionValuesParamsDto,+ @Query() query: V2DimensionValuesQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}, dimension: ${dimension}`,+ 'GET /v2/projects/:pid/dimensions/:dimension/values',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getDimensionValues(+ pid,+ dimension,+ query.type || 'traffic',+ )+ }+}diff --git a/backend/apps/community/src/analytics/v2/controllers/sessions-v2.controller.ts b/backend/apps/community/src/analytics/v2/controllers/sessions-v2.controller.tsnew file mode 100644index 000000000..9870e3744--- /dev/null+++ b/backend/apps/community/src/analytics/v2/controllers/sessions-v2.controller.ts@@ -0,0 +1,99 @@+import {+ Controller,+ Get,+ Headers,+ Param,+ Query,+ UseGuards,+ UseInterceptors,+ UsePipes,+ ValidationPipe,+} from '@nestjs/common'+import {+ ApiBearerAuth,+ ApiOperation,+ ApiSecurity,+ ApiTags,+} from '@nestjs/swagger'++import { Auth } from '../../../auth/decorators'+import { CurrentUserId } from '../../../auth/decorators/current-user-id.decorator'+import { OptionalJwtAccessTokenGuard } from '../../../auth/guards'+import { AuthenticationGuard } from '../../../auth/guards/authentication.guard'+import { AppLoggerService } from '../../../logger/logger.service'+import { AnalyticsReadGuard } from '../../protection/analytics-read.guard'+import { CacheableAnalytics } from '../../protection/cacheable-analytics.decorator'+import { PublicProjectCacheInterceptor } from '../../protection/public-project-cache.interceptor'+import { AnalyticsV2Service } from '../analytics-v2.service'+import {+ V2SessionParamsDto,+ V2SessionsQueryDto,+ V2TimezoneQueryDto,+} from '../dto/entities.dto'+import { V2ProjectParamsDto } from '../dto/v2-base.dto'++@ApiTags('Analytics v2')+@ApiBearerAuth()+@ApiSecurity('apiKey')+@UseGuards(OptionalJwtAccessTokenGuard, AuthenticationGuard, AnalyticsReadGuard)+@UseInterceptors(PublicProjectCacheInterceptor)+@UsePipes(new ValidationPipe({ transform: true }))+@Controller('v2/projects/:pid/sessions')+export class SessionsV2Controller {+ constructor(+ private readonly analyticsV2Service: AnalyticsV2Service,+ private readonly logger: AppLoggerService,+ ) {}++ @Get()+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Sessions',+ description:+ 'Paginated list of individual sessions for the selected period.',+ })+ async getSessions(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2SessionsQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(`pid: ${pid}`, 'GET /v2/projects/:pid/sessions')++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getSessionsList(pid, query)+ }++ @Get(':psid')+ @Auth(true, true)+ @ApiOperation({+ summary: 'Session details',+ description:+ 'Details for a single session: the page/event flow, session attributes and an activity chart.',+ })+ async getSession(+ @Param() { pid, psid }: V2SessionParamsDto,+ @Query() query: V2TimezoneQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}, psid: ${psid}`,+ 'GET /v2/projects/:pid/sessions/:psid',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getSessionDetails(pid, psid, query.timezone)+ }+}diff --git a/backend/apps/community/src/analytics/v2/controllers/traffic-v2.controller.ts b/backend/apps/community/src/analytics/v2/controllers/traffic-v2.controller.tsnew file mode 100644index 000000000..157186653--- /dev/null+++ b/backend/apps/community/src/analytics/v2/controllers/traffic-v2.controller.ts@@ -0,0 +1,324 @@+import {+ Controller,+ Get,+ Headers,+ Param,+ Query,+ UseGuards,+ UseInterceptors,+ UsePipes,+ ValidationPipe,+} from '@nestjs/common'+import {+ ApiBearerAuth,+ ApiOperation,+ ApiSecurity,+ ApiTags,+} from '@nestjs/swagger'++import { Auth } from '../../../auth/decorators'+import { CurrentUserId } from '../../../auth/decorators/current-user-id.decorator'+import { OptionalJwtAccessTokenGuard } from '../../../auth/guards'+import { AuthenticationGuard } from '../../../auth/guards/authentication.guard'+import { AppLoggerService } from '../../../logger/logger.service'+import { AnalyticsReadGuard } from '../../protection/analytics-read.guard'+import { CacheableAnalytics } from '../../protection/cacheable-analytics.decorator'+import { PublicProjectCacheInterceptor } from '../../protection/public-project-cache.interceptor'+import { AnalyticsV2Service } from '../analytics-v2.service'+import {+ V2CustomEventsTimeseriesDto,+ V2CustomMetricsQueryDto,+ V2EventMetadataQueryDto,+ V2PropertyMetadataQueryDto,+} from '../dto/project.dto'+import {+ V2BreakdownDto,+ V2ListQueryDto,+ V2ProjectParamsDto,+ V2SummaryDto,+ V2TimeseriesDto,+} from '../dto/v2-base.dto'++@ApiTags('Analytics v2')+@ApiBearerAuth()+@ApiSecurity('apiKey')+@UseGuards(OptionalJwtAccessTokenGuard, AuthenticationGuard, AnalyticsReadGuard)+@UseInterceptors(PublicProjectCacheInterceptor)+@UsePipes(new ValidationPipe({ transform: true }))+@Controller('v2/projects/:pid/traffic')+export class TrafficV2Controller {+ constructor(+ private readonly analyticsV2Service: AnalyticsV2Service,+ private readonly logger: AppLoggerService,+ ) {}++ @Get('summary')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Traffic summary',+ description:+ 'Key traffic metrics for the selected period, the previous period of the same length, and the change between them.',+ })+ async getSummary(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2SummaryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(`pid: ${pid}`, 'GET /v2/projects/:pid/traffic/summary')++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getTrafficSummary(pid, query)+ }++ @Get('timeseries')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Traffic timeseries',+ description:+ 'Selected traffic metrics grouped by time bucket, as rows of objects with ISO-8601 timestamps.',+ })+ async getTimeseries(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2TimeseriesDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(`pid: ${pid}`, 'GET /v2/projects/:pid/traffic/timeseries')++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getTrafficTimeseries(pid, query)+ }++ @Get('breakdown')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Traffic breakdown',+ description:+ 'Selected traffic metrics grouped by a single dimension (country, page, browser, ...), paginated and sortable.',+ })+ async getBreakdown(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2BreakdownDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}, dimension: ${query.dimension}`,+ 'GET /v2/projects/:pid/traffic/breakdown',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getBreakdown(pid, query, 'traffic')+ }++ @Get('custom-events')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Custom events',+ description:+ 'Counts of custom events recorded in the selected period, sorted by count.',+ })+ async getCustomEvents(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2ListQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}`,+ 'GET /v2/projects/:pid/traffic/custom-events',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getTrafficCustomEvents(pid, query)+ }++ @Get('custom-metrics')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Custom metrics',+ description:+ 'Sum / average of numeric custom event metadata values for the selected period and the previous one (project view custom metrics).',+ })+ async getCustomMetrics(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2CustomMetricsQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}`,+ 'GET /v2/projects/:pid/traffic/custom-metrics',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getTrafficCustomMetrics(pid, query)+ }++ @Get('custom-events/timeseries')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Custom events timeseries',+ description:+ 'Occurrence counts for the selected custom events grouped by time bucket.',+ })+ async getCustomEventsTimeseries(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2CustomEventsTimeseriesDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}, events: ${query.events}`,+ 'GET /v2/projects/:pid/traffic/custom-events/timeseries',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getTrafficCustomEventsTimeseries(pid, query)+ }++ @Get('custom-events/metadata')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Custom event metadata',+ description:+ 'Aggregated metadata key/value counts for a specific custom event.',+ })+ async getCustomEventMetadata(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2EventMetadataQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}, event: ${query.event}`,+ 'GET /v2/projects/:pid/traffic/custom-events/metadata',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getTrafficCustomEventMetadata(pid, query)+ }++ @Get('page-properties/metadata')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Page property values',+ description: 'Aggregated value counts for a specific page property (tag).',+ })+ async getPagePropertyMetadata(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2PropertyMetadataQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}, property: ${query.property}`,+ 'GET /v2/projects/:pid/traffic/page-properties/metadata',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getTrafficPagePropertyMetadata(pid, query)+ }++ @Get('page-properties')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'Page properties',+ description:+ 'Counts of pageview metadata (page property) keys recorded in the selected period.',+ })+ async getPageProperties(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2ListQueryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(+ `pid: ${pid}`,+ 'GET /v2/projects/:pid/traffic/page-properties',+ )++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getTrafficPageProperties(pid, query)+ }++ @Get('user-flow')+ @Auth(true, true)+ @CacheableAnalytics()+ @ApiOperation({+ summary: 'User flow',+ description:+ 'Page-to-page navigation flows (sankey nodes and links) for the selected period.',+ })+ async getUserFlow(+ @Param() { pid }: V2ProjectParamsDto,+ @Query() query: V2SummaryDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ this.logger.log(`pid: ${pid}`, 'GET /v2/projects/:pid/traffic/user-flow')++ await this.analyticsV2Service.assertReadAccess(+ pid,+ uid,+ headers['x-password'],+ )++ return this.analyticsV2Service.getTrafficUserFlow(pid, query)+ }+}diff --git a/backend/apps/community/src/analytics/v2/dto/entities.dto.ts b/backend/apps/community/src/analytics/v2/dto/entities.dto.tsnew file mode 100644index 000000000..4bbc83dd1--- /dev/null+++ b/backend/apps/community/src/analytics/v2/dto/entities.dto.ts@@ -0,0 +1,145 @@+import { ApiProperty } from '@nestjs/swagger'+import { Transform, Type } from 'class-transformer'+import {+ IsBoolean,+ IsEnum,+ IsIn,+ IsInt,+ IsNotEmpty,+ IsOptional,+ IsString,+ Max,+ Min,+} from 'class-validator'++import { TimeBucketType } from '../../dto/getData.dto'+import { V2BaseQueryDto, V2ProjectParamsDto } from './v2-base.dto'++export const V2_MAX_ENTITY_LIMIT = 150++class V2EntityListDto extends V2BaseQueryDto {+ @ApiProperty({+ required: false,+ default: 30,+ maximum: V2_MAX_ENTITY_LIMIT,+ description: 'Number of rows to return',+ })+ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(1)+ @Max(V2_MAX_ENTITY_LIMIT)+ limit?: number++ @ApiProperty({+ required: false,+ default: 0,+ description: 'Number of rows to skip (pagination)',+ })+ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(0)+ offset?: number+}++export class V2SessionsQueryDto extends V2EntityListDto {+ @ApiProperty({+ required: false,+ enum: ['traffic', 'performance', 'error'],+ default: 'traffic',+ description:+ 'Event scope for the returned sessions: sessions with traffic events (default), performance events, or errors in the selected range.',+ })+ @IsOptional()+ @IsIn(['traffic', 'performance', 'error'], {+ message: 'The provided event_type is incorrect',+ })+ event_type?: 'traffic' | 'performance' | 'error'+}++export class V2ProfilesQueryDto extends V2EntityListDto {+ @ApiProperty({+ required: false,+ enum: ['all', 'anonymous', 'identified'],+ default: 'all',+ description: 'Filter profiles by type',+ })+ @IsOptional()+ @IsIn(['all', 'anonymous', 'identified'], {+ message: 'The provided profile_type is incorrect',+ })+ profile_type?: 'all' | 'anonymous' | 'identified'+}++export class V2ErrorsQueryDto extends V2EntityListDto {+ @ApiProperty({+ required: false,+ default: false,+ description: 'Include resolved error groups in the list',+ })+ @IsOptional()+ @Transform(({ value }) => value === true || value === 'true')+ @IsBoolean()+ show_resolved?: boolean+}++export class V2ErrorDetailQueryDto extends V2BaseQueryDto {+ @ApiProperty({+ required: false,+ enum: TimeBucketType,+ description:+ 'Time bucket for the error occurrence chart. Defaults to the lowest bucket allowed for the requested range.',+ })+ @IsOptional()+ @IsEnum(TimeBucketType, { message: 'The provided timeBucket is incorrect' })+ timeBucket?: TimeBucketType+}++export class V2ErrorSessionsQueryDto extends V2BaseQueryDto {+ @ApiProperty({ required: false, default: 10, maximum: 50 })+ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(1)+ @Max(50)+ limit?: number++ @ApiProperty({ required: false, default: 0 })+ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(0)+ offset?: number+}++export class V2TimezoneQueryDto {+ @ApiProperty({+ required: false,+ description: 'IANA timezone used for displayed dates',+ })+ @IsOptional()+ @IsString()+ timezone?: string+}++export class V2SessionParamsDto extends V2ProjectParamsDto {+ @ApiProperty({ description: 'The session identifier' })+ @IsNotEmpty()+ @IsString()+ psid: string+}++export class V2ProfileParamsDto extends V2ProjectParamsDto {+ @ApiProperty({ description: 'The profile identifier' })+ @IsNotEmpty()+ @IsString()+ profileId: string+}++export class V2ErrorParamsDto extends V2ProjectParamsDto {+ @ApiProperty({ description: 'The error group identifier (eid)' })+ @IsNotEmpty()+ @IsString()+ eid: string+}diff --git a/backend/apps/community/src/analytics/v2/dto/performance.dto.ts b/backend/apps/community/src/analytics/v2/dto/performance.dto.tsnew file mode 100644index 000000000..acb7c5dd7--- /dev/null+++ b/backend/apps/community/src/analytics/v2/dto/performance.dto.ts@@ -0,0 +1,36 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsIn, IsOptional } from 'class-validator'++import { V2BreakdownDto, V2SummaryDto, V2TimeseriesDto } from './v2-base.dto'++const MEASURE_VALUES = ['median', 'average', 'p75', 'p95', 'quantiles']++const MeasureApiProperty = () =>+ ApiProperty({+ required: false,+ enum: MEASURE_VALUES,+ default: 'median',+ description:+ "Aggregate function applied to performance timings. 'quantiles' is only meaningful on the timeseries endpoint (returns p50/p75/p95 of the total load time); other endpoints treat it as 'median'.",+ })++export class V2PerfTimeseriesDto extends V2TimeseriesDto {+ @MeasureApiProperty()+ @IsOptional()+ @IsIn(MEASURE_VALUES, { message: 'The provided measure is incorrect' })+ measure?: string+}++export class V2PerfSummaryDto extends V2SummaryDto {+ @MeasureApiProperty()+ @IsOptional()+ @IsIn(MEASURE_VALUES, { message: 'The provided measure is incorrect' })+ measure?: string+}++export class V2PerfBreakdownDto extends V2BreakdownDto {+ @MeasureApiProperty()+ @IsOptional()+ @IsIn(MEASURE_VALUES, { message: 'The provided measure is incorrect' })+ measure?: string+}diff --git a/backend/apps/community/src/analytics/v2/dto/project.dto.ts b/backend/apps/community/src/analytics/v2/dto/project.dto.tsnew file mode 100644index 000000000..44dddc3a9--- /dev/null+++ b/backend/apps/community/src/analytics/v2/dto/project.dto.ts@@ -0,0 +1,158 @@+import { ApiProperty } from '@nestjs/swagger'+import { Transform, Type } from 'class-transformer'+import {+ IsBoolean,+ IsEnum,+ IsIn,+ IsInt,+ IsNotEmpty,+ IsOptional,+ IsString,+ Max,+ Min,+} from 'class-validator'++import { TimeBucketType } from '../../dto/getData.dto'+import { V2_MAX_ENTITY_LIMIT } from './entities.dto'+import { V2BaseQueryDto, V2ProjectParamsDto } from './v2-base.dto'++export class V2FunnelQueryDto extends V2BaseQueryDto {+ @ApiProperty({+ required: false,+ description:+ 'JSON array of page paths / custom event names defining the funnel steps. Mutually exclusive with funnelId.',+ example: '["/","/pricing","/signup"]',+ })+ @IsOptional()+ @IsString()+ steps?: string++ @ApiProperty({+ required: false,+ description: 'ID of a saved funnel. Mutually exclusive with steps.',+ })+ @IsOptional()+ @IsString()+ funnelId?: string+}++export class V2FunnelSessionsQueryDto extends V2FunnelQueryDto {+ @ApiProperty({+ description:+ 'Funnel step number the sessions must have reached (1-indexed)',+ example: 2,+ })+ @Type(() => Number)+ @IsInt()+ @Min(1)+ step: number++ @ApiProperty({+ required: false,+ default: false,+ description:+ 'Return sessions that reached the requested step but did not continue to the next one',+ })+ @IsOptional()+ @Transform(({ value }) => value === true || value === 'true')+ @IsBoolean()+ dropoff?: boolean++ @ApiProperty({ required: false, default: 30, maximum: V2_MAX_ENTITY_LIMIT })+ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(1)+ @Max(V2_MAX_ENTITY_LIMIT)+ limit?: number++ @ApiProperty({ required: false, default: 0 })+ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(0)+ offset?: number+}++export class V2DimensionsQueryDto {+ @ApiProperty({+ required: false,+ enum: ['traffic', 'performance', 'captcha', 'errors'],+ default: 'traffic',+ description: 'Data type to list dimensions and metrics for',+ })+ @IsOptional()+ @IsIn(['traffic', 'performance', 'captcha', 'errors'], {+ message: 'The provided type is incorrect',+ })+ type?: 'traffic' | 'performance' | 'captcha' | 'errors'+}++export class V2DimensionValuesParamsDto extends V2ProjectParamsDto {+ @ApiProperty({ description: "Dimension name, e.g. 'browser'" })+ @IsNotEmpty()+ @IsString()+ dimension: string+}++export class V2DimensionValuesQueryDto {+ @ApiProperty({+ required: false,+ enum: ['traffic', 'errors'],+ default: 'traffic',+ description: 'Data type to list dimension values for',+ })+ @IsOptional()+ @IsIn(['traffic', 'errors'], { message: 'The provided type is incorrect' })+ type?: 'traffic' | 'errors'+}++export class V2CustomMetricsQueryDto extends V2BaseQueryDto {+ @ApiProperty({+ description:+ 'JSON array of custom metric definitions (project view custom events)',+ })+ @IsNotEmpty()+ @IsString()+ metrics: string+}++export class V2EventMetadataQueryDto extends V2BaseQueryDto {+ @ApiProperty({ description: 'Custom event name to return metadata for' })+ @IsNotEmpty()+ @IsString()+ event: string++ @ApiProperty({ required: false, enum: TimeBucketType })+ @IsOptional()+ @IsEnum(TimeBucketType, { message: 'The provided timeBucket is incorrect' })+ timeBucket?: TimeBucketType+}++export class V2PropertyMetadataQueryDto extends V2BaseQueryDto {+ @ApiProperty({ description: 'Page property (tag) name to return values for' })+ @IsNotEmpty()+ @IsString()+ property: string++ @ApiProperty({ required: false, enum: TimeBucketType })+ @IsOptional()+ @IsEnum(TimeBucketType, { message: 'The provided timeBucket is incorrect' })+ timeBucket?: TimeBucketType+}++export class V2CustomEventsTimeseriesDto extends V2BaseQueryDto {+ @ApiProperty({+ description:+ 'Custom event names to chart: a comma-separated list or a JSON array',+ example: 'signup,purchase',+ })+ @IsNotEmpty()+ @IsString()+ events: string++ @ApiProperty({ required: false, enum: TimeBucketType })+ @IsOptional()+ @IsEnum(TimeBucketType, { message: 'The provided timeBucket is incorrect' })+ timeBucket?: TimeBucketType+}diff --git a/backend/apps/community/src/analytics/v2/dto/v2-base.dto.ts b/backend/apps/community/src/analytics/v2/dto/v2-base.dto.tsnew file mode 100644index 000000000..15e675fc1--- /dev/null+++ b/backend/apps/community/src/analytics/v2/dto/v2-base.dto.ts@@ -0,0 +1,197 @@+import { ApiProperty } from '@nestjs/swagger'+import { Type } from 'class-transformer'+import {+ IsEnum,+ IsInt,+ IsNotEmpty,+ IsOptional,+ IsString,+ Matches,+ Max,+ Min,+} from 'class-validator'++import { PID_REGEX } from '../../../common/constants'+import { DEFAULT_TIMEZONE } from '../../../user/entities/user.entity'+import { ValidatePeriod } from '../../decorators/validate-period.decorator'+import { ChartRenderMode, TimeBucketType } from '../../dto/getData.dto'++export const V2_DEFAULT_PERIOD = '7d'++export class V2ProjectParamsDto {+ @ApiProperty({+ example: 'aUn1quEid-3',+ description: 'The project ID',+ })+ @IsNotEmpty()+ @Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })+ pid: string+}++export class V2BaseQueryDto {+ @ApiProperty({+ required: false,+ description:+ "Predefined reporting period. One of: 1h, today, yesterday, 1d, 7d, 4w, 3M, 12M, 24M, all. Defaults to '7d'. Mutually exclusive with from/to.",+ example: '7d',+ })+ @IsOptional()+ @ValidatePeriod()+ period?: string++ @ApiProperty({+ required: false,+ description:+ 'Custom range start (ISO 8601 date or datetime). Must be used together with `to`.',+ example: '2026-06-01',+ })+ @IsOptional()+ @IsString()+ from?: string++ @ApiProperty({+ required: false,+ description:+ 'Custom range end (ISO 8601 date or datetime). Must be used together with `from`.',+ example: '2026-06-30',+ })+ @IsOptional()+ @IsString()+ to?: string++ @ApiProperty({+ required: false,+ description: 'IANA timezone used for bucketing and date boundaries',+ default: DEFAULT_TIMEZONE,+ example: 'Europe/Kyiv',+ })+ @IsOptional()+ @IsString()+ timezone?: string++ @ApiProperty({+ required: false,+ description:+ 'JSON array of filter objects: [{ "dimension": "country", "operator": "is" | "is_not" | "contains" | "contains_not", "value": "US" | ["US", "DE"] | null, "key": "<meta key, for event_metadata / page_property>" }]',+ example: '[{"dimension":"country","operator":"is","value":"US"}]',+ })+ @IsOptional()+ @IsString()+ filters?: string+}++export class V2TimeseriesDto extends V2BaseQueryDto {+ @ApiProperty({+ required: false,+ enum: TimeBucketType,+ description:+ 'Time bucket for grouping. Defaults to the lowest bucket allowed for the requested range.',+ })+ @IsOptional()+ @IsEnum(TimeBucketType, { message: 'The provided timeBucket is incorrect' })+ timeBucket?: TimeBucketType++ @ApiProperty({+ required: false,+ description:+ 'Comma-separated metric names to return. Defaults depend on the data type.',+ example: 'visitors,pageviews',+ })+ @IsOptional()+ @IsString()+ metrics?: string++ @ApiProperty({+ required: false,+ enum: ChartRenderMode,+ default: ChartRenderMode.PERIODICAL,+ description: 'Return periodical (per-bucket) or cumulative values',+ })+ @IsOptional()+ @IsEnum(ChartRenderMode, { message: 'The provided mode is incorrect' })+ mode?: ChartRenderMode+}++const V2_MAX_BREAKDOWN_LIMIT = 100++export class V2BreakdownDto extends V2BaseQueryDto {+ @ApiProperty({+ description: "Dimension to break down by, e.g. 'country', 'page'",+ example: 'country',+ })+ @IsNotEmpty()+ @IsString()+ dimension: string++ @ApiProperty({+ required: false,+ description:+ 'Comma-separated metric names to compute per dimension value. Defaults depend on the data type.',+ example: 'visitors,pageviews',+ })+ @IsOptional()+ @IsString()+ metrics?: string++ @ApiProperty({+ required: false,+ default: 30,+ maximum: V2_MAX_BREAKDOWN_LIMIT,+ description: 'Number of rows to return',+ })+ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(1)+ @Max(V2_MAX_BREAKDOWN_LIMIT)+ limit?: number++ @ApiProperty({+ required: false,+ default: 0,+ description: 'Number of rows to skip (pagination)',+ })+ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(0)+ offset?: number++ @ApiProperty({+ required: false,+ description:+ "Sorting as 'field:direction', where field is 'value' or a selected metric and direction is 'asc' or 'desc'. Defaults to the first selected metric, descending.",+ example: 'visitors:desc',+ })+ @IsOptional()+ @IsString()+ sort?: string+}++export class V2SummaryDto extends V2BaseQueryDto {}++export class V2ListQueryDto extends V2BaseQueryDto {+ @ApiProperty({+ required: false,+ default: 30,+ maximum: V2_MAX_BREAKDOWN_LIMIT,+ description: 'Number of rows to return',+ })+ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(1)+ @Max(V2_MAX_BREAKDOWN_LIMIT)+ limit?: number++ @ApiProperty({+ required: false,+ default: 0,+ description: 'Number of rows to skip (pagination)',+ })+ @IsOptional()+ @Type(() => Number)+ @IsInt()+ @Min(0)+ offset?: number+}diff --git a/backend/apps/community/src/analytics/v2/mappers/entity.mapper.ts b/backend/apps/community/src/analytics/v2/mappers/entity.mapper.tsnew file mode 100644index 000000000..39a85c290--- /dev/null+++ b/backend/apps/community/src/analytics/v2/mappers/entity.mapper.ts@@ -0,0 +1,51 @@+/**+ * Key renames applied to v1 entity payloads (sessions, profiles, session+ * details) so v2 responses use human-readable field names.+ */+const KEY_RENAMES: Record<string, string> = {+ cc: 'country',+ rg: 'region',+ rgc: 'region_code',+ ct: 'city',+ lc: 'locale',+ dv: 'device',+ br: 'browser',+ brv: 'browser_version',+ os: 'os',+ osv: 'os_version',+ ref: 'referrer',+ so: 'utm_source',+ me: 'utm_medium',+ ca: 'utm_campaign',+ te: 'utm_term',+ co: 'utm_content',+ isp: 'isp',+ og: 'organization',+ ut: 'user_type',+ ctp: 'connection_type',+ sdur: 'duration',+}++export const renameEntityKeys = <T extends Record<string, unknown>>(+ entity: T,+): Record<string, unknown> => {+ const result: Record<string, unknown> = {}++ for (const [key, value] of Object.entries(entity)) {+ result[KEY_RENAMES[key] ?? key] = value+ }++ return result+}++export const renameEntityList = (+ entities: unknown,+): Record<string, unknown>[] => {+ if (!Array.isArray(entities)) {+ return []+ }++ return entities.map((entity) =>+ renameEntityKeys(entity as Record<string, unknown>),+ )+}diff --git a/backend/apps/community/src/analytics/v2/mappers/envelope.ts b/backend/apps/community/src/analytics/v2/mappers/envelope.tsnew file mode 100644index 000000000..ca058667a--- /dev/null+++ b/backend/apps/community/src/analytics/v2/mappers/envelope.ts@@ -0,0 +1,9 @@+export interface V2Envelope<T> {+ data: T+ meta: Record<string, unknown>+}++export const envelope = <T>(+ data: T,+ meta: Record<string, unknown> = {},+): V2Envelope<T> => ({ data, meta })diff --git a/backend/apps/community/src/analytics/v2/mappers/summary.mapper.ts b/backend/apps/community/src/analytics/v2/mappers/summary.mapper.tsnew file mode 100644index 000000000..5f0ddef2f--- /dev/null+++ b/backend/apps/community/src/analytics/v2/mappers/summary.mapper.ts@@ -0,0 +1,67 @@+interface V1SummaryPeriod {+ all: number+ unique: number+ users: number+ bounceRate: number+ sdur: number | null+}++export interface V1TrafficSummary {+ current: V1SummaryPeriod+ previous: V1SummaryPeriod+ change: number+ uniqueChange: number+ usersChange: number+ bounceRateChange: number+ sdurChange: number | null+}++export interface TrafficSummaryPeriod {+ visitors: number+ pageviews: number+ users: number+ bounce_rate: number+ session_duration: number | null+}++export interface TrafficSummaryData {+ current: TrafficSummaryPeriod+ previous: TrafficSummaryPeriod+ change: TrafficSummaryPeriod+}++const toNumber = (value: unknown): number => Number(value) || 0++const toNullableNumber = (value: unknown): number | null => {+ if (value === null || typeof value === 'undefined') {+ return null+ }++ return Number(value) || 0+}++const mapPeriod = (period: V1SummaryPeriod): TrafficSummaryPeriod => ({+ visitors: toNumber(period.unique),+ pageviews: toNumber(period.all),+ users: toNumber(period.users),+ bounce_rate: toNumber(period.bounceRate),+ session_duration: toNullableNumber(period.sdur),+})++/**+ * Reshape a single project's v1 birdseye payload (getAnalyticsSummary) into+ * the v2 summary format with human-readable metric names.+ */+export const mapTrafficSummary = (+ v1Summary: V1TrafficSummary,+): TrafficSummaryData => ({+ current: mapPeriod(v1Summary.current),+ previous: mapPeriod(v1Summary.previous),+ change: {+ visitors: toNumber(v1Summary.uniqueChange),+ pageviews: toNumber(v1Summary.change),+ users: toNumber(v1Summary.usersChange),+ bounce_rate: toNumber(v1Summary.bounceRateChange),+ session_duration: toNullableNumber(v1Summary.sdurChange),+ },+})diff --git a/backend/apps/community/src/analytics/v2/mappers/timeseries.mapper.ts b/backend/apps/community/src/analytics/v2/mappers/timeseries.mapper.tsnew file mode 100644index 000000000..53494268a--- /dev/null+++ b/backend/apps/community/src/analytics/v2/mappers/timeseries.mapper.ts@@ -0,0 +1,75 @@+import dayjs from 'dayjs'+import utc from 'dayjs/plugin/utc'+import dayjsTimezone from 'dayjs/plugin/timezone'++import { DEFAULT_TIMEZONE } from '../../../user/entities/user.entity'++dayjs.extend(utc)+dayjs.extend(dayjsTimezone)++export type TimeseriesRow = { timestamp: string } & Record<+ string,+ string | number | null+>++/**+ * Convert a v1 timezone-shifted x-axis label (e.g. '2026-07-01',+ * '2026-07-01 13:00:00', '2026-07') into an ISO-8601 timestamp carrying the+ * requested timezone's UTC offset.+ */+export const toIsoTimestamp = (value: string, timezone: string): string => {+ const zone = timezone || DEFAULT_TIMEZONE++ return dayjs.tz(value, zone).format()+}++/**+ * Zip v1's columnar chart output ({ x: [...], seriesA: [...], seriesB: [...] })+ * into self-describing rows of objects β the v2 timeseries format.+ *+ * `series` maps v2 metric names to v1 arrays; missing/undefined series are+ * skipped. Array values falling outside the x range are ignored.+ */+export const zipTimeseries = (+ x: string[],+ series: Record<string, (number | null)[] | undefined>,+ timezone: string,+): TimeseriesRow[] => {+ const names = Object.keys(series).filter((name) =>+ Array.isArray(series[name]),+ )++ return x.map((label, index) => {+ const row: TimeseriesRow = { timestamp: toIsoTimestamp(label, timezone) }++ for (const name of names) {+ const value = series[name][index]+ row[name] = typeof value === 'undefined' ? null : value+ }++ return row+ })+}++/**+ * Per-bucket bounce rate (%) from v1's raw bounces + uniques arrays,+ * mirroring v1's calculateBounceRate (bounces / uniques * 100).+ */+export const computeBounceRateSeries = (+ bounces: number[] | undefined,+ uniques: number[] | undefined,+): number[] | undefined => {+ if (!Array.isArray(bounces) || !Array.isArray(uniques)) {+ return undefined+ }++ return bounces.map((bounceCount, index) => {+ const uniqueCount = Number(uniques[index]) || 0++ if (uniqueCount <= 0) {+ return 0+ }++ return Math.round((Number(bounceCount) / uniqueCount) * 100 * 100) / 100+ })+}diff --git a/backend/apps/community/src/analytics/v2/query/breakdown-query.builder.ts b/backend/apps/community/src/analytics/v2/query/breakdown-query.builder.tsnew file mode 100644index 000000000..1c17653ca--- /dev/null+++ b/backend/apps/community/src/analytics/v2/query/breakdown-query.builder.ts@@ -0,0 +1,112 @@+import { UnprocessableEntityException } from '@nestjs/common'++import { getCaptchaColumnExpression } from '../../analytics.service'+import {+ captchaExtraWhere,+ V2DataType,+ V2DimensionDef,+ V2MetricCtx,+ V2MetricDef,+} from '../registry'++export interface BreakdownSort {+ field: string+ direction: 'asc' | 'desc'+}++export interface BreakdownQueryOptions {+ dataType: V2DataType+ dimension: V2DimensionDef+ metrics: V2MetricDef[]+ /** 'FROM events WHERE ...' fragment, incl. filters and time range params */+ subQuery: string+ ctx: V2MetricCtx+ sort: BreakdownSort+}++export const parseSortParam = (+ sort: string | undefined,+ dimension: V2DimensionDef,+ metrics: V2MetricDef[],+): BreakdownSort => {+ if (!sort) {+ return { field: metrics[0].api, direction: 'desc' }+ }++ const [field, direction = 'desc'] = sort.split(':')++ if (direction !== 'asc' && direction !== 'desc') {+ throw new UnprocessableEntityException(+ `Invalid sort direction '${direction}'; use 'asc' or 'desc'`,+ )+ }++ const sortable = ['value', ...metrics.map((metric) => metric.api)]++ if (!sortable.includes(field)) {+ throw new UnprocessableEntityException(+ `Cannot sort '${dimension.api}' breakdown by '${field}'. Sortable fields: ${sortable.join(', ')}`,+ )+ }++ return { field, direction }+}++/**+ * Multi-metric generalization of v1's generateParamsQuery: one dimension,+ * N metric aggregates, ORDER BY + LIMIT/OFFSET pagination and a windowed+ * total. Expects `v2_limit` and `v2_offset` in the query params.+ */+export const buildBreakdownQuery = (opts: BreakdownQueryOptions): string => {+ const { dataType, dimension, metrics, subQuery, ctx, sort } = opts++ const dimensionSql =+ dataType === 'captcha'+ ? getCaptchaColumnExpression(dimension.column)+ : dimension.column++ const dimensionCols = [+ `${dimensionSql} AS value`,+ ...(dimension.extraFields ?? []).map(+ (field) => `${field.column} AS ${field.api}`,+ ),+ ]++ const metricCols = metrics.map((metric) => {+ const expr = metric.sqlExpr(ctx)++ if (!expr) {+ throw new UnprocessableEntityException(+ `The '${metric.api}' metric is not supported on breakdowns. Request it on the timeseries or summary endpoint instead`,+ )+ }++ return `${expr} AS ${metric.api}`+ })++ const groupBy = ['value', ...(dimension.extraFields ?? []).map((f) => f.api)]++ const whereParts: string[] = []++ if (dimension.excludeNull) {+ whereParts.push(`AND ${dimension.column} IS NOT NULL`)+ }++ if (dataType === 'captcha') {+ const guard = captchaExtraWhere(dimension)+ if (guard) {+ whereParts.push(guard)+ }+ }++ return `+ SELECT+ ${[...dimensionCols, ...metricCols].join(',\n ')},+ count() OVER () AS __total+ ${subQuery}+ ${whereParts.join(' ')}+ GROUP BY ${groupBy.join(', ')}+ ORDER BY ${sort.field} ${sort.direction}+ LIMIT {v2_limit:UInt32} OFFSET {v2_offset:UInt32}+ `+}diff --git a/backend/apps/community/src/analytics/v2/query/filters.translator.ts b/backend/apps/community/src/analytics/v2/query/filters.translator.tsnew file mode 100644index 000000000..daf09d212--- /dev/null+++ b/backend/apps/community/src/analytics/v2/query/filters.translator.ts@@ -0,0 +1,204 @@+import { UnprocessableEntityException } from '@nestjs/common'++import {+ findDimension,+ V2_KEYED_FILTER_DIMENSIONS,+ V2DataType,+} from '../registry'++const V2_FILTER_OPERATORS = [+ 'is',+ 'is_not',+ 'contains',+ 'contains_not',+] as const++type V2FilterOperator = (typeof V2_FILTER_OPERATORS)[number]++export interface V2Filter {+ dimension: string+ operator: V2FilterOperator+ value: string | null | (string | null)[]+ /** meta.key for event_metadata / page_property filters */+ key?: string+}++interface V1Filter {+ column: string+ filter: string | null | (string | null)[]+ isExclusive: boolean+ isContains: boolean+}++const parseFiltersJson = (filters: string): unknown => {+ try {+ return JSON.parse(filters)+ } catch {+ throw new UnprocessableEntityException(+ 'The provided filters are not a valid JSON array',+ )+ }+}++const resolveColumn = (+ filter: V2Filter,+ type: V2DataType,+ lenient: boolean,+): string | null => {+ const { dimension, key } = filter++ const keyedFamily = Object.hasOwn(V2_KEYED_FILTER_DIMENSIONS, dimension)+ ? V2_KEYED_FILTER_DIMENSIONS[dimension]+ : undefined++ if (keyedFamily) {+ if (!keyedFamily.types.includes(type)) {+ if (lenient) {+ return null+ }++ throw new UnprocessableEntityException(+ `The '${dimension}' filter is not supported for ${type} data`,+ )+ }++ // With a key: filter values of that meta key. Without: filter the+ // meta keys themselves.+ return key ? `${keyedFamily.v1Prefix}${key}` : keyedFamily.v1KeyColumn+ }++ const def = findDimension(dimension, type)++ if (!def) {+ if (lenient) {+ return null+ }++ throw new UnprocessableEntityException(+ `Unknown ${type} filter dimension '${dimension}'`,+ )+ }++ return def.column+}++/**+ * Parse and validate a v2 `filters` query param.+ * v2 filter shape: { dimension, operator: is|is_not|contains|contains_not, value, key? }+ */+export const parseV2Filters = (filters: string | undefined): V2Filter[] => {+ if (!filters || filters === '""') {+ return []+ }++ const parsed = parseFiltersJson(filters)++ if (!Array.isArray(parsed)) {+ throw new UnprocessableEntityException(+ 'The filters parameter must be a JSON array of filter objects',+ )+ }++ return parsed.map((raw, index) => {+ if (!raw || typeof raw !== 'object') {+ throw new UnprocessableEntityException(+ `Filter at index ${index} must be an object`,+ )+ }++ const { dimension, operator, value, key } = raw as Record<string, unknown>++ if (typeof dimension !== 'string' || !dimension) {+ throw new UnprocessableEntityException(+ `Filter at index ${index} is missing a 'dimension'`,+ )+ }++ if (!V2_FILTER_OPERATORS.includes(operator as V2FilterOperator)) {+ throw new UnprocessableEntityException(+ `Filter at index ${index} has an invalid operator. Supported operators: ${V2_FILTER_OPERATORS.join(', ')}`,+ )+ }++ const isValidValue = (v: unknown) => v === null || typeof v === 'string'++ if (Array.isArray(value)) {+ if (!value.every(isValidValue)) {+ throw new UnprocessableEntityException(+ `Filter at index ${index} has an invalid 'value'; array values must be strings or null`,+ )+ }+ } else if (!isValidValue(value)) {+ throw new UnprocessableEntityException(+ `Filter at index ${index} has an invalid 'value'; it must be a string, null or an array`,+ )+ }++ if (key !== undefined && (typeof key !== 'string' || !key)) {+ throw new UnprocessableEntityException(+ `Filter at index ${index} has an invalid 'key'; it must be a non-empty string`,+ )+ }++ if (+ key !== undefined &&+ !Object.hasOwn(V2_KEYED_FILTER_DIMENSIONS, dimension)+ ) {+ throw new UnprocessableEntityException(+ `Filter at index ${index} has a 'key', but the '${dimension}' dimension does not support keys. Keyed dimensions: ${Object.keys(V2_KEYED_FILTER_DIMENSIONS).join(', ')}`,+ )+ }++ const filter: V2Filter = {+ dimension,+ operator: operator as V2FilterOperator,+ value: value as V2Filter['value'],+ }++ if (typeof key === 'string' && key) {+ filter.key = key+ }++ return filter+ })+}++/**+ * Translate parsed v2 filters into the exact v1 filters JSON string consumed+ * by AnalyticsService.getFiltersQuery β all v1 special-case SQL (refn domain+ * expansion, entry/exit page psid subqueries, meta-array filters,+ * customEVFilterApplied detection) is inherited unchanged.+ */+export const toV1FiltersJson = (+ filters: V2Filter[],+ type: V2DataType,+ options: { lenient?: boolean } = {},+): string => {+ if (filters.length === 0) {+ return ''+ }++ const v1Filters: V1Filter[] = []++ for (const filter of filters) {+ const column = resolveColumn(filter, type, Boolean(options.lenient))++ // Lenient mode drops filters that don't apply to the data type instead+ // of rejecting the request (used when one endpoint queries several+ // data types with the same filter set)+ if (column === null) {+ continue+ }++ v1Filters.push({+ column,+ filter: filter.value,+ isExclusive:+ filter.operator === 'is_not' || filter.operator === 'contains_not',+ isContains:+ filter.operator === 'contains' || filter.operator === 'contains_not',+ })+ }++ return JSON.stringify(v1Filters)+}diff --git a/backend/apps/community/src/analytics/v2/registry/dimensions.ts b/backend/apps/community/src/analytics/v2/registry/dimensions.tsnew file mode 100644index 000000000..64d78ed77--- /dev/null+++ b/backend/apps/community/src/analytics/v2/registry/dimensions.ts@@ -0,0 +1,273 @@+import {+ CAPTCHA_EVENT_SQL,+ CAPTCHA_DIFFICULTY_SQL,+ CAPTCHA_REASON_SQL,+ CAPTCHA_SOLVE_MS_SQL,+} from '../../analytics.service'+import { V2DimensionDef } from './types'++const GEO_TYPES: V2DimensionDef['types'] = ['traffic', 'performance', 'errors']++export const V2_DIMENSIONS: V2DimensionDef[] = [+ {+ api: 'country',+ column: 'cc',+ types: ['traffic', 'performance', 'captcha', 'errors'],+ description: 'Country (ISO 3166-1 alpha-2 code)',+ },+ {+ api: 'region',+ column: 'rg',+ types: GEO_TYPES,+ excludeNull: true,+ extraFields: [+ { api: 'country', column: 'cc' },+ { api: 'region_code', column: 'rgc' },+ ],+ description: 'Region / subdivision',+ },+ {+ api: 'city',+ column: 'ct',+ types: GEO_TYPES,+ excludeNull: true,+ extraFields: [{ api: 'country', column: 'cc' }],+ description: 'City',+ },+ {+ api: 'page',+ column: 'pg',+ types: GEO_TYPES,+ description: 'Page path',+ },+ {+ api: 'host',+ column: 'host',+ types: GEO_TYPES,+ description: 'Hostname the event was recorded on',+ },+ {+ api: 'locale',+ column: 'lc',+ types: ['traffic', 'errors'],+ description: 'Browser locale (e.g. en-GB)',+ },+ {+ api: 'browser',+ column: 'br',+ types: ['traffic', 'performance', 'captcha', 'errors'],+ description: 'Browser name',+ },+ {+ api: 'browser_version',+ column: 'brv',+ types: GEO_TYPES,+ extraFields: [{ api: 'browser', column: 'br' }],+ description: 'Browser version',+ },+ {+ api: 'os',+ column: 'os',+ types: ['traffic', 'captcha', 'errors'],+ description: 'Operating system name',+ },+ {+ api: 'os_version',+ column: 'osv',+ types: ['traffic', 'errors'],+ extraFields: [{ api: 'os', column: 'os' }],+ description: 'Operating system version',+ },+ {+ api: 'device',+ column: 'dv',+ types: ['traffic', 'performance', 'captcha', 'errors'],+ description: 'Device type (desktop, mobile, tablet, ...)',+ },+ {+ api: 'referrer',+ column: 'ref',+ types: ['traffic'],+ description: 'Full referrer URL',+ },+ {+ api: 'referrer_name',+ column: 'refn',+ types: ['traffic'],+ filterOnly: true,+ description:+ 'Canonical referrer (root domain), filter-only; use the referrer dimension for breakdowns',+ },+ {+ api: 'utm_source',+ column: 'so',+ types: ['traffic'],+ excludeNull: true,+ description: 'UTM source',+ },+ {+ api: 'utm_medium',+ column: 'me',+ types: ['traffic'],+ excludeNull: true,+ description: 'UTM medium',+ },+ {+ api: 'utm_campaign',+ column: 'ca',+ types: ['traffic'],+ excludeNull: true,+ description: 'UTM campaign',+ },+ {+ api: 'utm_term',+ column: 'te',+ types: ['traffic'],+ excludeNull: true,+ description: 'UTM term',+ },+ {+ api: 'utm_content',+ column: 'co',+ types: ['traffic'],+ excludeNull: true,+ description: 'UTM content',+ },+ {+ api: 'isp',+ column: 'isp',+ types: GEO_TYPES,+ excludeNull: true,+ description: 'Internet service provider',+ },+ {+ api: 'organization',+ column: 'og',+ types: GEO_TYPES,+ excludeNull: true,+ description: 'Network organization',+ },+ {+ api: 'user_type',+ column: 'ut',+ types: GEO_TYPES,+ excludeNull: true,+ description: 'Connection user type (residential, hosting, ...)',+ },+ {+ api: 'connection_type',+ column: 'ctp',+ types: GEO_TYPES,+ excludeNull: true,+ description: 'Connection type (Cable/DSL, Cellular, ...)',+ },+ {+ api: 'entry_page',+ column: 'entryPage',+ types: ['traffic', 'errors'],+ virtual: 'entry_page',+ description: 'First page of the session',+ },+ {+ api: 'exit_page',+ column: 'exitPage',+ types: ['traffic', 'errors'],+ virtual: 'exit_page',+ description: 'Last page of the session',+ },+ {+ api: 'event',+ column: 'ev',+ types: ['traffic'],+ filterOnly: true,+ description:+ 'Custom event name (filter-only; use /traffic/custom-events for a breakdown)',+ },+ // Errors-only, filter-only dimensions. Columns are the v1 public filter+ // names β getFiltersQuery maps them to error_name/error_message/error_filename.+ {+ api: 'error_name',+ column: 'name',+ types: ['errors'],+ filterOnly: true,+ description: 'Error name',+ },+ {+ api: 'error_message',+ column: 'message',+ types: ['errors'],+ filterOnly: true,+ description: 'Error message',+ },+ {+ api: 'error_filename',+ column: 'filename',+ types: ['errors'],+ filterOnly: true,+ description: 'Source file the error originated from',+ },+ // Captcha meta dimensions. Per-dimension WHERE guards mirror v1+ // generateParamsQuery captcha handling.+ {+ api: 'captcha_event',+ column: 'captcha_event',+ types: ['captcha'],+ description: 'Captcha lifecycle event (generate, pass, verify_fail, ...)',+ },+ {+ api: 'captcha_difficulty',+ column: 'captcha_difficulty',+ types: ['captcha'],+ extraWhere: `AND ${CAPTCHA_EVENT_SQL} = 'generate' AND toUInt8OrZero(${CAPTCHA_DIFFICULTY_SQL}) > 0`,+ description: 'Captcha difficulty level',+ },+ {+ api: 'captcha_reason',+ column: 'captcha_reason',+ types: ['captcha'],+ extraWhere: `AND ${CAPTCHA_EVENT_SQL} = 'generate' AND ${CAPTCHA_REASON_SQL} NOT IN ('', 'baseline', 'manual')`,+ description: 'Reason for elevated captcha difficulty',+ },+ {+ api: 'solve_time',+ column: 'solve_time',+ types: ['captcha'],+ extraWhere: `AND ${CAPTCHA_EVENT_SQL} = 'pass' AND ${CAPTCHA_SOLVE_MS_SQL} > 0`,+ description: 'Captcha solve-time bucket',+ },+]++// Captcha country/browser/os/device breakdowns only count passed captchas (v1 parity)+const CAPTCHA_PASS_GUARD = `AND ${CAPTCHA_EVENT_SQL} = 'pass'`++export const captchaExtraWhere = (dim: V2DimensionDef): string | undefined => {+ if (dim.extraWhere) {+ return dim.extraWhere+ }++ if (['cc', 'br', 'os', 'dv'].includes(dim.column)) {+ return CAPTCHA_PASS_GUARD+ }++ return undefined+}++/**+ * Filter-only dimension families that carry a `key` (meta.key) and translate+ * to v1's `ev:key:<key>` / `tag:key:<key>` filter columns.+ */+export const V2_KEYED_FILTER_DIMENSIONS: Record<+ string,+ { v1Prefix: string; v1KeyColumn: string; types: V2DimensionDef['types'] }+> = {+ event_metadata: {+ v1Prefix: 'ev:key:',+ v1KeyColumn: 'ev:key',+ types: ['traffic'],+ },+ page_property: {+ v1Prefix: 'tag:key:',+ v1KeyColumn: 'tag:key',+ types: ['traffic', 'errors'],+ },+}diff --git a/backend/apps/community/src/analytics/v2/registry/index.ts b/backend/apps/community/src/analytics/v2/registry/index.tsnew file mode 100644index 000000000..6b2d94bdd--- /dev/null+++ b/backend/apps/community/src/analytics/v2/registry/index.ts@@ -0,0 +1,109 @@+import { UnprocessableEntityException } from '@nestjs/common'++import { DataType } from '../../analytics.service'+import { V2_DIMENSIONS } from './dimensions'+import { V2_METRICS } from './metrics'+import { V2DataType, V2DimensionDef, V2MetricDef } from './types'++export * from './types'+export {+ V2_DIMENSIONS,+ V2_KEYED_FILTER_DIMENSIONS,+ captchaExtraWhere,+} from './dimensions'++export const V2_TO_V1_DATATYPE: Record<V2DataType, DataType> = {+ traffic: DataType.ANALYTICS,+ performance: DataType.PERFORMANCE,+ captcha: DataType.CAPTCHA,+ errors: DataType.ERRORS,+}++export const listDimensions = (type: V2DataType): V2DimensionDef[] =>+ V2_DIMENSIONS.filter((dimension) => dimension.types.includes(type))++export const listMetrics = (type: V2DataType): V2MetricDef[] =>+ V2_METRICS.filter((metric) => metric.types.includes(type))++export const findDimension = (+ api: string,+ type: V2DataType,+): V2DimensionDef | undefined =>+ V2_DIMENSIONS.find(+ (dimension) => dimension.api === api && dimension.types.includes(type),+ )++/**+ * Resolve a dimension usable as ?dimension= (i.e. for breakdowns).+ * Throws a descriptive 422 for unknown or filter-only dimensions.+ */+export const getBreakdownDimension = (+ api: string,+ type: V2DataType,+): V2DimensionDef => {+ const dimension = findDimension(api, type)++ if (!dimension) {+ throw new UnprocessableEntityException(+ `Unknown ${type} dimension '${api}'. Supported dimensions: ${listDimensions(+ type,+ )+ .filter((d) => !d.filterOnly)+ .map((d) => d.api)+ .join(', ')}`,+ )+ }++ if (dimension.filterOnly) {+ throw new UnprocessableEntityException(+ `The '${api}' dimension can only be used in filters, not as a breakdown dimension`,+ )+ }++ return dimension+}++export const getMetric = (api: string, type: V2DataType): V2MetricDef => {+ const metric = V2_METRICS.find((m) => m.api === api && m.types.includes(type))++ if (!metric) {+ throw new UnprocessableEntityException(+ `Unknown ${type} metric '${api}'. Supported metrics: ${listMetrics(type)+ .map((m) => m.api)+ .join(', ')}`,+ )+ }++ return metric+}++export const getDefaultMetrics = (type: V2DataType): V2MetricDef[] =>+ listMetrics(type).filter((metric) => metric.isDefault)++/**+ * Parse a `metrics` CSV query param into validated metric definitions.+ * Returns the per-type defaults when the param is empty.+ */+export const parseMetricsParam = (+ metrics: string | undefined,+ type: V2DataType,+): V2MetricDef[] => {+ if (!metrics) {+ return getDefaultMetrics(type)+ }++ const names = [+ ...new Set(+ metrics+ .split(',')+ .map((name) => name.trim())+ .filter(Boolean),+ ),+ ]++ if (names.length === 0) {+ return getDefaultMetrics(type)+ }++ return names.map((name) => getMetric(name, type))+}diff --git a/backend/apps/community/src/analytics/v2/registry/metrics.ts b/backend/apps/community/src/analytics/v2/registry/metrics.tsnew file mode 100644index 000000000..a7edbcbdf--- /dev/null+++ b/backend/apps/community/src/analytics/v2/registry/metrics.ts@@ -0,0 +1,191 @@+import { V2MetricDef } from './types'++/**+ * Local copy of the v1 MEASURES_MAP (analytics.service.ts). Duplicated on+ * purpose β the v2 registry is self-contained and these four entries are the+ * public API contract for the `measure` parameter.+ */+const MEASURES_MAP_V2: Record<string, string> = {+ average: 'avg',+ median: 'median',+ p95: 'quantileExact(0.95)',+ p75: 'quantileExact(0.75)',+}++const perfExpr =+ (column: string) =>+ ({ measure }: { measure?: string }): string => {+ const processedMeasure =+ !measure || measure === 'quantiles' ? 'median' : measure+ const fn = MEASURES_MAP_V2[processedMeasure] || 'median'+ return `round(divide(${fn}(${column}), 1000), 2)`+ }++export const V2_METRICS: V2MetricDef[] = [+ // --- traffic ---+ {+ api: 'visitors',+ types: ['traffic'],+ // v1 semantics preserved: with a custom-event filter applied the base+ // event set is custom_event rows and "visitors" degrades to count(*)+ sqlExpr: ({ customEVFilterApplied }) =>+ customEVFilterApplied ? 'count(*)' : 'count(DISTINCT psid)',+ isDefault: true,+ format: 'integer',+ description: 'Unique sessions',+ },+ {+ api: 'pageviews',+ types: ['traffic'],+ sqlExpr: () => 'count(*)',+ isDefault: true,+ format: 'integer',+ description: 'Pageview (or matched custom event) count',+ },+ {+ api: 'users',+ types: ['traffic'],+ sqlExpr: () => 'count(DISTINCT profileId)',+ format: 'integer',+ description: 'Unique users (identified + anonymous profiles)',+ },+ {+ api: 'session_duration',+ types: ['traffic'],+ sqlExpr: () => null,+ requiresSessionsJoin: true,+ format: 'seconds',+ description:+ 'Average session duration in seconds (timeseries and summary only)',+ },+ {+ api: 'bounce_rate',+ types: ['traffic'],+ sqlExpr: () => null,+ requiresSessionsJoin: true,+ format: 'percent',+ description:+ 'Percentage of single-pageview sessions (timeseries and summary only)',+ },+ // --- performance (values in seconds; `measure` selects the aggregate) ---+ {+ api: 'load_time',+ types: ['performance'],+ sqlExpr: perfExpr('pageLoad'),+ isDefault: true,+ format: 'seconds',+ description: 'Full page load time',+ },+ {+ api: 'ttfb',+ types: ['performance'],+ sqlExpr: perfExpr('ttfb'),+ format: 'seconds',+ description: 'Time to first byte',+ },+ {+ api: 'dns',+ types: ['performance'],+ sqlExpr: perfExpr('dns'),+ format: 'seconds',+ description: 'DNS resolution time',+ },+ {+ api: 'tls',+ types: ['performance'],+ sqlExpr: perfExpr('tls'),+ format: 'seconds',+ description: 'TLS setup time',+ },+ {+ api: 'connection',+ types: ['performance'],+ sqlExpr: perfExpr('conn'),+ format: 'seconds',+ description: 'Connection establishment time',+ },+ {+ api: 'response',+ types: ['performance'],+ sqlExpr: perfExpr('response'),+ format: 'seconds',+ description: 'Response time',+ },+ {+ api: 'render',+ types: ['performance'],+ sqlExpr: perfExpr('render'),+ format: 'seconds',+ description: 'Browser render time',+ },+ {+ api: 'dom_load',+ types: ['performance'],+ sqlExpr: perfExpr('domLoad'),+ format: 'seconds',+ description: 'DOM content load time',+ },+ // --- errors ---+ {+ api: 'occurrences',+ types: ['errors'],+ sqlExpr: () => 'count(*)',+ isDefault: true,+ format: 'integer',+ description: 'Error occurrences',+ },+ {+ api: 'affected_users',+ types: ['errors'],+ sqlExpr: () => 'uniqExact(profileId)',+ format: 'integer',+ description: 'Distinct users affected',+ },+ // --- captcha ---+ {+ api: 'events',+ types: ['captcha'],+ sqlExpr: () => 'count(*)',+ isDefault: true,+ format: 'integer',+ description: 'Captcha events matching the dimension scope',+ },+ // Timeseries/summary-only captcha counters (computed by the captcha+ // aggregation query, not the generic breakdown builder)+ {+ api: 'generated',+ types: ['captcha'],+ sqlExpr: () => null,+ format: 'integer',+ description: 'Captchas generated (timeseries and summary only)',+ },+ {+ api: 'passed',+ types: ['captcha'],+ sqlExpr: () => null,+ format: 'integer',+ description: 'Captchas passed (timeseries and summary only)',+ },+ {+ api: 'failed',+ types: ['captcha'],+ sqlExpr: () => null,+ format: 'integer',+ description: 'Captchas failed verification (timeseries and summary only)',+ },+ {+ api: 'validation_failed',+ types: ['captcha'],+ sqlExpr: () => null,+ format: 'integer',+ description:+ 'Captchas that failed validation (timeseries and summary only)',+ },+ {+ api: 'replayed',+ types: ['captcha'],+ sqlExpr: () => null,+ format: 'integer',+ description: 'Replayed captcha attempts (timeseries and summary only)',+ },+]diff --git a/backend/apps/community/src/analytics/v2/registry/types.ts b/backend/apps/community/src/analytics/v2/registry/types.tsnew file mode 100644index 000000000..d4240e58c--- /dev/null+++ b/backend/apps/community/src/analytics/v2/registry/types.ts@@ -0,0 +1,64 @@+import { PerfMeasure } from '../../interfaces'++export type V2DataType = 'traffic' | 'performance' | 'captcha' | 'errors'++interface V2DimensionExtraField {+ /** Public API name of the sibling field, e.g. 'country' */+ api: string+ /** ClickHouse column of the sibling field, e.g. 'cc' */+ column: string+}++export interface V2DimensionDef {+ /** Public API name, snake_case: 'country', 'browser_version' */+ api: string+ /**+ * v1 filter column / ClickHouse column: 'cc', 'brv'. For captcha meta+ * dimensions this is the v1 virtual column name ('captcha_event',+ * 'solve_time') which getFiltersQuery resolves to a SQL expression.+ * For errors-only filter dimensions this is the v1 public name ('name',+ * 'message', 'filename') which getFiltersQuery maps to error_* columns.+ */+ column: string+ /** Data types this dimension is valid for */+ types: V2DataType[]+ /** Sibling columns returned with each row, e.g. region -> country + region_code */+ extraFields?: V2DimensionExtraField[]+ /** Mirrors v1 EXCLUDE_NULL_FOR behavior */+ excludeNull?: boolean+ /** Usable in ?filters but not as ?dimension= */+ filterOnly?: boolean+ /** Needs a dedicated query path instead of the generic breakdown builder */+ virtual?: 'entry_page' | 'exit_page'+ /**+ * Extra WHERE fragment (starting with 'AND ...') appended to the breakdown+ * query. Used by captcha dimensions to scope rows to the relevant+ * captcha lifecycle event, mirroring v1 generateParamsQuery.+ */+ extraWhere?: string+ description: string+}++export interface V2MetricCtx {+ customEVFilterApplied: boolean+ measure?: PerfMeasure+}++export interface V2MetricDef {+ /** Public API name, snake_case: 'visitors', 'bounce_rate' */+ api: string+ /** Data types this metric is valid for */+ types: V2DataType[]+ /**+ * ClickHouse aggregate expression, or null when the metric cannot be+ * computed by the generic breakdown builder (e.g. it needs the sessions+ * join, or it only exists on timeseries/summary queries).+ */+ sqlExpr: (ctx: V2MetricCtx) => string | null+ /** Metric needs the sessions-table join β timeseries/summary only */+ requiresSessionsJoin?: boolean+ /** Included when no ?metrics= is provided */+ isDefault?: boolean+ format?: 'integer' | 'seconds' | 'percent'+ description: string+}diff --git a/backend/apps/community/tsconfig.app.json b/backend/apps/community/tsconfig.app.jsonindex 3cef421cd..951e710e2 100644--- a/backend/apps/community/tsconfig.app.json+++ b/backend/apps/community/tsconfig.app.json@@ -7,7 +7,7 @@"esModuleInterop": true,"experimentalDecorators": true,"allowSyntheticDefaultImports": true,- "target": "es2017",+ "target": "es2022","sourceMap": true,"outDir": "./dist","baseUrl": "./",