-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.js
More file actions
3241 lines (2764 loc) · 103 KB
/
dashboard.js
File metadata and controls
3241 lines (2764 loc) · 103 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
// Dashboard logic for Auxa
let userCredentials = null;
const TEXT_FILE_EXTENSIONS = [
'txt', 'md', 'json', 'py', 'js', 'ts', 'jsx', 'tsx',
'go', 'c', 'cpp', 'h', 'hpp', 'java', 'cs', 'php',
'rb', 'rs', 'swift', 'kt', 'scala', 'r', 'sh', 'bash',
'sql', 'html', 'css', 'scss', 'xml', 'yaml', 'yml',
'csv', 'tex'
];
const IMAGE_FILE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'tiff'];
const DOCUMENT_OCR_PAGE_LIMIT = 5;
const DOCX_OCR_IMAGE_LIMIT = 5;
const OCR_CHARACTER_LIMIT = 6000;
const VISION_MODEL_KEYWORDS = ['gpt-4o', 'gpt-4.1', 'gpt-5'];
const VISION_MAX_ANALYSES_PER_SUBMISSION = 3;
const OCR_TEXT_HEAVY_THRESHOLD = 220;
const OCR_TEXT_MIN_THRESHOLD = 40;
const EDGE_DENSITY_VISION_THRESHOLD = 0.12;
const COLOR_DIVERSITY_THRESHOLD = 45;
const VISION_IMAGE_MAX_DIMENSION = 768;
const TESSERACT_RESOURCES = {
workerPath: 'https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/worker.min.js',
langPath: 'https://cdn.jsdelivr.net/npm/tesseract.js@5/languages/',
corePath: 'https://cdn.jsdelivr.net/npm/tesseract.js-core@5/dist/tesseract-core.wasm.js'
};
let ocrWorkerPromise = null;
document.addEventListener('DOMContentLoaded', async () => {
// Check if user is logged in
userCredentials = await window.secureStorage.getCredentials();
if (!userCredentials || !userCredentials.token || !userCredentials.school) {
// Redirect back to login if no credentials
window.location.href = 'index.html';
return;
}
// Initialize navigation
initNavigation();
// Initialize settings
await initSettings();
// Initialize rubrics
initRubrics();
// Initialize assignments view
initAssignmentsView();
// Initialize submissions view
initSubmissionsView();
// Load courses
loadCourses();
});
// Navigation between views
function initNavigation() {
const navButtons = document.querySelectorAll('.nav-btn');
const views = document.querySelectorAll('.view');
navButtons.forEach(button => {
button.addEventListener('click', () => {
const viewName = button.getAttribute('data-view');
// Update active button
navButtons.forEach(btn => btn.classList.remove('active'));
button.classList.add('active');
// Update active view
views.forEach(view => view.classList.remove('active'));
document.getElementById(`${viewName}-view`).classList.add('active');
});
});
}
// Initialize settings view
async function initSettings() {
document.getElementById('settings-token').value = userCredentials.token ? '••••••••••••••••' : '';
document.getElementById('settings-school').value = userCredentials.school || '';
// Disconnect button
document.querySelector('.disconnect-btn').addEventListener('click', async () => {
if (confirm('Are you sure you want to disconnect from Canvas?')) {
await window.secureStorage.deleteCredentials();
window.location.href = 'index.html';
}
});
// AI Platform settings
await initAISettings();
}
// Model options for each platform
const AI_MODELS = {
openai: {
text: [
{ value: 'gpt-5', label: 'GPT-5 (gpt-5) (Recommended)' },
{ value: 'gpt-5-mini', label: 'GPT-5 Mini (gpt-5-mini)' },
{ value: 'gpt-5-nano', label: 'GPT-5 Nano (gpt-5-nano)' },
{ value: 'gpt-4.1', label: 'GPT-4.1 (gpt-4.1)' },
{ value: 'gpt-4.1-mini', label: 'GPT-4.1 Mini (gpt-4.1-mini) (Cheapest)' },
{ value: 'gpt-4o', label: 'GPT-4o (gpt-4o) (Recommended)' },
{ value: 'gpt-4o-mini', label: 'GPT-4o Mini (gpt-4o-mini)' }
],
audio: [
{ value: 'gpt-4o-transcribe', label: 'GPT-4o Transcribe (gpt-4o-transcribe)' },
{ value: 'gpt-4o-mini-transcribe', label: 'GPT-4o Mini Transcribe (gpt-4o-mini-transcribe)' }
]
},
anthropic: {
text: [
{ value: 'claude-sonnet-4-5-20250929', label: 'Sonnet 4.5 (claude-sonnet-4-5-20250929) (Recommended)' },
{ value: 'claude-opus-4-1-20250805', label: 'Opus 4.1 (claude-opus-4-1-20250805)' },
{ value: 'claude-haiku-4-5-20251001', label: 'Haiku 4.5 (claude-haiku-4-5-20251001) (Cheapest)' }
],
audio: [] // Anthropic doesn't support audio
},
google: {
text: [
{ value: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro (gemini-2.5-pro) (Recommended)' },
{ value: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash (gemini-2.5-flash)' },
{ value: 'gemini-2.5-flash-lite', label: 'Gemini 2.5 Flash Lite (gemini-2.5-flash-lite) (Cheapest)' }
],
audio: [
{ value: 'gemini-2.5-pro-preview-tts', label: 'Gemini 2.5 Pro Preview TTS (gemini-2.5-pro-preview-tts)' },
{ value: 'gemini-2.5-flash-preview-tts', label: 'Gemini 2.5 Flash Preview TTS (gemini-2.5-flash-preview-tts)' }
]
}
};
// Initialize AI platform settings
async function initAISettings() {
const platformSelect = document.getElementById('ai-platform-select');
const apiKeySection = document.getElementById('api-key-section');
const apiKeyInput = document.getElementById('ai-api-key');
const textModelSection = document.getElementById('text-model-section');
const textModelSelect = document.getElementById('ai-text-model');
const audioModelSection = document.getElementById('audio-model-section');
const audioModelSelect = document.getElementById('ai-audio-model');
const systemPromptSection = document.getElementById('system-prompt-section');
const systemPromptInput = document.getElementById('ai-system-prompt');
const saveBtn = document.getElementById('save-ai-settings');
// Load saved AI settings
const savedPlatform = localStorage.getItem('aiPlatform');
const savedTextModel = localStorage.getItem('aiTextModel');
const savedAudioModel = localStorage.getItem('aiAudioModel');
const savedSystemPrompt = localStorage.getItem('aiSystemPrompt');
let savedApiKey = null;
if (window.secureStorage && typeof window.secureStorage.getAIKey === 'function') {
try {
savedApiKey = await window.secureStorage.getAIKey();
} catch (error) {
console.error('Failed to load saved AI key:', error);
savedApiKey = null;
}
}
// Migrate legacy localStorage key if present and no secure key stored
if (!savedApiKey) {
const legacyKey = localStorage.getItem('aiApiKey');
if (legacyKey && window.secureStorage && typeof window.secureStorage.saveAIKey === 'function') {
try {
const result = await window.secureStorage.saveAIKey(legacyKey);
if (result && result.success) {
savedApiKey = legacyKey;
}
} catch (error) {
console.error('Failed to migrate legacy AI key to secure storage:', error);
} finally {
localStorage.removeItem('aiApiKey');
}
}
}
if (savedPlatform) {
platformSelect.value = savedPlatform;
apiKeySection.style.display = 'block';
textModelSection.style.display = 'block';
systemPromptSection.style.display = 'block';
saveBtn.style.display = 'block';
// Show platform info
showPlatformInfo(savedPlatform);
// Show appropriate API key link
showApiKeyLink(savedPlatform);
// Populate model dropdowns
populateModelDropdowns(savedPlatform);
// Show audio model section if platform supports it
if (AI_MODELS[savedPlatform].audio.length > 0) {
audioModelSection.style.display = 'block';
}
if (savedApiKey) {
apiKeyInput.value = '••••••••••••••••';
apiKeyInput.setAttribute('data-has-key', 'true');
savedApiKey = null;
}
if (savedTextModel) {
textModelSelect.value = savedTextModel;
}
if (savedAudioModel) {
audioModelSelect.value = savedAudioModel;
}
if (savedSystemPrompt) {
systemPromptInput.value = savedSystemPrompt;
}
}
// Platform selection handler
platformSelect.addEventListener('change', (e) => {
const platform = e.target.value;
if (platform) {
apiKeySection.style.display = 'block';
textModelSection.style.display = 'block';
systemPromptSection.style.display = 'block';
saveBtn.style.display = 'block';
apiKeyInput.value = '';
apiKeyInput.removeAttribute('data-has-key');
// Show appropriate API key link
showApiKeyLink(platform);
// Populate model dropdowns
populateModelDropdowns(platform);
// Show/hide audio model section based on platform
if (AI_MODELS[platform].audio.length > 0) {
audioModelSection.style.display = 'block';
} else {
audioModelSection.style.display = 'none';
}
// Show platform-specific warnings/info
showPlatformInfo(platform);
} else {
apiKeySection.style.display = 'none';
textModelSection.style.display = 'none';
audioModelSection.style.display = 'none';
systemPromptSection.style.display = 'none';
saveBtn.style.display = 'none';
document.getElementById('platform-warning').style.display = 'none';
// Hide all API key links
showApiKeyLink(null);
}
});
// API key input - clear placeholder when typing
apiKeyInput.addEventListener('focus', () => {
if (apiKeyInput.getAttribute('data-has-key') === 'true') {
apiKeyInput.value = '';
apiKeyInput.removeAttribute('data-has-key');
}
});
// Save AI settings
saveBtn.addEventListener('click', async () => {
const platform = platformSelect.value;
const apiKey = apiKeyInput.value.trim();
const textModel = textModelSelect.value;
const audioModel = audioModelSelect.value;
const systemPrompt = systemPromptInput.value.trim();
if (!platform) {
alert('Please select an LLM API platform');
return;
}
if (!textModel) {
alert('Please select a text model');
return;
}
// If no new key entered and we have an existing key, keep it
if (!apiKey && apiKeyInput.getAttribute('data-has-key') === 'true') {
alert('LLM API platform updated (API key unchanged)');
localStorage.setItem('aiPlatform', platform);
localStorage.setItem('aiTextModel', textModel);
localStorage.setItem('aiAudioModel', audioModel);
localStorage.setItem('aiSystemPrompt', systemPrompt);
localStorage.removeItem('aiApiKey');
return;
}
if (!apiKey) {
alert('Please enter your API key');
return;
}
// Validate API key format based on platform
if (!validateApiKey(platform, apiKey)) {
alert('Invalid API key format for ' + getPlatformName(platform));
return;
}
let saveResult = null;
let usedFallbackStorage = false;
if (window.secureStorage && typeof window.secureStorage.saveAIKey === 'function') {
try {
saveResult = await window.secureStorage.saveAIKey(apiKey);
} catch (error) {
console.error('Failed to save AI key securely:', error);
saveResult = { success: false, error: error.message };
}
if (!saveResult || saveResult.success === false) {
alert('Failed to save AI API key securely.' + (saveResult && saveResult.error ? `\nReason: ${saveResult.error}` : ''));
return;
}
} else {
// Fallback (should not happen in production)
localStorage.setItem('aiApiKey', apiKey);
usedFallbackStorage = true;
}
// Save non-sensitive preferences
localStorage.setItem('aiPlatform', platform);
localStorage.setItem('aiTextModel', textModel);
localStorage.setItem('aiAudioModel', audioModel);
localStorage.setItem('aiSystemPrompt', systemPrompt);
if (!usedFallbackStorage) {
localStorage.removeItem('aiApiKey'); // Ensure plaintext key is cleared
}
// Update UI
apiKeyInput.value = '••••••••••••••••';
apiKeyInput.setAttribute('data-has-key', 'true');
alert('AI settings saved successfully!\n\nPlatform: ' + getPlatformName(platform) +
'\nText Model: ' + textModel +
(audioModel ? '\nAudio Model: ' + audioModel : '') +
(systemPrompt ? '\nCustom system prompt saved' : '\nUsing default system prompt'));
});
}
// Populate model dropdowns based on platform
function populateModelDropdowns(platform) {
const textModelSelect = document.getElementById('ai-text-model');
const audioModelSelect = document.getElementById('ai-audio-model');
// Clear existing options (except the first "Select a model..." option)
textModelSelect.innerHTML = '<option value="">Select a model...</option>';
audioModelSelect.innerHTML = '<option value="">Select a model...</option>';
if (!platform || !AI_MODELS[platform]) return;
// Populate text models
AI_MODELS[platform].text.forEach(model => {
const option = document.createElement('option');
option.value = model.value;
option.textContent = model.label;
textModelSelect.appendChild(option);
});
// Populate audio models (if available)
AI_MODELS[platform].audio.forEach(model => {
const option = document.createElement('option');
option.value = model.value;
option.textContent = model.label;
audioModelSelect.appendChild(option);
});
}
// Validate API key format
function validateApiKey(platform, key) {
if (!key) return false;
switch(platform) {
case 'openai':
return key.startsWith('sk-');
case 'anthropic':
return key.startsWith('sk-ant-');
case 'google':
return key.length > 20; // Basic validation for Google API keys
default:
return false;
}
}
// Get platform display name
function getPlatformName(platform) {
const names = {
'openai': 'OpenAI',
'anthropic': 'Anthropic (Claude)',
'google': 'Google (Gemini)'
};
return names[platform] || platform;
}
// Show platform-specific information/warnings
function showPlatformInfo(platform) {
const warningContainer = document.getElementById('platform-warning');
const anthropicWarning = document.getElementById('anthropic-warning');
const openaiInfo = document.getElementById('openai-info');
const googleInfo = document.getElementById('google-info');
// Hide all first
anthropicWarning.style.display = 'none';
openaiInfo.style.display = 'none';
googleInfo.style.display = 'none';
// Show appropriate one
switch(platform) {
case 'anthropic':
warningContainer.style.display = 'block';
anthropicWarning.style.display = 'block';
break;
case 'openai':
warningContainer.style.display = 'block';
openaiInfo.style.display = 'block';
break;
case 'google':
warningContainer.style.display = 'block';
googleInfo.style.display = 'block';
break;
default:
warningContainer.style.display = 'none';
}
}
// Show appropriate API key link based on platform
function showApiKeyLink(platform) {
const openaiLink = document.getElementById('openai-key-link');
const googleLink = document.getElementById('google-key-link');
const anthropicLink = document.getElementById('anthropic-key-link');
// Hide all first
openaiLink.style.display = 'none';
googleLink.style.display = 'none';
anthropicLink.style.display = 'none';
// Show appropriate one
switch(platform) {
case 'openai':
openaiLink.style.display = 'inline';
break;
case 'google':
googleLink.style.display = 'inline';
break;
case 'anthropic':
anthropicLink.style.display = 'inline';
break;
}
}
// Load courses from Canvas API via backend
async function loadCourses() {
const coursesList = document.getElementById('courses-list');
try {
const response = await fetch('http://localhost:3000/api/courses', {
headers: {
'Authorization': userCredentials.token,
'X-School-URL': userCredentials.school
}
});
if (!response.ok) {
throw new Error('Failed to fetch courses');
}
const courses = await response.json();
// Clear loading message
coursesList.innerHTML = '';
if (courses.length === 0) {
coursesList.innerHTML = `
<div class="empty-message">
<p>No TA courses found</p>
<p style="font-size: 14px; color: #888;">You are not currently a TA for any courses</p>
</div>
`;
return;
}
// Display courses
for (const course of courses) {
// Fetch ungraded count for each course
const ungradedCount = await getUngradedCountForCourse(course.id);
const courseData = {
id: course.id,
name: course.name,
code: course.course_code,
ungraded: ungradedCount,
total: course.total_students || 0
};
const courseCard = createCourseCard(courseData);
coursesList.appendChild(courseCard);
}
} catch (error) {
console.error('Error loading courses:', error);
coursesList.innerHTML = `
<div class="empty-message">
<p>Failed to load courses</p>
<p style="font-size: 14px; color: #888;">Make sure the backend server is running on port 3000</p>
</div>
`;
}
}
// Get ungraded submission count for a course
async function getUngradedCountForCourse(courseId) {
try {
// Get all assignments for the course
const response = await fetch(`http://localhost:3000/api/courses/${courseId}/assignments`, {
headers: {
'Authorization': userCredentials.token,
'X-School-URL': userCredentials.school
}
});
if (!response.ok) {
return 0;
}
const assignments = await response.json();
let totalUngraded = 0;
// Sum up needs_grading_count from all assignments, excluding quizzes
for (const assignment of assignments) {
// Skip quizzes (online_quiz or none submission types)
const isQuiz = assignment.submission_types &&
(assignment.submission_types.includes('online_quiz') ||
assignment.submission_types.includes('none'));
if (!isQuiz) {
totalUngraded += assignment.needs_grading_count || 0;
}
}
return totalUngraded;
} catch (error) {
console.error(`Error fetching ungraded count for course ${courseId}:`, error);
return 0;
}
}
// Create a course card element
function createCourseCard(course) {
const card = document.createElement('div');
card.className = 'course-card';
card.onclick = () => openCourse(course);
card.innerHTML = `
<div class="course-name">${course.name}</div>
<div class="course-code">${course.code}</div>
<div class="course-stats">
<div class="stat-item">
<div class="stat-label">Ungraded</div>
<div class="stat-value">${course.ungraded}</div>
</div>
<div class="stat-item">
<div class="stat-label">Total Students</div>
<div class="stat-value">${course.total}</div>
</div>
</div>
`;
return card;
}
// Open course details - show assignments with ungraded submissions
async function openCourse(course) {
console.log('Opening course:', course);
// Switch to assignments view
document.querySelectorAll('.view').forEach(v => v.classList.remove('active'));
document.getElementById('assignments-view').classList.add('active');
// Update header
document.getElementById('assignment-course-title').textContent = course.name;
document.getElementById('assignment-course-subtitle').textContent = `${course.code} - Assignments with ungraded submissions`;
// Load assignments
await loadCourseAssignmentsView(course.id);
}
// Initialize assignments view
function initAssignmentsView() {
const backBtn = document.getElementById('back-to-courses');
backBtn.addEventListener('click', () => {
// Switch back to courses view
document.querySelectorAll('.view').forEach(v => v.classList.remove('active'));
document.getElementById('courses-view').classList.add('active');
});
}
// Initialize submissions view
function initSubmissionsView() {
const backBtn = document.getElementById('back-to-assignments');
backBtn.addEventListener('click', () => {
// Switch back to assignments view
document.querySelectorAll('.view').forEach(v => v.classList.remove('active'));
document.getElementById('assignments-view').classList.add('active');
});
}
// Load assignments for a course (only those with ungraded submissions)
async function loadCourseAssignmentsView(courseId) {
const assignmentsList = document.getElementById('assignments-list');
assignmentsList.innerHTML = '<div class="loading-message"><p>Loading assignments...</p></div>';
try {
// Fetch assignments
const response = await fetch(`http://localhost:3000/api/courses/${courseId}/assignments`, {
headers: {
'Authorization': userCredentials.token,
'X-School-URL': userCredentials.school
}
});
if (!response.ok) {
throw new Error('Failed to fetch assignments');
}
const assignments = await response.json();
// Filter assignments with ungraded submissions and exclude quizzes
const ungradedAssignments = assignments.filter(a => {
// Check if it has ungraded submissions
if (a.needs_grading_count <= 0) return false;
// Exclude quizzes (online_quiz or none submission types)
const isQuiz = a.submission_types &&
(a.submission_types.includes('online_quiz') ||
a.submission_types.includes('none'));
return !isQuiz; // Only include non-quiz assignments
});
if (ungradedAssignments.length === 0) {
assignmentsList.innerHTML = `
<div class="empty-message">
<p>No assignments with ungraded submissions.</p>
</div>
`;
return;
}
// Display assignments
assignmentsList.innerHTML = '';
ungradedAssignments.forEach(assignment => {
const assignmentCard = createAssignmentCard(assignment, courseId);
assignmentsList.appendChild(assignmentCard);
});
} catch (error) {
console.error('Error loading assignments:', error);
assignmentsList.innerHTML = `
<div class="empty-message">
<p>Failed to load assignments</p>
<p style="font-size: 14px; color: #888; margin-top: 8px;">Please try again</p>
</div>
`;
}
}
// Create assignment card element
function createAssignmentCard(assignment, courseId) {
const card = document.createElement('div');
card.className = 'assignment-card';
// Format due date
let dueText = 'No due date';
if (assignment.due_at) {
const dueDate = new Date(assignment.due_at);
const now = new Date();
const isPast = dueDate < now;
dueText = isPast ?
`Due: ${dueDate.toLocaleDateString()} (past due)` :
`Due: ${dueDate.toLocaleDateString()}`;
}
// Escape assignment name for onclick
const escapedName = assignment.name.replace(/'/g, "\\'").replace(/"/g, '\\"');
card.innerHTML = `
<div class="assignment-header">
<div class="assignment-info">
<div class="assignment-name">${assignment.name}</div>
<div class="assignment-meta">
<div class="assignment-meta-item">
<span>Points: ${assignment.points_possible || 0}</span>
</div>
<div class="assignment-meta-item">
<span>Type: ${formatSubmissionType(assignment.submission_types)}</span>
</div>
</div>
</div>
<div class="assignment-badge ${assignment.needs_grading_count > 10 ? 'warning' : ''}">
${assignment.needs_grading_count}
</div>
</div>
<div class="assignment-footer">
<div class="assignment-due">${dueText}</div>
<div class="assignment-actions">
<button class="assignment-action-btn" onclick="startGrading(${courseId}, ${assignment.id}, '${escapedName}')">
Start Grading
</button>
</div>
</div>
`;
return card;
}
// Format submission types for display
function formatSubmissionType(types) {
if (!types || types.length === 0) return 'Unknown';
if (types.includes('online_quiz')) return 'Quiz';
if (types.includes('none')) return 'Quiz';
if (types.includes('online_text_entry')) return 'Text';
if (types.includes('online_upload')) return 'File Upload';
if (types.includes('online_url')) return 'URL';
return types[0].replace('online_', '').replace('_', ' ');
}
// Start grading - load submissions for an assignment
async function startGrading(courseId, assignmentId, assignmentName) {
console.log('Starting grading for assignment:', assignmentId, 'in course:', courseId);
// Switch to submissions view
document.querySelectorAll('.view').forEach(v => v.classList.remove('active'));
document.getElementById('submissions-view').classList.add('active');
// Update header
document.getElementById('submissions-assignment-title').textContent = assignmentName || 'Assignment Submissions';
document.getElementById('submissions-assignment-subtitle').textContent = 'Review and grade ungraded submissions';
// Load submissions
await loadSubmissionsView(courseId, assignmentId);
}
// Load submissions for an assignment
async function loadSubmissionsView(courseId, assignmentId) {
const submissionsList = document.getElementById('submissions-list');
submissionsList.innerHTML = '<div class="loading-message"><p>Loading submissions...</p></div>';
try {
// Fetch ungraded submissions
const response = await fetch(`http://localhost:3000/api/courses/${courseId}/assignments/${assignmentId}/ungraded`, {
headers: {
'Authorization': userCredentials.token,
'X-School-URL': userCredentials.school
}
});
if (!response.ok) {
throw new Error('Failed to fetch submissions');
}
const submissions = await response.json();
if (submissions.length === 0) {
submissionsList.innerHTML = `
<div class="empty-message">
<p>No ungraded submissions</p>
<p style="font-size: 14px; color: #888; margin-top: 8px;">All submissions have been graded! 🎉</p>
</div>
`;
return;
}
// Display submissions
submissionsList.innerHTML = '';
submissions.forEach(submission => {
const submissionCard = createSubmissionCard(submission, courseId, assignmentId);
submissionsList.appendChild(submissionCard);
});
} catch (error) {
console.error('Error loading submissions:', error);
submissionsList.innerHTML = `
<div class="empty-message">
<p>Failed to load submissions</p>
<p style="font-size: 14px; color: #888; margin-top: 8px;">Please try again</p>
</div>
`;
}
}
// Create avatar HTML component
function createAvatarHTML(avatarUrl, name) {
if (avatarUrl) {
return `<img src="${avatarUrl}" alt="${name}" class="user-avatar" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';" /><div class="user-avatar-fallback" style="display: none;">${getInitials(name)}</div>`;
} else {
return `<div class="user-avatar-fallback">${getInitials(name)}</div>`;
}
}
// Get initials from name for avatar fallback
function getInitials(name) {
if (!name) return '?';
const parts = name.trim().split(' ');
if (parts.length >= 2) {
return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}
return name.substring(0, 2).toUpperCase();
}
// Create submission card element
function createSubmissionCard(submission, courseId, assignmentId) {
const card = document.createElement('div');
card.className = 'submission-card';
// Format submission date
let submittedText = 'Not submitted';
if (submission.submitted_at) {
const submittedDate = new Date(submission.submitted_at);
submittedText = `Submitted: ${submittedDate.toLocaleString()}`;
}
// Get student info
const studentName = submission.user ? submission.user.name : 'Unknown Student';
const studentEmail = submission.user ? submission.user.email : '';
const avatarUrl = submission.user?.avatar_url;
// Create avatar HTML
const avatarHTML = createAvatarHTML(avatarUrl, studentName);
// Determine submission content preview
const contentPreview = getSubmissionContentPreview(submission);
card.innerHTML = `
<div class="submission-header">
${avatarHTML}
<div class="submission-student-info">
<div class="submission-student-name">${studentName}</div>
<div class="submission-student-email">${studentEmail}</div>
</div>
<div class="submission-meta">
<span class="submission-status ${submission.late ? 'late' : ''}">${submission.late ? '⚠️ Late' : '✓ On Time'}</span>
${submission.attempt > 1 ? `<span class="submission-attempt">Attempt ${submission.attempt}</span>` : ''}
</div>
</div>
<div class="submission-info">
<div class="submission-date">${submittedText}</div>
<div class="submission-type-badge">${formatSubmissionTypeBadge(submission.submission_type)}</div>
</div>
<div class="submission-content-preview">
${contentPreview}
</div>
<div class="submission-actions">
<button class="submission-action-btn primary" onclick="gradeSubmission(${courseId}, ${assignmentId}, ${submission.id}, ${submission.user_id})">
Grade Submission
</button>
<button class="submission-action-btn secondary" onclick="viewSubmissionDetails(${JSON.stringify(submission).replace(/"/g, '"')}, ${courseId})">
View Details
</button>
</div>
`;
return card;
}
// Get submission content preview based on type
function getSubmissionContentPreview(submission) {
switch (submission.submission_type) {
case 'online_text_entry':
// Show text preview
const textPreview = submission.body ?
submission.body.replace(/<[^>]*>/g, '').substring(0, 200) + '...' :
'No content';
return `
<div class="content-preview-text">
<strong>Text Submission:</strong><br>
${textPreview}
</div>
`;
case 'online_upload':
// Show file attachments
if (submission.attachments && submission.attachments.length > 0) {
const fileList = submission.attachments.map(file =>
`<div class="attachment-item">📎 ${file.filename} (${formatFileSize(file.size)})</div>`
).join('');
return `
<div class="content-preview-files">
<strong>Uploaded Files (${submission.attachments.length}):</strong><br>
${fileList}
</div>
`;
}
return '<div class="content-preview-text">No files attached</div>';
case 'media_recording':
// Show media recording info
if (submission.media_comment) {
const mediaType = submission.media_comment.media_type || 'media';
return `
<div class="content-preview-media">
<strong>${mediaType === 'video' ? '🎥' : '🎵'} ${mediaType.charAt(0).toUpperCase() + mediaType.slice(1)} Recording</strong><br>
${submission.media_comment.display_name || 'Media file'}
</div>
`;
}
return '<div class="content-preview-text">Media recording</div>';
case 'online_url':
// Show URL
return `
<div class="content-preview-url">
<strong>URL Submission:</strong><br>
<a href="${submission.url}" target="_blank">${submission.url}</a>
</div>
`;
default:
return `<div class="content-preview-text">Submission type: ${submission.submission_type}</div>`;
}
}
// Format submission type as badge
function formatSubmissionTypeBadge(type) {
const typeMap = {
'online_text_entry': '📝 Text Entry',
'online_upload': '📁 File Upload',
'media_recording': '🎥 Media Recording',
'online_url': '🔗 URL Submission'
};
return typeMap[type] || type;
}
// Format file size
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}
// Grade submission - Open grading modal
let currentGradingContext = null;
let currentMonacoEditor = null;
async function gradeSubmission(courseId, assignmentId, submissionId, userId) {
try {
// Fetch full submission details
const response = await fetch(`http://localhost:3000/api/courses/${courseId}/assignments/${assignmentId}/submissions`, {
headers: {
'Authorization': userCredentials.token,
'X-School-URL': userCredentials.school
}
});
if (!response.ok) {
throw new Error('Failed to fetch submission details');
}
const submissions = await response.json();
const submission = submissions.find(s => s.id === submissionId);
if (!submission) {
alert('Submission not found');
return;
}
// Fetch assignment details for rubric and points
const assignmentResponse = await fetch(`http://localhost:3000/api/courses/${courseId}/assignments`, {
headers: {
'Authorization': userCredentials.token,
'X-School-URL': userCredentials.school
}
});
const assignments = await assignmentResponse.json();
const assignment = assignments.find(a => a.id === assignmentId);
// Store context
currentGradingContext = {
courseId,
assignmentId,
submissionId,
userId,
submission,
assignment
};
// Open modal and load content
await openGradingModal(submission, assignment);
} catch (error) {
console.error('Error loading submission for grading:', error);
alert('Failed to load submission. Please try again.');