Compare commits

...

16 Commits

Author SHA1 Message Date
5019432b24 Noch ein Bisschen aufgeräumt 2023-10-19 15:22:45 +02:00
39d8108521 Viel Code erstmal auskommentiert, um der Logik besser folgen zu können + ein paar Änderungen 2023-10-18 17:08:27 +02:00
82ced65513 server.DisplayParticipantForm aufgeräumt 2023-10-18 16:59:02 +02:00
b605217625 db.WriteParticipant erstellt und dazu alle IDs von int auf int64 umgestellt 2023-10-18 16:43:04 +02:00
db070776b1 server.newParticipant() vereinfacht 2023-10-18 16:26:04 +02:00
3e9cfb49eb server.SubmitForm() zu server.SubmitBriefingForm() umbenannt und weitgehend an neues DB-Layout angepasst 2023-10-18 16:22:39 +02:00
b42f739581 DB.GetLastID() funktioniert wieder und DB.GetInstructors() erstellt für Darstellung in Drop-Down-Menü 2023-10-18 16:21:44 +02:00
c22647edd9 An allen wichtigen Stellen fmt.Errorf() durch http.Error() ersetzt 2023-10-17 18:37:31 +02:00
9bdc6e9f43 db.WriteBriefing umbenannt zu db.WriteAllDataOfBriefing und an neue DB-Struktur angepasst mit passenden Helferfunktionen 2023-10-17 18:28:09 +02:00
b17fa1edc7 TODO hinzugefügt, um GetLastID zu streichen 2023-10-17 17:46:01 +02:00
c69bfdfab2 db.ReadByName zu db.GetOverviewTableDataByName umbenannt und an die neue DB-Struktur angepasst 2023-10-17 17:45:26 +02:00
c38d3131c6 db.ReadAllBriefings zu db.GetAllOverviewTableData umbenannt und die Funktion an das neue DB-Layout angepasst 2023-10-17 17:30:39 +02:00
e4d2f9ae3e Typen dem neuen Datenbanklayout angepasst 2023-10-17 17:04:17 +02:00
523fee3ff2 document_name für Tabelle briefings hinzugefügt, um zwischen Landessprachen unterscheiden zu können 2023-10-17 16:39:21 +02:00
230d79c675 db.ReadAll zu db.ReadAllBriefings umbenannt, um neue DB-Struktur besser zu representieren 2023-10-17 16:36:08 +02:00
664c24974b SQL-Abfrage vereinfacht 2023-10-17 16:34:21 +02:00
5 changed files with 340 additions and 242 deletions

View File

@ -19,6 +19,7 @@ CREATE TABLE briefings (
date DATE NOT NULL, date DATE NOT NULL,
time TIME NOT NULL, time TIME NOT NULL,
location VARCHAR(32) NOT NULL, location VARCHAR(32) NOT NULL,
document_name VARCHAR(16) NOT NULL,
as_of DATE NOT NULL, as_of DATE NOT NULL,
instructor_id INT NOT NULL, instructor_id INT NOT NULL,
@ -69,8 +70,8 @@ VALUES
INSERT INTO briefings ( INSERT INTO briefings (
date, time, location, as_of, instructor_id date, time, location, as_of, instructor_id
) VALUES ) VALUES
( '2023-10-16', '17:00:00', 'Werk Langenhagen', '2021-02-01', '1' ), ( '2023-10-16', '17:00:00', 'Werk Langenhagen', 'ICS-2021-LGH', '2021-02-01', '1' ),
( '2023-10-16', '17:05:00', 'Werk Langenhagen', '2021-02-01', '2' ); ( '2023-10-16', '17:05:00', 'Werk Langenhagen', 'ICS-2021-LGH', '2021-02-01', '2' );
INSERT INTO participants ( INSERT INTO participants (
first_name, last_name, company first_name, last_name, company

37
main.go
View File

@ -1,60 +1,33 @@
package main package main
import ( import (
"fmt"
"html/template" "html/template"
"log" "log"
"net/http" "net/http"
"streifling.com/jason/sicherheitsunterweisung/packages/data" "streifling.com/jason/sicherheitsunterweisung/packages/data"
"streifling.com/jason/sicherheitsunterweisung/packages/server" "streifling.com/jason/sicherheitsunterweisung/packages/server"
"streifling.com/jason/sicherheitsunterweisung/packages/types"
) )
func waitForParticipants(sb []*types.Briefing, sp []*types.Participant, cp <-chan *types.Participant, m *http.ServeMux) {
for p := range cp {
p.Questions = data.InitQuestions()
sp = append(sp, p)
var i int
for i = range p.Questions {
m.HandleFunc("/display-question-"+fmt.Sprintf("%d", p.ID)+"-"+fmt.Sprintf("%d", i)+"/", server.DisplayQuestion(i, p))
}
m.HandleFunc("/display-question-"+fmt.Sprintf("%d", p.ID)+"-"+fmt.Sprintf("%d", i+1)+"/", server.DisplayTestResults(sb, p))
}
}
func main() { func main() {
logins := make([]string, 0) logins := make([]string, 0)
participants := make([]*types.Participant, 0)
briefings := make([]*types.Briefing, 0)
mux := http.NewServeMux()
db, err := data.OpenDB("sicherheitsunterweisung") db, err := data.OpenDB("sicherheitsunterweisung")
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
var i, j int64 mux := http.NewServeMux()
if err := db.GetLastID(&i); err != nil {
log.Fatalln(err)
}
j = i
participantChan := make(chan *types.Participant)
defer close(participantChan)
go waitForParticipants(briefings, participants, participantChan, mux)
mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/")))) mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
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("/search/", server.DisplaySearchResults(db)) mux.HandleFunc("/search/", server.DisplaySearchResults(db))
mux.HandleFunc("/new-briefing/", server.DisplayForm(&i)) mux.HandleFunc("/new-briefing/", server.DisplayInstructorForm())
mux.HandleFunc("/add-participant/", server.AddParticipant(&i, &logins)) mux.HandleFunc("/add-participant/", server.AddParticipant(&logins))
mux.HandleFunc("/submit-form/", server.SubmitForm(db, &i, &j)) mux.HandleFunc("/submit-form/", server.SubmitBriefingForm(db, &logins))
mux.HandleFunc("/internal-login/", server.DisplayTable(db)) mux.HandleFunc("/internal-login/", server.DisplayTable(db))
mux.HandleFunc("/external-login/", server.DisplayParticipantForm(&logins, participantChan)) mux.HandleFunc("/external-login/", server.DisplayParticipantForm(&logins))
log.Fatalln(http.ListenAndServe(":8080", mux)) log.Fatalln(http.ListenAndServe(":8080", mux))
} }

View File

@ -60,12 +60,6 @@ func getCredentials() (string, string, error) {
return user, pass, nil return user, pass, nil
} }
func reverseOrder(bs []*types.Briefing) {
for i, j := 0, len(bs)-1; i < j; i, j = i+1, j-1 {
bs[i], bs[j] = bs[j], bs[i]
}
}
func OpenDB(dbName string) (*DB, error) { func OpenDB(dbName string) (*DB, error) {
var err error var err error
db := new(DB) db := new(DB)
@ -90,103 +84,226 @@ func OpenDB(dbName string) (*DB, error) {
} }
func (db *DB) WriteBriefing(b *types.Briefing) error { func (db *DB) WriteBriefing(b *types.Briefing) error {
for i := 0; i < len(b.Participants); i++ { result, err := db.Exec(`
result, err := db.Exec("INSERT INTO "+db.Name+" (instructor_first,"+ INSERT INTO briefings
" instructor_last, date, time, state, location, participant_first,"+ (date, time, location, document_name, as_of, instructor_id)
" participant_last, company) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", VALUES
b.FirstName, b.LastName, b.Date, b.Time, b.State, b.Location, (?, ?, ?, ?, ?, ?)
b.Participants[i].FirstName, b.Participants[i].LastName, `, b.Date, b.Time, b.Location, b.DocumentName, b.AsOf, b.InstructorID)
b.Participants[i].Company) if err != nil {
if err != nil { return fmt.Errorf("*DB.writeBriefing: db.Exec(): %v\n", err)
return fmt.Errorf("*DB.WriteBriefing: db.Exec(\"INSERT INTO"+ }
" \"+db.Name+\" (instructor_first, instructor_last, date, time, state,"+
" location, participant_first, participant_last, company) VALUES (?, ?,"+
" ?, ?, ?, ?, ?, ?, ?)\", b.FirstName, b.LastName, b.Date, b.Time,"+
" b.State, b.Location, b.Participants[i].FirstName,"+
" b.Participants[i].LastName, b.Participants[i].Company): %v\n", err)
}
_, 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("*DB.writeBriefing: result.LastInsertId(): %v\n", err)
}
return nil
}
func (db *DB) WriteParticipant(p *types.Participant) error {
result, err := db.Exec(`
INSERT INTO participants
(first_name, last_name, company)
VALUES
(?, ?, ?)
`, p.FirstName, p.LastName, p.Company)
if err != nil {
return fmt.Errorf("*DB.writeParticipants: db.Exec(): %v\n", err)
}
p.ID, err = result.LastInsertId()
if err != nil {
return fmt.Errorf("*DB.writeParticipants: result.LastInsertId(): %v\n", err)
}
return nil
}
func (db *DB) WriteGivenAnswer(b *types.Briefing, p *types.Participant, q *types.Question, g *types.GivenAnswer) 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)
}
return nil
}
func (db *DB) WriteAllDataOfBriefing(b *types.Briefing, sp *[]*types.Participant, sq *[]*types.Question, sg *[]*types.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, (*sg)[i])
} }
} }
return nil return nil
} }
func (db *DB) ReadAll() ([]*types.Briefing, error) { func (db *DB) GetAllOverviewTableData() (*[]*types.OverviewTableData, error) {
bs := make([]*types.Briefing, 0) rows, err := db.Query(`
SELECT
rows, err := db.Query("SELECT *" + " FROM " + db.Name) i.first_name,
i.last_name,
b.date,
b.time,
b.location,
b.document_name,
b.as_of,
p.first_name,
p.last_name,
p.company
FROM given_answers AS g
INNER JOIN briefings AS b
ON b.id = g.briefing_id
INNER JOIN participants AS p
ON p.id = g.participant_id
INNER JOIN instructors AS i
ON i.id = b.instructor_id
ORDER BY
b.id DESC,
p.id
`)
if err != nil { if err != nil {
return nil, fmt.Errorf("*DB.ReadAll: db.Query(\"SELECT * FROM \"+db.Name): %v\n", err) return nil, fmt.Errorf("*DB.ReadAllBriefings: db.Query(): %v\n", err)
} }
defer rows.Close() defer rows.Close()
data := make([]*types.OverviewTableData, 0)
for rows.Next() { for rows.Next() {
b := new(types.Briefing) otd := new(types.OverviewTableData)
p := new(types.Participant)
if err := rows.Scan(&p.ID, &b.FirstName, &b.LastName, &b.Date, &b.Time, err := rows.Scan(
&b.State, &b.Location, &p.FirstName, &p.LastName, &p.Company); err != nil { &otd.InstructorFirstName,
return nil, fmt.Errorf("*DB.ReadAll: db.Query(): %v\n", err) &otd.InstructorLastName,
&otd.BriefingDate,
&otd.BriefingTime,
&otd.BriefingLocation,
&otd.BriefingDocumentName,
&otd.BriefingAsOf,
&otd.ParticipantFirstName,
&otd.ParticipantLastName,
&otd.ParticipantCompany,
)
if err != nil {
return nil, fmt.Errorf("*DB.ReadAllBriefings: rows.Scan(): %v\n", err)
} }
b.Participants = append(b.Participants, p) data = append(data, otd)
bs = append(bs, b)
} }
reverseOrder(bs) return &data, nil
return bs, nil
} }
func (db *DB) ReadByName(name string) ([]*types.Briefing, error) { func (db *DB) GetOverviewTableDataByName(n string) (*[]*types.OverviewTableData, error) {
bs := make([]*types.Briefing, 0) rows, err := db.Query(`
SELECT
rows, err := db.Query("SELECT *"+ i.first_name,
" FROM "+db.Name+ i.last_name,
" WHERE instructor_first LIKE ?"+ b.date,
" OR instructor_last LIKE ?"+ b.time,
" OR participant_first LIKE ?"+ b.location,
" OR participant_last LIKE ?", b.document_name,
"%"+name+"%", "%"+name+"%", "%"+name+"%", "%"+name+"%") b.as_of,
p.first_name,
p.last_name,
p.company
FROM given_answers AS g
INNER JOIN briefings AS b
ON b.id = g.briefing_id
INNER JOIN participants AS p
ON p.id = g.participant_id
INNER JOIN instructors AS i
ON i.id = b.instructor_id
WHERE
i.first_name LIKE ? OR
i.last_name LIKE ? OR
p.first_name LIKE ? OR
p.last_name LIKE ?
ORDER BY
b.id DESC,
p.id
`, "%"+n+"%", "%"+n+"%", "%"+n+"%", "%"+n+"%")
if err != nil { if err != nil {
return nil, fmt.Errorf("*DB.ReadByName: db.Query(\"SELECT *"+ return nil, fmt.Errorf("*DB.GetOverviewTableDataByName: db.Query(): %v\n", err)
" FROM \"+db.Name+"+
" WHERE instructor_first LIKE ?"+
" OR instructor_last LIKE ?"+
" OR participant_first LIKE ?"+
" OR participant_last LIKE ?\"): %v\n", err)
} }
defer rows.Close() defer rows.Close()
data := make([]*types.OverviewTableData, 0)
for rows.Next() { for rows.Next() {
b := new(types.Briefing) otd := new(types.OverviewTableData)
p := new(types.Participant)
if err := rows.Scan(&p.ID, &b.FirstName, &b.LastName, &b.Date, &b.Time, &b.State, err := rows.Scan(
&b.Location, &p.FirstName, &p.LastName, &p.Company); err != nil { &otd.InstructorFirstName,
return nil, fmt.Errorf("*DB.ReadByName: rows.Scan(&p.ID, &b.FirstName,"+ &otd.InstructorLastName,
" &b.LastName, &b.Date, &b.Time, &b.State, &b.Location, &p.FirstName,"+ &otd.BriefingDate,
" &p.LastName, &p.Company): %v\n", err) &otd.BriefingTime,
&otd.BriefingLocation,
&otd.BriefingDocumentName,
&otd.BriefingAsOf,
&otd.ParticipantFirstName,
&otd.ParticipantLastName,
&otd.ParticipantCompany,
)
if err != nil {
return nil, fmt.Errorf("*DB.ReadAllBriefings: rows.Scan(): %v\n", err)
} }
b.Participants = append(b.Participants, p)
bs = append(bs, b) data = append(data, otd)
} }
reverseOrder(bs) return &data, nil
return bs, nil
} }
func (db *DB) GetLastID(i *int64) error { func (db *DB) GetLastID(table string) (int, error) {
row := db.QueryRow("SELECT id" + var id int
" FROM " + db.Name +
" ORDER BY id DESC LIMIT 0, 1")
if err := row.Scan(i); err != nil { row := db.QueryRow(`
return fmt.Errorf("*DB.GetLastID: row.Scan(&i): %v\n", err) SELECT id
FROM ?
ORDER BY id DESC
LIMIT 0, 1
`, table)
if err := row.Scan(&id); err != nil {
return -1, fmt.Errorf("*DB.GetLastID: row.Scan(): %v\n", err)
} }
return nil return id, nil
}
func (db *DB) GetInstructors() (*[]*types.Instructor, error) {
rows, err := db.Query(`
SELECT *
FROM instructors
`)
if err != nil {
return nil, fmt.Errorf("*DB.GetInstructors: db.Query(): %v\n", err)
}
instructors := make([]*types.Instructor, 0)
for rows.Next() {
instructor := new(types.Instructor)
if err = rows.Scan(instructor); err != nil {
return nil, fmt.Errorf("*DB.GetInstructors: rows.Scan(): %v\n", err)
}
instructors = append(instructors, instructor)
}
return &instructors, nil
} }

View File

@ -5,27 +5,26 @@ import (
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"html/template" "html/template"
"log"
"net/http" "net/http"
"strconv" "strconv"
"strings" "time"
"streifling.com/jason/sicherheitsunterweisung/packages/data" "streifling.com/jason/sicherheitsunterweisung/packages/data"
"streifling.com/jason/sicherheitsunterweisung/packages/types" "streifling.com/jason/sicherheitsunterweisung/packages/types"
) )
type questionData struct { // type questionData struct {
ID int64 // ID int64
Q types.Question // Q types.Question
I int // I int
J int // J int
} // }
func DisplayTable(db *data.DB) http.HandlerFunc { func DisplayTable(db *data.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
bs, err := db.ReadAll() bs, err := db.GetAllOverviewTableData()
if err != nil { if err != nil {
_ = fmt.Errorf("DisplayTable: %v\n", err) http.Error(w, "DisplayTable: *DB.GetAllOverviewTableData(): "+fmt.Sprint(err), http.StatusInternalServerError)
} }
template.Must(template.ParseFiles("templates/table.html")).ExecuteTemplate(w, "content", bs) template.Must(template.ParseFiles("templates/table.html")).ExecuteTemplate(w, "content", bs)
} }
@ -33,70 +32,61 @@ func DisplayTable(db *data.DB) http.HandlerFunc {
func DisplaySearchResults(db *data.DB) http.HandlerFunc { func DisplaySearchResults(db *data.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
bs, err := db.ReadByName(r.PostFormValue("search")) bs, err := db.GetOverviewTableDataByName(r.PostFormValue("search"))
if err != nil { if err != nil {
_ = fmt.Errorf("DisplayResults: db.ReadByName(r.PostFormValue()): %v\n", err) http.Error(w, "DisplayResults: db.ReadByName(r.PostFormValue()): "+fmt.Sprint(err), http.StatusInternalServerError)
} }
template.Must(template.ParseFiles("templates/table.html")).ExecuteTemplate(w, "rows", bs) template.Must(template.ParseFiles("templates/table.html")).ExecuteTemplate(w, "rows", bs)
} }
} }
func DisplayForm(i *int64) http.HandlerFunc { func DisplayInstructorForm() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
template.Must(template.ParseFiles("templates/briefing.html")).ExecuteTemplate(w, "content", i) template.Must(template.ParseFiles("templates/briefing.html")).ExecuteTemplate(w, "content", nil)
} }
} }
func generateUUID() string { func generateUUID() (string, error) {
bs := make([]byte, 2) bs := make([]byte, 4)
if _, err := rand.Read(bs); err != nil { if _, err := rand.Read(bs); err != nil {
_ = fmt.Errorf("GenerateUUID: rand.Read(bs): %v\n", err) return "", fmt.Errorf("GenerateUUID: rand.Read(bs): %v\n", err)
return ""
} }
return hex.EncodeToString(bs) return hex.EncodeToString(bs), nil
} }
func AddParticipant(i *int64, ls *[]string) http.HandlerFunc { func AddParticipant(sl *[]string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
*i++ login, err := generateUUID()
login := fmt.Sprintf("%d", *i) + "-" + generateUUID() if err != nil {
(*ls) = append(*ls, login) http.Error(w, "AddParticipant: generateUUID(): "+fmt.Sprint(err), http.StatusInternalServerError)
}
(*sl) = append(*sl, login)
template.Must(template.ParseFiles("templates/briefing.html")).ExecuteTemplate(w, "new", login) template.Must(template.ParseFiles("templates/briefing.html")).ExecuteTemplate(w, "new", login)
} }
} }
func SubmitForm(db *data.DB, i, j *int64) http.HandlerFunc { // TODO: Hier weiter machen, irgendwie die b.ID herausgeben,
// am besten hier auch die p.IDs rausgeben, damit diese später verknüpft werden können
func SubmitBriefingForm(db *data.DB, sl *[]string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
b := new(types.Briefing) now := time.Now()
briefing := new(types.Briefing)
b.FirstName = r.PostFormValue("instructor-first") // TODO: Dropdownmenü
b.LastName = r.PostFormValue("instructor-last") // instructorFirstName := r.PostFormValue("instructor-first")
b.Date = r.PostFormValue("date") // instructorLastName := r.PostFormValue("instructor-last")
b.Time = r.PostFormValue("time")
b.State = r.PostFormValue("state")
b.Location = r.PostFormValue("location")
for ; *j <= *i; *j++ { briefing.Date = now.Format("2006-01-02")
b.Participants = append(b.Participants, &types.Participant{ briefing.Time = now.Format("15:04:05")
ID: *j, briefing.Location = r.PostFormValue("location")
Person: types.Person{ briefing.DocumentName = r.PostFormValue("document") // TODO: in HTML einfügen
FirstName: r.PostFormValue("participant-first-" + fmt.Sprint(*j)), briefing.AsOf = r.PostFormValue("state") // TODO: Umbenennen
LastName: r.PostFormValue(("participant-last-" + fmt.Sprint(*j))), // briefing.InstructorID = r.PostFormValue("instructor-id") // TODO: aus Dropdown holen
},
Company: r.PostFormValue(("participant-company-" + fmt.Sprint(*j))),
})
}
log.Println(b) db.WriteBriefing(briefing)
db.WriteBriefing(b)
bs, err := db.ReadAll()
if err != nil {
_ = fmt.Errorf("SubmitForm: db.ReadAll(): %v\n", err)
}
template.Must(template.ParseFiles("templates/table.html")).Execute(w, bs)
} }
} }
@ -112,95 +102,92 @@ func loginIsCorrect(l string, logins *[]string) bool {
} }
func newParticipant(l string) (*types.Participant, error) { func newParticipant(l string) (*types.Participant, error) {
var err error
p := new(types.Participant) p := new(types.Participant)
idInt, err := strconv.Atoi(strings.Split(l, "-")[0]) 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("newParticipant: strconv.Atoi(idString): %v\n", err)
} }
p.ID = int64(idInt)
return p, nil return p, nil
} }
func DisplayParticipantForm(ls *[]string, cp chan<- *types.Participant) http.HandlerFunc { func DisplayParticipantForm(sl *[]string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
l := r.PostFormValue("login") if loginIsCorrect(r.PostFormValue("login"), sl) {
uuid, err := generateUUID()
if loginIsCorrect(l, ls) {
p, err := newParticipant(l)
if err != nil { if err != nil {
http.Error(w, "GetParticipantData: newParticipant(l): "+fmt.Sprint(err), http.StatusInternalServerError) http.Error(w, "DisplayParticipantForm: generateUUID(): "+fmt.Sprint(err), http.StatusInternalServerError)
} }
cp <- p template.Must(template.ParseFiles("templates/participant.html")).ExecuteTemplate(w, "content", uuid)
template.Must(template.ParseFiles("templates/participant.html")).ExecuteTemplate(w, "content", p.ID)
} else { } else {
template.Must(template.ParseFiles("templates/login.html")).ExecuteTemplate(w, "content", nil) template.Must(template.ParseFiles("templates/login.html")).ExecuteTemplate(w, "content", nil)
} }
} }
} }
func readAnswer(r *http.Request, p *types.Participant, i int) error { // func readAnswer(r *http.Request, p *types.Participant, i int) error {
v, err := strconv.Atoi(r.PostFormValue("answer")) // v, err := strconv.Atoi(r.PostFormValue("answer"))
if err != nil { // if err != nil {
return fmt.Errorf("readAnswer: strconv.Atoi(r.PostFormValue(\"answer\")): %v\n", err) // return fmt.Errorf("readAnswer: strconv.Atoi(): %v\n", err)
} // }
//
p.Questions[i].Chosen = v // p.Questions[i].Chosen = v
//
return nil // return nil
} // }
//
func DisplayQuestion(i int, p *types.Participant) http.HandlerFunc { // func DisplayQuestion(i int, p *types.Participant) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { // return func(w http.ResponseWriter, r *http.Request) {
if i == 0 { // if i == 0 {
p.FirstName = r.PostFormValue("participant-first-" + fmt.Sprintf("%d", p.ID)) // p.FirstName = r.PostFormValue("participant-first-" + fmt.Sprintf("%d", p.ID))
p.LastName = r.PostFormValue("participant-last-" + fmt.Sprintf("%d", p.ID)) // p.LastName = r.PostFormValue("participant-last-" + fmt.Sprintf("%d", p.ID))
p.Company = r.PostFormValue("participant-company-" + fmt.Sprintf("%d", p.ID)) // p.Company = r.PostFormValue("participant-company-" + fmt.Sprintf("%d", p.ID))
} else { // } else {
if err := readAnswer(r, p, i-1); err != nil { // if err := readAnswer(r, p, i-1); err != nil {
http.Error(w, "DisplayQuestion: readAnswer(r, p, i): "+fmt.Sprint(err), http.StatusInternalServerError) // http.Error(w, "DisplayQuestion: readAnswer(r, p, i): "+fmt.Sprint(err), http.StatusInternalServerError)
} // }
} // }
//
data := new(questionData) // data := new(questionData)
data.ID = p.ID // data.ID = p.ID
data.Q = p.Questions[i] // data.Q = p.Questions[i]
data.I = i // data.I = i
data.J = i + 1 // data.J = i + 1
//
template.Must(template.ParseFiles("templates/question.html")).ExecuteTemplate(w, "content", data) // template.Must(template.ParseFiles("templates/question.html")).ExecuteTemplate(w, "content", data)
} // }
} // }
//
func DisplayTestResults(b *types.Briefing, p *types.Participant) http.HandlerFunc { // func DisplayTestResults(b *types.Briefing, p *types.Participant) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { // return func(w http.ResponseWriter, r *http.Request) {
numQuestions := len(p.Questions) // numQuestions := len(p.Questions)
wrongAnswers := make([]int, 0) // wrongAnswers := make([]int, 0)
fmt.Println(wrongAnswers) // fmt.Println(wrongAnswers)
//
if err := readAnswer(r, p, numQuestions-1); err != nil { // if err := readAnswer(r, p, numQuestions-1); err != nil {
http.Error(w, "DisplayTestResults: readAnswer(r, p, i): "+fmt.Sprint(err), http.StatusInternalServerError) // http.Error(w, "DisplayTestResults: readAnswer(r, p, i): "+fmt.Sprint(err), http.StatusInternalServerError)
} // }
//
for i, q := range p.Questions { // for i, q := range p.Questions {
if q.Chosen != q.Correct { // if q.Chosen != q.Correct {
wrongAnswers = append(wrongAnswers, i) // wrongAnswers = append(wrongAnswers, i)
} // }
} // }
//
if wrongAnswers == nil { // if wrongAnswers == nil {
b.Participants = append(b.Participants, p) // b.Participants = append(b.Participants, p)
} else { // } else {
data := new(questionData) // data := new(questionData)
data.ID = p.ID // data.ID = p.ID
data.Q = p.Questions[0] // data.Q = p.Questions[0]
data.I = 0 // data.I = 0
data.J = data.I + 1 // data.J = data.I + 1
template.Must(template.ParseFiles("templates/question.html")).ExecuteTemplate(w, "content", data) // template.Must(template.ParseFiles("templates/question.html")).ExecuteTemplate(w, "content", data)
} // }
//
template.Must(template.ParseFiles("templates/results.html")).ExecuteTemplate(w, "content", nil) // template.Must(template.ParseFiles("templates/results.html")).ExecuteTemplate(w, "content", nil)
} // }
} // }

View File

@ -1,36 +1,56 @@
package types package types
type Person struct { type Person struct {
ID int64
FirstName string FirstName string
LastName string LastName string
} }
type Instructor Person type Instructor Person
type Participant struct {
Person
Company string
}
type Briefing struct {
ID int64
Date string
Time string
Location string
DocumentName string
AsOf string
InstructorID int64
}
type Answer struct { type Answer struct {
ID int ID int64
Text string Text string
} }
type Question struct { type Question struct {
ID int64
Text string Text string
Answers []Answer Answers []Answer
Chosen int
Correct int Correct int
} }
type Participant struct { type GivenAnswer struct {
ID int64 BriefingID int64
Person ParticipantID int64
Company string QuestionID int64
Questions []Question GivenAnswer int
} }
type Briefing struct { type OverviewTableData struct {
Instructor InstructorFirstName string
Date string InstructorLastName string
Time string BriefingDate string
State string BriefingTime string
Location string BriefingLocation string
Participants []*Participant BriefingDocumentName string
BriefingAsOf string
ParticipantFirstName string
ParticipantLastName string
ParticipantCompany string
} }