admin: implement MCQ edition in interface

This commit is contained in:
nemunaire 2018-06-24 18:12:26 +02:00 committed by Pierre-Olivier Mercier
parent 92ba880006
commit 3a65363ebb
3 changed files with 137 additions and 0 deletions

View file

@ -38,6 +38,7 @@ func init() {
router.GET("/api/exercices/:eid/quiz", apiHandler(exerciceHandler(listExerciceQuiz)))
router.GET("/api/exercices/:eid/quiz/:qid", apiHandler(quizHandler(showExerciceQuiz)))
router.PUT("/api/exercices/:eid/quiz/:qid", apiHandler(quizHandler(updateExerciceQuiz)))
router.DELETE("/api/exercices/:eid/quiz/:qid", apiHandler(quizHandler(deleteExerciceQuiz)))
// Synchronize
@ -239,7 +240,71 @@ func showExerciceQuiz(quiz fic.MCQ, _ fic.Exercice, body []byte) (interface{}, e
return quiz, nil
}
func updateExerciceQuiz(quiz fic.MCQ, exercice fic.Exercice, body []byte) (interface{}, error) {
var uq fic.MCQ
if err := json.Unmarshal(body, &uq); err != nil {
return nil, err
}
quiz.Title = uq.Title
if _, err := quiz.Update(); err != nil {
return nil, err
}
// Update and remove old entries
var delete []int
for i, cur := range quiz.Entries {
seen := false
for _, next := range uq.Entries {
if cur.Id == next.Id {
seen = true
if cur.Label != next.Label || cur.Response != next.Response {
cur.Label = next.Label
cur.Response = next.Response
if _, err := cur.Update(); err != nil {
return nil, err
}
}
break
}
}
if seen == false {
if _, err := cur.Delete(); err != nil {
return nil, err
} else {
delete = append(delete, i)
}
}
}
for n, i := range delete {
quiz.Entries = append(quiz.Entries[:i-n-1], quiz.Entries[:i-n+1]...)
}
// Add new choices
for _, choice := range uq.Entries {
if choice.Id == 0 {
if c, err := quiz.AddEntry(choice.Label, choice.Response); err != nil {
return nil, err
} else {
quiz.Entries = append(quiz.Entries, c)
}
}
}
return quiz, nil
}
func deleteExerciceQuiz(quiz fic.MCQ, _ fic.Exercice, _ []byte) (interface{}, error) {
for _, choice := range quiz.Entries {
if _, err := choice.Delete(); err != nil {
return nil, err
}
}
return quiz.Delete()
}