From 678d40febdc459cec16b414284d63d0020219480 Mon Sep 17 00:00:00 2001 From: Uku Taht Date: Wed, 5 Apr 2023 18:36:17 +0300 Subject: [PATCH] WIP --- lib/plausible/stats/base.ex | 7 ++++++- .../api/stats_controller/top_stats_test.exs | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/lib/plausible/stats/base.ex b/lib/plausible/stats/base.ex index 02436a8c3..bdd07b57f 100644 --- a/lib/plausible/stats/base.ex +++ b/lib/plausible/stats/base.ex @@ -360,8 +360,13 @@ defmodule Plausible.Stats.Base do def select_session_metrics(q, [:bounce_rate | rest]) do from(s in q, select_merge: %{ + # Currently hard-coded. How to make this condition dynamic based on query.filters? Probably have to make use of Ecto.Query.dynamic/2 bounce_rate: - fragment("toUInt32(ifNotFinite(round(sum(is_bounce * sign) / sum(sign) * 100), 0))"), + fragment( + "toUInt32(ifNotFinite(round(sumIf(is_bounce * sign, entry_page = ?) / sumIf(sign, entry_page = ?) * 100), 0))", + "/page2", + "/page2" + ), __internal_visits: fragment("toUInt32(sum(sign))") } ) 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..8588abc46 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 @@ -73,6 +73,22 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do assert %{"name" => "Bounce rate", "value" => 50, "change" => nil} in res["top_stats"] end + test "calculates bounce rate when filtering for page", %{conn: conn, site: site} do + populate_stats(site, [ + build(:pageview, pathname: "/page1", user_id: @user_id), + build(:pageview, pathname: "/page2", user_id: @user_id), + build(:pageview, pathname: "/page2", user_id: 2), + build(:pageview, pathname: "/page3", user_id: 2), + build(:pageview, pathname: "/page2", user_id: 3) + ]) + + filters = Jason.encode!(%{page: "/page2"}) + conn = get(conn, "/api/stats/#{site.domain}/top-stats?period=day&filters=#{filters}") + + res = json_response(conn, 200) + assert %{"name" => "Bounce rate", "value" => 50, "change" => nil} in res["top_stats"] + end + test "calculates average visit duration", %{conn: conn, site: site} do populate_stats(site, [ build(:pageview,