-
Notifications
You must be signed in to change notification settings - Fork 0
/
Appointments.gs
387 lines (330 loc) · 14.2 KB
/
Appointments.gs
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
let boothappointment_calendarid = "[email protected]";
// let vanappointment_calendarid = "[email protected]";
var appointmentsSheet = SpreadsheetApp.openById("1DBZnKAFiB8MJy_e5h-M83ZauUhJeXBmSjAGBKq6owas").getActiveSheet();
class Appointment {
constructor(type, dr, patientName, patientPhone, event, meetUrl) {
this.type = type;
this.doctor = dr; // class Doctor
this.patient = patientName
this.patientPhone = patientPhone;
this.event = event; // class CalendarEvent
this.url = meetUrl;
}
getTitle() {
return this.event.getTitle();
}
getDate() {
return this.event.getStartTime();
}
htmlInfo() {
// turn Appointment object into a formatted HTML string to include in email
var out = this.getTitle().substring(0, this.getTitle().indexOf(' - ')) + "<BR>";
out += weekday[this.getDate().getDay()] + ", " + month[this.getDate().getMonth()] + " " + this.getDate().getDate();
out += " at <B>" + this.getDate().toTimeString() + "</B> " + "(" + this.getDate().toLocaleTimeString() + " Texas time).<BR>";
out += "Patient: " + this.patient + "<BR>";
out += (this.patientPhone == null) ? "" : "Patient Phone #: " + this.patientPhone + "<BR>";
out += "Link to join: <A target=_blank href=\"" + this.url + "\">" + this.url + "</A><BR>";
return out;
}
txtInfo() {
// turn Appointment object into a plaintext string to include in email
var out = this.getTitle().substring(0, this.getTitle().indexOf(' - ')) + "\n";
out += weekday[this.getDate().getDay()] + ", " + month[this.getDate().getMonth()] + " " + this.getDate().getDate();
out += " at " + this.getDate().toTimeString() + " (" + this.getDate().toLocaleTimeString() + " Texas time).\n";
out += "Patient: " + this.patient + "\n";
out += (this.patientPhone == null) ? "" : "Patient Phone #: " + this.patientPhone + "\n";
out += "Link to join: " + this.url + "\n";
return out;
}
}
function inDrList(drEmail, drsList) {
// Checks if drEmail is already in drsList
var out = false;
drsList.forEach(function(dr) {
if (dr.email == drEmail) {
out = true;
}
});
return out;
}
function updateAppointmentsForDay() {
// Runs once automatically each day. Collects all Setmore-generated calendar events for that day,
// and creates a better calendar event (with Meet link) to share with doctors.
var today = new Date();
today.setTime(today.getTime() + (1*60*60*1000)); // multiply second term by num hours to add when testing
var appointmentsList = [];
var doctorsList = [];
// Booth appointments
var boothCal = CalendarApp.getCalendarById(boothappointment_calendarid);
var boothAppointmentsForDay = boothCal.getEventsForDay(today);
// Use ID and label to attach existing Meet call to a calendar event
boothMeetingUrl = getBoothMeetingUrl();
boothMeetingId = boothMeetingUrl.substring(24);
boothMeetingLabel = boothMeetingUrl.substring(8);
var count = 0;
boothAppointmentsForDay.filter(a => a.getTitle().search("For Telemedicine Appointment") > 0).forEach(function(appointment) {
// Filter out invalid calendar events
// appointment = a calendar event (generated by Setmore) representing a particular appointment
var appointmentTitle = appointment.getTitle();
var dr = getDoctorFromEvent(appointment); // returns Doctor object
var patient = getPatientNameFromEvent(appointment);
var patientPhone = getPatientPhoneFromEvent(appointment);
// If the doctor is an ENDEAVR doctor?
// chooseDoctor(appointmentTitle);
// var rddFolder = DriveApp.getFileById(doctor.rddId);
var newStart = new Date(appointment.getStartTime());
var newEnd = new Date(appointment.getEndTime());
var desc = appointment.getDescription();
var newDesc = 'Scheduled Telemedicine Visit with ENDEAVR Patient.\n\nAPPOINTMENT DETAILS\n'
+ desc.substring(desc.indexOf('PROVIDER:')).replace('\n\n\n\n\n\n\n', '\n\n');
// get rid of extra lines in the middle of the Setmore generated description
// build calendar event
var payload = {
"summary": "ENDEAVR Telemedicine Booth Appointment - " + dr.getName(),
"description": newDesc,
"sendUpdates": "all",
"calendarId": boothappointment_calendarid,
"end": {
"dateTime": newEnd.toJSON(),
"timeZone": "America/Chicago"
},
"start": {
"dateTime": newStart.toJSON(),
"timeZone": "America/Chicago" //Los_Angeles, New_York
},
"conferenceData": {
"conferenceId": boothMeetingId,
"conferenceSolution": {
"key": {
"type": "hangoutsMeet",
"name": appointmentTitle
}
},
"entryPoints": [ // An array of objects. It accepts one video type.
{
"entryPointType": "video",
"label": boothMeetingLabel,
"uri": boothMeetingUrl
}],
},
// If the doctor is an ENDEAVR doctor?
// "attachments":[
// {fileId: doctor.rddId, fileUrl: rddFolder.getUrl(), mimeType: rddFolder.getMimeType(), title: rddFolder.getName()}
// ]
"attendees": [{"email": dr.email}]
}
const args = {"conferenceDataVersion": 1, supportsAttachments: true };
try {
var response = Calendar.Events.insert(payload, boothappointment_calendarid, args)
console.log(`Success! ${response}`)
appointmentsList.push(new Appointment("Booth", dr, patient, patientPhone,boothCal.getEventById(response.id), boothMeetingUrl));
if (!inDrList(dr.email, doctorsList)) {
// Logger.log("Pushing " + dr.name + " to doctorsList");
doctorsList.push(dr);
} else {
// Logger.log("Not pushing " + dr.email + " to doctorsList");
}
// appointment.deleteEvent();
} catch(e) {
console.log(`Oh no: ${e.message}`)
}
count++;
})
// console.log(count + " booth appointment events updated.")
// Van appointments (INCOMPLETE)
/* var vanCal = CalendarApp.getCalendarById(vanappointment_calendarid);
var vanAppointmentsForDay = vanCal.getEventsForDay(today);
count = 0;
vanAppointmentsForDay.forEach(function(appointment) {
var appointmentTitle = appointment.getTitle();
var guests = appointment.getGuestList();
var drGuest;
guests.forEach(function(guest) { // Doctor = calendar guest that isn't the calendar ID
if (guest.getEmail() != vanappointment_calendarid && guest.getEmail() != endeavrPatient) {
drGuest = guest;
}
})
var dr = new Doctor(getNameFromTitle(appointmentTitle), drGuest.getEmail());
var requestId = today + (count++); // used for van appointments
var newStart = new Date(appointment.getStartTime());
// newStart.setTime(newStart.getTime() + (60*60*1000));
var newEnd = new Date(appointment.getEndTime());
// newEnd.setTime(newEnd.getTime() + (60*60*1000));
var payload = {
"summary": "ENDEAVRide Telemedicine Van Appointment - " + dr.getName(),
"description": 'Scheduled Telemedicine Visit with ENDEAVRide Patient.\n\n'
+ appointment.getDescription(),
"sendUpdates": "none",
"calendarId": vanappointment_calendarid,
"end": {
"dateTime": newEnd.toJSON(),
"timeZone": "America/Chicago"
},
"start": {
"dateTime": newStart.toJSON(),
"timeZone": "America/Chicago" //Los_Angeles, New_York
},
"conferenceData": {
"createRequest": {
"conferenceSolutionKey": {
"type": "hangoutsMeet",
"name": appointmentTitle
},
"requestId": "req" + requestId //this needs to be unique on every request!
}
},
// "conferenceDataVersion": 1,
// "attachments":[
// {fileId: doctor.rddId, fileUrl: rddFolder.getUrl(), mimeType: rddFolder.getMimeType(), title: rddFolder.getName()}
// ]
"attendees": [{"email": dr.email},{"email": endeavrPatient}]
}
const args = {"conferenceDataVersion": 1, supportsAttachments: true };
try {
var response = Calendar.Events.insert(payload, vanappointment_calendarid, args)
console.log(`Success! ${response}`)
appointment.deleteEvent();
CalendarApp.getCalendarById('primary').getEventById(appointment.getId()).deleteEvent();
appointmentsList.push(new Appointment("Van", dr, vanCal.getEventById(response.id), response.conferenceData.entryPoints[0].uri));
if (!inDrList(dr.email, doctorsList)) {
Logger.log("Pushing " + dr.getName() + " to doctorsList");
doctorsList.push(dr);
}
} catch(e) {
console.log(`Oh no: ${e.message}`)
}
count++;
})
// console.log(count + " van appointment events updated.")
*/
console.log(appointmentsList.length + " appointments for today");
sendAppointmentEmails(doctorsList, appointmentsList);
addAppointmentsToSheet(appointmentsList);
}
function addAppointmentsToSheet(appointments) {
// Takes an array of Appointment objects and adds them to a Google sheet to log information
var n = appointments.length;
if (n == 0) return;
var cols = 7;
appointmentsSheet.insertRowsAfter(1, n);
var values = [];
appointments.forEach(function(appointment) {
values.unshift([appointment.event.getStartTime(), appointment.type, appointment.doctor.name, appointment.doctor.email,
appointment.patient, (appointment.patientPhone ? appointment.patientPhone : ""), appointment.url]);
})
var dest = appointmentsSheet.getRange(2, 1, n, cols);
dest.setValues(values);
console.log("Added " + n + " appointments to spreadsheet");
}
function sendAppointmentEmails(doctors, appointments) {
// Takes an array of Appointments and an array of Doctors (generated by updateAppointmentsForDay() function)
// and sends ONE email to each doctor in "doctors" containing all of THEIR appointments.
// This whole process could be improved with a better data structure but idk JS data structures.
var blob = UrlFetchApp.fetch("https://i.postimg.cc/m2bXVsCY/ENDEAVR-main-logo.png").getBlob();
var d = new Date().toLocaleDateString();
var i = 0;
doctors.forEach(function(doctor) {
var htmlbody = createAppointmentHTMLBody(doctor, appointments);
// Logger.log("Sending appointment email to:\n" + doctor.email);
GmailApp.sendEmail(doctor.email, "ENDEAVR Telemedicine Appointments for " + d + " (PHI Enclosed)",
createAppointmentTXTBody(doctor, appointments),
{htmlBody: htmlbody, inlineImages: {image: blob}, name:'ENDEAVR Institute', bcc:boothStaffGroup}
);
i++;
})
console.log(i + " Appointment emails sent to doctor");
}
function createAppointmentHTMLBody(doctor, appointments) {
// Creates the formatted HTML for the email sent to doctors with appointments
var output = "<HTML><BODY><P style=\"font-family:'Times New Roman';font-size:18px\">"
+ "Hello " + doctor.getName() + ",<BR><BR>"
+ "Here is a list of all your ENDEAVR appointments for today:<BR><BR>"
+ getHTMLAppointmentsForDoctor(doctor, appointments)
+ "If you run into any problems, please call 1-844-ENDEAVR (363-3287).<BR><BR>"
+ htmlEmailSignature + "</P></BODY></HTML>";
return output;
}
function createAppointmentTXTBody(doctor, appointments) {
// Creates plaintext for the email sent to doctors with appointments.
var output = "Hello " + doctor.getName() + ",\n\n"
+ "Here is a list of all your ENDEAVR appointments for today:\n\n"
+ getTXTAppointmentsForDoctor(doctor, appointments)
+ "If you run into any problems, please call 1-844-ENDEAVR (363-3287).\n\n"
+ "Thank you for your service!\nENDEAVR Telemedicine Team\n\n";
return output;
}
function getHTMLAppointmentsForDoctor(dr, appointments) {
// Given a particular doctor, find all the appointments in the appointmentsList
// that correspond to them and generate formatted text to include in the email.
var out = "";
appointments.forEach(function(appointment) {
if (appointment.doctor.email == dr.email) {
out += appointment.htmlInfo() + "<BR>";
}
})
return out;
}
function getTXTAppointmentsForDoctor(dr, appointments) {
// Given a particular doctor, find all the appointments in the appointmentsList
// that correspond to them and generate plaintext to include in the email.
var out = "";
appointments.forEach(function(appointment) {
if (appointment.doctor.email == dr.email) {
out += appointment.txtInfo() + "\n";
}
})
return out;
}
function getPatientNameFromEvent(event) {
// Using the event description, find the patient's name to include in the Appointment object
var desc = event.getDescription();
var patient;
if (desc.search("Patient Phone #: ") == -1)
patient = desc.substring(desc.indexOf('Patient Name: ')+14);
else
patient = desc.substring(desc.indexOf('Patient Name: ')+14, desc.indexOf('Patient Phone #: ')-1);
// Logger.log('Patient = ' + patient);
return patient;
}
function getPatientPhoneFromEvent(event) {
// Using the event description, find the patient's phone number (if applicable) to include
// in the Appointment object
var desc = event.getDescription();
var patientNum;
if (desc.search("Patient Phone #: ") == -1) {
// Logger.log('Patient Phone not provided');
return null;
}
patientNum = desc.substring(desc.indexOf('Patient Phone #: ')+17).trim();
// Logger.log('Patient Phone = ' + patientNum);
return patientNum;
}
function getDoctorFromEvent(event) {
// Find the doctor associated with an appointment event to include in the Appointment object
var desc = event.getDescription();
var email = desc.substring(desc.indexOf('EMAIL: ')+7, desc.indexOf('MOBILE: ')-1).trim();
var name = event.getTitle().substring(0, event.getTitle().indexOf('For Telemedicine Appointment')-1).trim();
console.log(name + '\n' + email);
return new Doctor(name, email);
}
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var month=new Array(12);
month[0]="January";
month[1]="February";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="August";
month[8]="September";
month[9]="October";
month[10]="November";
month[11]="December";