Adds user management
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "default",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/index.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
@@ -16,8 +16,10 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^5.4.0",
|
||||
"@radix-ui/react-dialog": "^1.1.17",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.18",
|
||||
"@radix-ui/react-label": "^2.1.10",
|
||||
"@radix-ui/react-select": "^2.3.1",
|
||||
"@radix-ui/react-slot": "^1.3.0",
|
||||
"@tanstack/react-query": "^5.101.0",
|
||||
"@tanstack/react-router": "^1.170.16",
|
||||
|
||||
Generated
+126
@@ -11,12 +11,18 @@ importers:
|
||||
'@hookform/resolvers':
|
||||
specifier: ^5.4.0
|
||||
version: 5.4.0(react-hook-form@7.79.0(react@19.2.7))
|
||||
'@radix-ui/react-dialog':
|
||||
specifier: ^1.1.17
|
||||
version: 1.1.17(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@radix-ui/react-dropdown-menu':
|
||||
specifier: ^2.1.18
|
||||
version: 2.1.18(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@radix-ui/react-label':
|
||||
specifier: ^2.1.10
|
||||
version: 2.1.10(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@radix-ui/react-select':
|
||||
specifier: ^2.3.1
|
||||
version: 2.3.1(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@radix-ui/react-slot':
|
||||
specifier: ^1.3.0
|
||||
version: 1.3.0(@types/react@19.2.17)(react@19.2.7)
|
||||
@@ -438,6 +444,9 @@ packages:
|
||||
'@oxc-project/types@0.133.0':
|
||||
resolution: {integrity: sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==}
|
||||
|
||||
'@radix-ui/number@1.1.2':
|
||||
resolution: {integrity: sha512-ceTwaxc4I5IOi97DgCotl3pqiyRGvffcc0oOsE2dQYaJOFIDsDt4VWG6xEbg1QePv9QWausCEIppud/tJ1wNig==}
|
||||
|
||||
'@radix-ui/primitive@1.1.4':
|
||||
resolution: {integrity: sha512-7AdCK9PQyiljKoBDbN8OuctCbd/esdwZPQ8RtOE3SsyQtUpiPb+ND75q0jEhC1m1ecBI0MFNeLJvwIh9iKHRcQ==}
|
||||
|
||||
@@ -485,6 +494,19 @@ packages:
|
||||
'@types/react':
|
||||
optional: true
|
||||
|
||||
'@radix-ui/react-dialog@1.1.17':
|
||||
resolution: {integrity: sha512-TDTYmpdq8dI2+Xgvgj9AJ8Ghqq+Eph/TRVEdaFQPDItIY+6QSkU7MJMeevw1568Yw/2Ijz8BTphPSP2XejKphw==}
|
||||
peerDependencies:
|
||||
'@types/react': '*'
|
||||
'@types/react-dom': '*'
|
||||
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
|
||||
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
|
||||
peerDependenciesMeta:
|
||||
'@types/react':
|
||||
optional: true
|
||||
'@types/react-dom':
|
||||
optional: true
|
||||
|
||||
'@radix-ui/react-direction@1.1.2':
|
||||
resolution: {integrity: sha512-C3vFhbyi4SW3PmbAi6Awpu4OzJtd0MxGurvSsYtr7p7nM8RNB3VAF3CUmnp2j50knpkrRcB7+ycVXzgLgF6yNA==}
|
||||
peerDependencies:
|
||||
@@ -642,6 +664,19 @@ packages:
|
||||
'@types/react-dom':
|
||||
optional: true
|
||||
|
||||
'@radix-ui/react-select@2.3.1':
|
||||
resolution: {integrity: sha512-w6eDvY78LE9ZUiNnXCA1QVK8RYN7k9galFv09kjVydJqBAgHd7Y9A6h0UJ/6DCZNGZMZrB2ohcSW1Bo9d8+wWA==}
|
||||
peerDependencies:
|
||||
'@types/react': '*'
|
||||
'@types/react-dom': '*'
|
||||
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
|
||||
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
|
||||
peerDependenciesMeta:
|
||||
'@types/react':
|
||||
optional: true
|
||||
'@types/react-dom':
|
||||
optional: true
|
||||
|
||||
'@radix-ui/react-slot@1.3.0':
|
||||
resolution: {integrity: sha512-MojKku4U/miO8Av4Dkb+ctMAQx7JmY96LmtDQlAarCRtd7rN52QCSzBF+XAvr5S6coSVj9HEPBgHAHKEJVk/WA==}
|
||||
peerDependencies:
|
||||
@@ -696,6 +731,15 @@ packages:
|
||||
'@types/react':
|
||||
optional: true
|
||||
|
||||
'@radix-ui/react-use-previous@1.1.2':
|
||||
resolution: {integrity: sha512-IGBQPtRFdhN6MQ8dbegVmBq1LVZluya3F1jWY+puIcQC3MHctRwTDSBWCkL/3ZcnMJLTMJ++Z+ktmvg0F89iCw==}
|
||||
peerDependencies:
|
||||
'@types/react': '*'
|
||||
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
|
||||
peerDependenciesMeta:
|
||||
'@types/react':
|
||||
optional: true
|
||||
|
||||
'@radix-ui/react-use-rect@1.1.2':
|
||||
resolution: {integrity: sha512-d8a+bBY/FxikNPlgJJoaBHZX+zKVbWHYJGTLnLvveQgFSTntkGdEKv3JDtHrMS0DNYpllz2nRsTLGLKYttbpmw==}
|
||||
peerDependencies:
|
||||
@@ -714,6 +758,19 @@ packages:
|
||||
'@types/react':
|
||||
optional: true
|
||||
|
||||
'@radix-ui/react-visually-hidden@1.2.6':
|
||||
resolution: {integrity: sha512-jCE0WljWifTI4niIMCll06kGpsJTAPiZVU9H4WR1N6qW7At9ystHbN7dDB+we2xH535roFHj7qKS+RGj0FMDWQ==}
|
||||
peerDependencies:
|
||||
'@types/react': '*'
|
||||
'@types/react-dom': '*'
|
||||
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
|
||||
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
|
||||
peerDependenciesMeta:
|
||||
'@types/react':
|
||||
optional: true
|
||||
'@types/react-dom':
|
||||
optional: true
|
||||
|
||||
'@radix-ui/rect@1.1.2':
|
||||
resolution: {integrity: sha512-xnXE7wG13PI+cxieVssYXlQJuYVRhH9NBoxt3KNwzghDIA69GMm7d4wXRouHIYjE+KvS6U/MsMO73NdS2MH9ZA==}
|
||||
|
||||
@@ -2541,6 +2598,8 @@ snapshots:
|
||||
|
||||
'@oxc-project/types@0.133.0': {}
|
||||
|
||||
'@radix-ui/number@1.1.2': {}
|
||||
|
||||
'@radix-ui/primitive@1.1.4': {}
|
||||
|
||||
'@radix-ui/react-arrow@1.1.10(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)':
|
||||
@@ -2576,6 +2635,28 @@ snapshots:
|
||||
optionalDependencies:
|
||||
'@types/react': 19.2.17
|
||||
|
||||
'@radix-ui/react-dialog@1.1.17(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)':
|
||||
dependencies:
|
||||
'@radix-ui/primitive': 1.1.4
|
||||
'@radix-ui/react-compose-refs': 1.1.3(@types/react@19.2.17)(react@19.2.7)
|
||||
'@radix-ui/react-context': 1.1.4(@types/react@19.2.17)(react@19.2.7)
|
||||
'@radix-ui/react-dismissable-layer': 1.1.13(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@radix-ui/react-focus-guards': 1.1.4(@types/react@19.2.17)(react@19.2.7)
|
||||
'@radix-ui/react-focus-scope': 1.1.10(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@radix-ui/react-id': 1.1.2(@types/react@19.2.17)(react@19.2.7)
|
||||
'@radix-ui/react-portal': 1.1.12(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@radix-ui/react-presence': 1.1.6(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@radix-ui/react-primitive': 2.1.6(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@radix-ui/react-slot': 1.3.0(@types/react@19.2.17)(react@19.2.7)
|
||||
'@radix-ui/react-use-controllable-state': 1.2.3(@types/react@19.2.17)(react@19.2.7)
|
||||
aria-hidden: 1.2.6
|
||||
react: 19.2.7
|
||||
react-dom: 19.2.7(react@19.2.7)
|
||||
react-remove-scroll: 2.7.2(@types/react@19.2.17)(react@19.2.7)
|
||||
optionalDependencies:
|
||||
'@types/react': 19.2.17
|
||||
'@types/react-dom': 19.2.3(@types/react@19.2.17)
|
||||
|
||||
'@radix-ui/react-direction@1.1.2(@types/react@19.2.17)(react@19.2.7)':
|
||||
dependencies:
|
||||
react: 19.2.7
|
||||
@@ -2732,6 +2813,36 @@ snapshots:
|
||||
'@types/react': 19.2.17
|
||||
'@types/react-dom': 19.2.3(@types/react@19.2.17)
|
||||
|
||||
'@radix-ui/react-select@2.3.1(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)':
|
||||
dependencies:
|
||||
'@radix-ui/number': 1.1.2
|
||||
'@radix-ui/primitive': 1.1.4
|
||||
'@radix-ui/react-collection': 1.1.10(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@radix-ui/react-compose-refs': 1.1.3(@types/react@19.2.17)(react@19.2.7)
|
||||
'@radix-ui/react-context': 1.1.4(@types/react@19.2.17)(react@19.2.7)
|
||||
'@radix-ui/react-direction': 1.1.2(@types/react@19.2.17)(react@19.2.7)
|
||||
'@radix-ui/react-dismissable-layer': 1.1.13(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@radix-ui/react-focus-guards': 1.1.4(@types/react@19.2.17)(react@19.2.7)
|
||||
'@radix-ui/react-focus-scope': 1.1.10(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@radix-ui/react-id': 1.1.2(@types/react@19.2.17)(react@19.2.7)
|
||||
'@radix-ui/react-popper': 1.3.1(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@radix-ui/react-portal': 1.1.12(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@radix-ui/react-presence': 1.1.6(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@radix-ui/react-primitive': 2.1.6(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@radix-ui/react-slot': 1.3.0(@types/react@19.2.17)(react@19.2.7)
|
||||
'@radix-ui/react-use-callback-ref': 1.1.2(@types/react@19.2.17)(react@19.2.7)
|
||||
'@radix-ui/react-use-controllable-state': 1.2.3(@types/react@19.2.17)(react@19.2.7)
|
||||
'@radix-ui/react-use-layout-effect': 1.1.2(@types/react@19.2.17)(react@19.2.7)
|
||||
'@radix-ui/react-use-previous': 1.1.2(@types/react@19.2.17)(react@19.2.7)
|
||||
'@radix-ui/react-visually-hidden': 1.2.6(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
aria-hidden: 1.2.6
|
||||
react: 19.2.7
|
||||
react-dom: 19.2.7(react@19.2.7)
|
||||
react-remove-scroll: 2.7.2(@types/react@19.2.17)(react@19.2.7)
|
||||
optionalDependencies:
|
||||
'@types/react': 19.2.17
|
||||
'@types/react-dom': 19.2.3(@types/react@19.2.17)
|
||||
|
||||
'@radix-ui/react-slot@1.3.0(@types/react@19.2.17)(react@19.2.7)':
|
||||
dependencies:
|
||||
'@radix-ui/react-compose-refs': 1.1.3(@types/react@19.2.17)(react@19.2.7)
|
||||
@@ -2773,6 +2884,12 @@ snapshots:
|
||||
optionalDependencies:
|
||||
'@types/react': 19.2.17
|
||||
|
||||
'@radix-ui/react-use-previous@1.1.2(@types/react@19.2.17)(react@19.2.7)':
|
||||
dependencies:
|
||||
react: 19.2.7
|
||||
optionalDependencies:
|
||||
'@types/react': 19.2.17
|
||||
|
||||
'@radix-ui/react-use-rect@1.1.2(@types/react@19.2.17)(react@19.2.7)':
|
||||
dependencies:
|
||||
'@radix-ui/rect': 1.1.2
|
||||
@@ -2787,6 +2904,15 @@ snapshots:
|
||||
optionalDependencies:
|
||||
'@types/react': 19.2.17
|
||||
|
||||
'@radix-ui/react-visually-hidden@1.2.6(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)':
|
||||
dependencies:
|
||||
'@radix-ui/react-primitive': 2.1.6(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
react: 19.2.7
|
||||
react-dom: 19.2.7(react@19.2.7)
|
||||
optionalDependencies:
|
||||
'@types/react': 19.2.17
|
||||
'@types/react-dom': 19.2.3(@types/react@19.2.17)
|
||||
|
||||
'@radix-ui/rect@1.1.2': {}
|
||||
|
||||
'@rolldown/binding-android-arm64@1.0.3':
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
allowBuilds:
|
||||
msw: true
|
||||
esbuild: true
|
||||
'@tailwindcss/oxide': true
|
||||
esbuild: true
|
||||
msw: true
|
||||
confirmModulesPurge: false
|
||||
|
||||
@@ -61,6 +61,25 @@ export interface InviteCompleteRequest {
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface UserListItem extends User {
|
||||
createdAt: string;
|
||||
invitationPending: boolean;
|
||||
inviteLink: string | null;
|
||||
}
|
||||
|
||||
export interface InviteUserPayload {
|
||||
email: string;
|
||||
role: Exclude<UserRole, 'Owner'>;
|
||||
}
|
||||
|
||||
export interface InviteUserResponse {
|
||||
inviteLink: string;
|
||||
}
|
||||
|
||||
export interface ChangeRolePayload {
|
||||
newRole: UserRole;
|
||||
}
|
||||
|
||||
export type AvailabilityStatus = 'Available' | 'Maintenance' | 'Unavailable';
|
||||
|
||||
export interface AvailabilityResponse {
|
||||
|
||||
@@ -1,83 +1,21 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { api } from '../lib/api-client';
|
||||
|
||||
interface InvitationValidationResponse {
|
||||
valid: boolean;
|
||||
email?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface InvitationCompleteRequest {
|
||||
token: string;
|
||||
name: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
interface InvitationCompleteResponse {
|
||||
message: string;
|
||||
user: {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: string;
|
||||
};
|
||||
}
|
||||
import { useQuery, useMutation } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api-client';
|
||||
import type { InvitationValidation, InviteCompleteRequest } from './types';
|
||||
|
||||
export function useValidateInvitation(token: string | null) {
|
||||
const [data, setData] = useState<InvitationValidationResponse | null>(null);
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return;
|
||||
|
||||
const fetchValidation = async () => {
|
||||
setIsPending(true);
|
||||
setError(null);
|
||||
try {
|
||||
const url = `/api/v1/Invitation/validate?token=${encodeURIComponent(token)}`;
|
||||
const response = await api.get(url);
|
||||
setData(response as InvitationValidationResponse);
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err : new Error(String(err)));
|
||||
setData(null);
|
||||
} finally {
|
||||
setIsPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchValidation();
|
||||
}, [token]);
|
||||
|
||||
return {
|
||||
data,
|
||||
isPending,
|
||||
error
|
||||
};
|
||||
return useQuery<InvitationValidation, Error>({
|
||||
queryKey: ['invitation', 'validate', token],
|
||||
queryFn: () =>
|
||||
api.get<InvitationValidation>(
|
||||
`/api/v1/Invitation/validate?token=${encodeURIComponent(token!)}`,
|
||||
),
|
||||
enabled: !!token,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCompleteInvitation() {
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
|
||||
const mutateAsync = useCallback(async (data: InvitationCompleteRequest): Promise<InvitationCompleteResponse> => {
|
||||
setIsPending(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await api.post('/api/v1/Invitation/complete', data);
|
||||
return response as InvitationCompleteResponse;
|
||||
} catch (err: unknown) {
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
setError(error);
|
||||
throw error;
|
||||
} finally {
|
||||
setIsPending(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
mutateAsync,
|
||||
isPending,
|
||||
error
|
||||
};
|
||||
return useMutation<void, Error, InviteCompleteRequest>({
|
||||
mutationFn: (data) => api.post('/api/v1/Invitation/complete', data),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { renderHook, waitFor, act } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { createElement } from 'react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE } from '@/mocks/auth/fixtures';
|
||||
import { getMockUsers } from '@/mocks/users/handlers';
|
||||
import { useUsers, useInviteUser, useChangeRole } from './useUsers';
|
||||
|
||||
function createWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
return ({ children }: { children: React.ReactNode }) =>
|
||||
createElement(QueryClientProvider, { client: queryClient }, children);
|
||||
}
|
||||
|
||||
const USERS_URL = `${API_BASE}/api/v1/Users`;
|
||||
|
||||
describe('useUsers', () => {
|
||||
it('starts in loading state', () => {
|
||||
const { result } = renderHook(() => useUsers(), { wrapper: createWrapper() });
|
||||
expect(result.current.isPending).toBe(true);
|
||||
});
|
||||
|
||||
it('returns the users list on success', async () => {
|
||||
const { result } = renderHook(() => useUsers(), { wrapper: createWrapper() });
|
||||
await waitFor(() => expect(result.current.isPending).toBe(false));
|
||||
|
||||
expect(result.current.isError).toBe(false);
|
||||
expect(result.current.data).toHaveLength(getMockUsers().length);
|
||||
expect(result.current.data?.[0].email).toBe(getMockUsers()[0].email);
|
||||
});
|
||||
|
||||
it('enters error state on 5xx', async () => {
|
||||
server.use(http.get(USERS_URL, () => HttpResponse.json({}, { status: 500 })));
|
||||
|
||||
const { result } = renderHook(() => useUsers(), { wrapper: createWrapper() });
|
||||
await waitFor(() => expect(result.current.isPending).toBe(false));
|
||||
|
||||
expect(result.current.isError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useInviteUser', () => {
|
||||
it('returns inviteLink on successful mutation', async () => {
|
||||
const { result } = renderHook(() => useInviteUser(), { wrapper: createWrapper() });
|
||||
|
||||
await act(async () => {
|
||||
await result.current.mutateAsync({ email: 'new@example.com', role: 'User' });
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
expect(result.current.data?.inviteLink).toContain('/invite/complete');
|
||||
});
|
||||
|
||||
it('fails when server returns 400', async () => {
|
||||
server.use(
|
||||
http.post(`${USERS_URL}/invite`, () =>
|
||||
HttpResponse.json({ detail: 'already exists' }, { status: 400 }),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useInviteUser(), { wrapper: createWrapper() });
|
||||
|
||||
await act(async () => {
|
||||
await result.current.mutateAsync({ email: 'dup@example.com', role: 'User' }).catch(() => {});
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isError).toBe(true));
|
||||
});
|
||||
});
|
||||
|
||||
describe('useChangeRole', () => {
|
||||
it('succeeds when server returns 200', async () => {
|
||||
const { result } = renderHook(() => useChangeRole(), { wrapper: createWrapper() });
|
||||
|
||||
await act(async () => {
|
||||
await result.current.mutateAsync({
|
||||
userId: '22222222-2222-2222-2222-222222222222',
|
||||
newRole: 'User',
|
||||
});
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
});
|
||||
|
||||
it('fails when server returns 403', async () => {
|
||||
server.use(
|
||||
http.put(`${USERS_URL}/:userId/role`, () => new HttpResponse(null, { status: 403 })),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useChangeRole(), { wrapper: createWrapper() });
|
||||
|
||||
await act(async () => {
|
||||
await result.current
|
||||
.mutateAsync({ userId: 'any-id', newRole: 'Administrator' })
|
||||
.catch(() => {});
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isError).toBe(true));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api-client';
|
||||
import type { UserListItem, InviteUserPayload, InviteUserResponse, ChangeRolePayload, UserRole } from './types';
|
||||
|
||||
export function useUsers() {
|
||||
return useQuery<UserListItem[], Error>({
|
||||
queryKey: ['users'],
|
||||
queryFn: () => api.get<UserListItem[]>('/api/v1/Users'),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useInviteUser() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<InviteUserResponse, Error, InviteUserPayload>({
|
||||
mutationFn: (data) => api.post<InviteUserResponse>('/api/v1/Users/invite', data),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['users'] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useChangeRole() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<void, Error, { userId: string; newRole: UserRole }>({
|
||||
mutationFn: ({ userId, newRole }: { userId: string; newRole: UserRole }) =>
|
||||
api.put<void>(`/api/v1/Users/${userId}/role`, { newRole } satisfies ChangeRolePayload),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['users'] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useSetUserActive() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<void, Error, { userId: string; isActive: boolean }>({
|
||||
mutationFn: ({ userId, isActive }) =>
|
||||
api.put<void>(`/api/v1/Users/${userId}/active`, { isActive }),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['users'] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteUser() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<void, Error, string>({
|
||||
mutationFn: (userId: string) => api.delete<void>(`/api/v1/Users/${userId}`),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['users'] }),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const badgeVariants = cva(
|
||||
'inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'border-transparent bg-primary text-primary-foreground hover:bg-primary/80',
|
||||
secondary:
|
||||
'border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80',
|
||||
destructive:
|
||||
'border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80',
|
||||
outline: 'text-foreground',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof badgeVariants> {}
|
||||
|
||||
function Badge({ className, variant, ...props }: BadgeProps) {
|
||||
return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants };
|
||||
@@ -0,0 +1,98 @@
|
||||
import * as React from 'react';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
import { X } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Dialog = DialogPrimitive.Root;
|
||||
const DialogTrigger = DialogPrimitive.Trigger;
|
||||
const DialogPortal = DialogPrimitive.Portal;
|
||||
const DialogClose = DialogPrimitive.Close;
|
||||
|
||||
const DialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
|
||||
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<DialogClose className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogClose>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
));
|
||||
DialogContent.displayName = DialogPrimitive.Content.displayName;
|
||||
|
||||
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn('flex flex-col space-y-1.5 text-center sm:text-left', className)} {...props} />
|
||||
);
|
||||
DialogHeader.displayName = 'DialogHeader';
|
||||
|
||||
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn('flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
DialogFooter.displayName = 'DialogFooter';
|
||||
|
||||
const DialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn('text-lg font-semibold leading-none tracking-tight', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogTitle.displayName = DialogPrimitive.Title.displayName;
|
||||
|
||||
const DialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn('text-sm text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogDescription.displayName = DialogPrimitive.Description.displayName;
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogClose,
|
||||
DialogTrigger,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
/* eslint-disable react-refresh/only-export-components */
|
||||
import * as React from 'react';
|
||||
import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
|
||||
import { Check } from 'lucide-react';
|
||||
import { Check, ChevronRight } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export const DropdownMenu = DropdownMenuPrimitive.Root;
|
||||
@@ -64,6 +64,43 @@ export const DropdownMenuSeparator = React.forwardRef<
|
||||
));
|
||||
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
|
||||
|
||||
export const DropdownMenuSub = DropdownMenuPrimitive.Sub;
|
||||
|
||||
export const DropdownMenuSubTrigger = React.forwardRef<
|
||||
React.ComponentRef<typeof DropdownMenuPrimitive.SubTrigger>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRight className="ml-auto h-4 w-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
));
|
||||
DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName;
|
||||
|
||||
export const DropdownMenuSubContent = React.forwardRef<
|
||||
React.ComponentRef<typeof DropdownMenuPrimitive.SubContent>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
));
|
||||
DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName;
|
||||
|
||||
/** A checkable indicator for selected items (e.g. the active language). */
|
||||
export function DropdownMenuCheck({ checked }: { checked: boolean }) {
|
||||
return <Check className={cn('ml-auto', checked ? 'opacity-100' : 'opacity-0')} />;
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import * as React from 'react';
|
||||
import * as SelectPrimitive from '@radix-ui/react-select';
|
||||
import { Check, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Select = SelectPrimitive.Root;
|
||||
const SelectGroup = SelectPrimitive.Group;
|
||||
const SelectValue = SelectPrimitive.Value;
|
||||
|
||||
const SelectTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
));
|
||||
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
|
||||
|
||||
const SelectScrollUpButton = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
ref={ref}
|
||||
className={cn('flex cursor-default items-center justify-center py-1', className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
));
|
||||
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
|
||||
|
||||
const SelectScrollDownButton = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
ref={ref}
|
||||
className={cn('flex cursor-default items-center justify-center py-1', className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
));
|
||||
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
|
||||
|
||||
const SelectContent = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
|
||||
>(({ className, children, position = 'popper', ...props }, ref) => (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
position === 'popper' &&
|
||||
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
|
||||
className,
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
'p-1',
|
||||
position === 'popper' &&
|
||||
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]',
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
));
|
||||
SelectContent.displayName = SelectPrimitive.Content.displayName;
|
||||
|
||||
const SelectLabel = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn('py-1.5 pl-8 pr-2 text-sm font-semibold', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
SelectLabel.displayName = SelectPrimitive.Label.displayName;
|
||||
|
||||
const SelectItem = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
));
|
||||
SelectItem.displayName = SelectPrimitive.Item.displayName;
|
||||
|
||||
const SelectSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn('-mx-1 my-1 h-px bg-muted', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectGroup,
|
||||
SelectValue,
|
||||
SelectTrigger,
|
||||
SelectContent,
|
||||
SelectLabel,
|
||||
SelectItem,
|
||||
SelectSeparator,
|
||||
SelectScrollUpButton,
|
||||
SelectScrollDownButton,
|
||||
};
|
||||
@@ -0,0 +1,98 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div className="relative w-full overflow-auto">
|
||||
<table
|
||||
ref={ref}
|
||||
className={cn('w-full caption-bottom text-sm', className)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
);
|
||||
Table.displayName = 'Table';
|
||||
|
||||
const TableHeader = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<thead ref={ref} className={cn('[&_tr]:border-b', className)} {...props} />
|
||||
));
|
||||
TableHeader.displayName = 'TableHeader';
|
||||
|
||||
const TableBody = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<tbody ref={ref} className={cn('[&_tr:last-child]:border-0', className)} {...props} />
|
||||
));
|
||||
TableBody.displayName = 'TableBody';
|
||||
|
||||
const TableFooter = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<tfoot
|
||||
ref={ref}
|
||||
className={cn('border-t bg-muted/50 font-medium [&>tr]:last:border-b-0', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TableFooter.displayName = 'TableFooter';
|
||||
|
||||
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<tr
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
);
|
||||
TableRow.displayName = 'TableRow';
|
||||
|
||||
const TableHead = React.forwardRef<
|
||||
HTMLTableCellElement,
|
||||
React.ThHTMLAttributes<HTMLTableCellElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<th
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TableHead.displayName = 'TableHead';
|
||||
|
||||
const TableCell = React.forwardRef<
|
||||
HTMLTableCellElement,
|
||||
React.TdHTMLAttributes<HTMLTableCellElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<td
|
||||
ref={ref}
|
||||
className={cn('p-4 align-middle [&:has([role=checkbox])]:pr-0', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TableCell.displayName = 'TableCell';
|
||||
|
||||
const TableCaption = React.forwardRef<
|
||||
HTMLTableCaptionElement,
|
||||
React.HTMLAttributes<HTMLTableCaptionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<caption
|
||||
ref={ref}
|
||||
className={cn('mt-4 text-sm text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TableCaption.displayName = 'TableCaption';
|
||||
|
||||
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
DialogDescription,
|
||||
} from '@/components/ui/dialog';
|
||||
import type { UserListItem } from '@/api/types';
|
||||
|
||||
interface DeleteUserDialogProps {
|
||||
user: UserListItem | null;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onConfirm: () => void;
|
||||
isPending: boolean;
|
||||
}
|
||||
|
||||
export function DeleteUserDialog({
|
||||
user,
|
||||
open,
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
isPending,
|
||||
}: DeleteUserDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
if (!user) return null;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md" data-testid="delete-user-dialog">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('users.delete.title')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{user.invitationPending
|
||||
? t('users.delete.descriptionPending', { email: user.email })
|
||||
: t('users.delete.description', { name: user.name, email: user.email })}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter className="gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={isPending}
|
||||
data-testid="delete-user-cancel"
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={onConfirm}
|
||||
disabled={isPending}
|
||||
data-testid="delete-user-confirm"
|
||||
>
|
||||
{isPending ? '...' : t('users.delete.confirmButton')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { renderApp, mockAuthenticated } from '@/test/utils';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE } from '@/mocks/auth/fixtures';
|
||||
import { _resetSetupStatusCache } from '@/router';
|
||||
|
||||
beforeEach(() => {
|
||||
_resetSetupStatusCache();
|
||||
});
|
||||
|
||||
async function openDialog() {
|
||||
mockAuthenticated();
|
||||
renderApp('/users');
|
||||
await screen.findByTestId('users-invite-button', {}, { timeout: 5000 });
|
||||
await userEvent.click(screen.getByTestId('users-invite-button'));
|
||||
expect(screen.getByTestId('invite-dialog-email')).toBeInTheDocument();
|
||||
}
|
||||
|
||||
describe('InviteUserDialog', () => {
|
||||
it('shows email and role fields on open', async () => {
|
||||
await openDialog();
|
||||
expect(screen.getByTestId('invite-dialog-email')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('invite-dialog-role')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('invite-dialog-submit')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows validation error when submitting with empty email', async () => {
|
||||
await openDialog();
|
||||
await userEvent.click(screen.getByTestId('invite-dialog-submit'));
|
||||
expect(await screen.findByTestId('invite-email-error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows validation error when submitting without selecting a role', async () => {
|
||||
await openDialog();
|
||||
await userEvent.type(screen.getByTestId('invite-dialog-email'), 'new@example.com');
|
||||
await userEvent.click(screen.getByTestId('invite-dialog-submit'));
|
||||
expect(await screen.findByTestId('invite-role-error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('advances to step 2 (invite link) after successful submission', async () => {
|
||||
await openDialog();
|
||||
|
||||
await userEvent.type(screen.getByTestId('invite-dialog-email'), 'new@example.com');
|
||||
|
||||
// Open role dropdown and select "User" (use role=option to avoid ambiguity)
|
||||
await userEvent.click(screen.getByTestId('invite-dialog-role'));
|
||||
const options = await screen.findAllByRole('option');
|
||||
const userOption = options.find((o) => o.textContent === 'User');
|
||||
await userEvent.click(userOption!);
|
||||
|
||||
await userEvent.click(screen.getByTestId('invite-dialog-submit'));
|
||||
|
||||
expect(await screen.findByTestId('invite-dialog-link-input')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('invite-dialog-copy')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows error banner when API returns 400', async () => {
|
||||
server.use(
|
||||
http.post(`${API_BASE}/api/v1/Users/invite`, () =>
|
||||
HttpResponse.json({ detail: 'User already exists.' }, { status: 400 }),
|
||||
),
|
||||
);
|
||||
await openDialog();
|
||||
|
||||
await userEvent.type(screen.getByTestId('invite-dialog-email'), 'dup@example.com');
|
||||
await userEvent.click(screen.getByTestId('invite-dialog-role'));
|
||||
const opts = await screen.findAllByRole('option');
|
||||
const userOpt = opts.find((o) => o.textContent === 'User');
|
||||
await userEvent.click(userOpt!);
|
||||
await userEvent.click(screen.getByTestId('invite-dialog-submit'));
|
||||
|
||||
expect(await screen.findByTestId('form-error-banner')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('resets to step 1 when dialog is closed and reopened', async () => {
|
||||
await openDialog();
|
||||
await userEvent.type(screen.getByTestId('invite-dialog-email'), 'test@example.com');
|
||||
|
||||
// Close the dialog by pressing Escape
|
||||
await userEvent.keyboard('{Escape}');
|
||||
|
||||
// Reopen
|
||||
await userEvent.click(screen.getByTestId('users-invite-button'));
|
||||
const emailInput = screen.getByTestId('invite-dialog-email') as HTMLInputElement;
|
||||
expect(emailInput.value).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,187 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { toast } from 'sonner';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
|
||||
import { FieldError } from '@/components/ui/FieldError';
|
||||
import { useInviteUser } from '@/api/useUsers';
|
||||
|
||||
const inviteSchema = z.object({
|
||||
email: z.string().email(),
|
||||
role: z.enum(['Administrator', 'User']),
|
||||
});
|
||||
type InviteFormData = z.infer<typeof inviteSchema>;
|
||||
|
||||
interface InviteUserDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function InviteUserDialog({ open, onOpenChange }: InviteUserDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [step, setStep] = useState<1 | 2>(1);
|
||||
const [inviteLink, setInviteLink] = useState<string | null>(null);
|
||||
const inviteUser = useInviteUser();
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setStep(1);
|
||||
setInviteLink(null);
|
||||
inviteUser.reset();
|
||||
reset();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open]);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
setValue,
|
||||
reset,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<InviteFormData>({
|
||||
resolver: zodResolver(inviteSchema),
|
||||
});
|
||||
|
||||
const onSubmit = handleSubmit(async (values) => {
|
||||
try {
|
||||
const response = await inviteUser.mutateAsync(values);
|
||||
setInviteLink(response.inviteLink);
|
||||
setStep(2);
|
||||
} catch {
|
||||
// error shown via inviteUser.error
|
||||
}
|
||||
});
|
||||
|
||||
const handleCopy = async () => {
|
||||
if (!inviteLink) return;
|
||||
await navigator.clipboard.writeText(`${window.location.origin}${inviteLink}`);
|
||||
toast.success(t('users.actions.linkCopied'));
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{step === 1 ? t('users.invite.title') : t('users.invite.step2Title')}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{step === 1 && (
|
||||
<form onSubmit={onSubmit} noValidate className="space-y-4">
|
||||
<FormErrorBanner
|
||||
error={inviteUser.error ? { message: inviteUser.error.message } : null}
|
||||
onDismiss={() => inviteUser.reset()}
|
||||
/>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="invite-email">{t('users.invite.emailLabel')}</Label>
|
||||
<Input
|
||||
id="invite-email"
|
||||
type="email"
|
||||
placeholder="user@example.com"
|
||||
data-testid="invite-dialog-email"
|
||||
aria-invalid={errors.email !== undefined}
|
||||
{...register('email')}
|
||||
/>
|
||||
{errors.email && (
|
||||
<FieldError message={errors.email.message} testId="invite-email-error" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="invite-role">{t('users.invite.roleLabel')}</Label>
|
||||
<Select
|
||||
onValueChange={(val) =>
|
||||
setValue('role', val as 'Administrator' | 'User', {
|
||||
shouldValidate: true,
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger
|
||||
id="invite-role"
|
||||
data-testid="invite-dialog-role"
|
||||
aria-invalid={errors.role !== undefined}
|
||||
>
|
||||
<SelectValue placeholder={t('users.invite.rolePlaceholder')} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="Administrator">
|
||||
{t('users.roles.Administrator')}
|
||||
</SelectItem>
|
||||
<SelectItem value="User">{t('users.roles.User')}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.role && (
|
||||
<FieldError message={errors.role.message} testId="invite-role-error" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isSubmitting || inviteUser.isPending}
|
||||
data-testid="invite-dialog-submit"
|
||||
>
|
||||
{isSubmitting || inviteUser.isPending
|
||||
? '...'
|
||||
: t('users.invite.submitButton')}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{step === 2 && (
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('users.invite.step2Description')}
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
<Label>{t('users.invite.linkLabel')}</Label>
|
||||
<Input
|
||||
value={`${window.location.origin}${inviteLink ?? ''}`}
|
||||
readOnly
|
||||
data-testid="invite-dialog-link-input"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1"
|
||||
onClick={handleCopy}
|
||||
data-testid="invite-dialog-copy"
|
||||
>
|
||||
{t('users.invite.copyLink')}
|
||||
</Button>
|
||||
<Button
|
||||
className="flex-1"
|
||||
onClick={() => onOpenChange(false)}
|
||||
data-testid="invite-dialog-close"
|
||||
>
|
||||
{t('users.invite.close')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -77,6 +77,73 @@
|
||||
"language": "Language",
|
||||
"logout": "Sign out"
|
||||
},
|
||||
"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",
|
||||
"deactivate": "Deactivate",
|
||||
"activate": "Activate",
|
||||
"delete": "Delete user",
|
||||
"linkCopied": "Invite link copied to clipboard"
|
||||
},
|
||||
"active": {
|
||||
"successDeactivated": "{{name}} has been deactivated.",
|
||||
"successActivated": "{{name}} has been activated."
|
||||
},
|
||||
"delete": {
|
||||
"title": "Delete user",
|
||||
"description": "Are you sure you want to delete {{name}} ({{email}})? This action cannot be undone.",
|
||||
"descriptionPending": "Are you sure you want to delete the pending invitation for {{email}}? This action cannot be undone.",
|
||||
"confirmButton": "Delete",
|
||||
"success": "{{name}} has been deleted."
|
||||
},
|
||||
"invite": {
|
||||
"title": "Invite User",
|
||||
"emailLabel": "Email address",
|
||||
"roleLabel": "Role",
|
||||
"rolePlaceholder": "Select a role",
|
||||
"submitButton": "Send invitation",
|
||||
"step2Title": "Invitation created",
|
||||
"step2Description": "Share the link below with the invitee.",
|
||||
"linkLabel": "Invite link",
|
||||
"copyLink": "Copy link",
|
||||
"close": "Close"
|
||||
},
|
||||
"roles": {
|
||||
"Owner": "Owner",
|
||||
"Administrator": "Administrator",
|
||||
"User": "User"
|
||||
},
|
||||
"ownerAssign": {
|
||||
"title": "Assign Owner role",
|
||||
"description": "You are about to make <strong>{{name}}</strong> an Owner. Owners have full access to the system, including the ability to manage and remove other Owners. Are you sure?",
|
||||
"confirmButton": "Make Owner"
|
||||
},
|
||||
"selfRoleChange": {
|
||||
"title": "Change your own role",
|
||||
"description": "You are about to change your own role to <strong>{{role}}</strong>. You will be logged out automatically so the change takes effect immediately.",
|
||||
"confirmButton": "Change and log out"
|
||||
},
|
||||
"errors": {
|
||||
"lastOwnerRequired": "At least one Owner must remain. Assign another Owner before changing this role.",
|
||||
"insufficientPermissions": "You do not have permission to perform this action."
|
||||
}
|
||||
},
|
||||
"errors": {
|
||||
"network": "Unable to reach the server. Check your connection and try again.",
|
||||
"generic": "Something went wrong. Please try again.",
|
||||
|
||||
@@ -77,6 +77,73 @@
|
||||
"language": "Taal",
|
||||
"logout": "Uitloggen"
|
||||
},
|
||||
"users": {
|
||||
"title": "Gebruikers",
|
||||
"inviteButton": "Gebruiker uitnodigen",
|
||||
"table": {
|
||||
"name": "Naam",
|
||||
"email": "E-mail",
|
||||
"role": "Rol",
|
||||
"status": "Status",
|
||||
"createdAt": "Aangemaakt",
|
||||
"actions": "Acties"
|
||||
},
|
||||
"status": {
|
||||
"active": "Actief",
|
||||
"inactive": "Inactief",
|
||||
"pendingInvite": "Uitnodiging in behandeling"
|
||||
},
|
||||
"actions": {
|
||||
"copyInviteLink": "Uitnodigingslink kopiëren",
|
||||
"changeRole": "Rol wijzigen",
|
||||
"deactivate": "Deactiveren",
|
||||
"activate": "Activeren",
|
||||
"delete": "Gebruiker verwijderen",
|
||||
"linkCopied": "Uitnodigingslink gekopieerd naar klembord"
|
||||
},
|
||||
"active": {
|
||||
"successDeactivated": "{{name}} is gedeactiveerd.",
|
||||
"successActivated": "{{name}} is geactiveerd."
|
||||
},
|
||||
"delete": {
|
||||
"title": "Gebruiker verwijderen",
|
||||
"description": "Weet je zeker dat je {{name}} ({{email}}) wilt verwijderen? Deze actie kan niet ongedaan worden gemaakt.",
|
||||
"descriptionPending": "Weet je zeker dat je de openstaande uitnodiging voor {{email}} wilt verwijderen? Deze actie kan niet ongedaan worden gemaakt.",
|
||||
"confirmButton": "Verwijderen",
|
||||
"success": "{{name}} is verwijderd."
|
||||
},
|
||||
"invite": {
|
||||
"title": "Gebruiker uitnodigen",
|
||||
"emailLabel": "E-mailadres",
|
||||
"roleLabel": "Rol",
|
||||
"rolePlaceholder": "Selecteer een rol",
|
||||
"submitButton": "Uitnodiging versturen",
|
||||
"step2Title": "Uitnodiging aangemaakt",
|
||||
"step2Description": "Deel de onderstaande link met de genodigde.",
|
||||
"linkLabel": "Uitnodigingslink",
|
||||
"copyLink": "Link kopiëren",
|
||||
"close": "Sluiten"
|
||||
},
|
||||
"roles": {
|
||||
"Owner": "Eigenaar",
|
||||
"Administrator": "Beheerder",
|
||||
"User": "Gebruiker"
|
||||
},
|
||||
"ownerAssign": {
|
||||
"title": "Eigenaarrol toewijzen",
|
||||
"description": "Je staat op het punt <strong>{{name}}</strong> eigenaar te maken. Eigenaars hebben volledige toegang tot het systeem, inclusief het kunnen beheren en verwijderen van andere eigenaars. Weet je het zeker?",
|
||||
"confirmButton": "Eigenaar maken"
|
||||
},
|
||||
"selfRoleChange": {
|
||||
"title": "Eigen rol wijzigen",
|
||||
"description": "Je staat op het punt je eigen rol te wijzigen naar <strong>{{role}}</strong>. Je wordt daarna automatisch uitgelogd zodat de wijziging direct ingaat.",
|
||||
"confirmButton": "Wijzigen en uitloggen"
|
||||
},
|
||||
"errors": {
|
||||
"lastOwnerRequired": "Er moet minimaal één Eigenaar blijven. Wijs eerst een andere Eigenaar aan voor je deze rol wijzigt.",
|
||||
"insufficientPermissions": "Je hebt geen toestemming om deze actie uit te voeren."
|
||||
}
|
||||
},
|
||||
"errors": {
|
||||
"network": "Kan de server niet bereiken. Controleer je verbinding en probeer opnieuw.",
|
||||
"generic": "Er is iets misgegaan. Probeer het opnieuw.",
|
||||
|
||||
@@ -7,21 +7,14 @@ export const invitationHandlers = [
|
||||
|
||||
if (token === 'valid-token') {
|
||||
return HttpResponse.json(
|
||||
{
|
||||
valid: true,
|
||||
email: 'invited@example.com'
|
||||
},
|
||||
{ status: 200 }
|
||||
{ isValid: true, email: 'invited@example.com', name: null, errorCode: null },
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
|
||||
// Any other token is invalid/expired
|
||||
return HttpResponse.json(
|
||||
{
|
||||
valid: false,
|
||||
error: 'Invalid or expired token'
|
||||
},
|
||||
{ status: 200 }
|
||||
{ isValid: false, email: '', name: null, errorCode: 'EXPIRED' },
|
||||
{ status: 200 },
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -31,39 +24,21 @@ export const invitationHandlers = [
|
||||
|
||||
if (!body.token || !body.name || !body.password) {
|
||||
return HttpResponse.json(
|
||||
{
|
||||
type: 'about:blank',
|
||||
title: 'Bad Request',
|
||||
status: 400,
|
||||
detail: 'Missing required fields'
|
||||
},
|
||||
{ status: 400 }
|
||||
{ type: 'about:blank', title: 'Bad Request', status: 400, detail: 'Missing required fields' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
if (body.token !== 'valid-token') {
|
||||
return HttpResponse.json(
|
||||
{
|
||||
type: 'about:blank',
|
||||
title: 'Bad Request',
|
||||
status: 400,
|
||||
detail: 'Invalid or expired token'
|
||||
},
|
||||
{ status: 400 }
|
||||
{ type: 'about:blank', title: 'Bad Request', status: 400, detail: 'Invalid or expired token' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
return HttpResponse.json(
|
||||
{
|
||||
message: 'Account created',
|
||||
user: {
|
||||
id: '2',
|
||||
name: body.name,
|
||||
email: 'invited@example.com',
|
||||
role: 'User'
|
||||
}
|
||||
},
|
||||
{ status: 201 }
|
||||
{ message: 'Account created', user: { id: '2', name: body.name, email: 'invited@example.com', role: 'User' } },
|
||||
{ status: 201 },
|
||||
);
|
||||
}),
|
||||
];
|
||||
|
||||
@@ -1,17 +1,106 @@
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import type { User } from '@/api/types';
|
||||
import type { UserListItem } from '@/api/types';
|
||||
import { API_BASE, mockUser } from '../auth/fixtures';
|
||||
|
||||
const mockUsers: User[] = [
|
||||
mockUser,
|
||||
let mockUsers: UserListItem[] = [
|
||||
{
|
||||
...mockUser,
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
invitationPending: false,
|
||||
inviteLink: null,
|
||||
},
|
||||
{
|
||||
id: '22222222-2222-2222-2222-222222222222',
|
||||
email: 'admin@example.com',
|
||||
name: 'Admin User',
|
||||
role: 'Administrator',
|
||||
isActive: true,
|
||||
createdAt: '2026-01-15T00:00:00.000Z',
|
||||
invitationPending: false,
|
||||
inviteLink: null,
|
||||
},
|
||||
{
|
||||
id: '33333333-3333-3333-3333-333333333333',
|
||||
email: 'pending@example.com',
|
||||
name: 'pending@example.com',
|
||||
role: 'User',
|
||||
isActive: true,
|
||||
createdAt: '2026-06-01T00:00:00.000Z',
|
||||
invitationPending: true,
|
||||
inviteLink: '/invite/complete?token=pending-mock-token',
|
||||
},
|
||||
];
|
||||
|
||||
/** Placeholder user-management mocks; expanded in Unit 5. */
|
||||
export const userHandlers = [http.get(`${API_BASE}/Users`, () => HttpResponse.json(mockUsers))];
|
||||
export const resetMockUsers = () => {
|
||||
mockUsers = [
|
||||
{
|
||||
...mockUser,
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
invitationPending: false,
|
||||
inviteLink: null,
|
||||
},
|
||||
{
|
||||
id: '22222222-2222-2222-2222-222222222222',
|
||||
email: 'admin@example.com',
|
||||
name: 'Admin User',
|
||||
role: 'Administrator',
|
||||
isActive: true,
|
||||
createdAt: '2026-01-15T00:00:00.000Z',
|
||||
invitationPending: false,
|
||||
inviteLink: null,
|
||||
},
|
||||
{
|
||||
id: '33333333-3333-3333-3333-333333333333',
|
||||
email: 'pending@example.com',
|
||||
name: 'pending@example.com',
|
||||
role: 'User',
|
||||
isActive: true,
|
||||
createdAt: '2026-06-01T00:00:00.000Z',
|
||||
invitationPending: true,
|
||||
inviteLink: '/invite/complete?token=pending-mock-token',
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
export const getMockUsers = () => mockUsers;
|
||||
|
||||
export const userHandlers = [
|
||||
http.get(`${API_BASE}/api/v1/Users`, () => HttpResponse.json(mockUsers)),
|
||||
|
||||
http.post(`${API_BASE}/api/v1/Users/invite`, async ({ request }) => {
|
||||
const body = (await request.json()) as { email: string; role: string };
|
||||
const token = `mock-token-${Date.now()}`;
|
||||
const inviteLink = `/invite/complete?token=${token}`;
|
||||
|
||||
const newUser: UserListItem = {
|
||||
id: crypto.randomUUID(),
|
||||
email: body.email,
|
||||
name: body.email,
|
||||
role: body.role as UserListItem['role'],
|
||||
isActive: true,
|
||||
createdAt: new Date().toISOString(),
|
||||
invitationPending: true,
|
||||
inviteLink,
|
||||
};
|
||||
mockUsers = [...mockUsers, newUser];
|
||||
|
||||
return HttpResponse.json({ inviteLink });
|
||||
}),
|
||||
|
||||
http.put(`${API_BASE}/api/v1/Users/:userId/role`, () => new HttpResponse(null, { status: 200 })),
|
||||
|
||||
http.put(`${API_BASE}/api/v1/Users/:userId/active`, () => new HttpResponse(null, { status: 200 })),
|
||||
|
||||
http.delete(`${API_BASE}/api/v1/Users/:userId`, ({ params }) => {
|
||||
const { userId } = params as { userId: string };
|
||||
const ownerUser = mockUsers.find((u) => u.role === 'Owner');
|
||||
if (userId === ownerUser?.id) {
|
||||
return HttpResponse.json(
|
||||
{ title: 'Bad Request', detail: 'At least one Owner must remain.', status: 400 },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
mockUsers = mockUsers.filter((u) => u.id !== userId);
|
||||
return new HttpResponse(null, { status: 204 });
|
||||
}),
|
||||
];
|
||||
|
||||
@@ -37,11 +37,11 @@ export function InviteCompletePage() {
|
||||
}
|
||||
} else if (validationQuery.isPending && loadingState !== 'submitting') {
|
||||
// Still loading
|
||||
} else if (validationQuery.error || (validationQuery.data && !validationQuery.data.valid)) {
|
||||
} else if (validationQuery.error || (validationQuery.data && !validationQuery.data.isValid)) {
|
||||
if (loadingState === 'loading') {
|
||||
setLoadingState('error');
|
||||
}
|
||||
} else if (validationQuery.data?.valid && loadingState === 'loading') {
|
||||
} else if (validationQuery.data?.isValid && loadingState === 'loading') {
|
||||
setLoadingState('ready');
|
||||
}
|
||||
|
||||
|
||||
@@ -89,6 +89,7 @@ export function LoginPage() {
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="••••••••"
|
||||
autoComplete="current-password"
|
||||
data-testid="login-password-input"
|
||||
aria-invalid={errors.password !== undefined}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { screen, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { renderApp, mockAuthenticated } from '@/test/utils';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE } from '@/mocks/auth/fixtures';
|
||||
import { getMockUsers } from '@/mocks/users/handlers';
|
||||
import { _resetSetupStatusCache } from '@/router';
|
||||
|
||||
beforeEach(() => {
|
||||
_resetSetupStatusCache();
|
||||
});
|
||||
|
||||
const USERS_URL = `${API_BASE}/api/v1/Users`;
|
||||
|
||||
describe('UsersPage', () => {
|
||||
it('renders the page title and invite button', async () => {
|
||||
mockAuthenticated();
|
||||
renderApp('/users');
|
||||
|
||||
expect(await screen.findByTestId('users-page', {}, { timeout: 5000 })).toBeInTheDocument();
|
||||
expect(screen.getByTestId('users-invite-button')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the users table with all mock users', async () => {
|
||||
mockAuthenticated();
|
||||
renderApp('/users');
|
||||
|
||||
const table = await screen.findByTestId('users-table');
|
||||
expect(table).toBeInTheDocument();
|
||||
|
||||
for (const user of getMockUsers()) {
|
||||
expect(screen.getByTestId(`user-row-${user.id}`)).toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
|
||||
it('shows "Pending invite" badge for invitation-pending users', async () => {
|
||||
mockAuthenticated();
|
||||
renderApp('/users');
|
||||
|
||||
await screen.findByTestId('users-table');
|
||||
const pendingUser = getMockUsers().find((u) => u.invitationPending)!;
|
||||
const row = screen.getByTestId(`user-row-${pendingUser.id}`);
|
||||
expect(within(row).getByText('Pending invite')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows copy invite link action for pending user', async () => {
|
||||
mockAuthenticated();
|
||||
renderApp('/users');
|
||||
|
||||
await screen.findByTestId('users-table');
|
||||
const pendingUser = getMockUsers().find((u) => u.invitationPending)!;
|
||||
const actionsBtn = screen.getByTestId(`user-actions-${pendingUser.id}`);
|
||||
await userEvent.click(actionsBtn);
|
||||
|
||||
expect(screen.getByTestId(`user-copy-link-${pendingUser.id}`)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows an error message when the API fails', async () => {
|
||||
mockAuthenticated();
|
||||
server.use(http.get(USERS_URL, () => HttpResponse.json({}, { status: 500 })));
|
||||
renderApp('/users');
|
||||
|
||||
await screen.findByTestId('users-page');
|
||||
expect(await screen.findByText(/something went wrong/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens the invite dialog when the invite button is clicked', async () => {
|
||||
mockAuthenticated();
|
||||
renderApp('/users');
|
||||
|
||||
await screen.findByTestId('users-invite-button');
|
||||
await userEvent.click(screen.getByTestId('users-invite-button'));
|
||||
|
||||
expect(screen.getByTestId('invite-dialog-email')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,447 @@
|
||||
import { useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { MoreHorizontal, Link as LinkIcon, Trash2, UserX, UserCheck } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { InviteUserDialog } from '@/components/users/InviteUserDialog';
|
||||
import { DeleteUserDialog } from '@/components/users/DeleteUserDialog';
|
||||
import { useUsers, useChangeRole, useSetUserActive, useDeleteUser } from '@/api/useUsers';
|
||||
import { useAuth } from '@/contexts/auth-context';
|
||||
import { Trans } from 'react-i18next';
|
||||
import { ProblemDetailsError } from '@/lib/api-client';
|
||||
import type { UserRole, UserListItem } from '@/api/types';
|
||||
|
||||
function roleBadgeVariant(role: UserRole) {
|
||||
if (role === 'Owner') return 'default';
|
||||
if (role === 'Administrator') return 'secondary';
|
||||
return 'outline';
|
||||
}
|
||||
|
||||
function statusBadgeVariant(user: UserListItem) {
|
||||
if (user.invitationPending) return 'outline';
|
||||
if (!user.isActive) return 'destructive';
|
||||
return 'secondary';
|
||||
}
|
||||
|
||||
function statusLabel(user: UserListItem, t: (key: string) => string) {
|
||||
if (user.invitationPending) return t('users.status.pendingInvite');
|
||||
if (!user.isActive) return t('users.status.inactive');
|
||||
return t('users.status.active');
|
||||
}
|
||||
|
||||
function formatDate(iso: string) {
|
||||
return new Date(iso).toLocaleDateString(undefined, { dateStyle: 'medium' });
|
||||
}
|
||||
|
||||
/** Placeholder; full user management arrives in Unit 5. */
|
||||
export function UsersPage() {
|
||||
const { t } = useTranslation();
|
||||
const { user: currentUser, logout } = useAuth();
|
||||
const [inviteDialogOpen, setInviteDialogOpen] = useState(false);
|
||||
const [deleteTarget, setDeleteTarget] = useState<UserListItem | null>(null);
|
||||
const [selfRoleChangeTarget, setSelfRoleChangeTarget] = useState<{
|
||||
userId: string;
|
||||
newRole: UserRole;
|
||||
} | null>(null);
|
||||
const [ownerAssignTarget, setOwnerAssignTarget] = useState<{
|
||||
userId: string;
|
||||
userName: string;
|
||||
} | null>(null);
|
||||
const { data: users, isPending, isError } = useUsers();
|
||||
const changeRole = useChangeRole();
|
||||
const setUserActive = useSetUserActive();
|
||||
const deleteUser = useDeleteUser();
|
||||
|
||||
const availableRolesFor = (user: UserListItem): UserRole[] => {
|
||||
const isSelf = user.id === currentUser?.id;
|
||||
if (currentUser?.role === 'Owner') return ['Owner', 'Administrator', 'User'];
|
||||
if (currentUser?.role === 'Administrator') {
|
||||
// Admins can demote themselves to User; they cannot touch other Admins or Owners
|
||||
if (isSelf) return ['Administrator', 'User'];
|
||||
if (user.role === 'User') return ['Administrator'];
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
const isOwnerAction = (user: UserListItem) =>
|
||||
currentUser?.role === 'Owner' && user.id !== currentUser.id;
|
||||
|
||||
const canToggleActive = (user: UserListItem) =>
|
||||
isOwnerAction(user) && !user.invitationPending;
|
||||
|
||||
const canDelete = (user: UserListItem) => isOwnerAction(user);
|
||||
|
||||
const hasAnyActions = (user: UserListItem) =>
|
||||
user.invitationPending ||
|
||||
availableRolesFor(user).length > 0 ||
|
||||
canToggleActive(user) ||
|
||||
canDelete(user);
|
||||
|
||||
const handleCopyInviteLink = async (user: UserListItem) => {
|
||||
if (!user.inviteLink) return;
|
||||
await navigator.clipboard.writeText(`${window.location.origin}${user.inviteLink}`);
|
||||
toast.success(t('users.actions.linkCopied'));
|
||||
};
|
||||
|
||||
const handleRoleChange = (user: UserListItem, newRole: UserRole) => {
|
||||
if (user.id === currentUser?.id) {
|
||||
setSelfRoleChangeTarget({ userId: user.id, newRole });
|
||||
return;
|
||||
}
|
||||
if (newRole === 'Owner') {
|
||||
setOwnerAssignTarget({ userId: user.id, userName: user.name });
|
||||
return;
|
||||
}
|
||||
void executeRoleChange(user.id, newRole);
|
||||
};
|
||||
|
||||
const executeRoleChange = async (userId: string, newRole: UserRole) => {
|
||||
try {
|
||||
await changeRole.mutateAsync({ userId, newRole });
|
||||
} catch (err) {
|
||||
if (err instanceof ProblemDetailsError) {
|
||||
if (err.status === 400) {
|
||||
toast.error(t('users.errors.lastOwnerRequired'));
|
||||
} else if (err.status === 403) {
|
||||
toast.error(t('users.errors.insufficientPermissions'));
|
||||
} else {
|
||||
toast.error(t('errors.generic'));
|
||||
}
|
||||
} else {
|
||||
toast.error(t('errors.generic'));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelfRoleChangeConfirm = async () => {
|
||||
if (!selfRoleChangeTarget) return;
|
||||
try {
|
||||
await changeRole.mutateAsync(selfRoleChangeTarget);
|
||||
setSelfRoleChangeTarget(null);
|
||||
await logout();
|
||||
} catch (err) {
|
||||
setSelfRoleChangeTarget(null);
|
||||
if (err instanceof ProblemDetailsError && err.status === 400) {
|
||||
toast.error(t('users.errors.lastOwnerRequired'));
|
||||
} else {
|
||||
toast.error(t('errors.generic'));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleOwnerAssignConfirm = async () => {
|
||||
if (!ownerAssignTarget) return;
|
||||
try {
|
||||
await changeRole.mutateAsync({ userId: ownerAssignTarget.userId, newRole: 'Owner' });
|
||||
setOwnerAssignTarget(null);
|
||||
} catch (err) {
|
||||
setOwnerAssignTarget(null);
|
||||
if (err instanceof ProblemDetailsError && err.status === 400) {
|
||||
toast.error(t('users.errors.lastOwnerRequired'));
|
||||
} else if (err instanceof ProblemDetailsError && err.status === 403) {
|
||||
toast.error(t('users.errors.insufficientPermissions'));
|
||||
} else {
|
||||
toast.error(t('errors.generic'));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleSetActive = async (user: UserListItem, isActive: boolean) => {
|
||||
try {
|
||||
await setUserActive.mutateAsync({ userId: user.id, isActive });
|
||||
toast.success(
|
||||
isActive
|
||||
? t('users.active.successActivated', { name: user.name })
|
||||
: t('users.active.successDeactivated', { name: user.name }),
|
||||
);
|
||||
} catch (err) {
|
||||
if (err instanceof ProblemDetailsError && err.status === 400) {
|
||||
toast.error(t('users.errors.lastOwnerRequired'));
|
||||
} else {
|
||||
toast.error(t('errors.generic'));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteConfirm = async () => {
|
||||
if (!deleteTarget) return;
|
||||
try {
|
||||
await deleteUser.mutateAsync(deleteTarget.id);
|
||||
toast.success(t('users.delete.success', { name: deleteTarget.name }));
|
||||
setDeleteTarget(null);
|
||||
} catch (err) {
|
||||
if (err instanceof ProblemDetailsError && err.status === 400) {
|
||||
toast.error(t('users.errors.lastOwnerRequired'));
|
||||
setDeleteTarget(null);
|
||||
} else {
|
||||
toast.error(t('errors.generic'));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-semibold" data-testid="users-title">
|
||||
{t('nav.users')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">Coming soon.</p>
|
||||
<div className="space-y-4" data-testid="users-page">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-semibold" data-testid="users-title">
|
||||
{t('users.title')}
|
||||
</h1>
|
||||
<Button onClick={() => setInviteDialogOpen(true)} data-testid="users-invite-button">
|
||||
{t('users.inviteButton')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isPending && (
|
||||
<p className="text-sm text-muted-foreground">{t('common.loading')}</p>
|
||||
)}
|
||||
|
||||
{isError && (
|
||||
<p className="text-sm text-destructive">{t('errors.generic')}</p>
|
||||
)}
|
||||
|
||||
{users && (
|
||||
<Table data-testid="users-table">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{t('users.table.name')}</TableHead>
|
||||
<TableHead>{t('users.table.email')}</TableHead>
|
||||
<TableHead>{t('users.table.role')}</TableHead>
|
||||
<TableHead>{t('users.table.status')}</TableHead>
|
||||
<TableHead>{t('users.table.createdAt')}</TableHead>
|
||||
<TableHead className="w-12" />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{users.map((user) => {
|
||||
const roles = availableRolesFor(user);
|
||||
const toggleActive = canToggleActive(user);
|
||||
const deletable = canDelete(user);
|
||||
const showActions = hasAnyActions(user);
|
||||
return (
|
||||
<TableRow key={user.id} data-testid={`user-row-${user.id}`}>
|
||||
<TableCell className="font-medium">{user.name}</TableCell>
|
||||
<TableCell>{user.email}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={roleBadgeVariant(user.role)}>
|
||||
{t(`users.roles.${user.role}`)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={statusBadgeVariant(user)}>
|
||||
{statusLabel(user, t)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{formatDate(user.createdAt)}</TableCell>
|
||||
<TableCell>
|
||||
{showActions && <DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={t('users.table.actions')}
|
||||
data-testid={`user-actions-${user.id}`}
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuLabel>
|
||||
{t('users.table.actions')}
|
||||
</DropdownMenuLabel>
|
||||
|
||||
{user.invitationPending && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleCopyInviteLink(user)}
|
||||
data-testid={`user-copy-link-${user.id}`}
|
||||
>
|
||||
<LinkIcon className="mr-2 h-4 w-4" />
|
||||
{t('users.actions.copyInviteLink')}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
|
||||
{roles.length > 0 && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger
|
||||
data-testid={`user-change-role-${user.id}`}
|
||||
>
|
||||
{t('users.actions.changeRole')}
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuSubContent>
|
||||
{roles.map((role) => (
|
||||
<DropdownMenuItem
|
||||
key={role}
|
||||
disabled={role === user.role}
|
||||
onClick={() =>
|
||||
handleRoleChange(user, role)
|
||||
}
|
||||
>
|
||||
{t(`users.roles.${role}`)}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
</>
|
||||
)}
|
||||
|
||||
{toggleActive && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
handleSetActive(user, !user.isActive)
|
||||
}
|
||||
data-testid={`user-toggle-active-${user.id}`}
|
||||
>
|
||||
{user.isActive ? (
|
||||
<>
|
||||
<UserX className="mr-2 h-4 w-4" />
|
||||
{t('users.actions.deactivate')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<UserCheck className="mr-2 h-4 w-4" />
|
||||
{t('users.actions.activate')}
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
|
||||
{deletable && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
onClick={() => setDeleteTarget(user)}
|
||||
data-testid={`user-delete-${user.id}`}
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
{t('users.actions.delete')}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
|
||||
<InviteUserDialog open={inviteDialogOpen} onOpenChange={setInviteDialogOpen} />
|
||||
|
||||
<Dialog
|
||||
open={selfRoleChangeTarget !== null}
|
||||
onOpenChange={(open) => { if (!open) setSelfRoleChangeTarget(null); }}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('users.selfRoleChange.title')}</DialogTitle>
|
||||
<DialogDescription asChild>
|
||||
<div>
|
||||
<Trans
|
||||
i18nKey="users.selfRoleChange.description"
|
||||
values={{
|
||||
role: selfRoleChangeTarget
|
||||
? t(`users.roles.${selfRoleChangeTarget.newRole}`)
|
||||
: '',
|
||||
}}
|
||||
components={{ strong: <strong /> }}
|
||||
/>
|
||||
</div>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setSelfRoleChangeTarget(null)}
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSelfRoleChangeConfirm}
|
||||
disabled={changeRole.isPending}
|
||||
>
|
||||
{t('users.selfRoleChange.confirmButton')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={ownerAssignTarget !== null}
|
||||
onOpenChange={(open) => { if (!open) setOwnerAssignTarget(null); }}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('users.ownerAssign.title')}</DialogTitle>
|
||||
<DialogDescription asChild>
|
||||
<div>
|
||||
<Trans
|
||||
i18nKey="users.ownerAssign.description"
|
||||
values={{ name: ownerAssignTarget?.userName ?? '' }}
|
||||
components={{ strong: <strong /> }}
|
||||
/>
|
||||
</div>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setOwnerAssignTarget(null)}
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleOwnerAssignConfirm}
|
||||
disabled={changeRole.isPending}
|
||||
>
|
||||
{t('users.ownerAssign.confirmButton')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<DeleteUserDialog
|
||||
user={deleteTarget}
|
||||
open={deleteTarget !== null}
|
||||
onOpenChange={(open) => { if (!open) setDeleteTarget(null); }}
|
||||
onConfirm={handleDeleteConfirm}
|
||||
isPending={deleteUser.isPending}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -32,6 +32,21 @@ if (typeof globalAny.ResizeObserver === 'undefined') {
|
||||
};
|
||||
}
|
||||
|
||||
// Radix UI uses pointer capture APIs not present in jsdom.
|
||||
if (typeof Element.prototype.hasPointerCapture === 'undefined') {
|
||||
Element.prototype.hasPointerCapture = () => false;
|
||||
}
|
||||
if (typeof Element.prototype.setPointerCapture === 'undefined') {
|
||||
Element.prototype.setPointerCapture = () => {};
|
||||
}
|
||||
if (typeof Element.prototype.releasePointerCapture === 'undefined') {
|
||||
Element.prototype.releasePointerCapture = () => {};
|
||||
}
|
||||
// Radix scroll-into-view
|
||||
if (typeof Element.prototype.scrollIntoView === 'undefined') {
|
||||
Element.prototype.scrollIntoView = () => {};
|
||||
}
|
||||
|
||||
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
Reference in New Issue
Block a user