-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
1212 lines (1022 loc) · 43.3 KB
/
Copy pathscript.js
File metadata and controls
1212 lines (1022 loc) · 43.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
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
/**
* Grade Sheet Analyzer Class
* Handles PDF upload, parsing, and course data extraction
*/
class GradeSheetAnalyzer {
constructor() {
this.courses = [];
this.originalCourses = []; // Store original grade points
this.initializeEventListeners();
this.showWelcomeMessage();
}
/**
* Initialize all event listeners for the application
*/
initializeEventListeners() {
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
// Click to upload
uploadArea.addEventListener('click', () => {
fileInput.click();
});
// File input change
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
if (file.type === 'application/pdf') {
this.processPDF(file);
} else if (file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
file.type === 'application/vnd.ms-excel' ||
file.name.endsWith('.xlsx') ||
file.name.endsWith('.xls')) {
this.processExcel(file);
} else {
this.showError('Please select a valid PDF or Excel file (.pdf, .xlsx, .xls).');
}
}
});
// Control buttons
document.addEventListener('click', (e) => {
if (e.target.id === 'resetBtn') {
this.resetToOriginal();
} else if (e.target.id === 'exportBtn') {
this.exportToExcel();
} else if (e.target.id === 'addCourseBtn') {
this.addNewCourseRow();
} else if (e.target.classList.contains('save-btn')) {
this.saveNewCourse(e.target);
} else if (e.target.classList.contains('cancel-btn')) {
this.cancelNewCourse(e.target);
}
});
// Remove the old add course form event listeners
// document.addEventListener('input', (e) => {
// if (e.target.id === 'newCredits' || e.target.id === 'newGradePoints') {
// this.updateQualityPointsPreview();
// }
// });
// document.addEventListener('input', (e) => {
// if (e.target.id === 'newCourseCode') {
// e.target.value = e.target.value.toUpperCase();
// }
// });
// Drag and drop functionality
uploadArea.addEventListener('dragover', (e) => {
e.preventDefault();
uploadArea.classList.add('dragover');
}, { passive: false });
uploadArea.addEventListener('dragleave', (e) => {
e.preventDefault();
uploadArea.classList.remove('dragover');
}, { passive: false });
uploadArea.addEventListener('drop', (e) => {
e.preventDefault();
uploadArea.classList.remove('dragover');
const file = e.dataTransfer.files[0];
if (file && file.type === 'application/pdf') {
this.processPDF(file);
} else {
this.showError('Please drop a valid PDF file.');
}
}, { passive: false });
}
/**
* Show welcome message on page load
*/
showWelcomeMessage() {
// Grade Sheet Analyzer initialized and ready
}
/**
* Check if PDF.js is ready
*/
async ensurePDFJSReady() {
return new Promise((resolve) => {
if (typeof pdfjsLib !== 'undefined') {
resolve();
return;
}
// Update loading message for first-time users
const loadingContent = document.querySelector('.loading-content');
if (loadingContent) {
loadingContent.textContent = 'Loading PDF processing library...';
}
const checkInterval = setInterval(() => {
if (typeof pdfjsLib !== 'undefined') {
clearInterval(checkInterval);
// Reset loading message
if (loadingContent) {
loadingContent.textContent = 'Processing your grade sheet...';
}
resolve();
}
}, 50);
// Timeout after 10 seconds
setTimeout(() => {
clearInterval(checkInterval);
resolve();
}, 10000);
});
}
/**
* Process uploaded PDF file
*/
async processPDF(file) {
try {
this.showLoading(true);
this.hideError();
this.hideResults();
// Ensure PDF.js is loaded
await this.ensurePDFJSReady();
const arrayBuffer = await file.arrayBuffer();
const pdf = await pdfjsLib.getDocument(arrayBuffer).promise;
let fullText = '';
// Extract text from all pages with optimized processing
const pagePromises = [];
for (let i = 1; i <= pdf.numPages; i++) {
pagePromises.push(this.extractPageText(pdf, i));
}
// Process pages in parallel
const pageTexts = await Promise.all(pagePromises);
fullText = pageTexts.join('\n');
// Parse the extracted text
this.parseGradeSheet(fullText);
if (this.courses.length === 0) {
this.showError(`No courses found in the PDF. Please make sure this is a valid grade sheet.`);
return;
}
this.displayResults();
this.showSuccessMessage(`Successfully extracted ${this.courses.length} courses from your grade sheet!`);
} catch (error) {
console.error('Error processing PDF:', error);
this.showError('Error processing PDF. Please try again with a different file.');
} finally {
this.showLoading(false);
}
}
/**
* Extract text from a single PDF page (optimized)
*/
async extractPageText(pdf, pageNumber) {
const page = await pdf.getPage(pageNumber);
const textContent = await page.getTextContent();
// Use Map for faster Y-coordinate grouping
const lineMap = new Map();
// Group text items by Y coordinate efficiently
for (const item of textContent.items) {
const y = Math.round(item.transform[5]);
const x = item.transform[4];
if (!lineMap.has(y)) {
lineMap.set(y, []);
}
lineMap.get(y).push({ text: item.str, x });
}
// Sort lines by Y coordinate and combine text
const sortedLines = Array.from(lineMap.entries())
.sort((a, b) => b[0] - a[0]) // Sort by Y (top to bottom)
.map(([_, items]) => {
// Sort items on same line by X coordinate
return items
.sort((a, b) => a.x - b.x)
.map(item => item.text)
.join(' ')
.trim();
})
.filter(line => line.length > 0);
return sortedLines.join('\n');
}
/**
* Process uploaded Excel file
*/
async processExcel(file) {
try {
this.showLoading(true);
this.hideError();
this.hideResults();
const arrayBuffer = await file.arrayBuffer();
const workbook = XLSX.read(arrayBuffer, { type: 'array' });
// Get the first sheet
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
// Convert to JSON
const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
// Parse the Excel data
this.parseExcelData(data);
if (this.courses.length === 0) {
this.showError(`No valid courses found in the Excel file. Please make sure the file contains columns for Course Code, Credits, and Grade Points.`);
return;
}
this.displayResults();
this.showSuccessMessage(`Successfully imported ${this.courses.length} courses from your Excel file!`);
} catch (error) {
console.error('Error processing Excel:', error);
this.showError('Error processing Excel file. Please check the file format and try again.');
} finally {
this.showLoading(false);
}
}
/**
* Parse grade sheet text and extract course information (optimized)
*/
parseGradeSheet(text) {
this.courses = [];
this.originalCourses = [];
// Cache regex patterns for better performance
const courseCodePattern = /^([A-Z]{2,4}\d{3}[A-Z]?[A-Z0-9]?)/;
const numbersPattern = /\d+\.\d+/g;
const retakePatterns = {
rp: /\b(RP|\(RP\)|\( RP \))\b/i,
rt: /\b(RT|\(RT\)|\( RT \))\b/i
};
const lines = text.split('\n').map(line => line.trim()).filter(line => line && !this.shouldSkipLine(line));
const courseMap = new Map();
// Optimized line parsing
for (const line of lines) {
const courseMatch = line.match(courseCodePattern);
if (courseMatch) {
const courseCode = courseMatch[1];
// Optimized retake detection
const hasRP = retakePatterns.rp.test(line);
const hasRT = retakePatterns.rt.test(line);
const isRetake = hasRP || hasRT;
// Extract numbers efficiently
const numbers = line.match(numbersPattern);
if (numbers && numbers.length >= 2) {
let credits = parseFloat(numbers[0]);
const gradePoints = parseFloat(numbers[numbers.length - 1]);
const isFailedCourse = credits === 0 && gradePoints === 0;
const isPrepCourse = this.isPrepCourse(courseCode);
if (isFailedCourse && !isPrepCourse) {
credits = this.getStandardCredits(courseCode);
}
if (this.isValidCourse(credits, gradePoints)) {
const courseData = {
courseCode,
credits,
gradePoints,
qualityPoints: credits * gradePoints,
isRetake,
retakeType: isRetake ? (hasRP && hasRT ? 'RP/RT' : (hasRP ? 'RP' : 'RT')) : null,
isFailed: isFailedCourse && !isPrepCourse
};
this.handleDuplicateCourse(courseMap, courseData);
}
}
}
}
// Fallback to word-by-word parsing only if no courses found
if (courseMap.size === 0) {
this.parseWordByWord(text.replace(/\s+/g, ' ').split(' '), courseMap);
}
this.courses = Array.from(courseMap.values());
this.originalCourses = this.courses.map(course => ({...course}));
}
/**
* Check if course is a prep course
*/
isPrepCourse(courseCode) {
return ['MAT091', 'MAT092', 'ENG091'].includes(courseCode);
}
/**
* Validate course credits and grade points
*/
isValidCourse(credits, gradePoints) {
return credits >= 0 && credits <= 10 && gradePoints >= 0 && gradePoints <= 4.0;
}
/**
* Handle duplicate courses by prioritizing retake courses with (RP) or (RT) notation
* For multiple retakes, prioritize the one with the highest grade points
*/
handleDuplicateCourse(courseMap, newCourseData) {
const courseCode = newCourseData.courseCode;
if (courseMap.has(courseCode)) {
const existingCourse = courseMap.get(courseCode);
// If the new course is a retake and the existing one is not, replace it
if (newCourseData.isRetake && !existingCourse.isRetake) {
courseMap.set(courseCode, newCourseData);
}
// If the existing course is a retake and the new one is not, keep the existing one
else if (existingCourse.isRetake && !newCourseData.isRetake) {
// Keep existing retake
return;
}
// If both are retakes, keep the one with higher grade points (latest/better grade)
else if (existingCourse.isRetake && newCourseData.isRetake) {
if (newCourseData.gradePoints > existingCourse.gradePoints) {
courseMap.set(courseCode, newCourseData);
}
}
// If both are originals, keep the first one found
} else {
// First occurrence of this course
courseMap.set(courseCode, newCourseData);
}
}
/**
* Get standard credit hours for a course based on course code patterns
*/
getStandardCredits(courseCode) {
// Common BRAC University credit patterns
if (courseCode.match(/^(CSE|EEE|ECE)\d{3}$/)) {
return 3; // Most CSE/EEE/ECE courses are 3 credits
} else if (courseCode.match(/^(CSE|EEE|ECE)\d{3}L$/)) {
return 1; // Lab courses are typically 1 credit
} else if (courseCode.match(/^MAT\d{3}$/)) {
return 3; // Math courses are typically 3 credits
} else if (courseCode.match(/^(PHY|CHE)\d{3}$/)) {
return 3; // Physics/Chemistry courses are typically 3 credits
} else if (courseCode.match(/^(PHY|CHE)\d{3}L$/)) {
return 1; // Lab courses are typically 1 credit
} else if (courseCode.match(/^ENG\d{3}$/)) {
return 3; // English courses are typically 3 credits
} else if (courseCode.match(/^BUS\d{3}$/)) {
return 3; // Business courses are typically 3 credits
} else {
// Default to 3 credits for unknown course patterns
return 3;
}
}
/**
* Check if a line should be skipped during parsing
*/
shouldSkipLine(line) {
const skipPatterns = [
'SEMESTER:',
'CUMULATIVE',
'Credits Attempted',
'Course No',
'Course Title',
'GRADE SHEET',
'Student ID',
'BRAC University',
'PROGRAM:',
'Page ',
'UNOFFICIAL COPY',
'GPA ',
'CGPA '
];
return skipPatterns.some(pattern => line.includes(pattern));
}
/**
* Alternative parsing method using word-by-word analysis (optimized)
*/
parseWordByWord(words, courseMap) {
const courseCodePattern = /^[A-Z]{2,4}\d{3}$/;
const numberPattern = /^\d+\.\d+$/;
for (let i = 0; i < words.length - 4; i++) {
const word = words[i];
if (courseCodePattern.test(word)) {
// Check for retake notation in context
const contextWords = words.slice(Math.max(0, i - 3), i + 10);
const contextText = contextWords.join(' ');
const hasRP = /\b(RP|\(RP\))\b/i.test(contextText);
const hasRT = /\b(RT|\(RT\))\b/i.test(contextText);
const isRetake = hasRP || hasRT;
// Extract numbers efficiently
const numbers = words.slice(i + 1, i + 10)
.filter(w => numberPattern.test(w))
.map(w => parseFloat(w));
if (numbers.length >= 2) {
let credits = numbers[0];
const gradePoints = numbers[1];
const isFailedCourse = credits === 0 && gradePoints === 0;
const isPrepCourse = this.isPrepCourse(word);
if (isFailedCourse && !isPrepCourse) {
credits = this.getStandardCredits(word);
}
if (this.isValidCourse(credits, gradePoints)) {
const courseData = {
courseCode: word,
credits,
gradePoints,
qualityPoints: credits * gradePoints,
isRetake,
retakeType: isRetake ? (hasRP && hasRT ? 'RP/RT' : (hasRP ? 'RP' : 'RT')) : null,
isFailed: isFailedCourse && !isPrepCourse
};
this.handleDuplicateCourse(courseMap, courseData);
break;
}
}
}
}
}
/**
* Parse Excel data and extract course information
*/
parseExcelData(data) {
this.courses = [];
this.originalCourses = [];
if (!data || data.length === 0) {
return;
}
// Find header row - look for common column names
let headerRowIndex = -1;
let courseCodeCol = -1;
let creditsCol = -1;
let gradePointsCol = -1;
for (let i = 0; i < Math.min(5, data.length); i++) {
const row = data[i];
if (!Array.isArray(row)) continue;
for (let j = 0; j < row.length; j++) {
const cell = String(row[j]).toLowerCase().trim();
if (cell.includes('course') && cell.includes('code')) {
courseCodeCol = j;
headerRowIndex = i;
} else if (cell.includes('credit') && creditsCol === -1) {
creditsCol = j;
headerRowIndex = i;
} else if (cell.includes('grade') && cell.includes('point') && gradePointsCol === -1) {
gradePointsCol = j;
headerRowIndex = i;
}
}
// If we found all three columns, we're good
if (courseCodeCol !== -1 && creditsCol !== -1 && gradePointsCol !== -1) {
break;
}
}
// If we couldn't find proper headers, try to guess based on first few rows
if (headerRowIndex === -1) {
headerRowIndex = 0;
// Look at first data row to determine structure
for (let i = 0; i < Math.min(3, data.length); i++) {
const row = data[i];
if (!Array.isArray(row) || row.length < 3) continue;
// Look for course code pattern in first few columns
for (let j = 0; j < Math.min(3, row.length); j++) {
const cell = String(row[j]).trim();
if (/^[A-Z]{2,4}\d{3}$/i.test(cell)) {
courseCodeCol = j;
creditsCol = j + 1;
gradePointsCol = j + 2;
headerRowIndex = i;
break;
}
}
if (courseCodeCol !== -1) break;
}
}
if (courseCodeCol === -1 || creditsCol === -1 || gradePointsCol === -1) {
return;
}
// Parse data rows
const courseMap = new Map();
const retakePatterns = {
rp: /\b(rp|\(rp\)|\( rp \))\b/i,
rt: /\b(rt|\(rt\)|\( rt \))\b/i
};
for (let i = headerRowIndex + 1; i < data.length; i++) {
const row = data[i];
if (!Array.isArray(row) || row.length < Math.max(courseCodeCol, creditsCol, gradePointsCol) + 1) {
continue;
}
const courseCode = String(row[courseCodeCol] || '').trim();
const creditsValue = row[creditsCol];
const gradePointsValue = row[gradePointsCol];
// Skip if course code doesn't look valid
if (!courseCode || courseCode.toLowerCase().includes('summary') || courseCode.toLowerCase().includes('total')) {
continue;
}
// Check for retake notation efficiently
const rowText = row.join(' ').toLowerCase();
const hasRP = retakePatterns.rp.test(rowText);
const hasRT = retakePatterns.rt.test(rowText);
const isRetake = hasRP || hasRT;
const retakeType = isRetake ? (hasRP && hasRT ? 'RP/RT' : (hasRP ? 'RP' : 'RT')) : null;
// Parse numeric values
let credits = parseFloat(creditsValue);
const gradePoints = parseFloat(gradePointsValue);
// Handle failed courses
const isFailedCourse = credits === 0 && gradePoints === 0;
const isPrepCourse = this.isPrepCourse(courseCode.toUpperCase());
if (isFailedCourse && !isPrepCourse) {
credits = this.getStandardCredits(courseCode.toUpperCase());
}
// Validate values
if (!this.isValidCourse(credits, gradePoints)) {
continue;
}
const courseData = {
courseCode: courseCode.toUpperCase(),
credits,
gradePoints,
qualityPoints: credits * gradePoints,
isManuallyAdded: false,
isRetake,
retakeType,
isFailed: isFailedCourse && !isPrepCourse
};
this.handleDuplicateCourse(courseMap, courseData);
}
// Convert the course map to arrays
this.courses = Array.from(courseMap.values());
this.originalCourses = this.courses.map(course => ({...course}));
}
/**
* Calculate CGPA from parsed courses
*/
calculateCGPA() {
if (this.courses.length === 0) return 0;
const totalQualityPoints = this.courses.reduce((sum, course) => sum + course.qualityPoints, 0);
const totalCredits = this.courses.reduce((sum, course) => sum + course.credits, 0);
return totalCredits > 0 ? (totalQualityPoints / totalCredits) : 0;
}
/**
* Calculate original CGPA from original courses (fixed value)
*/
calculateOriginalCGPA() {
if (this.originalCourses.length === 0) return 0;
const totalQualityPoints = this.originalCourses.reduce((sum, course) => sum + course.qualityPoints, 0);
const totalCredits = this.originalCourses.reduce((sum, course) => sum + course.credits, 0);
return totalCredits > 0 ? (totalQualityPoints / totalCredits) : 0;
}
/**
* Calculate total earned credits (excluding failed courses)
*/
calculateEarnedCredits() {
if (this.courses.length === 0) return 0;
return this.courses.reduce((sum, course) => {
// If it's a failed course (isFailed = true), don't count it as earned
// Failed courses are those with 0 grade points originally
if (course.isFailed || course.gradePoints === 0) {
return sum;
}
return sum + course.credits;
}, 0);
}
/**
* Calculate total credit courses (courses that have credits > 0)
*/
calculateCreditCourses() {
if (this.courses.length === 0) return 0;
return this.courses.filter(course => course.credits > 0).length;
}
/**
* Calculate CGPA rounded according to BRAC University grading system
* (The CGPA gets rounded up if the third decimal digit is 5 or more)
*/
calculateActualCGPA(cgpa) {
// Round to 2 decimal places according to BRACU system
// If third decimal is 5 or more, round up
const multiplied = cgpa * 100;
const thirdDecimal = Math.floor((cgpa * 1000) % 10);
if (thirdDecimal >= 5) {
return Math.ceil(multiplied) / 100;
} else {
return Math.floor(multiplied) / 100;
}
}
/**
* Check if there are any invalid inputs in the table
*/
hasInvalidInputs() {
const invalidInputs = document.querySelectorAll('.grade-input.invalid-input');
return invalidInputs.length > 0;
}
/**
* Lock or unlock input fields based on validation state
*/
updateInputLockState() {
const hasInvalid = this.hasInvalidInputs();
const allInputs = document.querySelectorAll('.grade-input');
const addCourseBtn = document.getElementById('addCourseBtn');
// Use DocumentFragment for better performance
allInputs.forEach(input => {
if (hasInvalid) {
// If this input is not the invalid one, disable it
if (!input.classList.contains('invalid-input')) {
input.disabled = true;
input.classList.add('locked-input');
}
} else {
// Re-enable all inputs
input.disabled = false;
input.classList.remove('locked-input');
}
});
// Disable/enable add course button
if (addCourseBtn) {
addCourseBtn.disabled = hasInvalid;
if (hasInvalid) {
addCourseBtn.classList.add('disabled');
} else {
addCourseBtn.classList.remove('disabled');
}
}
}
/**
* Update summary cards with current values
*/
updateSummaryCards() {
// Check for invalid inputs before calculating
if (this.hasInvalidInputs()) {
// Show error message and prevent calculation
const summaryCards = document.querySelectorAll('.summary-card .value');
summaryCards.forEach(card => {
card.textContent = '--';
});
return;
}
// Cache DOM queries for better performance
const elements = {
totalCourses: document.getElementById('totalCourses'),
creditCourses: document.getElementById('creditCourses'),
totalCredits: document.getElementById('totalCredits'),
earnedCredits: document.getElementById('earnedCredits'),
currentCGPA: document.getElementById('currentCGPA'),
currentActualCGPA: document.getElementById('currentActualCGPA'),
dreamCGPA: document.getElementById('dreamCGPA'),
dreamActualCGPA: document.getElementById('dreamActualCGPA')
};
elements.totalCourses.textContent = this.courses.length;
elements.creditCourses.textContent = this.calculateCreditCourses();
elements.totalCredits.textContent = this.courses.reduce((sum, course) => sum + course.credits, 0).toFixed(2);
elements.earnedCredits.textContent = this.calculateEarnedCredits().toFixed(2);
// If no courses have been deleted and no grade changes, show original CGPA
// Otherwise, show the current calculated CGPA for both
const currentCGPA = this.calculateCGPA();
const originalCGPA = this.calculateOriginalCGPA();
// Calculate actual CGPAs according to BRACU rounding system
const currentActualCGPA = this.calculateActualCGPA(originalCGPA);
const dreamActualCGPA = this.calculateActualCGPA(currentCGPA);
// Check if any courses have been deleted or grades modified
const coursesDeleted = this.courses.length < this.originalCourses.length;
const gradesModified = this.courses.some((course, index) => {
if (course.isManuallyAdded) return false; // Manually added courses don't affect this check
const original = this.originalCourses.find(orig => orig.courseCode === course.courseCode);
return original && Math.abs(original.gradePoints - course.gradePoints) > 0.001;
});
// Current CGPA: always show original CGPA (unchanged)
elements.currentCGPA.textContent = originalCGPA.toFixed(4);
elements.currentActualCGPA.textContent = currentActualCGPA.toFixed(2);
// Dream CGPA: always show current calculated value (reflects all changes)
elements.dreamCGPA.textContent = currentCGPA.toFixed(4);
elements.dreamActualCGPA.textContent = dreamActualCGPA.toFixed(2);
}
/**
* Debounce timer for real-time updates
*/
debounceTimer = null;
/**
* Real-time grade point update with debouncing
*/
updateGradePointsRealtime(courseIndex, newGradePoints) {
// Clear previous timer
if (this.debounceTimer) {
clearTimeout(this.debounceTimer);
}
// Validate and update UI immediately for visual feedback
const input = document.querySelector(`input[data-course-index="${courseIndex}"]`);
const gradePoints = parseFloat(newGradePoints);
if (isNaN(gradePoints) || gradePoints < 0 || gradePoints > 4) {
input.classList.add('invalid-input');
} else {
input.classList.remove('invalid-input');
}
// Lock/unlock other inputs based on validation state
this.updateInputLockState();
// Increase debounce time for better performance on low-end devices
// Set new timer - update after 800ms of no typing
this.debounceTimer = setTimeout(() => {
this.updateGradePoints(courseIndex, newGradePoints);
}, 800);
}
/**
* Update grade points for a specific course
*/
updateGradePoints(courseIndex, newGradePoints) {
const gradePoints = parseFloat(newGradePoints);
const input = document.querySelector(`input[data-course-index="${courseIndex}"]`);
// Validate grade points
if (isNaN(gradePoints) || gradePoints < 0 || gradePoints > 4) {
input.classList.add('invalid-input');
this.showError('Grade points must be between 0.00 and 4.00. Please fix invalid inputs to calculate results.');
return;
}
// Remove invalid styling if input is now valid
input.classList.remove('invalid-input');
// Update course data
this.courses[courseIndex].gradePoints = gradePoints;
this.courses[courseIndex].qualityPoints = this.courses[courseIndex].credits * gradePoints;
// Update summary cards
this.updateSummaryCards();
// Update input lock state
this.updateInputLockState();
}
/**
* Reset all courses to their original grade points
*/
resetToOriginal() {
if (this.originalCourses.length === 0) {
this.showError('No original data to reset to');
return;
}
// Reset courses to original values
this.courses = this.originalCourses.map(course => ({...course}));
// Update display
this.displayResults();
this.showSuccessMessage('Reset to original grade points');
// Clear any locked state
this.updateInputLockState();
}
/**
* Export course data to Excel file
*/
exportToExcel() {
if (this.courses.length === 0) {
this.showError('No courses to export');
return;
}
try {
// Prepare data for Excel
const exportData = this.courses.map(course => ({
'Course Code': course.courseCode,
'Credits Earned': course.credits,
'Grade Points': course.gradePoints.toFixed(2),
'Type': course.isManuallyAdded ? 'Manual' : (course.isRetake ? `Retake (${course.retakeType || 'RP/RT'})` : 'From Grade Sheet')
}));
// Add summary information
const currentCGPA = this.calculateOriginalCGPA();
const dreamCGPA = this.calculateCGPA();
const totalCredits = this.courses.reduce((sum, course) => sum + course.credits, 0);
const earnedCredits = this.calculateEarnedCredits();
const creditCourses = this.calculateCreditCourses();
const currentActualCGPA = this.calculateActualCGPA(currentCGPA);
const dreamActualCGPA = this.calculateActualCGPA(dreamCGPA);
const summaryData = [
{},
{ 'Course Code': 'SUMMARY', 'Credits Earned': '', 'Grade Points': '', 'Type': '' },
{ 'Course Code': 'Total Courses', 'Credits Earned': this.courses.length, 'Grade Points': '', 'Type': '' },
{ 'Course Code': 'Credit Courses', 'Credits Earned': creditCourses, 'Grade Points': '', 'Type': '' },
{ 'Course Code': 'Total Credits', 'Credits Earned': totalCredits.toFixed(2), 'Grade Points': '', 'Type': '' },
{ 'Course Code': 'Earned Credits', 'Credits Earned': earnedCredits.toFixed(2), 'Grade Points': '', 'Type': '' },
{ 'Course Code': 'Current CGPA', 'Credits Earned': currentCGPA.toFixed(4), 'Grade Points': '', 'Type': '' },
{ 'Course Code': 'Current Actual CGPA', 'Credits Earned': currentActualCGPA.toFixed(2), 'Grade Points': '', 'Type': '' },
{ 'Course Code': 'Dream CGPA', 'Credits Earned': dreamCGPA.toFixed(4), 'Grade Points': '', 'Type': '' },
{ 'Course Code': 'Dream Actual CGPA', 'Credits Earned': dreamActualCGPA.toFixed(2), 'Grade Points': '', 'Type': '' }
];
// Combine course data with summary
const finalData = [...exportData, ...summaryData];
// Create workbook
const ws = XLSX.utils.json_to_sheet(finalData);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Course Analysis");
// Set column widths
ws['!cols'] = [
{ wch: 15 }, // Course Code
{ wch: 12 }, // Credits Earned
{ wch: 12 }, // Grade Points
{ wch: 15 } // Type
];
// Generate filename with current date
const now = new Date();
const dateStr = now.toISOString().split('T')[0];
const filename = `should-i-retake-analysis-${dateStr}.xlsx`;
// Save the file
XLSX.writeFile(wb, filename);
this.showSuccessMessage('Excel file exported successfully!');
} catch (error) {
console.error('Export error:', error);
this.showError('Failed to export to Excel. Please try again.');
}
}
/**
* Display parsed results on the webpage
*/
displayResults() {
// Update summary cards
this.updateSummaryCards();
// Populate course table with editable grade points
const tableBody = document.getElementById('courseTableBody');
tableBody.innerHTML = '';
this.courses.forEach((course, index) => {
const row = document.createElement('tr');
row.innerHTML = `
<td class="course-code">
${course.courseCode}
${course.isManuallyAdded ? '<span class="manual-course-tag">Manual</span>' : ''}
${course.isFailed ? '<span class="failed-course-tag">(F)</span>' : ''}
</td>
<td>${course.credits.toFixed(2)}</td>
<td>
<input type="number"
class="grade-input"
value="${course.gradePoints.toFixed(2)}"
min="0"
max="4"
step="0.01"
data-course-index="${index}"
title="Updates automatically as you type"
oninput="analyzer.updateGradePointsRealtime(${index}, this.value)"
onchange="analyzer.updateGradePoints(${index}, this.value)"
onkeypress="if(event.key==='Enter'){this.blur();}">
</td>
<td class="actions-column">
<button class="delete-course-btn" onclick="analyzer.deleteCourse(${index})" title="Delete Course">Delete</button>
</td>
`;
tableBody.appendChild(row);
});
this.showResults();
}
/**
* Get the specific retake type for a course (RT, RP, or RP/RT)
*/
getRetakeType(course, index) {
// If the course has specific retake type stored, use it
if (course.retakeType) {
return course.retakeType;
}
// Default to RP/RT if we can't determine the specific type
return 'RP/RT';
}
/**
* Add a new editable course row to the table
*/
addNewCourseRow() {
const tableBody = document.getElementById('courseTableBody');
// Check if there's already an editable row
if (tableBody.querySelector('.editable-row')) {
this.showError('Please complete or cancel the current course entry first.');
return;
}
const row = document.createElement('tr');
row.className = 'editable-row';