-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler.ts
275 lines (255 loc) · 8.3 KB
/
handler.ts
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
import {
APIGatewayProxyHandler
} from 'aws-lambda';
import 'source-map-support/register';
import * as Knex from 'knex';
import * as moment from 'moment';
import {
Model,
knexSnakeCaseMappers
} from 'objection';
import {
Counties
} from './types';
import {
browardCountyCDLCheck
} from './lib/functions/browardCountyCheck';
import {
miamiDadeCountyCDLCheck
} from './lib/functions/miamiDadeCountyCheck';
//Helpers
import {
validateEmail,
validatePhoneNumber,
validateDLSubmission
} from './validators';
import {
Subscription
} from './models/subscription'
import
DriverLicense
from './models/driverLicense';
import {
sendEnrollmentConfirmation,
sendReportSMS,
lookupPhoneNumber
} from './lib/functions/twilio';
import {
SubscriptionRequest
} from './models/SubscriptionRequest';
import {
Notification
} from './models/notification';
const knexConfig = require('./knexfile');
const knex = Knex({
...knexConfig,
...knexSnakeCaseMappers()
});
Model.knex(knex);
export const migrate: APIGatewayProxyHandler = async (event, _context) => {
await knex.migrate.latest(knexConfig);
return {
statusCode: 200,
body: JSON.stringify({
message: 'Migration Ran',
input: event,
}, null, 2),
};
}
/**
* @param {string} dlNumber - Florida driverLicense For Miami Dade Selections
* @returns {string} - success or error
*/
export const rundlReports: APIGatewayProxyHandler = async (_, _context) => {
console.dir('starting');
const thirtyDaysAgo = moment().utc().subtract(1, 'months').format();
// get all valid Subscriptions with no notification in the last 30 days
// what if no notification but drivers report is last 30?
// what if no notification but drivers report is last 30?
const subscription = await Subscription.query()
.alias('sub')
.leftJoin((qb) =>
qb.select('subscription_id')
.max('created_on as createdOn')
.from('notifications')
.groupBy('subscription_id')
.as('notifications'),
(qb) => qb.on('notifications.subscription_id', '=', 'sub.id'))
.whereNull('sub.unsubscribedOn')
.andWhere((qb) => qb.where('notifications.createdOn', '<=', thirtyDaysAgo).orWhere('notifications.createdOn', null))
.first();
// TODO consider some sort of group by driverlicense so we can run the report onces and easily sent it to relevant recipients so we don't rerun scrapes.
if (typeof subscription !== 'undefined') {
try {
const driverLicense = await DriverLicense.query().where('id', subscription.driverLicenseId).first();
const reporterCounty = driverLicense.county === 'MIAMI-DADE' && driverLicense.dateOfBirth ? Counties['MIAMI-DADE'] : Counties['BROWARD'] ;
const notification = await Notification.query().insertAndFetch({
driverLicenseId: subscription.driverLicenseId,
contactMethod: 'SMS',
subscriptionId: subscription.id,
county: reporterCounty,
status: 'PENDING'
});
let reportText;
let source;
if (reporterCounty === Counties['MIAMI-DADE']) {
source = 'Miami-Dade County Clerk Of Courts';
const report = await miamiDadeCountyCDLCheck(driverLicense.driverLicenseNumber, driverLicense.dateOfBirth);
reportText = report;
} else {
source = 'Broward County Clerk Of Courts';
const { reportInnerText } = await browardCountyCDLCheck(driverLicense.driverLicenseNumber);
reportText = reportInnerText;
}
const message = await sendReportSMS(subscription.phoneNumber, driverLicense.driverLicenseNumber, reportText, source);
const messageResult = message[0];
delete messageResult.body;
await Notification.query()
.findById(notification.id)
.patch({
notificationRequestResponse: messageResult,
status: 'SENT'
});
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
// include number and some subscription ids?
body: JSON.stringify({
message: 'Notification sent'
}, null, 2),
};
} catch (error) {
// alert on these errors but don't halt thread cause we'll have to keep going
console.error(`unable to process subId ${subscription.id}`);
console.error(error);
// lets update the notification table so we can be sure we don't spam anyways
await Notification.query().insert({
driverLicenseId: subscription.driverLicenseId,
contactMethod: 'SMS',
subscriptionId: subscription.id,
notificationRequestResponse: {reason: "ERROR"},
county: subscription.county,
status: 'failed'
});
return {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
statusCode: 422,
body: JSON.stringify({
description: error.message
}),
};
}
}
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
message: 'No notifications to send'
}, null, 2),
};
}
export const subscription: APIGatewayProxyHandler = async (event, _context) => {
const subscriptionRequest: SubscriptionRequest = JSON.parse(event.body);
const {
emailAddressClient,
phoneNumberClient,
driverLicenseIdClient,
countyClient,
dateOfBirthClient
} = subscriptionRequest;
if (typeof emailAddressClient !== 'string' || typeof driverLicenseIdClient !== "string" || typeof countyClient !== "string" || typeof phoneNumberClient !== "string" || (countyClient === "MIAMI-DADE" && typeof dateOfBirthClient !== "string")) {
return {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
statusCode: 400,
body: 'BAD REQUEST'
};
}
try {
console.dir(`starting validation`);
const emailAddress = validateEmail(emailAddressClient);
const {
phoneNumber
} = await lookupPhoneNumber(phoneNumberClient);
validatePhoneNumber(phoneNumber);
const dateOfBirth = dateOfBirthClient ? moment.utc(dateOfBirthClient) : null;
const {
county,
driverLicenseNumber
} = validateDLSubmission(driverLicenseIdClient, countyClient);
console.dir(`client validation ended`);
// TODO upsert (adjust for concurrency). INSPO https://gist.github.com/derhuerst/7b97221e9bc4e278d33576156e28e12d
// TODO sanitaize return values from DB with try catch
let driverLicense = await DriverLicense.query().where('driverLicenseNumber', driverLicenseNumber).first()
if (driverLicense) {
const existingSubscription = await Subscription.query().where({
emailAddress,
phoneNumber,
driverLicenseId: driverLicense.id
}).first();
if (driverLicense.disabled || existingSubscription) {
return {
statusCode: 409,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
message: 'This is a duplicate Subscription in our system. Please reach out to [email protected] if you belive this is an Error'
}),
};
}
} else {
driverLicense = await DriverLicense.query().insert({
driverLicenseNumber,
county,
dateOfBirth,
disabled: false
});
}
// DL isn't found, need to create before moving forward
await Subscription.query().insert({
emailAddress,
phoneNumber,
driverLicenseId: driverLicense.id,
county,
createdOn: new Date(),
subscribedOn: new Date()
});
console.dir(`enrolled sending sms`);
await sendEnrollmentConfirmation(phoneNumberClient, driverLicenseIdClient);
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
message: 'success'
}),
};
} catch (error) {
console.error(error);
return {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
statusCode: 422,
body: JSON.stringify({
description: error.message
}),
};
}
};