From 1d2d6c3cecd3a6af1548ac01fbc835efa83c26fa Mon Sep 17 00:00:00 2001 From: Karl-Aksel Puulmann Date: Wed, 13 Nov 2024 08:49:45 +0200 Subject: [PATCH] Clamp dates on both directions We could still get warnings about negative date ranges when the date being queried is in the future. This could happen if the users local time is in the future for some reason or they manually edit the url. --- lib/plausible/stats/query.ex | 10 +++++++--- test/plausible/stats/query_test.exs | 7 +++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/lib/plausible/stats/query.ex b/lib/plausible/stats/query.ex index f5bd669a4..cc881fae0 100644 --- a/lib/plausible/stats/query.ex +++ b/lib/plausible/stats/query.ex @@ -57,15 +57,19 @@ defmodule Plausible.Stats.Query do Date.range( date_range.first, - earliest(date_range.last, today) + clamp(today, date_range.first, date_range.last) ) else date_range end end - defp earliest(a, b) do - if Date.compare(a, b) in [:eq, :lt], do: a, else: b + defp clamp(date, lower_bound, upper_bound) do + cond do + Date.compare(date, lower_bound) == :lt -> lower_bound + Date.compare(date, upper_bound) == :gt -> upper_bound + true -> date + end end def set(query, keywords) do diff --git a/test/plausible/stats/query_test.exs b/test/plausible/stats/query_test.exs index fae5524c3..ce5af98cd 100644 --- a/test/plausible/stats/query_test.exs +++ b/test/plausible/stats/query_test.exs @@ -266,6 +266,13 @@ defmodule Plausible.Stats.QueryTest do ~U[2024-05-07 07:00:00Z], trim_trailing: true ) == Date.range(~D[2024-05-05], ~D[2024-05-06]) + + assert date_range( + {~U[2024-05-05 12:00:00Z], ~U[2024-05-08 11:59:59Z]}, + "Etc/GMT+12", + ~U[2024-05-03 07:00:00Z], + trim_trailing: true + ) == Date.range(~D[2024-05-05], ~D[2024-05-05]) end end