Skip to content

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

Show detailed comparison dates in top stats (#2804)

Vini Brasil9f036d3915b2
diff --git a/assets/js/dashboard/comparison-input.js b/assets/js/dashboard/comparison-input.js
index 631f40d8e4..dac7ff2a28 100644
--- a/assets/js/dashboard/comparison-input.js
+++ b/assets/js/dashboard/comparison-input.js
@@ -6,7 +6,7 @@ import { ChevronDownIcon } from '@heroicons/react/20/solid'
import classNames from 'classnames'
import * as storage from './util/storage'
import Flatpickr from 'react-flatpickr'
-import { formatISO, parseUTCDate } from './util/date.js'
+import { formatISO, parseUTCDate, formatDateRange } from './util/date.js'
const COMPARISON_MODES = {
'off': 'Disable comparison',
@@ -90,11 +90,9 @@ const ComparisonInput = function({ site, query, history }) {
navigateToQuery(history, query, { comparison: mode, compare_from: from, compare_to: to })
}
- const buildLabel = (query) => {
+ const buildLabel = (site, query) => {
if (query.comparison == "custom") {
- const from = query.compare_from.format('D MMM')
- const to = query.compare_to.format('D MMM')
- return `${from} - ${to}`
+ return formatDateRange(site, query.compare_from, query.compare_to)
} else {
return COMPARISON_MODES[query.comparison]
}
@@ -127,7 +125,7 @@ const ComparisonInput = function({ site, query, history }) {
<div className="min-w-32 md:w-48 md:relative">
<Menu as="div" className="relative inline-block pl-2 w-full">
<Menu.Button className="bg-white text-gray-800 text-xs md:text-sm font-medium dark:bg-gray-800 dark:hover:bg-gray-900 dark:text-gray-200 hover:bg-gray-200 flex md:px-3 px-2 py-2 items-center justify-between leading-tight rounded shadow cursor-pointer w-full truncate">
- <span className="truncate">{ buildLabel(query) }</span>
+ <span className="truncate">{ buildLabel(site, query) }</span>
<ChevronDownIcon className="hidden sm:inline-block h-4 w-4 md:h-5 md:w-5 text-gray-500 ml-2" aria-hidden="true" />
</Menu.Button>
<Transition
diff --git a/assets/js/dashboard/datepicker.js b/assets/js/dashboard/datepicker.js
index c42ac16da7..47273f6210 100644
--- a/assets/js/dashboard/datepicker.js
+++ b/assets/js/dashboard/datepicker.js
@@ -7,7 +7,6 @@ import {
shiftDays,
shiftMonths,
formatDay,
- formatDayShort,
formatMonthYYYY,
formatYear,
formatISO,
@@ -19,7 +18,8 @@ import {
isThisYear,
parseUTCDate,
isBefore,
- isAfter
+ isAfter,
+ formatDateRange
} from "./util/date";
import { navigateToQuery, QueryLink, QueryButton } from "./query";
import { shouldIgnoreKeypress } from "./keybinding.js"
@@ -137,7 +137,7 @@ function DisplayPeriod({query, site}) {
} if (query.period === 'all') {
return 'All time'
} if (query.period === 'custom') {
- return `${formatDayShort(query.from)} - ${formatDayShort(query.to)}`
+ return formatDateRange(site, query.from, query.to)
}
return 'Realtime'
}
diff --git a/assets/js/dashboard/stats/graph/top-stats.js b/assets/js/dashboard/stats/graph/top-stats.js
index ce15718446..b645a053e0 100644
--- a/assets/js/dashboard/stats/graph/top-stats.js
+++ b/assets/js/dashboard/stats/graph/top-stats.js
@@ -4,43 +4,64 @@ import { SecondsSinceLastLoad } from '../../util/seconds-since-last-load'
import classNames from "classnames";
import numberFormatter, { durationFormatter } from '../../util/number-formatter'
import { METRIC_MAPPING } from './graph-util'
+import { formatDateRange } from '../../util/date.js'
+
+function Maybe({condition, children}) {
+ if (condition) {
+ return children
+ } else {
+ return null
+ }
+}
export default class TopStats extends React.Component {
- renderComparison(name, comparison) {
+ renderPercentageComparison(name, comparison, forceDarkMode = false) {
const formattedComparison = numberFormatter(Math.abs(comparison))
+ const defaultClassName = classNames({
+ "text-xs dark:text-gray-100": !forceDarkMode,
+ "text-xs text-gray-100": forceDarkMode
+ })
+
+ const noChangeClassName = classNames({
+ "text-xs text-gray-700 dark:text-gray-300": !forceDarkMode,
+ "text-xs text-gray-300": forceDarkMode
+ })
+
if (comparison > 0) {
const color = name === 'Bounce rate' ? 'text-red-400' : 'text-green-500'
- return <span className="text-xs dark:text-gray-100"><span className={color + ' font-bold'}>&uarr;</span> {formattedComparison}%</span>
+ return <span className={defaultClassName}><span className={color + ' font-bold'}>&uarr;</span> {formattedComparison}%</span>
} else if (comparison < 0) {
const color = name === 'Bounce rate' ? 'text-green-500' : 'text-red-400'
- return <span className="text-xs dark:text-gray-100"><span className={color + ' font-bold'}>&darr;</span> {formattedComparison}%</span>
+ return <span className={defaultClassName}><span className={color + ' font-bold'}>&darr;</span> {formattedComparison}%</span>
} else if (comparison === 0) {
- return <span className="text-xs text-gray-700 dark:text-gray-300">&#12336; 0%</span>
+ return <span className={noChangeClassName}>&#12336; 0%</span>
+ } else {
+ return null
}
}
- topStatNumberShort(stat) {
- if (['visit duration', 'time on page'].includes(stat.name.toLowerCase())) {
- return durationFormatter(stat.value)
- } else if (['bounce rate', 'conversion rate'].includes(stat.name.toLowerCase())) {
- return stat.value + '%'
+ topStatNumberShort(name, value) {
+ if (['visit duration', 'time on page'].includes(name.toLowerCase())) {
+ return durationFormatter(value)
+ } else if (['bounce rate', 'conversion rate'].includes(name.toLowerCase())) {
+ return value + '%'
} else {
- return numberFormatter(stat.value)
+ return numberFormatter(value)
}
}
- topStatNumberLong(stat) {
- if (['visit duration', 'time on page'].includes(stat.name.toLowerCase())) {
- return durationFormatter(stat.value)
- } else if (['bounce rate', 'conversion rate'].includes(stat.name.toLowerCase())) {
- return stat.value + '%'
+ topStatNumberLong(name, value) {
+ if (['visit duration', 'time on page'].includes(name.toLowerCase())) {
+ return durationFormatter(value)
+ } else if (['bounce rate', 'conversion rate'].includes(name.toLowerCase())) {
+ return value + '%'
} else {
- return stat.value.toLocaleString()
+ return (value || 0).toLocaleString()
}
}
- topStatTooltip(stat) {
+ topStatTooltip(stat, query) {
let statName = stat.name.toLowerCase()
statName = stat.value === 1 ? statName.slice(0, -1) : statName
@@ -49,7 +70,15 @@ export default class TopStats extends React.Component {
return (
<div>
- <div className="whitespace-nowrap">{this.topStatNumberLong(stat)} {statName}</div>
+ {query.comparison && <div className="whitespace-nowrap">
+ {this.topStatNumberLong(stat.name, stat.value)} vs. {this.topStatNumberLong(stat.name, stat.comparison_value)} {statName}
+ <span className="ml-2">{this.renderPercentageComparison(stat.name, stat.change, true)}</span>
+ </div>}
+
+ {!query.comparison && <div className="whitespace-nowrap">
+ {this.topStatNumberLong(stat.name, stat.value)} {statName}
+ </div>}
+
{stat.name === 'Current visitors' && <p className="font-normal text-xs">Last updated <SecondsSinceLastLoad lastLoadTimestamp={lastLoadTimestamp}/>s ago</p>}
{stat.name === 'Views per visit' && showingImported && <p className="font-normal text-xs whitespace-nowrap">Based only on native data</p>}
</div>
@@ -95,7 +124,7 @@ export default class TopStats extends React.Component {
}
render() {
- const { topStatData, query } = this.props
+ const { topStatData, query, site } = this.props
const stats = topStatData && topStatData.top_stats.map((stat, index) => {
@@ -106,11 +135,27 @@ export default class TopStats extends React.Component {
})
return (
- <Tooltip key={stat.name} info={this.topStatTooltip(stat)} className={className} onClick={() => { this.maybeUpdateMetric(stat) }} boundary={this.props.tooltipBoundary}>
+ <Tooltip key={stat.name} info={this.topStatTooltip(stat, query)} className={className} onClick={() => { this.maybeUpdateMetric(stat) }} boundary={this.props.tooltipBoundary}>
{this.renderStatName(stat)}
- <div className="flex items-center justify-between my-1 whitespace-nowrap">
- <b className="mr-4 text-xl md:text-2xl dark:text-gray-100" id={METRIC_MAPPING[stat.name]}>{this.topStatNumberShort(stat)}</b>
- {this.renderComparison(stat.name, stat.change)}
+ <div className="my-1 space-y-2">
+ <div>
+ <span className="flex items-center justify-between whitespace-nowrap">
+ <p className="font-bold text-xl dark:text-gray-100" id={METRIC_MAPPING[stat.name]}>{this.topStatNumberShort(stat.name, stat.value)}</p>
+ <Maybe condition={!query.comparison}>
+ {this.renderPercentageComparison(stat.name, stat.change)}
+ </Maybe>
+ </span>
+ <Maybe condition={query.comparison}>
+ <p className="text-xs dark:text-gray-100">{ formatDateRange(site, topStatData.from, topStatData.to) }</p>
+ </Maybe>
+ </div>
+
+ <Maybe condition={query.comparison}>
+ <div>
+ <p className="font-bold text-xl text-gray-500 dark:text-gray-400">{ this.topStatNumberShort(stat.name, stat.comparison_value) }</p>
+ <p className="text-xs text-gray-500 dark:text-gray-400">{ formatDateRange(site, topStatData.comparing_from, topStatData.comparing_to) }</p>
+ </div>
+ </Maybe>
</div>
</Tooltip>
)
diff --git a/assets/js/dashboard/stats/graph/visitor-graph.js b/assets/js/dashboard/stats/graph/visitor-graph.js
index 6c101444df..a69c7856fc 100644
--- a/assets/js/dashboard/stats/graph/visitor-graph.js
+++ b/assets/js/dashboard/stats/graph/visitor-graph.js
@@ -323,7 +323,7 @@ class LineGraph extends React.Component {
return (
<div>
<div id="top-stats-container" className="flex flex-wrap" ref={this.boundary} style={{height: this.getTopStatsHeight()}}>
- <TopStats query={query} metric={metric} updateMetric={updateMetric} topStatData={topStatData} tooltipBoundary={this.boundary.current} lastLoadTimestamp={lastLoadTimestamp} />
+ <TopStats site={site} query={query} metric={metric} updateMetric={updateMetric} topStatData={topStatData} tooltipBoundary={this.boundary.current} lastLoadTimestamp={lastLoadTimestamp} />
</div>
<div className="relative px-2">
{mainGraphRefreshing && renderLoader()}
diff --git a/assets/js/dashboard/util/date.js b/assets/js/dashboard/util/date.js
index 193ac2c6e9..3777688be2 100644
--- a/assets/js/dashboard/util/date.js
+++ b/assets/js/dashboard/util/date.js
@@ -44,6 +44,21 @@ export function formatDayShort(date, includeYear = false) {
}
}
+export function formatDateRange(site, from, to) {
+ if (!from || !to) return
+ if (typeof from === 'string') from = parseUTCDate(from)
+ if (typeof to === 'string') to = parseUTCDate(to)
+
+ if (from.isSame(to)) {
+ return formatDay(from)
+ } else if (from.isSame(to, 'year')) {
+ const includeYear = !isThisYear(site, from)
+ return `${formatDayShort(from, false)} - ${formatDayShort(to, includeYear)}`
+ } else {
+ return `${formatDayShort(from, true)} - ${formatDayShort(to, true)}`
+ }
+}
+
export function parseUTCDate(dateString) {
return dayjs.utc(dateString)
}
diff --git a/lib/plausible_web/controllers/api/stats_controller.ex b/lib/plausible_web/controllers/api/stats_controller.ex
index 386df3b8a9..6ad0c0b885 100644
--- a/lib/plausible_web/controllers/api/stats_controller.ex
+++ b/lib/plausible_web/controllers/api/stats_controller.ex
@@ -190,19 +190,29 @@ defmodule PlausibleWeb.Api.StatsController do
site = conn.assigns[:site]
with :ok <- validate_params(params) do
+ query = Query.from(site, params) |> Filters.add_prefix()
+
comparison_mode = params["comparison"] || "previous_period"
comparison_opts = [from: params["compare_from"], to: params["compare_to"]]
- query = Query.from(site, params) |> Filters.add_prefix()
+ comparison_query =
+ case Stats.Comparisons.compare(site, query, comparison_mode, comparison_opts) do
+ {:ok, query} -> query
+ {:error, _cause} -> nil
+ end
- {top_stats, sample_percent} = fetch_top_stats(site, query, comparison_mode, comparison_opts)
+ {top_stats, sample_percent} = fetch_top_stats(site, query, comparison_query)
json(conn, %{
top_stats: top_stats,
interval: query.interval,
sample_percent: sample_percent,
with_imported: query.include_imported,
- imported_source: site.imported_data && site.imported_data.source
+ imported_source: site.imported_data && site.imported_data.source,
+ comparing_from: comparison_query && comparison_query.date_range.first,
+ comparing_to: comparison_query && comparison_query.date_range.last,
+ from: query.date_range.first,
+ to: query.date_range.last
})
else
{:error, message} when is_binary(message) -> bad_request(conn, message)
@@ -263,8 +273,7 @@ defmodule PlausibleWeb.Api.StatsController do
defp fetch_top_stats(
site,
%Query{period: "realtime", filters: %{"event:goal" => _goal}} = query,
- _comparison_mode,
- _comparison_opts
+ _comparison_query
) do
query_30m = %Query{query | period: "30m"}
@@ -291,12 +300,7 @@ defmodule PlausibleWeb.Api.StatsController do
{stats, 100}
end
- defp fetch_top_stats(
- site,
- %Query{period: "realtime"} = query,
- _comparison_mode,
- _comparison_opts
- ) do
+ defp fetch_top_stats(site, %Query{period: "realtime"} = query, _comparison_query) do
query_30m = %Query{query | period: "30m"}
%{
@@ -322,35 +326,26 @@ defmodule PlausibleWeb.Api.StatsController do
{stats, 100}
end
- defp fetch_top_stats(
- site,
- %Query{filters: %{"event:goal" => _goal}} = query,
- comparison_mode,
- comparison_opts
- ) do
+ defp fetch_top_stats(site, %Query{filters: %{"event:goal" => _goal}} = query, comparison_query) do
total_q = Query.remove_event_filters(query, [:goal, :props])
{prev_converted_visitors, prev_completions} =
- case Stats.Comparisons.compare(site, query, comparison_mode, comparison_opts) do
- {:ok, prev_query} ->
- %{visitors: %{value: prev_converted_visitors}, events: %{value: prev_completions}} =
- Stats.aggregate(site, prev_query, [:visitors, :events])
-
- {prev_converted_visitors, prev_completions}
+ if comparison_query do
+ %{visitors: %{value: prev_converted_visitors}, events: %{value: prev_completions}} =
+ Stats.aggregate(site, comparison_query, [:visitors, :events])
- {:error, :not_supported} ->
- {nil, nil}
+ {prev_converted_visitors, prev_completions}
+ else
+ {nil, nil}
end
prev_unique_visitors =
- case Stats.Comparisons.compare(site, total_q, comparison_mode) do
- {:ok, prev_total_query} ->
- site
- |> Stats.aggregate(prev_total_query, [:visitors])
- |> get_in([:visitors, :value])
-
- {:error, :not_supported} ->
- nil
+ if comparison_query do
+ site
+ |> Stats.aggregate(comparison_query, [:visitors])
+ |> get_in([:visitors, :value])
+ else
+ nil
end
%{
@@ -369,21 +364,25 @@ defmodule PlausibleWeb.Api.StatsController do
%{
name: "Unique visitors",
value: unique_visitors,
+ comparison_value: prev_unique_visitors,
change: percent_change(prev_unique_visitors, unique_visitors)
},
%{
name: "Unique conversions",
value: converted_visitors,
+ comparison_value: prev_converted_visitors,
change: percent_change(prev_converted_visitors, converted_visitors)
},
%{
name: "Total conversions",
value: completions,
+ comparison_value: prev_completions,
change: percent_change(prev_completions, completions)
},
%{
name: "Conversion rate",
value: conversion_rate,
+ comparison_value: prev_conversion_rate,
change: percent_change(prev_conversion_rate, conversion_rate)
}
]
@@ -391,7 +390,7 @@ defmodule PlausibleWeb.Api.StatsController do
{stats, 100}
end
- defp fetch_top_stats(site, query, comparison_mode, comparison_opts) do
+ defp fetch_top_stats(site, query, comparison_query) do
metrics =
if query.filters["event:page"] do
[
@@ -416,12 +415,7 @@ defmodule PlausibleWeb.Api.StatsController do
end
current_results = Stats.aggregate(site, query, metrics)
-
- prev_results =
- case Stats.Comparisons.compare(site, query, comparison_mode, comparison_opts) do
- {:ok, prev_results_query} -> Stats.aggregate(site, prev_results_query, metrics)
- {:error, :not_supported} -> nil
- end
+ prev_results = comparison_query && Stats.aggregate(site, comparison_query, metrics)
stats =
[
@@ -444,7 +438,7 @@ defmodule PlausibleWeb.Api.StatsController do
prev_value = get_in(prev_results, [key, :value])
change = prev_value && calculate_change(key, prev_value, value)
- %{name: name, value: value, change: change}
+ %{name: name, value: value, comparison_value: prev_value, change: change}
end
end
diff --git a/test/plausible_web/controllers/api/stats_controller/top_stats_test.exs b/test/plausible_web/controllers/api/stats_controller/top_stats_test.exs
index 78ca014876..d0abafcbab 100644
--- a/test/plausible_web/controllers/api/stats_controller/top_stats_test.exs
+++ b/test/plausible_web/controllers/api/stats_controller/top_stats_test.exs
@@ -16,7 +16,13 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
conn = get(conn, "/api/stats/#{site.domain}/top-stats?period=day")
res = json_response(conn, 200)
- assert %{"name" => "Unique visitors", "value" => 2, "change" => 100} in res["top_stats"]
+
+ assert %{
+ "change" => 100,
+ "comparison_value" => 0,
+ "name" => "Unique visitors",
+ "value" => 2
+ } in res["top_stats"]
end
test "counts total pageviews", %{conn: conn, site: site} do
@@ -29,7 +35,13 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
conn = get(conn, "/api/stats/#{site.domain}/top-stats?period=day")
res = json_response(conn, 200)
- assert %{"name" => "Total pageviews", "value" => 3, "change" => 100} in res["top_stats"]
+
+ assert %{
+ "change" => 100,
+ "comparison_value" => 0,
+ "name" => "Total pageviews",
+ "value" => 3
+ } in res["top_stats"]
end
test "counts total visits", %{conn: conn, site: site} do
@@ -43,7 +55,10 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
conn = get(conn, "/api/stats/#{site.domain}/top-stats?period=day&date=2021-01-01")
res = json_response(conn, 200)
- assert %{"name" => "Total visits", "value" => 3, "change" => 100} in res["top_stats"]
+
+ assert %{"change" => 100, "comparison_value" => 0, "name" => "Total visits", "value" => 3} in res[
+ "top_stats"
+ ]
end
test "counts pages per visit", %{conn: conn, site: site} do
@@ -57,7 +72,13 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
conn = get(conn, "/api/stats/#{site.domain}/top-stats?period=day&date=2021-01-01")
res = json_response(conn, 200)
- assert %{"name" => "Views per visit", "value" => 1.33, "change" => 100} in res["top_stats"]
+
+ assert %{
+ "change" => 100,
+ "comparison_value" => 0.0,
+ "name" => "Views per visit",
+ "value" => 1.33
+ } in res["top_stats"]
end
test "calculates bounce rate", %{conn: conn, site: site} do
@@ -70,7 +91,10 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
conn = get(conn, "/api/stats/#{site.domain}/top-stats?period=day")
res = json_response(conn, 200)
- assert %{"name" => "Bounce rate", "value" => 50, "change" => nil} in res["top_stats"]
+
+ assert %{"change" => nil, "comparison_value" => 0, "name" => "Bounce rate", "value" => 50} in res[
+ "top_stats"
+ ]
end
test "calculates average visit duration", %{conn: conn, site: site} do
@@ -91,7 +115,13 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
conn = get(conn, "/api/stats/#{site.domain}/top-stats?period=day&date=2021-01-01")
res = json_response(conn, 200)
- assert %{"name" => "Visit duration", "value" => 450, "change" => 100} in res["top_stats"]
+
+ assert %{
+ "change" => 100,
+ "comparison_value" => 0,
+ "name" => "Visit duration",
+ "value" => 450
+ } in res["top_stats"]
end
test "calculates time on page instead when filtered for page", %{conn: conn, site: site} do
@@ -121,7 +151,10 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
)
res = json_response(conn, 200)
- assert %{"name" => "Time on page", "value" => 900, "change" => 100} in res["top_stats"]
+
+ assert %{"change" => 100, "comparison_value" => 0, "name" => "Time on page", "value" => 900} in res[
+ "top_stats"
+ ]
end
test "calculates time on page when filtered for multiple pages", %{
@@ -159,7 +192,10 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
)
res = json_response(conn, 200)
- assert %{"name" => "Time on page", "value" => 480, "change" => 100} in res["top_stats"]
+
+ assert %{"change" => 100, "comparison_value" => 0, "name" => "Time on page", "value" => 480} in res[
+ "top_stats"
+ ]
end
test "calculates time on page when filtered for multiple negated pages", %{
@@ -197,7 +233,10 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
)
res = json_response(conn, 200)
- assert %{"name" => "Time on page", "value" => 60, "change" => 100} in res["top_stats"]
+
+ assert %{"change" => 100, "comparison_value" => 0, "name" => "Time on page", "value" => 60} in res[
+ "top_stats"
+ ]
end
test "calculates time on page when filtered for multiple wildcard pages", %{
@@ -236,7 +275,10 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
)
res = json_response(conn, 200)
- assert %{"name" => "Time on page", "value" => 480, "change" => 100} in res["top_stats"]
+
+ assert %{"change" => 100, "comparison_value" => 0, "name" => "Time on page", "value" => 480} in res[
+ "top_stats"
+ ]
end
test "calculates time on page when filtered for multiple negated wildcard pages", %{
@@ -277,7 +319,10 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
)
res = json_response(conn, 200)
- assert %{"name" => "Time on page", "value" => 600, "change" => 100} in res["top_stats"]
+
+ assert %{"change" => 100, "comparison_value" => 0, "name" => "Time on page", "value" => 600} in res[
+ "top_stats"
+ ]
end
end
@@ -312,12 +357,42 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
res = json_response(conn, 200)
assert res["top_stats"] == [
- %{"name" => "Unique visitors", "value" => 3, "change" => 100},
- %{"name" => "Total visits", "value" => 3, "change" => 100},
- %{"name" => "Total pageviews", "value" => 4, "change" => 100},
- %{"name" => "Views per visit", "value" => 1.5, "change" => 100},
- %{"name" => "Bounce rate", "value" => 33, "change" => nil},
- %{"name" => "Visit duration", "value" => 303, "change" => 100}
+ %{
+ "change" => 100,
+ "comparison_value" => 0,
+ "name" => "Unique visitors",
+ "value" => 3
+ },
+ %{
+ "change" => 100,
+ "comparison_value" => 0,
+ "name" => "Total visits",
+ "value" => 3
+ },
+ %{
+ "change" => 100,
+ "comparison_value" => 0,
+ "name" => "Total pageviews",
+ "value" => 4
+ },
+ %{
+ "change" => 100,
+ "comparison_value" => 0.0,
+ "name" => "Views per visit",
+ "value" => 1.5
+ },
+ %{
+ "change" => nil,
+ "comparison_value" => 0,
+ "name" => "Bounce rate",
+ "value" => 33
+ },
+ %{
+ "change" => 100,
+ "comparison_value" => 0,
+ "name" => "Visit duration",
+ "value" => 303
+ }
]
end
end
@@ -422,7 +497,13 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
)
res = json_response(conn, 200)
- assert %{"name" => "Unique visitors", "value" => 2, "change" => 100} in res["top_stats"]
+
+ assert %{
+ "change" => 100,
+ "comparison_value" => 0,
+ "name" => "Unique visitors",
+ "value" => 2
+ } in res["top_stats"]
end
test "page glob filter", %{conn: conn, site: site} do
@@ -441,7 +522,13 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
)
res = json_response(conn, 200)
- assert %{"name" => "Unique visitors", "value" => 2, "change" => 100} in res["top_stats"]
+
+ assert %{
+ "change" => 100,
+ "comparison_value" => 0,
+ "name" => "Unique visitors",
+ "value" => 2
+ } in res["top_stats"]
end
test "contains (~) filter", %{conn: conn, site: site} do
@@ -460,7 +547,13 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
)
res = json_response(conn, 200)
- assert %{"name" => "Unique visitors", "value" => 2, "change" => 100} in res["top_stats"]
+
+ assert %{
+ "change" => 100,
+ "comparison_value" => 0,
+ "name" => "Unique visitors",
+ "value" => 2
+ } in res["top_stats"]
end
test "returns only visitors with specific screen size", %{conn: conn, site: site} do
@@ -479,7 +572,13 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
)
res = json_response(conn, 200)
- assert %{"name" => "Unique visitors", "value" => 2, "change" => 100} in res["top_stats"]
+
+ assert %{
+ "change" => 100,
+ "comparison_value" => 0,
+ "name" => "Unique visitors",
+ "value" => 2
+ } in res["top_stats"]
end
test "returns only visitors with specific browser", %{conn: conn, site: site} do
@@ -498,7 +597,13 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
)
res = json_response(conn, 200)
- assert %{"name" => "Unique visitors", "value" => 2, "change" => 100} in res["top_stats"]
+
+ assert %{
+ "change" => 100,
+ "comparison_value" => 0,
+ "name" => "Unique visitors",
+ "value" => 2
+ } in res["top_stats"]
end
test "returns only visitors with specific operating system", %{conn: conn, site: site} do
@@ -517,7 +622,13 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
)
res = json_response(conn, 200)
- assert %{"name" => "Unique visitors", "value" => 2, "change" => 100} in res["top_stats"]
+
+ assert %{
+ "change" => 100,
+ "comparison_value" => 0,
+ "name" => "Unique visitors",
+ "value" => 2
+ } in res["top_stats"]
end
test "returns number of visits from one specific referral source", %{conn: conn, site: site} do
@@ -549,7 +660,10 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
)
res = json_response(conn, 200)
- assert %{"name" => "Total visits", "value" => 2, "change" => 100} in res["top_stats"]
+
+ assert %{"change" => 100, "comparison_value" => 0, "name" => "Total visits", "value" => 2} in res[
+ "top_stats"
+ ]
end
end
@@ -573,7 +687,13 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
)
res = json_response(conn, 200)
- assert %{"name" => "Unique visitors", "value" => 3, "change" => 100} in res["top_stats"]
+
+ assert %{
+ "change" => 100,
+ "comparison_value" => 0,
+ "name" => "Unique visitors",
+ "value" => 3
+ } in res["top_stats"]
end
test "returns converted visitors", %{conn: conn, site: site} do
@@ -593,7 +713,13 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
)
res = json_response(conn, 200)
- assert %{"name" => "Unique conversions", "value" => 1, "change" => 100} in res["top_stats"]
+
+ assert %{
+ "change" => 100,
+ "comparison_value" => 0,
+ "name" => "Unique conversions",
+ "value" => 1
+ } in res["top_stats"]
end
test "returns conversion rate", %{conn: conn, site: site} do
@@ -614,7 +740,12 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
res = json_response(conn, 200)
- assert %{"name" => "Conversion rate", "value" => 33.3, "change" => 100} in res["top_stats"]
+ assert %{
+ "change" => 100,
+ "comparison_value" => 0.0,
+ "name" => "Conversion rate",
+ "value" => 33.3
+ } in res["top_stats"]
end
test "returns conversion rate with change=nil when comparison mode disallowed", %{
@@ -638,7 +769,83 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do
res = json_response(conn, 200)
- assert %{"name" => "Conversion rate", "value" => 33.3, "change" => nil} in res["top_stats"]
+ assert %{
+ "change" => nil,
+ "comparison_value" => nil,
+ "name" => "Conversion rate",
+ "value" => 33.3
+ } in res["top_stats"]
+ end
+ end
+
+ describe "GET /api/stats/top-stats - with comparisons" do
+ setup [:create_user, :log_in, :create_new_site]
+
+ test "defaults to previous period when comparison is not set", %{site: site, conn: conn} do
+ populate_stats(site, [
+ build(:pageview, timestamp: ~N[2020-12-31 00:00:00]),
+ build(:pageview, timestamp: ~N[2020-12-31 00:00:00]),
+ build(:pageview, timestamp: ~N[2021-01-01 00:00:00]),
+ build(:pageview, timestamp: ~N[2021-01-01 00:01:00]),
+ build(:pageview, timestamp: ~N[2021-01-01 10:00:00])
+ ])
+
+ conn = get(conn, "/api/stats/#{site.domain}/top-stats?period=day&date=2021-01-01")
+
+ res = json_response(conn, 200)
+
+ assert %{"change" => 50, "comparison_value" => 2, "name" => "Total visits", "value" => 3} in res[
+ "top_stats"
+ ]
+ end
+
+ test "returns comparison data when mode is custom", %{site: site, conn: conn} do
+ populate_stats(site, [
+ build(:pageview, timestamp: ~N[2020-01-01 00:00:00]),
+ build(:pageview, timestamp: ~N[2020-01-05 00:00:00]),
+ build(:pageview, timestamp: ~N[2020-01-20 00:00:00]),
+ build(:pageview, timestamp: ~N[2020-12-31 00:00:00]),
+ build(:pageview, timestamp: ~N[2021-01-01 00:00:00]),
+ build(:pageview, timestamp: ~N[2021-01-01 00:01:00]),
+ build(:pageview, timestamp: ~N[2021-01-01 10:00:00])
+ ])
+
+ conn =
+ get(
+ conn,
+ "/api/stats/#{site.domain}/top-stats?period=day&date=2021-01-01&comparison=custom&compare_from=2020-01-01&compare_to=2020-01-20"
+ )
+
+ res = json_response(conn, 200)
+
+ assert %{"change" => 0, "comparison_value" => 3, "name" => "Total visits", "value" => 3} in res[
+ "top_stats"
+ ]
+ end
+
+ test "returns source query and comparison query date range", %{site: site, conn: conn} do
+ populate_stats(site, [
+ build(:pageview, timestamp: ~N[2020-01-01 00:00:00]),
+ build(:pageview, timestamp: ~N[2020-01-05 00:00:00]),
+ build(:pageview, timestamp: ~N[2020-01-20 00:00:00]),
+ build(:pageview, timestamp: ~N[2020-12-31 00:00:00]),
+ build(:pageview, timestamp: ~N[2021-01-01 00:00:00]),
+ build(:pageview, timestamp: ~N[2021-01-01 00:01:00]),
+ build(:pageview, timestamp: ~N[2021-01-01 10:00:00])
+ ])
+
+ conn =
+ get(
+ conn,
+ "/api/stats/#{site.domain}/top-stats?period=month&date=2021-01-01&comparison=previous_period"
+ )
+
+ assert %{
+ "comparing_from" => "2020-12-01",
+ "comparing_to" => "2020-12-31",
+ "from" => "2021-01-01",
+ "to" => "2021-01-31"
+ } = json_response(conn, 200)
end
end
end