diff --git a/internal/handler/booking_handler.go b/internal/handler/booking_handler.go index 02a7ef99..f1ebed6f 100644 --- a/internal/handler/booking_handler.go +++ b/internal/handler/booking_handler.go @@ -409,6 +409,42 @@ func (h *Handler) validateRescheduleTime(ctx context.Context, bookingID, eventTy return h.validateBookingTime(ctx, &et, "fixed", hostIDs, nil, newStart, newEnd) } +// filterAvailableHosts narrows a candidate pool to the hosts actually free +// within their own configured availability for [startAt, endAt). +// +// Why this exists separately from validateBookingTime (#146): that function +// answers "does this slot exist at all?", which for round-robin means only that +// AT LEAST ONE candidate is within hours — deliberately, because it mirrors +// slots.pickHosts, and the public /slots listing must still offer a day where +// some host is free. It does NOT answer "who gets assigned?", and the +// assignment happens later inside booking.Service.Create by rotation strategy. +// Handing Create the unfiltered pool therefore let it pick a host who had +// declared themselves unavailable, booking them on the available host's slots. +// +// calendarFreeHosts does not close this gap: it filters on external calendar +// BUSY, and returns the pool untouched when no calendar provider is connected — +// the common self-hosted case, where overrides are the only availability signal. +// +// Pure DB reads (no external calls), so this is cheap on the hot path. For +// non-round-robin modes validateBookingTime has already required every +// candidate to be available, making this a no-op that preserves behaviour. +func (h *Handler) filterAvailableHosts(ctx context.Context, et *bookableEventType, candidates []string, startAt, endAt time.Time) ([]string, error) { + available := make([]string, 0, len(candidates)) + for _, hostID := range candidates { + ok, err := h.hostAvailableAt(ctx, hostID, et.ID, startAt, endAt) + if err != nil { + return nil, fmt.Errorf("check host availability: %w", err) + } + if ok { + available = append(available, hostID) + } + } + if len(available) == 0 { + return nil, errSlotUnavailable + } + return available, nil +} + // hostAvailableAt reports whether [startAt, endAt) falls entirely within one of // userID's configured availability windows (weekly rules, or a date override) for // eventTypeID, per internal/slots' own per-date resolution (slots.ResolveDayWindows). @@ -553,6 +589,9 @@ func (h *Handler) createBookingForSlug(ctx context.Context, slug string, startAt if err := h.validateBookingTime(ctx, et, et.RoutingMode, candidates, required, startAt.UTC(), endAt); err != nil { return nil, err } + if candidates, err = h.filterAvailableHosts(ctx, et, candidates, startAt.UTC(), endAt); err != nil { + return nil, err + } candidates, optional, err = h.calendarFreeHosts(ctx, et, candidates, required, optional, startAt.UTC(), endAt) if err != nil { if !errors.Is(err, errSlotUnavailable) { @@ -874,6 +913,10 @@ func (h *Handler) CreateBooking(w http.ResponseWriter, r *http.Request) { h.writeError(w, http.StatusConflict, "this slot is no longer available") return } + if candidates, err = h.filterAvailableHosts(r.Context(), et, candidates, startAt.UTC(), endAt); err != nil { + h.writeError(w, http.StatusConflict, "this slot is no longer available") + return + } candidates, optional, err = h.calendarFreeHosts(r.Context(), et, candidates, required, optional, startAt.UTC(), endAt) if err != nil { diff --git a/internal/handler/round_robin_unavailable_host_test.go b/internal/handler/round_robin_unavailable_host_test.go new file mode 100644 index 00000000..28b37726 --- /dev/null +++ b/internal/handler/round_robin_unavailable_host_test.go @@ -0,0 +1,104 @@ +package handler_test + +import ( + "net/http" + "testing" + + "github.com/calnode/calnode/internal/uid" +) + +// An unavailability override must remove a rotation host from the pool for that +// day, not merely make the day look unavailable when every host is out. +// +// The bug (#146): validateBookingTime's round-robin branch only requires that AT +// LEAST ONE candidate be inside their own hours — correct for deciding whether +// the slot exists at all (mirrors slots.pickHosts), but wrong for deciding WHO +// is assigned. The full candidate list was then handed to booking.Service.Create, +// which picks by rotation strategy, so it could assign a host who had declared +// themselves unavailable. calendarFreeHosts does not catch this: it filters on +// calendar busy, and returns the pool untouched when no calendar provider is +// connected (the common self-hosted case). +func TestRoundRobin_neverAssignsHostWithUnavailableOverride(t *testing.T) { + h, database, key, ownerID := setupWorkspaceWithDB(t) + database.Exec(`INSERT INTO users (id,email,name,iana_timezone,is_admin) VALUES ('u2','u2@example.com','Two','UTC',0)`) + seedFullAvailabilityDB(t, database, ownerID) + seedFullAvailabilityDB(t, database, "u2") + slug, etID := seedEventTypeHTTP(t, h, key) + makeRoundRobin(t, h, slug, key, ownerID, "u2") + + const day = "2027-05-03" + + // The FIRST rotation host (priority 0) declares the whole day unavailable. + // Round-robin's default least-loaded strategy would otherwise pick it first. + if _, err := database.Exec( + `INSERT INTO availability_overrides (id,user_id,date,is_available,reason) VALUES (?,?,?,0,'day off')`, + uid.New(), ownerID, day); err != nil { + t.Fatalf("seed unavailability override: %v", err) + } + + rec := postBooking(t, h, slug, day+"T10:00:00Z", "Alice", "alice@example.com") + if rec.Code != http.StatusCreated { + t.Fatalf("booking: %d — %s", rec.Code, rec.Body.String()) + } + + var hostID string + if err := database.QueryRow(`SELECT host_id FROM bookings WHERE event_type_id=?`, etID).Scan(&hostID); err != nil { + t.Fatalf("read assigned host: %v", err) + } + if hostID == ownerID { + t.Errorf("booking assigned to %s, who declared %s unavailable", hostID, day) + } +} + +// Same rule via the slug path that MCP and the booking assistant share. Without +// this, a fix applied only to the REST handler would leave those two entry points +// assigning unavailable hosts. +func TestRoundRobin_slugPathSkipsUnavailableHost(t *testing.T) { + h, database, key, ownerID := setupWorkspaceWithDB(t) + database.Exec(`INSERT INTO users (id,email,name,iana_timezone,is_admin) VALUES ('u2','u2@example.com','Two','UTC',0)`) + seedFullAvailabilityDB(t, database, ownerID) + seedFullAvailabilityDB(t, database, "u2") + slug, etID := seedEventTypeHTTP(t, h, key) + makeRoundRobin(t, h, slug, key, ownerID, "u2") + + const day = "2027-05-03" + if _, err := database.Exec( + `INSERT INTO availability_overrides (id,user_id,date,is_available,reason) VALUES (?,?,?,0,'day off')`, + uid.New(), ownerID, day); err != nil { + t.Fatalf("seed unavailability override: %v", err) + } + + if rec := postBooking(t, h, slug, day+"T14:00:00Z", "Alice", "alice@example.com"); rec.Code != http.StatusCreated { + t.Fatalf("booking: %d — %s", rec.Code, rec.Body.String()) + } + var hostID string + if err := database.QueryRow(`SELECT host_id FROM bookings WHERE event_type_id=?`, etID).Scan(&hostID); err != nil { + t.Fatalf("read assigned host: %v", err) + } + if hostID == ownerID { + t.Errorf("slug path assigned %s, who declared %s unavailable", hostID, day) + } +} + +// The all-hosts-unavailable case must still be refused, not silently assigned. +func TestRoundRobin_allHostsUnavailableStillRejected(t *testing.T) { + h, database, key, ownerID := setupWorkspaceWithDB(t) + database.Exec(`INSERT INTO users (id,email,name,iana_timezone,is_admin) VALUES ('u2','u2@example.com','Two','UTC',0)`) + seedFullAvailabilityDB(t, database, ownerID) + seedFullAvailabilityDB(t, database, "u2") + slug, _ := seedEventTypeHTTP(t, h, key) + makeRoundRobin(t, h, slug, key, ownerID, "u2") + + const day = "2027-05-03" + for _, u := range []string{ownerID, "u2"} { + if _, err := database.Exec( + `INSERT INTO availability_overrides (id,user_id,date,is_available,reason) VALUES (?,?,?,0,'day off')`, + uid.New(), u, day); err != nil { + t.Fatalf("seed unavailability override for %s: %v", u, err) + } + } + + if rec := postBooking(t, h, slug, day+"T10:00:00Z", "Alice", "alice@example.com"); rec.Code == http.StatusCreated { + t.Errorf("booking created with every host unavailable") + } +}