probo/cmd/serve/exam.go

82 lines
1.5 KiB
Go
Raw Normal View History

package serve
import (
"errors"
"net/http"
"git.andreafazzi.eu/andrea/probo/pkg/models"
"github.com/charmbracelet/log"
)
var ExamHandler = func(c *Controller, w http.ResponseWriter, r *http.Request) {
_, err := ValidateJwtCookie(r)
if err != nil {
panic(err)
}
2024-05-25 18:09:31 +02:00
participantID := r.PathValue("participantID")
session, err := c.sStore.Read(r.PathValue("uuid"))
if err != nil {
panic(err)
}
2024-05-25 18:09:31 +02:00
exam, ok := session.Exams[participantID]
if !ok {
panic(errors.New("Exam not found in the store!"))
}
examWithSession := struct {
*models.Exam
2024-05-25 18:09:31 +02:00
Session *models.Session
}{exam, session}
switch r.Method {
case http.MethodGet:
log.Info("Sending exam to", "participant", exam.Participant, "exam", exam)
err = c.ExecuteTemplate(w, examWithSession)
if err != nil {
panic(err)
}
case http.MethodPost:
err := r.ParseForm()
if err != nil {
panic(err)
}
answers := make([]*models.ParticipantAnswer, 0)
2024-05-25 18:09:31 +02:00
participant := session.Participants[participantID]
for quizID, values := range r.Form {
correct := false
2024-05-25 18:09:31 +02:00
quiz := session.Quizzes[quizID]
for _, answerID := range values {
if quiz.Correct.ID == answerID {
correct = true
}
answers = append(answers, &models.ParticipantAnswer{Quiz: quiz, Answer: session.Answers[answerID], Correct: correct})
}
}
response, err := c.rStore.Create(
&models.Response{
2024-05-25 18:09:31 +02:00
SessionTitle: session.Title,
Participant: participant,
Answers: answers,
})
if err != nil {
panic(err)
}
log.Info("Saving response", "response", response)
}
}