Connecteur COZY permettant de récupérer et stocker ses factures Enercoop.
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 

97 Zeilen
2.4 KiB

  1. const moment = require('moment')
  2. const {log, BaseKonnector, saveBills, requestFactory} = require('cozy-konnector-libs')
  3. const baseUrl = 'https://espace-client.enercoop.fr'
  4. const loginUrl = baseUrl + '/login'
  5. const billUrl = baseUrl + '/mon-espace/factures/'
  6. moment.locale('fr')
  7. let rq = requestFactory({
  8. cheerio: true,
  9. json: false,
  10. debug: false,
  11. jar: true
  12. })
  13. module.exports = new BaseKonnector(function fetch (fields) {
  14. return logIn(fields)
  15. .then(parsePage)
  16. .then(entries => saveBills(entries, fields.folderPath, {
  17. timeout: Date.now() + 60 * 1000,
  18. identifiers: ['Enercoop']
  19. }))
  20. })
  21. // Procedure to login to Enercoop website.
  22. function logIn (fields) {
  23. const form = {
  24. email: fields.login,
  25. password: fields.password,
  26. }
  27. const options = {
  28. url: loginUrl,
  29. method: 'POST',
  30. form: form,
  31. resolveWithFullResponse: true,
  32. followAllRedirects: true,
  33. simple: false
  34. }
  35. return rq(options)
  36. .then(res => {
  37. const isNot200 = res.statusCode !== 200
  38. if (isNot200) {
  39. log('info', 'Authentification error')
  40. throw new Error('LOGIN_FAILED')
  41. }
  42. const url = `${billUrl}`
  43. return rq(url)
  44. .catch(err => {
  45. console.log(err, 'authentication error details')
  46. throw new Error('LOGIN_FAILED')
  47. })
  48. })
  49. }
  50. // Parse the fetched DOM page to extract bill data.
  51. function parsePage ($) {
  52. const bills = []
  53. $('.invoice-line').each(function () {
  54. //one bill per line = a <li> with 'invoice-id' data-attr
  55. let billId = $(this).data('invoice-id')
  56. let amount = $(this).find('.amount').text()
  57. amount = amount.replace('€','')
  58. amount = amount.replace(',', '.').trim()
  59. amount = parseFloat(amount)
  60. //gets pdf download URL
  61. let pdfUrl = $(this).find('a > i').data('url')
  62. pdfUrl = baseUrl + pdfUrl
  63. //<French month>-YYYY format (Décembre - 2017)
  64. let billDate = $(this).find('.invoiceDate').text().trim()
  65. let monthAndYear = billDate.split('-')
  66. let billYear = monthAndYear[0].trim()
  67. let billMonth = monthAndYear[1].trim()
  68. billMonth = moment.months().indexOf(billMonth.toLowerCase()) + 1
  69. billMonth = billMonth < 10 ? '0' + billMonth : billMonth
  70. let date = moment(billYear + billMonth, 'YYYYMM')
  71. let bill = {
  72. amount,
  73. date: date.toDate(),
  74. vendor: 'Enercoop',
  75. filename: `${date.format('YYYYMM')}_enercoop.pdf`,
  76. fileurl: pdfUrl
  77. }
  78. bills.push(bill)
  79. })
  80. return bills
  81. }