sprechstunden-go/controllers/deleteOfficeHourHandler.go

63 lines
2 KiB
Go

// deleteOfficeHourHandler
package controllers
import (
"database/sql"
"errors"
"net/http"
"officeHours/models"
"officeHours/templating"
"strconv"
)
// Offer a table of all office hours to delete,
// verify the corresponding mail address and
// then send a confirmation mail.
func (b *BaseHandler) DeleteOfficeHourHandler(w http.ResponseWriter, req *http.Request) {
SendSecurityHeaders(w, req)
if req.FormValue("id") != "" {
id, err := strconv.Atoi(req.FormValue("id"))
if err != nil {
w.WriteHeader(http.StatusBadRequest)
templating.ServeTemplate(w, "deleteFailure", struct{ Error string }{"Id konnte nicht gelesen werden."})
return
}
officeHour, err := b.officeHourRepo.FindById(id)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
w.WriteHeader(http.StatusNotFound)
templating.ServeTemplate(w, "deleteFailure", struct{ Error string }{"Sprechstunde wurde nicht gefunden."})
} else {
w.WriteHeader(http.StatusInternalServerError)
templating.ServeTemplate(w, "deleteFailure", struct{ Error error }{err})
}
return
}
if req.FormValue("email") == "" {
templating.ServeTemplate(w, "deleteMailForm", struct {
Error string
OfficeHour models.OfficeHour
}{"", officeHour})
return
}
if req.FormValue("email") != officeHour.Tutor.Email {
w.WriteHeader(http.StatusUnauthorized)
templating.ServeTemplate(w, "deleteMailForm", struct {
Error string
OfficeHour models.OfficeHour
}{"Die Sprechstunde wurde nicht mit dieser Mailadresse angelegt.", officeHour})
return
}
_, err = b.requestRepo.Add(officeHour, models.RequestDelete)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
templating.ServeTemplate(w, "deleteFailure", struct{ Error error }{err})
return
}
templating.ServeTemplate(w, "deleteSuccess", nil)
} else {
officeHours, _ := b.officeHourRepo.GetAll(true)
timetable, slots := b.GetTimetable(officeHours)
b.writeTimetablePage(w, req, b.printTimetable(timetable, slots, true))
}
}