From 39f79a7f9b165e10db459c529ec182aafedb239a Mon Sep 17 00:00:00 2001
From: build-token <build-token>
Date: Wed, 10 Apr 2024 07:34:01 +0000
Subject: [PATCH] publish: Merge branch 'rework-folders' into 'dev'

generated from commit 17753befb0c582b3cee64e3ea33e5728bcd5e5a2
---
 index.js           | 707 +++++++++++++++++++++++----------------------
 onDeleteAccount.js |   5 +-
 2 files changed, 365 insertions(+), 347 deletions(-)

diff --git a/index.js b/index.js
index 478f3ba..bcd6e71 100644
--- a/index.js
+++ b/index.js
@@ -13,7 +13,7 @@ const {
   log
 } = __webpack_require__(1)
 const getDataGenericErrors = __webpack_require__(1465)
-const { isDev, isLocal } = __webpack_require__(1466)
+const { isDev } = __webpack_require__(1466)
 const moment = __webpack_require__(1467)
 __webpack_require__(1604)
 moment.locale('fr') // set the language
@@ -22,13 +22,8 @@ const Sentry = __webpack_require__(1607)
 // eslint-disable-next-line
 const Tracing = __webpack_require__(1691) // Needed for tracking performance in Sentry
 const { version } = __webpack_require__(1728)
-const { createBoConsent, deleteBoConsent } = __webpack_require__(1729)
-const {
-  createGRDFConsent,
-  getAuthToken,
-  getConsents
-} = __webpack_require__(1764)
-const { getAccount, saveAccountData } = __webpack_require__(1775)
+const { getAuthToken, getConsents } = __webpack_require__(1729)
+const { handleConsents, createConsent } = __webpack_require__(1774)
 
 Sentry.init({
   dsn:
@@ -54,126 +49,8 @@ const manualExecution = process.env.COZY_JOB_MANUAL_EXECUTION === 'true'
 const startDate = moment().subtract(manualExecution ? 1 : 3, 'year')
 const endDate = moment().startOf('day')
 
-const ACCOUNT_ID = isLocal() ? 'default_account_id' : 'grdfgrandlyon'
-
 module.exports = new BaseKonnector(start)
 
-/**
- * @param {GRDFConsent[]} consents
- * @param {string} boBaseUrl
- * @param {string} boToken
- * @returns {Promise<boolean>} Returns true if consent needs to be created. Returns false if consent is valid
- */
-async function handleConsents(consents, boBaseUrl, boToken) {
-  if (consents.some(consent => consent.etat_droit_acces === 'Active')) {
-    log('info', 'Found consent "Active"')
-    return false
-  }
-  if (consents.some(consent => consent.etat_droit_acces === 'A valider')) {
-    log('info', 'Found consent "A valider"')
-    throw errors.CHALLENGE_ASKED
-  }
-  if (consents.some(consent => consent.etat_droit_acces === 'Révoquée')) {
-    log('info', 'Found consent "Révoquée"')
-    throw errors.USER_ACTION_NEEDED_ACCOUNT_REMOVED
-  }
-
-  // Check if daily check & if obsolete consent is found, continue otherwise
-  if (
-    !manualExecution &&
-    consents.some(consent => consent.etat_droit_acces === 'Obsolète')
-  ) {
-    log('info', 'Found consent "Obsolète"')
-  }
-
-  if (consents.some(consent => consent.etat_droit_acces === 'A revérifier')) {
-    log('info', 'Found consent "A revérifier"')
-    throw errors.VENDOR_DOWN
-  }
-
-  if (consents.some(consent => consent.etat_droit_acces === 'Refusée')) {
-    log('info', 'Found consent "Refusée"')
-    const accountData = await getAccount(ACCOUNT_ID)
-    if (accountData?.data?.consentId) {
-      await deleteBoConsent({
-        boBaseUrl,
-        boToken,
-        consentId: accountData.data.consentId
-      })
-      delete accountData.data.consentId
-      await saveAccountData(accountData)
-    }
-    if (!manualExecution) {
-      throw errors.USER_ACTION_NEEDED_SCA_REQUIRED
-    }
-  }
-
-  // "message_retour_traitement": "Aucun droit d’accès trouvé." OU Obsolète -> create consent
-  return true
-}
-
-/**
- * Creates consents
- * - first in our back-office
- * - then at GRDF
- * @returns {Promise<boolean>} isWaitingForConsentValidation Boolean that indicates that the consent was created and needs a user validation.
- */
-async function createConsent({
-  bearerToken,
-  pce,
-  email,
-  firstname,
-  lastname,
-  postalCode,
-  startDate,
-  endDate,
-  boToken,
-  boBaseUrl
-}) {
-  const startDateString = moment(startDate).format('YYYY-MM-DD')
-  const endDateConsent = moment(endDate).add(1, 'year')
-  const endDateString = endDateConsent.format('YYYY-MM-DD')
-
-  const { ID: consentId } = await createBoConsent({
-    boBaseUrl,
-    boToken,
-    pce,
-    firstname,
-    lastname,
-    postalCode,
-    endDate: endDateConsent
-  }).catch(err => {
-    log('error', `Failed to create BO consent, ${err}`)
-    throw errors.MAINTENANCE
-  })
-
-  // Save BO consentId into account
-  const accountData = await getAccount(ACCOUNT_ID)
-  await saveAccountData(ACCOUNT_ID, {
-    ...accountData.data,
-    consentId: consentId
-  })
-
-  await createGRDFConsent({
-    bearerToken,
-    email,
-    lastname,
-    pce,
-    postalCode,
-    startDate: startDateString,
-    endDate: endDateString
-  }).catch(async err => {
-    await deleteBoConsent({
-      boBaseUrl,
-      boToken,
-      consentId: consentId
-    })
-    throw err
-  })
-
-  return true
-}
-
 /**
  * The start function is run by the BaseKonnector instance only when it got all the account
  * information (fields). When you run this connector yourself in "standalone" mode or "dev" mode,
@@ -244546,102 +244423,123 @@ module.exports = JSON.parse('{"name":"grdf","version":"1.3.1","engines":{"node":
 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
 
 // @ts-check
-const { log, errors } = __webpack_require__(1)
-const { default: axios } = __webpack_require__(1730)
+const { default: Axios } = __webpack_require__(1730)
+const { errors, log } = __webpack_require__(1)
+const qs = __webpack_require__(1764)
 const Sentry = __webpack_require__(1607)
 
 /**
- * @param {{
- * boBaseUrl: string,
- * boToken: string,
- * pce: string,
- * firstname: string,
- * lastname: string,
- * postalCode: string,
- * endDate: moment.Moment}} args
+ *
+ * @param {string} client_id
+ * @param {string} client_secret
+ * @returns {Promise<{ access_token: string, scope: string, token_type: string, expires_in: number }>}
  */
-async function createBoConsent({
-  boBaseUrl,
-  boToken,
-  pce,
-  lastname,
-  firstname,
-  postalCode,
-  endDate
-}) {
-  log('info', `Query createBoConsent`)
-  const headers = {
-    headers: {
-      Authorization: `Bearer ${boToken}`
-    }
+async function getAuthToken(client_id, client_secret) {
+  log('info', 'getAuthToken')
+  const body = {
+    scope: '/adict/v2',
+    grant_type: 'client_credentials',
+    client_id: client_id,
+    client_secret: client_secret
   }
-
   try {
-    const { data } = await axios.post(
-      `${boBaseUrl}/consent`,
-      {
-        lastname,
-        firstname,
-        pce,
-        postalCode,
-        endDate: endDate.toISOString()
-      },
-      headers
-    )
-    return data
-  } catch (err) {
-    const errorMessage = 'Error while creating BO consent : ' + err.message
-    log('error', errorMessage)
-    Sentry.captureException(errorMessage, {
-      tags: {
-        section: 'createBoConsent'
-      },
-      extra: {
-        pce
-      }
+    const response = await Axios({
+      method: 'POST',
+      url:
+        'https://sofit-sso-oidc.grdf.fr/openam/oauth2/realms/externeGrdf/access_token',
+      headers: { 'content-type': 'application/x-www-form-urlencoded' },
+      data: qs.stringify(body)
     })
-    throw new Error(errors.MAINTENANCE)
+
+    return response.data
+  } catch (error) {
+    log('error', 'Error inside getAuthToken', error)
+    throw errors.VENDOR_DOWN
   }
 }
 
 /**
- * @param {Object} args description
- * @param {string} args.boBaseUrl url
- * @param {string} args.boToken bo token
- * @param {string} args.consentId ID from back office
+ *
+ * @param {string} bearerToken
+ * @param {string} pce
+ * @returns {Promise<GRDFConsent[]>}
  */
-async function deleteBoConsent({ boBaseUrl, boToken, consentId }) {
-  log('info', `Query deleteBoConsent ${consentId}`)
-  const headers = {
-    headers: {
-      Authorization: `Bearer ${boToken}`
+async function getConsents(bearerToken, pce) {
+  try {
+    const response = await fetch('https://api.grdf.fr/adict/v2/droits_acces', {
+      method: 'POST',
+      headers: {
+        Authorization: `Bearer ${bearerToken}`,
+        'Content-Type': 'application/json'
+      },
+      body: JSON.stringify({ id_pce: [pce] })
+    })
+    const rawData = await response.text()
+    const consents = []
+    if (rawData !== null && rawData !== '') {
+      // @ts-ignore
+      rawData.match(/.+/g).map(rawConsent => {
+        const consent = JSON.parse(rawConsent)
+        if (consent.id_droit_acces) {
+          consents.push(consent)
+        }
+      })
     }
+
+    log('info', `Found ${consents.length} consents for pce`)
+    const etatDroitsAcces = consents.map(consent => consent.etat_droit_acces)
+    log('info', `Droits d'accès des consentements trouvés: ${etatDroitsAcces}`)
+    return consents
+  } catch (error) {
+    log('error', 'Error while getting consent')
+    log('error', error)
+    throw errors.VENDOR_DOWN
   }
+}
+
+async function createGRDFConsent({
+  bearerToken,
+  pce,
+  email,
+  lastname,
+  postalCode,
+  startDate,
+  endDate
+}) {
   try {
-    const { data } = await axios.delete(
-      `${boBaseUrl}/consent/${consentId}`,
-      headers
-    )
-    return data
-  } catch (err) {
-    const errorMessage = 'Error while deleting BO consent : ' + err.message
-    log('error', errorMessage)
-    Sentry.captureException(errorMessage, {
-      tags: {
-        section: 'deleteBoConsent'
-      },
-      extra: {
-        consentId: consentId
+    log('info', `Creating GRDF consent from ${startDate} to ${endDate}`)
+    const response = await Axios({
+      method: 'PUT',
+      url: `https://api.grdf.fr/adict/v2/pce/${pce}/droit_acces`,
+      headers: { Authorization: `Bearer ${bearerToken}` },
+      data: {
+        role_tiers: 'AUTORISE_CONTRAT_FOURNITURE',
+        raison_sociale: '',
+        nom_titulaire: lastname,
+        code_postal: postalCode,
+        courriel_titulaire: email,
+        // numero_telephone_mobile_titulaire: '',
+        date_debut_droit_acces: startDate,
+        perim_donnees_conso_debut: startDate,
+        date_fin_droit_acces: endDate,
+        perim_donnees_conso_fin: endDate,
+        perim_donnees_contractuelles: 'Vrai',
+        perim_donnees_techniques: 'Vrai',
+        perim_donnees_informatives: 'Vrai',
+        perim_donnees_publiees: 'Vrai'
       }
     })
-    throw new Error(errors.MAINTENANCE)
+    log('info', response.data.message_retour_traitement)
+    return true
+  } catch (error) {
+    log('error', `Failed to create GRDF consent`)
+    log('error', error.response.data)
+    Sentry.captureException('Failed to create GRDF consent')
+    throw errors.USER_ACTION_NEEDED_CGU_FORM
   }
 }
 
-module.exports = {
-  createBoConsent,
-  deleteBoConsent
-}
+module.exports = { createGRDFConsent, getAuthToken, getConsents }
 
 
 /***/ }),
@@ -247991,134 +247889,12 @@ module.exports = function spread(callback) {
 /* 1764 */
 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
 
-// @ts-check
-const { default: Axios } = __webpack_require__(1730)
-const { errors, log } = __webpack_require__(1)
-const qs = __webpack_require__(1765)
-
-/**
- *
- * @param {string} client_id
- * @param {string} client_secret
- * @returns {Promise<{ access_token: string, scope: string, token_type: string, expires_in: number }>}
- */
-async function getAuthToken(client_id, client_secret) {
-  log('info', 'getAuthToken')
-  const body = {
-    scope: '/adict/v2',
-    grant_type: 'client_credentials',
-    client_id: client_id,
-    client_secret: client_secret
-  }
-  try {
-    const response = await Axios({
-      method: 'POST',
-      url:
-        'https://sofit-sso-oidc.grdf.fr/openam/oauth2/realms/externeGrdf/access_token',
-      headers: { 'content-type': 'application/x-www-form-urlencoded' },
-      data: qs.stringify(body)
-    })
-
-    return response.data
-  } catch (error) {
-    log('error', 'Error inside getAuthToken', error)
-    throw errors.VENDOR_DOWN
-  }
-}
-
-/**
- *
- * @param {string} bearerToken
- * @param {string} pce
- * @returns {Promise<GRDFConsent[]>}
- */
-async function getConsents(bearerToken, pce) {
-  try {
-    const response = await fetch('https://api.grdf.fr/adict/v2/droits_acces', {
-      method: 'POST',
-      headers: {
-        Authorization: `Bearer ${bearerToken}`,
-        'Content-Type': 'application/json'
-      },
-      body: JSON.stringify({ id_pce: [pce] })
-    })
-    const rawData = await response.text()
-    const consents = []
-    if (rawData !== null && rawData !== '') {
-      // @ts-ignore
-      rawData.match(/.+/g).map(rawConsent => {
-        const consent = JSON.parse(rawConsent)
-        if (consent.id_droit_acces) {
-          consents.push(consent)
-        }
-      })
-    }
-
-    log('info', `Found ${consents.length} consents for pce`)
-    const etatDroitsAcces = consents.map(consent => consent.etat_droit_acces)
-    log('info', `Droits d'accès des consentements trouvés: ${etatDroitsAcces}`)
-    return consents
-  } catch (error) {
-    log('error', 'Error while getting consent')
-    log('error', error)
-    throw errors.VENDOR_DOWN
-  }
-}
-
-async function createGRDFConsent({
-  bearerToken,
-  pce,
-  email,
-  lastname,
-  postalCode,
-  startDate,
-  endDate
-}) {
-  try {
-    log('info', `Creating GRDF consent from ${startDate} to ${endDate}`)
-    const response = await Axios({
-      method: 'PUT',
-      url: `https://api.grdf.fr/adict/v2/pce/${pce}/droit_acces`,
-      headers: { Authorization: `Bearer ${bearerToken}` },
-      data: {
-        role_tiers: 'AUTORISE_CONTRAT_FOURNITURE',
-        raison_sociale: '',
-        nom_titulaire: lastname,
-        code_postal: postalCode,
-        courriel_titulaire: email,
-        // numero_telephone_mobile_titulaire: '',
-        date_debut_droit_acces: startDate,
-        perim_donnees_conso_debut: startDate,
-        date_fin_droit_acces: endDate,
-        perim_donnees_conso_fin: endDate,
-        perim_donnees_contractuelles: 'Vrai',
-        perim_donnees_techniques: 'Vrai',
-        perim_donnees_informatives: 'Vrai',
-        perim_donnees_publiees: 'Vrai'
-      }
-    })
-    log('info', response.data.message_retour_traitement)
-    return true
-  } catch (error) {
-    log('error', `Failed to create GRDF consent`)
-    log('error', error.response.data)
-    throw errors.USER_ACTION_NEEDED_CGU_FORM
-  }
-}
-
-module.exports = { createGRDFConsent, getAuthToken, getConsents }
-
-
-/***/ }),
-/* 1765 */
-/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
-
 "use strict";
 
 
-var stringify = __webpack_require__(1766);
-var parse = __webpack_require__(1774);
-var formats = __webpack_require__(1773);
+var stringify = __webpack_require__(1765);
+var parse = __webpack_require__(1773);
+var formats = __webpack_require__(1772);
 
 module.exports = {
     formats: formats,
@@ -248128,15 +247904,15 @@ module.exports = {
 
 
 /***/ }),
-/* 1766 */
+/* 1765 */
 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
 
 "use strict";
 
 
-var getSideChannel = __webpack_require__(1767);
-var utils = __webpack_require__(1772);
-var formats = __webpack_require__(1773);
+var getSideChannel = __webpack_require__(1766);
+var utils = __webpack_require__(1771);
+var formats = __webpack_require__(1772);
 var has = Object.prototype.hasOwnProperty;
 
 var arrayPrefixGenerators = {
@@ -248455,14 +248231,14 @@ module.exports = function (object, opts) {
 
 
 /***/ }),
-/* 1767 */
+/* 1766 */
 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
 
 "use strict";
 
 
 var GetIntrinsic = __webpack_require__(881);
-var callBound = __webpack_require__(1768);
+var callBound = __webpack_require__(1767);
 var inspect = __webpack_require__(902);
 
 var $TypeError = GetIntrinsic('%TypeError%');
@@ -248586,7 +248362,7 @@ module.exports = function getSideChannel() {
 
 
 /***/ }),
-/* 1768 */
+/* 1767 */
 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
 
 "use strict";
@@ -248594,7 +248370,7 @@ module.exports = function getSideChannel() {
 
 var GetIntrinsic = __webpack_require__(881);
 
-var callBind = __webpack_require__(1769);
+var callBind = __webpack_require__(1768);
 
 var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
 
@@ -248608,7 +248384,7 @@ module.exports = function callBoundIntrinsic(name, allowMissing) {
 
 
 /***/ }),
-/* 1769 */
+/* 1768 */
 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
 
 "use strict";
@@ -248616,7 +248392,7 @@ module.exports = function callBoundIntrinsic(name, allowMissing) {
 
 var bind = __webpack_require__(877);
 var GetIntrinsic = __webpack_require__(881);
-var setFunctionLength = __webpack_require__(1770);
+var setFunctionLength = __webpack_require__(1769);
 
 var $TypeError = GetIntrinsic('%TypeError%');
 var $apply = GetIntrinsic('%Function.prototype.apply%');
@@ -248659,14 +248435,14 @@ if ($defineProperty) {
 
 
 /***/ }),
-/* 1770 */
+/* 1769 */
 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
 
 "use strict";
 
 
 var GetIntrinsic = __webpack_require__(881);
-var define = __webpack_require__(1771);
+var define = __webpack_require__(1770);
 var hasDescriptors = __webpack_require__(883)();
 var gOPD = __webpack_require__(880);
 
@@ -248707,7 +248483,7 @@ module.exports = function setFunctionLength(fn, length) {
 
 
 /***/ }),
-/* 1771 */
+/* 1770 */
 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
 
 "use strict";
@@ -248782,13 +248558,13 @@ module.exports = function defineDataProperty(
 
 
 /***/ }),
-/* 1772 */
+/* 1771 */
 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
 
 "use strict";
 
 
-var formats = __webpack_require__(1773);
+var formats = __webpack_require__(1772);
 
 var has = Object.prototype.hasOwnProperty;
 var isArray = Array.isArray;
@@ -249041,7 +248817,7 @@ module.exports = {
 
 
 /***/ }),
-/* 1773 */
+/* 1772 */
 /***/ ((module) => {
 
 "use strict";
@@ -249071,13 +248847,13 @@ module.exports = {
 
 
 /***/ }),
-/* 1774 */
+/* 1773 */
 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
 
 "use strict";
 
 
-var utils = __webpack_require__(1772);
+var utils = __webpack_require__(1771);
 
 var has = Object.prototype.hasOwnProperty;
 var isArray = Array.isArray;
@@ -249341,6 +249117,144 @@ module.exports = function (str, opts) {
 };
 
 
+/***/ }),
+/* 1774 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+// @ts-check
+
+const { log, errors } = __webpack_require__(1)
+const { getAccount, saveAccountData } = __webpack_require__(1775)
+const { deleteBoConsent, createBoConsent } = __webpack_require__(1776)
+const moment = __webpack_require__(1467)
+const { isLocal } = __webpack_require__(1466)
+const { createGRDFConsent } = __webpack_require__(1729)
+__webpack_require__(1604)
+moment.locale('fr') // set the language
+moment.tz.setDefault('Europe/Paris') // set the timezone
+
+const ACCOUNT_ID = isLocal() ? 'default_account_id' : 'grdfgrandlyon'
+const manualExecution = process.env.COZY_JOB_MANUAL_EXECUTION === 'true'
+
+/**
+ * @param {GRDFConsent[]} consents
+ * @param {string} boBaseUrl
+ * @param {string} boToken
+ * @returns {Promise<boolean>} Returns true if consent needs to be created. Returns false if consent is valid
+ */
+async function handleConsents(consents, boBaseUrl, boToken) {
+  if (consents.some(consent => consent.etat_droit_acces === 'Active')) {
+    log('info', 'Found consent "Active"')
+    return false
+  }
+  if (consents.some(consent => consent.etat_droit_acces === 'A valider')) {
+    log('info', 'Found consent "A valider"')
+    throw errors.CHALLENGE_ASKED
+  }
+  if (consents.some(consent => consent.etat_droit_acces === 'Révoquée')) {
+    log('info', 'Found consent "Révoquée"')
+    throw errors.USER_ACTION_NEEDED_ACCOUNT_REMOVED
+  }
+
+  // Check if daily check & if obsolete consent is found, continue otherwise
+  if (
+    !manualExecution &&
+    consents.some(consent => consent.etat_droit_acces === 'Obsolète')
+  ) {
+    log('info', 'Found consent "Obsolète"')
+  }
+
+  if (consents.some(consent => consent.etat_droit_acces === 'A revérifier')) {
+    log('info', 'Found consent "A revérifier"')
+    throw errors.VENDOR_DOWN
+  }
+
+  if (consents.some(consent => consent.etat_droit_acces === 'Refusée')) {
+    log('info', 'Found consent "Refusée"')
+    const accountData = await getAccount(ACCOUNT_ID)
+    if (accountData?.data?.consentId) {
+      await deleteBoConsent({
+        boBaseUrl,
+        boToken,
+        consentId: accountData.data.consentId
+      })
+      delete accountData.data.consentId
+      await saveAccountData(accountData)
+    }
+    if (!manualExecution) {
+      throw errors.USER_ACTION_NEEDED_SCA_REQUIRED
+    }
+  }
+
+  // "message_retour_traitement": "Aucun droit d’accès trouvé." OU Obsolète -> create consent
+  return true
+}
+
+/**
+ * Creates consents
+ * - first in our back-office
+ * - then at GRDF
+ * @returns {Promise<boolean>} isWaitingForConsentValidation Boolean that indicates that the consent was created and needs a user validation.
+ */
+async function createConsent({
+  bearerToken,
+  pce,
+  email,
+  firstname,
+  lastname,
+  postalCode,
+  startDate,
+  endDate,
+  boToken,
+  boBaseUrl
+}) {
+  const startDateString = moment(startDate).format('YYYY-MM-DD')
+  const endDateConsent = moment(endDate).add(1, 'year')
+  const endDateString = endDateConsent.format('YYYY-MM-DD')
+
+  const { ID: consentId } = await createBoConsent({
+    boBaseUrl,
+    boToken,
+    pce,
+    firstname,
+    lastname,
+    postalCode,
+    endDate: endDateConsent
+  }).catch(err => {
+    log('error', `Failed to create BO consent, ${err}`)
+    throw errors.MAINTENANCE
+  })
+
+  // Save BO consentId into account
+  const accountData = await getAccount(ACCOUNT_ID)
+  await saveAccountData(ACCOUNT_ID, {
+    ...accountData.data,
+    consentId: consentId
+  })
+
+  await createGRDFConsent({
+    bearerToken,
+    email,
+    lastname,
+    pce,
+    postalCode,
+    startDate: startDateString,
+    endDate: endDateString
+  }).catch(async err => {
+    await deleteBoConsent({
+      boBaseUrl,
+      boToken,
+      consentId: consentId
+    })
+    throw err
+  })
+
+  return true
+}
+
+module.exports = { handleConsents, createConsent }
+
+
 /***/ }),
 /* 1775 */
 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
@@ -249395,6 +249309,109 @@ async function saveAccountData(accountId, accountData) {
 module.exports = { getAccount, saveAccountData }
 
 
+/***/ }),
+/* 1776 */
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+// @ts-check
+const { log, errors } = __webpack_require__(1)
+const { default: axios } = __webpack_require__(1730)
+const Sentry = __webpack_require__(1607)
+
+/**
+ * @param {{
+ * boBaseUrl: string,
+ * boToken: string,
+ * pce: string,
+ * firstname: string,
+ * lastname: string,
+ * postalCode: string,
+ * endDate: moment.Moment}} args
+ */
+async function createBoConsent({
+  boBaseUrl,
+  boToken,
+  pce,
+  lastname,
+  firstname,
+  postalCode,
+  endDate
+}) {
+  log('info', `Query createBoConsent`)
+  const headers = {
+    headers: {
+      Authorization: `Bearer ${boToken}`
+    }
+  }
+
+  try {
+    const { data } = await axios.post(
+      `${boBaseUrl}/consent`,
+      {
+        lastname,
+        firstname,
+        pce,
+        postalCode,
+        endDate: endDate.toISOString()
+      },
+      headers
+    )
+    return data
+  } catch (err) {
+    const errorMessage = 'Error while creating BO consent : ' + err.message
+    log('error', errorMessage)
+    Sentry.captureException(errorMessage, {
+      tags: {
+        section: 'createBoConsent'
+      },
+      extra: {
+        pce
+      }
+    })
+    throw new Error(errors.MAINTENANCE)
+  }
+}
+
+/**
+ * @param {Object} args description
+ * @param {string} args.boBaseUrl url
+ * @param {string} args.boToken bo token
+ * @param {string} args.consentId ID from back office
+ */
+async function deleteBoConsent({ boBaseUrl, boToken, consentId }) {
+  log('info', `Query deleteBoConsent ${consentId}`)
+  const headers = {
+    headers: {
+      Authorization: `Bearer ${boToken}`
+    }
+  }
+  try {
+    const { data } = await axios.delete(
+      `${boBaseUrl}/consent/${consentId}`,
+      headers
+    )
+    return data
+  } catch (err) {
+    const errorMessage = 'Error while deleting BO consent : ' + err.message
+    log('error', errorMessage)
+    Sentry.captureException(errorMessage, {
+      tags: {
+        section: 'deleteBoConsent'
+      },
+      extra: {
+        consentId: consentId
+      }
+    })
+    throw new Error(errors.MAINTENANCE)
+  }
+}
+
+module.exports = {
+  createBoConsent,
+  deleteBoConsent
+}
+
+
 /***/ })
 /******/ 	]);
 /************************************************************************/
diff --git a/onDeleteAccount.js b/onDeleteAccount.js
index f0f8da5..cbc310c 100644
--- a/onDeleteAccount.js
+++ b/onDeleteAccount.js
@@ -243997,7 +243997,8 @@ var SpanStatus; (function (SpanStatus) {
 /* 1773 */,
 /* 1774 */,
 /* 1775 */,
-/* 1776 */
+/* 1776 */,
+/* 1777 */
 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
 
 const { log } = __webpack_require__(1)
@@ -244132,7 +244133,7 @@ module.exports = { onDeleteAccount }
 /******/ 	// module cache are used so entry inlining is disabled
 /******/ 	// startup
 /******/ 	// Load entry module and return exports
-/******/ 	var __webpack_exports__ = __webpack_require__(__webpack_require__.s = 1776);
+/******/ 	var __webpack_exports__ = __webpack_require__(__webpack_require__.s = 1777);
 /******/ 	
 /******/ })()
 ;
\ No newline at end of file
-- 
GitLab