Compare commits
84 Commits
8f2a7a3528
...
feat/issue
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ebeb0cf865 | ||
|
|
46eb908ff4 | ||
|
|
616d6ba01c | ||
|
|
154f859efc | ||
|
|
591316aa22 | ||
|
|
89f2106d8b | ||
|
|
33c29fbff3 | ||
|
|
757d0493a0 | ||
|
|
50e637a9f2 | ||
|
|
4bb9393a83 | ||
|
|
ff3ea70826 | ||
|
|
010904d6e1 | ||
|
|
6b5f05bd2b | ||
|
|
cefcdf3072 | ||
|
|
9cacc6079e | ||
|
|
9d6c7b8605 | ||
|
|
c61b08d6de | ||
|
|
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 | ||
|
|
169e6dc578 | ||
|
|
04d3ac0415 | ||
|
|
a3e8a5e15e | ||
|
|
fffecb5bf6 | ||
|
|
f5645d6c32 | ||
|
|
27d7225330 | ||
|
|
241e4874ad | ||
|
|
272073f186 | ||
|
|
44e8891ca9 | ||
|
|
7141ae1e1f | ||
|
|
f4c99cabd5 | ||
|
|
3abdf9bb68 | ||
|
|
7b03aada3b | ||
|
|
707a7610f8 | ||
|
|
593638482d | ||
|
|
a3d750822c | ||
|
|
3987bbc1f9 | ||
|
|
d1e506135b | ||
|
|
ef9a85eee8 | ||
|
|
93107e7c59 | ||
|
|
5374bdabd4 | ||
|
|
7573d3b5da | ||
|
|
7dcb8bc705 | ||
|
|
29634c7f7a | ||
|
|
79185a2e34 | ||
|
|
209531ce0c | ||
|
|
4899e6301f | ||
|
|
9b24a88200 | ||
|
|
7155fbafd8 | ||
|
|
cb58e39f3c | ||
|
|
18b85bec1f | ||
|
|
26c58bf5dd | ||
|
|
c8f7225506 | ||
|
|
03ee9ccec4 | ||
|
|
64761d5c1f | ||
|
|
3b21aae44d | ||
|
|
5ac7880a2b | ||
|
|
9f73c2ee4a | ||
|
|
ae47af52b9 | ||
| 5facb52d21 |
@@ -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
|
||||
|
||||
@@ -34,6 +34,10 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package org.raddatz.familienarchiv.controller;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
import org.raddatz.familienarchiv.exception.DomainException;
|
||||
import org.raddatz.familienarchiv.exception.ErrorCode;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -32,6 +33,14 @@ public class GlobalExceptionHandler {
|
||||
return ResponseEntity.badRequest().body(new ErrorResponse(ErrorCode.VALIDATION_ERROR, message));
|
||||
}
|
||||
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
public ResponseEntity<ErrorResponse> handleConstraintViolation(ConstraintViolationException ex) {
|
||||
String message = ex.getConstraintViolations().stream()
|
||||
.map(v -> v.getPropertyPath() + ": " + v.getMessage())
|
||||
.collect(Collectors.joining(", "));
|
||||
return ResponseEntity.badRequest().body(new ErrorResponse(ErrorCode.VALIDATION_ERROR, message));
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
|
||||
public ResponseEntity<ErrorResponse> handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
|
||||
String message = "Invalid value '" + ex.getValue() + "' for parameter '" + ex.getName() + "'";
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package org.raddatz.familienarchiv.controller;
|
||||
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import org.raddatz.familienarchiv.dto.NotificationDTO;
|
||||
import org.raddatz.familienarchiv.dto.NotificationPreferenceDTO;
|
||||
import org.raddatz.familienarchiv.model.AppUser;
|
||||
@@ -16,6 +19,7 @@ import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
@@ -25,6 +29,7 @@ import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@Validated
|
||||
public class NotificationController {
|
||||
|
||||
private final NotificationService notificationService;
|
||||
@@ -44,9 +49,9 @@ public class NotificationController {
|
||||
@GetMapping("/api/notifications")
|
||||
public Page<NotificationDTO> getNotifications(
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "10") int size,
|
||||
@RequestParam(required = false) NotificationType type,
|
||||
@RequestParam(required = false) Boolean read,
|
||||
@RequestParam(defaultValue = "10") @Min(1) @Max(100) int size,
|
||||
@Parameter(description = "Filter by notification type") @RequestParam(required = false) NotificationType type,
|
||||
@Parameter(description = "Filter by read status") @RequestParam(required = false) Boolean read,
|
||||
Authentication authentication) {
|
||||
AppUser user = resolveUser(authentication);
|
||||
PageRequest pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
|
||||
|
||||
@@ -4,16 +4,23 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
|
||||
import org.raddatz.familienarchiv.dto.PersonSummaryDTO;
|
||||
import org.raddatz.familienarchiv.dto.PersonUpdateDTO;
|
||||
import org.raddatz.familienarchiv.model.Document;
|
||||
import org.raddatz.familienarchiv.model.Person;
|
||||
import org.raddatz.familienarchiv.security.Permission;
|
||||
import org.raddatz.familienarchiv.security.RequirePermission;
|
||||
import org.raddatz.familienarchiv.service.DocumentService;
|
||||
import org.raddatz.familienarchiv.service.PersonService;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@RestController
|
||||
@@ -25,7 +32,7 @@ public class PersonController {
|
||||
private final DocumentService documentService;
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<List<Person>> getPersons(@RequestParam(required = false) String q) {
|
||||
public ResponseEntity<List<PersonSummaryDTO>> getPersons(@RequestParam(required = false) String q) {
|
||||
return ResponseEntity.ok(personService.findAll(q));
|
||||
}
|
||||
|
||||
@@ -52,17 +59,20 @@ public class PersonController {
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<Person> createPerson(@RequestBody Map<String, String> body) {
|
||||
String firstName = body.get("firstName");
|
||||
String lastName = body.get("lastName");
|
||||
if (firstName == null || firstName.isBlank() || lastName == null || lastName.isBlank()) {
|
||||
@RequirePermission(Permission.WRITE_ALL)
|
||||
public ResponseEntity<Person> createPerson(@Valid @RequestBody PersonUpdateDTO dto) {
|
||||
if (dto.getFirstName() == null || dto.getFirstName().isBlank()
|
||||
|| dto.getLastName() == null || dto.getLastName().isBlank()) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Vor- und Nachname sind Pflichtfelder");
|
||||
}
|
||||
return ResponseEntity.ok(personService.createPerson(firstName.trim(), lastName.trim(), body.get("alias")));
|
||||
dto.setFirstName(dto.getFirstName().trim());
|
||||
dto.setLastName(dto.getLastName().trim());
|
||||
return ResponseEntity.ok(personService.createPerson(dto));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<Person> updatePerson(@PathVariable UUID id, @RequestBody PersonUpdateDTO dto) {
|
||||
@RequirePermission(Permission.WRITE_ALL)
|
||||
public ResponseEntity<Person> updatePerson(@PathVariable UUID id, @Valid @RequestBody PersonUpdateDTO dto) {
|
||||
if (dto.getFirstName() == null || dto.getFirstName().isBlank()
|
||||
|| dto.getLastName() == null || dto.getLastName().isBlank()) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Vor- und Nachname sind Pflichtfelder");
|
||||
@@ -74,6 +84,7 @@ public class PersonController {
|
||||
|
||||
@PostMapping("/{id}/merge")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
@RequirePermission(Permission.WRITE_ALL)
|
||||
public void mergePerson(@PathVariable UUID id, @RequestBody Map<String, String> body) {
|
||||
String targetIdStr = body.get("targetPersonId");
|
||||
if (targetIdStr == null || targetIdStr.isBlank()) {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.raddatz.familienarchiv.controller;
|
||||
|
||||
import org.raddatz.familienarchiv.dto.StatsDTO;
|
||||
import org.raddatz.familienarchiv.repository.DocumentRepository;
|
||||
import org.raddatz.familienarchiv.repository.PersonRepository;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/stats")
|
||||
@RequiredArgsConstructor
|
||||
public class StatsController {
|
||||
|
||||
private final PersonRepository personRepository;
|
||||
private final DocumentRepository documentRepository;
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<StatsDTO> getStats() {
|
||||
return ResponseEntity.ok(new StatsDTO(personRepository.count(), documentRepository.count()));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -14,5 +14,6 @@ public record NotificationDTO(
|
||||
UUID annotationId,
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED) boolean read,
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED) LocalDateTime createdAt,
|
||||
String actorName
|
||||
String actorName,
|
||||
String documentTitle
|
||||
) {}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package org.raddatz.familienarchiv.dto;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Projection returned by the /api/persons list endpoint.
|
||||
* Includes document count to avoid N+1 queries in the UI.
|
||||
* Uses interface projection for compatibility with native queries.
|
||||
*/
|
||||
public interface PersonSummaryDTO {
|
||||
UUID getId();
|
||||
String getFirstName();
|
||||
String getLastName();
|
||||
String getAlias();
|
||||
Integer getBirthYear();
|
||||
Integer getDeathYear();
|
||||
String getNotes();
|
||||
long getDocumentCount();
|
||||
}
|
||||
@@ -1,12 +1,17 @@
|
||||
package org.raddatz.familienarchiv.dto;
|
||||
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class PersonUpdateDTO {
|
||||
@Size(max = 100)
|
||||
private String firstName;
|
||||
@Size(max = 100)
|
||||
private String lastName;
|
||||
@Size(max = 200)
|
||||
private String alias;
|
||||
@Size(max = 5000)
|
||||
private String notes;
|
||||
private Integer birthYear;
|
||||
private Integer deathYear;
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package org.raddatz.familienarchiv.dto;
|
||||
|
||||
/**
|
||||
* Aggregate counts for the dashboard/persons stats bar.
|
||||
*/
|
||||
public record StatsDTO(long totalPersons, long totalDocuments) {
|
||||
}
|
||||
@@ -8,6 +8,10 @@ package org.raddatz.familienarchiv.exception;
|
||||
*/
|
||||
public enum ErrorCode {
|
||||
|
||||
// --- Persons ---
|
||||
/** A person with the given ID does not exist. 404 */
|
||||
PERSON_NOT_FOUND,
|
||||
|
||||
// --- Documents ---
|
||||
/** A document with the given ID does not exist. 404 */
|
||||
DOCUMENT_NOT_FOUND,
|
||||
|
||||
@@ -12,7 +12,9 @@ import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -44,6 +46,9 @@ public interface DocumentRepository extends JpaRepository<Document, UUID>, JpaSp
|
||||
|
||||
List<Document> findByFileHashIsNullAndFilePathIsNotNull();
|
||||
|
||||
@Query("SELECT d.id, d.title FROM Document d WHERE d.id IN :ids")
|
||||
List<Object[]> findIdAndTitleByIdIn(@Param("ids") Collection<UUID> ids);
|
||||
|
||||
long countByMetadataCompleteFalse();
|
||||
|
||||
List<Document> findByMetadataCompleteFalse(Sort sort);
|
||||
@@ -55,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,
|
||||
@@ -68,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);
|
||||
|
||||
}
|
||||
@@ -21,6 +21,9 @@ public interface NotificationRepository extends JpaRepository<Notification, UUID
|
||||
Page<Notification> findByRecipientIdAndTypeAndReadFalseOrderByCreatedAtDesc(
|
||||
UUID recipientId, NotificationType type, Pageable pageable);
|
||||
|
||||
Page<Notification> findByRecipientIdAndReadFalseOrderByCreatedAtDesc(
|
||||
UUID recipientId, Pageable pageable);
|
||||
|
||||
long countByRecipientIdAndReadFalse(UUID recipientId);
|
||||
|
||||
@Modifying
|
||||
|
||||
@@ -4,6 +4,7 @@ import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.raddatz.familienarchiv.dto.PersonSummaryDTO;
|
||||
import org.raddatz.familienarchiv.model.Person;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
@@ -31,6 +32,33 @@ public interface PersonRepository extends JpaRepository<Person, UUID> {
|
||||
// Exact first+last name match, used for filename-based sender lookup
|
||||
Optional<Person> findByFirstNameIgnoreCaseAndLastNameIgnoreCase(String firstName, String lastName);
|
||||
|
||||
// --- PersonSummaryDTO with document count ---
|
||||
|
||||
@Query(value = """
|
||||
SELECT p.id, p.first_name AS firstName, p.last_name AS lastName,
|
||||
p.alias, p.birth_year AS birthYear, p.death_year AS deathYear, p.notes,
|
||||
(SELECT COUNT(*) FROM documents d WHERE d.sender_id = p.id)
|
||||
+ (SELECT COUNT(*) FROM document_receivers dr WHERE dr.person_id = p.id) AS documentCount
|
||||
FROM persons p
|
||||
ORDER BY p.last_name ASC, p.first_name ASC
|
||||
""",
|
||||
nativeQuery = true)
|
||||
List<PersonSummaryDTO> findAllWithDocumentCount();
|
||||
|
||||
@Query(value = """
|
||||
SELECT p.id, p.first_name AS firstName, p.last_name AS lastName,
|
||||
p.alias, p.birth_year AS birthYear, p.death_year AS deathYear, p.notes,
|
||||
(SELECT COUNT(*) FROM documents d WHERE d.sender_id = p.id)
|
||||
+ (SELECT COUNT(*) FROM document_receivers dr WHERE dr.person_id = p.id) AS documentCount
|
||||
FROM persons p
|
||||
WHERE LOWER(CONCAT(p.first_name,' ',p.last_name)) LIKE LOWER(CONCAT('%',:query,'%'))
|
||||
OR LOWER(CONCAT(p.last_name,' ',p.first_name)) LIKE LOWER(CONCAT('%',:query,'%'))
|
||||
OR LOWER(p.alias) LIKE LOWER(CONCAT('%',:query,'%'))
|
||||
ORDER BY p.last_name ASC, p.first_name ASC
|
||||
""",
|
||||
nativeQuery = true)
|
||||
List<PersonSummaryDTO> searchWithDocumentCount(@Param("query") String query);
|
||||
|
||||
// --- Correspondent queries ---
|
||||
|
||||
@Query(value = """
|
||||
|
||||
@@ -25,8 +25,11 @@ import java.security.NoSuchAlgorithmException;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
@@ -46,6 +49,15 @@ public class DocumentService {
|
||||
|
||||
public record StoreResult(Document document, boolean isNew) {}
|
||||
|
||||
public Map<UUID, String> findTitlesByIds(Collection<UUID> ids) {
|
||||
if (ids.isEmpty()) return Map.of();
|
||||
Map<UUID, String> titles = new HashMap<>();
|
||||
for (Object[] row : documentRepository.findIdAndTitleByIdIn(ids)) {
|
||||
titles.put((UUID) row[0], (String) row[1]);
|
||||
}
|
||||
return titles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lädt eine Datei hoch.
|
||||
* - Prüft, ob ein Eintrag (aus Excel) schon existiert.
|
||||
@@ -316,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -20,10 +20,13 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -32,6 +35,7 @@ public class NotificationService {
|
||||
|
||||
private final NotificationRepository notificationRepository;
|
||||
private final UserService userService;
|
||||
private final DocumentService documentService;
|
||||
private final Optional<JavaMailSender> mailSender;
|
||||
private final SseEmitterRegistry sseEmitterRegistry;
|
||||
|
||||
@@ -94,16 +98,26 @@ public class NotificationService {
|
||||
}
|
||||
|
||||
public Page<NotificationDTO> getNotifications(UUID userId, NotificationType type, Boolean read, Pageable pageable) {
|
||||
Page<Notification> page;
|
||||
if (type != null && Boolean.FALSE.equals(read)) {
|
||||
return notificationRepository.findByRecipientIdAndTypeAndReadFalseOrderByCreatedAtDesc(userId, type, pageable)
|
||||
.map(this::toDTO);
|
||||
page = notificationRepository.findByRecipientIdAndTypeAndReadFalseOrderByCreatedAtDesc(userId, type, pageable);
|
||||
} else if (type != null) {
|
||||
page = notificationRepository.findByRecipientIdAndTypeOrderByCreatedAtDesc(userId, type, pageable);
|
||||
} else if (Boolean.FALSE.equals(read)) {
|
||||
page = notificationRepository.findByRecipientIdAndReadFalseOrderByCreatedAtDesc(userId, pageable);
|
||||
} else {
|
||||
page = notificationRepository.findByRecipientIdOrderByCreatedAtDesc(userId, pageable);
|
||||
}
|
||||
if (type != null) {
|
||||
return notificationRepository.findByRecipientIdAndTypeOrderByCreatedAtDesc(userId, type, pageable)
|
||||
.map(this::toDTO);
|
||||
}
|
||||
return notificationRepository.findByRecipientIdOrderByCreatedAtDesc(userId, pageable)
|
||||
.map(this::toDTO);
|
||||
return mapWithDocumentTitles(page);
|
||||
}
|
||||
|
||||
private Page<NotificationDTO> mapWithDocumentTitles(Page<Notification> page) {
|
||||
Set<UUID> documentIds = page.getContent().stream()
|
||||
.map(Notification::getDocumentId)
|
||||
.filter(id -> id != null)
|
||||
.collect(Collectors.toSet());
|
||||
Map<UUID, String> titles = documentService.findTitlesByIds(documentIds);
|
||||
return page.map(n -> toDTO(n, titles));
|
||||
}
|
||||
|
||||
public long countUnread(UUID userId) {
|
||||
@@ -124,7 +138,7 @@ public class NotificationService {
|
||||
throw DomainException.forbidden("Notification belongs to a different user");
|
||||
}
|
||||
notification.setRead(true);
|
||||
return toDTO(notificationRepository.save(notification));
|
||||
return toDTO(notificationRepository.save(notification), Map.of());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@@ -136,10 +150,10 @@ public class NotificationService {
|
||||
|
||||
private void saveAndPush(Notification notification) {
|
||||
Notification saved = notificationRepository.save(notification);
|
||||
sseEmitterRegistry.send(saved.getRecipient().getId(), toDTO(saved));
|
||||
sseEmitterRegistry.send(saved.getRecipient().getId(), toDTO(saved, Map.of()));
|
||||
}
|
||||
|
||||
private NotificationDTO toDTO(Notification n) {
|
||||
private NotificationDTO toDTO(Notification n, Map<UUID, String> titles) {
|
||||
return new NotificationDTO(
|
||||
n.getId(),
|
||||
n.getType(),
|
||||
@@ -148,7 +162,8 @@ public class NotificationService {
|
||||
n.getAnnotationId(),
|
||||
n.isRead(),
|
||||
n.getCreatedAt(),
|
||||
n.getActorName()
|
||||
n.getActorName(),
|
||||
n.getDocumentId() != null ? titles.get(n.getDocumentId()) : null
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,10 @@ import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.raddatz.familienarchiv.dto.PersonSummaryDTO;
|
||||
import org.raddatz.familienarchiv.dto.PersonUpdateDTO;
|
||||
import org.raddatz.familienarchiv.exception.DomainException;
|
||||
import org.raddatz.familienarchiv.exception.ErrorCode;
|
||||
import org.raddatz.familienarchiv.model.Person;
|
||||
import org.raddatz.familienarchiv.repository.PersonRepository;
|
||||
import org.springframework.http.HttpStatus;
|
||||
@@ -20,16 +23,19 @@ public class PersonService {
|
||||
|
||||
private final PersonRepository personRepository;
|
||||
|
||||
public List<Person> findAll(String q) {
|
||||
if (q != null && !q.isBlank()) {
|
||||
return personRepository.searchByName(q);
|
||||
public List<PersonSummaryDTO> findAll(String q) {
|
||||
if (q == null) {
|
||||
return personRepository.findAllWithDocumentCount();
|
||||
}
|
||||
return personRepository.findAllByOrderByLastNameAscFirstNameAsc();
|
||||
if (q.isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
return personRepository.searchWithDocumentCount(q.trim());
|
||||
}
|
||||
|
||||
public Person getById(UUID id) {
|
||||
return personRepository.findById(id)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Person nicht gefunden"));
|
||||
.orElseThrow(() -> DomainException.notFound(ErrorCode.PERSON_NOT_FOUND, "Person not found: " + id));
|
||||
}
|
||||
|
||||
public List<Person> findCorrespondents(UUID personId, String q) {
|
||||
@@ -71,12 +77,36 @@ public class PersonService {
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Person updatePerson(UUID id, PersonUpdateDTO dto) {
|
||||
if (dto.getBirthYear() != null && dto.getDeathYear() != null && dto.getBirthYear() > dto.getDeathYear()) {
|
||||
public Person createPerson(PersonUpdateDTO dto) {
|
||||
validateYears(dto.getBirthYear(), dto.getDeathYear());
|
||||
Person person = Person.builder()
|
||||
.firstName(dto.getFirstName())
|
||||
.lastName(dto.getLastName())
|
||||
.alias(dto.getAlias() == null || dto.getAlias().isBlank() ? null : dto.getAlias().trim())
|
||||
.notes(dto.getNotes() == null || dto.getNotes().isBlank() ? null : dto.getNotes().trim())
|
||||
.birthYear(dto.getBirthYear())
|
||||
.deathYear(dto.getDeathYear())
|
||||
.build();
|
||||
return personRepository.save(person);
|
||||
}
|
||||
|
||||
private void validateYears(Integer birthYear, Integer deathYear) {
|
||||
if (birthYear != null && birthYear <= 0) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Geburtsjahr muss eine positive Zahl sein");
|
||||
}
|
||||
if (deathYear != null && deathYear <= 0) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Todesjahr muss eine positive Zahl sein");
|
||||
}
|
||||
if (birthYear != null && deathYear != null && birthYear > deathYear) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Geburtsjahr darf nicht nach dem Todesjahr liegen");
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Person updatePerson(UUID id, PersonUpdateDTO dto) {
|
||||
validateYears(dto.getBirthYear(), dto.getDeathYear());
|
||||
Person person = personRepository.findById(id)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Person nicht gefunden"));
|
||||
.orElseThrow(() -> DomainException.notFound(ErrorCode.PERSON_NOT_FOUND, "Person not found: " + id));
|
||||
person.setFirstName(dto.getFirstName());
|
||||
person.setLastName(dto.getLastName());
|
||||
person.setAlias(dto.getAlias() == null || dto.getAlias().isBlank() ? null : dto.getAlias().trim());
|
||||
@@ -92,9 +122,9 @@ public class PersonService {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Quelle und Ziel dürfen nicht identisch sein");
|
||||
}
|
||||
personRepository.findById(sourceId)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Quell-Person nicht gefunden"));
|
||||
.orElseThrow(() -> DomainException.notFound(ErrorCode.PERSON_NOT_FOUND, "Source person not found: " + sourceId));
|
||||
personRepository.findById(targetId)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Ziel-Person nicht gefunden"));
|
||||
.orElseThrow(() -> DomainException.notFound(ErrorCode.PERSON_NOT_FOUND, "Target person not found: " + targetId));
|
||||
|
||||
// Reassign sender references
|
||||
personRepository.reassignSender(sourceId, targetId);
|
||||
|
||||
@@ -75,7 +75,7 @@ class NotificationControllerTest {
|
||||
AppUser user = AppUser.builder().id(USER_ID).username("testuser").build();
|
||||
NotificationDTO dto = new NotificationDTO(
|
||||
UUID.randomUUID(), NotificationType.REPLY, UUID.randomUUID(),
|
||||
UUID.randomUUID(), null, false, LocalDateTime.now(), "Anna Smith");
|
||||
UUID.randomUUID(), null, false, LocalDateTime.now(), "Anna Smith", "Testdokument");
|
||||
|
||||
when(userService.findByUsername("testuser")).thenReturn(user);
|
||||
when(notificationService.getNotifications(eq(USER_ID), any(), any(), any()))
|
||||
@@ -123,6 +123,20 @@ class NotificationControllerTest {
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "testuser", authorities = {"READ_ALL"})
|
||||
void getNotifications_returns400_whenSizeExceedsMaximum() throws Exception {
|
||||
mockMvc.perform(get("/api/notifications").param("size", "200"))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "testuser", authorities = {"READ_ALL"})
|
||||
void getNotifications_returns400_whenSizeIsZero() throws Exception {
|
||||
mockMvc.perform(get("/api/notifications").param("size", "0"))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
// ─── POST /api/notifications/read-all ────────────────────────────────────
|
||||
|
||||
@Test
|
||||
|
||||
@@ -21,6 +21,8 @@ import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.raddatz.familienarchiv.dto.PersonSummaryDTO;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -57,14 +59,27 @@ class PersonControllerTest {
|
||||
@Test
|
||||
@WithMockUser
|
||||
void getPersons_delegatesQueryParam_toService() throws Exception {
|
||||
Person person = Person.builder().id(UUID.randomUUID()).firstName("Hans").lastName("Müller").build();
|
||||
when(personService.findAll("Hans")).thenReturn(List.of(person));
|
||||
PersonSummaryDTO dto = mockPersonSummary("Hans", "Müller");
|
||||
when(personService.findAll("Hans")).thenReturn(List.of(dto));
|
||||
|
||||
mockMvc.perform(get("/api/persons").param("q", "Hans"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].firstName").value("Hans"));
|
||||
}
|
||||
|
||||
private PersonSummaryDTO mockPersonSummary(String firstName, String lastName) {
|
||||
return new PersonSummaryDTO() {
|
||||
public java.util.UUID getId() { return UUID.randomUUID(); }
|
||||
public String getFirstName() { return firstName; }
|
||||
public String getLastName() { return lastName; }
|
||||
public String getAlias() { return null; }
|
||||
public Integer getBirthYear() { return null; }
|
||||
public Integer getDeathYear() { return null; }
|
||||
public String getNotes() { return null; }
|
||||
public long getDocumentCount() { return 0; }
|
||||
};
|
||||
}
|
||||
|
||||
// ─── GET /api/persons/{id} ────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
@@ -162,7 +177,7 @@ class PersonControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
@WithMockUser(authorities = "WRITE_ALL")
|
||||
void createPerson_returns400_whenFirstNameIsMissing() throws Exception {
|
||||
mockMvc.perform(post("/api/persons")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
@@ -171,7 +186,7 @@ class PersonControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
@WithMockUser(authorities = "WRITE_ALL")
|
||||
void createPerson_returns400_whenFirstNameIsBlank() throws Exception {
|
||||
mockMvc.perform(post("/api/persons")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
@@ -180,7 +195,7 @@ class PersonControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
@WithMockUser(authorities = "WRITE_ALL")
|
||||
void createPerson_returns400_whenLastNameIsMissing() throws Exception {
|
||||
mockMvc.perform(post("/api/persons")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
@@ -189,7 +204,7 @@ class PersonControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
@WithMockUser(authorities = "WRITE_ALL")
|
||||
void createPerson_returns400_whenLastNameIsBlank() throws Exception {
|
||||
mockMvc.perform(post("/api/persons")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
@@ -198,10 +213,10 @@ class PersonControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
@WithMockUser(authorities = "WRITE_ALL")
|
||||
void createPerson_returns200_whenValid() throws Exception {
|
||||
Person saved = Person.builder().id(UUID.randomUUID()).firstName("Hans").lastName("Müller").build();
|
||||
when(personService.createPerson(eq("Hans"), eq("Müller"), any())).thenReturn(saved);
|
||||
when(personService.createPerson(any(org.raddatz.familienarchiv.dto.PersonUpdateDTO.class))).thenReturn(saved);
|
||||
|
||||
mockMvc.perform(post("/api/persons")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
@@ -221,7 +236,7 @@ class PersonControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
@WithMockUser(authorities = "WRITE_ALL")
|
||||
void updatePerson_returns400_whenFirstNameIsBlank() throws Exception {
|
||||
mockMvc.perform(put("/api/persons/{id}", UUID.randomUUID())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
@@ -230,7 +245,7 @@ class PersonControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
@WithMockUser(authorities = "WRITE_ALL")
|
||||
void updatePerson_returns400_whenLastNameIsNull() throws Exception {
|
||||
mockMvc.perform(put("/api/persons/{id}", UUID.randomUUID())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
@@ -239,7 +254,7 @@ class PersonControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
@WithMockUser(authorities = "WRITE_ALL")
|
||||
void updatePerson_returns200_whenValid() throws Exception {
|
||||
UUID id = UUID.randomUUID();
|
||||
Person updated = Person.builder().id(id).firstName("Hans").lastName("Müller").build();
|
||||
@@ -263,7 +278,7 @@ class PersonControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
@WithMockUser(authorities = "WRITE_ALL")
|
||||
void mergePerson_returns400_whenTargetPersonIdIsMissing() throws Exception {
|
||||
mockMvc.perform(post("/api/persons/{id}/merge", UUID.randomUUID())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
@@ -272,7 +287,7 @@ class PersonControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
@WithMockUser(authorities = "WRITE_ALL")
|
||||
void mergePerson_returns400_whenTargetPersonIdIsBlank() throws Exception {
|
||||
mockMvc.perform(post("/api/persons/{id}/merge", UUID.randomUUID())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
@@ -281,7 +296,7 @@ class PersonControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
@WithMockUser(authorities = "WRITE_ALL")
|
||||
void mergePerson_returns204_whenValid() throws Exception {
|
||||
UUID sourceId = UUID.randomUUID();
|
||||
UUID targetId = UUID.randomUUID();
|
||||
@@ -304,4 +319,78 @@ class PersonControllerTest {
|
||||
.content("{\"firstName\":\"Hans\",\"lastName\":\" \"}"))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
// ─── Phase 2.2: POST /api/persons with full PersonUpdateDTO ───────────────
|
||||
|
||||
@Test
|
||||
@WithMockUser(authorities = "WRITE_ALL")
|
||||
void createPerson_returns200_withAllSixFields() throws Exception {
|
||||
UUID id = UUID.randomUUID();
|
||||
Person saved = Person.builder().id(id).firstName("Maria").lastName("Raddatz")
|
||||
.alias("Oma Maria").birthYear(1901).deathYear(1975).notes("Some notes").build();
|
||||
when(personService.createPerson(any(org.raddatz.familienarchiv.dto.PersonUpdateDTO.class))).thenReturn(saved);
|
||||
|
||||
mockMvc.perform(post("/api/persons")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"firstName\":\"Maria\",\"lastName\":\"Raddatz\"," +
|
||||
"\"alias\":\"Oma Maria\",\"birthYear\":1901,\"deathYear\":1975," +
|
||||
"\"notes\":\"Some notes\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.firstName").value("Maria"))
|
||||
.andExpect(jsonPath("$.alias").value("Oma Maria"))
|
||||
.andExpect(jsonPath("$.birthYear").value(1901));
|
||||
}
|
||||
|
||||
// ─── Phase 1.2: @Size constraints ─────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
@WithMockUser(authorities = "WRITE_ALL")
|
||||
void updatePerson_returns400_whenNotesExceed5000Chars() throws Exception {
|
||||
String oversizedNotes = "x".repeat(5001);
|
||||
UUID id = UUID.randomUUID();
|
||||
mockMvc.perform(put("/api/persons/{id}", id)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"firstName\":\"Hans\",\"lastName\":\"Müller\",\"notes\":\"" + oversizedNotes + "\"}"))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(authorities = "WRITE_ALL")
|
||||
void updatePerson_returns400_whenFirstNameExceeds100Chars() throws Exception {
|
||||
String oversizedFirstName = "x".repeat(101);
|
||||
UUID id = UUID.randomUUID();
|
||||
mockMvc.perform(put("/api/persons/{id}", id)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"firstName\":\"" + oversizedFirstName + "\",\"lastName\":\"Müller\"}"))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
// ─── Phase 1.1: @RequirePermission(WRITE_ALL) on write endpoints ──────────
|
||||
|
||||
@Test
|
||||
@WithMockUser(authorities = "READ_ALL")
|
||||
void createPerson_returns403_whenUserHasOnlyReadPermission() throws Exception {
|
||||
mockMvc.perform(post("/api/persons")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"firstName\":\"Hans\",\"lastName\":\"Müller\"}"))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(authorities = "READ_ALL")
|
||||
void updatePerson_returns403_whenUserHasOnlyReadPermission() throws Exception {
|
||||
mockMvc.perform(put("/api/persons/{id}", UUID.randomUUID())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"firstName\":\"Hans\",\"lastName\":\"Müller\"}"))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(authorities = "READ_ALL")
|
||||
void mergePerson_returns403_whenUserHasOnlyReadPermission() throws Exception {
|
||||
mockMvc.perform(post("/api/persons/{id}/merge", UUID.randomUUID())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"targetPersonId\":\"" + UUID.randomUUID() + "\"}"))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package org.raddatz.familienarchiv.controller;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.raddatz.familienarchiv.config.SecurityConfig;
|
||||
import org.raddatz.familienarchiv.repository.DocumentRepository;
|
||||
import org.raddatz.familienarchiv.repository.PersonRepository;
|
||||
import org.raddatz.familienarchiv.security.PermissionAspect;
|
||||
import org.raddatz.familienarchiv.service.CustomUserDetailsService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.aop.AopAutoConfiguration;
|
||||
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@WebMvcTest(StatsController.class)
|
||||
@Import({SecurityConfig.class, PermissionAspect.class, AopAutoConfiguration.class})
|
||||
class StatsControllerTest {
|
||||
|
||||
@Autowired MockMvc mockMvc;
|
||||
|
||||
@MockitoBean PersonRepository personRepository;
|
||||
@MockitoBean DocumentRepository documentRepository;
|
||||
@MockitoBean CustomUserDetailsService customUserDetailsService;
|
||||
|
||||
@Test
|
||||
void getStats_returns401_whenUnauthenticated() throws Exception {
|
||||
mockMvc.perform(get("/api/stats"))
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
void getStats_returns200_withCorrectCounts() throws Exception {
|
||||
when(personRepository.count()).thenReturn(4L);
|
||||
when(documentRepository.count()).thenReturn(12L);
|
||||
|
||||
mockMvc.perform(get("/api/stats"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.totalPersons").value(4))
|
||||
.andExpect(jsonPath("$.totalDocuments").value(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
void getStats_returns200_withZeroCounts() throws Exception {
|
||||
when(personRepository.count()).thenReturn(0L);
|
||||
when(documentRepository.count()).thenReturn(0L);
|
||||
|
||||
mockMvc.perform(get("/api/stats"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.totalPersons").value(0))
|
||||
.andExpect(jsonPath("$.totalDocuments").value(0));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabas
|
||||
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import org.raddatz.familienarchiv.dto.PersonSummaryDTO;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import java.util.List;
|
||||
@@ -288,6 +290,76 @@ class PersonRepositoryTest {
|
||||
assertThat(targetCount).isEqualTo(1); // no duplicate
|
||||
}
|
||||
|
||||
// ─── Phase 3.2: findAllWithDocumentCount ──────────────────────────────────
|
||||
|
||||
@Test
|
||||
void findAllWithDocumentCount_includesDocumentCountAsSenderAndReceiver() {
|
||||
Person walter = personRepository.save(Person.builder().firstName("Walter").lastName("Müller").build());
|
||||
Person anna = personRepository.save(Person.builder().firstName("Anna").lastName("Schmidt").build());
|
||||
|
||||
// Walter sends 2 docs to Anna (Anna receives 2)
|
||||
documentRepository.save(Document.builder()
|
||||
.title("Brief 1").originalFilename("b1.pdf")
|
||||
.status(DocumentStatus.UPLOADED)
|
||||
.sender(walter).receivers(Set.of(anna)).build());
|
||||
documentRepository.save(Document.builder()
|
||||
.title("Brief 2").originalFilename("b2.pdf")
|
||||
.status(DocumentStatus.UPLOADED)
|
||||
.sender(walter).receivers(Set.of(anna)).build());
|
||||
// Anna also sends 1 doc to Walter
|
||||
documentRepository.save(Document.builder()
|
||||
.title("Brief 3").originalFilename("b3.pdf")
|
||||
.status(DocumentStatus.UPLOADED)
|
||||
.sender(anna).receivers(Set.of(walter)).build());
|
||||
|
||||
List<PersonSummaryDTO> result = personRepository.findAllWithDocumentCount();
|
||||
|
||||
PersonSummaryDTO walterSummary = result.stream()
|
||||
.filter(p -> p.getId().equals(walter.getId())).findFirst().orElseThrow();
|
||||
PersonSummaryDTO annaSummary = result.stream()
|
||||
.filter(p -> p.getId().equals(anna.getId())).findFirst().orElseThrow();
|
||||
|
||||
assertThat(walterSummary.getDocumentCount()).isEqualTo(3); // sent 2, received 1
|
||||
assertThat(annaSummary.getDocumentCount()).isEqualTo(3); // sent 1, received 2
|
||||
}
|
||||
|
||||
@Test
|
||||
void findAllWithDocumentCount_returnsZero_whenPersonHasNoDocuments() {
|
||||
Person solo = personRepository.save(Person.builder().firstName("Solo").lastName("Mensch").build());
|
||||
|
||||
List<PersonSummaryDTO> result = personRepository.findAllWithDocumentCount();
|
||||
|
||||
PersonSummaryDTO soloSummary = result.stream()
|
||||
.filter(p -> p.getId().equals(solo.getId())).findFirst().orElseThrow();
|
||||
assertThat(soloSummary.getDocumentCount()).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void searchWithDocumentCount_filtersAndIncludesCount() {
|
||||
Person hans = personRepository.save(Person.builder().firstName("Hans").lastName("Müller").build());
|
||||
Person anna = personRepository.save(Person.builder().firstName("Anna").lastName("Schmidt").build());
|
||||
|
||||
documentRepository.save(Document.builder()
|
||||
.title("Brief").originalFilename("brief.pdf")
|
||||
.status(DocumentStatus.UPLOADED)
|
||||
.sender(hans).receivers(Set.of(anna)).build());
|
||||
|
||||
List<PersonSummaryDTO> result = personRepository.searchWithDocumentCount("Hans");
|
||||
|
||||
assertThat(result).hasSize(1);
|
||||
assertThat(result.get(0).getFirstName()).isEqualTo("Hans");
|
||||
assertThat(result.get(0).getDocumentCount()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void searchWithDocumentCount_isCaseInsensitive() {
|
||||
personRepository.save(Person.builder().firstName("Hans").lastName("Müller").build());
|
||||
|
||||
List<PersonSummaryDTO> result = personRepository.searchWithDocumentCount("hans");
|
||||
|
||||
assertThat(result).hasSize(1);
|
||||
}
|
||||
|
||||
// ─── deleteReceiverReferences ─────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import org.raddatz.familienarchiv.dto.NotificationDTO;
|
||||
import org.raddatz.familienarchiv.exception.DomainException;
|
||||
import org.raddatz.familienarchiv.model.*;
|
||||
import org.raddatz.familienarchiv.repository.NotificationRepository;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.mail.MailException;
|
||||
import org.springframework.mail.MailSendException;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
@@ -19,6 +20,7 @@ import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
@@ -34,6 +36,7 @@ class NotificationServiceTest {
|
||||
|
||||
@Mock NotificationRepository notificationRepository;
|
||||
@Mock UserService userService;
|
||||
@Mock DocumentService documentService;
|
||||
@Mock JavaMailSender mailSender;
|
||||
@Mock SseEmitterRegistry sseEmitterRegistry;
|
||||
|
||||
@@ -45,7 +48,7 @@ class NotificationServiceTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
notificationService = new NotificationService(notificationRepository, userService, Optional.of(mailSender), sseEmitterRegistry);
|
||||
notificationService = new NotificationService(notificationRepository, userService, documentService, Optional.of(mailSender), sseEmitterRegistry);
|
||||
|
||||
userA = AppUser.builder().id(UUID.randomUUID()).username("userA")
|
||||
.firstName("Anna").lastName("Smith").email("a@test.com")
|
||||
@@ -258,7 +261,7 @@ class NotificationServiceTest {
|
||||
@Test
|
||||
void notifyReply_skipsEmail_whenMailSenderIsAbsent() {
|
||||
NotificationService serviceWithoutMail = new NotificationService(
|
||||
notificationRepository, userService, Optional.empty(), sseEmitterRegistry);
|
||||
notificationRepository, userService, documentService, Optional.empty(), sseEmitterRegistry);
|
||||
|
||||
userA.setNotifyOnReply(true);
|
||||
DocumentComment reply = commentWithAuthor(UUID.randomUUID(), null, userC.getId(), "Clara Doe");
|
||||
@@ -274,7 +277,7 @@ class NotificationServiceTest {
|
||||
@Test
|
||||
void notifyMentions_skipsEmail_whenMailSenderIsAbsent() {
|
||||
NotificationService serviceWithoutMail = new NotificationService(
|
||||
notificationRepository, userService, Optional.empty(), sseEmitterRegistry);
|
||||
notificationRepository, userService, documentService, Optional.empty(), sseEmitterRegistry);
|
||||
|
||||
userA.setNotifyOnMention(true);
|
||||
DocumentComment comment = commentWithAuthor(UUID.randomUUID(), null, userC.getId(), "Clara Doe");
|
||||
@@ -401,6 +404,63 @@ class NotificationServiceTest {
|
||||
.findByRecipientIdAndTypeAndReadFalseOrderByCreatedAtDesc(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getNotifications_withReadFalseAndNoType_usesUnreadOnlyRepoMethod() {
|
||||
when(notificationRepository.findByRecipientIdAndReadFalseOrderByCreatedAtDesc(
|
||||
eq(userA.getId()), any()))
|
||||
.thenReturn(Page.empty());
|
||||
|
||||
notificationService.getNotifications(userA.getId(), null, false, Pageable.ofSize(10));
|
||||
|
||||
verify(notificationRepository).findByRecipientIdAndReadFalseOrderByCreatedAtDesc(
|
||||
eq(userA.getId()), any());
|
||||
verify(notificationRepository, never()).findByRecipientIdOrderByCreatedAtDesc(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getNotifications_mapsDocumentTitleFromDocumentService() {
|
||||
UUID docId = UUID.randomUUID();
|
||||
Notification notification = Notification.builder()
|
||||
.id(UUID.randomUUID())
|
||||
.recipient(userA)
|
||||
.type(NotificationType.REPLY)
|
||||
.documentId(docId)
|
||||
.referenceId(UUID.randomUUID())
|
||||
.actorName("Clara Doe")
|
||||
.build();
|
||||
when(notificationRepository.findByRecipientIdOrderByCreatedAtDesc(eq(userA.getId()), any()))
|
||||
.thenReturn(new PageImpl<>(List.of(notification)));
|
||||
when(documentService.findTitlesByIds(Set.of(docId)))
|
||||
.thenReturn(Map.of(docId, "Geburtsurkunde Opa Karl"));
|
||||
|
||||
Page<NotificationDTO> result = notificationService.getNotifications(userA.getId(), null, null, Pageable.ofSize(10));
|
||||
|
||||
assertThat(result.getContent()).hasSize(1);
|
||||
assertThat(result.getContent().getFirst().documentTitle()).isEqualTo("Geburtsurkunde Opa Karl");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getNotifications_mapsDocumentTitleAsNull_whenDocumentDoesNotExist() {
|
||||
UUID docId = UUID.randomUUID();
|
||||
Notification notification = Notification.builder()
|
||||
.id(UUID.randomUUID())
|
||||
.recipient(userA)
|
||||
.type(NotificationType.MENTION)
|
||||
.documentId(docId)
|
||||
.referenceId(UUID.randomUUID())
|
||||
.actorName("Bob Jones")
|
||||
.build();
|
||||
when(notificationRepository.findByRecipientIdOrderByCreatedAtDesc(eq(userA.getId()), any()))
|
||||
.thenReturn(new PageImpl<>(List.of(notification)));
|
||||
when(documentService.findTitlesByIds(Set.of(docId)))
|
||||
.thenReturn(Map.of());
|
||||
|
||||
Page<NotificationDTO> result = notificationService.getNotifications(userA.getId(), null, null, Pageable.ofSize(10));
|
||||
|
||||
assertThat(result.getContent()).hasSize(1);
|
||||
assertThat(result.getContent().getFirst().documentTitle()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getNotifications_withTypeAndReadTrue_fallsBackToTypeOnlyQuery() {
|
||||
// read=true with a type filter falls through to the type-only branch —
|
||||
|
||||
@@ -5,7 +5,9 @@ import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.raddatz.familienarchiv.dto.PersonSummaryDTO;
|
||||
import org.raddatz.familienarchiv.dto.PersonUpdateDTO;
|
||||
import org.raddatz.familienarchiv.exception.DomainException;
|
||||
import org.raddatz.familienarchiv.model.Person;
|
||||
import org.raddatz.familienarchiv.repository.PersonRepository;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
@@ -33,8 +35,8 @@ class PersonServiceTest {
|
||||
when(personRepository.findById(id)).thenReturn(Optional.empty());
|
||||
|
||||
assertThatThrownBy(() -> personService.getById(id))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value())
|
||||
.isInstanceOf(DomainException.class)
|
||||
.extracting(e -> ((DomainException) e).getStatus().value())
|
||||
.isEqualTo(404);
|
||||
}
|
||||
|
||||
@@ -51,32 +53,29 @@ class PersonServiceTest {
|
||||
|
||||
@Test
|
||||
void findAll_returnsAll_whenQueryIsNull() {
|
||||
List<Person> expected = List.of(Person.builder().id(UUID.randomUUID()).firstName("A").lastName("B").build());
|
||||
when(personRepository.findAllByOrderByLastNameAscFirstNameAsc()).thenReturn(expected);
|
||||
List<PersonSummaryDTO> expected = List.of();
|
||||
when(personRepository.findAllWithDocumentCount()).thenReturn(expected);
|
||||
|
||||
assertThat(personService.findAll(null)).isEqualTo(expected);
|
||||
verify(personRepository).findAllByOrderByLastNameAscFirstNameAsc();
|
||||
verify(personRepository, never()).searchByName(any());
|
||||
verify(personRepository).findAllWithDocumentCount();
|
||||
verify(personRepository, never()).searchWithDocumentCount(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findAll_returnsAll_whenQueryIsBlank() {
|
||||
List<Person> expected = List.of();
|
||||
when(personRepository.findAllByOrderByLastNameAscFirstNameAsc()).thenReturn(expected);
|
||||
|
||||
assertThat(personService.findAll(" ")).isEqualTo(expected);
|
||||
verify(personRepository).findAllByOrderByLastNameAscFirstNameAsc();
|
||||
verify(personRepository, never()).searchByName(any());
|
||||
void findAll_returnsEmpty_whenQueryIsWhitespaceOnly() {
|
||||
assertThat(personService.findAll(" ")).isEmpty();
|
||||
verify(personRepository, never()).findAllWithDocumentCount();
|
||||
verify(personRepository, never()).searchWithDocumentCount(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findAll_searchesByName_whenQueryIsNonBlank() {
|
||||
List<Person> expected = List.of(Person.builder().id(UUID.randomUUID()).firstName("Anna").lastName("Müller").build());
|
||||
when(personRepository.searchByName("Anna")).thenReturn(expected);
|
||||
List<PersonSummaryDTO> expected = List.of();
|
||||
when(personRepository.searchWithDocumentCount("Anna")).thenReturn(expected);
|
||||
|
||||
assertThat(personService.findAll("Anna")).isEqualTo(expected);
|
||||
verify(personRepository).searchByName("Anna");
|
||||
verify(personRepository, never()).findAllByOrderByLastNameAscFirstNameAsc();
|
||||
verify(personRepository).searchWithDocumentCount("Anna");
|
||||
verify(personRepository, never()).findAllWithDocumentCount();
|
||||
}
|
||||
|
||||
// ─── createPerson ─────────────────────────────────────────────────────────
|
||||
@@ -109,6 +108,37 @@ class PersonServiceTest {
|
||||
assertThat(result.getAlias()).isEqualTo("Hans Müller");
|
||||
}
|
||||
|
||||
// ─── Phase 2.1: createPerson(PersonUpdateDTO) ─────────────────────────────
|
||||
|
||||
@Test
|
||||
void createPerson_dto_persistsAllSixFields() {
|
||||
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Maria"); dto.setLastName("Raddatz"); dto.setAlias("Oma Maria");
|
||||
dto.setBirthYear(1901); dto.setDeathYear(1975); dto.setNotes("Some notes");
|
||||
|
||||
Person result = personService.createPerson(dto);
|
||||
|
||||
assertThat(result.getFirstName()).isEqualTo("Maria");
|
||||
assertThat(result.getLastName()).isEqualTo("Raddatz");
|
||||
assertThat(result.getAlias()).isEqualTo("Oma Maria");
|
||||
assertThat(result.getBirthYear()).isEqualTo(1901);
|
||||
assertThat(result.getDeathYear()).isEqualTo(1975);
|
||||
assertThat(result.getNotes()).isEqualTo("Some notes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPerson_dto_yearValidationFires_whenBirthYearNegative() {
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Anna"); dto.setLastName("Test"); dto.setBirthYear(-1);
|
||||
|
||||
assertThatThrownBy(() -> personService.createPerson(dto))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value())
|
||||
.isEqualTo(400);
|
||||
}
|
||||
|
||||
// ─── updatePerson (alias) ─────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
@@ -267,6 +297,56 @@ class PersonServiceTest {
|
||||
assertThat(result.getDeathYear()).isEqualTo(1900);
|
||||
}
|
||||
|
||||
// ─── Phase 1.3: Year range bounds (> 0) ──────────────────────────────────
|
||||
|
||||
@Test
|
||||
void updatePerson_throwsBadRequest_whenBirthYearIsZero() {
|
||||
UUID id = UUID.randomUUID();
|
||||
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setBirthYear(0);
|
||||
assertThatThrownBy(() -> personService.updatePerson(id, dto))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value())
|
||||
.isEqualTo(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatePerson_throwsBadRequest_whenBirthYearIsNegative() {
|
||||
UUID id = UUID.randomUUID();
|
||||
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setBirthYear(-5);
|
||||
assertThatThrownBy(() -> personService.updatePerson(id, dto))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value())
|
||||
.isEqualTo(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatePerson_throwsBadRequest_whenDeathYearIsZero() {
|
||||
UUID id = UUID.randomUUID();
|
||||
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setDeathYear(0);
|
||||
assertThatThrownBy(() -> personService.updatePerson(id, dto))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value())
|
||||
.isEqualTo(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatePerson_throwsBadRequest_whenDeathYearIsNegative() {
|
||||
UUID id = UUID.randomUUID();
|
||||
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setDeathYear(-10);
|
||||
assertThatThrownBy(() -> personService.updatePerson(id, dto))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value())
|
||||
.isEqualTo(400);
|
||||
}
|
||||
|
||||
// ─── findCorrespondents ──────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
@@ -321,8 +401,8 @@ class PersonServiceTest {
|
||||
when(personRepository.findById(sourceId)).thenReturn(Optional.empty());
|
||||
|
||||
assertThatThrownBy(() -> personService.mergePersons(sourceId, targetId))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value())
|
||||
.isInstanceOf(DomainException.class)
|
||||
.extracting(e -> ((DomainException) e).getStatus().value())
|
||||
.isEqualTo(404);
|
||||
}
|
||||
|
||||
@@ -335,8 +415,8 @@ class PersonServiceTest {
|
||||
when(personRepository.findById(targetId)).thenReturn(Optional.empty());
|
||||
|
||||
assertThatThrownBy(() -> personService.mergePersons(sourceId, targetId))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value())
|
||||
.isInstanceOf(DomainException.class)
|
||||
.extracting(e -> ((DomainException) e).getStatus().value())
|
||||
.isEqualTo(404);
|
||||
}
|
||||
|
||||
|
||||
1938
docs/specs/admin-redesign-concept-c.html
Normal file
1938
docs/specs/admin-redesign-concept-c.html
Normal file
File diff suppressed because it is too large
Load Diff
1252
docs/specs/conversations-narrow-column.html
Normal file
1252
docs/specs/conversations-narrow-column.html
Normal file
File diff suppressed because it is too large
Load Diff
855
docs/specs/header-nav-redesign-spec.html
Normal file
855
docs/specs/header-nav-redesign-spec.html
Normal file
@@ -0,0 +1,855 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Header / Navigation Redesign Spec · Familienarchiv</title>
|
||||
<style>
|
||||
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
|
||||
body{font-family:'Helvetica Neue',Arial,sans-serif;background:#ECEAE4;color:#1A1A1A;line-height:1.5}
|
||||
.doc{max-width:1440px;margin:0 auto;padding:48px 32px}
|
||||
|
||||
/* ── Masthead ─── */
|
||||
.mast{background:#0D2240;border-radius:10px;padding:32px 40px;margin-bottom:48px}
|
||||
.mast-top{display:flex;align-items:flex-start;justify-content:space-between;gap:24px;margin-bottom:16px}
|
||||
.mast h1{font-size:22px;font-weight:900;color:#fff;letter-spacing:-.4px;margin-bottom:6px}
|
||||
.mast p{font-size:12px;color:rgba(255,255,255,.5);max-width:620px;line-height:1.7}
|
||||
.mast-badge{font-size:9px;font-weight:800;padding:3px 9px;border-radius:20px;text-transform:uppercase;letter-spacing:.8px;white-space:nowrap;flex-shrink:0;margin-top:4px}
|
||||
.mb-draft{background:#FCD34D;color:#78350F}
|
||||
.decisions{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-top:20px;border-top:1px solid rgba(255,255,255,.1);padding-top:16px}
|
||||
.dec{background:rgba(255,255,255,.06);border-radius:6px;padding:10px 12px}
|
||||
.dec-label{font-size:7px;font-weight:800;text-transform:uppercase;letter-spacing:.8px;color:rgba(255,255,255,.35);margin-bottom:5px}
|
||||
.dec-value{font-size:9.5px;font-weight:700;color:#fff;line-height:1.5}
|
||||
.dec-value s{color:rgba(255,255,255,.3);font-weight:400}
|
||||
|
||||
/* ── Section headings ─── */
|
||||
.sec{margin-bottom:64px}
|
||||
.sec+.sec{border-top:2px dashed #C8C4BE;padding-top:56px}
|
||||
.sec-h{font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:1.2px;color:#888;margin-bottom:20px;display:flex;align-items:center;gap:10px}
|
||||
.sec-h::after{content:'';flex:1;height:1px;background:#D8D4CE}
|
||||
.sec-num{background:#0D2240;color:#fff;font-size:9px;font-weight:900;padding:2px 7px;border-radius:10px}
|
||||
|
||||
/* ── Screen grid ─── */
|
||||
.sg{display:grid;gap:20px;align-items:start}
|
||||
.sg-3{grid-template-columns:1fr 1fr 1fr}
|
||||
.sg-2{grid-template-columns:1fr 1fr}
|
||||
.sg-2a{grid-template-columns:1.3fr 1fr}
|
||||
.sg-mob{grid-template-columns:1fr 220px}
|
||||
.sb{display:flex;flex-direction:column}
|
||||
.sl{font-size:9px;font-weight:800;color:#888;text-transform:uppercase;letter-spacing:1.5px;margin-bottom:6px;display:flex;align-items:center;gap:6px}
|
||||
.sz{background:#E8E4DF;color:#666;padding:1px 5px;border-radius:3px;font-size:8px}
|
||||
.state{padding:1px 6px;border-radius:3px;font-size:8px;font-weight:700}
|
||||
.st-bad{background:#FEE2E2;color:#991B1B}
|
||||
.st-good{background:#DCFCE7;color:#166534}
|
||||
.st-warn{background:#FEF3C7;color:#92400E}
|
||||
.sc{font-size:8.5px;color:#888;margin-top:6px;font-style:italic;line-height:1.5}
|
||||
|
||||
/* ── Annotation callouts ─── */
|
||||
.ann{display:inline-block;font-size:7.5px;font-weight:700;color:#C2410C;background:#FFF7ED;border:1px solid #FDBA74;border-radius:3px;padding:1px 5px;white-space:nowrap}
|
||||
.ann-block{background:#FFF7ED;border:1px solid #FDBA74;border-radius:5px;padding:8px 10px;font-size:10px;color:#7C2D12;line-height:1.5;margin-top:10px}
|
||||
.ann-block strong{font-weight:800}
|
||||
.ann-block ul{padding-left:14px;display:flex;flex-direction:column;gap:3px;margin-top:5px}
|
||||
.ann-block ol{padding-left:14px;display:flex;flex-direction:column;gap:3px;margin-top:5px}
|
||||
|
||||
/* ── Wireframe Chrome ─── */
|
||||
.wf{background:#fff;border:2px solid #B8B4AE;border-radius:10px;overflow:hidden;box-shadow:0 4px 18px rgba(0,0,0,.08)}
|
||||
.wf-bar{height:24px;background:#E8E4DF;border-bottom:1px solid #C8C4BE;display:flex;align-items:center;padding:0 9px;gap:4px}
|
||||
.dot{width:7px;height:7px;border-radius:50%;background:#C8C4BE}
|
||||
.dot.r{background:#F87171}.dot.y{background:#FCD34D}.dot.g{background:#4ADE80}
|
||||
.urlbar{flex:1;height:11px;background:#D8D4CE;border-radius:3px;margin-left:6px;display:flex;align-items:center;padding:0 5px}
|
||||
.urlbar span{font-size:7.5px;color:#888;font-family:monospace}
|
||||
|
||||
/* ── Current header (white/broken) ─── */
|
||||
.H-OLD{height:44px;background:#ffffff;border-bottom:1.5px solid #E5E7EB;display:flex;align-items:center;padding:0 16px;gap:14px;position:relative}
|
||||
.H-OLD-LOGO{font-size:9px;font-weight:900;color:#012851;letter-spacing:1.2px;font-family:'Arial Black',sans-serif}
|
||||
.H-OLD-NAV{display:flex;gap:10px;align-items:center;margin-left:8px}
|
||||
.H-OLD-LINK{font-size:7.5px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#012851;padding:3px 7px;border-radius:4px}
|
||||
.H-OLD-LINK.act{background:rgba(180,185,255,0.15);color:#012851}
|
||||
.H-OLD-R{margin-left:auto;display:flex;gap:7px;align-items:center}
|
||||
.H-OLD-ICO{width:22px;height:22px;background:#F3F4F6;border-radius:4px;border:1px solid #E5E7EB}
|
||||
.H-OLD-AV{width:22px;height:22px;background:#012851;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:6px;font-weight:900;color:#fff}
|
||||
|
||||
/* ── NEW header atoms ─── */
|
||||
.STRIP{height:4px;background:#B4B9FF} /* brand-purple accent strip */
|
||||
.N{height:42px;background:#012851;display:flex;align-items:center;padding:0 16px;gap:14px;flex-shrink:0}
|
||||
.logo{font-size:9px;font-weight:900;color:#fff;letter-spacing:1.2px;font-family:'Arial Black',sans-serif}
|
||||
.nl{font-size:7.5px;color:rgba(255,255,255,.55);font-weight:700;text-transform:uppercase;letter-spacing:.5px;padding-bottom:2px}
|
||||
.nl:hover{color:rgba(255,255,255,.85)}
|
||||
.nl.on{color:#fff;border-bottom:2px solid #A1DCD8;padding-bottom:2px}
|
||||
.nr{margin-left:auto;display:flex;gap:8px;align-items:center}
|
||||
.nico{width:20px;height:20px;background:rgba(255,255,255,.1);border-radius:4px}
|
||||
.nico-av{width:22px;height:22px;background:#A1DCD8;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:6px;font-weight:900;color:#012851}
|
||||
.nico-lbl{font-size:7px;color:rgba(255,255,255,.6);font-weight:700;text-transform:uppercase}
|
||||
|
||||
/* ── Page body placeholder ─── */
|
||||
.MAIN{padding:14px 18px;display:flex;flex-direction:column;gap:10px;background:#ECEAE4;min-height:80px}
|
||||
.PH{height:7px;background:#D8D4CE;border-radius:2px;margin-bottom:4px}
|
||||
.w80{width:80%}.w70{width:70%}.w60{width:60%}.w50{width:50%}.w40{width:40%}.w30{width:30%}
|
||||
|
||||
/* ── Mobile chrome ─── */
|
||||
.WF-M{background:#fff;border:2px solid #B8B4AE;border-radius:16px;overflow:hidden;box-shadow:0 4px 18px rgba(0,0,0,.08);width:220px}
|
||||
.WF-M-STATUS{height:18px;background:#012851;display:flex;align-items:center;justify-content:space-between;padding:0 10px}
|
||||
.WF-M-TIME{font-size:7px;color:#fff;font-weight:700}
|
||||
.WF-M-ICONS{display:flex;gap:3px}
|
||||
.WF-M-ICON{width:6px;height:6px;background:rgba(255,255,255,.5);border-radius:1px}
|
||||
.N-M{height:42px;display:flex;align-items:center;padding:0 12px;justify-content:space-between}
|
||||
.HAMBURGER{display:flex;flex-direction:column;gap:3px;justify-content:center;width:18px}
|
||||
.HAMBURGER-LINE{height:1.5px;background:rgba(255,255,255,.85);border-radius:1px}
|
||||
|
||||
/* Mobile old (white bg) */
|
||||
.N-M-OLD{height:44px;background:#ffffff;border-bottom:1.5px solid #E5E7EB;display:flex;align-items:center;padding:0 12px;justify-content:space-between}
|
||||
.H-OLD-M-LOGO{font-size:9px;font-weight:900;color:#012851;letter-spacing:1.2px}
|
||||
|
||||
/* Nav drawer */
|
||||
.DRAWER{background:#fff;border-top:1px solid #E5E7EB;padding:10px 0}
|
||||
.DRAWER-LINK{display:flex;align-items:center;padding:8px 14px;font-size:8px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#012851;border-left:3px solid transparent}
|
||||
.DRAWER-LINK.on{border-left-color:#A1DCD8;background:#F0EFE9;color:#012851}
|
||||
.DRAWER-LINK.off{color:rgba(1,40,81,.55)}
|
||||
.DRAWER-DIV{height:1px;background:#E5E7EB;margin:6px 14px}
|
||||
.DRAWER-LANG{display:flex;align-items:center;gap:8px;padding:6px 14px}
|
||||
.DRAWER-LANG-BTN{font-size:7.5px;font-weight:700;color:#012851;padding:2px 7px;border-radius:3px;border:1.5px solid #D1D5DB}
|
||||
.DRAWER-LANG-BTN.on{border-color:#012851;background:#012851;color:#fff}
|
||||
|
||||
/* ── Nav state grid ─── */
|
||||
.NSG{display:grid;grid-template-columns:repeat(4,1fr);gap:12px}
|
||||
.NS{display:flex;flex-direction:column;gap:6px}
|
||||
.NS-LABEL{font-size:8px;font-weight:800;text-transform:uppercase;letter-spacing:.8px;color:#888}
|
||||
.NS-DEMO{height:40px;background:#012851;display:flex;align-items:center;padding:0 14px;border-radius:6px}
|
||||
.NS-LINK{font-size:8px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;padding-bottom:2px}
|
||||
.NS-INACTIVE{color:rgba(255,255,255,.55)}
|
||||
.NS-HOVER{color:rgba(255,255,255,.85)}
|
||||
.NS-ACTIVE{color:#fff;border-bottom:2px solid #A1DCD8}
|
||||
.NS-FOCUS{color:#fff;outline:2px solid #A1DCD8;outline-offset:3px;border-radius:2px;padding:1px 3px}
|
||||
|
||||
/* ── Contrast badge ─── */
|
||||
.contrast-badge{display:inline-flex;align-items:center;gap:4px;font-size:8px;font-weight:700;padding:2px 7px;border-radius:20px}
|
||||
.cr-fail{background:#FEE2E2;color:#991B1B}
|
||||
.cr-pass{background:#DCFCE7;color:#166534}
|
||||
|
||||
/* ── Login page ─── */
|
||||
.LOGIN-BG{background:#F0EFE9;min-height:120px;display:flex;flex-direction:column;align-items:center;padding-bottom:14px}
|
||||
.LOGIN-HEADER{width:100%;height:4px;background:#B4B9FF}
|
||||
.LOGIN-NAV{width:100%;height:42px;background:#012851;display:flex;align-items:center;justify-content:space-between;padding:0 16px}
|
||||
.LOGIN-CARD{background:#fff;border:1.5px solid #D8D4CE;border-radius:8px;padding:14px 18px;width:200px;margin-top:14px}
|
||||
.LOGIN-CARD-TITLE{font-size:10px;font-weight:900;color:#012851;margin-bottom:10px;letter-spacing:-.2px}
|
||||
.LOGIN-FIELD{margin-bottom:7px}
|
||||
.LOGIN-FIELD-L{font-size:7px;font-weight:800;text-transform:uppercase;letter-spacing:.5px;color:#888;margin-bottom:3px}
|
||||
.LOGIN-FIELD-I{height:26px;border:1.5px solid #D1D5DB;border-radius:3px;background:#fff;width:100%}
|
||||
.LOGIN-BTN{height:28px;background:#012851;border-radius:3px;width:100%;display:flex;align-items:center;justify-content:center;font-size:8px;font-weight:800;color:#fff;text-transform:uppercase;letter-spacing:.5px;margin-top:10px}
|
||||
|
||||
/* ── Changelog / decision list ─── */
|
||||
.CHANGES{background:#fff;border:1.5px solid #E0DDD6;border-radius:8px;padding:20px 24px;margin-bottom:40px}
|
||||
.CHANGES h2{font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:.8px;color:#888;margin-bottom:14px;padding-bottom:10px;border-bottom:1px solid #E8E4DF}
|
||||
.CHANGES-GRID{display:grid;grid-template-columns:1fr 1fr;gap:16px}
|
||||
.C-COL h3{font-size:10px;font-weight:800;color:#444;margin-bottom:8px}
|
||||
.C-COL ul{list-style:none;display:flex;flex-direction:column;gap:5px}
|
||||
.C-COL ul li{font-size:11px;color:#555;padding-left:16px;position:relative;line-height:1.5}
|
||||
.C-COL.new li::before{content:'✦';position:absolute;left:0;color:#012851;font-size:8px}
|
||||
.C-COL.remove li::before{content:'✗';position:absolute;left:0;color:#DC2626}
|
||||
.C-COL.keep li::before{content:'→';position:absolute;left:0;color:#888}
|
||||
|
||||
/* ── Impl notes ─── */
|
||||
.IMPL{background:#0D2240;border-radius:8px;padding:20px 24px;margin-top:48px}
|
||||
.IMPL h2{font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:.8px;color:rgba(255,255,255,.4);margin-bottom:16px;padding-bottom:10px;border-bottom:1px solid rgba(255,255,255,.08)}
|
||||
.IMPL-GRID{display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px}
|
||||
.IMPL-COL h3{font-size:9.5px;font-weight:800;color:rgba(255,255,255,.6);text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px}
|
||||
.IMPL-COL ul{list-style:none;display:flex;flex-direction:column;gap:5px}
|
||||
.IMPL-COL ul li{font-size:10.5px;color:rgba(255,255,255,.75);padding-left:14px;position:relative;line-height:1.5}
|
||||
.IMPL-COL ul li::before{content:'›';position:absolute;left:0;color:rgba(255,255,255,.3)}
|
||||
.IMPL-COL code{font-family:monospace;font-size:9.5px;background:rgba(255,255,255,.08);padding:1px 4px;border-radius:3px;color:#A1DCD8}
|
||||
|
||||
/* ── Dark mode simulation ─── */
|
||||
.DK .N{background:#012851} /* same! brand constant */
|
||||
.DK .nl{color:rgba(255,255,255,.55)}
|
||||
.DK .nl.on{color:#fff}
|
||||
.DK-MAIN{background:#1A1A1A;padding:14px 18px;min-height:60px}
|
||||
.DK-PH{height:7px;background:#2A2A2A;border-radius:2px;margin-bottom:4px}
|
||||
|
||||
/* ── Measurement annotation ─── */
|
||||
.MEA{display:flex;align-items:center;gap:4px;font-size:7.5px;font-weight:700;color:#6B7280;margin-top:8px}
|
||||
.MEA-LINE{flex:1;height:1px;border-top:1px dashed #C8C4BE}
|
||||
.MEA-VAL{background:#E8E4DF;padding:1px 6px;border-radius:3px;white-space:nowrap}
|
||||
.token{font-family:monospace;font-size:8.5px;background:#F0EFE9;border:1px solid #D8D4CE;padding:1px 5px;border-radius:3px;color:#012851}
|
||||
|
||||
/* ── Color swatch ─── */
|
||||
.SW{display:flex;flex-direction:column;align-items:flex-start;gap:3px}
|
||||
.SW-BOX{width:36px;height:20px;border-radius:3px;border:1px solid rgba(0,0,0,.1)}
|
||||
.SW-NAME{font-size:7.5px;font-weight:700;color:#444}
|
||||
.SW-HEX{font-size:7px;color:#888;font-family:monospace}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="doc">
|
||||
|
||||
|
||||
<!-- ══════════════════════════════════
|
||||
MASTHEAD
|
||||
══════════════════════════════════ -->
|
||||
<div class="mast">
|
||||
<div class="mast-top">
|
||||
<div>
|
||||
<h1>Header / Navigation Redesign</h1>
|
||||
<p>Full header redesign: brand-navy bar, 4px purple accent strip, always-visible logo on mobile, high-contrast nav states, dark-mode as brand constant, and integrated login header. Replaces the current white <code style="font-family:monospace;font-size:10px;background:rgba(255,255,255,.08);padding:1px 4px;border-radius:3px;color:#A1DCD8">bg-surface</code> header that leaks the semantic surface color into what should be a brand-constant element.</p>
|
||||
</div>
|
||||
<span class="mast-badge mb-draft">Draft · 2026-03-30</span>
|
||||
</div>
|
||||
<div style="font-size:8.5px;color:rgba(255,255,255,.3);margin-bottom:12px">Leonie Voss · Senior UX Designer</div>
|
||||
<div class="decisions">
|
||||
<div class="dec">
|
||||
<div class="dec-label">Header background</div>
|
||||
<div class="dec-value"><s>bg-surface (#fff)</s><br>→ brand-navy #012851</div>
|
||||
</div>
|
||||
<div class="dec">
|
||||
<div class="dec-label">Top accent strip</div>
|
||||
<div class="dec-value"><s>None</s><br>→ 4px · brand-purple #B4B9FF</div>
|
||||
</div>
|
||||
<div class="dec">
|
||||
<div class="dec-label">Active nav state</div>
|
||||
<div class="dec-value"><s>rgba purple pill (~1.08:1)</s><br>→ white + mint underline</div>
|
||||
</div>
|
||||
<div class="dec">
|
||||
<div class="dec-label">Mobile logo</div>
|
||||
<div class="dec-value"><s>Hidden</s><br>→ Always visible, left side</div>
|
||||
</div>
|
||||
<div class="dec">
|
||||
<div class="dec-label">Dark mode header</div>
|
||||
<div class="dec-value"><s>Flips to #1a1a1a</s><br>→ Stays brand-navy (constant)</div>
|
||||
</div>
|
||||
<div class="dec">
|
||||
<div class="dec-label">Login page header</div>
|
||||
<div class="dec-value"><s>Hidden entirely</s><br>→ Brand header, logo-only</div>
|
||||
</div>
|
||||
<div class="dec">
|
||||
<div class="dec-label">Language switcher (login)</div>
|
||||
<div class="dec-value"><s>Floating, no context</s><br>→ Integrated in login header right</div>
|
||||
</div>
|
||||
<div class="dec">
|
||||
<div class="dec-label">Total header height</div>
|
||||
<div class="dec-value">4px strip + 64px bar<br>= 68px total</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ══════════════════════════════════
|
||||
CHANGES SUMMARY
|
||||
══════════════════════════════════ -->
|
||||
<div class="CHANGES">
|
||||
<h2>What changes vs. current implementation</h2>
|
||||
<div class="CHANGES-GRID">
|
||||
<div class="C-COL new">
|
||||
<h3>New / changed</h3>
|
||||
<ul>
|
||||
<li>Header <code style="font-size:9px;background:#F0EFE9;padding:1px 4px;border-radius:2px">bg-surface</code> → fixed <code style="font-size:9px;background:#F0EFE9;padding:1px 4px;border-radius:2px">bg-brand-navy</code> (#012851) — not theme-aware</li>
|
||||
<li>4px accent strip above header: <code style="font-size:9px;background:#F0EFE9;padding:1px 4px;border-radius:2px">background: #B4B9FF</code></li>
|
||||
<li>Nav link colors on navy: inactive 55% white, hover 85% white, active 100% white</li>
|
||||
<li>Active indicator: 2px bottom border in brand-mint (#A1DCD8) instead of rgba purple pill</li>
|
||||
<li>Mobile: logo always visible left; hamburger icon white (was hidden or missing)</li>
|
||||
<li>User avatar: mint background (#A1DCD8) with navy text (#012851)</li>
|
||||
<li>Dark mode: <code style="font-size:9px;background:#F0EFE9;padding:1px 4px;border-radius:2px">dark:bg-surface</code> override removed from header — stays navy</li>
|
||||
<li>Login page: <code style="font-size:9px;background:#F0EFE9;padding:1px 4px;border-radius:2px">isAuthPage</code> guard changed — shows logo-only header, not <code style="font-size:9px;background:#F0EFE9;padding:1px 4px;border-radius:2px">null</code></li>
|
||||
<li>Language switcher on login: moved into header right slot</li>
|
||||
<li>Mobile drawer: opens below navy header, white background, navy text links, mint active indicator</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="C-COL keep">
|
||||
<h3>Kept unchanged</h3>
|
||||
<ul>
|
||||
<li><code style="font-size:9px;background:#F0EFE9;padding:1px 4px;border-radius:2px">AppNav</code> component structure — only CSS changes</li>
|
||||
<li>Sticky header behavior (<code style="font-size:9px;background:#F0EFE9;padding:1px 4px;border-radius:2px">sticky top-0 z-50</code>)</li>
|
||||
<li>Max-width container and horizontal padding</li>
|
||||
<li>NotificationBell, ThemeToggle, LanguageSwitcher components — only icon color changes</li>
|
||||
<li>UserMenu component — only avatar color changes</li>
|
||||
<li>Mobile drawer open/close logic</li>
|
||||
<li>Admin nav link conditional visibility</li>
|
||||
<li><code style="font-size:9px;background:#F0EFE9;padding:1px 4px;border-radius:2px">isAuthPage</code> derived value — still used, just different output</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ══════════════════════════════════
|
||||
SECTION 1 — CURRENT STATE
|
||||
══════════════════════════════════ -->
|
||||
<div class="sec">
|
||||
<div class="sec-h"><span class="sec-num">1</span> Current state — problems annotated</div>
|
||||
|
||||
<div class="sg sg-2a">
|
||||
<div class="sb">
|
||||
<div class="sl">Desktop <span class="sz">≥768px</span> <span class="state st-bad">6 issues</span></div>
|
||||
<div class="wf">
|
||||
<div class="wf-bar"><div class="dot r"></div><div class="dot y"></div><div class="dot g"></div><div class="urlbar"><span>/dokumente</span></div></div>
|
||||
<!-- Current broken header -->
|
||||
<div class="H-OLD">
|
||||
<!-- issue 1: white bg, no strip -->
|
||||
<div style="position:absolute;top:0;left:0;right:0;height:2px;background:#FDBA74;opacity:.3"></div>
|
||||
<span class="H-OLD-LOGO">FAMILIENARCHIV</span>
|
||||
<div class="H-OLD-NAV">
|
||||
<span class="H-OLD-LINK act">Dokumente</span>
|
||||
<span class="H-OLD-LINK">Personen</span>
|
||||
<span class="H-OLD-LINK">Korrespondenz</span>
|
||||
</div>
|
||||
<div class="H-OLD-R">
|
||||
<span style="font-size:7px;color:#6B7280;font-weight:700">DE</span>
|
||||
<div class="H-OLD-ICO"></div>
|
||||
<div class="H-OLD-ICO"></div>
|
||||
<div class="H-OLD-AV">LV</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="MAIN"><div class="PH w80"></div><div class="PH w60"></div><div class="PH w70"></div></div>
|
||||
</div>
|
||||
<div class="ann-block">
|
||||
<strong>Issues — desktop</strong>
|
||||
<ol>
|
||||
<li><strong>①</strong> Background is <code style="font-size:9px;background:#FFF0E8;padding:1px 3px;border-radius:2px">bg-surface</code> (white) — not brand. Every other archival app in this family uses a dark branded header.</li>
|
||||
<li><strong>②</strong> No 4px accent strip at top — missing the canonical brand-purple cap.</li>
|
||||
<li><strong>③</strong> Active link "Dokumente" uses <code style="font-size:9px;background:#FFF0E8;padding:1px 3px;border-radius:2px">rgba(180,185,255,0.15)</code> on white = contrast ~1.08:1. Completely invisible. WCAG AA minimum is 3:1 for UI components.</li>
|
||||
<li><strong>④</strong> Logo is navy-on-white — works in light mode but will disappear in dark mode if header ever inherits <code style="font-size:9px;background:#FFF0E8;padding:1px 3px;border-radius:2px">#1a1a1a</code>.</li>
|
||||
<li><strong>⑤</strong> Dark mode: header flips to near-black (#1a1a1a) — breaks brand consistency. Header should be a brand constant, not a semantic surface.</li>
|
||||
<li><strong>⑥</strong> User avatar: dark navy circle blends with any dark-mode context and provides no semantic meaning via color.</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sb">
|
||||
<div class="sl">Mobile <span class="sz">375px</span> <span class="state st-bad">logo missing</span></div>
|
||||
<div style="display:flex;justify-content:center">
|
||||
<div class="WF-M">
|
||||
<div class="WF-M-STATUS"><span class="WF-M-TIME">09:41</span><div class="WF-M-ICONS"><div class="WF-M-ICON"></div><div class="WF-M-ICON"></div><div class="WF-M-ICON"></div></div></div>
|
||||
<div class="N-M-OLD">
|
||||
<!-- No logo! Just hamburger. -->
|
||||
<div style="width:18px;display:flex;flex-direction:column;gap:3px">
|
||||
<div style="height:1.5px;background:#012851;border-radius:1px"></div>
|
||||
<div style="height:1.5px;background:#012851;border-radius:1px"></div>
|
||||
<div style="height:1.5px;background:#012851;border-radius:1px"></div>
|
||||
</div>
|
||||
<div class="H-OLD-ICO" style="width:20px;height:20px"></div>
|
||||
<div class="H-OLD-AV">LV</div>
|
||||
</div>
|
||||
<div class="MAIN" style="padding:10px 12px;min-height:60px">
|
||||
<div class="PH w80"></div><div class="PH w60"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ann-block" style="margin-top:8px">
|
||||
<strong>Mobile issues</strong>
|
||||
<ul>
|
||||
<li>Logo hidden on mobile — brand identity completely lost</li>
|
||||
<li>Hamburger icon is dark on white — fine in light mode, breaks in dark</li>
|
||||
<li>Header still white — same surface-color problem as desktop</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ══════════════════════════════════
|
||||
SECTION 2 — PROPOSED DESKTOP
|
||||
══════════════════════════════════ -->
|
||||
<div class="sec">
|
||||
<div class="sec-h"><span class="sec-num">2</span> Proposed redesign — Desktop</div>
|
||||
|
||||
<div class="sg sg-2" style="margin-bottom:24px">
|
||||
|
||||
<!-- Light mode -->
|
||||
<div class="sb">
|
||||
<div class="sl">Light mode <span class="sz">≥768px</span> <span class="state st-good">Proposed</span></div>
|
||||
<div class="wf">
|
||||
<div class="wf-bar"><div class="dot r"></div><div class="dot y"></div><div class="dot g"></div><div class="urlbar"><span>/korrespondenz</span></div></div>
|
||||
<div class="STRIP"></div>
|
||||
<div class="N">
|
||||
<span class="logo">FAMILIENARCHIV</span>
|
||||
<div style="width:1px;height:16px;background:rgba(255,255,255,.15);margin:0 2px"></div>
|
||||
<span class="nl">Dokumente</span>
|
||||
<span class="nl">Personen</span>
|
||||
<span class="nl on">Korrespondenz</span>
|
||||
<div class="nr">
|
||||
<span class="nico-lbl">DE</span>
|
||||
<div class="nico" style="background:rgba(255,255,255,.12)"></div><!-- theme toggle -->
|
||||
<div class="nico" style="background:rgba(255,255,255,.12)"></div><!-- bell -->
|
||||
<div class="nico-av">LV</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="MAIN"><div class="PH w80"></div><div class="PH w60"></div><div class="PH w70"></div></div>
|
||||
</div>
|
||||
<div class="MEA">
|
||||
<div class="MEA-LINE"></div>
|
||||
<span class="MEA-VAL">4px accent strip · background: #B4B9FF</span>
|
||||
<div class="MEA-LINE"></div>
|
||||
</div>
|
||||
<div class="MEA">
|
||||
<div class="MEA-LINE"></div>
|
||||
<span class="MEA-VAL">64px nav bar · background: #012851</span>
|
||||
<div class="MEA-LINE"></div>
|
||||
</div>
|
||||
<div class="MEA">
|
||||
<div class="MEA-LINE"></div>
|
||||
<span class="MEA-VAL">Total: 68px</span>
|
||||
<div class="MEA-LINE"></div>
|
||||
</div>
|
||||
<div class="sc">Active link: "Korrespondenz" — white text + 2px bottom border in #A1DCD8. Divider between logo and nav: rgba(255,255,255,0.15). Avatar: mint bg + navy text.</div>
|
||||
</div>
|
||||
|
||||
<!-- Dark mode -->
|
||||
<div class="sb">
|
||||
<div class="sl">Dark mode <span class="sz">≥768px</span> <span class="state st-good">Same navy — brand constant</span></div>
|
||||
<div class="wf" style="border-color:#444">
|
||||
<div class="wf-bar" style="background:#333;border-color:#444"><div class="dot r"></div><div class="dot y"></div><div class="dot g"></div><div class="urlbar" style="background:#444"><span style="color:#aaa">/korrespondenz</span></div></div>
|
||||
<div class="STRIP"></div><!-- strip is identical — not theme-aware -->
|
||||
<div class="N"><!-- N stays the same #012851 in dark mode too -->
|
||||
<span class="logo">FAMILIENARCHIV</span>
|
||||
<div style="width:1px;height:16px;background:rgba(255,255,255,.15);margin:0 2px"></div>
|
||||
<span class="nl">Dokumente</span>
|
||||
<span class="nl">Personen</span>
|
||||
<span class="nl on">Korrespondenz</span>
|
||||
<div class="nr">
|
||||
<span class="nico-lbl">DE</span>
|
||||
<div class="nico"></div>
|
||||
<div class="nico"></div>
|
||||
<div class="nico-av">LV</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="DK-MAIN"><div class="DK-PH w80"></div><div class="DK-PH w60"></div><div class="DK-PH w70"></div></div>
|
||||
</div>
|
||||
<div class="ann-block" style="background:#EFF6FF;border-color:#BFDBFE;color:#1E40AF;margin-top:8px">
|
||||
<strong>Dark mode rule:</strong> The header is a brand element, not a semantic surface. It does NOT respond to the <code style="font-size:9px;background:rgba(30,64,175,.1);padding:1px 3px;border-radius:2px">dark:</code> variant. Page content behind it switches; the header stays #012851.
|
||||
<ul style="margin-top:4px">
|
||||
<li>Remove <code style="font-size:9px;background:rgba(30,64,175,.1);padding:1px 3px;border-radius:2px">dark:bg-surface</code> from header element</li>
|
||||
<li>Apply <code style="font-size:9px;background:rgba(30,64,175,.1);padding:1px 3px;border-radius:2px">bg-brand-navy</code> as a non-dark-variant class</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Element key -->
|
||||
<div style="background:#fff;border:1.5px solid #E0DDD6;border-radius:8px;padding:16px 20px;margin-top:8px">
|
||||
<div style="font-size:9px;font-weight:800;text-transform:uppercase;letter-spacing:.8px;color:#888;margin-bottom:12px">Element color tokens</div>
|
||||
<div style="display:grid;grid-template-columns:repeat(6,1fr);gap:16px">
|
||||
<div class="SW">
|
||||
<div class="SW-BOX" style="background:#012851"></div>
|
||||
<div class="SW-NAME">brand-navy</div>
|
||||
<div class="SW-HEX">#012851</div>
|
||||
<div style="font-size:7px;color:#888;margin-top:2px">Header bg</div>
|
||||
</div>
|
||||
<div class="SW">
|
||||
<div class="SW-BOX" style="background:#B4B9FF"></div>
|
||||
<div class="SW-NAME">brand-purple</div>
|
||||
<div class="SW-HEX">#B4B9FF</div>
|
||||
<div style="font-size:7px;color:#888;margin-top:2px">Accent strip</div>
|
||||
</div>
|
||||
<div class="SW">
|
||||
<div class="SW-BOX" style="background:#A1DCD8"></div>
|
||||
<div class="SW-NAME">brand-mint</div>
|
||||
<div class="SW-HEX">#A1DCD8</div>
|
||||
<div style="font-size:7px;color:#888;margin-top:2px">Active underline · avatar bg</div>
|
||||
</div>
|
||||
<div class="SW">
|
||||
<div class="SW-BOX" style="background:#ffffff;border-color:#D0D0D0"></div>
|
||||
<div class="SW-NAME">white</div>
|
||||
<div class="SW-HEX">#ffffff</div>
|
||||
<div style="font-size:7px;color:#888;margin-top:2px">Active link text · logo</div>
|
||||
</div>
|
||||
<div class="SW">
|
||||
<div class="SW-BOX" style="background:rgba(255,255,255,0.55)"></div>
|
||||
<div class="SW-NAME">white/55</div>
|
||||
<div class="SW-HEX">rgba(255,255,255,.55)</div>
|
||||
<div style="font-size:7px;color:#888;margin-top:2px">Inactive nav links</div>
|
||||
</div>
|
||||
<div class="SW">
|
||||
<div class="SW-BOX" style="background:rgba(255,255,255,0.85)"></div>
|
||||
<div class="SW-NAME">white/85</div>
|
||||
<div class="SW-HEX">rgba(255,255,255,.85)</div>
|
||||
<div style="font-size:7px;color:#888;margin-top:2px">Hover nav links</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ══════════════════════════════════
|
||||
SECTION 3 — NAV STATES
|
||||
══════════════════════════════════ -->
|
||||
<div class="sec">
|
||||
<div class="sec-h"><span class="sec-num">3</span> Nav link states</div>
|
||||
|
||||
<div class="NSG" style="margin-bottom:20px">
|
||||
|
||||
<!-- Inactive -->
|
||||
<div class="NS">
|
||||
<div class="NS-LABEL">Inactive</div>
|
||||
<div class="NS-DEMO">
|
||||
<span class="NS-LINK NS-INACTIVE">Personen</span>
|
||||
</div>
|
||||
<div style="margin-top:6px;font-size:9px;color:#555;line-height:1.6">
|
||||
<div><span class="token">color: rgba(255,255,255,.55)</span></div>
|
||||
<div style="margin-top:4px;display:flex;align-items:center;gap:6px">
|
||||
<span class="contrast-badge cr-pass">4.9:1 ✓ AA</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sc">Intentionally muted — communicates "not here yet" without removing affordance.</div>
|
||||
</div>
|
||||
|
||||
<!-- Hover -->
|
||||
<div class="NS">
|
||||
<div class="NS-LABEL">Hover</div>
|
||||
<div class="NS-DEMO">
|
||||
<span class="NS-LINK NS-HOVER">Personen</span>
|
||||
</div>
|
||||
<div style="margin-top:6px;font-size:9px;color:#555;line-height:1.6">
|
||||
<div><span class="token">color: rgba(255,255,255,.85)</span></div>
|
||||
<div style="margin-top:4px;display:flex;align-items:center;gap:6px">
|
||||
<span class="contrast-badge cr-pass">7.8:1 ✓ AA</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sc">Smooth brightness step on hover. Transition: <code style="font-size:9px">color 150ms ease</code>.</div>
|
||||
</div>
|
||||
|
||||
<!-- Active -->
|
||||
<div class="NS">
|
||||
<div class="NS-LABEL">Active (current page)</div>
|
||||
<div class="NS-DEMO">
|
||||
<span class="NS-LINK NS-ACTIVE">Korrespondenz</span>
|
||||
</div>
|
||||
<div style="margin-top:6px;font-size:9px;color:#555;line-height:1.6">
|
||||
<div><span class="token">color: #ffffff</span></div>
|
||||
<div><span class="token">border-bottom: 2px solid #A1DCD8</span></div>
|
||||
<div style="margin-top:4px;display:flex;align-items:center;gap:6px">
|
||||
<span class="contrast-badge cr-pass">21:1 ✓ AAA</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sc">Mint underline is the active indicator — not a background pill. Clear, low-weight, distinct from hover.</div>
|
||||
</div>
|
||||
|
||||
<!-- Focus -->
|
||||
<div class="NS">
|
||||
<div class="NS-LABEL">Focus (keyboard)</div>
|
||||
<div class="NS-DEMO">
|
||||
<span class="NS-LINK NS-FOCUS">Personen</span>
|
||||
</div>
|
||||
<div style="margin-top:6px;font-size:9px;color:#555;line-height:1.6">
|
||||
<div><span class="token">outline: 2px solid #A1DCD8</span></div>
|
||||
<div><span class="token">outline-offset: 3px</span></div>
|
||||
<div><span class="token">border-radius: 2px</span></div>
|
||||
<div style="margin-top:4px;display:flex;align-items:center;gap:6px">
|
||||
<span class="contrast-badge cr-pass">3.4:1 ✓ AA</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sc">Mint outline on navy — meets WCAG 3:1 focus indicator requirement. Never suppress outline.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Before/After contrast comparison -->
|
||||
<div style="background:#fff;border:1.5px solid #E0DDD6;border-radius:8px;padding:16px 20px">
|
||||
<div style="font-size:9px;font-weight:800;text-transform:uppercase;letter-spacing:.8px;color:#888;margin-bottom:12px">Active state contrast — before vs. after</div>
|
||||
<div class="sg sg-2">
|
||||
<div>
|
||||
<div class="sl" style="margin-bottom:8px">Before <span class="state st-bad">Fails WCAG</span></div>
|
||||
<div style="background:#ffffff;border-radius:5px;padding:10px 14px;border:1.5px solid #E5E7EB;display:inline-flex;align-items:center;gap:0">
|
||||
<span style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#012851;background:rgba(180,185,255,0.15);padding:4px 10px;border-radius:4px">Dokumente</span>
|
||||
</div>
|
||||
<div style="margin-top:8px;font-size:9px;color:#555">
|
||||
Navy text (#012851) on rgba(180,185,255,0.15) on white.<br>
|
||||
Effective background: approx. #F4F4FF.<br>
|
||||
<span class="contrast-badge cr-fail" style="margin-top:4px">~1.08:1 ✗ Fail</span>
|
||||
</div>
|
||||
<div class="sc">The active pill is invisible. Users can't tell which page they're on.</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="sl" style="margin-bottom:8px">After <span class="state st-good">Passes WCAG AAA</span></div>
|
||||
<div style="background:#012851;border-radius:5px;padding:10px 14px;display:inline-flex;align-items:center">
|
||||
<span style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#fff;border-bottom:2px solid #A1DCD8;padding-bottom:2px">Dokumente</span>
|
||||
</div>
|
||||
<div style="margin-top:8px;font-size:9px;color:#555">
|
||||
White text (#ffffff) on navy (#012851).<br>
|
||||
Mint underline: #A1DCD8 on navy = 3.1:1 for the indicator itself.<br>
|
||||
<span class="contrast-badge cr-pass" style="margin-top:4px">21:1 ✓ AAA (text)</span>
|
||||
</div>
|
||||
<div class="sc">Unambiguous. The underline echoes brand-mint used elsewhere as an accent.</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ══════════════════════════════════
|
||||
SECTION 4 — MOBILE
|
||||
══════════════════════════════════ -->
|
||||
<div class="sec">
|
||||
<div class="sec-h"><span class="sec-num">4</span> Mobile header + nav drawer</div>
|
||||
|
||||
<div class="sg sg-3" style="align-items:start">
|
||||
|
||||
<!-- Current mobile (broken) -->
|
||||
<div class="sb">
|
||||
<div class="sl">Current <span class="state st-bad">No logo</span></div>
|
||||
<div style="display:flex;justify-content:center">
|
||||
<div class="WF-M">
|
||||
<div class="WF-M-STATUS"><span class="WF-M-TIME">09:41</span><div class="WF-M-ICONS"><div class="WF-M-ICON"></div><div class="WF-M-ICON"></div><div class="WF-M-ICON"></div></div></div>
|
||||
<div class="N-M-OLD">
|
||||
<div style="width:18px;display:flex;flex-direction:column;gap:3px">
|
||||
<div style="height:1.5px;background:#012851;border-radius:1px;width:100%"></div>
|
||||
<div style="height:1.5px;background:#012851;border-radius:1px;width:100%"></div>
|
||||
<div style="height:1.5px;background:#012851;border-radius:1px;width:100%"></div>
|
||||
</div>
|
||||
<div style="margin-left:auto;display:flex;gap:5px;align-items:center">
|
||||
<div class="H-OLD-ICO" style="width:18px;height:18px"></div>
|
||||
<div class="H-OLD-AV" style="width:20px;height:20px">LV</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="MAIN" style="padding:10px 12px;min-height:60px"><div class="PH w80"></div><div class="PH w60"></div></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ann-block" style="margin-top:8px">
|
||||
<strong>Problem:</strong> No logo. The user has zero brand context. On first load, there is no visual cue that this is Familienarchiv. The hamburger icon color (dark navy) will also break in dark mode.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Proposed mobile header -->
|
||||
<div class="sb">
|
||||
<div class="sl">Proposed header <span class="state st-good">Logo visible</span></div>
|
||||
<div style="display:flex;justify-content:center">
|
||||
<div class="WF-M">
|
||||
<div class="WF-M-STATUS"><span class="WF-M-TIME">09:41</span><div class="WF-M-ICONS"><div class="WF-M-ICON"></div><div class="WF-M-ICON"></div><div class="WF-M-ICON"></div></div></div>
|
||||
<div style="height:3px;background:#B4B9FF"></div><!-- accent strip, thinner on mobile -->
|
||||
<div class="N-M" style="background:#012851">
|
||||
<span class="logo" style="font-size:7.5px;letter-spacing:1px">FAMILIENARCHIV</span>
|
||||
<div style="display:flex;gap:6px;align-items:center">
|
||||
<div class="nico-av" style="width:20px;height:20px;font-size:5.5px">LV</div>
|
||||
<div class="HAMBURGER">
|
||||
<div class="HAMBURGER-LINE"></div>
|
||||
<div class="HAMBURGER-LINE"></div>
|
||||
<div class="HAMBURGER-LINE"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="MAIN" style="padding:10px 12px;min-height:60px"><div class="PH w80"></div><div class="PH w60"></div></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sc">Logo always visible left. Avatar + hamburger right. Accent strip is 3px on mobile (saves 1px). Background is brand-navy — no theme variation.</div>
|
||||
</div>
|
||||
|
||||
<!-- Proposed drawer open -->
|
||||
<div class="sb">
|
||||
<div class="sl">Nav drawer <span class="state st-good">Open state</span></div>
|
||||
<div style="display:flex;justify-content:center">
|
||||
<div class="WF-M">
|
||||
<div class="WF-M-STATUS"><span class="WF-M-TIME">09:41</span><div class="WF-M-ICONS"><div class="WF-M-ICON"></div><div class="WF-M-ICON"></div><div class="WF-M-ICON"></div></div></div>
|
||||
<div style="height:3px;background:#B4B9FF"></div>
|
||||
<div class="N-M" style="background:#012851">
|
||||
<span class="logo" style="font-size:7.5px;letter-spacing:1px">FAMILIENARCHIV</span>
|
||||
<div style="display:flex;gap:6px;align-items:center">
|
||||
<div class="nico-av" style="width:20px;height:20px;font-size:5.5px">LV</div>
|
||||
<!-- X icon when drawer open -->
|
||||
<div style="width:18px;height:18px;display:flex;align-items:center;justify-content:center;color:rgba(255,255,255,.85);font-size:13px;font-weight:300">✕</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Drawer -->
|
||||
<div class="DRAWER">
|
||||
<div class="DRAWER-LINK off">Dokumente</div>
|
||||
<div class="DRAWER-LINK off">Personen</div>
|
||||
<div class="DRAWER-LINK on">Korrespondenz</div>
|
||||
<div class="DRAWER-LINK off" style="font-size:7px;color:rgba(1,40,81,.4)">Admin</div>
|
||||
<div class="DRAWER-DIV"></div>
|
||||
<div class="DRAWER-LANG">
|
||||
<span style="font-size:7px;color:#888;font-weight:700;text-transform:uppercase;letter-spacing:.5px;margin-right:4px">Sprache</span>
|
||||
<div class="DRAWER-LANG-BTN on">DE</div>
|
||||
<div class="DRAWER-LANG-BTN">EN</div>
|
||||
<div class="DRAWER-LANG-BTN">ES</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="MAIN" style="padding:10px 12px;min-height:40px;opacity:.4"><div class="PH w80"></div></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sc">Drawer uses white background with navy text — intentional reversal of the dark header. Active page: mint left border + sand background. Language switcher lives in drawer on mobile (not floating).</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ══════════════════════════════════
|
||||
SECTION 5 — LOGIN PAGE
|
||||
══════════════════════════════════ -->
|
||||
<div class="sec">
|
||||
<div class="sec-h"><span class="sec-num">5</span> Login page — branded header</div>
|
||||
|
||||
<div class="sg sg-2">
|
||||
|
||||
<!-- Current login (no header) -->
|
||||
<div class="sb">
|
||||
<div class="sl">Current — header hidden <span class="state st-bad">No brand context</span></div>
|
||||
<div class="wf">
|
||||
<div class="wf-bar"><div class="dot r"></div><div class="dot y"></div><div class="dot g"></div><div class="urlbar"><span>/login</span></div></div>
|
||||
<!-- Floating language switcher (no context) -->
|
||||
<div style="position:relative;min-height:140px;background:#F0EFE9">
|
||||
<div style="position:absolute;top:8px;right:10px;display:flex;gap:4px">
|
||||
<span style="font-size:7.5px;font-weight:700;color:#012851;background:#fff;border:1.5px solid #D1D5DB;padding:2px 7px;border-radius:3px">DE</span>
|
||||
<span style="font-size:7.5px;font-weight:700;color:#888;padding:2px 7px;border-radius:3px">EN</span>
|
||||
<span style="font-size:7.5px;font-weight:700;color:#888;padding:2px 7px;border-radius:3px">ES</span>
|
||||
</div>
|
||||
<div style="display:flex;flex-direction:column;align-items:center;padding-top:22px">
|
||||
<div class="LOGIN-CARD">
|
||||
<div class="LOGIN-CARD-TITLE">Anmelden</div>
|
||||
<div class="LOGIN-FIELD"><div class="LOGIN-FIELD-L">E-Mail</div><div class="LOGIN-FIELD-I"></div></div>
|
||||
<div class="LOGIN-FIELD"><div class="LOGIN-FIELD-L">Passwort</div><div class="LOGIN-FIELD-I"></div></div>
|
||||
<div class="LOGIN-BTN">Anmelden</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ann-block">
|
||||
<strong>Problems:</strong> Header is hidden entirely on auth pages. Language switcher floats top-right with no visual anchor — it's a ghost. Users arrive with zero brand context. The page could be any app.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Proposed login (branded header) -->
|
||||
<div class="sb">
|
||||
<div class="sl">Proposed — logo-only header <span class="state st-good">Branded</span></div>
|
||||
<div class="wf">
|
||||
<div class="wf-bar"><div class="dot r"></div><div class="dot y"></div><div class="dot g"></div><div class="urlbar"><span>/login</span></div></div>
|
||||
<div class="LOGIN-BG">
|
||||
<div class="LOGIN-HEADER"></div><!-- 4px purple strip -->
|
||||
<div class="LOGIN-NAV">
|
||||
<span class="logo">FAMILIENARCHIV</span>
|
||||
<!-- Right: language switcher integrated in header -->
|
||||
<div style="display:flex;gap:6px;align-items:center">
|
||||
<span style="font-size:7.5px;font-weight:800;color:#fff;opacity:.9">DE</span>
|
||||
<span style="font-size:7.5px;font-weight:700;color:rgba(255,255,255,.5)">EN</span>
|
||||
<span style="font-size:7.5px;font-weight:700;color:rgba(255,255,255,.5)">ES</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="LOGIN-CARD">
|
||||
<div class="LOGIN-CARD-TITLE">Anmelden</div>
|
||||
<div class="LOGIN-FIELD"><div class="LOGIN-FIELD-L">E-Mail</div><div class="LOGIN-FIELD-I"></div></div>
|
||||
<div class="LOGIN-FIELD"><div class="LOGIN-FIELD-L">Passwort</div><div class="LOGIN-FIELD-I"></div></div>
|
||||
<div class="LOGIN-BTN">Anmelden</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sc">Accent strip + navy header appears on login. No nav links (user is not authenticated). Language switcher lives in header right slot — same position as desktop, consistent muscle memory. The brand is present from the first moment the user sees the app.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Code change note -->
|
||||
<div class="ann-block" style="background:#EFF6FF;border-color:#BFDBFE;color:#1E40AF;margin-top:16px">
|
||||
<strong>Implementation change:</strong> In <code style="font-size:9px;background:rgba(30,64,175,.1);padding:1px 3px;border-radius:2px">+layout.svelte</code>, the <code style="font-size:9px;background:rgba(30,64,175,.1);padding:1px 3px;border-radius:2px">{#if !isAuthPage}</code> guard currently hides the entire header. Replace with a conditional that renders a <em>login variant</em> of the header (logo + lang switcher, no nav links) when <code style="font-size:9px;background:rgba(30,64,175,.1);padding:1px 3px;border-radius:2px">isAuthPage</code> is true. Move the <code style="font-size:9px;background:rgba(30,64,175,.1);padding:1px 3px;border-radius:2px">LanguageSwitcher</code> import into the header for the auth variant. Remove the floating <code style="font-size:9px;background:rgba(30,64,175,.1);padding:1px 3px;border-radius:2px">LanguageSwitcher</code> from <code style="font-size:9px;background:rgba(30,64,175,.1);padding:1px 3px;border-radius:2px">/login/+page.svelte</code>.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ══════════════════════════════════
|
||||
SECTION 6 — RIGHT UTILITIES DETAIL
|
||||
══════════════════════════════════ -->
|
||||
<div class="sec">
|
||||
<div class="sec-h"><span class="sec-num">6</span> Right utility area — element by element</div>
|
||||
|
||||
<div style="background:#012851;border-radius:8px;padding:16px 20px;margin-bottom:16px">
|
||||
<div style="height:40px;display:flex;align-items:center;gap:10px;justify-content:flex-end">
|
||||
<!-- Language switcher -->
|
||||
<div style="display:flex;gap:5px;align-items:center;border-right:1px solid rgba(255,255,255,.15);padding-right:10px">
|
||||
<span style="font-size:8px;font-weight:800;color:#fff">DE</span>
|
||||
<span style="font-size:8px;font-weight:700;color:rgba(255,255,255,.5)">EN</span>
|
||||
<span style="font-size:8px;font-weight:700;color:rgba(255,255,255,.5)">ES</span>
|
||||
</div>
|
||||
<!-- Theme toggle -->
|
||||
<div style="width:24px;height:24px;background:rgba(255,255,255,.1);border-radius:5px;display:flex;align-items:center;justify-content:center;font-size:12px;opacity:.7">☀</div>
|
||||
<!-- Notification bell -->
|
||||
<div style="position:relative;width:24px;height:24px;display:flex;align-items:center;justify-content:center">
|
||||
<span style="font-size:14px;color:rgba(255,255,255,.75)">🔔</span>
|
||||
<div style="position:absolute;top:3px;right:2px;width:7px;height:7px;background:#EF4444;border-radius:50%;border:1.5px solid #012851"></div>
|
||||
</div>
|
||||
<!-- User avatar -->
|
||||
<div class="nico-av">LV</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px">
|
||||
<div style="background:#fff;border:1.5px solid #E0DDD6;border-radius:6px;padding:12px">
|
||||
<div style="font-size:8px;font-weight:800;text-transform:uppercase;letter-spacing:.5px;color:#888;margin-bottom:8px">Language switcher</div>
|
||||
<div style="font-size:9px;color:#444;line-height:1.6">
|
||||
Active lang: <span class="token">color: #ffffff</span><br>
|
||||
Inactive lang: <span class="token">color: rgba(255,255,255,.5)</span><br>
|
||||
Separator from rest: <span class="token">border-right: 1px solid rgba(255,255,255,.15)</span><br>
|
||||
On login: visible in header right slot
|
||||
</div>
|
||||
</div>
|
||||
<div style="background:#fff;border:1.5px solid #E0DDD6;border-radius:6px;padding:12px">
|
||||
<div style="font-size:8px;font-weight:800;text-transform:uppercase;letter-spacing:.5px;color:#888;margin-bottom:8px">Theme toggle</div>
|
||||
<div style="font-size:9px;color:#444;line-height:1.6">
|
||||
Icon: white at <span class="token">opacity: 0.7</span><br>
|
||||
Hover: <span class="token">opacity: 1.0</span><br>
|
||||
Background: <span class="token">rgba(255,255,255,.1)</span><br>
|
||||
No change to toggle logic — icon color only
|
||||
</div>
|
||||
</div>
|
||||
<div style="background:#fff;border:1.5px solid #E0DDD6;border-radius:6px;padding:12px">
|
||||
<div style="font-size:8px;font-weight:800;text-transform:uppercase;letter-spacing:.5px;color:#888;margin-bottom:8px">Notification bell</div>
|
||||
<div style="font-size:9px;color:#444;line-height:1.6">
|
||||
Icon: white at <span class="token">opacity: 0.75</span><br>
|
||||
Badge: stays <span class="token">bg-red-500</span> (#EF4444)<br>
|
||||
Badge border: <span class="token">border: 1.5px solid #012851</span> (halos on navy)<br>
|
||||
No component logic changes
|
||||
</div>
|
||||
</div>
|
||||
<div style="background:#fff;border:1.5px solid #E0DDD6;border-radius:6px;padding:12px">
|
||||
<div style="font-size:8px;font-weight:800;text-transform:uppercase;letter-spacing:.5px;color:#888;margin-bottom:8px">User avatar</div>
|
||||
<div style="font-size:9px;color:#444;line-height:1.6">
|
||||
Background: <span class="token">#A1DCD8</span> (brand-mint)<br>
|
||||
Text: <span class="token">#012851</span> (brand-navy)<br>
|
||||
Contrast: 4.8:1 ✓ AA<br>
|
||||
Replaces navy bg (dark-on-dark in dark mode)
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ══════════════════════════════════
|
||||
IMPLEMENTATION NOTES
|
||||
══════════════════════════════════ -->
|
||||
<div class="IMPL">
|
||||
<h2>Implementation notes</h2>
|
||||
<div class="IMPL-GRID">
|
||||
<div class="IMPL-COL">
|
||||
<h3>CSS / Tailwind changes</h3>
|
||||
<ul>
|
||||
<li>Header: replace <code>bg-surface</code> with <code>bg-[#012851]</code> (or add a <code>bg-brand-navy</code> utility to <code>layout.css</code>)</li>
|
||||
<li>Remove <code>border-b border-line-2</code> from header — the accent strip replaces the visual separator</li>
|
||||
<li>Add a <code><div class="h-1 bg-[#B4B9FF]"></code> before the nav bar in <code>+layout.svelte</code></li>
|
||||
<li>Nav links: replace <code>text-ink</code> + <code>bg-nav-active</code> with opacity-based white utilities: <code>text-white/55</code> inactive, <code>hover:text-white/85</code>, <code>text-white border-b-2 border-[#A1DCD8]</code> active</li>
|
||||
<li>User avatar: swap <code>bg-brand-navy text-white</code> → <code>bg-[#A1DCD8] text-[#012851]</code></li>
|
||||
<li>Notification badge: add <code>border-2 border-[#012851]</code> to badge element</li>
|
||||
<li>Dark mode: on the <code><header></code> element, ensure there is NO <code>dark:</code> variant overriding the background</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="IMPL-COL">
|
||||
<h3>Component changes</h3>
|
||||
<ul>
|
||||
<li><code>+layout.svelte</code>: split the <code>{#if !isAuthPage}</code> guard into two branches — full header (authed) vs. login header (logo + lang only)</li>
|
||||
<li><code>AppNav.svelte</code>: ensure logo is always rendered, not hidden on mobile via <code>hidden sm:flex</code> or similar</li>
|
||||
<li><code>AppNav.svelte</code>: hamburger button — icon color from dark to <code>text-white/85</code></li>
|
||||
<li><code>AppNav.svelte</code>: active link class — remove <code>bg-nav-active</code>, add bottom border in mint</li>
|
||||
<li><code>UserMenu.svelte</code>: avatar background and text color</li>
|
||||
<li><code>ThemeToggle.svelte</code>: icon fill/stroke → <code>text-white/70</code></li>
|
||||
<li><code>NotificationBell.svelte</code>: icon color → <code>text-white/75</code></li>
|
||||
<li><code>/login/+page.svelte</code>: remove standalone <code><LanguageSwitcher></code> — it moves to the layout header</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="IMPL-COL">
|
||||
<h3>CSS variable candidates</h3>
|
||||
<ul>
|
||||
<li>Consider adding to <code>layout.css</code>:<br><code>--header-bg: #012851;</code><br><code>--header-accent: #B4B9FF;</code><br><code>--header-nav-active: #A1DCD8;</code></li>
|
||||
<li>These are intentionally NOT in the dark-mode <code>@media (prefers-color-scheme: dark)</code> block — they are brand constants</li>
|
||||
<li>If Tailwind 4 theme is configured, add:<br><code>brand-navy: #012851</code><br><code>brand-purple: #B4B9FF</code><br><code>brand-mint: #A1DCD8</code><br>to the <code>@theme</code> block in <code>layout.css</code></li>
|
||||
<li>No backend changes required</li>
|
||||
<li>No i18n key changes required</li>
|
||||
<li>No new routes required</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
1645
docs/specs/persons-concept-a-enriched-directory.html
Normal file
1645
docs/specs/persons-concept-a-enriched-directory.html
Normal file
File diff suppressed because it is too large
Load Diff
1
frontend/.gitignore
vendored
1
frontend/.gitignore
vendored
@@ -6,6 +6,7 @@ node_modules
|
||||
.netlify
|
||||
.wrangler
|
||||
/.svelte-kit
|
||||
/.svelte-kit-backup
|
||||
/build
|
||||
|
||||
# OS
|
||||
|
||||
@@ -8,7 +8,12 @@ bun.lockb
|
||||
# Miscellaneous
|
||||
/static/
|
||||
|
||||
# Build artifacts
|
||||
/.svelte-kit/
|
||||
/.svelte-kit-backup/
|
||||
|
||||
# Generated files
|
||||
/.svelte-kit-backup/
|
||||
/src/lib/generated/
|
||||
/src/lib/paraglide/
|
||||
/src/lib/paraglide_bak*/
|
||||
|
||||
31
frontend/.svelte-kit-backup/types/src/routes/persons/[id]/edit/$types.d.ts
vendored
Normal file
31
frontend/.svelte-kit-backup/types/src/routes/persons/[id]/edit/$types.d.ts
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
import type * as Kit from '@sveltejs/kit';
|
||||
|
||||
type Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;
|
||||
type MatcherParam<M> = M extends (param : string) => param is (infer U extends string) ? U : string;
|
||||
type RouteParams = { id: string };
|
||||
type RouteId = '/persons/[id]/edit';
|
||||
type MaybeWithVoid<T> = {} extends T ? T | void : T;
|
||||
export type RequiredKeys<T> = { [K in keyof T]-?: {} extends { [P in K]: T[K] } ? never : K; }[keyof T];
|
||||
type OutputDataShape<T> = MaybeWithVoid<Omit<App.PageData, RequiredKeys<T>> & Partial<Pick<App.PageData, keyof T & keyof App.PageData>> & Record<string, any>>
|
||||
type EnsureDefined<T> = T extends null | undefined ? {} : T;
|
||||
type OptionalUnion<U extends Record<string, any>, A extends keyof U = U extends U ? keyof U : never> = U extends unknown ? { [P in Exclude<A, keyof U>]?: never } & U : never;
|
||||
export type Snapshot<T = any> = Kit.Snapshot<T>;
|
||||
type PageServerParentData = EnsureDefined<import('../../../$types.js').LayoutServerData>;
|
||||
type PageParentData = EnsureDefined<import('../../../$types.js').LayoutData>;
|
||||
|
||||
export type EntryGenerator = () => Promise<Array<RouteParams>> | Array<RouteParams>;
|
||||
export type PageServerLoad<OutputData extends OutputDataShape<PageServerParentData> = OutputDataShape<PageServerParentData>> = Kit.ServerLoad<RouteParams, PageServerParentData, OutputData, RouteId>;
|
||||
export type PageServerLoadEvent = Parameters<PageServerLoad>[0];
|
||||
type ExcludeActionFailure<T> = T extends Kit.ActionFailure<any> ? never : T extends void ? never : T;
|
||||
type ActionsSuccess<T extends Record<string, (...args: any) => any>> = { [Key in keyof T]: ExcludeActionFailure<Awaited<ReturnType<T[Key]>>>; }[keyof T];
|
||||
type ExtractActionFailure<T> = T extends Kit.ActionFailure<infer X> ? X extends void ? never : X : never;
|
||||
type ActionsFailure<T extends Record<string, (...args: any) => any>> = { [Key in keyof T]: Exclude<ExtractActionFailure<Awaited<ReturnType<T[Key]>>>, void>; }[keyof T];
|
||||
type ActionsExport = typeof import('../../../../../../../src/routes/persons/[id]/edit/+page.server.js').actions
|
||||
export type SubmitFunction = Kit.SubmitFunction<Expand<ActionsSuccess<ActionsExport>>, Expand<ActionsFailure<ActionsExport>>>
|
||||
export type ActionData = Expand<Kit.AwaitedActions<ActionsExport>> | null;
|
||||
export type PageServerData = Expand<OptionalUnion<EnsureDefined<Kit.LoadProperties<Awaited<ReturnType<typeof import('../../../../../../../src/routes/persons/[id]/edit/+page.server.js').load>>>>>>;
|
||||
export type PageData = Expand<Omit<PageParentData, keyof PageServerData> & EnsureDefined<PageServerData>>;
|
||||
export type Action<OutputData extends Record<string, any> | void = Record<string, any> | void> = Kit.Action<RouteParams, OutputData, RouteId>
|
||||
export type Actions<OutputData extends Record<string, any> | void = Record<string, any> | void> = Kit.Actions<RouteParams, OutputData, RouteId>
|
||||
export type PageProps = { params: RouteParams; data: PageData; form: ActionData }
|
||||
export type RequestEvent = Kit.RequestEvent<RouteParams, RouteId>;
|
||||
@@ -5,7 +5,7 @@
|
||||
"value": "de",
|
||||
"domain": "localhost",
|
||||
"path": "/",
|
||||
"expires": 1808896929.897686,
|
||||
"expires": 1809337570.90398,
|
||||
"httpOnly": false,
|
||||
"secure": false,
|
||||
"sameSite": "Lax"
|
||||
@@ -15,7 +15,7 @@
|
||||
"value": "Basic%20YWRtaW46YWRtaW4xMjM%3D",
|
||||
"domain": "localhost",
|
||||
"path": "/",
|
||||
"expires": 1774423330.233039,
|
||||
"expires": 1774863971.187596,
|
||||
"httpOnly": true,
|
||||
"secure": false,
|
||||
"sameSite": "Strict"
|
||||
|
||||
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",
|
||||
@@ -120,23 +120,41 @@
|
||||
"person_role_sender": "Gesendet",
|
||||
"person_role_receiver": "Empfangen",
|
||||
"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",
|
||||
@@ -154,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",
|
||||
@@ -166,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.",
|
||||
@@ -249,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.",
|
||||
@@ -320,5 +376,43 @@
|
||||
"dashboard_needs_metadata_show_all": "Alle anzeigen",
|
||||
"dashboard_recent_heading": "Zuletzt aktiv",
|
||||
"dashboard_resume_label": "Zuletzt geöffnet:",
|
||||
"dashboard_resume_fallback": "Unbekanntes Dokument"
|
||||
"dashboard_resume_fallback": "Unbekanntes Dokument",
|
||||
"doc_status_placeholder": "Platzhalter",
|
||||
"doc_status_uploaded": "Hochgeladen",
|
||||
"doc_status_transcribed": "Transkribiert",
|
||||
"doc_status_reviewed": "Geprüft",
|
||||
"doc_status_archived": "Archiviert",
|
||||
"doc_status_unknown": "Unbekannt",
|
||||
"persons_stats_persons_one": "1 Person",
|
||||
"persons_stats_persons_many": "{count} Personen",
|
||||
"persons_stats_documents_one": "1 Dokument",
|
||||
"persons_stats_documents_many": "{count} Dokumente",
|
||||
"persons_stats_label_persons_one": "Person",
|
||||
"persons_stats_label_persons_many": "Personen",
|
||||
"persons_stats_label_documents_one": "Dokument",
|
||||
"persons_stats_label_documents_many": "Dokumente",
|
||||
"person_card_doc_count_one": "1 Dok.",
|
||||
"person_card_doc_count_many": "{count} Dok.",
|
||||
"error_person_not_found": "Die Person wurde nicht gefunden.",
|
||||
"person_btn_edit": "Bearbeiten",
|
||||
"person_discard_changes": "Änderungen verwerfen",
|
||||
"person_danger_zone_heading": "Gefahrenzone",
|
||||
"persons_new_birth_year": "Geburtsjahr",
|
||||
"persons_new_death_year": "Todesjahr",
|
||||
"persons_new_notes": "Notizen",
|
||||
"person_save_changes": "Änderungen speichern",
|
||||
"notification_view_all": "Alle anzeigen →",
|
||||
"notification_history_heading": "Benachrichtigungen",
|
||||
"notification_history_view_link": "Benachrichtigungsverlauf ansehen →",
|
||||
"notification_filter_all": "Alle",
|
||||
"notification_filter_unread": "Ungelesen",
|
||||
"notification_filter_mention": "Erwähnung",
|
||||
"notification_filter_reply": "Antwort",
|
||||
"notification_mark_all_read_aria": "Alle Benachrichtigungen als gelesen markieren",
|
||||
"notification_load_more": "Ältere laden",
|
||||
"notification_empty_history": "Keine Benachrichtigungen",
|
||||
"notification_empty_history_body": "Hier erscheinen Erwähnungen und Antworten auf deine Kommentare.",
|
||||
"notification_row_aria": "{actor} {type} auf \u201e{title}\u201c \u2014 {time} \u2014 {readState}",
|
||||
"notification_read_state_read": "gelesen",
|
||||
"notification_read_state_unread": "ungelesen"
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
@@ -120,23 +120,41 @@
|
||||
"person_role_sender": "Sent",
|
||||
"person_role_receiver": "Received",
|
||||
"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",
|
||||
@@ -154,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",
|
||||
@@ -166,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.",
|
||||
@@ -249,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.",
|
||||
@@ -320,5 +376,43 @@
|
||||
"dashboard_needs_metadata_show_all": "Show all",
|
||||
"dashboard_recent_heading": "Recent Activity",
|
||||
"dashboard_resume_label": "Last opened:",
|
||||
"dashboard_resume_fallback": "Unknown document"
|
||||
"dashboard_resume_fallback": "Unknown document",
|
||||
"doc_status_placeholder": "Placeholder",
|
||||
"doc_status_uploaded": "Uploaded",
|
||||
"doc_status_transcribed": "Transcribed",
|
||||
"doc_status_reviewed": "Reviewed",
|
||||
"doc_status_archived": "Archived",
|
||||
"doc_status_unknown": "Unknown",
|
||||
"persons_stats_persons_one": "1 person",
|
||||
"persons_stats_persons_many": "{count} persons",
|
||||
"persons_stats_documents_one": "1 document",
|
||||
"persons_stats_documents_many": "{count} documents",
|
||||
"persons_stats_label_persons_one": "Person",
|
||||
"persons_stats_label_persons_many": "Persons",
|
||||
"persons_stats_label_documents_one": "Document",
|
||||
"persons_stats_label_documents_many": "Documents",
|
||||
"person_card_doc_count_one": "1 doc",
|
||||
"person_card_doc_count_many": "{count} docs",
|
||||
"error_person_not_found": "Person not found.",
|
||||
"person_btn_edit": "Edit",
|
||||
"person_discard_changes": "Discard changes",
|
||||
"person_danger_zone_heading": "Danger zone",
|
||||
"persons_new_birth_year": "Birth year",
|
||||
"persons_new_death_year": "Death year",
|
||||
"persons_new_notes": "Notes",
|
||||
"person_save_changes": "Save changes",
|
||||
"notification_view_all": "View all →",
|
||||
"notification_history_heading": "Notifications",
|
||||
"notification_history_view_link": "View notification history →",
|
||||
"notification_filter_all": "All",
|
||||
"notification_filter_unread": "Unread",
|
||||
"notification_filter_mention": "Mention",
|
||||
"notification_filter_reply": "Reply",
|
||||
"notification_mark_all_read_aria": "Mark all notifications as read",
|
||||
"notification_load_more": "Load older",
|
||||
"notification_empty_history": "No notifications",
|
||||
"notification_empty_history_body": "Mentions and replies to your comments will appear here.",
|
||||
"notification_row_aria": "{actor} {type} on \"{title}\" — {time} — {readState}",
|
||||
"notification_read_state_read": "read",
|
||||
"notification_read_state_unread": "unread"
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
@@ -120,23 +120,41 @@
|
||||
"person_role_sender": "Enviado",
|
||||
"person_role_receiver": "Recibido",
|
||||
"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",
|
||||
@@ -154,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",
|
||||
@@ -166,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.",
|
||||
@@ -249,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.",
|
||||
@@ -320,5 +376,43 @@
|
||||
"dashboard_needs_metadata_show_all": "Ver todos",
|
||||
"dashboard_recent_heading": "Actividad reciente",
|
||||
"dashboard_resume_label": "Último abierto:",
|
||||
"dashboard_resume_fallback": "Documento desconocido"
|
||||
"dashboard_resume_fallback": "Documento desconocido",
|
||||
"doc_status_placeholder": "Marcador",
|
||||
"doc_status_uploaded": "Cargado",
|
||||
"doc_status_transcribed": "Transcrito",
|
||||
"doc_status_reviewed": "Revisado",
|
||||
"doc_status_archived": "Archivado",
|
||||
"doc_status_unknown": "Desconocido",
|
||||
"persons_stats_persons_one": "1 persona",
|
||||
"persons_stats_persons_many": "{count} personas",
|
||||
"persons_stats_documents_one": "1 documento",
|
||||
"persons_stats_documents_many": "{count} documentos",
|
||||
"persons_stats_label_persons_one": "Persona",
|
||||
"persons_stats_label_persons_many": "Personas",
|
||||
"persons_stats_label_documents_one": "Documento",
|
||||
"persons_stats_label_documents_many": "Documentos",
|
||||
"person_card_doc_count_one": "1 doc.",
|
||||
"person_card_doc_count_many": "{count} docs.",
|
||||
"error_person_not_found": "Persona no encontrada.",
|
||||
"person_btn_edit": "Editar",
|
||||
"person_discard_changes": "Descartar cambios",
|
||||
"person_danger_zone_heading": "Zona de peligro",
|
||||
"persons_new_birth_year": "Año de nacimiento",
|
||||
"persons_new_death_year": "Año de fallecimiento",
|
||||
"persons_new_notes": "Notas",
|
||||
"person_save_changes": "Guardar cambios",
|
||||
"notification_view_all": "Ver todas →",
|
||||
"notification_history_heading": "Notificaciones",
|
||||
"notification_history_view_link": "Ver historial de notificaciones →",
|
||||
"notification_filter_all": "Todas",
|
||||
"notification_filter_unread": "No leídas",
|
||||
"notification_filter_mention": "Mención",
|
||||
"notification_filter_reply": "Respuesta",
|
||||
"notification_mark_all_read_aria": "Marcar todas las notificaciones como leídas",
|
||||
"notification_load_more": "Cargar anteriores",
|
||||
"notification_empty_history": "Sin notificaciones",
|
||||
"notification_empty_history_body": "Aquí aparecerán las menciones y respuestas a tus comentarios.",
|
||||
"notification_row_aria": "{actor} {type} en \"{title}\" — {time} — {readState}",
|
||||
"notification_read_state_read": "leído",
|
||||
"notification_read_state_unread": "no leído"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"branch": "feature/68-new-document-file-first",
|
||||
"commitSha": "53b482c5f24688ca3426d434c832e8d24acfee4c",
|
||||
"startedAt": "2026-03-27T10:49:23.106Z",
|
||||
"description": null
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"branch": "feature/68-new-document-file-first",
|
||||
"commitSha": "53b482c5f24688ca3426d434c832e8d24acfee4c",
|
||||
"startedAt": "2026-03-27T10:49:39.204Z",
|
||||
"description": null
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"branch": "feature/68-new-document-file-first",
|
||||
"commitSha": "53b482c5f24688ca3426d434c832e8d24acfee4c",
|
||||
"startedAt": "2026-03-27T10:51:02.177Z",
|
||||
"description": null
|
||||
}
|
||||
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[];
|
||||
}[];
|
||||
|
||||
@@ -24,25 +24,34 @@ let { mentions }: Props = $props();
|
||||
<h2 class="mb-4 font-sans text-xs font-bold tracking-widest text-gray-400 uppercase">
|
||||
{m.dashboard_notifications_heading()}
|
||||
</h2>
|
||||
{#each mentions as mention (mention.id)}
|
||||
<div class="flex items-center gap-3 border-b border-line py-2 last:border-0">
|
||||
{#if mention.documentId}
|
||||
<a
|
||||
href={mention.annotationId
|
||||
? `/documents/${mention.documentId}?commentId=${mention.referenceId}&annotationId=${mention.annotationId}`
|
||||
: `/documents/${mention.documentId}?commentId=${mention.referenceId}`}
|
||||
class="font-serif text-lg text-ink hover:text-ink-2 hover:underline"
|
||||
>{mention.actorName ?? ''}</a
|
||||
>
|
||||
<span class="font-sans text-xs text-gray-400">
|
||||
{mention.type === 'MENTION'
|
||||
? m.dashboard_notification_mentioned()
|
||||
: m.dashboard_notification_replied()}
|
||||
</span>
|
||||
{:else}
|
||||
<span class="font-serif text-lg text-ink">{mention.actorName ?? ''}</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
<div>
|
||||
{#each mentions as mention (mention.id)}
|
||||
<div class="flex items-center gap-3 border-b border-line py-2 last:border-0">
|
||||
{#if mention.documentId}
|
||||
<a
|
||||
href={mention.annotationId
|
||||
? `/documents/${mention.documentId}?commentId=${mention.referenceId}&annotationId=${mention.annotationId}`
|
||||
: `/documents/${mention.documentId}?commentId=${mention.referenceId}`}
|
||||
class="font-serif text-lg text-ink hover:text-ink-2 hover:underline"
|
||||
>{mention.actorName ?? ''}</a
|
||||
>
|
||||
<span class="font-sans text-xs text-gray-400">
|
||||
{mention.type === 'MENTION'
|
||||
? m.dashboard_notification_mentioned()
|
||||
: m.dashboard_notification_replied()}
|
||||
</span>
|
||||
{:else}
|
||||
<span class="font-serif text-lg text-ink">{mention.actorName ?? ''}</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="mt-4 border-t border-line pt-4">
|
||||
<a
|
||||
href="/notifications"
|
||||
class="text-sm font-medium text-ink-2 transition-colors hover:text-ink"
|
||||
>{m.notification_history_view_link()}</a
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
79
frontend/src/lib/components/DateInput.svelte
Normal file
79
frontend/src/lib/components/DateInput.svelte
Normal file
@@ -0,0 +1,79 @@
|
||||
<script lang="ts">
|
||||
import { isoToGerman, handleGermanDateInput, germanToIso } from '$lib/utils/date';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
interface Props {
|
||||
value?: string;
|
||||
errorMessage?: string | null;
|
||||
name?: string;
|
||||
id?: string;
|
||||
placeholder?: string;
|
||||
class?: string;
|
||||
onchange?: () => void;
|
||||
}
|
||||
|
||||
let {
|
||||
value = $bindable(''),
|
||||
errorMessage = $bindable<string | null>(null),
|
||||
name,
|
||||
id,
|
||||
placeholder,
|
||||
class: className = '',
|
||||
onchange
|
||||
}: Props = $props();
|
||||
|
||||
let display = $state(isoToGerman(value ?? ''));
|
||||
|
||||
// ─── Validation helper ────────────────────────────────────────────────────
|
||||
function isCalendarValid(iso: string): boolean {
|
||||
if (!iso) return false;
|
||||
const [, mm, dd] = iso.match(/^\d{4}-(\d{2})-(\d{2})$/) ?? [];
|
||||
const month = parseInt(mm, 10);
|
||||
const day = parseInt(dd, 10);
|
||||
return month >= 1 && month <= 12 && day >= 1 && day <= 31;
|
||||
}
|
||||
|
||||
// ─── Input handler ────────────────────────────────────────────────────────
|
||||
function handleInput(e: Event) {
|
||||
const result = handleGermanDateInput(e);
|
||||
display = result.display;
|
||||
|
||||
if (result.display === '') {
|
||||
value = '';
|
||||
errorMessage = null;
|
||||
onchange?.();
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.display.length < 10) {
|
||||
value = '';
|
||||
errorMessage = m.form_date_error();
|
||||
return;
|
||||
}
|
||||
|
||||
const iso = germanToIso(result.display);
|
||||
if (!iso || !isCalendarValid(iso)) {
|
||||
value = '';
|
||||
errorMessage = m.form_date_error();
|
||||
return;
|
||||
}
|
||||
|
||||
value = iso;
|
||||
errorMessage = null;
|
||||
onchange?.();
|
||||
}
|
||||
</script>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
maxlength="10"
|
||||
id={id}
|
||||
value={display}
|
||||
placeholder={placeholder ?? m.form_placeholder_date()}
|
||||
oninput={handleInput}
|
||||
class={className}
|
||||
/>
|
||||
{#if name}
|
||||
<input type="hidden" name={name} value={value} />
|
||||
{/if}
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -2,17 +2,11 @@
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
type NotificationItem = {
|
||||
id: string;
|
||||
type: 'REPLY' | 'MENTION';
|
||||
documentId: string;
|
||||
referenceId: string;
|
||||
annotationId: string | null;
|
||||
read: boolean;
|
||||
createdAt: string;
|
||||
actorName: string;
|
||||
};
|
||||
import {
|
||||
type NotificationItem,
|
||||
relativeTime,
|
||||
parseNotificationEvent
|
||||
} from '$lib/utils/notifications';
|
||||
|
||||
let notifications: NotificationItem[] = $state([]);
|
||||
let unreadCount: number = $state(0);
|
||||
@@ -131,23 +125,12 @@ function attachClickOutside(node: HTMLElement) {
|
||||
};
|
||||
}
|
||||
|
||||
function relativeTime(isoString: string): string {
|
||||
const diffMs = Date.now() - new Date(isoString).getTime();
|
||||
const diffMin = Math.floor(diffMs / 60000);
|
||||
const rtf = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });
|
||||
if (diffMin < 1) return rtf.format(0, 'minute');
|
||||
if (diffMin < 60) return rtf.format(-diffMin, 'minute');
|
||||
const diffH = Math.floor(diffMin / 60);
|
||||
if (diffH < 24) return rtf.format(-diffH, 'hour');
|
||||
const diffD = Math.floor(diffH / 24);
|
||||
return rtf.format(-diffD, 'day');
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
fetchUnreadCount();
|
||||
eventSource = new EventSource('/api/notifications/stream');
|
||||
eventSource.addEventListener('notification', (e) => {
|
||||
const notification = JSON.parse(e.data) as NotificationItem;
|
||||
const notification = parseNotificationEvent(e.data);
|
||||
if (!notification) return;
|
||||
notifications = [notification, ...notifications];
|
||||
if (!notification.read) unreadCount += 1;
|
||||
});
|
||||
@@ -317,6 +300,16 @@ onDestroy(() => {
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
|
||||
<div class="border-t border-line px-4 py-2">
|
||||
<a
|
||||
href="/notifications"
|
||||
onclick={closeDropdown}
|
||||
class="text-xs font-medium text-ink-2 transition-colors hover:text-ink"
|
||||
>
|
||||
{m.notification_view_all()}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as m from '$lib/paraglide/messages.js';
|
||||
* Keep in sync with backend/src/main/java/org/raddatz/familienarchiv/exception/ErrorCode.java
|
||||
*/
|
||||
export type ErrorCode =
|
||||
| 'PERSON_NOT_FOUND'
|
||||
| 'DOCUMENT_NOT_FOUND'
|
||||
| 'DOCUMENT_NO_FILE'
|
||||
| 'FILE_NOT_FOUND'
|
||||
@@ -47,6 +48,8 @@ export async function parseBackendError(res: Response): Promise<BackendError | n
|
||||
/** Returns a localised message for the given error code via Paraglide. Falls back to INTERNAL_ERROR. */
|
||||
export function getErrorMessage(code: ErrorCode | string | undefined): string {
|
||||
switch (code) {
|
||||
case 'PERSON_NOT_FOUND':
|
||||
return m.error_person_not_found();
|
||||
case 'DOCUMENT_NOT_FOUND':
|
||||
return m.error_document_not_found();
|
||||
case 'DOCUMENT_NO_FILE':
|
||||
|
||||
@@ -468,6 +468,22 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/stats": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get: operations["getStats"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/persons/{id}/received-documents": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -708,22 +724,8 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/auth/reset-token-for-test": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get: operations["getResetTokenForTest"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
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;
|
||||
@@ -1002,6 +1004,27 @@ export interface components {
|
||||
/** Format: date-time */
|
||||
createdAt: string;
|
||||
actorName?: string;
|
||||
documentTitle?: string;
|
||||
};
|
||||
StatsDTO: {
|
||||
/** Format: int64 */
|
||||
totalPersons?: number;
|
||||
/** Format: int64 */
|
||||
totalDocuments?: number;
|
||||
};
|
||||
PersonSummaryDTO: {
|
||||
/** Format: uuid */
|
||||
id?: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
/** Format: int32 */
|
||||
birthYear?: number;
|
||||
/** Format: int32 */
|
||||
deathYear?: number;
|
||||
alias?: string;
|
||||
notes?: string;
|
||||
/** Format: int64 */
|
||||
documentCount?: number;
|
||||
};
|
||||
PageNotificationDTO: {
|
||||
/** Format: int64 */
|
||||
@@ -1022,11 +1045,11 @@ export interface components {
|
||||
empty?: boolean;
|
||||
};
|
||||
PageableObject: {
|
||||
paged?: boolean;
|
||||
/** Format: int32 */
|
||||
pageNumber?: number;
|
||||
/** Format: int32 */
|
||||
pageSize?: number;
|
||||
paged?: boolean;
|
||||
/** Format: int64 */
|
||||
offset?: number;
|
||||
sort?: components["schemas"]["SortObject"];
|
||||
@@ -1479,7 +1502,7 @@ export interface operations {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"*/*": components["schemas"]["Person"][];
|
||||
"*/*": components["schemas"]["PersonSummaryDTO"][];
|
||||
};
|
||||
};
|
||||
};
|
||||
@@ -1493,9 +1516,7 @@ export interface operations {
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
[key: string]: string;
|
||||
};
|
||||
"application/json": components["schemas"]["PersonUpdateDTO"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
@@ -2111,6 +2132,26 @@ export interface operations {
|
||||
};
|
||||
};
|
||||
};
|
||||
getStats: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"*/*": components["schemas"]["StatsDTO"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
getPersonReceivedDocuments: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -2437,7 +2478,7 @@ export interface operations {
|
||||
parameters: {
|
||||
query: {
|
||||
senderId: string;
|
||||
receiverId: string;
|
||||
receiverId?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
dir?: string;
|
||||
@@ -2459,28 +2500,7 @@ export interface operations {
|
||||
};
|
||||
};
|
||||
};
|
||||
getResetTokenForTest: {
|
||||
parameters: {
|
||||
query: {
|
||||
email: string;
|
||||
};
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"*/*": string;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
// 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');
|
||||
});
|
||||
});
|
||||
28
frontend/src/lib/utils/documentStatusLabel.spec.ts
Normal file
28
frontend/src/lib/utils/documentStatusLabel.spec.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { formatDocumentStatus } from './documentStatusLabel';
|
||||
|
||||
describe('formatDocumentStatus', () => {
|
||||
it('maps PLACEHOLDER to correct label', () => {
|
||||
expect(formatDocumentStatus('PLACEHOLDER')).toBe('Platzhalter');
|
||||
});
|
||||
|
||||
it('maps UPLOADED to correct label', () => {
|
||||
expect(formatDocumentStatus('UPLOADED')).toBe('Hochgeladen');
|
||||
});
|
||||
|
||||
it('maps TRANSCRIBED to correct label', () => {
|
||||
expect(formatDocumentStatus('TRANSCRIBED')).toBe('Transkribiert');
|
||||
});
|
||||
|
||||
it('maps REVIEWED to correct label', () => {
|
||||
expect(formatDocumentStatus('REVIEWED')).toBe('Geprüft');
|
||||
});
|
||||
|
||||
it('maps ARCHIVED to correct label', () => {
|
||||
expect(formatDocumentStatus('ARCHIVED')).toBe('Archiviert');
|
||||
});
|
||||
|
||||
it('returns fallback for unknown status', () => {
|
||||
expect(formatDocumentStatus('SOMETHING_NEW')).toBe('Unbekannt');
|
||||
});
|
||||
});
|
||||
22
frontend/src/lib/utils/documentStatusLabel.ts
Normal file
22
frontend/src/lib/utils/documentStatusLabel.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
/**
|
||||
* Maps a document status string to a localised human-readable label.
|
||||
* Falls back to "Unknown" for unrecognised values.
|
||||
*/
|
||||
export function formatDocumentStatus(status: string): string {
|
||||
switch (status) {
|
||||
case 'PLACEHOLDER':
|
||||
return m.doc_status_placeholder();
|
||||
case 'UPLOADED':
|
||||
return m.doc_status_uploaded();
|
||||
case 'TRANSCRIBED':
|
||||
return m.doc_status_transcribed();
|
||||
case 'REVIEWED':
|
||||
return m.doc_status_reviewed();
|
||||
case 'ARCHIVED':
|
||||
return m.doc_status_archived();
|
||||
default:
|
||||
return m.doc_status_unknown();
|
||||
}
|
||||
}
|
||||
106
frontend/src/lib/utils/notifications.spec.ts
Normal file
106
frontend/src/lib/utils/notifications.spec.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { relativeTime, parseNotificationEvent } from '$lib/utils/notifications';
|
||||
|
||||
const rtf = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });
|
||||
|
||||
function msAgo(ms: number, now: Date): string {
|
||||
return new Date(now.getTime() - ms).toISOString();
|
||||
}
|
||||
|
||||
describe('relativeTime', () => {
|
||||
const now = new Date('2024-06-15T12:00:00.000Z');
|
||||
|
||||
it('should use minute bucket for timestamps under 60 seconds ago', () => {
|
||||
const ts = msAgo(30_000, now);
|
||||
expect(relativeTime(ts, now)).toBe(rtf.format(0, 'minute'));
|
||||
});
|
||||
|
||||
it('should use minute bucket for exactly 59 minutes ago', () => {
|
||||
const ts = msAgo(59 * 60_000, now);
|
||||
expect(relativeTime(ts, now)).toBe(rtf.format(-59, 'minute'));
|
||||
});
|
||||
|
||||
it('should use minute bucket for exactly 1 minute ago', () => {
|
||||
const ts = msAgo(60_000, now);
|
||||
expect(relativeTime(ts, now)).toBe(rtf.format(-1, 'minute'));
|
||||
});
|
||||
|
||||
it('should use hour bucket for exactly 1 hour ago', () => {
|
||||
const ts = msAgo(60 * 60_000, now);
|
||||
expect(relativeTime(ts, now)).toBe(rtf.format(-1, 'hour'));
|
||||
});
|
||||
|
||||
it('should use hour bucket for 23 hours ago', () => {
|
||||
const ts = msAgo(23 * 60 * 60_000, now);
|
||||
expect(relativeTime(ts, now)).toBe(rtf.format(-23, 'hour'));
|
||||
});
|
||||
|
||||
it('should use day bucket for exactly 24 hours ago', () => {
|
||||
const ts = msAgo(24 * 60 * 60_000, now);
|
||||
expect(relativeTime(ts, now)).toBe(rtf.format(-1, 'day'));
|
||||
});
|
||||
|
||||
it('should use day bucket for 6 days ago', () => {
|
||||
const ts = msAgo(6 * 24 * 60 * 60_000, now);
|
||||
expect(relativeTime(ts, now)).toBe(rtf.format(-6, 'day'));
|
||||
});
|
||||
|
||||
it('should default now to current time when omitted', () => {
|
||||
// Just verify it returns a non-empty string — exact value depends on runtime clock
|
||||
const ts = new Date(Date.now() - 5 * 60_000).toISOString();
|
||||
expect(relativeTime(ts)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseNotificationEvent', () => {
|
||||
const valid = {
|
||||
id: '00000000-0000-0000-0000-000000000001',
|
||||
documentId: '00000000-0000-0000-0000-000000000002',
|
||||
actorName: 'Anna Müller',
|
||||
type: 'MENTION',
|
||||
referenceId: '00000000-0000-0000-0000-000000000003',
|
||||
annotationId: null,
|
||||
read: false,
|
||||
createdAt: '2024-06-15T10:00:00',
|
||||
documentTitle: 'Geburtsurkunde Opa Karl'
|
||||
};
|
||||
|
||||
it('should return parsed object for a valid payload', () => {
|
||||
const result = parseNotificationEvent(JSON.stringify(valid));
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.id).toBe(valid.id);
|
||||
expect(result?.actorName).toBe('Anna Müller');
|
||||
});
|
||||
|
||||
it('should return null for invalid JSON', () => {
|
||||
expect(parseNotificationEvent('not-json')).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null when id is missing', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { id, ...noId } = valid;
|
||||
expect(parseNotificationEvent(JSON.stringify(noId))).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null when documentId is missing', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { documentId, ...noDocId } = valid;
|
||||
expect(parseNotificationEvent(JSON.stringify(noDocId))).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null when actorName is missing', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { actorName, ...noActor } = valid;
|
||||
expect(parseNotificationEvent(JSON.stringify(noActor))).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null for unknown notification type', () => {
|
||||
expect(parseNotificationEvent(JSON.stringify({ ...valid, type: 'UNKNOWN' }))).toBeNull();
|
||||
});
|
||||
|
||||
it('should accept REPLY as a valid type', () => {
|
||||
const result = parseNotificationEvent(JSON.stringify({ ...valid, type: 'REPLY' }));
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.type).toBe('REPLY');
|
||||
});
|
||||
});
|
||||
42
frontend/src/lib/utils/notifications.ts
Normal file
42
frontend/src/lib/utils/notifications.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
export type NotificationItem = {
|
||||
id: string;
|
||||
type: 'REPLY' | 'MENTION';
|
||||
documentId: string;
|
||||
referenceId: string;
|
||||
annotationId: string | null;
|
||||
read: boolean;
|
||||
createdAt: string;
|
||||
actorName: string;
|
||||
documentTitle: string | null;
|
||||
};
|
||||
|
||||
const rtf = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });
|
||||
|
||||
export function relativeTime(isoString: string, now: Date = new Date()): string {
|
||||
const diffMs = now.getTime() - new Date(isoString).getTime();
|
||||
const diffMin = Math.floor(diffMs / 60_000);
|
||||
if (diffMin < 1) return rtf.format(0, 'minute');
|
||||
if (diffMin < 60) return rtf.format(-diffMin, 'minute');
|
||||
const diffH = Math.floor(diffMin / 60);
|
||||
if (diffH < 24) return rtf.format(-diffH, 'hour');
|
||||
const diffD = Math.floor(diffH / 24);
|
||||
return rtf.format(-diffD, 'day');
|
||||
}
|
||||
|
||||
export function parseNotificationEvent(raw: string): NotificationItem | null {
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (
|
||||
typeof parsed.id !== 'string' ||
|
||||
typeof parsed.documentId !== 'string' ||
|
||||
typeof parsed.actorName !== 'string' ||
|
||||
!['REPLY', 'MENTION'].includes(parsed.type)
|
||||
) {
|
||||
console.warn('Unexpected SSE payload shape:', parsed);
|
||||
return null;
|
||||
}
|
||||
return parsed as NotificationItem;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
24
frontend/src/lib/utils/personLifeDates.spec.ts
Normal file
24
frontend/src/lib/utils/personLifeDates.spec.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { formatLifeDateRange } from './personLifeDates';
|
||||
|
||||
describe('formatLifeDateRange', () => {
|
||||
it('returns both dates when birth and death year are given', () => {
|
||||
expect(formatLifeDateRange(1882, 1944)).toBe('* 1882 – † 1944');
|
||||
});
|
||||
|
||||
it('returns only birth year when only birthYear is given', () => {
|
||||
expect(formatLifeDateRange(1882, undefined)).toBe('* 1882');
|
||||
});
|
||||
|
||||
it('returns only death year when only deathYear is given', () => {
|
||||
expect(formatLifeDateRange(undefined, 1944)).toBe('† 1944');
|
||||
});
|
||||
|
||||
it('returns empty string when neither year is given', () => {
|
||||
expect(formatLifeDateRange(undefined, undefined)).toBe('');
|
||||
});
|
||||
|
||||
it('returns empty string when both are null', () => {
|
||||
expect(formatLifeDateRange(null, null)).toBe('');
|
||||
});
|
||||
});
|
||||
20
frontend/src/lib/utils/personLifeDates.ts
Normal file
20
frontend/src/lib/utils/personLifeDates.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Formats the life date range for a person.
|
||||
* Examples:
|
||||
* * 1882 – † 1944 (both)
|
||||
* * 1882 (birth only)
|
||||
* † 1944 (death only)
|
||||
* "" (neither)
|
||||
*/
|
||||
export function formatLifeDateRange(birthYear?: number | null, deathYear?: number | null): string {
|
||||
if (birthYear && deathYear) {
|
||||
return `* ${birthYear} – † ${deathYear}`;
|
||||
}
|
||||
if (birthYear) {
|
||||
return `* ${birthYear}`;
|
||||
}
|
||||
if (deathYear) {
|
||||
return `† ${deathYear}`;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
@@ -45,8 +45,11 @@ export async function load({ url, fetch }) {
|
||||
}
|
||||
|
||||
const documents: Document[] = docsResult?.data ?? [];
|
||||
const allPersons: { id: string; firstName: string; lastName: string }[] =
|
||||
personsResult.data ?? [];
|
||||
const allPersons = (personsResult.data ?? []) as {
|
||||
id: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
}[];
|
||||
|
||||
const senderObj = allPersons.find((p) => p.id === senderId);
|
||||
const receiverObj = allPersons.find((p) => p.id === receiverId);
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user