FIX: ensures average is applied on last incomplete segment (#13472)

FIX: ensures average is applied on last incomplete segment (#13472)

diff --git a/app/assets/javascripts/admin/addon/models/report.js b/app/assets/javascripts/admin/addon/models/report.js
index 7a6222c..57d9bb6 100644
--- a/app/assets/javascripts/admin/addon/models/report.js
+++ b/app/assets/javascripts/admin/addon/models/report.js
@@ -506,6 +506,11 @@ const Report = EmberObject.extend({
 export const WEEKLY_LIMIT_DAYS = 365;
 export const DAILY_LIMIT_DAYS = 34;
 
+function applyAverage(value, start, end) {
+  const count = end.diff(start, "day") + 1; // 1 to include start
+  return parseFloat((value / count).toFixed(2));
+}
+
 Report.reopenClass({
   groupingForDatapoints(count) {
     if (count < DAILY_LIMIT_DAYS) {
@@ -562,6 +567,7 @@ Report.reopenClass({
         },
       ];
 
+      let appliedAverage = false;
       data.forEach((d) => {
         const date = moment(d.x, "YYYY-MM-DD");
 
@@ -570,15 +576,20 @@ Report.reopenClass({
           !date.isBetween(currentStart, currentEnd)
         ) {
           if (model.average) {
-            const days = currentEnd.diff(currentStart, "day") + 1; // 1 to include start
-            transformedData[currentIndex].y = parseFloat(
-              (transformedData[currentIndex].y / days).toFixed(2)
+            transformedData[currentIndex].y = applyAverage(
+              transformedData[currentIndex].y,
+              currentStart,
+              currentEnd
             );
+
+            appliedAverage = true;
           }
 
           currentIndex += 1;
           currentStart = currentStart.add(1, kind).startOf(isoKind);
           currentEnd = currentEnd.add(1, kind).endOf(isoKind);
+        } else {
+          appliedAverage = false;
         }
 
         if (transformedData[currentIndex]) {
@@ -591,6 +602,14 @@ Report.reopenClass({
         }
       });
 
+      if (model.average && !appliedAverage) {
+        transformedData[currentIndex].y = applyAverage(
+          transformedData[currentIndex].y,
+          currentStart,
+          moment(model.end_date).subtract(1, "day") // remove 1 day as model end date is at 00:00 of next day
+        );
+      }
+
       return transformedData;
     }
 

GitHub sha: 1a6759a5d9e0bd49a99df31bb77c72310d84545b

This commit appears in #13472 which was approved by ZogStriP. It was merged by jjaffeux.