Commit 619a5d67 authored by Christos Tranoris's avatar Christos Tranoris
Browse files

dockerfile, compose and documentation

parent 86e7ed20
Loading
Loading
Loading
Loading
+29
Changes for .dockerignore: 29 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Build artifacts and deps (reinstalled/rebuilt inside the image)
node_modules
dist
*.tsbuildinfo

# VCS and CI
.git
.github

# Local env and secrets (config is injected at runtime, not baked in)
.env
.env.local
.env.*.local

# Tests and tooling not needed in the image
e2e
coverage
playwright-report
test-results

# Editor / OS
.vscode
.idea
.DS_Store
Thumbs.db

# Docs (not needed in the runtime image)
docs
*.md
+110 −102
Changes for CLAUDE.md: 110 added lines, 102 removed lines.
Original line number Diff line number Diff line
@@ -2,144 +2,152 @@

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Status
## What this is

This repository is in the **pre-implementation phase**. Currently only design/requirements documents and the OpenAPI contract exist — no source code has been written yet. All build commands, directory structure, and module descriptions below describe the intended implementation.
Chronos UI — a React 18 + TypeScript single-page app for the ETSI OSL Chronos
resource-reservation service. The application is **implemented**: all epics from
the implementation plan are built (pools, memberships, reservations, availability,
assessment, modification, activity/flags, statistics, inventory, calendars,
blackouts, OpenSlice resource browsing).

Key documents:
- `api-docs.json` — OpenAPI 3.0.1 contract; authoritative wire format (base path `/api/v1`, 34 operations)
- `chronos-ui-requirements-v0.1.md` — Functional requirements R1–R19 + NFRs with EARS-format acceptance criteria
- `chronos-ui-design-v1.0.md` — Hexagonal (ports-and-adapters) architecture, codec boundary, 8 ADRs
- `chronos-ui-implementation-plan-v0.1.md` — 19 epics, ~65 tasks with dependency ordering
Reference documents (kept in repo root):
- `api-docs.json` — OpenAPI 3.0.1 contract; authoritative wire format (base path `/api/v1`). Source for generated types.
- `chronos-ui-requirements-v0.1.md` — Functional requirements R1–R19 + NFRs (EARS format).
- `chronos-ui-design-v1.2.md` — Hexagonal architecture, codec boundary, ADRs.
- `chronos-ui-implementation-plan-v0.2.md` — Epics/tasks with dependency ordering.
- `docs/` — One dated markdown file per completed task (`yyyymmdd_hhmm_title.md`), indexed by `docs/index.md`. Add a new doc + index entry when completing a unit of work.

## Planned Stack
## Stack

React 18 + TypeScript (strict), Vite, TanStack Query, MUI v6, Luxon, `keycloak-js`, openapi-typescript, Vitest, React Testing Library, MSW (Mock Service Worker), Playwright.
React 18, TypeScript (strict), Vite 6, TanStack Query v5, MUI v9 (`@mui/material`),
`@mui/x-date-pickers` (Luxon adapter), `react-big-calendar`, Luxon, `keycloak-js`,
react-router-dom v7. Tests: Vitest 4 + React Testing Library + MSW + Playwright.

## Build Commands (to implement in Epic 1)
> Note: MUI is v9. Trust the installed version in `package.json`.

## Commands

```bash
npm install
npm run gen:types       # Regenerate DTOs from api-docs.json via openapi-typescript
npm run dev              # Vite dev server (http://localhost:5173)
npm run build           # Production build
npm run typecheck       # TypeScript strict check
npm run lint            # ESLint
npm run build            # tsc -b && vite build
npm run typecheck        # tsc --noEmit (strict)
npm run lint             # ESLint — INCLUDES the hexagonal boundary rules
npm run format           # Prettier
npm test                # Vitest unit/component tests
npm run test:watch      # Watch mode
npm run test:coverage   # Coverage report (target ≥80% overall, ≥90% on codec mappers)
npm run e2e             # Playwright E2E tests
npm run gen:types        # Regenerate DTOs: openapi-typescript api-docs.json -> src/adapters/api/generated/schema.d.ts
npm run check:types-drift# Regenerate and fail if the committed schema is out of date
npm test                 # Vitest single run
npm run test:watch       # Vitest watch
npm run test:coverage    # Vitest + V8 coverage (thresholds 80% all metrics; codec mappers expected ≥90%)
npm run e2e              # Playwright (auto-starts dev server)
npm run e2e:ui          # Playwright interactive
```

Run a single test file: `npm test -- path/to/file.test.ts`
Run by pattern: `npm test -- --grep "feasibility"`
Run a single test file: `npm test -- src/path/to/file.test.ts`
Filter by name: `npm test -- -t "feasibility"`

## Architecture
After editing `api-docs.json`, run `npm run gen:types` and commit the regenerated
`schema.d.ts` (CI / `check:types-drift` enforces this).

### Hexagonal (Ports-and-Adapters) with a Codec Boundary
## Architecture — Hexagonal with a codec boundary

```
┌─────────────────────────────────────────┐
│ DRIVING ADAPTERS (UI)                   │
│  React pages + MUI v6 + RoleGuard       │
│  — consume hooks; never see DTOs        │
└────────────────────┬────────────────────┘
                     │
┌────────────────────▼────────────────────┐
│ APPLICATION LAYER (TanStack Query)      │
│  Queries + mutations + cache policy     │
│  Role capabilities + ProblemDetail retry│
└────────────────────┬────────────────────┘
                     │
┌────────────────────▼────────────────────┐
│ DOMAIN (pure TypeScript)                │
│  Pool · Membership · Reservation        │
│  FeasibilityResult union · ProblemDetail│
│  — no HTTP, no React, no wire shapes   │
└────────────────────▲────────────────────┘
                     │
┌────────────────────┴────────────────────┐
│ DRIVEN ADAPTERS                         │
│  ① API adapter + CODEC BOUNDARY         │
│  ② Auth adapter (keycloak-js PKCE)      │
│  ③ Time adapter (Luxon + tenant zone)   │
└─────────────────────────────────────────┘
                     │
              Chronos /api/v1/*
```
Data flows: **React pages → TanStack Query hooks (`app/`) → domain gateway ports →
API adapter + codec (`adapters/api/`) → Chronos `/api/v1`**. The UI and `app/`
layers never see wire shapes; all DTO ↔ domain mapping happens in `adapters/api/`.

### Planned Directory Structure
### Path aliases (defined in `vite.config.ts`, mirrored in tsconfig)
`@domain`, `@app`, `@adapters`, `@features`, `@ui`, `@feedback`, `@time`.
Always import via these aliases, not deep relative paths.

### Layer boundaries — enforced by ESLint (`eslint.config.js`, `eslint-plugin-boundaries`)
- `domain/` may not import from any adapter, `app/`, `features/`, `ui/`, `feedback/`, or `time/` — it is pure.
- `app/`, `features/`, `ui/`, `feedback/` may **not** import `adapters/api/generated` (the raw DTOs).
- Only `adapters/api/` is allowed to touch generated DTOs. Violations fail `npm run lint`.

### Directory map (actual)
```
src/
  domain/          # Pure TS types, enums, validation (no HTTP, no React)
  app/             # TanStack Query hooks: queries/, mutations/, capabilities.ts
  domain/          # Pure TS: entities, primitives, FeasibilityResult union, ports.ts (gateway interfaces), validation
  app/             # One file per aggregate (pools.ts, reservations.ts, …) = TanStack Query hooks. queryKeys.ts is the single key registry. (mutations/ and queries/ dirs exist but are empty.)
  adapters/
    api/           # ⭐ CODEC BOUNDARY — all wire-shape mapping lives here
      generated/   # openapi-typescript output (committed; regenerate with gen:types)
      mappers/     # Duration↔Luxon, CapacityAmount, FeasibilityResult normalization
      gateways/    # Concrete gateway impls (one per domain aggregate)
      transport.ts # HTTP + 401 refresh-and-retry
    auth/          # AuthPort impl (keycloak-js)
    time/          # TimePort impl (Luxon + tenant timezone)
  features/        # Vertical slices: pools/, memberships/, reservations/, activity/, statistics/
  ui/              # Shared MUI wrappers, domain-bound inputs, theme.ts
  feedback/        # ProblemDetailAlert, StateView, ConfirmDialog, treatmentMap.ts
  time/            # Tenant timezone provider, format helpers
    api/
      generated/   # openapi-typescript output (committed). RAW DTOs — only this layer imports them.
      mappers/     # CODEC: primitives, flags, problems, feasibility, pagination, entity mappers
      gateways/    # One createXGateway(transport, zone) factory per aggregate; implements a domain port
      transport.ts # fetch wrapper: bearer injection, query params, ProblemDetail decode, 401 refresh-and-retry
      GatewayContext.tsx # GatewayProvider builds all gateways once; useGateways() hook consumes them
    auth/          # createKeycloakAuthAdapter — implements AuthPort
    time/          # luxonTimeAdapter — Luxon + tenant timezone (TimePort)
  features/        # Vertical slices, one dir per area; *Page.tsx are the routed pages
    shell/         # App chrome: Shell.tsx (drawer + appbar + routing), AppRoutes.tsx, RoleGuard, AuthProvider/AuthContext, capabilities.ts, LandingPage
  ui/              # Shared MUI components (OutcomePanel, StatusChip, CapacityInput, LocalTimeInput, IntervalDisplay) + theme/tokens
  feedback/        # ProblemDetailAlert, StateView, treatmentMap
  time/            # Tenant timezone provider + format helpers
  config.ts        # validateConfig() reads import.meta.env; throws on missing required vars
```

## The Codec Boundary (Requirement 16)
### Conventions
- **Hooks**: each `app/<aggregate>.ts` exports `useX()` queries and `useCreateX/useUpdateX/...` mutations. They call `useGateways()`, read/write via `queryKeys`, and invalidate on success. Follow the existing pattern in `app/pools.ts`.
- **Gateways**: a `createXGateway(transport, zone)` factory returning an object that implements the matching `XGateway` port from `domain/ports`. Wire shapes are decoded/encoded here via `mappers/`.
- **Query keys**: add new keys to `app/queryKeys.ts`; never inline raw arrays.
- **New page**: create `features/<area>/XPage.tsx`, export from the feature `index.ts`, then add a `<Route>` wrapped in `<RoleGuard capability="...">` in `shell/AppRoutes.tsx` and a nav entry in `shell/Shell.tsx`.

This is the architectural load-bearing wall. All wire-shape quirks are resolved in `adapters/api/mappers/` — views and hooks only ever see clean domain types.
## The codec boundary (the load-bearing wall)

Key mappings (implement in Epic 4):
All wire-shape quirks resolve in `adapters/api/mappers/`. Key mappings:

| Wire shape | Domain type | Rule |
|---|---|---|
| `Duration {seconds, nano}` | Luxon `Duration` | `Duration.fromObject({seconds, milliseconds: nano/1e6})`; absent → effective default |
| `LocalTime {hour,minute,second,nano}` | `{hour, minute}` | Read hour/minute; write back with `second:0, nano:0` |
| `CapacityAmount {quantity, unit}` | `CapacityAmount` | Keep nested; never flatten |
| `conflictFlags: string` | `ConflictFlag[]` | Provisional: treat whole string as single token (OQ-UI-5) |
| `date-time` (ISO-8601) | Luxon `DateTime` | `DateTime.fromISO(s, {zone: tenantZone})`; write `dt.toISO()` |
| HTTP status + `FeasibilityResponse.outcome` | `FeasibilityResult` (discriminated union) | `201 FEASIBLE` → arm 1; `200 alt/not-feasible` → arm 2–3; `409 OVERLAP/CAPACITY` → arm 4 |
| `Page*` response envelopes | `Page<T>` | Three envelope shapes; normalized per §5.3 of design doc |
| `Duration {seconds, nano}` / ISO-8601 duration | Luxon `Duration` | see `mappers/primitives` + duration ISO codec; absent → effective default |
| `LocalTime {hour,minute,second,nano}` | `{hour, minute}` | read hour/minute; write back `second:0, nano:0` |
| `CapacityAmount {quantity, unit}` | `CapacityAmount` | keep nested; never flatten |
| `conflictFlags: string` | `ConflictFlag[]` | provisional: whole string as one token (OQ-UI-5) |
| `date-time` ISO-8601 | Luxon `DateTime` | `fromISO(s, {zone: tenantZone})`; write `dt.toISO()` |
| HTTP status + `outcome` | `FeasibilityResult` (discriminated union) | `201 FEASIBLE` / `200 alt|not-feasible` / `409 OVERLAP|CAPACITY`. HTTP status never reaches the UI. |
| `Page*` envelopes | `Page<T>` | normalized in `mappers` (multiple envelope shapes) |

The `FeasibilityResult` discriminated union (FEASIBLE / FEASIBLE\_WITH\_ALTERNATIVES / NOT\_FEASIBLE / CONFLICT) is the central domain type — the `OutcomePanel` view switches on it; HTTP status codes never reach the UI layer.
`FeasibilityResult` (FEASIBLE / FEASIBLE_WITH_ALTERNATIVES / NOT_FEASIBLE / CONFLICT)
is the central domain union; `ui/OutcomePanel` switches on it.

## Auth & Security
## Auth & roles

- Keycloak PKCE authorization-code flow via `keycloak-js`
- Tokens stored in memory only (never `localStorage`) — Req 1.6
- Single 401 refresh-and-retry in `transport.ts`; re-auth on second 401 — ADR-3
- Role derivation from JWT claims; `RoleGuard` enforces per-feature access
- Keycloak is initialized **once** in `main.tsx` before React renders (avoids StrictMode double-`init` consuming the PKCE code). The adapter wraps that instance.
- PKCE auth-code flow; tokens in memory only (never `localStorage`/`sessionStorage`).
- Single 401 refresh-and-retry in `transport.ts`.
- Roles come from JWT: `chronos.admin`, `chronos.auditor`, `chronos.requester`.
- `features/shell/capabilities.ts#deriveCapabilities()` maps roles → boolean capabilities; `RoleGuard` and the nav use them. Add a new gated feature by adding a capability there.

## Environment Variables (Epic 1.4)
## Environment variables (validated in `config.ts`)

```
VITE_API_BASE_URL=http://localhost:8888
VITE_KEYCLOAK_REALM=...
VITE_KEYCLOAK_CLIENT_ID=...
VITE_KEYCLOAK_SERVER_URL=...
VITE_TENANT_TIMEZONE=UTC
VITE_API_BASE_URL=http://localhost:8888   # required
VITE_KEYCLOAK_URL=http://localhost:8080   # required  (NOT *_SERVER_URL)
VITE_KEYCLOAK_REALM=chronos               # required
VITE_KEYCLOAK_CLIENT_ID=chronos-ui        # required
VITE_TENANT_TIMEZONE=UTC                  # optional, defaults to UTC
```
Missing a required var throws at startup. See `.env.example`.

`config.ts#resolveEnv()` overlays **runtime** config (`window.__CHRONOS_CONFIG__`,
set by `docker-entrypoint.sh` rewriting `public/config.js`) on top of Vite's
build-time values — so the Docker image is configured per-environment at
container start without a rebuild. `index.html` loads `/config.js` before the app
bundle. In dev/tests the placeholder is empty and values fall back to `.env`.
Keep `buildTimeEnv` using dotted `import.meta.env.X` access (Vite static replace).

## Testing Strategy
## Containerization & build gotcha

- **Codec unit tests** (front-loaded, Epic 4): round-trips, absent-field defaults, unknown enum tokens
- **Integration tests** (MSW): all 34 API operations with contract-shaped responses; exercises real adapter + codec
- **E2E tests** (Playwright): admin push+reserve, requester feasibility→firm, auditor statistics, sign-out
- Coverage targets: ≥80% overall; ≥90% on `adapters/api/mappers/`
- Fixtures derived from `api-docs.json` schema examples to stay contract-anchored
- `Dockerfile` (multi-stage Node→nginx), `docker-compose.yml`, `nginx.conf` (SPA fallback + `/healthz`), `docker-entrypoint.sh`. See `docs/guides/operations-guide.md` §3a.
- **`npm run build` (`tsc -b && vite build`) currently fails** on pre-existing MUI v9 theme typing errors (`colorSchemes`/`colorSchemeSelector`/`theme.vars` in `src/ui/theme.ts` + theme/token tests) — unrelated to most changes. `vite build` alone succeeds, so the Docker image runs `npx vite build` directly. `npm run typecheck` is a **no-op** (root `tsconfig.json` has `files: []`); the real type gate is `tsc -b`. Fix the theme types to unbreak `npm run build`.

## Open Questions (resolve in Epic 19)
## Testing

- **OQ-UI-5**: `conflictFlags` delimiter — provisional: whole string as one token
- **OQ-UI-7**: Tenant timezone source — provisional: `VITE_TENANT_TIMEZONE` env var
- **OQ-UI-8**: `fieldErrors` array element shape — untyped in v1.1 contract
- **OQ-UI-9**: Extract-override wire format — query param vs request body
- **OQ-UI-3**: Statistics fields missing from v1.1 schema — dashboard omits, does not fabricate
- MSW intercepts all API calls (`src/test/server.ts`); no real backend needed for unit/component tests. Vitest config inlines `@mui` deps (MUI v9 `.mjs` subpath imports break native ESM resolution) — keep that `server.deps.inline` setting.
- Codec mappers have the heaviest unit coverage (round-trips, absent-field defaults, unknown enum tokens).
- E2E journeys live in `e2e/journeys.spec.ts` (Playwright, Chromium).

## Implementation Order
## Open questions (provisional decisions, see design doc §Open Questions)

Follow the epic dependency order in `chronos-ui-implementation-plan-v0.1.md`. The codec boundary (Epic 4) must be completed before any feature epics (7–17) because it establishes the mappers that all features depend on. Epic 2 (API type generation) must precede Epic 4.
- **OQ-UI-5**: `conflictFlags` delimiter → treat whole string as one token.
- **OQ-UI-7**: tenant timezone source → `VITE_TENANT_TIMEZONE` env (build-time, ADR-5).
- **OQ-UI-8/9**: `fieldErrors` element shape / extract-override wire format — untyped in contract.
- **OQ-UI-3**: statistics fields missing from schema → dashboard omits, never fabricates.
+37
Changes for Dockerfile: 37 added lines, 0 removed lines.
Original line number Diff line number Diff line
# syntax=docker/dockerfile:1

# ── Stage 1: build the static SPA ───────────────────────────────────────────
# No VITE_* values are baked in here — configuration is injected at runtime by
# the entrypoint (see docker-entrypoint.sh), so one image serves any environment.
FROM node:20-alpine AS build
WORKDIR /app

# Install dependencies against the lockfile first for better layer caching.
COPY package.json package-lock.json ./
RUN npm ci

# Build (bundle only). We invoke `vite build` directly rather than `npm run
# build`, which also runs `tsc -b` as a type-check gate. Type-checking belongs
# in CI/dev, not in the image build; keeping it out means a type error doesn't
# block producing a deployable artifact. Run `npm run build` / `npm run lint` in
# CI to gate merges.
COPY . .
RUN npx vite build

# ── Stage 2: serve with nginx ───────────────────────────────────────────────
FROM nginx:1.27-alpine AS runtime

# SPA routing + no-cache for the config/index entry points.
COPY nginx.conf /etc/nginx/conf.d/default.conf

# Static assets.
COPY --from=build /app/dist /usr/share/nginx/html

# Entrypoint writes /usr/share/nginx/html/config.js from env, then runs nginx.
COPY docker-entrypoint.sh /docker-entrypoint.d/40-chronos-config.sh
RUN chmod +x /docker-entrypoint.d/40-chronos-config.sh

EXPOSE 80

# The nginx base image runs every executable script in /docker-entrypoint.d/
# before starting nginx, so we reuse its default ENTRYPOINT/CMD.
+85 −53

File changed.

Preview size limit exceeded, changes collapsed.

+3 −3
Changes for chronos-ui-design-v1.2.md: 3 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -44,7 +44,7 @@ API base URL and Keycloak config are read from runtime env. The **tenant timezon
```
┌──────────────────────────────────────────────────────────────────────┐
│ DRIVING ADAPTERS (UI)                                                  │
│   React pages & components (MUI v6) · routing · route guards           │
│   React pages & components (MUI v9) · routing · route guards           │
│   — consume application hooks only; never call fetch or see DTOs       │
└───────────────────────────────┬──────────────────────────────────────┘
                                 │ calls
@@ -119,7 +119,7 @@ sequenceDiagram

### 2.4 Technology decisions (summary; ADRs in §8)

React 18 + TypeScript, Vite, TanStack Query, MUI v6 (CSS theme variables enabled), Luxon, `keycloak-js`, `openapi-typescript`, MSW, Playwright, Vitest + React Testing Library.
React 18 + TypeScript, Vite, TanStack Query, MUI v9 (CSS theme variables enabled), Luxon, `keycloak-js`, `openapi-typescript`, MSW, Playwright, Vitest + React Testing Library.

### 2.5 Synchronous operation model

@@ -560,7 +560,7 @@ No optimistic updates; reflect server result incl `cancelPending`/`inconsistent`
**Rationale:** matches the operator's model and keeps statistics restricted per R17.3/R2.3 — the v1.1 relaxation is reverted, so no requirements change is needed.
**Implications:** requester-only users get the full UI minus the statistics view; the `useStatistics` query is not enabled for them and the route is guarded.

### ADR-10: MUI v6 theming via CSS variables, dark mode, neutral AA palette (new)
### ADR-10: MUI v9 theming via CSS variables, dark mode, neutral AA palette (new)
**Decision:** `createTheme({ cssVariables: { cssVarPrefix: 'chronos' }, colorSchemes: { light: true, dark: true } })`; two-tier primitive→semantic tokens with TS module augmentation; neutral WCAG-AA default palette; status never color-only; Emotion runtime (not Pigment CSS); theme factory lives in the `ui` module.
**Rationale:** CSS variables give token visibility, plain-CSS reuse, and flash-free dark mode; dark mode is in scope; a neutral AA palette is brand-agnostic and accessible by default and easy to re-skin via primitives. Pigment CSS is alpha and brings no RSC benefit to a Vite SPA.
**Implications:** a user-facing dark/light toggle in the shell; components consume `theme.vars`/semantic tokens only; contrast is a token-level test target.
Loading