From 8fc360a5961ad49270a28c10ed025676809fdb84 Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 01:09:40 +0200 Subject: [PATCH 01/31] fix(admin): guard GET /api/users/{id} with @RequirePermission(ADMIN_USER) Fixes IDOR: the endpoint was publicly accessible to any authenticated user. Now requires ADMIN_USER permission, matching all other user management endpoints. Co-Authored-By: Claude Sonnet 4.6 --- .../controller/UserController.java | 1 + .../controller/UserControllerTest.java | 25 +++ frontend/messages/de.json | 4 + frontend/messages/en.json | 4 + frontend/messages/es.json | 4 + frontend/src/routes/admin/+layout.svelte | 34 ++++ frontend/src/routes/admin/+page.svelte | 118 ++++++------- frontend/src/routes/admin/EntityNav.svelte | 114 +++++++++++++ frontend/src/routes/admin/UsersTab.svelte | 156 +++++++++--------- .../src/routes/admin/layout.svelte.spec.ts | 87 ++++++++++ frontend/src/routes/admin/page.svelte.spec.ts | 116 ++++++------- .../src/routes/admin/users/+layout.server.ts | 8 + .../src/routes/admin/users/+layout.svelte | 12 ++ frontend/src/routes/admin/users/+page.svelte | 7 + .../routes/admin/users/UsersListPanel.svelte | 105 ++++++++++++ .../src/routes/admin/users/[id]/+page.svelte | 147 ++++++++--------- .../admin/users/[id]/page.svelte.spec.ts | 4 +- .../routes/admin/users/layout.server.spec.ts | 41 +++++ .../routes/admin/users/layout.svelte.spec.ts | 95 +++++++++++ .../routes/admin/users/new/+page.server.ts | 2 +- .../src/routes/admin/users/new/+page.svelte | 95 +++++------ .../admin/users/new/page.svelte.spec.ts | 11 +- 22 files changed, 844 insertions(+), 346 deletions(-) create mode 100644 frontend/src/routes/admin/+layout.svelte create mode 100644 frontend/src/routes/admin/EntityNav.svelte create mode 100644 frontend/src/routes/admin/layout.svelte.spec.ts create mode 100644 frontend/src/routes/admin/users/+layout.server.ts create mode 100644 frontend/src/routes/admin/users/+layout.svelte create mode 100644 frontend/src/routes/admin/users/+page.svelte create mode 100644 frontend/src/routes/admin/users/UsersListPanel.svelte create mode 100644 frontend/src/routes/admin/users/layout.server.spec.ts create mode 100644 frontend/src/routes/admin/users/layout.svelte.spec.ts diff --git a/backend/src/main/java/org/raddatz/familienarchiv/controller/UserController.java b/backend/src/main/java/org/raddatz/familienarchiv/controller/UserController.java index 92b0b0f1..a7bdacd8 100644 --- a/backend/src/main/java/org/raddatz/familienarchiv/controller/UserController.java +++ b/backend/src/main/java/org/raddatz/familienarchiv/controller/UserController.java @@ -61,6 +61,7 @@ public class UserController { } @GetMapping("users/{id}") + @RequirePermission(Permission.ADMIN_USER) public ResponseEntity getUser(@PathVariable UUID id) { AppUser user = userService.getById(id); user.setPassword(null); diff --git a/backend/src/test/java/org/raddatz/familienarchiv/controller/UserControllerTest.java b/backend/src/test/java/org/raddatz/familienarchiv/controller/UserControllerTest.java index eb4cc3e7..fa26f411 100644 --- a/backend/src/test/java/org/raddatz/familienarchiv/controller/UserControllerTest.java +++ b/backend/src/test/java/org/raddatz/familienarchiv/controller/UserControllerTest.java @@ -50,4 +50,29 @@ class UserControllerTest { .andExpect(status().isOk()) .andExpect(jsonPath("$.username").value("anna")); } + + // ─── GET /api/users/{id} ────────────────────────────────────────────────── + + @Test + @WithMockUser(username = "reader") + void getUser_returns403_whenCallerLacksAdminUserPermission() throws Exception { + UUID id = UUID.randomUUID(); + AppUser target = AppUser.builder().id(id).username("target").build(); + when(userService.getById(id)).thenReturn(target); + + mockMvc.perform(get("/api/users/" + id)) + .andExpect(status().isForbidden()); + } + + @Test + @WithMockUser(username = "admin", authorities = {"ADMIN_USER"}) + void getUser_returns200_whenCallerHasAdminUserPermission() throws Exception { + UUID id = UUID.randomUUID(); + AppUser user = AppUser.builder().id(id).username("target").build(); + when(userService.getById(id)).thenReturn(user); + + mockMvc.perform(get("/api/users/" + id)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.username").value("target")); + } } diff --git a/frontend/messages/de.json b/frontend/messages/de.json index e8cf82d4..ccaecdb2 100644 --- a/frontend/messages/de.json +++ b/frontend/messages/de.json @@ -167,6 +167,10 @@ "admin_group_name_placeholder": "Gruppenname (z.B. Editoren)", "admin_user_delete_confirm": "Benutzer {username} wirklich löschen?", "admin_btn_new_user": "Neuer Benutzer", + "admin_users_list_title": "Alle Benutzer", + "admin_users_search_placeholder": "Benutzer suchen\u2026", + "admin_users_empty": "Keine Benutzer vorhanden.", + "admin_users_select_prompt": "W\u00e4hle einen Benutzer aus der Liste.", "admin_user_new_heading": "Neuen Benutzer anlegen", "admin_user_edit_heading": "Benutzer bearbeiten: {username}", "admin_user_created": "Benutzer wurde erstellt.", diff --git a/frontend/messages/en.json b/frontend/messages/en.json index 527a4f48..c95a0303 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -167,6 +167,10 @@ "admin_group_name_placeholder": "Group name (e.g. Editors)", "admin_user_delete_confirm": "Really delete user {username}?", "admin_btn_new_user": "New User", + "admin_users_list_title": "All Users", + "admin_users_search_placeholder": "Search users\u2026", + "admin_users_empty": "No users found.", + "admin_users_select_prompt": "Select a user from the list.", "admin_user_new_heading": "Create new user", "admin_user_edit_heading": "Edit user: {username}", "admin_user_created": "User has been created.", diff --git a/frontend/messages/es.json b/frontend/messages/es.json index 3d72309e..48bebf1b 100644 --- a/frontend/messages/es.json +++ b/frontend/messages/es.json @@ -167,6 +167,10 @@ "admin_group_name_placeholder": "Nombre del grupo (p.ej. Editores)", "admin_user_delete_confirm": "¿Realmente eliminar al usuario {username}?", "admin_btn_new_user": "Nuevo usuario", + "admin_users_list_title": "Todos los usuarios", + "admin_users_search_placeholder": "Buscar usuarios\u2026", + "admin_users_empty": "No hay usuarios.", + "admin_users_select_prompt": "Selecciona un usuario de la lista.", "admin_user_new_heading": "Crear nuevo usuario", "admin_user_edit_heading": "Editar usuario: {username}", "admin_user_created": "Usuario creado.", diff --git a/frontend/src/routes/admin/+layout.svelte b/frontend/src/routes/admin/+layout.svelte new file mode 100644 index 00000000..13f98a76 --- /dev/null +++ b/frontend/src/routes/admin/+layout.svelte @@ -0,0 +1,34 @@ + + + + Admin · Familienarchiv + + + +
+ + + + +
+ {@render children()} +
+
diff --git a/frontend/src/routes/admin/+page.svelte b/frontend/src/routes/admin/+page.svelte index 92e0a5f8..b9da7c26 100644 --- a/frontend/src/routes/admin/+page.svelte +++ b/frontend/src/routes/admin/+page.svelte @@ -1,78 +1,68 @@ {m.page_title_admin()} -
-
-

{m.admin_heading()}

- - -
- - - - -
+ +
+
+

{m.admin_heading()}

- {#if form?.message} -
- {form.message} -
- {/if} +
diff --git a/frontend/src/routes/admin/EntityNav.svelte b/frontend/src/routes/admin/EntityNav.svelte new file mode 100644 index 00000000..36334284 --- /dev/null +++ b/frontend/src/routes/admin/EntityNav.svelte @@ -0,0 +1,114 @@ + + + diff --git a/frontend/src/routes/admin/UsersTab.svelte b/frontend/src/routes/admin/UsersTab.svelte index f6a72c32..32e4d5c6 100644 --- a/frontend/src/routes/admin/UsersTab.svelte +++ b/frontend/src/routes/admin/UsersTab.svelte @@ -29,64 +29,65 @@ let {
- - - - - - - - - - - {#each users as user (user.id)} - - - - + + {/each} + +
{m.admin_col_login()}{m.admin_col_full_name()}{m.admin_col_groups()}{m.admin_col_actions()}
- {user.username} - - {#if user.firstName || user.lastName} - {user.firstName ?? ''} {user.lastName ?? ''} - {:else} - - {/if} - -
- {#if user.groups && user.groups.length > 0} - {#each user.groups as group (group.id)} - - {group.name} - - {/each} +
+ + + + + + + + + + + {#each users as user (user.id)} + + + - + + - - {/each} - -
{m.admin_col_login()}{m.admin_col_full_name()}{m.admin_col_groups()}{m.admin_col_actions()}
+ {user.username} + + {#if user.firstName || user.lastName} + {user.firstName ?? ''} {user.lastName ?? ''} {:else} - {m.admin_no_groups()} + {/if} - - - +
+ {#if user.groups && user.groups.length > 0} + {#each user.groups as group (group.id)} + + {group.name} + + {/each} + {:else} + {m.admin_no_groups()} + {/if} +
+
+
+ + {m.btn_edit()} + -
{ + { if (!confirm(m.admin_user_delete_confirm({ username: user.username }))) { cancel(); } @@ -94,27 +95,28 @@ let { await update(); }; }} - class="flex items-center" - > - - -
-
-
+ + + +
+
+
diff --git a/frontend/src/routes/admin/layout.svelte.spec.ts b/frontend/src/routes/admin/layout.svelte.spec.ts new file mode 100644 index 00000000..7d26c7f1 --- /dev/null +++ b/frontend/src/routes/admin/layout.svelte.spec.ts @@ -0,0 +1,87 @@ +/** + * Layout shell tests — we test EntityNav.svelte directly since the layout + * itself is a thin shell that just composes EntityNav and renders children. + */ +import { afterEach, describe, it, expect, vi } from 'vitest'; +import { cleanup, render } from 'vitest-browser-svelte'; +import { page } from 'vitest/browser'; +import EntityNav from './EntityNav.svelte'; + +vi.mock('$app/state', () => ({ + page: { url: { pathname: '/admin/users' } } +})); + +afterEach(cleanup); + +const fullPerms = { + userCount: 4, + groupCount: 3, + tagCount: 7, + canManageUsers: true, + canManageTags: true, + canManageGroups: true, + canRunMaintenance: true +}; + +describe('admin EntityNav — links', () => { + it('renders users nav link pointing to /admin/users', async () => { + render(EntityNav, fullPerms); + await expect + .element(page.getByRole('link', { name: /benutzer/i })) + .toHaveAttribute('href', '/admin/users'); + }); + + it('renders groups nav link pointing to /admin/groups', async () => { + render(EntityNav, fullPerms); + await expect + .element(page.getByRole('link', { name: /gruppen/i })) + .toHaveAttribute('href', '/admin/groups'); + }); + + it('renders tags nav link pointing to /admin/tags', async () => { + render(EntityNav, fullPerms); + await expect + .element(page.getByRole('link', { name: /schlagworte/i })) + .toHaveAttribute('href', '/admin/tags'); + }); + + it('renders system nav link pointing to /admin/system', async () => { + render(EntityNav, fullPerms); + await expect + .element(page.getByRole('link', { name: /system/i })) + .toHaveAttribute('href', '/admin/system'); + }); +}); + +describe('admin EntityNav — permission-based rendering', () => { + it('hides users link when canManageUsers is false', async () => { + render(EntityNav, { ...fullPerms, canManageUsers: false }); + await expect.element(page.getByRole('link', { name: /benutzer/i })).not.toBeInTheDocument(); + }); + + it('hides tags link when canManageTags is false', async () => { + render(EntityNav, { ...fullPerms, canManageTags: false }); + await expect.element(page.getByRole('link', { name: /schlagworte/i })).not.toBeInTheDocument(); + }); + + it('hides system link when canRunMaintenance is false', async () => { + render(EntityNav, { ...fullPerms, canRunMaintenance: false }); + await expect.element(page.getByRole('link', { name: /system/i })).not.toBeInTheDocument(); + }); +}); + +describe('admin EntityNav — active state', () => { + it('marks users link as aria-current=page when on /admin/users', async () => { + render(EntityNav, fullPerms); + await expect + .element(page.getByRole('link', { name: /benutzer/i })) + .toHaveAttribute('aria-current', 'page'); + }); + + it('does not mark groups link as current when on /admin/users', async () => { + render(EntityNav, fullPerms); + await expect + .element(page.getByRole('link', { name: /gruppen/i })) + .not.toHaveAttribute('aria-current'); + }); +}); diff --git a/frontend/src/routes/admin/page.svelte.spec.ts b/frontend/src/routes/admin/page.svelte.spec.ts index fcbfd824..9072e164 100644 --- a/frontend/src/routes/admin/page.svelte.spec.ts +++ b/frontend/src/routes/admin/page.svelte.spec.ts @@ -1,83 +1,73 @@ +/** + * Tests for the admin root page — the mobile entity picker. + * On md+ viewports the page immediately redirects to /admin/users (tested + * in e2e). Here we verify the mobile-only list of entity links. + */ import { afterEach, describe, expect, it, vi } from 'vitest'; import { cleanup, render } from 'vitest-browser-svelte'; import { page } from 'vitest/browser'; import Page from './+page.svelte'; -vi.mock('$app/forms', () => ({ enhance: () => () => {} })); +vi.mock('$app/navigation', () => ({ goto: vi.fn() })); -const makeGroup = (overrides = {}) => ({ - id: 'g1', - name: 'Editoren', - permissions: ['WRITE_ALL'], - ...overrides -}); - -const makeUser = (overrides = {}) => ({ - id: 'u1', - username: 'max', - firstName: 'Max', - lastName: 'Mustermann', - email: 'max@example.com', - birthDate: undefined, - contact: undefined, - enabled: true, - groups: [makeGroup()], - createdAt: '2024-01-01T00:00:00Z', - ...overrides -}); - -const baseData = { - user: undefined, - canWrite: true, - canAnnotate: false, - users: [makeUser()], - groups: [makeGroup()], - tags: [] +const fullData = { + userCount: 4, + groupCount: 3, + tagCount: 7, + canManageUsers: true, + canManageTags: true, + canManageGroups: true, + canRunMaintenance: true }; afterEach(cleanup); -// ─── Users tab ──────────────────────────────────────────────────────────────── - -describe('Admin page – users tab', () => { - it('shows the username in the table', async () => { - render(Page, { data: baseData, form: null }); - await expect.element(page.getByRole('cell', { name: 'max', exact: true })).toBeInTheDocument(); +describe('Admin root page – entity picker', () => { + it('renders the admin heading', async () => { + render(Page, { data: fullData }); + await expect.element(page.getByRole('heading')).toBeInTheDocument(); }); - it('shows the full name in the table', async () => { - render(Page, { data: baseData, form: null }); - await expect.element(page.getByText(/Max Mustermann/)).toBeInTheDocument(); - }); - - it('shows a dash when user has no name set', async () => { - const data = { ...baseData, users: [makeUser({ firstName: undefined, lastName: undefined })] }; - render(Page, { data, form: null }); - await expect.element(page.getByText('–')).toBeInTheDocument(); - }); - - it('shows group badges for the user', async () => { - render(Page, { data: baseData, form: null }); - await expect.element(page.getByText('Editoren')).toBeInTheDocument(); - }); - - it('edit link points to /admin/users/[id]', async () => { - render(Page, { data: baseData, form: null }); + it('renders users link pointing to /admin/users', async () => { + render(Page, { data: fullData }); await expect - .element(page.getByRole('link', { name: /Bearbeiten/i })) - .toHaveAttribute('href', '/admin/users/u1'); + .element(page.getByRole('link', { name: /benutzer/i })) + .toHaveAttribute('href', '/admin/users'); }); - it('new user button links to /admin/users/new', async () => { - render(Page, { data: baseData, form: null }); + it('renders groups link pointing to /admin/groups', async () => { + render(Page, { data: fullData }); await expect - .element(page.getByRole('link', { name: /Neuer Benutzer/i })) - .toHaveAttribute('href', '/admin/users/new'); + .element(page.getByRole('link', { name: /gruppen/i })) + .toHaveAttribute('href', '/admin/groups'); }); - it('shows "no groups" label when user has no groups', async () => { - const data = { ...baseData, users: [makeUser({ groups: [] })] }; - render(Page, { data, form: null }); - await expect.element(page.getByText(/Keine Gruppen/i)).toBeInTheDocument(); + it('renders tags link pointing to /admin/tags', async () => { + render(Page, { data: fullData }); + await expect + .element(page.getByRole('link', { name: /schlagworte/i })) + .toHaveAttribute('href', '/admin/tags'); + }); + + it('renders system link pointing to /admin/system', async () => { + render(Page, { data: fullData }); + await expect + .element(page.getByRole('link', { name: /system/i })) + .toHaveAttribute('href', '/admin/system'); + }); + + it('hides users link when canManageUsers is false', async () => { + render(Page, { data: { ...fullData, canManageUsers: false } }); + await expect.element(page.getByRole('link', { name: /benutzer/i })).not.toBeInTheDocument(); + }); + + it('hides system link when canRunMaintenance is false', async () => { + render(Page, { data: { ...fullData, canRunMaintenance: false } }); + await expect.element(page.getByRole('link', { name: /system/i })).not.toBeInTheDocument(); + }); + + it('shows user count', async () => { + render(Page, { data: fullData }); + await expect.element(page.getByText('4')).toBeInTheDocument(); }); }); diff --git a/frontend/src/routes/admin/users/+layout.server.ts b/frontend/src/routes/admin/users/+layout.server.ts new file mode 100644 index 00000000..97be1fe5 --- /dev/null +++ b/frontend/src/routes/admin/users/+layout.server.ts @@ -0,0 +1,8 @@ +import { createApiClient } from '$lib/api.server'; +import type { LayoutServerLoad } from './$types'; + +export const load: LayoutServerLoad = async ({ fetch }) => { + const api = createApiClient(fetch); + const result = await api.GET('/api/users'); + return { users: result.data ?? [] }; +}; diff --git a/frontend/src/routes/admin/users/+layout.svelte b/frontend/src/routes/admin/users/+layout.svelte new file mode 100644 index 00000000..ade6a954 --- /dev/null +++ b/frontend/src/routes/admin/users/+layout.svelte @@ -0,0 +1,12 @@ + + + + + +
+ {@render children()} +
diff --git a/frontend/src/routes/admin/users/+page.svelte b/frontend/src/routes/admin/users/+page.svelte new file mode 100644 index 00000000..6759323e --- /dev/null +++ b/frontend/src/routes/admin/users/+page.svelte @@ -0,0 +1,7 @@ + + +
+

{m.admin_users_select_prompt()}

+
diff --git a/frontend/src/routes/admin/users/UsersListPanel.svelte b/frontend/src/routes/admin/users/UsersListPanel.svelte new file mode 100644 index 00000000..51758b2f --- /dev/null +++ b/frontend/src/routes/admin/users/UsersListPanel.svelte @@ -0,0 +1,105 @@ + + +
+ +
+ + {m.admin_users_list_title()} + + + + {m.admin_btn_new_user()} + +
+ + +
+ +
+ + +
+ {#if filtered.length === 0} +

+ {m.admin_users_empty()} +

+ {:else} + {#each filtered as user (user.id)} + {@const isActive = page.url.pathname.startsWith('/admin/users/' + user.id)} + {@const fullName = + [user.firstName, user.lastName].filter(Boolean).join(' ') || null} + +
{user.username}
+ {#if fullName} +
{fullName}
+ {/if} + {#if user.groups.length > 0} +
+ {#each user.groups as group (group.id)} + + {group.name} + + {/each} +
+ {/if} +
+ {/each} + {/if} +
+
diff --git a/frontend/src/routes/admin/users/[id]/+page.svelte b/frontend/src/routes/admin/users/[id]/+page.svelte index 2ebe7691..e2201990 100644 --- a/frontend/src/routes/admin/users/[id]/+page.svelte +++ b/frontend/src/routes/admin/users/[id]/+page.svelte @@ -10,85 +10,74 @@ let { data, form } = $props(); const selectedGroupIds = $derived(data.editUser.groups?.map((g: { id: string }) => g.id) ?? []); -
- - + +
+

+ {m.admin_user_edit_heading({ username: data.editUser.username })} +

+
+ + +
+ {#if form?.success} +
+ {m.admin_user_updated()} +
+ {/if} + {#if form?.error} +
+ {form.error} +
+ {/if} + +
+ +
+

+ {m.profile_section_personal()} +

+ +
+ + +
+

+ {m.admin_col_groups()} +

+ +
+ + +
+

+ {m.admin_label_new_password_optional()} +

+ +
+
+
+ + +
+ - - - {m.btn_back_to_overview()} - - -

- {m.admin_user_edit_heading({ username: data.editUser.username })} -

- - {#if form?.success} -
- {m.admin_user_updated()} -
- {/if} - {#if form?.error} -
- {form.error} -
- {/if} - -
- -
-

- {m.profile_section_personal()} -

- -
- - -
-

- {m.admin_col_groups()} -

- -
- - -
-

- {m.admin_label_new_password_optional()} -

- -
- - -
+ -
-
+ {m.btn_save()} + +
diff --git a/frontend/src/routes/admin/users/[id]/page.svelte.spec.ts b/frontend/src/routes/admin/users/[id]/page.svelte.spec.ts index acc3d6fd..43fca9b1 100644 --- a/frontend/src/routes/admin/users/[id]/page.svelte.spec.ts +++ b/frontend/src/routes/admin/users/[id]/page.svelte.spec.ts @@ -110,11 +110,11 @@ describe('Admin edit user page – rendering', () => { }); }); - it('cancel link points to /admin', async () => { + it('cancel link points to /admin/users', async () => { render(Page, { data: baseData, form: null }); await expect .element(page.getByRole('link', { name: /Abbrechen/i })) - .toHaveAttribute('href', '/admin'); + .toHaveAttribute('href', '/admin/users'); }); it('renders the save button', async () => { diff --git a/frontend/src/routes/admin/users/layout.server.spec.ts b/frontend/src/routes/admin/users/layout.server.spec.ts new file mode 100644 index 00000000..32433eb4 --- /dev/null +++ b/frontend/src/routes/admin/users/layout.server.spec.ts @@ -0,0 +1,41 @@ +import { describe, expect, it, vi, beforeEach } from 'vitest'; +import { load } from './+layout.server'; + +vi.mock('$lib/api.server', () => ({ createApiClient: vi.fn() })); + +import { createApiClient } from '$lib/api.server'; + +function mockApi(users: unknown[]) { + vi.mocked(createApiClient).mockReturnValue({ + GET: vi.fn().mockResolvedValueOnce({ response: { ok: true }, data: users }) + } as ReturnType); +} + +beforeEach(() => vi.clearAllMocks()); + +describe('admin/users layout load', () => { + it('returns the users list', async () => { + mockApi([ + { id: 'u1', username: 'alice' }, + { id: 'u2', username: 'bob' } + ]); + const result = await load({ fetch: vi.fn() as unknown as typeof fetch }); + expect(result.users).toHaveLength(2); + expect(result.users[0].username).toBe('alice'); + }); + + it('returns an empty array when the API returns nothing', async () => { + mockApi([]); + const result = await load({ fetch: vi.fn() as unknown as typeof fetch }); + expect(result.users).toEqual([]); + }); + + it('calls GET /api/users', async () => { + const mockGet = vi.fn().mockResolvedValue({ response: { ok: true }, data: [] }); + vi.mocked(createApiClient).mockReturnValue({ GET: mockGet } as ReturnType< + typeof createApiClient + >); + await load({ fetch: vi.fn() as unknown as typeof fetch }); + expect(mockGet).toHaveBeenCalledWith('/api/users'); + }); +}); diff --git a/frontend/src/routes/admin/users/layout.svelte.spec.ts b/frontend/src/routes/admin/users/layout.svelte.spec.ts new file mode 100644 index 00000000..4d736f2c --- /dev/null +++ b/frontend/src/routes/admin/users/layout.svelte.spec.ts @@ -0,0 +1,95 @@ +import { afterEach, describe, it, expect, vi } from 'vitest'; +import { cleanup, render } from 'vitest-browser-svelte'; +import { page } from 'vitest/browser'; +import UsersListPanel from './UsersListPanel.svelte'; + +vi.mock('$app/state', () => ({ + page: { url: { pathname: '/admin/users/u1' } } +})); + +afterEach(cleanup); + +const users = [ + { + id: 'u1', + username: 'reader', + firstName: 'Lea', + lastName: 'Leserin', + groups: [{ id: 'g1', name: 'Leser', permissions: ['READ_ALL'] }] + }, + { + id: 'u2', + username: 'admin', + firstName: null, + lastName: null, + groups: [{ id: 'g2', name: 'Admins', permissions: ['ADMIN'] }] + } +]; + +describe('UsersListPanel — header', () => { + it('renders the panel title', async () => { + render(UsersListPanel, { users }); + await expect.element(page.getByText(/Alle Benutzer/i)).toBeInTheDocument(); + }); + + it('renders a new-user link pointing to /admin/users/new', async () => { + render(UsersListPanel, { users }); + await expect + .element(page.getByRole('link', { name: /neuer benutzer/i })) + .toHaveAttribute('href', '/admin/users/new'); + }); + + it('renders a search input', async () => { + render(UsersListPanel, { users }); + await expect.element(page.getByRole('searchbox')).toBeInTheDocument(); + }); +}); + +describe('UsersListPanel — user items', () => { + it('renders each username', async () => { + render(UsersListPanel, { users }); + await expect.element(page.getByRole('link', { name: /reader/i })).toBeInTheDocument(); + await expect.element(page.getByRole('link', { name: /admin/i })).toBeInTheDocument(); + }); + + it('each user links to /admin/users/[id]', async () => { + const { container } = render(UsersListPanel, { users }); + const links = container.querySelectorAll('a[href^="/admin/users/u"]'); + expect(links.length).toBe(2); + expect(links[0].getAttribute('href')).toBe('/admin/users/u1'); + expect(links[1].getAttribute('href')).toBe('/admin/users/u2'); + }); + + it('shows full name as subtitle when available', async () => { + render(UsersListPanel, { users }); + await expect.element(page.getByText('Lea Leserin')).toBeInTheDocument(); + }); + + it('shows group name chip', async () => { + render(UsersListPanel, { users }); + await expect.element(page.getByText('Leser', { exact: true })).toBeInTheDocument(); + }); +}); + +describe('UsersListPanel — active state', () => { + it('marks the active user link with aria-current=page', async () => { + render(UsersListPanel, { users }); + await expect + .element(page.getByRole('link', { name: /reader/i })) + .toHaveAttribute('aria-current', 'page'); + }); + + it('does not mark the inactive user link with aria-current', async () => { + render(UsersListPanel, { users }); + await expect + .element(page.getByRole('link', { name: /admin/i })) + .not.toHaveAttribute('aria-current'); + }); +}); + +describe('UsersListPanel — empty state', () => { + it('shows empty state message when users array is empty', async () => { + render(UsersListPanel, { users: [] }); + await expect.element(page.getByText(/keine benutzer/i)).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/routes/admin/users/new/+page.server.ts b/frontend/src/routes/admin/users/new/+page.server.ts index 256e4f89..17af6aee 100644 --- a/frontend/src/routes/admin/users/new/+page.server.ts +++ b/frontend/src/routes/admin/users/new/+page.server.ts @@ -40,6 +40,6 @@ export const actions: Actions = { return fail(result.response.status, { error: getErrorMessage(code) }); } - throw redirect(303, '/admin'); + throw redirect(303, '/admin/users'); } }; diff --git a/frontend/src/routes/admin/users/new/+page.svelte b/frontend/src/routes/admin/users/new/+page.svelte index 4af6d8ba..cfb63278 100644 --- a/frontend/src/routes/admin/users/new/+page.svelte +++ b/frontend/src/routes/admin/users/new/+page.svelte @@ -8,64 +8,57 @@ import AccountSection from './AccountSection.svelte'; let { data, form } = $props(); -
- - - - - {m.btn_back_to_overview()} - +
+ +
+

{m.admin_user_new_heading()}

+
-

{m.admin_user_new_heading()}

+ +
+ {#if form?.error} +
+ {form.error} +
+ {/if} - {#if form?.error} -
- {form.error} -
- {/if} - -
-
- + +
+ +
-

- {m.profile_section_personal()} -

- +
+

+ {m.profile_section_personal()} +

+ +
-

- {m.admin_col_groups()} -

- - - -
- - {m.btn_cancel()} - - +
+

+ {m.admin_col_groups()} +

+
+ + +
+ + {m.btn_cancel()} + + +
diff --git a/frontend/src/routes/admin/users/new/page.svelte.spec.ts b/frontend/src/routes/admin/users/new/page.svelte.spec.ts index d80f5c6f..6ac42717 100644 --- a/frontend/src/routes/admin/users/new/page.svelte.spec.ts +++ b/frontend/src/routes/admin/users/new/page.svelte.spec.ts @@ -33,18 +33,11 @@ describe('Admin new user page – rendering', () => { await expect.element(page.getByText('Admins')).toBeInTheDocument(); }); - it('cancel link points to /admin', async () => { + it('cancel link points to /admin/users', async () => { render(Page, { data: baseData, form: null }); await expect .element(page.getByRole('link', { name: /Abbrechen/i })) - .toHaveAttribute('href', '/admin'); - }); - - it('back link points to /admin', async () => { - render(Page, { data: baseData, form: null }); - await expect - .element(page.getByRole('link', { name: /Zurück/i })) - .toHaveAttribute('href', '/admin'); + .toHaveAttribute('href', '/admin/users'); }); it('renders the create button', async () => { -- 2.49.1 From c8a834b91b164281eb127a94e1bb9c5fab927221 Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 01:10:51 +0200 Subject: [PATCH 02/31] feat(admin): add layout server auth guard and Phase 1 hotfixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - +layout.server.ts: auth guard (throws 403 for non-admin) with granular permission flags and entity counts for EntityNav - GroupsTab: add ⚙ prefix to ADMIN badge (WCAG 1.4.1, non-color indicator) - TagsTab: remove opacity-0 from action buttons (hidden on touch devices) - +layout.svelte: remove unused isSystem derived Co-Authored-By: Claude Sonnet 4.6 --- frontend/src/routes/admin/+layout.server.ts | 40 +++++++++++ frontend/src/routes/admin/+layout.svelte | 3 - frontend/src/routes/admin/GroupsTab.svelte | 2 +- .../src/routes/admin/GroupsTab.svelte.spec.ts | 27 +++++++ frontend/src/routes/admin/TagsTab.svelte | 2 +- .../src/routes/admin/TagsTab.svelte.spec.ts | 23 ++++++ .../src/routes/admin/layout.server.spec.ts | 72 +++++++++++++++++++ 7 files changed, 164 insertions(+), 5 deletions(-) create mode 100644 frontend/src/routes/admin/+layout.server.ts create mode 100644 frontend/src/routes/admin/GroupsTab.svelte.spec.ts create mode 100644 frontend/src/routes/admin/TagsTab.svelte.spec.ts create mode 100644 frontend/src/routes/admin/layout.server.spec.ts diff --git a/frontend/src/routes/admin/+layout.server.ts b/frontend/src/routes/admin/+layout.server.ts new file mode 100644 index 00000000..19405345 --- /dev/null +++ b/frontend/src/routes/admin/+layout.server.ts @@ -0,0 +1,40 @@ +import { error } from '@sveltejs/kit'; +import { createApiClient } from '$lib/api.server'; +import { getErrorMessage } from '$lib/errors'; + +type UserGroup = { permissions: string[] }; + +function hasPerm(user: { groups?: UserGroup[] } | undefined, perm: string): boolean { + return user?.groups?.some((g) => g.permissions.includes(perm)) ?? false; +} + +function hasAnyAdminPerm(user: { groups?: UserGroup[] } | undefined): boolean { + return ( + hasPerm(user, 'ADMIN') || + hasPerm(user, 'ADMIN_USER') || + hasPerm(user, 'ADMIN_TAG') || + hasPerm(user, 'ADMIN_PERMISSION') + ); +} + +export async function load({ fetch, locals }) { + const user = locals.user; + if (!hasAnyAdminPerm(user)) throw error(403, getErrorMessage('FORBIDDEN')); + + const api = createApiClient(fetch); + const [usersResult, groupsResult, tagsResult] = await Promise.all([ + api.GET('/api/users'), + api.GET('/api/groups'), + api.GET('/api/tags') + ]); + + return { + userCount: (usersResult.data ?? []).length, + groupCount: (groupsResult.data ?? []).length, + tagCount: (tagsResult.data ?? []).length, + canManageUsers: hasPerm(user, 'ADMIN_USER'), + canManageTags: hasPerm(user, 'ADMIN_TAG'), + canManageGroups: hasPerm(user, 'ADMIN_PERMISSION'), + canRunMaintenance: hasPerm(user, 'ADMIN') + }; +} diff --git a/frontend/src/routes/admin/+layout.svelte b/frontend/src/routes/admin/+layout.svelte index 13f98a76..6c9558dd 100644 --- a/frontend/src/routes/admin/+layout.svelte +++ b/frontend/src/routes/admin/+layout.svelte @@ -1,10 +1,7 @@ diff --git a/frontend/src/routes/admin/GroupsTab.svelte b/frontend/src/routes/admin/GroupsTab.svelte index 6eb22e53..0f5da793 100644 --- a/frontend/src/routes/admin/GroupsTab.svelte +++ b/frontend/src/routes/admin/GroupsTab.svelte @@ -126,7 +126,7 @@ function cancelEditGroup() { ? 'border-red-100 bg-red-50 text-red-700' : 'border-line bg-muted text-ink-2'}" > - {perm} + {perm === 'ADMIN' ? '⚙ ' : ''}{perm} {/each}
diff --git a/frontend/src/routes/admin/GroupsTab.svelte.spec.ts b/frontend/src/routes/admin/GroupsTab.svelte.spec.ts new file mode 100644 index 00000000..ad9cc66e --- /dev/null +++ b/frontend/src/routes/admin/GroupsTab.svelte.spec.ts @@ -0,0 +1,27 @@ +import { afterEach, describe, it, expect, vi } from 'vitest'; +import { cleanup, render } from 'vitest-browser-svelte'; +import GroupsTab from './GroupsTab.svelte'; + +vi.mock('$app/forms', () => ({ enhance: () => () => {} })); + +afterEach(cleanup); + +const makeGroups = () => [ + { id: 'g1', name: 'Administrators', permissions: ['ADMIN', 'WRITE_ALL'] }, + { id: 'g2', name: 'Editors', permissions: ['WRITE_ALL'] } +]; + +describe('GroupsTab — ADMIN permission badge (WCAG 1.4.1)', () => { + it('ADMIN badge has a non-color indicator so it is distinguishable without color', () => { + // The ADMIN badge must not rely on color alone (WCAG 1.4.1). + // It must contain a visible non-color indicator: a text prefix such as ⚙. + const { container } = render(GroupsTab, { groups: makeGroups() }); + + const adminBadge = Array.from(container.querySelectorAll('span')).find((el) => + el.textContent?.includes('ADMIN') + ); + expect(adminBadge).toBeDefined(); + // Badge text must include a non-color prefix character + expect(adminBadge!.textContent).toMatch(/[⚙★⚠!]/); + }); +}); diff --git a/frontend/src/routes/admin/TagsTab.svelte b/frontend/src/routes/admin/TagsTab.svelte index 01a1fec0..1b41558f 100644 --- a/frontend/src/routes/admin/TagsTab.svelte +++ b/frontend/src/routes/admin/TagsTab.svelte @@ -76,7 +76,7 @@ function cancelEditTag() { {tag.name} -
+
+ +
+ + +
+ {#if form?.success} +
+ {m.admin_group_updated()} +
+ {/if} + {#if form?.error} +
+ {form.error} +
+ {/if} + +
+ +
+

+ {m.admin_col_name()} +

+ +
+ + +
+

+ {m.admin_groups_section_standard()} +

+
+ {#each STANDARD_PERMISSIONS as perm (perm.value)} + + {/each} +
+
+ + +
+

+ {m.admin_groups_section_administrative()} +

+
+ {#each ADMIN_PERMISSIONS as perm (perm.value)} + + {/each} +
+
+
+
+ + +
+ + {m.btn_cancel()} + + +
+
diff --git a/frontend/src/routes/admin/groups/layout.server.spec.ts b/frontend/src/routes/admin/groups/layout.server.spec.ts new file mode 100644 index 00000000..a3fdc6e9 --- /dev/null +++ b/frontend/src/routes/admin/groups/layout.server.spec.ts @@ -0,0 +1,41 @@ +import { describe, expect, it, vi, beforeEach } from 'vitest'; +import { load } from './+layout.server'; + +vi.mock('$lib/api.server', () => ({ createApiClient: vi.fn() })); + +import { createApiClient } from '$lib/api.server'; + +function mockApi(groups: unknown[]) { + vi.mocked(createApiClient).mockReturnValue({ + GET: vi.fn().mockResolvedValueOnce({ response: { ok: true }, data: groups }) + } as ReturnType); +} + +beforeEach(() => vi.clearAllMocks()); + +describe('admin/groups layout load', () => { + it('returns the groups list', async () => { + mockApi([ + { id: 'g1', name: 'Admins', permissions: ['ADMIN'] }, + { id: 'g2', name: 'Editors', permissions: ['WRITE_ALL'] } + ]); + const result = await load({ fetch: vi.fn() as unknown as typeof fetch }); + expect(result.groups).toHaveLength(2); + expect(result.groups[0].name).toBe('Admins'); + }); + + it('returns an empty array when the API returns nothing', async () => { + mockApi([]); + const result = await load({ fetch: vi.fn() as unknown as typeof fetch }); + expect(result.groups).toEqual([]); + }); + + it('calls GET /api/groups', async () => { + const mockGet = vi.fn().mockResolvedValue({ response: { ok: true }, data: [] }); + vi.mocked(createApiClient).mockReturnValue({ GET: mockGet } as ReturnType< + typeof createApiClient + >); + await load({ fetch: vi.fn() as unknown as typeof fetch }); + expect(mockGet).toHaveBeenCalledWith('/api/groups'); + }); +}); diff --git a/frontend/src/routes/admin/groups/layout.svelte.spec.ts b/frontend/src/routes/admin/groups/layout.svelte.spec.ts new file mode 100644 index 00000000..4496e243 --- /dev/null +++ b/frontend/src/routes/admin/groups/layout.svelte.spec.ts @@ -0,0 +1,79 @@ +import { afterEach, describe, it, expect, vi } from 'vitest'; +import { cleanup, render } from 'vitest-browser-svelte'; +import { page } from 'vitest/browser'; +import GroupsListPanel from './GroupsListPanel.svelte'; + +vi.mock('$app/state', () => ({ + page: { url: { pathname: '/admin/groups/g1' } } +})); + +afterEach(cleanup); + +const groups = [ + { id: 'g1', name: 'Administrators', permissions: ['ADMIN', 'WRITE_ALL'] }, + { id: 'g2', name: 'Editors', permissions: ['WRITE_ALL'] }, + { id: 'g3', name: 'Readers', permissions: [] } +]; + +describe('GroupsListPanel — header', () => { + it('renders the panel title', async () => { + render(GroupsListPanel, { groups }); + await expect.element(page.getByText(/Alle Gruppen/i)).toBeInTheDocument(); + }); + + it('renders a new-group link pointing to /admin/groups/new', async () => { + render(GroupsListPanel, { groups }); + await expect + .element(page.getByRole('link', { name: /neue gruppe/i })) + .toHaveAttribute('href', '/admin/groups/new'); + }); +}); + +describe('GroupsListPanel — group items', () => { + it('renders each group name', async () => { + render(GroupsListPanel, { groups }); + await expect.element(page.getByRole('link', { name: /administrators/i })).toBeInTheDocument(); + await expect.element(page.getByRole('link', { name: /editors/i })).toBeInTheDocument(); + }); + + it('each group links to /admin/groups/[id]', async () => { + const { container } = render(GroupsListPanel, { groups }); + const links = container.querySelectorAll('a[href^="/admin/groups/g"]'); + expect(links.length).toBe(3); + expect(links[0].getAttribute('href')).toBe('/admin/groups/g1'); + }); + + it('shows permission count as subtitle', async () => { + render(GroupsListPanel, { groups }); + // Administrators has 2 permissions + await expect.element(page.getByText(/2 Berechtigungen/i)).toBeInTheDocument(); + }); + + it('shows "no permissions" for a group with zero permissions', async () => { + render(GroupsListPanel, { groups }); + await expect.element(page.getByText(/0 Berechtigungen/i)).toBeInTheDocument(); + }); +}); + +describe('GroupsListPanel — active state', () => { + it('marks the active group link with aria-current=page', async () => { + render(GroupsListPanel, { groups }); + await expect + .element(page.getByRole('link', { name: /administrators/i })) + .toHaveAttribute('aria-current', 'page'); + }); + + it('does not mark inactive group links with aria-current', async () => { + render(GroupsListPanel, { groups }); + await expect + .element(page.getByRole('link', { name: /editors/i })) + .not.toHaveAttribute('aria-current'); + }); +}); + +describe('GroupsListPanel — empty state', () => { + it('shows empty state when groups array is empty', async () => { + render(GroupsListPanel, { groups: [] }); + await expect.element(page.getByText(/keine gruppen/i)).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/routes/admin/groups/new/+page.server.ts b/frontend/src/routes/admin/groups/new/+page.server.ts new file mode 100644 index 00000000..1e6d7086 --- /dev/null +++ b/frontend/src/routes/admin/groups/new/+page.server.ts @@ -0,0 +1,25 @@ +import { fail, redirect } from '@sveltejs/kit'; +import type { Actions } from './$types'; +import { createApiClient } from '$lib/api.server'; +import { getErrorMessage } from '$lib/errors'; + +export const actions: Actions = { + default: async ({ request, fetch }) => { + const data = await request.formData(); + const api = createApiClient(fetch); + + const result = await api.POST('/api/groups', { + body: { + name: data.get('name') as string, + permissions: data.getAll('permissions') as string[] + } + }); + + if (!result.response.ok) { + const code = (result.error as unknown as { code?: string })?.code; + return fail(result.response.status, { error: getErrorMessage(code) }); + } + + throw redirect(303, '/admin/groups'); + } +}; diff --git a/frontend/src/routes/admin/groups/new/+page.svelte b/frontend/src/routes/admin/groups/new/+page.svelte new file mode 100644 index 00000000..bdeb445f --- /dev/null +++ b/frontend/src/routes/admin/groups/new/+page.svelte @@ -0,0 +1,117 @@ + + +
+ +
+

+ {m.admin_group_new_heading()} +

+
+ + +
+ {#if form?.error} +
+ {form.error} +
+ {/if} + +
+ +
+

+ {m.admin_col_name()} +

+ +
+ + +
+

+ {m.admin_groups_section_standard()} +

+
+ {#each availableStandard as perm (perm.value)} + + {/each} +
+
+ + +
+

+ {m.admin_groups_section_administrative()} +

+
+ {#each availableAdmin as perm (perm.value)} + + {/each} +
+
+
+
+ + +
+ + {m.btn_cancel()} + + +
+
-- 2.49.1 From 908173de972c4836b4945c4c0b9fedcf818d3770 Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 01:33:33 +0200 Subject: [PATCH 04/31] feat(admin/tags): add tags entity with master-detail sub-routes and type-to-confirm delete Creates the full tags section under /admin/tags/: - +layout.server.ts: loads tags list via GET /api/tags - TagsListPanel.svelte: left list panel (name, active state) - +layout.svelte: composes list panel + children slot - +page.svelte: empty selection prompt - [id]/+page.server.ts: rename (PUT) and delete actions - [id]/+page.svelte: rename form + danger zone with type-to-confirm delete Co-Authored-By: Claude Sonnet 4.6 --- frontend/messages/de.json | 5 + frontend/messages/en.json | 5 + frontend/messages/es.json | 5 + .../src/routes/admin/tags/+layout.server.ts | 8 ++ frontend/src/routes/admin/tags/+layout.svelte | 12 +++ frontend/src/routes/admin/tags/+page.svelte | 7 ++ .../routes/admin/tags/TagsListPanel.svelte | 42 ++++++++ .../routes/admin/tags/[id]/+page.server.ts | 44 +++++++++ .../src/routes/admin/tags/[id]/+page.svelte | 96 +++++++++++++++++++ .../routes/admin/tags/layout.server.spec.ts | 41 ++++++++ .../routes/admin/tags/layout.svelte.spec.ts | 61 ++++++++++++ 11 files changed, 326 insertions(+) create mode 100644 frontend/src/routes/admin/tags/+layout.server.ts create mode 100644 frontend/src/routes/admin/tags/+layout.svelte create mode 100644 frontend/src/routes/admin/tags/+page.svelte create mode 100644 frontend/src/routes/admin/tags/TagsListPanel.svelte create mode 100644 frontend/src/routes/admin/tags/[id]/+page.server.ts create mode 100644 frontend/src/routes/admin/tags/[id]/+page.svelte create mode 100644 frontend/src/routes/admin/tags/layout.server.spec.ts create mode 100644 frontend/src/routes/admin/tags/layout.svelte.spec.ts diff --git a/frontend/messages/de.json b/frontend/messages/de.json index 04be49cb..cd4ad3de 100644 --- a/frontend/messages/de.json +++ b/frontend/messages/de.json @@ -155,6 +155,11 @@ "admin_multiselect_hint_full": "Strg+Klick für Mehrfachauswahl", "admin_section_tags": "Schlagworte", "admin_tags_warning": "Warnung: Umbenennen oder Löschen wirkt sich auf alle verknüpften Dokumente aus.", + "admin_tags_list_title": "Alle Schlagworte", + "admin_tags_empty": "Keine Schlagworte vorhanden.", + "admin_tags_select_prompt": "W\u00e4hle ein Schlagwort aus der Liste.", + "admin_tag_edit_heading": "Schlagwort: {name}", + "admin_tag_updated": "Schlagwort umbenannt.", "admin_btn_edit_tag_label": "Schlagwort bearbeiten", "admin_tag_delete_confirm": "Wirklich löschen? Das Schlagwort wird aus allen Dokumenten entfernt.", "admin_btn_delete_tag_label": "Schlagwort löschen", diff --git a/frontend/messages/en.json b/frontend/messages/en.json index 9346ec74..1484b937 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -155,6 +155,11 @@ "admin_multiselect_hint_full": "Ctrl+Click for multiple selection", "admin_section_tags": "Tags", "admin_tags_warning": "Warning: Renaming or deleting affects all linked documents.", + "admin_tags_list_title": "All Tags", + "admin_tags_empty": "No tags found.", + "admin_tags_select_prompt": "Select a tag from the list.", + "admin_tag_edit_heading": "Tag: {name}", + "admin_tag_updated": "Tag renamed.", "admin_btn_edit_tag_label": "Edit tag", "admin_tag_delete_confirm": "Really delete? The tag will be removed from all documents.", "admin_btn_delete_tag_label": "Delete tag", diff --git a/frontend/messages/es.json b/frontend/messages/es.json index d5850122..381ba174 100644 --- a/frontend/messages/es.json +++ b/frontend/messages/es.json @@ -155,6 +155,11 @@ "admin_multiselect_hint_full": "Ctrl+Clic para selección múltiple", "admin_section_tags": "Etiquetas", "admin_tags_warning": "Advertencia: Renombrar o eliminar afecta a todos los documentos vinculados.", + "admin_tags_list_title": "Todas las etiquetas", + "admin_tags_empty": "No hay etiquetas.", + "admin_tags_select_prompt": "Selecciona una etiqueta de la lista.", + "admin_tag_edit_heading": "Etiqueta: {name}", + "admin_tag_updated": "Etiqueta renombrada.", "admin_btn_edit_tag_label": "Editar etiqueta", "admin_tag_delete_confirm": "¿Realmente eliminar? La etiqueta se eliminará de todos los documentos.", "admin_btn_delete_tag_label": "Eliminar etiqueta", diff --git a/frontend/src/routes/admin/tags/+layout.server.ts b/frontend/src/routes/admin/tags/+layout.server.ts new file mode 100644 index 00000000..01255d35 --- /dev/null +++ b/frontend/src/routes/admin/tags/+layout.server.ts @@ -0,0 +1,8 @@ +import { createApiClient } from '$lib/api.server'; +import type { LayoutServerLoad } from './$types'; + +export const load: LayoutServerLoad = async ({ fetch }) => { + const api = createApiClient(fetch); + const result = await api.GET('/api/tags'); + return { tags: result.data ?? [] }; +}; diff --git a/frontend/src/routes/admin/tags/+layout.svelte b/frontend/src/routes/admin/tags/+layout.svelte new file mode 100644 index 00000000..405779b2 --- /dev/null +++ b/frontend/src/routes/admin/tags/+layout.svelte @@ -0,0 +1,12 @@ + + + + + +
+ {@render children()} +
diff --git a/frontend/src/routes/admin/tags/+page.svelte b/frontend/src/routes/admin/tags/+page.svelte new file mode 100644 index 00000000..5db9b65c --- /dev/null +++ b/frontend/src/routes/admin/tags/+page.svelte @@ -0,0 +1,7 @@ + + +
+

{m.admin_tags_select_prompt()}

+
diff --git a/frontend/src/routes/admin/tags/TagsListPanel.svelte b/frontend/src/routes/admin/tags/TagsListPanel.svelte new file mode 100644 index 00000000..4a910bb4 --- /dev/null +++ b/frontend/src/routes/admin/tags/TagsListPanel.svelte @@ -0,0 +1,42 @@ + + +
+ +
+ + {m.admin_tags_list_title()} + +
+ + +
+ {#if tags.length === 0} +

+ {m.admin_tags_empty()} +

+ {:else} + {#each tags as tag (tag.id)} + {@const isActive = page.url.pathname.startsWith('/admin/tags/' + tag.id)} + +
{tag.name}
+
+ {/each} + {/if} +
+
diff --git a/frontend/src/routes/admin/tags/[id]/+page.server.ts b/frontend/src/routes/admin/tags/[id]/+page.server.ts new file mode 100644 index 00000000..0dbace2c --- /dev/null +++ b/frontend/src/routes/admin/tags/[id]/+page.server.ts @@ -0,0 +1,44 @@ +import { error, fail, redirect } from '@sveltejs/kit'; +import type { PageServerLoad, Actions } from './$types'; +import { createApiClient } from '$lib/api.server'; +import { getErrorMessage } from '$lib/errors'; + +export const load: PageServerLoad = async ({ params, parent }) => { + const { tags } = await parent(); + const tag = tags.find((t: { id: string }) => t.id === params.id); + if (!tag) throw error(404, getErrorMessage('TAG_NOT_FOUND')); + return { tag }; +}; + +export const actions: Actions = { + update: async ({ params, request, fetch }) => { + const data = await request.formData(); + const api = createApiClient(fetch); + + const result = await api.PUT('/api/tags/{id}', { + params: { path: { id: params.id } }, + body: { name: data.get('name') as string } + }); + + if (!result.response.ok) { + const code = (result.error as unknown as { code?: string })?.code; + return fail(result.response.status, { error: getErrorMessage(code) }); + } + + return { success: true }; + }, + + delete: async ({ params, fetch }) => { + const api = createApiClient(fetch); + const result = await api.DELETE('/api/tags/{id}', { + params: { path: { id: params.id } } + }); + + if (!result.response.ok) { + const code = (result.error as unknown as { code?: string })?.code; + return fail(result.response.status, { error: getErrorMessage(code) }); + } + + throw redirect(303, '/admin/tags'); + } +}; diff --git a/frontend/src/routes/admin/tags/[id]/+page.svelte b/frontend/src/routes/admin/tags/[id]/+page.svelte new file mode 100644 index 00000000..078b2601 --- /dev/null +++ b/frontend/src/routes/admin/tags/[id]/+page.svelte @@ -0,0 +1,96 @@ + + +
+ +
+

+ {m.admin_tag_edit_heading({ name: data.tag.name })} +

+
+ + +
+ {#if form?.success} +
+ {m.admin_tag_updated()} +
+ {/if} + {#if form?.error} +
+ {form.error} +
+ {/if} + + +
+
+

+ {m.admin_col_name()} +

+

{m.admin_tags_warning()}

+ +
+
+ + +
+

+ {m.btn_delete()} +

+

+ {m.admin_tag_delete_confirm()} +

+

+ Gib {data.tag.name} zur Bestätigung ein: +

+ +
+ +
+
+
+ + +
+ + {m.btn_cancel()} + + +
+
diff --git a/frontend/src/routes/admin/tags/layout.server.spec.ts b/frontend/src/routes/admin/tags/layout.server.spec.ts new file mode 100644 index 00000000..466a970b --- /dev/null +++ b/frontend/src/routes/admin/tags/layout.server.spec.ts @@ -0,0 +1,41 @@ +import { describe, expect, it, vi, beforeEach } from 'vitest'; +import { load } from './+layout.server'; + +vi.mock('$lib/api.server', () => ({ createApiClient: vi.fn() })); + +import { createApiClient } from '$lib/api.server'; + +function mockApi(tags: unknown[]) { + vi.mocked(createApiClient).mockReturnValue({ + GET: vi.fn().mockResolvedValueOnce({ response: { ok: true }, data: tags }) + } as ReturnType); +} + +beforeEach(() => vi.clearAllMocks()); + +describe('admin/tags layout load', () => { + it('returns the tags list', async () => { + mockApi([ + { id: 't1', name: 'Familie' }, + { id: 't2', name: 'Urlaub' } + ]); + const result = await load({ fetch: vi.fn() as unknown as typeof fetch }); + expect(result.tags).toHaveLength(2); + expect(result.tags[0].name).toBe('Familie'); + }); + + it('returns an empty array when the API returns nothing', async () => { + mockApi([]); + const result = await load({ fetch: vi.fn() as unknown as typeof fetch }); + expect(result.tags).toEqual([]); + }); + + it('calls GET /api/tags', async () => { + const mockGet = vi.fn().mockResolvedValue({ response: { ok: true }, data: [] }); + vi.mocked(createApiClient).mockReturnValue({ GET: mockGet } as ReturnType< + typeof createApiClient + >); + await load({ fetch: vi.fn() as unknown as typeof fetch }); + expect(mockGet).toHaveBeenCalledWith('/api/tags'); + }); +}); diff --git a/frontend/src/routes/admin/tags/layout.svelte.spec.ts b/frontend/src/routes/admin/tags/layout.svelte.spec.ts new file mode 100644 index 00000000..2fbd3e5b --- /dev/null +++ b/frontend/src/routes/admin/tags/layout.svelte.spec.ts @@ -0,0 +1,61 @@ +import { afterEach, describe, it, expect, vi } from 'vitest'; +import { cleanup, render } from 'vitest-browser-svelte'; +import { page } from 'vitest/browser'; +import TagsListPanel from './TagsListPanel.svelte'; + +vi.mock('$app/state', () => ({ + page: { url: { pathname: '/admin/tags/t1' } } +})); + +afterEach(cleanup); + +const tags = [ + { id: 't1', name: 'Familie' }, + { id: 't2', name: 'Urlaub' }, + { id: 't3', name: 'Schule' } +]; + +describe('TagsListPanel — header', () => { + it('renders the panel title', async () => { + render(TagsListPanel, { tags }); + await expect.element(page.getByText(/Alle Schlagworte/i)).toBeInTheDocument(); + }); +}); + +describe('TagsListPanel — tag items', () => { + it('renders each tag name', async () => { + render(TagsListPanel, { tags }); + await expect.element(page.getByRole('link', { name: /familie/i })).toBeInTheDocument(); + await expect.element(page.getByRole('link', { name: /urlaub/i })).toBeInTheDocument(); + }); + + it('each tag links to /admin/tags/[id]', async () => { + const { container } = render(TagsListPanel, { tags }); + const links = container.querySelectorAll('a[href^="/admin/tags/t"]'); + expect(links.length).toBe(3); + expect(links[0].getAttribute('href')).toBe('/admin/tags/t1'); + }); +}); + +describe('TagsListPanel — active state', () => { + it('marks the active tag link with aria-current=page', async () => { + render(TagsListPanel, { tags }); + await expect + .element(page.getByRole('link', { name: /familie/i })) + .toHaveAttribute('aria-current', 'page'); + }); + + it('does not mark inactive tag links with aria-current', async () => { + render(TagsListPanel, { tags }); + await expect + .element(page.getByRole('link', { name: /urlaub/i })) + .not.toHaveAttribute('aria-current'); + }); +}); + +describe('TagsListPanel — empty state', () => { + it('shows empty state when tags array is empty', async () => { + render(TagsListPanel, { tags: [] }); + await expect.element(page.getByText(/keine schlagworte/i)).toBeInTheDocument(); + }); +}); -- 2.49.1 From cee16c1657228cd6ed26dce5ea88ef08cf4e0e61 Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 01:39:09 +0200 Subject: [PATCH 05/31] feat(admin/system): add system maintenance page under /admin/system Moves the system maintenance panel out of the old tab-based admin page and into a dedicated route. Renders maintenance cards with spinner state and success message on completion. Co-Authored-By: Claude Sonnet 4.6 --- frontend/src/routes/admin/system/+page.svelte | 78 +++++++++++++++++++ .../routes/admin/system/page.svelte.spec.ts | 34 ++++++++ 2 files changed, 112 insertions(+) create mode 100644 frontend/src/routes/admin/system/+page.svelte create mode 100644 frontend/src/routes/admin/system/page.svelte.spec.ts diff --git a/frontend/src/routes/admin/system/+page.svelte b/frontend/src/routes/admin/system/+page.svelte new file mode 100644 index 00000000..ddb575c6 --- /dev/null +++ b/frontend/src/routes/admin/system/+page.svelte @@ -0,0 +1,78 @@ + + +
+
+ +
+

{m.admin_system_backfill_heading()}

+

{m.admin_system_backfill_description()}

+ + {#if backfillResult !== null} +

+ {m.admin_system_backfill_success({ count: backfillResult })} +

+ {/if} +
+ + +
+

+ {m.admin_system_backfill_hashes_heading()} +

+

{m.admin_system_backfill_hashes_description()}

+ + {#if backfillHashesResult !== null} +

+ {m.admin_system_backfill_hashes_success({ count: backfillHashesResult })} +

+ {/if} +
+
+
diff --git a/frontend/src/routes/admin/system/page.svelte.spec.ts b/frontend/src/routes/admin/system/page.svelte.spec.ts new file mode 100644 index 00000000..4d8e0bb7 --- /dev/null +++ b/frontend/src/routes/admin/system/page.svelte.spec.ts @@ -0,0 +1,34 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { cleanup, render } from 'vitest-browser-svelte'; +import { page } from 'vitest/browser'; +import Page from './+page.svelte'; + +afterEach(cleanup); + +describe('Admin system page', () => { + it('renders the backfill versions heading', async () => { + render(Page, {}); + await expect.element(page.getByText(/Verlaufsdaten auffüllen/i)).toBeInTheDocument(); + }); + + it('renders the backfill versions button', async () => { + render(Page, {}); + await expect + .element(page.getByRole('button', { name: /jetzt auffüllen/i })) + .toBeInTheDocument(); + }); + + it('renders the backfill file hashes heading', async () => { + render(Page, {}); + await expect + .element(page.getByRole('heading', { name: /Datei-Hashes berechnen/i })) + .toBeInTheDocument(); + }); + + it('renders the file hashes button', async () => { + render(Page, {}); + await expect + .element(page.getByRole('button', { name: /Datei-Hashes berechnen/i })) + .toBeInTheDocument(); + }); +}); -- 2.49.1 From fabb517d0bb962d4fb0ca8dac05968710c44afbb Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 01:44:52 +0200 Subject: [PATCH 06/31] =?UTF-8?q?refactor(admin):=20phase=207=20=E2=80=94?= =?UTF-8?q?=20delete=20old=20tab=20components=20and=20page.server.ts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove UsersTab, GroupsTab, TagsTab, SystemTab and their specs; delete the monolithic +page.server.ts with shared load + 6 form actions (all now handled by dedicated sub-route servers under users/, groups/, tags/). Add delete action and confirmation button to user edit panel. Fix test to query the edit form by id rather than the first form in DOM. Co-Authored-By: Claude Sonnet 4.6 --- frontend/src/routes/admin/+page.server.ts | 116 --------- frontend/src/routes/admin/GroupsTab.svelte | 221 ------------------ .../src/routes/admin/GroupsTab.svelte.spec.ts | 27 --- frontend/src/routes/admin/SystemTab.svelte | 72 ------ frontend/src/routes/admin/TagsTab.svelte | 127 ---------- .../src/routes/admin/TagsTab.svelte.spec.ts | 23 -- frontend/src/routes/admin/UsersTab.svelte | 122 ---------- frontend/src/routes/admin/page.server.spec.ts | 77 ------ .../routes/admin/users/[id]/+page.server.ts | 16 +- .../src/routes/admin/users/[id]/+page.svelte | 19 ++ .../admin/users/[id]/page.svelte.spec.ts | 2 +- 11 files changed, 35 insertions(+), 787 deletions(-) delete mode 100644 frontend/src/routes/admin/+page.server.ts delete mode 100644 frontend/src/routes/admin/GroupsTab.svelte delete mode 100644 frontend/src/routes/admin/GroupsTab.svelte.spec.ts delete mode 100644 frontend/src/routes/admin/SystemTab.svelte delete mode 100644 frontend/src/routes/admin/TagsTab.svelte delete mode 100644 frontend/src/routes/admin/TagsTab.svelte.spec.ts delete mode 100644 frontend/src/routes/admin/UsersTab.svelte delete mode 100644 frontend/src/routes/admin/page.server.spec.ts diff --git a/frontend/src/routes/admin/+page.server.ts b/frontend/src/routes/admin/+page.server.ts deleted file mode 100644 index b58bf3c4..00000000 --- a/frontend/src/routes/admin/+page.server.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { error, fail } from '@sveltejs/kit'; -import { createApiClient } from '$lib/api.server'; -import { getErrorMessage } from '$lib/errors'; - -type ApiResult = { response: Response; error?: unknown }; - -function toActionResult(result: ApiResult) { - if (!result.response.ok) { - const code = (result.error as { code?: string } | undefined)?.code; - return fail(result.response.status, { success: false, message: getErrorMessage(code) }); - } - return { success: true }; -} - -export async function load({ fetch, locals }) { - const user = locals.user; - const hasAdmin = user?.groups?.some((g: { permissions: string[] }) => - g.permissions.includes('ADMIN') - ); - if (!hasAdmin) throw error(403, getErrorMessage('FORBIDDEN')); - - const api = createApiClient(fetch); - - const [usersResult, groupsResult, tagsResult] = await Promise.all([ - api.GET('/api/users'), - api.GET('/api/groups'), - api.GET('/api/tags') - ]); - - return { - users: usersResult.data ?? [], - groups: groupsResult.data ?? [], - tags: tagsResult.data ?? [] - }; -} - -export const actions = { - deleteUser: async ({ request, fetch }) => { - const data = await request.formData(); - const id = data.get('id') as string; - const api = createApiClient(fetch); - - const result = await api.DELETE('/api/users/{id}', { - params: { path: { id } } - }); - - return toActionResult(result); - }, - - updateTag: async ({ request, fetch }) => { - const data = await request.formData(); - const id = data.get('id') as string; - const api = createApiClient(fetch); - - const result = await api.PUT('/api/tags/{id}', { - params: { path: { id } }, - body: { name: data.get('name') as string } - }); - - return toActionResult(result); - }, - - deleteTag: async ({ request, fetch }) => { - const data = await request.formData(); - const id = data.get('id') as string; - const api = createApiClient(fetch); - - const result = await api.DELETE('/api/tags/{id}', { - params: { path: { id } } - }); - - return toActionResult(result); - }, - - createGroup: async ({ request, fetch }) => { - const data = await request.formData(); - const api = createApiClient(fetch); - - const result = await api.POST('/api/groups', { - body: { - name: data.get('name') as string, - permissions: data.getAll('permissions') as string[] - } - }); - - return toActionResult(result); - }, - - updateGroup: async ({ request, fetch }) => { - const data = await request.formData(); - const id = data.get('id') as string; - const api = createApiClient(fetch); - - const result = await api.PATCH('/api/groups/{id}', { - params: { path: { id } }, - body: { - name: data.get('name') as string, - permissions: data.getAll('permissions') as string[] - } - }); - - return toActionResult(result); - }, - - deleteGroup: async ({ request, fetch }) => { - const data = await request.formData(); - const id = data.get('id') as string; - const api = createApiClient(fetch); - - const result = await api.DELETE('/api/groups/{id}', { - params: { path: { id } } - }); - - return toActionResult(result); - } -}; diff --git a/frontend/src/routes/admin/GroupsTab.svelte b/frontend/src/routes/admin/GroupsTab.svelte deleted file mode 100644 index 0f5da793..00000000 --- a/frontend/src/routes/admin/GroupsTab.svelte +++ /dev/null @@ -1,221 +0,0 @@ - - -
-
-

{m.admin_section_groups()}

-
- - - - - - - - - - - {#each groups as group (group.id)} - - {#if editingGroupId === group.id} - - - {:else} - - - - - {/if} - - {/each} - -
{m.admin_col_name()}{m.admin_col_permissions()}{m.admin_col_actions()}
-
- async ({ update }) => { - await update(); - cancelEditGroup(); - }} - class="flex w-full flex-col items-start gap-4 sm:flex-row" - > - - -
- -
- -
- {#each availablePermissions as perm (perm)} - - {/each} -
- -
- - -
-
-
- {group.name} - -
- {#each group.permissions as perm (perm)} - - {perm === 'ADMIN' ? '⚙ ' : ''}{perm} - - {/each} -
-
-
- - -
{ - if (!confirm(m.admin_group_delete_confirm())) { - cancel(); - } - return async ({ update }) => { - await update(); - }; - }} - > - - -
-
-
- - -
-

- {m.admin_section_new_group()} -

-
-
- -
- -
- {#each availablePermissions as perm (perm)} - - {/each} -
- - -
-
-
diff --git a/frontend/src/routes/admin/GroupsTab.svelte.spec.ts b/frontend/src/routes/admin/GroupsTab.svelte.spec.ts deleted file mode 100644 index ad9cc66e..00000000 --- a/frontend/src/routes/admin/GroupsTab.svelte.spec.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { afterEach, describe, it, expect, vi } from 'vitest'; -import { cleanup, render } from 'vitest-browser-svelte'; -import GroupsTab from './GroupsTab.svelte'; - -vi.mock('$app/forms', () => ({ enhance: () => () => {} })); - -afterEach(cleanup); - -const makeGroups = () => [ - { id: 'g1', name: 'Administrators', permissions: ['ADMIN', 'WRITE_ALL'] }, - { id: 'g2', name: 'Editors', permissions: ['WRITE_ALL'] } -]; - -describe('GroupsTab — ADMIN permission badge (WCAG 1.4.1)', () => { - it('ADMIN badge has a non-color indicator so it is distinguishable without color', () => { - // The ADMIN badge must not rely on color alone (WCAG 1.4.1). - // It must contain a visible non-color indicator: a text prefix such as ⚙. - const { container } = render(GroupsTab, { groups: makeGroups() }); - - const adminBadge = Array.from(container.querySelectorAll('span')).find((el) => - el.textContent?.includes('ADMIN') - ); - expect(adminBadge).toBeDefined(); - // Badge text must include a non-color prefix character - expect(adminBadge!.textContent).toMatch(/[⚙★⚠!]/); - }); -}); diff --git a/frontend/src/routes/admin/SystemTab.svelte b/frontend/src/routes/admin/SystemTab.svelte deleted file mode 100644 index bc4301ac..00000000 --- a/frontend/src/routes/admin/SystemTab.svelte +++ /dev/null @@ -1,72 +0,0 @@ - - -
-

{m.admin_system_backfill_heading()}

-

{m.admin_system_backfill_description()}

- - {#if backfillResult !== null} -

- {m.admin_system_backfill_success({ count: backfillResult })} -

- {/if} -
- -
-

- {m.admin_system_backfill_hashes_heading()} -

-

{m.admin_system_backfill_hashes_description()}

- - {#if backfillHashesResult !== null} -

- {m.admin_system_backfill_hashes_success({ count: backfillHashesResult })} -

- {/if} -
diff --git a/frontend/src/routes/admin/TagsTab.svelte b/frontend/src/routes/admin/TagsTab.svelte deleted file mode 100644 index 1b41558f..00000000 --- a/frontend/src/routes/admin/TagsTab.svelte +++ /dev/null @@ -1,127 +0,0 @@ - - -
-
-

{m.admin_section_tags()}

-

- {m.admin_tags_warning()} -

-
- -
    - {#each tags as tag (tag.id)} -
  • - {#if editingTagId === tag.id} -
    - async ({ update }) => { - await update(); - cancelEditTag(); - }} - class="flex flex-1 items-center gap-2" - > - - - - -
    - {:else} - - {tag.name} - -
    - -
    { - if (!confirm(m.admin_tag_delete_confirm())) { - cancel(); - } - return async ({ update }) => { - await update(); - }; - }} - class="inline" - > - - -
    -
    - {/if} -
  • - {/each} -
-
diff --git a/frontend/src/routes/admin/TagsTab.svelte.spec.ts b/frontend/src/routes/admin/TagsTab.svelte.spec.ts deleted file mode 100644 index 1f13f9c8..00000000 --- a/frontend/src/routes/admin/TagsTab.svelte.spec.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { afterEach, describe, it, expect, vi } from 'vitest'; -import { cleanup, render } from 'vitest-browser-svelte'; -import TagsTab from './TagsTab.svelte'; - -vi.mock('$app/forms', () => ({ enhance: () => () => {} })); - -afterEach(cleanup); - -const makeTags = () => [ - { id: 't1', name: 'Familie' }, - { id: 't2', name: 'Urlaub' } -]; - -describe('TagsTab — action buttons', () => { - it('no element with opacity-0 class exists (regression guard: buttons must not be hover-only)', () => { - // Before fix: the action buttons container had opacity-0 group-hover:opacity-100 - // which hides buttons on touch devices. After fix: that class is gone entirely. - const { container } = render(TagsTab, { tags: makeTags() }); - - const hiddenElements = container.querySelectorAll('.opacity-0'); - expect(hiddenElements.length).toBe(0); - }); -}); diff --git a/frontend/src/routes/admin/UsersTab.svelte b/frontend/src/routes/admin/UsersTab.svelte deleted file mode 100644 index 32e4d5c6..00000000 --- a/frontend/src/routes/admin/UsersTab.svelte +++ /dev/null @@ -1,122 +0,0 @@ - - -
-
-

{m.admin_section_users()}

- - - - - {m.admin_btn_new_user()} - -
- -
- - - - - - - - - - - {#each users as user (user.id)} - - - - - - - {/each} - -
{m.admin_col_login()}{m.admin_col_full_name()}{m.admin_col_groups()}{m.admin_col_actions()}
- {user.username} - - {#if user.firstName || user.lastName} - {user.firstName ?? ''} {user.lastName ?? ''} - {:else} - - {/if} - -
- {#if user.groups && user.groups.length > 0} - {#each user.groups as group (group.id)} - - {group.name} - - {/each} - {:else} - {m.admin_no_groups()} - {/if} -
-
-
- - {m.btn_edit()} - - -
{ - if (!confirm(m.admin_user_delete_confirm({ username: user.username }))) { - cancel(); - } - return async ({ update }) => { - await update(); - }; - }} - class="flex items-center" - > - - -
-
-
-
-
diff --git a/frontend/src/routes/admin/page.server.spec.ts b/frontend/src/routes/admin/page.server.spec.ts deleted file mode 100644 index a8edb053..00000000 --- a/frontend/src/routes/admin/page.server.spec.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest'; -import { load } from './+page.server'; - -vi.mock('$lib/api.server', () => ({ createApiClient: vi.fn() })); - -import { createApiClient } from '$lib/api.server'; - -const adminUser = { groups: [{ permissions: ['ADMIN'] }] }; -const readOnlyUser = { groups: [{ permissions: ['READ_ALL'] }] }; - -function mockApiReturning(users: unknown[], groups: unknown[], tags: unknown[]) { - vi.mocked(createApiClient).mockReturnValue({ - GET: vi - .fn() - .mockResolvedValueOnce({ response: { ok: true }, data: users }) - .mockResolvedValueOnce({ response: { ok: true }, data: groups }) - .mockResolvedValueOnce({ response: { ok: true }, data: tags }) - } as ReturnType); -} - -beforeEach(() => vi.clearAllMocks()); - -// ─── permission check ───────────────────────────────────────────────────────── - -describe('admin load — permission check', () => { - it('throws 403 when user has no ADMIN permission', async () => { - await expect( - load({ fetch: vi.fn() as unknown as typeof fetch, locals: { user: readOnlyUser } }) - ).rejects.toMatchObject({ status: 403 }); - }); - - it('throws 403 when user is undefined', async () => { - await expect( - load({ fetch: vi.fn() as unknown as typeof fetch, locals: { user: undefined } }) - ).rejects.toMatchObject({ status: 403 }); - }); - - it('throws 403 when user has no groups', async () => { - await expect( - load({ fetch: vi.fn() as unknown as typeof fetch, locals: { user: { groups: [] } } }) - ).rejects.toMatchObject({ status: 403 }); - }); -}); - -// ─── happy path ─────────────────────────────────────────────────────────────── - -describe('admin load — happy path', () => { - it('returns users, groups, and tags for an admin user', async () => { - mockApiReturning( - [{ id: 'u1', username: 'alice' }], - [{ id: 'g1', name: 'Editors' }], - [{ id: 't1', name: 'Familie' }] - ); - - const result = await load({ - fetch: vi.fn() as unknown as typeof fetch, - locals: { user: adminUser } - }); - - expect(result.users).toHaveLength(1); - expect(result.groups).toHaveLength(1); - expect(result.tags).toHaveLength(1); - }); - - it('returns empty arrays when API returns no data', async () => { - mockApiReturning([], [], []); - - const result = await load({ - fetch: vi.fn() as unknown as typeof fetch, - locals: { user: adminUser } - }); - - expect(result.users).toEqual([]); - expect(result.groups).toEqual([]); - expect(result.tags).toEqual([]); - }); -}); diff --git a/frontend/src/routes/admin/users/[id]/+page.server.ts b/frontend/src/routes/admin/users/[id]/+page.server.ts index 6d99c407..14c719b6 100644 --- a/frontend/src/routes/admin/users/[id]/+page.server.ts +++ b/frontend/src/routes/admin/users/[id]/+page.server.ts @@ -1,4 +1,4 @@ -import { error, fail } from '@sveltejs/kit'; +import { error, fail, redirect } from '@sveltejs/kit'; import type { PageServerLoad, Actions } from './$types'; import { createApiClient } from '$lib/api.server'; import { getErrorMessage } from '$lib/errors'; @@ -63,5 +63,19 @@ export const actions: Actions = { } return { success: true }; + }, + + delete: async ({ params, fetch }) => { + const api = createApiClient(fetch); + const result = await api.DELETE('/api/users/{id}', { + params: { path: { id: params.id } } + }); + + if (!result.response.ok) { + const code = (result.error as unknown as { code?: string })?.code; + return fail(result.response.status, { error: getErrorMessage(code) }); + } + + throw redirect(303, '/admin/users'); } }; diff --git a/frontend/src/routes/admin/users/[id]/+page.svelte b/frontend/src/routes/admin/users/[id]/+page.svelte index e2201990..03ac297a 100644 --- a/frontend/src/routes/admin/users/[id]/+page.svelte +++ b/frontend/src/routes/admin/users/[id]/+page.svelte @@ -16,6 +16,25 @@ const selectedGroupIds = $derived(data.editUser.groups?.map((g: { id: string })

{m.admin_user_edit_heading({ username: data.editUser.username })}

+
{ + if (!confirm(m.admin_user_delete_confirm({ username: data.editUser.username }))) { + cancel(); + } + return async ({ update }) => { + await update(); + }; + }} + > + +
diff --git a/frontend/src/routes/admin/users/[id]/page.svelte.spec.ts b/frontend/src/routes/admin/users/[id]/page.svelte.spec.ts index 43fca9b1..53dce8b4 100644 --- a/frontend/src/routes/admin/users/[id]/page.svelte.spec.ts +++ b/frontend/src/routes/admin/users/[id]/page.svelte.spec.ts @@ -96,7 +96,7 @@ describe('Admin edit user page – rendering', () => { it('includes pre-selected group ids in FormData at submit time (guards against groupIds being empty)', async () => { render(Page, { data: baseData, form: null }); - const form = document.querySelector('form')!; + const form = document.querySelector('form#edit-user-form')!; const formData = new FormData(form); expect(formData.getAll('groupIds')).toContain('g1'); expect(formData.getAll('groupIds')).not.toContain('g2'); -- 2.49.1 From 06a489567a6c901f6a14cc5de96d510d5658c3e5 Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 01:58:10 +0200 Subject: [PATCH 07/31] =?UTF-8?q?feat(admin):=20phase=208=20=E2=80=94=20un?= =?UTF-8?q?saved-changes=20guard=20on=20all=20detail=20panels?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add beforeNavigate + isDirty tracking to users/[id], users/new, groups/[id], groups/new, and tags/[id] edit panels. When a user navigates away with unsaved changes, the navigation is cancelled and an inline amber warning banner appears with a Discard button that resumes navigation. Saving successfully clears the dirty flag. Add i18n key admin_unsaved_warning (de/en/es). Add spec files for groups/[id] and tags/[id] panels. Co-Authored-By: Claude Sonnet 4.6 --- frontend/messages/de.json | 1 + frontend/messages/en.json | 1 + frontend/messages/es.json | 1 + .../src/routes/admin/groups/[id]/+page.svelte | 49 +++++++- .../admin/groups/[id]/page.svelte.spec.ts | 113 ++++++++++++++++++ .../src/routes/admin/groups/new/+page.svelte | 42 ++++++- .../src/routes/admin/tags/[id]/+page.svelte | 50 +++++++- .../admin/tags/[id]/page.svelte.spec.ts | 93 ++++++++++++++ .../src/routes/admin/users/[id]/+page.svelte | 49 +++++++- .../admin/users/[id]/page.svelte.spec.ts | 74 +++++++++++- .../src/routes/admin/users/new/+page.svelte | 42 ++++++- 11 files changed, 509 insertions(+), 6 deletions(-) create mode 100644 frontend/src/routes/admin/groups/[id]/page.svelte.spec.ts create mode 100644 frontend/src/routes/admin/tags/[id]/page.svelte.spec.ts diff --git a/frontend/messages/de.json b/frontend/messages/de.json index cd4ad3de..9b24a14c 100644 --- a/frontend/messages/de.json +++ b/frontend/messages/de.json @@ -160,6 +160,7 @@ "admin_tags_select_prompt": "W\u00e4hle ein Schlagwort aus der Liste.", "admin_tag_edit_heading": "Schlagwort: {name}", "admin_tag_updated": "Schlagwort umbenannt.", + "admin_unsaved_warning": "Du hast ungespeicherte Änderungen – speichere oder verwerfe, bevor du wechselst.", "admin_btn_edit_tag_label": "Schlagwort bearbeiten", "admin_tag_delete_confirm": "Wirklich löschen? Das Schlagwort wird aus allen Dokumenten entfernt.", "admin_btn_delete_tag_label": "Schlagwort löschen", diff --git a/frontend/messages/en.json b/frontend/messages/en.json index 1484b937..eda45cda 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -160,6 +160,7 @@ "admin_tags_select_prompt": "Select a tag from the list.", "admin_tag_edit_heading": "Tag: {name}", "admin_tag_updated": "Tag renamed.", + "admin_unsaved_warning": "You have unsaved changes — save or discard before switching.", "admin_btn_edit_tag_label": "Edit tag", "admin_tag_delete_confirm": "Really delete? The tag will be removed from all documents.", "admin_btn_delete_tag_label": "Delete tag", diff --git a/frontend/messages/es.json b/frontend/messages/es.json index 381ba174..49263510 100644 --- a/frontend/messages/es.json +++ b/frontend/messages/es.json @@ -160,6 +160,7 @@ "admin_tags_select_prompt": "Selecciona una etiqueta de la lista.", "admin_tag_edit_heading": "Etiqueta: {name}", "admin_tag_updated": "Etiqueta renombrada.", + "admin_unsaved_warning": "Tienes cambios sin guardar — guarda o descarta antes de cambiar.", "admin_btn_edit_tag_label": "Editar etiqueta", "admin_tag_delete_confirm": "¿Realmente eliminar? La etiqueta se eliminará de todos los documentos.", "admin_btn_delete_tag_label": "Eliminar etiqueta", diff --git a/frontend/src/routes/admin/groups/[id]/+page.svelte b/frontend/src/routes/admin/groups/[id]/+page.svelte index 377617d3..3705ea67 100644 --- a/frontend/src/routes/admin/groups/[id]/+page.svelte +++ b/frontend/src/routes/admin/groups/[id]/+page.svelte @@ -1,9 +1,29 @@
@@ -25,13 +38,40 @@ let { form } = $props();
+ {#if showUnsavedWarning} +
+ {m.admin_unsaved_warning()} + +
+ {/if} {#if form?.error}
{form.error}
{/if} -
+ { + isDirty = true; + showUnsavedWarning = false; + }} + class="space-y-5" + >

diff --git a/frontend/src/routes/admin/tags/[id]/+page.svelte b/frontend/src/routes/admin/tags/[id]/+page.svelte index 078b2601..77d4af1e 100644 --- a/frontend/src/routes/admin/tags/[id]/+page.svelte +++ b/frontend/src/routes/admin/tags/[id]/+page.svelte @@ -1,11 +1,31 @@
@@ -18,6 +38,24 @@ const deleteEnabled = $derived(deleteConfirmName === data.tag.name);
+ {#if showUnsavedWarning} +
+ {m.admin_unsaved_warning()} + +
+ {/if} {#if form?.success}
{m.admin_tag_updated()} @@ -30,7 +68,17 @@ const deleteEnabled = $derived(deleteConfirmName === data.tag.name); {/if} - + { + isDirty = true; + showUnsavedWarning = false; + }} + class="mb-5" + >

{m.admin_col_name()} diff --git a/frontend/src/routes/admin/tags/[id]/page.svelte.spec.ts b/frontend/src/routes/admin/tags/[id]/page.svelte.spec.ts new file mode 100644 index 00000000..e327f6b8 --- /dev/null +++ b/frontend/src/routes/admin/tags/[id]/page.svelte.spec.ts @@ -0,0 +1,93 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render } from 'vitest-browser-svelte'; +import { page } from 'vitest/browser'; +import Page from './+page.svelte'; + +vi.mock('$app/forms', () => ({ enhance: () => () => {} })); +vi.mock('$app/navigation', () => ({ beforeNavigate: vi.fn(), goto: vi.fn() })); + +import { beforeNavigate, goto } from '$app/navigation'; + +const baseTag = { id: 't1', name: 'Familie' }; +const baseData = { tag: baseTag }; + +afterEach(cleanup); + +// ─── Rendering ──────────────────────────────────────────────────────────────── + +describe('Admin edit tag page – rendering', () => { + it('renders the heading with tag name', async () => { + render(Page, { data: baseData, form: null }); + await expect.element(page.getByText(/Schlagwort: Familie/i)).toBeInTheDocument(); + }); + + it('pre-fills the name input', async () => { + render(Page, { data: baseData, form: null }); + const input = document.querySelector('input[name="name"]'); + expect(input?.value).toBe('Familie'); + }); + + it('renders the cancel link pointing to /admin/tags', async () => { + render(Page, { data: baseData, form: null }); + await expect + .element(page.getByRole('link', { name: /Abbrechen/i })) + .toHaveAttribute('href', '/admin/tags'); + }); + + it('delete button is disabled until tag name is typed in confirm field', async () => { + render(Page, { data: baseData, form: null }); + const deleteBtn = document.querySelector('button[type="submit"]'); + expect(deleteBtn?.disabled).toBe(true); + }); +}); + +// ─── Unsaved-changes guard ──────────────────────────────────────────────────── + +describe('Admin edit tag page – unsaved-changes guard', () => { + beforeEach(() => vi.clearAllMocks()); + + it('does not show unsaved warning initially', async () => { + render(Page, { data: baseData, form: null }); + await expect.element(page.getByText(/ungespeicherte Änderungen/i)).not.toBeInTheDocument(); + }); + + it('cancels navigation and shows warning when rename form is dirty', async () => { + render(Page, { data: baseData, form: null }); + const [callback] = vi.mocked(beforeNavigate).mock.calls[0]; + + document + .querySelector('input[name="name"]')! + .dispatchEvent(new InputEvent('input', { bubbles: true })); + + const cancel = vi.fn(); + callback({ cancel, to: { url: new URL('http://localhost/admin/tags/t2') } }); + + expect(cancel).toHaveBeenCalled(); + await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument(); + }); + + it('does not cancel navigation when form is clean', async () => { + render(Page, { data: baseData, form: null }); + const [callback] = vi.mocked(beforeNavigate).mock.calls[0]; + + const cancel = vi.fn(); + callback({ cancel, to: { url: new URL('http://localhost/admin/tags/t2') } }); + + expect(cancel).not.toHaveBeenCalled(); + }); + + it('discard button calls goto with the target URL', async () => { + render(Page, { data: baseData, form: null }); + const [callback] = vi.mocked(beforeNavigate).mock.calls[0]; + + document + .querySelector('input[name="name"]')! + .dispatchEvent(new InputEvent('input', { bubbles: true })); + + callback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/tags/t2') } }); + + await page.getByRole('button', { name: /verwerfen/i }).click(); + + expect(vi.mocked(goto)).toHaveBeenCalledWith('http://localhost/admin/tags/t2'); + }); +}); diff --git a/frontend/src/routes/admin/users/[id]/+page.svelte b/frontend/src/routes/admin/users/[id]/+page.svelte index 03ac297a..019f81ed 100644 --- a/frontend/src/routes/admin/users/[id]/+page.svelte +++ b/frontend/src/routes/admin/users/[id]/+page.svelte @@ -1,5 +1,6 @@
@@ -39,6 +59,24 @@ const selectedGroupIds = $derived(data.editUser.groups?.map((g: { id: string })
+ {#if showUnsavedWarning} +
+ {m.admin_unsaved_warning()} + +
+ {/if} {#if form?.success}
{m.admin_user_updated()} @@ -50,7 +88,16 @@ const selectedGroupIds = $derived(data.editUser.groups?.map((g: { id: string })
{/if} - + { + isDirty = true; + showUnsavedWarning = false; + }} + class="space-y-5" + >

diff --git a/frontend/src/routes/admin/users/[id]/page.svelte.spec.ts b/frontend/src/routes/admin/users/[id]/page.svelte.spec.ts index 53dce8b4..0c5fdd76 100644 --- a/frontend/src/routes/admin/users/[id]/page.svelte.spec.ts +++ b/frontend/src/routes/admin/users/[id]/page.svelte.spec.ts @@ -1,9 +1,12 @@ -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, render } from 'vitest-browser-svelte'; import { page } from 'vitest/browser'; import Page from './+page.svelte'; vi.mock('$app/forms', () => ({ enhance: () => () => {} })); +vi.mock('$app/navigation', () => ({ beforeNavigate: vi.fn(), goto: vi.fn() })); + +import { beforeNavigate, goto } from '$app/navigation'; const groups = [ { id: 'g1', name: 'Editoren', permissions: ['WRITE_ALL'] }, @@ -141,3 +144,72 @@ describe('Admin edit user page – feedback', () => { await expect.element(page.getByText(/Änderungen gespeichert/i)).not.toBeInTheDocument(); }); }); + +// ─── Unsaved-changes guard ──────────────────────────────────────────────────── + +describe('Admin edit user page – unsaved-changes guard', () => { + beforeEach(() => vi.clearAllMocks()); + + it('does not show unsaved warning initially', async () => { + render(Page, { data: baseData, form: null }); + await expect.element(page.getByText(/ungespeicherte Änderungen/i)).not.toBeInTheDocument(); + }); + + it('cancels navigation and shows warning when form is dirty', async () => { + render(Page, { data: baseData, form: null }); + const [callback] = vi.mocked(beforeNavigate).mock.calls[0]; + + document + .querySelector('input[name="firstName"]')! + .dispatchEvent(new InputEvent('input', { bubbles: true })); + + const cancel = vi.fn(); + callback({ cancel, to: { url: new URL('http://localhost/admin/users/u2') } }); + + expect(cancel).toHaveBeenCalled(); + await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument(); + }); + + it('does not cancel navigation when form is clean', async () => { + render(Page, { data: baseData, form: null }); + const [callback] = vi.mocked(beforeNavigate).mock.calls[0]; + + const cancel = vi.fn(); + callback({ cancel, to: { url: new URL('http://localhost/admin/users/u2') } }); + + expect(cancel).not.toHaveBeenCalled(); + }); + + it('discard button calls goto with the target URL', async () => { + render(Page, { data: baseData, form: null }); + const [callback] = vi.mocked(beforeNavigate).mock.calls[0]; + + document + .querySelector('input[name="firstName"]')! + .dispatchEvent(new InputEvent('input', { bubbles: true })); + + callback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/users/u2') } }); + + await page.getByRole('button', { name: /verwerfen/i }).click(); + + expect(vi.mocked(goto)).toHaveBeenCalledWith('http://localhost/admin/users/u2'); + }); + + it('clears dirty state when form saves successfully', async () => { + const { rerender } = render(Page, { data: baseData, form: null }); + const [callback] = vi.mocked(beforeNavigate).mock.calls[0]; + + document + .querySelector('input[name="firstName"]')! + .dispatchEvent(new InputEvent('input', { bubbles: true })); + + callback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/users/u2') } }); + await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument(); + + await rerender({ data: baseData, form: { success: true } }); + + const cancel = vi.fn(); + callback({ cancel, to: { url: new URL('http://localhost/admin/users/u2') } }); + expect(cancel).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/routes/admin/users/new/+page.svelte b/frontend/src/routes/admin/users/new/+page.svelte index cfb63278..30a0e68c 100644 --- a/frontend/src/routes/admin/users/new/+page.svelte +++ b/frontend/src/routes/admin/users/new/+page.svelte @@ -1,11 +1,24 @@
@@ -16,13 +29,40 @@ let { data, form } = $props();
+ {#if showUnsavedWarning} +
+ {m.admin_unsaved_warning()} + +
+ {/if} {#if form?.error}
{form.error}
{/if} - + { + isDirty = true; + showUnsavedWarning = false; + }} + class="space-y-5" + >
-- 2.49.1 From 3c54401bb2d1c97eca9a17fd2eacf02a6732e0d4 Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 07:19:41 +0200 Subject: [PATCH 08/31] feat(admin): responsive entity nav and collapsible list panels (Phase 9) EntityNav: hidden on mobile, 48px icon strip at tablet (md), full labels+counts at desktop (lg). Each list panel collapses to a 32px handle via localStorage-persisted state; auto-collapses when navigating to the "+New" route. Mobile routing hides the list panel when a detail route is active. Co-Authored-By: Claude Sonnet 4.6 --- frontend/messages/de.json | 2 + frontend/messages/en.json | 2 + frontend/messages/es.json | 2 + frontend/src/routes/admin/+layout.svelte | 22 ++- frontend/src/routes/admin/EntityNav.svelte | 126 ++++++++++-- .../src/routes/admin/groups/+layout.svelte | 11 +- .../admin/groups/GroupsListPanel.svelte | 141 +++++++++----- .../routes/admin/groups/layout.svelte.spec.ts | 33 +++- frontend/src/routes/admin/tags/+layout.svelte | 10 +- .../routes/admin/tags/TagsListPanel.svelte | 102 +++++++--- .../routes/admin/tags/layout.svelte.spec.ts | 30 ++- .../src/routes/admin/users/+layout.svelte | 16 +- .../routes/admin/users/UsersListPanel.svelte | 182 +++++++++++------- .../routes/admin/users/layout.svelte.spec.ts | 39 +++- 14 files changed, 540 insertions(+), 178 deletions(-) diff --git a/frontend/messages/de.json b/frontend/messages/de.json index 9b24a14c..fdd201d6 100644 --- a/frontend/messages/de.json +++ b/frontend/messages/de.json @@ -161,6 +161,8 @@ "admin_tag_edit_heading": "Schlagwort: {name}", "admin_tag_updated": "Schlagwort umbenannt.", "admin_unsaved_warning": "Du hast ungespeicherte Änderungen – speichere oder verwerfe, bevor du wechselst.", + "admin_btn_collapse_list": "Liste einklappen", + "admin_btn_expand_list": "Liste ausklappen", "admin_btn_edit_tag_label": "Schlagwort bearbeiten", "admin_tag_delete_confirm": "Wirklich löschen? Das Schlagwort wird aus allen Dokumenten entfernt.", "admin_btn_delete_tag_label": "Schlagwort löschen", diff --git a/frontend/messages/en.json b/frontend/messages/en.json index eda45cda..3c501a2a 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -161,6 +161,8 @@ "admin_tag_edit_heading": "Tag: {name}", "admin_tag_updated": "Tag renamed.", "admin_unsaved_warning": "You have unsaved changes — save or discard before switching.", + "admin_btn_collapse_list": "Collapse list", + "admin_btn_expand_list": "Expand list", "admin_btn_edit_tag_label": "Edit tag", "admin_tag_delete_confirm": "Really delete? The tag will be removed from all documents.", "admin_btn_delete_tag_label": "Delete tag", diff --git a/frontend/messages/es.json b/frontend/messages/es.json index 49263510..b65254cf 100644 --- a/frontend/messages/es.json +++ b/frontend/messages/es.json @@ -161,6 +161,8 @@ "admin_tag_edit_heading": "Etiqueta: {name}", "admin_tag_updated": "Etiqueta renombrada.", "admin_unsaved_warning": "Tienes cambios sin guardar — guarda o descarta antes de cambiar.", + "admin_btn_collapse_list": "Contraer lista", + "admin_btn_expand_list": "Expandir lista", "admin_btn_edit_tag_label": "Editar etiqueta", "admin_tag_delete_confirm": "¿Realmente eliminar? La etiqueta se eliminará de todos los documentos.", "admin_btn_delete_tag_label": "Eliminar etiqueta", diff --git a/frontend/src/routes/admin/+layout.svelte b/frontend/src/routes/admin/+layout.svelte index 6c9558dd..ba3e1849 100644 --- a/frontend/src/routes/admin/+layout.svelte +++ b/frontend/src/routes/admin/+layout.svelte @@ -13,16 +13,18 @@ let { data, children } = $props(); Height fills from below the global header (64px) to bottom of viewport. -->
- - + +
diff --git a/frontend/src/routes/admin/EntityNav.svelte b/frontend/src/routes/admin/EntityNav.svelte index 36334284..f0c35b81 100644 --- a/frontend/src/routes/admin/EntityNav.svelte +++ b/frontend/src/routes/admin/EntityNav.svelte @@ -24,71 +24,154 @@ const currentPath = $derived(page.url.pathname); const isActive = (section: string) => currentPath.startsWith(`/admin/${section}`); -
diff --git a/frontend/src/routes/admin/system/page.svelte.spec.ts b/frontend/src/routes/admin/system/page.svelte.spec.ts index 4d8e0bb7..df349893 100644 --- a/frontend/src/routes/admin/system/page.svelte.spec.ts +++ b/frontend/src/routes/admin/system/page.svelte.spec.ts @@ -1,9 +1,10 @@ -import { afterEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, render } from 'vitest-browser-svelte'; import { page } from 'vitest/browser'; import Page from './+page.svelte'; afterEach(cleanup); +afterEach(() => vi.restoreAllMocks()); describe('Admin system page', () => { it('renders the backfill versions heading', async () => { @@ -32,3 +33,104 @@ describe('Admin system page', () => { .toBeInTheDocument(); }); }); + +describe('Admin system page — mass import card', () => { + beforeEach(() => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + state: 'IDLE', + message: 'Kein Import gestartet.', + processed: 0, + startedAt: null + }) + }) + ); + }); + + it('renders the mass import heading', async () => { + render(Page, {}); + await expect.element(page.getByText(/Massenimport/i)).toBeInTheDocument(); + }); + + it('renders the start import button when idle', async () => { + render(Page, {}); + await expect.element(page.getByRole('button', { name: /Import starten/i })).toBeInTheDocument(); + }); + + it('shows idle status text', async () => { + render(Page, {}); + await expect.element(page.getByText(/Kein Import gestartet/i)).toBeInTheDocument(); + }); + + it('disables the start button and shows running state after click', async () => { + const fetchMock = vi + .fn() + // initial status fetch → IDLE + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ + state: 'IDLE', + message: 'Kein Import gestartet.', + processed: 0, + startedAt: null + }) + }) + // trigger POST → returns RUNNING immediately + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ + state: 'RUNNING', + message: 'Import läuft...', + processed: 0, + startedAt: '2026-01-01T10:00:00' + }) + }); + vi.stubGlobal('fetch', fetchMock); + + render(Page, {}); + await expect.element(page.getByRole('button', { name: /Import starten/i })).toBeInTheDocument(); + + document.querySelector('[data-import-trigger]')!.click(); + + await expect.element(page.getByText(/Import läuft/i)).toBeInTheDocument(); + }); + + it('shows done status and retry button after successful import', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + state: 'DONE', + message: 'Import abgeschlossen.', + processed: 42, + startedAt: '2026-01-01T10:00:00' + }) + }) + ); + render(Page, {}); + await expect.element(page.getByText(/42 Dokumente/i)).toBeInTheDocument(); + await expect.element(page.getByRole('button', { name: /Erneut starten/i })).toBeInTheDocument(); + }); + + it('shows failed status and retry button on error', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + state: 'FAILED', + message: 'Datei nicht gefunden.', + processed: 0, + startedAt: '2026-01-01T10:00:00' + }) + }) + ); + render(Page, {}); + await expect.element(page.getByText(/Datei nicht gefunden/i)).toBeInTheDocument(); + await expect.element(page.getByRole('button', { name: /Erneut starten/i })).toBeInTheDocument(); + }); +}); -- 2.49.1 From 09d8fb5f9525b70b340e0a4f32c0f24ed6b32db2 Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 10:12:48 +0200 Subject: [PATCH 11/31] feat(admin): add READ_ALL and ANNOTATE_ALL to groups permission matrix Adds 'Nur lesen' (READ_ALL) and 'Lesen & Annotieren' (ANNOTATE_ALL) as standard permission options alongside the existing 'Lesen & Schreiben' (WRITE_ALL), ordered from least to most access. Co-Authored-By: Claude Sonnet 4.6 --- .../src/routes/admin/groups/[id]/+page.svelte | 2 ++ .../admin/groups/[id]/page.svelte.spec.ts | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/frontend/src/routes/admin/groups/[id]/+page.svelte b/frontend/src/routes/admin/groups/[id]/+page.svelte index 3705ea67..66462616 100644 --- a/frontend/src/routes/admin/groups/[id]/+page.svelte +++ b/frontend/src/routes/admin/groups/[id]/+page.svelte @@ -25,6 +25,8 @@ $effect(() => { }); const STANDARD_PERMISSIONS: { value: string; label: string }[] = [ + { value: 'READ_ALL', label: 'Nur lesen' }, + { value: 'ANNOTATE_ALL', label: 'Lesen & Annotieren' }, { value: 'WRITE_ALL', label: 'Lesen & Schreiben' } ]; diff --git a/frontend/src/routes/admin/groups/[id]/page.svelte.spec.ts b/frontend/src/routes/admin/groups/[id]/page.svelte.spec.ts index 911ecf57..426ca22c 100644 --- a/frontend/src/routes/admin/groups/[id]/page.svelte.spec.ts +++ b/frontend/src/routes/admin/groups/[id]/page.svelte.spec.ts @@ -41,6 +41,42 @@ describe('Admin edit group page – rendering', () => { .element(page.getByRole('link', { name: /Abbrechen/i })) .toHaveAttribute('href', '/admin/groups'); }); + + it('renders a READ_ALL checkbox in the standard permissions section', async () => { + render(Page, { data: baseData, form: null }); + const cb = document.querySelector( + 'input[type="checkbox"][name="permissions"][value="READ_ALL"]' + ); + expect(cb).not.toBeNull(); + }); + + it('renders an ANNOTATE_ALL checkbox in the standard permissions section', async () => { + render(Page, { data: baseData, form: null }); + const cb = document.querySelector( + 'input[type="checkbox"][name="permissions"][value="ANNOTATE_ALL"]' + ); + expect(cb).not.toBeNull(); + }); + + it('pre-checks READ_ALL when group has it', async () => { + const data = { group: { id: 'g2', name: 'Leser', permissions: ['READ_ALL'] } }; + render(Page, { data, form: null }); + const cb = document.querySelector( + 'input[type="checkbox"][name="permissions"][value="READ_ALL"]' + ); + expect(cb?.checked).toBe(true); + }); + + it('pre-checks ANNOTATE_ALL when group has it', async () => { + const data = { + group: { id: 'g3', name: 'Annotatoren', permissions: ['READ_ALL', 'ANNOTATE_ALL'] } + }; + render(Page, { data, form: null }); + const cb = document.querySelector( + 'input[type="checkbox"][name="permissions"][value="ANNOTATE_ALL"]' + ); + expect(cb?.checked).toBe(true); + }); }); // ─── Unsaved-changes guard ──────────────────────────────────────────────────── -- 2.49.1 From 393cb52178d03718abc1c937a3e209b9018c0af1 Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 11:23:27 +0200 Subject: [PATCH 12/31] fix(admin): address PR review feedback from all personas MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Blockers resolved: - localStorage key collision: UsersListPanel/GroupsListPanel/TagsListPanel now each use their own key (admin_*_list_collapsed) - $effect autocollapse replaced with $derived(autocollapse || manualCollapse) across all three list panels (Felix — Svelte 5 rule violation) - groups/new: add READ_ALL and ANNOTATE_ALL to available standard permissions - Mobile back-to-list links added to all five detail panel headers (md:hidden) so users landing directly on a detail URL on mobile can navigate back - onDestroy(() => stopPolling()) added to system/+page.svelte (Tobias) High priority resolved: - Permission labels in groups/[id] and groups/new now use Paraglide i18n keys (admin_perm_read_all, admin_perm_annotate_all, etc.) across de/en/es - $derived used for permission arrays (reactive i18n) — Felix Svelte 5 rule - UserGroup type in +layout.server.ts now uses generated API type (Markus/Felix) - discardTarget annotation changed to variable-level type annotation Accessibility (Leonie): - EntityNav tablet icon strip buttons: min-h-[44px] for WCAG 2.5.8 compliance - Flyout focus management: openFlyout() focuses first link, closeFlyout() returns focus to the trigger button that opened it - Flyout animation replaced: broken inline style -> transition:fly={{ x: -160 }} Tests (Sara/Felix): - localStorage key assertion tests added per panel - localStorage.removeItem calls updated to use the panel-specific keys - page.server.spec.ts added for groups/[id] and tags/[id] delete actions - Polling lifecycle tests added to system/page.svelte.spec.ts Note: Paraglide types for new admin_perm_* keys regenerate automatically on next npm run dev (Vite plugin). No manual compilation step needed. Co-Authored-By: Claude Sonnet 4.6 --- frontend/messages/de.json | 7 ++ frontend/messages/en.json | 7 ++ frontend/messages/es.json | 7 ++ frontend/src/app.d.ts | 1 + frontend/src/routes/admin/+layout.server.ts | 3 +- frontend/src/routes/admin/EntityNav.svelte | 46 ++++++---- .../admin/groups/GroupsListPanel.svelte | 16 ++-- .../src/routes/admin/groups/[id]/+page.svelte | 39 ++++++--- .../admin/groups/[id]/page.server.spec.ts | 87 +++++++++++++++++++ .../routes/admin/groups/layout.svelte.spec.ts | 10 ++- .../src/routes/admin/groups/new/+page.svelte | 35 ++++++-- frontend/src/routes/admin/system/+page.svelte | 4 +- .../routes/admin/system/page.svelte.spec.ts | 55 +++++++++++- .../routes/admin/tags/TagsListPanel.svelte | 16 ++-- .../src/routes/admin/tags/[id]/+page.svelte | 17 +++- .../admin/tags/[id]/page.server.spec.ts | 85 ++++++++++++++++++ .../routes/admin/tags/layout.svelte.spec.ts | 10 ++- .../routes/admin/users/UsersListPanel.svelte | 16 ++-- .../src/routes/admin/users/[id]/+page.svelte | 17 +++- .../routes/admin/users/layout.svelte.spec.ts | 10 ++- .../src/routes/admin/users/new/+page.svelte | 17 +++- 21 files changed, 434 insertions(+), 71 deletions(-) create mode 100644 frontend/src/routes/admin/groups/[id]/page.server.spec.ts create mode 100644 frontend/src/routes/admin/tags/[id]/page.server.spec.ts diff --git a/frontend/messages/de.json b/frontend/messages/de.json index c344e8e3..de8e73e6 100644 --- a/frontend/messages/de.json +++ b/frontend/messages/de.json @@ -190,6 +190,13 @@ "admin_group_created": "Gruppe erstellt.", "admin_groups_section_standard": "Standard", "admin_groups_section_administrative": "Administrativ", + "admin_perm_read_all": "Nur lesen", + "admin_perm_annotate_all": "Lesen & Annotieren", + "admin_perm_write_all": "Lesen & Schreiben", + "admin_perm_admin": "Vollzugriff (Admin)", + "admin_perm_admin_user": "Benutzer verwalten", + "admin_perm_admin_tag": "Schlagworte verwalten", + "admin_perm_admin_permission": "Berechtigungen verwalten", "admin_user_new_heading": "Neuen Benutzer anlegen", "admin_user_edit_heading": "Benutzer bearbeiten: {username}", "admin_user_created": "Benutzer wurde erstellt.", diff --git a/frontend/messages/en.json b/frontend/messages/en.json index 7bb2a116..cc25945f 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -190,6 +190,13 @@ "admin_group_created": "Group created.", "admin_groups_section_standard": "Standard", "admin_groups_section_administrative": "Administrative", + "admin_perm_read_all": "Read only", + "admin_perm_annotate_all": "Read & Annotate", + "admin_perm_write_all": "Read & Write", + "admin_perm_admin": "Full access (Admin)", + "admin_perm_admin_user": "Manage users", + "admin_perm_admin_tag": "Manage tags", + "admin_perm_admin_permission": "Manage permissions", "admin_user_new_heading": "Create new user", "admin_user_edit_heading": "Edit user: {username}", "admin_user_created": "User has been created.", diff --git a/frontend/messages/es.json b/frontend/messages/es.json index 0f9d93d4..3e2cab2b 100644 --- a/frontend/messages/es.json +++ b/frontend/messages/es.json @@ -190,6 +190,13 @@ "admin_group_created": "Grupo creado.", "admin_groups_section_standard": "Est\u00e1ndar", "admin_groups_section_administrative": "Administrativo", + "admin_perm_read_all": "Solo lectura", + "admin_perm_annotate_all": "Leer y anotar", + "admin_perm_write_all": "Leer y escribir", + "admin_perm_admin": "Acceso completo (Admin)", + "admin_perm_admin_user": "Gestionar usuarios", + "admin_perm_admin_tag": "Gestionar etiquetas", + "admin_perm_admin_permission": "Gestionar permisos", "admin_user_new_heading": "Crear nuevo usuario", "admin_user_edit_heading": "Editar usuario: {username}", "admin_user_created": "Usuario creado.", diff --git a/frontend/src/app.d.ts b/frontend/src/app.d.ts index 0663671f..ca517012 100644 --- a/frontend/src/app.d.ts +++ b/frontend/src/app.d.ts @@ -12,6 +12,7 @@ declare global { email?: string; contact?: string; groups: { + id: string; name: string; permissions: string[]; }[]; diff --git a/frontend/src/routes/admin/+layout.server.ts b/frontend/src/routes/admin/+layout.server.ts index 19405345..f21bbff4 100644 --- a/frontend/src/routes/admin/+layout.server.ts +++ b/frontend/src/routes/admin/+layout.server.ts @@ -1,8 +1,9 @@ import { error } from '@sveltejs/kit'; import { createApiClient } from '$lib/api.server'; import { getErrorMessage } from '$lib/errors'; +import type { components } from '$lib/generated/api'; -type UserGroup = { permissions: string[] }; +type UserGroup = components['schemas']['UserGroup']; function hasPerm(user: { groups?: UserGroup[] } | undefined, perm: string): boolean { return user?.groups?.some((g) => g.permissions.includes(perm)) ?? false; diff --git a/frontend/src/routes/admin/EntityNav.svelte b/frontend/src/routes/admin/EntityNav.svelte index ae57556b..0de54985 100644 --- a/frontend/src/routes/admin/EntityNav.svelte +++ b/frontend/src/routes/admin/EntityNav.svelte @@ -1,4 +1,6 @@ @@ -55,8 +71,8 @@ function handleKeydown(event: KeyboardEvent) { data-flyout-trigger type="button" aria-label={m.admin_tab_users()} - onclick={() => (flyoutOpen = true)} - class="flex w-full flex-col items-center justify-center gap-0.5 border-l-[3px] py-3 transition-colors lg:hidden + onclick={openFlyout} + class="flex min-h-[44px] w-full flex-col items-center justify-center gap-0.5 border-l-[3px] py-3 transition-colors lg:hidden {isActive('users') ? 'border-brand-mint bg-white/10' : 'border-transparent hover:bg-white/5'}" @@ -121,8 +137,8 @@ function handleKeydown(event: KeyboardEvent) { data-flyout-trigger type="button" aria-label={m.admin_tab_groups()} - onclick={() => (flyoutOpen = true)} - class="flex w-full flex-col items-center justify-center gap-0.5 border-l-[3px] py-3 transition-colors lg:hidden + onclick={openFlyout} + class="flex min-h-[44px] w-full flex-col items-center justify-center gap-0.5 border-l-[3px] py-3 transition-colors lg:hidden {isActive('groups') ? 'border-brand-mint bg-white/10' : 'border-transparent hover:bg-white/5'}" @@ -187,8 +203,8 @@ function handleKeydown(event: KeyboardEvent) { data-flyout-trigger type="button" aria-label={m.admin_tab_tags()} - onclick={() => (flyoutOpen = true)} - class="flex w-full flex-col items-center justify-center gap-0.5 border-l-[3px] py-3 transition-colors lg:hidden + onclick={openFlyout} + class="flex min-h-[44px] w-full flex-col items-center justify-center gap-0.5 border-l-[3px] py-3 transition-colors lg:hidden {isActive('tags') ? 'border-brand-mint bg-white/10' : 'border-transparent hover:bg-white/5'}" @@ -257,8 +273,8 @@ function handleKeydown(event: KeyboardEvent) { data-flyout-trigger type="button" aria-label={m.admin_tab_system()} - onclick={() => (flyoutOpen = true)} - class="flex w-full flex-col items-center justify-center gap-0.5 border-t border-l-[3px] border-white/10 py-3 transition-colors lg:hidden + onclick={openFlyout} + class="flex min-h-[44px] w-full flex-col items-center justify-center gap-0.5 border-t border-l-[3px] border-white/10 py-3 transition-colors lg:hidden {isActive('system') ? 'border-brand-mint bg-white/10' : 'border-l-transparent hover:bg-white/5'}" @@ -320,7 +336,7 @@ function handleKeydown(event: KeyboardEvent) { data-flyout-backdrop role="none" class="fixed inset-0 z-40 bg-black/40" - onclick={() => (flyoutOpen = false)} + onclick={closeFlyout} >
@@ -329,7 +345,7 @@ function handleKeydown(event: KeyboardEvent) { aria-modal="true" aria-label={m.admin_heading()} class="fixed top-0 left-12 z-50 flex h-full w-40 flex-col bg-brand-navy shadow-xl" - style="transform: translateX(0); transition: transform 180ms ease-out;" + transition:fly={{ x: -160, duration: 180 }} >
@@ -339,7 +355,7 @@ function handleKeydown(event: KeyboardEvent) { {#if canManageUsers} (flyoutOpen = false)} + onclick={closeFlyout} class="flex flex-col items-start justify-center gap-0.5 border-l-[3px] px-3.5 py-2.5 transition-colors {isActive('users') ? 'border-brand-mint bg-white/10' @@ -377,7 +393,7 @@ function handleKeydown(event: KeyboardEvent) { {#if canManageGroups} (flyoutOpen = false)} + onclick={closeFlyout} class="flex flex-col items-start justify-center gap-0.5 border-l-[3px] px-3.5 py-2.5 transition-colors {isActive('groups') ? 'border-brand-mint bg-white/10' @@ -415,7 +431,7 @@ function handleKeydown(event: KeyboardEvent) { {#if canManageTags} (flyoutOpen = false)} + onclick={closeFlyout} class="flex flex-col items-start justify-center gap-0.5 border-l-[3px] px-3.5 py-2.5 transition-colors {isActive('tags') ? 'border-brand-mint bg-white/10' @@ -454,7 +470,7 @@ function handleKeydown(event: KeyboardEvent) { {#if canRunMaintenance} (flyoutOpen = false)} + onclick={closeFlyout} class="flex flex-col items-start justify-center gap-0.5 border-t border-l-[3px] border-white/10 px-3.5 py-2.5 transition-colors {isActive('system') ? 'border-brand-mint bg-white/10' diff --git a/frontend/src/routes/admin/groups/GroupsListPanel.svelte b/frontend/src/routes/admin/groups/GroupsListPanel.svelte index fe967f82..233a6943 100644 --- a/frontend/src/routes/admin/groups/GroupsListPanel.svelte +++ b/frontend/src/routes/admin/groups/GroupsListPanel.svelte @@ -16,17 +16,15 @@ let { autocollapse?: boolean; } = $props(); -let isCollapsed = $state( - typeof localStorage !== 'undefined' && localStorage.getItem('admin_list_collapsed') === 'true' +let manualCollapse = $state( + typeof localStorage !== 'undefined' && + localStorage.getItem('admin_groups_list_collapsed') === 'true' ); - -$effect(() => { - if (autocollapse) isCollapsed = true; -}); +const isCollapsed = $derived(autocollapse || manualCollapse); $effect(() => { if (typeof localStorage !== 'undefined') { - localStorage.setItem('admin_list_collapsed', String(isCollapsed)); + localStorage.setItem('admin_groups_list_collapsed', String(manualCollapse)); } }); @@ -34,7 +32,7 @@ $effect(() => { {#if isCollapsed} +
+ + +
+ onapplyFilters()} + /> +
+
+ +
+ +
+ + onapplyFilters()} + class="block w-full border-line py-2.5 text-sm shadow-sm focus:border-ink focus:ring-ink" + /> +
+ + +
+ + onapplyFilters()} + class="block w-full border-line py-2.5 text-sm shadow-sm focus:border-ink focus:ring-ink" + /> +
+ + +
+ +
+
+

diff --git a/frontend/src/routes/korrespondenz/ConversationTimeline.svelte b/frontend/src/routes/korrespondenz/ConversationTimeline.svelte new file mode 100644 index 00000000..6fc8bc56 --- /dev/null +++ b/frontend/src/routes/korrespondenz/ConversationTimeline.svelte @@ -0,0 +1,164 @@ + + + + + + +
+ + + +
+
+ {#each enrichedDocuments as { doc, year, showYearDivider } (doc.id)} + {#if showYearDivider} +
+
+ {year} +
+
+ {/if} + {@const isRight = doc.sender?.id === senderId} + + + + {/each} +
+
+
diff --git a/frontend/src/routes/korrespondenz/page.svelte.spec.ts b/frontend/src/routes/korrespondenz/page.svelte.spec.ts new file mode 100644 index 00000000..85f18e63 --- /dev/null +++ b/frontend/src/routes/korrespondenz/page.svelte.spec.ts @@ -0,0 +1,164 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render } from 'vitest-browser-svelte'; +import { page } from 'vitest/browser'; +import Page from './+page.svelte'; + +vi.mock('$app/navigation', () => ({ goto: vi.fn() })); + +afterEach(cleanup); + +// ─── Test data ──────────────────────────────────────────────────────────────── + +const baseData = { + user: undefined, + canWrite: true, + canAnnotate: false, + documents: [], + initialValues: { senderName: '', receiverName: '' }, + filters: { senderId: '', receiverId: '', from: '', to: '', dir: 'DESC' as const } +}; + +const withPersons = { + ...baseData, + filters: { ...baseData.filters, senderId: 'p1', receiverId: 'p2' } +}; + +const makeDoc = (overrides: Record = {}) => ({ + id: 'd1', + title: 'Testbrief', + originalFilename: 'testbrief.pdf', + status: 'UPLOADED' as const, + documentDate: '1923-04-12', + location: 'Berlin', + sender: { id: 'p1', firstName: 'Hans', lastName: 'Müller' }, + receivers: [{ id: 'p2', firstName: 'Anna', lastName: 'Schmidt' }], + tags: [], + transcription: undefined, + filePath: undefined, + createdAt: '1923-04-12T00:00:00Z', + updatedAt: '1923-04-12T00:00:00Z', + ...overrides +}); + +const withDocs = { + ...withPersons, + documents: [makeDoc()] +}; + +// ─── Empty state ────────────────────────────────────────────────────────────── + +describe('Conversations page – empty state', () => { + it('shows the "select two persons" prompt when no persons are selected', async () => { + render(Page, { data: baseData }); + await expect.element(page.getByText(/Wählen Sie zwei Personen aus/i)).toBeInTheDocument(); + }); + + it('hides the swap button when no persons are selected', async () => { + render(Page, { data: baseData }); + // Button is always in the DOM (holds grid column width on desktop) but made invisible + await expect.element(page.getByTestId('conv-swap-btn')).toHaveClass('invisible'); + }); + + it('does not show the new document link when no persons are selected', async () => { + render(Page, { data: baseData }); + await expect.element(page.getByTestId('conv-new-doc-link')).not.toBeInTheDocument(); + }); +}); + +// ─── No results ─────────────────────────────────────────────────────────────── + +describe('Conversations page – no results', () => { + it('shows "no documents found" when both persons are selected but there are no documents', async () => { + render(Page, { data: withPersons }); + await expect.element(page.getByText(/Keine Dokumente gefunden/i)).toBeInTheDocument(); + }); +}); + +// ─── Swap button ────────────────────────────────────────────────────────────── + +describe('Conversations page – swap button', () => { + it('shows the swap button when both persons are selected', async () => { + render(Page, { data: withPersons }); + await expect.element(page.getByTestId('conv-swap-btn')).not.toHaveClass('invisible'); + }); + + it('calls goto with swapped sender and receiver when clicked', async () => { + const { goto } = await import('$app/navigation'); + vi.mocked(goto).mockClear(); + render(Page, { data: withPersons }); + document.querySelector('[data-testid="conv-swap-btn"]')!.click(); + expect(goto).toHaveBeenCalledWith(expect.stringContaining('senderId=p2'), expect.anything()); + expect(goto).toHaveBeenCalledWith(expect.stringContaining('receiverId=p1'), expect.anything()); + }); +}); + +// ─── Summary ────────────────────────────────────────────────────────────────── + +describe('Conversations page – summary', () => { + it('shows document count and year range when documents are loaded', async () => { + const data = { + ...withPersons, + documents: [ + makeDoc({ documentDate: '1923-04-12' }), + makeDoc({ id: 'd2', documentDate: '1965-08-03' }) + ] + }; + render(Page, { data }); + const summary = page.getByTestId('conv-summary'); + await expect.element(summary).toHaveTextContent('2'); + await expect.element(summary).toHaveTextContent('1923'); + await expect.element(summary).toHaveTextContent('1965'); + }); +}); + +// ─── Year dividers ──────────────────────────────────────────────────────────── + +describe('Conversations page – year dividers', () => { + it('renders a year divider for the first document', async () => { + render(Page, { data: withDocs }); + await expect.element(page.getByTestId('year-divider').first()).toHaveTextContent('1923'); + }); + + it('renders a divider for each new year in the document list', async () => { + const data = { + ...withPersons, + documents: [ + makeDoc({ documentDate: '1923-04-12' }), + makeDoc({ id: 'd2', documentDate: '1965-08-03' }) + ] + }; + render(Page, { data }); + await expect.element(page.getByTestId('year-divider').first()).toHaveTextContent('1923'); + await expect.element(page.getByTestId('year-divider').nth(1)).toHaveTextContent('1965'); + }); + + it('does not render a second divider for documents from the same year', async () => { + const data = { + ...withPersons, + documents: [ + makeDoc({ documentDate: '1923-04-12' }), + makeDoc({ id: 'd2', documentDate: '1923-09-01' }) + ] + }; + render(Page, { data }); + // Only one divider for 1923; 1965 divider should not appear + await expect.element(page.getByTestId('year-divider').first()).toHaveTextContent('1923'); + await expect.element(page.getByTestId('year-divider').nth(1)).not.toBeInTheDocument(); + }); +}); + +// ─── New document link ──────────────────────────────────────────────────────── + +describe('Conversations page – new document link', () => { + it('shows the link with correct href for a write user', async () => { + render(Page, { data: { ...withDocs, canWrite: true } }); + const link = page.getByTestId('conv-new-doc-link'); + await expect.element(link).toBeInTheDocument(); + await expect.element(link).toHaveAttribute('href', '/documents/new?senderId=p1&receiverId=p2'); + }); + + it('hides the link for a read-only user', async () => { + render(Page, { data: { ...withDocs, canWrite: false } }); + await expect.element(page.getByTestId('conv-new-doc-link')).not.toBeInTheDocument(); + }); +}); diff --git a/frontend/src/routes/persons/[id]/CoCorrespondentsList.svelte b/frontend/src/routes/persons/[id]/CoCorrespondentsList.svelte index fc0cc90b..b6f0b01d 100644 --- a/frontend/src/routes/persons/[id]/CoCorrespondentsList.svelte +++ b/frontend/src/routes/persons/[id]/CoCorrespondentsList.svelte @@ -30,7 +30,7 @@ function initials(name: string): string {
{#each coCorrespondents as c (c.id)} -- 2.49.1 From e94269907814610af91a903719d21815809cb67b Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 12:36:35 +0200 Subject: [PATCH 16/31] feat(frontend): single-person mode in +page.server.ts load function Loads documents whenever senderId is set, using the optional receiverId param to switch between single-person and bilateral query modes. Co-Authored-By: Claude Sonnet 4.6 --- frontend/src/routes/korrespondenz/+page.server.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/frontend/src/routes/korrespondenz/+page.server.ts b/frontend/src/routes/korrespondenz/+page.server.ts index 62786d44..e61b3e13 100644 --- a/frontend/src/routes/korrespondenz/+page.server.ts +++ b/frontend/src/routes/korrespondenz/+page.server.ts @@ -16,14 +16,14 @@ export async function load({ url, fetch }) { const requests: Promise[] = []; - if (senderId && receiverId) { + if (senderId) { requests.push( api .GET('/api/documents/conversation', { params: { query: { senderId, - receiverId, + receiverId: receiverId || undefined, dir, from: from || undefined, to: to || undefined @@ -34,9 +34,7 @@ export async function load({ url, fetch }) { documents = data ?? []; }) ); - } - if (senderId) { requests.push( api.GET('/api/persons/{id}', { params: { path: { id: senderId } } }).then(({ data }) => { const p = data as { firstName: string; lastName: string } | undefined; -- 2.49.1 From 48286b9f7730e0abffb491329e192da893b3539e Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 12:50:40 +0200 Subject: [PATCH 17/31] feat(frontend): new strip components, suggestions dropdown, empty state CorrespondenzPersonBar (Row 1), CorrespondenzFilterControls (Row 2 with live count + sort), CorrespondentSuggestionsDropdown (fetch-on-focus, keyboard nav), SinglePersonHintBar, CorrespondenzEmptyState (recent persons from localStorage). New i18n shim in messages-extra.ts until root-owned paraglide files can be regenerated. Co-Authored-By: Claude Sonnet 4.6 --- frontend/src/lib/messages-extra.ts | 37 +++++ .../CorrespondentSuggestionsDropdown.svelte | 129 +++++++++++++++++ .../CorrespondenzEmptyState.svelte | 121 ++++++++++++++++ .../CorrespondenzFilterControls.svelte | 135 ++++++++++++++++++ .../CorrespondenzPersonBar.svelte | 87 +++++++++++ .../korrespondenz/SinglePersonHintBar.svelte | 38 +++++ 6 files changed, 547 insertions(+) create mode 100644 frontend/src/lib/messages-extra.ts create mode 100644 frontend/src/routes/korrespondenz/CorrespondentSuggestionsDropdown.svelte create mode 100644 frontend/src/routes/korrespondenz/CorrespondenzEmptyState.svelte create mode 100644 frontend/src/routes/korrespondenz/CorrespondenzFilterControls.svelte create mode 100644 frontend/src/routes/korrespondenz/CorrespondenzPersonBar.svelte create mode 100644 frontend/src/routes/korrespondenz/SinglePersonHintBar.svelte diff --git a/frontend/src/lib/messages-extra.ts b/frontend/src/lib/messages-extra.ts new file mode 100644 index 00000000..799999b6 --- /dev/null +++ b/frontend/src/lib/messages-extra.ts @@ -0,0 +1,37 @@ +/** + * Extra message functions for i18n keys added after the last paraglide compile. + * + * TODO: Remove this file once the root-owned paraglide files in src/lib/paraglide/ + * are regenerated (run `npm run dev` or the paraglide compile step as the owning user). + * At that point, these functions will be generated into _index.js and the components + * that import from here should switch back to importing from $lib/paraglide/messages.js. + * + * Note: these fall back to German only — locale switching is handled by the generated + * paraglide files, not this shim. + */ + +// Svelte auto-escapes interpolated values — do not use {@html} with these strings. + +export const conv_hint_single_person = (inputs: { name: string }) => + `Alle Briefe von ${inputs.name} — wähle einen Korrespondenten oben um einzugrenzen`; + +export const conv_hint_single_person_filtered = (inputs: { + name: string; + from: string; + to: string; + sortLabel: string; +}) => `Alle Briefe von ${inputs.name} · ${inputs.from}–${inputs.to} · ${inputs.sortLabel}`; + +export const conv_strip_period = () => 'Zeitraum'; +export const conv_strip_from_placeholder = () => 'Von…'; +export const conv_strip_to_placeholder = () => 'Bis…'; +export const conv_strip_all_correspondents = () => 'Alle Korrespondenten'; +export const conv_strip_sort_newest = () => 'Neueste'; +export const conv_strip_sort_oldest = () => 'Älteste'; +export const conv_suggestions_heading = () => 'Häufigste Korrespondenten'; +export const conv_suggestions_all_label = (inputs: { name: string }) => + `Alle Korrespondenten von ${inputs.name}`; +export const conv_letters_count = (inputs: { count: number }) => `${inputs.count} Briefe`; +export const conv_empty_search_placeholder = () => 'Person suchen…'; +export const conv_empty_recent_label = () => 'Zuletzt geöffnet'; +export const conv_no_party = () => '—'; diff --git a/frontend/src/routes/korrespondenz/CorrespondentSuggestionsDropdown.svelte b/frontend/src/routes/korrespondenz/CorrespondentSuggestionsDropdown.svelte new file mode 100644 index 00000000..e304cb4c --- /dev/null +++ b/frontend/src/routes/korrespondenz/CorrespondentSuggestionsDropdown.svelte @@ -0,0 +1,129 @@ + + +
handleKeydown(e, e.currentTarget as HTMLElement)} +> + +
+ {conv_suggestions_heading()} +
+ + + {#if !loading} + {#each results as person (person.id)} +
onselect(person.id)} + onkeydown={(e) => e.key === 'Enter' && onselect(person.id)} + > + + + + {person.lastName}, {person.firstName} + +
+ {/each} + {/if} + + +
+ + +
onselect('')} + onkeydown={(e) => e.key === 'Enter' && onselect('')} + > + {conv_suggestions_all_label({ name: senderName })} +
+
diff --git a/frontend/src/routes/korrespondenz/CorrespondenzEmptyState.svelte b/frontend/src/routes/korrespondenz/CorrespondenzEmptyState.svelte new file mode 100644 index 00000000..0ff49bbf --- /dev/null +++ b/frontend/src/routes/korrespondenz/CorrespondenzEmptyState.svelte @@ -0,0 +1,121 @@ + + +
+ +
+ +
+ + +

Korrespondenz durchsuchen

+ + +

+ Wähle eine Person aus dem Archiv um deren Briefe zu sehen — mit oder ohne Korrespondent. +

+ + + + + +
+
+ oder +
+
+ + + {#if recentPersons.length > 0} +
+ + {conv_empty_recent_label()} + +
+ {#each recentPersons as person (person.id)} + + + {/each} +
+
+ {/if} +
diff --git a/frontend/src/routes/korrespondenz/CorrespondenzFilterControls.svelte b/frontend/src/routes/korrespondenz/CorrespondenzFilterControls.svelte new file mode 100644 index 00000000..08c9a5ac --- /dev/null +++ b/frontend/src/routes/korrespondenz/CorrespondenzFilterControls.svelte @@ -0,0 +1,135 @@ + + +
+ + + + + onapplyFilters()} + placeholder={conv_strip_from_placeholder()} + aria-label="Von" + class="h-[22px] min-h-[44px] w-[80px] rounded-[3px] border px-1 text-xs focus:outline-none sm:min-h-0" + class:border-[#002850]={!!fromDate} + class:text-[#333]={!!fromDate} + class:border-[#D1D5DB]={!fromDate} + class:text-[#AAA]={!fromDate} + class:italic={!fromDate} + /> + + + + + onapplyFilters()} + placeholder={conv_strip_to_placeholder()} + aria-label="Bis" + class="h-[22px] min-h-[44px] w-[80px] rounded-[3px] border px-1 text-xs focus:outline-none sm:min-h-0" + class:border-[#002850]={!!toDate} + class:text-[#333]={!!toDate} + class:border-[#D1D5DB]={!toDate} + class:text-[#AAA]={!toDate} + class:italic={!toDate} + /> + + + + {conv_letters_count({ count: documentCount ?? 0 })} + + + + +
diff --git a/frontend/src/routes/korrespondenz/CorrespondenzPersonBar.svelte b/frontend/src/routes/korrespondenz/CorrespondenzPersonBar.svelte new file mode 100644 index 00000000..1a3b22ba --- /dev/null +++ b/frontend/src/routes/korrespondenz/CorrespondenzPersonBar.svelte @@ -0,0 +1,87 @@ + + +
+ +
+ onapplyFilters()} + /> +
+ + + + + +
+ onapplyFilters()} + /> + {#if !receiverId} + + — optional + + {/if} +
+
diff --git a/frontend/src/routes/korrespondenz/SinglePersonHintBar.svelte b/frontend/src/routes/korrespondenz/SinglePersonHintBar.svelte new file mode 100644 index 00000000..9bb49308 --- /dev/null +++ b/frontend/src/routes/korrespondenz/SinglePersonHintBar.svelte @@ -0,0 +1,38 @@ + + +
+ + + {#if hasDateFilter} + {conv_hint_single_person_filtered({ + name: senderName, + from: fromDate ?? '', + to: toDate ?? '', + sortLabel + })} + {:else} + {conv_hint_single_person({ name: senderName })} + {/if} +
-- 2.49.1 From 3addc72693c8505711ec5f8cd2fd09487d34d988 Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 12:57:27 +0200 Subject: [PATCH 18/31] feat(korrespondenz): redesign ConversationTimeline to correspondence log cards Replace chat-bubble layout with compact log rows featuring direction arrows, colored left borders (navy = outbound, mint = inbound), year dividers with per-year counts, asymmetry bar for bilateral mode, single-person other-party label, and encodeURIComponent-based new-doc link. Co-Authored-By: Claude Sonnet 4.6 --- .../korrespondenz/ConversationTimeline.svelte | 280 +++++++++--------- 1 file changed, 147 insertions(+), 133 deletions(-) diff --git a/frontend/src/routes/korrespondenz/ConversationTimeline.svelte b/frontend/src/routes/korrespondenz/ConversationTimeline.svelte index 6fc8bc56..1eedcd68 100644 --- a/frontend/src/routes/korrespondenz/ConversationTimeline.svelte +++ b/frontend/src/routes/korrespondenz/ConversationTimeline.svelte @@ -1,13 +1,9 @@ - -
- - -
- +{#if isBilateral && documents.length > 0} - -
-
- {#each enrichedDocuments as { doc, year, showYearDivider } (doc.id)} - {#if showYearDivider} -
-
- {year} -
-
- {/if} - {@const isRight = doc.sender?.id === senderId} - - - - {/each} + class="flex flex-col gap-1 border-b border-[#E8E4DF] bg-[#F7F5F2] px-[18px] py-2" + role="img" + aria-label="Briefverteilung in diesem Zeitraum: {outCount} von {senderName ?? ''}, {inCount} von {receiverName ?? ''}" + > +
+ {outCount} von {senderName} → + {inCount} von {receiverName} ← +
+
+
+
+{/if} + +
+ {#each enrichedDocuments as { doc, year, showYearDivider, isOut } (doc.id)} + {#if showYearDivider && year !== null} +
+ {year} + {countsByYear.get(year) ?? 0} Briefe +
+ {/if} + + + + +
+
+ {doc.title || doc.originalFilename} +
+
+ {doc.documentDate ? formatDate(doc.documentDate) : '—'} + {#if doc.location} + · + {doc.location} + {/if} + {#if !receiverId} + · + {otherPartyName(doc)} + {/if} + +
+
+ + +
+ {/each} + + {#if canWrite} + + {/if}
-- 2.49.1 From 4f5f8255a1483835677ab4ccbcdf652402e100ea Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 12:59:33 +0200 Subject: [PATCH 19/31] feat(korrespondenz): wire up +page.svelte orchestrator with new components Compose CorrespondenzPersonBar, CorrespondenzFilterControls, SinglePersonHintBar, CorrespondenzEmptyState, and updated ConversationTimeline. Add localStorage recent-persons persistence on applyFilters, single-person mode gate, and canWrite derived from user groups in load function. Co-Authored-By: Claude Sonnet 4.6 --- .../src/routes/korrespondenz/+page.server.ts | 8 +- .../src/routes/korrespondenz/+page.svelte | 105 ++++++++++++------ 2 files changed, 80 insertions(+), 33 deletions(-) diff --git a/frontend/src/routes/korrespondenz/+page.server.ts b/frontend/src/routes/korrespondenz/+page.server.ts index e61b3e13..c32c1afc 100644 --- a/frontend/src/routes/korrespondenz/+page.server.ts +++ b/frontend/src/routes/korrespondenz/+page.server.ts @@ -1,13 +1,18 @@ import type { components } from '$lib/generated/api'; import { createApiClient } from '$lib/api.server'; -export async function load({ url, fetch }) { +export async function load({ url, fetch, locals }) { const senderId = url.searchParams.get('senderId') || ''; const receiverId = url.searchParams.get('receiverId') || ''; const from = url.searchParams.get('from') || ''; const to = url.searchParams.get('to') || ''; const dir = url.searchParams.get('dir') || 'DESC'; + const canWrite = + (locals.user as { groups?: { permissions: string[] }[] } | undefined)?.groups?.some((g) => + g.permissions.includes('WRITE_ALL') + ) ?? false; + const api = createApiClient(fetch); let documents: components['schemas']['Document'][] = []; @@ -56,6 +61,7 @@ export async function load({ url, fetch }) { return { documents, + canWrite, initialValues: { senderName, receiverName }, filters: { senderId, receiverId, from, to, dir } }; diff --git a/frontend/src/routes/korrespondenz/+page.svelte b/frontend/src/routes/korrespondenz/+page.svelte index f151d4b2..d29e442d 100644 --- a/frontend/src/routes/korrespondenz/+page.svelte +++ b/frontend/src/routes/korrespondenz/+page.svelte @@ -2,9 +2,12 @@ import { goto } from '$app/navigation'; import { untrack } from 'svelte'; import { SvelteURLSearchParams } from 'svelte/reactivity'; -import { m } from '$lib/paraglide/messages.js'; -import ConversationFilterBar from './ConversationFilterBar.svelte'; +import CorrespondenzPersonBar from './CorrespondenzPersonBar.svelte'; +import CorrespondenzFilterControls from './CorrespondenzFilterControls.svelte'; +import SinglePersonHintBar from './SinglePersonHintBar.svelte'; import ConversationTimeline from './ConversationTimeline.svelte'; +import CorrespondenzEmptyState from './CorrespondenzEmptyState.svelte'; +import { m } from '$lib/paraglide/messages.js'; let { data } = $props(); @@ -14,6 +17,10 @@ let fromDate = $state(untrack(() => data.filters.from)); let toDate = $state(untrack(() => data.filters.to)); let sortDir = $state(untrack(() => data.filters.dir)); +// Derived name states — kept as reactive copies so ConversationTimeline always has current names +let senderName = $state(untrack(() => data.initialValues.senderName)); +let receiverName = $state(untrack(() => data.initialValues.receiverName)); + // Sync with server data after navigation $effect(() => { senderId = data.filters.senderId; @@ -21,9 +28,32 @@ $effect(() => { fromDate = data.filters.from; toDate = data.filters.to; sortDir = data.filters.dir; + senderName = data.initialValues.senderName; + receiverName = data.initialValues.receiverName; }); +const isSinglePerson = $derived(!!senderId && !receiverId); + +const RECENT_STORAGE_KEY = 'korrespondenz_recent_persons'; +const MAX_RECENT = 5; + +function persistRecentPerson(id: string, name: string) { + if (!id) return; + try { + const raw = localStorage.getItem(RECENT_STORAGE_KEY); + const existing: { id: string; name: string }[] = raw ? JSON.parse(raw) : []; + const filtered = existing.filter((p) => p.id !== id); + const updated = [{ id, name }, ...filtered].slice(0, MAX_RECENT); + localStorage.setItem(RECENT_STORAGE_KEY, JSON.stringify(updated)); + } catch { + // localStorage unavailable — silently ignore + } +} + function applyFilters() { + // Persist to recent persons when a person is selected + if (senderId && senderName) persistRecentPerson(senderId, senderName); + const params = new SvelteURLSearchParams(); if (senderId) params.set('senderId', senderId); if (receiverId) params.set('receiverId', receiverId); @@ -44,54 +74,63 @@ function swapPersons() { receiverId = tmp; applyFilters(); } + +function selectPerson(id: string) { + senderId = id; + receiverId = ''; + applyFilters(); +} -
+
-
-

{m.conv_heading()}

-

+

+

{m.conv_heading()}

+

{m.conv_subtitle()}

- + - - {#if !senderId || !receiverId} -
-
- -
-

{m.conv_empty_heading()}

-

{m.conv_empty_text()}

-
+ + + + + {#if isSinglePerson} + + {/if} + + + {#if !senderId} + {:else if data.documents.length === 0}
-

{m.conv_no_results_heading()}

-

{m.conv_no_results_text()}

+

{m.conv_no_results_heading()}

+

{m.conv_no_results_text()}

{:else} {/if}
-- 2.49.1 From 1b95d9472bc2f23a05788b0c93261019e4bff14e Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 13:04:27 +0200 Subject: [PATCH 20/31] test(korrespondenz): update and expand Vitest component specs Update empty-state, swap-button, and new-doc-link tests to match redesigned components. Add new tests for: single-person hint bar visibility, recent-persons chips from localStorage, corrupt localStorage graceful handling, Row 2 aria-disabled state, and strip letter count in single-person and bilateral modes. Fix CorrespondenzEmptyState to use {id, name} storage format matching persistRecentPerson in +page.svelte. Co-Authored-By: Claude Sonnet 4.6 --- .../CorrespondenzEmptyState.svelte | 7 +- .../routes/korrespondenz/page.svelte.spec.ts | 151 +++++++++++++----- 2 files changed, 116 insertions(+), 42 deletions(-) diff --git a/frontend/src/routes/korrespondenz/CorrespondenzEmptyState.svelte b/frontend/src/routes/korrespondenz/CorrespondenzEmptyState.svelte index 0ff49bbf..9dae76ee 100644 --- a/frontend/src/routes/korrespondenz/CorrespondenzEmptyState.svelte +++ b/frontend/src/routes/korrespondenz/CorrespondenzEmptyState.svelte @@ -4,8 +4,7 @@ import { conv_empty_search_placeholder, conv_empty_recent_label } from '$lib/mes interface RecentPerson { id: string; - firstName: string; - lastName: string; + name: string; } interface Props { @@ -110,9 +109,9 @@ onMount(() => { class="flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-[#002850] text-[10px] text-white" aria-hidden="true" > - {person.firstName[0]}{person.lastName[0]} + {person.name.charAt(0).toUpperCase()} - {person.firstName} + {person.name} {/each}
diff --git a/frontend/src/routes/korrespondenz/page.svelte.spec.ts b/frontend/src/routes/korrespondenz/page.svelte.spec.ts index 85f18e63..b4e4ca7e 100644 --- a/frontend/src/routes/korrespondenz/page.svelte.spec.ts +++ b/frontend/src/routes/korrespondenz/page.svelte.spec.ts @@ -18,8 +18,15 @@ const baseData = { filters: { senderId: '', receiverId: '', from: '', to: '', dir: 'DESC' as const } }; +const withSender = { + ...baseData, + initialValues: { senderName: 'Hans Müller', receiverName: '' }, + filters: { ...baseData.filters, senderId: 'p1' } +}; + const withPersons = { ...baseData, + initialValues: { senderName: 'Hans Müller', receiverName: 'Anna Schmidt' }, filters: { ...baseData.filters, senderId: 'p1', receiverId: 'p2' } }; @@ -45,41 +52,120 @@ const withDocs = { documents: [makeDoc()] }; -// ─── Empty state ────────────────────────────────────────────────────────────── +// ─── Empty state (no senderId) ──────────────────────────────────────────────── -describe('Conversations page – empty state', () => { - it('shows the "select two persons" prompt when no persons are selected', async () => { +describe('Korrespondenz page – empty state', () => { + it('shows the search heading when no person is selected', async () => { render(Page, { data: baseData }); - await expect.element(page.getByText(/Wählen Sie zwei Personen aus/i)).toBeInTheDocument(); + await expect.element(page.getByText(/Korrespondenz durchsuchen/i)).toBeInTheDocument(); }); - it('hides the swap button when no persons are selected', async () => { + it('shows the empty-search button', async () => { render(Page, { data: baseData }); - // Button is always in the DOM (holds grid column width on desktop) but made invisible - await expect.element(page.getByTestId('conv-swap-btn')).toHaveClass('invisible'); + await expect.element(page.getByTestId('conv-empty-search')).toBeInTheDocument(); }); - it('does not show the new document link when no persons are selected', async () => { + it('does not show the new document link when no person is selected', async () => { render(Page, { data: baseData }); await expect.element(page.getByTestId('conv-new-doc-link')).not.toBeInTheDocument(); }); + + it('does not show a year divider when no person is selected', async () => { + render(Page, { data: baseData }); + await expect.element(page.getByTestId('year-divider')).not.toBeInTheDocument(); + }); +}); + +// ─── Recent persons chips ───────────────────────────────────────────────────── + +describe('Korrespondenz page – recent persons', () => { + it('shows recent person chips from localStorage', async () => { + localStorage.setItem( + 'korrespondenz_recent_persons', + JSON.stringify([{ id: 'r1', name: 'Clara Braun' }]) + ); + render(Page, { data: baseData }); + await expect.element(page.getByText('Clara Braun')).toBeInTheDocument(); + localStorage.removeItem('korrespondenz_recent_persons'); + }); + + it('does not crash when localStorage contains corrupt JSON', async () => { + localStorage.setItem('korrespondenz_recent_persons', '}{not valid json'); + render(Page, { data: baseData }); + // Empty state heading is still shown — no chip list crash + await expect.element(page.getByText(/Korrespondenz durchsuchen/i)).toBeInTheDocument(); + localStorage.removeItem('korrespondenz_recent_persons'); + }); +}); + +// ─── Single-person hint bar ─────────────────────────────────────────────────── + +describe('Korrespondenz page – single-person hint bar', () => { + it('shows hint bar when only senderId is set', async () => { + render(Page, { data: withSender }); + await expect.element(page.getByText(/Alle Briefe von Hans Müller/i)).toBeInTheDocument(); + }); + + it('does not show hint bar when both persons are set', async () => { + render(Page, { data: { ...withPersons, documents: [makeDoc()] } }); + await expect.element(page.getByText(/Alle Briefe von Hans Müller/i)).not.toBeInTheDocument(); + }); + + it('does not show hint bar when no person is set', async () => { + render(Page, { data: baseData }); + await expect.element(page.getByText(/Alle Briefe von/i)).not.toBeInTheDocument(); + }); +}); + +// ─── Filter controls disabled state ────────────────────────────────────────── + +describe('Korrespondenz page – filter strip Row 2 disabled state', () => { + it('renders filter controls with aria-disabled when no senderId', async () => { + render(Page, { data: baseData }); + const strip = document.querySelector('[aria-disabled="true"]'); + expect(strip).not.toBeNull(); + }); +}); + +// ─── Strip letter count ─────────────────────────────────────────────────────── + +describe('Korrespondenz page – strip letter count', () => { + it('shows 0 Briefe when senderId is set but no documents', async () => { + render(Page, { data: withSender }); + await expect.element(page.getByTestId('conv-strip-count')).toHaveTextContent('0 Briefe'); + }); + + it('shows correct count when documents are loaded', async () => { + render(Page, { data: { ...withPersons, documents: [makeDoc()] } }); + await expect.element(page.getByTestId('conv-strip-count')).toHaveTextContent('1 Briefe'); + }); }); // ─── No results ─────────────────────────────────────────────────────────────── -describe('Conversations page – no results', () => { - it('shows "no documents found" when both persons are selected but there are no documents', async () => { - render(Page, { data: withPersons }); +describe('Korrespondenz page – no results', () => { + it('shows "no documents found" when a person is selected but there are no documents', async () => { + render(Page, { data: withSender }); await expect.element(page.getByText(/Keine Dokumente gefunden/i)).toBeInTheDocument(); }); }); // ─── Swap button ────────────────────────────────────────────────────────────── -describe('Conversations page – swap button', () => { - it('shows the swap button when both persons are selected', async () => { +describe('Korrespondenz page – swap button', () => { + it('swap button is invisible when only one person is set', async () => { + render(Page, { data: withSender }); + const btn = document.querySelector('[data-testid="conv-swap-btn"]'); + expect(btn).not.toBeNull(); + // opacity-0 is applied via class when swapVisible is false + expect(btn!.className).toMatch(/opacity-0/); + }); + + it('swap button is visible when both persons are set', async () => { render(Page, { data: withPersons }); - await expect.element(page.getByTestId('conv-swap-btn')).not.toHaveClass('invisible'); + const btn = document.querySelector('[data-testid="conv-swap-btn"]'); + expect(btn).not.toBeNull(); + expect(btn!.className).not.toMatch(/opacity-0/); }); it('calls goto with swapped sender and receiver when clicked', async () => { @@ -92,28 +178,9 @@ describe('Conversations page – swap button', () => { }); }); -// ─── Summary ────────────────────────────────────────────────────────────────── - -describe('Conversations page – summary', () => { - it('shows document count and year range when documents are loaded', async () => { - const data = { - ...withPersons, - documents: [ - makeDoc({ documentDate: '1923-04-12' }), - makeDoc({ id: 'd2', documentDate: '1965-08-03' }) - ] - }; - render(Page, { data }); - const summary = page.getByTestId('conv-summary'); - await expect.element(summary).toHaveTextContent('2'); - await expect.element(summary).toHaveTextContent('1923'); - await expect.element(summary).toHaveTextContent('1965'); - }); -}); - // ─── Year dividers ──────────────────────────────────────────────────────────── -describe('Conversations page – year dividers', () => { +describe('Korrespondenz page – year dividers', () => { it('renders a year divider for the first document', async () => { render(Page, { data: withDocs }); await expect.element(page.getByTestId('year-divider').first()).toHaveTextContent('1923'); @@ -141,7 +208,6 @@ describe('Conversations page – year dividers', () => { ] }; render(Page, { data }); - // Only one divider for 1923; 1965 divider should not appear await expect.element(page.getByTestId('year-divider').first()).toHaveTextContent('1923'); await expect.element(page.getByTestId('year-divider').nth(1)).not.toBeInTheDocument(); }); @@ -149,12 +215,21 @@ describe('Conversations page – year dividers', () => { // ─── New document link ──────────────────────────────────────────────────────── -describe('Conversations page – new document link', () => { - it('shows the link with correct href for a write user', async () => { +describe('Korrespondenz page – new document link', () => { + it('shows the link with correct href for a write user (bilateral)', async () => { render(Page, { data: { ...withDocs, canWrite: true } }); const link = page.getByTestId('conv-new-doc-link'); await expect.element(link).toBeInTheDocument(); - await expect.element(link).toHaveAttribute('href', '/documents/new?senderId=p1&receiverId=p2'); + await expect.element(link).toHaveAttribute('href', expect.stringContaining('senderId=p1')); + await expect.element(link).toHaveAttribute('href', expect.stringContaining('receiverId=p2')); + }); + + it('shows the link with correct href for single-person mode', async () => { + render(Page, { data: { ...withSender, documents: [makeDoc()], canWrite: true } }); + const link = page.getByTestId('conv-new-doc-link'); + await expect.element(link).toBeInTheDocument(); + await expect.element(link).toHaveAttribute('href', expect.stringContaining('senderId=p1')); + await expect.element(link).not.toHaveAttribute('href', expect.stringContaining('receiverId')); }); it('hides the link for a read-only user', async () => { -- 2.49.1 From 49f6b0a8c7695510562dbe8cdd8320513e1a8d8a Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 13:06:14 +0200 Subject: [PATCH 21/31] test(korrespondenz): add Playwright E2E happy-path journey Cover: empty state loads with search heading, nav link goes to /korrespondenz, single-person mode shows hint bar, sort toggle updates dir param, bilateral mode skips gracefully when no co-correspondents exist, swap button reflects swapped IDs in URL. Co-Authored-By: Claude Sonnet 4.6 --- frontend/e2e/korrespondenz.spec.ts | 114 +++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 frontend/e2e/korrespondenz.spec.ts diff --git a/frontend/e2e/korrespondenz.spec.ts b/frontend/e2e/korrespondenz.spec.ts new file mode 100644 index 00000000..225847cd --- /dev/null +++ b/frontend/e2e/korrespondenz.spec.ts @@ -0,0 +1,114 @@ +import { test, expect } from '@playwright/test'; + +test.describe('Korrespondenz – empty state', () => { + test('shows the search heading when no person is selected', async ({ page }) => { + await page.goto('/korrespondenz'); + await expect(page.getByText(/Korrespondenz durchsuchen/i)).toBeVisible(); + await page.screenshot({ path: 'test-results/e2e/korrespondenz-empty.png' }); + }); + + test('nav link goes to /korrespondenz', async ({ page }) => { + await page.goto('/'); + // Click the nav link (desktop text or mobile icon) + const navLink = page.getByRole('link', { name: /Korrespondenz/i }).first(); + await navLink.click(); + await expect(page).toHaveURL(/\/korrespondenz/); + }); +}); + +test.describe('Korrespondenz – single-person mode', () => { + test('shows hint bar and documents when navigated with senderId', async ({ page }) => { + // Get a real person ID from the persons list + await page.goto('/persons'); + const firstPersonLink = page.locator('a[href^="/persons/"]').first(); + await firstPersonLink.click(); + await page.waitForURL(/\/persons\/.+/); + + // Extract the person ID from the URL + const personId = page.url().split('/persons/')[1].split('?')[0]; + + // Navigate to korrespondenz in single-person mode + await page.goto(`/korrespondenz?senderId=${personId}`); + + // Hint bar should be visible + await expect(page.getByText(/Alle Briefe von/i)).toBeVisible(); + + // Filter controls should be active (not dimmed) + const filterStrip = page.locator('[aria-disabled="false"]').first(); + await expect(filterStrip).toBeAttached(); + + await page.screenshot({ path: 'test-results/e2e/korrespondenz-single-person.png' }); + }); + + test('sort toggle changes URL direction param', async ({ page }) => { + await page.goto('/persons'); + const firstPersonLink = page.locator('a[href^="/persons/"]').first(); + await firstPersonLink.click(); + await page.waitForURL(/\/persons\/.+/); + const personId = page.url().split('/persons/')[1].split('?')[0]; + + await page.goto(`/korrespondenz?senderId=${personId}&dir=DESC`); + await page.getByTestId('conv-sort-btn').click(); + + await expect(page).toHaveURL(/dir=ASC/); + await page.screenshot({ path: 'test-results/e2e/korrespondenz-sort-asc.png' }); + }); +}); + +test.describe('Korrespondenz – bilateral mode', () => { + test('shows asymmetry bar when both persons have shared documents', async ({ page }) => { + // Navigate to a person then follow a co-correspondent suggestion if available + await page.goto('/persons'); + const firstPersonLink = page.locator('a[href^="/persons/"]').first(); + await firstPersonLink.click(); + await page.waitForURL(/\/persons\/.+/); + const senderId = page.url().split('/persons/')[1].split('?')[0]; + + // Try to find a co-correspondent link from the person detail page + const corrLink = page + .locator('a[href*="/korrespondenz?senderId="][href*="receiverId="]') + .first(); + if (await corrLink.isVisible({ timeout: 2000 }).catch(() => false)) { + await corrLink.click(); + await page.waitForURL(/\/korrespondenz\?.*receiverId=/); + + // Hint bar should NOT be shown in bilateral mode + await expect(page.getByText(/Alle Briefe von/i)).not.toBeVisible(); + + await page.screenshot({ path: 'test-results/e2e/korrespondenz-bilateral.png' }); + } else { + // No bilateral data available for this person — skip with a note + test.skip(true, `No bilateral correspondent links found for person ${senderId}`); + } + }); + + test('swap button swaps sender and receiver in URL', async ({ page }) => { + await page.goto('/persons'); + const firstPersonLink = page.locator('a[href^="/persons/"]').first(); + await firstPersonLink.click(); + await page.waitForURL(/\/persons\/.+/); + const senderId = page.url().split('/persons/')[1].split('?')[0]; + + const corrLink = page + .locator('a[href*="/korrespondenz?senderId="][href*="receiverId="]') + .first(); + if (await corrLink.isVisible({ timeout: 2000 }).catch(() => false)) { + const href = await corrLink.getAttribute('href'); + await corrLink.click(); + await page.waitForURL(/\/korrespondenz\?.*receiverId=/); + + // Extract original receiverId from the href + const url = new URL(href!, 'http://x'); + const originalReceiverId = url.searchParams.get('receiverId')!; + + // Click swap + await page.getByTestId('conv-swap-btn').click(); + + // After swap the former receiver is now senderId + await expect(page).toHaveURL(new RegExp(`senderId=${originalReceiverId}`)); + await page.screenshot({ path: 'test-results/e2e/korrespondenz-swapped.png' }); + } else { + test.skip(true, `No bilateral correspondent links found for person ${senderId}`); + } + }); +}); -- 2.49.1 From 0387e9f428df468ad043d114fad892c18efebde6 Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 13:57:00 +0200 Subject: [PATCH 22/31] fix(korrespondenz): address 10 visual and functional regressions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Strip full-bleed: remove max-w container, put strips at page level - Remove page heading/subtitle above strip (not in spec) - Swap button always visible (drop opacity-0, keep pointer-events-none) - Korrespondent placeholder "Alle Korrespondenten" + label "— optional" - Add placeholder prop to PersonTypeahead; add onfocused callback prop - "Person suchen" button now focuses #senderId-search instead of no-op navigate - Wire CorrespondentSuggestionsDropdown on correspondent field focus - Hint bar: bold name via , year-only dates (no ISO strings) - Asymmetry bar: use first name only to prevent label overflow Co-Authored-By: Claude Sonnet 4.6 --- .../src/lib/components/PersonTypeahead.svelte | 9 ++- .../src/routes/korrespondenz/+page.svelte | 72 +++++++++---------- .../korrespondenz/ConversationTimeline.svelte | 7 +- .../CorrespondenzPersonBar.svelte | 36 +++++++--- .../korrespondenz/SinglePersonHintBar.svelte | 23 +++--- 5 files changed, 83 insertions(+), 64 deletions(-) diff --git a/frontend/src/lib/components/PersonTypeahead.svelte b/frontend/src/lib/components/PersonTypeahead.svelte index 5196108a..dfd4051f 100644 --- a/frontend/src/lib/components/PersonTypeahead.svelte +++ b/frontend/src/lib/components/PersonTypeahead.svelte @@ -10,8 +10,10 @@ interface Props { value?: string; initialName?: string; suggestedName?: string; + placeholder?: string; restrictToCorrespondentsOf?: string; onchange?: (value: string) => void; + onfocused?: () => void; } let { @@ -20,8 +22,10 @@ let { value = $bindable(''), initialName = '', suggestedName = '', + placeholder, restrictToCorrespondentsOf, - onchange + onchange, + onfocused }: Props = $props(); let searchTerm = $state(initialName); @@ -79,6 +83,7 @@ function handleInput() { } function handleFocus() { + onfocused?.(); showDropdown = true; if (restrictToCorrespondentsOf) { const personId = untrack(() => restrictToCorrespondentsOf)!; @@ -131,7 +136,7 @@ function clickOutside(node: HTMLElement) { bind:value={searchTerm} oninput={handleInput} onfocus={handleFocus} - placeholder={m.comp_typeahead_placeholder()} + placeholder={placeholder ?? m.comp_typeahead_placeholder()} class="mt-1 block w-full rounded-md border border-line p-2 shadow-sm focus:border-accent focus:ring-accent" /> diff --git a/frontend/src/routes/korrespondenz/+page.svelte b/frontend/src/routes/korrespondenz/+page.svelte index d29e442d..3b06de06 100644 --- a/frontend/src/routes/korrespondenz/+page.svelte +++ b/frontend/src/routes/korrespondenz/+page.svelte @@ -76,53 +76,49 @@ function swapPersons() { } function selectPerson(id: string) { + if (!id) { + document.querySelector('#senderId-search')?.focus(); + return; + } senderId = id; receiverId = ''; applyFilters(); } -
- -
-

{m.conv_heading()}

-

- {m.conv_subtitle()} -

-
+ + - - + + + +{#if isSinglePerson} + +{/if} - - - - - {#if isSinglePerson} - - {/if} - - + +
{#if !senderId} {:else if data.documents.length === 0} diff --git a/frontend/src/routes/korrespondenz/ConversationTimeline.svelte b/frontend/src/routes/korrespondenz/ConversationTimeline.svelte index 1eedcd68..cf52312f 100644 --- a/frontend/src/routes/korrespondenz/ConversationTimeline.svelte +++ b/frontend/src/routes/korrespondenz/ConversationTimeline.svelte @@ -51,6 +51,9 @@ const outPct = $derived(documents.length > 0 ? (outCount / documents.length) * 1 const isBilateral = $derived(!!senderId && !!receiverId); +const shortSenderName = $derived(senderName?.split(' ')[0] ?? senderName ?? ''); +const shortReceiverName = $derived(receiverName?.split(' ')[0] ?? receiverName ?? ''); + function statusDotClass(status: string): string { const map: Record = { PLACEHOLDER: 'bg-yellow-400', @@ -82,8 +85,8 @@ const newDocUrl = $derived( aria-label="Briefverteilung in diesem Zeitraum: {outCount} von {senderName ?? ''}, {inCount} von {receiverName ?? ''}" >
- {outCount} von {senderName} → - {inCount} von {receiverName} ← + {outCount} von {shortSenderName} → + {inCount} von {shortReceiverName} ←
diff --git a/frontend/src/routes/korrespondenz/CorrespondenzPersonBar.svelte b/frontend/src/routes/korrespondenz/CorrespondenzPersonBar.svelte index 1a3b22ba..ada7d11f 100644 --- a/frontend/src/routes/korrespondenz/CorrespondenzPersonBar.svelte +++ b/frontend/src/routes/korrespondenz/CorrespondenzPersonBar.svelte @@ -1,5 +1,6 @@
@@ -42,7 +55,6 @@ let swapVisible = $derived(!!(senderId && receiverId)); aria-label="Personen tauschen" onclick={onswapPersons} class="mb-1 flex h-7 w-7 shrink-0 items-center justify-center rounded border border-[#D1D5DB] bg-white text-[#888] transition-colors hover:border-[#002850] hover:text-[#002850]" - class:opacity-0={!swapVisible} class:pointer-events-none={!swapVisible} tabindex={swapVisible ? 0 : -1} > @@ -65,23 +77,31 @@ let swapVisible = $derived(!!(senderId && receiverId));
onapplyFilters()} + onchange={() => { + showSuggestions = false; + onapplyFilters(); + }} + onfocused={handleCorrespondentFocused} /> - {#if !receiverId} - - — optional - + {#if showSuggestions && senderId && !receiverId} + (showSuggestions = false)} + /> {/if}
diff --git a/frontend/src/routes/korrespondenz/SinglePersonHintBar.svelte b/frontend/src/routes/korrespondenz/SinglePersonHintBar.svelte index 9bb49308..e643e7eb 100644 --- a/frontend/src/routes/korrespondenz/SinglePersonHintBar.svelte +++ b/frontend/src/routes/korrespondenz/SinglePersonHintBar.svelte @@ -1,10 +1,5 @@ -- 2.49.1 From 5fd7e41492fd0150a00710e43e55e5251df4cb58 Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 14:33:23 +0200 Subject: [PATCH 23/31] fix(korrespondenz): dark theme, compact strip labels, year divider size, chevron alignment - Add compact prop to PersonTypeahead: 7px uppercase label, 30px h input (matches spec FL/FI) - Replace all hardcoded hex in 6 korrespondenz components with theme tokens (bg-surface, bg-muted, bg-canvas, border-line, text-ink, text-primary, text-accent, etc.) - Fix year divider: text-[15px] font-black (spec: 15px/900) - Fix log row chevron: items-center instead of items-start for vertical centering - Fix recent-persons persistence: move persistRecentPerson to post-navigation $effect so senderName is resolved from server before stored in localStorage - Add metadataComplete field to makeDoc() fixture to satisfy updated Document type - Restore opacity-0 on swap button when only one person is set (matches spec + test) Co-Authored-By: Claude Sonnet 4.6 --- .../src/lib/components/PersonTypeahead.svelte | 14 +++++- .../src/routes/korrespondenz/+page.svelte | 8 ++-- .../korrespondenz/ConversationTimeline.svelte | 46 +++++++++---------- .../CorrespondentSuggestionsDropdown.svelte | 13 +++--- .../CorrespondenzEmptyState.svelte | 22 ++++----- .../CorrespondenzFilterControls.svelte | 40 +++++++--------- .../CorrespondenzPersonBar.svelte | 9 ++-- .../routes/korrespondenz/page.svelte.spec.ts | 1 + 8 files changed, 80 insertions(+), 73 deletions(-) diff --git a/frontend/src/lib/components/PersonTypeahead.svelte b/frontend/src/lib/components/PersonTypeahead.svelte index dfd4051f..befe47d6 100644 --- a/frontend/src/lib/components/PersonTypeahead.svelte +++ b/frontend/src/lib/components/PersonTypeahead.svelte @@ -11,6 +11,7 @@ interface Props { initialName?: string; suggestedName?: string; placeholder?: string; + compact?: boolean; restrictToCorrespondentsOf?: string; onchange?: (value: string) => void; onfocused?: () => void; @@ -23,6 +24,7 @@ let { initialName = '', suggestedName = '', placeholder, + compact = false, restrictToCorrespondentsOf, onchange, onfocused @@ -125,7 +127,13 @@ function clickOutside(node: HTMLElement) {
- + @@ -137,7 +145,9 @@ function clickOutside(node: HTMLElement) { oninput={handleInput} onfocus={handleFocus} placeholder={placeholder ?? m.comp_typeahead_placeholder()} - class="mt-1 block w-full rounded-md border border-line p-2 shadow-sm focus:border-accent focus:ring-accent" + class={compact + ? 'block h-[30px] w-full rounded-[3px] border-[1.5px] border-line bg-surface px-[7px] text-[9px] text-ink placeholder:text-ink-3 focus:border-primary focus:outline-none' + : 'mt-1 block w-full rounded-md border border-line bg-surface p-2 text-ink shadow-sm placeholder:text-ink-3 focus:border-accent focus:ring-accent'} /> {#if showDropdown && (results.length > 0 || loading)} diff --git a/frontend/src/routes/korrespondenz/+page.svelte b/frontend/src/routes/korrespondenz/+page.svelte index 3b06de06..70142ed5 100644 --- a/frontend/src/routes/korrespondenz/+page.svelte +++ b/frontend/src/routes/korrespondenz/+page.svelte @@ -21,7 +21,7 @@ let sortDir = $state(untrack(() => data.filters.dir)); let senderName = $state(untrack(() => data.initialValues.senderName)); let receiverName = $state(untrack(() => data.initialValues.receiverName)); -// Sync with server data after navigation +// Sync with server data after navigation; persist recent persons once the name is resolved $effect(() => { senderId = data.filters.senderId; receiverId = data.filters.receiverId; @@ -30,6 +30,9 @@ $effect(() => { sortDir = data.filters.dir; senderName = data.initialValues.senderName; receiverName = data.initialValues.receiverName; + if (data.filters.senderId && data.initialValues.senderName) { + persistRecentPerson(data.filters.senderId, data.initialValues.senderName); + } }); const isSinglePerson = $derived(!!senderId && !receiverId); @@ -51,9 +54,6 @@ function persistRecentPerson(id: string, name: string) { } function applyFilters() { - // Persist to recent persons when a person is selected - if (senderId && senderName) persistRecentPerson(senderId, senderName); - const params = new SvelteURLSearchParams(); if (senderId) params.set('senderId', senderId); if (receiverId) params.set('receiverId', receiverId); diff --git a/frontend/src/routes/korrespondenz/ConversationTimeline.svelte b/frontend/src/routes/korrespondenz/ConversationTimeline.svelte index cf52312f..cddbfcf0 100644 --- a/frontend/src/routes/korrespondenz/ConversationTimeline.svelte +++ b/frontend/src/routes/korrespondenz/ConversationTimeline.svelte @@ -80,30 +80,30 @@ const newDocUrl = $derived( {#if isBilateral && documents.length > 0}