From 889d9284df58b84105e797f0a4bddb5294c3c1d4 Mon Sep 17 00:00:00 2001
From: Hugo SUBTIL <ext.sopra.husubtil@grandlyon.com>
Date: Fri, 7 Oct 2022 14:53:50 +0200
Subject: [PATCH] fix: limit date

---
 src/index.js | 20 +++++++++++---------
 1 file changed, 11 insertions(+), 9 deletions(-)

diff --git a/src/index.js b/src/index.js
index 31ffca3..2b078e3 100644
--- a/src/index.js
+++ b/src/index.js
@@ -131,6 +131,7 @@ async function start(fields, cozyParameters) {
       sgeLogin,
       pointId
     )
+
     startDailyDate = moment(userContractstartDate, 'YYYY-MM-DD')
     startDailyDateString = startDailyDate.format('YYYY-MM-DD')
 
@@ -311,7 +312,7 @@ async function getData(url, apiAuthKey, userLogin, pointId) {
     apikey: apiAuthKey,
   }
 
-  setStartDate()
+  limitStartDate()
 
   const { response } = await soapRequest({
     url: url,
@@ -355,7 +356,7 @@ async function getMaxPowerData(url, apiAuthKey, userLogin, pointId) {
     apikey: apiAuthKey,
   }
 
-  setStartDate()
+  limitStartDate()
 
   const { response } = await soapRequest({
     url: url,
@@ -385,11 +386,16 @@ async function getMaxPowerData(url, apiAuthKey, userLogin, pointId) {
 
 /**
  * If start date exceed the maximum amount of data we can get with one query
- * get only 36 month.
+ * get only 36 month. Or 12 month if manual execution
  * On manual execution, set the start date to one year ago.
  */
-function setStartDate() {
-  if (moment(endDate).diff(startDailyDate, 'months', true) > 36) {
+function limitStartDate() {
+  const livingDuration = moment(endDate).diff(startDailyDate, 'months', true)
+  // We need to prevent case that there is less than 12 month data
+  if (manualExecution && livingDuration > 12) {
+    startDailyDate = moment(endDate).subtract(12, 'month')
+    startDailyDateString = startDailyDate.format('YYYY-MM-DD')
+  } else if (livingDuration > 36) {
     log(
       'info',
       'Start date exceed 36 month, setting start date to current date minus 36 month'
@@ -397,10 +403,6 @@ function setStartDate() {
     startDailyDate = moment(endDate).subtract(36, 'month')
     startDailyDateString = startDailyDate.format('YYYY-MM-DD')
   }
-  if (manualExecution) {
-    startDailyDate = moment(endDate).subtract(12, 'month')
-    startDailyDateString = startDailyDate.format('YYYY-MM-DD')
-  }
 }
 
 /**
-- 
GitLab