feat: add holiday hours conflict detection with shared scheduling core
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.
This commit is contained in:
@@ -79,10 +79,16 @@ func GetContactAvailability(w http.ResponseWriter, r *http.Request) {
|
|||||||
var b bookingInfo
|
var b bookingInfo
|
||||||
if err := rows.Scan(&b.StartTime, &b.DurationMinutes, &b.Status); err != nil {
|
if err := rows.Scan(&b.StartTime, &b.DurationMinutes, &b.Status); err != nil {
|
||||||
log.Printf("Failed to scan booking for contact-availability: %v", err)
|
log.Printf("Failed to scan booking for contact-availability: %v", err)
|
||||||
continue
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
bookings = append(bookings, b)
|
bookings = append(bookings, b)
|
||||||
}
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
log.Printf("Error iterating bookings for contact-availability: %v", err)
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
for _, b := range bookings {
|
for _, b := range bookings {
|
||||||
if b.Status != "in_progress" {
|
if b.Status != "in_progress" {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package scheduling
|
package scheduling
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -21,6 +22,12 @@ import (
|
|||||||
|
|
||||||
var londonLocation = clock.London
|
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 ---
|
// --- Types ---
|
||||||
type DefaultHours struct {
|
type DefaultHours struct {
|
||||||
Weekday int `json:"weekday" validate:"gte=0,lte=6"`
|
Weekday int `json:"weekday" validate:"gte=0,lte=6"`
|
||||||
@@ -59,6 +66,10 @@ func GetDefaultHours(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
hours = append(hours, h)
|
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")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
if err := json.NewEncoder(w).Encode(hours); err != nil {
|
if err := json.NewEncoder(w).Encode(hours); err != nil {
|
||||||
@@ -178,17 +189,31 @@ func GetWorkingHours(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
// Load default hours
|
// Load default hours
|
||||||
defaultMap := map[int]DefaultHours{}
|
defaultMap := map[int]DefaultHours{}
|
||||||
defRows, _ := db.Conn.Query(r.Context(), `
|
defRows, err := db.Conn.Query(r.Context(), `
|
||||||
SELECT weekday, start_time::text, end_time, is_open
|
SELECT weekday, start_time::text, end_time, is_open
|
||||||
FROM working_hours
|
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() {
|
for defRows.Next() {
|
||||||
var d DefaultHours
|
var d DefaultHours
|
||||||
if err := defRows.Scan(&d.Weekday, &d.StartTime, &d.EndTime, &d.IsOpen); err == nil {
|
if err := defRows.Scan(&d.Weekday, &d.StartTime, &d.EndTime, &d.IsOpen); err != nil {
|
||||||
defaultMap[d.Weekday] = d
|
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()
|
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
|
// Load exceptional applications for Mondays in range
|
||||||
// Expand start to the Monday of its week so single-day queries still find the correct application
|
// Expand start to the Monday of its week so single-day queries still find the correct application
|
||||||
@@ -199,11 +224,16 @@ func GetWorkingHours(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
queryStart := start.AddDate(0, 0, -daysSinceMonday)
|
queryStart := start.AddDate(0, 0, -daysSinceMonday)
|
||||||
|
|
||||||
appRows, _ := db.Conn.Query(r.Context(), `
|
appRows, err := db.Conn.Query(r.Context(), `
|
||||||
SELECT group_id, week_start
|
SELECT group_id, week_start
|
||||||
FROM exceptional_group_applications
|
FROM exceptional_group_applications
|
||||||
WHERE week_start BETWEEN $1 AND $2
|
WHERE week_start BETWEEN $1 AND $2
|
||||||
`, queryStart, end)
|
`, 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 {
|
type appEntry struct {
|
||||||
GroupID int
|
GroupID int
|
||||||
WeekStart time.Time
|
WeekStart time.Time
|
||||||
@@ -212,28 +242,51 @@ func GetWorkingHours(w http.ResponseWriter, r *http.Request) {
|
|||||||
groupIDs := []int{}
|
groupIDs := []int{}
|
||||||
for appRows.Next() {
|
for appRows.Next() {
|
||||||
var a appEntry
|
var a appEntry
|
||||||
if err := appRows.Scan(&a.GroupID, &a.WeekStart); err == nil {
|
if err := appRows.Scan(&a.GroupID, &a.WeekStart); err != nil {
|
||||||
a.WeekStart = time.Date(a.WeekStart.Year(), a.WeekStart.Month(), a.WeekStart.Day(), 0, 0, 0, 0, time.UTC)
|
appRows.Close()
|
||||||
apps = append(apps, a)
|
log.Printf("Failed to scan exceptional application row: %v", err)
|
||||||
groupIDs = append(groupIDs, a.GroupID)
|
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()
|
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{}
|
exHoursMap := map[int]map[int]ExceptionalHours{}
|
||||||
if len(groupIDs) > 0 {
|
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)
|
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, _ := db.Conn.Query(r.Context(), query, args...)
|
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() {
|
for rows.Next() {
|
||||||
var h ExceptionalHours
|
var h ExceptionalHours
|
||||||
if err := rows.Scan(&h.GroupID, &h.Weekday, &h.StartTime, &h.EndTime, &h.IsOpen); err == nil {
|
if err := rows.Scan(&h.GroupID, &h.Weekday, &h.StartTime, &h.EndTime, &h.IsOpen); err != nil {
|
||||||
if _, ok := exHoursMap[h.GroupID]; !ok {
|
rows.Close()
|
||||||
exHoursMap[h.GroupID] = map[int]ExceptionalHours{}
|
log.Printf("Failed to scan exceptional hours row: %v", err)
|
||||||
}
|
http.Error(w, "Failed to read exceptional hours", http.StatusInternalServerError)
|
||||||
exHoursMap[h.GroupID][h.Weekday] = h
|
return
|
||||||
}
|
}
|
||||||
|
if _, ok := exHoursMap[h.GroupID]; !ok {
|
||||||
|
exHoursMap[h.GroupID] = map[int]ExceptionalHours{}
|
||||||
|
}
|
||||||
|
exHoursMap[h.GroupID][h.Weekday] = h
|
||||||
}
|
}
|
||||||
rows.Close()
|
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
|
// Generate final result per day
|
||||||
@@ -321,7 +374,7 @@ func isValidTime15Min(t string) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// --- helper: sqlIn generates IN queries dynamically for Postgres ---
|
// --- helper: sqlIn generates IN queries dynamically for Postgres ---
|
||||||
func sqlIn(query string, args []int) (string, []any, error) {
|
func sqlIn(query string, args []int) (string, []any) {
|
||||||
inArgs := []any{}
|
inArgs := []any{}
|
||||||
var placeholders strings.Builder
|
var placeholders strings.Builder
|
||||||
for i, arg := range args {
|
for i, arg := range args {
|
||||||
@@ -332,7 +385,7 @@ func sqlIn(query string, args []int) (string, []any, error) {
|
|||||||
inArgs = append(inArgs, arg)
|
inArgs = append(inArgs, arg)
|
||||||
}
|
}
|
||||||
query = fmt.Sprintf(query, placeholders.String())
|
query = fmt.Sprintf(query, placeholders.String())
|
||||||
return query, inArgs, nil
|
return query, inArgs
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Types for Available Hours ---
|
// --- Types for Available Hours ---
|
||||||
@@ -350,6 +403,17 @@ type DayAvailableHours struct {
|
|||||||
Blockers []TimeSlot `json:"blockers,omitempty"`
|
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) ---
|
// --- GetAvailableHours (with bookings, UK-local) ---
|
||||||
func GetAvailableHours(w http.ResponseWriter, r *http.Request) {
|
func GetAvailableHours(w http.ResponseWriter, r *http.Request) {
|
||||||
startStr := r.URL.Query().Get("start")
|
startStr := r.URL.Query().Get("start")
|
||||||
@@ -358,41 +422,95 @@ func GetAvailableHours(w http.ResponseWriter, r *http.Request) {
|
|||||||
http.Error(w, "start and end query params required", http.StatusBadRequest)
|
http.Error(w, "start and end query params required", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
start, _ := time.Parse("2006-01-02", startStr)
|
start, err := time.Parse("2006-01-02", startStr)
|
||||||
end, _ := time.Parse("2006-01-02", endStr)
|
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"
|
outOfHours := r.URL.Query().Get("out_of_hours") == "true"
|
||||||
|
|
||||||
// set start/end of day in Europe/London (see comment above)
|
isAdmin := false
|
||||||
start = time.Date(start.Year(), start.Month(), start.Day(), 0, 0, 0, 0, londonLocation)
|
if userRole, ok := r.Context().Value(mw.UserRoleKey).(string); ok {
|
||||||
end = time.Date(end.Year(), end.Month(), end.Day(), 23, 59, 59, 999999999, londonLocation)
|
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
|
// Load default hours
|
||||||
defaultMap := map[int]DefaultHours{}
|
defaultMap := map[int]DefaultHours{}
|
||||||
defRows, _ := db.Conn.Query(r.Context(), `SELECT weekday, start_time::text, end_time, is_open FROM working_hours`)
|
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() {
|
for defRows.Next() {
|
||||||
var d DefaultHours
|
var d DefaultHours
|
||||||
if err := defRows.Scan(&d.Weekday, &d.StartTime, &d.EndTime, &d.IsOpen); err == nil {
|
if err := defRows.Scan(&d.Weekday, &d.StartTime, &d.EndTime, &d.IsOpen); err != nil {
|
||||||
defaultMap[d.Weekday] = d
|
defRows.Close()
|
||||||
|
return nil, fmt.Errorf("failed to scan default hours row: %w", err)
|
||||||
}
|
}
|
||||||
|
defaultMap[d.Weekday] = d
|
||||||
}
|
}
|
||||||
defRows.Close()
|
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
|
// 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())
|
startWeekday := int(start.Weekday())
|
||||||
daysSinceMonday := startWeekday - 1
|
daysSinceMonday := startWeekday - 1
|
||||||
if daysSinceMonday < 0 {
|
if daysSinceMonday < 0 {
|
||||||
daysSinceMonday = 6 // Sunday
|
daysSinceMonday = 6
|
||||||
}
|
}
|
||||||
queryStart := start.AddDate(0, 0, -daysSinceMonday)
|
queryStart := start.AddDate(0, 0, -daysSinceMonday)
|
||||||
|
|
||||||
appRows, _ := db.Conn.Query(r.Context(), `
|
appRows, err := db.Conn.Query(ctx, `
|
||||||
SELECT group_id, week_start
|
SELECT group_id, week_start
|
||||||
FROM exceptional_group_applications
|
FROM exceptional_group_applications
|
||||||
WHERE week_start BETWEEN $1 AND $2
|
WHERE week_start BETWEEN $1 AND $2
|
||||||
`, queryStart, end)
|
`, queryStart, end)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to load exceptional applications: %w", err)
|
||||||
|
}
|
||||||
type appEntry struct {
|
type appEntry struct {
|
||||||
GroupID int
|
GroupID int
|
||||||
WeekStart time.Time
|
WeekStart time.Time
|
||||||
@@ -401,83 +519,100 @@ func GetAvailableHours(w http.ResponseWriter, r *http.Request) {
|
|||||||
groupIDs := []int{}
|
groupIDs := []int{}
|
||||||
for appRows.Next() {
|
for appRows.Next() {
|
||||||
var a appEntry
|
var a appEntry
|
||||||
if err := appRows.Scan(&a.GroupID, &a.WeekStart); err == nil {
|
if err := appRows.Scan(&a.GroupID, &a.WeekStart); err != nil {
|
||||||
a.WeekStart = time.Date(a.WeekStart.Year(), a.WeekStart.Month(), a.WeekStart.Day(), 0, 0, 0, 0, time.UTC)
|
appRows.Close()
|
||||||
apps = append(apps, a)
|
return nil, fmt.Errorf("failed to scan exceptional application row: %w", err)
|
||||||
groupIDs = append(groupIDs, a.GroupID)
|
|
||||||
}
|
}
|
||||||
|
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()
|
appRows.Close()
|
||||||
|
if err := appRows.Err(); err != nil {
|
||||||
|
return nil, fmt.Errorf("error iterating exceptional applications: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
exHoursMap := map[int]map[int]ExceptionalHours{}
|
exHoursMap := map[int]map[int]ExceptionalHours{}
|
||||||
if len(groupIDs) > 0 {
|
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)
|
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, _ := db.Conn.Query(r.Context(), query, args...)
|
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() {
|
for rows.Next() {
|
||||||
var h ExceptionalHours
|
var h ExceptionalHours
|
||||||
if err := rows.Scan(&h.GroupID, &h.Weekday, &h.StartTime, &h.EndTime, &h.IsOpen); err == nil {
|
if err := rows.Scan(&h.GroupID, &h.Weekday, &h.StartTime, &h.EndTime, &h.IsOpen); err != nil {
|
||||||
if _, ok := exHoursMap[h.GroupID]; !ok {
|
rows.Close()
|
||||||
exHoursMap[h.GroupID] = map[int]ExceptionalHours{}
|
return nil, fmt.Errorf("failed to scan exceptional hours row: %w", err)
|
||||||
}
|
|
||||||
exHoursMap[h.GroupID][h.Weekday] = h
|
|
||||||
}
|
}
|
||||||
|
if _, ok := exHoursMap[h.GroupID]; !ok {
|
||||||
|
exHoursMap[h.GroupID] = map[int]ExceptionalHours{}
|
||||||
|
}
|
||||||
|
exHoursMap[h.GroupID][h.Weekday] = h
|
||||||
}
|
}
|
||||||
rows.Close()
|
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.
|
// Load bookings that overlap the query range.
|
||||||
// Must catch bookings that STARTED before the range but EXTEND INTO it
|
bookingRows, err := db.Conn.Query(ctx, `
|
||||||
// (e.g. a booking at 23:00 the previous day lasting 120min crosses midnight).
|
|
||||||
// Use the same overlap condition as the booking creation handlers.
|
|
||||||
bookingRows, _ := db.Conn.Query(r.Context(), `
|
|
||||||
SELECT
|
SELECT
|
||||||
b.start_time,
|
b.start_time,
|
||||||
b.total_duration_minutes AS total_duration
|
b.total_duration_minutes AS total_duration
|
||||||
FROM bookings b
|
FROM bookings b
|
||||||
WHERE b.start_time < $2
|
WHERE b.start_time < $2
|
||||||
AND b.end_time > $1
|
AND b.end_time > $1
|
||||||
AND b.status NOT IN ('client_cancelled', 'we_cancelled', 'no_show', 'pending_release', 'deposit_lapsed')
|
AND `+ActiveBookingStatuses+`
|
||||||
ORDER BY b.start_time
|
ORDER BY b.start_time
|
||||||
`, start, end)
|
`, start, end)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to load bookings: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
bookings := map[string][]TimeSlot{}
|
bookings := map[string][]TimeSlot{}
|
||||||
for bookingRows.Next() {
|
for bookingRows.Next() {
|
||||||
var t time.Time
|
var t time.Time
|
||||||
var dur int
|
var dur int
|
||||||
if err := bookingRows.Scan(&t, &dur); err == nil {
|
if err := bookingRows.Scan(&t, &dur); err != nil {
|
||||||
tLondon := t.In(londonLocation)
|
bookingRows.Close()
|
||||||
dateStr := tLondon.Format("2006-01-02")
|
return nil, fmt.Errorf("failed to scan booking row: %w", err)
|
||||||
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"),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
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()
|
bookingRows.Close()
|
||||||
|
if err := bookingRows.Err(); err != nil {
|
||||||
|
return nil, fmt.Errorf("error iterating bookings: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
// Load time blockers, excluding the current user's own RESERVATION entries
|
// Load time blockers
|
||||||
// so their existing reservation doesn't hide the slot from them
|
blockers, err := GetTimeBlockersInRange(ctx, start, end, params.ExcludeUserID)
|
||||||
var excludeUserID *string
|
|
||||||
if uid, ok := r.Context().Value(mw.UserIDKey).(string); ok && uid != "" {
|
|
||||||
excludeUserID = &uid
|
|
||||||
}
|
|
||||||
blockers, err := GetTimeBlockersInRange(r.Context(), start, end, excludeUserID)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Failed to load time blockers: %v", err)
|
return nil, fmt.Errorf("failed to load time blockers: %w", err)
|
||||||
}
|
}
|
||||||
// Convert blockers to map by date for easier lookup
|
|
||||||
|
|
||||||
blockerMap := make(map[string][]TimeSlot)
|
blockerMap := make(map[string][]TimeSlot)
|
||||||
|
|
||||||
for _, blocker := range blockers {
|
for _, blocker := range blockers {
|
||||||
blockStart := blocker.StartTime
|
blockStart := blocker.StartTime
|
||||||
blockEnd := blockStart.Add(time.Duration(blocker.DurationMinutes) * time.Minute)
|
blockEnd := blockStart.Add(time.Duration(blocker.DurationMinutes) * time.Minute)
|
||||||
|
|
||||||
// Split multi-day blockers into per-day segments so subtractTimeSlots
|
|
||||||
// only compares times within the same calendar day. Each segment's end
|
|
||||||
// time uses "24:00" for day boundaries (midnight of the next day) since
|
|
||||||
// "00:00" as an end time would incorrectly appear before all slot times.
|
|
||||||
cur := blockStart
|
cur := blockStart
|
||||||
for cur.Before(blockEnd) {
|
for cur.Before(blockEnd) {
|
||||||
dayEnd := time.Date(cur.Year(), cur.Month(), cur.Day(), 0, 0, 0, 0, londonLocation).AddDate(0, 0, 1)
|
dayEnd := time.Date(cur.Year(), cur.Month(), cur.Day(), 0, 0, 0, 0, londonLocation).AddDate(0, 0, 1)
|
||||||
@@ -487,8 +622,6 @@ func GetAvailableHours(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dateStr := cur.Format("2006-01-02")
|
dateStr := cur.Format("2006-01-02")
|
||||||
// Format times in Europe/London so that blocker time strings use
|
|
||||||
// wall-clock hours matching working_hours and booking slots.
|
|
||||||
londonStart := cur.In(londonLocation)
|
londonStart := cur.In(londonLocation)
|
||||||
londonEnd := segEnd.In(londonLocation)
|
londonEnd := segEnd.In(londonLocation)
|
||||||
endStr := londonEnd.Format("15:04")
|
endStr := londonEnd.Format("15:04")
|
||||||
@@ -504,12 +637,6 @@ func GetAvailableHours(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if user is admin
|
|
||||||
isAdmin := false
|
|
||||||
if userRole, ok := r.Context().Value(mw.UserRoleKey).(string); ok {
|
|
||||||
isAdmin = userRole == "admin"
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate available slots per day
|
// Generate available slots per day
|
||||||
var results []DayAvailableHours
|
var results []DayAvailableHours
|
||||||
for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {
|
for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {
|
||||||
@@ -523,7 +650,7 @@ func GetAvailableHours(w http.ResponseWriter, r *http.Request) {
|
|||||||
// Calculate the Monday of this week
|
// Calculate the Monday of this week
|
||||||
daysSinceMonday := int(d.Weekday()) - 1
|
daysSinceMonday := int(d.Weekday()) - 1
|
||||||
if daysSinceMonday < 0 {
|
if daysSinceMonday < 0 {
|
||||||
daysSinceMonday = 6 // Sunday
|
daysSinceMonday = 6
|
||||||
}
|
}
|
||||||
weekStart := d.AddDate(0, 0, -daysSinceMonday)
|
weekStart := d.AddDate(0, 0, -daysSinceMonday)
|
||||||
weekStart = time.Date(weekStart.Year(), weekStart.Month(), weekStart.Day(), 0, 0, 0, 0, time.UTC)
|
weekStart = time.Date(weekStart.Year(), weekStart.Month(), weekStart.Day(), 0, 0, 0, 0, time.UTC)
|
||||||
@@ -546,7 +673,31 @@ func GetAvailableHours(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
var baseStart, baseEnd string
|
var baseStart, baseEnd string
|
||||||
var isOpen bool
|
var isOpen bool
|
||||||
if applied != nil {
|
|
||||||
|
// 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
|
baseStart = applied.StartTime
|
||||||
baseEnd = applied.EndTime
|
baseEnd = applied.EndTime
|
||||||
isOpen = applied.IsOpen
|
isOpen = applied.IsOpen
|
||||||
@@ -564,7 +715,7 @@ func GetAvailableHours(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Out-of-hours override for admin
|
// Out-of-hours override for admin
|
||||||
if outOfHours && isAdmin {
|
if params.OutOfHours && params.IsAdmin {
|
||||||
baseStart = "06:00"
|
baseStart = "06:00"
|
||||||
baseEnd = "22:00"
|
baseEnd = "22:00"
|
||||||
isOpen = true
|
isOpen = true
|
||||||
@@ -573,7 +724,6 @@ func GetAvailableHours(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
day.IsOpen = isOpen
|
day.IsOpen = isOpen
|
||||||
if isOpen {
|
if isOpen {
|
||||||
// Normalize to HH:MM to match blocker and booking time formats
|
|
||||||
baseStart = normalizeTime(baseStart)
|
baseStart = normalizeTime(baseStart)
|
||||||
baseEnd = normalizeTime(baseEnd)
|
baseEnd = normalizeTime(baseEnd)
|
||||||
slots := []TimeSlot{{StartTime: baseStart, EndTime: baseEnd}}
|
slots := []TimeSlot{{StartTime: baseStart, EndTime: baseEnd}}
|
||||||
@@ -581,26 +731,21 @@ func GetAvailableHours(w http.ResponseWriter, r *http.Request) {
|
|||||||
slots = subtractTimeSlots(slots, booked)
|
slots = subtractTimeSlots(slots, booked)
|
||||||
}
|
}
|
||||||
day.Slots = slots
|
day.Slots = slots
|
||||||
// Subtract time blockers from available slots for ALL users
|
|
||||||
// (prevents showing blocked slots that would fail on reserve)
|
|
||||||
if dayBlockers, ok := blockerMap[day.Date]; ok {
|
if dayBlockers, ok := blockerMap[day.Date]; ok {
|
||||||
day.Slots = subtractTimeSlots(day.Slots, dayBlockers)
|
day.Slots = subtractTimeSlots(day.Slots, dayBlockers)
|
||||||
// Store blockers separately for admin warning display
|
if params.IsAdmin {
|
||||||
if isAdmin {
|
|
||||||
day.Blockers = dayBlockers
|
day.Blockers = dayBlockers
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Late night lock: after 22:00, block next morning 00:00-11:00 for non-admin users
|
// Late night lock: after 22:00, block next morning 00:00-11:00 for non-admin users
|
||||||
if !isAdmin {
|
if !params.IsAdmin {
|
||||||
now := clock.Now()
|
now := clock.Now()
|
||||||
londonNow := now.In(londonLocation)
|
londonNow := now.In(londonLocation)
|
||||||
if londonNow.Hour() >= 22 {
|
if londonNow.Hour() >= 22 {
|
||||||
// Check if this is tomorrow's date
|
|
||||||
tomorrow := now.AddDate(0, 0, 1)
|
tomorrow := now.AddDate(0, 0, 1)
|
||||||
tomorrowStr := tomorrow.Format("2006-01-02")
|
tomorrowStr := tomorrow.Format("2006-01-02")
|
||||||
if day.Date == tomorrowStr {
|
if day.Date == tomorrowStr {
|
||||||
// Add a fake blocker for 00:00-11:00
|
|
||||||
lateNightBlock := TimeSlot{
|
lateNightBlock := TimeSlot{
|
||||||
StartTime: "00:00",
|
StartTime: "00:00",
|
||||||
EndTime: "11:00",
|
EndTime: "11:00",
|
||||||
@@ -616,10 +761,7 @@ func GetAvailableHours(w http.ResponseWriter, r *http.Request) {
|
|||||||
results = append(results, day)
|
results = append(results, day)
|
||||||
}
|
}
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
return results, nil
|
||||||
if err := json.NewEncoder(w).Encode(results); err != nil {
|
|
||||||
log.Printf("Failed to encode JSON response: %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// normalizeTime strips seconds from HH:MM:SS to HH:MM for consistent string
|
// normalizeTime strips seconds from HH:MM:SS to HH:MM for consistent string
|
||||||
@@ -688,3 +830,74 @@ func subtractTimeSlots(available []TimeSlot, gaps []TimeSlot) []TimeSlot {
|
|||||||
|
|
||||||
return result
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"crussell/db"
|
"crussell/db"
|
||||||
@@ -29,7 +30,7 @@ type ExceptionalGroup struct {
|
|||||||
Name string `json:"name" validate:"required"`
|
Name string `json:"name" validate:"required"`
|
||||||
Description string `json:"description" validate:"required"`
|
Description string `json:"description" validate:"required"`
|
||||||
Hours []ExceptionalHours `json:"hours,omitempty" validate:"required,min=7,max=7,dive"`
|
Hours []ExceptionalHours `json:"hours,omitempty" validate:"required,min=7,max=7,dive"`
|
||||||
WeekStarts []string `json:"weekStarts,omitempty" validate:"required,min=1,dive,required"`
|
WeekStarts []string `json:"weekStarts,omitempty" validate:"required,min=1,max=52,dive,required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- List Groups with Hours and Applications ---
|
// --- List Groups with Hours and Applications ---
|
||||||
@@ -300,7 +301,7 @@ func DeleteExceptionalGroup(w http.ResponseWriter, r *http.Request) {
|
|||||||
func UpdateExceptionalApplications(w http.ResponseWriter, r *http.Request) {
|
func UpdateExceptionalApplications(w http.ResponseWriter, r *http.Request) {
|
||||||
var req struct {
|
var req struct {
|
||||||
GroupID int `json:"groupId" validate:"required"`
|
GroupID int `json:"groupId" validate:"required"`
|
||||||
WeekStarts []string `json:"weekStarts" validate:"required,min=1,dive,required"`
|
WeekStarts []string `json:"weekStarts" validate:"required,min=1,max=52,dive,required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
@@ -368,3 +369,224 @@ func UpdateExceptionalApplications(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Response types mirroring bookings.OverlappingBooking, bookings.OverlappingBookingsResponse, and bookings.UserSummary
|
||||||
|
// (defined locally to avoid circular import: bookings → scheduling → bookings)
|
||||||
|
type (
|
||||||
|
UserSummary struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
FullName string `json:"full_name"`
|
||||||
|
Email *string `json:"email,omitempty"`
|
||||||
|
Phone *string `json:"phone,omitempty"`
|
||||||
|
PreviousFirstName *string `json:"previous_first_name,omitempty"`
|
||||||
|
PreviousLastName *string `json:"previous_last_name,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
OverlappingBooking struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
StartTime time.Time `json:"start_time"`
|
||||||
|
Duration int `json:"duration_minutes"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
User *UserSummary `json:"user,omitempty"`
|
||||||
|
Services []string `json:"services,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
OverlappingBookingsResponse struct {
|
||||||
|
Bookings []OverlappingBooking `json:"bookings"`
|
||||||
|
}
|
||||||
|
|
||||||
|
ConflictingBookingsRequest struct {
|
||||||
|
WeekStarts []string `json:"weekStarts" validate:"required,max=52,dive,required"`
|
||||||
|
ProposedHours []ExceptionalHours `json:"proposedHours" validate:"required,len=7,dive"`
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// GetConflictingBookingsForExceptionHandler accepts POST with proposed exceptional hours
|
||||||
|
// and week starts, queries active bookings that would conflict (bookings that overlap
|
||||||
|
// with the affected weeks but fall OUTSIDE the proposed open hours), and returns them
|
||||||
|
// in the existing OverlappingBookingsResponse format.
|
||||||
|
func GetConflictingBookingsForExceptionHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req ConflictingBookingsRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
http.Error(w, "invalid payload", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := validators.Validate.Struct(&req); err != nil {
|
||||||
|
log.Printf("Failed to process request: %v", err)
|
||||||
|
http.Error(w, "Invalid request", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(req.ProposedHours) != 7 {
|
||||||
|
http.Error(w, "must provide exactly 7 weekday entries (0-6)", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var allConflicts []OverlappingBooking
|
||||||
|
|
||||||
|
// Build weekday map for robust lookup (not relying on array index = weekday)
|
||||||
|
proposedByWeekday := map[int]ExceptionalHours{}
|
||||||
|
for _, h := range req.ProposedHours {
|
||||||
|
proposedByWeekday[h.Weekday] = h
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, weekStart := range req.WeekStarts {
|
||||||
|
ws, err := time.Parse("2006-01-02", weekStart)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Invalid week_start format: %v", err)
|
||||||
|
http.Error(w, "invalid week_start format, expected YYYY-MM-DD", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
wsLondon := ws.In(londonLocation)
|
||||||
|
rangeStart := time.Date(wsLondon.Year(), wsLondon.Month(), wsLondon.Day(), 0, 0, 0, 0, londonLocation)
|
||||||
|
rangeEnd := rangeStart.AddDate(0, 0, 7).Add(-time.Nanosecond) // Sun 23:59:59.999999999
|
||||||
|
|
||||||
|
rows, err := db.Conn.Query(r.Context(), `
|
||||||
|
SELECT
|
||||||
|
b.id,
|
||||||
|
b.start_time,
|
||||||
|
b.status,
|
||||||
|
b.created_at,
|
||||||
|
b.total_duration_minutes as duration,
|
||||||
|
u.id as user_id,
|
||||||
|
u.fn,
|
||||||
|
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 ASC
|
||||||
|
`, rangeStart, rangeEnd)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to query conflicting bookings: %v", err)
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
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 row: %v", err)
|
||||||
|
rows.Close()
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine which weekday this booking falls on (London wall-clock time)
|
||||||
|
bookingLondon := ob.StartTime.In(londonLocation)
|
||||||
|
// Go: Sun=0,Mon=1,...,Sat=6 → Our convention: Mon=0,...,Sun=6
|
||||||
|
ourWeekday := int((bookingLondon.Weekday() + 6) % 7)
|
||||||
|
|
||||||
|
proposed, _ := proposedByWeekday[ourWeekday]
|
||||||
|
|
||||||
|
isConflict := false
|
||||||
|
if !proposed.IsOpen {
|
||||||
|
// Salon is closed on this day — any active booking conflicts
|
||||||
|
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()
|
||||||
|
|
||||||
|
propStartMinutes := parseTimeToMinutes(proposed.StartTime)
|
||||||
|
propEndMinutes := parseTimeToMinutes(proposed.EndTime)
|
||||||
|
|
||||||
|
// Check if booking starts before opening or ends after closing.
|
||||||
|
// For midnight-crossing bookings (endMinutes < startMinutes), the booking
|
||||||
|
// extends past midnight and always conflicts with daily hours since the
|
||||||
|
// day's open window cannot span past midnight.
|
||||||
|
if startMinutes < 0 || endMinutes < 0 {
|
||||||
|
// parse error — treat as conflict
|
||||||
|
isConflict = true
|
||||||
|
} else if endMinutes < startMinutes {
|
||||||
|
// Booking crosses midnight — always a conflict with daily hours
|
||||||
|
isConflict = true
|
||||||
|
} else if startMinutes < propStartMinutes || endMinutes > propEndMinutes {
|
||||||
|
isConflict = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if isConflict {
|
||||||
|
allConflicts = append(allConflicts, ob)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
log.Printf("Error iterating conflicting bookings: %v", err)
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 for conflicting bookings: %v", err)
|
||||||
|
} else {
|
||||||
|
serviceMap := map[string][]string{}
|
||||||
|
for serviceRows.Next() {
|
||||||
|
var bookingID, name string
|
||||||
|
if err := serviceRows.Scan(&bookingID, &name); err != nil {
|
||||||
|
log.Printf("Failed to scan service row: %v", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
serviceMap[bookingID] = append(serviceMap[bookingID], name)
|
||||||
|
}
|
||||||
|
serviceRows.Close()
|
||||||
|
if err := serviceRows.Err(); err != nil {
|
||||||
|
log.Printf("Error iterating services for conflicting bookings: %v", err)
|
||||||
|
}
|
||||||
|
for i, ob := range allConflicts {
|
||||||
|
allConflicts[i].Services = serviceMap[ob.ID]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if allConflicts == nil {
|
||||||
|
allConflicts = []OverlappingBooking{}
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
if err := json.NewEncoder(w).Encode(OverlappingBookingsResponse{Bookings: allConflicts}); err != nil {
|
||||||
|
log.Printf("Failed to encode conflicting bookings response: %v", err)
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseTimeToMinutes converts a "HH:MM" string to minutes since midnight.
|
||||||
|
// Returns -1 on parse failure.
|
||||||
|
func parseTimeToMinutes(t string) int {
|
||||||
|
parts := strings.Split(t, ":")
|
||||||
|
if len(parts) < 2 {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
h, err1 := strconv.Atoi(parts[0])
|
||||||
|
m, err2 := strconv.Atoi(parts[1])
|
||||||
|
if err1 != nil || err2 != nil || h < 0 || h > 23 || m < 0 || m > 59 {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
return h*60 + m
|
||||||
|
}
|
||||||
|
|||||||
@@ -124,7 +124,7 @@ func ListTimeBlockers(w http.ResponseWriter, r *http.Request) {
|
|||||||
func CreateTimeBlocker(w http.ResponseWriter, r *http.Request) {
|
func CreateTimeBlocker(w http.ResponseWriter, r *http.Request) {
|
||||||
var req CreateTimeBlockerRequest
|
var req CreateTimeBlockerRequest
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest)
|
http.Error(w, "invalid request body", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -398,6 +398,8 @@ func CleanupOldReservations(ctx context.Context) (int, error) {
|
|||||||
OR (description LIKE 'RESERVATION:admin:callin:%' AND created_at < $3)
|
OR (description LIKE 'RESERVATION:admin:callin:%' AND created_at < $3)
|
||||||
OR (description LIKE 'RESERVATION:edit_request:%' AND created_at < $4)
|
OR (description LIKE 'RESERVATION:edit_request:%' AND created_at < $4)
|
||||||
OR (description LIKE 'PAYMENT_IN_FLIGHT:%' AND start_time + (duration_minutes * INTERVAL '1 minute') < NOW())
|
OR (description LIKE 'PAYMENT_IN_FLIGHT:%' AND start_time + (duration_minutes * INTERVAL '1 minute') < NOW())
|
||||||
|
OR (description LIKE 'RESERVATION:placeholder:%' AND created_at < $4)
|
||||||
|
OR (description LIKE 'RESERVATION:holiday_placeholder:%' AND created_at < $4)
|
||||||
`, oneHourAgo, tenMinutesAgo, fifteenMinutesAgo, twentyFourHoursAgo)
|
`, oneHourAgo, tenMinutesAgo, fifteenMinutesAgo, twentyFourHoursAgo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
|
|||||||
Reference in New Issue
Block a user