Extract computeAvailableHours as shared core between GetAvailableHours and GetPreviewAvailableHours, eliminating ~320 lines of duplication. Add GetConflictingBookingsForExceptionHandler (POST) for holiday hours conflict detection with batch service loading, int-based time comparison, and ActiveBookingStatuses constant. Add RESERVATION:placeholder cleanup (24h TTL). Fix scan error propagation in all scheduling row iterations. Add rows.Err() checks.
904 lines
26 KiB
Go
904 lines
26 KiB
Go
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"
|
|
}
|
|
|
|
// --- 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 {
|
|
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 {
|
|
http.Error(w, "failed to scan default hours", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
hours = append(hours, h)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
http.Error(w, "error iterating default hours", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
if err := json.NewEncoder(w).Encode(hours); 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 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 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 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 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)
|
|
}
|
|
}
|