Adds user management

This commit is contained in:
2026-06-22 21:14:22 +02:00
parent 5331be4279
commit 6976eb4337
40 changed files with 3392 additions and 146 deletions
@@ -0,0 +1,118 @@
# Business Logic Model — Unit 5: User Management
## Process Overview
Unit 5 covers three main user flows:
1. **Invite User** — two-step dialog: fill in email + role → copy generated invite link
2. **Copy Pending Invite Link** — one-click copy from the user table row for pending invitations
3. **Change Role** — dropdown action in the user table row; optimistic or confirmed update
---
## Flow 1 — Invite User
```mermaid
sequenceDiagram
box rgba(246,224,94,0.4) Browser
participant U as Gebruiker
participant FE as UsersPage
participant DLG as InviteUserDialog
end
box rgba(99,179,237,0.4) Backend
participant API as Users API
end
U->>FE: Click Invite User button
FE->>DLG: Open dialog at Step 1
DLG-->>U: Show form with email and role fields
U->>DLG: Enter email and select role
U->>DLG: Submit form
DLG->>DLG: Validate with zod schema
alt Validation fails
DLG-->>U: Show inline field errors
else Validation passes
DLG->>API: POST /api/v1/Users/invite with email and role
alt API error
API-->>DLG: 400 or 409 error response
DLG-->>U: Show FormErrorBanner with error message
else API success
API-->>DLG: 200 with inviteLink
DLG->>DLG: Advance to Step 2
DLG-->>U: Show invite link with Copy button
U->>DLG: Click Copy to clipboard
DLG->>FE: Invalidate useUsers query
FE->>API: GET /api/v1/Users
API-->>FE: Updated user list with new pending user
FE-->>U: Table refreshed
U->>DLG: Close dialog
end
end
```
Text alternative: User opens dialog, fills email and role, submits; on success the backend returns an invite link shown in Step 2 with a copy button; closing the dialog triggers a user list refresh.
---
## Flow 2 — Copy Pending Invite Link from Table Row
```mermaid
sequenceDiagram
box rgba(246,224,94,0.4) Browser
participant U as Gebruiker
participant Row as UserTableRow
end
U->>Row: Click copy-link icon on pending user row
Row->>Row: Read inviteLink from UserListItem
Row->>Row: navigator.clipboard.writeText with inviteLink
Row-->>U: Show toast "Invite link copied to clipboard"
```
Text alternative: Copy invite link is a client-side operation — the link is already in the fetched user list (inviteLink field); no API call required.
---
## Flow 3 — Change User Role
```mermaid
sequenceDiagram
box rgba(246,224,94,0.4) Browser
participant U as Gebruiker
participant Row as UserTableRow
participant FE as UsersPage
end
box rgba(99,179,237,0.4) Backend
participant API as Users API
end
U->>Row: Open role dropdown for a user
Row-->>U: Show available roles based on requester role
U->>Row: Select new role
Row->>API: PUT /api/v1/Users/{userId}/role with newRole
alt API error
API-->>Row: 403 or 409 error
Row-->>U: Show toast with error message
else API success
API-->>Row: 200 OK
Row->>FE: Invalidate useUsers query
FE->>API: GET /api/v1/Users
API-->>FE: Updated user list with new role
FE-->>U: Table row updated with new role badge
end
```
Text alternative: User selects a new role from a dropdown in the table row; on backend success the user list is re-fetched to reflect the updated role.
---
## useInvitation.ts Migration (supporting InviteCompletePage)
`useInvitation.ts` was created in Unit 2 with raw `useState`/`useEffect`. In Unit 5 it is migrated to TanStack Query for consistency. This does not change the behavior of `InviteCompletePage` — only the internal implementation of the hooks changes.
| Hook | Before (Unit 2) | After (Unit 5) |
|---|---|---|
| `useValidateInvitation(token)` | useState + useEffect | useQuery (auto-fetches on mount) |
| `useCompleteInvitation()` | useState + useCallback | useMutation |
| Types | Local interfaces in useInvitation.ts | Shared types from types.ts |
Local types (`InvitationValidationResponse`, `InvitationCompleteRequest`, `InvitationCompleteResponse`) are removed and replaced with `InvitationValidation` and `InviteCompleteRequest` from `types.ts`.
@@ -0,0 +1,114 @@
# Business Rules — Unit 5: User Management
## Rule Index
| ID | Rule | Enforced In |
|---|---|---|
| BR-U5-01 | Only Owner and Administrator can access UsersPage | Frontend (RoleGuard), Backend (AdminOnly policy) |
| BR-U5-02 | Owner role cannot be assigned via invitation | Frontend (role selector), Backend |
| BR-U5-03 | At least one Owner must exist at all times | Backend (change role endpoint) |
| BR-U5-04 | Owner can change any user's role (subject to BR-U5-03) | Backend (change role endpoint) |
| BR-U5-05 | Administrator can only promote User to Administrator | Backend (change role endpoint) |
| BR-U5-06 | Copy invite link action is only shown for users where invitationPending = true | Frontend (conditional rendering) |
| BR-U5-07 | Invite form requires valid email format and role selection | Frontend (zod validation) |
| BR-U5-08 | An email already registered cannot be invited again | Backend (invite endpoint validation) |
---
## Decision Flow 1 — Invite User Authorization
```mermaid
graph TD
invite_req["Invite User request"]
check_access{"Requester is Owner\nor Administrator?"}
check_email{"Email has valid format?"}
check_registered{"Email already registered?"}
check_role{"Role is Administrator\nor User?"}
success_invite["Create invitation token\nReturn inviteLink"]
deny_403["403 Forbidden"]
err_email["Validation error\nInvalid email format"]
err_registered["Validation error\nEmail already in use"]
err_role["Validation error\nOwner role cannot be invited"]
invite_req --> check_access
check_access -->|No| deny_403
check_access -->|Yes| check_email
check_email -->|No| err_email
check_email -->|Yes| check_registered
check_registered -->|Yes| err_registered
check_registered -->|No| check_role
check_role -->|Owner| err_role
check_role -->|Administrator or User| success_invite
classDef start_node fill:#2196F3,stroke:#0d47a1,stroke-width:1px,color:#000
classDef decision_node fill:#FF9800,stroke:#e65100,stroke-width:1px,color:#000
classDef success_node fill:#4CAF50,stroke:#2e7d32,stroke-width:1px,color:#000
classDef error_node fill:#F44336,stroke:#b71c1c,stroke-width:1px,color:#000
class invite_req start_node
class check_access,check_email,check_registered,check_role decision_node
class success_invite success_node
class deny_403,err_email,err_registered,err_role error_node
```
Text alternative: Invite request checked for requester access, email validity, registration status, and role — only valid Administrator/User invites proceed; all others are blocked.
---
## Decision Flow 2 — Change Role Authorization
```mermaid
graph TD
change_req["Change Role request\nPUT /Users/{userId}/role"]
req_role{"Requester role?"}
deny_user["403 Forbidden\nUser role cannot change roles"]
admin_target{"Target user's current role?"}
deny_admin["403 Forbidden\nAdmin cannot change Owner or Admin roles"]
owner_check{"Would this leave\nzero Owners?"}
deny_last["Blocked\nAt least 1 Owner required"]
success_change["Update user role\nReturn 200 OK"]
change_req --> req_role
req_role -->|User| deny_user
req_role -->|Administrator| admin_target
req_role -->|Owner| owner_check
admin_target -->|Owner or Administrator| deny_admin
admin_target -->|User| success_change
owner_check -->|Yes| deny_last
owner_check -->|No| success_change
classDef start_node fill:#2196F3,stroke:#0d47a1,stroke-width:1px,color:#000
classDef decision_node fill:#FF9800,stroke:#e65100,stroke-width:1px,color:#000
classDef success_node fill:#4CAF50,stroke:#2e7d32,stroke-width:1px,color:#000
classDef error_node fill:#F44336,stroke:#b71c1c,stroke-width:1px,color:#000
class change_req start_node
class req_role,admin_target,owner_check decision_node
class success_change success_node
class deny_user,deny_admin,deny_last error_node
```
Text alternative: Role change checked for requester level — User is blocked; Administrator can only change User-role targets; Owner can change any role, blocked only if it would leave zero Owners.
---
## Frontend Validation Rules (InviteUserForm — zod schema)
```typescript
const inviteUserSchema = z.object({
email: z.string().email({ message: 'Valid email address required' }),
role: z.enum(['Administrator', 'User'], {
required_error: 'Role selection is required',
}),
});
```
## Frontend Access Control Rules (RoleGuard / conditional rendering)
| Element | Visibility condition |
|---|---|
| UsersPage route | `role === 'Owner' \|\| role === 'Administrator'` |
| Invite User button | Always visible on UsersPage (same role requirement as page) |
| Copy invite link action | `user.invitationPending === true` |
| Change role dropdown | Visible to all UsersPage visitors; available target roles differ by requester role (see BR-U5-04, BR-U5-05) |
| Owner option in role dropdown | Only shown when requester is Owner |
@@ -0,0 +1,92 @@
# Domain Entities — Unit 5: User Management
## Overview
Unit 5 introduces user listing, invitation management, and role changes. Two new backend endpoints are required: `GET /api/v1/Users` (list with invitation state) and `PUT /api/v1/Users/{userId}/role` (role assignment). The frontend extends `types.ts` with new interfaces for these operations.
## Entity Diagram
```mermaid
graph LR
UserListItem["UserListItem\nid, email, name, role\nisActive, createdAt\ninvitationPending, inviteLink"]
UserRole["UserRole\nOwner, Administrator, User"]
InviteUserRequest["InviteUserRequest\nemail, role"]
InviteUserResponse["InviteUserResponse\ninviteLink"]
ChangeRoleRequest["ChangeRoleRequest\nnewRole"]
UserListItem -->|has role| UserRole
InviteUserRequest -->|assigns role| UserRole
ChangeRoleRequest -->|assigns| UserRole
classDef entity fill:#2196F3,stroke:#0d47a1,stroke-width:1px,color:#000
classDef request fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000
classDef enumType fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000
class UserListItem entity
class InviteUserRequest,InviteUserResponse,ChangeRoleRequest request
class UserRole enumType
```
Text alternative: UserListItem (blauw) heeft een UserRole enum (geel); InviteUserRequest en ChangeRoleRequest (groen) wijzen een UserRole toe.
## Field Descriptions
### UserListItem — GET /api/v1/Users response item
| Field | Type | Description |
|---|---|---|
| id | string (UUID) | Unique user identifier |
| email | string | User's email address |
| name | string | Display name (DisplayName ?? Email fallback, consistent with AuthResponse) |
| role | UserRole | Current role: Owner, Administrator, or User |
| isActive | bool | Whether the account is active |
| createdAt | string (ISO 8601) | Account creation timestamp |
| invitationPending | bool | True when the user has not yet completed invitation setup |
| inviteLink | string \| null | Full invite URL for pending users; null for active accounts |
### InviteUserRequest — POST /api/v1/Users/invite
| Field | Type | Description |
|---|---|---|
| email | string | Email address of the invitee |
| role | 'Administrator' \| 'User' | Role to assign — Owner is excluded by business rule |
### InviteUserResponse — POST /api/v1/Users/invite response
| Field | Type | Description |
|---|---|---|
| inviteLink | string | Relative URL for the invitation (e.g. `/invite/complete?token=...`) |
### ChangeRoleRequest — PUT /api/v1/Users/{userId}/role
| Field | Type | Description |
|---|---|---|
| newRole | UserRole | Role to assign to the target user |
## Type Extensions — frontend/src/api/types.ts
The existing `User` type covers the logged-in session user. Unit 5 adds:
```typescript
// User item returned by GET /api/v1/Users
export interface UserListItem extends User {
createdAt: string; // ISO 8601
invitationPending: boolean;
inviteLink: string | null;
}
// POST /api/v1/Users/invite
export interface InviteUserRequest {
email: string;
role: Exclude<UserRole, 'Owner'>; // Owner cannot be invited
}
export interface InviteUserResponse {
inviteLink: string;
}
// PUT /api/v1/Users/{userId}/role
export interface ChangeRoleRequest {
newRole: UserRole;
}
```
@@ -0,0 +1,295 @@
# Frontend Components — Unit 5: User Management
## Component Hierarchy
```mermaid
graph TD
role_guard["RoleGuard\n(Owner or Admin only)"]
users_page["UsersPage\n(pages/UsersPage.tsx)"]
page_header["Page Header\nh1 + Invite button"]
user_table["UserTable\n(shadcn Table)"]
table_row["UserTableRow\n(×n per user)"]
row_actions["RowActionsMenu\n(shadcn DropdownMenu)"]
copy_link["CopyInviteLinkAction\n(if invitationPending)"]
change_role["ChangeRoleAction\n(role-filtered options)"]
invite_dialog["InviteUserDialog\n(shadcn Dialog)"]
step1["Step1InviteForm\n(email + role select)"]
step2["Step2ShareLinkView\n(link + copy button)"]
role_guard --> users_page
users_page --> page_header
users_page --> user_table
users_page --> invite_dialog
page_header --> invite_dialog
user_table --> table_row
table_row --> row_actions
row_actions --> copy_link
row_actions --> change_role
invite_dialog --> step1
invite_dialog --> step2
classDef guard_node fill:#FF9800,stroke:#e65100,stroke-width:1px,color:#000
classDef page_node fill:#2196F3,stroke:#0d47a1,stroke-width:1px,color:#000
classDef table_node fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000
classDef action_node fill:#9C27B0,stroke:#4a148c,stroke-width:1px,color:#000
classDef dialog_node fill:#4CAF50,stroke:#2e7d32,stroke-width:1px,color:#000
class role_guard guard_node
class users_page,page_header page_node
class user_table,table_row table_node
class row_actions,copy_link,change_role action_node
class invite_dialog,step1,step2 dialog_node
```
Text alternative: RoleGuard wraps UsersPage; the page contains a header (with Invite button), a UserTable (rows with DropdownMenu actions), and an InviteUserDialog (Step 1 form → Step 2 share link).
---
## Component Specifications
### UsersPage — `pages/UsersPage.tsx`
**Purpose**: Main user management page. Fetches user list, renders table and invite dialog.
**State**:
- `dialogOpen: boolean` — controls InviteUserDialog visibility
- `dialogStep: 1 | 2` — which dialog step is shown
- `generatedLink: string | null` — invite link returned after successful invite
**API integration**:
- `useUsers()` — fetches user list on mount; staleTime: 30s
**Render structure**:
- RoleGuard enforced at router level (`router.tsx`)
- Page title (`t('nav.users')`)
- "Invite User" button (opens dialog)
- UserTable with fetched data
- InviteUserDialog (controlled by state above)
---
### UserTable (inline in UsersPage or extracted component)
**Purpose**: Renders the shadcn Table with one row per UserListItem.
**Columns**:
| Column | Field | Notes |
|---|---|---|
| Name | `user.name` | Plain text |
| Email | `user.email` | Plain text |
| Role | `user.role` | Colored badge (Owner=red, Admin=orange, User=blue) |
| Status | `user.isActive` + `user.invitationPending` | "Active", "Inactive", or "Pending invite" badge |
| Created | `user.createdAt` | Formatted as locale date string |
| Actions | — | DropdownMenu (see RowActionsMenu) |
**Props**:
```typescript
interface UserTableProps {
users: UserListItem[];
currentUser: User; // from AuthContext — for role-based action filtering
onRoleChange: (userId: string, newRole: UserRole) => void;
}
```
---
### RowActionsMenu — DropdownMenu per row
**Purpose**: Contextual actions per user row.
**Actions**:
1. **Copy invite link** — visible only when `user.invitationPending === true`; calls `navigator.clipboard.writeText(user.inviteLink!)` and shows a toast
2. **Change role** — opens an inline role picker (sub-menu or inline select); available roles depend on requester:
- Requester is Owner: all three roles shown (Owner, Administrator, User)
- Requester is Administrator: only User → Administrator promotion (target must be User role)
**Props**:
```typescript
interface RowActionsMenuProps {
user: UserListItem;
currentUser: User;
onRoleChange: (userId: string, newRole: UserRole) => void;
}
```
---
### InviteUserDialog — `components/users/InviteUserDialog.tsx`
**Purpose**: Two-step modal dialog for inviting a new user.
**Props**:
```typescript
interface InviteUserDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
```
**Step 1 — InviteUserForm**:
- Fields: email (text input), role (Select: Administrator | User)
- Validation: zod schema (see business-rules.md)
- On submit: calls `useInviteUser()` mutation
- On success: transitions to Step 2 with the returned inviteLink
- On error: shows `FormErrorBanner` with backend error message
**Step 2 — Step2ShareLinkView**:
- Read-only text input displaying the full invite link
- "Copy to clipboard" button (copies link, shows toast)
- "Close" button (closes dialog, triggers `useUsers` query invalidation)
**State** (internal):
```typescript
const [step, setStep] = useState<1 | 2>(1);
const [inviteLink, setInviteLink] = useState<string | null>(null);
// Reset to step 1 on open
useEffect(() => { if (!open) { setStep(1); setInviteLink(null); } }, [open]);
```
---
## Hooks
### useUsers — `api/useUsers.ts`
```typescript
// GET /api/v1/Users
export function useUsers(): UseQueryResult<UserListItem[]>
```
- **Query key**: `['users']`
- **staleTime**: 30 000 ms (30s)
- **Invalidated by**: useInviteUser.onSuccess, useChangeRole.onSuccess
### useInviteUser — `api/useUsers.ts`
```typescript
// POST /api/v1/Users/invite
export function useInviteUser(): UseMutationResult<InviteUserResponse, Error, InviteUserRequest>
```
- **onSuccess**: invalidates `['users']` query
### useChangeRole — `api/useUsers.ts`
```typescript
// PUT /api/v1/Users/{userId}/role
export function useChangeRole(): UseMutationResult<void, Error, { userId: string; newRole: UserRole }>
```
- **onSuccess**: invalidates `['users']` query
### useValidateInvitation (migrated) — `api/useInvitation.ts`
```typescript
// GET /api/v1/Invitation/validate?token=...
export function useValidateInvitation(token: string | null): UseQueryResult<InvitationValidation>
```
- Migrated from useState/useEffect to useQuery
- Uses `InvitationValidation` from types.ts (replacing local interface)
- **enabled**: `!!token` (skip query when token is null)
### useCompleteInvitation (migrated) — `api/useInvitation.ts`
```typescript
// POST /api/v1/Invitation/complete
export function useCompleteInvitation(): UseMutationResult<void, Error, InviteCompleteRequest>
```
- Migrated from useState/useCallback to useMutation
- Uses `InviteCompleteRequest` from types.ts
---
## Form Validation Rules
### InviteUserForm (zod)
| Field | Rule | Error message |
|---|---|---|
| email | `z.string().email()` | "Valid email address required" |
| role | `z.enum(['Administrator', 'User'])` | "Role selection is required" |
---
## API Integration Summary
| Component / Hook | Endpoint | Method | Auth required |
|---|---|---|---|
| useUsers | /api/v1/Users | GET | Yes (Owner / Admin) |
| useInviteUser | /api/v1/Users/invite | POST | Yes (Owner / Admin) |
| useChangeRole | /api/v1/Users/{userId}/role | PUT | Yes (Owner / Admin) |
| useValidateInvitation | /api/v1/Invitation/validate | GET | No |
| useCompleteInvitation | /api/v1/Invitation/complete | POST | No |
---
## i18n Keys (en + nl)
```json
{
"users": {
"title": "Users",
"inviteButton": "Invite User",
"table": {
"name": "Name",
"email": "Email",
"role": "Role",
"status": "Status",
"createdAt": "Created",
"actions": "Actions"
},
"status": {
"active": "Active",
"inactive": "Inactive",
"pendingInvite": "Pending invite"
},
"actions": {
"copyInviteLink": "Copy invite link",
"changeRole": "Change role",
"linkCopied": "Invite link copied to clipboard"
},
"invite": {
"title": "Invite User",
"emailLabel": "Email address",
"roleLabel": "Role",
"submitButton": "Send invitation",
"step2Title": "Invitation created",
"step2Description": "Share the link below with the invitee.",
"copyLink": "Copy link",
"close": "Close"
},
"roles": {
"Owner": "Owner",
"Administrator": "Administrator",
"User": "User"
}
}
}
```
---
## MSW Mocks (Unit 5 additions)
Extend `frontend/src/mocks/users/handlers.ts`:
| Handler | Method | Path | Response |
|---|---|---|---|
| List users | GET | /api/v1/Users | Array of UserListItem (including 1 pending) |
| Invite user | POST | /api/v1/Users/invite | `{ inviteLink: '/invite/complete?token=mock-token' }` |
| Change role | PUT | /api/v1/Users/:userId/role | 200 OK (no body) |
---
## Unit Test Scope
| Test file | Coverage |
|---|---|
| `api/useUsers.test.ts` | useUsers (loading, success, error); useInviteUser (success, API error); useChangeRole (success, 403) |
| `pages/UsersPage.test.tsx` | Renders table with user list; Invite button opens dialog; Step 1 → Step 2 transition; copy invite link toast |
| `components/users/InviteUserDialog.test.tsx` | Step 1 form validation; successful invite shows Step 2; error shows FormErrorBanner |
| `api/useInvitation.test.ts` | useValidateInvitation (valid token, invalid token); useCompleteInvitation (success, error) — replaces Unit 2 tests |