forked from codeforanchorage/courtbot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sendReminders.js
77 lines (72 loc) · 2.33 KB
/
sendReminders.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
/* eslint "no-console": "off" */
const db = require('./db.js');
const manager = require('./utils/db/manager');
const messages = require('./utils/messages');
const knex = manager.knex;
const logger = require('./utils/logger');
/**
* Find all reminders with a case date of tomorrow for which a reminder has not been sent for that date/time
*
* @return {array} Promise to return results
*/
function findReminders() {
return knex.raw(`
SELECT DISTINCT case_id, phone, defendant, date, room FROM requests
INNER JOIN hearings USING (case_id)
WHERE tstzrange(TIMESTAMP 'tomorrow', TIMESTAMP 'tomorrow' + interval '1 day') @> hearings.date
AND requests.active = true
AND hearings.case_id NOT IN
(SELECT case_id FROM notifications WHERE notifications.type = 'reminder' AND notifications.event_date = hearings.date )
`)
.then(result => result.rows)
}
/**
* Update statuses of reminders that we send messages for.
*
* @param {Object} reminder reminder record that needs to be updated in db.
* @return {Promise} Promise that resolves to the reminder.
*/
function sendReminder(reminder) {
const phone = db.decryptPhone(reminder.phone);
return messages.send(phone, process.env.TWILIO_PHONE_NUMBER, messages.reminder(reminder))
.then(() => {
return knex('notifications')
.insert({
case_id: reminder.case_id,
phone:reminder.phone,
event_date: reminder.date,
type: 'reminder'
})
.then(() => reminder) // knex needsa then() to fire the request
})
.catch(err => {
return knex('notifications')
.insert({
case_id: reminder.case_id,
phone:reminder.phone,
event_date: reminder.date,
type: 'reminder',
error: err.message
})
.then(() =>{
logger.error(err)
reminder.error = err
return reminder
})
})
}
/**
* Main function for executing:
* 1.) The retrieval of court date reminders
* 2.) Add notification and Send Status
*
* @return {Promise} Promise to send messages and update statuses.
*/
function sendReminders() {
return findReminders()
.then(resultArray => Promise.all(resultArray.map(r => sendReminder(r))))
}
module.exports = {
findReminders,
sendReminders,
};