From 9f036d3915b289c1549fe7d5b3d3448ea85f1e69 Mon Sep 17 00:00:00 2001 From: Vini Brasil Date: Tue, 11 Apr 2023 09:59:10 -0300 Subject: [PATCH] Show detailed comparison dates in top stats (#2804) * Pass comparison_query as argument to top stats functions * Add comparison values and dates to top stats API * Display comparison dates and values in top stats * Rename function to renderPercentageComparison * Create component to do conditional rendering * DRY date range formatting function --------- Co-authored-by: Uku Taht --- assets/js/dashboard/comparison-input.js | 10 +- assets/js/dashboard/datepicker.js | 6 +- assets/js/dashboard/stats/graph/top-stats.js | 91 ++++-- .../js/dashboard/stats/graph/visitor-graph.js | 2 +- assets/js/dashboard/util/date.js | 15 + .../controllers/api/stats_controller.ex | 76 +++-- .../api/stats_controller/top_stats_test.exs | 263 ++++++++++++++++-- 7 files changed, 361 insertions(+), 102 deletions(-) diff --git a/assets/js/dashboard/comparison-input.js b/assets/js/dashboard/comparison-input.js index 631f40d8e..dac7ff2a2 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 }) {
- { buildLabel(query) } + { buildLabel(site, query) } 0) { const color = name === 'Bounce rate' ? 'text-red-400' : 'text-green-500' - return ↑ {formattedComparison}% + return ↑ {formattedComparison}% } else if (comparison < 0) { const color = name === 'Bounce rate' ? 'text-green-500' : 'text-red-400' - return ↓ {formattedComparison}% + return ↓ {formattedComparison}% } else if (comparison === 0) { - return 〰 0% + return 〰 0% + } 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 (
-
{this.topStatNumberLong(stat)} {statName}
+ {query.comparison &&
+ {this.topStatNumberLong(stat.name, stat.value)} vs. {this.topStatNumberLong(stat.name, stat.comparison_value)} {statName} + {this.renderPercentageComparison(stat.name, stat.change, true)} +
} + + {!query.comparison &&
+ {this.topStatNumberLong(stat.name, stat.value)} {statName} +
} + {stat.name === 'Current visitors' &&

Last updated s ago

} {stat.name === 'Views per visit' && showingImported &&

Based only on native data

}
@@ -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 ( - { this.maybeUpdateMetric(stat) }} boundary={this.props.tooltipBoundary}> + { this.maybeUpdateMetric(stat) }} boundary={this.props.tooltipBoundary}> {this.renderStatName(stat)} -
- {this.topStatNumberShort(stat)} - {this.renderComparison(stat.name, stat.change)} +
+
+ +

{this.topStatNumberShort(stat.name, stat.value)}

+ + {this.renderPercentageComparison(stat.name, stat.change)} + +
+ +

{ formatDateRange(site, topStatData.from, topStatData.to) }

+
+
+ + +
+

{ this.topStatNumberShort(stat.name, stat.comparison_value) }

+

{ formatDateRange(site, topStatData.comparing_from, topStatData.comparing_to) }

+
+
) diff --git a/assets/js/dashboard/stats/graph/visitor-graph.js b/assets/js/dashboard/stats/graph/visitor-graph.js index 6c101444d..a69c7856f 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 (
- +
{mainGraphRefreshing && renderLoader()} diff --git a/assets/js/dashboard/util/date.js b/assets/js/dashboard/util/date.js index 193ac2c6e..3777688be 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 386df3b8a..6ad0c0b88 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 78ca01487..d0abafcba 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