-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode.gs
More file actions
1395 lines (1169 loc) · 61.4 KB
/
Code.gs
File metadata and controls
1395 lines (1169 loc) · 61.4 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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function doGet(e) {
// 1. Default to Dashboard
if (!e.parameter.page && !e.parameter.action) {
return HtmlService.createHtmlOutputFromFile('Dashboard').setTitle('Admin Dashboard');
}
// 2. Submit Page
if (e.parameter.page === 'submit') {
let template = HtmlService.createTemplateFromFile('Index');
template.docTypes = getDocTypes();
template.directory = getDirectory();
return template.evaluate().setTitle('HRMDD-ComBen Document Submission');
}
// 3. Update/Manage Page
else if (e.parameter.action === 'update') {
const transactionId = e.parameter.id;
const transactionDetails = getTransactionDetails(transactionId);
let template = HtmlService.createTemplateFromFile('Update');
template.transactionId = transactionId;
template.details = transactionDetails;
// CRITICAL FIX: Pass directory data to the Update page for Autofill to work
template.directory = getDirectory();
return template.evaluate().setTitle('Update Transaction - ' + transactionId);
}
// 4. Print Slip
else if (e.parameter.action === 'print-slip') {
const transactionId = e.parameter.id;
const transactionDetails = getTransactionDetails(transactionId);
let template = HtmlService.createTemplateFromFile('PrintSlip');
template.transactionId = transactionId;
template.details = transactionDetails;
template.appUrl = ScriptApp.getService().getUrl();
return template.evaluate().setTitle('Print Slip - ' + transactionId);
}
return HtmlService.createHtmlOutputFromFile('Dashboard');
}
// SAFE URL GETTER: Prevents crashes if getUrl fails
function getWebAppUrlSafe() {
try {
return ScriptApp.getService().getUrl();
} catch (e) {
return ""; // Return empty string instead of crashing
}
}
function getDocTypes() {
try {
const docTypesSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('DocTypes');
if (!docTypesSheet || docTypesSheet.getLastRow() < 2) return [];
const types = docTypesSheet.getRange('A2:A' + docTypesSheet.getLastRow()).getValues();
return types.map(function(row) { return row[0]; }).filter(function(type) { return type; });
} catch (e) {
console.error("Error fetching DocTypes: " + e.toString());
return [];
}
}
function generateTransactionID() {
const lock = LockService.getScriptLock();
lock.waitLock(15000);
try {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const transactionsSheet = ss.getSheetByName('Transactions');
if (!transactionsSheet) { throw new Error("CRITICAL ERROR: The sheet named 'Transactions' could not be found."); }
const today = new Date();
const currentMonthYear = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2);
const lastRow = transactionsSheet.getLastRow();
let maxSerial = 0;
if (lastRow > 1) {
// Assuming TransactionID is in Column A (Index 0)
const allTransactionIDs = transactionsSheet.getRange('A2:A' + lastRow).getValues().flat();
for (let i = 0; i < allTransactionIDs.length; i++) {
let id = String(allTransactionIDs[i]);
if (id && id.startsWith(currentMonthYear)) {
let serialPart = parseInt(id.substring(8), 10);
if (serialPart > maxSerial) {
maxSerial = serialPart;
}
}
}
}
const newSerial = maxSerial + 1;
const serialFormatted = ('000' + newSerial).slice(-3);
return currentMonthYear + '-' + serialFormatted;
} finally {
lock.releaseLock();
}
}
function processForm(formObject) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const transactionsSheet = ss.getSheetByName('Transactions');
const documentsSheet = ss.getSheetByName('Documents');
let leaveLedgerSheet = ss.getSheetByName('LeaveLedger');
if (!transactionsSheet || !documentsSheet) {
throw new Error("CRITICAL ERROR: Sheets not found.");
}
if (!leaveLedgerSheet) {
leaveLedgerSheet = ss.insertSheet('LeaveLedger');
leaveLedgerSheet.appendRow(['TransactionID', 'EmployeeName', 'LeaveType', 'StartDate', 'EndDate', 'TotalDays', 'InclusiveDates', 'Timestamp']);
}
const newTransactionID = generateTransactionID();
const timestamp = new Date();
const txDetails = formObject.transactionDetails;
transactionsSheet.appendRow([
newTransactionID,
txDetails.contactPerson,
txDetails.centerDept,
txDetails.officeUnit,
txDetails.email,
timestamp
]);
const initialStatus = "Pending Signature";
const documentsForEmail = [];
const documentsWithOwner = [];
formObject.documents.forEach(function(doc) {
const principalName = doc.principalName || "";
const principalEmail = doc.principalEmail || "";
let inclusiveDatesString = "";
let emailLeaveDetails = [];
if (doc.docType === 'Application for Leave (ALA)' && doc.alaData) {
try {
const leaves = JSON.parse(doc.alaData);
const dateSummaries = [];
leaves.forEach(leave => {
let startDate = "";
let endDate = "";
if (leave.dates.includes(' to ')) {
const parts = leave.dates.split(' to ');
startDate = parts[0];
endDate = parts[1];
} else if (leave.dates.includes(', ')) {
const parts = leave.dates.split(', ');
startDate = parts[0];
endDate = parts[parts.length-1];
} else {
startDate = leave.dates;
endDate = leave.dates;
}
leaveLedgerSheet.appendRow([
newTransactionID,
principalName,
leave.type,
startDate,
endDate,
leave.days,
leave.dates,
timestamp
]);
dateSummaries.push(`${leave.type}: ${leave.dates} (${leave.days})`);
emailLeaveDetails.push({
type: leave.type,
dates: leave.dates,
days: leave.days
});
});
inclusiveDatesString = dateSummaries.join(";\n");
} catch (e) {
console.error("Error parsing ALA JSON: " + e.message);
inclusiveDatesString = "Error parsing dates";
}
} else {
inclusiveDatesString = doc.inclusiveDates || "";
}
documentsSheet.appendRow([
newTransactionID,
doc.docType,
doc.docTitle,
inclusiveDatesString,
initialStatus,
timestamp,
"",
"",
principalName,
principalEmail
]);
const docData = {
title: doc.docTitle,
type: doc.docType,
datesSummary: inclusiveDatesString,
leaveDetails: emailLeaveDetails,
owner: principalName || "(Liaison)",
principalEmail: principalEmail
};
documentsForEmail.push(docData);
documentsWithOwner.push(docData);
});
try {
sendLiaisonReceiptEmail(txDetails, newTransactionID, documentsForEmail);
const ownerGroups = {};
documentsWithOwner.forEach(doc => {
if (doc.principalEmail && doc.principalEmail !== txDetails.email) {
if (!ownerGroups[doc.principalEmail]) {
ownerGroups[doc.principalEmail] = { name: doc.owner, docs: [] };
}
ownerGroups[doc.principalEmail].docs.push(doc);
}
});
Object.keys(ownerGroups).forEach(email => {
const group = ownerGroups[email];
sendOwnerReceiptEmail(group.name, email, newTransactionID, group.docs, txDetails.contactPerson);
});
// HRIS Email removed from here
} catch(e) {
console.error("Email failed: " + e.toString());
}
return {
transactionId: newTransactionID,
appUrl: getWebAppUrlSafe(),
details: {
ContactPerson: txDetails.contactPerson,
Timestamp: timestamp.toLocaleString('en-US', { timeZone: 'Asia/Manila' }),
documents: documentsForEmail
}
};
}
// Helper: HR Summary Email (Branded & Optimized for Encoding)
function sendHROfficerSummary(leaveList, transactionId, timestamp) {
const subject = `[HRMDD] New Leave Application(s) Filed - Ref: ${transactionId}`;
// Build rows with prominent data points
const rows = leaveList.map(l =>
`<tr>
<td style="padding: 12px; border-bottom: 1px solid #eee; font-size: 14px; color: #333;">
<strong>${l.name}</strong>
</td>
<td style="padding: 12px; border-bottom: 1px solid #eee; font-size: 14px; color: #555;">
${l.type}
</td>
<td style="padding: 12px; border-bottom: 1px solid #eee; text-align: center; font-size: 16px; font-weight: bold; color: #1C2790; background-color: #fcfcfc;">
${l.days}
</td>
<td style="padding: 12px; border-bottom: 1px solid #eee; font-size: 13px; color: #555; font-family: monospace;">
${l.dates}
</td>
</tr>`
).join('');
const html = `
<div style="background-color: #f4f6f8; padding: 40px 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">
<div style="max-width: 750px; margin: 0 auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.05);">
<div style="background-color: #1C2790; padding: 25px; text-align: center;">
<img src="https://i.imgur.com/jaEbfAR.png" alt="DAP Logo" style="width: 280px; display: block; margin: 0 auto;">
</div>
<div style="padding: 40px; border-top: 6px solid #CDAE2C;">
<div style="display: flex; justify-content: space-between; align-items: flex-end; margin-bottom: 30px; border-bottom: 2px solid #f0f0f0; padding-bottom: 20px;">
<div>
<h1 style="color: #1C2790; margin: 0; font-size: 22px; text-transform: uppercase; letter-spacing: 0.5px;">For HRIS Encoding</h1>
<p style="margin: 5px 0 0 0; font-size: 14px; color: #666;">New Leave Applications Received</p>
</div>
<div style="text-align: right;">
<span style="font-size: 11px; color: #999; text-transform: uppercase;">Transaction Ref</span><br>
<span style="font-size: 18px; font-weight: bold; color: #333;">${transactionId}</span>
</div>
</div>
<table style="width: 100%; border-collapse: collapse; margin-bottom: 30px;">
<thead style="background-color: #f8f9fa;">
<tr>
<th style="padding: 12px; text-align: left; color: #666; font-size: 12px; text-transform: uppercase; border-bottom: 2px solid #ddd; width: 30%;">Employee Name</th>
<th style="padding: 12px; text-align: left; color: #666; font-size: 12px; text-transform: uppercase; border-bottom: 2px solid #ddd; width: 25%;">Leave Type</th>
<th style="padding: 12px; text-align: center; color: #666; font-size: 12px; text-transform: uppercase; border-bottom: 2px solid #ddd; width: 15%;">Day[s]</th>
<th style="padding: 12px; text-align: left; color: #666; font-size: 12px; text-transform: uppercase; border-bottom: 2px solid #ddd; width: 30%;">Inclusive Dates</th>
</tr>
</thead>
<tbody>${rows}</tbody>
</table>
<div style="padding: 15px; background-color: #fff9db; border-left: 4px solid #CDAE2C; border-radius: 4px; font-size: 13px; color: #856404;">
<strong>Encoder's Note:</strong> Please verify leave credit balances in the HRIS before posting. Date filed: ${timestamp.toLocaleString('en-US', { timeZone: 'Asia/Manila' })}.
</div>
</div>
<div style="background-color: #eeeeee; padding: 20px; text-align: center; font-size: 12px; color: #888;">
<p style="margin: 0;">© ${new Date().getFullYear()} HRMDD-ComBen Document Management System.</p>
<p style="margin: 5px 0 0 0;">Development Academy of the Philippines</p>
</div>
</div>
</div>`;
MailApp.sendEmail({
to: 'sabugoj@dap.edu.ph',
subject: subject,
htmlBody: html,
name: 'HRMDD-ComBen System'
});
}
function sendLiaisonReceiptEmail(txDetails, transactionId, documents) {
const subject = `[DMS] Transaction Logged - Ref: ${transactionId}`;
let documentsHtmlList = documents.map(doc => {
let titleDisplay = doc.title;
// LOGIC CHANGE: Handle Multi-Leave ALA
// If we have detailed leave info (Array from processForm)
if (doc.type === 'Application for Leave (ALA)' && doc.leaveDetails && doc.leaveDetails.length > 0) {
let listItems = doc.leaveDetails.map(l =>
`<div style="margin-bottom:4px;">
<strong>${l.type}</strong>: <span style="color:#555;">${l.dates}</span>
<span style="background:#eee;padding:1px 4px;border-radius:3px;font-size:11px;">${l.days} day[s]</span>
</div>`
).join('');
titleDisplay = `<div style="font-size:12px;">${listItems}</div>`;
}
// Fallback logic from previous versions (Composite String)
else if (doc.datesSummary && doc.datesSummary !== "") {
// Convert newlines to <br> for HTML display
let formattedSummary = doc.datesSummary.replace(/\n/g, '<br>');
titleDisplay += `<br><span style="font-size:12px; color:#666;">${formattedSummary}</span>`;
}
return `<tr>
<td style="padding: 12px; border-bottom: 1px solid #eee;"><b>${doc.owner}</b></td>
<td style="padding: 12px; border-bottom: 1px solid #eee;">${titleDisplay}</td>
<td style="padding: 12px; border-bottom: 1px solid #eee;">${doc.type}</td>
</tr>`;
}).join('');
const emailBody = `
<div style="background-color: #f4f6f8; padding: 40px 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">
<div style="max-width: 650px; margin: 0 auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.05);">
<div style="background-color: #1C2790; padding: 30px; text-align: center;">
<img src="https://i.imgur.com/jaEbfAR.png" alt="DAP Logo" style="width: 320px; display: block; margin: 0 auto;">
</div>
<div style="padding: 40px; border-top: 6px solid #CDAE2C;">
<h1 style="color: #1C2790; margin: 0 0 20px 0; text-align: center; font-size: 24px; text-transform: uppercase;">Transaction Logged</h1>
<div style="background-color: #f0f4ff; padding: 20px; text-align: center; margin: 0 0 30px 0; border-radius: 4px; border: 1px dashed #1C2790;">
<span style="font-size: 11px; color: #555; text-transform: uppercase; display: block; margin-bottom: 5px;">Transaction Reference</span>
<span style="font-size: 24px; font-weight: bold; color: #1C2790;">${transactionId}</span>
</div>
<p style="font-size: 16px; color: #333;">Dear <b>${txDetails.contactPerson}</b>,</p>
<p style="font-size: 16px; color: #333;">We have received the documents you submitted. Here is the summary:</p>
<table style="width: 100%; border-collapse: collapse; font-size: 14px; margin-top: 20px;">
<thead style="background-color: #f8f9fa;">
<tr>
<th style="padding: 12px; text-align: left;">Owner</th>
<th style="padding: 12px; text-align: left;">Details</th>
<th style="padding: 12px; text-align: left;">Type</th>
</tr>
</thead>
<tbody>${documentsHtmlList}</tbody>
</table>
</div>
<div style="background-color: #eeeeee; padding: 20px; text-align: center; font-size: 12px; color: #888;">
<p>© ${new Date().getFullYear()} HRMDD-ComBen Document Management System.</p>
</div>
</div>
</div>`;
MailApp.sendEmail({ to: txDetails.email, subject: subject, htmlBody: emailBody, name: 'DAP HRMDD-ComBen' });
}
function sendOwnerReceiptEmail(ownerName, ownerEmail, transactionId, documents, liaisonName) {
const subject = `[DMS] Document Received - Ref: ${transactionId}`;
let documentsHtmlList = documents.map(doc => {
let titleDisplay = doc.title;
// LOGIC CHANGE: Handle Multi-Leave ALA
if (doc.type === 'Application for Leave (ALA)' && doc.leaveDetails && doc.leaveDetails.length > 0) {
let listItems = doc.leaveDetails.map(l =>
`<div style="margin-bottom:4px; border-bottom:1px dashed #eee; padding-bottom:2px;">
<div style="font-weight:bold; color:#1C2790;">${l.type}</div>
<div style="font-size:12px; color:#555;">${l.dates} (${l.days} day[s])</div>
</div>`
).join('');
titleDisplay = listItems;
}
else if (doc.datesSummary && doc.datesSummary !== "") {
let formattedSummary = doc.datesSummary.replace(/\n/g, '<br>');
titleDisplay += `<br><span style="font-size:12px; color:#666;">${formattedSummary}</span>`;
}
return `<tr>
<td style="padding: 12px; border-bottom: 1px solid #eee;">${titleDisplay}</td>
<td style="padding: 12px; border-bottom: 1px solid #eee;">${doc.type}</td>
</tr>`;
}).join('');
const emailBody = `
<div style="background-color: #f4f6f8; padding: 40px 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">
<div style="max-width: 650px; margin: 0 auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.05);">
<div style="background-color: #1C2790; padding: 30px; text-align: center;">
<img src="https://i.imgur.com/jaEbfAR.png" alt="DAP Logo" style="width: 320px; display: block; margin: 0 auto;">
</div>
<div style="padding: 40px; border-top: 6px solid #CDAE2C;">
<h1 style="color: #1C2790; margin: 0 0 20px 0; text-align: center; font-size: 24px; text-transform: uppercase;">Document Received</h1>
<div style="background-color: #f0f4ff; padding: 20px; text-align: center; margin: 0 0 30px 0; border-radius: 4px; border: 1px dashed #1C2790;">
<span style="font-size: 11px; color: #555; text-transform: uppercase; display: block; margin-bottom: 5px;">Transaction Reference</span>
<span style="font-size: 24px; font-weight: bold; color: #1C2790;">${transactionId}</span>
</div>
<p style="font-size: 16px; color: #333;">Dear <b>${ownerName}</b>,</p>
<p style="font-size: 16px; color: #333;">This email confirms that HRMDD-ComBen has received the following document(s) submitted on your behalf by <b>${liaisonName}</b>:</p>
<table style="width: 100%; border-collapse: collapse; font-size: 14px; margin-top: 20px;">
<thead style="background-color: #f8f9fa;">
<tr>
<th style="padding: 12px; text-align: left;">Details</th>
<th style="padding: 12px; text-align: left;">Type</th>
</tr>
</thead>
<tbody>${documentsHtmlList}</tbody>
</table>
<p style="margin-top: 30px; font-size: 14px; color: #666; font-style: italic;">You will receive another notification once your document is processed.</p>
</div>
<div style="background-color: #eeeeee; padding: 20px; text-align: center; font-size: 12px; color: #888;">
<p>© ${new Date().getFullYear()} HRMDD-ComBen Document Management System.</p>
</div>
</div>
</div>`;
MailApp.sendEmail({ to: ownerEmail, subject: subject, htmlBody: emailBody, name: 'DAP HRMDD-ComBen' });
}
function getDashboardData() {
try {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const transactionsSheet = ss.getSheetByName('Transactions');
const documentsSheet = ss.getSheetByName('Documents');
const leaveSheet = ss.getSheetByName('LeaveLedger');
if (!transactionsSheet || !documentsSheet) {
return { transactions: [], docTypes: [], leaveData: [], appUrl: getWebAppUrlSafe() };
}
const docsByTxId = {};
const statusMap = {};
if (documentsSheet.getLastRow() > 1) {
const docRange = documentsSheet.getRange(2, 1, documentsSheet.getLastRow() - 1, documentsSheet.getLastColumn());
const docValues = docRange.getValues();
const docHeaders = documentsSheet.getRange(1, 1, 1, documentsSheet.getLastColumn()).getValues()[0];
docValues.forEach(function(row, index) {
if (!row[0]) return;
let docObject = { rowNumber: index + 2 };
docHeaders.forEach(function(header, i) {
if(header) {
const cleanHeader = header.trim();
if (row[i] instanceof Date) {
docObject[cleanHeader] = row[i].toLocaleString('en-US', { timeZone: 'Asia/Manila' });
} else {
docObject[cleanHeader] = String(row[i]);
}
}
});
if (docObject.TransactionID) {
if (docObject.DocumentType === 'Application for Leave (ALA)') {
statusMap[docObject.TransactionID] = docObject.Status;
}
if (!docsByTxId[docObject.TransactionID]) { docsByTxId[docObject.TransactionID] = []; }
docsByTxId[docObject.TransactionID].push(docObject);
}
});
}
const allTransactions = [];
const docTypes = new Set();
if (transactionsSheet.getLastRow() > 1) {
const txRange = transactionsSheet.getRange(2, 1, transactionsSheet.getLastRow() - 1, transactionsSheet.getLastColumn());
const txValues = txRange.getValues();
const txHeaders = transactionsSheet.getRange(1, 1, 1, transactionsSheet.getLastColumn()).getValues()[0];
txValues.forEach(function(row) {
if (!row[0]) return;
let txObject = {};
txHeaders.forEach(function(header, i) {
if(!header) return;
const cleanHeader = header.trim();
if (row[i] instanceof Date) {
txObject[cleanHeader] = row[i].toLocaleString('en-US', { timeZone: 'Asia/Manila' });
} else {
txObject[cleanHeader] = String(row[i]);
}
});
if (txObject.TransactionID) {
const relatedDocs = docsByTxId[txObject.TransactionID] || [];
txObject.documents = relatedDocs;
relatedDocs.forEach(function(d) { if(d.DocumentType) docTypes.add(d.DocumentType); });
allTransactions.push(txObject);
}
});
}
// --- LEAVE DATA & COMMUTABLE SUMMARY ---
const allLeaveData = [];
const commutableSummary = {}; // { "Name": { VL: 5, SL: 2 } }
const currentYear = new Date().getFullYear();
if (leaveSheet && leaveSheet.getLastRow() > 1) {
const lRange = leaveSheet.getRange(2, 1, leaveSheet.getLastRow() - 1, leaveSheet.getLastColumn());
const lValues = lRange.getValues();
const lHeaders = leaveSheet.getRange(1, 1, 1, leaveSheet.getLastColumn()).getValues()[0];
lValues.forEach(function(row) {
if (!row[0]) return;
let leaveObj = {};
let timestampDate = null;
lHeaders.forEach(function(header, i) {
if (header) {
const cleanHeader = header.trim();
if (row[i] instanceof Date) {
leaveObj[cleanHeader] = row[i].toLocaleString('en-US', { timeZone: 'Asia/Manila' });
leaveObj[cleanHeader + "_ISO"] = row[i].toISOString();
if (cleanHeader === 'Timestamp') timestampDate = row[i];
} else {
leaveObj[cleanHeader] = String(row[i]);
}
}
});
const currentStatus = statusMap[leaveObj.TransactionID] || "Pending Signature";
leaveObj.CurrentStatus = currentStatus;
allLeaveData.push(leaveObj);
// Calculate Commutable Summary (Active Only, Current Year)
if (currentStatus !== 'Pulled Out' && timestampDate && timestampDate.getFullYear() === currentYear) {
const name = leaveObj.EmployeeName || "Unknown";
const type = leaveObj.LeaveType;
const days = parseInt(leaveObj.TotalDays) || 0;
if (!commutableSummary[name]) commutableSummary[name] = { VL: 0, SL: 0 };
if (type === 'Vacation Leave') commutableSummary[name].VL += days;
if (type === 'Sick Leave') commutableSummary[name].SL += days;
}
});
}
return {
transactions: allTransactions.reverse(),
docTypes: Array.from(docTypes),
leaveData: allLeaveData.reverse(),
commutableSummary: commutableSummary, // Return the pre-calculated summary
appUrl: getWebAppUrlSafe()
};
} catch (e) {
return { transactions: [], docTypes: [], leaveData: [], appUrl: getWebAppUrlSafe() };
}
}
function getTransactionDetails(transactionId) {
try {
if (!transactionId) return null;
const ss = SpreadsheetApp.getActiveSpreadsheet();
const transactionsSheet = ss.getSheetByName('Transactions');
const documentsSheet = ss.getSheetByName('Documents');
let transactionInfo = null;
// Fetch Header
if (transactionsSheet.getLastRow() > 1) {
const txData = transactionsSheet.getDataRange().getValues();
const txHeaders = txData.shift();
for (let i = 0; i < txData.length; i++) {
if (String(txData[i][0]) === String(transactionId)) {
transactionInfo = {};
txHeaders.forEach(function(header, idx) {
if(header) {
const cleanHeader = header.trim();
const cellValue = txData[i][idx];
// Added Safety: Convert Dates to Strings like in Dashboard
if (cellValue instanceof Date) {
transactionInfo[cleanHeader] = cellValue.toLocaleString('en-US', { timeZone: 'Asia/Manila' });
} else {
transactionInfo[cleanHeader] = String(cellValue);
}
}
});
break;
}
}
}
if (!transactionInfo) return null;
// Fetch Related Documents
const relatedDocuments = [];
if (documentsSheet.getLastRow() > 1) {
const docData = documentsSheet.getDataRange().getValues();
const docHeaders = docData.shift();
for (let i = 0; i < docData.length; i++) {
if (String(docData[i][0]) === String(transactionId)) {
let docObject = {};
docHeaders.forEach(function(header, idx) {
if(header) {
const cleanHeader = header.trim(); // This captures 'PrincipalName'
const cellValue = docData[i][idx];
// Added Safety: Convert Dates to Strings
if (cellValue instanceof Date) {
docObject[cleanHeader] = cellValue.toLocaleString('en-US', { timeZone: 'Asia/Manila' });
} else {
docObject[cleanHeader] = String(cellValue);
}
}
});
docObject.rowNumber = i + 2;
relatedDocuments.push(docObject);
}
}
}
transactionInfo.documents = relatedDocuments;
return transactionInfo;
} catch (e) {
console.error("Error in getTransactionDetails: " + e.toString());
return null;
}
}
function updateDocumentStatus(updateData) {
const documentsSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Documents');
const lastRow = documentsSheet.getLastRow();
const affectedDocs = [];
// A. BATCH UPDATE
if (updateData.isBatch) {
if (lastRow < 2) return "No documents to update.";
const data = documentsSheet.getRange(2, 1, lastRow - 1, 1).getValues();
for (let i = 0; i < data.length; i++) {
if (String(data[i][0]) === String(updateData.transactionId)) {
const currentRow = i + 2;
const currentStatus = documentsSheet.getRange(currentRow, 5).getValue();
if (currentStatus !== 'Claimed/Released' && currentStatus !== 'Pulled Out') {
documentsSheet.getRange(currentRow, 5).setValue(updateData.newStatus);
documentsSheet.getRange(currentRow, 6).setValue(new Date());
if (updateData.notes) documentsSheet.getRange(currentRow, 8).setValue(updateData.notes);
const pName = documentsSheet.getRange(currentRow, 9).getValue();
const pEmail = documentsSheet.getRange(currentRow, 10).getValue();
const datesSummary = documentsSheet.getRange(currentRow, 4).getValue(); // Col D
affectedDocs.push({
Title: documentsSheet.getRange(currentRow, 3).getValue(),
Type: documentsSheet.getRange(currentRow, 2).getValue(),
Status: updateData.newStatus,
PrincipalName: pName,
PrincipalEmail: pEmail,
DatesSummary: datesSummary
});
}
}
}
}
// B. INDIVIDUAL UPDATE
else {
try {
const row = parseInt(updateData.documentRow);
documentsSheet.getRange(row, 5).setValue(updateData.newStatus);
documentsSheet.getRange(row, 6).setValue(new Date());
if (updateData.notes) documentsSheet.getRange(row, 8).setValue(updateData.notes);
const pName = documentsSheet.getRange(row, 9).getValue();
const pEmail = documentsSheet.getRange(row, 10).getValue();
const datesSummary = documentsSheet.getRange(row, 4).getValue();
affectedDocs.push({
Title: documentsSheet.getRange(row, 3).getValue(),
Type: documentsSheet.getRange(row, 2).getValue(),
Status: updateData.newStatus,
PrincipalName: pName,
PrincipalEmail: pEmail,
DatesSummary: datesSummary
});
} catch (e) { return "Error: " + e.message; }
}
// C. SEND EMAILS (If updates occurred)
if (affectedDocs.length > 0) {
const txDetails = getTransactionDetails(updateData.transactionId);
const leavesForHR = []; // Store leaves for HRIS email
// 1. Prepare HRIS Data if Signed
if (updateData.newStatus === 'Signed') {
affectedDocs.forEach(doc => {
if (doc.Type === 'Application for Leave (ALA)' && doc.DatesSummary) {
// Parse the composite string: "VL: Date (1); SL: Date (2)"
const entries = doc.DatesSummary.split(';');
entries.forEach(entry => {
// entry example: "Vacation Leave: 2025-01-01 (1)"
// Simple parsing logic
const parts = entry.trim().split(':');
if (parts.length > 1) {
const lType = parts[0].trim();
const rest = parts[1].trim(); // "2025-01-01 (1)"
const daysMatch = rest.match(/\((\d+)\)$/);
const days = daysMatch ? daysMatch[1] : "1";
const dateStr = rest.replace(/\s*\(\d+\)$/, "");
leavesForHR.push({
name: doc.PrincipalName,
type: lType,
days: days,
dates: dateStr
});
}
});
}
});
}
// 2. Send Principals Emails
const principalGroups = {};
affectedDocs.forEach(doc => {
if (doc.PrincipalEmail && doc.PrincipalEmail.trim() !== "") {
if (!principalGroups[doc.PrincipalEmail]) {
principalGroups[doc.PrincipalEmail] = { Name: doc.PrincipalName, Docs: [] };
}
principalGroups[doc.PrincipalEmail].Docs.push(doc);
}
});
Object.keys(principalGroups).forEach(email => {
const group = principalGroups[email];
const principalTxDetails = {
TransactionID: txDetails.TransactionID,
ContactPerson: group.Name || "Document Owner",
ContactEmail: email
};
if (updateData.newStatus === 'Signed') {
sendReadyForPickupEmail(principalTxDetails, group.Docs, updateData.notes, false);
} else if (updateData.newStatus === 'For pick up, but with comments') {
sendPickupWithCommentsEmail(principalTxDetails, group.Docs, updateData.notes, false);
}
});
// 3. Send Liaison Summary
if (updateData.newStatus === 'Signed') {
sendReadyForPickupEmail(txDetails, affectedDocs, updateData.notes, true);
} else if (updateData.newStatus === 'For pick up, but with comments') {
sendPickupWithCommentsEmail(txDetails, affectedDocs, updateData.notes, true);
}
// 4. Send HRIS Summary (NEW TRIGGER)
if (leavesForHR.length > 0) {
sendHROfficerSummary(leavesForHR, updateData.transactionId, new Date());
}
return `Success: Updated ${affectedDocs.length} document(s).`;
}
return "No documents were updated.";
}
function sendReadyForPickupEmail(txDetails, docsList, notes, isBatch) {
const subject = `[DMS] Ready for Pickup - Ref: ${txDetails.TransactionID}`;
const rows = docsList.map(d => `<tr><td style="padding:12px;border-bottom:1px solid #eee;">${d.Title}</td><td style="padding:12px;border-bottom:1px solid #eee;color:#555;">${d.Type}</td></tr>`).join('');
let remarksHtml = '';
if (notes) {
remarksHtml = `
<div style="margin-top: 25px; padding: 20px; background-color: #f0fcf4; border-left: 5px solid #198754; border-radius: 4px;">
<h4 style="margin:0 0 5px 0; color: #198754; font-size: 14px; text-transform: uppercase;">Remarks</h4>
<p style="margin:0; font-size: 15px; color: #333;">${notes}</p>
</div>`;
}
const docContext = isBatch
? `All pending documents in this transaction have been signed.`
: `The document listed below has been signed.`;
const html = `
<div style="background-color: #f4f6f8; padding: 40px 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">
<div style="max-width: 650px; margin: 0 auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.05);">
<div style="background-color: #1C2790; padding: 30px; text-align: center;">
<img src="https://i.imgur.com/jaEbfAR.png" alt="DAP Logo" style="width: 320px; display: block; margin: 0 auto;">
</div>
<div style="padding: 40px; border-top: 6px solid #198754;">
<h1 style="color: #198754; margin: 0 0 20px 0; text-align: center; font-size: 26px; text-transform: uppercase; letter-spacing: 1px;">Ready for Pickup</h1>
<div style="background-color: #f0f4ff; padding: 20px; text-align: center; margin: 0 0 30px 0; border-radius: 4px; border: 1px dashed #1C2790;">
<span style="font-size: 11px; color: #555; text-transform: uppercase; display: block; margin-bottom: 5px; letter-spacing: 1px;">Transaction Reference</span>
<span style="font-size: 24px; font-weight: bold; color: #1C2790;">${txDetails.TransactionID}</span>
</div>
<p style="font-size: 16px; color: #333; margin-bottom: 20px;">Dear <b>${txDetails.ContactPerson}</b>,</p>
<p style="font-size: 16px; color: #333; line-height: 1.6;">Good news! ${docContext}</p>
<table style="width: 100%; border-collapse: collapse; margin-top: 20px; font-size: 14px;">
<thead style="background-color: #198754; color: white;">
<tr>
<th style="padding: 12px; text-align: left;">Document Title</th>
<th style="padding: 12px; text-align: left;">Type</th>
</tr>
</thead>
<tbody>${rows}</tbody>
</table>
${remarksHtml}
<div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; text-align: center;">
<p style="font-size: 15px; font-weight: bold; color: #555;">You may now proceed to the HRMDD-ComBen office or have someone claim the document(s) on your behalf.</p>
</div>
</div>
<div style="background-color: #eeeeee; padding: 20px; text-align: center; font-size: 12px; color: #888;">
<p style="margin: 0;">© ${new Date().getFullYear()} HRMDD-ComBen Document Management System.</p>
<p style="margin: 5px 0 0 0;">All Rights Reserved.</p>
</div>
</div>
</div>`;
MailApp.sendEmail({ to: txDetails.ContactEmail, subject: subject, htmlBody: html, name: 'DAP HRMDD-ComBen' });
}
function sendPickupWithCommentsEmail(txDetails, docsList, notes, isBatch) {
const subject = `[DMS] Action Required - Ref: ${txDetails.TransactionID}`;
const rows = docsList.map(d => `<tr><td style="padding:12px;border-bottom:1px solid #e0e0e0;">${d.Title}</td><td style="padding:12px;border-bottom:1px solid #e0e0e0;">${d.Type}</td></tr>`).join('');
const html = `
<div style="background-color: #f4f6f8; padding: 40px 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">
<div style="max-width: 650px; margin: 0 auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.05);">
<div style="background-color: #1C2790; padding: 30px; text-align: center;">
<img src="https://i.imgur.com/jaEbfAR.png" alt="DAP Logo" style="width: 320px; display: block; margin: 0 auto;">
</div>
<div style="padding: 40px; border-top: 6px solid #ffc107;">
<h1 style="color: #bfa006; margin: 0 0 20px 0; text-align: center; font-size: 26px; text-transform: uppercase; letter-spacing: 1px;">Action Required</h1>
<div style="background-color: #f0f4ff; padding: 20px; text-align: center; margin: 0 0 30px 0; border-radius: 4px; border: 1px dashed #1C2790;">
<span style="font-size: 11px; color: #555; text-transform: uppercase; display: block; margin-bottom: 5px; letter-spacing: 1px;">Transaction Reference</span>
<span style="font-size: 24px; font-weight: bold; color: #1C2790;">${txDetails.TransactionID}</span>
</div>
<p style="font-size: 16px; color: #333;">Dear <b>${txDetails.ContactPerson}</b>,</p>
<p style="font-size: 16px; color: #333; line-height: 1.6;">The following documents have been reviewed but require your attention:</p>
<table style="width: 100%; border-collapse: collapse; margin-top: 20px; font-size: 14px;">
<thead style="background-color: #fff3cd; color: #856404;">
<tr>
<th style="padding: 12px; text-align: left;">Document Title</th>
<th style="padding: 12px; text-align: left;">Type</th>
</tr>
</thead>
<tbody>${rows}</tbody>
</table>
<div style="margin-top: 25px; padding: 20px; background-color: #fff9db; border: 1px solid #ffeeba; border-radius: 4px; color: #856404;">
<h4 style="margin:0 0 10px 0; font-size: 14px; text-transform: uppercase;">Requirements / Comments:</h4>
<p style="margin:0; font-size: 15px; font-weight: 500;">${notes}</p>
</div>
<p style="margin-top: 30px; text-align: center; font-weight: bold; color: #555;">Please visit the office to address these items.</p>
</div>
<div style="background-color: #eeeeee; padding: 20px; text-align: center; font-size: 12px; color: #888;">
<p style="margin: 0;">© ${new Date().getFullYear()} HRMDD-ComBen Document Management System.</p>
<p style="margin: 5px 0 0 0;">All Rights Reserved.</p>
</div>
</div>
</div>`;
MailApp.sendEmail({ to: txDetails.ContactEmail, subject: subject, htmlBody: html, name: 'DAP HRMDD-ComBen' });
}
function sendClaimedEmail(txDetails, docsList, claimantName, timestamp, isThirdParty) {
const subject = `[DMS] Document Claimed - Ref: ${txDetails.TransactionID}`;
const formattedTimestamp = timestamp.toLocaleString('en-US', { timeZone: 'Asia/Manila' });
const rows = docsList.map(d => {
// Logic for Claimed Email: The data comes from the sheet (via processClaim or getTransactionDetails).
// We don't have the granular 'leaveDetails' array here because that was only in processForm scope.
// However, we saved the composite string into the sheet column "InclusiveDates" (or Title, depending on implementation).
// If the Title contains newlines (from processForm logic), we need to replace them with <br> for HTML display.
let displayTitle = d.Title;
// Safety check if Title has newlines from the multi-leave summary
if (displayTitle && typeof displayTitle === 'string') {
displayTitle = displayTitle.replace(/\n/g, '<br>');
}
return `<tr>
<td style="padding:12px;border-bottom:1px solid #eee;">${displayTitle}</td>
<td style="padding:12px;border-bottom:1px solid #eee;color:#555;">${d.Type}</td>
</tr>`;
}).join('');
let thirdPartyWarning = "";
if (isThirdParty) {
thirdPartyWarning = `
<div style="margin-top: 20px; padding: 15px; background-color: #fff3cd; border-left: 4px solid #ffc107; color: #856404; font-size: 13px;">
<strong>Note:</strong> Documents were claimed by an authorized representative: <strong>${claimantName}</strong>.
</div>`;
}
const html = `
<div style="background-color: #f4f6f8; padding: 40px 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">
<div style="max-width: 650px; margin: 0 auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.05);">
<div style="background-color: #1C2790; padding: 30px; text-align: center;">
<img src="https://i.imgur.com/jaEbfAR.png" alt="DAP Logo" style="width: 320px; display: block; margin: 0 auto;">
</div>
<div style="padding: 40px; border-top: 6px solid #1C2790;">
<h1 style="color: #1C2790; margin: 0 0 20px 0; text-align: center; font-size: 26px; text-transform: uppercase; letter-spacing: 1px;">Transaction Complete</h1>
<div style="background-color: #f0f4ff; padding: 20px; text-align: center; margin: 0 0 30px 0; border-radius: 4px; border: 1px dashed #1C2790;">
<span style="font-size: 11px; color: #555; text-transform: uppercase; display: block; margin-bottom: 5px; letter-spacing: 1px;">Transaction Reference</span>
<span style="font-size: 24px; font-weight: bold; color: #1C2790;">${txDetails.TransactionID}</span>
</div>
<p style="font-size: 16px; color: #333;">Dear <b>${txDetails.ContactPerson}</b>,</p>
<p style="font-size: 16px; color: #333; line-height: 1.6;">This email serves as an official confirmation that the following documents were successfully claimed:</p>
<table style="width: 100%; border-collapse: collapse; margin-top: 20px; font-size: 14px;">
<thead style="background-color: #f2f4f8;">
<tr>
<th style="padding: 12px; text-align: left; color: #333;">Document Title / Details</th>
<th style="padding: 12px; text-align: left; color: #333;">Type</th>
</tr>
</thead>
<tbody>${rows}</tbody>
</table>
${thirdPartyWarning}
<div style="margin-top: 30px; border: 1px solid #eee; padding: 20px; border-radius: 6px; text-align: center; background-color: #fafafa;">
<p style="font-size: 12px; color: #999; text-transform: uppercase; margin-bottom: 10px;">Claimed By</p>
<p style="font-size: 18px; font-weight: bold; color: #333; margin: 0;">${claimantName}</p>
<p style="font-size: 13px; color: #555; margin-top: 5px;"><strong>Date:</strong> ${formattedTimestamp}</p>
</div>
<div style="margin-top: 40px; padding: 0; background-color: #ffffff; border: 1px solid #e0e0e0; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.02);">
<div style="padding: 30px 30px 25px 30px; text-align: center;">
<h3 style="margin: 0 0 10px 0; color: #1C2790; font-size: 20px;">How was your transaction?</h3>
<p style="margin: 0 0 25px 0; color: #555; font-size: 15px; line-height: 1.5;">We're always working to make our services faster and more convenient. We would like to hear from you!</p>
<a href="https://ee.kobotoolbox.org/single/qWDFihHz?return%20_url=https:dap.edu.ph" target="_blank" style="display: inline-block; padding: 14px 28px; background-color: #CDAE2C; color: #1C2790; text-decoration: none; border-radius: 5px; font-weight: bold; font-size: 15px; letter-spacing: 0.5px; border: 1px solid #B59820; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">Share Your Experience (1-Min Survey)</a>
</div>
<div style="background-color: #f8f9fa; padding: 25px; text-align: left; border-top: 1px solid #eee; font-size: 13px; color: #444; line-height: 1.6;">
<p style="margin: 0 0 15px 0; color: #1C2790;"><strong>On the survey form, please follow these steps:</strong></p>
<div style="margin-bottom: 12px;">
<span style="font-weight: bold; color: #333;">1. Select Office:</span> <br>
Human Resource Management Division (HRMD) - HRMDD
</div>