Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions api/exam.go
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,130 @@ func (h *Handler) SubmitExamHandler(w http.ResponseWriter, r *http.Request) {
})
}

// 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,
})
}

// GetAvailableExamCategoriesHandler handles GET /instructor/exams/categories
// Returns all distinct topic categories available in the database.
func (h *Handler) GetAvailableExamCategoriesHandler(w http.ResponseWriter, r *http.Request) {
Expand Down
87 changes: 87 additions & 0 deletions api/exam_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
})
}
24 changes: 17 additions & 7 deletions database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
18 changes: 14 additions & 4 deletions database/exam.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -296,19 +296,24 @@ 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

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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
2 changes: 2 additions & 0 deletions models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
1 change: 1 addition & 0 deletions router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions static/dashboard.html
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ <h2 class="mb-4">Student Dashboard</h2>
<button class="btn btn-warning btn-lg me-2" id="assignedQuizzesBtn" onclick="showAssignedQuizzes()" style="display:none;">
📋 Assigned Quizzes <span id="assignedQuizzesBadge" class="badge bg-danger ms-1" style="display:none;"></span>
</button>
<a href="/exam-center.html" class="btn btn-danger btn-lg me-2" id="examCenterBtn" style="display:none;">
📝 Exam Center <span id="examCenterBadge" class="badge bg-warning ms-1" style="display:none;"></span>
</a>
<button class="btn btn-danger btn-lg" id="assignedExamsBtn" onclick="showAssignedExams()" style="display:none;">
📝 Assigned Exams <span id="assignedExamsBadge" class="badge bg-warning ms-1" style="display:none;"></span>
</button>
Expand Down
Loading
Loading