From c5f4b3b4ea2629f1699afa89fa19b18e8baaef78 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 22 Jul 2026 13:15:29 +0000 Subject: [PATCH 1/4] Initial plan From 79a4ae175d2102da8210819b98e95db09690fb79 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 22 Jul 2026 13:26:18 +0000 Subject: [PATCH 2/4] feat: add student exam center, submission review, and instructor view --- api/exam.go | 126 ++++++++++++++++++- api/exam_test.go | 87 +++++++++++++ database/database.go | 24 ++-- database/exam.go | 18 ++- models/models.go | 2 + router/router.go | 1 + static/dashboard.html | 3 + static/exam-center.html | 92 ++++++++++++++ static/exam-review.html | 158 ++++++++++++++++++++++++ static/js/admin/exams-page.js | 5 +- static/js/dashboard.js | 14 ++- static/js/exam-center.js | 153 +++++++++++++++++++++++ static/js/exam-review.js | 224 ++++++++++++++++++++++++++++++++++ 13 files changed, 892 insertions(+), 15 deletions(-) create mode 100644 static/exam-center.html create mode 100644 static/exam-review.html create mode 100644 static/js/exam-center.js create mode 100644 static/js/exam-review.js diff --git a/api/exam.go b/api/exam.go index 432cceb..09fa983 100644 --- a/api/exam.go +++ b/api/exam.go @@ -476,7 +476,131 @@ func (h *Handler) SubmitExamHandler(w http.ResponseWriter, r *http.Request) { }) } -// GetAvailableExamCategoriesHandler handles GET /instructor/exams/categories +// GetExamSubmissionHandler handles GET /exam/submission?attempt_id={id}&user_id={id} +// Returns the full detail of a submitted exam attempt (questions, answers, results). +// The requesting user must either own the attempt or be an admin. +func (h *Handler) GetExamSubmissionHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + attemptIDStr := r.URL.Query().Get("attempt_id") + attemptID, err := strconv.Atoi(attemptIDStr) + if err != nil || attemptID <= 0 { + http.Error(w, "Invalid attempt_id", http.StatusBadRequest) + return + } + + userIDStr := r.URL.Query().Get("user_id") + userID, err := strconv.Atoi(userIDStr) + if err != nil || userID <= 0 { + http.Error(w, "Invalid user_id", http.StatusBadRequest) + return + } + + attempt, err := h.db.GetExamAttempt(attemptID) + if err != nil { + if err == database.ErrNotFound { + http.Error(w, "Attempt not found", http.StatusNotFound) + return + } + h.logger.WithContext(r.Context()).WithError(err).Error("Failed to get exam attempt") + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Allow access if the requesting user owns the attempt or is an admin + if attempt.UserID != userID { + requestingUser, err := h.db.GetUser(userID) + if err != nil || !requestingUser.IsAdmin { + http.Error(w, "Forbidden", http.StatusForbidden) + return + } + } + + exam, err := h.db.GetExam(attempt.ExamID) + if err != nil { + h.logger.WithContext(r.Context()).WithError(err).Error("Failed to get exam for submission") + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + type submissionAnswer struct { + ID int `json:"id"` + AnswerText string `json:"answer_text"` + IsCorrect bool `json:"is_correct"` + } + type submissionQuestion struct { + ID int `json:"id"` + QuestionText string `json:"question_text"` + Category string `json:"category"` + Difficulty int `json:"difficulty"` + SelectedAnswerID int `json:"selected_answer_id"` + IsCorrect bool `json:"is_correct"` + Answers []submissionAnswer `json:"answers"` + } + + questions := make([]submissionQuestion, 0, len(exam.QuestionIDs)) + for _, qid := range exam.QuestionIDs { + q, err := h.db.GetQuestion(qid) + if err != nil { + continue + } + answers, err := h.db.GetAnswersByQuestion(qid) + if err != nil { + continue + } + + categoryLabel := "" + if topic, err := h.db.GetTopic(q.TopicID); err == nil { + categoryLabel = strings.TrimSpace(topic.Name) + if categoryLabel == "" { + categoryLabel = strings.TrimSpace(topic.Category) + } + } + if categoryLabel == "" && len(q.Tags) > 0 { + categoryLabel = strings.TrimSpace(q.Tags[0]) + } + + key := itoa(qid) + selectedAnswerID := attempt.Answers[key] + isCorrect := attempt.QuestionResults[key] + + sas := make([]submissionAnswer, len(answers)) + for i, a := range answers { + sas[i] = submissionAnswer{ + ID: a.ID, + AnswerText: a.AnswerText, + IsCorrect: a.IsCorrect, + } + } + + questions = append(questions, submissionQuestion{ + ID: q.ID, + QuestionText: q.QuestionText, + Category: categoryLabel, + Difficulty: q.Difficulty, + SelectedAnswerID: selectedAnswerID, + IsCorrect: isCorrect, + Answers: sas, + }) + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]interface{}{ + "attempt_id": attempt.ID, + "exam_id": attempt.ExamID, + "exam_name": exam.Name, + "completed_at": attempt.CompletedAt, + "score": attempt.Score, + "correct_answers": attempt.CorrectAnswers, + "total_questions": attempt.TotalQuestions, + "questions": questions, + }) +} + + // Returns all distinct topic categories available in the database. func (h *Handler) GetAvailableExamCategoriesHandler(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { diff --git a/api/exam_test.go b/api/exam_test.go index 7aef0d4..c563e09 100644 --- a/api/exam_test.go +++ b/api/exam_test.go @@ -616,3 +616,90 @@ func TestUnassignExamFromUserHandler_NotFound(t *testing.T) { t.Errorf("Expected status 404, got %d", w.Code) } } + +func TestGetExamSubmissionHandler(t *testing.T) { + db, admin, student := setupExamDB(t) + handler := NewHandler(db) + + questions, _ := db.ListQuestions() + qIDs := []int{questions[0].ID} + + exam := &models.Exam{ + Name: "Submission Exam", Categories: []string{"java"}, DifficultyLevels: []int{1, 2, 3}, + QuestionIDs: qIDs, QuestionCount: 1, AccessToken: "submissiontoken", + CreatedBy: admin.ID, CreatedAt: time.Now(), + } + db.CreateExam(exam) + db.AssignExamToUser(exam.ID, student.ID, admin.ID) + + // Create and submit an attempt + attempt := &models.ExamAttempt{ + ExamID: exam.ID, UserID: student.ID, StartedAt: time.Now(), + TotalQuestions: 1, Answers: map[string]int{}, QuestionResults: map[string]bool{}, + } + db.CreateExamAttempt(attempt) + + answers, _ := db.GetAnswersByQuestion(questions[0].ID) + var correctAnswerID int + for _, a := range answers { + if a.IsCorrect { + correctAnswerID = a.ID + break + } + } + db.SubmitExamAttempt(attempt.ID, map[string]int{fmt.Sprintf("%d", questions[0].ID): correctAnswerID}) + + t.Run("student can view own submission", func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, + fmt.Sprintf("/exam/submission?attempt_id=%d&user_id=%d", attempt.ID, student.ID), nil) + w := httptest.NewRecorder() + handler.GetExamSubmissionHandler(w, req) + if w.Code != http.StatusOK { + t.Fatalf("Expected 200, got %d: %s", w.Code, w.Body.String()) + } + var result map[string]interface{} + json.NewDecoder(w.Body).Decode(&result) + if result["exam_name"] != "Submission Exam" { + t.Errorf("Expected exam_name 'Submission Exam', got %v", result["exam_name"]) + } + qs, ok := result["questions"].([]interface{}) + if !ok || len(qs) == 0 { + t.Fatal("Expected questions in response") + } + }) + + t.Run("admin can view any submission", func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, + fmt.Sprintf("/exam/submission?attempt_id=%d&user_id=%d", attempt.ID, admin.ID), nil) + w := httptest.NewRecorder() + handler.GetExamSubmissionHandler(w, req) + if w.Code != http.StatusOK { + t.Fatalf("Expected 200, got %d: %s", w.Code, w.Body.String()) + } + }) + + t.Run("other student cannot view", func(t *testing.T) { + other := &models.User{Username: "other", Email: "other@test.com", IsAdmin: false} + db.CreateUser(other) + req := httptest.NewRequest(http.MethodGet, + fmt.Sprintf("/exam/submission?attempt_id=%d&user_id=%d", attempt.ID, other.ID), nil) + w := httptest.NewRecorder() + handler.GetExamSubmissionHandler(w, req) + if w.Code != http.StatusForbidden { + t.Errorf("Expected 403, got %d", w.Code) + } + }) + + t.Run("attempt_id includes attempt_id in status", func(t *testing.T) { + status, err := db.GetExamStatus(exam.ID) + if err != nil { + t.Fatal(err) + } + if len(status.StudentResults) == 0 { + t.Fatal("Expected at least one student result") + } + if status.StudentResults[0].AttemptID == nil { + t.Error("Expected AttemptID to be set in ExamStudentResult after submission") + } + }) +} diff --git a/database/database.go b/database/database.go index 3be2124..11c8697 100644 --- a/database/database.go +++ b/database/database.go @@ -2963,6 +2963,8 @@ func (db *InMemoryDB) GetAssignedExamsForUser(userID int) ([]*models.ExamInfo, e } if bestAttempt != nil { info.CompletedAt = bestAttempt.CompletedAt + aid := bestAttempt.ID + info.AttemptID = &aid ca := bestAttempt.CorrectAnswers info.CorrectAnswers = &ca tq := bestAttempt.TotalQuestions @@ -3077,17 +3079,25 @@ func (db *InMemoryDB) GetExamStatus(examID int) (*models.ExamStatus, error) { AssignedAt: a.AssignedAt, } // Find most recent completed attempt + var bestAttemptID int for _, att := range db.examAttempts { if att.ExamID == examID && att.UserID == a.UserID && att.CompletedAt != nil { - r.CompletedAt = att.CompletedAt - ca := att.CorrectAnswers - r.CorrectAnswers = &ca - tq := att.TotalQuestions - r.TotalQuestions = &tq - s := att.Score - r.Score = &s + if bestAttemptID == 0 || att.ID > bestAttemptID { + bestAttemptID = att.ID + r.CompletedAt = att.CompletedAt + ca := att.CorrectAnswers + r.CorrectAnswers = &ca + tq := att.TotalQuestions + r.TotalQuestions = &tq + s := att.Score + r.Score = &s + } } } + if bestAttemptID > 0 { + aid := bestAttemptID + r.AttemptID = &aid + } status.StudentResults = append(status.StudentResults, r) } return status, nil diff --git a/database/exam.go b/database/exam.go index 6fbedb7..9f2f4b5 100644 --- a/database/exam.go +++ b/database/exam.go @@ -274,7 +274,7 @@ func (db *SQLiteDB) GetAssignedExamsForUser(userID int) ([]*models.ExamInfo, err query := ` SELECT ea.id, ea.exam_id, ea.user_id, ea.assigned_at, ea.assigned_by, e.name, e.question_count, e.access_token, - att.completed_at, att.correct_answers, att.total_questions, att.score + att.id, att.completed_at, att.correct_answers, att.total_questions, att.score FROM exam_assignments ea JOIN exams e ON ea.exam_id = e.id LEFT JOIN exam_attempts att ON att.exam_id = e.id @@ -296,6 +296,7 @@ func (db *SQLiteDB) GetAssignedExamsForUser(userID int) ([]*models.ExamInfo, err var result []*models.ExamInfo for rows.Next() { info := &models.ExamInfo{} + var attemptID sql.NullInt64 var completedAt sql.NullTime var correctAnswers, totalQuestions sql.NullInt64 var score sql.NullFloat64 @@ -303,12 +304,16 @@ func (db *SQLiteDB) GetAssignedExamsForUser(userID int) ([]*models.ExamInfo, err if err := rows.Scan( &info.ID, &info.ExamID, &info.UserID, &info.AssignedAt, &info.AssignedBy, &info.ExamName, &info.QuestionCount, &info.AccessToken, - &completedAt, &correctAnswers, &totalQuestions, &score, + &attemptID, &completedAt, &correctAnswers, &totalQuestions, &score, ); err != nil { return nil, err } if completedAt.Valid { info.CompletedAt = &completedAt.Time + if attemptID.Valid { + aid := int(attemptID.Int64) + info.AttemptID = &aid + } if correctAnswers.Valid { ca := int(correctAnswers.Int64) info.CorrectAnswers = &ca @@ -445,7 +450,7 @@ func (db *SQLiteDB) GetExamStatus(examID int) (*models.ExamStatus, error) { query := ` SELECT u.id, u.username, ea.assigned_at, - att.completed_at, att.correct_answers, att.total_questions, att.score + att.id, att.completed_at, att.correct_answers, att.total_questions, att.score FROM exam_assignments ea JOIN users u ON ea.user_id = u.id LEFT JOIN exam_attempts att ON att.exam_id = ea.exam_id @@ -466,18 +471,23 @@ func (db *SQLiteDB) GetExamStatus(examID int) (*models.ExamStatus, error) { for rows.Next() { r := models.ExamStudentResult{} + var attemptID sql.NullInt64 var completedAt sql.NullTime var correctAnswers, totalQuestions sql.NullInt64 var score sql.NullFloat64 if err := rows.Scan( &r.UserID, &r.Username, &r.AssignedAt, - &completedAt, &correctAnswers, &totalQuestions, &score, + &attemptID, &completedAt, &correctAnswers, &totalQuestions, &score, ); err != nil { return nil, err } if completedAt.Valid { r.CompletedAt = &completedAt.Time + if attemptID.Valid { + aid := int(attemptID.Int64) + r.AttemptID = &aid + } if correctAnswers.Valid { ca := int(correctAnswers.Int64) r.CorrectAnswers = &ca diff --git a/models/models.go b/models/models.go index a23e048..ae11e1b 100644 --- a/models/models.go +++ b/models/models.go @@ -482,6 +482,7 @@ type ExamStudentResult struct { Score *float64 `json:"score,omitempty"` CorrectAnswers *int `json:"correct_answers,omitempty"` TotalQuestions *int `json:"total_questions,omitempty"` + AttemptID *int `json:"attempt_id,omitempty"` } // ExamStatus is the instructor view of an exam and all student results @@ -502,6 +503,7 @@ type ExamInfo struct { Score *float64 `json:"score,omitempty"` CorrectAnswers *int `json:"correct_answers,omitempty"` TotalQuestions *int `json:"total_questions,omitempty"` + AttemptID *int `json:"attempt_id,omitempty"` } // FlagReason constants (Phase 5) diff --git a/router/router.go b/router/router.go index cae33bb..93f68f3 100644 --- a/router/router.go +++ b/router/router.go @@ -65,6 +65,7 @@ func New(h *api.Handler) *chi.Mux { r.Get("/assigned-exams", h.GetAssignedExamsHandler) r.Post("/exam/start", h.StartExamHandler) r.Post("/exam/submit", h.SubmitExamHandler) + r.Get("/exam/submission", h.GetExamSubmissionHandler) r.Route("/quizzes", func(r chi.Router) { r.Get("/", h.GetQuizHandler) diff --git a/static/dashboard.html b/static/dashboard.html index 0eec8ce..f045de0 100644 --- a/static/dashboard.html +++ b/static/dashboard.html @@ -53,6 +53,9 @@

Student Dashboard

+ diff --git a/static/exam-center.html b/static/exam-center.html new file mode 100644 index 0000000..7024c01 --- /dev/null +++ b/static/exam-center.html @@ -0,0 +1,92 @@ + + + + + + + + Exam Center - Athena + + + + + + + + +
+
+
+

Exam Center

+

View your assigned exams and review submitted exams.

+
+
+ + +
+
+
+
+
Pending Exams
+
+
+
+
+
+ Loading... +
+
+
+
+
+
+ + +
+
+
+
+
Submitted Exams
+
+
+
+
+
+ Loading... +
+
+
+
+
+
+
+ + + + + + + diff --git a/static/exam-review.html b/static/exam-review.html new file mode 100644 index 0000000..99efbc6 --- /dev/null +++ b/static/exam-review.html @@ -0,0 +1,158 @@ + + + + + + + + Exam Review - Athena + + + + + + + + + +
+ + +
+
+

Loading submission...

+
+ + + + + + + +
+ + + + + + + diff --git a/static/js/admin/exams-page.js b/static/js/admin/exams-page.js index abbc5b9..eae2768 100644 --- a/static/js/admin/exams-page.js +++ b/static/js/admin/exams-page.js @@ -383,13 +383,16 @@ async function showExamDetail(examId, examName) { const correct = result.correct_answers !== undefined && result.correct_answers !== null ? `${result.correct_answers} / ${result.total_questions}` : '—'; + const viewSubmissionBtn = result.attempt_id + ? `View Submission` + : ''; html += ` ${escapeHtml(result.username)} ${new Date(result.assigned_at).toLocaleDateString()} ${completed} ${scoreHtml} ${correct} - + ${viewSubmissionBtn} `; }); html += ''; diff --git a/static/js/dashboard.js b/static/js/dashboard.js index eb7c661..1227974 100644 --- a/static/js/dashboard.js +++ b/static/js/dashboard.js @@ -391,14 +391,24 @@ async function loadAssignedExamsBadge() { const exams = await response.json(); if (!exams || exams.length === 0) return; - document.getElementById('assignedExamsBtn').style.display = 'inline-block'; + // Show Exam Center link whenever there are any exams + document.getElementById('examCenterBtn').style.display = 'inline-block'; + // Hide old inline button (superseded by Exam Center page) + document.getElementById('assignedExamsBtn').style.display = 'none'; const pending = exams.filter(e => !e.completed_at).length; - const badge = document.getElementById('assignedExamsBadge'); + const badge = document.getElementById('examCenterBadge'); if (pending > 0) { badge.textContent = pending; badge.style.display = 'inline-block'; } + + // Keep old badge in sync for any leftover code references + const oldBadge = document.getElementById('assignedExamsBadge'); + if (pending > 0 && oldBadge) { + oldBadge.textContent = pending; + oldBadge.style.display = 'inline-block'; + } } catch (error) { console.error('Error loading assigned exams badge:', error); } diff --git a/static/js/exam-center.js b/static/js/exam-center.js new file mode 100644 index 0000000..961ca9a --- /dev/null +++ b/static/js/exam-center.js @@ -0,0 +1,153 @@ +// Exam Center JavaScript + +const user = JSON.parse(localStorage.getItem('user')); +if (!user) { + window.location.href = '/index.html'; +} + +document.getElementById('userDisplay').textContent = `Welcome, ${user.username}!`; + +function logout() { + localStorage.removeItem('user'); + window.location.href = '/index.html'; +} + +async function loadExams() { + try { + const response = await fetch(`/assigned-exams?user_id=${user.id}`); + if (!response.ok) { + throw new Error('Failed to load exams'); + } + const exams = await response.json(); + + const pending = exams.filter(e => !e.completed_at); + const submitted = exams.filter(e => !!e.completed_at); + + renderPendingExams(pending); + renderSubmittedExams(submitted); + } catch (error) { + console.error('Error loading exams:', error); + document.getElementById('pendingExamsList').innerHTML = + '
Error loading exams. Please try again.
'; + document.getElementById('submittedExamsList').innerHTML = + '
Error loading exams. Please try again.
'; + } +} + +function renderPendingExams(exams) { + const container = document.getElementById('pendingExamsList'); + if (!exams || exams.length === 0) { + container.innerHTML = '

No pending exams. You\'re all caught up!

'; + return; + } + + let html = '
'; + exams.forEach(e => { + html += ` +
+
+
+ ${escapeHtml(e.exam_name)} + ${e.question_count} questions +
+ Assigned: ${new Date(e.assigned_at).toLocaleDateString()} +
+ Not Started +
+
+ +
+
+
+ `; + }); + html += '
'; + container.innerHTML = html; +} + +function renderSubmittedExams(exams) { + const container = document.getElementById('submittedExamsList'); + if (!exams || exams.length === 0) { + container.innerHTML = '

No submitted exams yet.

'; + return; + } + + let html = '
'; + exams.forEach(e => { + const scoreVal = e.score !== undefined && e.score !== null ? e.score.toFixed(0) : '?'; + const scoreNum = e.score !== undefined && e.score !== null ? e.score : 0; + const scoreClass = scoreNum >= 80 ? 'bg-success' : scoreNum >= 60 ? 'bg-warning' : 'bg-danger'; + const completedDate = e.completed_at ? new Date(e.completed_at).toLocaleString() : 'Unknown'; + + // Link directly with attempt_id when available for reliability + const reviewLink = e.attempt_id + ? `/exam-review.html?attempt_id=${e.attempt_id}&user_id=${user.id}` + : `/exam-review.html?exam_id=${e.exam_id}&user_id=${user.id}`; + + html += ` +
+
+
+ ${escapeHtml(e.exam_name)} + ${e.question_count} questions +
+ Submitted: ${completedDate} +
+ Submitted + ${scoreVal}% + (${e.correct_answers}/${e.total_questions} correct) +
+
+ + View Submission + + +
+
+
+ `; + }); + html += '
'; + container.innerHTML = html; +} + +async function startExam(examId, token) { + try { + const response = await fetch(`/exam/start?token=${encodeURIComponent(token)}&user_id=${user.id}`, { + method: 'POST', + headers: {'Content-Type': 'application/json'} + }); + + if (!response.ok) { + const errorText = await response.text(); + alert('Failed to start exam: ' + errorText); + return; + } + + const examData = await response.json(); + localStorage.setItem('currentExam', JSON.stringify(examData)); + window.location.href = '/exam.html?token=' + encodeURIComponent(token); + } catch (error) { + console.error('Error starting exam:', error); + alert('Error starting exam. Please try again.'); + } +} + +function escapeHtml(text) { + const div = document.createElement('div'); + div.textContent = text == null ? '' : String(text); + return div.innerHTML; +} + +// Load exams on page load +loadExams(); diff --git a/static/js/exam-review.js b/static/js/exam-review.js new file mode 100644 index 0000000..6f60ee1 --- /dev/null +++ b/static/js/exam-review.js @@ -0,0 +1,224 @@ +// Exam Review JavaScript + +const user = JSON.parse(localStorage.getItem('user')); +if (!user) { + window.location.href = '/index.html'; +} + +document.getElementById('userDisplay').textContent = `Welcome, ${user.username}!`; + +function logout() { + localStorage.removeItem('user'); + window.location.href = '/index.html'; +} + +function showPanel(id) { + ['loadingPanel', 'errorPanel', 'reviewPanel'].forEach(p => { + const el = document.getElementById(p); + if (el) el.style.display = p === id ? 'block' : 'none'; + }); +} + +function showError(msg) { + document.getElementById('errorMsg').textContent = msg; + showPanel('errorPanel'); +} + +function escapeHtml(text) { + const div = document.createElement('div'); + div.textContent = text == null ? '' : String(text); + return div.innerHTML; +} + +function renderQuestionText(container, text) { + container.innerHTML = ''; + const codeBlockRegex = /```(\w+)?\r?\n?([\s\S]*?)```/g; + let lastIndex = 0; + let match; + + while ((match = codeBlockRegex.exec(text)) !== null) { + if (match.index > lastIndex) { + const preamble = text.substring(lastIndex, match.index).trim(); + if (preamble) { + const p = document.createElement('p'); + p.textContent = preamble; + container.appendChild(p); + } + } + const pre = document.createElement('pre'); + const code = document.createElement('code'); + code.textContent = match[2]; + pre.appendChild(code); + pre.style.cssText = 'background:#f4f4f4;padding:10px;border-radius:4px;overflow-x:auto;font-size:0.85em;'; + container.appendChild(pre); + lastIndex = match.index + match[0].length; + } + + const remaining = text.substring(lastIndex).trim(); + if (remaining) { + const p = document.createElement('p'); + p.textContent = remaining; + container.appendChild(p); + } + + if (!container.hasChildNodes()) { + container.textContent = text; + } +} + +(async function init() { + const params = new URLSearchParams(window.location.search); + + const attemptId = params.get('attempt_id') ? parseInt(params.get('attempt_id'), 10) : null; + + if (!attemptId || attemptId <= 0) { + showError('Missing or invalid attempt ID. Please navigate here from the Exam Center or the Admin Exams page.'); + return; + } + + // Adjust back link for instructors + if (user.is_admin) { + const backLink = document.getElementById('examCenterLink'); + if (backLink) { + backLink.href = '/admin-exams.html'; + backLink.textContent = '← Admin Exams'; + } + } + + try { + const response = await fetch(`/exam/submission?attempt_id=${attemptId}&user_id=${user.id}`); + if (!response.ok) { + const errText = await response.text(); + showError('Could not load submission: ' + errText); + return; + } + const data = await response.json(); + renderReview(data); + } catch (e) { + showError('Network error: ' + e.message); + } +})(); + +function renderReview(data) { + // Fill summary + document.getElementById('examNameTitle').textContent = data.exam_name || 'Exam Review'; + + if (data.completed_at) { + document.getElementById('completedAtBadge').textContent = + 'Submitted: ' + new Date(data.completed_at).toLocaleString(); + } + + const score = data.score !== undefined && data.score !== null ? data.score : 0; + const scoreClass = score >= 80 ? 'text-success' : score >= 60 ? 'text-warning' : 'text-danger'; + document.getElementById('scoreDisplay').innerHTML = + `${score.toFixed(0)}%`; + + const correct = data.correct_answers || 0; + const total = data.total_questions || 0; + const incorrect = total - correct; + + document.getElementById('correctDisplay').textContent = correct; + document.getElementById('incorrectDisplay').textContent = incorrect; + document.getElementById('totalDisplay').textContent = total; + + // Render questions + const container = document.getElementById('questionsReview'); + container.innerHTML = ''; + + if (!data.questions || data.questions.length === 0) { + container.innerHTML = '

No question details available.

'; + showPanel('reviewPanel'); + return; + } + + data.questions.forEach((q, idx) => { + const cardDiv = document.createElement('div'); + cardDiv.className = `card mb-3 question-card ${q.is_correct ? 'correct-card' : 'wrong-card'}`; + + const cardHeader = document.createElement('div'); + cardHeader.className = 'card-header d-flex justify-content-between align-items-center'; + + const questionNum = document.createElement('span'); + questionNum.className = 'question-number'; + questionNum.textContent = `Question ${idx + 1} of ${data.questions.length}`; + + const statusBadge = document.createElement('span'); + if (q.is_correct) { + statusBadge.className = 'badge bg-success'; + statusBadge.innerHTML = ' Correct'; + } else { + statusBadge.className = 'badge bg-danger'; + statusBadge.innerHTML = ' Incorrect'; + } + + const categoryBadge = document.createElement('span'); + categoryBadge.className = 'badge bg-secondary ms-2'; + categoryBadge.textContent = q.category || ''; + + cardHeader.appendChild(questionNum); + const badgeGroup = document.createElement('div'); + badgeGroup.appendChild(categoryBadge); + badgeGroup.appendChild(document.createTextNode(' ')); + badgeGroup.appendChild(statusBadge); + cardHeader.appendChild(badgeGroup); + + const cardBody = document.createElement('div'); + cardBody.className = 'card-body'; + + const questionTextEl = document.createElement('div'); + questionTextEl.className = 'mb-3 fw-semibold'; + renderQuestionText(questionTextEl, q.question_text); + cardBody.appendChild(questionTextEl); + + // Render answers + const answersDiv = document.createElement('div'); + if (q.answers && q.answers.length > 0) { + q.answers.forEach(a => { + const answerDiv = document.createElement('div'); + answerDiv.className = 'answer-option'; + + const isSelected = a.id === q.selected_answer_id; + const isCorrectAnswer = a.is_correct; + + if (isSelected && isCorrectAnswer) { + answerDiv.classList.add('answer-selected-correct'); + } else if (isSelected && !isCorrectAnswer) { + answerDiv.classList.add('answer-selected-wrong'); + } else if (!isSelected && isCorrectAnswer) { + answerDiv.classList.add('answer-correct-not-selected'); + } else { + answerDiv.classList.add('answer-neutral'); + } + + let prefix = ''; + if (isSelected && isCorrectAnswer) { + prefix = '✅ '; + } else if (isSelected && !isCorrectAnswer) { + prefix = '❌ '; + } else if (!isSelected && isCorrectAnswer) { + prefix = '✓ '; + } + + answerDiv.textContent = prefix + a.answer_text; + answersDiv.appendChild(answerDiv); + }); + } else { + answersDiv.innerHTML = 'No answer details available.'; + } + cardBody.appendChild(answersDiv); + + // If no answer was selected + if (q.selected_answer_id === 0 && !q.is_correct) { + const noAnswer = document.createElement('small'); + noAnswer.className = 'text-muted d-block mt-2'; + noAnswer.textContent = 'No answer was selected for this question.'; + cardBody.appendChild(noAnswer); + } + + cardDiv.appendChild(cardHeader); + cardDiv.appendChild(cardBody); + container.appendChild(cardDiv); + }); + + showPanel('reviewPanel'); +} From d6e2886c8fca403e772eb82d42156abef05a31ae Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 22 Jul 2026 13:29:27 +0000 Subject: [PATCH 3/4] fix: address code review feedback on exam center and dashboard --- static/js/dashboard.js | 7 ------- static/js/exam-center.js | 16 ++++++++-------- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/static/js/dashboard.js b/static/js/dashboard.js index 1227974..150f66a 100644 --- a/static/js/dashboard.js +++ b/static/js/dashboard.js @@ -402,13 +402,6 @@ async function loadAssignedExamsBadge() { badge.textContent = pending; badge.style.display = 'inline-block'; } - - // Keep old badge in sync for any leftover code references - const oldBadge = document.getElementById('assignedExamsBadge'); - if (pending > 0 && oldBadge) { - oldBadge.textContent = pending; - oldBadge.style.display = 'inline-block'; - } } catch (error) { console.error('Error loading assigned exams badge:', error); } diff --git a/static/js/exam-center.js b/static/js/exam-center.js index 961ca9a..0d64063 100644 --- a/static/js/exam-center.js +++ b/static/js/exam-center.js @@ -48,7 +48,7 @@ function renderPendingExams(exams) {
${escapeHtml(e.exam_name)} - ${e.question_count} questions + ${e.question_count} questions
Assigned: ${new Date(e.assigned_at).toLocaleDateString()}
@@ -84,10 +84,12 @@ function renderSubmittedExams(exams) { const scoreClass = scoreNum >= 80 ? 'bg-success' : scoreNum >= 60 ? 'bg-warning' : 'bg-danger'; const completedDate = e.completed_at ? new Date(e.completed_at).toLocaleString() : 'Unknown'; - // Link directly with attempt_id when available for reliability - const reviewLink = e.attempt_id - ? `/exam-review.html?attempt_id=${e.attempt_id}&user_id=${user.id}` - : `/exam-review.html?exam_id=${e.exam_id}&user_id=${user.id}`; + // Only show View Submission link when attempt_id is available + const viewSubmissionHtml = e.attempt_id + ? ` + View Submission + ` + : ''; html += `
@@ -103,9 +105,7 @@ function renderSubmittedExams(exams) { (${e.correct_answers}/${e.total_questions} correct)
- - View Submission - + ${viewSubmissionHtml}