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.
This commit is contained in:
Karl-Aksel Puulmann 2024-11-13 08:49:45 +02:00
parent c932a25fd6
commit 1d2d6c3cec
2 changed files with 14 additions and 3 deletions

View File

@ -57,15 +57,19 @@ defmodule Plausible.Stats.Query do
Date.range( Date.range(
date_range.first, date_range.first,
earliest(date_range.last, today) clamp(today, date_range.first, date_range.last)
) )
else else
date_range date_range
end end
end end
defp earliest(a, b) do defp clamp(date, lower_bound, upper_bound) do
if Date.compare(a, b) in [:eq, :lt], do: a, else: b cond do
Date.compare(date, lower_bound) == :lt -> lower_bound
Date.compare(date, upper_bound) == :gt -> upper_bound
true -> date
end
end end
def set(query, keywords) do def set(query, keywords) do

View File

@ -266,6 +266,13 @@ defmodule Plausible.Stats.QueryTest do
~U[2024-05-07 07:00:00Z], ~U[2024-05-07 07:00:00Z],
trim_trailing: true trim_trailing: true
) == Date.range(~D[2024-05-05], ~D[2024-05-06]) ) == 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
end end