From 8fc360a5961ad49270a28c10ed025676809fdb84 Mon Sep 17 00:00:00 2001 From: Marcel Date: Mon, 30 Mar 2026 01:09:40 +0200 Subject: [PATCH 01/11] 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/11] 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/11] 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/11] 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/11] =?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/11] =?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/11] 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/11] 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