Skip to content
Snippets Groups Projects
index.js 7.57 MiB
Newer Older
  • Learn to ignore specific revisions
  • Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    };
    
    /**
     * Assert object's properties type
     * @param {object} options
     * @param {object} schema
     * @param {boolean?} allowUnknown
     */
    
    function assertOptions(options, schema, allowUnknown) {
      if (typeof options !== 'object') {
        throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
      }
      var keys = Object.keys(options);
      var i = keys.length;
      while (i-- > 0) {
        var opt = keys[i];
        var validator = schema[opt];
        if (validator) {
          var value = options[opt];
          var result = value === undefined || validator(value, opt, options);
          if (result !== true) {
            throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
          }
          continue;
        }
        if (allowUnknown !== true) {
          throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      assertOptions: assertOptions,
      validators: validators
    };
    
    /* 1598 */
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    
    var CanceledError = __webpack_require__(1586);
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * A `CancelToken` is an object that can be used to request cancellation of an operation.
     *
     * @class
     * @param {Function} executor The executor function.
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
     */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    function CancelToken(executor) {
      if (typeof executor !== 'function') {
        throw new TypeError('executor must be a function.');
      }
    
      var resolvePromise;
    
      this.promise = new Promise(function promiseExecutor(resolve) {
        resolvePromise = resolve;
      });
    
      var token = this;
    
      // eslint-disable-next-line func-names
      this.promise.then(function(cancel) {
        if (!token._listeners) return;
    
        var i;
        var l = token._listeners.length;
    
        for (i = 0; i < l; i++) {
          token._listeners[i](cancel);
        }
        token._listeners = null;
      });
    
      // eslint-disable-next-line func-names
      this.promise.then = function(onfulfilled) {
        var _resolve;
        // eslint-disable-next-line func-names
        var promise = new Promise(function(resolve) {
          token.subscribe(resolve);
          _resolve = resolve;
        }).then(onfulfilled);
    
        promise.cancel = function reject() {
          token.unsubscribe(_resolve);
        };
    
        return promise;
      };
    
      executor(function cancel(message) {
        if (token.reason) {
          // Cancellation has already been requested
          return;
        }
    
        token.reason = new CanceledError(message);
        resolvePromise(token.reason);
      });
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * Throws a `CanceledError` if cancellation has been requested.
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
     */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    CancelToken.prototype.throwIfRequested = function throwIfRequested() {
      if (this.reason) {
        throw this.reason;
      }
    };
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * Subscribe to the cancel signal
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
     */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    
    CancelToken.prototype.subscribe = function subscribe(listener) {
      if (this.reason) {
        listener(this.reason);
        return;
      }
    
      if (this._listeners) {
        this._listeners.push(listener);
      } else {
        this._listeners = [listener];
      }
    };
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * Unsubscribe from the cancel signal
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
     */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    
    CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
      if (!this._listeners) {
        return;
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
      }
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      var index = this._listeners.indexOf(listener);
      if (index !== -1) {
        this._listeners.splice(index, 1);
      }
    };
    
    /**
     * Returns an object that contains a new `CancelToken` and a function that, when called,
     * cancels the `CancelToken`.
     */
    CancelToken.source = function source() {
      var cancel;
      var token = new CancelToken(function executor(c) {
        cancel = c;
      });
      return {
        token: token,
        cancel: cancel
      };
    };
    
    module.exports = CancelToken;
    
    
    /***/ }),
    
    /* 1599 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ ((module) => {
    
    "use strict";
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * Syntactic sugar for invoking a function and expanding an array for arguments.
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
     *
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * Common use case would be to use `Function.prototype.apply`.
     *
     *  ```js
     *  function f(x, y, z) {}
     *  var args = [1, 2, 3];
     *  f.apply(null, args);
     *  ```
     *
     * With `spread` this example can be re-written.
     *
     *  ```js
     *  spread(function(x, y, z) {})([1, 2, 3]);
     *  ```
     *
     * @param {Function} callback
     * @returns {Function}
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
     */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    module.exports = function spread(callback) {
      return function wrap(arr) {
        return callback.apply(null, arr);
      };
    };
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    
    /***/ }),
    
    /* 1600 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    "use strict";
    
    
    
    var utils = __webpack_require__(1566);
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    
    /**
     * Determines whether the payload is an error thrown by Axios
     *
     * @param {*} payload The value to test
     * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
     */
    module.exports = function isAxiosError(payload) {
      return utils.isObject(payload) && (payload.isAxiosError === true);
    };
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ }),
    
    /* 1601 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    
    const { activateContract } = __webpack_require__(1602)
    const { getContractStartDate } = __webpack_require__(1603)
    const { terminateContract } = __webpack_require__(1604)
    const { verifyContract } = __webpack_require__(1605)
    const { findUserPdl } = __webpack_require__(1607)
    const { verifyUserIdentity } = __webpack_require__(1608)
    const { findUserAddress } = __webpack_require__(1610)
    
    module.exports = {
      activateContract,
      getContractStartDate,
      terminateContract,
      verifyContract,
      findUserPdl,
      verifyUserIdentity,
    
    /* 1602 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    // @ts-check
    const { log, errors } = __webpack_require__(1)
    
    const soapRequest = __webpack_require__(1337)
    const { parseTags, parseValue, parseServiceId } = __webpack_require__(1561)
    const { commanderCollectePublicationMesures } = __webpack_require__(1562)
    const xml2js = __webpack_require__(1519)
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    
    /**
     * @param {string} url
     * @param {string} apiAuthKey
     * @param {string} appLogin
     * @param {string} name
    
     * @param {number} pointId
     * @param {string} startDate
     * @param {string} endDate
     * @return {Promise<number>} User contractId
    
    async function activateContract(
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      url,
      apiAuthKey,
      appLogin,
    
      contractId,
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      name,
    
      pointId,
      startDate,
      endDate
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    ) {
    
      log('info', 'activateContract')
    
    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_CommandeCollectePublicationMesures/1.0`,
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        headers: sgeHeaders,
    
        xml: commanderCollectePublicationMesures(
          appLogin,
          contractId,
          pointId,
          name,
          startDate,
          endDate
        ),
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      }).catch(err => {
    
        log('error', 'commanderCollectePublicationMesures')
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        log('error', err)
        throw errors.LOGIN_FAILED
      })
    
      const parsedReply = await xml2js.parseStringPromise(response.body, {
        tagNameProcessors: [parseTags],
        valueProcessors: [parseValue],
        explicitArray: false,
      })
    
      try {
    
        return parseServiceId(parsedReply)
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      } catch (error) {
    
        log('error', 'Error while activating contract: ' + error)
    
        if (parsedReply.Envelope.Body.Fault) {
          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 }
    
    /* 1603 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    // @ts-check
    const { log, errors } = __webpack_require__(1)
    
    const soapRequest = __webpack_require__(1337)
    
    const {
      parseTags,
      parseValue,
      parseContractStartDate,
    
    } = __webpack_require__(1561)
    const xml2js = __webpack_require__(1519)
    const { consulterDonneesTechniquesContractuelles } = __webpack_require__(1562)
    
     * 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)
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      } catch (error) {
    
        log('error', 'Error while processing contract start date: ' + error)
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        log(
          'error',
    
          `Enedis issue ${result.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${result.Envelope.Body.Fault.faultstring}`
    
        throw errors.NOT_EXISTING_DIRECTORY
    
    module.exports = { getContractStartDate }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    /***/ }),
    
    /* 1604 */
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    // @ts-check
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    const { log, errors } = __webpack_require__(1)
    
    const soapRequest = __webpack_require__(1337)
    const { parseTags, parseValue } = __webpack_require__(1561)
    const { commanderArretServiceSouscritMesures } = __webpack_require__(1562)
    const xml2js = __webpack_require__(1519)
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * @param {string} url
     * @param {string} apiAuthKey
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * @param {number} pointId
    
     * @param {number} serviceId
     * @return {Promise<string>} User contractId
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
     */
    
    async function terminateContract(
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      url,
      apiAuthKey,
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      contractId,
      pointId,
    
      serviceId
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    ) {
    
      log('info', 'terminateContract')
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      const sgeHeaders = {
        'Content-Type': 'text/xml;charset=UTF-8',
        apikey: apiAuthKey,
      }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      const { response } = await soapRequest({
    
        url: `${url}/enedis_SGE_CommandeArretServiceSouscritMesures/1.0`,
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        headers: sgeHeaders,
    
        xml: commanderArretServiceSouscritMesures(
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
          appLogin,
          contractId,
          pointId,
    
          serviceId
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        ),
      }).catch(err => {
    
        log('error', 'commanderArretServiceSouscritMesures')
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        log('error', err)
    
        throw errors.VENDOR_DOWN
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      })
    
      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}`
          )
        }
        return parsedReply
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      } catch (error) {
    
        log('error', 'Error while parsing user contract termination: ' + error)
        log('error', `Enedis issue ${JSON.stringify(parsedReply.Envelope.Body)}`)
        throw errors.VENDOR_DOWN
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      }
    
    module.exports = { terminateContract }
    
    /* 1605 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    // @ts-check
    const { log, errors } = __webpack_require__(1)
    
    const soapRequest = __webpack_require__(1337)
    
    const {
      parseTags,
      parseValue,
      parseContracts,
      checkContractExists,
    
    } = __webpack_require__(1561)
    const { rechercherServicesSouscritsMesures } = __webpack_require__(1562)
    const xml2js = __webpack_require__(1519)
    const { contractState, contractLibelle } = __webpack_require__(1606)
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    /**
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * @param {string} url
     * @param {string} apiAuthKey
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * @param {number} pointId
     * @return {Promise<number | null>} User contractId
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
     */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    async function verifyContract(url, apiAuthKey, appLogin, contractId, pointId) {
      log('info', 'verifyContract')
      const sgeHeaders = {
        'Content-Type': 'text/xml;charset=UTF-8',
        apikey: apiAuthKey,
      }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      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 {
    
        if (!checkContractExists(parsedReply)) {
          log('error', 'no contract found')
          return null
        }
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        const currentContracts = parseContracts(parsedReply)
        let currentContract = null
        if (Array.isArray(currentContracts)) {
          currentContract = parseContracts(parsedReply)[0]
        } else {
    
          currentContract = currentContracts
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        }
        if (
          (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)
    
        if (parsedReply.Envelope.Body.Fault) {
          log(
            'error',
            `Enedis issue ${parsedReply.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${parsedReply.Envelope.Body.Fault.faultstring}`
          )
        }
    
        log(
          'error',
          'if an erorr is thrown here, it probably means that the contract has already been open today and that enedis cannot open a second one. Wait until tomorow to try again'
        )
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        throw errors.LOGIN_FAILED
      }
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    module.exports = { verifyContract }
    
    
    /***/ }),
    
    /* 1606 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ ((module) => {
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * Enum for contract-state values.
     * @readonly
     * @enum {number}
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    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',
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    module.exports = { contractState, contractLibelle }
    
    /* 1607 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    // @ts-check
    const { log, errors } = __webpack_require__(1)
    
    const soapRequest = __webpack_require__(1337)
    const { parseUserPdl, parseTags, parseValue } = __webpack_require__(1561)
    const { rechercherPoint } = __webpack_require__(1562)
    const xml2js = __webpack_require__(1519)
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * @param {string} url
     * @param {string} apiAuthKey
    
     * @param {string} name
     * @param {string} address
     * @param {string} postalCode
     * @param {string} inseeCode
     * @return {Promise<string | null>} User Pdl
    
    async function findUserPdl(
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      url,
      apiAuthKey,
    
      name,
      address,
      postalCode,
    
      inseeCode,
      escalierEtEtageEtAppartement = ''
    
      log('info', 'Fetching user pdl')
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      const sgeHeaders = {
        'Content-Type': 'text/xml;charset=UTF-8',
        apikey: apiAuthKey,
      }
    
      const { response } = await soapRequest({
    
        url: url,
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        headers: sgeHeaders,
    
        xml: rechercherPoint(
          appLogin,
          name,
          postalCode,
          inseeCode,
          address,
          escalierEtEtageEtAppartement
        ),
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      }).catch(err => {
    
        log('error', 'rechercherPointResponse')
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        log('error', err)
    
        throw errors.LOGIN_FAILED
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      })
    
      const parsedReply = await xml2js.parseStringPromise(response.body, {
        tagNameProcessors: [parseTags],
        valueProcessors: [parseValue],
        explicitArray: false,
      })
    
      try {
    
        return parseUserPdl(parsedReply)
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      } catch (error) {
    
        log('warn', 'Error while parsing user PDL: ' + error)
        if (parsedReply.Envelope.Body.Fault) {
          log(
            'warn',
            `Enedis issue ${parsedReply.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${parsedReply.Envelope.Body.Fault.faultstring}`
          )
        }
        return null
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      }
    
    module.exports = { findUserPdl }
    
    /* 1608 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    // @ts-check
    const { log, errors } = __webpack_require__(1)
    
    const { findUserPdl } = __webpack_require__(1607)
    const { getInseeCode } = __webpack_require__(1609)
    const { findUserAddress } = __webpack_require__(1610)
    
    const {
      removeMultipleSpaces,
      removeAddressnumber,
    
    } = __webpack_require__(1561)
    
     * Verify user identity
     * @param {object} fields
     * @param {string} baseUrl
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * @param {string} apiAuthKey
    
     * @param {string} loginUtilisateur
     * @param {boolean} isAlternateStart
     * @returns {Promise<User>}
    
    async function verifyUserIdentity(
      fields,
      baseUrl,
      apiAuthKey,
      loginUtilisateur,
    
      isAlternateStart = false,
      inseeCode = ''
    
      // If first start get InseeCode
      log('debug', 'verifyUserIdentity')
      if (!isAlternateStart) {
        inseeCode = await getInseeCode(fields.postalCode, fields.city)
      }
    
      // Store if user is going through safety sge onboarding
      let userSafetyOnBoarding = false
    
      // First try with user adresse
      let pdl = await findUserPdl(
    
        `${baseUrl}/enedis_SDE_recherche-point/1.0`,
        apiAuthKey,
        loginUtilisateur,
        fields.lastname,
        fields.address,
        fields.postalCode,
        inseeCode
      )
    
    
      if (!pdl) {
        log('warn', 'Second chance for sge onboarding')
        // Set safety onboarding in order to save it inside BO
        userSafetyOnBoarding = true
        // Backup verification
        const userAddress = await findUserAddress(
          baseUrl,
          apiAuthKey,
          loginUtilisateur,
          fields.pointId
        )
    
        const escalierEtEtageEtAppartement = userAddress.escalierEtEtageEtAppartement
          ? removeMultipleSpaces(userAddress.escalierEtEtageEtAppartement)
          : ''
    
        pdl = await findUserPdl(
          `${baseUrl}/enedis_SDE_recherche-point/1.0`,
          apiAuthKey,
          loginUtilisateur,
          fields.lastname,
          removeMultipleSpaces(userAddress.numeroEtNomVoie),
          userAddress.codePostal,
          userAddress.commune.$.code,
          escalierEtEtageEtAppartement
        )
    
        // Third try, remove address number because it's buggy on SGE side
        if (!pdl) {
          log('warn', 'Third chance onboarding for sge')
          pdl = await findUserPdl(
            `${baseUrl}/enedis_SDE_recherche-point/1.0`,
            apiAuthKey,
            loginUtilisateur,
            fields.lastname,
            removeMultipleSpaces(removeAddressnumber(userAddress.numeroEtNomVoie)),
            userAddress.codePostal,
            userAddress.commune.$.code
          )
        }
        // Third try, remove address number and add escalierEtEtageEtAppartement because it's buggy on SGE side
        if (!pdl) {
          log('warn', 'Last chance onboarding for sge')
          pdl = await findUserPdl(
            `${baseUrl}/enedis_SDE_recherche-point/1.0`,
            apiAuthKey,
            loginUtilisateur,
            fields.lastname,
            removeMultipleSpaces(removeAddressnumber(userAddress.numeroEtNomVoie)),
            userAddress.codePostal,
            userAddress.commune.$.code,
            escalierEtEtageEtAppartement
          )
        }
      }
    
    
      if (fields.pointId != pdl) {
        log('error', 'PointId does not match')
    
        if (isAlternateStart) {
          throw errors.TERMS_VERSION_MISMATCH
        } else {
          throw errors.LOGIN_FAILED
        }
    
      return {
        lastname: fields.lastname,
        firstname: fields.firstname,
        pointId: fields.pointId,
        inseeCode,
        postalCode: fields.postalCode,
        address: fields.address,
    
        hasBeenThroughtSafetyOnBoarding: userSafetyOnBoarding,
        city: fields.city,
    
    module.exports = { verifyUserIdentity }
    
    
    /***/ }),
    
    /* 1609 */
    
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    // @ts-check
    
    const { default: axios } = __webpack_require__(1564)
    
    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) {
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      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
        }
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      } catch (error) {
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        log(
          'error',
    
          `Query getInseeCode failed for postalCode ${postalCode} / ${city}`
    
        throw errors.USER_ACTION_NEEDED
    
    module.exports = {
      getInseeCode,
    }
    
    /* 1610 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    
    // @ts-check
    const { log, errors } = __webpack_require__(1)
    
    const soapRequest = __webpack_require__(1337)
    
    } = __webpack_require__(1561)
    const xml2js = __webpack_require__(1519)
    const { consulterDonneesTechniquesContractuelles } = __webpack_require__(1562)
    
    
    /**
     * Get user contract start date
     * @param {string} url
     * @param {string} apiAuthKey
     * @param {string} userLogin
     * @param {number} pointId
     * @returns {Promise<Address>}
     */
    async function findUserAddress(url, apiAuthKey, userLogin, pointId) {
      log('info', 'Fetching user address')
      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, false),
      }).catch(err => {
        log('error', 'Error while fetching user : ' + err)
        throw errors.VENDOR_DOWN
      })
    
      const result = await xml2js.parseStringPromise(response.body, {
        tagNameProcessors: [parseTags],
        valueProcessors: [parseValue],
        explicitArray: false,
      })
    
      try {
        return parseUserAddress(result)
      } catch (error) {
        log('error', 'Error while processing user address: ' + error)
        log(
          'error',
          `Enedis issue ${result.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${result.Envelope.Body.Fault.faultstring}`
        )
    
    /* 1611 */
    
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    const { log, updateOrCreate } = __webpack_require__(1)
    
    const { isLocal } = __webpack_require__(1612)
    
    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)
    
      log('info', `saveAccountData account: ${JSON.stringify(account)}`)
      log(
        'info',
        `saveAccountData account: ${JSON.stringify({
          ...account,
          data: accountData,
        })}`
      )
    
      log(
        'info',
        `saveAccountData account after id: ${JSON.stringify({
          ...account,
          data: accountData,
        })}`
      )
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      account = await updateOrCreate(
        [{ ...account, data: accountData }],
    
        'io.cozy.accounts',
        ['account_type']
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      )
    
      log('info', `saveAccountData account reply: ${JSON.stringify(account)}`)
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      return account
    
    /**
     * Return account
     * @param {string} accountId
     * @returns {Account}
     */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    async function getAccount(accountId) {
      log('info', `getAccount: ${accountId}`)
      const accounts = await cozyClient.data.findAll('io.cozy.accounts')
    
      log('info', `getAccount data: ${JSON.stringify(accounts)}`)
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      return accounts.filter(account =>
    
        isLocal() ? account._id === accountId : account.account_type === accountId
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      )[0]
    
    async function getAccountForDelete(accountId, accountRev) {
      log('info', `getAccountForDelete: ${accountId} ${accountRev}`)
      const body = await cozyClient.fetchJSON(
        'GET',
        `/data/io.cozy.accounts/${accountId}?rev=${accountRev}`
      )
    
      log('debug', `getAccountForDelete: ${body}`)
      return body
    }
    
    module.exports = { getAccount, saveAccountData, getAccountForDelete }
    
    /* 1612 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ ((module) => {
    
    
    function isLocal() {
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      return (
        process.env.NODE_ENV === 'development' ||
        process.env.NODE_ENV === 'local' ||
        process.env.NODE_ENV === 'standalone'
      )
    
    /**
     * Verify if it's an alpha URL
     * @returns {boolean}
     */
    function isDev() {
      return (
        process.env.COZY_URL.includes('alpha') ||
        process.env.COZY_URL.includes('cozy.tools')
      )
    }
    
    module.exports = { isLocal, isDev }
    
    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;
    /******/ 	}
    /******/