feat(person): migrate birth/death year to LocalDate + DatePrecision (#773) #812

Merged
marcel merged 16 commits from feat/issue-773-person-birth-death-localdate into main 2026-06-12 21:49:17 +02:00
49 changed files with 1869 additions and 280 deletions

View File

@@ -15,6 +15,10 @@ public enum ErrorCode {
ALIAS_NOT_FOUND, ALIAS_NOT_FOUND,
/** The submitted personType value is not allowed (e.g. SKIP is import-only). 400 */ /** The submitted personType value is not allowed (e.g. SKIP is import-only). 400 */
INVALID_PERSON_TYPE, 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 --- // --- Documents ---
/** A document with the given ID does not exist. 404 */ /** A document with the given ID does not exist. 404 */
DOCUMENT_NOT_FOUND, DOCUMENT_NOT_FOUND,

View File

@@ -6,7 +6,9 @@ import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.*; import lombok.*;
import org.raddatz.familienarchiv.document.DatePrecision;
import org.raddatz.familienarchiv.user.DisplayNameFormatter; import org.raddatz.familienarchiv.user.DisplayNameFormatter;
import java.time.LocalDate;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@@ -49,8 +51,25 @@ public class Person {
@Column(columnDefinition = "TEXT") @Column(columnDefinition = "TEXT")
private String notes; private String notes;
private Integer birthYear; // Most precise birth/death date known. Precision mirrors Document.metaDatePrecision:
private Integer deathYear; // 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;
// Hand-curated generation index from canonical-persons.xlsx (G 0 = oldest). // Hand-curated generation index from canonical-persons.xlsx (G 0 = oldest).
// Nullable for persons outside the curated family graph. Drives the // Nullable for persons outside the curated family graph. Drives the

View File

@@ -66,7 +66,10 @@ public interface PersonRepository extends JpaRepository<Person, UUID> {
@Query(value = """ @Query(value = """
SELECT p.id, p.title, p.first_name AS firstName, p.last_name AS lastName, SELECT p.id, p.title, p.first_name AS firstName, p.last_name AS lastName,
p.person_type AS personType, p.person_type AS personType,
p.alias, p.birth_year AS birthYear, p.death_year AS deathYear, p.notes, 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.family_member AS familyMember, p.provisional AS provisional, p.family_member AS familyMember, p.provisional AS provisional,
(SELECT COUNT(*) FROM documents d WHERE d.sender_id = p.id) (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 + (SELECT COUNT(*) FROM document_receivers dr WHERE dr.person_id = p.id) AS documentCount
@@ -79,7 +82,10 @@ public interface PersonRepository extends JpaRepository<Person, UUID> {
@Query(value = """ @Query(value = """
SELECT p.id, p.title, p.first_name AS firstName, p.last_name AS lastName, SELECT p.id, p.title, p.first_name AS firstName, p.last_name AS lastName,
p.person_type AS personType, p.person_type AS personType,
p.alias, p.birth_year AS birthYear, p.death_year AS deathYear, p.notes, 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.family_member AS familyMember, p.provisional AS provisional, p.family_member AS familyMember, p.provisional AS provisional,
(SELECT COUNT(*) FROM documents d WHERE d.sender_id = p.id) (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 + (SELECT COUNT(*) FROM document_receivers dr WHERE dr.person_id = p.id) AS documentCount
@@ -89,7 +95,7 @@ public interface PersonRepository extends JpaRepository<Person, UUID> {
OR LOWER(CONCAT(p.last_name,' ',COALESCE(p.first_name,''))) LIKE LOWER(CONCAT('%',:query,'%')) OR LOWER(CONCAT(p.last_name,' ',COALESCE(p.first_name,''))) LIKE LOWER(CONCAT('%',:query,'%'))
OR LOWER(p.alias) LIKE LOWER(CONCAT('%',:query,'%')) OR LOWER(p.alias) LIKE LOWER(CONCAT('%',:query,'%'))
OR LOWER(a.last_name) 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_year, p.death_year, 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_date, p.birth_date_precision, p.death_date, p.death_date_precision, p.notes, p.family_member, p.provisional
ORDER BY p.last_name ASC, p.first_name ASC ORDER BY p.last_name ASC, p.first_name ASC
""", """,
nativeQuery = true) nativeQuery = true)
@@ -100,7 +106,10 @@ public interface PersonRepository extends JpaRepository<Person, UUID> {
@Query(value = """ @Query(value = """
SELECT p.id, p.title, p.first_name AS firstName, p.last_name AS lastName, SELECT p.id, p.title, p.first_name AS firstName, p.last_name AS lastName,
p.person_type AS personType, p.person_type AS personType,
p.alias, p.birth_year AS birthYear, p.death_year AS deathYear, p.notes, 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.family_member AS familyMember, p.provisional AS provisional, p.family_member AS familyMember, p.provisional AS provisional,
(SELECT COUNT(*) FROM documents d WHERE d.sender_id = p.id) (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 + (SELECT COUNT(*) FROM document_receivers dr WHERE dr.person_id = p.id) AS documentCount
@@ -139,7 +148,10 @@ public interface PersonRepository extends JpaRepository<Person, UUID> {
@Query(value = """ @Query(value = """
SELECT p.id, p.title, p.first_name AS firstName, p.last_name AS lastName, SELECT p.id, p.title, p.first_name AS firstName, p.last_name AS lastName,
p.person_type AS personType, p.person_type AS personType,
p.alias, p.birth_year AS birthYear, p.death_year AS deathYear, p.notes, 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.family_member AS familyMember, p.provisional AS provisional, p.family_member AS familyMember, p.provisional AS provisional,
(SELECT COUNT(*) FROM documents d WHERE d.sender_id = p.id) (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 + (SELECT COUNT(*) FROM document_receivers dr WHERE dr.person_id = p.id) AS documentCount

View File

@@ -1,5 +1,6 @@
package org.raddatz.familienarchiv.person; package org.raddatz.familienarchiv.person;
import java.time.LocalDate;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@@ -16,6 +17,7 @@ import org.springframework.lang.Nullable;
import org.raddatz.familienarchiv.person.PersonNameAliasDTO; import org.raddatz.familienarchiv.person.PersonNameAliasDTO;
import org.raddatz.familienarchiv.person.PersonSummaryDTO; import org.raddatz.familienarchiv.person.PersonSummaryDTO;
import org.raddatz.familienarchiv.person.PersonUpdateDTO; import org.raddatz.familienarchiv.person.PersonUpdateDTO;
import org.raddatz.familienarchiv.document.DatePrecision;
import org.raddatz.familienarchiv.exception.DomainException; import org.raddatz.familienarchiv.exception.DomainException;
import org.raddatz.familienarchiv.exception.ErrorCode; import org.raddatz.familienarchiv.exception.ErrorCode;
import org.raddatz.familienarchiv.person.Person; import org.raddatz.familienarchiv.person.Person;
@@ -299,13 +301,20 @@ public class PersonService {
} }
private Person fromCanonical(PersonUpsertCommand cmd) { 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() Person person = personRepository.save(Person.builder()
.sourceRef(cmd.sourceRef()) .sourceRef(cmd.sourceRef())
.firstName(blankToNull(cmd.firstName())) .firstName(blankToNull(cmd.firstName()))
.lastName(cmd.lastName()) .lastName(cmd.lastName())
.notes(blankToNull(cmd.notes())) .notes(blankToNull(cmd.notes()))
.birthYear(cmd.birthYear()) .birthDate(birth.date())
.deathYear(cmd.deathYear()) .birthDatePrecision(birth.precision())
.deathDate(death.date())
.deathDatePrecision(death.precision())
.generation(cmd.generation()) .generation(cmd.generation())
.familyMember(cmd.familyMember()) .familyMember(cmd.familyMember())
.personType(cmd.personType() == null ? PersonType.PERSON : cmd.personType()) .personType(cmd.personType() == null ? PersonType.PERSON : cmd.personType())
@@ -328,8 +337,16 @@ public class PersonService {
existing.setFirstName(preferHuman(existing.getFirstName(), cmd.firstName())); existing.setFirstName(preferHuman(existing.getFirstName(), cmd.firstName()));
existing.setLastName(preferHuman(existing.getLastName(), cmd.lastName())); existing.setLastName(preferHuman(existing.getLastName(), cmd.lastName()));
existing.setNotes(preferHuman(existing.getNotes(), cmd.notes())); existing.setNotes(preferHuman(existing.getNotes(), cmd.notes()));
existing.setBirthYear(preferHuman(existing.getBirthYear(), cmd.birthYear())); LifeDates dates = degradeIfConflicting(
existing.setDeathYear(preferHuman(existing.getDeathYear(), cmd.deathYear())); 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.setGeneration(preferHuman(existing.getGeneration(), cmd.generation())); existing.setGeneration(preferHuman(existing.getGeneration(), cmd.generation()));
if (cmd.personType() != null && existing.getPersonType() == PersonType.PERSON) { if (cmd.personType() != null && existing.getPersonType() == PersonType.PERSON) {
existing.setPersonType(cmd.personType()); existing.setPersonType(cmd.personType());
@@ -356,6 +373,48 @@ public class PersonService {
return existing != null ? existing : canonical; 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) { private static String blankToNull(String s) {
return (s == null || s.isBlank()) ? null : s.trim(); return (s == null || s.isBlank()) ? null : s.trim();
} }
@@ -375,7 +434,8 @@ public class PersonService {
if (dto.getPersonType() == PersonType.SKIP) { if (dto.getPersonType() == PersonType.SKIP) {
throw DomainException.badRequest(ErrorCode.INVALID_PERSON_TYPE, "SKIP is not a valid person type for manual creation"); throw DomainException.badRequest(ErrorCode.INVALID_PERSON_TYPE, "SKIP is not a valid person type for manual creation");
} }
validateYears(dto.getBirthYear(), dto.getDeathYear()); validateLifeDates(dto.getBirthDate(), dto.getBirthDatePrecision(),
dto.getDeathDate(), dto.getDeathDatePrecision());
Person person = Person.builder() Person person = Person.builder()
.personType(dto.getPersonType()) .personType(dto.getPersonType())
.title(dto.getTitle() == null || dto.getTitle().isBlank() ? null : dto.getTitle().trim()) .title(dto.getTitle() == null || dto.getTitle().isBlank() ? null : dto.getTitle().trim())
@@ -383,23 +443,40 @@ public class PersonService {
.lastName(dto.getLastName()) .lastName(dto.getLastName())
.alias(dto.getAlias() == null || dto.getAlias().isBlank() ? null : dto.getAlias().trim()) .alias(dto.getAlias() == null || dto.getAlias().isBlank() ? null : dto.getAlias().trim())
.notes(dto.getNotes() == null || dto.getNotes().isBlank() ? null : dto.getNotes().trim()) .notes(dto.getNotes() == null || dto.getNotes().isBlank() ? null : dto.getNotes().trim())
.birthYear(dto.getBirthYear()) .birthDate(dto.getBirthDate())
.deathYear(dto.getDeathYear()) .birthDatePrecision(normalizePrecision(dto.getBirthDatePrecision()))
.deathDate(dto.getDeathDate())
.deathDatePrecision(normalizePrecision(dto.getDeathDatePrecision()))
.generation(dto.getGeneration()) .generation(dto.getGeneration())
.build(); .build();
return personRepository.save(person); return personRepository.save(person);
} }
private void validateYears(Integer birthYear, Integer deathYear) { // Cross-field invariants the V76 CHECK constraints also enforce — validated here so the
if (birthYear != null && birthYear <= 0) { // user gets a structured ErrorCode instead of a raw constraint-violation 500.
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Geburtsjahr muss eine positive Zahl sein"); 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);
} }
if (deathYear != null && deathYear <= 0) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Todesjahr muss eine positive Zahl sein");
} }
if (birthYear != null && deathYear != null && birthYear > deathYear) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Geburtsjahr darf nicht nach dem Todesjahr liegen"); 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 (date == null && precision != null && precision != DatePrecision.UNKNOWN) {
throw DomainException.badRequest(ErrorCode.INVALID_DATE_PRECISION,
side + " date precision " + precision + " is set without a date");
}
}
private static DatePrecision normalizePrecision(DatePrecision precision) {
return precision == null ? DatePrecision.UNKNOWN : precision;
} }
@Transactional @Transactional
@@ -407,7 +484,8 @@ public class PersonService {
if (dto.getPersonType() == PersonType.SKIP) { if (dto.getPersonType() == PersonType.SKIP) {
throw DomainException.badRequest(ErrorCode.INVALID_PERSON_TYPE, "SKIP is not a valid person type for manual editing"); throw DomainException.badRequest(ErrorCode.INVALID_PERSON_TYPE, "SKIP is not a valid person type for manual editing");
} }
validateYears(dto.getBirthYear(), dto.getDeathYear()); validateLifeDates(dto.getBirthDate(), dto.getBirthDatePrecision(),
dto.getDeathDate(), dto.getDeathDatePrecision());
Person person = personRepository.findById(id) Person person = personRepository.findById(id)
.orElseThrow(() -> DomainException.notFound(ErrorCode.PERSON_NOT_FOUND, "Person not found: " + id)); .orElseThrow(() -> DomainException.notFound(ErrorCode.PERSON_NOT_FOUND, "Person not found: " + id));
person.setPersonType(dto.getPersonType()); person.setPersonType(dto.getPersonType());
@@ -416,8 +494,10 @@ public class PersonService {
person.setLastName(dto.getLastName()); person.setLastName(dto.getLastName());
person.setAlias(dto.getAlias() == null || dto.getAlias().isBlank() ? null : dto.getAlias().trim()); 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.setNotes(dto.getNotes() == null || dto.getNotes().isBlank() ? null : dto.getNotes().trim());
person.setBirthYear(dto.getBirthYear()); person.setBirthDate(dto.getBirthDate());
person.setDeathYear(dto.getDeathYear()); person.setBirthDatePrecision(normalizePrecision(dto.getBirthDatePrecision()));
person.setDeathDate(dto.getDeathDate());
person.setDeathDatePrecision(normalizePrecision(dto.getDeathDatePrecision()));
// Form path: a human can clear generation back to null. Unlike the importer // Form path: a human can clear generation back to null. Unlike the importer
// which routes through preferHuman, we write the DTO value verbatim. // which routes through preferHuman, we write the DTO value verbatim.
person.setGeneration(dto.getGeneration()); person.setGeneration(dto.getGeneration());

View File

@@ -1,5 +1,8 @@
package org.raddatz.familienarchiv.person; package org.raddatz.familienarchiv.person;
import org.raddatz.familienarchiv.document.DatePrecision;
import java.time.LocalDate;
import java.util.UUID; import java.util.UUID;
/** /**
@@ -16,6 +19,13 @@ public interface PersonSummaryDTO {
String getAlias(); String getAlias();
Integer getBirthYear(); Integer getBirthYear();
Integer getDeathYear(); 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(); String getNotes();
boolean isFamilyMember(); boolean isFamilyMember();
boolean isProvisional(); boolean isProvisional();

View File

@@ -5,8 +5,11 @@ import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
import lombok.Data; import lombok.Data;
import org.raddatz.familienarchiv.document.DatePrecision;
import org.raddatz.familienarchiv.person.PersonType; import org.raddatz.familienarchiv.person.PersonType;
import java.time.LocalDate;
@Data @Data
public class PersonUpdateDTO { public class PersonUpdateDTO {
@NotNull @NotNull
@@ -21,8 +24,10 @@ public class PersonUpdateDTO {
private String alias; private String alias;
@Size(max = 5000) @Size(max = 5000)
private String notes; private String notes;
private Integer birthYear; private LocalDate birthDate;
private Integer deathYear; private DatePrecision birthDatePrecision;
private LocalDate deathDate;
private DatePrecision deathDatePrecision;
// Mirror of the persons.generation CHECK constraint (V70). Bounds live in // Mirror of the persons.generation CHECK constraint (V70). Bounds live in
// PersonGeneration so DB, DTO, and importer all read from one place. // PersonGeneration so DB, DTO, and importer all read from one place.
@Min(PersonGeneration.MIN_GENERATION) @Min(PersonGeneration.MIN_GENERATION)

View File

@@ -96,7 +96,9 @@ public class RelationshipInferenceService {
if (p == null) continue; if (p == null) continue;
List<RelationToken> path = shortestPaths.get(id); List<RelationToken> path = shortestPaths.get(id);
PersonNodeDTO node = new PersonNodeDTO( PersonNodeDTO node = new PersonNodeDTO(
p.getId(), p.getDisplayName(), p.getBirthYear(), p.getDeathYear(), p.getId(), p.getDisplayName(),
RelationshipService.yearOf(p.getBirthDate()),
RelationshipService.yearOf(p.getDeathDate()),
p.getGeneration(), p.isFamilyMember()); p.getGeneration(), p.isFamilyMember());
out.add(new InferredRelationshipWithPersonDTO(node, labelFor(path), path.size())); out.add(new InferredRelationshipWithPersonDTO(node, labelFor(path), path.size()));
} }

View File

@@ -15,6 +15,7 @@ import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
@@ -66,7 +67,8 @@ public class RelationshipService {
for (Person p : familyMembers) { for (Person p : familyMembers) {
familyIds.add(p.getId()); familyIds.add(p.getId());
nodes.add(new PersonNodeDTO( nodes.add(new PersonNodeDTO(
p.getId(), p.getDisplayName(), p.getBirthYear(), p.getDeathYear(), p.getId(), p.getDisplayName(),
yearOf(p.getBirthDate()), yearOf(p.getDeathDate()),
p.getGeneration(), true)); p.getGeneration(), true));
} }
@@ -155,6 +157,13 @@ public class RelationshipService {
return (s == null || s.isBlank()) ? null : s.trim(); 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) { private static void validateYears(Integer fromYear, Integer toYear) {
if (fromYear != null && toYear != null && toYear < fromYear) { if (fromYear != null && toYear != null && toYear < fromYear) {
throw DomainException.badRequest( throw DomainException.badRequest(
@@ -170,11 +179,11 @@ public class RelationshipService {
p.getId(), p.getId(),
rp.getId(), rp.getId(),
p.getDisplayName(), p.getDisplayName(),
p.getBirthYear(), yearOf(p.getBirthDate()),
p.getDeathYear(), yearOf(p.getDeathDate()),
rp.getDisplayName(), rp.getDisplayName(),
rp.getBirthYear(), yearOf(rp.getBirthDate()),
rp.getDeathYear(), yearOf(rp.getDeathDate()),
r.getRelationType(), r.getRelationType(),
r.getFromYear(), r.getFromYear(),
r.getToYear(), r.getToYear(),

View File

@@ -0,0 +1,42 @@
-- 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;

View File

@@ -0,0 +1,244 @@
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());
}
}

View File

@@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.raddatz.familienarchiv.exception.DomainException; import org.raddatz.familienarchiv.exception.DomainException;
import org.raddatz.familienarchiv.exception.ErrorCode; import org.raddatz.familienarchiv.exception.ErrorCode;
import org.raddatz.familienarchiv.document.DatePrecision;
import org.raddatz.familienarchiv.document.Document; import org.raddatz.familienarchiv.document.Document;
import org.raddatz.familienarchiv.person.Person; import org.raddatz.familienarchiv.person.Person;
import org.raddatz.familienarchiv.person.PersonNameAlias; import org.raddatz.familienarchiv.person.PersonNameAlias;
@@ -22,6 +23,7 @@ import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDate;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@@ -215,6 +217,14 @@ class PersonControllerTest {
public String getAlias() { return null; } public String getAlias() { return null; }
public Integer getBirthYear() { return null; } public Integer getBirthYear() { return null; }
public Integer getDeathYear() { 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 String getNotes() { return null; }
public boolean isFamilyMember() { return false; } public boolean isFamilyMember() { return false; }
public boolean isProvisional() { return false; } public boolean isProvisional() { return false; }
@@ -572,18 +582,53 @@ class PersonControllerTest {
void createPerson_returns200_withAllSixFields() throws Exception { void createPerson_returns200_withAllSixFields() throws Exception {
UUID id = UUID.randomUUID(); UUID id = UUID.randomUUID();
Person saved = Person.builder().id(id).firstName("Maria").lastName("Raddatz") Person saved = Person.builder().id(id).firstName("Maria").lastName("Raddatz")
.alias("Oma Maria").birthYear(1901).deathYear(1975).notes("Some notes").build(); .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();
when(personService.createPerson(any(org.raddatz.familienarchiv.person.PersonUpdateDTO.class))).thenReturn(saved); when(personService.createPerson(any(org.raddatz.familienarchiv.person.PersonUpdateDTO.class))).thenReturn(saved);
mockMvc.perform(post("/api/persons").with(csrf()) mockMvc.perform(post("/api/persons").with(csrf())
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.content("{\"firstName\":\"Maria\",\"lastName\":\"Raddatz\"," + .content("{\"firstName\":\"Maria\",\"lastName\":\"Raddatz\"," +
"\"alias\":\"Oma Maria\",\"birthYear\":1901,\"deathYear\":1975," + "\"alias\":\"Oma Maria\"," +
"\"birthDate\":\"1901-03-14\",\"birthDatePrecision\":\"DAY\"," +
"\"deathDate\":\"1975-01-01\",\"deathDatePrecision\":\"YEAR\"," +
"\"notes\":\"Some notes\",\"personType\":\"PERSON\"}")) "\"notes\":\"Some notes\",\"personType\":\"PERSON\"}"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.firstName").value("Maria")) .andExpect(jsonPath("$.firstName").value("Maria"))
.andExpect(jsonPath("$.alias").value("Oma Maria")) .andExpect(jsonPath("$.alias").value("Oma Maria"))
.andExpect(jsonPath("$.birthYear").value(1901)); .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"));
} }
// ─── Phase 1.2: @Size constraints ───────────────────────────────────────── // ─── Phase 1.2: @Size constraints ─────────────────────────────────────────

View File

@@ -5,7 +5,9 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import org.raddatz.familienarchiv.document.DatePrecision;
import java.time.LocalDate;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
@@ -97,24 +99,120 @@ class PersonImportUpsertTest {
assertThat(result.getNotes()).isEqualTo("Nichte von Herbert"); assertThat(result.getNotes()).isEqualTo("Nichte von Herbert");
} }
// ─── life dates (ADR-025 extension via preferHumanDate, #773) ─────────────
@Test @Test
void upsertBySourceRef_fillsBlankYears_butPreservesHumanEditedYears_onReimport() { void upsertBySourceRef_preservesDayPrecisionDate_onReimportWithDifferentYear() {
// Existing has a human-set birthYear and a blank deathYear. // A human entered the exact birthday in-app; the spreadsheet only knows a year.
Person existing = Person.builder() Person handDated = Person.builder()
.id(UUID.randomUUID()).sourceRef("clara-cram") .id(UUID.randomUUID()).sourceRef("clara-cram").lastName("Cram")
.lastName("Cram").birthYear(1890).deathYear(null).build(); .birthDate(LocalDate.of(1890, 3, 14)).birthDatePrecision(DatePrecision.DAY).build();
when(personRepository.findBySourceRef("clara-cram")).thenReturn(Optional.of(existing)); when(personRepository.findBySourceRef("clara-cram")).thenReturn(Optional.of(handDated));
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0)); when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
PersonUpsertCommand cmd = PersonUpsertCommand.builder() PersonUpsertCommand cmd = PersonUpsertCommand.builder()
.sourceRef("clara-cram").lastName("Cram") .sourceRef("clara-cram").lastName("Cram")
.birthYear(1888).deathYear(1965) .birthYear(1888)
.personType(PersonType.PERSON).provisional(false).build(); .personType(PersonType.PERSON).provisional(false).build();
Person result = personService.upsertBySourceRef(cmd); Person result = personService.upsertBySourceRef(cmd);
assertThat(result.getBirthYear()).isEqualTo(1890); // human value kept assertThat(result.getBirthDate()).isEqualTo(LocalDate.of(1890, 3, 14));
assertThat(result.getDeathYear()).isEqualTo(1965); // blank filled from canonical 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);
} }
@Test @Test
@@ -199,4 +297,70 @@ class PersonImportUpsertTest {
assertThat(result.getGeneration()).isEqualTo(3); 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);
}
} }

View File

@@ -18,6 +18,9 @@ import org.raddatz.familienarchiv.document.DocumentRepository;
import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext; import jakarta.persistence.PersistenceContext;
import org.raddatz.familienarchiv.document.DatePrecision;
import java.time.LocalDate;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
@@ -910,4 +913,146 @@ class PersonRepositoryTest {
.setParameter(1, blockId).getSingleResult(); .setParameter(1, blockId).getSingleResult();
assertThat(text).isEqualTo("Brief an @Auguste Raddatz und @Clara Cram"); 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);
}
} }

View File

@@ -8,7 +8,9 @@ import org.mockito.junit.jupiter.MockitoExtension;
import org.raddatz.familienarchiv.person.PersonNameAliasDTO; import org.raddatz.familienarchiv.person.PersonNameAliasDTO;
import org.raddatz.familienarchiv.person.PersonSummaryDTO; import org.raddatz.familienarchiv.person.PersonSummaryDTO;
import org.raddatz.familienarchiv.person.PersonUpdateDTO; import org.raddatz.familienarchiv.person.PersonUpdateDTO;
import org.raddatz.familienarchiv.document.DatePrecision;
import org.raddatz.familienarchiv.exception.DomainException; import org.raddatz.familienarchiv.exception.DomainException;
import org.raddatz.familienarchiv.exception.ErrorCode;
import org.raddatz.familienarchiv.person.Person; import org.raddatz.familienarchiv.person.Person;
import org.raddatz.familienarchiv.person.PersonNameAlias; import org.raddatz.familienarchiv.person.PersonNameAlias;
import org.raddatz.familienarchiv.person.PersonNameAliasType; import org.raddatz.familienarchiv.person.PersonNameAliasType;
@@ -17,6 +19,7 @@ import org.raddatz.familienarchiv.person.PersonNameAliasRepository;
import org.raddatz.familienarchiv.person.PersonRepository; import org.raddatz.familienarchiv.person.PersonRepository;
import org.springframework.web.server.ResponseStatusException; import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDate;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
@@ -241,27 +244,49 @@ class PersonServiceTest {
PersonUpdateDTO dto = new PersonUpdateDTO(); PersonUpdateDTO dto = new PersonUpdateDTO();
dto.setFirstName("Maria"); dto.setLastName("Raddatz"); dto.setAlias("Oma Maria"); dto.setFirstName("Maria"); dto.setLastName("Raddatz"); dto.setAlias("Oma Maria");
dto.setBirthYear(1901); dto.setDeathYear(1975); dto.setNotes("Some notes"); 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");
Person result = personService.createPerson(dto); Person result = personService.createPerson(dto);
assertThat(result.getFirstName()).isEqualTo("Maria"); assertThat(result.getFirstName()).isEqualTo("Maria");
assertThat(result.getLastName()).isEqualTo("Raddatz"); assertThat(result.getLastName()).isEqualTo("Raddatz");
assertThat(result.getAlias()).isEqualTo("Oma Maria"); assertThat(result.getAlias()).isEqualTo("Oma Maria");
assertThat(result.getBirthYear()).isEqualTo(1901); assertThat(result.getBirthDate()).isEqualTo(LocalDate.of(1901, 3, 14));
assertThat(result.getDeathYear()).isEqualTo(1975); assertThat(result.getBirthDatePrecision()).isEqualTo(DatePrecision.DAY);
assertThat(result.getDeathDate()).isEqualTo(LocalDate.of(1975, 11, 2));
assertThat(result.getDeathDatePrecision()).isEqualTo(DatePrecision.DAY);
assertThat(result.getNotes()).isEqualTo("Some notes"); assertThat(result.getNotes()).isEqualTo("Some notes");
} }
@Test @Test
void createPerson_dto_yearValidationFires_whenBirthYearNegative() { void createPerson_dto_rejectsDateWithUnknownPrecision() {
PersonUpdateDTO dto = new PersonUpdateDTO(); PersonUpdateDTO dto = new PersonUpdateDTO();
dto.setFirstName("Anna"); dto.setLastName("Test"); dto.setBirthYear(-1); dto.setFirstName("Anna"); dto.setLastName("Test");
dto.setBirthDate(LocalDate.of(1901, 3, 14)); dto.setBirthDatePrecision(DatePrecision.UNKNOWN);
assertThatThrownBy(() -> personService.createPerson(dto)) assertThatThrownBy(() -> personService.createPerson(dto))
.isInstanceOf(ResponseStatusException.class) .isInstanceOf(DomainException.class)
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value()) .satisfies(e -> {
.isEqualTo(400); 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);
} }
@Test @Test
@@ -600,114 +625,135 @@ class PersonServiceTest {
assertThat(result.getNotes()).isNull(); assertThat(result.getNotes()).isNull();
} }
// ─── updatePerson (birth/death years) ──────────────────────────────────── // ─── updatePerson (birth/death dates) ────────────────────────────────────
@Test @Test
void updatePerson_persistsBirthAndDeathYear() { void updatePerson_persistsBirthAndDeathDateWithPrecision() {
UUID id = UUID.randomUUID(); UUID id = UUID.randomUUID();
Person person = Person.builder().id(id).firstName("Anna").lastName("Alt").build(); Person person = Person.builder().id(id).firstName("Anna").lastName("Alt").build();
when(personRepository.findById(id)).thenReturn(Optional.of(person)); when(personRepository.findById(id)).thenReturn(Optional.of(person));
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0)); when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
PersonUpdateDTO dto = new PersonUpdateDTO(); PersonUpdateDTO dto = new PersonUpdateDTO();
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setBirthYear(1890); dto.setDeathYear(1965); 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);
Person result = personService.updatePerson(id, dto); Person result = personService.updatePerson(id, dto);
assertThat(result.getBirthYear()).isEqualTo(1890); assertThat(result.getBirthDate()).isEqualTo(LocalDate.of(1890, 1, 1));
assertThat(result.getDeathYear()).isEqualTo(1965); assertThat(result.getBirthDatePrecision()).isEqualTo(DatePrecision.YEAR);
assertThat(result.getDeathDate()).isEqualTo(LocalDate.of(1965, 6, 12));
assertThat(result.getDeathDatePrecision()).isEqualTo(DatePrecision.DAY);
} }
@Test @Test
void updatePerson_throwsBadRequest_whenBirthYearAfterDeathYear() { void updatePerson_throwsBirthAfterDeath_whenBirthDateAfterDeathDate() {
UUID id = UUID.randomUUID(); UUID id = UUID.randomUUID();
PersonUpdateDTO dto = new PersonUpdateDTO(); PersonUpdateDTO dto = new PersonUpdateDTO();
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setBirthYear(1970); dto.setDeathYear(1950); 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);
assertThatThrownBy(() -> personService.updatePerson(id, dto)) assertThatThrownBy(() -> personService.updatePerson(id, dto))
.isInstanceOf(ResponseStatusException.class) .isInstanceOf(DomainException.class)
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value()) .satisfies(e -> {
.isEqualTo(400); assertThat(((DomainException) e).getCode()).isEqualTo(ErrorCode.BIRTH_AFTER_DEATH);
assertThat(((DomainException) e).getStatus().value()).isEqualTo(400);
});
} }
@Test @Test
void updatePerson_doesNotThrow_whenBirthYearNonNullButDeathYearIsNull() { void updatePerson_throwsBirthAfterDeath_onMixedPrecisionLateBirthday() {
// Covers A && B short-circuit: birthYear != null (true) but deathYear == null (false) → no throw // 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() {
UUID id = UUID.randomUUID(); UUID id = UUID.randomUUID();
Person person = Person.builder().id(id).firstName("Anna").lastName("Alt").build(); Person person = Person.builder().id(id).firstName("Anna").lastName("Alt").build();
when(personRepository.findById(id)).thenReturn(Optional.of(person)); when(personRepository.findById(id)).thenReturn(Optional.of(person));
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0)); when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
PersonUpdateDTO dto = new PersonUpdateDTO(); PersonUpdateDTO dto = new PersonUpdateDTO();
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setBirthYear(1890); dto.setDeathYear(null); dto.setFirstName("Anna"); dto.setLastName("Alt");
dto.setBirthDate(LocalDate.of(1890, 1, 1)); dto.setBirthDatePrecision(DatePrecision.YEAR);
Person result = personService.updatePerson(id, dto); Person result = personService.updatePerson(id, dto);
assertThat(result.getBirthYear()).isEqualTo(1890); assertThat(result.getBirthDate()).isEqualTo(LocalDate.of(1890, 1, 1));
assertThat(result.getDeathYear()).isNull(); assertThat(result.getDeathDate()).isNull();
assertThat(result.getDeathDatePrecision()).isEqualTo(DatePrecision.UNKNOWN);
} }
@Test @Test
void updatePerson_allowsSameYear() { void updatePerson_allowsEqualBirthAndDeathDate() {
UUID id = UUID.randomUUID(); UUID id = UUID.randomUUID();
Person person = Person.builder().id(id).firstName("Anna").lastName("Alt").build(); Person person = Person.builder().id(id).firstName("Anna").lastName("Alt").build();
when(personRepository.findById(id)).thenReturn(Optional.of(person)); when(personRepository.findById(id)).thenReturn(Optional.of(person));
when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0)); when(personRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
PersonUpdateDTO dto = new PersonUpdateDTO(); PersonUpdateDTO dto = new PersonUpdateDTO();
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setBirthYear(1900); dto.setDeathYear(1900); 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);
Person result = personService.updatePerson(id, dto); Person result = personService.updatePerson(id, dto);
assertThat(result.getBirthYear()).isEqualTo(1900); assertThat(result.getBirthDate()).isEqualTo(LocalDate.of(1900, 1, 1));
assertThat(result.getDeathYear()).isEqualTo(1900); assertThat(result.getDeathDate()).isEqualTo(LocalDate.of(1900, 1, 1));
} }
// ─── Phase 1.3: Year range bounds (> 0) ────────────────────────────────── // ─── Date/precision coherence (V76 CHECK constraint mirror) ─────────────
@Test @Test
void updatePerson_throwsBadRequest_whenBirthYearIsZero() { void updatePerson_throwsInvalidDatePrecision_whenDatePresentButPrecisionUnknown() {
UUID id = UUID.randomUUID(); UUID id = UUID.randomUUID();
PersonUpdateDTO dto = new PersonUpdateDTO(); PersonUpdateDTO dto = new PersonUpdateDTO();
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setBirthYear(0); dto.setFirstName("Anna"); dto.setLastName("Alt");
dto.setDeathDate(LocalDate.of(1944, 11, 2)); dto.setDeathDatePrecision(DatePrecision.UNKNOWN);
assertThatThrownBy(() -> personService.updatePerson(id, dto)) assertThatThrownBy(() -> personService.updatePerson(id, dto))
.isInstanceOf(ResponseStatusException.class) .isInstanceOf(DomainException.class)
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value()) .satisfies(e -> {
.isEqualTo(400); assertThat(((DomainException) e).getCode()).isEqualTo(ErrorCode.INVALID_DATE_PRECISION);
assertThat(((DomainException) e).getStatus().value()).isEqualTo(400);
});
} }
@Test @Test
void updatePerson_throwsBadRequest_whenBirthYearIsNegative() { void updatePerson_throwsInvalidDatePrecision_whenDatePresentButPrecisionNull() {
UUID id = UUID.randomUUID(); UUID id = UUID.randomUUID();
PersonUpdateDTO dto = new PersonUpdateDTO(); PersonUpdateDTO dto = new PersonUpdateDTO();
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setBirthYear(-5); dto.setFirstName("Anna"); dto.setLastName("Alt");
dto.setBirthDate(LocalDate.of(1901, 3, 14));
assertThatThrownBy(() -> personService.updatePerson(id, dto)) assertThatThrownBy(() -> personService.updatePerson(id, dto))
.isInstanceOf(ResponseStatusException.class) .isInstanceOf(DomainException.class)
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value()) .extracting(e -> ((DomainException) e).getCode())
.isEqualTo(400); .isEqualTo(ErrorCode.INVALID_DATE_PRECISION);
} }
@Test @Test
void updatePerson_throwsBadRequest_whenDeathYearIsZero() { void updatePerson_throwsInvalidDatePrecision_whenPrecisionSetWithoutDate() {
UUID id = UUID.randomUUID(); UUID id = UUID.randomUUID();
PersonUpdateDTO dto = new PersonUpdateDTO(); PersonUpdateDTO dto = new PersonUpdateDTO();
dto.setFirstName("Anna"); dto.setLastName("Alt"); dto.setDeathYear(0); dto.setFirstName("Anna"); dto.setLastName("Alt");
dto.setBirthDatePrecision(DatePrecision.DAY);
assertThatThrownBy(() -> personService.updatePerson(id, dto)) assertThatThrownBy(() -> personService.updatePerson(id, dto))
.isInstanceOf(ResponseStatusException.class) .isInstanceOf(DomainException.class)
.extracting(e -> ((ResponseStatusException) e).getStatusCode().value()) .extracting(e -> ((DomainException) e).getCode())
.isEqualTo(400); .isEqualTo(ErrorCode.INVALID_DATE_PRECISION);
}
@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 ────────────────────────────────────────────────── // ─── findCorrespondents ──────────────────────────────────────────────────

View File

@@ -518,6 +518,26 @@ 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.** 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 ### 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: 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:

View File

@@ -0,0 +1,98 @@
# 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.

View File

@@ -1,6 +1,6 @@
@startuml db-orm @startuml db-orm
' Schema source: Flyway V1V72 (excl. V37, V43 — intentionally removed) ' Schema source: Flyway V1V76 (excl. V37, V43 — intentionally removed)
' Schema as of: V72 (2026-06-08) ' Schema as of: V76 (2026-06-12)
' ⚠ This is a versioned snapshot. Update when the schema changes significantly. ' ⚠ This is a versioned snapshot. Update when the schema changes significantly.
hide circle hide circle
@@ -184,8 +184,10 @@ package "Persons" {
title : VARCHAR(50) title : VARCHAR(50)
person_type : VARCHAR(20) NOT NULL person_type : VARCHAR(20) NOT NULL
notes : TEXT notes : TEXT
birth_year : INTEGER birth_date : DATE
death_year : INTEGER birth_date_precision : VARCHAR(16) NOT NULL
death_date : DATE
death_date_precision : VARCHAR(16) NOT NULL
generation : SMALLINT generation : SMALLINT
family_member : BOOLEAN NOT NULL family_member : BOOLEAN NOT NULL
source_ref : VARCHAR(255) UNIQUE source_ref : VARCHAR(255) UNIQUE

View File

@@ -4,6 +4,8 @@
' ⚠ This is a versioned snapshot. Update when the schema changes significantly. ' ⚠ This is a versioned snapshot. Update when the schema changes significantly.
' Note: V69 adds columns only (persons.source_ref, tag.source_ref, document ' Note: V69 adds columns only (persons.source_ref, tag.source_ref, document
' precision/attribution fields); no new FK relationships, so this diagram is unchanged. ' 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 hide circle
skinparam linetype ortho skinparam linetype ortho

View File

@@ -174,12 +174,18 @@
"person_merge_warning": "Achtung: Diese Aktion ist nicht rückgängig zu machen.", "person_merge_warning": "Achtung: Diese Aktion ist nicht rückgängig zu machen.",
"person_label_notes": "Notizen", "person_label_notes": "Notizen",
"person_placeholder_notes": "Biographische Hinweise, Besonderheiten…", "person_placeholder_notes": "Biographische Hinweise, Besonderheiten…",
"person_label_birth_year": "Geburtsjahr", "person_label_birth_date": "Geburtsdatum",
"person_label_death_year": "Todesjahr", "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_generation": "Generation", "person_label_generation": "Generation",
"person_option_generation_unset": "(keine)", "person_option_generation_unset": "(keine)",
"person_hint_generation": "Generation in der Familie (G 0 = älteste Generation)", "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_year_error": "Bitte eine vierstellige Jahreszahl eingeben",
"person_years_error_order": "Geburtsjahr muss vor dem Todesjahr liegen", "person_years_error_order": "Geburtsjahr muss vor dem Todesjahr liegen",
"person_docs_heading": "Gesendete Dokumente", "person_docs_heading": "Gesendete Dokumente",
@@ -643,6 +649,8 @@
"error_alias_not_found": "Der Namensalias wurde nicht gefunden.", "error_alias_not_found": "Der Namensalias wurde nicht gefunden.",
"error_invalid_person_type": "Der angegebene Personentyp ist ungültig.", "error_invalid_person_type": "Der angegebene Personentyp ist ungültig.",
"error_invalid_date_range": "Das Enddatum darf nicht vor dem Startdatum liegen.", "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_last_name_required": "Nachname ist Pflichtfeld.",
"validation_first_name_required": "Vorname ist Pflichtfeld.", "validation_first_name_required": "Vorname ist Pflichtfeld.",
"error_ocr_service_unavailable": "Der OCR-Dienst ist nicht verfügbar.", "error_ocr_service_unavailable": "Der OCR-Dienst ist nicht verfügbar.",

View File

@@ -174,12 +174,18 @@
"person_merge_warning": "Warning: This action cannot be undone.", "person_merge_warning": "Warning: This action cannot be undone.",
"person_label_notes": "Notes", "person_label_notes": "Notes",
"person_placeholder_notes": "Biographical notes, remarks…", "person_placeholder_notes": "Biographical notes, remarks…",
"person_label_birth_year": "Birth year", "person_label_birth_date": "Date of birth",
"person_label_death_year": "Death year", "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_generation": "Generation", "person_label_generation": "Generation",
"person_option_generation_unset": "(none)", "person_option_generation_unset": "(none)",
"person_hint_generation": "Generation within the family (G 0 = oldest generation)", "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_year_error": "Please enter a four-digit year",
"person_years_error_order": "Birth year must be before death year", "person_years_error_order": "Birth year must be before death year",
"person_docs_heading": "Sent documents", "person_docs_heading": "Sent documents",
@@ -643,6 +649,8 @@
"error_alias_not_found": "The name alias was not found.", "error_alias_not_found": "The name alias was not found.",
"error_invalid_person_type": "The specified person type is not valid.", "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_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_last_name_required": "Last name is required.",
"validation_first_name_required": "First name is required.", "validation_first_name_required": "First name is required.",
"error_ocr_service_unavailable": "The OCR service is not available.", "error_ocr_service_unavailable": "The OCR service is not available.",

View File

@@ -174,12 +174,18 @@
"person_merge_warning": "Atención: Esta acción no se puede deshacer.", "person_merge_warning": "Atención: Esta acción no se puede deshacer.",
"person_label_notes": "Notas", "person_label_notes": "Notas",
"person_placeholder_notes": "Notas biográficas, observaciones…", "person_placeholder_notes": "Notas biográficas, observaciones…",
"person_label_birth_year": "Año de nacimiento", "person_label_birth_date": "Fecha de nacimiento",
"person_label_death_year": "Año de fallecimiento", "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_generation": "Generación", "person_label_generation": "Generación",
"person_option_generation_unset": "(ninguna)", "person_option_generation_unset": "(ninguna)",
"person_hint_generation": "Generación dentro de la familia (G 0 = generación más antigua)", "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_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_years_error_order": "El año de nacimiento debe ser anterior al año de fallecimiento",
"person_docs_heading": "Documentos enviados", "person_docs_heading": "Documentos enviados",
@@ -643,6 +649,8 @@
"error_alias_not_found": "No se encontro el alias de nombre.", "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_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_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_last_name_required": "El apellido es obligatorio.",
"validation_first_name_required": "El nombre es obligatorio.", "validation_first_name_required": "El nombre es obligatorio.",
"error_ocr_service_unavailable": "El servicio OCR no está disponible.", "error_ocr_service_unavailable": "El servicio OCR no está disponible.",

View File

@@ -335,8 +335,10 @@ describe('TranscriptionReadView — person-mention rendering', () => {
displayName: 'Auguste Raddatz', displayName: 'Auguste Raddatz',
personType: 'PERSON', personType: 'PERSON',
familyMember: true, familyMember: true,
birthYear: 1882, birthDate: '1882-01-01',
deathYear: 1944 birthDatePrecision: 'YEAR',
deathDate: '1944-01-01',
deathDatePrecision: 'YEAR'
}) })
}); });
}) })

View File

@@ -1714,10 +1714,14 @@ export interface components {
lastName?: string; lastName?: string;
alias?: string; alias?: string;
notes?: string; notes?: string;
/** Format: int32 */ /** Format: date */
birthYear?: number; birthDate?: string;
/** Format: int32 */ /** @enum {string} */
deathYear?: number; birthDatePrecision?: "DAY" | "MONTH" | "SEASON" | "YEAR" | "RANGE" | "APPROX" | "UNKNOWN";
/** Format: date */
deathDate?: string;
/** @enum {string} */
deathDatePrecision?: "DAY" | "MONTH" | "SEASON" | "YEAR" | "RANGE" | "APPROX" | "UNKNOWN";
/** Format: int32 */ /** Format: int32 */
generation?: number; generation?: number;
}; };
@@ -1731,10 +1735,14 @@ export interface components {
personType: "PERSON" | "INSTITUTION" | "GROUP" | "UNKNOWN" | "SKIP"; personType: "PERSON" | "INSTITUTION" | "GROUP" | "UNKNOWN" | "SKIP";
alias?: string; alias?: string;
notes?: string; notes?: string;
/** Format: int32 */ /** Format: date */
birthYear?: number; birthDate?: string;
/** Format: int32 */ /** @enum {string} */
deathYear?: number; birthDatePrecision: "DAY" | "MONTH" | "SEASON" | "YEAR" | "RANGE" | "APPROX" | "UNKNOWN";
/** Format: date */
deathDate?: string;
/** @enum {string} */
deathDatePrecision: "DAY" | "MONTH" | "SEASON" | "YEAR" | "RANGE" | "APPROX" | "UNKNOWN";
/** Format: int32 */ /** Format: int32 */
generation?: number; generation?: number;
familyMember: boolean; familyMember: boolean;
@@ -2373,13 +2381,21 @@ export interface components {
documentCount?: number; documentCount?: number;
alias?: string; alias?: string;
notes?: 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 */ /** Format: int32 */
birthYear?: number; birthYear?: number;
/** Format: int32 */ /** Format: int32 */
deathYear?: number; deathYear?: number;
provisional?: boolean;
personType?: string;
familyMember?: boolean;
}; };
InferredRelationshipWithPersonDTO: { InferredRelationshipWithPersonDTO: {
person: components["schemas"]["PersonNodeDTO"]; person: components["schemas"]["PersonNodeDTO"];
@@ -2476,8 +2492,6 @@ export interface components {
/** Format: int32 */ /** Format: int32 */
totalPages?: number; totalPages?: number;
pageable?: components["schemas"]["PageableObject"]; pageable?: components["schemas"]["PageableObject"];
first?: boolean;
last?: boolean;
/** Format: int32 */ /** Format: int32 */
size?: number; size?: number;
content?: components["schemas"]["NotificationDTO"][]; content?: components["schemas"]["NotificationDTO"][];
@@ -2486,6 +2500,8 @@ export interface components {
sort?: components["schemas"]["SortObject"]; sort?: components["schemas"]["SortObject"];
/** Format: int32 */ /** Format: int32 */
numberOfElements?: number; numberOfElements?: number;
first?: boolean;
last?: boolean;
empty?: boolean; empty?: boolean;
}; };
PageableObject: { PageableObject: {
@@ -2673,7 +2689,7 @@ export interface components {
}; };
ActivityFeedItemDTO: { ActivityFeedItemDTO: {
/** @enum {string} */ /** @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" | "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" | "DOCUMENT_DELETED" | "JOURNEY_ITEM_ADDED" | "JOURNEY_ITEM_REMOVED" | "JOURNEY_ITEM_NOTE_UPDATED" | "JOURNEY_ITEMS_REORDERED";
actor?: components["schemas"]["ActivityActorDTO"]; actor?: components["schemas"]["ActivityActorDTO"];
/** Format: uuid */ /** Format: uuid */
documentId: string; documentId: string;
@@ -5541,7 +5557,7 @@ export interface operations {
query?: { query?: {
limit?: number; limit?: number;
/** @description Filter by audit kinds; omit for all rollup-eligible kinds */ /** @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" | "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" | "DOCUMENT_DELETED" | "JOURNEY_ITEM_ADDED" | "JOURNEY_ITEM_REMOVED" | "JOURNEY_ITEM_NOTE_UPDATED" | "JOURNEY_ITEMS_REORDERED")[];
}; };
header?: never; header?: never;
path?: never; path?: never;

View File

@@ -10,6 +10,8 @@ const personFactory = (id: string, displayName: string) => ({
lastName: displayName.split(' ').slice(1).join(' ') || displayName, lastName: displayName.split(' ').slice(1).join(' ') || displayName,
displayName, displayName,
personType: 'PERSON' as const, personType: 'PERSON' as const,
birthDatePrecision: 'UNKNOWN' as const,
deathDatePrecision: 'UNKNOWN' as const,
familyMember: false, familyMember: false,
provisional: false provisional: false
}); });

View File

@@ -1,6 +1,5 @@
<script lang="ts"> <script lang="ts">
import { m } from '$lib/paraglide/messages.js'; import { m } from '$lib/paraglide/messages.js';
import { formatLifeDateRange } from '$lib/person/personLifeDates';
import PersonTypeBadge from '$lib/person/PersonTypeBadge.svelte'; import PersonTypeBadge from '$lib/person/PersonTypeBadge.svelte';
import type { components } from '$lib/generated/api'; import type { components } from '$lib/generated/api';
@@ -125,10 +124,17 @@ const documentCount = $derived(person.documentCount ?? 0);
<p class="font-sans text-sm text-ink-2 italic">{person.alias}"</p> <p class="font-sans text-sm text-ink-2 italic">{person.alias}"</p>
{/if} {/if}
<!-- Life dates --> <!-- Life dates — PersonSummaryDTO is year-shaped by design (ADR-039); the glyphs are
aria-hidden so screen readers only announce the years. -->
{#if person.birthYear || person.deathYear} {#if person.birthYear || person.deathYear}
<p class="font-sans text-sm text-ink-3"> <p class="font-sans text-sm text-ink-3">
{formatLifeDateRange(person.birthYear, person.deathYear)} {#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}
</p> </p>
{/if} {/if}

View File

@@ -30,6 +30,27 @@ describe('PersonCard — confirmed person', () => {
render(PersonCard, { props: { person: makePerson() } }); render(PersonCard, { props: { person: makePerson() } });
await expect.element(page.getByText('unbestätigt')).not.toBeInTheDocument(); 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)', () => { describe('PersonCard — unconfirmed badge keys off provisional only (badge ⇔ count ⇔ triage parity)', () => {

View File

@@ -1,6 +1,6 @@
<script lang="ts"> <script lang="ts">
import { m } from '$lib/paraglide/messages.js'; import { m } from '$lib/paraglide/messages.js';
import { formatLifeDateRange } from '$lib/person/personLifeDates'; import { formatLifeDate } from '$lib/person/personLifeDates';
import { chipLabel, otherName } from '$lib/person/relationshipLabels'; import { chipLabel, otherName } from '$lib/person/relationshipLabels';
import type { components } from '$lib/generated/api'; import type { components } from '$lib/generated/api';
import type { LoadState } from '$lib/person/personHoverCard'; import type { LoadState } from '$lib/person/personHoverCard';
@@ -31,9 +31,14 @@ const familyChips = $derived(
: [] : []
); );
const dateRange = $derived( const birthText = $derived(
state.status === 'loaded' state.status === 'loaded'
? formatLifeDateRange(state.person.birthYear, state.person.deathYear) ? formatLifeDate(state.person.birthDate, state.person.birthDatePrecision)
: ''
);
const deathText = $derived(
state.status === 'loaded'
? formatLifeDate(state.person.deathDate, state.person.deathDatePrecision)
: '' : ''
); );
@@ -123,8 +128,17 @@ const showMaidenName = $derived(
<div data-testid="person-hover-card-content" class="content"> <div data-testid="person-hover-card-content" class="content">
<div class="header"> <div class="header">
<div class="name" data-testid="person-hover-card-name">{state.person.displayName}</div> <div class="name" data-testid="person-hover-card-name">{state.person.displayName}</div>
{#if dateRange} {#if birthText || deathText}
<div class="dates" data-testid="person-hover-card-dates">{dateRange}</div> <!-- 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} {/if}
{#if showMaidenName} {#if showMaidenName}
<div class="maiden" data-testid="person-hover-card-maiden"> <div class="maiden" data-testid="person-hover-card-maiden">

View File

@@ -14,8 +14,10 @@ const AUGUSTE: Person = {
displayName: 'Auguste Raddatz', displayName: 'Auguste Raddatz',
personType: 'PERSON', personType: 'PERSON',
familyMember: true, familyMember: true,
birthYear: 1882, birthDate: '1882-01-01',
deathYear: 1944 birthDatePrecision: 'YEAR',
deathDate: '1944-01-01',
deathDatePrecision: 'YEAR'
} as unknown as Person; } as unknown as Person;
const POSITION = { top: 100, left: 200 }; const POSITION = { top: 100, left: 200 };
@@ -81,18 +83,76 @@ describe('PersonHoverCard — loaded state', () => {
await expect.element(page.getByText('Auguste Raddatz')).toBeInTheDocument(); await expect.element(page.getByText('Auguste Raddatz')).toBeInTheDocument();
}); });
it('renders the life-date range when birthYear and deathYear are present', async () => { it('renders the life-date range when birth and death dates are present', async () => {
render(PersonHoverCard, { render(PersonHoverCard, {
personId: 'p-aug', personId: 'p-aug',
cardId: 'card-1', cardId: 'card-1',
position: POSITION, position: POSITION,
state: { status: 'loaded', person: AUGUSTE, relationships: [] } state: { status: 'loaded', person: AUGUSTE, relationships: [] }
}); });
await expect.element(page.getByText('* 1882 † 1944')).toBeInTheDocument(); await expect
.element(page.getByTestId('person-hover-card-dates'))
.toHaveTextContent('* 1882 † 1944');
}); });
it('omits the life-date line when both years are missing', async () => { it('renders a DAY-precision birth date as a full localized date', async () => {
const noDates = { ...AUGUSTE, birthYear: undefined, deathYear: undefined } as Person; 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;
render(PersonHoverCard, { render(PersonHoverCard, {
personId: 'p-aug', personId: 'p-aug',
cardId: 'card-1', cardId: 'card-1',

View File

@@ -0,0 +1,98 @@
<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>

View File

@@ -0,0 +1,64 @@
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');
});
});

View File

@@ -9,8 +9,10 @@ export type PersonFormData = {
firstName?: string | null; firstName?: string | null;
lastName: string; lastName: string;
alias?: string | null; alias?: string | null;
birthYear?: number | null; birthDate?: string | null;
deathYear?: number | null; birthDatePrecision?: string | null;
deathDate?: string | null;
deathDatePrecision?: string | null;
generation?: number | null; generation?: number | null;
notes?: string | null; notes?: string | null;
}; };

View File

@@ -1,24 +1,113 @@
import { describe, it, expect } from 'vitest'; import { describe, expect, it } from 'vitest';
import { formatLifeDateRange } from './personLifeDates'; import { formatLifeDate, 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('formatLifeDateRange', () => {
it('returns both dates when birth and death year are given', () => { describe('both dates (de default)', () => {
expect(formatLifeDateRange(1882, 1944)).toBe('* 1882 † 1944'); 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('returns only birth year when only birthYear is given', () => { it('renders MONTH precision as month + year', () => {
expect(formatLifeDateRange(1882, undefined)).toBe('* 1882'); expect(formatLifeDateRange('1901-03-01', 'MONTH', '1944-11-01', 'MONTH')).toBe(
'* März 1901 † November 1944'
);
}); });
it('returns only death year when only deathYear is given', () => { it('renders YEAR precision as bare years', () => {
expect(formatLifeDateRange(undefined, 1944)).toBe('† 1944'); expect(formatLifeDateRange('1901-01-01', 'YEAR', '1944-01-01', 'YEAR')).toBe(
'* 1901 † 1944'
);
}); });
it('returns empty string when neither year is given', () => { it('renders mixed precisions per side', () => {
expect(formatLifeDateRange(undefined, undefined)).toBe(''); expect(formatLifeDateRange('1901-03-14', 'DAY', '1944-01-01', 'YEAR')).toBe(
'* 14. März 1901 † 1944'
);
}); });
it('returns empty string when both are null', () => { it('renders APPROX precision with the ca. prefix (legacy imports)', () => {
expect(formatLifeDateRange(null, null)).toBe(''); expect(formatLifeDateRange('1901-01-01', 'APPROX', '1944-01-01', 'APPROX')).toBe(
'* ca. 1901 † ca. 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');
});
});
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('renders MONTH precision in English', () => {
expect(formatLifeDateRange('1901-03-01', 'MONTH', null, null, 'en')).toBe('* March 1901');
});
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');
}); });
}); });

View File

@@ -1,20 +1,44 @@
import { formatDocumentDate, type DatePrecision } from '$lib/shared/utils/documentDate';
/** /**
* Formats the life date range for a person. * Formats one life date (birth or death) at the precision the data claims,
* Examples: * delegating all rendering to {@link formatDocumentDate}. Returns '' for a
* * 1882 † 1944 (both) * missing date. Carries no * / † glyph — components that need the glyphs wrap
* * 1882 (birth only) * them in their own `aria-hidden` markup so screen readers only hear the date.
* † 1944 (death only) *
* "" (neither) * 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 formatLifeDateRange(birthYear?: number | null, deathYear?: number | null): string { export function formatLifeDate(
if (birthYear && deathYear) { date: string | null | undefined,
return `* ${birthYear} ${deathYear}`; precision: DatePrecision | null | undefined,
} locale?: string
if (birthYear) { ): string {
return `* ${birthYear}`; if (!date) {
}
if (deathYear) {
return `${deathYear}`;
}
return ''; return '';
} }
return formatDocumentDate(date, precision ?? 'YEAR', null, null, locale);
}
/**
* Formats the full life date range as plain text, e.g. for dropdown subtitles.
* Examples:
* * 14. März 1901 † 2. November 1944 (both, DAY precision)
* * 1882 (birth only, YEAR precision)
* † ca. 1944 (death only, APPROX precision)
* "" (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}`;
}
return birth ?? death ?? '';
}

View File

@@ -143,6 +143,8 @@ describe('ReaderRecentDocs', () => {
firstName: 'Anna', firstName: 'Anna',
displayName: 'Anna Müller', displayName: 'Anna Müller',
personType: 'PERSON' as const, personType: 'PERSON' as const,
birthDatePrecision: 'UNKNOWN' as const,
deathDatePrecision: 'UNKNOWN' as const,
familyMember: false, familyMember: false,
provisional: false provisional: false
} }

View File

@@ -15,7 +15,9 @@ import { m } from '$lib/paraglide/messages.js';
// — see Felix #3 on PR #629. // — see Felix #3 on PR #629.
import { MAX_QUERY_LENGTH } from './mentionConstants'; import { MAX_QUERY_LENGTH } from './mentionConstants';
type Person = components['schemas']['Person']; // 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'];
// The dropdown receives a single reactive state object. PersonMentionEditor // The dropdown receives a single reactive state object. PersonMentionEditor
// mutates fields on this object (model.items = ..., etc.) and Svelte's $state // mutates fields on this object (model.items = ..., etc.) and Svelte's $state
@@ -306,6 +308,12 @@ function selectItem(item: Person) {
</a> </a>
{:else} {:else}
{#each model.items as person, i (person.id)} {#each model.items as person, i (person.id)}
{@const lifeDates = formatLifeDateRange(
person.birthDate,
person.birthDatePrecision,
person.deathDate,
person.deathDatePrecision
)}
<div <div
class={[ class={[
'flex min-h-[44px] cursor-pointer flex-col gap-1 px-3 py-2.5 text-left hover:bg-canvas', 'flex min-h-[44px] cursor-pointer flex-col gap-1 px-3 py-2.5 text-left hover:bg-canvas',
@@ -325,9 +333,11 @@ function selectItem(item: Person) {
}} }}
> >
<span class="truncate font-serif text-base text-ink">{person.displayName}</span> <span class="truncate font-serif text-base text-ink">{person.displayName}</span>
{#if formatLifeDateRange(person.birthYear, person.deathYear)} {#if lifeDates}
<span class="truncate font-sans text-xs text-ink-3"> <!-- whitespace-normal: a DAY-precision range (~37 chars) wraps to a second
{formatLifeDateRange(person.birthYear, person.deathYear)} line at 320px instead of being clipped by truncate. -->
<span class="font-sans text-xs whitespace-normal text-ink-3">
{lifeDates}
</span> </span>
{/if} {/if}
</div> </div>

View File

@@ -7,7 +7,9 @@ import MentionDropdownFixture from './MentionDropdown.test-fixture.svelte';
import { m } from '$lib/paraglide/messages.js'; import { m } from '$lib/paraglide/messages.js';
import type { components } from '$lib/generated/api'; import type { components } from '$lib/generated/api';
type Person = components['schemas']['Person']; // PersonSummaryDTO mirrors the real runtime shape: /api/persons list items are
// the summary projection, not the full entity (#812).
type Person = components['schemas']['PersonSummaryDTO'];
afterEach(cleanup); afterEach(cleanup);
@@ -19,6 +21,8 @@ const makePerson = (id: string, name: string, overrides: Partial<Person> = {}):
lastName: parts.slice(1).join(' ') || name, lastName: parts.slice(1).join(' ') || name,
displayName: name, displayName: name,
personType: 'PERSON', personType: 'PERSON',
birthDatePrecision: 'UNKNOWN',
deathDatePrecision: 'UNKNOWN',
familyMember: false, familyMember: false,
provisional: false, provisional: false,
...overrides ...overrides
@@ -103,11 +107,18 @@ describe('MentionDropdown', () => {
expect(option?.getAttribute('aria-selected')).toBe('true'); expect(option?.getAttribute('aria-selected')).toBe('true');
}); });
it('renders the life-date range when birthYear or deathYear is present', async () => { it('renders the life-date range when birth or death date is present', async () => {
render(MentionDropdown, { render(MentionDropdown, {
props: { props: {
model: baseModel({ model: baseModel({
items: [makePerson('p1', 'Anna', { birthYear: 1899, deathYear: 1972 })] items: [
makePerson('p1', 'Anna', {
birthDate: '1899-01-01',
birthDatePrecision: 'YEAR',
deathDate: '1972-01-01',
deathDatePrecision: 'YEAR'
})
]
}) })
} }
}); });
@@ -115,6 +126,25 @@ describe('MentionDropdown', () => {
await expect.element(page.getByText(/1899/)).toBeVisible(); 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 () => { it('falls back to a default position when clientRect returns null', async () => {
render(MentionDropdown, { render(MentionDropdown, {
props: { props: {

View File

@@ -3,7 +3,7 @@ import { untrack } from 'svelte';
import MentionDropdown from './MentionDropdown.svelte'; import MentionDropdown from './MentionDropdown.svelte';
import type { components } from '$lib/generated/api'; import type { components } from '$lib/generated/api';
type Person = components['schemas']['Person']; type Person = components['schemas']['PersonSummaryDTO'];
type DropdownState = { type DropdownState = {
items: Person[]; items: Person[];
command: (item: Person) => void; command: (item: Person) => void;

View File

@@ -12,7 +12,9 @@ import MentionDropdown from './MentionDropdown.svelte';
import { createMentionNodeView } from './mentionNodeView'; import { createMentionNodeView } from './mentionNodeView';
import { MAX_QUERY_LENGTH, SEARCH_DEBOUNCE_MS, SEARCH_RESULT_LIMIT } from './mentionConstants'; import { MAX_QUERY_LENGTH, SEARCH_DEBOUNCE_MS, SEARCH_RESULT_LIMIT } from './mentionConstants';
type Person = components['schemas']['Person']; // 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 Props = { type Props = {
value: string; value: string;
@@ -216,14 +218,15 @@ const controller = createMentionController();
// reflected data-person-id or the search input). // reflected data-person-id or the search input).
function commitRelink(pos: number): CommitFn { function commitRelink(pos: number): CommitFn {
return (item: Person) => { return (item: Person) => {
if (!editor) return; if (!editor || !item.id) return;
const personId = item.id;
editor editor
.chain() .chain()
.focus() .focus()
.command(({ tr, state }) => { .command(({ tr, state }) => {
const node = state.doc.nodeAt(pos); const node = state.doc.nodeAt(pos);
if (!node || node.type.name !== 'mention') return false; if (!node || node.type.name !== 'mention') return false;
tr.setNodeMarkup(pos, undefined, { ...node.attrs, personId: item.id }); tr.setNodeMarkup(pos, undefined, { ...node.attrs, personId });
return true; return true;
}) })
.run(); .run();
@@ -364,9 +367,11 @@ onMount(() => {
render() { render() {
const buildFreshCommit = (loose: LooseRenderProps): CommitFn => { const buildFreshCommit = (loose: LooseRenderProps): CommitFn => {
const clippedQuery = loose.query.slice(0, MAX_QUERY_LENGTH); const clippedQuery = loose.query.slice(0, MAX_QUERY_LENGTH);
return (item: Person) => return (item: Person) => {
if (!item.id) return;
loose.command({ personId: item.id, displayName: clippedQuery }); loose.command({ personId: item.id, displayName: clippedQuery });
}; };
};
return { return {
onStart(renderProps) { onStart(renderProps) {
const loose = renderProps as unknown as LooseRenderProps; const loose = renderProps as unknown as LooseRenderProps;

View File

@@ -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. // module so the test cannot drift from production. Sara on PR #629 round 3.
import { SEARCH_DEBOUNCE_MS } from './mentionConstants'; import { SEARCH_DEBOUNCE_MS } from './mentionConstants';
type Person = components['schemas']['Person']; type Person = components['schemas']['PersonSummaryDTO'];
type PersonMention = components['schemas']['PersonMention']; type PersonMention = components['schemas']['PersonMention'];
/** /**
@@ -35,8 +35,10 @@ const AUGUSTE: Person = {
personType: 'PERSON', personType: 'PERSON',
familyMember: false, familyMember: false,
provisional: false, provisional: false,
birthYear: 1882, birthDate: '1882-01-01',
deathYear: 1944 birthDatePrecision: 'YEAR',
deathDate: '1944-01-01',
deathDatePrecision: 'YEAR'
}; };
const ANNA: Person = { const ANNA: Person = {
@@ -47,7 +49,9 @@ const ANNA: Person = {
personType: 'PERSON', personType: 'PERSON',
familyMember: false, familyMember: false,
provisional: false, provisional: false,
birthYear: 1860 birthDate: '1860-01-01',
birthDatePrecision: 'YEAR',
deathDatePrecision: 'UNKNOWN'
}; };
function mockFetchWithPersons(persons: Person[] = [AUGUSTE, ANNA]) { function mockFetchWithPersons(persons: Person[] = [AUGUSTE, ANNA]) {

View File

@@ -8,6 +8,8 @@ export type ErrorCode =
| 'PERSON_NOT_FOUND' | 'PERSON_NOT_FOUND'
| 'ALIAS_NOT_FOUND' | 'ALIAS_NOT_FOUND'
| 'INVALID_PERSON_TYPE' | 'INVALID_PERSON_TYPE'
| 'BIRTH_AFTER_DEATH'
| 'INVALID_DATE_PRECISION'
| 'INVALID_DATE_RANGE' | 'INVALID_DATE_RANGE'
| 'DOCUMENT_NOT_FOUND' | 'DOCUMENT_NOT_FOUND'
| 'DOCUMENT_NO_FILE' | 'DOCUMENT_NO_FILE'
@@ -96,6 +98,10 @@ export function getErrorMessage(code: ErrorCode | string | undefined): string {
return m.error_alias_not_found(); return m.error_alias_not_found();
case 'INVALID_PERSON_TYPE': case 'INVALID_PERSON_TYPE':
return m.error_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': case 'INVALID_DATE_RANGE':
return m.error_invalid_date_range(); return m.error_invalid_date_range();
case 'DOCUMENT_NOT_FOUND': case 'DOCUMENT_NOT_FOUND':

View File

@@ -11,6 +11,11 @@ interface Props {
placeholder?: string; placeholder?: string;
class?: string; class?: string;
onchange?: () => void; 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 { let {
@@ -20,7 +25,10 @@ let {
id, id,
placeholder, placeholder,
class: className = '', class: className = '',
onchange onchange,
ariaLabel,
ariaDescribedby,
inputEl = $bindable()
}: Props = $props(); }: Props = $props();
let display = $state(isoToGerman(value ?? '')); let display = $state(isoToGerman(value ?? ''));
@@ -76,10 +84,13 @@ function handleInput(e: Event) {
</script> </script>
<input <input
bind:this={inputEl}
type="text" type="text"
inputmode="numeric" inputmode="numeric"
maxlength="10" maxlength="10"
id={id} id={id}
aria-label={ariaLabel}
aria-describedby={ariaDescribedby}
value={display} value={display}
placeholder={placeholder ?? m.form_placeholder_date()} placeholder={placeholder ?? m.form_placeholder_date()}
oninput={handleInput} oninput={handleInput}

View File

@@ -288,6 +288,8 @@ describe('DocumentList undated badge in person grouping', () => {
lastName: 'Mustermann', lastName: 'Mustermann',
displayName: 'Max Mustermann', displayName: 'Max Mustermann',
personType: 'PERSON' as const, personType: 'PERSON' as const,
birthDatePrecision: 'UNKNOWN' as const,
deathDatePrecision: 'UNKNOWN' as const,
familyMember: false, familyMember: false,
provisional: false provisional: false
}; };
@@ -296,6 +298,8 @@ describe('DocumentList undated badge in person grouping', () => {
lastName: 'Brandt', lastName: 'Brandt',
displayName: 'Felix Brandt', displayName: 'Felix Brandt',
personType: 'PERSON' as const, personType: 'PERSON' as const,
birthDatePrecision: 'UNKNOWN' as const,
deathDatePrecision: 'UNKNOWN' as const,
familyMember: false, familyMember: false,
provisional: false provisional: false
}; };

View File

@@ -1,7 +1,8 @@
<script lang="ts"> <script lang="ts">
import { m } from '$lib/paraglide/messages.js'; import { m } from '$lib/paraglide/messages.js';
import { formatLifeDateRange } from '$lib/person/personLifeDates'; import { formatLifeDate } from '$lib/person/personLifeDates';
import PersonTypeBadge from '$lib/person/PersonTypeBadge.svelte'; import PersonTypeBadge from '$lib/person/PersonTypeBadge.svelte';
import type { DatePrecision } from '$lib/shared/utils/documentDate';
let { let {
person, person,
@@ -15,12 +16,17 @@ let {
personType?: string | null; personType?: string | null;
title?: string | null; title?: string | null;
alias?: string | null; alias?: string | null;
birthYear?: number | null; birthDate?: string | null;
deathYear?: number | null; birthDatePrecision?: DatePrecision | null;
deathDate?: string | null;
deathDatePrecision?: DatePrecision | null;
notes?: string | null; notes?: string | null;
}; };
canWrite: boolean; canWrite: boolean;
} = $props(); } = $props();
const birthText = $derived(formatLifeDate(person.birthDate, person.birthDatePrecision));
const deathText = $derived(formatLifeDate(person.deathDate, person.deathDatePrecision));
</script> </script>
<div class="overflow-hidden rounded-sm border border-line bg-surface shadow-sm"> <div class="overflow-hidden rounded-sm border border-line bg-surface shadow-sm">
@@ -91,10 +97,16 @@ let {
<p class="mb-1 text-center font-sans text-sm text-ink-2 italic">{person.alias}"</p> <p class="mb-1 text-center font-sans text-sm text-ink-2 italic">{person.alias}"</p>
{/if} {/if}
<!-- Life dates — centered --> <!-- Life dates — centered; glyphs aria-hidden so screen readers only hear the dates -->
{#if person.birthYear || person.deathYear} {#if birthText || deathText}
<p class="mb-4 text-center font-sans text-sm text-ink-3"> <p class="mb-4 text-center font-sans text-sm text-ink-3">
{formatLifeDateRange(person.birthYear, person.deathYear)} {#if birthText}
<span aria-hidden="true">*</span> {birthText}
{/if}
{#if birthText && deathText}{/if}
{#if deathText}
<span aria-hidden="true"></span> {deathText}
{/if}
</p> </p>
{:else} {:else}
<div class="mb-4"></div> <div class="mb-4"></div>

View File

@@ -82,15 +82,84 @@ describe('PersonCard', () => {
await expect.element(page.getByText(/Annerl/)).toBeVisible(); await expect.element(page.getByText(/Annerl/)).toBeVisible();
}); });
it('renders the life-date range when birthYear or deathYear are present', async () => { it('renders DAY-precision life dates as full localized dates', async () => {
render(PersonCard, { render(PersonCard, {
props: { props: {
person: { ...basePerson, birthYear: 1899, deathYear: 1972 }, person: {
...basePerson,
birthDate: '1901-03-14',
birthDatePrecision: 'DAY' as const,
deathDate: '1944-11-02',
deathDatePrecision: 'DAY' as const
},
canWrite: false canWrite: false
} }
}); });
await expect.element(page.getByText(/1899/)).toBeVisible(); 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('†');
}); });
it('renders the notes section when notes are provided', async () => { it('renders the notes section when notes are provided', async () => {

View File

@@ -1,6 +1,7 @@
import { error, fail, redirect } from '@sveltejs/kit'; import { error, fail, redirect } from '@sveltejs/kit';
import { createApiClient, extractErrorCode } from '$lib/shared/api.server'; import { createApiClient, extractErrorCode } from '$lib/shared/api.server';
import { getErrorMessage } from '$lib/shared/errors'; import { getErrorMessage } from '$lib/shared/errors';
import type { DatePrecision } from '$lib/shared/utils/documentDate';
import { import {
normalizePersonType, normalizePersonType,
validatePersonFields, validatePersonFields,
@@ -47,10 +48,17 @@ export const actions = {
const lastName = formData.get('lastName')?.toString().trim(); const lastName = formData.get('lastName')?.toString().trim();
const alias = formData.get('alias')?.toString().trim() || undefined; const alias = formData.get('alias')?.toString().trim() || undefined;
const notes = formData.get('notes')?.toString().trim() || undefined; const notes = formData.get('notes')?.toString().trim() || undefined;
const birthYearStr = formData.get('birthYear')?.toString().trim(); // Empty date input → omit date AND precision: the backend normalises the
const deathYearStr = formData.get('deathYear')?.toString().trim(); // absent pair to null/UNKNOWN, and a lone precision would fail the
const birthYear = birthYearStr ? parseInt(birthYearStr, 10) : undefined; // coherence check (INVALID_DATE_PRECISION).
const deathYear = deathYearStr ? parseInt(deathYearStr, 10) : undefined; 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;
// Must NOT use the conditional-spread idiom for generation: G 0 is a // 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 // valid family-tree-root value. The key always travels in the body so
// an explicit clear (empty option) reaches the backend as null. // an explicit clear (empty option) reaches the backend as null.
@@ -73,8 +81,8 @@ export const actions = {
lastName, lastName,
...(alias ? { alias } : {}), ...(alias ? { alias } : {}),
...(notes ? { notes } : {}), ...(notes ? { notes } : {}),
...(birthYear ? { birthYear } : {}), ...(birthDate ? { birthDate, birthDatePrecision } : {}),
...(deathYear ? { deathYear } : {}), ...(deathDate ? { deathDate, deathDatePrecision } : {}),
generation generation
} }
}); });

View File

@@ -1,6 +1,7 @@
<script lang="ts"> <script lang="ts">
import { untrack } from 'svelte'; import { untrack } from 'svelte';
import { m } from '$lib/paraglide/messages.js'; import { m } from '$lib/paraglide/messages.js';
import PersonLifeDateField from '$lib/person/PersonLifeDateField.svelte';
import PersonTypeSelector from '$lib/person/PersonTypeSelector.svelte'; import PersonTypeSelector from '$lib/person/PersonTypeSelector.svelte';
import { import {
PERSON_TYPES as TYPES, PERSON_TYPES as TYPES,
@@ -88,32 +89,20 @@ const inputCls =
<label for="alias" class={labelCls}>{m.form_label_alias()}</label> <label for="alias" class={labelCls}>{m.form_label_alias()}</label>
<input id="alias" name="alias" type="text" value={person.alias ?? ''} class={inputCls} /> <input id="alias" name="alias" type="text" value={person.alias ?? ''} class={inputCls} />
</div> </div>
<div> <PersonLifeDateField
<label for="birthYear" class={labelCls}>{m.person_label_birth_year()}</label> name="birthDate"
<input legend={m.person_label_birth_date()}
id="birthYear" precisionLabel={m.person_label_birth_date_precision()}
name="birthYear" initialIso={person.birthDate ?? ''}
type="number" initialPrecision={person.birthDatePrecision ?? null}
min="1"
max="2100"
placeholder={m.person_placeholder_year()}
value={person.birthYear ?? ''}
class={inputCls}
/> />
</div> <PersonLifeDateField
<div> name="deathDate"
<label for="deathYear" class={labelCls}>{m.person_label_death_year()}</label> legend={m.person_label_death_date()}
<input precisionLabel={m.person_label_death_date_precision()}
id="deathYear" initialIso={person.deathDate ?? ''}
name="deathYear" initialPrecision={person.deathDatePrecision ?? null}
type="number"
min="1"
max="2100"
placeholder={m.person_placeholder_year()}
value={person.deathYear ?? ''}
class={inputCls}
/> />
</div>
<div class="md:col-span-2"> <div class="md:col-span-2">
<label for="generation" class={labelCls}>{m.person_label_generation()}</label> <label for="generation" class={labelCls}>{m.person_label_generation()}</label>
<select <select

View File

@@ -1,6 +1,6 @@
import { describe, it, expect, afterEach } from 'vitest'; import { describe, it, expect, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte'; import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser'; import { page, userEvent } from 'vitest/browser';
import PersonEditForm from './PersonEditForm.svelte'; import PersonEditForm from './PersonEditForm.svelte';
afterEach(cleanup); afterEach(cleanup);
@@ -12,8 +12,10 @@ const personPersonal = {
firstName: 'Anna', firstName: 'Anna',
lastName: 'Schmidt', lastName: 'Schmidt',
alias: 'Anni', alias: 'Anni',
birthYear: 1899 as number | null, birthDate: '1899-03-14' as string | null,
deathYear: 1972 as number | null, birthDatePrecision: 'DAY' as string | null,
deathDate: '1972-01-01' as string | null,
deathDatePrecision: 'YEAR' as string | null,
notes: 'Wohnte in Berlin.' notes: 'Wohnte in Berlin.'
}; };
@@ -24,8 +26,10 @@ const personInstitution = {
firstName: null, firstName: null,
lastName: 'Acme GmbH', lastName: 'Acme GmbH',
alias: null, alias: null,
birthYear: null, birthDate: null,
deathYear: null, birthDatePrecision: null,
deathDate: null,
deathDatePrecision: null,
notes: null notes: null
}; };
@@ -42,14 +46,14 @@ describe('PersonEditForm', () => {
await expect.element(page.getByLabelText(/titel/i)).toBeVisible(); await expect.element(page.getByLabelText(/titel/i)).toBeVisible();
}); });
it('hides the firstName / title / alias / year fields for INSTITUTION', async () => { it('hides the firstName / title / alias / life-date fields for INSTITUTION', async () => {
render(PersonEditForm, { props: { person: personInstitution } }); render(PersonEditForm, { props: { person: personInstitution } });
await expect.element(page.getByLabelText(/vorname/i)).not.toBeInTheDocument(); await expect.element(page.getByLabelText(/vorname/i)).not.toBeInTheDocument();
await expect.element(page.getByLabelText(/^titel$/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(/rufname/i)).not.toBeInTheDocument();
await expect.element(page.getByLabelText(/geburtsjahr/i)).not.toBeInTheDocument(); await expect.element(page.getByLabelText(/^geburtsdatum$/i)).not.toBeInTheDocument();
await expect.element(page.getByLabelText(/todesjahr/i)).not.toBeInTheDocument(); await expect.element(page.getByLabelText(/^sterbedatum$/i)).not.toBeInTheDocument();
}); });
it('uses the "Nachname" label for PERSON', async () => { it('uses the "Nachname" label for PERSON', async () => {
@@ -77,13 +81,63 @@ describe('PersonEditForm', () => {
expect(title.value).toBe('Frau Dr.'); expect(title.value).toBe('Frau Dr.');
}); });
it('renders birthYear and deathYear inputs with prior values', async () => { it('renders an existing DAY-precision birth date as dd.mm.yyyy in the date input', async () => {
render(PersonEditForm, { props: { person: personPersonal } }); render(PersonEditForm, { props: { person: personPersonal } });
const birthYear = (await page.getByLabelText(/geburtsjahr/i).element()) as HTMLInputElement; const birthInput = (await page.getByLabelText(/^geburtsdatum$/i).element()) as HTMLInputElement;
const deathYear = (await page.getByLabelText(/todesjahr/i).element()) as HTMLInputElement; expect(birthInput.value).toBe('14.03.1899');
expect(birthYear.value).toBe('1899'); });
expect(deathYear.value).toBe('1972');
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);
}); });
it('renders the notes textarea pre-filled with prior content', async () => { it('renders the notes textarea pre-filled with prior content', async () => {
@@ -103,15 +157,23 @@ describe('PersonEditForm', () => {
it('renders empty inputs when nullable fields are null', async () => { it('renders empty inputs when nullable fields are null', async () => {
render(PersonEditForm, { render(PersonEditForm, {
props: { person: { ...personPersonal, title: null, alias: null, birthYear: null } } props: {
person: {
...personPersonal,
title: null,
alias: null,
birthDate: null,
birthDatePrecision: null
}
}
}); });
const title = (await page.getByLabelText(/^titel/i).element()) as HTMLInputElement; const title = (await page.getByLabelText(/^titel/i).element()) as HTMLInputElement;
const alias = (await page.getByLabelText(/rufname/i).element()) as HTMLInputElement; const alias = (await page.getByLabelText(/rufname/i).element()) as HTMLInputElement;
const birthYear = (await page.getByLabelText(/geburtsjahr/i).element()) as HTMLInputElement; const birthInput = (await page.getByLabelText(/^geburtsdatum$/i).element()) as HTMLInputElement;
expect(title.value).toBe(''); expect(title.value).toBe('');
expect(alias.value).toBe(''); expect(alias.value).toBe('');
expect(birthYear.value).toBe(''); expect(birthInput.value).toBe('');
}); });
// ─── generation dropdown (#689) ───────────────────────────────────────────── // ─── generation dropdown (#689) ─────────────────────────────────────────────
@@ -157,4 +219,16 @@ describe('PersonEditForm', () => {
const select = (await page.getByLabelText(/^generation$/i).element()) as HTMLSelectElement; const select = (await page.getByLabelText(/^generation$/i).element()) as HTMLSelectElement;
expect(select.value).toBe(''); 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();
});
}); });

View File

@@ -1,6 +1,7 @@
import { error, fail, redirect } from '@sveltejs/kit'; import { error, fail, redirect } from '@sveltejs/kit';
import { createApiClient, extractErrorCode } from '$lib/shared/api.server'; import { createApiClient, extractErrorCode } from '$lib/shared/api.server';
import { getErrorMessage } from '$lib/shared/errors'; import { getErrorMessage } from '$lib/shared/errors';
import type { DatePrecision } from '$lib/shared/utils/documentDate';
import { import {
normalizePersonType, normalizePersonType,
validatePersonFields, validatePersonFields,
@@ -23,8 +24,17 @@ export const actions = {
const firstName = formData.get('firstName')?.toString().trim(); const firstName = formData.get('firstName')?.toString().trim();
const lastName = formData.get('lastName')?.toString().trim(); const lastName = formData.get('lastName')?.toString().trim();
const alias = formData.get('alias')?.toString().trim() || undefined; const alias = formData.get('alias')?.toString().trim() || undefined;
const birthYearStr = formData.get('birthYear')?.toString().trim(); // Empty date input → omit date AND precision: the backend normalises the
const deathYearStr = formData.get('deathYear')?.toString().trim(); // 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 notes = formData.get('notes')?.toString().trim() || undefined; const notes = formData.get('notes')?.toString().trim() || undefined;
// Must NOT use the conditional-spread idiom for generation: G 0 is a // 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 // valid family-tree-root value. Always travels in the body so an
@@ -45,9 +55,6 @@ export const actions = {
}); });
} }
const birthYear = birthYearStr ? parseInt(birthYearStr, 10) : undefined;
const deathYear = deathYearStr ? parseInt(deathYearStr, 10) : undefined;
const api = createApiClient(fetch); const api = createApiClient(fetch);
const result = await api.POST('/api/persons', { const result = await api.POST('/api/persons', {
body: { body: {
@@ -56,8 +63,8 @@ export const actions = {
...(firstName ? { firstName } : {}), ...(firstName ? { firstName } : {}),
lastName: lastName!, lastName: lastName!,
...(alias ? { alias } : {}), ...(alias ? { alias } : {}),
...(birthYear ? { birthYear } : {}), ...(birthDate ? { birthDate, birthDatePrecision } : {}),
...(deathYear ? { deathYear } : {}), ...(deathDate ? { deathDate, deathDatePrecision } : {}),
...(notes ? { notes } : {}), ...(notes ? { notes } : {}),
generation generation
} }

View File

@@ -2,6 +2,7 @@
import { untrack } from 'svelte'; import { untrack } from 'svelte';
import { m } from '$lib/paraglide/messages.js'; import { m } from '$lib/paraglide/messages.js';
import BackButton from '$lib/shared/primitives/BackButton.svelte'; import BackButton from '$lib/shared/primitives/BackButton.svelte';
import PersonLifeDateField from '$lib/person/PersonLifeDateField.svelte';
import PersonTypeSelector from '$lib/person/PersonTypeSelector.svelte'; import PersonTypeSelector from '$lib/person/PersonTypeSelector.svelte';
import { PERSON_TYPES as TYPES, type PersonType } from '$lib/person/person-validation'; import { PERSON_TYPES as TYPES, type PersonType } from '$lib/person/person-validation';
@@ -102,30 +103,16 @@ const labelCls = 'mb-1 block text-sm font-medium text-ink-2';
class={inputCls} class={inputCls}
/> />
</div> </div>
<div> <PersonLifeDateField
<label for="birthYear" class={labelCls}>{m.person_label_birth_year()}</label> name="birthDate"
<input legend={m.person_label_birth_date()}
id="birthYear" precisionLabel={m.person_label_birth_date_precision()}
name="birthYear"
type="number"
min="1"
max="2100"
placeholder={m.person_placeholder_year()}
class={inputCls}
/> />
</div> <PersonLifeDateField
<div> name="deathDate"
<label for="deathYear" class={labelCls}>{m.person_label_death_year()}</label> legend={m.person_label_death_date()}
<input precisionLabel={m.person_label_death_date_precision()}
id="deathYear"
name="deathYear"
type="number"
min="1"
max="2100"
placeholder={m.person_placeholder_year()}
class={inputCls}
/> />
</div>
{/if} {/if}
<div class="md:col-span-2"> <div class="md:col-span-2">