From 3ac185809b90d692b5303579ad909c78da012da9 Mon Sep 17 00:00:00 2001
From: build-token <build-token>
Date: Mon, 1 Aug 2022 15:17:25 +0000
Subject: [PATCH] publish: Merge branch 'feat/insee-code' of
 https://forge.grandlyon.com/web-et-numerique/llle_project/enedis-sge-konnector
 into feat/insee-code

generated from commit fe2d077dc932bad22401813f1fcf6989fff2f55b
---
 index.js | 83 +++++++++++++++++++++++++++++++++++++++-----------------
 1 file changed, 58 insertions(+), 25 deletions(-)

diff --git a/index.js b/index.js
index 2dbd786..93eaa84 100644
--- a/index.js
+++ b/index.js
@@ -22,6 +22,7 @@ const {
   formateDataForDoctype,
   parseTags,
   parseValue,
+  parseUserPdl,
 } = __webpack_require__(1555)
 const {
   consulterDonneesTechniquesContractuelles,
@@ -85,7 +86,9 @@ async function start(fields, cozyParameters) {
   log('info', 'User Logging...')
 
   if (await isFirstStart()) {
-    if (!(await verifyUserIdentity(fields))) {
+    if (
+      !(await verifyUserIdentity(fields, baseUrl, apiAuthKey, loginUtilisateur))
+    ) {
       throw errors.LOGIN_FAILED
     }
     await createBoConsent()
@@ -114,16 +117,29 @@ async function start(fields, cozyParameters) {
 /**
  * Verify user identity
  * @param {object} fields
+ * @param {string} baseUrl
+ * @param {string} apiAuthKey
+ * @param {string} loginUtilisateur
  */
-async function verifyUserIdentity(fields) {
-  const inseeCode = getInseeCode(fields.postalCode)
-  const user = await findUser(
+async function verifyUserIdentity(
+  fields,
+  baseUrl,
+  apiAuthKey,
+  loginUtilisateur
+) {
+  const inseeCode = await getInseeCode(fields.postalCode)
+
+  const pdl = await findUserPdl(
+    `${baseUrl}/enedis_SDE_recherche-point/1.0`,
+    apiAuthKey,
+    loginUtilisateur,
     fields.name,
     fields.addresse,
     fields.postalCode,
     inseeCode
   )
-  if (fields.pointId !== user.pointId) {
+
+  if (fields.pointId != pdl) {
     log('error', 'PointId does not match')
     return false
   }
@@ -460,14 +476,15 @@ async function agregateMonthAndYearData(data) {
  * @returns {boolean}
  */
 function isFirstStart() {
+  console.log('isFirstStart')
   //TODO: Implement
-  return false
+  return true
 }
 
 /**
- * @return {User}
+ * @return {Promise<string>} User Pdl
  */
-async function findUser(
+async function findUserPdl(
   url,
   apiAuthKey,
   appLogin,
@@ -481,11 +498,10 @@ async function findUser(
     'Content-Type': 'text/xml;charset=UTF-8',
     apikey: apiAuthKey,
   }
-
   const { response } = await soapRequest({
     url: url,
     headers: sampleHeaders,
-    xml: rechercherPoint(appLogin, name, addresse, postalCode, inseeCode),
+    xml: rechercherPoint(appLogin, name, postalCode, inseeCode, addresse),
   }).catch(err => {
     log('error', 'rechercherPointResponse')
     log('error', err)
@@ -493,16 +509,15 @@ async function findUser(
     //TODO: handling code error SGT4F6 and SGT432 into USER_ACTIon_NEEDED
   })
 
-  //TODO: handle reply
-  xml2js.parseString(
-    response.body,
-    {
-      tagNameProcessors: [parseTags],
-      valueProcessors: [parseValue],
-      explicitArray: false,
-    },
-    processStartDate()
-  )
+  const parsedReply = await xml2js.parseStringPromise(response.body, {
+    tagNameProcessors: [parseTags],
+    valueProcessors: [parseValue],
+    explicitArray: false,
+  })
+
+  //TODO: handle errors
+  console.log(parsedReply)
+  return parseUserPdl(parsedReply)
 }
 
 
@@ -223171,6 +223186,19 @@ module.exports = {
 const { log } = __webpack_require__(1)
 const moment = __webpack_require__(1373)
 
+/**
+ * Return User PDL
+ * @param {string} result
+ * @returns {string}
+ */
+function parseUserPdl(result) {
+  log('info', 'Parsing User Pdl')
+  const json = JSON.stringify(result)
+  return JSON.parse(json)['Envelope']['Body']['rechercherPointResponse'][
+    'points'
+  ]['point']['$'].id
+}
+
 /**
  * Return start date
  * @param {string} result
@@ -223178,7 +223206,7 @@ const moment = __webpack_require__(1373)
  */
 function parseSgeXmlTechnicalData(result) {
   log('info', 'Parsing technical data')
-  let json = JSON.stringify(result)
+  const json = JSON.stringify(result)
   return JSON.parse(json)['Envelope']['Body'][
     'consulterDonneesTechniquesContractuellesResponse'
   ]['point']['donneesGenerales'][
@@ -223193,7 +223221,7 @@ function parseSgeXmlTechnicalData(result) {
  */
 function parseSgeXmlData(result) {
   log('info', 'Parsing list of documents')
-  let json = JSON.stringify(result)
+  const json = JSON.stringify(result)
   return JSON.parse(json)['Envelope']['Body'][
     'consulterMesuresDetailleesResponse'
   ]['grandeur']['mesure']
@@ -223207,7 +223235,7 @@ function parseSgeXmlData(result) {
 async function formateDataForDoctype(data) {
   log('info', 'Formating data')
   return data.map(record => {
-    let date = moment(record.d, 'YYYY/MM/DD h:mm:ss')
+    const date = moment(record.d, 'YYYY/MM/DD h:mm:ss')
     return {
       load: record.v,
       year: parseInt(date.format('YYYY')),
@@ -223251,6 +223279,7 @@ module.exports = {
   formateDataForDoctype,
   parseTags,
   parseValue,
+  parseUserPdl,
 }
 
 
@@ -223385,11 +223414,15 @@ function consulterDonneesTechniquesContractuelles(pointId, appLogin) {
  * @param {string} name
  * @param {string} postalCode
  * @param {string} inseeCode
- * @param {string} address
+ * @param {string} [address]
  * @returns {string} PDL
  */
 function rechercherPoint(appLogin, name, postalCode, inseeCode, address) {
-  log('info', `Query rechercherPoint - postal code: ${postalCode}`)
+  log(
+    'info',
+    `Query rechercherPoint - postal code / insee code: ${postalCode} / ${inseeCode}`
+  )
+  //TODO: handle address
   return `<?xml version='1.0' encoding='utf-8'?>
   <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
      xmlns:v2="http://www.enedis.fr/sge/b2b/services/rechercherpoint/v2.0"
-- 
GitLab