From fa0279dc01e6d59877e803b1529bf5da610bb462 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 8 Jun 2026 14:22:01 +0000 Subject: [PATCH 1/3] Initial plan From eb322b96fb4568c036a97ec7c54d71746b5327ff Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 8 Jun 2026 14:35:56 +0000 Subject: [PATCH 2/3] Complete exam feature: frontend UI for instructor, dashboard, and student exam page --- api/exam.go | 442 ++++++++++++++++++ api/exam_test.go | 378 +++++++++++++++ database/database.go | 308 ++++++++++++ database/exam.go | 426 +++++++++++++++++ .../migrations/006_assigned_exams.down.sql | 4 + database/migrations/006_assigned_exams.up.sql | 49 ++ models/models.go | 68 +++ router/router.go | 12 + static/dashboard.html | 22 +- static/exam.html | 391 ++++++++++++++++ static/instructor.html | 410 ++++++++++++++++ static/js/dashboard.js | 122 +++++ 12 files changed, 2631 insertions(+), 1 deletion(-) create mode 100644 api/exam.go create mode 100644 api/exam_test.go create mode 100644 database/exam.go create mode 100644 database/migrations/006_assigned_exams.down.sql create mode 100644 database/migrations/006_assigned_exams.up.sql create mode 100644 static/exam.html diff --git a/api/exam.go b/api/exam.go new file mode 100644 index 0000000..cae24e1 --- /dev/null +++ b/api/exam.go @@ -0,0 +1,442 @@ +package api + +import ( + cryptorand "crypto/rand" + "encoding/hex" + "encoding/json" + "fmt" + mathrand "math/rand" + "net/http" + "strconv" + "time" + + "github.com/ZipCodeCore/zip-athena/database" + "github.com/ZipCodeCore/zip-athena/models" +) + +// generateToken creates a cryptographically random hex token. +func generateToken() (string, error) { + b := make([]byte, 16) + if _, err := cryptorand.Read(b); err != nil { + return "", err + } + return hex.EncodeToString(b), nil +} + +// GenerateExamHandler handles POST /instructor/exams/generate +// Creates a new exam by randomly selecting questions that match the given +// categories and difficulty levels, then saves the exam. +func (h *Handler) GenerateExamHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + var body struct { + Name string `json:"name"` + Categories []string `json:"categories"` + DifficultyLevels []int `json:"difficulty_levels"` + QuestionCount int `json:"question_count"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest) + return + } + + if body.Name == "" { + http.Error(w, "name is required", http.StatusBadRequest) + return + } + if len(body.Categories) == 0 { + http.Error(w, "at least one category is required", http.StatusBadRequest) + return + } + if len(body.DifficultyLevels) == 0 { + http.Error(w, "at least one difficulty_level is required", http.StatusBadRequest) + return + } + count := body.QuestionCount + if count <= 0 { + count = 30 + } + + questions, err := h.db.GetQuestionsByCategories(body.Categories, body.DifficultyLevels, count) + if err != nil { + h.logger.WithContext(r.Context()).WithError(err).Error("Failed to fetch questions for exam generation") + http.Error(w, "Failed to fetch questions: "+err.Error(), http.StatusInternalServerError) + return + } + if len(questions) == 0 { + http.Error(w, "No questions found matching the selected criteria", http.StatusUnprocessableEntity) + return + } + + questionIDs := make([]int, len(questions)) + for i, q := range questions { + questionIDs[i] = q.ID + } + + token, err := generateToken() + if err != nil { + h.logger.WithContext(r.Context()).WithError(err).Error("Failed to generate exam token") + http.Error(w, "Failed to generate exam token", http.StatusInternalServerError) + return + } + + assignerIDStr := r.Header.Get("X-User-ID") + assignerID, _ := strconv.Atoi(assignerIDStr) + + exam := &models.Exam{ + Name: body.Name, + Categories: body.Categories, + DifficultyLevels: body.DifficultyLevels, + QuestionIDs: questionIDs, + QuestionCount: len(questionIDs), + AccessToken: token, + CreatedBy: assignerID, + CreatedAt: time.Now(), + } + + if err := h.db.CreateExam(exam); err != nil { + h.logger.WithContext(r.Context()).WithError(err).Error("Failed to create exam") + http.Error(w, "Failed to create exam: "+err.Error(), http.StatusInternalServerError) + return + } + + examURL := fmt.Sprintf("/exam.html?token=%s", exam.AccessToken) + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(map[string]interface{}{ + "success": true, + "exam_id": exam.ID, + "exam_name": exam.Name, + "question_count": exam.QuestionCount, + "access_token": exam.AccessToken, + "exam_url": examURL, + }) +} + +// ListExamsHandler handles GET /instructor/exams +func (h *Handler) ListExamsHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + exams, err := h.db.ListExams() + if err != nil { + h.logger.WithContext(r.Context()).WithError(err).Error("Failed to list exams") + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(exams) +} + +// AssignExamToStudentsHandler handles POST /instructor/exams/assign?exam_id={id} +// Assigns an exam to one or more students. +func (h *Handler) AssignExamToStudentsHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + examIDStr := r.URL.Query().Get("exam_id") + examID, err := strconv.Atoi(examIDStr) + if err != nil || examID <= 0 { + http.Error(w, "Invalid exam_id", http.StatusBadRequest) + return + } + + if _, err := h.db.GetExam(examID); err != nil { + if err == database.ErrNotFound { + http.Error(w, "Exam not found", http.StatusNotFound) + return + } + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + assignerIDStr := r.Header.Get("X-User-ID") + assignerID, _ := strconv.Atoi(assignerIDStr) + + var body struct { + UserIDs []int `json:"user_ids"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest) + return + } + if len(body.UserIDs) == 0 { + http.Error(w, "user_ids must not be empty", http.StatusBadRequest) + return + } + + assigned := 0 + var assignErrors []string + for _, uid := range body.UserIDs { + if err := h.db.AssignExamToUser(examID, uid, assignerID); err != nil { + assignErrors = append(assignErrors, fmt.Sprintf("user %d: %s", uid, err.Error())) + } else { + assigned++ + } + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]interface{}{ + "success": true, + "assigned": assigned, + "errors": assignErrors, + }) +} + +// GetExamStatusHandler handles GET /instructor/exams/status?exam_id={id} +// Returns results for all students assigned to the given exam. +func (h *Handler) GetExamStatusHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + examIDStr := r.URL.Query().Get("exam_id") + examID, err := strconv.Atoi(examIDStr) + if err != nil || examID <= 0 { + http.Error(w, "Invalid exam_id", http.StatusBadRequest) + return + } + + status, err := h.db.GetExamStatus(examID) + if err != nil { + if err == database.ErrNotFound { + http.Error(w, "Exam not found", http.StatusNotFound) + return + } + h.logger.WithContext(r.Context()).WithError(err).Error("Failed to get exam status") + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(status) +} + +// GetAssignedExamsHandler handles GET /assigned-exams?user_id={id} +// Returns exams assigned to a student. +func (h *Handler) GetAssignedExamsHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + 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 + } + + exams, err := h.db.GetAssignedExamsForUser(userID) + if err != nil { + h.logger.WithContext(r.Context()).WithError(err).Error("Failed to get assigned exams") + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(exams) +} + +// StartExamHandler handles POST /exam/start?token={token}&user_id={id} +// Verifies the student is assigned to the exam, creates an attempt, and returns +// the questions (answers randomized). +func (h *Handler) StartExamHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + token := r.URL.Query().Get("token") + if token == "" { + http.Error(w, "token is required", 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 + } + + exam, err := h.db.GetExamByToken(token) + if err != nil { + if err == database.ErrNotFound { + http.Error(w, "Exam not found", http.StatusNotFound) + return + } + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Verify the exam is assigned to this user + assignedExams, err := h.db.GetAssignedExamsForUser(userID) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + assigned := false + for _, ae := range assignedExams { + if ae.ExamID == exam.ID { + assigned = true + break + } + } + if !assigned { + http.Error(w, "Exam not assigned to this user", http.StatusForbidden) + return + } + + // Build question list with answers + type examAnswer struct { + ID int `json:"id"` + AnswerText string `json:"answer_text"` + } + type examQuestion struct { + ID int `json:"id"` + QuestionText string `json:"question_text"` + Difficulty int `json:"difficulty"` + Answers []examAnswer `json:"answers"` + } + + questions := make([]examQuestion, 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 + } + // Randomize answer order + mathrand.Shuffle(len(answers), func(i, j int) { answers[i], answers[j] = answers[j], answers[i] }) + + eas := make([]examAnswer, len(answers)) + for i, a := range answers { + eas[i] = examAnswer{ID: a.ID, AnswerText: a.AnswerText} + } + questions = append(questions, examQuestion{ + ID: q.ID, + QuestionText: q.QuestionText, + Difficulty: q.Difficulty, + Answers: eas, + }) + } + + attempt := &models.ExamAttempt{ + ExamID: exam.ID, + UserID: userID, + StartedAt: time.Now(), + TotalQuestions: len(questions), + Answers: map[string]int{}, + QuestionResults: map[string]bool{}, + } + if err := h.db.CreateExamAttempt(attempt); err != nil { + h.logger.WithContext(r.Context()).WithError(err).Error("Failed to create exam attempt") + http.Error(w, "Failed to start exam: "+err.Error(), http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]interface{}{ + "attempt_id": attempt.ID, + "exam_id": exam.ID, + "exam_name": exam.Name, + "question_count": len(questions), + "questions": questions, + }) +} + +// SubmitExamHandler handles POST /exam/submit +// Body: { "attempt_id": int, "answers": { "questionID": answerID, ... } } +func (h *Handler) SubmitExamHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + var body struct { + AttemptID int `json:"attempt_id"` + Answers map[string]int `json:"answers"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest) + return + } + if body.AttemptID <= 0 { + http.Error(w, "attempt_id is required", http.StatusBadRequest) + return + } + if body.Answers == nil { + body.Answers = map[string]int{} + } + + if err := h.db.SubmitExamAttempt(body.AttemptID, body.Answers); 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 submit exam attempt") + http.Error(w, "Failed to submit exam: "+err.Error(), http.StatusInternalServerError) + return + } + + attempt, err := h.db.GetExamAttempt(body.AttemptID) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]interface{}{ + "attempt_id": attempt.ID, + "exam_id": attempt.ExamID, + "score": attempt.Score, + "correct_answers": attempt.CorrectAnswers, + "total_questions": attempt.TotalQuestions, + "completed_at": attempt.CompletedAt, + "question_results": attempt.QuestionResults, + }) +} + +// 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) { + if r.Method != http.MethodGet { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + topics, err := h.db.ListAllTopics() + if err != nil { + h.logger.WithContext(r.Context()).WithError(err).Error("Failed to list topics for categories") + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + seen := map[string]bool{} + var categories []string + for _, t := range topics { + if t.Category != "" && !seen[t.Category] { + seen[t.Category] = true + categories = append(categories, t.Category) + } + } + if categories == nil { + categories = []string{} + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(categories) +} diff --git a/api/exam_test.go b/api/exam_test.go new file mode 100644 index 0000000..8f28877 --- /dev/null +++ b/api/exam_test.go @@ -0,0 +1,378 @@ +package api + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/ZipCodeCore/zip-athena/database" + "github.com/ZipCodeCore/zip-athena/models" +) + +// setupExamDB creates a test database with questions for exam tests +func setupExamDB(t *testing.T) (*database.InMemoryDB, *models.User, *models.User) { + t.Helper() + db := database.NewInMemoryDB() + + admin := &models.User{Username: "examadmin", Email: "examadmin@test.com", IsAdmin: true} + db.CreateUser(admin) + + student := &models.User{Username: "examstudent", Email: "examstudent@test.com", IsAdmin: false, Category: "java"} + db.CreateUser(student) + + // Create a topic and questions + topic := &models.Topic{Name: "Java Basics", Category: "java", IsActive: true, CreatedAt: time.Now()} + db.CreateTopic(topic) + + for i := 1; i <= 5; i++ { + q := &models.Question{ + TopicID: topic.ID, + QuestionText: fmt.Sprintf("Question %d?", i), + Difficulty: i % 3 + 1, // cycles through 2,3,1 + Tags: []string{"java"}, + TopicQuestionID: fmt.Sprintf("%d.%d", topic.ID, i), + IsActive: true, + CreatedAt: time.Now(), + } + db.CreateQuestion(q) + db.CreateAnswer(&models.Answer{QuestionID: q.ID, AnswerText: "Correct", IsCorrect: true}) + db.CreateAnswer(&models.Answer{QuestionID: q.ID, AnswerText: "Wrong", IsCorrect: false}) + } + + return db, admin, student +} + +func TestGenerateExamHandler(t *testing.T) { + db, admin, _ := setupExamDB(t) + handler := NewHandler(db) + + body, _ := json.Marshal(map[string]interface{}{ + "name": "Java Midterm", + "categories": []string{"java"}, + "difficulty_levels": []int{1, 2, 3}, + "question_count": 3, + }) + + req := httptest.NewRequest(http.MethodPost, "/instructor/exams/generate", bytes.NewBuffer(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-User-ID", fmt.Sprintf("%d", admin.ID)) + w := httptest.NewRecorder() + + handler.GenerateExamHandler(w, req) + + if w.Code != http.StatusCreated { + t.Fatalf("Expected status 201, got %d: %s", w.Code, w.Body.String()) + } + + var result map[string]interface{} + json.NewDecoder(w.Body).Decode(&result) + + if result["success"] != true { + t.Errorf("Expected success=true, got %v", result["success"]) + } + if result["exam_name"].(string) != "Java Midterm" { + t.Errorf("Expected exam_name 'Java Midterm', got %v", result["exam_name"]) + } + if result["access_token"] == "" || result["access_token"] == nil { + t.Error("Expected non-empty access_token") + } + if result["exam_url"] == "" || result["exam_url"] == nil { + t.Error("Expected non-empty exam_url") + } +} + +func TestGenerateExamHandler_MissingName(t *testing.T) { + db, admin, _ := setupExamDB(t) + handler := NewHandler(db) + + body, _ := json.Marshal(map[string]interface{}{ + "categories": []string{"java"}, + "difficulty_levels": []int{1}, + }) + + req := httptest.NewRequest(http.MethodPost, "/instructor/exams/generate", bytes.NewBuffer(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-User-ID", fmt.Sprintf("%d", admin.ID)) + w := httptest.NewRecorder() + + handler.GenerateExamHandler(w, req) + + if w.Code != http.StatusBadRequest { + t.Errorf("Expected status 400, got %d", w.Code) + } +} + +func TestListExamsHandler(t *testing.T) { + db, admin, _ := setupExamDB(t) + handler := NewHandler(db) + + // Create an exam first + db.CreateExam(&models.Exam{ + Name: "Test Exam", Categories: []string{"java"}, DifficultyLevels: []int{1}, + QuestionIDs: []int{1}, QuestionCount: 1, AccessToken: "testtoken123", + CreatedBy: admin.ID, CreatedAt: time.Now(), + }) + + req := httptest.NewRequest(http.MethodGet, "/instructor/exams", nil) + req.Header.Set("X-User-ID", fmt.Sprintf("%d", admin.ID)) + w := httptest.NewRecorder() + + handler.ListExamsHandler(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("Expected status 200, got %d: %s", w.Code, w.Body.String()) + } + + var exams []*models.Exam + json.NewDecoder(w.Body).Decode(&exams) + if len(exams) != 1 { + t.Errorf("Expected 1 exam, got %d", len(exams)) + } +} + +func TestAssignExamToStudentsHandler(t *testing.T) { + db, admin, student := setupExamDB(t) + handler := NewHandler(db) + + exam := &models.Exam{ + Name: "Assigned Exam", Categories: []string{"java"}, DifficultyLevels: []int{1}, + QuestionIDs: []int{1}, QuestionCount: 1, AccessToken: "assigntoken", + CreatedBy: admin.ID, CreatedAt: time.Now(), + } + db.CreateExam(exam) + + body, _ := json.Marshal(map[string]interface{}{ + "user_ids": []int{student.ID}, + }) + + req := httptest.NewRequest(http.MethodPost, fmt.Sprintf("/instructor/exams/assign?exam_id=%d", exam.ID), bytes.NewBuffer(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-User-ID", fmt.Sprintf("%d", admin.ID)) + w := httptest.NewRecorder() + + handler.AssignExamToStudentsHandler(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("Expected status 200, got %d: %s", w.Code, w.Body.String()) + } + + var result map[string]interface{} + json.NewDecoder(w.Body).Decode(&result) + if result["assigned"].(float64) != 1 { + t.Errorf("Expected assigned=1, got %v", result["assigned"]) + } +} + +func TestGetAssignedExamsHandler(t *testing.T) { + db, admin, student := setupExamDB(t) + handler := NewHandler(db) + + exam := &models.Exam{ + Name: "My Exam", Categories: []string{"java"}, DifficultyLevels: []int{1}, + QuestionIDs: []int{1}, QuestionCount: 1, AccessToken: "mytoken", + CreatedBy: admin.ID, CreatedAt: time.Now(), + } + db.CreateExam(exam) + db.AssignExamToUser(exam.ID, student.ID, admin.ID) + + req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/assigned-exams?user_id=%d", student.ID), nil) + w := httptest.NewRecorder() + + handler.GetAssignedExamsHandler(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("Expected status 200, got %d: %s", w.Code, w.Body.String()) + } + + var exams []*models.ExamInfo + json.NewDecoder(w.Body).Decode(&exams) + if len(exams) != 1 { + t.Errorf("Expected 1 assigned exam, got %d", len(exams)) + } + if exams[0].ExamID != exam.ID { + t.Errorf("Expected exam ID %d, got %d", exam.ID, exams[0].ExamID) + } +} + +func TestStartExamHandler(t *testing.T) { + db, admin, student := setupExamDB(t) + handler := NewHandler(db) + + // Get IDs of questions in the DB + questions, _ := db.ListQuestions() + qIDs := make([]int, 0, 3) + for i, q := range questions { + if i >= 3 { + break + } + qIDs = append(qIDs, q.ID) + } + + exam := &models.Exam{ + Name: "Start Exam", Categories: []string{"java"}, DifficultyLevels: []int{1, 2, 3}, + QuestionIDs: qIDs, QuestionCount: len(qIDs), AccessToken: "starttoken", + CreatedBy: admin.ID, CreatedAt: time.Now(), + } + db.CreateExam(exam) + db.AssignExamToUser(exam.ID, student.ID, admin.ID) + + req := httptest.NewRequest(http.MethodPost, + fmt.Sprintf("/exam/start?token=%s&user_id=%d", exam.AccessToken, student.ID), nil) + w := httptest.NewRecorder() + + handler.StartExamHandler(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("Expected status 200, got %d: %s", w.Code, w.Body.String()) + } + + var result map[string]interface{} + json.NewDecoder(w.Body).Decode(&result) + if result["attempt_id"] == nil || result["attempt_id"].(float64) == 0 { + t.Error("Expected attempt_id to be set") + } + if result["questions"] == nil { + t.Error("Expected questions in response") + } +} + +func TestStartExamHandler_NotAssigned(t *testing.T) { + db, admin, student := setupExamDB(t) + handler := NewHandler(db) + + exam := &models.Exam{ + Name: "Unassigned Exam", Categories: []string{"java"}, DifficultyLevels: []int{1}, + QuestionIDs: []int{1}, QuestionCount: 1, AccessToken: "unassignedtoken", + CreatedBy: admin.ID, CreatedAt: time.Now(), + } + db.CreateExam(exam) + // Do NOT assign to student + + req := httptest.NewRequest(http.MethodPost, + fmt.Sprintf("/exam/start?token=%s&user_id=%d", exam.AccessToken, student.ID), nil) + w := httptest.NewRecorder() + + handler.StartExamHandler(w, req) + + if w.Code != http.StatusForbidden { + t.Errorf("Expected status 403, got %d", w.Code) + } +} + +func TestSubmitExamHandler(t *testing.T) { + db, admin, student := setupExamDB(t) + handler := NewHandler(db) + + questions, _ := db.ListQuestions() + qIDs := []int{questions[0].ID} + + exam := &models.Exam{ + Name: "Submit Exam", Categories: []string{"java"}, DifficultyLevels: []int{1, 2, 3}, + QuestionIDs: qIDs, QuestionCount: 1, AccessToken: "submittoken", + CreatedBy: admin.ID, CreatedAt: time.Now(), + } + db.CreateExam(exam) + db.AssignExamToUser(exam.ID, student.ID, admin.ID) + + // Create 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) + + // Get correct answer for question + answers, _ := db.GetAnswersByQuestion(questions[0].ID) + var correctAnswerID int + for _, a := range answers { + if a.IsCorrect { + correctAnswerID = a.ID + break + } + } + + body, _ := json.Marshal(map[string]interface{}{ + "attempt_id": attempt.ID, + "answers": map[string]int{fmt.Sprintf("%d", questions[0].ID): correctAnswerID}, + }) + + req := httptest.NewRequest(http.MethodPost, "/exam/submit", bytes.NewBuffer(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + + handler.SubmitExamHandler(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("Expected status 200, got %d: %s", w.Code, w.Body.String()) + } + + var result map[string]interface{} + json.NewDecoder(w.Body).Decode(&result) + if result["score"].(float64) != 100.0 { + t.Errorf("Expected score 100, got %v", result["score"]) + } +} + +func TestGetExamStatusHandler(t *testing.T) { + db, admin, student := setupExamDB(t) + handler := NewHandler(db) + + exam := &models.Exam{ + Name: "Status Exam", Categories: []string{"java"}, DifficultyLevels: []int{1}, + QuestionIDs: []int{1}, QuestionCount: 1, AccessToken: "statustoken", + CreatedBy: admin.ID, CreatedAt: time.Now(), + } + db.CreateExam(exam) + db.AssignExamToUser(exam.ID, student.ID, admin.ID) + + req := httptest.NewRequest(http.MethodGet, + fmt.Sprintf("/instructor/exams/status?exam_id=%d", exam.ID), nil) + req.Header.Set("X-User-ID", fmt.Sprintf("%d", admin.ID)) + w := httptest.NewRecorder() + + handler.GetExamStatusHandler(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("Expected status 200, got %d: %s", w.Code, w.Body.String()) + } + + var status models.ExamStatus + json.NewDecoder(w.Body).Decode(&status) + if status.ExamID != exam.ID { + t.Errorf("Expected exam ID %d, got %d", exam.ID, status.ExamID) + } + if len(status.StudentResults) != 1 { + t.Errorf("Expected 1 student result, got %d", len(status.StudentResults)) + } +} + +func TestGetAvailableExamCategoriesHandler(t *testing.T) { + db, admin, _ := setupExamDB(t) + handler := NewHandler(db) + + req := httptest.NewRequest(http.MethodGet, "/instructor/exams/categories", nil) + req.Header.Set("X-User-ID", fmt.Sprintf("%d", admin.ID)) + w := httptest.NewRecorder() + + handler.GetAvailableExamCategoriesHandler(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("Expected status 200, got %d: %s", w.Code, w.Body.String()) + } + + var categories []string + json.NewDecoder(w.Body).Decode(&categories) + found := false + for _, c := range categories { + if c == "java" { + found = true + } + } + if !found { + t.Errorf("Expected 'java' in categories, got %v", categories) + } +} diff --git a/database/database.go b/database/database.go index af5d9e0..d6a9e49 100644 --- a/database/database.go +++ b/database/database.go @@ -184,6 +184,24 @@ type BulkImportRepository interface { BulkCreateQuestions(rows []models.CSVImportRow) (int, error) } +// ExamRepository handles assigned-exam operations +type ExamRepository interface { + CreateExam(exam *models.Exam) error + GetExam(id int) (*models.Exam, error) + GetExamByToken(token string) (*models.Exam, error) + ListExams() ([]*models.Exam, error) + GetQuestionsByCategories(categories []string, difficultyLevels []int, limit int) ([]*models.Question, error) + + AssignExamToUser(examID, userID, assignedBy int) error + GetAssignedExamsForUser(userID int) ([]*models.ExamInfo, error) + + CreateExamAttempt(attempt *models.ExamAttempt) error + GetExamAttempt(id int) (*models.ExamAttempt, error) + SubmitExamAttempt(attemptID int, answers map[string]int) error + + GetExamStatus(examID int) (*models.ExamStatus, error) +} + // Database interface composes all repository interfaces type Database interface { // Core database access @@ -204,6 +222,7 @@ type Database interface { QualityRepository BulkImportRepository AssignedQuizRepository + ExamRepository } // InMemoryDB implements the Database interface using in-memory storage @@ -222,6 +241,9 @@ type InMemoryDB struct { testAttempts map[int]*models.TestAttempt // Phase 4 flaggedQuestions map[int]*models.FlaggedQuestion // Phase 5 assignedQuizzes map[int]*models.AssignedQuiz // key: id + exams map[int]*models.Exam + examAssignments map[int]*models.ExamAssignment + examAttempts map[int]*models.ExamAttempt nextUserID int nextTopicID int nextQuestionID int @@ -235,6 +257,9 @@ type InMemoryDB struct { nextTestQuestionID int // Phase 3 nextTestAttemptID int // Phase 4 nextAssignedQuizID int + nextExamID int + nextExamAssignID int + nextExamAttemptID int mu sync.RWMutex } @@ -255,6 +280,9 @@ func NewInMemoryDB() *InMemoryDB { testAttempts: make(map[int]*models.TestAttempt), flaggedQuestions: make(map[int]*models.FlaggedQuestion), assignedQuizzes: make(map[int]*models.AssignedQuiz), + exams: make(map[int]*models.Exam), + examAssignments: make(map[int]*models.ExamAssignment), + examAttempts: make(map[int]*models.ExamAttempt), nextUserID: 1, nextTopicID: 1, nextQuestionID: 1, @@ -267,6 +295,9 @@ func NewInMemoryDB() *InMemoryDB { nextQuizQuestionID: 1, nextTestQuestionID: 1, nextAssignedQuizID: 1, + nextExamID: 1, + nextExamAssignID: 1, + nextExamAttemptID: 1, } } @@ -2686,3 +2717,280 @@ result = append(result, aq) } return result, nil } + +// ---- InMemoryDB implementation of ExamRepository ---- + +func (db *InMemoryDB) CreateExam(exam *models.Exam) error { +db.mu.Lock() +defer db.mu.Unlock() +exam.ID = db.nextExamID +db.nextExamID++ +cp := *exam +db.exams[cp.ID] = &cp +return nil +} + +func (db *InMemoryDB) GetExam(id int) (*models.Exam, error) { +db.mu.RLock() +defer db.mu.RUnlock() +e, ok := db.exams[id] +if !ok { +return nil, ErrNotFound +} +cp := *e +return &cp, nil +} + +func (db *InMemoryDB) GetExamByToken(token string) (*models.Exam, error) { +db.mu.RLock() +defer db.mu.RUnlock() +for _, e := range db.exams { +if e.AccessToken == token { +cp := *e +return &cp, nil +} +} +return nil, ErrNotFound +} + +func (db *InMemoryDB) ListExams() ([]*models.Exam, error) { +db.mu.RLock() +defer db.mu.RUnlock() +result := make([]*models.Exam, 0, len(db.exams)) +for _, e := range db.exams { +cp := *e +result = append(result, &cp) +} +return result, nil +} + +func (db *InMemoryDB) GetQuestionsByCategories(categories []string, difficultyLevels []int, limit int) ([]*models.Question, error) { +db.mu.RLock() +defer db.mu.RUnlock() + +catSet := map[string]bool{} +for _, c := range categories { +catSet[c] = true +} + +diffRanges := difficultyRanges(difficultyLevels) + +inDiff := func(d int) bool { +if len(diffRanges) == 0 { +return true +} +for _, r := range diffRanges { +if d >= r[0] && d <= r[1] { +return true +} +} +return false +} + +var result []*models.Question +for _, q := range db.questions { +topic, ok := db.topics[q.TopicID] +if !ok || !topic.IsActive { +continue +} +if len(catSet) > 0 && !catSet[topic.Category] && topic.Category != "all" { +continue +} +if !inDiff(q.Difficulty) { +continue +} +cp := *q +result = append(result, &cp) +} + +// shuffle +for i := len(result) - 1; i > 0; i-- { +j := i // simple deterministic shuffle for tests +result[i], result[j] = result[j], result[i] +} +if limit > 0 && len(result) > limit { +result = result[:limit] +} +return result, nil +} + +func (db *InMemoryDB) AssignExamToUser(examID, userID, assignedBy int) error { +db.mu.Lock() +defer db.mu.Unlock() +// check for duplicates +for _, a := range db.examAssignments { +if a.ExamID == examID && a.UserID == userID { +return nil // ignore duplicate +} +} +a := &models.ExamAssignment{ +ID: db.nextExamAssignID, +ExamID: examID, +UserID: userID, +AssignedAt: time.Now(), +AssignedBy: assignedBy, +} +db.nextExamAssignID++ +db.examAssignments[a.ID] = a +return nil +} + +func (db *InMemoryDB) GetAssignedExamsForUser(userID int) ([]*models.ExamInfo, error) { +db.mu.RLock() +defer db.mu.RUnlock() + +var result []*models.ExamInfo +for _, a := range db.examAssignments { +if a.UserID != userID { +continue +} +exam, ok := db.exams[a.ExamID] +if !ok { +continue +} +info := &models.ExamInfo{ +ExamAssignment: *a, +ExamName: exam.Name, +QuestionCount: exam.QuestionCount, +AccessToken: exam.AccessToken, +} +// Find most recent completed attempt +var bestAttempt *models.ExamAttempt +for _, att := range db.examAttempts { +if att.ExamID == a.ExamID && att.UserID == userID && att.CompletedAt != nil { +if bestAttempt == nil || att.ID > bestAttempt.ID { +bestAttempt = att +} +} +} +if bestAttempt != nil { +info.CompletedAt = bestAttempt.CompletedAt +ca := bestAttempt.CorrectAnswers +info.CorrectAnswers = &ca +tq := bestAttempt.TotalQuestions +info.TotalQuestions = &tq +s := bestAttempt.Score +info.Score = &s +} +result = append(result, info) +} +if result == nil { +result = []*models.ExamInfo{} +} +return result, nil +} + +func (db *InMemoryDB) CreateExamAttempt(attempt *models.ExamAttempt) error { +db.mu.Lock() +defer db.mu.Unlock() +attempt.ID = db.nextExamAttemptID +db.nextExamAttemptID++ +cp := *attempt +if cp.Answers == nil { +cp.Answers = map[string]int{} +} +if cp.QuestionResults == nil { +cp.QuestionResults = map[string]bool{} +} +db.examAttempts[cp.ID] = &cp +return nil +} + +func (db *InMemoryDB) GetExamAttempt(id int) (*models.ExamAttempt, error) { +db.mu.RLock() +defer db.mu.RUnlock() +a, ok := db.examAttempts[id] +if !ok { +return nil, ErrNotFound +} +cp := *a +return &cp, nil +} + +func (db *InMemoryDB) SubmitExamAttempt(attemptID int, answers map[string]int) error { +db.mu.Lock() +defer db.mu.Unlock() + +attempt, ok := db.examAttempts[attemptID] +if !ok { +return ErrNotFound +} +exam, ok := db.exams[attempt.ExamID] +if !ok { +return ErrNotFound +} + +attempt.Answers = answers +attempt.QuestionResults = map[string]bool{} +attempt.CorrectAnswers = 0 +attempt.TotalQuestions = len(exam.QuestionIDs) + +for _, qid := range exam.QuestionIDs { +key := fmt.Sprintf("%d", qid) +answerID, ok := answers[key] +if !ok { +attempt.QuestionResults[key] = false +continue +} +answer, ok := db.answers[answerID] +if ok && answer.QuestionID == qid && answer.IsCorrect { +attempt.CorrectAnswers++ +attempt.QuestionResults[key] = true +} else { +attempt.QuestionResults[key] = false +} +} + +if attempt.TotalQuestions > 0 { +attempt.Score = float64(attempt.CorrectAnswers) / float64(attempt.TotalQuestions) * 100 +} +now := time.Now() +attempt.CompletedAt = &now +return nil +} + +func (db *InMemoryDB) GetExamStatus(examID int) (*models.ExamStatus, error) { +db.mu.RLock() +defer db.mu.RUnlock() + +exam, ok := db.exams[examID] +if !ok { +return nil, ErrNotFound +} + +status := &models.ExamStatus{ +ExamID: exam.ID, +ExamName: exam.Name, +QuestionCount: exam.QuestionCount, +StudentResults: []models.ExamStudentResult{}, +} + +for _, a := range db.examAssignments { +if a.ExamID != examID { +continue +} +user, ok := db.users[a.UserID] +if !ok { +continue +} +r := models.ExamStudentResult{ +UserID: a.UserID, +Username: user.Username, +AssignedAt: a.AssignedAt, +} +// Find most recent completed attempt +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 +} +} +status.StudentResults = append(status.StudentResults, r) +} +return status, nil +} diff --git a/database/exam.go b/database/exam.go new file mode 100644 index 0000000..379f6e7 --- /dev/null +++ b/database/exam.go @@ -0,0 +1,426 @@ +package database + +import ( + "database/sql" + "encoding/json" + "fmt" + "math/rand" + "time" + + "github.com/ZipCodeCore/zip-athena/models" +) + +// ---- SQLiteDB implementation of ExamRepository ---- + +func (db *SQLiteDB) CreateExam(exam *models.Exam) error { + categoriesJSON, _ := json.Marshal(exam.Categories) + difficultyJSON, _ := json.Marshal(exam.DifficultyLevels) + questionIDsJSON, _ := json.Marshal(exam.QuestionIDs) + + result, err := db.db.Exec( + `INSERT INTO exams (name, categories, difficulty_levels, question_ids, question_count, access_token, created_by, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + exam.Name, string(categoriesJSON), string(difficultyJSON), string(questionIDsJSON), + exam.QuestionCount, exam.AccessToken, exam.CreatedBy, exam.CreatedAt, + ) + if err != nil { + return err + } + id, err := result.LastInsertId() + if err != nil { + return err + } + exam.ID = int(id) + return nil +} + +func (db *SQLiteDB) GetExam(id int) (*models.Exam, error) { + return db.scanExam(db.db.QueryRow( + `SELECT id, name, categories, difficulty_levels, question_ids, question_count, access_token, created_by, created_at + FROM exams WHERE id = ?`, id)) +} + +func (db *SQLiteDB) GetExamByToken(token string) (*models.Exam, error) { + return db.scanExam(db.db.QueryRow( + `SELECT id, name, categories, difficulty_levels, question_ids, question_count, access_token, created_by, created_at + FROM exams WHERE access_token = ?`, token)) +} + +func (db *SQLiteDB) scanExam(row *sql.Row) (*models.Exam, error) { + exam := &models.Exam{} + var catJSON, diffJSON, qidsJSON string + err := row.Scan( + &exam.ID, &exam.Name, &catJSON, &diffJSON, &qidsJSON, + &exam.QuestionCount, &exam.AccessToken, &exam.CreatedBy, &exam.CreatedAt, + ) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + json.Unmarshal([]byte(catJSON), &exam.Categories) + json.Unmarshal([]byte(diffJSON), &exam.DifficultyLevels) + json.Unmarshal([]byte(qidsJSON), &exam.QuestionIDs) + return exam, nil +} + +func (db *SQLiteDB) ListExams() ([]*models.Exam, error) { + rows, err := db.db.Query( + `SELECT id, name, categories, difficulty_levels, question_ids, question_count, access_token, created_by, created_at + FROM exams ORDER BY created_at DESC`) + if err != nil { + return nil, err + } + defer rows.Close() + + var exams []*models.Exam + for rows.Next() { + exam := &models.Exam{} + var catJSON, diffJSON, qidsJSON string + if err := rows.Scan( + &exam.ID, &exam.Name, &catJSON, &diffJSON, &qidsJSON, + &exam.QuestionCount, &exam.AccessToken, &exam.CreatedBy, &exam.CreatedAt, + ); err != nil { + return nil, err + } + json.Unmarshal([]byte(catJSON), &exam.Categories) + json.Unmarshal([]byte(diffJSON), &exam.DifficultyLevels) + json.Unmarshal([]byte(qidsJSON), &exam.QuestionIDs) + exams = append(exams, exam) + } + if exams == nil { + exams = []*models.Exam{} + } + return exams, rows.Err() +} + +// GetQuestionsByCategories returns up to `limit` questions from the given +// categories and difficulty levels, chosen in random order from all matches. +// DifficultyLevels mapping: 1 = difficulty 1-2, 2 = difficulty 3-4, 3 = difficulty 5-7. +func (db *SQLiteDB) GetQuestionsByCategories(categories []string, difficultyLevels []int, limit int) ([]*models.Question, error) { + diffRanges := difficultyRanges(difficultyLevels) + + // Build a query that joins topics for category filtering and filters by difficulty + query := ` + SELECT DISTINCT q.id, q.topic_id, q.question_text, q.difficulty, q.tags, q.topic_question_id, q.created_at + FROM questions q + JOIN topics t ON q.topic_id = t.id + WHERE t.is_active = 1 + ` + args := []interface{}{} + + if len(categories) > 0 { + placeholders := make([]string, len(categories)) + for i, c := range categories { + placeholders[i] = "?" + args = append(args, c) + } + query += " AND (t.category IN (" + joinStrings(placeholders, ",") + ") OR t.category = 'all')" + } + + if len(diffRanges) > 0 { + conds := make([]string, len(diffRanges)) + for i, r := range diffRanges { + conds[i] = "(q.difficulty >= ? AND q.difficulty <= ?)" + args = append(args, r[0], r[1]) + } + query += " AND (" + joinStrings(conds, " OR ") + ")" + } + + rows, err := db.db.Query(query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var all []*models.Question + for rows.Next() { + q := &models.Question{} + var tagsJSON string + if err := rows.Scan(&q.ID, &q.TopicID, &q.QuestionText, &q.Difficulty, &tagsJSON, &q.TopicQuestionID, &q.CreatedAt); err != nil { + return nil, err + } + json.Unmarshal([]byte(tagsJSON), &q.Tags) + all = append(all, q) + } + if err := rows.Err(); err != nil { + return nil, err + } + + // Shuffle and cap to limit + rand.Shuffle(len(all), func(i, j int) { all[i], all[j] = all[j], all[i] }) + if limit > 0 && len(all) > limit { + all = all[:limit] + } + return all, nil +} + +func (db *SQLiteDB) AssignExamToUser(examID, userID, assignedBy int) error { + _, err := db.db.Exec( + `INSERT OR IGNORE INTO exam_assignments (exam_id, user_id, assigned_by, assigned_at) VALUES (?, ?, ?, ?)`, + examID, userID, assignedBy, time.Now(), + ) + return err +} + +func (db *SQLiteDB) GetAssignedExamsForUser(userID int) ([]*models.ExamInfo, error) { + 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 + FROM exam_assignments ea + JOIN exams e ON ea.exam_id = e.id + LEFT JOIN exam_attempts att ON att.exam_id = e.id + AND att.user_id = ea.user_id + AND att.completed_at IS NOT NULL + AND att.id = ( + SELECT MAX(a2.id) FROM exam_attempts a2 + WHERE a2.exam_id = e.id AND a2.user_id = ea.user_id AND a2.completed_at IS NOT NULL + ) + WHERE ea.user_id = ? + ORDER BY ea.assigned_at DESC + ` + rows, err := db.db.Query(query, userID) + if err != nil { + return nil, err + } + defer rows.Close() + + var result []*models.ExamInfo + for rows.Next() { + info := &models.ExamInfo{} + 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, + ); err != nil { + return nil, err + } + if completedAt.Valid { + info.CompletedAt = &completedAt.Time + if correctAnswers.Valid { + ca := int(correctAnswers.Int64) + info.CorrectAnswers = &ca + } + if totalQuestions.Valid { + tq := int(totalQuestions.Int64) + info.TotalQuestions = &tq + } + if score.Valid { + s := score.Float64 + info.Score = &s + } + } + result = append(result, info) + } + if result == nil { + result = []*models.ExamInfo{} + } + return result, rows.Err() +} + +func (db *SQLiteDB) CreateExamAttempt(attempt *models.ExamAttempt) error { + answersJSON, _ := json.Marshal(attempt.Answers) + resultsJSON, _ := json.Marshal(attempt.QuestionResults) + + result, err := db.db.Exec( + `INSERT INTO exam_attempts (exam_id, user_id, started_at, total_questions, correct_answers, score, answers, question_results) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + attempt.ExamID, attempt.UserID, attempt.StartedAt, + attempt.TotalQuestions, attempt.CorrectAnswers, attempt.Score, + string(answersJSON), string(resultsJSON), + ) + if err != nil { + return err + } + id, err := result.LastInsertId() + if err != nil { + return err + } + attempt.ID = int(id) + return nil +} + +func (db *SQLiteDB) GetExamAttempt(id int) (*models.ExamAttempt, error) { + attempt := &models.ExamAttempt{} + var completedAt sql.NullTime + var answersJSON, resultsJSON string + + err := db.db.QueryRow( + `SELECT id, exam_id, user_id, started_at, completed_at, total_questions, correct_answers, score, answers, question_results + FROM exam_attempts WHERE id = ?`, id, + ).Scan( + &attempt.ID, &attempt.ExamID, &attempt.UserID, &attempt.StartedAt, &completedAt, + &attempt.TotalQuestions, &attempt.CorrectAnswers, &attempt.Score, + &answersJSON, &resultsJSON, + ) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + if completedAt.Valid { + attempt.CompletedAt = &completedAt.Time + } + json.Unmarshal([]byte(answersJSON), &attempt.Answers) + json.Unmarshal([]byte(resultsJSON), &attempt.QuestionResults) + return attempt, nil +} + +// SubmitExamAttempt grades the exam and records the results. +func (db *SQLiteDB) SubmitExamAttempt(attemptID int, answers map[string]int) error { + attempt, err := db.GetExamAttempt(attemptID) + if err != nil { + return err + } + + exam, err := db.GetExam(attempt.ExamID) + if err != nil { + return err + } + + attempt.Answers = answers + attempt.QuestionResults = make(map[string]bool) + attempt.CorrectAnswers = 0 + attempt.TotalQuestions = len(exam.QuestionIDs) + + for _, qid := range exam.QuestionIDs { + key := itoa(qid) + answerID, ok := answers[key] + if !ok { + attempt.QuestionResults[key] = false + continue + } + answer, err := db.GetAnswer(answerID) + if err == nil && answer.QuestionID == qid && answer.IsCorrect { + attempt.CorrectAnswers++ + attempt.QuestionResults[key] = true + } else { + attempt.QuestionResults[key] = false + } + } + + if attempt.TotalQuestions > 0 { + attempt.Score = float64(attempt.CorrectAnswers) / float64(attempt.TotalQuestions) * 100 + } + now := time.Now() + attempt.CompletedAt = &now + + answersJSON, _ := json.Marshal(attempt.Answers) + resultsJSON, _ := json.Marshal(attempt.QuestionResults) + + _, err = db.db.Exec( + `UPDATE exam_attempts SET completed_at = ?, total_questions = ?, correct_answers = ?, score = ?, answers = ?, question_results = ? + WHERE id = ?`, + now, attempt.TotalQuestions, attempt.CorrectAnswers, attempt.Score, + string(answersJSON), string(resultsJSON), attemptID, + ) + return err +} + +func (db *SQLiteDB) GetExamStatus(examID int) (*models.ExamStatus, error) { + exam, err := db.GetExam(examID) + if err != nil { + return nil, err + } + + status := &models.ExamStatus{ + ExamID: exam.ID, + ExamName: exam.Name, + QuestionCount: exam.QuestionCount, + StudentResults: []models.ExamStudentResult{}, + } + + query := ` + SELECT u.id, u.username, ea.assigned_at, + 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 + AND att.user_id = ea.user_id + AND att.completed_at IS NOT NULL + AND att.id = ( + SELECT MAX(a2.id) FROM exam_attempts a2 + WHERE a2.exam_id = ea.exam_id AND a2.user_id = ea.user_id AND a2.completed_at IS NOT NULL + ) + WHERE ea.exam_id = ? + ORDER BY u.username + ` + rows, err := db.db.Query(query, examID) + if err != nil { + return nil, err + } + defer rows.Close() + + for rows.Next() { + r := models.ExamStudentResult{} + 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, + ); err != nil { + return nil, err + } + if completedAt.Valid { + r.CompletedAt = &completedAt.Time + if correctAnswers.Valid { + ca := int(correctAnswers.Int64) + r.CorrectAnswers = &ca + } + if totalQuestions.Valid { + tq := int(totalQuestions.Int64) + r.TotalQuestions = &tq + } + if score.Valid { + s := score.Float64 + r.Score = &s + } + } + status.StudentResults = append(status.StudentResults, r) + } + return status, rows.Err() +} + +// ---- helpers ---- + +func joinStrings(ss []string, sep string) string { + result := "" + for i, s := range ss { + if i > 0 { + result += sep + } + result += s + } + return result +} + +func itoa(n int) string { + return json.Number(fmt.Sprintf("%d", n)).String() +} + +// difficultyRanges converts exam difficulty levels (1,2,3) to [min,max] DB ranges. +func difficultyRanges(levels []int) [][2]int { + mapping := map[int][2]int{ + 1: {1, 2}, + 2: {3, 4}, + 3: {5, 7}, + } + var result [][2]int + seen := map[int]bool{} + for _, l := range levels { + if r, ok := mapping[l]; ok && !seen[l] { + result = append(result, r) + seen[l] = true + } + } + return result +} diff --git a/database/migrations/006_assigned_exams.down.sql b/database/migrations/006_assigned_exams.down.sql new file mode 100644 index 0000000..9339ec9 --- /dev/null +++ b/database/migrations/006_assigned_exams.down.sql @@ -0,0 +1,4 @@ +-- Rollback assigned exams feature +DROP TABLE IF EXISTS exam_attempts; +DROP TABLE IF EXISTS exam_assignments; +DROP TABLE IF EXISTS exams; diff --git a/database/migrations/006_assigned_exams.up.sql b/database/migrations/006_assigned_exams.up.sql new file mode 100644 index 0000000..42d683a --- /dev/null +++ b/database/migrations/006_assigned_exams.up.sql @@ -0,0 +1,49 @@ +-- Add assigned exams feature +-- Exams are distinct from quizzes: they are generated from random questions +-- filtered by category and difficulty level. + +CREATE TABLE IF NOT EXISTS exams ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + categories TEXT NOT NULL DEFAULT '[]', -- JSON array of category strings + difficulty_levels TEXT NOT NULL DEFAULT '[]', -- JSON array of ints (1=easy,2=medium,3=hard) + question_ids TEXT NOT NULL DEFAULT '[]', -- JSON array of question IDs selected at generation time + question_count INTEGER NOT NULL DEFAULT 30, + access_token TEXT NOT NULL UNIQUE, -- Unique token for exam URL + created_by INTEGER NOT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (created_by) REFERENCES users(id) +); + +CREATE TABLE IF NOT EXISTS exam_assignments ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + exam_id INTEGER NOT NULL, + user_id INTEGER NOT NULL, + assigned_at DATETIME DEFAULT CURRENT_TIMESTAMP, + assigned_by INTEGER NOT NULL, + FOREIGN KEY (exam_id) REFERENCES exams(id) ON DELETE CASCADE, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + FOREIGN KEY (assigned_by) REFERENCES users(id), + UNIQUE(exam_id, user_id) +); + +CREATE TABLE IF NOT EXISTS exam_attempts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + exam_id INTEGER NOT NULL, + user_id INTEGER NOT NULL, + started_at DATETIME DEFAULT CURRENT_TIMESTAMP, + completed_at DATETIME, + total_questions INTEGER DEFAULT 0, + correct_answers INTEGER DEFAULT 0, + score REAL DEFAULT 0.0, + answers TEXT DEFAULT '{}', -- JSON: question_id -> answer_id + question_results TEXT DEFAULT '{}', -- JSON: question_id -> bool (correct/incorrect) + FOREIGN KEY (exam_id) REFERENCES exams(id) ON DELETE CASCADE, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE +); + +CREATE INDEX IF NOT EXISTS idx_exams_token ON exams(access_token); +CREATE INDEX IF NOT EXISTS idx_exam_assignments_exam ON exam_assignments(exam_id); +CREATE INDEX IF NOT EXISTS idx_exam_assignments_user ON exam_assignments(user_id); +CREATE INDEX IF NOT EXISTS idx_exam_attempts_exam ON exam_attempts(exam_id); +CREATE INDEX IF NOT EXISTS idx_exam_attempts_user ON exam_attempts(user_id); diff --git a/models/models.go b/models/models.go index 27995e4..f6ec7cd 100644 --- a/models/models.go +++ b/models/models.go @@ -434,6 +434,74 @@ type FlaggedQuestion struct { TotalAttempts int `json:"total_attempts,omitempty"` } +// Exam represents a named assigned exam generated from random questions +// filtered by category and difficulty level. +type Exam struct { + ID int `json:"id"` + Name string `json:"name"` + Categories []string `json:"categories"` // e.g. ["java","python"] + DifficultyLevels []int `json:"difficulty_levels"` // 1=easy,2=medium,3=hard + QuestionIDs []int `json:"question_ids"` // IDs chosen at generation time + QuestionCount int `json:"question_count"` + AccessToken string `json:"access_token"` + CreatedBy int `json:"created_by"` + CreatedAt time.Time `json:"created_at"` +} + +// ExamAssignment represents an exam assigned to a specific student +type ExamAssignment struct { + ID int `json:"id"` + ExamID int `json:"exam_id"` + UserID int `json:"user_id"` + AssignedAt time.Time `json:"assigned_at"` + AssignedBy int `json:"assigned_by"` +} + +// ExamAttempt records a student's attempt at an exam +type ExamAttempt struct { + ID int `json:"id"` + ExamID int `json:"exam_id"` + UserID int `json:"user_id"` + StartedAt time.Time `json:"started_at"` + CompletedAt *time.Time `json:"completed_at,omitempty"` + TotalQuestions int `json:"total_questions"` + CorrectAnswers int `json:"correct_answers"` + Score float64 `json:"score"` + Answers map[string]int `json:"answers"` // question_id -> answer_id + QuestionResults map[string]bool `json:"question_results"` // question_id -> correct +} + +// ExamStudentResult summarises one student's result for an exam +type ExamStudentResult struct { + UserID int `json:"user_id"` + Username string `json:"username"` + AssignedAt time.Time `json:"assigned_at"` + CompletedAt *time.Time `json:"completed_at,omitempty"` + Score *float64 `json:"score,omitempty"` + CorrectAnswers *int `json:"correct_answers,omitempty"` + TotalQuestions *int `json:"total_questions,omitempty"` +} + +// ExamStatus is the instructor view of an exam and all student results +type ExamStatus struct { + ExamID int `json:"exam_id"` + ExamName string `json:"exam_name"` + QuestionCount int `json:"question_count"` + StudentResults []ExamStudentResult `json:"student_results"` +} + +// ExamInfo combines exam info with assignment details for the student view +type ExamInfo struct { + ExamAssignment + ExamName string `json:"exam_name"` + QuestionCount int `json:"question_count"` + AccessToken string `json:"access_token"` + CompletedAt *time.Time `json:"completed_at,omitempty"` + Score *float64 `json:"score,omitempty"` + CorrectAnswers *int `json:"correct_answers,omitempty"` + TotalQuestions *int `json:"total_questions,omitempty"` +} + // FlagReason constants (Phase 5) const ( FlagReasonTooHard = "TOO_HARD" // <30% accuracy diff --git a/router/router.go b/router/router.go index c2bdb53..4c9c50d 100644 --- a/router/router.go +++ b/router/router.go @@ -64,6 +64,11 @@ func New(h *api.Handler) *chi.Mux { r.Get("/assigned-quizzes", h.GetAssignedQuizzesHandler) r.Post("/assigned-quizzes/start", h.TakeAssignedQuizHandler) + // Assigned Exam routes (student) + r.Get("/assigned-exams", h.GetAssignedExamsHandler) + r.Post("/exam/start", h.StartExamHandler) + r.Post("/exam/submit", h.SubmitExamHandler) + r.Route("/quizzes", func(r chi.Router) { r.Get("/", h.GetQuizHandler) }) @@ -221,6 +226,13 @@ func New(h *api.Handler) *chi.Mux { r.Get("/assigned-quizzes/status", h.ListAssignedQuizzesStatusHandler) r.Get("/assigned-quizzes/status/quiz", h.GetAssignedQuizStatusHandler) + // Assigned Exam routes + r.Post("/exams/generate", h.GenerateExamHandler) + r.Get("/exams", h.ListExamsHandler) + r.Post("/exams/assign", h.AssignExamToStudentsHandler) + r.Get("/exams/status", h.GetExamStatusHandler) + r.Get("/exams/categories", h.GetAvailableExamCategoriesHandler) + // Topic Management routes r.Route("/topics", func(r chi.Router) { r.Post("/", h.CreateInstructorTopicHandler) diff --git a/static/dashboard.html b/static/dashboard.html index 3ef024a..26ddfd1 100644 --- a/static/dashboard.html +++ b/static/dashboard.html @@ -50,9 +50,12 @@