-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
289 lines (203 loc) · 6.68 KB
/
app.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
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Require the module express
var express = require('express');
// Create a new express server, store in the variable app
var app = express();
// Store chat messages in messages
var messages = [];
// Store response objects that we want to respond to later
var responseObjs = [];
var data = require('./MOCK-DATA.json');
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
// Active index
var cindex = 0;
var state = [
{ "step": "introduction",
"options": ["Hitta bostad"],
"message": "Hejsan! Jag är en simpel chattbot som gärna hjälper dig att hitta ditt drömboende. För nuvarande kan jag hjälpa dig att.." ,
"err": "Vänligen välj 'hitta bostad' för att komma igång.",
"value":undefined},
{ "step": "city",
"message": "Vilken stad vill du hitta boende i?",
"options": ['Stockholm', 'Göteborg', 'Malmö'],
"err": "Vi kan inte hantera ditt val av stad just nu. Vänligen försök igen.",
"value":undefined},
{ "step": "price",
"message": "Vad är din maxbudget?",
"options": ['0-500.000','500.000-1.000.000', '1.000.000-2.500.000', '2.500.000-5.000.000'],
"err": "Vi kan inte hantera ditt val av maxbudget just nu. Vänligen försök igen.",
"value":undefined},
{ "step": "sqm",
"message": "Hur stor yta vill du bo på?",
"options": ["0-30", "31-60", "61-80", "81-150"],
"err": "Vi kan inte hantera ditt val av yta att bo på. Vänligen försök igen.",
"value":undefined},
{ "step": "generate",
"message": "Söker efter bostäder enligt dina kriterier ...",
"options": ["Återställ"],
"err": "Försår inte ..",
"value":undefined}
];
function botResponse(value) {
if (value) { value = capitalizeFirstLetter(value.toLowerCase()); }
if (value === "Återställ") {return reset();}
let st = state[cindex];
// Value handler
// Check if inputvalue is OK
let correctInput = st.options.indexOf(value);
if (correctInput == -1) {
messages.push({
name: "Bostadsbotten",
time: new Date().getTime(),
text: st.err,
options: st.options || false
});
return answer();
}else{
state[cindex].value = value;
cindex++
}
st = state[cindex];
if (st){
state[cindex].value = value;
messages.push({
name: "Bostadsbotten",
time: new Date().getTime(),
options: st.options || false,
text: st.message
});
}
if (st.step === "generate") {
let propertiesObj = generateLiving(state);
let txt = propertiesObj.length>0 ? "Vi fann dessa object" : "Tyvrr finns det inga lediga object enligt dina kriterier.";
messages.push({
name: "Bostadsbotten",
time: new Date().getTime(),
text: txt,
properties: propertiesObj
});
}
answer();
//console.log("state",state[cindex])
}
function reset() {
cindex = 0;
messages = [];
messages.push({
name: "Bostadsbotten",
time: new Date().getTime(),
text: state[0].message,
options: state[0].options
});
state.forEach(function(object) {
object.value = undefined;
});
}
// Initiate with a reset of the application
reset();
function generateLiving(st) {
//console.log("st",st)
var objects = [];
objects = data.filter(function(obj){
var meetsRequirements = true;
for (var i in st) {
var inputObj = st[i];
var dataValue = obj[inputObj.step];
if (dataValue) {
var hasTwoValues = inputObj.value.indexOf("-");
if (hasTwoValues > 0) {
let min = inputObj.value.substr(0, hasTwoValues).split('.').join("");
let max = inputObj.value.substr(hasTwoValues + 1, inputObj.value.length).split('.').join("");
//console.log(obj[inputObj.step], min, max, dataValue >= min && dataValue <= max)
meetsRequirements = (dataValue >= min && dataValue <= max);
}else{
meetsRequirements = (dataValue === inputObj.value);
}
}
if (meetsRequirements === false){break;}
}
return meetsRequirements;
});
return objects;
}
// Testfunction
function runTest() {
console.log("#TestRun")
let st = state;
for(var i=1;i<state.length;i++){
let obj = st[i];
console.log("Fråga:",obj.question)
for (var t=0;t<obj.options.length;t++){
console.log(obj.options[t])
}
let randomOption = obj.options[getRandomInt(obj.options.length)];
console.log("Du valde", randomOption);
obj.value = randomOption;
}
generateLiving(st);
}
//runTest();
// Send a new message
app.get('/send-message/:message',function(req,res){
// add the message to the message array
// with a timestamp and the text of the message
messages.push({
name: "Anton",
time: new Date().getTime(),
text:req.params.message
});
res.json({ok:"messaged recieved"});
botResponse(req.params.message);
answer();
});
// Get all messages after a certain timestamp
app.get('/read-messages/:lastTime',function(req,res){
responseObjs.push({
name: "Anton",
lastTime: req.params.lastTime,
time: new Date().getTime(),
res: res
});
answer();
});
// Point to a folder where we have static files
// (our frontend code)
app.use(express.static('www'));
app.listen(3000, function () {
console.log('Express app listening on port 3000!');
});
// Add an interval for answer so that the function
// runs even if nobody is chatting right now
setInterval(answer,1000);
function answer(){
// Answer things
responseObjs.forEach(function(obj){
var res = obj.res,
time = obj.time,
lastTime = obj.lastTime,
answer = [],
now = new Date().getTime();
// collect all messages for that hasn't been read yet
messages.forEach(function(message){
if(message.time > lastTime){
answer.push(message);
}
});
// close the response = send to browser
// if there are unread messages or the request
// is older than 25 seconds
if(answer.length || now - time > 25000){
res.json(answer);
obj.answered = true;
}
});
// Remove things from the responseObjs array
// that has been answered
responseObjs = responseObjs.filter(function(resObj){
return !resObj.answered;
});
}