diff --git a/CHANGELOG.md b/CHANGELOG.md index af754087e..b8fbaa2d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,10 @@ All notable changes to this project will be documented in this file. ## Unreleased +### Added +- New parameter `metrics` for the `/api/v1/stats/timeseries` endpoint plausible/analytics#952 +- CSV export now includes pageviews, bounce rate and visit duration in addition to visitors plausible/analytics#952 + ### Fixed - Fix weekly report time range plausible/analytics#951 diff --git a/lib/plausible/stats/mod.ex b/lib/plausible/stats/mod.ex index cab1d3de2..88fc12818 100644 --- a/lib/plausible/stats/mod.ex +++ b/lib/plausible/stats/mod.ex @@ -1,5 +1,5 @@ defmodule Plausible.Stats do defdelegate breakdown(site, query, prop, metrics, pagination), to: Plausible.Stats.Breakdown defdelegate aggregate(site, query, metrics), to: Plausible.Stats.Aggregate - defdelegate timeseries(site, query), to: Plausible.Stats.Timeseries + defdelegate timeseries(site, query, metrics), to: Plausible.Stats.Timeseries end diff --git a/lib/plausible/stats/timeseries.ex b/lib/plausible/stats/timeseries.ex index 1c57a0b1d..74eceb3af 100644 --- a/lib/plausible/stats/timeseries.ex +++ b/lib/plausible/stats/timeseries.ex @@ -2,28 +2,49 @@ defmodule Plausible.Stats.Timeseries do use Plausible.ClickhouseRepo alias Plausible.Stats.Query import Plausible.Stats.Base + use Plausible.Stats.Fragments - def timeseries(site, query) do + @event_metrics ["visitors", "pageviews"] + @session_metrics ["bounce_rate", "visit_duration"] + def timeseries(site, query, metrics) do steps = buckets(query) - groups = - from(e in base_event_query(site, query), - group_by: fragment("bucket"), - order_by: fragment("bucket") - ) - |> select_bucket(site, query) - |> ClickhouseRepo.all() - |> Enum.into(%{}) + event_metrics = Enum.filter(metrics, &(&1 in @event_metrics)) + session_metrics = Enum.filter(metrics, &(&1 in @session_metrics)) - plot = Enum.map(steps, fn step -> groups[step] || 0 end) + [event_result, session_result] = + Task.await_many([ + Task.async(fn -> events_timeseries(site, query, event_metrics) end), + Task.async(fn -> sessions_timeseries(site, query, session_metrics) end) + ]) - labels = - Enum.map(steps, fn - step when is_binary(step) -> step - step -> Timex.format!(step, "{ISOdate}") - end) + Enum.map(steps, fn step -> + empty_row(step, metrics) + |> Map.merge(Enum.find(event_result, fn row -> row["date"] == step end) || %{}) + |> Map.merge(Enum.find(session_result, fn row -> row["date"] == step end) || %{}) + end) + end + + defp events_timeseries(site, query, metrics) do + from(e in base_event_query(site, query), + group_by: fragment("date"), + order_by: fragment("date"), + select: %{} + ) + |> select_bucket(site, query) + |> select_event_metrics(metrics) + |> ClickhouseRepo.all() + end - {plot, labels} + defp sessions_timeseries(site, query, metrics) do + from(e in query_sessions(site, query), + group_by: fragment("date"), + order_by: fragment("date"), + select: %{} + ) + |> select_bucket(site, query) + |> select_session_metrics(metrics) + |> ClickhouseRepo.all() end defp buckets(%Query{interval: "month"} = query) do @@ -51,27 +72,73 @@ defmodule Plausible.Stats.Timeseries do defp select_bucket(q, site, %Query{interval: "month"}) do from( e in q, - select: - {fragment("toStartOfMonth(toTimeZone(?, ?)) as bucket", e.timestamp, ^site.timezone), - fragment("uniq(?)", e.user_id)} + select_merge: %{ + "date" => + fragment("toStartOfMonth(toTimeZone(?, ?)) as date", e.timestamp, ^site.timezone) + } ) end defp select_bucket(q, site, %Query{interval: "date"}) do from( e in q, - select: - {fragment("toDate(toTimeZone(?, ?)) as bucket", e.timestamp, ^site.timezone), - fragment("uniq(?)", e.user_id)} + select_merge: %{ + "date" => fragment("toDate(toTimeZone(?, ?)) as date", e.timestamp, ^site.timezone) + } ) end defp select_bucket(q, site, %Query{interval: "hour"}) do from( e in q, - select: - {fragment("toStartOfHour(toTimeZone(?, ?)) as bucket", e.timestamp, ^site.timezone), - fragment("uniq(?)", e.user_id)} + select_merge: %{ + "date" => fragment("toStartOfHour(toTimeZone(?, ?)) as date", e.timestamp, ^site.timezone) + } ) end + + defp select_event_metrics(q, []), do: q + + defp select_event_metrics(q, ["pageviews" | rest]) do + from(e in q, + select_merge: %{"pageviews" => fragment("countIf(? = 'pageview')", e.name)} + ) + |> select_event_metrics(rest) + end + + defp select_event_metrics(q, ["visitors" | rest]) do + from(e in q, + select_merge: %{"visitors" => fragment("uniq(?) as count", e.user_id)} + ) + |> select_event_metrics(rest) + end + + defp select_session_metrics(q, []), do: q + + defp select_session_metrics(q, ["bounce_rate" | rest]) do + from(s in q, + select_merge: %{ + "bounce_rate" => bounce_rate() + } + ) + |> select_session_metrics(rest) + end + + defp select_session_metrics(q, ["visit_duration" | rest]) do + from(s in q, + select_merge: %{"visit_duration" => visit_duration()} + ) + |> select_session_metrics(rest) + end + + defp empty_row(date, metrics) do + Enum.reduce(metrics, %{"date" => date}, fn metric, row -> + case metric do + "pageviews" -> Map.merge(row, %{"pageviews" => 0}) + "visitors" -> Map.merge(row, %{"visitors" => 0}) + "bounce_rate" -> Map.merge(row, %{"bounce_rate" => nil}) + "visit_duration" -> Map.merge(row, %{"visit_duration" => nil}) + end + end) + end end diff --git a/lib/plausible_web/controllers/api/external_stats_controller.ex b/lib/plausible_web/controllers/api/external_stats_controller.ex index 8cdbbd5ea..f50c5ca59 100644 --- a/lib/plausible_web/controllers/api/external_stats_controller.ex +++ b/lib/plausible_web/controllers/api/external_stats_controller.ex @@ -120,14 +120,9 @@ defmodule PlausibleWeb.Api.ExternalStatsController do with :ok <- validate_period(params), :ok <- validate_date(params), :ok <- validate_interval(params), - query <- Query.from(site.timezone, params) do - {plot, labels} = Plausible.Stats.timeseries(site, query) - - graph = - Enum.zip(labels, plot) - |> Enum.map(fn {label, val} -> %{date: label, visitors: val} end) - |> Enum.into([]) - + query <- Query.from(site.timezone, params), + {:ok, metrics} <- parse_metrics(params, nil, query) do + graph = Plausible.Stats.timeseries(site, query, metrics) json(conn, %{"results" => graph}) else {:error, msg} -> diff --git a/lib/plausible_web/controllers/stats_controller.ex b/lib/plausible_web/controllers/stats_controller.ex index 4287d8db2..14956ac2d 100644 --- a/lib/plausible_web/controllers/stats_controller.ex +++ b/lib/plausible_web/controllers/stats_controller.ex @@ -36,20 +36,28 @@ defmodule PlausibleWeb.StatsController do def csv_export(conn, %{"domain" => domain}) do site = conn.assigns[:site] - query = Query.from(site.timezone, conn.params) - {plot, labels, _} = Stats.calculate_plot(site, query) + + metrics = + if query.filters["event:name"] do + ["visitors", "pageviews"] + else + ["visitors", "pageviews", "bounce_rate", "visit_duration"] + end + + graph = Plausible.Stats.timeseries(site, query, metrics) + + headers = ["date" | metrics] csv_content = - Enum.zip(labels, plot) - |> Enum.map(fn {k, v} -> [k, v] end) - |> (fn data -> [["Date", "Visitors"] | data] end).() + Enum.map(graph, fn row -> Enum.map(headers, &row[&1]) end) + |> (fn data -> [headers | data] end).() |> CSV.encode() |> Enum.into([]) |> Enum.join() filename = - "Visitors #{domain} #{Timex.format!(query.date_range.first, "{ISOdate} ")} to #{ + "Plausible export #{domain} #{Timex.format!(query.date_range.first, "{ISOdate} ")} to #{ Timex.format!(query.date_range.last, "{ISOdate} ") }.csv" diff --git a/test/plausible_web/controllers/api/external_stats_controller/timeseries_test.exs b/test/plausible_web/controllers/api/external_stats_controller/timeseries_test.exs index b424cbff1..ec75776be 100644 --- a/test/plausible_web/controllers/api/external_stats_controller/timeseries_test.exs +++ b/test/plausible_web/controllers/api/external_stats_controller/timeseries_test.exs @@ -47,9 +47,11 @@ defmodule PlausibleWeb.Api.ExternalStatsController.TimeseriesTest do end end + @user_id 123 test "shows hourly data for a certain date", %{conn: conn, site: site} do populate_stats([ - build(:pageview, domain: site.domain, timestamp: ~N[2021-01-01 00:00:00]), + build(:pageview, user_id: @user_id, domain: site.domain, timestamp: ~N[2021-01-01 00:00:00]), + build(:pageview, user_id: @user_id, domain: site.domain, timestamp: ~N[2021-01-01 00:10:00]), build(:pageview, domain: site.domain, timestamp: ~N[2021-01-01 23:59:00]) ]) @@ -57,35 +59,180 @@ defmodule PlausibleWeb.Api.ExternalStatsController.TimeseriesTest do get(conn, "/api/v1/stats/timeseries", %{ "site_id" => site.domain, "period" => "day", - "date" => "2021-01-01" + "date" => "2021-01-01", + "metrics" => "visitors,pageviews,visit_duration,bounce_rate" }) assert json_response(conn, 200) == %{ "results" => [ - %{"date" => "2021-01-01 00:00:00", "visitors" => 1}, - %{"date" => "2021-01-01 01:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 02:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 03:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 04:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 05:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 06:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 07:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 08:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 09:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 10:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 11:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 12:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 13:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 14:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 15:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 16:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 17:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 18:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 19:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 20:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 21:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 22:00:00", "visitors" => 0}, - %{"date" => "2021-01-01 23:00:00", "visitors" => 1} + %{ + "date" => "2021-01-01 00:00:00", + "visitors" => 1, + "pageviews" => 2, + "visit_duration" => 600, + "bounce_rate" => 0 + }, + %{ + "date" => "2021-01-01 01:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 02:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 03:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 04:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 05:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 06:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 07:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 08:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 09:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 10:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 11:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 12:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 13:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 14:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 15:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 16:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 17:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 18:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 19:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 20:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 21:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 22:00:00", + "visitors" => 0, + "pageviews" => 0, + "visit_duration" => nil, + "bounce_rate" => nil + }, + %{ + "date" => "2021-01-01 23:00:00", + "visitors" => 1, + "pageviews" => 1, + "visit_duration" => 0, + "bounce_rate" => 100 + } ] } end @@ -218,7 +365,8 @@ defmodule PlausibleWeb.Api.ExternalStatsController.TimeseriesTest do test "shows a custom range with monthly interval", %{conn: conn, site: site} do populate_stats([ - build(:pageview, domain: site.domain, timestamp: ~N[2020-12-01 00:00:00]), + build(:pageview, user_id: @user_id, domain: site.domain, timestamp: ~N[2020-12-01 00:00:00]), + build(:pageview, user_id: @user_id, domain: site.domain, timestamp: ~N[2020-12-01 00:05:00]), build(:pageview, domain: site.domain, timestamp: ~N[2021-01-01 00:00:00]), build(:pageview, domain: site.domain, timestamp: ~N[2021-01-02 00:00:00]) ]) @@ -228,13 +376,26 @@ defmodule PlausibleWeb.Api.ExternalStatsController.TimeseriesTest do "site_id" => site.domain, "period" => "custom", "date" => "2020-12-01, 2021-01-02", - "interval" => "month" + "interval" => "month", + "metrics" => "pageviews,visitors,bounce_rate,visit_duration" }) assert json_response(conn, 200) == %{ "results" => [ - %{"date" => "2020-12-01", "visitors" => 1}, - %{"date" => "2021-01-01", "visitors" => 2} + %{ + "date" => "2020-12-01", + "visitors" => 1, + "pageviews" => 2, + "bounce_rate" => 0, + "visit_duration" => 300 + }, + %{ + "date" => "2021-01-01", + "visitors" => 2, + "pageviews" => 2, + "bounce_rate" => 100, + "visit_duration" => 0 + } ] } end @@ -461,11 +622,19 @@ defmodule PlausibleWeb.Api.ExternalStatsController.TimeseriesTest do test "can filter by country", %{conn: conn, site: site} do populate_stats([ build(:pageview, + user_id: @user_id, country_code: "EE", operating_system_version: "10.5", domain: site.domain, timestamp: ~N[2021-01-01 00:00:00] ), + build(:pageview, + user_id: @user_id, + country_code: "EE", + operating_system_version: "10.5", + domain: site.domain, + timestamp: ~N[2021-01-01 00:15:00] + ), build(:pageview, domain: site.domain, timestamp: ~N[2021-01-01 00:00:00]) ]) @@ -474,24 +643,42 @@ defmodule PlausibleWeb.Api.ExternalStatsController.TimeseriesTest do "site_id" => site.domain, "period" => "month", "date" => "2021-01-01", - "filters" => "visit:country==EE" + "filters" => "visit:country==EE", + "metrics" => "visitors,pageviews,bounce_rate,visit_duration" }) res = json_response(conn, 200)["results"] - assert List.first(res) == %{"date" => "2021-01-01", "visitors" => 1} + + assert List.first(res) == %{ + "date" => "2021-01-01", + "visitors" => 1, + "pageviews" => 2, + "bounce_rate" => 0, + "visit_duration" => 900 + } end - test "can filter by page", %{conn: conn, site: site} do + test "filtering by page - session metrics consider it like entry_page", %{ + conn: conn, + site: site + } do populate_stats([ build(:pageview, pathname: "/hello", + user_id: @user_id, domain: site.domain, timestamp: ~N[2021-01-01 00:00:00] ), build(:pageview, pathname: "/hello", + user_id: @user_id, domain: site.domain, - timestamp: ~N[2021-01-01 00:00:00] + timestamp: ~N[2021-01-01 00:05:00] + ), + build(:pageview, + pathname: "/hello", + domain: site.domain, + timestamp: ~N[2021-01-01 05:00:00] ), build(:pageview, pathname: "/goobye", @@ -505,11 +692,19 @@ defmodule PlausibleWeb.Api.ExternalStatsController.TimeseriesTest do "site_id" => site.domain, "period" => "month", "date" => "2021-01-01", - "filters" => "event:page==/hello" + "filters" => "event:page==/hello", + "metrics" => "visitors,pageviews,bounce_rate,visit_duration" }) res = json_response(conn, 200)["results"] - assert List.first(res) == %{"date" => "2021-01-01", "visitors" => 2} + + assert List.first(res) == %{ + "date" => "2021-01-01", + "visitors" => 2, + "pageviews" => 3, + "bounce_rate" => 50, + "visit_duration" => 150 + } end test "can filter by event:name", %{conn: conn, site: site} do diff --git a/test/plausible_web/controllers/stats_controller_test.exs b/test/plausible_web/controllers/stats_controller_test.exs index ab36c19bb..90fe4e0ff 100644 --- a/test/plausible_web/controllers/stats_controller_test.exs +++ b/test/plausible_web/controllers/stats_controller_test.exs @@ -45,8 +45,8 @@ defmodule PlausibleWeb.StatsControllerTest do today = Timex.today() |> Timex.format!("{ISOdate}") conn = get(conn, "/" <> site.domain <> "/visitors.csv") - assert response(conn, 200) =~ "Date,Visitors" - assert response(conn, 200) =~ "#{today},3" + assert response(conn, 200) =~ "visitors,pageviews,bounce_rate,visit_duration" + assert response(conn, 200) =~ "#{today},3,3,0,0" end end @@ -58,8 +58,8 @@ defmodule PlausibleWeb.StatsControllerTest do today = Timex.today() |> Timex.format!("{ISOdate}") conn = get(conn, "/" <> site.domain <> "/visitors.csv?auth=#{link.slug}") - assert response(conn, 200) =~ "Date,Visitors" - assert response(conn, 200) =~ "#{today},3" + assert response(conn, 200) =~ "visitors,pageviews,bounce_rate,visit_duration" + assert response(conn, 200) =~ "#{today},3,3,0,0" end end