package scheduling import ( "context" "encoding/json" "errors" "fmt" "net/http" "strconv" "strings" "time" "crussell/clock" "crussell/db" "crussell/internal/validators" "crussell/mw" "log" "log/slog" "github.com/jackc/pgx/v5" ) var londonLocation = clock.London // ActiveBookingStatuses is the SQL filter used by all scheduling handlers to // exclude inactive booking statuses. Must stay in sync with the bookings // package's overlapping endpoints. Includes pending_release so clients who // owe deposits are also contacted before schedule changes. const ActiveBookingStatuses = `status NOT IN ('completed', 'client_cancelled', 'we_cancelled', 'no_show', 'deposit_lapsed')` // --- Types --- type DefaultHours struct { Weekday int `json:"weekday" validate:"gte=0,lte=6"` StartTime string `json:"startTime" validate:"required"` EndTime string `json:"endTime" validate:"required"` IsOpen bool `json:"isOpen"` } type DayWorkingHours struct { Date string `json:"date"` Weekday int `json:"weekday"` StartTime string `json:"startTime"` EndTime string `json:"endTime"` IsOpen bool `json:"isOpen"` Source string `json:"source"` // "default" or "exceptional" } // ScheduledHoursChange represents a pending default hours change. type ScheduledHoursChange struct { EffectiveDate string `json:"effective_date"` Hours []DefaultHours `json:"hours"` CreatedAt string `json:"created_at,omitempty"` CreatedBy string `json:"created_by,omitempty"` } // ScheduledHoursChangeResponse wraps current + scheduled hours. type ScheduledHoursChangeResponse struct { Current []DefaultHours `json:"current"` ScheduledChange *ScheduledHoursChange `json:"scheduled_change,omitempty"` } // loadScheduledChange loads the pending default hours scheduled change, if any. // Returns nil when no pending change exists. func loadScheduledChange(ctx context.Context) *ScheduledHoursChange { var effDate, createdAt, createdBy, hoursJSON string err := db.Conn.QueryRow(ctx, ` SELECT effective_date::text, COALESCE(created_at::text, ''), COALESCE(created_by, ''), hours::text FROM default_hours_scheduled_changes WHERE applied_at IS NULL AND cancelled_at IS NULL LIMIT 1 `).Scan(&effDate, &createdAt, &createdBy, &hoursJSON) if err != nil { return nil } var sh []DefaultHours if json.Unmarshal([]byte(hoursJSON), &sh) != nil { return nil } return &ScheduledHoursChange{ EffectiveDate: effDate, Hours: sh, CreatedAt: createdAt, CreatedBy: createdBy, } } // --- Default Hours Handlers --- func GetDefaultHours(w http.ResponseWriter, r *http.Request) { rows, err := db.Conn.Query(r.Context(), ` SELECT weekday, start_time::text, end_time, is_open FROM working_hours ORDER BY weekday `) if err != nil { log.Printf("Failed to fetch default hours: %v", err) http.Error(w, "failed to fetch default hours", http.StatusInternalServerError) return } defer rows.Close() var hours []DefaultHours for rows.Next() { var h DefaultHours if err := rows.Scan(&h.Weekday, &h.StartTime, &h.EndTime, &h.IsOpen); err != nil { log.Printf("Failed to scan default hours: %v", err) http.Error(w, "failed to scan default hours", http.StatusInternalServerError) return } hours = append(hours, h) } if err := rows.Err(); err != nil { log.Printf("Error iterating default hours: %v", err) http.Error(w, "error loading default hours", http.StatusInternalServerError) return } // Check for pending scheduled change resp := ScheduledHoursChangeResponse{Current: hours} if sc := loadScheduledChange(r.Context()); sc != nil { resp.ScheduledChange = sc } w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(resp); err != nil { log.Printf("Failed to encode JSON response: %v", err) } } func UpdateDefaultHours(w http.ResponseWriter, r *http.Request) { var hours []DefaultHours if err := json.NewDecoder(r.Body).Decode(&hours); err != nil { http.Error(w, "invalid payload", http.StatusBadRequest) return } for _, h := range hours { if err := validators.Validate.Struct(&h); err != nil { log.Printf("Failed to process request: %v", err) http.Error(w, "Invalid request", http.StatusBadRequest) return } } // M8 // L5 for _, h := range hours { if !isValidTime15Min(h.StartTime) { http.Error(w, "start_time must be in 15-minute intervals (00, 15, 30, 45)", http.StatusBadRequest) return } if !isValidTime15Min(h.EndTime) { http.Error(w, "end_time must be in 15-minute intervals (00, 15, 30, 45)", http.StatusBadRequest) return } } tx, err := db.Conn.Begin(r.Context()) if err != nil { http.Error(w, "failed to start tx", http.StatusInternalServerError) return } defer func() { if err := tx.Rollback(r.Context()); err != nil && !errors.Is(err, pgx.ErrTxClosed) { slog.Error("failed to rollback transaction", "err", err) } }() weekdays := make([]int, len(hours)) startTimes := make([]string, len(hours)) endTimes := make([]string, len(hours)) isOpenFlags := make([]bool, len(hours)) for i, h := range hours { weekdays[i] = h.Weekday startTimes[i] = h.StartTime endTimes[i] = h.EndTime isOpenFlags[i] = h.IsOpen } if _, err := tx.Exec(r.Context(), ` UPDATE working_hours AS wh SET start_time = v.start_time, end_time = v.end_time, is_open = v.is_open FROM ( SELECT unnest($1::smallint[]) AS weekday, unnest($2::time[]) AS start_time, unnest($3::time[]) AS end_time, unnest($4::boolean[]) AS is_open ) v WHERE wh.weekday = v.weekday `, weekdays, startTimes, endTimes, isOpenFlags); err != nil { http.Error(w, "failed to update default hours", http.StatusInternalServerError) return } if err := tx.Commit(r.Context()); err != nil { http.Error(w, "failed to commit", http.StatusInternalServerError) return } w.WriteHeader(http.StatusNoContent) } // --- GetWorkingHours (merged default + applied exceptions, UK-local) --- func GetWorkingHours(w http.ResponseWriter, r *http.Request) { startStr := r.URL.Query().Get("start") endStr := r.URL.Query().Get("end") if startStr == "" || endStr == "" { http.Error(w, "start and end query params required", http.StatusBadRequest) return } start, err := time.Parse("2006-01-02", startStr) if err != nil { http.Error(w, "invalid start date", http.StatusBadRequest) return } end, err := time.Parse("2006-01-02", endStr) if err != nil { http.Error(w, "invalid end date", http.StatusBadRequest) return } // Parse out_of_hours toggle (admin-only extended hours) outOfHours := r.URL.Query().Get("out_of_hours") == "true" isAdmin := false if userRole, ok := r.Context().Value(mw.UserRoleKey).(string); ok { isAdmin = userRole == "admin" } useOutOfHours := outOfHours && isAdmin // Set to local start/end of day in Europe/London so that bookings // at BST midnight (23:00 UTC the previous day) are included in the // correct date range. start = time.Date(start.Year(), start.Month(), start.Day(), 0, 0, 0, 0, londonLocation) end = time.Date(end.Year(), end.Month(), end.Day(), 23, 59, 59, 999999999, londonLocation) // Load default hours defaultMap := map[int]DefaultHours{} defRows, err := db.Conn.Query(r.Context(), ` SELECT weekday, start_time::text, end_time, is_open FROM working_hours `) if err != nil { log.Printf("Failed to load default hours: %v", err) http.Error(w, "Failed to load default hours", http.StatusInternalServerError) return } for defRows.Next() { var d DefaultHours if err := defRows.Scan(&d.Weekday, &d.StartTime, &d.EndTime, &d.IsOpen); err != nil { defRows.Close() log.Printf("Failed to scan default hours row: %v", err) http.Error(w, "Failed to read default hours", http.StatusInternalServerError) return } defaultMap[d.Weekday] = d } defRows.Close() if err := defRows.Err(); err != nil { log.Printf("Error iterating default hours: %v", err) http.Error(w, "Failed to read default hours", http.StatusInternalServerError) return } // Load staged default hours change (if any) stagedChange := loadScheduledChange(r.Context()) // Load exceptional applications for Mondays in range // Expand start to the Monday of its week so single-day queries still find the correct application startWeekday := int(start.Weekday()) daysSinceMonday := startWeekday - 1 if daysSinceMonday < 0 { daysSinceMonday = 6 // Sunday } queryStart := start.AddDate(0, 0, -daysSinceMonday) appRows, err := db.Conn.Query(r.Context(), ` SELECT group_id, week_start FROM exceptional_group_applications WHERE week_start BETWEEN $1 AND $2 `, queryStart, end) if err != nil { log.Printf("Failed to load exceptional applications: %v", err) http.Error(w, "Failed to load exceptional applications", http.StatusInternalServerError) return } type appEntry struct { GroupID int WeekStart time.Time } apps := []appEntry{} groupIDs := []int{} for appRows.Next() { var a appEntry if err := appRows.Scan(&a.GroupID, &a.WeekStart); err != nil { appRows.Close() log.Printf("Failed to scan exceptional application row: %v", err) http.Error(w, "Failed to read exceptional applications", http.StatusInternalServerError) return } a.WeekStart = time.Date(a.WeekStart.Year(), a.WeekStart.Month(), a.WeekStart.Day(), 0, 0, 0, 0, time.UTC) apps = append(apps, a) groupIDs = append(groupIDs, a.GroupID) } appRows.Close() if err := appRows.Err(); err != nil { log.Printf("Error iterating exceptional applications: %v", err) http.Error(w, "Failed to read exceptional applications", http.StatusInternalServerError) return } exHoursMap := map[int]map[int]ExceptionalHours{} if len(groupIDs) > 0 { query, args := sqlIn("SELECT group_id, weekday, start_time::text, end_time, is_open FROM exceptional_working_hours WHERE group_id IN (%s)", groupIDs) rows, err := db.Conn.Query(r.Context(), query, args...) if err != nil { log.Printf("Failed to load exceptional hours: %v", err) http.Error(w, "Failed to load exceptional hours", http.StatusInternalServerError) return } for rows.Next() { var h ExceptionalHours if err := rows.Scan(&h.GroupID, &h.Weekday, &h.StartTime, &h.EndTime, &h.IsOpen); err != nil { rows.Close() log.Printf("Failed to scan exceptional hours row: %v", err) http.Error(w, "Failed to read exceptional hours", http.StatusInternalServerError) return } if _, ok := exHoursMap[h.GroupID]; !ok { exHoursMap[h.GroupID] = map[int]ExceptionalHours{} } exHoursMap[h.GroupID][h.Weekday] = h } rows.Close() if err := rows.Err(); err != nil { log.Printf("Error iterating exceptional hours: %v", err) http.Error(w, "Failed to read exceptional hours", http.StatusInternalServerError) return } } // Generate final result per day var results []DayWorkingHours for d := start; !d.After(end); d = d.AddDate(0, 0, 1) { weekday := int(d.Weekday()) if weekday == 0 { weekday = 6 // Go Sunday=0 -> our Sunday=6 } else { weekday -= 1 } // Calculate the Monday of this week daysSinceMonday := int(d.Weekday()) - 1 if daysSinceMonday < 0 { daysSinceMonday = 6 // Sunday } weekStart := d.AddDate(0, 0, -daysSinceMonday) weekStart = time.Date(weekStart.Year(), weekStart.Month(), weekStart.Day(), 0, 0, 0, 0, time.UTC) var applied *ExceptionalHours weekStartStr := weekStart.Format("2006-01-02") for _, a := range apps { appWeekStartStr := a.WeekStart.Format("2006-01-02") if appWeekStartStr == weekStartStr { if dayHours, ok := exHoursMap[a.GroupID][weekday]; ok { applied = &dayHours } break } } var day DayWorkingHours day.Date = d.Format("2006-01-02") day.Weekday = weekday if applied != nil { day.StartTime = applied.StartTime day.EndTime = applied.EndTime day.IsOpen = applied.IsOpen day.Source = "exceptional" } else if stagedChange != nil && d.Format("2006-01-02") >= stagedChange.EffectiveDate { for _, sh := range stagedChange.Hours { if sh.Weekday == weekday { day.StartTime = sh.StartTime day.EndTime = sh.EndTime day.IsOpen = sh.IsOpen day.Source = "default" break } } } else if def, ok := defaultMap[weekday]; ok { day.StartTime = def.StartTime day.EndTime = def.EndTime day.IsOpen = def.IsOpen day.Source = "default" } else { day.StartTime = "00:00" day.EndTime = "00:00" day.IsOpen = false day.Source = "default" } // Out-of-hours override for admin if useOutOfHours { day.IsOpen = true day.StartTime = "06:00" day.EndTime = "22:00" day.Source = "default" } results = append(results, day) } w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(results); err != nil { log.Printf("Failed to encode JSON response: %v", err) } } // isValidTime15Min checks that a time string (HH:MM or HH:MM:SS) has minutes in {00, 15, 30, 45}. func isValidTime15Min(t string) bool { parts := strings.Split(t, ":") if len(parts) < 2 || len(parts) > 3 { return false } if parts[0] == "" { return false } mins, err := strconv.Atoi(parts[1]) if err != nil { return false } return mins == 0 || mins == 15 || mins == 30 || mins == 45 } // --- helper: sqlIn generates IN queries dynamically for Postgres --- func sqlIn(query string, args []int) (string, []any) { inArgs := []any{} var placeholders strings.Builder for i, arg := range args { if i > 0 { placeholders.WriteString(",") } placeholders.WriteString(fmt.Sprintf("$%d", i+1)) inArgs = append(inArgs, arg) } query = fmt.Sprintf(query, placeholders.String()) return query, inArgs } // --- Types for Available Hours --- type TimeSlot struct { StartTime string `json:"startTime"` EndTime string `json:"endTime"` } type DayAvailableHours struct { Date string `json:"date"` Weekday int `json:"weekday"` IsOpen bool `json:"isOpen"` Slots []TimeSlot `json:"slots"` Source string `json:"source"` Blockers []TimeSlot `json:"blockers,omitempty"` } // availableHoursParams holds parameters for computeAvailableHours. type availableHoursParams struct { Start time.Time End time.Time OutOfHours bool IsAdmin bool ExcludeUserID *string ProposedHours []ExceptionalHours // nil for normal mode ProposedWeekStarts []string // nil for normal mode } // --- GetAvailableHours (with bookings, UK-local) --- func GetAvailableHours(w http.ResponseWriter, r *http.Request) { startStr := r.URL.Query().Get("start") endStr := r.URL.Query().Get("end") if startStr == "" || endStr == "" { http.Error(w, "start and end query params required", http.StatusBadRequest) return } start, err := time.Parse("2006-01-02", startStr) if err != nil { http.Error(w, "invalid start date", http.StatusBadRequest) return } end, err := time.Parse("2006-01-02", endStr) if err != nil { http.Error(w, "invalid end date", http.StatusBadRequest) return } outOfHours := r.URL.Query().Get("out_of_hours") == "true" isAdmin := false if userRole, ok := r.Context().Value(mw.UserRoleKey).(string); ok { isAdmin = userRole == "admin" } var excludeUserID *string if uid, ok := r.Context().Value(mw.UserIDKey).(string); ok && uid != "" { excludeUserID = &uid } startLondon := time.Date(start.Year(), start.Month(), start.Day(), 0, 0, 0, 0, londonLocation) endLondon := time.Date(end.Year(), end.Month(), end.Day(), 23, 59, 59, 999999999, londonLocation) results, err := computeAvailableHours(r.Context(), availableHoursParams{ Start: startLondon, End: endLondon, OutOfHours: outOfHours, IsAdmin: isAdmin, ExcludeUserID: excludeUserID, }) if err != nil { log.Printf("Failed to compute available hours: %v", err) http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(results); err != nil { log.Printf("Failed to encode JSON response: %v", err) } } // computeAvailableHours is the shared core for both GetAvailableHours and // GetPreviewAvailableHours. It loads default hours, exceptional applications, // bookings, and time blockers, then generates per-day available slot lists. // When params.ProposedHours is non-nil, those hours override exceptional // applications for the specified weeks (what-if simulation). func computeAvailableHours(ctx context.Context, params availableHoursParams) ([]DayAvailableHours, error) { start := params.Start end := params.End // Load default hours defaultMap := map[int]DefaultHours{} defRows, err := db.Conn.Query(ctx, `SELECT weekday, start_time::text, end_time, is_open FROM working_hours`) if err != nil { return nil, fmt.Errorf("failed to load default hours: %w", err) } for defRows.Next() { var d DefaultHours if err := defRows.Scan(&d.Weekday, &d.StartTime, &d.EndTime, &d.IsOpen); err != nil { defRows.Close() return nil, fmt.Errorf("failed to scan default hours row: %w", err) } defaultMap[d.Weekday] = d } defRows.Close() if err := defRows.Err(); err != nil { return nil, fmt.Errorf("error iterating default hours: %w", err) } // Load staged default hours change (if any) stagedChange := loadScheduledChange(ctx) // Load exceptional applications for Mondays in range startWeekday := int(start.Weekday()) daysSinceMonday := startWeekday - 1 if daysSinceMonday < 0 { daysSinceMonday = 6 } queryStart := start.AddDate(0, 0, -daysSinceMonday) appRows, err := db.Conn.Query(ctx, ` SELECT group_id, week_start FROM exceptional_group_applications WHERE week_start BETWEEN $1 AND $2 `, queryStart, end) if err != nil { return nil, fmt.Errorf("failed to load exceptional applications: %w", err) } type appEntry struct { GroupID int WeekStart time.Time } apps := []appEntry{} groupIDs := []int{} for appRows.Next() { var a appEntry if err := appRows.Scan(&a.GroupID, &a.WeekStart); err != nil { appRows.Close() return nil, fmt.Errorf("failed to scan exceptional application row: %w", err) } a.WeekStart = time.Date(a.WeekStart.Year(), a.WeekStart.Month(), a.WeekStart.Day(), 0, 0, 0, 0, time.UTC) apps = append(apps, a) groupIDs = append(groupIDs, a.GroupID) } appRows.Close() if err := appRows.Err(); err != nil { return nil, fmt.Errorf("error iterating exceptional applications: %w", err) } exHoursMap := map[int]map[int]ExceptionalHours{} if len(groupIDs) > 0 { query, args := sqlIn("SELECT group_id, weekday, start_time::text, end_time, is_open FROM exceptional_working_hours WHERE group_id IN (%s)", groupIDs) rows, err := db.Conn.Query(ctx, query, args...) if err != nil { return nil, fmt.Errorf("failed to load exceptional hours: %w", err) } for rows.Next() { var h ExceptionalHours if err := rows.Scan(&h.GroupID, &h.Weekday, &h.StartTime, &h.EndTime, &h.IsOpen); err != nil { rows.Close() return nil, fmt.Errorf("failed to scan exceptional hours row: %w", err) } if _, ok := exHoursMap[h.GroupID]; !ok { exHoursMap[h.GroupID] = map[int]ExceptionalHours{} } exHoursMap[h.GroupID][h.Weekday] = h } rows.Close() if err := rows.Err(); err != nil { return nil, fmt.Errorf("error iterating exceptional hours: %w", err) } } // Build proposed hours lookup maps proposedByWeekday := map[int]ExceptionalHours{} for _, ph := range params.ProposedHours { proposedByWeekday[ph.Weekday] = ph } proposedWeekSet := map[string]bool{} for _, ws := range params.ProposedWeekStarts { proposedWeekSet[ws] = true } // Load bookings that overlap the query range. bookingRows, err := db.Conn.Query(ctx, ` SELECT b.start_time, b.total_duration_minutes AS total_duration FROM bookings b WHERE b.start_time < $2 AND b.end_time > $1 AND `+ActiveBookingStatuses+` ORDER BY b.start_time `, start, end) if err != nil { return nil, fmt.Errorf("failed to load bookings: %w", err) } bookings := map[string][]TimeSlot{} for bookingRows.Next() { var t time.Time var dur int if err := bookingRows.Scan(&t, &dur); err != nil { bookingRows.Close() return nil, fmt.Errorf("failed to scan booking row: %w", err) } tLondon := t.In(londonLocation) dateStr := tLondon.Format("2006-01-02") endTime := t.Add(time.Duration(dur) * time.Minute) bookings[dateStr] = append(bookings[dateStr], TimeSlot{ StartTime: tLondon.Format("15:04"), EndTime: endTime.In(londonLocation).Format("15:04"), }) } bookingRows.Close() if err := bookingRows.Err(); err != nil { return nil, fmt.Errorf("error iterating bookings: %w", err) } // Load time blockers blockers, err := GetTimeBlockersInRange(ctx, start, end, params.ExcludeUserID) if err != nil { return nil, fmt.Errorf("failed to load time blockers: %w", err) } blockerMap := make(map[string][]TimeSlot) for _, blocker := range blockers { blockStart := blocker.StartTime blockEnd := blockStart.Add(time.Duration(blocker.DurationMinutes) * time.Minute) cur := blockStart for cur.Before(blockEnd) { dayEnd := time.Date(cur.Year(), cur.Month(), cur.Day(), 0, 0, 0, 0, londonLocation).AddDate(0, 0, 1) segEnd := blockEnd if segEnd.After(dayEnd) { segEnd = dayEnd } dateStr := cur.Format("2006-01-02") londonStart := cur.In(londonLocation) londonEnd := segEnd.In(londonLocation) endStr := londonEnd.Format("15:04") if segEnd.Equal(dayEnd) { endStr = "24:00" } blockerMap[dateStr] = append(blockerMap[dateStr], TimeSlot{ StartTime: londonStart.Format("15:04"), EndTime: endStr, }) cur = dayEnd } } // Generate available slots per day var results []DayAvailableHours for d := start; !d.After(end); d = d.AddDate(0, 0, 1) { weekday := int(d.Weekday()) if weekday == 0 { weekday = 6 } else { weekday -= 1 } // Calculate the Monday of this week daysSinceMonday := int(d.Weekday()) - 1 if daysSinceMonday < 0 { daysSinceMonday = 6 } weekStart := d.AddDate(0, 0, -daysSinceMonday) weekStart = time.Date(weekStart.Year(), weekStart.Month(), weekStart.Day(), 0, 0, 0, 0, time.UTC) var applied *ExceptionalHours weekStartStr := weekStart.Format("2006-01-02") for _, a := range apps { appWeekStartStr := a.WeekStart.Format("2006-01-02") if appWeekStartStr == weekStartStr { if dayHours, ok := exHoursMap[a.GroupID][weekday]; ok { applied = &dayHours } break } } var day DayAvailableHours day.Date = d.Format("2006-01-02") day.Weekday = weekday var baseStart, baseEnd string var isOpen bool // Proposed hours override (what-if simulation for preview) if proposedWeekSet[weekStartStr] { if ph, ok := proposedByWeekday[weekday]; ok { baseStart = ph.StartTime baseEnd = ph.EndTime isOpen = ph.IsOpen day.Source = "proposed" } else if applied != nil { baseStart = applied.StartTime baseEnd = applied.EndTime isOpen = applied.IsOpen day.Source = "exceptional" } else if def, ok := defaultMap[weekday]; ok { baseStart = def.StartTime baseEnd = def.EndTime isOpen = def.IsOpen day.Source = "default" } else { baseStart = "00:00" baseEnd = "00:00" isOpen = false day.Source = "default" } } else if applied != nil { baseStart = applied.StartTime baseEnd = applied.EndTime isOpen = applied.IsOpen day.Source = "exceptional" } else if stagedChange != nil && d.Format("2006-01-02") >= stagedChange.EffectiveDate { for _, sh := range stagedChange.Hours { if sh.Weekday == weekday { baseStart = sh.StartTime baseEnd = sh.EndTime isOpen = sh.IsOpen day.Source = "default" break } } } else if def, ok := defaultMap[weekday]; ok { baseStart = def.StartTime baseEnd = def.EndTime isOpen = def.IsOpen day.Source = "default" } else { baseStart = "00:00" baseEnd = "00:00" isOpen = false day.Source = "default" } // Out-of-hours override for admin if params.OutOfHours && params.IsAdmin { baseStart = "06:00" baseEnd = "22:00" isOpen = true day.Source = "out_of_hours" } day.IsOpen = isOpen if isOpen { baseStart = normalizeTime(baseStart) baseEnd = normalizeTime(baseEnd) slots := []TimeSlot{{StartTime: baseStart, EndTime: baseEnd}} if booked, ok := bookings[day.Date]; ok { slots = subtractTimeSlots(slots, booked) } day.Slots = slots if dayBlockers, ok := blockerMap[day.Date]; ok { day.Slots = subtractTimeSlots(day.Slots, dayBlockers) if params.IsAdmin { day.Blockers = dayBlockers } } // Late night lock: after 22:00, block next morning 00:00-11:00 for non-admin users if !params.IsAdmin { now := clock.Now() londonNow := now.In(londonLocation) if londonNow.Hour() >= 22 { tomorrow := now.AddDate(0, 0, 1) tomorrowStr := tomorrow.Format("2006-01-02") if day.Date == tomorrowStr { lateNightBlock := TimeSlot{ StartTime: "00:00", EndTime: "11:00", } day.Slots = subtractTimeSlots(day.Slots, []TimeSlot{lateNightBlock}) } } } } else { day.Slots = []TimeSlot{} } results = append(results, day) } return results, nil } // normalizeTime strips seconds from HH:MM:SS to HH:MM for consistent string // comparison with blocker and booking time formats in subtractTimeSlots. func normalizeTime(t string) string { parts := strings.Split(t, ":") if len(parts) < 2 { return t } hour := parts[0] minute := parts[1] // Only pad numeric single-digit segments. Non-numeric single-char // values (e.g. from garbage input) pass through without padding. if len(hour) == 1 && hour[0] >= '0' && hour[0] <= '9' { hour = "0" + hour } if len(minute) == 1 && minute[0] >= '0' && minute[0] <= '9' { minute = "0" + minute } return hour + ":" + minute } // subtractTimeSlots removes gaps from available slots // Returns the remaining available time slots after removing the gaps func subtractTimeSlots(available []TimeSlot, gaps []TimeSlot) []TimeSlot { if len(gaps) == 0 { return available } result := []TimeSlot{} for _, slot := range available { current := []TimeSlot{slot} // Apply each gap for _, gap := range gaps { var temp []TimeSlot for _, s := range current { // Check if gap overlaps with this slot if gap.EndTime <= s.StartTime || gap.StartTime >= s.EndTime { // No overlap, keep the slot as is temp = append(temp, s) } else { // Overlap exists, split the slot if s.StartTime < gap.StartTime { // Keep the part before the gap temp = append(temp, TimeSlot{ StartTime: s.StartTime, EndTime: gap.StartTime, }) } if gap.EndTime < s.EndTime { // Keep the part after the gap temp = append(temp, TimeSlot{ StartTime: gap.EndTime, EndTime: s.EndTime, }) } } } current = temp } result = append(result, current...) } return result } // --- GetPreviewAvailableHours (with proposed hours what-if simulation) --- func GetPreviewAvailableHours(w http.ResponseWriter, r *http.Request) { startStr := r.URL.Query().Get("start") endStr := r.URL.Query().Get("end") if startStr == "" || endStr == "" { http.Error(w, "start and end query params required", http.StatusBadRequest) return } startDate, err := time.Parse("2006-01-02", startStr) if err != nil { http.Error(w, "invalid start date", http.StatusBadRequest) return } endDate, err := time.Parse("2006-01-02", endStr) if err != nil { http.Error(w, "invalid end date", http.StatusBadRequest) return } outOfHours := r.URL.Query().Get("out_of_hours") == "true" // Parse proposed hours and weeks (what-if simulation) var proposedHours []ExceptionalHours if phStr := r.URL.Query().Get("proposed_hours"); phStr != "" { if err := json.Unmarshal([]byte(phStr), &proposedHours); err != nil { http.Error(w, "invalid proposed_hours JSON", http.StatusBadRequest) return } } var proposedWeekStarts []string if pwStr := r.URL.Query().Get("proposed_weeks"); pwStr != "" { if err := json.Unmarshal([]byte(pwStr), &proposedWeekStarts); err != nil { http.Error(w, "invalid proposed_weeks JSON", http.StatusBadRequest) return } } isAdmin := false if userRole, ok := r.Context().Value(mw.UserRoleKey).(string); ok { isAdmin = userRole == "admin" } var excludeUserID *string if uid, ok := r.Context().Value(mw.UserIDKey).(string); ok && uid != "" { excludeUserID = &uid } startLondon := time.Date(startDate.Year(), startDate.Month(), startDate.Day(), 0, 0, 0, 0, londonLocation) endLondon := time.Date(endDate.Year(), endDate.Month(), endDate.Day(), 23, 59, 59, 999999999, londonLocation) results, err := computeAvailableHours(r.Context(), availableHoursParams{ Start: startLondon, End: endLondon, OutOfHours: outOfHours, IsAdmin: isAdmin, ExcludeUserID: excludeUserID, ProposedHours: proposedHours, ProposedWeekStarts: proposedWeekStarts, }) if err != nil { log.Printf("Failed to compute preview available hours: %v", err) http.Error(w, "Internal server error", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(results); err != nil { log.Printf("Failed to encode JSON response: %v", err) } } // --- Staged Default Hours Change Handlers --- // GetDefaultHoursConflictingBookings checks which active bookings would conflict // with proposed default hours if they take effect from a given date. func GetDefaultHoursConflictingBookings(w http.ResponseWriter, r *http.Request) { var req struct { ProposedHours []ExceptionalHours `json:"proposedHours" validate:"required,len=7,dive"` EffectiveDate string `json:"effective_date" validate:"required"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { mw.RespondError(w, http.StatusBadRequest, "invalid request body") return } if len(req.ProposedHours) != 7 { http.Error(w, "must provide exactly 7 weekday entries (0-6)", http.StatusBadRequest) return } effDate, err := time.Parse("2006-01-02", req.EffectiveDate) if err != nil { http.Error(w, "invalid effective_date format, expected YYYY-MM-DD", http.StatusBadRequest) return } // Build proposedByWeekday map proposedByWeekday := map[int]ExceptionalHours{} for _, h := range req.ProposedHours { proposedByWeekday[h.Weekday] = h } // Query range: effective date to 90 days out rangeStart := time.Date(effDate.Year(), effDate.Month(), effDate.Day(), 0, 0, 0, 0, londonLocation) rangeEnd := rangeStart.AddDate(0, 0, 90) rows, err := db.Conn.Query(r.Context(), ` SELECT b.id, b.start_time, b.status, b.created_at, b.total_duration_minutes as duration, COALESCE(u.id, '') as user_id, COALESCE(u.fn, '') as full_name, u.email, u.phone FROM bookings b LEFT JOIN users u ON b.user_id = u.id WHERE `+ActiveBookingStatuses+` AND b.start_time < $2 AND b.end_time > $1 ORDER BY b.start_time `, rangeStart, rangeEnd) if err != nil { log.Printf("Failed to query conflicting bookings: %v", err) http.Error(w, "Internal server error", http.StatusInternalServerError) return } defer rows.Close() allConflicts := []OverlappingBooking{} for rows.Next() { var ob OverlappingBooking ob.User = &UserSummary{} if err := rows.Scan(&ob.ID, &ob.StartTime, &ob.Status, &ob.CreatedAt, &ob.Duration, &ob.User.ID, &ob.User.FullName, &ob.User.Email, &ob.User.Phone); err != nil { log.Printf("Failed to scan conflicting booking: %v", err) continue } bookingLondon := ob.StartTime.In(londonLocation) ourWeekday := int((bookingLondon.Weekday() + 6) % 7) proposed, _ := proposedByWeekday[ourWeekday] isConflict := false if !proposed.IsOpen { isConflict = true } else { startMinutes := bookingLondon.Hour()*60 + bookingLondon.Minute() endLondon := ob.StartTime.Add(time.Duration(ob.Duration) * time.Minute).In(londonLocation) endMinutes := endLondon.Hour()*60 + endLondon.Minute() propStart := parseTimeToMinutes(proposed.StartTime) propEnd := parseTimeToMinutes(proposed.EndTime) if endMinutes < startMinutes { isConflict = true } else if startMinutes < propStart || endMinutes > propEnd { isConflict = true } } if isConflict { allConflicts = append(allConflicts, ob) } } if err := rows.Err(); err != nil { log.Printf("Error iterating conflicting bookings: %v", err) http.Error(w, "Internal server error", http.StatusInternalServerError) return } // Batch-load services if len(allConflicts) > 0 { ids := make([]string, len(allConflicts)) for i, ob := range allConflicts { ids[i] = ob.ID } serviceRows, err := db.Conn.Query(r.Context(), ` SELECT booking_id, name FROM ( SELECT bs.booking_id, s.name FROM booking_services bs JOIN services s ON bs.service_id = s.id WHERE bs.booking_id = ANY($1) UNION ALL SELECT bcs.booking_id, cs.name FROM booking_custom_services bcs JOIN custom_services cs ON bcs.custom_service_id = cs.id WHERE bcs.booking_id = ANY($1) ) sub ORDER BY booking_id, name `, ids) if err != nil { log.Printf("Failed to batch-load services: %v", err) } else { serviceMap := map[string][]string{} for serviceRows.Next() { var bookingID, name string if serviceRows.Scan(&bookingID, &name) == nil { serviceMap[bookingID] = append(serviceMap[bookingID], name) } } serviceRows.Close() for i, ob := range allConflicts { allConflicts[i].Services = serviceMap[ob.ID] } } } if allConflicts == nil { allConflicts = []OverlappingBooking{} } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(OverlappingBookingsResponse{Bookings: allConflicts}) } // ScheduleDefaultHoursChange creates a staged default hours change. func ScheduleDefaultHoursChange(w http.ResponseWriter, r *http.Request) { var req struct { Hours []DefaultHours `json:"hours" validate:"required,len=7,dive"` EffectiveDate string `json:"effective_date" validate:"required"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { mw.RespondError(w, http.StatusBadRequest, "invalid request body") return } // Validate effective_date is in the future effDate, err := time.Parse("2006-01-02", req.EffectiveDate) if err != nil { http.Error(w, "invalid effective_date format, expected YYYY-MM-DD", http.StatusBadRequest) return } // Convert to London timezone so comparison with today is DST-safe // (time.Parse yields UTC midnight, but London midnight may differ by 1h during BST). effDate = time.Date(effDate.Year(), effDate.Month(), effDate.Day(), 0, 0, 0, 0, londonLocation) londonNow := clock.Now().In(londonLocation) today := time.Date(londonNow.Year(), londonNow.Month(), londonNow.Day(), 0, 0, 0, 0, londonLocation) if !effDate.After(today) { http.Error(w, "effective_date must be tomorrow or later", http.StatusBadRequest) return } // Check there isn't already a pending change var existingID int err = db.Conn.QueryRow(r.Context(), ` SELECT id FROM default_hours_scheduled_changes WHERE applied_at IS NULL AND cancelled_at IS NULL LIMIT 1 `).Scan(&existingID) if err == nil { http.Error(w, "A pending default hours change already exists. Cancel it first.", http.StatusConflict) return } // Each hour entry must pass validation for _, h := range req.Hours { if err := validators.Validate.Struct(&h); err != nil { mw.RespondError(w, http.StatusBadRequest, "Invalid hours data") return } } // Get admin user ID from context adminID, _ := r.Context().Value(mw.UserIDKey).(string) hoursBytes, err := json.Marshal(req.Hours) if err != nil { http.Error(w, "failed to serialize hours", http.StatusInternalServerError) return } _, err = db.Conn.Exec(r.Context(), ` INSERT INTO default_hours_scheduled_changes (effective_date, created_by, hours) VALUES ($1, $2, $3) `, effDate, adminID, string(hoursBytes)) if err != nil { log.Printf("Failed to insert scheduled change: %v", err) http.Error(w, "Failed to schedule change", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{ "effective_date": req.EffectiveDate, "message": "Default hours will change at 23:59 on " + effDate.In(londonLocation).Format("02/01/2006"), }) } // GetScheduledDefaultHoursChange returns the pending change, if any. func GetScheduledDefaultHoursChange(w http.ResponseWriter, r *http.Request) { var effDate, createdAt, createdBy *string var hoursJSON *string err := db.Conn.QueryRow(r.Context(), ` SELECT effective_date::text, created_at::text, created_by, hours::text FROM default_hours_scheduled_changes WHERE applied_at IS NULL AND cancelled_at IS NULL LIMIT 1 `).Scan(&effDate, &createdAt, &createdBy, &hoursJSON) if err != nil || effDate == nil || hoursJSON == nil { http.Error(w, "no pending change", http.StatusNotFound) return } var scheduledHours []DefaultHours json.Unmarshal([]byte(*hoursJSON), &scheduledHours) resp := ScheduledHoursChange{ EffectiveDate: *effDate, Hours: scheduledHours, CreatedAt: *createdAt, CreatedBy: *createdBy, } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(resp) } // CancelScheduledDefaultHoursChange cancels a pending change. func CancelScheduledDefaultHoursChange(w http.ResponseWriter, r *http.Request) { result, err := db.Conn.Exec(r.Context(), ` UPDATE default_hours_scheduled_changes SET cancelled_at = NOW() WHERE applied_at IS NULL AND cancelled_at IS NULL `) if err != nil { log.Printf("Failed to cancel scheduled change: %v", err) http.Error(w, "Failed to cancel", http.StatusInternalServerError) return } if result.RowsAffected() == 0 { http.Error(w, "no pending change to cancel", http.StatusNotFound) return } w.WriteHeader(http.StatusNoContent) }