Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
const {
BaseKonnector,
log,
errors,
addData,
hydrateAndFilter,
cozyClient
} = require('cozy-konnector-libs')
const rp = require('request-promise')
//const moment = require('moment')
//require('request-debug')(rp)
const baseUrl = 'https://agence-rec.eaudugrandlyon.com/ws'
const apiAuthKey =
'abe55f32cbcb403b3a121637c67d7570aadd62d1abb9696a6dcacdb87993e034'
module.exports = new BaseKonnector(start)
// The start function is run by the BaseKonnector instance only when it got all the account
// information (fields). When you run this connector yourself in "standalone" mode or "dev" mode,
// the account information come from ./konnector-dev-config.json file
async function start(fields) {
try {
// resetting data for demo only
// await resetData()
log('info', 'Authenticating ...')
const response = await authenticate(fields.login, fields.password)
log('info', 'Successfully logged in')
log('info', 'Getting data')
const loadProfile = await getData(response)
log('info', 'Saving data to Cozy')
storeLoadProfile(loadProfile)
} catch (error) {
throw new Error(error.message)
}
}
async function authenticate(login, password) {
const authRequest = {
method: 'POST',
uri: baseUrl + '/connect.aspx',
headers: {
AuthKey: apiAuthKey,
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
login: login,
pass: password
},
json: true
}
try {
const response = await rp(authRequest)
if (response.codeRetour === 100) {
return response
} else {
throw new Error(errors.LOGIN_FAILED)
}
} catch (error) {
throw error
}
}
async function getData(response) {
const dataRequest = {
method: 'POST',
uri: baseUrl + '/getAllAgregatsByAbonnement.aspx',
headers: {
AuthKey: apiAuthKey,
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
token: response.resultatRetour.token,
num_abt: response.resultatRetour.num_abt,
date_debut: '01/01/2019',
date_fin: '01/10/2019'
},
json: true
}
try {
const response = await rp(dataRequest)
return response
} catch (error) {
throw new Error(errors.VENDOR_DOWN)
}
}
function storeLoadProfile(loadProfile) {
return hydrateAndFilter(loadProfile, 'egl.loadprofile', {
keys: ['DateReleve']
}).then(filteredDocuments => {
addData(filteredDocuments, 'egl.loadprofile')
})
}
// eslint-disable-next-line no-unused-vars
async function resetData() {
const result = await cozyClient.data.findAll('egl.loadprofile')
if (result.error) {
// eslint-disable-next-line no-console
console.error('Error while fetching loads')
}
for (const load of result) {
await cozyClient.data.delete('egl.loadprofile', load)
}
}