forked from ThorntonTomasetti/HealthyReentry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
office_directors_email.js
352 lines (277 loc) · 12.4 KB
/
office_directors_email.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// heroku scheduler script for automated email to office directors
// heroku scheduler every friday
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectId;
var moment = require('moment');
moment().format();
const sgClient = require('@sendgrid/mail');
sgClient.setApiKey(process.env.SENDGRID_API_KEY);
var sender ="[email protected]"
var url = process.env.MONGO_URL;
const fs = require('fs');
var content = fs.readFileSync("./server/assets/email_templates/officeDirectorsReport.html").toString("utf-8");
const userCountByOffice = require("./server/util/officeHeadCount.js");
const directors = require("./server/util/officeDirectors.js");
function checkVaccinationStatus(user, vaccination) {
var vaccinationStatus = "No vaccination data recorded";
if (user.fullyVaccinated){
vaccinationStatus = "Fully Vaccinated";
}
else if (user.duringVacIncubation == true) {
vaccinationStatus = "Incubation Period(2wks)";
}
else if (vaccination && vaccination.count > 0){
vaccinationStatus = "Partially Vaccinated"
}
return vaccinationStatus;
}
//"Name,Email\r\n";
function nodeToCsv(node, vaccination) {
const statusDate = node.status? moment(node.status.date).format('MMMM DD YYYY') : "Not Available";
const vaccinationStatus = checkVaccinationStatus(node, vaccination);
// return `${node.name},${node.email}\r\n`;
if (vaccination) return `${node.name},${node.email},${statusDate},${vaccinationStatus}, ${node.PCRDate}\r\n`;
else return `${node.name},${node.email},${statusDate},${vaccinationStatus}, ${node.PCRDate} \r\n`;
}
let allUsers = [];
let officeCount = 0;
let finishedOfficeCount = 0;
MongoClient.connect(url, {
useUnifiedTopology: true
}).then(function (db) {
console.log("CONNECTED TO DB");
var today = new Date();
if (today.getDay() == 5) console.log("today is friday");
else {
console.log("today is not friday yet!")
db.close();
return;
}
getUsers(db).then(function () {
officeCount = Object.keys(directors).length;
Object.keys(directors).forEach((key, index) => {
// three attachment
// 1. employees who have signed up for the app,
// 2. employees who have signed up for the app but haven't reported their health status for more than 7 days,
// 3. the number of app users in your office with a health status of Red and/or Orange.
getOfficeUserVaccination(db, key).then(usersWithVacs => {
// 1. employees who have signed up for the app,
const usersbyOffice = allUsers.filter(u => u.location === key);
if(usersbyOffice.length === 0 ) return;
// let csvHeader = "Name,Email, \r\n";
let csvHeader = "Name,Email, Last reported status, Vaccination Status, Latest PCR Date\r\n";
let csv = csvHeader;
usersbyOffice.forEach((user) => {
const userWithVac = usersWithVacs.filter(uVac => String(uVac._id) == String(user._id))[0];
user.vaccination = userWithVac.vaccination; // COMBINE!
csv += nodeToCsv(user, userWithVac.vaccination);
})
let attachment = Buffer.from(csv).toString('base64');
// 2. employees who have signed up for the app but haven't reported their health status for more than 7 days,
var checkDate = new Date();
var pastDate = checkDate.getDate() - 7;
checkDate.setDate(pastDate);
// 3. the number of app users in your office with a health status of Red and/or Orange.
const usersStatusOrange = usersbyOffice.filter(u => u.status.status === 1);
const usersStatusRed = usersbyOffice.filter(u => u.status.status === 2);
let csv3 = "Office,Number of Orange,Number of Red,Total Signups in Office, Total Office Employee Count, Total Fully Vaccinated in Office, Percentage of Employees Fully Vaccinated, Total Partially Vaccinated, Total in Vaccine Incubation, Total No Vaccination Record\r\n";
var numberOfOrange = usersStatusOrange.length;
var numberOfRed = usersStatusRed.length;
var numberOfIncubation = usersbyOffice.filter(u => u.duringVacIncubation);
var numberOfPartialVac = usersbyOffice.filter(u => u.fullyVaccinated == false && u.duringVacIncubation == false && u.vaccination && u.vaccination.count > 0);
var numberOfNoVac = usersbyOffice.filter(u => !u.vaccination);
var total = usersbyOffice.length;
const employeeVaccinated = usersWithVacs.filter(u=>u.fullyVaccinated).length;
if (key === "New York") {
csv3 += `${"120 Broadway"},${numberOfOrange},${numberOfRed},${total}, ${userCountByOffice["New York - 120 Broadway"]}, ${employeeVaccinated}, ${String((employeeVaccinated/userCountByOffice["New York - 120 Broadway"]*100).toFixed(2)) + "%"}, ${numberOfPartialVac.length}, ${numberOfIncubation.length}, ${numberOfNoVac.length}\r\n`;
csv3 += `${"Downtown"},${''},${''},${''},${userCountByOffice["New York - Downtown"]},${''},${''}, ${''}, ${''}, ${''} \r\n`;
// csv3 += `${"Midtown"},${''},${''},${''},${''},${userCountByOffice["New York - Madison"]},${employeeInOffice2}, ${String((employeeInOffice/userCountByOffice["New York - Madison"]*100).toFixed(2)) + "%"},${''} \r\n`;
// csv3 += `${"120 Broadway"},${''},${''},${''},${''},${userCountByOffice["New York - 120 Broadway"]},${employeeInOffice3}, ${String((employeeInOffice/userCountByOffice["New York - 120 Broadway"]*100).toFixed(2)) + "%"}\r\n`;
}
else csv3 += `${key},${numberOfOrange},${numberOfRed},${total},${userCountByOffice[key]}, ${employeeVaccinated}, ${String((employeeVaccinated/userCountByOffice[key]*100).toFixed(2)) + "%"}, ${numberOfPartialVac.length}, ${numberOfIncubation.length}, ${numberOfNoVac.length}\r\n`;
let attachment3 = Buffer.from(csv3).toString('base64');
sendEmail(directors[key], key, attachment, attachment3);
})
.catch(e => {
console.log("error in getting vaccination info: ", key, e);
});
});
})
}).catch(err => {
db.close();
console.error("An error occurred reading the database.");
console.error(err);
});
function getUsers(client_db) {
return new Promise((resolve, reject) => {
let db = client_db.db();
let include = {
"_id": 1,
// "dateOfConsent": 1,
"name": 1,
"location": 1,
"fullyVaccinated": 1
}
let collection = db.collection('users');
let statusCollection = db.collection('status');
let wpCollection = db.collection('workpreferences');
collection.find({}, include).toArray(function (err, users) {
var counter = 0;
// getWorkPreferences(client_db).then(function(){
for (let u of users) {
statusCollection.find({
"user": u._id
})
.sort({
date: -1
})
.limit(1).toArray(function (error, st) {
u.status = st[0];
if (u.PCRTests && u.PCRTests.length > 0) {
wpCollection.find({
"user": u._id
})
.sort({
pcrTestDate: -1
}).limit(1).toArray(function(err, pcrTest) {
u.PCRDate = moment(pcrTest[0].pcrTestDate).format('MMMM Do YYYY');
allUsers.push(u);
isDone();
})
}
else {
u.PCRDate = "Not Available";
allUsers.push(u);
isDone();
}
});
}
// })
function isDone() {
counter += 1;
if (users.length === counter) {
// client_db.close();
resolve(true);
}
}
});
});
}
function getOfficeUserVaccination(client_db, curOffice) {
return new Promise((resolve, reject) => {
var officeToSearch = curOffice;
if (curOffice == "New York - 120 Broadway") officeToSearch = "New York";
else if (curOffice == "New York - Downtown" || curOffice == "New York - Madison") resolve([]);
let db = client_db.db();
let userCollection = db.collection('users');
let vaccinationCollection = db.collection('vaccinations');
let includeUser = {
"_id": 1,
"email": 1,
"name":1
}
// Search all users in this office
userCollection
.find({location: officeToSearch}, includeUser)
.toArray( function (err, users) {
if (err) {
console.log("vaccination search err", err);
resolve([]);
}
if (!users || users.length == 0) resolve([]);
let promises = [];
if (users && Array.isArray(users)) {
users.forEach(u => {
let curP = vaccinationCollection.find({
"user": u._id
})
.sort({
date: -1
}).toArray();
promises.push(curP);
});
Promise.all(promises).then((usersWithVacs) => {
usersWithVacs.forEach((vaccine, index) => {
var curVac = {
manufacturer:null,
lastDate: null,
count: 0
}
if (!vaccine || vaccine.length == 0) return;
const uniqueManufacturer = [];
vaccine.forEach(v => {
if (!uniqueManufacturer.includes(v.manufacturer)) uniqueManufacturer.push(v.manufacturer);
})
curVac.count = vaccine.length;
if (vaccine.length == 1) {
curVac.manufacturer = vaccine[0].manufacturer
}
else {
curVac.manufacturer = uniqueManufacturer.join("; ");
}
curVac.lastDate = vaccine[0].date;
users[index].vaccination = curVac;
})
finishedOfficeCount += 1;
if (finishedOfficeCount == officeCount) {
console.log("closing db");
client_db.close();
}
resolve(users)
});
}
else {
resolve([]);
}
});
})
}
function sendEmail(emails, location, attachment, attachment3) {
if (emails == null) return;
var toEmails = Array.isArray(emails)? emails : [emails];
const mailOptions = {
// to: toEmail,
// to: "[email protected]",
from: sender,
bcc: '[email protected]',
subject: "Healthy Reentry – Weekly Report for " + location,
html: content
};
if (attachment) {
mailOptions.attachments = [{
"content": attachment,
"filename": "Employees Who Have Signed up.csv",
"type": "text/csv"
},
// {
// "content": attachment2,
// "filename": "Employees Who Have Not Updated in 7 Days.csv",
// "type": "text/csv"
// },
{
"content": attachment3,
"filename": "Office Breakdown.csv",
"type": "text/csv"
}
]
}
const messages = [];
toEmails.forEach(function(toEmail){
var curOption = JSON.parse(JSON.stringify(mailOptions))
curOption["to"] = toEmail;
messages.push(curOption);
})
sgClient.send(messages).then(() => {
console.log('emails sent successfully to: ', toEmails, location);
}).catch(error => {
console.log(error);
});
// sgClient.send(messages, function (err) {
// console.log("err?", err)
// if (err)
// return;
// else
// console.log('sent');
//
// });
}