Complete first iteration of question/answer MVC

This commit is contained in:
Andrea Fazzi 2019-11-13 15:54:17 +01:00
parent dbccda3279
commit 71997176b7
13 changed files with 242 additions and 174 deletions

View file

@ -1,8 +1,10 @@
package orm package orm
import ( import (
"github.com/jinzhu/gorm"
"net/http" "net/http"
"git.andreafazzi.eu/andrea/oef/renderer"
"github.com/jinzhu/gorm"
) )
type Answer struct { type Answer struct {
@ -11,7 +13,11 @@ type Answer struct {
Text string Text string
Correct bool Correct bool
QuestionID uint Question *Question
QuestionID uint `schema:"question_id"`
AllQuestions []*Question `gorm:"-"`
Selected map[uint]string `gorm:"-"`
} }
func (a *Answer) GetID() uint { return a.ID } func (a *Answer) GetID() uint { return a.ID }
@ -21,11 +27,37 @@ func (a *Answer) String() string {
} }
func (a *Answer) Create(args map[string]string, r *http.Request) (interface{}, error) { func (a *Answer) Create(args map[string]string, r *http.Request) (interface{}, error) {
return nil, nil if r.Method == "GET" {
answer := new(Answer)
if err := DB().Find(&answer.AllQuestions).Error; err != nil {
return nil, err
}
return answer, nil
} else {
answer := new(Answer)
err := renderer.Decode(answer, r)
if err != nil {
return nil, err
}
answer, err = CreateAnswer(answer)
if err != nil {
return nil, err
}
return answer, nil
}
} }
func (a *Answer) Read(args map[string]string, r *http.Request) (interface{}, error) { func (a *Answer) Read(args map[string]string, r *http.Request) (interface{}, error) {
return nil, nil var answer Answer
id := args["id"]
if err := DB().Preload("Question").First(&answer, id).Error; err != nil {
return nil, err
}
return &answer, nil
} }
func (a *Answer) ReadAll(args map[string]string, r *http.Request) (interface{}, error) { func (a *Answer) ReadAll(args map[string]string, r *http.Request) (interface{}, error) {
@ -37,9 +69,57 @@ func (a *Answer) ReadAll(args map[string]string, r *http.Request) (interface{},
} }
func (a *Answer) Update(args map[string]string, r *http.Request) (interface{}, error) { func (a *Answer) Update(args map[string]string, r *http.Request) (interface{}, error) {
return nil, nil if r.Method == "GET" {
result, err := a.Read(args, r)
if err != nil {
return nil, err
}
answer := result.(*Answer)
if err := DB().Find(&answer.AllQuestions).Error; err != nil {
return nil, err
}
answer.Selected = make(map[uint]string)
answer.Selected[answer.QuestionID] = "selected"
return answer, nil
} else {
answer, err := a.Read(args, nil)
if err != nil {
return nil, err
}
err = renderer.Decode(answer, r)
if err != nil {
return nil, err
}
_, err = SaveAnswer(answer)
if err != nil {
return nil, err
}
answer, err = a.Read(args, nil)
if err != nil {
return nil, err
}
return answer.(*Answer), nil
}
} }
func (a *Answer) Delete(args map[string]string, r *http.Request) (interface{}, error) { func (a *Answer) Delete(args map[string]string, r *http.Request) (interface{}, error) {
return nil, nil return nil, nil
} }
func CreateAnswer(answer *Answer) (*Answer, error) {
if err := DB().Create(answer).Error; err != nil {
return nil, err
}
return answer, nil
}
func SaveAnswer(answer interface{}) (interface{}, error) {
if err := DB().Omit("Answers").Save(answer).Error; err != nil {
return nil, err
}
return answer, nil
}

View file

@ -11,6 +11,8 @@ type Question struct {
gorm.Model gorm.Model
Text string Text string
Answers []*Answer
} }
func (q *Question) GetID() uint { return q.ID } func (q *Question) GetID() uint { return q.ID }
@ -37,7 +39,15 @@ func (q *Question) Create(args map[string]string, r *http.Request) (interface{},
} }
func (q *Question) Read(args map[string]string, r *http.Request) (interface{}, error) { func (q *Question) Read(args map[string]string, r *http.Request) (interface{}, error) {
return nil, nil var question Question
id := args["id"]
if err := DB().Preload("Answers").Where("id = ?", id).Find(&question).Error; err != nil {
return nil, err
}
return &question, nil
} }
func (q *Question) ReadAll(args map[string]string, r *http.Request) (interface{}, error) { func (q *Question) ReadAll(args map[string]string, r *http.Request) (interface{}, error) {
@ -49,7 +59,27 @@ func (q *Question) ReadAll(args map[string]string, r *http.Request) (interface{}
} }
func (q *Question) Update(args map[string]string, r *http.Request) (interface{}, error) { func (q *Question) Update(args map[string]string, r *http.Request) (interface{}, error) {
return nil, nil if r.Method == "GET" {
return q.Read(args, r)
} else {
question, err := q.Read(args, nil)
if err != nil {
return nil, err
}
err = renderer.Decode(question, r)
if err != nil {
return nil, err
}
_, err = SaveQuestion(question)
if err != nil {
return nil, err
}
question, err = q.Read(args, nil)
if err != nil {
return nil, err
}
return question.(*Question), nil
}
} }
func (q *Question) Delete(args map[string]string, r *http.Request) (interface{}, error) { func (q *Question) Delete(args map[string]string, r *http.Request) (interface{}, error) {
@ -62,3 +92,10 @@ func CreateQuestion(question *Question) (*Question, error) {
} }
return question, nil return question, nil
} }
func SaveQuestion(question interface{}) (interface{}, error) {
if err := DB().Omit("Answers").Save(question).Error; err != nil {
return nil, err
}
return question, nil
}

View file

@ -13,6 +13,10 @@ import (
yml "gopkg.in/yaml.v2" yml "gopkg.in/yaml.v2"
) )
const (
MaxTextLength = 20
)
var ( var (
funcMap = template.FuncMap{ funcMap = template.FuncMap{
"query": query, "query": query,
@ -39,9 +43,18 @@ var (
"active": active, "active": active,
"pluralize": pluralize, "pluralize": pluralize,
"lower": lower, "lower": lower,
"trim": trim,
} }
) )
func trim(text string) string {
var result string
if len(text) > MaxTextLength {
result = text[0:MaxTextLength]
}
return result + "…"
}
func modelName(value interface{}) string { func modelName(value interface{}) string {
t := reflect.TypeOf(value) t := reflect.TypeOf(value)
switch t.Kind() { switch t.Kind() {

View file

@ -229,7 +229,7 @@ func (rend *HTMLRenderer) writeError(w http.ResponseWriter, r *http.Request, dat
log.Println(data.(*htmlTemplateData).Data.(error)) log.Println(data.(*htmlTemplateData).Data.(error))
w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Content-Type", "text/html; charset=utf-8")
e := t.ExecuteTemplate(w, "base", data) e := t.ExecuteTemplate(w, "error", data)
if e != nil { if e != nil {
panic(e) panic(e)
} }
@ -237,17 +237,17 @@ func (rend *HTMLRenderer) writeError(w http.ResponseWriter, r *http.Request, dat
func (rend *HTMLRenderer) Render(w http.ResponseWriter, r *http.Request, data interface{}, options ...url.Values) { func (rend *HTMLRenderer) Render(w http.ResponseWriter, r *http.Request, data interface{}, options ...url.Values) {
if data != nil && isErrorType(data) { if data != nil && isErrorType(data) {
rend.writeError(w, r, &htmlTemplateData{data.(error), options[0]}) rend.writeError(w, r, &htmlTemplateData{data.(error), nil})
} else { } else {
t, ok := rend.templates[options[0]["tpl_content"][0]] t, ok := rend.templates[options[0]["tpl_content"][0]]
if !ok { if !ok {
err := fmt.Errorf("Template %s not found", options[0]["tpl_content"][0]) err := fmt.Errorf("Template %s not found", options[0]["tpl_content"][0])
rend.writeError(w, r, &htmlTemplateData{err, options[0]}) rend.writeError(w, r, &htmlTemplateData{err, nil})
} }
w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Content-Type", "text/html; charset=utf-8")
err := t.ExecuteTemplate(w, options[0]["tpl_layout"][0], &htmlTemplateData{data, options[0]}) err := t.ExecuteTemplate(w, options[0]["tpl_layout"][0], &htmlTemplateData{data, options[0]})
if err != nil { if err != nil {
rend.writeError(w, r, &htmlTemplateData{err, options[0]}) rend.writeError(w, r, &htmlTemplateData{err, nil})
} }
} }
} }

View file

@ -19,6 +19,9 @@
role="form" role="form"
{{" id={{$form}}>"}} {{" id={{$form}}>"}}
{{" {{$options := ` { cancelTitle: \"Annulla\", saveTitle: \"Salva\", model: "}}"{{.Model}}"{{" `}} "}}
{{" {{template \"submit_cancel_buttons\" dict \"options\" ($options|yaml) \"id\" (.Data|field \"ID\") \"update\" $update}} "}}
</form> </form>
</div> </div>

View file

@ -2,60 +2,24 @@
<div class="container"> <div class="container">
<nav aria-label="breadcrumb"> {{" {{template \"breadcrumb\" toSlice \"ELEMENTS\" (all "}}"{{.Model}}"){{" (.Data|string) \"current\"}}"}}
<ol class="breadcrumb"> {{" {{template \"show_header\" dict \"title\" (.Data|string) \"updatePath\" (.Data.ID|update "}} "{{.Model}}"){{" \"deletePath\" (.Data.ID|delete "}}"{{.Model}}"){{ "}}" }}
<li class="breadcrumb-item"><a href="/{{.Models}}?{{"{{query \"tpl_layout\" \"base\" \"tpl_content\" "}}"{{.Models}}"}}">{{.Models}}</a></li>
<li class="breadcrumb-item active"><a href="#">{{"{{.Data.Name}}"}}</a></li>
</ol>
</nav>
<div class="karmen-info-header"> <h2 class="karmen-relation-header">GENERAL SECTION</h2>
<div class="row">
<div class="col-md-8">
<h1>{{"{{.Data.Name}}"}}</h1>
</div>
<div class="col-md-4">
<div class="btn-group pull-right" role="group">
<a href="/{{.Models}}/add/?{{"{{query \"tpl_layout\" \"base\" \"tpl_content\" "}}"{{.Models}}_add_update"}}" class="btn btn-success">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
Crea
</a>
<a href="/{{.Models}}/{{"{{.Data.ID}}"}}/update?{{"{{query \"tpl_layout\" \"base\" \"tpl_content\" "}}"{{.Models}}_add_update" "update" "true"}}" class="btn btn-primary">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
Modifica
</a>
<button href="/{{.Models}}/{{"{{.Data.ID}}"}}/delete"
data-url="/{{.Models}}/{{"{{.Data.ID}}"}}/delete"
class="btn btn-danger karmen-ajax-delete">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
Elimina
</button>
</div>
</div>
</div>
</div>
<div class="row"> <div class="row">
<div class="col-md-12"> <div class="col-md-12">
<h2 class="karmen-relation-header">sub items</h2> {{" {{$options := `"}}
{{"{{if .Data.Items}}"}} {{" title: \"RELATIONS\""}}
<div class="list-group" id="materie_list_group"> {{" model: \"MODEL\""}}
<a href="{{"/subjects/{{.Data.Subject.ID}}?{{query \"tpl_layout\" \"base\" \"tpl_content\" \"subjects_show\"}}"}}" class="list-group-item clearfix"> {{" icon: \"ICON_CLASS\""}}
<span class="glyphicon glyphicon-book"></span> {{" `}}"}}
{{"{{.Data.Subject.Name}}"}}
</a>
</div>
{{"{{else}}"}}
<p>All'attività non è associata alcuna materia
didattica. Clicca <a href="{{"/activities/update?{{query \"tpl_layout\" \"base\" \"tpl_content\" \"activities_add_update\"}}"}}">qui</a> per
modificare questa attività didattica.</p>
{{"{{end}}"}}
</div>
{{" {{$noElements := \"NO ELEMENTS\"}}"}}
{{" {{template \"relation_list\" dict \"options\" ($options|yaml) \"data\" .Data.RELATIONS \"noElements\" $noElements}} "}}
</div>
</div> </div>
</div> </div>

View file

@ -16,7 +16,7 @@
<div class="list-group" id="myUL"> <div class="list-group" id="myUL">
{{range $element := .Data}} {{range $element := .Data}}
<a class="list-group-item list-group-item-action" href={{$element.ID|show "Answer"}}> <a class="list-group-item list-group-item-action" href={{$element.ID|show "Answer"}}>
<span class="fa fa-user"></span> <span class="fa fa-reply"></span>
{{$element|string}} {{$element|string}}
<div class="text-right"> <div class="text-right">
{{$options := `noElements: "no subelements"`}} {{$options := `noElements: "no subelements"`}}

View file

@ -5,12 +5,12 @@
{{if $update}} {{if $update}}
{{template "breadcrumb" toSlice "Answers" (all "Answer") (.Data|string) (.Data.ID|show "Answer") "Aggiorna" "current"}} {{template "breadcrumb" toSlice "Risposte" (all "Answer") (.Data|string) (.Data.ID|show "Answer") "Aggiorna" "current"}}
{{else}} {{else}}
{{template "breadcrumb" toSlice "Answers" (all "Answer") "Aggiungi" "current"}} {{template "breadcrumb" toSlice "Risposte" (all "Answer") "Aggiungi" "current"}}
{{end}} {{end}}
{{template "add_update_header" dict "update" $update "addTitle" "Crea nuovo ELEMENTO" "updateTitle" (printf "Aggiorna ELEMENTO %s" (.Data|string))}} {{template "add_update_header" dict "update" $update "addTitle" "Crea nuova risposta" "updateTitle" (printf "Aggiorna risposta %s" (.Data|string|trim))}}
{{$form := "form_add_update"}} {{$form := "form_add_update"}}
<form <form
class="needs-validation" class="needs-validation"
@ -19,6 +19,15 @@
role="form" role="form"
id={{$form}}> id={{$form}}>
{{$options := ` { name: "Text",id: "answer_text",label: "Testo della risposta",placeholder: "Inserire il testo della risposta",type: "text",required: "true"} `}}
{{template "input" dict "options" ($options|yaml) "value" (.Data|field "Text") "update" $update}}
{{$options := ` { name: "question_id", id: "question_id", label: "Domanda relativa a questa risposta", title: "Seleziona la domanda"}`}}
{{template "select" dict "options" ($options|yaml) "data" (.Data|field "AllQuestions") "selected" (.Data|field "Selected") "update" $update "form" $form}}
{{$options := ` { cancelTitle: "Annulla", saveTitle: "Salva", model: "Answer"} `}}
{{template "submit_cancel_buttons" dict "options" ($options|yaml) "id" (.Data|field "ID") "update" $update}}
</form> </form>
</div> </div>

View file

@ -2,60 +2,26 @@
<div class="container"> <div class="container">
<nav aria-label="breadcrumb"> {{template "breadcrumb" toSlice "Risposte" (all "Answer") (.Data|string|trim) "current"}}
<ol class="breadcrumb"> {{template "show_header" dict "title" (.Data|string|trim) "updatePath" (.Data.ID|update "Answer") "deletePath" (.Data.ID|delete "Answer")}}
<li class="breadcrumb-item"><a href="/Answers?{{query "tpl_layout" "base" "tpl_content" "Answers"}}">Answers</a></li>
<li class="breadcrumb-item active"><a href="#">{{.Data.Name}}</a></li>
</ol>
</nav>
<div class="karmen-info-header">
<div class="row">
<div class="col-md-8">
<h1>{{.Data.Name}}</h1>
</div>
<div class="col-md-4">
<div class="btn-group pull-right" role="group">
<a href="/Answers/add/?{{query "tpl_layout" "base" "tpl_content" "Answers_add_update"}}" class="btn btn-success">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
Crea
</a>
<a href="/Answers/{{.Data.ID}}/update?{{query "tpl_layout" "base" "tpl_content" "Answers_add_update" "update" "true"}}" class="btn btn-primary">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
Modifica
</a>
<button href="/Answers/{{.Data.ID}}/delete"
data-url="/Answers/{{.Data.ID}}/delete"
class="btn btn-danger karmen-ajax-delete">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
Elimina
</button>
</div>
</div>
</div>
</div>
<h2 class="karmen-relation-header">Testo della risposta</h2>
<p>
{{.Data.Text}}
</p>
<div class="row"> <div class="row">
<div class="col-md-12"> <div class="col-md-12">
<h2 class="karmen-relation-header">sub items</h2> {{$options := `
{{if .Data.Items}} title: "Domanda relativa alla risposta"
<div class="list-group" id="materie_list_group"> model: "Question"
<a href="/subjects/{{.Data.Subject.ID}}?{{query "tpl_layout" "base" "tpl_content" "subjects_show"}}" class="list-group-item clearfix"> icon: "fa fa-question-circle"
<span class="glyphicon glyphicon-book"></span> `}}
{{.Data.Subject.Name}}
</a>
</div>
{{else}}
<p>All'attività non è associata alcuna materia
didattica. Clicca <a href="/activities/update?{{query "tpl_layout" "base" "tpl_content" "activities_add_update"}}">qui</a> per
modificare questa attività didattica.</p>
{{end}}
</div>
{{$noElements := "nessuna domanda relativa a questa risposta"}}
{{template "relation_list" dict "options" ($options|yaml) "data" .Data.Question "noElements" $noElements}}
</div>
</div> </div>
</div> </div>

View file

@ -1,10 +1,9 @@
{{ define "content" }} {{ define "content" }}
<div class="container"> <div class="container">
<h1>Errore</h1> <h1>Errore</h1>
<p> <p>
{{.}} {{.Data}}
</p> </p>
</div> </div>

View file

@ -0,0 +1,32 @@
{{define "error"}}
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/styles.css" />
<title>Olimpiadi di Economia e Finanza - Piattaforma di gara</title>
</head>
<body>
<nav class="navbar navbar-expand-lg fixed-top navbar-dark bg-primary">
<a class="navbar-brand" href="/teachers?{{query "tpl_layout" "base" "tpl_content" "teachers"}}">
<span class="fa fa-landmark"></span>
OEF 2020
</a>
<button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="navbar-toggler-icon"></span>
</button>
</nav>
<div class="base-template">
{{ template "content" . }}
</div>
<script src="/main.bundle.js"></script>
</body>
</html>
{{end}}

View file

@ -10,7 +10,7 @@
{{template "breadcrumb" toSlice "Domande" (all "Question") "Aggiungi" "current"}} {{template "breadcrumb" toSlice "Domande" (all "Question") "Aggiungi" "current"}}
{{end}} {{end}}
{{template "add_update_header" dict "update" $update "addTitle" "Crea nuova domanda" "updateTitle" (printf "Aggiorna domanda %s" (.Data|string))}} {{template "add_update_header" dict "update" $update "addTitle" "Crea nuova domanda" "updateTitle" (printf "Aggiorna domanda \"%s\"" (.Data|string|trim))}}
{{$form := "form_add_update"}} {{$form := "form_add_update"}}
<form <form
class="needs-validation" class="needs-validation"

View file

@ -2,60 +2,25 @@
<div class="container"> <div class="container">
<nav aria-label="breadcrumb"> {{template "breadcrumb" toSlice "Domande" (all "Question") (.Data|string|trim) "current"}}
<ol class="breadcrumb"> {{template "show_header" dict "title" (.Data|string|trim) "updatePath" (.Data.ID|update "Question") "deletePath" (.Data.ID|delete "Question")}}
<li class="breadcrumb-item"><a href="/Questions?{{query "tpl_layout" "base" "tpl_content" "Questions"}}">Questions</a></li>
<li class="breadcrumb-item active"><a href="#">{{.Data.Name}}</a></li>
</ol>
</nav>
<div class="karmen-info-header"> <h2 class="karmen-relation-header">Testo della domanda</h2>
<div class="row"> <p>{{.Data.Text}}</p>
<div class="col-md-8">
<h1>{{.Data.Name}}</h1>
</div>
<div class="col-md-4">
<div class="btn-group pull-right" role="group">
<a href="/Questions/add/?{{query "tpl_layout" "base" "tpl_content" "Questions_add_update"}}" class="btn btn-success">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
Crea
</a>
<a href="/Questions/{{.Data.ID}}/update?{{query "tpl_layout" "base" "tpl_content" "Questions_add_update" "update" "true"}}" class="btn btn-primary">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
Modifica
</a>
<button href="/Questions/{{.Data.ID}}/delete"
data-url="/Questions/{{.Data.ID}}/delete"
class="btn btn-danger karmen-ajax-delete">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
Elimina
</button>
</div>
</div>
</div>
</div>
<div class="row"> <div class="row">
<div class="col-md-12"> <div class="col-md-12">
<h2 class="karmen-relation-header">sub items</h2> {{$options := `
{{if .Data.Items}} title: "Risposte alla domanda"
<div class="list-group" id="materie_list_group"> model: "Answer"
<a href="/subjects/{{.Data.Subject.ID}}?{{query "tpl_layout" "base" "tpl_content" "subjects_show"}}" class="list-group-item clearfix"> icon: "fa fa-reply"
<span class="glyphicon glyphicon-book"></span> `}}
{{.Data.Subject.Name}}
</a>
</div>
{{else}}
<p>All'attività non è associata alcuna materia
didattica. Clicca <a href="/activities/update?{{query "tpl_layout" "base" "tpl_content" "activities_add_update"}}">qui</a> per
modificare questa attività didattica.</p>
{{end}}
</div>
{{$noElements := "Alla domanda non è associata alcuna risposta."}}
{{template "relation_list" dict "options" ($options|yaml) "data" .Data.Answers "noElements" $noElements}}
</div>
</div> </div>
</div> </div>