Skip to content

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

Fix present_index for daily, weekly and monthly intervals (#4358)

Uku Taht28787198b202
diff --git a/lib/plausible_web/controllers/api/stats_controller.ex b/lib/plausible_web/controllers/api/stats_controller.ex
index 6696eb1a6a..bfc34cbd87 100644
--- a/lib/plausible_web/controllers/api/stats_controller.ex
+++ b/lib/plausible_web/controllers/api/stats_controller.ex
@@ -276,6 +276,7 @@ defmodule PlausibleWeb.Api.StatsController do
current_date =
Timex.now(site.timezone)
|> Timex.to_date()
+ |> Date.to_string()
Enum.find_index(dates, &(&1 == current_date))
@@ -284,6 +285,7 @@ defmodule PlausibleWeb.Api.StatsController do
Timex.now(site.timezone)
|> Timex.to_date()
|> date_or_weekstart(query)
+ |> Date.to_string()
Enum.find_index(dates, &(&1 == current_date))
@@ -292,6 +294,7 @@ defmodule PlausibleWeb.Api.StatsController do
Timex.now(site.timezone)
|> Timex.to_date()
|> Timex.beginning_of_month()
+ |> Date.to_string()
Enum.find_index(dates, &(&1 == current_date))
diff --git a/test/plausible_web/controllers/api/stats_controller/main_graph_test.exs b/test/plausible_web/controllers/api/stats_controller/main_graph_test.exs
index 74b7bbaeee..db0d0e440a 100644
--- a/test/plausible_web/controllers/api/stats_controller/main_graph_test.exs
+++ b/test/plausible_web/controllers/api/stats_controller/main_graph_test.exs
@@ -1426,4 +1426,43 @@ defmodule PlausibleWeb.Api.StatsController.MainGraphTest do
]
end
end
+
+ describe "present_index" do
+ setup [:create_user, :log_in, :create_new_site]
+
+ test "exists for a date range that includes the current day", %{conn: conn, site: site} do
+ populate_stats(site, [
+ build(:pageview)
+ ])
+
+ conn =
+ get(
+ conn,
+ "/api/stats/#{site.domain}/main-graph?period=month&metric=pageviews"
+ )
+
+ assert %{"present_index" => present_index} = json_response(conn, 200)
+
+ assert present_index >= 0
+ end
+
+ test "is null for a date range that does not include the current day", %{
+ conn: conn,
+ site: site
+ } do
+ populate_stats(site, [
+ build(:pageview)
+ ])
+
+ conn =
+ get(
+ conn,
+ "/api/stats/#{site.domain}/main-graph?period=month&date=2021-01-01&metric=pageviews"
+ )
+
+ assert %{"present_index" => present_index} = json_response(conn, 200)
+
+ refute present_index
+ end
+ end
end