Compare commits
43 Commits
c61b08d6de
...
feat/issue
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ebeb0cf865 | ||
|
|
46eb908ff4 | ||
|
|
616d6ba01c | ||
|
|
154f859efc | ||
|
|
591316aa22 | ||
|
|
89f2106d8b | ||
|
|
33c29fbff3 | ||
|
|
757d0493a0 | ||
|
|
50e637a9f2 | ||
|
|
4bb9393a83 | ||
|
|
ff3ea70826 | ||
|
|
010904d6e1 | ||
|
|
6b5f05bd2b | ||
|
|
cefcdf3072 | ||
|
|
9cacc6079e | ||
|
|
9d6c7b8605 | ||
|
|
56d79c919e | ||
|
|
3318b5f1c6 | ||
|
|
71eaca9495 | ||
|
|
a3a7af123d | ||
|
|
5fd7e41492 | ||
|
|
0387e9f428 | ||
|
|
49f6b0a8c7 | ||
|
|
1b95d9472b | ||
|
|
4f5f8255a1 | ||
|
|
3addc72693 | ||
|
|
48286b9f77 | ||
|
|
e942699078 | ||
|
|
f352058bc6 | ||
|
|
252881b8d1 | ||
|
|
f88371e9af | ||
|
|
393cb52178 | ||
|
|
09d8fb5f95 | ||
|
|
9996055cac | ||
|
|
559b522507 | ||
|
|
3c54401bb2 | ||
|
|
06a489567a | ||
|
|
fabb517d0b | ||
|
|
cee16c1657 | ||
|
|
908173de97 | ||
|
|
8197db2c14 | ||
|
|
c8a834b91b | ||
|
|
8fc360a596 |
@@ -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
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -61,6 +61,7 @@ public class UserController {
|
||||
}
|
||||
|
||||
@GetMapping("users/{id}")
|
||||
@RequirePermission(Permission.ADMIN_USER)
|
||||
public ResponseEntity<AppUser> getUser(@PathVariable UUID id) {
|
||||
AppUser user = userService.getById(id);
|
||||
user.setPassword(null);
|
||||
|
||||
@@ -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);
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -50,4 +50,29 @@ class UserControllerTest {
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.username").value("anna"));
|
||||
}
|
||||
|
||||
// ─── GET /api/users/{id} ──────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "reader")
|
||||
void getUser_returns403_whenCallerLacksAdminUserPermission() throws Exception {
|
||||
UUID id = UUID.randomUUID();
|
||||
AppUser target = AppUser.builder().id(id).username("target").build();
|
||||
when(userService.getById(id)).thenReturn(target);
|
||||
|
||||
mockMvc.perform(get("/api/users/" + id))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "admin", authorities = {"ADMIN_USER"})
|
||||
void getUser_returns200_whenCallerHasAdminUserPermission() throws Exception {
|
||||
UUID id = UUID.randomUUID();
|
||||
AppUser user = AppUser.builder().id(id).username("target").build();
|
||||
when(userService.getById(id)).thenReturn(user);
|
||||
|
||||
mockMvc.perform(get("/api/users/" + id))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.username").value("target"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
|
||||
127
frontend/e2e/korrespondenz.spec.ts
Normal file
127
frontend/e2e/korrespondenz.spec.ts
Normal 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}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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",
|
||||
@@ -155,6 +172,14 @@
|
||||
"admin_multiselect_hint_full": "Strg+Klick für Mehrfachauswahl",
|
||||
"admin_section_tags": "Schlagworte",
|
||||
"admin_tags_warning": "Warnung: Umbenennen oder Löschen wirkt sich auf alle verknüpften Dokumente aus.",
|
||||
"admin_tags_list_title": "Alle Schlagworte",
|
||||
"admin_tags_empty": "Keine Schlagworte vorhanden.",
|
||||
"admin_tags_select_prompt": "W\u00e4hle ein Schlagwort aus der Liste.",
|
||||
"admin_tag_edit_heading": "Schlagwort: {name}",
|
||||
"admin_tag_updated": "Schlagwort umbenannt.",
|
||||
"admin_unsaved_warning": "Du hast ungespeicherte Änderungen – speichere oder verwerfe, bevor du wechselst.",
|
||||
"admin_btn_collapse_list": "Liste einklappen",
|
||||
"admin_btn_expand_list": "Liste ausklappen",
|
||||
"admin_btn_edit_tag_label": "Schlagwort bearbeiten",
|
||||
"admin_tag_delete_confirm": "Wirklich löschen? Das Schlagwort wird aus allen Dokumenten entfernt.",
|
||||
"admin_btn_delete_tag_label": "Schlagwort löschen",
|
||||
@@ -167,6 +192,28 @@
|
||||
"admin_group_name_placeholder": "Gruppenname (z.B. Editoren)",
|
||||
"admin_user_delete_confirm": "Benutzer {username} wirklich löschen?",
|
||||
"admin_btn_new_user": "Neuer Benutzer",
|
||||
"admin_users_list_title": "Alle Benutzer",
|
||||
"admin_users_search_placeholder": "Benutzer suchen\u2026",
|
||||
"admin_users_empty": "Keine Benutzer vorhanden.",
|
||||
"admin_users_select_prompt": "W\u00e4hle einen Benutzer aus der Liste.",
|
||||
"admin_btn_new_group": "Neue Gruppe",
|
||||
"admin_groups_list_title": "Alle Gruppen",
|
||||
"admin_groups_empty": "Keine Gruppen vorhanden.",
|
||||
"admin_groups_select_prompt": "W\u00e4hle eine Gruppe aus der Liste.",
|
||||
"admin_groups_permission_count": "{count} Berechtigungen",
|
||||
"admin_group_new_heading": "Neue Gruppe anlegen",
|
||||
"admin_group_edit_heading": "Gruppe: {name}",
|
||||
"admin_group_updated": "Gruppe gespeichert.",
|
||||
"admin_group_created": "Gruppe erstellt.",
|
||||
"admin_groups_section_standard": "Standard",
|
||||
"admin_groups_section_administrative": "Administrativ",
|
||||
"admin_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.",
|
||||
@@ -250,6 +297,14 @@
|
||||
"admin_system_backfill_hashes_description": "Berechnet den SHA-256-Hash für alle bereits hochgeladenen Dokumente, die noch keinen Hash haben. Dadurch werden Annotationen korrekt mit ihrer Dateiversion verknüpft und wieder angezeigt.",
|
||||
"admin_system_backfill_hashes_btn": "Datei-Hashes berechnen",
|
||||
"admin_system_backfill_hashes_success": "{count} Dokumente wurden aktualisiert.",
|
||||
"admin_system_import_heading": "Massenimport",
|
||||
"admin_system_import_description": "Importiert Dokumente und Metadaten aus der Importdatei im /import-Verzeichnis.",
|
||||
"admin_system_import_btn_start": "Import starten",
|
||||
"admin_system_import_btn_retry": "Erneut starten",
|
||||
"admin_system_import_status_idle": "Kein Import gestartet.",
|
||||
"admin_system_import_status_running": "Import läuft…",
|
||||
"admin_system_import_status_done": "Import abgeschlossen – {count} Dokumente verarbeitet.",
|
||||
"admin_system_import_status_failed": "Fehler: {message}",
|
||||
"comp_expandable_show_more": "Mehr anzeigen",
|
||||
"comp_expandable_show_less": "Weniger anzeigen",
|
||||
"error_comment_not_found": "Der Kommentar wurde nicht gefunden.",
|
||||
|
||||
@@ -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",
|
||||
@@ -155,6 +172,14 @@
|
||||
"admin_multiselect_hint_full": "Ctrl+Click for multiple selection",
|
||||
"admin_section_tags": "Tags",
|
||||
"admin_tags_warning": "Warning: Renaming or deleting affects all linked documents.",
|
||||
"admin_tags_list_title": "All Tags",
|
||||
"admin_tags_empty": "No tags found.",
|
||||
"admin_tags_select_prompt": "Select a tag from the list.",
|
||||
"admin_tag_edit_heading": "Tag: {name}",
|
||||
"admin_tag_updated": "Tag renamed.",
|
||||
"admin_unsaved_warning": "You have unsaved changes — save or discard before switching.",
|
||||
"admin_btn_collapse_list": "Collapse list",
|
||||
"admin_btn_expand_list": "Expand list",
|
||||
"admin_btn_edit_tag_label": "Edit tag",
|
||||
"admin_tag_delete_confirm": "Really delete? The tag will be removed from all documents.",
|
||||
"admin_btn_delete_tag_label": "Delete tag",
|
||||
@@ -167,6 +192,28 @@
|
||||
"admin_group_name_placeholder": "Group name (e.g. Editors)",
|
||||
"admin_user_delete_confirm": "Really delete user {username}?",
|
||||
"admin_btn_new_user": "New User",
|
||||
"admin_users_list_title": "All Users",
|
||||
"admin_users_search_placeholder": "Search users\u2026",
|
||||
"admin_users_empty": "No users found.",
|
||||
"admin_users_select_prompt": "Select a user from the list.",
|
||||
"admin_btn_new_group": "New Group",
|
||||
"admin_groups_list_title": "All Groups",
|
||||
"admin_groups_empty": "No groups found.",
|
||||
"admin_groups_select_prompt": "Select a group from the list.",
|
||||
"admin_groups_permission_count": "{count} permissions",
|
||||
"admin_group_new_heading": "Create new group",
|
||||
"admin_group_edit_heading": "Group: {name}",
|
||||
"admin_group_updated": "Group saved.",
|
||||
"admin_group_created": "Group created.",
|
||||
"admin_groups_section_standard": "Standard",
|
||||
"admin_groups_section_administrative": "Administrative",
|
||||
"admin_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.",
|
||||
@@ -250,6 +297,14 @@
|
||||
"admin_system_backfill_hashes_description": "Computes the SHA-256 hash for all previously uploaded documents that do not have one yet. This ensures annotations are correctly linked to their file version and shown again.",
|
||||
"admin_system_backfill_hashes_btn": "Compute file hashes",
|
||||
"admin_system_backfill_hashes_success": "{count} documents were updated.",
|
||||
"admin_system_import_heading": "Mass import",
|
||||
"admin_system_import_description": "Imports documents and metadata from the spreadsheet file in the /import directory.",
|
||||
"admin_system_import_btn_start": "Start import",
|
||||
"admin_system_import_btn_retry": "Start again",
|
||||
"admin_system_import_status_idle": "No import started.",
|
||||
"admin_system_import_status_running": "Import running…",
|
||||
"admin_system_import_status_done": "Import complete – {count} documents processed.",
|
||||
"admin_system_import_status_failed": "Error: {message}",
|
||||
"comp_expandable_show_more": "Show more",
|
||||
"comp_expandable_show_less": "Show less",
|
||||
"error_comment_not_found": "The comment could not be found.",
|
||||
|
||||
@@ -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",
|
||||
@@ -155,6 +172,14 @@
|
||||
"admin_multiselect_hint_full": "Ctrl+Clic para selección múltiple",
|
||||
"admin_section_tags": "Etiquetas",
|
||||
"admin_tags_warning": "Advertencia: Renombrar o eliminar afecta a todos los documentos vinculados.",
|
||||
"admin_tags_list_title": "Todas las etiquetas",
|
||||
"admin_tags_empty": "No hay etiquetas.",
|
||||
"admin_tags_select_prompt": "Selecciona una etiqueta de la lista.",
|
||||
"admin_tag_edit_heading": "Etiqueta: {name}",
|
||||
"admin_tag_updated": "Etiqueta renombrada.",
|
||||
"admin_unsaved_warning": "Tienes cambios sin guardar — guarda o descarta antes de cambiar.",
|
||||
"admin_btn_collapse_list": "Contraer lista",
|
||||
"admin_btn_expand_list": "Expandir lista",
|
||||
"admin_btn_edit_tag_label": "Editar etiqueta",
|
||||
"admin_tag_delete_confirm": "¿Realmente eliminar? La etiqueta se eliminará de todos los documentos.",
|
||||
"admin_btn_delete_tag_label": "Eliminar etiqueta",
|
||||
@@ -167,6 +192,28 @@
|
||||
"admin_group_name_placeholder": "Nombre del grupo (p.ej. Editores)",
|
||||
"admin_user_delete_confirm": "¿Realmente eliminar al usuario {username}?",
|
||||
"admin_btn_new_user": "Nuevo usuario",
|
||||
"admin_users_list_title": "Todos los usuarios",
|
||||
"admin_users_search_placeholder": "Buscar usuarios\u2026",
|
||||
"admin_users_empty": "No hay usuarios.",
|
||||
"admin_users_select_prompt": "Selecciona un usuario de la lista.",
|
||||
"admin_btn_new_group": "Nuevo grupo",
|
||||
"admin_groups_list_title": "Todos los grupos",
|
||||
"admin_groups_empty": "No hay grupos.",
|
||||
"admin_groups_select_prompt": "Selecciona un grupo de la lista.",
|
||||
"admin_groups_permission_count": "{count} permisos",
|
||||
"admin_group_new_heading": "Crear nuevo grupo",
|
||||
"admin_group_edit_heading": "Grupo: {name}",
|
||||
"admin_group_updated": "Grupo guardado.",
|
||||
"admin_group_created": "Grupo creado.",
|
||||
"admin_groups_section_standard": "Est\u00e1ndar",
|
||||
"admin_groups_section_administrative": "Administrativo",
|
||||
"admin_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.",
|
||||
@@ -250,6 +297,14 @@
|
||||
"admin_system_backfill_hashes_description": "Calcula el hash SHA-256 para todos los documentos ya subidos que aún no tienen uno. Así las anotaciones se vinculan correctamente a su versión del archivo y vuelven a mostrarse.",
|
||||
"admin_system_backfill_hashes_btn": "Calcular hashes de archivo",
|
||||
"admin_system_backfill_hashes_success": "{count} documentos fueron actualizados.",
|
||||
"admin_system_import_heading": "Importación masiva",
|
||||
"admin_system_import_description": "Importa documentos y metadatos desde el archivo en el directorio /import.",
|
||||
"admin_system_import_btn_start": "Iniciar importación",
|
||||
"admin_system_import_btn_retry": "Iniciar de nuevo",
|
||||
"admin_system_import_status_idle": "No hay importación iniciada.",
|
||||
"admin_system_import_status_running": "Importación en curso…",
|
||||
"admin_system_import_status_done": "Importación completada – {count} documentos procesados.",
|
||||
"admin_system_import_status_failed": "Error: {message}",
|
||||
"comp_expandable_show_more": "Mostrar más",
|
||||
"comp_expandable_show_less": "Mostrar menos",
|
||||
"error_comment_not_found": "El comentario no pudo encontrarse.",
|
||||
|
||||
1
frontend/src/app.d.ts
vendored
1
frontend/src/app.d.ts
vendored
@@ -12,6 +12,7 @@ declare global {
|
||||
email?: string;
|
||||
contact?: string;
|
||||
groups: {
|
||||
id: string;
|
||||
name: string;
|
||||
permissions: string[];
|
||||
}[];
|
||||
|
||||
@@ -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} />
|
||||
|
||||
210
frontend/src/lib/components/DateInput.svelte.spec.ts
Normal file
210
frontend/src/lib/components/DateInput.svelte.spec.ts
Normal 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');
|
||||
});
|
||||
});
|
||||
@@ -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()}
|
||||
>
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -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;
|
||||
|
||||
109
frontend/src/lib/utils/date.spec.ts
Normal file
109
frontend/src/lib/utils/date.spec.ts
Normal 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 1–2 digits as-is', () => {
|
||||
expect(formatGermanDateInput('2')).toBe('2');
|
||||
expect(formatGermanDateInput('20')).toBe('20');
|
||||
});
|
||||
|
||||
it('auto-inserts dot after 2 digits for 3–4 digit input', () => {
|
||||
expect(formatGermanDateInput('201')).toBe('20.1');
|
||||
expect(formatGermanDateInput('2012')).toBe('20.12');
|
||||
});
|
||||
|
||||
it('auto-inserts two dots for 5–8 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');
|
||||
});
|
||||
});
|
||||
@@ -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'}"
|
||||
>
|
||||
|
||||
57
frontend/src/routes/admin/+layout.server.ts
Normal file
57
frontend/src/routes/admin/+layout.server.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
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 = components['schemas']['UserGroup'];
|
||||
|
||||
function hasPerm(user: { groups?: UserGroup[] } | undefined, perm: string): boolean {
|
||||
return user?.groups?.some((g) => g.permissions.includes(perm)) ?? false;
|
||||
}
|
||||
|
||||
function hasAnyAdminPerm(user: { groups?: UserGroup[] } | undefined): boolean {
|
||||
return (
|
||||
hasPerm(user, 'ADMIN') ||
|
||||
hasPerm(user, 'ADMIN_USER') ||
|
||||
hasPerm(user, 'ADMIN_TAG') ||
|
||||
hasPerm(user, 'ADMIN_PERMISSION')
|
||||
);
|
||||
}
|
||||
|
||||
export async function load({ fetch, locals }) {
|
||||
const user = locals.user;
|
||||
if (!hasAnyAdminPerm(user)) throw error(403, getErrorMessage('FORBIDDEN'));
|
||||
|
||||
const api = createApiClient(fetch);
|
||||
|
||||
// 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'),
|
||||
canManagePermissions: hasPerm(user, 'ADMIN_PERMISSION'),
|
||||
canRunMaintenance: hasPerm(user, 'ADMIN')
|
||||
};
|
||||
}
|
||||
33
frontend/src/routes/admin/+layout.svelte
Normal file
33
frontend/src/routes/admin/+layout.svelte
Normal file
@@ -0,0 +1,33 @@
|
||||
<script lang="ts">
|
||||
import EntityNav from './EntityNav.svelte';
|
||||
|
||||
let { data, children } = $props();
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Admin · Familienarchiv</title>
|
||||
</svelte:head>
|
||||
|
||||
<!--
|
||||
-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 -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
|
||||
userCount={data.userCount}
|
||||
groupCount={data.groupCount}
|
||||
tagCount={data.tagCount}
|
||||
canManageUsers={data.canManageUsers}
|
||||
canManageTags={data.canManageTags}
|
||||
canManagePermissions={data.canManagePermissions}
|
||||
canRunMaintenance={data.canRunMaintenance}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Right side: list panel + detail panel (or full-width for system) -->
|
||||
<div class="flex min-w-0 flex-1 overflow-hidden">
|
||||
{@render children()}
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,116 +0,0 @@
|
||||
import { error, fail } from '@sveltejs/kit';
|
||||
import { createApiClient } from '$lib/api.server';
|
||||
import { getErrorMessage } from '$lib/errors';
|
||||
|
||||
type ApiResult = { response: Response; error?: unknown };
|
||||
|
||||
function toActionResult(result: ApiResult) {
|
||||
if (!result.response.ok) {
|
||||
const code = (result.error as { code?: string } | undefined)?.code;
|
||||
return fail(result.response.status, { success: false, message: getErrorMessage(code) });
|
||||
}
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function load({ fetch, locals }) {
|
||||
const user = locals.user;
|
||||
const hasAdmin = user?.groups?.some((g: { permissions: string[] }) =>
|
||||
g.permissions.includes('ADMIN')
|
||||
);
|
||||
if (!hasAdmin) throw error(403, getErrorMessage('FORBIDDEN'));
|
||||
|
||||
const api = createApiClient(fetch);
|
||||
|
||||
const [usersResult, groupsResult, tagsResult] = await Promise.all([
|
||||
api.GET('/api/users'),
|
||||
api.GET('/api/groups'),
|
||||
api.GET('/api/tags')
|
||||
]);
|
||||
|
||||
return {
|
||||
users: usersResult.data ?? [],
|
||||
groups: groupsResult.data ?? [],
|
||||
tags: tagsResult.data ?? []
|
||||
};
|
||||
}
|
||||
|
||||
export const actions = {
|
||||
deleteUser: async ({ request, fetch }) => {
|
||||
const data = await request.formData();
|
||||
const id = data.get('id') as string;
|
||||
const api = createApiClient(fetch);
|
||||
|
||||
const result = await api.DELETE('/api/users/{id}', {
|
||||
params: { path: { id } }
|
||||
});
|
||||
|
||||
return toActionResult(result);
|
||||
},
|
||||
|
||||
updateTag: async ({ request, fetch }) => {
|
||||
const data = await request.formData();
|
||||
const id = data.get('id') as string;
|
||||
const api = createApiClient(fetch);
|
||||
|
||||
const result = await api.PUT('/api/tags/{id}', {
|
||||
params: { path: { id } },
|
||||
body: { name: data.get('name') as string }
|
||||
});
|
||||
|
||||
return toActionResult(result);
|
||||
},
|
||||
|
||||
deleteTag: async ({ request, fetch }) => {
|
||||
const data = await request.formData();
|
||||
const id = data.get('id') as string;
|
||||
const api = createApiClient(fetch);
|
||||
|
||||
const result = await api.DELETE('/api/tags/{id}', {
|
||||
params: { path: { id } }
|
||||
});
|
||||
|
||||
return toActionResult(result);
|
||||
},
|
||||
|
||||
createGroup: async ({ request, fetch }) => {
|
||||
const data = await request.formData();
|
||||
const api = createApiClient(fetch);
|
||||
|
||||
const result = await api.POST('/api/groups', {
|
||||
body: {
|
||||
name: data.get('name') as string,
|
||||
permissions: data.getAll('permissions') as string[]
|
||||
}
|
||||
});
|
||||
|
||||
return toActionResult(result);
|
||||
},
|
||||
|
||||
updateGroup: async ({ request, fetch }) => {
|
||||
const data = await request.formData();
|
||||
const id = data.get('id') as string;
|
||||
const api = createApiClient(fetch);
|
||||
|
||||
const result = await api.PATCH('/api/groups/{id}', {
|
||||
params: { path: { id } },
|
||||
body: {
|
||||
name: data.get('name') as string,
|
||||
permissions: data.getAll('permissions') as string[]
|
||||
}
|
||||
});
|
||||
|
||||
return toActionResult(result);
|
||||
},
|
||||
|
||||
deleteGroup: async ({ request, fetch }) => {
|
||||
const data = await request.formData();
|
||||
const id = data.get('id') as string;
|
||||
const api = createApiClient(fetch);
|
||||
|
||||
const result = await api.DELETE('/api/groups/{id}', {
|
||||
params: { path: { id } }
|
||||
});
|
||||
|
||||
return toActionResult(result);
|
||||
}
|
||||
};
|
||||
@@ -1,78 +1,68 @@
|
||||
<script lang="ts">
|
||||
import { slide } from 'svelte/transition';
|
||||
import { goto } from '$app/navigation';
|
||||
import { onMount } from 'svelte';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
import UsersTab from './UsersTab.svelte';
|
||||
import TagsTab from './TagsTab.svelte';
|
||||
import GroupsTab from './GroupsTab.svelte';
|
||||
import SystemTab from './SystemTab.svelte';
|
||||
|
||||
let { data, form } = $props();
|
||||
let { data } = $props();
|
||||
|
||||
let activeTab = $state('users');
|
||||
// On desktop/tablet the layout shell with EntityNav is visible.
|
||||
// On mobile this page IS the entity picker — tapping an entity pushes
|
||||
// the user to that route so the browser back button returns here.
|
||||
onMount(() => {
|
||||
if (window.matchMedia('(min-width: 768px)').matches) {
|
||||
goto('/admin/users', { replaceState: true });
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>{m.page_title_admin()}</title>
|
||||
</svelte:head>
|
||||
|
||||
<div class="mx-auto max-w-7xl px-4 py-8 font-sans sm:px-6 lg:px-8">
|
||||
<div class="mb-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<h1 class="font-serif text-3xl text-ink">{m.admin_heading()}</h1>
|
||||
|
||||
<!-- Tabs -->
|
||||
<div class="grid grid-cols-2 rounded-lg border border-line bg-surface p-1 shadow-sm sm:flex">
|
||||
<button
|
||||
class="rounded-md px-2 py-2 text-sm font-bold tracking-wide uppercase transition sm:px-4 {activeTab ===
|
||||
'users'
|
||||
? 'bg-primary text-primary-fg'
|
||||
: 'text-ink-2 hover:text-ink'}"
|
||||
onclick={() => (activeTab = 'users')}>{m.admin_tab_users()}</button
|
||||
>
|
||||
<button
|
||||
class="rounded-md px-2 py-2 text-sm font-bold tracking-wide uppercase transition sm:px-4 {activeTab ===
|
||||
'groups'
|
||||
? 'bg-primary text-primary-fg'
|
||||
: 'text-ink-2 hover:text-ink'}"
|
||||
onclick={() => (activeTab = 'groups')}>{m.admin_tab_groups()}</button
|
||||
>
|
||||
<button
|
||||
class="rounded-md px-2 py-2 text-sm font-bold tracking-wide uppercase transition sm:px-4 {activeTab ===
|
||||
'tags'
|
||||
? 'bg-primary text-primary-fg'
|
||||
: 'text-ink-2 hover:text-ink'}"
|
||||
onclick={() => (activeTab = 'tags')}>{m.admin_tab_tags()}</button
|
||||
>
|
||||
<button
|
||||
class="rounded-md px-2 py-2 text-sm font-bold tracking-wide uppercase transition sm:px-4 {activeTab ===
|
||||
'system'
|
||||
? 'bg-primary text-primary-fg'
|
||||
: 'text-ink-2 hover:text-ink'}"
|
||||
onclick={() => (activeTab = 'system')}>{m.admin_tab_system()}</button
|
||||
>
|
||||
</div>
|
||||
<!-- Mobile entity picker (md+ viewports redirect to /admin/users on mount) -->
|
||||
<div class="flex flex-1 flex-col bg-surface">
|
||||
<div class="border-b border-line px-4 py-4">
|
||||
<h1 class="font-sans text-lg font-bold text-ink">{m.admin_heading()}</h1>
|
||||
</div>
|
||||
|
||||
{#if form?.message}
|
||||
<div class="mb-6 rounded border border-accent/50 bg-accent/20 p-4 text-ink">
|
||||
{form.message}
|
||||
</div>
|
||||
{/if}
|
||||
<nav class="divide-y divide-line" aria-label={m.admin_heading()}>
|
||||
{#if data.canManageUsers}
|
||||
<a href="/admin/users" 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_users()}</div>
|
||||
<div class="mt-0.5 font-sans text-xs text-ink-3">{data.userCount}</div>
|
||||
</div>
|
||||
<span class="text-ink-3">›</span>
|
||||
</a>
|
||||
{/if}
|
||||
|
||||
{#if activeTab === 'users'}
|
||||
<div in:slide>
|
||||
<UsersTab users={data.users} />
|
||||
</div>
|
||||
{:else if activeTab === 'tags'}
|
||||
<div in:slide>
|
||||
<TagsTab tags={data.tags} />
|
||||
</div>
|
||||
{:else if activeTab === 'groups'}
|
||||
<div in:slide>
|
||||
<GroupsTab groups={data.groups} />
|
||||
</div>
|
||||
{:else if activeTab === 'system'}
|
||||
<div in:slide>
|
||||
<SystemTab />
|
||||
</div>
|
||||
{/if}
|
||||
{#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>
|
||||
<div class="mt-0.5 font-sans text-xs text-ink-3">{data.groupCount}</div>
|
||||
</div>
|
||||
<span class="text-ink-3">›</span>
|
||||
</a>
|
||||
{/if}
|
||||
|
||||
{#if data.canManageTags}
|
||||
<a href="/admin/tags" 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_tags()}</div>
|
||||
<div class="mt-0.5 font-sans text-xs text-ink-3">{data.tagCount}</div>
|
||||
</div>
|
||||
<span class="text-ink-3">›</span>
|
||||
</a>
|
||||
{/if}
|
||||
|
||||
{#if data.canRunMaintenance}
|
||||
<a href="/admin/system" 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_system()}</div>
|
||||
</div>
|
||||
<span class="text-ink-3">›</span>
|
||||
</a>
|
||||
{/if}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
515
frontend/src/routes/admin/EntityNav.svelte
Normal file
515
frontend/src/routes/admin/EntityNav.svelte
Normal file
@@ -0,0 +1,515 @@
|
||||
<script lang="ts">
|
||||
import { tick } from 'svelte';
|
||||
import { fly } from 'svelte/transition';
|
||||
import { page } from '$app/state';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
let {
|
||||
userCount,
|
||||
groupCount,
|
||||
tagCount,
|
||||
canManageUsers,
|
||||
canManageTags,
|
||||
canManagePermissions,
|
||||
canRunMaintenance
|
||||
}: {
|
||||
userCount: number;
|
||||
groupCount: number;
|
||||
tagCount: number;
|
||||
canManageUsers: boolean;
|
||||
canManageTags: boolean;
|
||||
canManagePermissions: boolean;
|
||||
canRunMaintenance: boolean;
|
||||
} = $props();
|
||||
|
||||
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) {
|
||||
closeFlyout();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:document onkeydown={handleKeydown} />
|
||||
|
||||
<!--
|
||||
Desktop (lg+): 120px with text labels
|
||||
Tablet (md–lg): 48px icon-only strip with flyout panel
|
||||
-->
|
||||
<nav
|
||||
class="flex flex-shrink-0 flex-col bg-brand-navy md:w-12 lg:w-30"
|
||||
aria-label={m.admin_heading()}
|
||||
>
|
||||
<!-- Desktop-only heading -->
|
||||
<div
|
||||
class="hidden px-3 pt-3 pb-1 text-[9px] font-extrabold tracking-widest text-white/30 uppercase lg:block"
|
||||
>
|
||||
{m.admin_heading()}
|
||||
</div>
|
||||
|
||||
{#if canManageUsers}
|
||||
<!-- Tablet trigger button (md only, hidden at lg) -->
|
||||
<button
|
||||
data-flyout-trigger
|
||||
type="button"
|
||||
aria-label={m.admin_tab_users()}
|
||||
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'}"
|
||||
>
|
||||
<svg
|
||||
class="h-5 w-5 flex-shrink-0 {isActive('users') ? 'text-brand-mint' : 'text-white/40'}"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z"
|
||||
/>
|
||||
</svg>
|
||||
<span class="text-[9px] font-bold {isActive('users') ? 'text-white/80' : 'text-white/35'}">
|
||||
{userCount}
|
||||
</span>
|
||||
</button>
|
||||
<!-- Desktop link (lg+) -->
|
||||
<a
|
||||
href="/admin/users"
|
||||
class="hidden flex-col items-start justify-center gap-0.5 border-l-[3px] px-3.5 py-2.5 transition-colors lg:flex
|
||||
{isActive('users')
|
||||
? 'border-brand-mint bg-white/10'
|
||||
: 'border-transparent hover:bg-white/5'}"
|
||||
aria-current={isActive('users') ? 'page' : undefined}
|
||||
title={m.admin_tab_users()}
|
||||
>
|
||||
<svg
|
||||
class="h-5 w-5 flex-shrink-0 {isActive('users') ? 'text-brand-mint' : 'text-white/40'}"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z"
|
||||
/>
|
||||
</svg>
|
||||
<span class="text-[13px] font-black {isActive('users') ? 'text-white/65' : 'text-white/20'}">
|
||||
{userCount}
|
||||
</span>
|
||||
<span
|
||||
class="text-[9px] font-extrabold tracking-[0.5px] uppercase
|
||||
{isActive('users') ? 'text-white' : 'text-white/55'}"
|
||||
>
|
||||
{m.admin_tab_users()}
|
||||
</span>
|
||||
</a>
|
||||
{/if}
|
||||
|
||||
{#if canManagePermissions}
|
||||
<!-- Tablet trigger button (md only, hidden at lg) -->
|
||||
<button
|
||||
data-flyout-trigger
|
||||
type="button"
|
||||
aria-label={m.admin_tab_groups()}
|
||||
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'}"
|
||||
>
|
||||
<svg
|
||||
class="h-5 w-5 flex-shrink-0 {isActive('groups') ? 'text-brand-mint' : 'text-white/40'}"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z"
|
||||
/>
|
||||
</svg>
|
||||
<span class="text-[9px] font-bold {isActive('groups') ? 'text-white/80' : 'text-white/35'}">
|
||||
{groupCount}
|
||||
</span>
|
||||
</button>
|
||||
<!-- Desktop link (lg+) -->
|
||||
<a
|
||||
href="/admin/groups"
|
||||
class="hidden flex-col items-start justify-center gap-0.5 border-l-[3px] px-3.5 py-2.5 transition-colors lg:flex
|
||||
{isActive('groups')
|
||||
? 'border-brand-mint bg-white/10'
|
||||
: 'border-transparent hover:bg-white/5'}"
|
||||
aria-current={isActive('groups') ? 'page' : undefined}
|
||||
title={m.admin_tab_groups()}
|
||||
>
|
||||
<svg
|
||||
class="h-5 w-5 flex-shrink-0 {isActive('groups') ? 'text-brand-mint' : 'text-white/40'}"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z"
|
||||
/>
|
||||
</svg>
|
||||
<span class="text-[13px] font-black {isActive('groups') ? 'text-white/65' : 'text-white/20'}">
|
||||
{groupCount}
|
||||
</span>
|
||||
<span
|
||||
class="text-[9px] font-extrabold tracking-[0.5px] uppercase
|
||||
{isActive('groups') ? 'text-white' : 'text-white/55'}"
|
||||
>
|
||||
{m.admin_tab_groups()}
|
||||
</span>
|
||||
</a>
|
||||
{/if}
|
||||
|
||||
{#if canManageTags}
|
||||
<!-- Tablet trigger button (md only, hidden at lg) -->
|
||||
<button
|
||||
data-flyout-trigger
|
||||
type="button"
|
||||
aria-label={m.admin_tab_tags()}
|
||||
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'}"
|
||||
>
|
||||
<svg
|
||||
class="h-5 w-5 flex-shrink-0 {isActive('tags') ? 'text-brand-mint' : 'text-white/40'}"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M9.568 3H5.25A2.25 2.25 0 003 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581c.699.699 1.78.872 2.607.33a18.095 18.095 0 005.223-5.223c.542-.827.369-1.908-.33-2.607L11.16 3.66A2.25 2.25 0 009.568 3z"
|
||||
/>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M6 6h.008v.008H6V6z" />
|
||||
</svg>
|
||||
<span class="text-[9px] font-bold {isActive('tags') ? 'text-white/80' : 'text-white/35'}">
|
||||
{tagCount}
|
||||
</span>
|
||||
</button>
|
||||
<!-- Desktop link (lg+) -->
|
||||
<a
|
||||
href="/admin/tags"
|
||||
class="hidden flex-col items-start justify-center gap-0.5 border-l-[3px] px-3.5 py-2.5 transition-colors lg:flex
|
||||
{isActive('tags')
|
||||
? 'border-brand-mint bg-white/10'
|
||||
: 'border-transparent hover:bg-white/5'}"
|
||||
aria-current={isActive('tags') ? 'page' : undefined}
|
||||
title={m.admin_tab_tags()}
|
||||
>
|
||||
<svg
|
||||
class="h-5 w-5 flex-shrink-0 {isActive('tags') ? 'text-brand-mint' : 'text-white/40'}"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M9.568 3H5.25A2.25 2.25 0 003 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581c.699.699 1.78.872 2.607.33a18.095 18.095 0 005.223-5.223c.542-.827.369-1.908-.33-2.607L11.16 3.66A2.25 2.25 0 009.568 3z"
|
||||
/>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M6 6h.008v.008H6V6z" />
|
||||
</svg>
|
||||
<span class="text-[13px] font-black {isActive('tags') ? 'text-white/65' : 'text-white/20'}">
|
||||
{tagCount}
|
||||
</span>
|
||||
<span
|
||||
class="text-[9px] font-extrabold tracking-[0.5px] uppercase
|
||||
{isActive('tags') ? 'text-white' : 'text-white/55'}"
|
||||
>
|
||||
{m.admin_tab_tags()}
|
||||
</span>
|
||||
</a>
|
||||
{/if}
|
||||
|
||||
<div class="flex-1"></div>
|
||||
|
||||
{#if canRunMaintenance}
|
||||
<!-- Tablet trigger button (md only, hidden at lg) -->
|
||||
<button
|
||||
data-flyout-trigger
|
||||
type="button"
|
||||
aria-label={m.admin_tab_system()}
|
||||
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'}"
|
||||
>
|
||||
<svg
|
||||
class="h-5 w-5 flex-shrink-0 {isActive('system') ? 'text-brand-mint' : 'text-white/40'}"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z"
|
||||
/>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
</button>
|
||||
<!-- Desktop link (lg+) -->
|
||||
<a
|
||||
href="/admin/system"
|
||||
class="hidden 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 lg:flex
|
||||
{isActive('system')
|
||||
? 'border-brand-mint bg-white/10'
|
||||
: 'border-l-transparent hover:bg-white/5'}"
|
||||
aria-current={isActive('system') ? 'page' : undefined}
|
||||
title={m.admin_tab_system()}
|
||||
>
|
||||
<svg
|
||||
class="h-5 w-5 flex-shrink-0 {isActive('system') ? 'text-brand-mint' : 'text-white/40'}"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z"
|
||||
/>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
<span
|
||||
class="text-[9px] font-extrabold tracking-[0.5px] uppercase
|
||||
{isActive('system') ? 'text-white' : 'text-white/55'}"
|
||||
>
|
||||
{m.admin_tab_system()}
|
||||
</span>
|
||||
</a>
|
||||
{/if}
|
||||
</nav>
|
||||
|
||||
{#if flyoutOpen}
|
||||
<!-- Backdrop -->
|
||||
<div
|
||||
data-flyout-backdrop
|
||||
role="none"
|
||||
class="fixed inset-0 z-40 bg-black/40"
|
||||
onclick={closeFlyout}
|
||||
></div>
|
||||
|
||||
<!-- Flyout panel -->
|
||||
<div
|
||||
role="dialog"
|
||||
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"
|
||||
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">
|
||||
{m.admin_heading()}
|
||||
</div>
|
||||
|
||||
{#if canManageUsers}
|
||||
<a
|
||||
href="/admin/users"
|
||||
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'
|
||||
: 'border-transparent hover:bg-white/5'}"
|
||||
aria-current={isActive('users') ? 'page' : undefined}
|
||||
>
|
||||
<svg
|
||||
class="h-5 w-5 flex-shrink-0 {isActive('users') ? 'text-brand-mint' : 'text-white/40'}"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z"
|
||||
/>
|
||||
</svg>
|
||||
<span
|
||||
class="text-[13px] font-black {isActive('users') ? 'text-white/65' : 'text-white/20'}"
|
||||
>
|
||||
{userCount}
|
||||
</span>
|
||||
<span
|
||||
class="text-[9px] font-extrabold tracking-[0.5px] uppercase
|
||||
{isActive('users') ? 'text-white' : 'text-white/55'}"
|
||||
>
|
||||
{m.admin_tab_users()}
|
||||
</span>
|
||||
</a>
|
||||
{/if}
|
||||
|
||||
{#if canManagePermissions}
|
||||
<a
|
||||
href="/admin/groups"
|
||||
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'
|
||||
: 'border-transparent hover:bg-white/5'}"
|
||||
aria-current={isActive('groups') ? 'page' : undefined}
|
||||
>
|
||||
<svg
|
||||
class="h-5 w-5 flex-shrink-0 {isActive('groups') ? 'text-brand-mint' : 'text-white/40'}"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z"
|
||||
/>
|
||||
</svg>
|
||||
<span
|
||||
class="text-[13px] font-black {isActive('groups') ? 'text-white/65' : 'text-white/20'}"
|
||||
>
|
||||
{groupCount}
|
||||
</span>
|
||||
<span
|
||||
class="text-[9px] font-extrabold tracking-[0.5px] uppercase
|
||||
{isActive('groups') ? 'text-white' : 'text-white/55'}"
|
||||
>
|
||||
{m.admin_tab_groups()}
|
||||
</span>
|
||||
</a>
|
||||
{/if}
|
||||
|
||||
{#if canManageTags}
|
||||
<a
|
||||
href="/admin/tags"
|
||||
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'
|
||||
: 'border-transparent hover:bg-white/5'}"
|
||||
aria-current={isActive('tags') ? 'page' : undefined}
|
||||
>
|
||||
<svg
|
||||
class="h-5 w-5 flex-shrink-0 {isActive('tags') ? 'text-brand-mint' : 'text-white/40'}"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M9.568 3H5.25A2.25 2.25 0 003 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581c.699.699 1.78.872 2.607.33a18.095 18.095 0 005.223-5.223c.542-.827.369-1.908-.33-2.607L11.16 3.66A2.25 2.25 0 009.568 3z"
|
||||
/>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M6 6h.008v.008H6V6z" />
|
||||
</svg>
|
||||
<span class="text-[13px] font-black {isActive('tags') ? 'text-white/65' : 'text-white/20'}">
|
||||
{tagCount}
|
||||
</span>
|
||||
<span
|
||||
class="text-[9px] font-extrabold tracking-[0.5px] uppercase
|
||||
{isActive('tags') ? 'text-white' : 'text-white/55'}"
|
||||
>
|
||||
{m.admin_tab_tags()}
|
||||
</span>
|
||||
</a>
|
||||
{/if}
|
||||
|
||||
<div class="flex-1"></div>
|
||||
|
||||
{#if canRunMaintenance}
|
||||
<a
|
||||
href="/admin/system"
|
||||
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'
|
||||
: 'border-l-transparent hover:bg-white/5'}"
|
||||
aria-current={isActive('system') ? 'page' : undefined}
|
||||
>
|
||||
<svg
|
||||
class="h-5 w-5 flex-shrink-0 {isActive('system') ? 'text-brand-mint' : 'text-white/40'}"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z"
|
||||
/>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
|
||||
/>
|
||||
</svg>
|
||||
<span
|
||||
class="text-[9px] font-extrabold tracking-[0.5px] uppercase
|
||||
{isActive('system') ? 'text-white' : 'text-white/55'}"
|
||||
>
|
||||
{m.admin_tab_system()}
|
||||
</span>
|
||||
</a>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -1,221 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
let { groups }: { groups: { id: string; name: string; permissions: string[] }[] } = $props();
|
||||
|
||||
const availablePermissions = ['WRITE_ALL', 'ADMIN', 'ADMIN_USER', 'ADMIN_TAG', 'ADMIN_PERMISSION'];
|
||||
|
||||
let editingGroupId: string | null = $state(null);
|
||||
|
||||
function startEditGroup(id: string) {
|
||||
editingGroupId = id;
|
||||
}
|
||||
|
||||
function cancelEditGroup() {
|
||||
editingGroupId = null;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="overflow-hidden rounded-lg border border-line bg-surface shadow-sm">
|
||||
<div class="flex items-center justify-between border-b border-line-2 p-6">
|
||||
<h2 class="text-lg font-bold text-ink-2">{m.admin_section_groups()}</h2>
|
||||
</div>
|
||||
|
||||
<table class="min-w-full divide-y divide-line">
|
||||
<thead class="bg-muted">
|
||||
<tr>
|
||||
<th class="px-6 py-3 text-left text-xs font-bold tracking-wider text-ink-2 uppercase"
|
||||
>{m.admin_col_name()}</th
|
||||
>
|
||||
<th class="px-6 py-3 text-left text-xs font-bold tracking-wider text-ink-2 uppercase"
|
||||
>{m.admin_col_permissions()}</th
|
||||
>
|
||||
<th class="px-6 py-3 text-right text-xs font-bold tracking-wider text-ink-2 uppercase"
|
||||
>{m.admin_col_actions()}</th
|
||||
>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-line bg-surface">
|
||||
{#each groups as group (group.id)}
|
||||
<tr class="group/row hover:bg-muted">
|
||||
{#if editingGroupId === group.id}
|
||||
<!-- EDIT MODE -->
|
||||
<td colspan="3" class="px-6 py-4">
|
||||
<form
|
||||
method="POST"
|
||||
action="?/updateGroup"
|
||||
use:enhance={() =>
|
||||
async ({ update }) => {
|
||||
await update();
|
||||
cancelEditGroup();
|
||||
}}
|
||||
class="flex w-full flex-col items-start gap-4 sm:flex-row"
|
||||
>
|
||||
<input type="hidden" name="id" value={group.id} />
|
||||
|
||||
<div class="w-full sm:w-1/3">
|
||||
<input
|
||||
type="text"
|
||||
name="name"
|
||||
value={group.name}
|
||||
class="w-full rounded border-accent text-sm"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex h-full flex-1 flex-wrap items-center gap-4 pt-2">
|
||||
{#each availablePermissions as perm (perm)}
|
||||
<label class="inline-flex items-center text-xs font-bold text-ink-2 uppercase">
|
||||
<input
|
||||
type="checkbox"
|
||||
name="permissions"
|
||||
value={perm}
|
||||
checked={group.permissions.includes(perm)}
|
||||
class="mr-2 rounded border-line text-ink focus:ring-accent"
|
||||
/>
|
||||
{perm.replace('_', ' ')}
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 self-start sm:self-center">
|
||||
<button
|
||||
type="submit"
|
||||
aria-label={m.btn_save()}
|
||||
class="p-1 text-green-600 hover:text-green-800"
|
||||
>
|
||||
<svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
|
||||
><path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M5 13l4 4L19 7"
|
||||
/></svg
|
||||
>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onclick={cancelEditGroup}
|
||||
aria-label={m.btn_cancel()}
|
||||
class="p-1 text-ink-3 hover:text-red-500"
|
||||
>
|
||||
<svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
|
||||
><path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
/></svg
|
||||
>
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</td>
|
||||
{:else}
|
||||
<!-- VIEW MODE -->
|
||||
<td class="px-6 py-4 text-sm font-bold whitespace-nowrap text-ink">
|
||||
{group.name}
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm text-ink-2">
|
||||
<div class="flex flex-wrap gap-1">
|
||||
{#each group.permissions as perm (perm)}
|
||||
<span
|
||||
class="rounded-full px-2 py-0.5 text-[10px] font-bold uppercase
|
||||
{perm === 'ADMIN'
|
||||
? 'border-red-100 bg-red-50 text-red-700'
|
||||
: 'border-line bg-muted text-ink-2'}"
|
||||
>
|
||||
{perm}
|
||||
</span>
|
||||
{/each}
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-right whitespace-nowrap">
|
||||
<div class="flex items-center justify-end gap-3">
|
||||
<button
|
||||
onclick={() => startEditGroup(group.id)}
|
||||
class="text-sm font-bold tracking-wide text-primary uppercase hover:text-ink-2"
|
||||
>
|
||||
{m.btn_edit()}
|
||||
</button>
|
||||
|
||||
<form
|
||||
method="POST"
|
||||
action="?/deleteGroup"
|
||||
use:enhance={({ cancel }) => {
|
||||
if (!confirm(m.admin_group_delete_confirm())) {
|
||||
cancel();
|
||||
}
|
||||
return async ({ update }) => {
|
||||
await update();
|
||||
};
|
||||
}}
|
||||
>
|
||||
<input type="hidden" name="id" value={group.id} />
|
||||
<button
|
||||
class="p-1 text-ink-3 transition-colors hover:text-red-600"
|
||||
title={m.btn_delete()}
|
||||
>
|
||||
<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</td>
|
||||
{/if}
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- CREATE GROUP FORM -->
|
||||
<div class="border-t border-line bg-muted p-6">
|
||||
<h3 class="mb-4 text-xs font-bold tracking-wide text-ink-2 uppercase">
|
||||
{m.admin_section_new_group()}
|
||||
</h3>
|
||||
<form
|
||||
method="POST"
|
||||
action="?/createGroup"
|
||||
use:enhance
|
||||
class="flex flex-col items-start gap-4 md:flex-row md:items-center"
|
||||
>
|
||||
<div class="w-full flex-1">
|
||||
<input
|
||||
type="text"
|
||||
name="name"
|
||||
placeholder={m.admin_group_name_placeholder()}
|
||||
required
|
||||
class="w-full rounded border-line text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-4">
|
||||
{#each availablePermissions as perm (perm)}
|
||||
<label class="inline-flex items-center text-xs font-bold text-ink-2 uppercase">
|
||||
<input
|
||||
type="checkbox"
|
||||
name="permissions"
|
||||
value={perm}
|
||||
class="mr-2 rounded border-line text-ink focus:ring-accent"
|
||||
/>
|
||||
{perm.replace('_', ' ')}
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
class="w-full rounded bg-primary px-6 py-2 text-sm font-bold text-primary-fg uppercase hover:bg-accent hover:text-ink md:w-auto"
|
||||
>
|
||||
{m.btn_create()}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,72 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
let backfillResult: number | null = $state(null);
|
||||
let backfillLoading = $state(false);
|
||||
let backfillHashesResult: number | null = $state(null);
|
||||
let backfillHashesLoading = $state(false);
|
||||
|
||||
async function backfillVersions() {
|
||||
backfillLoading = true;
|
||||
backfillResult = null;
|
||||
try {
|
||||
const res = await fetch('/api/admin/backfill-versions', { method: 'POST' });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
backfillResult = data.count;
|
||||
}
|
||||
} finally {
|
||||
backfillLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function backfillFileHashes() {
|
||||
backfillHashesLoading = true;
|
||||
backfillHashesResult = null;
|
||||
try {
|
||||
const res = await fetch('/api/admin/backfill-file-hashes', { method: 'POST' });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
backfillHashesResult = data.count;
|
||||
}
|
||||
} finally {
|
||||
backfillHashesLoading = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
|
||||
<h2 class="mb-1 text-lg font-bold text-ink-2">{m.admin_system_backfill_heading()}</h2>
|
||||
<p class="mb-4 text-sm text-ink-2">{m.admin_system_backfill_description()}</p>
|
||||
<button
|
||||
onclick={backfillVersions}
|
||||
disabled={backfillLoading}
|
||||
class="rounded bg-primary px-6 py-2 text-sm font-bold text-primary-fg uppercase transition hover:bg-accent hover:text-ink disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{backfillLoading ? '…' : m.admin_system_backfill_btn()}
|
||||
</button>
|
||||
{#if backfillResult !== null}
|
||||
<p class="mt-4 text-sm font-medium text-ink">
|
||||
{m.admin_system_backfill_success({ count: backfillResult })}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="mt-4 rounded-sm border border-line bg-surface p-6 shadow-sm">
|
||||
<h2 class="mb-1 text-lg font-bold text-ink-2">
|
||||
{m.admin_system_backfill_hashes_heading()}
|
||||
</h2>
|
||||
<p class="mb-4 text-sm text-ink-2">{m.admin_system_backfill_hashes_description()}</p>
|
||||
<button
|
||||
onclick={backfillFileHashes}
|
||||
disabled={backfillHashesLoading}
|
||||
class="rounded bg-primary px-6 py-2 text-sm font-bold text-primary-fg uppercase transition hover:bg-accent hover:text-ink disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{backfillHashesLoading ? '…' : m.admin_system_backfill_hashes_btn()}
|
||||
</button>
|
||||
{#if backfillHashesResult !== null}
|
||||
<p class="mt-4 text-sm font-medium text-ink">
|
||||
{m.admin_system_backfill_hashes_success({ count: backfillHashesResult })}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,127 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
let { tags }: { tags: { id: string; name: string }[] } = $props();
|
||||
|
||||
let editingTagId: string | null = $state(null);
|
||||
let editingTagName = $state('');
|
||||
|
||||
function startEditTag(tag: { id: string; name: string }) {
|
||||
editingTagId = tag.id;
|
||||
editingTagName = tag.name;
|
||||
}
|
||||
|
||||
function cancelEditTag() {
|
||||
editingTagId = null;
|
||||
editingTagName = '';
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="overflow-hidden rounded-lg border border-line bg-surface shadow-sm">
|
||||
<div class="border-b border-line-2 bg-yellow-50/50 p-6">
|
||||
<h2 class="text-lg font-bold text-ink-2">{m.admin_section_tags()}</h2>
|
||||
<p class="mt-1 text-xs text-yellow-800">
|
||||
{m.admin_tags_warning()}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ul class="max-h-[600px] divide-y divide-line-2 overflow-y-auto">
|
||||
{#each tags as tag (tag.id)}
|
||||
<li class="group flex items-center justify-between px-6 py-3 hover:bg-muted">
|
||||
{#if editingTagId === tag.id}
|
||||
<form
|
||||
method="POST"
|
||||
action="?/updateTag"
|
||||
use:enhance={() =>
|
||||
async ({ update }) => {
|
||||
await update();
|
||||
cancelEditTag();
|
||||
}}
|
||||
class="flex flex-1 items-center gap-2"
|
||||
>
|
||||
<input type="hidden" name="id" value={tag.id} />
|
||||
<input
|
||||
type="text"
|
||||
name="name"
|
||||
bind:value={editingTagName}
|
||||
class="flex-1 rounded border-accent px-2 py-1 text-sm ring-1 ring-accent"
|
||||
/>
|
||||
<button aria-label={m.btn_save()} class="text-green-600 hover:text-green-800"
|
||||
><svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"
|
||||
><path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M5 13l4 4L19 7"
|
||||
/></svg
|
||||
></button
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onclick={cancelEditTag}
|
||||
aria-label={m.btn_cancel()}
|
||||
class="text-ink-3 hover:text-ink-2"
|
||||
><svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"
|
||||
><path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
/></svg
|
||||
></button
|
||||
>
|
||||
</form>
|
||||
{:else}
|
||||
<span class="rounded bg-muted px-2 py-1 text-sm font-medium text-ink">
|
||||
{tag.name}
|
||||
</span>
|
||||
<div class="flex items-center gap-2 opacity-0 transition-opacity group-hover:opacity-100">
|
||||
<button
|
||||
onclick={() => startEditTag(tag)}
|
||||
aria-label={m.admin_btn_edit_tag_label()}
|
||||
class="p-1 text-ink-3 hover:text-ink"
|
||||
>
|
||||
<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"
|
||||
><path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"
|
||||
/></svg
|
||||
>
|
||||
</button>
|
||||
<form
|
||||
method="POST"
|
||||
action="?/deleteTag"
|
||||
use:enhance={({ cancel }) => {
|
||||
if (!confirm(m.admin_tag_delete_confirm())) {
|
||||
cancel();
|
||||
}
|
||||
return async ({ update }) => {
|
||||
await update();
|
||||
};
|
||||
}}
|
||||
class="inline"
|
||||
>
|
||||
<input type="hidden" name="id" value={tag.id} />
|
||||
<button
|
||||
aria-label={m.admin_btn_delete_tag_label()}
|
||||
class="p-1 text-ink-3 hover:text-red-600"
|
||||
>
|
||||
<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"
|
||||
><path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
|
||||
/></svg
|
||||
>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
@@ -1,120 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
let {
|
||||
users
|
||||
}: {
|
||||
users: {
|
||||
id: string;
|
||||
username: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
groups?: { id: string; name: string }[];
|
||||
}[];
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
<div class="overflow-hidden rounded-lg border border-line bg-surface shadow-sm">
|
||||
<div class="flex items-center justify-between border-b border-line-2 p-6">
|
||||
<h2 class="text-lg font-bold text-ink-2">{m.admin_section_users()}</h2>
|
||||
<a
|
||||
href="/admin/users/new"
|
||||
class="inline-flex items-center gap-1 rounded-sm bg-primary px-4 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
>
|
||||
<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
{m.admin_btn_new_user()}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<table class="min-w-full divide-y divide-line">
|
||||
<thead class="bg-muted">
|
||||
<tr>
|
||||
<th class="px-6 py-3 text-left text-xs font-bold tracking-wider text-ink-2 uppercase"
|
||||
>{m.admin_col_login()}</th
|
||||
>
|
||||
<th class="px-6 py-3 text-left text-xs font-bold tracking-wider text-ink-2 uppercase"
|
||||
>{m.admin_col_full_name()}</th
|
||||
>
|
||||
<th class="px-6 py-3 text-left text-xs font-bold tracking-wider text-ink-2 uppercase"
|
||||
>{m.admin_col_groups()}</th
|
||||
>
|
||||
<th class="px-6 py-3 text-right text-xs font-bold tracking-wider text-ink-2 uppercase"
|
||||
>{m.admin_col_actions()}</th
|
||||
>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-line bg-surface">
|
||||
{#each users as user (user.id)}
|
||||
<tr class="group/row hover:bg-muted">
|
||||
<td class="px-6 py-4 text-sm font-medium whitespace-nowrap text-ink">
|
||||
{user.username}
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm whitespace-nowrap text-ink-2">
|
||||
{#if user.firstName || user.lastName}
|
||||
{user.firstName ?? ''} {user.lastName ?? ''}
|
||||
{:else}
|
||||
<span class="text-ink-3 italic">–</span>
|
||||
{/if}
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm text-ink-2">
|
||||
<div class="flex flex-wrap gap-1">
|
||||
{#if user.groups && user.groups.length > 0}
|
||||
{#each user.groups as group (group.id)}
|
||||
<span
|
||||
class="rounded-full border border-blue-100 bg-blue-50 px-2 py-0.5 text-[10px] font-bold text-blue-700 uppercase"
|
||||
>
|
||||
{group.name}
|
||||
</span>
|
||||
{/each}
|
||||
{:else}
|
||||
<span class="text-xs text-ink-3 italic">{m.admin_no_groups()}</span>
|
||||
{/if}
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-right whitespace-nowrap">
|
||||
<div class="flex items-center justify-end gap-4">
|
||||
<a
|
||||
href="/admin/users/{user.id}"
|
||||
class="text-sm font-bold tracking-wide text-primary uppercase hover:text-ink-2"
|
||||
>
|
||||
{m.btn_edit()}
|
||||
</a>
|
||||
|
||||
<form
|
||||
method="POST"
|
||||
action="?/deleteUser"
|
||||
use:enhance={({ cancel }) => {
|
||||
if (!confirm(m.admin_user_delete_confirm({ username: user.username }))) {
|
||||
cancel();
|
||||
}
|
||||
return async ({ update }) => {
|
||||
await update();
|
||||
};
|
||||
}}
|
||||
class="flex items-center"
|
||||
>
|
||||
<input type="hidden" name="id" value={user.id} />
|
||||
<button
|
||||
class="p-1 text-ink-3 transition-colors hover:text-red-600"
|
||||
title={m.admin_btn_delete_user_title()}
|
||||
>
|
||||
<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
81
frontend/src/routes/admin/entity-nav.svelte.spec.ts
Normal file
81
frontend/src/routes/admin/entity-nav.svelte.spec.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { afterEach, describe, it, expect, vi } from 'vitest';
|
||||
import { cleanup, render } from 'vitest-browser-svelte';
|
||||
import { page } from 'vitest/browser';
|
||||
import EntityNav from './EntityNav.svelte';
|
||||
|
||||
vi.mock('$app/state', () => ({
|
||||
page: { url: { pathname: '/admin/users' } }
|
||||
}));
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const props = {
|
||||
userCount: 5,
|
||||
groupCount: 3,
|
||||
tagCount: 8,
|
||||
canManageUsers: true,
|
||||
canManageTags: true,
|
||||
canManagePermissions: true,
|
||||
canRunMaintenance: true
|
||||
};
|
||||
|
||||
describe('EntityNav — flyout', () => {
|
||||
it('flyout dialog is not visible initially', async () => {
|
||||
render(EntityNav, props);
|
||||
await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clicking a flyout trigger opens the dialog', async () => {
|
||||
render(EntityNav, props);
|
||||
document.querySelector<HTMLButtonElement>('[data-flyout-trigger]')!.click();
|
||||
await expect.element(page.getByRole('dialog')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('flyout dialog has aria-modal="true"', async () => {
|
||||
render(EntityNav, props);
|
||||
document.querySelector<HTMLButtonElement>('[data-flyout-trigger]')!.click();
|
||||
await expect.element(page.getByRole('dialog')).toHaveAttribute('aria-modal', 'true');
|
||||
});
|
||||
|
||||
it('flyout dialog has an aria-label', async () => {
|
||||
render(EntityNav, props);
|
||||
document.querySelector<HTMLButtonElement>('[data-flyout-trigger]')!.click();
|
||||
await expect.element(page.getByRole('dialog')).toBeInTheDocument();
|
||||
const dialog = document.querySelector('[role="dialog"]')!;
|
||||
expect(dialog.getAttribute('aria-label')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('flyout contains navigation links to each entity', async () => {
|
||||
render(EntityNav, props);
|
||||
document.querySelector<HTMLButtonElement>('[data-flyout-trigger]')!.click();
|
||||
await expect.element(page.getByRole('dialog')).toBeInTheDocument();
|
||||
const dialog = document.querySelector('[role="dialog"]')!;
|
||||
const links = dialog.querySelectorAll('a[href^="/admin/"]');
|
||||
expect(links.length).toBeGreaterThanOrEqual(3);
|
||||
});
|
||||
|
||||
it('pressing Escape closes the flyout', async () => {
|
||||
render(EntityNav, props);
|
||||
document.querySelector<HTMLButtonElement>('[data-flyout-trigger]')!.click();
|
||||
await expect.element(page.getByRole('dialog')).toBeInTheDocument();
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
|
||||
await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clicking the backdrop closes the flyout', async () => {
|
||||
render(EntityNav, props);
|
||||
document.querySelector<HTMLButtonElement>('[data-flyout-trigger]')!.click();
|
||||
await expect.element(page.getByRole('dialog')).toBeInTheDocument();
|
||||
document.querySelector<HTMLElement>('[data-flyout-backdrop]')!.click();
|
||||
await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clicking a flyout link closes the flyout', async () => {
|
||||
render(EntityNav, props);
|
||||
document.querySelector<HTMLButtonElement>('[data-flyout-trigger]')!.click();
|
||||
await expect.element(page.getByRole('dialog')).toBeInTheDocument();
|
||||
const dialog = document.querySelector('[role="dialog"]')!;
|
||||
dialog.querySelector<HTMLAnchorElement>('a[href^="/admin/"]')!.click();
|
||||
await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
8
frontend/src/routes/admin/groups/+layout.server.ts
Normal file
8
frontend/src/routes/admin/groups/+layout.server.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { createApiClient } from '$lib/api.server';
|
||||
import type { LayoutServerLoad } from './$types';
|
||||
|
||||
export const load: LayoutServerLoad = async ({ fetch }) => {
|
||||
const api = createApiClient(fetch);
|
||||
const result = await api.GET('/api/groups');
|
||||
return { groups: result.data ?? [] };
|
||||
};
|
||||
17
frontend/src/routes/admin/groups/+layout.svelte
Normal file
17
frontend/src/routes/admin/groups/+layout.svelte
Normal file
@@ -0,0 +1,17 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/state';
|
||||
import GroupsListPanel from './GroupsListPanel.svelte';
|
||||
|
||||
let { data, children } = $props();
|
||||
|
||||
const autoCollapse = $derived(page.url.pathname === '/admin/groups/new');
|
||||
const isAtListRoot = $derived(page.url.pathname === '/admin/groups');
|
||||
</script>
|
||||
|
||||
<div class="{isAtListRoot ? 'flex' : 'hidden'} flex-shrink-0 md:flex">
|
||||
<GroupsListPanel groups={data.groups} autocollapse={autoCollapse} />
|
||||
</div>
|
||||
|
||||
<div class="{isAtListRoot ? 'hidden' : 'flex'} min-w-0 flex-1 flex-col overflow-hidden md:flex">
|
||||
{@render children()}
|
||||
</div>
|
||||
7
frontend/src/routes/admin/groups/+page.svelte
Normal file
7
frontend/src/routes/admin/groups/+page.svelte
Normal file
@@ -0,0 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
</script>
|
||||
|
||||
<div class="flex flex-1 items-center justify-center p-8">
|
||||
<p class="text-sm text-ink-3">{m.admin_groups_select_prompt()}</p>
|
||||
</div>
|
||||
109
frontend/src/routes/admin/groups/GroupsListPanel.svelte
Normal file
109
frontend/src/routes/admin/groups/GroupsListPanel.svelte
Normal file
@@ -0,0 +1,109 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/state';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
type Group = {
|
||||
id: string;
|
||||
name: string;
|
||||
permissions: string[];
|
||||
};
|
||||
|
||||
let {
|
||||
groups,
|
||||
autocollapse = false
|
||||
}: {
|
||||
groups: Group[];
|
||||
autocollapse?: boolean;
|
||||
} = $props();
|
||||
|
||||
let manualCollapse = $state(
|
||||
typeof localStorage !== 'undefined' &&
|
||||
localStorage.getItem('admin_groups_list_collapsed') === 'true'
|
||||
);
|
||||
const isCollapsed = $derived(autocollapse || manualCollapse);
|
||||
|
||||
$effect(() => {
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
localStorage.setItem('admin_groups_list_collapsed', String(manualCollapse));
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if isCollapsed}
|
||||
<!-- Collapsed handle: 32px -->
|
||||
<button
|
||||
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"
|
||||
>
|
||||
<span class="text-sm font-bold text-ink-2">›</span>
|
||||
<span
|
||||
class="text-[8px] font-extrabold tracking-widest text-ink-3 uppercase"
|
||||
style="writing-mode: vertical-rl; transform: rotate(180deg);"
|
||||
>
|
||||
{m.admin_tab_groups()}
|
||||
</span>
|
||||
</button>
|
||||
{:else}
|
||||
<div
|
||||
class="flex w-[200px] flex-shrink-0 flex-col overflow-hidden border-r border-line bg-surface"
|
||||
>
|
||||
<!-- Panel header -->
|
||||
<div class="flex items-center justify-between border-b border-line px-3 py-2">
|
||||
<span class="text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_groups_list_title()}
|
||||
</span>
|
||||
<div class="flex items-center gap-1">
|
||||
<a
|
||||
href="/admin/groups/new"
|
||||
class="inline-flex items-center gap-1 rounded-sm px-2 py-1 text-xs font-medium text-ink-2 transition-colors hover:bg-muted hover:text-ink"
|
||||
title={m.admin_btn_new_group()}
|
||||
aria-label={m.admin_btn_new_group()}
|
||||
>
|
||||
<svg
|
||||
class="h-3.5 w-3.5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="2.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
</a>
|
||||
<button
|
||||
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"
|
||||
>
|
||||
‹
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Scrollable group list -->
|
||||
<div class="flex-1 overflow-y-auto">
|
||||
{#if groups.length === 0}
|
||||
<p class="px-4 py-6 text-center text-xs text-ink-3">
|
||||
{m.admin_groups_empty()}
|
||||
</p>
|
||||
{:else}
|
||||
{#each groups as group (group.id)}
|
||||
{@const isActive = page.url.pathname.startsWith('/admin/groups/' + group.id)}
|
||||
<a
|
||||
href="/admin/groups/{group.id}"
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
class="block border-l-2 px-3 py-2.5 transition-colors {isActive
|
||||
? 'border-primary bg-primary/10 dark:bg-primary/15'
|
||||
: 'border-transparent hover:bg-muted'}"
|
||||
>
|
||||
<div class="text-sm font-bold text-ink">{group.name}</div>
|
||||
<div class="mt-0.5 text-xs text-ink-3">
|
||||
{m.admin_groups_permission_count({ count: group.permissions.length })}
|
||||
</div>
|
||||
</a>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
47
frontend/src/routes/admin/groups/[id]/+page.server.ts
Normal file
47
frontend/src/routes/admin/groups/[id]/+page.server.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { error, fail, redirect } from '@sveltejs/kit';
|
||||
import type { PageServerLoad, Actions } from './$types';
|
||||
import { createApiClient } from '$lib/api.server';
|
||||
import { getErrorMessage } from '$lib/errors';
|
||||
|
||||
export const load: PageServerLoad = async ({ params, parent }) => {
|
||||
const { groups } = await parent();
|
||||
const group = groups.find((g: { id: string }) => g.id === params.id);
|
||||
if (!group) throw error(404, getErrorMessage('GROUP_NOT_FOUND'));
|
||||
return { group };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
update: async ({ params, request, fetch }) => {
|
||||
const data = await request.formData();
|
||||
const api = createApiClient(fetch);
|
||||
|
||||
const result = await api.PATCH('/api/groups/{id}', {
|
||||
params: { path: { id: params.id } },
|
||||
body: {
|
||||
name: data.get('name') as string,
|
||||
permissions: data.getAll('permissions') as string[]
|
||||
}
|
||||
});
|
||||
|
||||
if (!result.response.ok) {
|
||||
const code = (result.error as unknown as { code?: string })?.code;
|
||||
return fail(result.response.status, { error: getErrorMessage(code) });
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
},
|
||||
|
||||
delete: async ({ params, fetch }) => {
|
||||
const api = createApiClient(fetch);
|
||||
const result = await api.DELETE('/api/groups/{id}', {
|
||||
params: { path: { id: params.id } }
|
||||
});
|
||||
|
||||
if (!result.response.ok) {
|
||||
const code = (result.error as unknown as { code?: string })?.code;
|
||||
return fail(result.response.status, { error: getErrorMessage(code) });
|
||||
}
|
||||
|
||||
throw redirect(303, '/admin/groups');
|
||||
}
|
||||
};
|
||||
208
frontend/src/routes/admin/groups/[id]/+page.svelte
Normal file
208
frontend/src/routes/admin/groups/[id]/+page.svelte
Normal file
@@ -0,0 +1,208 @@
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { beforeNavigate, goto } from '$app/navigation';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
let { data, form } = $props();
|
||||
|
||||
let isDirty = $state(false);
|
||||
let showUnsavedWarning = $state(false);
|
||||
let discardTarget: string | null = $state(null);
|
||||
|
||||
beforeNavigate(({ cancel, to }) => {
|
||||
if (isDirty) {
|
||||
cancel();
|
||||
showUnsavedWarning = true;
|
||||
discardTarget = to?.url.href ?? null;
|
||||
}
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (form?.success) {
|
||||
isDirty = false;
|
||||
showUnsavedWarning = false;
|
||||
}
|
||||
});
|
||||
|
||||
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 = $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>
|
||||
<form
|
||||
method="POST"
|
||||
action="?/delete"
|
||||
use:enhance={({ cancel }) => {
|
||||
if (!confirm(m.admin_group_delete_confirm())) cancel();
|
||||
return async ({ update }) => {
|
||||
await update();
|
||||
};
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="submit"
|
||||
class="rounded-sm border border-red-200 bg-red-50 px-3 py-1.5 font-sans text-xs font-bold tracking-widest text-red-700 uppercase transition-colors hover:bg-red-100 dark:border-red-800 dark:bg-red-950/40 dark:text-red-400 dark:hover:bg-red-950/60"
|
||||
>
|
||||
{m.btn_delete()}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Scrollable body -->
|
||||
<div class="flex-1 overflow-y-auto px-5 py-5">
|
||||
{#if showUnsavedWarning}
|
||||
<div
|
||||
class="mb-5 flex items-center justify-between rounded border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-300"
|
||||
>
|
||||
<span>{m.admin_unsaved_warning()}</span>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => {
|
||||
isDirty = false;
|
||||
showUnsavedWarning = false;
|
||||
if (discardTarget) goto(discardTarget);
|
||||
}}
|
||||
class="ml-4 shrink-0 font-sans text-xs font-bold tracking-widest text-amber-800 uppercase hover:text-amber-900 dark:text-amber-300"
|
||||
>
|
||||
{m.person_discard_changes()}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
{#if form?.success}
|
||||
<div
|
||||
class="mb-5 rounded border border-green-200 bg-green-50 p-3 text-sm text-green-700 dark:border-green-800 dark:bg-green-950/40 dark:text-green-400"
|
||||
>
|
||||
{m.admin_group_updated()}
|
||||
</div>
|
||||
{/if}
|
||||
{#if form?.error}
|
||||
<div
|
||||
class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700 dark:border-red-800 dark:bg-red-950/40 dark:text-red-400"
|
||||
>
|
||||
{form.error}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<form
|
||||
id="edit-group-form"
|
||||
method="POST"
|
||||
action="?/update"
|
||||
use:enhance
|
||||
oninput={() => {
|
||||
isDirty = true;
|
||||
showUnsavedWarning = false;
|
||||
}}
|
||||
>
|
||||
<!-- Group name card -->
|
||||
<div class="mb-5 rounded-sm border border-line bg-surface p-5 shadow-sm">
|
||||
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_col_name()}
|
||||
</h3>
|
||||
<input
|
||||
type="text"
|
||||
name="name"
|
||||
value={data.group.name}
|
||||
required
|
||||
class="bg-background w-full rounded-sm border border-line px-3 py-2 font-sans text-sm text-ink placeholder:text-ink-3 focus:border-primary focus:ring-1 focus:ring-primary focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Standard permissions card -->
|
||||
<div class="mb-5 rounded-sm border border-line bg-surface p-5 shadow-sm">
|
||||
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_groups_section_standard()}
|
||||
</h3>
|
||||
<div class="space-y-3">
|
||||
{#each STANDARD_PERMISSIONS as perm (perm.value)}
|
||||
<label class="flex items-center gap-2 text-sm text-ink">
|
||||
<input
|
||||
type="checkbox"
|
||||
name="permissions"
|
||||
value={perm.value}
|
||||
checked={data.group.permissions.includes(perm.value)}
|
||||
class="h-4 w-4 rounded border-line text-primary focus:ring-primary"
|
||||
/>
|
||||
{perm.label}
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Administrative permissions card -->
|
||||
<div
|
||||
class="rounded-sm border border-amber-200 bg-amber-50 p-5 shadow-sm dark:border-amber-900 dark:bg-amber-950/30"
|
||||
>
|
||||
<h3
|
||||
class="mb-4 text-xs font-bold tracking-widest text-amber-700 uppercase dark:text-amber-400"
|
||||
>
|
||||
{m.admin_groups_section_administrative()}
|
||||
</h3>
|
||||
<div class="space-y-3">
|
||||
{#each ADMIN_PERMISSIONS as perm (perm.value)}
|
||||
<label
|
||||
class="flex items-center gap-2 text-sm {perm.value === 'ADMIN'
|
||||
? 'font-semibold text-amber-800 dark:text-amber-300'
|
||||
: 'text-ink'}"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="permissions"
|
||||
value={perm.value}
|
||||
checked={data.group.permissions.includes(perm.value)}
|
||||
class="h-4 w-4 rounded border-amber-300 text-amber-600 focus:ring-amber-500 dark:border-amber-700"
|
||||
/>
|
||||
{perm.label}
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Docked footer -->
|
||||
<div class="flex items-center justify-between border-t border-line bg-surface px-5 py-3">
|
||||
<a
|
||||
href="/admin/groups"
|
||||
class="font-sans text-xs font-bold tracking-widest text-ink-2 uppercase hover:text-ink"
|
||||
>
|
||||
{m.btn_cancel()}
|
||||
</a>
|
||||
<button
|
||||
type="submit"
|
||||
form="edit-group-form"
|
||||
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
>
|
||||
{m.btn_save()}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
87
frontend/src/routes/admin/groups/[id]/page.server.spec.ts
Normal file
87
frontend/src/routes/admin/groups/[id]/page.server.spec.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
149
frontend/src/routes/admin/groups/[id]/page.svelte.spec.ts
Normal file
149
frontend/src/routes/admin/groups/[id]/page.svelte.spec.ts
Normal file
@@ -0,0 +1,149 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { cleanup, render } from 'vitest-browser-svelte';
|
||||
import { page } from 'vitest/browser';
|
||||
import Page from './+page.svelte';
|
||||
|
||||
vi.mock('$app/forms', () => ({ enhance: () => () => {} }));
|
||||
vi.mock('$app/navigation', () => ({ beforeNavigate: vi.fn(), goto: vi.fn() }));
|
||||
|
||||
import { beforeNavigate, goto } from '$app/navigation';
|
||||
|
||||
const baseGroup = { id: 'g1', name: 'Editoren', permissions: ['WRITE_ALL'] };
|
||||
const baseData = { group: baseGroup };
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
// ─── Rendering ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('Admin edit group page – rendering', () => {
|
||||
it('renders the heading with group name', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
await expect.element(page.getByText(/Gruppe: Editoren/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('pre-fills the name input', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const input = document.querySelector<HTMLInputElement>('input[name="name"]');
|
||||
expect(input?.value).toBe('Editoren');
|
||||
});
|
||||
|
||||
it('pre-checks permissions that the group already has', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const checkbox = document.querySelector<HTMLInputElement>(
|
||||
'input[type="checkbox"][name="permissions"][value="WRITE_ALL"]'
|
||||
);
|
||||
expect(checkbox?.checked).toBe(true);
|
||||
});
|
||||
|
||||
it('renders the cancel link pointing to /admin/groups', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /Abbrechen/i }))
|
||||
.toHaveAttribute('href', '/admin/groups');
|
||||
});
|
||||
|
||||
it('renders a READ_ALL checkbox in the standard permissions section', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const cb = document.querySelector<HTMLInputElement>(
|
||||
'input[type="checkbox"][name="permissions"][value="READ_ALL"]'
|
||||
);
|
||||
expect(cb).not.toBeNull();
|
||||
});
|
||||
|
||||
it('renders an ANNOTATE_ALL checkbox in the standard permissions section', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const cb = document.querySelector<HTMLInputElement>(
|
||||
'input[type="checkbox"][name="permissions"][value="ANNOTATE_ALL"]'
|
||||
);
|
||||
expect(cb).not.toBeNull();
|
||||
});
|
||||
|
||||
it('pre-checks READ_ALL when group has it', async () => {
|
||||
const data = { group: { id: 'g2', name: 'Leser', permissions: ['READ_ALL'] } };
|
||||
render(Page, { data, form: null });
|
||||
const cb = document.querySelector<HTMLInputElement>(
|
||||
'input[type="checkbox"][name="permissions"][value="READ_ALL"]'
|
||||
);
|
||||
expect(cb?.checked).toBe(true);
|
||||
});
|
||||
|
||||
it('pre-checks ANNOTATE_ALL when group has it', async () => {
|
||||
const data = {
|
||||
group: { id: 'g3', name: 'Annotatoren', permissions: ['READ_ALL', 'ANNOTATE_ALL'] }
|
||||
};
|
||||
render(Page, { data, form: null });
|
||||
const cb = document.querySelector<HTMLInputElement>(
|
||||
'input[type="checkbox"][name="permissions"][value="ANNOTATE_ALL"]'
|
||||
);
|
||||
expect(cb?.checked).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Unsaved-changes guard ────────────────────────────────────────────────────
|
||||
|
||||
describe('Admin edit group page – unsaved-changes guard', () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it('does not show unsaved warning initially', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('cancels navigation and shows warning when form is dirty', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="name"]')!
|
||||
.dispatchEvent(new InputEvent('input', { bubbles: true }));
|
||||
|
||||
const cancel = vi.fn();
|
||||
callback({ cancel, to: { url: new URL('http://localhost/admin/groups/g2') } });
|
||||
|
||||
expect(cancel).toHaveBeenCalled();
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not cancel navigation when form is clean', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
const cancel = vi.fn();
|
||||
callback({ cancel, to: { url: new URL('http://localhost/admin/groups/g2') } });
|
||||
|
||||
expect(cancel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('discard button calls goto with the target URL', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="name"]')!
|
||||
.dispatchEvent(new InputEvent('input', { bubbles: true }));
|
||||
|
||||
callback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/groups/g2') } });
|
||||
|
||||
await page.getByRole('button', { name: /verwerfen/i }).click();
|
||||
|
||||
expect(vi.mocked(goto)).toHaveBeenCalledWith('http://localhost/admin/groups/g2');
|
||||
});
|
||||
|
||||
it('clears dirty state when form saves successfully', async () => {
|
||||
const { rerender } = render(Page, { data: baseData, form: null });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="name"]')!
|
||||
.dispatchEvent(new InputEvent('input', { bubbles: true }));
|
||||
|
||||
callback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/groups/g2') } });
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument();
|
||||
|
||||
await rerender({ data: baseData, form: { success: true } });
|
||||
|
||||
const cancel = vi.fn();
|
||||
callback({ cancel, to: { url: new URL('http://localhost/admin/groups/g2') } });
|
||||
expect(cancel).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
41
frontend/src/routes/admin/groups/layout.server.spec.ts
Normal file
41
frontend/src/routes/admin/groups/layout.server.spec.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { load } from './+layout.server';
|
||||
|
||||
vi.mock('$lib/api.server', () => ({ createApiClient: vi.fn() }));
|
||||
|
||||
import { createApiClient } from '$lib/api.server';
|
||||
|
||||
function mockApi(groups: unknown[]) {
|
||||
vi.mocked(createApiClient).mockReturnValue({
|
||||
GET: vi.fn().mockResolvedValueOnce({ response: { ok: true }, data: groups })
|
||||
} as ReturnType<typeof createApiClient>);
|
||||
}
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('admin/groups layout load', () => {
|
||||
it('returns the groups list', async () => {
|
||||
mockApi([
|
||||
{ id: 'g1', name: 'Admins', permissions: ['ADMIN'] },
|
||||
{ id: 'g2', name: 'Editors', permissions: ['WRITE_ALL'] }
|
||||
]);
|
||||
const result = await load({ fetch: vi.fn() as unknown as typeof fetch });
|
||||
expect(result.groups).toHaveLength(2);
|
||||
expect(result.groups[0].name).toBe('Admins');
|
||||
});
|
||||
|
||||
it('returns an empty array when the API returns nothing', async () => {
|
||||
mockApi([]);
|
||||
const result = await load({ fetch: vi.fn() as unknown as typeof fetch });
|
||||
expect(result.groups).toEqual([]);
|
||||
});
|
||||
|
||||
it('calls GET /api/groups', async () => {
|
||||
const mockGet = vi.fn().mockResolvedValue({ response: { ok: true }, data: [] });
|
||||
vi.mocked(createApiClient).mockReturnValue({ GET: mockGet } as ReturnType<
|
||||
typeof createApiClient
|
||||
>);
|
||||
await load({ fetch: vi.fn() as unknown as typeof fetch });
|
||||
expect(mockGet).toHaveBeenCalledWith('/api/groups');
|
||||
});
|
||||
});
|
||||
118
frontend/src/routes/admin/groups/layout.svelte.spec.ts
Normal file
118
frontend/src/routes/admin/groups/layout.svelte.spec.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest';
|
||||
import { cleanup, render } from 'vitest-browser-svelte';
|
||||
import { page } from 'vitest/browser';
|
||||
import GroupsListPanel from './GroupsListPanel.svelte';
|
||||
|
||||
vi.mock('$app/state', () => ({
|
||||
page: { url: { pathname: '/admin/groups/g1' } }
|
||||
}));
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const groups = [
|
||||
{ id: 'g1', name: 'Administrators', permissions: ['ADMIN', 'WRITE_ALL'] },
|
||||
{ id: 'g2', name: 'Editors', permissions: ['WRITE_ALL'] },
|
||||
{ id: 'g3', name: 'Readers', permissions: [] }
|
||||
];
|
||||
|
||||
describe('GroupsListPanel — header', () => {
|
||||
it('renders the panel title', async () => {
|
||||
render(GroupsListPanel, { groups });
|
||||
await expect.element(page.getByText(/Alle Gruppen/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders a new-group link pointing to /admin/groups/new', async () => {
|
||||
render(GroupsListPanel, { groups });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /neue gruppe/i }))
|
||||
.toHaveAttribute('href', '/admin/groups/new');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GroupsListPanel — group items', () => {
|
||||
it('renders each group name', async () => {
|
||||
render(GroupsListPanel, { groups });
|
||||
await expect.element(page.getByRole('link', { name: /administrators/i })).toBeInTheDocument();
|
||||
await expect.element(page.getByRole('link', { name: /editors/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('each group links to /admin/groups/[id]', async () => {
|
||||
const { container } = render(GroupsListPanel, { groups });
|
||||
const links = container.querySelectorAll<HTMLAnchorElement>('a[href^="/admin/groups/g"]');
|
||||
expect(links.length).toBe(3);
|
||||
expect(links[0].getAttribute('href')).toBe('/admin/groups/g1');
|
||||
});
|
||||
|
||||
it('shows permission count as subtitle', async () => {
|
||||
render(GroupsListPanel, { groups });
|
||||
// Administrators has 2 permissions
|
||||
await expect.element(page.getByText(/2 Berechtigungen/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows "no permissions" for a group with zero permissions', async () => {
|
||||
render(GroupsListPanel, { groups });
|
||||
await expect.element(page.getByText(/0 Berechtigungen/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('GroupsListPanel — active state', () => {
|
||||
it('marks the active group link with aria-current=page', async () => {
|
||||
render(GroupsListPanel, { groups });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /administrators/i }))
|
||||
.toHaveAttribute('aria-current', 'page');
|
||||
});
|
||||
|
||||
it('does not mark inactive group links with aria-current', async () => {
|
||||
render(GroupsListPanel, { groups });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /editors/i }))
|
||||
.not.toHaveAttribute('aria-current');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GroupsListPanel — empty state', () => {
|
||||
it('shows empty state when groups array is empty', async () => {
|
||||
render(GroupsListPanel, { groups: [] });
|
||||
await expect.element(page.getByText(/keine gruppen/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Collapse toggle ──────────────────────────────────────────────────────────
|
||||
|
||||
describe('GroupsListPanel — collapse toggle', () => {
|
||||
beforeEach(() => localStorage.removeItem('admin_groups_list_collapsed'));
|
||||
|
||||
it('renders a collapse button with aria-label', async () => {
|
||||
render(GroupsListPanel, { groups });
|
||||
await expect
|
||||
.element(page.getByRole('button', { name: /Liste einklappen/i }))
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clicking collapse shows the expand handle', async () => {
|
||||
render(GroupsListPanel, { groups });
|
||||
await expect
|
||||
.element(page.getByRole('button', { name: /Liste einklappen/i }))
|
||||
.toBeInTheDocument();
|
||||
document.querySelector<HTMLButtonElement>('[aria-label="Liste einklappen"]')!.click();
|
||||
await expect
|
||||
.element(page.getByRole('button', { name: /Liste ausklappen/i }))
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('autocollapse prop starts the panel in collapsed state', async () => {
|
||||
render(GroupsListPanel, { groups, autocollapse: true });
|
||||
await expect
|
||||
.element(page.getByRole('button', { name: /Liste ausklappen/i }))
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
25
frontend/src/routes/admin/groups/new/+page.server.ts
Normal file
25
frontend/src/routes/admin/groups/new/+page.server.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { fail, redirect } from '@sveltejs/kit';
|
||||
import type { Actions } from './$types';
|
||||
import { createApiClient } from '$lib/api.server';
|
||||
import { getErrorMessage } from '$lib/errors';
|
||||
|
||||
export const actions: Actions = {
|
||||
default: async ({ request, fetch }) => {
|
||||
const data = await request.formData();
|
||||
const api = createApiClient(fetch);
|
||||
|
||||
const result = await api.POST('/api/groups', {
|
||||
body: {
|
||||
name: data.get('name') as string,
|
||||
permissions: data.getAll('permissions') as string[]
|
||||
}
|
||||
});
|
||||
|
||||
if (!result.response.ok) {
|
||||
const code = (result.error as unknown as { code?: string })?.code;
|
||||
return fail(result.response.status, { error: getErrorMessage(code) });
|
||||
}
|
||||
|
||||
throw redirect(303, '/admin/groups');
|
||||
}
|
||||
};
|
||||
176
frontend/src/routes/admin/groups/new/+page.svelte
Normal file
176
frontend/src/routes/admin/groups/new/+page.svelte
Normal file
@@ -0,0 +1,176 @@
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { beforeNavigate, goto } from '$app/navigation';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
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: string | null = $state(null);
|
||||
|
||||
beforeNavigate(({ cancel, to }) => {
|
||||
if (isDirty) {
|
||||
cancel();
|
||||
showUnsavedWarning = true;
|
||||
discardTarget = to?.url.href ?? null;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="flex flex-1 flex-col overflow-hidden">
|
||||
<!-- Detail panel header -->
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<!-- Scrollable body -->
|
||||
<div class="flex-1 overflow-y-auto px-5 py-5">
|
||||
{#if showUnsavedWarning}
|
||||
<div
|
||||
class="mb-5 flex items-center justify-between rounded border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-300"
|
||||
>
|
||||
<span>{m.admin_unsaved_warning()}</span>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => {
|
||||
isDirty = false;
|
||||
showUnsavedWarning = false;
|
||||
if (discardTarget) goto(discardTarget);
|
||||
}}
|
||||
class="ml-4 shrink-0 font-sans text-xs font-bold tracking-widest text-amber-800 uppercase hover:text-amber-900 dark:text-amber-300"
|
||||
>
|
||||
{m.person_discard_changes()}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
{#if form?.error}
|
||||
<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
|
||||
{form.error}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<form
|
||||
id="new-group-form"
|
||||
method="POST"
|
||||
use:enhance
|
||||
oninput={() => {
|
||||
isDirty = true;
|
||||
showUnsavedWarning = false;
|
||||
}}
|
||||
class="space-y-5"
|
||||
>
|
||||
<!-- Name card -->
|
||||
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
|
||||
<h3 class="mb-3 text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_col_name()}
|
||||
</h3>
|
||||
<input
|
||||
type="text"
|
||||
name="name"
|
||||
placeholder={m.admin_group_name_placeholder()}
|
||||
required
|
||||
class="w-full rounded-sm border border-line bg-surface px-3 py-2 text-sm text-ink placeholder:text-ink-3 focus:ring-1 focus:ring-primary focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Standard permissions -->
|
||||
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
|
||||
<h3 class="mb-3 text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_groups_section_standard()}
|
||||
</h3>
|
||||
<div class="space-y-2">
|
||||
{#each availableStandard as perm (perm.value)}
|
||||
<label class="flex items-center gap-2 text-sm text-ink">
|
||||
<input
|
||||
type="checkbox"
|
||||
name="permissions"
|
||||
value={perm.value}
|
||||
class="rounded border-line text-primary focus:ring-primary"
|
||||
/>
|
||||
<span class="font-mono text-xs font-bold uppercase">{perm.value}</span>
|
||||
<span class="text-ink-3">— {perm.label}</span>
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Administrative permissions -->
|
||||
<div
|
||||
class="rounded-sm border border-amber-200 bg-amber-50 p-5 shadow-sm dark:border-amber-900 dark:bg-amber-950/30"
|
||||
>
|
||||
<h3
|
||||
class="mb-3 text-xs font-bold tracking-widest text-amber-700 uppercase dark:text-amber-400"
|
||||
>
|
||||
{m.admin_groups_section_administrative()}
|
||||
</h3>
|
||||
<div class="space-y-2">
|
||||
{#each availableAdmin as perm (perm.value)}
|
||||
<label
|
||||
class="flex items-center gap-2 text-sm {perm.value === 'ADMIN'
|
||||
? 'font-bold text-red-700 dark:text-red-400'
|
||||
: 'text-ink'}"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="permissions"
|
||||
value={perm.value}
|
||||
class="rounded border-line text-primary focus:ring-primary"
|
||||
/>
|
||||
<span class="font-mono text-xs font-bold uppercase">{perm.value}</span>
|
||||
<span class="font-normal text-ink-3">— {perm.label}</span>
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Docked footer -->
|
||||
<div class="flex items-center justify-between border-t border-line bg-surface px-5 py-3">
|
||||
<a
|
||||
href="/admin/groups"
|
||||
class="font-sans text-xs font-bold tracking-widest text-ink-2 uppercase hover:text-ink"
|
||||
>
|
||||
{m.btn_cancel()}
|
||||
</a>
|
||||
<button
|
||||
type="submit"
|
||||
form="new-group-form"
|
||||
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
>
|
||||
{m.btn_create()}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
72
frontend/src/routes/admin/layout.server.spec.ts
Normal file
72
frontend/src/routes/admin/layout.server.spec.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { load } from './+layout.server';
|
||||
|
||||
vi.mock('$lib/api.server', () => ({ createApiClient: vi.fn() }));
|
||||
|
||||
import { createApiClient } from '$lib/api.server';
|
||||
|
||||
function mockApi(users: unknown[], groups: unknown[], tags: unknown[]) {
|
||||
vi.mocked(createApiClient).mockReturnValue({
|
||||
GET: vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ response: { ok: true }, data: users })
|
||||
.mockResolvedValueOnce({ response: { ok: true }, data: groups })
|
||||
.mockResolvedValueOnce({ response: { ok: true }, data: tags })
|
||||
} as ReturnType<typeof createApiClient>);
|
||||
}
|
||||
|
||||
const adminUser = {
|
||||
groups: [{ permissions: ['ADMIN', 'ADMIN_USER', 'ADMIN_TAG', 'ADMIN_PERMISSION'] }]
|
||||
};
|
||||
const tagAdminUser = { groups: [{ permissions: ['ADMIN_TAG'] }] };
|
||||
const noPermUser = { groups: [{ permissions: ['READ_ALL'] }] };
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('admin layout load — permission check', () => {
|
||||
it('throws 403 when user has no admin permission', async () => {
|
||||
await expect(
|
||||
load({ fetch: vi.fn() as unknown as typeof fetch, locals: { user: noPermUser } })
|
||||
).rejects.toMatchObject({ status: 403 });
|
||||
});
|
||||
|
||||
it('throws 403 when user is undefined', async () => {
|
||||
await expect(
|
||||
load({ fetch: vi.fn() as unknown as typeof fetch, locals: { user: undefined } })
|
||||
).rejects.toMatchObject({ status: 403 });
|
||||
});
|
||||
|
||||
it('throws 403 when user has no groups', async () => {
|
||||
await expect(
|
||||
load({ fetch: vi.fn() as unknown as typeof fetch, locals: { user: { groups: [] } } })
|
||||
).rejects.toMatchObject({ status: 403 });
|
||||
});
|
||||
|
||||
it('allows access for a user with ADMIN_TAG only', async () => {
|
||||
mockApi([], [], []);
|
||||
await expect(
|
||||
load({ fetch: vi.fn() as unknown as typeof fetch, locals: { user: tagAdminUser } })
|
||||
).resolves.toBeDefined();
|
||||
});
|
||||
|
||||
it('returns entity counts and permission flags for a full admin', async () => {
|
||||
mockApi(
|
||||
[{ id: 'u1' }, { id: 'u2' }],
|
||||
[{ id: 'g1' }],
|
||||
[{ id: 't1' }, { id: 't2' }, { id: 't3' }]
|
||||
);
|
||||
|
||||
const result = await load({
|
||||
fetch: vi.fn() as unknown as typeof fetch,
|
||||
locals: { user: adminUser }
|
||||
});
|
||||
|
||||
expect(result.userCount).toBe(2);
|
||||
expect(result.groupCount).toBe(1);
|
||||
expect(result.tagCount).toBe(3);
|
||||
expect(result.canManageUsers).toBe(true);
|
||||
expect(result.canManageTags).toBe(true);
|
||||
expect(result.canManagePermissions).toBe(true);
|
||||
expect(result.canRunMaintenance).toBe(true);
|
||||
});
|
||||
});
|
||||
87
frontend/src/routes/admin/layout.svelte.spec.ts
Normal file
87
frontend/src/routes/admin/layout.svelte.spec.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* Layout shell tests — we test EntityNav.svelte directly since the layout
|
||||
* itself is a thin shell that just composes EntityNav and renders children.
|
||||
*/
|
||||
import { afterEach, describe, it, expect, vi } from 'vitest';
|
||||
import { cleanup, render } from 'vitest-browser-svelte';
|
||||
import { page } from 'vitest/browser';
|
||||
import EntityNav from './EntityNav.svelte';
|
||||
|
||||
vi.mock('$app/state', () => ({
|
||||
page: { url: { pathname: '/admin/users' } }
|
||||
}));
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const fullPerms = {
|
||||
userCount: 4,
|
||||
groupCount: 3,
|
||||
tagCount: 7,
|
||||
canManageUsers: true,
|
||||
canManageTags: true,
|
||||
canManagePermissions: true,
|
||||
canRunMaintenance: true
|
||||
};
|
||||
|
||||
describe('admin EntityNav — links', () => {
|
||||
it('renders users nav link pointing to /admin/users', async () => {
|
||||
render(EntityNav, fullPerms);
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /benutzer/i }))
|
||||
.toHaveAttribute('href', '/admin/users');
|
||||
});
|
||||
|
||||
it('renders groups nav link pointing to /admin/groups', async () => {
|
||||
render(EntityNav, fullPerms);
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /gruppen/i }))
|
||||
.toHaveAttribute('href', '/admin/groups');
|
||||
});
|
||||
|
||||
it('renders tags nav link pointing to /admin/tags', async () => {
|
||||
render(EntityNav, fullPerms);
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /schlagworte/i }))
|
||||
.toHaveAttribute('href', '/admin/tags');
|
||||
});
|
||||
|
||||
it('renders system nav link pointing to /admin/system', async () => {
|
||||
render(EntityNav, fullPerms);
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /system/i }))
|
||||
.toHaveAttribute('href', '/admin/system');
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin EntityNav — permission-based rendering', () => {
|
||||
it('hides users link when canManageUsers is false', async () => {
|
||||
render(EntityNav, { ...fullPerms, canManageUsers: false });
|
||||
await expect.element(page.getByRole('link', { name: /benutzer/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides tags link when canManageTags is false', async () => {
|
||||
render(EntityNav, { ...fullPerms, canManageTags: false });
|
||||
await expect.element(page.getByRole('link', { name: /schlagworte/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides system link when canRunMaintenance is false', async () => {
|
||||
render(EntityNav, { ...fullPerms, canRunMaintenance: false });
|
||||
await expect.element(page.getByRole('link', { name: /system/i })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin EntityNav — active state', () => {
|
||||
it('marks users link as aria-current=page when on /admin/users', async () => {
|
||||
render(EntityNav, fullPerms);
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /benutzer/i }))
|
||||
.toHaveAttribute('aria-current', 'page');
|
||||
});
|
||||
|
||||
it('does not mark groups link as current when on /admin/users', async () => {
|
||||
render(EntityNav, fullPerms);
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /gruppen/i }))
|
||||
.not.toHaveAttribute('aria-current');
|
||||
});
|
||||
});
|
||||
@@ -1,77 +0,0 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { load } from './+page.server';
|
||||
|
||||
vi.mock('$lib/api.server', () => ({ createApiClient: vi.fn() }));
|
||||
|
||||
import { createApiClient } from '$lib/api.server';
|
||||
|
||||
const adminUser = { groups: [{ permissions: ['ADMIN'] }] };
|
||||
const readOnlyUser = { groups: [{ permissions: ['READ_ALL'] }] };
|
||||
|
||||
function mockApiReturning(users: unknown[], groups: unknown[], tags: unknown[]) {
|
||||
vi.mocked(createApiClient).mockReturnValue({
|
||||
GET: vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ response: { ok: true }, data: users })
|
||||
.mockResolvedValueOnce({ response: { ok: true }, data: groups })
|
||||
.mockResolvedValueOnce({ response: { ok: true }, data: tags })
|
||||
} as ReturnType<typeof createApiClient>);
|
||||
}
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
// ─── permission check ─────────────────────────────────────────────────────────
|
||||
|
||||
describe('admin load — permission check', () => {
|
||||
it('throws 403 when user has no ADMIN permission', async () => {
|
||||
await expect(
|
||||
load({ fetch: vi.fn() as unknown as typeof fetch, locals: { user: readOnlyUser } })
|
||||
).rejects.toMatchObject({ status: 403 });
|
||||
});
|
||||
|
||||
it('throws 403 when user is undefined', async () => {
|
||||
await expect(
|
||||
load({ fetch: vi.fn() as unknown as typeof fetch, locals: { user: undefined } })
|
||||
).rejects.toMatchObject({ status: 403 });
|
||||
});
|
||||
|
||||
it('throws 403 when user has no groups', async () => {
|
||||
await expect(
|
||||
load({ fetch: vi.fn() as unknown as typeof fetch, locals: { user: { groups: [] } } })
|
||||
).rejects.toMatchObject({ status: 403 });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── happy path ───────────────────────────────────────────────────────────────
|
||||
|
||||
describe('admin load — happy path', () => {
|
||||
it('returns users, groups, and tags for an admin user', async () => {
|
||||
mockApiReturning(
|
||||
[{ id: 'u1', username: 'alice' }],
|
||||
[{ id: 'g1', name: 'Editors' }],
|
||||
[{ id: 't1', name: 'Familie' }]
|
||||
);
|
||||
|
||||
const result = await load({
|
||||
fetch: vi.fn() as unknown as typeof fetch,
|
||||
locals: { user: adminUser }
|
||||
});
|
||||
|
||||
expect(result.users).toHaveLength(1);
|
||||
expect(result.groups).toHaveLength(1);
|
||||
expect(result.tags).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('returns empty arrays when API returns no data', async () => {
|
||||
mockApiReturning([], [], []);
|
||||
|
||||
const result = await load({
|
||||
fetch: vi.fn() as unknown as typeof fetch,
|
||||
locals: { user: adminUser }
|
||||
});
|
||||
|
||||
expect(result.users).toEqual([]);
|
||||
expect(result.groups).toEqual([]);
|
||||
expect(result.tags).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,83 +1,73 @@
|
||||
/**
|
||||
* Tests for the admin root page — the mobile entity picker.
|
||||
* On md+ viewports the page immediately redirects to /admin/users (tested
|
||||
* in e2e). Here we verify the mobile-only list of entity links.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { cleanup, render } from 'vitest-browser-svelte';
|
||||
import { page } from 'vitest/browser';
|
||||
import Page from './+page.svelte';
|
||||
|
||||
vi.mock('$app/forms', () => ({ enhance: () => () => {} }));
|
||||
vi.mock('$app/navigation', () => ({ goto: vi.fn() }));
|
||||
|
||||
const makeGroup = (overrides = {}) => ({
|
||||
id: 'g1',
|
||||
name: 'Editoren',
|
||||
permissions: ['WRITE_ALL'],
|
||||
...overrides
|
||||
});
|
||||
|
||||
const makeUser = (overrides = {}) => ({
|
||||
id: 'u1',
|
||||
username: 'max',
|
||||
firstName: 'Max',
|
||||
lastName: 'Mustermann',
|
||||
email: 'max@example.com',
|
||||
birthDate: undefined,
|
||||
contact: undefined,
|
||||
enabled: true,
|
||||
groups: [makeGroup()],
|
||||
createdAt: '2024-01-01T00:00:00Z',
|
||||
...overrides
|
||||
});
|
||||
|
||||
const baseData = {
|
||||
user: undefined,
|
||||
canWrite: true,
|
||||
canAnnotate: false,
|
||||
users: [makeUser()],
|
||||
groups: [makeGroup()],
|
||||
tags: []
|
||||
const fullData = {
|
||||
userCount: 4,
|
||||
groupCount: 3,
|
||||
tagCount: 7,
|
||||
canManageUsers: true,
|
||||
canManageTags: true,
|
||||
canManagePermissions: true,
|
||||
canRunMaintenance: true
|
||||
};
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
// ─── Users tab ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('Admin page – users tab', () => {
|
||||
it('shows the username in the table', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
await expect.element(page.getByRole('cell', { name: 'max', exact: true })).toBeInTheDocument();
|
||||
describe('Admin root page – entity picker', () => {
|
||||
it('renders the admin heading', async () => {
|
||||
render(Page, { data: fullData });
|
||||
await expect.element(page.getByRole('heading')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the full name in the table', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
await expect.element(page.getByText(/Max Mustermann/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows a dash when user has no name set', async () => {
|
||||
const data = { ...baseData, users: [makeUser({ firstName: undefined, lastName: undefined })] };
|
||||
render(Page, { data, form: null });
|
||||
await expect.element(page.getByText('–')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows group badges for the user', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
await expect.element(page.getByText('Editoren')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('edit link points to /admin/users/[id]', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
it('renders users link pointing to /admin/users', async () => {
|
||||
render(Page, { data: fullData });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /Bearbeiten/i }))
|
||||
.toHaveAttribute('href', '/admin/users/u1');
|
||||
.element(page.getByRole('link', { name: /benutzer/i }))
|
||||
.toHaveAttribute('href', '/admin/users');
|
||||
});
|
||||
|
||||
it('new user button links to /admin/users/new', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
it('renders groups link pointing to /admin/groups', async () => {
|
||||
render(Page, { data: fullData });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /Neuer Benutzer/i }))
|
||||
.toHaveAttribute('href', '/admin/users/new');
|
||||
.element(page.getByRole('link', { name: /gruppen/i }))
|
||||
.toHaveAttribute('href', '/admin/groups');
|
||||
});
|
||||
|
||||
it('shows "no groups" label when user has no groups', async () => {
|
||||
const data = { ...baseData, users: [makeUser({ groups: [] })] };
|
||||
render(Page, { data, form: null });
|
||||
await expect.element(page.getByText(/Keine Gruppen/i)).toBeInTheDocument();
|
||||
it('renders tags link pointing to /admin/tags', async () => {
|
||||
render(Page, { data: fullData });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /schlagworte/i }))
|
||||
.toHaveAttribute('href', '/admin/tags');
|
||||
});
|
||||
|
||||
it('renders system link pointing to /admin/system', async () => {
|
||||
render(Page, { data: fullData });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /system/i }))
|
||||
.toHaveAttribute('href', '/admin/system');
|
||||
});
|
||||
|
||||
it('hides users link when canManageUsers is false', async () => {
|
||||
render(Page, { data: { ...fullData, canManageUsers: false } });
|
||||
await expect.element(page.getByRole('link', { name: /benutzer/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides system link when canRunMaintenance is false', async () => {
|
||||
render(Page, { data: { ...fullData, canRunMaintenance: false } });
|
||||
await expect.element(page.getByRole('link', { name: /system/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows user count', async () => {
|
||||
render(Page, { data: fullData });
|
||||
await expect.element(page.getByText('4')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
172
frontend/src/routes/admin/system/+page.svelte
Normal file
172
frontend/src/routes/admin/system/+page.svelte
Normal file
@@ -0,0 +1,172 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy } from 'svelte';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
let backfillResult: number | null = $state(null);
|
||||
let backfillLoading = $state(false);
|
||||
let backfillHashesResult: number | null = $state(null);
|
||||
let backfillHashesLoading = $state(false);
|
||||
|
||||
type ImportStatus = {
|
||||
state: 'IDLE' | 'RUNNING' | 'DONE' | 'FAILED';
|
||||
message: string;
|
||||
processed: number;
|
||||
startedAt: string | null;
|
||||
};
|
||||
|
||||
let importStatus: ImportStatus | null = $state(null);
|
||||
let pollInterval: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
function startPolling() {
|
||||
if (pollInterval) return;
|
||||
pollInterval = setInterval(fetchImportStatus, 2000);
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollInterval) {
|
||||
clearInterval(pollInterval);
|
||||
pollInterval = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchImportStatus() {
|
||||
const res = await fetch('/api/admin/import-status');
|
||||
if (res.ok) {
|
||||
importStatus = await res.json();
|
||||
if (importStatus!.state === 'RUNNING') {
|
||||
startPolling();
|
||||
} else {
|
||||
stopPolling();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function triggerImport() {
|
||||
const res = await fetch('/api/admin/trigger-import', { method: 'POST' });
|
||||
if (res.ok) {
|
||||
importStatus = await res.json();
|
||||
if (importStatus!.state === 'RUNNING') {
|
||||
startPolling();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
fetchImportStatus();
|
||||
});
|
||||
|
||||
onDestroy(() => stopPolling());
|
||||
|
||||
async function backfillVersions() {
|
||||
backfillLoading = true;
|
||||
backfillResult = null;
|
||||
try {
|
||||
const res = await fetch('/api/admin/backfill-versions', { method: 'POST' });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
backfillResult = data.count;
|
||||
}
|
||||
} finally {
|
||||
backfillLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function backfillFileHashes() {
|
||||
backfillHashesLoading = true;
|
||||
backfillHashesResult = null;
|
||||
try {
|
||||
const res = await fetch('/api/admin/backfill-file-hashes', { method: 'POST' });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
backfillHashesResult = data.count;
|
||||
}
|
||||
} finally {
|
||||
backfillHashesLoading = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex-1 overflow-y-auto p-6">
|
||||
<div class="mx-auto max-w-2xl space-y-5">
|
||||
<!-- Backfill versions -->
|
||||
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
|
||||
<h2 class="mb-1 font-sans text-sm font-bold text-ink">{m.admin_system_backfill_heading()}</h2>
|
||||
<p class="mb-4 text-sm text-ink-2">{m.admin_system_backfill_description()}</p>
|
||||
<button
|
||||
onclick={backfillVersions}
|
||||
disabled={backfillLoading}
|
||||
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{backfillLoading ? '…' : m.admin_system_backfill_btn()}
|
||||
</button>
|
||||
{#if backfillResult !== null}
|
||||
<p class="mt-4 rounded-sm border border-green-200 bg-green-50 p-3 text-sm text-green-700">
|
||||
{m.admin_system_backfill_success({ count: backfillResult })}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Backfill file hashes -->
|
||||
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
|
||||
<h2 class="mb-1 font-sans text-sm font-bold text-ink">
|
||||
{m.admin_system_backfill_hashes_heading()}
|
||||
</h2>
|
||||
<p class="mb-4 text-sm text-ink-2">{m.admin_system_backfill_hashes_description()}</p>
|
||||
<button
|
||||
onclick={backfillFileHashes}
|
||||
disabled={backfillHashesLoading}
|
||||
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{backfillHashesLoading ? '…' : m.admin_system_backfill_hashes_btn()}
|
||||
</button>
|
||||
{#if backfillHashesResult !== null}
|
||||
<p class="mt-4 rounded-sm border border-green-200 bg-green-50 p-3 text-sm text-green-700">
|
||||
{m.admin_system_backfill_hashes_success({ count: backfillHashesResult })}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Mass import -->
|
||||
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
|
||||
<h2 class="mb-1 font-sans text-sm font-bold text-ink">{m.admin_system_import_heading()}</h2>
|
||||
<p class="mb-4 text-sm text-ink-2">{m.admin_system_import_description()}</p>
|
||||
|
||||
{#if importStatus?.state === 'RUNNING'}
|
||||
<p class="text-sm text-ink-2">{m.admin_system_import_status_running()}</p>
|
||||
{:else if importStatus?.state === 'DONE'}
|
||||
<p class="mb-4 rounded-sm border border-green-200 bg-green-50 p-3 text-sm text-green-700">
|
||||
{m.admin_system_import_status_done({ count: importStatus.processed })}
|
||||
</p>
|
||||
<button
|
||||
data-import-trigger
|
||||
onclick={triggerImport}
|
||||
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
>
|
||||
{m.admin_system_import_btn_retry()}
|
||||
</button>
|
||||
{:else if importStatus?.state === 'FAILED'}
|
||||
<p class="mb-4 rounded-sm border border-red-200 bg-red-50 p-3 text-sm text-red-700">
|
||||
{m.admin_system_import_status_failed({ message: importStatus.message })}
|
||||
</p>
|
||||
<button
|
||||
data-import-trigger
|
||||
onclick={triggerImport}
|
||||
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
>
|
||||
{m.admin_system_import_btn_retry()}
|
||||
</button>
|
||||
{:else}
|
||||
{#if importStatus !== null}
|
||||
<p class="mb-4 text-sm text-ink-2">{m.admin_system_import_status_idle()}</p>
|
||||
{/if}
|
||||
<button
|
||||
data-import-trigger
|
||||
onclick={triggerImport}
|
||||
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
>
|
||||
{m.admin_system_import_btn_start()}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
189
frontend/src/routes/admin/system/page.svelte.spec.ts
Normal file
189
frontend/src/routes/admin/system/page.svelte.spec.ts
Normal file
@@ -0,0 +1,189 @@
|
||||
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';
|
||||
|
||||
afterEach(cleanup);
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
describe('Admin system page', () => {
|
||||
it('renders the backfill versions heading', async () => {
|
||||
render(Page, {});
|
||||
await expect.element(page.getByText(/Verlaufsdaten auffüllen/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the backfill versions button', async () => {
|
||||
render(Page, {});
|
||||
await expect
|
||||
.element(page.getByRole('button', { name: /jetzt auffüllen/i }))
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the backfill file hashes heading', async () => {
|
||||
render(Page, {});
|
||||
await expect
|
||||
.element(page.getByRole('heading', { name: /Datei-Hashes berechnen/i }))
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the file hashes button', async () => {
|
||||
render(Page, {});
|
||||
await expect
|
||||
.element(page.getByRole('button', { name: /Datei-Hashes berechnen/i }))
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Admin system page — mass import card', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
state: 'IDLE',
|
||||
message: 'Kein Import gestartet.',
|
||||
processed: 0,
|
||||
startedAt: null
|
||||
})
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('renders the mass import heading', async () => {
|
||||
render(Page, {});
|
||||
await expect.element(page.getByText(/Massenimport/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the start import button when idle', async () => {
|
||||
render(Page, {});
|
||||
await expect.element(page.getByRole('button', { name: /Import starten/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows idle status text', async () => {
|
||||
render(Page, {});
|
||||
await expect.element(page.getByText(/Kein Import gestartet/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('disables the start button and shows running state after click', async () => {
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
// initial status fetch → IDLE
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
state: 'IDLE',
|
||||
message: 'Kein Import gestartet.',
|
||||
processed: 0,
|
||||
startedAt: null
|
||||
})
|
||||
})
|
||||
// trigger POST → returns RUNNING immediately
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
state: 'RUNNING',
|
||||
message: 'Import läuft...',
|
||||
processed: 0,
|
||||
startedAt: '2026-01-01T10:00:00'
|
||||
})
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
render(Page, {});
|
||||
await expect.element(page.getByRole('button', { name: /Import starten/i })).toBeInTheDocument();
|
||||
|
||||
document.querySelector<HTMLButtonElement>('[data-import-trigger]')!.click();
|
||||
|
||||
await expect.element(page.getByText(/Import läuft/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows done status and retry button after successful import', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
state: 'DONE',
|
||||
message: 'Import abgeschlossen.',
|
||||
processed: 42,
|
||||
startedAt: '2026-01-01T10:00:00'
|
||||
})
|
||||
})
|
||||
);
|
||||
render(Page, {});
|
||||
await expect.element(page.getByText(/42 Dokumente/i)).toBeInTheDocument();
|
||||
await expect.element(page.getByRole('button', { name: /Erneut starten/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows failed status and retry button on error', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
state: 'FAILED',
|
||||
message: 'Datei nicht gefunden.',
|
||||
processed: 0,
|
||||
startedAt: '2026-01-01T10:00:00'
|
||||
})
|
||||
})
|
||||
);
|
||||
render(Page, {});
|
||||
await expect.element(page.getByText(/Datei nicht gefunden/i)).toBeInTheDocument();
|
||||
await expect.element(page.getByRole('button', { name: /Erneut starten/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── 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();
|
||||
});
|
||||
});
|
||||
8
frontend/src/routes/admin/tags/+layout.server.ts
Normal file
8
frontend/src/routes/admin/tags/+layout.server.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { createApiClient } from '$lib/api.server';
|
||||
import type { LayoutServerLoad } from './$types';
|
||||
|
||||
export const load: LayoutServerLoad = async ({ fetch }) => {
|
||||
const api = createApiClient(fetch);
|
||||
const result = await api.GET('/api/tags');
|
||||
return { tags: result.data ?? [] };
|
||||
};
|
||||
16
frontend/src/routes/admin/tags/+layout.svelte
Normal file
16
frontend/src/routes/admin/tags/+layout.svelte
Normal file
@@ -0,0 +1,16 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/state';
|
||||
import TagsListPanel from './TagsListPanel.svelte';
|
||||
|
||||
let { data, children } = $props();
|
||||
|
||||
const isAtListRoot = $derived(page.url.pathname === '/admin/tags');
|
||||
</script>
|
||||
|
||||
<div class="{isAtListRoot ? 'flex' : 'hidden'} flex-shrink-0 md:flex">
|
||||
<TagsListPanel tags={data.tags} />
|
||||
</div>
|
||||
|
||||
<div class="{isAtListRoot ? 'hidden' : 'flex'} min-w-0 flex-1 flex-col overflow-hidden md:flex">
|
||||
{@render children()}
|
||||
</div>
|
||||
7
frontend/src/routes/admin/tags/+page.svelte
Normal file
7
frontend/src/routes/admin/tags/+page.svelte
Normal file
@@ -0,0 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
</script>
|
||||
|
||||
<div class="flex flex-1 items-center justify-center p-8">
|
||||
<p class="text-sm text-ink-3">{m.admin_tags_select_prompt()}</p>
|
||||
</div>
|
||||
86
frontend/src/routes/admin/tags/TagsListPanel.svelte
Normal file
86
frontend/src/routes/admin/tags/TagsListPanel.svelte
Normal file
@@ -0,0 +1,86 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/state';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
type Tag = {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
let {
|
||||
tags,
|
||||
autocollapse = false
|
||||
}: {
|
||||
tags: Tag[];
|
||||
autocollapse?: boolean;
|
||||
} = $props();
|
||||
|
||||
let manualCollapse = $state(
|
||||
typeof localStorage !== 'undefined' &&
|
||||
localStorage.getItem('admin_tags_list_collapsed') === 'true'
|
||||
);
|
||||
const isCollapsed = $derived(autocollapse || manualCollapse);
|
||||
|
||||
$effect(() => {
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
localStorage.setItem('admin_tags_list_collapsed', String(manualCollapse));
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if isCollapsed}
|
||||
<!-- Collapsed handle: 32px -->
|
||||
<button
|
||||
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"
|
||||
>
|
||||
<span class="text-sm font-bold text-ink-2">›</span>
|
||||
<span
|
||||
class="text-[8px] font-extrabold tracking-widest text-ink-3 uppercase"
|
||||
style="writing-mode: vertical-rl; transform: rotate(180deg);"
|
||||
>
|
||||
{m.admin_tab_tags()}
|
||||
</span>
|
||||
</button>
|
||||
{:else}
|
||||
<div
|
||||
class="flex w-[200px] flex-shrink-0 flex-col overflow-hidden border-r border-line bg-surface"
|
||||
>
|
||||
<!-- Panel header -->
|
||||
<div class="flex items-center justify-between border-b border-line px-3 py-2">
|
||||
<span class="text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_tags_list_title()}
|
||||
</span>
|
||||
<button
|
||||
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"
|
||||
>
|
||||
‹
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Scrollable tag list -->
|
||||
<div class="flex-1 overflow-y-auto">
|
||||
{#if tags.length === 0}
|
||||
<p class="px-4 py-6 text-center text-xs text-ink-3">
|
||||
{m.admin_tags_empty()}
|
||||
</p>
|
||||
{:else}
|
||||
{#each tags as tag (tag.id)}
|
||||
{@const isActive = page.url.pathname.startsWith('/admin/tags/' + tag.id)}
|
||||
<a
|
||||
href="/admin/tags/{tag.id}"
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
class="block border-l-2 px-3 py-2.5 transition-colors {isActive
|
||||
? 'border-primary bg-primary/10 dark:bg-primary/15'
|
||||
: 'border-transparent hover:bg-muted'}"
|
||||
>
|
||||
<div class="text-sm font-bold text-ink">{tag.name}</div>
|
||||
</a>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
44
frontend/src/routes/admin/tags/[id]/+page.server.ts
Normal file
44
frontend/src/routes/admin/tags/[id]/+page.server.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { error, fail, redirect } from '@sveltejs/kit';
|
||||
import type { PageServerLoad, Actions } from './$types';
|
||||
import { createApiClient } from '$lib/api.server';
|
||||
import { getErrorMessage } from '$lib/errors';
|
||||
|
||||
export const load: PageServerLoad = async ({ params, parent }) => {
|
||||
const { tags } = await parent();
|
||||
const tag = tags.find((t: { id: string }) => t.id === params.id);
|
||||
if (!tag) throw error(404, getErrorMessage('TAG_NOT_FOUND'));
|
||||
return { tag };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
update: async ({ params, request, fetch }) => {
|
||||
const data = await request.formData();
|
||||
const api = createApiClient(fetch);
|
||||
|
||||
const result = await api.PUT('/api/tags/{id}', {
|
||||
params: { path: { id: params.id } },
|
||||
body: { name: data.get('name') as string }
|
||||
});
|
||||
|
||||
if (!result.response.ok) {
|
||||
const code = (result.error as unknown as { code?: string })?.code;
|
||||
return fail(result.response.status, { error: getErrorMessage(code) });
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
},
|
||||
|
||||
delete: async ({ params, fetch }) => {
|
||||
const api = createApiClient(fetch);
|
||||
const result = await api.DELETE('/api/tags/{id}', {
|
||||
params: { path: { id: params.id } }
|
||||
});
|
||||
|
||||
if (!result.response.ok) {
|
||||
const code = (result.error as unknown as { code?: string })?.code;
|
||||
return fail(result.response.status, { error: getErrorMessage(code) });
|
||||
}
|
||||
|
||||
throw redirect(303, '/admin/tags');
|
||||
}
|
||||
};
|
||||
159
frontend/src/routes/admin/tags/[id]/+page.svelte
Normal file
159
frontend/src/routes/admin/tags/[id]/+page.svelte
Normal file
@@ -0,0 +1,159 @@
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { beforeNavigate, goto } from '$app/navigation';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
let { data, form } = $props();
|
||||
|
||||
let deleteConfirmName = $state('');
|
||||
const deleteEnabled = $derived(deleteConfirmName === data.tag.name);
|
||||
|
||||
let isDirty = $state(false);
|
||||
let showUnsavedWarning = $state(false);
|
||||
let discardTarget: string | null = $state(null);
|
||||
|
||||
beforeNavigate(({ cancel, to }) => {
|
||||
if (isDirty) {
|
||||
cancel();
|
||||
showUnsavedWarning = true;
|
||||
discardTarget = to?.url.href ?? null;
|
||||
}
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (form?.success) {
|
||||
isDirty = false;
|
||||
showUnsavedWarning = false;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<!-- Scrollable body -->
|
||||
<div class="flex-1 overflow-y-auto px-5 py-5">
|
||||
{#if showUnsavedWarning}
|
||||
<div
|
||||
class="mb-5 flex items-center justify-between rounded border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-300"
|
||||
>
|
||||
<span>{m.admin_unsaved_warning()}</span>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => {
|
||||
isDirty = false;
|
||||
showUnsavedWarning = false;
|
||||
if (discardTarget) goto(discardTarget);
|
||||
}}
|
||||
class="ml-4 shrink-0 font-sans text-xs font-bold tracking-widest text-amber-800 uppercase hover:text-amber-900 dark:text-amber-300"
|
||||
>
|
||||
{m.person_discard_changes()}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
{#if form?.success}
|
||||
<div class="mb-5 rounded border border-green-200 bg-green-50 p-3 text-sm text-green-700">
|
||||
{m.admin_tag_updated()}
|
||||
</div>
|
||||
{/if}
|
||||
{#if form?.error}
|
||||
<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
|
||||
{form.error}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Rename form -->
|
||||
<form
|
||||
id="edit-tag-form"
|
||||
method="POST"
|
||||
action="?/update"
|
||||
use:enhance
|
||||
oninput={() => {
|
||||
isDirty = true;
|
||||
showUnsavedWarning = false;
|
||||
}}
|
||||
class="mb-5"
|
||||
>
|
||||
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
|
||||
<h3 class="mb-3 text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_col_name()}
|
||||
</h3>
|
||||
<p class="mb-3 text-xs text-amber-700">{m.admin_tags_warning()}</p>
|
||||
<input
|
||||
type="text"
|
||||
name="name"
|
||||
value={data.tag.name}
|
||||
required
|
||||
class="w-full rounded-sm border border-line bg-surface px-3 py-2 text-sm text-ink focus:ring-1 focus:ring-primary focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<!-- Danger zone -->
|
||||
<div
|
||||
class="rounded-sm border border-red-200 bg-red-50 p-5 dark:border-red-900 dark:bg-red-950/30"
|
||||
>
|
||||
<h3 class="mb-3 text-xs font-bold tracking-widest text-red-700 uppercase dark:text-red-400">
|
||||
{m.btn_delete()}
|
||||
</h3>
|
||||
<p class="mb-3 text-xs text-red-700 dark:text-red-400">
|
||||
{m.admin_tag_delete_confirm()}
|
||||
</p>
|
||||
<p class="mb-2 text-xs font-bold text-ink-2">
|
||||
Gib <span class="font-mono">{data.tag.name}</span> zur Bestätigung ein:
|
||||
</p>
|
||||
<input
|
||||
type="text"
|
||||
bind:value={deleteConfirmName}
|
||||
placeholder={data.tag.name}
|
||||
class="mb-3 w-full rounded-sm border border-red-200 bg-white px-3 py-2 text-sm text-ink focus:ring-1 focus:ring-red-400 focus:outline-none"
|
||||
/>
|
||||
<form method="POST" action="?/delete" use:enhance>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!deleteEnabled}
|
||||
class="rounded-sm bg-red-600 px-4 py-2 font-sans text-xs font-bold tracking-widest text-white uppercase transition-opacity hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
{m.btn_delete()}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Docked footer -->
|
||||
<div class="flex items-center justify-between border-t border-line bg-surface px-5 py-3">
|
||||
<a
|
||||
href="/admin/tags"
|
||||
class="font-sans text-xs font-bold tracking-widest text-ink-2 uppercase hover:text-ink"
|
||||
>
|
||||
{m.btn_cancel()}
|
||||
</a>
|
||||
<button
|
||||
type="submit"
|
||||
form="edit-tag-form"
|
||||
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
>
|
||||
{m.btn_save()}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
85
frontend/src/routes/admin/tags/[id]/page.server.spec.ts
Normal file
85
frontend/src/routes/admin/tags/[id]/page.server.spec.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
93
frontend/src/routes/admin/tags/[id]/page.svelte.spec.ts
Normal file
93
frontend/src/routes/admin/tags/[id]/page.svelte.spec.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { cleanup, render } from 'vitest-browser-svelte';
|
||||
import { page } from 'vitest/browser';
|
||||
import Page from './+page.svelte';
|
||||
|
||||
vi.mock('$app/forms', () => ({ enhance: () => () => {} }));
|
||||
vi.mock('$app/navigation', () => ({ beforeNavigate: vi.fn(), goto: vi.fn() }));
|
||||
|
||||
import { beforeNavigate, goto } from '$app/navigation';
|
||||
|
||||
const baseTag = { id: 't1', name: 'Familie' };
|
||||
const baseData = { tag: baseTag };
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
// ─── Rendering ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('Admin edit tag page – rendering', () => {
|
||||
it('renders the heading with tag name', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
await expect.element(page.getByText(/Schlagwort: Familie/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('pre-fills the name input', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const input = document.querySelector<HTMLInputElement>('input[name="name"]');
|
||||
expect(input?.value).toBe('Familie');
|
||||
});
|
||||
|
||||
it('renders the cancel link pointing to /admin/tags', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /Abbrechen/i }))
|
||||
.toHaveAttribute('href', '/admin/tags');
|
||||
});
|
||||
|
||||
it('delete button is disabled until tag name is typed in confirm field', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const deleteBtn = document.querySelector<HTMLButtonElement>('button[type="submit"]');
|
||||
expect(deleteBtn?.disabled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Unsaved-changes guard ────────────────────────────────────────────────────
|
||||
|
||||
describe('Admin edit tag page – unsaved-changes guard', () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it('does not show unsaved warning initially', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('cancels navigation and shows warning when rename form is dirty', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="name"]')!
|
||||
.dispatchEvent(new InputEvent('input', { bubbles: true }));
|
||||
|
||||
const cancel = vi.fn();
|
||||
callback({ cancel, to: { url: new URL('http://localhost/admin/tags/t2') } });
|
||||
|
||||
expect(cancel).toHaveBeenCalled();
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not cancel navigation when form is clean', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
const cancel = vi.fn();
|
||||
callback({ cancel, to: { url: new URL('http://localhost/admin/tags/t2') } });
|
||||
|
||||
expect(cancel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('discard button calls goto with the target URL', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="name"]')!
|
||||
.dispatchEvent(new InputEvent('input', { bubbles: true }));
|
||||
|
||||
callback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/tags/t2') } });
|
||||
|
||||
await page.getByRole('button', { name: /verwerfen/i }).click();
|
||||
|
||||
expect(vi.mocked(goto)).toHaveBeenCalledWith('http://localhost/admin/tags/t2');
|
||||
});
|
||||
});
|
||||
41
frontend/src/routes/admin/tags/layout.server.spec.ts
Normal file
41
frontend/src/routes/admin/tags/layout.server.spec.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { load } from './+layout.server';
|
||||
|
||||
vi.mock('$lib/api.server', () => ({ createApiClient: vi.fn() }));
|
||||
|
||||
import { createApiClient } from '$lib/api.server';
|
||||
|
||||
function mockApi(tags: unknown[]) {
|
||||
vi.mocked(createApiClient).mockReturnValue({
|
||||
GET: vi.fn().mockResolvedValueOnce({ response: { ok: true }, data: tags })
|
||||
} as ReturnType<typeof createApiClient>);
|
||||
}
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('admin/tags layout load', () => {
|
||||
it('returns the tags list', async () => {
|
||||
mockApi([
|
||||
{ id: 't1', name: 'Familie' },
|
||||
{ id: 't2', name: 'Urlaub' }
|
||||
]);
|
||||
const result = await load({ fetch: vi.fn() as unknown as typeof fetch });
|
||||
expect(result.tags).toHaveLength(2);
|
||||
expect(result.tags[0].name).toBe('Familie');
|
||||
});
|
||||
|
||||
it('returns an empty array when the API returns nothing', async () => {
|
||||
mockApi([]);
|
||||
const result = await load({ fetch: vi.fn() as unknown as typeof fetch });
|
||||
expect(result.tags).toEqual([]);
|
||||
});
|
||||
|
||||
it('calls GET /api/tags', async () => {
|
||||
const mockGet = vi.fn().mockResolvedValue({ response: { ok: true }, data: [] });
|
||||
vi.mocked(createApiClient).mockReturnValue({ GET: mockGet } as ReturnType<
|
||||
typeof createApiClient
|
||||
>);
|
||||
await load({ fetch: vi.fn() as unknown as typeof fetch });
|
||||
expect(mockGet).toHaveBeenCalledWith('/api/tags');
|
||||
});
|
||||
});
|
||||
97
frontend/src/routes/admin/tags/layout.svelte.spec.ts
Normal file
97
frontend/src/routes/admin/tags/layout.svelte.spec.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest';
|
||||
import { cleanup, render } from 'vitest-browser-svelte';
|
||||
import { page } from 'vitest/browser';
|
||||
import TagsListPanel from './TagsListPanel.svelte';
|
||||
|
||||
vi.mock('$app/state', () => ({
|
||||
page: { url: { pathname: '/admin/tags/t1' } }
|
||||
}));
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const tags = [
|
||||
{ id: 't1', name: 'Familie' },
|
||||
{ id: 't2', name: 'Urlaub' },
|
||||
{ id: 't3', name: 'Schule' }
|
||||
];
|
||||
|
||||
describe('TagsListPanel — header', () => {
|
||||
it('renders the panel title', async () => {
|
||||
render(TagsListPanel, { tags });
|
||||
await expect.element(page.getByText(/Alle Schlagworte/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TagsListPanel — tag items', () => {
|
||||
it('renders each tag name', async () => {
|
||||
render(TagsListPanel, { tags });
|
||||
await expect.element(page.getByRole('link', { name: /familie/i })).toBeInTheDocument();
|
||||
await expect.element(page.getByRole('link', { name: /urlaub/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('each tag links to /admin/tags/[id]', async () => {
|
||||
const { container } = render(TagsListPanel, { tags });
|
||||
const links = container.querySelectorAll<HTMLAnchorElement>('a[href^="/admin/tags/t"]');
|
||||
expect(links.length).toBe(3);
|
||||
expect(links[0].getAttribute('href')).toBe('/admin/tags/t1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('TagsListPanel — active state', () => {
|
||||
it('marks the active tag link with aria-current=page', async () => {
|
||||
render(TagsListPanel, { tags });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /familie/i }))
|
||||
.toHaveAttribute('aria-current', 'page');
|
||||
});
|
||||
|
||||
it('does not mark inactive tag links with aria-current', async () => {
|
||||
render(TagsListPanel, { tags });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /urlaub/i }))
|
||||
.not.toHaveAttribute('aria-current');
|
||||
});
|
||||
});
|
||||
|
||||
describe('TagsListPanel — empty state', () => {
|
||||
it('shows empty state when tags array is empty', async () => {
|
||||
render(TagsListPanel, { tags: [] });
|
||||
await expect.element(page.getByText(/keine schlagworte/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Collapse toggle ──────────────────────────────────────────────────────────
|
||||
|
||||
describe('TagsListPanel — collapse toggle', () => {
|
||||
beforeEach(() => localStorage.removeItem('admin_tags_list_collapsed'));
|
||||
|
||||
it('renders a collapse button with aria-label', async () => {
|
||||
render(TagsListPanel, { tags });
|
||||
await expect
|
||||
.element(page.getByRole('button', { name: /Liste einklappen/i }))
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clicking collapse shows the expand handle', async () => {
|
||||
render(TagsListPanel, { tags });
|
||||
await page.getByRole('button', { name: /Liste einklappen/i }).click();
|
||||
await expect
|
||||
.element(page.getByRole('button', { name: /Liste ausklappen/i }))
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('autocollapse prop starts the panel in collapsed state', async () => {
|
||||
render(TagsListPanel, { tags, autocollapse: true });
|
||||
await expect
|
||||
.element(page.getByRole('button', { name: /Liste ausklappen/i }))
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
8
frontend/src/routes/admin/users/+layout.server.ts
Normal file
8
frontend/src/routes/admin/users/+layout.server.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { createApiClient } from '$lib/api.server';
|
||||
import type { LayoutServerLoad } from './$types';
|
||||
|
||||
export const load: LayoutServerLoad = async ({ fetch }) => {
|
||||
const api = createApiClient(fetch);
|
||||
const result = await api.GET('/api/users');
|
||||
return { users: result.data ?? [] };
|
||||
};
|
||||
22
frontend/src/routes/admin/users/+layout.svelte
Normal file
22
frontend/src/routes/admin/users/+layout.svelte
Normal file
@@ -0,0 +1,22 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/state';
|
||||
import UsersListPanel from './UsersListPanel.svelte';
|
||||
|
||||
let { data, children } = $props();
|
||||
|
||||
// Auto-collapse list when user opens the create form (gives max form space on tablet)
|
||||
const autoCollapse = $derived(page.url.pathname === '/admin/users/new');
|
||||
|
||||
// Mobile: show only the relevant panel at a time
|
||||
const isAtListRoot = $derived(page.url.pathname === '/admin/users');
|
||||
</script>
|
||||
|
||||
<!-- List panel: full-screen on mobile at list root; always visible at md+ -->
|
||||
<div class="{isAtListRoot ? 'flex' : 'hidden'} flex-shrink-0 md:flex">
|
||||
<UsersListPanel users={data.users} autocollapse={autoCollapse} />
|
||||
</div>
|
||||
|
||||
<!-- Detail panel: full-screen on mobile when not at list root; always visible at md+ -->
|
||||
<div class="{isAtListRoot ? 'hidden' : 'flex'} min-w-0 flex-1 flex-col overflow-hidden md:flex">
|
||||
{@render children()}
|
||||
</div>
|
||||
7
frontend/src/routes/admin/users/+page.svelte
Normal file
7
frontend/src/routes/admin/users/+page.svelte
Normal file
@@ -0,0 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
</script>
|
||||
|
||||
<div class="flex flex-1 items-center justify-center p-8">
|
||||
<p class="text-sm text-ink-3">{m.admin_users_select_prompt()}</p>
|
||||
</div>
|
||||
149
frontend/src/routes/admin/users/UsersListPanel.svelte
Normal file
149
frontend/src/routes/admin/users/UsersListPanel.svelte
Normal file
@@ -0,0 +1,149 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/state';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
type Group = {
|
||||
id: string;
|
||||
name: string;
|
||||
permissions: string[];
|
||||
};
|
||||
|
||||
type User = {
|
||||
id: string;
|
||||
username: string;
|
||||
firstName: string | null;
|
||||
lastName: string | null;
|
||||
groups: Group[];
|
||||
};
|
||||
|
||||
let {
|
||||
users,
|
||||
autocollapse = false
|
||||
}: {
|
||||
users: User[];
|
||||
autocollapse?: boolean;
|
||||
} = $props();
|
||||
|
||||
let searchQuery = $state('');
|
||||
let manualCollapse = $state(
|
||||
typeof localStorage !== 'undefined' &&
|
||||
localStorage.getItem('admin_users_list_collapsed') === 'true'
|
||||
);
|
||||
const isCollapsed = $derived(autocollapse || manualCollapse);
|
||||
|
||||
$effect(() => {
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
localStorage.setItem('admin_users_list_collapsed', String(manualCollapse));
|
||||
}
|
||||
});
|
||||
|
||||
const filtered = $derived(
|
||||
searchQuery.trim() === ''
|
||||
? users
|
||||
: users.filter((u) =>
|
||||
[u.username, u.firstName, u.lastName]
|
||||
.filter(Boolean)
|
||||
.some((v) => v!.toLowerCase().includes(searchQuery.toLowerCase()))
|
||||
)
|
||||
);
|
||||
</script>
|
||||
|
||||
{#if isCollapsed}
|
||||
<!-- Collapsed handle: 32px -->
|
||||
<button
|
||||
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"
|
||||
>
|
||||
<span class="text-sm font-bold text-ink-2">›</span>
|
||||
<span
|
||||
class="text-[8px] font-extrabold tracking-widest text-ink-3 uppercase"
|
||||
style="writing-mode: vertical-rl; transform: rotate(180deg);"
|
||||
>
|
||||
{m.admin_tab_users()}
|
||||
</span>
|
||||
</button>
|
||||
{:else}
|
||||
<div
|
||||
class="flex w-[200px] flex-shrink-0 flex-col overflow-hidden border-r border-line bg-surface"
|
||||
>
|
||||
<!-- Panel header -->
|
||||
<div class="flex items-center justify-between border-b border-line px-3 py-2">
|
||||
<span class="text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_users_list_title()}
|
||||
</span>
|
||||
<div class="flex items-center gap-1">
|
||||
<a
|
||||
href="/admin/users/new"
|
||||
class="inline-flex items-center gap-1 rounded-sm px-2 py-1 text-xs font-medium text-ink-2 transition-colors hover:bg-muted hover:text-ink"
|
||||
title={m.admin_btn_new_user()}
|
||||
aria-label={m.admin_btn_new_user()}
|
||||
>
|
||||
<svg
|
||||
class="h-3.5 w-3.5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="2.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
</a>
|
||||
<button
|
||||
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"
|
||||
>
|
||||
‹
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Search -->
|
||||
<div class="border-b border-line px-3 py-2">
|
||||
<input
|
||||
type="search"
|
||||
bind:value={searchQuery}
|
||||
placeholder={m.admin_users_search_placeholder()}
|
||||
class="w-full rounded-sm border border-line bg-surface px-2 py-1.5 text-sm text-ink placeholder:text-ink-3 focus:ring-1 focus:ring-primary focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Scrollable user list -->
|
||||
<div class="flex-1 overflow-y-auto">
|
||||
{#if filtered.length === 0}
|
||||
<p class="px-4 py-6 text-center text-xs text-ink-3">
|
||||
{m.admin_users_empty()}
|
||||
</p>
|
||||
{:else}
|
||||
{#each filtered as user (user.id)}
|
||||
{@const isActive = page.url.pathname.startsWith('/admin/users/' + user.id)}
|
||||
{@const fullName =
|
||||
[user.firstName, user.lastName].filter(Boolean).join(' ') || null}
|
||||
<a
|
||||
href="/admin/users/{user.id}"
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
class="block border-l-2 px-3 py-2.5 transition-colors {isActive
|
||||
? 'border-primary bg-primary/10 dark:bg-primary/15'
|
||||
: 'border-transparent hover:bg-muted'}"
|
||||
>
|
||||
<div class="text-sm font-bold text-ink">{user.username}</div>
|
||||
{#if fullName}
|
||||
<div class="mt-0.5 text-xs text-ink-3">{fullName}</div>
|
||||
{/if}
|
||||
{#if user.groups.length > 0}
|
||||
<div class="mt-1 flex flex-wrap gap-1">
|
||||
{#each user.groups as group (group.id)}
|
||||
<span class="rounded-sm bg-muted px-1.5 py-0.5 text-[10px] text-ink-3">
|
||||
{group.name}
|
||||
</span>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</a>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { error, fail } from '@sveltejs/kit';
|
||||
import { error, fail, redirect } from '@sveltejs/kit';
|
||||
import type { PageServerLoad, Actions } from './$types';
|
||||
import { createApiClient } from '$lib/api.server';
|
||||
import { getErrorMessage } from '$lib/errors';
|
||||
@@ -63,5 +63,19 @@ export const actions: Actions = {
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
},
|
||||
|
||||
delete: async ({ params, fetch }) => {
|
||||
const api = createApiClient(fetch);
|
||||
const result = await api.DELETE('/api/users/{id}', {
|
||||
params: { path: { id: params.id } }
|
||||
});
|
||||
|
||||
if (!result.response.ok) {
|
||||
const code = (result.error as unknown as { code?: string })?.code;
|
||||
return fail(result.response.status, { error: getErrorMessage(code) });
|
||||
}
|
||||
|
||||
throw redirect(303, '/admin/users');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { beforeNavigate, goto } from '$app/navigation';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
import UserProfileSection from '$lib/components/user/UserProfileSection.svelte';
|
||||
import UserGroupsSection from '$lib/components/user/UserGroupsSection.svelte';
|
||||
@@ -8,87 +9,156 @@ import UserPasswordSection from '$lib/components/user/UserPasswordSection.svelte
|
||||
let { data, form } = $props();
|
||||
|
||||
const selectedGroupIds = $derived(data.editUser.groups?.map((g: { id: string }) => g.id) ?? []);
|
||||
|
||||
let isDirty = $state(false);
|
||||
let showUnsavedWarning = $state(false);
|
||||
let discardTarget: string | null = $state(null);
|
||||
|
||||
beforeNavigate(({ cancel, to }) => {
|
||||
if (isDirty) {
|
||||
cancel();
|
||||
showUnsavedWarning = true;
|
||||
discardTarget = to?.url.href ?? null;
|
||||
}
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (form?.success) {
|
||||
isDirty = false;
|
||||
showUnsavedWarning = false;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="mx-auto max-w-3xl px-4 py-8 sm:px-6 lg:px-8">
|
||||
<a
|
||||
href="/admin"
|
||||
class="group mb-4 inline-flex items-center text-xs font-bold tracking-widest text-ink-2 uppercase transition-colors hover:text-ink"
|
||||
>
|
||||
<svg
|
||||
class="mr-2 h-4 w-4 transform transition-transform group-hover:-translate-x-1"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
<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"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
|
||||
</svg>
|
||||
{m.btn_back_to_overview()}
|
||||
</a>
|
||||
|
||||
<h1 class="mb-6 font-serif text-3xl font-bold text-ink">
|
||||
{m.admin_user_edit_heading({ username: data.editUser.username })}
|
||||
</h1>
|
||||
|
||||
{#if form?.success}
|
||||
<div class="mb-5 rounded border border-green-200 bg-green-50 p-3 text-sm text-green-700">
|
||||
{m.admin_user_updated()}
|
||||
</div>
|
||||
{/if}
|
||||
{#if form?.error}
|
||||
<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
|
||||
{form.error}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<form method="POST" use:enhance class="space-y-6">
|
||||
<!-- Profile card -->
|
||||
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
|
||||
<h2 class="mb-5 text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.profile_section_personal()}
|
||||
</h2>
|
||||
<UserProfileSection
|
||||
firstName={data.editUser.firstName ?? ''}
|
||||
lastName={data.editUser.lastName ?? ''}
|
||||
birthDate={data.editUser.birthDate ?? ''}
|
||||
email={data.editUser.email ?? ''}
|
||||
contact={data.editUser.contact ?? ''}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Groups card -->
|
||||
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
|
||||
<h2 class="mb-5 text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_col_groups()}
|
||||
</h2>
|
||||
<UserGroupsSection groups={data.groups} selectedGroupIds={selectedGroupIds} />
|
||||
</div>
|
||||
|
||||
<!-- Password card -->
|
||||
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
|
||||
<h2 class="mb-5 text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_label_new_password_optional()}
|
||||
</h2>
|
||||
<UserPasswordSection />
|
||||
</div>
|
||||
|
||||
<!-- Save bar -->
|
||||
<div
|
||||
class="sticky bottom-0 z-10 -mx-4 flex items-center justify-between border-t border-line bg-surface px-6 py-4 shadow-[0_-2px_8px_rgba(0,0,0,0.06)]"
|
||||
>
|
||||
<a
|
||||
href="/admin"
|
||||
class="font-sans text-xs font-bold tracking-widest text-ink-2 uppercase hover:text-ink"
|
||||
<svg
|
||||
class="h-4 w-4"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{m.btn_cancel()}
|
||||
</a>
|
||||
<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>
|
||||
<form
|
||||
method="POST"
|
||||
action="?/delete"
|
||||
use:enhance={({ cancel }) => {
|
||||
if (!confirm(m.admin_user_delete_confirm({ username: data.editUser.username }))) {
|
||||
cancel();
|
||||
}
|
||||
return async ({ update }) => {
|
||||
await update();
|
||||
};
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="submit"
|
||||
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
class="rounded-sm border border-red-200 bg-red-50 px-3 py-1 font-sans text-xs font-bold tracking-widest text-red-700 uppercase transition-colors hover:bg-red-100 dark:border-red-900 dark:bg-red-950/30 dark:text-red-400"
|
||||
>
|
||||
{m.btn_save()}
|
||||
{m.btn_delete()}…
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Scrollable body -->
|
||||
<div class="flex-1 overflow-y-auto px-5 py-5">
|
||||
{#if showUnsavedWarning}
|
||||
<div
|
||||
class="mb-5 flex items-center justify-between rounded border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-300"
|
||||
>
|
||||
<span>{m.admin_unsaved_warning()}</span>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => {
|
||||
isDirty = false;
|
||||
showUnsavedWarning = false;
|
||||
if (discardTarget) goto(discardTarget);
|
||||
}}
|
||||
class="ml-4 shrink-0 font-sans text-xs font-bold tracking-widest text-amber-800 uppercase hover:text-amber-900 dark:text-amber-300"
|
||||
>
|
||||
{m.person_discard_changes()}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
{#if form?.success}
|
||||
<div class="mb-5 rounded border border-green-200 bg-green-50 p-3 text-sm text-green-700">
|
||||
{m.admin_user_updated()}
|
||||
</div>
|
||||
{/if}
|
||||
{#if form?.error}
|
||||
<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
|
||||
{form.error}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<form
|
||||
id="edit-user-form"
|
||||
method="POST"
|
||||
use:enhance
|
||||
oninput={() => {
|
||||
isDirty = true;
|
||||
showUnsavedWarning = false;
|
||||
}}
|
||||
class="space-y-5"
|
||||
>
|
||||
<!-- Profile card -->
|
||||
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
|
||||
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.profile_section_personal()}
|
||||
</h3>
|
||||
<UserProfileSection
|
||||
firstName={data.editUser.firstName ?? ''}
|
||||
lastName={data.editUser.lastName ?? ''}
|
||||
birthDate={data.editUser.birthDate ?? ''}
|
||||
email={data.editUser.email ?? ''}
|
||||
contact={data.editUser.contact ?? ''}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Groups card -->
|
||||
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
|
||||
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_col_groups()}
|
||||
</h3>
|
||||
<UserGroupsSection groups={data.groups} selectedGroupIds={selectedGroupIds} />
|
||||
</div>
|
||||
|
||||
<!-- Password card -->
|
||||
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
|
||||
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_label_new_password_optional()}
|
||||
</h3>
|
||||
<UserPasswordSection />
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Docked footer -->
|
||||
<div class="flex items-center justify-between border-t border-line bg-surface px-5 py-3">
|
||||
<a
|
||||
href="/admin/users"
|
||||
class="font-sans text-xs font-bold tracking-widest text-ink-2 uppercase hover:text-ink"
|
||||
>
|
||||
{m.btn_cancel()}
|
||||
</a>
|
||||
<button
|
||||
type="submit"
|
||||
form="edit-user-form"
|
||||
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
>
|
||||
{m.btn_save()}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { cleanup, render } from 'vitest-browser-svelte';
|
||||
import { page } from 'vitest/browser';
|
||||
import Page from './+page.svelte';
|
||||
|
||||
vi.mock('$app/forms', () => ({ enhance: () => () => {} }));
|
||||
vi.mock('$app/navigation', () => ({ beforeNavigate: vi.fn(), goto: vi.fn() }));
|
||||
|
||||
import { beforeNavigate, goto } from '$app/navigation';
|
||||
|
||||
const groups = [
|
||||
{ id: 'g1', name: 'Editoren', permissions: ['WRITE_ALL'] },
|
||||
@@ -96,7 +99,7 @@ describe('Admin edit user page – rendering', () => {
|
||||
|
||||
it('includes pre-selected group ids in FormData at submit time (guards against groupIds being empty)', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const form = document.querySelector('form')!;
|
||||
const form = document.querySelector<HTMLFormElement>('form#edit-user-form')!;
|
||||
const formData = new FormData(form);
|
||||
expect(formData.getAll('groupIds')).toContain('g1');
|
||||
expect(formData.getAll('groupIds')).not.toContain('g2');
|
||||
@@ -110,11 +113,11 @@ describe('Admin edit user page – rendering', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('cancel link points to /admin', async () => {
|
||||
it('cancel link points to /admin/users', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /Abbrechen/i }))
|
||||
.toHaveAttribute('href', '/admin');
|
||||
.toHaveAttribute('href', '/admin/users');
|
||||
});
|
||||
|
||||
it('renders the save button', async () => {
|
||||
@@ -141,3 +144,72 @@ describe('Admin edit user page – feedback', () => {
|
||||
await expect.element(page.getByText(/Änderungen gespeichert/i)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Unsaved-changes guard ────────────────────────────────────────────────────
|
||||
|
||||
describe('Admin edit user page – unsaved-changes guard', () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it('does not show unsaved warning initially', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('cancels navigation and shows warning when form is dirty', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="firstName"]')!
|
||||
.dispatchEvent(new InputEvent('input', { bubbles: true }));
|
||||
|
||||
const cancel = vi.fn();
|
||||
callback({ cancel, to: { url: new URL('http://localhost/admin/users/u2') } });
|
||||
|
||||
expect(cancel).toHaveBeenCalled();
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not cancel navigation when form is clean', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
const cancel = vi.fn();
|
||||
callback({ cancel, to: { url: new URL('http://localhost/admin/users/u2') } });
|
||||
|
||||
expect(cancel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('discard button calls goto with the target URL', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="firstName"]')!
|
||||
.dispatchEvent(new InputEvent('input', { bubbles: true }));
|
||||
|
||||
callback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/users/u2') } });
|
||||
|
||||
await page.getByRole('button', { name: /verwerfen/i }).click();
|
||||
|
||||
expect(vi.mocked(goto)).toHaveBeenCalledWith('http://localhost/admin/users/u2');
|
||||
});
|
||||
|
||||
it('clears dirty state when form saves successfully', async () => {
|
||||
const { rerender } = render(Page, { data: baseData, form: null });
|
||||
const [callback] = vi.mocked(beforeNavigate).mock.calls[0];
|
||||
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="firstName"]')!
|
||||
.dispatchEvent(new InputEvent('input', { bubbles: true }));
|
||||
|
||||
callback({ cancel: vi.fn(), to: { url: new URL('http://localhost/admin/users/u2') } });
|
||||
await expect.element(page.getByText(/ungespeicherte Änderungen/i)).toBeInTheDocument();
|
||||
|
||||
await rerender({ data: baseData, form: { success: true } });
|
||||
|
||||
const cancel = vi.fn();
|
||||
callback({ cancel, to: { url: new URL('http://localhost/admin/users/u2') } });
|
||||
expect(cancel).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
41
frontend/src/routes/admin/users/layout.server.spec.ts
Normal file
41
frontend/src/routes/admin/users/layout.server.spec.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { load } from './+layout.server';
|
||||
|
||||
vi.mock('$lib/api.server', () => ({ createApiClient: vi.fn() }));
|
||||
|
||||
import { createApiClient } from '$lib/api.server';
|
||||
|
||||
function mockApi(users: unknown[]) {
|
||||
vi.mocked(createApiClient).mockReturnValue({
|
||||
GET: vi.fn().mockResolvedValueOnce({ response: { ok: true }, data: users })
|
||||
} as ReturnType<typeof createApiClient>);
|
||||
}
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('admin/users layout load', () => {
|
||||
it('returns the users list', async () => {
|
||||
mockApi([
|
||||
{ id: 'u1', username: 'alice' },
|
||||
{ id: 'u2', username: 'bob' }
|
||||
]);
|
||||
const result = await load({ fetch: vi.fn() as unknown as typeof fetch });
|
||||
expect(result.users).toHaveLength(2);
|
||||
expect(result.users[0].username).toBe('alice');
|
||||
});
|
||||
|
||||
it('returns an empty array when the API returns nothing', async () => {
|
||||
mockApi([]);
|
||||
const result = await load({ fetch: vi.fn() as unknown as typeof fetch });
|
||||
expect(result.users).toEqual([]);
|
||||
});
|
||||
|
||||
it('calls GET /api/users', async () => {
|
||||
const mockGet = vi.fn().mockResolvedValue({ response: { ok: true }, data: [] });
|
||||
vi.mocked(createApiClient).mockReturnValue({ GET: mockGet } as ReturnType<
|
||||
typeof createApiClient
|
||||
>);
|
||||
await load({ fetch: vi.fn() as unknown as typeof fetch });
|
||||
expect(mockGet).toHaveBeenCalledWith('/api/users');
|
||||
});
|
||||
});
|
||||
140
frontend/src/routes/admin/users/layout.svelte.spec.ts
Normal file
140
frontend/src/routes/admin/users/layout.svelte.spec.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest';
|
||||
import { cleanup, render } from 'vitest-browser-svelte';
|
||||
import { page } from 'vitest/browser';
|
||||
import UsersListPanel from './UsersListPanel.svelte';
|
||||
|
||||
vi.mock('$app/state', () => ({
|
||||
page: { url: { pathname: '/admin/users/u1' } }
|
||||
}));
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const users = [
|
||||
{
|
||||
id: 'u1',
|
||||
username: 'reader',
|
||||
firstName: 'Lea',
|
||||
lastName: 'Leserin',
|
||||
groups: [{ id: 'g1', name: 'Leser', permissions: ['READ_ALL'] }]
|
||||
},
|
||||
{
|
||||
id: 'u2',
|
||||
username: 'admin',
|
||||
firstName: null,
|
||||
lastName: null,
|
||||
groups: [{ id: 'g2', name: 'Admins', permissions: ['ADMIN'] }]
|
||||
}
|
||||
];
|
||||
|
||||
describe('UsersListPanel — header', () => {
|
||||
it('renders the panel title', async () => {
|
||||
render(UsersListPanel, { users });
|
||||
await expect.element(page.getByText(/Alle Benutzer/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders a new-user link pointing to /admin/users/new', async () => {
|
||||
render(UsersListPanel, { users });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /neuer benutzer/i }))
|
||||
.toHaveAttribute('href', '/admin/users/new');
|
||||
});
|
||||
|
||||
it('renders a search input', async () => {
|
||||
render(UsersListPanel, { users });
|
||||
await expect.element(page.getByRole('searchbox')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('UsersListPanel — user items', () => {
|
||||
it('renders each username', async () => {
|
||||
render(UsersListPanel, { users });
|
||||
await expect.element(page.getByRole('link', { name: /reader/i })).toBeInTheDocument();
|
||||
await expect.element(page.getByRole('link', { name: /admin/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('each user links to /admin/users/[id]', async () => {
|
||||
const { container } = render(UsersListPanel, { users });
|
||||
const links = container.querySelectorAll<HTMLAnchorElement>('a[href^="/admin/users/u"]');
|
||||
expect(links.length).toBe(2);
|
||||
expect(links[0].getAttribute('href')).toBe('/admin/users/u1');
|
||||
expect(links[1].getAttribute('href')).toBe('/admin/users/u2');
|
||||
});
|
||||
|
||||
it('shows full name as subtitle when available', async () => {
|
||||
render(UsersListPanel, { users });
|
||||
await expect.element(page.getByText('Lea Leserin')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows group name chip', async () => {
|
||||
render(UsersListPanel, { users });
|
||||
await expect.element(page.getByText('Leser', { exact: true })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('UsersListPanel — active state', () => {
|
||||
it('marks the active user link with aria-current=page', async () => {
|
||||
render(UsersListPanel, { users });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /reader/i }))
|
||||
.toHaveAttribute('aria-current', 'page');
|
||||
});
|
||||
|
||||
it('does not mark the inactive user link with aria-current', async () => {
|
||||
render(UsersListPanel, { users });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /admin/i }))
|
||||
.not.toHaveAttribute('aria-current');
|
||||
});
|
||||
});
|
||||
|
||||
describe('UsersListPanel — empty state', () => {
|
||||
it('shows empty state message when users array is empty', async () => {
|
||||
render(UsersListPanel, { users: [] });
|
||||
await expect.element(page.getByText(/keine benutzer/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Collapse toggle ──────────────────────────────────────────────────────────
|
||||
|
||||
describe('UsersListPanel — collapse toggle', () => {
|
||||
beforeEach(() => localStorage.removeItem('admin_users_list_collapsed'));
|
||||
|
||||
it('renders a collapse button with aria-label', async () => {
|
||||
render(UsersListPanel, { users });
|
||||
await expect
|
||||
.element(page.getByRole('button', { name: /Liste einklappen/i }))
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clicking collapse shows the expand handle', async () => {
|
||||
render(UsersListPanel, { users });
|
||||
await page.getByRole('button', { name: /Liste einklappen/i }).click();
|
||||
await expect
|
||||
.element(page.getByRole('button', { name: /Liste ausklappen/i }))
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clicking expand handle restores the full panel', async () => {
|
||||
render(UsersListPanel, { users });
|
||||
await page.getByRole('button', { name: /Liste einklappen/i }).click();
|
||||
await page.getByRole('button', { name: /Liste ausklappen/i }).click();
|
||||
await expect
|
||||
.element(page.getByRole('button', { name: /Liste einklappen/i }))
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('autocollapse prop starts the panel in collapsed state', async () => {
|
||||
render(UsersListPanel, { users, autocollapse: true });
|
||||
await expect
|
||||
.element(page.getByRole('button', { name: /Liste ausklappen/i }))
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -40,6 +40,6 @@ export const actions: Actions = {
|
||||
return fail(result.response.status, { error: getErrorMessage(code) });
|
||||
}
|
||||
|
||||
throw redirect(303, '/admin');
|
||||
throw redirect(303, '/admin/users');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,71 +1,119 @@
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { beforeNavigate, goto } from '$app/navigation';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
import UserProfileSection from '$lib/components/user/UserProfileSection.svelte';
|
||||
import UserGroupsSection from '$lib/components/user/UserGroupsSection.svelte';
|
||||
import AccountSection from './AccountSection.svelte';
|
||||
|
||||
let { data, form } = $props();
|
||||
|
||||
let isDirty = $state(false);
|
||||
let showUnsavedWarning = $state(false);
|
||||
let discardTarget: string | null = $state(null);
|
||||
|
||||
beforeNavigate(({ cancel, to }) => {
|
||||
if (isDirty) {
|
||||
cancel();
|
||||
showUnsavedWarning = true;
|
||||
discardTarget = to?.url.href ?? null;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="mx-auto max-w-3xl px-4 py-8 sm:px-6 lg:px-8">
|
||||
<a
|
||||
href="/admin"
|
||||
class="group mb-4 inline-flex items-center text-xs font-bold tracking-widest text-ink-2 uppercase transition-colors hover:text-ink"
|
||||
>
|
||||
<svg
|
||||
class="mr-2 h-4 w-4 transform transition-transform group-hover:-translate-x-1"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
<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"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
|
||||
</svg>
|
||||
{m.btn_back_to_overview()}
|
||||
</a>
|
||||
<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>
|
||||
|
||||
<h1 class="mb-6 font-serif text-3xl font-bold text-ink">{m.admin_user_new_heading()}</h1>
|
||||
<!-- Scrollable body -->
|
||||
<div class="flex-1 overflow-y-auto px-5 py-5">
|
||||
{#if showUnsavedWarning}
|
||||
<div
|
||||
class="mb-5 flex items-center justify-between rounded border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-300"
|
||||
>
|
||||
<span>{m.admin_unsaved_warning()}</span>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => {
|
||||
isDirty = false;
|
||||
showUnsavedWarning = false;
|
||||
if (discardTarget) goto(discardTarget);
|
||||
}}
|
||||
class="ml-4 shrink-0 font-sans text-xs font-bold tracking-widest text-amber-800 uppercase hover:text-amber-900 dark:text-amber-300"
|
||||
>
|
||||
{m.person_discard_changes()}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
{#if form?.error}
|
||||
<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
|
||||
{form.error}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if form?.error}
|
||||
<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
|
||||
{form.error}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
|
||||
<form method="POST" use:enhance class="space-y-5">
|
||||
<AccountSection />
|
||||
<form
|
||||
id="new-user-form"
|
||||
method="POST"
|
||||
use:enhance
|
||||
oninput={() => {
|
||||
isDirty = true;
|
||||
showUnsavedWarning = false;
|
||||
}}
|
||||
class="space-y-5"
|
||||
>
|
||||
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
|
||||
<AccountSection />
|
||||
</div>
|
||||
|
||||
<!-- Profile -->
|
||||
<h2 class="pt-2 text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.profile_section_personal()}
|
||||
</h2>
|
||||
<UserProfileSection />
|
||||
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
|
||||
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.profile_section_personal()}
|
||||
</h3>
|
||||
<UserProfileSection />
|
||||
</div>
|
||||
|
||||
<!-- Groups -->
|
||||
<h2 class="pt-2 text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_col_groups()}
|
||||
</h2>
|
||||
<UserGroupsSection groups={data.groups} />
|
||||
|
||||
<!-- Save bar -->
|
||||
<div
|
||||
class="mt-4 flex items-center justify-between rounded-sm border border-line bg-surface px-6 py-4 shadow-sm"
|
||||
>
|
||||
<a
|
||||
href="/admin"
|
||||
class="font-sans text-xs font-bold tracking-widest text-ink-2 uppercase hover:text-ink"
|
||||
>
|
||||
{m.btn_cancel()}
|
||||
</a>
|
||||
<button
|
||||
type="submit"
|
||||
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
>
|
||||
{m.btn_create()}
|
||||
</button>
|
||||
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
|
||||
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.admin_col_groups()}
|
||||
</h3>
|
||||
<UserGroupsSection groups={data.groups} />
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Docked footer -->
|
||||
<div class="flex items-center justify-between border-t border-line bg-surface px-5 py-3">
|
||||
<a
|
||||
href="/admin/users"
|
||||
class="font-sans text-xs font-bold tracking-widest text-ink-2 uppercase hover:text-ink"
|
||||
>
|
||||
{m.btn_cancel()}
|
||||
</a>
|
||||
<button
|
||||
type="submit"
|
||||
form="new-user-form"
|
||||
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
|
||||
>
|
||||
{m.btn_create()}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -33,18 +33,11 @@ describe('Admin new user page – rendering', () => {
|
||||
await expect.element(page.getByText('Admins')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('cancel link points to /admin', async () => {
|
||||
it('cancel link points to /admin/users', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /Abbrechen/i }))
|
||||
.toHaveAttribute('href', '/admin');
|
||||
});
|
||||
|
||||
it('back link points to /admin', async () => {
|
||||
render(Page, { data: baseData, form: null });
|
||||
await expect
|
||||
.element(page.getByRole('link', { name: /Zurück/i }))
|
||||
.toHaveAttribute('href', '/admin');
|
||||
.toHaveAttribute('href', '/admin/users');
|
||||
});
|
||||
|
||||
it('renders the create button', async () => {
|
||||
|
||||
82
frontend/src/routes/korrespondenz/+page.server.ts
Normal file
82
frontend/src/routes/korrespondenz/+page.server.ts
Normal 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 }
|
||||
};
|
||||
}
|
||||
140
frontend/src/routes/korrespondenz/+page.svelte
Normal file
140
frontend/src/routes/korrespondenz/+page.svelte
Normal 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>
|
||||
142
frontend/src/routes/korrespondenz/ConversationFilterBar.svelte
Normal file
142
frontend/src/routes/korrespondenz/ConversationFilterBar.svelte
Normal 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>
|
||||
180
frontend/src/routes/korrespondenz/ConversationTimeline.svelte
Normal file
180
frontend/src/routes/korrespondenz/ConversationTimeline.svelte
Normal 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>
|
||||
@@ -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>
|
||||
120
frontend/src/routes/korrespondenz/CorrespondenzEmptyState.svelte
Normal file
120
frontend/src/routes/korrespondenz/CorrespondenzEmptyState.svelte
Normal 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>
|
||||
@@ -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>
|
||||
129
frontend/src/routes/korrespondenz/CorrespondenzPersonBar.svelte
Normal file
129
frontend/src/routes/korrespondenz/CorrespondenzPersonBar.svelte
Normal 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>
|
||||
50
frontend/src/routes/korrespondenz/SinglePersonHintBar.svelte
Normal file
50
frontend/src/routes/korrespondenz/SinglePersonHintBar.svelte
Normal 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>
|
||||
146
frontend/src/routes/korrespondenz/page.server.spec.ts
Normal file
146
frontend/src/routes/korrespondenz/page.server.spec.ts
Normal 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 });
|
||||
});
|
||||
});
|
||||
246
frontend/src/routes/korrespondenz/page.svelte.spec.ts
Normal file
246
frontend/src/routes/korrespondenz/page.svelte.spec.ts
Normal 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();
|
||||
});
|
||||
});
|
||||
@@ -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"
|
||||
>
|
||||
|
||||
Reference in New Issue
Block a user