From e24c8c86d672a6970780660ffcbd34cda8df0602 Mon Sep 17 00:00:00 2001 From: IliesAllali Date: Fri, 16 Oct 2026 22:16:45 +0200 Subject: [PATCH 1/4] =?UTF-8?q?=C3=89v=C3=A9nements=20de=20vie=20:=20table?= =?UTF-8?q?,=20migration,=20import=20GEDCOM?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nouvelle table life_events (baptême, résidence, métiers, études, service militaire, inhumation, divorce, événements libres…) avec date, précision, lieu, description, notes et sources. Personne : précision et borne des dates de naissance et de décès, lieu de décès, surnom. Union : lieu et précision du mariage. Naissance, décès et mariage gardent leur date et leur lieu sur la personne ou l'union ; leur ligne d'événement ne porte que les sources et les notes. Migration additive. L'import lit tous ces événements (balises de la norme, variantes Gramps, Heredis, RootsMagic), les adresses complètes, et les adoptions déclarées par PEDI. Une personne ou une union déjà présente ne reçoit rien en double. Co-Authored-By: Claude Opus 5.5 --- .../migration.sql | 47 +++ backend/prisma/schema.prisma | 268 ++++++++++-------- backend/src/lib/gedcom-events.ts | 189 ++++++++++++ backend/src/lib/gedcom-photos.ts | 6 +- backend/src/routes/gedcom.ts | 21 +- backend/test/gedcom-events.test.ts | 98 +++++++ 6 files changed, 510 insertions(+), 119 deletions(-) create mode 100644 backend/prisma/migrations/20261016_001_evenements_de_vie/migration.sql create mode 100644 backend/src/lib/gedcom-events.ts create mode 100644 backend/test/gedcom-events.test.ts diff --git a/backend/prisma/migrations/20261016_001_evenements_de_vie/migration.sql b/backend/prisma/migrations/20261016_001_evenements_de_vie/migration.sql new file mode 100644 index 0000000..262c572 --- /dev/null +++ b/backend/prisma/migrations/20261016_001_evenements_de_vie/migration.sql @@ -0,0 +1,47 @@ +-- AlterTable +ALTER TABLE "persons" ADD COLUMN "birthDateEnd" TIMESTAMP(3), +ADD COLUMN "birthDatePrecision" TEXT, +ADD COLUMN "deathDateEnd" TIMESTAMP(3), +ADD COLUMN "deathDatePrecision" TEXT, +ADD COLUMN "deathPlace" TEXT, +ADD COLUMN "nickname" TEXT; + +-- AlterTable +ALTER TABLE "unions" ADD COLUMN "startDatePrecision" TEXT, +ADD COLUMN "startPlace" TEXT; + +-- CreateTable +CREATE TABLE "life_events" ( + "id" TEXT NOT NULL, + "treeId" TEXT NOT NULL, + "personId" TEXT, + "unionId" TEXT, + "type" TEXT NOT NULL, + "label" TEXT, + "date" TIMESTAMP(3), + "dateEnd" TIMESTAMP(3), + "datePrecision" TEXT, + "dateText" TEXT, + "place" TEXT, + "description" TEXT, + "notes" TEXT, + "sources" TEXT, + "displayOrder" INTEGER NOT NULL DEFAULT 1, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + "deletedAt" TIMESTAMP(3), + + CONSTRAINT "life_events_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "life_events_treeId_idx" ON "life_events"("treeId"); + +-- CreateIndex +CREATE INDEX "life_events_treeId_personId_idx" ON "life_events"("treeId", "personId"); + +-- CreateIndex +CREATE INDEX "life_events_treeId_unionId_idx" ON "life_events"("treeId", "unionId"); + +-- AddForeignKey +ALTER TABLE "life_events" ADD CONSTRAINT "life_events_treeId_fkey" FOREIGN KEY ("treeId") REFERENCES "trees"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 3176006..43660a1 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -78,21 +78,21 @@ enum SharedAccessRole { } model User { - id String @id @default(cuid()) - email String @unique - passwordHash String - lastOpenedTreeId String? - lastOpenedAccessMode String? - lastOpenedRole String? - lastOpenedAt DateTime? - createdAt DateTime @default(now()) - ownedTrees Tree[] @relation("TreeOwner") - memberships TreeMembership[] - sharedTreeAccesses UserTreeAccess[] + id String @id @default(cuid()) + email String @unique + passwordHash String + lastOpenedTreeId String? + lastOpenedAccessMode String? + lastOpenedRole String? + lastOpenedAt DateTime? + createdAt DateTime @default(now()) + ownedTrees Tree[] @relation("TreeOwner") + memberships TreeMembership[] + sharedTreeAccesses UserTreeAccess[] submittedContributionSessions ContributionSession[] @relation("ContributionSubmittedBy") - reviewedContributionSessions ContributionSession[] @relation("ContributionReviewedBy") - treeVisits TreeVisit[] - lastOpenedTree Tree? @relation("UserLastOpenedTree", fields: [lastOpenedTreeId], references: [id], onDelete: SetNull) + reviewedContributionSessions ContributionSession[] @relation("ContributionReviewedBy") + treeVisits TreeVisit[] + lastOpenedTree Tree? @relation("UserLastOpenedTree", fields: [lastOpenedTreeId], references: [id], onDelete: SetNull) @@index([lastOpenedAt]) @@map("users") @@ -123,6 +123,7 @@ model Tree { auditLogs AuditLog[] annotations Annotation[] visits TreeVisit[] + lifeEvents LifeEvent[] lastOpenedByUsers User[] @relation("UserLastOpenedTree") @@index([ownerUserId]) @@ -151,14 +152,14 @@ model TreeSharePassword { } model TreeMembership { - id String @id @default(cuid()) + id String @id @default(cuid()) treeId String userId String role MembershipRole contributionModeOverride ContributionPolicy? - createdAt DateTime @default(now()) - tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) - user User @relation(fields: [userId], references: [id], onDelete: Cascade) + createdAt DateTime @default(now()) + tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) + user User @relation(fields: [userId], references: [id], onDelete: Cascade) @@unique([treeId, userId]) @@index([userId]) @@ -166,14 +167,14 @@ model TreeMembership { } model UserTreeAccess { - id String @id @default(cuid()) - treeId String - userId String - role SharedAccessRole - createdAt DateTime @default(now()) - updatedAt DateTime @default(now()) @updatedAt - tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) - user User @relation(fields: [userId], references: [id], onDelete: Cascade) + id String @id @default(cuid()) + treeId String + userId String + role SharedAccessRole + createdAt DateTime @default(now()) + updatedAt DateTime @default(now()) @updatedAt + tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) + user User @relation(fields: [userId], references: [id], onDelete: Cascade) @@unique([treeId, userId]) @@index([userId, updatedAt]) @@ -181,12 +182,12 @@ model UserTreeAccess { } model TreeSettings { - treeId String @id - memberContributionPolicy ContributionPolicy @default(pending) - visitorPolicy VisitorPolicy @default(read_only) - contributorPolicy ContributionPolicy @default(pending) - updatedAt DateTime @updatedAt - tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) + treeId String @id + memberContributionPolicy ContributionPolicy @default(pending) + visitorPolicy VisitorPolicy @default(read_only) + contributorPolicy ContributionPolicy @default(pending) + updatedAt DateTime @updatedAt + tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) @@map("tree_settings") } @@ -205,89 +206,98 @@ model TreeImmichConfig { } model Person { - id String @id @default(cuid()) - treeId String - firstName String - lastName String - birthName String? - birthDate DateTime? - deathDate DateTime? - birthPlace String? - profession String? - region String? - nationality String? - avatarPath String? - avatarMimeType String? - sex String? - notes String? - createdBy String? - updatedBy String? + id String @id @default(cuid()) + treeId String + firstName String + lastName String + birthName String? + birthDate DateTime? + deathDate DateTime? + birthPlace String? + // Précision d'une date importée (« vers », « avant », « entre »…) et sa borne de fin pour « entre … et … » + birthDatePrecision String? + birthDateEnd DateTime? + deathDatePrecision String? + deathDateEnd DateTime? + deathPlace String? + nickname String? + profession String? + region String? + nationality String? + avatarPath String? + avatarMimeType String? + sex String? + notes String? + createdBy String? + updatedBy String? // Personne Immich associée (reconnaissance des visages) : identifiant côté Immich, ou null. - immichPersonId String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - deletedAt DateTime? - tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) + immichPersonId String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + deletedAt DateTime? + tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) @@index([treeId]) @@map("persons") } model Union { - id String @id @default(cuid()) - treeId String - partner1PersonId String - partner2PersonId String? - unionType String? - startDate DateTime? - endDate DateTime? - displayOrder Int @default(1) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - deletedAt DateTime? - tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) + id String @id @default(cuid()) + treeId String + partner1PersonId String + partner2PersonId String? + unionType String? + startDate DateTime? + endDate DateTime? + displayOrder Int @default(1) + startPlace String? + startDatePrecision String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + deletedAt DateTime? + tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) @@index([treeId]) @@map("unions") } model ParentChildLink { - id String @id @default(cuid()) - treeId String + id String @id @default(cuid()) + treeId String parentPersonId String - childPersonId String - viaUnionId String? - parentageType String? - displayOrder Int @default(1) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - deletedAt DateTime? - tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) + childPersonId String + viaUnionId String? + parentageType String? + displayOrder Int @default(1) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + deletedAt DateTime? + tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) @@index([treeId]) @@map("parent_child_links") } model MediaItem { - id String @id @default(cuid()) - treeId String - personId String - type String - mimeType String - filePath String - thumbPath String? - caption String? - source String? - sizeBytes Int - displayOrder Int @default(1) - isFeatured Boolean @default(false) - uploadedBy String? - status MediaStatus @default(approved) + id String @id @default(cuid()) + treeId String + personId String + type String + mimeType String + filePath String + thumbPath String? + caption String? + source String? + sizeBytes Int + displayOrder Int @default(1) + isFeatured Boolean @default(false) + uploadedBy String? + status MediaStatus @default(approved) contributionSessionId String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - deletedAt DateTime? - tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + deletedAt DateTime? + tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) @@index([treeId, personId, displayOrder]) @@map("media_items") @@ -316,17 +326,17 @@ model ContributionSession { } model ContributionChange { - id String @id @default(cuid()) - sessionId String - entityType ContributionEntityType - entityId String? - action ContributionAction - beforeJson Json? - afterJson Json? - conflictState ConflictState @default(none) - decision ContributionDecision? - createdAt DateTime @default(now()) - session ContributionSession @relation(fields: [sessionId], references: [id], onDelete: Cascade) + id String @id @default(cuid()) + sessionId String + entityType ContributionEntityType + entityId String? + action ContributionAction + beforeJson Json? + afterJson Json? + conflictState ConflictState @default(none) + decision ContributionDecision? + createdAt DateTime @default(now()) + session ContributionSession @relation(fields: [sessionId], references: [id], onDelete: Cascade) @@index([sessionId]) @@map("contribution_changes") @@ -352,16 +362,16 @@ model Annotation { } model AuditLog { - id String @id @default(cuid()) - treeId String - actorType String - actorId String? - action String - entityType String - entityId String + id String @id @default(cuid()) + treeId String + actorType String + actorId String? + action String + entityType String + entityId String payloadJson Json? - createdAt DateTime @default(now()) - tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) + createdAt DateTime @default(now()) + tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) @@index([treeId, createdAt]) @@map("audit_log") @@ -395,3 +405,33 @@ model WaitlistEntry { @@map("waitlist_entries") } + +// Événements de vie d'une personne (baptême, résidence, métier, études, service militaire, inhumation…) ou +// d'un couple (divorce…). Naissance, décès et mariage gardent leur date et leur lieu sur la personne ou +// l'union ; leur ligne ici ne porte que les sources et les notes (type birth, death, marriage). +model LifeEvent { + id String @id @default(cuid()) + treeId String + personId String? + unionId String? + type String + label String? + date DateTime? + dateEnd DateTime? + datePrecision String? + dateText String? + place String? + description String? + notes String? + sources String? + displayOrder Int @default(1) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + deletedAt DateTime? + tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) + + @@index([treeId]) + @@index([treeId, personId]) + @@index([treeId, unionId]) + @@map("life_events") +} diff --git a/backend/src/lib/gedcom-events.ts b/backend/src/lib/gedcom-events.ts new file mode 100644 index 0000000..c5cf8fe --- /dev/null +++ b/backend/src/lib/gedcom-events.ts @@ -0,0 +1,189 @@ +// Événements de vie lus dans un GEDCOM. Naissance, décès et mariage gardent leur date et leur lieu sur la +// personne ou l'union : on n'en tire ici que la précision, le lieu de décès, les sources et les notes. +// Les autres événements (baptême, résidence, métier, inhumation, divorce…) deviennent des LifeEvent. + +import { parseGedcomDate } from './gedcom-dates.js' +import { joinedText, noteText, sourceLabel } from './gedcom-photos.js' +import type { GedcomPhotoNode, GedcomRecords } from './gedcom-photos.js' + +type Node = GedcomPhotoNode + +export type ImportedEvent = { + type: string + label: string | null + date: Date | null + dateEnd: Date | null + datePrecision: string | null + dateText: string | null + place: string | null + description: string | null + notes: string | null + sources: string | null +} + +// Balises de la norme et variantes courantes (Gramps, Heredis, Geneatique, RootsMagic) +export const PERSON_EVENT_TYPES: Record = { + BAPM: 'baptism', CHR: 'baptism', BURI: 'burial', CREM: 'cremation', RESI: 'residence', OCCU: 'occupation', + EDUC: 'education', GRAD: 'graduation', RELI: 'religion', CONF: 'confirmation', FCOM: 'first_communion', + BARM: 'bar_mitzvah', BASM: 'bat_mitzvah', ORDN: 'ordination', ADOP: 'adoption', EMIG: 'emigration', + IMMI: 'immigration', NATU: 'naturalization', CENS: 'census', TITL: 'title', PROP: 'property', + RETI: 'retirement', WILL: 'will', PROB: 'probate', _MILT: 'military', _MDCL: 'medical', _DEG: 'degree', + EVEN: 'custom', FACT: 'custom', +} + +export const FAMILY_EVENT_TYPES: Record = { + DIV: 'divorce', DIVF: 'divorce_filed', ANUL: 'annulment', ENGA: 'engagement', MARB: 'marriage_banns', + MARC: 'marriage_contract', MARL: 'marriage_license', MARS: 'marriage_settlement', EVEN: 'custom', FACT: 'custom', +} + +const MAX_EVENTS_PER_OWNER = 200 +const clip = (value: string | null | undefined, max: number) => { + const text = (value ?? '').replace(/\s+\n/g, '\n').trim() + if (!text) return null + return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text +} + +const child = (node: Node | undefined, tag: string) => node?.children.find((c) => c.tag === tag) + +// Même règle que le lieu de naissance : noms seulement, sans case vide ni code INSEE ou postal +export function cleanPlace(value: string | null | undefined): string | null { + if (!value) return null + const parts: string[] = [] + for (const raw of value.split(',')) { + const part = raw.trim() + if (!part || /^(\d{4,5}|2[AB]\d{3})$/i.test(part)) continue + if (parts.length && parts[parts.length - 1].toLowerCase() === part.toLowerCase()) continue + parts.push(part) + } + return parts.length ? parts.join(', ') : null +} + +export function isoToDbDate(iso: string | null | undefined): Date | null { + if (!iso) return null + if (/^\d{4}$/.test(iso)) return new Date(`${iso}-01-01T00:00:00.000Z`) + if (/^\d{4}-\d{2}$/.test(iso)) return new Date(`${iso}-01T00:00:00.000Z`) + return new Date(`${iso}T00:00:00.000Z`) +} + +function eventNotes(node: Node, records: GedcomRecords): string | null { + const texts = node.children.filter((c) => c.tag === 'NOTE').map((n) => noteText(n, records)).filter(Boolean) + return clip(texts.join('\n\n'), 4000) +} + +function eventSources(node: Node, records: GedcomRecords): string | null { + const labels = node.children.filter((c) => c.tag === 'SOUR').map((s) => sourceLabel(s, records)).filter(Boolean) as string[] + return clip([...new Set(labels)].join('\n'), 4000) +} + +// Ce qu'on lit d'un événement : date et précision, lieu (ou adresse), description, notes, sources +export function readEvent(node: Node, type: string, records: GedcomRecords): ImportedEvent { + const dateText = child(node, 'DATE')?.value ?? null + const parsed = parseGedcomDate(dateText) + const addr = child(node, 'ADDR') + const address = [joinedText(addr).replace(/\n+/g, ', '), ...['CITY', 'STAE', 'CTRY'].map((tag) => child(addr, tag)?.value ?? '')] + .map((part) => part.trim()) + .filter(Boolean) + .join(', ') + const place = cleanPlace(child(node, 'PLAC')?.value) ?? clip(address, 300) + const typeLabel = joinedText(child(node, 'TYPE')) + const value = node.value && node.value.toUpperCase() !== 'Y' ? node.value : '' + return { + type, + label: type === 'custom' ? clip(typeLabel || value, 120) : null, + date: isoToDbDate(parsed?.iso), + dateEnd: isoToDbDate(parsed?.endIso), + datePrecision: parsed && parsed.precision !== 'exact' ? parsed.precision : null, + dateText: parsed && parsed.precision === 'exact' ? null : clip(dateText, 120), + place: clip(place, 300), + description: clip(type === 'custom' && !typeLabel ? '' : value, 1000), + notes: eventNotes(node, records), + sources: eventSources(node, records), + } +} + +export type PersonExtras = { + birthDatePrecision: string | null + birthDateEnd: Date | null + deathDatePrecision: string | null + deathDateEnd: Date | null + deathPlace: string | null + nickname: string | null + events: ImportedEvent[] +} + +const hasDetails = (e: ImportedEvent) => Boolean(e.notes || e.sources) + +export function personExtras(indi: Node, records: GedcomRecords): PersonExtras { + const events: ImportedEvent[] = [] + const birth = child(indi, 'BIRT') + const death = child(indi, 'DEAT') + const birthDate = parseGedcomDate(child(birth, 'DATE')?.value) + const deathDate = parseGedcomDate(child(death, 'DATE')?.value) + + // Naissance et décès : leurs sources et notes, sans recopier la date ni le lieu + for (const [node, type] of [[birth, 'birth'], [death, 'death']] as const) { + if (!node) continue + const event = readEvent(node, type, records) + if (hasDetails(event)) events.push({ ...event, date: null, dateEnd: null, datePrecision: null, dateText: null, place: null, description: null }) + } + + // La première profession reste aussi sur la fiche (champ « profession ») et figure quand même ici + for (const c of indi.children) { + const type = PERSON_EVENT_TYPES[c.tag] + if (!type || events.length >= MAX_EVENTS_PER_OWNER) continue + const event = readEvent(c, type, records) + if (!event.date && !event.place && !event.description && !event.label && !hasDetails(event)) continue + events.push(event) + } + + const nameNode = child(indi, 'NAME') + return { + birthDatePrecision: birthDate && birthDate.precision !== 'exact' ? birthDate.precision : null, + birthDateEnd: isoToDbDate(birthDate?.endIso), + deathDatePrecision: deathDate && deathDate.precision !== 'exact' ? deathDate.precision : null, + deathDateEnd: isoToDbDate(deathDate?.endIso), + deathPlace: clip(cleanPlace(child(death, 'PLAC')?.value), 200), + nickname: clip(child(nameNode, 'NICK')?.value ?? child(indi, 'NICK')?.value, 120), + events, + } +} + +export type UnionExtras = { + startPlace: string | null + startDatePrecision: string | null + events: ImportedEvent[] +} + +export function familyExtras(fam: Node, records: GedcomRecords): UnionExtras { + const marriage = child(fam, 'MARR') + const date = parseGedcomDate(child(marriage, 'DATE')?.value) + const events: ImportedEvent[] = [] + if (marriage) { + const event = readEvent(marriage, 'marriage', records) + if (hasDetails(event)) events.push({ ...event, date: null, dateEnd: null, datePrecision: null, dateText: null, place: null, description: null }) + } + for (const c of fam.children) { + const type = FAMILY_EVENT_TYPES[c.tag] + if (!type || events.length >= MAX_EVENTS_PER_OWNER) continue + const event = readEvent(c, type, records) + // « 1 DIV Y » sans rien d'autre dit quand même qu'il y a eu divorce + if (!event.date && !event.place && !event.description && !event.label && !hasDetails(event) && c.value.toUpperCase() !== 'Y') continue + events.push(event) + } + return { + startPlace: clip(cleanPlace(child(marriage, 'PLAC')?.value), 300), + startDatePrecision: date && date.precision !== 'exact' ? date.precision : null, + events, + } +} + +// Adoption déclarée sous l'enfant : « 1 FAMC @F1@ » / « 2 PEDI adopted » +export function adoptedFamilies(indi: Node): Set { + const out = new Set() + for (const famc of indi.children.filter((c) => c.tag === 'FAMC')) { + const pedi = (child(famc, 'PEDI')?.value || '').toLowerCase() + const pointer = famc.value.match(/^@([^@]+)@$/)?.[1] + if (pointer && pedi === 'adopted') out.add(pointer) + } + return out +} diff --git a/backend/src/lib/gedcom-photos.ts b/backend/src/lib/gedcom-photos.ts index efb96af..d790a82 100644 --- a/backend/src/lib/gedcom-photos.ts +++ b/backend/src/lib/gedcom-photos.ts @@ -123,7 +123,7 @@ export function localMediaPath(value: string): string | null { return dot > 0 && MEDIA_EXTENSIONS.has(name.slice(dot + 1).toLowerCase()) ? path : null } -function joinedText(node: GedcomPhotoNode | undefined): string { +export function joinedText(node: GedcomPhotoNode | undefined): string { if (!node) return '' let text = node.rawValue ?? node.value for (const c of node.children) { @@ -148,7 +148,7 @@ export function plainNoteText(raw: string): string { return text.replace(/[ \t]+/g, ' ').replace(/\s*\n\s*/g, '\n').trim() } -function noteText(node: GedcomPhotoNode | undefined, records: GedcomRecords): string { +export function noteText(node: GedcomPhotoNode | undefined, records: GedcomRecords): string { if (!node) return '' const pointer = pointerOf(node.value) return plainNoteText(joinedText(pointer ? records.note.get(pointer) : node)) @@ -167,7 +167,7 @@ function baseNameWithoutExtension(path: string): string { } // Titre d'une source citée : son titre (ou son abréviation), puis la page ou le détail de la citation -function sourceLabel(citation: GedcomPhotoNode, records: GedcomRecords): string | null { +export function sourceLabel(citation: GedcomPhotoNode, records: GedcomRecords): string | null { const pointer = pointerOf(citation.value) const record = pointer ? records.sour.get(pointer) : null const title = joinedText(child(record ?? undefined, 'TITL')) || joinedText(child(record ?? undefined, 'ABBR')) || (pointer ? '' : citation.value) diff --git a/backend/src/routes/gedcom.ts b/backend/src/routes/gedcom.ts index 68f5842..cb73a6d 100644 --- a/backend/src/routes/gedcom.ts +++ b/backend/src/routes/gedcom.ts @@ -3,6 +3,7 @@ import { z } from 'zod' import { UPLOAD_BODY_LIMIT } from '../config/env.js' import { parseGedcomDate } from '../lib/gedcom-dates.js' +import { adoptedFamilies, familyExtras, personExtras } from '../lib/gedcom-events.js' import { indexGedcomRecords, mediaRefsForPerson, photoPathForPerson, plainNoteText } from '../lib/gedcom-photos.js' import type { GedcomRecords } from '../lib/gedcom-photos.js' import type { MembershipRole } from '../types/auth.js' @@ -528,6 +529,9 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => { let personsReused = 0 let unionsCreated = 0 let linksCreated = 0 + let eventsCreated = 0 + // Adoptions déclarées sous l'enfant (« 2 PEDI adopted ») : enfant → familles où il est adopté + const adoptedByChild = new Map(indiNodes.map((indi) => [indi.xref!, adoptedFamilies(indi)])) importInProgress = true try { @@ -567,6 +571,7 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => { continue } + const { events, ...extras } = personExtras(indi, records) const person = await tx.person.create({ data: { treeId, @@ -578,10 +583,15 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => { birthPlace, profession, notes, + ...extras, createdBy: actor.userId, updatedBy: actor.userId, }, }) + if (events.length) { + await tx.lifeEvent.createMany({ data: events.map((event, index) => ({ ...event, treeId, personId: person.id, displayOrder: index + 1 })) }) + eventsCreated += events.length + } xrefToPersonId.set(indi.xref!, person.id) personsCreated++ @@ -608,17 +618,23 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => { const secondPartner = partner1Id ? (partner2Id ?? null) : null let unionId = unionByPair.get(pairKey(firstPartner, secondPartner)) if (!unionId) { + const { events: familyEvents, ...unionExtras } = familyExtras(fam, records) const union = await tx.union.create({ data: { treeId, partner1PersonId: firstPartner, partner2PersonId: secondPartner, startDate: isoDateToDbDate(marriageDateIso), + ...unionExtras, }, }) unionId = union.id unionByPair.set(pairKey(firstPartner, secondPartner), unionId) unionsCreated++ + if (familyEvents.length) { + await tx.lifeEvent.createMany({ data: familyEvents.map((event, index) => ({ ...event, treeId, unionId: union.id, displayOrder: index + 1 })) }) + eventsCreated += familyEvents.length + } } const chilNodes = findAllChildren(fam, 'CHIL') @@ -643,6 +659,7 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => { parentPersonId: parentId, childPersonId: childId, viaUnionId: unionId, + ...(adoptedByChild.get(chilXref)?.has(fam.xref!) ? { parentageType: 'adoption' } : {}), displayOrder: await nextSiblingOrder(tx, treeId, parentId), }, }) @@ -660,7 +677,7 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => { action: 'gedcom_imported', entityType: 'tree', entityId: treeId, - payloadJson: { personsCreated, personsReused, unionsCreated, linksCreated, photoRefs: photoRefs.length, mediaRefs: mediaRefs.length }, + payloadJson: { personsCreated, personsReused, unionsCreated, linksCreated, eventsCreated, photoRefs: photoRefs.length, mediaRefs: mediaRefs.length }, }, }) }, { timeout: 60000 }) @@ -670,6 +687,6 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => { // photoRefs : chemin de la photo que le logiciel d'origine associait à chaque personne ; mediaRefs : les // autres fichiers cités, avec leur titre et leur source (rien n'est gardé en base) - return reply.send({ personsCreated, personsReused, unionsCreated, linksCreated, photoRefs, mediaRefs }) + return reply.send({ personsCreated, personsReused, unionsCreated, linksCreated, eventsCreated, photoRefs, mediaRefs }) }) } diff --git a/backend/test/gedcom-events.test.ts b/backend/test/gedcom-events.test.ts new file mode 100644 index 0000000..0d9f11a --- /dev/null +++ b/backend/test/gedcom-events.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from 'vitest' + +import { adoptedFamilies, familyExtras, personExtras } from '../src/lib/gedcom-events' +import { indexGedcomRecords } from '../src/lib/gedcom-photos' +import { parseGedcom } from '../src/routes/gedcom' + +const text = [ + '0 @I1@ INDI', + '1 NAME Louis /RAGOT/', + '2 NICK Loulou', + '1 BIRT', + '2 DATE ABT 1879', + '2 PLAC La Roche-sur-Yon,85191,Vendée,Pays de la Loire,France,', + '2 SOUR @S1@', + '3 PAGE Acte n° 12', + '1 BAPM', + '2 DATE 9 MAR 1879', + '2 PLAC La Roche-sur-Yon,85191,Vendée,,France,', + '1 OCCU Instituteur', + '2 DATE FROM 1900 TO 1935', + '2 PLAC Limoges', + '1 OCCU Maire', + '2 DATE 1936', + '1 RESI', + '2 ADDR 12 rue des Écoles', + '3 CITY Limoges', + '1 EVEN', + '2 TYPE Militaire', + '2 DATE BET 1914 AND 1918', + '2 NOTE Blessé à Verdun.', + '1 DEAT', + '2 DATE @#DFRENCH R@ 18 BRUM 8', + '2 PLAC Nantes,44109,Loire-Atlantique,Pays de la Loire,France,', + '1 BURI', + '2 PLAC Cimetière de Miséricorde, Nantes', + '1 FAMC @F0@', + '2 PEDI adopted', + '1 FAMC @F9@', + '0 @F1@ FAM', + '1 HUSB @I1@', + '1 MARR', + '2 DATE EST 1905', + '2 PLAC Limoges,87085,Haute-Vienne,Nouvelle-Aquitaine,France,', + '2 SOUR Registre des mariages de Limoges', + '1 DIV Y', + '0 @S1@ SOUR', + '1 TITL Registre des naissances', +].join('\n') + +const roots = parseGedcom(text) +const records = indexGedcomRecords(roots) +const indi = roots.find((n) => n.tag === 'INDI')! +const fam = roots.find((n) => n.tag === 'FAM')! + +describe('événements de vie d’une personne', () => { + const extras = personExtras(indi as never, records) + const byType = (type: string) => extras.events.filter((e) => e.type === type) + + it('précision des dates, lieu de décès, surnom', () => { + expect(extras.birthDatePrecision).toBe('about') + expect(extras.deathDatePrecision).toBeNull() + expect(extras.deathPlace).toBe('Nantes, Loire-Atlantique, Pays de la Loire, France') + expect(extras.nickname).toBe('Loulou') + }) + + it('naissance : seulement ses sources, sans recopier la date ni le lieu', () => { + expect(byType('birth')).toEqual([expect.objectContaining({ sources: 'Registre des naissances, Acte n° 12', date: null, place: null })]) + }) + + it('baptême, métiers successifs, résidence, inhumation', () => { + expect(byType('baptism')[0]).toMatchObject({ place: 'La Roche-sur-Yon, Vendée, France', datePrecision: null }) + expect(byType('baptism')[0].date?.toISOString().slice(0, 10)).toBe('1879-03-09') + expect(byType('occupation').map((e) => e.description)).toEqual(['Instituteur', 'Maire']) + expect(byType('occupation')[0]).toMatchObject({ datePrecision: 'from', dateText: 'FROM 1900 TO 1935', place: 'Limoges' }) + expect(byType('occupation')[0].dateEnd?.getUTCFullYear()).toBe(1935) + expect(byType('residence')[0].place).toBe('12 rue des Écoles, Limoges') + expect(byType('burial')[0].place).toBe('Cimetière de Miséricorde, Nantes') + }) + + it('événement libre (Heredis « Militaire ») avec sa note', () => { + expect(byType('custom')[0]).toMatchObject({ label: 'Militaire', datePrecision: 'between', notes: 'Blessé à Verdun.' }) + }) + + it('adoption déclarée par PEDI', () => { + expect([...adoptedFamilies(indi as never)]).toEqual(['F0']) + }) +}) + +describe('événements d’un couple', () => { + const extras = familyExtras(fam as never, records) + + it('lieu et précision du mariage, sources du mariage, divorce', () => { + expect(extras.startPlace).toBe('Limoges, Haute-Vienne, Nouvelle-Aquitaine, France') + expect(extras.startDatePrecision).toBe('estimated') + expect(extras.events.map((e) => e.type)).toEqual(['marriage', 'divorce']) + expect(extras.events[0]).toMatchObject({ sources: 'Registre des mariages de Limoges', place: null }) + }) +}) From 87c564fd3ce0649a918d37cbdea0de44434e611a Mon Sep 17 00:00:00 2001 From: IliesAllali Date: Fri, 16 Oct 2026 22:20:30 +0200 Subject: [PATCH 2/4] API : frise de vie d'une personne MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET /trees/:id/persons/:personId/life rend la précision des dates, le lieu de décès, le surnom, les unions avec leur lieu de mariage, et les événements de la personne et de ses couples. Chargée à l'ouverture de la fiche, pas dans le graphe. Les droits de lecture du graphe sont factorisés (resolveReadAccess) et servent aux deux. Supprimer une personne supprime aussi ses événements et ceux de ses unions. Co-Authored-By: Claude Opus 5.5 --- backend/src/lib/entity-deletion.ts | 9 + backend/src/routes/graph.ts | 201 ++++++++++++------ backend/test/api-routes.test.ts | 48 +++++ backend/test/api-security.integration.test.ts | 5 + backend/test/e2e-journeys.test.ts | 5 + 5 files changed, 208 insertions(+), 60 deletions(-) diff --git a/backend/src/lib/entity-deletion.ts b/backend/src/lib/entity-deletion.ts index eb41427..2078dee 100644 --- a/backend/src/lib/entity-deletion.ts +++ b/backend/src/lib/entity-deletion.ts @@ -72,6 +72,15 @@ export async function softDeletePersonCascade( where: { treeId, personId, deletedAt: null }, data: { deletedAt: now }, }), + // Événements de vie de la personne et de ses unions + db.lifeEvent.updateMany({ + where: { + treeId, + deletedAt: null, + OR: [{ personId }, ...(unionIds.length > 0 ? [{ unionId: { in: unionIds } }] : [])], + }, + data: { deletedAt: now }, + }), ]) // Racine de l'arbre supprimée : le graphe repart sans racine plutôt que sur une personne effacée diff --git a/backend/src/routes/graph.ts b/backend/src/routes/graph.ts index 79824ce..a4c9e2e 100644 --- a/backend/src/routes/graph.ts +++ b/backend/src/routes/graph.ts @@ -1,4 +1,4 @@ -import type { FastifyPluginAsync } from 'fastify' +import type { FastifyInstance, FastifyPluginAsync, FastifyRequest } from 'fastify' import { z } from 'zod' import { signMediaToken } from '../lib/tree-access.js' @@ -9,47 +9,65 @@ const treeIdParamSchema = z.object({ id: z.string().min(1), }) -export const graphRoutes: FastifyPluginAsync = async (app) => { - app.get('/trees/:id/graph', async (request, reply) => { - const params = treeIdParamSchema.safeParse(request.params) - if (!params.success) { - return reply.code(400).send({ error: 'invalid_tree_id' }) +type ReadAccess = + | { ok: true; rootPersonId: string | null; visitKind: VisitAccessKind } + | { ok: false; status: number; error: string } + +// Qui peut lire un arbre : un accès par mot de passe de cet arbre, un membre, ou un compte avec qui il est +// partagé. Utilisé par le graphe et par la frise de vie d'une personne. +async function resolveReadAccess(app: FastifyInstance, actor: FastifyRequest['actor'], treeId: string): Promise { + let rootPersonId: string | null = null + let visitKind: VisitAccessKind = 'share' + if (!actor) { + return { ok: false, status: 401, error: 'authentication_required' } + } + + if (actor.kind === 'tree_access') { + if (actor.treeId !== treeId) { + return { ok: false, status: 403, error: 'forbidden' } } - const treeId = params.data.id - const actor = request.actor - let rootPersonId: string | null = null - let visitKind: VisitAccessKind = 'share' + const tree = await app.prisma.tree.findFirst({ + where: { + id: treeId, + deletedAt: null, + }, + select: { + id: true, + rootPersonId: true, + }, + }) - if (!actor) { - return reply.code(401).send({ error: 'authentication_required' }) + if (!tree) { + return { ok: false, status: 404, error: 'tree_not_found' } } - if (actor.kind === 'tree_access') { - if (actor.treeId !== treeId) { - return reply.code(403).send({ error: 'forbidden' }) - } + rootPersonId = tree.rootPersonId + } - const tree = await app.prisma.tree.findFirst({ - where: { - id: treeId, - deletedAt: null, + if (actor.kind === 'user') { + const membership = await app.prisma.treeMembership.findUnique({ + where: { + treeId_userId: { + treeId, + userId: actor.userId, }, - select: { - id: true, - rootPersonId: true, + }, + include: { + tree: { + select: { + deletedAt: true, + rootPersonId: true, + }, }, - }) + }, + }) - if (!tree) { - return reply.code(404).send({ error: 'tree_not_found' }) - } - - rootPersonId = tree.rootPersonId - } - - if (actor.kind === 'user') { - const membership = await app.prisma.treeMembership.findUnique({ + if (membership && !membership.tree.deletedAt) { + rootPersonId = membership.tree.rootPersonId + visitKind = 'member' + } else { + const shared = await app.prisma.userTreeAccess.findUnique({ where: { treeId_userId: { treeId, @@ -66,35 +84,37 @@ export const graphRoutes: FastifyPluginAsync = async (app) => { }, }) - if (membership && !membership.tree.deletedAt) { - rootPersonId = membership.tree.rootPersonId - visitKind = 'member' - } else { - const shared = await app.prisma.userTreeAccess.findUnique({ - where: { - treeId_userId: { - treeId, - userId: actor.userId, - }, - }, - include: { - tree: { - select: { - deletedAt: true, - rootPersonId: true, - }, - }, - }, - }) - - if (!shared || shared.tree.deletedAt) { - return reply.code(403).send({ error: 'forbidden' }) - } - - rootPersonId = shared.tree.rootPersonId - visitKind = 'shared_account' + if (!shared || shared.tree.deletedAt) { + return { ok: false, status: 403, error: 'forbidden' } } + + rootPersonId = shared.tree.rootPersonId + visitKind = 'shared_account' } + } + + return { ok: true, rootPersonId, visitKind } +} + +export const graphRoutes: FastifyPluginAsync = async (app) => { + app.get('/trees/:id/graph', async (request, reply) => { + const params = treeIdParamSchema.safeParse(request.params) + if (!params.success) { + return reply.code(400).send({ error: 'invalid_tree_id' }) + } + + const treeId = params.data.id + const actor = request.actor + let rootPersonId: string | null = null + let visitKind: VisitAccessKind = 'share' + + const access = await resolveReadAccess(app, actor, treeId) + if (!access.ok || !actor) { + if (access.ok) return reply.code(401).send({ error: 'authentication_required' }) + return reply.code(access.status).send({ error: access.error }) + } + rootPersonId = access.rootPersonId + visitKind = access.visitKind // Journal des visites (onglet Visites des administrateurs), sans attendre void recordTreeVisit(app, request, treeId, visitKind, actor.kind === 'user' ? actor.userId : null) @@ -148,4 +168,65 @@ export const graphRoutes: FastifyPluginAsync = async (app) => { mediaToken: signMediaToken(app, treeId, actor), }) }) + + // Frise de vie d'une personne : chargée à l'ouverture de la fiche plutôt que dans le graphe, qui resterait + // lourd sur un grand arbre. Mêmes droits de lecture que le graphe. + app.get('/trees/:id/persons/:personId/life', async (request, reply) => { + const params = z.object({ id: z.string().min(1), personId: z.string().min(1) }).safeParse(request.params) + if (!params.success) { + return reply.code(400).send({ error: 'invalid_params' }) + } + const { id: treeId, personId } = params.data + const access = await resolveReadAccess(app, request.actor, treeId) + if (!access.ok) { + return reply.code(access.status).send({ error: access.error }) + } + + const person = await app.prisma.person.findFirst({ + where: { id: personId, treeId, deletedAt: null }, + select: { + id: true, birthDatePrecision: true, birthDateEnd: true, deathDatePrecision: true, deathDateEnd: true, + deathPlace: true, nickname: true, + }, + }) + if (!person) { + return reply.code(404).send({ error: 'person_not_found' }) + } + + const unions = await app.prisma.union.findMany({ + where: { treeId, deletedAt: null, OR: [{ partner1PersonId: personId }, { partner2PersonId: personId }] }, + select: { id: true, partner1PersonId: true, partner2PersonId: true, startDate: true, startPlace: true, startDatePrecision: true, endDate: true }, + orderBy: [{ displayOrder: 'asc' }, { createdAt: 'asc' }], + }) + const unionIds = unions.map((union) => union.id) + const events = await app.prisma.lifeEvent.findMany({ + where: { treeId, deletedAt: null, OR: [{ personId }, ...(unionIds.length ? [{ unionId: { in: unionIds } }] : [])] }, + select: { + id: true, personId: true, unionId: true, type: true, label: true, date: true, dateEnd: true, datePrecision: true, + dateText: true, place: true, description: true, notes: true, sources: true, displayOrder: true, + }, + orderBy: [{ date: 'asc' }, { displayOrder: 'asc' }, { createdAt: 'asc' }], + }) + + const day = (value: Date | null) => (value ? value.toISOString().slice(0, 10) : null) + return reply.send({ + person: { + birthDatePrecision: person.birthDatePrecision, + birthDateEnd: day(person.birthDateEnd), + deathDatePrecision: person.deathDatePrecision, + deathDateEnd: day(person.deathDateEnd), + deathPlace: person.deathPlace, + nickname: person.nickname, + }, + unions: unions.map((union) => ({ + id: union.id, + partnerId: union.partner1PersonId === personId ? union.partner2PersonId : union.partner1PersonId, + startDate: day(union.startDate), + startPlace: union.startPlace, + startDatePrecision: union.startDatePrecision, + endDate: day(union.endDate), + })), + events: events.map((event) => ({ ...event, date: day(event.date), dateEnd: day(event.dateEnd) })), + }) + }) } diff --git a/backend/test/api-routes.test.ts b/backend/test/api-routes.test.ts index 38f076b..d8e2d0c 100644 --- a/backend/test/api-routes.test.ts +++ b/backend/test/api-routes.test.ts @@ -67,6 +67,11 @@ const { prismaMock } = vi.hoisted(() => ({ update: vi.fn(), updateMany: vi.fn(), }, + lifeEvent: { + findMany: vi.fn().mockResolvedValue([]), + createMany: vi.fn().mockResolvedValue({ count: 0 }), + updateMany: vi.fn().mockResolvedValue({ count: 0 }), + }, annotation: { findMany: vi.fn(), }, @@ -419,6 +424,49 @@ describe('Graph routes', () => { await app.close() }) + it('frise de vie : lisible avec un accès à l’arbre, refusée pour un autre arbre, 404 pour une personne inconnue', async () => { + const app = createApp() + await app.ready() + const sign = (treeId: string) => (app as any).jwt.sign({ + kind: 'tree_access', + sub: `tree:${treeId}:visitor`, + treeId, + role: 'visitor', + accessVersion: new Date('2026-02-11T10:00:00.000Z').getTime(), + }) + + prismaMock.tree.findFirst.mockResolvedValue({ id: 'tree-1', rootPersonId: null }) + prismaMock.person.findFirst.mockResolvedValue({ + id: 'p-1', birthDatePrecision: 'about', birthDateEnd: null, deathDatePrecision: null, deathDateEnd: null, + deathPlace: 'Nantes, France', nickname: 'Loulou', + }) + prismaMock.union.findMany.mockResolvedValue([ + { id: 'u-1', partner1PersonId: 'p-1', partner2PersonId: 'p-2', startDate: new Date('1905-01-01T00:00:00Z'), startPlace: 'Limoges', startDatePrecision: 'estimated', endDate: null }, + ]) + prismaMock.lifeEvent.findMany.mockResolvedValue([ + { id: 'e-1', personId: 'p-1', unionId: null, type: 'baptism', label: null, date: new Date('1879-03-09T00:00:00Z'), dateEnd: null, datePrecision: null, dateText: null, place: 'La Roche-sur-Yon', description: null, notes: null, sources: 'Registre', displayOrder: 1 }, + ]) + + const ok = await app.inject({ method: 'GET', url: '/trees/tree-1/persons/p-1/life', headers: { authorization: `Bearer ${sign('tree-1')}` } }) + expect(ok.statusCode).toBe(200) + expect(ok.json()).toMatchObject({ + person: { birthDatePrecision: 'about', deathPlace: 'Nantes, France', nickname: 'Loulou' }, + unions: [{ id: 'u-1', partnerId: 'p-2', startDate: '1905-01-01', startPlace: 'Limoges', startDatePrecision: 'estimated' }], + events: [{ id: 'e-1', type: 'baptism', date: '1879-03-09', place: 'La Roche-sur-Yon', sources: 'Registre' }], + }) + + const other = await app.inject({ method: 'GET', url: '/trees/tree-1/persons/p-1/life', headers: { authorization: `Bearer ${sign('tree-2')}` } }) + expect(other.statusCode).toBe(403) + + prismaMock.person.findFirst.mockResolvedValue(null) + const missing = await app.inject({ method: 'GET', url: '/trees/tree-1/persons/p-404/life', headers: { authorization: `Bearer ${sign('tree-1')}` } }) + expect(missing.statusCode).toBe(404) + + const anonymous = await app.inject({ method: 'GET', url: '/trees/tree-1/persons/p-1/life' }) + expect(anonymous.statusCode).toBe(401) + await app.close() + }) + it('allows tree access token to fetch graph', async () => { const app = createApp() await app.ready() diff --git a/backend/test/api-security.integration.test.ts b/backend/test/api-security.integration.test.ts index 39c3cd3..98fb729 100644 --- a/backend/test/api-security.integration.test.ts +++ b/backend/test/api-security.integration.test.ts @@ -72,6 +72,11 @@ const { prismaMock } = vi.hoisted(() => ({ update: vi.fn(), updateMany: vi.fn(), }, + lifeEvent: { + findMany: vi.fn().mockResolvedValue([]), + createMany: vi.fn().mockResolvedValue({ count: 0 }), + updateMany: vi.fn().mockResolvedValue({ count: 0 }), + }, annotation: { findMany: vi.fn(), }, diff --git a/backend/test/e2e-journeys.test.ts b/backend/test/e2e-journeys.test.ts index ce3c47e..f09bdb6 100644 --- a/backend/test/e2e-journeys.test.ts +++ b/backend/test/e2e-journeys.test.ts @@ -77,6 +77,11 @@ const { prismaMock } = vi.hoisted(() => ({ update: vi.fn(), updateMany: vi.fn(), }, + lifeEvent: { + findMany: vi.fn().mockResolvedValue([]), + createMany: vi.fn().mockResolvedValue({ count: 0 }), + updateMany: vi.fn().mockResolvedValue({ count: 0 }), + }, annotation: { findMany: vi.fn(), }, From f6affa81d6e74eb3514cca406c24e6f23507c144 Mon Sep 17 00:00:00 2001 From: IliesAllali Date: Fri, 16 Oct 2026 22:27:51 +0200 Subject: [PATCH 3/4] feat(gedcom): export des evenements de vie, precisions de date, sources et adoption L'export rend ce que l'import lit : dates qualifiees (ABT, EST, BET ... AND, FROM ... TO) ou texte d'origine, lieu de deces, surnom, tous les evenements de la personne et du couple avec lieu, notes et sources, lieu du mariage, PEDI adopted. Test aller-retour. Co-Authored-By: Claude Opus 5.5 --- backend/src/routes/gedcom.ts | 134 +++++++++++++++++++++++++++++--- backend/test/api-routes.test.ts | 62 +++++++++++++++ 2 files changed, 185 insertions(+), 11 deletions(-) diff --git a/backend/src/routes/gedcom.ts b/backend/src/routes/gedcom.ts index cb73a6d..0b47349 100644 --- a/backend/src/routes/gedcom.ts +++ b/backend/src/routes/gedcom.ts @@ -3,7 +3,7 @@ import { z } from 'zod' import { UPLOAD_BODY_LIMIT } from '../config/env.js' import { parseGedcomDate } from '../lib/gedcom-dates.js' -import { adoptedFamilies, familyExtras, personExtras } from '../lib/gedcom-events.js' +import { adoptedFamilies, FAMILY_EVENT_TYPES, familyExtras, PERSON_EVENT_TYPES, personExtras } from '../lib/gedcom-events.js' import { indexGedcomRecords, mediaRefsForPerson, photoPathForPerson, plainNoteText } from '../lib/gedcom-photos.js' import type { GedcomRecords } from '../lib/gedcom-photos.js' import type { MembershipRole } from '../types/auth.js' @@ -180,6 +180,82 @@ function isoToGedcomDate(value: string | Date | null): string | null { return null } +// Date avec sa précision (ABT 1879, BET 1914 AND 1918…). Une date exacte reste telle quelle. +const PRECISION_PREFIX: Record = { + about: 'ABT', estimated: 'EST', calculated: 'CAL', before: 'BEF', after: 'AFT', interpreted: 'INT', +} + +// Une date tronquée au 1er janvier vient d'une année seule : on la réécrit comme une année +function exportedDate(value: Date | null): string | null { + if (!value) return null + const iso = value.toISOString().slice(0, 10) + return isoToGedcomDate(iso.endsWith('-01-01') ? iso.slice(0, 4) : iso) +} + +function qualifiedGedcomDate(start: Date | null, end: Date | null, precision: string | null, text?: string | null): string | null { + // Le texte d'origine (calendrier républicain, julien, période) prime : on le rend tel qu'il a été lu + if (text && precision) return oneLine(text) + const from = exportedDate(start) + const to = exportedDate(end) + if (!from) return text ? oneLine(text) : null + if (!precision || precision === 'exact') return from + if (precision === 'between') return to ? `BET ${from} AND ${to}` : `AFT ${from}` + if (precision === 'from') return to ? `FROM ${from} TO ${to}` : `FROM ${from}` + if (precision === 'to') return `TO ${from}` + const prefix = PRECISION_PREFIX[precision] + return prefix ? `${prefix} ${from}` : from +} + +type ExportedEvent = { + type: string + label: string | null + date: Date | null + dateEnd: Date | null + datePrecision: string | null + dateText: string | null + place: string | null + description: string | null + notes: string | null + sources: string | null +} + +// Balise GEDCOM de chaque type : la première rencontrée dans la table de lecture (BAPM avant CHR) +const reverseTags = (table: Record) => { + const out: Record = {} + for (const [tag, type] of Object.entries(table)) if (!out[type]) out[type] = tag + return out +} +const PERSON_EVENT_TAGS = reverseTags(PERSON_EVENT_TYPES) +const FAMILY_EVENT_TAGS = reverseTags(FAMILY_EVENT_TYPES) + +function pushMultiline(lines: string[], level: number, tag: string, text: string) { + const [first, ...rest] = text.split(/\r\n|\r|\n/) + lines.push(`${level} ${tag} ${first}`.trimEnd()) + for (const line of rest) lines.push(`${level + 1} CONT ${line}`.trimEnd()) +} + +function pushNotesAndSources(lines: string[], level: number, event: Pick | undefined) { + if (!event) return + if (event.notes) pushMultiline(lines, level, 'NOTE', event.notes) + for (const source of (event.sources ?? '').split('\n').map((s) => s.trim()).filter(Boolean)) { + lines.push(`${level} SOUR ${source}`) + } +} + +function pushLifeEvent(lines: string[], event: ExportedEvent, tags: Record) { + const tag = tags[event.type] ?? 'EVEN' + const value = event.description ? ` ${oneLine(event.description)}` : '' + lines.push(`1 ${tag}${value}`) + if (tag === 'EVEN' || tag === 'FACT') { + const label = event.label ?? (tags[event.type] ? null : event.type) + if (label) lines.push(`2 TYPE ${oneLine(label)}`) + } + const date = qualifiedGedcomDate(event.date, event.dateEnd, event.datePrecision, event.dateText) + if (date) lines.push(`2 DATE ${date}`) + if (event.place) lines.push(`2 PLAC ${oneLine(event.place)}`) + pushNotesAndSources(lines, 2, event) +} + // ─── Name Parsing ──────────────────────────────────────────────────────────── // « Jean /Dupont/ » : lu par indexOf, l'ancienne expression régulière était quadratique sur les espaces @@ -262,10 +338,11 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => { } } - const [persons, unions, links] = await Promise.all([ + const [persons, unions, links, lifeEvents] = await Promise.all([ app.prisma.person.findMany({ where: { treeId, deletedAt: null } }), app.prisma.union.findMany({ where: { treeId, deletedAt: null } }), app.prisma.parentChildLink.findMany({ where: { treeId, deletedAt: null } }), + app.prisma.lifeEvent.findMany({ where: { treeId, deletedAt: null }, orderBy: [{ date: 'asc' }, { displayOrder: 'asc' }] }), ]) const personById = new Map(persons.map((p) => [p.id, p])) @@ -302,6 +379,7 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => { // Assign each child to a union FAM const childrenByUnion = new Map>() + const adoptedInUnion = new Set() for (const link of links) { const childId = link.childPersonId let unionId: string | undefined @@ -322,6 +400,7 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => { } if (!unionId) continue + if (link.parentageType === 'adoption') adoptedInUnion.add(`${unionId}|${childId}`) const set = childrenByUnion.get(unionId) ?? new Set() set.add(childId) childrenByUnion.set(unionId, set) @@ -348,6 +427,16 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => { } } + // Événements de vie : rangés par personne et par union, pour les réécrire sous leur propriétaire + const eventsByPerson = new Map() + const eventsByUnion = new Map() + for (const event of lifeEvents) { + const target = event.personId ? eventsByPerson : event.unionId ? eventsByUnion : null + const key = event.personId ?? event.unionId + if (!target || !key) continue + target.set(key, [...(target.get(key) ?? []), event]) + } + // ── Write GEDCOM ── const lines: string[] = [] const now = new Date() @@ -365,24 +454,39 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => { const xref = sanitizeXref(person.id) lines.push(`0 @I${xref}@ INDI`) lines.push(`1 NAME ${oneLine(person.firstName)} /${oneLine(person.lastName).replace(/\//g, '')}/`) + if (person.nickname) lines.push(`2 NICK ${oneLine(person.nickname)}`) if (person.sex === 'male' || person.sex === 'M') lines.push('1 SEX M') else if (person.sex === 'female' || person.sex === 'F') lines.push('1 SEX F') - const birthDate = isoToGedcomDate(person.birthDate) - if (birthDate || person.birthPlace) { + const personEvents = eventsByPerson.get(person.id) ?? [] + const birthDetails = personEvents.find((event) => event.type === 'birth') + const deathDetails = personEvents.find((event) => event.type === 'death') + + const birthDate = qualifiedGedcomDate(person.birthDate, person.birthDateEnd, person.birthDatePrecision) + if (birthDate || person.birthPlace || birthDetails) { lines.push('1 BIRT') if (birthDate) lines.push(`2 DATE ${birthDate}`) if (person.birthPlace) lines.push(`2 PLAC ${oneLine(person.birthPlace)}`) + pushNotesAndSources(lines, 2, birthDetails) } - const deathDate = isoToGedcomDate(person.deathDate) - if (deathDate) { + const deathDate = qualifiedGedcomDate(person.deathDate, person.deathDateEnd, person.deathDatePrecision) + if (deathDate || person.deathPlace || deathDetails) { lines.push('1 DEAT') - lines.push(`2 DATE ${deathDate}`) + if (deathDate) lines.push(`2 DATE ${deathDate}`) + if (person.deathPlace) lines.push(`2 PLAC ${oneLine(person.deathPlace)}`) + pushNotesAndSources(lines, 2, deathDetails) } - if (person.profession) lines.push(`1 OCCU ${oneLine(person.profession)}`) + // Le champ « profession » s'écrit seulement s'il n'est pas déjà un des métiers datés + const professionKnown = personEvents.some( + (event) => event.type === 'occupation' && event.description?.trim().toLowerCase() === person.profession?.trim().toLowerCase(), + ) + if (person.profession && !professionKnown) lines.push(`1 OCCU ${oneLine(person.profession)}`) + for (const event of personEvents) { + if (event.type !== 'birth' && event.type !== 'death') pushLifeEvent(lines, event, PERSON_EVENT_TAGS) + } if (person.notes) { const noteLines = person.notes.split(/\r\n|\r|\n/) @@ -400,6 +504,7 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => { // FAMC: links this person to their parent family (as child) for (const uid of famcByPerson.get(person.id) ?? []) { lines.push(`1 FAMC @F${sanitizeXref(uid)}@`) + if (adoptedInUnion.has(`${uid}|${person.id}`)) lines.push('2 PEDI adopted') } } @@ -427,10 +532,17 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => { lines.push(`1 CHIL @I${sanitizeXref(childId)}@`) } - const marriageDate = isoToGedcomDate(union.startDate) - if (marriageDate) { + const unionEvents = eventsByUnion.get(union.id) ?? [] + const marriageDetails = unionEvents.find((event) => event.type === 'marriage') + const marriageDate = qualifiedGedcomDate(union.startDate, null, union.startDatePrecision) + if (marriageDate || union.startPlace || marriageDetails) { lines.push('1 MARR') - lines.push(`2 DATE ${marriageDate}`) + if (marriageDate) lines.push(`2 DATE ${marriageDate}`) + if (union.startPlace) lines.push(`2 PLAC ${oneLine(union.startPlace)}`) + pushNotesAndSources(lines, 2, marriageDetails) + } + for (const event of unionEvents) { + if (event.type !== 'marriage') pushLifeEvent(lines, event, FAMILY_EVENT_TAGS) } } diff --git a/backend/test/api-routes.test.ts b/backend/test/api-routes.test.ts index d8e2d0c..23fbdfd 100644 --- a/backend/test/api-routes.test.ts +++ b/backend/test/api-routes.test.ts @@ -1,6 +1,9 @@ import { randomUUID } from 'node:crypto' import type { FastifyInstance } from 'fastify' import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { adoptedFamilies, familyExtras, personExtras } from '../src/lib/gedcom-events' +import { indexGedcomRecords } from '../src/lib/gedcom-photos' +import { parseGedcom } from '../src/routes/gedcom' const { prismaMock } = vi.hoisted(() => ({ prismaMock: { @@ -467,6 +470,65 @@ describe('Graph routes', () => { await app.close() }) + it('export GEDCOM : précisions, événements, sources et adoption relus à l’identique', async () => { + const app = createApp() + await app.ready() + const token = (app as any).jwt.sign({ + kind: 'tree_access', + sub: 'tree:tree-1:visitor', + treeId: 'tree-1', + role: 'visitor', + accessVersion: new Date('2026-02-11T10:00:00.000Z').getTime(), + }) + const base = { birthDateEnd: null, deathDateEnd: null, deathDatePrecision: null, deathPlace: null, nickname: null, notes: null, profession: null, deathDate: null } + prismaMock.tree.findFirst.mockResolvedValue({ id: 'tree-1', name: 'Ragot', rootPersonId: null }) + prismaMock.person.findMany.mockResolvedValue([ + { ...base, id: 'p-1', firstName: 'Louis', lastName: 'Ragot', sex: 'male', birthDate: new Date('1879-01-01T00:00:00Z'), birthDatePrecision: 'about', birthPlace: 'La Roche-sur-Yon', deathDate: new Date('1950-05-02T00:00:00Z'), deathPlace: 'Nantes', nickname: 'Loulou', profession: 'Instituteur' }, + { ...base, id: 'p-2', firstName: 'Marie', lastName: 'Bodin', sex: 'female', birthDate: null, birthDatePrecision: null, birthPlace: null }, + { ...base, id: 'p-3', firstName: 'Jean', lastName: 'Ragot', sex: 'male', birthDate: null, birthDatePrecision: null, birthPlace: null }, + ]) + prismaMock.union.findMany.mockResolvedValue([ + { id: 'u-1', partner1PersonId: 'p-1', partner2PersonId: 'p-2', startDate: new Date('1905-01-01T00:00:00Z'), startDatePrecision: 'estimated', startPlace: 'Limoges', endDate: null }, + ]) + prismaMock.parentChildLink.findMany.mockResolvedValue([ + { id: 'l-1', parentPersonId: 'p-1', childPersonId: 'p-3', viaUnionId: 'u-1', parentageType: 'adoption' }, + { id: 'l-2', parentPersonId: 'p-2', childPersonId: 'p-3', viaUnionId: 'u-1', parentageType: 'adoption' }, + ]) + const event = { label: null, dateEnd: null, datePrecision: null, dateText: null, place: null, description: null, notes: null, sources: null, displayOrder: 1 } + prismaMock.lifeEvent.findMany.mockResolvedValue([ + { ...event, id: 'e-1', personId: 'p-1', unionId: null, type: 'birth', date: null, sources: 'Registre des naissances, Acte n° 12' }, + { ...event, id: 'e-2', personId: 'p-1', unionId: null, type: 'baptism', date: new Date('1879-03-09T00:00:00Z'), place: 'La Roche-sur-Yon' }, + { ...event, id: 'e-3', personId: 'p-1', unionId: null, type: 'occupation', date: new Date('1900-01-01T00:00:00Z'), dateEnd: new Date('1935-01-01T00:00:00Z'), datePrecision: 'from', description: 'Instituteur' }, + { ...event, id: 'e-4', personId: 'p-1', unionId: null, type: 'custom', label: 'Militaire', date: new Date('1914-01-01T00:00:00Z'), dateEnd: new Date('1918-01-01T00:00:00Z'), datePrecision: 'between', notes: 'Blessé à Verdun.\nRentré en 1919.' }, + { ...event, id: 'e-6', personId: null, unionId: 'u-1', type: 'marriage', date: null, sources: 'Registre des mariages de Limoges' }, + { ...event, id: 'e-7', personId: null, unionId: 'u-1', type: 'divorce', date: new Date('1920-06-01T00:00:00Z') }, + ]) + + const response = await app.inject({ method: 'GET', url: '/trees/tree-1/export/gedcom', headers: { authorization: `Bearer ${token}` } }) + expect(response.statusCode).toBe(200) + const text = response.body.replace(/\r\n/g, '\n') + expect(text).toContain('1 OCCU Instituteur\n2 DATE FROM 1900 TO 1935') + expect(text.match(/1 OCCU/g)).toHaveLength(1) + expect(text).toContain('2 PEDI adopted') + + const roots = parseGedcom(text) + const records = indexGedcomRecords(roots) + const louis = roots.find((n) => n.tag === 'INDI' && n.children.some((c) => c.tag === 'NAME' && c.value.startsWith('Louis')))! + const extras = personExtras(louis as never, records) + expect(extras).toMatchObject({ birthDatePrecision: 'about', deathPlace: 'Nantes', nickname: 'Loulou' }) + expect(extras.events.map((e) => e.type)).toEqual(['birth', 'baptism', 'occupation', 'custom']) + expect(extras.events[0].sources).toBe('Registre des naissances, Acte n° 12') + expect(extras.events[3]).toMatchObject({ label: 'Militaire', datePrecision: 'between', notes: 'Blessé à Verdun.\nRentré en 1919.' }) + + const fam = roots.find((n) => n.tag === 'FAM')! + const family = familyExtras(fam as never, records) + expect(family).toMatchObject({ startPlace: 'Limoges', startDatePrecision: 'estimated' }) + expect(family.events.map((e) => e.type)).toEqual(['marriage', 'divorce']) + const jean = roots.find((n) => n.tag === 'INDI' && n.children.some((c) => c.tag === 'NAME' && c.value.startsWith('Jean')))! + expect(adoptedFamilies(jean as never).size).toBe(1) + await app.close() + }) + it('allows tree access token to fetch graph', async () => { const app = createApp() await app.ready() From f47ef8ecacfc6f2834c491b43a9fe8cf6019fb4b Mon Sep 17 00:00:00 2001 From: IliesAllali Date: Fri, 16 Oct 2026 22:29:21 +0200 Subject: [PATCH 4/4] fix(dates): une date corrigee a la main perd la precision importee MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sinon « vers 1879 » restait colle a la date saisie ensuite, et l'export l'aurait ecrite. Personne, union, et voie contribution. Co-Authored-By: Claude Opus 5.5 --- backend/src/lib/date-precision.ts | 26 ++++++++++++++++++++++++++ backend/src/routes/contributions.ts | 21 +++++++++++++++++++-- backend/src/routes/trees.ts | 16 ++++++++++++++-- backend/test/date-precision.test.ts | 23 +++++++++++++++++++++++ 4 files changed, 82 insertions(+), 4 deletions(-) create mode 100644 backend/src/lib/date-precision.ts create mode 100644 backend/test/date-precision.test.ts diff --git a/backend/src/lib/date-precision.ts b/backend/src/lib/date-precision.ts new file mode 100644 index 0000000..6efe191 --- /dev/null +++ b/backend/src/lib/date-precision.ts @@ -0,0 +1,26 @@ +// Une date corrigée à la main perd la précision lue dans le GEDCOM (« vers 1879 », « entre 1914 et 1918 ») : +// elle décrivait l'ancienne date, pas celle qu'on vient de saisir. Une date renvoyée telle quelle la garde. + +const sameDay = (a: Date | null | undefined, b: Date | null | undefined) => + (a ? a.toISOString().slice(0, 10) : null) === (b ? b.toISOString().slice(0, 10) : null) + +type PersonDates = { birthDate: Date | null; deathDate: Date | null } + +export function personPrecisionResets(current: PersonDates | null, next: Partial) { + const out: { birthDatePrecision?: null; birthDateEnd?: null; deathDatePrecision?: null; deathDateEnd?: null } = {} + if (!current) return out + if (next.birthDate !== undefined && !sameDay(current.birthDate, next.birthDate)) { + out.birthDatePrecision = null + out.birthDateEnd = null + } + if (next.deathDate !== undefined && !sameDay(current.deathDate, next.deathDate)) { + out.deathDatePrecision = null + out.deathDateEnd = null + } + return out +} + +export function unionPrecisionResets(current: { startDate: Date | null } | null, next: { startDate?: Date | null }) { + if (!current || next.startDate === undefined || sameDay(current.startDate, next.startDate)) return {} + return { startDatePrecision: null } +} diff --git a/backend/src/routes/contributions.ts b/backend/src/routes/contributions.ts index b5b8fdc..17ed7bf 100644 --- a/backend/src/routes/contributions.ts +++ b/backend/src/routes/contributions.ts @@ -12,6 +12,7 @@ import { syncPersonMediaOrder } from '../lib/media-order.js' import type { Actor, MembershipRole } from '../types/auth.js' import { findParentChildValidationError, findUnionValidationError } from '../utils/relationship-guards.js' import { nextSiblingOrder } from '../lib/sibling-order.js' +import { personPrecisionResets, unionPrecisionResets } from '../lib/date-precision.js' const isoDateRegex = /^\d{4}-\d{2}-\d{2}$/ @@ -391,6 +392,17 @@ async function applyContributionChange( throw new ContributionRouteError(400, 'invalid_change_after') } + const nextDates = { + birthDate: parsed.data.birthDate !== undefined ? toDateOrNull(parsed.data.birthDate) : undefined, + deathDate: parsed.data.deathDate !== undefined ? toDateOrNull(parsed.data.deathDate) : undefined, + } + const currentDates = nextDates.birthDate !== undefined || nextDates.deathDate !== undefined + ? await tx.person.findFirst({ + where: { id: change.entityId, treeId, deletedAt: null }, + select: { birthDate: true, deathDate: true }, + }) + : null + const result = await tx.person.updateMany({ where: { id: change.entityId, @@ -398,11 +410,12 @@ async function applyContributionChange( deletedAt: null, }, data: { + ...personPrecisionResets(currentDates, nextDates), firstName: parsed.data.firstName !== undefined ? parsed.data.firstName.trim() : undefined, lastName: parsed.data.lastName !== undefined ? parsed.data.lastName.trim() : undefined, birthName: parsed.data.birthName !== undefined ? toTrimmedStringOrNull(parsed.data.birthName) : undefined, - birthDate: parsed.data.birthDate !== undefined ? toDateOrNull(parsed.data.birthDate) : undefined, - deathDate: parsed.data.deathDate !== undefined ? toDateOrNull(parsed.data.deathDate) : undefined, + birthDate: nextDates.birthDate, + deathDate: nextDates.deathDate, birthPlace: parsed.data.birthPlace !== undefined ? toTrimmedStringOrNull(parsed.data.birthPlace) : undefined, profession: parsed.data.profession !== undefined ? toTrimmedStringOrNull(parsed.data.profession) : undefined, region: parsed.data.region !== undefined ? toTrimmedStringOrNull(parsed.data.region) : undefined, @@ -511,6 +524,7 @@ async function applyContributionChange( select: { partner1PersonId: true, partner2PersonId: true, + startDate: true, }, }) if (!existingUnion) { @@ -537,6 +551,9 @@ async function applyContributionChange( deletedAt: null, }, data: { + ...unionPrecisionResets(existingUnion, { + startDate: parsed.data.startDate !== undefined ? toDateOrNull(parsed.data.startDate) : undefined, + }), partner1PersonId: parsed.data.partner1PersonId, partner2PersonId: parsed.data.partner2PersonId, unionType: parsed.data.unionType, diff --git a/backend/src/routes/trees.ts b/backend/src/routes/trees.ts index ac43ec7..86c8eb2 100644 --- a/backend/src/routes/trees.ts +++ b/backend/src/routes/trees.ts @@ -15,6 +15,7 @@ import { nextSiblingOrder } from '../lib/sibling-order.js' import { reserveTreeUnlockAttempt, serializePasswordCheck } from '../lib/unlock-guard.js' import type { MembershipRole } from '../types/auth.js' import { findParentChildValidationError, findUnionValidationError } from '../utils/relationship-guards.js' +import { personPrecisionResets, unionPrecisionResets } from '../lib/date-precision.js' const MAX_TREES_PER_ACCOUNT = 10 @@ -1371,13 +1372,21 @@ export const treeRoutes: FastifyPluginAsync = async (app) => { data.updatedBy = user.userId + const datesChanged = data.birthDate !== undefined || data.deathDate !== undefined + const current = datesChanged + ? await app.prisma.person.findFirst({ + where: { id: params.data.personId, treeId: params.data.id, deletedAt: null }, + select: { birthDate: true, deathDate: true }, + }) + : null + const updated = await app.prisma.person.updateMany({ where: { id: params.data.personId, treeId: params.data.id, deletedAt: null, }, - data, + data: { ...data, ...personPrecisionResets(current, data) }, }) if (updated.count === 0) { @@ -1586,6 +1595,7 @@ export const treeRoutes: FastifyPluginAsync = async (app) => { select: { partner1PersonId: true, partner2PersonId: true, + startDate: true, }, }) @@ -1636,6 +1646,7 @@ export const treeRoutes: FastifyPluginAsync = async (app) => { return reply.code(400).send({ error: unionValidationError }) } + const startDate = payload.data.startDate !== undefined ? toDateOrNull(payload.data.startDate) : undefined const updated = await app.prisma.union.updateMany({ where: { id: params.data.unionId, @@ -1643,10 +1654,11 @@ export const treeRoutes: FastifyPluginAsync = async (app) => { deletedAt: null, }, data: { + ...unionPrecisionResets(existingUnion, { startDate }), partner1PersonId: payload.data.partner1PersonId, partner2PersonId: payload.data.partner2PersonId, unionType: payload.data.unionType, - startDate: payload.data.startDate !== undefined ? toDateOrNull(payload.data.startDate) : undefined, + startDate, endDate: payload.data.endDate !== undefined ? toDateOrNull(payload.data.endDate) : undefined, displayOrder: payload.data.displayOrder, }, diff --git a/backend/test/date-precision.test.ts b/backend/test/date-precision.test.ts new file mode 100644 index 0000000..ac348d0 --- /dev/null +++ b/backend/test/date-precision.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest' + +import { personPrecisionResets, unionPrecisionResets } from '../src/lib/date-precision' + +const d = (iso: string) => new Date(`${iso}T00:00:00.000Z`) + +describe('précision d’une date corrigée à la main', () => { + const current = { birthDate: d('1879-01-01'), deathDate: d('1950-05-02') } + + it('une date changée perd sa précision, une date renvoyée telle quelle la garde', () => { + expect(personPrecisionResets(current, { birthDate: d('1880-03-12'), deathDate: d('1950-05-02') })) + .toEqual({ birthDatePrecision: null, birthDateEnd: null }) + expect(personPrecisionResets(current, { birthDate: d('1879-01-01') })).toEqual({}) + expect(personPrecisionResets(current, { deathDate: null })).toEqual({ deathDatePrecision: null, deathDateEnd: null }) + expect(personPrecisionResets(current, {})).toEqual({}) + }) + + it('mariage', () => { + expect(unionPrecisionResets({ startDate: d('1905-01-01') }, { startDate: d('1906-01-01') })).toEqual({ startDatePrecision: null }) + expect(unionPrecisionResets({ startDate: d('1905-01-01') }, { startDate: d('1905-01-01') })).toEqual({}) + expect(unionPrecisionResets({ startDate: d('1905-01-01') }, {})).toEqual({}) + }) +})