From 4eca1aef709d0f1ac41d452b8c8992b40e1d27c0 Mon Sep 17 00:00:00 2001 From: RobertJoonas <56999674+RobertJoonas@users.noreply.github.com> Date: Wed, 8 Mar 2023 13:45:04 +0200 Subject: [PATCH] fix a bug in percent change calculation (#2731) --- .../controllers/api/stats_controller.ex | 4 +++- .../api/stats_controller/top_stats_test.exs | 24 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/lib/plausible_web/controllers/api/stats_controller.ex b/lib/plausible_web/controllers/api/stats_controller.ex index 499f4f762..26fefc22e 100644 --- a/lib/plausible_web/controllers/api/stats_controller.ex +++ b/lib/plausible_web/controllers/api/stats_controller.ex @@ -427,6 +427,8 @@ defmodule PlausibleWeb.Api.StatsController do percent_change(old_count, new_count) end + defp percent_change(nil, _new_count), do: nil + defp percent_change(old_count, new_count) do cond do old_count == 0 and new_count > 0 -> @@ -1007,7 +1009,7 @@ defmodule PlausibleWeb.Api.StatsController do end end - defp calculate_cr(nil, _converted_visitors), do: 100.0 + defp calculate_cr(nil, _converted_visitors), do: nil defp calculate_cr(unique_visitors, converted_visitors) do if unique_visitors > 0, 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 c6b295abe..b41da6896 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 @@ -419,5 +419,29 @@ defmodule PlausibleWeb.Api.StatsController.TopStatsTest do assert %{"name" => "Conversion rate", "value" => 33.3, "change" => 100} in res["top_stats"] end + + test "returns conversion rate with change=nil when comparison mode disallowed", %{ + conn: conn, + site: site + } do + populate_stats(site, [ + build(:pageview, user_id: @user_id), + build(:pageview, user_id: @user_id), + build(:pageview), + build(:event, name: "Signup") + ]) + + filters = Jason.encode!(%{goal: "Signup"}) + + conn = + get( + conn, + "/api/stats/#{site.domain}/top-stats?period=all&filters=#{filters}" + ) + + res = json_response(conn, 200) + + assert %{"name" => "Conversion rate", "value" => 33.3, "change" => nil} in res["top_stats"] + end end end