Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Fix trend viz dates diff calculation for a year unit (#65985)

Denis Berezin0b42ad89a9e4
diff --git a/src/metabase/analyze/fingerprint/insights.clj b/src/metabase/analyze/fingerprint/insights.clj
index fe0ca4359bd..223389d7ccf 100644
--- a/src/metabase/analyze/fingerprint/insights.clj
+++ b/src/metabase/analyze/fingerprint/insights.clj
@@ -217,8 +217,14 @@
[from to unit]
(when (and from to unit)
;; Make sure we work for both ascending and descending time series
- (let [[from to] (sort [from to])]
- (about= (- to from) (unit->duration unit)))))
+ (let [[from to] (sort [from to])
+ diff (- to from)]
+ (if (= unit :year)
+ ;; Special handling for years: accept both 365 days (non-leap) and 366 days (leap year),
+ ;; but reject anything less than 365 days
+ (and (>= diff 364.5)
+ (<= diff 366.5))
+ (about= diff (unit->duration unit))))))
(defn- infer-unit
[from to]
diff --git a/test/metabase/analyze/fingerprint/insights_test.clj b/test/metabase/analyze/fingerprint/insights_test.clj
index d6f3d5d522a..54f3d297313 100644
--- a/test/metabase/analyze/fingerprint/insights_test.clj
+++ b/test/metabase/analyze/fingerprint/insights_test.clj
@@ -51,6 +51,15 @@
(is (true? (valid-period? #t "2015-01-01" #t "2015-01-08")))
(is (true? (valid-period? #t "2015-01-01" #t "2015-04-03")))
(is (true? (valid-period? #t "2015" #t "2016")))
+ ;; Test leap year handling
+ (is (true? (valid-period? #t "2016" #t "2017")))
+ (is (true? (valid-period? #t "2017" #t "2018")))
+ ;; Periods less than 365 days should NOT be inferred as :year
+ (is (not= :year (#'insights/infer-unit (inst->day #t "2015-01-01") (inst->day #t "2015-12-01"))))
+ (is (not= :year (#'insights/infer-unit (inst->day #t "2015-02-01") (inst->day #t "2016-01-01"))))
+ ;; Both 365 and 366 day periods should be inferred as :year
+ (is (= :year (#'insights/infer-unit (inst->day #t "2015-01-01") (inst->day #t "2016-01-01"))))
+ (is (= :year (#'insights/infer-unit (inst->day #t "2016-01-01") (inst->day #t "2017-01-01"))))
(is (= false (valid-period? #t "2015-01-01" #t "2015-01-09")))
(is (true? (valid-period? #t "2015-01-01" #t "2015-04-03" :quarter)))
(is (= false (valid-period? #t "2015-01-01" #t "2015-04-03" :month)))