Compare commits
1 Commits
feat/issue
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 38a6d6b0fc |
@@ -15,10 +15,6 @@ public enum ErrorCode {
|
||||
ALIAS_NOT_FOUND,
|
||||
/** The submitted personType value is not allowed (e.g. SKIP is import-only). 400 */
|
||||
INVALID_PERSON_TYPE,
|
||||
/** A person's birth date is after their death date. 400 */
|
||||
BIRTH_AFTER_DEATH,
|
||||
/** A life date and its precision are incoherent: date present with UNKNOWN precision, or precision set without a date. 400 */
|
||||
INVALID_DATE_PRECISION,
|
||||
// --- Documents ---
|
||||
/** A document with the given ID does not exist. 404 */
|
||||
DOCUMENT_NOT_FOUND,
|
||||
|
||||
@@ -117,12 +117,17 @@ public class GeschichteService {
|
||||
*
|
||||
* <p>Returns a {@link GeschichteSummary} projection — never carries items, preventing
|
||||
* LazyInitializationException on the non-transactional list path.
|
||||
*
|
||||
* <p>Security: {@code null} status always resolves to PUBLISHED — even for blog writers.
|
||||
* Only an explicit {@code DRAFT} request scopes the query to the caller's own drafts.
|
||||
* This prevents CWE-639: a blog writer passing {@code null} must not see all authors' drafts.
|
||||
*/
|
||||
public List<GeschichteSummary> list(GeschichteStatus status, List<UUID> personIds, UUID documentId, int limit) {
|
||||
GeschichteStatus effective = currentUserHasBlogWrite() ? status : GeschichteStatus.PUBLISHED;
|
||||
boolean isDraftRequest = currentUserHasBlogWrite() && status == GeschichteStatus.DRAFT;
|
||||
GeschichteStatus effective = isDraftRequest ? GeschichteStatus.DRAFT : GeschichteStatus.PUBLISHED;
|
||||
int safeLimit = limit <= 0 ? DEFAULT_LIMIT : Math.min(limit, MAX_LIMIT);
|
||||
|
||||
UUID authorId = effective == GeschichteStatus.DRAFT ? currentUser().getId() : null;
|
||||
UUID authorId = isDraftRequest ? currentUser().getId() : null;
|
||||
|
||||
// When personIds is empty, personCount=0 short-circuits the IN() predicate.
|
||||
// Pass a sentinel UUID to avoid invalid empty IN() SQL while the predicate is skipped.
|
||||
|
||||
@@ -6,9 +6,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import org.raddatz.familienarchiv.document.DatePrecision;
|
||||
import org.raddatz.familienarchiv.user.DisplayNameFormatter;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
@@ -51,25 +49,8 @@ public class Person {
|
||||
@Column(columnDefinition = "TEXT")
|
||||
private String notes;
|
||||
|
||||
// Most precise birth/death date known. Precision mirrors Document.metaDatePrecision:
|
||||
// the date column is nullable, the precision column is NOT NULL with UNKNOWN meaning
|
||||
// "no date" — the V76 CHECK constraints enforce (date IS NULL) = (precision = UNKNOWN).
|
||||
// DatePrecision is imported cross-domain from document/ by design (ADR-039).
|
||||
private LocalDate birthDate;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "birth_date_precision", nullable = false, length = 16)
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@Builder.Default
|
||||
private DatePrecision birthDatePrecision = DatePrecision.UNKNOWN;
|
||||
|
||||
private LocalDate deathDate;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "death_date_precision", nullable = false, length = 16)
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@Builder.Default
|
||||
private DatePrecision deathDatePrecision = DatePrecision.UNKNOWN;
|
||||
private Integer birthYear;
|
||||
private Integer deathYear;
|
||||
|
||||
// Hand-curated generation index from canonical-persons.xlsx (G 0 = oldest).
|
||||
// Nullable for persons outside the curated family graph. Drives the
|
||||
|
||||
@@ -66,10 +66,7 @@ public interface PersonRepository extends JpaRepository<Person, UUID> {
|
||||
@Query(value = """
|
||||
SELECT p.id, p.title, p.first_name AS firstName, p.last_name AS lastName,
|
||||
p.person_type AS personType,
|
||||
p.alias, CAST(EXTRACT(YEAR FROM p.birth_date) AS int) AS birthYear,
|
||||
CAST(EXTRACT(YEAR FROM p.death_date) AS int) AS deathYear,
|
||||
p.birth_date AS birthDate, p.birth_date_precision AS birthDatePrecision,
|
||||
p.death_date AS deathDate, p.death_date_precision AS deathDatePrecision, p.notes,
|
||||
p.alias, p.birth_year AS birthYear, p.death_year AS deathYear, p.notes,
|
||||
p.family_member AS familyMember, p.provisional AS provisional,
|
||||
(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
|
||||
@@ -82,10 +79,7 @@ public interface PersonRepository extends JpaRepository<Person, UUID> {
|
||||
@Query(value = """
|
||||
SELECT p.id, p.title, p.first_name AS firstName, p.last_name AS lastName,
|
||||
p.person_type AS personType,
|
||||
p.alias, CAST(EXTRACT(YEAR FROM p.birth_date) AS int) AS birthYear,
|
||||
CAST(EXTRACT(YEAR FROM p.death_date) AS int) AS deathYear,
|
||||
p.birth_date AS birthDate, p.birth_date_precision AS birthDatePrecision,
|
||||
p.death_date AS deathDate, p.death_date_precision AS deathDatePrecision, p.notes,
|
||||
p.alias, p.birth_year AS birthYear, p.death_year AS deathYear, p.notes,
|
||||
p.family_member AS familyMember, p.provisional AS provisional,
|
||||
(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
|
||||
@@ -95,7 +89,7 @@ public interface PersonRepository extends JpaRepository<Person, UUID> {
|
||||
OR LOWER(CONCAT(p.last_name,' ',COALESCE(p.first_name,''))) LIKE LOWER(CONCAT('%',:query,'%'))
|
||||
OR LOWER(p.alias) LIKE LOWER(CONCAT('%',:query,'%'))
|
||||
OR LOWER(a.last_name) LIKE LOWER(CONCAT('%',:query,'%'))
|
||||
GROUP BY p.id, p.title, p.first_name, p.last_name, p.person_type, p.alias, p.birth_date, p.birth_date_precision, p.death_date, p.death_date_precision, p.notes, p.family_member, p.provisional
|
||||
GROUP BY p.id, p.title, p.first_name, p.last_name, p.person_type, p.alias, p.birth_year, p.death_year, p.notes, p.family_member, p.provisional
|
||||
ORDER BY p.last_name ASC, p.first_name ASC
|
||||
""",
|
||||
nativeQuery = true)
|
||||
@@ -106,10 +100,7 @@ public interface PersonRepository extends JpaRepository<Person, UUID> {
|
||||
@Query(value = """
|
||||
SELECT p.id, p.title, p.first_name AS firstName, p.last_name AS lastName,
|
||||
p.person_type AS personType,
|
||||
p.alias, CAST(EXTRACT(YEAR FROM p.birth_date) AS int) AS birthYear,
|
||||
CAST(EXTRACT(YEAR FROM p.death_date) AS int) AS deathYear,
|
||||
p.birth_date AS birthDate, p.birth_date_precision AS birthDatePrecision,
|
||||
p.death_date AS deathDate, p.death_date_precision AS deathDatePrecision, p.notes,
|
||||
p.alias, p.birth_year AS birthYear, p.death_year AS deathYear, p.notes,
|
||||
p.family_member AS familyMember, p.provisional AS provisional,
|
||||
(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
|
||||
@@ -148,10 +139,7 @@ public interface PersonRepository extends JpaRepository<Person, UUID> {
|
||||
@Query(value = """
|
||||
SELECT p.id, p.title, p.first_name AS firstName, p.last_name AS lastName,
|
||||
p.person_type AS personType,
|
||||
p.alias, CAST(EXTRACT(YEAR FROM p.birth_date) AS int) AS birthYear,
|
||||
CAST(EXTRACT(YEAR FROM p.death_date) AS int) AS deathYear,
|
||||
p.birth_date AS birthDate, p.birth_date_precision AS birthDatePrecision,
|
||||
p.death_date AS deathDate, p.death_date_precision AS deathDatePrecision, p.notes,
|
||||
p.alias, p.birth_year AS birthYear, p.death_year AS deathYear, p.notes,
|
||||
p.family_member AS familyMember, p.provisional AS provisional,
|
||||
(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
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package org.raddatz.familienarchiv.person;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -17,7 +16,6 @@ import org.springframework.lang.Nullable;
|
||||
import org.raddatz.familienarchiv.person.PersonNameAliasDTO;
|
||||
import org.raddatz.familienarchiv.person.PersonSummaryDTO;
|
||||
import org.raddatz.familienarchiv.person.PersonUpdateDTO;
|
||||
import org.raddatz.familienarchiv.document.DatePrecision;
|
||||
import org.raddatz.familienarchiv.exception.DomainException;
|
||||
import org.raddatz.familienarchiv.exception.ErrorCode;
|
||||
import org.raddatz.familienarchiv.person.Person;
|
||||
@@ -301,20 +299,13 @@ public class PersonService {
|
||||
}
|
||||
|
||||
private Person fromCanonical(PersonUpsertCommand cmd) {
|
||||
DatePrecisionPair none = new DatePrecisionPair(null, DatePrecision.UNKNOWN);
|
||||
LifeDates dates = degradeIfConflicting(
|
||||
yearPair(cmd.birthYear()), yearPair(cmd.deathYear()), none, none, cmd.sourceRef());
|
||||
DatePrecisionPair birth = dates.birth();
|
||||
DatePrecisionPair death = dates.death();
|
||||
Person person = personRepository.save(Person.builder()
|
||||
.sourceRef(cmd.sourceRef())
|
||||
.firstName(blankToNull(cmd.firstName()))
|
||||
.lastName(cmd.lastName())
|
||||
.notes(blankToNull(cmd.notes()))
|
||||
.birthDate(birth.date())
|
||||
.birthDatePrecision(birth.precision())
|
||||
.deathDate(death.date())
|
||||
.deathDatePrecision(death.precision())
|
||||
.birthYear(cmd.birthYear())
|
||||
.deathYear(cmd.deathYear())
|
||||
.generation(cmd.generation())
|
||||
.familyMember(cmd.familyMember())
|
||||
.personType(cmd.personType() == null ? PersonType.PERSON : cmd.personType())
|
||||
@@ -337,16 +328,8 @@ public class PersonService {
|
||||
existing.setFirstName(preferHuman(existing.getFirstName(), cmd.firstName()));
|
||||
existing.setLastName(preferHuman(existing.getLastName(), cmd.lastName()));
|
||||
existing.setNotes(preferHuman(existing.getNotes(), cmd.notes()));
|
||||
LifeDates dates = degradeIfConflicting(
|
||||
preferHumanDate(existing.getBirthDate(), existing.getBirthDatePrecision(), cmd.birthYear()),
|
||||
preferHumanDate(existing.getDeathDate(), existing.getDeathDatePrecision(), cmd.deathYear()),
|
||||
new DatePrecisionPair(existing.getBirthDate(), existing.getBirthDatePrecision()),
|
||||
new DatePrecisionPair(existing.getDeathDate(), existing.getDeathDatePrecision()),
|
||||
cmd.sourceRef());
|
||||
existing.setBirthDate(dates.birth().date());
|
||||
existing.setBirthDatePrecision(dates.birth().precision());
|
||||
existing.setDeathDate(dates.death().date());
|
||||
existing.setDeathDatePrecision(dates.death().precision());
|
||||
existing.setBirthYear(preferHuman(existing.getBirthYear(), cmd.birthYear()));
|
||||
existing.setDeathYear(preferHuman(existing.getDeathYear(), cmd.deathYear()));
|
||||
existing.setGeneration(preferHuman(existing.getGeneration(), cmd.generation()));
|
||||
if (cmd.personType() != null && existing.getPersonType() == PersonType.PERSON) {
|
||||
existing.setPersonType(cmd.personType());
|
||||
@@ -373,48 +356,6 @@ public class PersonService {
|
||||
return existing != null ? existing : canonical;
|
||||
}
|
||||
|
||||
// Date + precision travel as one value so they can never go out of sync (ADR-039).
|
||||
record DatePrecisionPair(LocalDate date, DatePrecision precision) {}
|
||||
|
||||
record LifeDates(DatePrecisionPair birth, DatePrecisionPair death) {}
|
||||
|
||||
// The canonical path skips validateLifeDates (the form-only guard), so a conflicting
|
||||
// resolved pair would hit chk_person_birth_before_death at flush time and abort the
|
||||
// whole import batch with a raw 500. Degrade instead (REQ-IMP-001: never abort the
|
||||
// batch): keep the person's stored life dates — empty for a new person — and drop the
|
||||
// conflicting canonical refresh. A hand-entered side is preserved by construction,
|
||||
// since preferHumanDate returned it verbatim and it equals the stored value; two
|
||||
// stored values can never conflict with each other (they already satisfied the CHECK).
|
||||
static LifeDates degradeIfConflicting(DatePrecisionPair birth, DatePrecisionPair death,
|
||||
DatePrecisionPair existingBirth, DatePrecisionPair existingDeath,
|
||||
String sourceRef) {
|
||||
if (birth.date() == null || death.date() == null || !birth.date().isAfter(death.date())) {
|
||||
return new LifeDates(birth, death);
|
||||
}
|
||||
log.warn("Conflicting canonical life dates for {}: birth {} is after death {} — keeping stored values",
|
||||
sourceRef, birth.date(), death.date());
|
||||
return new LifeDates(existingBirth, existingDeath);
|
||||
}
|
||||
|
||||
// preferHuman for life dates (ADR-025 extension): a hand-entered date more precise than
|
||||
// the spreadsheet's year (DAY/MONTH/SEASON/RANGE/APPROX) is preserved on re-import; a
|
||||
// YEAR-precision or absent date is refreshed from the canonical year.
|
||||
static DatePrecisionPair preferHumanDate(LocalDate existingDate, DatePrecision existingPrecision,
|
||||
Integer canonicalYear) {
|
||||
boolean handEntered = existingDate != null && existingPrecision != null
|
||||
&& existingPrecision != DatePrecision.YEAR && existingPrecision != DatePrecision.UNKNOWN;
|
||||
if (handEntered) {
|
||||
return new DatePrecisionPair(existingDate, existingPrecision);
|
||||
}
|
||||
return yearPair(canonicalYear);
|
||||
}
|
||||
|
||||
private static DatePrecisionPair yearPair(Integer year) {
|
||||
return year != null
|
||||
? new DatePrecisionPair(LocalDate.of(year, 1, 1), DatePrecision.YEAR)
|
||||
: new DatePrecisionPair(null, DatePrecision.UNKNOWN);
|
||||
}
|
||||
|
||||
private static String blankToNull(String s) {
|
||||
return (s == null || s.isBlank()) ? null : s.trim();
|
||||
}
|
||||
@@ -434,8 +375,7 @@ public class PersonService {
|
||||
if (dto.getPersonType() == PersonType.SKIP) {
|
||||
throw DomainException.badRequest(ErrorCode.INVALID_PERSON_TYPE, "SKIP is not a valid person type for manual creation");
|
||||
}
|
||||
validateLifeDates(dto.getBirthDate(), dto.getBirthDatePrecision(),
|
||||
dto.getDeathDate(), dto.getDeathDatePrecision());
|
||||
validateYears(dto.getBirthYear(), dto.getDeathYear());
|
||||
Person person = Person.builder()
|
||||
.personType(dto.getPersonType())
|
||||
.title(dto.getTitle() == null || dto.getTitle().isBlank() ? null : dto.getTitle().trim())
|
||||
@@ -443,49 +383,31 @@ public class PersonService {
|
||||
.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())
|
||||
.birthDate(dto.getBirthDate())
|
||||
.birthDatePrecision(normalizePrecision(dto.getBirthDatePrecision()))
|
||||
.deathDate(dto.getDeathDate())
|
||||
.deathDatePrecision(normalizePrecision(dto.getDeathDatePrecision()))
|
||||
.birthYear(dto.getBirthYear())
|
||||
.deathYear(dto.getDeathYear())
|
||||
.generation(dto.getGeneration())
|
||||
.build();
|
||||
return personRepository.save(person);
|
||||
}
|
||||
|
||||
// Cross-field invariants the V76 CHECK constraints also enforce — validated here so the
|
||||
// user gets a structured ErrorCode instead of a raw constraint-violation 500.
|
||||
private void validateLifeDates(LocalDate birthDate, DatePrecision birthPrecision,
|
||||
LocalDate deathDate, DatePrecision deathPrecision) {
|
||||
requireDatePrecisionCoherence(birthDate, birthPrecision, "birth");
|
||||
requireDatePrecisionCoherence(deathDate, deathPrecision, "death");
|
||||
if (birthDate != null && deathDate != null && birthDate.isAfter(deathDate)) {
|
||||
throw DomainException.badRequest(ErrorCode.BIRTH_AFTER_DEATH,
|
||||
"Birth date " + birthDate + " is after death date " + deathDate);
|
||||
private void validateYears(Integer birthYear, Integer deathYear) {
|
||||
if (birthYear != null && birthYear <= 0) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Geburtsjahr muss eine positive Zahl sein");
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireDatePrecisionCoherence(LocalDate date, DatePrecision precision, String side) {
|
||||
if (date != null && (precision == null || precision == DatePrecision.UNKNOWN)) {
|
||||
throw DomainException.badRequest(ErrorCode.INVALID_DATE_PRECISION,
|
||||
side + " date is set but its precision is missing or UNKNOWN");
|
||||
if (deathYear != null && deathYear <= 0) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Todesjahr muss eine positive Zahl sein");
|
||||
}
|
||||
if (date == null && precision != null && precision != DatePrecision.UNKNOWN) {
|
||||
throw DomainException.badRequest(ErrorCode.INVALID_DATE_PRECISION,
|
||||
side + " date precision " + precision + " is set without a date");
|
||||
if (birthYear != null && deathYear != null && birthYear > deathYear) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Geburtsjahr darf nicht nach dem Todesjahr liegen");
|
||||
}
|
||||
}
|
||||
|
||||
private static DatePrecision normalizePrecision(DatePrecision precision) {
|
||||
return precision == null ? DatePrecision.UNKNOWN : precision;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Person updatePerson(UUID id, PersonUpdateDTO dto) {
|
||||
if (dto.getPersonType() == PersonType.SKIP) {
|
||||
throw DomainException.badRequest(ErrorCode.INVALID_PERSON_TYPE, "SKIP is not a valid person type for manual editing");
|
||||
}
|
||||
validateLifeDates(dto.getBirthDate(), dto.getBirthDatePrecision(),
|
||||
dto.getDeathDate(), dto.getDeathDatePrecision());
|
||||
validateYears(dto.getBirthYear(), dto.getDeathYear());
|
||||
Person person = personRepository.findById(id)
|
||||
.orElseThrow(() -> DomainException.notFound(ErrorCode.PERSON_NOT_FOUND, "Person not found: " + id));
|
||||
person.setPersonType(dto.getPersonType());
|
||||
@@ -494,10 +416,8 @@ public class PersonService {
|
||||
person.setLastName(dto.getLastName());
|
||||
person.setAlias(dto.getAlias() == null || dto.getAlias().isBlank() ? null : dto.getAlias().trim());
|
||||
person.setNotes(dto.getNotes() == null || dto.getNotes().isBlank() ? null : dto.getNotes().trim());
|
||||
person.setBirthDate(dto.getBirthDate());
|
||||
person.setBirthDatePrecision(normalizePrecision(dto.getBirthDatePrecision()));
|
||||
person.setDeathDate(dto.getDeathDate());
|
||||
person.setDeathDatePrecision(normalizePrecision(dto.getDeathDatePrecision()));
|
||||
person.setBirthYear(dto.getBirthYear());
|
||||
person.setDeathYear(dto.getDeathYear());
|
||||
// Form path: a human can clear generation back to null. Unlike the importer
|
||||
// which routes through preferHuman, we write the DTO value verbatim.
|
||||
person.setGeneration(dto.getGeneration());
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
package org.raddatz.familienarchiv.person;
|
||||
|
||||
import org.raddatz.familienarchiv.document.DatePrecision;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
@@ -19,13 +16,6 @@ public interface PersonSummaryDTO {
|
||||
String getAlias();
|
||||
Integer getBirthYear();
|
||||
Integer getDeathYear();
|
||||
// Full date + precision alongside the derived years: list consumers that render
|
||||
// precise life dates (mention dropdown) read these; year-only consumers keep
|
||||
// the cheaper getBirthYear/getDeathYear.
|
||||
LocalDate getBirthDate();
|
||||
DatePrecision getBirthDatePrecision();
|
||||
LocalDate getDeathDate();
|
||||
DatePrecision getDeathDatePrecision();
|
||||
String getNotes();
|
||||
boolean isFamilyMember();
|
||||
boolean isProvisional();
|
||||
|
||||
@@ -5,11 +5,8 @@ import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
import org.raddatz.familienarchiv.document.DatePrecision;
|
||||
import org.raddatz.familienarchiv.person.PersonType;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Data
|
||||
public class PersonUpdateDTO {
|
||||
@NotNull
|
||||
@@ -24,10 +21,8 @@ public class PersonUpdateDTO {
|
||||
private String alias;
|
||||
@Size(max = 5000)
|
||||
private String notes;
|
||||
private LocalDate birthDate;
|
||||
private DatePrecision birthDatePrecision;
|
||||
private LocalDate deathDate;
|
||||
private DatePrecision deathDatePrecision;
|
||||
private Integer birthYear;
|
||||
private Integer deathYear;
|
||||
// Mirror of the persons.generation CHECK constraint (V70). Bounds live in
|
||||
// PersonGeneration so DB, DTO, and importer all read from one place.
|
||||
@Min(PersonGeneration.MIN_GENERATION)
|
||||
|
||||
@@ -96,9 +96,7 @@ public class RelationshipInferenceService {
|
||||
if (p == null) continue;
|
||||
List<RelationToken> path = shortestPaths.get(id);
|
||||
PersonNodeDTO node = new PersonNodeDTO(
|
||||
p.getId(), p.getDisplayName(),
|
||||
RelationshipService.yearOf(p.getBirthDate()),
|
||||
RelationshipService.yearOf(p.getDeathDate()),
|
||||
p.getId(), p.getDisplayName(), p.getBirthYear(), p.getDeathYear(),
|
||||
p.getGeneration(), p.isFamilyMember());
|
||||
out.add(new InferredRelationshipWithPersonDTO(node, labelFor(path), path.size()));
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
@@ -67,8 +66,7 @@ public class RelationshipService {
|
||||
for (Person p : familyMembers) {
|
||||
familyIds.add(p.getId());
|
||||
nodes.add(new PersonNodeDTO(
|
||||
p.getId(), p.getDisplayName(),
|
||||
yearOf(p.getBirthDate()), yearOf(p.getDeathDate()),
|
||||
p.getId(), p.getDisplayName(), p.getBirthYear(), p.getDeathYear(),
|
||||
p.getGeneration(), true));
|
||||
}
|
||||
|
||||
@@ -157,13 +155,6 @@ public class RelationshipService {
|
||||
return (s == null || s.isBlank()) ? null : s.trim();
|
||||
}
|
||||
|
||||
// Stammbaum DTOs stay year-shaped: derive the year from the LocalDate, null-safe
|
||||
// for persons with no date entered (ADR-039, REQ-PERSON-DATE-01). Package-private
|
||||
// so RelationshipInferenceService shares the same derivation.
|
||||
static Integer yearOf(LocalDate date) {
|
||||
return date != null ? date.getYear() : null;
|
||||
}
|
||||
|
||||
private static void validateYears(Integer fromYear, Integer toYear) {
|
||||
if (fromYear != null && toYear != null && toYear < fromYear) {
|
||||
throw DomainException.badRequest(
|
||||
@@ -179,11 +170,11 @@ public class RelationshipService {
|
||||
p.getId(),
|
||||
rp.getId(),
|
||||
p.getDisplayName(),
|
||||
yearOf(p.getBirthDate()),
|
||||
yearOf(p.getDeathDate()),
|
||||
p.getBirthYear(),
|
||||
p.getDeathYear(),
|
||||
rp.getDisplayName(),
|
||||
yearOf(rp.getBirthDate()),
|
||||
yearOf(rp.getDeathDate()),
|
||||
rp.getBirthYear(),
|
||||
rp.getDeathYear(),
|
||||
r.getRelationType(),
|
||||
r.getFromYear(),
|
||||
r.getToYear(),
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
-- V76: persons.birth_year/death_year (integer) → birth_date/death_date (date)
|
||||
-- plus NOT NULL precision columns mirroring documents.meta_date_precision.
|
||||
-- Existing years are backfilled as YYYY-01-01 at YEAR precision (ADR-039).
|
||||
-- One-way migration: rollback is a targeted pg_restore -t persons from the
|
||||
-- pre-deploy backup (see docs/DEPLOYMENT.md).
|
||||
|
||||
-- Pre-check (data quality gate — not a race guard): abort on corrupt year data
|
||||
-- before any DDL runs. Single-writer family archive, so no race window matters.
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (SELECT 1 FROM persons WHERE birth_year IS NOT NULL AND death_year IS NOT NULL AND birth_year > death_year)
|
||||
THEN RAISE EXCEPTION 'V76 aborted: % persons have birth_year > death_year — fix data before migrating',
|
||||
(SELECT COUNT(*) FROM persons WHERE birth_year IS NOT NULL AND death_year IS NOT NULL AND birth_year > death_year);
|
||||
END IF;
|
||||
IF EXISTS (SELECT 1 FROM persons WHERE birth_year = 0 OR death_year = 0)
|
||||
THEN RAISE EXCEPTION 'V76 aborted: persons table contains birth_year=0 or death_year=0 rows — clean data before migrating';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
ALTER TABLE persons ADD COLUMN birth_date date;
|
||||
ALTER TABLE persons ADD COLUMN birth_date_precision varchar(16) NOT NULL DEFAULT 'UNKNOWN';
|
||||
ALTER TABLE persons ADD COLUMN death_date date;
|
||||
ALTER TABLE persons ADD COLUMN death_date_precision varchar(16) NOT NULL DEFAULT 'UNKNOWN';
|
||||
|
||||
UPDATE persons SET birth_date = make_date(birth_year, 1, 1), birth_date_precision = 'YEAR'
|
||||
WHERE birth_year IS NOT NULL;
|
||||
UPDATE persons SET death_date = make_date(death_year, 1, 1), death_date_precision = 'YEAR'
|
||||
WHERE death_year IS NOT NULL;
|
||||
|
||||
-- Named constraints: readable Postgres error messages when violated.
|
||||
ALTER TABLE persons ADD CONSTRAINT chk_person_birth_before_death
|
||||
CHECK (death_date IS NULL OR birth_date IS NULL OR birth_date <= death_date);
|
||||
ALTER TABLE persons ADD CONSTRAINT chk_person_birth_date_precision_coherence
|
||||
CHECK ((birth_date IS NULL) = (birth_date_precision = 'UNKNOWN'));
|
||||
ALTER TABLE persons ADD CONSTRAINT chk_person_birth_date_precision_values
|
||||
CHECK (birth_date_precision IN ('DAY', 'MONTH', 'SEASON', 'YEAR', 'RANGE', 'APPROX', 'UNKNOWN'));
|
||||
ALTER TABLE persons ADD CONSTRAINT chk_person_death_date_precision_coherence
|
||||
CHECK ((death_date IS NULL) = (death_date_precision = 'UNKNOWN'));
|
||||
ALTER TABLE persons ADD CONSTRAINT chk_person_death_date_precision_values
|
||||
CHECK (death_date_precision IN ('DAY', 'MONTH', 'SEASON', 'YEAR', 'RANGE', 'APPROX', 'UNKNOWN'));
|
||||
|
||||
ALTER TABLE persons DROP COLUMN birth_year;
|
||||
ALTER TABLE persons DROP COLUMN death_year;
|
||||
@@ -2,6 +2,7 @@ package org.raddatz.familienarchiv.geschichte;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
@@ -35,6 +36,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -228,21 +230,7 @@ class GeschichteServiceTest {
|
||||
|
||||
geschichteService.list(null, List.of(), null, 50);
|
||||
|
||||
verify(geschichteRepository).findSummaries(any(), any(), any(), anyLong(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_passes_null_status_through_for_BLOG_WRITER_so_drafts_are_visible() {
|
||||
authenticateAs(writer, Permission.BLOG_WRITE);
|
||||
GeschichteSummary s1 = mock(GeschichteSummary.class);
|
||||
GeschichteSummary s2 = mock(GeschichteSummary.class);
|
||||
when(geschichteRepository.findSummaries(any(), any(), any(), anyLong(), any()))
|
||||
.thenReturn(List.of(s1, s2));
|
||||
|
||||
List<GeschichteSummary> out = geschichteService.list(null, List.of(), null, 50);
|
||||
|
||||
assertThat(out).hasSize(2);
|
||||
verify(geschichteRepository).findSummaries(any(), any(), any(), anyLong(), any());
|
||||
verify(geschichteRepository).findSummaries(eq(GeschichteStatus.PUBLISHED), isNull(), any(), anyLong(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -308,6 +296,33 @@ class GeschichteServiceTest {
|
||||
assertThat(out).hasSizeLessThanOrEqualTo(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("security: null status for blog writer returns PUBLISHED, never leaks drafts")
|
||||
void list_with_blog_writer_and_null_status_returns_PUBLISHED_not_all_drafts() {
|
||||
authenticateAs(writer, Permission.BLOG_WRITE);
|
||||
when(geschichteRepository.findSummaries(any(), any(), any(), anyLong(), any()))
|
||||
.thenReturn(List.of());
|
||||
|
||||
geschichteService.list(null, List.of(), null, 50);
|
||||
|
||||
verify(geschichteRepository).findSummaries(
|
||||
eq(GeschichteStatus.PUBLISHED), isNull(), any(), anyLong(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("security: DRAFT status scopes to current user only")
|
||||
void list_with_DRAFT_status_scopes_to_current_user_not_all_authors() {
|
||||
authenticateAs(writer, Permission.BLOG_WRITE);
|
||||
when(userService.findByEmail(writer.getEmail())).thenReturn(writer);
|
||||
when(geschichteRepository.findSummaries(any(), any(), any(), anyLong(), any()))
|
||||
.thenReturn(List.of());
|
||||
|
||||
geschichteService.list(GeschichteStatus.DRAFT, List.of(), null, 50);
|
||||
|
||||
verify(geschichteRepository).findSummaries(
|
||||
eq(GeschichteStatus.DRAFT), eq(writer.getId()), any(), anyLong(), any());
|
||||
}
|
||||
|
||||
// ─── create ──────────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,244 +0,0 @@
|
||||
package org.raddatz.familienarchiv.person;
|
||||
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.testcontainers.containers.PostgreSQLContainer;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
/**
|
||||
* Verifies V76: persons.birth_year/death_year (integer) become
|
||||
* birth_date/death_date (date) + *_date_precision columns, with backfill to
|
||||
* YYYY-01-01 at YEAR precision, named CHECK constraints, and a data-quality
|
||||
* pre-check that aborts the migration on corrupt year data.
|
||||
*
|
||||
* <p>Runs Flyway programmatically (no Spring context): each test gets its own
|
||||
* database so the staged migrate-to-V75 → seed → migrate-to-latest flow and
|
||||
* the abort cases cannot interfere with each other.
|
||||
*/
|
||||
class PersonBirthDeathMigrationTest {
|
||||
|
||||
private static final PostgreSQLContainer<?> POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine");
|
||||
private static final AtomicInteger DB_COUNTER = new AtomicInteger();
|
||||
|
||||
private String dbUrl;
|
||||
|
||||
@BeforeAll
|
||||
static void startContainer() {
|
||||
POSTGRES.start();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopContainer() {
|
||||
POSTGRES.stop();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void createFreshDatabase() throws SQLException {
|
||||
String dbName = "mig_v76_" + DB_COUNTER.incrementAndGet();
|
||||
try (Connection conn = DriverManager.getConnection(
|
||||
baseUrl("postgres"), POSTGRES.getUsername(), POSTGRES.getPassword());
|
||||
Statement stmt = conn.createStatement()) {
|
||||
stmt.execute("CREATE DATABASE " + dbName);
|
||||
}
|
||||
dbUrl = baseUrl(dbName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void precheck_abortsWhenBirthYearAfterDeathYear() throws SQLException {
|
||||
migrateTo("75");
|
||||
seedPerson("Corrupt", 1950, 1940);
|
||||
|
||||
assertThatThrownBy(this::migrateToLatest)
|
||||
.hasMessageContaining("V76 aborted")
|
||||
.hasMessageContaining("birth_year > death_year");
|
||||
}
|
||||
|
||||
@Test
|
||||
void precheck_abortsWhenYearZeroPresent() throws SQLException {
|
||||
migrateTo("75");
|
||||
seedPerson("Zero", 0, null);
|
||||
|
||||
assertThatThrownBy(this::migrateToLatest)
|
||||
.hasMessageContaining("V76 aborted")
|
||||
.hasMessageContaining("birth_year=0 or death_year=0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void backfill_birthOnly_becomesYearPrecisionDate_deathStaysUnknown() throws SQLException {
|
||||
migrateTo("75");
|
||||
seedPerson("BirthOnly", 1901, null);
|
||||
|
||||
migrateToLatest();
|
||||
|
||||
LifeDates row = lifeDates("BirthOnly");
|
||||
assertThat(row.birthDate()).hasToString("1901-01-01");
|
||||
assertThat(row.birthPrecision()).isEqualTo("YEAR");
|
||||
assertThat(row.deathDate()).isNull();
|
||||
assertThat(row.deathPrecision()).isEqualTo("UNKNOWN");
|
||||
}
|
||||
|
||||
@Test
|
||||
void backfill_deathOnly_becomesYearPrecisionDate_birthStaysUnknown() throws SQLException {
|
||||
migrateTo("75");
|
||||
seedPerson("DeathOnly", null, 1944);
|
||||
|
||||
migrateToLatest();
|
||||
|
||||
LifeDates row = lifeDates("DeathOnly");
|
||||
assertThat(row.birthDate()).isNull();
|
||||
assertThat(row.birthPrecision()).isEqualTo("UNKNOWN");
|
||||
assertThat(row.deathDate()).hasToString("1944-01-01");
|
||||
assertThat(row.deathPrecision()).isEqualTo("YEAR");
|
||||
}
|
||||
|
||||
@Test
|
||||
void backfill_bothNull_leavesDatesNullAndPrecisionsUnknown() throws SQLException {
|
||||
migrateTo("75");
|
||||
seedPerson("NoDates", null, null);
|
||||
|
||||
migrateToLatest();
|
||||
|
||||
LifeDates row = lifeDates("NoDates");
|
||||
assertThat(row.birthDate()).isNull();
|
||||
assertThat(row.birthPrecision()).isEqualTo("UNKNOWN");
|
||||
assertThat(row.deathDate()).isNull();
|
||||
assertThat(row.deathPrecision()).isEqualTo("UNKNOWN");
|
||||
}
|
||||
|
||||
@Test
|
||||
void backfill_neverProducesBirthDateAfterDeathDate() throws SQLException {
|
||||
migrateTo("75");
|
||||
seedPerson("SameYear", 1901, 1901);
|
||||
seedPerson("Ordered", 1899, 1972);
|
||||
|
||||
migrateToLatest();
|
||||
|
||||
assertThat(countWhere("birth_date IS NOT NULL AND death_date IS NOT NULL AND birth_date > death_date"))
|
||||
.isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void yearColumnsDropped_andNamedCheckConstraintsExist() throws SQLException {
|
||||
migrateTo("75");
|
||||
seedPerson("Schema", 1901, 1944);
|
||||
|
||||
migrateToLatest();
|
||||
|
||||
assertThat(columnExists("birth_year")).isFalse();
|
||||
assertThat(columnExists("death_year")).isFalse();
|
||||
assertThat(columnExists("birth_date")).isTrue();
|
||||
assertThat(columnExists("death_date")).isTrue();
|
||||
for (String constraint : new String[]{
|
||||
"chk_person_birth_before_death",
|
||||
"chk_person_birth_date_precision_coherence",
|
||||
"chk_person_birth_date_precision_values",
|
||||
"chk_person_death_date_precision_coherence",
|
||||
"chk_person_death_date_precision_values"}) {
|
||||
assertThat(constraintExists(constraint)).as(constraint).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
// --- helpers ---
|
||||
|
||||
private static String baseUrl(String dbName) {
|
||||
return "jdbc:postgresql://" + POSTGRES.getHost() + ":" + POSTGRES.getMappedPort(5432) + "/" + dbName;
|
||||
}
|
||||
|
||||
private void migrateTo(String targetVersion) {
|
||||
flywayBuilder().target(targetVersion).load().migrate();
|
||||
}
|
||||
|
||||
private void migrateToLatest() {
|
||||
flywayBuilder().load().migrate();
|
||||
}
|
||||
|
||||
private org.flywaydb.core.api.configuration.FluentConfiguration flywayBuilder() {
|
||||
return Flyway.configure()
|
||||
.dataSource(dbUrl, POSTGRES.getUsername(), POSTGRES.getPassword())
|
||||
.locations("classpath:db/migration")
|
||||
.placeholders(Map.of("grafanaDbPassword", "test-only"));
|
||||
}
|
||||
|
||||
private void seedPerson(String lastName, Integer birthYear, Integer deathYear) throws SQLException {
|
||||
try (Connection conn = connect();
|
||||
PreparedStatement stmt = conn.prepareStatement(
|
||||
"INSERT INTO persons (id, last_name, person_type, family_member, provisional, birth_year, death_year) "
|
||||
+ "VALUES (gen_random_uuid(), ?, 'PERSON', false, false, ?, ?)")) {
|
||||
stmt.setString(1, lastName);
|
||||
stmt.setObject(2, birthYear);
|
||||
stmt.setObject(3, deathYear);
|
||||
stmt.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
private record LifeDates(Object birthDate, String birthPrecision, Object deathDate, String deathPrecision) {}
|
||||
|
||||
private LifeDates lifeDates(String lastName) throws SQLException {
|
||||
try (Connection conn = connect();
|
||||
PreparedStatement stmt = conn.prepareStatement(
|
||||
"SELECT birth_date, birth_date_precision, death_date, death_date_precision "
|
||||
+ "FROM persons WHERE last_name = ?")) {
|
||||
stmt.setString(1, lastName);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
assertThat(rs.next()).as("person %s exists", lastName).isTrue();
|
||||
return new LifeDates(
|
||||
rs.getObject("birth_date"),
|
||||
rs.getString("birth_date_precision"),
|
||||
rs.getObject("death_date"),
|
||||
rs.getString("death_date_precision"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private long countWhere(String condition) throws SQLException {
|
||||
try (Connection conn = connect();
|
||||
Statement stmt = conn.createStatement();
|
||||
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM persons WHERE " + condition)) {
|
||||
rs.next();
|
||||
return rs.getLong(1);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean columnExists(String columnName) throws SQLException {
|
||||
try (Connection conn = connect();
|
||||
PreparedStatement stmt = conn.prepareStatement(
|
||||
"SELECT COUNT(*) FROM information_schema.columns "
|
||||
+ "WHERE table_schema = 'public' AND table_name = 'persons' AND column_name = ?")) {
|
||||
stmt.setString(1, columnName);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
rs.next();
|
||||
return rs.getInt(1) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean constraintExists(String constraintName) throws SQLException {
|
||||
try (Connection conn = connect();
|
||||
PreparedStatement stmt = conn.prepareStatement(
|
||||
"SELECT COUNT(*) FROM pg_constraint WHERE conname = ?")) {
|
||||
stmt.setString(1, constraintName);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
rs.next();
|
||||
return rs.getInt(1) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Connection connect() throws SQLException {
|
||||
return DriverManager.getConnection(dbUrl, POSTGRES.getUsername(), POSTGRES.getPassword());
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.raddatz.familienarchiv.exception.DomainException;
|
||||
import org.raddatz.familienarchiv.exception.ErrorCode;
|
||||
import org.raddatz.familienarchiv.document.DatePrecision;
|
||||
import org.raddatz.familienarchiv.document.Document;
|
||||
import org.raddatz.familienarchiv.person.Person;
|
||||
import org.raddatz.familienarchiv.person.PersonNameAlias;
|
||||
@@ -23,7 +22,6 @@ 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 java.time.LocalDate;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
@@ -217,14 +215,6 @@ class PersonControllerTest {
|
||||
public String getAlias() { return null; }
|
||||
public Integer getBirthYear() { return null; }
|
||||
public Integer getDeathYear() { return null; }
|
||||
public java.time.LocalDate getBirthDate() { return null; }
|
||||
public org.raddatz.familienarchiv.document.DatePrecision getBirthDatePrecision() {
|
||||
return org.raddatz.familienarchiv.document.DatePrecision.UNKNOWN;
|
||||
}
|
||||
public java.time.LocalDate getDeathDate() { return null; }
|
||||
public org.raddatz.familienarchiv.document.DatePrecision getDeathDatePrecision() {
|
||||
return org.raddatz.familienarchiv.document.DatePrecision.UNKNOWN;
|
||||
}
|
||||
public String getNotes() { return null; }
|
||||
public boolean isFamilyMember() { return false; }
|
||||
public boolean isProvisional() { return false; }
|
||||
@@ -582,53 +572,18 @@ class PersonControllerTest {
|
||||
void createPerson_returns200_withAllSixFields() throws Exception {
|
||||
UUID id = UUID.randomUUID();
|
||||
Person saved = Person.builder().id(id).firstName("Maria").lastName("Raddatz")
|
||||
.alias("Oma Maria")
|
||||
.birthDate(LocalDate.of(1901, 3, 14)).birthDatePrecision(DatePrecision.DAY)
|
||||
.deathDate(LocalDate.of(1975, 1, 1)).deathDatePrecision(DatePrecision.YEAR)
|
||||
.notes("Some notes").build();
|
||||
.alias("Oma Maria").birthYear(1901).deathYear(1975).notes("Some notes").build();
|
||||
when(personService.createPerson(any(org.raddatz.familienarchiv.person.PersonUpdateDTO.class))).thenReturn(saved);
|
||||
|
||||
mockMvc.perform(post("/api/persons").with(csrf())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"firstName\":\"Maria\",\"lastName\":\"Raddatz\"," +
|
||||
"\"alias\":\"Oma Maria\"," +
|
||||
"\"birthDate\":\"1901-03-14\",\"birthDatePrecision\":\"DAY\"," +
|
||||
"\"deathDate\":\"1975-01-01\",\"deathDatePrecision\":\"YEAR\"," +
|
||||
"\"alias\":\"Oma Maria\",\"birthYear\":1901,\"deathYear\":1975," +
|
||||
"\"notes\":\"Some notes\",\"personType\":\"PERSON\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.firstName").value("Maria"))
|
||||
.andExpect(jsonPath("$.alias").value("Oma Maria"))
|
||||
.andExpect(jsonPath("$.birthDate").value("1901-03-14"))
|
||||
.andExpect(jsonPath("$.birthDatePrecision").value("DAY"));
|
||||
}
|
||||
|
||||
// ─── #773: malformed date payloads return structured 400s, not Jackson traces ──
|
||||
// Jackson rejects unknown enum values by default. Verified 2026-06-12: the only
|
||||
// DeserializationFeature hit in src/main is RestClientOcrClient's private ObjectMapper
|
||||
// (OCR HTTP client) — the Spring MVC mapper has no READ_UNKNOWN_ENUM_VALUES_* override.
|
||||
|
||||
@Test
|
||||
@WithMockUser(authorities = "WRITE_ALL")
|
||||
void updatePerson_returns400WithStructuredErrorCode_whenPrecisionEnumInvalid() throws Exception {
|
||||
UUID id = UUID.randomUUID();
|
||||
mockMvc.perform(put("/api/persons/{id}", id).with(csrf())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"firstName\":\"Hans\",\"lastName\":\"Müller\",\"personType\":\"PERSON\"," +
|
||||
"\"birthDate\":\"1901-03-14\",\"birthDatePrecision\":\"INVALID_VALUE\"}"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.code").value("VALIDATION_ERROR"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(authorities = "WRITE_ALL")
|
||||
void updatePerson_returns400WithStructuredErrorCode_whenBirthDateNotADate() throws Exception {
|
||||
UUID id = UUID.randomUUID();
|
||||
mockMvc.perform(put("/api/persons/{id}", id).with(csrf())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"firstName\":\"Hans\",\"lastName\":\"Müller\",\"personType\":\"PERSON\"," +
|
||||
"\"birthDate\":\"not-a-date\",\"birthDatePrecision\":\"DAY\"}"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.code").value("VALIDATION_ERROR"));
|
||||
.andExpect(jsonPath("$.birthYear").value(1901));
|
||||
}
|
||||
|
||||
// ─── Phase 1.2: @Size constraints ─────────────────────────────────────────
|
||||
|
||||
@@ -5,9 +5,7 @@ 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.document.DatePrecision;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -99,120 +97,24 @@ class PersonImportUpsertTest {
|
||||
assertThat(result.getNotes()).isEqualTo("Nichte von Herbert");
|
||||
}
|
||||
|
||||
// ─── life dates (ADR-025 extension via preferHumanDate, #773) ─────────────
|
||||
|
||||
@Test
|
||||
void upsertBySourceRef_preservesDayPrecisionDate_onReimportWithDifferentYear() {
|
||||
// A human entered the exact birthday in-app; the spreadsheet only knows a year.
|
||||
Person handDated = Person.builder()
|
||||
.id(UUID.randomUUID()).sourceRef("clara-cram").lastName("Cram")
|
||||
.birthDate(LocalDate.of(1890, 3, 14)).birthDatePrecision(DatePrecision.DAY).build();
|
||||
when(personRepository.findBySourceRef("clara-cram")).thenReturn(Optional.of(handDated));
|
||||
void upsertBySourceRef_fillsBlankYears_butPreservesHumanEditedYears_onReimport() {
|
||||
// Existing has a human-set birthYear and a blank deathYear.
|
||||
Person existing = Person.builder()
|
||||
.id(UUID.randomUUID()).sourceRef("clara-cram")
|
||||
.lastName("Cram").birthYear(1890).deathYear(null).build();
|
||||
when(personRepository.findBySourceRef("clara-cram")).thenReturn(Optional.of(existing));
|
||||
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
PersonUpsertCommand cmd = PersonUpsertCommand.builder()
|
||||
.sourceRef("clara-cram").lastName("Cram")
|
||||
.birthYear(1888)
|
||||
.birthYear(1888).deathYear(1965)
|
||||
.personType(PersonType.PERSON).provisional(false).build();
|
||||
|
||||
Person result = personService.upsertBySourceRef(cmd);
|
||||
|
||||
assertThat(result.getBirthDate()).isEqualTo(LocalDate.of(1890, 3, 14));
|
||||
assertThat(result.getBirthDatePrecision()).isEqualTo(DatePrecision.DAY);
|
||||
}
|
||||
|
||||
@Test
|
||||
void upsertBySourceRef_preservesMonthPrecisionDate_onReimport() {
|
||||
Person handDated = Person.builder()
|
||||
.id(UUID.randomUUID()).sourceRef("clara-cram").lastName("Cram")
|
||||
.deathDate(LocalDate.of(1944, 11, 1)).deathDatePrecision(DatePrecision.MONTH).build();
|
||||
when(personRepository.findBySourceRef("clara-cram")).thenReturn(Optional.of(handDated));
|
||||
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
PersonUpsertCommand cmd = PersonUpsertCommand.builder()
|
||||
.sourceRef("clara-cram").lastName("Cram")
|
||||
.deathYear(1945)
|
||||
.personType(PersonType.PERSON).provisional(false).build();
|
||||
|
||||
Person result = personService.upsertBySourceRef(cmd);
|
||||
|
||||
assertThat(result.getDeathDate()).isEqualTo(LocalDate.of(1944, 11, 1));
|
||||
assertThat(result.getDeathDatePrecision()).isEqualTo(DatePrecision.MONTH);
|
||||
}
|
||||
|
||||
@Test
|
||||
void upsertBySourceRef_refreshesYearPrecisionDate_whenSpreadsheetYearChanges() {
|
||||
// YEAR precision means "the importer's year" — a corrected spreadsheet year wins.
|
||||
Person yearOnly = Person.builder()
|
||||
.id(UUID.randomUUID()).sourceRef("clara-cram").lastName("Cram")
|
||||
.birthDate(LocalDate.of(1890, 1, 1)).birthDatePrecision(DatePrecision.YEAR).build();
|
||||
when(personRepository.findBySourceRef("clara-cram")).thenReturn(Optional.of(yearOnly));
|
||||
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
PersonUpsertCommand cmd = PersonUpsertCommand.builder()
|
||||
.sourceRef("clara-cram").lastName("Cram")
|
||||
.birthYear(1888)
|
||||
.personType(PersonType.PERSON).provisional(false).build();
|
||||
|
||||
Person result = personService.upsertBySourceRef(cmd);
|
||||
|
||||
assertThat(result.getBirthDate()).isEqualTo(LocalDate.of(1888, 1, 1));
|
||||
assertThat(result.getBirthDatePrecision()).isEqualTo(DatePrecision.YEAR);
|
||||
}
|
||||
|
||||
@Test
|
||||
void upsertBySourceRef_fillsEmptyDateAtYearPrecision_onReimport() {
|
||||
Person noDates = Person.builder()
|
||||
.id(UUID.randomUUID()).sourceRef("clara-cram").lastName("Cram").build();
|
||||
when(personRepository.findBySourceRef("clara-cram")).thenReturn(Optional.of(noDates));
|
||||
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
PersonUpsertCommand cmd = PersonUpsertCommand.builder()
|
||||
.sourceRef("clara-cram").lastName("Cram")
|
||||
.deathYear(1965)
|
||||
.personType(PersonType.PERSON).provisional(false).build();
|
||||
|
||||
Person result = personService.upsertBySourceRef(cmd);
|
||||
|
||||
assertThat(result.getDeathDate()).isEqualTo(LocalDate.of(1965, 1, 1));
|
||||
assertThat(result.getDeathDatePrecision()).isEqualTo(DatePrecision.YEAR);
|
||||
}
|
||||
|
||||
@Test
|
||||
void upsertBySourceRef_keepsDatesEmpty_whenSpreadsheetHasNoYear() {
|
||||
Person noDates = Person.builder()
|
||||
.id(UUID.randomUUID()).sourceRef("clara-cram").lastName("Cram").build();
|
||||
when(personRepository.findBySourceRef("clara-cram")).thenReturn(Optional.of(noDates));
|
||||
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
PersonUpsertCommand cmd = PersonUpsertCommand.builder()
|
||||
.sourceRef("clara-cram").lastName("Cram")
|
||||
.personType(PersonType.PERSON).provisional(false).build();
|
||||
|
||||
Person result = personService.upsertBySourceRef(cmd);
|
||||
|
||||
assertThat(result.getBirthDate()).isNull();
|
||||
assertThat(result.getBirthDatePrecision()).isEqualTo(DatePrecision.UNKNOWN);
|
||||
assertThat(result.getDeathDate()).isNull();
|
||||
assertThat(result.getDeathDatePrecision()).isEqualTo(DatePrecision.UNKNOWN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void upsertBySourceRef_translatesYearToDate_onFirstImport() {
|
||||
when(personRepository.findBySourceRef("clara-cram")).thenReturn(Optional.empty());
|
||||
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
PersonUpsertCommand cmd = PersonUpsertCommand.builder()
|
||||
.sourceRef("clara-cram").lastName("Cram")
|
||||
.birthYear(1890).deathYear(1965)
|
||||
.personType(PersonType.PERSON).provisional(false).build();
|
||||
|
||||
Person result = personService.upsertBySourceRef(cmd);
|
||||
|
||||
assertThat(result.getBirthDate()).isEqualTo(LocalDate.of(1890, 1, 1));
|
||||
assertThat(result.getBirthDatePrecision()).isEqualTo(DatePrecision.YEAR);
|
||||
assertThat(result.getDeathDate()).isEqualTo(LocalDate.of(1965, 1, 1));
|
||||
assertThat(result.getDeathDatePrecision()).isEqualTo(DatePrecision.YEAR);
|
||||
assertThat(result.getBirthYear()).isEqualTo(1890); // human value kept
|
||||
assertThat(result.getDeathYear()).isEqualTo(1965); // blank filled from canonical
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -297,70 +199,4 @@ class PersonImportUpsertTest {
|
||||
|
||||
assertThat(result.getGeneration()).isEqualTo(3);
|
||||
}
|
||||
|
||||
// ─── conflicting canonical life dates degrade instead of hitting the DB CHECK ──
|
||||
// (chk_person_birth_before_death would abort the whole batch — REQ-IMP-001)
|
||||
|
||||
@Test
|
||||
void upsertBySourceRef_dropsBothDates_whenCanonicalBirthAfterDeath_newPerson() {
|
||||
when(personRepository.findBySourceRef("clara-cram")).thenReturn(Optional.empty());
|
||||
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
PersonUpsertCommand cmd = PersonUpsertCommand.builder()
|
||||
.sourceRef("clara-cram").lastName("Cram")
|
||||
.birthYear(1950).deathYear(1949)
|
||||
.personType(PersonType.PERSON).provisional(false).build();
|
||||
|
||||
Person result = personService.upsertBySourceRef(cmd);
|
||||
|
||||
assertThat(result.getBirthDate()).isNull();
|
||||
assertThat(result.getBirthDatePrecision()).isEqualTo(DatePrecision.UNKNOWN);
|
||||
assertThat(result.getDeathDate()).isNull();
|
||||
assertThat(result.getDeathDatePrecision()).isEqualTo(DatePrecision.UNKNOWN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void upsertBySourceRef_keepsHandEnteredBirth_andDropsConflictingCanonicalDeath() {
|
||||
// A human entered an exact birthday; the spreadsheet's death year lies before it.
|
||||
// The hand-entered side must survive, the conflicting canonical refresh is dropped.
|
||||
Person handDated = Person.builder()
|
||||
.id(UUID.randomUUID()).sourceRef("clara-cram").lastName("Cram")
|
||||
.birthDate(LocalDate.of(1950, 6, 1)).birthDatePrecision(DatePrecision.DAY).build();
|
||||
when(personRepository.findBySourceRef("clara-cram")).thenReturn(Optional.of(handDated));
|
||||
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
PersonUpsertCommand cmd = PersonUpsertCommand.builder()
|
||||
.sourceRef("clara-cram").lastName("Cram")
|
||||
.deathYear(1949)
|
||||
.personType(PersonType.PERSON).provisional(false).build();
|
||||
|
||||
Person result = personService.upsertBySourceRef(cmd);
|
||||
|
||||
assertThat(result.getBirthDate()).isEqualTo(LocalDate.of(1950, 6, 1));
|
||||
assertThat(result.getBirthDatePrecision()).isEqualTo(DatePrecision.DAY);
|
||||
assertThat(result.getDeathDate()).isNull();
|
||||
assertThat(result.getDeathDatePrecision()).isEqualTo(DatePrecision.UNKNOWN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void upsertBySourceRef_keepsExistingYearDates_whenCanonicalRefreshConflicts() {
|
||||
Person existing = Person.builder()
|
||||
.id(UUID.randomUUID()).sourceRef("clara-cram").lastName("Cram")
|
||||
.birthDate(LocalDate.of(1900, 1, 1)).birthDatePrecision(DatePrecision.YEAR)
|
||||
.deathDate(LocalDate.of(1980, 1, 1)).deathDatePrecision(DatePrecision.YEAR).build();
|
||||
when(personRepository.findBySourceRef("clara-cram")).thenReturn(Optional.of(existing));
|
||||
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
PersonUpsertCommand cmd = PersonUpsertCommand.builder()
|
||||
.sourceRef("clara-cram").lastName("Cram")
|
||||
.birthYear(1990).deathYear(1985)
|
||||
.personType(PersonType.PERSON).provisional(false).build();
|
||||
|
||||
Person result = personService.upsertBySourceRef(cmd);
|
||||
|
||||
assertThat(result.getBirthDate()).isEqualTo(LocalDate.of(1900, 1, 1));
|
||||
assertThat(result.getBirthDatePrecision()).isEqualTo(DatePrecision.YEAR);
|
||||
assertThat(result.getDeathDate()).isEqualTo(LocalDate.of(1980, 1, 1));
|
||||
assertThat(result.getDeathDatePrecision()).isEqualTo(DatePrecision.YEAR);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,9 +18,6 @@ import org.raddatz.familienarchiv.document.DocumentRepository;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import org.raddatz.familienarchiv.document.DatePrecision;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
@@ -913,146 +910,4 @@ class PersonRepositoryTest {
|
||||
.setParameter(1, blockId).getSingleResult();
|
||||
assertThat(text).isEqualTo("Brief an @Auguste Raddatz und @Clara Cram");
|
||||
}
|
||||
|
||||
// ─── #773: PersonSummaryDTO year projection from birth_date/death_date ──────
|
||||
|
||||
@Test
|
||||
void findAllWithDocumentCount_derivesYearsFromDates_nullSafe() {
|
||||
personRepository.save(Person.builder()
|
||||
.firstName("Maria").lastName("Datiert")
|
||||
.birthDate(LocalDate.of(1901, 3, 14)).birthDatePrecision(DatePrecision.DAY)
|
||||
.build());
|
||||
personRepository.save(Person.builder()
|
||||
.firstName("Nora").lastName("Undatiert")
|
||||
.build());
|
||||
entityManager.flush();
|
||||
|
||||
List<PersonSummaryDTO> all = personRepository.findAllWithDocumentCount();
|
||||
|
||||
PersonSummaryDTO dated = all.stream()
|
||||
.filter(p -> "Datiert".equals(p.getLastName())).findFirst().orElseThrow();
|
||||
assertThat(dated.getBirthYear()).isEqualTo(1901);
|
||||
assertThat(dated.getDeathYear()).isNull();
|
||||
PersonSummaryDTO undated = all.stream()
|
||||
.filter(p -> "Undatiert".equals(p.getLastName())).findFirst().orElseThrow();
|
||||
assertThat(undated.getBirthYear()).isNull();
|
||||
assertThat(undated.getDeathYear()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void searchWithDocumentCount_groupByPath_derivesYearsFromDates() {
|
||||
personRepository.save(Person.builder()
|
||||
.firstName("Herbert").lastName("Gruppiert")
|
||||
.birthDate(LocalDate.of(1899, 1, 1)).birthDatePrecision(DatePrecision.YEAR)
|
||||
.deathDate(LocalDate.of(1972, 6, 12)).deathDatePrecision(DatePrecision.DAY)
|
||||
.build());
|
||||
entityManager.flush();
|
||||
|
||||
List<PersonSummaryDTO> found = personRepository.searchWithDocumentCount("Gruppiert");
|
||||
|
||||
assertThat(found).hasSize(1);
|
||||
assertThat(found.get(0).getBirthYear()).isEqualTo(1899);
|
||||
assertThat(found.get(0).getDeathYear()).isEqualTo(1972);
|
||||
}
|
||||
|
||||
@Test
|
||||
void findByFilter_derivesYearsFromDates() {
|
||||
personRepository.save(Person.builder()
|
||||
.firstName("Filtriert").lastName("Person")
|
||||
.birthDate(LocalDate.of(1920, 1, 1)).birthDatePrecision(DatePrecision.YEAR)
|
||||
.build());
|
||||
entityManager.flush();
|
||||
|
||||
List<PersonSummaryDTO> found = personRepository.findByFilter(
|
||||
null, null, null, null, false, "Filtriert", 10, 0);
|
||||
|
||||
assertThat(found).hasSize(1);
|
||||
assertThat(found.get(0).getBirthYear()).isEqualTo(1920);
|
||||
assertThat(found.get(0).getDeathYear()).isNull();
|
||||
}
|
||||
|
||||
// ─── #773 follow-up: full date + precision exposed on the summary projection ──
|
||||
// (the mention dropdown renders precise life dates from the list endpoint)
|
||||
|
||||
@Test
|
||||
void findAllWithDocumentCount_exposesDateAndPrecisionFields() {
|
||||
personRepository.save(Person.builder()
|
||||
.firstName("Maria").lastName("Praezise")
|
||||
.birthDate(LocalDate.of(1901, 3, 14)).birthDatePrecision(DatePrecision.DAY)
|
||||
.deathDate(LocalDate.of(1972, 1, 1)).deathDatePrecision(DatePrecision.YEAR)
|
||||
.build());
|
||||
personRepository.save(Person.builder()
|
||||
.firstName("Nora").lastName("Datenlos")
|
||||
.build());
|
||||
entityManager.flush();
|
||||
|
||||
List<PersonSummaryDTO> all = personRepository.findAllWithDocumentCount();
|
||||
|
||||
PersonSummaryDTO dated = all.stream()
|
||||
.filter(p -> "Praezise".equals(p.getLastName())).findFirst().orElseThrow();
|
||||
assertThat(dated.getBirthDate()).isEqualTo(LocalDate.of(1901, 3, 14));
|
||||
assertThat(dated.getBirthDatePrecision()).isEqualTo(DatePrecision.DAY);
|
||||
assertThat(dated.getDeathDate()).isEqualTo(LocalDate.of(1972, 1, 1));
|
||||
assertThat(dated.getDeathDatePrecision()).isEqualTo(DatePrecision.YEAR);
|
||||
PersonSummaryDTO undated = all.stream()
|
||||
.filter(p -> "Datenlos".equals(p.getLastName())).findFirst().orElseThrow();
|
||||
assertThat(undated.getBirthDate()).isNull();
|
||||
assertThat(undated.getBirthDatePrecision()).isEqualTo(DatePrecision.UNKNOWN);
|
||||
assertThat(undated.getDeathDate()).isNull();
|
||||
assertThat(undated.getDeathDatePrecision()).isEqualTo(DatePrecision.UNKNOWN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void searchWithDocumentCount_exposesDateAndPrecisionFields() {
|
||||
personRepository.save(Person.builder()
|
||||
.firstName("Herbert").lastName("Suchbar")
|
||||
.birthDate(LocalDate.of(1899, 1, 1)).birthDatePrecision(DatePrecision.YEAR)
|
||||
.deathDate(LocalDate.of(1972, 6, 12)).deathDatePrecision(DatePrecision.DAY)
|
||||
.build());
|
||||
entityManager.flush();
|
||||
|
||||
List<PersonSummaryDTO> found = personRepository.searchWithDocumentCount("Suchbar");
|
||||
|
||||
assertThat(found).hasSize(1);
|
||||
assertThat(found.get(0).getBirthDate()).isEqualTo(LocalDate.of(1899, 1, 1));
|
||||
assertThat(found.get(0).getBirthDatePrecision()).isEqualTo(DatePrecision.YEAR);
|
||||
assertThat(found.get(0).getDeathDate()).isEqualTo(LocalDate.of(1972, 6, 12));
|
||||
assertThat(found.get(0).getDeathDatePrecision()).isEqualTo(DatePrecision.DAY);
|
||||
}
|
||||
|
||||
@Test
|
||||
void findTopByDocumentCount_exposesDateAndPrecisionFields() {
|
||||
personRepository.save(Person.builder()
|
||||
.firstName("Top").lastName("Dokumentiert")
|
||||
.birthDate(LocalDate.of(1910, 5, 1)).birthDatePrecision(DatePrecision.MONTH)
|
||||
.build());
|
||||
entityManager.flush();
|
||||
|
||||
List<PersonSummaryDTO> top = personRepository.findTopByDocumentCount(10);
|
||||
|
||||
PersonSummaryDTO found = top.stream()
|
||||
.filter(p -> "Dokumentiert".equals(p.getLastName())).findFirst().orElseThrow();
|
||||
assertThat(found.getBirthDate()).isEqualTo(LocalDate.of(1910, 5, 1));
|
||||
assertThat(found.getBirthDatePrecision()).isEqualTo(DatePrecision.MONTH);
|
||||
assertThat(found.getDeathDate()).isNull();
|
||||
assertThat(found.getDeathDatePrecision()).isEqualTo(DatePrecision.UNKNOWN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void findByFilter_exposesDateAndPrecisionFields() {
|
||||
personRepository.save(Person.builder()
|
||||
.firstName("Gefiltert").lastName("Genau")
|
||||
.deathDate(LocalDate.of(1944, 11, 2)).deathDatePrecision(DatePrecision.DAY)
|
||||
.build());
|
||||
entityManager.flush();
|
||||
|
||||
List<PersonSummaryDTO> found = personRepository.findByFilter(
|
||||
null, null, null, null, false, "Gefiltert", 10, 0);
|
||||
|
||||
assertThat(found).hasSize(1);
|
||||
assertThat(found.get(0).getBirthDate()).isNull();
|
||||
assertThat(found.get(0).getBirthDatePrecision()).isEqualTo(DatePrecision.UNKNOWN);
|
||||
assertThat(found.get(0).getDeathDate()).isEqualTo(LocalDate.of(1944, 11, 2));
|
||||
assertThat(found.get(0).getDeathDatePrecision()).isEqualTo(DatePrecision.DAY);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.raddatz.familienarchiv.person.PersonNameAliasDTO;
|
||||
import org.raddatz.familienarchiv.person.PersonSummaryDTO;
|
||||
import org.raddatz.familienarchiv.person.PersonUpdateDTO;
|
||||
import org.raddatz.familienarchiv.document.DatePrecision;
|
||||
import org.raddatz.familienarchiv.exception.DomainException;
|
||||
import org.raddatz.familienarchiv.exception.ErrorCode;
|
||||
import org.raddatz.familienarchiv.person.Person;
|
||||
import org.raddatz.familienarchiv.person.PersonNameAlias;
|
||||
import org.raddatz.familienarchiv.person.PersonNameAliasType;
|
||||
@@ -19,7 +17,6 @@ import org.raddatz.familienarchiv.person.PersonNameAliasRepository;
|
||||
import org.raddatz.familienarchiv.person.PersonRepository;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
@@ -244,49 +241,27 @@ class PersonServiceTest {
|
||||
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Maria"); dto.setLastName("Raddatz"); dto.setAlias("Oma Maria");
|
||||
dto.setBirthDate(LocalDate.of(1901, 3, 14)); dto.setBirthDatePrecision(DatePrecision.DAY);
|
||||
dto.setDeathDate(LocalDate.of(1975, 11, 2)); dto.setDeathDatePrecision(DatePrecision.DAY);
|
||||
dto.setNotes("Some notes");
|
||||
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.getBirthDate()).isEqualTo(LocalDate.of(1901, 3, 14));
|
||||
assertThat(result.getBirthDatePrecision()).isEqualTo(DatePrecision.DAY);
|
||||
assertThat(result.getDeathDate()).isEqualTo(LocalDate.of(1975, 11, 2));
|
||||
assertThat(result.getDeathDatePrecision()).isEqualTo(DatePrecision.DAY);
|
||||
assertThat(result.getBirthYear()).isEqualTo(1901);
|
||||
assertThat(result.getDeathYear()).isEqualTo(1975);
|
||||
assertThat(result.getNotes()).isEqualTo("Some notes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPerson_dto_rejectsDateWithUnknownPrecision() {
|
||||
void createPerson_dto_yearValidationFires_whenBirthYearNegative() {
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Anna"); dto.setLastName("Test");
|
||||
dto.setBirthDate(LocalDate.of(1901, 3, 14)); dto.setBirthDatePrecision(DatePrecision.UNKNOWN);
|
||||
dto.setFirstName("Anna"); dto.setLastName("Test"); dto.setBirthYear(-1);
|
||||
|
||||
assertThatThrownBy(() -> personService.createPerson(dto))
|
||||
.isInstanceOf(DomainException.class)
|
||||
.satisfies(e -> {
|
||||
assertThat(((DomainException) e).getCode()).isEqualTo(ErrorCode.INVALID_DATE_PRECISION);
|
||||
assertThat(((DomainException) e).getStatus().value()).isEqualTo(400);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPerson_dto_treatsNullPrecisionWithNullDateAsUnknown() {
|
||||
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Anna"); dto.setLastName("Test"); dto.setPersonType(PersonType.PERSON);
|
||||
|
||||
Person result = personService.createPerson(dto);
|
||||
|
||||
assertThat(result.getBirthDate()).isNull();
|
||||
assertThat(result.getBirthDatePrecision()).isEqualTo(DatePrecision.UNKNOWN);
|
||||
assertThat(result.getDeathDate()).isNull();
|
||||
assertThat(result.getDeathDatePrecision()).isEqualTo(DatePrecision.UNKNOWN);
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value())
|
||||
.isEqualTo(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -625,135 +600,114 @@ class PersonServiceTest {
|
||||
assertThat(result.getNotes()).isNull();
|
||||
}
|
||||
|
||||
// ─── updatePerson (birth/death dates) ────────────────────────────────────
|
||||
// ─── updatePerson (birth/death years) ────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void updatePerson_persistsBirthAndDeathDateWithPrecision() {
|
||||
void updatePerson_persistsBirthAndDeathYear() {
|
||||
UUID id = UUID.randomUUID();
|
||||
Person person = Person.builder().id(id).firstName("Anna").lastName("Alt").build();
|
||||
when(personRepository.findById(id)).thenReturn(Optional.of(person));
|
||||
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt");
|
||||
dto.setBirthDate(LocalDate.of(1890, 1, 1)); dto.setBirthDatePrecision(DatePrecision.YEAR);
|
||||
dto.setDeathDate(LocalDate.of(1965, 6, 12)); dto.setDeathDatePrecision(DatePrecision.DAY);
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setBirthYear(1890); dto.setDeathYear(1965);
|
||||
Person result = personService.updatePerson(id, dto);
|
||||
|
||||
assertThat(result.getBirthDate()).isEqualTo(LocalDate.of(1890, 1, 1));
|
||||
assertThat(result.getBirthDatePrecision()).isEqualTo(DatePrecision.YEAR);
|
||||
assertThat(result.getDeathDate()).isEqualTo(LocalDate.of(1965, 6, 12));
|
||||
assertThat(result.getDeathDatePrecision()).isEqualTo(DatePrecision.DAY);
|
||||
assertThat(result.getBirthYear()).isEqualTo(1890);
|
||||
assertThat(result.getDeathYear()).isEqualTo(1965);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatePerson_throwsBirthAfterDeath_whenBirthDateAfterDeathDate() {
|
||||
void updatePerson_throwsBadRequest_whenBirthYearAfterDeathYear() {
|
||||
UUID id = UUID.randomUUID();
|
||||
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt");
|
||||
dto.setBirthDate(LocalDate.of(1970, 5, 1)); dto.setBirthDatePrecision(DatePrecision.DAY);
|
||||
dto.setDeathDate(LocalDate.of(1950, 5, 1)); dto.setDeathDatePrecision(DatePrecision.DAY);
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setBirthYear(1970); dto.setDeathYear(1950);
|
||||
assertThatThrownBy(() -> personService.updatePerson(id, dto))
|
||||
.isInstanceOf(DomainException.class)
|
||||
.satisfies(e -> {
|
||||
assertThat(((DomainException) e).getCode()).isEqualTo(ErrorCode.BIRTH_AFTER_DEATH);
|
||||
assertThat(((DomainException) e).getStatus().value()).isEqualTo(400);
|
||||
});
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value())
|
||||
.isEqualTo(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatePerson_throwsBirthAfterDeath_onMixedPrecisionLateBirthday() {
|
||||
// Known limitation (#773): DAY-precision birth late in the death's YEAR-precision year
|
||||
// compares against the year's backfilled Jan 1st and is rejected. The error message
|
||||
// carries the workaround hint via the BIRTH_AFTER_DEATH i18n key.
|
||||
UUID id = UUID.randomUUID();
|
||||
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt");
|
||||
dto.setBirthDate(LocalDate.of(1901, 11, 15)); dto.setBirthDatePrecision(DatePrecision.DAY);
|
||||
dto.setDeathDate(LocalDate.of(1901, 1, 1)); dto.setDeathDatePrecision(DatePrecision.YEAR);
|
||||
assertThatThrownBy(() -> personService.updatePerson(id, dto))
|
||||
.isInstanceOf(DomainException.class)
|
||||
.extracting(e -> ((DomainException) e).getCode())
|
||||
.isEqualTo(ErrorCode.BIRTH_AFTER_DEATH);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatePerson_doesNotThrow_whenBirthDateSetButDeathDateNull() {
|
||||
void updatePerson_doesNotThrow_whenBirthYearNonNullButDeathYearIsNull() {
|
||||
// Covers A && B short-circuit: birthYear != null (true) but deathYear == null (false) → no throw
|
||||
UUID id = UUID.randomUUID();
|
||||
Person person = Person.builder().id(id).firstName("Anna").lastName("Alt").build();
|
||||
when(personRepository.findById(id)).thenReturn(Optional.of(person));
|
||||
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt");
|
||||
dto.setBirthDate(LocalDate.of(1890, 1, 1)); dto.setBirthDatePrecision(DatePrecision.YEAR);
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setBirthYear(1890); dto.setDeathYear(null);
|
||||
Person result = personService.updatePerson(id, dto);
|
||||
|
||||
assertThat(result.getBirthDate()).isEqualTo(LocalDate.of(1890, 1, 1));
|
||||
assertThat(result.getDeathDate()).isNull();
|
||||
assertThat(result.getDeathDatePrecision()).isEqualTo(DatePrecision.UNKNOWN);
|
||||
assertThat(result.getBirthYear()).isEqualTo(1890);
|
||||
assertThat(result.getDeathYear()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatePerson_allowsEqualBirthAndDeathDate() {
|
||||
void updatePerson_allowsSameYear() {
|
||||
UUID id = UUID.randomUUID();
|
||||
Person person = Person.builder().id(id).firstName("Anna").lastName("Alt").build();
|
||||
when(personRepository.findById(id)).thenReturn(Optional.of(person));
|
||||
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt");
|
||||
dto.setBirthDate(LocalDate.of(1900, 1, 1)); dto.setBirthDatePrecision(DatePrecision.YEAR);
|
||||
dto.setDeathDate(LocalDate.of(1900, 1, 1)); dto.setDeathDatePrecision(DatePrecision.YEAR);
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setBirthYear(1900); dto.setDeathYear(1900);
|
||||
Person result = personService.updatePerson(id, dto);
|
||||
|
||||
assertThat(result.getBirthDate()).isEqualTo(LocalDate.of(1900, 1, 1));
|
||||
assertThat(result.getDeathDate()).isEqualTo(LocalDate.of(1900, 1, 1));
|
||||
assertThat(result.getBirthYear()).isEqualTo(1900);
|
||||
assertThat(result.getDeathYear()).isEqualTo(1900);
|
||||
}
|
||||
|
||||
// ─── Date/precision coherence (V76 CHECK constraint mirror) ─────────────
|
||||
// ─── Phase 1.3: Year range bounds (> 0) ──────────────────────────────────
|
||||
|
||||
@Test
|
||||
void updatePerson_throwsInvalidDatePrecision_whenDatePresentButPrecisionUnknown() {
|
||||
void updatePerson_throwsBadRequest_whenBirthYearIsZero() {
|
||||
UUID id = UUID.randomUUID();
|
||||
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt");
|
||||
dto.setDeathDate(LocalDate.of(1944, 11, 2)); dto.setDeathDatePrecision(DatePrecision.UNKNOWN);
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setBirthYear(0);
|
||||
assertThatThrownBy(() -> personService.updatePerson(id, dto))
|
||||
.isInstanceOf(DomainException.class)
|
||||
.satisfies(e -> {
|
||||
assertThat(((DomainException) e).getCode()).isEqualTo(ErrorCode.INVALID_DATE_PRECISION);
|
||||
assertThat(((DomainException) e).getStatus().value()).isEqualTo(400);
|
||||
});
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value())
|
||||
.isEqualTo(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatePerson_throwsInvalidDatePrecision_whenDatePresentButPrecisionNull() {
|
||||
void updatePerson_throwsBadRequest_whenBirthYearIsNegative() {
|
||||
UUID id = UUID.randomUUID();
|
||||
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt");
|
||||
dto.setBirthDate(LocalDate.of(1901, 3, 14));
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setBirthYear(-5);
|
||||
assertThatThrownBy(() -> personService.updatePerson(id, dto))
|
||||
.isInstanceOf(DomainException.class)
|
||||
.extracting(e -> ((DomainException) e).getCode())
|
||||
.isEqualTo(ErrorCode.INVALID_DATE_PRECISION);
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value())
|
||||
.isEqualTo(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatePerson_throwsInvalidDatePrecision_whenPrecisionSetWithoutDate() {
|
||||
void updatePerson_throwsBadRequest_whenDeathYearIsZero() {
|
||||
UUID id = UUID.randomUUID();
|
||||
|
||||
PersonUpdateDTO dto = new PersonUpdateDTO();
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt");
|
||||
dto.setBirthDatePrecision(DatePrecision.DAY);
|
||||
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setDeathYear(0);
|
||||
assertThatThrownBy(() -> personService.updatePerson(id, dto))
|
||||
.isInstanceOf(DomainException.class)
|
||||
.extracting(e -> ((DomainException) e).getCode())
|
||||
.isEqualTo(ErrorCode.INVALID_DATE_PRECISION);
|
||||
.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 ──────────────────────────────────────────────────
|
||||
|
||||
@@ -518,26 +518,6 @@ docker exec -i archive-db psql -U ${POSTGRES_USER} ${POSTGRES_DB} < backup-YYYYM
|
||||
|
||||
Automated backup (nightly `pg_dump` + MinIO `mc mirror` over Tailscale to `heim-nas`) is a follow-up issue. Until that ships: **manual backups are the only recovery option.**
|
||||
|
||||
### Deploy note — V76 (persons birth/death → date + precision, #773)
|
||||
|
||||
V76 drops `persons.birth_year`/`death_year` after backfilling the new
|
||||
`birth_date`/`death_date` + precision columns — a **one-way migration** (Flyway cannot
|
||||
roll it back). Before deploying:
|
||||
|
||||
1. Take a manual `pg_dump` (see above) — there is no automated nightly backup yet, so
|
||||
confirm the dump completed before starting the deploy.
|
||||
2. No maintenance window is required: the pre-check + DDL run in one atomic Flyway
|
||||
transaction, and this single-writer archive has no concurrent importers during deploy.
|
||||
|
||||
If post-deploy data issues are found, restore **only the persons table** from the
|
||||
pre-migration dump (targeted restore, not a full-database restore):
|
||||
|
||||
```bash
|
||||
pg_restore -t persons -d ${POSTGRES_DB} backup-YYYYMMDD.dump
|
||||
```
|
||||
|
||||
(For a plain-SQL dump, extract the persons COPY block instead of replaying the full file.)
|
||||
|
||||
### Rollback
|
||||
|
||||
Each release tag corresponds to a docker image tag on the host daemon (built via DooD; no registry). Rolling back to a previous tag is one command:
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
# ADR-039 — Person life dates become LocalDate + DatePrecision
|
||||
|
||||
**Status:** Accepted
|
||||
**Date:** 2026-06-12
|
||||
**Issue:** #773 (Zeitstrahl milestone, foundational)
|
||||
|
||||
## Context
|
||||
|
||||
`Person` stored `birthYear`/`deathYear` as `Integer`. A known exact birthday
|
||||
(`1901-03-14`) had nowhere to live, and every display was stuck at year precision.
|
||||
The Zeitstrahl's derived life-events need real dates with precision metadata, and the
|
||||
document domain already solved exactly this problem with
|
||||
`Document.documentDate` + `metaDatePrecision`.
|
||||
|
||||
V76 replaces the two integer columns with `birth_date`/`death_date` (`DATE`, nullable)
|
||||
plus `birth_date_precision`/`death_date_precision` (`VARCHAR(16) NOT NULL DEFAULT
|
||||
'UNKNOWN'`), backfilling existing years as `YYYY-01-01` at `YEAR` precision.
|
||||
|
||||
## Decisions
|
||||
|
||||
### 1. `DatePrecision` stays in `document/` and is imported cross-domain
|
||||
|
||||
The `person` package imports `org.raddatz.familienarchiv.document.DatePrecision`
|
||||
directly. The layering rule (controllers → services → own repository) governs
|
||||
service-to-repository coupling, **not** value-type sharing — an enum has no behaviour
|
||||
and no persistence side effects. Creating a `common/` package for one enum would be
|
||||
premature structure; if a third domain needs it, revisit then. The enum remains a
|
||||
verbatim mirror of the import normalizer's `Precision` values (ADR-025) — changes must
|
||||
stay in sync with `tools/import-normalizer/dates.py`.
|
||||
|
||||
### 2. Precision columns are NOT NULL with default `UNKNOWN`
|
||||
|
||||
Mirrors `Document.metaDatePrecision`. The illegal state "date present, precision null"
|
||||
cannot exist: the named CHECK constraints
|
||||
(`chk_person_birth_date_precision_coherence`, `…_values`,
|
||||
`chk_person_birth_before_death`, and the death-side twins) enforce
|
||||
`(date IS NULL) = (precision = 'UNKNOWN')` and the temporal order at the DB level;
|
||||
`PersonService.validateLifeDates` enforces the same rules first so users get a
|
||||
structured 400 (`INVALID_DATE_PRECISION` / `BIRTH_AFTER_DEATH`) instead of a
|
||||
constraint-violation 500.
|
||||
|
||||
Storage accepts all seven `DatePrecision` values (enum-to-string mapping consistency),
|
||||
but the person new/edit form offers only **DAY / MONTH / YEAR** — `RANGE` and `SEASON`
|
||||
are semantically nonsensical for a birth or death, and `APPROX` is excluded from the
|
||||
form to reduce cognitive load for the senior author audience. Legacy `APPROX` rows
|
||||
still render correctly (display delegates to `formatDocumentDate`).
|
||||
|
||||
The edit form seeds a stored non-offered precision (`APPROX`/`SEASON`/`RANGE`) into
|
||||
the select as `YEAR`, so an untouched save coerces it to `YEAR` ("ca. 1944" becomes
|
||||
"1944"). Accepted: nothing currently writes those precisions to persons (the form
|
||||
offers DAY/MONTH/YEAR, the importer writes YEAR/UNKNOWN, V76 backfills YEAR), so the
|
||||
case is only reachable via direct API writes — and seeding `YEAR` is strictly safer
|
||||
than the alternative of silently claiming `DAY` precision.
|
||||
|
||||
### 3. Derived-year pattern for backward-compatible DTOs
|
||||
|
||||
`PersonNodeDTO` (Stammbaum) and `RelationshipDTO` keep `Integer birthYear/deathYear`,
|
||||
derived null-safely in the relationship services (`birthDate != null ?
|
||||
birthDate.getYear() : null` — never 0, never empty string; REQ-PERSON-DATE-01). The
|
||||
native queries behind `PersonSummaryDTO` project
|
||||
`CAST(EXTRACT(YEAR FROM p.birth_date) AS int) AS birthYear`.
|
||||
|
||||
### 4. `PersonSummaryDTO` intentionally exposes years only
|
||||
|
||||
The person list/search views show year precision only; full precision lives on the
|
||||
person detail page. Do **not** add `LocalDate getBirthDate()` to the interface without
|
||||
updating all four native queries (`findAllWithDocumentCount`,
|
||||
`searchWithDocumentCount`, `findTopByDocumentCount`, `findByFilter`) — the interface
|
||||
projection is satisfied purely by the SQL SELECT aliases.
|
||||
|
||||
### 5. `preferHumanDate` extends ADR-025's human-edit-preserve rule
|
||||
|
||||
The importer stays year-shaped: `PersonUpsertCommand` keeps `Integer birthYear/
|
||||
deathYear` because the spreadsheet only knows a year — pushing `LocalDate` into the
|
||||
importer would fabricate precision. On upsert, `PersonService.preferHumanDate` returns
|
||||
a `DatePrecisionPair` record (date and precision travel as one value so they cannot go
|
||||
out of sync):
|
||||
|
||||
- existing precision DAY/MONTH/SEASON/RANGE/APPROX → hand-entered, preserved verbatim;
|
||||
- existing precision YEAR/UNKNOWN → refreshed from the canonical year as
|
||||
`YYYY-01-01` + `YEAR` (or cleared to null/`UNKNOWN` when the sheet has no year).
|
||||
|
||||
The original integer/string `preferHuman` overloads remain for non-date fields.
|
||||
|
||||
### 6. Known limitation — mixed-precision comparison
|
||||
|
||||
`validateLifeDates` compares stored `LocalDate` values. A DAY-precision birth late in
|
||||
the same year as a YEAR-precision death (stored as Jan 1st) is rejected with
|
||||
`BIRTH_AFTER_DEATH`. This is intentional; the `error_birth_after_death` i18n message
|
||||
carries the workaround hint (enter the following year as the death year).
|
||||
|
||||
## Consequences
|
||||
|
||||
- V76 is one-way (columns dropped). Rollback = targeted `pg_restore -t persons` from
|
||||
the pre-deploy dump — see `docs/DEPLOYMENT.md` §5.
|
||||
- Exact dates now render on person cards, hover cards, and the mention dropdown; the
|
||||
Stammbaum and person list are visually unchanged.
|
||||
- The Zeitstrahl can derive birth/death life-events at full precision.
|
||||
@@ -1,6 +1,6 @@
|
||||
@startuml db-orm
|
||||
' Schema source: Flyway V1–V76 (excl. V37, V43 — intentionally removed)
|
||||
' Schema as of: V76 (2026-06-12)
|
||||
' Schema source: Flyway V1–V72 (excl. V37, V43 — intentionally removed)
|
||||
' Schema as of: V72 (2026-06-08)
|
||||
' ⚠ This is a versioned snapshot. Update when the schema changes significantly.
|
||||
|
||||
hide circle
|
||||
@@ -184,10 +184,8 @@ package "Persons" {
|
||||
title : VARCHAR(50)
|
||||
person_type : VARCHAR(20) NOT NULL
|
||||
notes : TEXT
|
||||
birth_date : DATE
|
||||
birth_date_precision : VARCHAR(16) NOT NULL
|
||||
death_date : DATE
|
||||
death_date_precision : VARCHAR(16) NOT NULL
|
||||
birth_year : INTEGER
|
||||
death_year : INTEGER
|
||||
generation : SMALLINT
|
||||
family_member : BOOLEAN NOT NULL
|
||||
source_ref : VARCHAR(255) UNIQUE
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
' ⚠ This is a versioned snapshot. Update when the schema changes significantly.
|
||||
' Note: V69 adds columns only (persons.source_ref, tag.source_ref, document
|
||||
' precision/attribution fields); no new FK relationships, so this diagram is unchanged.
|
||||
' Note: V76 swaps persons.birth_year/death_year for birth_date/death_date +
|
||||
' precision columns; columns only, no new FK relationships, diagram unchanged.
|
||||
|
||||
hide circle
|
||||
skinparam linetype ortho
|
||||
|
||||
@@ -174,18 +174,12 @@
|
||||
"person_merge_warning": "Achtung: Diese Aktion ist nicht rückgängig zu machen.",
|
||||
"person_label_notes": "Notizen",
|
||||
"person_placeholder_notes": "Biographische Hinweise, Besonderheiten…",
|
||||
"person_label_birth_date": "Geburtsdatum",
|
||||
"person_label_death_date": "Sterbedatum",
|
||||
"person_label_birth_date_precision": "Genauigkeit",
|
||||
"person_label_death_date_precision": "Genauigkeit",
|
||||
"person_precision_hint": "Wie genau ist dieses Datum bekannt?",
|
||||
"person_precision_day": "Genaues Datum (Tag)",
|
||||
"person_precision_month": "Monat bekannt",
|
||||
"person_precision_year": "Nur Jahreszahl",
|
||||
"person_date_placeholder_hint": "Leer lassen, wenn unbekannt",
|
||||
"person_label_birth_year": "Geburtsjahr",
|
||||
"person_label_death_year": "Todesjahr",
|
||||
"person_label_generation": "Generation",
|
||||
"person_option_generation_unset": "(keine)",
|
||||
"person_hint_generation": "Generation in der Familie (G 0 = älteste Generation)",
|
||||
"person_placeholder_year": "z.B. 1923",
|
||||
"person_year_error": "Bitte eine vierstellige Jahreszahl eingeben",
|
||||
"person_years_error_order": "Geburtsjahr muss vor dem Todesjahr liegen",
|
||||
"person_docs_heading": "Gesendete Dokumente",
|
||||
@@ -649,8 +643,6 @@
|
||||
"error_alias_not_found": "Der Namensalias wurde nicht gefunden.",
|
||||
"error_invalid_person_type": "Der angegebene Personentyp ist ungültig.",
|
||||
"error_invalid_date_range": "Das Enddatum darf nicht vor dem Startdatum liegen.",
|
||||
"error_birth_after_death": "Geburtsdatum muss vor dem Sterbedatum liegen. Tipp: Falls nur das Todesjahr bekannt ist und der Geburtstag spät im selben Jahr lag, bitte das Folgejahr eintragen.",
|
||||
"error_invalid_date_precision": "Datum und Genauigkeit stimmen nicht überein.",
|
||||
"validation_last_name_required": "Nachname ist Pflichtfeld.",
|
||||
"validation_first_name_required": "Vorname ist Pflichtfeld.",
|
||||
"error_ocr_service_unavailable": "Der OCR-Dienst ist nicht verfügbar.",
|
||||
@@ -1050,6 +1042,10 @@
|
||||
"geschichten_filter_document_chip": "Gefiltert nach Brief:",
|
||||
"geschichten_filter_remove_document_chip": "Brief {title} aus Filter entfernen",
|
||||
"geschichten_empty_for_document": "Noch keine Geschichten zu diesem Brief",
|
||||
"geschichten_published_heading": "Veröffentlicht",
|
||||
"geschichten_drafts_heading": "Entwürfe",
|
||||
"geschichten_draft_badge": "Entwurf",
|
||||
"geschichten_drafts_unfiltered_caption": "(alle Entwürfe)",
|
||||
"geschichten_back_to_index": "Zurück zu Geschichten",
|
||||
"geschichten_published_on": "veröffentlicht am {date}",
|
||||
"journey_compiled_on": "zusammengestellt am {date}",
|
||||
|
||||
@@ -174,18 +174,12 @@
|
||||
"person_merge_warning": "Warning: This action cannot be undone.",
|
||||
"person_label_notes": "Notes",
|
||||
"person_placeholder_notes": "Biographical notes, remarks…",
|
||||
"person_label_birth_date": "Date of birth",
|
||||
"person_label_death_date": "Date of death",
|
||||
"person_label_birth_date_precision": "Precision",
|
||||
"person_label_death_date_precision": "Precision",
|
||||
"person_precision_hint": "How precisely is this date known?",
|
||||
"person_precision_day": "Exact date (day)",
|
||||
"person_precision_month": "Month known",
|
||||
"person_precision_year": "Year only",
|
||||
"person_date_placeholder_hint": "Leave empty if unknown",
|
||||
"person_label_birth_year": "Birth year",
|
||||
"person_label_death_year": "Death year",
|
||||
"person_label_generation": "Generation",
|
||||
"person_option_generation_unset": "(none)",
|
||||
"person_hint_generation": "Generation within the family (G 0 = oldest generation)",
|
||||
"person_placeholder_year": "e.g. 1923",
|
||||
"person_year_error": "Please enter a four-digit year",
|
||||
"person_years_error_order": "Birth year must be before death year",
|
||||
"person_docs_heading": "Sent documents",
|
||||
@@ -649,8 +643,6 @@
|
||||
"error_alias_not_found": "The name alias was not found.",
|
||||
"error_invalid_person_type": "The specified person type is not valid.",
|
||||
"error_invalid_date_range": "The end date must not be before the start date.",
|
||||
"error_birth_after_death": "Birth date must be before death date. Tip: if only the death year is known and the birthday is late in the same year, enter the following year.",
|
||||
"error_invalid_date_precision": "Date and precision do not match.",
|
||||
"validation_last_name_required": "Last name is required.",
|
||||
"validation_first_name_required": "First name is required.",
|
||||
"error_ocr_service_unavailable": "The OCR service is not available.",
|
||||
@@ -1050,6 +1042,10 @@
|
||||
"geschichten_filter_document_chip": "Filtered by letter:",
|
||||
"geschichten_filter_remove_document_chip": "Remove letter {title} from filter",
|
||||
"geschichten_empty_for_document": "No stories reference this letter yet",
|
||||
"geschichten_published_heading": "Published",
|
||||
"geschichten_drafts_heading": "Drafts",
|
||||
"geschichten_draft_badge": "Draft",
|
||||
"geschichten_drafts_unfiltered_caption": "(all drafts)",
|
||||
"geschichten_back_to_index": "Back to stories",
|
||||
"geschichten_published_on": "published on {date}",
|
||||
"journey_compiled_on": "compiled on {date}",
|
||||
|
||||
@@ -174,18 +174,12 @@
|
||||
"person_merge_warning": "Atención: Esta acción no se puede deshacer.",
|
||||
"person_label_notes": "Notas",
|
||||
"person_placeholder_notes": "Notas biográficas, observaciones…",
|
||||
"person_label_birth_date": "Fecha de nacimiento",
|
||||
"person_label_death_date": "Fecha de defunción",
|
||||
"person_label_birth_date_precision": "Precisión",
|
||||
"person_label_death_date_precision": "Precisión",
|
||||
"person_precision_hint": "¿Con qué precisión se conoce esta fecha?",
|
||||
"person_precision_day": "Fecha exacta (día)",
|
||||
"person_precision_month": "Mes conocido",
|
||||
"person_precision_year": "Solo año",
|
||||
"person_date_placeholder_hint": "Dejar vacío si es desconocido",
|
||||
"person_label_birth_year": "Año de nacimiento",
|
||||
"person_label_death_year": "Año de fallecimiento",
|
||||
"person_label_generation": "Generación",
|
||||
"person_option_generation_unset": "(ninguna)",
|
||||
"person_hint_generation": "Generación dentro de la familia (G 0 = generación más antigua)",
|
||||
"person_placeholder_year": "p.ej. 1923",
|
||||
"person_year_error": "Introduzca un año de cuatro dígitos",
|
||||
"person_years_error_order": "El año de nacimiento debe ser anterior al año de fallecimiento",
|
||||
"person_docs_heading": "Documentos enviados",
|
||||
@@ -649,8 +643,6 @@
|
||||
"error_alias_not_found": "No se encontro el alias de nombre.",
|
||||
"error_invalid_person_type": "El tipo de persona especificado no es válido.",
|
||||
"error_invalid_date_range": "La fecha final no puede ser anterior a la inicial.",
|
||||
"error_birth_after_death": "La fecha de nacimiento debe ser anterior a la de defunción.",
|
||||
"error_invalid_date_precision": "La fecha y la precisión no coinciden.",
|
||||
"validation_last_name_required": "El apellido es obligatorio.",
|
||||
"validation_first_name_required": "El nombre es obligatorio.",
|
||||
"error_ocr_service_unavailable": "El servicio OCR no está disponible.",
|
||||
@@ -1050,6 +1042,10 @@
|
||||
"geschichten_filter_document_chip": "Filtrado por carta:",
|
||||
"geschichten_filter_remove_document_chip": "Quitar la carta {title} del filtro",
|
||||
"geschichten_empty_for_document": "Aún no hay historias sobre esta carta",
|
||||
"geschichten_published_heading": "Publicadas",
|
||||
"geschichten_drafts_heading": "Borradores",
|
||||
"geschichten_draft_badge": "Borrador",
|
||||
"geschichten_drafts_unfiltered_caption": "(todos los borradores)",
|
||||
"geschichten_back_to_index": "Volver a Historias",
|
||||
"geschichten_published_on": "publicada el {date}",
|
||||
"journey_compiled_on": "recopilada el {date}",
|
||||
|
||||
@@ -335,10 +335,8 @@ describe('TranscriptionReadView — person-mention rendering', () => {
|
||||
displayName: 'Auguste Raddatz',
|
||||
personType: 'PERSON',
|
||||
familyMember: true,
|
||||
birthDate: '1882-01-01',
|
||||
birthDatePrecision: 'YEAR',
|
||||
deathDate: '1944-01-01',
|
||||
deathDatePrecision: 'YEAR'
|
||||
birthYear: 1882,
|
||||
deathYear: 1944
|
||||
})
|
||||
});
|
||||
})
|
||||
|
||||
@@ -1714,14 +1714,10 @@ export interface components {
|
||||
lastName?: string;
|
||||
alias?: string;
|
||||
notes?: string;
|
||||
/** Format: date */
|
||||
birthDate?: string;
|
||||
/** @enum {string} */
|
||||
birthDatePrecision?: "DAY" | "MONTH" | "SEASON" | "YEAR" | "RANGE" | "APPROX" | "UNKNOWN";
|
||||
/** Format: date */
|
||||
deathDate?: string;
|
||||
/** @enum {string} */
|
||||
deathDatePrecision?: "DAY" | "MONTH" | "SEASON" | "YEAR" | "RANGE" | "APPROX" | "UNKNOWN";
|
||||
/** Format: int32 */
|
||||
birthYear?: number;
|
||||
/** Format: int32 */
|
||||
deathYear?: number;
|
||||
/** Format: int32 */
|
||||
generation?: number;
|
||||
};
|
||||
@@ -1735,14 +1731,10 @@ export interface components {
|
||||
personType: "PERSON" | "INSTITUTION" | "GROUP" | "UNKNOWN" | "SKIP";
|
||||
alias?: string;
|
||||
notes?: string;
|
||||
/** Format: date */
|
||||
birthDate?: string;
|
||||
/** @enum {string} */
|
||||
birthDatePrecision: "DAY" | "MONTH" | "SEASON" | "YEAR" | "RANGE" | "APPROX" | "UNKNOWN";
|
||||
/** Format: date */
|
||||
deathDate?: string;
|
||||
/** @enum {string} */
|
||||
deathDatePrecision: "DAY" | "MONTH" | "SEASON" | "YEAR" | "RANGE" | "APPROX" | "UNKNOWN";
|
||||
/** Format: int32 */
|
||||
birthYear?: number;
|
||||
/** Format: int32 */
|
||||
deathYear?: number;
|
||||
/** Format: int32 */
|
||||
generation?: number;
|
||||
familyMember: boolean;
|
||||
@@ -2381,21 +2373,13 @@ export interface components {
|
||||
documentCount?: number;
|
||||
alias?: string;
|
||||
notes?: string;
|
||||
/** Format: date */
|
||||
birthDate?: string;
|
||||
/** @enum {string} */
|
||||
birthDatePrecision?: "DAY" | "MONTH" | "SEASON" | "YEAR" | "RANGE" | "APPROX" | "UNKNOWN";
|
||||
/** Format: date */
|
||||
deathDate?: string;
|
||||
/** @enum {string} */
|
||||
deathDatePrecision?: "DAY" | "MONTH" | "SEASON" | "YEAR" | "RANGE" | "APPROX" | "UNKNOWN";
|
||||
personType?: string;
|
||||
familyMember?: boolean;
|
||||
provisional?: boolean;
|
||||
/** Format: int32 */
|
||||
birthYear?: number;
|
||||
/** Format: int32 */
|
||||
deathYear?: number;
|
||||
provisional?: boolean;
|
||||
personType?: string;
|
||||
familyMember?: boolean;
|
||||
};
|
||||
InferredRelationshipWithPersonDTO: {
|
||||
person: components["schemas"]["PersonNodeDTO"];
|
||||
@@ -2492,6 +2476,8 @@ export interface components {
|
||||
/** Format: int32 */
|
||||
totalPages?: number;
|
||||
pageable?: components["schemas"]["PageableObject"];
|
||||
first?: boolean;
|
||||
last?: boolean;
|
||||
/** Format: int32 */
|
||||
size?: number;
|
||||
content?: components["schemas"]["NotificationDTO"][];
|
||||
@@ -2500,8 +2486,6 @@ export interface components {
|
||||
sort?: components["schemas"]["SortObject"];
|
||||
/** Format: int32 */
|
||||
numberOfElements?: number;
|
||||
first?: boolean;
|
||||
last?: boolean;
|
||||
empty?: boolean;
|
||||
};
|
||||
PageableObject: {
|
||||
@@ -2689,7 +2673,7 @@ export interface components {
|
||||
};
|
||||
ActivityFeedItemDTO: {
|
||||
/** @enum {string} */
|
||||
kind: "FILE_UPLOADED" | "STATUS_CHANGED" | "METADATA_UPDATED" | "TEXT_SAVED" | "BLOCK_REVIEWED" | "ANNOTATION_CREATED" | "COMMENT_ADDED" | "MENTION_CREATED" | "USER_CREATED" | "USER_DELETED" | "GROUP_MEMBERSHIP_CHANGED" | "LOGIN_SUCCESS" | "LOGIN_FAILED" | "LOGOUT" | "ADMIN_FORCE_LOGOUT" | "LOGIN_RATE_LIMITED" | "DOCUMENT_DELETED" | "JOURNEY_ITEM_ADDED" | "JOURNEY_ITEM_REMOVED" | "JOURNEY_ITEM_NOTE_UPDATED" | "JOURNEY_ITEMS_REORDERED";
|
||||
kind: "FILE_UPLOADED" | "STATUS_CHANGED" | "METADATA_UPDATED" | "TEXT_SAVED" | "BLOCK_REVIEWED" | "ANNOTATION_CREATED" | "COMMENT_ADDED" | "MENTION_CREATED" | "USER_CREATED" | "USER_DELETED" | "GROUP_MEMBERSHIP_CHANGED" | "LOGIN_SUCCESS" | "LOGIN_FAILED" | "LOGOUT" | "ADMIN_FORCE_LOGOUT" | "LOGIN_RATE_LIMITED" | "JOURNEY_ITEM_ADDED" | "JOURNEY_ITEM_REMOVED" | "JOURNEY_ITEM_NOTE_UPDATED" | "JOURNEY_ITEMS_REORDERED";
|
||||
actor?: components["schemas"]["ActivityActorDTO"];
|
||||
/** Format: uuid */
|
||||
documentId: string;
|
||||
@@ -5557,7 +5541,7 @@ export interface operations {
|
||||
query?: {
|
||||
limit?: number;
|
||||
/** @description Filter by audit kinds; omit for all rollup-eligible kinds */
|
||||
kinds?: ("FILE_UPLOADED" | "STATUS_CHANGED" | "METADATA_UPDATED" | "TEXT_SAVED" | "BLOCK_REVIEWED" | "ANNOTATION_CREATED" | "COMMENT_ADDED" | "MENTION_CREATED" | "USER_CREATED" | "USER_DELETED" | "GROUP_MEMBERSHIP_CHANGED" | "LOGIN_SUCCESS" | "LOGIN_FAILED" | "LOGOUT" | "ADMIN_FORCE_LOGOUT" | "LOGIN_RATE_LIMITED" | "DOCUMENT_DELETED" | "JOURNEY_ITEM_ADDED" | "JOURNEY_ITEM_REMOVED" | "JOURNEY_ITEM_NOTE_UPDATED" | "JOURNEY_ITEMS_REORDERED")[];
|
||||
kinds?: ("FILE_UPLOADED" | "STATUS_CHANGED" | "METADATA_UPDATED" | "TEXT_SAVED" | "BLOCK_REVIEWED" | "ANNOTATION_CREATED" | "COMMENT_ADDED" | "MENTION_CREATED" | "USER_CREATED" | "USER_DELETED" | "GROUP_MEMBERSHIP_CHANGED" | "LOGIN_SUCCESS" | "LOGIN_FAILED" | "LOGOUT" | "ADMIN_FORCE_LOGOUT" | "LOGIN_RATE_LIMITED" | "JOURNEY_ITEM_ADDED" | "JOURNEY_ITEM_REMOVED" | "JOURNEY_ITEM_NOTE_UPDATED" | "JOURNEY_ITEMS_REORDERED")[];
|
||||
};
|
||||
header?: never;
|
||||
path?: never;
|
||||
|
||||
@@ -10,8 +10,6 @@ const personFactory = (id: string, displayName: string) => ({
|
||||
lastName: displayName.split(' ').slice(1).join(' ') || displayName,
|
||||
displayName,
|
||||
personType: 'PERSON' as const,
|
||||
birthDatePrecision: 'UNKNOWN' as const,
|
||||
deathDatePrecision: 'UNKNOWN' as const,
|
||||
familyMember: false,
|
||||
provisional: false
|
||||
});
|
||||
|
||||
@@ -7,12 +7,13 @@ import type { components } from '$lib/generated/api';
|
||||
|
||||
type GeschichteRow = Pick<
|
||||
components['schemas']['GeschichteSummary'],
|
||||
'id' | 'title' | 'body' | 'type' | 'author' | 'publishedAt'
|
||||
'id' | 'title' | 'body' | 'type' | 'status' | 'author' | 'publishedAt'
|
||||
>;
|
||||
|
||||
let { geschichte }: { geschichte: GeschichteRow } = $props();
|
||||
|
||||
const isJourney = $derived(geschichte.type === 'JOURNEY');
|
||||
const isDraft = $derived(geschichte.status === 'DRAFT');
|
||||
|
||||
const publishedAt = $derived(formatPublishedAt(geschichte.publishedAt, 'short'));
|
||||
|
||||
@@ -44,12 +45,20 @@ const authorName = $derived(formatAuthorName(geschichte.author));
|
||||
{m.journey_badge_list()}
|
||||
</span>
|
||||
{/if}
|
||||
{#if isDraft}
|
||||
<span
|
||||
data-testid="draft-badge"
|
||||
class="inline-flex items-center rounded-sm border border-line bg-canvas px-1.5 py-px font-sans text-xs font-bold tracking-wide text-ink-3 uppercase"
|
||||
>
|
||||
{m.geschichten_draft_badge()}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Content column -->
|
||||
<div class="min-w-0 flex-1 p-3 sm:px-4">
|
||||
<!-- Compact meta line (mobile only) -->
|
||||
<div class="mb-1 flex items-center gap-1.5 sm:hidden">
|
||||
<div class="mb-1 flex flex-wrap items-center gap-1.5 sm:hidden">
|
||||
<!-- 7px initials render as smudge at this size — a plain color dot reads better -->
|
||||
<span
|
||||
aria-hidden="true"
|
||||
@@ -57,6 +66,14 @@ const authorName = $derived(formatAuthorName(geschichte.author));
|
||||
style="background-color: {personAvatarColor(authorName)}"
|
||||
></span>
|
||||
<span class="font-sans text-sm font-semibold text-ink">{authorName}</span>
|
||||
{#if isDraft}
|
||||
<span
|
||||
data-testid="draft-badge-mobile"
|
||||
class="inline-flex shrink-0 items-center rounded-sm border border-line bg-canvas px-1.5 py-px font-sans text-xs font-bold tracking-wide text-ink-3 uppercase"
|
||||
>
|
||||
{m.geschichten_draft_badge()}
|
||||
</span>
|
||||
{/if}
|
||||
{#if publishedAt}
|
||||
<span class="ml-auto font-sans text-sm text-ink-3">{publishedAt}</span>
|
||||
{/if}
|
||||
|
||||
@@ -91,4 +91,34 @@ describe('GeschichteListRow', () => {
|
||||
render(GeschichteListRow, { props: { geschichte: baseRow() } });
|
||||
expect(document.body.textContent).toContain('Anna Schmidt');
|
||||
});
|
||||
|
||||
it('shows no draft badge for PUBLISHED stories', async () => {
|
||||
render(GeschichteListRow, { props: { geschichte: baseRow({ status: 'PUBLISHED' }) } });
|
||||
expect(document.querySelector('[data-testid="draft-badge"]')).toBeNull();
|
||||
expect(document.querySelector('[data-testid="draft-badge-mobile"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows desktop draft badge for DRAFT stories', async () => {
|
||||
render(GeschichteListRow, { props: { geschichte: baseRow({ status: 'DRAFT' }) } });
|
||||
const badge = document.querySelector('[data-testid="draft-badge"]');
|
||||
expect(badge).not.toBeNull();
|
||||
});
|
||||
|
||||
it('shows mobile draft badge for DRAFT stories', async () => {
|
||||
render(GeschichteListRow, { props: { geschichte: baseRow({ status: 'DRAFT' }) } });
|
||||
const badge = document.querySelector('[data-testid="draft-badge-mobile"]');
|
||||
expect(badge).not.toBeNull();
|
||||
});
|
||||
|
||||
it('draft badge is a plain <span>', async () => {
|
||||
render(GeschichteListRow, { props: { geschichte: baseRow({ status: 'DRAFT' }) } });
|
||||
const badge = document.querySelector('[data-testid="draft-badge"]');
|
||||
expect(badge?.tagName.toLowerCase()).toBe('span');
|
||||
});
|
||||
|
||||
it('draft badge uses text-xs label size', async () => {
|
||||
render(GeschichteListRow, { props: { geschichte: baseRow({ status: 'DRAFT' }) } });
|
||||
const badge = document.querySelector('[data-testid="draft-badge"]');
|
||||
expect(badge!.className).toContain('text-xs');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
import { formatLifeDateRange } from '$lib/person/personLifeDates';
|
||||
import PersonTypeBadge from '$lib/person/PersonTypeBadge.svelte';
|
||||
import type { components } from '$lib/generated/api';
|
||||
|
||||
@@ -124,17 +125,10 @@ const documentCount = $derived(person.documentCount ?? 0);
|
||||
<p class="font-sans text-sm text-ink-2 italic">„{person.alias}"</p>
|
||||
{/if}
|
||||
|
||||
<!-- Life dates — PersonSummaryDTO is year-shaped by design (ADR-039); the glyphs are
|
||||
aria-hidden so screen readers only announce the years. -->
|
||||
<!-- Life dates -->
|
||||
{#if person.birthYear || person.deathYear}
|
||||
<p class="font-sans text-sm text-ink-3">
|
||||
{#if person.birthYear}
|
||||
<span aria-hidden="true">*</span> {person.birthYear}
|
||||
{/if}
|
||||
{#if person.birthYear && person.deathYear}–{/if}
|
||||
{#if person.deathYear}
|
||||
<span aria-hidden="true">†</span> {person.deathYear}
|
||||
{/if}
|
||||
{formatLifeDateRange(person.birthYear, person.deathYear)}
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
|
||||
@@ -30,27 +30,6 @@ describe('PersonCard — confirmed person', () => {
|
||||
render(PersonCard, { props: { person: makePerson() } });
|
||||
await expect.element(page.getByText('unbestätigt')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
// PersonSummaryDTO intentionally stays year-shaped (ADR-039): the list shows
|
||||
// year precision only; full dates live on the detail page.
|
||||
it('renders the year-only life-date range', async () => {
|
||||
render(PersonCard, { props: { person: makePerson({ birthYear: 1899, deathYear: 1972 }) } });
|
||||
await expect.element(page.getByText(/1899/)).toBeVisible();
|
||||
await expect.element(page.getByText(/1972/)).toBeVisible();
|
||||
});
|
||||
|
||||
it('renders birth-only without dash and wraps glyphs in aria-hidden spans', async () => {
|
||||
const { container } = render(PersonCard, {
|
||||
props: { person: makePerson({ birthYear: 1899 }) }
|
||||
});
|
||||
await expect.element(page.getByText(/1899/)).toBeVisible();
|
||||
expect(container.textContent).not.toContain('–');
|
||||
expect(container.textContent).not.toContain('†');
|
||||
const hidden = [...container.querySelectorAll('span[aria-hidden="true"]')].map((el) =>
|
||||
el.textContent?.trim()
|
||||
);
|
||||
expect(hidden).toContain('*');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PersonCard — unconfirmed badge keys off provisional only (badge ⇔ count ⇔ triage parity)', () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
import { formatLifeDate } from '$lib/person/personLifeDates';
|
||||
import { formatLifeDateRange } from '$lib/person/personLifeDates';
|
||||
import { chipLabel, otherName } from '$lib/person/relationshipLabels';
|
||||
import type { components } from '$lib/generated/api';
|
||||
import type { LoadState } from '$lib/person/personHoverCard';
|
||||
@@ -31,14 +31,9 @@ const familyChips = $derived(
|
||||
: []
|
||||
);
|
||||
|
||||
const birthText = $derived(
|
||||
const dateRange = $derived(
|
||||
state.status === 'loaded'
|
||||
? formatLifeDate(state.person.birthDate, state.person.birthDatePrecision)
|
||||
: ''
|
||||
);
|
||||
const deathText = $derived(
|
||||
state.status === 'loaded'
|
||||
? formatLifeDate(state.person.deathDate, state.person.deathDatePrecision)
|
||||
? formatLifeDateRange(state.person.birthYear, state.person.deathYear)
|
||||
: ''
|
||||
);
|
||||
|
||||
@@ -128,17 +123,8 @@ const showMaidenName = $derived(
|
||||
<div data-testid="person-hover-card-content" class="content">
|
||||
<div class="header">
|
||||
<div class="name" data-testid="person-hover-card-name">{state.person.displayName}</div>
|
||||
{#if birthText || deathText}
|
||||
<!-- Glyphs aria-hidden so screen readers only announce the dates -->
|
||||
<div class="dates" data-testid="person-hover-card-dates">
|
||||
{#if birthText}
|
||||
<span aria-hidden="true">*</span> {birthText}
|
||||
{/if}
|
||||
{#if birthText && deathText}–{/if}
|
||||
{#if deathText}
|
||||
<span aria-hidden="true">†</span> {deathText}
|
||||
{/if}
|
||||
</div>
|
||||
{#if dateRange}
|
||||
<div class="dates" data-testid="person-hover-card-dates">{dateRange}</div>
|
||||
{/if}
|
||||
{#if showMaidenName}
|
||||
<div class="maiden" data-testid="person-hover-card-maiden">
|
||||
|
||||
@@ -14,10 +14,8 @@ const AUGUSTE: Person = {
|
||||
displayName: 'Auguste Raddatz',
|
||||
personType: 'PERSON',
|
||||
familyMember: true,
|
||||
birthDate: '1882-01-01',
|
||||
birthDatePrecision: 'YEAR',
|
||||
deathDate: '1944-01-01',
|
||||
deathDatePrecision: 'YEAR'
|
||||
birthYear: 1882,
|
||||
deathYear: 1944
|
||||
} as unknown as Person;
|
||||
|
||||
const POSITION = { top: 100, left: 200 };
|
||||
@@ -83,76 +81,18 @@ describe('PersonHoverCard — loaded state', () => {
|
||||
await expect.element(page.getByText('Auguste Raddatz')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the life-date range when birth and death dates are present', async () => {
|
||||
it('renders the life-date range when birthYear and deathYear are present', async () => {
|
||||
render(PersonHoverCard, {
|
||||
personId: 'p-aug',
|
||||
cardId: 'card-1',
|
||||
position: POSITION,
|
||||
state: { status: 'loaded', person: AUGUSTE, relationships: [] }
|
||||
});
|
||||
await expect
|
||||
.element(page.getByTestId('person-hover-card-dates'))
|
||||
.toHaveTextContent('* 1882 – † 1944');
|
||||
await expect.element(page.getByText('* 1882 – † 1944')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders a DAY-precision birth date as a full localized date', async () => {
|
||||
const exact = {
|
||||
...AUGUSTE,
|
||||
birthDate: '1882-03-14',
|
||||
birthDatePrecision: 'DAY'
|
||||
} as unknown as Person;
|
||||
render(PersonHoverCard, {
|
||||
personId: 'p-aug',
|
||||
cardId: 'card-1',
|
||||
position: POSITION,
|
||||
state: { status: 'loaded', person: exact, relationships: [] }
|
||||
});
|
||||
await expect
|
||||
.element(page.getByTestId('person-hover-card-dates'))
|
||||
.toHaveTextContent('14. März 1882');
|
||||
});
|
||||
|
||||
it('renders APPROX-precision legacy dates with the ca. prefix', async () => {
|
||||
const approx = {
|
||||
...AUGUSTE,
|
||||
birthDate: '1882-01-01',
|
||||
birthDatePrecision: 'APPROX',
|
||||
deathDate: undefined,
|
||||
deathDatePrecision: 'UNKNOWN'
|
||||
} as unknown as Person;
|
||||
render(PersonHoverCard, {
|
||||
personId: 'p-aug',
|
||||
cardId: 'card-1',
|
||||
position: POSITION,
|
||||
state: { status: 'loaded', person: approx, relationships: [] }
|
||||
});
|
||||
await expect.element(page.getByTestId('person-hover-card-dates')).toHaveTextContent('ca. 1882');
|
||||
});
|
||||
|
||||
it('keeps the * and † glyphs out of the accessible text via aria-hidden', async () => {
|
||||
render(PersonHoverCard, {
|
||||
personId: 'p-aug',
|
||||
cardId: 'card-1',
|
||||
position: POSITION,
|
||||
state: { status: 'loaded', person: AUGUSTE, relationships: [] }
|
||||
});
|
||||
const hidden = [
|
||||
...document.querySelectorAll(
|
||||
'[data-testid="person-hover-card-dates"] span[aria-hidden="true"]'
|
||||
)
|
||||
].map((el) => el.textContent?.trim());
|
||||
expect(hidden).toContain('*');
|
||||
expect(hidden).toContain('†');
|
||||
});
|
||||
|
||||
it('omits the life-date line when both dates are missing', async () => {
|
||||
const noDates = {
|
||||
...AUGUSTE,
|
||||
birthDate: undefined,
|
||||
birthDatePrecision: 'UNKNOWN',
|
||||
deathDate: undefined,
|
||||
deathDatePrecision: 'UNKNOWN'
|
||||
} as unknown as Person;
|
||||
it('omits the life-date line when both years are missing', async () => {
|
||||
const noDates = { ...AUGUSTE, birthYear: undefined, deathYear: undefined } as Person;
|
||||
render(PersonHoverCard, {
|
||||
personId: 'p-aug',
|
||||
cardId: 'card-1',
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
import DateInput from '$lib/shared/primitives/DateInput.svelte';
|
||||
import type { DatePrecision } from '$lib/shared/utils/documentDate';
|
||||
|
||||
// Only DAY / MONTH / YEAR are offered for life dates: RANGE and SEASON make no
|
||||
// sense for a birth or death, and APPROX stays display-only for legacy imports (#773).
|
||||
const PERSON_DATE_PRECISIONS: { value: DatePrecision; label: () => string }[] = [
|
||||
{ value: 'DAY', label: m.person_precision_day },
|
||||
{ value: 'MONTH', label: m.person_precision_month },
|
||||
{ value: 'YEAR', label: m.person_precision_year }
|
||||
];
|
||||
|
||||
let {
|
||||
name,
|
||||
legend,
|
||||
precisionLabel,
|
||||
initialIso = '',
|
||||
initialPrecision = null
|
||||
}: {
|
||||
name: string;
|
||||
legend: string;
|
||||
precisionLabel: string;
|
||||
initialIso?: string | null;
|
||||
initialPrecision?: string | null;
|
||||
} = $props();
|
||||
|
||||
let iso = $state('');
|
||||
let errorMessage = $state<string | null>(null);
|
||||
let inputEl = $state<HTMLInputElement | undefined>();
|
||||
let precision = $state<DatePrecision>('DAY');
|
||||
|
||||
// Seed once at mount (WhoWhenSection pattern): a later load() rerun must not
|
||||
// stomp the user's in-progress edit.
|
||||
onMount(() => {
|
||||
if (initialIso) {
|
||||
iso = initialIso;
|
||||
}
|
||||
const offered = PERSON_DATE_PRECISIONS.some((p) => p.value === initialPrecision);
|
||||
if (offered) {
|
||||
precision = initialPrecision as DatePrecision;
|
||||
} else if (initialIso) {
|
||||
// Legacy APPROX/SEASON/RANGE precision is not editable here — seed YEAR so an
|
||||
// untouched save does not silently claim DAY precision for the stored date.
|
||||
precision = 'YEAR';
|
||||
}
|
||||
});
|
||||
|
||||
// A partial date leaves the hidden ISO empty — submitting then would silently
|
||||
// clear a stored date. Block native submission until completed or fully emptied.
|
||||
$effect(() => {
|
||||
inputEl?.setCustomValidity(errorMessage ?? '');
|
||||
});
|
||||
|
||||
const controlCls =
|
||||
'block min-h-[44px] w-full rounded border border-line px-3 py-2 font-serif text-ink focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring';
|
||||
</script>
|
||||
|
||||
<fieldset>
|
||||
<legend class="mb-1 block text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{legend}
|
||||
</legend>
|
||||
<div class="flex flex-col gap-2 sm:flex-row">
|
||||
<div class="flex-1">
|
||||
<DateInput
|
||||
bind:value={iso}
|
||||
bind:errorMessage={errorMessage}
|
||||
bind:inputEl={inputEl}
|
||||
name={name}
|
||||
id={name}
|
||||
placeholder="TT.MM.JJJJ"
|
||||
ariaLabel={legend}
|
||||
ariaDescribedby={errorMessage ? `${name}-error` : undefined}
|
||||
class={controlCls}
|
||||
/>
|
||||
{#if errorMessage}
|
||||
<p id="{name}-error" class="mt-1 font-sans text-xs text-red-600">{errorMessage}</p>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
<select
|
||||
id="{name}Precision"
|
||||
name="{name}Precision"
|
||||
aria-label="{legend}: {precisionLabel}"
|
||||
bind:value={precision}
|
||||
class="{controlCls} bg-surface"
|
||||
>
|
||||
{#each PERSON_DATE_PRECISIONS as p (p.value)}
|
||||
<option value={p.value}>{p.label()}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<p class="mt-1 font-sans text-xs text-ink-3">
|
||||
{m.person_precision_hint()} · {m.person_date_placeholder_hint()}
|
||||
</p>
|
||||
</fieldset>
|
||||
@@ -1,64 +0,0 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest';
|
||||
import { cleanup, render } from 'vitest-browser-svelte';
|
||||
import { page, userEvent } from 'vitest/browser';
|
||||
import PersonLifeDateField from './PersonLifeDateField.svelte';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const baseProps = {
|
||||
name: 'birthDate',
|
||||
legend: 'Geburtsdatum',
|
||||
precisionLabel: 'Genauigkeit'
|
||||
};
|
||||
|
||||
const visibleInput = () => page.getByLabelText('Geburtsdatum', { exact: true });
|
||||
const hiddenIso = () => document.querySelector<HTMLInputElement>('input[name="birthDate"]');
|
||||
|
||||
describe('PersonLifeDateField', () => {
|
||||
it('shows the format error and flags the input invalid for a partial date', async () => {
|
||||
render(PersonLifeDateField, { props: baseProps });
|
||||
|
||||
await userEvent.fill(visibleInput(), '14.03.');
|
||||
|
||||
await expect.element(page.getByText(m.form_date_error())).toBeVisible();
|
||||
const input = (await visibleInput().element()) as HTMLInputElement;
|
||||
expect(input.checkValidity()).toBe(false);
|
||||
expect(hiddenIso()?.value).toBe('');
|
||||
});
|
||||
|
||||
it('clears error and custom validity when the input is fully emptied', async () => {
|
||||
render(PersonLifeDateField, { props: { ...baseProps, initialIso: '1899-03-14' } });
|
||||
|
||||
await userEvent.fill(visibleInput(), '');
|
||||
|
||||
await expect.element(page.getByText(m.form_date_error())).not.toBeInTheDocument();
|
||||
const input = (await visibleInput().element()) as HTMLInputElement;
|
||||
expect(input.checkValidity()).toBe(true);
|
||||
// Empty hidden ISO is the intentional clear path — the server action omits the pair.
|
||||
expect(hiddenIso()?.value).toBe('');
|
||||
});
|
||||
|
||||
it('keeps a stored date submittable when untouched', async () => {
|
||||
render(PersonLifeDateField, {
|
||||
props: { ...baseProps, initialIso: '1899-03-14', initialPrecision: 'DAY' }
|
||||
});
|
||||
|
||||
await expect.element(visibleInput()).toHaveValue('14.03.1899');
|
||||
const input = (await visibleInput().element()) as HTMLInputElement;
|
||||
expect(input.checkValidity()).toBe(true);
|
||||
expect(hiddenIso()?.value).toBe('1899-03-14');
|
||||
});
|
||||
|
||||
it('becomes valid again once the partial date is completed', async () => {
|
||||
render(PersonLifeDateField, { props: baseProps });
|
||||
|
||||
await userEvent.fill(visibleInput(), '14.03.');
|
||||
await userEvent.fill(visibleInput(), '14.03.1899');
|
||||
|
||||
await expect.element(page.getByText(m.form_date_error())).not.toBeInTheDocument();
|
||||
const input = (await visibleInput().element()) as HTMLInputElement;
|
||||
expect(input.checkValidity()).toBe(true);
|
||||
expect(hiddenIso()?.value).toBe('1899-03-14');
|
||||
});
|
||||
});
|
||||
@@ -9,10 +9,8 @@ export type PersonFormData = {
|
||||
firstName?: string | null;
|
||||
lastName: string;
|
||||
alias?: string | null;
|
||||
birthDate?: string | null;
|
||||
birthDatePrecision?: string | null;
|
||||
deathDate?: string | null;
|
||||
deathDatePrecision?: string | null;
|
||||
birthYear?: number | null;
|
||||
deathYear?: number | null;
|
||||
generation?: number | null;
|
||||
notes?: string | null;
|
||||
};
|
||||
|
||||
@@ -1,113 +1,24 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { formatLifeDate, formatLifeDateRange } from './personLifeDates';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { formatLifeDateRange } from './personLifeDates';
|
||||
|
||||
// Delegates all precision rendering to formatDocumentDate — these tests pin the
|
||||
// composition (glyphs, dash, empty sides) and one rendering per precision so a
|
||||
// regression in the delegation is caught here, not on a person card.
|
||||
describe('formatLifeDateRange', () => {
|
||||
describe('both dates (de default)', () => {
|
||||
it('renders DAY precision as full dates', () => {
|
||||
expect(formatLifeDateRange('1901-03-14', 'DAY', '1944-11-02', 'DAY')).toBe(
|
||||
'* 14. März 1901 – † 2. November 1944'
|
||||
);
|
||||
});
|
||||
|
||||
it('renders MONTH precision as month + year', () => {
|
||||
expect(formatLifeDateRange('1901-03-01', 'MONTH', '1944-11-01', 'MONTH')).toBe(
|
||||
'* März 1901 – † November 1944'
|
||||
);
|
||||
});
|
||||
|
||||
it('renders YEAR precision as bare years', () => {
|
||||
expect(formatLifeDateRange('1901-01-01', 'YEAR', '1944-01-01', 'YEAR')).toBe(
|
||||
'* 1901 – † 1944'
|
||||
);
|
||||
});
|
||||
|
||||
it('renders mixed precisions per side', () => {
|
||||
expect(formatLifeDateRange('1901-03-14', 'DAY', '1944-01-01', 'YEAR')).toBe(
|
||||
'* 14. März 1901 – † 1944'
|
||||
);
|
||||
});
|
||||
|
||||
it('renders APPROX precision with the ca. prefix (legacy imports)', () => {
|
||||
expect(formatLifeDateRange('1901-01-01', 'APPROX', '1944-01-01', 'APPROX')).toBe(
|
||||
'* ca. 1901 – † ca. 1944'
|
||||
);
|
||||
});
|
||||
it('returns both dates when birth and death year are given', () => {
|
||||
expect(formatLifeDateRange(1882, 1944)).toBe('* 1882 – † 1944');
|
||||
});
|
||||
|
||||
describe('single sides and empty states', () => {
|
||||
it('renders birth only without dash or dagger', () => {
|
||||
expect(formatLifeDateRange('1901-03-14', 'DAY', null, null)).toBe('* 14. März 1901');
|
||||
});
|
||||
|
||||
it('renders death only without dash or asterisk', () => {
|
||||
expect(formatLifeDateRange(null, null, '1944-11-02', 'DAY')).toBe('† 2. November 1944');
|
||||
});
|
||||
|
||||
it('renders YEAR birth only', () => {
|
||||
expect(formatLifeDateRange('1882-01-01', 'YEAR', null, null)).toBe('* 1882');
|
||||
});
|
||||
|
||||
it('renders APPROX death only', () => {
|
||||
expect(formatLifeDateRange(null, null, '1944-01-01', 'APPROX')).toBe('† ca. 1944');
|
||||
});
|
||||
|
||||
it('returns empty string when both dates are null', () => {
|
||||
expect(formatLifeDateRange(null, null, null, null)).toBe('');
|
||||
});
|
||||
|
||||
it('returns empty string when both dates are null even with UNKNOWN precisions', () => {
|
||||
expect(formatLifeDateRange(null, 'UNKNOWN', null, 'UNKNOWN')).toBe('');
|
||||
});
|
||||
|
||||
it('falls back to YEAR rendering when a precision is missing', () => {
|
||||
expect(formatLifeDateRange('1901-01-01', null, null, null)).toBe('* 1901');
|
||||
});
|
||||
it('returns only birth year when only birthYear is given', () => {
|
||||
expect(formatLifeDateRange(1882, undefined)).toBe('* 1882');
|
||||
});
|
||||
|
||||
describe('locales (German-month-leak guard)', () => {
|
||||
it('renders DAY precision in English', () => {
|
||||
expect(formatLifeDateRange('1901-03-14', 'DAY', null, null, 'en')).toBe('* March 14, 1901');
|
||||
});
|
||||
it('returns only death year when only deathYear is given', () => {
|
||||
expect(formatLifeDateRange(undefined, 1944)).toBe('† 1944');
|
||||
});
|
||||
|
||||
it('renders MONTH precision in English', () => {
|
||||
expect(formatLifeDateRange('1901-03-01', 'MONTH', null, null, 'en')).toBe('* March 1901');
|
||||
});
|
||||
it('returns empty string when neither year is given', () => {
|
||||
expect(formatLifeDateRange(undefined, undefined)).toBe('');
|
||||
});
|
||||
|
||||
it('renders DAY precision in Spanish', () => {
|
||||
expect(formatLifeDateRange('1901-03-14', 'DAY', null, null, 'es')).toBe(
|
||||
'* 14 de marzo de 1901'
|
||||
);
|
||||
});
|
||||
|
||||
it('renders MONTH precision in Spanish', () => {
|
||||
expect(formatLifeDateRange('1901-03-01', 'MONTH', null, null, 'es')).toBe('* marzo de 1901');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Single-date helper for components that must keep the * / † glyphs in their own
|
||||
// aria-hidden markup (PersonCard, PersonHoverCard) instead of in the string.
|
||||
describe('formatLifeDate', () => {
|
||||
it('renders a DAY-precision date without any glyph', () => {
|
||||
expect(formatLifeDate('1901-03-14', 'DAY')).toBe('14. März 1901');
|
||||
});
|
||||
|
||||
it('renders an APPROX-precision date (legacy imports)', () => {
|
||||
expect(formatLifeDate('1901-01-01', 'APPROX')).toBe('ca. 1901');
|
||||
});
|
||||
|
||||
it('falls back to YEAR rendering when precision is missing', () => {
|
||||
expect(formatLifeDate('1901-01-01', null)).toBe('1901');
|
||||
});
|
||||
|
||||
it('returns empty string for a null date', () => {
|
||||
expect(formatLifeDate(null, 'DAY')).toBe('');
|
||||
});
|
||||
|
||||
it('renders in the requested locale', () => {
|
||||
expect(formatLifeDate('1901-03-14', 'DAY', 'en')).toBe('March 14, 1901');
|
||||
it('returns empty string when both are null', () => {
|
||||
expect(formatLifeDateRange(null, null)).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,44 +1,20 @@
|
||||
import { formatDocumentDate, type DatePrecision } from '$lib/shared/utils/documentDate';
|
||||
|
||||
/**
|
||||
* Formats one life date (birth or death) at the precision the data claims,
|
||||
* delegating all rendering to {@link formatDocumentDate}. Returns '' for a
|
||||
* missing date. Carries no * / † glyph — components that need the glyphs wrap
|
||||
* them in their own `aria-hidden` markup so screen readers only hear the date.
|
||||
*
|
||||
* A missing precision falls back to YEAR: pre-V76 rows only knew a year, and
|
||||
* a bare year is the only safe rendering for a date without precision metadata.
|
||||
*/
|
||||
export function formatLifeDate(
|
||||
date: string | null | undefined,
|
||||
precision: DatePrecision | null | undefined,
|
||||
locale?: string
|
||||
): string {
|
||||
if (!date) {
|
||||
return '';
|
||||
}
|
||||
return formatDocumentDate(date, precision ?? 'YEAR', null, null, locale);
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats the full life date range as plain text, e.g. for dropdown subtitles.
|
||||
* Formats the life date range for a person.
|
||||
* Examples:
|
||||
* * 14. März 1901 – † 2. November 1944 (both, DAY precision)
|
||||
* * 1882 (birth only, YEAR precision)
|
||||
* † ca. 1944 (death only, APPROX precision)
|
||||
* "" (neither)
|
||||
* * 1882 – † 1944 (both)
|
||||
* * 1882 (birth only)
|
||||
* † 1944 (death only)
|
||||
* "" (neither)
|
||||
*/
|
||||
export function formatLifeDateRange(
|
||||
birthDate: string | null | undefined,
|
||||
birthDatePrecision: DatePrecision | null | undefined,
|
||||
deathDate: string | null | undefined,
|
||||
deathDatePrecision: DatePrecision | null | undefined,
|
||||
locale?: string
|
||||
): string {
|
||||
const birth = birthDate ? `* ${formatLifeDate(birthDate, birthDatePrecision, locale)}` : null;
|
||||
const death = deathDate ? `† ${formatLifeDate(deathDate, deathDatePrecision, locale)}` : null;
|
||||
if (birth && death) {
|
||||
return `${birth} – ${death}`;
|
||||
export function formatLifeDateRange(birthYear?: number | null, deathYear?: number | null): string {
|
||||
if (birthYear && deathYear) {
|
||||
return `* ${birthYear} – † ${deathYear}`;
|
||||
}
|
||||
return birth ?? death ?? '';
|
||||
if (birthYear) {
|
||||
return `* ${birthYear}`;
|
||||
}
|
||||
if (deathYear) {
|
||||
return `† ${deathYear}`;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
@@ -143,8 +143,6 @@ describe('ReaderRecentDocs', () => {
|
||||
firstName: 'Anna',
|
||||
displayName: 'Anna Müller',
|
||||
personType: 'PERSON' as const,
|
||||
birthDatePrecision: 'UNKNOWN' as const,
|
||||
deathDatePrecision: 'UNKNOWN' as const,
|
||||
familyMember: false,
|
||||
provisional: false
|
||||
}
|
||||
|
||||
@@ -15,9 +15,7 @@ import { m } from '$lib/paraglide/messages.js';
|
||||
// — see Felix #3 on PR #629.
|
||||
import { MAX_QUERY_LENGTH } from './mentionConstants';
|
||||
|
||||
// PersonSummaryDTO, not Person: /api/persons list items are the summary projection.
|
||||
// Typing them as the full entity hid a runtime bug (missing date fields, #812).
|
||||
type Person = components['schemas']['PersonSummaryDTO'];
|
||||
type Person = components['schemas']['Person'];
|
||||
|
||||
// The dropdown receives a single reactive state object. PersonMentionEditor
|
||||
// mutates fields on this object (model.items = ..., etc.) and Svelte's $state
|
||||
@@ -308,12 +306,6 @@ function selectItem(item: Person) {
|
||||
</a>
|
||||
{:else}
|
||||
{#each model.items as person, i (person.id)}
|
||||
{@const lifeDates = formatLifeDateRange(
|
||||
person.birthDate,
|
||||
person.birthDatePrecision,
|
||||
person.deathDate,
|
||||
person.deathDatePrecision
|
||||
)}
|
||||
<div
|
||||
class={[
|
||||
'flex min-h-[44px] cursor-pointer flex-col gap-1 px-3 py-2.5 text-left hover:bg-canvas',
|
||||
@@ -333,11 +325,9 @@ function selectItem(item: Person) {
|
||||
}}
|
||||
>
|
||||
<span class="truncate font-serif text-base text-ink">{person.displayName}</span>
|
||||
{#if lifeDates}
|
||||
<!-- whitespace-normal: a DAY-precision range (~37 chars) wraps to a second
|
||||
line at 320px instead of being clipped by truncate. -->
|
||||
<span class="font-sans text-xs whitespace-normal text-ink-3">
|
||||
{lifeDates}
|
||||
{#if formatLifeDateRange(person.birthYear, person.deathYear)}
|
||||
<span class="truncate font-sans text-xs text-ink-3">
|
||||
{formatLifeDateRange(person.birthYear, person.deathYear)}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -7,9 +7,7 @@ import MentionDropdownFixture from './MentionDropdown.test-fixture.svelte';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
import type { components } from '$lib/generated/api';
|
||||
|
||||
// PersonSummaryDTO mirrors the real runtime shape: /api/persons list items are
|
||||
// the summary projection, not the full entity (#812).
|
||||
type Person = components['schemas']['PersonSummaryDTO'];
|
||||
type Person = components['schemas']['Person'];
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
@@ -21,8 +19,6 @@ const makePerson = (id: string, name: string, overrides: Partial<Person> = {}):
|
||||
lastName: parts.slice(1).join(' ') || name,
|
||||
displayName: name,
|
||||
personType: 'PERSON',
|
||||
birthDatePrecision: 'UNKNOWN',
|
||||
deathDatePrecision: 'UNKNOWN',
|
||||
familyMember: false,
|
||||
provisional: false,
|
||||
...overrides
|
||||
@@ -107,18 +103,11 @@ describe('MentionDropdown', () => {
|
||||
expect(option?.getAttribute('aria-selected')).toBe('true');
|
||||
});
|
||||
|
||||
it('renders the life-date range when birth or death date is present', async () => {
|
||||
it('renders the life-date range when birthYear or deathYear is present', async () => {
|
||||
render(MentionDropdown, {
|
||||
props: {
|
||||
model: baseModel({
|
||||
items: [
|
||||
makePerson('p1', 'Anna', {
|
||||
birthDate: '1899-01-01',
|
||||
birthDatePrecision: 'YEAR',
|
||||
deathDate: '1972-01-01',
|
||||
deathDatePrecision: 'YEAR'
|
||||
})
|
||||
]
|
||||
items: [makePerson('p1', 'Anna', { birthYear: 1899, deathYear: 1972 })]
|
||||
})
|
||||
}
|
||||
});
|
||||
@@ -126,25 +115,6 @@ describe('MentionDropdown', () => {
|
||||
await expect.element(page.getByText(/1899/)).toBeVisible();
|
||||
});
|
||||
|
||||
it('renders a DAY-precision birth date as a full date without clipping it away', async () => {
|
||||
render(MentionDropdown, {
|
||||
props: {
|
||||
model: baseModel({
|
||||
items: [
|
||||
makePerson('p1', 'Anna', {
|
||||
birthDate: '1901-03-14',
|
||||
birthDatePrecision: 'DAY',
|
||||
deathDate: '1944-11-02',
|
||||
deathDatePrecision: 'DAY'
|
||||
})
|
||||
]
|
||||
})
|
||||
}
|
||||
});
|
||||
|
||||
await expect.element(page.getByText(/14\. März 1901/)).toBeVisible();
|
||||
});
|
||||
|
||||
it('falls back to a default position when clientRect returns null', async () => {
|
||||
render(MentionDropdown, {
|
||||
props: {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { untrack } from 'svelte';
|
||||
import MentionDropdown from './MentionDropdown.svelte';
|
||||
import type { components } from '$lib/generated/api';
|
||||
|
||||
type Person = components['schemas']['PersonSummaryDTO'];
|
||||
type Person = components['schemas']['Person'];
|
||||
type DropdownState = {
|
||||
items: Person[];
|
||||
command: (item: Person) => void;
|
||||
|
||||
@@ -12,9 +12,7 @@ import MentionDropdown from './MentionDropdown.svelte';
|
||||
import { createMentionNodeView } from './mentionNodeView';
|
||||
import { MAX_QUERY_LENGTH, SEARCH_DEBOUNCE_MS, SEARCH_RESULT_LIMIT } from './mentionConstants';
|
||||
|
||||
// PersonSummaryDTO, not Person: /api/persons list items are the summary projection.
|
||||
// Typing them as the full entity hid a runtime bug (missing date fields, #812).
|
||||
type Person = components['schemas']['PersonSummaryDTO'];
|
||||
type Person = components['schemas']['Person'];
|
||||
|
||||
type Props = {
|
||||
value: string;
|
||||
@@ -218,15 +216,14 @@ const controller = createMentionController();
|
||||
// reflected data-person-id or the search input).
|
||||
function commitRelink(pos: number): CommitFn {
|
||||
return (item: Person) => {
|
||||
if (!editor || !item.id) return;
|
||||
const personId = item.id;
|
||||
if (!editor) return;
|
||||
editor
|
||||
.chain()
|
||||
.focus()
|
||||
.command(({ tr, state }) => {
|
||||
const node = state.doc.nodeAt(pos);
|
||||
if (!node || node.type.name !== 'mention') return false;
|
||||
tr.setNodeMarkup(pos, undefined, { ...node.attrs, personId });
|
||||
tr.setNodeMarkup(pos, undefined, { ...node.attrs, personId: item.id });
|
||||
return true;
|
||||
})
|
||||
.run();
|
||||
@@ -367,10 +364,8 @@ onMount(() => {
|
||||
render() {
|
||||
const buildFreshCommit = (loose: LooseRenderProps): CommitFn => {
|
||||
const clippedQuery = loose.query.slice(0, MAX_QUERY_LENGTH);
|
||||
return (item: Person) => {
|
||||
if (!item.id) return;
|
||||
return (item: Person) =>
|
||||
loose.command({ personId: item.id, displayName: clippedQuery });
|
||||
};
|
||||
};
|
||||
return {
|
||||
onStart(renderProps) {
|
||||
|
||||
@@ -16,7 +16,7 @@ import { m } from '$lib/paraglide/messages.js';
|
||||
// module so the test cannot drift from production. Sara on PR #629 round 3.
|
||||
import { SEARCH_DEBOUNCE_MS } from './mentionConstants';
|
||||
|
||||
type Person = components['schemas']['PersonSummaryDTO'];
|
||||
type Person = components['schemas']['Person'];
|
||||
type PersonMention = components['schemas']['PersonMention'];
|
||||
|
||||
/**
|
||||
@@ -35,10 +35,8 @@ const AUGUSTE: Person = {
|
||||
personType: 'PERSON',
|
||||
familyMember: false,
|
||||
provisional: false,
|
||||
birthDate: '1882-01-01',
|
||||
birthDatePrecision: 'YEAR',
|
||||
deathDate: '1944-01-01',
|
||||
deathDatePrecision: 'YEAR'
|
||||
birthYear: 1882,
|
||||
deathYear: 1944
|
||||
};
|
||||
|
||||
const ANNA: Person = {
|
||||
@@ -49,9 +47,7 @@ const ANNA: Person = {
|
||||
personType: 'PERSON',
|
||||
familyMember: false,
|
||||
provisional: false,
|
||||
birthDate: '1860-01-01',
|
||||
birthDatePrecision: 'YEAR',
|
||||
deathDatePrecision: 'UNKNOWN'
|
||||
birthYear: 1860
|
||||
};
|
||||
|
||||
function mockFetchWithPersons(persons: Person[] = [AUGUSTE, ANNA]) {
|
||||
|
||||
@@ -8,8 +8,6 @@ export type ErrorCode =
|
||||
| 'PERSON_NOT_FOUND'
|
||||
| 'ALIAS_NOT_FOUND'
|
||||
| 'INVALID_PERSON_TYPE'
|
||||
| 'BIRTH_AFTER_DEATH'
|
||||
| 'INVALID_DATE_PRECISION'
|
||||
| 'INVALID_DATE_RANGE'
|
||||
| 'DOCUMENT_NOT_FOUND'
|
||||
| 'DOCUMENT_NO_FILE'
|
||||
@@ -98,10 +96,6 @@ export function getErrorMessage(code: ErrorCode | string | undefined): string {
|
||||
return m.error_alias_not_found();
|
||||
case 'INVALID_PERSON_TYPE':
|
||||
return m.error_invalid_person_type();
|
||||
case 'BIRTH_AFTER_DEATH':
|
||||
return m.error_birth_after_death();
|
||||
case 'INVALID_DATE_PRECISION':
|
||||
return m.error_invalid_date_precision();
|
||||
case 'INVALID_DATE_RANGE':
|
||||
return m.error_invalid_date_range();
|
||||
case 'DOCUMENT_NOT_FOUND':
|
||||
|
||||
@@ -11,11 +11,6 @@ interface Props {
|
||||
placeholder?: string;
|
||||
class?: string;
|
||||
onchange?: () => void;
|
||||
ariaLabel?: string;
|
||||
ariaDescribedby?: string;
|
||||
// Escape hatch for callers that need the raw element, e.g. to set a custom
|
||||
// validity and block native form submission while the date is partial.
|
||||
inputEl?: HTMLInputElement;
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -25,10 +20,7 @@ let {
|
||||
id,
|
||||
placeholder,
|
||||
class: className = '',
|
||||
onchange,
|
||||
ariaLabel,
|
||||
ariaDescribedby,
|
||||
inputEl = $bindable()
|
||||
onchange
|
||||
}: Props = $props();
|
||||
|
||||
let display = $state(isoToGerman(value ?? ''));
|
||||
@@ -84,13 +76,10 @@ function handleInput(e: Event) {
|
||||
</script>
|
||||
|
||||
<input
|
||||
bind:this={inputEl}
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
maxlength="10"
|
||||
id={id}
|
||||
aria-label={ariaLabel}
|
||||
aria-describedby={ariaDescribedby}
|
||||
value={display}
|
||||
placeholder={placeholder ?? m.form_placeholder_date()}
|
||||
oninput={handleInput}
|
||||
|
||||
37
frontend/src/lib/shared/server/settled.test.ts
Normal file
37
frontend/src/lib/shared/server/settled.test.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { settled } from './settled';
|
||||
|
||||
describe('settled', () => {
|
||||
it('returns the data for a fulfilled ok response', () => {
|
||||
const res: PromiseSettledResult<unknown> = {
|
||||
status: 'fulfilled',
|
||||
value: { response: { ok: true } as Response, data: [{ id: '1' }] }
|
||||
};
|
||||
expect(settled<{ id: string }[]>(res)).toEqual([{ id: '1' }]);
|
||||
});
|
||||
|
||||
it('returns null for a fulfilled non-ok response', () => {
|
||||
const res: PromiseSettledResult<unknown> = {
|
||||
status: 'fulfilled',
|
||||
value: { response: { ok: false, status: 403 } as Response, data: undefined }
|
||||
};
|
||||
expect(settled(res)).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for a rejected result', () => {
|
||||
const res: PromiseSettledResult<unknown> = {
|
||||
status: 'rejected',
|
||||
reason: new Error('network error')
|
||||
};
|
||||
expect(settled(res)).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for undefined input', () => {
|
||||
expect(settled(undefined)).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for a fulfilled null value (Promise.resolve(null) placeholder slot)', () => {
|
||||
const res: PromiseSettledResult<unknown> = { status: 'fulfilled', value: null };
|
||||
expect(settled(res)).toBeNull();
|
||||
});
|
||||
});
|
||||
5
frontend/src/lib/shared/server/settled.ts
Normal file
5
frontend/src/lib/shared/server/settled.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export function settled<T>(res: PromiseSettledResult<unknown> | undefined): T | null {
|
||||
if (res?.status !== 'fulfilled') return null;
|
||||
const v = res.value as { response: Response; data: unknown } | null;
|
||||
return v?.response?.ok ? ((v.data as T) ?? null) : null;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import { createApiClient } from '$lib/shared/api.server';
|
||||
import type { components } from '$lib/generated/api';
|
||||
import { settled } from '$lib/shared/server/settled';
|
||||
|
||||
type StatsDTO = components['schemas']['StatsDTO'];
|
||||
type TranscriptionQueueItemDTO = components['schemas']['TranscriptionQueueItemDTO'];
|
||||
@@ -14,12 +15,6 @@ type DocumentListItem = components['schemas']['DocumentListItem'];
|
||||
type GeschichteSummary = components['schemas']['GeschichteSummary'];
|
||||
type TagTreeNodeDTO = components['schemas']['TagTreeNodeDTO'];
|
||||
|
||||
function settled<T>(res: PromiseSettledResult<unknown> | undefined): T | null {
|
||||
if (res?.status !== 'fulfilled') return null;
|
||||
const v = res.value as { response: Response; data: unknown };
|
||||
return v.response.ok ? ((v.data as T) ?? null) : null;
|
||||
}
|
||||
|
||||
export async function load({ fetch, parent }) {
|
||||
const { canWrite, canAnnotate, canBlogWrite } = await parent();
|
||||
// READ_ALL without WRITE_ALL or ANNOTATE_ALL — see ADR-007.
|
||||
|
||||
@@ -288,8 +288,6 @@ describe('DocumentList – undated badge in person grouping', () => {
|
||||
lastName: 'Mustermann',
|
||||
displayName: 'Max Mustermann',
|
||||
personType: 'PERSON' as const,
|
||||
birthDatePrecision: 'UNKNOWN' as const,
|
||||
deathDatePrecision: 'UNKNOWN' as const,
|
||||
familyMember: false,
|
||||
provisional: false
|
||||
};
|
||||
@@ -298,8 +296,6 @@ describe('DocumentList – undated badge in person grouping', () => {
|
||||
lastName: 'Brandt',
|
||||
displayName: 'Felix Brandt',
|
||||
personType: 'PERSON' as const,
|
||||
birthDatePrecision: 'UNKNOWN' as const,
|
||||
deathDatePrecision: 'UNKNOWN' as const,
|
||||
familyMember: false,
|
||||
provisional: false
|
||||
};
|
||||
|
||||
@@ -1,20 +1,23 @@
|
||||
import { error } from '@sveltejs/kit';
|
||||
import { createApiClient, extractErrorCode } from '$lib/shared/api.server';
|
||||
import { getErrorMessage } from '$lib/shared/errors';
|
||||
import { settled } from '$lib/shared/server/settled';
|
||||
import type { components } from '$lib/generated/api';
|
||||
import type { PageServerLoad } from './$types';
|
||||
|
||||
type Person = components['schemas']['Person'];
|
||||
type GeschichteSummary = components['schemas']['GeschichteSummary'];
|
||||
|
||||
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export const load: PageServerLoad = async ({ url, fetch }) => {
|
||||
export const load: PageServerLoad = async ({ url, fetch, parent }) => {
|
||||
const { canBlogWrite } = await parent();
|
||||
const api = createApiClient(fetch);
|
||||
const personIds = url.searchParams.getAll('personId');
|
||||
const rawDocumentId = url.searchParams.get('documentId');
|
||||
const documentId = rawDocumentId && UUID_PATTERN.test(rawDocumentId) ? rawDocumentId : null;
|
||||
|
||||
const [listResult, docResult, ...personResults] = await Promise.all([
|
||||
const [listSettled, draftsSettled, docSettled, ...personResults] = await Promise.allSettled([
|
||||
api.GET('/api/geschichten', {
|
||||
params: {
|
||||
query: {
|
||||
@@ -24,20 +27,32 @@ export const load: PageServerLoad = async ({ url, fetch }) => {
|
||||
}
|
||||
}
|
||||
}),
|
||||
canBlogWrite
|
||||
? api.GET('/api/geschichten', { params: { query: { status: 'DRAFT' } } })
|
||||
: Promise.resolve(null),
|
||||
documentId
|
||||
? api.GET('/api/documents/{id}', { params: { path: { id: documentId } } })
|
||||
: Promise.resolve(null),
|
||||
...personIds.map((id) => api.GET('/api/persons/{id}', { params: { path: { id } } }))
|
||||
]);
|
||||
|
||||
if (!listResult.response.ok) {
|
||||
throw error(listResult.response.status, getErrorMessage(extractErrorCode(listResult.error)));
|
||||
const listResult = listSettled.status === 'fulfilled' ? listSettled.value : null;
|
||||
if (!listResult?.response.ok) {
|
||||
throw error(
|
||||
listResult?.response.status ?? 500,
|
||||
getErrorMessage(extractErrorCode(listResult?.error))
|
||||
);
|
||||
}
|
||||
|
||||
const personFilters = personResults
|
||||
.filter((r) => r && r.response.ok && r.data)
|
||||
.map((r) => r!.data!) as Person[];
|
||||
const drafts: GeschichteSummary[] = canBlogWrite
|
||||
? (settled<GeschichteSummary[]>(draftsSettled) ?? [])
|
||||
: [];
|
||||
|
||||
const personFilters = personResults
|
||||
.filter((r) => r.status === 'fulfilled' && r.value?.response.ok && r.value?.data)
|
||||
.map((r) => (r as PromiseFulfilledResult<{ response: Response; data: Person }>).value.data);
|
||||
|
||||
const docResult = docSettled.status === 'fulfilled' ? docSettled.value : null;
|
||||
let documentFilter: { id: string; title: string | null } | null = null;
|
||||
if (documentId) {
|
||||
if (docResult && docResult.response.ok && docResult.data) {
|
||||
@@ -53,6 +68,7 @@ export const load: PageServerLoad = async ({ url, fetch }) => {
|
||||
|
||||
return {
|
||||
geschichten: listResult.data ?? [],
|
||||
drafts,
|
||||
personFilters,
|
||||
documentFilter
|
||||
};
|
||||
|
||||
@@ -133,7 +133,32 @@ function removeDocument() {
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Rows -->
|
||||
<!-- Entwürfe section (blog writers only, unfiltered) -->
|
||||
{#if data.drafts.length > 0}
|
||||
<div class="border-b-2 border-line">
|
||||
<h2 class="px-3 pt-3 pb-1 font-sans text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.geschichten_drafts_heading()}
|
||||
<span class="ml-1 font-normal text-ink-3 normal-case"
|
||||
>{m.geschichten_drafts_unfiltered_caption()}</span
|
||||
>
|
||||
</h2>
|
||||
<ul>
|
||||
{#each data.drafts as g (g.id)}
|
||||
<li class="border-b border-line-2 last:border-b-0">
|
||||
<GeschichteListRow geschichte={g} />
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Published rows -->
|
||||
{#if data.drafts.length > 0}
|
||||
<!-- Heading only when the Entwürfe section is present, to keep the h2 outline balanced -->
|
||||
<h2 class="px-3 pt-3 pb-1 font-sans text-xs font-bold tracking-widest text-ink-3 uppercase">
|
||||
{m.geschichten_published_heading()}
|
||||
</h2>
|
||||
{/if}
|
||||
{#if data.geschichten.length === 0}
|
||||
<div class="px-4 py-12 text-center font-serif text-sm text-ink-3 italic">
|
||||
{emptyMessage}
|
||||
|
||||
@@ -24,11 +24,18 @@ function makeUrl(params: Record<string, string | string[]> = {}) {
|
||||
return url;
|
||||
}
|
||||
|
||||
function callLoad(url: URL) {
|
||||
function callLoad(url: URL, parentData: { canBlogWrite?: boolean } = {}) {
|
||||
return load({
|
||||
url,
|
||||
request: new Request('http://localhost/geschichten'),
|
||||
fetch: vi.fn() as unknown as typeof fetch
|
||||
fetch: vi.fn() as unknown as typeof fetch,
|
||||
parent: vi.fn().mockResolvedValue({
|
||||
canBlogWrite: false,
|
||||
canWrite: false,
|
||||
canAnnotate: false,
|
||||
user: null,
|
||||
...parentData
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
@@ -191,3 +198,60 @@ describe('geschichten page load — documentFilter title resolution', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── draft fetch ──────────────────────────────────────────────────────────────
|
||||
|
||||
describe('geschichten page load — draft fetch', () => {
|
||||
it('makes a second API call for DRAFT stories when canBlogWrite is true', async () => {
|
||||
const mockGet = mockApi();
|
||||
|
||||
await callLoad(makeUrl(), { canBlogWrite: true });
|
||||
|
||||
const draftCall = mockGet.mock.calls.find(
|
||||
([, opts]: [string, { params?: { query?: { status?: string } } }]) =>
|
||||
opts?.params?.query?.status === 'DRAFT'
|
||||
);
|
||||
expect(draftCall).toBeDefined();
|
||||
});
|
||||
|
||||
it('does NOT make a DRAFT API call when canBlogWrite is false', async () => {
|
||||
const mockGet = mockApi();
|
||||
|
||||
await callLoad(makeUrl(), { canBlogWrite: false });
|
||||
|
||||
const draftCall = mockGet.mock.calls.find(
|
||||
([, opts]: [string, { params?: { query?: { status?: string } } }]) =>
|
||||
opts?.params?.query?.status === 'DRAFT'
|
||||
);
|
||||
expect(draftCall).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns empty drafts array when the DRAFT fetch rejects', async () => {
|
||||
const mockGet = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ response: { ok: true, status: 200 }, data: [] })
|
||||
.mockRejectedValueOnce(new Error('network error'));
|
||||
vi.mocked(createApiClient).mockReturnValue({ GET: mockGet } as ReturnType<
|
||||
typeof createApiClient
|
||||
>);
|
||||
|
||||
const result = await callLoad(makeUrl(), { canBlogWrite: true });
|
||||
|
||||
expect(result.drafts).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns drafts in page data when canBlogWrite is true', async () => {
|
||||
const draft = { id: 'draft-1', title: 'My Draft', status: 'DRAFT' };
|
||||
const mockGet = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ response: { ok: true, status: 200 }, data: [] })
|
||||
.mockResolvedValueOnce({ response: { ok: true, status: 200 }, data: [draft] });
|
||||
vi.mocked(createApiClient).mockReturnValue({ GET: mockGet } as ReturnType<
|
||||
typeof createApiClient
|
||||
>);
|
||||
|
||||
const result = await callLoad(makeUrl(), { canBlogWrite: true });
|
||||
|
||||
expect(result.drafts).toEqual([draft]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -26,6 +26,7 @@ function person(id: string, displayName: string) {
|
||||
function makeData(overrides: Partial<PageData> = {}): PageData {
|
||||
return {
|
||||
geschichten: [],
|
||||
drafts: [],
|
||||
personFilters: [],
|
||||
documentFilter: null,
|
||||
canBlogWrite: false,
|
||||
@@ -349,3 +350,62 @@ describe('geschichten page — multi-person filter chips', () => {
|
||||
expect(addEl.className).toContain('h-11');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Entwürfe section ─────────────────────────────────────────────────────────
|
||||
|
||||
describe('geschichten page — Entwürfe section', () => {
|
||||
const draft = () =>
|
||||
({
|
||||
id: 'draft-1',
|
||||
title: 'Mein Entwurf',
|
||||
body: '<p>test</p>',
|
||||
type: 'STORY',
|
||||
status: 'DRAFT',
|
||||
author: { firstName: 'Max', lastName: 'Muster' },
|
||||
publishedAt: null
|
||||
}) as unknown as PageData['geschichten'][0];
|
||||
|
||||
it('Entwürfe section is hidden when drafts array is empty', async () => {
|
||||
render(Page, { data: makeData({ drafts: [] }) });
|
||||
const heading = Array.from(document.querySelectorAll('h2')).find(
|
||||
(h) => h.textContent?.includes('Entwürfe') || h.textContent?.includes('Drafts')
|
||||
);
|
||||
expect(heading).toBeUndefined();
|
||||
});
|
||||
|
||||
it('Entwürfe section is visible when drafts are present', async () => {
|
||||
render(Page, { data: makeData({ drafts: [draft()] as PageData['geschichten'] }) });
|
||||
const heading = Array.from(document.querySelectorAll('h2')).find(
|
||||
(h) => h.textContent?.includes('Entwürfe') || h.textContent?.includes('Drafts')
|
||||
);
|
||||
expect(heading).not.toBeUndefined();
|
||||
});
|
||||
|
||||
it('renders a row for each draft story', async () => {
|
||||
render(Page, { data: makeData({ drafts: [draft()] as PageData['geschichten'] }) });
|
||||
const link = document.querySelector('a[href="/geschichten/draft-1"]');
|
||||
expect(link).not.toBeNull();
|
||||
});
|
||||
|
||||
it('draft row shows the draft badge', async () => {
|
||||
render(Page, { data: makeData({ drafts: [draft()] as PageData['geschichten'] }) });
|
||||
const badge = document.querySelector('[data-testid="draft-badge"]');
|
||||
expect(badge).not.toBeNull();
|
||||
});
|
||||
|
||||
it('Veröffentlicht heading is present when the Entwürfe section is visible', async () => {
|
||||
render(Page, { data: makeData({ drafts: [draft()] as PageData['geschichten'] }) });
|
||||
const heading = Array.from(document.querySelectorAll('h2')).find(
|
||||
(h) => h.textContent?.includes('Veröffentlicht') || h.textContent?.includes('Published')
|
||||
);
|
||||
expect(heading).not.toBeUndefined();
|
||||
});
|
||||
|
||||
it('Veröffentlicht heading is absent when there are no drafts', async () => {
|
||||
render(Page, { data: makeData({ drafts: [] }) });
|
||||
const heading = Array.from(document.querySelectorAll('h2')).find(
|
||||
(h) => h.textContent?.includes('Veröffentlicht') || h.textContent?.includes('Published')
|
||||
);
|
||||
expect(heading).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
import { formatLifeDate } from '$lib/person/personLifeDates';
|
||||
import { formatLifeDateRange } from '$lib/person/personLifeDates';
|
||||
import PersonTypeBadge from '$lib/person/PersonTypeBadge.svelte';
|
||||
import type { DatePrecision } from '$lib/shared/utils/documentDate';
|
||||
|
||||
let {
|
||||
person,
|
||||
@@ -16,17 +15,12 @@ let {
|
||||
personType?: string | null;
|
||||
title?: string | null;
|
||||
alias?: string | null;
|
||||
birthDate?: string | null;
|
||||
birthDatePrecision?: DatePrecision | null;
|
||||
deathDate?: string | null;
|
||||
deathDatePrecision?: DatePrecision | null;
|
||||
birthYear?: number | null;
|
||||
deathYear?: number | null;
|
||||
notes?: string | null;
|
||||
};
|
||||
canWrite: boolean;
|
||||
} = $props();
|
||||
|
||||
const birthText = $derived(formatLifeDate(person.birthDate, person.birthDatePrecision));
|
||||
const deathText = $derived(formatLifeDate(person.deathDate, person.deathDatePrecision));
|
||||
</script>
|
||||
|
||||
<div class="overflow-hidden rounded-sm border border-line bg-surface shadow-sm">
|
||||
@@ -97,16 +91,10 @@ const deathText = $derived(formatLifeDate(person.deathDate, person.deathDatePrec
|
||||
<p class="mb-1 text-center font-sans text-sm text-ink-2 italic">„{person.alias}"</p>
|
||||
{/if}
|
||||
|
||||
<!-- Life dates — centered; glyphs aria-hidden so screen readers only hear the dates -->
|
||||
{#if birthText || deathText}
|
||||
<!-- Life dates — centered -->
|
||||
{#if person.birthYear || person.deathYear}
|
||||
<p class="mb-4 text-center font-sans text-sm text-ink-3">
|
||||
{#if birthText}
|
||||
<span aria-hidden="true">*</span> {birthText}
|
||||
{/if}
|
||||
{#if birthText && deathText}–{/if}
|
||||
{#if deathText}
|
||||
<span aria-hidden="true">†</span> {deathText}
|
||||
{/if}
|
||||
{formatLifeDateRange(person.birthYear, person.deathYear)}
|
||||
</p>
|
||||
{:else}
|
||||
<div class="mb-4"></div>
|
||||
|
||||
@@ -82,84 +82,15 @@ describe('PersonCard', () => {
|
||||
await expect.element(page.getByText(/Annerl/)).toBeVisible();
|
||||
});
|
||||
|
||||
it('renders DAY-precision life dates as full localized dates', async () => {
|
||||
it('renders the life-date range when birthYear or deathYear are present', async () => {
|
||||
render(PersonCard, {
|
||||
props: {
|
||||
person: {
|
||||
...basePerson,
|
||||
birthDate: '1901-03-14',
|
||||
birthDatePrecision: 'DAY' as const,
|
||||
deathDate: '1944-11-02',
|
||||
deathDatePrecision: 'DAY' as const
|
||||
},
|
||||
person: { ...basePerson, birthYear: 1899, deathYear: 1972 },
|
||||
canWrite: false
|
||||
}
|
||||
});
|
||||
|
||||
await expect.element(page.getByText(/14\. März 1901/)).toBeVisible();
|
||||
await expect.element(page.getByText(/2\. November 1944/)).toBeVisible();
|
||||
});
|
||||
|
||||
it('wraps the * and † glyphs in aria-hidden spans', async () => {
|
||||
const { container } = render(PersonCard, {
|
||||
props: {
|
||||
person: {
|
||||
...basePerson,
|
||||
birthDate: '1901-03-14',
|
||||
birthDatePrecision: 'DAY' as const,
|
||||
deathDate: '1944-11-02',
|
||||
deathDatePrecision: 'DAY' as const
|
||||
},
|
||||
canWrite: false
|
||||
}
|
||||
});
|
||||
|
||||
const hidden = [...container.querySelectorAll('span[aria-hidden="true"]')].map((el) =>
|
||||
el.textContent?.trim()
|
||||
);
|
||||
expect(hidden).toContain('*');
|
||||
expect(hidden).toContain('†');
|
||||
});
|
||||
|
||||
it('renders birth-only without dash or dagger', async () => {
|
||||
const { container } = render(PersonCard, {
|
||||
props: {
|
||||
person: {
|
||||
...basePerson,
|
||||
birthDate: '1901-03-14',
|
||||
birthDatePrecision: 'DAY' as const
|
||||
},
|
||||
canWrite: false
|
||||
}
|
||||
});
|
||||
|
||||
await expect.element(page.getByText(/14\. März 1901/)).toBeVisible();
|
||||
expect(container.textContent).not.toContain('–');
|
||||
expect(container.textContent).not.toContain('†');
|
||||
});
|
||||
|
||||
it('renders APPROX-precision legacy dates with the ca. prefix', async () => {
|
||||
render(PersonCard, {
|
||||
props: {
|
||||
person: {
|
||||
...basePerson,
|
||||
birthDate: '1882-01-01',
|
||||
birthDatePrecision: 'APPROX' as const
|
||||
},
|
||||
canWrite: false
|
||||
}
|
||||
});
|
||||
|
||||
await expect.element(page.getByText(/ca\. 1882/)).toBeVisible();
|
||||
});
|
||||
|
||||
it('renders no life-date line when both dates are missing', async () => {
|
||||
const { container } = render(PersonCard, {
|
||||
props: { person: basePerson, canWrite: false }
|
||||
});
|
||||
|
||||
expect(container.textContent).not.toContain('*');
|
||||
expect(container.textContent).not.toContain('†');
|
||||
await expect.element(page.getByText(/1899/)).toBeVisible();
|
||||
});
|
||||
|
||||
it('renders the notes section when notes are provided', async () => {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { error, fail, redirect } from '@sveltejs/kit';
|
||||
import { createApiClient, extractErrorCode } from '$lib/shared/api.server';
|
||||
import { getErrorMessage } from '$lib/shared/errors';
|
||||
import type { DatePrecision } from '$lib/shared/utils/documentDate';
|
||||
import {
|
||||
normalizePersonType,
|
||||
validatePersonFields,
|
||||
@@ -48,17 +47,10 @@ export const actions = {
|
||||
const lastName = formData.get('lastName')?.toString().trim();
|
||||
const alias = formData.get('alias')?.toString().trim() || undefined;
|
||||
const notes = formData.get('notes')?.toString().trim() || undefined;
|
||||
// Empty date input → omit date AND precision: the backend normalises the
|
||||
// absent pair to null/UNKNOWN, and a lone precision would fail the
|
||||
// coherence check (INVALID_DATE_PRECISION).
|
||||
const birthDate = formData.get('birthDate')?.toString().trim() || undefined;
|
||||
const birthDatePrecision = birthDate
|
||||
? (formData.get('birthDatePrecision')?.toString() as DatePrecision)
|
||||
: undefined;
|
||||
const deathDate = formData.get('deathDate')?.toString().trim() || undefined;
|
||||
const deathDatePrecision = deathDate
|
||||
? (formData.get('deathDatePrecision')?.toString() as DatePrecision)
|
||||
: undefined;
|
||||
const birthYearStr = formData.get('birthYear')?.toString().trim();
|
||||
const deathYearStr = formData.get('deathYear')?.toString().trim();
|
||||
const birthYear = birthYearStr ? parseInt(birthYearStr, 10) : undefined;
|
||||
const deathYear = deathYearStr ? parseInt(deathYearStr, 10) : undefined;
|
||||
// Must NOT use the conditional-spread idiom for generation: G 0 is a
|
||||
// valid family-tree-root value. The key always travels in the body so
|
||||
// an explicit clear (empty option) reaches the backend as null.
|
||||
@@ -81,8 +73,8 @@ export const actions = {
|
||||
lastName,
|
||||
...(alias ? { alias } : {}),
|
||||
...(notes ? { notes } : {}),
|
||||
...(birthDate ? { birthDate, birthDatePrecision } : {}),
|
||||
...(deathDate ? { deathDate, deathDatePrecision } : {}),
|
||||
...(birthYear ? { birthYear } : {}),
|
||||
...(deathYear ? { deathYear } : {}),
|
||||
generation
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { untrack } from 'svelte';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
import PersonLifeDateField from '$lib/person/PersonLifeDateField.svelte';
|
||||
import PersonTypeSelector from '$lib/person/PersonTypeSelector.svelte';
|
||||
import {
|
||||
PERSON_TYPES as TYPES,
|
||||
@@ -89,20 +88,32 @@ const inputCls =
|
||||
<label for="alias" class={labelCls}>{m.form_label_alias()}</label>
|
||||
<input id="alias" name="alias" type="text" value={person.alias ?? ''} class={inputCls} />
|
||||
</div>
|
||||
<PersonLifeDateField
|
||||
name="birthDate"
|
||||
legend={m.person_label_birth_date()}
|
||||
precisionLabel={m.person_label_birth_date_precision()}
|
||||
initialIso={person.birthDate ?? ''}
|
||||
initialPrecision={person.birthDatePrecision ?? null}
|
||||
/>
|
||||
<PersonLifeDateField
|
||||
name="deathDate"
|
||||
legend={m.person_label_death_date()}
|
||||
precisionLabel={m.person_label_death_date_precision()}
|
||||
initialIso={person.deathDate ?? ''}
|
||||
initialPrecision={person.deathDatePrecision ?? null}
|
||||
/>
|
||||
<div>
|
||||
<label for="birthYear" class={labelCls}>{m.person_label_birth_year()}</label>
|
||||
<input
|
||||
id="birthYear"
|
||||
name="birthYear"
|
||||
type="number"
|
||||
min="1"
|
||||
max="2100"
|
||||
placeholder={m.person_placeholder_year()}
|
||||
value={person.birthYear ?? ''}
|
||||
class={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label for="deathYear" class={labelCls}>{m.person_label_death_year()}</label>
|
||||
<input
|
||||
id="deathYear"
|
||||
name="deathYear"
|
||||
type="number"
|
||||
min="1"
|
||||
max="2100"
|
||||
placeholder={m.person_placeholder_year()}
|
||||
value={person.deathYear ?? ''}
|
||||
class={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div class="md:col-span-2">
|
||||
<label for="generation" class={labelCls}>{m.person_label_generation()}</label>
|
||||
<select
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest';
|
||||
import { cleanup, render } from 'vitest-browser-svelte';
|
||||
import { page, userEvent } from 'vitest/browser';
|
||||
import { page } from 'vitest/browser';
|
||||
import PersonEditForm from './PersonEditForm.svelte';
|
||||
|
||||
afterEach(cleanup);
|
||||
@@ -12,10 +12,8 @@ const personPersonal = {
|
||||
firstName: 'Anna',
|
||||
lastName: 'Schmidt',
|
||||
alias: 'Anni',
|
||||
birthDate: '1899-03-14' as string | null,
|
||||
birthDatePrecision: 'DAY' as string | null,
|
||||
deathDate: '1972-01-01' as string | null,
|
||||
deathDatePrecision: 'YEAR' as string | null,
|
||||
birthYear: 1899 as number | null,
|
||||
deathYear: 1972 as number | null,
|
||||
notes: 'Wohnte in Berlin.'
|
||||
};
|
||||
|
||||
@@ -26,10 +24,8 @@ const personInstitution = {
|
||||
firstName: null,
|
||||
lastName: 'Acme GmbH',
|
||||
alias: null,
|
||||
birthDate: null,
|
||||
birthDatePrecision: null,
|
||||
deathDate: null,
|
||||
deathDatePrecision: null,
|
||||
birthYear: null,
|
||||
deathYear: null,
|
||||
notes: null
|
||||
};
|
||||
|
||||
@@ -46,14 +42,14 @@ describe('PersonEditForm', () => {
|
||||
await expect.element(page.getByLabelText(/titel/i)).toBeVisible();
|
||||
});
|
||||
|
||||
it('hides the firstName / title / alias / life-date fields for INSTITUTION', async () => {
|
||||
it('hides the firstName / title / alias / year fields for INSTITUTION', async () => {
|
||||
render(PersonEditForm, { props: { person: personInstitution } });
|
||||
|
||||
await expect.element(page.getByLabelText(/vorname/i)).not.toBeInTheDocument();
|
||||
await expect.element(page.getByLabelText(/^titel$/i)).not.toBeInTheDocument();
|
||||
await expect.element(page.getByLabelText(/rufname/i)).not.toBeInTheDocument();
|
||||
await expect.element(page.getByLabelText(/^geburtsdatum$/i)).not.toBeInTheDocument();
|
||||
await expect.element(page.getByLabelText(/^sterbedatum$/i)).not.toBeInTheDocument();
|
||||
await expect.element(page.getByLabelText(/geburtsjahr/i)).not.toBeInTheDocument();
|
||||
await expect.element(page.getByLabelText(/todesjahr/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses the "Nachname" label for PERSON', async () => {
|
||||
@@ -81,63 +77,13 @@ describe('PersonEditForm', () => {
|
||||
expect(title.value).toBe('Frau Dr.');
|
||||
});
|
||||
|
||||
it('renders an existing DAY-precision birth date as dd.mm.yyyy in the date input', async () => {
|
||||
it('renders birthYear and deathYear inputs with prior values', async () => {
|
||||
render(PersonEditForm, { props: { person: personPersonal } });
|
||||
|
||||
const birthInput = (await page.getByLabelText(/^geburtsdatum$/i).element()) as HTMLInputElement;
|
||||
expect(birthInput.value).toBe('14.03.1899');
|
||||
});
|
||||
|
||||
it('submits the ISO date via the hidden birthDate input', async () => {
|
||||
const { container } = render(PersonEditForm, { props: { person: personPersonal } });
|
||||
|
||||
const hidden = container.querySelector('input[type="hidden"][name="birthDate"]');
|
||||
expect((hidden as HTMLInputElement).value).toBe('1899-03-14');
|
||||
});
|
||||
|
||||
it('offers only DAY / MONTH / YEAR precisions for life dates', async () => {
|
||||
const { container } = render(PersonEditForm, { props: { person: personPersonal } });
|
||||
|
||||
const select = container.querySelector(
|
||||
'select[name="birthDatePrecision"]'
|
||||
) as HTMLSelectElement;
|
||||
const values = Array.from(select.options).map((o) => o.value);
|
||||
expect(values).toEqual(['DAY', 'MONTH', 'YEAR']);
|
||||
});
|
||||
|
||||
it('hydrates the precision selects from the person prop', async () => {
|
||||
const { container } = render(PersonEditForm, { props: { person: personPersonal } });
|
||||
|
||||
const birth = container.querySelector('select[name="birthDatePrecision"]') as HTMLSelectElement;
|
||||
const death = container.querySelector('select[name="deathDatePrecision"]') as HTMLSelectElement;
|
||||
expect(birth.value).toBe('DAY');
|
||||
expect(death.value).toBe('YEAR');
|
||||
});
|
||||
|
||||
it('seeds a non-form precision (APPROX legacy import) as YEAR instead of DAY', async () => {
|
||||
const { container } = render(PersonEditForm, {
|
||||
props: {
|
||||
person: { ...personPersonal, birthDate: '1899-01-01', birthDatePrecision: 'APPROX' }
|
||||
}
|
||||
});
|
||||
|
||||
const birth = container.querySelector('select[name="birthDatePrecision"]') as HTMLSelectElement;
|
||||
expect(birth.value).toBe('YEAR');
|
||||
});
|
||||
|
||||
it('stacks the date input and precision select without overflow at 320px', async () => {
|
||||
await page.viewport(320, 640);
|
||||
const { container } = render(PersonEditForm, { props: { person: personPersonal } });
|
||||
|
||||
const input = container.querySelector('#birthDate') as HTMLElement;
|
||||
const select = container.querySelector('select[name="birthDatePrecision"]') as HTMLElement;
|
||||
expect(input.getBoundingClientRect().right).toBeLessThanOrEqual(320);
|
||||
expect(select.getBoundingClientRect().right).toBeLessThanOrEqual(320);
|
||||
// Stacked, not side by side: the select starts below the input.
|
||||
expect(select.getBoundingClientRect().top).toBeGreaterThanOrEqual(
|
||||
input.getBoundingClientRect().bottom
|
||||
);
|
||||
await page.viewport(1280, 720);
|
||||
const birthYear = (await page.getByLabelText(/geburtsjahr/i).element()) as HTMLInputElement;
|
||||
const deathYear = (await page.getByLabelText(/todesjahr/i).element()) as HTMLInputElement;
|
||||
expect(birthYear.value).toBe('1899');
|
||||
expect(deathYear.value).toBe('1972');
|
||||
});
|
||||
|
||||
it('renders the notes textarea pre-filled with prior content', async () => {
|
||||
@@ -157,23 +103,15 @@ describe('PersonEditForm', () => {
|
||||
|
||||
it('renders empty inputs when nullable fields are null', async () => {
|
||||
render(PersonEditForm, {
|
||||
props: {
|
||||
person: {
|
||||
...personPersonal,
|
||||
title: null,
|
||||
alias: null,
|
||||
birthDate: null,
|
||||
birthDatePrecision: null
|
||||
}
|
||||
}
|
||||
props: { person: { ...personPersonal, title: null, alias: null, birthYear: null } }
|
||||
});
|
||||
|
||||
const title = (await page.getByLabelText(/^titel/i).element()) as HTMLInputElement;
|
||||
const alias = (await page.getByLabelText(/rufname/i).element()) as HTMLInputElement;
|
||||
const birthInput = (await page.getByLabelText(/^geburtsdatum$/i).element()) as HTMLInputElement;
|
||||
const birthYear = (await page.getByLabelText(/geburtsjahr/i).element()) as HTMLInputElement;
|
||||
expect(title.value).toBe('');
|
||||
expect(alias.value).toBe('');
|
||||
expect(birthInput.value).toBe('');
|
||||
expect(birthYear.value).toBe('');
|
||||
});
|
||||
|
||||
// ─── generation dropdown (#689) ─────────────────────────────────────────────
|
||||
@@ -219,16 +157,4 @@ describe('PersonEditForm', () => {
|
||||
const select = (await page.getByLabelText(/^generation$/i).element()) as HTMLSelectElement;
|
||||
expect(select.value).toBe('');
|
||||
});
|
||||
|
||||
// ─── partial-date guard (#812 review) ────────────────────────────────────────
|
||||
|
||||
it('blocks submission while a stored birth date is partially edited (no silent clear)', async () => {
|
||||
render(PersonEditForm, { props: { person: personPersonal } });
|
||||
|
||||
await userEvent.fill(page.getByLabelText(/^geburtsdatum$/i), '14.03.');
|
||||
|
||||
const birthInput = (await page.getByLabelText(/^geburtsdatum$/i).element()) as HTMLInputElement;
|
||||
expect(birthInput.checkValidity()).toBe(false);
|
||||
await expect.element(page.getByText(/Bitte im Format TT\.MM\.JJJJ/)).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { error, fail, redirect } from '@sveltejs/kit';
|
||||
import { createApiClient, extractErrorCode } from '$lib/shared/api.server';
|
||||
import { getErrorMessage } from '$lib/shared/errors';
|
||||
import type { DatePrecision } from '$lib/shared/utils/documentDate';
|
||||
import {
|
||||
normalizePersonType,
|
||||
validatePersonFields,
|
||||
@@ -24,17 +23,8 @@ export const actions = {
|
||||
const firstName = formData.get('firstName')?.toString().trim();
|
||||
const lastName = formData.get('lastName')?.toString().trim();
|
||||
const alias = formData.get('alias')?.toString().trim() || undefined;
|
||||
// Empty date input → omit date AND precision: the backend normalises the
|
||||
// absent pair to null/UNKNOWN, and a lone precision would fail the
|
||||
// coherence check (INVALID_DATE_PRECISION).
|
||||
const birthDate = formData.get('birthDate')?.toString().trim() || undefined;
|
||||
const birthDatePrecision = birthDate
|
||||
? (formData.get('birthDatePrecision')?.toString() as DatePrecision)
|
||||
: undefined;
|
||||
const deathDate = formData.get('deathDate')?.toString().trim() || undefined;
|
||||
const deathDatePrecision = deathDate
|
||||
? (formData.get('deathDatePrecision')?.toString() as DatePrecision)
|
||||
: undefined;
|
||||
const birthYearStr = formData.get('birthYear')?.toString().trim();
|
||||
const deathYearStr = formData.get('deathYear')?.toString().trim();
|
||||
const notes = formData.get('notes')?.toString().trim() || undefined;
|
||||
// Must NOT use the conditional-spread idiom for generation: G 0 is a
|
||||
// valid family-tree-root value. Always travels in the body so an
|
||||
@@ -55,6 +45,9 @@ export const actions = {
|
||||
});
|
||||
}
|
||||
|
||||
const birthYear = birthYearStr ? parseInt(birthYearStr, 10) : undefined;
|
||||
const deathYear = deathYearStr ? parseInt(deathYearStr, 10) : undefined;
|
||||
|
||||
const api = createApiClient(fetch);
|
||||
const result = await api.POST('/api/persons', {
|
||||
body: {
|
||||
@@ -63,8 +56,8 @@ export const actions = {
|
||||
...(firstName ? { firstName } : {}),
|
||||
lastName: lastName!,
|
||||
...(alias ? { alias } : {}),
|
||||
...(birthDate ? { birthDate, birthDatePrecision } : {}),
|
||||
...(deathDate ? { deathDate, deathDatePrecision } : {}),
|
||||
...(birthYear ? { birthYear } : {}),
|
||||
...(deathYear ? { deathYear } : {}),
|
||||
...(notes ? { notes } : {}),
|
||||
generation
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
import { untrack } from 'svelte';
|
||||
import { m } from '$lib/paraglide/messages.js';
|
||||
import BackButton from '$lib/shared/primitives/BackButton.svelte';
|
||||
import PersonLifeDateField from '$lib/person/PersonLifeDateField.svelte';
|
||||
import PersonTypeSelector from '$lib/person/PersonTypeSelector.svelte';
|
||||
import { PERSON_TYPES as TYPES, type PersonType } from '$lib/person/person-validation';
|
||||
|
||||
@@ -103,16 +102,30 @@ const labelCls = 'mb-1 block text-sm font-medium text-ink-2';
|
||||
class={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<PersonLifeDateField
|
||||
name="birthDate"
|
||||
legend={m.person_label_birth_date()}
|
||||
precisionLabel={m.person_label_birth_date_precision()}
|
||||
/>
|
||||
<PersonLifeDateField
|
||||
name="deathDate"
|
||||
legend={m.person_label_death_date()}
|
||||
precisionLabel={m.person_label_death_date_precision()}
|
||||
/>
|
||||
<div>
|
||||
<label for="birthYear" class={labelCls}>{m.person_label_birth_year()}</label>
|
||||
<input
|
||||
id="birthYear"
|
||||
name="birthYear"
|
||||
type="number"
|
||||
min="1"
|
||||
max="2100"
|
||||
placeholder={m.person_placeholder_year()}
|
||||
class={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label for="deathYear" class={labelCls}>{m.person_label_death_year()}</label>
|
||||
<input
|
||||
id="deathYear"
|
||||
name="deathYear"
|
||||
type="number"
|
||||
min="1"
|
||||
max="2100"
|
||||
placeholder={m.person_placeholder_year()}
|
||||
class={inputCls}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="md:col-span-2">
|
||||
|
||||
Reference in New Issue
Block a user