forked from krysttian/ftw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.ts
279 lines (242 loc) · 7.78 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
276
277
278
279
import {
APIGatewayProxyHandler
} from 'aws-lambda';
import 'source-map-support/register';
import * as Knex from 'knex';
import {
Model,
knexSnakeCaseMappers
} from 'objection';
import * as convertXmlToJSON from 'xml2js'
import axios from 'axios';
//Helpers
import {
validateEmail,
validatePhoneNumber,
validateDLSubmission
} from './validators';
import {
Subscription
} from './models/subscription'
import
DriverLicense
from './models/driverLicense';
import {
sendEnrollmentConfirmation
} from './lib/functions/twilio';
// TYPES
import {
SubscriptionRequest
} from './subscription';
import {
DriverLicenseReport
} from './models/driverLicenseReport';
const knexConfig = require('./knexfile');
const knex = Knex({
...knexConfig,
...knexSnakeCaseMappers()
});
Model.knex(knex);
export const migrate: APIGatewayProxyHandler = async (event, _context) => {
console.dir('here');
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) => {
// log starting
// log number of subs
// log number of DL reports found vs making
const thirtyDaysAgo = new Date(new Date().setDate(new Date().getDate() - 30));
// get all valid Subscriptions with no notification in the last 30 days
// what if no notification but drivers report is last 30?
const dlIdsThatNeedReport = [];
const validSubscriptions = await Subscription.query().where('unsubscribedOn', null);
// extract just DL ids and transform to set for just unique values to reduce in unessecary addtional queries.
for (const sub of validSubscriptions) {
// most recent notification for that sub ID
const lastDlReport = await DriverLicenseReport.query().where('driverLicenseId', sub.driverLicenseId).orderBy('createdOn', 'desc').where('createdOn', '>=', thirtyDaysAgo).first();
if (!lastDlReport) {
dlIdsThatNeedReport.push(sub.driverLicenseId);
}
}
if (dlIdsThatNeedReport.length === 0) {
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: 'no subscriptions require report'
};
}
const uniqueDlIds = [...new Set(dlIdsThatNeedReport)];
const driverLicenses = await DriverLicense.query().whereIn('id', uniqueDlIds);
const baseURL = 'https://www2.miami-dadeclerk.com/Developers/';
const miamiDadeApiAuthKey = process.env['MIAMI_DADE_COUNTY_AUTH_KEY'] || 'NOKEY';
const apiMap = {
dlNumberSearch: 'api/TrafficWeb?DL={DL}&AuthKey='
}
for (const dl of driverLicenses) {
try {
// build url
const dlRequestUrl = baseURL.concat(apiMap.dlNumberSearch).replace('{DL}', dl.driverLicenseNumber).concat(miamiDadeApiAuthKey);
const dlRecord = await DriverLicense.query()
.where('driverLicenseNumber', dl.driverLicenseNumber).first();
// make request, XML only has information
const request = await axios.get(dlRequestUrl, {
headers: {
'Accept': 'application/xml',
}
});
const response = request.data;
const jsonResponse = await convertXmlToJSON.parseStringPromise(response);
//<StatusDesc>NO CASE FOUND FOR A111-111-10-011-1 DRIVER LICENSE NOT DATABASE</StatusDesc> not sure if this is good enough to ommit all with a similar statusDesc
console.dir(jsonResponse);
await DriverLicenseReport.query().insert({
driverLicenseId: dlRecord.id,
report: response,
reportJsonb: jsonResponse,
county: 'MIAMI-DADE'
})
} catch (error) {
// alert on these errors
console.error(error);
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,
},
// include number and some subscription ids?
body: 'Reports run',
};
}
export const subscription: APIGatewayProxyHandler = async (event, _context) => {
const subscriptionRequest: SubscriptionRequest = JSON.parse(event.body);
const {
emailAddressClient,
phoneNumberClient,
driverLicenseIdClient,
countyClient
} = subscriptionRequest;
if (typeof emailAddressClient !== 'string' || typeof driverLicenseIdClient !== "string" || typeof countyClient !== "string") {
return {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
statusCode: 400,
// move to http error handling
body: 'BAD REQUEST'
};
}
try {
console.dir(`starting validation`);
const emailAddress = validateEmail(emailAddressClient);
const phoneNumber = validatePhoneNumber(phoneNumberClient);
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
const existingDriverLicense = await DriverLicense.query().where('driverLicenseNumber', driverLicenseNumber).first()
if (existingDriverLicense) {
const existingSubscription = await Subscription.query().where({
emailAddress,
phoneNumber,
driverLicenseId: existingDriverLicense.id
}).first();
if (existingDriverLicense.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 support@drivefine.com if you belive this is an Error'
}),
};
}
await Subscription.query().insert({
emailAddress,
phoneNumber,
driverLicenseId: existingDriverLicense.id,
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'
}),
};
}
// DL isn't found, need to create before moving forward
const newDriverLicense = await DriverLicense.query().insert({
driverLicenseNumber,
county,
disabled: false
});
// TODO validate DL here or exit?
await Subscription.query().insert({
emailAddress,
phoneNumber,
driverLicenseId: newDriverLicense.id,
subscribedOn: new Date()
});
await sendEnrollmentConfirmation(phoneNumberClient, driverLicenseIdClient);
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
message: 'success'
}),
};
// user signed up, sending sms notification
} catch (error) {
console.error(error);
return {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
statusCode: 422,
body: JSON.stringify({
description: error.message
}),
};
}
};