From ff13580be7a7376057faaa9269d752717fa04e0a Mon Sep 17 00:00:00 2001
From: git-directory-deploy <>
Date: Wed, 27 Jan 2021 10:54:49 +0100
Subject: [PATCH] publish: fix: set usage point id when refresh token

generated from commit 6f45a986836a8a7af4507a1135138dbf3b69e18b
---
 index.js | 104 ++++++++++++++++++++++++++++++++++++-------------------
 1 file changed, 68 insertions(+), 36 deletions(-)

diff --git a/index.js b/index.js
index 8b284aa..b2325be 100644
--- a/index.js
+++ b/index.js
@@ -122,13 +122,14 @@ const baseUrl = 'https://gw.prd.api.enedis.fr'
  * cozyParameters are static parameters, independents from the account. Most often, it can be a
  * secret api key.
  * @param {Object}  fields
- * @param {string}  fields.access_token - a google access token
- * @param {string}  fields.refresh_token - a google refresh token
+ * @param {string}  fields.access_token - access token
+ * @param {string}  fields.refresh_token - refresh token
  * @param {Object}  cozyParameters - cozy parameters
  * @param {boolean} doRetry - whether we should use the refresh token or not
  */
 async function start(fields, cozyParameters, doRetry = true) {
   log('info', 'Starting the enedis konnector')
+  log("info", "COZY_JOB_MANUAL_EXECUTION: " + process.env.COZY_JOB_MANUAL_EXECUTION)
   const accountId = getAccountId()
   let usage_point_id = ''
   try {
@@ -180,7 +181,6 @@ async function start(fields, cozyParameters, doRetry = true) {
           log('info', `Error during refresh ${err.message}`)
           throw errors.USER_ACTION_NEEDED_OAUTH_OUTDATED
         }
-
         log('info', 'refresh response')
         log('info', JSON.stringify(body))
         fields.access_token = body.attributes.oauth.access_token
@@ -227,33 +227,40 @@ async function getDailyData(token, usagePointID) {
  * If yes only call once the api
  */
 async function startLoadDataProcess(token, usagePointID) {
-  log('info', 'Check history')
-  const isHistory = await isHistoryLoaded('com.grandlyon.enedis.minute')
-  if (isHistory) {
-    log('info', 'launch process without history')
-    await launchLoadDataProcess(
-      token,
-      usagePointID,
-      startLoadDateString,
-      endDateString
-    )
-  } else {
-    log('info', 'launch process with history')
-    for (var i = 0; i < 4; i++) {
-      const increamentedStartDate = moment(startLoadDate)
-      const incrementedEndDate = moment(endDate)
-      const increamentedStartDateString = increamentedStartDate
-        .subtract(7 * i, 'day')
-        .format('YYYY-MM-DD')
-      const incrementedEndDateString = incrementedEndDate
-        .subtract(7 * i, 'day')
-        .format('YYYY-MM-DD')
+  log('info', 'Check consent for user')
+  const isConsent = await checkConsentForLoadCurve(token,
+    usagePointID,
+    startLoadDateString,
+    endDateString)
+  if(isConsent) {
+    log('info', 'Check history')
+    const isHistory = await isHistoryLoaded('com.grandlyon.enedis.minute')
+    if (isHistory) {
+      log('info', 'launch process without history')
       await launchLoadDataProcess(
         token,
         usagePointID,
-        increamentedStartDateString,
-        incrementedEndDateString
+        startLoadDateString,
+        endDateString
       )
+    } else {
+      log('info', 'launch process with history')
+      for (var i = 0; i < 4; i++) {
+        const increamentedStartDate = moment(startLoadDate)
+        const incrementedEndDate = moment(endDate)
+        const increamentedStartDateString = increamentedStartDate
+          .subtract(7 * i, 'day')
+          .format('YYYY-MM-DD')
+        const incrementedEndDateString = incrementedEndDate
+          .subtract(7 * i, 'day')
+          .format('YYYY-MM-DD')
+        await launchLoadDataProcess(
+          token,
+          usagePointID,
+          increamentedStartDateString,
+          incrementedEndDateString
+        )
+      }
     }
   }
 }
@@ -289,10 +296,10 @@ async function launchLoadDataProcess(
 }
 
 /**
- * Retrieve data from the API
- * Format: { value: "W", "date": "YYYY-MM-DD hh:mm:ss" }
+ * Request API and check return code
+ * Return true or false
  */
-async function getLoadData(token, usagePointID, _startDate, _endDate) {
+async function checkConsentForLoadCurve(token, usagePointID, _startDate, _endDate) {
   const dataRequest = {
     method: 'GET',
     uri:
@@ -309,20 +316,45 @@ async function getLoadData(token, usagePointID, _startDate, _endDate) {
     }
   }
   try {
-    const response = await rp(dataRequest)
-    return response
+    await rp(dataRequest)
+    return true
   } catch (err) {
-    if (err.statusCode === 404 || err.code === 404) {
-      log('warning', 'caught an 404 error')
-      log('warning', err.message)
-      log('warning', err)
-      throw errors.USER_ACTION_NEEDED_OAUTH_OUTDATED
+    if ((err.statusCode === 400 || err.code === 400) && err.message.search("ADAM-ERR0075") > 0) {
+      log('warning', 'No consent for load curve')
+      return false
+    } else if (err.statusCode === 403 || err.code === 403) {
+      log('warning', 'No consent for load curve')
+      return false
     } else {
       throw err
     }
   }
 }
 
+/**
+ * Retrieve data from the API
+ * Format: { value: "W", "date": "YYYY-MM-DD hh:mm:ss" }
+ */
+async function getLoadData(token, usagePointID, _startDate, _endDate) {
+  const dataRequest = {
+    method: 'GET',
+    uri:
+      baseUrl +
+      '/v4/metering_data/consumption_load_curve?start=' +
+      _startDate +
+      '&end=' +
+      _endDate +
+      '&usage_point_id=' +
+      usagePointID,
+    headers: {
+      Accept: 'application/json',
+      Authorization: 'Bearer ' + token
+    }
+  }
+  const response = await rp(dataRequest)
+  return response
+}
+
 /**
  * Parse data
  * Remove existing data from DB using hydrateAndFilter
-- 
GitLab