-
Notifications
You must be signed in to change notification settings - Fork 17
/
requests.js
331 lines (313 loc) · 9.53 KB
/
requests.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
const { merge } = require("lodash");
const _ = require("lodash");
const { airbase } = require("~airtable/bases");
const requestNotInSlack = (r) => {
const meta = r.get(fields.meta);
let parsed = {};
try {
parsed = JSON.parse(meta);
} catch {
console.log("Invalid meta %s: %O", r.get(fields.code), meta);
}
return parsed.slack_ts === undefined;
};
// Delivery cluster requests are handled separately
const notForDrivingCluster = (r) => {
const forDrivingCluster = r.get(fields.forDrivingClusters);
return !forDrivingCluster;
};
exports.deleteRequest = async (recordId) => {
console.log("Deleting record");
try {
const records = await requestsTable.destroy([recordId]);
return [records[0], null];
} catch (e) {
console.error(`Couldn't delete request: ${e}`);
return [null, e];
}
};
exports.createRequest = async (request) => {
// TODO: add asserts for non-|| fields below
console.log("creating record");
try {
const record = await requestsTable.create({
[fields.message]: request.message,
[fields.phone]: request.phone || "",
[fields.type]: request.source,
[fields.externalId]: request.externalId || "",
[fields.crossStreetFirst]: request.crossStreets || "",
[fields.email]: request.email || "",
[fields.timeSensitivity]: request.urgency || "",
[fields.status]: request.status || fields.status_options.dispatchNeeded,
});
return [record, null];
} catch (e) {
console.error(`Couldn't create request: ${e}`);
return [null, e];
}
};
exports.findRequestByExternalId = async (externalId) => {
try {
const record = await requestsTable
.select({
filterByFormula: `({${fields.externalId}} = '${externalId}')`,
})
.firstPage();
return record
? [record[0], null]
: [null, "Request with that external ID not found"];
} catch (e) {
console.error(`Error while fetching request by eID: ${e}`);
return [null, e];
}
};
// Find open requests that area already in Slack
exports.findDeliveryNeededRequests = async () => {
const requestOpenStates = [
fields.status_options.dispatchStarted,
fields.status_options.deliveryNeeded,
];
const statusConstraints = requestOpenStates.map(
(s) => `{${fields.status}} = '${s}'`
);
const formula = `OR(${statusConstraints.join(", ")})`;
try {
const requests = await requestsTable
.select({
filterByFormula: formula,
})
.all();
return [requests.filter((r) => !requestNotInSlack(r)), null];
} catch (e) {
return [[], `Error while looking up open requests: ${e}`];
}
};
// Returns requests that are to be posted in a public requests channel
exports.findOpenRequestsForSlack = async () => {
const requestOpenStates = [
fields.status_options.dispatchStarted,
fields.status_options.deliveryNeeded,
];
const statusConstraints = requestOpenStates.map(
(s) => `{${fields.status}} = '${s}'`
);
const formula = `OR(${statusConstraints.join(", ")})`;
try {
const requests = await requestsTable
.select({
filterByFormula: formula,
})
.all();
return [
requests.filter(requestNotInSlack).filter(notForDrivingCluster),
null,
];
} catch (e) {
return [[], `Error while looking up open requests: ${e}`];
}
};
exports.findRequestByCode = async (code) => {
if (code && code.length < 4) {
return [null, `Request code must be at least 4 characters.`];
}
try {
const records = await requestsTable
.select({
filterByFormula: `(FIND('${code}', {${fields.code}}) > 0)`,
})
.firstPage();
if (records.length === 0) {
return [null, "No requests found with that code."];
}
const record = records[0];
return [record, null];
} catch (e) {
return [null, `Error while finding request: ${e}`];
}
};
exports.findRequestByPhone = async (phone) => {
try {
const records = await requestsTable
.select({
maxRecords: 1,
fields: [fields.phone],
filterByFormula: `({${fields.phone}} = '${phone}')`,
})
.firstPage();
if (records && records.length === 0) {
return [null, "No existing request with that phone"];
}
return [records[0], null];
} catch (e) {
return [null, `Error while finding request: ${e}`];
}
};
// `update` should look like:
// {
// "Some Requests Field": "New Value",
// "Another field": "Another New Value"
// "Meta": {key: "value"}
// }
exports.updateRequestByCode = async (code, update) => {
if (code && code.length < 4) {
return [null, `Request code must be at least 4 characters.`];
}
try {
const records = await requestsTable
.select({
filterByFormula: `(FIND('${code}', {${fields.code}}) > 0)`,
})
.firstPage();
if (records.length === 0) {
return [null, `No requests found with code: ${code}`];
}
if (update[fields.meta]) {
// Support for updating Meta as an object (rather than string)
/* eslint no-param-reassign: ["error", { "props": false }] */
const parsed = JSON.parse(records[0].get(fields.meta));
merge(parsed, update[fields.meta]);
update[fields.meta] = JSON.stringify(parsed);
}
const record = records[0];
const airUpdate = {
id: record.id,
fields: update,
};
const updatedRecords = await requestsTable.update([airUpdate]);
return [updatedRecords[0], null];
} catch (e) {
return [null, `Error while processing update: ${e}`];
}
};
exports.unlinkSlackMessage = async (slackTs, slackChannel) => {
const tsFilter = `"slack_ts":"${slackTs}"`;
const channelFilter = `"slack_channel":"${slackChannel}"`;
const filter = `AND(SEARCH('${tsFilter}', {${fields.meta}}), SEARCH('${channelFilter}', {${fields.meta}}))`;
await requestsTable
.select({
filterByFormula: filter,
})
.eachPage((records, fetchNextPage) => {
records.forEach(async (record) => {
const meta = removeSlackMeta(record.get(fields.meta));
try {
await requestsTable.update([
{ id: record.id, fields: { [fields.meta]: meta } },
]);
} catch (e) {
console.error("Error updating Request %O %O", record.id, e);
}
});
fetchNextPage();
});
};
const removeSlackMeta = (meta) =>
_.chain(meta)
.thru(JSON.parse)
.omit("slack_ts")
.omit("slack_channel")
.thru(JSON.stringify)
.value();
// ==================================================================
// Schema
// ==================================================================
const requestsTableName = (exports.tableName = "Requests");
const requestsTable = (exports.table = airbase(requestsTableName));
const fields = (exports.fields = {
phone: "Phone",
time: "Time",
type: "Text or Voice?",
type_options: {
text: "text",
voice: "voice",
manyc: "manyc",
email: "email",
},
message: "Message",
crossStreetFirst: "Cross Street #1",
crossStreetSecond: "Cross Street #2",
email: "Email Address",
neighborhoodArea: "Neighborhood Area (See Map)",
neighborhoodArea_options: {
ne: "NE",
nw: "NW",
se: "SE",
sw: "SW",
notCrownHeights: "Other - not Crown Heights",
},
languages: "Languages",
languages_options: {
spanish: "Spanish",
chineseMandarin: "Chinese - Mandarin",
chineseCantonese: "Chinese - Cantonese",
haitianKreyol: "Haitian Kreyol",
russian: "Russian",
bengali: "Bengali",
french: "French",
yiddish: "Yiddish",
italian: "Italian",
korean: "Korean",
arabic: "Arabic",
tagalog: "Tagalog",
polish: "Polish",
asl: "ASL",
english: "English",
eglish: "eglish",
},
supportType: "What type(s) of support are you seeking?",
supportType_options: {
delivery: "Deliver groceries or supplies to me",
prescriptionPickUp: "Pick up a prescription for me",
"1On1CheckInsPhoneCallZoomEtcToTouchBaseWithANeighbor":
"1 on 1 check-ins (phone call, Zoom, etc to touch base with a neighbor)",
financialSupport: "Financial support",
translation:
"Translation and interpretation into a language other than English",
socialServices:
"Social Services guidance (filing for medicare, unemployment, etc)",
other: "Other (please describe below)",
},
financialSupportNeeded: "Financial Support Needed?",
financialSupportNeeded_options: {
yes: "yes - need donation",
no: "no donation need",
},
intakeVolunteer: "Intake volunteer",
deliveryVolunteer: "Delivery volunteer",
timeSensitivity: "Time Sensitivity",
intakeNotes: "Intake General Notes",
startEditingHere: "Start Editing Here!",
receipts: "Receipts",
code: "Code",
status: "Status",
status_options: {
dispatchNeeded: "Dispatch Needed",
dispatchStarted: "Dispatch Started",
noAnswer: "No Answer (call back)",
deliveryNeeded: "Delivery Needed",
duplicate: "Duplicate",
deliveryAssigned: "Delivery Assigned",
requestComplete: "Request Complete",
beyondCrownHeights: "Beyond Crown Heights",
otherFollowup: "Other Followup",
sentToAnotherGroup: "Sent to Another Group",
needsPosting: "Needs Posting!",
brownsville: "Brownsville/East NY",
},
externalId: "External Id",
deliverySlackId: "Delivery slackId",
lastModified: "Last Modified",
meta: "Meta",
lastProcessed: "Last Processed",
firstName: "First Name",
triggerBackfill: "Trigger Backfill",
neighborhood: "Neighborhood MA-NYC",
householdSize: "Household Size",
forDrivingClusters: "For Driving Clusters",
});
exports.SENSITIVE_FIELDS = [
fields.phone,
fields.email,
fields.message,
fields.intakeNotes,
];