Commit 281ace0c authored by Christos Tranoris's avatar Christos Tranoris
Browse files

Book whole span" now respects the requested duration

parent 70b6fe4c
Loading
Loading
Loading
Loading
+108
Changes for docs/20260809_1640_book_whole_span_respects_duration.md: 108 added lines, 0 removed lines.
Original line number Diff line number Diff line
# "Book whole span" now respects the requested duration

**Date:** 2026-08-09 16:40
**Reported as:** *"in availability page when click the Book whole span moves to the reservation page
but it does not respect the duration when clip to calendar is selected"*

## What was wrong

`handleBookSpan` handed the reservation form the **searched horizon**, verbatim:

```ts
from: DateTime.fromISO(startTs).toISO()!,
to:   DateTime.fromISO(endTs).toISO()!,     // ← the To field, whatever the duration said
```

So *Slot duration* was write-only on that path: it shaped the search request, and then
the span booked every window the preview returned. Ask for two hours across a week and
you got the week.

The single-window **Book separate** path already trimmed by the duration in `STRICT`
mode; only the span ignored it.

## Why the fix isn't "To = From + duration"

The contract is explicit about what the two mean in this mode:

> `CLIP_TO_CALENDAR` treats the window as an outer span and books only the open parts
> of it: a Monday-to-Friday span against a Mon-Fri 09:00-17:00 person becomes five
> eight-hour reservations sharing one `spanGroupId` — forty hours of occupancy rather
> than one 104-hour block.

and, on the search side:

> `requestedDuration` is not applied per window in that mode.

A clipped span books **open time**, so "eight hours" is answered by however many calendar
windows add up to eight — never by a range eight hours wide. Ending the span at
`from + PT8H` against a 9-to-5 calendar would book *fewer* than eight hours, not eight.

## What it does now

The span ends the moment the preview's windows have accumulated the requested duration —
inside the last window when only part of it is needed, which is exact: the server clips
the span to the calendar either way, so the final segment is `windowStart..spanEnd`.

```ts
function spanExtent(): { end: DateTime; windowCount: number } {
  const windows    = results?.windows ?? [];
  const horizonEnd = DateTime.fromISO(endTs);
  let remaining    = requestedDuration.toMillis();
  if (remaining <= 0) return { end: horizonEnd, windowCount: windows.length };

  for (let i = 0; i < windows.length; i++) {
    const open = windows[i].end.diff(windows[i].start).toMillis();
    if (open >= remaining) {
      return { end: windows[i].start.plus({ milliseconds: remaining }), windowCount: i + 1 };
    }
    remaining -= open;
  }
  return { end: horizonEnd, windowCount: windows.length };
}
```

Worked through a Mon–Fri 09:00–17:00 calendar searched over a week:

| Duration | Span ends | Books |
|---|---|---|
| `PT2H` | Mon 11:00 | one 2-hour segment |
| `PT12H` | Tue 13:00 | Mon 09:00–17:00 + Tue 09:00–13:00 = 12h |
| `P1W` (more than the preview holds) | the horizon end | all five windows |
| none / zero | the horizon end | all five windows |

Falling back to the horizon when the preview is *shorter* than the duration is deliberate:
there is nothing more to book, and trimming would only drop windows the operator asked for.
`from` is still the searched horizon start — nothing before the first window is open, so the
server clips it away.

The header caption reports what the button will actually do, because the duration can now
stop the span short of the table:

```
Book separate reserves one window; Book whole span reserves the first 1 of 2 as one group.
```

**Book separate** is unchanged: in clipped mode it still books the window as offered
(the server does not apply the duration per window, so trimming there would book
something the preview never showed).

## Changed files

| File | Change |
|---|---|
| `src/features/availability/AvailabilitySearchPage.tsx` | `spanExtent()`; `handleBookSpan` sends its `end` as `to`; header caption counts the windows the span takes. |
| `src/features/availability/AvailabilitySearchPage.test.tsx` | `searchClipped()` split out of `searchClippedAndBookSpan()`, both taking `initialEntries` so the duration can be seeded from the URL; 5 tests added. |

## Tests

- ends the span where the windows have added up to the requested duration (`PT2H` → first
  window start + 2h), with `from` still the horizon start;
- carries the span into later windows when one is not enough (`PT12H` → second window start + 4h);
- books the whole horizon when the preview is shorter than the requested duration;
- says "the first 1 of 2" when the duration stops it short, and "all 2" when it does not.

## Verification

- `npx vitest run` — **1042/1042 passing**, 67 files (+5).
- `npm run lint` — 104 errors, all pre-existing `no-explicit-any`.
- `npx tsc -b --force` — no new errors versus the baseline.
+1
Changes for docs/index.md: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
@@ -2,6 +2,7 @@

| Date | File | Description |
|---|---|---|
| 2026-08-09 16:40 | ["Book whole span" now respects the requested duration](20260809_1640_book_whole_span_respects_duration.md) | The span handed the reservation form the searched horizon verbatim, so *Slot duration* was write-only on that path and a two-hour request booked every window the preview returned; the fix is **not** `To = From + duration` — a clipped span books *open time*, so eight hours is however many calendar windows add up to eight, and a wall-clock range that wide against a 9-to-5 calendar would book fewer — `spanExtent()` walks the preview accumulating window lengths and ends the span the moment the duration is met, inside the last window when only part of it is needed (exact, since the server clips the span to the calendar either way); a preview shorter than the duration, or no duration at all, still books the whole horizon, and the header caption now says "the first *k* of *n*" so the button reports what it will actually reserve; **Book separate** is unchanged, because the server does not apply the duration per window in that mode; +5 tests (1042) |
| 2026-08-09 16:05 | [Availability results — "Book whole span" is a button, and the row action says "Book separate"](20260809_1605_availability_book_span_button.md) | The clipped-mode span action lived in the `action` slot of an info `Alert`, which renders a low-emphasis text button — the primary way to use a `CLIP_TO_CALENDAR` preview looked like a footnote, and an info box is not where an operator looks for something to click; it is now a `contained` button in the results header row beside the window count, with one caption naming both scopes, and the per-row action reads **Book separate** while the span button is on screen (still plain "Book" in `STRICT`, still "Select" in the embedded picker); the gating condition became a named `spanBookable` flag read by all three; presentation only — both handlers and their query strings, including the agreed-suggestion resource handoff, are untouched; +2 tests (1037) |
| 2026-08-09 15:45 | [Nav: Availability moves next to Pools, Assessment leaves the drawer](20260809_1545_nav_availability_after_pools.md) | **Availability** moved from below Reservations to directly after **Pools** — it is asked *about* a pool, `/pools/{id}` links straight into it per resource, and the drawer now reads in the order the work happens (pick a pool → ask when it is free → book it); **Assessment** dropped from the sidebar while keeping its route, page and capability, the same call made for Memberships: it answers a question about a service order, and opened cold from the drawer there is no order to assess; the order regression test reads the rendered link list rather than the `navItems` array, so it also fails if a capability hides Pools from under it; the one pre-existing `Shell.tsx` `badge` tsc error changes only its message text, because the printed union now lists Availability second |
| 2026-08-09 15:30 | ["membershipId must not be null" — every reservation targets a resource](20260809_1530_reservation_requires_membership.md) | Book whole span → Create Reservation returned a 400 because both booking forms labelled the resource "(optional)" and offered "— Any resource —", and the codec dropped the field when empty — but `FeasibilityRequest` lists `membershipId` as required "for every pool category, capacity pools included", so there is no pool-level booking to express; `FeasibilityDraft.membershipId` is now required in the domain (which surfaced every construction site through `tsc -b`), the encoder sends it unconditionally, and both forms make the resource a required field that gates Submit instead of failing after the click, with an explicit message when the pool has no members; an alternative no longer clears the chosen resource (the kinds are all start/end moves, and clearing it now leaves the form unsubmittable); Book whole span carries the preview's suggested resource when — and only when — every window agrees on one; +8 tests (1033), lint 106 → 104 |
+46 −2
Changes for src/features/availability/AvailabilitySearchPage.test.tsx: 46 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -525,13 +525,23 @@ describe('AvailabilitySearchPage — coverage mode', () => {
    );
  }

  async function searchClippedAndBookSpan(suggestions: Array<string | undefined>) {
  async function searchClipped(
    suggestions: Array<string | undefined>,
    initialEntries: string[] = ['/'],
  ) {
    stubClippedSearch(suggestions);
    renderPage();
    renderPage(['chronos.admin'], {}, initialEntries);
    fillForm();
    pickClipped();
    fireEvent.click(screen.getByRole('button', { name: /^search$/i }));
    await waitFor(() => expect(screen.getByRole('table')).toBeInTheDocument());
  }

  async function searchClippedAndBookSpan(
    suggestions: Array<string | undefined>,
    initialEntries: string[] = ['/'],
  ) {
    await searchClipped(suggestions, initialEntries);
    fireEvent.click(screen.getByRole('button', { name: /book whole span/i }));
    return bookedParams();
  }
@@ -554,4 +564,38 @@ describe('AvailabilitySearchPage — coverage mode', () => {
    const params = await searchClippedAndBookSpan(['mem-1', undefined]);
    expect(params.has('membershipId')).toBe(false);
  });

  // The span used to hand the form the whole searched horizon, so a two-hour request booked
  // every window the preview returned. A clipped span books the open parts of its range, so two
  // hours means two hours of *window* — reached inside the first one here.
  it('ends the span where the windows have added up to the requested duration', async () => {
    const params = await searchClippedAndBookSpan(['mem-1', 'mem-1'], ['/?duration=PT2H']);
    expect(params.get('to')).toBe(WINDOW.start.plus({ hours: 2 }).toISO());
    // The start is still the searched horizon: nothing before the first window is open anyway.
    expect(params.get('from')).toBe(DateTime.fromISO('2024-06-01T08:00').toISO());
  });

  // Spilling into a later window is the whole point of the mode: 12 hours of a 9-to-5 calendar
  // is one full day plus half of the next.
  it('carries the span into later windows when one is not enough', async () => {
    const params = await searchClippedAndBookSpan(['mem-1', 'mem-1'], ['/?duration=PT12H']);
    expect(params.get('to')).toBe(WINDOW.start.plus({ days: 1, hours: 4 }).toISO());
  });

  // 16 hours of preview against the default 1-day duration: there is no more to book, and
  // trimming to the duration would drop windows the operator asked for.
  it('books the whole horizon when the preview is shorter than the requested duration', async () => {
    const params = await searchClippedAndBookSpan(['mem-1', 'mem-1']);
    expect(params.get('to')).toBe(DateTime.fromISO('2024-06-01T18:00').toISO());
  });

  it('says how many windows the span takes when the duration stops it short', async () => {
    await searchClipped(['mem-1', 'mem-1'], ['/?duration=PT2H']);
    expect(screen.getByText(/the first 1 of 2/i)).toBeInTheDocument();
  });

  it('says the span takes them all when the duration does not stop it short', async () => {
    await searchClipped(['mem-1', 'mem-1']);
    expect(screen.getByText(/reserves all 2 as one group/i)).toBeInTheDocument();
  });
});
+38 −3
Changes for src/features/availability/AvailabilitySearchPage.tsx: 38 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -156,6 +156,35 @@ export function AvailabilitySearchPage({ onWindowSelect }: Props = {}) {
    return first && ids.every(id => id === first) ? first : '';
  }

  /**
   * How far the span has to run to book the requested duration, and how many windows of the
   * preview that takes.
   *
   * A clipped span books the *open parts* of its outer range, so a request for eight hours is
   * answered by however many calendar windows add up to eight — never by a range eight hours wide.
   * The span therefore ends the moment the preview's windows have accumulated the requested
   * duration, which falls inside the last of them when only part of it is needed: the server clips
   * the span to the calendar either way, so cutting there books exactly what was asked for.
   *
   * With no duration, or with the whole preview still short of it, the span stays the searched
   * horizon — there is nothing more to book, and trimming would only lose windows.
   */
  function spanExtent(): { end: DateTime; windowCount: number } {
    const windows    = results?.windows ?? [];
    const horizonEnd = DateTime.fromISO(endTs);
    let remaining    = requestedDuration.toMillis();
    if (remaining <= 0) return { end: horizonEnd, windowCount: windows.length };

    for (let i = 0; i < windows.length; i++) {
      const open = windows[i].end.diff(windows[i].start).toMillis();
      if (open >= remaining) {
        return { end: windows[i].start.plus({ milliseconds: remaining }), windowCount: i + 1 };
      }
      remaining -= open;
    }
    return { end: horizonEnd, windowCount: windows.length };
  }

  /**
   * The clipped preview describes what booking the *whole horizon* would produce, so it needs an
   * action that does that — booking the windows one at a time is the thing the mode exists to
@@ -168,7 +197,7 @@ export function AvailabilitySearchPage({ onWindowSelect }: Props = {}) {
      ...(poolId                ? { poolId }                              : {}),
      ...(effectiveMembershipId ? { membershipId: effectiveMembershipId } : {}),
      from: DateTime.fromISO(startTs).toISO()!,
      to:   DateTime.fromISO(endTs).toISO()!,
      to:   spanExtent().end.toISO()!,
      coverageMode: 'CLIP_TO_CALENDAR',
      ...writeCapacityParams(capacityAmount),
      [RESERVATION_TAB_PARAM]: 'firm',
@@ -180,6 +209,9 @@ export function AvailabilitySearchPage({ onWindowSelect }: Props = {}) {
  // Only a clipped preview describes a span, and only the routed page can navigate to the form —
  // embedded in a picker there is nothing to hand the span to.
  const spanBookable = isClipped && !onWindowSelect && !noWindows;
  // The duration can stop the span short of the horizon, so the header says what will be booked
  // rather than counting rows the operator is not about to reserve.
  const spanWindowCount = spanExtent().windowCount;
  const emptyMessage = !searched
    ? 'Enter search criteria above and click Search.'
    : results?.nextAvailability
@@ -328,8 +360,11 @@ export function AvailabilitySearchPage({ onWindowSelect }: Props = {}) {
                {/* Two ways to book the same preview, so each says which windows it takes */}
                <Typography variant="caption" color="text.secondary">
                  <strong>Book separate</strong> reserves one window;{' '}
                  <strong>Book whole span</strong> reserves all {results!.windows.length} as one
                  group.
                  <strong>Book whole span</strong> reserves{' '}
                  {spanWindowCount === results!.windows.length
                    ? `all ${results!.windows.length}`
                    : `the first ${spanWindowCount} of ${results!.windows.length}`}{' '}
                  as one group.
                </Typography>
                <Button
                  variant="contained"