-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
303 lines (271 loc) · 9.34 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
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
const Airtable = require("airtable");
const Task = require("./task");
const config = require("./config");
const AirtableUtils = require("./utils/airtable-utils");
const { filterByLanguage } = require("./languageFilter");
const { volunteerWithCustomFields } = require("./volunteerWithCustomFields");
const http = require("./http");
const { getCoords, distanceBetweenCoords } = require("./geo");
const { logger } = require("./logger");
const Request = require("./model/request-record");
const RequesterService = require("./service/requester-service");
const RequestService = require("./service/request-service");
const VolunteerService = require("./service/volunteer-service");
const { sendDispatch } = require("./slack/sendDispatch");
require("dotenv").config();
/* System notes:
* - Certain tasks should probably have an unmatchable requirement (because the tasks requires
* looking a shortlist of specialized volunteers)
* - Airtable fields that start with '_' are system columns, not to be updated manually
* - If the result seems weird, verify the addresses of the request/volunteers
*/
// Airtable
const base = new Airtable({ apiKey: config.AIRTABLE_API_KEY }).base(
config.AIRTABLE_BASE_ID
);
const customAirtable = new AirtableUtils(base);
const requesterService = new RequesterService(
base(config.AIRTABLE_REQUESTERS_TABLE_NAME)
);
const requestService = new RequestService(
base(config.AIRTABLE_REQUESTS_TABLE_NAME),
customAirtable,
requesterService
);
const volunteerService = new VolunteerService(
base(config.AIRTABLE_VOLUNTEERS_TABLE_NAME)
);
// Accepts errand address and checks volunteer spreadsheet for closest volunteers
/**
* Find volunteers.
*
* @param {object} request The Airtable request object.
* @returns {Array} An array of objects of the closest volunteers to the request,
* or an empty array if none are found.
*/
async function findVolunteers(request) {
const { tasks } = request;
if (tasks && tasks.length > 0 && tasks[0].equals(Task.LONELINESS)) {
return (await volunteerService.findVolunteersForLoneliness())
.map((v) => [v, "N/A"])
.map((volunteerAndDistance) =>
volunteerWithCustomFields(volunteerAndDistance, request)
);
}
let errandCoords;
try {
errandCoords = request.coordinates;
} catch (e) {
logger.error(
`Unable to parse coordinates for request ${request.id} from ${request.name}`
);
return [];
}
logger.info(`Tasks: ${tasks.map((task) => task.rawTask).join(", ")}`);
const volunteerDistances = [];
// Figure out which volunteers can fulfill at least one of the tasks
await base(config.AIRTABLE_VOLUNTEERS_TABLE_NAME)
.select({
view: config.AIRTABLE_VOLUNTEERS_VIEW_NAME,
filterByFormula: "{Account Disabled} != TRUE()",
})
.eachPage(async (volunteers, nextPage) => {
const suitableVolunteers = volunteers.filter((volunteer) =>
tasks.some((task) => task.canBeFulfilledByVolunteer(volunteer))
);
// Calculate the distance to each volunteer
for (const volunteer of suitableVolunteers) {
const volAddress =
volunteer.get(
"Full Street address (You can leave out your apartment/unit.)"
) || "";
// Check if we need to retrieve the addresses coordinates
// NOTE: We do this to prevent using up our free tier queries on Mapquest (15k/month)
if (volAddress !== volunteer.get("_coordinates_address")) {
let newVolCoords;
try {
newVolCoords = await getCoords(volAddress);
} catch (e) {
logger.info(
"Unable to retrieve volunteer coordinates:",
volunteer.get("Full Name")
);
customAirtable.logErrorToTable(
config.AIRTABLE_VOLUNTEERS_TABLE_NAME,
volunteer,
e,
"getCoords"
);
continue;
}
volunteer.patchUpdate({
_coordinates: JSON.stringify(newVolCoords),
_coordinates_address: volAddress,
});
volunteer.fetch();
}
// Try to get coordinates for this volunteer
let volCoords;
try {
volCoords = JSON.parse(volunteer.get("_coordinates"));
} catch (e) {
logger.info(
"Unable to parse volunteer coordinates:",
volunteer.get("Full Name")
);
continue;
}
// Calculate the distance
const distance = distanceBetweenCoords(volCoords, errandCoords);
volunteerDistances.push([volunteer, distance]);
}
nextPage();
});
// Filter the volunteers by language, then sort by distance and grab the closest 10
const volFilteredByLanguage = filterByLanguage(request, volunteerDistances);
const closestVolunteers = volFilteredByLanguage
.sort((a, b) => a[1] - b[1])
.slice(0, 10)
.map((volunteerAndDistance) =>
volunteerWithCustomFields(volunteerAndDistance, request)
);
logger.info("Closest:");
closestVolunteers.forEach((v) => {
logger.info(`${v.Name} ${v.Distance.toFixed(2)} Mi`);
});
return closestVolunteers;
}
/**
* Checks for updates on errand spreadsheet, finds closest volunteers from volunteer
* spreadsheet and executes slack message if new row has been detected or if the row's reminder
* date/time has passed
*
* @returns {void}
*/
async function checkForNewSubmissions() {
base(config.AIRTABLE_REQUESTS_TABLE_NAME)
.select({
view: config.AIRTABLE_REQUESTS_VIEW_NAME,
filterByFormula: `
AND(
{Name} != '',
OR(
{Posted to Slack?} != 'yes',
AND(
{Posted to Slack?} = 'yes',
{Reminder Posted} != 'yes',
AND(
{Reminder Date/Time} != '',
{Reminder Date/Time} < ${Date.now()}
)
)
)
)`,
})
.eachPage(async (records, nextPage) => {
if (!records.length) return;
const newSubmissions = records.map((r) => new Request(r));
// Look for records that have not been posted to slack yet
for (const record of newSubmissions) {
let requestWithCoords;
try {
requestWithCoords = await requestService.resolveAndUpdateCoords(
record
);
} catch (e) {
logger.error(
`Error resolving and updating coordinates of request ${record.id} of ${record.name}`
);
continue;
}
if (requestWithCoords.tasks.length > 1) {
// noinspection ES6MissingAwait
requestService.splitMultiTaskRequest(requestWithCoords);
continue;
}
logger.info(`New help request for: ${requestWithCoords.get("Name")}`);
try {
// Can be an async operation
// noinspection ES6MissingAwait - no need to wait for a response.
requestService.linkUserWithRequest(record);
} catch (e) {
logger.error("Unable to link user with request ", e);
}
let volunteers;
try {
// Find the closest volunteers
volunteers = await findVolunteers(requestWithCoords);
} catch (e) {
logger.error("Unable to find volunteers for request ", e);
}
// Send the message to Slack
let messageSent = false;
let reminder = false;
try {
if (
Date.now() > record.get("Reminder Date/Time") &&
record.get("Posted to Slack?") === "yes"
) {
await sendDispatch(requestWithCoords, volunteers, true);
reminder = true;
} else {
await sendDispatch(requestWithCoords, volunteers);
}
messageSent = true;
logger.info("Posted to Slack!");
} catch (error) {
logger.error("Unable to post to Slack: ", error);
}
if (messageSent) {
if (reminder) {
await requestWithCoords.airtableRequest
.patchUpdate({
"Reminder Posted": "yes",
})
.then(logger.info("Updated Airtable record!"))
.catch((error) => logger.error(error));
} else {
await requestWithCoords.airtableRequest
.patchUpdate({
"Posted to Slack?": "yes",
Status: record.get("Status") || "Needs assigning", // don't overwrite the status
})
.then(logger.info("Updated Airtable record!"))
.catch((error) => logger.error(error));
}
}
}
nextPage();
});
}
/**
* Start the chat bot service.
*
* @returns {void}
*/
async function start() {
try {
// Run once right away, and run again every 15 seconds
if (config.VOLUNTEER_DISPATCH_PREVENT_PROCESSING) {
logger.info(
"Processing prevented by VOLUNTEER_DISPATCH_PREVENT_PROCESSING flag!"
);
} else {
logger.info("Volunteer Dispatch started!");
setTimeout(checkForNewSubmissions, 0);
setInterval(checkForNewSubmissions, 15000);
}
// Run an HTTP server for health-check purposes
http.run();
} catch (error) {
logger.error(error);
}
}
process.on("unhandledRejection", (reason) => {
logger.error({
message: `Unhandled Rejection: ${reason.message}`,
stack: reason.stack,
});
// application specific logging, throwing an error, or other logic here
});
start();