feat: add admin controllers, permissions and navigation for quizzes and attempts

This commit is contained in:
Jakub Zych
2026-10-02 14:17:43 +02:00
parent effe640549
commit 793cc4aac0
32 changed files with 1108 additions and 114 deletions

View File

@@ -2,12 +2,7 @@
package models
import (
"time"
"git.golem15.com/golem15/summercms/modules/pact"
"gorm.io/gorm"
)
import "time"
// Question types.
const (
@@ -56,91 +51,3 @@ func (Question) Rules() map[string]string {
"points": "required|integer|min:0",
}
}
// FilterDB returns the database the admin filter choices are read from. The
// plugin sets it at boot.
//
// TODO: requires SummerCMS change. pact.FilterOptions receives neither a
// context nor a database handle, so a model whose filter choices come from
// the database needs this package-level hook.
var FilterDB func() *gorm.DB
// Filter scopes of the questions admin list.
const (
ScopeByQuiz = "filterByQuiz"
ScopeByCategory = "filterByCategory"
)
// FilterScopes lists the admin list scopes the model answers.
func (Question) FilterScopes() []string { return []string{ScopeByQuiz, ScopeByCategory} }
// FilterScope narrows the admin list to the chosen quizzes or categories.
func (Question) FilterScope(name string, db *gorm.DB, value any) *gorm.DB {
if db == nil {
return db
}
values := filterValues(value)
if len(values) == 0 {
return db
}
switch name {
case ScopeByQuiz:
return db.Where("golem15_quizzes_questions.quiz_id IN ?", values)
case ScopeByCategory:
return db.Where("golem15_quizzes_questions.category IN ?", values)
}
return db
}
// FilterOptions serves the quizzes and the distinct categories as choices.
func (Question) FilterOptions(scope string) []pact.Option {
if FilterDB == nil {
return nil
}
db := FilterDB()
if db == nil {
return nil
}
var out []pact.Option
switch scope {
case ScopeByQuiz:
var quizzes []Quiz
if err := db.Select("id", "title").Order("title").Find(&quizzes).Error; err != nil {
return nil
}
for _, q := range quizzes {
out = append(out, pact.Option{Value: uintString(q.ID), Label: q.Title})
}
case ScopeByCategory:
var cats []string
if err := db.Model(&Question{}).Where("category IS NOT NULL AND category <> ''").
Distinct("category").Order("category").Pluck("category", &cats).Error; err != nil {
return nil
}
for _, c := range cats {
out = append(out, pact.Option{Value: c, Label: c})
}
}
return out
}
func filterValues(value any) []string {
switch v := value.(type) {
case string:
if v == "" {
return nil
}
return []string{v}
case []string:
return v
case []any:
out := make([]string, 0, len(v))
for _, x := range v {
if s, ok := x.(string); ok && s != "" {
out = append(out, s)
}
}
return out
}
return nil
}