Commit 5c7bb60e authored by Christos Tranoris's avatar Christos Tranoris
Browse files

adding coverage mode, search, purge and pool dateail expand

parent b8ee3498
Loading
Loading
Loading
Loading
+1 −1

File changed.

Preview size limit exceeded, changes collapsed.

+196
Changes for docs/20260808_0120_coverage_mode_clip_to_calendar.md: 196 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Coverage mode: `STRICT` vs `CLIP_TO_CALENDAR` (reservation spans)

**Date:** 2026-08-08 01:20
**Scope:** contract refresh → domain → codec → gateways → hooks → shared UI → availability, reservations and activity pages

## What the backend added

`coverageMode` is a new required-with-default field on four request schemas
(`FeasibilityRequest`, `ResourceFirmRequest`, `AvailabilitySearchRequest`,
`ResourceAvailabilitySearchRequest`). It answers a question the API previously
had only one answer for: *what should happen when the requested window is partly
outside the availability calendar?*

| Mode | Meaning |
|---|---|
| `STRICT` (default) | One continuous block. The whole Effective Interval — including setup and teardown buffers — must fall inside open calendar windows, or the request comes back `NOT_FEASIBLE` with reason `CALENDAR`. |
| `CLIP_TO_CALENDAR` | The window is an **outer span**. The server books only its open parts: one reservation per open calendar window, all sharing a `spanGroupId`. All-or-nothing — one taken or blacked-out day writes nothing at all. |

Three consequences drove the UI work:

1. **A clipped response has a different shape.** Instead of `reservation`, a
   `FeasibilityResponse` carries `spanGroupId` + `reservations[]`.
2. **A span is cancelled as a group** via `POST /api/v1/reservations/cancel` with
   `spanGroupId` as the sole selector, returning a `CancellationResult`
   (`SUCCESS` / `PARTIAL` / `REJECTED` plus per-reservation rows).
3. **New `NOT_FEASIBLE` reason** `MAX_DURATION_EXCEEDED` — the booked window is
   longer than the pool's maximum reservation duration.

## Contract refresh

`api-docs.json` re-fetched from `http://localhost:8888/v3/api-docs` and
`schema.d.ts` regenerated (`npm run gen:types`, 394 lines changed). Besides
coverage mode this pulled in renamed operation IDs (`createFirm` →
`createFirmReservation` etc. — cosmetic, the codec addresses schemas not
operations), `readonly createdBy`, and `maxReservationDuration` on the pool
schemas.

> An earlier fetch had duplicate enum members
> (`["STRICT","CLIP_TO_CALENDAR","STRICT","CLIP_TO_CALENDAR"]`) on all four
> schemas. That was reported as a spec-generation bug rather than worked around,
> and was fixed backend-side before this work landed.

## Domain (`src/domain/`)

- `reservation.ts` — `COVERAGE_MODES`, `CoverageMode`, `DEFAULT_COVERAGE_MODE`,
  the `isCoverageMode` guard (used to validate URL params), plus
  `CancellationOutcome`, `ReservationCancellation`, `CancellationResult`.
  `Reservation` gained an optional `spanGroupId`.
- `feasibility.ts` — `MAX_DURATION_EXCEEDED` added to `NOT_FEASIBLE_REASONS`; new
  `ReservationSpan { spanGroupId, reservations }`; the `FEASIBLE` arm of
  `FeasibilityResult` gained an optional `span`.
- `gateways.ts` — `coverageMode?` on `FeasibilityDraft` and
  `PoolAvailabilityQuery`; `cancelSpan(spanGroupId)` on `ReservationGateway`.

### Why `span` is optional and `reservation` always populated

The obvious modelling would be a fifth outcome, or a `reservation | reservations`
union. Both would have forced every existing consumer of the `FEASIBLE` arm to
grow a branch for a case most of them don't care about.

Instead `decodeFeasible()` in `mappers/feasibility.ts` **folds** the two wire
shapes: the first member of a span doubles as the representative `reservation`,
and `span` is only set when the server actually returned several. A caller that
only asks "did it book?" needs no span handling and behaves exactly as before;
callers that need the whole picture read `span`. A `STRICT` booking deliberately
leaves `span` undefined — it is a span of one by definition, and synthesising one
would put the span-cancel affordance in front of an operator with nothing to
cancel as a group.

## Codec (`src/adapters/api/mappers/`)

- `encodeFeasibilityDraft`, `encodePoolAvailabilitySearch` and
  `encodeResourceAvailabilitySearch` **always** send `coverageMode`, defaulting to
  `STRICT`. openapi-typescript emits defaulted properties as required, and
  stating the mode costs nothing while keeping a logged request self-describing.
- `decodeReservation` carries `spanGroupId` through (conditional spread — absent,
  not `undefined`).
- `decodeFeasible` folds `spanGroupId` + `reservations[]`, falling back to the
  members' own `spanGroupId` when the envelope omits it.
- New `decodeCancellationResult`. An empty envelope decodes to `REJECTED` with no
  rows: reading it as `SUCCESS` would tell an operator the span is gone when
  nothing was touched.

### One deliberate wire-type widening

The refreshed contract makes `membershipId` **required** on `FeasibilityRequest`,
but the booking forms still offer "— Any resource —", and a pool-level request has
always simply omitted the field. Rather than silently change booking behaviour,
`encodeFeasibilityDraft` returns a locally widened
`WireFeasibilityRequestOut = Omit<WireFeasibilityRequest,'membershipId'> & { membershipId?: string }`.
**This is a real contract divergence and should be confirmed with the backend** —
either the field is genuinely optional (spec should say so) or the "any resource"
option needs removing.

## Gateway + hooks

- `reservationGateway.cancelSpan()` posts `{ spanGroupId }` — the sole selector —
  to `/api/v1/reservations/cancel` and decodes the `CancellationResult`.
- `useCancelSpan()` in `app/reservations.ts`, invalidating `reservations.all()`,
  `activity.all()` and `inventory.all()`.

## Shared UI (`src/ui/`)

- **`CoverageModeSelect`** — the select plus a helper line that changes with the
  selection. Two hint sets: `booking` (span groups, all-or-nothing) and `search`
  (previewing; requested duration not applied per window). The modes differ only
  in what exists afterwards, so explaining at the point of choice is cheaper than
  explaining the resulting occupancy.
- **`SpanSummary`** — "Span booked — N reservations", the `spanGroupId` chip, and
  a table of booked/effective window and state per member. The count *is* the
  mode's observable effect; showing only the first member would misreport what
  was committed.
- `OutcomePanel` renders `SpanSummary` **instead of** `IntervalDisplay` when a
  span is present — the outer window the user asked for was never booked as such,
  so showing it would misdescribe what exists. `MAX_DURATION_EXCEEDED` added to
  `REASON_LABELS`.

## Pages

**`AvailabilitySearchPage`** — mode selector (search variant), seeded from the URL
via `isCoverageMode`; `coverageMode` sent with the search. In clipped mode:

- window rows are no longer trimmed by `requestedDuration` (the server doesn't
  apply it per window, so trimming would book something the preview never offered);
- selecting a single window navigates with `coverageMode: STRICT` — one window is
  continuous by construction;
- an info alert offers **Book whole span**, navigating with the full horizon and
  `coverageMode: CLIP_TO_CALENDAR`. Booking windows one at a time is exactly what
  the mode exists to avoid, and would lose the shared span group.

**`ReservationsPage` / `FirmReservationForm` / `HoldRequestForm`** — mode read from
the URL (guarded, falling back to `STRICT`) and passed down as
`initialCoverageMode`; selector on both forms; the resulting span held in state.

**`ActiveHoldsPanel`** — accepts an optional `span`. Promote and cancel are
**asymmetric** and are wired accordingly:

- *Promote* still goes through the first member's id — promoting any one hold
  promotes the whole group atomically.
- *Cancel* routes through `cancelSpan(spanGroupId)`. `DELETE` on one hold releases
  only that one, so cancelling a span member-wise would leave the siblings held
  until they expire. Button label and heading switch to span wording.

**`ReservationDetailPage`** — a monospace "Span group" row, and a new
**`CancelSpanButton`** sitting *alongside* the single-reservation cancel. Both
actions remain legitimate (the contract allows dropping one day of a span), so the
operator must be able to tell them apart. The button is capability-gated, confirms
before firing, and renders the `CancellationResult` per reservation —
`PARTIAL` shows as a warning rather than collapsing into "done", because a skipped
member is something to act on.

## Tests

New/extended coverage:

| Area | What |
|---|---|
| `mappers/entities.test.ts` | `coverageMode` defaulting + explicit send across all three encoders; `membershipId` omission; `decodeCancellationResult` incl. empty-envelope → `REJECTED` |
| `mappers/feasibility.test.ts` | `spanGroupId` decode + absence; span folding at 201 and 200; envelope-missing fallback; `span` undefined for STRICT; `MAX_DURATION_EXCEEDED` |
| `gateways.test.ts` | `createFirm` states the mode on the wire; `cancelSpan` posts `spanGroupId` as sole selector and decodes a `PARTIAL` |
| `CoverageModeSelect.test.tsx` | selection reported as a domain token; hint tracks selection; search-variant wording; disabled |
| `SpanSummary.test.tsx` | count + singularisation, group id, one row per member, dash for absent effective window |
| `ActiveHoldsPanel.test.tsx` | the promote/cancel asymmetry pinned in both directions, plus plain-hold behaviour unchanged |
| `CancelSpanButton.test.tsx` | gating (no span / read-only role), confirm-then-cancel with group id, back-out, `PARTIAL` warning rows, `SUCCESS` |
| `ReservationDetailPage.test.tsx` | span row + span action present when grouped, absent when not, single cancel retained |
| `AvailabilitySearchPage.test.tsx` | `STRICT` default sent, `CLIP_TO_CALENDAR` after selection, "Book whole span" only in clipped mode |

**Results:** 902 tests, 64 files — green. Lint is unchanged at its pre-existing
112 `no-explicit-any` errors (no new violations, no boundary violations).
`npx vite build` succeeds. `npx tsc -b` introduces **zero** new errors against a
stashed baseline.

> The full-suite run is flaky on this machine: a *different* unrelated test file
> hits the 5 s timeout on roughly two runs in three (observed in
> `FirmReservationForm`, `OpenSliceBrowsePage`). Each passes in isolation and one
> full run was green at 902/902. This is parallel-load timing, not a regression.

## Separate infrastructure fix (not part of the feature)

`tsconfig.app.json` mapped only the wildcard aliases (`@domain/*`) and never the
bare ones (`@domain`), while `vite.config.ts` maps both. Every bare-alias import
therefore failed `tsc -b` with `TS2307`, cascading into hundreds of implicit-any
errors and making the type gate useless — which is why `npm run build` was
documented as "currently failing on MUI theme typings". Bare entries added for all
seven aliases. The remaining ~52 baseline errors are now visible and real
(LocalTime object-vs-string in `entities.ts`, `getProfile` missing from test
`AuthPort` mocks, `ImportMetaEnv` in `config.ts`, and the MUI v9 theme typings).

## Follow-ups

1. **Confirm `membershipId`** — required in the contract, optional in practice (above).
2. **`maxReservationDuration`** now exists on `PoolRequest`/`PoolEntity` and is not
   surfaced in the pool forms. Deliberately out of scope here; it pairs naturally
   with the new `MAX_DURATION_EXCEEDED` reason and is worth its own task.
3. **Fix the baseline `tsc -b` errors** now that they are visible, so
   `npm run build` can replace `npx vite build` in the Dockerfile.
+97
Changes for docs/20260808_1819_availability_search_layout.md: 97 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Availability Search — form and results layout

**Date:** 2026-08-08 18:19
**Scope:** `src/features/availability/AvailabilitySearchPage.tsx` (presentation only — no behaviour change)

## Why

Adding the coverage-mode selector was the last straw for a form row that had
already outgrown its container. The page had four concrete layout defects:

1. **Horizontal overflow.** The second row was a `Stack direction="row"` holding
   six children — From, To, `DurationInput`, `CapacityInput`,
   `CoverageModeSelect` (`minWidth: 260`) and the Search button — with **no
   `flexWrap`**. Their combined minimum widths exceed 1200 px, so on a laptop
   viewport the row did not fold; it pushed Search off the right edge.
2. **Ragged input alignment.** The row used `alignItems="flex-start"`, which
   aligns the *outer boxes*, not the inputs inside them. `DurationInput` renders
   a `FormLabel` **above** its three fields and `CoverageModeSelect` renders a
   multi-line `FormHelperText` **below** its select, so every actual input box
   sat at a different height.
3. **Collapsed capacity field.** `CapacityInput` sizes its quantity `TextField`
   with `flex: 1`. In an unconstrained parent there is nothing to grow into, so
   it rendered at its minimum.
4. **No visual grouping.** The results table sat in a `Paper` while the controls
   that produced it floated on the page background, so the form did not read as
   a single unit.

## What changed

### The form

Wrapped in `<Paper variant="outlined" sx={{ p: 2 }}>` and split into three
`Divider`-separated rows, each a flex row with `flexWrap: 'wrap'`:

| Row | Contents | Alignment |
|---|---|---|
| What to search | Pool, Resource (optional) | `flex-end` |
| When, and how much of it | From, To, Slot duration, Capacity | `flex-end` |
| How to cover it | `CoverageModeSelect`, Search | `flex-start` |

- Rows 1–2 bottom-align (`alignItems: 'flex-end'`) so the **input boxes** line up
  regardless of whether a control carries its label above or its helper below —
  the fix for defect 2.
- Row 3 top-aligns instead, so Search sits level with the select rather than
  with the bottom of its three-line hint.
- Coverage mode gets its own line. It changes what the results *mean*, not just
  which ones come back, so it needs room for the explanation rather than being
  squeezed between the value inputs.
- `CapacityInput` wrapped in `<Box sx={{ width: 240 }}>` — a width for its
  `flex: 1` quantity field to grow into.
- `CoverageModeSelect` wrapped in `<Box sx={{ flex: '1 1 320px', maxWidth: 460 }}>`
  so the hint has a readable measure without running the width of the page.
- Search gets `sx={{ ml: { xs: 0, sm: 'auto' } }}` — pushed right on a normal
  viewport, flush left once the row has wrapped on a narrow one.
- From/To marked `required` (matching Pool, and matching the `handleSearch`
  guard that already refused to run without them) and given `minWidth: 210`, the
  width a `datetime-local` control needs before the browser truncates it.

### The results

- Window count leads the table (`Typography variant="subtitle2"`) — it is the
  direct answer to the question that was asked, and in clipped mode it is the
  number that matters.
- `TableContainer` is now `variant="outlined"` with `overflowX: 'auto'`, so a
  wide table scrolls inside its own box instead of the page.
- Window and Book-by cells set `whiteSpace: 'nowrap'`: a timestamp reads as one
  value and wrapping an interval mid-string is unreadable.
- The clipped-mode "Book whole span" alert margin went `mb: 1` → `mb: 2` to
  match the surrounding rhythm.

## Not changed

No state, no handler, no query, and no navigation target was touched.
`handleSearch`, `handleWindowSelect` and `handleBookSpan` are byte-identical —
including the clipped-mode rules from the coverage-mode work (windows are not
trimmed by `requestedDuration`, a single window books `STRICT`, the span action
books the full horizon `CLIP_TO_CALENDAR`).

## Verification

- `npx vitest run` — **902 tests, 64 files, all passing**, including the 10 in
  `AvailabilitySearchPage.test.tsx`. Those tests address controls by accessible
  role and name, so they pin the behaviour through the restructure rather than
  the markup.
- `npm run lint` — **112 errors**, exactly the pre-existing
  `no-explicit-any` baseline. No new violations.
- `npx tsc -b` — **zero** new errors against the stashed baseline.

> The full-suite flakiness noted in the coverage-mode doc did not reproduce here;
> this run was green first time.

## Follow-up

The same six-control-row pattern exists on the reservation forms
(`FirmReservationForm`, `HoldRequestForm`), which also gained a
`CoverageModeSelect`. They are narrower today but will hit the same wrapping
problem — worth applying the same row/divider treatment in its own pass.
+123
Changes for docs/20260808_1901_availability_search_defaults_local_time.md: 123 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Availability Search — usable defaults and browser-local times

**Date:** 2026-08-08 19:01
**Scope:** `src/features/availability/AvailabilitySearchPage.tsx` (+ tests)

## What changed

| Field | Before | After |
|---|---|---|
| From | empty | **now** |
| To | empty | **now + 1 day** |
| Slot duration | `0` (omitted from the request) | **1 day** |
| Result times | tenant zone (`VITE_TENANT_TIMEZONE`) | **browser local zone** |

URL parameters still win over all three defaults — the page is navigated to from
calendars and pool views carrying an explicit range, and a default that
overrode it would discard the reason the operator arrived. That is pinned by a
test.

## Why the defaults

Search is disabled until From and To are filled, so empty defaults meant every
visit began with the same two pieces of typing before the page could do
anything. A day is the usual unit of the question "when is this free?", and it
makes the pre-filled duration and the pre-filled range agree with each other.

`DEFAULT_SLOT_DURATION` is a module constant rather than an inline literal, since
it is referenced from the state seed and is the value the To default is chosen to
match.

## Why browser-local, and the trap underneath it

`datetime-local` inputs have **no timezone**. The browser reads and writes a bare
wall-clock string in the user's own zone, and there is no way to make one display
a different zone. From and To are therefore unavoidably local.

The results table, meanwhile, rendered whatever zone the codec decoded into —
`VITE_TENANT_TIMEZONE`, defaulting to UTC. So an operator typed `09:00`, and the
windows came back labelled in another zone: the answer silently disagreed with
the question.

Fixed by converting at the three display sites (`w.start` / `w.end`,
`latestBookableStart`, and `nextAvailability` in the empty message). The domain
values are untouched — `.toLocal()` is applied at render only, so the instants
sent to the server are unchanged. `formatDateTime`/`formatInterval` already append
the offset name, so the zone stays *stated* rather than assumed.

A new helper, `toLocalInput(dt)`, is the single place that converts an instant
into what a `datetime-local` field holds; both seeds go through it.

## A defect the new default exposed

`handleWindowSelect` trims the booked range to `start + requestedDuration` in
`STRICT` mode. With the old default of `0` that branch never ran. With a 1-day
default it runs on every Book click — and a 1-day duration is **longer than most
windows**, so it would have seeded the reservation form with a range extending
past the end of the window the search had just offered, asking to book hours
reported as unavailable.

The duration now only ever *trims*:

```ts
const trimmed = w.start.plus(requestedDuration);
const toTs = !isClipped && requestedDuration.toMillis() > 0 && trimmed < w.end
  ? trimmed.toISO()!
  : w.end.toISO()!;
```

This was latent before (anyone could type a long duration by hand); the default
just moved it onto the common path.

## Tests

Seven added to `AvailabilitySearchPage.test.tsx` (10 → 17):

| Test | Pins |
|---|---|
| seeds From with now and To with a day later | the two defaults, under `vi.setSystemTime` |
| seeds the slot duration with one day | days/hours/minutes fields |
| sends the default duration with the search | that the default actually reaches the request |
| lets URL params win over the defaults | `from` / `to` / `duration` still honoured |
| never extends the booked range past the end of the window | the clamp above |
| trims to the requested duration when it fits | that the clamp does not over-clamp |
| renders window times converted to the browser zone | the local-time conversion |

Two details worth keeping:

- The timezone test derives its tenant zone as **local offset + 7 h**
  (`FixedOffsetZone`) rather than naming a real one, so it proves a conversion
  happened whatever zone CI runs in.

  > **Correction (19:53).** This section originally claimed the file had been
  > verified "under both `Europe/Athens` and `America/Los_Angeles`" via the `TZ`
  > environment variable. That run was a no-op: Node does **not** honour `TZ` on
  > Windows (`Intl.DateTimeFormat().resolvedOptions().timeZone` still reported the
  > machine zone). The working mechanism is the `CHRONOS_TEST_ZONE` hook added to
  > `src/test/setup.ts` — see
  > [App-wide browser-local times](20260808_1940_app_wide_local_time.md).
  > Re-verified under that hook in `Asia/Tokyo`, `America/Los_Angeles` and
  > `Pacific/Kiritimati`.

- `useNavigate` is now mocked in this file. The Book destination carries the
  range in its query string, and the range is the thing under test.

## Verification

- `npx vitest run` — **909 tests**, 63 of 64 files green. The one failure is
  `FirmReservationForm.test.tsx` hitting the 5 s timeout, the known parallel-load
  flake documented in the coverage-mode write-up; it passes **8/8 in isolation**
  and was not touched by this change.
- `npm run lint` — **112 errors**, exactly the pre-existing baseline.
- `npx tsc -b` — **zero** new errors against the stashed baseline.

## Follow-up

**The rest of the app still displays the tenant zone.** This change makes
Availability Search local because its own inputs force the issue. Reservations,
Activity, Calendars and the detail pages all still render
`VITE_TENANT_TIMEZONE`. That is now an inconsistency: the same reservation reads
differently on two pages, distinguished only by the offset suffix. Worth a
deliberate decision — either move `formatDateTime`/`formatInterval` in
`src/time/` to local across the board, or add an explicit zone toggle — rather
than letting it spread page by page.
+136

File added.

Preview size limit exceeded, changes collapsed.

Loading