const moment = require('moment') const {log, BaseKonnector, saveBills, requestFactory} = require('cozy-konnector-libs') const baseUrl = 'https://espace-client.enercoop.fr' const loginUrl = baseUrl + '/login' const billUrl = baseUrl + '/mon-espace/factures/' moment.locale('fr') let rq = requestFactory({ cheerio: true, json: false, debug: false, jar: true }) module.exports = new BaseKonnector(function fetch (fields) { return logIn(fields) .then(parsePage) .then(entries => saveBills(entries, fields.folderPath, { timeout: Date.now() + 60 * 1000, identifiers: ['Enercoop'] })) }) // Procedure to login to Enercoop website. function logIn (fields) { const form = { email: fields.login, password: fields.password, } const options = { url: loginUrl, method: 'POST', form: form, resolveWithFullResponse: true, followAllRedirects: true, simple: false } return rq(options) .then(res => { const isNot200 = res.statusCode !== 200 if (isNot200) { log('info', 'Authentification error') throw new Error('LOGIN_FAILED') } const url = `${billUrl}` return rq(url) .catch(err => { console.log(err, 'authentication error details') throw new Error('LOGIN_FAILED') }) }) } // Parse the fetched DOM page to extract bill data. function parsePage ($) { const bills = [] $('.invoice-line').each(function () { //one bill per line = a