Skip to content
Snippets Groups Projects
index.js 7.56 MiB
Newer Older
  • Learn to ignore specific revisions
  • const { log, errors } = __webpack_require__(1)
    const soapRequest = __webpack_require__(1331)
    const { parseUserPdl, parseTags, parseValue } = __webpack_require__(1555)
    const { rechercherPoint } = __webpack_require__(1556)
    const xml2js = __webpack_require__(1513)
    
    /**
     * @param {string} url
     * @param {string} apiAuthKey
     * @param {string} appLogin
     * @param {string} name
     * @param {string} address
     * @param {string} postalCode
     * @param {string} inseeCode
     * @return {Promise<string | null>} User Pdl
     */
    async function findUserPdl(
      url,
      apiAuthKey,
      appLogin,
      name,
      address,
      postalCode,
      inseeCode
    ) {
      log('info', 'Fetching user data')
      const sgeHeaders = {
        'Content-Type': 'text/xml;charset=UTF-8',
        apikey: apiAuthKey,
      }
    
      const { response } = await soapRequest({
        url: url,
        headers: sgeHeaders,
        xml: rechercherPoint(appLogin, name, postalCode, inseeCode, address),
      }).catch(err => {
        log('error', 'rechercherPointResponse')
        log('error', err)
        throw errors.LOGIN_FAILED
      })
    
      const parsedReply = await xml2js.parseStringPromise(response.body, {
        tagNameProcessors: [parseTags],
        valueProcessors: [parseValue],
        explicitArray: false,
      })
    
      try {
        return parseUserPdl(parsedReply)
      } catch (error) {
        log('error', 'Error while parsing user PDL: ' + error)
        log(
          'error',
          `Enedis issue ${parsedReply.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${parsedReply.Envelope.Body.Fault.faultstring}`
        )
        throw errors.LOGIN_FAILED
      }
    }
    
    module.exports = { findUserPdl }
    
    
    /***/ }),
    /* 1597 */
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    // @ts-check
    const { default: axios } = __webpack_require__(1558)
    const { log, errors } = __webpack_require__(1)
    
    const API_URL = 'https://apicarto.ign.fr/api/codes-postaux/communes'
    
    /**
     * Return inseeCode given a postalCode
     * @param {string} postalCode
     * @param {string} [city]
     * @return {Promise<string>} inseeCode
     */
    async function getInseeCode(postalCode, city) {
      try {
        log('info', `Query getInseeCode for postalCode ${postalCode} / ${city}`)
        const response = await axios.get(`${API_URL}/${postalCode}`)
    
        if (response.data.length === 1) {
          return response.data[0].codeCommune
        } else {
          if (!city) throw errors.USER_ACTION_NEEDED
    
          const filteredResponse = response.data.filter(
            town => town.nomCommune.toLowerCase() === city.toLowerCase()
          )
          return filteredResponse[0].codeCommune
        }
      } catch (error) {
        log(
          'error',
          `Query getInseeCode failed for postalCode ${postalCode} / ${city}`
        )
        throw errors.USER_ACTION_NEEDED
      }
    }
    
    module.exports = {
      getInseeCode,
    }
    
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ }),
    /* 1598 */
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    // @ts-check
    const { log, errors } = __webpack_require__(1)
    const soapRequest = __webpack_require__(1331)
    const { parseTags, parseValue, parseServiceId } = __webpack_require__(1555)
    const { commanderCollectePublicationMesures } = __webpack_require__(1556)
    const xml2js = __webpack_require__(1513)
    
    /**
     * @param {string} url
     * @param {string} apiAuthKey
     * @param {string} appLogin
     * @param {string} name
    
     * @param {number} pointId
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * @param {string} startDate
     * @param {string} endDate
     * @return {Promise<number>} User contractId
     */
    async function activateContract(
      url,
      apiAuthKey,
      appLogin,
      contractId,
      name,
      pointId,
      startDate,
      endDate
    ) {
      log('info', 'activateContract')
      const sgeHeaders = {
        'Content-Type': 'text/xml;charset=UTF-8',
        apikey: apiAuthKey,
      }
    
      const { response } = await soapRequest({
    
        url: `${url}/enedis_SGE_CommandeCollectePublicationMesures/1.0`,
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        headers: sgeHeaders,
        xml: commanderCollectePublicationMesures(
          appLogin,
          contractId,
          pointId,
          name,
          startDate,
          endDate
        ),
      }).catch(err => {
        log('error', 'commanderCollectePublicationMesures')
        log('error', err)
        throw errors.LOGIN_FAILED
      })
    
      const parsedReply = await xml2js.parseStringPromise(response.body, {
        tagNameProcessors: [parseTags],
        valueProcessors: [parseValue],
        explicitArray: false,
      })
    
      try {
        return parseServiceId(parsedReply)
      } catch (error) {
    
        log('error', 'Error while activating contract: ' + error)
        log(
          'error',
          `Enedis issue ${parsedReply.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${parsedReply.Envelope.Body.Fault.faultstring}`
        )
        //TODO: handle SGT4B8: Il existe déjà plusieurs demandes en cours sur le point ?
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        throw errors.LOGIN_FAILED
      }
    }
    
    module.exports = { activateContract }
    
    
    /***/ }),
    /* 1599 */
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    // @ts-check
    const { log, errors } = __webpack_require__(1)
    const soapRequest = __webpack_require__(1331)
    const { parseTags, parseValue, parseContracts } = __webpack_require__(1555)
    const { rechercherServicesSouscritsMesures } = __webpack_require__(1556)
    const xml2js = __webpack_require__(1513)
    
    const { contractState, contractLibelle } = __webpack_require__(1600)
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    
    /**
     * @param {string} url
     * @param {string} apiAuthKey
     * @param {string} appLogin
    
     * @param {number} pointId
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * @return {Promise<number | null>} User contractId
     */
    async function verifyContract(url, apiAuthKey, appLogin, contractId, pointId) {
      log('info', 'verifyContract')
      const sgeHeaders = {
        'Content-Type': 'text/xml;charset=UTF-8',
        apikey: apiAuthKey,
      }
    
      const { response } = await soapRequest({
        url: `${url}/enedis_SGE_RechercheServicesMesures/1.0`,
        headers: sgeHeaders,
        xml: rechercherServicesSouscritsMesures(appLogin, contractId, pointId),
      }).catch(err => {
        log('error', 'rechercherServicesSouscritsMesures')
        log('error', err)
        throw errors.LOGIN_FAILED
      })
    
      const parsedReply = await xml2js.parseStringPromise(response.body, {
        tagNameProcessors: [parseTags],
        valueProcessors: [parseValue],
        explicitArray: false,
      })
    
      try {
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        const currentContracts = parseContracts(parsedReply)
    
        let currentContract = null
        if (Array.isArray(currentContracts)) {
          currentContract = parseContracts(parsedReply)[0]
        } else {
          currentContract = parseContracts(parsedReply)
        }
        if (
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
          (currentContract.etatCode === contractState.ACTIF ||
            currentContract.etatCode === contractState.DEMANDE) &&
    
          currentContract.serviceSouscritLibelle === contractLibelle.ACTIF
        )
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
          return currentContract.serviceSouscritId
        return null
      } catch (error) {
        log('error', 'Error while parsing user contract: ' + error)
    
        log(
          'error',
          `Enedis issue ${parsedReply.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${parsedReply.Envelope.Body.Fault.faultstring}`
        )
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        throw errors.LOGIN_FAILED
      }
    }
    
    module.exports = { verifyContract }
    
    
    /***/ }),
    /* 1600 */
    /***/ ((module) => {
    
    /**
     * Enum for contract-state values.
     * @readonly
     * @enum {number}
     */
    const contractState = {
      TERMINE: 'TERMINE',
      ACTIF: 'ACTIF',
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      DEMANDE: 'DEMANDE',
    
    /**
     * Enum for contractLibelle values.
     * @readonly
     * @enum {number}
     */
    const contractLibelle = {
      ACTIF:
        'Collecte de la courbe de charge au pas 30 min avec transmission quotidienne des données brutes en soutirage',
    }
    
    module.exports = { contractState, contractLibelle }
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    
    
    /***/ }),
    /* 1601 */
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    // @ts-check
    const { log, errors } = __webpack_require__(1)
    const soapRequest = __webpack_require__(1331)
    const { parseTags, parseValue } = __webpack_require__(1555)
    const { commanderArretServiceSouscritMesures } = __webpack_require__(1556)
    const xml2js = __webpack_require__(1513)
    
    /**
     * @param {string} url
     * @param {string} apiAuthKey
     * @param {string} appLogin
    
     * @param {number} pointId
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * @param {number} serviceId
     * @return {Promise<string>} User contractId
     */
    async function terminateContract(
      url,
      apiAuthKey,
      appLogin,
      contractId,
      pointId,
      serviceId
    ) {
    
      log('info', 'terminateContract')
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      const sgeHeaders = {
        'Content-Type': 'text/xml;charset=UTF-8',
        apikey: apiAuthKey,
      }
    
      const { response } = await soapRequest({
    
        url: `${url}/enedis_SGE_CommandeArretServiceSouscritMesures/1.0`,
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        headers: sgeHeaders,
        xml: commanderArretServiceSouscritMesures(
          appLogin,
          contractId,
          pointId,
          serviceId
        ),
      }).catch(err => {
        log('error', 'commanderArretServiceSouscritMesures')
        log('error', err)
        throw errors.VENDOR_DOWN
      })
    
      const parsedReply = await xml2js.parseStringPromise(response.body, {
        tagNameProcessors: [parseTags],
        valueProcessors: [parseValue],
        explicitArray: false,
      })
    
      try {
        // We don't need any action on reply for now
    
        if (parsedReply.Envelope.Body.Fault) {
          log(
            'error',
            `Enedis issue ${parsedReply.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${parsedReply.Envelope.Body.Fault.faultstring}`
          )
        }
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        return parsedReply
      } catch (error) {
        log('error', 'Error while parsing user contract termination: ' + error)
    
        log(
          'error',
          `Enedis issue ${parsedReply.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${parsedReply.Envelope.Body.Fault.faultstring}`
        )
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        throw errors.VENDOR_DOWN
      }
    }
    
    module.exports = { terminateContract }
    
    
    /***/ }),
    /* 1602 */
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    // @ts-check
    const { log, errors } = __webpack_require__(1)
    const soapRequest = __webpack_require__(1331)
    const {
      parseTags,
      parseValue,
      parseContractStartDate,
    } = __webpack_require__(1555)
    const xml2js = __webpack_require__(1513)
    const { consulterDonneesTechniquesContractuelles } = __webpack_require__(1556)
    
    /**
     * Get user contract start date
     * @param {string} url
     * @param {string} apiAuthKey
     * @param {string} userLogin
     * @param {number} pointId
     * @returns {Promise<string>}
     */
    async function getContractStartDate(url, apiAuthKey, userLogin, pointId) {
      log('info', 'Fetching data start date')
      const sgeHeaders = {
        'Content-Type': 'text/xml;charset=UTF-8',
        apikey: apiAuthKey,
      }
    
      const { response } = await soapRequest({
        url: `${url}/enedis_SGE_ConsultationDonneesTechniquesContractuelles/1.0`,
        headers: sgeHeaders,
        xml: consulterDonneesTechniquesContractuelles(pointId, userLogin),
      }).catch(err => {
        log('error', 'Error while fetching contract start date : ' + err)
        throw errors.VENDOR_DOWN
      })
    
      const result = await xml2js.parseStringPromise(response.body, {
        tagNameProcessors: [parseTags],
        valueProcessors: [parseValue],
        explicitArray: false,
      })
      try {
        return parseContractStartDate(result)
      } catch (error) {
        log('error', 'Error while processing contract start date: ' + error)
    
        log(
          'error',
          `Enedis issue ${result.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${result.Envelope.Body.Fault.faultstring}`
        )
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        throw errors.NOT_EXISTING_DIRECTORY
      }
    }
    
    module.exports = { getContractStartDate }
    
    
    /***/ }),
    /* 1603 */
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    const { log, updateOrCreate } = __webpack_require__(1)
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    const { iSLocal } = __webpack_require__(1604)
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    const cozyClient = __webpack_require__(485)
    
    async function saveAccountData(accountId, accountData) {
      log('info', `saveAccountData: ${accountId}`)
    
      let account = await getAccount(accountId)
    
      account = await updateOrCreate(
        [{ ...account, data: accountData }],
        'io.cozy.accounts'
      )
      return account
    }
    
    async function getAccount(accountId) {
      log('info', `getAccount: ${accountId}`)
      //TODO: refactor with usageof cozy-libs. Not working during implementation
      const accounts = await cozyClient.data.findAll('io.cozy.accounts')
      return accounts.filter(account =>
        iSLocal() ? account._id === accountId : account.account_type === accountId
      )[0]
    }
    
    module.exports = { getAccount, saveAccountData }
    
    
    /***/ }),
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /* 1604 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ ((module) => {
    
    function iSLocal() {
    
        process.env.NODE_ENV === 'development' ||
        process.env.NODE_ENV === 'local' ||
        process.env.NODE_ENV === 'standalone'
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    /***/ })
    /******/ 	]);
    /************************************************************************/
    /******/ 	// The module cache
    /******/ 	var __webpack_module_cache__ = {};
    /******/ 	
    /******/ 	// The require function
    /******/ 	function __webpack_require__(moduleId) {
    /******/ 		// Check if module is in cache
    /******/ 		var cachedModule = __webpack_module_cache__[moduleId];
    /******/ 		if (cachedModule !== undefined) {
    /******/ 			return cachedModule.exports;
    /******/ 		}
    /******/ 		// Create a new module (and put it into the cache)
    /******/ 		var module = __webpack_module_cache__[moduleId] = {
    /******/ 			id: moduleId,
    /******/ 			loaded: false,
    /******/ 			exports: {}
    /******/ 		};
    /******/ 	
    /******/ 		// Execute the module function
    /******/ 		__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
    /******/ 	
    /******/ 		// Flag the module as loaded
    /******/ 		module.loaded = true;
    /******/ 	
    /******/ 		// Return the exports of the module
    /******/ 		return module.exports;
    /******/ 	}
    /******/ 	
    /******/ 	// expose the module cache
    /******/ 	__webpack_require__.c = __webpack_module_cache__;
    /******/ 	
    /************************************************************************/
    /******/ 	/* webpack/runtime/compat get default export */
    /******/ 	(() => {
    /******/ 		// getDefaultExport function for compatibility with non-harmony modules
    /******/ 		__webpack_require__.n = (module) => {
    /******/ 			var getter = module && module.__esModule ?
    /******/ 				() => (module['default']) :
    /******/ 				() => (module);
    /******/ 			__webpack_require__.d(getter, { a: getter });
    /******/ 			return getter;
    /******/ 		};
    /******/ 	})();
    /******/ 	
    /******/ 	/* webpack/runtime/define property getters */
    /******/ 	(() => {
    /******/ 		// define getter functions for harmony exports
    /******/ 		__webpack_require__.d = (exports, definition) => {
    /******/ 			for(var key in definition) {
    /******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
    /******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
    /******/ 				}
    /******/ 			}
    /******/ 		};
    /******/ 	})();
    /******/ 	
    /******/ 	/* webpack/runtime/hasOwnProperty shorthand */
    /******/ 	(() => {
    /******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
    /******/ 	})();
    /******/ 	
    /******/ 	/* webpack/runtime/make namespace object */
    /******/ 	(() => {
    /******/ 		// define __esModule on exports
    /******/ 		__webpack_require__.r = (exports) => {
    /******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
    /******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
    /******/ 			}
    /******/ 			Object.defineProperty(exports, '__esModule', { value: true });
    /******/ 		};
    /******/ 	})();
    /******/ 	
    /******/ 	/* webpack/runtime/node module decorator */
    /******/ 	(() => {
    /******/ 		__webpack_require__.nmd = (module) => {
    /******/ 			module.paths = [];
    /******/ 			if (!module.children) module.children = [];
    /******/ 			return module;
    /******/ 		};
    /******/ 	})();
    /******/ 	
    /************************************************************************/
    /******/ 	
    /******/ 	// module cache are used so entry inlining is disabled
    /******/ 	// startup
    /******/ 	// Load entry module and return exports
    /******/ 	var __webpack_exports__ = __webpack_require__(__webpack_require__.s = 0);
    /******/ 	
    /******/ })()
    ;