7 Commits

16 changed files with 458 additions and 321 deletions

42
main.go
View File

@ -1,7 +1,6 @@
package main
import (
"fmt"
"html/template"
"log"
"net/http"
@ -10,47 +9,13 @@ import (
"streifling.com/jason/sicherheitsunterweisung/packages/session"
)
func handleParticipants(mux *http.ServeMux, db *data.DB, cp <-chan *data.Participant, s *session.Session) {
for participant := range cp {
mux.HandleFunc("/submit-participant/"+fmt.Sprint(s.ID)+"/"+fmt.Sprint(participant.Login)+"/", s.HandleParticipant(participant, &s.Questions, db))
for i := range s.Questions {
mux.HandleFunc("/submit-answer/"+fmt.Sprint(s.ID)+"/"+fmt.Sprint(participant.Login)+"/"+fmt.Sprint(i+1)+"/", s.HandleAnswer(db, participant, &s.Questions, int64(i+1)))
}
mux.HandleFunc("/retry/"+fmt.Sprint(s.ID)+"/"+fmt.Sprint(participant.Login)+"/", s.HandleRetry(participant, &s.Questions))
}
}
func handleSessions(mux *http.ServeMux, db *data.DB, cs <-chan *session.Session, ss *[]*session.Session) {
for s := range cs {
(*ss) = append(*ss, s)
participantChan := make(chan *data.Participant)
questionIDs := make([]string, 4)
for i := 0; i < len(questionIDs); i++ {
questionIDs[i] = fmt.Sprint(i + 1)
}
var err error
s.Questions, err = db.GetQuestions(questionIDs)
if err != nil {
log.Fatalln(err)
}
mux.HandleFunc("/new-briefing/", s.HandleNewBriefing())
mux.HandleFunc("/new-participant/"+fmt.Sprint(s.ID)+"/", s.HandleNewParticipant(participantChan))
mux.HandleFunc("/submit-form/"+fmt.Sprint(s.ID)+"/", s.HandleBriefingForm(db))
go handleParticipants(mux, db, participantChan, s)
}
}
func main() {
db, err := data.OpenDB("sicherheitsunterweisung")
if err != nil {
log.Fatalln(err)
}
mux := http.NewServeMux()
mux := session.NewMux()
sessions := make([]*session.Session, 0)
sessionChan := make(chan *session.Session)
@ -58,11 +23,10 @@ func main() {
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
template.Must(template.ParseFiles("templates/index.html", "templates/login.html")).Execute(w, nil)
})
mux.HandleFunc("/internal-login/", session.HandleInternalLogin(&sessions, sessionChan, db))
mux.HandleFunc("/internal-login/", session.HandleInternalLogin(db, &sessions, sessionChan))
mux.HandleFunc("/external-login/", session.HandleExternalLogin(&sessions))
mux.HandleFunc("/search/", session.HandleSearch(db))
go handleSessions(mux, db, sessionChan, &sessions)
go mux.HandleSessions(db, sessionChan, &sessions)
log.Fatalln(http.ListenAndServe(":8080", mux))
}

View File

@ -1,5 +1,11 @@
package data
import "database/sql"
type DB struct {
*sql.DB
}
type Person struct {
ID int64
FirstName string
@ -11,7 +17,6 @@ type Instructor Person
type Participant struct {
Person
Company string
Login string
}
type Briefing struct {

View File

@ -1,63 +1,13 @@
package data
import (
"bufio"
"database/sql"
"fmt"
"os"
"strings"
"syscall"
"github.com/go-sql-driver/mysql"
"golang.org/x/term"
)
type DB struct {
*sql.DB
Name string
}
func getUsername() (string, error) {
user := os.Getenv("DB_USER")
if user == "" {
var err error
fmt.Printf("DB Benutzer: ")
user, err = bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
return "", fmt.Errorf("getUsername: bufio.NewReader(os.Stdin).ReadString('\n'): %v", err)
}
}
return strings.TrimSpace(user), nil
}
func getPassword() (string, error) {
pass := os.Getenv("DB_PASS")
if pass == "" {
fmt.Printf("DB Passwort: ")
bytePass, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
return "", fmt.Errorf("getCredentials: term.ReadPassword(int(syscall.Stdin)): %v", err)
}
fmt.Println()
pass = strings.TrimSpace(string(bytePass))
}
return pass, nil
}
func getCredentials() (string, string, error) {
user, err := getUsername()
if err != nil {
return "", "", fmt.Errorf("getCredentials: getUsername(): %v", err)
}
pass, err := getPassword()
if err != nil {
return "", "", fmt.Errorf("getCredentials: getPassword(): %v", err)
}
return user, pass, nil
}
func OpenDB(dbName string) (*DB, error) {
var err error
db := new(DB)
@ -66,95 +16,82 @@ func OpenDB(dbName string) (*DB, error) {
cfg.DBName = dbName
cfg.User, cfg.Passwd, err = getCredentials()
if err != nil {
return nil, fmt.Errorf("Open: getCredentials(): %v\n", err)
return nil, fmt.Errorf("error: OpenDB: getCredentials(): %v", err)
}
db.Name = dbName
db.DB, err = sql.Open("mysql", cfg.FormatDSN())
if err != nil {
return nil, fmt.Errorf("Open: sql.Open(\"mysql\", cfg.FormatDSN()): %v\n", err)
return nil, fmt.Errorf("error: OpenDB: sql.Open(\"mysql\", cfg.FormatDSN()): %v", err)
}
if err := db.Ping(); err != nil {
return nil, fmt.Errorf("Open: db.Ping(): %v\n", err)
return nil, fmt.Errorf("error: OpenDB: db.Ping(): %v", err)
}
return db, nil
}
func (db *DB) WriteBriefing(b *Briefing) error {
result, err := db.Exec(`
query := `
INSERT INTO briefings
(date, time, location, document_name, as_of, instructor_id)
VALUES
(?, ?, ?, ?, ?, ?)
`, b.Date, b.Time, b.Location, b.DocumentName, b.AsOf, b.InstructorID)
`
result, err := db.Exec(query, b.Date, b.Time, b.Location, b.DocumentName, b.AsOf, b.InstructorID)
if err != nil {
return fmt.Errorf("*DB.writeBriefing: db.Exec(): %v\n", err)
return fmt.Errorf("error: *DB.writeBriefing: db.Exec(): %v", err)
}
b.ID, err = result.LastInsertId()
if err != nil {
return fmt.Errorf("*DB.writeBriefing: result.LastInsertId(): %v\n", err)
return fmt.Errorf("error: *DB.writeBriefing: result.LastInsertId(): %v", err)
}
return nil
}
func (db *DB) WriteParticipant(p *Participant) error {
result, err := db.Exec(`
query := `
INSERT INTO participants
(first_name, last_name, company)
VALUES
(?, ?, ?)
`, p.FirstName, p.LastName, p.Company)
`
result, err := db.Exec(query, p.FirstName, p.LastName, p.Company)
if err != nil {
return fmt.Errorf("*DB.writeParticipants: db.Exec(): %v\n", err)
return fmt.Errorf("error: *DB.writeParticipants: db.Exec(): %v", err)
}
p.ID, err = result.LastInsertId()
if err != nil {
return fmt.Errorf("*DB.writeParticipants: result.LastInsertId(): %v\n", err)
return fmt.Errorf("error: *DB.writeParticipants: result.LastInsertId(): %v", err)
}
return nil
}
func (db *DB) WriteGivenAnswer(b *Briefing, p *Participant, q *Question, g int) error {
_, err := db.Exec(`
INSERT INTO given_answers
(briefing_id, participant_id, question_id, given_answer)
VALUES
(?, ?, ?, ?)
`, b.ID, p.ID, q.ID, g)
if err != nil {
return fmt.Errorf("*DB.writeGivenAnswers: db.Exec(): %v\n", err)
}
func (db *DB) WriteGivenAnswers(b Briefing, p Participant, sq []Question, givenAnswers []int) error {
query := `
INSERT INTO given_answers
(briefing_id, participant_id, question_id, given_answer)
VALUES
(?, ?, ?, ?)
`
return nil
}
func (db *DB) WriteAllDataOfBriefing(b *Briefing, sp *[]*Participant, sq *[]*Question, sg *[]*GivenAnswer) error {
if err := db.WriteBriefing(b); err != nil {
return fmt.Errorf("*DB.WriteAllDataOfBriefing: db.writeBriefing(): %v\n", err)
}
for _, p := range *sp {
if err := db.WriteParticipant(p); err != nil {
return fmt.Errorf("*DB.WriteAllDataOfBriefing: db.writeParticipants(): %v\n", err)
}
}
for _, p := range *sp {
for i, q := range *sq {
db.WriteGivenAnswer(b, p, q, i)
for i, q := range sq {
_, err := db.Exec(query, b.ID, p.ID, q.ID, givenAnswers[i])
if err != nil {
return fmt.Errorf("error: *DB.WriteGivenAnswers: db.Exec(): %v", err)
}
}
return nil
}
func (db *DB) GetAllOverviewTableData() ([]*OverviewTableData, error) {
rows, err := db.Query(`
func (db *DB) GetAllOverviewTableData() ([]OverviewTableData, error) {
query := `
SELECT
i.first_name,
i.last_name,
@ -180,13 +117,15 @@ func (db *DB) GetAllOverviewTableData() ([]*OverviewTableData, error) {
ORDER BY
b.id DESC,
p.id
`)
`
rows, err := db.Query(query)
if err != nil {
return nil, fmt.Errorf("*DB.ReadAllBriefings: db.Query(): %v\n", err)
return nil, fmt.Errorf("error: *DB.ReadAllBriefings: db.Query(): %v", err)
}
defer rows.Close()
data := make([]*OverviewTableData, 0)
data := make([]OverviewTableData, 0)
for rows.Next() {
otd := new(OverviewTableData)
@ -203,17 +142,17 @@ func (db *DB) GetAllOverviewTableData() ([]*OverviewTableData, error) {
&otd.ParticipantCompany,
)
if err != nil {
return nil, fmt.Errorf("*DB.ReadAllBriefings: rows.Scan(): %v\n", err)
return nil, fmt.Errorf("error: *DB.ReadAllBriefings: rows.Scan(): %v", err)
}
data = append(data, otd)
data = append(data, *otd)
}
return data, nil
}
func (db *DB) GetOverviewTableDataByName(n string) (*[]*OverviewTableData, error) {
rows, err := db.Query(`
func (db *DB) GetOverviewTableDataByName(n string) ([]OverviewTableData, error) {
query := `
SELECT
i.first_name,
i.last_name,
@ -241,13 +180,15 @@ func (db *DB) GetOverviewTableDataByName(n string) (*[]*OverviewTableData, error
ORDER BY
b.id DESC,
p.id
`, "%"+n+"%", "%"+n+"%", "%"+n+"%", "%"+n+"%")
`
rows, err := db.Query(query, "%"+n+"%", "%"+n+"%", "%"+n+"%", "%"+n+"%")
if err != nil {
return nil, fmt.Errorf("*DB.GetOverviewTableDataByName: db.Query(): %v\n", err)
return nil, fmt.Errorf("error: *DB.GetOverviewTableDataByName: db.Query(): %v", err)
}
defer rows.Close()
data := make([]*OverviewTableData, 0)
data := make([]OverviewTableData, 0)
for rows.Next() {
otd := new(OverviewTableData)
@ -264,42 +205,44 @@ func (db *DB) GetOverviewTableDataByName(n string) (*[]*OverviewTableData, error
&otd.ParticipantCompany,
)
if err != nil {
return nil, fmt.Errorf("*DB.ReadAllBriefings: rows.Scan(): %v\n", err)
return nil, fmt.Errorf("error: *DB.ReadAllBriefings: rows.Scan(): %v", err)
}
data = append(data, otd)
data = append(data, *otd)
}
return &data, nil
return data, nil
}
func (db *DB) GetLastID(table string) (int, error) {
var id int
row := db.QueryRow(`
query := `
SELECT id
FROM ?
ORDER BY id DESC
LIMIT 0, 1
`, table)
`
row := db.QueryRow(query, table)
if err := row.Scan(&id); err != nil {
return -1, fmt.Errorf("*DB.GetLastID: row.Scan(): %v\n", err)
return -1, fmt.Errorf("error: *DB.GetLastID: row.Scan(): %v", err)
}
return id, nil
}
func (db *DB) GetInstructors() ([]*Instructor, error) {
rows, err := db.Query(`
query := `
SELECT *
FROM instructors
ORDER BY
last_name,
first_name
`)
`
rows, err := db.Query(query)
if err != nil {
return nil, fmt.Errorf("*DB.GetInstructors: db.Query(): %v\n", err)
return nil, fmt.Errorf("error: *DB.GetInstructors: db.Query(): %v", err)
}
defer rows.Close()
@ -307,7 +250,7 @@ func (db *DB) GetInstructors() ([]*Instructor, error) {
for rows.Next() {
instructor := new(Instructor)
if err = rows.Scan(&instructor.ID, &instructor.FirstName, &instructor.LastName); err != nil {
return nil, fmt.Errorf("*DB.GetInstructors: rows.Scan(): %v\n", err)
return nil, fmt.Errorf("error: *DB.GetInstructors: rows.Scan(): %v", err)
}
instructors = append(instructors, instructor)
}
@ -316,16 +259,19 @@ func (db *DB) GetInstructors() ([]*Instructor, error) {
}
func (db *DB) GetQuestions(nums []string) ([]Question, error) {
rows, err := db.Query(`
query := `
SELECT *
FROM questions
WHERE id IN (` + strings.Join(nums, ", ") + `)
`)
`
rows, err := db.Query(query)
if err != nil {
return nil, fmt.Errorf("*DB.GetQuestions: db.Query(): %v\n", err)
return nil, fmt.Errorf("error: *DB.GetQuestions: db.Query(): %v", err)
}
defer rows.Close()
// TODO: not scalable
questions := make([]Question, 0)
for rows.Next() {
q := new(Question)
@ -340,7 +286,7 @@ func (db *DB) GetQuestions(nums []string) ([]Question, error) {
a4.ID = 4
if err := rows.Scan(&q.ID, &q.Text, &a1.Text, &a2.Text, &a3.Text, &a4.Text, &q.Correct); err != nil {
return nil, fmt.Errorf("*DB.GetQuestions: rows.Scan(): %v\n", err)
return nil, fmt.Errorf("error: *DB.GetQuestions: rows.Scan(): %v", err)
}
q.Answers = append(q.Answers, *a1)
@ -370,7 +316,7 @@ func (db *DB) GetGivenAnswers(bid, pid int64, sq []Question) ([]int, error) {
row := db.QueryRow(query, bid, pid, q.ID)
if err := row.Scan(&answer); err != nil {
return nil, fmt.Errorf("*DB.GetGivenAnswers: row.Scan(): %v\n", err)
return nil, fmt.Errorf("error: *DB.GetGivenAnswers: row.Scan(): %v", err)
}
answers = append(answers, answer)

View File

@ -0,0 +1,52 @@
package data
import (
"bufio"
"fmt"
"os"
"strings"
"syscall"
"golang.org/x/term"
)
func getUsername() (string, error) {
user := os.Getenv("DB_USER")
if user == "" {
var err error
fmt.Printf("DB Benutzer: ")
user, err = bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
return "", fmt.Errorf("error: getUsername: bufio.NewReader().ReadString(): %v", err)
}
}
return strings.TrimSpace(user), nil
}
func getPassword() (string, error) {
pass := os.Getenv("DB_PASS")
if pass == "" {
fmt.Printf("DB Passwort: ")
bytePass, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
return "", fmt.Errorf("error: getPassword: term.ReadPassword(): %v", err)
}
fmt.Println()
pass = strings.TrimSpace(string(bytePass))
}
return pass, nil
}
func getCredentials() (string, string, error) {
user, err := getUsername()
if err != nil {
return "", "", fmt.Errorf("error: getCredentials: getUsername(): %v", err)
}
pass, err := getPassword()
if err != nil {
return "", "", fmt.Errorf("error: getCredentials: getPassword(): %v", err)
}
return user, pass, nil
}

View File

@ -11,11 +11,11 @@ import (
"streifling.com/jason/sicherheitsunterweisung/packages/data"
)
func HandleInternalLogin(ss *[]*Session, cs chan<- *Session, db *data.DB) http.HandlerFunc {
func HandleInternalLogin(db *data.DB, ss *[]*Session, cs chan<- *Session) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
instructors, err := db.GetInstructors()
if err != nil {
http.Error(w, "HandleInternalLogin: db.GetInstructors(): "+fmt.Sprint(err), http.StatusInternalServerError)
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panicln(err)
}
@ -24,11 +24,19 @@ func HandleInternalLogin(ss *[]*Session, cs chan<- *Session, db *data.DB) http.H
session := new(Session)
session.ID = uuid.New()
session.Briefing = new(data.Briefing)
session.Briefing.InstructorID = i.ID
session.InstructorID = i.ID
(*ss) = append((*ss), session)
cs <- session
displayTable(w, db)
data := new(tableHTMLData)
data.SessionID = session.ID
data.OTD, err = db.GetAllOverviewTableData()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panicln(err)
}
template.Must(template.ParseFiles("templates/table.html")).ExecuteTemplate(w, "content", data)
return
}
}
@ -36,40 +44,52 @@ func HandleInternalLogin(ss *[]*Session, cs chan<- *Session, db *data.DB) http.H
}
}
func HandleSearch(db *data.DB) http.HandlerFunc {
func (s *Session) HandleSearch(db *data.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
bs, err := db.GetOverviewTableDataByName(r.PostFormValue("search"))
log.Println("hier")
var err error
data := tableHTMLData{}
data.SessionID = s.ID
data.OTD, err = db.GetOverviewTableDataByName(r.PostFormValue("search"))
if err != nil {
http.Error(w, "DisplayResults: db.ReadByName(r.PostFormValue()): "+fmt.Sprint(err), http.StatusInternalServerError)
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panicln(err)
}
template.Must(template.ParseFiles("templates/table.html")).ExecuteTemplate(w, "rows", bs)
template.Must(template.ParseFiles("templates/table.html")).ExecuteTemplate(w, "rows", data)
}
}
func (s *Session) HandleNewBriefing() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
data := new(briefingHTMLData)
data := new(participantHTMLData)
data.SessionID = s.ID
template.Must(template.ParseFiles("templates/briefing.html")).ExecuteTemplate(w, "content", data)
}
}
func (s *Session) HandleNewParticipant(cp chan<- *data.Participant) http.HandlerFunc {
func (s *Session) HandleNewParticipant(cp chan<- *BriefingParticipant) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var err error
p := new(data.Participant)
p := new(BriefingParticipant)
p.Participant = new(data.Participant)
p.NoIncorrect = -1
p.AllowRetry = false
p.Login, err = generateLogin()
if err != nil {
http.Error(w, "AddParticipant: generateLogin(): "+fmt.Sprint(err), http.StatusInternalServerError)
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panicln(err)
}
s.Participants = append(s.Participants, p)
cp <- p
data := new(briefingHTMLData)
data := new(participantHTMLData)
data.SessionID = s.ID
data.Login = p.Login
if err != nil {
http.Error(w, "AddParticipant: generateLogin(): "+fmt.Sprint(err), http.StatusInternalServerError)
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panicln(err)
}
template.Must(template.ParseFiles("templates/briefing.html")).ExecuteTemplate(w, "new", data)
@ -79,21 +99,28 @@ func (s *Session) HandleNewParticipant(cp chan<- *data.Participant) http.Handler
func (s *Session) HandleBriefingForm(db *data.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
now := time.Now()
var err error
s.Briefing.Date = now.Format("2006-01-02")
s.Briefing.Time = now.Format("15:04:05")
s.Briefing.Location = r.PostFormValue("location")
s.Briefing.DocumentName = r.PostFormValue("document")
s.Briefing.AsOf = r.PostFormValue("as-of")
s.Date = now.Format("2006-01-02")
s.Time = now.Format("15:04:05")
s.Location = r.PostFormValue("location")
s.DocumentName = r.PostFormValue("document")
s.AsOf = r.PostFormValue("as-of")
err = db.WriteBriefing(s.Briefing)
err := db.WriteBriefing(s.Briefing)
if err != nil {
http.Error(w, "SubmitBriefingForm: db.WriteBriefing(): "+fmt.Sprint(err), http.StatusInternalServerError)
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panicln(err)
}
displayTable(w, db)
data := new(summaryHTMLData)
data.SessionID = s.ID
data.ParticipantsData = make([]participantHTMLData, len(s.Participants))
for i, p := range s.Participants {
data.ParticipantsData[i].SessionID = s.ID
data.ParticipantsData[i].BriefingParticipant = *p
}
template.Must(template.ParseFiles("templates/summary.html")).ExecuteTemplate(w, "content", data)
}
}
@ -112,88 +139,65 @@ func HandleExternalLogin(ss *[]*Session) http.HandlerFunc {
}
}
func (s *Session) HandleParticipant(p *data.Participant, sq *[]data.Question, db *data.DB) http.HandlerFunc {
func (s *Session) HandleParticipant(db *data.DB, p *BriefingParticipant) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
p.FirstName = r.PostFormValue("first-" + fmt.Sprint(p.Login))
p.LastName = r.PostFormValue("last-" + fmt.Sprint(p.Login))
p.Company = r.PostFormValue("company-" + fmt.Sprint(p.Login))
err := db.WriteParticipant(p)
err := db.WriteParticipant(p.Participant)
if err != nil {
http.Error(w, "DisplayQuestion: db.WriteParticipant(): "+fmt.Sprint(err), http.StatusInternalServerError)
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panicln(err)
}
data := new(questionHTMLData)
data.SessionID = s.ID
data.Login = p.Login
data.Question = (*sq)[0]
data.Question = s.Questions[0]
data.QuestionID = 1
template.Must(template.ParseFiles("templates/question.html")).ExecuteTemplate(w, "content", data)
}
}
func (s *Session) HandleAnswer(db *data.DB, p *data.Participant, sq *[]data.Question, i int64) http.HandlerFunc {
func (s *Session) HandleAnswer(db *data.DB, p *BriefingParticipant, i int64) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(i, len(*sq))
if i < int64(len(*sq)) {
if err := handleGivenAnswer(s, p, i-1, r, db); err != nil {
http.Error(w, "DisplayQuestion: handleGivenAnswer(): "+fmt.Sprint(err), http.StatusInternalServerError)
if i < int64(len(s.Questions)) {
if err := handleGivenAnswer(p, i-1, r); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panicln(err)
}
data := new(questionHTMLData)
data.SessionID = s.ID
data.Login = p.Login
data.Question = (*sq)[i]
data.Question = s.Questions[i]
data.QuestionID = i + 1
template.Must(template.ParseFiles("templates/question.html")).ExecuteTemplate(w, "content", data)
} else {
if err := handleGivenAnswer(s, p, i-1, r, db); err != nil {
http.Error(w, "DisplayTestResults: handleGivenAnswer(): "+fmt.Sprint(err), http.StatusInternalServerError)
if err := handleGivenAnswer(p, i-1, r); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panicln(err)
}
givenAnswers, err := db.GetGivenAnswers(s.Briefing.ID, p.ID, s.Questions)
if err != nil {
http.Error(w, "DisplayTestResults: db.GetGivenAnswers(): "+fmt.Sprint(err), http.StatusInternalServerError)
log.Panicln(err)
p.NoIncorrect = 0
for i, q := range s.Questions {
if p.GivenAnswers[i] != q.Correct {
p.NoIncorrect++
}
}
data := new(resultHTMLData)
data.SessionID = s.ID
data.Login = p.Login
data.Incorrect = 0
data.BriefingParticipant = *p
data.Questions = makeHTMLQuestions(s.Questions, p.GivenAnswers)
data.Questions = make([]htmlQuestion, 0)
for i, q := range s.Questions {
question := new(htmlQuestion)
question.Text = q.Text
question.Answers = make([]htmlAnswer, 0)
for j, a := range q.Answers {
answer := new(htmlAnswer)
answer.Text = a.Text
if j+1 == q.Correct {
answer.Correct = true
} else {
answer.Correct = false
}
if j+1 == givenAnswers[i] {
answer.Chosen = true
} else {
answer.Chosen = false
}
question.Answers = append(question.Answers, *answer)
}
data.Questions = append(data.Questions, *question)
if givenAnswers[i] != q.Correct {
data.Incorrect++
if data.NoIncorrect == 0 {
if err := db.WriteGivenAnswers(*s.Briefing, *p.Participant, s.Questions, p.GivenAnswers); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panicln(err)
}
}
@ -202,14 +206,49 @@ func (s *Session) HandleAnswer(db *data.DB, p *data.Participant, sq *[]data.Ques
}
}
func (s *Session) HandleRetry(p *data.Participant, sq *[]data.Question) http.HandlerFunc {
func (s *Session) HandleAllowRetry(p *BriefingParticipant) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
data := new(questionHTMLData)
data.SessionID = s.ID
data.Login = p.Login
data.Question = (*sq)[0]
data.QuestionID = 1
template.Must(template.ParseFiles("templates/question.html")).ExecuteTemplate(w, "content", data)
p.NoIncorrect = -1
p.AllowRetry = true
}
}
func (s *Session) HandleRetry(p *BriefingParticipant, i *int) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if p.AllowRetry {
p.AllowRetry = false
(*i) = 0
data := new(questionHTMLData)
data.SessionID = s.ID
data.Login = p.Login
data.Question = s.Questions[*i]
data.QuestionID = int64(*i + 1)
template.Must(template.ParseFiles("templates/question.html")).ExecuteTemplate(w, "content", data)
} else {
data := new(resultHTMLData)
data.SessionID = s.ID
data.BriefingParticipant = *p
data.Questions = makeHTMLQuestions(s.Questions, p.GivenAnswers)
template.Must(template.ParseFiles("templates/result.html")).ExecuteTemplate(w, "content", data)
}
}
}
func (s *Session) HandleRefresh(p *BriefingParticipant) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
data := new(participantHTMLData)
data.SessionID = s.ID
data.BriefingParticipant = *p
template.Must(template.ParseFiles("templates/summary.html")).ExecuteTemplate(w, "participant", data)
}
}
func (s *Session) HandleBriefingDone() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
template.Must(template.ParseFiles("templates/login.html")).ExecuteTemplate(w, "content", nil)
}
}

View File

@ -4,32 +4,23 @@ import (
"crypto/rand"
"encoding/hex"
"fmt"
"html/template"
"net/http"
"strconv"
"streifling.com/jason/sicherheitsunterweisung/packages/data"
)
func displayTable(w http.ResponseWriter, db *data.DB) {
bs, err := db.GetAllOverviewTableData()
if err != nil {
http.Error(w, "displayTable: *DB.GetAllOverviewTableData(): "+fmt.Sprint(err), http.StatusInternalServerError)
}
template.Must(template.ParseFiles("templates/table.html")).ExecuteTemplate(w, "content", bs)
}
func generateLogin() (string, error) {
bs := make([]byte, 4)
if _, err := rand.Read(bs); err != nil {
return "", fmt.Errorf("generateLogin: rand.Read(bs): %v\n", err)
return "", fmt.Errorf("error: generateLogin: rand.Read(bs): %v", err)
}
return hex.EncodeToString(bs), nil
}
func findCorrectLogin(l string, ss *[]*Session) (*Session, *data.Participant, bool) {
func findCorrectLogin(l string, ss *[]*Session) (*Session, *BriefingParticipant, bool) {
for _, session := range *ss {
for _, p := range session.Participants {
if l == p.Login {
@ -46,21 +37,48 @@ func newParticipant(l string) (*data.Participant, error) {
p.ID, err = strconv.ParseInt(l, 10, 64)
if err != nil {
return nil, fmt.Errorf("newParticipant: strconv.Atoi(idString): %v\n", err)
return nil, fmt.Errorf("error: newParticipant: strconv.Atoi(): %v", err)
}
return p, nil
}
func handleGivenAnswer(s *Session, p *data.Participant, i int64, r *http.Request, db *data.DB) error {
func handleGivenAnswer(p *BriefingParticipant, i int64, r *http.Request) error {
answer, err := strconv.Atoi(r.PostFormValue("answer"))
if err != nil {
return fmt.Errorf("handleGivenAnswer: strconv.Atoi(): %v\n", err)
}
if err := db.WriteGivenAnswer(s.Briefing, p, &s.Questions[i], answer); err != nil {
return fmt.Errorf("handleGivenAnswer: db.WriteGivenAnswer(): %v\n", err)
return fmt.Errorf("error: handleGivenAnswer: strconv.Atoi(): %v", err)
}
p.GivenAnswers[i] = answer
return nil
}
func makeHTMLQuestions(sq []data.Question, givenAnswers []int) []resultQuestion {
questions := make([]resultQuestion, 0)
for i, q := range sq {
question := new(resultQuestion)
question.Text = q.Text
question.Answers = make([]resultAnswer, 0)
for j, a := range q.Answers {
answer := new(resultAnswer)
answer.Text = a.Text
if j+1 == q.Correct {
answer.Correct = true
} else {
answer.Correct = false
}
if j+1 == givenAnswers[i] {
answer.Chosen = true
} else {
answer.Chosen = false
}
question.Answers = append(question.Answers, *answer)
}
questions = append(questions, *question)
}
return questions
}

View File

@ -5,44 +5,39 @@ import (
"streifling.com/jason/sicherheitsunterweisung/packages/data"
)
type Session struct {
ID uuid.UUID
*data.Briefing
Participants []*data.Participant
Questions []data.Question
}
type briefingHTMLData struct {
type tableHTMLData struct {
SessionID uuid.UUID
Login string
OTD []data.OverviewTableData
}
type participantHTMLData struct {
SessionID uuid.UUID
Login string
BriefingParticipant
}
type questionHTMLData struct {
SessionID uuid.UUID
Login string
participantHTMLData
Question data.Question
QuestionID int64
}
type htmlAnswer struct {
type resultAnswer struct {
Text string
Correct bool
Chosen bool
}
type htmlQuestion struct {
type resultQuestion struct {
Text string
Answers []htmlAnswer
Answers []resultAnswer
}
type resultHTMLData struct {
SessionID uuid.UUID
Login string
Questions []htmlQuestion
Incorrect int
participantHTMLData
Questions []resultQuestion
}
type summaryHTMLData struct {
SessionID uuid.UUID
ParticipantsData []participantHTMLData
}

View File

@ -0,0 +1,56 @@
package session
import (
"fmt"
"log"
"net/http"
"streifling.com/jason/sicherheitsunterweisung/packages/data"
)
func (mux *Mux) handleParticipants(db *data.DB, cp <-chan *BriefingParticipant, s *Session) {
for p := range cp {
p.GivenAnswers = make([]int, len(s.Questions))
mux.HandleFunc("/submit-participant/"+fmt.Sprint(s.ID)+"/"+fmt.Sprint(p.Login)+"/", s.HandleParticipant(db, p))
var i int
for i = range s.Questions {
mux.HandleFunc("/submit-answer/"+fmt.Sprint(s.ID)+"/"+fmt.Sprint(p.Login)+"/"+fmt.Sprint(i+1)+"/", s.HandleAnswer(db, p, int64(i+1)))
}
mux.HandleFunc("/allow-retry/"+fmt.Sprint(s.ID)+"/"+fmt.Sprint(p.Login)+"/", s.HandleAllowRetry(p))
mux.HandleFunc("/retry/"+fmt.Sprint(s.ID)+"/"+fmt.Sprint(p.Login)+"/", s.HandleRetry(p, &i))
mux.HandleFunc("/refresh-summary/"+fmt.Sprint(s.ID)+"/"+fmt.Sprint(p.Login)+"/", s.HandleRefresh(p))
}
}
func NewMux() *Mux {
mux := new(Mux)
mux.ServeMux = http.NewServeMux()
return mux
}
func (mux *Mux) HandleSessions(db *data.DB, cs <-chan *Session, ss *[]*Session) {
for s := range cs {
(*ss) = append(*ss, s)
participantChan := make(chan *BriefingParticipant)
questionIDs := make([]string, 4)
for i := 0; i < len(questionIDs); i++ {
questionIDs[i] = fmt.Sprint(i + 1)
}
var err error
s.Questions, err = db.GetQuestions(questionIDs)
if err != nil {
log.Fatalln(err)
}
mux.HandleFunc("/search/"+fmt.Sprint(s.ID)+"/", s.HandleSearch(db))
mux.HandleFunc("/new-briefing/"+fmt.Sprint(s.ID)+"/", s.HandleNewBriefing())
mux.HandleFunc("/new-participant/"+fmt.Sprint(s.ID)+"/", s.HandleNewParticipant(participantChan))
mux.HandleFunc("/submit-form/"+fmt.Sprint(s.ID)+"/", s.HandleBriefingForm(db))
mux.HandleFunc("/briefing-done/"+fmt.Sprint(s.ID)+"/", s.HandleBriefingDone())
go mux.handleParticipants(db, participantChan, s)
}
}

View File

@ -0,0 +1,27 @@
package session
import (
"net/http"
"github.com/google/uuid"
"streifling.com/jason/sicherheitsunterweisung/packages/data"
)
type Mux struct {
*http.ServeMux
}
type BriefingParticipant struct {
*data.Participant
Login string
GivenAnswers []int
NoIncorrect int
AllowRetry bool
}
type Session struct {
ID uuid.UUID
*data.Briefing
Participants []*BriefingParticipant
Questions []data.Question
}

View File

@ -1,37 +1,37 @@
{{ define "add-buttons" }}
{{define "add-buttons"}}
<div id="briefing-buttons">
<button type="button" hx-post="/new-participant/{{ .SessionID }}/" hx-target="#briefing-buttons" hx-swap="outerHTML">
<button type="button" hx-post="/new-participant/{{.SessionID}}/" hx-target="#briefing-buttons" hx-swap="outerHTML">
Neuer Teilnehmer
</button>
<button type="submit" hx-post="/submit-form/{{ .SessionID }}/" hx-target="#content" hx-swap="innerHTML">
Fertig
<button type="submit" hx-post="/submit-form/{{.SessionID}}/" hx-target="#content">
Weiter
</button>
</div>
{{ end }}
{{end}}
{{ define "new" }}
{{ template "add-buttons" . }}
<p>{{ .Login }}</p>
{{ end }}
{{define "new"}}
{{template "add-buttons" .}}
<p>{{.Login}}</p>
{{end}}
{{ define "content" }}
{{define "content"}}
<form>
<div>
<label for="location">Ort</label>
<input id="location" name="location" required type="text" />
<input id="location" name="location" required type="text" value="Werk Langenhagen" />
</div>
<div>
<label for="document">Dokument</label>
<input id="document" name="document" required type="text" />
<input id="document" name="document" required type="text" value="ICL-1901-LGH" />
</div>
<div>
<label for="as-of">Stand vom</label>
<input id="as-of" name="as-of" required type="date" />
<input id="as-of" name="as-of" required type="date" value="2021-02-01" />
</div>
{{ template "add-buttons" . }}
{{template "add-buttons" .}}
</form>
{{ end }}
{{end}}

View File

@ -12,7 +12,7 @@
<h1>Sicherheitsunterweisung</h1>
<div id="content">
{{ template "content" . }}
{{template "content" .}}
</div>
<script src="/static/js/htmx.min.js" type="text/javascript"></script>

View File

@ -1,4 +1,4 @@
{{ define "content" }}
{{define "content"}}
<h2>Anmeldung</h2>
<form>
@ -14,4 +14,4 @@
</button>
</div>
</form>
{{ end }}
{{end}}

View File

@ -1,16 +1,16 @@
{{ define "content" }}
{{define "content"}}
<form>
<label for="first-{{ .Login }}">Vorname</label>
<input type="text" name="first-{{ .Login }}" id="first-{{ .Login }}" />
<label for="first-{{.Login}}">Vorname</label>
<input type="text" name="first-{{.Login}}" id="first-{{.Login}}" />
<label for="last-{{ .Login }}">Nachname</label>
<input type="text" name="last-{{ .Login }}" id="last-{{ .Login }}" />
<label for="last-{{.Login}}">Nachname</label>
<input type="text" name="last-{{.Login}}" id="last-{{.Login}}" />
<label for="company-{{ .Login }}">Firma</label>
<input type="text" name="company-{{ .Login }}" id="company-{{ .Login }}" />
<label for="company-{{.Login}}">Firma</label>
<input type="text" name="company-{{.Login}}" id="company-{{.Login}}" />
<button type="button" hx-post="/submit-participant/{{ .SessionID }}/{{ .Login }}/" hx-target="#content">
<button type="button" hx-post="/submit-participant/{{.SessionID}}/{{.Login}}/" hx-target="#content">
Fertig
</button>
</form>
{{ end }}
{{end}}

View File

@ -7,12 +7,13 @@
{{end}}
{{define "content"}}
<p>{{.Incorrect}} Fehler</p>
<p>{{.BriefingParticipant.NoIncorrect}} Fehler</p>
{{if gt .BriefingParticipant.NoIncorrect 0}}
<p>Bitte nachschulen lassen und anschließend wiederholen.</p>
<button hx-post="/retry/{{.SessionID}}/{{.Login}}/" hx-target="#content" type="submit">Wiederholen</button>
{{end}}
{{range .Questions}}
<p>{{.Text}}</p>
{{template "answers" .}}
{{end}}
{{if gt .Incorrect 0}}
<button hx-post="/retry/{{.SessionID}}/{{.Login}}/" hx-target="#content" type="submit">Wiederholen</button>
{{end}}
{{end}}

35
templates/summary.html Normal file
View File

@ -0,0 +1,35 @@
{{define "refresh"}}
<button hx-post="/refresh-summary/{{.SessionID}}/{{.Login}}/" hx-target="#id-{{.Login}}"
type="button">Aktualisieren</button>
{{end}}
{{define "retry"}}
<button hx-post="/allow-retry/{{.SessionID}}/{{.Login}}/" type="button">Wiederholen erlauben</button>
{{end}}
{{define "participant"}}
<div id="id-{{.Login}}">
<h2>{{.Login}}</h2>
{{if not .LastName}}
{{template "refresh" .}}
{{else}}
<p>{{.FirstName}} {{.LastName}}</p>
<p>{{.Company}}</p>
{{if lt .NoIncorrect 0}}
{{template "refresh" .}}
{{else if gt .NoIncorrect 0}}
{{template "retry" .}}
{{template "refresh" .}}
{{else}}
<p>{{.NoIncorrect}} Fehler</p>
{{end}}
{{end}}
</div>
{{end}}
{{define "content"}}
<button hx-post="/briefing-done/{{.SessionID}}/" hx-target="#content" type="button">Beenden</button>
{{range .ParticipantsData}}
{{template "participant" .}}
{{end}}
{{end}}

View File

@ -1,29 +1,28 @@
{{ define "rows" }}
{{ range . }}
{{define "rows"}}
{{range .OTD}}
<tr>
<td>{{ .InstructorFirstName }}</td>
<td>{{ .InstructorLastName }}</td>
<td>{{ .BriefingDate }}</td>
<td>{{ .BriefingTime }}</td>
<td>{{ .BriefingLocation }}</td>
<td>{{ .BriefingDocumentName }}</td>
<td>{{ .BriefingAsOf }}</td>
<td>{{ .ParticipantFirstName }}</td>
<td>{{ .ParticipantLastName }}</td>
<td>{{ .ParticipantCompany }}</td>
<td>{{.InstructorFirstName}}</td>
<td>{{.InstructorLastName}}</td>
<td>{{.BriefingDate}}</td>
<td>{{.BriefingTime}}</td>
<td>{{.BriefingLocation}}</td>
<td>{{.BriefingDocumentName}}</td>
<td>{{.BriefingAsOf}}</td>
<td>{{.ParticipantFirstName}}</td>
<td>{{.ParticipantLastName}}</td>
<td>{{.ParticipantCompany}}</td>
</tr>
{{ end }}
{{ end }}
{{end}}
{{end}}
{{ define "content" }}
{{define "content"}}
<form>
<label for="search-input">Suche</label>
<input type="text" name="search" id="search-input" hx-post="/search/" hx-target="#results" hx-swap="innerHTML"
hx-trigger="keyup changed delay:200ms" />
<input type="text" name="search" id="search-input" hx-post="/search/{{.SessionID}}/" hx-target="#results">
</form>
<form>
<button type="submit" hx-post="/new-briefing/" hx-target="#content" hx-swap="innerHTML">
<button type="submit" hx-post="/new-briefing/{{.SessionID}}/" hx-target="#content">
Neue Unterweisung
</button>
</form>
@ -43,7 +42,7 @@
</thead>
<tbody id="results">
{{ template "rows" . }}
{{template "rows" .}}
</tbody>
</table>
{{ end }}
{{end}}