Adds frontend for cms page

This commit is contained in:
2026-06-30 23:23:50 +02:00
parent c156107cb1
commit 488ab821a7
38 changed files with 2047 additions and 39 deletions
@@ -0,0 +1,116 @@
# Logical Components — Unit 3: frontend-cms-page
## Overview
```
src/lib/schemas/
├── auth.ts (existing — unchanged)
├── users.ts (NEW — migrated from InviteUserDialog inline)
└── cms.ts (NEW — addCmsInstanceSchema, setStatusSchema)
src/api/
├── types.ts (extended — CmsInstance, CmsInstanceStatus, CreateCmsInstanceRequest,
│ UpdateCmsInstanceStatusRequest, UpdateStatusResult)
├── useCmsInstances.ts (NEW)
├── useAddCmsInstance.ts (NEW)
└── useUpdateCmsInstanceStatus.ts (NEW)
src/components/cms/
├── CmsInstanceList.tsx (NEW)
├── AddCmsInstanceDialog.tsx (NEW)
└── SetStatusDialog.tsx (NEW)
src/components/users/
└── InviteUserDialog.tsx (MODIFIED — schema import + serverError migration)
src/pages/
└── CmsPage.tsx (MODIFIED — replace placeholder with full page)
src/i18n/locales/
├── en/translation.json (MODIFIED — cms.* keys added)
└── nl/translation.json (MODIFIED — cms.* keys added)
src/mocks/
├── cms/handlers.ts (NEW — GET, POST, PUT MSW handlers)
├── browser.ts (MODIFIED — register cms handlers)
└── server.ts (MODIFIED — register cms handlers)
Test files:
├── src/lib/schemas/cms.test.ts (NEW)
├── src/lib/schemas/users.test.ts (NEW)
├── src/api/useCmsInstances.test.ts (NEW)
├── src/api/useAddCmsInstance.test.ts (NEW)
├── src/api/useUpdateCmsInstanceStatus.test.ts (NEW)
├── src/components/cms/AddCmsInstanceDialog.test.tsx (NEW)
├── src/components/cms/SetStatusDialog.test.tsx (NEW)
└── src/pages/CmsPage.test.tsx (MODIFIED — replace placeholder assertions)
```
---
## Component Responsibilities
### `src/lib/schemas/cms.ts` — Validation Logic
| Export | Validates |
|--------|-----------|
| `addCmsInstanceSchema` | name (required, max 255), url (z.string().url()), apiKey (required) |
| `AddCmsInstanceFormData` | Inferred type |
| `setStatusSchema` | status (enum), disableMessage (required when NotAvailable via `.refine()`) |
| `SetStatusFormData` | Inferred type |
### `src/lib/schemas/users.ts` — Migrated Schema
| Export | Source |
|--------|--------|
| `inviteUserSchema` | Migrated from `InviteUserDialog.tsx` inline — no behaviour change |
| `InviteUserFormData` | Inferred type |
### `src/api/useCmsInstances.ts` — Query Hook
| Concern | Implementation |
|---------|---------------|
| Endpoint | `GET /api/v1/CmsInstances` |
| Query key | `['cmsInstances']` |
| Stale time | 30 000 ms |
| Return type | `UseQueryResult<CmsInstance[], Error>` |
### `src/api/useAddCmsInstance.ts` — Mutation Hook
| Concern | Implementation |
|---------|---------------|
| Endpoint | `POST /api/v1/CmsInstances` |
| Body | `CreateCmsInstanceRequest` |
| On success | `invalidateQueries(['cmsInstances'])` |
| Accepts | Optional `onError` callback (caller sets `serverError` state) |
### `src/api/useUpdateCmsInstanceStatus.ts` — Mutation Hook
| Concern | Implementation |
|---------|---------------|
| Endpoint | `PUT /api/v1/CmsInstances/{id}/status` |
| Variables | `{ id: string } & UpdateCmsInstanceStatusRequest` |
| Return | `UpdateStatusResult` |
| On success | `invalidateQueries(['cmsInstances'])` |
| Accepts | Optional `onSuccess` / `onError` callbacks |
### `src/mocks/cms/handlers.ts` — MSW Handlers
| Handler | Behaviour |
|---------|-----------|
| `GET /api/v1/CmsInstances` | Returns in-memory `cmsInstances[]` array |
| `POST /api/v1/CmsInstances` | Pushes new instance to array; returns 201 + created instance |
| `PUT /api/v1/CmsInstances/:id/status` | Updates instance in array; returns `UpdateStatusResult` |
In-memory state initialised with 1-2 seed instances to support development and test scenarios.
---
## Migration Summary
| File | Change | Reason |
|------|--------|--------|
| `InviteUserDialog.tsx` | Import schema from `@/lib/schemas/users` instead of inline | Pattern 1 (centralised schemas) |
| `InviteUserDialog.tsx` | Replace `inviteUser.error` with `useState<string \| null>` | Pattern 2 (consistent error handling) |
| `src/lib/schemas/users.ts` | New file — migrated `inviteSchema` | Pattern 1 |
| `src/lib/schemas/users.test.ts` | New file — tests for `inviteUserSchema` | NFR-FE-04 |
@@ -0,0 +1,156 @@
# NFR Design Patterns — Unit 3: frontend-cms-page
## Pattern 1 — Validation: Centralised Zod Schema Module
**NFR**: NFR-FE-01, NFR-FE-13, NFR-FE-14
**Decision**: Q1 Other — all Zod form schemas live in `src/lib/schemas/`
### Rule
Every form schema in the project is defined in `src/lib/schemas/{domain}.ts` and exported from that module. No schema is defined inline inside a component file.
### New files (this unit)
**`src/lib/schemas/cms.ts`**
```typescript
import { z } from 'zod';
export const addCmsInstanceSchema = z.object({
name: z.string().min(1, 'Name is required').max(255),
url: z.string().url('Must be a valid URL (include http:// or https://)'),
apiKey: z.string().min(1, 'API key is required'),
});
export type AddCmsInstanceFormData = z.infer<typeof addCmsInstanceSchema>;
export const setStatusSchema = z.object({
status: z.enum(['Available', 'NotAvailable', 'Inactive']),
disableMessage: z.string().optional(),
}).refine(
(data) => data.status !== 'NotAvailable' || (data.disableMessage?.trim().length ?? 0) > 0,
{ message: 'Disable message is required when status is Not Available', path: ['disableMessage'] }
);
export type SetStatusFormData = z.infer<typeof setStatusSchema>;
```
### Migration (existing inline schema)
`InviteUserDialog.tsx` currently defines `inviteSchema` inline. As part of this unit, migrate it to **`src/lib/schemas/users.ts`**:
```typescript
import { z } from 'zod';
export const inviteUserSchema = z.object({
email: z.string().email(),
role: z.enum(['Administrator', 'User']),
});
export type InviteUserFormData = z.infer<typeof inviteUserSchema>;
```
`InviteUserDialog.tsx` then imports from `@/lib/schemas/users` and removes the inline definition.
### Test files
- `src/lib/schemas/cms.test.ts` — tests for `addCmsInstanceSchema` (URL strictness, DisableMessage refinement) and `setStatusSchema`
- `src/lib/schemas/users.test.ts` — tests for `inviteUserSchema` (migrated from inline, no behaviour change)
---
## Pattern 2 — Error Handling: Local Server Error State
**NFR**: NFR-FE-15 (field errors via `FieldError`), BR-FE-15/16 (FormErrorBanner for server errors)
**Decision**: Q2 B — all forms use `useState<string | null>(null)` for server-side error messages
### Rule
Every form component that calls a mutation owns a `const [serverError, setServerError] = useState<string | null>(null)` local state. The mutation's `onError` callback translates the error type to an i18n string and sets `serverError`. The `<FormErrorBanner>` receives `serverError`.
This pattern is adopted **project-wide**, including the migration of `InviteUserDialog` (currently using `mutation.error` directly).
### Standard implementation
```typescript
const [serverError, setServerError] = useState<string | null>(null);
const addInstance = useAddCmsInstance({
onError: (err) => {
if (err instanceof ProblemDetailsError && err.status === 409) {
setServerError(t('cms.add.errors.conflict'));
} else if (err instanceof NetworkError) {
setServerError(t('errors.network'));
} else {
setServerError(t('errors.generic'));
}
},
});
// Reset on dialog close
useEffect(() => {
if (!open) {
setServerError(null);
addInstance.reset();
reset();
}
}, [open]);
```
### FormErrorBanner usage
```tsx
<FormErrorBanner
error={serverError !== null ? { message: serverError } : null}
onDismiss={() => setServerError(null)}
/>
```
### Migration (existing InviteUserDialog)
`InviteUserDialog` currently passes `inviteUser.error` directly to `FormErrorBanner`. Migrate to local `useState<string | null>` + `onError` callback. Error message stays generic (`t('errors.generic')`) since invite errors are not status-code-specific.
---
## Pattern 3 — Form Lifecycle: Reset on Close
**NFR**: NFR-FE-01 (consistent patterns)
All dialog forms reset their full state (form values, server error, mutation state) when the dialog closes. Implemented via `useEffect` watching the `open` prop:
```typescript
useEffect(() => {
if (!open) {
setServerError(null);
mutation.reset();
reset(); // react-hook-form reset
}
}, [open]);
```
This pattern is already present in `InviteUserDialog` and is carried forward to `AddCmsInstanceDialog` and `SetStatusDialog`.
---
## Pattern 4 — Security: PasswordField for Credentials
**NFR**: NFR-FE-07, NFR-FE-08
**Decision**: TSD-03
The `apiKey` field in `AddCmsInstanceDialog` uses the existing `PasswordField` component:
```tsx
import { PasswordField } from '@/components/ui/PasswordField';
<PasswordField
id="add-cms-apikey"
label={t('cms.add.apiKeyLabel')}
data-testid="add-cms-apikey"
aria-invalid={errors.apiKey !== undefined}
{...register('apiKey')}
/>
```
`PasswordField` already renders `type="password"` with a show/hide toggle button. No new component needed.
---
## Pattern 5 — Cache Invalidation: Pessimistic Refetch
**NFR**: NFR-FE-12
All mutations invalidate `['cmsInstances']` in `onSuccess` after the server confirms the operation. No optimistic updates. Consistent with `useUsers` / `useChangeRole` patterns in this project.
```typescript
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['cmsInstances'] }),
```
@@ -0,0 +1,41 @@
# NFR Requirements — Unit 3: frontend-cms-page
## Maintainability
| ID | Requirement | Rationale |
|----|-------------|-----------|
| NFR-FE-01 | All new components use `react-hook-form` + `zodResolver` + Zod schemas, consistent with `InviteUserDialog` and `LoginPage` patterns in this project. | Single validation strategy across the entire frontend. |
| NFR-FE-02 | All user-visible strings are externalised in `src/i18n/locales/{lang}/translation.json` under the `cms.*` namespace. No hardcoded UI text in components. | Enables future language additions without code changes. |
| NFR-FE-03 | Components follow the existing Shadcn/UI composition pattern: `Dialog`, `Table`, `Select`, `Badge`, `DropdownMenu` from `@/components/ui/*`. No third-party UI additions. | Keeps the component surface consistent and avoids dependency sprawl. |
## Testability
| ID | Requirement | Rationale |
|----|-------------|-----------|
| NFR-FE-04 | Test scope: **hooks + page integration + individual component tests** (Q2: C). Required test files: `useCmsInstances.test.ts`, `useAddCmsInstance.test.ts`, `useUpdateCmsInstanceStatus.test.ts`, `CmsPage.test.tsx`, `AddCmsInstanceDialog.test.tsx`, `SetStatusDialog.test.tsx`. | Matches precedent set by `InviteUserDialog.test.tsx`. Isolated component tests cover error states and conditional logic (DisableMessage) without needing a full page mount. |
| NFR-FE-05 | MSW handlers cover all three API operations (GET list, POST create, PUT status) with at least one happy-path and one error variant per endpoint. | Handlers must be registered in both `src/mocks/browser.ts` (dev) and `src/mocks/server.ts` (tests). |
| NFR-FE-06 | All interactive elements receive `data-testid` attributes following the existing naming convention (`cms-*`, e.g. `cms-add-button`, `cms-instance-row`, `cms-set-status-submit`). | Required for RTL `getByTestId` selectors in tests. |
## Security
| ID | Requirement | Rationale |
|----|-------------|-----------|
| NFR-FE-07 | The `apiKey` field in `AddCmsInstanceDialog` is rendered as `type="password"` using the existing `PasswordField` component (which includes a show/hide toggle). | Prevents shoulder-surfing of infrastructure credentials during the add flow (Q3: A). Reuses existing `PasswordField.tsx` component. |
| NFR-FE-08 | The `apiKey` value is sent once to the backend on form submit. It is not stored in React state beyond the form lifecycle and is not logged to the console. | Credentials must not leak into browser DevTools' React state inspector or console logs. |
| NFR-FE-09 | `CmsPage` relies on `RoleGuard allowedRoles={['Owner']}` at the route level. No additional role check is implemented inside the page or its components. | Single point of access control; avoids partial/inconsistent guards. See BR-FE-20. |
## Reliability
| ID | Requirement | Rationale |
|----|-------------|-----------|
| NFR-FE-10 | Loading state for `useCmsInstances` is rendered as `<p className="text-sm text-muted-foreground">{t('common.loading')}</p>`, consistent with `UsersPage`. No skeleton component is introduced. | Uniform loading UX without additional dependencies. |
| NFR-FE-11 | Error state for `useCmsInstances` is rendered as `<p className="text-sm text-destructive">{t('errors.generic')}</p>`, consistent with `UsersPage`. | No custom error component needed. |
| NFR-FE-12 | TanStack Query stale time for `useCmsInstances` is 30 000 ms. Cache is invalidated on every successful mutation (add or status update). | Balances freshness with network efficiency; avoids redundant refetches while dialogs are open. |
## Validation
| ID | Requirement | Rationale |
|----|-------------|-----------|
| NFR-FE-13 | URL field in `AddCmsInstanceDialog` uses `z.string().url()` (strict Zod URL validation). The user must supply a fully-qualified URL including protocol (e.g. `http://192.168.1.5:8080`). | Q1: A. Backend validates anyway; client-side strict validation prevents protocol-less entries from ever reaching the API. |
| NFR-FE-14 | `react-hook-form` mode is set to `onTouched` for all new dialogs, consistent with `LoginPage`. Validation messages appear after a field is touched, not on initial render. | Avoids red errors appearing before the user has interacted with the form. |
| NFR-FE-15 | Field-level validation errors are rendered using the existing `<FieldError>` component (`src/components/ui/FieldError.tsx`). | Consistent error presentation across all forms. |
@@ -0,0 +1,50 @@
# Tech Stack Decisions — Unit 3: frontend-cms-page
## Existing stack — no changes
| Layer | Technology | Notes |
|-------|-----------|-------|
| UI components | Shadcn/UI | `Dialog`, `Table`, `Select`, `Badge`, `DropdownMenu` — all already present |
| Styling | Tailwind CSS | `opacity-50` for Inactive rows (BR-FE-04) |
| Data fetching | TanStack Query v5 | `useQuery` + `useMutation` pattern already used by `useUsers` |
| Form state | react-hook-form + zodResolver | Used in `InviteUserDialog`, `LoginPage`, `SetupPage` |
| Schema validation | Zod | `z.string().url()` for URL field (NFR-FE-13) |
| Routing | TanStack Router | `/cms` route already exists; `RoleGuard` already wired |
| i18n | react-i18next | New `cms.*` keys added to EN + NL locales |
| Toasts | Sonner | `toast.success()` / `toast.error()` — already used throughout |
| Testing | Vitest + React Testing Library + MSW | All already configured |
| HTTP client | Custom `api-client` (`NetworkError`, `ProblemDetailsError`) | Same error types used across all existing hooks |
## Decisions made in this unit
### TSD-01 — URL validation: `z.string().url()` (strict)
**Decision**: Use Zod's built-in `z.string().url()` for the URL field.
**Rationale**: Q1: A. Users must enter a fully-qualified URL with protocol. The backend validates anyway, but client-side strict validation stops obviously malformed input early and improves error feedback.
**Implication**: Users entering `192.168.1.5:8080` will see a validation error. They must enter `http://192.168.1.5:8080`.
### TSD-02 — Test scope: hooks + page + component tests
**Decision**: Three test layers:
1. Hook unit tests (`useCmsInstances.test.ts`, `useAddCmsInstance.test.ts`, `useUpdateCmsInstanceStatus.test.ts`) using `renderHook` + MSW server
2. Page integration test (`CmsPage.test.tsx`) covering load, empty state, add flow, status flow
3. Component tests (`AddCmsInstanceDialog.test.tsx`, `SetStatusDialog.test.tsx`) for error states and conditional logic
**Rationale**: Q2: C. Matches `InviteUserDialog.test.tsx` precedent. Dialog component tests are necessary to cover `FormErrorBanner` on HTTP 400 and the `DisableMessage` conditional show/hide (BR-FE-08) without a full page mount.
### TSD-03 — ApiKey field: `PasswordField` with show/hide toggle
**Decision**: Reuse the existing `PasswordField` component (`src/components/ui/PasswordField.tsx`) for the `apiKey` input.
**Rationale**: Q3: A. Hides the credential from shoulder-surfing while allowing the user to reveal it for verification. No new component needed — `PasswordField` already implements the show/hide pattern.
### TSD-04 — Toast content: differentiated on `slaveContactSuccess`
**Decision**: Two distinct toast messages for `PUT /api/v1/CmsInstances/{id}/status`:
- `slaveContactSuccess === true``t('cms.setStatus.successContactedToast')` = "Status updated — cliënt confirmed"
- `slaveContactSuccess === false``t('cms.setStatus.successUnreachableToast')` = "Status saved — cliënt unreachable"
**Rationale**: Q3 FD: B + user terminology preference (no "slave" in UI). Both cases are HTTP 200; the distinction is surfaced via the `UpdateStatusResult.slaveContactSuccess` field from the backend.
### TSD-05 — `FormErrorBanner` component name
The project has both `FormBannerError` (`src/components/ui/FormBannerError.tsx`) and `FormErrorBanner` (`src/components/ui/FormErrorBanner.tsx`). The dialogs use `FormErrorBanner` (as used in `InviteUserDialog`). The `AddCmsInstanceDialog` and `SetStatusDialog` will import from `@/components/ui/FormErrorBanner`.