Restructures frontend to a feature-based folder layout
Continuous Integration / config (pull_request) Successful in 11s
Continuous Integration / changes (pull_request) Successful in 21s
Continuous Integration / backend-build (pull_request) Skipped
Continuous Integration / backend-test (pull_request) Skipped
Continuous Integration / vulnerability-scan (pull_request) Skipped
Continuous Integration / frontend-prepare (pull_request) Successful in 1m37s
Continuous Integration / frontend-build (pull_request) Successful in 2m12s
Continuous Integration / frontend-test (pull_request) Successful in 4m42s
Continuous Integration / frontend-lint (pull_request) Successful in 2m2s
Continuous Integration / publish-production (pull_request) Skipped
Continuous Integration / deploy-production (pull_request) Skipped
Continuous Integration / publish-test (pull_request) Successful in 6m51s
Continuous Integration / deploy-test (pull_request) Skipped
Continuous Integration / config (pull_request) Successful in 11s
Continuous Integration / changes (pull_request) Successful in 21s
Continuous Integration / backend-build (pull_request) Skipped
Continuous Integration / backend-test (pull_request) Skipped
Continuous Integration / vulnerability-scan (pull_request) Skipped
Continuous Integration / frontend-prepare (pull_request) Successful in 1m37s
Continuous Integration / frontend-build (pull_request) Successful in 2m12s
Continuous Integration / frontend-test (pull_request) Successful in 4m42s
Continuous Integration / frontend-lint (pull_request) Successful in 2m2s
Continuous Integration / publish-production (pull_request) Skipped
Continuous Integration / deploy-production (pull_request) Skipped
Continuous Integration / publish-test (pull_request) Successful in 6m51s
Continuous Integration / deploy-test (pull_request) Skipped
Groups auth, setup, invitation, profile, users, cms, availability and system code (services/hooks, components, schemas, mocks, pages) under src/features/<name> instead of splitting by technical layer (api/, components/, lib/schemas/, mocks/, pages/). Renames the old connection-oriented `api` layer to `services` per feature, and splits the monolithic api/types.ts into per-feature types.ts files (with ProblemDetails/ApiResult merged into lib/api-client.ts as shared infra). Layout-agnostic code (ui primitives, app shell, i18n, test utils, lib) stays at the top level. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -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 '@/features/auth/mocks/fixtures';
|
||||
import { _resetSetupStatusCache } from '@/router';
|
||||
|
||||
beforeEach(() => {
|
||||
_resetSetupStatusCache();
|
||||
});
|
||||
|
||||
async function openDialog() {
|
||||
mockAuthenticated();
|
||||
renderApp('/users');
|
||||
await screen.findByTestId('users-invite-button', {}, { timeout: 10000 });
|
||||
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,193 @@
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/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 '@/features/users/services/useUsers';
|
||||
import { inviteUserSchema, type InviteUserFormData } from '@/features/users/schemas/users';
|
||||
import { NetworkError } from '@/lib/api-client';
|
||||
|
||||
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 [serverError, setServerError] = useState<string | null>(null);
|
||||
const inviteUser = useInviteUser({
|
||||
onError: (err) => {
|
||||
if (err instanceof NetworkError) {
|
||||
setServerError(t('errors.network'));
|
||||
} else {
|
||||
setServerError(t('errors.generic'));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
setValue,
|
||||
reset,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<InviteUserFormData>({
|
||||
resolver: zodResolver(inviteUserSchema),
|
||||
});
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
if (!nextOpen) {
|
||||
setStep(1);
|
||||
setInviteLink(null);
|
||||
setServerError(null);
|
||||
inviteUser.reset();
|
||||
reset();
|
||||
}
|
||||
onOpenChange(nextOpen);
|
||||
};
|
||||
|
||||
const onSubmit = handleSubmit(async (values) => {
|
||||
setServerError(null);
|
||||
try {
|
||||
const response = await inviteUser.mutateAsync(values);
|
||||
setInviteLink(response.inviteLink);
|
||||
setStep(2);
|
||||
} catch {
|
||||
// error shown via serverError state
|
||||
}
|
||||
});
|
||||
|
||||
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={handleOpenChange}>
|
||||
<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={serverError !== null ? { message: serverError } : null}
|
||||
onDismiss={() => setServerError(null)}
|
||||
/>
|
||||
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { API_BASE } from '@/features/auth/mocks/fixtures';
|
||||
|
||||
export const invitationHandlers = [
|
||||
http.get(`${API_BASE}/api/v1/Invitation/validate`, ({ request }) => {
|
||||
const token = new URL(request.url).searchParams.get('token');
|
||||
|
||||
if (token === 'valid-token') {
|
||||
return HttpResponse.json(
|
||||
{ isValid: true, email: 'invited@example.com', name: null, errorCode: null },
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
|
||||
return HttpResponse.json(
|
||||
{ isValid: false, email: '', name: null, errorCode: 'EXPIRED' },
|
||||
{ status: 200 },
|
||||
);
|
||||
}),
|
||||
|
||||
http.post(`${API_BASE}/api/v1/Invitation/complete`, async ({ request }) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const body = await request.json() as any;
|
||||
|
||||
if (!body.token || !body.name || !body.password) {
|
||||
return HttpResponse.json(
|
||||
{ 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 },
|
||||
);
|
||||
}
|
||||
|
||||
return HttpResponse.json(
|
||||
{ message: 'Account created', user: { id: '2', name: body.name, email: 'invited@example.com', role: 'User' } },
|
||||
{ status: 201 },
|
||||
);
|
||||
}),
|
||||
];
|
||||
@@ -0,0 +1,86 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { renderApp, mockGuest } from '@/test/utils';
|
||||
import { server } from '@/mocks/server';
|
||||
import { setupUninitializedHandlers } from '@/mocks/index';
|
||||
import { _resetSetupStatusCache } from '@/router';
|
||||
|
||||
// Reset module-level setup status cache before each test.
|
||||
beforeEach(() => {
|
||||
_resetSetupStatusCache();
|
||||
});
|
||||
|
||||
describe('InviteCompletePage', () => {
|
||||
it('shows a loading spinner on mount while validating the token', async () => {
|
||||
server.use(...setupUninitializedHandlers);
|
||||
mockGuest();
|
||||
renderApp('/invite/complete?token=valid-token');
|
||||
|
||||
// Loading spinner should appear immediately.
|
||||
expect(await screen.findByTestId('invite-loading')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows an error state for an expired token', async () => {
|
||||
server.use(...setupUninitializedHandlers);
|
||||
mockGuest();
|
||||
renderApp('/invite/complete?token=expired-token');
|
||||
|
||||
expect(await screen.findByTestId('invite-error')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('invite-name-input')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows an error state for a used token', async () => {
|
||||
server.use(...setupUninitializedHandlers);
|
||||
mockGuest();
|
||||
renderApp('/invite/complete?token=used-token');
|
||||
|
||||
expect(await screen.findByTestId('invite-error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows an error state when no token is provided', async () => {
|
||||
server.use(...setupUninitializedHandlers);
|
||||
mockGuest();
|
||||
renderApp('/invite/complete');
|
||||
|
||||
expect(await screen.findByTestId('invite-error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the form with a read-only email for a valid token', async () => {
|
||||
server.use(...setupUninitializedHandlers);
|
||||
mockGuest();
|
||||
renderApp('/invite/complete?token=valid-token');
|
||||
|
||||
expect(await screen.findByTestId('invite-name-input')).toBeInTheDocument();
|
||||
const emailInput = screen.getByTestId('invite-email-input') as HTMLInputElement;
|
||||
expect(emailInput.value).toBe('invited@example.com');
|
||||
expect(emailInput.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('shows validation errors when submitting an empty form', async () => {
|
||||
server.use(...setupUninitializedHandlers);
|
||||
mockGuest();
|
||||
const user = userEvent.setup();
|
||||
renderApp('/invite/complete?token=valid-token');
|
||||
|
||||
const submit = await screen.findByTestId('invite-submit-button');
|
||||
await user.click(submit);
|
||||
|
||||
expect(await screen.findByTestId('invite-name-error')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('invite-password-error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows success message after a valid submission', async () => {
|
||||
server.use(...setupUninitializedHandlers);
|
||||
mockGuest();
|
||||
const user = userEvent.setup();
|
||||
renderApp('/invite/complete?token=valid-token');
|
||||
|
||||
await user.type(await screen.findByTestId('invite-name-input'), 'Bob User');
|
||||
await user.type(screen.getByTestId('invite-password-input'), 'ValidPass1!');
|
||||
await user.type(screen.getByTestId('invite-confirmPassword-input'), 'ValidPass1!');
|
||||
await user.click(screen.getByTestId('invite-submit-button'));
|
||||
|
||||
expect(await screen.findByTestId('invite-success')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,231 @@
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useNavigate, useSearch } from '@tanstack/react-router';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { invitationCompleteFormSchema, type InvitationCompleteFormData } from '@/features/auth/schemas/auth';
|
||||
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
|
||||
import { FieldError } from '@/components/ui/FieldError';
|
||||
import { useValidateInvitation, useCompleteInvitation } from '@/features/invitation/services/useInvitation';
|
||||
import { ProblemDetailsError, NetworkError } from '@/lib/api-client';
|
||||
|
||||
interface FormError {
|
||||
message: string;
|
||||
}
|
||||
|
||||
type LoadingState = 'loading' | 'ready' | 'error' | 'submitting' | 'success';
|
||||
|
||||
export function InviteCompletePage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const search = useSearch({ strict: false }) as { token?: string };
|
||||
const [serverError, setServerError] = useState<FormError | null>(null);
|
||||
const [loadingState, setLoadingState] = useState<LoadingState>('loading');
|
||||
|
||||
const token = search.token || null;
|
||||
const validationQuery = useValidateInvitation(token);
|
||||
const completeMutation = useCompleteInvitation();
|
||||
|
||||
// Handle validation query state changes
|
||||
if (!token) {
|
||||
if (loadingState === 'loading') {
|
||||
setLoadingState('error');
|
||||
}
|
||||
} else if (validationQuery.isPending && loadingState !== 'submitting') {
|
||||
// Still loading
|
||||
} else if (validationQuery.error || (validationQuery.data && !validationQuery.data.isValid)) {
|
||||
if (loadingState === 'loading') {
|
||||
setLoadingState('error');
|
||||
}
|
||||
} else if (validationQuery.data?.isValid && loadingState === 'loading') {
|
||||
setLoadingState('ready');
|
||||
}
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors, isSubmitting }
|
||||
} = useForm<InvitationCompleteFormData>({
|
||||
resolver: zodResolver(invitationCompleteFormSchema),
|
||||
mode: 'onBlur',
|
||||
defaultValues: {
|
||||
name: '',
|
||||
password: '',
|
||||
confirmPassword: ''
|
||||
}
|
||||
});
|
||||
|
||||
const onSubmit = handleSubmit(async (values) => {
|
||||
setServerError(null);
|
||||
setLoadingState('submitting');
|
||||
try {
|
||||
if (!token) {
|
||||
setServerError({ message: t('errors.invalidInvitationToken') });
|
||||
setLoadingState('error');
|
||||
return;
|
||||
}
|
||||
const { confirmPassword: _, ...fields } = values;
|
||||
await completeMutation.mutateAsync({ token, ...fields });
|
||||
setLoadingState('success');
|
||||
setTimeout(() => {
|
||||
navigate({ to: '/login' });
|
||||
}, 2000);
|
||||
} catch (err) {
|
||||
setLoadingState('ready');
|
||||
if (err instanceof ProblemDetailsError) {
|
||||
setServerError({ message: err.problem.detail || err.message || t('errors.generic') });
|
||||
} else if (err instanceof NetworkError) {
|
||||
setServerError({ message: t('errors.network') });
|
||||
} else {
|
||||
setServerError({ message: t('errors.generic') });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (loadingState === 'loading') {
|
||||
return (
|
||||
<div className="flex min-h-svh items-center justify-center bg-secondary/40 p-4" data-testid="invite-loading">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardContent className="pt-6">
|
||||
<div className="text-center space-y-4">
|
||||
<div
|
||||
className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-muted border-t-primary"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('inviteComplete.loadingMessage')}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (loadingState === 'error') {
|
||||
return (
|
||||
<div className="flex min-h-svh items-center justify-center bg-secondary/40 p-4" data-testid="invite-error">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-destructive">{t('errors.setupRequired')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('inviteComplete.invalidTokenMessage')}
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
onClick={() => navigate({ to: '/' })}
|
||||
>
|
||||
{t('inviteComplete.requestNewInvitationLink')}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (loadingState === 'success') {
|
||||
return (
|
||||
<div className="flex min-h-svh items-center justify-center bg-secondary/40 p-4" data-testid="invite-success">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardContent className="pt-6">
|
||||
<div className="text-center space-y-4">
|
||||
<div className="text-green-600 text-lg font-medium">
|
||||
✓ {t('inviteComplete.successMessage')}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('login.subtitle')}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const email = validationQuery.data?.email || '';
|
||||
|
||||
return (
|
||||
<div className="flex min-h-svh items-center justify-center bg-secondary/40 p-4">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardHeader>
|
||||
<CardTitle>{t('inviteComplete.title')}</CardTitle>
|
||||
<CardDescription>{t('login.subtitle')}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={onSubmit} noValidate className="space-y-4" data-testid="invite-complete-form">
|
||||
<FormErrorBanner
|
||||
error={serverError || (completeMutation.error ? { message: completeMutation.error.message } : null)}
|
||||
onDismiss={() => setServerError(null)}
|
||||
/>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">{t('inviteComplete.emailLabel')}</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
disabled
|
||||
data-testid="invite-email-input"
|
||||
className="bg-muted"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">{t('inviteComplete.nameLabel')}</Label>
|
||||
<Input
|
||||
id="name"
|
||||
type="text"
|
||||
placeholder="John Doe"
|
||||
data-testid="invite-name-input"
|
||||
aria-invalid={errors.name !== undefined}
|
||||
{...register('name')}
|
||||
/>
|
||||
{errors.name && <FieldError message={errors.name.message} testId="invite-name-error" />}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">{t('inviteComplete.passwordLabel')}</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="••••••••"
|
||||
data-testid="invite-password-input"
|
||||
aria-invalid={errors.password !== undefined}
|
||||
{...register('password')}
|
||||
/>
|
||||
{errors.password && <FieldError message={errors.password.message} testId="invite-password-error" />}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirmPassword">{t('inviteComplete.confirmPasswordLabel')}</Label>
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
placeholder="••••••••"
|
||||
data-testid="invite-confirmPassword-input"
|
||||
aria-invalid={errors.confirmPassword !== undefined}
|
||||
{...register('confirmPassword')}
|
||||
/>
|
||||
{errors.confirmPassword && <FieldError message={errors.confirmPassword.message} />}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isSubmitting || completeMutation.isPending}
|
||||
className="w-full"
|
||||
data-testid="invite-submit-button"
|
||||
>
|
||||
{isSubmitting || completeMutation.isPending ? '...' : t('inviteComplete.submitButton')}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export interface InvitationValidation {
|
||||
email: string;
|
||||
name: string | null;
|
||||
isValid: boolean;
|
||||
errorCode: 'EXPIRED' | 'USED' | 'NOT_FOUND' | null;
|
||||
}
|
||||
|
||||
export interface InviteCompleteRequest {
|
||||
token: string;
|
||||
name: string;
|
||||
password: string;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { createElement } from 'react';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE } from '@/features/auth/mocks/fixtures';
|
||||
import { useValidateInvitation, useCompleteInvitation } from '@/features/invitation/services/useInvitation';
|
||||
|
||||
function createWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
return ({ children }: { children: React.ReactNode }) =>
|
||||
createElement(QueryClientProvider, { client: queryClient }, children);
|
||||
}
|
||||
|
||||
describe('useValidateInvitation', () => {
|
||||
it('returns isValid=true for a valid token', async () => {
|
||||
const { result } = renderHook(() => useValidateInvitation('valid-token'), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isPending).toBe(false));
|
||||
|
||||
expect(result.current.data?.isValid).toBe(true);
|
||||
expect(result.current.data?.email).toBe('invited@example.com');
|
||||
});
|
||||
|
||||
it('returns isValid=false for an expired or unknown token', async () => {
|
||||
const { result } = renderHook(() => useValidateInvitation('expired-token'), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isPending).toBe(false));
|
||||
|
||||
expect(result.current.data?.isValid).toBe(false);
|
||||
});
|
||||
|
||||
it('does not fetch when token is null', () => {
|
||||
const { result } = renderHook(() => useValidateInvitation(null), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
expect(result.current.isPending).toBe(true);
|
||||
expect(result.current.fetchStatus).toBe('idle');
|
||||
});
|
||||
|
||||
it('enters error state on server error', async () => {
|
||||
server.use(
|
||||
http.get(`${API_BASE}/api/v1/Invitation/validate`, () =>
|
||||
HttpResponse.json({}, { status: 500 }),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useValidateInvitation('any-token'), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isPending).toBe(false));
|
||||
|
||||
expect(result.current.isError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useCompleteInvitation', () => {
|
||||
it('succeeds with valid token, name, and password', async () => {
|
||||
const { result } = renderHook(() => useCompleteInvitation(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.mutateAsync({
|
||||
token: 'valid-token',
|
||||
name: 'New User',
|
||||
password: 'Password1!',
|
||||
});
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
});
|
||||
|
||||
it('enters error state when token is invalid', async () => {
|
||||
const { result } = renderHook(() => useCompleteInvitation(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current
|
||||
.mutateAsync({ token: 'bad-token', name: 'User', password: 'Password1!' })
|
||||
.catch(() => {});
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isError).toBe(true));
|
||||
});
|
||||
|
||||
it('enters error state on server error', async () => {
|
||||
server.use(
|
||||
http.post(`${API_BASE}/api/v1/Invitation/complete`, () =>
|
||||
HttpResponse.json({}, { status: 500 }),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useCompleteInvitation(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current
|
||||
.mutateAsync({ token: 'valid-token', name: 'User', password: 'Password1!' })
|
||||
.catch(() => {});
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isError).toBe(true));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
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) {
|
||||
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() {
|
||||
return useMutation<void, Error, InviteCompleteRequest>({
|
||||
mutationFn: (data) => api.post('/api/v1/Invitation/complete', data),
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user