diff --git a/internal/handlers/test.go b/internal/handlers/test.go index c3ac36e..977b7d9 100644 --- a/internal/handlers/test.go +++ b/internal/handlers/test.go @@ -7,7 +7,9 @@ import ( "log/slog" "math/rand" "net/http" + "os" "strconv" + "strings" "time" "github.com/go-chi/chi/v5" @@ -18,6 +20,9 @@ import ( "qbank/internal/sampling" ) +// happyCatThreshold is the minimum score percentage to show a happy cat. +const happyCatThreshold = 60 + type TestHandler struct { auth *auth.Manager repo *db.Repo @@ -302,11 +307,18 @@ func (h *TestHandler) ResultsGet(w http.ResponseWriter, r *http.Request) { } } + mood := "sad" + if test.NQuestions > 0 && nCorrect*100/test.NQuestions >= happyCatThreshold { + mood = "happy" + } + catURL := randomCatURL(mood) + data := BaseData(h.auth, r) data["Test"] = test data["Items"] = items data["NCorrect"] = nCorrect data["TimeTaken"] = timeTaken + data["CatURL"] = catURL h.render.Render(w, http.StatusOK, "test_results", data) } @@ -342,6 +354,32 @@ func (h *TestHandler) loadTestAndN(w http.ResponseWriter, r *http.Request) (int, return n, test, true } +// randomCatURL picks a random image from web/static/cats// and returns +// its URL path, or an empty string if the folder is missing or empty. +func randomCatURL(mood string) string { + dir := "web/static/cats/" + mood + entries, err := os.ReadDir(dir) + if err != nil { + return "" + } + var images []string + for _, e := range entries { + if e.IsDir() { + continue + } + n := strings.ToLower(e.Name()) + if strings.HasSuffix(n, ".jpg") || strings.HasSuffix(n, ".jpeg") || + strings.HasSuffix(n, ".png") || strings.HasSuffix(n, ".gif") || + strings.HasSuffix(n, ".webp") { + images = append(images, e.Name()) + } + } + if len(images) == 0 { + return "" + } + return "/static/cats/" + mood + "/" + images[rand.Intn(len(images))] +} + // deterministicShuffle returns a copy of answers shuffled by a seed derived // from the test ID and question ID, so the order is stable across page reloads. func deterministicShuffle(answers []*models.Answer, testID int64, questionID string) []*models.Answer { diff --git a/web/static/cats/happy/.gitkeep b/web/static/cats/happy/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/web/static/cats/sad/.gitkeep b/web/static/cats/sad/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/web/templates/test_results.html b/web/templates/test_results.html index e4c556e..365f034 100644 --- a/web/templates/test_results.html +++ b/web/templates/test_results.html @@ -11,6 +11,15 @@ {{end}} + +{{if .CatURL}} +
+ +
+{{end}} +
{{range $i, $item := .Items}}