Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

charts refactoring

kruzhambus969f8767b204
diff --git a/src/api/index.js b/src/api/index.js
index ad7de3a61..b9db7085d 100644
--- a/src/api/index.js
+++ b/src/api/index.js
@@ -231,9 +231,9 @@ export const getSharedProjects = (take = 0, skip = 0) =>
: error.response.data.message
})
-export const getProject = (pid) =>
+export const getProject = (pid, isCaptcha = false) =>
api
- .get(`/project/${pid}`)
+ .get(`/project/${pid}&isCaptcha=${isCaptcha}`)
.then((response) => response.data)
.catch((error) => {
debug('%s', error)
@@ -328,6 +328,26 @@ export const getPerfData = (
: error.response.data.message
})
+export const getCaptchaData = (
+ pid,
+ tb = 'hour',
+ period = '3d',
+ filters = [],
+ from = '',
+ to = '',
+) =>
+ api
+ .get(
+ `log/captcha?pid=${pid}&timeBucket=${tb}&period=${period}&filters=${JSON.stringify(filters)}&from=${from}&to=${to}`,
+ )
+ .then((response) => response.data)
+ .catch((error) => {
+ debug('%s', error)
+ throw _isEmpty(error.response.data?.message)
+ ? error.response.data
+ : error.response.data.message
+ })
+
export const getOverallStats = (pids) =>
api
.get(`log/birdseye?pids=[${_map(pids, (pid) => `"${pid}"`).join(',')}]`)
diff --git a/src/pages/Captcha/View/ViewCaptcha.helpers.jsx b/src/pages/Captcha/View/ViewCaptcha.helpers.jsx
index 2e13da849..c9bb36280 100644
--- a/src/pages/Captcha/View/ViewCaptcha.helpers.jsx
+++ b/src/pages/Captcha/View/ViewCaptcha.helpers.jsx
@@ -16,8 +16,6 @@ import _isEmpty from 'lodash/isEmpty'
import _keys from 'lodash/keys'
import _size from 'lodash/size'
import _round from 'lodash/round'
-import _fill from 'lodash/fill'
-import _reduce from 'lodash/reduce'
import JSZip from 'jszip'
import {
@@ -26,51 +24,6 @@ import {
import { getTimeFromSeconds, getStringFromTime } from 'utils/generic'
import countries from 'utils/isoCountries'
-const getAvg = (arr) => {
- const total = _reduce(arr, (acc, c) => acc + c, 0)
- return total / _size(arr)
-}
-
-const getSum = (arr) => {
- return _reduce(arr, (acc, c) => acc + c, 0)
-}
-
-const trendline = (data) => {
- const xData = _map(_fill(new Array(_size(data)), 0), (_, i) => i + 1)
- const yData = data
-
- const xMean = getAvg(xData)
- const yMean = getAvg(yData)
-
- const xMinusxMean = _map(xData, (val) => val - xMean)
- const yMinusyMean = _map(yData, (val) => val - yMean)
-
- const xMinusxMeanSq = _map(xMinusxMean, (val) => val ** 2)
-
- const xy = []
- for (let x = 0; x < _size(data); ++x) {
- xy.push(xMinusxMean[x] * yMinusyMean[x])
- }
-
- const xySum = getSum(xy)
-
- const b1 = xySum / getSum(xMinusxMeanSq)
-
- const b0 = yMean - b1 * xMean
-
- const trendData = []
- for (let x = 0; x < _size(data); ++x) {
- const y = _round(b0 + b1 * x, 2)
- if (y < 0) {
- trendData.push(0)
- } else {
- trendData.push(y)
- }
- }
-
- return trendData
-}
-
const getExportFilename = (prefix) => {
// turn something like 2022-03-02T19:31:00.100Z into 2022-03-02
const date = _split(_replace(_split(new Date().toISOString(), '.')[0], /:/g, '-'), 'T')[0]
@@ -131,17 +84,12 @@ const onCSVExportClick = (data, pid, tnMapping, language) => {
const CHART_METRICS_MAPPING = {
unique: 'unique',
- views: 'views',
- bounce: 'bounce',
- viewsPerUnique: 'viewsPerUnique',
- trendlines: 'trendlines',
- sessionDuration: 'sessionDuration',
}
// function to filter the data for the chart
const getColumns = (chart, activeChartMetrics) => {
const {
- views, bounce, viewsPerUnique, unique, trendlines, sessionDuration,
+ unique,
} = activeChartMetrics
const columns = [
@@ -150,39 +98,6 @@ const getColumns = (chart, activeChartMetrics) => {
if (unique) {
columns.push(['unique', ...chart.uniques])
- if (trendlines) {
- columns.push(['trendlineUnique', ...trendline(chart.uniques)])
- }
- }
-
- if (views) {
- columns.push(['total', ...chart.visits])
- if (trendlines) {
- columns.push(['trendlineTotal', ...trendline(chart.visits)])
- }
- }
-
- if (bounce) {
- const bounceArray = _map(chart.uniques, (el, i) => {
- return _round((el * 100) / chart.visits[i], 1) || 0
- })
- columns.push(
- ['bounce', ...bounceArray],
- )
- }
-
- if (viewsPerUnique) {
- const viewsPerUniqueArray = _map(chart.visits, (el, i) => {
- if (chart.uniques[i] === 0 || chart.uniques[i] === undefined) {
- return 0
- }
- return _round(el / chart.uniques[i], 1)
- })
- columns.push(['viewsPerUnique', ...viewsPerUniqueArray])
- }
-
- if (sessionDuration) {
- columns.push(['sessionDuration', ...chart.sdur])
}
return columns
@@ -216,30 +131,6 @@ const getSettings = (chart, timeBucket, activeChartMetrics, applyRegions, timeFo
},
},
],
- total: [
- {
- start: regionStart,
- style: {
- dasharray: '6 2',
- },
- },
- ],
- bounce: [
- {
- start: regionStart,
- style: {
- dasharray: '6 2',
- },
- },
- ],
- viewsPerUnique: [
- {
- start: regionStart,
- style: {
- dasharray: '6 2',
- },
- },
- ],
}
}
@@ -249,27 +140,11 @@ const getSettings = (chart, timeBucket, activeChartMetrics, applyRegions, timeFo
columns: getColumns(modifiedChart, activeChartMetrics),
types: {
unique: chartType === chartTypes.line ? area() : bar(),
- total: chartType === chartTypes.line ? area() : bar(),
- bounce: chartType === chartTypes.line ? spline() : bar(),
- viewsPerUnique: chartType === chartTypes.line ? spline() : bar(),
- trendlineUnique: spline(),
- trendlineTotal: spline(),
- sessionDuration: chartType === chartTypes.line ? spline() : bar(),
},
colors: {
unique: '#2563EB',
- total: '#D97706',
- bounce: '#2AC4B3',
- viewsPerUnique: '#F87171',
- trendlineUnique: '#436abf',
- trendlineTotal: '#eba14b',
- sessionDuration: '#c945ed',
},
regions,
- axes: {
- bounce: 'y2',
- sessionDuration: 'y2',
- },
},
grid: {
x: {
@@ -287,15 +162,6 @@ const getSettings = (chart, timeBucket, activeChartMetrics, applyRegions, timeFo
localtime: timeFormat === TimeFormat['24-hour'],
type: 'timeseries',
},
- y2: {
- show: activeChartMetrics.bounce || activeChartMetrics.sessionDuration,
- tick: {
- format: activeChartMetrics.bounce ? (d) => `${d}%` : (d) => getStringFromTime(getTimeFromSeconds(d)),
- },
- min: activeChartMetrics.bounce ? 10 : null,
- max: activeChartMetrics.bounce ? 100 : null,
- default: activeChartMetrics.bounce ? [10, 100] : null,
- },
},
tooltip: {
format: {
diff --git a/src/pages/Captcha/View/ViewCaptcha.jsx b/src/pages/Captcha/View/ViewCaptcha.jsx
index d0cc49ebe..43abdcbb0 100644
--- a/src/pages/Captcha/View/ViewCaptcha.jsx
+++ b/src/pages/Captcha/View/ViewCaptcha.jsx
@@ -43,7 +43,7 @@ import FlatPicker from 'ui/Flatpicker'
import PaidFeature from 'modals/PaidFeature'
import routes from 'routes'
import {
- getProjectData, getProject, getOverallStats, getLiveVisitors,
+ getProject, getOverallStats, getLiveVisitors, getCaptchaData,
} from 'api'
import {
Panel, Overview, CustomEvents,
@@ -82,11 +82,6 @@ const ViewProject = ({
const [dataLoading, setDataLoading] = useState(false)
const [activeChartMetrics, setActiveChartMetrics] = useState({
[CHART_METRICS_MAPPING.unique]: true,
- [CHART_METRICS_MAPPING.views]: false,
- [CHART_METRICS_MAPPING.sessionDuration]: false,
- [CHART_METRICS_MAPPING.bounce]: false,
- [CHART_METRICS_MAPPING.viewsPerUnique]: false,
- [CHART_METRICS_MAPPING.trendlines]: false,
})
const [sessionDurationAVG, setSessionDurationAVG] = useState(null)
const checkIfAllMetricsAreDisabled = useMemo(() => !_some(activeChartMetrics, (value) => value), [activeChartMetrics])
@@ -116,45 +111,12 @@ const ViewProject = ({
label: t('dashboard.unique'),
active: activeChartMetrics[CHART_METRICS_MAPPING.unique],
},
- {
- id: CHART_METRICS_MAPPING.views,
- label: t('project.showAll'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.views],
- },
- {
- id: CHART_METRICS_MAPPING.sessionDuration,
- label: t('dashboard.sessionDuration'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.sessionDuration],
- conflicts: [CHART_METRICS_MAPPING.bounce],
- },
- {
- id: CHART_METRICS_MAPPING.bounce,
- label: t('dashboard.bounceRate'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.bounce],
- conflicts: [CHART_METRICS_MAPPING.sessionDuration],
- },
- {
- id: CHART_METRICS_MAPPING.viewsPerUnique,
- label: t('dashboard.viewsPerUnique'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.viewsPerUnique],
- },
- {
- id: CHART_METRICS_MAPPING.trendlines,
- label: t('dashboard.trendlines'),
- active: activeChartMetrics[CHART_METRICS_MAPPING.trendlines],
- },
]
}, [t, activeChartMetrics])
const dataNames = useMemo(() => {
return {
unique: t('project.unique'),
- total: t('project.total'),
- bounce: `${t('dashboard.bounceRate')} (%)`,
- viewsPerUnique: t('dashboard.viewsPerUnique'),
- trendlineTotal: t('project.trendlineTotal'),
- trendlineUnique: t('project.trendlineUnique'),
- sessionDuration: t('dashboard.sessionDuration'),
}
}, [t])
@@ -193,9 +155,9 @@ const ViewProject = ({
data = cache[id][key]
} else {
if (period === 'custom' && dateRange) {
- data = await getProjectData(id, timeBucket, '', newFilters || filters, from, to)
+ data = await getCaptchaData(id, timeBucket, '', newFilters || filters, from, to)
} else {
- data = await getProjectData(id, timeBucket, period, newFilters || filters, '', '')
+ data = await getCaptchaData(id, timeBucket, period, newFilters || filters, '', '')
}
setProjectCache(id, data || {}, key)
@@ -339,68 +301,6 @@ const ViewProject = ({
}
}
- useEffect(() => {
- if (!isLoading && !_isEmpty(chartData) && !_isEmpty(mainChart)) {
- if (activeChartMetrics.views || activeChartMetrics.unique || activeChartMetrics.viewsPerUnique || activeChartMetrics.trendlines) {
- mainChart.load({
- columns: getColumns(chartData, activeChartMetrics),
- })
- }
-
- if (activeChartMetrics.bounce || activeChartMetrics.sessionDuration || activeChartMetrics.views || activeChartMetrics.unique) {
- const applyRegions = !_includes(noRegionPeriods, activePeriod.period)
- const bbSettings = getSettings(chartData, timeBucket, activeChartMetrics, applyRegions, timeFormat, rotateXAxias, chartType)
-
- if (!_isEmpty(mainChart)) {
- mainChart.destroy()
- }
-
- setMainChart(() => {
- const generete = bb.generate(bbSettings)
- generete.data.names(dataNames)
- return generete
- })
- }
-
- if (!activeChartMetrics.bounce || !activeChartMetrics.sessionDuration || activeChartMetrics.views || activeChartMetrics.unique) {
- const applyRegions = !_includes(noRegionPeriods, activePeriod.period)
- const bbSettings = getSettings(chartData, timeBucket, activeChartMetrics, applyRegions, timeFormat, rotateXAxias, chartType)
-
- if (!_isEmpty(mainChart)) {
- mainChart.destroy()
- }
-
- setMainChart(() => {
- const generete = bb.generate(bbSettings)
- generete.data.names(dataNames)
- return generete
- })
- }
-
- if (!activeChartMetrics.views) {
- mainChart.unload({
- ids: 'total',
- })
- }
-
- if (!activeChartMetrics.unique) {
- mainChart.unload({
- ids: 'unique',
- })
- }
-
- if (!activeChartMetrics.viewsPerUnique) {
- mainChart.unload({
- ids: 'viewsPerUnique',
- })
- }
- }
- }, [isLoading, activeChartMetrics, chartData]) // eslint-disable-line
-
- useEffect(() => {
- setPeriodPairs(tbPeriodPairs(t))
- }, [t])
-
// Parsing initial filters from the address bar
useEffect(() => {
// using try/catch because new URL is not supported by browsers like IE, so at least analytics would work without parsing filters
@@ -514,7 +414,7 @@ const ViewProject = ({
useEffect(() => {
if (!isLoading && _isEmpty(project)) {
- getProject(id)
+ getProject(id, true)
.then(projectRes => {
if (!_isEmpty(projectRes)) {
getOverallStats([id])
@@ -637,14 +537,6 @@ const ViewProject = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
- const isConflicted = (conflicts) => {
- const conflicted = conflicts && _some(conflicts, (conflict) => {
- const conflictPair = _find(chartMetrics, (metric) => metric.id === conflict)
- return conflictPair && conflictPair.active
- })
- return conflicted
- }
-
const resetFilters = () => {
const url = new URL(window.location)
const { searchParams } = url
@@ -796,27 +688,20 @@ const ViewProject = ({
title={t('project.metricVis')}
labelExtractor={(pair) => {
const {
- label, id: pairID, active, conflicts,
+ label, id: pairID, active,
} = pair
- const conflicted = isConflicted(conflicts)
-
return (
<Checkbox
className={cx({ hidden: isPanelsDataEmpty || analyticsLoading })}
label={label}
- disabled={conflicted}
id={pairID}
checked={active}
/>
)
}}
keyExtractor={(pair) => pair.id}
- onSelect={({ id: pairID, conflicts }) => {
- if (isConflicted(conflicts)) {
- generateAlert(t('project.conflictMetric'), 'error')
- return
- }
+ onSelect={({ id: pairID }) => {
switchActiveChartMetric(pairID)
}}
/>