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
                parser.sgmlDecl = ''
                parser.state = S.TEXT
              } else if (isQuote(c)) {
                parser.state = S.SGML_DECL_QUOTED
                parser.sgmlDecl += c
              } else {
                parser.sgmlDecl += c
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.SGML_DECL_QUOTED:
              if (c === parser.q) {
                parser.state = S.SGML_DECL
                parser.q = ''
              }
              parser.sgmlDecl += c
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.DOCTYPE:
              if (c === '>') {
                parser.state = S.TEXT
                emitNode(parser, 'ondoctype', parser.doctype)
                parser.doctype = true // just remember that we saw it.
              } else {
                parser.doctype += c
                if (c === '[') {
                  parser.state = S.DOCTYPE_DTD
                } else if (isQuote(c)) {
                  parser.state = S.DOCTYPE_QUOTED
                  parser.q = c
                }
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.DOCTYPE_QUOTED:
              parser.doctype += c
              if (c === parser.q) {
                parser.q = ''
                parser.state = S.DOCTYPE
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.DOCTYPE_DTD:
              parser.doctype += c
              if (c === ']') {
                parser.state = S.DOCTYPE
              } else if (isQuote(c)) {
                parser.state = S.DOCTYPE_DTD_QUOTED
                parser.q = c
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.DOCTYPE_DTD_QUOTED:
              parser.doctype += c
              if (c === parser.q) {
                parser.state = S.DOCTYPE_DTD
                parser.q = ''
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.COMMENT:
              if (c === '-') {
                parser.state = S.COMMENT_ENDING
              } else {
                parser.comment += c
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.COMMENT_ENDING:
              if (c === '-') {
                parser.state = S.COMMENT_ENDED
                parser.comment = textopts(parser.opt, parser.comment)
                if (parser.comment) {
                  emitNode(parser, 'oncomment', parser.comment)
                }
                parser.comment = ''
              } else {
                parser.comment += '-' + c
                parser.state = S.COMMENT
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.COMMENT_ENDED:
              if (c !== '>') {
                strictFail(parser, 'Malformed comment')
                // allow <!-- blah -- bloo --> in non-strict mode,
                // which is a comment of " blah -- bloo "
                parser.comment += '--' + c
                parser.state = S.COMMENT
              } else {
                parser.state = S.TEXT
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.CDATA:
              if (c === ']') {
                parser.state = S.CDATA_ENDING
              } else {
                parser.cdata += c
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.CDATA_ENDING:
              if (c === ']') {
                parser.state = S.CDATA_ENDING_2
              } else {
                parser.cdata += ']' + c
                parser.state = S.CDATA
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.CDATA_ENDING_2:
              if (c === '>') {
                if (parser.cdata) {
                  emitNode(parser, 'oncdata', parser.cdata)
                }
                emitNode(parser, 'onclosecdata')
                parser.cdata = ''
                parser.state = S.TEXT
              } else if (c === ']') {
                parser.cdata += ']'
              } else {
                parser.cdata += ']]' + c
                parser.state = S.CDATA
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.PROC_INST:
              if (c === '?') {
                parser.state = S.PROC_INST_ENDING
              } else if (isWhitespace(c)) {
                parser.state = S.PROC_INST_BODY
              } else {
                parser.procInstName += c
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.PROC_INST_BODY:
              if (!parser.procInstBody && isWhitespace(c)) {
                continue
              } else if (c === '?') {
                parser.state = S.PROC_INST_ENDING
              } else {
                parser.procInstBody += c
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.PROC_INST_ENDING:
              if (c === '>') {
                emitNode(parser, 'onprocessinginstruction', {
                  name: parser.procInstName,
                  body: parser.procInstBody
                })
                parser.procInstName = parser.procInstBody = ''
                parser.state = S.TEXT
              } else {
                parser.procInstBody += '?' + c
                parser.state = S.PROC_INST_BODY
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.OPEN_TAG:
              if (isMatch(nameBody, c)) {
                parser.tagName += c
              } else {
                newTag(parser)
                if (c === '>') {
                  openTag(parser)
                } else if (c === '/') {
                  parser.state = S.OPEN_TAG_SLASH
                } else {
                  if (!isWhitespace(c)) {
                    strictFail(parser, 'Invalid character in tag name')
                  }
                  parser.state = S.ATTRIB
                }
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.OPEN_TAG_SLASH:
              if (c === '>') {
                openTag(parser, true)
                closeTag(parser)
              } else {
                strictFail(parser, 'Forward-slash in opening tag not followed by >')
                parser.state = S.ATTRIB
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.ATTRIB:
              // haven't read the attribute name yet.
              if (isWhitespace(c)) {
                continue
              } else if (c === '>') {
                openTag(parser)
              } else if (c === '/') {
                parser.state = S.OPEN_TAG_SLASH
              } else if (isMatch(nameStart, c)) {
                parser.attribName = c
                parser.attribValue = ''
                parser.state = S.ATTRIB_NAME
              } else {
                strictFail(parser, 'Invalid attribute name')
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.ATTRIB_NAME:
              if (c === '=') {
                parser.state = S.ATTRIB_VALUE
              } else if (c === '>') {
                strictFail(parser, 'Attribute without value')
                parser.attribValue = parser.attribName
                attrib(parser)
                openTag(parser)
              } else if (isWhitespace(c)) {
                parser.state = S.ATTRIB_NAME_SAW_WHITE
              } else if (isMatch(nameBody, c)) {
                parser.attribName += c
              } else {
                strictFail(parser, 'Invalid attribute name')
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.ATTRIB_NAME_SAW_WHITE:
              if (c === '=') {
                parser.state = S.ATTRIB_VALUE
              } else if (isWhitespace(c)) {
                continue
              } else {
                strictFail(parser, 'Attribute without value')
                parser.tag.attributes[parser.attribName] = ''
                parser.attribValue = ''
                emitNode(parser, 'onattribute', {
                  name: parser.attribName,
                  value: ''
                })
                parser.attribName = ''
                if (c === '>') {
                  openTag(parser)
                } else if (isMatch(nameStart, c)) {
                  parser.attribName = c
                  parser.state = S.ATTRIB_NAME
                } else {
                  strictFail(parser, 'Invalid attribute name')
                  parser.state = S.ATTRIB
                }
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.ATTRIB_VALUE:
              if (isWhitespace(c)) {
                continue
              } else if (isQuote(c)) {
                parser.q = c
                parser.state = S.ATTRIB_VALUE_QUOTED
              } else {
                strictFail(parser, 'Unquoted attribute value')
                parser.state = S.ATTRIB_VALUE_UNQUOTED
                parser.attribValue = c
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.ATTRIB_VALUE_QUOTED:
              if (c !== parser.q) {
                if (c === '&') {
                  parser.state = S.ATTRIB_VALUE_ENTITY_Q
                } else {
                  parser.attribValue += c
                }
                continue
              }
              attrib(parser)
              parser.q = ''
              parser.state = S.ATTRIB_VALUE_CLOSED
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.ATTRIB_VALUE_CLOSED:
              if (isWhitespace(c)) {
                parser.state = S.ATTRIB
              } else if (c === '>') {
                openTag(parser)
              } else if (c === '/') {
                parser.state = S.OPEN_TAG_SLASH
              } else if (isMatch(nameStart, c)) {
                strictFail(parser, 'No whitespace between attributes')
                parser.attribName = c
                parser.attribValue = ''
                parser.state = S.ATTRIB_NAME
              } else {
                strictFail(parser, 'Invalid attribute name')
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.ATTRIB_VALUE_UNQUOTED:
              if (!isAttribEnd(c)) {
                if (c === '&') {
                  parser.state = S.ATTRIB_VALUE_ENTITY_U
                } else {
                  parser.attribValue += c
                }
                continue
              }
              attrib(parser)
              if (c === '>') {
                openTag(parser)
              } else {
                parser.state = S.ATTRIB
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.CLOSE_TAG:
              if (!parser.tagName) {
                if (isWhitespace(c)) {
                  continue
                } else if (notMatch(nameStart, c)) {
                  if (parser.script) {
                    parser.script += '</' + c
                    parser.state = S.SCRIPT
                  } else {
                    strictFail(parser, 'Invalid tagname in closing tag.')
                  }
                } else {
                  parser.tagName = c
                }
              } else if (c === '>') {
                closeTag(parser)
              } else if (isMatch(nameBody, c)) {
                parser.tagName += c
              } else if (parser.script) {
                parser.script += '</' + parser.tagName
                parser.tagName = ''
                parser.state = S.SCRIPT
              } else {
                if (!isWhitespace(c)) {
                  strictFail(parser, 'Invalid tagname in closing tag')
                }
                parser.state = S.CLOSE_TAG_SAW_WHITE
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.CLOSE_TAG_SAW_WHITE:
              if (isWhitespace(c)) {
                continue
              }
              if (c === '>') {
                closeTag(parser)
              } else {
                strictFail(parser, 'Invalid characters in closing tag')
              }
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            case S.TEXT_ENTITY:
            case S.ATTRIB_VALUE_ENTITY_Q:
            case S.ATTRIB_VALUE_ENTITY_U:
              var returnState
              var buffer
              switch (parser.state) {
                case S.TEXT_ENTITY:
                  returnState = S.TEXT
                  buffer = 'textNode'
                  break
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
                case S.ATTRIB_VALUE_ENTITY_Q:
                  returnState = S.ATTRIB_VALUE_QUOTED
                  buffer = 'attribValue'
                  break
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
                case S.ATTRIB_VALUE_ENTITY_U:
                  returnState = S.ATTRIB_VALUE_UNQUOTED
                  buffer = 'attribValue'
                  break
              }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
              if (c === ';') {
                parser[buffer] += parseEntity(parser)
                parser.entity = ''
                parser.state = returnState
              } else if (isMatch(parser.entity.length ? entityBody : entityStart, c)) {
                parser.entity += c
              } else {
                strictFail(parser, 'Invalid character in entity name')
                parser[buffer] += '&' + parser.entity + c
                parser.entity = ''
                parser.state = returnState
              }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
              continue
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            default:
              throw new Error(parser, 'Unknown state: ' + parser.state)
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
          }
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        } // while
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        if (parser.position >= parser.bufferCheckPosition) {
          checkBufferLength(parser)
        }
        return parser
      }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      /*! http://mths.be/fromcodepoint v0.1.0 by @mathias */
      /* istanbul ignore next */
      if (!String.fromCodePoint) {
        (function () {
          var stringFromCharCode = String.fromCharCode
          var floor = Math.floor
          var fromCodePoint = function () {
            var MAX_SIZE = 0x4000
            var codeUnits = []
            var highSurrogate
            var lowSurrogate
            var index = -1
            var length = arguments.length
            if (!length) {
              return ''
            }
            var result = ''
            while (++index < length) {
              var codePoint = Number(arguments[index])
              if (
                !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
                codePoint < 0 || // not a valid Unicode code point
                codePoint > 0x10FFFF || // not a valid Unicode code point
                floor(codePoint) !== codePoint // not an integer
              ) {
                throw RangeError('Invalid code point: ' + codePoint)
              }
              if (codePoint <= 0xFFFF) { // BMP code point
                codeUnits.push(codePoint)
              } else { // Astral code point; split in surrogate halves
                // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
                codePoint -= 0x10000
                highSurrogate = (codePoint >> 10) + 0xD800
                lowSurrogate = (codePoint % 0x400) + 0xDC00
                codeUnits.push(highSurrogate, lowSurrogate)
              }
              if (index + 1 === length || codeUnits.length > MAX_SIZE) {
                result += stringFromCharCode.apply(null, codeUnits)
                codeUnits.length = 0
              }
            }
            return result
          }
          /* istanbul ignore next */
          if (Object.defineProperty) {
            Object.defineProperty(String, 'fromCodePoint', {
              value: fromCodePoint,
              configurable: true,
              writable: true
            })
          } else {
            String.fromCodePoint = fromCodePoint
          }
        }())
      }
    })( false ? 0 : exports)
    
    /* 1557 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ (function(__unused_webpack_module, exports) {
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    // Generated by CoffeeScript 1.12.7
    (function() {
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      "use strict";
      exports.stripBOM = function(str) {
        if (str[0] === '\uFEFF') {
          return str.substring(1);
        } else {
          return str;
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
        }
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      };
    
    /* 1558 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ (function(__unused_webpack_module, exports) {
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    // Generated by CoffeeScript 1.12.7
    (function() {
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      "use strict";
      var prefixMatch;
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      prefixMatch = new RegExp(/(?!xmlns)^.*:/);
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      exports.normalize = function(str) {
        return str.toLowerCase();
      };
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      exports.firstCharLowerCase = function(str) {
        return str.charAt(0).toLowerCase() + str.slice(1);
      };
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      exports.stripPrefix = function(str) {
        return str.replace(prefixMatch, '');
      };
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      exports.parseNumbers = function(str) {
        if (!isNaN(str)) {
          str = str % 1 === 0 ? parseInt(str, 10) : parseFloat(str);
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
        }
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        return str;
      };
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      exports.parseBooleans = function(str) {
        if (/^(?:true|false)$/i.test(str)) {
          str = str.toLowerCase() === 'true';
        }
        return str;
      };
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    }).call(this);
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ }),
    
    /* 1559 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ ((module) => {
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    "use strict";
    module.exports = require("timers");
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    /***/ }),
    
    /* 1560 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    // @ts-check
    const { log, cozyClient } = __webpack_require__(1)
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /**
     * Retrieve and remove old data for a specific doctype
     * Return an Array of agregated data
     */
    async function buildAgregatedData(data, doctype) {
      let agregatedData = []
      // eslint-disable-next-line no-unused-vars
      for (let [key, value] of Object.entries(data)) {
        const data = buildDataFromKey(doctype, key, value)
        const oldValue = await resetInProgressAggregatedData(data, doctype)
        data.load += oldValue
        agregatedData.push(data)
      }
      return agregatedData
    }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /**
     * Format an entry for DB storage
     * using key and value
     * For year doctype: key = "YYYY"
     * For month doctype: key = "YYYY-MM"
     */
    function buildDataFromKey(doctype, key, value) {
      let year, month, day, hour
      if (doctype === 'com.grandlyon.enedis.year') {
        year = key
        month = 1
        day = 0
        hour = 0
      } else if (doctype === 'com.grandlyon.enedis.month') {
        const split = key.split('-')
        year = split[0]
        month = split[1]
        day = 0
        hour = 0
      } else {
        const split = key.split('-')
        year = split[0]
        month = split[1]
        day = split[2]
        hour = split[3]
      }
      return {
        load: Math.round(value * 10000) / 10000,
        year: parseInt(year),
        month: parseInt(month),
        day: parseInt(day),
        hour: parseInt(hour),
        minute: 0,
      }
    }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /**
     * Function handling special case.
     * The temporary aggregated data need to be remove in order for the most recent one te be saved.
     * ex for com.grandlyon.enedis.year :
     * { load: 76.712, year: 2020, ... } need to be replace by
     * { load: 82.212, year: 2020, ... } after enedis data reprocess
     */
    async function resetInProgressAggregatedData(data, doctype) {
      // /!\ Warning: cannot use mongo queries because not supported for dev by cozy-konnectors-libs
      log('debug', doctype, 'Remove aggregated data for')
      const result = await cozyClient.data.findAll(doctype)
      if (result && result.length > 0) {
        // Filter data to remove
        var filtered = []
        if (doctype === 'com.grandlyon.enedis.year') {
          // Yearly case
          filtered = result.filter(function(el) {
            return el.year == data.year
          })
        } else if (doctype === 'com.grandlyon.enedis.month') {
          // Monthly case
          filtered = result.filter(function(el) {
            return el.year == data.year && el.month == data.month
          })
        } else {
          // Hourly case
          filtered = result.filter(function(el) {
            return (
              el.year == data.year &&
              el.month == data.month &&
              el.day == data.day &&
              el.hour == data.hour
            )
          })
        }
        // Remove data
        let sum = 0.0
        // eslint-disable-next-line no-unused-vars
        for (const doc of filtered) {
          sum += doc.load
          log('debug', doc, 'Removing this entry for ' + doctype)
          await cozyClient.data.delete(doctype, doc)
        }
        return sum
      }
      return 0.0
    }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    module.exports = {
      buildAgregatedData,
    }
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ }),
    
    /* 1561 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    // @ts-check
    const { log } = __webpack_require__(1)
    
    const moment = __webpack_require__(1379)
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /**
     * 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
    }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /**
     * Return User contract start date
     * @param {string} result
     * @returns {string}
     */
    function parseContractStartDate(result) {
      log('info', 'Parsing contract start date')
      const json = JSON.stringify(result)
      return JSON.parse(json)['Envelope']['Body'][
        'consulterDonneesTechniquesContractuellesResponse'
      ]['point']['donneesGenerales'][
        'dateDerniereModificationFormuleTarifaireAcheminement'
      ]
    }
    
    /**
     * Return User address
     * @param {string} result
     * @returns {Address}
     */
    function parseUserAddress(result) {
      log('info', 'Parsing user Address')
      const json = JSON.stringify(result)
      return JSON.parse(json)['Envelope']['Body'][
        'consulterDonneesTechniquesContractuellesResponse'
      ]['point']['donneesGenerales']['adresseInstallation']
    }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /**
     * Return User contract start date
     * @param {string} result
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * @returns {Contract[] | Contract}
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     */
    function parseContracts(result) {
      log('info', 'Parsing contract')
      const json = JSON.stringify(result)
      return JSON.parse(json)['Envelope']['Body'][
        'rechercherServicesSouscritsMesuresResponse'
      ]['servicesSouscritsMesures']['serviceSouscritMesures']
    }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /**
     * Return User contract start date
     * @param {string} result
     * @returns {number}
     */
    function parseServiceId(result) {
      log('info', 'Parsing serviceId')
      const json = JSON.stringify(result)
      return JSON.parse(json)['Envelope']['Body'][
        'commanderCollectePublicationMesuresResponse'
      ]['serviceSouscritId']
    }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /**
     * Parsing SGE xml reply to get only mesure data
     * @param {string} result
     * @returns {SGEData[]}
     */
    function parseSgeXmlData(result) {
      log('info', 'Parsing list of documents')
      const json = JSON.stringify(result)
      return JSON.parse(json)['Envelope']['Body'][
        'consulterMesuresDetailleesResponse'
      ]['grandeur']['mesure']
    }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /**
     * Format data for DB storage
     * @param {SGEData[]} data
     * @returns {Promise<EnedisKonnectorData[]>} Parsed timestamp array
     */
    async function formateDataForDoctype(data) {
      log('info', 'Formating data')
      return data.map(record => {
        const date = moment(record.d, 'YYYY/MM/DD h:mm:ss')
        return {
          load: record.v,
          year: parseInt(date.format('YYYY')),
          month: parseInt(date.format('M')),
          day: parseInt(date.format('D')),
          hour: parseInt(date.format('H')),
          minute: parseInt(date.format('m')),
        }
      })
    }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    /**
     * Check if response contains contracts
     * @param {string} parsedReply
     * @return {boolean}
     */
    function checkContractExists(parsedReply) {
      const json = JSON.stringify(parsedReply)
      return JSON.parse(json)['Envelope']['Body'][
        'rechercherServicesSouscritsMesuresResponse'
      ]['servicesSouscritsMesures']
    }
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /**
     * Format tag in order to be manipulated easly
     * @param {string} name
     * @returns {string} name
     */
    function parseTags(name) {
      if (name.split(':')[1] !== undefined) {
        return name.split(':')[1]
      }
      return name
    }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /**
     *
     * @param {string} value
     * @param {string} name
     * @returns {string|number} value
     */
    function parseValue(value, name) {
      // Wh => KWh
      if (name === 'v') {
        return parseFloat((parseInt(value) / 1000).toFixed(2))
      }
      return value
    }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    /**
     * Remove SGE useless multiple white spaces
     * @param {string} str
     * @returns {string}
     */
    function removeMultipleSpaces(str) {
      return str.replace(/  +/g, ' ')
    }
    
    /**
     * Remove SGE address number
     * @param {string} str
     * @returns {string}
     */
    function removeAddressnumber(str) {
      return str.replace(/\d+ |b |B |T |t |\d+/g, '')
    }
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    module.exports = {
      parseSgeXmlData,
      formateDataForDoctype,
      parseTags,
      parseValue,
      parseUserPdl,
      parseContracts,
      parseContractStartDate,
      parseServiceId,
    
      checkContractExists,
    
      removeMultipleSpaces,
      removeAddressnumber,
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    }
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ }),
    
    /* 1562 */
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    // @ts-check
    const { log } = __webpack_require__(1)
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /**
     * Get daily data up to 36 months & P max
     * @param {number} pointId
     * @param {string} appLogin
     * @param {string} startDate
     * @param {string} endDate
     * @param {'COURBE' | 'ENERGIE' | 'PMAX'} mesureType
     * @param {'EA' | 'PA' | 'PMA'} unit
     * @returns {string}
     */
    function consultationMesuresDetaillees(
      pointId,
      appLogin,
      startDate,
      endDate,
      mesureType = 'ENERGIE',
      unit = 'EA'
    ) {
      log(
        'info',
        `Query consultationMesuresDetaillees - ${mesureType}/${unit} between ${startDate} and ${endDate}`
      )
      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/consultationmesuresdetaillees/v2.0"
         xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0">
         <soapenv:Header/>
         <soapenv:Body>
            <v2:consulterMesuresDetaillees>
               <demande>
                  <initiateurLogin>${appLogin}</initiateurLogin>
                  <pointId>${pointId}</pointId>
                  <mesuresTypeCode>${mesureType}</mesuresTypeCode>
                  <grandeurPhysique>${unit}</grandeurPhysique>
                  <soutirage>true</soutirage>
                  <injection>false</injection>
                  <dateDebut>${startDate}</dateDebut>
                  <dateFin>${endDate}</dateFin>
                  <mesuresCorrigees>false</mesuresCorrigees>
                  <accordClient>true</accordClient>
               </demande>
            </v2:consulterMesuresDetaillees>
         </soapenv:Body>
      </soapenv:Envelope>
      `
    }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /**
     * Get user max power
     * @param {number} pointId
     * @param {string} appLogin
     * @param {string} startDate
     * @param {string} endDate
     * @param {'COURBE' | 'ENERGIE' | 'PMAX'} mesureType
     * @param {'EA' | 'PA' | 'PMA'} unit
     * @returns {string}
     */
    function consultationMesuresDetailleesMaxPower(
      pointId,
      appLogin,
      startDate,
      endDate,
      mesureType = 'PMAX',
      unit = 'PMA'
    ) {
      log(
        'info',
        `Query consultationMesuresDetaillees - ${mesureType}/${unit} between ${startDate} and ${endDate}`
      )
      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/consultationmesuresdetaillees/v2.0"
         xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0">
          <soapenv:Header/>
          <soapenv:Body>
              <v2:consulterMesuresDetaillees>
                  <demande>
                      <initiateurLogin>${appLogin}</initiateurLogin>
                      <pointId>${pointId}</pointId>
                      <mesuresTypeCode>${mesureType}</mesuresTypeCode>
                      <grandeurPhysique>${unit}</grandeurPhysique>
                      <soutirage>true</soutirage>
                      <injection>false</injection>
                      <dateDebut>${startDate}</dateDebut>
                      <dateFin>${endDate}</dateFin>
                      <mesuresPas>P1D</mesuresPas>
                      <mesuresCorrigees>false</mesuresCorrigees>
                      <accordClient>true</accordClient>
                  </demande>
              </v2:consulterMesuresDetaillees>
          </soapenv:Body>
      </soapenv:Envelope>
      `
    }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /**
     * Get user technical data (contract start date)
     * @param {number} pointId
     * @param {string} appLogin
     * @returns {string}
     */
    
    function consulterDonneesTechniquesContractuelles(
      pointId,
      appLogin,
      consent = true
    ) {
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      log('info', `Query consulterDonneesTechniquesContractuelles`)
      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/consulterdonneestechniquescontractuelles/v1.0"
         xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0">
         <soapenv:Header/>
         <soapenv:Body>
            <v2:consulterDonneesTechniquesContractuelles>
               <pointId>${pointId}</pointId>
               <loginUtilisateur>${appLogin}</loginUtilisateur>
    
               <autorisationClient>${consent}</autorisationClient>
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
            </v2:consulterDonneesTechniquesContractuelles>
         </soapenv:Body>
      </soapenv:Envelope>
      `
    }
    
    Hugo NOUTS's avatar
    Hugo NOUTS committed
    
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
    /**
     * Use rechercherPoint to find user PDL if exist
     * @param {string} name
     * @param {string} postalCode
     * @param {string} inseeCode
    
     * @param {string} address
     * @param {string} [escalierEtEtageEtAppartement]
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
     * @returns {string} PDL
     */
    
    function rechercherPoint(
      appLogin,
      name,
      postalCode,
      inseeCode,
      address,
      escalierEtEtageEtAppartement
    ) {
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      log(
        'info',
    
        `Query rechercherPoint - postal code : ${postalCode} / insee code: ${inseeCode}`
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      )
    
      if (escalierEtEtageEtAppartement) {
        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"
           xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0">
           <soapenv:Header/>
           <soapenv:Body>
              <v2:rechercherPoint>
                 <criteres>
                    <adresseInstallation>
                       <escalierEtEtageEtAppartement>${escalierEtEtageEtAppartement}</escalierEtEtageEtAppartement>
                       <numeroEtNomVoie>${address}</numeroEtNomVoie>
                       <codePostal>${postalCode}</codePostal>
                       <codeInseeCommune>${inseeCode}</codeInseeCommune>
                    </adresseInstallation>
                    <nomClientFinalOuDenominationSociale>${name}</nomClientFinalOuDenominationSociale>
                    <rechercheHorsPerimetre>true</rechercheHorsPerimetre>
                 </criteres>
                 <loginUtilisateur>${appLogin}</loginUtilisateur>
              </v2:rechercherPoint>
           </soapenv:Body>
        </soapenv:Envelope>`
      }
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      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"
         xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0">
         <soapenv:Header/>
         <soapenv:Body>
            <v2:rechercherPoint>
               <criteres>
                  <adresseInstallation>
                     <numeroEtNomVoie>${address}</numeroEtNomVoie>
                     <codePostal>${postalCode}</codePostal>
                     <codeInseeCommune>${inseeCode}</codeInseeCommune>
                  </adresseInstallation>