📈 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
Display events charts on dashboard
Blue Mouseb4adbde3012e
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.tsindex 017d55034..8204a3e52 100644--- a/backend/apps/cloud/src/analytics/analytics.controller.ts+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts@@ -854,6 +854,7 @@ export class AnalyticsController {timezone = DEFAULT_TIMEZONE,timeBucket,filters,+ includeChart,} = dataconst pidsArray = getPIDsArray(pids, pid)@@ -892,6 +893,7 @@ export class AnalyticsController {to,timezone,filters,+ includeChart,)}diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.tsindex 7d3f84f46..845a56260 100644--- a/backend/apps/cloud/src/analytics/analytics.service.ts+++ b/backend/apps/cloud/src/analytics/analytics.service.ts@@ -1526,20 +1526,27 @@ export class AnalyticsService {to?: string,timezone?: string,filters?: string,+ includeChart?: boolean,): Promise<IOverall> {const safeTimezone = this.getSafeTimezone(timezone)- const { groupFromUTC, groupToUTC } = this.getGroupFromTo(- from,- to,- ['today', 'yesterday', 'custom'].includes(period)- ? TimeBucketType.HOUR- : (timeBucket as TimeBucketType) || TimeBucketType.DAY,+ // Determine the time bucket for chart data+ const effectiveTimeBucket = ['today', 'yesterday', 'custom'].includes(period,- safeTimezone,- undefined,- false,)+ ? TimeBucketType.HOUR+ : (timeBucket as TimeBucketType) || TimeBucketType.DAY++ const { groupFrom, groupTo, groupFromUTC, groupToUTC } =+ this.getGroupFromTo(+ from,+ to,+ effectiveTimeBucket,+ period,+ safeTimezone,+ undefined,+ false,+ )const result = {}@@ -1620,6 +1627,29 @@ export class AnalyticsService {sdurChange: data[0].sdur,customEVFilterApplied,}++ // For 'all' period, we use month time bucket for chart+ if (includeChart) {+ const allTimeChartBucket = TimeBucketType.MONTH+ const { groupFrom: allFrom, groupTo: allTo } = this.getGroupFromTo(+ undefined,+ undefined,+ allTimeChartBucket,+ 'all',+ safeTimezone,+ )+ const chartData = await this.getSimplifiedChartData(+ pid,+ allTimeChartBucket,+ allFrom,+ allTo,+ filtersQuery,+ filtersParams,+ safeTimezone,+ customEVFilterApplied,+ )+ result[pid].chart = chartData+ }return}@@ -1773,6 +1803,21 @@ export class AnalyticsService {sdurChange: currentPeriod.sdur - previousPeriod.sdur,customEVFilterApplied,}++ // Add chart data if requested+ if (includeChart) {+ const chartData = await this.getSimplifiedChartData(+ pid,+ effectiveTimeBucket,+ groupFrom,+ groupTo,+ filtersQuery,+ filtersParams,+ safeTimezone,+ customEVFilterApplied,+ )+ result[pid].chart = chartData+ }} catch (reason) {console.error(`[ERROR] (getAnalyticsSummary) Error occurred for PID ${pid}`,@@ -1789,6 +1834,74 @@ export class AnalyticsService {return result}+ /**+ * Get simplified chart data for dashboard cards+ * Returns only x (dates) and visits (pageviews) for a lightweight chart+ */+ async getSimplifiedChartData(+ pid: string,+ timeBucket: TimeBucketType,+ groupFrom: string,+ groupTo: string,+ filtersQuery: string,+ filtersParams: Record<string, string | boolean>,+ safeTimezone: string,+ customEVFilterApplied: boolean,+ ): Promise<{ x: string[]; visits: number[] }> {+ const { xShifted } = this.generateXAxis(+ timeBucket,+ groupFrom,+ groupTo,+ safeTimezone,+ )++ const paramsData = {+ params: {+ pid,+ groupFrom,+ groupTo,+ ...filtersParams,+ },+ }++ if (customEVFilterApplied) {+ const query = this.generateCustomEventsAggregationQuery(+ timeBucket,+ filtersQuery,+ ChartRenderMode.PERIODICAL,+ )++ const { data } = await clickhouse+ .query({+ query,+ query_params: { ...paramsData.params, timezone: safeTimezone },+ })+ .then(resultSet => resultSet.json<TrafficCEFilterCHResponse>())++ const visits =+ this.extractCustomEventsChartData(data, xShifted)?._unknown_event || []++ return { x: xShifted, visits }+ }++ const query = this.generateAnalyticsAggregationQuery(+ timeBucket,+ filtersQuery,+ ChartRenderMode.PERIODICAL,+ )++ const { data } = await clickhouse+ .query({+ query,+ query_params: { ...paramsData.params, timezone: safeTimezone },+ })+ .then(resultSet => resultSet.json<TrafficCHResponse>())++ const { visits } = this.extractChartData(data, xShifted)++ return { x: xShifted, visits }+ }+async getPerformanceSummary(pids: string[],period?: string,diff --git a/backend/apps/cloud/src/analytics/dto/get-overall-stats.dto.ts b/backend/apps/cloud/src/analytics/dto/get-overall-stats.dto.tsindex 1460d9039..92104b02d 100644--- a/backend/apps/cloud/src/analytics/dto/get-overall-stats.dto.ts+++ b/backend/apps/cloud/src/analytics/dto/get-overall-stats.dto.ts@@ -1,5 +1,12 @@import { ApiProperty } from '@nestjs/swagger'-import { IsOptional, IsString, Matches, ValidateIf } from 'class-validator'+import {+ IsOptional,+ IsString,+ Matches,+ ValidateIf,+ IsBoolean,+} from 'class-validator'+import { Transform } from 'class-transformer'import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'import { ValidatePeriod } from '../decorators/validate-period.decorator'import { PID_REGEX } from '../../common/constants'@@ -56,4 +63,14 @@ export class GetOverallStatsDto {@IsOptional()@IsString()filters?: string++ @ApiProperty({+ description: 'Whether to include simplified chart data for each project',+ required: false,+ default: false,+ })+ @IsOptional()+ @IsBoolean()+ @Transform(({ value }) => value === 'true' || value === true)+ includeChart?: boolean = false}diff --git a/backend/apps/cloud/src/analytics/interfaces/index.ts b/backend/apps/cloud/src/analytics/interfaces/index.tsindex d1e7c4390..1618907f5 100644--- a/backend/apps/cloud/src/analytics/interfaces/index.ts+++ b/backend/apps/cloud/src/analytics/interfaces/index.ts@@ -156,6 +156,11 @@ interface IPerformanceObject {networkChange: number}+interface IOverallChart {+ x: string[]+ visits: number[]+}+interface IOverallObject {current: IOverallPeriodStatsprevious: IOverallPeriodStats@@ -164,6 +169,7 @@ interface IOverallObject {usersChange?: numberbounceRateChange?: numbersdurChange?: number+ chart?: IOverallChart}export interface IOverall {diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.tsindex c03b5fc17..bb9bd6541 100644--- a/backend/apps/community/src/analytics/analytics.controller.ts+++ b/backend/apps/community/src/analytics/analytics.controller.ts@@ -692,6 +692,7 @@ export class AnalyticsController {timezone = DEFAULT_TIMEZONE,filters,timeBucket,+ includeChart,} = dataconst pidsArray = getPIDsArray(pids, pid)@@ -713,6 +714,7 @@ export class AnalyticsController {to,timezone,filters,+ includeChart,)}diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.tsindex 4501faec1..023f11c72 100644--- a/backend/apps/community/src/analytics/analytics.service.ts+++ b/backend/apps/community/src/analytics/analytics.service.ts@@ -1457,20 +1457,27 @@ export class AnalyticsService {to?: string,timezone?: string,filters?: string,+ includeChart?: boolean,): Promise<IOverall> {const safeTimezone = this.getSafeTimezone(timezone)- const { groupFromUTC, groupToUTC } = this.getGroupFromTo(- from,- to,- ['today', 'yesterday', 'custom'].includes(period)- ? TimeBucketType.HOUR- : (timeBucket as TimeBucketType) || TimeBucketType.DAY,+ // Determine the time bucket for chart data+ const effectiveTimeBucket = ['today', 'yesterday', 'custom'].includes(period,- safeTimezone,- undefined,- false,)+ ? TimeBucketType.HOUR+ : (timeBucket as TimeBucketType) || TimeBucketType.DAY++ const { groupFrom, groupTo, groupFromUTC, groupToUTC } =+ this.getGroupFromTo(+ from,+ to,+ effectiveTimeBucket,+ period,+ safeTimezone,+ undefined,+ false,+ )const result = {}@@ -1551,6 +1558,29 @@ export class AnalyticsService {sdurChange: data[0].sdur,customEVFilterApplied,}++ // For 'all' period, we use month time bucket for chart+ if (includeChart) {+ const allTimeChartBucket = TimeBucketType.MONTH+ const { groupFrom: allFrom, groupTo: allTo } = this.getGroupFromTo(+ undefined,+ undefined,+ allTimeChartBucket,+ 'all',+ safeTimezone,+ )+ const chartData = await this.getSimplifiedChartData(+ pid,+ allTimeChartBucket,+ allFrom,+ allTo,+ filtersQuery,+ filtersParams,+ safeTimezone,+ customEVFilterApplied,+ )+ result[pid].chart = chartData+ }return}@@ -1704,6 +1734,21 @@ export class AnalyticsService {sdurChange: currentPeriod.sdur - previousPeriod.sdur,customEVFilterApplied,}++ // Add chart data if requested+ if (includeChart) {+ const chartData = await this.getSimplifiedChartData(+ pid,+ effectiveTimeBucket,+ groupFrom,+ groupTo,+ filtersQuery,+ filtersParams,+ safeTimezone,+ customEVFilterApplied,+ )+ result[pid].chart = chartData+ }} catch (reason) {console.error(`[ERROR] (getAnalyticsSummary) Error occurred for PID ${pid}`,@@ -1720,6 +1765,74 @@ export class AnalyticsService {return result}+ /**+ * Get simplified chart data for dashboard cards+ * Returns only x (dates) and visits (pageviews) for a lightweight chart+ */+ async getSimplifiedChartData(+ pid: string,+ timeBucket: TimeBucketType,+ groupFrom: string,+ groupTo: string,+ filtersQuery: string,+ filtersParams: Record<string, string | boolean>,+ safeTimezone: string,+ customEVFilterApplied: boolean,+ ): Promise<{ x: string[]; visits: number[] }> {+ const { xShifted } = this.generateXAxis(+ timeBucket,+ groupFrom,+ groupTo,+ safeTimezone,+ )++ const paramsData = {+ params: {+ pid,+ groupFrom,+ groupTo,+ ...filtersParams,+ },+ }++ if (customEVFilterApplied) {+ const query = this.generateCustomEventsAggregationQuery(+ timeBucket,+ filtersQuery,+ ChartRenderMode.PERIODICAL,+ )++ const { data } = await clickhouse+ .query({+ query,+ query_params: { ...paramsData.params, timezone: safeTimezone },+ })+ .then(resultSet => resultSet.json<TrafficCEFilterCHResponse>())++ const visits =+ this.extractCustomEventsChartData(data, xShifted)?._unknown_event || []++ return { x: xShifted, visits }+ }++ const query = this.generateAnalyticsAggregationQuery(+ timeBucket,+ filtersQuery,+ ChartRenderMode.PERIODICAL,+ )++ const { data } = await clickhouse+ .query({+ query,+ query_params: { ...paramsData.params, timezone: safeTimezone },+ })+ .then(resultSet => resultSet.json<TrafficCHResponse>())++ const { visits } = this.extractChartData(data, xShifted)++ return { x: xShifted, visits }+ }+async getPerformanceSummary(pids: string[],period?: string,diff --git a/backend/apps/community/src/analytics/dto/get-overall-stats.dto.ts b/backend/apps/community/src/analytics/dto/get-overall-stats.dto.tsindex 1460d9039..92104b02d 100644--- a/backend/apps/community/src/analytics/dto/get-overall-stats.dto.ts+++ b/backend/apps/community/src/analytics/dto/get-overall-stats.dto.ts@@ -1,5 +1,12 @@import { ApiProperty } from '@nestjs/swagger'-import { IsOptional, IsString, Matches, ValidateIf } from 'class-validator'+import {+ IsOptional,+ IsString,+ Matches,+ ValidateIf,+ IsBoolean,+} from 'class-validator'+import { Transform } from 'class-transformer'import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'import { ValidatePeriod } from '../decorators/validate-period.decorator'import { PID_REGEX } from '../../common/constants'@@ -56,4 +63,14 @@ export class GetOverallStatsDto {@IsOptional()@IsString()filters?: string++ @ApiProperty({+ description: 'Whether to include simplified chart data for each project',+ required: false,+ default: false,+ })+ @IsOptional()+ @IsBoolean()+ @Transform(({ value }) => value === 'true' || value === true)+ includeChart?: boolean = false}diff --git a/backend/apps/community/src/analytics/interfaces/index.ts b/backend/apps/community/src/analytics/interfaces/index.tsindex caedb95c0..fedd7e54f 100644--- a/backend/apps/community/src/analytics/interfaces/index.ts+++ b/backend/apps/community/src/analytics/interfaces/index.ts@@ -156,6 +156,11 @@ interface IPerformanceObject {networkChange: number}+interface IOverallChart {+ x: string[]+ visits: number[]+}+interface IOverallObject {current: IOverallPeriodStatsprevious: IOverallPeriodStats@@ -164,6 +169,7 @@ interface IOverallObject {usersChange?: numberbounceRateChange?: numbersdurChange?: number+ chart?: IOverallChart}export interface IOverall {diff --git a/web/app/api/index.ts b/web/app/api/index.tsindex 0ad67fb69..63e89c5ba 100644--- a/web/app/api/index.ts+++ b/web/app/api/index.ts@@ -967,12 +967,13 @@ export const getOverallStats = (timezone = 'Etc/GMT',filters: any = '',password?: string,+ includeChart = false,) =>api.get(`log/birdseye?pids=[${_map(pids, (pid) => `"${pid}"`).join(',',- )}]&timeBucket=${tb}&period=${period}&from=${from}&to=${to}&timezone=${timezone}&filters=${JSON.stringify(filters)}`,+ )}]&timeBucket=${tb}&period=${period}&from=${from}&to=${to}&timezone=${timezone}&filters=${JSON.stringify(filters)}&includeChart=${includeChart}`,{headers: {'x-password': password,diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.tsindex 2ed1cc8bc..131cba91e 100644--- a/web/app/lib/models/Project.ts+++ b/web/app/lib/models/Project.ts@@ -8,6 +8,11 @@ interface OverallPeriodStats {sdur?: number}+export interface OverallChart {+ x: string[]+ visits: number[]+}+export interface OverallObject {current: OverallPeriodStatsprevious: OverallPeriodStats@@ -17,6 +22,7 @@ export interface OverallObject {bounceRateChange?: numbersdurChange?: numbercustomEVFilterApplied?: boolean+ chart?: OverallChart}export type Overall = Record<string, OverallObject>diff --git a/web/app/pages/Dashboard/Dashboard.tsx b/web/app/pages/Dashboard/Dashboard.tsxindex 4f0f8ff0d..b7a90c143 100644--- a/web/app/pages/Dashboard/Dashboard.tsx+++ b/web/app/pages/Dashboard/Dashboard.tsx@@ -348,7 +348,17 @@ const Dashboard = () => {try {const timeBucket = tbPeriodPairs(t).find((p) => p.period === activePeriod)?.tbs[0] || ''- const stats = await getOverallStats(projectIds, timeBucket, activePeriod)+ const stats = await getOverallStats(+ projectIds,+ timeBucket,+ activePeriod,+ '',+ '',+ 'Etc/GMT',+ '',+ undefined,+ true,+ )setOverallStats((prev) => ({ ...prev, ...stats }))} catch (reason) {console.error('Failed to fetch overall stats:', reason)diff --git a/web/app/pages/Dashboard/ProjectCard.tsx b/web/app/pages/Dashboard/ProjectCard.tsxindex c431d7970..dc265d8f4 100644--- a/web/app/pages/Dashboard/ProjectCard.tsx+++ b/web/app/pages/Dashboard/ProjectCard.tsx@@ -24,6 +24,7 @@ import { Text } from '~/ui/Text'import { nFormatter, calculateRelativePercentage } from '~/utils/generic'import routes from '~/utils/routes'+import Sparkline from './Sparkline'import { DASHBOARD_TABS } from './Tabs'interface ProjectCardProps {@@ -205,11 +206,17 @@ export const ProjectCard = ({}}onClick={onElementClick}className={cx(- 'cursor-pointer overflow-hidden rounded-xl border border-gray-200 bg-gray-50 transition-colors hover:bg-gray-200/70 dark:border-slate-800/25 dark:bg-slate-800/70 dark:hover:bg-slate-700/60',+ 'relative cursor-pointer overflow-hidden rounded-xl border border-gray-200 bg-gray-50 transition-colors hover:bg-gray-200/70 dark:border-slate-800/25 dark:bg-slate-800/70 dark:hover:bg-slate-700/60',viewMode === 'list' ? 'flex items-center justify-between px-6 py-4' : 'min-h-[153.1px]',)}>- <div className={cx('flex flex-col', viewMode === 'list' ? 'flex-1' : 'px-4 py-4')}>+ {/* Background sparkline chart */}+ {viewMode === 'grid' && overallStats?.chart ? (+ <div className='pointer-events-none absolute inset-x-0 bottom-0 z-0 opacity-50'>+ <Sparkline chart={overallStats.chart} className='w-full' />+ </div>+ ) : null}+ <div className={cx('relative z-10 flex flex-col', viewMode === 'list' ? 'flex-1' : 'px-4 py-4')}><div className={cx('flex items-center', viewMode === 'grid' ? 'justify-between' : 'justify-start gap-1')}><Text as='p' size='lg' weight='semibold' truncate>{name}@@ -234,7 +241,7 @@ export const ProjectCard = ({)}</div></div>- <div className={cx('flex shrink-0 gap-5', viewMode === 'list' ? 'ml-4' : 'mt-4 px-4 pb-4')}>+ <div className={cx('relative z-10 flex shrink-0 gap-5', viewMode === 'list' ? 'ml-4' : 'mt-4 px-4 pb-4')}>{isHostnameNavigationEnabled ? (<MiniCardlabelTKey='dashboard.pageviews'diff --git a/web/app/pages/Dashboard/Sparkline.tsx b/web/app/pages/Dashboard/Sparkline.tsxnew file mode 100644index 000000000..f8ab924e1--- /dev/null+++ b/web/app/pages/Dashboard/Sparkline.tsx@@ -0,0 +1,89 @@+import type { ChartOptions } from 'billboard.js'+import { area } from 'billboard.js'+import React, { useMemo, memo } from 'react'++import { OverallChart } from '~/lib/models/Project'+import BillboardChart from '~/ui/BillboardChart'++interface SparklineProps {+ chart?: OverallChart+ className?: string+}++const Sparkline = memo(({ chart, className }: SparklineProps) => {+ // Check if there's any meaningful data (at least one non-zero value)+ const hasData = useMemo(() => {+ if (!chart || !chart.visits || chart.visits.length === 0) {+ return false+ }+ return chart.visits.some((value) => value > 0)+ }, [chart])++ const options: ChartOptions = useMemo(() => {+ if (!hasData) {+ return null as unknown as ChartOptions+ }++ return {+ data: {+ columns: [['visits', ...(chart?.visits || [])]],+ type: area(),+ colors: {+ visits: 'rgb(99, 102, 241)', // indigo-500+ },+ },+ area: {+ linearGradient: {+ x: [0, 0],+ y: [0, 1],+ stops: [+ [0, 'rgba(99, 102, 241, 0.3)'],+ [1, 'rgba(99, 102, 241, 0.05)'],+ ],+ },+ },+ point: {+ show: false,+ },+ line: {+ classes: ['sparkline-line'],+ },+ axis: {+ x: {+ show: false,+ },+ y: {+ show: false,+ },+ },+ legend: {+ show: false,+ },+ tooltip: {+ show: false,+ },+ padding: {+ top: 0,+ right: 0,+ bottom: 0,+ left: 0,+ },+ size: {+ height: 60,+ },+ interaction: {+ enabled: false,+ },+ }+ }, [chart, hasData])++ if (!hasData || !options) {+ return null+ }++ return <BillboardChart options={options} className={className} deps={[chart]} />+})++Sparkline.displayName = 'Sparkline'++export default Sparkline