Sessions vollständig implementiert

This commit is contained in:
Jason Streifling 2023-10-30 11:38:56 +01:00
parent 33cbf4b215
commit ba53bba0f6
13 changed files with 257 additions and 162 deletions

View File

@ -25,7 +25,6 @@ func main() {
}) })
mux.HandleFunc("/internal-login/", session.HandleInternalLogin(db, &sessions, sessionChan)) 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 mux.HandleSessions(db, sessionChan, &sessions) go mux.HandleSessions(db, sessionChan, &sessions)

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,68 +16,74 @@ 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) WriteGivenAnswers(b Briefing, p Participant, sq []Question, givenAnswers []int) error { func (db *DB) WriteGivenAnswers(b Briefing, p Participant, sq []Question, givenAnswers []int) error {
for i, q := range sq { query := `
_, err := db.Exec(`
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, givenAnswers[i]) `
for i, q := range sq {
_, err := db.Exec(query, b.ID, p.ID, q.ID, givenAnswers[i])
if err != nil { if err != nil {
return fmt.Errorf("*DB.WriteGivenAnswers: db.Exec(): %v\n", err) return fmt.Errorf("error: *DB.WriteGivenAnswers: db.Exec(): %v", err)
} }
} }
@ -85,7 +91,7 @@ func (db *DB) WriteGivenAnswers(b Briefing, p Participant, sq []Question, givenA
} }
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,
@ -111,9 +117,11 @@ 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()
@ -134,7 +142,7 @@ 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)
@ -143,8 +151,8 @@ func (db *DB) GetAllOverviewTableData() ([]OverviewTableData, error) {
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,
@ -172,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)
@ -195,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()
@ -238,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)
} }
@ -247,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)
@ -271,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)
@ -301,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

@ -15,7 +15,7 @@ func HandleInternalLogin(db *data.DB, ss *[]*Session, cs chan<- *Session) http.H
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,7 +24,7 @@ func HandleInternalLogin(db *data.DB, ss *[]*Session, cs chan<- *Session) 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
@ -32,7 +32,7 @@ func HandleInternalLogin(db *data.DB, ss *[]*Session, cs chan<- *Session) http.H
data.SessionID = session.ID data.SessionID = session.ID
data.OTD, err = db.GetAllOverviewTableData() data.OTD, err = db.GetAllOverviewTableData()
if err != nil { if err != nil {
http.Error(w, "displayTable: *DB.GetAllOverviewTableData(): "+fmt.Sprint(err), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panicln(err) log.Panicln(err)
} }
@ -44,42 +44,51 @@ func HandleInternalLogin(db *data.DB, ss *[]*Session, cs chan<- *Session) 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) 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) 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) log.Panicln(err)
} }
@ -90,27 +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)
} }
bs, err := db.GetAllOverviewTableData() data := new(summaryHTMLData)
if err != nil { data.SessionID = s.ID
http.Error(w, "displayTable: *DB.GetAllOverviewTableData(): "+fmt.Sprint(err), http.StatusInternalServerError) data.ParticipantsData = make([]participantHTMLData, len(s.Participants))
log.Panicln(err) for i, p := range s.Participants {
data.ParticipantsData[i].SessionID = s.ID
data.ParticipantsData[i].BriefingParticipant = *p
} }
template.Must(template.ParseFiles("templates/table.html")).ExecuteTemplate(w, "content", bs) template.Must(template.ParseFiles("templates/summary.html")).ExecuteTemplate(w, "content", data)
} }
} }
@ -129,64 +139,64 @@ func HandleExternalLogin(ss *[]*Session) http.HandlerFunc {
} }
} }
func (s *Session) HandleParticipant(db *data.DB, p *data.Participant, sq *[]data.Question) 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 *SessionParticipant, 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) {
if i < int64(len(*sq)) { if i < int64(len(s.Questions)) {
if err := handleGivenAnswer(s, p, i-1, r); err != nil { if err := handleGivenAnswer(p, i-1, r); err != nil {
http.Error(w, "DisplayQuestion: handleGivenAnswer(): "+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)[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); 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)
} }
log.Println(p.GivenAnswers)
p.NoIncorrect = 0
for i, q := range s.Questions {
if p.GivenAnswers[i] != q.Correct {
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 = makeHTMLQuestions(s.Questions, p.GivenAnswers)
for i, q := range *sq {
if p.GivenAnswers[i] != q.Correct {
data.Incorrect++
}
}
if data.Incorrect == 0 { if data.NoIncorrect == 0 {
if err := db.WriteGivenAnswers(*s.Briefing, *p.Participant, s.Questions, p.GivenAnswers); err != nil { if err := db.WriteGivenAnswers(*s.Briefing, *p.Participant, s.Questions, p.GivenAnswers); err != nil {
http.Error(w, "HandleAnswer: db.WriteGivenAnswer(): "+fmt.Sprint(err), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panicln(err) log.Panicln(err)
} }
} }
@ -196,16 +206,49 @@ func (s *Session) HandleAnswer(db *data.DB, p *SessionParticipant, sq *[]data.Qu
} }
} }
func (s *Session) HandleRetry(p *data.Participant, sq *[]data.Question, i *int) 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) {
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 (*i) = 0
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 = int64(*i + 1) data.QuestionID = int64(*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 {
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

@ -10,32 +10,17 @@ import (
"streifling.com/jason/sicherheitsunterweisung/packages/data" "streifling.com/jason/sicherheitsunterweisung/packages/data"
) )
func (mux *Mux) handleParticipants(db *data.DB, cp <-chan *data.Participant, s *Session) {
for p := range cp {
sessionParticipant := new(SessionParticipant)
sessionParticipant.Participant = p
sessionParticipant.GivenAnswers = make([]int, len(s.Questions))
mux.HandleFunc("/submit-participant/"+fmt.Sprint(s.ID)+"/"+fmt.Sprint(p.Login)+"/", s.HandleParticipant(db, p, &s.Questions))
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, sessionParticipant, &s.Questions, int64(i+1)))
}
mux.HandleFunc("/retry/"+fmt.Sprint(s.ID)+"/"+fmt.Sprint(p.Login)+"/", s.HandleRetry(p, &s.Questions, &i))
}
}
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 {
@ -52,31 +37,31 @@ 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 *SessionParticipant, i int64, r *http.Request) 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)
} }
p.GivenAnswers[i] = answer p.GivenAnswers[i] = answer
return nil return nil
} }
func makeHTMLQuestions(sq []data.Question, givenAnswers []int) []htmlQuestion { func makeHTMLQuestions(sq []data.Question, givenAnswers []int) []resultQuestion {
questions := make([]htmlQuestion, 0) questions := make([]resultQuestion, 0)
for i, q := range sq { for i, q := range sq {
question := new(htmlQuestion) question := new(resultQuestion)
question.Text = q.Text question.Text = q.Text
question.Answers = make([]htmlAnswer, 0) question.Answers = make([]resultAnswer, 0)
for j, a := range q.Answers { for j, a := range q.Answers {
answer := new(htmlAnswer) answer := new(resultAnswer)
answer.Text = a.Text answer.Text = a.Text
if j+1 == q.Correct { if j+1 == q.Correct {

View File

@ -10,37 +10,34 @@ type tableHTMLData struct {
OTD []data.OverviewTableData OTD []data.OverviewTableData
} }
type briefingHTMLData struct {
SessionID uuid.UUID
Login string
}
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

@ -8,6 +8,21 @@ import (
"streifling.com/jason/sicherheitsunterweisung/packages/data" "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 { func NewMux() *Mux {
mux := new(Mux) mux := new(Mux)
mux.ServeMux = http.NewServeMux() mux.ServeMux = http.NewServeMux()
@ -17,7 +32,7 @@ func NewMux() *Mux {
func (mux *Mux) HandleSessions(db *data.DB, cs <-chan *Session, ss *[]*Session) { func (mux *Mux) HandleSessions(db *data.DB, cs <-chan *Session, ss *[]*Session) {
for s := range cs { for s := range cs {
(*ss) = append(*ss, s) (*ss) = append(*ss, s)
participantChan := make(chan *data.Participant) participantChan := make(chan *BriefingParticipant)
questionIDs := make([]string, 4) questionIDs := make([]string, 4)
for i := 0; i < len(questionIDs); i++ { for i := 0; i < len(questionIDs); i++ {
@ -30,9 +45,11 @@ func (mux *Mux) HandleSessions(db *data.DB, cs <-chan *Session, ss *[]*Session)
log.Fatalln(err) 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-briefing/"+fmt.Sprint(s.ID)+"/", s.HandleNewBriefing())
mux.HandleFunc("/new-participant/"+fmt.Sprint(s.ID)+"/", s.HandleNewParticipant(participantChan)) mux.HandleFunc("/new-participant/"+fmt.Sprint(s.ID)+"/", s.HandleNewParticipant(participantChan))
mux.HandleFunc("/submit-form/"+fmt.Sprint(s.ID)+"/", s.HandleBriefingForm(db)) 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) go mux.handleParticipants(db, participantChan, s)
} }

View File

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

View File

@ -4,8 +4,8 @@
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}}
@ -19,17 +19,17 @@
<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" .}}

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

@ -18,11 +18,11 @@
{{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"> <input type="text" name="search" id="search-input" hx-post="/search/{{.SessionID}}/" hx-target="#results">
</form> </form>
<form> <form>
<button type="submit" hx-post="/new-briefing/{{.SessionID}}" hx-target="#content"> <button type="submit" hx-post="/new-briefing/{{.SessionID}}/" hx-target="#content">
Neue Unterweisung Neue Unterweisung
</button> </button>
</form> </form>