feat(ui): Korrespondenz redesign — compact strip, log cards, single-person mode #164

Merged
marcel merged 32 commits from feat/issue-162-korrespondenz-redesign into main 2026-03-30 21:38:23 +02:00
56 changed files with 2645 additions and 151 deletions

View File

@@ -28,6 +28,10 @@ jobs:
run: npm ci
working-directory: frontend
- name: Compile Paraglide i18n
run: npx @inlang/paraglide-js compile --project ./project.inlang --outdir ./src/lib/paraglide
working-directory: frontend
- name: Lint
run: npm run lint
working-directory: frontend

View File

@@ -10,6 +10,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
/**
@@ -24,6 +26,9 @@ public class AuthE2EController {
private final PasswordResetTokenRepository tokenRepository;
// Hidden from the OpenAPI spec — this endpoint must never appear in the generated api.ts
// even when the e2e profile is active alongside the dev profile during spec generation.
@Operation(hidden = true)
@GetMapping("/reset-token-for-test")
public ResponseEntity<String> getResetTokenForTest(@RequestParam String email) {
return tokenRepository.findLatestActiveTokenByEmail(email, LocalDateTime.now())

View File

@@ -212,7 +212,7 @@ public class DocumentController {
@GetMapping("/conversation")
public List<Document> getConversation(
@RequestParam UUID senderId,
@RequestParam UUID receiverId,
@RequestParam(required = false) UUID receiverId,
@RequestParam(required = false) LocalDate from,
@RequestParam(required = false) LocalDate to,
@RequestParam(defaultValue = "DESC") String dir) {

View File

@@ -60,11 +60,9 @@ public interface DocumentRepository extends JpaRepository<Document, UUID>, JpaSp
@Query("SELECT DISTINCT d FROM Document d " +
"JOIN d.receivers r " +
"WHERE " +
// Logik: (Sender A an Empfänger B) ODER (Sender B an Empfänger A)
"((d.sender.id = :person1 AND r.id = :person2) " +
" OR " +
" (d.sender.id = :person2 AND r.id = :person1)) " +
// UND das Datum stimmt
"AND d.documentDate BETWEEN :from AND :to")
List<Document> findConversation(
@Param("person1") UUID person1,
@@ -73,4 +71,14 @@ public interface DocumentRepository extends JpaRepository<Document, UUID>, JpaSp
@Param("to") LocalDate to,
Sort sort);
@Query("SELECT DISTINCT d FROM Document d " +
"LEFT JOIN d.receivers r " +
"WHERE (d.sender.id = :personId OR r.id = :personId) " +
"AND d.documentDate BETWEEN :from AND :to")
List<Document> findSinglePersonCorrespondence(
@Param("personId") UUID personId,
@Param("from") LocalDate from,
@Param("to") LocalDate to,
Sort sort);
}

View File

@@ -328,6 +328,9 @@ public class DocumentService {
public List<Document> getConversationFiltered(UUID senderId, UUID receiverId, LocalDate from, LocalDate to, Sort sort) {
LocalDate dateFrom = (from != null) ? from : LocalDate.parse("0000-01-01");
LocalDate dateTo = (to != null) ? to : LocalDate.now();
if (receiverId == null) {
return documentRepository.findSinglePersonCorrespondence(senderId, dateFrom, dateTo, sort);
}
return documentRepository.findConversation(senderId, receiverId, dateFrom, dateTo, sort);
}

View File

@@ -24,10 +24,13 @@ public class PersonService {
private final PersonRepository personRepository;
public List<PersonSummaryDTO> findAll(String q) {
if (q != null && !q.isBlank()) {
return personRepository.searchWithDocumentCount(q);
if (q == null) {
return personRepository.findAllWithDocumentCount();
}
return personRepository.findAllWithDocumentCount();
if (q.isBlank()) {
return List.of();
}
return personRepository.searchWithDocumentCount(q.trim());
}
public Person getById(UUID id) {

View File

@@ -15,8 +15,11 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
@@ -189,4 +192,65 @@ class DocumentRepositoryTest {
assertThat(result.getTotalElements()).isEqualTo(5);
assertThat(result.getContent()).allMatch(d -> !d.isMetadataComplete());
}
// ─── findSinglePersonCorrespondence — DISTINCT / multi-receiver safety ────
@Test
void findSinglePersonCorrespondence_returnsExactlyOneResult_whenDocumentHasThreeReceiversAndOneMatchesPersonId() {
Person sender = personRepository.save(Person.builder()
.firstName("Hans").lastName("Müller").build());
Person receiver1 = personRepository.save(Person.builder()
.firstName("Anna").lastName("Schmidt").build());
Person receiver2 = personRepository.save(Person.builder()
.firstName("Bertha").lastName("Wagner").build());
Person receiver3 = personRepository.save(Person.builder()
.firstName("Clara").lastName("Koch").build());
// Document addressed to all three receivers
Document doc = documentRepository.save(Document.builder()
.title("Rundschreiben")
.originalFilename("rundschreiben.pdf")
.status(DocumentStatus.UPLOADED)
.sender(sender)
.receivers(new HashSet<>(Set.of(receiver1, receiver2, receiver3)))
.documentDate(LocalDate.of(1950, 6, 1))
.build());
Sort sort = Sort.by(Sort.Direction.DESC, "documentDate");
LocalDate from = LocalDate.of(1900, 1, 1);
LocalDate to = LocalDate.of(2000, 1, 1);
// Query for receiver1 — the DISTINCT must collapse the 3 JOIN rows into 1 result
List<Document> results = documentRepository.findSinglePersonCorrespondence(
receiver1.getId(), from, to, sort);
assertThat(results).hasSize(1);
assertThat(results.get(0).getId()).isEqualTo(doc.getId());
}
@Test
void findSinglePersonCorrespondence_includesDocumentsWherePerson_isSender() {
Person sender = personRepository.save(Person.builder()
.firstName("Hans").lastName("Müller").build());
Person receiver = personRepository.save(Person.builder()
.firstName("Anna").lastName("Schmidt").build());
documentRepository.save(Document.builder()
.title("Brief als Absender")
.originalFilename("brief_absender.pdf")
.status(DocumentStatus.UPLOADED)
.sender(sender)
.receivers(new HashSet<>(Set.of(receiver)))
.documentDate(LocalDate.of(1950, 6, 1))
.build());
Sort sort = Sort.by(Sort.Direction.DESC, "documentDate");
LocalDate from = LocalDate.of(1900, 1, 1);
LocalDate to = LocalDate.of(2000, 1, 1);
List<Document> results = documentRepository.findSinglePersonCorrespondence(
sender.getId(), from, to, sort);
assertThat(results).hasSize(1);
}
}

View File

@@ -1244,4 +1244,33 @@ class DocumentServiceTest {
assertThat(captor.getValue().getSort())
.isEqualTo(Sort.by(Sort.Direction.DESC, "updatedAt"));
}
// ─── getConversationFiltered (single-person mode) ─────────────────────────
@Test
void getConversationFiltered_callsSinglePersonQuery_whenReceiverIdIsNull() {
UUID personId = UUID.randomUUID();
Sort sort = Sort.by(Sort.Direction.DESC, "documentDate");
when(documentRepository.findSinglePersonCorrespondence(eq(personId), any(), any(), eq(sort)))
.thenReturn(List.of());
documentService.getConversationFiltered(personId, null, null, null, sort);
verify(documentRepository).findSinglePersonCorrespondence(eq(personId), any(), any(), eq(sort));
verify(documentRepository, never()).findConversation(any(), any(), any(), any(), any());
}
@Test
void getConversationFiltered_callsBilateralQuery_whenReceiverIdIsSet() {
UUID senderId = UUID.randomUUID();
UUID receiverId = UUID.randomUUID();
Sort sort = Sort.by(Sort.Direction.DESC, "documentDate");
when(documentRepository.findConversation(eq(senderId), eq(receiverId), any(), any(), eq(sort)))
.thenReturn(List.of());
documentService.getConversationFiltered(senderId, receiverId, null, null, sort);
verify(documentRepository).findConversation(eq(senderId), eq(receiverId), any(), any(), eq(sort));
verify(documentRepository, never()).findSinglePersonCorrespondence(any(), any(), any(), any());
}
}

View File

@@ -62,12 +62,9 @@ class PersonServiceTest {
}
@Test
void findAll_returnsAll_whenQueryIsBlank() {
List<PersonSummaryDTO> expected = List.of();
when(personRepository.findAllWithDocumentCount()).thenReturn(expected);
assertThat(personService.findAll(" ")).isEqualTo(expected);
verify(personRepository).findAllWithDocumentCount();
void findAll_returnsEmpty_whenQueryIsWhitespaceOnly() {
assertThat(personService.findAll(" ")).isEmpty();
verify(personRepository, never()).findAllWithDocumentCount();
verify(personRepository, never()).searchWithDocumentCount(any());
}

View File

@@ -0,0 +1,127 @@
import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
function buildAxe(page: Parameters<typeof AxeBuilder>[0]['page']) {
return new AxeBuilder({ page }).withTags(['wcag2a', 'wcag2aa']);
}
test.describe('Korrespondenz empty state', () => {
test('shows the search heading when no person is selected', async ({ page }) => {
await page.goto('/korrespondenz');
await expect(page.getByText(/Korrespondenz durchsuchen/i)).toBeVisible();
const a11y = await buildAxe(page).analyze();
expect(a11y.violations, JSON.stringify(a11y.violations, null, 2)).toHaveLength(0);
await page.screenshot({ path: 'test-results/e2e/korrespondenz-empty.png' });
});
test('nav link goes to /korrespondenz', async ({ page }) => {
await page.goto('/');
// Click the nav link (desktop text or mobile icon)
const navLink = page.getByRole('link', { name: /Korrespondenz/i }).first();
await navLink.click();
await expect(page).toHaveURL(/\/korrespondenz/);
});
});
test.describe('Korrespondenz single-person mode', () => {
test('shows hint bar and documents when navigated with senderId', async ({ page }) => {
// Get a real person ID from the persons list
await page.goto('/persons');
const firstPersonLink = page.locator('a[href^="/persons/"]').first();
await firstPersonLink.click();
await page.waitForURL(/\/persons\/.+/);
// Extract the person ID from the URL
const personId = page.url().split('/persons/')[1].split('?')[0];
// Navigate to korrespondenz in single-person mode
await page.goto(`/korrespondenz?senderId=${personId}`);
// Hint bar should be visible
await expect(page.getByText(/Alle Briefe von/i)).toBeVisible();
// Filter controls should be active (not dimmed)
const filterStrip = page.locator('[aria-disabled="false"]').first();
await expect(filterStrip).toBeAttached();
const a11y = await buildAxe(page).analyze();
expect(a11y.violations, JSON.stringify(a11y.violations, null, 2)).toHaveLength(0);
await page.screenshot({ path: 'test-results/e2e/korrespondenz-single-person.png' });
});
test('sort toggle changes URL direction param', async ({ page }) => {
await page.goto('/persons');
const firstPersonLink = page.locator('a[href^="/persons/"]').first();
await firstPersonLink.click();
await page.waitForURL(/\/persons\/.+/);
const personId = page.url().split('/persons/')[1].split('?')[0];
await page.goto(`/korrespondenz?senderId=${personId}&dir=DESC`);
await page.getByTestId('conv-sort-btn').click();
await expect(page).toHaveURL(/dir=ASC/);
await page.screenshot({ path: 'test-results/e2e/korrespondenz-sort-asc.png' });
});
});
test.describe('Korrespondenz bilateral mode', () => {
test('shows asymmetry bar when both persons have shared documents', async ({ page }) => {
// Navigate to a person then follow a co-correspondent suggestion if available
await page.goto('/persons');
const firstPersonLink = page.locator('a[href^="/persons/"]').first();
await firstPersonLink.click();
await page.waitForURL(/\/persons\/.+/);
const senderId = page.url().split('/persons/')[1].split('?')[0];
// Try to find a co-correspondent link from the person detail page
const corrLink = page
.locator('a[href*="/korrespondenz?senderId="][href*="receiverId="]')
.first();
if (await corrLink.isVisible({ timeout: 2000 }).catch(() => false)) {
await corrLink.click();
await page.waitForURL(/\/korrespondenz\?.*receiverId=/);
// Hint bar should NOT be shown in bilateral mode
await expect(page.getByText(/Alle Briefe von/i)).not.toBeVisible();
const a11y = await buildAxe(page).analyze();
expect(a11y.violations, JSON.stringify(a11y.violations, null, 2)).toHaveLength(0);
await page.screenshot({ path: 'test-results/e2e/korrespondenz-bilateral.png' });
} else {
// E2E seed must include bilateral correspondents — a missing link is a test failure.
throw new Error(
`No bilateral correspondent links found for person ${senderId}. Ensure the E2E seed contains at least one bilateral correspondence pair.`
);
}
});
test('swap button swaps sender and receiver in URL', async ({ page }) => {
await page.goto('/persons');
const firstPersonLink = page.locator('a[href^="/persons/"]').first();
await firstPersonLink.click();
await page.waitForURL(/\/persons\/.+/);
const senderId = page.url().split('/persons/')[1].split('?')[0];
const corrLink = page
.locator('a[href*="/korrespondenz?senderId="][href*="receiverId="]')
.first();
if (await corrLink.isVisible({ timeout: 2000 }).catch(() => false)) {
const href = await corrLink.getAttribute('href');
await corrLink.click();
await page.waitForURL(/\/korrespondenz\?.*receiverId=/);
// Extract original receiverId from the href
const url = new URL(href!, 'http://x');
const originalReceiverId = url.searchParams.get('receiverId')!;
// Click swap
await page.getByTestId('conv-swap-btn').click();
// After swap the former receiver is now senderId
await expect(page).toHaveURL(new RegExp(`senderId=${originalReceiverId}`));
await page.screenshot({ path: 'test-results/e2e/korrespondenz-swapped.png' });
} else {
test.skip(true, `No bilateral correspondent links found for person ${senderId}`);
}
});
});

View File

@@ -16,7 +16,7 @@
"error_internal_error": "Ein unerwarteter Fehler ist aufgetreten.",
"nav_documents": "Dokumente",
"nav_persons": "Personen",
"nav_conversations": "Konversationen",
"nav_conversations": "Korrespondenz",
"nav_admin": "Admin",
"nav_logout": "Abmelden",
"btn_save": "Speichern",
@@ -122,22 +122,39 @@
"person_co_correspondents_heading": "Häufige Korrespondenten",
"person_correspondents_hint": "klicken für Konversation",
"person_show_more": "+ {count} weitere anzeigen",
"conv_heading": "Konversationen",
"conv_subtitle": "Verfolgen Sie den Schriftverkehr zwischen zwei Personen chronologisch.",
"conv_heading": "Korrespondenz",
"conv_subtitle": "Briefwechsel einer Person durchsuchen — mit oder ohne Korrespondent.",
"conv_label_person_a": "Person A (Absender)",
"conv_label_person_b": "Person B (Empfänger)",
"conv_label_person_b": "Korrespondent",
"conv_label_from": "Zeitraum von",
"conv_label_to": "Zeitraum bis",
"conv_sort_label": "Sortierung:",
"conv_sort_newest": "Neueste zuerst",
"conv_sort_oldest": "Älteste zuerst",
"conv_empty_heading": "Wählen Sie zwei Personen aus",
"conv_empty_text": "Die Korrespondenz wird hier angezeigt.",
"conv_empty_heading": "Korrespondenz durchsuchen",
"conv_empty_text": "Wähle eine Person aus dem Archiv um deren Briefe zu sehen — mit oder ohne Korrespondent.",
"conv_no_results_heading": "Keine Dokumente gefunden.",
"conv_no_results_text": "Versuchen Sie, den Zeitraum anzupassen.",
"conv_swap_btn": "Personen tauschen",
"conv_summary": "{count} Dokumente · {yearFrom}{yearTo}",
"conv_new_doc_link": "Neues Dokument in dieser Korrespondenz",
"conv_label_correspondent_optional": "Korrespondent",
"conv_hint_single_person": "Alle Briefe von {name} — wähle einen Korrespondenten oben um einzugrenzen",
"conv_hint_single_person_filtered": "Alle Briefe von {name} · {from}{to} · {sortLabel}",
"conv_strip_period": "Zeitraum",
"conv_strip_from_placeholder": "Von…",
"conv_strip_to_placeholder": "Bis…",
"conv_strip_all_correspondents": "Alle Korrespondenten",
"conv_strip_sort_newest": "Neueste",
"conv_strip_sort_oldest": "Älteste",
"conv_suggestions_heading": "Häufigste Korrespondenten",
"conv_suggestions_all_label": "Alle Korrespondenten von {name}",
"conv_letters_count": "{count} Briefe",
"conv_empty_search_placeholder": "Person suchen…",
"conv_empty_recent_label": "Zuletzt geöffnet",
"conv_asym_sent": "{count} von {name} →",
"conv_asym_received": "{count} von {name} ←",
"conv_no_party": "—",
"admin_heading": "Admin Dashboard",
"admin_tab_users": "Benutzer",
"admin_tab_groups": "Gruppen",
@@ -190,6 +207,13 @@
"admin_group_created": "Gruppe erstellt.",
"admin_groups_section_standard": "Standard",
"admin_groups_section_administrative": "Administrativ",
"admin_perm_read_all": "Nur lesen",
"admin_perm_annotate_all": "Lesen & Annotieren",
"admin_perm_write_all": "Lesen & Schreiben",
"admin_perm_admin": "Vollzugriff (Admin)",
"admin_perm_admin_user": "Benutzer verwalten",
"admin_perm_admin_tag": "Schlagworte verwalten",
"admin_perm_admin_permission": "Berechtigungen verwalten",
"admin_user_new_heading": "Neuen Benutzer anlegen",
"admin_user_edit_heading": "Benutzer bearbeiten: {username}",
"admin_user_created": "Benutzer wurde erstellt.",

View File

@@ -16,7 +16,7 @@
"error_internal_error": "An unexpected error occurred.",
"nav_documents": "Documents",
"nav_persons": "Persons",
"nav_conversations": "Conversations",
"nav_conversations": "Correspondence",
"nav_admin": "Admin",
"nav_logout": "Sign out",
"btn_save": "Save",
@@ -122,22 +122,39 @@
"person_co_correspondents_heading": "Frequent correspondents",
"person_correspondents_hint": "click to view conversation",
"person_show_more": "+ {count} more",
"conv_heading": "Conversations",
"conv_subtitle": "Follow the correspondence between two persons chronologically.",
"conv_heading": "Correspondence",
"conv_subtitle": "Browse a person's letters — with or without a correspondent.",
"conv_label_person_a": "Person A (Sender)",
"conv_label_person_b": "Person B (Recipient)",
"conv_label_person_b": "Correspondent",
"conv_label_from": "Period from",
"conv_label_to": "Period to",
"conv_sort_label": "Sort:",
"conv_sort_newest": "Newest first",
"conv_sort_oldest": "Oldest first",
"conv_empty_heading": "Select two persons",
"conv_empty_text": "The correspondence will be shown here.",
"conv_empty_heading": "Browse correspondence",
"conv_empty_text": "Choose a person from the archive to see their letters — with or without a correspondent.",
"conv_no_results_heading": "No documents found.",
"conv_no_results_text": "Try adjusting the time period.",
"conv_swap_btn": "Swap persons",
"conv_summary": "{count} documents · {yearFrom}{yearTo}",
"conv_new_doc_link": "New document in this correspondence",
"conv_label_correspondent_optional": "Correspondent",
"conv_hint_single_person": "All letters from {name} — choose a correspondent above to narrow down",
"conv_hint_single_person_filtered": "All letters from {name} · {from}{to} · {sortLabel}",
"conv_strip_period": "Period",
"conv_strip_from_placeholder": "From…",
"conv_strip_to_placeholder": "To…",
"conv_strip_all_correspondents": "All correspondents",
"conv_strip_sort_newest": "Newest",
"conv_strip_sort_oldest": "Oldest",
"conv_suggestions_heading": "Top correspondents",
"conv_suggestions_all_label": "All correspondents of {name}",
"conv_letters_count": "{count} letters",
"conv_empty_search_placeholder": "Search person…",
"conv_empty_recent_label": "Recently opened",
"conv_asym_sent": "{count} from {name} →",
"conv_asym_received": "{count} from {name} ←",
"conv_no_party": "—",
"admin_heading": "Admin Dashboard",
"admin_tab_users": "Users",
"admin_tab_groups": "Groups",
@@ -190,6 +207,13 @@
"admin_group_created": "Group created.",
"admin_groups_section_standard": "Standard",
"admin_groups_section_administrative": "Administrative",
"admin_perm_read_all": "Read only",
"admin_perm_annotate_all": "Read & Annotate",
"admin_perm_write_all": "Read & Write",
"admin_perm_admin": "Full access (Admin)",
"admin_perm_admin_user": "Manage users",
"admin_perm_admin_tag": "Manage tags",
"admin_perm_admin_permission": "Manage permissions",
"admin_user_new_heading": "Create new user",
"admin_user_edit_heading": "Edit user: {username}",
"admin_user_created": "User has been created.",

View File

@@ -16,7 +16,7 @@
"error_internal_error": "Se ha producido un error inesperado.",
"nav_documents": "Documentos",
"nav_persons": "Personas",
"nav_conversations": "Conversaciones",
"nav_conversations": "Correspondencia",
"nav_admin": "Admin",
"nav_logout": "Cerrar sesión",
"btn_save": "Guardar",
@@ -122,22 +122,39 @@
"person_co_correspondents_heading": "Corresponsales frecuentes",
"person_correspondents_hint": "clic para ver conversación",
"person_show_more": "+ {count} más",
"conv_heading": "Conversaciones",
"conv_subtitle": "Siga la correspondencia entre dos personas cronológicamente.",
"conv_heading": "Correspondencia",
"conv_subtitle": "Explore las cartas de una persona con o sin corresponsal.",
"conv_label_person_a": "Persona A (Remitente)",
"conv_label_person_b": "Persona B (Destinatario)",
"conv_label_person_b": "Corresponsal",
"conv_label_from": "Período desde",
"conv_label_to": "Período hasta",
"conv_sort_label": "Ordenar:",
"conv_sort_newest": "Más reciente primero",
"conv_sort_oldest": "Más antiguo primero",
"conv_empty_heading": "Seleccione dos personas",
"conv_empty_text": "La correspondencia se mostrará aquí.",
"conv_empty_heading": "Explorar correspondencia",
"conv_empty_text": "Elige una persona del archivo para ver sus cartas — con o sin corresponsal.",
"conv_no_results_heading": "No se encontraron documentos.",
"conv_no_results_text": "Intente ajustar el período de tiempo.",
"conv_swap_btn": "Intercambiar personas",
"conv_summary": "{count} documentos · {yearFrom}{yearTo}",
"conv_new_doc_link": "Nuevo documento en esta correspondencia",
"conv_label_correspondent_optional": "Corresponsal",
"conv_hint_single_person": "Todas las cartas de {name} — elige un corresponsal arriba para filtrar",
"conv_hint_single_person_filtered": "Todas las cartas de {name} · {from}{to} · {sortLabel}",
"conv_strip_period": "Período",
"conv_strip_from_placeholder": "Desde…",
"conv_strip_to_placeholder": "Hasta…",
"conv_strip_all_correspondents": "Todos los corresponsales",
"conv_strip_sort_newest": "Más reciente",
"conv_strip_sort_oldest": "Más antiguo",
"conv_suggestions_heading": "Corresponsales frecuentes",
"conv_suggestions_all_label": "Todos los corresponsales de {name}",
"conv_letters_count": "{count} cartas",
"conv_empty_search_placeholder": "Buscar persona…",
"conv_empty_recent_label": "Recientemente abiertos",
"conv_asym_sent": "{count} de {name} →",
"conv_asym_received": "{count} de {name} ←",
"conv_no_party": "—",
"admin_heading": "Panel de administración",
"admin_tab_users": "Usuarios",
"admin_tab_groups": "Grupos",
@@ -190,6 +207,13 @@
"admin_group_created": "Grupo creado.",
"admin_groups_section_standard": "Est\u00e1ndar",
"admin_groups_section_administrative": "Administrativo",
"admin_perm_read_all": "Solo lectura",
"admin_perm_annotate_all": "Leer y anotar",
"admin_perm_write_all": "Leer y escribir",
"admin_perm_admin": "Acceso completo (Admin)",
"admin_perm_admin_user": "Gestionar usuarios",
"admin_perm_admin_tag": "Gestionar etiquetas",
"admin_perm_admin_permission": "Gestionar permisos",
"admin_user_new_heading": "Crear nuevo usuario",
"admin_user_edit_heading": "Editar usuario: {username}",
"admin_user_created": "Usuario creado.",

View File

@@ -12,6 +12,7 @@ declare global {
email?: string;
contact?: string;
groups: {
id: string;
name: string;
permissions: string[];
}[];

View File

@@ -1,31 +1,28 @@
<script lang="ts">
import { isoToGerman, handleGermanDateInput } from '$lib/utils/date.js';
import * as m from '$lib/paraglide/messages.js';
import { isoToGerman, handleGermanDateInput, germanToIso } from '$lib/utils/date';
import { m } from '$lib/paraglide/messages.js';
interface Props {
value?: string;
errorMessage?: string | null;
class?: string;
id?: string;
name?: string;
id?: string;
placeholder?: string;
oninput?: () => void;
[key: string]: unknown;
class?: string;
onchange?: () => void;
}
let {
value = $bindable(''),
errorMessage = $bindable<string | null>(null),
class: extraClass,
id,
name,
placeholder = m.form_placeholder_date(),
oninput: onInputCallback,
...rest
id,
placeholder,
class: className = '',
onchange
}: Props = $props();
// ─── Display state ────────────────────────────────────────────────────────
let display = $state(isoToGerman(value));
let display = $state(isoToGerman(value ?? ''));
// ─── Validation helper ────────────────────────────────────────────────────
function isCalendarValid(iso: string): boolean {
@@ -38,20 +35,32 @@ function isCalendarValid(iso: string): boolean {
// ─── Input handler ────────────────────────────────────────────────────────
function handleInput(e: Event) {
const { display: formatted, iso } = handleGermanDateInput(e);
display = formatted;
const result = handleGermanDateInput(e);
display = result.display;
if (formatted === '') {
if (result.display === '') {
value = '';
errorMessage = null;
} else if (iso && isCalendarValid(iso)) {
value = iso;
errorMessage = null;
} else {
onchange?.();
return;
}
if (result.display.length < 10) {
value = '';
errorMessage = m.form_date_error();
return;
}
onInputCallback?.();
const iso = germanToIso(result.display);
if (!iso || !isCalendarValid(iso)) {
value = '';
errorMessage = m.form_date_error();
return;
}
value = iso;
errorMessage = null;
onchange?.();
}
</script>
@@ -60,11 +69,10 @@ function handleInput(e: Event) {
inputmode="numeric"
maxlength="10"
id={id}
placeholder={placeholder}
class={extraClass}
value={display}
placeholder={placeholder ?? m.form_placeholder_date()}
oninput={handleInput}
{...rest}
class={className}
/>
{#if name}
<input type="hidden" name={name} value={value} />

View File

@@ -0,0 +1,210 @@
import { describe, expect, it, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import DateInput from './DateInput.svelte';
afterEach(() => cleanup());
// ─── Rendering ────────────────────────────────────────────────────────────────
describe('DateInput rendering', () => {
it('renders a text input with inputmode=numeric and maxlength=10', async () => {
render(DateInput, {});
const input = page.getByRole('textbox');
await expect.element(input).toBeInTheDocument();
await expect.element(input).toHaveAttribute('inputmode', 'numeric');
await expect.element(input).toHaveAttribute('maxlength', '10');
});
it('has default placeholder from paraglide', async () => {
render(DateInput, {});
const input = page.getByRole('textbox');
await expect.element(input).toHaveAttribute('placeholder', 'TT.MM.JJJJ');
});
it('accepts a custom placeholder', async () => {
render(DateInput, { placeholder: 'Geburtsdatum' });
const input = page.getByRole('textbox');
await expect.element(input).toHaveAttribute('placeholder', 'Geburtsdatum');
});
it('passes id prop to the input', async () => {
render(DateInput, { id: 'my-date' });
const input = page.getByRole('textbox');
await expect.element(input).toHaveAttribute('id', 'my-date');
});
});
// ─── Init from value ──────────────────────────────────────────────────────────
describe('DateInput init from value', () => {
it('displays ISO value in German format on mount', async () => {
render(DateInput, { value: '2024-12-20' });
const input = page.getByRole('textbox');
await expect.element(input).toHaveValue('20.12.2024');
});
it('starts empty and error-free when no value is given', async () => {
let errorMessage: string | null = null;
render(DateInput, {
get errorMessage() {
return errorMessage;
},
set errorMessage(v) {
errorMessage = v;
}
});
const input = page.getByRole('textbox');
await expect.element(input).toHaveValue('');
expect(errorMessage).toBeNull();
});
});
// ─── Typing valid date ────────────────────────────────────────────────────────
describe('DateInput typing a valid date', () => {
it('auto-formats to DD.MM.YYYY and updates value to ISO', async () => {
let value = '';
let errorMessage: string | null = null;
render(DateInput, {
get value() {
return value;
},
set value(v) {
value = v;
},
get errorMessage() {
return errorMessage;
},
set errorMessage(v) {
errorMessage = v;
}
});
const input = page.getByRole('textbox');
await input.fill('20122024');
await expect.element(input).toHaveValue('20.12.2024');
expect(value).toBe('2024-12-20');
expect(errorMessage).toBeNull();
});
});
// ─── Typing invalid month ─────────────────────────────────────────────────────
describe('DateInput typing a date with invalid month', () => {
it('sets errorMessage and clears value when month > 12', async () => {
let value = '';
let errorMessage: string | null = null;
render(DateInput, {
get value() {
return value;
},
set value(v) {
value = v;
},
get errorMessage() {
return errorMessage;
},
set errorMessage(v) {
errorMessage = v;
}
});
const input = page.getByRole('textbox');
await input.fill('22222222');
await expect.element(input).toHaveValue('22.22.2222');
expect(value).toBe('');
expect(errorMessage).not.toBeNull();
});
});
// ─── Typing partial date ──────────────────────────────────────────────────────
describe('DateInput typing a partial date', () => {
it('sets errorMessage and clears value when date is incomplete', async () => {
let value = '';
let errorMessage: string | null = null;
render(DateInput, {
get value() {
return value;
},
set value(v) {
value = v;
},
get errorMessage() {
return errorMessage;
},
set errorMessage(v) {
errorMessage = v;
}
});
const input = page.getByRole('textbox');
await input.fill('2212');
await expect.element(input).toHaveValue('22.12');
expect(value).toBe('');
expect(errorMessage).not.toBeNull();
});
});
// ─── Clearing date ────────────────────────────────────────────────────────────
describe('DateInput clearing the date', () => {
it('resets value and errorMessage to null when cleared', async () => {
let value = '';
let errorMessage: string | null = null;
render(DateInput, {
get value() {
return value;
},
set value(v) {
value = v;
},
get errorMessage() {
return errorMessage;
},
set errorMessage(v) {
errorMessage = v;
}
});
const input = page.getByRole('textbox');
// Type a valid date first
await input.fill('20122024');
expect(value).toBe('2024-12-20');
// Now clear
await input.fill('');
expect(value).toBe('');
expect(errorMessage).toBeNull();
});
it('fires onchange when the field is cleared', async () => {
let called = 0;
render(DateInput, { value: '2024-12-20', onchange: () => called++ });
const input = page.getByRole('textbox');
await input.fill('');
expect(called).toBeGreaterThan(0);
});
});
// ─── Hidden input ─────────────────────────────────────────────────────────────
describe('DateInput hidden input for form submission', () => {
it('renders a hidden input with the given name when name prop is set', async () => {
render(DateInput, { name: 'documentDate' });
const hidden = document.querySelector('input[type="hidden"][name="documentDate"]');
expect(hidden).not.toBeNull();
});
it('does not render a hidden input when name prop is absent', async () => {
render(DateInput, {});
const hidden = document.querySelector('input[type="hidden"]');
expect(hidden).toBeNull();
});
it('hidden input value reflects the ISO value', async () => {
render(DateInput, { name: 'documentDate', value: '' });
const input = page.getByRole('textbox');
await input.fill('20122024');
const hidden = document.querySelector<HTMLInputElement>(
'input[type="hidden"][name="documentDate"]'
);
await expect.poll(() => hidden?.value).toBe('2024-12-20');
});
});

View File

@@ -175,7 +175,7 @@ let { doc }: { doc: Doc } = $props();
{#if doc.sender}
<a
href="/conversations?senderId={doc.sender.id}&receiverId={receiver.id}"
href="/korrespondenz?senderId={doc.sender.id}&receiverId={receiver.id}"
class="text-ink-3 transition hover:text-accent"
title={m.doc_conversation_title()}
>

View File

@@ -10,8 +10,11 @@ interface Props {
value?: string;
initialName?: string;
suggestedName?: string;
placeholder?: string;
compact?: boolean;
restrictToCorrespondentsOf?: string;
onchange?: (value: string) => void;
onfocused?: () => void;
}
let {
@@ -20,12 +23,23 @@ let {
value = $bindable(''),
initialName = '',
suggestedName = '',
placeholder,
compact = false,
restrictToCorrespondentsOf,
onchange
onchange,
onfocused
}: Props = $props();
// searchTerm must be both prop-derived AND locally writable (user typing), so $state +
// $effect is the correct pattern here — writable $derived is read-only and won't work.
// eslint-disable-next-line svelte/prefer-writable-derived
let searchTerm = $state(initialName);
// Sync display text when the selected person changes externally (e.g. swap, navigation).
$effect(() => {
searchTerm = initialName;
});
$effect(() => {
const suggested = suggestedName;
if (suggested && !untrack(() => value)) {
@@ -79,6 +93,7 @@ function handleInput() {
}
function handleFocus() {
onfocused?.();
showDropdown = true;
if (restrictToCorrespondentsOf) {
const personId = untrack(() => restrictToCorrespondentsOf)!;
@@ -120,7 +135,13 @@ function clickOutside(node: HTMLElement) {
</script>
<div class="relative" use:clickOutside>
<label for={name} class="block text-sm font-medium text-ink-2">{label}</label>
<label
for={name}
class={compact
? 'block text-xs font-bold tracking-wide text-ink-3 uppercase'
: 'block text-sm font-medium text-ink-2'}
>{label}</label
>
<input type="hidden" name={name} bind:value={value} />
@@ -131,8 +152,10 @@ function clickOutside(node: HTMLElement) {
bind:value={searchTerm}
oninput={handleInput}
onfocus={handleFocus}
placeholder={m.comp_typeahead_placeholder()}
class="mt-1 block w-full rounded-md border border-line p-2 shadow-sm focus:border-accent focus:ring-accent"
placeholder={placeholder ?? m.comp_typeahead_placeholder()}
class={compact
? 'mt-1 block h-9 w-full rounded border border-line bg-surface px-2 text-sm text-ink placeholder:text-ink-3 focus:border-primary focus:outline-none'
: 'mt-1 block w-full rounded-md border border-line bg-surface p-2 text-ink shadow-sm placeholder:text-ink-3 focus:border-accent focus:ring-accent'}
/>
{#if showDropdown && (results.length > 0 || loading)}

View File

@@ -724,6 +724,8 @@ export interface paths {
patch?: never;
trace?: never;
};
// "/api/auth/reset-token-for-test" removed — @Operation(hidden=true) on AuthE2EController.
// Regenerate with `npm run generate:api` after the next backend build to keep in sync.
"/api/admin/import-status": {
parameters: {
query?: never;
@@ -1030,8 +1032,6 @@ export interface components {
/** Format: int32 */
totalPages?: number;
pageable?: components["schemas"]["PageableObject"];
first?: boolean;
last?: boolean;
/** Format: int32 */
size?: number;
content?: components["schemas"]["NotificationDTO"][];
@@ -1040,14 +1040,16 @@ export interface components {
sort?: components["schemas"]["SortObject"];
/** Format: int32 */
numberOfElements?: number;
first?: boolean;
last?: boolean;
empty?: boolean;
};
PageableObject: {
paged?: boolean;
/** Format: int32 */
pageNumber?: number;
/** Format: int32 */
pageSize?: number;
paged?: boolean;
/** Format: int64 */
offset?: number;
sort?: components["schemas"]["SortObject"];
@@ -2223,7 +2225,9 @@ export interface operations {
query?: {
page?: number;
size?: number;
/** @description Filter by notification type */
type?: "REPLY" | "MENTION";
/** @description Filter by read status */
read?: boolean;
};
header?: never;
@@ -2474,7 +2478,7 @@ export interface operations {
parameters: {
query: {
senderId: string;
receiverId: string;
receiverId?: string;
from?: string;
to?: string;
dir?: string;
@@ -2496,6 +2500,7 @@ export interface operations {
};
};
};
// getResetTokenForTest removed — @Operation(hidden=true) on AuthE2EController.
importStatus: {
parameters: {
query?: never;

View File

@@ -0,0 +1,109 @@
import { describe, expect, it } from 'vitest';
import { formatGermanDateInput, isoToGerman, germanToIso } from './date';
// ─── isoToGerman ─────────────────────────────────────────────────────────────
describe('isoToGerman', () => {
it('converts a valid ISO date to DD.MM.YYYY', () => {
expect(isoToGerman('2024-12-20')).toBe('20.12.2024');
});
it('returns empty string for empty input', () => {
expect(isoToGerman('')).toBe('');
});
it('returns empty string for invalid format', () => {
expect(isoToGerman('not-a-date')).toBe('');
});
});
// ─── germanToIso ─────────────────────────────────────────────────────────────
describe('germanToIso', () => {
it('converts DD.MM.YYYY to ISO', () => {
expect(germanToIso('20.12.2024')).toBe('2024-12-20');
});
it('returns empty string for partial input', () => {
expect(germanToIso('20.12')).toBe('');
});
it('returns empty string for empty input', () => {
expect(germanToIso('')).toBe('');
});
});
// ─── formatGermanDateInput ────────────────────────────────────────────────────
describe('formatGermanDateInput digit stream (no dots typed)', () => {
it('leaves 12 digits as-is', () => {
expect(formatGermanDateInput('2')).toBe('2');
expect(formatGermanDateInput('20')).toBe('20');
});
it('auto-inserts dot after 2 digits for 34 digit input', () => {
expect(formatGermanDateInput('201')).toBe('20.1');
expect(formatGermanDateInput('2012')).toBe('20.12');
});
it('auto-inserts two dots for 58 digit input', () => {
expect(formatGermanDateInput('20121')).toBe('20.12.1');
expect(formatGermanDateInput('20122024')).toBe('20.12.2024');
});
it('ignores digits beyond 8', () => {
expect(formatGermanDateInput('201220249')).toBe('20.12.2024');
});
});
describe('formatGermanDateInput manual dot entry with padding', () => {
it('pads single-digit day to 2 digits when dot is typed after it', () => {
expect(formatGermanDateInput('3.')).toBe('03.');
});
it('does not pad a 2-digit day', () => {
expect(formatGermanDateInput('03.')).toBe('03.');
expect(formatGermanDateInput('20.')).toBe('20.');
});
it('pads single-digit month to 2 digits when dot is typed after it', () => {
expect(formatGermanDateInput('03.3.')).toBe('03.03.');
});
it('does not pad a 2-digit month', () => {
expect(formatGermanDateInput('03.12.')).toBe('03.12.');
});
it('pads both day and month in a fully typed date', () => {
expect(formatGermanDateInput('3.3.2012')).toBe('03.03.2012');
});
it('pads only day when month is already 2 digits', () => {
expect(formatGermanDateInput('3.12.2024')).toBe('03.12.2024');
});
it('pads only month when day is already 2 digits', () => {
expect(formatGermanDateInput('20.3.2024')).toBe('20.03.2024');
});
it('handles a complete date entered with manual dots and no padding needed', () => {
expect(formatGermanDateInput('20.12.2024')).toBe('20.12.2024');
});
it('overflows excess day digits into month when dot follows', () => {
expect(formatGermanDateInput('123.')).toBe('12.3');
});
it('caps year digits at 4', () => {
expect(formatGermanDateInput('03.03.20249')).toBe('03.03.2024');
});
it('overflows excess month digits into year (digit stream then continue typing)', () => {
// User typed digits → auto-dot gave "20.12", then types "2" → raw becomes "20.122"
expect(formatGermanDateInput('20.122')).toBe('20.12.2');
});
it('continues building year after overflow', () => {
expect(formatGermanDateInput('20.12.2024')).toBe('20.12.2024');
});
});

View File

@@ -60,9 +60,9 @@ function handleOverlayKeydown(event: KeyboardEvent) {
</a>
<a
href="/conversations"
href="/korrespondenz"
class="inline-flex items-center px-3 py-1.5 font-sans text-xs font-bold tracking-widest uppercase transition-colors
{page.url.pathname.startsWith('/conversations')
{page.url.pathname.startsWith('/korrespondenz')
? 'rounded bg-nav-active text-ink'
: 'rounded text-ink-2 hover:bg-muted hover:text-ink'}"
>
@@ -161,9 +161,9 @@ function handleOverlayKeydown(event: KeyboardEvent) {
</a>
<a
href="/conversations"
href="/korrespondenz"
class="block flex min-h-[44px] w-full items-center px-4 py-3 font-sans text-sm font-bold tracking-widest uppercase transition-colors
{page.url.pathname.startsWith('/conversations')
{page.url.pathname.startsWith('/korrespondenz')
? 'bg-nav-active text-ink'
: 'text-ink-2 hover:bg-muted hover:text-ink'}"
>

View File

@@ -1,8 +1,9 @@
import { error } from '@sveltejs/kit';
import { createApiClient } from '$lib/api.server';
import { getErrorMessage } from '$lib/errors';
import type { components } from '$lib/generated/api';
type UserGroup = { permissions: string[] };
type UserGroup = components['schemas']['UserGroup'];
function hasPerm(user: { groups?: UserGroup[] } | undefined, perm: string): boolean {
return user?.groups?.some((g) => g.permissions.includes(perm)) ?? false;
@@ -22,19 +23,35 @@ export async function load({ fetch, locals }) {
if (!hasAnyAdminPerm(user)) throw error(403, getErrorMessage('FORBIDDEN'));
const api = createApiClient(fetch);
// TODO: replace with a dedicated /api/admin/stats endpoint that returns counts only,
// so the System page does not load full entity lists it does not render.
const [usersResult, groupsResult, tagsResult] = await Promise.all([
api.GET('/api/users'),
api.GET('/api/groups'),
api.GET('/api/tags')
]);
if (!usersResult.response.ok) {
const code = (usersResult.error as unknown as { code?: string })?.code;
throw error(usersResult.response.status, getErrorMessage(code));
}
if (!groupsResult.response.ok) {
const code = (groupsResult.error as unknown as { code?: string })?.code;
throw error(groupsResult.response.status, getErrorMessage(code));
}
if (!tagsResult.response.ok) {
const code = (tagsResult.error as unknown as { code?: string })?.code;
throw error(tagsResult.response.status, getErrorMessage(code));
}
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'),
canManagePermissions: hasPerm(user, 'ADMIN_PERMISSION'),
canRunMaintenance: hasPerm(user, 'ADMIN')
};
}

View File

@@ -12,7 +12,7 @@ let { data, children } = $props();
-mt-6: cancel the global layout's pt-6 on <main>
Height fills from below the global header (64px) to bottom of viewport.
-->
<div class="-mt-6 flex overflow-hidden" style="height: calc(100vh - 65px)">
<div class="-mt-6 -mb-6 flex overflow-hidden" style="height: calc(100vh - 65px)">
<!-- Entity Nav: hidden on mobile, icon strip on tablet, full labels on desktop -->
<div class="hidden md:flex">
<EntityNav
@@ -21,7 +21,7 @@ let { data, children } = $props();
tagCount={data.tagCount}
canManageUsers={data.canManageUsers}
canManageTags={data.canManageTags}
canManageGroups={data.canManageGroups}
canManagePermissions={data.canManagePermissions}
canRunMaintenance={data.canRunMaintenance}
/>
</div>

View File

@@ -36,7 +36,7 @@ onMount(() => {
</a>
{/if}
{#if data.canManageGroups}
{#if data.canManagePermissions}
<a href="/admin/groups" class="flex items-center justify-between px-4 py-4 hover:bg-muted">
<div>
<div class="font-sans text-sm font-bold text-ink">{m.admin_tab_groups()}</div>

View File

@@ -1,4 +1,6 @@
<script lang="ts">
import { tick } from 'svelte';
import { fly } from 'svelte/transition';
import { page } from '$app/state';
import { m } from '$lib/paraglide/messages.js';
@@ -8,7 +10,7 @@ let {
tagCount,
canManageUsers,
canManageTags,
canManageGroups,
canManagePermissions,
canRunMaintenance
}: {
userCount: number;
@@ -16,7 +18,7 @@ let {
tagCount: number;
canManageUsers: boolean;
canManageTags: boolean;
canManageGroups: boolean;
canManagePermissions: boolean;
canRunMaintenance: boolean;
} = $props();
@@ -24,10 +26,27 @@ const currentPath = $derived(page.url.pathname);
const isActive = (section: string) => currentPath.startsWith(`/admin/${section}`);
let flyoutOpen = $state(false);
let flyoutTriggerElement: HTMLButtonElement | null = null;
// All four section buttons open the same flyout that repeats the full nav.
// This is intentional: on tablet the flyout shows all sections as a wider navigation panel,
// not a context-specific panel for the clicked section.
async function openFlyout(event: MouseEvent) {
flyoutTriggerElement = event.currentTarget as HTMLButtonElement;
flyoutOpen = true;
await tick();
const firstLink = document.querySelector<HTMLAnchorElement>('[role="dialog"] a');
firstLink?.focus();
}
function closeFlyout() {
flyoutOpen = false;
flyoutTriggerElement?.focus();
}
function handleKeydown(event: KeyboardEvent) {
if (event.key === 'Escape' && flyoutOpen) {
flyoutOpen = false;
closeFlyout();
}
}
</script>
@@ -55,8 +74,9 @@ function handleKeydown(event: KeyboardEvent) {
data-flyout-trigger
type="button"
aria-label={m.admin_tab_users()}
onclick={() => (flyoutOpen = true)}
class="flex w-full flex-col items-center justify-center gap-0.5 border-l-[3px] py-3 transition-colors lg:hidden
title={m.admin_tab_users()}
onclick={openFlyout}
class="flex min-h-[44px] w-full flex-col items-center justify-center gap-0.5 border-l-[3px] py-3 transition-colors lg:hidden
{isActive('users')
? 'border-brand-mint bg-white/10'
: 'border-transparent hover:bg-white/5'}"
@@ -115,14 +135,15 @@ function handleKeydown(event: KeyboardEvent) {
</a>
{/if}
{#if canManageGroups}
{#if canManagePermissions}
<!-- Tablet trigger button (md only, hidden at lg) -->
<button
data-flyout-trigger
type="button"
aria-label={m.admin_tab_groups()}
onclick={() => (flyoutOpen = true)}
class="flex w-full flex-col items-center justify-center gap-0.5 border-l-[3px] py-3 transition-colors lg:hidden
title={m.admin_tab_groups()}
onclick={openFlyout}
class="flex min-h-[44px] w-full flex-col items-center justify-center gap-0.5 border-l-[3px] py-3 transition-colors lg:hidden
{isActive('groups')
? 'border-brand-mint bg-white/10'
: 'border-transparent hover:bg-white/5'}"
@@ -187,8 +208,9 @@ function handleKeydown(event: KeyboardEvent) {
data-flyout-trigger
type="button"
aria-label={m.admin_tab_tags()}
onclick={() => (flyoutOpen = true)}
class="flex w-full flex-col items-center justify-center gap-0.5 border-l-[3px] py-3 transition-colors lg:hidden
title={m.admin_tab_tags()}
onclick={openFlyout}
class="flex min-h-[44px] w-full flex-col items-center justify-center gap-0.5 border-l-[3px] py-3 transition-colors lg:hidden
{isActive('tags')
? 'border-brand-mint bg-white/10'
: 'border-transparent hover:bg-white/5'}"
@@ -257,8 +279,9 @@ function handleKeydown(event: KeyboardEvent) {
data-flyout-trigger
type="button"
aria-label={m.admin_tab_system()}
onclick={() => (flyoutOpen = true)}
class="flex w-full flex-col items-center justify-center gap-0.5 border-t border-l-[3px] border-white/10 py-3 transition-colors lg:hidden
title={m.admin_tab_system()}
onclick={openFlyout}
class="flex min-h-[44px] w-full flex-col items-center justify-center gap-0.5 border-t border-l-[3px] border-white/10 py-3 transition-colors lg:hidden
{isActive('system')
? 'border-brand-mint bg-white/10'
: 'border-l-transparent hover:bg-white/5'}"
@@ -320,7 +343,7 @@ function handleKeydown(event: KeyboardEvent) {
data-flyout-backdrop
role="none"
class="fixed inset-0 z-40 bg-black/40"
onclick={() => (flyoutOpen = false)}
onclick={closeFlyout}
></div>
<!-- Flyout panel -->
@@ -329,7 +352,7 @@ function handleKeydown(event: KeyboardEvent) {
aria-modal="true"
aria-label={m.admin_heading()}
class="fixed top-0 left-12 z-50 flex h-full w-40 flex-col bg-brand-navy shadow-xl"
style="transform: translateX(0); transition: transform 180ms ease-out;"
transition:fly={{ x: -160, duration: 180 }}
>
<!-- Heading -->
<div class="px-3 pt-3 pb-1 text-[9px] font-extrabold tracking-widest text-white/30 uppercase">
@@ -339,7 +362,7 @@ function handleKeydown(event: KeyboardEvent) {
{#if canManageUsers}
<a
href="/admin/users"
onclick={() => (flyoutOpen = false)}
onclick={closeFlyout}
class="flex flex-col items-start justify-center gap-0.5 border-l-[3px] px-3.5 py-2.5 transition-colors
{isActive('users')
? 'border-brand-mint bg-white/10'
@@ -374,10 +397,10 @@ function handleKeydown(event: KeyboardEvent) {
</a>
{/if}
{#if canManageGroups}
{#if canManagePermissions}
<a
href="/admin/groups"
onclick={() => (flyoutOpen = false)}
onclick={closeFlyout}
class="flex flex-col items-start justify-center gap-0.5 border-l-[3px] px-3.5 py-2.5 transition-colors
{isActive('groups')
? 'border-brand-mint bg-white/10'
@@ -415,7 +438,7 @@ function handleKeydown(event: KeyboardEvent) {
{#if canManageTags}
<a
href="/admin/tags"
onclick={() => (flyoutOpen = false)}
onclick={closeFlyout}
class="flex flex-col items-start justify-center gap-0.5 border-l-[3px] px-3.5 py-2.5 transition-colors
{isActive('tags')
? 'border-brand-mint bg-white/10'
@@ -454,7 +477,7 @@ function handleKeydown(event: KeyboardEvent) {
{#if canRunMaintenance}
<a
href="/admin/system"
onclick={() => (flyoutOpen = false)}
onclick={closeFlyout}
class="flex flex-col items-start justify-center gap-0.5 border-t border-l-[3px] border-white/10 px-3.5 py-2.5 transition-colors
{isActive('system')
? 'border-brand-mint bg-white/10'

View File

@@ -15,7 +15,7 @@ const props = {
tagCount: 8,
canManageUsers: true,
canManageTags: true,
canManageGroups: true,
canManagePermissions: true,
canRunMaintenance: true
};

View File

@@ -16,17 +16,15 @@ let {
autocollapse?: boolean;
} = $props();
let isCollapsed = $state(
typeof localStorage !== 'undefined' && localStorage.getItem('admin_list_collapsed') === 'true'
let manualCollapse = $state(
typeof localStorage !== 'undefined' &&
localStorage.getItem('admin_groups_list_collapsed') === 'true'
);
$effect(() => {
if (autocollapse) isCollapsed = true;
});
const isCollapsed = $derived(autocollapse || manualCollapse);
$effect(() => {
if (typeof localStorage !== 'undefined') {
localStorage.setItem('admin_list_collapsed', String(isCollapsed));
localStorage.setItem('admin_groups_list_collapsed', String(manualCollapse));
}
});
</script>
@@ -34,7 +32,7 @@ $effect(() => {
{#if isCollapsed}
<!-- Collapsed handle: 32px -->
<button
onclick={() => (isCollapsed = false)}
onclick={() => (manualCollapse = false)}
aria-label={m.admin_btn_expand_list()}
class="flex w-8 flex-shrink-0 flex-col items-center gap-2 border-r border-line bg-surface pt-2 hover:bg-muted"
>
@@ -74,7 +72,7 @@ $effect(() => {
</svg>
</a>
<button
onclick={() => (isCollapsed = true)}
onclick={() => (manualCollapse = true)}
aria-label={m.admin_btn_collapse_list()}
class="flex h-6 w-6 items-center justify-center rounded-sm text-xs font-bold text-ink-2 transition-colors hover:bg-muted"
>

View File

@@ -7,7 +7,7 @@ let { data, form } = $props();
let isDirty = $state(false);
let showUnsavedWarning = $state(false);
let discardTarget = $state<string | null>(null);
let discardTarget: string | null = $state(null);
beforeNavigate(({ cancel, to }) => {
if (isDirty) {
@@ -24,23 +24,38 @@ $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' }
];
const STANDARD_PERMISSIONS = $derived([
{ value: 'READ_ALL', label: m.admin_perm_read_all() },
{ value: 'ANNOTATE_ALL', label: m.admin_perm_annotate_all() },
{ value: 'WRITE_ALL', label: m.admin_perm_write_all() }
]);
const ADMIN_PERMISSIONS: { value: string; label: string }[] = [
{ value: 'ADMIN', label: 'Vollzugriff (Admin)' },
{ value: 'ADMIN_USER', label: 'Benutzer verwalten' },
{ value: 'ADMIN_TAG', label: 'Schlagworte verwalten' },
{ value: 'ADMIN_PERMISSION', label: 'Berechtigungen verwalten' }
];
const ADMIN_PERMISSIONS = $derived([
{ value: 'ADMIN', label: m.admin_perm_admin() },
{ value: 'ADMIN_USER', label: m.admin_perm_admin_user() },
{ value: 'ADMIN_TAG', label: m.admin_perm_admin_tag() },
{ value: 'ADMIN_PERMISSION', label: m.admin_perm_admin_permission() }
]);
</script>
<div class="flex flex-1 flex-col overflow-hidden">
<!-- Header -->
<div class="flex items-center border-b border-line px-5 py-3">
<a
href="/admin/groups"
class="mr-3 inline-flex items-center gap-1 text-xs text-ink-3 hover:text-ink md:hidden"
>
<svg
class="h-4 w-4"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
aria-hidden="true"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
</svg>
</a>
<h2 class="flex-1 font-sans text-sm font-bold text-ink">
{m.admin_group_edit_heading({ name: data.group.name })}
</h2>

View File

@@ -0,0 +1,87 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { actions } from './+page.server';
const mockApi = {
PATCH: vi.fn(),
DELETE: vi.fn()
};
vi.mock('$lib/api.server', () => ({
createApiClient: () => mockApi
}));
beforeEach(() => vi.clearAllMocks());
// ─── update action ─────────────────────────────────────────────────────────────
describe('groups/[id] — update action', () => {
it('returns success: true when API responds ok', async () => {
mockApi.PATCH.mockResolvedValue({ response: { ok: true }, data: {} });
const formData = new FormData();
formData.set('name', 'Editors');
formData.append('permissions', 'WRITE_ALL');
const result = await actions.update({
params: { id: 'g1' },
request: { formData: async () => formData },
fetch
} as never);
expect(result).toEqual({ success: true });
});
it('returns fail with error message when API responds not ok', async () => {
mockApi.PATCH.mockResolvedValue({
response: { ok: false, status: 409 },
error: { code: 'GROUP_NOT_FOUND' }
});
const formData = new FormData();
formData.set('name', 'Editors');
const result = await actions.update({
params: { id: 'g1' },
request: { formData: async () => formData },
fetch
} as never);
expect((result as { status: number }).status).toBe(409);
});
});
// ─── delete action ─────────────────────────────────────────────────────────────
describe('groups/[id] — delete action', () => {
it('redirects to /admin/groups on successful delete', async () => {
mockApi.DELETE.mockResolvedValue({ response: { ok: true } });
let redirectUrl: string | null = null;
try {
await actions.delete({
params: { id: 'g1' },
fetch
} as never);
} catch (e: unknown) {
// SvelteKit redirect throws a Response-like object
const r = e as { location?: string; status?: number };
redirectUrl = r.location ?? null;
}
expect(redirectUrl).toBe('/admin/groups');
});
it('returns fail with error message when delete API responds not ok', async () => {
mockApi.DELETE.mockResolvedValue({
response: { ok: false, status: 403 },
error: { code: 'FORBIDDEN' }
});
const result = await actions.delete({
params: { id: 'g1' },
fetch
} as never);
expect((result as { status: number }).status).toBe(403);
});
});

View File

@@ -81,7 +81,7 @@ describe('GroupsListPanel — empty state', () => {
// ─── Collapse toggle ──────────────────────────────────────────────────────────
describe('GroupsListPanel — collapse toggle', () => {
beforeEach(() => localStorage.removeItem('admin_list_collapsed'));
beforeEach(() => localStorage.removeItem('admin_groups_list_collapsed'));
it('renders a collapse button with aria-label', async () => {
render(GroupsListPanel, { groups });
@@ -107,4 +107,12 @@ describe('GroupsListPanel — collapse toggle', () => {
.element(page.getByRole('button', { name: /Liste ausklappen/i }))
.toBeInTheDocument();
});
it('persists collapse state using the groups-specific localStorage key', async () => {
const setSpy = vi.spyOn(Storage.prototype, 'setItem');
render(GroupsListPanel, { groups });
document.querySelector<HTMLButtonElement>('[aria-label="Liste einklappen"]')!.click();
expect(setSpy).toHaveBeenCalledWith('admin_groups_list_collapsed', 'true');
setSpy.mockRestore();
});
});

View File

@@ -3,19 +3,23 @@ import { enhance } from '$app/forms';
import { beforeNavigate, goto } from '$app/navigation';
import { m } from '$lib/paraglide/messages.js';
const availableStandard = [{ value: 'WRITE_ALL', label: 'Lesen & Schreiben' }];
const availableAdmin = [
{ value: 'ADMIN', label: 'Vollzugriff (Admin)' },
{ value: 'ADMIN_USER', label: 'Benutzer verwalten' },
{ value: 'ADMIN_TAG', label: 'Schlagworte verwalten' },
{ value: 'ADMIN_PERMISSION', label: 'Berechtigungen verwalten' }
];
const availableStandard = $derived([
{ value: 'READ_ALL', label: m.admin_perm_read_all() },
{ value: 'ANNOTATE_ALL', label: m.admin_perm_annotate_all() },
{ value: 'WRITE_ALL', label: m.admin_perm_write_all() }
]);
const availableAdmin = $derived([
{ value: 'ADMIN', label: m.admin_perm_admin() },
{ value: 'ADMIN_USER', label: m.admin_perm_admin_user() },
{ value: 'ADMIN_TAG', label: m.admin_perm_admin_tag() },
{ value: 'ADMIN_PERMISSION', label: m.admin_perm_admin_permission() }
]);
let { form } = $props();
let isDirty = $state(false);
let showUnsavedWarning = $state(false);
let discardTarget = $state<string | null>(null);
let discardTarget: string | null = $state(null);
beforeNavigate(({ cancel, to }) => {
if (isDirty) {
@@ -31,6 +35,21 @@ beforeNavigate(({ cancel, to }) => {
<div
class="flex items-center border-b border-green-200 bg-green-50 px-5 py-3 dark:border-green-900 dark:bg-green-950/30"
>
<a
href="/admin/groups"
class="mr-3 inline-flex items-center gap-1 text-xs text-green-700 hover:text-green-900 md:hidden"
>
<svg
class="h-4 w-4"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
aria-hidden="true"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
</svg>
</a>
<h2 class="flex-1 font-sans text-sm font-bold text-green-800 dark:text-green-300">
{m.admin_group_new_heading()}
</h2>

View File

@@ -66,7 +66,7 @@ describe('admin layout load — permission check', () => {
expect(result.tagCount).toBe(3);
expect(result.canManageUsers).toBe(true);
expect(result.canManageTags).toBe(true);
expect(result.canManageGroups).toBe(true);
expect(result.canManagePermissions).toBe(true);
expect(result.canRunMaintenance).toBe(true);
});
});

View File

@@ -19,7 +19,7 @@ const fullPerms = {
tagCount: 7,
canManageUsers: true,
canManageTags: true,
canManageGroups: true,
canManagePermissions: true,
canRunMaintenance: true
};

View File

@@ -16,7 +16,7 @@ const fullData = {
tagCount: 7,
canManageUsers: true,
canManageTags: true,
canManageGroups: true,
canManagePermissions: true,
canRunMaintenance: true
};

View File

@@ -1,4 +1,5 @@
<script lang="ts">
import { onDestroy } from 'svelte';
import { m } from '$lib/paraglide/messages.js';
let backfillResult: number | null = $state(null);
@@ -52,9 +53,10 @@ async function triggerImport() {
$effect(() => {
fetchImportStatus();
return () => stopPolling();
});
onDestroy(() => stopPolling());
async function backfillVersions() {
backfillLoading = true;
backfillResult = null;

View File

@@ -1,4 +1,4 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import Page from './+page.svelte';
@@ -134,3 +134,56 @@ describe('Admin system page — mass import card', () => {
await expect.element(page.getByRole('button', { name: /Erneut starten/i })).toBeInTheDocument();
});
});
// ─── Polling lifecycle ────────────────────────────────────────────────────────
describe('Admin system page — polling lifecycle', () => {
let setIntervalSpy: MockInstance;
let clearIntervalSpy: MockInstance;
beforeEach(() => {
setIntervalSpy = vi.spyOn(globalThis, 'setInterval');
clearIntervalSpy = vi.spyOn(globalThis, 'clearInterval');
});
afterEach(() => {
setIntervalSpy.mockRestore();
clearIntervalSpy.mockRestore();
});
it('starts polling when initial status is RUNNING', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
state: 'RUNNING',
message: 'Import läuft...',
processed: 0,
startedAt: '2026-01-01T10:00:00'
})
})
);
render(Page, {});
await expect.element(page.getByText(/Import läuft/i)).toBeInTheDocument();
expect(setIntervalSpy).toHaveBeenCalled();
});
it('does not start polling when initial status is IDLE', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
state: 'IDLE',
message: '',
processed: 0,
startedAt: null
})
})
);
render(Page, {});
await expect.element(page.getByRole('button', { name: /Import starten/i })).toBeInTheDocument();
expect(setIntervalSpy).not.toHaveBeenCalled();
});
});

View File

@@ -15,17 +15,15 @@ let {
autocollapse?: boolean;
} = $props();
let isCollapsed = $state(
typeof localStorage !== 'undefined' && localStorage.getItem('admin_list_collapsed') === 'true'
let manualCollapse = $state(
typeof localStorage !== 'undefined' &&
localStorage.getItem('admin_tags_list_collapsed') === 'true'
);
$effect(() => {
if (autocollapse) isCollapsed = true;
});
const isCollapsed = $derived(autocollapse || manualCollapse);
$effect(() => {
if (typeof localStorage !== 'undefined') {
localStorage.setItem('admin_list_collapsed', String(isCollapsed));
localStorage.setItem('admin_tags_list_collapsed', String(manualCollapse));
}
});
</script>
@@ -33,7 +31,7 @@ $effect(() => {
{#if isCollapsed}
<!-- Collapsed handle: 32px -->
<button
onclick={() => (isCollapsed = false)}
onclick={() => (manualCollapse = false)}
aria-label={m.admin_btn_expand_list()}
class="flex w-8 flex-shrink-0 flex-col items-center gap-2 border-r border-line bg-surface pt-2 hover:bg-muted"
>
@@ -55,7 +53,7 @@ $effect(() => {
{m.admin_tags_list_title()}
</span>
<button
onclick={() => (isCollapsed = true)}
onclick={() => (manualCollapse = true)}
aria-label={m.admin_btn_collapse_list()}
class="flex h-6 w-6 items-center justify-center rounded-sm text-xs font-bold text-ink-2 transition-colors hover:bg-muted"
>

View File

@@ -10,7 +10,7 @@ const deleteEnabled = $derived(deleteConfirmName === data.tag.name);
let isDirty = $state(false);
let showUnsavedWarning = $state(false);
let discardTarget = $state<string | null>(null);
let discardTarget: string | null = $state(null);
beforeNavigate(({ cancel, to }) => {
if (isDirty) {
@@ -31,6 +31,21 @@ $effect(() => {
<div class="flex flex-1 flex-col overflow-hidden">
<!-- Detail panel header -->
<div class="flex items-center border-b border-line px-5 py-3">
<a
href="/admin/tags"
class="mr-3 inline-flex items-center gap-1 text-xs text-ink-3 hover:text-ink md:hidden"
>
<svg
class="h-4 w-4"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
aria-hidden="true"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
</svg>
</a>
<h2 class="flex-1 font-sans text-sm font-bold text-ink">
{m.admin_tag_edit_heading({ name: data.tag.name })}
</h2>

View File

@@ -0,0 +1,85 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { actions } from './+page.server';
const mockApi = {
PUT: vi.fn(),
DELETE: vi.fn()
};
vi.mock('$lib/api.server', () => ({
createApiClient: () => mockApi
}));
beforeEach(() => vi.clearAllMocks());
// ─── update action ─────────────────────────────────────────────────────────────
describe('tags/[id] — update action', () => {
it('returns success: true when API responds ok', async () => {
mockApi.PUT.mockResolvedValue({ response: { ok: true }, data: {} });
const formData = new FormData();
formData.set('name', 'Archiv');
const result = await actions.update({
params: { id: 't1' },
request: { formData: async () => formData },
fetch
} as never);
expect(result).toEqual({ success: true });
});
it('returns fail with error message when API responds not ok', async () => {
mockApi.PUT.mockResolvedValue({
response: { ok: false, status: 409 },
error: { code: 'TAG_CONFLICT' }
});
const formData = new FormData();
formData.set('name', 'Archiv');
const result = await actions.update({
params: { id: 't1' },
request: { formData: async () => formData },
fetch
} as never);
expect((result as { status: number }).status).toBe(409);
});
});
// ─── delete action ─────────────────────────────────────────────────────────────
describe('tags/[id] — delete action', () => {
it('redirects to /admin/tags on successful delete', async () => {
mockApi.DELETE.mockResolvedValue({ response: { ok: true } });
let redirectUrl: string | null = null;
try {
await actions.delete({
params: { id: 't1' },
fetch
} as never);
} catch (e: unknown) {
const r = e as { location?: string; status?: number };
redirectUrl = r.location ?? null;
}
expect(redirectUrl).toBe('/admin/tags');
});
it('returns fail with error message when delete API responds not ok', async () => {
mockApi.DELETE.mockResolvedValue({
response: { ok: false, status: 403 },
error: { code: 'FORBIDDEN' }
});
const result = await actions.delete({
params: { id: 't1' },
fetch
} as never);
expect((result as { status: number }).status).toBe(403);
});
});

View File

@@ -63,7 +63,7 @@ describe('TagsListPanel — empty state', () => {
// ─── Collapse toggle ──────────────────────────────────────────────────────────
describe('TagsListPanel — collapse toggle', () => {
beforeEach(() => localStorage.removeItem('admin_list_collapsed'));
beforeEach(() => localStorage.removeItem('admin_tags_list_collapsed'));
it('renders a collapse button with aria-label', async () => {
render(TagsListPanel, { tags });
@@ -86,4 +86,12 @@ describe('TagsListPanel — collapse toggle', () => {
.element(page.getByRole('button', { name: /Liste ausklappen/i }))
.toBeInTheDocument();
});
it('persists collapse state using the tags-specific localStorage key', async () => {
const setSpy = vi.spyOn(Storage.prototype, 'setItem');
render(TagsListPanel, { tags });
document.querySelector<HTMLButtonElement>('[aria-label="Liste einklappen"]')!.click();
expect(setSpy).toHaveBeenCalledWith('admin_tags_list_collapsed', 'true');
setSpy.mockRestore();
});
});

View File

@@ -25,17 +25,15 @@ let {
} = $props();
let searchQuery = $state('');
let isCollapsed = $state(
typeof localStorage !== 'undefined' && localStorage.getItem('admin_list_collapsed') === 'true'
let manualCollapse = $state(
typeof localStorage !== 'undefined' &&
localStorage.getItem('admin_users_list_collapsed') === 'true'
);
$effect(() => {
if (autocollapse) isCollapsed = true;
});
const isCollapsed = $derived(autocollapse || manualCollapse);
$effect(() => {
if (typeof localStorage !== 'undefined') {
localStorage.setItem('admin_list_collapsed', String(isCollapsed));
localStorage.setItem('admin_users_list_collapsed', String(manualCollapse));
}
});
@@ -53,7 +51,7 @@ const filtered = $derived(
{#if isCollapsed}
<!-- Collapsed handle: 32px -->
<button
onclick={() => (isCollapsed = false)}
onclick={() => (manualCollapse = false)}
aria-label={m.admin_btn_expand_list()}
class="flex w-8 flex-shrink-0 flex-col items-center gap-2 border-r border-line bg-surface pt-2 hover:bg-muted"
>
@@ -93,7 +91,7 @@ const filtered = $derived(
</svg>
</a>
<button
onclick={() => (isCollapsed = true)}
onclick={() => (manualCollapse = true)}
aria-label={m.admin_btn_collapse_list()}
class="flex h-6 w-6 items-center justify-center rounded-sm text-xs font-bold text-ink-2 transition-colors hover:bg-muted"
>

View File

@@ -12,7 +12,7 @@ const selectedGroupIds = $derived(data.editUser.groups?.map((g: { id: string })
let isDirty = $state(false);
let showUnsavedWarning = $state(false);
let discardTarget = $state<string | null>(null);
let discardTarget: string | null = $state(null);
beforeNavigate(({ cancel, to }) => {
if (isDirty) {
@@ -33,6 +33,21 @@ $effect(() => {
<div class="flex flex-1 flex-col overflow-hidden">
<!-- Detail panel header -->
<div class="flex items-center border-b border-line px-5 py-3">
<a
href="/admin/users"
class="mr-3 inline-flex items-center gap-1 text-xs text-ink-3 hover:text-ink md:hidden"
>
<svg
class="h-4 w-4"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
aria-hidden="true"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
</svg>
</a>
<h2 class="flex-1 font-sans text-sm font-bold text-ink">
{m.admin_user_edit_heading({ username: data.editUser.username })}
</h2>

View File

@@ -97,7 +97,7 @@ describe('UsersListPanel — empty state', () => {
// ─── Collapse toggle ──────────────────────────────────────────────────────────
describe('UsersListPanel — collapse toggle', () => {
beforeEach(() => localStorage.removeItem('admin_list_collapsed'));
beforeEach(() => localStorage.removeItem('admin_users_list_collapsed'));
it('renders a collapse button with aria-label', async () => {
render(UsersListPanel, { users });
@@ -129,4 +129,12 @@ describe('UsersListPanel — collapse toggle', () => {
.element(page.getByRole('button', { name: /Liste ausklappen/i }))
.toBeInTheDocument();
});
it('persists collapse state using the users-specific localStorage key', async () => {
const setSpy = vi.spyOn(Storage.prototype, 'setItem');
render(UsersListPanel, { users });
document.querySelector<HTMLButtonElement>('[aria-label="Liste einklappen"]')!.click();
expect(setSpy).toHaveBeenCalledWith('admin_users_list_collapsed', 'true');
setSpy.mockRestore();
});
});

View File

@@ -10,7 +10,7 @@ let { data, form } = $props();
let isDirty = $state(false);
let showUnsavedWarning = $state(false);
let discardTarget = $state<string | null>(null);
let discardTarget: string | null = $state(null);
beforeNavigate(({ cancel, to }) => {
if (isDirty) {
@@ -24,6 +24,21 @@ beforeNavigate(({ cancel, to }) => {
<div class="flex flex-1 flex-col overflow-hidden">
<!-- Detail panel header -->
<div class="flex items-center border-b border-line px-5 py-3">
<a
href="/admin/users"
class="mr-3 inline-flex items-center gap-1 text-xs text-ink-3 hover:text-ink md:hidden"
>
<svg
class="h-4 w-4"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
aria-hidden="true"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
</svg>
</a>
<h2 class="flex-1 font-sans text-sm font-bold text-ink">{m.admin_user_new_heading()}</h2>
</div>

View File

@@ -0,0 +1,82 @@
import { error } from '@sveltejs/kit';
import type { components } from '$lib/generated/api';
import { createApiClient } from '$lib/api.server';
import { getErrorMessage } from '$lib/errors';
export async function load({ url, fetch, locals }) {
const senderId = url.searchParams.get('senderId') || '';
const receiverId = url.searchParams.get('receiverId') || '';
const from = url.searchParams.get('from') || '';
const to = url.searchParams.get('to') || '';
const dir = url.searchParams.get('dir') || 'DESC';
const canWrite =
(locals.user as { groups?: { permissions: string[] }[] } | undefined)?.groups?.some((g) =>
g.permissions.includes('WRITE_ALL')
) ?? false;
const api = createApiClient(fetch);
let documents: components['schemas']['Document'][] = [];
let senderName = '';
let receiverName = '';
const requests: Promise<void>[] = [];
if (senderId) {
requests.push(
api
.GET('/api/documents/conversation', {
params: {
query: {
senderId,
receiverId: receiverId || undefined,
dir,
from: from || undefined,
to: to || undefined
}
}
})
.then((result) => {
if (!result.response.ok) {
const code = (result.error as unknown as { code?: string })?.code;
throw error(result.response.status, getErrorMessage(code));
}
documents = result.data ?? [];
})
);
requests.push(
api.GET('/api/persons/{id}', { params: { path: { id: senderId } } }).then((result) => {
if (!result.response.ok) {
const code = (result.error as unknown as { code?: string })?.code;
throw error(result.response.status, getErrorMessage(code));
}
const p = result.data as { firstName: string; lastName: string } | undefined;
if (p) senderName = `${p.firstName} ${p.lastName}`;
})
);
}
if (receiverId) {
requests.push(
api.GET('/api/persons/{id}', { params: { path: { id: receiverId } } }).then((result) => {
if (!result.response.ok) {
const code = (result.error as unknown as { code?: string })?.code;
throw error(result.response.status, getErrorMessage(code));
}
const p = result.data as { firstName: string; lastName: string } | undefined;
if (p) receiverName = `${p.firstName} ${p.lastName}`;
})
);
}
await Promise.all(requests);
return {
documents,
canWrite,
initialValues: { senderName, receiverName },
filters: { senderId, receiverId, from, to, dir }
};
}

View File

@@ -0,0 +1,140 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { untrack } from 'svelte';
import { SvelteURLSearchParams } from 'svelte/reactivity';
import CorrespondenzPersonBar from './CorrespondenzPersonBar.svelte';
import CorrespondenzFilterControls from './CorrespondenzFilterControls.svelte';
import SinglePersonHintBar from './SinglePersonHintBar.svelte';
import ConversationTimeline from './ConversationTimeline.svelte';
import CorrespondenzEmptyState from './CorrespondenzEmptyState.svelte';
import { m } from '$lib/paraglide/messages.js';
let { data } = $props();
// Filter values are local $state so swapPersons/toggleSort can mutate them before goto.
// They are initialised once from server data and never re-synced — navigation replaces
// the page component, so each load gets a fresh init.
let senderId = $state(untrack(() => data.filters.senderId));
let receiverId = $state(untrack(() => data.filters.receiverId));
let fromDate = $state(untrack(() => data.filters.from));
let toDate = $state(untrack(() => data.filters.to));
let sortDir = $state(untrack(() => data.filters.dir));
// Names are pure reads of server data — no local mutation needed.
const senderName = $derived(data.initialValues.senderName);
const receiverName = $derived(data.initialValues.receiverName);
// Side-effect only: persist the resolved sender to localStorage once the name is available.
$effect(() => {
if (data.filters.senderId && data.initialValues.senderName) {
persistRecentPerson(data.filters.senderId, data.initialValues.senderName);
}
});
const isSinglePerson = $derived(!!senderId && !receiverId);
const RECENT_STORAGE_KEY = 'korrespondenz_recent_persons';
const MAX_RECENT = 5;
function persistRecentPerson(id: string, name: string) {
if (!id) return;
try {
const raw = localStorage.getItem(RECENT_STORAGE_KEY);
const existing: { id: string; name: string }[] = raw ? JSON.parse(raw) : [];
const filtered = existing.filter((p) => p.id !== id);
const updated = [{ id, name }, ...filtered].slice(0, MAX_RECENT);
localStorage.setItem(RECENT_STORAGE_KEY, JSON.stringify(updated));
} catch {
// localStorage unavailable — silently ignore
}
}
function applyFilters() {
const params = new SvelteURLSearchParams();
if (senderId) params.set('senderId', senderId);
if (receiverId) params.set('receiverId', receiverId);
if (fromDate) params.set('from', fromDate);
if (toDate) params.set('to', toDate);
params.set('dir', sortDir);
goto(`/korrespondenz?${params.toString()}`, { keepFocus: true });
}
function toggleSort() {
sortDir = sortDir === 'DESC' ? 'ASC' : 'DESC';
applyFilters();
}
function swapPersons() {
const tmp = senderId;
senderId = receiverId;
receiverId = tmp;
applyFilters();
}
function selectPerson(id: string) {
if (!id) {
document.querySelector<HTMLInputElement>('#senderId-search')?.focus();
return;
}
senderId = id;
receiverId = '';
applyFilters();
}
</script>
<!-- Strips — pulled up to negate main's py-6 top padding so they sit flush -->
<div class="-mt-6">
<!-- Strip: Row 1 — full width, no container -->
<CorrespondenzPersonBar
bind:senderId={senderId}
bind:receiverId={receiverId}
initialSenderName={data.initialValues.senderName}
initialReceiverName={data.initialValues.receiverName}
onapplyFilters={applyFilters}
onswapPersons={swapPersons}
/>
<!-- Strip: Row 2 — full width -->
<CorrespondenzFilterControls
senderId={senderId}
bind:fromDate={fromDate}
bind:toDate={toDate}
bind:sortDir={sortDir}
documentCount={data.documents.length}
onapplyFilters={applyFilters}
ontoggleSort={toggleSort}
/>
<!-- Single-person hint bar -->
{#if isSinglePerson}
<SinglePersonHintBar
senderName={senderName}
fromDate={fromDate || undefined}
toDate={toDate || undefined}
sortDir={sortDir}
/>
{/if}
</div>
<!-- Content area with padding -->
<div class="px-[18px] py-[14px]">
{#if !senderId}
<CorrespondenzEmptyState onSelectPerson={selectPerson} />
{:else if data.documents.length === 0}
<div
class="flex flex-col items-center justify-center rounded-sm border border-line bg-muted py-24 text-center shadow-sm"
>
<p class="font-serif text-ink">{m.conv_no_results_heading()}</p>
<p class="mt-2 text-sm text-ink-3">{m.conv_no_results_text()}</p>
</div>
{:else}
<ConversationTimeline
documents={data.documents}
senderId={senderId}
receiverId={receiverId}
canWrite={data.canWrite}
senderName={senderName}
receiverName={receiverName}
/>
{/if}
</div>

View File

@@ -0,0 +1,142 @@
<script lang="ts">
import PersonTypeahead from '$lib/components/PersonTypeahead.svelte';
import { m } from '$lib/paraglide/messages.js';
let {
senderId = $bindable(''),
receiverId = $bindable(''),
fromDate = $bindable(''),
toDate = $bindable(''),
sortDir = $bindable('DESC'),
initialSenderName = '',
initialReceiverName = '',
onapplyFilters,
ontoggleSort,
onswapPersons
}: {
senderId?: string;
receiverId?: string;
fromDate?: string;
toDate?: string;
sortDir?: string;
initialSenderName?: string;
initialReceiverName?: string;
onapplyFilters: () => void;
ontoggleSort: () => void;
onswapPersons: () => void;
} = $props();
</script>
<div class="relative z-20 mb-10 border border-line bg-surface p-8 shadow-sm">
<div class="mb-6 grid grid-cols-1 items-end gap-4 md:grid-cols-[1fr_auto_1fr] md:gap-6">
<!-- Sender -->
<div
class="relative z-30 [&_input]:border-line [&_input]:py-2.5 [&_input]:focus:border-ink [&_input]:focus:ring-ink [&_label]:mb-2 [&_label]:text-xs [&_label]:font-bold [&_label]:tracking-widest [&_label]:text-ink-2 [&_label]:uppercase"
>
<PersonTypeahead
name="senderId"
label={m.conv_label_person_a()}
bind:value={senderId}
initialName={initialSenderName}
restrictToCorrespondentsOf={receiverId || undefined}
onchange={() => onapplyFilters()}
/>
</div>
<!-- Swap button -->
<div class="{senderId && receiverId ? 'flex' : 'hidden md:flex'} items-end">
<button
data-testid="conv-swap-btn"
onclick={onswapPersons}
class="flex w-full items-center justify-center gap-2 border border-line px-3 py-2.5 text-xs font-bold tracking-widest text-ink uppercase transition-colors hover:bg-primary hover:text-primary-fg md:w-auto {senderId &&
receiverId
? ''
: 'invisible'}"
title={m.conv_swap_btn()}
>
<svg
class="h-4 w-4 flex-shrink-0 md:rotate-90"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M7 16V4m0 0L3 8m4-4l4 4M17 8v12m0 0l4-4m-4 4l-4-4"
></path>
</svg>
<span class="md:hidden">{m.conv_swap_btn()}</span>
</button>
</div>
<!-- Receiver -->
<div
class="relative z-30 [&_input]:border-line [&_input]:py-2.5 [&_input]:focus:border-ink [&_input]:focus:ring-ink [&_label]:mb-2 [&_label]:text-xs [&_label]:font-bold [&_label]:tracking-widest [&_label]:text-ink-2 [&_label]:uppercase"
>
<PersonTypeahead
name="receiverId"
label={m.conv_label_person_b()}
bind:value={receiverId}
initialName={initialReceiverName}
restrictToCorrespondentsOf={senderId || undefined}
onchange={() => onapplyFilters()}
/>
</div>
</div>
<div class="relative z-10 grid grid-cols-1 items-end gap-6 md:grid-cols-3">
<!-- Date From -->
<div>
<label
for="dateFrom"
class="mb-2 block text-xs font-bold tracking-widest text-ink-2 uppercase"
>{m.conv_label_from()}</label
>
<input
id="dateFrom"
type="date"
bind:value={fromDate}
onchange={() => onapplyFilters()}
class="block w-full border-line py-2.5 text-sm shadow-sm focus:border-ink focus:ring-ink"
/>
</div>
<!-- Date To -->
<div>
<label for="dateTo" class="mb-2 block text-xs font-bold tracking-widest text-ink-2 uppercase"
>{m.conv_label_to()}</label
>
<input
id="dateTo"
type="date"
bind:value={toDate}
onchange={() => onapplyFilters()}
class="block w-full border-line py-2.5 text-sm shadow-sm focus:border-ink focus:ring-ink"
/>
</div>
<!-- Sort Toggle -->
<div>
<button
onclick={ontoggleSort}
class="flex h-[42px] w-full items-center justify-center border border-line text-xs font-bold tracking-wide text-ink uppercase transition-colors hover:bg-primary hover:text-primary-fg"
>
<span class="mr-2">{m.conv_sort_label()}</span>
<span>{sortDir === 'DESC' ? m.conv_sort_newest() : m.conv_sort_oldest()}</span>
<svg
class="ml-2 h-4 w-4 transform {sortDir === 'ASC'
? 'rotate-180'
: ''} transition-transform"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"
></path>
</svg>
</button>
</div>
</div>
</div>

View File

@@ -0,0 +1,180 @@
<script lang="ts">
import { formatDate } from '$lib/utils/date';
import { m } from '$lib/paraglide/messages.js';
interface Props {
documents: {
id: string;
title?: string;
originalFilename: string;
documentDate?: string;
location?: string;
status: string;
sender?: { id: string; firstName: string; lastName: string } | null;
receivers?: { id: string; firstName: string; lastName: string }[];
}[];
senderId: string;
receiverId?: string;
canWrite: boolean;
senderName?: string;
receiverName?: string;
}
let { documents, senderId, receiverId, canWrite, senderName, receiverName }: Props = $props();
const enrichedDocuments = $derived(
documents.map((doc, i) => {
const year = doc.documentDate ? new Date(doc.documentDate).getFullYear() : null;
const prevYear =
i > 0 && documents[i - 1].documentDate
? new Date(documents[i - 1].documentDate!).getFullYear()
: null;
const isOut = doc.sender?.id === senderId;
return { doc, year, showYearDivider: year !== null && year !== prevYear, isOut };
})
);
const countsByYear = $derived(
documents.reduce((acc, d) => {
if (d.documentDate) {
const y = new Date(d.documentDate).getFullYear();
acc.set(y, (acc.get(y) ?? 0) + 1);
}
return acc;
}, new Map<number, number>())
);
const outCount = $derived(documents.filter((d) => d.sender?.id === senderId).length);
const inCount = $derived(documents.length - outCount);
const outPct = $derived(documents.length > 0 ? (outCount / documents.length) * 100 : 0);
const isBilateral = $derived(!!senderId && !!receiverId);
const shortSenderName = $derived(senderName?.split(' ')[0] ?? senderName ?? '');
const shortReceiverName = $derived(receiverName?.split(' ')[0] ?? receiverName ?? '');
function statusDotClass(status: string): string {
const map: Record<string, string> = {
PLACEHOLDER: 'bg-brand-sand',
UPLOADED: 'bg-brand-mint',
TRANSCRIBED: 'bg-brand-mint',
REVIEWED: 'bg-brand-navy/70',
ARCHIVED: 'bg-brand-navy'
};
return map[status] ?? 'bg-brand-sand';
}
function otherPartyName(doc: (typeof documents)[number]): string {
if (doc.sender?.id === senderId) {
const r = doc.receivers?.[0];
return r ? `${r.firstName} ${r.lastName}` : m.conv_no_party();
}
return doc.sender ? `${doc.sender.firstName} ${doc.sender.lastName}` : m.conv_no_party();
}
const newDocUrl = $derived(
`/documents/new?senderId=${encodeURIComponent(senderId)}${receiverId ? `&receiverId=${encodeURIComponent(receiverId)}` : ''}`
);
</script>
{#if isBilateral && documents.length > 0}
<div
class="flex flex-col gap-1 border-b border-line bg-muted px-[18px] py-2"
role="img"
aria-label="Briefverteilung in diesem Zeitraum: {outCount} von {senderName ?? ''}, {inCount} von {receiverName ?? ''}"
>
<div class="flex justify-between text-sm font-bold">
<span class="text-primary">{outCount} von {shortSenderName}</span>
<span class="text-accent">{inCount} von {shortReceiverName}</span>
</div>
<div class="flex h-[5px] overflow-hidden rounded-full bg-line">
<div class="h-full bg-primary transition-all" style="width: {outPct}%"></div>
<div class="h-full bg-accent transition-all" style="width: {100 - outPct}%"></div>
</div>
</div>
{/if}
<div class="overflow-hidden rounded-sm border border-line bg-surface">
{#each enrichedDocuments as { doc, year, showYearDivider, isOut } (doc.id)}
{#if showYearDivider && year !== null}
<div
data-testid="year-divider"
class="flex items-baseline gap-3 border-t-2 border-b border-line bg-muted px-[14px] py-[8px]"
>
<span class="text-2xl font-black tracking-tight text-primary">{year}</span>
<span class="text-sm font-bold text-ink-3">{countsByYear.get(year) ?? 0} Briefe</span>
</div>
{/if}
<a
href="/documents/{doc.id}"
aria-label="{doc.title || doc.originalFilename}, {doc.documentDate
? formatDate(doc.documentDate)
: ''}"
class="group flex min-h-[44px] cursor-pointer items-center gap-[9px] border-b border-l-[3px] border-line-2 px-[14px] py-[10px] transition-colors last:border-b-0 hover:bg-muted"
class:border-l-primary={isOut}
class:border-l-accent={!isOut}
>
<span
class="w-[16px] shrink-0 text-sm font-black"
class:text-primary={isOut}
class:text-accent={!isOut}
aria-hidden="true"
>
{isOut ? '→' : '←'}
</span>
<div class="min-w-0 flex-1">
<div class="mb-[2px] truncate text-sm font-bold text-ink">
{doc.title || doc.originalFilename}
</div>
<div class="flex items-center gap-[5px] text-sm text-ink-3">
<span>{doc.documentDate ? formatDate(doc.documentDate) : '—'}</span>
{#if doc.location}
<span class="text-line">·</span>
<span>{doc.location}</span>
{/if}
{#if !receiverId}
<span class="text-line">·</span>
<span>{otherPartyName(doc)}</span>
{/if}
<span
class="ml-[3px] h-[6px] w-[6px] shrink-0 rounded-full {statusDotClass(doc.status)}"
title={doc.status}
></span>
</div>
</div>
<span
class="shrink-0 text-sm text-ink-3 opacity-0 transition-opacity group-hover:opacity-100"
aria-hidden="true"></span
>
</a>
{/each}
{#if canWrite}
<div class="flex justify-end border-t border-line px-[14px] py-[6px]">
<a
href={newDocUrl}
data-testid="conv-new-doc-link"
class="inline-flex items-center gap-1 text-xs font-bold text-primary/50 transition-colors hover:text-primary"
>
<svg
class="h-3 w-3"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 4v16m8-8H4"
/>
</svg>
{m.conv_new_doc_link()}
</a>
</div>
{/if}
</div>

View File

@@ -0,0 +1,112 @@
<script lang="ts">
import { m } from '$lib/paraglide/messages.js';
interface Correspondent {
id: string;
firstName: string;
lastName: string;
}
interface Props {
correspondents: Correspondent[];
loading: boolean;
senderName: string;
onselect: (id: string) => void;
onclose: () => void;
}
let { correspondents, loading, senderName, onselect, onclose }: Props = $props();
function clickOutside(node: HTMLElement) {
const handleClick = (event: MouseEvent) => {
if (node && !node.contains(event.target as Node) && !event.defaultPrevented) {
onclose();
}
};
document.addEventListener('click', handleClick, true);
return {
destroy() {
document.removeEventListener('click', handleClick, true);
}
};
}
function getOptionElements(container: HTMLElement): HTMLElement[] {
return Array.from(container.querySelectorAll<HTMLElement>('[role="option"]'));
}
function handleKeydown(event: KeyboardEvent, container: HTMLElement) {
const options = getOptionElements(container);
const focused = document.activeElement as HTMLElement;
const idx = options.indexOf(focused);
if (event.key === 'ArrowDown') {
event.preventDefault();
const next = options[idx + 1] ?? options[0];
next?.focus();
} else if (event.key === 'ArrowUp') {
event.preventDefault();
const prev = options[idx - 1] ?? options[options.length - 1];
prev?.focus();
} else if (event.key === 'Escape') {
onclose();
}
}
function getInitials(person: Correspondent): string {
return `${person.firstName.charAt(0)}${person.lastName.charAt(0)}`.toUpperCase();
}
</script>
<div
use:clickOutside
role="listbox"
tabindex="-1"
aria-label={m.conv_suggestions_heading()}
class="absolute top-full right-0 left-0 z-30 mt-1 rounded-sm border border-line bg-surface shadow-lg"
onkeydown={(e) => handleKeydown(e, e.currentTarget as HTMLElement)}
>
<!-- Heading -->
<div class="px-3 pt-2 pb-1 text-[10px] font-bold tracking-widest text-ink-3 uppercase">
{m.conv_suggestions_heading()}
</div>
<!-- Correspondent rows -->
{#if !loading}
{#each correspondents as person (person.id)}
<div
role="option"
aria-selected="false"
tabindex="0"
class="flex cursor-pointer items-center gap-2 px-3 py-2 text-sm text-ink hover:bg-muted focus:bg-muted focus:outline-none"
onclick={() => onselect(person.id)}
onkeydown={(e) => e.key === 'Enter' && onselect(person.id)}
>
<!-- Avatar with initials -->
<span
class="flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-primary text-[10px] font-bold text-primary-fg"
aria-hidden="true"
>
{getInitials(person)}
</span>
<!-- Svelte auto-escapes — do not use {@html} here. -->
{person.lastName}, {person.firstName}
</div>
{/each}
{/if}
<!-- Separator -->
<div class="mt-1 border-t border-line"></div>
<!-- "Alle Korrespondenten" row -->
<div
role="option"
aria-selected="false"
tabindex="0"
class="flex cursor-pointer items-center gap-2 px-3 py-2 text-sm text-ink hover:bg-muted focus:bg-muted focus:outline-none"
onclick={() => onselect('')}
onkeydown={(e) => e.key === 'Enter' && onselect('')}
>
{m.conv_suggestions_all_label({ name: senderName })}
</div>
</div>

View File

@@ -0,0 +1,120 @@
<script lang="ts">
import { onMount } from 'svelte';
import { m } from '$lib/paraglide/messages.js';
interface RecentPerson {
id: string;
name: string;
}
interface Props {
onSelectPerson: (id: string) => void;
}
const { onSelectPerson }: Props = $props();
let recentPersons = $state<RecentPerson[]>([]);
onMount(() => {
try {
const raw = localStorage.getItem('korrespondenz_recent_persons');
if (raw) {
// Svelte auto-escapes firstName/lastName — do not use {@html} with these values
recentPersons = JSON.parse(raw) as RecentPerson[];
}
} catch {
recentPersons = [];
}
});
</script>
<div class="mx-auto flex max-w-lg flex-col items-center gap-5 py-12 text-center">
<!-- Icon circle -->
<div class="rounded-full bg-muted p-5">
<svg
xmlns="http://www.w3.org/2000/svg"
width="36"
height="36"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
class="text-primary"
aria-hidden="true"
>
<rect x="2" y="4" width="20" height="16" rx="2" />
<path d="M2 7l10 7 10-7" />
</svg>
</div>
<!-- Heading -->
<h2 class="font-serif text-xl font-black text-ink">{m.conv_empty_heading()}</h2>
<!-- Subtext -->
<p class="max-w-sm text-base text-ink-3">
{m.conv_empty_text()}
</p>
<!-- Search input placeholder (visual only — clicking focuses Person A typeahead above) -->
<button
type="button"
data-testid="conv-empty-search"
aria-label={m.conv_empty_search_placeholder()}
onclick={() => onSelectPerson('')}
class="flex h-10 w-full max-w-sm items-center rounded border border-line bg-muted px-4 text-sm text-ink-3 italic transition-colors hover:border-primary"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="mr-2 shrink-0"
aria-hidden="true"
>
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.35-4.35" />
</svg>
{m.conv_empty_search_placeholder()}
</button>
<!-- Recent persons — only shown when localStorage has entries -->
{#if recentPersons.length > 0}
<!-- Divider -->
<div class="flex w-full max-w-sm items-center gap-2">
<div class="flex-1 border-t border-line"></div>
<span class="text-xs font-bold tracking-wider text-ink-3 uppercase">oder</span>
<div class="flex-1 border-t border-line"></div>
</div>
<div class="flex w-full max-w-sm flex-col items-center gap-3">
<span class="text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.conv_empty_recent_label()}
</span>
<div class="flex flex-wrap justify-center gap-2">
{#each recentPersons as person (person.id)}
<!-- TODO: allow clearing recent history -->
<button
type="button"
onclick={() => onSelectPerson(person.id)}
class="flex items-center gap-2 rounded-full border border-line bg-surface px-4 py-2 text-sm font-bold text-ink transition-colors hover:border-primary hover:text-primary"
>
<span
class="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-primary text-xs text-primary-fg"
aria-hidden="true"
>
{person.name.charAt(0).toUpperCase()}
</span>
{person.name}
</button>
{/each}
</div>
</div>
{/if}
</div>

View File

@@ -0,0 +1,115 @@
<script lang="ts">
import { m } from '$lib/paraglide/messages.js';
import DateInput from '$lib/components/DateInput.svelte';
interface Props {
senderId: string;
fromDate?: string;
toDate?: string;
sortDir?: string;
documentCount?: number;
onapplyFilters: () => void;
ontoggleSort: () => void;
}
let {
senderId,
fromDate = $bindable(''),
toDate = $bindable(''),
sortDir = $bindable('DESC'),
documentCount,
onapplyFilters,
ontoggleSort
}: Props = $props();
let hasDateFilter = $derived(!!(fromDate || toDate));
let isActive = $derived(!!(fromDate || toDate || sortDir !== 'DESC'));
</script>
<div
class="flex items-center gap-[10px] border-b border-line bg-muted px-4 py-[5px] transition-opacity sm:px-[18px]"
class:opacity-40={!senderId}
class:pointer-events-none={!senderId}
aria-disabled={!senderId}
>
<!-- Period label -->
<span class="hidden text-xs font-bold tracking-wide text-ink-3 uppercase sm:block">
{m.conv_strip_period()}
</span>
<!-- From date -->
<DateInput
bind:value={fromDate}
onchange={() => onapplyFilters()}
placeholder={m.conv_strip_from_placeholder()}
class="h-8 w-[100px] rounded border bg-surface px-2 text-xs text-ink focus:outline-none {fromDate ? 'border-primary' : 'border-line'}"
/>
<span class="text-xs text-ink-3"></span>
<!-- To date -->
<DateInput
bind:value={toDate}
onchange={() => onapplyFilters()}
placeholder={m.conv_strip_to_placeholder()}
class="h-8 w-[100px] rounded border bg-surface px-2 text-xs text-ink focus:outline-none {toDate ? 'border-primary' : 'border-line'}"
/>
<!-- Document count -->
<span
data-testid="conv-strip-count"
class="ml-auto text-xs font-bold"
class:text-primary={hasDateFilter}
class:text-ink-3={!hasDateFilter}
>
{m.conv_letters_count({ count: documentCount ?? 0 })}
</span>
<!-- Sort button -->
<button
data-testid="conv-sort-btn"
type="button"
aria-label="Sortierung umkehren"
aria-pressed={sortDir === 'ASC'}
onclick={ontoggleSort}
class="flex h-8 min-h-[44px] items-center gap-1 rounded border px-3 text-xs font-bold"
class:border-primary={isActive}
class:text-primary={isActive}
class:border-line={!isActive}
class:text-ink-3={!isActive}
>
{#if sortDir === 'ASC'}
{m.conv_strip_sort_oldest()}
<svg
xmlns="http://www.w3.org/2000/svg"
width="10"
height="10"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<polyline points="18 15 12 9 6 15" />
</svg>
{:else}
{m.conv_strip_sort_newest()}
<svg
xmlns="http://www.w3.org/2000/svg"
width="10"
height="10"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<polyline points="6 9 12 15 18 9" />
</svg>
{/if}
</button>
</div>

View File

@@ -0,0 +1,129 @@
<script lang="ts">
import PersonTypeahead from '$lib/components/PersonTypeahead.svelte';
import CorrespondentSuggestionsDropdown from './CorrespondentSuggestionsDropdown.svelte';
interface Props {
senderId?: string;
receiverId?: string;
initialSenderName?: string;
initialReceiverName?: string;
onapplyFilters: () => void;
onswapPersons: () => void;
}
let {
senderId = $bindable(''),
receiverId = $bindable(''),
initialSenderName = '',
initialReceiverName = '',
onapplyFilters,
onswapPersons
}: Props = $props();
interface Correspondent {
id: string;
firstName: string;
lastName: string;
}
let swapVisible = $derived(!!(senderId && receiverId));
let showSuggestions = $state(false);
let correspondents = $state<Correspondent[]>([]);
let loadingCorrespondents = $state(false);
async function handleCorrespondentFocused() {
if (!senderId) return;
showSuggestions = true;
loadingCorrespondents = true;
try {
const res = await fetch(`/api/persons/${senderId}/correspondents`);
correspondents = res.ok ? await res.json() : [];
} catch {
correspondents = [];
} finally {
loadingCorrespondents = false;
}
}
function handleSuggestionSelect(id: string) {
receiverId = id;
showSuggestions = false;
onapplyFilters();
}
</script>
<div class="flex items-end gap-[9px] border-b border-line bg-surface px-4 py-[9px] sm:px-[18px]">
<!-- Person A -->
<div class="min-w-0 flex-1">
<PersonTypeahead
name="senderId"
label="Person"
bind:value={senderId}
initialName={initialSenderName}
compact={true}
restrictToCorrespondentsOf={receiverId || undefined}
onchange={() => onapplyFilters()}
/>
</div>
<!-- Swap button -->
<button
data-testid="conv-swap-btn"
type="button"
aria-label="Personen tauschen"
onclick={onswapPersons}
class="flex h-9 w-9 shrink-0 items-center justify-center rounded border border-line bg-surface text-ink-3 transition-colors hover:border-primary hover:text-primary"
class:opacity-0={!swapVisible}
class:pointer-events-none={!swapVisible}
tabindex={swapVisible ? 0 : -1}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M7 16V4m0 0L3 8m4-4l4 4" />
<path d="M17 8v12m0 0l4-4m-4 4l-4-4" />
</svg>
</button>
<!-- Korrespondent field -->
<div
class="relative min-w-0 flex-1"
class:[&_input]:border-dashed={!receiverId}
class:[&_input]:border-solid={!!receiverId}
class:[&_input]:bg-canvas={!receiverId}
>
<PersonTypeahead
name="receiverId"
label={receiverId ? 'Korrespondent' : 'Korrespondent — optional'}
bind:value={receiverId}
initialName={initialReceiverName}
compact={true}
placeholder="Alle Korrespondenten"
restrictToCorrespondentsOf={senderId || undefined}
onchange={() => {
showSuggestions = false;
onapplyFilters();
}}
onfocused={handleCorrespondentFocused}
/>
{#if showSuggestions && senderId && !receiverId}
<CorrespondentSuggestionsDropdown
correspondents={correspondents}
loading={loadingCorrespondents}
senderName=""
onselect={handleSuggestionSelect}
onclose={() => (showSuggestions = false)}
/>
{/if}
</div>
</div>

View File

@@ -0,0 +1,50 @@
<script lang="ts">
import { m } from '$lib/paraglide/messages.js';
interface Props {
senderName: string;
fromDate?: string;
toDate?: string;
sortDir?: string;
}
let { senderName, fromDate = '', toDate = '', sortDir = 'DESC' }: Props = $props();
let hasDateFilter = $derived(!!(fromDate || toDate));
let sortLabel = $derived(
sortDir === 'ASC' ? m.conv_strip_sort_oldest() : m.conv_strip_sort_newest()
);
let fromYear = $derived(fromDate ? fromDate.substring(0, 4) : '');
let toYear = $derived(toDate ? toDate.substring(0, 4) : '');
</script>
<div
class="flex items-center gap-[5px] border-b border-accent bg-accent-bg px-[18px] py-[6px] text-xs text-ink"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
class="shrink-0"
>
<path d="M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2" />
<rect x="9" y="3" width="6" height="4" rx="1" />
</svg>
{#if hasDateFilter}
<strong>{senderName}</strong>
<span>·</span>
<span>{fromYear}{toYear}</span>
<span>·</span>
<span>{sortLabel}</span>
{:else}
Alle Briefe von <strong>{senderName}</strong> — wähle einen Korrespondenten oben um einzugrenzen
{/if}
</div>

View File

@@ -0,0 +1,146 @@
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { load } from './+page.server';
vi.mock('$lib/api.server', () => ({ createApiClient: vi.fn() }));
vi.mock('$lib/errors', () => ({ getErrorMessage: (code: string) => code ?? 'Unknown error' }));
import { createApiClient } from '$lib/api.server';
const writeUser = { groups: [{ permissions: ['WRITE_ALL'] }] };
const readUser = { groups: [{ permissions: ['READ_ALL'] }] };
function makeUrl(params: Record<string, string> = {}): URL {
const url = new URL('http://x/korrespondenz');
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
return url;
}
function mockApi(calls: { ok: boolean; data?: unknown; status?: number }[]) {
const GET = vi.fn();
for (const call of calls) {
GET.mockResolvedValueOnce({
response: { ok: call.ok, status: call.status ?? (call.ok ? 200 : 500) },
data: call.data,
error: call.ok ? undefined : { code: 'INTERNAL_ERROR' }
});
}
vi.mocked(createApiClient).mockReturnValue({ GET } as ReturnType<typeof createApiClient>);
return GET;
}
beforeEach(() => vi.clearAllMocks());
// ─── No senderId ──────────────────────────────────────────────────────────────
describe('korrespondenz load — no senderId', () => {
it('returns empty documents without calling the conversation endpoint', async () => {
const GET = mockApi([]);
const result = await load({
url: makeUrl(),
fetch: vi.fn() as unknown as typeof fetch,
locals: { user: readUser }
});
expect(result.documents).toEqual([]);
expect(GET).not.toHaveBeenCalled();
});
});
// ─── With senderId, no receiverId ────────────────────────────────────────────
describe('korrespondenz load — senderId set, no receiverId', () => {
it('calls the conversation endpoint and the sender person endpoint', async () => {
const docs = [{ id: 'd1', title: 'Testbrief' }];
const GET = mockApi([
{ ok: true, data: docs },
{ ok: true, data: { firstName: 'Hans', lastName: 'Müller' } }
]);
const result = await load({
url: makeUrl({ senderId: 'p1' }),
fetch: vi.fn() as unknown as typeof fetch,
locals: { user: readUser }
});
expect(result.documents).toEqual(docs);
expect(result.initialValues.senderName).toBe('Hans Müller');
expect(result.initialValues.receiverName).toBe('');
expect(GET).toHaveBeenCalledTimes(2);
});
});
// ─── With senderId and receiverId ────────────────────────────────────────────
describe('korrespondenz load — senderId and receiverId set', () => {
it('calls conversation, sender person, and receiver person endpoints', async () => {
const GET = mockApi([
{ ok: true, data: [] },
{ ok: true, data: { firstName: 'Hans', lastName: 'Müller' } },
{ ok: true, data: { firstName: 'Anna', lastName: 'Schmidt' } }
]);
const result = await load({
url: makeUrl({ senderId: 'p1', receiverId: 'p2' }),
fetch: vi.fn() as unknown as typeof fetch,
locals: { user: readUser }
});
expect(result.initialValues.senderName).toBe('Hans Müller');
expect(result.initialValues.receiverName).toBe('Anna Schmidt');
expect(GET).toHaveBeenCalledTimes(3);
});
});
// ─── canWrite derivation ─────────────────────────────────────────────────────
describe('korrespondenz load — canWrite', () => {
it('derives canWrite true from WRITE_ALL permission', async () => {
mockApi([
{ ok: true, data: [] },
{ ok: true, data: { firstName: 'Hans', lastName: 'Müller' } }
]);
const result = await load({
url: makeUrl({ senderId: 'p1' }),
fetch: vi.fn() as unknown as typeof fetch,
locals: { user: writeUser }
});
expect(result.canWrite).toBe(true);
});
it('derives canWrite false when user lacks WRITE_ALL', async () => {
mockApi([
{ ok: true, data: [] },
{ ok: true, data: { firstName: 'Hans', lastName: 'Müller' } }
]);
const result = await load({
url: makeUrl({ senderId: 'p1' }),
fetch: vi.fn() as unknown as typeof fetch,
locals: { user: readUser }
});
expect(result.canWrite).toBe(false);
});
});
// ─── Backend error propagation ────────────────────────────────────────────────
describe('korrespondenz load — backend error', () => {
it('throws when the conversation endpoint returns non-ok', async () => {
mockApi([
{ ok: false, status: 500 },
{ ok: true, data: { firstName: 'Hans', lastName: 'Müller' } }
]);
await expect(
load({
url: makeUrl({ senderId: 'p1' }),
fetch: vi.fn() as unknown as typeof fetch,
locals: { user: readUser }
})
).rejects.toMatchObject({ status: 500 });
});
});

View File

@@ -0,0 +1,246 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import Page from './+page.svelte';
vi.mock('$app/navigation', () => ({ goto: vi.fn() }));
afterEach(cleanup);
// ─── Test data ────────────────────────────────────────────────────────────────
const baseData = {
user: undefined,
canWrite: true,
canAnnotate: false,
documents: [],
initialValues: { senderName: '', receiverName: '' },
filters: { senderId: '', receiverId: '', from: '', to: '', dir: 'DESC' as const }
};
const withSender = {
...baseData,
initialValues: { senderName: 'Hans Müller', receiverName: '' },
filters: { ...baseData.filters, senderId: 'p1' }
};
const withPersons = {
...baseData,
initialValues: { senderName: 'Hans Müller', receiverName: 'Anna Schmidt' },
filters: { ...baseData.filters, senderId: 'p1', receiverId: 'p2' }
};
const makeDoc = (overrides: Record<string, unknown> = {}) => ({
id: 'd1',
title: 'Testbrief',
originalFilename: 'testbrief.pdf',
status: 'UPLOADED' as const,
documentDate: '1923-04-12',
location: 'Berlin',
metadataComplete: false,
sender: { id: 'p1', firstName: 'Hans', lastName: 'Müller' },
receivers: [{ id: 'p2', firstName: 'Anna', lastName: 'Schmidt' }],
tags: [],
transcription: undefined,
filePath: undefined,
createdAt: '1923-04-12T00:00:00Z',
updatedAt: '1923-04-12T00:00:00Z',
...overrides
});
const withDocs = {
...withPersons,
documents: [makeDoc()]
};
// ─── Empty state (no senderId) ────────────────────────────────────────────────
describe('Korrespondenz page empty state', () => {
it('shows the search heading when no person is selected', async () => {
render(Page, { data: baseData });
await expect.element(page.getByText(/Korrespondenz durchsuchen/i)).toBeInTheDocument();
});
it('shows the empty-search button', async () => {
render(Page, { data: baseData });
await expect.element(page.getByTestId('conv-empty-search')).toBeInTheDocument();
});
it('does not show the new document link when no person is selected', async () => {
render(Page, { data: baseData });
await expect.element(page.getByTestId('conv-new-doc-link')).not.toBeInTheDocument();
});
it('does not show a year divider when no person is selected', async () => {
render(Page, { data: baseData });
await expect.element(page.getByTestId('year-divider')).not.toBeInTheDocument();
});
});
// ─── Recent persons chips ─────────────────────────────────────────────────────
describe('Korrespondenz page recent persons', () => {
it('shows recent person chips from localStorage', async () => {
localStorage.setItem(
'korrespondenz_recent_persons',
JSON.stringify([{ id: 'r1', name: 'Clara Braun' }])
);
render(Page, { data: baseData });
await expect.element(page.getByText('Clara Braun')).toBeInTheDocument();
localStorage.removeItem('korrespondenz_recent_persons');
});
it('does not crash when localStorage contains corrupt JSON', async () => {
localStorage.setItem('korrespondenz_recent_persons', '}{not valid json');
render(Page, { data: baseData });
// Empty state heading is still shown — no chip list crash
await expect.element(page.getByText(/Korrespondenz durchsuchen/i)).toBeInTheDocument();
localStorage.removeItem('korrespondenz_recent_persons');
});
});
// ─── Single-person hint bar ───────────────────────────────────────────────────
describe('Korrespondenz page single-person hint bar', () => {
it('shows hint bar when only senderId is set', async () => {
render(Page, { data: withSender });
await expect.element(page.getByText(/Alle Briefe von Hans Müller/i)).toBeInTheDocument();
});
it('does not show hint bar when both persons are set', async () => {
render(Page, { data: { ...withPersons, documents: [makeDoc()] } });
await expect.element(page.getByText(/Alle Briefe von Hans Müller/i)).not.toBeInTheDocument();
});
it('does not show hint bar when no person is set', async () => {
render(Page, { data: baseData });
await expect.element(page.getByText(/Alle Briefe von/i)).not.toBeInTheDocument();
});
});
// ─── Filter controls disabled state ──────────────────────────────────────────
describe('Korrespondenz page filter strip Row 2 disabled state', () => {
it('renders filter controls with aria-disabled when no senderId', async () => {
render(Page, { data: baseData });
const strip = document.querySelector('[aria-disabled="true"]');
expect(strip).not.toBeNull();
});
it('filter controls are not aria-disabled when senderId is set', async () => {
render(Page, { data: withSender });
const strip = document.querySelector('[aria-disabled="false"]');
expect(strip).not.toBeNull();
});
});
// ─── Strip letter count ───────────────────────────────────────────────────────
describe('Korrespondenz page strip letter count', () => {
it('shows 0 Briefe when senderId is set but no documents', async () => {
render(Page, { data: withSender });
await expect.element(page.getByTestId('conv-strip-count')).toHaveTextContent('0 Briefe');
});
it('shows correct count when documents are loaded', async () => {
render(Page, { data: { ...withPersons, documents: [makeDoc()] } });
await expect.element(page.getByTestId('conv-strip-count')).toHaveTextContent('1 Briefe');
});
});
// ─── No results ───────────────────────────────────────────────────────────────
describe('Korrespondenz page no results', () => {
it('shows "no documents found" when a person is selected but there are no documents', async () => {
render(Page, { data: withSender });
await expect.element(page.getByText(/Keine Dokumente gefunden/i)).toBeInTheDocument();
});
});
// ─── Swap button ──────────────────────────────────────────────────────────────
describe('Korrespondenz page swap button', () => {
it('swap button is invisible when only one person is set', async () => {
render(Page, { data: withSender });
const btn = document.querySelector<HTMLElement>('[data-testid="conv-swap-btn"]');
expect(btn).not.toBeNull();
// opacity-0 is applied via class when swapVisible is false
expect(btn!.className).toMatch(/opacity-0/);
});
it('swap button is visible when both persons are set', async () => {
render(Page, { data: withPersons });
const btn = document.querySelector<HTMLElement>('[data-testid="conv-swap-btn"]');
expect(btn).not.toBeNull();
expect(btn!.className).not.toMatch(/opacity-0/);
});
it('calls goto with swapped sender and receiver when clicked', async () => {
const { goto } = await import('$app/navigation');
vi.mocked(goto).mockClear();
render(Page, { data: withPersons });
document.querySelector<HTMLElement>('[data-testid="conv-swap-btn"]')!.click();
expect(goto).toHaveBeenCalledWith(expect.stringContaining('senderId=p2'), expect.anything());
expect(goto).toHaveBeenCalledWith(expect.stringContaining('receiverId=p1'), expect.anything());
});
});
// ─── Year dividers ────────────────────────────────────────────────────────────
describe('Korrespondenz page year dividers', () => {
it('renders a year divider for the first document', async () => {
render(Page, { data: withDocs });
await expect.element(page.getByTestId('year-divider').first()).toHaveTextContent('1923');
});
it('renders a divider for each new year in the document list', async () => {
const data = {
...withPersons,
documents: [
makeDoc({ documentDate: '1923-04-12' }),
makeDoc({ id: 'd2', documentDate: '1965-08-03' })
]
};
render(Page, { data });
await expect.element(page.getByTestId('year-divider').first()).toHaveTextContent('1923');
await expect.element(page.getByTestId('year-divider').nth(1)).toHaveTextContent('1965');
});
it('does not render a second divider for documents from the same year', async () => {
const data = {
...withPersons,
documents: [
makeDoc({ documentDate: '1923-04-12' }),
makeDoc({ id: 'd2', documentDate: '1923-09-01' })
]
};
render(Page, { data });
await expect.element(page.getByTestId('year-divider').first()).toHaveTextContent('1923');
await expect.element(page.getByTestId('year-divider').nth(1)).not.toBeInTheDocument();
});
});
// ─── New document link ────────────────────────────────────────────────────────
describe('Korrespondenz page new document link', () => {
it('shows the link with correct href for a write user (bilateral)', async () => {
render(Page, { data: { ...withDocs, canWrite: true } });
const link = page.getByTestId('conv-new-doc-link');
await expect.element(link).toBeInTheDocument();
await expect.element(link).toHaveAttribute('href', expect.stringContaining('senderId=p1'));
await expect.element(link).toHaveAttribute('href', expect.stringContaining('receiverId=p2'));
});
it('shows the link with correct href for single-person mode', async () => {
render(Page, { data: { ...withSender, documents: [makeDoc()], canWrite: true } });
const link = page.getByTestId('conv-new-doc-link');
await expect.element(link).toBeInTheDocument();
await expect.element(link).toHaveAttribute('href', expect.stringContaining('senderId=p1'));
await expect.element(link).not.toHaveAttribute('href', expect.stringContaining('receiverId'));
});
it('hides the link for a read-only user', async () => {
render(Page, { data: { ...withDocs, canWrite: false } });
await expect.element(page.getByTestId('conv-new-doc-link')).not.toBeInTheDocument();
});
});

View File

@@ -30,7 +30,7 @@ function initials(name: string): string {
<div class="flex flex-wrap gap-2">
{#each coCorrespondents as c (c.id)}
<a
href="/conversations?senderId={personId}&receiverId={c.id}"
href="/korrespondenz?senderId={personId}&receiverId={c.id}"
title={m.doc_conversation_title()}
class="inline-flex items-center gap-1.5 rounded-full border border-line bg-muted px-3 py-1.5 font-sans text-xs font-bold text-ink transition-colors hover:border-primary hover:bg-surface"
>