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

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:
2026-07-31 22:30:37 +02:00
co-authored by Claude Sonnet 5
parent 650cf09cfa
commit 11ec08aac3
83 changed files with 249 additions and 254 deletions
-75
View File
@@ -1,75 +0,0 @@
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, mockGuest } from '@/test/utils';
import { server } from '@/mocks/server';
import { API_BASE } from '@/mocks/auth/fixtures';
import { resetMockCmsInstances } from '@/mocks/cms/handlers';
import { _resetSetupStatusCache } from '@/router';
beforeEach(() => {
_resetSetupStatusCache();
resetMockCmsInstances();
});
const CMS_URL = `${API_BASE}/api/v1/CmsInstances`;
describe('CmsPage', () => {
it('renders the page title and Add button', async () => {
mockAuthenticated();
renderApp('/cms');
expect(await screen.findByTestId('cms-title', {}, { timeout: 10000 })).toBeInTheDocument();
expect(screen.getByTestId('cms-add-button')).toBeInTheDocument();
});
it('renders list of CMS instances from seed data', async () => {
mockAuthenticated();
renderApp('/cms');
const rows = await screen.findAllByTestId('cms-instance-row', {}, { timeout: 10000 });
expect(rows.length).toBe(2);
});
it('renders empty state when no instances exist', async () => {
mockAuthenticated();
server.use(http.get(CMS_URL, () => HttpResponse.json([])));
renderApp('/cms');
expect(await screen.findByTestId('cms-empty-state', {}, { timeout: 10000 })).toBeInTheDocument();
expect(screen.getByTestId('cms-empty-add-button')).toBeInTheDocument();
});
it('opens AddCmsInstanceDialog when Add button is clicked', async () => {
mockAuthenticated();
renderApp('/cms');
await screen.findByTestId('cms-add-button', {}, { timeout: 10000 });
await userEvent.click(screen.getByTestId('cms-add-button'));
expect(await screen.findByTestId('add-cms-name')).toBeInTheDocument();
});
it('adds a CMS instance successfully', async () => {
mockAuthenticated();
renderApp('/cms');
await screen.findByTestId('cms-add-button', {}, { timeout: 10000 });
await userEvent.click(screen.getByTestId('cms-add-button'));
await userEvent.type(screen.getByTestId('add-cms-name'), 'New CMS');
await userEvent.type(screen.getByTestId('add-cms-url'), 'http://new.example.com');
await userEvent.type(screen.getByTestId('add-cms-apikey-input'), 'secret-key');
await userEvent.click(screen.getByTestId('add-cms-submit'));
const rows = await screen.findAllByTestId('cms-instance-row', {}, { timeout: 10000 });
expect(rows.length).toBe(3);
});
it('redirects unauthenticated users to login', async () => {
mockGuest();
renderApp('/cms');
expect(await screen.findByTestId('login-form-submit-button')).toBeInTheDocument();
});
});
-72
View File
@@ -1,72 +0,0 @@
import { useState } from 'react';
import { LayoutGrid } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { CmsInstanceList } from '@/components/cms/CmsInstanceList';
import { AddCmsInstanceDialog } from '@/components/cms/AddCmsInstanceDialog';
import { SetStatusDialog } from '@/components/cms/SetStatusDialog';
import { useCmsInstances } from '@/api/useCmsInstances';
import type { CmsInstance } from '@/api/types';
export function CmsPage() {
const { t } = useTranslation();
const [addDialogOpen, setAddDialogOpen] = useState(false);
const [statusTarget, setStatusTarget] = useState<CmsInstance | null>(null);
const { data: instances, isPending, isError } = useCmsInstances();
return (
<div className="space-y-4 p-4">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-semibold" data-testid="cms-title">
{t('cms.title')}
</h1>
<Button
onClick={() => setAddDialogOpen(true)}
data-testid="cms-add-button"
>
{t('cms.addButton')}
</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>
)}
{!isPending && !isError && instances?.length === 0 && (
<div
className="flex flex-col items-center justify-center py-16 text-center space-y-4"
data-testid="cms-empty-state"
>
<LayoutGrid className="size-12 text-muted-foreground" />
<h2 className="text-xl font-semibold">{t('cms.emptyState.heading')}</h2>
<p className="text-muted-foreground max-w-sm">{t('cms.emptyState.description')}</p>
<Button onClick={() => setAddDialogOpen(true)} data-testid="cms-empty-add-button">
{t('cms.addButton')}
</Button>
</div>
)}
{!isPending && !isError && instances && instances.length > 0 && (
<CmsInstanceList
instances={instances}
onSetStatus={(instance) => setStatusTarget(instance)}
/>
)}
<AddCmsInstanceDialog
open={addDialogOpen}
onOpenChange={setAddDialogOpen}
/>
<SetStatusDialog
instance={statusTarget}
open={statusTarget !== null}
onOpenChange={(open) => { if (!open) setStatusTarget(null); }}
/>
</div>
);
}
-68
View File
@@ -1,68 +0,0 @@
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, mockGuest } from '@/test/utils';
import { server } from '@/mocks/server';
import { _resetSetupStatusCache } from '@/router';
beforeEach(() => {
_resetSetupStatusCache();
});
describe('DashboardPage', () => {
it('renders title and welcome message for authenticated user', async () => {
mockAuthenticated();
renderApp('/dashboard');
expect(await screen.findByTestId('dashboard-title')).toBeInTheDocument();
expect(screen.getByTestId('dashboard-welcome')).toBeInTheDocument();
});
it('displays the availability status badge when data loads', async () => {
mockAuthenticated();
renderApp('/dashboard');
await screen.findByTestId('dashboard-title');
// Availability badge should eventually appear after status loads
expect(await screen.findByTestId('availability-badge')).toBeInTheDocument();
});
it('shows retry button when availability fetch fails', async () => {
server.use(http.get('*/Availability/status', () => HttpResponse.error()));
mockAuthenticated();
renderApp('/dashboard');
await screen.findByTestId('dashboard-title');
expect(await screen.findByTestId('availability-retry')).toBeInTheDocument();
});
it('refetches availability when retry button is clicked', async () => {
let callCount = 0;
server.use(
http.get('*/Availability/status', () => {
callCount += 1;
if (callCount === 1) return HttpResponse.error();
return HttpResponse.json({ status: 'Available', checkedAt: new Date().toISOString(), message: '' });
}),
);
mockAuthenticated();
renderApp('/dashboard');
const retryButton = await screen.findByTestId('availability-retry');
await userEvent.click(retryButton);
expect(callCount).toBeGreaterThanOrEqual(2);
});
it('redirects unauthenticated users to login', async () => {
mockGuest();
renderApp('/dashboard');
expect(await screen.findByTestId('login-form-submit-button')).toBeInTheDocument();
expect(screen.queryByTestId('dashboard-title')).not.toBeInTheDocument();
});
});
-66
View File
@@ -1,66 +0,0 @@
import { useTranslation } from 'react-i18next';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { useAuth } from '@/contexts/auth-context';
import { useAvailabilityStatus } from '@/api/useAvailability';
import { AvailabilityStatusBadge } from '@/components/shared/AvailabilityStatusBadge';
export function DashboardPage() {
const { t } = useTranslation();
const { user } = useAuth();
const { data, isLoading, isError, refetch } = useAvailabilityStatus();
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-semibold" data-testid="dashboard-title">
{t('dashboard.title')}
</h1>
<p className="text-muted-foreground" data-testid="dashboard-welcome">
{t('dashboard.welcome', { name: user?.name ?? '' })}
</p>
</div>
<Card>
<CardHeader>
<CardTitle>{t('availability.title')}</CardTitle>
</CardHeader>
<CardContent>
{isLoading && (
<div
data-testid="availability-skeleton"
className="h-8 w-32 animate-pulse rounded-full bg-muted"
/>
)}
{!isLoading && data && (
<AvailabilityStatusBadge
status={data.status}
message={data.message}
stale={isError}
/>
)}
{isError && (
<div
data-testid="availability-error"
className="mt-3 flex items-center gap-3 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive"
>
<span>{t('availability.errorTitle')}</span>
<Button
variant="outline"
size="sm"
data-testid="availability-retry"
onClick={() => void refetch()}
>
{t('availability.retry')}
</Button>
</div>
)}
{!isLoading && !data && !isError && null}
</CardContent>
</Card>
</div>
);
}
@@ -1,86 +0,0 @@
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();
});
});
-231
View File
@@ -1,231 +0,0 @@
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 '@/lib/schemas/auth';
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
import { FieldError } from '@/components/ui/FieldError';
import { useValidateInvitation, useCompleteInvitation } from '@/api/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>
);
}
-49
View File
@@ -1,49 +0,0 @@
import { describe, expect, it } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderApp, mockGuest } from '@/test/utils';
import { TEST_CREDENTIALS } from '@/mocks/auth/fixtures';
describe('LoginPage', () => {
it('shows validation errors when submitting an empty form', async () => {
mockGuest();
const user = userEvent.setup();
renderApp('/login');
const submit = await screen.findByTestId('login-form-submit-button');
await user.click(submit);
expect(await screen.findByTestId('login-email-error')).toBeInTheDocument();
expect(await screen.findByTestId('login-password-error')).toBeInTheDocument();
});
it('logs in with valid credentials and lands on the dashboard', async () => {
mockGuest();
const user = userEvent.setup();
renderApp('/login');
await user.type(await screen.findByTestId('login-email-input'), TEST_CREDENTIALS.email);
await user.type(screen.getByTestId('login-password-input'), TEST_CREDENTIALS.password);
await user.click(screen.getByTestId('login-form-submit-button'));
expect(await screen.findByTestId('dashboard-title')).toBeInTheDocument();
});
it('shows an error banner on invalid credentials', async () => {
mockGuest();
const user = userEvent.setup();
renderApp('/login');
await user.type(await screen.findByTestId('login-email-input'), 'wrong@example.com');
await user.type(screen.getByTestId('login-password-input'), 'wrongpassword');
await user.click(screen.getByTestId('login-form-submit-button'));
const banner = await screen.findByTestId('login-error');
expect(banner).toBeInTheDocument();
// Still on the login page.
await waitFor(() =>
expect(screen.queryByTestId('dashboard-title')).not.toBeInTheDocument(),
);
});
});
-121
View File
@@ -1,121 +0,0 @@
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 { useAuth } from '@/contexts/auth-context';
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
import { loginFormSchema, type LoginFormData } from '@/lib/schemas/auth';
export function LoginPage() {
const { t } = useTranslation();
const { login } = useAuth();
const navigate = useNavigate();
const search = useSearch({ strict: false }) as { redirect?: string };
const [serverError, setServerError] = useState<string | null>(null);
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<LoginFormData>({
resolver: zodResolver(loginFormSchema),
mode: 'onTouched',
defaultValues: { email: '', password: '' },
});
const onSubmit = handleSubmit(async (values) => {
setServerError(null);
try {
await login(values.email, values.password);
await navigate({ to: (search.redirect as string | undefined) ?? '/dashboard' });
} catch (err) {
if (err instanceof ProblemDetailsError && err.status === 401) {
setServerError(t('login.errors.invalidCredentials'));
} else if (err instanceof NetworkError) {
setServerError(t('errors.network'));
} else {
setServerError(t('login.errors.generic'));
}
}
});
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('login.title')}</CardTitle>
<CardDescription>{t('login.subtitle')}</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={onSubmit} noValidate className="space-y-4">
{serverError !== null && (
<div
role="alert"
data-testid="login-error"
className="rounded-md border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm text-destructive"
>
{serverError}
</div>
)}
<div className="space-y-2">
<Label htmlFor="email">{t('login.email')}</Label>
<Input
id="email"
type="email"
autoComplete="email"
placeholder={t('login.emailPlaceholder')}
data-testid="login-email-input"
aria-invalid={errors.email !== undefined}
{...register('email')}
/>
{errors.email && (
<p
className="text-sm text-destructive"
data-testid="login-email-error"
>
{errors.email.message}
</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="password">{t('login.password')}</Label>
<Input
id="password"
type="password"
placeholder="••••••••"
autoComplete="current-password"
data-testid="login-password-input"
aria-invalid={errors.password !== undefined}
{...register('password')}
/>
{errors.password && (
<p
className="text-sm text-destructive"
data-testid="login-password-error"
>
{errors.password.message}
</p>
)}
</div>
<Button
type="submit"
className="w-full"
disabled={isSubmitting}
data-testid="login-form-submit-button"
>
{isSubmitting ? t('login.submitting') : t('login.submit')}
</Button>
</form>
</CardContent>
</Card>
</div>
);
}
-120
View File
@@ -1,120 +0,0 @@
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, mockGuest } from '@/test/utils';
import { server } from '@/mocks/server';
import { API_BASE } from '@/mocks/auth/fixtures';
import { _resetSetupStatusCache } from '@/router';
beforeEach(() => {
_resetSetupStatusCache();
});
describe('ProfilePage', () => {
it('renders the page title and profile form', async () => {
mockAuthenticated();
renderApp('/profile');
expect(await screen.findByTestId('profile-title', {}, { timeout: 10000 })).toBeInTheDocument();
expect(screen.getByTestId('profile-name-input')).toBeInTheDocument();
expect(screen.getByTestId('profile-email-input')).toBeInTheDocument();
expect(screen.getByTestId('profile-role-badge')).toBeInTheDocument();
});
it('pre-fills name and email from authenticated user', async () => {
mockAuthenticated();
renderApp('/profile');
const nameInput = await screen.findByTestId<HTMLInputElement>('profile-name-input');
const emailInput = screen.getByTestId<HTMLInputElement>('profile-email-input');
expect(nameInput.value).toBe('Test Owner');
expect(emailInput.value).toBe('owner@example.com');
});
it('save button is disabled when form is pristine', async () => {
mockAuthenticated();
renderApp('/profile');
await screen.findByTestId('profile-name-input');
expect(screen.getByTestId('profile-save-button')).toBeDisabled();
});
it('save button enables after editing a field', async () => {
mockAuthenticated();
renderApp('/profile');
const nameInput = await screen.findByTestId('profile-name-input');
await userEvent.clear(nameInput);
await userEvent.type(nameInput, 'Updated Name');
expect(screen.getByTestId('profile-save-button')).not.toBeDisabled();
});
it('saves profile successfully and shows success toast', async () => {
mockAuthenticated();
renderApp('/profile');
const nameInput = await screen.findByTestId('profile-name-input');
await userEvent.clear(nameInput);
await userEvent.type(nameInput, 'New Name');
await userEvent.click(screen.getByTestId('profile-save-button'));
expect(await screen.findByText(/profile updated/i, {}, { timeout: 10000 })).toBeInTheDocument();
});
it('shows validation error for invalid email', async () => {
mockAuthenticated();
renderApp('/profile');
// Type invalid email — this makes form dirty and triggers validation on submit
const emailInput = await screen.findByTestId('profile-email-input');
await userEvent.tripleClick(emailInput);
await userEvent.type(emailInput, 'not-an-email');
const saveButton = screen.getByTestId('profile-save-button');
expect(saveButton).not.toBeDisabled();
await userEvent.click(saveButton);
expect(await screen.findByTestId('profile-email-error')).toBeInTheDocument();
});
it('opens change password dialog when button is clicked', async () => {
mockAuthenticated();
renderApp('/profile');
await screen.findByTestId('change-password-button');
await userEvent.click(screen.getByTestId('change-password-button'));
expect(await screen.findByTestId('change-password-dialog')).toBeInTheDocument();
});
it('shows error in dialog when current password is wrong', async () => {
server.use(
http.post(`${API_BASE}/api/v1/Auth/change-password`, () =>
HttpResponse.json({ title: 'Bad Request' }, { status: 400 }),
),
);
mockAuthenticated();
renderApp('/profile');
await screen.findByTestId('change-password-button');
await userEvent.click(screen.getByTestId('change-password-button'));
await screen.findByTestId('change-password-dialog');
// PasswordField auto-generates testid as ${id}-input
await userEvent.type(screen.getByTestId('currentPassword-input'), 'WrongPass1!');
await userEvent.type(screen.getByTestId('newPassword-input'), 'NewPassword1!');
await userEvent.type(screen.getByTestId('confirmPassword-input'), 'NewPassword1!');
await userEvent.click(screen.getByTestId('change-password-submit'));
expect(await screen.findByTestId('current-password-error')).toBeInTheDocument();
});
it('redirects unauthenticated users to login', async () => {
mockGuest();
renderApp('/profile');
expect(await screen.findByTestId('login-form-submit-button')).toBeInTheDocument();
});
});
-287
View File
@@ -1,287 +0,0 @@
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { useAuth } from '@/contexts/auth-context';
import { useUpdateProfile, useChangePassword } from '@/api/useProfile';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { RoleBadge } from '@/components/shared/RoleBadge';
import { PasswordField } from '@/components/ui/PasswordField';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { ProblemDetailsError } from '@/lib/api-client';
const profileSchema = z.object({
name: z.string().min(1, 'Name is required'),
email: z.string().email('Enter a valid email address'),
});
const changePasswordSchema = z
.object({
currentPassword: z.string().min(1, 'Required'),
newPassword: z
.string()
.min(8, 'At least 8 characters')
.regex(/[A-Z]/, 'At least 1 uppercase letter')
.regex(/[a-z]/, 'At least 1 lowercase letter')
.regex(/[0-9]/, 'At least 1 digit')
.regex(/[^a-zA-Z0-9]/, 'At least 1 special character'),
confirmPassword: z.string().min(1, 'Required'),
})
.refine((d) => d.newPassword === d.confirmPassword, {
message: 'Passwords do not match',
path: ['confirmPassword'],
});
type ProfileFormData = z.infer<typeof profileSchema>;
type ChangePasswordFormData = z.infer<typeof changePasswordSchema>;
function ChangePasswordDialog({
open,
onClose,
}: {
open: boolean;
onClose: () => void;
}) {
const { t } = useTranslation();
const changePassword = useChangePassword();
const {
register,
handleSubmit,
reset,
setError,
formState: { errors, isSubmitting },
} = useForm<ChangePasswordFormData>({
resolver: zodResolver(changePasswordSchema),
});
const onSubmit = async (data: ChangePasswordFormData) => {
try {
await changePassword.mutateAsync({
currentPassword: data.currentPassword,
newPassword: data.newPassword,
});
toast.success(t('profile.changePasswordDialog.success'));
reset();
onClose();
} catch (err) {
if (err instanceof ProblemDetailsError && err.status === 400) {
setError('currentPassword', {
message: t('profile.changePasswordDialog.errorCurrent'),
});
} else {
setError('root', { message: t('errors.generic') });
}
}
};
const handleClose = () => {
reset();
onClose();
};
return (
<Dialog open={open} onOpenChange={(o) => { if (!o) handleClose(); }}>
<DialogContent data-testid="change-password-dialog">
<DialogHeader>
<DialogTitle>{t('profile.changePasswordDialog.title')}</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
{errors.root && (
<p className="text-sm text-destructive" data-testid="change-password-error">
{errors.root.message}
</p>
)}
<div className="space-y-1">
<Label htmlFor="currentPassword">
{t('profile.changePasswordDialog.current')}
</Label>
<PasswordField
id="currentPassword"
data-testid="current-password-input"
{...register('currentPassword')}
/>
{errors.currentPassword && (
<p className="text-sm text-destructive" data-testid="current-password-error">
{errors.currentPassword.message}
</p>
)}
</div>
<div className="space-y-1">
<Label htmlFor="newPassword">
{t('profile.changePasswordDialog.new')}
</Label>
<PasswordField
id="newPassword"
data-testid="new-password-input"
{...register('newPassword')}
/>
{errors.newPassword && (
<p className="text-sm text-destructive" data-testid="new-password-error">
{errors.newPassword.message}
</p>
)}
</div>
<div className="space-y-1">
<Label htmlFor="confirmPassword">
{t('profile.changePasswordDialog.confirm')}
</Label>
<PasswordField
id="confirmPassword"
data-testid="confirm-password-input"
{...register('confirmPassword')}
/>
{errors.confirmPassword && (
<p className="text-sm text-destructive" data-testid="confirm-password-error">
{errors.confirmPassword.message}
</p>
)}
</div>
<div className="flex justify-end gap-2 pt-2">
<Button
type="button"
variant="outline"
onClick={handleClose}
data-testid="change-password-cancel"
>
{t('common.cancel')}
</Button>
<Button
type="submit"
disabled={isSubmitting}
data-testid="change-password-submit"
>
{isSubmitting
? t('profile.changePasswordDialog.submitting')
: t('profile.changePasswordDialog.submit')}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
);
}
export function ProfilePage() {
const { t } = useTranslation();
const { user } = useAuth();
const updateProfile = useUpdateProfile();
const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);
const {
register,
handleSubmit,
formState: { errors, isSubmitting, isDirty },
} = useForm<ProfileFormData>({
resolver: zodResolver(profileSchema),
defaultValues: {
name: user?.name ?? '',
email: user?.email ?? '',
},
});
const onSubmit = async (data: ProfileFormData) => {
try {
await updateProfile.mutateAsync(data);
toast.success(t('profile.saveSuccess'));
} catch (err) {
if (err instanceof ProblemDetailsError && err.status === 400) {
toast.error(t('errors.generic'));
} else {
toast.error(t('errors.generic'));
}
}
};
return (
<div className="space-y-6 max-w-lg">
<h1 className="text-2xl font-semibold" data-testid="profile-title">
{t('profile.title')}
</h1>
{/* Profile info card */}
<Card>
<CardHeader>
<CardTitle className="text-base">{t('profile.title')}</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div className="space-y-1">
<Label htmlFor="name">{t('profile.name')}</Label>
<Input
id="name"
data-testid="profile-name-input"
{...register('name')}
/>
{errors.name && (
<p className="text-sm text-destructive" data-testid="profile-name-error">
{errors.name.message}
</p>
)}
</div>
<div className="space-y-1">
<Label htmlFor="email">{t('profile.email')}</Label>
<Input
id="email"
type="email"
data-testid="profile-email-input"
{...register('email')}
/>
{errors.email && (
<p className="text-sm text-destructive" data-testid="profile-email-error">
{errors.email.message}
</p>
)}
</div>
<div className="space-y-1">
<Label>{t('profile.role')}</Label>
<div>
{user?.role
? <RoleBadge role={user.role} data-testid="profile-role-badge" />
: <span data-testid="profile-role-badge">—</span>}
</div>
</div>
<Button
type="submit"
disabled={isSubmitting || !isDirty}
data-testid="profile-save-button"
>
{isSubmitting ? t('profile.saving') : t('profile.save')}
</Button>
</form>
</CardContent>
</Card>
{/* Security card */}
<Card>
<CardHeader>
<CardTitle className="text-base">Security</CardTitle>
</CardHeader>
<CardContent>
<Button
variant="outline"
onClick={() => setPasswordDialogOpen(true)}
data-testid="change-password-button"
>
{t('profile.changePassword')}
</Button>
</CardContent>
</Card>
<ChangePasswordDialog
open={passwordDialogOpen}
onClose={() => setPasswordDialogOpen(false)}
/>
</div>
);
}
-136
View File
@@ -1,136 +0,0 @@
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, mockGuest } from '@/test/utils';
import { server } from '@/mocks/server';
import { API_BASE } from '@/mocks/auth/fixtures';
import { _resetSetupStatusCache } from '@/router';
beforeEach(() => {
_resetSetupStatusCache();
});
describe('SettingsPage', () => {
it('renders the page title', async () => {
mockAuthenticated();
renderApp('/settings');
expect(await screen.findByTestId('settings-title', {}, { timeout: 10000 })).toBeInTheDocument();
});
it('shows the current availability status badge', async () => {
mockAuthenticated();
renderApp('/settings');
expect(await screen.findByTestId('availability-badge', {}, { timeout: 10000 })).toBeInTheDocument();
});
it('renders all three availability mode buttons', async () => {
mockAuthenticated();
renderApp('/settings');
await screen.findByTestId('availability-mode-selector', {}, { timeout: 10000 });
expect(screen.getByTestId('mode-option-Available')).toBeInTheDocument();
expect(screen.getByTestId('mode-option-Maintenance')).toBeInTheDocument();
expect(screen.getByTestId('mode-option-NotAvailable')).toBeInTheDocument();
});
it('selecting a mode highlights that mode button', async () => {
mockAuthenticated();
renderApp('/settings');
await screen.findByTestId('availability-mode-selector', {}, { timeout: 10000 });
const maintenanceBtn = screen.getByTestId('mode-option-Maintenance');
await userEvent.click(maintenanceBtn);
expect(maintenanceBtn.className).toContain('bg-primary');
});
it('saves availability and shows success toast', async () => {
mockAuthenticated();
renderApp('/settings');
await screen.findByTestId('availability-save-button', {}, { timeout: 10000 });
await userEvent.click(screen.getByTestId('availability-save-button'));
expect(await screen.findByText(/availability updated/i, {}, { timeout: 10000 })).toBeInTheDocument();
});
it('shows error toast when save fails', async () => {
server.use(
http.post(`${API_BASE}/api/v1/Availability/admin/status`, () =>
HttpResponse.json({ title: 'Error' }, { status: 500 }),
),
);
mockAuthenticated();
renderApp('/settings');
await screen.findByTestId('availability-save-button', {}, { timeout: 10000 });
await userEvent.click(screen.getByTestId('availability-save-button'));
expect(await screen.findByText(/something went wrong/i, {}, { timeout: 10000 })).toBeInTheDocument();
});
it('disables the availability controls and shows a banner when master-controlled', async () => {
server.use(
http.get(`${API_BASE}/api/v1/Availability/status`, () =>
HttpResponse.json({
status: 'NotAvailable',
checkedAt: new Date().toISOString(),
message: 'Uitgeschakeld door master',
isMasterControlled: true,
}),
),
);
mockAuthenticated();
renderApp('/settings');
expect(await screen.findByTestId('availability-master-controlled-banner', {}, { timeout: 10000 })).toBeInTheDocument();
expect(screen.getByTestId('mode-option-Available')).toBeDisabled();
expect(screen.getByTestId('mode-option-Maintenance')).toBeDisabled();
expect(screen.getByTestId('mode-option-NotAvailable')).toBeDisabled();
expect(screen.getByTestId('availability-reason-input')).toBeDisabled();
expect(screen.getByTestId('availability-save-button')).toBeDisabled();
});
it('does not show the master-controlled banner when not master-controlled', async () => {
mockAuthenticated();
renderApp('/settings');
await screen.findByTestId('availability-save-button', {}, { timeout: 10000 });
expect(screen.queryByTestId('availability-master-controlled-banner')).not.toBeInTheDocument();
expect(screen.getByTestId('availability-save-button')).not.toBeDisabled();
});
it('shows a master-controlled error toast on a 409 conflict from the server', async () => {
server.use(
http.post(`${API_BASE}/api/v1/Availability/admin/status`, () =>
HttpResponse.json({ title: 'Conflict' }, { status: 409 }),
),
);
mockAuthenticated();
renderApp('/settings');
await screen.findByTestId('availability-save-button', {}, { timeout: 10000 });
await userEvent.click(screen.getByTestId('availability-save-button'));
expect(await screen.findByText(/master cms controls this status/i, {}, { timeout: 10000 })).toBeInTheDocument();
});
it('renders all placeholder sections', async () => {
mockAuthenticated();
renderApp('/settings');
await screen.findByTestId('settings-title', {}, { timeout: 10000 });
expect(screen.getByTestId('placeholder-settings.modules.title')).toBeInTheDocument();
expect(screen.getByTestId('placeholder-settings.systemConfig.title')).toBeInTheDocument();
expect(screen.getByTestId('placeholder-settings.branding.title')).toBeInTheDocument();
});
it('redirects unauthenticated users to login', async () => {
mockGuest();
renderApp('/settings');
expect(await screen.findByTestId('login-form-submit-button')).toBeInTheDocument();
});
});
-164
View File
@@ -1,164 +0,0 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { Lock } from 'lucide-react';
import { useAvailabilityStatus, useUpdateAvailability } from '@/api/useAvailability';
import { AvailabilityStatusBadge } from '@/components/shared/AvailabilityStatusBadge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { ProblemDetailsError } from '@/lib/api-client';
import type { AvailabilityStatus } from '@/api/types';
function PlaceholderCard({ titleKey, comingSoonKey }: { titleKey: string; comingSoonKey: string }) {
const { t } = useTranslation();
return (
<Card className="opacity-60">
<CardHeader className="flex flex-row items-center gap-2">
<Lock className="size-4 text-muted-foreground" />
<CardTitle className="text-base">{t(titleKey)}</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground" data-testid={`placeholder-${titleKey}`}>
{t(comingSoonKey)}
</p>
</CardContent>
</Card>
);
}
export function SettingsPage() {
const { t } = useTranslation();
const { data: availability, isLoading } = useAvailabilityStatus();
const updateAvailability = useUpdateAvailability();
const [selectedMode, setSelectedMode] = useState<AvailabilityStatus>('Available');
const [reason, setReason] = useState('');
// Adjusts local edit state when the fetched availability changes, without an Effect
// (https://react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes).
const [syncedAvailability, setSyncedAvailability] = useState(availability);
if (availability !== syncedAvailability) {
setSyncedAvailability(availability);
if (availability) {
setSelectedMode(availability.status);
setReason(availability.message ?? '');
}
}
const isMasterControlled = availability?.isMasterControlled ?? false;
const handleSave = async () => {
try {
await updateAvailability.mutateAsync({ newStatus: selectedMode, reason });
toast.success(t('settings.availability.saveSuccess'));
} catch (err) {
if (err instanceof ProblemDetailsError && err.status === 409) {
toast.error(t('settings.availability.masterControlledSaveError'));
} else {
toast.error(t('errors.generic'));
}
}
};
const modes: AvailabilityStatus[] = ['Available', 'Maintenance', 'NotAvailable'];
return (
<div className="space-y-6 max-w-xl">
<h1 className="text-2xl font-semibold" data-testid="settings-title">
{t('settings.title')}
</h1>
{/* Availability section */}
<Card>
<CardHeader>
<CardTitle className="text-base">{t('settings.availability.title')}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{isLoading ? (
<p className="text-sm text-muted-foreground">{t('common.loading')}</p>
) : availability ? (
<AvailabilityStatusBadge
status={availability.status}
message={availability.message}
/>
) : null}
{isMasterControlled && (
<div
data-testid="availability-master-controlled-banner"
className="flex items-start gap-2 rounded-md border border-amber-400/50 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:bg-amber-950 dark:text-amber-200"
>
<Lock className="size-4 mt-0.5 shrink-0" />
<div>
<p className="font-medium">{t('settings.availability.masterControlledTitle')}</p>
<p>{t('settings.availability.masterControlled')}</p>
</div>
</div>
)}
<div className="space-y-2">
<Label>{t('settings.availability.mode')}</Label>
<div className="flex gap-2 flex-wrap" data-testid="availability-mode-selector">
{modes.map((mode) => (
<button
key={mode}
type="button"
onClick={() => setSelectedMode(mode)}
disabled={isMasterControlled}
data-testid={`mode-option-${mode}`}
className={`rounded-full border px-4 py-1.5 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
selectedMode === mode
? 'border-primary bg-primary text-primary-foreground'
: 'border-input bg-background hover:bg-accent'
}`}
>
{t(`settings.availability.modes.${mode}`)}
</button>
))}
</div>
</div>
<div className="space-y-1">
<Label htmlFor="availability-reason">
{t('settings.availability.reason')}
</Label>
<textarea
id="availability-reason"
rows={2}
value={reason}
onChange={(e) => setReason(e.target.value)}
disabled={isMasterControlled}
data-testid="availability-reason-input"
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
placeholder={t('settings.availability.reason')}
/>
</div>
<Button
onClick={handleSave}
disabled={updateAvailability.isPending || isMasterControlled}
data-testid="availability-save-button"
>
{updateAvailability.isPending
? t('settings.availability.saving')
: t('settings.availability.save')}
</Button>
</CardContent>
</Card>
<PlaceholderCard
titleKey="settings.modules.title"
comingSoonKey="settings.modules.comingSoon"
/>
<PlaceholderCard
titleKey="settings.systemConfig.title"
comingSoonKey="settings.systemConfig.comingSoon"
/>
<PlaceholderCard
titleKey="settings.branding.title"
comingSoonKey="settings.branding.comingSoon"
/>
</div>
);
}
-108
View File
@@ -1,108 +0,0 @@
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, setupConflictHandlers } from '@/mocks/index';
import { _resetSetupStatusCache } from '@/router';
// Each test starts with a fresh setup status cache so the MSW handler controls
// what the InitGuard fetches (BR-U2-08).
beforeEach(() => {
_resetSetupStatusCache();
});
describe('SetupPage', () => {
it('renders all five form fields when system is uninitialized', async () => {
server.use(...setupUninitializedHandlers);
mockGuest();
renderApp('/setup');
expect(await screen.findByTestId('setup-name-input')).toBeInTheDocument();
expect(screen.getByTestId('setup-email-input')).toBeInTheDocument();
expect(screen.getByTestId('setup-password-input')).toBeInTheDocument();
expect(screen.getByTestId('setup-confirmPassword-input')).toBeInTheDocument();
expect(screen.getByTestId('setup-locale-select')).toBeInTheDocument();
expect(screen.getByTestId('setup-submit-button')).toBeInTheDocument();
});
it('shows inline validation errors when submitting an empty form', async () => {
server.use(...setupUninitializedHandlers);
mockGuest();
const user = userEvent.setup();
renderApp('/setup');
const submit = await screen.findByTestId('setup-submit-button');
await user.click(submit);
expect(await screen.findByTestId('setup-name-error')).toBeInTheDocument();
expect(screen.getByTestId('setup-email-error')).toBeInTheDocument();
expect(screen.getByTestId('setup-password-error')).toBeInTheDocument();
});
it('shows password error for a weak password (no uppercase)', async () => {
server.use(...setupUninitializedHandlers);
mockGuest();
const user = userEvent.setup();
renderApp('/setup');
const passwordInput = await screen.findByTestId('setup-password-input');
await user.type(passwordInput, 'weakpassword1!');
await user.tab();
expect(await screen.findByTestId('setup-password-error')).toBeInTheDocument();
});
it('shows confirm-password error when passwords do not match', async () => {
server.use(...setupUninitializedHandlers);
mockGuest();
const user = userEvent.setup();
renderApp('/setup');
const passwordInput = await screen.findByTestId('setup-password-input');
const confirmInput = screen.getByTestId('setup-confirmPassword-input');
await user.type(passwordInput, 'ValidPass1!');
await user.type(confirmInput, 'DifferentPass1!');
await user.tab();
expect(await screen.findByTestId('setup-confirm-error')).toBeInTheDocument();
});
it('shows success message after a valid submission', async () => {
server.use(...setupUninitializedHandlers);
mockGuest();
const user = userEvent.setup();
renderApp('/setup');
await user.type(await screen.findByTestId('setup-name-input'), 'Alice Owner');
await user.type(screen.getByTestId('setup-email-input'), 'alice@example.com');
await user.type(screen.getByTestId('setup-password-input'), 'ValidPass1!');
await user.type(screen.getByTestId('setup-confirmPassword-input'), 'ValidPass1!');
await user.click(screen.getByTestId('setup-submit-button'));
expect(await screen.findByTestId('setup-success')).toBeInTheDocument();
});
it('shows "already initialized" banner on 409 response', async () => {
server.use(...setupConflictHandlers);
mockGuest();
const user = userEvent.setup();
renderApp('/setup');
await user.type(await screen.findByTestId('setup-name-input'), 'Alice Owner');
await user.type(screen.getByTestId('setup-email-input'), 'alice@example.com');
await user.type(screen.getByTestId('setup-password-input'), 'ValidPass1!');
await user.type(screen.getByTestId('setup-confirmPassword-input'), 'ValidPass1!');
await user.click(screen.getByTestId('setup-submit-button'));
expect(await screen.findByTestId('form-error-banner')).toBeInTheDocument();
});
it('redirects to /login when system is already initialized', async () => {
// Default setupHandlers return { initialized: true } — InitGuard redirects.
mockGuest();
renderApp('/setup');
expect(await screen.findByTestId('login-form-submit-button')).toBeInTheDocument();
});
});
-186
View File
@@ -1,186 +0,0 @@
import { useState } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useNavigate } 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 { setupFormSchema, type SetupFormData } from '@/lib/schemas/auth';
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
import { FieldError } from '@/components/ui/FieldError';
import { useSetup } from '@/api/useSetup';
import { ProblemDetailsError, NetworkError } from '@/lib/api-client';
import { changeLanguage } from '@/i18n/config';
import { _markSystemInitialized } from '@/router';
interface FormError {
message: string;
}
export function SetupPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const [serverError, setServerError] = useState<FormError | null>(null);
const [successMessage, setSuccessMessage] = useState(false);
const setupMutation = useSetup();
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
control
} = useForm<SetupFormData>({
resolver: zodResolver(setupFormSchema),
mode: 'onBlur',
defaultValues: {
name: '',
email: '',
password: '',
confirmPassword: '',
language: 'nl'
}
});
const onSubmit = handleSubmit(async (values) => {
setServerError(null);
try {
const { confirmPassword: _, ...payload } = values;
await setupMutation.mutateAsync(payload);
await changeLanguage(values.language);
_markSystemInitialized();
setSuccessMessage(true);
setTimeout(() => {
navigate({ to: '/login' });
}, 2000);
} catch (err) {
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 (successMessage) {
return (
<div className="flex min-h-svh items-center justify-center bg-secondary/40 p-4" data-testid="setup-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('setup.successMessage')}
</div>
<p className="text-sm text-muted-foreground">
{t('login.subtitle')}
</p>
</div>
</CardContent>
</Card>
</div>
);
}
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('setup.title')}</CardTitle>
<CardDescription>{t('login.subtitle')}</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={onSubmit} noValidate className="space-y-4" data-testid="setup-form">
<FormErrorBanner
error={serverError || (setupMutation.error ? { message: setupMutation.error.message } : null)}
onDismiss={() => setServerError(null)}
/>
<div className="space-y-2">
<Label htmlFor="name">{t('setup.nameLabel')}</Label>
<Input
id="name"
type="text"
placeholder="John Doe"
data-testid="setup-name-input"
aria-invalid={errors.name !== undefined}
{...register('name')}
/>
{errors.name && <FieldError message={errors.name.message} testId="setup-name-error" />}
</div>
<div className="space-y-2">
<Label htmlFor="email">{t('setup.emailLabel')}</Label>
<Input
id="email"
type="email"
placeholder="owner@example.com"
data-testid="setup-email-input"
aria-invalid={errors.email !== undefined}
{...register('email')}
/>
{errors.email && <FieldError message={errors.email.message} testId="setup-email-error" />}
</div>
<div className="space-y-2">
<Label htmlFor="password">{t('setup.passwordLabel')}</Label>
<Input
id="password"
type="password"
placeholder="••••••••"
data-testid="setup-password-input"
aria-invalid={errors.password !== undefined}
{...register('password')}
/>
{errors.password && <FieldError message={errors.password.message} testId="setup-password-error" />}
</div>
<div className="space-y-2">
<Label htmlFor="confirmPassword">{t('setup.confirmPasswordLabel')}</Label>
<Input
id="confirmPassword"
type="password"
placeholder="••••••••"
data-testid="setup-confirmPassword-input"
aria-invalid={errors.confirmPassword !== undefined}
{...register('confirmPassword')}
/>
{errors.confirmPassword && <FieldError message={errors.confirmPassword.message} testId="setup-confirm-error" />}
</div>
<div className="space-y-2">
<Label htmlFor="language">{t('setup.languageLabel')}</Label>
<Controller
name="language"
control={control}
render={({ field }) => (
<select
{...field}
id="language"
data-testid="setup-locale-select"
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
<option value="nl">Nederlands</option>
<option value="en">English</option>
</select>
)}
/>
</div>
<Button
type="submit"
disabled={isSubmitting || setupMutation.isPending}
className="w-full"
data-testid="setup-submit-button"
>
{isSubmitting || setupMutation.isPending ? '...' : t('setup.submitButton')}
</Button>
</form>
</CardContent>
</Card>
</div>
);
}
-78
View File
@@ -1,78 +0,0 @@
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: 10000 })).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();
});
});
-440
View File
@@ -1,440 +0,0 @@
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 { RoleBadge } from '@/components/shared/RoleBadge';
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 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' });
}
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-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>
<RoleBadge role={user.role} />
</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>
);
}