-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
139 lines (118 loc) · 3.81 KB
/
index.js
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
const { WebhookClient } = require('dialogflow-fulfillment');
const express = require('express');
const bodyParser = require('body-parser');
const got = require('got');
const dotenv = require('dotenv');
const dayjs = require('dayjs');
const app = express();
const client = got.extend({
headers: {
'content-type': 'application/json',
},
});
dotenv.config();
const port = 3000;
app.use(bodyParser.json());
const { BUXFER_USERNAME } = process.env;
const { BUXFER_PASSWORD } = process.env;
const { BUXFER_API_URL } = process.env;
const { BUXFER_ACCOUNT_ID } = process.env;
let loginToken = '';
const transactionTags = {
'ristoranti-bar': {
tag: 'Ristoranti Bar',
periodTag: 'Uscite / Mensili',
type: 'expense',
},
};
const login = async () => {
try {
console.log('LOGIN');
const body = JSON.stringify({
userid: BUXFER_USERNAME,
password: BUXFER_PASSWORD,
});
const res = await client.post(`${BUXFER_API_URL}/login`, { body });
const resBody = JSON.parse(res.body);
if (resBody.response.status !== 'OK' || resBody.response.token.length === 0) return new Error('login failed');
loginToken = resBody.response.token;
return undefined;
} catch (err) {
return err;
}
};
const addTransaction = async ({
date, description, amount, type, tag, periodTag,
}) => {
try {
if (!loginToken) {
const err = await login();
if (err) return err;
}
const body = JSON.stringify({
date,
description,
amount,
type,
token: loginToken,
tags: [tag, periodTag].join(','),
accountId: BUXFER_ACCOUNT_ID,
});
const res = await client.post(`${BUXFER_API_URL}/add_transaction`, { body });
const resBody = JSON.parse(res.body);
if (resBody.response.error) {
if (resBody.response.error.message === 'Access denied. Please login first.') {
console.log('token expired, new retry with login first');
loginToken = '';
return await addTransaction(date, description, amount, type, tag, periodTag);
}
return new Error(resBody.response.error.message);
}
return undefined;
} catch (err) {
return err;
}
};
const onInsertTransaction = async agent => {
const { number, date, ...parameters } = agent.parameters;
if (!number) return agent.add('Vostra eccellenza, mancherebbe l\'importo');
const transaction = Object.entries(parameters)
.reduce((acc, param) => {
if (param[1]) {
acc.push({
description: param[1],
...transactionTags[param[0]],
amount: number,
});
}
return acc;
}, [])
// .flatMap(param => (param[1] ? { description: param[1], ...transactionTags[param[0]], amount: number } : undefined))
.filter(param => param)
.shift();
transaction.date = date ? dayjs(date) : dayjs();
transaction.date = transaction.date.format('YYYY-MM-DD');
let reply;
if (!transaction.tag || !transaction.periodTag) {
console.error(new Error('missing tag and/or error tag'));
console.log(transaction);
reply = 'non riesco a capire il tag o il period tag di riferimento! vuoi registrare una nuova transazione?';
} else {
const error = await addTransaction(transaction);
if (error) {
console.error(error);
reply = 'qualcosa è andato storto! vuoi registrare una nuova transazione?';
} else reply = 'ho registrato la transazione, vostra eccellenza! vuole registrarne una nuova?';
}
return agent.add(reply);
};
const dialogflowAgentProcessor = (request, response) => {
const agent = new WebhookClient({ request, response });
const intentMap = new Map();
intentMap.set('Insert transaction', onInsertTransaction);
agent.handleRequest(intentMap);
};
app.post('/', (req, res) => {
dialogflowAgentProcessor(req, res);
});
app.listen(port, () => console.log(`Listening on port ${port}`));