-
Notifications
You must be signed in to change notification settings - Fork 0
/
witController.js
225 lines (204 loc) · 6.41 KB
/
witController.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
const express = require("express");
const router = express.Router();
const axios = require("axios");
const moment = require("moment");
const { isEmpty, get } = require("lodash");
const totalLeaves = 10;
router.post("/leaves", async (req, res) => {
const { rawText = "" } = req.body;
//CALL WIT API
let config = {
method: "get",
maxBodyLength: Infinity,
url: `https://api.wit.ai/message?v=${moment()
.utc()
.format("YYYYMMD")}&q=${encodeURIComponent(rawText)}`,
headers: {
Authorization: "Bearer CBS4VBTWVOHMKZVLCPY4L2NJOYYIQLOC",
},
};
let witResponse = await axios
.request(config)
.then((response) => {
console.log("WIT Response --> ", JSON.stringify(response.data));
return response.data;
return res.status(200).json(response.data);
})
.catch((error) => {
console.log(error);
return {};
// return res.status(400).json(error);
});
let query = "";
let completeQuery = "";
let startDate = moment().utc();
let endDate = moment().utc();
//CATEGORIZE THE INTENTS
let intent = get(witResponse, "intents[0].name", null);
let nameEntity = get(witResponse, "entities.name:name", {});
let timeEntity = get(witResponse, "entities.wit$datetime:datetime", {});
let comparisionEntity = get(
witResponse,
"comparison_factor:comparison_factor[0].value",
"most"
);
//Destructure intent / enteties
let { startTime, endTime, isTimePresent } = resolveTimeEntity(
timeEntity,
intent
);
startDate = startTime;
endDate = endTime;
let name = !isEmpty(nameEntity) ? getNameString(nameEntity) : "";
if (!isEmpty(intent)) {
if (intent == "get_public_holiday") {
query =
"SELECT holiday_name, TO_CHAR(holiday_date, 'DD-MM-YYYY') AS formatted_date from public_holiday";
query += ` where holiday_date BETWEEN $1 AND $2`;
} else {
if (["get_leave", "get_leave_people"].includes(intent)) {
query =
"SELECT u.user_name, TO_CHAR(l.date, 'DD-MM-YYYY') AS leave_date FROM leaves l JOIN users u ON u.user_id=l.user_id";
} else if (intent == "check_leave_people") {
completeQuery = `SELECT
CASE
WHEN EXISTS (
SELECT
1
FROM
leaves l
JOIN users u ON u.user_id = l.user_id
where
l.date BETWEEN $1 AND $2
AND u.user_name ILIKE ANY (ARRAY[${name}])
) THEN 'Yes'
ELSE 'No'
END AS ON_LEAVE;`;
} else if (intent == "get_leave_count") {
query = `SELECT (${totalLeaves} - COUNT(*)) AS leaves_left FROM leaves l JOIN users u ON u.user_id=l.user_id`;
} else if (intent == "get_leave_people_past") {
completeQuery = `SELECT
u.user_name,
TO_CHAR(l.date, 'DD-MM-YYYY') AS leave_date
FROM
leaves l
JOIN users u ON u.user_id = l.user_id
where
l.date BETWEEN $1 AND $2
AND u.user_name ILIKE ANY (ARRAY[${name}])
ORDER BY
l.date
LIMIT
1`;
} else if (intent == "get_leave_comparision") {
let comp = comparisionEntity == "most" ? "desc" : "asc";
completeQuery = `SELECT u.user_name, COUNT(*) AS leave_count
FROM leaves l JOIN users u ON u.user_id=l.user_id
WHERE l.date BETWEEN $1 AND $2
GROUP BY u.user_name
ORDER BY leave_count ${comp}
limit 1`;
}
query += ` where l.date BETWEEN $1 AND $2`;
}
} else {
return res.status(200).json("unable to get intent from the text");
}
if (!isEmpty(nameEntity)) {
// query += ` AND u.user_name IN (${name})`; OLD QUERY
query += ` AND u.user_name ILIKE ANY (ARRAY[${name}])`;
}
if (!isEmpty(completeQuery)) {
query = completeQuery;
}
// CALL POSTGRES DB
console.log("DB QUERY -->", query, [startDate, endDate]);
await global.pool.query(query, [startDate, endDate], (error, result) => {
if (error) {
console.error("Error executing query:", error);
return res.status(400).json({ error: "Error executing query" });
} else {
let data = result.rows;
console.log("RESULT -->", data);
return res.status(200).json(formatResult(data, intent));
}
});
});
const getNameString = (array) => {
const values = array.map((obj) => `'%${obj.value}%'`);
return values.join(",");
};
const resolveTimeEntity = (timeEntity, intent) => {
let startTime;
let endTime;
let defaultDate = moment();
let timeObj = timeEntity[0];
if (intent == "get_leave_people_past") {
return {
startTime: moment().utc().startOf("year").toDate(),
endTime: moment().utc().endOf("day").toDate(),
isTimePresent: false,
};
}
if (intent == "get_leave_count") {
return {
startTime: moment().utc().startOf("year").toDate(),
endTime: moment().utc().endOf("year").toDate(),
isTimePresent: false,
};
}
if (isEmpty(timeObj)) {
return {
startTime: moment().utc().startOf("day").toDate(),
endTime: moment().utc().endOf("year").toDate(),
isTimePresent: false,
};
} else {
let type = get(timeObj, "type", "");
let grain = get(timeObj, "grain", "");
if (type == "interval") {
let start = get(timeObj, "from.value", defaultDate);
let end = get(timeObj, "to.value", defaultDate);
startTime = moment(start).startOf("day").utc().toDate();
endTime = moment(end).endOf("day").utc().toDate();
}
if (["day", "week", "month", "year"].includes(grain)) {
let value = get(timeObj, "value", defaultDate);
startTime = moment(value).startOf(grain).utc().toDate();
endTime = moment(value).endOf(grain).utc().toDate();
}
}
return {
startTime,
endTime,
isTimePresent: true,
};
};
const formatResult = (data, intent) => {
let result;
switch (intent) {
case "get_public_holiday":
result = data;
break;
case "get_leave":
case "get_leave_people":
result = isEmpty(data) ? "No Leaves found" : data;
break;
case "check_leave_people":
result = data;
break;
case "get_leave_count":
result = data;
break;
case "get_leave_people_past":
result = isEmpty(data) ? "No Leaves found" : data;
break;
case "get_leave_comparision":
result = data;
break;
default:
result = "Unable to acquire leave data";
}
return result;
};
module.exports = router;