fix(frontend): align types + UI to backend contract (docs/api.md @ dd5c508)
Some checks failed
ci / backend (lint + typecheck + unit tests) (push) Failing after 0s
ci / frontend (lint + typecheck + build + unit tests) (push) Failing after 0s

Backend pushed the authoritative contract in docs/api.md and tightened
the error envelope via a global HTTPException handler (dd5c508). This
commit folds the frontend onto that contract — every drift flagged by
the code-reviewer MAJOR is closed.

Types (src/types/api.ts)
- User: `id` → `user_id`; `display_name` is `string | null`; add
  `permissions: string[]` and `groups: string[]`; drop `engagement_id`
  and `engagement_name` (not part of CurrentUser).
- Engagement: drop `name`, `client_name` is non-null `string`; status
  enum aligned to `draft | active | closed | archived`; `c2_type` is
  non-null `C2Type`; drop `created_at` (not in EngagementRead v1).
- EngagementCreate body: `client_name` required, plus optional
  `description`, `c2_type`, `start_date`, `end_date`. No `name`.
- Replace ApiError + ApiValidationError with a single uniform envelope:
  `{ error: string, message: string, details?: PydanticErrorItem[] }`,
  matching the new HTTPException handler. PydanticErrorItem is the
  per-field shape on 422 (`{ loc, msg, type }`).

Fetch client (src/lib/api.ts)
- `bodyAsApiError` now recognizes the uniform envelope by shape
  (error+message strings). Anything else returns null so callers fall
  back to a generic message — keeps us robust if the backend ever
  emits a non-JSON response.

Engagements API (src/screens/engagements/engagementsApi.ts)
- Drop the `{ items: [] }` envelope tolerance — backend serves a bare
  `Engagement[]`.
- Hit `/engagements/` with trailing slash explicitly; backend now sets
  `strict_slashes=False` but staying consistent with docs/api.md.

EngagementsPage
- Status tone map switched to the new enum (`draft → pending`,
  `closed → soc`).
- Drop "Name" column. `client_name` is the primary identifier; the
  description column replaces the now-meaningless name field.
- `c2_type` is non-null, so no nullable rendering path.

EngagementCreateDialog
- Drop `name` field. New required field is `client_name`; add a
  `c2_type` select (default `mythic`); brief textarea stays optional.
- `mapValidationErrors` now reads `body.details[*].loc` (last segment
  matches the form field) — direct alignment with the backend's new
  shape after dd5c508.
- 401 still surfaces "Session expirée"; 403 gains a dedicated message;
  other errors fall back to a capitalized backend `message` when
  available, then to a generic French string.

Sidebar
- Display fallback: `user.display_name ?? user.username` (now nullable).
- Drop the `ENG · {engagement_name}` line; show `user.username` (the
  email) as the secondary identity instead.

LoginPage
- Field label "Username" → "Email or username" so RT users with email
  accounts find the field semantically obvious (per docs/api.md note
  on the username/email mapping).

Tests (Vitest, 14 cases, all green)
- Refreshed fixtures to the new shapes (no more `name`, no
  `created_at`, status `draft`, envelopes carry `error`+`message`).
- New 422 test exercises the `details[*].loc` mapping shape.
- New 401 test on the dialog covers the top-of-form alert path.
This commit is contained in:
ux-frontend
2026-05-23 11:14:32 +02:00
parent ec7effcaac
commit 140a34b81e
9 changed files with 256 additions and 151 deletions

View File

@@ -12,14 +12,20 @@ import {
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/Button';
import { ApiClientError } from '@/lib/api';
import type { ApiValidationError } from '@/types/api';
import type { ApiError, C2Type, PydanticErrorItem } from '@/types/api';
import { createEngagement, ENGAGEMENTS_QUERY_KEY } from './engagementsApi';
interface EngagementCreateDialogProps {
onClose: () => void;
}
type FieldErrors = Partial<Record<'name' | 'client_name' | 'description', string>>;
type FieldKey = 'client_name' | 'description' | 'c2_type';
type FieldErrors = Partial<Record<FieldKey, string>>;
const C2_OPTIONS: ReadonlyArray<{ value: C2Type; label: string }> = [
{ value: 'mythic', label: 'Mythic' },
{ value: 'home', label: 'Home (RT-internal)' },
];
/**
* "Arm engagement" dialog.
@@ -35,19 +41,21 @@ type FieldErrors = Partial<Record<'name' | 'client_name' | 'description', string
* - Submit: primary amber Button — the same accent used for RT-only
* actions throughout the app, so the action lineage is obvious.
*
* Behavior:
* - Esc and outside click close (unless the mutation is in flight).
* - Backend 422 Pydantic errors are mapped to per-field inline messages.
* - Other 4xx/5xx surface as a generic top-of-form alert.
* Contract (api.md):
* POST /api/v1/engagements/ with { client_name (required), description?,
* c2_type? (default mythic), start_date?, end_date? }. Backend returns
* the created Engagement on 201, the uniform { error, message, details? }
* envelope on 422 / 4xx. Per-field details on 422 are matched via the
* last segment of `loc`.
*/
export function EngagementCreateDialog({ onClose }: EngagementCreateDialogProps) {
const titleId = useId();
const surfaceRef = useRef<HTMLDivElement>(null);
const firstFieldRef = useRef<HTMLInputElement>(null);
const [name, setName] = useState('');
const [clientName, setClientName] = useState('');
const [description, setDescription] = useState('');
const [c2Type, setC2Type] = useState<C2Type>('mythic');
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
const [topError, setTopError] = useState<string | null>(null);
@@ -60,14 +68,24 @@ export function EngagementCreateDialog({ onClose }: EngagementCreateDialogProps)
onClose();
},
onError: (err) => {
if (err instanceof ApiClientError && err.status === 422 && err.body) {
setFieldErrors(mapValidationErrors(err.body as ApiValidationError));
setTopError(null);
return;
}
if (err instanceof ApiClientError && err.status === 401) {
setTopError('Session expirée. Reconnectez-vous.');
return;
if (err instanceof ApiClientError) {
if (err.status === 422 && err.body?.details) {
setFieldErrors(mapValidationErrors(err.body.details));
setTopError(null);
return;
}
if (err.status === 401) {
setTopError('Session expirée. Reconnectez-vous.');
return;
}
if (err.status === 403) {
setTopError('Action interdite pour ce rôle.');
return;
}
if (err.body?.message) {
setTopError(genericMessage(err.body));
return;
}
}
setTopError('Création impossible. Réessayez dans un instant.');
},
@@ -75,7 +93,6 @@ export function EngagementCreateDialog({ onClose }: EngagementCreateDialogProps)
const isPending = mutation.isPending;
// Focus the first field on open. ESC closes unless a request is in flight.
useEffect(() => {
firstFieldRef.current?.focus();
const onKeyDown = (e: globalThis.KeyboardEvent) => {
@@ -88,11 +105,10 @@ export function EngagementCreateDialog({ onClose }: EngagementCreateDialogProps)
return () => window.removeEventListener('keydown', onKeyDown);
}, [isPending, onClose]);
// Rudimentary focus trap: cycle Tab/Shift+Tab within the dialog.
const handleSurfaceKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
if (e.key !== 'Tab' || !surfaceRef.current) return;
const focusables = surfaceRef.current.querySelectorAll<HTMLElement>(
'input, textarea, button, [tabindex]:not([tabindex="-1"])',
'input, textarea, select, button, [tabindex]:not([tabindex="-1"])',
);
if (focusables.length === 0) return;
const first = focusables[0];
@@ -112,14 +128,14 @@ export function EngagementCreateDialog({ onClose }: EngagementCreateDialogProps)
e.preventDefault();
setFieldErrors({});
setTopError(null);
if (!name.trim()) {
setFieldErrors({ name: 'Nom requis.' });
if (!clientName.trim()) {
setFieldErrors({ client_name: 'Client requis.' });
return;
}
mutation.mutate({
name: name.trim(),
client_name: clientName.trim() || undefined,
description: description.trim() || undefined,
client_name: clientName.trim(),
description: description.trim() || null,
c2_type: c2Type,
});
};
@@ -140,7 +156,6 @@ export function EngagementCreateDialog({ onClose }: EngagementCreateDialogProps)
backgroundColor: 'oklch(5.8% 0.012 247 / 0.78)',
}}
>
{/* Faint scanline texture overlay — reads as "instrument feed paused" */}
<div
aria-hidden="true"
style={{
@@ -172,7 +187,6 @@ export function EngagementCreateDialog({ onClose }: EngagementCreateDialogProps)
animation: 'dialog-in 140ms var(--ease-mech) both',
}}
>
{/* Masthead */}
<div
className="flex items-center justify-between gap-3 px-5 py-3 border-b"
style={{ borderColor: 'var(--line-default)' }}
@@ -199,7 +213,6 @@ export function EngagementCreateDialog({ onClose }: EngagementCreateDialogProps)
</span>
</div>
{/* Amber hairline accent */}
<div
aria-hidden="true"
style={{
@@ -227,24 +240,25 @@ export function EngagementCreateDialog({ onClose }: EngagementCreateDialogProps)
)}
<ConsoleField
label="Engagement name"
label="Client name"
required
value={name}
onChange={setName}
error={fieldErrors.name}
disabled={isPending}
placeholder="OPERATION RUSTED ANCHOR"
ref={firstFieldRef}
mono
/>
<ConsoleField
label="Client"
value={clientName}
onChange={setClientName}
error={fieldErrors.client_name}
disabled={isPending}
placeholder="Démo Client X"
ref={firstFieldRef}
/>
<ConsoleSelect
label="C2 backend"
value={c2Type}
onChange={(v) => setC2Type(v)}
error={fieldErrors.c2_type}
disabled={isPending}
options={C2_OPTIONS}
/>
<ConsoleTextarea
label="Brief"
value={description}
@@ -279,7 +293,6 @@ export function EngagementCreateDialog({ onClose }: EngagementCreateDialogProps)
</form>
</div>
{/* keyframes inlined so the component is self-contained */}
<style>{`
@keyframes dialog-in {
0% { opacity: 0; transform: translate(-50%, calc(-50% + 4px)) translateY(8px); }
@@ -290,17 +303,24 @@ export function EngagementCreateDialog({ onClose }: EngagementCreateDialogProps)
);
}
function mapValidationErrors(body: ApiValidationError): FieldErrors {
function mapValidationErrors(details: PydanticErrorItem[]): FieldErrors {
const out: FieldErrors = {};
for (const item of body.detail) {
for (const item of details) {
const last = item.loc[item.loc.length - 1];
if (last === 'name' || last === 'client_name' || last === 'description') {
if (last === 'client_name' || last === 'description' || last === 'c2_type') {
out[last] = item.msg;
}
}
return out;
}
function genericMessage(body: ApiError): string {
// Capitalize first letter for display while keeping the message verbatim.
const msg = body.message.trim();
if (!msg) return 'Création impossible.';
return msg.charAt(0).toUpperCase() + msg.slice(1);
}
function generateDraftId(): string {
const t = new Date();
const pad = (n: number) => String(n).padStart(2, '0');
@@ -375,11 +395,65 @@ function ConsoleField({
}}
/>
{error && (
<p
id={`${id}-err`}
className="label-system"
style={{ color: 'var(--state-failed)' }}
>
<p id={`${id}-err`} className="label-system" style={{ color: 'var(--state-failed)' }}>
{error}
</p>
)}
</div>
);
}
interface ConsoleSelectProps<T extends string> {
label: string;
value: T;
onChange: (next: T) => void;
options: ReadonlyArray<{ value: T; label: string }>;
disabled?: boolean;
error?: string;
}
function ConsoleSelect<T extends string>({
label,
value,
onChange,
options,
disabled,
error,
}: ConsoleSelectProps<T>): ReactNode {
const id = useId();
return (
<div className="space-y-1.5">
<label htmlFor={id} className="block label-system">
{label}
</label>
<select
id={id}
value={value}
onChange={(e) => onChange(e.target.value as T)}
disabled={disabled}
aria-invalid={error ? 'true' : undefined}
aria-describedby={error ? `${id}-err` : undefined}
className="font-sans"
style={{
width: '100%',
height: 30,
padding: '0 8px',
backgroundColor: 'var(--surface-inset)',
color: 'var(--fg-default)',
border: `1px solid ${error ? 'var(--state-failed)' : 'var(--line-strong)'}`,
borderRadius: 'var(--radius-sm)',
fontSize: 12.5,
outline: 'none',
}}
>
{options.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
{error && (
<p id={`${id}-err`} className="label-system" style={{ color: 'var(--state-failed)' }}>
{error}
</p>
)}
@@ -434,11 +508,7 @@ function ConsoleTextarea({
}}
/>
{error && (
<p
id={`${id}-err`}
className="label-system"
style={{ color: 'var(--state-failed)' }}
>
<p id={`${id}-err`} className="label-system" style={{ color: 'var(--state-failed)' }}>
{error}
</p>
)}