forked from jjabraham/hack-21-0ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
187 lines (155 loc) · 7.05 KB
/
server.js
File metadata and controls
187 lines (155 loc) · 7.05 KB
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const training = require("./training.js");
const axios = require('axios').default;
const {NlpManager} = require('node-nlp');
const manager = new NlpManager({languages: ['en'], nlu: {useNoneFeature: false}});
const knex = require("knex")({
client: "pg",
searchPath: ["hack_21_0ui"],
connection: {
database: "hack_21_0ui",
host: "hack-21-0ui-1.cbh1nk2bl81k.ap-southeast-2.rds.amazonaws.com",
port: 5432,
user: "postgres",
password: "uB7mUnQ2xRdrTl",
}
})
training(manager);
app.use(bodyParser.json({limit: "5mb"}));
app.get("/", ((req, res) => {
const response = manager.process('en', req.query.q).then(res => {
// select conversation_id = 1 from chat_state
let row = knex("chat_state").select('*').where('conversation_id', 'xxxxxxxx').then(res => {
console.log(res);
}).catch(err => {
console.log(err);
})
});
// send response hello world
res.send("Hello World");
}
));
app.post("/", async (req, res) => {
const body = req.body;
const senderId = body.data.message.senderId;
const options = {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'};
let incomingMessageText = body.data.message.text;
if (senderId === "1") {
console.log('this stopped')
return;
}
let row = await knex("chat_state").select('*').where('conversation_id', body.data.message.conversationId);
if (row.length === 0) {
// get random from 10 to 20
let random = Math.floor(Math.random() * 10) + 10;
let data = {
leave: random
}
await knex("chat_state").insert({conversation_id: body.data.message.conversationId, data: data});
row = await knex("chat_state").select('*').where('conversation_id', body.data.message.conversationId);
console.log(row);
}
row = row[0];
console.log(row);
console.log(incomingMessageText);
incomingMessageText = incomingMessageText.toLowerCase();
if (incomingMessageText.includes("apply") && incomingMessageText.includes("leave")) {
const res = await manager.process('en', incomingMessageText);
let startDate = false;
let endDate = false;
let days = false;
for (let entity in res.entities) {
if (res.entities[entity].entity === 'daterange') {
console.log(res.entities[entity].entity);
startDate = new Date(res.entities[entity].resolution.start).toLocaleDateString("en-AU", options);
endDate = new Date(res.entities[entity].resolution.end).toLocaleDateString("en-AU", options);
// exclude weekends
let start = new Date(res.entities[entity].resolution.start);
let end = new Date(res.entities[entity].resolution.end);
let count = 0;
while (start <= end) {
if (start.getDay() !== 0 && start.getDay() !== 6) {
count++;
}
start.setDate(start.getDate() + 1);
}
days = count;
}
}
if (!startDate) {
return answerMessage("Did you mean to apply for leave? I didn't understand your date range", body);
}
// get difference between start and end date
console.log(days);
if (row.data.leave >= days) {
// update leave
let newLeave = row.data.leave - days;
row.data.pendingLeave = newLeave;
row.data.lastMessage = 'apply';
await knex("chat_state").update({data: row.data}).where('conversation_id', row.conversation_id);
//await knex("chat_state").update({data: {leave: newLeave}}).where('conversation_id', body.data.message.conversationId);
// send response
return answerMessage("Do you want to apply for leave from "
+ startDate + " to " + endDate + "? This will take a total of " + days
+ " days from your current leave, leaving you with a leave balance of " + newLeave + " days", body);
} else {
return answerMessage("You don't have enough leave to fulfill your request, your current leave balance is " + row.data.leave + " days", body);
}
}
if (incomingMessageText.includes("yes") && row.data.lastMessage === 'apply') {
row.data.leave = row.data.pendingLeave;
row.data.pendingLeave = null;
row.data.lastMessage = null;
await knex("chat_state").update({data: row.data}).where('conversation_id', row.conversation_id);
answerMessage("Awesome, your leave is applied, I hope you have a great time, your resulting leave balance is: NULL days", body);
// timeout for 2 seconds
setTimeout(() => {
answerMessage("Just kidding you have still " + row.data.leave + " days of leave 😀", body);
}, 3000);
return;
}
if (incomingMessageText.includes("no") && row.data.lastMessage === 'apply') {
return answerMessage("Oh I must have misunderstood something, you can try again anytime you like", body);
}
if ((incomingMessageText.includes("what") || incomingMessageText.includes("how much")) && incomingMessageText.includes("leave")) {
return answerMessage('Your leave balance is: ' + row.data.leave + " days", body);
}
if ((incomingMessageText.includes("paid") || incomingMessageText.includes("pay") || incomingMessageText.includes("salary"))
&& incomingMessageText.includes("when")
) {
return answerMessage('Your next payment is due at 24th of December', body);
}
if ((incomingMessageText.includes("paid") || incomingMessageText.includes("pay") || incomingMessageText.includes("salary"))
&& incomingMessageText.includes("how much")
) {
return answerMessage('Your payment will be a total $100.000 and will be deposited on your account at 24th of December', body);
}
return answerMessage(
"Sorry I didn't understand that, I can help you check your leave balance or apply for leave or check when is your next payment due",
body
);
function answerMessage(text, body) {
axios.post("https://api.talkjs.com/v1/" + process.env.TALK_JS_APP_ID + "/conversations/" + body.data.message.conversationId + "/messages", [
{
"text": text,
"sender": "1",
"type": "UserMessage"
}
], {
headers: {
'Authorization': 'Bearer ' + process.env.TALK_JS_API_TOKEN,
'Content-Type': 'application/json'
}
}).then(response => {
console.log(response.data);
res.send(response.data);
}).catch(error => {
console.log(error);
res.send(error);
});
}
})
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Sever listening at http://localhost:${PORT}`));