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:
@@ -5,7 +5,7 @@
|
||||
- **Feature Slug**: identity-email-notifications
|
||||
- **Project Type**: Brownfield
|
||||
- **Start Date**: 2026-11-08
|
||||
- **Current Stage**: CONSTRUCTION - U1 mail-foundation code generated and tested (local commits, not pushed); requirements and design approved by Bryan (relayed), D1 and D2 decided
|
||||
- **Current Stage**: CONSTRUCTION - U1 and U2 code generated and tested; requirements and design approved by Bryan (relayed), D1 and D2 decided
|
||||
- **Branch**: feature/identity-email-notifications (branched from feature/andreaslop-site-hosting at e9feb37; own branch, not merged anywhere)
|
||||
- **Request Type**: Feature (Bryan chose real e-mail over a workaround button; relayed by session "CMS & API")
|
||||
|
||||
@@ -48,5 +48,5 @@
|
||||
|
||||
### CONSTRUCTION
|
||||
- [x] U1 mail-foundation - Infrastructure Design (construction/mail-foundation/infrastructure-design/infrastructure-design.md), Code Generation done, build and tests green (see code-summary.md); hand-back pending
|
||||
- [ ] U2 identity-mail-flows
|
||||
- [ ] U3 password-reset (includes D2: security stamp in the access token)
|
||||
- [x] U2 identity-mail-flows - Code Generation done, build and tests green (see construction/identity-mail-flows/code/code-summary.md); includes D1 and D2; hand-back pending
|
||||
- [ ] U3 password-reset (D2, the security stamp in the access token, was built in U2)
|
||||
|
||||
@@ -69,3 +69,15 @@
|
||||
**Context**: Construction U1, per-unit build and test done; completion message to follow via the peer session.
|
||||
|
||||
---
|
||||
|
||||
## Construction U2 - code generation
|
||||
|
||||
**Timestamp**: 2026-11-08T22:00:00Z
|
||||
|
||||
**User Input**: "(Relayed by 'CMS & API') Start nu U2 identity-mail-flows (Bryan heeft ontwerp, D1 en D2 goedgekeurd): taal per gebruiker (kolom + profielkeuze), uitnodigingsmail met door beheerder gekozen taal, nieuwe link, opnieuw versturen (respons-resultaat, knop bij openstaande uitnodigingen), meldingen bij deactiveren/heractiveren/rolwijziging, plus de D2 security-stamp-controle. ... Bryan zegt in zijn chat: 'Er mag door jullie gecommit en gepusht worden.' ... Dat geldt NIET voor mergen naar master, deploy naar productie of rollen van mail-secrets; ASF test deploy blijft toegestaan zoals eerder."
|
||||
|
||||
**AI Response**: "Built U2 (migration AddLanguagePreference, IdentityMailService, invite/regenerate/resend with mail result, notices on deactivation/reactivation/role change, language preference in the profile and at sign-in, D2 stamp claim and check). Tests: Core 478 (incl. MariaDB-backed migration up/down/up on a real container), Identity 115, frontend 345. Pushing the branch and dispatching deploy_asf_test (mail stays off until the host gets its mail settings)."
|
||||
|
||||
**Context**: Construction U2 complete; completion message via the peer session.
|
||||
|
||||
---
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
# Code summary - U2 identity-mail-flows
|
||||
|
||||
## What was built
|
||||
**Data (migration `AddLanguagePreference`, additive, reversible)**: `Users.PreferredLanguage` (nullable, nl/en), `Invitations.Language` (nullable).
|
||||
|
||||
**Core**
|
||||
- `IIdentityMailService` / `IdentityMailService`: one orchestration point for invitation, new-link, deactivation, reactivation and role-change mails. Builds the link as `App:PublicBaseUrl + /admin + path`, resolves the language (user preference, else the invitation's, else `App:DefaultLanguage`, else nl), takes the sender and name from the site settings, logo and colour from config, renders, sends, logs only kind and recipient domain, and never throws (a failure is a `MailSendResult`). Returns `disabled` when the site has no SMTP host.
|
||||
- `InvitationService`: language stored normalised on the invitation and copied to the new account's `PreferredLanguage` on completion.
|
||||
- **D2**: the security stamp is a claim of the access token (`AuthService`) and is compared in `ActiveUserTokenValidation`. A password change or reset changes the stamp, so every access token issued before it is refused; a token without the claim (issued before this release) is refused once; the refresh token silently issues a new one that carries the claim.
|
||||
- `UserResponse`/`UserDto` carry `Language`.
|
||||
|
||||
**Identity module (`UsersController`)**
|
||||
- `POST Users/invite` accepts `language`, sends the mail, returns `{ inviteLink, mail }` (the invitation exists whatever happens to the mail). `POST Users/{id}/regenerate-invite` now also mails the new link. New `POST Users/{id}/resend-invite`: resends the current link, or creates a new one first when expired. `mail` is `{ sent, error }`, or null on a site without mail. Same role-hierarchy rules as the other invitation actions.
|
||||
- Deactivate, reactivate and role change send a notice only on a real change (and not for invitations); a failure never fails the action.
|
||||
- `PUT Users/me` accepts `language` (null = unchanged, "" = clear, nl/en, anything else 400).
|
||||
|
||||
**Frontend**: language select in the profile (applied immediately; clearing falls back to the site default), the saved language is applied at sign-in and on the first silent refresh after a page load (not on later refreshes, so a temporary top-bar switch survives); invite dialog gets a language select (default = site language) and shows "mail sent to X" or a failure with a short reason next to the copyable link; users list gets "Uitnodiging opnieuw mailen" and the regenerate action reports the mail result; everything mail-related is hidden when the site has no mail (`emailEnabled` false).
|
||||
|
||||
## Tests
|
||||
- Core.Tests 478: `IdentityMailServiceTests` (link, sender, logo, lifetime, language chain, disabled, failure value, exceptions never escape, notices, role names, `BuildLink`), invitation language (normalised, unsupported ignored, copied to the account), D2 (`DeactivatedUserAccessTests`: stamp change ends tokens for GET and POST, missing and wrong stamp refused; `SessionEndsOnPasswordChangeTests`: real Identity password change with real tokens, the old access token is refused, the refresh token gives a working new one, login response carries the language). MariaDB-backed migration test now covers both new migrations up, down, up (verified on a real MariaDB container).
|
||||
- Identity.Tests 115: `UsersControllerMailTests` (invite with language and result, failure still succeeds, no mail result without mail, unsupported language, regenerate/resend including expired and failed, hierarchy, notices only on real change, notice failure never fails the action, role change of an invitation sends nothing, profile language set/clear/unchanged/invalid, list shows languages).
|
||||
- Frontend 345: invite dialog (no language field without mail, default site language, chosen language sent, sent/failed/no mail line), resend (hidden without mail, success, failure hands over the link, expired), profile language, language applied at sign-in or left alone. ESLint and tsc clean; asf build ok.
|
||||
|
||||
## Behaviour change for SlpSoftware (and every host)
|
||||
1. After deploy, access tokens issued before it lack the stamp and are refused once; the silent refresh issues a new one (users stay signed in). 2. A password change now ends earlier access tokens immediately (refresh tokens are not revoked by a plain password change; only the reset flow in U3 revokes them). 3. Two nullable columns are added by migration. 4. Mail only when `Email:Smtp:Host` is set; otherwise nothing changes (the new `language` field of the invite request is ignored when mail is off in the UI).
|
||||
@@ -1,8 +1,14 @@
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import type { AuthResponse } from '@/features/auth/services/types';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { changeLanguage } from '@/i18n/config';
|
||||
import { AuthContext, type AuthContextValue, type AuthStatus } from '@/features/auth/context/auth-context';
|
||||
|
||||
/** The user's own language choice wins over the browser default; no preference leaves things alone. */
|
||||
function applyPreferredLanguage(language: 'nl' | 'en' | null | undefined) {
|
||||
if (language === 'nl' || language === 'en') void changeLanguage(language);
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the in-memory authentication session. On mount it attempts a silent
|
||||
* refresh using the httpOnly cookie (BR-U1-01) and wires the ApiClient's
|
||||
@@ -14,7 +20,15 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [expiresAt, setExpiresAt] = useState<string | null>(null);
|
||||
const [status, setStatus] = useState<AuthStatus>('loading');
|
||||
|
||||
// The user's saved language is applied once per sign-in (the first session after the page loads and
|
||||
// after each login), not on every later token refresh, so a temporary switch in the top bar survives.
|
||||
const applyLanguageNext = useRef(true);
|
||||
|
||||
const applySession = useCallback((data: AuthResponse) => {
|
||||
if (applyLanguageNext.current) {
|
||||
applyLanguageNext.current = false;
|
||||
applyPreferredLanguage(data.user.language);
|
||||
}
|
||||
setUser(data.user);
|
||||
setAccessToken(data.accessToken);
|
||||
setExpiresAt(data.expiresAt);
|
||||
@@ -50,6 +64,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
{ email, password },
|
||||
{ skipAuthRefresh: true },
|
||||
);
|
||||
applyLanguageNext.current = true;
|
||||
applySession(data);
|
||||
},
|
||||
[applySession],
|
||||
|
||||
@@ -7,6 +7,8 @@ export interface User {
|
||||
name: string;
|
||||
role: UserRole;
|
||||
isActive: boolean;
|
||||
/** Preferred language (also for e-mails); absent or null = the site default. */
|
||||
language?: 'nl' | 'en' | null;
|
||||
}
|
||||
|
||||
export interface AuthResponse {
|
||||
|
||||
@@ -23,6 +23,9 @@ import {
|
||||
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
|
||||
import { FieldError } from '@/components/ui/FieldError';
|
||||
import { useInviteUser } from '@/features/users/services/useUsers';
|
||||
import { useSystemCapabilities } from '@/features/system/services/useSystemCapabilities';
|
||||
import type { MailResult } from '@/features/users/services/types';
|
||||
import { mailErrorText } from '@/features/users/mailErrors';
|
||||
import { inviteUserSchema, type InviteUserFormData } from '@/features/users/schemas/users';
|
||||
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
|
||||
|
||||
@@ -36,6 +39,13 @@ export function InviteUserDialog({ open, onOpenChange }: InviteUserDialogProps)
|
||||
const [step, setStep] = useState<1 | 2>(1);
|
||||
const [inviteLink, setInviteLink] = useState<string | null>(null);
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
const [mailResult, setMailResult] = useState<MailResult | null>(null);
|
||||
const [invitedEmail, setInvitedEmail] = useState('');
|
||||
const { data: capabilities } = useSystemCapabilities();
|
||||
const emailEnabled = capabilities?.emailEnabled ?? false;
|
||||
const [language, setLanguage] = useState<'nl' | 'en' | null>(null);
|
||||
// Default = the site's language until the administrator picks another.
|
||||
const chosenLanguage = language ?? capabilities?.defaultLanguage ?? 'nl';
|
||||
const inviteUser = useInviteUser({
|
||||
onError: (err) => {
|
||||
if (err instanceof NetworkError) {
|
||||
@@ -63,6 +73,8 @@ export function InviteUserDialog({ open, onOpenChange }: InviteUserDialogProps)
|
||||
if (!nextOpen) {
|
||||
setStep(1);
|
||||
setInviteLink(null);
|
||||
setMailResult(null);
|
||||
setLanguage(null);
|
||||
setServerError(null);
|
||||
inviteUser.reset();
|
||||
reset();
|
||||
@@ -73,8 +85,10 @@ export function InviteUserDialog({ open, onOpenChange }: InviteUserDialogProps)
|
||||
const onSubmit = handleSubmit(async (values) => {
|
||||
setServerError(null);
|
||||
try {
|
||||
const response = await inviteUser.mutateAsync(values);
|
||||
const response = await inviteUser.mutateAsync(emailEnabled ? { ...values, language: chosenLanguage } : values);
|
||||
setInviteLink(response.inviteLink);
|
||||
setMailResult(response.mail ?? null);
|
||||
setInvitedEmail(values.email);
|
||||
setStep(2);
|
||||
} catch {
|
||||
// error shown via serverError state
|
||||
@@ -146,6 +160,23 @@ export function InviteUserDialog({ open, onOpenChange }: InviteUserDialogProps)
|
||||
)}
|
||||
</div>
|
||||
|
||||
{emailEnabled && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="invite-language">{t('users.invite.languageLabel')}</Label>
|
||||
<select
|
||||
id="invite-language"
|
||||
data-testid="invite-dialog-language"
|
||||
value={chosenLanguage}
|
||||
onChange={(e) => setLanguage(e.target.value as 'nl' | 'en')}
|
||||
className="h-10 w-full rounded-md border border-input bg-background px-3 text-sm"
|
||||
>
|
||||
<option value="nl">Nederlands</option>
|
||||
<option value="en">English</option>
|
||||
</select>
|
||||
<p className="text-xs text-muted-foreground">{t('users.invite.languageHelp')}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
@@ -161,6 +192,20 @@ export function InviteUserDialog({ open, onOpenChange }: InviteUserDialogProps)
|
||||
|
||||
{step === 2 && (
|
||||
<div className="space-y-4">
|
||||
{mailResult !== null && (
|
||||
<p
|
||||
className={`rounded-md border px-3 py-2 text-sm ${
|
||||
mailResult.sent
|
||||
? 'border-green-500/40 bg-green-50 text-green-900 dark:bg-green-950 dark:text-green-200'
|
||||
: 'border-amber-400/50 bg-amber-50 text-amber-900 dark:bg-amber-950 dark:text-amber-200'
|
||||
}`}
|
||||
data-testid="invite-dialog-mail-result"
|
||||
>
|
||||
{mailResult.sent
|
||||
? t('users.invite.mailSent', { email: invitedEmail })
|
||||
: t('users.invite.mailFailed', { reason: mailErrorText(t, mailResult.error) })}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('users.invite.step2Description')}
|
||||
</p>
|
||||
|
||||
@@ -19,10 +19,13 @@ import {
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { ProblemDetailsError } from '@/lib/api-client';
|
||||
import { changeLanguage } from '@/i18n/config';
|
||||
import { useSystemCapabilities } from '@/features/system/services/useSystemCapabilities';
|
||||
|
||||
const profileSchema = z.object({
|
||||
name: z.string().min(1, 'Name is required'),
|
||||
email: z.string().email('Enter a valid email address'),
|
||||
language: z.enum(['', 'nl', 'en']),
|
||||
});
|
||||
|
||||
const changePasswordSchema = z
|
||||
@@ -176,6 +179,7 @@ export function ProfilePage() {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useAuth();
|
||||
const updateProfile = useUpdateProfile();
|
||||
const { data: capabilities } = useSystemCapabilities();
|
||||
const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);
|
||||
|
||||
const {
|
||||
@@ -187,12 +191,16 @@ export function ProfilePage() {
|
||||
defaultValues: {
|
||||
name: user?.name ?? '',
|
||||
email: user?.email ?? '',
|
||||
language: user?.language ?? '',
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (data: ProfileFormData) => {
|
||||
try {
|
||||
await updateProfile.mutateAsync(data);
|
||||
// Show the choice right away; clearing it falls back to the site's default language.
|
||||
if (data.language === 'nl' || data.language === 'en') await changeLanguage(data.language);
|
||||
else await changeLanguage(capabilities?.defaultLanguage ?? 'nl');
|
||||
toast.success(t('profile.saveSuccess'));
|
||||
} catch (err) {
|
||||
if (err instanceof ProblemDetailsError && err.status === 400) {
|
||||
@@ -243,6 +251,20 @@ export function ProfilePage() {
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="language">{t('profile.language')}</Label>
|
||||
<select
|
||||
id="language"
|
||||
data-testid="profile-language-select"
|
||||
className="h-10 w-full rounded-md border border-input bg-background px-3 text-sm"
|
||||
{...register('language')}
|
||||
>
|
||||
<option value="">{t('profile.languageDefault')}</option>
|
||||
<option value="nl">Nederlands</option>
|
||||
<option value="en">English</option>
|
||||
</select>
|
||||
<p className="text-xs text-muted-foreground">{t('profile.languageHelp')}</p>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label>{t('profile.role')}</Label>
|
||||
<div>
|
||||
|
||||
@@ -6,6 +6,8 @@ import type { UserListItem } from '@/features/users/services/types';
|
||||
export interface UpdateProfilePayload {
|
||||
name: string;
|
||||
email: string;
|
||||
/** 'nl' | 'en'; '' clears the preference (site default); omitted leaves it unchanged. */
|
||||
language?: string;
|
||||
}
|
||||
|
||||
export interface ChangePasswordPayload {
|
||||
|
||||
@@ -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'] }),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -103,6 +103,8 @@
|
||||
"actions": {
|
||||
"copyInviteLink": "Copy invite link",
|
||||
"regenerateInvite": "Create new invite link",
|
||||
"resendInvite": "Resend invitation by e-mail",
|
||||
"inviteRegeneratedMailed": "New invite link created and e-mailed to {{email}}. The old link no longer works.",
|
||||
"inviteRegenerated": "New invite link copied to clipboard. The old link no longer works.",
|
||||
"changeRole": "Change role",
|
||||
"deactivate": "Deactivate",
|
||||
@@ -129,6 +131,17 @@
|
||||
"rolePlaceholder": "Select a role",
|
||||
"submitButton": "Send invitation",
|
||||
"step2Title": "Invitation created",
|
||||
"languageLabel": "Invitation language",
|
||||
"languageHelp": "The language of the e-mail and the preferred language of the new account.",
|
||||
"mailSent": "Invitation e-mail sent to {{email}}.",
|
||||
"mailFailed": "The e-mail could not be sent ({{reason}}). Copy the link and share it yourself, or try e-mailing again later.",
|
||||
"mailErrors": {
|
||||
"timeout": "the mail server did not respond in time",
|
||||
"auth_failed": "signing in to the mail server failed",
|
||||
"rejected": "the mail server or the address refused the message",
|
||||
"not_configured": "e-mail is not set up",
|
||||
"unknown": "unknown error"
|
||||
},
|
||||
"step2Description": "Share the link below with the invitee.",
|
||||
"linkLabel": "Invite link",
|
||||
"copyLink": "Copy link",
|
||||
@@ -163,6 +176,9 @@
|
||||
"saving": "Saving…",
|
||||
"saveSuccess": "Profile updated successfully",
|
||||
"securityTitle": "Change password",
|
||||
"language": "Language",
|
||||
"languageDefault": "Site default",
|
||||
"languageHelp": "The language of the admin and of e-mails you receive.",
|
||||
"changePassword": "Change password",
|
||||
"changePasswordDialog": {
|
||||
"title": "Change Password",
|
||||
|
||||
@@ -103,6 +103,8 @@
|
||||
"actions": {
|
||||
"copyInviteLink": "Uitnodigingslink kopiëren",
|
||||
"regenerateInvite": "Nieuwe uitnodigingslink maken",
|
||||
"resendInvite": "Uitnodiging opnieuw mailen",
|
||||
"inviteRegeneratedMailed": "Nieuwe uitnodigingslink gemaakt en gemaild naar {{email}}. De oude link werkt niet meer.",
|
||||
"inviteRegenerated": "Nieuwe uitnodigingslink gekopieerd naar klembord. De oude link werkt niet meer.",
|
||||
"changeRole": "Rol wijzigen",
|
||||
"deactivate": "Deactiveren",
|
||||
@@ -130,6 +132,17 @@
|
||||
"submitButton": "Uitnodiging versturen",
|
||||
"step2Title": "Uitnodiging aangemaakt",
|
||||
"step2Description": "Deel de onderstaande link met de genodigde.",
|
||||
"languageLabel": "Taal van de uitnodiging",
|
||||
"languageHelp": "De taal van de e-mail en de voorkeurstaal van het nieuwe account.",
|
||||
"mailSent": "E-mail met de uitnodiging verstuurd naar {{email}}.",
|
||||
"mailFailed": "De e-mail kon niet worden verstuurd ({{reason}}). Kopieer de link en deel die zelf, of probeer later opnieuw te mailen.",
|
||||
"mailErrors": {
|
||||
"timeout": "de mailserver reageerde niet op tijd",
|
||||
"auth_failed": "inloggen op de mailserver mislukt",
|
||||
"rejected": "de mailserver of het adres weigerde het bericht",
|
||||
"not_configured": "e-mail is niet ingesteld",
|
||||
"unknown": "onbekende fout"
|
||||
},
|
||||
"linkLabel": "Uitnodigingslink",
|
||||
"copyLink": "Link kopiëren",
|
||||
"close": "Sluiten"
|
||||
@@ -163,6 +176,9 @@
|
||||
"saving": "Opslaan…",
|
||||
"saveSuccess": "Profiel succesvol bijgewerkt",
|
||||
"securityTitle": "Wachtwoord wijzigen",
|
||||
"language": "Taal",
|
||||
"languageDefault": "Standaard van de site",
|
||||
"languageHelp": "De taal van de beheeromgeving en van e-mails die je ontvangt.",
|
||||
"changePassword": "Wachtwoord wijzigen",
|
||||
"changePasswordDialog": {
|
||||
"title": "Wachtwoord wijzigen",
|
||||
|
||||
Reference in New Issue
Block a user