U2 identity-mail-flows (frontend en documentatie): taalkeuze, mailresultaat, opnieuw mailen

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 19:15:47 +01:00
co-authored by Claude Sonnet 5.5
parent 149f81a479
commit 3cba2facb3
16 changed files with 496 additions and 9 deletions
@@ -0,0 +1,5 @@
/** A short, human reason for a failed mail (codes come from the server; unknown codes read as generic). */
export function mailErrorText(t: (key: string) => string, error: string | null | undefined): string {
const known = ['timeout', 'auth_failed', 'rejected', 'not_configured', 'unknown'];
return t(`users.invite.mailErrors.${known.includes(error ?? '') ? error : 'unknown'}`);
}
@@ -0,0 +1,269 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { act, renderHook, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { I18nextProvider } from 'react-i18next';
import type { ReactNode } from 'react';
import { renderApp, mockAuthenticated } from '@/test/utils';
import { server } from '@/mocks/server';
import { API_BASE, makeAuthResponse, mockUser } from '@/features/auth/mocks/fixtures';
import { getMockUsers } from '@/features/users/mocks/handlers';
import { AuthProvider } from '@/features/auth/context/AuthProvider';
import { useAuth } from '@/features/auth/context/auth-context';
import { _resetSetupStatusCache } from '@/router';
import i18n from '@/i18n/config';
beforeEach(() => {
_resetSetupStatusCache();
});
const USERS = `${API_BASE}/api/v1/Users`;
function mailOn(defaultLanguage: 'nl' | 'en' = 'nl') {
server.use(
http.get('*/System/capabilities', () =>
HttpResponse.json({ modules: ['Availability', 'Identity'], emailEnabled: true, defaultLanguage }),
),
);
}
async function openInviteDialog() {
renderApp('/users');
await screen.findByTestId('users-invite-button', {}, { timeout: 10000 });
await userEvent.click(screen.getByTestId('users-invite-button'));
}
async function fillInvite(email = 'new@example.com') {
await userEvent.type(screen.getByTestId('invite-dialog-email'), email);
await userEvent.click(screen.getByTestId('invite-dialog-role'));
const options = await screen.findAllByRole('option');
await userEvent.click(options.find((o) => o.textContent === 'User')!);
}
describe('invite dialog with mail', () => {
it('has no language field on a site without mail (the dialog is unchanged)', async () => {
mockAuthenticated();
await openInviteDialog();
expect(screen.queryByTestId('invite-dialog-language')).not.toBeInTheDocument();
});
it('offers a language, defaulting to the site language, and sends the chosen one', async () => {
mockAuthenticated();
mailOn('en');
let body: Record<string, unknown> | undefined;
server.use(
http.post(`${USERS}/invite`, async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ inviteLink: '/invite/complete?token=abc', mail: { sent: true, error: null } });
}),
);
await openInviteDialog();
const select = (await screen.findByTestId('invite-dialog-language')) as HTMLSelectElement;
expect(select.value).toBe('en');
await userEvent.selectOptions(select, 'nl');
await fillInvite();
await userEvent.click(screen.getByTestId('invite-dialog-submit'));
await screen.findByTestId('invite-dialog-link-input');
expect(body).toMatchObject({ email: 'new@example.com', role: 'User', language: 'nl' });
});
it('says the mail was sent, next to the copyable link', async () => {
mockAuthenticated();
mailOn();
server.use(
http.post(`${USERS}/invite`, () =>
HttpResponse.json({ inviteLink: '/invite/complete?token=abc', mail: { sent: true, error: null } }),
),
);
await openInviteDialog();
await fillInvite('sent@example.com');
await userEvent.click(screen.getByTestId('invite-dialog-submit'));
const result = await screen.findByTestId('invite-dialog-mail-result');
expect(result).toHaveTextContent('sent@example.com');
expect(screen.getByTestId('invite-dialog-link-input')).toBeInTheDocument();
expect(screen.getByTestId('invite-dialog-copy')).toBeInTheDocument();
});
it('explains a failed mail with a reason and still shows the link', async () => {
mockAuthenticated();
mailOn();
server.use(
http.post(`${USERS}/invite`, () =>
HttpResponse.json({ inviteLink: '/invite/complete?token=abc', mail: { sent: false, error: 'timeout' } }),
),
);
await openInviteDialog();
await fillInvite();
await userEvent.click(screen.getByTestId('invite-dialog-submit'));
const result = await screen.findByTestId('invite-dialog-mail-result');
expect(result).toHaveTextContent(/could not be sent/i);
expect(result).toHaveTextContent(/did not respond in time/i);
expect(screen.getByTestId('invite-dialog-link-input')).toBeInTheDocument();
});
it('shows no mail line on a site without mail', async () => {
mockAuthenticated();
server.use(
http.post(`${USERS}/invite`, () => HttpResponse.json({ inviteLink: '/invite/complete?token=abc', mail: null })),
);
await openInviteDialog();
await fillInvite();
await userEvent.click(screen.getByTestId('invite-dialog-submit'));
await screen.findByTestId('invite-dialog-link-input');
expect(screen.queryByTestId('invite-dialog-mail-result')).not.toBeInTheDocument();
});
});
describe('users list: resend', () => {
it('has no resend action on a site without mail', async () => {
mockAuthenticated();
renderApp('/users');
await screen.findByTestId('users-table');
const pending = getMockUsers().find((u) => u.invitationPending)!;
await userEvent.click(screen.getByTestId(`user-actions-${pending.id}`));
expect(screen.queryByTestId(`user-resend-invite-${pending.id}`)).not.toBeInTheDocument();
expect(screen.getByTestId(`user-copy-link-${pending.id}`)).toBeInTheDocument();
});
it('resends the mail for an open invitation', async () => {
mockAuthenticated();
mailOn();
let called = false;
server.use(
http.post(`${USERS}/:id/resend-invite`, () => {
called = true;
return HttpResponse.json({ inviteLink: '/invite/complete?token=old', mail: { sent: true, error: null } });
}),
);
renderApp('/users');
await screen.findByTestId('users-table');
const pending = getMockUsers().find((u) => u.invitationPending)!;
await userEvent.click(screen.getByTestId(`user-actions-${pending.id}`));
await userEvent.click(await screen.findByTestId(`user-resend-invite-${pending.id}`));
await vi.waitFor(() => expect(called).toBe(true));
});
it('hands over the link when the resend fails', async () => {
mockAuthenticated();
mailOn();
const writeText = vi.fn().mockResolvedValue(undefined);
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
server.use(
http.post(`${USERS}/:id/resend-invite`, () =>
HttpResponse.json({ inviteLink: '/invite/complete?token=kept', mail: { sent: false, error: 'auth_failed' } }),
),
);
renderApp('/users');
await screen.findByTestId('users-table');
const pending = getMockUsers().find((u) => u.invitationPending)!;
await userEvent.click(screen.getByTestId(`user-actions-${pending.id}`));
await userEvent.click(await screen.findByTestId(`user-resend-invite-${pending.id}`));
await vi.waitFor(() => expect(writeText).toHaveBeenCalled());
expect(writeText.mock.calls[0][0]).toContain('/invite/complete?token=kept');
});
it('an expired invitation can be resent too (it gets a new link on the server)', async () => {
mockAuthenticated();
mailOn();
server.use(
http.get(USERS, () =>
HttpResponse.json([
{
id: '55555555-5555-5555-5555-555555555555', email: 'late@example.com', name: 'late@example.com', role: 'User',
isActive: true, createdAt: '2026-01-01T00:00:00.000Z', invitationPending: true, invitationExpired: true, inviteLink: null,
},
]),
),
);
renderApp('/users');
const row = await screen.findByTestId('user-row-55555555-5555-5555-5555-555555555555');
expect(within(row).getByText('Invitation expired')).toBeInTheDocument();
await userEvent.click(screen.getByTestId('user-actions-55555555-5555-5555-5555-555555555555'));
expect(await screen.findByTestId('user-resend-invite-55555555-5555-5555-5555-555555555555')).toBeInTheDocument();
});
});
describe('language preference in the profile', () => {
it('pre-fills the saved language and sends the choice, an empty value clears it', async () => {
server.use(
http.post(`${API_BASE}/api/v1/auth/refresh`, () =>
HttpResponse.json(makeAuthResponse({ user: { ...mockUser, language: 'en' } })),
),
);
let body: Record<string, unknown> | undefined;
server.use(
http.put(`${USERS}/me`, async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ ...mockUser, createdAt: '2026-01-01T00:00:00.000Z', invitationPending: false, inviteLink: null });
}),
);
renderApp('/profile');
const select = (await screen.findByTestId('profile-language-select', {}, { timeout: 10000 })) as HTMLSelectElement;
expect(select.value).toBe('en');
await userEvent.selectOptions(select, '');
await userEvent.click(screen.getByTestId('profile-save-button'));
await vi.waitFor(() => expect(body).toMatchObject({ language: '' }));
});
});
describe('language at sign-in', () => {
function wrapper({ children }: { children: ReactNode }) {
return (
<I18nextProvider i18n={i18n}>
<AuthProvider>{children}</AuthProvider>
</I18nextProvider>
);
}
it('applies the language saved on the account when signing in', async () => {
await i18n.changeLanguage('nl');
server.use(
http.post(`${API_BASE}/api/v1/auth/refresh`, () => HttpResponse.json({ status: 401 }, { status: 401 })),
http.post(`${API_BASE}/api/v1/auth/login`, () =>
HttpResponse.json(makeAuthResponse({ user: { ...mockUser, language: 'en' } })),
),
);
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.status).toBe('guest'));
await act(async () => {
await result.current.login('owner@example.com', 'Password123!');
});
await waitFor(() => expect(i18n.language).toBe('en'));
await i18n.changeLanguage('en');
});
it('leaves the language alone for an account without a preference', async () => {
await i18n.changeLanguage('nl');
server.use(
http.post(`${API_BASE}/api/v1/auth/refresh`, () => HttpResponse.json({ status: 401 }, { status: 401 })),
http.post(`${API_BASE}/api/v1/auth/login`, () => HttpResponse.json(makeAuthResponse({ user: { ...mockUser, language: null } }))),
);
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.status).toBe('guest'));
await act(async () => {
await result.current.login('owner@example.com', 'Password123!');
});
expect(i18n.language).toBe('nl');
await i18n.changeLanguage('en');
});
});
@@ -91,6 +91,10 @@ export const userHandlers = [
HttpResponse.json({ inviteLink: `/invite/complete?token=regenerated-mock-token` }),
),
http.post(`${API_BASE}/api/v1/Users/:invitationId/resend-invite`, () =>
HttpResponse.json({ inviteLink: `/invite/complete?token=resent-mock-token`, mail: null }),
),
http.put(`${API_BASE}/api/v1/Users/:userId/role`, () => new HttpResponse(null, { status: 200 })),
http.put(`${API_BASE}/api/v1/Users/:userId/active`, () => new HttpResponse(null, { status: 200 })),
@@ -2,7 +2,7 @@ import { useState } from 'react';
import { buildAppUrl } from '@/lib/links';
import { toast } from 'sonner';
import { useTranslation } from 'react-i18next';
import { MoreHorizontal, Link as LinkIcon, Trash2, UserX, UserCheck, RefreshCw } from 'lucide-react';
import { MoreHorizontal, Link as LinkIcon, Trash2, UserX, UserCheck, RefreshCw, Mail } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
Dialog,
@@ -35,9 +35,11 @@ import {
import { InviteUserDialog } from '@/features/invitation/components/InviteUserDialog';
import { DeleteUserDialog } from '@/features/users/components/DeleteUserDialog';
import { RoleBadge } from '@/components/shared/RoleBadge';
import { useUsers, useChangeRole, useSetUserActive, useDeleteUser, useRegenerateInvite } from '@/features/users/services/useUsers';
import { useUsers, useChangeRole, useSetUserActive, useDeleteUser, useRegenerateInvite, useResendInvite } from '@/features/users/services/useUsers';
import { useAuth } from '@/features/auth/context/auth-context';
import { Trans } from 'react-i18next';
import { mailErrorText } from '@/features/users/mailErrors';
import { useSystemCapabilities } from '@/features/system/services/useSystemCapabilities';
import { ProblemDetailsError } from '@/lib/api-client';
import type { UserRole } from '@/features/auth/services/types';
import type { UserListItem } from '@/features/users/services/types';
@@ -77,6 +79,9 @@ export function UsersPage() {
const setUserActive = useSetUserActive();
const deleteUser = useDeleteUser();
const regenerateInvite = useRegenerateInvite();
const resendInvite = useResendInvite();
const { data: capabilities } = useSystemCapabilities();
const emailEnabled = capabilities?.emailEnabled ?? false;
const availableRolesFor = (user: UserListItem): UserRole[] => {
const isSelf = user.id === currentUser?.id;
@@ -116,9 +121,26 @@ export function UsersPage() {
const handleRegenerateInvite = async (user: UserListItem) => {
try {
const { inviteLink } = await regenerateInvite.mutateAsync(user.id);
const { inviteLink, mail } = await regenerateInvite.mutateAsync(user.id);
await navigator.clipboard.writeText(buildAppUrl(inviteLink));
toast.success(t('users.actions.inviteRegenerated'));
if (mail?.sent) toast.success(t('users.actions.inviteRegeneratedMailed', { email: user.email }));
else if (mail) toast.warning(t('users.invite.mailFailed', { reason: mailErrorText(t, mail.error) }));
else toast.success(t('users.actions.inviteRegenerated'));
} catch {
toast.error(t('errors.generic'));
}
};
const handleResendInvite = async (user: UserListItem) => {
try {
const { inviteLink, mail } = await resendInvite.mutateAsync(user.id);
if (mail?.sent) {
toast.success(t('users.invite.mailSent', { email: user.email }));
} else {
// The mail did not go out (or the site has none): hand over the link instead.
await navigator.clipboard.writeText(buildAppUrl(inviteLink));
toast.warning(t('users.invite.mailFailed', { reason: mailErrorText(t, mail?.error) }));
}
} catch {
toast.error(t('errors.generic'));
}
@@ -301,6 +323,19 @@ export function UsersPage() {
</>
)}
{regenerable && emailEnabled && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => handleResendInvite(user)}
data-testid={`user-resend-invite-${user.id}`}
>
<Mail className="mr-2 h-4 w-4" />
{t('users.actions.resendInvite')}
</DropdownMenuItem>
</>
)}
{regenerable && (
<>
<DropdownMenuSeparator />
@@ -6,15 +6,25 @@ export interface UserListItem extends User {
inviteLink: string | null;
/** Pending invitation whose link has expired: still listed so it can be removed. */
invitationExpired?: boolean;
language?: 'nl' | 'en' | null;
}
export interface InviteUserPayload {
email: string;
role: Exclude<UserRole, 'Owner'>;
/** Language of the invitation mail and of the new account; omitted = the site default. */
language?: 'nl' | 'en';
}
/** Outcome of sending the mail; absent/null on a site without mail. The link is always returned too. */
export interface MailResult {
sent: boolean;
error: string | null;
}
export interface InviteUserResponse {
inviteLink: string;
mail?: MailResult | null;
}
export interface ChangeRolePayload {
@@ -56,3 +56,12 @@ export function useRegenerateInvite() {
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['users'] }),
});
}
export function useResendInvite() {
const queryClient = useQueryClient();
return useMutation<InviteUserResponse, Error, string>({
mutationFn: (invitationId) =>
api.post<InviteUserResponse>(`/api/v1/Users/${invitationId}/resend-invite`, {}),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['users'] }),
});
}