-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode.js
More file actions
738 lines (632 loc) · 24.3 KB
/
Copy pathCode.js
File metadata and controls
738 lines (632 loc) · 24.3 KB
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
/**
* LONGWApps Leave Alert System using OrangeHRM + Google Apps Script
*/
const BASE_URL = 'https://www.longwapps.com/hrm/web';
/**
* Manual Leave Reminder - Run this manually
* Uses date from MANUAL_REMINDER_DATE in Config.js
*/
function sendManualLeaveReminder() {
if (typeof MANUAL_REMINDER_DATE === 'undefined' || !MANUAL_REMINDER_DATE) {
Logger.log('Please set MANUAL_REMINDER_DATE in Config.js (format: yyyy-MM-dd)');
return;
}
Logger.log('Manual Leave Reminder trigger: ' + MANUAL_REMINDER_DATE);
sendLeaveReminder(MANUAL_REMINDER_DATE);
}
/**
* Manual Leave Notification - Run this manually
* Uses date from MANUAL_NOTIFICATION_DATE in Config.js
*/
function sendManualLeaveNotification() {
if (typeof MANUAL_NOTIFICATION_DATE === 'undefined' || !MANUAL_NOTIFICATION_DATE) {
Logger.log('Please set MANUAL_NOTIFICATION_DATE in Config.js (format: yyyy-MM-dd)');
return;
}
Logger.log('Manual Leave Notification trigger: ' + MANUAL_NOTIFICATION_DATE);
sendLeaveNotification(MANUAL_NOTIFICATION_DATE, [2, 3]);
}
/**
* System Test - validates configuration, credentials, and authentication
*/
function testSystem() {
Logger.log('===== LEAVE ALERT SYSTEM TEST =====');
Logger.log('');
let allTestsPassed = true;
// Test 1: Script Properties (Credentials)
Logger.log('TEST 1: Script Properties');
const username = PropertiesService.getScriptProperties().getProperty('HRM_USERNAME');
const password = PropertiesService.getScriptProperties().getProperty('HRM_PASSWORD');
if (username && password) {
Logger.log('✓ HRM_USERNAME: Set');
Logger.log('✓ HRM_PASSWORD: Set');
} else {
Logger.log('✗ FAILED: Missing credentials in Script Properties');
if (!username) Logger.log(' - HRM_USERNAME not set');
if (!password) Logger.log(' - HRM_PASSWORD not set');
allTestsPassed = false;
}
Logger.log('');
// Test 2: Configuration Data
Logger.log('TEST 2: Configuration Data');
Logger.log('Total Employees: ' + Object.keys(EMPLOYEES).length);
Logger.log('Total Teams: ' + TEAMS.length);
TEAMS.forEach(function(team) {
Logger.log(' Team: ' + team.teamName + ' (' + team.members.length + ' members)');
});
Logger.log('');
// Test 3: Configuration Validation
Logger.log('TEST 3: Configuration Validation');
let configErrors = false;
TEAMS.forEach(function(team) {
team.members.forEach(function(personId) {
if (!EMPLOYEES[personId]) {
Logger.log('✗ ERROR: Employee ID "' + personId + '" in team "' + team.teamName + '" not found in EMPLOYEES');
configErrors = true;
}
});
});
if (!configErrors) {
Logger.log('✓ All team members exist in EMPLOYEES');
} else {
allTestsPassed = false;
}
Logger.log('');
// Test 4: Authentication
if (username && password) {
Logger.log('TEST 4: Authentication');
const sessionCookie = authenticateUser(username, password);
if (sessionCookie) {
Logger.log('✓ Authentication successful');
} else {
Logger.log('✗ FAILED: Authentication failed');
allTestsPassed = false;
}
Logger.log('');
}
// Final Result
if (allTestsPassed) {
Logger.log('==== ✓ ALL TESTS PASSED ====');
} else {
Logger.log('===== ✗ SOME TESTS FAILED =====');
}
}
/**
* Daily Leave Reminder - Sends reminder for today's leaves
*/
function sendDailyLeaveReminder() {
const today = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd');
sendLeaveReminder(today);
}
/**
* Daily Leave Notification - Sends notification for next business day's leaves
*/
function sendDailyLeaveNotification() {
const today = new Date();
const dayOfWeek = today.getDay();
// Skip if weekend - trigger should only run Mon-Fri
if (dayOfWeek === 0 || dayOfWeek === 6) {
Logger.log('Skipping notification - Today is weekend');
return;
}
// Calculate next business day
const daysToAdd = dayOfWeek === 5 ? 3 : 1; // Friday → Monday (3 days), else tomorrow (1 day)
const nextBusinessDay = new Date(today);
nextBusinessDay.setDate(today.getDate() + daysToAdd);
const nextBusinessDayString = Utilities.formatDate(nextBusinessDay, Session.getScriptTimeZone(), 'yyyy-MM-dd');
sendLeaveNotification(nextBusinessDayString, [2]);
}
/**
* Authenticate user and return session cookie
* Handles complete authentication flow: token fetch, login, and session validation
*/
function authenticateUser(username, password) {
try {
// Helper function to extract cookie from response headers
function extractCookie(headers) {
if (headers['Set-Cookie'] || headers['set-cookie']) {
const setCookie = headers['Set-Cookie'] || headers['set-cookie'];
const cookieMatch = setCookie.match(/orangehrm=([^;]+)/);
if (cookieMatch && cookieMatch[1]) {
return cookieMatch[1];
}
}
return null;
}
// Get login token and initial cookie
const loginPageResponse = UrlFetchApp.fetch(BASE_URL + '/auth/login', {
method: 'get',
followRedirects: false,
muteHttpExceptions: true
});
const html = loginPageResponse.getContentText();
const initialCookie = extractCookie(loginPageResponse.getAllHeaders());
const tokenMatch = html.match(/:token=""([^"]+)""/);
const token = tokenMatch ? tokenMatch[1] : null;
if (!token) {
Logger.log('Failed to get login token');
return null;
}
// Login and validate credentials
const loginOptions = {
method: 'post',
payload: {
'_token': token,
'username': username,
'password': password
},
followRedirects: false,
muteHttpExceptions: true
};
if (initialCookie) {
loginOptions.headers = { 'Cookie': 'orangehrm=' + initialCookie };
}
const loginResponse = UrlFetchApp.fetch(BASE_URL + '/auth/validate', loginOptions);
if (loginResponse.getResponseCode() !== 302) {
Logger.log('Login validation failed');
return null;
}
// Extract session cookie from login response
let sessionCookie = extractCookie(loginResponse.getAllHeaders());
if (!sessionCookie) {
Logger.log('Failed to get session cookie from login');
return null;
}
// Access dashboard to finalize session
const dashboardResponse = UrlFetchApp.fetch(BASE_URL + '/dashboard/index', {
method: 'get',
headers: {
'Cookie': 'orangehrm=' + sessionCookie,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
},
followRedirects: true,
muteHttpExceptions: true
});
if (dashboardResponse.getResponseCode() !== 200) {
Logger.log('Dashboard access failed');
return null;
}
// Update session cookie if refreshed
const updatedCookie = extractCookie(dashboardResponse.getAllHeaders());
if (updatedCookie) {
sessionCookie = updatedCookie;
}
Logger.log('Authentication successful');
return sessionCookie;
} catch (error) {
const errorMsg = 'Authentication error: ' + error.toString();
Logger.log(errorMsg);
notifyAdmin(errorMsg, 'authenticateUser');
return null;
}
}
/**
* Core reminder function - Send leave reminder for a specific date
*/
function sendLeaveReminder(dateString) {
try {
Logger.log('Starting leave reminder for: ' + dateString);
const username = PropertiesService.getScriptProperties().getProperty('HRM_USERNAME');
const password = PropertiesService.getScriptProperties().getProperty('HRM_PASSWORD');
if (!username || !password) {
const error = 'Username or password not found in Script Properties';
Logger.log('ERROR: ' + error);
notifyAdmin(error, 'sendLeaveReminder');
return;
}
// Authenticate and get session cookie
const sessionCookie = authenticateUser(username, password);
if (!sessionCookie) {
const error = 'Authentication failed - Unable to get session cookie';
Logger.log('ERROR: ' + error);
notifyAdmin(error, 'sendLeaveReminder');
return;
}
// Fetch leave data for the specific date
const leaveData = fetchLeaveRequests(sessionCookie, {
fromDate: dateString,
toDate: dateString,
statuses: [2, 3] // 2 = Scheduled, 3 = Taken
});
let leavesForDate = [];
if (leaveData && leaveData.data) {
// Filter leaves that actually fall on the target date
leavesForDate = leaveData.data.filter(function(leave) {
const fromDate = leave.dates.fromDate;
const toDate = leave.dates.toDate || fromDate;
return dateString >= fromDate && dateString <= toDate;
});
} else {
Logger.log('ERROR: Failed to fetch leave data');
}
// Add manual leaves
const manualLeaves = processManualLeaves(dateString, false);
manualLeaves.forEach(function(leave) {
leavesForDate.push(leave);
});
if (leavesForDate.length === 0) {
Logger.log('No employees on leave on ' + dateString);
return;
}
dispatchLeaveEmails(leavesForDate, dateString, 'reminder');
Logger.log('Success! Reminder emails sent to team members about ' + leavesForDate.length + ' employee(s) on leave');
} catch (error) {
const errorMsg = 'Error in sendLeaveReminder: ' + error.toString();
Logger.log('ERROR: ' + errorMsg);
notifyAdmin(errorMsg, 'sendLeaveReminder');
}
}
/**
* Core notification function - Send leave notification for leaves starting on a specific date
*/
function sendLeaveNotification(startDate, statuses) {
try {
statuses = statuses || [2];
Logger.log('Starting Leave Notification for leaves starting on: ' + startDate);
const username = PropertiesService.getScriptProperties().getProperty('HRM_USERNAME');
const password = PropertiesService.getScriptProperties().getProperty('HRM_PASSWORD');
if (!username || !password) {
const error = 'Username or password not found in Script Properties';
Logger.log('ERROR: ' + error);
notifyAdmin(error, 'sendLeaveNotification');
return;
}
// Authenticate and get session cookie
const sessionCookie = authenticateUser(username, password);
if (!sessionCookie) {
const error = 'Authentication failed - Unable to get session cookie';
Logger.log('ERROR: ' + error);
notifyAdmin(error, 'sendLeaveNotification');
return;
}
// Fetch all approved leaves starting from the specified date
const leaveData = fetchLeaveRequests(sessionCookie, {
fromDate: startDate,
toDate: startDate,
statuses: statuses
});
let leavesStartingOnDate = [];
if (leaveData && leaveData.data) {
// Filter to only include leaves that START on the target date
leavesStartingOnDate = leaveData.data.filter(function(leave) {
return leave.dates.fromDate === startDate;
});
} else {
Logger.log('ERROR: Failed to fetch leave data');
}
// Add manual leaves that START on this date
const manualLeaves = processManualLeaves(startDate, true);
manualLeaves.forEach(function(leave) {
leavesStartingOnDate.push(leave);
});
if (leavesStartingOnDate.length === 0) {
Logger.log('No approved leaves starting on ' + startDate);
return;
}
dispatchLeaveEmails(leavesStartingOnDate, startDate, 'notification');
Logger.log('Success! Notification emails sent to team members about ' + leavesStartingOnDate.length + ' upcoming leave(s)');
} catch (error) {
const errorMsg = 'Error in sendLeaveNotification: ' + error.toString();
Logger.log('ERROR: ' + errorMsg);
notifyAdmin(errorMsg, 'sendLeaveNotification');
}
}
/**
* Fetch leave requests from full API
* @param {string} sessionCookie - Authenticated session cookie
* @param {Object} options - Filter options
* @param {string} options.fromDate - Start date (yyyy-MM-dd)
* @param {string} options.toDate - End date (yyyy-MM-dd)
* @param {Array<number>} options.statuses - Leave statuses [2=Scheduled, 3=Taken]
* @param {number} options.leaveTypeId - Optional: 1=Annual, 2=Casual, 3=Maternity (omit to get all types)
* @param {number} options.limit - Optional: Default 50
* @param {number} options.offset - Optional: Default 0
*/
function fetchLeaveRequests(sessionCookie, options) {
try {
options = options || {};
const fromDate = options.fromDate || Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd');
const toDate = options.toDate || fromDate;
const statuses = options.statuses || [2, 3];
const limit = options.limit ?? 50;
const offset = options.offset ?? 0;
Logger.log('Fetching leave requests from ' + fromDate + ' to ' + toDate);
let apiUrl = BASE_URL + '/api/v2/leave/employees/leave-requests'
+ '?limit=' + limit
+ '&offset=' + offset
+ '&fromDate=' + fromDate
+ '&toDate=' + toDate
+ '&includeEmployees=onlyCurrent';
statuses.forEach(s => apiUrl += '&statuses[]=' + s);
if (options.leaveTypeId != null) {
apiUrl += '&leaveTypeId=' + options.leaveTypeId;
}
Logger.log('API URL: ' + apiUrl);
const apiResponse = UrlFetchApp.fetch(apiUrl, {
method: 'get',
headers: {
'Cookie': 'orangehrm=' + sessionCookie,
'Accept': 'application/json',
'Cache-Control': 'no-store, no-cache, must-revalidate',
'Referer': BASE_URL + '/leave/viewLeaveList',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
},
muteHttpExceptions: true
});
if (apiResponse.getResponseCode() !== 200) {
Logger.log('API call failed: ' + apiResponse.getContentText());
return null;
}
Logger.log('Leave requests fetched successfully');
return JSON.parse(apiResponse.getContentText());
} catch (error) {
const errorMsg = 'Error fetching leave requests: ' + error.toString();
Logger.log(errorMsg);
notifyAdmin(errorMsg, 'fetchLeaveRequests');
return null;
}
}
/**
* Process manual leaves for a specific date and return in OrangeHRM format
* @param {string} dateString - Date in yyyy-MM-dd format
* @param {boolean} startDateOnly - If true, only return leaves that START on this date
* @return {Array} Array of formatted leave objects ready to merge with OrangeHRM data
*/
function processManualLeaves(dateString, startDateOnly) {
// Check if manual leaves exist
if (typeof MANUAL_LEAVES === 'undefined' || !MANUAL_LEAVES || MANUAL_LEAVES.length === 0) {
return [];
}
const formattedLeaves = [];
let processedCount = 0;
MANUAL_LEAVES.forEach(function(leave) {
// Filter by date
const isInRange = dateString >= leave.fromDate && dateString <= leave.toDate;
const startsOnDate = leave.fromDate === dateString;
// Skip if doesn't match filter criteria
if (startDateOnly && !startsOnDate) return;
if (!startDateOnly && !isInRange) return;
// Get employee info
const employeeInfo = EMPLOYEES[leave.employeeId];
if (!employeeInfo) {
Logger.log('Warning: Manual leave for unknown employee: ' + leave.employeeId);
return;
}
// Calculate number of days
const fromDate = new Date(leave.fromDate + 'T00:00:00');
const toDate = new Date(leave.toDate + 'T00:00:00');
const daysDiff = Math.round((toDate - fromDate) / (1000 * 60 * 60 * 24)) + 1;
// Determine duration type and days (default to 'full' if not specified)
const leaveType = leave.type || 'full';
let durationType = { type: 'full_day' };
let noOfDays = daysDiff;
if (leaveType === 'morning') {
durationType = { type: 'half_day_morning' };
noOfDays = 0.5;
} else if (leaveType === 'afternoon') {
durationType = { type: 'half_day_afternoon' };
noOfDays = 0.5;
} else if (leaveType === 'time' && leave.startTime && leave.endTime) {
durationType = { type: 'specify_time' };
noOfDays = 0.5;
}
// Build formatted leave object
formattedLeaves.push({
employee: {
employeeId: leave.employeeId,
firstName: employeeInfo.name.split(' ')[0],
middleName: '',
lastName: employeeInfo.name.split(' ').slice(1).join(' ') || ''
},
leaveType: {
name: 'Leave'
},
dates: {
fromDate: leave.fromDate,
toDate: leave.toDate,
durationType: durationType,
startTime: leave.startTime || null,
endTime: leave.endTime || null
},
noOfDays: noOfDays,
_isManual: true
});
processedCount++;
});
if (processedCount > 0) {
Logger.log('Processed ' + processedCount + ' manual leave(s) for ' + dateString);
}
return formattedLeaves;
}
/**
* Process leave data and send emails to relevant team members
* @param {Array} leaves - Leave data
* @param {string} dateString - Reference date
* @param {string} mode - 'reminder' or 'notification'
*/
function dispatchLeaveEmails(leaves, dateString, mode) {
const emailsToSend = {};
const isReminder = mode === 'reminder';
// Get list of people on leave
const employeesOnLeave = leaves.map(function(leave) {
return leave.employee.employeeId;
});
Logger.log(isReminder ? 'Employees on leave: ' + employeesOnLeave.join(', ') : 'Employees with upcoming leave: ' + employeesOnLeave.join(', '));
// Process each employee
leaves.forEach(function(leave) {
const employeeId = leave.employee.employeeId;
const employeeName = EMPLOYEES[employeeId] ? EMPLOYEES[employeeId].name : employeeId;
// Find teams this employee belongs to
const employeeTeams = [];
TEAMS.forEach(function(team) {
if (team.members.indexOf(employeeId) !== -1) {
employeeTeams.push(team.teamName);
// Notify team members based on mode
team.members.forEach(function(memberId) {
// Reminder: exclude ALL people on leave | Notification: exclude only THIS person
const shouldExclude = isReminder
? employeesOnLeave.indexOf(memberId) !== -1
: memberId === employeeId;
if (!shouldExclude) {
const memberInfo = EMPLOYEES[memberId];
if (memberInfo && memberInfo.email) {
if (!emailsToSend[memberInfo.email]) {
emailsToSend[memberInfo.email] = [];
}
const alreadyAdded = emailsToSend[memberInfo.email].some(function(item) {
return item.employee.employeeId === employeeId;
});
if (!alreadyAdded) {
emailsToSend[memberInfo.email].push(leave);
}
}
}
});
}
});
if (employeeTeams.length > 0) {
Logger.log('Processing: ' + employeeName + ' [' + employeeId + '] (Teams: ' + employeeTeams.join(', ') + ')');
}
});
// Send emails
let emailCount = 0;
for (let email in emailsToSend) {
sendLeaveEmail(email, emailsToSend[email], dateString, mode);
emailCount++;
Logger.log('Sent to: ' + email + ' (' + emailsToSend[email].length + (isReminder ? ' on leave' : ' upcoming leave(s)') + ')');
}
Logger.log('Total ' + mode + ' emails sent: ' + emailCount);
}
/**
* Build and send leave email with both HTML and plain text versions
* @param {string} toEmail - Recipient email
* @param {Array} leaves - Array of leave objects
* @param {string} dateString - Reference date
* @param {string} mode - 'reminder' for today's leaves, 'notification' for upcoming leaves
*/
function sendLeaveEmail(toEmail, leaves, dateString, mode) {
mode = mode || 'reminder';
const isNotification = mode === 'notification';
// Format date
const dateObj = new Date(dateString + 'T00:00:00');
const formattedDate = Utilities.formatDate(
dateObj,
Session.getScriptTimeZone(),
'EEEE, MMMM dd, yyyy'
);
// Subject
const subject = isNotification
? 'Notification: Upcoming Team Members on Leave'
: 'Reminder: Team Members on Leave Today – ' + formattedDate;
// Prepare leave data
const formattedLeaves = leaves.map(function (leave) {
const employeeId = leave.employee.employeeId;
const name =
(EMPLOYEES[employeeId] && EMPLOYEES[employeeId].name) ||
leave.employee.firstName + ' ' +
(leave.employee.middleName ? leave.employee.middleName + ' ' : '') +
leave.employee.lastName;
let duration = null;
const from = leave.dates.fromDate;
const to = leave.dates.toDate;
const type = leave.dates.durationType && leave.dates.durationType.type;
if (isNotification) {
if (to && from !== to) {
const fromDateObj = new Date(from + 'T00:00:00');
const toDateObj = new Date(to + 'T00:00:00');
const formattedFrom = Utilities.formatDate(fromDateObj, Session.getScriptTimeZone(), 'MMM dd');
const formattedTo = Utilities.formatDate(toDateObj, Session.getScriptTimeZone(), 'MMM dd');
duration = leave.noOfDays + ' day(s): ' + formattedFrom + ' - ' + formattedTo;
} else if (type === 'half_day_morning') {
duration = 'Half Day (Morning)';
} else if (type === 'half_day_afternoon') {
duration = 'Half Day (Afternoon)';
} else if (type === 'specify_time') {
duration = leave.dates.startTime + ' - ' + leave.dates.endTime;
} else {
duration = 'Full Day';
}
} else {
if (type === 'half_day_morning') {
duration = 'Half Day (Morning)';
} else if (type === 'half_day_afternoon') {
duration = 'Half Day (Afternoon)';
} else if (type === 'specify_time') {
duration = leave.dates.startTime + ' - ' + leave.dates.endTime;
}
}
return {
name: name,
type: leave.leaveType && leave.leaveType.name ? leave.leaveType.name : 'Leave',
duration: duration
};
});
// Build template
const template = HtmlService.createTemplateFromFile('EmailTemplate');
template.isNotification = isNotification;
template.formattedDate = formattedDate;
template.leaves = formattedLeaves;
const htmlBody = template.evaluate().getContent();
// Plain text fallback
let plainBody =
(isNotification ? 'Upcoming Team Member Leaves' : "Today’s Team Member Leaves") + '\n' +
template.title + '\n' +
formattedDate + '\n\n' +
(isNotification
? 'The following team members will be on leave starting tomorrow:'
: 'The following team members are on leave today:') + '\n\n';
formattedLeaves.forEach(function (l) {
plainBody += '- ' + l.name +
(isNotification
? ' (' + l.type + ' - ' + l.duration + ')'
: l.duration ? ' - ' + l.duration : '') +
'\n';
});
plainBody +=
'\n---\nThis is an automated ' +
(isNotification ? 'notification' : 'reminder') +
' email from the Leave Alert System.';
// Send email
try {
MailApp.sendEmail({
to: toEmail,
subject: subject,
body: plainBody,
htmlBody: htmlBody
});
} catch (error) {
Logger.log('Error sending email to ' + toEmail + ': ' + error.toString());
}
}
/**
* Send error notification to system administrators
* @param {string} errorMessage - The error message to send
* @param {string} functionName - The function where the error occurred
*/
function notifyAdmin(errorMessage, functionName) {
if (typeof ADMIN_EMAILS === 'undefined' || !ADMIN_EMAILS || ADMIN_EMAILS.length === 0) {
Logger.log('ADMIN_EMAILS not configured - skipping admin notification');
return;
}
const timestamp = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd HH:mm:ss');
const subject = '⚠️ Leave Alert System Error - ' + functionName;
const body = 'Leave Alert System Error Report\n' +
'================================\n\n' +
'Function: ' + functionName + '\n' +
'Timestamp: ' + timestamp + '\n' +
'Error: ' + errorMessage + '\n\n' +
'================================\n' +
'Please check the Apps Script execution logs for more details.\n\n' +
'This is an automated error notification from the Leave Alert System.';
try {
MailApp.sendEmail({
to: ADMIN_EMAILS.join(','),
subject: subject,
body: body
});
Logger.log('Admin notification sent to: ' + ADMIN_EMAILS.join(', '));
} catch (emailError) {
Logger.log('Failed to send admin notification: ' + emailError.toString());
}
}