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..c344e8e3 100644 --- a/frontend/messages/de.json +++ b/frontend/messages/de.json @@ -155,6 +155,14 @@ "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_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", @@ -167,6 +175,21 @@ "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_btn_new_group": "Neue Gruppe", + "admin_groups_list_title": "Alle Gruppen", + "admin_groups_empty": "Keine Gruppen vorhanden.", + "admin_groups_select_prompt": "W\u00e4hle eine Gruppe aus der Liste.", + "admin_groups_permission_count": "{count} Berechtigungen", + "admin_group_new_heading": "Neue Gruppe anlegen", + "admin_group_edit_heading": "Gruppe: {name}", + "admin_group_updated": "Gruppe gespeichert.", + "admin_group_created": "Gruppe erstellt.", + "admin_groups_section_standard": "Standard", + "admin_groups_section_administrative": "Administrativ", "admin_user_new_heading": "Neuen Benutzer anlegen", "admin_user_edit_heading": "Benutzer bearbeiten: {username}", "admin_user_created": "Benutzer wurde erstellt.", @@ -250,6 +273,14 @@ "admin_system_backfill_hashes_description": "Berechnet den SHA-256-Hash für alle bereits hochgeladenen Dokumente, die noch keinen Hash haben. Dadurch werden Annotationen korrekt mit ihrer Dateiversion verknüpft und wieder angezeigt.", "admin_system_backfill_hashes_btn": "Datei-Hashes berechnen", "admin_system_backfill_hashes_success": "{count} Dokumente wurden aktualisiert.", + "admin_system_import_heading": "Massenimport", + "admin_system_import_description": "Importiert Dokumente und Metadaten aus der Importdatei im /import-Verzeichnis.", + "admin_system_import_btn_start": "Import starten", + "admin_system_import_btn_retry": "Erneut starten", + "admin_system_import_status_idle": "Kein Import gestartet.", + "admin_system_import_status_running": "Import läuft…", + "admin_system_import_status_done": "Import abgeschlossen – {count} Dokumente verarbeitet.", + "admin_system_import_status_failed": "Fehler: {message}", "comp_expandable_show_more": "Mehr anzeigen", "comp_expandable_show_less": "Weniger anzeigen", "error_comment_not_found": "Der Kommentar wurde nicht gefunden.", diff --git a/frontend/messages/en.json b/frontend/messages/en.json index 527a4f48..7bb2a116 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -155,6 +155,14 @@ "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_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", @@ -167,6 +175,21 @@ "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_btn_new_group": "New Group", + "admin_groups_list_title": "All Groups", + "admin_groups_empty": "No groups found.", + "admin_groups_select_prompt": "Select a group from the list.", + "admin_groups_permission_count": "{count} permissions", + "admin_group_new_heading": "Create new group", + "admin_group_edit_heading": "Group: {name}", + "admin_group_updated": "Group saved.", + "admin_group_created": "Group created.", + "admin_groups_section_standard": "Standard", + "admin_groups_section_administrative": "Administrative", "admin_user_new_heading": "Create new user", "admin_user_edit_heading": "Edit user: {username}", "admin_user_created": "User has been created.", @@ -250,6 +273,14 @@ "admin_system_backfill_hashes_description": "Computes the SHA-256 hash for all previously uploaded documents that do not have one yet. This ensures annotations are correctly linked to their file version and shown again.", "admin_system_backfill_hashes_btn": "Compute file hashes", "admin_system_backfill_hashes_success": "{count} documents were updated.", + "admin_system_import_heading": "Mass import", + "admin_system_import_description": "Imports documents and metadata from the spreadsheet file in the /import directory.", + "admin_system_import_btn_start": "Start import", + "admin_system_import_btn_retry": "Start again", + "admin_system_import_status_idle": "No import started.", + "admin_system_import_status_running": "Import running…", + "admin_system_import_status_done": "Import complete – {count} documents processed.", + "admin_system_import_status_failed": "Error: {message}", "comp_expandable_show_more": "Show more", "comp_expandable_show_less": "Show less", "error_comment_not_found": "The comment could not be found.", diff --git a/frontend/messages/es.json b/frontend/messages/es.json index 3d72309e..0f9d93d4 100644 --- a/frontend/messages/es.json +++ b/frontend/messages/es.json @@ -155,6 +155,14 @@ "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_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", @@ -167,6 +175,21 @@ "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_btn_new_group": "Nuevo grupo", + "admin_groups_list_title": "Todos los grupos", + "admin_groups_empty": "No hay grupos.", + "admin_groups_select_prompt": "Selecciona un grupo de la lista.", + "admin_groups_permission_count": "{count} permisos", + "admin_group_new_heading": "Crear nuevo grupo", + "admin_group_edit_heading": "Grupo: {name}", + "admin_group_updated": "Grupo guardado.", + "admin_group_created": "Grupo creado.", + "admin_groups_section_standard": "Est\u00e1ndar", + "admin_groups_section_administrative": "Administrativo", "admin_user_new_heading": "Crear nuevo usuario", "admin_user_edit_heading": "Editar usuario: {username}", "admin_user_created": "Usuario creado.", @@ -250,6 +273,14 @@ "admin_system_backfill_hashes_description": "Calcula el hash SHA-256 para todos los documentos ya subidos que aún no tienen uno. Así las anotaciones se vinculan correctamente a su versión del archivo y vuelven a mostrarse.", "admin_system_backfill_hashes_btn": "Calcular hashes de archivo", "admin_system_backfill_hashes_success": "{count} documentos fueron actualizados.", + "admin_system_import_heading": "Importación masiva", + "admin_system_import_description": "Importa documentos y metadatos desde el archivo en el directorio /import.", + "admin_system_import_btn_start": "Iniciar importación", + "admin_system_import_btn_retry": "Iniciar de nuevo", + "admin_system_import_status_idle": "No hay importación iniciada.", + "admin_system_import_status_running": "Importación en curso…", + "admin_system_import_status_done": "Importación completada – {count} documentos procesados.", + "admin_system_import_status_failed": "Error: {message}", "comp_expandable_show_more": "Mostrar más", "comp_expandable_show_less": "Mostrar menos", "error_comment_not_found": "El comentario no pudo encontrarse.", 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 new file mode 100644 index 00000000..ba3e1849 --- /dev/null +++ b/frontend/src/routes/admin/+layout.svelte @@ -0,0 +1,33 @@ + + + + Admin · Familienarchiv + + + +
+ + + + +
+ {@render children()} +
+
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/+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..ae57556b --- /dev/null +++ b/frontend/src/routes/admin/EntityNav.svelte @@ -0,0 +1,492 @@ + + + + + + + +{#if flyoutOpen} + +
(flyoutOpen = false)} + >
+ + + +{/if} diff --git a/frontend/src/routes/admin/GroupsTab.svelte b/frontend/src/routes/admin/GroupsTab.svelte deleted file mode 100644 index 6eb22e53..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} - - {/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/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 01a1fec0..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/UsersTab.svelte b/frontend/src/routes/admin/UsersTab.svelte deleted file mode 100644 index f6a72c32..00000000 --- a/frontend/src/routes/admin/UsersTab.svelte +++ /dev/null @@ -1,120 +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/entity-nav.svelte.spec.ts b/frontend/src/routes/admin/entity-nav.svelte.spec.ts new file mode 100644 index 00000000..c9fea364 --- /dev/null +++ b/frontend/src/routes/admin/entity-nav.svelte.spec.ts @@ -0,0 +1,81 @@ +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 props = { + userCount: 5, + groupCount: 3, + tagCount: 8, + canManageUsers: true, + canManageTags: true, + canManageGroups: true, + canRunMaintenance: true +}; + +describe('EntityNav — flyout', () => { + it('flyout dialog is not visible initially', async () => { + render(EntityNav, props); + await expect.element(page.getByRole('dialog')).not.toBeInTheDocument(); + }); + + it('clicking a flyout trigger opens the dialog', async () => { + render(EntityNav, props); + document.querySelector('[data-flyout-trigger]')!.click(); + await expect.element(page.getByRole('dialog')).toBeInTheDocument(); + }); + + it('flyout dialog has aria-modal="true"', async () => { + render(EntityNav, props); + document.querySelector('[data-flyout-trigger]')!.click(); + await expect.element(page.getByRole('dialog')).toHaveAttribute('aria-modal', 'true'); + }); + + it('flyout dialog has an aria-label', async () => { + render(EntityNav, props); + document.querySelector('[data-flyout-trigger]')!.click(); + await expect.element(page.getByRole('dialog')).toBeInTheDocument(); + const dialog = document.querySelector('[role="dialog"]')!; + expect(dialog.getAttribute('aria-label')).toBeTruthy(); + }); + + it('flyout contains navigation links to each entity', async () => { + render(EntityNav, props); + document.querySelector('[data-flyout-trigger]')!.click(); + await expect.element(page.getByRole('dialog')).toBeInTheDocument(); + const dialog = document.querySelector('[role="dialog"]')!; + const links = dialog.querySelectorAll('a[href^="/admin/"]'); + expect(links.length).toBeGreaterThanOrEqual(3); + }); + + it('pressing Escape closes the flyout', async () => { + render(EntityNav, props); + document.querySelector('[data-flyout-trigger]')!.click(); + await expect.element(page.getByRole('dialog')).toBeInTheDocument(); + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); + await expect.element(page.getByRole('dialog')).not.toBeInTheDocument(); + }); + + it('clicking the backdrop closes the flyout', async () => { + render(EntityNav, props); + document.querySelector('[data-flyout-trigger]')!.click(); + await expect.element(page.getByRole('dialog')).toBeInTheDocument(); + document.querySelector('[data-flyout-backdrop]')!.click(); + await expect.element(page.getByRole('dialog')).not.toBeInTheDocument(); + }); + + it('clicking a flyout link closes the flyout', async () => { + render(EntityNav, props); + document.querySelector('[data-flyout-trigger]')!.click(); + await expect.element(page.getByRole('dialog')).toBeInTheDocument(); + const dialog = document.querySelector('[role="dialog"]')!; + dialog.querySelector('a[href^="/admin/"]')!.click(); + await expect.element(page.getByRole('dialog')).not.toBeInTheDocument(); + }); +}); diff --git a/frontend/src/routes/admin/groups/+layout.server.ts b/frontend/src/routes/admin/groups/+layout.server.ts new file mode 100644 index 00000000..d9cf130a --- /dev/null +++ b/frontend/src/routes/admin/groups/+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/groups'); + return { groups: result.data ?? [] }; +}; diff --git a/frontend/src/routes/admin/groups/+layout.svelte b/frontend/src/routes/admin/groups/+layout.svelte new file mode 100644 index 00000000..ab2a89b8 --- /dev/null +++ b/frontend/src/routes/admin/groups/+layout.svelte @@ -0,0 +1,17 @@ + + +
+ +
+ +
+ {@render children()} +
diff --git a/frontend/src/routes/admin/groups/+page.svelte b/frontend/src/routes/admin/groups/+page.svelte new file mode 100644 index 00000000..d98bacd4 --- /dev/null +++ b/frontend/src/routes/admin/groups/+page.svelte @@ -0,0 +1,7 @@ + + +
+

{m.admin_groups_select_prompt()}

+
diff --git a/frontend/src/routes/admin/groups/GroupsListPanel.svelte b/frontend/src/routes/admin/groups/GroupsListPanel.svelte new file mode 100644 index 00000000..fe967f82 --- /dev/null +++ b/frontend/src/routes/admin/groups/GroupsListPanel.svelte @@ -0,0 +1,111 @@ + + +{#if isCollapsed} + + +{:else} +
+ +
+ + {m.admin_groups_list_title()} + +
+ + + + +
+
+ + +
+ {#if groups.length === 0} +

+ {m.admin_groups_empty()} +

+ {:else} + {#each groups as group (group.id)} + {@const isActive = page.url.pathname.startsWith('/admin/groups/' + group.id)} + +
{group.name}
+
+ {m.admin_groups_permission_count({ count: group.permissions.length })} +
+
+ {/each} + {/if} +
+
+{/if} diff --git a/frontend/src/routes/admin/groups/[id]/+page.server.ts b/frontend/src/routes/admin/groups/[id]/+page.server.ts new file mode 100644 index 00000000..b3441c04 --- /dev/null +++ b/frontend/src/routes/admin/groups/[id]/+page.server.ts @@ -0,0 +1,47 @@ +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 { groups } = await parent(); + const group = groups.find((g: { id: string }) => g.id === params.id); + if (!group) throw error(404, getErrorMessage('GROUP_NOT_FOUND')); + return { group }; +}; + +export const actions: Actions = { + update: async ({ params, request, fetch }) => { + const data = await request.formData(); + const api = createApiClient(fetch); + + const result = await api.PATCH('/api/groups/{id}', { + params: { path: { id: params.id } }, + 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) }); + } + + return { success: true }; + }, + + delete: async ({ params, fetch }) => { + const api = createApiClient(fetch); + const result = await api.DELETE('/api/groups/{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/groups'); + } +}; diff --git a/frontend/src/routes/admin/groups/[id]/+page.svelte b/frontend/src/routes/admin/groups/[id]/+page.svelte new file mode 100644 index 00000000..66462616 --- /dev/null +++ b/frontend/src/routes/admin/groups/[id]/+page.svelte @@ -0,0 +1,193 @@ + + +
+ +
+

+ {m.admin_group_edit_heading({ name: data.group.name })} +

+
{ + if (!confirm(m.admin_group_delete_confirm())) cancel(); + return async ({ update }) => { + await update(); + }; + }} + > + +
+
+ + +
+ {#if showUnsavedWarning} +
+ {m.admin_unsaved_warning()} + +
+ {/if} + {#if form?.success} +
+ {m.admin_group_updated()} +
+ {/if} + {#if form?.error} +
+ {form.error} +
+ {/if} + +
{ + isDirty = true; + showUnsavedWarning = false; + }} + > + +
+

+ {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/[id]/page.svelte.spec.ts b/frontend/src/routes/admin/groups/[id]/page.svelte.spec.ts new file mode 100644 index 00000000..426ca22c --- /dev/null +++ b/frontend/src/routes/admin/groups/[id]/page.svelte.spec.ts @@ -0,0 +1,149 @@ +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 baseGroup = { id: 'g1', name: 'Editoren', permissions: ['WRITE_ALL'] }; +const baseData = { group: baseGroup }; + +afterEach(cleanup); + +// ─── Rendering ──────────────────────────────────────────────────────────────── + +describe('Admin edit group page – rendering', () => { + it('renders the heading with group name', async () => { + render(Page, { data: baseData, form: null }); + await expect.element(page.getByText(/Gruppe: Editoren/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('Editoren'); + }); + + it('pre-checks permissions that the group already has', async () => { + render(Page, { data: baseData, form: null }); + const checkbox = document.querySelector( + 'input[type="checkbox"][name="permissions"][value="WRITE_ALL"]' + ); + expect(checkbox?.checked).toBe(true); + }); + + it('renders the cancel link pointing to /admin/groups', async () => { + render(Page, { data: baseData, form: null }); + await expect + .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 ──────────────────────────────────────────────────── + +describe('Admin edit group 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="name"]')! + .dispatchEvent(new InputEvent('input', { bubbles: true })); + + const cancel = vi.fn(); + callback({ cancel, to: { url: new URL('http://localhost/admin/groups/g2') } }); + + 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/groups/g2') } }); + + 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/groups/g2') } }); + + await page.getByRole('button', { name: /verwerfen/i }).click(); + + expect(vi.mocked(goto)).toHaveBeenCalledWith('http://localhost/admin/groups/g2'); + }); + + 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="name"]')! + .dispatchEvent(new InputEvent('input', { bubbles: true })); + + callback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/groups/g2') } }); + 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/groups/g2') } }); + expect(cancel).not.toHaveBeenCalled(); + }); +}); 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..5cc160ad --- /dev/null +++ b/frontend/src/routes/admin/groups/layout.svelte.spec.ts @@ -0,0 +1,110 @@ +import { afterEach, beforeEach, 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(); + }); +}); + +// ─── Collapse toggle ────────────────────────────────────────────────────────── + +describe('GroupsListPanel — collapse toggle', () => { + beforeEach(() => localStorage.removeItem('admin_list_collapsed')); + + it('renders a collapse button with aria-label', async () => { + render(GroupsListPanel, { groups }); + await expect + .element(page.getByRole('button', { name: /Liste einklappen/i })) + .toBeInTheDocument(); + }); + + it('clicking collapse shows the expand handle', async () => { + render(GroupsListPanel, { groups }); + await expect + .element(page.getByRole('button', { name: /Liste einklappen/i })) + .toBeInTheDocument(); + document.querySelector('[aria-label="Liste einklappen"]')!.click(); + await expect + .element(page.getByRole('button', { name: /Liste ausklappen/i })) + .toBeInTheDocument(); + }); + + it('autocollapse prop starts the panel in collapsed state', async () => { + render(GroupsListPanel, { groups, autocollapse: true }); + await expect + .element(page.getByRole('button', { name: /Liste ausklappen/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..eb188298 --- /dev/null +++ b/frontend/src/routes/admin/groups/new/+page.svelte @@ -0,0 +1,157 @@ + + +
+ +
+

+ {m.admin_group_new_heading()} +

+
+ + +
+ {#if showUnsavedWarning} +
+ {m.admin_unsaved_warning()} + +
+ {/if} + {#if form?.error} +
+ {form.error} +
+ {/if} + +
{ + isDirty = true; + showUnsavedWarning = false; + }} + class="space-y-5" + > + +
+

+ {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()} + + +
+
diff --git a/frontend/src/routes/admin/layout.server.spec.ts b/frontend/src/routes/admin/layout.server.spec.ts new file mode 100644 index 00000000..eb5f39c8 --- /dev/null +++ b/frontend/src/routes/admin/layout.server.spec.ts @@ -0,0 +1,72 @@ +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[], 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); +} + +const adminUser = { + groups: [{ permissions: ['ADMIN', 'ADMIN_USER', 'ADMIN_TAG', 'ADMIN_PERMISSION'] }] +}; +const tagAdminUser = { groups: [{ permissions: ['ADMIN_TAG'] }] }; +const noPermUser = { groups: [{ permissions: ['READ_ALL'] }] }; + +beforeEach(() => vi.clearAllMocks()); + +describe('admin layout 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: noPermUser } }) + ).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 }); + }); + + it('allows access for a user with ADMIN_TAG only', async () => { + mockApi([], [], []); + await expect( + load({ fetch: vi.fn() as unknown as typeof fetch, locals: { user: tagAdminUser } }) + ).resolves.toBeDefined(); + }); + + it('returns entity counts and permission flags for a full admin', async () => { + mockApi( + [{ id: 'u1' }, { id: 'u2' }], + [{ id: 'g1' }], + [{ id: 't1' }, { id: 't2' }, { id: 't3' }] + ); + + const result = await load({ + fetch: vi.fn() as unknown as typeof fetch, + locals: { user: adminUser } + }); + + expect(result.userCount).toBe(2); + expect(result.groupCount).toBe(1); + expect(result.tagCount).toBe(3); + expect(result.canManageUsers).toBe(true); + expect(result.canManageTags).toBe(true); + expect(result.canManageGroups).toBe(true); + expect(result.canRunMaintenance).toBe(true); + }); +}); 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.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/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/system/+page.svelte b/frontend/src/routes/admin/system/+page.svelte new file mode 100644 index 00000000..463b1677 --- /dev/null +++ b/frontend/src/routes/admin/system/+page.svelte @@ -0,0 +1,170 @@ + + +
+
+ +
+

{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} +
+ + +
+

{m.admin_system_import_heading()}

+

{m.admin_system_import_description()}

+ + {#if importStatus?.state === 'RUNNING'} +

{m.admin_system_import_status_running()}

+ {:else if importStatus?.state === 'DONE'} +

+ {m.admin_system_import_status_done({ count: importStatus.processed })} +

+ + {:else if importStatus?.state === 'FAILED'} +

+ {m.admin_system_import_status_failed({ message: importStatus.message })} +

+ + {:else} + {#if importStatus !== null} +

{m.admin_system_import_status_idle()}

+ {/if} + + {/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..df349893 --- /dev/null +++ b/frontend/src/routes/admin/system/page.svelte.spec.ts @@ -0,0 +1,136 @@ +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 () => { + 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(); + }); +}); + +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(); + }); +}); 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..190f5e29 --- /dev/null +++ b/frontend/src/routes/admin/tags/+layout.svelte @@ -0,0 +1,16 @@ + + +
+ +
+ +
+ {@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..deb08c9d --- /dev/null +++ b/frontend/src/routes/admin/tags/TagsListPanel.svelte @@ -0,0 +1,88 @@ + + +{#if isCollapsed} + + +{:else} +
+ +
+ + {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} +
+
+{/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..77d4af1e --- /dev/null +++ b/frontend/src/routes/admin/tags/[id]/+page.svelte @@ -0,0 +1,144 @@ + + +
+ +
+

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

+
+ + +
+ {#if showUnsavedWarning} +
+ {m.admin_unsaved_warning()} + +
+ {/if} + {#if form?.success} +
+ {m.admin_tag_updated()} +
+ {/if} + {#if form?.error} +
+ {form.error} +
+ {/if} + + +
{ + isDirty = true; + showUnsavedWarning = false; + }} + class="mb-5" + > +
+

+ {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/[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/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..6638b9db --- /dev/null +++ b/frontend/src/routes/admin/tags/layout.svelte.spec.ts @@ -0,0 +1,89 @@ +import { afterEach, beforeEach, 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(); + }); +}); + +// ─── Collapse toggle ────────────────────────────────────────────────────────── + +describe('TagsListPanel — collapse toggle', () => { + beforeEach(() => localStorage.removeItem('admin_list_collapsed')); + + it('renders a collapse button with aria-label', async () => { + render(TagsListPanel, { tags }); + await expect + .element(page.getByRole('button', { name: /Liste einklappen/i })) + .toBeInTheDocument(); + }); + + it('clicking collapse shows the expand handle', async () => { + render(TagsListPanel, { tags }); + await page.getByRole('button', { name: /Liste einklappen/i }).click(); + await expect + .element(page.getByRole('button', { name: /Liste ausklappen/i })) + .toBeInTheDocument(); + }); + + it('autocollapse prop starts the panel in collapsed state', async () => { + render(TagsListPanel, { tags, autocollapse: true }); + await expect + .element(page.getByRole('button', { name: /Liste ausklappen/i })) + .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..27077156 --- /dev/null +++ b/frontend/src/routes/admin/users/+layout.svelte @@ -0,0 +1,22 @@ + + + +
+ +
+ + +
+ {@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..9e453ea2 --- /dev/null +++ b/frontend/src/routes/admin/users/UsersListPanel.svelte @@ -0,0 +1,151 @@ + + +{#if isCollapsed} + + +{:else} +
+ +
+ + {m.admin_users_list_title()} + +
+ + + + +
+
+ + +
+ +
+ + +
+ {#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} +
+
+{/if} 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 2ebe7691..019f81ed 100644 --- a/frontend/src/routes/admin/users/[id]/+page.svelte +++ b/frontend/src/routes/admin/users/[id]/+page.svelte @@ -1,5 +1,6 @@ -
- - + +
+

+ {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(); + }; + }} > - - - {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_cancel()} - -
-
+ +
+ + +
+ {#if showUnsavedWarning} +
+ {m.admin_unsaved_warning()} + +
+ {/if} + {#if form?.success} +
+ {m.admin_user_updated()} +
+ {/if} + {#if form?.error} +
+ {form.error} +
+ {/if} + +
{ + isDirty = true; + showUnsavedWarning = false; + }} + class="space-y-5" + > + +
+

+ {m.profile_section_personal()} +

+ +
+ + +
+

+ {m.admin_col_groups()} +

+ +
+ + +
+

+ {m.admin_label_new_password_optional()} +

+ +
+
+
+ + +
+ + {m.btn_cancel()} + + +
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..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'] }, @@ -96,7 +99,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'); @@ -110,11 +113,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 () => { @@ -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/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..121a2bae --- /dev/null +++ b/frontend/src/routes/admin/users/layout.svelte.spec.ts @@ -0,0 +1,132 @@ +import { afterEach, beforeEach, 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(); + }); +}); + +// ─── Collapse toggle ────────────────────────────────────────────────────────── + +describe('UsersListPanel — collapse toggle', () => { + beforeEach(() => localStorage.removeItem('admin_list_collapsed')); + + it('renders a collapse button with aria-label', async () => { + render(UsersListPanel, { users }); + await expect + .element(page.getByRole('button', { name: /Liste einklappen/i })) + .toBeInTheDocument(); + }); + + it('clicking collapse shows the expand handle', async () => { + render(UsersListPanel, { users }); + await page.getByRole('button', { name: /Liste einklappen/i }).click(); + await expect + .element(page.getByRole('button', { name: /Liste ausklappen/i })) + .toBeInTheDocument(); + }); + + it('clicking expand handle restores the full panel', async () => { + render(UsersListPanel, { users }); + await page.getByRole('button', { name: /Liste einklappen/i }).click(); + await page.getByRole('button', { name: /Liste ausklappen/i }).click(); + await expect + .element(page.getByRole('button', { name: /Liste einklappen/i })) + .toBeInTheDocument(); + }); + + it('autocollapse prop starts the panel in collapsed state', async () => { + render(UsersListPanel, { users, autocollapse: true }); + await expect + .element(page.getByRole('button', { name: /Liste ausklappen/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..30a0e68c 100644 --- a/frontend/src/routes/admin/users/new/+page.svelte +++ b/frontend/src/routes/admin/users/new/+page.svelte @@ -1,71 +1,104 @@ -
- - + +
+

{m.admin_user_new_heading()}

+
+ + +
+ {#if showUnsavedWarning} +
+ {m.admin_unsaved_warning()} + +
+ {/if} + {#if form?.error} +
+ {form.error} +
+ {/if} + +
{ + isDirty = true; + showUnsavedWarning = false; + }} + class="space-y-5" > - - - {m.btn_back_to_overview()} - - -

{m.admin_user_new_heading()}

- - {#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 () => {