Commit 817805a0 authored by Christos Tranoris's avatar Christos Tranoris
Browse files

fix calendar/blackout dialogs for timezones

parent 7206323e
Loading
Loading
Loading
Loading
+85
Changes for docs/20260830_2011_home_dashboard.md: 85 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Home dashboard built from statistics, with quick-launch navigation

**Date:** 2026-08-30 20:11

## Problem

An authenticated user landing on `/` was redirected to `/pools`
(`AppRoutes.tsx`). `/pools` is gated by `canManagePools` (admin only), so **every
requester and auditor hit "Access Denied" on login** — there was no home screen.
The only statistics view was `/statistics` (`StatisticsDashboard`), a plain text
list reachable only by admin/auditor from the drawer.

## Change

`/` is now a real **home dashboard**: a capability-filtered summary of system
statistics plus quick-launch cards into Pools, Availability, Reservations,
Activity, etc.

### Decisions (from clarifying questions)

1. The dashboard **is `/` for every authenticated user** — replaces the `/pools`
   redirect and fixes the Access-Denied-on-login bug. No `RoleGuard` on the route;
   each tile and card is individually capability-filtered.
2. **Both kept**: the dashboard is a summary + launcher; `/statistics` keeps its
   full per-category breakdown and the dashboard links to it.
3. **Requesters get cards only** — the stat numbers stay gated behind the existing
   `canViewStatistics` (admin/auditor). No permission changes.
4. The quick-launch cards and the sidebar drawer share **one nav-item module**.

### Files

- **`features/shell/navItems.tsx`** (new) — single source of truth for primary
  nav: `NavItem { label, to, icon, capability?, description? }`, the `NAV_ITEMS`
  list (Dashboard first, then the existing 12 in their established order, Purge
  last), and `visibleNavItems(caps)` which filters by capability while preserving
  order. The nav-icon imports moved here out of `Shell.tsx`.
- **`features/shell/Shell.tsx`** — the inline `navItems` array is gone; the drawer
  now renders `visibleNavItems(caps)`, re-attaching the Flags unresolved-count
  badge (still computed in `Shell` from `useFlags()`). `isActive` logic unchanged
  — `to === '/'` highlights only on an exact `/` match.
- **`features/dashboard/DashboardPage.tsx`** (new) — header + greeting; an
  "At a glance" stat grid rendered **only when `caps.canViewStatistics`**
  (`useStatistics()`, `StateView` with the same empty rule as
  `StatisticsDashboard`, an "As of:" caption, six `StatTile`s, and a
  "View full statistics →" link); a "Go to" grid of quick-launch `Card`s from
  `visibleNavItems(caps)` (minus the Dashboard entry itself), always shown.
- **`features/dashboard/StatTile.tsx`** (new) — outlined `Paper`, value in `h4`,
  label in `body2`. Wrapped in a `CardActionArea` link when `to` is set
  (capability held); plain text otherwise, so an auditor sees "Pools: 12" as info
  rather than a dead link.
- **`features/dashboard/index.ts`** (new) — barrel.
- **`features/shell/AppRoutes.tsx`** — `/` → `<DashboardPage />` (no guard).
  Removed the now-doubly-dead `Placeholder` component (lint −1).

## Tests

- `features/shell/navItems.test.tsx` (new) — order (Dashboard first, Availability
  after Pools, Purge last), Dashboard has no `capability`, `visibleNavItems`
  filters while preserving order, requester/auditor subsets.
- `features/dashboard/DashboardPage.test.tsx` (new) — admin/auditor see tiles +
  "As of:"; requester sees neither; a tile is a link with the capability and
  plain text without; quick-launch cards are capability-gated; no card points back
  at `/`; `StateView` loading and empty states.
- `features/shell/Shell.test.tsx` (updated) — mocks `@features/dashboard`; asserts
  the Dashboard nav link exists and is first; requester landing on `/` sees the
  dashboard, not "Access Denied".

Full suite: **1070 tests pass**. `npx eslint src` 107 errors (was 108 — all
pre-existing, per `CLAUDE.md`; this change removed one, the dead `Placeholder`).
`tsc -b` 92 → 89 errors (the new files are clean; the drop is the fixed
`navItems` `badge` union error). `npx vite build` succeeds.

## Verification

1. `npx vitest run src/features/dashboard src/features/shell src/features/statistics`
2. `npm run lint` (baseline unchanged bar the −1)
3. `npx vite build`
4. `npm run dev`:
   - **admin** → `/` shows stat tiles with live numbers + every quick-launch card;
     "Pools"/"Availability" navigate; "View full statistics" opens `/statistics`.
   - **requester** → `/` shows **no** "Access Denied", no stat tiles, cards for
     Reservations / Availability / Activity only.
   - **auditor** → stat tiles visible; the Pools tile is plain text, not a link.
   - Drawer nav lists the same items in the same order with a new "Dashboard"
     entry on top; the Flags badge still shows the unresolved count.
+94
Changes for docs/20260902_1346_calendar_timezone_dropdown.md: 94 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Timezone dropdowns — calendar & blackout dialogs

## Problem

Adding a calendar opens the **New Calendar** dialog, where *Timezone* is
optional. It was a free-text `TextField`, so an operator had to know and type an
exact IANA zone id (`Europe/Athens`) with no guidance, and a typo silently
produced an unusable calendar.

The same dialog exists in **two** places, both fixed:

- `features/calendars/CalendarsPage.tsx` — the standalone Calendars page
- `features/pools/PoolDetailPage.tsx` — the `CalendarsPanel` on the pool
  detail page's *Calendars* tab

The **New / Edit Blackout** dialog (`features/blackouts/BlackoutFormDialog.tsx`)
had the mirror-image problem: it had *no* zone control at all. Its Start / End
fields are `datetime-local` inputs, so the wall-clock an operator types was
silently interpreted in the **browser's** zone — fine when that matches the pool,
wrong (with no warning) when booking a blackout for a resource in another
region.

## Change

Both `CalendarsPage.tsx` and `PoolDetailPage.tsx`'s `CalendarsPanel` — the
*Timezone* field is now a `TextField select` (dropdown):

- **Pre-selected to the operator's browser zone** (`browserTimezone()` →
  `DateTime.local().zoneName`). Previously the field was left blank and the
  payload omitted `timezone`, so the server applied the *tenant* default —
  which is `UTC` — and a calendar created without a second thought had its
  availability windows silently interpreted in UTC rather than the zone the
  operator was thinking in. The dropdown now shows the resolved zone up front,
  and the operator can change it.
- The empty option is kept but relabelled `— Server default —`; picking it
  still omits `timezone` from the payload for anyone who deliberately wants the
  server to decide.
- Followed by a list of zone ids, `UTC` first, the rest sorted.
- `helperText`: "Availability windows are interpreted in this zone. Defaults to
  your browser's." The menu is capped at 320px with its own scroll.

New `features/calendars/timezones.ts`:

- `TIMEZONE_OPTIONS` — the runtime's full IANA list via
  `Intl.supportedValuesOf('timeZone')` (modern browsers, Node ≥ 18) when
  available; a curated ~23-entry fallback otherwise; `UTC` always first.
- `browserTimezone()` — `DateTime.local().zoneName ?? 'UTC'`, via Luxon so it
  honours `Settings.defaultZone` in tests.

The `handleCreate` payload logic is unchanged — `...(newTimezone ? { timezone } : {})`
still drops an empty value; only the input control and its initial value changed.

### Blackouts

`BlackoutFormDialog.tsx` gained a **Time zone** `TextField select` above the
Start / End fields, from the same `TIMEZONE_OPTIONS`:

- First option `— Browser local —` (empty value) — the previous behaviour,
  still the default for a new blackout.
- The chosen zone only governs how the typed wall-clock is turned into an
  instant (`parseInput` → `DateTime.fromISO(value, { zone })`) and how an
  existing blackout's times are shown (`toInputValue` → `dt.setZone(zone)`).
  **No wire field is added** — `CreateBlackoutRequest` / `UpdateBlackoutRequest`
  carry only `startTs` / `endTs` as `date-time`, and the offset in the emitted
  ISO string already encodes the zone. Changing the dropdown does not rewrite
  the input boxes; the string is simply reinterpreted on submit.
- On **edit**, the dropdown seeds from the blackout's own
  `startTs.zoneName` so the fields show the original wall-clock unchanged.

## Tests

`features/calendars/CalendarsPage.test.tsx` — 3 new cases:

- picking `Europe/Athens` from the dropdown submits `timezone: 'Europe/Athens'`
- with nothing touched, the payload carries `timezone: DateTime.local().zoneName`
  (the browser default)
- picking `— Server default —` omits `timezone` from the payload

14 tests pass in the file. `PoolDetailPage`'s `CalendarsPanel` is not currently
under test (not exported), but the control is identical and shares
`TIMEZONE_OPTIONS` / `browserTimezone()`; its 27-test suite still passes.

New `features/blackouts/BlackoutFormDialog.test.tsx` — 4 cases: browser-local
default preserves the wall-clock, a picked zone (`America/New_York`) sets
`zoneName` + the June `-04:00` EDT offset, the option list carries
`— Browser local —` / `UTC` / `Europe/Athens`, and edit mode seeds the zone
from the blackout and shows its original wall-clock. `BlackoutsPage.test.tsx`
gains 1 case (the dropdown renders in the page's dialog). All pass in isolation
(blackouts 17, calendars 13); a whole-suite run on a loaded machine showed
unrelated timeout flakiness that clears on per-file reruns.

Lint clean on all changed files (the blackouts test files keep their
pre-existing baseline of 11 errors, none new). Pre-existing `tsc -b` baseline
errors (documented in CLAUDE.md) are untouched.
+2
Changes for docs/index.md: 2 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -2,6 +2,8 @@

| Date | File | Description |
|---|---|---|
| 2026-09-02 13:46 | [Timezone dropdowns — calendar & blackout dialogs](20260902_1346_calendar_timezone_dropdown.md) | The optional *Timezone* field in the **New Calendar** dialog was free text (typos → unusable calendars) and left blank meant the server's *tenant* default (`UTC`) — so a calendar created without thought had its windows read in UTC, not the operator's zone; it is now a `TextField select` **pre-selected to the browser zone** (`browserTimezone()`), with a `— Server default —` option that still omits `timezone`, in **both** copies of the dialog (`CalendarsPage` and the pool detail page's `CalendarsPanel`); new `features/calendars/timezones.ts` supplies `TIMEZONE_OPTIONS` (from `Intl.supportedValuesOf('timeZone')`, ~23-zone fallback) + `browserTimezone()`. The **New/Edit Blackout** dialog had the opposite gap — no zone control, so typed Start/End wall-clocks were silently read in the browser zone; added a *Time zone* dropdown (same options, `— Browser local —` default) that governs only how the `datetime-local` values are parsed/displayed (`DateTime.fromISO(v,{zone})`), adds **no** wire field, and on edit seeds from the blackout's own zone; +8 tests total |
| 2026-08-30 20:11 | [Home dashboard built from statistics](20260830_2011_home_dashboard.md) | `/` redirected to `/pools` (admin-only), so every requester and auditor hit "Access Denied" on login; `/` is now a real home dashboard with no `RoleGuard` — a capability-filtered "At a glance" stat grid (shown only to `canViewStatistics`, reusing `useStatistics` + `StateView`, linking to the still-intact `/statistics`) over a "Go to" grid of quick-launch cards; the drawer and the cards now render from one shared `features/shell/navItems.tsx` (`NAV_ITEMS` + `visibleNavItems(caps)`, Dashboard first, order preserved), replacing the inline array in `Shell.tsx`; stat tiles are links when the target capability is held and plain text otherwise; removed the doubly-dead `Placeholder` in `AppRoutes` (lint 108 → 107); +16 tests (1070) |
| 2026-08-30 19:35 | [Service Order Ref input on the reservation forms](20260830_1935_serviceorderref_reservation_forms.md) | `FeasibilityRequest.serviceOrderRef` ("originating service order, stamped on the reservation and usable as a cancellation selector") was supported end-to-end — domain draft, `encodeFeasibilityDraft`, the hold/firm hooks, the detail view, the Activity and Purge filters — but had **no input control**, so every reservation booked from the UI carried no service order; added a *Service Order Ref* `TextField` to both `HoldRequestForm` and `FirmReservationForm` (trimmed, conditional-spread into the draft so blank stays absent), a `?serviceOrderRef=` URL prefill via new `read/writeServiceOrderRefParam` in `bookingHandoff.ts` wired through `ReservationsPage`, and hardened `encodeFeasibilityDraft` to run the value through the existing `omitBlank()` helper; +8 tests |
| 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) |
+103
Changes for src/features/blackouts/BlackoutFormDialog.test.tsx: 103 added lines, 0 removed lines.
Original line number Diff line number Diff line
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor, within } from '@testing-library/react';
import { createElement } from 'react';
import { DateTime } from 'luxon';
import type { Blackout } from '@domain';

const createAsync = vi.fn().mockResolvedValue({});
const updateAsync = vi.fn().mockResolvedValue({});

vi.mock('@app/blackouts', () => ({
  useCreateBlackout: () => ({ mutateAsync: createAsync, isPending: false }),
  useUpdateBlackout: () => ({ mutateAsync: updateAsync, isPending: false }),
}));

import { BlackoutFormDialog } from './BlackoutFormDialog';

function renderDialog(props: Partial<Parameters<typeof BlackoutFormDialog>[0]> = {}) {
  return render(
    createElement(BlackoutFormDialog, {
      open: true,
      defaultScope: { type: 'POOL', ref: 'pool-1' },
      onClose: vi.fn(),
      ...props,
    }),
  );
}

function setDateTimes(dialog: HTMLElement, start: string, end: string) {
  const dt = dialog.querySelectorAll('input[type="datetime-local"]');
  fireEvent.change(dt[0], { target: { value: start } });
  fireEvent.change(dt[1], { target: { value: end } });
}

function pickZone(dialog: HTMLElement, name: RegExp | string) {
  fireEvent.mouseDown(within(dialog).getByRole('combobox', { name: /time zone/i }));
  fireEvent.click(screen.getByRole('option', { name }));
}

beforeEach(() => {
  createAsync.mockClear();
  updateAsync.mockClear();
});

describe('BlackoutFormDialog — time zone', () => {
  it('defaults to browser local and sends the instant in the browser zone', async () => {
    renderDialog();
    const dialog = screen.getByRole('dialog');
    setDateTimes(dialog, '2024-06-10T09:00', '2024-06-10T17:00');

    fireEvent.click(within(dialog).getByRole('button', { name: /^create$/i }));

    await waitFor(() => expect(createAsync).toHaveBeenCalled());
    const arg = createAsync.mock.calls[0][0];
    // wall-clock preserved; zone is whatever the test runner's default is
    expect(arg.startTs.hour).toBe(9);
    expect(arg.endTs.hour).toBe(17);
  });

  it('interprets Start and End in the chosen zone', async () => {
    renderDialog();
    const dialog = screen.getByRole('dialog');
    setDateTimes(dialog, '2024-06-10T09:00', '2024-06-10T17:00');
    pickZone(dialog, 'America/New_York');

    fireEvent.click(within(dialog).getByRole('button', { name: /^create$/i }));

    await waitFor(() => expect(createAsync).toHaveBeenCalled());
    const arg = createAsync.mock.calls[0][0];
    expect(arg.startTs.zoneName).toBe('America/New_York');
    expect(arg.startTs.hour).toBe(9);
    expect(arg.endTs.hour).toBe(17);
    expect(arg.startTs.offset).toBe(-4 * 60); // June → EDT
  });

  it('offers a browser-local option and named zones', () => {
    renderDialog();
    const dialog = screen.getByRole('dialog');
    fireEvent.mouseDown(within(dialog).getByRole('combobox', { name: /time zone/i }));
    expect(screen.getByRole('option', { name: /browser local/i })).toBeInTheDocument();
    expect(screen.getByRole('option', { name: 'UTC' })).toBeInTheDocument();
    expect(screen.getByRole('option', { name: 'Europe/Athens' })).toBeInTheDocument();
  });

  it('seeds the zone from an existing blackout on edit', async () => {
    const blackout: Blackout = {
      id: 'blk-9',
      scopeType: 'POOL',
      scopeRef: 'pool-1',
      startTs: DateTime.fromISO('2024-06-10T09:00:00', { zone: 'America/New_York' }),
      endTs: DateTime.fromISO('2024-06-10T17:00:00', { zone: 'America/New_York' }),
      reason: 'maintenance',
      state: 'SCHEDULED',
      createdAt: DateTime.fromISO('2024-01-01T00:00:00Z'),
    };
    renderDialog({ blackout, defaultScope: undefined });
    const dialog = screen.getByRole('dialog');

    expect(within(dialog).getByRole('combobox', { name: /time zone/i })).toHaveTextContent('America/New_York');
    // the datetime inputs show the original wall clock, not a converted one
    const dt = dialog.querySelectorAll('input[type="datetime-local"]');
    expect((dt[0] as HTMLInputElement).value).toBe('2024-06-10T09:00');
  });
});
+30 −8
Changes for src/features/blackouts/BlackoutFormDialog.tsx: 30 added lines, 8 removed lines.
Original line number Diff line number Diff line
@@ -13,6 +13,7 @@ import { DateTime } from 'luxon';
import type { Blackout, ProblemDetail, ScopeType } from '@domain';
import { useCreateBlackout, useUpdateBlackout } from '@app/blackouts';
import { ProblemDetailAlert } from '@feedback';
import { TIMEZONE_OPTIONS } from '../calendars/timezones';

interface Props {
  open: boolean;
@@ -21,16 +22,23 @@ interface Props {
  onClose(): void;
}

function toInputValue(dt: DateTime): string {
  return dt.toISO({ suppressMilliseconds: true })?.slice(0, 16) ?? '';
function toInputValue(dt: DateTime, zone: string): string {
  const zoned = zone ? dt.setZone(zone) : dt;
  return zoned.toISO({ suppressMilliseconds: true })?.slice(0, 16) ?? '';
}

function parseInput(value: string, zone: string): DateTime {
  return DateTime.fromISO(value, zone ? { zone } : undefined);
}

export function BlackoutFormDialog({ open, blackout, defaultScope, onClose }: Props) {
  const isEdit = blackout != null;
  const initialZone = blackout?.startTs.zoneName ?? '';
  const [scopeType, setScopeType] = useState<ScopeType>(blackout?.scopeType ?? defaultScope?.type ?? 'POOL');
  const [scopeRef,  setScopeRef]  = useState(blackout?.scopeRef ?? defaultScope?.ref ?? '');
  const [startTs,   setStartTs]   = useState(blackout ? toInputValue(blackout.startTs) : '');
  const [endTs,     setEndTs]     = useState(blackout ? toInputValue(blackout.endTs) : '');
  const [zone,      setZone]      = useState(initialZone);
  const [startTs,   setStartTs]   = useState(blackout ? toInputValue(blackout.startTs, initialZone) : '');
  const [endTs,     setEndTs]     = useState(blackout ? toInputValue(blackout.endTs, initialZone) : '');
  const [reason,    setReason]    = useState(blackout?.reason ?? '');
  const [formError, setFormError] = useState<ProblemDetail | null>(null);

@@ -44,8 +52,8 @@ export function BlackoutFormDialog({ open, blackout, defaultScope, onClose }: Pr
        await updateMutation.mutateAsync({
          id: blackout.id,
          draft: {
            ...(startTs ? { startTs: DateTime.fromISO(startTs) } : {}),
            ...(endTs   ? { endTs:   DateTime.fromISO(endTs)   } : {}),
            ...(startTs ? { startTs: parseInput(startTs, zone) } : {}),
            ...(endTs   ? { endTs:   parseInput(endTs, zone)   } : {}),
            ...(reason  ? { reason }                            : {}),
          },
        });
@@ -54,8 +62,8 @@ export function BlackoutFormDialog({ open, blackout, defaultScope, onClose }: Pr
        await createMutation.mutateAsync({
          scopeType,
          scopeRef,
          startTs: DateTime.fromISO(startTs),
          endTs:   DateTime.fromISO(endTs),
          startTs: parseInput(startTs, zone),
          endTs:   parseInput(endTs, zone),
          ...(reason ? { reason } : {}),
        });
      }
@@ -97,6 +105,20 @@ export function BlackoutFormDialog({ open, blackout, defaultScope, onClose }: Pr
              />
            </>
          )}
          <TextField
            select
            label="Time zone"
            size="small"
            value={zone}
            onChange={e => setZone(e.target.value)}
            helperText="Start and End are entered in this zone"
            slotProps={{ select: { MenuProps: { PaperProps: { sx: { maxHeight: 320 } } } } }}
          >
            <MenuItem value="">— Browser local —</MenuItem>
            {TIMEZONE_OPTIONS.map(tz => (
              <MenuItem key={tz} value={tz}>{tz}</MenuItem>
            ))}
          </TextField>
          <TextField
            label="Start"
            type="datetime-local"
Loading