📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Added basic support for custom metrics
Blue Mousef5f99ffc4c2b
diff --git a/app/api/index.ts b/app/api/index.tsindex 5cd809712..c2a533dd7 100644--- a/app/api/index.ts+++ b/app/api/index.ts@@ -358,7 +358,8 @@ export const getProjectData = (pid: string,tb: string = 'hour',period: string = '1d',- filters: any[] = [],+ filters: IFilter[] = [],+ metrics: IProjectViewCustomEvent[] = [],from: string = '',to: string = '',timezone: string = '',@@ -367,7 +368,7 @@ export const getProjectData = () =>api.get(- `log?pid=${pid}&timeBucket=${tb}&period=${period}&filters=${JSON.stringify(+ `log?pid=${pid}&timeBucket=${tb}&period=${period}&metrics=${JSON.stringify(metrics)}&filters=${JSON.stringify(filters,)}&from=${from}&to=${to}&timezone=${timezone}&mode=${mode}`,{diff --git a/app/pages/Project/View/ViewProject.tsx b/app/pages/Project/View/ViewProject.tsxindex ea62cd55e..59ad1c05f 100644--- a/app/pages/Project/View/ViewProject.tsx+++ b/app/pages/Project/View/ViewProject.tsx@@ -179,7 +179,7 @@ import SearchFilters from './components/SearchFilters'import Filters from './components/Filters'import LiveVisitorsDropdown from './components/LiveVisitorsDropdown'import CountryDropdown from './components/CountryDropdown'-import MetricCards from './components/MetricCards'+import MetricCards, { MetricCard } from './components/MetricCards'import PerformanceMetricCards from './components/PerformanceMetricCards'import ProjectAlertsView from '../Alerts/View'import UTMDropdown from './components/UTMDropdown'@@ -198,9 +198,19 @@ import { IError } from './interfaces/error'import NoErrorDetails from './components/NoErrorDetails'import WaitingForAnError from './components/WaitingForAnError'import NoSessionDetails from './components/NoSessionDetails'-import { ICustoms, IFilter, IParams, IProjectView, IProperties, ITrafficLogResponse } from './interfaces/traffic'+import {+ ICustoms,+ IFilter,+ IMetric,+ IParams,+ IProjectView,+ IProjectViewCustomEvent,+ IProperties,+ ITrafficLogResponse,+} from './interfaces/traffic'import { trackCustom } from 'utils/analytics'import AddAViewModal from './components/AddAViewModal'+import CustomMetrics from './components/CustomMetrics'const SwetrixSDK = require('@swetrix/sdk')const CUSTOM_EV_DROPDOWN_MAX_VISIBLE_LENGTH = 32@@ -367,6 +377,7 @@ const ViewProject = ({data: IParamscustoms: ICustomsproperties: IProperties+ meta?: IMetric[]// @ts-expect-error}>({})const [overall, setOverall] = useState<Partial<IOverallObject>>({})@@ -420,6 +431,7 @@ const ViewProject = ({() => !_some({ ...activeChartMetrics, ...activeChartMetricsCustomEvents }, (value) => value),[activeChartMetrics, activeChartMetricsCustomEvents],)+ const [customMetrics, setCustomMetrics] = useState<IProjectViewCustomEvent[]>([])const [filters, setFilters] = useState<IFilter[]>([])const [filtersPerf, setFiltersPerf] = useState<IFilter[]>([])const [filtersSessions, setFiltersSessions] = useState<IFilter[]>([])@@ -1227,7 +1239,11 @@ const ViewProject = ({}// loadAnalytics is a function for load data for chart from api- const loadAnalytics = async (forced = false, newFilters: any[] | null = null) => {+ const loadAnalytics = async (+ forced = false,+ newFilters: IFilter[] | null = null,+ newMetrics: IProjectViewCustomEvent[] | null = null,+ ) => {if (!forced && (isLoading || _isEmpty(project) || dataLoading)) {return}@@ -1344,6 +1360,7 @@ const ViewProject = ({timeBucket,'',newFilters || filters,+ newMetrics || customMetrics,from,to,timezone,@@ -1368,6 +1385,7 @@ const ViewProject = ({timeBucket,period,newFilters || filters,+ newMetrics || customMetrics,'','',timezone,@@ -1418,7 +1436,7 @@ const ViewProject = ({return}- const { chart, params, customs, properties, appliedFilters } = data+ const { chart, params, customs, properties, appliedFilters, meta } = datalet newTimebucket = timeBucketsdkInstance?._emitEvent('load', sdkData)@@ -1485,6 +1503,7 @@ const ViewProject = ({data: params,customs,properties,+ meta,})if (activeTab === PROJECT_TABS.traffic) {@@ -2389,6 +2408,15 @@ const ViewProject = ({resetErrors()}+ const onCustomMetric = (metrics: IProjectViewCustomEvent[]) => {+ if (activeTab !== PROJECT_TABS.traffic) {+ return+ }++ setCustomMetrics(metrics)+ loadAnalytics(true, null, metrics)+ }+// this function is used for requesting the data from the API when the exclusive filter is changedconst onChangeExclusive = (column: string, filter: string, isExclusive: boolean) => {let newFilters@@ -3790,6 +3818,10 @@ const ViewProject = ({if (item.filters && !_isEmpty(item.filters)) {onFilterSearch(item.filters, true)}++ if (item.customEvents && !_isEmpty(item.customEvents)) {+ onCustomMetric(item.customEvents)+ }}}chevron='mini'buttonClassName='!p-2 rounded-md hover:bg-white hover:shadow-sm dark:hover:bg-slate-800 focus:z-10 focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 focus:dark:ring-gray-200 focus:dark:border-gray-200'@@ -4614,11 +4646,20 @@ const ViewProject = ({{activeTab === PROJECT_TABS.traffic && (<div className={cx('pt-2', { hidden: isPanelsDataEmpty || analyticsLoading })}>{!_isEmpty(overall) && (- <MetricCards- overall={overall}- overallCompare={overallCompare}- activePeriodCompare={activePeriodCompare}- />+ <div className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'>+ <MetricCards+ overall={overall}+ overallCompare={overallCompare}+ activePeriodCompare={activePeriodCompare}+ />+ {!_isEmpty(panelsData.meta) &&+ _map(panelsData.meta, ({ key, sum, avg }) => (+ <React.Fragment key={key}>+ <MetricCard label={t('project.metrics.xAvg', { x: key })} value={avg} />+ <MetricCard label={t('project.metrics.xTotal', { x: key })} value={sum} />+ </React.Fragment>+ ))}+ </div>)}<divclassName={cx('h-80', {@@ -4634,6 +4675,7 @@ const ViewProject = ({tnMapping={tnMapping}resetFilters={resetActiveTabFilters}/>+ <CustomMetrics metrics={customMetrics} onRemoveMetric={() => {}} resetMetrics={() => {}} />{dataLoading && (<div className='static mt-4 !bg-transparent' id='loader'><div className='loader-head dark:!bg-slate-800'>diff --git a/app/pages/Project/View/components/CustomMetrics.tsx b/app/pages/Project/View/components/CustomMetrics.tsxnew file mode 100644index 000000000..c3dccba37--- /dev/null+++ b/app/pages/Project/View/components/CustomMetrics.tsx@@ -0,0 +1,144 @@+import { FunnelIcon, XMarkIcon } from '@heroicons/react/24/outline'+import React, { memo } from 'react'+import cx from 'clsx'+import _truncate from 'lodash/truncate'+import _isEmpty from 'lodash/isEmpty'+import _map from 'lodash/map'+import _startsWith from 'lodash/startsWith'+import _replace from 'lodash/replace'+import { useTranslation } from 'react-i18next'++import countries from 'utils/isoCountries'+import { getLocaleDisplayName } from 'utils/generic'+import { IProjectViewCustomEvent } from '../interfaces/traffic'++interface IFilter {+ column: string+ filter: string+ isExclusive: boolean+ // eslint-disable-next-line no-shadow+ onRemoveFilter: (column: string, filter: string) => void+ // eslint-disable-next-line no-shadow+ onChangeExclusive: (column: string, filter: string, isExclusive: boolean) => void+ tnMapping: Record<string, string>+ canChangeExclusive?: boolean+ removable?: boolean+}++export const Filter = ({+ column,+ filter,+ isExclusive,+ onRemoveFilter,+ onChangeExclusive,+ tnMapping,+ canChangeExclusive,+ removable,+}: IFilter): JSX.Element => {+ const {+ t,+ i18n: { language },+ } = useTranslation('common')++ let displayColumn = tnMapping[column]+ let displayFilter = filter++ if (column === 'cc') {+ displayFilter = countries.getName(filter, language) as string+ }++ if (column === 'pg') {+ displayFilter = filter || t('project.redactedPage')+ }++ if (column === 'lc') {+ displayFilter = getLocaleDisplayName(displayFilter, language)+ }++ if (_startsWith(column, 'ev:key:')) {+ const key = _replace(column, /^ev:key:/, '')+ displayColumn = t('project.metamapping.ev.dynamicKey', {+ key,+ })+ }++ if (_startsWith(column, 'tag:key:')) {+ const key = _replace(column, /^tag:key:/, '')+ displayColumn = t('project.metamapping.tag.dynamicKey', {+ key,+ })+ }++ const truncatedFilter = _truncate(displayFilter)++ return (+ <span+ title={truncatedFilter === displayFilter ? undefined : displayFilter}+ className={cx(+ 'm-1 inline-flex items-center rounded-md bg-gray-50 py-0.5 pl-2.5 pr-1 text-sm font-medium text-gray-800 dark:bg-slate-800 dark:text-gray-50',+ {+ 'pr-2': !removable,+ },+ )}+ >+ {displayColumn}+ + {canChangeExclusive ? (+ <span+ className='cursor-pointer border-b-2 border-dotted border-blue-400 text-blue-400'+ onClick={() => onChangeExclusive(column, filter, !isExclusive)}+ >+ {t(`common.${isExclusive ? 'isNot' : 'is'}`)}+ </span>+ ) : (+ <span>{t(`common.${isExclusive ? 'isNot' : 'is'}`)}</span>+ )}+ "+ {truncatedFilter}+ "+ {removable && (+ <button+ onClick={() => onRemoveFilter(column, filter)}+ type='button'+ className='ml-0.5 inline-flex h-4 w-4 flex-shrink-0 items-center justify-center rounded-full text-gray-800 hover:bg-gray-300 hover:text-gray-900 focus:bg-gray-300 focus:text-gray-900 focus:outline-none dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-gray-800 dark:hover:text-gray-300 dark:focus:bg-gray-800 dark:focus:text-gray-300 '+ >+ <span className='sr-only'>Remove filter</span>+ <svg className='h-2 w-2' stroke='currentColor' fill='none' viewBox='0 0 8 8'>+ <path strokeLinecap='round' strokeWidth='1.5' d='M1 1l6 6m0-6L1 7' />+ </svg>+ </button>+ )}+ </span>+ )+}++interface IFilters {+ metrics: IProjectViewCustomEvent[]+ onRemoveMetric: (column: string, filter: string) => void+ resetMetrics: () => void+}++const CustomMetrics = ({ metrics, onRemoveMetric, resetMetrics }: IFilters) => {+ if (_isEmpty(metrics)) {+ return null+ }++ return (+ <div className='flex items-center justify-between rounded-md bg-slate-200 p-1 shadow dark:border dark:border-slate-800/50 dark:bg-slate-800/25'>+ <div className=' flex items-center'>+ <FunnelIcon className='box-content size-6 flex-shrink-0 px-1 text-gray-700 dark:text-gray-200' />+ <div className='flex flex-wrap'>+ {_map(metrics, (props) => {+ return <div key={JSON.stringify(props)}>{JSON.stringify(props)}</div>+ })}+ </div>+ </div>+ <XMarkIcon+ className='box-content size-6 flex-shrink-0 cursor-pointer stroke-2 px-1 text-gray-800 hover:text-gray-600 dark:text-gray-200 dark:hover:text-gray-300'+ onClick={resetMetrics}+ />+ </div>+ )+}++export default memo(CustomMetrics)diff --git a/app/pages/Project/View/components/MetricCards.tsx b/app/pages/Project/View/components/MetricCards.tsxindex 4c017ea69..c33b114b8 100644--- a/app/pages/Project/View/components/MetricCards.tsx+++ b/app/pages/Project/View/components/MetricCards.tsx@@ -174,21 +174,19 @@ const MetricCards = ({ overall, overallCompare, activePeriodCompare }: IMetricCaif (overall.customEVFilterApplied) {return (- <div className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'>- <MetricCard- label={t('project.events')}- value={overall.current?.all}- change={allChange}- type='percent'- goodChangeDirection='down'- valueMapper={(value, type) => `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`}- />- </div>+ <MetricCard+ label={t('project.events')}+ value={overall.current?.all}+ change={allChange}+ type='percent'+ goodChangeDirection='down'+ valueMapper={(value, type) => `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`}+ />)}return (- <div className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'>+ <><MetricCardlabel={t('dashboard.unique')}value={overall.current?.unique}@@ -222,7 +220,7 @@ const MetricCards = ({ overall, overallCompare, activePeriodCompare }: IMetricCa`${type === 'badge' && value > 0 ? '+' : ''}${getStringFromTime(getTimeFromSeconds(value))}`}/>- </div>+ </>)}