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 @@
View your assigned exams and review submitted exams.
+Loading submission...
+No pending exams. You\'re all caught up!
'; + return; + } + + let html = 'No submitted exams yet.
'; + return; + } + + let html = '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) {