Add exceptional hour modals

This commit is contained in:
2025-10-19 21:17:28 +01:00
parent 5efc893269
commit 17ebaeba94
4 changed files with 667 additions and 156 deletions
+197 -59
View File
@@ -3,6 +3,7 @@ package scheduling
import (
"encoding/json"
"net/http"
"strconv"
"time"
"crussell/db"
@@ -21,19 +22,14 @@ type ExceptionalGroup struct {
ID int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Hours []ExceptionalHours `json:"hours,omitempty"` // opening hours per day, 7 (day) entries per week
Hours []ExceptionalHours `json:"hours,omitempty"`
WeekStarts []string `json:"weekStarts,omitempty"`
}
type ExceptionalApplication struct {
ID int `json:"id"`
GroupID int `json:"groupId"`
WeekStart string `json:"weekStart"` // week beginning monday the Xth
}
// --- Exceptional Groups & Hours ---
// --- List Groups with Hours and Applications ---
func ListExceptionalGroups(w http.ResponseWriter, r *http.Request) {
rows, err := db.DB.Query(r.Context(), `
SELECT id,name,description
SELECT id, name, description
FROM exceptional_working_hours_groups
ORDER BY id DESC
`)
@@ -50,125 +46,267 @@ func ListExceptionalGroups(w http.ResponseWriter, r *http.Request) {
http.Error(w, "failed to scan group", http.StatusInternalServerError)
return
}
// load 7-day hours
hoursRows, _ := db.DB.Query(r.Context(), `
// Load 7-day hours
hoursRows, err := db.DB.Query(r.Context(), `
SELECT id, weekday, start_time::text, end_time::text, is_open
FROM exceptional_working_hours
WHERE group_id=$1 ORDER BY weekday
`, g.ID)
if err != nil {
http.Error(w, "failed to fetch group hours", http.StatusInternalServerError)
return
}
for hoursRows.Next() {
var h ExceptionalHours
if err := hoursRows.Scan(&h.ID, &h.Weekday, &h.StartTime, &h.EndTime, &h.IsOpen); err == nil {
h.GroupID = g.ID
g.Hours = append(g.Hours, h)
if err := hoursRows.Scan(&h.ID, &h.Weekday, &h.StartTime, &h.EndTime, &h.IsOpen); err != nil {
hoursRows.Close()
http.Error(w, "failed to scan hours", http.StatusInternalServerError)
return
}
h.GroupID = g.ID
g.Hours = append(g.Hours, h)
}
hoursRows.Close()
if err := hoursRows.Err(); err != nil {
http.Error(w, "error iterating hours", http.StatusInternalServerError)
return
}
// Load applied week starts
weekRows, err := db.DB.Query(r.Context(), `
SELECT week_start
FROM exceptional_group_applications
WHERE group_id=$1 ORDER BY week_start
`, g.ID)
if err != nil {
http.Error(w, "failed to fetch applications", http.StatusInternalServerError)
return
}
for weekRows.Next() {
var weekStart time.Time
if err := weekRows.Scan(&weekStart); err != nil {
weekRows.Close()
http.Error(w, "failed to scan week_start", http.StatusInternalServerError)
return
}
g.WeekStarts = append(g.WeekStarts, weekStart.Format("2006-01-02"))
}
weekRows.Close()
if err := weekRows.Err(); err != nil {
http.Error(w, "error iterating applications", http.StatusInternalServerError)
return
}
groups = append(groups, g)
}
if err := rows.Err(); err != nil {
http.Error(w, "error iterating groups", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(groups)
}
// --- Create Group with Hours and Applications (bulk) ---
func CreateExceptionalGroup(w http.ResponseWriter, r *http.Request) {
var g ExceptionalGroup
if err := json.NewDecoder(r.Body).Decode(&g); err != nil {
http.Error(w, "invalid payload", http.StatusBadRequest)
return
}
if len(g.Hours) != 7 {
http.Error(w, "must provide 7 weekday entries", http.StatusBadRequest)
http.Error(w, "must provide exactly 7 weekday entries (0-6)", http.StatusBadRequest)
return
}
// Validate weekdays and parse week_starts
weekdaysSeen := make(map[int]bool)
for _, h := range g.Hours {
if h.Weekday < 0 || h.Weekday > 6 {
http.Error(w, "weekday must be 0-6", http.StatusBadRequest)
return
}
if weekdaysSeen[h.Weekday] {
http.Error(w, "duplicate weekday entries", http.StatusBadRequest)
return
}
weekdaysSeen[h.Weekday] = true
}
var parsedWeeks []time.Time
for _, ws := range g.WeekStarts {
weekStart, err := time.Parse("2006-01-02", ws)
if err != nil {
http.Error(w, "invalid week_start format, expected YYYY-MM-DD", http.StatusBadRequest)
return
}
if weekStart.Weekday() != time.Monday {
http.Error(w, "week_start must be a Monday", http.StatusBadRequest)
return
}
parsedWeeks = append(parsedWeeks, weekStart)
}
tx, err := db.DB.Begin(r.Context())
if err != nil {
http.Error(w, "failed to start tx", http.StatusInternalServerError)
http.Error(w, "failed to start transaction", http.StatusInternalServerError)
return
}
defer tx.Rollback(r.Context())
// Create group
err = tx.QueryRow(r.Context(), `
INSERT INTO exceptional_working_hours_groups (name, description)
VALUES ($1,$2) RETURNING id
VALUES ($1, $2) RETURNING id
`, g.Name, g.Description).Scan(&g.ID)
if err != nil {
http.Error(w, "failed to create group", http.StatusInternalServerError)
return
}
for _, h := range g.Hours {
_, err := tx.Exec(r.Context(), `
// Insert hours and collect their IDs
inputHours := g.Hours
g.Hours = []ExceptionalHours{} // Clear and rebuild with IDs
for _, h := range inputHours {
var id int
err := tx.QueryRow(r.Context(), `
INSERT INTO exceptional_working_hours (group_id, weekday, start_time, end_time, is_open)
VALUES ($1,$2,$3,$4,$5)
`, g.ID, h.Weekday, h.StartTime, h.EndTime, h.IsOpen)
VALUES ($1, $2, $3, $4, $5)
RETURNING id
`, g.ID, h.Weekday, h.StartTime, h.EndTime, h.IsOpen).Scan(&id)
if err != nil {
http.Error(w, "failed to insert group hours", http.StatusInternalServerError)
http.Error(w, "failed to insert hours", http.StatusInternalServerError)
return
}
h.ID = id
h.GroupID = g.ID
g.Hours = append(g.Hours, h)
}
// Insert applications
for _, weekStart := range parsedWeeks {
_, err := tx.Exec(r.Context(), `
INSERT INTO exceptional_group_applications (group_id, week_start)
VALUES ($1, $2)
`, g.ID, weekStart)
if err != nil {
http.Error(w, "failed to insert application", http.StatusInternalServerError)
return
}
}
if err := tx.Commit(r.Context()); err != nil {
http.Error(w, "failed to commit", http.StatusInternalServerError)
http.Error(w, "failed to commit transaction", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(g)
}
// --- Exceptional Applications (assign a group to a week) ---
func ListExceptionalApplications(w http.ResponseWriter, r *http.Request) {
rows, err := db.DB.Query(r.Context(), `
SELECT id, group_id, week_start
FROM exceptional_group_applications
ORDER BY week_start DESC
`)
if err != nil {
http.Error(w, "failed to fetch applications", http.StatusInternalServerError)
// --- Delete Group (cascades to hours and applications) ---
func DeleteExceptionalGroup(w http.ResponseWriter, r *http.Request) {
// Extract group ID from URL path or query params
// Assuming you have a router that provides this, e.g. chi, mux, etc.
// For this example, we'll use query param: DELETE /exceptional-groups?id=123
idStr := r.URL.Query().Get("id")
if idStr == "" {
http.Error(w, "missing id parameter", http.StatusBadRequest)
return
}
defer rows.Close()
var list []ExceptionalApplication
for rows.Next() {
var a ExceptionalApplication
var weekStart time.Time
if err := rows.Scan(&a.ID, &a.GroupID, &weekStart); err != nil {
http.Error(w, "failed to scan application", http.StatusInternalServerError)
return
}
a.WeekStart = weekStart.Format("2006-01-02")
list = append(list, a)
id, err := strconv.Atoi(idStr)
if err != nil {
http.Error(w, "invalid id parameter", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(list)
result, err := db.DB.Exec(r.Context(), `
DELETE FROM exceptional_working_hours_groups WHERE id=$1
`, id)
if err != nil {
http.Error(w, "failed to delete group", http.StatusInternalServerError)
return
}
rowsAffected := result.RowsAffected()
if rowsAffected == 0 {
http.Error(w, "group not found", http.StatusNotFound)
return
}
w.WriteHeader(http.StatusNoContent)
}
func CreateExceptionalApplication(w http.ResponseWriter, r *http.Request) {
var a ExceptionalApplication
if err := json.NewDecoder(r.Body).Decode(&a); err != nil {
// --- Update Applied Weeks (replaces all applications for a group) ---
func UpdateExceptionalApplications(w http.ResponseWriter, r *http.Request) {
var req struct {
GroupID int `json:"groupId"`
WeekStarts []string `json:"weekStarts"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid payload", http.StatusBadRequest)
return
}
weekStart, err := time.Parse("2006-01-02", a.WeekStart)
// Validate and parse weeks
var parsedWeeks []time.Time
for _, ws := range req.WeekStarts {
weekStart, err := time.Parse("2006-01-02", ws)
if err != nil {
http.Error(w, "invalid week_start format, expected YYYY-MM-DD", http.StatusBadRequest)
return
}
if weekStart.Weekday() != time.Monday {
http.Error(w, "week_start must be a Monday", http.StatusBadRequest)
return
}
parsedWeeks = append(parsedWeeks, weekStart)
}
tx, err := db.DB.Begin(r.Context())
if err != nil {
http.Error(w, "invalid week_start format, expected YYYY-MM-DD", http.StatusBadRequest)
http.Error(w, "failed to start transaction", http.StatusInternalServerError)
return
}
defer tx.Rollback(r.Context())
// Delete existing applications for this group
_, err = tx.Exec(r.Context(), `
DELETE FROM exceptional_group_applications WHERE group_id=$1
`, req.GroupID)
if err != nil {
http.Error(w, "failed to delete existing applications", http.StatusInternalServerError)
return
}
err = db.DB.QueryRow(r.Context(), `
INSERT INTO exceptional_group_applications (group_id, week_start)
VALUES ($1,$2)
RETURNING id
`, a.GroupID, weekStart).Scan(&a.ID)
if err != nil {
http.Error(w, "failed to create application", http.StatusInternalServerError)
// Insert new applications
for _, weekStart := range parsedWeeks {
_, err := tx.Exec(r.Context(), `
INSERT INTO exceptional_group_applications (group_id, week_start)
VALUES ($1, $2)
`, req.GroupID, weekStart)
if err != nil {
http.Error(w, "failed to insert application", http.StatusInternalServerError)
return
}
}
if err := tx.Commit(r.Context()); err != nil {
http.Error(w, "failed to commit transaction", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(a)
w.WriteHeader(http.StatusNoContent)
}