5 Commits

16 changed files with 404 additions and 274 deletions

42
main.go
View File

@ -1,7 +1,6 @@
package main package main
import ( import (
"fmt"
"html/template" "html/template"
"log" "log"
"net/http" "net/http"
@ -10,47 +9,13 @@ import (
"streifling.com/jason/sicherheitsunterweisung/packages/session" "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() { func main() {
db, err := data.OpenDB("sicherheitsunterweisung") db, err := data.OpenDB("sicherheitsunterweisung")
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
mux := http.NewServeMux() mux := session.NewMux()
sessions := make([]*session.Session, 0) sessions := make([]*session.Session, 0)
sessionChan := make(chan *session.Session) sessionChan := make(chan *session.Session)
@ -58,11 +23,10 @@ func main() {
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
template.Must(template.ParseFiles("templates/index.html", "templates/login.html")).Execute(w, nil) 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("/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)) log.Fatalln(http.ListenAndServe(":8080", mux))
} }

View File

@ -17,7 +17,6 @@ type Instructor Person
type Participant struct { type Participant struct {
Person Person
Company string Company string
Login string
} }
type Briefing struct { type Briefing struct {

View File

@ -16,94 +16,82 @@ func OpenDB(dbName string) (*DB, error) {
cfg.DBName = dbName cfg.DBName = dbName
cfg.User, cfg.Passwd, err = getCredentials() cfg.User, cfg.Passwd, err = getCredentials()
if err != nil { if err != nil {
return nil, fmt.Errorf("Open: getCredentials(): %v\n", err) return nil, fmt.Errorf("error: OpenDB: getCredentials(): %v", err)
} }
db.DB, err = sql.Open("mysql", cfg.FormatDSN()) db.DB, err = sql.Open("mysql", cfg.FormatDSN())
if err != nil { 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 { 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 return db, nil
} }
func (db *DB) WriteBriefing(b *Briefing) error { func (db *DB) WriteBriefing(b *Briefing) error {
result, err := db.Exec(` query := `
INSERT INTO briefings INSERT INTO briefings
(date, time, location, document_name, as_of, instructor_id) (date, time, location, document_name, as_of, instructor_id)
VALUES 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 { 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() b.ID, err = result.LastInsertId()
if err != nil { 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 return nil
} }
func (db *DB) WriteParticipant(p *Participant) error { func (db *DB) WriteParticipant(p *Participant) error {
result, err := db.Exec(` query := `
INSERT INTO participants INSERT INTO participants
(first_name, last_name, company) (first_name, last_name, company)
VALUES VALUES
(?, ?, ?) (?, ?, ?)
`, p.FirstName, p.LastName, p.Company) `
result, err := db.Exec(query, p.FirstName, p.LastName, p.Company)
if err != nil { 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() p.ID, err = result.LastInsertId()
if err != nil { 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 return nil
} }
func (db *DB) WriteGivenAnswer(b *Briefing, p *Participant, q *Question, g int) error { func (db *DB) WriteGivenAnswers(b Briefing, p Participant, sq []Question, givenAnswers []int) error {
_, err := db.Exec(` query := `
INSERT INTO given_answers INSERT INTO given_answers
(briefing_id, participant_id, question_id, given_answer) (briefing_id, participant_id, question_id, given_answer)
VALUES VALUES
(?, ?, ?, ?) (?, ?, ?, ?)
`, b.ID, p.ID, q.ID, g) `
if err != nil {
return fmt.Errorf("*DB.writeGivenAnswers: db.Exec(): %v\n", err)
}
return nil for i, q := range sq {
} _, err := db.Exec(query, b.ID, p.ID, q.ID, givenAnswers[i])
if err != nil {
func (db *DB) WriteAllDataOfBriefing(b *Briefing, sp *[]*Participant, sq *[]*Question, sg *[]*GivenAnswer) error { return fmt.Errorf("error: *DB.WriteGivenAnswers: db.Exec(): %v", err)
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)
} }
} }
return nil return nil
} }
func (db *DB) GetAllOverviewTableData() ([]*OverviewTableData, error) { func (db *DB) GetAllOverviewTableData() ([]OverviewTableData, error) {
rows, err := db.Query(` query := `
SELECT SELECT
i.first_name, i.first_name,
i.last_name, i.last_name,
@ -129,13 +117,15 @@ func (db *DB) GetAllOverviewTableData() ([]*OverviewTableData, error) {
ORDER BY ORDER BY
b.id DESC, b.id DESC,
p.id p.id
`) `
rows, err := db.Query(query)
if err != nil { 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() defer rows.Close()
data := make([]*OverviewTableData, 0) data := make([]OverviewTableData, 0)
for rows.Next() { for rows.Next() {
otd := new(OverviewTableData) otd := new(OverviewTableData)
@ -152,17 +142,17 @@ func (db *DB) GetAllOverviewTableData() ([]*OverviewTableData, error) {
&otd.ParticipantCompany, &otd.ParticipantCompany,
) )
if err != nil { 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) GetOverviewTableDataByName(n string) (*[]*OverviewTableData, error) { func (db *DB) GetOverviewTableDataByName(n string) ([]OverviewTableData, error) {
rows, err := db.Query(` query := `
SELECT SELECT
i.first_name, i.first_name,
i.last_name, i.last_name,
@ -190,13 +180,15 @@ func (db *DB) GetOverviewTableDataByName(n string) (*[]*OverviewTableData, error
ORDER BY ORDER BY
b.id DESC, b.id DESC,
p.id p.id
`, "%"+n+"%", "%"+n+"%", "%"+n+"%", "%"+n+"%") `
rows, err := db.Query(query, "%"+n+"%", "%"+n+"%", "%"+n+"%", "%"+n+"%")
if err != nil { 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() defer rows.Close()
data := make([]*OverviewTableData, 0) data := make([]OverviewTableData, 0)
for rows.Next() { for rows.Next() {
otd := new(OverviewTableData) otd := new(OverviewTableData)
@ -213,42 +205,44 @@ func (db *DB) GetOverviewTableDataByName(n string) (*[]*OverviewTableData, error
&otd.ParticipantCompany, &otd.ParticipantCompany,
) )
if err != nil { 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) { func (db *DB) GetLastID(table string) (int, error) {
var id int var id int
query := `
row := db.QueryRow(`
SELECT id SELECT id
FROM ? FROM ?
ORDER BY id DESC ORDER BY id DESC
LIMIT 0, 1 LIMIT 0, 1
`, table) `
row := db.QueryRow(query, table)
if err := row.Scan(&id); err != nil { 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 return id, nil
} }
func (db *DB) GetInstructors() ([]*Instructor, error) { func (db *DB) GetInstructors() ([]*Instructor, error) {
rows, err := db.Query(` query := `
SELECT * SELECT *
FROM instructors FROM instructors
ORDER BY ORDER BY
last_name, last_name,
first_name first_name
`) `
rows, err := db.Query(query)
if err != nil { 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() defer rows.Close()
@ -256,7 +250,7 @@ func (db *DB) GetInstructors() ([]*Instructor, error) {
for rows.Next() { for rows.Next() {
instructor := new(Instructor) instructor := new(Instructor)
if err = rows.Scan(&instructor.ID, &instructor.FirstName, &instructor.LastName); err != nil { 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) instructors = append(instructors, instructor)
} }
@ -265,16 +259,19 @@ func (db *DB) GetInstructors() ([]*Instructor, error) {
} }
func (db *DB) GetQuestions(nums []string) ([]Question, error) { func (db *DB) GetQuestions(nums []string) ([]Question, error) {
rows, err := db.Query(` query := `
SELECT * SELECT *
FROM questions FROM questions
WHERE id IN (` + strings.Join(nums, ", ") + `) WHERE id IN (` + strings.Join(nums, ", ") + `)
`) `
rows, err := db.Query(query)
if err != nil { 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() defer rows.Close()
// TODO: not scalable
questions := make([]Question, 0) questions := make([]Question, 0)
for rows.Next() { for rows.Next() {
q := new(Question) q := new(Question)
@ -289,7 +286,7 @@ func (db *DB) GetQuestions(nums []string) ([]Question, error) {
a4.ID = 4 a4.ID = 4
if err := rows.Scan(&q.ID, &q.Text, &a1.Text, &a2.Text, &a3.Text, &a4.Text, &q.Correct); err != nil { 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) q.Answers = append(q.Answers, *a1)
@ -319,7 +316,7 @@ func (db *DB) GetGivenAnswers(bid, pid int64, sq []Question) ([]int, error) {
row := db.QueryRow(query, bid, pid, q.ID) row := db.QueryRow(query, bid, pid, q.ID)
if err := row.Scan(&answer); err != nil { 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) answers = append(answers, answer)

View File

@ -17,7 +17,7 @@ func getUsername() (string, error) {
fmt.Printf("DB Benutzer: ") fmt.Printf("DB Benutzer: ")
user, err = bufio.NewReader(os.Stdin).ReadString('\n') user, err = bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil { if err != nil {
return "", fmt.Errorf("getUsername: bufio.NewReader(os.Stdin).ReadString('\n'): %v", err) return "", fmt.Errorf("error: getUsername: bufio.NewReader().ReadString(): %v", err)
} }
} }
return strings.TrimSpace(user), nil return strings.TrimSpace(user), nil
@ -29,7 +29,7 @@ func getPassword() (string, error) {
fmt.Printf("DB Passwort: ") fmt.Printf("DB Passwort: ")
bytePass, err := term.ReadPassword(int(syscall.Stdin)) bytePass, err := term.ReadPassword(int(syscall.Stdin))
if err != nil { if err != nil {
return "", fmt.Errorf("getCredentials: term.ReadPassword(int(syscall.Stdin)): %v", err) return "", fmt.Errorf("error: getPassword: term.ReadPassword(): %v", err)
} }
fmt.Println() fmt.Println()
pass = strings.TrimSpace(string(bytePass)) pass = strings.TrimSpace(string(bytePass))
@ -40,12 +40,12 @@ func getPassword() (string, error) {
func getCredentials() (string, string, error) { func getCredentials() (string, string, error) {
user, err := getUsername() user, err := getUsername()
if err != nil { if err != nil {
return "", "", fmt.Errorf("getCredentials: getUsername(): %v", err) return "", "", fmt.Errorf("error: getCredentials: getUsername(): %v", err)
} }
pass, err := getPassword() pass, err := getPassword()
if err != nil { if err != nil {
return "", "", fmt.Errorf("getCredentials: getPassword(): %v", err) return "", "", fmt.Errorf("error: getCredentials: getPassword(): %v", err)
} }
return user, pass, nil return user, pass, nil

View File

@ -11,11 +11,11 @@ import (
"streifling.com/jason/sicherheitsunterweisung/packages/data" "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) { return func(w http.ResponseWriter, r *http.Request) {
instructors, err := db.GetInstructors() instructors, err := db.GetInstructors()
if err != nil { if err != nil {
http.Error(w, "HandleInternalLogin: db.GetInstructors(): "+fmt.Sprint(err), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panicln(err) log.Panicln(err)
} }
@ -24,11 +24,19 @@ func HandleInternalLogin(ss *[]*Session, cs chan<- *Session, db *data.DB) http.H
session := new(Session) session := new(Session)
session.ID = uuid.New() session.ID = uuid.New()
session.Briefing = new(data.Briefing) session.Briefing = new(data.Briefing)
session.Briefing.InstructorID = i.ID session.InstructorID = i.ID
(*ss) = append((*ss), session) (*ss) = append((*ss), session)
cs <- 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 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) { 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 { 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 { func (s *Session) HandleNewBriefing() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
data := new(briefingHTMLData) data := new(participantHTMLData)
data.SessionID = s.ID data.SessionID = s.ID
template.Must(template.ParseFiles("templates/briefing.html")).ExecuteTemplate(w, "content", data) 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) { return func(w http.ResponseWriter, r *http.Request) {
var err error 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() p.Login, err = generateLogin()
if err != nil { 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) s.Participants = append(s.Participants, p)
cp <- p cp <- p
data := new(briefingHTMLData) data := new(participantHTMLData)
data.SessionID = s.ID data.SessionID = s.ID
data.Login = p.Login data.Login = p.Login
if err != nil { 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) 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 { func (s *Session) HandleBriefingForm(db *data.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
now := time.Now() now := time.Now()
var err error
s.Briefing.Date = now.Format("2006-01-02") s.Date = now.Format("2006-01-02")
s.Briefing.Time = now.Format("15:04:05") s.Time = now.Format("15:04:05")
s.Briefing.Location = r.PostFormValue("location") s.Location = r.PostFormValue("location")
s.Briefing.DocumentName = r.PostFormValue("document") s.DocumentName = r.PostFormValue("document")
s.Briefing.AsOf = r.PostFormValue("as-of") s.AsOf = r.PostFormValue("as-of")
err = db.WriteBriefing(s.Briefing) err := db.WriteBriefing(s.Briefing)
if err != nil { if err != nil {
http.Error(w, "SubmitBriefingForm: db.WriteBriefing(): "+fmt.Sprint(err), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panicln(err) 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) { return func(w http.ResponseWriter, r *http.Request) {
p.FirstName = r.PostFormValue("first-" + fmt.Sprint(p.Login)) p.FirstName = r.PostFormValue("first-" + fmt.Sprint(p.Login))
p.LastName = r.PostFormValue("last-" + fmt.Sprint(p.Login)) p.LastName = r.PostFormValue("last-" + fmt.Sprint(p.Login))
p.Company = r.PostFormValue("company-" + 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 { if err != nil {
http.Error(w, "DisplayQuestion: db.WriteParticipant(): "+fmt.Sprint(err), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panicln(err) log.Panicln(err)
} }
data := new(questionHTMLData) data := new(questionHTMLData)
data.SessionID = s.ID data.SessionID = s.ID
data.Login = p.Login data.Login = p.Login
data.Question = (*sq)[0] data.Question = s.Questions[0]
data.QuestionID = 1 data.QuestionID = 1
template.Must(template.ParseFiles("templates/question.html")).ExecuteTemplate(w, "content", data) 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) { return func(w http.ResponseWriter, r *http.Request) {
log.Println(i, len(*sq)) if i < int64(len(s.Questions)) {
if i < int64(len(*sq)) { if err := handleGivenAnswer(p, i-1, r); err != nil {
if err := handleGivenAnswer(s, p, i-1, r, db); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError)
http.Error(w, "DisplayQuestion: handleGivenAnswer(): "+fmt.Sprint(err), http.StatusInternalServerError)
log.Panicln(err) log.Panicln(err)
} }
data := new(questionHTMLData) data := new(questionHTMLData)
data.SessionID = s.ID data.SessionID = s.ID
data.Login = p.Login data.Login = p.Login
data.Question = (*sq)[i] data.Question = s.Questions[i]
data.QuestionID = i + 1 data.QuestionID = i + 1
template.Must(template.ParseFiles("templates/question.html")).ExecuteTemplate(w, "content", data) template.Must(template.ParseFiles("templates/question.html")).ExecuteTemplate(w, "content", data)
} else { } else {
if err := handleGivenAnswer(s, p, i-1, r, db); err != nil { if err := handleGivenAnswer(p, i-1, r); err != nil {
http.Error(w, "DisplayTestResults: handleGivenAnswer(): "+fmt.Sprint(err), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panicln(err) log.Panicln(err)
} }
givenAnswers, err := db.GetGivenAnswers(s.Briefing.ID, p.ID, s.Questions) p.NoIncorrect = 0
if err != nil { for i, q := range s.Questions {
http.Error(w, "DisplayTestResults: db.GetGivenAnswers(): "+fmt.Sprint(err), http.StatusInternalServerError) if p.GivenAnswers[i] != q.Correct {
log.Panicln(err) p.NoIncorrect++
}
} }
data := new(resultHTMLData) data := new(resultHTMLData)
data.SessionID = s.ID data.SessionID = s.ID
data.Login = p.Login data.BriefingParticipant = *p
data.Incorrect = 0 data.Questions = makeHTMLQuestions(s.Questions, p.GivenAnswers)
data.Questions = make([]htmlQuestion, 0) if data.NoIncorrect == 0 {
for i, q := range s.Questions { if err := db.WriteGivenAnswers(*s.Briefing, *p.Participant, s.Questions, p.GivenAnswers); err != nil {
question := new(htmlQuestion) http.Error(w, err.Error(), http.StatusInternalServerError)
question.Text = q.Text log.Panicln(err)
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++
} }
} }
@ -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) { return func(w http.ResponseWriter, r *http.Request) {
data := new(questionHTMLData) p.NoIncorrect = -1
data.SessionID = s.ID p.AllowRetry = true
data.Login = p.Login }
data.Question = (*sq)[0] }
data.QuestionID = 1
func (s *Session) HandleRetry(p *BriefingParticipant, i *int) http.HandlerFunc {
template.Must(template.ParseFiles("templates/question.html")).ExecuteTemplate(w, "content", data) 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" "crypto/rand"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"html/template"
"net/http" "net/http"
"strconv" "strconv"
"streifling.com/jason/sicherheitsunterweisung/packages/data" "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) { func generateLogin() (string, error) {
bs := make([]byte, 4) bs := make([]byte, 4)
if _, err := rand.Read(bs); err != nil { 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 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 _, session := range *ss {
for _, p := range session.Participants { for _, p := range session.Participants {
if l == p.Login { if l == p.Login {
@ -46,21 +37,48 @@ func newParticipant(l string) (*data.Participant, error) {
p.ID, err = strconv.ParseInt(l, 10, 64) p.ID, err = strconv.ParseInt(l, 10, 64)
if err != nil { 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 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")) answer, err := strconv.Atoi(r.PostFormValue("answer"))
if err != nil { if err != nil {
return fmt.Errorf("handleGivenAnswer: strconv.Atoi(): %v\n", err) return fmt.Errorf("error: handleGivenAnswer: strconv.Atoi(): %v", err)
}
if err := db.WriteGivenAnswer(s.Briefing, p, &s.Questions[i], answer); err != nil {
return fmt.Errorf("handleGivenAnswer: db.WriteGivenAnswer(): %v\n", err)
} }
p.GivenAnswers[i] = answer
return nil 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" "streifling.com/jason/sicherheitsunterweisung/packages/data"
) )
type Session struct { type tableHTMLData struct {
ID uuid.UUID
*data.Briefing
Participants []*data.Participant
Questions []data.Question
}
type briefingHTMLData struct {
SessionID uuid.UUID SessionID uuid.UUID
Login string OTD []data.OverviewTableData
} }
type participantHTMLData struct { type participantHTMLData struct {
SessionID uuid.UUID SessionID uuid.UUID
Login string BriefingParticipant
} }
type questionHTMLData struct { type questionHTMLData struct {
SessionID uuid.UUID participantHTMLData
Login string
Question data.Question Question data.Question
QuestionID int64 QuestionID int64
} }
type htmlAnswer struct { type resultAnswer struct {
Text string Text string
Correct bool Correct bool
Chosen bool Chosen bool
} }
type htmlQuestion struct { type resultQuestion struct {
Text string Text string
Answers []htmlAnswer Answers []resultAnswer
} }
type resultHTMLData struct { type resultHTMLData struct {
SessionID uuid.UUID participantHTMLData
Login string Questions []resultQuestion
Questions []htmlQuestion }
Incorrect int
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"> <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 Neuer Teilnehmer
</button> </button>
<button type="submit" hx-post="/submit-form/{{ .SessionID }}/" hx-target="#content" hx-swap="innerHTML"> <button type="submit" hx-post="/submit-form/{{.SessionID}}/" hx-target="#content">
Fertig Weiter
</button> </button>
</div> </div>
{{ end }} {{end}}
{{ define "new" }} {{define "new"}}
{{ template "add-buttons" . }} {{template "add-buttons" .}}
<p>{{ .Login }}</p> <p>{{.Login}}</p>
{{ end }} {{end}}
{{ define "content" }} {{define "content"}}
<form> <form>
<div> <div>
<label for="location">Ort</label> <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>
<div> <div>
<label for="document">Dokument</label> <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>
<div> <div>
<label for="as-of">Stand vom</label> <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> </div>
{{ template "add-buttons" . }} {{template "add-buttons" .}}
</form> </form>
{{ end }} {{end}}

View File

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

View File

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

View File

@ -1,16 +1,16 @@
{{ define "content" }} {{define "content"}}
<form> <form>
<label for="first-{{ .Login }}">Vorname</label> <label for="first-{{.Login}}">Vorname</label>
<input type="text" name="first-{{ .Login }}" id="first-{{ .Login }}" /> <input type="text" name="first-{{.Login}}" id="first-{{.Login}}" />
<label for="last-{{ .Login }}">Nachname</label> <label for="last-{{.Login}}">Nachname</label>
<input type="text" name="last-{{ .Login }}" id="last-{{ .Login }}" /> <input type="text" name="last-{{.Login}}" id="last-{{.Login}}" />
<label for="company-{{ .Login }}">Firma</label> <label for="company-{{.Login}}">Firma</label>
<input type="text" name="company-{{ .Login }}" id="company-{{ .Login }}" /> <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 Fertig
</button> </button>
</form> </form>
{{ end }} {{end}}

View File

@ -7,12 +7,13 @@
{{end}} {{end}}
{{define "content"}} {{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}} {{range .Questions}}
<p>{{.Text}}</p> <p>{{.Text}}</p>
{{template "answers" .}} {{template "answers" .}}
{{end}} {{end}}
{{if gt .Incorrect 0}}
<button hx-post="/retry/{{.SessionID}}/{{.Login}}/" hx-target="#content" type="submit">Wiederholen</button>
{{end}}
{{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" }} {{define "rows"}}
{{ range . }} {{range .OTD}}
<tr> <tr>
<td>{{ .InstructorFirstName }}</td> <td>{{.InstructorFirstName}}</td>
<td>{{ .InstructorLastName }}</td> <td>{{.InstructorLastName}}</td>
<td>{{ .BriefingDate }}</td> <td>{{.BriefingDate}}</td>
<td>{{ .BriefingTime }}</td> <td>{{.BriefingTime}}</td>
<td>{{ .BriefingLocation }}</td> <td>{{.BriefingLocation}}</td>
<td>{{ .BriefingDocumentName }}</td> <td>{{.BriefingDocumentName}}</td>
<td>{{ .BriefingAsOf }}</td> <td>{{.BriefingAsOf}}</td>
<td>{{ .ParticipantFirstName }}</td> <td>{{.ParticipantFirstName}}</td>
<td>{{ .ParticipantLastName }}</td> <td>{{.ParticipantLastName}}</td>
<td>{{ .ParticipantCompany }}</td> <td>{{.ParticipantCompany}}</td>
</tr> </tr>
{{ end }} {{end}}
{{ end }} {{end}}
{{ define "content" }} {{define "content"}}
<form> <form>
<label for="search-input">Suche</label> <label for="search-input">Suche</label>
<input type="text" name="search" id="search-input" hx-post="/search/" hx-target="#results" hx-swap="innerHTML" <input type="text" name="search" id="search-input" hx-post="/search/{{.SessionID}}/" hx-target="#results">
hx-trigger="keyup changed delay:200ms" />
</form> </form>
<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 Neue Unterweisung
</button> </button>
</form> </form>
@ -43,7 +42,7 @@
</thead> </thead>
<tbody id="results"> <tbody id="results">
{{ template "rows" . }} {{template "rows" .}}
</tbody> </tbody>
</table> </table>
{{ end }} {{end}}