add GetAvailableHours
This commit is contained in:
@@ -390,3 +390,239 @@ func sqlIn(query string, args []int) (string, []interface{}, error) {
|
||||
query = fmt.Sprintf(query, placeholders)
|
||||
return query, inArgs, nil
|
||||
}
|
||||
|
||||
// --- 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"` // Can have gaps (lunch, bookings, etc.)
|
||||
Source string `json:"source"` // "default" or "exceptional"
|
||||
}
|
||||
|
||||
// --- GetAvailableHours (working hours with gaps for lunch, bookings, etc.) ---
|
||||
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
|
||||
}
|
||||
|
||||
// Load default hours
|
||||
defaultMap := map[int]DefaultHours{}
|
||||
defRows, _ := db.DB.Query(r.Context(), `
|
||||
SELECT weekday, start_time::text, end_time::text, is_open
|
||||
FROM working_hours
|
||||
`)
|
||||
for defRows.Next() {
|
||||
var d DefaultHours
|
||||
if err := defRows.Scan(&d.Weekday, &d.StartTime, &d.EndTime, &d.IsOpen); err == nil {
|
||||
defaultMap[d.Weekday] = d
|
||||
}
|
||||
}
|
||||
defRows.Close()
|
||||
|
||||
// Load exceptional applications in range
|
||||
appRows, _ := db.DB.Query(r.Context(), `
|
||||
SELECT a.group_id, a.week_start
|
||||
FROM exceptional_group_applications a
|
||||
WHERE a.week_start <= $1 AND a.week_start >= $2 - INTERVAL '6 days'
|
||||
`, end, start)
|
||||
type appEntry struct {
|
||||
GroupID int
|
||||
WeekStart time.Time
|
||||
}
|
||||
var apps []appEntry
|
||||
for appRows.Next() {
|
||||
var e appEntry
|
||||
if err := appRows.Scan(&e.GroupID, &e.WeekStart); err == nil {
|
||||
apps = append(apps, e)
|
||||
}
|
||||
}
|
||||
appRows.Close()
|
||||
|
||||
// Load exceptional hours for all relevant groups
|
||||
groupIDs := []int{}
|
||||
for _, a := range apps {
|
||||
groupIDs = append(groupIDs, a.GroupID)
|
||||
}
|
||||
|
||||
exHoursMap := map[int]map[int]ExceptionalHours{} // groupID -> weekday -> hours
|
||||
if len(groupIDs) > 0 {
|
||||
query, args, _ := sqlIn("SELECT group_id, weekday, start_time::text, end_time::text, is_open FROM exceptional_working_hours WHERE group_id IN (?)", groupIDs)
|
||||
rows, _ := db.DB.Query(r.Context(), query, args...)
|
||||
for rows.Next() {
|
||||
var h ExceptionalHours
|
||||
if err := rows.Scan(&h.GroupID, &h.Weekday, &h.StartTime, &h.EndTime, &h.IsOpen); err == nil {
|
||||
if _, ok := exHoursMap[h.GroupID]; !ok {
|
||||
exHoursMap[h.GroupID] = map[int]ExceptionalHours{}
|
||||
}
|
||||
exHoursMap[h.GroupID][h.Weekday] = h
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
}
|
||||
|
||||
// Load bookings with their total duration (sum of all services)
|
||||
bookingRows, _ := db.DB.Query(r.Context(), `
|
||||
SELECT
|
||||
b.start_time,
|
||||
COALESCE(SUM(s.duration_minutes), 0) as total_duration
|
||||
FROM bookings b
|
||||
LEFT JOIN booking_services bs ON b.id = bs.booking_id
|
||||
LEFT JOIN services s ON bs.service_id = s.id
|
||||
WHERE b.start_time >= $1
|
||||
AND b.start_time < $2 + INTERVAL '1 day'
|
||||
AND b.status IN ('confirmed', 'pending')
|
||||
GROUP BY b.id, b.start_time
|
||||
ORDER BY b.start_time
|
||||
`, start, end)
|
||||
|
||||
bookings := map[string][]TimeSlot{} // date -> booked slots
|
||||
for bookingRows.Next() {
|
||||
var startTime time.Time
|
||||
var durationMinutes int
|
||||
if err := bookingRows.Scan(&startTime, &durationMinutes); err == nil {
|
||||
dateStr := startTime.Format("2006-01-02")
|
||||
endTime := startTime.Add(time.Duration(durationMinutes) * time.Minute)
|
||||
|
||||
bookings[dateStr] = append(bookings[dateStr], TimeSlot{
|
||||
StartTime: startTime.Format("15:04"),
|
||||
EndTime: endTime.Format("15:04"),
|
||||
})
|
||||
}
|
||||
}
|
||||
bookingRows.Close()
|
||||
|
||||
// Generate final result per day with gaps
|
||||
var results []DayAvailableHours
|
||||
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 // shift Monday=0 ... Sunday=6
|
||||
}
|
||||
|
||||
// Find applied group for this week
|
||||
var applied *ExceptionalHours
|
||||
weekStart := d.AddDate(0, 0, -weekday) // Monday of current week
|
||||
for _, a := range apps {
|
||||
if a.WeekStart.Equal(weekStart) {
|
||||
if dayHours, ok := exHoursMap[a.GroupID][weekday]; ok {
|
||||
applied = &dayHours
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
var day DayAvailableHours
|
||||
day.Date = d.Format("2006-01-02")
|
||||
day.Weekday = weekday
|
||||
|
||||
// Determine base working hours and source
|
||||
var baseStart, baseEnd string
|
||||
var isOpen bool
|
||||
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"
|
||||
}
|
||||
|
||||
day.IsOpen = isOpen
|
||||
|
||||
if isOpen {
|
||||
// Start with the full working hours as one slot
|
||||
allSlots := []TimeSlot{{StartTime: baseStart, EndTime: baseEnd}}
|
||||
|
||||
// Apply gaps from bookings
|
||||
dateStr := day.Date
|
||||
if booked, ok := bookings[dateStr]; ok {
|
||||
allSlots = subtractTimeSlots(allSlots, booked)
|
||||
}
|
||||
|
||||
day.Slots = allSlots
|
||||
} else {
|
||||
day.Slots = []TimeSlot{}
|
||||
}
|
||||
|
||||
results = append(results, day)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(results)
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
+4
-1
@@ -113,8 +113,11 @@ func main() {
|
||||
r.Post("/exceptional-applications", scheduling.CreateExceptionalApplication)
|
||||
})
|
||||
|
||||
// Merged working hours by date range
|
||||
// Merged working hours (default + exceptional)
|
||||
r.Get("/working-hours", scheduling.GetWorkingHours)
|
||||
|
||||
// Fully calculated available hours (default + exceptional + bookings + lunch breaks)
|
||||
r.Get("/available-hours", scheduling.GetAvailableHours)
|
||||
})
|
||||
|
||||
fmt.Println("Server is listening on :8080")
|
||||
|
||||
Reference in New Issue
Block a user