Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Additional filters (#358)

Uku Tahte228fd1f85f5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aa5a232af0..666564b1dc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@ All notable changes to this project will be documented in this file.
### Added
- Linkify top pages [plausible/analytics#91](https://github.com/plausible/analytics/issues/91)
+- Filter by country, screen size, browser and operating system [plausible/analytics#303](https://github.com/plausible/analytics/issues/303)
### Fixed
- Fix issue with creating a PostgreSQL database when `?ssl=true` [plausible/analytics#347](https://github.com/plausible/analytics/issues/347)
diff --git a/assets/css/app.css b/assets/css/app.css
index 34b6c29e77..9b40219efd 100644
--- a/assets/css/app.css
+++ b/assets/css/app.css
@@ -256,3 +256,7 @@ blockquote {
right: 2px;
top: calc(100% - 12px);
}
+
+.datamaps-subunit {
+ cursor: pointer;
+}
diff --git a/assets/js/dashboard/filters.js b/assets/js/dashboard/filters.js
index 42f8586f1d..36bad839ad 100644
--- a/assets/js/dashboard/filters.js
+++ b/assets/js/dashboard/filters.js
@@ -1,6 +1,7 @@
import React from 'react';
import { withRouter } from 'react-router-dom'
import {removeQueryParam} from './query'
+import Datamap from 'datamaps'
function filterText(key, value) {
if (key === "goal") {
@@ -21,6 +22,20 @@ function filterText(key, value) {
if (key === "referrer") {
return <span className="inline-block max-w-sm truncate">Referrer: <b>{value}</b></span>
}
+ if (key === "screen") {
+ return <span className="inline-block max-w-sm truncate">Screen size: <b>{value}</b></span>
+ }
+ if (key === "browser") {
+ return <span className="inline-block max-w-sm truncate">Browser: <b>{value}</b></span>
+ }
+ if (key === "os") {
+ return <span className="inline-block max-w-sm truncate">Operating System: <b>{value}</b></span>
+ }
+ if (key === "country") {
+ const allCountries = Datamap.prototype.worldTopo.objects.world.geometries;
+ const selectedCountry = allCountries.find((c) => c.id === value)
+ return <span className="inline-block max-w-sm truncate">Country: <b>{selectedCountry.properties.name}</b></span>
+ }
if (key === "page") {
return <span className="inline-block max-w-sm truncate">Page: <b>{value}</b></span>
}
diff --git a/assets/js/dashboard/query.js b/assets/js/dashboard/query.js
index e2f9a434be..e27f95b7c5 100644
--- a/assets/js/dashboard/query.js
+++ b/assets/js/dashboard/query.js
@@ -29,6 +29,10 @@ export function parseQuery(querystring, site) {
'utm_source': q.get('utm_source'),
'utm_campaign': q.get('utm_campaign'),
'referrer': q.get('referrer'),
+ 'screen': q.get('screen'),
+ 'browser': q.get('browser'),
+ 'os': q.get('os'),
+ 'country': q.get('country'),
'page': q.get('page')
}
}
diff --git a/assets/js/dashboard/stats/countries.js b/assets/js/dashboard/stats/countries.js
index 1d24a622f3..88e5d29230 100644
--- a/assets/js/dashboard/stats/countries.js
+++ b/assets/js/dashboard/stats/countries.js
@@ -1,5 +1,6 @@
import React from 'react';
import Datamap from 'datamaps'
+import { withRouter } from 'react-router-dom'
import numberFormatter from '../number-formatter'
import FadeIn from '../fade-in'
@@ -7,7 +8,7 @@ import Bar from './bar'
import MoreLink from './more-link'
import * as api from '../api'
-export default class Countries extends React.Component {
+class Countries extends React.Component {
constructor(props) {
super(props)
this.resizeMap = this.resizeMap.bind(this)
@@ -89,6 +90,13 @@ export default class Countries extends React.Component {
'<br><strong>', numberFormatter(data.numberOfThings), '</strong> ' + pluralizedLabel,
'</div>'].join('');
}
+ },
+ done: (datamap) => {
+ datamap.svg.selectAll('.datamaps-subunit').on('click', (geography) => {
+ const query = new URLSearchParams(window.location.search)
+ query.set('country', geography.id)
+ this.props.history.push({search: query.toString()})
+ })
}
});
}
@@ -116,3 +124,5 @@ export default class Countries extends React.Component {
)
}
}
+
+export default withRouter(Countries)
diff --git a/assets/js/dashboard/stats/devices.js b/assets/js/dashboard/stats/devices.js
index 3762d63c97..3ec85b44b0 100644
--- a/assets/js/dashboard/stats/devices.js
+++ b/assets/js/dashboard/stats/devices.js
@@ -1,4 +1,5 @@
import React from 'react';
+import { Link } from 'react-router-dom'
import numberFormatter from '../number-formatter'
import Bar from './bar'
@@ -63,11 +64,18 @@ class ScreenSizes extends React.Component {
}
renderScreenSize(size) {
+ const query = new URLSearchParams(window.location.search)
+ query.set('screen', size.name)
+
return (
<div className="flex items-center justify-between my-1 text-sm" key={size.name}>
<div className="w-full h-8" style={{maxWidth: 'calc(100% - 6rem)'}}>
<Bar count={size.count} all={this.state.sizes} bg="bg-green-50" />
- <span tooltip={EXPLANATION[size.name]} className="block px-2" style={{marginTop: '-26px'}}>{iconFor(size.name)} {size.name}</span>
+ <span tooltip={EXPLANATION[size.name]} className="flex px-2" style={{marginTop: '-26px'}} >
+ <Link className="block truncate hover:underline" to={{search: query.toString()}}>
+ {iconFor(size.name)} {size.name}
+ </Link>
+ </span>
</div>
<span className="font-medium">{numberFormatter(size.count)} <span className="inline-block text-xs w-8 text-right">({size.percentage}%)</span></span>
</div>
@@ -130,11 +138,18 @@ class Browsers extends React.Component {
}
renderBrowser(browser) {
+ const query = new URLSearchParams(window.location.search)
+ query.set('browser', browser.name)
+
return (
<div className="flex items-center justify-between my-1 text-sm" key={browser.name}>
<div className="w-full h-8" style={{maxWidth: 'calc(100% - 6rem)'}}>
<Bar count={browser.count} all={this.state.browsers} bg="bg-green-50" />
- <span className="block px-2" style={{marginTop: '-26px'}}>{browser.name}</span>
+ <span className="flex px-2" style={{marginTop: '-26px'}} >
+ <Link className="block truncate hover:underline" to={{search: query.toString()}}>
+ {browser.name}
+ </Link>
+ </span>
</div>
<span className="font-medium">{numberFormatter(browser.count)} <span className="inline-block text-xs w-8 text-right">({browser.percentage}%)</span></span>
</div>
@@ -197,11 +212,18 @@ class OperatingSystems extends React.Component {
}
renderOperatingSystem(os) {
+ const query = new URLSearchParams(window.location.search)
+ query.set('os', os.name)
+
return (
<div className="flex items-center justify-between my-1 text-sm" key={os.name}>
<div className="w-full h-8" style={{maxWidth: 'calc(100% - 6rem)'}}>
<Bar count={os.count} all={this.state.operatingSystems} bg="bg-green-50" />
- <span className="block px-2" style={{marginTop: '-26px'}}>{os.name}</span>
+ <span className="flex px-2" style={{marginTop: '-26px'}}>
+ <Link className="block truncate hover:underline" to={{search: query.toString()}}>
+ {os.name}
+ </Link>
+ </span>
</div>
<span className="font-medium">{numberFormatter(os.count)} <span className="inline-block text-xs w-8 text-right">({os.percentage}%)</span></span>
</div>
diff --git a/assets/js/dashboard/stats/modals/countries.js b/assets/js/dashboard/stats/modals/countries.js
index 08f51f2b89..85a196a8fd 100644
--- a/assets/js/dashboard/stats/modals/countries.js
+++ b/assets/js/dashboard/stats/modals/countries.js
@@ -1,5 +1,5 @@
import React from "react";
-import { withRouter } from 'react-router-dom'
+import { Link, withRouter } from 'react-router-dom'
import Modal from './modal'
import * as api from '../../api'
@@ -22,9 +22,16 @@ class CountriesModal extends React.Component {
}
renderCountry(country) {
+ const query = new URLSearchParams(window.location.search)
+ query.set('country', country.name)
+
return (
<tr className="text-sm" key={country.name}>
- <td className="p-2">{country.full_country_name}</td>
+ <td className="p-2">
+ <Link className="hover:underline" to={{search: query.toString(), pathname: '/' + encodeURIComponent(this.props.site.domain)}}>
+ {country.full_country_name}
+ </Link>
+ </td>
<td className="p-2 w-32 font-medium" align="right">
{numberFormatter(country.count)} <span className="inline-block text-xs w-8 text-right">({country.percentage}%)</span>
</td>
diff --git a/lib/plausible/stats/clickhouse.ex b/lib/plausible/stats/clickhouse.ex
index d3179d8830..d32f5af96a 100644
--- a/lib/plausible/stats/clickhouse.ex
+++ b/lib/plausible/stats/clickhouse.ex
@@ -701,6 +701,38 @@ defmodule Plausible.Stats.Clickhouse do
sessions_q
end
+ sessions_q =
+ if query.filters["screen"] do
+ size = query.filters["screen"]
+ from(s in sessions_q, where: s.screen_size == ^size)
+ else
+ sessions_q
+ end
+
+ sessions_q =
+ if query.filters["browser"] do
+ browser = query.filters["browser"]
+ from(s in sessions_q, where: s.browser == ^browser)
+ else
+ sessions_q
+ end
+
+ sessions_q =
+ if query.filters["os"] do
+ os = query.filters["os"]
+ from(s in sessions_q, where: s.operating_system == ^os)
+ else
+ sessions_q
+ end
+
+ sessions_q =
+ if query.filters["country"] do
+ country = Plausible.Stats.CountryName.to_alpha2(query.filters["country"])
+ from(s in sessions_q, where: s.country_code == ^country)
+ else
+ sessions_q
+ end
+
sessions_q =
if query.filters["utm_medium"] do
utm_medium = query.filters["utm_medium"]
@@ -738,7 +770,7 @@ defmodule Plausible.Stats.Clickhouse do
where: e.timestamp >= ^first_datetime and e.timestamp < ^last_datetime
)
- q = if query.filters["source"] || query.filters['referrer'] || query.filters["utm_medium"] || query.filters["utm_source"] || query.filters["utm_campaign"] do
+ q = if query.filters["source"] || query.filters['referrer'] || query.filters["utm_medium"] || query.filters["utm_source"] || query.filters["utm_campaign"] || query.filters["screen"] || query.filters["browser"] || query.filters["os"] || query.filters["country"] do
from(
e in q,
join: sq in subquery(sessions_q),
@@ -774,6 +806,38 @@ defmodule Plausible.Stats.Clickhouse do
q
end
+ q =
+ if query.filters["screen"] do
+ size = query.filters["screen"]
+ from(s in q, where: s.screen_size == ^size)
+ else
+ q
+ end
+
+ q =
+ if query.filters["browser"] do
+ browser = query.filters["browser"]
+ from(s in q, where: s.browser == ^browser)
+ else
+ q
+ end
+
+ q =
+ if query.filters["os"] do
+ os = query.filters["os"]
+ from(s in q, where: s.operating_system == ^os)
+ else
+ q
+ end
+
+ q =
+ if query.filters["country"] do
+ country = Plausible.Stats.CountryName.to_alpha2(query.filters["country"])
+ from(s in q, where: s.country_code == ^country)
+ else
+ q
+ end
+
q =
if query.filters["utm_medium"] do
utm_medium = query.filters["utm_medium"]
@@ -833,6 +897,38 @@ defmodule Plausible.Stats.Clickhouse do
q
end
+ q =
+ if query.filters["screen"] do
+ size = query.filters["screen"]
+ from(e in q, where: e.screen_size == ^size)
+ else
+ q
+ end
+
+ q =
+ if query.filters["browser"] do
+ browser = query.filters["browser"]
+ from(s in q, where: s.browser == ^browser)
+ else
+ q
+ end
+
+ q =
+ if query.filters["os"] do
+ os = query.filters["os"]
+ from(s in q, where: s.operating_system == ^os)
+ else
+ q
+ end
+
+ q =
+ if query.filters["country"] do
+ country = Plausible.Stats.CountryName.to_alpha2(query.filters["country"])
+ from(s in q, where: s.country_code == ^country)
+ else
+ q
+ end
+
q =
if query.filters["utm_medium"] do
utm_medium = query.filters["utm_medium"]
diff --git a/lib/plausible/stats/countries.ex b/lib/plausible/stats/countries.ex
index adb2ca5632..22df0ee072 100644
--- a/lib/plausible/stats/countries.ex
+++ b/lib/plausible/stats/countries.ex
@@ -493,10 +493,18 @@ defmodule Plausible.Stats.CountryName do
"EH" => "ESH"
}
+ @alpha2_codes @alpha3_codes
+ |> Enum.map(fn {k, v} -> {v, k} end)
+ |> Enum.into(%{})
+
def to_alpha3(code) do
Map.get(@alpha3_codes, code, code)
end
+ def to_alpha2(code) do
+ Map.get(@alpha2_codes, code, code)
+ end
+
def from_iso3166(code) do
Map.get(@country_codes_to_names, code, code)
end
diff --git a/test/plausible_web/controllers/api/stats_controller/main_graph_test.exs b/test/plausible_web/controllers/api/stats_controller/main_graph_test.exs
index 2da5f0d554..f0c3cb607a 100644
--- a/test/plausible_web/controllers/api/stats_controller/main_graph_test.exs
+++ b/test/plausible_web/controllers/api/stats_controller/main_graph_test.exs
@@ -153,4 +153,60 @@ defmodule PlausibleWeb.Api.StatsController.MainGraphTest do
]
end
end
+
+ describe "GET /api/stats/main-graph - top stats - filters" do
+ setup [:create_user, :log_in, :create_site]
+
+ test "returns only visitors from a country based on alpha3 code", %{conn: conn, site: site} do
+ filters = Jason.encode!(%{country: "USA"})
+
+ conn =
+ get(
+ conn,
+ "/api/stats/#{site.domain}/main-graph?period=month&date=2019-01-01&filters=#{filters}"
+ )
+
+ res = json_response(conn, 200)
+ assert %{"name" => "Unique visitors", "count" => 4, "change" => 100} in res["top_stats"]
+ end
+
+ test "returns only visitors with specific screen size", %{conn: conn, site: site} do
+ filters = Jason.encode!(%{screen: "Desktop"})
+
+ conn =
+ get(
+ conn,
+ "/api/stats/#{site.domain}/main-graph?period=month&date=2019-01-01&filters=#{filters}"
+ )
+
+ res = json_response(conn, 200)
+ assert %{"name" => "Unique visitors", "count" => 4, "change" => 100} in res["top_stats"]
+ end
+
+ test "returns only visitors with specific browser", %{conn: conn, site: site} do
+ filters = Jason.encode!(%{browser: "Chrome"})
+
+ conn =
+ get(
+ conn,
+ "/api/stats/#{site.domain}/main-graph?period=month&date=2019-01-01&filters=#{filters}"
+ )
+
+ res = json_response(conn, 200)
+ assert %{"name" => "Unique visitors", "count" => 4, "change" => 100} in res["top_stats"]
+ end
+
+ test "returns only visitors with specific operating system", %{conn: conn, site: site} do
+ filters = Jason.encode!(%{os: "Mac"})
+
+ conn =
+ get(
+ conn,
+ "/api/stats/#{site.domain}/main-graph?period=month&date=2019-01-01&filters=#{filters}"
+ )
+
+ res = json_response(conn, 200)
+ assert %{"name" => "Unique visitors", "count" => 4, "change" => 100} in res["top_stats"]
+ end
+ end
end
diff --git a/test/support/clickhouse_setup.ex b/test/support/clickhouse_setup.ex
index 63ab33a77c..4e6de6ee69 100644
--- a/test/support/clickhouse_setup.ex
+++ b/test/support/clickhouse_setup.ex
@@ -148,6 +148,10 @@ defmodule Plausible.Test.ClickhouseSetup do
referrer_source: "10words",
referrer: "10words.com/page1",
utm_medium: "listing",
+ country_code: "US",
+ screen_size: "Desktop",
+ browser: "Chrome",
+ operating_system: "Mac",
session_id: @conversion_1_session_id,
is_bounce: true,
duration: 100,